blob: 7918bfb4455a45b5200eed26e3a0d183f6245e67 [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
501const char* Dbg::GetSourceFile(JDWP::RefTypeId refTypeId) {
502 UNIMPLEMENTED(FATAL);
503 return NULL;
504}
505
506const char* Dbg::GetObjectTypeName(JDWP::ObjectId objectId) {
507 UNIMPLEMENTED(FATAL);
508 return NULL;
509}
510
511uint8_t Dbg::GetObjectTag(JDWP::ObjectId objectId) {
512 UNIMPLEMENTED(FATAL);
513 return 0;
514}
515
516int Dbg::GetTagWidth(int tag) {
517 UNIMPLEMENTED(FATAL);
518 return 0;
519}
520
521int Dbg::GetArrayLength(JDWP::ObjectId arrayId) {
522 UNIMPLEMENTED(FATAL);
523 return 0;
524}
525
526uint8_t Dbg::GetArrayElementTag(JDWP::ObjectId arrayId) {
527 UNIMPLEMENTED(FATAL);
528 return 0;
529}
530
531bool Dbg::OutputArray(JDWP::ObjectId arrayId, int firstIndex, int count, JDWP::ExpandBuf* pReply) {
532 UNIMPLEMENTED(FATAL);
533 return false;
534}
535
536bool Dbg::SetArrayElements(JDWP::ObjectId arrayId, int firstIndex, int count, const uint8_t* buf) {
537 UNIMPLEMENTED(FATAL);
538 return false;
539}
540
541JDWP::ObjectId Dbg::CreateString(const char* str) {
542 UNIMPLEMENTED(FATAL);
543 return 0;
544}
545
546JDWP::ObjectId Dbg::CreateObject(JDWP::RefTypeId classId) {
547 UNIMPLEMENTED(FATAL);
548 return 0;
549}
550
551JDWP::ObjectId Dbg::CreateArrayObject(JDWP::RefTypeId arrayTypeId, uint32_t length) {
552 UNIMPLEMENTED(FATAL);
553 return 0;
554}
555
556bool Dbg::MatchType(JDWP::RefTypeId instClassId, JDWP::RefTypeId classId) {
557 UNIMPLEMENTED(FATAL);
558 return false;
559}
560
561const char* Dbg::GetMethodName(JDWP::RefTypeId refTypeId, JDWP::MethodId id) {
562 UNIMPLEMENTED(FATAL);
563 return NULL;
564}
565
Elliott Hughesa2e54f62011-11-17 13:01:30 -0800566/*
567 * Augment the access flags for synthetic methods and fields by setting
568 * the (as described by the spec) "0xf0000000 bit". Also, strip out any
569 * flags not specified by the Java programming language.
570 */
571static uint32_t MangleAccessFlags(uint32_t accessFlags) {
572 accessFlags &= kAccJavaFlagsMask;
573 if ((accessFlags & kAccSynthetic) != 0) {
574 accessFlags |= 0xf0000000;
575 }
576 return accessFlags;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700577}
578
Elliott Hughesa2e54f62011-11-17 13:01:30 -0800579JDWP::FieldId ToFieldId(Field* f) {
580 return static_cast<JDWP::FieldId>(reinterpret_cast<uintptr_t>(f));
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700581}
582
Elliott Hughesa2e54f62011-11-17 13:01:30 -0800583JDWP::MethodId ToMethodId(Method* m) {
584 return static_cast<JDWP::MethodId>(reinterpret_cast<uintptr_t>(m));
585}
586
587void Dbg::OutputDeclaredFields(JDWP::RefTypeId refTypeId, bool withGeneric, JDWP::ExpandBuf* pReply) {
588 Class* c = gRegistry->Get<Class*>(refTypeId);
589 CHECK(c != NULL);
590
591 size_t instance_field_count = c->NumInstanceFields();
592 size_t static_field_count = c->NumStaticFields();
593
594 expandBufAdd4BE(pReply, instance_field_count + static_field_count);
595
596 for (size_t i = 0; i < instance_field_count + static_field_count; ++i) {
597 Field* f = (i < instance_field_count) ? c->GetInstanceField(i) : c->GetStaticField(i - instance_field_count);
598
599 expandBufAddFieldId(pReply, ToFieldId(f));
600 expandBufAddUtf8String(pReply, f->GetName()->ToModifiedUtf8().c_str());
601 expandBufAddUtf8String(pReply, f->GetTypeDescriptor());
602 if (withGeneric) {
603 static const char genericSignature[1] = "";
604 expandBufAddUtf8String(pReply, genericSignature);
605 }
606 expandBufAdd4BE(pReply, MangleAccessFlags(f->GetAccessFlags()));
607 }
608}
609
610void Dbg::OutputDeclaredMethods(JDWP::RefTypeId refTypeId, bool withGeneric, JDWP::ExpandBuf* pReply) {
611 Class* c = gRegistry->Get<Class*>(refTypeId);
612 CHECK(c != NULL);
613
614 size_t direct_method_count = c->NumDirectMethods();
615 size_t virtual_method_count = c->NumVirtualMethods();
616
617 expandBufAdd4BE(pReply, direct_method_count + virtual_method_count);
618
619 for (size_t i = 0; i < direct_method_count + virtual_method_count; ++i) {
620 Method* m = (i < direct_method_count) ? c->GetDirectMethod(i) : c->GetVirtualMethod(i - direct_method_count);
621
622 expandBufAddMethodId(pReply, ToMethodId(m));
623 expandBufAddUtf8String(pReply, m->GetName()->ToModifiedUtf8().c_str());
624 expandBufAddUtf8String(pReply, m->GetSignature()->ToModifiedUtf8().c_str());
625 if (withGeneric) {
626 static const char genericSignature[1] = "";
627 expandBufAddUtf8String(pReply, genericSignature);
628 }
629 expandBufAdd4BE(pReply, MangleAccessFlags(m->GetAccessFlags()));
630 }
631}
632
633void Dbg::OutputDeclaredInterfaces(JDWP::RefTypeId refTypeId, JDWP::ExpandBuf* pReply) {
634 Class* c = gRegistry->Get<Class*>(refTypeId);
635 CHECK(c != NULL);
636 size_t interface_count = c->NumInterfaces();
637 expandBufAdd4BE(pReply, interface_count);
638 for (size_t i = 0; i < interface_count; ++i) {
639 expandBufAddRefTypeId(pReply, gRegistry->Add(c->GetInterface(i)));
640 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700641}
642
643void Dbg::OutputLineTable(JDWP::RefTypeId refTypeId, JDWP::MethodId methodId, JDWP::ExpandBuf* pReply) {
644 UNIMPLEMENTED(FATAL);
645}
646
647void Dbg::OutputVariableTable(JDWP::RefTypeId refTypeId, JDWP::MethodId id, bool withGeneric, JDWP::ExpandBuf* pReply) {
648 UNIMPLEMENTED(FATAL);
649}
650
651uint8_t Dbg::GetFieldBasicTag(JDWP::ObjectId objId, JDWP::FieldId fieldId) {
652 UNIMPLEMENTED(FATAL);
653 return 0;
654}
655
656uint8_t Dbg::GetStaticFieldBasicTag(JDWP::RefTypeId refTypeId, JDWP::FieldId fieldId) {
657 UNIMPLEMENTED(FATAL);
658 return 0;
659}
660
661void Dbg::GetFieldValue(JDWP::ObjectId objectId, JDWP::FieldId fieldId, JDWP::ExpandBuf* pReply) {
662 UNIMPLEMENTED(FATAL);
663}
664
665void Dbg::SetFieldValue(JDWP::ObjectId objectId, JDWP::FieldId fieldId, uint64_t value, int width) {
666 UNIMPLEMENTED(FATAL);
667}
668
669void Dbg::GetStaticFieldValue(JDWP::RefTypeId refTypeId, JDWP::FieldId fieldId, JDWP::ExpandBuf* pReply) {
670 UNIMPLEMENTED(FATAL);
671}
672
673void Dbg::SetStaticFieldValue(JDWP::RefTypeId refTypeId, JDWP::FieldId fieldId, uint64_t rawValue, int width) {
674 UNIMPLEMENTED(FATAL);
675}
676
677char* Dbg::StringToUtf8(JDWP::ObjectId strId) {
678 UNIMPLEMENTED(FATAL);
679 return NULL;
680}
681
Elliott Hughesa2e54f62011-11-17 13:01:30 -0800682Thread* DecodeThread(JDWP::ObjectId threadId) {
683 Object* thread_peer = gRegistry->Get<Object*>(threadId);
684 CHECK(thread_peer != NULL);
685 return Thread::FromManagedThread(thread_peer);
686}
687
688bool Dbg::GetThreadName(JDWP::ObjectId threadId, std::string& name) {
689 ScopedThreadListLock thread_list_lock;
690 Thread* thread = DecodeThread(threadId);
691 if (thread == NULL) {
692 return false;
693 }
694 StringAppendF(&name, "<%d> %s", thread->GetThinLockId(), thread->GetName()->ToModifiedUtf8().c_str());
695 return true;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700696}
697
698JDWP::ObjectId Dbg::GetThreadGroup(JDWP::ObjectId threadId) {
Elliott Hughes499c5132011-11-17 14:55:11 -0800699 Object* thread = gRegistry->Get<Object*>(threadId);
700 CHECK(thread != NULL);
701
702 Class* c = Runtime::Current()->GetClassLinker()->FindSystemClass("Ljava/lang/Thread;");
703 CHECK(c != NULL);
704 Field* f = c->FindInstanceField("group", "Ljava/lang/ThreadGroup;");
705 CHECK(f != NULL);
706 Object* group = f->GetObject(thread);
707 CHECK(group != NULL);
708 return gRegistry->Add(group);
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700709}
710
Elliott Hughes499c5132011-11-17 14:55:11 -0800711std::string Dbg::GetThreadGroupName(JDWP::ObjectId threadGroupId) {
712 Object* thread_group = gRegistry->Get<Object*>(threadGroupId);
713 CHECK(thread_group != NULL);
714
715 Class* c = Runtime::Current()->GetClassLinker()->FindSystemClass("Ljava/lang/ThreadGroup;");
716 CHECK(c != NULL);
717 Field* f = c->FindInstanceField("name", "Ljava/lang/String;");
718 CHECK(f != NULL);
719 String* s = reinterpret_cast<String*>(f->GetObject(thread_group));
720 return s->ToModifiedUtf8();
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700721}
722
723JDWP::ObjectId Dbg::GetThreadGroupParent(JDWP::ObjectId threadGroupId) {
724 UNIMPLEMENTED(FATAL);
725 return 0;
726}
727
Elliott Hughes499c5132011-11-17 14:55:11 -0800728static Object* GetStaticThreadGroup(const char* field_name) {
729 Class* c = Runtime::Current()->GetClassLinker()->FindSystemClass("Ljava/lang/ThreadGroup;");
730 CHECK(c != NULL);
731 Field* f = c->FindStaticField(field_name, "Ljava/lang/ThreadGroup;");
732 CHECK(f != NULL);
733 Object* group = f->GetObject(NULL);
734 CHECK(group != NULL);
735 return group;
736}
737
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700738JDWP::ObjectId Dbg::GetSystemThreadGroupId() {
Elliott Hughes499c5132011-11-17 14:55:11 -0800739 return gRegistry->Add(GetStaticThreadGroup("mSystem"));
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700740}
741
742JDWP::ObjectId Dbg::GetMainThreadGroupId() {
Elliott Hughes499c5132011-11-17 14:55:11 -0800743 return gRegistry->Add(GetStaticThreadGroup("mMain"));
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700744}
745
Elliott Hughes499c5132011-11-17 14:55:11 -0800746bool Dbg::GetThreadStatus(JDWP::ObjectId threadId, uint32_t* pThreadStatus, uint32_t* pSuspendStatus) {
747 ScopedThreadListLock thread_list_lock;
748
749 Thread* thread = DecodeThread(threadId);
750 if (thread == NULL) {
751 return false;
752 }
753
754 switch (thread->GetState()) {
755 case Thread::kTerminated: *pThreadStatus = JDWP::TS_ZOMBIE; break;
756 case Thread::kRunnable: *pThreadStatus = JDWP::TS_RUNNING; break;
757 case Thread::kTimedWaiting: *pThreadStatus = JDWP::TS_SLEEPING; break;
758 case Thread::kBlocked: *pThreadStatus = JDWP::TS_MONITOR; break;
759 case Thread::kWaiting: *pThreadStatus = JDWP::TS_WAIT; break;
760 case Thread::kInitializing: *pThreadStatus = JDWP::TS_ZOMBIE; break;
761 case Thread::kStarting: *pThreadStatus = JDWP::TS_ZOMBIE; break;
762 case Thread::kNative: *pThreadStatus = JDWP::TS_RUNNING; break;
763 case Thread::kVmWait: *pThreadStatus = JDWP::TS_WAIT; break;
764 case Thread::kSuspended: *pThreadStatus = JDWP::TS_RUNNING; break;
765 default:
766 LOG(FATAL) << "unknown thread state " << thread->GetState();
767 }
768
769 *pSuspendStatus = (thread->IsSuspended() ? JDWP::SUSPEND_STATUS_SUSPENDED : 0);
770
771 return true;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700772}
773
774uint32_t Dbg::GetThreadSuspendCount(JDWP::ObjectId threadId) {
775 UNIMPLEMENTED(FATAL);
776 return 0;
777}
778
779bool Dbg::ThreadExists(JDWP::ObjectId threadId) {
Elliott Hughes761928d2011-11-16 18:33:03 -0800780 return DecodeThread(threadId) != NULL;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700781}
782
783bool Dbg::IsSuspended(JDWP::ObjectId threadId) {
Elliott Hughes761928d2011-11-16 18:33:03 -0800784 return DecodeThread(threadId)->IsSuspended();
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700785}
786
787//void Dbg::WaitForSuspend(JDWP::ObjectId threadId);
788
Elliott Hughesa2155262011-11-16 16:26:58 -0800789void Dbg::GetThreadGroupThreadsImpl(Object* thread_group, JDWP::ObjectId** ppThreadIds, uint32_t* pThreadCount) {
790 struct ThreadListVisitor {
791 static void Visit(Thread* t, void* arg) {
792 reinterpret_cast<ThreadListVisitor*>(arg)->Visit(t);
793 }
794
795 void Visit(Thread* t) {
796 if (t == Dbg::GetDebugThread()) {
797 // Skip the JDWP thread. Some debuggers get bent out of shape when they can't suspend and
798 // query all threads, so it's easier if we just don't tell them about this thread.
799 return;
800 }
801 if (thread_group == NULL || t->GetThreadGroup() == thread_group) {
802 threads.push_back(gRegistry->Add(t->GetPeer()));
803 }
804 }
805
806 Object* thread_group;
807 std::vector<JDWP::ObjectId> threads;
808 };
809
810 ThreadListVisitor tlv;
811 tlv.thread_group = thread_group;
812
813 {
814 ScopedThreadListLock thread_list_lock;
815 Runtime::Current()->GetThreadList()->ForEach(ThreadListVisitor::Visit, &tlv);
816 }
817
818 *pThreadCount = tlv.threads.size();
819 if (*pThreadCount == 0) {
820 *ppThreadIds = NULL;
821 } else {
822 *ppThreadIds = new JDWP::ObjectId[*pThreadCount];
823 for (size_t i = 0; i < *pThreadCount; ++i) {
824 (*ppThreadIds)[i] = tlv.threads[i];
825 }
826 }
827}
828
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700829void Dbg::GetThreadGroupThreads(JDWP::ObjectId threadGroupId, JDWP::ObjectId** ppThreadIds, uint32_t* pThreadCount) {
Elliott Hughesa2155262011-11-16 16:26:58 -0800830 GetThreadGroupThreadsImpl(gRegistry->Get<Object*>(threadGroupId), ppThreadIds, pThreadCount);
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700831}
832
833void Dbg::GetAllThreads(JDWP::ObjectId** ppThreadIds, uint32_t* pThreadCount) {
Elliott Hughesa2155262011-11-16 16:26:58 -0800834 GetThreadGroupThreadsImpl(NULL, ppThreadIds, pThreadCount);
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700835}
836
837int Dbg::GetThreadFrameCount(JDWP::ObjectId threadId) {
Elliott Hughesa2e54f62011-11-17 13:01:30 -0800838 struct CountStackDepthVisitor : public Thread::StackVisitor {
839 CountStackDepthVisitor() : depth(0) {}
840 virtual void VisitFrame(const Frame& frame, uintptr_t pc) {
841 ++depth;
842 }
843 size_t depth;
844 };
845 CountStackDepthVisitor visitor;
846 DecodeThread(threadId)->WalkStack(&visitor);
847 return visitor.depth;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700848}
849
850bool Dbg::GetThreadFrame(JDWP::ObjectId threadId, int num, JDWP::FrameId* pFrameId, JDWP::JdwpLocation* pLoc) {
851 UNIMPLEMENTED(FATAL);
852 return false;
853}
854
855JDWP::ObjectId Dbg::GetThreadSelfId() {
Elliott Hughes475fc232011-10-25 15:00:35 -0700856 return gRegistry->Add(Thread::Current()->GetPeer());
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700857}
858
Elliott Hughes475fc232011-10-25 15:00:35 -0700859void Dbg::SuspendVM() {
Elliott Hughesa2155262011-11-16 16:26:58 -0800860 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 -0700861 Runtime::Current()->GetThreadList()->SuspendAll(true);
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700862}
863
864void Dbg::ResumeVM() {
Elliott Hughes475fc232011-10-25 15:00:35 -0700865 Runtime::Current()->GetThreadList()->ResumeAll(true);
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700866}
867
868void Dbg::SuspendThread(JDWP::ObjectId threadId) {
869 UNIMPLEMENTED(FATAL);
870}
871
872void Dbg::ResumeThread(JDWP::ObjectId threadId) {
873 UNIMPLEMENTED(FATAL);
874}
875
876void Dbg::SuspendSelf() {
Elliott Hughes475fc232011-10-25 15:00:35 -0700877 Runtime::Current()->GetThreadList()->SuspendSelfForDebugger();
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700878}
879
880bool Dbg::GetThisObject(JDWP::ObjectId threadId, JDWP::FrameId frameId, JDWP::ObjectId* pThisId) {
881 UNIMPLEMENTED(FATAL);
882 return false;
883}
884
885void Dbg::GetLocalValue(JDWP::ObjectId threadId, JDWP::FrameId frameId, int slot, uint8_t tag, uint8_t* buf, int expectedLen) {
886 UNIMPLEMENTED(FATAL);
887}
888
889void Dbg::SetLocalValue(JDWP::ObjectId threadId, JDWP::FrameId frameId, int slot, uint8_t tag, uint64_t value, int width) {
890 UNIMPLEMENTED(FATAL);
891}
892
893void Dbg::PostLocationEvent(const Method* method, int pcOffset, Object* thisPtr, int eventFlags) {
894 UNIMPLEMENTED(FATAL);
895}
896
897void Dbg::PostException(void* throwFp, int throwRelPc, void* catchFp, int catchRelPc, Object* exception) {
898 UNIMPLEMENTED(FATAL);
899}
900
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700901void Dbg::PostClassPrepare(Class* c) {
902 UNIMPLEMENTED(FATAL);
903}
904
905bool Dbg::WatchLocation(const JDWP::JdwpLocation* pLoc) {
906 UNIMPLEMENTED(FATAL);
907 return false;
908}
909
910void Dbg::UnwatchLocation(const JDWP::JdwpLocation* pLoc) {
911 UNIMPLEMENTED(FATAL);
912}
913
914bool Dbg::ConfigureStep(JDWP::ObjectId threadId, JDWP::JdwpStepSize size, JDWP::JdwpStepDepth depth) {
915 UNIMPLEMENTED(FATAL);
916 return false;
917}
918
919void Dbg::UnconfigureStep(JDWP::ObjectId threadId) {
920 UNIMPLEMENTED(FATAL);
921}
922
923JDWP::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) {
924 UNIMPLEMENTED(FATAL);
925 return JDWP::ERR_NONE;
926}
927
928void Dbg::ExecuteMethod(DebugInvokeReq* pReq) {
929 UNIMPLEMENTED(FATAL);
930}
931
932void Dbg::RegisterObjectId(JDWP::ObjectId id) {
933 UNIMPLEMENTED(FATAL);
934}
935
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -0700936/*
937 * "buf" contains a full JDWP packet, possibly with multiple chunks. We
938 * need to process each, accumulate the replies, and ship the whole thing
939 * back.
940 *
941 * Returns "true" if we have a reply. The reply buffer is newly allocated,
942 * and includes the chunk type/length, followed by the data.
943 *
944 * TODO: we currently assume that the request and reply include a single
945 * chunk. If this becomes inconvenient we will need to adapt.
946 */
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700947bool Dbg::DdmHandlePacket(const uint8_t* buf, int dataLen, uint8_t** pReplyBuf, int* pReplyLen) {
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -0700948 CHECK_GE(dataLen, 0);
949
950 Thread* self = Thread::Current();
951 JNIEnv* env = self->GetJniEnv();
952
953 static jclass Chunk_class = env->FindClass("org/apache/harmony/dalvik/ddmc/Chunk");
954 static jclass DdmServer_class = env->FindClass("org/apache/harmony/dalvik/ddmc/DdmServer");
955 static jmethodID dispatch_mid = env->GetStaticMethodID(DdmServer_class, "dispatch",
956 "(I[BII)Lorg/apache/harmony/dalvik/ddmc/Chunk;");
957 static jfieldID data_fid = env->GetFieldID(Chunk_class, "data", "[B");
958 static jfieldID length_fid = env->GetFieldID(Chunk_class, "length", "I");
959 static jfieldID offset_fid = env->GetFieldID(Chunk_class, "offset", "I");
960 static jfieldID type_fid = env->GetFieldID(Chunk_class, "type", "I");
961
962 // Create a byte[] corresponding to 'buf'.
Elliott Hughes6a5bd492011-10-28 14:33:57 -0700963 ScopedLocalRef<jbyteArray> dataArray(env, env->NewByteArray(dataLen));
964 if (dataArray.get() == NULL) {
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -0700965 LOG(WARNING) << "byte[] allocation failed: " << dataLen;
966 env->ExceptionClear();
967 return false;
968 }
Elliott Hughes6a5bd492011-10-28 14:33:57 -0700969 env->SetByteArrayRegion(dataArray.get(), 0, dataLen, reinterpret_cast<const jbyte*>(buf));
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -0700970
971 const int kChunkHdrLen = 8;
972
973 // Run through and find all chunks. [Currently just find the first.]
Elliott Hughes6a5bd492011-10-28 14:33:57 -0700974 ScopedByteArrayRO contents(env, dataArray.get());
Elliott Hughesf7c3b662011-10-27 12:04:56 -0700975 jint type = JDWP::Get4BE(reinterpret_cast<const uint8_t*>(&contents[0]));
976 jint length = JDWP::Get4BE(reinterpret_cast<const uint8_t*>(&contents[4]));
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -0700977 jint offset = kChunkHdrLen;
978 if (offset + length > dataLen) {
979 LOG(WARNING) << StringPrintf("bad chunk found (len=%u pktLen=%d)", length, dataLen);
980 return false;
981 }
982
983 // Call "private static Chunk dispatch(int type, byte[] data, int offset, int length)".
Elliott Hughes6a5bd492011-10-28 14:33:57 -0700984 ScopedLocalRef<jobject> chunk(env, env->CallStaticObjectMethod(DdmServer_class, dispatch_mid, type, dataArray.get(), offset, length));
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -0700985 if (env->ExceptionCheck()) {
986 LOG(INFO) << StringPrintf("Exception thrown by dispatcher for 0x%08x", type);
987 env->ExceptionDescribe();
988 env->ExceptionClear();
989 return false;
990 }
991
Elliott Hughes6a5bd492011-10-28 14:33:57 -0700992 if (chunk.get() == NULL) {
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -0700993 return false;
994 }
995
996 /*
997 * Pull the pieces out of the chunk. We copy the results into a
998 * newly-allocated buffer that the caller can free. We don't want to
999 * continue using the Chunk object because nothing has a reference to it.
1000 *
1001 * We could avoid this by returning type/data/offset/length and having
1002 * the caller be aware of the object lifetime issues, but that
1003 * integrates the JDWP code more tightly into the VM, and doesn't work
1004 * if we have responses for multiple chunks.
1005 *
1006 * So we're pretty much stuck with copying data around multiple times.
1007 */
Elliott Hughes6a5bd492011-10-28 14:33:57 -07001008 ScopedLocalRef<jbyteArray> replyData(env, reinterpret_cast<jbyteArray>(env->GetObjectField(chunk.get(), data_fid)));
1009 length = env->GetIntField(chunk.get(), length_fid);
1010 offset = env->GetIntField(chunk.get(), offset_fid);
1011 type = env->GetIntField(chunk.get(), type_fid);
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07001012
Elliott Hughes6a5bd492011-10-28 14:33:57 -07001013 LOG(VERBOSE) << StringPrintf("DDM reply: type=0x%08x data=%p offset=%d length=%d", type, replyData.get(), offset, length);
1014 if (length == 0 || replyData.get() == NULL) {
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07001015 return false;
1016 }
1017
Elliott Hughes6a5bd492011-10-28 14:33:57 -07001018 jsize replyLength = env->GetArrayLength(replyData.get());
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07001019 if (offset + length > replyLength) {
1020 LOG(WARNING) << StringPrintf("chunk off=%d len=%d exceeds reply array len %d", offset, length, replyLength);
1021 return false;
1022 }
1023
1024 uint8_t* reply = new uint8_t[length + kChunkHdrLen];
1025 if (reply == NULL) {
1026 LOG(WARNING) << "malloc failed: " << (length + kChunkHdrLen);
1027 return false;
1028 }
Elliott Hughesf7c3b662011-10-27 12:04:56 -07001029 JDWP::Set4BE(reply + 0, type);
1030 JDWP::Set4BE(reply + 4, length);
Elliott Hughes6a5bd492011-10-28 14:33:57 -07001031 env->GetByteArrayRegion(replyData.get(), offset, length, reinterpret_cast<jbyte*>(reply + kChunkHdrLen));
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07001032
1033 *pReplyBuf = reply;
1034 *pReplyLen = length + kChunkHdrLen;
1035
1036 LOG(VERBOSE) << StringPrintf("dvmHandleDdm returning type=%.4s buf=%p len=%d", (char*) reply, reply, length);
1037 return true;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001038}
1039
Elliott Hughesa2155262011-11-16 16:26:58 -08001040void Dbg::DdmBroadcast(bool connect) {
Elliott Hughes47fce012011-10-25 18:37:19 -07001041 LOG(VERBOSE) << "Broadcasting DDM " << (connect ? "connect" : "disconnect") << "...";
1042
1043 Thread* self = Thread::Current();
1044 if (self->GetState() != Thread::kRunnable) {
1045 LOG(ERROR) << "DDM broadcast in thread state " << self->GetState();
1046 /* try anyway? */
1047 }
1048
1049 JNIEnv* env = self->GetJniEnv();
1050 static jclass DdmServer_class = env->FindClass("org/apache/harmony/dalvik/ddmc/DdmServer");
1051 static jmethodID broadcast_mid = env->GetStaticMethodID(DdmServer_class, "broadcast", "(I)V");
1052 jint event = connect ? 1 /*DdmServer.CONNECTED*/ : 2 /*DdmServer.DISCONNECTED*/;
1053 env->CallStaticVoidMethod(DdmServer_class, broadcast_mid, event);
1054 if (env->ExceptionCheck()) {
1055 LOG(ERROR) << "DdmServer.broadcast " << event << " failed";
1056 env->ExceptionDescribe();
1057 env->ExceptionClear();
1058 }
1059}
1060
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001061void Dbg::DdmConnected() {
Elliott Hughesa2155262011-11-16 16:26:58 -08001062 Dbg::DdmBroadcast(true);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001063}
1064
1065void Dbg::DdmDisconnected() {
Elliott Hughesa2155262011-11-16 16:26:58 -08001066 Dbg::DdmBroadcast(false);
Elliott Hughes47fce012011-10-25 18:37:19 -07001067 gDdmThreadNotification = false;
1068}
1069
1070/*
Elliott Hughes82188472011-11-07 18:11:48 -08001071 * Send a notification when a thread starts, stops, or changes its name.
Elliott Hughes47fce012011-10-25 18:37:19 -07001072 *
1073 * Because we broadcast the full set of threads when the notifications are
1074 * first enabled, it's possible for "thread" to be actively executing.
1075 */
Elliott Hughes82188472011-11-07 18:11:48 -08001076void Dbg::DdmSendThreadNotification(Thread* t, uint32_t type) {
Elliott Hughes47fce012011-10-25 18:37:19 -07001077 if (!gDdmThreadNotification) {
1078 return;
1079 }
1080
Elliott Hughes82188472011-11-07 18:11:48 -08001081 if (type == CHUNK_TYPE("THDE")) {
Elliott Hughes47fce012011-10-25 18:37:19 -07001082 uint8_t buf[4];
Elliott Hughesf7c3b662011-10-27 12:04:56 -07001083 JDWP::Set4BE(&buf[0], t->GetThinLockId());
Elliott Hughes47fce012011-10-25 18:37:19 -07001084 Dbg::DdmSendChunk(CHUNK_TYPE("THDE"), 4, buf);
Elliott Hughes82188472011-11-07 18:11:48 -08001085 } else {
1086 CHECK(type == CHUNK_TYPE("THCR") || type == CHUNK_TYPE("THNM")) << type;
1087 SirtRef<String> name(t->GetName());
1088 size_t char_count = (name.get() != NULL) ? name->GetLength() : 0;
1089 const jchar* chars = name->GetCharArray()->GetData();
1090
Elliott Hughes21f32d72011-11-09 17:44:13 -08001091 std::vector<uint8_t> bytes;
Elliott Hughes545a0642011-11-08 19:10:03 -08001092 JDWP::Append4BE(bytes, t->GetThinLockId());
1093 JDWP::AppendUtf16BE(bytes, chars, char_count);
Elliott Hughes21f32d72011-11-09 17:44:13 -08001094 CHECK_EQ(bytes.size(), char_count*2 + sizeof(uint32_t)*2);
1095 Dbg::DdmSendChunk(type, bytes);
Elliott Hughes47fce012011-10-25 18:37:19 -07001096 }
1097}
1098
Elliott Hughesa2155262011-11-16 16:26:58 -08001099static void DdmSendThreadStartCallback(Thread* t, void*) {
Elliott Hughes82188472011-11-07 18:11:48 -08001100 Dbg::DdmSendThreadNotification(t, CHUNK_TYPE("THCR"));
Elliott Hughes47fce012011-10-25 18:37:19 -07001101}
1102
1103void Dbg::DdmSetThreadNotification(bool enable) {
1104 // We lock the thread list to avoid sending duplicate events or missing
1105 // a thread change. We should be okay holding this lock while sending
1106 // the messages out. (We have to hold it while accessing a live thread.)
Elliott Hughesbbd9d832011-11-07 14:40:00 -08001107 ScopedThreadListLock thread_list_lock;
Elliott Hughes47fce012011-10-25 18:37:19 -07001108
1109 gDdmThreadNotification = enable;
1110 if (enable) {
Elliott Hughesbfe487b2011-10-26 15:48:55 -07001111 Runtime::Current()->GetThreadList()->ForEach(DdmSendThreadStartCallback, NULL);
Elliott Hughes47fce012011-10-25 18:37:19 -07001112 }
1113}
1114
Elliott Hughesa2155262011-11-16 16:26:58 -08001115void Dbg::PostThreadStartOrStop(Thread* t, uint32_t type) {
Elliott Hughes47fce012011-10-25 18:37:19 -07001116 if (gDebuggerActive) {
1117 JDWP::ObjectId id = gRegistry->Add(t->GetPeer());
Elliott Hughes82188472011-11-07 18:11:48 -08001118 gJdwpState->PostThreadChange(id, type == CHUNK_TYPE("THCR"));
Elliott Hughes47fce012011-10-25 18:37:19 -07001119 }
Elliott Hughes82188472011-11-07 18:11:48 -08001120 Dbg::DdmSendThreadNotification(t, type);
Elliott Hughes47fce012011-10-25 18:37:19 -07001121}
1122
1123void Dbg::PostThreadStart(Thread* t) {
Elliott Hughesa2155262011-11-16 16:26:58 -08001124 Dbg::PostThreadStartOrStop(t, CHUNK_TYPE("THCR"));
Elliott Hughes47fce012011-10-25 18:37:19 -07001125}
1126
1127void Dbg::PostThreadDeath(Thread* t) {
Elliott Hughesa2155262011-11-16 16:26:58 -08001128 Dbg::PostThreadStartOrStop(t, CHUNK_TYPE("THDE"));
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001129}
1130
Elliott Hughes82188472011-11-07 18:11:48 -08001131void Dbg::DdmSendChunk(uint32_t type, size_t byte_count, const uint8_t* buf) {
Elliott Hughes3bb81562011-10-21 18:52:59 -07001132 CHECK(buf != NULL);
1133 iovec vec[1];
1134 vec[0].iov_base = reinterpret_cast<void*>(const_cast<uint8_t*>(buf));
1135 vec[0].iov_len = byte_count;
1136 Dbg::DdmSendChunkV(type, vec, 1);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001137}
1138
Elliott Hughes21f32d72011-11-09 17:44:13 -08001139void Dbg::DdmSendChunk(uint32_t type, const std::vector<uint8_t>& bytes) {
1140 DdmSendChunk(type, bytes.size(), &bytes[0]);
1141}
1142
Elliott Hughes82188472011-11-07 18:11:48 -08001143void Dbg::DdmSendChunkV(uint32_t type, const struct iovec* iov, int iovcnt) {
Elliott Hughes3bb81562011-10-21 18:52:59 -07001144 if (gJdwpState == NULL) {
1145 LOG(VERBOSE) << "Debugger thread not active, ignoring DDM send: " << type;
1146 } else {
Elliott Hughes376a7a02011-10-24 18:35:55 -07001147 gJdwpState->DdmSendChunkV(type, iov, iovcnt);
Elliott Hughes3bb81562011-10-21 18:52:59 -07001148 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001149}
1150
Elliott Hughes767a1472011-10-26 18:49:02 -07001151int Dbg::DdmHandleHpifChunk(HpifWhen when) {
1152 if (when == HPIF_WHEN_NOW) {
Elliott Hughes7162ad92011-10-27 14:08:42 -07001153 DdmSendHeapInfo(when);
Elliott Hughes767a1472011-10-26 18:49:02 -07001154 return true;
1155 }
1156
1157 if (when != HPIF_WHEN_NEVER && when != HPIF_WHEN_NEXT_GC && when != HPIF_WHEN_EVERY_GC) {
1158 LOG(ERROR) << "invalid HpifWhen value: " << static_cast<int>(when);
1159 return false;
1160 }
1161
1162 gDdmHpifWhen = when;
1163 return true;
1164}
1165
1166bool Dbg::DdmHandleHpsgNhsgChunk(Dbg::HpsgWhen when, Dbg::HpsgWhat what, bool native) {
1167 if (when != HPSG_WHEN_NEVER && when != HPSG_WHEN_EVERY_GC) {
1168 LOG(ERROR) << "invalid HpsgWhen value: " << static_cast<int>(when);
1169 return false;
1170 }
1171
1172 if (what != HPSG_WHAT_MERGED_OBJECTS && what != HPSG_WHAT_DISTINCT_OBJECTS) {
1173 LOG(ERROR) << "invalid HpsgWhat value: " << static_cast<int>(what);
1174 return false;
1175 }
1176
1177 if (native) {
1178 gDdmNhsgWhen = when;
1179 gDdmNhsgWhat = what;
1180 } else {
1181 gDdmHpsgWhen = when;
1182 gDdmHpsgWhat = what;
1183 }
1184 return true;
1185}
1186
Elliott Hughes7162ad92011-10-27 14:08:42 -07001187void Dbg::DdmSendHeapInfo(HpifWhen reason) {
1188 // If there's a one-shot 'when', reset it.
1189 if (reason == gDdmHpifWhen) {
1190 if (gDdmHpifWhen == HPIF_WHEN_NEXT_GC) {
1191 gDdmHpifWhen = HPIF_WHEN_NEVER;
1192 }
1193 }
1194
1195 /*
1196 * Chunk HPIF (client --> server)
1197 *
1198 * Heap Info. General information about the heap,
1199 * suitable for a summary display.
1200 *
1201 * [u4]: number of heaps
1202 *
1203 * For each heap:
1204 * [u4]: heap ID
1205 * [u8]: timestamp in ms since Unix epoch
1206 * [u1]: capture reason (same as 'when' value from server)
1207 * [u4]: max heap size in bytes (-Xmx)
1208 * [u4]: current heap size in bytes
1209 * [u4]: current number of bytes allocated
1210 * [u4]: current number of objects allocated
1211 */
1212 uint8_t heap_count = 1;
Elliott Hughes21f32d72011-11-09 17:44:13 -08001213 std::vector<uint8_t> bytes;
Elliott Hughes545a0642011-11-08 19:10:03 -08001214 JDWP::Append4BE(bytes, heap_count);
1215 JDWP::Append4BE(bytes, 1); // Heap id (bogus; we only have one heap).
1216 JDWP::Append8BE(bytes, MilliTime());
1217 JDWP::Append1BE(bytes, reason);
1218 JDWP::Append4BE(bytes, Heap::GetMaxMemory()); // Max allowed heap size in bytes.
1219 JDWP::Append4BE(bytes, Heap::GetTotalMemory()); // Current heap size in bytes.
1220 JDWP::Append4BE(bytes, Heap::GetBytesAllocated());
1221 JDWP::Append4BE(bytes, Heap::GetObjectsAllocated());
Elliott Hughes21f32d72011-11-09 17:44:13 -08001222 CHECK_EQ(bytes.size(), 4U + (heap_count * (4 + 8 + 1 + 4 + 4 + 4 + 4)));
1223 Dbg::DdmSendChunk(CHUNK_TYPE("HPIF"), bytes);
Elliott Hughes767a1472011-10-26 18:49:02 -07001224}
1225
Elliott Hughes6a5bd492011-10-28 14:33:57 -07001226enum HpsgSolidity {
1227 SOLIDITY_FREE = 0,
1228 SOLIDITY_HARD = 1,
1229 SOLIDITY_SOFT = 2,
1230 SOLIDITY_WEAK = 3,
1231 SOLIDITY_PHANTOM = 4,
1232 SOLIDITY_FINALIZABLE = 5,
1233 SOLIDITY_SWEEP = 6,
1234};
1235
1236enum HpsgKind {
1237 KIND_OBJECT = 0,
1238 KIND_CLASS_OBJECT = 1,
1239 KIND_ARRAY_1 = 2,
1240 KIND_ARRAY_2 = 3,
1241 KIND_ARRAY_4 = 4,
1242 KIND_ARRAY_8 = 5,
1243 KIND_UNKNOWN = 6,
1244 KIND_NATIVE = 7,
1245};
1246
1247#define HPSG_PARTIAL (1<<7)
1248#define HPSG_STATE(solidity, kind) ((uint8_t)((((kind) & 0x7) << 3) | ((solidity) & 0x7)))
1249
1250struct HeapChunkContext {
1251 std::vector<uint8_t> buf;
1252 uint8_t* p;
1253 uint8_t* pieceLenField;
1254 size_t totalAllocationUnits;
Elliott Hughes82188472011-11-07 18:11:48 -08001255 uint32_t type;
Elliott Hughes6a5bd492011-10-28 14:33:57 -07001256 bool merge;
1257 bool needHeader;
1258
1259 // Maximum chunk size. Obtain this from the formula:
1260 // (((maximum_heap_size / ALLOCATION_UNIT_SIZE) + 255) / 256) * 2
1261 HeapChunkContext(bool merge, bool native)
1262 : buf(16384 - 16),
1263 type(0),
1264 merge(merge) {
1265 Reset();
1266 if (native) {
1267 type = CHUNK_TYPE("NHSG");
1268 } else {
1269 type = merge ? CHUNK_TYPE("HPSG") : CHUNK_TYPE("HPSO");
1270 }
1271 }
1272
1273 ~HeapChunkContext() {
1274 if (p > &buf[0]) {
1275 Flush();
1276 }
1277 }
1278
1279 void EnsureHeader(const void* chunk_ptr) {
1280 if (!needHeader) {
1281 return;
1282 }
1283
1284 // Start a new HPSx chunk.
1285 JDWP::Write4BE(&p, 1); // Heap id (bogus; we only have one heap).
1286 JDWP::Write1BE(&p, 8); // Size of allocation unit, in bytes.
1287
1288 JDWP::Write4BE(&p, reinterpret_cast<uintptr_t>(chunk_ptr)); // virtual address of segment start.
1289 JDWP::Write4BE(&p, 0); // offset of this piece (relative to the virtual address).
1290 // [u4]: length of piece, in allocation units
1291 // We won't know this until we're done, so save the offset and stuff in a dummy value.
1292 pieceLenField = p;
1293 JDWP::Write4BE(&p, 0x55555555);
1294 needHeader = false;
1295 }
1296
1297 void Flush() {
1298 // Patch the "length of piece" field.
1299 CHECK_LE(&buf[0], pieceLenField);
1300 CHECK_LE(pieceLenField, p);
1301 JDWP::Set4BE(pieceLenField, totalAllocationUnits);
1302
1303 Dbg::DdmSendChunk(type, p - &buf[0], &buf[0]);
1304 Reset();
1305 }
1306
Elliott Hughesa2155262011-11-16 16:26:58 -08001307 static void HeapChunkCallback(const void* chunk_ptr, size_t chunk_len, const void* user_ptr, size_t user_len, void* arg) {
1308 reinterpret_cast<HeapChunkContext*>(arg)->HeapChunkCallback(chunk_ptr, chunk_len, user_ptr, user_len);
1309 }
1310
Elliott Hughes6a5bd492011-10-28 14:33:57 -07001311 private:
Elliott Hughesa2155262011-11-16 16:26:58 -08001312 enum { ALLOCATION_UNIT_SIZE = 8 };
1313
Elliott Hughes6a5bd492011-10-28 14:33:57 -07001314 void Reset() {
1315 p = &buf[0];
1316 totalAllocationUnits = 0;
1317 needHeader = true;
1318 pieceLenField = NULL;
1319 }
1320
Elliott Hughesa2155262011-11-16 16:26:58 -08001321 void HeapChunkCallback(const void* chunk_ptr, size_t chunk_len, const void* user_ptr, size_t user_len) {
1322 CHECK_EQ((chunk_len & (ALLOCATION_UNIT_SIZE-1)), 0U);
Elliott Hughes6a5bd492011-10-28 14:33:57 -07001323
Elliott Hughesa2155262011-11-16 16:26:58 -08001324 /* Make sure there's enough room left in the buffer.
1325 * We need to use two bytes for every fractional 256
1326 * allocation units used by the chunk.
1327 */
1328 {
1329 size_t needed = (((chunk_len/ALLOCATION_UNIT_SIZE + 255) / 256) * 2);
1330 size_t bytesLeft = buf.size() - (size_t)(p - &buf[0]);
1331 if (bytesLeft < needed) {
1332 Flush();
1333 }
Elliott Hughes6a5bd492011-10-28 14:33:57 -07001334
Elliott Hughesa2155262011-11-16 16:26:58 -08001335 bytesLeft = buf.size() - (size_t)(p - &buf[0]);
1336 if (bytesLeft < needed) {
1337 LOG(WARNING) << "chunk is too big to transmit (chunk_len=" << chunk_len << ", " << needed << " bytes)";
1338 return;
1339 }
1340 }
1341
1342 // OLD-TODO: notice when there's a gap and start a new heap, or at least a new range.
1343 EnsureHeader(chunk_ptr);
1344
1345 // Determine the type of this chunk.
1346 // OLD-TODO: if context.merge, see if this chunk is different from the last chunk.
1347 // If it's the same, we should combine them.
1348 uint8_t state = ExamineObject(reinterpret_cast<const Object*>(user_ptr), (type == CHUNK_TYPE("NHSG")));
1349
1350 // Write out the chunk description.
1351 chunk_len /= ALLOCATION_UNIT_SIZE; // convert to allocation units
1352 totalAllocationUnits += chunk_len;
1353 while (chunk_len > 256) {
1354 *p++ = state | HPSG_PARTIAL;
1355 *p++ = 255; // length - 1
1356 chunk_len -= 256;
1357 }
1358 *p++ = state;
1359 *p++ = chunk_len - 1;
Elliott Hughes6a5bd492011-10-28 14:33:57 -07001360 }
1361
Elliott Hughesa2155262011-11-16 16:26:58 -08001362 uint8_t ExamineObject(const Object* o, bool is_native_heap) {
1363 if (o == NULL) {
1364 return HPSG_STATE(SOLIDITY_FREE, 0);
1365 }
Elliott Hughes6a5bd492011-10-28 14:33:57 -07001366
Elliott Hughesa2155262011-11-16 16:26:58 -08001367 // It's an allocated chunk. Figure out what it is.
Elliott Hughes6a5bd492011-10-28 14:33:57 -07001368
Elliott Hughesa2155262011-11-16 16:26:58 -08001369 // If we're looking at the native heap, we'll just return
1370 // (SOLIDITY_HARD, KIND_NATIVE) for all allocated chunks.
1371 if (is_native_heap || !Heap::IsLiveObjectLocked(o)) {
1372 return HPSG_STATE(SOLIDITY_HARD, KIND_NATIVE);
1373 }
1374
1375 Class* c = o->GetClass();
1376 if (c == NULL) {
1377 // The object was probably just created but hasn't been initialized yet.
1378 return HPSG_STATE(SOLIDITY_HARD, KIND_OBJECT);
1379 }
1380
1381 if (!Heap::IsHeapAddress(c)) {
1382 LOG(WARNING) << "invalid class for managed heap object: " << o << " " << c;
1383 return HPSG_STATE(SOLIDITY_HARD, KIND_UNKNOWN);
1384 }
1385
1386 if (c->IsClassClass()) {
1387 return HPSG_STATE(SOLIDITY_HARD, KIND_CLASS_OBJECT);
1388 }
1389
1390 if (c->IsArrayClass()) {
1391 if (o->IsObjectArray()) {
1392 return HPSG_STATE(SOLIDITY_HARD, KIND_ARRAY_4);
1393 }
1394 switch (c->GetComponentSize()) {
1395 case 1: return HPSG_STATE(SOLIDITY_HARD, KIND_ARRAY_1);
1396 case 2: return HPSG_STATE(SOLIDITY_HARD, KIND_ARRAY_2);
1397 case 4: return HPSG_STATE(SOLIDITY_HARD, KIND_ARRAY_4);
1398 case 8: return HPSG_STATE(SOLIDITY_HARD, KIND_ARRAY_8);
1399 }
1400 }
1401
Elliott Hughes6a5bd492011-10-28 14:33:57 -07001402 return HPSG_STATE(SOLIDITY_HARD, KIND_OBJECT);
1403 }
1404
Elliott Hughesa2155262011-11-16 16:26:58 -08001405 DISALLOW_COPY_AND_ASSIGN(HeapChunkContext);
1406};
Elliott Hughes6a5bd492011-10-28 14:33:57 -07001407
1408void Dbg::DdmSendHeapSegments(bool native) {
1409 Dbg::HpsgWhen when;
1410 Dbg::HpsgWhat what;
1411 if (!native) {
1412 when = gDdmHpsgWhen;
1413 what = gDdmHpsgWhat;
1414 } else {
1415 when = gDdmNhsgWhen;
1416 what = gDdmNhsgWhat;
1417 }
1418 if (when == HPSG_WHEN_NEVER) {
1419 return;
1420 }
1421
1422 // Figure out what kind of chunks we'll be sending.
1423 CHECK(what == HPSG_WHAT_MERGED_OBJECTS || what == HPSG_WHAT_DISTINCT_OBJECTS) << static_cast<int>(what);
1424
1425 // First, send a heap start chunk.
1426 uint8_t heap_id[4];
1427 JDWP::Set4BE(&heap_id[0], 1); // Heap id (bogus; we only have one heap).
1428 Dbg::DdmSendChunk(native ? CHUNK_TYPE("NHST") : CHUNK_TYPE("HPST"), sizeof(heap_id), heap_id);
1429
1430 // Send a series of heap segment chunks.
Elliott Hughesa2155262011-11-16 16:26:58 -08001431 HeapChunkContext context((what == HPSG_WHAT_MERGED_OBJECTS), native);
1432 if (native) {
1433 dlmalloc_walk_heap(HeapChunkContext::HeapChunkCallback, &context);
1434 } else {
1435 Heap::WalkHeap(HeapChunkContext::HeapChunkCallback, &context);
1436 }
Elliott Hughes6a5bd492011-10-28 14:33:57 -07001437
1438 // Finally, send a heap end chunk.
1439 Dbg::DdmSendChunk(native ? CHUNK_TYPE("NHEN") : CHUNK_TYPE("HPEN"), sizeof(heap_id), heap_id);
Elliott Hughes767a1472011-10-26 18:49:02 -07001440}
1441
Elliott Hughes545a0642011-11-08 19:10:03 -08001442void Dbg::SetAllocTrackingEnabled(bool enabled) {
1443 MutexLock mu(gAllocTrackerLock);
1444 if (enabled) {
1445 if (recent_allocation_records_ == NULL) {
1446 LOG(INFO) << "Enabling alloc tracker (" << kNumAllocRecords << " entries, "
1447 << kMaxAllocRecordStackDepth << " frames --> "
1448 << (sizeof(AllocRecord) * kNumAllocRecords) << " bytes)";
1449 gAllocRecordHead = gAllocRecordCount = 0;
1450 recent_allocation_records_ = new AllocRecord[kNumAllocRecords];
1451 CHECK(recent_allocation_records_ != NULL);
1452 }
1453 } else {
1454 delete[] recent_allocation_records_;
1455 recent_allocation_records_ = NULL;
1456 }
1457}
1458
1459struct AllocRecordStackVisitor : public Thread::StackVisitor {
1460 AllocRecordStackVisitor(AllocRecord* record) : record(record), depth(0) {
1461 }
1462
1463 virtual void VisitFrame(const Frame& f, uintptr_t pc) {
1464 if (depth >= kMaxAllocRecordStackDepth) {
1465 return;
1466 }
1467 Method* m = f.GetMethod();
1468 if (m == NULL || m->IsCalleeSaveMethod()) {
1469 return;
1470 }
1471 record->stack[depth].method = m;
1472 record->stack[depth].raw_pc = pc;
1473 ++depth;
1474 }
1475
1476 ~AllocRecordStackVisitor() {
1477 // Clear out any unused stack trace elements.
1478 for (; depth < kMaxAllocRecordStackDepth; ++depth) {
1479 record->stack[depth].method = NULL;
1480 record->stack[depth].raw_pc = 0;
1481 }
1482 }
1483
1484 AllocRecord* record;
1485 size_t depth;
1486};
1487
1488void Dbg::RecordAllocation(Class* type, size_t byte_count) {
1489 Thread* self = Thread::Current();
1490 CHECK(self != NULL);
1491
1492 MutexLock mu(gAllocTrackerLock);
1493 if (recent_allocation_records_ == NULL) {
1494 return;
1495 }
1496
1497 // Advance and clip.
1498 if (++gAllocRecordHead == kNumAllocRecords) {
1499 gAllocRecordHead = 0;
1500 }
1501
1502 // Fill in the basics.
1503 AllocRecord* record = &recent_allocation_records_[gAllocRecordHead];
1504 record->type = type;
1505 record->byte_count = byte_count;
1506 record->thin_lock_id = self->GetThinLockId();
1507
1508 // Fill in the stack trace.
1509 AllocRecordStackVisitor visitor(record);
1510 self->WalkStack(&visitor);
1511
1512 if (gAllocRecordCount < kNumAllocRecords) {
1513 ++gAllocRecordCount;
1514 }
1515}
1516
1517/*
1518 * Return the index of the head element.
1519 *
1520 * We point at the most-recently-written record, so if allocRecordCount is 1
1521 * we want to use the current element. Take "head+1" and subtract count
1522 * from it.
1523 *
1524 * We need to handle underflow in our circular buffer, so we add
1525 * kNumAllocRecords and then mask it back down.
1526 */
1527inline static int headIndex() {
1528 return (gAllocRecordHead+1 + kNumAllocRecords - gAllocRecordCount) & (kNumAllocRecords-1);
1529}
1530
1531void Dbg::DumpRecentAllocations() {
1532 MutexLock mu(gAllocTrackerLock);
1533 if (recent_allocation_records_ == NULL) {
1534 LOG(INFO) << "Not recording tracked allocations";
1535 return;
1536 }
1537
1538 // "i" is the head of the list. We want to start at the end of the
1539 // list and move forward to the tail.
1540 size_t i = headIndex();
1541 size_t count = gAllocRecordCount;
1542
1543 LOG(INFO) << "Tracked allocations, (head=" << gAllocRecordHead << " count=" << count << ")";
1544 while (count--) {
1545 AllocRecord* record = &recent_allocation_records_[i];
1546
1547 LOG(INFO) << StringPrintf(" T=%-2d %6d ", record->thin_lock_id, record->byte_count)
1548 << PrettyClass(record->type);
1549
1550 for (size_t stack_frame = 0; stack_frame < kMaxAllocRecordStackDepth; ++stack_frame) {
1551 const Method* m = record->stack[stack_frame].method;
1552 if (m == NULL) {
1553 break;
1554 }
1555 LOG(INFO) << " " << PrettyMethod(m) << " line " << record->stack[stack_frame].LineNumber();
1556 }
1557
1558 // pause periodically to help logcat catch up
1559 if ((count % 5) == 0) {
1560 usleep(40000);
1561 }
1562
1563 i = (i + 1) & (kNumAllocRecords-1);
1564 }
1565}
1566
1567class StringTable {
1568 public:
1569 StringTable() {
1570 }
1571
1572 void Add(const String* s) {
1573 table_.insert(s);
1574 }
1575
1576 size_t IndexOf(const String* s) {
1577 return std::distance(table_.begin(), table_.find(s));
1578 }
1579
1580 size_t Size() {
1581 return table_.size();
1582 }
1583
1584 void WriteTo(std::vector<uint8_t>& bytes) {
1585 typedef std::set<const String*>::const_iterator It; // TODO: C++0x auto
1586 for (It it = table_.begin(); it != table_.end(); ++it) {
1587 const String* s = *it;
1588 JDWP::AppendUtf16BE(bytes, s->GetCharArray()->GetData(), s->GetLength());
1589 }
1590 }
1591
1592 private:
1593 std::set<const String*> table_;
1594 DISALLOW_COPY_AND_ASSIGN(StringTable);
1595};
1596
1597/*
1598 * The data we send to DDMS contains everything we have recorded.
1599 *
1600 * Message header (all values big-endian):
1601 * (1b) message header len (to allow future expansion); includes itself
1602 * (1b) entry header len
1603 * (1b) stack frame len
1604 * (2b) number of entries
1605 * (4b) offset to string table from start of message
1606 * (2b) number of class name strings
1607 * (2b) number of method name strings
1608 * (2b) number of source file name strings
1609 * For each entry:
1610 * (4b) total allocation size
1611 * (2b) threadId
1612 * (2b) allocated object's class name index
1613 * (1b) stack depth
1614 * For each stack frame:
1615 * (2b) method's class name
1616 * (2b) method name
1617 * (2b) method source file
1618 * (2b) line number, clipped to 32767; -2 if native; -1 if no source
1619 * (xb) class name strings
1620 * (xb) method name strings
1621 * (xb) source file strings
1622 *
1623 * As with other DDM traffic, strings are sent as a 4-byte length
1624 * followed by UTF-16 data.
1625 *
1626 * We send up 16-bit unsigned indexes into string tables. In theory there
1627 * can be (kMaxAllocRecordStackDepth * kNumAllocRecords) unique strings in
1628 * each table, but in practice there should be far fewer.
1629 *
1630 * The chief reason for using a string table here is to keep the size of
1631 * the DDMS message to a minimum. This is partly to make the protocol
1632 * efficient, but also because we have to form the whole thing up all at
1633 * once in a memory buffer.
1634 *
1635 * We use separate string tables for class names, method names, and source
1636 * files to keep the indexes small. There will generally be no overlap
1637 * between the contents of these tables.
1638 */
1639jbyteArray Dbg::GetRecentAllocations() {
1640 if (false) {
1641 DumpRecentAllocations();
1642 }
1643
1644 MutexLock mu(gAllocTrackerLock);
1645
1646 /*
1647 * Part 1: generate string tables.
1648 */
1649 StringTable class_names;
1650 StringTable method_names;
1651 StringTable filenames;
1652
1653 int count = gAllocRecordCount;
1654 int idx = headIndex();
1655 while (count--) {
1656 AllocRecord* record = &recent_allocation_records_[idx];
1657
1658 class_names.Add(record->type->GetDescriptor());
1659
1660 for (size_t i = 0; i < kMaxAllocRecordStackDepth; i++) {
1661 const Method* m = record->stack[i].method;
1662 if (m != NULL) {
1663 class_names.Add(m->GetDeclaringClass()->GetDescriptor());
1664 method_names.Add(m->GetName());
1665 filenames.Add(m->GetDeclaringClass()->GetSourceFile());
1666 }
1667 }
1668
1669 idx = (idx + 1) & (kNumAllocRecords-1);
1670 }
1671
1672 LOG(INFO) << "allocation records: " << gAllocRecordCount;
1673
1674 /*
1675 * Part 2: allocate a buffer and generate the output.
1676 */
1677 std::vector<uint8_t> bytes;
1678
1679 // (1b) message header len (to allow future expansion); includes itself
1680 // (1b) entry header len
1681 // (1b) stack frame len
1682 const int kMessageHeaderLen = 15;
1683 const int kEntryHeaderLen = 9;
1684 const int kStackFrameLen = 8;
1685 JDWP::Append1BE(bytes, kMessageHeaderLen);
1686 JDWP::Append1BE(bytes, kEntryHeaderLen);
1687 JDWP::Append1BE(bytes, kStackFrameLen);
1688
1689 // (2b) number of entries
1690 // (4b) offset to string table from start of message
1691 // (2b) number of class name strings
1692 // (2b) number of method name strings
1693 // (2b) number of source file name strings
1694 JDWP::Append2BE(bytes, gAllocRecordCount);
1695 size_t string_table_offset = bytes.size();
1696 JDWP::Append4BE(bytes, 0); // We'll patch this later...
1697 JDWP::Append2BE(bytes, class_names.Size());
1698 JDWP::Append2BE(bytes, method_names.Size());
1699 JDWP::Append2BE(bytes, filenames.Size());
1700
1701 count = gAllocRecordCount;
1702 idx = headIndex();
1703 while (count--) {
1704 // For each entry:
1705 // (4b) total allocation size
1706 // (2b) thread id
1707 // (2b) allocated object's class name index
1708 // (1b) stack depth
1709 AllocRecord* record = &recent_allocation_records_[idx];
1710 size_t stack_depth = record->GetDepth();
1711 JDWP::Append4BE(bytes, record->byte_count);
1712 JDWP::Append2BE(bytes, record->thin_lock_id);
1713 JDWP::Append2BE(bytes, class_names.IndexOf(record->type->GetDescriptor()));
1714 JDWP::Append1BE(bytes, stack_depth);
1715
1716 for (size_t stack_frame = 0; stack_frame < stack_depth; ++stack_frame) {
1717 // For each stack frame:
1718 // (2b) method's class name
1719 // (2b) method name
1720 // (2b) method source file
1721 // (2b) line number, clipped to 32767; -2 if native; -1 if no source
1722 const Method* m = record->stack[stack_frame].method;
1723 JDWP::Append2BE(bytes, class_names.IndexOf(m->GetDeclaringClass()->GetDescriptor()));
1724 JDWP::Append2BE(bytes, method_names.IndexOf(m->GetName()));
1725 JDWP::Append2BE(bytes, filenames.IndexOf(m->GetDeclaringClass()->GetSourceFile()));
1726 JDWP::Append2BE(bytes, record->stack[stack_frame].LineNumber());
1727 }
1728
1729 idx = (idx + 1) & (kNumAllocRecords-1);
1730 }
1731
1732 // (xb) class name strings
1733 // (xb) method name strings
1734 // (xb) source file strings
1735 JDWP::Set4BE(&bytes[string_table_offset], bytes.size());
1736 class_names.WriteTo(bytes);
1737 method_names.WriteTo(bytes);
1738 filenames.WriteTo(bytes);
1739
1740 JNIEnv* env = Thread::Current()->GetJniEnv();
1741 jbyteArray result = env->NewByteArray(bytes.size());
1742 if (result != NULL) {
1743 env->SetByteArrayRegion(result, 0, bytes.size(), reinterpret_cast<const jbyte*>(&bytes[0]));
1744 }
1745 return result;
1746}
1747
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001748} // namespace art