blob: cdb17d3d4f782cfdb456d21e01b4195c623242e3 [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 Hughes6a5bd492011-10-28 14:33:57 -070024#include "ScopedLocalRef.h"
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -070025#include "ScopedPrimitiveArray.h"
Elliott Hughes47fce012011-10-25 18:37:19 -070026#include "stack_indirect_reference_table.h"
Elliott Hughes475fc232011-10-25 15:00:35 -070027#include "thread_list.h"
28
Elliott Hughes6a5bd492011-10-28 14:33:57 -070029extern "C" void dlmalloc_walk_heap(void(*)(const void*, size_t, const void*, size_t, void*), void*);
30#ifndef HAVE_ANDROID_OS
31void dlmalloc_walk_heap(void(*)(const void*, size_t, const void*, size_t, void*), void*) {
32 // No-op for glibc.
33}
34#endif
35
Elliott Hughes872d4ec2011-10-21 17:07:15 -070036namespace art {
37
Elliott Hughes545a0642011-11-08 19:10:03 -080038static const size_t kMaxAllocRecordStackDepth = 16; // Max 255.
39static const size_t kNumAllocRecords = 512; // Must be power of 2.
40
Elliott Hughes475fc232011-10-25 15:00:35 -070041class ObjectRegistry {
42 public:
43 ObjectRegistry() : lock_("ObjectRegistry lock") {
44 }
45
46 JDWP::ObjectId Add(Object* o) {
47 if (o == NULL) {
48 return 0;
49 }
50 JDWP::ObjectId id = static_cast<JDWP::ObjectId>(reinterpret_cast<uintptr_t>(o));
51 MutexLock mu(lock_);
52 map_[id] = o;
53 return id;
54 }
55
Elliott Hughes234ab152011-10-26 14:02:26 -070056 void Clear() {
57 MutexLock mu(lock_);
58 LOG(DEBUG) << "Debugger has detached; object registry had " << map_.size() << " entries";
59 map_.clear();
60 }
61
Elliott Hughes475fc232011-10-25 15:00:35 -070062 bool Contains(JDWP::ObjectId id) {
63 MutexLock mu(lock_);
64 return map_.find(id) != map_.end();
65 }
66
Elliott Hughesa2155262011-11-16 16:26:58 -080067 template<typename T> T Get(JDWP::ObjectId id) {
68 MutexLock mu(lock_);
69 typedef std::map<JDWP::ObjectId, Object*>::iterator It; // C++0x auto
70 It it = map_.find(id);
71 return (it != map_.end()) ? reinterpret_cast<T>(it->second) : NULL;
72 }
73
Elliott Hughesbfe487b2011-10-26 15:48:55 -070074 void VisitRoots(Heap::RootVisitor* visitor, void* arg) {
75 MutexLock mu(lock_);
76 typedef std::map<JDWP::ObjectId, Object*>::iterator It; // C++0x auto
77 for (It it = map_.begin(); it != map_.end(); ++it) {
78 visitor(it->second, arg);
79 }
80 }
81
Elliott Hughes475fc232011-10-25 15:00:35 -070082 private:
83 Mutex lock_;
84 std::map<JDWP::ObjectId, Object*> map_;
85};
86
Elliott Hughes545a0642011-11-08 19:10:03 -080087struct AllocRecordStackTraceElement {
88 const Method* method;
89 uintptr_t raw_pc;
90
91 int32_t LineNumber() const {
92 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
93 Class* c = method->GetDeclaringClass();
94 DexCache* dex_cache = c->GetDexCache();
95 const DexFile& dex_file = class_linker->FindDexFile(dex_cache);
96 return dex_file.GetLineNumFromPC(method, method->ToDexPC(raw_pc));
97 }
98};
99
100struct AllocRecord {
101 Class* type;
102 size_t byte_count;
103 uint16_t thin_lock_id;
104 AllocRecordStackTraceElement stack[kMaxAllocRecordStackDepth]; // Unused entries have NULL method.
105
106 size_t GetDepth() {
107 size_t depth = 0;
108 while (depth < kMaxAllocRecordStackDepth && stack[depth].method != NULL) {
109 ++depth;
110 }
111 return depth;
112 }
113};
114
Elliott Hughes4ffd3132011-10-24 12:06:42 -0700115// JDWP is allowed unless the Zygote forbids it.
116static bool gJdwpAllowed = true;
117
Elliott Hughes3bb81562011-10-21 18:52:59 -0700118// Was there a -Xrunjdwp or -agent argument on the command-line?
119static bool gJdwpConfigured = false;
120
121// Broken-down JDWP options. (Only valid if gJdwpConfigured is true.)
Elliott Hughes376a7a02011-10-24 18:35:55 -0700122static JDWP::JdwpOptions gJdwpOptions;
Elliott Hughes3bb81562011-10-21 18:52:59 -0700123
124// Runtime JDWP state.
125static JDWP::JdwpState* gJdwpState = NULL;
126static bool gDebuggerConnected; // debugger or DDMS is connected.
127static bool gDebuggerActive; // debugger is making requests.
128
Elliott Hughes47fce012011-10-25 18:37:19 -0700129static bool gDdmThreadNotification = false;
130
Elliott Hughes767a1472011-10-26 18:49:02 -0700131// DDMS GC-related settings.
132static Dbg::HpifWhen gDdmHpifWhen = Dbg::HPIF_WHEN_NEVER;
133static Dbg::HpsgWhen gDdmHpsgWhen = Dbg::HPSG_WHEN_NEVER;
134static Dbg::HpsgWhat gDdmHpsgWhat;
135static Dbg::HpsgWhen gDdmNhsgWhen = Dbg::HPSG_WHEN_NEVER;
136static Dbg::HpsgWhat gDdmNhsgWhat;
137
Elliott Hughes475fc232011-10-25 15:00:35 -0700138static ObjectRegistry* gRegistry = NULL;
139
Elliott Hughes545a0642011-11-08 19:10:03 -0800140// Recent allocation tracking.
141static Mutex gAllocTrackerLock("AllocTracker lock");
142AllocRecord* Dbg::recent_allocation_records_ = NULL; // TODO: CircularBuffer<AllocRecord>
143static size_t gAllocRecordHead = 0;
144static size_t gAllocRecordCount = 0;
145
Elliott Hughes3bb81562011-10-21 18:52:59 -0700146/*
147 * Handle one of the JDWP name/value pairs.
148 *
149 * JDWP options are:
150 * help: if specified, show help message and bail
151 * transport: may be dt_socket or dt_shmem
152 * address: for dt_socket, "host:port", or just "port" when listening
153 * server: if "y", wait for debugger to attach; if "n", attach to debugger
154 * timeout: how long to wait for debugger to connect / listen
155 *
156 * Useful with server=n (these aren't supported yet):
157 * onthrow=<exception-name>: connect to debugger when exception thrown
158 * onuncaught=y|n: connect to debugger when uncaught exception thrown
159 * launch=<command-line>: launch the debugger itself
160 *
161 * The "transport" option is required, as is "address" if server=n.
162 */
163static bool ParseJdwpOption(const std::string& name, const std::string& value) {
164 if (name == "transport") {
165 if (value == "dt_socket") {
Elliott Hughes376a7a02011-10-24 18:35:55 -0700166 gJdwpOptions.transport = JDWP::kJdwpTransportSocket;
Elliott Hughes3bb81562011-10-21 18:52:59 -0700167 } else if (value == "dt_android_adb") {
Elliott Hughes376a7a02011-10-24 18:35:55 -0700168 gJdwpOptions.transport = JDWP::kJdwpTransportAndroidAdb;
Elliott Hughes3bb81562011-10-21 18:52:59 -0700169 } else {
170 LOG(ERROR) << "JDWP transport not supported: " << value;
171 return false;
172 }
173 } else if (name == "server") {
174 if (value == "n") {
Elliott Hughes376a7a02011-10-24 18:35:55 -0700175 gJdwpOptions.server = false;
Elliott Hughes3bb81562011-10-21 18:52:59 -0700176 } else if (value == "y") {
Elliott Hughes376a7a02011-10-24 18:35:55 -0700177 gJdwpOptions.server = true;
Elliott Hughes3bb81562011-10-21 18:52:59 -0700178 } else {
179 LOG(ERROR) << "JDWP option 'server' must be 'y' or 'n'";
180 return false;
181 }
182 } else if (name == "suspend") {
183 if (value == "n") {
Elliott Hughes376a7a02011-10-24 18:35:55 -0700184 gJdwpOptions.suspend = false;
Elliott Hughes3bb81562011-10-21 18:52:59 -0700185 } else if (value == "y") {
Elliott Hughes376a7a02011-10-24 18:35:55 -0700186 gJdwpOptions.suspend = true;
Elliott Hughes3bb81562011-10-21 18:52:59 -0700187 } else {
188 LOG(ERROR) << "JDWP option 'suspend' must be 'y' or 'n'";
189 return false;
190 }
191 } else if (name == "address") {
192 /* this is either <port> or <host>:<port> */
193 std::string port_string;
Elliott Hughes376a7a02011-10-24 18:35:55 -0700194 gJdwpOptions.host.clear();
Elliott Hughes3bb81562011-10-21 18:52:59 -0700195 std::string::size_type colon = value.find(':');
196 if (colon != std::string::npos) {
Elliott Hughes376a7a02011-10-24 18:35:55 -0700197 gJdwpOptions.host = value.substr(0, colon);
Elliott Hughes3bb81562011-10-21 18:52:59 -0700198 port_string = value.substr(colon + 1);
199 } else {
200 port_string = value;
201 }
202 if (port_string.empty()) {
203 LOG(ERROR) << "JDWP address missing port: " << value;
204 return false;
205 }
206 char* end;
207 long port = strtol(port_string.c_str(), &end, 10);
208 if (*end != '\0') {
209 LOG(ERROR) << "JDWP address has junk in port field: " << value;
210 return false;
211 }
Elliott Hughes376a7a02011-10-24 18:35:55 -0700212 gJdwpOptions.port = port;
Elliott Hughes3bb81562011-10-21 18:52:59 -0700213 } else if (name == "launch" || name == "onthrow" || name == "oncaught" || name == "timeout") {
214 /* valid but unsupported */
215 LOG(INFO) << "Ignoring JDWP option '" << name << "'='" << value << "'";
216 } else {
217 LOG(INFO) << "Ignoring unrecognized JDWP option '" << name << "'='" << value << "'";
218 }
219
220 return true;
221}
222
223/*
224 * Parse the latter half of a -Xrunjdwp/-agentlib:jdwp= string, e.g.:
225 * "transport=dt_socket,address=8000,server=y,suspend=n"
226 */
227bool Dbg::ParseJdwpOptions(const std::string& options) {
Elliott Hughes47fce012011-10-25 18:37:19 -0700228 LOG(VERBOSE) << "ParseJdwpOptions: " << options;
229
Elliott Hughes3bb81562011-10-21 18:52:59 -0700230 std::vector<std::string> pairs;
231 Split(options, ',', pairs);
232
233 for (size_t i = 0; i < pairs.size(); ++i) {
234 std::string::size_type equals = pairs[i].find('=');
235 if (equals == std::string::npos) {
236 LOG(ERROR) << "Can't parse JDWP option '" << pairs[i] << "' in '" << options << "'";
237 return false;
238 }
239 ParseJdwpOption(pairs[i].substr(0, equals), pairs[i].substr(equals + 1));
240 }
241
Elliott Hughes376a7a02011-10-24 18:35:55 -0700242 if (gJdwpOptions.transport == JDWP::kJdwpTransportUnknown) {
Elliott Hughes3bb81562011-10-21 18:52:59 -0700243 LOG(ERROR) << "Must specify JDWP transport: " << options;
244 }
Elliott Hughes376a7a02011-10-24 18:35:55 -0700245 if (!gJdwpOptions.server && (gJdwpOptions.host.empty() || gJdwpOptions.port == 0)) {
Elliott Hughes3bb81562011-10-21 18:52:59 -0700246 LOG(ERROR) << "Must specify JDWP host and port when server=n: " << options;
247 return false;
248 }
249
250 gJdwpConfigured = true;
251 return true;
252}
253
Elliott Hughesd1cc8362011-10-24 16:58:50 -0700254void Dbg::StartJdwp() {
Elliott Hughes376a7a02011-10-24 18:35:55 -0700255 if (!gJdwpAllowed || !gJdwpConfigured) {
256 // No JDWP for you!
257 return;
258 }
259
Elliott Hughes475fc232011-10-25 15:00:35 -0700260 CHECK(gRegistry == NULL);
261 gRegistry = new ObjectRegistry;
262
Elliott Hughesd1cc8362011-10-24 16:58:50 -0700263 // Init JDWP if the debugger is enabled. This may connect out to a
264 // debugger, passively listen for a debugger, or block waiting for a
265 // debugger.
Elliott Hughes376a7a02011-10-24 18:35:55 -0700266 gJdwpState = JDWP::JdwpState::Create(&gJdwpOptions);
267 if (gJdwpState == NULL) {
268 LOG(WARNING) << "debugger thread failed to initialize";
Elliott Hughes475fc232011-10-25 15:00:35 -0700269 return;
Elliott Hughesd1cc8362011-10-24 16:58:50 -0700270 }
271
272 // If a debugger has already attached, send the "welcome" message.
273 // This may cause us to suspend all threads.
Elliott Hughes376a7a02011-10-24 18:35:55 -0700274 if (gJdwpState->IsActive()) {
Elliott Hughesa2155262011-11-16 16:26:58 -0800275 //ScopedThreadStateChange tsc(Thread::Current(), Thread::kRunnable);
Elliott Hughes376a7a02011-10-24 18:35:55 -0700276 if (!gJdwpState->PostVMStart()) {
Elliott Hughesd1cc8362011-10-24 16:58:50 -0700277 LOG(WARNING) << "failed to post 'start' message to debugger";
278 }
279 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700280}
281
Elliott Hughesd1cc8362011-10-24 16:58:50 -0700282void Dbg::StopJdwp() {
Elliott Hughes376a7a02011-10-24 18:35:55 -0700283 delete gJdwpState;
Elliott Hughes475fc232011-10-25 15:00:35 -0700284 delete gRegistry;
285 gRegistry = NULL;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700286}
287
Elliott Hughes767a1472011-10-26 18:49:02 -0700288void Dbg::GcDidFinish() {
289 if (gDdmHpifWhen != HPIF_WHEN_NEVER) {
290 LOG(DEBUG) << "Sending VM heap info to DDM";
Elliott Hughes7162ad92011-10-27 14:08:42 -0700291 DdmSendHeapInfo(gDdmHpifWhen);
Elliott Hughes767a1472011-10-26 18:49:02 -0700292 }
293 if (gDdmHpsgWhen != HPSG_WHEN_NEVER) {
294 LOG(DEBUG) << "Dumping VM heap to DDM";
Elliott Hughes6a5bd492011-10-28 14:33:57 -0700295 DdmSendHeapSegments(false);
Elliott Hughes767a1472011-10-26 18:49:02 -0700296 }
297 if (gDdmNhsgWhen != HPSG_WHEN_NEVER) {
298 LOG(DEBUG) << "Dumping native heap to DDM";
Elliott Hughes6a5bd492011-10-28 14:33:57 -0700299 DdmSendHeapSegments(true);
Elliott Hughes767a1472011-10-26 18:49:02 -0700300 }
301}
302
Elliott Hughes4ffd3132011-10-24 12:06:42 -0700303void Dbg::SetJdwpAllowed(bool allowed) {
304 gJdwpAllowed = allowed;
305}
306
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700307DebugInvokeReq* Dbg::GetInvokeReq() {
Elliott Hughes475fc232011-10-25 15:00:35 -0700308 return Thread::Current()->GetInvokeReq();
309}
310
311Thread* Dbg::GetDebugThread() {
312 return (gJdwpState != NULL) ? gJdwpState->GetDebugThread() : NULL;
313}
314
315void Dbg::ClearWaitForEventThread() {
316 gJdwpState->ClearWaitForEventThread();
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700317}
318
319void Dbg::Connected() {
Elliott Hughes3bb81562011-10-21 18:52:59 -0700320 CHECK(!gDebuggerConnected);
321 LOG(VERBOSE) << "JDWP has attached";
322 gDebuggerConnected = true;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700323}
324
Elliott Hughesa2155262011-11-16 16:26:58 -0800325void Dbg::GoActive() {
326 // Enable all debugging features, including scans for breakpoints.
327 // This is a no-op if we're already active.
328 // Only called from the JDWP handler thread.
329 if (gDebuggerActive) {
330 return;
331 }
332
333 LOG(INFO) << "Debugger is active";
334
335 // TODO: CHECK we don't have any outstanding breakpoints.
336
337 gDebuggerActive = true;
338
339 //dvmEnableAllSubMode(kSubModeDebuggerActive);
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700340}
341
342void Dbg::Disconnected() {
Elliott Hughes234ab152011-10-26 14:02:26 -0700343 CHECK(gDebuggerConnected);
344
345 gDebuggerActive = false;
346
347 //dvmDisableAllSubMode(kSubModeDebuggerActive);
348
349 gRegistry->Clear();
350 gDebuggerConnected = false;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700351}
352
353bool Dbg::IsDebuggerConnected() {
Elliott Hughes3bb81562011-10-21 18:52:59 -0700354 return gDebuggerActive;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700355}
356
357bool Dbg::IsDebuggingEnabled() {
Elliott Hughes3bb81562011-10-21 18:52:59 -0700358 return gJdwpConfigured;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700359}
360
361int64_t Dbg::LastDebuggerActivity() {
362 UNIMPLEMENTED(WARNING);
363 return -1;
364}
365
366int Dbg::ThreadRunning() {
Elliott Hughesd1cc8362011-10-24 16:58:50 -0700367 return static_cast<int>(Thread::Current()->SetState(Thread::kRunnable));
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700368}
369
370int Dbg::ThreadWaiting() {
Elliott Hughesd1cc8362011-10-24 16:58:50 -0700371 return static_cast<int>(Thread::Current()->SetState(Thread::kVmWait));
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700372}
373
Elliott Hughes6ba581a2011-10-25 11:45:35 -0700374int Dbg::ThreadContinuing(int new_state) {
375 return static_cast<int>(Thread::Current()->SetState(static_cast<Thread::State>(new_state)));
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700376}
377
378void Dbg::UndoDebuggerSuspensions() {
Elliott Hughes234ab152011-10-26 14:02:26 -0700379 Runtime::Current()->GetThreadList()->UndoDebuggerSuspensions();
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700380}
381
382void Dbg::Exit(int status) {
383 UNIMPLEMENTED(FATAL);
384}
385
Elliott Hughesbfe487b2011-10-26 15:48:55 -0700386void Dbg::VisitRoots(Heap::RootVisitor* visitor, void* arg) {
387 if (gRegistry != NULL) {
388 gRegistry->VisitRoots(visitor, arg);
389 }
390}
391
Elliott Hughesa2155262011-11-16 16:26:58 -0800392std::string Dbg::GetClassDescriptor(JDWP::RefTypeId classId) {
393 Class* c = gRegistry->Get<Class*>(classId);
394 return c->GetDescriptor()->ToModifiedUtf8();
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700395}
396
397JDWP::ObjectId Dbg::GetClassObject(JDWP::RefTypeId id) {
398 UNIMPLEMENTED(FATAL);
399 return 0;
400}
401
402JDWP::RefTypeId Dbg::GetSuperclass(JDWP::RefTypeId id) {
403 UNIMPLEMENTED(FATAL);
404 return 0;
405}
406
407JDWP::ObjectId Dbg::GetClassLoader(JDWP::RefTypeId id) {
408 UNIMPLEMENTED(FATAL);
409 return 0;
410}
411
412uint32_t Dbg::GetAccessFlags(JDWP::RefTypeId id) {
413 UNIMPLEMENTED(FATAL);
414 return 0;
415}
416
417bool Dbg::IsInterface(JDWP::RefTypeId id) {
418 UNIMPLEMENTED(FATAL);
419 return false;
420}
421
Elliott Hughesa2155262011-11-16 16:26:58 -0800422void Dbg::GetClassList(uint32_t* pClassCount, JDWP::RefTypeId** pClasses) {
423 // Get the complete list of reference classes (i.e. all classes except
424 // the primitive types).
425 // Returns a newly-allocated buffer full of RefTypeId values.
426 struct ClassListCreator {
427 static bool Visit(Class* c, void* arg) {
428 return reinterpret_cast<ClassListCreator*>(arg)->Visit(c);
429 }
430
431 bool Visit(Class* c) {
432 if (!c->IsPrimitive()) {
433 classes.push_back(static_cast<JDWP::RefTypeId>(gRegistry->Add(c)));
434 }
435 return true;
436 }
437
438 std::vector<JDWP::RefTypeId> classes;
439 };
440
441 ClassListCreator clc;
442 Runtime::Current()->GetClassLinker()->VisitClasses(ClassListCreator::Visit, &clc);
443 *pClassCount = clc.classes.size();
444 *pClasses = new JDWP::RefTypeId[clc.classes.size()];
445 for (size_t i = 0; i < clc.classes.size(); ++i) {
446 (*pClasses)[i] = clc.classes[i];
447 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700448}
449
450void Dbg::GetVisibleClassList(JDWP::ObjectId classLoaderId, uint32_t* pNumClasses, JDWP::RefTypeId** pClassRefBuf) {
451 UNIMPLEMENTED(FATAL);
452}
453
Elliott Hughesa2155262011-11-16 16:26:58 -0800454void Dbg::GetClassInfo(JDWP::RefTypeId classId, uint8_t* pTypeTag, uint32_t* pStatus, std::string* pDescriptor) {
455 Class* c = gRegistry->Get<Class*>(classId);
456 if (c->IsArrayClass()) {
457 *pStatus = JDWP::CS_VERIFIED | JDWP::CS_PREPARED;
458 *pTypeTag = JDWP::TT_ARRAY;
459 } else {
460 if (c->IsErroneous()) {
461 *pStatus = JDWP::CS_ERROR;
462 } else {
463 *pStatus = JDWP::CS_VERIFIED | JDWP::CS_PREPARED | JDWP::CS_INITIALIZED;
464 }
465 *pTypeTag = c->IsInterface() ? JDWP::TT_INTERFACE : JDWP::TT_CLASS;
466 }
467
468 if (pDescriptor != NULL) {
469 *pDescriptor = c->GetDescriptor()->ToModifiedUtf8();
470 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700471}
472
473bool Dbg::FindLoadedClassBySignature(const char* classDescriptor, JDWP::RefTypeId* pRefTypeId) {
474 UNIMPLEMENTED(FATAL);
475 return false;
476}
477
478void Dbg::GetObjectType(JDWP::ObjectId objectId, uint8_t* pRefTypeTag, JDWP::RefTypeId* pRefTypeId) {
479 UNIMPLEMENTED(FATAL);
480}
481
482uint8_t Dbg::GetClassObjectType(JDWP::RefTypeId refTypeId) {
483 UNIMPLEMENTED(FATAL);
484 return 0;
485}
486
487const char* Dbg::GetSignature(JDWP::RefTypeId refTypeId) {
488 UNIMPLEMENTED(FATAL);
489 return NULL;
490}
491
492const char* Dbg::GetSourceFile(JDWP::RefTypeId refTypeId) {
493 UNIMPLEMENTED(FATAL);
494 return NULL;
495}
496
497const char* Dbg::GetObjectTypeName(JDWP::ObjectId objectId) {
498 UNIMPLEMENTED(FATAL);
499 return NULL;
500}
501
502uint8_t Dbg::GetObjectTag(JDWP::ObjectId objectId) {
503 UNIMPLEMENTED(FATAL);
504 return 0;
505}
506
507int Dbg::GetTagWidth(int tag) {
508 UNIMPLEMENTED(FATAL);
509 return 0;
510}
511
512int Dbg::GetArrayLength(JDWP::ObjectId arrayId) {
513 UNIMPLEMENTED(FATAL);
514 return 0;
515}
516
517uint8_t Dbg::GetArrayElementTag(JDWP::ObjectId arrayId) {
518 UNIMPLEMENTED(FATAL);
519 return 0;
520}
521
522bool Dbg::OutputArray(JDWP::ObjectId arrayId, int firstIndex, int count, JDWP::ExpandBuf* pReply) {
523 UNIMPLEMENTED(FATAL);
524 return false;
525}
526
527bool Dbg::SetArrayElements(JDWP::ObjectId arrayId, int firstIndex, int count, const uint8_t* buf) {
528 UNIMPLEMENTED(FATAL);
529 return false;
530}
531
532JDWP::ObjectId Dbg::CreateString(const char* str) {
533 UNIMPLEMENTED(FATAL);
534 return 0;
535}
536
537JDWP::ObjectId Dbg::CreateObject(JDWP::RefTypeId classId) {
538 UNIMPLEMENTED(FATAL);
539 return 0;
540}
541
542JDWP::ObjectId Dbg::CreateArrayObject(JDWP::RefTypeId arrayTypeId, uint32_t length) {
543 UNIMPLEMENTED(FATAL);
544 return 0;
545}
546
547bool Dbg::MatchType(JDWP::RefTypeId instClassId, JDWP::RefTypeId classId) {
548 UNIMPLEMENTED(FATAL);
549 return false;
550}
551
552const char* Dbg::GetMethodName(JDWP::RefTypeId refTypeId, JDWP::MethodId id) {
553 UNIMPLEMENTED(FATAL);
554 return NULL;
555}
556
557void Dbg::OutputAllFields(JDWP::RefTypeId refTypeId, bool withGeneric, JDWP::ExpandBuf* pReply) {
558 UNIMPLEMENTED(FATAL);
559}
560
561void Dbg::OutputAllMethods(JDWP::RefTypeId refTypeId, bool withGeneric, JDWP::ExpandBuf* pReply) {
562 UNIMPLEMENTED(FATAL);
563}
564
565void Dbg::OutputAllInterfaces(JDWP::RefTypeId refTypeId, JDWP::ExpandBuf* pReply) {
566 UNIMPLEMENTED(FATAL);
567}
568
569void Dbg::OutputLineTable(JDWP::RefTypeId refTypeId, JDWP::MethodId methodId, JDWP::ExpandBuf* pReply) {
570 UNIMPLEMENTED(FATAL);
571}
572
573void Dbg::OutputVariableTable(JDWP::RefTypeId refTypeId, JDWP::MethodId id, bool withGeneric, JDWP::ExpandBuf* pReply) {
574 UNIMPLEMENTED(FATAL);
575}
576
577uint8_t Dbg::GetFieldBasicTag(JDWP::ObjectId objId, JDWP::FieldId fieldId) {
578 UNIMPLEMENTED(FATAL);
579 return 0;
580}
581
582uint8_t Dbg::GetStaticFieldBasicTag(JDWP::RefTypeId refTypeId, JDWP::FieldId fieldId) {
583 UNIMPLEMENTED(FATAL);
584 return 0;
585}
586
587void Dbg::GetFieldValue(JDWP::ObjectId objectId, JDWP::FieldId fieldId, JDWP::ExpandBuf* pReply) {
588 UNIMPLEMENTED(FATAL);
589}
590
591void Dbg::SetFieldValue(JDWP::ObjectId objectId, JDWP::FieldId fieldId, uint64_t value, int width) {
592 UNIMPLEMENTED(FATAL);
593}
594
595void Dbg::GetStaticFieldValue(JDWP::RefTypeId refTypeId, JDWP::FieldId fieldId, JDWP::ExpandBuf* pReply) {
596 UNIMPLEMENTED(FATAL);
597}
598
599void Dbg::SetStaticFieldValue(JDWP::RefTypeId refTypeId, JDWP::FieldId fieldId, uint64_t rawValue, int width) {
600 UNIMPLEMENTED(FATAL);
601}
602
603char* Dbg::StringToUtf8(JDWP::ObjectId strId) {
604 UNIMPLEMENTED(FATAL);
605 return NULL;
606}
607
608char* Dbg::GetThreadName(JDWP::ObjectId threadId) {
609 UNIMPLEMENTED(FATAL);
610 return NULL;
611}
612
613JDWP::ObjectId Dbg::GetThreadGroup(JDWP::ObjectId threadId) {
614 UNIMPLEMENTED(FATAL);
615 return 0;
616}
617
618char* Dbg::GetThreadGroupName(JDWP::ObjectId threadGroupId) {
619 UNIMPLEMENTED(FATAL);
620 return NULL;
621}
622
623JDWP::ObjectId Dbg::GetThreadGroupParent(JDWP::ObjectId threadGroupId) {
624 UNIMPLEMENTED(FATAL);
625 return 0;
626}
627
628JDWP::ObjectId Dbg::GetSystemThreadGroupId() {
629 UNIMPLEMENTED(FATAL);
630 return 0;
631}
632
633JDWP::ObjectId Dbg::GetMainThreadGroupId() {
634 UNIMPLEMENTED(FATAL);
635 return 0;
636}
637
638bool Dbg::GetThreadStatus(JDWP::ObjectId threadId, uint32_t* threadStatus, uint32_t* suspendStatus) {
639 UNIMPLEMENTED(FATAL);
640 return false;
641}
642
643uint32_t Dbg::GetThreadSuspendCount(JDWP::ObjectId threadId) {
644 UNIMPLEMENTED(FATAL);
645 return 0;
646}
647
648bool Dbg::ThreadExists(JDWP::ObjectId threadId) {
649 UNIMPLEMENTED(FATAL);
650 return false;
651}
652
653bool Dbg::IsSuspended(JDWP::ObjectId threadId) {
654 UNIMPLEMENTED(FATAL);
655 return false;
656}
657
658//void Dbg::WaitForSuspend(JDWP::ObjectId threadId);
659
Elliott Hughesa2155262011-11-16 16:26:58 -0800660void Dbg::GetThreadGroupThreadsImpl(Object* thread_group, JDWP::ObjectId** ppThreadIds, uint32_t* pThreadCount) {
661 struct ThreadListVisitor {
662 static void Visit(Thread* t, void* arg) {
663 reinterpret_cast<ThreadListVisitor*>(arg)->Visit(t);
664 }
665
666 void Visit(Thread* t) {
667 if (t == Dbg::GetDebugThread()) {
668 // Skip the JDWP thread. Some debuggers get bent out of shape when they can't suspend and
669 // query all threads, so it's easier if we just don't tell them about this thread.
670 return;
671 }
672 if (thread_group == NULL || t->GetThreadGroup() == thread_group) {
673 threads.push_back(gRegistry->Add(t->GetPeer()));
674 }
675 }
676
677 Object* thread_group;
678 std::vector<JDWP::ObjectId> threads;
679 };
680
681 ThreadListVisitor tlv;
682 tlv.thread_group = thread_group;
683
684 {
685 ScopedThreadListLock thread_list_lock;
686 Runtime::Current()->GetThreadList()->ForEach(ThreadListVisitor::Visit, &tlv);
687 }
688
689 *pThreadCount = tlv.threads.size();
690 if (*pThreadCount == 0) {
691 *ppThreadIds = NULL;
692 } else {
693 *ppThreadIds = new JDWP::ObjectId[*pThreadCount];
694 for (size_t i = 0; i < *pThreadCount; ++i) {
695 (*ppThreadIds)[i] = tlv.threads[i];
696 }
697 }
698}
699
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700700void Dbg::GetThreadGroupThreads(JDWP::ObjectId threadGroupId, JDWP::ObjectId** ppThreadIds, uint32_t* pThreadCount) {
Elliott Hughesa2155262011-11-16 16:26:58 -0800701 GetThreadGroupThreadsImpl(gRegistry->Get<Object*>(threadGroupId), ppThreadIds, pThreadCount);
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700702}
703
704void Dbg::GetAllThreads(JDWP::ObjectId** ppThreadIds, uint32_t* pThreadCount) {
Elliott Hughesa2155262011-11-16 16:26:58 -0800705 GetThreadGroupThreadsImpl(NULL, ppThreadIds, pThreadCount);
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700706}
707
708int Dbg::GetThreadFrameCount(JDWP::ObjectId threadId) {
709 UNIMPLEMENTED(FATAL);
710 return 0;
711}
712
713bool Dbg::GetThreadFrame(JDWP::ObjectId threadId, int num, JDWP::FrameId* pFrameId, JDWP::JdwpLocation* pLoc) {
714 UNIMPLEMENTED(FATAL);
715 return false;
716}
717
718JDWP::ObjectId Dbg::GetThreadSelfId() {
Elliott Hughes475fc232011-10-25 15:00:35 -0700719 return gRegistry->Add(Thread::Current()->GetPeer());
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700720}
721
Elliott Hughes475fc232011-10-25 15:00:35 -0700722void Dbg::SuspendVM() {
Elliott Hughesa2155262011-11-16 16:26:58 -0800723 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 -0700724 Runtime::Current()->GetThreadList()->SuspendAll(true);
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700725}
726
727void Dbg::ResumeVM() {
Elliott Hughes475fc232011-10-25 15:00:35 -0700728 Runtime::Current()->GetThreadList()->ResumeAll(true);
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700729}
730
731void Dbg::SuspendThread(JDWP::ObjectId threadId) {
732 UNIMPLEMENTED(FATAL);
733}
734
735void Dbg::ResumeThread(JDWP::ObjectId threadId) {
736 UNIMPLEMENTED(FATAL);
737}
738
739void Dbg::SuspendSelf() {
Elliott Hughes475fc232011-10-25 15:00:35 -0700740 Runtime::Current()->GetThreadList()->SuspendSelfForDebugger();
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700741}
742
743bool Dbg::GetThisObject(JDWP::ObjectId threadId, JDWP::FrameId frameId, JDWP::ObjectId* pThisId) {
744 UNIMPLEMENTED(FATAL);
745 return false;
746}
747
748void Dbg::GetLocalValue(JDWP::ObjectId threadId, JDWP::FrameId frameId, int slot, uint8_t tag, uint8_t* buf, int expectedLen) {
749 UNIMPLEMENTED(FATAL);
750}
751
752void Dbg::SetLocalValue(JDWP::ObjectId threadId, JDWP::FrameId frameId, int slot, uint8_t tag, uint64_t value, int width) {
753 UNIMPLEMENTED(FATAL);
754}
755
756void Dbg::PostLocationEvent(const Method* method, int pcOffset, Object* thisPtr, int eventFlags) {
757 UNIMPLEMENTED(FATAL);
758}
759
760void Dbg::PostException(void* throwFp, int throwRelPc, void* catchFp, int catchRelPc, Object* exception) {
761 UNIMPLEMENTED(FATAL);
762}
763
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700764void Dbg::PostClassPrepare(Class* c) {
765 UNIMPLEMENTED(FATAL);
766}
767
768bool Dbg::WatchLocation(const JDWP::JdwpLocation* pLoc) {
769 UNIMPLEMENTED(FATAL);
770 return false;
771}
772
773void Dbg::UnwatchLocation(const JDWP::JdwpLocation* pLoc) {
774 UNIMPLEMENTED(FATAL);
775}
776
777bool Dbg::ConfigureStep(JDWP::ObjectId threadId, JDWP::JdwpStepSize size, JDWP::JdwpStepDepth depth) {
778 UNIMPLEMENTED(FATAL);
779 return false;
780}
781
782void Dbg::UnconfigureStep(JDWP::ObjectId threadId) {
783 UNIMPLEMENTED(FATAL);
784}
785
786JDWP::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) {
787 UNIMPLEMENTED(FATAL);
788 return JDWP::ERR_NONE;
789}
790
791void Dbg::ExecuteMethod(DebugInvokeReq* pReq) {
792 UNIMPLEMENTED(FATAL);
793}
794
795void Dbg::RegisterObjectId(JDWP::ObjectId id) {
796 UNIMPLEMENTED(FATAL);
797}
798
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -0700799/*
800 * "buf" contains a full JDWP packet, possibly with multiple chunks. We
801 * need to process each, accumulate the replies, and ship the whole thing
802 * back.
803 *
804 * Returns "true" if we have a reply. The reply buffer is newly allocated,
805 * and includes the chunk type/length, followed by the data.
806 *
807 * TODO: we currently assume that the request and reply include a single
808 * chunk. If this becomes inconvenient we will need to adapt.
809 */
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700810bool Dbg::DdmHandlePacket(const uint8_t* buf, int dataLen, uint8_t** pReplyBuf, int* pReplyLen) {
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -0700811 CHECK_GE(dataLen, 0);
812
813 Thread* self = Thread::Current();
814 JNIEnv* env = self->GetJniEnv();
815
816 static jclass Chunk_class = env->FindClass("org/apache/harmony/dalvik/ddmc/Chunk");
817 static jclass DdmServer_class = env->FindClass("org/apache/harmony/dalvik/ddmc/DdmServer");
818 static jmethodID dispatch_mid = env->GetStaticMethodID(DdmServer_class, "dispatch",
819 "(I[BII)Lorg/apache/harmony/dalvik/ddmc/Chunk;");
820 static jfieldID data_fid = env->GetFieldID(Chunk_class, "data", "[B");
821 static jfieldID length_fid = env->GetFieldID(Chunk_class, "length", "I");
822 static jfieldID offset_fid = env->GetFieldID(Chunk_class, "offset", "I");
823 static jfieldID type_fid = env->GetFieldID(Chunk_class, "type", "I");
824
825 // Create a byte[] corresponding to 'buf'.
Elliott Hughes6a5bd492011-10-28 14:33:57 -0700826 ScopedLocalRef<jbyteArray> dataArray(env, env->NewByteArray(dataLen));
827 if (dataArray.get() == NULL) {
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -0700828 LOG(WARNING) << "byte[] allocation failed: " << dataLen;
829 env->ExceptionClear();
830 return false;
831 }
Elliott Hughes6a5bd492011-10-28 14:33:57 -0700832 env->SetByteArrayRegion(dataArray.get(), 0, dataLen, reinterpret_cast<const jbyte*>(buf));
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -0700833
834 const int kChunkHdrLen = 8;
835
836 // Run through and find all chunks. [Currently just find the first.]
Elliott Hughes6a5bd492011-10-28 14:33:57 -0700837 ScopedByteArrayRO contents(env, dataArray.get());
Elliott Hughesf7c3b662011-10-27 12:04:56 -0700838 jint type = JDWP::Get4BE(reinterpret_cast<const uint8_t*>(&contents[0]));
839 jint length = JDWP::Get4BE(reinterpret_cast<const uint8_t*>(&contents[4]));
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -0700840 jint offset = kChunkHdrLen;
841 if (offset + length > dataLen) {
842 LOG(WARNING) << StringPrintf("bad chunk found (len=%u pktLen=%d)", length, dataLen);
843 return false;
844 }
845
846 // Call "private static Chunk dispatch(int type, byte[] data, int offset, int length)".
Elliott Hughes6a5bd492011-10-28 14:33:57 -0700847 ScopedLocalRef<jobject> chunk(env, env->CallStaticObjectMethod(DdmServer_class, dispatch_mid, type, dataArray.get(), offset, length));
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -0700848 if (env->ExceptionCheck()) {
849 LOG(INFO) << StringPrintf("Exception thrown by dispatcher for 0x%08x", type);
850 env->ExceptionDescribe();
851 env->ExceptionClear();
852 return false;
853 }
854
Elliott Hughes6a5bd492011-10-28 14:33:57 -0700855 if (chunk.get() == NULL) {
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -0700856 return false;
857 }
858
859 /*
860 * Pull the pieces out of the chunk. We copy the results into a
861 * newly-allocated buffer that the caller can free. We don't want to
862 * continue using the Chunk object because nothing has a reference to it.
863 *
864 * We could avoid this by returning type/data/offset/length and having
865 * the caller be aware of the object lifetime issues, but that
866 * integrates the JDWP code more tightly into the VM, and doesn't work
867 * if we have responses for multiple chunks.
868 *
869 * So we're pretty much stuck with copying data around multiple times.
870 */
Elliott Hughes6a5bd492011-10-28 14:33:57 -0700871 ScopedLocalRef<jbyteArray> replyData(env, reinterpret_cast<jbyteArray>(env->GetObjectField(chunk.get(), data_fid)));
872 length = env->GetIntField(chunk.get(), length_fid);
873 offset = env->GetIntField(chunk.get(), offset_fid);
874 type = env->GetIntField(chunk.get(), type_fid);
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -0700875
Elliott Hughes6a5bd492011-10-28 14:33:57 -0700876 LOG(VERBOSE) << StringPrintf("DDM reply: type=0x%08x data=%p offset=%d length=%d", type, replyData.get(), offset, length);
877 if (length == 0 || replyData.get() == NULL) {
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -0700878 return false;
879 }
880
Elliott Hughes6a5bd492011-10-28 14:33:57 -0700881 jsize replyLength = env->GetArrayLength(replyData.get());
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -0700882 if (offset + length > replyLength) {
883 LOG(WARNING) << StringPrintf("chunk off=%d len=%d exceeds reply array len %d", offset, length, replyLength);
884 return false;
885 }
886
887 uint8_t* reply = new uint8_t[length + kChunkHdrLen];
888 if (reply == NULL) {
889 LOG(WARNING) << "malloc failed: " << (length + kChunkHdrLen);
890 return false;
891 }
Elliott Hughesf7c3b662011-10-27 12:04:56 -0700892 JDWP::Set4BE(reply + 0, type);
893 JDWP::Set4BE(reply + 4, length);
Elliott Hughes6a5bd492011-10-28 14:33:57 -0700894 env->GetByteArrayRegion(replyData.get(), offset, length, reinterpret_cast<jbyte*>(reply + kChunkHdrLen));
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -0700895
896 *pReplyBuf = reply;
897 *pReplyLen = length + kChunkHdrLen;
898
899 LOG(VERBOSE) << StringPrintf("dvmHandleDdm returning type=%.4s buf=%p len=%d", (char*) reply, reply, length);
900 return true;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700901}
902
Elliott Hughesa2155262011-11-16 16:26:58 -0800903void Dbg::DdmBroadcast(bool connect) {
Elliott Hughes47fce012011-10-25 18:37:19 -0700904 LOG(VERBOSE) << "Broadcasting DDM " << (connect ? "connect" : "disconnect") << "...";
905
906 Thread* self = Thread::Current();
907 if (self->GetState() != Thread::kRunnable) {
908 LOG(ERROR) << "DDM broadcast in thread state " << self->GetState();
909 /* try anyway? */
910 }
911
912 JNIEnv* env = self->GetJniEnv();
913 static jclass DdmServer_class = env->FindClass("org/apache/harmony/dalvik/ddmc/DdmServer");
914 static jmethodID broadcast_mid = env->GetStaticMethodID(DdmServer_class, "broadcast", "(I)V");
915 jint event = connect ? 1 /*DdmServer.CONNECTED*/ : 2 /*DdmServer.DISCONNECTED*/;
916 env->CallStaticVoidMethod(DdmServer_class, broadcast_mid, event);
917 if (env->ExceptionCheck()) {
918 LOG(ERROR) << "DdmServer.broadcast " << event << " failed";
919 env->ExceptionDescribe();
920 env->ExceptionClear();
921 }
922}
923
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700924void Dbg::DdmConnected() {
Elliott Hughesa2155262011-11-16 16:26:58 -0800925 Dbg::DdmBroadcast(true);
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700926}
927
928void Dbg::DdmDisconnected() {
Elliott Hughesa2155262011-11-16 16:26:58 -0800929 Dbg::DdmBroadcast(false);
Elliott Hughes47fce012011-10-25 18:37:19 -0700930 gDdmThreadNotification = false;
931}
932
933/*
Elliott Hughes82188472011-11-07 18:11:48 -0800934 * Send a notification when a thread starts, stops, or changes its name.
Elliott Hughes47fce012011-10-25 18:37:19 -0700935 *
936 * Because we broadcast the full set of threads when the notifications are
937 * first enabled, it's possible for "thread" to be actively executing.
938 */
Elliott Hughes82188472011-11-07 18:11:48 -0800939void Dbg::DdmSendThreadNotification(Thread* t, uint32_t type) {
Elliott Hughes47fce012011-10-25 18:37:19 -0700940 if (!gDdmThreadNotification) {
941 return;
942 }
943
Elliott Hughes82188472011-11-07 18:11:48 -0800944 if (type == CHUNK_TYPE("THDE")) {
Elliott Hughes47fce012011-10-25 18:37:19 -0700945 uint8_t buf[4];
Elliott Hughesf7c3b662011-10-27 12:04:56 -0700946 JDWP::Set4BE(&buf[0], t->GetThinLockId());
Elliott Hughes47fce012011-10-25 18:37:19 -0700947 Dbg::DdmSendChunk(CHUNK_TYPE("THDE"), 4, buf);
Elliott Hughes82188472011-11-07 18:11:48 -0800948 } else {
949 CHECK(type == CHUNK_TYPE("THCR") || type == CHUNK_TYPE("THNM")) << type;
950 SirtRef<String> name(t->GetName());
951 size_t char_count = (name.get() != NULL) ? name->GetLength() : 0;
952 const jchar* chars = name->GetCharArray()->GetData();
953
Elliott Hughes21f32d72011-11-09 17:44:13 -0800954 std::vector<uint8_t> bytes;
Elliott Hughes545a0642011-11-08 19:10:03 -0800955 JDWP::Append4BE(bytes, t->GetThinLockId());
956 JDWP::AppendUtf16BE(bytes, chars, char_count);
Elliott Hughes21f32d72011-11-09 17:44:13 -0800957 CHECK_EQ(bytes.size(), char_count*2 + sizeof(uint32_t)*2);
958 Dbg::DdmSendChunk(type, bytes);
Elliott Hughes47fce012011-10-25 18:37:19 -0700959 }
960}
961
Elliott Hughesa2155262011-11-16 16:26:58 -0800962static void DdmSendThreadStartCallback(Thread* t, void*) {
Elliott Hughes82188472011-11-07 18:11:48 -0800963 Dbg::DdmSendThreadNotification(t, CHUNK_TYPE("THCR"));
Elliott Hughes47fce012011-10-25 18:37:19 -0700964}
965
966void Dbg::DdmSetThreadNotification(bool enable) {
967 // We lock the thread list to avoid sending duplicate events or missing
968 // a thread change. We should be okay holding this lock while sending
969 // the messages out. (We have to hold it while accessing a live thread.)
Elliott Hughesbbd9d832011-11-07 14:40:00 -0800970 ScopedThreadListLock thread_list_lock;
Elliott Hughes47fce012011-10-25 18:37:19 -0700971
972 gDdmThreadNotification = enable;
973 if (enable) {
Elliott Hughesbfe487b2011-10-26 15:48:55 -0700974 Runtime::Current()->GetThreadList()->ForEach(DdmSendThreadStartCallback, NULL);
Elliott Hughes47fce012011-10-25 18:37:19 -0700975 }
976}
977
Elliott Hughesa2155262011-11-16 16:26:58 -0800978void Dbg::PostThreadStartOrStop(Thread* t, uint32_t type) {
Elliott Hughes47fce012011-10-25 18:37:19 -0700979 if (gDebuggerActive) {
980 JDWP::ObjectId id = gRegistry->Add(t->GetPeer());
Elliott Hughes82188472011-11-07 18:11:48 -0800981 gJdwpState->PostThreadChange(id, type == CHUNK_TYPE("THCR"));
Elliott Hughes47fce012011-10-25 18:37:19 -0700982 }
Elliott Hughes82188472011-11-07 18:11:48 -0800983 Dbg::DdmSendThreadNotification(t, type);
Elliott Hughes47fce012011-10-25 18:37:19 -0700984}
985
986void Dbg::PostThreadStart(Thread* t) {
Elliott Hughesa2155262011-11-16 16:26:58 -0800987 Dbg::PostThreadStartOrStop(t, CHUNK_TYPE("THCR"));
Elliott Hughes47fce012011-10-25 18:37:19 -0700988}
989
990void Dbg::PostThreadDeath(Thread* t) {
Elliott Hughesa2155262011-11-16 16:26:58 -0800991 Dbg::PostThreadStartOrStop(t, CHUNK_TYPE("THDE"));
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700992}
993
Elliott Hughes82188472011-11-07 18:11:48 -0800994void Dbg::DdmSendChunk(uint32_t type, size_t byte_count, const uint8_t* buf) {
Elliott Hughes3bb81562011-10-21 18:52:59 -0700995 CHECK(buf != NULL);
996 iovec vec[1];
997 vec[0].iov_base = reinterpret_cast<void*>(const_cast<uint8_t*>(buf));
998 vec[0].iov_len = byte_count;
999 Dbg::DdmSendChunkV(type, vec, 1);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001000}
1001
Elliott Hughes21f32d72011-11-09 17:44:13 -08001002void Dbg::DdmSendChunk(uint32_t type, const std::vector<uint8_t>& bytes) {
1003 DdmSendChunk(type, bytes.size(), &bytes[0]);
1004}
1005
Elliott Hughes82188472011-11-07 18:11:48 -08001006void Dbg::DdmSendChunkV(uint32_t type, const struct iovec* iov, int iovcnt) {
Elliott Hughes3bb81562011-10-21 18:52:59 -07001007 if (gJdwpState == NULL) {
1008 LOG(VERBOSE) << "Debugger thread not active, ignoring DDM send: " << type;
1009 } else {
Elliott Hughes376a7a02011-10-24 18:35:55 -07001010 gJdwpState->DdmSendChunkV(type, iov, iovcnt);
Elliott Hughes3bb81562011-10-21 18:52:59 -07001011 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001012}
1013
Elliott Hughes767a1472011-10-26 18:49:02 -07001014int Dbg::DdmHandleHpifChunk(HpifWhen when) {
1015 if (when == HPIF_WHEN_NOW) {
Elliott Hughes7162ad92011-10-27 14:08:42 -07001016 DdmSendHeapInfo(when);
Elliott Hughes767a1472011-10-26 18:49:02 -07001017 return true;
1018 }
1019
1020 if (when != HPIF_WHEN_NEVER && when != HPIF_WHEN_NEXT_GC && when != HPIF_WHEN_EVERY_GC) {
1021 LOG(ERROR) << "invalid HpifWhen value: " << static_cast<int>(when);
1022 return false;
1023 }
1024
1025 gDdmHpifWhen = when;
1026 return true;
1027}
1028
1029bool Dbg::DdmHandleHpsgNhsgChunk(Dbg::HpsgWhen when, Dbg::HpsgWhat what, bool native) {
1030 if (when != HPSG_WHEN_NEVER && when != HPSG_WHEN_EVERY_GC) {
1031 LOG(ERROR) << "invalid HpsgWhen value: " << static_cast<int>(when);
1032 return false;
1033 }
1034
1035 if (what != HPSG_WHAT_MERGED_OBJECTS && what != HPSG_WHAT_DISTINCT_OBJECTS) {
1036 LOG(ERROR) << "invalid HpsgWhat value: " << static_cast<int>(what);
1037 return false;
1038 }
1039
1040 if (native) {
1041 gDdmNhsgWhen = when;
1042 gDdmNhsgWhat = what;
1043 } else {
1044 gDdmHpsgWhen = when;
1045 gDdmHpsgWhat = what;
1046 }
1047 return true;
1048}
1049
Elliott Hughes7162ad92011-10-27 14:08:42 -07001050void Dbg::DdmSendHeapInfo(HpifWhen reason) {
1051 // If there's a one-shot 'when', reset it.
1052 if (reason == gDdmHpifWhen) {
1053 if (gDdmHpifWhen == HPIF_WHEN_NEXT_GC) {
1054 gDdmHpifWhen = HPIF_WHEN_NEVER;
1055 }
1056 }
1057
1058 /*
1059 * Chunk HPIF (client --> server)
1060 *
1061 * Heap Info. General information about the heap,
1062 * suitable for a summary display.
1063 *
1064 * [u4]: number of heaps
1065 *
1066 * For each heap:
1067 * [u4]: heap ID
1068 * [u8]: timestamp in ms since Unix epoch
1069 * [u1]: capture reason (same as 'when' value from server)
1070 * [u4]: max heap size in bytes (-Xmx)
1071 * [u4]: current heap size in bytes
1072 * [u4]: current number of bytes allocated
1073 * [u4]: current number of objects allocated
1074 */
1075 uint8_t heap_count = 1;
Elliott Hughes21f32d72011-11-09 17:44:13 -08001076 std::vector<uint8_t> bytes;
Elliott Hughes545a0642011-11-08 19:10:03 -08001077 JDWP::Append4BE(bytes, heap_count);
1078 JDWP::Append4BE(bytes, 1); // Heap id (bogus; we only have one heap).
1079 JDWP::Append8BE(bytes, MilliTime());
1080 JDWP::Append1BE(bytes, reason);
1081 JDWP::Append4BE(bytes, Heap::GetMaxMemory()); // Max allowed heap size in bytes.
1082 JDWP::Append4BE(bytes, Heap::GetTotalMemory()); // Current heap size in bytes.
1083 JDWP::Append4BE(bytes, Heap::GetBytesAllocated());
1084 JDWP::Append4BE(bytes, Heap::GetObjectsAllocated());
Elliott Hughes21f32d72011-11-09 17:44:13 -08001085 CHECK_EQ(bytes.size(), 4U + (heap_count * (4 + 8 + 1 + 4 + 4 + 4 + 4)));
1086 Dbg::DdmSendChunk(CHUNK_TYPE("HPIF"), bytes);
Elliott Hughes767a1472011-10-26 18:49:02 -07001087}
1088
Elliott Hughes6a5bd492011-10-28 14:33:57 -07001089enum HpsgSolidity {
1090 SOLIDITY_FREE = 0,
1091 SOLIDITY_HARD = 1,
1092 SOLIDITY_SOFT = 2,
1093 SOLIDITY_WEAK = 3,
1094 SOLIDITY_PHANTOM = 4,
1095 SOLIDITY_FINALIZABLE = 5,
1096 SOLIDITY_SWEEP = 6,
1097};
1098
1099enum HpsgKind {
1100 KIND_OBJECT = 0,
1101 KIND_CLASS_OBJECT = 1,
1102 KIND_ARRAY_1 = 2,
1103 KIND_ARRAY_2 = 3,
1104 KIND_ARRAY_4 = 4,
1105 KIND_ARRAY_8 = 5,
1106 KIND_UNKNOWN = 6,
1107 KIND_NATIVE = 7,
1108};
1109
1110#define HPSG_PARTIAL (1<<7)
1111#define HPSG_STATE(solidity, kind) ((uint8_t)((((kind) & 0x7) << 3) | ((solidity) & 0x7)))
1112
1113struct HeapChunkContext {
1114 std::vector<uint8_t> buf;
1115 uint8_t* p;
1116 uint8_t* pieceLenField;
1117 size_t totalAllocationUnits;
Elliott Hughes82188472011-11-07 18:11:48 -08001118 uint32_t type;
Elliott Hughes6a5bd492011-10-28 14:33:57 -07001119 bool merge;
1120 bool needHeader;
1121
1122 // Maximum chunk size. Obtain this from the formula:
1123 // (((maximum_heap_size / ALLOCATION_UNIT_SIZE) + 255) / 256) * 2
1124 HeapChunkContext(bool merge, bool native)
1125 : buf(16384 - 16),
1126 type(0),
1127 merge(merge) {
1128 Reset();
1129 if (native) {
1130 type = CHUNK_TYPE("NHSG");
1131 } else {
1132 type = merge ? CHUNK_TYPE("HPSG") : CHUNK_TYPE("HPSO");
1133 }
1134 }
1135
1136 ~HeapChunkContext() {
1137 if (p > &buf[0]) {
1138 Flush();
1139 }
1140 }
1141
1142 void EnsureHeader(const void* chunk_ptr) {
1143 if (!needHeader) {
1144 return;
1145 }
1146
1147 // Start a new HPSx chunk.
1148 JDWP::Write4BE(&p, 1); // Heap id (bogus; we only have one heap).
1149 JDWP::Write1BE(&p, 8); // Size of allocation unit, in bytes.
1150
1151 JDWP::Write4BE(&p, reinterpret_cast<uintptr_t>(chunk_ptr)); // virtual address of segment start.
1152 JDWP::Write4BE(&p, 0); // offset of this piece (relative to the virtual address).
1153 // [u4]: length of piece, in allocation units
1154 // We won't know this until we're done, so save the offset and stuff in a dummy value.
1155 pieceLenField = p;
1156 JDWP::Write4BE(&p, 0x55555555);
1157 needHeader = false;
1158 }
1159
1160 void Flush() {
1161 // Patch the "length of piece" field.
1162 CHECK_LE(&buf[0], pieceLenField);
1163 CHECK_LE(pieceLenField, p);
1164 JDWP::Set4BE(pieceLenField, totalAllocationUnits);
1165
1166 Dbg::DdmSendChunk(type, p - &buf[0], &buf[0]);
1167 Reset();
1168 }
1169
Elliott Hughesa2155262011-11-16 16:26:58 -08001170 static void HeapChunkCallback(const void* chunk_ptr, size_t chunk_len, const void* user_ptr, size_t user_len, void* arg) {
1171 reinterpret_cast<HeapChunkContext*>(arg)->HeapChunkCallback(chunk_ptr, chunk_len, user_ptr, user_len);
1172 }
1173
Elliott Hughes6a5bd492011-10-28 14:33:57 -07001174 private:
Elliott Hughesa2155262011-11-16 16:26:58 -08001175 enum { ALLOCATION_UNIT_SIZE = 8 };
1176
Elliott Hughes6a5bd492011-10-28 14:33:57 -07001177 void Reset() {
1178 p = &buf[0];
1179 totalAllocationUnits = 0;
1180 needHeader = true;
1181 pieceLenField = NULL;
1182 }
1183
Elliott Hughesa2155262011-11-16 16:26:58 -08001184 void HeapChunkCallback(const void* chunk_ptr, size_t chunk_len, const void* user_ptr, size_t user_len) {
1185 CHECK_EQ((chunk_len & (ALLOCATION_UNIT_SIZE-1)), 0U);
Elliott Hughes6a5bd492011-10-28 14:33:57 -07001186
Elliott Hughesa2155262011-11-16 16:26:58 -08001187 /* Make sure there's enough room left in the buffer.
1188 * We need to use two bytes for every fractional 256
1189 * allocation units used by the chunk.
1190 */
1191 {
1192 size_t needed = (((chunk_len/ALLOCATION_UNIT_SIZE + 255) / 256) * 2);
1193 size_t bytesLeft = buf.size() - (size_t)(p - &buf[0]);
1194 if (bytesLeft < needed) {
1195 Flush();
1196 }
Elliott Hughes6a5bd492011-10-28 14:33:57 -07001197
Elliott Hughesa2155262011-11-16 16:26:58 -08001198 bytesLeft = buf.size() - (size_t)(p - &buf[0]);
1199 if (bytesLeft < needed) {
1200 LOG(WARNING) << "chunk is too big to transmit (chunk_len=" << chunk_len << ", " << needed << " bytes)";
1201 return;
1202 }
1203 }
1204
1205 // OLD-TODO: notice when there's a gap and start a new heap, or at least a new range.
1206 EnsureHeader(chunk_ptr);
1207
1208 // Determine the type of this chunk.
1209 // OLD-TODO: if context.merge, see if this chunk is different from the last chunk.
1210 // If it's the same, we should combine them.
1211 uint8_t state = ExamineObject(reinterpret_cast<const Object*>(user_ptr), (type == CHUNK_TYPE("NHSG")));
1212
1213 // Write out the chunk description.
1214 chunk_len /= ALLOCATION_UNIT_SIZE; // convert to allocation units
1215 totalAllocationUnits += chunk_len;
1216 while (chunk_len > 256) {
1217 *p++ = state | HPSG_PARTIAL;
1218 *p++ = 255; // length - 1
1219 chunk_len -= 256;
1220 }
1221 *p++ = state;
1222 *p++ = chunk_len - 1;
Elliott Hughes6a5bd492011-10-28 14:33:57 -07001223 }
1224
Elliott Hughesa2155262011-11-16 16:26:58 -08001225 uint8_t ExamineObject(const Object* o, bool is_native_heap) {
1226 if (o == NULL) {
1227 return HPSG_STATE(SOLIDITY_FREE, 0);
1228 }
Elliott Hughes6a5bd492011-10-28 14:33:57 -07001229
Elliott Hughesa2155262011-11-16 16:26:58 -08001230 // It's an allocated chunk. Figure out what it is.
Elliott Hughes6a5bd492011-10-28 14:33:57 -07001231
Elliott Hughesa2155262011-11-16 16:26:58 -08001232 // If we're looking at the native heap, we'll just return
1233 // (SOLIDITY_HARD, KIND_NATIVE) for all allocated chunks.
1234 if (is_native_heap || !Heap::IsLiveObjectLocked(o)) {
1235 return HPSG_STATE(SOLIDITY_HARD, KIND_NATIVE);
1236 }
1237
1238 Class* c = o->GetClass();
1239 if (c == NULL) {
1240 // The object was probably just created but hasn't been initialized yet.
1241 return HPSG_STATE(SOLIDITY_HARD, KIND_OBJECT);
1242 }
1243
1244 if (!Heap::IsHeapAddress(c)) {
1245 LOG(WARNING) << "invalid class for managed heap object: " << o << " " << c;
1246 return HPSG_STATE(SOLIDITY_HARD, KIND_UNKNOWN);
1247 }
1248
1249 if (c->IsClassClass()) {
1250 return HPSG_STATE(SOLIDITY_HARD, KIND_CLASS_OBJECT);
1251 }
1252
1253 if (c->IsArrayClass()) {
1254 if (o->IsObjectArray()) {
1255 return HPSG_STATE(SOLIDITY_HARD, KIND_ARRAY_4);
1256 }
1257 switch (c->GetComponentSize()) {
1258 case 1: return HPSG_STATE(SOLIDITY_HARD, KIND_ARRAY_1);
1259 case 2: return HPSG_STATE(SOLIDITY_HARD, KIND_ARRAY_2);
1260 case 4: return HPSG_STATE(SOLIDITY_HARD, KIND_ARRAY_4);
1261 case 8: return HPSG_STATE(SOLIDITY_HARD, KIND_ARRAY_8);
1262 }
1263 }
1264
Elliott Hughes6a5bd492011-10-28 14:33:57 -07001265 return HPSG_STATE(SOLIDITY_HARD, KIND_OBJECT);
1266 }
1267
Elliott Hughesa2155262011-11-16 16:26:58 -08001268 DISALLOW_COPY_AND_ASSIGN(HeapChunkContext);
1269};
Elliott Hughes6a5bd492011-10-28 14:33:57 -07001270
1271void Dbg::DdmSendHeapSegments(bool native) {
1272 Dbg::HpsgWhen when;
1273 Dbg::HpsgWhat what;
1274 if (!native) {
1275 when = gDdmHpsgWhen;
1276 what = gDdmHpsgWhat;
1277 } else {
1278 when = gDdmNhsgWhen;
1279 what = gDdmNhsgWhat;
1280 }
1281 if (when == HPSG_WHEN_NEVER) {
1282 return;
1283 }
1284
1285 // Figure out what kind of chunks we'll be sending.
1286 CHECK(what == HPSG_WHAT_MERGED_OBJECTS || what == HPSG_WHAT_DISTINCT_OBJECTS) << static_cast<int>(what);
1287
1288 // First, send a heap start chunk.
1289 uint8_t heap_id[4];
1290 JDWP::Set4BE(&heap_id[0], 1); // Heap id (bogus; we only have one heap).
1291 Dbg::DdmSendChunk(native ? CHUNK_TYPE("NHST") : CHUNK_TYPE("HPST"), sizeof(heap_id), heap_id);
1292
1293 // Send a series of heap segment chunks.
Elliott Hughesa2155262011-11-16 16:26:58 -08001294 HeapChunkContext context((what == HPSG_WHAT_MERGED_OBJECTS), native);
1295 if (native) {
1296 dlmalloc_walk_heap(HeapChunkContext::HeapChunkCallback, &context);
1297 } else {
1298 Heap::WalkHeap(HeapChunkContext::HeapChunkCallback, &context);
1299 }
Elliott Hughes6a5bd492011-10-28 14:33:57 -07001300
1301 // Finally, send a heap end chunk.
1302 Dbg::DdmSendChunk(native ? CHUNK_TYPE("NHEN") : CHUNK_TYPE("HPEN"), sizeof(heap_id), heap_id);
Elliott Hughes767a1472011-10-26 18:49:02 -07001303}
1304
Elliott Hughes545a0642011-11-08 19:10:03 -08001305void Dbg::SetAllocTrackingEnabled(bool enabled) {
1306 MutexLock mu(gAllocTrackerLock);
1307 if (enabled) {
1308 if (recent_allocation_records_ == NULL) {
1309 LOG(INFO) << "Enabling alloc tracker (" << kNumAllocRecords << " entries, "
1310 << kMaxAllocRecordStackDepth << " frames --> "
1311 << (sizeof(AllocRecord) * kNumAllocRecords) << " bytes)";
1312 gAllocRecordHead = gAllocRecordCount = 0;
1313 recent_allocation_records_ = new AllocRecord[kNumAllocRecords];
1314 CHECK(recent_allocation_records_ != NULL);
1315 }
1316 } else {
1317 delete[] recent_allocation_records_;
1318 recent_allocation_records_ = NULL;
1319 }
1320}
1321
1322struct AllocRecordStackVisitor : public Thread::StackVisitor {
1323 AllocRecordStackVisitor(AllocRecord* record) : record(record), depth(0) {
1324 }
1325
1326 virtual void VisitFrame(const Frame& f, uintptr_t pc) {
1327 if (depth >= kMaxAllocRecordStackDepth) {
1328 return;
1329 }
1330 Method* m = f.GetMethod();
1331 if (m == NULL || m->IsCalleeSaveMethod()) {
1332 return;
1333 }
1334 record->stack[depth].method = m;
1335 record->stack[depth].raw_pc = pc;
1336 ++depth;
1337 }
1338
1339 ~AllocRecordStackVisitor() {
1340 // Clear out any unused stack trace elements.
1341 for (; depth < kMaxAllocRecordStackDepth; ++depth) {
1342 record->stack[depth].method = NULL;
1343 record->stack[depth].raw_pc = 0;
1344 }
1345 }
1346
1347 AllocRecord* record;
1348 size_t depth;
1349};
1350
1351void Dbg::RecordAllocation(Class* type, size_t byte_count) {
1352 Thread* self = Thread::Current();
1353 CHECK(self != NULL);
1354
1355 MutexLock mu(gAllocTrackerLock);
1356 if (recent_allocation_records_ == NULL) {
1357 return;
1358 }
1359
1360 // Advance and clip.
1361 if (++gAllocRecordHead == kNumAllocRecords) {
1362 gAllocRecordHead = 0;
1363 }
1364
1365 // Fill in the basics.
1366 AllocRecord* record = &recent_allocation_records_[gAllocRecordHead];
1367 record->type = type;
1368 record->byte_count = byte_count;
1369 record->thin_lock_id = self->GetThinLockId();
1370
1371 // Fill in the stack trace.
1372 AllocRecordStackVisitor visitor(record);
1373 self->WalkStack(&visitor);
1374
1375 if (gAllocRecordCount < kNumAllocRecords) {
1376 ++gAllocRecordCount;
1377 }
1378}
1379
1380/*
1381 * Return the index of the head element.
1382 *
1383 * We point at the most-recently-written record, so if allocRecordCount is 1
1384 * we want to use the current element. Take "head+1" and subtract count
1385 * from it.
1386 *
1387 * We need to handle underflow in our circular buffer, so we add
1388 * kNumAllocRecords and then mask it back down.
1389 */
1390inline static int headIndex() {
1391 return (gAllocRecordHead+1 + kNumAllocRecords - gAllocRecordCount) & (kNumAllocRecords-1);
1392}
1393
1394void Dbg::DumpRecentAllocations() {
1395 MutexLock mu(gAllocTrackerLock);
1396 if (recent_allocation_records_ == NULL) {
1397 LOG(INFO) << "Not recording tracked allocations";
1398 return;
1399 }
1400
1401 // "i" is the head of the list. We want to start at the end of the
1402 // list and move forward to the tail.
1403 size_t i = headIndex();
1404 size_t count = gAllocRecordCount;
1405
1406 LOG(INFO) << "Tracked allocations, (head=" << gAllocRecordHead << " count=" << count << ")";
1407 while (count--) {
1408 AllocRecord* record = &recent_allocation_records_[i];
1409
1410 LOG(INFO) << StringPrintf(" T=%-2d %6d ", record->thin_lock_id, record->byte_count)
1411 << PrettyClass(record->type);
1412
1413 for (size_t stack_frame = 0; stack_frame < kMaxAllocRecordStackDepth; ++stack_frame) {
1414 const Method* m = record->stack[stack_frame].method;
1415 if (m == NULL) {
1416 break;
1417 }
1418 LOG(INFO) << " " << PrettyMethod(m) << " line " << record->stack[stack_frame].LineNumber();
1419 }
1420
1421 // pause periodically to help logcat catch up
1422 if ((count % 5) == 0) {
1423 usleep(40000);
1424 }
1425
1426 i = (i + 1) & (kNumAllocRecords-1);
1427 }
1428}
1429
1430class StringTable {
1431 public:
1432 StringTable() {
1433 }
1434
1435 void Add(const String* s) {
1436 table_.insert(s);
1437 }
1438
1439 size_t IndexOf(const String* s) {
1440 return std::distance(table_.begin(), table_.find(s));
1441 }
1442
1443 size_t Size() {
1444 return table_.size();
1445 }
1446
1447 void WriteTo(std::vector<uint8_t>& bytes) {
1448 typedef std::set<const String*>::const_iterator It; // TODO: C++0x auto
1449 for (It it = table_.begin(); it != table_.end(); ++it) {
1450 const String* s = *it;
1451 JDWP::AppendUtf16BE(bytes, s->GetCharArray()->GetData(), s->GetLength());
1452 }
1453 }
1454
1455 private:
1456 std::set<const String*> table_;
1457 DISALLOW_COPY_AND_ASSIGN(StringTable);
1458};
1459
1460/*
1461 * The data we send to DDMS contains everything we have recorded.
1462 *
1463 * Message header (all values big-endian):
1464 * (1b) message header len (to allow future expansion); includes itself
1465 * (1b) entry header len
1466 * (1b) stack frame len
1467 * (2b) number of entries
1468 * (4b) offset to string table from start of message
1469 * (2b) number of class name strings
1470 * (2b) number of method name strings
1471 * (2b) number of source file name strings
1472 * For each entry:
1473 * (4b) total allocation size
1474 * (2b) threadId
1475 * (2b) allocated object's class name index
1476 * (1b) stack depth
1477 * For each stack frame:
1478 * (2b) method's class name
1479 * (2b) method name
1480 * (2b) method source file
1481 * (2b) line number, clipped to 32767; -2 if native; -1 if no source
1482 * (xb) class name strings
1483 * (xb) method name strings
1484 * (xb) source file strings
1485 *
1486 * As with other DDM traffic, strings are sent as a 4-byte length
1487 * followed by UTF-16 data.
1488 *
1489 * We send up 16-bit unsigned indexes into string tables. In theory there
1490 * can be (kMaxAllocRecordStackDepth * kNumAllocRecords) unique strings in
1491 * each table, but in practice there should be far fewer.
1492 *
1493 * The chief reason for using a string table here is to keep the size of
1494 * the DDMS message to a minimum. This is partly to make the protocol
1495 * efficient, but also because we have to form the whole thing up all at
1496 * once in a memory buffer.
1497 *
1498 * We use separate string tables for class names, method names, and source
1499 * files to keep the indexes small. There will generally be no overlap
1500 * between the contents of these tables.
1501 */
1502jbyteArray Dbg::GetRecentAllocations() {
1503 if (false) {
1504 DumpRecentAllocations();
1505 }
1506
1507 MutexLock mu(gAllocTrackerLock);
1508
1509 /*
1510 * Part 1: generate string tables.
1511 */
1512 StringTable class_names;
1513 StringTable method_names;
1514 StringTable filenames;
1515
1516 int count = gAllocRecordCount;
1517 int idx = headIndex();
1518 while (count--) {
1519 AllocRecord* record = &recent_allocation_records_[idx];
1520
1521 class_names.Add(record->type->GetDescriptor());
1522
1523 for (size_t i = 0; i < kMaxAllocRecordStackDepth; i++) {
1524 const Method* m = record->stack[i].method;
1525 if (m != NULL) {
1526 class_names.Add(m->GetDeclaringClass()->GetDescriptor());
1527 method_names.Add(m->GetName());
1528 filenames.Add(m->GetDeclaringClass()->GetSourceFile());
1529 }
1530 }
1531
1532 idx = (idx + 1) & (kNumAllocRecords-1);
1533 }
1534
1535 LOG(INFO) << "allocation records: " << gAllocRecordCount;
1536
1537 /*
1538 * Part 2: allocate a buffer and generate the output.
1539 */
1540 std::vector<uint8_t> bytes;
1541
1542 // (1b) message header len (to allow future expansion); includes itself
1543 // (1b) entry header len
1544 // (1b) stack frame len
1545 const int kMessageHeaderLen = 15;
1546 const int kEntryHeaderLen = 9;
1547 const int kStackFrameLen = 8;
1548 JDWP::Append1BE(bytes, kMessageHeaderLen);
1549 JDWP::Append1BE(bytes, kEntryHeaderLen);
1550 JDWP::Append1BE(bytes, kStackFrameLen);
1551
1552 // (2b) number of entries
1553 // (4b) offset to string table from start of message
1554 // (2b) number of class name strings
1555 // (2b) number of method name strings
1556 // (2b) number of source file name strings
1557 JDWP::Append2BE(bytes, gAllocRecordCount);
1558 size_t string_table_offset = bytes.size();
1559 JDWP::Append4BE(bytes, 0); // We'll patch this later...
1560 JDWP::Append2BE(bytes, class_names.Size());
1561 JDWP::Append2BE(bytes, method_names.Size());
1562 JDWP::Append2BE(bytes, filenames.Size());
1563
1564 count = gAllocRecordCount;
1565 idx = headIndex();
1566 while (count--) {
1567 // For each entry:
1568 // (4b) total allocation size
1569 // (2b) thread id
1570 // (2b) allocated object's class name index
1571 // (1b) stack depth
1572 AllocRecord* record = &recent_allocation_records_[idx];
1573 size_t stack_depth = record->GetDepth();
1574 JDWP::Append4BE(bytes, record->byte_count);
1575 JDWP::Append2BE(bytes, record->thin_lock_id);
1576 JDWP::Append2BE(bytes, class_names.IndexOf(record->type->GetDescriptor()));
1577 JDWP::Append1BE(bytes, stack_depth);
1578
1579 for (size_t stack_frame = 0; stack_frame < stack_depth; ++stack_frame) {
1580 // For each stack frame:
1581 // (2b) method's class name
1582 // (2b) method name
1583 // (2b) method source file
1584 // (2b) line number, clipped to 32767; -2 if native; -1 if no source
1585 const Method* m = record->stack[stack_frame].method;
1586 JDWP::Append2BE(bytes, class_names.IndexOf(m->GetDeclaringClass()->GetDescriptor()));
1587 JDWP::Append2BE(bytes, method_names.IndexOf(m->GetName()));
1588 JDWP::Append2BE(bytes, filenames.IndexOf(m->GetDeclaringClass()->GetSourceFile()));
1589 JDWP::Append2BE(bytes, record->stack[stack_frame].LineNumber());
1590 }
1591
1592 idx = (idx + 1) & (kNumAllocRecords-1);
1593 }
1594
1595 // (xb) class name strings
1596 // (xb) method name strings
1597 // (xb) source file strings
1598 JDWP::Set4BE(&bytes[string_table_offset], bytes.size());
1599 class_names.WriteTo(bytes);
1600 method_names.WriteTo(bytes);
1601 filenames.WriteTo(bytes);
1602
1603 JNIEnv* env = Thread::Current()->GetJniEnv();
1604 jbyteArray result = env->NewByteArray(bytes.size());
1605 if (result != NULL) {
1606 env->SetByteArrayRegion(result, 0, bytes.size(), reinterpret_cast<const jbyte*>(&bytes[0]));
1607 }
1608 return result;
1609}
1610
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001611} // namespace art