blob: 38346e7794f73f1166d2c848fe1f204f1badc9bc [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) {
Elliott Hughesa2e54f62011-11-17 13:01:30 -0800403 Class* c = gRegistry->Get<Class*>(id);
404 return gRegistry->Add(c->GetSuperClass());
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700405}
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
Elliott Hughesa2e54f62011-11-17 13:01:30 -0800487std::string Dbg::GetSignature(JDWP::RefTypeId refTypeId) {
488 Class* c = gRegistry->Get<Class*>(refTypeId);
489 CHECK(c != NULL);
490 return c->GetDescriptor()->ToModifiedUtf8();
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700491}
492
493const char* Dbg::GetSourceFile(JDWP::RefTypeId refTypeId) {
494 UNIMPLEMENTED(FATAL);
495 return NULL;
496}
497
498const char* Dbg::GetObjectTypeName(JDWP::ObjectId objectId) {
499 UNIMPLEMENTED(FATAL);
500 return NULL;
501}
502
503uint8_t Dbg::GetObjectTag(JDWP::ObjectId objectId) {
504 UNIMPLEMENTED(FATAL);
505 return 0;
506}
507
508int Dbg::GetTagWidth(int tag) {
509 UNIMPLEMENTED(FATAL);
510 return 0;
511}
512
513int Dbg::GetArrayLength(JDWP::ObjectId arrayId) {
514 UNIMPLEMENTED(FATAL);
515 return 0;
516}
517
518uint8_t Dbg::GetArrayElementTag(JDWP::ObjectId arrayId) {
519 UNIMPLEMENTED(FATAL);
520 return 0;
521}
522
523bool Dbg::OutputArray(JDWP::ObjectId arrayId, int firstIndex, int count, JDWP::ExpandBuf* pReply) {
524 UNIMPLEMENTED(FATAL);
525 return false;
526}
527
528bool Dbg::SetArrayElements(JDWP::ObjectId arrayId, int firstIndex, int count, const uint8_t* buf) {
529 UNIMPLEMENTED(FATAL);
530 return false;
531}
532
533JDWP::ObjectId Dbg::CreateString(const char* str) {
534 UNIMPLEMENTED(FATAL);
535 return 0;
536}
537
538JDWP::ObjectId Dbg::CreateObject(JDWP::RefTypeId classId) {
539 UNIMPLEMENTED(FATAL);
540 return 0;
541}
542
543JDWP::ObjectId Dbg::CreateArrayObject(JDWP::RefTypeId arrayTypeId, uint32_t length) {
544 UNIMPLEMENTED(FATAL);
545 return 0;
546}
547
548bool Dbg::MatchType(JDWP::RefTypeId instClassId, JDWP::RefTypeId classId) {
549 UNIMPLEMENTED(FATAL);
550 return false;
551}
552
553const char* Dbg::GetMethodName(JDWP::RefTypeId refTypeId, JDWP::MethodId id) {
554 UNIMPLEMENTED(FATAL);
555 return NULL;
556}
557
Elliott Hughesa2e54f62011-11-17 13:01:30 -0800558/*
559 * Augment the access flags for synthetic methods and fields by setting
560 * the (as described by the spec) "0xf0000000 bit". Also, strip out any
561 * flags not specified by the Java programming language.
562 */
563static uint32_t MangleAccessFlags(uint32_t accessFlags) {
564 accessFlags &= kAccJavaFlagsMask;
565 if ((accessFlags & kAccSynthetic) != 0) {
566 accessFlags |= 0xf0000000;
567 }
568 return accessFlags;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700569}
570
Elliott Hughesa2e54f62011-11-17 13:01:30 -0800571JDWP::FieldId ToFieldId(Field* f) {
572 return static_cast<JDWP::FieldId>(reinterpret_cast<uintptr_t>(f));
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700573}
574
Elliott Hughesa2e54f62011-11-17 13:01:30 -0800575JDWP::MethodId ToMethodId(Method* m) {
576 return static_cast<JDWP::MethodId>(reinterpret_cast<uintptr_t>(m));
577}
578
579void Dbg::OutputDeclaredFields(JDWP::RefTypeId refTypeId, bool withGeneric, JDWP::ExpandBuf* pReply) {
580 Class* c = gRegistry->Get<Class*>(refTypeId);
581 CHECK(c != NULL);
582
583 size_t instance_field_count = c->NumInstanceFields();
584 size_t static_field_count = c->NumStaticFields();
585
586 expandBufAdd4BE(pReply, instance_field_count + static_field_count);
587
588 for (size_t i = 0; i < instance_field_count + static_field_count; ++i) {
589 Field* f = (i < instance_field_count) ? c->GetInstanceField(i) : c->GetStaticField(i - instance_field_count);
590
591 expandBufAddFieldId(pReply, ToFieldId(f));
592 expandBufAddUtf8String(pReply, f->GetName()->ToModifiedUtf8().c_str());
593 expandBufAddUtf8String(pReply, f->GetTypeDescriptor());
594 if (withGeneric) {
595 static const char genericSignature[1] = "";
596 expandBufAddUtf8String(pReply, genericSignature);
597 }
598 expandBufAdd4BE(pReply, MangleAccessFlags(f->GetAccessFlags()));
599 }
600}
601
602void Dbg::OutputDeclaredMethods(JDWP::RefTypeId refTypeId, bool withGeneric, JDWP::ExpandBuf* pReply) {
603 Class* c = gRegistry->Get<Class*>(refTypeId);
604 CHECK(c != NULL);
605
606 size_t direct_method_count = c->NumDirectMethods();
607 size_t virtual_method_count = c->NumVirtualMethods();
608
609 expandBufAdd4BE(pReply, direct_method_count + virtual_method_count);
610
611 for (size_t i = 0; i < direct_method_count + virtual_method_count; ++i) {
612 Method* m = (i < direct_method_count) ? c->GetDirectMethod(i) : c->GetVirtualMethod(i - direct_method_count);
613
614 expandBufAddMethodId(pReply, ToMethodId(m));
615 expandBufAddUtf8String(pReply, m->GetName()->ToModifiedUtf8().c_str());
616 expandBufAddUtf8String(pReply, m->GetSignature()->ToModifiedUtf8().c_str());
617 if (withGeneric) {
618 static const char genericSignature[1] = "";
619 expandBufAddUtf8String(pReply, genericSignature);
620 }
621 expandBufAdd4BE(pReply, MangleAccessFlags(m->GetAccessFlags()));
622 }
623}
624
625void Dbg::OutputDeclaredInterfaces(JDWP::RefTypeId refTypeId, JDWP::ExpandBuf* pReply) {
626 Class* c = gRegistry->Get<Class*>(refTypeId);
627 CHECK(c != NULL);
628 size_t interface_count = c->NumInterfaces();
629 expandBufAdd4BE(pReply, interface_count);
630 for (size_t i = 0; i < interface_count; ++i) {
631 expandBufAddRefTypeId(pReply, gRegistry->Add(c->GetInterface(i)));
632 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700633}
634
635void Dbg::OutputLineTable(JDWP::RefTypeId refTypeId, JDWP::MethodId methodId, JDWP::ExpandBuf* pReply) {
636 UNIMPLEMENTED(FATAL);
637}
638
639void Dbg::OutputVariableTable(JDWP::RefTypeId refTypeId, JDWP::MethodId id, bool withGeneric, JDWP::ExpandBuf* pReply) {
640 UNIMPLEMENTED(FATAL);
641}
642
643uint8_t Dbg::GetFieldBasicTag(JDWP::ObjectId objId, JDWP::FieldId fieldId) {
644 UNIMPLEMENTED(FATAL);
645 return 0;
646}
647
648uint8_t Dbg::GetStaticFieldBasicTag(JDWP::RefTypeId refTypeId, JDWP::FieldId fieldId) {
649 UNIMPLEMENTED(FATAL);
650 return 0;
651}
652
653void Dbg::GetFieldValue(JDWP::ObjectId objectId, JDWP::FieldId fieldId, JDWP::ExpandBuf* pReply) {
654 UNIMPLEMENTED(FATAL);
655}
656
657void Dbg::SetFieldValue(JDWP::ObjectId objectId, JDWP::FieldId fieldId, uint64_t value, int width) {
658 UNIMPLEMENTED(FATAL);
659}
660
661void Dbg::GetStaticFieldValue(JDWP::RefTypeId refTypeId, JDWP::FieldId fieldId, JDWP::ExpandBuf* pReply) {
662 UNIMPLEMENTED(FATAL);
663}
664
665void Dbg::SetStaticFieldValue(JDWP::RefTypeId refTypeId, JDWP::FieldId fieldId, uint64_t rawValue, int width) {
666 UNIMPLEMENTED(FATAL);
667}
668
669char* Dbg::StringToUtf8(JDWP::ObjectId strId) {
670 UNIMPLEMENTED(FATAL);
671 return NULL;
672}
673
Elliott Hughesa2e54f62011-11-17 13:01:30 -0800674Thread* DecodeThread(JDWP::ObjectId threadId) {
675 Object* thread_peer = gRegistry->Get<Object*>(threadId);
676 CHECK(thread_peer != NULL);
677 return Thread::FromManagedThread(thread_peer);
678}
679
680bool Dbg::GetThreadName(JDWP::ObjectId threadId, std::string& name) {
681 ScopedThreadListLock thread_list_lock;
682 Thread* thread = DecodeThread(threadId);
683 if (thread == NULL) {
684 return false;
685 }
686 StringAppendF(&name, "<%d> %s", thread->GetThinLockId(), thread->GetName()->ToModifiedUtf8().c_str());
687 return true;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700688}
689
690JDWP::ObjectId Dbg::GetThreadGroup(JDWP::ObjectId threadId) {
691 UNIMPLEMENTED(FATAL);
692 return 0;
693}
694
695char* Dbg::GetThreadGroupName(JDWP::ObjectId threadGroupId) {
696 UNIMPLEMENTED(FATAL);
697 return NULL;
698}
699
700JDWP::ObjectId Dbg::GetThreadGroupParent(JDWP::ObjectId threadGroupId) {
701 UNIMPLEMENTED(FATAL);
702 return 0;
703}
704
705JDWP::ObjectId Dbg::GetSystemThreadGroupId() {
706 UNIMPLEMENTED(FATAL);
707 return 0;
708}
709
710JDWP::ObjectId Dbg::GetMainThreadGroupId() {
711 UNIMPLEMENTED(FATAL);
712 return 0;
713}
714
715bool Dbg::GetThreadStatus(JDWP::ObjectId threadId, uint32_t* threadStatus, uint32_t* suspendStatus) {
716 UNIMPLEMENTED(FATAL);
717 return false;
718}
719
720uint32_t Dbg::GetThreadSuspendCount(JDWP::ObjectId threadId) {
721 UNIMPLEMENTED(FATAL);
722 return 0;
723}
724
725bool Dbg::ThreadExists(JDWP::ObjectId threadId) {
Elliott Hughes761928d2011-11-16 18:33:03 -0800726 return DecodeThread(threadId) != NULL;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700727}
728
729bool Dbg::IsSuspended(JDWP::ObjectId threadId) {
Elliott Hughes761928d2011-11-16 18:33:03 -0800730 return DecodeThread(threadId)->IsSuspended();
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700731}
732
733//void Dbg::WaitForSuspend(JDWP::ObjectId threadId);
734
Elliott Hughesa2155262011-11-16 16:26:58 -0800735void Dbg::GetThreadGroupThreadsImpl(Object* thread_group, JDWP::ObjectId** ppThreadIds, uint32_t* pThreadCount) {
736 struct ThreadListVisitor {
737 static void Visit(Thread* t, void* arg) {
738 reinterpret_cast<ThreadListVisitor*>(arg)->Visit(t);
739 }
740
741 void Visit(Thread* t) {
742 if (t == Dbg::GetDebugThread()) {
743 // Skip the JDWP thread. Some debuggers get bent out of shape when they can't suspend and
744 // query all threads, so it's easier if we just don't tell them about this thread.
745 return;
746 }
747 if (thread_group == NULL || t->GetThreadGroup() == thread_group) {
748 threads.push_back(gRegistry->Add(t->GetPeer()));
749 }
750 }
751
752 Object* thread_group;
753 std::vector<JDWP::ObjectId> threads;
754 };
755
756 ThreadListVisitor tlv;
757 tlv.thread_group = thread_group;
758
759 {
760 ScopedThreadListLock thread_list_lock;
761 Runtime::Current()->GetThreadList()->ForEach(ThreadListVisitor::Visit, &tlv);
762 }
763
764 *pThreadCount = tlv.threads.size();
765 if (*pThreadCount == 0) {
766 *ppThreadIds = NULL;
767 } else {
768 *ppThreadIds = new JDWP::ObjectId[*pThreadCount];
769 for (size_t i = 0; i < *pThreadCount; ++i) {
770 (*ppThreadIds)[i] = tlv.threads[i];
771 }
772 }
773}
774
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700775void Dbg::GetThreadGroupThreads(JDWP::ObjectId threadGroupId, JDWP::ObjectId** ppThreadIds, uint32_t* pThreadCount) {
Elliott Hughesa2155262011-11-16 16:26:58 -0800776 GetThreadGroupThreadsImpl(gRegistry->Get<Object*>(threadGroupId), ppThreadIds, pThreadCount);
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700777}
778
779void Dbg::GetAllThreads(JDWP::ObjectId** ppThreadIds, uint32_t* pThreadCount) {
Elliott Hughesa2155262011-11-16 16:26:58 -0800780 GetThreadGroupThreadsImpl(NULL, ppThreadIds, pThreadCount);
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700781}
782
783int Dbg::GetThreadFrameCount(JDWP::ObjectId threadId) {
Elliott Hughesa2e54f62011-11-17 13:01:30 -0800784 struct CountStackDepthVisitor : public Thread::StackVisitor {
785 CountStackDepthVisitor() : depth(0) {}
786 virtual void VisitFrame(const Frame& frame, uintptr_t pc) {
787 ++depth;
788 }
789 size_t depth;
790 };
791 CountStackDepthVisitor visitor;
792 DecodeThread(threadId)->WalkStack(&visitor);
793 return visitor.depth;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700794}
795
796bool Dbg::GetThreadFrame(JDWP::ObjectId threadId, int num, JDWP::FrameId* pFrameId, JDWP::JdwpLocation* pLoc) {
797 UNIMPLEMENTED(FATAL);
798 return false;
799}
800
801JDWP::ObjectId Dbg::GetThreadSelfId() {
Elliott Hughes475fc232011-10-25 15:00:35 -0700802 return gRegistry->Add(Thread::Current()->GetPeer());
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700803}
804
Elliott Hughes475fc232011-10-25 15:00:35 -0700805void Dbg::SuspendVM() {
Elliott Hughesa2155262011-11-16 16:26:58 -0800806 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 -0700807 Runtime::Current()->GetThreadList()->SuspendAll(true);
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700808}
809
810void Dbg::ResumeVM() {
Elliott Hughes475fc232011-10-25 15:00:35 -0700811 Runtime::Current()->GetThreadList()->ResumeAll(true);
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700812}
813
814void Dbg::SuspendThread(JDWP::ObjectId threadId) {
815 UNIMPLEMENTED(FATAL);
816}
817
818void Dbg::ResumeThread(JDWP::ObjectId threadId) {
819 UNIMPLEMENTED(FATAL);
820}
821
822void Dbg::SuspendSelf() {
Elliott Hughes475fc232011-10-25 15:00:35 -0700823 Runtime::Current()->GetThreadList()->SuspendSelfForDebugger();
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700824}
825
826bool Dbg::GetThisObject(JDWP::ObjectId threadId, JDWP::FrameId frameId, JDWP::ObjectId* pThisId) {
827 UNIMPLEMENTED(FATAL);
828 return false;
829}
830
831void Dbg::GetLocalValue(JDWP::ObjectId threadId, JDWP::FrameId frameId, int slot, uint8_t tag, uint8_t* buf, int expectedLen) {
832 UNIMPLEMENTED(FATAL);
833}
834
835void Dbg::SetLocalValue(JDWP::ObjectId threadId, JDWP::FrameId frameId, int slot, uint8_t tag, uint64_t value, int width) {
836 UNIMPLEMENTED(FATAL);
837}
838
839void Dbg::PostLocationEvent(const Method* method, int pcOffset, Object* thisPtr, int eventFlags) {
840 UNIMPLEMENTED(FATAL);
841}
842
843void Dbg::PostException(void* throwFp, int throwRelPc, void* catchFp, int catchRelPc, Object* exception) {
844 UNIMPLEMENTED(FATAL);
845}
846
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700847void Dbg::PostClassPrepare(Class* c) {
848 UNIMPLEMENTED(FATAL);
849}
850
851bool Dbg::WatchLocation(const JDWP::JdwpLocation* pLoc) {
852 UNIMPLEMENTED(FATAL);
853 return false;
854}
855
856void Dbg::UnwatchLocation(const JDWP::JdwpLocation* pLoc) {
857 UNIMPLEMENTED(FATAL);
858}
859
860bool Dbg::ConfigureStep(JDWP::ObjectId threadId, JDWP::JdwpStepSize size, JDWP::JdwpStepDepth depth) {
861 UNIMPLEMENTED(FATAL);
862 return false;
863}
864
865void Dbg::UnconfigureStep(JDWP::ObjectId threadId) {
866 UNIMPLEMENTED(FATAL);
867}
868
869JDWP::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) {
870 UNIMPLEMENTED(FATAL);
871 return JDWP::ERR_NONE;
872}
873
874void Dbg::ExecuteMethod(DebugInvokeReq* pReq) {
875 UNIMPLEMENTED(FATAL);
876}
877
878void Dbg::RegisterObjectId(JDWP::ObjectId id) {
879 UNIMPLEMENTED(FATAL);
880}
881
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -0700882/*
883 * "buf" contains a full JDWP packet, possibly with multiple chunks. We
884 * need to process each, accumulate the replies, and ship the whole thing
885 * back.
886 *
887 * Returns "true" if we have a reply. The reply buffer is newly allocated,
888 * and includes the chunk type/length, followed by the data.
889 *
890 * TODO: we currently assume that the request and reply include a single
891 * chunk. If this becomes inconvenient we will need to adapt.
892 */
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700893bool Dbg::DdmHandlePacket(const uint8_t* buf, int dataLen, uint8_t** pReplyBuf, int* pReplyLen) {
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -0700894 CHECK_GE(dataLen, 0);
895
896 Thread* self = Thread::Current();
897 JNIEnv* env = self->GetJniEnv();
898
899 static jclass Chunk_class = env->FindClass("org/apache/harmony/dalvik/ddmc/Chunk");
900 static jclass DdmServer_class = env->FindClass("org/apache/harmony/dalvik/ddmc/DdmServer");
901 static jmethodID dispatch_mid = env->GetStaticMethodID(DdmServer_class, "dispatch",
902 "(I[BII)Lorg/apache/harmony/dalvik/ddmc/Chunk;");
903 static jfieldID data_fid = env->GetFieldID(Chunk_class, "data", "[B");
904 static jfieldID length_fid = env->GetFieldID(Chunk_class, "length", "I");
905 static jfieldID offset_fid = env->GetFieldID(Chunk_class, "offset", "I");
906 static jfieldID type_fid = env->GetFieldID(Chunk_class, "type", "I");
907
908 // Create a byte[] corresponding to 'buf'.
Elliott Hughes6a5bd492011-10-28 14:33:57 -0700909 ScopedLocalRef<jbyteArray> dataArray(env, env->NewByteArray(dataLen));
910 if (dataArray.get() == NULL) {
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -0700911 LOG(WARNING) << "byte[] allocation failed: " << dataLen;
912 env->ExceptionClear();
913 return false;
914 }
Elliott Hughes6a5bd492011-10-28 14:33:57 -0700915 env->SetByteArrayRegion(dataArray.get(), 0, dataLen, reinterpret_cast<const jbyte*>(buf));
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -0700916
917 const int kChunkHdrLen = 8;
918
919 // Run through and find all chunks. [Currently just find the first.]
Elliott Hughes6a5bd492011-10-28 14:33:57 -0700920 ScopedByteArrayRO contents(env, dataArray.get());
Elliott Hughesf7c3b662011-10-27 12:04:56 -0700921 jint type = JDWP::Get4BE(reinterpret_cast<const uint8_t*>(&contents[0]));
922 jint length = JDWP::Get4BE(reinterpret_cast<const uint8_t*>(&contents[4]));
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -0700923 jint offset = kChunkHdrLen;
924 if (offset + length > dataLen) {
925 LOG(WARNING) << StringPrintf("bad chunk found (len=%u pktLen=%d)", length, dataLen);
926 return false;
927 }
928
929 // Call "private static Chunk dispatch(int type, byte[] data, int offset, int length)".
Elliott Hughes6a5bd492011-10-28 14:33:57 -0700930 ScopedLocalRef<jobject> chunk(env, env->CallStaticObjectMethod(DdmServer_class, dispatch_mid, type, dataArray.get(), offset, length));
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -0700931 if (env->ExceptionCheck()) {
932 LOG(INFO) << StringPrintf("Exception thrown by dispatcher for 0x%08x", type);
933 env->ExceptionDescribe();
934 env->ExceptionClear();
935 return false;
936 }
937
Elliott Hughes6a5bd492011-10-28 14:33:57 -0700938 if (chunk.get() == NULL) {
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -0700939 return false;
940 }
941
942 /*
943 * Pull the pieces out of the chunk. We copy the results into a
944 * newly-allocated buffer that the caller can free. We don't want to
945 * continue using the Chunk object because nothing has a reference to it.
946 *
947 * We could avoid this by returning type/data/offset/length and having
948 * the caller be aware of the object lifetime issues, but that
949 * integrates the JDWP code more tightly into the VM, and doesn't work
950 * if we have responses for multiple chunks.
951 *
952 * So we're pretty much stuck with copying data around multiple times.
953 */
Elliott Hughes6a5bd492011-10-28 14:33:57 -0700954 ScopedLocalRef<jbyteArray> replyData(env, reinterpret_cast<jbyteArray>(env->GetObjectField(chunk.get(), data_fid)));
955 length = env->GetIntField(chunk.get(), length_fid);
956 offset = env->GetIntField(chunk.get(), offset_fid);
957 type = env->GetIntField(chunk.get(), type_fid);
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -0700958
Elliott Hughes6a5bd492011-10-28 14:33:57 -0700959 LOG(VERBOSE) << StringPrintf("DDM reply: type=0x%08x data=%p offset=%d length=%d", type, replyData.get(), offset, length);
960 if (length == 0 || replyData.get() == NULL) {
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -0700961 return false;
962 }
963
Elliott Hughes6a5bd492011-10-28 14:33:57 -0700964 jsize replyLength = env->GetArrayLength(replyData.get());
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -0700965 if (offset + length > replyLength) {
966 LOG(WARNING) << StringPrintf("chunk off=%d len=%d exceeds reply array len %d", offset, length, replyLength);
967 return false;
968 }
969
970 uint8_t* reply = new uint8_t[length + kChunkHdrLen];
971 if (reply == NULL) {
972 LOG(WARNING) << "malloc failed: " << (length + kChunkHdrLen);
973 return false;
974 }
Elliott Hughesf7c3b662011-10-27 12:04:56 -0700975 JDWP::Set4BE(reply + 0, type);
976 JDWP::Set4BE(reply + 4, length);
Elliott Hughes6a5bd492011-10-28 14:33:57 -0700977 env->GetByteArrayRegion(replyData.get(), offset, length, reinterpret_cast<jbyte*>(reply + kChunkHdrLen));
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -0700978
979 *pReplyBuf = reply;
980 *pReplyLen = length + kChunkHdrLen;
981
982 LOG(VERBOSE) << StringPrintf("dvmHandleDdm returning type=%.4s buf=%p len=%d", (char*) reply, reply, length);
983 return true;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700984}
985
Elliott Hughesa2155262011-11-16 16:26:58 -0800986void Dbg::DdmBroadcast(bool connect) {
Elliott Hughes47fce012011-10-25 18:37:19 -0700987 LOG(VERBOSE) << "Broadcasting DDM " << (connect ? "connect" : "disconnect") << "...";
988
989 Thread* self = Thread::Current();
990 if (self->GetState() != Thread::kRunnable) {
991 LOG(ERROR) << "DDM broadcast in thread state " << self->GetState();
992 /* try anyway? */
993 }
994
995 JNIEnv* env = self->GetJniEnv();
996 static jclass DdmServer_class = env->FindClass("org/apache/harmony/dalvik/ddmc/DdmServer");
997 static jmethodID broadcast_mid = env->GetStaticMethodID(DdmServer_class, "broadcast", "(I)V");
998 jint event = connect ? 1 /*DdmServer.CONNECTED*/ : 2 /*DdmServer.DISCONNECTED*/;
999 env->CallStaticVoidMethod(DdmServer_class, broadcast_mid, event);
1000 if (env->ExceptionCheck()) {
1001 LOG(ERROR) << "DdmServer.broadcast " << event << " failed";
1002 env->ExceptionDescribe();
1003 env->ExceptionClear();
1004 }
1005}
1006
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001007void Dbg::DdmConnected() {
Elliott Hughesa2155262011-11-16 16:26:58 -08001008 Dbg::DdmBroadcast(true);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001009}
1010
1011void Dbg::DdmDisconnected() {
Elliott Hughesa2155262011-11-16 16:26:58 -08001012 Dbg::DdmBroadcast(false);
Elliott Hughes47fce012011-10-25 18:37:19 -07001013 gDdmThreadNotification = false;
1014}
1015
1016/*
Elliott Hughes82188472011-11-07 18:11:48 -08001017 * Send a notification when a thread starts, stops, or changes its name.
Elliott Hughes47fce012011-10-25 18:37:19 -07001018 *
1019 * Because we broadcast the full set of threads when the notifications are
1020 * first enabled, it's possible for "thread" to be actively executing.
1021 */
Elliott Hughes82188472011-11-07 18:11:48 -08001022void Dbg::DdmSendThreadNotification(Thread* t, uint32_t type) {
Elliott Hughes47fce012011-10-25 18:37:19 -07001023 if (!gDdmThreadNotification) {
1024 return;
1025 }
1026
Elliott Hughes82188472011-11-07 18:11:48 -08001027 if (type == CHUNK_TYPE("THDE")) {
Elliott Hughes47fce012011-10-25 18:37:19 -07001028 uint8_t buf[4];
Elliott Hughesf7c3b662011-10-27 12:04:56 -07001029 JDWP::Set4BE(&buf[0], t->GetThinLockId());
Elliott Hughes47fce012011-10-25 18:37:19 -07001030 Dbg::DdmSendChunk(CHUNK_TYPE("THDE"), 4, buf);
Elliott Hughes82188472011-11-07 18:11:48 -08001031 } else {
1032 CHECK(type == CHUNK_TYPE("THCR") || type == CHUNK_TYPE("THNM")) << type;
1033 SirtRef<String> name(t->GetName());
1034 size_t char_count = (name.get() != NULL) ? name->GetLength() : 0;
1035 const jchar* chars = name->GetCharArray()->GetData();
1036
Elliott Hughes21f32d72011-11-09 17:44:13 -08001037 std::vector<uint8_t> bytes;
Elliott Hughes545a0642011-11-08 19:10:03 -08001038 JDWP::Append4BE(bytes, t->GetThinLockId());
1039 JDWP::AppendUtf16BE(bytes, chars, char_count);
Elliott Hughes21f32d72011-11-09 17:44:13 -08001040 CHECK_EQ(bytes.size(), char_count*2 + sizeof(uint32_t)*2);
1041 Dbg::DdmSendChunk(type, bytes);
Elliott Hughes47fce012011-10-25 18:37:19 -07001042 }
1043}
1044
Elliott Hughesa2155262011-11-16 16:26:58 -08001045static void DdmSendThreadStartCallback(Thread* t, void*) {
Elliott Hughes82188472011-11-07 18:11:48 -08001046 Dbg::DdmSendThreadNotification(t, CHUNK_TYPE("THCR"));
Elliott Hughes47fce012011-10-25 18:37:19 -07001047}
1048
1049void Dbg::DdmSetThreadNotification(bool enable) {
1050 // We lock the thread list to avoid sending duplicate events or missing
1051 // a thread change. We should be okay holding this lock while sending
1052 // the messages out. (We have to hold it while accessing a live thread.)
Elliott Hughesbbd9d832011-11-07 14:40:00 -08001053 ScopedThreadListLock thread_list_lock;
Elliott Hughes47fce012011-10-25 18:37:19 -07001054
1055 gDdmThreadNotification = enable;
1056 if (enable) {
Elliott Hughesbfe487b2011-10-26 15:48:55 -07001057 Runtime::Current()->GetThreadList()->ForEach(DdmSendThreadStartCallback, NULL);
Elliott Hughes47fce012011-10-25 18:37:19 -07001058 }
1059}
1060
Elliott Hughesa2155262011-11-16 16:26:58 -08001061void Dbg::PostThreadStartOrStop(Thread* t, uint32_t type) {
Elliott Hughes47fce012011-10-25 18:37:19 -07001062 if (gDebuggerActive) {
1063 JDWP::ObjectId id = gRegistry->Add(t->GetPeer());
Elliott Hughes82188472011-11-07 18:11:48 -08001064 gJdwpState->PostThreadChange(id, type == CHUNK_TYPE("THCR"));
Elliott Hughes47fce012011-10-25 18:37:19 -07001065 }
Elliott Hughes82188472011-11-07 18:11:48 -08001066 Dbg::DdmSendThreadNotification(t, type);
Elliott Hughes47fce012011-10-25 18:37:19 -07001067}
1068
1069void Dbg::PostThreadStart(Thread* t) {
Elliott Hughesa2155262011-11-16 16:26:58 -08001070 Dbg::PostThreadStartOrStop(t, CHUNK_TYPE("THCR"));
Elliott Hughes47fce012011-10-25 18:37:19 -07001071}
1072
1073void Dbg::PostThreadDeath(Thread* t) {
Elliott Hughesa2155262011-11-16 16:26:58 -08001074 Dbg::PostThreadStartOrStop(t, CHUNK_TYPE("THDE"));
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001075}
1076
Elliott Hughes82188472011-11-07 18:11:48 -08001077void Dbg::DdmSendChunk(uint32_t type, size_t byte_count, const uint8_t* buf) {
Elliott Hughes3bb81562011-10-21 18:52:59 -07001078 CHECK(buf != NULL);
1079 iovec vec[1];
1080 vec[0].iov_base = reinterpret_cast<void*>(const_cast<uint8_t*>(buf));
1081 vec[0].iov_len = byte_count;
1082 Dbg::DdmSendChunkV(type, vec, 1);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001083}
1084
Elliott Hughes21f32d72011-11-09 17:44:13 -08001085void Dbg::DdmSendChunk(uint32_t type, const std::vector<uint8_t>& bytes) {
1086 DdmSendChunk(type, bytes.size(), &bytes[0]);
1087}
1088
Elliott Hughes82188472011-11-07 18:11:48 -08001089void Dbg::DdmSendChunkV(uint32_t type, const struct iovec* iov, int iovcnt) {
Elliott Hughes3bb81562011-10-21 18:52:59 -07001090 if (gJdwpState == NULL) {
1091 LOG(VERBOSE) << "Debugger thread not active, ignoring DDM send: " << type;
1092 } else {
Elliott Hughes376a7a02011-10-24 18:35:55 -07001093 gJdwpState->DdmSendChunkV(type, iov, iovcnt);
Elliott Hughes3bb81562011-10-21 18:52:59 -07001094 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001095}
1096
Elliott Hughes767a1472011-10-26 18:49:02 -07001097int Dbg::DdmHandleHpifChunk(HpifWhen when) {
1098 if (when == HPIF_WHEN_NOW) {
Elliott Hughes7162ad92011-10-27 14:08:42 -07001099 DdmSendHeapInfo(when);
Elliott Hughes767a1472011-10-26 18:49:02 -07001100 return true;
1101 }
1102
1103 if (when != HPIF_WHEN_NEVER && when != HPIF_WHEN_NEXT_GC && when != HPIF_WHEN_EVERY_GC) {
1104 LOG(ERROR) << "invalid HpifWhen value: " << static_cast<int>(when);
1105 return false;
1106 }
1107
1108 gDdmHpifWhen = when;
1109 return true;
1110}
1111
1112bool Dbg::DdmHandleHpsgNhsgChunk(Dbg::HpsgWhen when, Dbg::HpsgWhat what, bool native) {
1113 if (when != HPSG_WHEN_NEVER && when != HPSG_WHEN_EVERY_GC) {
1114 LOG(ERROR) << "invalid HpsgWhen value: " << static_cast<int>(when);
1115 return false;
1116 }
1117
1118 if (what != HPSG_WHAT_MERGED_OBJECTS && what != HPSG_WHAT_DISTINCT_OBJECTS) {
1119 LOG(ERROR) << "invalid HpsgWhat value: " << static_cast<int>(what);
1120 return false;
1121 }
1122
1123 if (native) {
1124 gDdmNhsgWhen = when;
1125 gDdmNhsgWhat = what;
1126 } else {
1127 gDdmHpsgWhen = when;
1128 gDdmHpsgWhat = what;
1129 }
1130 return true;
1131}
1132
Elliott Hughes7162ad92011-10-27 14:08:42 -07001133void Dbg::DdmSendHeapInfo(HpifWhen reason) {
1134 // If there's a one-shot 'when', reset it.
1135 if (reason == gDdmHpifWhen) {
1136 if (gDdmHpifWhen == HPIF_WHEN_NEXT_GC) {
1137 gDdmHpifWhen = HPIF_WHEN_NEVER;
1138 }
1139 }
1140
1141 /*
1142 * Chunk HPIF (client --> server)
1143 *
1144 * Heap Info. General information about the heap,
1145 * suitable for a summary display.
1146 *
1147 * [u4]: number of heaps
1148 *
1149 * For each heap:
1150 * [u4]: heap ID
1151 * [u8]: timestamp in ms since Unix epoch
1152 * [u1]: capture reason (same as 'when' value from server)
1153 * [u4]: max heap size in bytes (-Xmx)
1154 * [u4]: current heap size in bytes
1155 * [u4]: current number of bytes allocated
1156 * [u4]: current number of objects allocated
1157 */
1158 uint8_t heap_count = 1;
Elliott Hughes21f32d72011-11-09 17:44:13 -08001159 std::vector<uint8_t> bytes;
Elliott Hughes545a0642011-11-08 19:10:03 -08001160 JDWP::Append4BE(bytes, heap_count);
1161 JDWP::Append4BE(bytes, 1); // Heap id (bogus; we only have one heap).
1162 JDWP::Append8BE(bytes, MilliTime());
1163 JDWP::Append1BE(bytes, reason);
1164 JDWP::Append4BE(bytes, Heap::GetMaxMemory()); // Max allowed heap size in bytes.
1165 JDWP::Append4BE(bytes, Heap::GetTotalMemory()); // Current heap size in bytes.
1166 JDWP::Append4BE(bytes, Heap::GetBytesAllocated());
1167 JDWP::Append4BE(bytes, Heap::GetObjectsAllocated());
Elliott Hughes21f32d72011-11-09 17:44:13 -08001168 CHECK_EQ(bytes.size(), 4U + (heap_count * (4 + 8 + 1 + 4 + 4 + 4 + 4)));
1169 Dbg::DdmSendChunk(CHUNK_TYPE("HPIF"), bytes);
Elliott Hughes767a1472011-10-26 18:49:02 -07001170}
1171
Elliott Hughes6a5bd492011-10-28 14:33:57 -07001172enum HpsgSolidity {
1173 SOLIDITY_FREE = 0,
1174 SOLIDITY_HARD = 1,
1175 SOLIDITY_SOFT = 2,
1176 SOLIDITY_WEAK = 3,
1177 SOLIDITY_PHANTOM = 4,
1178 SOLIDITY_FINALIZABLE = 5,
1179 SOLIDITY_SWEEP = 6,
1180};
1181
1182enum HpsgKind {
1183 KIND_OBJECT = 0,
1184 KIND_CLASS_OBJECT = 1,
1185 KIND_ARRAY_1 = 2,
1186 KIND_ARRAY_2 = 3,
1187 KIND_ARRAY_4 = 4,
1188 KIND_ARRAY_8 = 5,
1189 KIND_UNKNOWN = 6,
1190 KIND_NATIVE = 7,
1191};
1192
1193#define HPSG_PARTIAL (1<<7)
1194#define HPSG_STATE(solidity, kind) ((uint8_t)((((kind) & 0x7) << 3) | ((solidity) & 0x7)))
1195
1196struct HeapChunkContext {
1197 std::vector<uint8_t> buf;
1198 uint8_t* p;
1199 uint8_t* pieceLenField;
1200 size_t totalAllocationUnits;
Elliott Hughes82188472011-11-07 18:11:48 -08001201 uint32_t type;
Elliott Hughes6a5bd492011-10-28 14:33:57 -07001202 bool merge;
1203 bool needHeader;
1204
1205 // Maximum chunk size. Obtain this from the formula:
1206 // (((maximum_heap_size / ALLOCATION_UNIT_SIZE) + 255) / 256) * 2
1207 HeapChunkContext(bool merge, bool native)
1208 : buf(16384 - 16),
1209 type(0),
1210 merge(merge) {
1211 Reset();
1212 if (native) {
1213 type = CHUNK_TYPE("NHSG");
1214 } else {
1215 type = merge ? CHUNK_TYPE("HPSG") : CHUNK_TYPE("HPSO");
1216 }
1217 }
1218
1219 ~HeapChunkContext() {
1220 if (p > &buf[0]) {
1221 Flush();
1222 }
1223 }
1224
1225 void EnsureHeader(const void* chunk_ptr) {
1226 if (!needHeader) {
1227 return;
1228 }
1229
1230 // Start a new HPSx chunk.
1231 JDWP::Write4BE(&p, 1); // Heap id (bogus; we only have one heap).
1232 JDWP::Write1BE(&p, 8); // Size of allocation unit, in bytes.
1233
1234 JDWP::Write4BE(&p, reinterpret_cast<uintptr_t>(chunk_ptr)); // virtual address of segment start.
1235 JDWP::Write4BE(&p, 0); // offset of this piece (relative to the virtual address).
1236 // [u4]: length of piece, in allocation units
1237 // We won't know this until we're done, so save the offset and stuff in a dummy value.
1238 pieceLenField = p;
1239 JDWP::Write4BE(&p, 0x55555555);
1240 needHeader = false;
1241 }
1242
1243 void Flush() {
1244 // Patch the "length of piece" field.
1245 CHECK_LE(&buf[0], pieceLenField);
1246 CHECK_LE(pieceLenField, p);
1247 JDWP::Set4BE(pieceLenField, totalAllocationUnits);
1248
1249 Dbg::DdmSendChunk(type, p - &buf[0], &buf[0]);
1250 Reset();
1251 }
1252
Elliott Hughesa2155262011-11-16 16:26:58 -08001253 static void HeapChunkCallback(const void* chunk_ptr, size_t chunk_len, const void* user_ptr, size_t user_len, void* arg) {
1254 reinterpret_cast<HeapChunkContext*>(arg)->HeapChunkCallback(chunk_ptr, chunk_len, user_ptr, user_len);
1255 }
1256
Elliott Hughes6a5bd492011-10-28 14:33:57 -07001257 private:
Elliott Hughesa2155262011-11-16 16:26:58 -08001258 enum { ALLOCATION_UNIT_SIZE = 8 };
1259
Elliott Hughes6a5bd492011-10-28 14:33:57 -07001260 void Reset() {
1261 p = &buf[0];
1262 totalAllocationUnits = 0;
1263 needHeader = true;
1264 pieceLenField = NULL;
1265 }
1266
Elliott Hughesa2155262011-11-16 16:26:58 -08001267 void HeapChunkCallback(const void* chunk_ptr, size_t chunk_len, const void* user_ptr, size_t user_len) {
1268 CHECK_EQ((chunk_len & (ALLOCATION_UNIT_SIZE-1)), 0U);
Elliott Hughes6a5bd492011-10-28 14:33:57 -07001269
Elliott Hughesa2155262011-11-16 16:26:58 -08001270 /* Make sure there's enough room left in the buffer.
1271 * We need to use two bytes for every fractional 256
1272 * allocation units used by the chunk.
1273 */
1274 {
1275 size_t needed = (((chunk_len/ALLOCATION_UNIT_SIZE + 255) / 256) * 2);
1276 size_t bytesLeft = buf.size() - (size_t)(p - &buf[0]);
1277 if (bytesLeft < needed) {
1278 Flush();
1279 }
Elliott Hughes6a5bd492011-10-28 14:33:57 -07001280
Elliott Hughesa2155262011-11-16 16:26:58 -08001281 bytesLeft = buf.size() - (size_t)(p - &buf[0]);
1282 if (bytesLeft < needed) {
1283 LOG(WARNING) << "chunk is too big to transmit (chunk_len=" << chunk_len << ", " << needed << " bytes)";
1284 return;
1285 }
1286 }
1287
1288 // OLD-TODO: notice when there's a gap and start a new heap, or at least a new range.
1289 EnsureHeader(chunk_ptr);
1290
1291 // Determine the type of this chunk.
1292 // OLD-TODO: if context.merge, see if this chunk is different from the last chunk.
1293 // If it's the same, we should combine them.
1294 uint8_t state = ExamineObject(reinterpret_cast<const Object*>(user_ptr), (type == CHUNK_TYPE("NHSG")));
1295
1296 // Write out the chunk description.
1297 chunk_len /= ALLOCATION_UNIT_SIZE; // convert to allocation units
1298 totalAllocationUnits += chunk_len;
1299 while (chunk_len > 256) {
1300 *p++ = state | HPSG_PARTIAL;
1301 *p++ = 255; // length - 1
1302 chunk_len -= 256;
1303 }
1304 *p++ = state;
1305 *p++ = chunk_len - 1;
Elliott Hughes6a5bd492011-10-28 14:33:57 -07001306 }
1307
Elliott Hughesa2155262011-11-16 16:26:58 -08001308 uint8_t ExamineObject(const Object* o, bool is_native_heap) {
1309 if (o == NULL) {
1310 return HPSG_STATE(SOLIDITY_FREE, 0);
1311 }
Elliott Hughes6a5bd492011-10-28 14:33:57 -07001312
Elliott Hughesa2155262011-11-16 16:26:58 -08001313 // It's an allocated chunk. Figure out what it is.
Elliott Hughes6a5bd492011-10-28 14:33:57 -07001314
Elliott Hughesa2155262011-11-16 16:26:58 -08001315 // If we're looking at the native heap, we'll just return
1316 // (SOLIDITY_HARD, KIND_NATIVE) for all allocated chunks.
1317 if (is_native_heap || !Heap::IsLiveObjectLocked(o)) {
1318 return HPSG_STATE(SOLIDITY_HARD, KIND_NATIVE);
1319 }
1320
1321 Class* c = o->GetClass();
1322 if (c == NULL) {
1323 // The object was probably just created but hasn't been initialized yet.
1324 return HPSG_STATE(SOLIDITY_HARD, KIND_OBJECT);
1325 }
1326
1327 if (!Heap::IsHeapAddress(c)) {
1328 LOG(WARNING) << "invalid class for managed heap object: " << o << " " << c;
1329 return HPSG_STATE(SOLIDITY_HARD, KIND_UNKNOWN);
1330 }
1331
1332 if (c->IsClassClass()) {
1333 return HPSG_STATE(SOLIDITY_HARD, KIND_CLASS_OBJECT);
1334 }
1335
1336 if (c->IsArrayClass()) {
1337 if (o->IsObjectArray()) {
1338 return HPSG_STATE(SOLIDITY_HARD, KIND_ARRAY_4);
1339 }
1340 switch (c->GetComponentSize()) {
1341 case 1: return HPSG_STATE(SOLIDITY_HARD, KIND_ARRAY_1);
1342 case 2: return HPSG_STATE(SOLIDITY_HARD, KIND_ARRAY_2);
1343 case 4: return HPSG_STATE(SOLIDITY_HARD, KIND_ARRAY_4);
1344 case 8: return HPSG_STATE(SOLIDITY_HARD, KIND_ARRAY_8);
1345 }
1346 }
1347
Elliott Hughes6a5bd492011-10-28 14:33:57 -07001348 return HPSG_STATE(SOLIDITY_HARD, KIND_OBJECT);
1349 }
1350
Elliott Hughesa2155262011-11-16 16:26:58 -08001351 DISALLOW_COPY_AND_ASSIGN(HeapChunkContext);
1352};
Elliott Hughes6a5bd492011-10-28 14:33:57 -07001353
1354void Dbg::DdmSendHeapSegments(bool native) {
1355 Dbg::HpsgWhen when;
1356 Dbg::HpsgWhat what;
1357 if (!native) {
1358 when = gDdmHpsgWhen;
1359 what = gDdmHpsgWhat;
1360 } else {
1361 when = gDdmNhsgWhen;
1362 what = gDdmNhsgWhat;
1363 }
1364 if (when == HPSG_WHEN_NEVER) {
1365 return;
1366 }
1367
1368 // Figure out what kind of chunks we'll be sending.
1369 CHECK(what == HPSG_WHAT_MERGED_OBJECTS || what == HPSG_WHAT_DISTINCT_OBJECTS) << static_cast<int>(what);
1370
1371 // First, send a heap start chunk.
1372 uint8_t heap_id[4];
1373 JDWP::Set4BE(&heap_id[0], 1); // Heap id (bogus; we only have one heap).
1374 Dbg::DdmSendChunk(native ? CHUNK_TYPE("NHST") : CHUNK_TYPE("HPST"), sizeof(heap_id), heap_id);
1375
1376 // Send a series of heap segment chunks.
Elliott Hughesa2155262011-11-16 16:26:58 -08001377 HeapChunkContext context((what == HPSG_WHAT_MERGED_OBJECTS), native);
1378 if (native) {
1379 dlmalloc_walk_heap(HeapChunkContext::HeapChunkCallback, &context);
1380 } else {
1381 Heap::WalkHeap(HeapChunkContext::HeapChunkCallback, &context);
1382 }
Elliott Hughes6a5bd492011-10-28 14:33:57 -07001383
1384 // Finally, send a heap end chunk.
1385 Dbg::DdmSendChunk(native ? CHUNK_TYPE("NHEN") : CHUNK_TYPE("HPEN"), sizeof(heap_id), heap_id);
Elliott Hughes767a1472011-10-26 18:49:02 -07001386}
1387
Elliott Hughes545a0642011-11-08 19:10:03 -08001388void Dbg::SetAllocTrackingEnabled(bool enabled) {
1389 MutexLock mu(gAllocTrackerLock);
1390 if (enabled) {
1391 if (recent_allocation_records_ == NULL) {
1392 LOG(INFO) << "Enabling alloc tracker (" << kNumAllocRecords << " entries, "
1393 << kMaxAllocRecordStackDepth << " frames --> "
1394 << (sizeof(AllocRecord) * kNumAllocRecords) << " bytes)";
1395 gAllocRecordHead = gAllocRecordCount = 0;
1396 recent_allocation_records_ = new AllocRecord[kNumAllocRecords];
1397 CHECK(recent_allocation_records_ != NULL);
1398 }
1399 } else {
1400 delete[] recent_allocation_records_;
1401 recent_allocation_records_ = NULL;
1402 }
1403}
1404
1405struct AllocRecordStackVisitor : public Thread::StackVisitor {
1406 AllocRecordStackVisitor(AllocRecord* record) : record(record), depth(0) {
1407 }
1408
1409 virtual void VisitFrame(const Frame& f, uintptr_t pc) {
1410 if (depth >= kMaxAllocRecordStackDepth) {
1411 return;
1412 }
1413 Method* m = f.GetMethod();
1414 if (m == NULL || m->IsCalleeSaveMethod()) {
1415 return;
1416 }
1417 record->stack[depth].method = m;
1418 record->stack[depth].raw_pc = pc;
1419 ++depth;
1420 }
1421
1422 ~AllocRecordStackVisitor() {
1423 // Clear out any unused stack trace elements.
1424 for (; depth < kMaxAllocRecordStackDepth; ++depth) {
1425 record->stack[depth].method = NULL;
1426 record->stack[depth].raw_pc = 0;
1427 }
1428 }
1429
1430 AllocRecord* record;
1431 size_t depth;
1432};
1433
1434void Dbg::RecordAllocation(Class* type, size_t byte_count) {
1435 Thread* self = Thread::Current();
1436 CHECK(self != NULL);
1437
1438 MutexLock mu(gAllocTrackerLock);
1439 if (recent_allocation_records_ == NULL) {
1440 return;
1441 }
1442
1443 // Advance and clip.
1444 if (++gAllocRecordHead == kNumAllocRecords) {
1445 gAllocRecordHead = 0;
1446 }
1447
1448 // Fill in the basics.
1449 AllocRecord* record = &recent_allocation_records_[gAllocRecordHead];
1450 record->type = type;
1451 record->byte_count = byte_count;
1452 record->thin_lock_id = self->GetThinLockId();
1453
1454 // Fill in the stack trace.
1455 AllocRecordStackVisitor visitor(record);
1456 self->WalkStack(&visitor);
1457
1458 if (gAllocRecordCount < kNumAllocRecords) {
1459 ++gAllocRecordCount;
1460 }
1461}
1462
1463/*
1464 * Return the index of the head element.
1465 *
1466 * We point at the most-recently-written record, so if allocRecordCount is 1
1467 * we want to use the current element. Take "head+1" and subtract count
1468 * from it.
1469 *
1470 * We need to handle underflow in our circular buffer, so we add
1471 * kNumAllocRecords and then mask it back down.
1472 */
1473inline static int headIndex() {
1474 return (gAllocRecordHead+1 + kNumAllocRecords - gAllocRecordCount) & (kNumAllocRecords-1);
1475}
1476
1477void Dbg::DumpRecentAllocations() {
1478 MutexLock mu(gAllocTrackerLock);
1479 if (recent_allocation_records_ == NULL) {
1480 LOG(INFO) << "Not recording tracked allocations";
1481 return;
1482 }
1483
1484 // "i" is the head of the list. We want to start at the end of the
1485 // list and move forward to the tail.
1486 size_t i = headIndex();
1487 size_t count = gAllocRecordCount;
1488
1489 LOG(INFO) << "Tracked allocations, (head=" << gAllocRecordHead << " count=" << count << ")";
1490 while (count--) {
1491 AllocRecord* record = &recent_allocation_records_[i];
1492
1493 LOG(INFO) << StringPrintf(" T=%-2d %6d ", record->thin_lock_id, record->byte_count)
1494 << PrettyClass(record->type);
1495
1496 for (size_t stack_frame = 0; stack_frame < kMaxAllocRecordStackDepth; ++stack_frame) {
1497 const Method* m = record->stack[stack_frame].method;
1498 if (m == NULL) {
1499 break;
1500 }
1501 LOG(INFO) << " " << PrettyMethod(m) << " line " << record->stack[stack_frame].LineNumber();
1502 }
1503
1504 // pause periodically to help logcat catch up
1505 if ((count % 5) == 0) {
1506 usleep(40000);
1507 }
1508
1509 i = (i + 1) & (kNumAllocRecords-1);
1510 }
1511}
1512
1513class StringTable {
1514 public:
1515 StringTable() {
1516 }
1517
1518 void Add(const String* s) {
1519 table_.insert(s);
1520 }
1521
1522 size_t IndexOf(const String* s) {
1523 return std::distance(table_.begin(), table_.find(s));
1524 }
1525
1526 size_t Size() {
1527 return table_.size();
1528 }
1529
1530 void WriteTo(std::vector<uint8_t>& bytes) {
1531 typedef std::set<const String*>::const_iterator It; // TODO: C++0x auto
1532 for (It it = table_.begin(); it != table_.end(); ++it) {
1533 const String* s = *it;
1534 JDWP::AppendUtf16BE(bytes, s->GetCharArray()->GetData(), s->GetLength());
1535 }
1536 }
1537
1538 private:
1539 std::set<const String*> table_;
1540 DISALLOW_COPY_AND_ASSIGN(StringTable);
1541};
1542
1543/*
1544 * The data we send to DDMS contains everything we have recorded.
1545 *
1546 * Message header (all values big-endian):
1547 * (1b) message header len (to allow future expansion); includes itself
1548 * (1b) entry header len
1549 * (1b) stack frame len
1550 * (2b) number of entries
1551 * (4b) offset to string table from start of message
1552 * (2b) number of class name strings
1553 * (2b) number of method name strings
1554 * (2b) number of source file name strings
1555 * For each entry:
1556 * (4b) total allocation size
1557 * (2b) threadId
1558 * (2b) allocated object's class name index
1559 * (1b) stack depth
1560 * For each stack frame:
1561 * (2b) method's class name
1562 * (2b) method name
1563 * (2b) method source file
1564 * (2b) line number, clipped to 32767; -2 if native; -1 if no source
1565 * (xb) class name strings
1566 * (xb) method name strings
1567 * (xb) source file strings
1568 *
1569 * As with other DDM traffic, strings are sent as a 4-byte length
1570 * followed by UTF-16 data.
1571 *
1572 * We send up 16-bit unsigned indexes into string tables. In theory there
1573 * can be (kMaxAllocRecordStackDepth * kNumAllocRecords) unique strings in
1574 * each table, but in practice there should be far fewer.
1575 *
1576 * The chief reason for using a string table here is to keep the size of
1577 * the DDMS message to a minimum. This is partly to make the protocol
1578 * efficient, but also because we have to form the whole thing up all at
1579 * once in a memory buffer.
1580 *
1581 * We use separate string tables for class names, method names, and source
1582 * files to keep the indexes small. There will generally be no overlap
1583 * between the contents of these tables.
1584 */
1585jbyteArray Dbg::GetRecentAllocations() {
1586 if (false) {
1587 DumpRecentAllocations();
1588 }
1589
1590 MutexLock mu(gAllocTrackerLock);
1591
1592 /*
1593 * Part 1: generate string tables.
1594 */
1595 StringTable class_names;
1596 StringTable method_names;
1597 StringTable filenames;
1598
1599 int count = gAllocRecordCount;
1600 int idx = headIndex();
1601 while (count--) {
1602 AllocRecord* record = &recent_allocation_records_[idx];
1603
1604 class_names.Add(record->type->GetDescriptor());
1605
1606 for (size_t i = 0; i < kMaxAllocRecordStackDepth; i++) {
1607 const Method* m = record->stack[i].method;
1608 if (m != NULL) {
1609 class_names.Add(m->GetDeclaringClass()->GetDescriptor());
1610 method_names.Add(m->GetName());
1611 filenames.Add(m->GetDeclaringClass()->GetSourceFile());
1612 }
1613 }
1614
1615 idx = (idx + 1) & (kNumAllocRecords-1);
1616 }
1617
1618 LOG(INFO) << "allocation records: " << gAllocRecordCount;
1619
1620 /*
1621 * Part 2: allocate a buffer and generate the output.
1622 */
1623 std::vector<uint8_t> bytes;
1624
1625 // (1b) message header len (to allow future expansion); includes itself
1626 // (1b) entry header len
1627 // (1b) stack frame len
1628 const int kMessageHeaderLen = 15;
1629 const int kEntryHeaderLen = 9;
1630 const int kStackFrameLen = 8;
1631 JDWP::Append1BE(bytes, kMessageHeaderLen);
1632 JDWP::Append1BE(bytes, kEntryHeaderLen);
1633 JDWP::Append1BE(bytes, kStackFrameLen);
1634
1635 // (2b) number of entries
1636 // (4b) offset to string table from start of message
1637 // (2b) number of class name strings
1638 // (2b) number of method name strings
1639 // (2b) number of source file name strings
1640 JDWP::Append2BE(bytes, gAllocRecordCount);
1641 size_t string_table_offset = bytes.size();
1642 JDWP::Append4BE(bytes, 0); // We'll patch this later...
1643 JDWP::Append2BE(bytes, class_names.Size());
1644 JDWP::Append2BE(bytes, method_names.Size());
1645 JDWP::Append2BE(bytes, filenames.Size());
1646
1647 count = gAllocRecordCount;
1648 idx = headIndex();
1649 while (count--) {
1650 // For each entry:
1651 // (4b) total allocation size
1652 // (2b) thread id
1653 // (2b) allocated object's class name index
1654 // (1b) stack depth
1655 AllocRecord* record = &recent_allocation_records_[idx];
1656 size_t stack_depth = record->GetDepth();
1657 JDWP::Append4BE(bytes, record->byte_count);
1658 JDWP::Append2BE(bytes, record->thin_lock_id);
1659 JDWP::Append2BE(bytes, class_names.IndexOf(record->type->GetDescriptor()));
1660 JDWP::Append1BE(bytes, stack_depth);
1661
1662 for (size_t stack_frame = 0; stack_frame < stack_depth; ++stack_frame) {
1663 // For each stack frame:
1664 // (2b) method's class name
1665 // (2b) method name
1666 // (2b) method source file
1667 // (2b) line number, clipped to 32767; -2 if native; -1 if no source
1668 const Method* m = record->stack[stack_frame].method;
1669 JDWP::Append2BE(bytes, class_names.IndexOf(m->GetDeclaringClass()->GetDescriptor()));
1670 JDWP::Append2BE(bytes, method_names.IndexOf(m->GetName()));
1671 JDWP::Append2BE(bytes, filenames.IndexOf(m->GetDeclaringClass()->GetSourceFile()));
1672 JDWP::Append2BE(bytes, record->stack[stack_frame].LineNumber());
1673 }
1674
1675 idx = (idx + 1) & (kNumAllocRecords-1);
1676 }
1677
1678 // (xb) class name strings
1679 // (xb) method name strings
1680 // (xb) source file strings
1681 JDWP::Set4BE(&bytes[string_table_offset], bytes.size());
1682 class_names.WriteTo(bytes);
1683 method_names.WriteTo(bytes);
1684 filenames.WriteTo(bytes);
1685
1686 JNIEnv* env = Thread::Current()->GetJniEnv();
1687 jbyteArray result = env->NewByteArray(bytes.size());
1688 if (result != NULL) {
1689 env->SetByteArrayRegion(result, 0, bytes.size(), reinterpret_cast<const jbyte*>(&bytes[0]));
1690 }
1691 return result;
1692}
1693
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001694} // namespace art