blob: 7128fdc0a4928f5baac9657e107496ff1b49cf94 [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) {
326 LOG(WARNING) << "debugger thread failed to initialize";
Elliott Hughes475fc232011-10-25 15:00:35 -0700327 return;
Elliott Hughesd1cc8362011-10-24 16:58:50 -0700328 }
329
330 // If a debugger has already attached, send the "welcome" message.
331 // This may cause us to suspend all threads.
Elliott Hughes376a7a02011-10-24 18:35:55 -0700332 if (gJdwpState->IsActive()) {
Elliott Hughesa2155262011-11-16 16:26:58 -0800333 //ScopedThreadStateChange tsc(Thread::Current(), Thread::kRunnable);
Elliott Hughes376a7a02011-10-24 18:35:55 -0700334 if (!gJdwpState->PostVMStart()) {
Elliott Hughesd1cc8362011-10-24 16:58:50 -0700335 LOG(WARNING) << "failed to post 'start' message to debugger";
336 }
337 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700338}
339
Elliott Hughesd1cc8362011-10-24 16:58:50 -0700340void Dbg::StopJdwp() {
Elliott Hughes376a7a02011-10-24 18:35:55 -0700341 delete gJdwpState;
Elliott Hughes475fc232011-10-25 15:00:35 -0700342 delete gRegistry;
343 gRegistry = NULL;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700344}
345
Elliott Hughes767a1472011-10-26 18:49:02 -0700346void Dbg::GcDidFinish() {
347 if (gDdmHpifWhen != HPIF_WHEN_NEVER) {
348 LOG(DEBUG) << "Sending VM heap info to DDM";
Elliott Hughes7162ad92011-10-27 14:08:42 -0700349 DdmSendHeapInfo(gDdmHpifWhen);
Elliott Hughes767a1472011-10-26 18:49:02 -0700350 }
351 if (gDdmHpsgWhen != HPSG_WHEN_NEVER) {
352 LOG(DEBUG) << "Dumping VM heap to DDM";
Elliott Hughes6a5bd492011-10-28 14:33:57 -0700353 DdmSendHeapSegments(false);
Elliott Hughes767a1472011-10-26 18:49:02 -0700354 }
355 if (gDdmNhsgWhen != HPSG_WHEN_NEVER) {
356 LOG(DEBUG) << "Dumping native heap to DDM";
Elliott Hughes6a5bd492011-10-28 14:33:57 -0700357 DdmSendHeapSegments(true);
Elliott Hughes767a1472011-10-26 18:49:02 -0700358 }
359}
360
Elliott Hughes4ffd3132011-10-24 12:06:42 -0700361void Dbg::SetJdwpAllowed(bool allowed) {
362 gJdwpAllowed = allowed;
363}
364
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700365DebugInvokeReq* Dbg::GetInvokeReq() {
Elliott Hughes475fc232011-10-25 15:00:35 -0700366 return Thread::Current()->GetInvokeReq();
367}
368
369Thread* Dbg::GetDebugThread() {
370 return (gJdwpState != NULL) ? gJdwpState->GetDebugThread() : NULL;
371}
372
373void Dbg::ClearWaitForEventThread() {
374 gJdwpState->ClearWaitForEventThread();
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700375}
376
377void Dbg::Connected() {
Elliott Hughes3bb81562011-10-21 18:52:59 -0700378 CHECK(!gDebuggerConnected);
379 LOG(VERBOSE) << "JDWP has attached";
380 gDebuggerConnected = true;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700381}
382
Elliott Hughesa2155262011-11-16 16:26:58 -0800383void Dbg::GoActive() {
384 // Enable all debugging features, including scans for breakpoints.
385 // This is a no-op if we're already active.
386 // Only called from the JDWP handler thread.
387 if (gDebuggerActive) {
388 return;
389 }
390
391 LOG(INFO) << "Debugger is active";
392
393 // TODO: CHECK we don't have any outstanding breakpoints.
394
395 gDebuggerActive = true;
396
397 //dvmEnableAllSubMode(kSubModeDebuggerActive);
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700398}
399
400void Dbg::Disconnected() {
Elliott Hughes234ab152011-10-26 14:02:26 -0700401 CHECK(gDebuggerConnected);
402
403 gDebuggerActive = false;
404
405 //dvmDisableAllSubMode(kSubModeDebuggerActive);
406
407 gRegistry->Clear();
408 gDebuggerConnected = false;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700409}
410
411bool Dbg::IsDebuggerConnected() {
Elliott Hughes3bb81562011-10-21 18:52:59 -0700412 return gDebuggerActive;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700413}
414
415bool Dbg::IsDebuggingEnabled() {
Elliott Hughes3bb81562011-10-21 18:52:59 -0700416 return gJdwpConfigured;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700417}
418
419int64_t Dbg::LastDebuggerActivity() {
420 UNIMPLEMENTED(WARNING);
421 return -1;
422}
423
424int Dbg::ThreadRunning() {
Elliott Hughesd1cc8362011-10-24 16:58:50 -0700425 return static_cast<int>(Thread::Current()->SetState(Thread::kRunnable));
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700426}
427
428int Dbg::ThreadWaiting() {
Elliott Hughesd1cc8362011-10-24 16:58:50 -0700429 return static_cast<int>(Thread::Current()->SetState(Thread::kVmWait));
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700430}
431
Elliott Hughes6ba581a2011-10-25 11:45:35 -0700432int Dbg::ThreadContinuing(int new_state) {
433 return static_cast<int>(Thread::Current()->SetState(static_cast<Thread::State>(new_state)));
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700434}
435
436void Dbg::UndoDebuggerSuspensions() {
Elliott Hughes234ab152011-10-26 14:02:26 -0700437 Runtime::Current()->GetThreadList()->UndoDebuggerSuspensions();
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700438}
439
440void Dbg::Exit(int status) {
441 UNIMPLEMENTED(FATAL);
442}
443
Elliott Hughesbfe487b2011-10-26 15:48:55 -0700444void Dbg::VisitRoots(Heap::RootVisitor* visitor, void* arg) {
445 if (gRegistry != NULL) {
446 gRegistry->VisitRoots(visitor, arg);
447 }
448}
449
Elliott Hughesa2155262011-11-16 16:26:58 -0800450std::string Dbg::GetClassDescriptor(JDWP::RefTypeId classId) {
451 Class* c = gRegistry->Get<Class*>(classId);
452 return c->GetDescriptor()->ToModifiedUtf8();
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700453}
454
455JDWP::ObjectId Dbg::GetClassObject(JDWP::RefTypeId id) {
456 UNIMPLEMENTED(FATAL);
457 return 0;
458}
459
460JDWP::RefTypeId Dbg::GetSuperclass(JDWP::RefTypeId id) {
Elliott Hughesa2e54f62011-11-17 13:01:30 -0800461 Class* c = gRegistry->Get<Class*>(id);
462 return gRegistry->Add(c->GetSuperClass());
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700463}
464
465JDWP::ObjectId Dbg::GetClassLoader(JDWP::RefTypeId id) {
466 UNIMPLEMENTED(FATAL);
467 return 0;
468}
469
470uint32_t Dbg::GetAccessFlags(JDWP::RefTypeId id) {
471 UNIMPLEMENTED(FATAL);
472 return 0;
473}
474
475bool Dbg::IsInterface(JDWP::RefTypeId id) {
476 UNIMPLEMENTED(FATAL);
477 return false;
478}
479
Elliott Hughesa2155262011-11-16 16:26:58 -0800480void Dbg::GetClassList(uint32_t* pClassCount, JDWP::RefTypeId** pClasses) {
481 // Get the complete list of reference classes (i.e. all classes except
482 // the primitive types).
483 // Returns a newly-allocated buffer full of RefTypeId values.
484 struct ClassListCreator {
485 static bool Visit(Class* c, void* arg) {
486 return reinterpret_cast<ClassListCreator*>(arg)->Visit(c);
487 }
488
489 bool Visit(Class* c) {
490 if (!c->IsPrimitive()) {
491 classes.push_back(static_cast<JDWP::RefTypeId>(gRegistry->Add(c)));
492 }
493 return true;
494 }
495
496 std::vector<JDWP::RefTypeId> classes;
497 };
498
499 ClassListCreator clc;
500 Runtime::Current()->GetClassLinker()->VisitClasses(ClassListCreator::Visit, &clc);
501 *pClassCount = clc.classes.size();
502 *pClasses = new JDWP::RefTypeId[clc.classes.size()];
503 for (size_t i = 0; i < clc.classes.size(); ++i) {
504 (*pClasses)[i] = clc.classes[i];
505 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700506}
507
508void Dbg::GetVisibleClassList(JDWP::ObjectId classLoaderId, uint32_t* pNumClasses, JDWP::RefTypeId** pClassRefBuf) {
509 UNIMPLEMENTED(FATAL);
510}
511
Elliott Hughesa2155262011-11-16 16:26:58 -0800512void Dbg::GetClassInfo(JDWP::RefTypeId classId, uint8_t* pTypeTag, uint32_t* pStatus, std::string* pDescriptor) {
513 Class* c = gRegistry->Get<Class*>(classId);
514 if (c->IsArrayClass()) {
515 *pStatus = JDWP::CS_VERIFIED | JDWP::CS_PREPARED;
516 *pTypeTag = JDWP::TT_ARRAY;
517 } else {
518 if (c->IsErroneous()) {
519 *pStatus = JDWP::CS_ERROR;
520 } else {
521 *pStatus = JDWP::CS_VERIFIED | JDWP::CS_PREPARED | JDWP::CS_INITIALIZED;
522 }
523 *pTypeTag = c->IsInterface() ? JDWP::TT_INTERFACE : JDWP::TT_CLASS;
524 }
525
526 if (pDescriptor != NULL) {
527 *pDescriptor = c->GetDescriptor()->ToModifiedUtf8();
528 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700529}
530
531bool Dbg::FindLoadedClassBySignature(const char* classDescriptor, JDWP::RefTypeId* pRefTypeId) {
532 UNIMPLEMENTED(FATAL);
533 return false;
534}
535
536void Dbg::GetObjectType(JDWP::ObjectId objectId, uint8_t* pRefTypeTag, JDWP::RefTypeId* pRefTypeId) {
Elliott Hughes499c5132011-11-17 14:55:11 -0800537 Object* o = gRegistry->Get<Object*>(objectId);
538 if (o->GetClass()->IsArrayClass()) {
539 *pRefTypeTag = JDWP::TT_ARRAY;
540 } else if (o->GetClass()->IsInterface()) {
541 *pRefTypeTag = JDWP::TT_INTERFACE;
542 } else {
543 *pRefTypeTag = JDWP::TT_CLASS;
544 }
545 *pRefTypeId = gRegistry->Add(o->GetClass());
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700546}
547
548uint8_t Dbg::GetClassObjectType(JDWP::RefTypeId refTypeId) {
549 UNIMPLEMENTED(FATAL);
550 return 0;
551}
552
Elliott Hughesa2e54f62011-11-17 13:01:30 -0800553std::string Dbg::GetSignature(JDWP::RefTypeId refTypeId) {
554 Class* c = gRegistry->Get<Class*>(refTypeId);
555 CHECK(c != NULL);
556 return c->GetDescriptor()->ToModifiedUtf8();
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700557}
558
Elliott Hughes03181a82011-11-17 17:22:21 -0800559bool Dbg::GetSourceFile(JDWP::RefTypeId refTypeId, std::string& result) {
560 Class* c = gRegistry->Get<Class*>(refTypeId);
561 CHECK(c != NULL);
562
563 String* source_file = c->GetSourceFile();
564 if (source_file == NULL) {
565 return false;
566 }
567 result = source_file->ToModifiedUtf8();
568 return true;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700569}
570
571const char* Dbg::GetObjectTypeName(JDWP::ObjectId objectId) {
572 UNIMPLEMENTED(FATAL);
573 return NULL;
574}
575
576uint8_t Dbg::GetObjectTag(JDWP::ObjectId objectId) {
Elliott Hughes24437992011-11-30 14:49:33 -0800577 Object* o = gRegistry->Get<Object*>(objectId);
578 return TagFromObject(o);
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700579}
580
Elliott Hughesdbb40792011-11-18 17:05:22 -0800581size_t Dbg::GetTagWidth(int tag) {
582 switch (tag) {
583 case JDWP::JT_VOID:
584 return 0;
585 case JDWP::JT_BYTE:
586 case JDWP::JT_BOOLEAN:
587 return 1;
588 case JDWP::JT_CHAR:
589 case JDWP::JT_SHORT:
590 return 2;
591 case JDWP::JT_FLOAT:
592 case JDWP::JT_INT:
593 return 4;
594 case JDWP::JT_ARRAY:
595 case JDWP::JT_OBJECT:
596 case JDWP::JT_STRING:
597 case JDWP::JT_THREAD:
598 case JDWP::JT_THREAD_GROUP:
599 case JDWP::JT_CLASS_LOADER:
600 case JDWP::JT_CLASS_OBJECT:
601 return sizeof(JDWP::ObjectId);
602 case JDWP::JT_DOUBLE:
603 case JDWP::JT_LONG:
604 return 8;
605 default:
606 LOG(FATAL) << "unknown tag " << tag;
607 return -1;
608 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700609}
610
611int Dbg::GetArrayLength(JDWP::ObjectId arrayId) {
Elliott Hughes68fdbd02011-11-29 19:22:47 -0800612 Object* o = gRegistry->Get<Object*>(arrayId);
613 Array* a = o->AsArray();
614 return a->GetLength();
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700615}
616
617uint8_t Dbg::GetArrayElementTag(JDWP::ObjectId arrayId) {
Elliott Hughes24437992011-11-30 14:49:33 -0800618 Object* o = gRegistry->Get<Object*>(arrayId);
619 Array* a = o->AsArray();
620 std::string descriptor(a->GetClass()->GetDescriptor()->ToModifiedUtf8());
621 JDWP::JdwpTag tag = BasicTagFromDescriptor(descriptor.c_str() + 1);
622 if (!IsPrimitiveTag(tag)) {
623 tag = TagFromClass(a->GetClass()->GetComponentType());
624 }
625 return tag;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700626}
627
Elliott Hughes24437992011-11-30 14:49:33 -0800628bool Dbg::OutputArray(JDWP::ObjectId arrayId, int offset, int count, JDWP::ExpandBuf* pReply) {
629 Object* o = gRegistry->Get<Object*>(arrayId);
630 Array* a = o->AsArray();
631
632 if (offset < 0 || count < 0 || offset > a->GetLength() || a->GetLength() - offset < count) {
633 LOG(WARNING) << __FUNCTION__ << " access out of bounds: offset=" << offset << "; count=" << count;
634 return false;
635 }
636
637 std::string descriptor(a->GetClass()->GetDescriptor()->ToModifiedUtf8());
638 JDWP::JdwpTag tag = BasicTagFromDescriptor(descriptor.c_str() + 1);
639
640 if (IsPrimitiveTag(tag)) {
641 size_t width = GetTagWidth(tag);
642 const uint8_t* src = reinterpret_cast<uint8_t*>(a->GetRawData());
643 uint8_t* dst = expandBufAddSpace(pReply, count * width);
644 if (width == 8) {
645 const uint64_t* src8 = reinterpret_cast<const uint64_t*>(src);
646 for (int i = 0; i < count; ++i) JDWP::Write8BE(&dst, src8[offset + i]);
647 } else if (width == 4) {
648 const uint32_t* src4 = reinterpret_cast<const uint32_t*>(src);
649 for (int i = 0; i < count; ++i) JDWP::Write4BE(&dst, src4[offset + i]);
650 } else if (width == 2) {
651 const uint16_t* src2 = reinterpret_cast<const uint16_t*>(src);
652 for (int i = 0; i < count; ++i) JDWP::Write2BE(&dst, src2[offset + i]);
653 } else {
654 memcpy(dst, &src[offset * width], count * width);
655 }
656 } else {
657 ObjectArray<Object>* oa = a->AsObjectArray<Object>();
658 for (int i = 0; i < count; ++i) {
659 Object* element = oa->Get(i);
660 JDWP::JdwpTag specific_tag = (element != NULL) ? TagFromObject(element) : tag;
661 expandBufAdd1(pReply, specific_tag);
662 expandBufAddObjectId(pReply, gRegistry->Add(element));
663 }
664 }
665
666 return true;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700667}
668
669bool Dbg::SetArrayElements(JDWP::ObjectId arrayId, int firstIndex, int count, const uint8_t* buf) {
670 UNIMPLEMENTED(FATAL);
671 return false;
672}
673
674JDWP::ObjectId Dbg::CreateString(const char* str) {
675 UNIMPLEMENTED(FATAL);
676 return 0;
677}
678
679JDWP::ObjectId Dbg::CreateObject(JDWP::RefTypeId classId) {
680 UNIMPLEMENTED(FATAL);
681 return 0;
682}
683
684JDWP::ObjectId Dbg::CreateArrayObject(JDWP::RefTypeId arrayTypeId, uint32_t length) {
685 UNIMPLEMENTED(FATAL);
686 return 0;
687}
688
689bool Dbg::MatchType(JDWP::RefTypeId instClassId, JDWP::RefTypeId classId) {
690 UNIMPLEMENTED(FATAL);
691 return false;
692}
693
Elliott Hughes03181a82011-11-17 17:22:21 -0800694JDWP::FieldId ToFieldId(Field* f) {
695#ifdef MOVING_GARBAGE_COLLECTOR
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700696 UNIMPLEMENTED(FATAL);
Elliott Hughes03181a82011-11-17 17:22:21 -0800697#else
698 return static_cast<JDWP::FieldId>(reinterpret_cast<uintptr_t>(f));
699#endif
700}
701
702JDWP::MethodId ToMethodId(Method* m) {
703#ifdef MOVING_GARBAGE_COLLECTOR
704 UNIMPLEMENTED(FATAL);
705#else
706 return static_cast<JDWP::MethodId>(reinterpret_cast<uintptr_t>(m));
707#endif
708}
709
710Method* FromMethodId(JDWP::MethodId mid) {
711#ifdef MOVING_GARBAGE_COLLECTOR
712 UNIMPLEMENTED(FATAL);
713#else
714 return reinterpret_cast<Method*>(static_cast<uintptr_t>(mid));
715#endif
716}
717
718std::string Dbg::GetMethodName(JDWP::RefTypeId refTypeId, JDWP::MethodId methodId) {
719 return FromMethodId(methodId)->GetName()->ToModifiedUtf8();
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700720}
721
Elliott Hughesa2e54f62011-11-17 13:01:30 -0800722/*
723 * Augment the access flags for synthetic methods and fields by setting
724 * the (as described by the spec) "0xf0000000 bit". Also, strip out any
725 * flags not specified by the Java programming language.
726 */
727static uint32_t MangleAccessFlags(uint32_t accessFlags) {
728 accessFlags &= kAccJavaFlagsMask;
729 if ((accessFlags & kAccSynthetic) != 0) {
730 accessFlags |= 0xf0000000;
731 }
732 return accessFlags;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700733}
734
Elliott Hughesdbb40792011-11-18 17:05:22 -0800735static const uint16_t kEclipseWorkaroundSlot = 1000;
736
737/*
738 * Eclipse appears to expect that the "this" reference is in slot zero.
739 * If it's not, the "variables" display will show two copies of "this",
740 * possibly because it gets "this" from SF.ThisObject and then displays
741 * all locals with nonzero slot numbers.
742 *
743 * So, we remap the item in slot 0 to 1000, and remap "this" to zero. On
744 * SF.GetValues / SF.SetValues we map them back.
745 */
746static uint16_t MangleSlot(uint16_t slot, const char* name) {
747 uint16_t newSlot = slot;
748 if (strcmp(name, "this") == 0) {
749 newSlot = 0;
750 } else if (slot == 0) {
751 newSlot = kEclipseWorkaroundSlot;
752 }
753 return newSlot;
754}
755
756/*
757 * Reverse Eclipse hack.
758 */
Elliott Hughes68fdbd02011-11-29 19:22:47 -0800759static uint16_t DemangleSlot(uint16_t slot, Frame& f) {
Elliott Hughesdbb40792011-11-18 17:05:22 -0800760 if (slot == kEclipseWorkaroundSlot) {
Elliott Hughes68fdbd02011-11-29 19:22:47 -0800761 return 0;
Elliott Hughesdbb40792011-11-18 17:05:22 -0800762 } else if (slot == 0) {
Elliott Hughesdbb40792011-11-18 17:05:22 -0800763 Method* m = f.GetMethod();
Elliott Hughes68fdbd02011-11-29 19:22:47 -0800764 return m->NumRegisters() - m->NumIns();
Elliott Hughesdbb40792011-11-18 17:05:22 -0800765 }
Elliott Hughes68fdbd02011-11-29 19:22:47 -0800766 return slot;
Elliott Hughesdbb40792011-11-18 17:05:22 -0800767}
768
Elliott Hughesa2e54f62011-11-17 13:01:30 -0800769void Dbg::OutputDeclaredFields(JDWP::RefTypeId refTypeId, bool withGeneric, JDWP::ExpandBuf* pReply) {
770 Class* c = gRegistry->Get<Class*>(refTypeId);
771 CHECK(c != NULL);
772
773 size_t instance_field_count = c->NumInstanceFields();
774 size_t static_field_count = c->NumStaticFields();
775
776 expandBufAdd4BE(pReply, instance_field_count + static_field_count);
777
778 for (size_t i = 0; i < instance_field_count + static_field_count; ++i) {
779 Field* f = (i < instance_field_count) ? c->GetInstanceField(i) : c->GetStaticField(i - instance_field_count);
780
781 expandBufAddFieldId(pReply, ToFieldId(f));
782 expandBufAddUtf8String(pReply, f->GetName()->ToModifiedUtf8().c_str());
783 expandBufAddUtf8String(pReply, f->GetTypeDescriptor());
784 if (withGeneric) {
785 static const char genericSignature[1] = "";
786 expandBufAddUtf8String(pReply, genericSignature);
787 }
788 expandBufAdd4BE(pReply, MangleAccessFlags(f->GetAccessFlags()));
789 }
790}
791
792void Dbg::OutputDeclaredMethods(JDWP::RefTypeId refTypeId, bool withGeneric, JDWP::ExpandBuf* pReply) {
793 Class* c = gRegistry->Get<Class*>(refTypeId);
794 CHECK(c != NULL);
795
796 size_t direct_method_count = c->NumDirectMethods();
797 size_t virtual_method_count = c->NumVirtualMethods();
798
799 expandBufAdd4BE(pReply, direct_method_count + virtual_method_count);
800
801 for (size_t i = 0; i < direct_method_count + virtual_method_count; ++i) {
802 Method* m = (i < direct_method_count) ? c->GetDirectMethod(i) : c->GetVirtualMethod(i - direct_method_count);
803
804 expandBufAddMethodId(pReply, ToMethodId(m));
805 expandBufAddUtf8String(pReply, m->GetName()->ToModifiedUtf8().c_str());
806 expandBufAddUtf8String(pReply, m->GetSignature()->ToModifiedUtf8().c_str());
807 if (withGeneric) {
808 static const char genericSignature[1] = "";
809 expandBufAddUtf8String(pReply, genericSignature);
810 }
811 expandBufAdd4BE(pReply, MangleAccessFlags(m->GetAccessFlags()));
812 }
813}
814
815void Dbg::OutputDeclaredInterfaces(JDWP::RefTypeId refTypeId, JDWP::ExpandBuf* pReply) {
816 Class* c = gRegistry->Get<Class*>(refTypeId);
817 CHECK(c != NULL);
818 size_t interface_count = c->NumInterfaces();
819 expandBufAdd4BE(pReply, interface_count);
820 for (size_t i = 0; i < interface_count; ++i) {
821 expandBufAddRefTypeId(pReply, gRegistry->Add(c->GetInterface(i)));
822 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700823}
824
825void Dbg::OutputLineTable(JDWP::RefTypeId refTypeId, JDWP::MethodId methodId, JDWP::ExpandBuf* pReply) {
Elliott Hughes03181a82011-11-17 17:22:21 -0800826 struct DebugCallbackContext {
827 int numItems;
828 JDWP::ExpandBuf* pReply;
829
830 static bool Callback(void* context, uint32_t address, uint32_t lineNum) {
831 DebugCallbackContext* pContext = reinterpret_cast<DebugCallbackContext*>(context);
832 expandBufAdd8BE(pContext->pReply, address);
833 expandBufAdd4BE(pContext->pReply, lineNum);
834 pContext->numItems++;
835 return true;
836 }
837 };
838
839 Method* m = FromMethodId(methodId);
840 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
841 const DexFile& dex_file = class_linker->FindDexFile(m->GetDeclaringClass()->GetDexCache());
842 const DexFile::CodeItem* code_item = dex_file.GetCodeItem(m->GetCodeItemOffset());
843
844 uint64_t start, end;
845 if (m->IsNative()) {
846 start = -1;
847 end = -1;
848 } else {
849 start = 0;
850 end = code_item->insns_size_in_code_units_; // TODO: what are the units supposed to be? *2?
851 }
852
853 expandBufAdd8BE(pReply, start);
854 expandBufAdd8BE(pReply, end);
855
856 // Add numLines later
857 size_t numLinesOffset = expandBufGetLength(pReply);
858 expandBufAdd4BE(pReply, 0);
859
860 DebugCallbackContext context;
861 context.numItems = 0;
862 context.pReply = pReply;
863
864 dex_file.DecodeDebugInfo(code_item, m, DebugCallbackContext::Callback, NULL, &context);
865
866 JDWP::Set4BE(expandBufGetBuffer(pReply) + numLinesOffset, context.numItems);
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700867}
868
Elliott Hughesdbb40792011-11-18 17:05:22 -0800869void Dbg::OutputVariableTable(JDWP::RefTypeId refTypeId, JDWP::MethodId methodId, bool withGeneric, JDWP::ExpandBuf* pReply) {
870 struct DebugCallbackContext {
871 int numItems;
872 JDWP::ExpandBuf* pReply;
873 bool withGeneric;
874
875 static void Callback(void* context, uint16_t slot, uint32_t startAddress, uint32_t endAddress, const char *name, const char *descriptor, const char *signature) {
876 DebugCallbackContext* pContext = reinterpret_cast<DebugCallbackContext*>(context);
877
Elliott Hughesdbb40792011-11-18 17:05:22 -0800878 LOG(VERBOSE) << StringPrintf(" %2d: %d(%d) '%s' '%s' '%s' slot=%d", pContext->numItems, startAddress, endAddress - startAddress, name, descriptor, signature, slot);
879
Elliott Hughes68fdbd02011-11-29 19:22:47 -0800880 slot = MangleSlot(slot, name);
881
Elliott Hughesdbb40792011-11-18 17:05:22 -0800882 expandBufAdd8BE(pContext->pReply, startAddress);
883 expandBufAddUtf8String(pContext->pReply, name);
884 expandBufAddUtf8String(pContext->pReply, descriptor);
885 if (pContext->withGeneric) {
886 expandBufAddUtf8String(pContext->pReply, signature);
887 }
888 expandBufAdd4BE(pContext->pReply, endAddress - startAddress);
889 expandBufAdd4BE(pContext->pReply, slot);
890
891 pContext->numItems++;
892 }
893 };
894
895 Method* m = FromMethodId(methodId);
896 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
897 const DexFile& dex_file = class_linker->FindDexFile(m->GetDeclaringClass()->GetDexCache());
898 const DexFile::CodeItem* code_item = dex_file.GetCodeItem(m->GetCodeItemOffset());
899
900 expandBufAdd4BE(pReply, m->NumIns());
901
902 // Add numLocals later
903 size_t numLocalsOffset = expandBufGetLength(pReply);
904 expandBufAdd4BE(pReply, 0);
905
906 DebugCallbackContext context;
907 context.numItems = 0;
908 context.pReply = pReply;
909 context.withGeneric = withGeneric;
910
911 dex_file.DecodeDebugInfo(code_item, m, NULL, DebugCallbackContext::Callback, &context);
912
913 JDWP::Set4BE(expandBufGetBuffer(pReply) + numLocalsOffset, context.numItems);
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700914}
915
916uint8_t Dbg::GetFieldBasicTag(JDWP::ObjectId objId, JDWP::FieldId fieldId) {
917 UNIMPLEMENTED(FATAL);
918 return 0;
919}
920
921uint8_t Dbg::GetStaticFieldBasicTag(JDWP::RefTypeId refTypeId, JDWP::FieldId fieldId) {
922 UNIMPLEMENTED(FATAL);
923 return 0;
924}
925
926void Dbg::GetFieldValue(JDWP::ObjectId objectId, JDWP::FieldId fieldId, JDWP::ExpandBuf* pReply) {
927 UNIMPLEMENTED(FATAL);
928}
929
930void Dbg::SetFieldValue(JDWP::ObjectId objectId, JDWP::FieldId fieldId, uint64_t value, int width) {
931 UNIMPLEMENTED(FATAL);
932}
933
934void Dbg::GetStaticFieldValue(JDWP::RefTypeId refTypeId, JDWP::FieldId fieldId, JDWP::ExpandBuf* pReply) {
935 UNIMPLEMENTED(FATAL);
936}
937
938void Dbg::SetStaticFieldValue(JDWP::RefTypeId refTypeId, JDWP::FieldId fieldId, uint64_t rawValue, int width) {
939 UNIMPLEMENTED(FATAL);
940}
941
Elliott Hughes68fdbd02011-11-29 19:22:47 -0800942std::string Dbg::StringToUtf8(JDWP::ObjectId strId) {
943 String* s = gRegistry->Get<String*>(strId);
944 return s->ToModifiedUtf8();
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700945}
946
Elliott Hughesa2e54f62011-11-17 13:01:30 -0800947Thread* DecodeThread(JDWP::ObjectId threadId) {
948 Object* thread_peer = gRegistry->Get<Object*>(threadId);
949 CHECK(thread_peer != NULL);
950 return Thread::FromManagedThread(thread_peer);
951}
952
953bool Dbg::GetThreadName(JDWP::ObjectId threadId, std::string& name) {
954 ScopedThreadListLock thread_list_lock;
955 Thread* thread = DecodeThread(threadId);
956 if (thread == NULL) {
957 return false;
958 }
959 StringAppendF(&name, "<%d> %s", thread->GetThinLockId(), thread->GetName()->ToModifiedUtf8().c_str());
960 return true;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700961}
962
963JDWP::ObjectId Dbg::GetThreadGroup(JDWP::ObjectId threadId) {
Elliott Hughes499c5132011-11-17 14:55:11 -0800964 Object* thread = gRegistry->Get<Object*>(threadId);
965 CHECK(thread != NULL);
966
967 Class* c = Runtime::Current()->GetClassLinker()->FindSystemClass("Ljava/lang/Thread;");
968 CHECK(c != NULL);
969 Field* f = c->FindInstanceField("group", "Ljava/lang/ThreadGroup;");
970 CHECK(f != NULL);
971 Object* group = f->GetObject(thread);
972 CHECK(group != NULL);
973 return gRegistry->Add(group);
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700974}
975
Elliott Hughes499c5132011-11-17 14:55:11 -0800976std::string Dbg::GetThreadGroupName(JDWP::ObjectId threadGroupId) {
977 Object* thread_group = gRegistry->Get<Object*>(threadGroupId);
978 CHECK(thread_group != NULL);
979
980 Class* c = Runtime::Current()->GetClassLinker()->FindSystemClass("Ljava/lang/ThreadGroup;");
981 CHECK(c != NULL);
982 Field* f = c->FindInstanceField("name", "Ljava/lang/String;");
983 CHECK(f != NULL);
984 String* s = reinterpret_cast<String*>(f->GetObject(thread_group));
985 return s->ToModifiedUtf8();
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700986}
987
988JDWP::ObjectId Dbg::GetThreadGroupParent(JDWP::ObjectId threadGroupId) {
989 UNIMPLEMENTED(FATAL);
990 return 0;
991}
992
Elliott Hughes499c5132011-11-17 14:55:11 -0800993static Object* GetStaticThreadGroup(const char* field_name) {
994 Class* c = Runtime::Current()->GetClassLinker()->FindSystemClass("Ljava/lang/ThreadGroup;");
995 CHECK(c != NULL);
996 Field* f = c->FindStaticField(field_name, "Ljava/lang/ThreadGroup;");
997 CHECK(f != NULL);
998 Object* group = f->GetObject(NULL);
999 CHECK(group != NULL);
1000 return group;
1001}
1002
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001003JDWP::ObjectId Dbg::GetSystemThreadGroupId() {
Elliott Hughes499c5132011-11-17 14:55:11 -08001004 return gRegistry->Add(GetStaticThreadGroup("mSystem"));
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001005}
1006
1007JDWP::ObjectId Dbg::GetMainThreadGroupId() {
Elliott Hughes499c5132011-11-17 14:55:11 -08001008 return gRegistry->Add(GetStaticThreadGroup("mMain"));
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001009}
1010
Elliott Hughes499c5132011-11-17 14:55:11 -08001011bool Dbg::GetThreadStatus(JDWP::ObjectId threadId, uint32_t* pThreadStatus, uint32_t* pSuspendStatus) {
1012 ScopedThreadListLock thread_list_lock;
1013
1014 Thread* thread = DecodeThread(threadId);
1015 if (thread == NULL) {
1016 return false;
1017 }
1018
1019 switch (thread->GetState()) {
1020 case Thread::kTerminated: *pThreadStatus = JDWP::TS_ZOMBIE; break;
1021 case Thread::kRunnable: *pThreadStatus = JDWP::TS_RUNNING; break;
1022 case Thread::kTimedWaiting: *pThreadStatus = JDWP::TS_SLEEPING; break;
1023 case Thread::kBlocked: *pThreadStatus = JDWP::TS_MONITOR; break;
1024 case Thread::kWaiting: *pThreadStatus = JDWP::TS_WAIT; break;
1025 case Thread::kInitializing: *pThreadStatus = JDWP::TS_ZOMBIE; break;
1026 case Thread::kStarting: *pThreadStatus = JDWP::TS_ZOMBIE; break;
1027 case Thread::kNative: *pThreadStatus = JDWP::TS_RUNNING; break;
1028 case Thread::kVmWait: *pThreadStatus = JDWP::TS_WAIT; break;
1029 case Thread::kSuspended: *pThreadStatus = JDWP::TS_RUNNING; break;
1030 default:
1031 LOG(FATAL) << "unknown thread state " << thread->GetState();
1032 }
1033
1034 *pSuspendStatus = (thread->IsSuspended() ? JDWP::SUSPEND_STATUS_SUSPENDED : 0);
1035
1036 return true;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001037}
1038
1039uint32_t Dbg::GetThreadSuspendCount(JDWP::ObjectId threadId) {
1040 UNIMPLEMENTED(FATAL);
1041 return 0;
1042}
1043
1044bool Dbg::ThreadExists(JDWP::ObjectId threadId) {
Elliott Hughes761928d2011-11-16 18:33:03 -08001045 return DecodeThread(threadId) != NULL;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001046}
1047
1048bool Dbg::IsSuspended(JDWP::ObjectId threadId) {
Elliott Hughes761928d2011-11-16 18:33:03 -08001049 return DecodeThread(threadId)->IsSuspended();
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001050}
1051
1052//void Dbg::WaitForSuspend(JDWP::ObjectId threadId);
1053
Elliott Hughesa2155262011-11-16 16:26:58 -08001054void Dbg::GetThreadGroupThreadsImpl(Object* thread_group, JDWP::ObjectId** ppThreadIds, uint32_t* pThreadCount) {
1055 struct ThreadListVisitor {
1056 static void Visit(Thread* t, void* arg) {
1057 reinterpret_cast<ThreadListVisitor*>(arg)->Visit(t);
1058 }
1059
1060 void Visit(Thread* t) {
1061 if (t == Dbg::GetDebugThread()) {
1062 // Skip the JDWP thread. Some debuggers get bent out of shape when they can't suspend and
1063 // query all threads, so it's easier if we just don't tell them about this thread.
1064 return;
1065 }
1066 if (thread_group == NULL || t->GetThreadGroup() == thread_group) {
1067 threads.push_back(gRegistry->Add(t->GetPeer()));
1068 }
1069 }
1070
1071 Object* thread_group;
1072 std::vector<JDWP::ObjectId> threads;
1073 };
1074
1075 ThreadListVisitor tlv;
1076 tlv.thread_group = thread_group;
1077
1078 {
1079 ScopedThreadListLock thread_list_lock;
1080 Runtime::Current()->GetThreadList()->ForEach(ThreadListVisitor::Visit, &tlv);
1081 }
1082
1083 *pThreadCount = tlv.threads.size();
1084 if (*pThreadCount == 0) {
1085 *ppThreadIds = NULL;
1086 } else {
1087 *ppThreadIds = new JDWP::ObjectId[*pThreadCount];
1088 for (size_t i = 0; i < *pThreadCount; ++i) {
1089 (*ppThreadIds)[i] = tlv.threads[i];
1090 }
1091 }
1092}
1093
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001094void Dbg::GetThreadGroupThreads(JDWP::ObjectId threadGroupId, JDWP::ObjectId** ppThreadIds, uint32_t* pThreadCount) {
Elliott Hughesa2155262011-11-16 16:26:58 -08001095 GetThreadGroupThreadsImpl(gRegistry->Get<Object*>(threadGroupId), ppThreadIds, pThreadCount);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001096}
1097
1098void Dbg::GetAllThreads(JDWP::ObjectId** ppThreadIds, uint32_t* pThreadCount) {
Elliott Hughesa2155262011-11-16 16:26:58 -08001099 GetThreadGroupThreadsImpl(NULL, ppThreadIds, pThreadCount);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001100}
1101
1102int Dbg::GetThreadFrameCount(JDWP::ObjectId threadId) {
Elliott Hughes03181a82011-11-17 17:22:21 -08001103 ScopedThreadListLock thread_list_lock;
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001104 struct CountStackDepthVisitor : public Thread::StackVisitor {
1105 CountStackDepthVisitor() : depth(0) {}
Elliott Hughes03181a82011-11-17 17:22:21 -08001106 virtual void VisitFrame(const Frame&, uintptr_t) {
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001107 ++depth;
1108 }
1109 size_t depth;
1110 };
1111 CountStackDepthVisitor visitor;
1112 DecodeThread(threadId)->WalkStack(&visitor);
1113 return visitor.depth;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001114}
1115
Elliott Hughes03181a82011-11-17 17:22:21 -08001116bool Dbg::GetThreadFrame(JDWP::ObjectId threadId, int desired_frame_number, JDWP::FrameId* pFrameId, JDWP::JdwpLocation* pLoc) {
1117 ScopedThreadListLock thread_list_lock;
1118 struct GetFrameVisitor : public Thread::StackVisitor {
1119 GetFrameVisitor(int desired_frame_number, JDWP::FrameId* pFrameId, JDWP::JdwpLocation* pLoc)
1120 : found(false) ,depth(0), desired_frame_number(desired_frame_number), pFrameId(pFrameId), pLoc(pLoc) {
1121 }
1122 virtual void VisitFrame(const Frame& f, uintptr_t pc) {
1123 if (!f.HasMethod()) {
1124 return; // These don't count?
1125 }
1126
1127 if (depth == desired_frame_number) {
1128 *pFrameId = reinterpret_cast<JDWP::FrameId>(f.GetSP());
1129
1130 Method* m = f.GetMethod();
1131 Class* c = m->GetDeclaringClass();
1132
1133 pLoc->typeTag = c->IsInterface() ? JDWP::TT_INTERFACE : JDWP::TT_CLASS;
1134 pLoc->classId = gRegistry->Add(c);
1135 pLoc->methodId = ToMethodId(m);
1136 pLoc->idx = m->IsNative() ? -1 : m->ToDexPC(pc);
1137
1138 found = true;
1139 }
1140 ++depth;
1141 }
1142 bool found;
1143 int depth;
1144 int desired_frame_number;
1145 JDWP::FrameId* pFrameId;
1146 JDWP::JdwpLocation* pLoc;
1147 };
1148 GetFrameVisitor visitor(desired_frame_number, pFrameId, pLoc);
1149 visitor.desired_frame_number = desired_frame_number;
1150 DecodeThread(threadId)->WalkStack(&visitor);
1151 return visitor.found;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001152}
1153
1154JDWP::ObjectId Dbg::GetThreadSelfId() {
Elliott Hughes475fc232011-10-25 15:00:35 -07001155 return gRegistry->Add(Thread::Current()->GetPeer());
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001156}
1157
Elliott Hughes475fc232011-10-25 15:00:35 -07001158void Dbg::SuspendVM() {
Elliott Hughesa2155262011-11-16 16:26:58 -08001159 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 -07001160 Runtime::Current()->GetThreadList()->SuspendAll(true);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001161}
1162
1163void Dbg::ResumeVM() {
Elliott Hughes475fc232011-10-25 15:00:35 -07001164 Runtime::Current()->GetThreadList()->ResumeAll(true);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001165}
1166
1167void Dbg::SuspendThread(JDWP::ObjectId threadId) {
1168 UNIMPLEMENTED(FATAL);
1169}
1170
1171void Dbg::ResumeThread(JDWP::ObjectId threadId) {
1172 UNIMPLEMENTED(FATAL);
1173}
1174
1175void Dbg::SuspendSelf() {
Elliott Hughes475fc232011-10-25 15:00:35 -07001176 Runtime::Current()->GetThreadList()->SuspendSelfForDebugger();
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001177}
1178
1179bool Dbg::GetThisObject(JDWP::ObjectId threadId, JDWP::FrameId frameId, JDWP::ObjectId* pThisId) {
1180 UNIMPLEMENTED(FATAL);
1181 return false;
1182}
1183
Elliott Hughesdbb40792011-11-18 17:05:22 -08001184void Dbg::GetLocalValue(JDWP::ObjectId threadId, JDWP::FrameId frameId, int slot, JDWP::JdwpTag tag, uint8_t* buf, size_t expectedLen) {
1185 Method** sp = reinterpret_cast<Method**>(frameId);
Elliott Hughes68fdbd02011-11-29 19:22:47 -08001186 Frame f;
1187 f.SetSP(sp);
1188 uint16_t reg = DemangleSlot(slot, f);
1189 Method* m = f.GetMethod();
1190
1191 const VmapTable vmap_table(m->GetVmapTableRaw());
1192 uint32_t vmap_offset;
1193 if (vmap_table.IsInContext(reg, vmap_offset)) {
1194 UNIMPLEMENTED(FATAL) << "don't know how to pull locals from callee save frames: " << vmap_offset;
1195 }
Elliott Hughesdbb40792011-11-18 17:05:22 -08001196
1197 switch (tag) {
1198 case JDWP::JT_BOOLEAN:
1199 {
Elliott Hughesdbb40792011-11-18 17:05:22 -08001200 CHECK_EQ(expectedLen, 1U);
Elliott Hughes68fdbd02011-11-29 19:22:47 -08001201 uint32_t intVal = static_cast<uint32_t>(f.GetVReg(m, reg));
1202 LOG(WARNING) << "get boolean local " << reg << " = " << intVal;
Elliott Hughesdbb40792011-11-18 17:05:22 -08001203 JDWP::Set1(buf+1, intVal != 0);
1204 }
1205 break;
1206 case JDWP::JT_BYTE:
1207 {
Elliott Hughesdbb40792011-11-18 17:05:22 -08001208 CHECK_EQ(expectedLen, 1U);
Elliott Hughes68fdbd02011-11-29 19:22:47 -08001209 uint32_t intVal = static_cast<uint32_t>(f.GetVReg(m, reg));
1210 LOG(WARNING) << "get byte local " << reg << " = " << intVal;
Elliott Hughesdbb40792011-11-18 17:05:22 -08001211 JDWP::Set1(buf+1, intVal);
1212 }
1213 break;
1214 case JDWP::JT_SHORT:
1215 case JDWP::JT_CHAR:
1216 {
Elliott Hughesdbb40792011-11-18 17:05:22 -08001217 CHECK_EQ(expectedLen, 2U);
Elliott Hughes68fdbd02011-11-29 19:22:47 -08001218 uint32_t intVal = static_cast<uint32_t>(f.GetVReg(m, reg));
1219 LOG(WARNING) << "get short/char local " << reg << " = " << intVal;
Elliott Hughesdbb40792011-11-18 17:05:22 -08001220 JDWP::Set2BE(buf+1, intVal);
1221 }
1222 break;
1223 case JDWP::JT_INT:
1224 case JDWP::JT_FLOAT:
1225 {
Elliott Hughesdbb40792011-11-18 17:05:22 -08001226 CHECK_EQ(expectedLen, 4U);
Elliott Hughes68fdbd02011-11-29 19:22:47 -08001227 uint32_t intVal = static_cast<uint32_t>(f.GetVReg(m, reg));
1228 LOG(WARNING) << "get int/float local " << reg << " = " << intVal;
Elliott Hughesdbb40792011-11-18 17:05:22 -08001229 JDWP::Set4BE(buf+1, intVal);
1230 }
1231 break;
1232 case JDWP::JT_ARRAY:
1233 {
Elliott Hughesdbb40792011-11-18 17:05:22 -08001234 CHECK_EQ(expectedLen, sizeof(JDWP::ObjectId));
Elliott Hughes68fdbd02011-11-29 19:22:47 -08001235 Object* o = reinterpret_cast<Object*>(f.GetVReg(m, reg));
1236 LOG(WARNING) << "get array local " << reg << " = " << o;
Elliott Hughesdbb40792011-11-18 17:05:22 -08001237 if (o != NULL && !Heap::IsHeapAddress(o)) {
Elliott Hughes68fdbd02011-11-29 19:22:47 -08001238 LOG(FATAL) << "reg " << reg << " expected to hold array: " << o;
Elliott Hughesdbb40792011-11-18 17:05:22 -08001239 }
1240 JDWP::SetObjectId(buf+1, gRegistry->Add(o));
1241 }
1242 break;
1243 case JDWP::JT_OBJECT:
1244 {
Elliott Hughesdbb40792011-11-18 17:05:22 -08001245 CHECK_EQ(expectedLen, sizeof(JDWP::ObjectId));
Elliott Hughes68fdbd02011-11-29 19:22:47 -08001246 Object* o = reinterpret_cast<Object*>(f.GetVReg(m, reg));
1247 LOG(WARNING) << "get object local " << reg << " = " << o;
Elliott Hughesdbb40792011-11-18 17:05:22 -08001248 if (o != NULL && !Heap::IsHeapAddress(o)) {
Elliott Hughes68fdbd02011-11-29 19:22:47 -08001249 LOG(FATAL) << "reg " << reg << " expected to hold object: " << o;
Elliott Hughesdbb40792011-11-18 17:05:22 -08001250 }
1251 tag = TagFromObject(o);
1252 JDWP::SetObjectId(buf+1, gRegistry->Add(o));
1253 }
1254 break;
1255 case JDWP::JT_DOUBLE:
1256 case JDWP::JT_LONG:
1257 {
Elliott Hughes68fdbd02011-11-29 19:22:47 -08001258 UNIMPLEMENTED(WARNING) << "get 64-bit local " << reg;
Elliott Hughesdbb40792011-11-18 17:05:22 -08001259 CHECK_EQ(expectedLen, 8U);
Elliott Hughes68fdbd02011-11-29 19:22:47 -08001260 uint64_t longVal = 0; // memcpy(&longVal, &framePtr[reg], 8);
Elliott Hughesdbb40792011-11-18 17:05:22 -08001261 JDWP::Set8BE(buf+1, longVal);
1262 }
1263 break;
1264 default:
1265 LOG(FATAL) << "unknown tag " << tag;
1266 break;
1267 }
1268
1269 // Prepend tag, which may have been updated.
1270 JDWP::Set1(buf, tag);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001271}
1272
Elliott Hughesdbb40792011-11-18 17:05:22 -08001273void 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 -07001274 UNIMPLEMENTED(FATAL);
1275}
1276
1277void Dbg::PostLocationEvent(const Method* method, int pcOffset, Object* thisPtr, int eventFlags) {
1278 UNIMPLEMENTED(FATAL);
1279}
1280
1281void Dbg::PostException(void* throwFp, int throwRelPc, void* catchFp, int catchRelPc, Object* exception) {
1282 UNIMPLEMENTED(FATAL);
1283}
1284
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001285void Dbg::PostClassPrepare(Class* c) {
1286 UNIMPLEMENTED(FATAL);
1287}
1288
1289bool Dbg::WatchLocation(const JDWP::JdwpLocation* pLoc) {
1290 UNIMPLEMENTED(FATAL);
1291 return false;
1292}
1293
1294void Dbg::UnwatchLocation(const JDWP::JdwpLocation* pLoc) {
1295 UNIMPLEMENTED(FATAL);
1296}
1297
1298bool Dbg::ConfigureStep(JDWP::ObjectId threadId, JDWP::JdwpStepSize size, JDWP::JdwpStepDepth depth) {
1299 UNIMPLEMENTED(FATAL);
1300 return false;
1301}
1302
1303void Dbg::UnconfigureStep(JDWP::ObjectId threadId) {
1304 UNIMPLEMENTED(FATAL);
1305}
1306
1307JDWP::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) {
1308 UNIMPLEMENTED(FATAL);
1309 return JDWP::ERR_NONE;
1310}
1311
1312void Dbg::ExecuteMethod(DebugInvokeReq* pReq) {
1313 UNIMPLEMENTED(FATAL);
1314}
1315
1316void Dbg::RegisterObjectId(JDWP::ObjectId id) {
1317 UNIMPLEMENTED(FATAL);
1318}
1319
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07001320/*
1321 * "buf" contains a full JDWP packet, possibly with multiple chunks. We
1322 * need to process each, accumulate the replies, and ship the whole thing
1323 * back.
1324 *
1325 * Returns "true" if we have a reply. The reply buffer is newly allocated,
1326 * and includes the chunk type/length, followed by the data.
1327 *
1328 * TODO: we currently assume that the request and reply include a single
1329 * chunk. If this becomes inconvenient we will need to adapt.
1330 */
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001331bool Dbg::DdmHandlePacket(const uint8_t* buf, int dataLen, uint8_t** pReplyBuf, int* pReplyLen) {
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07001332 CHECK_GE(dataLen, 0);
1333
1334 Thread* self = Thread::Current();
1335 JNIEnv* env = self->GetJniEnv();
1336
1337 static jclass Chunk_class = env->FindClass("org/apache/harmony/dalvik/ddmc/Chunk");
1338 static jclass DdmServer_class = env->FindClass("org/apache/harmony/dalvik/ddmc/DdmServer");
1339 static jmethodID dispatch_mid = env->GetStaticMethodID(DdmServer_class, "dispatch",
1340 "(I[BII)Lorg/apache/harmony/dalvik/ddmc/Chunk;");
1341 static jfieldID data_fid = env->GetFieldID(Chunk_class, "data", "[B");
1342 static jfieldID length_fid = env->GetFieldID(Chunk_class, "length", "I");
1343 static jfieldID offset_fid = env->GetFieldID(Chunk_class, "offset", "I");
1344 static jfieldID type_fid = env->GetFieldID(Chunk_class, "type", "I");
1345
1346 // Create a byte[] corresponding to 'buf'.
Elliott Hughes6a5bd492011-10-28 14:33:57 -07001347 ScopedLocalRef<jbyteArray> dataArray(env, env->NewByteArray(dataLen));
1348 if (dataArray.get() == NULL) {
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07001349 LOG(WARNING) << "byte[] allocation failed: " << dataLen;
1350 env->ExceptionClear();
1351 return false;
1352 }
Elliott Hughes6a5bd492011-10-28 14:33:57 -07001353 env->SetByteArrayRegion(dataArray.get(), 0, dataLen, reinterpret_cast<const jbyte*>(buf));
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07001354
1355 const int kChunkHdrLen = 8;
1356
1357 // Run through and find all chunks. [Currently just find the first.]
Elliott Hughes6a5bd492011-10-28 14:33:57 -07001358 ScopedByteArrayRO contents(env, dataArray.get());
Elliott Hughesf7c3b662011-10-27 12:04:56 -07001359 jint type = JDWP::Get4BE(reinterpret_cast<const uint8_t*>(&contents[0]));
1360 jint length = JDWP::Get4BE(reinterpret_cast<const uint8_t*>(&contents[4]));
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07001361 jint offset = kChunkHdrLen;
1362 if (offset + length > dataLen) {
1363 LOG(WARNING) << StringPrintf("bad chunk found (len=%u pktLen=%d)", length, dataLen);
1364 return false;
1365 }
1366
1367 // Call "private static Chunk dispatch(int type, byte[] data, int offset, int length)".
Elliott Hughes6a5bd492011-10-28 14:33:57 -07001368 ScopedLocalRef<jobject> chunk(env, env->CallStaticObjectMethod(DdmServer_class, dispatch_mid, type, dataArray.get(), offset, length));
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07001369 if (env->ExceptionCheck()) {
1370 LOG(INFO) << StringPrintf("Exception thrown by dispatcher for 0x%08x", type);
1371 env->ExceptionDescribe();
1372 env->ExceptionClear();
1373 return false;
1374 }
1375
Elliott Hughes6a5bd492011-10-28 14:33:57 -07001376 if (chunk.get() == NULL) {
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07001377 return false;
1378 }
1379
1380 /*
1381 * Pull the pieces out of the chunk. We copy the results into a
1382 * newly-allocated buffer that the caller can free. We don't want to
1383 * continue using the Chunk object because nothing has a reference to it.
1384 *
1385 * We could avoid this by returning type/data/offset/length and having
1386 * the caller be aware of the object lifetime issues, but that
1387 * integrates the JDWP code more tightly into the VM, and doesn't work
1388 * if we have responses for multiple chunks.
1389 *
1390 * So we're pretty much stuck with copying data around multiple times.
1391 */
Elliott Hughes6a5bd492011-10-28 14:33:57 -07001392 ScopedLocalRef<jbyteArray> replyData(env, reinterpret_cast<jbyteArray>(env->GetObjectField(chunk.get(), data_fid)));
1393 length = env->GetIntField(chunk.get(), length_fid);
1394 offset = env->GetIntField(chunk.get(), offset_fid);
1395 type = env->GetIntField(chunk.get(), type_fid);
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07001396
Elliott Hughes6a5bd492011-10-28 14:33:57 -07001397 LOG(VERBOSE) << StringPrintf("DDM reply: type=0x%08x data=%p offset=%d length=%d", type, replyData.get(), offset, length);
1398 if (length == 0 || replyData.get() == NULL) {
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07001399 return false;
1400 }
1401
Elliott Hughes6a5bd492011-10-28 14:33:57 -07001402 jsize replyLength = env->GetArrayLength(replyData.get());
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07001403 if (offset + length > replyLength) {
1404 LOG(WARNING) << StringPrintf("chunk off=%d len=%d exceeds reply array len %d", offset, length, replyLength);
1405 return false;
1406 }
1407
1408 uint8_t* reply = new uint8_t[length + kChunkHdrLen];
1409 if (reply == NULL) {
1410 LOG(WARNING) << "malloc failed: " << (length + kChunkHdrLen);
1411 return false;
1412 }
Elliott Hughesf7c3b662011-10-27 12:04:56 -07001413 JDWP::Set4BE(reply + 0, type);
1414 JDWP::Set4BE(reply + 4, length);
Elliott Hughes6a5bd492011-10-28 14:33:57 -07001415 env->GetByteArrayRegion(replyData.get(), offset, length, reinterpret_cast<jbyte*>(reply + kChunkHdrLen));
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07001416
1417 *pReplyBuf = reply;
1418 *pReplyLen = length + kChunkHdrLen;
1419
1420 LOG(VERBOSE) << StringPrintf("dvmHandleDdm returning type=%.4s buf=%p len=%d", (char*) reply, reply, length);
1421 return true;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001422}
1423
Elliott Hughesa2155262011-11-16 16:26:58 -08001424void Dbg::DdmBroadcast(bool connect) {
Elliott Hughes47fce012011-10-25 18:37:19 -07001425 LOG(VERBOSE) << "Broadcasting DDM " << (connect ? "connect" : "disconnect") << "...";
1426
1427 Thread* self = Thread::Current();
1428 if (self->GetState() != Thread::kRunnable) {
1429 LOG(ERROR) << "DDM broadcast in thread state " << self->GetState();
1430 /* try anyway? */
1431 }
1432
1433 JNIEnv* env = self->GetJniEnv();
1434 static jclass DdmServer_class = env->FindClass("org/apache/harmony/dalvik/ddmc/DdmServer");
1435 static jmethodID broadcast_mid = env->GetStaticMethodID(DdmServer_class, "broadcast", "(I)V");
1436 jint event = connect ? 1 /*DdmServer.CONNECTED*/ : 2 /*DdmServer.DISCONNECTED*/;
1437 env->CallStaticVoidMethod(DdmServer_class, broadcast_mid, event);
1438 if (env->ExceptionCheck()) {
1439 LOG(ERROR) << "DdmServer.broadcast " << event << " failed";
1440 env->ExceptionDescribe();
1441 env->ExceptionClear();
1442 }
1443}
1444
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001445void Dbg::DdmConnected() {
Elliott Hughesa2155262011-11-16 16:26:58 -08001446 Dbg::DdmBroadcast(true);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001447}
1448
1449void Dbg::DdmDisconnected() {
Elliott Hughesa2155262011-11-16 16:26:58 -08001450 Dbg::DdmBroadcast(false);
Elliott Hughes47fce012011-10-25 18:37:19 -07001451 gDdmThreadNotification = false;
1452}
1453
1454/*
Elliott Hughes82188472011-11-07 18:11:48 -08001455 * Send a notification when a thread starts, stops, or changes its name.
Elliott Hughes47fce012011-10-25 18:37:19 -07001456 *
1457 * Because we broadcast the full set of threads when the notifications are
1458 * first enabled, it's possible for "thread" to be actively executing.
1459 */
Elliott Hughes82188472011-11-07 18:11:48 -08001460void Dbg::DdmSendThreadNotification(Thread* t, uint32_t type) {
Elliott Hughes47fce012011-10-25 18:37:19 -07001461 if (!gDdmThreadNotification) {
1462 return;
1463 }
1464
Elliott Hughes82188472011-11-07 18:11:48 -08001465 if (type == CHUNK_TYPE("THDE")) {
Elliott Hughes47fce012011-10-25 18:37:19 -07001466 uint8_t buf[4];
Elliott Hughesf7c3b662011-10-27 12:04:56 -07001467 JDWP::Set4BE(&buf[0], t->GetThinLockId());
Elliott Hughes47fce012011-10-25 18:37:19 -07001468 Dbg::DdmSendChunk(CHUNK_TYPE("THDE"), 4, buf);
Elliott Hughes82188472011-11-07 18:11:48 -08001469 } else {
1470 CHECK(type == CHUNK_TYPE("THCR") || type == CHUNK_TYPE("THNM")) << type;
1471 SirtRef<String> name(t->GetName());
1472 size_t char_count = (name.get() != NULL) ? name->GetLength() : 0;
1473 const jchar* chars = name->GetCharArray()->GetData();
1474
Elliott Hughes21f32d72011-11-09 17:44:13 -08001475 std::vector<uint8_t> bytes;
Elliott Hughes545a0642011-11-08 19:10:03 -08001476 JDWP::Append4BE(bytes, t->GetThinLockId());
1477 JDWP::AppendUtf16BE(bytes, chars, char_count);
Elliott Hughes21f32d72011-11-09 17:44:13 -08001478 CHECK_EQ(bytes.size(), char_count*2 + sizeof(uint32_t)*2);
1479 Dbg::DdmSendChunk(type, bytes);
Elliott Hughes47fce012011-10-25 18:37:19 -07001480 }
1481}
1482
Elliott Hughesa2155262011-11-16 16:26:58 -08001483static void DdmSendThreadStartCallback(Thread* t, void*) {
Elliott Hughes82188472011-11-07 18:11:48 -08001484 Dbg::DdmSendThreadNotification(t, CHUNK_TYPE("THCR"));
Elliott Hughes47fce012011-10-25 18:37:19 -07001485}
1486
1487void Dbg::DdmSetThreadNotification(bool enable) {
1488 // We lock the thread list to avoid sending duplicate events or missing
1489 // a thread change. We should be okay holding this lock while sending
1490 // the messages out. (We have to hold it while accessing a live thread.)
Elliott Hughesbbd9d832011-11-07 14:40:00 -08001491 ScopedThreadListLock thread_list_lock;
Elliott Hughes47fce012011-10-25 18:37:19 -07001492
1493 gDdmThreadNotification = enable;
1494 if (enable) {
Elliott Hughesbfe487b2011-10-26 15:48:55 -07001495 Runtime::Current()->GetThreadList()->ForEach(DdmSendThreadStartCallback, NULL);
Elliott Hughes47fce012011-10-25 18:37:19 -07001496 }
1497}
1498
Elliott Hughesa2155262011-11-16 16:26:58 -08001499void Dbg::PostThreadStartOrStop(Thread* t, uint32_t type) {
Elliott Hughes47fce012011-10-25 18:37:19 -07001500 if (gDebuggerActive) {
1501 JDWP::ObjectId id = gRegistry->Add(t->GetPeer());
Elliott Hughes82188472011-11-07 18:11:48 -08001502 gJdwpState->PostThreadChange(id, type == CHUNK_TYPE("THCR"));
Elliott Hughes47fce012011-10-25 18:37:19 -07001503 }
Elliott Hughes82188472011-11-07 18:11:48 -08001504 Dbg::DdmSendThreadNotification(t, type);
Elliott Hughes47fce012011-10-25 18:37:19 -07001505}
1506
1507void Dbg::PostThreadStart(Thread* t) {
Elliott Hughesa2155262011-11-16 16:26:58 -08001508 Dbg::PostThreadStartOrStop(t, CHUNK_TYPE("THCR"));
Elliott Hughes47fce012011-10-25 18:37:19 -07001509}
1510
1511void Dbg::PostThreadDeath(Thread* t) {
Elliott Hughesa2155262011-11-16 16:26:58 -08001512 Dbg::PostThreadStartOrStop(t, CHUNK_TYPE("THDE"));
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001513}
1514
Elliott Hughes82188472011-11-07 18:11:48 -08001515void Dbg::DdmSendChunk(uint32_t type, size_t byte_count, const uint8_t* buf) {
Elliott Hughes3bb81562011-10-21 18:52:59 -07001516 CHECK(buf != NULL);
1517 iovec vec[1];
1518 vec[0].iov_base = reinterpret_cast<void*>(const_cast<uint8_t*>(buf));
1519 vec[0].iov_len = byte_count;
1520 Dbg::DdmSendChunkV(type, vec, 1);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001521}
1522
Elliott Hughes21f32d72011-11-09 17:44:13 -08001523void Dbg::DdmSendChunk(uint32_t type, const std::vector<uint8_t>& bytes) {
1524 DdmSendChunk(type, bytes.size(), &bytes[0]);
1525}
1526
Elliott Hughes82188472011-11-07 18:11:48 -08001527void Dbg::DdmSendChunkV(uint32_t type, const struct iovec* iov, int iovcnt) {
Elliott Hughes3bb81562011-10-21 18:52:59 -07001528 if (gJdwpState == NULL) {
1529 LOG(VERBOSE) << "Debugger thread not active, ignoring DDM send: " << type;
1530 } else {
Elliott Hughes376a7a02011-10-24 18:35:55 -07001531 gJdwpState->DdmSendChunkV(type, iov, iovcnt);
Elliott Hughes3bb81562011-10-21 18:52:59 -07001532 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001533}
1534
Elliott Hughes767a1472011-10-26 18:49:02 -07001535int Dbg::DdmHandleHpifChunk(HpifWhen when) {
1536 if (when == HPIF_WHEN_NOW) {
Elliott Hughes7162ad92011-10-27 14:08:42 -07001537 DdmSendHeapInfo(when);
Elliott Hughes767a1472011-10-26 18:49:02 -07001538 return true;
1539 }
1540
1541 if (when != HPIF_WHEN_NEVER && when != HPIF_WHEN_NEXT_GC && when != HPIF_WHEN_EVERY_GC) {
1542 LOG(ERROR) << "invalid HpifWhen value: " << static_cast<int>(when);
1543 return false;
1544 }
1545
1546 gDdmHpifWhen = when;
1547 return true;
1548}
1549
1550bool Dbg::DdmHandleHpsgNhsgChunk(Dbg::HpsgWhen when, Dbg::HpsgWhat what, bool native) {
1551 if (when != HPSG_WHEN_NEVER && when != HPSG_WHEN_EVERY_GC) {
1552 LOG(ERROR) << "invalid HpsgWhen value: " << static_cast<int>(when);
1553 return false;
1554 }
1555
1556 if (what != HPSG_WHAT_MERGED_OBJECTS && what != HPSG_WHAT_DISTINCT_OBJECTS) {
1557 LOG(ERROR) << "invalid HpsgWhat value: " << static_cast<int>(what);
1558 return false;
1559 }
1560
1561 if (native) {
1562 gDdmNhsgWhen = when;
1563 gDdmNhsgWhat = what;
1564 } else {
1565 gDdmHpsgWhen = when;
1566 gDdmHpsgWhat = what;
1567 }
1568 return true;
1569}
1570
Elliott Hughes7162ad92011-10-27 14:08:42 -07001571void Dbg::DdmSendHeapInfo(HpifWhen reason) {
1572 // If there's a one-shot 'when', reset it.
1573 if (reason == gDdmHpifWhen) {
1574 if (gDdmHpifWhen == HPIF_WHEN_NEXT_GC) {
1575 gDdmHpifWhen = HPIF_WHEN_NEVER;
1576 }
1577 }
1578
1579 /*
1580 * Chunk HPIF (client --> server)
1581 *
1582 * Heap Info. General information about the heap,
1583 * suitable for a summary display.
1584 *
1585 * [u4]: number of heaps
1586 *
1587 * For each heap:
1588 * [u4]: heap ID
1589 * [u8]: timestamp in ms since Unix epoch
1590 * [u1]: capture reason (same as 'when' value from server)
1591 * [u4]: max heap size in bytes (-Xmx)
1592 * [u4]: current heap size in bytes
1593 * [u4]: current number of bytes allocated
1594 * [u4]: current number of objects allocated
1595 */
1596 uint8_t heap_count = 1;
Elliott Hughes21f32d72011-11-09 17:44:13 -08001597 std::vector<uint8_t> bytes;
Elliott Hughes545a0642011-11-08 19:10:03 -08001598 JDWP::Append4BE(bytes, heap_count);
1599 JDWP::Append4BE(bytes, 1); // Heap id (bogus; we only have one heap).
1600 JDWP::Append8BE(bytes, MilliTime());
1601 JDWP::Append1BE(bytes, reason);
1602 JDWP::Append4BE(bytes, Heap::GetMaxMemory()); // Max allowed heap size in bytes.
1603 JDWP::Append4BE(bytes, Heap::GetTotalMemory()); // Current heap size in bytes.
1604 JDWP::Append4BE(bytes, Heap::GetBytesAllocated());
1605 JDWP::Append4BE(bytes, Heap::GetObjectsAllocated());
Elliott Hughes21f32d72011-11-09 17:44:13 -08001606 CHECK_EQ(bytes.size(), 4U + (heap_count * (4 + 8 + 1 + 4 + 4 + 4 + 4)));
1607 Dbg::DdmSendChunk(CHUNK_TYPE("HPIF"), bytes);
Elliott Hughes767a1472011-10-26 18:49:02 -07001608}
1609
Elliott Hughes6a5bd492011-10-28 14:33:57 -07001610enum HpsgSolidity {
1611 SOLIDITY_FREE = 0,
1612 SOLIDITY_HARD = 1,
1613 SOLIDITY_SOFT = 2,
1614 SOLIDITY_WEAK = 3,
1615 SOLIDITY_PHANTOM = 4,
1616 SOLIDITY_FINALIZABLE = 5,
1617 SOLIDITY_SWEEP = 6,
1618};
1619
1620enum HpsgKind {
1621 KIND_OBJECT = 0,
1622 KIND_CLASS_OBJECT = 1,
1623 KIND_ARRAY_1 = 2,
1624 KIND_ARRAY_2 = 3,
1625 KIND_ARRAY_4 = 4,
1626 KIND_ARRAY_8 = 5,
1627 KIND_UNKNOWN = 6,
1628 KIND_NATIVE = 7,
1629};
1630
1631#define HPSG_PARTIAL (1<<7)
1632#define HPSG_STATE(solidity, kind) ((uint8_t)((((kind) & 0x7) << 3) | ((solidity) & 0x7)))
1633
1634struct HeapChunkContext {
1635 std::vector<uint8_t> buf;
1636 uint8_t* p;
1637 uint8_t* pieceLenField;
1638 size_t totalAllocationUnits;
Elliott Hughes82188472011-11-07 18:11:48 -08001639 uint32_t type;
Elliott Hughes6a5bd492011-10-28 14:33:57 -07001640 bool merge;
1641 bool needHeader;
1642
1643 // Maximum chunk size. Obtain this from the formula:
1644 // (((maximum_heap_size / ALLOCATION_UNIT_SIZE) + 255) / 256) * 2
1645 HeapChunkContext(bool merge, bool native)
1646 : buf(16384 - 16),
1647 type(0),
1648 merge(merge) {
1649 Reset();
1650 if (native) {
1651 type = CHUNK_TYPE("NHSG");
1652 } else {
1653 type = merge ? CHUNK_TYPE("HPSG") : CHUNK_TYPE("HPSO");
1654 }
1655 }
1656
1657 ~HeapChunkContext() {
1658 if (p > &buf[0]) {
1659 Flush();
1660 }
1661 }
1662
1663 void EnsureHeader(const void* chunk_ptr) {
1664 if (!needHeader) {
1665 return;
1666 }
1667
1668 // Start a new HPSx chunk.
1669 JDWP::Write4BE(&p, 1); // Heap id (bogus; we only have one heap).
1670 JDWP::Write1BE(&p, 8); // Size of allocation unit, in bytes.
1671
1672 JDWP::Write4BE(&p, reinterpret_cast<uintptr_t>(chunk_ptr)); // virtual address of segment start.
1673 JDWP::Write4BE(&p, 0); // offset of this piece (relative to the virtual address).
1674 // [u4]: length of piece, in allocation units
1675 // We won't know this until we're done, so save the offset and stuff in a dummy value.
1676 pieceLenField = p;
1677 JDWP::Write4BE(&p, 0x55555555);
1678 needHeader = false;
1679 }
1680
1681 void Flush() {
1682 // Patch the "length of piece" field.
1683 CHECK_LE(&buf[0], pieceLenField);
1684 CHECK_LE(pieceLenField, p);
1685 JDWP::Set4BE(pieceLenField, totalAllocationUnits);
1686
1687 Dbg::DdmSendChunk(type, p - &buf[0], &buf[0]);
1688 Reset();
1689 }
1690
Elliott Hughesa2155262011-11-16 16:26:58 -08001691 static void HeapChunkCallback(const void* chunk_ptr, size_t chunk_len, const void* user_ptr, size_t user_len, void* arg) {
1692 reinterpret_cast<HeapChunkContext*>(arg)->HeapChunkCallback(chunk_ptr, chunk_len, user_ptr, user_len);
1693 }
1694
Elliott Hughes6a5bd492011-10-28 14:33:57 -07001695 private:
Elliott Hughesa2155262011-11-16 16:26:58 -08001696 enum { ALLOCATION_UNIT_SIZE = 8 };
1697
Elliott Hughes6a5bd492011-10-28 14:33:57 -07001698 void Reset() {
1699 p = &buf[0];
1700 totalAllocationUnits = 0;
1701 needHeader = true;
1702 pieceLenField = NULL;
1703 }
1704
Elliott Hughesa2155262011-11-16 16:26:58 -08001705 void HeapChunkCallback(const void* chunk_ptr, size_t chunk_len, const void* user_ptr, size_t user_len) {
1706 CHECK_EQ((chunk_len & (ALLOCATION_UNIT_SIZE-1)), 0U);
Elliott Hughes6a5bd492011-10-28 14:33:57 -07001707
Elliott Hughesa2155262011-11-16 16:26:58 -08001708 /* Make sure there's enough room left in the buffer.
1709 * We need to use two bytes for every fractional 256
1710 * allocation units used by the chunk.
1711 */
1712 {
1713 size_t needed = (((chunk_len/ALLOCATION_UNIT_SIZE + 255) / 256) * 2);
1714 size_t bytesLeft = buf.size() - (size_t)(p - &buf[0]);
1715 if (bytesLeft < needed) {
1716 Flush();
1717 }
Elliott Hughes6a5bd492011-10-28 14:33:57 -07001718
Elliott Hughesa2155262011-11-16 16:26:58 -08001719 bytesLeft = buf.size() - (size_t)(p - &buf[0]);
1720 if (bytesLeft < needed) {
1721 LOG(WARNING) << "chunk is too big to transmit (chunk_len=" << chunk_len << ", " << needed << " bytes)";
1722 return;
1723 }
1724 }
1725
1726 // OLD-TODO: notice when there's a gap and start a new heap, or at least a new range.
1727 EnsureHeader(chunk_ptr);
1728
1729 // Determine the type of this chunk.
1730 // OLD-TODO: if context.merge, see if this chunk is different from the last chunk.
1731 // If it's the same, we should combine them.
1732 uint8_t state = ExamineObject(reinterpret_cast<const Object*>(user_ptr), (type == CHUNK_TYPE("NHSG")));
1733
1734 // Write out the chunk description.
1735 chunk_len /= ALLOCATION_UNIT_SIZE; // convert to allocation units
1736 totalAllocationUnits += chunk_len;
1737 while (chunk_len > 256) {
1738 *p++ = state | HPSG_PARTIAL;
1739 *p++ = 255; // length - 1
1740 chunk_len -= 256;
1741 }
1742 *p++ = state;
1743 *p++ = chunk_len - 1;
Elliott Hughes6a5bd492011-10-28 14:33:57 -07001744 }
1745
Elliott Hughesa2155262011-11-16 16:26:58 -08001746 uint8_t ExamineObject(const Object* o, bool is_native_heap) {
1747 if (o == NULL) {
1748 return HPSG_STATE(SOLIDITY_FREE, 0);
1749 }
Elliott Hughes6a5bd492011-10-28 14:33:57 -07001750
Elliott Hughesa2155262011-11-16 16:26:58 -08001751 // It's an allocated chunk. Figure out what it is.
Elliott Hughes6a5bd492011-10-28 14:33:57 -07001752
Elliott Hughesa2155262011-11-16 16:26:58 -08001753 // If we're looking at the native heap, we'll just return
1754 // (SOLIDITY_HARD, KIND_NATIVE) for all allocated chunks.
1755 if (is_native_heap || !Heap::IsLiveObjectLocked(o)) {
1756 return HPSG_STATE(SOLIDITY_HARD, KIND_NATIVE);
1757 }
1758
1759 Class* c = o->GetClass();
1760 if (c == NULL) {
1761 // The object was probably just created but hasn't been initialized yet.
1762 return HPSG_STATE(SOLIDITY_HARD, KIND_OBJECT);
1763 }
1764
1765 if (!Heap::IsHeapAddress(c)) {
1766 LOG(WARNING) << "invalid class for managed heap object: " << o << " " << c;
1767 return HPSG_STATE(SOLIDITY_HARD, KIND_UNKNOWN);
1768 }
1769
1770 if (c->IsClassClass()) {
1771 return HPSG_STATE(SOLIDITY_HARD, KIND_CLASS_OBJECT);
1772 }
1773
1774 if (c->IsArrayClass()) {
1775 if (o->IsObjectArray()) {
1776 return HPSG_STATE(SOLIDITY_HARD, KIND_ARRAY_4);
1777 }
1778 switch (c->GetComponentSize()) {
1779 case 1: return HPSG_STATE(SOLIDITY_HARD, KIND_ARRAY_1);
1780 case 2: return HPSG_STATE(SOLIDITY_HARD, KIND_ARRAY_2);
1781 case 4: return HPSG_STATE(SOLIDITY_HARD, KIND_ARRAY_4);
1782 case 8: return HPSG_STATE(SOLIDITY_HARD, KIND_ARRAY_8);
1783 }
1784 }
1785
Elliott Hughes6a5bd492011-10-28 14:33:57 -07001786 return HPSG_STATE(SOLIDITY_HARD, KIND_OBJECT);
1787 }
1788
Elliott Hughesa2155262011-11-16 16:26:58 -08001789 DISALLOW_COPY_AND_ASSIGN(HeapChunkContext);
1790};
Elliott Hughes6a5bd492011-10-28 14:33:57 -07001791
1792void Dbg::DdmSendHeapSegments(bool native) {
1793 Dbg::HpsgWhen when;
1794 Dbg::HpsgWhat what;
1795 if (!native) {
1796 when = gDdmHpsgWhen;
1797 what = gDdmHpsgWhat;
1798 } else {
1799 when = gDdmNhsgWhen;
1800 what = gDdmNhsgWhat;
1801 }
1802 if (when == HPSG_WHEN_NEVER) {
1803 return;
1804 }
1805
1806 // Figure out what kind of chunks we'll be sending.
1807 CHECK(what == HPSG_WHAT_MERGED_OBJECTS || what == HPSG_WHAT_DISTINCT_OBJECTS) << static_cast<int>(what);
1808
1809 // First, send a heap start chunk.
1810 uint8_t heap_id[4];
1811 JDWP::Set4BE(&heap_id[0], 1); // Heap id (bogus; we only have one heap).
1812 Dbg::DdmSendChunk(native ? CHUNK_TYPE("NHST") : CHUNK_TYPE("HPST"), sizeof(heap_id), heap_id);
1813
1814 // Send a series of heap segment chunks.
Elliott Hughesa2155262011-11-16 16:26:58 -08001815 HeapChunkContext context((what == HPSG_WHAT_MERGED_OBJECTS), native);
1816 if (native) {
1817 dlmalloc_walk_heap(HeapChunkContext::HeapChunkCallback, &context);
1818 } else {
1819 Heap::WalkHeap(HeapChunkContext::HeapChunkCallback, &context);
1820 }
Elliott Hughes6a5bd492011-10-28 14:33:57 -07001821
1822 // Finally, send a heap end chunk.
1823 Dbg::DdmSendChunk(native ? CHUNK_TYPE("NHEN") : CHUNK_TYPE("HPEN"), sizeof(heap_id), heap_id);
Elliott Hughes767a1472011-10-26 18:49:02 -07001824}
1825
Elliott Hughes545a0642011-11-08 19:10:03 -08001826void Dbg::SetAllocTrackingEnabled(bool enabled) {
1827 MutexLock mu(gAllocTrackerLock);
1828 if (enabled) {
1829 if (recent_allocation_records_ == NULL) {
1830 LOG(INFO) << "Enabling alloc tracker (" << kNumAllocRecords << " entries, "
1831 << kMaxAllocRecordStackDepth << " frames --> "
1832 << (sizeof(AllocRecord) * kNumAllocRecords) << " bytes)";
1833 gAllocRecordHead = gAllocRecordCount = 0;
1834 recent_allocation_records_ = new AllocRecord[kNumAllocRecords];
1835 CHECK(recent_allocation_records_ != NULL);
1836 }
1837 } else {
1838 delete[] recent_allocation_records_;
1839 recent_allocation_records_ = NULL;
1840 }
1841}
1842
1843struct AllocRecordStackVisitor : public Thread::StackVisitor {
1844 AllocRecordStackVisitor(AllocRecord* record) : record(record), depth(0) {
1845 }
1846
1847 virtual void VisitFrame(const Frame& f, uintptr_t pc) {
1848 if (depth >= kMaxAllocRecordStackDepth) {
1849 return;
1850 }
1851 Method* m = f.GetMethod();
1852 if (m == NULL || m->IsCalleeSaveMethod()) {
1853 return;
1854 }
1855 record->stack[depth].method = m;
1856 record->stack[depth].raw_pc = pc;
1857 ++depth;
1858 }
1859
1860 ~AllocRecordStackVisitor() {
1861 // Clear out any unused stack trace elements.
1862 for (; depth < kMaxAllocRecordStackDepth; ++depth) {
1863 record->stack[depth].method = NULL;
1864 record->stack[depth].raw_pc = 0;
1865 }
1866 }
1867
1868 AllocRecord* record;
1869 size_t depth;
1870};
1871
1872void Dbg::RecordAllocation(Class* type, size_t byte_count) {
1873 Thread* self = Thread::Current();
1874 CHECK(self != NULL);
1875
1876 MutexLock mu(gAllocTrackerLock);
1877 if (recent_allocation_records_ == NULL) {
1878 return;
1879 }
1880
1881 // Advance and clip.
1882 if (++gAllocRecordHead == kNumAllocRecords) {
1883 gAllocRecordHead = 0;
1884 }
1885
1886 // Fill in the basics.
1887 AllocRecord* record = &recent_allocation_records_[gAllocRecordHead];
1888 record->type = type;
1889 record->byte_count = byte_count;
1890 record->thin_lock_id = self->GetThinLockId();
1891
1892 // Fill in the stack trace.
1893 AllocRecordStackVisitor visitor(record);
1894 self->WalkStack(&visitor);
1895
1896 if (gAllocRecordCount < kNumAllocRecords) {
1897 ++gAllocRecordCount;
1898 }
1899}
1900
1901/*
1902 * Return the index of the head element.
1903 *
1904 * We point at the most-recently-written record, so if allocRecordCount is 1
1905 * we want to use the current element. Take "head+1" and subtract count
1906 * from it.
1907 *
1908 * We need to handle underflow in our circular buffer, so we add
1909 * kNumAllocRecords and then mask it back down.
1910 */
1911inline static int headIndex() {
1912 return (gAllocRecordHead+1 + kNumAllocRecords - gAllocRecordCount) & (kNumAllocRecords-1);
1913}
1914
1915void Dbg::DumpRecentAllocations() {
1916 MutexLock mu(gAllocTrackerLock);
1917 if (recent_allocation_records_ == NULL) {
1918 LOG(INFO) << "Not recording tracked allocations";
1919 return;
1920 }
1921
1922 // "i" is the head of the list. We want to start at the end of the
1923 // list and move forward to the tail.
1924 size_t i = headIndex();
1925 size_t count = gAllocRecordCount;
1926
1927 LOG(INFO) << "Tracked allocations, (head=" << gAllocRecordHead << " count=" << count << ")";
1928 while (count--) {
1929 AllocRecord* record = &recent_allocation_records_[i];
1930
1931 LOG(INFO) << StringPrintf(" T=%-2d %6d ", record->thin_lock_id, record->byte_count)
1932 << PrettyClass(record->type);
1933
1934 for (size_t stack_frame = 0; stack_frame < kMaxAllocRecordStackDepth; ++stack_frame) {
1935 const Method* m = record->stack[stack_frame].method;
1936 if (m == NULL) {
1937 break;
1938 }
1939 LOG(INFO) << " " << PrettyMethod(m) << " line " << record->stack[stack_frame].LineNumber();
1940 }
1941
1942 // pause periodically to help logcat catch up
1943 if ((count % 5) == 0) {
1944 usleep(40000);
1945 }
1946
1947 i = (i + 1) & (kNumAllocRecords-1);
1948 }
1949}
1950
1951class StringTable {
1952 public:
1953 StringTable() {
1954 }
1955
1956 void Add(const String* s) {
1957 table_.insert(s);
1958 }
1959
1960 size_t IndexOf(const String* s) {
1961 return std::distance(table_.begin(), table_.find(s));
1962 }
1963
1964 size_t Size() {
1965 return table_.size();
1966 }
1967
1968 void WriteTo(std::vector<uint8_t>& bytes) {
1969 typedef std::set<const String*>::const_iterator It; // TODO: C++0x auto
1970 for (It it = table_.begin(); it != table_.end(); ++it) {
1971 const String* s = *it;
1972 JDWP::AppendUtf16BE(bytes, s->GetCharArray()->GetData(), s->GetLength());
1973 }
1974 }
1975
1976 private:
1977 std::set<const String*> table_;
1978 DISALLOW_COPY_AND_ASSIGN(StringTable);
1979};
1980
1981/*
1982 * The data we send to DDMS contains everything we have recorded.
1983 *
1984 * Message header (all values big-endian):
1985 * (1b) message header len (to allow future expansion); includes itself
1986 * (1b) entry header len
1987 * (1b) stack frame len
1988 * (2b) number of entries
1989 * (4b) offset to string table from start of message
1990 * (2b) number of class name strings
1991 * (2b) number of method name strings
1992 * (2b) number of source file name strings
1993 * For each entry:
1994 * (4b) total allocation size
1995 * (2b) threadId
1996 * (2b) allocated object's class name index
1997 * (1b) stack depth
1998 * For each stack frame:
1999 * (2b) method's class name
2000 * (2b) method name
2001 * (2b) method source file
2002 * (2b) line number, clipped to 32767; -2 if native; -1 if no source
2003 * (xb) class name strings
2004 * (xb) method name strings
2005 * (xb) source file strings
2006 *
2007 * As with other DDM traffic, strings are sent as a 4-byte length
2008 * followed by UTF-16 data.
2009 *
2010 * We send up 16-bit unsigned indexes into string tables. In theory there
2011 * can be (kMaxAllocRecordStackDepth * kNumAllocRecords) unique strings in
2012 * each table, but in practice there should be far fewer.
2013 *
2014 * The chief reason for using a string table here is to keep the size of
2015 * the DDMS message to a minimum. This is partly to make the protocol
2016 * efficient, but also because we have to form the whole thing up all at
2017 * once in a memory buffer.
2018 *
2019 * We use separate string tables for class names, method names, and source
2020 * files to keep the indexes small. There will generally be no overlap
2021 * between the contents of these tables.
2022 */
2023jbyteArray Dbg::GetRecentAllocations() {
2024 if (false) {
2025 DumpRecentAllocations();
2026 }
2027
2028 MutexLock mu(gAllocTrackerLock);
2029
2030 /*
2031 * Part 1: generate string tables.
2032 */
2033 StringTable class_names;
2034 StringTable method_names;
2035 StringTable filenames;
2036
2037 int count = gAllocRecordCount;
2038 int idx = headIndex();
2039 while (count--) {
2040 AllocRecord* record = &recent_allocation_records_[idx];
2041
2042 class_names.Add(record->type->GetDescriptor());
2043
2044 for (size_t i = 0; i < kMaxAllocRecordStackDepth; i++) {
2045 const Method* m = record->stack[i].method;
2046 if (m != NULL) {
2047 class_names.Add(m->GetDeclaringClass()->GetDescriptor());
2048 method_names.Add(m->GetName());
2049 filenames.Add(m->GetDeclaringClass()->GetSourceFile());
2050 }
2051 }
2052
2053 idx = (idx + 1) & (kNumAllocRecords-1);
2054 }
2055
2056 LOG(INFO) << "allocation records: " << gAllocRecordCount;
2057
2058 /*
2059 * Part 2: allocate a buffer and generate the output.
2060 */
2061 std::vector<uint8_t> bytes;
2062
2063 // (1b) message header len (to allow future expansion); includes itself
2064 // (1b) entry header len
2065 // (1b) stack frame len
2066 const int kMessageHeaderLen = 15;
2067 const int kEntryHeaderLen = 9;
2068 const int kStackFrameLen = 8;
2069 JDWP::Append1BE(bytes, kMessageHeaderLen);
2070 JDWP::Append1BE(bytes, kEntryHeaderLen);
2071 JDWP::Append1BE(bytes, kStackFrameLen);
2072
2073 // (2b) number of entries
2074 // (4b) offset to string table from start of message
2075 // (2b) number of class name strings
2076 // (2b) number of method name strings
2077 // (2b) number of source file name strings
2078 JDWP::Append2BE(bytes, gAllocRecordCount);
2079 size_t string_table_offset = bytes.size();
2080 JDWP::Append4BE(bytes, 0); // We'll patch this later...
2081 JDWP::Append2BE(bytes, class_names.Size());
2082 JDWP::Append2BE(bytes, method_names.Size());
2083 JDWP::Append2BE(bytes, filenames.Size());
2084
2085 count = gAllocRecordCount;
2086 idx = headIndex();
2087 while (count--) {
2088 // For each entry:
2089 // (4b) total allocation size
2090 // (2b) thread id
2091 // (2b) allocated object's class name index
2092 // (1b) stack depth
2093 AllocRecord* record = &recent_allocation_records_[idx];
2094 size_t stack_depth = record->GetDepth();
2095 JDWP::Append4BE(bytes, record->byte_count);
2096 JDWP::Append2BE(bytes, record->thin_lock_id);
2097 JDWP::Append2BE(bytes, class_names.IndexOf(record->type->GetDescriptor()));
2098 JDWP::Append1BE(bytes, stack_depth);
2099
2100 for (size_t stack_frame = 0; stack_frame < stack_depth; ++stack_frame) {
2101 // For each stack frame:
2102 // (2b) method's class name
2103 // (2b) method name
2104 // (2b) method source file
2105 // (2b) line number, clipped to 32767; -2 if native; -1 if no source
2106 const Method* m = record->stack[stack_frame].method;
2107 JDWP::Append2BE(bytes, class_names.IndexOf(m->GetDeclaringClass()->GetDescriptor()));
2108 JDWP::Append2BE(bytes, method_names.IndexOf(m->GetName()));
2109 JDWP::Append2BE(bytes, filenames.IndexOf(m->GetDeclaringClass()->GetSourceFile()));
2110 JDWP::Append2BE(bytes, record->stack[stack_frame].LineNumber());
2111 }
2112
2113 idx = (idx + 1) & (kNumAllocRecords-1);
2114 }
2115
2116 // (xb) class name strings
2117 // (xb) method name strings
2118 // (xb) source file strings
2119 JDWP::Set4BE(&bytes[string_table_offset], bytes.size());
2120 class_names.WriteTo(bytes);
2121 method_names.WriteTo(bytes);
2122 filenames.WriteTo(bytes);
2123
2124 JNIEnv* env = Thread::Current()->GetJniEnv();
2125 jbyteArray result = env->NewByteArray(bytes.size());
2126 if (result != NULL) {
2127 env->SetByteArrayRegion(result, 0, bytes.size(), reinterpret_cast<const jbyte*>(&bytes[0]));
2128 }
2129 return result;
2130}
2131
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002132} // namespace art