blob: 8c28cd9b7b106cbb7ea698f1267ed0f5a799c942 [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 Hughes86964332012-02-15 19:37:42 -080025#include "dex_verifier.h" // For Instruction.
Elliott Hughes68fdbd02011-11-29 19:22:47 -080026#include "context.h"
Ian Rogers6d4d9fc2011-11-30 16:24:48 -080027#include "object_utils.h"
Elliott Hughes6a5bd492011-10-28 14:33:57 -070028#include "ScopedLocalRef.h"
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -070029#include "ScopedPrimitiveArray.h"
Ian Rogers30fab402012-01-23 15:43:46 -080030#include "space.h"
Elliott Hughes47fce012011-10-25 18:37:19 -070031#include "stack_indirect_reference_table.h"
Elliott Hughes475fc232011-10-25 15:00:35 -070032#include "thread_list.h"
33
Elliott Hughes6a5bd492011-10-28 14:33:57 -070034extern "C" void dlmalloc_walk_heap(void(*)(const void*, size_t, const void*, size_t, void*), void*);
35#ifndef HAVE_ANDROID_OS
36void dlmalloc_walk_heap(void(*)(const void*, size_t, const void*, size_t, void*), void*) {
37 // No-op for glibc.
38}
39#endif
40
Elliott Hughes872d4ec2011-10-21 17:07:15 -070041namespace art {
42
Elliott Hughes545a0642011-11-08 19:10:03 -080043static const size_t kMaxAllocRecordStackDepth = 16; // Max 255.
44static const size_t kNumAllocRecords = 512; // Must be power of 2.
45
Elliott Hughes475fc232011-10-25 15:00:35 -070046class ObjectRegistry {
47 public:
48 ObjectRegistry() : lock_("ObjectRegistry lock") {
49 }
50
51 JDWP::ObjectId Add(Object* o) {
52 if (o == NULL) {
53 return 0;
54 }
55 JDWP::ObjectId id = static_cast<JDWP::ObjectId>(reinterpret_cast<uintptr_t>(o));
56 MutexLock mu(lock_);
57 map_[id] = o;
58 return id;
59 }
60
Elliott Hughes234ab152011-10-26 14:02:26 -070061 void Clear() {
62 MutexLock mu(lock_);
63 LOG(DEBUG) << "Debugger has detached; object registry had " << map_.size() << " entries";
64 map_.clear();
65 }
66
Elliott Hughes475fc232011-10-25 15:00:35 -070067 bool Contains(JDWP::ObjectId id) {
68 MutexLock mu(lock_);
69 return map_.find(id) != map_.end();
70 }
71
Elliott Hughesa2155262011-11-16 16:26:58 -080072 template<typename T> T Get(JDWP::ObjectId id) {
73 MutexLock mu(lock_);
74 typedef std::map<JDWP::ObjectId, Object*>::iterator It; // C++0x auto
75 It it = map_.find(id);
76 return (it != map_.end()) ? reinterpret_cast<T>(it->second) : NULL;
77 }
78
Elliott Hughesbfe487b2011-10-26 15:48:55 -070079 void VisitRoots(Heap::RootVisitor* visitor, void* arg) {
80 MutexLock mu(lock_);
81 typedef std::map<JDWP::ObjectId, Object*>::iterator It; // C++0x auto
82 for (It it = map_.begin(); it != map_.end(); ++it) {
83 visitor(it->second, arg);
84 }
85 }
86
Elliott Hughes475fc232011-10-25 15:00:35 -070087 private:
88 Mutex lock_;
89 std::map<JDWP::ObjectId, Object*> map_;
90};
91
Elliott Hughes545a0642011-11-08 19:10:03 -080092struct AllocRecordStackTraceElement {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -080093 Method* method;
Elliott Hughes545a0642011-11-08 19:10:03 -080094 uintptr_t raw_pc;
95
96 int32_t LineNumber() const {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -080097 return MethodHelper(method).GetLineNumFromNativePC(raw_pc);
Elliott Hughes545a0642011-11-08 19:10:03 -080098 }
99};
100
101struct AllocRecord {
102 Class* type;
103 size_t byte_count;
104 uint16_t thin_lock_id;
105 AllocRecordStackTraceElement stack[kMaxAllocRecordStackDepth]; // Unused entries have NULL method.
106
107 size_t GetDepth() {
108 size_t depth = 0;
109 while (depth < kMaxAllocRecordStackDepth && stack[depth].method != NULL) {
110 ++depth;
111 }
112 return depth;
113 }
114};
115
Elliott Hughes86964332012-02-15 19:37:42 -0800116struct Breakpoint {
117 Method* method;
118 uint32_t pc;
119 Breakpoint(Method* method, uint32_t pc) : method(method), pc(pc) {}
120};
121
122static std::ostream& operator<<(std::ostream& os, const Breakpoint& rhs) {
123 os << "Breakpoint[" << PrettyMethod(rhs.method) << " @" << rhs.pc << "]";
124 return os;
125}
126
127struct SingleStepControl {
128 // Are we single-stepping right now?
129 bool is_active;
130 Thread* thread;
131
132 JDWP::JdwpStepSize step_size;
133 JDWP::JdwpStepDepth step_depth;
134
135 const Method* method;
Elliott Hughes2435a572012-02-17 16:07:41 -0800136 int32_t line_number; // Or -1 for native methods.
137 std::set<uint32_t> dex_pcs;
Elliott Hughes86964332012-02-15 19:37:42 -0800138 int stack_depth;
139};
140
Elliott Hughes4ffd3132011-10-24 12:06:42 -0700141// JDWP is allowed unless the Zygote forbids it.
142static bool gJdwpAllowed = true;
143
Elliott Hughes3bb81562011-10-21 18:52:59 -0700144// Was there a -Xrunjdwp or -agent argument on the command-line?
145static bool gJdwpConfigured = false;
146
147// Broken-down JDWP options. (Only valid if gJdwpConfigured is true.)
Elliott Hughes376a7a02011-10-24 18:35:55 -0700148static JDWP::JdwpOptions gJdwpOptions;
Elliott Hughes3bb81562011-10-21 18:52:59 -0700149
150// Runtime JDWP state.
151static JDWP::JdwpState* gJdwpState = NULL;
152static bool gDebuggerConnected; // debugger or DDMS is connected.
153static bool gDebuggerActive; // debugger is making requests.
Elliott Hughes86964332012-02-15 19:37:42 -0800154static bool gDisposed; // debugger called VirtualMachine.Dispose, so we should drop the connection.
Elliott Hughes3bb81562011-10-21 18:52:59 -0700155
Elliott Hughes47fce012011-10-25 18:37:19 -0700156static bool gDdmThreadNotification = false;
157
Elliott Hughes767a1472011-10-26 18:49:02 -0700158// DDMS GC-related settings.
159static Dbg::HpifWhen gDdmHpifWhen = Dbg::HPIF_WHEN_NEVER;
160static Dbg::HpsgWhen gDdmHpsgWhen = Dbg::HPSG_WHEN_NEVER;
161static Dbg::HpsgWhat gDdmHpsgWhat;
162static Dbg::HpsgWhen gDdmNhsgWhen = Dbg::HPSG_WHEN_NEVER;
163static Dbg::HpsgWhat gDdmNhsgWhat;
164
Elliott Hughes475fc232011-10-25 15:00:35 -0700165static ObjectRegistry* gRegistry = NULL;
166
Elliott Hughes545a0642011-11-08 19:10:03 -0800167// Recent allocation tracking.
168static Mutex gAllocTrackerLock("AllocTracker lock");
169AllocRecord* Dbg::recent_allocation_records_ = NULL; // TODO: CircularBuffer<AllocRecord>
170static size_t gAllocRecordHead = 0;
171static size_t gAllocRecordCount = 0;
172
Elliott Hughes86964332012-02-15 19:37:42 -0800173// Breakpoints and single-stepping.
174static Mutex gBreakpointsLock("breakpoints lock");
175static std::vector<Breakpoint> gBreakpoints;
176static SingleStepControl gSingleStepControl;
177
178static bool IsBreakpoint(Method* m, uint32_t dex_pc) {
179 MutexLock mu(gBreakpointsLock);
Elliott Hughes2aa2e392012-02-17 17:15:43 -0800180 uint32_t pc = dex_pc / 2; // dex bytecodes are twice the size JDWP expects.
Elliott Hughes86964332012-02-15 19:37:42 -0800181 for (size_t i = 0; i < gBreakpoints.size(); ++i) {
Elliott Hughes2aa2e392012-02-17 17:15:43 -0800182 if (gBreakpoints[i].method == m && gBreakpoints[i].pc == pc) {
Elliott Hughes86964332012-02-15 19:37:42 -0800183 VLOG(jdwp) << "Hit breakpoint #" << i << ": " << gBreakpoints[i];
184 return true;
185 }
186 }
187 return false;
188}
189
Elliott Hughes24437992011-11-30 14:49:33 -0800190static JDWP::JdwpTag BasicTagFromDescriptor(const char* descriptor) {
191 // JDWP deliberately uses the descriptor characters' ASCII values for its enum.
192 // Note that by "basic" we mean that we don't get more specific than JT_OBJECT.
193 return static_cast<JDWP::JdwpTag>(descriptor[0]);
194}
195
196static JDWP::JdwpTag TagFromClass(Class* c) {
Elliott Hughes86b00102011-12-05 17:54:26 -0800197 CHECK(c != NULL);
Elliott Hughes24437992011-11-30 14:49:33 -0800198 if (c->IsArrayClass()) {
199 return JDWP::JT_ARRAY;
200 }
201
Elliott Hughes3d30d9b2011-12-07 17:35:48 -0800202 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
Elliott Hughes24437992011-11-30 14:49:33 -0800203 if (c->IsStringClass()) {
204 return JDWP::JT_STRING;
205 } else if (c->IsClassClass()) {
206 return JDWP::JT_CLASS_OBJECT;
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -0800207 } else if (class_linker->FindSystemClass("Ljava/lang/Thread;")->IsAssignableFrom(c)) {
Elliott Hughes24437992011-11-30 14:49:33 -0800208 return JDWP::JT_THREAD;
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -0800209 } else if (class_linker->FindSystemClass("Ljava/lang/ThreadGroup;")->IsAssignableFrom(c)) {
Elliott Hughes24437992011-11-30 14:49:33 -0800210 return JDWP::JT_THREAD_GROUP;
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -0800211 } else if (class_linker->FindSystemClass("Ljava/lang/ClassLoader;")->IsAssignableFrom(c)) {
Elliott Hughes24437992011-11-30 14:49:33 -0800212 return JDWP::JT_CLASS_LOADER;
Elliott Hughes24437992011-11-30 14:49:33 -0800213 } else {
214 return JDWP::JT_OBJECT;
215 }
216}
217
218/*
219 * Objects declared to hold Object might actually hold a more specific
220 * type. The debugger may take a special interest in these (e.g. it
221 * wants to display the contents of Strings), so we want to return an
222 * appropriate tag.
223 *
224 * Null objects are tagged JT_OBJECT.
225 */
226static JDWP::JdwpTag TagFromObject(const Object* o) {
227 return (o == NULL) ? JDWP::JT_OBJECT : TagFromClass(o->GetClass());
228}
229
230static bool IsPrimitiveTag(JDWP::JdwpTag tag) {
231 switch (tag) {
232 case JDWP::JT_BOOLEAN:
233 case JDWP::JT_BYTE:
234 case JDWP::JT_CHAR:
235 case JDWP::JT_FLOAT:
236 case JDWP::JT_DOUBLE:
237 case JDWP::JT_INT:
238 case JDWP::JT_LONG:
239 case JDWP::JT_SHORT:
240 case JDWP::JT_VOID:
241 return true;
242 default:
243 return false;
244 }
245}
246
Elliott Hughes3bb81562011-10-21 18:52:59 -0700247/*
248 * Handle one of the JDWP name/value pairs.
249 *
250 * JDWP options are:
251 * help: if specified, show help message and bail
252 * transport: may be dt_socket or dt_shmem
253 * address: for dt_socket, "host:port", or just "port" when listening
254 * server: if "y", wait for debugger to attach; if "n", attach to debugger
255 * timeout: how long to wait for debugger to connect / listen
256 *
257 * Useful with server=n (these aren't supported yet):
258 * onthrow=<exception-name>: connect to debugger when exception thrown
259 * onuncaught=y|n: connect to debugger when uncaught exception thrown
260 * launch=<command-line>: launch the debugger itself
261 *
262 * The "transport" option is required, as is "address" if server=n.
263 */
264static bool ParseJdwpOption(const std::string& name, const std::string& value) {
265 if (name == "transport") {
266 if (value == "dt_socket") {
Elliott Hughes376a7a02011-10-24 18:35:55 -0700267 gJdwpOptions.transport = JDWP::kJdwpTransportSocket;
Elliott Hughes3bb81562011-10-21 18:52:59 -0700268 } else if (value == "dt_android_adb") {
Elliott Hughes376a7a02011-10-24 18:35:55 -0700269 gJdwpOptions.transport = JDWP::kJdwpTransportAndroidAdb;
Elliott Hughes3bb81562011-10-21 18:52:59 -0700270 } else {
271 LOG(ERROR) << "JDWP transport not supported: " << value;
272 return false;
273 }
274 } else if (name == "server") {
275 if (value == "n") {
Elliott Hughes376a7a02011-10-24 18:35:55 -0700276 gJdwpOptions.server = false;
Elliott Hughes3bb81562011-10-21 18:52:59 -0700277 } else if (value == "y") {
Elliott Hughes376a7a02011-10-24 18:35:55 -0700278 gJdwpOptions.server = true;
Elliott Hughes3bb81562011-10-21 18:52:59 -0700279 } else {
280 LOG(ERROR) << "JDWP option 'server' must be 'y' or 'n'";
281 return false;
282 }
283 } else if (name == "suspend") {
284 if (value == "n") {
Elliott Hughes376a7a02011-10-24 18:35:55 -0700285 gJdwpOptions.suspend = false;
Elliott Hughes3bb81562011-10-21 18:52:59 -0700286 } else if (value == "y") {
Elliott Hughes376a7a02011-10-24 18:35:55 -0700287 gJdwpOptions.suspend = true;
Elliott Hughes3bb81562011-10-21 18:52:59 -0700288 } else {
289 LOG(ERROR) << "JDWP option 'suspend' must be 'y' or 'n'";
290 return false;
291 }
292 } else if (name == "address") {
293 /* this is either <port> or <host>:<port> */
294 std::string port_string;
Elliott Hughes376a7a02011-10-24 18:35:55 -0700295 gJdwpOptions.host.clear();
Elliott Hughes3bb81562011-10-21 18:52:59 -0700296 std::string::size_type colon = value.find(':');
297 if (colon != std::string::npos) {
Elliott Hughes376a7a02011-10-24 18:35:55 -0700298 gJdwpOptions.host = value.substr(0, colon);
Elliott Hughes3bb81562011-10-21 18:52:59 -0700299 port_string = value.substr(colon + 1);
300 } else {
301 port_string = value;
302 }
303 if (port_string.empty()) {
304 LOG(ERROR) << "JDWP address missing port: " << value;
305 return false;
306 }
307 char* end;
Elliott Hughesba8eee12012-01-24 20:25:24 -0800308 uint64_t port = strtoul(port_string.c_str(), &end, 10);
309 if (*end != '\0' || port > 0xffff) {
Elliott Hughes3bb81562011-10-21 18:52:59 -0700310 LOG(ERROR) << "JDWP address has junk in port field: " << value;
311 return false;
312 }
Elliott Hughes376a7a02011-10-24 18:35:55 -0700313 gJdwpOptions.port = port;
Elliott Hughes3bb81562011-10-21 18:52:59 -0700314 } else if (name == "launch" || name == "onthrow" || name == "oncaught" || name == "timeout") {
315 /* valid but unsupported */
316 LOG(INFO) << "Ignoring JDWP option '" << name << "'='" << value << "'";
317 } else {
318 LOG(INFO) << "Ignoring unrecognized JDWP option '" << name << "'='" << value << "'";
319 }
320
321 return true;
322}
323
324/*
325 * Parse the latter half of a -Xrunjdwp/-agentlib:jdwp= string, e.g.:
326 * "transport=dt_socket,address=8000,server=y,suspend=n"
327 */
328bool Dbg::ParseJdwpOptions(const std::string& options) {
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -0800329 VLOG(jdwp) << "ParseJdwpOptions: " << options;
Elliott Hughes47fce012011-10-25 18:37:19 -0700330
Elliott Hughes3bb81562011-10-21 18:52:59 -0700331 std::vector<std::string> pairs;
332 Split(options, ',', pairs);
333
334 for (size_t i = 0; i < pairs.size(); ++i) {
335 std::string::size_type equals = pairs[i].find('=');
336 if (equals == std::string::npos) {
337 LOG(ERROR) << "Can't parse JDWP option '" << pairs[i] << "' in '" << options << "'";
338 return false;
339 }
340 ParseJdwpOption(pairs[i].substr(0, equals), pairs[i].substr(equals + 1));
341 }
342
Elliott Hughes376a7a02011-10-24 18:35:55 -0700343 if (gJdwpOptions.transport == JDWP::kJdwpTransportUnknown) {
Elliott Hughes3bb81562011-10-21 18:52:59 -0700344 LOG(ERROR) << "Must specify JDWP transport: " << options;
345 }
Elliott Hughes376a7a02011-10-24 18:35:55 -0700346 if (!gJdwpOptions.server && (gJdwpOptions.host.empty() || gJdwpOptions.port == 0)) {
Elliott Hughes3bb81562011-10-21 18:52:59 -0700347 LOG(ERROR) << "Must specify JDWP host and port when server=n: " << options;
348 return false;
349 }
350
351 gJdwpConfigured = true;
352 return true;
353}
354
Elliott Hughesd1cc8362011-10-24 16:58:50 -0700355void Dbg::StartJdwp() {
Elliott Hughes376a7a02011-10-24 18:35:55 -0700356 if (!gJdwpAllowed || !gJdwpConfigured) {
357 // No JDWP for you!
358 return;
359 }
360
Elliott Hughes475fc232011-10-25 15:00:35 -0700361 CHECK(gRegistry == NULL);
362 gRegistry = new ObjectRegistry;
363
Elliott Hughesd1cc8362011-10-24 16:58:50 -0700364 // Init JDWP if the debugger is enabled. This may connect out to a
365 // debugger, passively listen for a debugger, or block waiting for a
366 // debugger.
Elliott Hughes376a7a02011-10-24 18:35:55 -0700367 gJdwpState = JDWP::JdwpState::Create(&gJdwpOptions);
368 if (gJdwpState == NULL) {
Elliott Hughesf8a2df72011-12-01 12:19:54 -0800369 // We probably failed because some other process has the port already, which means that
370 // if we don't abort the user is likely to think they're talking to us when they're actually
371 // talking to that other process.
Elliott Hughes3d30d9b2011-12-07 17:35:48 -0800372 LOG(FATAL) << "Debugger thread failed to initialize";
Elliott Hughesd1cc8362011-10-24 16:58:50 -0700373 }
374
375 // If a debugger has already attached, send the "welcome" message.
376 // This may cause us to suspend all threads.
Elliott Hughes376a7a02011-10-24 18:35:55 -0700377 if (gJdwpState->IsActive()) {
Elliott Hughesa2155262011-11-16 16:26:58 -0800378 //ScopedThreadStateChange tsc(Thread::Current(), Thread::kRunnable);
Elliott Hughes376a7a02011-10-24 18:35:55 -0700379 if (!gJdwpState->PostVMStart()) {
Elliott Hughes3d30d9b2011-12-07 17:35:48 -0800380 LOG(WARNING) << "Failed to post 'start' message to debugger";
Elliott Hughesd1cc8362011-10-24 16:58:50 -0700381 }
382 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700383}
384
Elliott Hughesd1cc8362011-10-24 16:58:50 -0700385void Dbg::StopJdwp() {
Elliott Hughes376a7a02011-10-24 18:35:55 -0700386 delete gJdwpState;
Elliott Hughes475fc232011-10-25 15:00:35 -0700387 delete gRegistry;
388 gRegistry = NULL;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700389}
390
Elliott Hughes767a1472011-10-26 18:49:02 -0700391void Dbg::GcDidFinish() {
392 if (gDdmHpifWhen != HPIF_WHEN_NEVER) {
393 LOG(DEBUG) << "Sending VM heap info to DDM";
Elliott Hughes7162ad92011-10-27 14:08:42 -0700394 DdmSendHeapInfo(gDdmHpifWhen);
Elliott Hughes767a1472011-10-26 18:49:02 -0700395 }
396 if (gDdmHpsgWhen != HPSG_WHEN_NEVER) {
397 LOG(DEBUG) << "Dumping VM heap to DDM";
Elliott Hughes6a5bd492011-10-28 14:33:57 -0700398 DdmSendHeapSegments(false);
Elliott Hughes767a1472011-10-26 18:49:02 -0700399 }
400 if (gDdmNhsgWhen != HPSG_WHEN_NEVER) {
401 LOG(DEBUG) << "Dumping native heap to DDM";
Elliott Hughes6a5bd492011-10-28 14:33:57 -0700402 DdmSendHeapSegments(true);
Elliott Hughes767a1472011-10-26 18:49:02 -0700403 }
404}
405
Elliott Hughes4ffd3132011-10-24 12:06:42 -0700406void Dbg::SetJdwpAllowed(bool allowed) {
407 gJdwpAllowed = allowed;
408}
409
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700410DebugInvokeReq* Dbg::GetInvokeReq() {
Elliott Hughes475fc232011-10-25 15:00:35 -0700411 return Thread::Current()->GetInvokeReq();
412}
413
414Thread* Dbg::GetDebugThread() {
415 return (gJdwpState != NULL) ? gJdwpState->GetDebugThread() : NULL;
416}
417
418void Dbg::ClearWaitForEventThread() {
419 gJdwpState->ClearWaitForEventThread();
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700420}
421
422void Dbg::Connected() {
Elliott Hughes3bb81562011-10-21 18:52:59 -0700423 CHECK(!gDebuggerConnected);
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -0800424 VLOG(jdwp) << "JDWP has attached";
Elliott Hughes3bb81562011-10-21 18:52:59 -0700425 gDebuggerConnected = true;
Elliott Hughes86964332012-02-15 19:37:42 -0800426 gDisposed = false;
427}
428
429void Dbg::Disposed() {
430 gDisposed = true;
431}
432
433bool Dbg::IsDisposed() {
434 return gDisposed;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700435}
436
Elliott Hughesa2155262011-11-16 16:26:58 -0800437void Dbg::GoActive() {
438 // Enable all debugging features, including scans for breakpoints.
439 // This is a no-op if we're already active.
440 // Only called from the JDWP handler thread.
441 if (gDebuggerActive) {
442 return;
443 }
444
445 LOG(INFO) << "Debugger is active";
446
447 // TODO: CHECK we don't have any outstanding breakpoints.
448
449 gDebuggerActive = true;
450
451 //dvmEnableAllSubMode(kSubModeDebuggerActive);
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700452}
453
454void Dbg::Disconnected() {
Elliott Hughes234ab152011-10-26 14:02:26 -0700455 CHECK(gDebuggerConnected);
456
457 gDebuggerActive = false;
458
459 //dvmDisableAllSubMode(kSubModeDebuggerActive);
460
461 gRegistry->Clear();
462 gDebuggerConnected = false;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700463}
464
465bool Dbg::IsDebuggerConnected() {
Elliott Hughes3bb81562011-10-21 18:52:59 -0700466 return gDebuggerActive;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700467}
468
469bool Dbg::IsDebuggingEnabled() {
Elliott Hughes3bb81562011-10-21 18:52:59 -0700470 return gJdwpConfigured;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700471}
472
473int64_t Dbg::LastDebuggerActivity() {
Elliott Hughesca951522011-12-05 12:01:32 -0800474 return gJdwpState->LastDebuggerActivity();
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700475}
476
477int Dbg::ThreadRunning() {
Elliott Hughesd1cc8362011-10-24 16:58:50 -0700478 return static_cast<int>(Thread::Current()->SetState(Thread::kRunnable));
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700479}
480
481int Dbg::ThreadWaiting() {
Elliott Hughesd1cc8362011-10-24 16:58:50 -0700482 return static_cast<int>(Thread::Current()->SetState(Thread::kVmWait));
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700483}
484
Elliott Hughes6ba581a2011-10-25 11:45:35 -0700485int Dbg::ThreadContinuing(int new_state) {
486 return static_cast<int>(Thread::Current()->SetState(static_cast<Thread::State>(new_state)));
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700487}
488
489void Dbg::UndoDebuggerSuspensions() {
Elliott Hughes234ab152011-10-26 14:02:26 -0700490 Runtime::Current()->GetThreadList()->UndoDebuggerSuspensions();
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700491}
492
493void Dbg::Exit(int status) {
Elliott Hughes1bba14f2011-12-01 18:00:36 -0800494 exit(status); // This is all dalvik did.
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700495}
496
Elliott Hughesbfe487b2011-10-26 15:48:55 -0700497void Dbg::VisitRoots(Heap::RootVisitor* visitor, void* arg) {
498 if (gRegistry != NULL) {
499 gRegistry->VisitRoots(visitor, arg);
500 }
501}
502
Elliott Hughesc308a5d2012-02-16 17:12:06 -0800503std::string Dbg::GetClassName(JDWP::RefTypeId classId) {
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -0800504 Object* o = gRegistry->Get<Object*>(classId);
505 if (o == NULL || !o->IsClass()) {
506 return StringPrintf("non-class %p", o); // This is only used for debugging output anyway.
507 }
Elliott Hughesc308a5d2012-02-16 17:12:06 -0800508 return DescriptorToName(ClassHelper(o->AsClass()).GetDescriptor());
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700509}
510
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -0800511bool Dbg::GetClassObject(JDWP::RefTypeId id, JDWP::ObjectId& classObjectId) {
512 Object* o = gRegistry->Get<Object*>(id);
513 if (o == NULL || !o->IsClass()) {
514 return false;
515 }
516 classObjectId = gRegistry->Add(o);
517 return true;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700518}
519
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -0800520static Array* DecodeArray(JDWP::RefTypeId id, JDWP::JdwpError& status) {
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -0800521 Object* o = gRegistry->Get<Object*>(id);
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -0800522 if (o == NULL) {
523 status = JDWP::ERR_INVALID_OBJECT;
524 return NULL;
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -0800525 }
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -0800526 if (!o->IsArrayInstance()) {
527 status = JDWP::ERR_INVALID_ARRAY;
528 return NULL;
529 }
530 status = JDWP::ERR_NONE;
531 return o->AsArray();
532}
533
534// TODO: this should probably be used everywhere we're converting a RefTypeId to a Class*.
535static Class* DecodeClass(JDWP::RefTypeId id, JDWP::JdwpError& status) {
536 Object* o = gRegistry->Get<Object*>(id);
537 if (o == NULL) {
538 status = JDWP::ERR_INVALID_OBJECT;
539 return NULL;
540 }
541 if (!o->IsClass()) {
542 status = JDWP::ERR_INVALID_CLASS;
543 return NULL;
544 }
545 status = JDWP::ERR_NONE;
546 return o->AsClass();
547}
548
Elliott Hughes86964332012-02-15 19:37:42 -0800549static Thread* DecodeThread(JDWP::ObjectId threadId) {
550 Object* thread_peer = gRegistry->Get<Object*>(threadId);
Elliott Hughes2435a572012-02-17 16:07:41 -0800551 if (thread_peer == NULL) {
552 return NULL;
553 }
Elliott Hughes86964332012-02-15 19:37:42 -0800554 return Thread::FromManagedThread(thread_peer);
555}
556
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -0800557JDWP::JdwpError Dbg::GetSuperclass(JDWP::RefTypeId id, JDWP::RefTypeId& superclassId) {
558 JDWP::JdwpError status;
559 Class* c = DecodeClass(id, status);
560 if (c == NULL) {
561 return status;
562 }
563 if (c->IsInterface()) {
564 // http://code.google.com/p/android/issues/detail?id=20856
565 superclassId = NULL;
566 } else {
567 superclassId = gRegistry->Add(c->GetSuperClass());
568 }
569 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700570}
571
572JDWP::ObjectId Dbg::GetClassLoader(JDWP::RefTypeId id) {
Elliott Hughes1bba14f2011-12-01 18:00:36 -0800573 Object* o = gRegistry->Get<Object*>(id);
574 return gRegistry->Add(o->GetClass()->GetClassLoader());
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700575}
576
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -0800577bool Dbg::GetAccessFlags(JDWP::RefTypeId id, uint32_t& access_flags) {
578 Object* o = gRegistry->Get<Object*>(id);
579 if (o == NULL || !o->IsClass()) {
580 return false;
581 }
582 access_flags = o->AsClass()->GetAccessFlags() & kAccJavaFlagsMask;
583 return true;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700584}
585
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -0800586bool Dbg::IsInterface(JDWP::RefTypeId classId, bool& is_interface) {
587 Object* o = gRegistry->Get<Object*>(classId);
588 if (o == NULL || !o->IsClass()) {
589 return false;
590 }
591 is_interface = o->AsClass()->IsInterface();
592 return true;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700593}
594
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -0800595void Dbg::GetClassList(std::vector<JDWP::RefTypeId>& classes) {
Elliott Hughesa2155262011-11-16 16:26:58 -0800596 // Get the complete list of reference classes (i.e. all classes except
597 // the primitive types).
598 // Returns a newly-allocated buffer full of RefTypeId values.
599 struct ClassListCreator {
Elliott Hughesba8eee12012-01-24 20:25:24 -0800600 explicit ClassListCreator(std::vector<JDWP::RefTypeId>& classes) : classes(classes) {
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -0800601 }
602
Elliott Hughesa2155262011-11-16 16:26:58 -0800603 static bool Visit(Class* c, void* arg) {
604 return reinterpret_cast<ClassListCreator*>(arg)->Visit(c);
605 }
606
607 bool Visit(Class* c) {
608 if (!c->IsPrimitive()) {
609 classes.push_back(static_cast<JDWP::RefTypeId>(gRegistry->Add(c)));
610 }
611 return true;
612 }
613
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -0800614 std::vector<JDWP::RefTypeId>& classes;
Elliott Hughesa2155262011-11-16 16:26:58 -0800615 };
616
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -0800617 ClassListCreator clc(classes);
Elliott Hughesa2155262011-11-16 16:26:58 -0800618 Runtime::Current()->GetClassLinker()->VisitClasses(ClassListCreator::Visit, &clc);
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700619}
620
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -0800621bool Dbg::GetClassInfo(JDWP::RefTypeId classId, JDWP::JdwpTypeTag* pTypeTag, uint32_t* pStatus, std::string* pDescriptor) {
622 Object* o = gRegistry->Get<Object*>(classId);
623 if (o == NULL || !o->IsClass()) {
624 return false;
625 }
626
627 Class* c = o->AsClass();
Elliott Hughesa2155262011-11-16 16:26:58 -0800628 if (c->IsArrayClass()) {
629 *pStatus = JDWP::CS_VERIFIED | JDWP::CS_PREPARED;
630 *pTypeTag = JDWP::TT_ARRAY;
631 } else {
632 if (c->IsErroneous()) {
633 *pStatus = JDWP::CS_ERROR;
634 } else {
635 *pStatus = JDWP::CS_VERIFIED | JDWP::CS_PREPARED | JDWP::CS_INITIALIZED;
636 }
637 *pTypeTag = c->IsInterface() ? JDWP::TT_INTERFACE : JDWP::TT_CLASS;
638 }
639
640 if (pDescriptor != NULL) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800641 *pDescriptor = ClassHelper(c).GetDescriptor();
Elliott Hughesa2155262011-11-16 16:26:58 -0800642 }
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -0800643 return true;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700644}
645
Elliott Hughesc3b77c72011-12-15 20:56:48 -0800646void Dbg::FindLoadedClassBySignature(const char* descriptor, std::vector<JDWP::RefTypeId>& ids) {
Elliott Hughes6fa602d2011-12-02 17:54:25 -0800647 std::vector<Class*> classes;
648 Runtime::Current()->GetClassLinker()->LookupClasses(descriptor, classes);
649 ids.clear();
650 for (size_t i = 0; i < classes.size(); ++i) {
651 ids.push_back(gRegistry->Add(classes[i]));
652 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700653}
654
Elliott Hughes2435a572012-02-17 16:07:41 -0800655JDWP::JdwpError Dbg::GetReferenceType(JDWP::ObjectId objectId, JDWP::ExpandBuf* pReply) {
Elliott Hughes499c5132011-11-17 14:55:11 -0800656 Object* o = gRegistry->Get<Object*>(objectId);
Elliott Hughes2435a572012-02-17 16:07:41 -0800657 if (o == NULL) {
658 return JDWP::ERR_INVALID_OBJECT;
Elliott Hughes499c5132011-11-17 14:55:11 -0800659 }
Elliott Hughes2435a572012-02-17 16:07:41 -0800660
661 JDWP::JdwpTypeTag type_tag;
662 if (o->GetClass()->IsArrayClass()) {
663 type_tag = JDWP::TT_ARRAY;
664 } else if (o->GetClass()->IsInterface()) {
665 type_tag = JDWP::TT_INTERFACE;
666 } else {
667 type_tag = JDWP::TT_CLASS;
668 }
669 JDWP::RefTypeId type_id = gRegistry->Add(o->GetClass());
670
671 expandBufAdd1(pReply, type_tag);
672 expandBufAddRefTypeId(pReply, type_id);
673
674 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700675}
676
Elliott Hughes1fe7afb2012-02-13 17:23:03 -0800677JDWP::JdwpError Dbg::GetSignature(JDWP::RefTypeId refTypeId, std::string& signature) {
678 JDWP::JdwpError status;
679 Class* c = DecodeClass(refTypeId, status);
680 if (c == NULL) {
681 return status;
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -0800682 }
Elliott Hughes1fe7afb2012-02-13 17:23:03 -0800683 signature = ClassHelper(c).GetDescriptor();
684 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700685}
686
Elliott Hughes03181a82011-11-17 17:22:21 -0800687bool Dbg::GetSourceFile(JDWP::RefTypeId refTypeId, std::string& result) {
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -0800688 Object* o = gRegistry->Get<Object*>(refTypeId);
689 if (o == NULL || !o->IsClass()) {
690 return false;
691 }
692 result = ClassHelper(o->AsClass()).GetSourceFile();
693 return result != NULL;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700694}
695
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700696uint8_t Dbg::GetObjectTag(JDWP::ObjectId objectId) {
Elliott Hughes24437992011-11-30 14:49:33 -0800697 Object* o = gRegistry->Get<Object*>(objectId);
698 return TagFromObject(o);
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700699}
700
Elliott Hughesaed4be92011-12-02 16:16:23 -0800701size_t Dbg::GetTagWidth(JDWP::JdwpTag tag) {
Elliott Hughesdbb40792011-11-18 17:05:22 -0800702 switch (tag) {
703 case JDWP::JT_VOID:
704 return 0;
705 case JDWP::JT_BYTE:
706 case JDWP::JT_BOOLEAN:
707 return 1;
708 case JDWP::JT_CHAR:
709 case JDWP::JT_SHORT:
710 return 2;
711 case JDWP::JT_FLOAT:
712 case JDWP::JT_INT:
713 return 4;
714 case JDWP::JT_ARRAY:
715 case JDWP::JT_OBJECT:
716 case JDWP::JT_STRING:
717 case JDWP::JT_THREAD:
718 case JDWP::JT_THREAD_GROUP:
719 case JDWP::JT_CLASS_LOADER:
720 case JDWP::JT_CLASS_OBJECT:
721 return sizeof(JDWP::ObjectId);
722 case JDWP::JT_DOUBLE:
723 case JDWP::JT_LONG:
724 return 8;
725 default:
Elliott Hughes3d30d9b2011-12-07 17:35:48 -0800726 LOG(FATAL) << "Unknown tag " << tag;
Elliott Hughesdbb40792011-11-18 17:05:22 -0800727 return -1;
728 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700729}
730
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -0800731JDWP::JdwpError Dbg::GetArrayLength(JDWP::ObjectId arrayId, int& length) {
732 JDWP::JdwpError status;
733 Array* a = DecodeArray(arrayId, status);
734 if (a == NULL) {
735 return status;
Elliott Hughes24437992011-11-30 14:49:33 -0800736 }
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -0800737 length = a->GetLength();
738 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700739}
740
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -0800741JDWP::JdwpError Dbg::OutputArray(JDWP::ObjectId arrayId, int offset, int count, JDWP::ExpandBuf* pReply) {
742 JDWP::JdwpError status;
743 Array* a = DecodeArray(arrayId, status);
744 if (a == NULL) {
745 return status;
746 }
Elliott Hughes24437992011-11-30 14:49:33 -0800747
748 if (offset < 0 || count < 0 || offset > a->GetLength() || a->GetLength() - offset < count) {
749 LOG(WARNING) << __FUNCTION__ << " access out of bounds: offset=" << offset << "; count=" << count;
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -0800750 return JDWP::ERR_INVALID_LENGTH;
Elliott Hughes24437992011-11-30 14:49:33 -0800751 }
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800752 std::string descriptor(ClassHelper(a->GetClass()).GetDescriptor());
Elliott Hughes24437992011-11-30 14:49:33 -0800753 JDWP::JdwpTag tag = BasicTagFromDescriptor(descriptor.c_str() + 1);
754
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -0800755 expandBufAdd1(pReply, tag);
756 expandBufAdd4BE(pReply, count);
757
Elliott Hughes24437992011-11-30 14:49:33 -0800758 if (IsPrimitiveTag(tag)) {
759 size_t width = GetTagWidth(tag);
760 const uint8_t* src = reinterpret_cast<uint8_t*>(a->GetRawData());
761 uint8_t* dst = expandBufAddSpace(pReply, count * width);
762 if (width == 8) {
763 const uint64_t* src8 = reinterpret_cast<const uint64_t*>(src);
764 for (int i = 0; i < count; ++i) JDWP::Write8BE(&dst, src8[offset + i]);
765 } else if (width == 4) {
766 const uint32_t* src4 = reinterpret_cast<const uint32_t*>(src);
767 for (int i = 0; i < count; ++i) JDWP::Write4BE(&dst, src4[offset + i]);
768 } else if (width == 2) {
769 const uint16_t* src2 = reinterpret_cast<const uint16_t*>(src);
770 for (int i = 0; i < count; ++i) JDWP::Write2BE(&dst, src2[offset + i]);
771 } else {
772 memcpy(dst, &src[offset * width], count * width);
773 }
774 } else {
775 ObjectArray<Object>* oa = a->AsObjectArray<Object>();
776 for (int i = 0; i < count; ++i) {
Elliott Hughesf03b8f62011-12-02 14:26:25 -0800777 Object* element = oa->Get(offset + i);
Elliott Hughes24437992011-11-30 14:49:33 -0800778 JDWP::JdwpTag specific_tag = (element != NULL) ? TagFromObject(element) : tag;
779 expandBufAdd1(pReply, specific_tag);
780 expandBufAddObjectId(pReply, gRegistry->Add(element));
781 }
782 }
783
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -0800784 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700785}
786
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -0800787JDWP::JdwpError Dbg::SetArrayElements(JDWP::ObjectId arrayId, int offset, int count, const uint8_t* src) {
788 JDWP::JdwpError status;
789 Array* a = DecodeArray(arrayId, status);
790 if (a == NULL) {
791 return status;
792 }
Elliott Hughesf03b8f62011-12-02 14:26:25 -0800793
794 if (offset < 0 || count < 0 || offset > a->GetLength() || a->GetLength() - offset < count) {
795 LOG(WARNING) << __FUNCTION__ << " access out of bounds: offset=" << offset << "; count=" << count;
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -0800796 return JDWP::ERR_INVALID_LENGTH;
Elliott Hughesf03b8f62011-12-02 14:26:25 -0800797 }
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800798 std::string descriptor(ClassHelper(a->GetClass()).GetDescriptor());
Elliott Hughesf03b8f62011-12-02 14:26:25 -0800799 JDWP::JdwpTag tag = BasicTagFromDescriptor(descriptor.c_str() + 1);
800
801 if (IsPrimitiveTag(tag)) {
802 size_t width = GetTagWidth(tag);
803 uint8_t* dst = &(reinterpret_cast<uint8_t*>(a->GetRawData())[offset * width]);
804 if (width == 8) {
805 for (int i = 0; i < count; ++i) {
806 // Handle potentially non-aligned memory access one byte at a time for ARM's benefit.
807 uint64_t value;
808 for (size_t j = 0; j < sizeof(uint64_t); ++j) reinterpret_cast<uint8_t*>(&value)[j] = src[j];
809 src += sizeof(uint64_t);
810 JDWP::Write8BE(&dst, value);
811 }
812 } else if (width == 4) {
813 const uint32_t* src4 = reinterpret_cast<const uint32_t*>(src);
814 for (int i = 0; i < count; ++i) JDWP::Write4BE(&dst, src4[i]);
815 } else if (width == 2) {
816 const uint16_t* src2 = reinterpret_cast<const uint16_t*>(src);
817 for (int i = 0; i < count; ++i) JDWP::Write2BE(&dst, src2[i]);
818 } else {
819 memcpy(&dst[offset * width], src, count * width);
820 }
821 } else {
822 ObjectArray<Object>* oa = a->AsObjectArray<Object>();
823 for (int i = 0; i < count; ++i) {
824 JDWP::ObjectId id = JDWP::ReadObjectId(&src);
825 oa->Set(offset + i, gRegistry->Get<Object*>(id));
826 }
827 }
828
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -0800829 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700830}
831
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -0800832JDWP::ObjectId Dbg::CreateString(const std::string& str) {
833 return gRegistry->Add(String::AllocFromModifiedUtf8(str.c_str()));
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700834}
835
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -0800836bool Dbg::CreateObject(JDWP::RefTypeId classId, JDWP::ObjectId& new_object) {
837 Object* o = gRegistry->Get<Object*>(classId);
838 if (o == NULL || !o->IsClass()) {
839 return false;
840 }
841 new_object = gRegistry->Add(o->AsClass()->AllocObject());
842 return true;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700843}
844
Elliott Hughesbf13d362011-12-08 15:51:37 -0800845/*
846 * Used by Eclipse's "Display" view to evaluate "new byte[5]" to get "(byte[]) [0, 0, 0, 0, 0]".
847 */
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -0800848bool Dbg::CreateArrayObject(JDWP::RefTypeId arrayTypeId, uint32_t length, JDWP::ObjectId& new_array) {
849 Object* o = gRegistry->Get<Object*>(arrayTypeId);
850 if (o == NULL || !o->IsClass()) {
851 return false;
852 }
853 new_array = gRegistry->Add(Array::Alloc(o->AsClass(), length));
854 return true;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700855}
856
857bool Dbg::MatchType(JDWP::RefTypeId instClassId, JDWP::RefTypeId classId) {
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -0800858 // TODO: error handling if the RefTypeIds aren't actually Class*s.
Elliott Hughesd07986f2011-12-06 18:27:45 -0800859 return gRegistry->Get<Class*>(instClassId)->InstanceOf(gRegistry->Get<Class*>(classId));
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700860}
861
Elliott Hughes86964332012-02-15 19:37:42 -0800862static JDWP::FieldId ToFieldId(const Field* f) {
Elliott Hughes03181a82011-11-17 17:22:21 -0800863#ifdef MOVING_GARBAGE_COLLECTOR
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700864 UNIMPLEMENTED(FATAL);
Elliott Hughes03181a82011-11-17 17:22:21 -0800865#else
866 return static_cast<JDWP::FieldId>(reinterpret_cast<uintptr_t>(f));
867#endif
868}
869
Elliott Hughes86964332012-02-15 19:37:42 -0800870static JDWP::MethodId ToMethodId(const Method* m) {
Elliott Hughes03181a82011-11-17 17:22:21 -0800871#ifdef MOVING_GARBAGE_COLLECTOR
872 UNIMPLEMENTED(FATAL);
873#else
874 return static_cast<JDWP::MethodId>(reinterpret_cast<uintptr_t>(m));
875#endif
876}
877
Elliott Hughes86964332012-02-15 19:37:42 -0800878static Field* FromFieldId(JDWP::FieldId fid) {
Elliott Hughesaed4be92011-12-02 16:16:23 -0800879#ifdef MOVING_GARBAGE_COLLECTOR
880 UNIMPLEMENTED(FATAL);
881#else
882 return reinterpret_cast<Field*>(static_cast<uintptr_t>(fid));
883#endif
884}
885
Elliott Hughes86964332012-02-15 19:37:42 -0800886static Method* FromMethodId(JDWP::MethodId mid) {
Elliott Hughes03181a82011-11-17 17:22:21 -0800887#ifdef MOVING_GARBAGE_COLLECTOR
888 UNIMPLEMENTED(FATAL);
889#else
890 return reinterpret_cast<Method*>(static_cast<uintptr_t>(mid));
891#endif
892}
893
Elliott Hughes86964332012-02-15 19:37:42 -0800894static void SetLocation(JDWP::JdwpLocation& location, Method* m, uintptr_t native_pc) {
Elliott Hughes91bf6cd2012-02-14 17:27:48 -0800895 if (m == NULL) {
896 memset(&location, 0, sizeof(location));
897 } else {
898 Class* c = m->GetDeclaringClass();
899 location.typeTag = c->IsInterface() ? JDWP::TT_INTERFACE : JDWP::TT_CLASS;
900 location.classId = gRegistry->Add(c);
901 location.methodId = ToMethodId(m);
Elliott Hughes2aa2e392012-02-17 17:15:43 -0800902 location.idx = m->IsNative() ? -1 : m->ToDexPC(native_pc) / 2;
Elliott Hughes91bf6cd2012-02-14 17:27:48 -0800903 }
Elliott Hughesd07986f2011-12-06 18:27:45 -0800904}
905
Elliott Hughes03181a82011-11-17 17:22:21 -0800906std::string Dbg::GetMethodName(JDWP::RefTypeId refTypeId, JDWP::MethodId methodId) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800907 Method* m = FromMethodId(methodId);
908 return MethodHelper(m).GetName();
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700909}
910
Elliott Hughesa2e54f62011-11-17 13:01:30 -0800911/*
912 * Augment the access flags for synthetic methods and fields by setting
913 * the (as described by the spec) "0xf0000000 bit". Also, strip out any
914 * flags not specified by the Java programming language.
915 */
916static uint32_t MangleAccessFlags(uint32_t accessFlags) {
917 accessFlags &= kAccJavaFlagsMask;
918 if ((accessFlags & kAccSynthetic) != 0) {
919 accessFlags |= 0xf0000000;
920 }
921 return accessFlags;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700922}
923
Elliott Hughesdbb40792011-11-18 17:05:22 -0800924static const uint16_t kEclipseWorkaroundSlot = 1000;
925
926/*
927 * Eclipse appears to expect that the "this" reference is in slot zero.
928 * If it's not, the "variables" display will show two copies of "this",
929 * possibly because it gets "this" from SF.ThisObject and then displays
930 * all locals with nonzero slot numbers.
931 *
932 * So, we remap the item in slot 0 to 1000, and remap "this" to zero. On
933 * SF.GetValues / SF.SetValues we map them back.
Elliott Hughesc5b734a2011-12-01 17:20:58 -0800934 *
935 * TODO: jdb uses the value to determine whether a variable is a local or an argument,
936 * by checking whether it's less than the number of arguments. To make that work, we'd
937 * have to "mangle" all the arguments to come first, not just the implicit argument 'this'.
Elliott Hughesdbb40792011-11-18 17:05:22 -0800938 */
939static uint16_t MangleSlot(uint16_t slot, const char* name) {
940 uint16_t newSlot = slot;
941 if (strcmp(name, "this") == 0) {
942 newSlot = 0;
943 } else if (slot == 0) {
944 newSlot = kEclipseWorkaroundSlot;
945 }
946 return newSlot;
947}
948
Elliott Hughes91bf6cd2012-02-14 17:27:48 -0800949static uint16_t DemangleSlot(uint16_t slot, Method* m) {
Elliott Hughesdbb40792011-11-18 17:05:22 -0800950 if (slot == kEclipseWorkaroundSlot) {
Elliott Hughes68fdbd02011-11-29 19:22:47 -0800951 return 0;
Elliott Hughesdbb40792011-11-18 17:05:22 -0800952 } else if (slot == 0) {
Elliott Hughes91bf6cd2012-02-14 17:27:48 -0800953 const DexFile::CodeItem* code_item = MethodHelper(m).GetCodeItem();
954 CHECK(code_item != NULL);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800955 return code_item->registers_size_ - code_item->ins_size_;
Elliott Hughesdbb40792011-11-18 17:05:22 -0800956 }
Elliott Hughes68fdbd02011-11-29 19:22:47 -0800957 return slot;
Elliott Hughesdbb40792011-11-18 17:05:22 -0800958}
959
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -0800960bool Dbg::OutputDeclaredFields(JDWP::RefTypeId refTypeId, bool with_generic, JDWP::ExpandBuf* pReply) {
961 Object* o = gRegistry->Get<Object*>(refTypeId);
962 if (o == NULL || !o->IsClass()) {
963 return false;
964 }
Elliott Hughesa2e54f62011-11-17 13:01:30 -0800965
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -0800966 Class* c = o->AsClass();
Elliott Hughesa2e54f62011-11-17 13:01:30 -0800967 size_t instance_field_count = c->NumInstanceFields();
968 size_t static_field_count = c->NumStaticFields();
969
970 expandBufAdd4BE(pReply, instance_field_count + static_field_count);
971
972 for (size_t i = 0; i < instance_field_count + static_field_count; ++i) {
973 Field* f = (i < instance_field_count) ? c->GetInstanceField(i) : c->GetStaticField(i - instance_field_count);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800974 FieldHelper fh(f);
Elliott Hughesa2e54f62011-11-17 13:01:30 -0800975 expandBufAddFieldId(pReply, ToFieldId(f));
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800976 expandBufAddUtf8String(pReply, fh.GetName());
977 expandBufAddUtf8String(pReply, fh.GetTypeDescriptor());
Elliott Hughesc5b734a2011-12-01 17:20:58 -0800978 if (with_generic) {
Elliott Hughesa2e54f62011-11-17 13:01:30 -0800979 static const char genericSignature[1] = "";
980 expandBufAddUtf8String(pReply, genericSignature);
981 }
982 expandBufAdd4BE(pReply, MangleAccessFlags(f->GetAccessFlags()));
983 }
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -0800984 return true;
Elliott Hughesa2e54f62011-11-17 13:01:30 -0800985}
986
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -0800987bool Dbg::OutputDeclaredMethods(JDWP::RefTypeId refTypeId, bool with_generic, JDWP::ExpandBuf* pReply) {
988 Object* o = gRegistry->Get<Object*>(refTypeId);
989 if (o == NULL || !o->IsClass()) {
990 return false;
991 }
Elliott Hughesa2e54f62011-11-17 13:01:30 -0800992
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -0800993 Class* c = o->AsClass();
Elliott Hughesa2e54f62011-11-17 13:01:30 -0800994 size_t direct_method_count = c->NumDirectMethods();
995 size_t virtual_method_count = c->NumVirtualMethods();
996
997 expandBufAdd4BE(pReply, direct_method_count + virtual_method_count);
998
999 for (size_t i = 0; i < direct_method_count + virtual_method_count; ++i) {
1000 Method* m = (i < direct_method_count) ? c->GetDirectMethod(i) : c->GetVirtualMethod(i - direct_method_count);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001001 MethodHelper mh(m);
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001002 expandBufAddMethodId(pReply, ToMethodId(m));
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001003 expandBufAddUtf8String(pReply, mh.GetName());
Elliott Hughes4740cdf2011-12-07 14:07:12 -08001004 expandBufAddUtf8String(pReply, mh.GetSignature());
Elliott Hughesc5b734a2011-12-01 17:20:58 -08001005 if (with_generic) {
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001006 static const char genericSignature[1] = "";
1007 expandBufAddUtf8String(pReply, genericSignature);
1008 }
1009 expandBufAdd4BE(pReply, MangleAccessFlags(m->GetAccessFlags()));
1010 }
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -08001011 return true;
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001012}
1013
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -08001014bool Dbg::OutputDeclaredInterfaces(JDWP::RefTypeId refTypeId, JDWP::ExpandBuf* pReply) {
1015 Object* o = gRegistry->Get<Object*>(refTypeId);
1016 if (o == NULL || !o->IsClass()) {
1017 return false;
1018 }
1019 ClassHelper kh(o->AsClass());
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001020 size_t interface_count = kh.NumInterfaces();
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001021 expandBufAdd4BE(pReply, interface_count);
1022 for (size_t i = 0; i < interface_count; ++i) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001023 expandBufAddRefTypeId(pReply, gRegistry->Add(kh.GetInterface(i)));
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001024 }
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -08001025 return true;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001026}
1027
1028void Dbg::OutputLineTable(JDWP::RefTypeId refTypeId, JDWP::MethodId methodId, JDWP::ExpandBuf* pReply) {
Elliott Hughes03181a82011-11-17 17:22:21 -08001029 struct DebugCallbackContext {
1030 int numItems;
1031 JDWP::ExpandBuf* pReply;
1032
Elliott Hughes2435a572012-02-17 16:07:41 -08001033 static bool Callback(void* context, uint32_t address, uint32_t line_number) {
Elliott Hughes03181a82011-11-17 17:22:21 -08001034 DebugCallbackContext* pContext = reinterpret_cast<DebugCallbackContext*>(context);
1035 expandBufAdd8BE(pContext->pReply, address);
Elliott Hughes2435a572012-02-17 16:07:41 -08001036 expandBufAdd4BE(pContext->pReply, line_number);
Elliott Hughes03181a82011-11-17 17:22:21 -08001037 pContext->numItems++;
1038 return true;
1039 }
1040 };
1041
1042 Method* m = FromMethodId(methodId);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001043 MethodHelper mh(m);
Elliott Hughes03181a82011-11-17 17:22:21 -08001044 uint64_t start, end;
1045 if (m->IsNative()) {
1046 start = -1;
1047 end = -1;
1048 } else {
1049 start = 0;
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001050 // TODO: what are the units supposed to be? *2?
1051 end = mh.GetCodeItem()->insns_size_in_code_units_;
Elliott Hughes03181a82011-11-17 17:22:21 -08001052 }
1053
1054 expandBufAdd8BE(pReply, start);
1055 expandBufAdd8BE(pReply, end);
1056
1057 // Add numLines later
1058 size_t numLinesOffset = expandBufGetLength(pReply);
1059 expandBufAdd4BE(pReply, 0);
1060
1061 DebugCallbackContext context;
1062 context.numItems = 0;
1063 context.pReply = pReply;
1064
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001065 mh.GetDexFile().DecodeDebugInfo(mh.GetCodeItem(), m->IsStatic(), m->GetDexMethodIndex(),
1066 DebugCallbackContext::Callback, NULL, &context);
Elliott Hughes03181a82011-11-17 17:22:21 -08001067
1068 JDWP::Set4BE(expandBufGetBuffer(pReply) + numLinesOffset, context.numItems);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001069}
1070
Elliott Hughesc5b734a2011-12-01 17:20:58 -08001071void Dbg::OutputVariableTable(JDWP::RefTypeId refTypeId, JDWP::MethodId methodId, bool with_generic, JDWP::ExpandBuf* pReply) {
Elliott Hughesdbb40792011-11-18 17:05:22 -08001072 struct DebugCallbackContext {
Elliott Hughesdbb40792011-11-18 17:05:22 -08001073 JDWP::ExpandBuf* pReply;
Elliott Hughesc5b734a2011-12-01 17:20:58 -08001074 size_t variable_count;
1075 bool with_generic;
Elliott Hughesdbb40792011-11-18 17:05:22 -08001076
Elliott Hughesc5b734a2011-12-01 17:20:58 -08001077 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 -08001078 DebugCallbackContext* pContext = reinterpret_cast<DebugCallbackContext*>(context);
1079
Elliott Hughesaa6e1cd2012-01-18 19:26:06 -08001080 VLOG(jdwp) << StringPrintf(" %2zd: %d(%d) '%s' '%s' '%s' slot=%d", pContext->variable_count, startAddress, endAddress - startAddress, name, descriptor, signature, slot);
Elliott Hughesdbb40792011-11-18 17:05:22 -08001081
Elliott Hughes68fdbd02011-11-29 19:22:47 -08001082 slot = MangleSlot(slot, name);
1083
Elliott Hughesdbb40792011-11-18 17:05:22 -08001084 expandBufAdd8BE(pContext->pReply, startAddress);
1085 expandBufAddUtf8String(pContext->pReply, name);
1086 expandBufAddUtf8String(pContext->pReply, descriptor);
Elliott Hughesc5b734a2011-12-01 17:20:58 -08001087 if (pContext->with_generic) {
Elliott Hughesdbb40792011-11-18 17:05:22 -08001088 expandBufAddUtf8String(pContext->pReply, signature);
1089 }
1090 expandBufAdd4BE(pContext->pReply, endAddress - startAddress);
1091 expandBufAdd4BE(pContext->pReply, slot);
1092
Elliott Hughesc5b734a2011-12-01 17:20:58 -08001093 ++pContext->variable_count;
Elliott Hughesdbb40792011-11-18 17:05:22 -08001094 }
1095 };
1096
1097 Method* m = FromMethodId(methodId);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001098 MethodHelper mh(m);
1099 const DexFile::CodeItem* code_item = mh.GetCodeItem();
Elliott Hughesdbb40792011-11-18 17:05:22 -08001100
Elliott Hughesc5b734a2011-12-01 17:20:58 -08001101 // arg_count considers doubles and longs to take 2 units.
1102 // variable_count considers everything to take 1 unit.
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001103 std::string shorty(mh.GetShorty());
Elliott Hughesc5b734a2011-12-01 17:20:58 -08001104 expandBufAdd4BE(pReply, m->NumArgRegisters(shorty));
Elliott Hughesdbb40792011-11-18 17:05:22 -08001105
Elliott Hughesc5b734a2011-12-01 17:20:58 -08001106 // We don't know the total number of variables yet, so leave a blank and update it later.
1107 size_t variable_count_offset = expandBufGetLength(pReply);
Elliott Hughesdbb40792011-11-18 17:05:22 -08001108 expandBufAdd4BE(pReply, 0);
1109
1110 DebugCallbackContext context;
Elliott Hughesdbb40792011-11-18 17:05:22 -08001111 context.pReply = pReply;
Elliott Hughesc5b734a2011-12-01 17:20:58 -08001112 context.variable_count = 0;
1113 context.with_generic = with_generic;
Elliott Hughesdbb40792011-11-18 17:05:22 -08001114
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001115 mh.GetDexFile().DecodeDebugInfo(code_item, m->IsStatic(), m->GetDexMethodIndex(), NULL,
1116 DebugCallbackContext::Callback, &context);
Elliott Hughesdbb40792011-11-18 17:05:22 -08001117
Elliott Hughesc5b734a2011-12-01 17:20:58 -08001118 JDWP::Set4BE(expandBufGetBuffer(pReply) + variable_count_offset, context.variable_count);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001119}
1120
Elliott Hughesaed4be92011-12-02 16:16:23 -08001121JDWP::JdwpTag Dbg::GetFieldBasicTag(JDWP::FieldId fieldId) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001122 return BasicTagFromDescriptor(FieldHelper(FromFieldId(fieldId)).GetTypeDescriptor());
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001123}
1124
Elliott Hughesaed4be92011-12-02 16:16:23 -08001125JDWP::JdwpTag Dbg::GetStaticFieldBasicTag(JDWP::FieldId fieldId) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001126 return BasicTagFromDescriptor(FieldHelper(FromFieldId(fieldId)).GetTypeDescriptor());
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001127}
1128
1129void Dbg::GetFieldValue(JDWP::ObjectId objectId, JDWP::FieldId fieldId, JDWP::ExpandBuf* pReply) {
Elliott Hughesaed4be92011-12-02 16:16:23 -08001130 Object* o = gRegistry->Get<Object*>(objectId);
1131 Field* f = FromFieldId(fieldId);
1132
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001133 JDWP::JdwpTag tag = BasicTagFromDescriptor(FieldHelper(f).GetTypeDescriptor());
Elliott Hughesaed4be92011-12-02 16:16:23 -08001134
1135 if (IsPrimitiveTag(tag)) {
1136 expandBufAdd1(pReply, tag);
1137 if (tag == JDWP::JT_BOOLEAN || tag == JDWP::JT_BYTE) {
1138 expandBufAdd1(pReply, f->Get32(o));
1139 } else if (tag == JDWP::JT_CHAR || tag == JDWP::JT_SHORT) {
1140 expandBufAdd2BE(pReply, f->Get32(o));
1141 } else if (tag == JDWP::JT_FLOAT || tag == JDWP::JT_INT) {
1142 expandBufAdd4BE(pReply, f->Get32(o));
1143 } else if (tag == JDWP::JT_DOUBLE || tag == JDWP::JT_LONG) {
1144 expandBufAdd8BE(pReply, f->Get64(o));
1145 } else {
Elliott Hughes3d30d9b2011-12-07 17:35:48 -08001146 LOG(FATAL) << "Unknown tag: " << tag;
Elliott Hughesaed4be92011-12-02 16:16:23 -08001147 }
1148 } else {
1149 Object* value = f->GetObject(o);
1150 expandBufAdd1(pReply, TagFromObject(value));
1151 expandBufAddObjectId(pReply, gRegistry->Add(value));
1152 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001153}
1154
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -08001155JDWP::JdwpError Dbg::SetFieldValue(JDWP::ObjectId objectId, JDWP::FieldId fieldId, uint64_t value, int width) {
Elliott Hughesaed4be92011-12-02 16:16:23 -08001156 Object* o = gRegistry->Get<Object*>(objectId);
1157 Field* f = FromFieldId(fieldId);
1158
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001159 JDWP::JdwpTag tag = BasicTagFromDescriptor(FieldHelper(f).GetTypeDescriptor());
Elliott Hughesaed4be92011-12-02 16:16:23 -08001160
1161 if (IsPrimitiveTag(tag)) {
1162 if (tag == JDWP::JT_DOUBLE || tag == JDWP::JT_LONG) {
1163 f->Set64(o, value);
1164 } else {
1165 f->Set32(o, value);
1166 }
1167 } else {
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -08001168 Object* v = gRegistry->Get<Object*>(value);
1169 Class* field_type = FieldHelper(f).GetType();
1170 if (!field_type->IsAssignableFrom(v->GetClass())) {
1171 return JDWP::ERR_INVALID_OBJECT;
1172 }
1173 f->SetObject(o, v);
Elliott Hughesaed4be92011-12-02 16:16:23 -08001174 }
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -08001175
1176 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001177}
1178
Elliott Hughes6fa602d2011-12-02 17:54:25 -08001179void Dbg::GetStaticFieldValue(JDWP::FieldId fieldId, JDWP::ExpandBuf* pReply) {
1180 GetFieldValue(0, fieldId, pReply);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001181}
1182
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -08001183JDWP::JdwpError Dbg::SetStaticFieldValue(JDWP::FieldId fieldId, uint64_t value, int width) {
1184 return SetFieldValue(0, fieldId, value, width);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001185}
1186
Elliott Hughes68fdbd02011-11-29 19:22:47 -08001187std::string Dbg::StringToUtf8(JDWP::ObjectId strId) {
1188 String* s = gRegistry->Get<String*>(strId);
1189 return s->ToModifiedUtf8();
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001190}
1191
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001192bool Dbg::GetThreadName(JDWP::ObjectId threadId, std::string& name) {
1193 ScopedThreadListLock thread_list_lock;
1194 Thread* thread = DecodeThread(threadId);
1195 if (thread == NULL) {
1196 return false;
1197 }
Elliott Hughes899e7892012-01-24 14:57:32 -08001198 StringAppendF(&name, "<%d> %s", thread->GetThinLockId(), thread->GetThreadName()->ToModifiedUtf8().c_str());
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001199 return true;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001200}
1201
Elliott Hughes2435a572012-02-17 16:07:41 -08001202JDWP::JdwpError Dbg::GetThreadGroup(JDWP::ObjectId threadId, JDWP::ExpandBuf* pReply) {
Elliott Hughes499c5132011-11-17 14:55:11 -08001203 Object* thread = gRegistry->Get<Object*>(threadId);
Elliott Hughes2435a572012-02-17 16:07:41 -08001204 if (thread != NULL) {
1205 return JDWP::ERR_INVALID_OBJECT;
1206 }
1207
1208 // Okay, so it's an object, but is it actually a thread?
1209 if (DecodeThread(threadId)) {
1210 return JDWP::ERR_INVALID_THREAD;
1211 }
Elliott Hughes499c5132011-11-17 14:55:11 -08001212
1213 Class* c = Runtime::Current()->GetClassLinker()->FindSystemClass("Ljava/lang/Thread;");
1214 CHECK(c != NULL);
1215 Field* f = c->FindInstanceField("group", "Ljava/lang/ThreadGroup;");
1216 CHECK(f != NULL);
1217 Object* group = f->GetObject(thread);
1218 CHECK(group != NULL);
Elliott Hughes2435a572012-02-17 16:07:41 -08001219 JDWP::ObjectId thread_group_id = gRegistry->Add(group);
1220
1221 expandBufAddObjectId(pReply, thread_group_id);
1222 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001223}
1224
Elliott Hughes499c5132011-11-17 14:55:11 -08001225std::string Dbg::GetThreadGroupName(JDWP::ObjectId threadGroupId) {
1226 Object* thread_group = gRegistry->Get<Object*>(threadGroupId);
1227 CHECK(thread_group != NULL);
1228
1229 Class* c = Runtime::Current()->GetClassLinker()->FindSystemClass("Ljava/lang/ThreadGroup;");
1230 CHECK(c != NULL);
1231 Field* f = c->FindInstanceField("name", "Ljava/lang/String;");
1232 CHECK(f != NULL);
1233 String* s = reinterpret_cast<String*>(f->GetObject(thread_group));
1234 return s->ToModifiedUtf8();
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001235}
1236
1237JDWP::ObjectId Dbg::GetThreadGroupParent(JDWP::ObjectId threadGroupId) {
Elliott Hughes4e235312011-12-02 11:34:15 -08001238 Object* thread_group = gRegistry->Get<Object*>(threadGroupId);
1239 CHECK(thread_group != NULL);
1240
1241 Class* c = Runtime::Current()->GetClassLinker()->FindSystemClass("Ljava/lang/ThreadGroup;");
1242 CHECK(c != NULL);
1243 Field* f = c->FindInstanceField("parent", "Ljava/lang/ThreadGroup;");
1244 CHECK(f != NULL);
1245 Object* parent = f->GetObject(thread_group);
1246 return gRegistry->Add(parent);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001247}
1248
Elliott Hughes499c5132011-11-17 14:55:11 -08001249static Object* GetStaticThreadGroup(const char* field_name) {
1250 Class* c = Runtime::Current()->GetClassLinker()->FindSystemClass("Ljava/lang/ThreadGroup;");
1251 CHECK(c != NULL);
1252 Field* f = c->FindStaticField(field_name, "Ljava/lang/ThreadGroup;");
1253 CHECK(f != NULL);
1254 Object* group = f->GetObject(NULL);
1255 CHECK(group != NULL);
1256 return group;
1257}
1258
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001259JDWP::ObjectId Dbg::GetSystemThreadGroupId() {
Elliott Hughes499c5132011-11-17 14:55:11 -08001260 return gRegistry->Add(GetStaticThreadGroup("mSystem"));
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001261}
1262
1263JDWP::ObjectId Dbg::GetMainThreadGroupId() {
Elliott Hughes499c5132011-11-17 14:55:11 -08001264 return gRegistry->Add(GetStaticThreadGroup("mMain"));
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001265}
1266
Elliott Hughes3d30d9b2011-12-07 17:35:48 -08001267bool Dbg::GetThreadStatus(JDWP::ObjectId threadId, JDWP::JdwpThreadStatus* pThreadStatus, JDWP::JdwpSuspendStatus* pSuspendStatus) {
Elliott Hughes499c5132011-11-17 14:55:11 -08001268 ScopedThreadListLock thread_list_lock;
1269
1270 Thread* thread = DecodeThread(threadId);
1271 if (thread == NULL) {
1272 return false;
1273 }
1274
1275 switch (thread->GetState()) {
1276 case Thread::kTerminated: *pThreadStatus = JDWP::TS_ZOMBIE; break;
1277 case Thread::kRunnable: *pThreadStatus = JDWP::TS_RUNNING; break;
1278 case Thread::kTimedWaiting: *pThreadStatus = JDWP::TS_SLEEPING; break;
1279 case Thread::kBlocked: *pThreadStatus = JDWP::TS_MONITOR; break;
1280 case Thread::kWaiting: *pThreadStatus = JDWP::TS_WAIT; break;
1281 case Thread::kInitializing: *pThreadStatus = JDWP::TS_ZOMBIE; break;
1282 case Thread::kStarting: *pThreadStatus = JDWP::TS_ZOMBIE; break;
1283 case Thread::kNative: *pThreadStatus = JDWP::TS_RUNNING; break;
1284 case Thread::kVmWait: *pThreadStatus = JDWP::TS_WAIT; break;
1285 case Thread::kSuspended: *pThreadStatus = JDWP::TS_RUNNING; break;
1286 default:
Elliott Hughes3d30d9b2011-12-07 17:35:48 -08001287 LOG(FATAL) << "Unknown thread state " << thread->GetState();
Elliott Hughes499c5132011-11-17 14:55:11 -08001288 }
1289
Elliott Hughes3d30d9b2011-12-07 17:35:48 -08001290 *pSuspendStatus = (thread->IsSuspended() ? JDWP::SUSPEND_STATUS_SUSPENDED : JDWP::SUSPEND_STATUS_NOT_SUSPENDED);
Elliott Hughes499c5132011-11-17 14:55:11 -08001291
1292 return true;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001293}
1294
Elliott Hughes2435a572012-02-17 16:07:41 -08001295JDWP::JdwpError Dbg::GetThreadSuspendCount(JDWP::ObjectId threadId, JDWP::ExpandBuf* pReply) {
1296 Thread* thread = DecodeThread(threadId);
1297 if (thread == NULL) {
1298 return JDWP::ERR_INVALID_THREAD;
1299 }
1300 expandBufAdd4BE(pReply, thread->GetSuspendCount());
1301 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001302}
1303
1304bool Dbg::ThreadExists(JDWP::ObjectId threadId) {
Elliott Hughes761928d2011-11-16 18:33:03 -08001305 return DecodeThread(threadId) != NULL;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001306}
1307
1308bool Dbg::IsSuspended(JDWP::ObjectId threadId) {
Elliott Hughes761928d2011-11-16 18:33:03 -08001309 return DecodeThread(threadId)->IsSuspended();
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001310}
1311
Elliott Hughesa2155262011-11-16 16:26:58 -08001312void Dbg::GetThreadGroupThreadsImpl(Object* thread_group, JDWP::ObjectId** ppThreadIds, uint32_t* pThreadCount) {
1313 struct ThreadListVisitor {
1314 static void Visit(Thread* t, void* arg) {
1315 reinterpret_cast<ThreadListVisitor*>(arg)->Visit(t);
1316 }
1317
1318 void Visit(Thread* t) {
1319 if (t == Dbg::GetDebugThread()) {
1320 // Skip the JDWP thread. Some debuggers get bent out of shape when they can't suspend and
1321 // query all threads, so it's easier if we just don't tell them about this thread.
1322 return;
1323 }
1324 if (thread_group == NULL || t->GetThreadGroup() == thread_group) {
1325 threads.push_back(gRegistry->Add(t->GetPeer()));
1326 }
1327 }
1328
1329 Object* thread_group;
1330 std::vector<JDWP::ObjectId> threads;
1331 };
1332
1333 ThreadListVisitor tlv;
1334 tlv.thread_group = thread_group;
1335
1336 {
1337 ScopedThreadListLock thread_list_lock;
1338 Runtime::Current()->GetThreadList()->ForEach(ThreadListVisitor::Visit, &tlv);
1339 }
1340
1341 *pThreadCount = tlv.threads.size();
1342 if (*pThreadCount == 0) {
1343 *ppThreadIds = NULL;
1344 } else {
1345 *ppThreadIds = new JDWP::ObjectId[*pThreadCount];
1346 for (size_t i = 0; i < *pThreadCount; ++i) {
1347 (*ppThreadIds)[i] = tlv.threads[i];
1348 }
1349 }
1350}
1351
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001352void Dbg::GetThreadGroupThreads(JDWP::ObjectId threadGroupId, JDWP::ObjectId** ppThreadIds, uint32_t* pThreadCount) {
Elliott Hughesa2155262011-11-16 16:26:58 -08001353 GetThreadGroupThreadsImpl(gRegistry->Get<Object*>(threadGroupId), ppThreadIds, pThreadCount);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001354}
1355
1356void Dbg::GetAllThreads(JDWP::ObjectId** ppThreadIds, uint32_t* pThreadCount) {
Elliott Hughesa2155262011-11-16 16:26:58 -08001357 GetThreadGroupThreadsImpl(NULL, ppThreadIds, pThreadCount);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001358}
1359
Elliott Hughes86964332012-02-15 19:37:42 -08001360static int GetStackDepth(Thread* thread) {
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001361 struct CountStackDepthVisitor : public Thread::StackVisitor {
1362 CountStackDepthVisitor() : depth(0) {}
Elliott Hughesf8a2df72011-12-01 12:19:54 -08001363 virtual void VisitFrame(const Frame& f, uintptr_t) {
1364 // TODO: we'll need to skip callee-save frames too.
1365 if (f.HasMethod()) {
1366 ++depth;
1367 }
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001368 }
1369 size_t depth;
1370 };
1371 CountStackDepthVisitor visitor;
Elliott Hughes86964332012-02-15 19:37:42 -08001372 thread->WalkStack(&visitor);
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001373 return visitor.depth;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001374}
1375
Elliott Hughes86964332012-02-15 19:37:42 -08001376int Dbg::GetThreadFrameCount(JDWP::ObjectId threadId) {
1377 ScopedThreadListLock thread_list_lock;
1378 return GetStackDepth(DecodeThread(threadId));
1379}
1380
Elliott Hughes03181a82011-11-17 17:22:21 -08001381bool Dbg::GetThreadFrame(JDWP::ObjectId threadId, int desired_frame_number, JDWP::FrameId* pFrameId, JDWP::JdwpLocation* pLoc) {
1382 ScopedThreadListLock thread_list_lock;
1383 struct GetFrameVisitor : public Thread::StackVisitor {
1384 GetFrameVisitor(int desired_frame_number, JDWP::FrameId* pFrameId, JDWP::JdwpLocation* pLoc)
Elliott Hughesba8eee12012-01-24 20:25:24 -08001385 : found(false), depth(0), desired_frame_number(desired_frame_number), pFrameId(pFrameId), pLoc(pLoc) {
Elliott Hughes03181a82011-11-17 17:22:21 -08001386 }
1387 virtual void VisitFrame(const Frame& f, uintptr_t pc) {
Elliott Hughesf8a2df72011-12-01 12:19:54 -08001388 // TODO: we'll need to skip callee-save frames too.
Elliott Hughes03181a82011-11-17 17:22:21 -08001389 if (!f.HasMethod()) {
Elliott Hughesf8a2df72011-12-01 12:19:54 -08001390 return; // The debugger can't do anything useful with a frame that has no Method*.
Elliott Hughes03181a82011-11-17 17:22:21 -08001391 }
1392
1393 if (depth == desired_frame_number) {
1394 *pFrameId = reinterpret_cast<JDWP::FrameId>(f.GetSP());
Elliott Hughesd07986f2011-12-06 18:27:45 -08001395 SetLocation(*pLoc, f.GetMethod(), pc);
Elliott Hughes03181a82011-11-17 17:22:21 -08001396 found = true;
1397 }
1398 ++depth;
1399 }
1400 bool found;
1401 int depth;
1402 int desired_frame_number;
1403 JDWP::FrameId* pFrameId;
1404 JDWP::JdwpLocation* pLoc;
1405 };
1406 GetFrameVisitor visitor(desired_frame_number, pFrameId, pLoc);
1407 visitor.desired_frame_number = desired_frame_number;
1408 DecodeThread(threadId)->WalkStack(&visitor);
1409 return visitor.found;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001410}
1411
1412JDWP::ObjectId Dbg::GetThreadSelfId() {
Elliott Hughes475fc232011-10-25 15:00:35 -07001413 return gRegistry->Add(Thread::Current()->GetPeer());
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001414}
1415
Elliott Hughes475fc232011-10-25 15:00:35 -07001416void Dbg::SuspendVM() {
Elliott Hughesa2155262011-11-16 16:26:58 -08001417 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 -07001418 Runtime::Current()->GetThreadList()->SuspendAll(true);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001419}
1420
1421void Dbg::ResumeVM() {
Elliott Hughes475fc232011-10-25 15:00:35 -07001422 Runtime::Current()->GetThreadList()->ResumeAll(true);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001423}
1424
1425void Dbg::SuspendThread(JDWP::ObjectId threadId) {
Elliott Hughes4e235312011-12-02 11:34:15 -08001426 Object* peer = gRegistry->Get<Object*>(threadId);
1427 ScopedThreadListLock thread_list_lock;
1428 Thread* thread = Thread::FromManagedThread(peer);
1429 if (thread == NULL) {
1430 LOG(WARNING) << "No such thread for suspend: " << peer;
1431 return;
1432 }
1433 Runtime::Current()->GetThreadList()->Suspend(thread, true);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001434}
1435
1436void Dbg::ResumeThread(JDWP::ObjectId threadId) {
Elliott Hughes4e235312011-12-02 11:34:15 -08001437 Object* peer = gRegistry->Get<Object*>(threadId);
1438 ScopedThreadListLock thread_list_lock;
1439 Thread* thread = Thread::FromManagedThread(peer);
1440 if (thread == NULL) {
1441 LOG(WARNING) << "No such thread for resume: " << peer;
1442 return;
1443 }
1444 Runtime::Current()->GetThreadList()->Resume(thread, true);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001445}
1446
1447void Dbg::SuspendSelf() {
Elliott Hughes475fc232011-10-25 15:00:35 -07001448 Runtime::Current()->GetThreadList()->SuspendSelfForDebugger();
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001449}
1450
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08001451static Object* GetThis(Frame& f) {
Elliott Hughes86b00102011-12-05 17:54:26 -08001452 Method* m = f.GetMethod();
Elliott Hughes86b00102011-12-05 17:54:26 -08001453 Object* o = NULL;
1454 if (!m->IsNative() && !m->IsStatic()) {
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08001455 uint16_t reg = DemangleSlot(0, m);
Elliott Hughes86b00102011-12-05 17:54:26 -08001456 o = reinterpret_cast<Object*>(f.GetVReg(m, reg));
1457 }
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08001458 return o;
1459}
1460
1461void Dbg::GetThisObject(JDWP::FrameId frameId, JDWP::ObjectId* pThisId) {
1462 Method** sp = reinterpret_cast<Method**>(frameId);
1463 Frame f(sp);
1464 Object* o = GetThis(f);
Elliott Hughes86b00102011-12-05 17:54:26 -08001465 *pThisId = gRegistry->Add(o);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001466}
1467
Elliott Hughescccd84f2011-12-05 16:51:54 -08001468void 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 -08001469 Method** sp = reinterpret_cast<Method**>(frameId);
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08001470 Frame f(sp);
Elliott Hughes68fdbd02011-11-29 19:22:47 -08001471 Method* m = f.GetMethod();
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08001472 uint16_t reg = DemangleSlot(slot, m);
Elliott Hughes68fdbd02011-11-29 19:22:47 -08001473
1474 const VmapTable vmap_table(m->GetVmapTableRaw());
1475 uint32_t vmap_offset;
1476 if (vmap_table.IsInContext(reg, vmap_offset)) {
Elliott Hughes3d30d9b2011-12-07 17:35:48 -08001477 UNIMPLEMENTED(FATAL) << "Don't know how to pull locals from callee save frames: " << vmap_offset;
Elliott Hughes68fdbd02011-11-29 19:22:47 -08001478 }
Elliott Hughesdbb40792011-11-18 17:05:22 -08001479
1480 switch (tag) {
1481 case JDWP::JT_BOOLEAN:
1482 {
Elliott Hughescccd84f2011-12-05 16:51:54 -08001483 CHECK_EQ(width, 1U);
Elliott Hughes1bba14f2011-12-01 18:00:36 -08001484 uint32_t intVal = f.GetVReg(m, reg);
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08001485 VLOG(jdwp) << "get boolean local " << reg << " = " << intVal;
Elliott Hughesdbb40792011-11-18 17:05:22 -08001486 JDWP::Set1(buf+1, intVal != 0);
1487 }
1488 break;
1489 case JDWP::JT_BYTE:
1490 {
Elliott Hughescccd84f2011-12-05 16:51:54 -08001491 CHECK_EQ(width, 1U);
Elliott Hughes1bba14f2011-12-01 18:00:36 -08001492 uint32_t intVal = f.GetVReg(m, reg);
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08001493 VLOG(jdwp) << "get byte local " << reg << " = " << intVal;
Elliott Hughesdbb40792011-11-18 17:05:22 -08001494 JDWP::Set1(buf+1, intVal);
1495 }
1496 break;
1497 case JDWP::JT_SHORT:
1498 case JDWP::JT_CHAR:
1499 {
Elliott Hughescccd84f2011-12-05 16:51:54 -08001500 CHECK_EQ(width, 2U);
Elliott Hughes1bba14f2011-12-01 18:00:36 -08001501 uint32_t intVal = f.GetVReg(m, reg);
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08001502 VLOG(jdwp) << "get short/char local " << reg << " = " << intVal;
Elliott Hughesdbb40792011-11-18 17:05:22 -08001503 JDWP::Set2BE(buf+1, intVal);
1504 }
1505 break;
1506 case JDWP::JT_INT:
1507 case JDWP::JT_FLOAT:
1508 {
Elliott Hughescccd84f2011-12-05 16:51:54 -08001509 CHECK_EQ(width, 4U);
Elliott Hughes1bba14f2011-12-01 18:00:36 -08001510 uint32_t intVal = f.GetVReg(m, reg);
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08001511 VLOG(jdwp) << "get int/float local " << reg << " = " << intVal;
Elliott Hughesdbb40792011-11-18 17:05:22 -08001512 JDWP::Set4BE(buf+1, intVal);
1513 }
1514 break;
1515 case JDWP::JT_ARRAY:
1516 {
Elliott Hughescccd84f2011-12-05 16:51:54 -08001517 CHECK_EQ(width, sizeof(JDWP::ObjectId));
Elliott Hughes68fdbd02011-11-29 19:22:47 -08001518 Object* o = reinterpret_cast<Object*>(f.GetVReg(m, reg));
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08001519 VLOG(jdwp) << "get array local " << reg << " = " << o;
Elliott Hughesdbb40792011-11-18 17:05:22 -08001520 if (o != NULL && !Heap::IsHeapAddress(o)) {
Elliott Hughes3d30d9b2011-12-07 17:35:48 -08001521 LOG(FATAL) << "Register " << reg << " expected to hold array: " << o;
Elliott Hughesdbb40792011-11-18 17:05:22 -08001522 }
1523 JDWP::SetObjectId(buf+1, gRegistry->Add(o));
1524 }
1525 break;
1526 case JDWP::JT_OBJECT:
1527 {
Elliott Hughescccd84f2011-12-05 16:51:54 -08001528 CHECK_EQ(width, sizeof(JDWP::ObjectId));
Elliott Hughes68fdbd02011-11-29 19:22:47 -08001529 Object* o = reinterpret_cast<Object*>(f.GetVReg(m, reg));
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08001530 VLOG(jdwp) << "get object local " << reg << " = " << o;
Elliott Hughesdbb40792011-11-18 17:05:22 -08001531 if (o != NULL && !Heap::IsHeapAddress(o)) {
Elliott Hughes3d30d9b2011-12-07 17:35:48 -08001532 LOG(FATAL) << "Register " << reg << " expected to hold object: " << o;
Elliott Hughesdbb40792011-11-18 17:05:22 -08001533 }
1534 tag = TagFromObject(o);
1535 JDWP::SetObjectId(buf+1, gRegistry->Add(o));
1536 }
1537 break;
1538 case JDWP::JT_DOUBLE:
1539 case JDWP::JT_LONG:
1540 {
Elliott Hughescccd84f2011-12-05 16:51:54 -08001541 CHECK_EQ(width, 8U);
Elliott Hughes1bba14f2011-12-01 18:00:36 -08001542 uint32_t lo = f.GetVReg(m, reg);
1543 uint64_t hi = f.GetVReg(m, reg + 1);
1544 uint64_t longVal = (hi << 32) | lo;
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08001545 VLOG(jdwp) << "get double/long local " << hi << ":" << lo << " = " << longVal;
Elliott Hughesdbb40792011-11-18 17:05:22 -08001546 JDWP::Set8BE(buf+1, longVal);
1547 }
1548 break;
1549 default:
Elliott Hughes3d30d9b2011-12-07 17:35:48 -08001550 LOG(FATAL) << "Unknown tag " << tag;
Elliott Hughesdbb40792011-11-18 17:05:22 -08001551 break;
1552 }
1553
1554 // Prepend tag, which may have been updated.
1555 JDWP::Set1(buf, tag);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001556}
1557
Elliott Hughesdbb40792011-11-18 17:05:22 -08001558void 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 -08001559 Method** sp = reinterpret_cast<Method**>(frameId);
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08001560 Frame f(sp);
Elliott Hughescccd84f2011-12-05 16:51:54 -08001561 Method* m = f.GetMethod();
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08001562 uint16_t reg = DemangleSlot(slot, m);
Elliott Hughescccd84f2011-12-05 16:51:54 -08001563
1564 const VmapTable vmap_table(m->GetVmapTableRaw());
1565 uint32_t vmap_offset;
1566 if (vmap_table.IsInContext(reg, vmap_offset)) {
Elliott Hughes3d30d9b2011-12-07 17:35:48 -08001567 UNIMPLEMENTED(FATAL) << "Don't know how to pull locals from callee save frames: " << vmap_offset;
Elliott Hughescccd84f2011-12-05 16:51:54 -08001568 }
1569
1570 switch (tag) {
1571 case JDWP::JT_BOOLEAN:
1572 case JDWP::JT_BYTE:
1573 CHECK_EQ(width, 1U);
1574 f.SetVReg(m, reg, static_cast<uint32_t>(value));
1575 break;
1576 case JDWP::JT_SHORT:
1577 case JDWP::JT_CHAR:
1578 CHECK_EQ(width, 2U);
1579 f.SetVReg(m, reg, static_cast<uint32_t>(value));
1580 break;
1581 case JDWP::JT_INT:
1582 case JDWP::JT_FLOAT:
1583 CHECK_EQ(width, 4U);
1584 f.SetVReg(m, reg, static_cast<uint32_t>(value));
1585 break;
1586 case JDWP::JT_ARRAY:
1587 case JDWP::JT_OBJECT:
1588 case JDWP::JT_STRING:
1589 {
1590 CHECK_EQ(width, sizeof(JDWP::ObjectId));
1591 Object* o = gRegistry->Get<Object*>(static_cast<JDWP::ObjectId>(value));
1592 f.SetVReg(m, reg, static_cast<uint32_t>(reinterpret_cast<uintptr_t>(o)));
1593 }
1594 break;
1595 case JDWP::JT_DOUBLE:
1596 case JDWP::JT_LONG:
1597 CHECK_EQ(width, 8U);
1598 f.SetVReg(m, reg, static_cast<uint32_t>(value));
1599 f.SetVReg(m, reg + 1, static_cast<uint32_t>(value >> 32));
1600 break;
1601 default:
Elliott Hughes3d30d9b2011-12-07 17:35:48 -08001602 LOG(FATAL) << "Unknown tag " << tag;
Elliott Hughescccd84f2011-12-05 16:51:54 -08001603 break;
1604 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001605}
1606
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08001607void Dbg::PostLocationEvent(const Method* m, int dex_pc, Object* this_object, int event_flags) {
1608 Class* c = m->GetDeclaringClass();
1609
1610 JDWP::JdwpLocation location;
1611 location.typeTag = c->IsInterface() ? JDWP::TT_INTERFACE : JDWP::TT_CLASS;
1612 location.classId = gRegistry->Add(c);
1613 location.methodId = ToMethodId(m);
Elliott Hughes2aa2e392012-02-17 17:15:43 -08001614 location.idx = m->IsNative() ? -1 : dex_pc / 2;
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08001615
1616 // Note we use "NoReg" so we don't keep track of references that are
1617 // never actually sent to the debugger. 'this_id' is only used to
1618 // compare against registered events...
1619 JDWP::ObjectId this_id = static_cast<JDWP::ObjectId>(reinterpret_cast<uintptr_t>(this_object));
1620 if (gJdwpState->PostLocationEvent(&location, this_id, event_flags)) {
1621 // ...unless there's a registered event, in which case we
1622 // need to really track the class and 'this'.
1623 gRegistry->Add(c);
1624 gRegistry->Add(this_object);
1625 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001626}
1627
Elliott Hughesd07986f2011-12-06 18:27:45 -08001628void Dbg::PostException(Method** sp, Method* throwMethod, uintptr_t throwNativePc, Method* catchMethod, uintptr_t catchNativePc, Object* exception) {
Ian Rogers0ad5bb82011-12-07 10:16:32 -08001629 if (!gDebuggerActive) {
1630 return;
1631 }
Elliott Hughes4740cdf2011-12-07 14:07:12 -08001632
Elliott Hughesd07986f2011-12-06 18:27:45 -08001633 JDWP::JdwpLocation throw_location;
1634 SetLocation(throw_location, throwMethod, throwNativePc);
1635 JDWP::JdwpLocation catch_location;
1636 SetLocation(catch_location, catchMethod, catchNativePc);
1637
1638 // We need 'this' for InstanceOnly filters.
1639 JDWP::ObjectId this_id;
1640 GetThisObject(reinterpret_cast<JDWP::FrameId>(sp), &this_id);
1641
1642 /*
1643 * Hand the event to the JDWP exception handler. Note we're using the
1644 * "NoReg" objectID on the exception, which is not strictly correct --
1645 * the exception object WILL be passed up to the debugger if the
1646 * debugger is interested in the event. We do this because the current
1647 * implementation of the debugger object registry never throws anything
1648 * away, and some people were experiencing a fatal build up of exception
1649 * objects when dealing with certain libraries.
1650 */
1651 JDWP::ObjectId exception_id = static_cast<JDWP::ObjectId>(reinterpret_cast<uintptr_t>(exception));
1652 JDWP::RefTypeId exception_class_id = gRegistry->Add(exception->GetClass());
1653
1654 gJdwpState->PostException(&throw_location, exception_id, exception_class_id, &catch_location, this_id);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001655}
1656
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001657void Dbg::PostClassPrepare(Class* c) {
Elliott Hughes4740cdf2011-12-07 14:07:12 -08001658 if (!gDebuggerActive) {
1659 return;
1660 }
1661
Elliott Hughes3d30d9b2011-12-07 17:35:48 -08001662 // OLD-TODO - we currently always send both "verified" and "prepared" since
Elliott Hughes4740cdf2011-12-07 14:07:12 -08001663 // debuggers seem to like that. There might be some advantage to honesty,
1664 // since the class may not yet be verified.
1665 int state = JDWP::CS_VERIFIED | JDWP::CS_PREPARED;
1666 JDWP::JdwpTypeTag tag = c->IsInterface() ? JDWP::TT_INTERFACE : JDWP::TT_CLASS;
1667 gJdwpState->PostClassPrepare(tag, gRegistry->Add(c), ClassHelper(c).GetDescriptor(), state);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001668}
1669
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08001670void Dbg::UpdateDebugger(int32_t dex_pc, Thread* self, Method** sp) {
Elliott Hughes2aa2e392012-02-17 17:15:43 -08001671 if (!gDebuggerActive || dex_pc == -2 /* fake method exit */) {
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08001672 return;
1673 }
1674
Elliott Hughes86964332012-02-15 19:37:42 -08001675 Frame f(sp);
1676 f.Next(); // Skip callee save frame.
1677 Method* m = f.GetMethod();
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08001678
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08001679 if (dex_pc == -1) {
Elliott Hughes2aa2e392012-02-17 17:15:43 -08001680 // We use a pc of -1 to represent method entry, since we might branch back to pc 0 later.
1681 // This means that for this special notification, there can't be anything else interesting
1682 // going on, so we're done already.
1683 Dbg::PostLocationEvent(m, 0, GetThis(f), kMethodEntry);
1684 return;
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08001685 }
1686
Elliott Hughes2aa2e392012-02-17 17:15:43 -08001687 int event_flags = 0;
1688
Elliott Hughes86964332012-02-15 19:37:42 -08001689 if (IsBreakpoint(m, dex_pc)) {
1690 event_flags |= kBreakpoint;
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08001691 }
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08001692
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08001693 // If the debugger is single-stepping one of our threads, check to
1694 // see if we're that thread and we've reached a step point.
Elliott Hughes86964332012-02-15 19:37:42 -08001695 if (gSingleStepControl.is_active && gSingleStepControl.thread == self) {
1696 CHECK(!m->IsNative());
1697 if (gSingleStepControl.step_depth == JDWP::SD_INTO) {
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08001698 // Step into method calls. We break when the line number
1699 // or method pointer changes. If we're in SS_MIN mode, we
1700 // always stop.
Elliott Hughes86964332012-02-15 19:37:42 -08001701 if (gSingleStepControl.method != m) {
1702 event_flags |= kSingleStep;
1703 VLOG(jdwp) << "SS new method";
1704 } else if (gSingleStepControl.step_size == JDWP::SS_MIN) {
1705 event_flags |= kSingleStep;
1706 VLOG(jdwp) << "SS new instruction";
Elliott Hughes2435a572012-02-17 16:07:41 -08001707 } else if (gSingleStepControl.dex_pcs.find(dex_pc) == gSingleStepControl.dex_pcs.end()) {
1708 event_flags |= kSingleStep;
1709 VLOG(jdwp) << "SS new line";
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08001710 }
Elliott Hughes86964332012-02-15 19:37:42 -08001711 } else if (gSingleStepControl.step_depth == JDWP::SD_OVER) {
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08001712 // Step over method calls. We break when the line number is
1713 // different and the frame depth is <= the original frame
1714 // depth. (We can't just compare on the method, because we
1715 // might get unrolled past it by an exception, and it's tricky
1716 // to identify recursion.)
Elliott Hughes86964332012-02-15 19:37:42 -08001717
1718 // TODO: can we just use the value of 'sp'?
1719 int stack_depth = GetStackDepth(self);
1720
1721 if (stack_depth < gSingleStepControl.stack_depth) {
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08001722 // popped up one or more frames, always trigger
Elliott Hughes86964332012-02-15 19:37:42 -08001723 event_flags |= kSingleStep;
1724 VLOG(jdwp) << "SS method pop";
1725 } else if (stack_depth == gSingleStepControl.stack_depth) {
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08001726 // same depth, see if we moved
Elliott Hughes86964332012-02-15 19:37:42 -08001727 if (gSingleStepControl.step_size == JDWP::SS_MIN) {
1728 event_flags |= kSingleStep;
1729 VLOG(jdwp) << "SS new instruction";
Elliott Hughes2435a572012-02-17 16:07:41 -08001730 } else if (gSingleStepControl.dex_pcs.find(dex_pc) == gSingleStepControl.dex_pcs.end()) {
1731 event_flags |= kSingleStep;
1732 VLOG(jdwp) << "SS new line";
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08001733 }
1734 }
1735 } else {
Elliott Hughes86964332012-02-15 19:37:42 -08001736 CHECK_EQ(gSingleStepControl.step_depth, JDWP::SD_OUT);
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08001737 // Return from the current method. We break when the frame
1738 // depth pops up.
1739
1740 // This differs from the "method exit" break in that it stops
1741 // with the PC at the next instruction in the returned-to
1742 // function, rather than the end of the returning function.
Elliott Hughes86964332012-02-15 19:37:42 -08001743
1744 // TODO: can we just use the value of 'sp'?
1745 int stack_depth = GetStackDepth(self);
1746 if (stack_depth < gSingleStepControl.stack_depth) {
1747 event_flags |= kSingleStep;
1748 VLOG(jdwp) << "SS method pop";
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08001749 }
1750 }
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08001751 }
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08001752
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08001753 // Check to see if this is a "return" instruction. JDWP says we should
1754 // send the event *after* the code has been executed, but it also says
1755 // the location we provide is the last instruction. Since the "return"
1756 // instruction has no interesting side effects, we should be safe.
1757 // (We can't just move this down to the returnFromMethod label because
1758 // we potentially need to combine it with other events.)
1759 // We're also not supposed to generate a method exit event if the method
1760 // terminates "with a thrown exception".
Elliott Hughes86964332012-02-15 19:37:42 -08001761 if (dex_pc >= 0) {
1762 const DexFile::CodeItem* code_item = MethodHelper(m).GetCodeItem();
1763 CHECK(code_item != NULL);
1764 CHECK_LT(dex_pc, static_cast<int32_t>(code_item->insns_size_in_code_units_));
1765 if (Instruction::At(&code_item->insns_[dex_pc])->IsReturn()) {
1766 event_flags |= kMethodExit;
1767 }
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08001768 }
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08001769
1770 // If there's something interesting going on, see if it matches one
1771 // of the debugger filters.
1772 if (event_flags != 0) {
Elliott Hughes86964332012-02-15 19:37:42 -08001773 Dbg::PostLocationEvent(m, dex_pc, GetThis(f), event_flags);
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08001774 }
1775}
1776
Elliott Hughes86964332012-02-15 19:37:42 -08001777void Dbg::WatchLocation(const JDWP::JdwpLocation* location) {
1778 MutexLock mu(gBreakpointsLock);
1779 Method* m = FromMethodId(location->methodId);
1780 gBreakpoints.push_back(Breakpoint(m, location->idx));
1781 VLOG(jdwp) << "Set breakpoint #" << (gBreakpoints.size() - 1) << ": " << gBreakpoints[gBreakpoints.size() - 1];
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001782}
1783
Elliott Hughes86964332012-02-15 19:37:42 -08001784void Dbg::UnwatchLocation(const JDWP::JdwpLocation* location) {
1785 MutexLock mu(gBreakpointsLock);
1786 Method* m = FromMethodId(location->methodId);
1787 for (size_t i = 0; i < gBreakpoints.size(); ++i) {
1788 if (gBreakpoints[i].method == m && gBreakpoints[i].pc == location->idx) {
1789 VLOG(jdwp) << "Removed breakpoint #" << i << ": " << gBreakpoints[i];
1790 gBreakpoints.erase(gBreakpoints.begin() + i);
1791 return;
1792 }
1793 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001794}
1795
Elliott Hughes2435a572012-02-17 16:07:41 -08001796JDWP::JdwpError Dbg::ConfigureStep(JDWP::ObjectId threadId, JDWP::JdwpStepSize step_size, JDWP::JdwpStepDepth step_depth) {
Elliott Hughes86964332012-02-15 19:37:42 -08001797 Thread* thread = DecodeThread(threadId);
Elliott Hughes2435a572012-02-17 16:07:41 -08001798 if (thread == NULL) {
1799 return JDWP::ERR_INVALID_THREAD;
1800 }
Elliott Hughes86964332012-02-15 19:37:42 -08001801
1802 // TODO: there's no theoretical reason why we couldn't support single-stepping
1803 // of multiple threads at once, but we never did so historically.
1804 if (gSingleStepControl.thread != NULL && thread != gSingleStepControl.thread) {
1805 LOG(WARNING) << "single-step already active for " << *gSingleStepControl.thread
1806 << "; switching to " << *thread;
1807 }
1808
Elliott Hughes2435a572012-02-17 16:07:41 -08001809 //
1810 // Work out what Method* we're in, the current line number, and how deep the stack currently
1811 // is for step-out.
1812 //
1813
Elliott Hughes86964332012-02-15 19:37:42 -08001814 struct SingleStepStackVisitor : public Thread::StackVisitor {
1815 SingleStepStackVisitor() {
1816 gSingleStepControl.method = NULL;
1817 gSingleStepControl.stack_depth = 0;
1818 }
Elliott Hughes2435a572012-02-17 16:07:41 -08001819 virtual void VisitFrame(const Frame& f, uintptr_t pc) {
Elliott Hughes86964332012-02-15 19:37:42 -08001820 // TODO: we'll need to skip callee-save frames too.
1821 if (f.HasMethod()) {
1822 ++gSingleStepControl.stack_depth;
1823 if (gSingleStepControl.method == NULL) {
Elliott Hughes2435a572012-02-17 16:07:41 -08001824 const Method* m = f.GetMethod();
1825 const DexCache* dex_cache = m->GetDeclaringClass()->GetDexCache();
1826 gSingleStepControl.method = m;
1827 gSingleStepControl.line_number = -1;
1828 if (dex_cache != NULL) {
1829 const DexFile& dex_file = Runtime::Current()->GetClassLinker()->FindDexFile(dex_cache);
1830 gSingleStepControl.line_number = dex_file.GetLineNumFromPC(m, m->ToDexPC(pc));
1831 }
Elliott Hughes86964332012-02-15 19:37:42 -08001832 }
1833 }
1834 }
1835 };
1836 SingleStepStackVisitor visitor;
1837 thread->WalkStack(&visitor);
1838
Elliott Hughes2435a572012-02-17 16:07:41 -08001839 //
1840 // Find the dex_pc values that correspond to the current line, for line-based single-stepping.
1841 //
1842
1843 struct DebugCallbackContext {
1844 DebugCallbackContext() {
1845 last_pc_valid = false;
1846 last_pc = 0;
1847 gSingleStepControl.dex_pcs.clear();
1848 }
1849
1850 static bool Callback(void* raw_context, uint32_t address, uint32_t line_number) {
1851 DebugCallbackContext* context = reinterpret_cast<DebugCallbackContext*>(raw_context);
1852 if (static_cast<int32_t>(line_number) == gSingleStepControl.line_number) {
1853 if (!context->last_pc_valid) {
1854 // Everything from this address until the next line change is ours.
1855 context->last_pc = address;
1856 context->last_pc_valid = true;
1857 }
1858 // Otherwise, if we're already in a valid range for this line,
1859 // just keep going (shouldn't really happen)...
1860 } else if (context->last_pc_valid) { // and the line number is new
1861 // Add everything from the last entry up until here to the set
1862 for (uint32_t dex_pc = context->last_pc; dex_pc < address; ++dex_pc) {
1863 gSingleStepControl.dex_pcs.insert(dex_pc);
1864 }
1865 context->last_pc_valid = false;
1866 }
1867 return false; // There may be multiple entries for any given line.
1868 }
1869
1870 ~DebugCallbackContext() {
1871 // If the line number was the last in the position table...
1872 if (last_pc_valid) {
1873 size_t end = MethodHelper(gSingleStepControl.method).GetCodeItem()->insns_size_in_code_units_;
1874 for (uint32_t dex_pc = last_pc; dex_pc < end; ++dex_pc) {
1875 gSingleStepControl.dex_pcs.insert(dex_pc);
1876 }
1877 }
1878 }
1879
1880 bool last_pc_valid;
1881 uint32_t last_pc;
1882 };
1883 DebugCallbackContext context;
1884 const Method* m = gSingleStepControl.method;
1885 MethodHelper mh(m);
1886 mh.GetDexFile().DecodeDebugInfo(mh.GetCodeItem(), m->IsStatic(), m->GetDexMethodIndex(),
1887 DebugCallbackContext::Callback, NULL, &context);
1888
1889 //
1890 // Everything else...
1891 //
1892
Elliott Hughes86964332012-02-15 19:37:42 -08001893 gSingleStepControl.thread = thread;
1894 gSingleStepControl.step_size = step_size;
1895 gSingleStepControl.step_depth = step_depth;
1896 gSingleStepControl.is_active = true;
1897
Elliott Hughes2435a572012-02-17 16:07:41 -08001898 if (VLOG_IS_ON(jdwp)) {
1899 VLOG(jdwp) << "Single-step thread: " << *gSingleStepControl.thread;
1900 VLOG(jdwp) << "Single-step step size: " << gSingleStepControl.step_size;
1901 VLOG(jdwp) << "Single-step step depth: " << gSingleStepControl.step_depth;
1902 VLOG(jdwp) << "Single-step current method: " << PrettyMethod(gSingleStepControl.method);
1903 VLOG(jdwp) << "Single-step current line: " << gSingleStepControl.line_number;
1904 VLOG(jdwp) << "Single-step current stack depth: " << gSingleStepControl.stack_depth;
1905 VLOG(jdwp) << "Single-step dex_pc values:";
1906 for (std::set<uint32_t>::iterator it = gSingleStepControl.dex_pcs.begin() ; it != gSingleStepControl.dex_pcs.end(); ++it) {
1907 VLOG(jdwp) << " " << *it;
1908 }
1909 }
1910
1911 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001912}
1913
1914void Dbg::UnconfigureStep(JDWP::ObjectId threadId) {
Elliott Hughes86964332012-02-15 19:37:42 -08001915 gSingleStepControl.is_active = false;
1916 gSingleStepControl.thread = NULL;
Elliott Hughes2435a572012-02-17 16:07:41 -08001917 gSingleStepControl.dex_pcs.clear();
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001918}
1919
Elliott Hughesd07986f2011-12-06 18:27:45 -08001920JDWP::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* pExceptionId) {
1921 ThreadList* thread_list = Runtime::Current()->GetThreadList();
1922
1923 Thread* targetThread = NULL;
1924 DebugInvokeReq* req = NULL;
1925 {
1926 ScopedThreadListLock thread_list_lock;
1927 targetThread = DecodeThread(threadId);
1928 if (targetThread == NULL) {
1929 LOG(ERROR) << "InvokeMethod request for non-existent thread " << threadId;
1930 return JDWP::ERR_INVALID_THREAD;
1931 }
1932 req = targetThread->GetInvokeReq();
1933 if (!req->ready) {
1934 LOG(ERROR) << "InvokeMethod request for thread not stopped by event: " << *targetThread;
1935 return JDWP::ERR_INVALID_THREAD;
1936 }
1937
1938 /*
1939 * We currently have a bug where we don't successfully resume the
1940 * target thread if the suspend count is too deep. We're expected to
1941 * require one "resume" for each "suspend", but when asked to execute
1942 * a method we have to resume fully and then re-suspend it back to the
1943 * same level. (The easiest way to cause this is to type "suspend"
1944 * multiple times in jdb.)
1945 *
1946 * It's unclear what this means when the event specifies "resume all"
1947 * and some threads are suspended more deeply than others. This is
1948 * a rare problem, so for now we just prevent it from hanging forever
1949 * by rejecting the method invocation request. Without this, we will
1950 * be stuck waiting on a suspended thread.
1951 */
1952 int suspend_count = targetThread->GetSuspendCount();
1953 if (suspend_count > 1) {
1954 LOG(ERROR) << *targetThread << " suspend count too deep for method invocation: " << suspend_count;
1955 return JDWP::ERR_THREAD_SUSPENDED; // Probably not expected here.
1956 }
1957
1958 /*
Elliott Hughes3d30d9b2011-12-07 17:35:48 -08001959 * OLD-TODO: ought to screen the various IDs, and verify that the argument
Elliott Hughesd07986f2011-12-06 18:27:45 -08001960 * list is valid.
1961 */
1962 req->receiver_ = gRegistry->Get<Object*>(objectId);
1963 req->thread_ = gRegistry->Get<Object*>(threadId);
1964 req->class_ = gRegistry->Get<Class*>(classId);
1965 req->method_ = FromMethodId(methodId);
1966 req->num_args_ = numArgs;
1967 req->arg_array_ = argArray;
1968 req->options_ = options;
1969 req->invoke_needed_ = true;
1970 }
1971
1972 // The fact that we've released the thread list lock is a bit risky --- if the thread goes
1973 // away we're sitting high and dry -- but we must release this before the ResumeAllThreads
1974 // call, and it's unwise to hold it during WaitForSuspend.
1975
1976 {
1977 /*
1978 * We change our (JDWP thread) status, which should be THREAD_RUNNING,
1979 * so the VM can suspend for a GC if the invoke request causes us to
1980 * run out of memory. It's also a good idea to change it before locking
1981 * the invokeReq mutex, although that should never be held for long.
1982 */
1983 ScopedThreadStateChange tsc(Thread::Current(), Thread::kVmWait);
1984
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08001985 VLOG(jdwp) << " Transferring control to event thread";
Elliott Hughesd07986f2011-12-06 18:27:45 -08001986 {
1987 MutexLock mu(req->lock_);
1988
1989 if ((options & JDWP::INVOKE_SINGLE_THREADED) == 0) {
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08001990 VLOG(jdwp) << " Resuming all threads";
Elliott Hughesd07986f2011-12-06 18:27:45 -08001991 thread_list->ResumeAll(true);
1992 } else {
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08001993 VLOG(jdwp) << " Resuming event thread only";
Elliott Hughesd07986f2011-12-06 18:27:45 -08001994 thread_list->Resume(targetThread, true);
1995 }
1996
1997 // Wait for the request to finish executing.
1998 while (req->invoke_needed_) {
1999 req->cond_.Wait(req->lock_);
2000 }
2001 }
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08002002 VLOG(jdwp) << " Control has returned from event thread";
Elliott Hughesd07986f2011-12-06 18:27:45 -08002003
2004 /* wait for thread to re-suspend itself */
2005 targetThread->WaitUntilSuspended();
2006 //dvmWaitForSuspend(targetThread);
2007 }
2008
2009 /*
2010 * Suspend the threads. We waited for the target thread to suspend
2011 * itself, so all we need to do is suspend the others.
2012 *
2013 * The suspendAllThreads() call will double-suspend the event thread,
2014 * so we want to resume the target thread once to keep the books straight.
2015 */
2016 if ((options & JDWP::INVOKE_SINGLE_THREADED) == 0) {
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08002017 VLOG(jdwp) << " Suspending all threads";
Elliott Hughesd07986f2011-12-06 18:27:45 -08002018 thread_list->SuspendAll(true);
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08002019 VLOG(jdwp) << " Resuming event thread to balance the count";
Elliott Hughesd07986f2011-12-06 18:27:45 -08002020 thread_list->Resume(targetThread, true);
2021 }
2022
2023 // Copy the result.
2024 *pResultTag = req->result_tag;
2025 if (IsPrimitiveTag(req->result_tag)) {
2026 *pResultValue = req->result_value.j;
2027 } else {
2028 *pResultValue = gRegistry->Add(req->result_value.l);
2029 }
2030 *pExceptionId = req->exception;
2031 return req->error;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002032}
2033
2034void Dbg::ExecuteMethod(DebugInvokeReq* pReq) {
Elliott Hughesd07986f2011-12-06 18:27:45 -08002035 Thread* self = Thread::Current();
2036
2037 // We can be called while an exception is pending in the VM. We need
2038 // to preserve that across the method invocation.
2039 SirtRef<Throwable> old_exception(self->GetException());
2040 self->ClearException();
2041
2042 ScopedThreadStateChange tsc(self, Thread::kRunnable);
2043
2044 // Translate the method through the vtable, unless the debugger wants to suppress it.
2045 Method* m = pReq->method_;
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08002046 VLOG(jdwp) << "ExecuteMethod " << PrettyMethod(m);
Elliott Hughesd07986f2011-12-06 18:27:45 -08002047 if ((pReq->options_ & JDWP::INVOKE_NONVIRTUAL) == 0 && pReq->receiver_ != NULL) {
2048 m = pReq->class_->FindVirtualMethodForVirtualOrInterface(pReq->method_);
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08002049 VLOG(jdwp) << "ExecuteMethod " << PrettyMethod(m);
Elliott Hughesd07986f2011-12-06 18:27:45 -08002050 }
2051 CHECK(m != NULL);
2052
2053 CHECK_EQ(sizeof(jvalue), sizeof(uint64_t));
2054
2055 pReq->result_value = InvokeWithJValues(self, pReq->receiver_, m, reinterpret_cast<JValue*>(pReq->arg_array_));
2056
2057 pReq->exception = gRegistry->Add(self->GetException());
2058 pReq->result_tag = BasicTagFromDescriptor(MethodHelper(m).GetShorty());
2059 if (pReq->exception != 0) {
2060 Object* exc = self->GetException();
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08002061 VLOG(jdwp) << " JDWP invocation returning with exception=" << exc << " " << PrettyTypeOf(exc);
Elliott Hughesd07986f2011-12-06 18:27:45 -08002062 self->ClearException();
2063 pReq->result_value.j = 0;
2064 } else if (pReq->result_tag == JDWP::JT_OBJECT) {
2065 /* if no exception thrown, examine object result more closely */
2066 JDWP::JdwpTag new_tag = TagFromObject(pReq->result_value.l);
2067 if (new_tag != pReq->result_tag) {
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08002068 VLOG(jdwp) << " JDWP promoted result from " << pReq->result_tag << " to " << new_tag;
Elliott Hughesd07986f2011-12-06 18:27:45 -08002069 pReq->result_tag = new_tag;
2070 }
2071
2072 /*
2073 * Register the object. We don't actually need an ObjectId yet,
2074 * but we do need to be sure that the GC won't move or discard the
2075 * object when we switch out of RUNNING. The ObjectId conversion
2076 * will add the object to the "do not touch" list.
2077 *
2078 * We can't use the "tracked allocation" mechanism here because
2079 * the object is going to be handed off to a different thread.
2080 */
2081 gRegistry->Add(pReq->result_value.l);
2082 }
2083
2084 if (old_exception.get() != NULL) {
2085 self->SetException(old_exception.get());
2086 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002087}
2088
Elliott Hughesd07986f2011-12-06 18:27:45 -08002089/*
2090 * Register an object ID that might not have been registered previously.
2091 *
2092 * Normally this wouldn't happen -- the conversion to an ObjectId would
2093 * have added the object to the registry -- but in some cases (e.g.
2094 * throwing exceptions) we really want to do the registration late.
2095 */
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002096void Dbg::RegisterObjectId(JDWP::ObjectId id) {
Elliott Hughesd07986f2011-12-06 18:27:45 -08002097 gRegistry->Add(reinterpret_cast<Object*>(id));
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002098}
2099
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07002100/*
2101 * "buf" contains a full JDWP packet, possibly with multiple chunks. We
2102 * need to process each, accumulate the replies, and ship the whole thing
2103 * back.
2104 *
2105 * Returns "true" if we have a reply. The reply buffer is newly allocated,
2106 * and includes the chunk type/length, followed by the data.
2107 *
Elliott Hughes3d30d9b2011-12-07 17:35:48 -08002108 * OLD-TODO: we currently assume that the request and reply include a single
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07002109 * chunk. If this becomes inconvenient we will need to adapt.
2110 */
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002111bool Dbg::DdmHandlePacket(const uint8_t* buf, int dataLen, uint8_t** pReplyBuf, int* pReplyLen) {
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07002112 CHECK_GE(dataLen, 0);
2113
2114 Thread* self = Thread::Current();
2115 JNIEnv* env = self->GetJniEnv();
2116
Elliott Hughes844f9a02012-01-24 20:19:58 -08002117 static jclass Chunk_class = CacheClass(env, "org/apache/harmony/dalvik/ddmc/Chunk");
2118 static jclass DdmServer_class = CacheClass(env, "org/apache/harmony/dalvik/ddmc/DdmServer");
2119 static jmethodID dispatch_mid = env->GetStaticMethodID(DdmServer_class, "dispatch", "(I[BII)Lorg/apache/harmony/dalvik/ddmc/Chunk;");
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07002120 static jfieldID data_fid = env->GetFieldID(Chunk_class, "data", "[B");
2121 static jfieldID length_fid = env->GetFieldID(Chunk_class, "length", "I");
2122 static jfieldID offset_fid = env->GetFieldID(Chunk_class, "offset", "I");
2123 static jfieldID type_fid = env->GetFieldID(Chunk_class, "type", "I");
2124
2125 // Create a byte[] corresponding to 'buf'.
Elliott Hughes6a5bd492011-10-28 14:33:57 -07002126 ScopedLocalRef<jbyteArray> dataArray(env, env->NewByteArray(dataLen));
2127 if (dataArray.get() == NULL) {
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07002128 LOG(WARNING) << "byte[] allocation failed: " << dataLen;
2129 env->ExceptionClear();
2130 return false;
2131 }
Elliott Hughes6a5bd492011-10-28 14:33:57 -07002132 env->SetByteArrayRegion(dataArray.get(), 0, dataLen, reinterpret_cast<const jbyte*>(buf));
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07002133
2134 const int kChunkHdrLen = 8;
2135
2136 // Run through and find all chunks. [Currently just find the first.]
Elliott Hughes6a5bd492011-10-28 14:33:57 -07002137 ScopedByteArrayRO contents(env, dataArray.get());
Elliott Hughesf7c3b662011-10-27 12:04:56 -07002138 jint type = JDWP::Get4BE(reinterpret_cast<const uint8_t*>(&contents[0]));
2139 jint length = JDWP::Get4BE(reinterpret_cast<const uint8_t*>(&contents[4]));
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07002140 jint offset = kChunkHdrLen;
2141 if (offset + length > dataLen) {
2142 LOG(WARNING) << StringPrintf("bad chunk found (len=%u pktLen=%d)", length, dataLen);
2143 return false;
2144 }
2145
2146 // Call "private static Chunk dispatch(int type, byte[] data, int offset, int length)".
Elliott Hughes6a5bd492011-10-28 14:33:57 -07002147 ScopedLocalRef<jobject> chunk(env, env->CallStaticObjectMethod(DdmServer_class, dispatch_mid, type, dataArray.get(), offset, length));
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07002148 if (env->ExceptionCheck()) {
2149 LOG(INFO) << StringPrintf("Exception thrown by dispatcher for 0x%08x", type);
2150 env->ExceptionDescribe();
2151 env->ExceptionClear();
2152 return false;
2153 }
2154
Elliott Hughes6a5bd492011-10-28 14:33:57 -07002155 if (chunk.get() == NULL) {
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07002156 return false;
2157 }
2158
2159 /*
2160 * Pull the pieces out of the chunk. We copy the results into a
2161 * newly-allocated buffer that the caller can free. We don't want to
2162 * continue using the Chunk object because nothing has a reference to it.
2163 *
2164 * We could avoid this by returning type/data/offset/length and having
2165 * the caller be aware of the object lifetime issues, but that
2166 * integrates the JDWP code more tightly into the VM, and doesn't work
2167 * if we have responses for multiple chunks.
2168 *
2169 * So we're pretty much stuck with copying data around multiple times.
2170 */
Elliott Hughes6a5bd492011-10-28 14:33:57 -07002171 ScopedLocalRef<jbyteArray> replyData(env, reinterpret_cast<jbyteArray>(env->GetObjectField(chunk.get(), data_fid)));
2172 length = env->GetIntField(chunk.get(), length_fid);
2173 offset = env->GetIntField(chunk.get(), offset_fid);
2174 type = env->GetIntField(chunk.get(), type_fid);
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07002175
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08002176 VLOG(jdwp) << StringPrintf("DDM reply: type=0x%08x data=%p offset=%d length=%d", type, replyData.get(), offset, length);
Elliott Hughes6a5bd492011-10-28 14:33:57 -07002177 if (length == 0 || replyData.get() == NULL) {
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07002178 return false;
2179 }
2180
Elliott Hughes6a5bd492011-10-28 14:33:57 -07002181 jsize replyLength = env->GetArrayLength(replyData.get());
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07002182 if (offset + length > replyLength) {
2183 LOG(WARNING) << StringPrintf("chunk off=%d len=%d exceeds reply array len %d", offset, length, replyLength);
2184 return false;
2185 }
2186
2187 uint8_t* reply = new uint8_t[length + kChunkHdrLen];
2188 if (reply == NULL) {
2189 LOG(WARNING) << "malloc failed: " << (length + kChunkHdrLen);
2190 return false;
2191 }
Elliott Hughesf7c3b662011-10-27 12:04:56 -07002192 JDWP::Set4BE(reply + 0, type);
2193 JDWP::Set4BE(reply + 4, length);
Elliott Hughes6a5bd492011-10-28 14:33:57 -07002194 env->GetByteArrayRegion(replyData.get(), offset, length, reinterpret_cast<jbyte*>(reply + kChunkHdrLen));
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07002195
2196 *pReplyBuf = reply;
2197 *pReplyLen = length + kChunkHdrLen;
2198
Elliott Hughesba8eee12012-01-24 20:25:24 -08002199 VLOG(jdwp) << StringPrintf("dvmHandleDdm returning type=%.4s buf=%p len=%d", reinterpret_cast<char*>(reply), reply, length);
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07002200 return true;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002201}
2202
Elliott Hughesa2155262011-11-16 16:26:58 -08002203void Dbg::DdmBroadcast(bool connect) {
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08002204 VLOG(jdwp) << "Broadcasting DDM " << (connect ? "connect" : "disconnect") << "...";
Elliott Hughes47fce012011-10-25 18:37:19 -07002205
2206 Thread* self = Thread::Current();
2207 if (self->GetState() != Thread::kRunnable) {
2208 LOG(ERROR) << "DDM broadcast in thread state " << self->GetState();
2209 /* try anyway? */
2210 }
2211
2212 JNIEnv* env = self->GetJniEnv();
Elliott Hughes844f9a02012-01-24 20:19:58 -08002213 static jclass DdmServer_class = CacheClass(env, "org/apache/harmony/dalvik/ddmc/DdmServer");
Elliott Hughes47fce012011-10-25 18:37:19 -07002214 static jmethodID broadcast_mid = env->GetStaticMethodID(DdmServer_class, "broadcast", "(I)V");
2215 jint event = connect ? 1 /*DdmServer.CONNECTED*/ : 2 /*DdmServer.DISCONNECTED*/;
2216 env->CallStaticVoidMethod(DdmServer_class, broadcast_mid, event);
2217 if (env->ExceptionCheck()) {
2218 LOG(ERROR) << "DdmServer.broadcast " << event << " failed";
2219 env->ExceptionDescribe();
2220 env->ExceptionClear();
2221 }
2222}
2223
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002224void Dbg::DdmConnected() {
Elliott Hughesa2155262011-11-16 16:26:58 -08002225 Dbg::DdmBroadcast(true);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002226}
2227
2228void Dbg::DdmDisconnected() {
Elliott Hughesa2155262011-11-16 16:26:58 -08002229 Dbg::DdmBroadcast(false);
Elliott Hughes47fce012011-10-25 18:37:19 -07002230 gDdmThreadNotification = false;
2231}
2232
2233/*
Elliott Hughes82188472011-11-07 18:11:48 -08002234 * Send a notification when a thread starts, stops, or changes its name.
Elliott Hughes47fce012011-10-25 18:37:19 -07002235 *
2236 * Because we broadcast the full set of threads when the notifications are
2237 * first enabled, it's possible for "thread" to be actively executing.
2238 */
Elliott Hughes82188472011-11-07 18:11:48 -08002239void Dbg::DdmSendThreadNotification(Thread* t, uint32_t type) {
Elliott Hughes47fce012011-10-25 18:37:19 -07002240 if (!gDdmThreadNotification) {
2241 return;
2242 }
2243
Elliott Hughes82188472011-11-07 18:11:48 -08002244 if (type == CHUNK_TYPE("THDE")) {
Elliott Hughes47fce012011-10-25 18:37:19 -07002245 uint8_t buf[4];
Elliott Hughesf7c3b662011-10-27 12:04:56 -07002246 JDWP::Set4BE(&buf[0], t->GetThinLockId());
Elliott Hughes47fce012011-10-25 18:37:19 -07002247 Dbg::DdmSendChunk(CHUNK_TYPE("THDE"), 4, buf);
Elliott Hughes82188472011-11-07 18:11:48 -08002248 } else {
2249 CHECK(type == CHUNK_TYPE("THCR") || type == CHUNK_TYPE("THNM")) << type;
Elliott Hughes899e7892012-01-24 14:57:32 -08002250 SirtRef<String> name(t->GetThreadName());
Elliott Hughes82188472011-11-07 18:11:48 -08002251 size_t char_count = (name.get() != NULL) ? name->GetLength() : 0;
2252 const jchar* chars = name->GetCharArray()->GetData();
2253
Elliott Hughes21f32d72011-11-09 17:44:13 -08002254 std::vector<uint8_t> bytes;
Elliott Hughes545a0642011-11-08 19:10:03 -08002255 JDWP::Append4BE(bytes, t->GetThinLockId());
2256 JDWP::AppendUtf16BE(bytes, chars, char_count);
Elliott Hughes21f32d72011-11-09 17:44:13 -08002257 CHECK_EQ(bytes.size(), char_count*2 + sizeof(uint32_t)*2);
2258 Dbg::DdmSendChunk(type, bytes);
Elliott Hughes47fce012011-10-25 18:37:19 -07002259 }
2260}
2261
Elliott Hughesa2155262011-11-16 16:26:58 -08002262static void DdmSendThreadStartCallback(Thread* t, void*) {
Elliott Hughes82188472011-11-07 18:11:48 -08002263 Dbg::DdmSendThreadNotification(t, CHUNK_TYPE("THCR"));
Elliott Hughes47fce012011-10-25 18:37:19 -07002264}
2265
2266void Dbg::DdmSetThreadNotification(bool enable) {
2267 // We lock the thread list to avoid sending duplicate events or missing
2268 // a thread change. We should be okay holding this lock while sending
2269 // the messages out. (We have to hold it while accessing a live thread.)
Elliott Hughesbbd9d832011-11-07 14:40:00 -08002270 ScopedThreadListLock thread_list_lock;
Elliott Hughes47fce012011-10-25 18:37:19 -07002271
2272 gDdmThreadNotification = enable;
2273 if (enable) {
Elliott Hughesbfe487b2011-10-26 15:48:55 -07002274 Runtime::Current()->GetThreadList()->ForEach(DdmSendThreadStartCallback, NULL);
Elliott Hughes47fce012011-10-25 18:37:19 -07002275 }
2276}
2277
Elliott Hughesa2155262011-11-16 16:26:58 -08002278void Dbg::PostThreadStartOrStop(Thread* t, uint32_t type) {
Elliott Hughes47fce012011-10-25 18:37:19 -07002279 if (gDebuggerActive) {
2280 JDWP::ObjectId id = gRegistry->Add(t->GetPeer());
Elliott Hughes82188472011-11-07 18:11:48 -08002281 gJdwpState->PostThreadChange(id, type == CHUNK_TYPE("THCR"));
Elliott Hughes47fce012011-10-25 18:37:19 -07002282 }
Elliott Hughes82188472011-11-07 18:11:48 -08002283 Dbg::DdmSendThreadNotification(t, type);
Elliott Hughes47fce012011-10-25 18:37:19 -07002284}
2285
2286void Dbg::PostThreadStart(Thread* t) {
Elliott Hughesa2155262011-11-16 16:26:58 -08002287 Dbg::PostThreadStartOrStop(t, CHUNK_TYPE("THCR"));
Elliott Hughes47fce012011-10-25 18:37:19 -07002288}
2289
2290void Dbg::PostThreadDeath(Thread* t) {
Elliott Hughesa2155262011-11-16 16:26:58 -08002291 Dbg::PostThreadStartOrStop(t, CHUNK_TYPE("THDE"));
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002292}
2293
Elliott Hughes82188472011-11-07 18:11:48 -08002294void Dbg::DdmSendChunk(uint32_t type, size_t byte_count, const uint8_t* buf) {
Elliott Hughes3bb81562011-10-21 18:52:59 -07002295 CHECK(buf != NULL);
2296 iovec vec[1];
2297 vec[0].iov_base = reinterpret_cast<void*>(const_cast<uint8_t*>(buf));
2298 vec[0].iov_len = byte_count;
2299 Dbg::DdmSendChunkV(type, vec, 1);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002300}
2301
Elliott Hughes21f32d72011-11-09 17:44:13 -08002302void Dbg::DdmSendChunk(uint32_t type, const std::vector<uint8_t>& bytes) {
2303 DdmSendChunk(type, bytes.size(), &bytes[0]);
2304}
2305
Elliott Hughescccd84f2011-12-05 16:51:54 -08002306void Dbg::DdmSendChunkV(uint32_t type, const struct iovec* iov, int iov_count) {
Elliott Hughes3bb81562011-10-21 18:52:59 -07002307 if (gJdwpState == NULL) {
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08002308 VLOG(jdwp) << "Debugger thread not active, ignoring DDM send: " << type;
Elliott Hughes3bb81562011-10-21 18:52:59 -07002309 } else {
Elliott Hughescccd84f2011-12-05 16:51:54 -08002310 gJdwpState->DdmSendChunkV(type, iov, iov_count);
Elliott Hughes3bb81562011-10-21 18:52:59 -07002311 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002312}
2313
Elliott Hughes767a1472011-10-26 18:49:02 -07002314int Dbg::DdmHandleHpifChunk(HpifWhen when) {
2315 if (when == HPIF_WHEN_NOW) {
Elliott Hughes7162ad92011-10-27 14:08:42 -07002316 DdmSendHeapInfo(when);
Elliott Hughes767a1472011-10-26 18:49:02 -07002317 return true;
2318 }
2319
2320 if (when != HPIF_WHEN_NEVER && when != HPIF_WHEN_NEXT_GC && when != HPIF_WHEN_EVERY_GC) {
2321 LOG(ERROR) << "invalid HpifWhen value: " << static_cast<int>(when);
2322 return false;
2323 }
2324
2325 gDdmHpifWhen = when;
2326 return true;
2327}
2328
2329bool Dbg::DdmHandleHpsgNhsgChunk(Dbg::HpsgWhen when, Dbg::HpsgWhat what, bool native) {
2330 if (when != HPSG_WHEN_NEVER && when != HPSG_WHEN_EVERY_GC) {
2331 LOG(ERROR) << "invalid HpsgWhen value: " << static_cast<int>(when);
2332 return false;
2333 }
2334
2335 if (what != HPSG_WHAT_MERGED_OBJECTS && what != HPSG_WHAT_DISTINCT_OBJECTS) {
2336 LOG(ERROR) << "invalid HpsgWhat value: " << static_cast<int>(what);
2337 return false;
2338 }
2339
2340 if (native) {
2341 gDdmNhsgWhen = when;
2342 gDdmNhsgWhat = what;
2343 } else {
2344 gDdmHpsgWhen = when;
2345 gDdmHpsgWhat = what;
2346 }
2347 return true;
2348}
2349
Elliott Hughes7162ad92011-10-27 14:08:42 -07002350void Dbg::DdmSendHeapInfo(HpifWhen reason) {
2351 // If there's a one-shot 'when', reset it.
2352 if (reason == gDdmHpifWhen) {
2353 if (gDdmHpifWhen == HPIF_WHEN_NEXT_GC) {
2354 gDdmHpifWhen = HPIF_WHEN_NEVER;
2355 }
2356 }
2357
2358 /*
2359 * Chunk HPIF (client --> server)
2360 *
2361 * Heap Info. General information about the heap,
2362 * suitable for a summary display.
2363 *
2364 * [u4]: number of heaps
2365 *
2366 * For each heap:
2367 * [u4]: heap ID
2368 * [u8]: timestamp in ms since Unix epoch
2369 * [u1]: capture reason (same as 'when' value from server)
2370 * [u4]: max heap size in bytes (-Xmx)
2371 * [u4]: current heap size in bytes
2372 * [u4]: current number of bytes allocated
2373 * [u4]: current number of objects allocated
2374 */
2375 uint8_t heap_count = 1;
Elliott Hughes21f32d72011-11-09 17:44:13 -08002376 std::vector<uint8_t> bytes;
Elliott Hughes545a0642011-11-08 19:10:03 -08002377 JDWP::Append4BE(bytes, heap_count);
2378 JDWP::Append4BE(bytes, 1); // Heap id (bogus; we only have one heap).
2379 JDWP::Append8BE(bytes, MilliTime());
2380 JDWP::Append1BE(bytes, reason);
2381 JDWP::Append4BE(bytes, Heap::GetMaxMemory()); // Max allowed heap size in bytes.
2382 JDWP::Append4BE(bytes, Heap::GetTotalMemory()); // Current heap size in bytes.
2383 JDWP::Append4BE(bytes, Heap::GetBytesAllocated());
2384 JDWP::Append4BE(bytes, Heap::GetObjectsAllocated());
Elliott Hughes21f32d72011-11-09 17:44:13 -08002385 CHECK_EQ(bytes.size(), 4U + (heap_count * (4 + 8 + 1 + 4 + 4 + 4 + 4)));
2386 Dbg::DdmSendChunk(CHUNK_TYPE("HPIF"), bytes);
Elliott Hughes767a1472011-10-26 18:49:02 -07002387}
2388
Elliott Hughes6a5bd492011-10-28 14:33:57 -07002389enum HpsgSolidity {
2390 SOLIDITY_FREE = 0,
2391 SOLIDITY_HARD = 1,
2392 SOLIDITY_SOFT = 2,
2393 SOLIDITY_WEAK = 3,
2394 SOLIDITY_PHANTOM = 4,
2395 SOLIDITY_FINALIZABLE = 5,
2396 SOLIDITY_SWEEP = 6,
2397};
2398
2399enum HpsgKind {
2400 KIND_OBJECT = 0,
2401 KIND_CLASS_OBJECT = 1,
2402 KIND_ARRAY_1 = 2,
2403 KIND_ARRAY_2 = 3,
2404 KIND_ARRAY_4 = 4,
2405 KIND_ARRAY_8 = 5,
2406 KIND_UNKNOWN = 6,
2407 KIND_NATIVE = 7,
2408};
2409
2410#define HPSG_PARTIAL (1<<7)
2411#define HPSG_STATE(solidity, kind) ((uint8_t)((((kind) & 0x7) << 3) | ((solidity) & 0x7)))
2412
Ian Rogers30fab402012-01-23 15:43:46 -08002413class HeapChunkContext {
2414 public:
Elliott Hughes6a5bd492011-10-28 14:33:57 -07002415 // Maximum chunk size. Obtain this from the formula:
2416 // (((maximum_heap_size / ALLOCATION_UNIT_SIZE) + 255) / 256) * 2
2417 HeapChunkContext(bool merge, bool native)
Ian Rogers30fab402012-01-23 15:43:46 -08002418 : buf_(16384 - 16),
2419 type_(0),
2420 merge_(merge) {
Elliott Hughes6a5bd492011-10-28 14:33:57 -07002421 Reset();
2422 if (native) {
Ian Rogers30fab402012-01-23 15:43:46 -08002423 type_ = CHUNK_TYPE("NHSG");
Elliott Hughes6a5bd492011-10-28 14:33:57 -07002424 } else {
Ian Rogers30fab402012-01-23 15:43:46 -08002425 type_ = merge ? CHUNK_TYPE("HPSG") : CHUNK_TYPE("HPSO");
Elliott Hughes6a5bd492011-10-28 14:33:57 -07002426 }
2427 }
2428
2429 ~HeapChunkContext() {
Ian Rogers30fab402012-01-23 15:43:46 -08002430 if (p_ > &buf_[0]) {
Elliott Hughes6a5bd492011-10-28 14:33:57 -07002431 Flush();
2432 }
2433 }
2434
2435 void EnsureHeader(const void* chunk_ptr) {
Ian Rogers30fab402012-01-23 15:43:46 -08002436 if (!needHeader_) {
Elliott Hughes6a5bd492011-10-28 14:33:57 -07002437 return;
2438 }
2439
2440 // Start a new HPSx chunk.
Ian Rogers30fab402012-01-23 15:43:46 -08002441 JDWP::Write4BE(&p_, 1); // Heap id (bogus; we only have one heap).
2442 JDWP::Write1BE(&p_, 8); // Size of allocation unit, in bytes.
Elliott Hughes6a5bd492011-10-28 14:33:57 -07002443
Ian Rogers30fab402012-01-23 15:43:46 -08002444 JDWP::Write4BE(&p_, reinterpret_cast<uintptr_t>(chunk_ptr)); // virtual address of segment start.
2445 JDWP::Write4BE(&p_, 0); // offset of this piece (relative to the virtual address).
Elliott Hughes6a5bd492011-10-28 14:33:57 -07002446 // [u4]: length of piece, in allocation units
2447 // We won't know this until we're done, so save the offset and stuff in a dummy value.
Ian Rogers30fab402012-01-23 15:43:46 -08002448 pieceLenField_ = p_;
2449 JDWP::Write4BE(&p_, 0x55555555);
2450 needHeader_ = false;
Elliott Hughes6a5bd492011-10-28 14:33:57 -07002451 }
2452
2453 void Flush() {
2454 // Patch the "length of piece" field.
Ian Rogers30fab402012-01-23 15:43:46 -08002455 CHECK_LE(&buf_[0], pieceLenField_);
2456 CHECK_LE(pieceLenField_, p_);
2457 JDWP::Set4BE(pieceLenField_, totalAllocationUnits_);
Elliott Hughes6a5bd492011-10-28 14:33:57 -07002458
Ian Rogers30fab402012-01-23 15:43:46 -08002459 Dbg::DdmSendChunk(type_, p_ - &buf_[0], &buf_[0]);
Elliott Hughes6a5bd492011-10-28 14:33:57 -07002460 Reset();
2461 }
2462
Ian Rogers30fab402012-01-23 15:43:46 -08002463 static void HeapChunkCallback(void* start, void* end, size_t used_bytes, void* arg) {
2464 reinterpret_cast<HeapChunkContext*>(arg)->HeapChunkCallback(start, end, used_bytes);
Elliott Hughesa2155262011-11-16 16:26:58 -08002465 }
2466
Elliott Hughes6a5bd492011-10-28 14:33:57 -07002467 private:
Elliott Hughesa2155262011-11-16 16:26:58 -08002468 enum { ALLOCATION_UNIT_SIZE = 8 };
2469
Elliott Hughes6a5bd492011-10-28 14:33:57 -07002470 void Reset() {
Ian Rogers30fab402012-01-23 15:43:46 -08002471 p_ = &buf_[0];
2472 totalAllocationUnits_ = 0;
2473 needHeader_ = true;
2474 pieceLenField_ = NULL;
Elliott Hughes6a5bd492011-10-28 14:33:57 -07002475 }
2476
Ian Rogers30fab402012-01-23 15:43:46 -08002477 void HeapChunkCallback(void* start, void* end, size_t used_bytes) {
2478 // Note: heap call backs cannot manipulate the heap upon which they are crawling, care is taken
2479 // in the following code not to allocate memory, by ensuring buf_ is of the correct size
2480
2481 const void* user_ptr = used_bytes > 0 ? const_cast<void*>(start) : NULL;
2482 // from malloc.c mem2chunk(mem)
2483 const void* chunk_ptr =
2484 reinterpret_cast<const void*>(reinterpret_cast<const char*>(const_cast<void*>(start)) -
2485 (2 * sizeof(size_t)));
2486 // from malloc.c chunksize
2487 size_t chunk_len = (*reinterpret_cast<size_t* const*>(chunk_ptr))[1] & ~7;
2488
2489
2490 //size_t chunk_len = malloc_usable_size(user_ptr);
Elliott Hughesa2155262011-11-16 16:26:58 -08002491 CHECK_EQ((chunk_len & (ALLOCATION_UNIT_SIZE-1)), 0U);
Elliott Hughes6a5bd492011-10-28 14:33:57 -07002492
Elliott Hughesa2155262011-11-16 16:26:58 -08002493 /* Make sure there's enough room left in the buffer.
2494 * We need to use two bytes for every fractional 256
2495 * allocation units used by the chunk.
2496 */
2497 {
2498 size_t needed = (((chunk_len/ALLOCATION_UNIT_SIZE + 255) / 256) * 2);
Ian Rogers30fab402012-01-23 15:43:46 -08002499 size_t bytesLeft = buf_.size() - (size_t)(p_ - &buf_[0]);
Elliott Hughesa2155262011-11-16 16:26:58 -08002500 if (bytesLeft < needed) {
2501 Flush();
2502 }
Elliott Hughes6a5bd492011-10-28 14:33:57 -07002503
Ian Rogers30fab402012-01-23 15:43:46 -08002504 bytesLeft = buf_.size() - (size_t)(p_ - &buf_[0]);
Elliott Hughesa2155262011-11-16 16:26:58 -08002505 if (bytesLeft < needed) {
Elliott Hughes3d30d9b2011-12-07 17:35:48 -08002506 LOG(WARNING) << "Chunk is too big to transmit (chunk_len=" << chunk_len << ", " << needed << " bytes)";
Elliott Hughesa2155262011-11-16 16:26:58 -08002507 return;
2508 }
2509 }
2510
2511 // OLD-TODO: notice when there's a gap and start a new heap, or at least a new range.
2512 EnsureHeader(chunk_ptr);
2513
2514 // Determine the type of this chunk.
2515 // OLD-TODO: if context.merge, see if this chunk is different from the last chunk.
2516 // If it's the same, we should combine them.
Ian Rogers30fab402012-01-23 15:43:46 -08002517 uint8_t state = ExamineObject(reinterpret_cast<const Object*>(user_ptr), (type_ == CHUNK_TYPE("NHSG")));
Elliott Hughesa2155262011-11-16 16:26:58 -08002518
2519 // Write out the chunk description.
2520 chunk_len /= ALLOCATION_UNIT_SIZE; // convert to allocation units
Ian Rogers30fab402012-01-23 15:43:46 -08002521 totalAllocationUnits_ += chunk_len;
Elliott Hughesa2155262011-11-16 16:26:58 -08002522 while (chunk_len > 256) {
Ian Rogers30fab402012-01-23 15:43:46 -08002523 *p_++ = state | HPSG_PARTIAL;
2524 *p_++ = 255; // length - 1
Elliott Hughesa2155262011-11-16 16:26:58 -08002525 chunk_len -= 256;
2526 }
Ian Rogers30fab402012-01-23 15:43:46 -08002527 *p_++ = state;
2528 *p_++ = chunk_len - 1;
Elliott Hughes6a5bd492011-10-28 14:33:57 -07002529 }
2530
Elliott Hughesa2155262011-11-16 16:26:58 -08002531 uint8_t ExamineObject(const Object* o, bool is_native_heap) {
2532 if (o == NULL) {
2533 return HPSG_STATE(SOLIDITY_FREE, 0);
2534 }
Elliott Hughes6a5bd492011-10-28 14:33:57 -07002535
Elliott Hughesa2155262011-11-16 16:26:58 -08002536 // It's an allocated chunk. Figure out what it is.
Elliott Hughes6a5bd492011-10-28 14:33:57 -07002537
Elliott Hughesa2155262011-11-16 16:26:58 -08002538 // If we're looking at the native heap, we'll just return
2539 // (SOLIDITY_HARD, KIND_NATIVE) for all allocated chunks.
2540 if (is_native_heap || !Heap::IsLiveObjectLocked(o)) {
2541 return HPSG_STATE(SOLIDITY_HARD, KIND_NATIVE);
2542 }
2543
2544 Class* c = o->GetClass();
2545 if (c == NULL) {
2546 // The object was probably just created but hasn't been initialized yet.
2547 return HPSG_STATE(SOLIDITY_HARD, KIND_OBJECT);
2548 }
2549
2550 if (!Heap::IsHeapAddress(c)) {
Elliott Hughes3d30d9b2011-12-07 17:35:48 -08002551 LOG(WARNING) << "Invalid class for managed heap object: " << o << " " << c;
Elliott Hughesa2155262011-11-16 16:26:58 -08002552 return HPSG_STATE(SOLIDITY_HARD, KIND_UNKNOWN);
2553 }
2554
2555 if (c->IsClassClass()) {
2556 return HPSG_STATE(SOLIDITY_HARD, KIND_CLASS_OBJECT);
2557 }
2558
2559 if (c->IsArrayClass()) {
2560 if (o->IsObjectArray()) {
2561 return HPSG_STATE(SOLIDITY_HARD, KIND_ARRAY_4);
2562 }
2563 switch (c->GetComponentSize()) {
2564 case 1: return HPSG_STATE(SOLIDITY_HARD, KIND_ARRAY_1);
2565 case 2: return HPSG_STATE(SOLIDITY_HARD, KIND_ARRAY_2);
2566 case 4: return HPSG_STATE(SOLIDITY_HARD, KIND_ARRAY_4);
2567 case 8: return HPSG_STATE(SOLIDITY_HARD, KIND_ARRAY_8);
2568 }
2569 }
2570
Elliott Hughes6a5bd492011-10-28 14:33:57 -07002571 return HPSG_STATE(SOLIDITY_HARD, KIND_OBJECT);
2572 }
2573
Ian Rogers30fab402012-01-23 15:43:46 -08002574 std::vector<uint8_t> buf_;
2575 uint8_t* p_;
2576 uint8_t* pieceLenField_;
2577 size_t totalAllocationUnits_;
2578 uint32_t type_;
2579 bool merge_;
2580 bool needHeader_;
2581
Elliott Hughesa2155262011-11-16 16:26:58 -08002582 DISALLOW_COPY_AND_ASSIGN(HeapChunkContext);
2583};
Elliott Hughes6a5bd492011-10-28 14:33:57 -07002584
2585void Dbg::DdmSendHeapSegments(bool native) {
2586 Dbg::HpsgWhen when;
2587 Dbg::HpsgWhat what;
2588 if (!native) {
2589 when = gDdmHpsgWhen;
2590 what = gDdmHpsgWhat;
2591 } else {
2592 when = gDdmNhsgWhen;
2593 what = gDdmNhsgWhat;
2594 }
2595 if (when == HPSG_WHEN_NEVER) {
2596 return;
2597 }
2598
2599 // Figure out what kind of chunks we'll be sending.
2600 CHECK(what == HPSG_WHAT_MERGED_OBJECTS || what == HPSG_WHAT_DISTINCT_OBJECTS) << static_cast<int>(what);
2601
2602 // First, send a heap start chunk.
2603 uint8_t heap_id[4];
2604 JDWP::Set4BE(&heap_id[0], 1); // Heap id (bogus; we only have one heap).
2605 Dbg::DdmSendChunk(native ? CHUNK_TYPE("NHST") : CHUNK_TYPE("HPST"), sizeof(heap_id), heap_id);
2606
2607 // Send a series of heap segment chunks.
Elliott Hughesa2155262011-11-16 16:26:58 -08002608 HeapChunkContext context((what == HPSG_WHAT_MERGED_OBJECTS), native);
2609 if (native) {
Ian Rogers30fab402012-01-23 15:43:46 -08002610 // TODO: enable when bionic has moved to dlmalloc 2.8.5
2611 // dlmalloc_inspect_all(HeapChunkContext::HeapChunkCallback, &context);
2612 UNIMPLEMENTED(WARNING) << "Native heap send heap segments";
Elliott Hughesa2155262011-11-16 16:26:58 -08002613 } else {
Ian Rogers30fab402012-01-23 15:43:46 -08002614 Heap::GetAllocSpace()->Walk(HeapChunkContext::HeapChunkCallback, &context);
Elliott Hughesa2155262011-11-16 16:26:58 -08002615 }
Elliott Hughes6a5bd492011-10-28 14:33:57 -07002616
2617 // Finally, send a heap end chunk.
2618 Dbg::DdmSendChunk(native ? CHUNK_TYPE("NHEN") : CHUNK_TYPE("HPEN"), sizeof(heap_id), heap_id);
Elliott Hughes767a1472011-10-26 18:49:02 -07002619}
2620
Elliott Hughes545a0642011-11-08 19:10:03 -08002621void Dbg::SetAllocTrackingEnabled(bool enabled) {
2622 MutexLock mu(gAllocTrackerLock);
2623 if (enabled) {
2624 if (recent_allocation_records_ == NULL) {
2625 LOG(INFO) << "Enabling alloc tracker (" << kNumAllocRecords << " entries, "
2626 << kMaxAllocRecordStackDepth << " frames --> "
2627 << (sizeof(AllocRecord) * kNumAllocRecords) << " bytes)";
2628 gAllocRecordHead = gAllocRecordCount = 0;
2629 recent_allocation_records_ = new AllocRecord[kNumAllocRecords];
2630 CHECK(recent_allocation_records_ != NULL);
2631 }
2632 } else {
2633 delete[] recent_allocation_records_;
2634 recent_allocation_records_ = NULL;
2635 }
2636}
2637
2638struct AllocRecordStackVisitor : public Thread::StackVisitor {
Elliott Hughesba8eee12012-01-24 20:25:24 -08002639 explicit AllocRecordStackVisitor(AllocRecord* record) : record(record), depth(0) {
Elliott Hughes545a0642011-11-08 19:10:03 -08002640 }
2641
2642 virtual void VisitFrame(const Frame& f, uintptr_t pc) {
2643 if (depth >= kMaxAllocRecordStackDepth) {
2644 return;
2645 }
2646 Method* m = f.GetMethod();
2647 if (m == NULL || m->IsCalleeSaveMethod()) {
2648 return;
2649 }
2650 record->stack[depth].method = m;
2651 record->stack[depth].raw_pc = pc;
2652 ++depth;
2653 }
2654
2655 ~AllocRecordStackVisitor() {
2656 // Clear out any unused stack trace elements.
2657 for (; depth < kMaxAllocRecordStackDepth; ++depth) {
2658 record->stack[depth].method = NULL;
2659 record->stack[depth].raw_pc = 0;
2660 }
2661 }
2662
2663 AllocRecord* record;
2664 size_t depth;
2665};
2666
2667void Dbg::RecordAllocation(Class* type, size_t byte_count) {
2668 Thread* self = Thread::Current();
2669 CHECK(self != NULL);
2670
2671 MutexLock mu(gAllocTrackerLock);
2672 if (recent_allocation_records_ == NULL) {
2673 return;
2674 }
2675
2676 // Advance and clip.
2677 if (++gAllocRecordHead == kNumAllocRecords) {
2678 gAllocRecordHead = 0;
2679 }
2680
2681 // Fill in the basics.
2682 AllocRecord* record = &recent_allocation_records_[gAllocRecordHead];
2683 record->type = type;
2684 record->byte_count = byte_count;
2685 record->thin_lock_id = self->GetThinLockId();
2686
2687 // Fill in the stack trace.
2688 AllocRecordStackVisitor visitor(record);
2689 self->WalkStack(&visitor);
2690
2691 if (gAllocRecordCount < kNumAllocRecords) {
2692 ++gAllocRecordCount;
2693 }
2694}
2695
2696/*
2697 * Return the index of the head element.
2698 *
2699 * We point at the most-recently-written record, so if allocRecordCount is 1
2700 * we want to use the current element. Take "head+1" and subtract count
2701 * from it.
2702 *
2703 * We need to handle underflow in our circular buffer, so we add
2704 * kNumAllocRecords and then mask it back down.
2705 */
2706inline static int headIndex() {
2707 return (gAllocRecordHead+1 + kNumAllocRecords - gAllocRecordCount) & (kNumAllocRecords-1);
2708}
2709
2710void Dbg::DumpRecentAllocations() {
2711 MutexLock mu(gAllocTrackerLock);
2712 if (recent_allocation_records_ == NULL) {
2713 LOG(INFO) << "Not recording tracked allocations";
2714 return;
2715 }
2716
2717 // "i" is the head of the list. We want to start at the end of the
2718 // list and move forward to the tail.
2719 size_t i = headIndex();
2720 size_t count = gAllocRecordCount;
2721
2722 LOG(INFO) << "Tracked allocations, (head=" << gAllocRecordHead << " count=" << count << ")";
2723 while (count--) {
2724 AllocRecord* record = &recent_allocation_records_[i];
2725
Elliott Hughesaa6e1cd2012-01-18 19:26:06 -08002726 LOG(INFO) << StringPrintf(" T=%-2d %6zd ", record->thin_lock_id, record->byte_count)
Elliott Hughes545a0642011-11-08 19:10:03 -08002727 << PrettyClass(record->type);
2728
2729 for (size_t stack_frame = 0; stack_frame < kMaxAllocRecordStackDepth; ++stack_frame) {
2730 const Method* m = record->stack[stack_frame].method;
2731 if (m == NULL) {
2732 break;
2733 }
2734 LOG(INFO) << " " << PrettyMethod(m) << " line " << record->stack[stack_frame].LineNumber();
2735 }
2736
2737 // pause periodically to help logcat catch up
2738 if ((count % 5) == 0) {
2739 usleep(40000);
2740 }
2741
2742 i = (i + 1) & (kNumAllocRecords-1);
2743 }
2744}
2745
2746class StringTable {
2747 public:
2748 StringTable() {
2749 }
2750
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002751 void Add(const char* s) {
Elliott Hughes545a0642011-11-08 19:10:03 -08002752 table_.insert(s);
2753 }
2754
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002755 size_t IndexOf(const char* s) {
Elliott Hughes545a0642011-11-08 19:10:03 -08002756 return std::distance(table_.begin(), table_.find(s));
2757 }
2758
2759 size_t Size() {
2760 return table_.size();
2761 }
2762
2763 void WriteTo(std::vector<uint8_t>& bytes) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002764 typedef std::set<const char*>::const_iterator It; // TODO: C++0x auto
Elliott Hughes545a0642011-11-08 19:10:03 -08002765 for (It it = table_.begin(); it != table_.end(); ++it) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002766 const char* s = *it;
2767 size_t s_len = CountModifiedUtf8Chars(s);
2768 UniquePtr<uint16_t> s_utf16(new uint16_t[s_len]);
2769 ConvertModifiedUtf8ToUtf16(s_utf16.get(), s);
2770 JDWP::AppendUtf16BE(bytes, s_utf16.get(), s_len);
Elliott Hughes545a0642011-11-08 19:10:03 -08002771 }
2772 }
2773
2774 private:
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002775 std::set<const char*> table_;
Elliott Hughes545a0642011-11-08 19:10:03 -08002776 DISALLOW_COPY_AND_ASSIGN(StringTable);
2777};
2778
2779/*
2780 * The data we send to DDMS contains everything we have recorded.
2781 *
2782 * Message header (all values big-endian):
2783 * (1b) message header len (to allow future expansion); includes itself
2784 * (1b) entry header len
2785 * (1b) stack frame len
2786 * (2b) number of entries
2787 * (4b) offset to string table from start of message
2788 * (2b) number of class name strings
2789 * (2b) number of method name strings
2790 * (2b) number of source file name strings
2791 * For each entry:
2792 * (4b) total allocation size
2793 * (2b) threadId
2794 * (2b) allocated object's class name index
2795 * (1b) stack depth
2796 * For each stack frame:
2797 * (2b) method's class name
2798 * (2b) method name
2799 * (2b) method source file
2800 * (2b) line number, clipped to 32767; -2 if native; -1 if no source
2801 * (xb) class name strings
2802 * (xb) method name strings
2803 * (xb) source file strings
2804 *
2805 * As with other DDM traffic, strings are sent as a 4-byte length
2806 * followed by UTF-16 data.
2807 *
2808 * We send up 16-bit unsigned indexes into string tables. In theory there
2809 * can be (kMaxAllocRecordStackDepth * kNumAllocRecords) unique strings in
2810 * each table, but in practice there should be far fewer.
2811 *
2812 * The chief reason for using a string table here is to keep the size of
2813 * the DDMS message to a minimum. This is partly to make the protocol
2814 * efficient, but also because we have to form the whole thing up all at
2815 * once in a memory buffer.
2816 *
2817 * We use separate string tables for class names, method names, and source
2818 * files to keep the indexes small. There will generally be no overlap
2819 * between the contents of these tables.
2820 */
2821jbyteArray Dbg::GetRecentAllocations() {
2822 if (false) {
2823 DumpRecentAllocations();
2824 }
2825
2826 MutexLock mu(gAllocTrackerLock);
2827
2828 /*
2829 * Part 1: generate string tables.
2830 */
2831 StringTable class_names;
2832 StringTable method_names;
2833 StringTable filenames;
2834
2835 int count = gAllocRecordCount;
2836 int idx = headIndex();
2837 while (count--) {
2838 AllocRecord* record = &recent_allocation_records_[idx];
2839
Elliott Hughes91250e02011-12-13 22:30:35 -08002840 class_names.Add(ClassHelper(record->type).GetDescriptor());
Elliott Hughes545a0642011-11-08 19:10:03 -08002841
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002842 MethodHelper mh;
Elliott Hughes545a0642011-11-08 19:10:03 -08002843 for (size_t i = 0; i < kMaxAllocRecordStackDepth; i++) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002844 Method* m = record->stack[i].method;
2845 mh.ChangeMethod(m);
Elliott Hughes545a0642011-11-08 19:10:03 -08002846 if (m != NULL) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002847 class_names.Add(mh.GetDeclaringClassDescriptor());
2848 method_names.Add(mh.GetName());
2849 filenames.Add(mh.GetDeclaringClassSourceFile());
Elliott Hughes545a0642011-11-08 19:10:03 -08002850 }
2851 }
2852
2853 idx = (idx + 1) & (kNumAllocRecords-1);
2854 }
2855
2856 LOG(INFO) << "allocation records: " << gAllocRecordCount;
2857
2858 /*
2859 * Part 2: allocate a buffer and generate the output.
2860 */
2861 std::vector<uint8_t> bytes;
2862
2863 // (1b) message header len (to allow future expansion); includes itself
2864 // (1b) entry header len
2865 // (1b) stack frame len
2866 const int kMessageHeaderLen = 15;
2867 const int kEntryHeaderLen = 9;
2868 const int kStackFrameLen = 8;
2869 JDWP::Append1BE(bytes, kMessageHeaderLen);
2870 JDWP::Append1BE(bytes, kEntryHeaderLen);
2871 JDWP::Append1BE(bytes, kStackFrameLen);
2872
2873 // (2b) number of entries
2874 // (4b) offset to string table from start of message
2875 // (2b) number of class name strings
2876 // (2b) number of method name strings
2877 // (2b) number of source file name strings
2878 JDWP::Append2BE(bytes, gAllocRecordCount);
2879 size_t string_table_offset = bytes.size();
2880 JDWP::Append4BE(bytes, 0); // We'll patch this later...
2881 JDWP::Append2BE(bytes, class_names.Size());
2882 JDWP::Append2BE(bytes, method_names.Size());
2883 JDWP::Append2BE(bytes, filenames.Size());
2884
2885 count = gAllocRecordCount;
2886 idx = headIndex();
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002887 ClassHelper kh;
Elliott Hughes545a0642011-11-08 19:10:03 -08002888 while (count--) {
2889 // For each entry:
2890 // (4b) total allocation size
2891 // (2b) thread id
2892 // (2b) allocated object's class name index
2893 // (1b) stack depth
2894 AllocRecord* record = &recent_allocation_records_[idx];
2895 size_t stack_depth = record->GetDepth();
2896 JDWP::Append4BE(bytes, record->byte_count);
2897 JDWP::Append2BE(bytes, record->thin_lock_id);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002898 kh.ChangeClass(record->type);
Elliott Hughes91250e02011-12-13 22:30:35 -08002899 JDWP::Append2BE(bytes, class_names.IndexOf(kh.GetDescriptor()));
Elliott Hughes545a0642011-11-08 19:10:03 -08002900 JDWP::Append1BE(bytes, stack_depth);
2901
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002902 MethodHelper mh;
Elliott Hughes545a0642011-11-08 19:10:03 -08002903 for (size_t stack_frame = 0; stack_frame < stack_depth; ++stack_frame) {
2904 // For each stack frame:
2905 // (2b) method's class name
2906 // (2b) method name
2907 // (2b) method source file
2908 // (2b) line number, clipped to 32767; -2 if native; -1 if no source
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002909 mh.ChangeMethod(record->stack[stack_frame].method);
2910 JDWP::Append2BE(bytes, class_names.IndexOf(mh.GetDeclaringClassDescriptor()));
2911 JDWP::Append2BE(bytes, method_names.IndexOf(mh.GetName()));
2912 JDWP::Append2BE(bytes, filenames.IndexOf(mh.GetDeclaringClassSourceFile()));
Elliott Hughes545a0642011-11-08 19:10:03 -08002913 JDWP::Append2BE(bytes, record->stack[stack_frame].LineNumber());
2914 }
2915
2916 idx = (idx + 1) & (kNumAllocRecords-1);
2917 }
2918
2919 // (xb) class name strings
2920 // (xb) method name strings
2921 // (xb) source file strings
2922 JDWP::Set4BE(&bytes[string_table_offset], bytes.size());
2923 class_names.WriteTo(bytes);
2924 method_names.WriteTo(bytes);
2925 filenames.WriteTo(bytes);
2926
2927 JNIEnv* env = Thread::Current()->GetJniEnv();
2928 jbyteArray result = env->NewByteArray(bytes.size());
2929 if (result != NULL) {
2930 env->SetByteArrayRegion(result, 0, bytes.size(), reinterpret_cast<const jbyte*>(&bytes[0]));
2931 }
2932 return result;
2933}
2934
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002935} // namespace art