blob: aaabffb68479935fd8177367e8464f26625f7686 [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) {
Elliott Hughes499c5132011-11-17 14:55:11 -0800479 Object* o = gRegistry->Get<Object*>(objectId);
480 if (o->GetClass()->IsArrayClass()) {
481 *pRefTypeTag = JDWP::TT_ARRAY;
482 } else if (o->GetClass()->IsInterface()) {
483 *pRefTypeTag = JDWP::TT_INTERFACE;
484 } else {
485 *pRefTypeTag = JDWP::TT_CLASS;
486 }
487 *pRefTypeId = gRegistry->Add(o->GetClass());
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700488}
489
490uint8_t Dbg::GetClassObjectType(JDWP::RefTypeId refTypeId) {
491 UNIMPLEMENTED(FATAL);
492 return 0;
493}
494
Elliott Hughesa2e54f62011-11-17 13:01:30 -0800495std::string Dbg::GetSignature(JDWP::RefTypeId refTypeId) {
496 Class* c = gRegistry->Get<Class*>(refTypeId);
497 CHECK(c != NULL);
498 return c->GetDescriptor()->ToModifiedUtf8();
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700499}
500
Elliott Hughes03181a82011-11-17 17:22:21 -0800501bool Dbg::GetSourceFile(JDWP::RefTypeId refTypeId, std::string& result) {
502 Class* c = gRegistry->Get<Class*>(refTypeId);
503 CHECK(c != NULL);
504
505 String* source_file = c->GetSourceFile();
506 if (source_file == NULL) {
507 return false;
508 }
509 result = source_file->ToModifiedUtf8();
510 return true;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700511}
512
513const char* Dbg::GetObjectTypeName(JDWP::ObjectId objectId) {
514 UNIMPLEMENTED(FATAL);
515 return NULL;
516}
517
518uint8_t Dbg::GetObjectTag(JDWP::ObjectId objectId) {
519 UNIMPLEMENTED(FATAL);
520 return 0;
521}
522
523int Dbg::GetTagWidth(int tag) {
524 UNIMPLEMENTED(FATAL);
525 return 0;
526}
527
528int Dbg::GetArrayLength(JDWP::ObjectId arrayId) {
529 UNIMPLEMENTED(FATAL);
530 return 0;
531}
532
533uint8_t Dbg::GetArrayElementTag(JDWP::ObjectId arrayId) {
534 UNIMPLEMENTED(FATAL);
535 return 0;
536}
537
538bool Dbg::OutputArray(JDWP::ObjectId arrayId, int firstIndex, int count, JDWP::ExpandBuf* pReply) {
539 UNIMPLEMENTED(FATAL);
540 return false;
541}
542
543bool Dbg::SetArrayElements(JDWP::ObjectId arrayId, int firstIndex, int count, const uint8_t* buf) {
544 UNIMPLEMENTED(FATAL);
545 return false;
546}
547
548JDWP::ObjectId Dbg::CreateString(const char* str) {
549 UNIMPLEMENTED(FATAL);
550 return 0;
551}
552
553JDWP::ObjectId Dbg::CreateObject(JDWP::RefTypeId classId) {
554 UNIMPLEMENTED(FATAL);
555 return 0;
556}
557
558JDWP::ObjectId Dbg::CreateArrayObject(JDWP::RefTypeId arrayTypeId, uint32_t length) {
559 UNIMPLEMENTED(FATAL);
560 return 0;
561}
562
563bool Dbg::MatchType(JDWP::RefTypeId instClassId, JDWP::RefTypeId classId) {
564 UNIMPLEMENTED(FATAL);
565 return false;
566}
567
Elliott Hughes03181a82011-11-17 17:22:21 -0800568JDWP::FieldId ToFieldId(Field* f) {
569#ifdef MOVING_GARBAGE_COLLECTOR
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700570 UNIMPLEMENTED(FATAL);
Elliott Hughes03181a82011-11-17 17:22:21 -0800571#else
572 return static_cast<JDWP::FieldId>(reinterpret_cast<uintptr_t>(f));
573#endif
574}
575
576JDWP::MethodId ToMethodId(Method* m) {
577#ifdef MOVING_GARBAGE_COLLECTOR
578 UNIMPLEMENTED(FATAL);
579#else
580 return static_cast<JDWP::MethodId>(reinterpret_cast<uintptr_t>(m));
581#endif
582}
583
584Method* FromMethodId(JDWP::MethodId mid) {
585#ifdef MOVING_GARBAGE_COLLECTOR
586 UNIMPLEMENTED(FATAL);
587#else
588 return reinterpret_cast<Method*>(static_cast<uintptr_t>(mid));
589#endif
590}
591
592std::string Dbg::GetMethodName(JDWP::RefTypeId refTypeId, JDWP::MethodId methodId) {
593 return FromMethodId(methodId)->GetName()->ToModifiedUtf8();
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700594}
595
Elliott Hughesa2e54f62011-11-17 13:01:30 -0800596/*
597 * Augment the access flags for synthetic methods and fields by setting
598 * the (as described by the spec) "0xf0000000 bit". Also, strip out any
599 * flags not specified by the Java programming language.
600 */
601static uint32_t MangleAccessFlags(uint32_t accessFlags) {
602 accessFlags &= kAccJavaFlagsMask;
603 if ((accessFlags & kAccSynthetic) != 0) {
604 accessFlags |= 0xf0000000;
605 }
606 return accessFlags;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700607}
608
Elliott Hughesa2e54f62011-11-17 13:01:30 -0800609void Dbg::OutputDeclaredFields(JDWP::RefTypeId refTypeId, bool withGeneric, JDWP::ExpandBuf* pReply) {
610 Class* c = gRegistry->Get<Class*>(refTypeId);
611 CHECK(c != NULL);
612
613 size_t instance_field_count = c->NumInstanceFields();
614 size_t static_field_count = c->NumStaticFields();
615
616 expandBufAdd4BE(pReply, instance_field_count + static_field_count);
617
618 for (size_t i = 0; i < instance_field_count + static_field_count; ++i) {
619 Field* f = (i < instance_field_count) ? c->GetInstanceField(i) : c->GetStaticField(i - instance_field_count);
620
621 expandBufAddFieldId(pReply, ToFieldId(f));
622 expandBufAddUtf8String(pReply, f->GetName()->ToModifiedUtf8().c_str());
623 expandBufAddUtf8String(pReply, f->GetTypeDescriptor());
624 if (withGeneric) {
625 static const char genericSignature[1] = "";
626 expandBufAddUtf8String(pReply, genericSignature);
627 }
628 expandBufAdd4BE(pReply, MangleAccessFlags(f->GetAccessFlags()));
629 }
630}
631
632void Dbg::OutputDeclaredMethods(JDWP::RefTypeId refTypeId, bool withGeneric, JDWP::ExpandBuf* pReply) {
633 Class* c = gRegistry->Get<Class*>(refTypeId);
634 CHECK(c != NULL);
635
636 size_t direct_method_count = c->NumDirectMethods();
637 size_t virtual_method_count = c->NumVirtualMethods();
638
639 expandBufAdd4BE(pReply, direct_method_count + virtual_method_count);
640
641 for (size_t i = 0; i < direct_method_count + virtual_method_count; ++i) {
642 Method* m = (i < direct_method_count) ? c->GetDirectMethod(i) : c->GetVirtualMethod(i - direct_method_count);
643
644 expandBufAddMethodId(pReply, ToMethodId(m));
645 expandBufAddUtf8String(pReply, m->GetName()->ToModifiedUtf8().c_str());
646 expandBufAddUtf8String(pReply, m->GetSignature()->ToModifiedUtf8().c_str());
647 if (withGeneric) {
648 static const char genericSignature[1] = "";
649 expandBufAddUtf8String(pReply, genericSignature);
650 }
651 expandBufAdd4BE(pReply, MangleAccessFlags(m->GetAccessFlags()));
652 }
653}
654
655void Dbg::OutputDeclaredInterfaces(JDWP::RefTypeId refTypeId, JDWP::ExpandBuf* pReply) {
656 Class* c = gRegistry->Get<Class*>(refTypeId);
657 CHECK(c != NULL);
658 size_t interface_count = c->NumInterfaces();
659 expandBufAdd4BE(pReply, interface_count);
660 for (size_t i = 0; i < interface_count; ++i) {
661 expandBufAddRefTypeId(pReply, gRegistry->Add(c->GetInterface(i)));
662 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700663}
664
665void Dbg::OutputLineTable(JDWP::RefTypeId refTypeId, JDWP::MethodId methodId, JDWP::ExpandBuf* pReply) {
Elliott Hughes03181a82011-11-17 17:22:21 -0800666 struct DebugCallbackContext {
667 int numItems;
668 JDWP::ExpandBuf* pReply;
669
670 static bool Callback(void* context, uint32_t address, uint32_t lineNum) {
671 DebugCallbackContext* pContext = reinterpret_cast<DebugCallbackContext*>(context);
672 expandBufAdd8BE(pContext->pReply, address);
673 expandBufAdd4BE(pContext->pReply, lineNum);
674 pContext->numItems++;
675 return true;
676 }
677 };
678
679 Method* m = FromMethodId(methodId);
680 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
681 const DexFile& dex_file = class_linker->FindDexFile(m->GetDeclaringClass()->GetDexCache());
682 const DexFile::CodeItem* code_item = dex_file.GetCodeItem(m->GetCodeItemOffset());
683
684 uint64_t start, end;
685 if (m->IsNative()) {
686 start = -1;
687 end = -1;
688 } else {
689 start = 0;
690 end = code_item->insns_size_in_code_units_; // TODO: what are the units supposed to be? *2?
691 }
692
693 expandBufAdd8BE(pReply, start);
694 expandBufAdd8BE(pReply, end);
695
696 // Add numLines later
697 size_t numLinesOffset = expandBufGetLength(pReply);
698 expandBufAdd4BE(pReply, 0);
699
700 DebugCallbackContext context;
701 context.numItems = 0;
702 context.pReply = pReply;
703
704 dex_file.DecodeDebugInfo(code_item, m, DebugCallbackContext::Callback, NULL, &context);
705
706 JDWP::Set4BE(expandBufGetBuffer(pReply) + numLinesOffset, context.numItems);
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700707}
708
709void Dbg::OutputVariableTable(JDWP::RefTypeId refTypeId, JDWP::MethodId id, bool withGeneric, JDWP::ExpandBuf* pReply) {
710 UNIMPLEMENTED(FATAL);
711}
712
713uint8_t Dbg::GetFieldBasicTag(JDWP::ObjectId objId, JDWP::FieldId fieldId) {
714 UNIMPLEMENTED(FATAL);
715 return 0;
716}
717
718uint8_t Dbg::GetStaticFieldBasicTag(JDWP::RefTypeId refTypeId, JDWP::FieldId fieldId) {
719 UNIMPLEMENTED(FATAL);
720 return 0;
721}
722
723void Dbg::GetFieldValue(JDWP::ObjectId objectId, JDWP::FieldId fieldId, JDWP::ExpandBuf* pReply) {
724 UNIMPLEMENTED(FATAL);
725}
726
727void Dbg::SetFieldValue(JDWP::ObjectId objectId, JDWP::FieldId fieldId, uint64_t value, int width) {
728 UNIMPLEMENTED(FATAL);
729}
730
731void Dbg::GetStaticFieldValue(JDWP::RefTypeId refTypeId, JDWP::FieldId fieldId, JDWP::ExpandBuf* pReply) {
732 UNIMPLEMENTED(FATAL);
733}
734
735void Dbg::SetStaticFieldValue(JDWP::RefTypeId refTypeId, JDWP::FieldId fieldId, uint64_t rawValue, int width) {
736 UNIMPLEMENTED(FATAL);
737}
738
739char* Dbg::StringToUtf8(JDWP::ObjectId strId) {
740 UNIMPLEMENTED(FATAL);
741 return NULL;
742}
743
Elliott Hughesa2e54f62011-11-17 13:01:30 -0800744Thread* DecodeThread(JDWP::ObjectId threadId) {
745 Object* thread_peer = gRegistry->Get<Object*>(threadId);
746 CHECK(thread_peer != NULL);
747 return Thread::FromManagedThread(thread_peer);
748}
749
750bool Dbg::GetThreadName(JDWP::ObjectId threadId, std::string& name) {
751 ScopedThreadListLock thread_list_lock;
752 Thread* thread = DecodeThread(threadId);
753 if (thread == NULL) {
754 return false;
755 }
756 StringAppendF(&name, "<%d> %s", thread->GetThinLockId(), thread->GetName()->ToModifiedUtf8().c_str());
757 return true;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700758}
759
760JDWP::ObjectId Dbg::GetThreadGroup(JDWP::ObjectId threadId) {
Elliott Hughes499c5132011-11-17 14:55:11 -0800761 Object* thread = gRegistry->Get<Object*>(threadId);
762 CHECK(thread != NULL);
763
764 Class* c = Runtime::Current()->GetClassLinker()->FindSystemClass("Ljava/lang/Thread;");
765 CHECK(c != NULL);
766 Field* f = c->FindInstanceField("group", "Ljava/lang/ThreadGroup;");
767 CHECK(f != NULL);
768 Object* group = f->GetObject(thread);
769 CHECK(group != NULL);
770 return gRegistry->Add(group);
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700771}
772
Elliott Hughes499c5132011-11-17 14:55:11 -0800773std::string Dbg::GetThreadGroupName(JDWP::ObjectId threadGroupId) {
774 Object* thread_group = gRegistry->Get<Object*>(threadGroupId);
775 CHECK(thread_group != NULL);
776
777 Class* c = Runtime::Current()->GetClassLinker()->FindSystemClass("Ljava/lang/ThreadGroup;");
778 CHECK(c != NULL);
779 Field* f = c->FindInstanceField("name", "Ljava/lang/String;");
780 CHECK(f != NULL);
781 String* s = reinterpret_cast<String*>(f->GetObject(thread_group));
782 return s->ToModifiedUtf8();
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700783}
784
785JDWP::ObjectId Dbg::GetThreadGroupParent(JDWP::ObjectId threadGroupId) {
786 UNIMPLEMENTED(FATAL);
787 return 0;
788}
789
Elliott Hughes499c5132011-11-17 14:55:11 -0800790static Object* GetStaticThreadGroup(const char* field_name) {
791 Class* c = Runtime::Current()->GetClassLinker()->FindSystemClass("Ljava/lang/ThreadGroup;");
792 CHECK(c != NULL);
793 Field* f = c->FindStaticField(field_name, "Ljava/lang/ThreadGroup;");
794 CHECK(f != NULL);
795 Object* group = f->GetObject(NULL);
796 CHECK(group != NULL);
797 return group;
798}
799
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700800JDWP::ObjectId Dbg::GetSystemThreadGroupId() {
Elliott Hughes499c5132011-11-17 14:55:11 -0800801 return gRegistry->Add(GetStaticThreadGroup("mSystem"));
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700802}
803
804JDWP::ObjectId Dbg::GetMainThreadGroupId() {
Elliott Hughes499c5132011-11-17 14:55:11 -0800805 return gRegistry->Add(GetStaticThreadGroup("mMain"));
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700806}
807
Elliott Hughes499c5132011-11-17 14:55:11 -0800808bool Dbg::GetThreadStatus(JDWP::ObjectId threadId, uint32_t* pThreadStatus, uint32_t* pSuspendStatus) {
809 ScopedThreadListLock thread_list_lock;
810
811 Thread* thread = DecodeThread(threadId);
812 if (thread == NULL) {
813 return false;
814 }
815
816 switch (thread->GetState()) {
817 case Thread::kTerminated: *pThreadStatus = JDWP::TS_ZOMBIE; break;
818 case Thread::kRunnable: *pThreadStatus = JDWP::TS_RUNNING; break;
819 case Thread::kTimedWaiting: *pThreadStatus = JDWP::TS_SLEEPING; break;
820 case Thread::kBlocked: *pThreadStatus = JDWP::TS_MONITOR; break;
821 case Thread::kWaiting: *pThreadStatus = JDWP::TS_WAIT; break;
822 case Thread::kInitializing: *pThreadStatus = JDWP::TS_ZOMBIE; break;
823 case Thread::kStarting: *pThreadStatus = JDWP::TS_ZOMBIE; break;
824 case Thread::kNative: *pThreadStatus = JDWP::TS_RUNNING; break;
825 case Thread::kVmWait: *pThreadStatus = JDWP::TS_WAIT; break;
826 case Thread::kSuspended: *pThreadStatus = JDWP::TS_RUNNING; break;
827 default:
828 LOG(FATAL) << "unknown thread state " << thread->GetState();
829 }
830
831 *pSuspendStatus = (thread->IsSuspended() ? JDWP::SUSPEND_STATUS_SUSPENDED : 0);
832
833 return true;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700834}
835
836uint32_t Dbg::GetThreadSuspendCount(JDWP::ObjectId threadId) {
837 UNIMPLEMENTED(FATAL);
838 return 0;
839}
840
841bool Dbg::ThreadExists(JDWP::ObjectId threadId) {
Elliott Hughes761928d2011-11-16 18:33:03 -0800842 return DecodeThread(threadId) != NULL;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700843}
844
845bool Dbg::IsSuspended(JDWP::ObjectId threadId) {
Elliott Hughes761928d2011-11-16 18:33:03 -0800846 return DecodeThread(threadId)->IsSuspended();
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700847}
848
849//void Dbg::WaitForSuspend(JDWP::ObjectId threadId);
850
Elliott Hughesa2155262011-11-16 16:26:58 -0800851void Dbg::GetThreadGroupThreadsImpl(Object* thread_group, JDWP::ObjectId** ppThreadIds, uint32_t* pThreadCount) {
852 struct ThreadListVisitor {
853 static void Visit(Thread* t, void* arg) {
854 reinterpret_cast<ThreadListVisitor*>(arg)->Visit(t);
855 }
856
857 void Visit(Thread* t) {
858 if (t == Dbg::GetDebugThread()) {
859 // Skip the JDWP thread. Some debuggers get bent out of shape when they can't suspend and
860 // query all threads, so it's easier if we just don't tell them about this thread.
861 return;
862 }
863 if (thread_group == NULL || t->GetThreadGroup() == thread_group) {
864 threads.push_back(gRegistry->Add(t->GetPeer()));
865 }
866 }
867
868 Object* thread_group;
869 std::vector<JDWP::ObjectId> threads;
870 };
871
872 ThreadListVisitor tlv;
873 tlv.thread_group = thread_group;
874
875 {
876 ScopedThreadListLock thread_list_lock;
877 Runtime::Current()->GetThreadList()->ForEach(ThreadListVisitor::Visit, &tlv);
878 }
879
880 *pThreadCount = tlv.threads.size();
881 if (*pThreadCount == 0) {
882 *ppThreadIds = NULL;
883 } else {
884 *ppThreadIds = new JDWP::ObjectId[*pThreadCount];
885 for (size_t i = 0; i < *pThreadCount; ++i) {
886 (*ppThreadIds)[i] = tlv.threads[i];
887 }
888 }
889}
890
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700891void Dbg::GetThreadGroupThreads(JDWP::ObjectId threadGroupId, JDWP::ObjectId** ppThreadIds, uint32_t* pThreadCount) {
Elliott Hughesa2155262011-11-16 16:26:58 -0800892 GetThreadGroupThreadsImpl(gRegistry->Get<Object*>(threadGroupId), ppThreadIds, pThreadCount);
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700893}
894
895void Dbg::GetAllThreads(JDWP::ObjectId** ppThreadIds, uint32_t* pThreadCount) {
Elliott Hughesa2155262011-11-16 16:26:58 -0800896 GetThreadGroupThreadsImpl(NULL, ppThreadIds, pThreadCount);
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700897}
898
899int Dbg::GetThreadFrameCount(JDWP::ObjectId threadId) {
Elliott Hughes03181a82011-11-17 17:22:21 -0800900 ScopedThreadListLock thread_list_lock;
Elliott Hughesa2e54f62011-11-17 13:01:30 -0800901 struct CountStackDepthVisitor : public Thread::StackVisitor {
902 CountStackDepthVisitor() : depth(0) {}
Elliott Hughes03181a82011-11-17 17:22:21 -0800903 virtual void VisitFrame(const Frame&, uintptr_t) {
Elliott Hughesa2e54f62011-11-17 13:01:30 -0800904 ++depth;
905 }
906 size_t depth;
907 };
908 CountStackDepthVisitor visitor;
909 DecodeThread(threadId)->WalkStack(&visitor);
910 return visitor.depth;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700911}
912
Elliott Hughes03181a82011-11-17 17:22:21 -0800913bool Dbg::GetThreadFrame(JDWP::ObjectId threadId, int desired_frame_number, JDWP::FrameId* pFrameId, JDWP::JdwpLocation* pLoc) {
914 ScopedThreadListLock thread_list_lock;
915 struct GetFrameVisitor : public Thread::StackVisitor {
916 GetFrameVisitor(int desired_frame_number, JDWP::FrameId* pFrameId, JDWP::JdwpLocation* pLoc)
917 : found(false) ,depth(0), desired_frame_number(desired_frame_number), pFrameId(pFrameId), pLoc(pLoc) {
918 }
919 virtual void VisitFrame(const Frame& f, uintptr_t pc) {
920 if (!f.HasMethod()) {
921 return; // These don't count?
922 }
923
924 if (depth == desired_frame_number) {
925 *pFrameId = reinterpret_cast<JDWP::FrameId>(f.GetSP());
926
927 Method* m = f.GetMethod();
928 Class* c = m->GetDeclaringClass();
929
930 pLoc->typeTag = c->IsInterface() ? JDWP::TT_INTERFACE : JDWP::TT_CLASS;
931 pLoc->classId = gRegistry->Add(c);
932 pLoc->methodId = ToMethodId(m);
933 pLoc->idx = m->IsNative() ? -1 : m->ToDexPC(pc);
934
935 found = true;
936 }
937 ++depth;
938 }
939 bool found;
940 int depth;
941 int desired_frame_number;
942 JDWP::FrameId* pFrameId;
943 JDWP::JdwpLocation* pLoc;
944 };
945 GetFrameVisitor visitor(desired_frame_number, pFrameId, pLoc);
946 visitor.desired_frame_number = desired_frame_number;
947 DecodeThread(threadId)->WalkStack(&visitor);
948 return visitor.found;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700949}
950
951JDWP::ObjectId Dbg::GetThreadSelfId() {
Elliott Hughes475fc232011-10-25 15:00:35 -0700952 return gRegistry->Add(Thread::Current()->GetPeer());
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700953}
954
Elliott Hughes475fc232011-10-25 15:00:35 -0700955void Dbg::SuspendVM() {
Elliott Hughesa2155262011-11-16 16:26:58 -0800956 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 -0700957 Runtime::Current()->GetThreadList()->SuspendAll(true);
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700958}
959
960void Dbg::ResumeVM() {
Elliott Hughes475fc232011-10-25 15:00:35 -0700961 Runtime::Current()->GetThreadList()->ResumeAll(true);
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700962}
963
964void Dbg::SuspendThread(JDWP::ObjectId threadId) {
965 UNIMPLEMENTED(FATAL);
966}
967
968void Dbg::ResumeThread(JDWP::ObjectId threadId) {
969 UNIMPLEMENTED(FATAL);
970}
971
972void Dbg::SuspendSelf() {
Elliott Hughes475fc232011-10-25 15:00:35 -0700973 Runtime::Current()->GetThreadList()->SuspendSelfForDebugger();
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700974}
975
976bool Dbg::GetThisObject(JDWP::ObjectId threadId, JDWP::FrameId frameId, JDWP::ObjectId* pThisId) {
977 UNIMPLEMENTED(FATAL);
978 return false;
979}
980
981void Dbg::GetLocalValue(JDWP::ObjectId threadId, JDWP::FrameId frameId, int slot, uint8_t tag, uint8_t* buf, int expectedLen) {
982 UNIMPLEMENTED(FATAL);
983}
984
985void Dbg::SetLocalValue(JDWP::ObjectId threadId, JDWP::FrameId frameId, int slot, uint8_t tag, uint64_t value, int width) {
986 UNIMPLEMENTED(FATAL);
987}
988
989void Dbg::PostLocationEvent(const Method* method, int pcOffset, Object* thisPtr, int eventFlags) {
990 UNIMPLEMENTED(FATAL);
991}
992
993void Dbg::PostException(void* throwFp, int throwRelPc, void* catchFp, int catchRelPc, Object* exception) {
994 UNIMPLEMENTED(FATAL);
995}
996
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700997void Dbg::PostClassPrepare(Class* c) {
998 UNIMPLEMENTED(FATAL);
999}
1000
1001bool Dbg::WatchLocation(const JDWP::JdwpLocation* pLoc) {
1002 UNIMPLEMENTED(FATAL);
1003 return false;
1004}
1005
1006void Dbg::UnwatchLocation(const JDWP::JdwpLocation* pLoc) {
1007 UNIMPLEMENTED(FATAL);
1008}
1009
1010bool Dbg::ConfigureStep(JDWP::ObjectId threadId, JDWP::JdwpStepSize size, JDWP::JdwpStepDepth depth) {
1011 UNIMPLEMENTED(FATAL);
1012 return false;
1013}
1014
1015void Dbg::UnconfigureStep(JDWP::ObjectId threadId) {
1016 UNIMPLEMENTED(FATAL);
1017}
1018
1019JDWP::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) {
1020 UNIMPLEMENTED(FATAL);
1021 return JDWP::ERR_NONE;
1022}
1023
1024void Dbg::ExecuteMethod(DebugInvokeReq* pReq) {
1025 UNIMPLEMENTED(FATAL);
1026}
1027
1028void Dbg::RegisterObjectId(JDWP::ObjectId id) {
1029 UNIMPLEMENTED(FATAL);
1030}
1031
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07001032/*
1033 * "buf" contains a full JDWP packet, possibly with multiple chunks. We
1034 * need to process each, accumulate the replies, and ship the whole thing
1035 * back.
1036 *
1037 * Returns "true" if we have a reply. The reply buffer is newly allocated,
1038 * and includes the chunk type/length, followed by the data.
1039 *
1040 * TODO: we currently assume that the request and reply include a single
1041 * chunk. If this becomes inconvenient we will need to adapt.
1042 */
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001043bool Dbg::DdmHandlePacket(const uint8_t* buf, int dataLen, uint8_t** pReplyBuf, int* pReplyLen) {
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07001044 CHECK_GE(dataLen, 0);
1045
1046 Thread* self = Thread::Current();
1047 JNIEnv* env = self->GetJniEnv();
1048
1049 static jclass Chunk_class = env->FindClass("org/apache/harmony/dalvik/ddmc/Chunk");
1050 static jclass DdmServer_class = env->FindClass("org/apache/harmony/dalvik/ddmc/DdmServer");
1051 static jmethodID dispatch_mid = env->GetStaticMethodID(DdmServer_class, "dispatch",
1052 "(I[BII)Lorg/apache/harmony/dalvik/ddmc/Chunk;");
1053 static jfieldID data_fid = env->GetFieldID(Chunk_class, "data", "[B");
1054 static jfieldID length_fid = env->GetFieldID(Chunk_class, "length", "I");
1055 static jfieldID offset_fid = env->GetFieldID(Chunk_class, "offset", "I");
1056 static jfieldID type_fid = env->GetFieldID(Chunk_class, "type", "I");
1057
1058 // Create a byte[] corresponding to 'buf'.
Elliott Hughes6a5bd492011-10-28 14:33:57 -07001059 ScopedLocalRef<jbyteArray> dataArray(env, env->NewByteArray(dataLen));
1060 if (dataArray.get() == NULL) {
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07001061 LOG(WARNING) << "byte[] allocation failed: " << dataLen;
1062 env->ExceptionClear();
1063 return false;
1064 }
Elliott Hughes6a5bd492011-10-28 14:33:57 -07001065 env->SetByteArrayRegion(dataArray.get(), 0, dataLen, reinterpret_cast<const jbyte*>(buf));
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07001066
1067 const int kChunkHdrLen = 8;
1068
1069 // Run through and find all chunks. [Currently just find the first.]
Elliott Hughes6a5bd492011-10-28 14:33:57 -07001070 ScopedByteArrayRO contents(env, dataArray.get());
Elliott Hughesf7c3b662011-10-27 12:04:56 -07001071 jint type = JDWP::Get4BE(reinterpret_cast<const uint8_t*>(&contents[0]));
1072 jint length = JDWP::Get4BE(reinterpret_cast<const uint8_t*>(&contents[4]));
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07001073 jint offset = kChunkHdrLen;
1074 if (offset + length > dataLen) {
1075 LOG(WARNING) << StringPrintf("bad chunk found (len=%u pktLen=%d)", length, dataLen);
1076 return false;
1077 }
1078
1079 // Call "private static Chunk dispatch(int type, byte[] data, int offset, int length)".
Elliott Hughes6a5bd492011-10-28 14:33:57 -07001080 ScopedLocalRef<jobject> chunk(env, env->CallStaticObjectMethod(DdmServer_class, dispatch_mid, type, dataArray.get(), offset, length));
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07001081 if (env->ExceptionCheck()) {
1082 LOG(INFO) << StringPrintf("Exception thrown by dispatcher for 0x%08x", type);
1083 env->ExceptionDescribe();
1084 env->ExceptionClear();
1085 return false;
1086 }
1087
Elliott Hughes6a5bd492011-10-28 14:33:57 -07001088 if (chunk.get() == NULL) {
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07001089 return false;
1090 }
1091
1092 /*
1093 * Pull the pieces out of the chunk. We copy the results into a
1094 * newly-allocated buffer that the caller can free. We don't want to
1095 * continue using the Chunk object because nothing has a reference to it.
1096 *
1097 * We could avoid this by returning type/data/offset/length and having
1098 * the caller be aware of the object lifetime issues, but that
1099 * integrates the JDWP code more tightly into the VM, and doesn't work
1100 * if we have responses for multiple chunks.
1101 *
1102 * So we're pretty much stuck with copying data around multiple times.
1103 */
Elliott Hughes6a5bd492011-10-28 14:33:57 -07001104 ScopedLocalRef<jbyteArray> replyData(env, reinterpret_cast<jbyteArray>(env->GetObjectField(chunk.get(), data_fid)));
1105 length = env->GetIntField(chunk.get(), length_fid);
1106 offset = env->GetIntField(chunk.get(), offset_fid);
1107 type = env->GetIntField(chunk.get(), type_fid);
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07001108
Elliott Hughes6a5bd492011-10-28 14:33:57 -07001109 LOG(VERBOSE) << StringPrintf("DDM reply: type=0x%08x data=%p offset=%d length=%d", type, replyData.get(), offset, length);
1110 if (length == 0 || replyData.get() == NULL) {
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07001111 return false;
1112 }
1113
Elliott Hughes6a5bd492011-10-28 14:33:57 -07001114 jsize replyLength = env->GetArrayLength(replyData.get());
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07001115 if (offset + length > replyLength) {
1116 LOG(WARNING) << StringPrintf("chunk off=%d len=%d exceeds reply array len %d", offset, length, replyLength);
1117 return false;
1118 }
1119
1120 uint8_t* reply = new uint8_t[length + kChunkHdrLen];
1121 if (reply == NULL) {
1122 LOG(WARNING) << "malloc failed: " << (length + kChunkHdrLen);
1123 return false;
1124 }
Elliott Hughesf7c3b662011-10-27 12:04:56 -07001125 JDWP::Set4BE(reply + 0, type);
1126 JDWP::Set4BE(reply + 4, length);
Elliott Hughes6a5bd492011-10-28 14:33:57 -07001127 env->GetByteArrayRegion(replyData.get(), offset, length, reinterpret_cast<jbyte*>(reply + kChunkHdrLen));
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07001128
1129 *pReplyBuf = reply;
1130 *pReplyLen = length + kChunkHdrLen;
1131
1132 LOG(VERBOSE) << StringPrintf("dvmHandleDdm returning type=%.4s buf=%p len=%d", (char*) reply, reply, length);
1133 return true;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001134}
1135
Elliott Hughesa2155262011-11-16 16:26:58 -08001136void Dbg::DdmBroadcast(bool connect) {
Elliott Hughes47fce012011-10-25 18:37:19 -07001137 LOG(VERBOSE) << "Broadcasting DDM " << (connect ? "connect" : "disconnect") << "...";
1138
1139 Thread* self = Thread::Current();
1140 if (self->GetState() != Thread::kRunnable) {
1141 LOG(ERROR) << "DDM broadcast in thread state " << self->GetState();
1142 /* try anyway? */
1143 }
1144
1145 JNIEnv* env = self->GetJniEnv();
1146 static jclass DdmServer_class = env->FindClass("org/apache/harmony/dalvik/ddmc/DdmServer");
1147 static jmethodID broadcast_mid = env->GetStaticMethodID(DdmServer_class, "broadcast", "(I)V");
1148 jint event = connect ? 1 /*DdmServer.CONNECTED*/ : 2 /*DdmServer.DISCONNECTED*/;
1149 env->CallStaticVoidMethod(DdmServer_class, broadcast_mid, event);
1150 if (env->ExceptionCheck()) {
1151 LOG(ERROR) << "DdmServer.broadcast " << event << " failed";
1152 env->ExceptionDescribe();
1153 env->ExceptionClear();
1154 }
1155}
1156
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001157void Dbg::DdmConnected() {
Elliott Hughesa2155262011-11-16 16:26:58 -08001158 Dbg::DdmBroadcast(true);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001159}
1160
1161void Dbg::DdmDisconnected() {
Elliott Hughesa2155262011-11-16 16:26:58 -08001162 Dbg::DdmBroadcast(false);
Elliott Hughes47fce012011-10-25 18:37:19 -07001163 gDdmThreadNotification = false;
1164}
1165
1166/*
Elliott Hughes82188472011-11-07 18:11:48 -08001167 * Send a notification when a thread starts, stops, or changes its name.
Elliott Hughes47fce012011-10-25 18:37:19 -07001168 *
1169 * Because we broadcast the full set of threads when the notifications are
1170 * first enabled, it's possible for "thread" to be actively executing.
1171 */
Elliott Hughes82188472011-11-07 18:11:48 -08001172void Dbg::DdmSendThreadNotification(Thread* t, uint32_t type) {
Elliott Hughes47fce012011-10-25 18:37:19 -07001173 if (!gDdmThreadNotification) {
1174 return;
1175 }
1176
Elliott Hughes82188472011-11-07 18:11:48 -08001177 if (type == CHUNK_TYPE("THDE")) {
Elliott Hughes47fce012011-10-25 18:37:19 -07001178 uint8_t buf[4];
Elliott Hughesf7c3b662011-10-27 12:04:56 -07001179 JDWP::Set4BE(&buf[0], t->GetThinLockId());
Elliott Hughes47fce012011-10-25 18:37:19 -07001180 Dbg::DdmSendChunk(CHUNK_TYPE("THDE"), 4, buf);
Elliott Hughes82188472011-11-07 18:11:48 -08001181 } else {
1182 CHECK(type == CHUNK_TYPE("THCR") || type == CHUNK_TYPE("THNM")) << type;
1183 SirtRef<String> name(t->GetName());
1184 size_t char_count = (name.get() != NULL) ? name->GetLength() : 0;
1185 const jchar* chars = name->GetCharArray()->GetData();
1186
Elliott Hughes21f32d72011-11-09 17:44:13 -08001187 std::vector<uint8_t> bytes;
Elliott Hughes545a0642011-11-08 19:10:03 -08001188 JDWP::Append4BE(bytes, t->GetThinLockId());
1189 JDWP::AppendUtf16BE(bytes, chars, char_count);
Elliott Hughes21f32d72011-11-09 17:44:13 -08001190 CHECK_EQ(bytes.size(), char_count*2 + sizeof(uint32_t)*2);
1191 Dbg::DdmSendChunk(type, bytes);
Elliott Hughes47fce012011-10-25 18:37:19 -07001192 }
1193}
1194
Elliott Hughesa2155262011-11-16 16:26:58 -08001195static void DdmSendThreadStartCallback(Thread* t, void*) {
Elliott Hughes82188472011-11-07 18:11:48 -08001196 Dbg::DdmSendThreadNotification(t, CHUNK_TYPE("THCR"));
Elliott Hughes47fce012011-10-25 18:37:19 -07001197}
1198
1199void Dbg::DdmSetThreadNotification(bool enable) {
1200 // We lock the thread list to avoid sending duplicate events or missing
1201 // a thread change. We should be okay holding this lock while sending
1202 // the messages out. (We have to hold it while accessing a live thread.)
Elliott Hughesbbd9d832011-11-07 14:40:00 -08001203 ScopedThreadListLock thread_list_lock;
Elliott Hughes47fce012011-10-25 18:37:19 -07001204
1205 gDdmThreadNotification = enable;
1206 if (enable) {
Elliott Hughesbfe487b2011-10-26 15:48:55 -07001207 Runtime::Current()->GetThreadList()->ForEach(DdmSendThreadStartCallback, NULL);
Elliott Hughes47fce012011-10-25 18:37:19 -07001208 }
1209}
1210
Elliott Hughesa2155262011-11-16 16:26:58 -08001211void Dbg::PostThreadStartOrStop(Thread* t, uint32_t type) {
Elliott Hughes47fce012011-10-25 18:37:19 -07001212 if (gDebuggerActive) {
1213 JDWP::ObjectId id = gRegistry->Add(t->GetPeer());
Elliott Hughes82188472011-11-07 18:11:48 -08001214 gJdwpState->PostThreadChange(id, type == CHUNK_TYPE("THCR"));
Elliott Hughes47fce012011-10-25 18:37:19 -07001215 }
Elliott Hughes82188472011-11-07 18:11:48 -08001216 Dbg::DdmSendThreadNotification(t, type);
Elliott Hughes47fce012011-10-25 18:37:19 -07001217}
1218
1219void Dbg::PostThreadStart(Thread* t) {
Elliott Hughesa2155262011-11-16 16:26:58 -08001220 Dbg::PostThreadStartOrStop(t, CHUNK_TYPE("THCR"));
Elliott Hughes47fce012011-10-25 18:37:19 -07001221}
1222
1223void Dbg::PostThreadDeath(Thread* t) {
Elliott Hughesa2155262011-11-16 16:26:58 -08001224 Dbg::PostThreadStartOrStop(t, CHUNK_TYPE("THDE"));
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001225}
1226
Elliott Hughes82188472011-11-07 18:11:48 -08001227void Dbg::DdmSendChunk(uint32_t type, size_t byte_count, const uint8_t* buf) {
Elliott Hughes3bb81562011-10-21 18:52:59 -07001228 CHECK(buf != NULL);
1229 iovec vec[1];
1230 vec[0].iov_base = reinterpret_cast<void*>(const_cast<uint8_t*>(buf));
1231 vec[0].iov_len = byte_count;
1232 Dbg::DdmSendChunkV(type, vec, 1);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001233}
1234
Elliott Hughes21f32d72011-11-09 17:44:13 -08001235void Dbg::DdmSendChunk(uint32_t type, const std::vector<uint8_t>& bytes) {
1236 DdmSendChunk(type, bytes.size(), &bytes[0]);
1237}
1238
Elliott Hughes82188472011-11-07 18:11:48 -08001239void Dbg::DdmSendChunkV(uint32_t type, const struct iovec* iov, int iovcnt) {
Elliott Hughes3bb81562011-10-21 18:52:59 -07001240 if (gJdwpState == NULL) {
1241 LOG(VERBOSE) << "Debugger thread not active, ignoring DDM send: " << type;
1242 } else {
Elliott Hughes376a7a02011-10-24 18:35:55 -07001243 gJdwpState->DdmSendChunkV(type, iov, iovcnt);
Elliott Hughes3bb81562011-10-21 18:52:59 -07001244 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001245}
1246
Elliott Hughes767a1472011-10-26 18:49:02 -07001247int Dbg::DdmHandleHpifChunk(HpifWhen when) {
1248 if (when == HPIF_WHEN_NOW) {
Elliott Hughes7162ad92011-10-27 14:08:42 -07001249 DdmSendHeapInfo(when);
Elliott Hughes767a1472011-10-26 18:49:02 -07001250 return true;
1251 }
1252
1253 if (when != HPIF_WHEN_NEVER && when != HPIF_WHEN_NEXT_GC && when != HPIF_WHEN_EVERY_GC) {
1254 LOG(ERROR) << "invalid HpifWhen value: " << static_cast<int>(when);
1255 return false;
1256 }
1257
1258 gDdmHpifWhen = when;
1259 return true;
1260}
1261
1262bool Dbg::DdmHandleHpsgNhsgChunk(Dbg::HpsgWhen when, Dbg::HpsgWhat what, bool native) {
1263 if (when != HPSG_WHEN_NEVER && when != HPSG_WHEN_EVERY_GC) {
1264 LOG(ERROR) << "invalid HpsgWhen value: " << static_cast<int>(when);
1265 return false;
1266 }
1267
1268 if (what != HPSG_WHAT_MERGED_OBJECTS && what != HPSG_WHAT_DISTINCT_OBJECTS) {
1269 LOG(ERROR) << "invalid HpsgWhat value: " << static_cast<int>(what);
1270 return false;
1271 }
1272
1273 if (native) {
1274 gDdmNhsgWhen = when;
1275 gDdmNhsgWhat = what;
1276 } else {
1277 gDdmHpsgWhen = when;
1278 gDdmHpsgWhat = what;
1279 }
1280 return true;
1281}
1282
Elliott Hughes7162ad92011-10-27 14:08:42 -07001283void Dbg::DdmSendHeapInfo(HpifWhen reason) {
1284 // If there's a one-shot 'when', reset it.
1285 if (reason == gDdmHpifWhen) {
1286 if (gDdmHpifWhen == HPIF_WHEN_NEXT_GC) {
1287 gDdmHpifWhen = HPIF_WHEN_NEVER;
1288 }
1289 }
1290
1291 /*
1292 * Chunk HPIF (client --> server)
1293 *
1294 * Heap Info. General information about the heap,
1295 * suitable for a summary display.
1296 *
1297 * [u4]: number of heaps
1298 *
1299 * For each heap:
1300 * [u4]: heap ID
1301 * [u8]: timestamp in ms since Unix epoch
1302 * [u1]: capture reason (same as 'when' value from server)
1303 * [u4]: max heap size in bytes (-Xmx)
1304 * [u4]: current heap size in bytes
1305 * [u4]: current number of bytes allocated
1306 * [u4]: current number of objects allocated
1307 */
1308 uint8_t heap_count = 1;
Elliott Hughes21f32d72011-11-09 17:44:13 -08001309 std::vector<uint8_t> bytes;
Elliott Hughes545a0642011-11-08 19:10:03 -08001310 JDWP::Append4BE(bytes, heap_count);
1311 JDWP::Append4BE(bytes, 1); // Heap id (bogus; we only have one heap).
1312 JDWP::Append8BE(bytes, MilliTime());
1313 JDWP::Append1BE(bytes, reason);
1314 JDWP::Append4BE(bytes, Heap::GetMaxMemory()); // Max allowed heap size in bytes.
1315 JDWP::Append4BE(bytes, Heap::GetTotalMemory()); // Current heap size in bytes.
1316 JDWP::Append4BE(bytes, Heap::GetBytesAllocated());
1317 JDWP::Append4BE(bytes, Heap::GetObjectsAllocated());
Elliott Hughes21f32d72011-11-09 17:44:13 -08001318 CHECK_EQ(bytes.size(), 4U + (heap_count * (4 + 8 + 1 + 4 + 4 + 4 + 4)));
1319 Dbg::DdmSendChunk(CHUNK_TYPE("HPIF"), bytes);
Elliott Hughes767a1472011-10-26 18:49:02 -07001320}
1321
Elliott Hughes6a5bd492011-10-28 14:33:57 -07001322enum HpsgSolidity {
1323 SOLIDITY_FREE = 0,
1324 SOLIDITY_HARD = 1,
1325 SOLIDITY_SOFT = 2,
1326 SOLIDITY_WEAK = 3,
1327 SOLIDITY_PHANTOM = 4,
1328 SOLIDITY_FINALIZABLE = 5,
1329 SOLIDITY_SWEEP = 6,
1330};
1331
1332enum HpsgKind {
1333 KIND_OBJECT = 0,
1334 KIND_CLASS_OBJECT = 1,
1335 KIND_ARRAY_1 = 2,
1336 KIND_ARRAY_2 = 3,
1337 KIND_ARRAY_4 = 4,
1338 KIND_ARRAY_8 = 5,
1339 KIND_UNKNOWN = 6,
1340 KIND_NATIVE = 7,
1341};
1342
1343#define HPSG_PARTIAL (1<<7)
1344#define HPSG_STATE(solidity, kind) ((uint8_t)((((kind) & 0x7) << 3) | ((solidity) & 0x7)))
1345
1346struct HeapChunkContext {
1347 std::vector<uint8_t> buf;
1348 uint8_t* p;
1349 uint8_t* pieceLenField;
1350 size_t totalAllocationUnits;
Elliott Hughes82188472011-11-07 18:11:48 -08001351 uint32_t type;
Elliott Hughes6a5bd492011-10-28 14:33:57 -07001352 bool merge;
1353 bool needHeader;
1354
1355 // Maximum chunk size. Obtain this from the formula:
1356 // (((maximum_heap_size / ALLOCATION_UNIT_SIZE) + 255) / 256) * 2
1357 HeapChunkContext(bool merge, bool native)
1358 : buf(16384 - 16),
1359 type(0),
1360 merge(merge) {
1361 Reset();
1362 if (native) {
1363 type = CHUNK_TYPE("NHSG");
1364 } else {
1365 type = merge ? CHUNK_TYPE("HPSG") : CHUNK_TYPE("HPSO");
1366 }
1367 }
1368
1369 ~HeapChunkContext() {
1370 if (p > &buf[0]) {
1371 Flush();
1372 }
1373 }
1374
1375 void EnsureHeader(const void* chunk_ptr) {
1376 if (!needHeader) {
1377 return;
1378 }
1379
1380 // Start a new HPSx chunk.
1381 JDWP::Write4BE(&p, 1); // Heap id (bogus; we only have one heap).
1382 JDWP::Write1BE(&p, 8); // Size of allocation unit, in bytes.
1383
1384 JDWP::Write4BE(&p, reinterpret_cast<uintptr_t>(chunk_ptr)); // virtual address of segment start.
1385 JDWP::Write4BE(&p, 0); // offset of this piece (relative to the virtual address).
1386 // [u4]: length of piece, in allocation units
1387 // We won't know this until we're done, so save the offset and stuff in a dummy value.
1388 pieceLenField = p;
1389 JDWP::Write4BE(&p, 0x55555555);
1390 needHeader = false;
1391 }
1392
1393 void Flush() {
1394 // Patch the "length of piece" field.
1395 CHECK_LE(&buf[0], pieceLenField);
1396 CHECK_LE(pieceLenField, p);
1397 JDWP::Set4BE(pieceLenField, totalAllocationUnits);
1398
1399 Dbg::DdmSendChunk(type, p - &buf[0], &buf[0]);
1400 Reset();
1401 }
1402
Elliott Hughesa2155262011-11-16 16:26:58 -08001403 static void HeapChunkCallback(const void* chunk_ptr, size_t chunk_len, const void* user_ptr, size_t user_len, void* arg) {
1404 reinterpret_cast<HeapChunkContext*>(arg)->HeapChunkCallback(chunk_ptr, chunk_len, user_ptr, user_len);
1405 }
1406
Elliott Hughes6a5bd492011-10-28 14:33:57 -07001407 private:
Elliott Hughesa2155262011-11-16 16:26:58 -08001408 enum { ALLOCATION_UNIT_SIZE = 8 };
1409
Elliott Hughes6a5bd492011-10-28 14:33:57 -07001410 void Reset() {
1411 p = &buf[0];
1412 totalAllocationUnits = 0;
1413 needHeader = true;
1414 pieceLenField = NULL;
1415 }
1416
Elliott Hughesa2155262011-11-16 16:26:58 -08001417 void HeapChunkCallback(const void* chunk_ptr, size_t chunk_len, const void* user_ptr, size_t user_len) {
1418 CHECK_EQ((chunk_len & (ALLOCATION_UNIT_SIZE-1)), 0U);
Elliott Hughes6a5bd492011-10-28 14:33:57 -07001419
Elliott Hughesa2155262011-11-16 16:26:58 -08001420 /* Make sure there's enough room left in the buffer.
1421 * We need to use two bytes for every fractional 256
1422 * allocation units used by the chunk.
1423 */
1424 {
1425 size_t needed = (((chunk_len/ALLOCATION_UNIT_SIZE + 255) / 256) * 2);
1426 size_t bytesLeft = buf.size() - (size_t)(p - &buf[0]);
1427 if (bytesLeft < needed) {
1428 Flush();
1429 }
Elliott Hughes6a5bd492011-10-28 14:33:57 -07001430
Elliott Hughesa2155262011-11-16 16:26:58 -08001431 bytesLeft = buf.size() - (size_t)(p - &buf[0]);
1432 if (bytesLeft < needed) {
1433 LOG(WARNING) << "chunk is too big to transmit (chunk_len=" << chunk_len << ", " << needed << " bytes)";
1434 return;
1435 }
1436 }
1437
1438 // OLD-TODO: notice when there's a gap and start a new heap, or at least a new range.
1439 EnsureHeader(chunk_ptr);
1440
1441 // Determine the type of this chunk.
1442 // OLD-TODO: if context.merge, see if this chunk is different from the last chunk.
1443 // If it's the same, we should combine them.
1444 uint8_t state = ExamineObject(reinterpret_cast<const Object*>(user_ptr), (type == CHUNK_TYPE("NHSG")));
1445
1446 // Write out the chunk description.
1447 chunk_len /= ALLOCATION_UNIT_SIZE; // convert to allocation units
1448 totalAllocationUnits += chunk_len;
1449 while (chunk_len > 256) {
1450 *p++ = state | HPSG_PARTIAL;
1451 *p++ = 255; // length - 1
1452 chunk_len -= 256;
1453 }
1454 *p++ = state;
1455 *p++ = chunk_len - 1;
Elliott Hughes6a5bd492011-10-28 14:33:57 -07001456 }
1457
Elliott Hughesa2155262011-11-16 16:26:58 -08001458 uint8_t ExamineObject(const Object* o, bool is_native_heap) {
1459 if (o == NULL) {
1460 return HPSG_STATE(SOLIDITY_FREE, 0);
1461 }
Elliott Hughes6a5bd492011-10-28 14:33:57 -07001462
Elliott Hughesa2155262011-11-16 16:26:58 -08001463 // It's an allocated chunk. Figure out what it is.
Elliott Hughes6a5bd492011-10-28 14:33:57 -07001464
Elliott Hughesa2155262011-11-16 16:26:58 -08001465 // If we're looking at the native heap, we'll just return
1466 // (SOLIDITY_HARD, KIND_NATIVE) for all allocated chunks.
1467 if (is_native_heap || !Heap::IsLiveObjectLocked(o)) {
1468 return HPSG_STATE(SOLIDITY_HARD, KIND_NATIVE);
1469 }
1470
1471 Class* c = o->GetClass();
1472 if (c == NULL) {
1473 // The object was probably just created but hasn't been initialized yet.
1474 return HPSG_STATE(SOLIDITY_HARD, KIND_OBJECT);
1475 }
1476
1477 if (!Heap::IsHeapAddress(c)) {
1478 LOG(WARNING) << "invalid class for managed heap object: " << o << " " << c;
1479 return HPSG_STATE(SOLIDITY_HARD, KIND_UNKNOWN);
1480 }
1481
1482 if (c->IsClassClass()) {
1483 return HPSG_STATE(SOLIDITY_HARD, KIND_CLASS_OBJECT);
1484 }
1485
1486 if (c->IsArrayClass()) {
1487 if (o->IsObjectArray()) {
1488 return HPSG_STATE(SOLIDITY_HARD, KIND_ARRAY_4);
1489 }
1490 switch (c->GetComponentSize()) {
1491 case 1: return HPSG_STATE(SOLIDITY_HARD, KIND_ARRAY_1);
1492 case 2: return HPSG_STATE(SOLIDITY_HARD, KIND_ARRAY_2);
1493 case 4: return HPSG_STATE(SOLIDITY_HARD, KIND_ARRAY_4);
1494 case 8: return HPSG_STATE(SOLIDITY_HARD, KIND_ARRAY_8);
1495 }
1496 }
1497
Elliott Hughes6a5bd492011-10-28 14:33:57 -07001498 return HPSG_STATE(SOLIDITY_HARD, KIND_OBJECT);
1499 }
1500
Elliott Hughesa2155262011-11-16 16:26:58 -08001501 DISALLOW_COPY_AND_ASSIGN(HeapChunkContext);
1502};
Elliott Hughes6a5bd492011-10-28 14:33:57 -07001503
1504void Dbg::DdmSendHeapSegments(bool native) {
1505 Dbg::HpsgWhen when;
1506 Dbg::HpsgWhat what;
1507 if (!native) {
1508 when = gDdmHpsgWhen;
1509 what = gDdmHpsgWhat;
1510 } else {
1511 when = gDdmNhsgWhen;
1512 what = gDdmNhsgWhat;
1513 }
1514 if (when == HPSG_WHEN_NEVER) {
1515 return;
1516 }
1517
1518 // Figure out what kind of chunks we'll be sending.
1519 CHECK(what == HPSG_WHAT_MERGED_OBJECTS || what == HPSG_WHAT_DISTINCT_OBJECTS) << static_cast<int>(what);
1520
1521 // First, send a heap start chunk.
1522 uint8_t heap_id[4];
1523 JDWP::Set4BE(&heap_id[0], 1); // Heap id (bogus; we only have one heap).
1524 Dbg::DdmSendChunk(native ? CHUNK_TYPE("NHST") : CHUNK_TYPE("HPST"), sizeof(heap_id), heap_id);
1525
1526 // Send a series of heap segment chunks.
Elliott Hughesa2155262011-11-16 16:26:58 -08001527 HeapChunkContext context((what == HPSG_WHAT_MERGED_OBJECTS), native);
1528 if (native) {
1529 dlmalloc_walk_heap(HeapChunkContext::HeapChunkCallback, &context);
1530 } else {
1531 Heap::WalkHeap(HeapChunkContext::HeapChunkCallback, &context);
1532 }
Elliott Hughes6a5bd492011-10-28 14:33:57 -07001533
1534 // Finally, send a heap end chunk.
1535 Dbg::DdmSendChunk(native ? CHUNK_TYPE("NHEN") : CHUNK_TYPE("HPEN"), sizeof(heap_id), heap_id);
Elliott Hughes767a1472011-10-26 18:49:02 -07001536}
1537
Elliott Hughes545a0642011-11-08 19:10:03 -08001538void Dbg::SetAllocTrackingEnabled(bool enabled) {
1539 MutexLock mu(gAllocTrackerLock);
1540 if (enabled) {
1541 if (recent_allocation_records_ == NULL) {
1542 LOG(INFO) << "Enabling alloc tracker (" << kNumAllocRecords << " entries, "
1543 << kMaxAllocRecordStackDepth << " frames --> "
1544 << (sizeof(AllocRecord) * kNumAllocRecords) << " bytes)";
1545 gAllocRecordHead = gAllocRecordCount = 0;
1546 recent_allocation_records_ = new AllocRecord[kNumAllocRecords];
1547 CHECK(recent_allocation_records_ != NULL);
1548 }
1549 } else {
1550 delete[] recent_allocation_records_;
1551 recent_allocation_records_ = NULL;
1552 }
1553}
1554
1555struct AllocRecordStackVisitor : public Thread::StackVisitor {
1556 AllocRecordStackVisitor(AllocRecord* record) : record(record), depth(0) {
1557 }
1558
1559 virtual void VisitFrame(const Frame& f, uintptr_t pc) {
1560 if (depth >= kMaxAllocRecordStackDepth) {
1561 return;
1562 }
1563 Method* m = f.GetMethod();
1564 if (m == NULL || m->IsCalleeSaveMethod()) {
1565 return;
1566 }
1567 record->stack[depth].method = m;
1568 record->stack[depth].raw_pc = pc;
1569 ++depth;
1570 }
1571
1572 ~AllocRecordStackVisitor() {
1573 // Clear out any unused stack trace elements.
1574 for (; depth < kMaxAllocRecordStackDepth; ++depth) {
1575 record->stack[depth].method = NULL;
1576 record->stack[depth].raw_pc = 0;
1577 }
1578 }
1579
1580 AllocRecord* record;
1581 size_t depth;
1582};
1583
1584void Dbg::RecordAllocation(Class* type, size_t byte_count) {
1585 Thread* self = Thread::Current();
1586 CHECK(self != NULL);
1587
1588 MutexLock mu(gAllocTrackerLock);
1589 if (recent_allocation_records_ == NULL) {
1590 return;
1591 }
1592
1593 // Advance and clip.
1594 if (++gAllocRecordHead == kNumAllocRecords) {
1595 gAllocRecordHead = 0;
1596 }
1597
1598 // Fill in the basics.
1599 AllocRecord* record = &recent_allocation_records_[gAllocRecordHead];
1600 record->type = type;
1601 record->byte_count = byte_count;
1602 record->thin_lock_id = self->GetThinLockId();
1603
1604 // Fill in the stack trace.
1605 AllocRecordStackVisitor visitor(record);
1606 self->WalkStack(&visitor);
1607
1608 if (gAllocRecordCount < kNumAllocRecords) {
1609 ++gAllocRecordCount;
1610 }
1611}
1612
1613/*
1614 * Return the index of the head element.
1615 *
1616 * We point at the most-recently-written record, so if allocRecordCount is 1
1617 * we want to use the current element. Take "head+1" and subtract count
1618 * from it.
1619 *
1620 * We need to handle underflow in our circular buffer, so we add
1621 * kNumAllocRecords and then mask it back down.
1622 */
1623inline static int headIndex() {
1624 return (gAllocRecordHead+1 + kNumAllocRecords - gAllocRecordCount) & (kNumAllocRecords-1);
1625}
1626
1627void Dbg::DumpRecentAllocations() {
1628 MutexLock mu(gAllocTrackerLock);
1629 if (recent_allocation_records_ == NULL) {
1630 LOG(INFO) << "Not recording tracked allocations";
1631 return;
1632 }
1633
1634 // "i" is the head of the list. We want to start at the end of the
1635 // list and move forward to the tail.
1636 size_t i = headIndex();
1637 size_t count = gAllocRecordCount;
1638
1639 LOG(INFO) << "Tracked allocations, (head=" << gAllocRecordHead << " count=" << count << ")";
1640 while (count--) {
1641 AllocRecord* record = &recent_allocation_records_[i];
1642
1643 LOG(INFO) << StringPrintf(" T=%-2d %6d ", record->thin_lock_id, record->byte_count)
1644 << PrettyClass(record->type);
1645
1646 for (size_t stack_frame = 0; stack_frame < kMaxAllocRecordStackDepth; ++stack_frame) {
1647 const Method* m = record->stack[stack_frame].method;
1648 if (m == NULL) {
1649 break;
1650 }
1651 LOG(INFO) << " " << PrettyMethod(m) << " line " << record->stack[stack_frame].LineNumber();
1652 }
1653
1654 // pause periodically to help logcat catch up
1655 if ((count % 5) == 0) {
1656 usleep(40000);
1657 }
1658
1659 i = (i + 1) & (kNumAllocRecords-1);
1660 }
1661}
1662
1663class StringTable {
1664 public:
1665 StringTable() {
1666 }
1667
1668 void Add(const String* s) {
1669 table_.insert(s);
1670 }
1671
1672 size_t IndexOf(const String* s) {
1673 return std::distance(table_.begin(), table_.find(s));
1674 }
1675
1676 size_t Size() {
1677 return table_.size();
1678 }
1679
1680 void WriteTo(std::vector<uint8_t>& bytes) {
1681 typedef std::set<const String*>::const_iterator It; // TODO: C++0x auto
1682 for (It it = table_.begin(); it != table_.end(); ++it) {
1683 const String* s = *it;
1684 JDWP::AppendUtf16BE(bytes, s->GetCharArray()->GetData(), s->GetLength());
1685 }
1686 }
1687
1688 private:
1689 std::set<const String*> table_;
1690 DISALLOW_COPY_AND_ASSIGN(StringTable);
1691};
1692
1693/*
1694 * The data we send to DDMS contains everything we have recorded.
1695 *
1696 * Message header (all values big-endian):
1697 * (1b) message header len (to allow future expansion); includes itself
1698 * (1b) entry header len
1699 * (1b) stack frame len
1700 * (2b) number of entries
1701 * (4b) offset to string table from start of message
1702 * (2b) number of class name strings
1703 * (2b) number of method name strings
1704 * (2b) number of source file name strings
1705 * For each entry:
1706 * (4b) total allocation size
1707 * (2b) threadId
1708 * (2b) allocated object's class name index
1709 * (1b) stack depth
1710 * For each stack frame:
1711 * (2b) method's class name
1712 * (2b) method name
1713 * (2b) method source file
1714 * (2b) line number, clipped to 32767; -2 if native; -1 if no source
1715 * (xb) class name strings
1716 * (xb) method name strings
1717 * (xb) source file strings
1718 *
1719 * As with other DDM traffic, strings are sent as a 4-byte length
1720 * followed by UTF-16 data.
1721 *
1722 * We send up 16-bit unsigned indexes into string tables. In theory there
1723 * can be (kMaxAllocRecordStackDepth * kNumAllocRecords) unique strings in
1724 * each table, but in practice there should be far fewer.
1725 *
1726 * The chief reason for using a string table here is to keep the size of
1727 * the DDMS message to a minimum. This is partly to make the protocol
1728 * efficient, but also because we have to form the whole thing up all at
1729 * once in a memory buffer.
1730 *
1731 * We use separate string tables for class names, method names, and source
1732 * files to keep the indexes small. There will generally be no overlap
1733 * between the contents of these tables.
1734 */
1735jbyteArray Dbg::GetRecentAllocations() {
1736 if (false) {
1737 DumpRecentAllocations();
1738 }
1739
1740 MutexLock mu(gAllocTrackerLock);
1741
1742 /*
1743 * Part 1: generate string tables.
1744 */
1745 StringTable class_names;
1746 StringTable method_names;
1747 StringTable filenames;
1748
1749 int count = gAllocRecordCount;
1750 int idx = headIndex();
1751 while (count--) {
1752 AllocRecord* record = &recent_allocation_records_[idx];
1753
1754 class_names.Add(record->type->GetDescriptor());
1755
1756 for (size_t i = 0; i < kMaxAllocRecordStackDepth; i++) {
1757 const Method* m = record->stack[i].method;
1758 if (m != NULL) {
1759 class_names.Add(m->GetDeclaringClass()->GetDescriptor());
1760 method_names.Add(m->GetName());
1761 filenames.Add(m->GetDeclaringClass()->GetSourceFile());
1762 }
1763 }
1764
1765 idx = (idx + 1) & (kNumAllocRecords-1);
1766 }
1767
1768 LOG(INFO) << "allocation records: " << gAllocRecordCount;
1769
1770 /*
1771 * Part 2: allocate a buffer and generate the output.
1772 */
1773 std::vector<uint8_t> bytes;
1774
1775 // (1b) message header len (to allow future expansion); includes itself
1776 // (1b) entry header len
1777 // (1b) stack frame len
1778 const int kMessageHeaderLen = 15;
1779 const int kEntryHeaderLen = 9;
1780 const int kStackFrameLen = 8;
1781 JDWP::Append1BE(bytes, kMessageHeaderLen);
1782 JDWP::Append1BE(bytes, kEntryHeaderLen);
1783 JDWP::Append1BE(bytes, kStackFrameLen);
1784
1785 // (2b) number of entries
1786 // (4b) offset to string table from start of message
1787 // (2b) number of class name strings
1788 // (2b) number of method name strings
1789 // (2b) number of source file name strings
1790 JDWP::Append2BE(bytes, gAllocRecordCount);
1791 size_t string_table_offset = bytes.size();
1792 JDWP::Append4BE(bytes, 0); // We'll patch this later...
1793 JDWP::Append2BE(bytes, class_names.Size());
1794 JDWP::Append2BE(bytes, method_names.Size());
1795 JDWP::Append2BE(bytes, filenames.Size());
1796
1797 count = gAllocRecordCount;
1798 idx = headIndex();
1799 while (count--) {
1800 // For each entry:
1801 // (4b) total allocation size
1802 // (2b) thread id
1803 // (2b) allocated object's class name index
1804 // (1b) stack depth
1805 AllocRecord* record = &recent_allocation_records_[idx];
1806 size_t stack_depth = record->GetDepth();
1807 JDWP::Append4BE(bytes, record->byte_count);
1808 JDWP::Append2BE(bytes, record->thin_lock_id);
1809 JDWP::Append2BE(bytes, class_names.IndexOf(record->type->GetDescriptor()));
1810 JDWP::Append1BE(bytes, stack_depth);
1811
1812 for (size_t stack_frame = 0; stack_frame < stack_depth; ++stack_frame) {
1813 // For each stack frame:
1814 // (2b) method's class name
1815 // (2b) method name
1816 // (2b) method source file
1817 // (2b) line number, clipped to 32767; -2 if native; -1 if no source
1818 const Method* m = record->stack[stack_frame].method;
1819 JDWP::Append2BE(bytes, class_names.IndexOf(m->GetDeclaringClass()->GetDescriptor()));
1820 JDWP::Append2BE(bytes, method_names.IndexOf(m->GetName()));
1821 JDWP::Append2BE(bytes, filenames.IndexOf(m->GetDeclaringClass()->GetSourceFile()));
1822 JDWP::Append2BE(bytes, record->stack[stack_frame].LineNumber());
1823 }
1824
1825 idx = (idx + 1) & (kNumAllocRecords-1);
1826 }
1827
1828 // (xb) class name strings
1829 // (xb) method name strings
1830 // (xb) source file strings
1831 JDWP::Set4BE(&bytes[string_table_offset], bytes.size());
1832 class_names.WriteTo(bytes);
1833 method_names.WriteTo(bytes);
1834 filenames.WriteTo(bytes);
1835
1836 JNIEnv* env = Thread::Current()->GetJniEnv();
1837 jbyteArray result = env->NewByteArray(bytes.size());
1838 if (result != NULL) {
1839 env->SetByteArrayRegion(result, 0, bytes.size(), reinterpret_cast<const jbyte*>(&bytes[0]));
1840 }
1841 return result;
1842}
1843
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001844} // namespace art