blob: b2f96296bbcc1c3af9652afbaa71f2139fa2a9e3 [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 Hughes1bba14f2011-12-01 18:00:36 -080024#include "class_loader.h"
Elliott Hughes68fdbd02011-11-29 19:22:47 -080025#include "context.h"
Ian Rogers6d4d9fc2011-11-30 16:24:48 -080026#include "object_utils.h"
Elliott Hughes6a5bd492011-10-28 14:33:57 -070027#include "ScopedLocalRef.h"
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -070028#include "ScopedPrimitiveArray.h"
Elliott Hughes47fce012011-10-25 18:37:19 -070029#include "stack_indirect_reference_table.h"
Elliott Hughes475fc232011-10-25 15:00:35 -070030#include "thread_list.h"
31
Elliott Hughes6a5bd492011-10-28 14:33:57 -070032extern "C" void dlmalloc_walk_heap(void(*)(const void*, size_t, const void*, size_t, void*), void*);
33#ifndef HAVE_ANDROID_OS
34void dlmalloc_walk_heap(void(*)(const void*, size_t, const void*, size_t, void*), void*) {
35 // No-op for glibc.
36}
37#endif
38
Elliott Hughes872d4ec2011-10-21 17:07:15 -070039namespace art {
40
Elliott Hughes545a0642011-11-08 19:10:03 -080041static const size_t kMaxAllocRecordStackDepth = 16; // Max 255.
42static const size_t kNumAllocRecords = 512; // Must be power of 2.
43
Elliott Hughes475fc232011-10-25 15:00:35 -070044class ObjectRegistry {
45 public:
46 ObjectRegistry() : lock_("ObjectRegistry lock") {
47 }
48
49 JDWP::ObjectId Add(Object* o) {
50 if (o == NULL) {
51 return 0;
52 }
53 JDWP::ObjectId id = static_cast<JDWP::ObjectId>(reinterpret_cast<uintptr_t>(o));
54 MutexLock mu(lock_);
55 map_[id] = o;
56 return id;
57 }
58
Elliott Hughes234ab152011-10-26 14:02:26 -070059 void Clear() {
60 MutexLock mu(lock_);
61 LOG(DEBUG) << "Debugger has detached; object registry had " << map_.size() << " entries";
62 map_.clear();
63 }
64
Elliott Hughes475fc232011-10-25 15:00:35 -070065 bool Contains(JDWP::ObjectId id) {
66 MutexLock mu(lock_);
67 return map_.find(id) != map_.end();
68 }
69
Elliott Hughesa2155262011-11-16 16:26:58 -080070 template<typename T> T Get(JDWP::ObjectId id) {
71 MutexLock mu(lock_);
72 typedef std::map<JDWP::ObjectId, Object*>::iterator It; // C++0x auto
73 It it = map_.find(id);
74 return (it != map_.end()) ? reinterpret_cast<T>(it->second) : NULL;
75 }
76
Elliott Hughesbfe487b2011-10-26 15:48:55 -070077 void VisitRoots(Heap::RootVisitor* visitor, void* arg) {
78 MutexLock mu(lock_);
79 typedef std::map<JDWP::ObjectId, Object*>::iterator It; // C++0x auto
80 for (It it = map_.begin(); it != map_.end(); ++it) {
81 visitor(it->second, arg);
82 }
83 }
84
Elliott Hughes475fc232011-10-25 15:00:35 -070085 private:
86 Mutex lock_;
87 std::map<JDWP::ObjectId, Object*> map_;
88};
89
Elliott Hughes545a0642011-11-08 19:10:03 -080090struct AllocRecordStackTraceElement {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -080091 Method* method;
Elliott Hughes545a0642011-11-08 19:10:03 -080092 uintptr_t raw_pc;
93
94 int32_t LineNumber() const {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -080095 return MethodHelper(method).GetLineNumFromNativePC(raw_pc);
Elliott Hughes545a0642011-11-08 19:10:03 -080096 }
97};
98
99struct AllocRecord {
100 Class* type;
101 size_t byte_count;
102 uint16_t thin_lock_id;
103 AllocRecordStackTraceElement stack[kMaxAllocRecordStackDepth]; // Unused entries have NULL method.
104
105 size_t GetDepth() {
106 size_t depth = 0;
107 while (depth < kMaxAllocRecordStackDepth && stack[depth].method != NULL) {
108 ++depth;
109 }
110 return depth;
111 }
112};
113
Elliott Hughes4ffd3132011-10-24 12:06:42 -0700114// JDWP is allowed unless the Zygote forbids it.
115static bool gJdwpAllowed = true;
116
Elliott Hughes3bb81562011-10-21 18:52:59 -0700117// Was there a -Xrunjdwp or -agent argument on the command-line?
118static bool gJdwpConfigured = false;
119
120// Broken-down JDWP options. (Only valid if gJdwpConfigured is true.)
Elliott Hughes376a7a02011-10-24 18:35:55 -0700121static JDWP::JdwpOptions gJdwpOptions;
Elliott Hughes3bb81562011-10-21 18:52:59 -0700122
123// Runtime JDWP state.
124static JDWP::JdwpState* gJdwpState = NULL;
125static bool gDebuggerConnected; // debugger or DDMS is connected.
126static bool gDebuggerActive; // debugger is making requests.
127
Elliott Hughes47fce012011-10-25 18:37:19 -0700128static bool gDdmThreadNotification = false;
129
Elliott Hughes767a1472011-10-26 18:49:02 -0700130// DDMS GC-related settings.
131static Dbg::HpifWhen gDdmHpifWhen = Dbg::HPIF_WHEN_NEVER;
132static Dbg::HpsgWhen gDdmHpsgWhen = Dbg::HPSG_WHEN_NEVER;
133static Dbg::HpsgWhat gDdmHpsgWhat;
134static Dbg::HpsgWhen gDdmNhsgWhen = Dbg::HPSG_WHEN_NEVER;
135static Dbg::HpsgWhat gDdmNhsgWhat;
136
Elliott Hughes475fc232011-10-25 15:00:35 -0700137static ObjectRegistry* gRegistry = NULL;
138
Elliott Hughes545a0642011-11-08 19:10:03 -0800139// Recent allocation tracking.
140static Mutex gAllocTrackerLock("AllocTracker lock");
141AllocRecord* Dbg::recent_allocation_records_ = NULL; // TODO: CircularBuffer<AllocRecord>
142static size_t gAllocRecordHead = 0;
143static size_t gAllocRecordCount = 0;
144
Elliott Hughes24437992011-11-30 14:49:33 -0800145static JDWP::JdwpTag BasicTagFromDescriptor(const char* descriptor) {
146 // JDWP deliberately uses the descriptor characters' ASCII values for its enum.
147 // Note that by "basic" we mean that we don't get more specific than JT_OBJECT.
148 return static_cast<JDWP::JdwpTag>(descriptor[0]);
149}
150
151static JDWP::JdwpTag TagFromClass(Class* c) {
Elliott Hughes86b00102011-12-05 17:54:26 -0800152 CHECK(c != NULL);
Elliott Hughes24437992011-11-30 14:49:33 -0800153 if (c->IsArrayClass()) {
154 return JDWP::JT_ARRAY;
155 }
156
157 if (c->IsStringClass()) {
158 return JDWP::JT_STRING;
159 } else if (c->IsClassClass()) {
160 return JDWP::JT_CLASS_OBJECT;
161#if 0 // TODO
162 } else if (dvmInstanceof(clazz, gDvm.classJavaLangThread)) {
163 return JDWP::JT_THREAD;
164 } else if (dvmInstanceof(clazz, gDvm.classJavaLangThreadGroup)) {
165 return JDWP::JT_THREAD_GROUP;
166 } else if (dvmInstanceof(clazz, gDvm.classJavaLangClassLoader)) {
167 return JDWP::JT_CLASS_LOADER;
168#endif
169 } else {
170 return JDWP::JT_OBJECT;
171 }
172}
173
174/*
175 * Objects declared to hold Object might actually hold a more specific
176 * type. The debugger may take a special interest in these (e.g. it
177 * wants to display the contents of Strings), so we want to return an
178 * appropriate tag.
179 *
180 * Null objects are tagged JT_OBJECT.
181 */
182static JDWP::JdwpTag TagFromObject(const Object* o) {
183 return (o == NULL) ? JDWP::JT_OBJECT : TagFromClass(o->GetClass());
184}
185
186static bool IsPrimitiveTag(JDWP::JdwpTag tag) {
187 switch (tag) {
188 case JDWP::JT_BOOLEAN:
189 case JDWP::JT_BYTE:
190 case JDWP::JT_CHAR:
191 case JDWP::JT_FLOAT:
192 case JDWP::JT_DOUBLE:
193 case JDWP::JT_INT:
194 case JDWP::JT_LONG:
195 case JDWP::JT_SHORT:
196 case JDWP::JT_VOID:
197 return true;
198 default:
199 return false;
200 }
201}
202
Elliott Hughes3bb81562011-10-21 18:52:59 -0700203/*
204 * Handle one of the JDWP name/value pairs.
205 *
206 * JDWP options are:
207 * help: if specified, show help message and bail
208 * transport: may be dt_socket or dt_shmem
209 * address: for dt_socket, "host:port", or just "port" when listening
210 * server: if "y", wait for debugger to attach; if "n", attach to debugger
211 * timeout: how long to wait for debugger to connect / listen
212 *
213 * Useful with server=n (these aren't supported yet):
214 * onthrow=<exception-name>: connect to debugger when exception thrown
215 * onuncaught=y|n: connect to debugger when uncaught exception thrown
216 * launch=<command-line>: launch the debugger itself
217 *
218 * The "transport" option is required, as is "address" if server=n.
219 */
220static bool ParseJdwpOption(const std::string& name, const std::string& value) {
221 if (name == "transport") {
222 if (value == "dt_socket") {
Elliott Hughes376a7a02011-10-24 18:35:55 -0700223 gJdwpOptions.transport = JDWP::kJdwpTransportSocket;
Elliott Hughes3bb81562011-10-21 18:52:59 -0700224 } else if (value == "dt_android_adb") {
Elliott Hughes376a7a02011-10-24 18:35:55 -0700225 gJdwpOptions.transport = JDWP::kJdwpTransportAndroidAdb;
Elliott Hughes3bb81562011-10-21 18:52:59 -0700226 } else {
227 LOG(ERROR) << "JDWP transport not supported: " << value;
228 return false;
229 }
230 } else if (name == "server") {
231 if (value == "n") {
Elliott Hughes376a7a02011-10-24 18:35:55 -0700232 gJdwpOptions.server = false;
Elliott Hughes3bb81562011-10-21 18:52:59 -0700233 } else if (value == "y") {
Elliott Hughes376a7a02011-10-24 18:35:55 -0700234 gJdwpOptions.server = true;
Elliott Hughes3bb81562011-10-21 18:52:59 -0700235 } else {
236 LOG(ERROR) << "JDWP option 'server' must be 'y' or 'n'";
237 return false;
238 }
239 } else if (name == "suspend") {
240 if (value == "n") {
Elliott Hughes376a7a02011-10-24 18:35:55 -0700241 gJdwpOptions.suspend = false;
Elliott Hughes3bb81562011-10-21 18:52:59 -0700242 } else if (value == "y") {
Elliott Hughes376a7a02011-10-24 18:35:55 -0700243 gJdwpOptions.suspend = true;
Elliott Hughes3bb81562011-10-21 18:52:59 -0700244 } else {
245 LOG(ERROR) << "JDWP option 'suspend' must be 'y' or 'n'";
246 return false;
247 }
248 } else if (name == "address") {
249 /* this is either <port> or <host>:<port> */
250 std::string port_string;
Elliott Hughes376a7a02011-10-24 18:35:55 -0700251 gJdwpOptions.host.clear();
Elliott Hughes3bb81562011-10-21 18:52:59 -0700252 std::string::size_type colon = value.find(':');
253 if (colon != std::string::npos) {
Elliott Hughes376a7a02011-10-24 18:35:55 -0700254 gJdwpOptions.host = value.substr(0, colon);
Elliott Hughes3bb81562011-10-21 18:52:59 -0700255 port_string = value.substr(colon + 1);
256 } else {
257 port_string = value;
258 }
259 if (port_string.empty()) {
260 LOG(ERROR) << "JDWP address missing port: " << value;
261 return false;
262 }
263 char* end;
264 long port = strtol(port_string.c_str(), &end, 10);
265 if (*end != '\0') {
266 LOG(ERROR) << "JDWP address has junk in port field: " << value;
267 return false;
268 }
Elliott Hughes376a7a02011-10-24 18:35:55 -0700269 gJdwpOptions.port = port;
Elliott Hughes3bb81562011-10-21 18:52:59 -0700270 } else if (name == "launch" || name == "onthrow" || name == "oncaught" || name == "timeout") {
271 /* valid but unsupported */
272 LOG(INFO) << "Ignoring JDWP option '" << name << "'='" << value << "'";
273 } else {
274 LOG(INFO) << "Ignoring unrecognized JDWP option '" << name << "'='" << value << "'";
275 }
276
277 return true;
278}
279
280/*
281 * Parse the latter half of a -Xrunjdwp/-agentlib:jdwp= string, e.g.:
282 * "transport=dt_socket,address=8000,server=y,suspend=n"
283 */
284bool Dbg::ParseJdwpOptions(const std::string& options) {
Elliott Hughes47fce012011-10-25 18:37:19 -0700285 LOG(VERBOSE) << "ParseJdwpOptions: " << options;
286
Elliott Hughes3bb81562011-10-21 18:52:59 -0700287 std::vector<std::string> pairs;
288 Split(options, ',', pairs);
289
290 for (size_t i = 0; i < pairs.size(); ++i) {
291 std::string::size_type equals = pairs[i].find('=');
292 if (equals == std::string::npos) {
293 LOG(ERROR) << "Can't parse JDWP option '" << pairs[i] << "' in '" << options << "'";
294 return false;
295 }
296 ParseJdwpOption(pairs[i].substr(0, equals), pairs[i].substr(equals + 1));
297 }
298
Elliott Hughes376a7a02011-10-24 18:35:55 -0700299 if (gJdwpOptions.transport == JDWP::kJdwpTransportUnknown) {
Elliott Hughes3bb81562011-10-21 18:52:59 -0700300 LOG(ERROR) << "Must specify JDWP transport: " << options;
301 }
Elliott Hughes376a7a02011-10-24 18:35:55 -0700302 if (!gJdwpOptions.server && (gJdwpOptions.host.empty() || gJdwpOptions.port == 0)) {
Elliott Hughes3bb81562011-10-21 18:52:59 -0700303 LOG(ERROR) << "Must specify JDWP host and port when server=n: " << options;
304 return false;
305 }
306
307 gJdwpConfigured = true;
308 return true;
309}
310
Elliott Hughesd1cc8362011-10-24 16:58:50 -0700311void Dbg::StartJdwp() {
Elliott Hughes376a7a02011-10-24 18:35:55 -0700312 if (!gJdwpAllowed || !gJdwpConfigured) {
313 // No JDWP for you!
314 return;
315 }
316
Elliott Hughes475fc232011-10-25 15:00:35 -0700317 CHECK(gRegistry == NULL);
318 gRegistry = new ObjectRegistry;
319
Elliott Hughesd1cc8362011-10-24 16:58:50 -0700320 // Init JDWP if the debugger is enabled. This may connect out to a
321 // debugger, passively listen for a debugger, or block waiting for a
322 // debugger.
Elliott Hughes376a7a02011-10-24 18:35:55 -0700323 gJdwpState = JDWP::JdwpState::Create(&gJdwpOptions);
324 if (gJdwpState == NULL) {
Elliott Hughesf8a2df72011-12-01 12:19:54 -0800325 // We probably failed because some other process has the port already, which means that
326 // if we don't abort the user is likely to think they're talking to us when they're actually
327 // talking to that other process.
328 LOG(FATAL) << "debugger thread failed to initialize";
Elliott Hughesd1cc8362011-10-24 16:58:50 -0700329 }
330
331 // If a debugger has already attached, send the "welcome" message.
332 // This may cause us to suspend all threads.
Elliott Hughes376a7a02011-10-24 18:35:55 -0700333 if (gJdwpState->IsActive()) {
Elliott Hughesa2155262011-11-16 16:26:58 -0800334 //ScopedThreadStateChange tsc(Thread::Current(), Thread::kRunnable);
Elliott Hughes376a7a02011-10-24 18:35:55 -0700335 if (!gJdwpState->PostVMStart()) {
Elliott Hughesd1cc8362011-10-24 16:58:50 -0700336 LOG(WARNING) << "failed to post 'start' message to debugger";
337 }
338 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700339}
340
Elliott Hughesd1cc8362011-10-24 16:58:50 -0700341void Dbg::StopJdwp() {
Elliott Hughes376a7a02011-10-24 18:35:55 -0700342 delete gJdwpState;
Elliott Hughes475fc232011-10-25 15:00:35 -0700343 delete gRegistry;
344 gRegistry = NULL;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700345}
346
Elliott Hughes767a1472011-10-26 18:49:02 -0700347void Dbg::GcDidFinish() {
348 if (gDdmHpifWhen != HPIF_WHEN_NEVER) {
349 LOG(DEBUG) << "Sending VM heap info to DDM";
Elliott Hughes7162ad92011-10-27 14:08:42 -0700350 DdmSendHeapInfo(gDdmHpifWhen);
Elliott Hughes767a1472011-10-26 18:49:02 -0700351 }
352 if (gDdmHpsgWhen != HPSG_WHEN_NEVER) {
353 LOG(DEBUG) << "Dumping VM heap to DDM";
Elliott Hughes6a5bd492011-10-28 14:33:57 -0700354 DdmSendHeapSegments(false);
Elliott Hughes767a1472011-10-26 18:49:02 -0700355 }
356 if (gDdmNhsgWhen != HPSG_WHEN_NEVER) {
357 LOG(DEBUG) << "Dumping native heap to DDM";
Elliott Hughes6a5bd492011-10-28 14:33:57 -0700358 DdmSendHeapSegments(true);
Elliott Hughes767a1472011-10-26 18:49:02 -0700359 }
360}
361
Elliott Hughes4ffd3132011-10-24 12:06:42 -0700362void Dbg::SetJdwpAllowed(bool allowed) {
363 gJdwpAllowed = allowed;
364}
365
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700366DebugInvokeReq* Dbg::GetInvokeReq() {
Elliott Hughes475fc232011-10-25 15:00:35 -0700367 return Thread::Current()->GetInvokeReq();
368}
369
370Thread* Dbg::GetDebugThread() {
371 return (gJdwpState != NULL) ? gJdwpState->GetDebugThread() : NULL;
372}
373
374void Dbg::ClearWaitForEventThread() {
375 gJdwpState->ClearWaitForEventThread();
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700376}
377
378void Dbg::Connected() {
Elliott Hughes3bb81562011-10-21 18:52:59 -0700379 CHECK(!gDebuggerConnected);
380 LOG(VERBOSE) << "JDWP has attached";
381 gDebuggerConnected = true;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700382}
383
Elliott Hughesa2155262011-11-16 16:26:58 -0800384void Dbg::GoActive() {
385 // Enable all debugging features, including scans for breakpoints.
386 // This is a no-op if we're already active.
387 // Only called from the JDWP handler thread.
388 if (gDebuggerActive) {
389 return;
390 }
391
392 LOG(INFO) << "Debugger is active";
393
394 // TODO: CHECK we don't have any outstanding breakpoints.
395
396 gDebuggerActive = true;
397
398 //dvmEnableAllSubMode(kSubModeDebuggerActive);
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700399}
400
401void Dbg::Disconnected() {
Elliott Hughes234ab152011-10-26 14:02:26 -0700402 CHECK(gDebuggerConnected);
403
404 gDebuggerActive = false;
405
406 //dvmDisableAllSubMode(kSubModeDebuggerActive);
407
408 gRegistry->Clear();
409 gDebuggerConnected = false;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700410}
411
412bool Dbg::IsDebuggerConnected() {
Elliott Hughes3bb81562011-10-21 18:52:59 -0700413 return gDebuggerActive;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700414}
415
416bool Dbg::IsDebuggingEnabled() {
Elliott Hughes3bb81562011-10-21 18:52:59 -0700417 return gJdwpConfigured;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700418}
419
420int64_t Dbg::LastDebuggerActivity() {
Elliott Hughesca951522011-12-05 12:01:32 -0800421 return gJdwpState->LastDebuggerActivity();
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700422}
423
424int Dbg::ThreadRunning() {
Elliott Hughesd1cc8362011-10-24 16:58:50 -0700425 return static_cast<int>(Thread::Current()->SetState(Thread::kRunnable));
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700426}
427
428int Dbg::ThreadWaiting() {
Elliott Hughesd1cc8362011-10-24 16:58:50 -0700429 return static_cast<int>(Thread::Current()->SetState(Thread::kVmWait));
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700430}
431
Elliott Hughes6ba581a2011-10-25 11:45:35 -0700432int Dbg::ThreadContinuing(int new_state) {
433 return static_cast<int>(Thread::Current()->SetState(static_cast<Thread::State>(new_state)));
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700434}
435
436void Dbg::UndoDebuggerSuspensions() {
Elliott Hughes234ab152011-10-26 14:02:26 -0700437 Runtime::Current()->GetThreadList()->UndoDebuggerSuspensions();
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700438}
439
440void Dbg::Exit(int status) {
Elliott Hughes1bba14f2011-12-01 18:00:36 -0800441 exit(status); // This is all dalvik did.
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700442}
443
Elliott Hughesbfe487b2011-10-26 15:48:55 -0700444void Dbg::VisitRoots(Heap::RootVisitor* visitor, void* arg) {
445 if (gRegistry != NULL) {
446 gRegistry->VisitRoots(visitor, arg);
447 }
448}
449
Elliott Hughesa2155262011-11-16 16:26:58 -0800450std::string Dbg::GetClassDescriptor(JDWP::RefTypeId classId) {
451 Class* c = gRegistry->Get<Class*>(classId);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800452 return ClassHelper(c).GetDescriptor();
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700453}
454
455JDWP::ObjectId Dbg::GetClassObject(JDWP::RefTypeId id) {
456 UNIMPLEMENTED(FATAL);
457 return 0;
458}
459
460JDWP::RefTypeId Dbg::GetSuperclass(JDWP::RefTypeId id) {
Elliott Hughesa2e54f62011-11-17 13:01:30 -0800461 Class* c = gRegistry->Get<Class*>(id);
462 return gRegistry->Add(c->GetSuperClass());
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700463}
464
465JDWP::ObjectId Dbg::GetClassLoader(JDWP::RefTypeId id) {
Elliott Hughes1bba14f2011-12-01 18:00:36 -0800466 Object* o = gRegistry->Get<Object*>(id);
467 return gRegistry->Add(o->GetClass()->GetClassLoader());
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700468}
469
470uint32_t Dbg::GetAccessFlags(JDWP::RefTypeId id) {
Elliott Hughes6fa602d2011-12-02 17:54:25 -0800471 Class* c = gRegistry->Get<Class*>(id);
472 return c->GetAccessFlags() & kAccJavaFlagsMask;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700473}
474
Elliott Hughesaed4be92011-12-02 16:16:23 -0800475bool Dbg::IsInterface(JDWP::RefTypeId classId) {
476 Class* c = gRegistry->Get<Class*>(classId);
477 return c->IsInterface();
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700478}
479
Elliott Hughesa2155262011-11-16 16:26:58 -0800480void Dbg::GetClassList(uint32_t* pClassCount, JDWP::RefTypeId** pClasses) {
481 // Get the complete list of reference classes (i.e. all classes except
482 // the primitive types).
483 // Returns a newly-allocated buffer full of RefTypeId values.
484 struct ClassListCreator {
485 static bool Visit(Class* c, void* arg) {
486 return reinterpret_cast<ClassListCreator*>(arg)->Visit(c);
487 }
488
489 bool Visit(Class* c) {
490 if (!c->IsPrimitive()) {
491 classes.push_back(static_cast<JDWP::RefTypeId>(gRegistry->Add(c)));
492 }
493 return true;
494 }
495
496 std::vector<JDWP::RefTypeId> classes;
497 };
498
499 ClassListCreator clc;
500 Runtime::Current()->GetClassLinker()->VisitClasses(ClassListCreator::Visit, &clc);
501 *pClassCount = clc.classes.size();
502 *pClasses = new JDWP::RefTypeId[clc.classes.size()];
503 for (size_t i = 0; i < clc.classes.size(); ++i) {
504 (*pClasses)[i] = clc.classes[i];
505 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700506}
507
508void Dbg::GetVisibleClassList(JDWP::ObjectId classLoaderId, uint32_t* pNumClasses, JDWP::RefTypeId** pClassRefBuf) {
509 UNIMPLEMENTED(FATAL);
510}
511
Elliott Hughes6fa602d2011-12-02 17:54:25 -0800512void Dbg::GetClassInfo(JDWP::RefTypeId classId, JDWP::JdwpTypeTag* pTypeTag, uint32_t* pStatus, std::string* pDescriptor) {
Elliott Hughesa2155262011-11-16 16:26:58 -0800513 Class* c = gRegistry->Get<Class*>(classId);
514 if (c->IsArrayClass()) {
515 *pStatus = JDWP::CS_VERIFIED | JDWP::CS_PREPARED;
516 *pTypeTag = JDWP::TT_ARRAY;
517 } else {
518 if (c->IsErroneous()) {
519 *pStatus = JDWP::CS_ERROR;
520 } else {
521 *pStatus = JDWP::CS_VERIFIED | JDWP::CS_PREPARED | JDWP::CS_INITIALIZED;
522 }
523 *pTypeTag = c->IsInterface() ? JDWP::TT_INTERFACE : JDWP::TT_CLASS;
524 }
525
526 if (pDescriptor != NULL) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800527 *pDescriptor = ClassHelper(c).GetDescriptor();
Elliott Hughesa2155262011-11-16 16:26:58 -0800528 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700529}
530
Elliott Hughes6fa602d2011-12-02 17:54:25 -0800531void Dbg::FindLoadedClassBySignature(const char* descriptor, std::vector<JDWP::RefTypeId>& ids) {
532 std::vector<Class*> classes;
533 Runtime::Current()->GetClassLinker()->LookupClasses(descriptor, classes);
534 ids.clear();
535 for (size_t i = 0; i < classes.size(); ++i) {
536 ids.push_back(gRegistry->Add(classes[i]));
537 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700538}
539
Elliott Hughes6fa602d2011-12-02 17:54:25 -0800540void Dbg::GetObjectType(JDWP::ObjectId objectId, JDWP::JdwpTypeTag* pRefTypeTag, JDWP::RefTypeId* pRefTypeId) {
Elliott Hughes499c5132011-11-17 14:55:11 -0800541 Object* o = gRegistry->Get<Object*>(objectId);
542 if (o->GetClass()->IsArrayClass()) {
543 *pRefTypeTag = JDWP::TT_ARRAY;
544 } else if (o->GetClass()->IsInterface()) {
545 *pRefTypeTag = JDWP::TT_INTERFACE;
546 } else {
547 *pRefTypeTag = JDWP::TT_CLASS;
548 }
549 *pRefTypeId = gRegistry->Add(o->GetClass());
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700550}
551
552uint8_t Dbg::GetClassObjectType(JDWP::RefTypeId refTypeId) {
553 UNIMPLEMENTED(FATAL);
554 return 0;
555}
556
Elliott Hughesa2e54f62011-11-17 13:01:30 -0800557std::string Dbg::GetSignature(JDWP::RefTypeId refTypeId) {
558 Class* c = gRegistry->Get<Class*>(refTypeId);
559 CHECK(c != NULL);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800560 return ClassHelper(c).GetDescriptor();
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700561}
562
Elliott Hughes03181a82011-11-17 17:22:21 -0800563bool Dbg::GetSourceFile(JDWP::RefTypeId refTypeId, std::string& result) {
564 Class* c = gRegistry->Get<Class*>(refTypeId);
565 CHECK(c != NULL);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800566 result = ClassHelper(c).GetSourceFile();
567 return result == NULL;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700568}
569
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700570uint8_t Dbg::GetObjectTag(JDWP::ObjectId objectId) {
Elliott Hughes24437992011-11-30 14:49:33 -0800571 Object* o = gRegistry->Get<Object*>(objectId);
572 return TagFromObject(o);
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700573}
574
Elliott Hughesaed4be92011-12-02 16:16:23 -0800575size_t Dbg::GetTagWidth(JDWP::JdwpTag tag) {
Elliott Hughesdbb40792011-11-18 17:05:22 -0800576 switch (tag) {
577 case JDWP::JT_VOID:
578 return 0;
579 case JDWP::JT_BYTE:
580 case JDWP::JT_BOOLEAN:
581 return 1;
582 case JDWP::JT_CHAR:
583 case JDWP::JT_SHORT:
584 return 2;
585 case JDWP::JT_FLOAT:
586 case JDWP::JT_INT:
587 return 4;
588 case JDWP::JT_ARRAY:
589 case JDWP::JT_OBJECT:
590 case JDWP::JT_STRING:
591 case JDWP::JT_THREAD:
592 case JDWP::JT_THREAD_GROUP:
593 case JDWP::JT_CLASS_LOADER:
594 case JDWP::JT_CLASS_OBJECT:
595 return sizeof(JDWP::ObjectId);
596 case JDWP::JT_DOUBLE:
597 case JDWP::JT_LONG:
598 return 8;
599 default:
600 LOG(FATAL) << "unknown tag " << tag;
601 return -1;
602 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700603}
604
605int Dbg::GetArrayLength(JDWP::ObjectId arrayId) {
Elliott Hughes68fdbd02011-11-29 19:22:47 -0800606 Object* o = gRegistry->Get<Object*>(arrayId);
607 Array* a = o->AsArray();
608 return a->GetLength();
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700609}
610
611uint8_t Dbg::GetArrayElementTag(JDWP::ObjectId arrayId) {
Elliott Hughes24437992011-11-30 14:49:33 -0800612 Object* o = gRegistry->Get<Object*>(arrayId);
613 Array* a = o->AsArray();
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800614 std::string descriptor(ClassHelper(a->GetClass()).GetDescriptor());
Elliott Hughes24437992011-11-30 14:49:33 -0800615 JDWP::JdwpTag tag = BasicTagFromDescriptor(descriptor.c_str() + 1);
616 if (!IsPrimitiveTag(tag)) {
617 tag = TagFromClass(a->GetClass()->GetComponentType());
618 }
619 return tag;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700620}
621
Elliott Hughes24437992011-11-30 14:49:33 -0800622bool Dbg::OutputArray(JDWP::ObjectId arrayId, int offset, int count, JDWP::ExpandBuf* pReply) {
623 Object* o = gRegistry->Get<Object*>(arrayId);
624 Array* a = o->AsArray();
625
626 if (offset < 0 || count < 0 || offset > a->GetLength() || a->GetLength() - offset < count) {
627 LOG(WARNING) << __FUNCTION__ << " access out of bounds: offset=" << offset << "; count=" << count;
628 return false;
629 }
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800630 std::string descriptor(ClassHelper(a->GetClass()).GetDescriptor());
Elliott Hughes24437992011-11-30 14:49:33 -0800631 JDWP::JdwpTag tag = BasicTagFromDescriptor(descriptor.c_str() + 1);
632
633 if (IsPrimitiveTag(tag)) {
634 size_t width = GetTagWidth(tag);
635 const uint8_t* src = reinterpret_cast<uint8_t*>(a->GetRawData());
636 uint8_t* dst = expandBufAddSpace(pReply, count * width);
637 if (width == 8) {
638 const uint64_t* src8 = reinterpret_cast<const uint64_t*>(src);
639 for (int i = 0; i < count; ++i) JDWP::Write8BE(&dst, src8[offset + i]);
640 } else if (width == 4) {
641 const uint32_t* src4 = reinterpret_cast<const uint32_t*>(src);
642 for (int i = 0; i < count; ++i) JDWP::Write4BE(&dst, src4[offset + i]);
643 } else if (width == 2) {
644 const uint16_t* src2 = reinterpret_cast<const uint16_t*>(src);
645 for (int i = 0; i < count; ++i) JDWP::Write2BE(&dst, src2[offset + i]);
646 } else {
647 memcpy(dst, &src[offset * width], count * width);
648 }
649 } else {
650 ObjectArray<Object>* oa = a->AsObjectArray<Object>();
651 for (int i = 0; i < count; ++i) {
Elliott Hughesf03b8f62011-12-02 14:26:25 -0800652 Object* element = oa->Get(offset + i);
Elliott Hughes24437992011-11-30 14:49:33 -0800653 JDWP::JdwpTag specific_tag = (element != NULL) ? TagFromObject(element) : tag;
654 expandBufAdd1(pReply, specific_tag);
655 expandBufAddObjectId(pReply, gRegistry->Add(element));
656 }
657 }
658
659 return true;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700660}
661
Elliott Hughesf03b8f62011-12-02 14:26:25 -0800662bool Dbg::SetArrayElements(JDWP::ObjectId arrayId, int offset, int count, const uint8_t* src) {
663 Object* o = gRegistry->Get<Object*>(arrayId);
664 Array* a = o->AsArray();
665
666 if (offset < 0 || count < 0 || offset > a->GetLength() || a->GetLength() - offset < count) {
667 LOG(WARNING) << __FUNCTION__ << " access out of bounds: offset=" << offset << "; count=" << count;
668 return false;
669 }
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800670 std::string descriptor(ClassHelper(a->GetClass()).GetDescriptor());
Elliott Hughesf03b8f62011-12-02 14:26:25 -0800671 JDWP::JdwpTag tag = BasicTagFromDescriptor(descriptor.c_str() + 1);
672
673 if (IsPrimitiveTag(tag)) {
674 size_t width = GetTagWidth(tag);
675 uint8_t* dst = &(reinterpret_cast<uint8_t*>(a->GetRawData())[offset * width]);
676 if (width == 8) {
677 for (int i = 0; i < count; ++i) {
678 // Handle potentially non-aligned memory access one byte at a time for ARM's benefit.
679 uint64_t value;
680 for (size_t j = 0; j < sizeof(uint64_t); ++j) reinterpret_cast<uint8_t*>(&value)[j] = src[j];
681 src += sizeof(uint64_t);
682 JDWP::Write8BE(&dst, value);
683 }
684 } else if (width == 4) {
685 const uint32_t* src4 = reinterpret_cast<const uint32_t*>(src);
686 for (int i = 0; i < count; ++i) JDWP::Write4BE(&dst, src4[i]);
687 } else if (width == 2) {
688 const uint16_t* src2 = reinterpret_cast<const uint16_t*>(src);
689 for (int i = 0; i < count; ++i) JDWP::Write2BE(&dst, src2[i]);
690 } else {
691 memcpy(&dst[offset * width], src, count * width);
692 }
693 } else {
694 ObjectArray<Object>* oa = a->AsObjectArray<Object>();
695 for (int i = 0; i < count; ++i) {
696 JDWP::ObjectId id = JDWP::ReadObjectId(&src);
697 oa->Set(offset + i, gRegistry->Get<Object*>(id));
698 }
699 }
700
701 return true;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700702}
703
704JDWP::ObjectId Dbg::CreateString(const char* str) {
Elliott Hughescccd84f2011-12-05 16:51:54 -0800705 return gRegistry->Add(String::AllocFromModifiedUtf8(str));
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700706}
707
708JDWP::ObjectId Dbg::CreateObject(JDWP::RefTypeId classId) {
Elliott Hughescccd84f2011-12-05 16:51:54 -0800709 Class* c = gRegistry->Get<Class*>(classId);
710 return gRegistry->Add(c->AllocObject());
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700711}
712
713JDWP::ObjectId Dbg::CreateArrayObject(JDWP::RefTypeId arrayTypeId, uint32_t length) {
714 UNIMPLEMENTED(FATAL);
715 return 0;
716}
717
718bool Dbg::MatchType(JDWP::RefTypeId instClassId, JDWP::RefTypeId classId) {
719 UNIMPLEMENTED(FATAL);
720 return false;
721}
722
Elliott Hughes03181a82011-11-17 17:22:21 -0800723JDWP::FieldId ToFieldId(Field* f) {
724#ifdef MOVING_GARBAGE_COLLECTOR
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700725 UNIMPLEMENTED(FATAL);
Elliott Hughes03181a82011-11-17 17:22:21 -0800726#else
727 return static_cast<JDWP::FieldId>(reinterpret_cast<uintptr_t>(f));
728#endif
729}
730
731JDWP::MethodId ToMethodId(Method* m) {
732#ifdef MOVING_GARBAGE_COLLECTOR
733 UNIMPLEMENTED(FATAL);
734#else
735 return static_cast<JDWP::MethodId>(reinterpret_cast<uintptr_t>(m));
736#endif
737}
738
Elliott Hughesaed4be92011-12-02 16:16:23 -0800739Field* FromFieldId(JDWP::FieldId fid) {
740#ifdef MOVING_GARBAGE_COLLECTOR
741 UNIMPLEMENTED(FATAL);
742#else
743 return reinterpret_cast<Field*>(static_cast<uintptr_t>(fid));
744#endif
745}
746
Elliott Hughes03181a82011-11-17 17:22:21 -0800747Method* FromMethodId(JDWP::MethodId mid) {
748#ifdef MOVING_GARBAGE_COLLECTOR
749 UNIMPLEMENTED(FATAL);
750#else
751 return reinterpret_cast<Method*>(static_cast<uintptr_t>(mid));
752#endif
753}
754
755std::string Dbg::GetMethodName(JDWP::RefTypeId refTypeId, JDWP::MethodId methodId) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800756 Method* m = FromMethodId(methodId);
757 return MethodHelper(m).GetName();
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700758}
759
Elliott Hughesa2e54f62011-11-17 13:01:30 -0800760/*
761 * Augment the access flags for synthetic methods and fields by setting
762 * the (as described by the spec) "0xf0000000 bit". Also, strip out any
763 * flags not specified by the Java programming language.
764 */
765static uint32_t MangleAccessFlags(uint32_t accessFlags) {
766 accessFlags &= kAccJavaFlagsMask;
767 if ((accessFlags & kAccSynthetic) != 0) {
768 accessFlags |= 0xf0000000;
769 }
770 return accessFlags;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700771}
772
Elliott Hughesdbb40792011-11-18 17:05:22 -0800773static const uint16_t kEclipseWorkaroundSlot = 1000;
774
775/*
776 * Eclipse appears to expect that the "this" reference is in slot zero.
777 * If it's not, the "variables" display will show two copies of "this",
778 * possibly because it gets "this" from SF.ThisObject and then displays
779 * all locals with nonzero slot numbers.
780 *
781 * So, we remap the item in slot 0 to 1000, and remap "this" to zero. On
782 * SF.GetValues / SF.SetValues we map them back.
Elliott Hughesc5b734a2011-12-01 17:20:58 -0800783 *
784 * TODO: jdb uses the value to determine whether a variable is a local or an argument,
785 * by checking whether it's less than the number of arguments. To make that work, we'd
786 * have to "mangle" all the arguments to come first, not just the implicit argument 'this'.
Elliott Hughesdbb40792011-11-18 17:05:22 -0800787 */
788static uint16_t MangleSlot(uint16_t slot, const char* name) {
789 uint16_t newSlot = slot;
790 if (strcmp(name, "this") == 0) {
791 newSlot = 0;
792 } else if (slot == 0) {
793 newSlot = kEclipseWorkaroundSlot;
794 }
795 return newSlot;
796}
797
Elliott Hughes68fdbd02011-11-29 19:22:47 -0800798static uint16_t DemangleSlot(uint16_t slot, Frame& f) {
Elliott Hughesdbb40792011-11-18 17:05:22 -0800799 if (slot == kEclipseWorkaroundSlot) {
Elliott Hughes68fdbd02011-11-29 19:22:47 -0800800 return 0;
Elliott Hughesdbb40792011-11-18 17:05:22 -0800801 } else if (slot == 0) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800802 const DexFile::CodeItem* code_item = MethodHelper(f.GetMethod()).GetCodeItem();
803 return code_item->registers_size_ - code_item->ins_size_;
Elliott Hughesdbb40792011-11-18 17:05:22 -0800804 }
Elliott Hughes68fdbd02011-11-29 19:22:47 -0800805 return slot;
Elliott Hughesdbb40792011-11-18 17:05:22 -0800806}
807
Elliott Hughesc5b734a2011-12-01 17:20:58 -0800808void Dbg::OutputDeclaredFields(JDWP::RefTypeId refTypeId, bool with_generic, JDWP::ExpandBuf* pReply) {
Elliott Hughesa2e54f62011-11-17 13:01:30 -0800809 Class* c = gRegistry->Get<Class*>(refTypeId);
810 CHECK(c != NULL);
811
812 size_t instance_field_count = c->NumInstanceFields();
813 size_t static_field_count = c->NumStaticFields();
814
815 expandBufAdd4BE(pReply, instance_field_count + static_field_count);
816
817 for (size_t i = 0; i < instance_field_count + static_field_count; ++i) {
818 Field* f = (i < instance_field_count) ? c->GetInstanceField(i) : c->GetStaticField(i - instance_field_count);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800819 FieldHelper fh(f);
Elliott Hughesa2e54f62011-11-17 13:01:30 -0800820 expandBufAddFieldId(pReply, ToFieldId(f));
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800821 expandBufAddUtf8String(pReply, fh.GetName());
822 expandBufAddUtf8String(pReply, fh.GetTypeDescriptor());
Elliott Hughesc5b734a2011-12-01 17:20:58 -0800823 if (with_generic) {
Elliott Hughesa2e54f62011-11-17 13:01:30 -0800824 static const char genericSignature[1] = "";
825 expandBufAddUtf8String(pReply, genericSignature);
826 }
827 expandBufAdd4BE(pReply, MangleAccessFlags(f->GetAccessFlags()));
828 }
829}
830
Elliott Hughesc5b734a2011-12-01 17:20:58 -0800831void Dbg::OutputDeclaredMethods(JDWP::RefTypeId refTypeId, bool with_generic, JDWP::ExpandBuf* pReply) {
Elliott Hughesa2e54f62011-11-17 13:01:30 -0800832 Class* c = gRegistry->Get<Class*>(refTypeId);
833 CHECK(c != NULL);
834
835 size_t direct_method_count = c->NumDirectMethods();
836 size_t virtual_method_count = c->NumVirtualMethods();
837
838 expandBufAdd4BE(pReply, direct_method_count + virtual_method_count);
839
840 for (size_t i = 0; i < direct_method_count + virtual_method_count; ++i) {
841 Method* m = (i < direct_method_count) ? c->GetDirectMethod(i) : c->GetVirtualMethod(i - direct_method_count);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800842 MethodHelper mh(m);
Elliott Hughesa2e54f62011-11-17 13:01:30 -0800843 expandBufAddMethodId(pReply, ToMethodId(m));
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800844 expandBufAddUtf8String(pReply, mh.GetName());
845 expandBufAddUtf8String(pReply, mh.GetSignature().c_str());
Elliott Hughesc5b734a2011-12-01 17:20:58 -0800846 if (with_generic) {
Elliott Hughesa2e54f62011-11-17 13:01:30 -0800847 static const char genericSignature[1] = "";
848 expandBufAddUtf8String(pReply, genericSignature);
849 }
850 expandBufAdd4BE(pReply, MangleAccessFlags(m->GetAccessFlags()));
851 }
852}
853
854void Dbg::OutputDeclaredInterfaces(JDWP::RefTypeId refTypeId, JDWP::ExpandBuf* pReply) {
855 Class* c = gRegistry->Get<Class*>(refTypeId);
856 CHECK(c != NULL);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800857 ClassHelper kh(c);
858 size_t interface_count = kh.NumInterfaces();
Elliott Hughesa2e54f62011-11-17 13:01:30 -0800859 expandBufAdd4BE(pReply, interface_count);
860 for (size_t i = 0; i < interface_count; ++i) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800861 expandBufAddRefTypeId(pReply, gRegistry->Add(kh.GetInterface(i)));
Elliott Hughesa2e54f62011-11-17 13:01:30 -0800862 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700863}
864
865void Dbg::OutputLineTable(JDWP::RefTypeId refTypeId, JDWP::MethodId methodId, JDWP::ExpandBuf* pReply) {
Elliott Hughes03181a82011-11-17 17:22:21 -0800866 struct DebugCallbackContext {
867 int numItems;
868 JDWP::ExpandBuf* pReply;
869
870 static bool Callback(void* context, uint32_t address, uint32_t lineNum) {
871 DebugCallbackContext* pContext = reinterpret_cast<DebugCallbackContext*>(context);
872 expandBufAdd8BE(pContext->pReply, address);
873 expandBufAdd4BE(pContext->pReply, lineNum);
874 pContext->numItems++;
875 return true;
876 }
877 };
878
879 Method* m = FromMethodId(methodId);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800880 MethodHelper mh(m);
Elliott Hughes03181a82011-11-17 17:22:21 -0800881 uint64_t start, end;
882 if (m->IsNative()) {
883 start = -1;
884 end = -1;
885 } else {
886 start = 0;
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800887 // TODO: what are the units supposed to be? *2?
888 end = mh.GetCodeItem()->insns_size_in_code_units_;
Elliott Hughes03181a82011-11-17 17:22:21 -0800889 }
890
891 expandBufAdd8BE(pReply, start);
892 expandBufAdd8BE(pReply, end);
893
894 // Add numLines later
895 size_t numLinesOffset = expandBufGetLength(pReply);
896 expandBufAdd4BE(pReply, 0);
897
898 DebugCallbackContext context;
899 context.numItems = 0;
900 context.pReply = pReply;
901
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800902 mh.GetDexFile().DecodeDebugInfo(mh.GetCodeItem(), m->IsStatic(), m->GetDexMethodIndex(),
903 DebugCallbackContext::Callback, NULL, &context);
Elliott Hughes03181a82011-11-17 17:22:21 -0800904
905 JDWP::Set4BE(expandBufGetBuffer(pReply) + numLinesOffset, context.numItems);
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700906}
907
Elliott Hughesc5b734a2011-12-01 17:20:58 -0800908void Dbg::OutputVariableTable(JDWP::RefTypeId refTypeId, JDWP::MethodId methodId, bool with_generic, JDWP::ExpandBuf* pReply) {
Elliott Hughesdbb40792011-11-18 17:05:22 -0800909 struct DebugCallbackContext {
Elliott Hughesdbb40792011-11-18 17:05:22 -0800910 JDWP::ExpandBuf* pReply;
Elliott Hughesc5b734a2011-12-01 17:20:58 -0800911 size_t variable_count;
912 bool with_generic;
Elliott Hughesdbb40792011-11-18 17:05:22 -0800913
Elliott Hughesc5b734a2011-12-01 17:20:58 -0800914 static void Callback(void* context, uint16_t slot, uint32_t startAddress, uint32_t endAddress, const char* name, const char* descriptor, const char* signature) {
Elliott Hughesdbb40792011-11-18 17:05:22 -0800915 DebugCallbackContext* pContext = reinterpret_cast<DebugCallbackContext*>(context);
916
Elliott Hughesc5b734a2011-12-01 17:20:58 -0800917 LOG(VERBOSE) << StringPrintf(" %2d: %d(%d) '%s' '%s' '%s' slot=%d", pContext->variable_count, startAddress, endAddress - startAddress, name, descriptor, signature, slot);
Elliott Hughesdbb40792011-11-18 17:05:22 -0800918
Elliott Hughes68fdbd02011-11-29 19:22:47 -0800919 slot = MangleSlot(slot, name);
920
Elliott Hughesdbb40792011-11-18 17:05:22 -0800921 expandBufAdd8BE(pContext->pReply, startAddress);
922 expandBufAddUtf8String(pContext->pReply, name);
923 expandBufAddUtf8String(pContext->pReply, descriptor);
Elliott Hughesc5b734a2011-12-01 17:20:58 -0800924 if (pContext->with_generic) {
Elliott Hughesdbb40792011-11-18 17:05:22 -0800925 expandBufAddUtf8String(pContext->pReply, signature);
926 }
927 expandBufAdd4BE(pContext->pReply, endAddress - startAddress);
928 expandBufAdd4BE(pContext->pReply, slot);
929
Elliott Hughesc5b734a2011-12-01 17:20:58 -0800930 ++pContext->variable_count;
Elliott Hughesdbb40792011-11-18 17:05:22 -0800931 }
932 };
933
934 Method* m = FromMethodId(methodId);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800935 MethodHelper mh(m);
936 const DexFile::CodeItem* code_item = mh.GetCodeItem();
Elliott Hughesdbb40792011-11-18 17:05:22 -0800937
Elliott Hughesc5b734a2011-12-01 17:20:58 -0800938 // arg_count considers doubles and longs to take 2 units.
939 // variable_count considers everything to take 1 unit.
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800940 std::string shorty(mh.GetShorty());
Elliott Hughesc5b734a2011-12-01 17:20:58 -0800941 expandBufAdd4BE(pReply, m->NumArgRegisters(shorty));
Elliott Hughesdbb40792011-11-18 17:05:22 -0800942
Elliott Hughesc5b734a2011-12-01 17:20:58 -0800943 // We don't know the total number of variables yet, so leave a blank and update it later.
944 size_t variable_count_offset = expandBufGetLength(pReply);
Elliott Hughesdbb40792011-11-18 17:05:22 -0800945 expandBufAdd4BE(pReply, 0);
946
947 DebugCallbackContext context;
Elliott Hughesdbb40792011-11-18 17:05:22 -0800948 context.pReply = pReply;
Elliott Hughesc5b734a2011-12-01 17:20:58 -0800949 context.variable_count = 0;
950 context.with_generic = with_generic;
Elliott Hughesdbb40792011-11-18 17:05:22 -0800951
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800952 mh.GetDexFile().DecodeDebugInfo(code_item, m->IsStatic(), m->GetDexMethodIndex(), NULL,
953 DebugCallbackContext::Callback, &context);
Elliott Hughesdbb40792011-11-18 17:05:22 -0800954
Elliott Hughesc5b734a2011-12-01 17:20:58 -0800955 JDWP::Set4BE(expandBufGetBuffer(pReply) + variable_count_offset, context.variable_count);
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700956}
957
Elliott Hughesaed4be92011-12-02 16:16:23 -0800958JDWP::JdwpTag Dbg::GetFieldBasicTag(JDWP::FieldId fieldId) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800959 return BasicTagFromDescriptor(FieldHelper(FromFieldId(fieldId)).GetTypeDescriptor());
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700960}
961
Elliott Hughesaed4be92011-12-02 16:16:23 -0800962JDWP::JdwpTag Dbg::GetStaticFieldBasicTag(JDWP::FieldId fieldId) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800963 return BasicTagFromDescriptor(FieldHelper(FromFieldId(fieldId)).GetTypeDescriptor());
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700964}
965
966void Dbg::GetFieldValue(JDWP::ObjectId objectId, JDWP::FieldId fieldId, JDWP::ExpandBuf* pReply) {
Elliott Hughesaed4be92011-12-02 16:16:23 -0800967 Object* o = gRegistry->Get<Object*>(objectId);
968 Field* f = FromFieldId(fieldId);
969
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800970 JDWP::JdwpTag tag = BasicTagFromDescriptor(FieldHelper(f).GetTypeDescriptor());
Elliott Hughesaed4be92011-12-02 16:16:23 -0800971
972 if (IsPrimitiveTag(tag)) {
973 expandBufAdd1(pReply, tag);
974 if (tag == JDWP::JT_BOOLEAN || tag == JDWP::JT_BYTE) {
975 expandBufAdd1(pReply, f->Get32(o));
976 } else if (tag == JDWP::JT_CHAR || tag == JDWP::JT_SHORT) {
977 expandBufAdd2BE(pReply, f->Get32(o));
978 } else if (tag == JDWP::JT_FLOAT || tag == JDWP::JT_INT) {
979 expandBufAdd4BE(pReply, f->Get32(o));
980 } else if (tag == JDWP::JT_DOUBLE || tag == JDWP::JT_LONG) {
981 expandBufAdd8BE(pReply, f->Get64(o));
982 } else {
983 LOG(FATAL) << "unknown tag: " << tag;
984 }
985 } else {
986 Object* value = f->GetObject(o);
987 expandBufAdd1(pReply, TagFromObject(value));
988 expandBufAddObjectId(pReply, gRegistry->Add(value));
989 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700990}
991
992void Dbg::SetFieldValue(JDWP::ObjectId objectId, JDWP::FieldId fieldId, uint64_t value, int width) {
Elliott Hughesaed4be92011-12-02 16:16:23 -0800993 Object* o = gRegistry->Get<Object*>(objectId);
994 Field* f = FromFieldId(fieldId);
995
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800996 JDWP::JdwpTag tag = BasicTagFromDescriptor(FieldHelper(f).GetTypeDescriptor());
Elliott Hughesaed4be92011-12-02 16:16:23 -0800997
998 if (IsPrimitiveTag(tag)) {
999 if (tag == JDWP::JT_DOUBLE || tag == JDWP::JT_LONG) {
1000 f->Set64(o, value);
1001 } else {
1002 f->Set32(o, value);
1003 }
1004 } else {
1005 f->SetObject(o, gRegistry->Get<Object*>(value));
1006 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001007}
1008
Elliott Hughes6fa602d2011-12-02 17:54:25 -08001009void Dbg::GetStaticFieldValue(JDWP::FieldId fieldId, JDWP::ExpandBuf* pReply) {
1010 GetFieldValue(0, fieldId, pReply);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001011}
1012
Elliott Hughes6fa602d2011-12-02 17:54:25 -08001013void Dbg::SetStaticFieldValue(JDWP::FieldId fieldId, uint64_t value, int width) {
1014 SetFieldValue(0, fieldId, value, width);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001015}
1016
Elliott Hughes68fdbd02011-11-29 19:22:47 -08001017std::string Dbg::StringToUtf8(JDWP::ObjectId strId) {
1018 String* s = gRegistry->Get<String*>(strId);
1019 return s->ToModifiedUtf8();
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001020}
1021
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001022Thread* DecodeThread(JDWP::ObjectId threadId) {
1023 Object* thread_peer = gRegistry->Get<Object*>(threadId);
1024 CHECK(thread_peer != NULL);
1025 return Thread::FromManagedThread(thread_peer);
1026}
1027
1028bool Dbg::GetThreadName(JDWP::ObjectId threadId, std::string& name) {
1029 ScopedThreadListLock thread_list_lock;
1030 Thread* thread = DecodeThread(threadId);
1031 if (thread == NULL) {
1032 return false;
1033 }
1034 StringAppendF(&name, "<%d> %s", thread->GetThinLockId(), thread->GetName()->ToModifiedUtf8().c_str());
1035 return true;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001036}
1037
1038JDWP::ObjectId Dbg::GetThreadGroup(JDWP::ObjectId threadId) {
Elliott Hughes499c5132011-11-17 14:55:11 -08001039 Object* thread = gRegistry->Get<Object*>(threadId);
1040 CHECK(thread != NULL);
1041
1042 Class* c = Runtime::Current()->GetClassLinker()->FindSystemClass("Ljava/lang/Thread;");
1043 CHECK(c != NULL);
1044 Field* f = c->FindInstanceField("group", "Ljava/lang/ThreadGroup;");
1045 CHECK(f != NULL);
1046 Object* group = f->GetObject(thread);
1047 CHECK(group != NULL);
1048 return gRegistry->Add(group);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001049}
1050
Elliott Hughes499c5132011-11-17 14:55:11 -08001051std::string Dbg::GetThreadGroupName(JDWP::ObjectId threadGroupId) {
1052 Object* thread_group = gRegistry->Get<Object*>(threadGroupId);
1053 CHECK(thread_group != NULL);
1054
1055 Class* c = Runtime::Current()->GetClassLinker()->FindSystemClass("Ljava/lang/ThreadGroup;");
1056 CHECK(c != NULL);
1057 Field* f = c->FindInstanceField("name", "Ljava/lang/String;");
1058 CHECK(f != NULL);
1059 String* s = reinterpret_cast<String*>(f->GetObject(thread_group));
1060 return s->ToModifiedUtf8();
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001061}
1062
1063JDWP::ObjectId Dbg::GetThreadGroupParent(JDWP::ObjectId threadGroupId) {
Elliott Hughes4e235312011-12-02 11:34:15 -08001064 Object* thread_group = gRegistry->Get<Object*>(threadGroupId);
1065 CHECK(thread_group != NULL);
1066
1067 Class* c = Runtime::Current()->GetClassLinker()->FindSystemClass("Ljava/lang/ThreadGroup;");
1068 CHECK(c != NULL);
1069 Field* f = c->FindInstanceField("parent", "Ljava/lang/ThreadGroup;");
1070 CHECK(f != NULL);
1071 Object* parent = f->GetObject(thread_group);
1072 return gRegistry->Add(parent);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001073}
1074
Elliott Hughes499c5132011-11-17 14:55:11 -08001075static Object* GetStaticThreadGroup(const char* field_name) {
1076 Class* c = Runtime::Current()->GetClassLinker()->FindSystemClass("Ljava/lang/ThreadGroup;");
1077 CHECK(c != NULL);
1078 Field* f = c->FindStaticField(field_name, "Ljava/lang/ThreadGroup;");
1079 CHECK(f != NULL);
1080 Object* group = f->GetObject(NULL);
1081 CHECK(group != NULL);
1082 return group;
1083}
1084
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001085JDWP::ObjectId Dbg::GetSystemThreadGroupId() {
Elliott Hughes499c5132011-11-17 14:55:11 -08001086 return gRegistry->Add(GetStaticThreadGroup("mSystem"));
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001087}
1088
1089JDWP::ObjectId Dbg::GetMainThreadGroupId() {
Elliott Hughes499c5132011-11-17 14:55:11 -08001090 return gRegistry->Add(GetStaticThreadGroup("mMain"));
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001091}
1092
Elliott Hughes499c5132011-11-17 14:55:11 -08001093bool Dbg::GetThreadStatus(JDWP::ObjectId threadId, uint32_t* pThreadStatus, uint32_t* pSuspendStatus) {
1094 ScopedThreadListLock thread_list_lock;
1095
1096 Thread* thread = DecodeThread(threadId);
1097 if (thread == NULL) {
1098 return false;
1099 }
1100
1101 switch (thread->GetState()) {
1102 case Thread::kTerminated: *pThreadStatus = JDWP::TS_ZOMBIE; break;
1103 case Thread::kRunnable: *pThreadStatus = JDWP::TS_RUNNING; break;
1104 case Thread::kTimedWaiting: *pThreadStatus = JDWP::TS_SLEEPING; break;
1105 case Thread::kBlocked: *pThreadStatus = JDWP::TS_MONITOR; break;
1106 case Thread::kWaiting: *pThreadStatus = JDWP::TS_WAIT; break;
1107 case Thread::kInitializing: *pThreadStatus = JDWP::TS_ZOMBIE; break;
1108 case Thread::kStarting: *pThreadStatus = JDWP::TS_ZOMBIE; break;
1109 case Thread::kNative: *pThreadStatus = JDWP::TS_RUNNING; break;
1110 case Thread::kVmWait: *pThreadStatus = JDWP::TS_WAIT; break;
1111 case Thread::kSuspended: *pThreadStatus = JDWP::TS_RUNNING; break;
1112 default:
1113 LOG(FATAL) << "unknown thread state " << thread->GetState();
1114 }
1115
1116 *pSuspendStatus = (thread->IsSuspended() ? JDWP::SUSPEND_STATUS_SUSPENDED : 0);
1117
1118 return true;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001119}
1120
1121uint32_t Dbg::GetThreadSuspendCount(JDWP::ObjectId threadId) {
1122 UNIMPLEMENTED(FATAL);
1123 return 0;
1124}
1125
1126bool Dbg::ThreadExists(JDWP::ObjectId threadId) {
Elliott Hughes761928d2011-11-16 18:33:03 -08001127 return DecodeThread(threadId) != NULL;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001128}
1129
1130bool Dbg::IsSuspended(JDWP::ObjectId threadId) {
Elliott Hughes761928d2011-11-16 18:33:03 -08001131 return DecodeThread(threadId)->IsSuspended();
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001132}
1133
1134//void Dbg::WaitForSuspend(JDWP::ObjectId threadId);
1135
Elliott Hughesa2155262011-11-16 16:26:58 -08001136void Dbg::GetThreadGroupThreadsImpl(Object* thread_group, JDWP::ObjectId** ppThreadIds, uint32_t* pThreadCount) {
1137 struct ThreadListVisitor {
1138 static void Visit(Thread* t, void* arg) {
1139 reinterpret_cast<ThreadListVisitor*>(arg)->Visit(t);
1140 }
1141
1142 void Visit(Thread* t) {
1143 if (t == Dbg::GetDebugThread()) {
1144 // Skip the JDWP thread. Some debuggers get bent out of shape when they can't suspend and
1145 // query all threads, so it's easier if we just don't tell them about this thread.
1146 return;
1147 }
1148 if (thread_group == NULL || t->GetThreadGroup() == thread_group) {
1149 threads.push_back(gRegistry->Add(t->GetPeer()));
1150 }
1151 }
1152
1153 Object* thread_group;
1154 std::vector<JDWP::ObjectId> threads;
1155 };
1156
1157 ThreadListVisitor tlv;
1158 tlv.thread_group = thread_group;
1159
1160 {
1161 ScopedThreadListLock thread_list_lock;
1162 Runtime::Current()->GetThreadList()->ForEach(ThreadListVisitor::Visit, &tlv);
1163 }
1164
1165 *pThreadCount = tlv.threads.size();
1166 if (*pThreadCount == 0) {
1167 *ppThreadIds = NULL;
1168 } else {
1169 *ppThreadIds = new JDWP::ObjectId[*pThreadCount];
1170 for (size_t i = 0; i < *pThreadCount; ++i) {
1171 (*ppThreadIds)[i] = tlv.threads[i];
1172 }
1173 }
1174}
1175
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001176void Dbg::GetThreadGroupThreads(JDWP::ObjectId threadGroupId, JDWP::ObjectId** ppThreadIds, uint32_t* pThreadCount) {
Elliott Hughesa2155262011-11-16 16:26:58 -08001177 GetThreadGroupThreadsImpl(gRegistry->Get<Object*>(threadGroupId), ppThreadIds, pThreadCount);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001178}
1179
1180void Dbg::GetAllThreads(JDWP::ObjectId** ppThreadIds, uint32_t* pThreadCount) {
Elliott Hughesa2155262011-11-16 16:26:58 -08001181 GetThreadGroupThreadsImpl(NULL, ppThreadIds, pThreadCount);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001182}
1183
1184int Dbg::GetThreadFrameCount(JDWP::ObjectId threadId) {
Elliott Hughes03181a82011-11-17 17:22:21 -08001185 ScopedThreadListLock thread_list_lock;
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001186 struct CountStackDepthVisitor : public Thread::StackVisitor {
1187 CountStackDepthVisitor() : depth(0) {}
Elliott Hughesf8a2df72011-12-01 12:19:54 -08001188 virtual void VisitFrame(const Frame& f, uintptr_t) {
1189 // TODO: we'll need to skip callee-save frames too.
1190 if (f.HasMethod()) {
1191 ++depth;
1192 }
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001193 }
1194 size_t depth;
1195 };
1196 CountStackDepthVisitor visitor;
1197 DecodeThread(threadId)->WalkStack(&visitor);
1198 return visitor.depth;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001199}
1200
Elliott Hughes03181a82011-11-17 17:22:21 -08001201bool Dbg::GetThreadFrame(JDWP::ObjectId threadId, int desired_frame_number, JDWP::FrameId* pFrameId, JDWP::JdwpLocation* pLoc) {
1202 ScopedThreadListLock thread_list_lock;
1203 struct GetFrameVisitor : public Thread::StackVisitor {
1204 GetFrameVisitor(int desired_frame_number, JDWP::FrameId* pFrameId, JDWP::JdwpLocation* pLoc)
1205 : found(false) ,depth(0), desired_frame_number(desired_frame_number), pFrameId(pFrameId), pLoc(pLoc) {
1206 }
1207 virtual void VisitFrame(const Frame& f, uintptr_t pc) {
Elliott Hughesf8a2df72011-12-01 12:19:54 -08001208 // TODO: we'll need to skip callee-save frames too.
Elliott Hughes03181a82011-11-17 17:22:21 -08001209 if (!f.HasMethod()) {
Elliott Hughesf8a2df72011-12-01 12:19:54 -08001210 return; // The debugger can't do anything useful with a frame that has no Method*.
Elliott Hughes03181a82011-11-17 17:22:21 -08001211 }
1212
1213 if (depth == desired_frame_number) {
1214 *pFrameId = reinterpret_cast<JDWP::FrameId>(f.GetSP());
1215
1216 Method* m = f.GetMethod();
1217 Class* c = m->GetDeclaringClass();
1218
1219 pLoc->typeTag = c->IsInterface() ? JDWP::TT_INTERFACE : JDWP::TT_CLASS;
1220 pLoc->classId = gRegistry->Add(c);
1221 pLoc->methodId = ToMethodId(m);
1222 pLoc->idx = m->IsNative() ? -1 : m->ToDexPC(pc);
1223
1224 found = true;
1225 }
1226 ++depth;
1227 }
1228 bool found;
1229 int depth;
1230 int desired_frame_number;
1231 JDWP::FrameId* pFrameId;
1232 JDWP::JdwpLocation* pLoc;
1233 };
1234 GetFrameVisitor visitor(desired_frame_number, pFrameId, pLoc);
1235 visitor.desired_frame_number = desired_frame_number;
1236 DecodeThread(threadId)->WalkStack(&visitor);
1237 return visitor.found;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001238}
1239
1240JDWP::ObjectId Dbg::GetThreadSelfId() {
Elliott Hughes475fc232011-10-25 15:00:35 -07001241 return gRegistry->Add(Thread::Current()->GetPeer());
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001242}
1243
Elliott Hughes475fc232011-10-25 15:00:35 -07001244void Dbg::SuspendVM() {
Elliott Hughesa2155262011-11-16 16:26:58 -08001245 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 -07001246 Runtime::Current()->GetThreadList()->SuspendAll(true);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001247}
1248
1249void Dbg::ResumeVM() {
Elliott Hughes475fc232011-10-25 15:00:35 -07001250 Runtime::Current()->GetThreadList()->ResumeAll(true);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001251}
1252
1253void Dbg::SuspendThread(JDWP::ObjectId threadId) {
Elliott Hughes4e235312011-12-02 11:34:15 -08001254 Object* peer = gRegistry->Get<Object*>(threadId);
1255 ScopedThreadListLock thread_list_lock;
1256 Thread* thread = Thread::FromManagedThread(peer);
1257 if (thread == NULL) {
1258 LOG(WARNING) << "No such thread for suspend: " << peer;
1259 return;
1260 }
1261 Runtime::Current()->GetThreadList()->Suspend(thread, true);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001262}
1263
1264void Dbg::ResumeThread(JDWP::ObjectId threadId) {
Elliott Hughes4e235312011-12-02 11:34:15 -08001265 Object* peer = gRegistry->Get<Object*>(threadId);
1266 ScopedThreadListLock thread_list_lock;
1267 Thread* thread = Thread::FromManagedThread(peer);
1268 if (thread == NULL) {
1269 LOG(WARNING) << "No such thread for resume: " << peer;
1270 return;
1271 }
1272 Runtime::Current()->GetThreadList()->Resume(thread, true);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001273}
1274
1275void Dbg::SuspendSelf() {
Elliott Hughes475fc232011-10-25 15:00:35 -07001276 Runtime::Current()->GetThreadList()->SuspendSelfForDebugger();
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001277}
1278
1279bool Dbg::GetThisObject(JDWP::ObjectId threadId, JDWP::FrameId frameId, JDWP::ObjectId* pThisId) {
Elliott Hughes86b00102011-12-05 17:54:26 -08001280 Method** sp = reinterpret_cast<Method**>(frameId);
1281 Frame f;
1282 f.SetSP(sp);
1283 uint16_t reg = DemangleSlot(0, f);
1284 Method* m = f.GetMethod();
1285
1286 Object* o = NULL;
1287 if (!m->IsNative() && !m->IsStatic()) {
1288 o = reinterpret_cast<Object*>(f.GetVReg(m, reg));
1289 }
1290 *pThisId = gRegistry->Add(o);
1291 return true;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001292}
1293
Elliott Hughescccd84f2011-12-05 16:51:54 -08001294void Dbg::GetLocalValue(JDWP::ObjectId threadId, JDWP::FrameId frameId, int slot, JDWP::JdwpTag tag, uint8_t* buf, size_t width) {
Elliott Hughesdbb40792011-11-18 17:05:22 -08001295 Method** sp = reinterpret_cast<Method**>(frameId);
Elliott Hughes68fdbd02011-11-29 19:22:47 -08001296 Frame f;
1297 f.SetSP(sp);
1298 uint16_t reg = DemangleSlot(slot, f);
1299 Method* m = f.GetMethod();
1300
1301 const VmapTable vmap_table(m->GetVmapTableRaw());
1302 uint32_t vmap_offset;
1303 if (vmap_table.IsInContext(reg, vmap_offset)) {
1304 UNIMPLEMENTED(FATAL) << "don't know how to pull locals from callee save frames: " << vmap_offset;
1305 }
Elliott Hughesdbb40792011-11-18 17:05:22 -08001306
1307 switch (tag) {
1308 case JDWP::JT_BOOLEAN:
1309 {
Elliott Hughescccd84f2011-12-05 16:51:54 -08001310 CHECK_EQ(width, 1U);
Elliott Hughes1bba14f2011-12-01 18:00:36 -08001311 uint32_t intVal = f.GetVReg(m, reg);
1312 LOG(VERBOSE) << "get boolean local " << reg << " = " << intVal;
Elliott Hughesdbb40792011-11-18 17:05:22 -08001313 JDWP::Set1(buf+1, intVal != 0);
1314 }
1315 break;
1316 case JDWP::JT_BYTE:
1317 {
Elliott Hughescccd84f2011-12-05 16:51:54 -08001318 CHECK_EQ(width, 1U);
Elliott Hughes1bba14f2011-12-01 18:00:36 -08001319 uint32_t intVal = f.GetVReg(m, reg);
1320 LOG(VERBOSE) << "get byte local " << reg << " = " << intVal;
Elliott Hughesdbb40792011-11-18 17:05:22 -08001321 JDWP::Set1(buf+1, intVal);
1322 }
1323 break;
1324 case JDWP::JT_SHORT:
1325 case JDWP::JT_CHAR:
1326 {
Elliott Hughescccd84f2011-12-05 16:51:54 -08001327 CHECK_EQ(width, 2U);
Elliott Hughes1bba14f2011-12-01 18:00:36 -08001328 uint32_t intVal = f.GetVReg(m, reg);
1329 LOG(VERBOSE) << "get short/char local " << reg << " = " << intVal;
Elliott Hughesdbb40792011-11-18 17:05:22 -08001330 JDWP::Set2BE(buf+1, intVal);
1331 }
1332 break;
1333 case JDWP::JT_INT:
1334 case JDWP::JT_FLOAT:
1335 {
Elliott Hughescccd84f2011-12-05 16:51:54 -08001336 CHECK_EQ(width, 4U);
Elliott Hughes1bba14f2011-12-01 18:00:36 -08001337 uint32_t intVal = f.GetVReg(m, reg);
1338 LOG(VERBOSE) << "get int/float local " << reg << " = " << intVal;
Elliott Hughesdbb40792011-11-18 17:05:22 -08001339 JDWP::Set4BE(buf+1, intVal);
1340 }
1341 break;
1342 case JDWP::JT_ARRAY:
1343 {
Elliott Hughescccd84f2011-12-05 16:51:54 -08001344 CHECK_EQ(width, sizeof(JDWP::ObjectId));
Elliott Hughes68fdbd02011-11-29 19:22:47 -08001345 Object* o = reinterpret_cast<Object*>(f.GetVReg(m, reg));
Elliott Hughes1bba14f2011-12-01 18:00:36 -08001346 LOG(VERBOSE) << "get array local " << reg << " = " << o;
Elliott Hughesdbb40792011-11-18 17:05:22 -08001347 if (o != NULL && !Heap::IsHeapAddress(o)) {
Elliott Hughes68fdbd02011-11-29 19:22:47 -08001348 LOG(FATAL) << "reg " << reg << " expected to hold array: " << o;
Elliott Hughesdbb40792011-11-18 17:05:22 -08001349 }
1350 JDWP::SetObjectId(buf+1, gRegistry->Add(o));
1351 }
1352 break;
1353 case JDWP::JT_OBJECT:
1354 {
Elliott Hughescccd84f2011-12-05 16:51:54 -08001355 CHECK_EQ(width, sizeof(JDWP::ObjectId));
Elliott Hughes68fdbd02011-11-29 19:22:47 -08001356 Object* o = reinterpret_cast<Object*>(f.GetVReg(m, reg));
Elliott Hughes1bba14f2011-12-01 18:00:36 -08001357 LOG(VERBOSE) << "get object local " << reg << " = " << o;
Elliott Hughesdbb40792011-11-18 17:05:22 -08001358 if (o != NULL && !Heap::IsHeapAddress(o)) {
Elliott Hughes68fdbd02011-11-29 19:22:47 -08001359 LOG(FATAL) << "reg " << reg << " expected to hold object: " << o;
Elliott Hughesdbb40792011-11-18 17:05:22 -08001360 }
1361 tag = TagFromObject(o);
1362 JDWP::SetObjectId(buf+1, gRegistry->Add(o));
1363 }
1364 break;
1365 case JDWP::JT_DOUBLE:
1366 case JDWP::JT_LONG:
1367 {
Elliott Hughescccd84f2011-12-05 16:51:54 -08001368 CHECK_EQ(width, 8U);
Elliott Hughes1bba14f2011-12-01 18:00:36 -08001369 uint32_t lo = f.GetVReg(m, reg);
1370 uint64_t hi = f.GetVReg(m, reg + 1);
1371 uint64_t longVal = (hi << 32) | lo;
1372 LOG(VERBOSE) << "get double/long local " << hi << ":" << lo << " = " << longVal;
Elliott Hughesdbb40792011-11-18 17:05:22 -08001373 JDWP::Set8BE(buf+1, longVal);
1374 }
1375 break;
1376 default:
1377 LOG(FATAL) << "unknown tag " << tag;
1378 break;
1379 }
1380
1381 // Prepend tag, which may have been updated.
1382 JDWP::Set1(buf, tag);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001383}
1384
Elliott Hughesdbb40792011-11-18 17:05:22 -08001385void Dbg::SetLocalValue(JDWP::ObjectId threadId, JDWP::FrameId frameId, int slot, JDWP::JdwpTag tag, uint64_t value, size_t width) {
Elliott Hughescccd84f2011-12-05 16:51:54 -08001386 Method** sp = reinterpret_cast<Method**>(frameId);
1387 Frame f;
1388 f.SetSP(sp);
1389 uint16_t reg = DemangleSlot(slot, f);
1390 Method* m = f.GetMethod();
1391
1392 const VmapTable vmap_table(m->GetVmapTableRaw());
1393 uint32_t vmap_offset;
1394 if (vmap_table.IsInContext(reg, vmap_offset)) {
1395 UNIMPLEMENTED(FATAL) << "don't know how to pull locals from callee save frames: " << vmap_offset;
1396 }
1397
1398 switch (tag) {
1399 case JDWP::JT_BOOLEAN:
1400 case JDWP::JT_BYTE:
1401 CHECK_EQ(width, 1U);
1402 f.SetVReg(m, reg, static_cast<uint32_t>(value));
1403 break;
1404 case JDWP::JT_SHORT:
1405 case JDWP::JT_CHAR:
1406 CHECK_EQ(width, 2U);
1407 f.SetVReg(m, reg, static_cast<uint32_t>(value));
1408 break;
1409 case JDWP::JT_INT:
1410 case JDWP::JT_FLOAT:
1411 CHECK_EQ(width, 4U);
1412 f.SetVReg(m, reg, static_cast<uint32_t>(value));
1413 break;
1414 case JDWP::JT_ARRAY:
1415 case JDWP::JT_OBJECT:
1416 case JDWP::JT_STRING:
1417 {
1418 CHECK_EQ(width, sizeof(JDWP::ObjectId));
1419 Object* o = gRegistry->Get<Object*>(static_cast<JDWP::ObjectId>(value));
1420 f.SetVReg(m, reg, static_cast<uint32_t>(reinterpret_cast<uintptr_t>(o)));
1421 }
1422 break;
1423 case JDWP::JT_DOUBLE:
1424 case JDWP::JT_LONG:
1425 CHECK_EQ(width, 8U);
1426 f.SetVReg(m, reg, static_cast<uint32_t>(value));
1427 f.SetVReg(m, reg + 1, static_cast<uint32_t>(value >> 32));
1428 break;
1429 default:
1430 LOG(FATAL) << "unknown tag " << tag;
1431 break;
1432 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001433}
1434
1435void Dbg::PostLocationEvent(const Method* method, int pcOffset, Object* thisPtr, int eventFlags) {
1436 UNIMPLEMENTED(FATAL);
1437}
1438
1439void Dbg::PostException(void* throwFp, int throwRelPc, void* catchFp, int catchRelPc, Object* exception) {
1440 UNIMPLEMENTED(FATAL);
1441}
1442
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001443void Dbg::PostClassPrepare(Class* c) {
1444 UNIMPLEMENTED(FATAL);
1445}
1446
1447bool Dbg::WatchLocation(const JDWP::JdwpLocation* pLoc) {
1448 UNIMPLEMENTED(FATAL);
1449 return false;
1450}
1451
1452void Dbg::UnwatchLocation(const JDWP::JdwpLocation* pLoc) {
1453 UNIMPLEMENTED(FATAL);
1454}
1455
1456bool Dbg::ConfigureStep(JDWP::ObjectId threadId, JDWP::JdwpStepSize size, JDWP::JdwpStepDepth depth) {
1457 UNIMPLEMENTED(FATAL);
1458 return false;
1459}
1460
1461void Dbg::UnconfigureStep(JDWP::ObjectId threadId) {
1462 UNIMPLEMENTED(FATAL);
1463}
1464
Elliott Hughesaed4be92011-12-02 16:16:23 -08001465JDWP::JdwpError Dbg::InvokeMethod(JDWP::ObjectId threadId, JDWP::ObjectId objectId, JDWP::RefTypeId classId, JDWP::MethodId methodId, uint32_t numArgs, uint64_t* argArray, uint32_t options, JDWP::JdwpTag* pResultTag, uint64_t* pResultValue, JDWP::ObjectId* pExceptObj) {
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001466 UNIMPLEMENTED(FATAL);
1467 return JDWP::ERR_NONE;
1468}
1469
1470void Dbg::ExecuteMethod(DebugInvokeReq* pReq) {
1471 UNIMPLEMENTED(FATAL);
1472}
1473
1474void Dbg::RegisterObjectId(JDWP::ObjectId id) {
1475 UNIMPLEMENTED(FATAL);
1476}
1477
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07001478/*
1479 * "buf" contains a full JDWP packet, possibly with multiple chunks. We
1480 * need to process each, accumulate the replies, and ship the whole thing
1481 * back.
1482 *
1483 * Returns "true" if we have a reply. The reply buffer is newly allocated,
1484 * and includes the chunk type/length, followed by the data.
1485 *
1486 * TODO: we currently assume that the request and reply include a single
1487 * chunk. If this becomes inconvenient we will need to adapt.
1488 */
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001489bool Dbg::DdmHandlePacket(const uint8_t* buf, int dataLen, uint8_t** pReplyBuf, int* pReplyLen) {
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07001490 CHECK_GE(dataLen, 0);
1491
1492 Thread* self = Thread::Current();
1493 JNIEnv* env = self->GetJniEnv();
1494
1495 static jclass Chunk_class = env->FindClass("org/apache/harmony/dalvik/ddmc/Chunk");
1496 static jclass DdmServer_class = env->FindClass("org/apache/harmony/dalvik/ddmc/DdmServer");
1497 static jmethodID dispatch_mid = env->GetStaticMethodID(DdmServer_class, "dispatch",
1498 "(I[BII)Lorg/apache/harmony/dalvik/ddmc/Chunk;");
1499 static jfieldID data_fid = env->GetFieldID(Chunk_class, "data", "[B");
1500 static jfieldID length_fid = env->GetFieldID(Chunk_class, "length", "I");
1501 static jfieldID offset_fid = env->GetFieldID(Chunk_class, "offset", "I");
1502 static jfieldID type_fid = env->GetFieldID(Chunk_class, "type", "I");
1503
1504 // Create a byte[] corresponding to 'buf'.
Elliott Hughes6a5bd492011-10-28 14:33:57 -07001505 ScopedLocalRef<jbyteArray> dataArray(env, env->NewByteArray(dataLen));
1506 if (dataArray.get() == NULL) {
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07001507 LOG(WARNING) << "byte[] allocation failed: " << dataLen;
1508 env->ExceptionClear();
1509 return false;
1510 }
Elliott Hughes6a5bd492011-10-28 14:33:57 -07001511 env->SetByteArrayRegion(dataArray.get(), 0, dataLen, reinterpret_cast<const jbyte*>(buf));
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07001512
1513 const int kChunkHdrLen = 8;
1514
1515 // Run through and find all chunks. [Currently just find the first.]
Elliott Hughes6a5bd492011-10-28 14:33:57 -07001516 ScopedByteArrayRO contents(env, dataArray.get());
Elliott Hughesf7c3b662011-10-27 12:04:56 -07001517 jint type = JDWP::Get4BE(reinterpret_cast<const uint8_t*>(&contents[0]));
1518 jint length = JDWP::Get4BE(reinterpret_cast<const uint8_t*>(&contents[4]));
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07001519 jint offset = kChunkHdrLen;
1520 if (offset + length > dataLen) {
1521 LOG(WARNING) << StringPrintf("bad chunk found (len=%u pktLen=%d)", length, dataLen);
1522 return false;
1523 }
1524
1525 // Call "private static Chunk dispatch(int type, byte[] data, int offset, int length)".
Elliott Hughes6a5bd492011-10-28 14:33:57 -07001526 ScopedLocalRef<jobject> chunk(env, env->CallStaticObjectMethod(DdmServer_class, dispatch_mid, type, dataArray.get(), offset, length));
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07001527 if (env->ExceptionCheck()) {
1528 LOG(INFO) << StringPrintf("Exception thrown by dispatcher for 0x%08x", type);
1529 env->ExceptionDescribe();
1530 env->ExceptionClear();
1531 return false;
1532 }
1533
Elliott Hughes6a5bd492011-10-28 14:33:57 -07001534 if (chunk.get() == NULL) {
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07001535 return false;
1536 }
1537
1538 /*
1539 * Pull the pieces out of the chunk. We copy the results into a
1540 * newly-allocated buffer that the caller can free. We don't want to
1541 * continue using the Chunk object because nothing has a reference to it.
1542 *
1543 * We could avoid this by returning type/data/offset/length and having
1544 * the caller be aware of the object lifetime issues, but that
1545 * integrates the JDWP code more tightly into the VM, and doesn't work
1546 * if we have responses for multiple chunks.
1547 *
1548 * So we're pretty much stuck with copying data around multiple times.
1549 */
Elliott Hughes6a5bd492011-10-28 14:33:57 -07001550 ScopedLocalRef<jbyteArray> replyData(env, reinterpret_cast<jbyteArray>(env->GetObjectField(chunk.get(), data_fid)));
1551 length = env->GetIntField(chunk.get(), length_fid);
1552 offset = env->GetIntField(chunk.get(), offset_fid);
1553 type = env->GetIntField(chunk.get(), type_fid);
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07001554
Elliott Hughes6a5bd492011-10-28 14:33:57 -07001555 LOG(VERBOSE) << StringPrintf("DDM reply: type=0x%08x data=%p offset=%d length=%d", type, replyData.get(), offset, length);
1556 if (length == 0 || replyData.get() == NULL) {
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07001557 return false;
1558 }
1559
Elliott Hughes6a5bd492011-10-28 14:33:57 -07001560 jsize replyLength = env->GetArrayLength(replyData.get());
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07001561 if (offset + length > replyLength) {
1562 LOG(WARNING) << StringPrintf("chunk off=%d len=%d exceeds reply array len %d", offset, length, replyLength);
1563 return false;
1564 }
1565
1566 uint8_t* reply = new uint8_t[length + kChunkHdrLen];
1567 if (reply == NULL) {
1568 LOG(WARNING) << "malloc failed: " << (length + kChunkHdrLen);
1569 return false;
1570 }
Elliott Hughesf7c3b662011-10-27 12:04:56 -07001571 JDWP::Set4BE(reply + 0, type);
1572 JDWP::Set4BE(reply + 4, length);
Elliott Hughes6a5bd492011-10-28 14:33:57 -07001573 env->GetByteArrayRegion(replyData.get(), offset, length, reinterpret_cast<jbyte*>(reply + kChunkHdrLen));
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07001574
1575 *pReplyBuf = reply;
1576 *pReplyLen = length + kChunkHdrLen;
1577
1578 LOG(VERBOSE) << StringPrintf("dvmHandleDdm returning type=%.4s buf=%p len=%d", (char*) reply, reply, length);
1579 return true;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001580}
1581
Elliott Hughesa2155262011-11-16 16:26:58 -08001582void Dbg::DdmBroadcast(bool connect) {
Elliott Hughes47fce012011-10-25 18:37:19 -07001583 LOG(VERBOSE) << "Broadcasting DDM " << (connect ? "connect" : "disconnect") << "...";
1584
1585 Thread* self = Thread::Current();
1586 if (self->GetState() != Thread::kRunnable) {
1587 LOG(ERROR) << "DDM broadcast in thread state " << self->GetState();
1588 /* try anyway? */
1589 }
1590
1591 JNIEnv* env = self->GetJniEnv();
1592 static jclass DdmServer_class = env->FindClass("org/apache/harmony/dalvik/ddmc/DdmServer");
1593 static jmethodID broadcast_mid = env->GetStaticMethodID(DdmServer_class, "broadcast", "(I)V");
1594 jint event = connect ? 1 /*DdmServer.CONNECTED*/ : 2 /*DdmServer.DISCONNECTED*/;
1595 env->CallStaticVoidMethod(DdmServer_class, broadcast_mid, event);
1596 if (env->ExceptionCheck()) {
1597 LOG(ERROR) << "DdmServer.broadcast " << event << " failed";
1598 env->ExceptionDescribe();
1599 env->ExceptionClear();
1600 }
1601}
1602
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001603void Dbg::DdmConnected() {
Elliott Hughesa2155262011-11-16 16:26:58 -08001604 Dbg::DdmBroadcast(true);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001605}
1606
1607void Dbg::DdmDisconnected() {
Elliott Hughesa2155262011-11-16 16:26:58 -08001608 Dbg::DdmBroadcast(false);
Elliott Hughes47fce012011-10-25 18:37:19 -07001609 gDdmThreadNotification = false;
1610}
1611
1612/*
Elliott Hughes82188472011-11-07 18:11:48 -08001613 * Send a notification when a thread starts, stops, or changes its name.
Elliott Hughes47fce012011-10-25 18:37:19 -07001614 *
1615 * Because we broadcast the full set of threads when the notifications are
1616 * first enabled, it's possible for "thread" to be actively executing.
1617 */
Elliott Hughes82188472011-11-07 18:11:48 -08001618void Dbg::DdmSendThreadNotification(Thread* t, uint32_t type) {
Elliott Hughes47fce012011-10-25 18:37:19 -07001619 if (!gDdmThreadNotification) {
1620 return;
1621 }
1622
Elliott Hughes82188472011-11-07 18:11:48 -08001623 if (type == CHUNK_TYPE("THDE")) {
Elliott Hughes47fce012011-10-25 18:37:19 -07001624 uint8_t buf[4];
Elliott Hughesf7c3b662011-10-27 12:04:56 -07001625 JDWP::Set4BE(&buf[0], t->GetThinLockId());
Elliott Hughes47fce012011-10-25 18:37:19 -07001626 Dbg::DdmSendChunk(CHUNK_TYPE("THDE"), 4, buf);
Elliott Hughes82188472011-11-07 18:11:48 -08001627 } else {
1628 CHECK(type == CHUNK_TYPE("THCR") || type == CHUNK_TYPE("THNM")) << type;
1629 SirtRef<String> name(t->GetName());
1630 size_t char_count = (name.get() != NULL) ? name->GetLength() : 0;
1631 const jchar* chars = name->GetCharArray()->GetData();
1632
Elliott Hughes21f32d72011-11-09 17:44:13 -08001633 std::vector<uint8_t> bytes;
Elliott Hughes545a0642011-11-08 19:10:03 -08001634 JDWP::Append4BE(bytes, t->GetThinLockId());
1635 JDWP::AppendUtf16BE(bytes, chars, char_count);
Elliott Hughes21f32d72011-11-09 17:44:13 -08001636 CHECK_EQ(bytes.size(), char_count*2 + sizeof(uint32_t)*2);
1637 Dbg::DdmSendChunk(type, bytes);
Elliott Hughes47fce012011-10-25 18:37:19 -07001638 }
1639}
1640
Elliott Hughesa2155262011-11-16 16:26:58 -08001641static void DdmSendThreadStartCallback(Thread* t, void*) {
Elliott Hughes82188472011-11-07 18:11:48 -08001642 Dbg::DdmSendThreadNotification(t, CHUNK_TYPE("THCR"));
Elliott Hughes47fce012011-10-25 18:37:19 -07001643}
1644
1645void Dbg::DdmSetThreadNotification(bool enable) {
1646 // We lock the thread list to avoid sending duplicate events or missing
1647 // a thread change. We should be okay holding this lock while sending
1648 // the messages out. (We have to hold it while accessing a live thread.)
Elliott Hughesbbd9d832011-11-07 14:40:00 -08001649 ScopedThreadListLock thread_list_lock;
Elliott Hughes47fce012011-10-25 18:37:19 -07001650
1651 gDdmThreadNotification = enable;
1652 if (enable) {
Elliott Hughesbfe487b2011-10-26 15:48:55 -07001653 Runtime::Current()->GetThreadList()->ForEach(DdmSendThreadStartCallback, NULL);
Elliott Hughes47fce012011-10-25 18:37:19 -07001654 }
1655}
1656
Elliott Hughesa2155262011-11-16 16:26:58 -08001657void Dbg::PostThreadStartOrStop(Thread* t, uint32_t type) {
Elliott Hughes47fce012011-10-25 18:37:19 -07001658 if (gDebuggerActive) {
1659 JDWP::ObjectId id = gRegistry->Add(t->GetPeer());
Elliott Hughes82188472011-11-07 18:11:48 -08001660 gJdwpState->PostThreadChange(id, type == CHUNK_TYPE("THCR"));
Elliott Hughes47fce012011-10-25 18:37:19 -07001661 }
Elliott Hughes82188472011-11-07 18:11:48 -08001662 Dbg::DdmSendThreadNotification(t, type);
Elliott Hughes47fce012011-10-25 18:37:19 -07001663}
1664
1665void Dbg::PostThreadStart(Thread* t) {
Elliott Hughesa2155262011-11-16 16:26:58 -08001666 Dbg::PostThreadStartOrStop(t, CHUNK_TYPE("THCR"));
Elliott Hughes47fce012011-10-25 18:37:19 -07001667}
1668
1669void Dbg::PostThreadDeath(Thread* t) {
Elliott Hughesa2155262011-11-16 16:26:58 -08001670 Dbg::PostThreadStartOrStop(t, CHUNK_TYPE("THDE"));
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001671}
1672
Elliott Hughes82188472011-11-07 18:11:48 -08001673void Dbg::DdmSendChunk(uint32_t type, size_t byte_count, const uint8_t* buf) {
Elliott Hughes3bb81562011-10-21 18:52:59 -07001674 CHECK(buf != NULL);
1675 iovec vec[1];
1676 vec[0].iov_base = reinterpret_cast<void*>(const_cast<uint8_t*>(buf));
1677 vec[0].iov_len = byte_count;
1678 Dbg::DdmSendChunkV(type, vec, 1);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001679}
1680
Elliott Hughes21f32d72011-11-09 17:44:13 -08001681void Dbg::DdmSendChunk(uint32_t type, const std::vector<uint8_t>& bytes) {
1682 DdmSendChunk(type, bytes.size(), &bytes[0]);
1683}
1684
Elliott Hughescccd84f2011-12-05 16:51:54 -08001685void Dbg::DdmSendChunkV(uint32_t type, const struct iovec* iov, int iov_count) {
Elliott Hughes3bb81562011-10-21 18:52:59 -07001686 if (gJdwpState == NULL) {
1687 LOG(VERBOSE) << "Debugger thread not active, ignoring DDM send: " << type;
1688 } else {
Elliott Hughescccd84f2011-12-05 16:51:54 -08001689 gJdwpState->DdmSendChunkV(type, iov, iov_count);
Elliott Hughes3bb81562011-10-21 18:52:59 -07001690 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001691}
1692
Elliott Hughes767a1472011-10-26 18:49:02 -07001693int Dbg::DdmHandleHpifChunk(HpifWhen when) {
1694 if (when == HPIF_WHEN_NOW) {
Elliott Hughes7162ad92011-10-27 14:08:42 -07001695 DdmSendHeapInfo(when);
Elliott Hughes767a1472011-10-26 18:49:02 -07001696 return true;
1697 }
1698
1699 if (when != HPIF_WHEN_NEVER && when != HPIF_WHEN_NEXT_GC && when != HPIF_WHEN_EVERY_GC) {
1700 LOG(ERROR) << "invalid HpifWhen value: " << static_cast<int>(when);
1701 return false;
1702 }
1703
1704 gDdmHpifWhen = when;
1705 return true;
1706}
1707
1708bool Dbg::DdmHandleHpsgNhsgChunk(Dbg::HpsgWhen when, Dbg::HpsgWhat what, bool native) {
1709 if (when != HPSG_WHEN_NEVER && when != HPSG_WHEN_EVERY_GC) {
1710 LOG(ERROR) << "invalid HpsgWhen value: " << static_cast<int>(when);
1711 return false;
1712 }
1713
1714 if (what != HPSG_WHAT_MERGED_OBJECTS && what != HPSG_WHAT_DISTINCT_OBJECTS) {
1715 LOG(ERROR) << "invalid HpsgWhat value: " << static_cast<int>(what);
1716 return false;
1717 }
1718
1719 if (native) {
1720 gDdmNhsgWhen = when;
1721 gDdmNhsgWhat = what;
1722 } else {
1723 gDdmHpsgWhen = when;
1724 gDdmHpsgWhat = what;
1725 }
1726 return true;
1727}
1728
Elliott Hughes7162ad92011-10-27 14:08:42 -07001729void Dbg::DdmSendHeapInfo(HpifWhen reason) {
1730 // If there's a one-shot 'when', reset it.
1731 if (reason == gDdmHpifWhen) {
1732 if (gDdmHpifWhen == HPIF_WHEN_NEXT_GC) {
1733 gDdmHpifWhen = HPIF_WHEN_NEVER;
1734 }
1735 }
1736
1737 /*
1738 * Chunk HPIF (client --> server)
1739 *
1740 * Heap Info. General information about the heap,
1741 * suitable for a summary display.
1742 *
1743 * [u4]: number of heaps
1744 *
1745 * For each heap:
1746 * [u4]: heap ID
1747 * [u8]: timestamp in ms since Unix epoch
1748 * [u1]: capture reason (same as 'when' value from server)
1749 * [u4]: max heap size in bytes (-Xmx)
1750 * [u4]: current heap size in bytes
1751 * [u4]: current number of bytes allocated
1752 * [u4]: current number of objects allocated
1753 */
1754 uint8_t heap_count = 1;
Elliott Hughes21f32d72011-11-09 17:44:13 -08001755 std::vector<uint8_t> bytes;
Elliott Hughes545a0642011-11-08 19:10:03 -08001756 JDWP::Append4BE(bytes, heap_count);
1757 JDWP::Append4BE(bytes, 1); // Heap id (bogus; we only have one heap).
1758 JDWP::Append8BE(bytes, MilliTime());
1759 JDWP::Append1BE(bytes, reason);
1760 JDWP::Append4BE(bytes, Heap::GetMaxMemory()); // Max allowed heap size in bytes.
1761 JDWP::Append4BE(bytes, Heap::GetTotalMemory()); // Current heap size in bytes.
1762 JDWP::Append4BE(bytes, Heap::GetBytesAllocated());
1763 JDWP::Append4BE(bytes, Heap::GetObjectsAllocated());
Elliott Hughes21f32d72011-11-09 17:44:13 -08001764 CHECK_EQ(bytes.size(), 4U + (heap_count * (4 + 8 + 1 + 4 + 4 + 4 + 4)));
1765 Dbg::DdmSendChunk(CHUNK_TYPE("HPIF"), bytes);
Elliott Hughes767a1472011-10-26 18:49:02 -07001766}
1767
Elliott Hughes6a5bd492011-10-28 14:33:57 -07001768enum HpsgSolidity {
1769 SOLIDITY_FREE = 0,
1770 SOLIDITY_HARD = 1,
1771 SOLIDITY_SOFT = 2,
1772 SOLIDITY_WEAK = 3,
1773 SOLIDITY_PHANTOM = 4,
1774 SOLIDITY_FINALIZABLE = 5,
1775 SOLIDITY_SWEEP = 6,
1776};
1777
1778enum HpsgKind {
1779 KIND_OBJECT = 0,
1780 KIND_CLASS_OBJECT = 1,
1781 KIND_ARRAY_1 = 2,
1782 KIND_ARRAY_2 = 3,
1783 KIND_ARRAY_4 = 4,
1784 KIND_ARRAY_8 = 5,
1785 KIND_UNKNOWN = 6,
1786 KIND_NATIVE = 7,
1787};
1788
1789#define HPSG_PARTIAL (1<<7)
1790#define HPSG_STATE(solidity, kind) ((uint8_t)((((kind) & 0x7) << 3) | ((solidity) & 0x7)))
1791
1792struct HeapChunkContext {
1793 std::vector<uint8_t> buf;
1794 uint8_t* p;
1795 uint8_t* pieceLenField;
1796 size_t totalAllocationUnits;
Elliott Hughes82188472011-11-07 18:11:48 -08001797 uint32_t type;
Elliott Hughes6a5bd492011-10-28 14:33:57 -07001798 bool merge;
1799 bool needHeader;
1800
1801 // Maximum chunk size. Obtain this from the formula:
1802 // (((maximum_heap_size / ALLOCATION_UNIT_SIZE) + 255) / 256) * 2
1803 HeapChunkContext(bool merge, bool native)
1804 : buf(16384 - 16),
1805 type(0),
1806 merge(merge) {
1807 Reset();
1808 if (native) {
1809 type = CHUNK_TYPE("NHSG");
1810 } else {
1811 type = merge ? CHUNK_TYPE("HPSG") : CHUNK_TYPE("HPSO");
1812 }
1813 }
1814
1815 ~HeapChunkContext() {
1816 if (p > &buf[0]) {
1817 Flush();
1818 }
1819 }
1820
1821 void EnsureHeader(const void* chunk_ptr) {
1822 if (!needHeader) {
1823 return;
1824 }
1825
1826 // Start a new HPSx chunk.
1827 JDWP::Write4BE(&p, 1); // Heap id (bogus; we only have one heap).
1828 JDWP::Write1BE(&p, 8); // Size of allocation unit, in bytes.
1829
1830 JDWP::Write4BE(&p, reinterpret_cast<uintptr_t>(chunk_ptr)); // virtual address of segment start.
1831 JDWP::Write4BE(&p, 0); // offset of this piece (relative to the virtual address).
1832 // [u4]: length of piece, in allocation units
1833 // We won't know this until we're done, so save the offset and stuff in a dummy value.
1834 pieceLenField = p;
1835 JDWP::Write4BE(&p, 0x55555555);
1836 needHeader = false;
1837 }
1838
1839 void Flush() {
1840 // Patch the "length of piece" field.
1841 CHECK_LE(&buf[0], pieceLenField);
1842 CHECK_LE(pieceLenField, p);
1843 JDWP::Set4BE(pieceLenField, totalAllocationUnits);
1844
1845 Dbg::DdmSendChunk(type, p - &buf[0], &buf[0]);
1846 Reset();
1847 }
1848
Elliott Hughesa2155262011-11-16 16:26:58 -08001849 static void HeapChunkCallback(const void* chunk_ptr, size_t chunk_len, const void* user_ptr, size_t user_len, void* arg) {
1850 reinterpret_cast<HeapChunkContext*>(arg)->HeapChunkCallback(chunk_ptr, chunk_len, user_ptr, user_len);
1851 }
1852
Elliott Hughes6a5bd492011-10-28 14:33:57 -07001853 private:
Elliott Hughesa2155262011-11-16 16:26:58 -08001854 enum { ALLOCATION_UNIT_SIZE = 8 };
1855
Elliott Hughes6a5bd492011-10-28 14:33:57 -07001856 void Reset() {
1857 p = &buf[0];
1858 totalAllocationUnits = 0;
1859 needHeader = true;
1860 pieceLenField = NULL;
1861 }
1862
Elliott Hughesa2155262011-11-16 16:26:58 -08001863 void HeapChunkCallback(const void* chunk_ptr, size_t chunk_len, const void* user_ptr, size_t user_len) {
1864 CHECK_EQ((chunk_len & (ALLOCATION_UNIT_SIZE-1)), 0U);
Elliott Hughes6a5bd492011-10-28 14:33:57 -07001865
Elliott Hughesa2155262011-11-16 16:26:58 -08001866 /* Make sure there's enough room left in the buffer.
1867 * We need to use two bytes for every fractional 256
1868 * allocation units used by the chunk.
1869 */
1870 {
1871 size_t needed = (((chunk_len/ALLOCATION_UNIT_SIZE + 255) / 256) * 2);
1872 size_t bytesLeft = buf.size() - (size_t)(p - &buf[0]);
1873 if (bytesLeft < needed) {
1874 Flush();
1875 }
Elliott Hughes6a5bd492011-10-28 14:33:57 -07001876
Elliott Hughesa2155262011-11-16 16:26:58 -08001877 bytesLeft = buf.size() - (size_t)(p - &buf[0]);
1878 if (bytesLeft < needed) {
1879 LOG(WARNING) << "chunk is too big to transmit (chunk_len=" << chunk_len << ", " << needed << " bytes)";
1880 return;
1881 }
1882 }
1883
1884 // OLD-TODO: notice when there's a gap and start a new heap, or at least a new range.
1885 EnsureHeader(chunk_ptr);
1886
1887 // Determine the type of this chunk.
1888 // OLD-TODO: if context.merge, see if this chunk is different from the last chunk.
1889 // If it's the same, we should combine them.
1890 uint8_t state = ExamineObject(reinterpret_cast<const Object*>(user_ptr), (type == CHUNK_TYPE("NHSG")));
1891
1892 // Write out the chunk description.
1893 chunk_len /= ALLOCATION_UNIT_SIZE; // convert to allocation units
1894 totalAllocationUnits += chunk_len;
1895 while (chunk_len > 256) {
1896 *p++ = state | HPSG_PARTIAL;
1897 *p++ = 255; // length - 1
1898 chunk_len -= 256;
1899 }
1900 *p++ = state;
1901 *p++ = chunk_len - 1;
Elliott Hughes6a5bd492011-10-28 14:33:57 -07001902 }
1903
Elliott Hughesa2155262011-11-16 16:26:58 -08001904 uint8_t ExamineObject(const Object* o, bool is_native_heap) {
1905 if (o == NULL) {
1906 return HPSG_STATE(SOLIDITY_FREE, 0);
1907 }
Elliott Hughes6a5bd492011-10-28 14:33:57 -07001908
Elliott Hughesa2155262011-11-16 16:26:58 -08001909 // It's an allocated chunk. Figure out what it is.
Elliott Hughes6a5bd492011-10-28 14:33:57 -07001910
Elliott Hughesa2155262011-11-16 16:26:58 -08001911 // If we're looking at the native heap, we'll just return
1912 // (SOLIDITY_HARD, KIND_NATIVE) for all allocated chunks.
1913 if (is_native_heap || !Heap::IsLiveObjectLocked(o)) {
1914 return HPSG_STATE(SOLIDITY_HARD, KIND_NATIVE);
1915 }
1916
1917 Class* c = o->GetClass();
1918 if (c == NULL) {
1919 // The object was probably just created but hasn't been initialized yet.
1920 return HPSG_STATE(SOLIDITY_HARD, KIND_OBJECT);
1921 }
1922
1923 if (!Heap::IsHeapAddress(c)) {
1924 LOG(WARNING) << "invalid class for managed heap object: " << o << " " << c;
1925 return HPSG_STATE(SOLIDITY_HARD, KIND_UNKNOWN);
1926 }
1927
1928 if (c->IsClassClass()) {
1929 return HPSG_STATE(SOLIDITY_HARD, KIND_CLASS_OBJECT);
1930 }
1931
1932 if (c->IsArrayClass()) {
1933 if (o->IsObjectArray()) {
1934 return HPSG_STATE(SOLIDITY_HARD, KIND_ARRAY_4);
1935 }
1936 switch (c->GetComponentSize()) {
1937 case 1: return HPSG_STATE(SOLIDITY_HARD, KIND_ARRAY_1);
1938 case 2: return HPSG_STATE(SOLIDITY_HARD, KIND_ARRAY_2);
1939 case 4: return HPSG_STATE(SOLIDITY_HARD, KIND_ARRAY_4);
1940 case 8: return HPSG_STATE(SOLIDITY_HARD, KIND_ARRAY_8);
1941 }
1942 }
1943
Elliott Hughes6a5bd492011-10-28 14:33:57 -07001944 return HPSG_STATE(SOLIDITY_HARD, KIND_OBJECT);
1945 }
1946
Elliott Hughesa2155262011-11-16 16:26:58 -08001947 DISALLOW_COPY_AND_ASSIGN(HeapChunkContext);
1948};
Elliott Hughes6a5bd492011-10-28 14:33:57 -07001949
1950void Dbg::DdmSendHeapSegments(bool native) {
1951 Dbg::HpsgWhen when;
1952 Dbg::HpsgWhat what;
1953 if (!native) {
1954 when = gDdmHpsgWhen;
1955 what = gDdmHpsgWhat;
1956 } else {
1957 when = gDdmNhsgWhen;
1958 what = gDdmNhsgWhat;
1959 }
1960 if (when == HPSG_WHEN_NEVER) {
1961 return;
1962 }
1963
1964 // Figure out what kind of chunks we'll be sending.
1965 CHECK(what == HPSG_WHAT_MERGED_OBJECTS || what == HPSG_WHAT_DISTINCT_OBJECTS) << static_cast<int>(what);
1966
1967 // First, send a heap start chunk.
1968 uint8_t heap_id[4];
1969 JDWP::Set4BE(&heap_id[0], 1); // Heap id (bogus; we only have one heap).
1970 Dbg::DdmSendChunk(native ? CHUNK_TYPE("NHST") : CHUNK_TYPE("HPST"), sizeof(heap_id), heap_id);
1971
1972 // Send a series of heap segment chunks.
Elliott Hughesa2155262011-11-16 16:26:58 -08001973 HeapChunkContext context((what == HPSG_WHAT_MERGED_OBJECTS), native);
1974 if (native) {
1975 dlmalloc_walk_heap(HeapChunkContext::HeapChunkCallback, &context);
1976 } else {
1977 Heap::WalkHeap(HeapChunkContext::HeapChunkCallback, &context);
1978 }
Elliott Hughes6a5bd492011-10-28 14:33:57 -07001979
1980 // Finally, send a heap end chunk.
1981 Dbg::DdmSendChunk(native ? CHUNK_TYPE("NHEN") : CHUNK_TYPE("HPEN"), sizeof(heap_id), heap_id);
Elliott Hughes767a1472011-10-26 18:49:02 -07001982}
1983
Elliott Hughes545a0642011-11-08 19:10:03 -08001984void Dbg::SetAllocTrackingEnabled(bool enabled) {
1985 MutexLock mu(gAllocTrackerLock);
1986 if (enabled) {
1987 if (recent_allocation_records_ == NULL) {
1988 LOG(INFO) << "Enabling alloc tracker (" << kNumAllocRecords << " entries, "
1989 << kMaxAllocRecordStackDepth << " frames --> "
1990 << (sizeof(AllocRecord) * kNumAllocRecords) << " bytes)";
1991 gAllocRecordHead = gAllocRecordCount = 0;
1992 recent_allocation_records_ = new AllocRecord[kNumAllocRecords];
1993 CHECK(recent_allocation_records_ != NULL);
1994 }
1995 } else {
1996 delete[] recent_allocation_records_;
1997 recent_allocation_records_ = NULL;
1998 }
1999}
2000
2001struct AllocRecordStackVisitor : public Thread::StackVisitor {
2002 AllocRecordStackVisitor(AllocRecord* record) : record(record), depth(0) {
2003 }
2004
2005 virtual void VisitFrame(const Frame& f, uintptr_t pc) {
2006 if (depth >= kMaxAllocRecordStackDepth) {
2007 return;
2008 }
2009 Method* m = f.GetMethod();
2010 if (m == NULL || m->IsCalleeSaveMethod()) {
2011 return;
2012 }
2013 record->stack[depth].method = m;
2014 record->stack[depth].raw_pc = pc;
2015 ++depth;
2016 }
2017
2018 ~AllocRecordStackVisitor() {
2019 // Clear out any unused stack trace elements.
2020 for (; depth < kMaxAllocRecordStackDepth; ++depth) {
2021 record->stack[depth].method = NULL;
2022 record->stack[depth].raw_pc = 0;
2023 }
2024 }
2025
2026 AllocRecord* record;
2027 size_t depth;
2028};
2029
2030void Dbg::RecordAllocation(Class* type, size_t byte_count) {
2031 Thread* self = Thread::Current();
2032 CHECK(self != NULL);
2033
2034 MutexLock mu(gAllocTrackerLock);
2035 if (recent_allocation_records_ == NULL) {
2036 return;
2037 }
2038
2039 // Advance and clip.
2040 if (++gAllocRecordHead == kNumAllocRecords) {
2041 gAllocRecordHead = 0;
2042 }
2043
2044 // Fill in the basics.
2045 AllocRecord* record = &recent_allocation_records_[gAllocRecordHead];
2046 record->type = type;
2047 record->byte_count = byte_count;
2048 record->thin_lock_id = self->GetThinLockId();
2049
2050 // Fill in the stack trace.
2051 AllocRecordStackVisitor visitor(record);
2052 self->WalkStack(&visitor);
2053
2054 if (gAllocRecordCount < kNumAllocRecords) {
2055 ++gAllocRecordCount;
2056 }
2057}
2058
2059/*
2060 * Return the index of the head element.
2061 *
2062 * We point at the most-recently-written record, so if allocRecordCount is 1
2063 * we want to use the current element. Take "head+1" and subtract count
2064 * from it.
2065 *
2066 * We need to handle underflow in our circular buffer, so we add
2067 * kNumAllocRecords and then mask it back down.
2068 */
2069inline static int headIndex() {
2070 return (gAllocRecordHead+1 + kNumAllocRecords - gAllocRecordCount) & (kNumAllocRecords-1);
2071}
2072
2073void Dbg::DumpRecentAllocations() {
2074 MutexLock mu(gAllocTrackerLock);
2075 if (recent_allocation_records_ == NULL) {
2076 LOG(INFO) << "Not recording tracked allocations";
2077 return;
2078 }
2079
2080 // "i" is the head of the list. We want to start at the end of the
2081 // list and move forward to the tail.
2082 size_t i = headIndex();
2083 size_t count = gAllocRecordCount;
2084
2085 LOG(INFO) << "Tracked allocations, (head=" << gAllocRecordHead << " count=" << count << ")";
2086 while (count--) {
2087 AllocRecord* record = &recent_allocation_records_[i];
2088
2089 LOG(INFO) << StringPrintf(" T=%-2d %6d ", record->thin_lock_id, record->byte_count)
2090 << PrettyClass(record->type);
2091
2092 for (size_t stack_frame = 0; stack_frame < kMaxAllocRecordStackDepth; ++stack_frame) {
2093 const Method* m = record->stack[stack_frame].method;
2094 if (m == NULL) {
2095 break;
2096 }
2097 LOG(INFO) << " " << PrettyMethod(m) << " line " << record->stack[stack_frame].LineNumber();
2098 }
2099
2100 // pause periodically to help logcat catch up
2101 if ((count % 5) == 0) {
2102 usleep(40000);
2103 }
2104
2105 i = (i + 1) & (kNumAllocRecords-1);
2106 }
2107}
2108
2109class StringTable {
2110 public:
2111 StringTable() {
2112 }
2113
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002114 void Add(const char* s) {
Elliott Hughes545a0642011-11-08 19:10:03 -08002115 table_.insert(s);
2116 }
2117
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002118 size_t IndexOf(const char* s) {
Elliott Hughes545a0642011-11-08 19:10:03 -08002119 return std::distance(table_.begin(), table_.find(s));
2120 }
2121
2122 size_t Size() {
2123 return table_.size();
2124 }
2125
2126 void WriteTo(std::vector<uint8_t>& bytes) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002127 typedef std::set<const char*>::const_iterator It; // TODO: C++0x auto
Elliott Hughes545a0642011-11-08 19:10:03 -08002128 for (It it = table_.begin(); it != table_.end(); ++it) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002129 const char* s = *it;
2130 size_t s_len = CountModifiedUtf8Chars(s);
2131 UniquePtr<uint16_t> s_utf16(new uint16_t[s_len]);
2132 ConvertModifiedUtf8ToUtf16(s_utf16.get(), s);
2133 JDWP::AppendUtf16BE(bytes, s_utf16.get(), s_len);
Elliott Hughes545a0642011-11-08 19:10:03 -08002134 }
2135 }
2136
2137 private:
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002138 std::set<const char*> table_;
Elliott Hughes545a0642011-11-08 19:10:03 -08002139 DISALLOW_COPY_AND_ASSIGN(StringTable);
2140};
2141
2142/*
2143 * The data we send to DDMS contains everything we have recorded.
2144 *
2145 * Message header (all values big-endian):
2146 * (1b) message header len (to allow future expansion); includes itself
2147 * (1b) entry header len
2148 * (1b) stack frame len
2149 * (2b) number of entries
2150 * (4b) offset to string table from start of message
2151 * (2b) number of class name strings
2152 * (2b) number of method name strings
2153 * (2b) number of source file name strings
2154 * For each entry:
2155 * (4b) total allocation size
2156 * (2b) threadId
2157 * (2b) allocated object's class name index
2158 * (1b) stack depth
2159 * For each stack frame:
2160 * (2b) method's class name
2161 * (2b) method name
2162 * (2b) method source file
2163 * (2b) line number, clipped to 32767; -2 if native; -1 if no source
2164 * (xb) class name strings
2165 * (xb) method name strings
2166 * (xb) source file strings
2167 *
2168 * As with other DDM traffic, strings are sent as a 4-byte length
2169 * followed by UTF-16 data.
2170 *
2171 * We send up 16-bit unsigned indexes into string tables. In theory there
2172 * can be (kMaxAllocRecordStackDepth * kNumAllocRecords) unique strings in
2173 * each table, but in practice there should be far fewer.
2174 *
2175 * The chief reason for using a string table here is to keep the size of
2176 * the DDMS message to a minimum. This is partly to make the protocol
2177 * efficient, but also because we have to form the whole thing up all at
2178 * once in a memory buffer.
2179 *
2180 * We use separate string tables for class names, method names, and source
2181 * files to keep the indexes small. There will generally be no overlap
2182 * between the contents of these tables.
2183 */
2184jbyteArray Dbg::GetRecentAllocations() {
2185 if (false) {
2186 DumpRecentAllocations();
2187 }
2188
2189 MutexLock mu(gAllocTrackerLock);
2190
2191 /*
2192 * Part 1: generate string tables.
2193 */
2194 StringTable class_names;
2195 StringTable method_names;
2196 StringTable filenames;
2197
2198 int count = gAllocRecordCount;
2199 int idx = headIndex();
2200 while (count--) {
2201 AllocRecord* record = &recent_allocation_records_[idx];
2202
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002203 class_names.Add(ClassHelper(record->type).GetDescriptor().c_str());
Elliott Hughes545a0642011-11-08 19:10:03 -08002204
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002205 MethodHelper mh;
Elliott Hughes545a0642011-11-08 19:10:03 -08002206 for (size_t i = 0; i < kMaxAllocRecordStackDepth; i++) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002207 Method* m = record->stack[i].method;
2208 mh.ChangeMethod(m);
Elliott Hughes545a0642011-11-08 19:10:03 -08002209 if (m != NULL) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002210 class_names.Add(mh.GetDeclaringClassDescriptor());
2211 method_names.Add(mh.GetName());
2212 filenames.Add(mh.GetDeclaringClassSourceFile());
Elliott Hughes545a0642011-11-08 19:10:03 -08002213 }
2214 }
2215
2216 idx = (idx + 1) & (kNumAllocRecords-1);
2217 }
2218
2219 LOG(INFO) << "allocation records: " << gAllocRecordCount;
2220
2221 /*
2222 * Part 2: allocate a buffer and generate the output.
2223 */
2224 std::vector<uint8_t> bytes;
2225
2226 // (1b) message header len (to allow future expansion); includes itself
2227 // (1b) entry header len
2228 // (1b) stack frame len
2229 const int kMessageHeaderLen = 15;
2230 const int kEntryHeaderLen = 9;
2231 const int kStackFrameLen = 8;
2232 JDWP::Append1BE(bytes, kMessageHeaderLen);
2233 JDWP::Append1BE(bytes, kEntryHeaderLen);
2234 JDWP::Append1BE(bytes, kStackFrameLen);
2235
2236 // (2b) number of entries
2237 // (4b) offset to string table from start of message
2238 // (2b) number of class name strings
2239 // (2b) number of method name strings
2240 // (2b) number of source file name strings
2241 JDWP::Append2BE(bytes, gAllocRecordCount);
2242 size_t string_table_offset = bytes.size();
2243 JDWP::Append4BE(bytes, 0); // We'll patch this later...
2244 JDWP::Append2BE(bytes, class_names.Size());
2245 JDWP::Append2BE(bytes, method_names.Size());
2246 JDWP::Append2BE(bytes, filenames.Size());
2247
2248 count = gAllocRecordCount;
2249 idx = headIndex();
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002250 ClassHelper kh;
Elliott Hughes545a0642011-11-08 19:10:03 -08002251 while (count--) {
2252 // For each entry:
2253 // (4b) total allocation size
2254 // (2b) thread id
2255 // (2b) allocated object's class name index
2256 // (1b) stack depth
2257 AllocRecord* record = &recent_allocation_records_[idx];
2258 size_t stack_depth = record->GetDepth();
2259 JDWP::Append4BE(bytes, record->byte_count);
2260 JDWP::Append2BE(bytes, record->thin_lock_id);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002261 kh.ChangeClass(record->type);
2262 JDWP::Append2BE(bytes, class_names.IndexOf(kh.GetDescriptor().c_str()));
Elliott Hughes545a0642011-11-08 19:10:03 -08002263 JDWP::Append1BE(bytes, stack_depth);
2264
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002265 MethodHelper mh;
Elliott Hughes545a0642011-11-08 19:10:03 -08002266 for (size_t stack_frame = 0; stack_frame < stack_depth; ++stack_frame) {
2267 // For each stack frame:
2268 // (2b) method's class name
2269 // (2b) method name
2270 // (2b) method source file
2271 // (2b) line number, clipped to 32767; -2 if native; -1 if no source
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002272 mh.ChangeMethod(record->stack[stack_frame].method);
2273 JDWP::Append2BE(bytes, class_names.IndexOf(mh.GetDeclaringClassDescriptor()));
2274 JDWP::Append2BE(bytes, method_names.IndexOf(mh.GetName()));
2275 JDWP::Append2BE(bytes, filenames.IndexOf(mh.GetDeclaringClassSourceFile()));
Elliott Hughes545a0642011-11-08 19:10:03 -08002276 JDWP::Append2BE(bytes, record->stack[stack_frame].LineNumber());
2277 }
2278
2279 idx = (idx + 1) & (kNumAllocRecords-1);
2280 }
2281
2282 // (xb) class name strings
2283 // (xb) method name strings
2284 // (xb) source file strings
2285 JDWP::Set4BE(&bytes[string_table_offset], bytes.size());
2286 class_names.WriteTo(bytes);
2287 method_names.WriteTo(bytes);
2288 filenames.WriteTo(bytes);
2289
2290 JNIEnv* env = Thread::Current()->GetJniEnv();
2291 jbyteArray result = env->NewByteArray(bytes.size());
2292 if (result != NULL) {
2293 env->SetByteArrayRegion(result, 0, bytes.size(), reinterpret_cast<const jbyte*>(&bytes[0]));
2294 }
2295 return result;
2296}
2297
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002298} // namespace art