blob: 37b02aff4ffa1db5b97f29be7b058b0412cfae72 [file] [log] [blame]
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001/*
2 * Copyright (C) 2008 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17#include "debugger.h"
18
Elliott Hughes3bb81562011-10-21 18:52:59 -070019#include <sys/uio.h>
20
Elliott Hughes545a0642011-11-08 19:10:03 -080021#include <set>
22
23#include "class_linker.h"
Elliott Hughes68fdbd02011-11-29 19:22:47 -080024#include "context.h"
Elliott Hughes6a5bd492011-10-28 14:33:57 -070025#include "ScopedLocalRef.h"
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -070026#include "ScopedPrimitiveArray.h"
Elliott Hughes47fce012011-10-25 18:37:19 -070027#include "stack_indirect_reference_table.h"
Elliott Hughes475fc232011-10-25 15:00:35 -070028#include "thread_list.h"
29
Elliott Hughes6a5bd492011-10-28 14:33:57 -070030extern "C" void dlmalloc_walk_heap(void(*)(const void*, size_t, const void*, size_t, void*), void*);
31#ifndef HAVE_ANDROID_OS
32void dlmalloc_walk_heap(void(*)(const void*, size_t, const void*, size_t, void*), void*) {
33 // No-op for glibc.
34}
35#endif
36
Elliott Hughes872d4ec2011-10-21 17:07:15 -070037namespace art {
38
Elliott Hughes545a0642011-11-08 19:10:03 -080039static const size_t kMaxAllocRecordStackDepth = 16; // Max 255.
40static const size_t kNumAllocRecords = 512; // Must be power of 2.
41
Elliott Hughes475fc232011-10-25 15:00:35 -070042class ObjectRegistry {
43 public:
44 ObjectRegistry() : lock_("ObjectRegistry lock") {
45 }
46
47 JDWP::ObjectId Add(Object* o) {
48 if (o == NULL) {
49 return 0;
50 }
51 JDWP::ObjectId id = static_cast<JDWP::ObjectId>(reinterpret_cast<uintptr_t>(o));
52 MutexLock mu(lock_);
53 map_[id] = o;
54 return id;
55 }
56
Elliott Hughes234ab152011-10-26 14:02:26 -070057 void Clear() {
58 MutexLock mu(lock_);
59 LOG(DEBUG) << "Debugger has detached; object registry had " << map_.size() << " entries";
60 map_.clear();
61 }
62
Elliott Hughes475fc232011-10-25 15:00:35 -070063 bool Contains(JDWP::ObjectId id) {
64 MutexLock mu(lock_);
65 return map_.find(id) != map_.end();
66 }
67
Elliott Hughesa2155262011-11-16 16:26:58 -080068 template<typename T> T Get(JDWP::ObjectId id) {
69 MutexLock mu(lock_);
70 typedef std::map<JDWP::ObjectId, Object*>::iterator It; // C++0x auto
71 It it = map_.find(id);
72 return (it != map_.end()) ? reinterpret_cast<T>(it->second) : NULL;
73 }
74
Elliott Hughesbfe487b2011-10-26 15:48:55 -070075 void VisitRoots(Heap::RootVisitor* visitor, void* arg) {
76 MutexLock mu(lock_);
77 typedef std::map<JDWP::ObjectId, Object*>::iterator It; // C++0x auto
78 for (It it = map_.begin(); it != map_.end(); ++it) {
79 visitor(it->second, arg);
80 }
81 }
82
Elliott Hughes475fc232011-10-25 15:00:35 -070083 private:
84 Mutex lock_;
85 std::map<JDWP::ObjectId, Object*> map_;
86};
87
Elliott Hughes545a0642011-11-08 19:10:03 -080088struct AllocRecordStackTraceElement {
89 const Method* method;
90 uintptr_t raw_pc;
91
92 int32_t LineNumber() const {
93 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
94 Class* c = method->GetDeclaringClass();
95 DexCache* dex_cache = c->GetDexCache();
96 const DexFile& dex_file = class_linker->FindDexFile(dex_cache);
97 return dex_file.GetLineNumFromPC(method, method->ToDexPC(raw_pc));
98 }
99};
100
101struct AllocRecord {
102 Class* type;
103 size_t byte_count;
104 uint16_t thin_lock_id;
105 AllocRecordStackTraceElement stack[kMaxAllocRecordStackDepth]; // Unused entries have NULL method.
106
107 size_t GetDepth() {
108 size_t depth = 0;
109 while (depth < kMaxAllocRecordStackDepth && stack[depth].method != NULL) {
110 ++depth;
111 }
112 return depth;
113 }
114};
115
Elliott Hughes4ffd3132011-10-24 12:06:42 -0700116// JDWP is allowed unless the Zygote forbids it.
117static bool gJdwpAllowed = true;
118
Elliott Hughes3bb81562011-10-21 18:52:59 -0700119// Was there a -Xrunjdwp or -agent argument on the command-line?
120static bool gJdwpConfigured = false;
121
122// Broken-down JDWP options. (Only valid if gJdwpConfigured is true.)
Elliott Hughes376a7a02011-10-24 18:35:55 -0700123static JDWP::JdwpOptions gJdwpOptions;
Elliott Hughes3bb81562011-10-21 18:52:59 -0700124
125// Runtime JDWP state.
126static JDWP::JdwpState* gJdwpState = NULL;
127static bool gDebuggerConnected; // debugger or DDMS is connected.
128static bool gDebuggerActive; // debugger is making requests.
129
Elliott Hughes47fce012011-10-25 18:37:19 -0700130static bool gDdmThreadNotification = false;
131
Elliott Hughes767a1472011-10-26 18:49:02 -0700132// DDMS GC-related settings.
133static Dbg::HpifWhen gDdmHpifWhen = Dbg::HPIF_WHEN_NEVER;
134static Dbg::HpsgWhen gDdmHpsgWhen = Dbg::HPSG_WHEN_NEVER;
135static Dbg::HpsgWhat gDdmHpsgWhat;
136static Dbg::HpsgWhen gDdmNhsgWhen = Dbg::HPSG_WHEN_NEVER;
137static Dbg::HpsgWhat gDdmNhsgWhat;
138
Elliott Hughes475fc232011-10-25 15:00:35 -0700139static ObjectRegistry* gRegistry = NULL;
140
Elliott Hughes545a0642011-11-08 19:10:03 -0800141// Recent allocation tracking.
142static Mutex gAllocTrackerLock("AllocTracker lock");
143AllocRecord* Dbg::recent_allocation_records_ = NULL; // TODO: CircularBuffer<AllocRecord>
144static size_t gAllocRecordHead = 0;
145static size_t gAllocRecordCount = 0;
146
Elliott Hughes24437992011-11-30 14:49:33 -0800147static JDWP::JdwpTag BasicTagFromDescriptor(const char* descriptor) {
148 // JDWP deliberately uses the descriptor characters' ASCII values for its enum.
149 // Note that by "basic" we mean that we don't get more specific than JT_OBJECT.
150 return static_cast<JDWP::JdwpTag>(descriptor[0]);
151}
152
153static JDWP::JdwpTag TagFromClass(Class* c) {
154 if (c->IsArrayClass()) {
155 return JDWP::JT_ARRAY;
156 }
157
158 if (c->IsStringClass()) {
159 return JDWP::JT_STRING;
160 } else if (c->IsClassClass()) {
161 return JDWP::JT_CLASS_OBJECT;
162#if 0 // TODO
163 } else if (dvmInstanceof(clazz, gDvm.classJavaLangThread)) {
164 return JDWP::JT_THREAD;
165 } else if (dvmInstanceof(clazz, gDvm.classJavaLangThreadGroup)) {
166 return JDWP::JT_THREAD_GROUP;
167 } else if (dvmInstanceof(clazz, gDvm.classJavaLangClassLoader)) {
168 return JDWP::JT_CLASS_LOADER;
169#endif
170 } else {
171 return JDWP::JT_OBJECT;
172 }
173}
174
175/*
176 * Objects declared to hold Object might actually hold a more specific
177 * type. The debugger may take a special interest in these (e.g. it
178 * wants to display the contents of Strings), so we want to return an
179 * appropriate tag.
180 *
181 * Null objects are tagged JT_OBJECT.
182 */
183static JDWP::JdwpTag TagFromObject(const Object* o) {
184 return (o == NULL) ? JDWP::JT_OBJECT : TagFromClass(o->GetClass());
185}
186
187static bool IsPrimitiveTag(JDWP::JdwpTag tag) {
188 switch (tag) {
189 case JDWP::JT_BOOLEAN:
190 case JDWP::JT_BYTE:
191 case JDWP::JT_CHAR:
192 case JDWP::JT_FLOAT:
193 case JDWP::JT_DOUBLE:
194 case JDWP::JT_INT:
195 case JDWP::JT_LONG:
196 case JDWP::JT_SHORT:
197 case JDWP::JT_VOID:
198 return true;
199 default:
200 return false;
201 }
202}
203
Elliott Hughes3bb81562011-10-21 18:52:59 -0700204/*
205 * Handle one of the JDWP name/value pairs.
206 *
207 * JDWP options are:
208 * help: if specified, show help message and bail
209 * transport: may be dt_socket or dt_shmem
210 * address: for dt_socket, "host:port", or just "port" when listening
211 * server: if "y", wait for debugger to attach; if "n", attach to debugger
212 * timeout: how long to wait for debugger to connect / listen
213 *
214 * Useful with server=n (these aren't supported yet):
215 * onthrow=<exception-name>: connect to debugger when exception thrown
216 * onuncaught=y|n: connect to debugger when uncaught exception thrown
217 * launch=<command-line>: launch the debugger itself
218 *
219 * The "transport" option is required, as is "address" if server=n.
220 */
221static bool ParseJdwpOption(const std::string& name, const std::string& value) {
222 if (name == "transport") {
223 if (value == "dt_socket") {
Elliott Hughes376a7a02011-10-24 18:35:55 -0700224 gJdwpOptions.transport = JDWP::kJdwpTransportSocket;
Elliott Hughes3bb81562011-10-21 18:52:59 -0700225 } else if (value == "dt_android_adb") {
Elliott Hughes376a7a02011-10-24 18:35:55 -0700226 gJdwpOptions.transport = JDWP::kJdwpTransportAndroidAdb;
Elliott Hughes3bb81562011-10-21 18:52:59 -0700227 } else {
228 LOG(ERROR) << "JDWP transport not supported: " << value;
229 return false;
230 }
231 } else if (name == "server") {
232 if (value == "n") {
Elliott Hughes376a7a02011-10-24 18:35:55 -0700233 gJdwpOptions.server = false;
Elliott Hughes3bb81562011-10-21 18:52:59 -0700234 } else if (value == "y") {
Elliott Hughes376a7a02011-10-24 18:35:55 -0700235 gJdwpOptions.server = true;
Elliott Hughes3bb81562011-10-21 18:52:59 -0700236 } else {
237 LOG(ERROR) << "JDWP option 'server' must be 'y' or 'n'";
238 return false;
239 }
240 } else if (name == "suspend") {
241 if (value == "n") {
Elliott Hughes376a7a02011-10-24 18:35:55 -0700242 gJdwpOptions.suspend = false;
Elliott Hughes3bb81562011-10-21 18:52:59 -0700243 } else if (value == "y") {
Elliott Hughes376a7a02011-10-24 18:35:55 -0700244 gJdwpOptions.suspend = true;
Elliott Hughes3bb81562011-10-21 18:52:59 -0700245 } else {
246 LOG(ERROR) << "JDWP option 'suspend' must be 'y' or 'n'";
247 return false;
248 }
249 } else if (name == "address") {
250 /* this is either <port> or <host>:<port> */
251 std::string port_string;
Elliott Hughes376a7a02011-10-24 18:35:55 -0700252 gJdwpOptions.host.clear();
Elliott Hughes3bb81562011-10-21 18:52:59 -0700253 std::string::size_type colon = value.find(':');
254 if (colon != std::string::npos) {
Elliott Hughes376a7a02011-10-24 18:35:55 -0700255 gJdwpOptions.host = value.substr(0, colon);
Elliott Hughes3bb81562011-10-21 18:52:59 -0700256 port_string = value.substr(colon + 1);
257 } else {
258 port_string = value;
259 }
260 if (port_string.empty()) {
261 LOG(ERROR) << "JDWP address missing port: " << value;
262 return false;
263 }
264 char* end;
265 long port = strtol(port_string.c_str(), &end, 10);
266 if (*end != '\0') {
267 LOG(ERROR) << "JDWP address has junk in port field: " << value;
268 return false;
269 }
Elliott Hughes376a7a02011-10-24 18:35:55 -0700270 gJdwpOptions.port = port;
Elliott Hughes3bb81562011-10-21 18:52:59 -0700271 } else if (name == "launch" || name == "onthrow" || name == "oncaught" || name == "timeout") {
272 /* valid but unsupported */
273 LOG(INFO) << "Ignoring JDWP option '" << name << "'='" << value << "'";
274 } else {
275 LOG(INFO) << "Ignoring unrecognized JDWP option '" << name << "'='" << value << "'";
276 }
277
278 return true;
279}
280
281/*
282 * Parse the latter half of a -Xrunjdwp/-agentlib:jdwp= string, e.g.:
283 * "transport=dt_socket,address=8000,server=y,suspend=n"
284 */
285bool Dbg::ParseJdwpOptions(const std::string& options) {
Elliott Hughes47fce012011-10-25 18:37:19 -0700286 LOG(VERBOSE) << "ParseJdwpOptions: " << options;
287
Elliott Hughes3bb81562011-10-21 18:52:59 -0700288 std::vector<std::string> pairs;
289 Split(options, ',', pairs);
290
291 for (size_t i = 0; i < pairs.size(); ++i) {
292 std::string::size_type equals = pairs[i].find('=');
293 if (equals == std::string::npos) {
294 LOG(ERROR) << "Can't parse JDWP option '" << pairs[i] << "' in '" << options << "'";
295 return false;
296 }
297 ParseJdwpOption(pairs[i].substr(0, equals), pairs[i].substr(equals + 1));
298 }
299
Elliott Hughes376a7a02011-10-24 18:35:55 -0700300 if (gJdwpOptions.transport == JDWP::kJdwpTransportUnknown) {
Elliott Hughes3bb81562011-10-21 18:52:59 -0700301 LOG(ERROR) << "Must specify JDWP transport: " << options;
302 }
Elliott Hughes376a7a02011-10-24 18:35:55 -0700303 if (!gJdwpOptions.server && (gJdwpOptions.host.empty() || gJdwpOptions.port == 0)) {
Elliott Hughes3bb81562011-10-21 18:52:59 -0700304 LOG(ERROR) << "Must specify JDWP host and port when server=n: " << options;
305 return false;
306 }
307
308 gJdwpConfigured = true;
309 return true;
310}
311
Elliott Hughesd1cc8362011-10-24 16:58:50 -0700312void Dbg::StartJdwp() {
Elliott Hughes376a7a02011-10-24 18:35:55 -0700313 if (!gJdwpAllowed || !gJdwpConfigured) {
314 // No JDWP for you!
315 return;
316 }
317
Elliott Hughes475fc232011-10-25 15:00:35 -0700318 CHECK(gRegistry == NULL);
319 gRegistry = new ObjectRegistry;
320
Elliott Hughesd1cc8362011-10-24 16:58:50 -0700321 // Init JDWP if the debugger is enabled. This may connect out to a
322 // debugger, passively listen for a debugger, or block waiting for a
323 // debugger.
Elliott Hughes376a7a02011-10-24 18:35:55 -0700324 gJdwpState = JDWP::JdwpState::Create(&gJdwpOptions);
325 if (gJdwpState == NULL) {
Elliott Hughesf8a2df72011-12-01 12:19:54 -0800326 // We probably failed because some other process has the port already, which means that
327 // if we don't abort the user is likely to think they're talking to us when they're actually
328 // talking to that other process.
329 LOG(FATAL) << "debugger thread failed to initialize";
Elliott Hughesd1cc8362011-10-24 16:58:50 -0700330 }
331
332 // If a debugger has already attached, send the "welcome" message.
333 // This may cause us to suspend all threads.
Elliott Hughes376a7a02011-10-24 18:35:55 -0700334 if (gJdwpState->IsActive()) {
Elliott Hughesa2155262011-11-16 16:26:58 -0800335 //ScopedThreadStateChange tsc(Thread::Current(), Thread::kRunnable);
Elliott Hughes376a7a02011-10-24 18:35:55 -0700336 if (!gJdwpState->PostVMStart()) {
Elliott Hughesd1cc8362011-10-24 16:58:50 -0700337 LOG(WARNING) << "failed to post 'start' message to debugger";
338 }
339 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700340}
341
Elliott Hughesd1cc8362011-10-24 16:58:50 -0700342void Dbg::StopJdwp() {
Elliott Hughes376a7a02011-10-24 18:35:55 -0700343 delete gJdwpState;
Elliott Hughes475fc232011-10-25 15:00:35 -0700344 delete gRegistry;
345 gRegistry = NULL;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700346}
347
Elliott Hughes767a1472011-10-26 18:49:02 -0700348void Dbg::GcDidFinish() {
349 if (gDdmHpifWhen != HPIF_WHEN_NEVER) {
350 LOG(DEBUG) << "Sending VM heap info to DDM";
Elliott Hughes7162ad92011-10-27 14:08:42 -0700351 DdmSendHeapInfo(gDdmHpifWhen);
Elliott Hughes767a1472011-10-26 18:49:02 -0700352 }
353 if (gDdmHpsgWhen != HPSG_WHEN_NEVER) {
354 LOG(DEBUG) << "Dumping VM heap to DDM";
Elliott Hughes6a5bd492011-10-28 14:33:57 -0700355 DdmSendHeapSegments(false);
Elliott Hughes767a1472011-10-26 18:49:02 -0700356 }
357 if (gDdmNhsgWhen != HPSG_WHEN_NEVER) {
358 LOG(DEBUG) << "Dumping native heap to DDM";
Elliott Hughes6a5bd492011-10-28 14:33:57 -0700359 DdmSendHeapSegments(true);
Elliott Hughes767a1472011-10-26 18:49:02 -0700360 }
361}
362
Elliott Hughes4ffd3132011-10-24 12:06:42 -0700363void Dbg::SetJdwpAllowed(bool allowed) {
364 gJdwpAllowed = allowed;
365}
366
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700367DebugInvokeReq* Dbg::GetInvokeReq() {
Elliott Hughes475fc232011-10-25 15:00:35 -0700368 return Thread::Current()->GetInvokeReq();
369}
370
371Thread* Dbg::GetDebugThread() {
372 return (gJdwpState != NULL) ? gJdwpState->GetDebugThread() : NULL;
373}
374
375void Dbg::ClearWaitForEventThread() {
376 gJdwpState->ClearWaitForEventThread();
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700377}
378
379void Dbg::Connected() {
Elliott Hughes3bb81562011-10-21 18:52:59 -0700380 CHECK(!gDebuggerConnected);
381 LOG(VERBOSE) << "JDWP has attached";
382 gDebuggerConnected = true;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700383}
384
Elliott Hughesa2155262011-11-16 16:26:58 -0800385void Dbg::GoActive() {
386 // Enable all debugging features, including scans for breakpoints.
387 // This is a no-op if we're already active.
388 // Only called from the JDWP handler thread.
389 if (gDebuggerActive) {
390 return;
391 }
392
393 LOG(INFO) << "Debugger is active";
394
395 // TODO: CHECK we don't have any outstanding breakpoints.
396
397 gDebuggerActive = true;
398
399 //dvmEnableAllSubMode(kSubModeDebuggerActive);
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700400}
401
402void Dbg::Disconnected() {
Elliott Hughes234ab152011-10-26 14:02:26 -0700403 CHECK(gDebuggerConnected);
404
405 gDebuggerActive = false;
406
407 //dvmDisableAllSubMode(kSubModeDebuggerActive);
408
409 gRegistry->Clear();
410 gDebuggerConnected = false;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700411}
412
413bool Dbg::IsDebuggerConnected() {
Elliott Hughes3bb81562011-10-21 18:52:59 -0700414 return gDebuggerActive;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700415}
416
417bool Dbg::IsDebuggingEnabled() {
Elliott Hughes3bb81562011-10-21 18:52:59 -0700418 return gJdwpConfigured;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700419}
420
421int64_t Dbg::LastDebuggerActivity() {
422 UNIMPLEMENTED(WARNING);
423 return -1;
424}
425
426int Dbg::ThreadRunning() {
Elliott Hughesd1cc8362011-10-24 16:58:50 -0700427 return static_cast<int>(Thread::Current()->SetState(Thread::kRunnable));
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700428}
429
430int Dbg::ThreadWaiting() {
Elliott Hughesd1cc8362011-10-24 16:58:50 -0700431 return static_cast<int>(Thread::Current()->SetState(Thread::kVmWait));
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700432}
433
Elliott Hughes6ba581a2011-10-25 11:45:35 -0700434int Dbg::ThreadContinuing(int new_state) {
435 return static_cast<int>(Thread::Current()->SetState(static_cast<Thread::State>(new_state)));
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700436}
437
438void Dbg::UndoDebuggerSuspensions() {
Elliott Hughes234ab152011-10-26 14:02:26 -0700439 Runtime::Current()->GetThreadList()->UndoDebuggerSuspensions();
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700440}
441
442void Dbg::Exit(int status) {
443 UNIMPLEMENTED(FATAL);
444}
445
Elliott Hughesbfe487b2011-10-26 15:48:55 -0700446void Dbg::VisitRoots(Heap::RootVisitor* visitor, void* arg) {
447 if (gRegistry != NULL) {
448 gRegistry->VisitRoots(visitor, arg);
449 }
450}
451
Elliott Hughesa2155262011-11-16 16:26:58 -0800452std::string Dbg::GetClassDescriptor(JDWP::RefTypeId classId) {
453 Class* c = gRegistry->Get<Class*>(classId);
454 return c->GetDescriptor()->ToModifiedUtf8();
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700455}
456
457JDWP::ObjectId Dbg::GetClassObject(JDWP::RefTypeId id) {
458 UNIMPLEMENTED(FATAL);
459 return 0;
460}
461
462JDWP::RefTypeId Dbg::GetSuperclass(JDWP::RefTypeId id) {
Elliott Hughesa2e54f62011-11-17 13:01:30 -0800463 Class* c = gRegistry->Get<Class*>(id);
464 return gRegistry->Add(c->GetSuperClass());
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700465}
466
467JDWP::ObjectId Dbg::GetClassLoader(JDWP::RefTypeId id) {
468 UNIMPLEMENTED(FATAL);
469 return 0;
470}
471
472uint32_t Dbg::GetAccessFlags(JDWP::RefTypeId id) {
473 UNIMPLEMENTED(FATAL);
474 return 0;
475}
476
477bool Dbg::IsInterface(JDWP::RefTypeId id) {
478 UNIMPLEMENTED(FATAL);
479 return false;
480}
481
Elliott Hughesa2155262011-11-16 16:26:58 -0800482void Dbg::GetClassList(uint32_t* pClassCount, JDWP::RefTypeId** pClasses) {
483 // Get the complete list of reference classes (i.e. all classes except
484 // the primitive types).
485 // Returns a newly-allocated buffer full of RefTypeId values.
486 struct ClassListCreator {
487 static bool Visit(Class* c, void* arg) {
488 return reinterpret_cast<ClassListCreator*>(arg)->Visit(c);
489 }
490
491 bool Visit(Class* c) {
492 if (!c->IsPrimitive()) {
493 classes.push_back(static_cast<JDWP::RefTypeId>(gRegistry->Add(c)));
494 }
495 return true;
496 }
497
498 std::vector<JDWP::RefTypeId> classes;
499 };
500
501 ClassListCreator clc;
502 Runtime::Current()->GetClassLinker()->VisitClasses(ClassListCreator::Visit, &clc);
503 *pClassCount = clc.classes.size();
504 *pClasses = new JDWP::RefTypeId[clc.classes.size()];
505 for (size_t i = 0; i < clc.classes.size(); ++i) {
506 (*pClasses)[i] = clc.classes[i];
507 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700508}
509
510void Dbg::GetVisibleClassList(JDWP::ObjectId classLoaderId, uint32_t* pNumClasses, JDWP::RefTypeId** pClassRefBuf) {
511 UNIMPLEMENTED(FATAL);
512}
513
Elliott Hughesa2155262011-11-16 16:26:58 -0800514void Dbg::GetClassInfo(JDWP::RefTypeId classId, uint8_t* pTypeTag, uint32_t* pStatus, std::string* pDescriptor) {
515 Class* c = gRegistry->Get<Class*>(classId);
516 if (c->IsArrayClass()) {
517 *pStatus = JDWP::CS_VERIFIED | JDWP::CS_PREPARED;
518 *pTypeTag = JDWP::TT_ARRAY;
519 } else {
520 if (c->IsErroneous()) {
521 *pStatus = JDWP::CS_ERROR;
522 } else {
523 *pStatus = JDWP::CS_VERIFIED | JDWP::CS_PREPARED | JDWP::CS_INITIALIZED;
524 }
525 *pTypeTag = c->IsInterface() ? JDWP::TT_INTERFACE : JDWP::TT_CLASS;
526 }
527
528 if (pDescriptor != NULL) {
529 *pDescriptor = c->GetDescriptor()->ToModifiedUtf8();
530 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700531}
532
533bool Dbg::FindLoadedClassBySignature(const char* classDescriptor, JDWP::RefTypeId* pRefTypeId) {
534 UNIMPLEMENTED(FATAL);
535 return false;
536}
537
538void Dbg::GetObjectType(JDWP::ObjectId objectId, uint8_t* pRefTypeTag, JDWP::RefTypeId* pRefTypeId) {
Elliott Hughes499c5132011-11-17 14:55:11 -0800539 Object* o = gRegistry->Get<Object*>(objectId);
540 if (o->GetClass()->IsArrayClass()) {
541 *pRefTypeTag = JDWP::TT_ARRAY;
542 } else if (o->GetClass()->IsInterface()) {
543 *pRefTypeTag = JDWP::TT_INTERFACE;
544 } else {
545 *pRefTypeTag = JDWP::TT_CLASS;
546 }
547 *pRefTypeId = gRegistry->Add(o->GetClass());
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700548}
549
550uint8_t Dbg::GetClassObjectType(JDWP::RefTypeId refTypeId) {
551 UNIMPLEMENTED(FATAL);
552 return 0;
553}
554
Elliott Hughesa2e54f62011-11-17 13:01:30 -0800555std::string Dbg::GetSignature(JDWP::RefTypeId refTypeId) {
556 Class* c = gRegistry->Get<Class*>(refTypeId);
557 CHECK(c != NULL);
558 return c->GetDescriptor()->ToModifiedUtf8();
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700559}
560
Elliott Hughes03181a82011-11-17 17:22:21 -0800561bool Dbg::GetSourceFile(JDWP::RefTypeId refTypeId, std::string& result) {
562 Class* c = gRegistry->Get<Class*>(refTypeId);
563 CHECK(c != NULL);
564
565 String* source_file = c->GetSourceFile();
566 if (source_file == NULL) {
567 return false;
568 }
569 result = source_file->ToModifiedUtf8();
570 return true;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700571}
572
573const char* Dbg::GetObjectTypeName(JDWP::ObjectId objectId) {
574 UNIMPLEMENTED(FATAL);
575 return NULL;
576}
577
578uint8_t Dbg::GetObjectTag(JDWP::ObjectId objectId) {
Elliott Hughes24437992011-11-30 14:49:33 -0800579 Object* o = gRegistry->Get<Object*>(objectId);
580 return TagFromObject(o);
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700581}
582
Elliott Hughesdbb40792011-11-18 17:05:22 -0800583size_t Dbg::GetTagWidth(int tag) {
584 switch (tag) {
585 case JDWP::JT_VOID:
586 return 0;
587 case JDWP::JT_BYTE:
588 case JDWP::JT_BOOLEAN:
589 return 1;
590 case JDWP::JT_CHAR:
591 case JDWP::JT_SHORT:
592 return 2;
593 case JDWP::JT_FLOAT:
594 case JDWP::JT_INT:
595 return 4;
596 case JDWP::JT_ARRAY:
597 case JDWP::JT_OBJECT:
598 case JDWP::JT_STRING:
599 case JDWP::JT_THREAD:
600 case JDWP::JT_THREAD_GROUP:
601 case JDWP::JT_CLASS_LOADER:
602 case JDWP::JT_CLASS_OBJECT:
603 return sizeof(JDWP::ObjectId);
604 case JDWP::JT_DOUBLE:
605 case JDWP::JT_LONG:
606 return 8;
607 default:
608 LOG(FATAL) << "unknown tag " << tag;
609 return -1;
610 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700611}
612
613int Dbg::GetArrayLength(JDWP::ObjectId arrayId) {
Elliott Hughes68fdbd02011-11-29 19:22:47 -0800614 Object* o = gRegistry->Get<Object*>(arrayId);
615 Array* a = o->AsArray();
616 return a->GetLength();
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700617}
618
619uint8_t Dbg::GetArrayElementTag(JDWP::ObjectId arrayId) {
Elliott Hughes24437992011-11-30 14:49:33 -0800620 Object* o = gRegistry->Get<Object*>(arrayId);
621 Array* a = o->AsArray();
622 std::string descriptor(a->GetClass()->GetDescriptor()->ToModifiedUtf8());
623 JDWP::JdwpTag tag = BasicTagFromDescriptor(descriptor.c_str() + 1);
624 if (!IsPrimitiveTag(tag)) {
625 tag = TagFromClass(a->GetClass()->GetComponentType());
626 }
627 return tag;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700628}
629
Elliott Hughes24437992011-11-30 14:49:33 -0800630bool Dbg::OutputArray(JDWP::ObjectId arrayId, int offset, int count, JDWP::ExpandBuf* pReply) {
631 Object* o = gRegistry->Get<Object*>(arrayId);
632 Array* a = o->AsArray();
633
634 if (offset < 0 || count < 0 || offset > a->GetLength() || a->GetLength() - offset < count) {
635 LOG(WARNING) << __FUNCTION__ << " access out of bounds: offset=" << offset << "; count=" << count;
636 return false;
637 }
638
639 std::string descriptor(a->GetClass()->GetDescriptor()->ToModifiedUtf8());
640 JDWP::JdwpTag tag = BasicTagFromDescriptor(descriptor.c_str() + 1);
641
642 if (IsPrimitiveTag(tag)) {
643 size_t width = GetTagWidth(tag);
644 const uint8_t* src = reinterpret_cast<uint8_t*>(a->GetRawData());
645 uint8_t* dst = expandBufAddSpace(pReply, count * width);
646 if (width == 8) {
647 const uint64_t* src8 = reinterpret_cast<const uint64_t*>(src);
648 for (int i = 0; i < count; ++i) JDWP::Write8BE(&dst, src8[offset + i]);
649 } else if (width == 4) {
650 const uint32_t* src4 = reinterpret_cast<const uint32_t*>(src);
651 for (int i = 0; i < count; ++i) JDWP::Write4BE(&dst, src4[offset + i]);
652 } else if (width == 2) {
653 const uint16_t* src2 = reinterpret_cast<const uint16_t*>(src);
654 for (int i = 0; i < count; ++i) JDWP::Write2BE(&dst, src2[offset + i]);
655 } else {
656 memcpy(dst, &src[offset * width], count * width);
657 }
658 } else {
659 ObjectArray<Object>* oa = a->AsObjectArray<Object>();
660 for (int i = 0; i < count; ++i) {
661 Object* element = oa->Get(i);
662 JDWP::JdwpTag specific_tag = (element != NULL) ? TagFromObject(element) : tag;
663 expandBufAdd1(pReply, specific_tag);
664 expandBufAddObjectId(pReply, gRegistry->Add(element));
665 }
666 }
667
668 return true;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700669}
670
671bool Dbg::SetArrayElements(JDWP::ObjectId arrayId, int firstIndex, int count, const uint8_t* buf) {
672 UNIMPLEMENTED(FATAL);
673 return false;
674}
675
676JDWP::ObjectId Dbg::CreateString(const char* str) {
677 UNIMPLEMENTED(FATAL);
678 return 0;
679}
680
681JDWP::ObjectId Dbg::CreateObject(JDWP::RefTypeId classId) {
682 UNIMPLEMENTED(FATAL);
683 return 0;
684}
685
686JDWP::ObjectId Dbg::CreateArrayObject(JDWP::RefTypeId arrayTypeId, uint32_t length) {
687 UNIMPLEMENTED(FATAL);
688 return 0;
689}
690
691bool Dbg::MatchType(JDWP::RefTypeId instClassId, JDWP::RefTypeId classId) {
692 UNIMPLEMENTED(FATAL);
693 return false;
694}
695
Elliott Hughes03181a82011-11-17 17:22:21 -0800696JDWP::FieldId ToFieldId(Field* f) {
697#ifdef MOVING_GARBAGE_COLLECTOR
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700698 UNIMPLEMENTED(FATAL);
Elliott Hughes03181a82011-11-17 17:22:21 -0800699#else
700 return static_cast<JDWP::FieldId>(reinterpret_cast<uintptr_t>(f));
701#endif
702}
703
704JDWP::MethodId ToMethodId(Method* m) {
705#ifdef MOVING_GARBAGE_COLLECTOR
706 UNIMPLEMENTED(FATAL);
707#else
708 return static_cast<JDWP::MethodId>(reinterpret_cast<uintptr_t>(m));
709#endif
710}
711
712Method* FromMethodId(JDWP::MethodId mid) {
713#ifdef MOVING_GARBAGE_COLLECTOR
714 UNIMPLEMENTED(FATAL);
715#else
716 return reinterpret_cast<Method*>(static_cast<uintptr_t>(mid));
717#endif
718}
719
720std::string Dbg::GetMethodName(JDWP::RefTypeId refTypeId, JDWP::MethodId methodId) {
721 return FromMethodId(methodId)->GetName()->ToModifiedUtf8();
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700722}
723
Elliott Hughesa2e54f62011-11-17 13:01:30 -0800724/*
725 * Augment the access flags for synthetic methods and fields by setting
726 * the (as described by the spec) "0xf0000000 bit". Also, strip out any
727 * flags not specified by the Java programming language.
728 */
729static uint32_t MangleAccessFlags(uint32_t accessFlags) {
730 accessFlags &= kAccJavaFlagsMask;
731 if ((accessFlags & kAccSynthetic) != 0) {
732 accessFlags |= 0xf0000000;
733 }
734 return accessFlags;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700735}
736
Elliott Hughesdbb40792011-11-18 17:05:22 -0800737static const uint16_t kEclipseWorkaroundSlot = 1000;
738
739/*
740 * Eclipse appears to expect that the "this" reference is in slot zero.
741 * If it's not, the "variables" display will show two copies of "this",
742 * possibly because it gets "this" from SF.ThisObject and then displays
743 * all locals with nonzero slot numbers.
744 *
745 * So, we remap the item in slot 0 to 1000, and remap "this" to zero. On
746 * SF.GetValues / SF.SetValues we map them back.
747 */
748static uint16_t MangleSlot(uint16_t slot, const char* name) {
749 uint16_t newSlot = slot;
750 if (strcmp(name, "this") == 0) {
751 newSlot = 0;
752 } else if (slot == 0) {
753 newSlot = kEclipseWorkaroundSlot;
754 }
755 return newSlot;
756}
757
758/*
759 * Reverse Eclipse hack.
760 */
Elliott Hughes68fdbd02011-11-29 19:22:47 -0800761static uint16_t DemangleSlot(uint16_t slot, Frame& f) {
Elliott Hughesdbb40792011-11-18 17:05:22 -0800762 if (slot == kEclipseWorkaroundSlot) {
Elliott Hughes68fdbd02011-11-29 19:22:47 -0800763 return 0;
Elliott Hughesdbb40792011-11-18 17:05:22 -0800764 } else if (slot == 0) {
Elliott Hughesdbb40792011-11-18 17:05:22 -0800765 Method* m = f.GetMethod();
Elliott Hughes68fdbd02011-11-29 19:22:47 -0800766 return m->NumRegisters() - m->NumIns();
Elliott Hughesdbb40792011-11-18 17:05:22 -0800767 }
Elliott Hughes68fdbd02011-11-29 19:22:47 -0800768 return slot;
Elliott Hughesdbb40792011-11-18 17:05:22 -0800769}
770
Elliott Hughesa2e54f62011-11-17 13:01:30 -0800771void Dbg::OutputDeclaredFields(JDWP::RefTypeId refTypeId, bool withGeneric, JDWP::ExpandBuf* pReply) {
772 Class* c = gRegistry->Get<Class*>(refTypeId);
773 CHECK(c != NULL);
774
775 size_t instance_field_count = c->NumInstanceFields();
776 size_t static_field_count = c->NumStaticFields();
777
778 expandBufAdd4BE(pReply, instance_field_count + static_field_count);
779
780 for (size_t i = 0; i < instance_field_count + static_field_count; ++i) {
781 Field* f = (i < instance_field_count) ? c->GetInstanceField(i) : c->GetStaticField(i - instance_field_count);
782
783 expandBufAddFieldId(pReply, ToFieldId(f));
784 expandBufAddUtf8String(pReply, f->GetName()->ToModifiedUtf8().c_str());
785 expandBufAddUtf8String(pReply, f->GetTypeDescriptor());
786 if (withGeneric) {
787 static const char genericSignature[1] = "";
788 expandBufAddUtf8String(pReply, genericSignature);
789 }
790 expandBufAdd4BE(pReply, MangleAccessFlags(f->GetAccessFlags()));
791 }
792}
793
794void Dbg::OutputDeclaredMethods(JDWP::RefTypeId refTypeId, bool withGeneric, JDWP::ExpandBuf* pReply) {
795 Class* c = gRegistry->Get<Class*>(refTypeId);
796 CHECK(c != NULL);
797
798 size_t direct_method_count = c->NumDirectMethods();
799 size_t virtual_method_count = c->NumVirtualMethods();
800
801 expandBufAdd4BE(pReply, direct_method_count + virtual_method_count);
802
803 for (size_t i = 0; i < direct_method_count + virtual_method_count; ++i) {
804 Method* m = (i < direct_method_count) ? c->GetDirectMethod(i) : c->GetVirtualMethod(i - direct_method_count);
805
806 expandBufAddMethodId(pReply, ToMethodId(m));
807 expandBufAddUtf8String(pReply, m->GetName()->ToModifiedUtf8().c_str());
808 expandBufAddUtf8String(pReply, m->GetSignature()->ToModifiedUtf8().c_str());
809 if (withGeneric) {
810 static const char genericSignature[1] = "";
811 expandBufAddUtf8String(pReply, genericSignature);
812 }
813 expandBufAdd4BE(pReply, MangleAccessFlags(m->GetAccessFlags()));
814 }
815}
816
817void Dbg::OutputDeclaredInterfaces(JDWP::RefTypeId refTypeId, JDWP::ExpandBuf* pReply) {
818 Class* c = gRegistry->Get<Class*>(refTypeId);
819 CHECK(c != NULL);
820 size_t interface_count = c->NumInterfaces();
821 expandBufAdd4BE(pReply, interface_count);
822 for (size_t i = 0; i < interface_count; ++i) {
823 expandBufAddRefTypeId(pReply, gRegistry->Add(c->GetInterface(i)));
824 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700825}
826
827void Dbg::OutputLineTable(JDWP::RefTypeId refTypeId, JDWP::MethodId methodId, JDWP::ExpandBuf* pReply) {
Elliott Hughes03181a82011-11-17 17:22:21 -0800828 struct DebugCallbackContext {
829 int numItems;
830 JDWP::ExpandBuf* pReply;
831
832 static bool Callback(void* context, uint32_t address, uint32_t lineNum) {
833 DebugCallbackContext* pContext = reinterpret_cast<DebugCallbackContext*>(context);
834 expandBufAdd8BE(pContext->pReply, address);
835 expandBufAdd4BE(pContext->pReply, lineNum);
836 pContext->numItems++;
837 return true;
838 }
839 };
840
841 Method* m = FromMethodId(methodId);
842 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
843 const DexFile& dex_file = class_linker->FindDexFile(m->GetDeclaringClass()->GetDexCache());
844 const DexFile::CodeItem* code_item = dex_file.GetCodeItem(m->GetCodeItemOffset());
845
846 uint64_t start, end;
847 if (m->IsNative()) {
848 start = -1;
849 end = -1;
850 } else {
851 start = 0;
852 end = code_item->insns_size_in_code_units_; // TODO: what are the units supposed to be? *2?
853 }
854
855 expandBufAdd8BE(pReply, start);
856 expandBufAdd8BE(pReply, end);
857
858 // Add numLines later
859 size_t numLinesOffset = expandBufGetLength(pReply);
860 expandBufAdd4BE(pReply, 0);
861
862 DebugCallbackContext context;
863 context.numItems = 0;
864 context.pReply = pReply;
865
866 dex_file.DecodeDebugInfo(code_item, m, DebugCallbackContext::Callback, NULL, &context);
867
868 JDWP::Set4BE(expandBufGetBuffer(pReply) + numLinesOffset, context.numItems);
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700869}
870
Elliott Hughesdbb40792011-11-18 17:05:22 -0800871void Dbg::OutputVariableTable(JDWP::RefTypeId refTypeId, JDWP::MethodId methodId, bool withGeneric, JDWP::ExpandBuf* pReply) {
872 struct DebugCallbackContext {
873 int numItems;
874 JDWP::ExpandBuf* pReply;
875 bool withGeneric;
876
877 static void Callback(void* context, uint16_t slot, uint32_t startAddress, uint32_t endAddress, const char *name, const char *descriptor, const char *signature) {
878 DebugCallbackContext* pContext = reinterpret_cast<DebugCallbackContext*>(context);
879
Elliott Hughesdbb40792011-11-18 17:05:22 -0800880 LOG(VERBOSE) << StringPrintf(" %2d: %d(%d) '%s' '%s' '%s' slot=%d", pContext->numItems, startAddress, endAddress - startAddress, name, descriptor, signature, slot);
881
Elliott Hughes68fdbd02011-11-29 19:22:47 -0800882 slot = MangleSlot(slot, name);
883
Elliott Hughesdbb40792011-11-18 17:05:22 -0800884 expandBufAdd8BE(pContext->pReply, startAddress);
885 expandBufAddUtf8String(pContext->pReply, name);
886 expandBufAddUtf8String(pContext->pReply, descriptor);
887 if (pContext->withGeneric) {
888 expandBufAddUtf8String(pContext->pReply, signature);
889 }
890 expandBufAdd4BE(pContext->pReply, endAddress - startAddress);
891 expandBufAdd4BE(pContext->pReply, slot);
892
893 pContext->numItems++;
894 }
895 };
896
897 Method* m = FromMethodId(methodId);
898 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
899 const DexFile& dex_file = class_linker->FindDexFile(m->GetDeclaringClass()->GetDexCache());
900 const DexFile::CodeItem* code_item = dex_file.GetCodeItem(m->GetCodeItemOffset());
901
902 expandBufAdd4BE(pReply, m->NumIns());
903
904 // Add numLocals later
905 size_t numLocalsOffset = expandBufGetLength(pReply);
906 expandBufAdd4BE(pReply, 0);
907
908 DebugCallbackContext context;
909 context.numItems = 0;
910 context.pReply = pReply;
911 context.withGeneric = withGeneric;
912
913 dex_file.DecodeDebugInfo(code_item, m, NULL, DebugCallbackContext::Callback, &context);
914
915 JDWP::Set4BE(expandBufGetBuffer(pReply) + numLocalsOffset, context.numItems);
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700916}
917
918uint8_t Dbg::GetFieldBasicTag(JDWP::ObjectId objId, JDWP::FieldId fieldId) {
919 UNIMPLEMENTED(FATAL);
920 return 0;
921}
922
923uint8_t Dbg::GetStaticFieldBasicTag(JDWP::RefTypeId refTypeId, JDWP::FieldId fieldId) {
924 UNIMPLEMENTED(FATAL);
925 return 0;
926}
927
928void Dbg::GetFieldValue(JDWP::ObjectId objectId, JDWP::FieldId fieldId, JDWP::ExpandBuf* pReply) {
929 UNIMPLEMENTED(FATAL);
930}
931
932void Dbg::SetFieldValue(JDWP::ObjectId objectId, JDWP::FieldId fieldId, uint64_t value, int width) {
933 UNIMPLEMENTED(FATAL);
934}
935
936void Dbg::GetStaticFieldValue(JDWP::RefTypeId refTypeId, JDWP::FieldId fieldId, JDWP::ExpandBuf* pReply) {
937 UNIMPLEMENTED(FATAL);
938}
939
940void Dbg::SetStaticFieldValue(JDWP::RefTypeId refTypeId, JDWP::FieldId fieldId, uint64_t rawValue, int width) {
941 UNIMPLEMENTED(FATAL);
942}
943
Elliott Hughes68fdbd02011-11-29 19:22:47 -0800944std::string Dbg::StringToUtf8(JDWP::ObjectId strId) {
945 String* s = gRegistry->Get<String*>(strId);
946 return s->ToModifiedUtf8();
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700947}
948
Elliott Hughesa2e54f62011-11-17 13:01:30 -0800949Thread* DecodeThread(JDWP::ObjectId threadId) {
950 Object* thread_peer = gRegistry->Get<Object*>(threadId);
951 CHECK(thread_peer != NULL);
952 return Thread::FromManagedThread(thread_peer);
953}
954
955bool Dbg::GetThreadName(JDWP::ObjectId threadId, std::string& name) {
956 ScopedThreadListLock thread_list_lock;
957 Thread* thread = DecodeThread(threadId);
958 if (thread == NULL) {
959 return false;
960 }
961 StringAppendF(&name, "<%d> %s", thread->GetThinLockId(), thread->GetName()->ToModifiedUtf8().c_str());
962 return true;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700963}
964
965JDWP::ObjectId Dbg::GetThreadGroup(JDWP::ObjectId threadId) {
Elliott Hughes499c5132011-11-17 14:55:11 -0800966 Object* thread = gRegistry->Get<Object*>(threadId);
967 CHECK(thread != NULL);
968
969 Class* c = Runtime::Current()->GetClassLinker()->FindSystemClass("Ljava/lang/Thread;");
970 CHECK(c != NULL);
971 Field* f = c->FindInstanceField("group", "Ljava/lang/ThreadGroup;");
972 CHECK(f != NULL);
973 Object* group = f->GetObject(thread);
974 CHECK(group != NULL);
975 return gRegistry->Add(group);
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700976}
977
Elliott Hughes499c5132011-11-17 14:55:11 -0800978std::string Dbg::GetThreadGroupName(JDWP::ObjectId threadGroupId) {
979 Object* thread_group = gRegistry->Get<Object*>(threadGroupId);
980 CHECK(thread_group != NULL);
981
982 Class* c = Runtime::Current()->GetClassLinker()->FindSystemClass("Ljava/lang/ThreadGroup;");
983 CHECK(c != NULL);
984 Field* f = c->FindInstanceField("name", "Ljava/lang/String;");
985 CHECK(f != NULL);
986 String* s = reinterpret_cast<String*>(f->GetObject(thread_group));
987 return s->ToModifiedUtf8();
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700988}
989
990JDWP::ObjectId Dbg::GetThreadGroupParent(JDWP::ObjectId threadGroupId) {
991 UNIMPLEMENTED(FATAL);
992 return 0;
993}
994
Elliott Hughes499c5132011-11-17 14:55:11 -0800995static Object* GetStaticThreadGroup(const char* field_name) {
996 Class* c = Runtime::Current()->GetClassLinker()->FindSystemClass("Ljava/lang/ThreadGroup;");
997 CHECK(c != NULL);
998 Field* f = c->FindStaticField(field_name, "Ljava/lang/ThreadGroup;");
999 CHECK(f != NULL);
1000 Object* group = f->GetObject(NULL);
1001 CHECK(group != NULL);
1002 return group;
1003}
1004
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001005JDWP::ObjectId Dbg::GetSystemThreadGroupId() {
Elliott Hughes499c5132011-11-17 14:55:11 -08001006 return gRegistry->Add(GetStaticThreadGroup("mSystem"));
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001007}
1008
1009JDWP::ObjectId Dbg::GetMainThreadGroupId() {
Elliott Hughes499c5132011-11-17 14:55:11 -08001010 return gRegistry->Add(GetStaticThreadGroup("mMain"));
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001011}
1012
Elliott Hughes499c5132011-11-17 14:55:11 -08001013bool Dbg::GetThreadStatus(JDWP::ObjectId threadId, uint32_t* pThreadStatus, uint32_t* pSuspendStatus) {
1014 ScopedThreadListLock thread_list_lock;
1015
1016 Thread* thread = DecodeThread(threadId);
1017 if (thread == NULL) {
1018 return false;
1019 }
1020
1021 switch (thread->GetState()) {
1022 case Thread::kTerminated: *pThreadStatus = JDWP::TS_ZOMBIE; break;
1023 case Thread::kRunnable: *pThreadStatus = JDWP::TS_RUNNING; break;
1024 case Thread::kTimedWaiting: *pThreadStatus = JDWP::TS_SLEEPING; break;
1025 case Thread::kBlocked: *pThreadStatus = JDWP::TS_MONITOR; break;
1026 case Thread::kWaiting: *pThreadStatus = JDWP::TS_WAIT; break;
1027 case Thread::kInitializing: *pThreadStatus = JDWP::TS_ZOMBIE; break;
1028 case Thread::kStarting: *pThreadStatus = JDWP::TS_ZOMBIE; break;
1029 case Thread::kNative: *pThreadStatus = JDWP::TS_RUNNING; break;
1030 case Thread::kVmWait: *pThreadStatus = JDWP::TS_WAIT; break;
1031 case Thread::kSuspended: *pThreadStatus = JDWP::TS_RUNNING; break;
1032 default:
1033 LOG(FATAL) << "unknown thread state " << thread->GetState();
1034 }
1035
1036 *pSuspendStatus = (thread->IsSuspended() ? JDWP::SUSPEND_STATUS_SUSPENDED : 0);
1037
1038 return true;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001039}
1040
1041uint32_t Dbg::GetThreadSuspendCount(JDWP::ObjectId threadId) {
1042 UNIMPLEMENTED(FATAL);
1043 return 0;
1044}
1045
1046bool Dbg::ThreadExists(JDWP::ObjectId threadId) {
Elliott Hughes761928d2011-11-16 18:33:03 -08001047 return DecodeThread(threadId) != NULL;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001048}
1049
1050bool Dbg::IsSuspended(JDWP::ObjectId threadId) {
Elliott Hughes761928d2011-11-16 18:33:03 -08001051 return DecodeThread(threadId)->IsSuspended();
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001052}
1053
1054//void Dbg::WaitForSuspend(JDWP::ObjectId threadId);
1055
Elliott Hughesa2155262011-11-16 16:26:58 -08001056void Dbg::GetThreadGroupThreadsImpl(Object* thread_group, JDWP::ObjectId** ppThreadIds, uint32_t* pThreadCount) {
1057 struct ThreadListVisitor {
1058 static void Visit(Thread* t, void* arg) {
1059 reinterpret_cast<ThreadListVisitor*>(arg)->Visit(t);
1060 }
1061
1062 void Visit(Thread* t) {
1063 if (t == Dbg::GetDebugThread()) {
1064 // Skip the JDWP thread. Some debuggers get bent out of shape when they can't suspend and
1065 // query all threads, so it's easier if we just don't tell them about this thread.
1066 return;
1067 }
1068 if (thread_group == NULL || t->GetThreadGroup() == thread_group) {
1069 threads.push_back(gRegistry->Add(t->GetPeer()));
1070 }
1071 }
1072
1073 Object* thread_group;
1074 std::vector<JDWP::ObjectId> threads;
1075 };
1076
1077 ThreadListVisitor tlv;
1078 tlv.thread_group = thread_group;
1079
1080 {
1081 ScopedThreadListLock thread_list_lock;
1082 Runtime::Current()->GetThreadList()->ForEach(ThreadListVisitor::Visit, &tlv);
1083 }
1084
1085 *pThreadCount = tlv.threads.size();
1086 if (*pThreadCount == 0) {
1087 *ppThreadIds = NULL;
1088 } else {
1089 *ppThreadIds = new JDWP::ObjectId[*pThreadCount];
1090 for (size_t i = 0; i < *pThreadCount; ++i) {
1091 (*ppThreadIds)[i] = tlv.threads[i];
1092 }
1093 }
1094}
1095
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001096void Dbg::GetThreadGroupThreads(JDWP::ObjectId threadGroupId, JDWP::ObjectId** ppThreadIds, uint32_t* pThreadCount) {
Elliott Hughesa2155262011-11-16 16:26:58 -08001097 GetThreadGroupThreadsImpl(gRegistry->Get<Object*>(threadGroupId), ppThreadIds, pThreadCount);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001098}
1099
1100void Dbg::GetAllThreads(JDWP::ObjectId** ppThreadIds, uint32_t* pThreadCount) {
Elliott Hughesa2155262011-11-16 16:26:58 -08001101 GetThreadGroupThreadsImpl(NULL, ppThreadIds, pThreadCount);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001102}
1103
1104int Dbg::GetThreadFrameCount(JDWP::ObjectId threadId) {
Elliott Hughes03181a82011-11-17 17:22:21 -08001105 ScopedThreadListLock thread_list_lock;
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001106 struct CountStackDepthVisitor : public Thread::StackVisitor {
1107 CountStackDepthVisitor() : depth(0) {}
Elliott Hughesf8a2df72011-12-01 12:19:54 -08001108 virtual void VisitFrame(const Frame& f, uintptr_t) {
1109 // TODO: we'll need to skip callee-save frames too.
1110 if (f.HasMethod()) {
1111 ++depth;
1112 }
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001113 }
1114 size_t depth;
1115 };
1116 CountStackDepthVisitor visitor;
1117 DecodeThread(threadId)->WalkStack(&visitor);
1118 return visitor.depth;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001119}
1120
Elliott Hughes03181a82011-11-17 17:22:21 -08001121bool Dbg::GetThreadFrame(JDWP::ObjectId threadId, int desired_frame_number, JDWP::FrameId* pFrameId, JDWP::JdwpLocation* pLoc) {
1122 ScopedThreadListLock thread_list_lock;
1123 struct GetFrameVisitor : public Thread::StackVisitor {
1124 GetFrameVisitor(int desired_frame_number, JDWP::FrameId* pFrameId, JDWP::JdwpLocation* pLoc)
1125 : found(false) ,depth(0), desired_frame_number(desired_frame_number), pFrameId(pFrameId), pLoc(pLoc) {
1126 }
1127 virtual void VisitFrame(const Frame& f, uintptr_t pc) {
Elliott Hughesf8a2df72011-12-01 12:19:54 -08001128 // TODO: we'll need to skip callee-save frames too.
Elliott Hughes03181a82011-11-17 17:22:21 -08001129 if (!f.HasMethod()) {
Elliott Hughesf8a2df72011-12-01 12:19:54 -08001130 return; // The debugger can't do anything useful with a frame that has no Method*.
Elliott Hughes03181a82011-11-17 17:22:21 -08001131 }
1132
1133 if (depth == desired_frame_number) {
1134 *pFrameId = reinterpret_cast<JDWP::FrameId>(f.GetSP());
1135
1136 Method* m = f.GetMethod();
1137 Class* c = m->GetDeclaringClass();
1138
1139 pLoc->typeTag = c->IsInterface() ? JDWP::TT_INTERFACE : JDWP::TT_CLASS;
1140 pLoc->classId = gRegistry->Add(c);
1141 pLoc->methodId = ToMethodId(m);
1142 pLoc->idx = m->IsNative() ? -1 : m->ToDexPC(pc);
1143
1144 found = true;
1145 }
1146 ++depth;
1147 }
1148 bool found;
1149 int depth;
1150 int desired_frame_number;
1151 JDWP::FrameId* pFrameId;
1152 JDWP::JdwpLocation* pLoc;
1153 };
1154 GetFrameVisitor visitor(desired_frame_number, pFrameId, pLoc);
1155 visitor.desired_frame_number = desired_frame_number;
1156 DecodeThread(threadId)->WalkStack(&visitor);
1157 return visitor.found;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001158}
1159
1160JDWP::ObjectId Dbg::GetThreadSelfId() {
Elliott Hughes475fc232011-10-25 15:00:35 -07001161 return gRegistry->Add(Thread::Current()->GetPeer());
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001162}
1163
Elliott Hughes475fc232011-10-25 15:00:35 -07001164void Dbg::SuspendVM() {
Elliott Hughesa2155262011-11-16 16:26:58 -08001165 ScopedThreadStateChange tsc(Thread::Current(), Thread::kRunnable); // TODO: do we really want to change back? should the JDWP thread be Runnable usually?
Elliott Hughes475fc232011-10-25 15:00:35 -07001166 Runtime::Current()->GetThreadList()->SuspendAll(true);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001167}
1168
1169void Dbg::ResumeVM() {
Elliott Hughes475fc232011-10-25 15:00:35 -07001170 Runtime::Current()->GetThreadList()->ResumeAll(true);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001171}
1172
1173void Dbg::SuspendThread(JDWP::ObjectId threadId) {
1174 UNIMPLEMENTED(FATAL);
1175}
1176
1177void Dbg::ResumeThread(JDWP::ObjectId threadId) {
1178 UNIMPLEMENTED(FATAL);
1179}
1180
1181void Dbg::SuspendSelf() {
Elliott Hughes475fc232011-10-25 15:00:35 -07001182 Runtime::Current()->GetThreadList()->SuspendSelfForDebugger();
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001183}
1184
1185bool Dbg::GetThisObject(JDWP::ObjectId threadId, JDWP::FrameId frameId, JDWP::ObjectId* pThisId) {
1186 UNIMPLEMENTED(FATAL);
1187 return false;
1188}
1189
Elliott Hughesdbb40792011-11-18 17:05:22 -08001190void Dbg::GetLocalValue(JDWP::ObjectId threadId, JDWP::FrameId frameId, int slot, JDWP::JdwpTag tag, uint8_t* buf, size_t expectedLen) {
1191 Method** sp = reinterpret_cast<Method**>(frameId);
Elliott Hughes68fdbd02011-11-29 19:22:47 -08001192 Frame f;
1193 f.SetSP(sp);
1194 uint16_t reg = DemangleSlot(slot, f);
1195 Method* m = f.GetMethod();
1196
1197 const VmapTable vmap_table(m->GetVmapTableRaw());
1198 uint32_t vmap_offset;
1199 if (vmap_table.IsInContext(reg, vmap_offset)) {
1200 UNIMPLEMENTED(FATAL) << "don't know how to pull locals from callee save frames: " << vmap_offset;
1201 }
Elliott Hughesdbb40792011-11-18 17:05:22 -08001202
1203 switch (tag) {
1204 case JDWP::JT_BOOLEAN:
1205 {
Elliott Hughesdbb40792011-11-18 17:05:22 -08001206 CHECK_EQ(expectedLen, 1U);
Elliott Hughes68fdbd02011-11-29 19:22:47 -08001207 uint32_t intVal = static_cast<uint32_t>(f.GetVReg(m, reg));
1208 LOG(WARNING) << "get boolean local " << reg << " = " << intVal;
Elliott Hughesdbb40792011-11-18 17:05:22 -08001209 JDWP::Set1(buf+1, intVal != 0);
1210 }
1211 break;
1212 case JDWP::JT_BYTE:
1213 {
Elliott Hughesdbb40792011-11-18 17:05:22 -08001214 CHECK_EQ(expectedLen, 1U);
Elliott Hughes68fdbd02011-11-29 19:22:47 -08001215 uint32_t intVal = static_cast<uint32_t>(f.GetVReg(m, reg));
1216 LOG(WARNING) << "get byte local " << reg << " = " << intVal;
Elliott Hughesdbb40792011-11-18 17:05:22 -08001217 JDWP::Set1(buf+1, intVal);
1218 }
1219 break;
1220 case JDWP::JT_SHORT:
1221 case JDWP::JT_CHAR:
1222 {
Elliott Hughesdbb40792011-11-18 17:05:22 -08001223 CHECK_EQ(expectedLen, 2U);
Elliott Hughes68fdbd02011-11-29 19:22:47 -08001224 uint32_t intVal = static_cast<uint32_t>(f.GetVReg(m, reg));
1225 LOG(WARNING) << "get short/char local " << reg << " = " << intVal;
Elliott Hughesdbb40792011-11-18 17:05:22 -08001226 JDWP::Set2BE(buf+1, intVal);
1227 }
1228 break;
1229 case JDWP::JT_INT:
1230 case JDWP::JT_FLOAT:
1231 {
Elliott Hughesdbb40792011-11-18 17:05:22 -08001232 CHECK_EQ(expectedLen, 4U);
Elliott Hughes68fdbd02011-11-29 19:22:47 -08001233 uint32_t intVal = static_cast<uint32_t>(f.GetVReg(m, reg));
1234 LOG(WARNING) << "get int/float local " << reg << " = " << intVal;
Elliott Hughesdbb40792011-11-18 17:05:22 -08001235 JDWP::Set4BE(buf+1, intVal);
1236 }
1237 break;
1238 case JDWP::JT_ARRAY:
1239 {
Elliott Hughesdbb40792011-11-18 17:05:22 -08001240 CHECK_EQ(expectedLen, sizeof(JDWP::ObjectId));
Elliott Hughes68fdbd02011-11-29 19:22:47 -08001241 Object* o = reinterpret_cast<Object*>(f.GetVReg(m, reg));
1242 LOG(WARNING) << "get array local " << reg << " = " << o;
Elliott Hughesdbb40792011-11-18 17:05:22 -08001243 if (o != NULL && !Heap::IsHeapAddress(o)) {
Elliott Hughes68fdbd02011-11-29 19:22:47 -08001244 LOG(FATAL) << "reg " << reg << " expected to hold array: " << o;
Elliott Hughesdbb40792011-11-18 17:05:22 -08001245 }
1246 JDWP::SetObjectId(buf+1, gRegistry->Add(o));
1247 }
1248 break;
1249 case JDWP::JT_OBJECT:
1250 {
Elliott Hughesdbb40792011-11-18 17:05:22 -08001251 CHECK_EQ(expectedLen, sizeof(JDWP::ObjectId));
Elliott Hughes68fdbd02011-11-29 19:22:47 -08001252 Object* o = reinterpret_cast<Object*>(f.GetVReg(m, reg));
1253 LOG(WARNING) << "get object local " << reg << " = " << o;
Elliott Hughesdbb40792011-11-18 17:05:22 -08001254 if (o != NULL && !Heap::IsHeapAddress(o)) {
Elliott Hughes68fdbd02011-11-29 19:22:47 -08001255 LOG(FATAL) << "reg " << reg << " expected to hold object: " << o;
Elliott Hughesdbb40792011-11-18 17:05:22 -08001256 }
1257 tag = TagFromObject(o);
1258 JDWP::SetObjectId(buf+1, gRegistry->Add(o));
1259 }
1260 break;
1261 case JDWP::JT_DOUBLE:
1262 case JDWP::JT_LONG:
1263 {
Elliott Hughes68fdbd02011-11-29 19:22:47 -08001264 UNIMPLEMENTED(WARNING) << "get 64-bit local " << reg;
Elliott Hughesdbb40792011-11-18 17:05:22 -08001265 CHECK_EQ(expectedLen, 8U);
Elliott Hughes68fdbd02011-11-29 19:22:47 -08001266 uint64_t longVal = 0; // memcpy(&longVal, &framePtr[reg], 8);
Elliott Hughesdbb40792011-11-18 17:05:22 -08001267 JDWP::Set8BE(buf+1, longVal);
1268 }
1269 break;
1270 default:
1271 LOG(FATAL) << "unknown tag " << tag;
1272 break;
1273 }
1274
1275 // Prepend tag, which may have been updated.
1276 JDWP::Set1(buf, tag);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001277}
1278
Elliott Hughesdbb40792011-11-18 17:05:22 -08001279void Dbg::SetLocalValue(JDWP::ObjectId threadId, JDWP::FrameId frameId, int slot, JDWP::JdwpTag tag, uint64_t value, size_t width) {
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001280 UNIMPLEMENTED(FATAL);
1281}
1282
1283void Dbg::PostLocationEvent(const Method* method, int pcOffset, Object* thisPtr, int eventFlags) {
1284 UNIMPLEMENTED(FATAL);
1285}
1286
1287void Dbg::PostException(void* throwFp, int throwRelPc, void* catchFp, int catchRelPc, Object* exception) {
1288 UNIMPLEMENTED(FATAL);
1289}
1290
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001291void Dbg::PostClassPrepare(Class* c) {
1292 UNIMPLEMENTED(FATAL);
1293}
1294
1295bool Dbg::WatchLocation(const JDWP::JdwpLocation* pLoc) {
1296 UNIMPLEMENTED(FATAL);
1297 return false;
1298}
1299
1300void Dbg::UnwatchLocation(const JDWP::JdwpLocation* pLoc) {
1301 UNIMPLEMENTED(FATAL);
1302}
1303
1304bool Dbg::ConfigureStep(JDWP::ObjectId threadId, JDWP::JdwpStepSize size, JDWP::JdwpStepDepth depth) {
1305 UNIMPLEMENTED(FATAL);
1306 return false;
1307}
1308
1309void Dbg::UnconfigureStep(JDWP::ObjectId threadId) {
1310 UNIMPLEMENTED(FATAL);
1311}
1312
1313JDWP::JdwpError Dbg::InvokeMethod(JDWP::ObjectId threadId, JDWP::ObjectId objectId, JDWP::RefTypeId classId, JDWP::MethodId methodId, uint32_t numArgs, uint64_t* argArray, uint32_t options, uint8_t* pResultTag, uint64_t* pResultValue, JDWP::ObjectId* pExceptObj) {
1314 UNIMPLEMENTED(FATAL);
1315 return JDWP::ERR_NONE;
1316}
1317
1318void Dbg::ExecuteMethod(DebugInvokeReq* pReq) {
1319 UNIMPLEMENTED(FATAL);
1320}
1321
1322void Dbg::RegisterObjectId(JDWP::ObjectId id) {
1323 UNIMPLEMENTED(FATAL);
1324}
1325
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07001326/*
1327 * "buf" contains a full JDWP packet, possibly with multiple chunks. We
1328 * need to process each, accumulate the replies, and ship the whole thing
1329 * back.
1330 *
1331 * Returns "true" if we have a reply. The reply buffer is newly allocated,
1332 * and includes the chunk type/length, followed by the data.
1333 *
1334 * TODO: we currently assume that the request and reply include a single
1335 * chunk. If this becomes inconvenient we will need to adapt.
1336 */
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001337bool Dbg::DdmHandlePacket(const uint8_t* buf, int dataLen, uint8_t** pReplyBuf, int* pReplyLen) {
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07001338 CHECK_GE(dataLen, 0);
1339
1340 Thread* self = Thread::Current();
1341 JNIEnv* env = self->GetJniEnv();
1342
1343 static jclass Chunk_class = env->FindClass("org/apache/harmony/dalvik/ddmc/Chunk");
1344 static jclass DdmServer_class = env->FindClass("org/apache/harmony/dalvik/ddmc/DdmServer");
1345 static jmethodID dispatch_mid = env->GetStaticMethodID(DdmServer_class, "dispatch",
1346 "(I[BII)Lorg/apache/harmony/dalvik/ddmc/Chunk;");
1347 static jfieldID data_fid = env->GetFieldID(Chunk_class, "data", "[B");
1348 static jfieldID length_fid = env->GetFieldID(Chunk_class, "length", "I");
1349 static jfieldID offset_fid = env->GetFieldID(Chunk_class, "offset", "I");
1350 static jfieldID type_fid = env->GetFieldID(Chunk_class, "type", "I");
1351
1352 // Create a byte[] corresponding to 'buf'.
Elliott Hughes6a5bd492011-10-28 14:33:57 -07001353 ScopedLocalRef<jbyteArray> dataArray(env, env->NewByteArray(dataLen));
1354 if (dataArray.get() == NULL) {
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07001355 LOG(WARNING) << "byte[] allocation failed: " << dataLen;
1356 env->ExceptionClear();
1357 return false;
1358 }
Elliott Hughes6a5bd492011-10-28 14:33:57 -07001359 env->SetByteArrayRegion(dataArray.get(), 0, dataLen, reinterpret_cast<const jbyte*>(buf));
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07001360
1361 const int kChunkHdrLen = 8;
1362
1363 // Run through and find all chunks. [Currently just find the first.]
Elliott Hughes6a5bd492011-10-28 14:33:57 -07001364 ScopedByteArrayRO contents(env, dataArray.get());
Elliott Hughesf7c3b662011-10-27 12:04:56 -07001365 jint type = JDWP::Get4BE(reinterpret_cast<const uint8_t*>(&contents[0]));
1366 jint length = JDWP::Get4BE(reinterpret_cast<const uint8_t*>(&contents[4]));
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07001367 jint offset = kChunkHdrLen;
1368 if (offset + length > dataLen) {
1369 LOG(WARNING) << StringPrintf("bad chunk found (len=%u pktLen=%d)", length, dataLen);
1370 return false;
1371 }
1372
1373 // Call "private static Chunk dispatch(int type, byte[] data, int offset, int length)".
Elliott Hughes6a5bd492011-10-28 14:33:57 -07001374 ScopedLocalRef<jobject> chunk(env, env->CallStaticObjectMethod(DdmServer_class, dispatch_mid, type, dataArray.get(), offset, length));
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07001375 if (env->ExceptionCheck()) {
1376 LOG(INFO) << StringPrintf("Exception thrown by dispatcher for 0x%08x", type);
1377 env->ExceptionDescribe();
1378 env->ExceptionClear();
1379 return false;
1380 }
1381
Elliott Hughes6a5bd492011-10-28 14:33:57 -07001382 if (chunk.get() == NULL) {
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07001383 return false;
1384 }
1385
1386 /*
1387 * Pull the pieces out of the chunk. We copy the results into a
1388 * newly-allocated buffer that the caller can free. We don't want to
1389 * continue using the Chunk object because nothing has a reference to it.
1390 *
1391 * We could avoid this by returning type/data/offset/length and having
1392 * the caller be aware of the object lifetime issues, but that
1393 * integrates the JDWP code more tightly into the VM, and doesn't work
1394 * if we have responses for multiple chunks.
1395 *
1396 * So we're pretty much stuck with copying data around multiple times.
1397 */
Elliott Hughes6a5bd492011-10-28 14:33:57 -07001398 ScopedLocalRef<jbyteArray> replyData(env, reinterpret_cast<jbyteArray>(env->GetObjectField(chunk.get(), data_fid)));
1399 length = env->GetIntField(chunk.get(), length_fid);
1400 offset = env->GetIntField(chunk.get(), offset_fid);
1401 type = env->GetIntField(chunk.get(), type_fid);
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07001402
Elliott Hughes6a5bd492011-10-28 14:33:57 -07001403 LOG(VERBOSE) << StringPrintf("DDM reply: type=0x%08x data=%p offset=%d length=%d", type, replyData.get(), offset, length);
1404 if (length == 0 || replyData.get() == NULL) {
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07001405 return false;
1406 }
1407
Elliott Hughes6a5bd492011-10-28 14:33:57 -07001408 jsize replyLength = env->GetArrayLength(replyData.get());
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07001409 if (offset + length > replyLength) {
1410 LOG(WARNING) << StringPrintf("chunk off=%d len=%d exceeds reply array len %d", offset, length, replyLength);
1411 return false;
1412 }
1413
1414 uint8_t* reply = new uint8_t[length + kChunkHdrLen];
1415 if (reply == NULL) {
1416 LOG(WARNING) << "malloc failed: " << (length + kChunkHdrLen);
1417 return false;
1418 }
Elliott Hughesf7c3b662011-10-27 12:04:56 -07001419 JDWP::Set4BE(reply + 0, type);
1420 JDWP::Set4BE(reply + 4, length);
Elliott Hughes6a5bd492011-10-28 14:33:57 -07001421 env->GetByteArrayRegion(replyData.get(), offset, length, reinterpret_cast<jbyte*>(reply + kChunkHdrLen));
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07001422
1423 *pReplyBuf = reply;
1424 *pReplyLen = length + kChunkHdrLen;
1425
1426 LOG(VERBOSE) << StringPrintf("dvmHandleDdm returning type=%.4s buf=%p len=%d", (char*) reply, reply, length);
1427 return true;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001428}
1429
Elliott Hughesa2155262011-11-16 16:26:58 -08001430void Dbg::DdmBroadcast(bool connect) {
Elliott Hughes47fce012011-10-25 18:37:19 -07001431 LOG(VERBOSE) << "Broadcasting DDM " << (connect ? "connect" : "disconnect") << "...";
1432
1433 Thread* self = Thread::Current();
1434 if (self->GetState() != Thread::kRunnable) {
1435 LOG(ERROR) << "DDM broadcast in thread state " << self->GetState();
1436 /* try anyway? */
1437 }
1438
1439 JNIEnv* env = self->GetJniEnv();
1440 static jclass DdmServer_class = env->FindClass("org/apache/harmony/dalvik/ddmc/DdmServer");
1441 static jmethodID broadcast_mid = env->GetStaticMethodID(DdmServer_class, "broadcast", "(I)V");
1442 jint event = connect ? 1 /*DdmServer.CONNECTED*/ : 2 /*DdmServer.DISCONNECTED*/;
1443 env->CallStaticVoidMethod(DdmServer_class, broadcast_mid, event);
1444 if (env->ExceptionCheck()) {
1445 LOG(ERROR) << "DdmServer.broadcast " << event << " failed";
1446 env->ExceptionDescribe();
1447 env->ExceptionClear();
1448 }
1449}
1450
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001451void Dbg::DdmConnected() {
Elliott Hughesa2155262011-11-16 16:26:58 -08001452 Dbg::DdmBroadcast(true);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001453}
1454
1455void Dbg::DdmDisconnected() {
Elliott Hughesa2155262011-11-16 16:26:58 -08001456 Dbg::DdmBroadcast(false);
Elliott Hughes47fce012011-10-25 18:37:19 -07001457 gDdmThreadNotification = false;
1458}
1459
1460/*
Elliott Hughes82188472011-11-07 18:11:48 -08001461 * Send a notification when a thread starts, stops, or changes its name.
Elliott Hughes47fce012011-10-25 18:37:19 -07001462 *
1463 * Because we broadcast the full set of threads when the notifications are
1464 * first enabled, it's possible for "thread" to be actively executing.
1465 */
Elliott Hughes82188472011-11-07 18:11:48 -08001466void Dbg::DdmSendThreadNotification(Thread* t, uint32_t type) {
Elliott Hughes47fce012011-10-25 18:37:19 -07001467 if (!gDdmThreadNotification) {
1468 return;
1469 }
1470
Elliott Hughes82188472011-11-07 18:11:48 -08001471 if (type == CHUNK_TYPE("THDE")) {
Elliott Hughes47fce012011-10-25 18:37:19 -07001472 uint8_t buf[4];
Elliott Hughesf7c3b662011-10-27 12:04:56 -07001473 JDWP::Set4BE(&buf[0], t->GetThinLockId());
Elliott Hughes47fce012011-10-25 18:37:19 -07001474 Dbg::DdmSendChunk(CHUNK_TYPE("THDE"), 4, buf);
Elliott Hughes82188472011-11-07 18:11:48 -08001475 } else {
1476 CHECK(type == CHUNK_TYPE("THCR") || type == CHUNK_TYPE("THNM")) << type;
1477 SirtRef<String> name(t->GetName());
1478 size_t char_count = (name.get() != NULL) ? name->GetLength() : 0;
1479 const jchar* chars = name->GetCharArray()->GetData();
1480
Elliott Hughes21f32d72011-11-09 17:44:13 -08001481 std::vector<uint8_t> bytes;
Elliott Hughes545a0642011-11-08 19:10:03 -08001482 JDWP::Append4BE(bytes, t->GetThinLockId());
1483 JDWP::AppendUtf16BE(bytes, chars, char_count);
Elliott Hughes21f32d72011-11-09 17:44:13 -08001484 CHECK_EQ(bytes.size(), char_count*2 + sizeof(uint32_t)*2);
1485 Dbg::DdmSendChunk(type, bytes);
Elliott Hughes47fce012011-10-25 18:37:19 -07001486 }
1487}
1488
Elliott Hughesa2155262011-11-16 16:26:58 -08001489static void DdmSendThreadStartCallback(Thread* t, void*) {
Elliott Hughes82188472011-11-07 18:11:48 -08001490 Dbg::DdmSendThreadNotification(t, CHUNK_TYPE("THCR"));
Elliott Hughes47fce012011-10-25 18:37:19 -07001491}
1492
1493void Dbg::DdmSetThreadNotification(bool enable) {
1494 // We lock the thread list to avoid sending duplicate events or missing
1495 // a thread change. We should be okay holding this lock while sending
1496 // the messages out. (We have to hold it while accessing a live thread.)
Elliott Hughesbbd9d832011-11-07 14:40:00 -08001497 ScopedThreadListLock thread_list_lock;
Elliott Hughes47fce012011-10-25 18:37:19 -07001498
1499 gDdmThreadNotification = enable;
1500 if (enable) {
Elliott Hughesbfe487b2011-10-26 15:48:55 -07001501 Runtime::Current()->GetThreadList()->ForEach(DdmSendThreadStartCallback, NULL);
Elliott Hughes47fce012011-10-25 18:37:19 -07001502 }
1503}
1504
Elliott Hughesa2155262011-11-16 16:26:58 -08001505void Dbg::PostThreadStartOrStop(Thread* t, uint32_t type) {
Elliott Hughes47fce012011-10-25 18:37:19 -07001506 if (gDebuggerActive) {
1507 JDWP::ObjectId id = gRegistry->Add(t->GetPeer());
Elliott Hughes82188472011-11-07 18:11:48 -08001508 gJdwpState->PostThreadChange(id, type == CHUNK_TYPE("THCR"));
Elliott Hughes47fce012011-10-25 18:37:19 -07001509 }
Elliott Hughes82188472011-11-07 18:11:48 -08001510 Dbg::DdmSendThreadNotification(t, type);
Elliott Hughes47fce012011-10-25 18:37:19 -07001511}
1512
1513void Dbg::PostThreadStart(Thread* t) {
Elliott Hughesa2155262011-11-16 16:26:58 -08001514 Dbg::PostThreadStartOrStop(t, CHUNK_TYPE("THCR"));
Elliott Hughes47fce012011-10-25 18:37:19 -07001515}
1516
1517void Dbg::PostThreadDeath(Thread* t) {
Elliott Hughesa2155262011-11-16 16:26:58 -08001518 Dbg::PostThreadStartOrStop(t, CHUNK_TYPE("THDE"));
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001519}
1520
Elliott Hughes82188472011-11-07 18:11:48 -08001521void Dbg::DdmSendChunk(uint32_t type, size_t byte_count, const uint8_t* buf) {
Elliott Hughes3bb81562011-10-21 18:52:59 -07001522 CHECK(buf != NULL);
1523 iovec vec[1];
1524 vec[0].iov_base = reinterpret_cast<void*>(const_cast<uint8_t*>(buf));
1525 vec[0].iov_len = byte_count;
1526 Dbg::DdmSendChunkV(type, vec, 1);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001527}
1528
Elliott Hughes21f32d72011-11-09 17:44:13 -08001529void Dbg::DdmSendChunk(uint32_t type, const std::vector<uint8_t>& bytes) {
1530 DdmSendChunk(type, bytes.size(), &bytes[0]);
1531}
1532
Elliott Hughes82188472011-11-07 18:11:48 -08001533void Dbg::DdmSendChunkV(uint32_t type, const struct iovec* iov, int iovcnt) {
Elliott Hughes3bb81562011-10-21 18:52:59 -07001534 if (gJdwpState == NULL) {
1535 LOG(VERBOSE) << "Debugger thread not active, ignoring DDM send: " << type;
1536 } else {
Elliott Hughes376a7a02011-10-24 18:35:55 -07001537 gJdwpState->DdmSendChunkV(type, iov, iovcnt);
Elliott Hughes3bb81562011-10-21 18:52:59 -07001538 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001539}
1540
Elliott Hughes767a1472011-10-26 18:49:02 -07001541int Dbg::DdmHandleHpifChunk(HpifWhen when) {
1542 if (when == HPIF_WHEN_NOW) {
Elliott Hughes7162ad92011-10-27 14:08:42 -07001543 DdmSendHeapInfo(when);
Elliott Hughes767a1472011-10-26 18:49:02 -07001544 return true;
1545 }
1546
1547 if (when != HPIF_WHEN_NEVER && when != HPIF_WHEN_NEXT_GC && when != HPIF_WHEN_EVERY_GC) {
1548 LOG(ERROR) << "invalid HpifWhen value: " << static_cast<int>(when);
1549 return false;
1550 }
1551
1552 gDdmHpifWhen = when;
1553 return true;
1554}
1555
1556bool Dbg::DdmHandleHpsgNhsgChunk(Dbg::HpsgWhen when, Dbg::HpsgWhat what, bool native) {
1557 if (when != HPSG_WHEN_NEVER && when != HPSG_WHEN_EVERY_GC) {
1558 LOG(ERROR) << "invalid HpsgWhen value: " << static_cast<int>(when);
1559 return false;
1560 }
1561
1562 if (what != HPSG_WHAT_MERGED_OBJECTS && what != HPSG_WHAT_DISTINCT_OBJECTS) {
1563 LOG(ERROR) << "invalid HpsgWhat value: " << static_cast<int>(what);
1564 return false;
1565 }
1566
1567 if (native) {
1568 gDdmNhsgWhen = when;
1569 gDdmNhsgWhat = what;
1570 } else {
1571 gDdmHpsgWhen = when;
1572 gDdmHpsgWhat = what;
1573 }
1574 return true;
1575}
1576
Elliott Hughes7162ad92011-10-27 14:08:42 -07001577void Dbg::DdmSendHeapInfo(HpifWhen reason) {
1578 // If there's a one-shot 'when', reset it.
1579 if (reason == gDdmHpifWhen) {
1580 if (gDdmHpifWhen == HPIF_WHEN_NEXT_GC) {
1581 gDdmHpifWhen = HPIF_WHEN_NEVER;
1582 }
1583 }
1584
1585 /*
1586 * Chunk HPIF (client --> server)
1587 *
1588 * Heap Info. General information about the heap,
1589 * suitable for a summary display.
1590 *
1591 * [u4]: number of heaps
1592 *
1593 * For each heap:
1594 * [u4]: heap ID
1595 * [u8]: timestamp in ms since Unix epoch
1596 * [u1]: capture reason (same as 'when' value from server)
1597 * [u4]: max heap size in bytes (-Xmx)
1598 * [u4]: current heap size in bytes
1599 * [u4]: current number of bytes allocated
1600 * [u4]: current number of objects allocated
1601 */
1602 uint8_t heap_count = 1;
Elliott Hughes21f32d72011-11-09 17:44:13 -08001603 std::vector<uint8_t> bytes;
Elliott Hughes545a0642011-11-08 19:10:03 -08001604 JDWP::Append4BE(bytes, heap_count);
1605 JDWP::Append4BE(bytes, 1); // Heap id (bogus; we only have one heap).
1606 JDWP::Append8BE(bytes, MilliTime());
1607 JDWP::Append1BE(bytes, reason);
1608 JDWP::Append4BE(bytes, Heap::GetMaxMemory()); // Max allowed heap size in bytes.
1609 JDWP::Append4BE(bytes, Heap::GetTotalMemory()); // Current heap size in bytes.
1610 JDWP::Append4BE(bytes, Heap::GetBytesAllocated());
1611 JDWP::Append4BE(bytes, Heap::GetObjectsAllocated());
Elliott Hughes21f32d72011-11-09 17:44:13 -08001612 CHECK_EQ(bytes.size(), 4U + (heap_count * (4 + 8 + 1 + 4 + 4 + 4 + 4)));
1613 Dbg::DdmSendChunk(CHUNK_TYPE("HPIF"), bytes);
Elliott Hughes767a1472011-10-26 18:49:02 -07001614}
1615
Elliott Hughes6a5bd492011-10-28 14:33:57 -07001616enum HpsgSolidity {
1617 SOLIDITY_FREE = 0,
1618 SOLIDITY_HARD = 1,
1619 SOLIDITY_SOFT = 2,
1620 SOLIDITY_WEAK = 3,
1621 SOLIDITY_PHANTOM = 4,
1622 SOLIDITY_FINALIZABLE = 5,
1623 SOLIDITY_SWEEP = 6,
1624};
1625
1626enum HpsgKind {
1627 KIND_OBJECT = 0,
1628 KIND_CLASS_OBJECT = 1,
1629 KIND_ARRAY_1 = 2,
1630 KIND_ARRAY_2 = 3,
1631 KIND_ARRAY_4 = 4,
1632 KIND_ARRAY_8 = 5,
1633 KIND_UNKNOWN = 6,
1634 KIND_NATIVE = 7,
1635};
1636
1637#define HPSG_PARTIAL (1<<7)
1638#define HPSG_STATE(solidity, kind) ((uint8_t)((((kind) & 0x7) << 3) | ((solidity) & 0x7)))
1639
1640struct HeapChunkContext {
1641 std::vector<uint8_t> buf;
1642 uint8_t* p;
1643 uint8_t* pieceLenField;
1644 size_t totalAllocationUnits;
Elliott Hughes82188472011-11-07 18:11:48 -08001645 uint32_t type;
Elliott Hughes6a5bd492011-10-28 14:33:57 -07001646 bool merge;
1647 bool needHeader;
1648
1649 // Maximum chunk size. Obtain this from the formula:
1650 // (((maximum_heap_size / ALLOCATION_UNIT_SIZE) + 255) / 256) * 2
1651 HeapChunkContext(bool merge, bool native)
1652 : buf(16384 - 16),
1653 type(0),
1654 merge(merge) {
1655 Reset();
1656 if (native) {
1657 type = CHUNK_TYPE("NHSG");
1658 } else {
1659 type = merge ? CHUNK_TYPE("HPSG") : CHUNK_TYPE("HPSO");
1660 }
1661 }
1662
1663 ~HeapChunkContext() {
1664 if (p > &buf[0]) {
1665 Flush();
1666 }
1667 }
1668
1669 void EnsureHeader(const void* chunk_ptr) {
1670 if (!needHeader) {
1671 return;
1672 }
1673
1674 // Start a new HPSx chunk.
1675 JDWP::Write4BE(&p, 1); // Heap id (bogus; we only have one heap).
1676 JDWP::Write1BE(&p, 8); // Size of allocation unit, in bytes.
1677
1678 JDWP::Write4BE(&p, reinterpret_cast<uintptr_t>(chunk_ptr)); // virtual address of segment start.
1679 JDWP::Write4BE(&p, 0); // offset of this piece (relative to the virtual address).
1680 // [u4]: length of piece, in allocation units
1681 // We won't know this until we're done, so save the offset and stuff in a dummy value.
1682 pieceLenField = p;
1683 JDWP::Write4BE(&p, 0x55555555);
1684 needHeader = false;
1685 }
1686
1687 void Flush() {
1688 // Patch the "length of piece" field.
1689 CHECK_LE(&buf[0], pieceLenField);
1690 CHECK_LE(pieceLenField, p);
1691 JDWP::Set4BE(pieceLenField, totalAllocationUnits);
1692
1693 Dbg::DdmSendChunk(type, p - &buf[0], &buf[0]);
1694 Reset();
1695 }
1696
Elliott Hughesa2155262011-11-16 16:26:58 -08001697 static void HeapChunkCallback(const void* chunk_ptr, size_t chunk_len, const void* user_ptr, size_t user_len, void* arg) {
1698 reinterpret_cast<HeapChunkContext*>(arg)->HeapChunkCallback(chunk_ptr, chunk_len, user_ptr, user_len);
1699 }
1700
Elliott Hughes6a5bd492011-10-28 14:33:57 -07001701 private:
Elliott Hughesa2155262011-11-16 16:26:58 -08001702 enum { ALLOCATION_UNIT_SIZE = 8 };
1703
Elliott Hughes6a5bd492011-10-28 14:33:57 -07001704 void Reset() {
1705 p = &buf[0];
1706 totalAllocationUnits = 0;
1707 needHeader = true;
1708 pieceLenField = NULL;
1709 }
1710
Elliott Hughesa2155262011-11-16 16:26:58 -08001711 void HeapChunkCallback(const void* chunk_ptr, size_t chunk_len, const void* user_ptr, size_t user_len) {
1712 CHECK_EQ((chunk_len & (ALLOCATION_UNIT_SIZE-1)), 0U);
Elliott Hughes6a5bd492011-10-28 14:33:57 -07001713
Elliott Hughesa2155262011-11-16 16:26:58 -08001714 /* Make sure there's enough room left in the buffer.
1715 * We need to use two bytes for every fractional 256
1716 * allocation units used by the chunk.
1717 */
1718 {
1719 size_t needed = (((chunk_len/ALLOCATION_UNIT_SIZE + 255) / 256) * 2);
1720 size_t bytesLeft = buf.size() - (size_t)(p - &buf[0]);
1721 if (bytesLeft < needed) {
1722 Flush();
1723 }
Elliott Hughes6a5bd492011-10-28 14:33:57 -07001724
Elliott Hughesa2155262011-11-16 16:26:58 -08001725 bytesLeft = buf.size() - (size_t)(p - &buf[0]);
1726 if (bytesLeft < needed) {
1727 LOG(WARNING) << "chunk is too big to transmit (chunk_len=" << chunk_len << ", " << needed << " bytes)";
1728 return;
1729 }
1730 }
1731
1732 // OLD-TODO: notice when there's a gap and start a new heap, or at least a new range.
1733 EnsureHeader(chunk_ptr);
1734
1735 // Determine the type of this chunk.
1736 // OLD-TODO: if context.merge, see if this chunk is different from the last chunk.
1737 // If it's the same, we should combine them.
1738 uint8_t state = ExamineObject(reinterpret_cast<const Object*>(user_ptr), (type == CHUNK_TYPE("NHSG")));
1739
1740 // Write out the chunk description.
1741 chunk_len /= ALLOCATION_UNIT_SIZE; // convert to allocation units
1742 totalAllocationUnits += chunk_len;
1743 while (chunk_len > 256) {
1744 *p++ = state | HPSG_PARTIAL;
1745 *p++ = 255; // length - 1
1746 chunk_len -= 256;
1747 }
1748 *p++ = state;
1749 *p++ = chunk_len - 1;
Elliott Hughes6a5bd492011-10-28 14:33:57 -07001750 }
1751
Elliott Hughesa2155262011-11-16 16:26:58 -08001752 uint8_t ExamineObject(const Object* o, bool is_native_heap) {
1753 if (o == NULL) {
1754 return HPSG_STATE(SOLIDITY_FREE, 0);
1755 }
Elliott Hughes6a5bd492011-10-28 14:33:57 -07001756
Elliott Hughesa2155262011-11-16 16:26:58 -08001757 // It's an allocated chunk. Figure out what it is.
Elliott Hughes6a5bd492011-10-28 14:33:57 -07001758
Elliott Hughesa2155262011-11-16 16:26:58 -08001759 // If we're looking at the native heap, we'll just return
1760 // (SOLIDITY_HARD, KIND_NATIVE) for all allocated chunks.
1761 if (is_native_heap || !Heap::IsLiveObjectLocked(o)) {
1762 return HPSG_STATE(SOLIDITY_HARD, KIND_NATIVE);
1763 }
1764
1765 Class* c = o->GetClass();
1766 if (c == NULL) {
1767 // The object was probably just created but hasn't been initialized yet.
1768 return HPSG_STATE(SOLIDITY_HARD, KIND_OBJECT);
1769 }
1770
1771 if (!Heap::IsHeapAddress(c)) {
1772 LOG(WARNING) << "invalid class for managed heap object: " << o << " " << c;
1773 return HPSG_STATE(SOLIDITY_HARD, KIND_UNKNOWN);
1774 }
1775
1776 if (c->IsClassClass()) {
1777 return HPSG_STATE(SOLIDITY_HARD, KIND_CLASS_OBJECT);
1778 }
1779
1780 if (c->IsArrayClass()) {
1781 if (o->IsObjectArray()) {
1782 return HPSG_STATE(SOLIDITY_HARD, KIND_ARRAY_4);
1783 }
1784 switch (c->GetComponentSize()) {
1785 case 1: return HPSG_STATE(SOLIDITY_HARD, KIND_ARRAY_1);
1786 case 2: return HPSG_STATE(SOLIDITY_HARD, KIND_ARRAY_2);
1787 case 4: return HPSG_STATE(SOLIDITY_HARD, KIND_ARRAY_4);
1788 case 8: return HPSG_STATE(SOLIDITY_HARD, KIND_ARRAY_8);
1789 }
1790 }
1791
Elliott Hughes6a5bd492011-10-28 14:33:57 -07001792 return HPSG_STATE(SOLIDITY_HARD, KIND_OBJECT);
1793 }
1794
Elliott Hughesa2155262011-11-16 16:26:58 -08001795 DISALLOW_COPY_AND_ASSIGN(HeapChunkContext);
1796};
Elliott Hughes6a5bd492011-10-28 14:33:57 -07001797
1798void Dbg::DdmSendHeapSegments(bool native) {
1799 Dbg::HpsgWhen when;
1800 Dbg::HpsgWhat what;
1801 if (!native) {
1802 when = gDdmHpsgWhen;
1803 what = gDdmHpsgWhat;
1804 } else {
1805 when = gDdmNhsgWhen;
1806 what = gDdmNhsgWhat;
1807 }
1808 if (when == HPSG_WHEN_NEVER) {
1809 return;
1810 }
1811
1812 // Figure out what kind of chunks we'll be sending.
1813 CHECK(what == HPSG_WHAT_MERGED_OBJECTS || what == HPSG_WHAT_DISTINCT_OBJECTS) << static_cast<int>(what);
1814
1815 // First, send a heap start chunk.
1816 uint8_t heap_id[4];
1817 JDWP::Set4BE(&heap_id[0], 1); // Heap id (bogus; we only have one heap).
1818 Dbg::DdmSendChunk(native ? CHUNK_TYPE("NHST") : CHUNK_TYPE("HPST"), sizeof(heap_id), heap_id);
1819
1820 // Send a series of heap segment chunks.
Elliott Hughesa2155262011-11-16 16:26:58 -08001821 HeapChunkContext context((what == HPSG_WHAT_MERGED_OBJECTS), native);
1822 if (native) {
1823 dlmalloc_walk_heap(HeapChunkContext::HeapChunkCallback, &context);
1824 } else {
1825 Heap::WalkHeap(HeapChunkContext::HeapChunkCallback, &context);
1826 }
Elliott Hughes6a5bd492011-10-28 14:33:57 -07001827
1828 // Finally, send a heap end chunk.
1829 Dbg::DdmSendChunk(native ? CHUNK_TYPE("NHEN") : CHUNK_TYPE("HPEN"), sizeof(heap_id), heap_id);
Elliott Hughes767a1472011-10-26 18:49:02 -07001830}
1831
Elliott Hughes545a0642011-11-08 19:10:03 -08001832void Dbg::SetAllocTrackingEnabled(bool enabled) {
1833 MutexLock mu(gAllocTrackerLock);
1834 if (enabled) {
1835 if (recent_allocation_records_ == NULL) {
1836 LOG(INFO) << "Enabling alloc tracker (" << kNumAllocRecords << " entries, "
1837 << kMaxAllocRecordStackDepth << " frames --> "
1838 << (sizeof(AllocRecord) * kNumAllocRecords) << " bytes)";
1839 gAllocRecordHead = gAllocRecordCount = 0;
1840 recent_allocation_records_ = new AllocRecord[kNumAllocRecords];
1841 CHECK(recent_allocation_records_ != NULL);
1842 }
1843 } else {
1844 delete[] recent_allocation_records_;
1845 recent_allocation_records_ = NULL;
1846 }
1847}
1848
1849struct AllocRecordStackVisitor : public Thread::StackVisitor {
1850 AllocRecordStackVisitor(AllocRecord* record) : record(record), depth(0) {
1851 }
1852
1853 virtual void VisitFrame(const Frame& f, uintptr_t pc) {
1854 if (depth >= kMaxAllocRecordStackDepth) {
1855 return;
1856 }
1857 Method* m = f.GetMethod();
1858 if (m == NULL || m->IsCalleeSaveMethod()) {
1859 return;
1860 }
1861 record->stack[depth].method = m;
1862 record->stack[depth].raw_pc = pc;
1863 ++depth;
1864 }
1865
1866 ~AllocRecordStackVisitor() {
1867 // Clear out any unused stack trace elements.
1868 for (; depth < kMaxAllocRecordStackDepth; ++depth) {
1869 record->stack[depth].method = NULL;
1870 record->stack[depth].raw_pc = 0;
1871 }
1872 }
1873
1874 AllocRecord* record;
1875 size_t depth;
1876};
1877
1878void Dbg::RecordAllocation(Class* type, size_t byte_count) {
1879 Thread* self = Thread::Current();
1880 CHECK(self != NULL);
1881
1882 MutexLock mu(gAllocTrackerLock);
1883 if (recent_allocation_records_ == NULL) {
1884 return;
1885 }
1886
1887 // Advance and clip.
1888 if (++gAllocRecordHead == kNumAllocRecords) {
1889 gAllocRecordHead = 0;
1890 }
1891
1892 // Fill in the basics.
1893 AllocRecord* record = &recent_allocation_records_[gAllocRecordHead];
1894 record->type = type;
1895 record->byte_count = byte_count;
1896 record->thin_lock_id = self->GetThinLockId();
1897
1898 // Fill in the stack trace.
1899 AllocRecordStackVisitor visitor(record);
1900 self->WalkStack(&visitor);
1901
1902 if (gAllocRecordCount < kNumAllocRecords) {
1903 ++gAllocRecordCount;
1904 }
1905}
1906
1907/*
1908 * Return the index of the head element.
1909 *
1910 * We point at the most-recently-written record, so if allocRecordCount is 1
1911 * we want to use the current element. Take "head+1" and subtract count
1912 * from it.
1913 *
1914 * We need to handle underflow in our circular buffer, so we add
1915 * kNumAllocRecords and then mask it back down.
1916 */
1917inline static int headIndex() {
1918 return (gAllocRecordHead+1 + kNumAllocRecords - gAllocRecordCount) & (kNumAllocRecords-1);
1919}
1920
1921void Dbg::DumpRecentAllocations() {
1922 MutexLock mu(gAllocTrackerLock);
1923 if (recent_allocation_records_ == NULL) {
1924 LOG(INFO) << "Not recording tracked allocations";
1925 return;
1926 }
1927
1928 // "i" is the head of the list. We want to start at the end of the
1929 // list and move forward to the tail.
1930 size_t i = headIndex();
1931 size_t count = gAllocRecordCount;
1932
1933 LOG(INFO) << "Tracked allocations, (head=" << gAllocRecordHead << " count=" << count << ")";
1934 while (count--) {
1935 AllocRecord* record = &recent_allocation_records_[i];
1936
1937 LOG(INFO) << StringPrintf(" T=%-2d %6d ", record->thin_lock_id, record->byte_count)
1938 << PrettyClass(record->type);
1939
1940 for (size_t stack_frame = 0; stack_frame < kMaxAllocRecordStackDepth; ++stack_frame) {
1941 const Method* m = record->stack[stack_frame].method;
1942 if (m == NULL) {
1943 break;
1944 }
1945 LOG(INFO) << " " << PrettyMethod(m) << " line " << record->stack[stack_frame].LineNumber();
1946 }
1947
1948 // pause periodically to help logcat catch up
1949 if ((count % 5) == 0) {
1950 usleep(40000);
1951 }
1952
1953 i = (i + 1) & (kNumAllocRecords-1);
1954 }
1955}
1956
1957class StringTable {
1958 public:
1959 StringTable() {
1960 }
1961
1962 void Add(const String* s) {
1963 table_.insert(s);
1964 }
1965
1966 size_t IndexOf(const String* s) {
1967 return std::distance(table_.begin(), table_.find(s));
1968 }
1969
1970 size_t Size() {
1971 return table_.size();
1972 }
1973
1974 void WriteTo(std::vector<uint8_t>& bytes) {
1975 typedef std::set<const String*>::const_iterator It; // TODO: C++0x auto
1976 for (It it = table_.begin(); it != table_.end(); ++it) {
1977 const String* s = *it;
1978 JDWP::AppendUtf16BE(bytes, s->GetCharArray()->GetData(), s->GetLength());
1979 }
1980 }
1981
1982 private:
1983 std::set<const String*> table_;
1984 DISALLOW_COPY_AND_ASSIGN(StringTable);
1985};
1986
1987/*
1988 * The data we send to DDMS contains everything we have recorded.
1989 *
1990 * Message header (all values big-endian):
1991 * (1b) message header len (to allow future expansion); includes itself
1992 * (1b) entry header len
1993 * (1b) stack frame len
1994 * (2b) number of entries
1995 * (4b) offset to string table from start of message
1996 * (2b) number of class name strings
1997 * (2b) number of method name strings
1998 * (2b) number of source file name strings
1999 * For each entry:
2000 * (4b) total allocation size
2001 * (2b) threadId
2002 * (2b) allocated object's class name index
2003 * (1b) stack depth
2004 * For each stack frame:
2005 * (2b) method's class name
2006 * (2b) method name
2007 * (2b) method source file
2008 * (2b) line number, clipped to 32767; -2 if native; -1 if no source
2009 * (xb) class name strings
2010 * (xb) method name strings
2011 * (xb) source file strings
2012 *
2013 * As with other DDM traffic, strings are sent as a 4-byte length
2014 * followed by UTF-16 data.
2015 *
2016 * We send up 16-bit unsigned indexes into string tables. In theory there
2017 * can be (kMaxAllocRecordStackDepth * kNumAllocRecords) unique strings in
2018 * each table, but in practice there should be far fewer.
2019 *
2020 * The chief reason for using a string table here is to keep the size of
2021 * the DDMS message to a minimum. This is partly to make the protocol
2022 * efficient, but also because we have to form the whole thing up all at
2023 * once in a memory buffer.
2024 *
2025 * We use separate string tables for class names, method names, and source
2026 * files to keep the indexes small. There will generally be no overlap
2027 * between the contents of these tables.
2028 */
2029jbyteArray Dbg::GetRecentAllocations() {
2030 if (false) {
2031 DumpRecentAllocations();
2032 }
2033
2034 MutexLock mu(gAllocTrackerLock);
2035
2036 /*
2037 * Part 1: generate string tables.
2038 */
2039 StringTable class_names;
2040 StringTable method_names;
2041 StringTable filenames;
2042
2043 int count = gAllocRecordCount;
2044 int idx = headIndex();
2045 while (count--) {
2046 AllocRecord* record = &recent_allocation_records_[idx];
2047
2048 class_names.Add(record->type->GetDescriptor());
2049
2050 for (size_t i = 0; i < kMaxAllocRecordStackDepth; i++) {
2051 const Method* m = record->stack[i].method;
2052 if (m != NULL) {
2053 class_names.Add(m->GetDeclaringClass()->GetDescriptor());
2054 method_names.Add(m->GetName());
2055 filenames.Add(m->GetDeclaringClass()->GetSourceFile());
2056 }
2057 }
2058
2059 idx = (idx + 1) & (kNumAllocRecords-1);
2060 }
2061
2062 LOG(INFO) << "allocation records: " << gAllocRecordCount;
2063
2064 /*
2065 * Part 2: allocate a buffer and generate the output.
2066 */
2067 std::vector<uint8_t> bytes;
2068
2069 // (1b) message header len (to allow future expansion); includes itself
2070 // (1b) entry header len
2071 // (1b) stack frame len
2072 const int kMessageHeaderLen = 15;
2073 const int kEntryHeaderLen = 9;
2074 const int kStackFrameLen = 8;
2075 JDWP::Append1BE(bytes, kMessageHeaderLen);
2076 JDWP::Append1BE(bytes, kEntryHeaderLen);
2077 JDWP::Append1BE(bytes, kStackFrameLen);
2078
2079 // (2b) number of entries
2080 // (4b) offset to string table from start of message
2081 // (2b) number of class name strings
2082 // (2b) number of method name strings
2083 // (2b) number of source file name strings
2084 JDWP::Append2BE(bytes, gAllocRecordCount);
2085 size_t string_table_offset = bytes.size();
2086 JDWP::Append4BE(bytes, 0); // We'll patch this later...
2087 JDWP::Append2BE(bytes, class_names.Size());
2088 JDWP::Append2BE(bytes, method_names.Size());
2089 JDWP::Append2BE(bytes, filenames.Size());
2090
2091 count = gAllocRecordCount;
2092 idx = headIndex();
2093 while (count--) {
2094 // For each entry:
2095 // (4b) total allocation size
2096 // (2b) thread id
2097 // (2b) allocated object's class name index
2098 // (1b) stack depth
2099 AllocRecord* record = &recent_allocation_records_[idx];
2100 size_t stack_depth = record->GetDepth();
2101 JDWP::Append4BE(bytes, record->byte_count);
2102 JDWP::Append2BE(bytes, record->thin_lock_id);
2103 JDWP::Append2BE(bytes, class_names.IndexOf(record->type->GetDescriptor()));
2104 JDWP::Append1BE(bytes, stack_depth);
2105
2106 for (size_t stack_frame = 0; stack_frame < stack_depth; ++stack_frame) {
2107 // For each stack frame:
2108 // (2b) method's class name
2109 // (2b) method name
2110 // (2b) method source file
2111 // (2b) line number, clipped to 32767; -2 if native; -1 if no source
2112 const Method* m = record->stack[stack_frame].method;
2113 JDWP::Append2BE(bytes, class_names.IndexOf(m->GetDeclaringClass()->GetDescriptor()));
2114 JDWP::Append2BE(bytes, method_names.IndexOf(m->GetName()));
2115 JDWP::Append2BE(bytes, filenames.IndexOf(m->GetDeclaringClass()->GetSourceFile()));
2116 JDWP::Append2BE(bytes, record->stack[stack_frame].LineNumber());
2117 }
2118
2119 idx = (idx + 1) & (kNumAllocRecords-1);
2120 }
2121
2122 // (xb) class name strings
2123 // (xb) method name strings
2124 // (xb) source file strings
2125 JDWP::Set4BE(&bytes[string_table_offset], bytes.size());
2126 class_names.WriteTo(bytes);
2127 method_names.WriteTo(bytes);
2128 filenames.WriteTo(bytes);
2129
2130 JNIEnv* env = Thread::Current()->GetJniEnv();
2131 jbyteArray result = env->NewByteArray(bytes.size());
2132 if (result != NULL) {
2133 env->SetByteArrayRegion(result, 0, bytes.size(), reinterpret_cast<const jbyte*>(&bytes[0]));
2134 }
2135 return result;
2136}
2137
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002138} // namespace art