blob: 1ba0c73ed018545cf6b3ff2230b6c34304554413 [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"
Ian Rogers776ac1f2012-04-13 23:36:36 -070025#include "dex_instruction.h"
26#if !defined(ART_USE_LLVM_COMPILER)
27#include "oat/runtime/context.h" // For VmapTable
28#endif
Ian Rogers6d4d9fc2011-11-30 16:24:48 -080029#include "object_utils.h"
Elliott Hughesa0e18062012-04-13 15:59:59 -070030#include "safe_map.h"
31#include "scoped_thread_list_lock.h"
Elliott Hughes6a5bd492011-10-28 14:33:57 -070032#include "ScopedLocalRef.h"
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -070033#include "ScopedPrimitiveArray.h"
Ian Rogers30fab402012-01-23 15:43:46 -080034#include "space.h"
Elliott Hughes47fce012011-10-25 18:37:19 -070035#include "stack_indirect_reference_table.h"
Elliott Hughes475fc232011-10-25 15:00:35 -070036#include "thread_list.h"
37
Elliott Hughes6a5bd492011-10-28 14:33:57 -070038extern "C" void dlmalloc_walk_heap(void(*)(const void*, size_t, const void*, size_t, void*), void*);
39#ifndef HAVE_ANDROID_OS
40void dlmalloc_walk_heap(void(*)(const void*, size_t, const void*, size_t, void*), void*) {
41 // No-op for glibc.
42}
43#endif
44
Elliott Hughes872d4ec2011-10-21 17:07:15 -070045namespace art {
46
Elliott Hughes545a0642011-11-08 19:10:03 -080047static const size_t kMaxAllocRecordStackDepth = 16; // Max 255.
48static const size_t kNumAllocRecords = 512; // Must be power of 2.
49
Elliott Hughes436e3722012-02-17 20:01:47 -080050static const uintptr_t kInvalidId = 1;
51static const Object* kInvalidObject = reinterpret_cast<Object*>(kInvalidId);
52
Elliott Hughes475fc232011-10-25 15:00:35 -070053class ObjectRegistry {
54 public:
55 ObjectRegistry() : lock_("ObjectRegistry lock") {
56 }
57
58 JDWP::ObjectId Add(Object* o) {
59 if (o == NULL) {
60 return 0;
61 }
62 JDWP::ObjectId id = static_cast<JDWP::ObjectId>(reinterpret_cast<uintptr_t>(o));
63 MutexLock mu(lock_);
Elliott Hughesa0e18062012-04-13 15:59:59 -070064 map_.Overwrite(id, o);
Elliott Hughes475fc232011-10-25 15:00:35 -070065 return id;
66 }
67
Elliott Hughes234ab152011-10-26 14:02:26 -070068 void Clear() {
69 MutexLock mu(lock_);
70 LOG(DEBUG) << "Debugger has detached; object registry had " << map_.size() << " entries";
71 map_.clear();
72 }
73
Elliott Hughes475fc232011-10-25 15:00:35 -070074 bool Contains(JDWP::ObjectId id) {
75 MutexLock mu(lock_);
76 return map_.find(id) != map_.end();
77 }
78
Elliott Hughesa2155262011-11-16 16:26:58 -080079 template<typename T> T Get(JDWP::ObjectId id) {
Elliott Hughes436e3722012-02-17 20:01:47 -080080 if (id == 0) {
81 return NULL;
82 }
83
Elliott Hughesa2155262011-11-16 16:26:58 -080084 MutexLock mu(lock_);
Elliott Hughesa0e18062012-04-13 15:59:59 -070085 typedef SafeMap<JDWP::ObjectId, Object*>::iterator It; // C++0x auto
Elliott Hughesa2155262011-11-16 16:26:58 -080086 It it = map_.find(id);
Elliott Hughes436e3722012-02-17 20:01:47 -080087 return (it != map_.end()) ? reinterpret_cast<T>(it->second) : reinterpret_cast<T>(kInvalidId);
Elliott Hughesa2155262011-11-16 16:26:58 -080088 }
89
Elliott Hughesbfe487b2011-10-26 15:48:55 -070090 void VisitRoots(Heap::RootVisitor* visitor, void* arg) {
91 MutexLock mu(lock_);
Elliott Hughesa0e18062012-04-13 15:59:59 -070092 typedef SafeMap<JDWP::ObjectId, Object*>::iterator It; // C++0x auto
Elliott Hughesbfe487b2011-10-26 15:48:55 -070093 for (It it = map_.begin(); it != map_.end(); ++it) {
94 visitor(it->second, arg);
95 }
96 }
97
Elliott Hughes475fc232011-10-25 15:00:35 -070098 private:
99 Mutex lock_;
Elliott Hughesa0e18062012-04-13 15:59:59 -0700100 SafeMap<JDWP::ObjectId, Object*> map_;
Elliott Hughes475fc232011-10-25 15:00:35 -0700101};
102
Elliott Hughes545a0642011-11-08 19:10:03 -0800103struct AllocRecordStackTraceElement {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800104 Method* method;
Elliott Hughes545a0642011-11-08 19:10:03 -0800105 uintptr_t raw_pc;
106
107 int32_t LineNumber() const {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800108 return MethodHelper(method).GetLineNumFromNativePC(raw_pc);
Elliott Hughes545a0642011-11-08 19:10:03 -0800109 }
110};
111
112struct AllocRecord {
113 Class* type;
114 size_t byte_count;
115 uint16_t thin_lock_id;
116 AllocRecordStackTraceElement stack[kMaxAllocRecordStackDepth]; // Unused entries have NULL method.
117
118 size_t GetDepth() {
119 size_t depth = 0;
120 while (depth < kMaxAllocRecordStackDepth && stack[depth].method != NULL) {
121 ++depth;
122 }
123 return depth;
124 }
125};
126
Elliott Hughes86964332012-02-15 19:37:42 -0800127struct Breakpoint {
128 Method* method;
Elliott Hughesa656a0f2012-02-21 18:03:44 -0800129 uint32_t dex_pc;
130 Breakpoint(Method* method, uint32_t dex_pc) : method(method), dex_pc(dex_pc) {}
Elliott Hughes86964332012-02-15 19:37:42 -0800131};
132
133static std::ostream& operator<<(std::ostream& os, const Breakpoint& rhs) {
Elliott Hughes229feb72012-02-23 13:33:29 -0800134 os << StringPrintf("Breakpoint[%s @%#x]", PrettyMethod(rhs.method).c_str(), rhs.dex_pc);
Elliott Hughes86964332012-02-15 19:37:42 -0800135 return os;
136}
137
138struct SingleStepControl {
139 // Are we single-stepping right now?
140 bool is_active;
141 Thread* thread;
142
143 JDWP::JdwpStepSize step_size;
144 JDWP::JdwpStepDepth step_depth;
145
146 const Method* method;
Elliott Hughes2435a572012-02-17 16:07:41 -0800147 int32_t line_number; // Or -1 for native methods.
148 std::set<uint32_t> dex_pcs;
Elliott Hughes86964332012-02-15 19:37:42 -0800149 int stack_depth;
150};
151
Elliott Hughes4ffd3132011-10-24 12:06:42 -0700152// JDWP is allowed unless the Zygote forbids it.
153static bool gJdwpAllowed = true;
154
Elliott Hughesc0f09332012-03-26 13:27:06 -0700155// Was there a -Xrunjdwp or -agentlib:jdwp= argument on the command line?
Elliott Hughes3bb81562011-10-21 18:52:59 -0700156static bool gJdwpConfigured = false;
157
Elliott Hughesc0f09332012-03-26 13:27:06 -0700158// Broken-down JDWP options. (Only valid if IsJdwpConfigured() is true.)
Elliott Hughes376a7a02011-10-24 18:35:55 -0700159static JDWP::JdwpOptions gJdwpOptions;
Elliott Hughes3bb81562011-10-21 18:52:59 -0700160
161// Runtime JDWP state.
162static JDWP::JdwpState* gJdwpState = NULL;
163static bool gDebuggerConnected; // debugger or DDMS is connected.
164static bool gDebuggerActive; // debugger is making requests.
Elliott Hughes86964332012-02-15 19:37:42 -0800165static bool gDisposed; // debugger called VirtualMachine.Dispose, so we should drop the connection.
Elliott Hughes3bb81562011-10-21 18:52:59 -0700166
Elliott Hughes47fce012011-10-25 18:37:19 -0700167static bool gDdmThreadNotification = false;
168
Elliott Hughes767a1472011-10-26 18:49:02 -0700169// DDMS GC-related settings.
170static Dbg::HpifWhen gDdmHpifWhen = Dbg::HPIF_WHEN_NEVER;
171static Dbg::HpsgWhen gDdmHpsgWhen = Dbg::HPSG_WHEN_NEVER;
172static Dbg::HpsgWhat gDdmHpsgWhat;
173static Dbg::HpsgWhen gDdmNhsgWhen = Dbg::HPSG_WHEN_NEVER;
174static Dbg::HpsgWhat gDdmNhsgWhat;
175
Elliott Hughes475fc232011-10-25 15:00:35 -0700176static ObjectRegistry* gRegistry = NULL;
177
Elliott Hughes545a0642011-11-08 19:10:03 -0800178// Recent allocation tracking.
179static Mutex gAllocTrackerLock("AllocTracker lock");
180AllocRecord* Dbg::recent_allocation_records_ = NULL; // TODO: CircularBuffer<AllocRecord>
181static size_t gAllocRecordHead = 0;
182static size_t gAllocRecordCount = 0;
183
Elliott Hughes86964332012-02-15 19:37:42 -0800184// Breakpoints and single-stepping.
185static Mutex gBreakpointsLock("breakpoints lock");
186static std::vector<Breakpoint> gBreakpoints;
187static SingleStepControl gSingleStepControl;
188
189static bool IsBreakpoint(Method* m, uint32_t dex_pc) {
190 MutexLock mu(gBreakpointsLock);
191 for (size_t i = 0; i < gBreakpoints.size(); ++i) {
Elliott Hughesa656a0f2012-02-21 18:03:44 -0800192 if (gBreakpoints[i].method == m && gBreakpoints[i].dex_pc == dex_pc) {
Elliott Hughes86964332012-02-15 19:37:42 -0800193 VLOG(jdwp) << "Hit breakpoint #" << i << ": " << gBreakpoints[i];
194 return true;
195 }
196 }
197 return false;
198}
199
Elliott Hughes436e3722012-02-17 20:01:47 -0800200static Array* DecodeArray(JDWP::RefTypeId id, JDWP::JdwpError& status) {
201 Object* o = gRegistry->Get<Object*>(id);
202 if (o == NULL || o == kInvalidObject) {
203 status = JDWP::ERR_INVALID_OBJECT;
204 return NULL;
205 }
206 if (!o->IsArrayInstance()) {
207 status = JDWP::ERR_INVALID_ARRAY;
208 return NULL;
209 }
210 status = JDWP::ERR_NONE;
211 return o->AsArray();
212}
213
214static Class* DecodeClass(JDWP::RefTypeId id, JDWP::JdwpError& status) {
215 Object* o = gRegistry->Get<Object*>(id);
216 if (o == NULL || o == kInvalidObject) {
217 status = JDWP::ERR_INVALID_OBJECT;
218 return NULL;
219 }
220 if (!o->IsClass()) {
221 status = JDWP::ERR_INVALID_CLASS;
222 return NULL;
223 }
224 status = JDWP::ERR_NONE;
225 return o->AsClass();
226}
227
228static Thread* DecodeThread(JDWP::ObjectId threadId) {
229 Object* thread_peer = gRegistry->Get<Object*>(threadId);
230 if (thread_peer == NULL || thread_peer == kInvalidObject) {
231 return NULL;
232 }
233 return Thread::FromManagedThread(thread_peer);
234}
235
Elliott Hughes24437992011-11-30 14:49:33 -0800236static JDWP::JdwpTag BasicTagFromDescriptor(const char* descriptor) {
237 // JDWP deliberately uses the descriptor characters' ASCII values for its enum.
238 // Note that by "basic" we mean that we don't get more specific than JT_OBJECT.
239 return static_cast<JDWP::JdwpTag>(descriptor[0]);
240}
241
242static JDWP::JdwpTag TagFromClass(Class* c) {
Elliott Hughes86b00102011-12-05 17:54:26 -0800243 CHECK(c != NULL);
Elliott Hughes24437992011-11-30 14:49:33 -0800244 if (c->IsArrayClass()) {
245 return JDWP::JT_ARRAY;
246 }
247
Elliott Hughes3d30d9b2011-12-07 17:35:48 -0800248 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
Elliott Hughes24437992011-11-30 14:49:33 -0800249 if (c->IsStringClass()) {
250 return JDWP::JT_STRING;
251 } else if (c->IsClassClass()) {
252 return JDWP::JT_CLASS_OBJECT;
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -0800253 } else if (class_linker->FindSystemClass("Ljava/lang/Thread;")->IsAssignableFrom(c)) {
Elliott Hughes24437992011-11-30 14:49:33 -0800254 return JDWP::JT_THREAD;
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -0800255 } else if (class_linker->FindSystemClass("Ljava/lang/ThreadGroup;")->IsAssignableFrom(c)) {
Elliott Hughes24437992011-11-30 14:49:33 -0800256 return JDWP::JT_THREAD_GROUP;
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -0800257 } else if (class_linker->FindSystemClass("Ljava/lang/ClassLoader;")->IsAssignableFrom(c)) {
Elliott Hughes24437992011-11-30 14:49:33 -0800258 return JDWP::JT_CLASS_LOADER;
Elliott Hughes24437992011-11-30 14:49:33 -0800259 } else {
260 return JDWP::JT_OBJECT;
261 }
262}
263
264/*
265 * Objects declared to hold Object might actually hold a more specific
266 * type. The debugger may take a special interest in these (e.g. it
267 * wants to display the contents of Strings), so we want to return an
268 * appropriate tag.
269 *
270 * Null objects are tagged JT_OBJECT.
271 */
272static JDWP::JdwpTag TagFromObject(const Object* o) {
273 return (o == NULL) ? JDWP::JT_OBJECT : TagFromClass(o->GetClass());
274}
275
276static bool IsPrimitiveTag(JDWP::JdwpTag tag) {
277 switch (tag) {
278 case JDWP::JT_BOOLEAN:
279 case JDWP::JT_BYTE:
280 case JDWP::JT_CHAR:
281 case JDWP::JT_FLOAT:
282 case JDWP::JT_DOUBLE:
283 case JDWP::JT_INT:
284 case JDWP::JT_LONG:
285 case JDWP::JT_SHORT:
286 case JDWP::JT_VOID:
287 return true;
288 default:
289 return false;
290 }
291}
292
Elliott Hughes3bb81562011-10-21 18:52:59 -0700293/*
294 * Handle one of the JDWP name/value pairs.
295 *
296 * JDWP options are:
297 * help: if specified, show help message and bail
298 * transport: may be dt_socket or dt_shmem
299 * address: for dt_socket, "host:port", or just "port" when listening
300 * server: if "y", wait for debugger to attach; if "n", attach to debugger
301 * timeout: how long to wait for debugger to connect / listen
302 *
303 * Useful with server=n (these aren't supported yet):
304 * onthrow=<exception-name>: connect to debugger when exception thrown
305 * onuncaught=y|n: connect to debugger when uncaught exception thrown
306 * launch=<command-line>: launch the debugger itself
307 *
308 * The "transport" option is required, as is "address" if server=n.
309 */
310static bool ParseJdwpOption(const std::string& name, const std::string& value) {
311 if (name == "transport") {
312 if (value == "dt_socket") {
Elliott Hughes376a7a02011-10-24 18:35:55 -0700313 gJdwpOptions.transport = JDWP::kJdwpTransportSocket;
Elliott Hughes3bb81562011-10-21 18:52:59 -0700314 } else if (value == "dt_android_adb") {
Elliott Hughes376a7a02011-10-24 18:35:55 -0700315 gJdwpOptions.transport = JDWP::kJdwpTransportAndroidAdb;
Elliott Hughes3bb81562011-10-21 18:52:59 -0700316 } else {
317 LOG(ERROR) << "JDWP transport not supported: " << value;
318 return false;
319 }
320 } else if (name == "server") {
321 if (value == "n") {
Elliott Hughes376a7a02011-10-24 18:35:55 -0700322 gJdwpOptions.server = false;
Elliott Hughes3bb81562011-10-21 18:52:59 -0700323 } else if (value == "y") {
Elliott Hughes376a7a02011-10-24 18:35:55 -0700324 gJdwpOptions.server = true;
Elliott Hughes3bb81562011-10-21 18:52:59 -0700325 } else {
326 LOG(ERROR) << "JDWP option 'server' must be 'y' or 'n'";
327 return false;
328 }
329 } else if (name == "suspend") {
330 if (value == "n") {
Elliott Hughes376a7a02011-10-24 18:35:55 -0700331 gJdwpOptions.suspend = false;
Elliott Hughes3bb81562011-10-21 18:52:59 -0700332 } else if (value == "y") {
Elliott Hughes376a7a02011-10-24 18:35:55 -0700333 gJdwpOptions.suspend = true;
Elliott Hughes3bb81562011-10-21 18:52:59 -0700334 } else {
335 LOG(ERROR) << "JDWP option 'suspend' must be 'y' or 'n'";
336 return false;
337 }
338 } else if (name == "address") {
339 /* this is either <port> or <host>:<port> */
340 std::string port_string;
Elliott Hughes376a7a02011-10-24 18:35:55 -0700341 gJdwpOptions.host.clear();
Elliott Hughes3bb81562011-10-21 18:52:59 -0700342 std::string::size_type colon = value.find(':');
343 if (colon != std::string::npos) {
Elliott Hughes376a7a02011-10-24 18:35:55 -0700344 gJdwpOptions.host = value.substr(0, colon);
Elliott Hughes3bb81562011-10-21 18:52:59 -0700345 port_string = value.substr(colon + 1);
346 } else {
347 port_string = value;
348 }
349 if (port_string.empty()) {
350 LOG(ERROR) << "JDWP address missing port: " << value;
351 return false;
352 }
353 char* end;
Elliott Hughesba8eee12012-01-24 20:25:24 -0800354 uint64_t port = strtoul(port_string.c_str(), &end, 10);
355 if (*end != '\0' || port > 0xffff) {
Elliott Hughes3bb81562011-10-21 18:52:59 -0700356 LOG(ERROR) << "JDWP address has junk in port field: " << value;
357 return false;
358 }
Elliott Hughes376a7a02011-10-24 18:35:55 -0700359 gJdwpOptions.port = port;
Elliott Hughes3bb81562011-10-21 18:52:59 -0700360 } else if (name == "launch" || name == "onthrow" || name == "oncaught" || name == "timeout") {
361 /* valid but unsupported */
362 LOG(INFO) << "Ignoring JDWP option '" << name << "'='" << value << "'";
363 } else {
364 LOG(INFO) << "Ignoring unrecognized JDWP option '" << name << "'='" << value << "'";
365 }
366
367 return true;
368}
369
370/*
371 * Parse the latter half of a -Xrunjdwp/-agentlib:jdwp= string, e.g.:
372 * "transport=dt_socket,address=8000,server=y,suspend=n"
373 */
374bool Dbg::ParseJdwpOptions(const std::string& options) {
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -0800375 VLOG(jdwp) << "ParseJdwpOptions: " << options;
Elliott Hughes47fce012011-10-25 18:37:19 -0700376
Elliott Hughes3bb81562011-10-21 18:52:59 -0700377 std::vector<std::string> pairs;
378 Split(options, ',', pairs);
379
380 for (size_t i = 0; i < pairs.size(); ++i) {
381 std::string::size_type equals = pairs[i].find('=');
382 if (equals == std::string::npos) {
383 LOG(ERROR) << "Can't parse JDWP option '" << pairs[i] << "' in '" << options << "'";
384 return false;
385 }
386 ParseJdwpOption(pairs[i].substr(0, equals), pairs[i].substr(equals + 1));
387 }
388
Elliott Hughes376a7a02011-10-24 18:35:55 -0700389 if (gJdwpOptions.transport == JDWP::kJdwpTransportUnknown) {
Elliott Hughes3bb81562011-10-21 18:52:59 -0700390 LOG(ERROR) << "Must specify JDWP transport: " << options;
391 }
Elliott Hughes376a7a02011-10-24 18:35:55 -0700392 if (!gJdwpOptions.server && (gJdwpOptions.host.empty() || gJdwpOptions.port == 0)) {
Elliott Hughes3bb81562011-10-21 18:52:59 -0700393 LOG(ERROR) << "Must specify JDWP host and port when server=n: " << options;
394 return false;
395 }
396
397 gJdwpConfigured = true;
398 return true;
399}
400
Elliott Hughesd1cc8362011-10-24 16:58:50 -0700401void Dbg::StartJdwp() {
Elliott Hughesc0f09332012-03-26 13:27:06 -0700402 if (!gJdwpAllowed || !IsJdwpConfigured()) {
Elliott Hughes376a7a02011-10-24 18:35:55 -0700403 // No JDWP for you!
404 return;
405 }
406
Elliott Hughes475fc232011-10-25 15:00:35 -0700407 CHECK(gRegistry == NULL);
408 gRegistry = new ObjectRegistry;
409
Elliott Hughesd1cc8362011-10-24 16:58:50 -0700410 // Init JDWP if the debugger is enabled. This may connect out to a
411 // debugger, passively listen for a debugger, or block waiting for a
412 // debugger.
Elliott Hughes376a7a02011-10-24 18:35:55 -0700413 gJdwpState = JDWP::JdwpState::Create(&gJdwpOptions);
414 if (gJdwpState == NULL) {
Elliott Hughesf8a2df72011-12-01 12:19:54 -0800415 // We probably failed because some other process has the port already, which means that
416 // if we don't abort the user is likely to think they're talking to us when they're actually
417 // talking to that other process.
Elliott Hughes3d30d9b2011-12-07 17:35:48 -0800418 LOG(FATAL) << "Debugger thread failed to initialize";
Elliott Hughesd1cc8362011-10-24 16:58:50 -0700419 }
420
421 // If a debugger has already attached, send the "welcome" message.
422 // This may cause us to suspend all threads.
Elliott Hughes376a7a02011-10-24 18:35:55 -0700423 if (gJdwpState->IsActive()) {
Elliott Hughes34e06962012-04-09 13:55:55 -0700424 //ScopedThreadStateChange tsc(Thread::Current(), kRunnable);
Elliott Hughes376a7a02011-10-24 18:35:55 -0700425 if (!gJdwpState->PostVMStart()) {
Elliott Hughes3d30d9b2011-12-07 17:35:48 -0800426 LOG(WARNING) << "Failed to post 'start' message to debugger";
Elliott Hughesd1cc8362011-10-24 16:58:50 -0700427 }
428 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700429}
430
Elliott Hughesd1cc8362011-10-24 16:58:50 -0700431void Dbg::StopJdwp() {
Elliott Hughes376a7a02011-10-24 18:35:55 -0700432 delete gJdwpState;
Elliott Hughes475fc232011-10-25 15:00:35 -0700433 delete gRegistry;
434 gRegistry = NULL;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700435}
436
Elliott Hughes767a1472011-10-26 18:49:02 -0700437void Dbg::GcDidFinish() {
438 if (gDdmHpifWhen != HPIF_WHEN_NEVER) {
Elliott Hughes81ff3182012-03-23 20:35:56 -0700439 LOG(DEBUG) << "Sending heap info to DDM";
Elliott Hughes7162ad92011-10-27 14:08:42 -0700440 DdmSendHeapInfo(gDdmHpifWhen);
Elliott Hughes767a1472011-10-26 18:49:02 -0700441 }
442 if (gDdmHpsgWhen != HPSG_WHEN_NEVER) {
Elliott Hughes81ff3182012-03-23 20:35:56 -0700443 LOG(DEBUG) << "Dumping heap to DDM";
Elliott Hughes6a5bd492011-10-28 14:33:57 -0700444 DdmSendHeapSegments(false);
Elliott Hughes767a1472011-10-26 18:49:02 -0700445 }
446 if (gDdmNhsgWhen != HPSG_WHEN_NEVER) {
447 LOG(DEBUG) << "Dumping native heap to DDM";
Elliott Hughes6a5bd492011-10-28 14:33:57 -0700448 DdmSendHeapSegments(true);
Elliott Hughes767a1472011-10-26 18:49:02 -0700449 }
450}
451
Elliott Hughes4ffd3132011-10-24 12:06:42 -0700452void Dbg::SetJdwpAllowed(bool allowed) {
453 gJdwpAllowed = allowed;
454}
455
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700456DebugInvokeReq* Dbg::GetInvokeReq() {
Elliott Hughes475fc232011-10-25 15:00:35 -0700457 return Thread::Current()->GetInvokeReq();
458}
459
460Thread* Dbg::GetDebugThread() {
461 return (gJdwpState != NULL) ? gJdwpState->GetDebugThread() : NULL;
462}
463
464void Dbg::ClearWaitForEventThread() {
465 gJdwpState->ClearWaitForEventThread();
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700466}
467
468void Dbg::Connected() {
Elliott Hughes3bb81562011-10-21 18:52:59 -0700469 CHECK(!gDebuggerConnected);
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -0800470 VLOG(jdwp) << "JDWP has attached";
Elliott Hughes3bb81562011-10-21 18:52:59 -0700471 gDebuggerConnected = true;
Elliott Hughes86964332012-02-15 19:37:42 -0800472 gDisposed = false;
473}
474
475void Dbg::Disposed() {
476 gDisposed = true;
477}
478
479bool Dbg::IsDisposed() {
480 return gDisposed;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700481}
482
Elliott Hughesc0f09332012-03-26 13:27:06 -0700483static void SetDebuggerUpdatesEnabledCallback(Thread* t, void* user_data) {
484 t->SetDebuggerUpdatesEnabled(*reinterpret_cast<bool*>(user_data));
485}
486
487static void SetDebuggerUpdatesEnabled(bool enabled) {
488 Runtime* runtime = Runtime::Current();
489 ScopedThreadListLock thread_list_lock;
490 runtime->GetThreadList()->ForEach(SetDebuggerUpdatesEnabledCallback, &enabled);
491}
492
Elliott Hughesa2155262011-11-16 16:26:58 -0800493void Dbg::GoActive() {
494 // Enable all debugging features, including scans for breakpoints.
495 // This is a no-op if we're already active.
496 // Only called from the JDWP handler thread.
497 if (gDebuggerActive) {
498 return;
499 }
500
501 LOG(INFO) << "Debugger is active";
502
Elliott Hughesc0f09332012-03-26 13:27:06 -0700503 {
504 // TODO: dalvik only warned if there were breakpoints left over. clear in Dbg::Disconnected?
505 MutexLock mu(gBreakpointsLock);
506 CHECK_EQ(gBreakpoints.size(), 0U);
507 }
Elliott Hughesa2155262011-11-16 16:26:58 -0800508
509 gDebuggerActive = true;
Elliott Hughesc0f09332012-03-26 13:27:06 -0700510 SetDebuggerUpdatesEnabled(true);
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700511}
512
513void Dbg::Disconnected() {
Elliott Hughes234ab152011-10-26 14:02:26 -0700514 CHECK(gDebuggerConnected);
515
Elliott Hughesc0f09332012-03-26 13:27:06 -0700516 LOG(INFO) << "Debugger is no longer active";
Elliott Hughes234ab152011-10-26 14:02:26 -0700517
Elliott Hughesc0f09332012-03-26 13:27:06 -0700518 gDebuggerActive = false;
519 SetDebuggerUpdatesEnabled(false);
Elliott Hughes234ab152011-10-26 14:02:26 -0700520
521 gRegistry->Clear();
522 gDebuggerConnected = false;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700523}
524
Elliott Hughesc0f09332012-03-26 13:27:06 -0700525bool Dbg::IsDebuggerActive() {
Elliott Hughes3bb81562011-10-21 18:52:59 -0700526 return gDebuggerActive;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700527}
528
Elliott Hughesc0f09332012-03-26 13:27:06 -0700529bool Dbg::IsJdwpConfigured() {
Elliott Hughes3bb81562011-10-21 18:52:59 -0700530 return gJdwpConfigured;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700531}
532
533int64_t Dbg::LastDebuggerActivity() {
Elliott Hughesca951522011-12-05 12:01:32 -0800534 return gJdwpState->LastDebuggerActivity();
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700535}
536
537int Dbg::ThreadRunning() {
Elliott Hughes34e06962012-04-09 13:55:55 -0700538 return static_cast<int>(Thread::Current()->SetState(kRunnable));
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700539}
540
541int Dbg::ThreadWaiting() {
Elliott Hughes34e06962012-04-09 13:55:55 -0700542 return static_cast<int>(Thread::Current()->SetState(kVmWait));
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700543}
544
Elliott Hughes6ba581a2011-10-25 11:45:35 -0700545int Dbg::ThreadContinuing(int new_state) {
Elliott Hughes34e06962012-04-09 13:55:55 -0700546 return static_cast<int>(Thread::Current()->SetState(static_cast<ThreadState>(new_state)));
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700547}
548
549void Dbg::UndoDebuggerSuspensions() {
Elliott Hughes234ab152011-10-26 14:02:26 -0700550 Runtime::Current()->GetThreadList()->UndoDebuggerSuspensions();
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700551}
552
553void Dbg::Exit(int status) {
Elliott Hughes1bba14f2011-12-01 18:00:36 -0800554 exit(status); // This is all dalvik did.
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700555}
556
Elliott Hughesbfe487b2011-10-26 15:48:55 -0700557void Dbg::VisitRoots(Heap::RootVisitor* visitor, void* arg) {
558 if (gRegistry != NULL) {
559 gRegistry->VisitRoots(visitor, arg);
560 }
561}
562
Elliott Hughesc308a5d2012-02-16 17:12:06 -0800563std::string Dbg::GetClassName(JDWP::RefTypeId classId) {
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -0800564 Object* o = gRegistry->Get<Object*>(classId);
Elliott Hughes436e3722012-02-17 20:01:47 -0800565 if (o == NULL) {
566 return "NULL";
567 }
568 if (o == kInvalidObject) {
569 return StringPrintf("invalid object %p", reinterpret_cast<void*>(classId));
570 }
571 if (!o->IsClass()) {
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -0800572 return StringPrintf("non-class %p", o); // This is only used for debugging output anyway.
573 }
Elliott Hughesc308a5d2012-02-16 17:12:06 -0800574 return DescriptorToName(ClassHelper(o->AsClass()).GetDescriptor());
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700575}
576
Elliott Hughes436e3722012-02-17 20:01:47 -0800577JDWP::JdwpError Dbg::GetClassObject(JDWP::RefTypeId id, JDWP::ObjectId& classObjectId) {
578 JDWP::JdwpError status;
579 Class* c = DecodeClass(id, status);
580 if (c == NULL) {
581 return status;
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -0800582 }
Elliott Hughes436e3722012-02-17 20:01:47 -0800583 classObjectId = gRegistry->Add(c);
584 return JDWP::ERR_NONE;
Elliott Hughes86964332012-02-15 19:37:42 -0800585}
586
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -0800587JDWP::JdwpError Dbg::GetSuperclass(JDWP::RefTypeId id, JDWP::RefTypeId& superclassId) {
588 JDWP::JdwpError status;
589 Class* c = DecodeClass(id, status);
590 if (c == NULL) {
591 return status;
592 }
593 if (c->IsInterface()) {
594 // http://code.google.com/p/android/issues/detail?id=20856
595 superclassId = NULL;
596 } else {
597 superclassId = gRegistry->Add(c->GetSuperClass());
598 }
599 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700600}
601
Elliott Hughes436e3722012-02-17 20:01:47 -0800602JDWP::JdwpError Dbg::GetClassLoader(JDWP::RefTypeId id, JDWP::ExpandBuf* pReply) {
Elliott Hughes1bba14f2011-12-01 18:00:36 -0800603 Object* o = gRegistry->Get<Object*>(id);
Elliott Hughes436e3722012-02-17 20:01:47 -0800604 if (o == NULL || o == kInvalidObject) {
605 return JDWP::ERR_INVALID_OBJECT;
606 }
607 expandBufAddObjectId(pReply, gRegistry->Add(o->GetClass()->GetClassLoader()));
608 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700609}
610
Elliott Hughes436e3722012-02-17 20:01:47 -0800611JDWP::JdwpError Dbg::GetModifiers(JDWP::RefTypeId id, JDWP::ExpandBuf* pReply) {
612 JDWP::JdwpError status;
613 Class* c = DecodeClass(id, status);
614 if (c == NULL) {
615 return status;
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -0800616 }
Elliott Hughes436e3722012-02-17 20:01:47 -0800617
618 uint32_t access_flags = c->GetAccessFlags() & kAccJavaFlagsMask;
619
620 // Set ACC_SUPER; dex files don't contain this flag, but all classes are supposed to have it set.
621 // Class.getModifiers doesn't return it, but JDWP does, so we set it here.
622 access_flags |= kAccSuper;
623
624 expandBufAdd4BE(pReply, access_flags);
625
626 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700627}
628
Elliott Hughes436e3722012-02-17 20:01:47 -0800629JDWP::JdwpError Dbg::GetReflectedType(JDWP::RefTypeId classId, JDWP::ExpandBuf* pReply) {
630 JDWP::JdwpError status;
631 Class* c = DecodeClass(classId, status);
632 if (c == NULL) {
633 return status;
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -0800634 }
Elliott Hughes436e3722012-02-17 20:01:47 -0800635
636 expandBufAdd1(pReply, c->IsInterface() ? JDWP::TT_INTERFACE : JDWP::TT_CLASS);
637 expandBufAddRefTypeId(pReply, classId);
638 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700639}
640
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -0800641void Dbg::GetClassList(std::vector<JDWP::RefTypeId>& classes) {
Elliott Hughesa2155262011-11-16 16:26:58 -0800642 // Get the complete list of reference classes (i.e. all classes except
643 // the primitive types).
644 // Returns a newly-allocated buffer full of RefTypeId values.
645 struct ClassListCreator {
Elliott Hughesba8eee12012-01-24 20:25:24 -0800646 explicit ClassListCreator(std::vector<JDWP::RefTypeId>& classes) : classes(classes) {
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -0800647 }
648
Elliott Hughesa2155262011-11-16 16:26:58 -0800649 static bool Visit(Class* c, void* arg) {
650 return reinterpret_cast<ClassListCreator*>(arg)->Visit(c);
651 }
652
653 bool Visit(Class* c) {
654 if (!c->IsPrimitive()) {
655 classes.push_back(static_cast<JDWP::RefTypeId>(gRegistry->Add(c)));
656 }
657 return true;
658 }
659
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -0800660 std::vector<JDWP::RefTypeId>& classes;
Elliott Hughesa2155262011-11-16 16:26:58 -0800661 };
662
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -0800663 ClassListCreator clc(classes);
Elliott Hughesa2155262011-11-16 16:26:58 -0800664 Runtime::Current()->GetClassLinker()->VisitClasses(ClassListCreator::Visit, &clc);
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700665}
666
Elliott Hughes436e3722012-02-17 20:01:47 -0800667JDWP::JdwpError Dbg::GetClassInfo(JDWP::RefTypeId classId, JDWP::JdwpTypeTag* pTypeTag, uint32_t* pStatus, std::string* pDescriptor) {
668 JDWP::JdwpError status;
669 Class* c = DecodeClass(classId, status);
670 if (c == NULL) {
671 return status;
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -0800672 }
673
Elliott Hughesa2155262011-11-16 16:26:58 -0800674 if (c->IsArrayClass()) {
675 *pStatus = JDWP::CS_VERIFIED | JDWP::CS_PREPARED;
676 *pTypeTag = JDWP::TT_ARRAY;
677 } else {
678 if (c->IsErroneous()) {
679 *pStatus = JDWP::CS_ERROR;
680 } else {
681 *pStatus = JDWP::CS_VERIFIED | JDWP::CS_PREPARED | JDWP::CS_INITIALIZED;
682 }
683 *pTypeTag = c->IsInterface() ? JDWP::TT_INTERFACE : JDWP::TT_CLASS;
684 }
685
686 if (pDescriptor != NULL) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800687 *pDescriptor = ClassHelper(c).GetDescriptor();
Elliott Hughesa2155262011-11-16 16:26:58 -0800688 }
Elliott Hughes436e3722012-02-17 20:01:47 -0800689 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700690}
691
Elliott Hughesc3b77c72011-12-15 20:56:48 -0800692void Dbg::FindLoadedClassBySignature(const char* descriptor, std::vector<JDWP::RefTypeId>& ids) {
Elliott Hughes6fa602d2011-12-02 17:54:25 -0800693 std::vector<Class*> classes;
694 Runtime::Current()->GetClassLinker()->LookupClasses(descriptor, classes);
695 ids.clear();
696 for (size_t i = 0; i < classes.size(); ++i) {
697 ids.push_back(gRegistry->Add(classes[i]));
698 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700699}
700
Elliott Hughes2435a572012-02-17 16:07:41 -0800701JDWP::JdwpError Dbg::GetReferenceType(JDWP::ObjectId objectId, JDWP::ExpandBuf* pReply) {
Elliott Hughes499c5132011-11-17 14:55:11 -0800702 Object* o = gRegistry->Get<Object*>(objectId);
Elliott Hughes436e3722012-02-17 20:01:47 -0800703 if (o == NULL || o == kInvalidObject) {
Elliott Hughes2435a572012-02-17 16:07:41 -0800704 return JDWP::ERR_INVALID_OBJECT;
Elliott Hughes499c5132011-11-17 14:55:11 -0800705 }
Elliott Hughes2435a572012-02-17 16:07:41 -0800706
707 JDWP::JdwpTypeTag type_tag;
708 if (o->GetClass()->IsArrayClass()) {
709 type_tag = JDWP::TT_ARRAY;
710 } else if (o->GetClass()->IsInterface()) {
711 type_tag = JDWP::TT_INTERFACE;
712 } else {
713 type_tag = JDWP::TT_CLASS;
714 }
715 JDWP::RefTypeId type_id = gRegistry->Add(o->GetClass());
716
717 expandBufAdd1(pReply, type_tag);
718 expandBufAddRefTypeId(pReply, type_id);
719
720 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700721}
722
Elliott Hughes436e3722012-02-17 20:01:47 -0800723JDWP::JdwpError Dbg::GetSignature(JDWP::RefTypeId classId, std::string& signature) {
Elliott Hughes1fe7afb2012-02-13 17:23:03 -0800724 JDWP::JdwpError status;
Elliott Hughes436e3722012-02-17 20:01:47 -0800725 Class* c = DecodeClass(classId, status);
Elliott Hughes1fe7afb2012-02-13 17:23:03 -0800726 if (c == NULL) {
727 return status;
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -0800728 }
Elliott Hughes1fe7afb2012-02-13 17:23:03 -0800729 signature = ClassHelper(c).GetDescriptor();
730 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700731}
732
Elliott Hughes436e3722012-02-17 20:01:47 -0800733JDWP::JdwpError Dbg::GetSourceFile(JDWP::RefTypeId classId, std::string& result) {
734 JDWP::JdwpError status;
735 Class* c = DecodeClass(classId, status);
736 if (c == NULL) {
737 return status;
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -0800738 }
Elliott Hughes436e3722012-02-17 20:01:47 -0800739 result = ClassHelper(c).GetSourceFile();
740 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700741}
742
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700743uint8_t Dbg::GetObjectTag(JDWP::ObjectId objectId) {
Elliott Hughes24437992011-11-30 14:49:33 -0800744 Object* o = gRegistry->Get<Object*>(objectId);
745 return TagFromObject(o);
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700746}
747
Elliott Hughesaed4be92011-12-02 16:16:23 -0800748size_t Dbg::GetTagWidth(JDWP::JdwpTag tag) {
Elliott Hughesdbb40792011-11-18 17:05:22 -0800749 switch (tag) {
750 case JDWP::JT_VOID:
751 return 0;
752 case JDWP::JT_BYTE:
753 case JDWP::JT_BOOLEAN:
754 return 1;
755 case JDWP::JT_CHAR:
756 case JDWP::JT_SHORT:
757 return 2;
758 case JDWP::JT_FLOAT:
759 case JDWP::JT_INT:
760 return 4;
761 case JDWP::JT_ARRAY:
762 case JDWP::JT_OBJECT:
763 case JDWP::JT_STRING:
764 case JDWP::JT_THREAD:
765 case JDWP::JT_THREAD_GROUP:
766 case JDWP::JT_CLASS_LOADER:
767 case JDWP::JT_CLASS_OBJECT:
768 return sizeof(JDWP::ObjectId);
769 case JDWP::JT_DOUBLE:
770 case JDWP::JT_LONG:
771 return 8;
772 default:
Elliott Hughes3d30d9b2011-12-07 17:35:48 -0800773 LOG(FATAL) << "Unknown tag " << tag;
Elliott Hughesdbb40792011-11-18 17:05:22 -0800774 return -1;
775 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700776}
777
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -0800778JDWP::JdwpError Dbg::GetArrayLength(JDWP::ObjectId arrayId, int& length) {
779 JDWP::JdwpError status;
780 Array* a = DecodeArray(arrayId, status);
781 if (a == NULL) {
782 return status;
Elliott Hughes24437992011-11-30 14:49:33 -0800783 }
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -0800784 length = a->GetLength();
785 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700786}
787
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -0800788JDWP::JdwpError Dbg::OutputArray(JDWP::ObjectId arrayId, int offset, int count, JDWP::ExpandBuf* pReply) {
789 JDWP::JdwpError status;
790 Array* a = DecodeArray(arrayId, status);
791 if (a == NULL) {
792 return status;
793 }
Elliott Hughes24437992011-11-30 14:49:33 -0800794
795 if (offset < 0 || count < 0 || offset > a->GetLength() || a->GetLength() - offset < count) {
796 LOG(WARNING) << __FUNCTION__ << " access out of bounds: offset=" << offset << "; count=" << count;
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -0800797 return JDWP::ERR_INVALID_LENGTH;
Elliott Hughes24437992011-11-30 14:49:33 -0800798 }
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800799 std::string descriptor(ClassHelper(a->GetClass()).GetDescriptor());
Elliott Hughes24437992011-11-30 14:49:33 -0800800 JDWP::JdwpTag tag = BasicTagFromDescriptor(descriptor.c_str() + 1);
801
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -0800802 expandBufAdd1(pReply, tag);
803 expandBufAdd4BE(pReply, count);
804
Elliott Hughes24437992011-11-30 14:49:33 -0800805 if (IsPrimitiveTag(tag)) {
806 size_t width = GetTagWidth(tag);
Elliott Hughes24437992011-11-30 14:49:33 -0800807 uint8_t* dst = expandBufAddSpace(pReply, count * width);
808 if (width == 8) {
Ian Rogersa15e67d2012-02-28 13:51:55 -0800809 const uint64_t* src8 = reinterpret_cast<uint64_t*>(a->GetRawData(sizeof(uint64_t)));
Elliott Hughes24437992011-11-30 14:49:33 -0800810 for (int i = 0; i < count; ++i) JDWP::Write8BE(&dst, src8[offset + i]);
811 } else if (width == 4) {
Ian Rogersa15e67d2012-02-28 13:51:55 -0800812 const uint32_t* src4 = reinterpret_cast<uint32_t*>(a->GetRawData(sizeof(uint32_t)));
Elliott Hughes24437992011-11-30 14:49:33 -0800813 for (int i = 0; i < count; ++i) JDWP::Write4BE(&dst, src4[offset + i]);
814 } else if (width == 2) {
Ian Rogersa15e67d2012-02-28 13:51:55 -0800815 const uint16_t* src2 = reinterpret_cast<uint16_t*>(a->GetRawData(sizeof(uint16_t)));
Elliott Hughes24437992011-11-30 14:49:33 -0800816 for (int i = 0; i < count; ++i) JDWP::Write2BE(&dst, src2[offset + i]);
817 } else {
Ian Rogersa15e67d2012-02-28 13:51:55 -0800818 const uint8_t* src = reinterpret_cast<uint8_t*>(a->GetRawData(sizeof(uint8_t)));
Elliott Hughes24437992011-11-30 14:49:33 -0800819 memcpy(dst, &src[offset * width], count * width);
820 }
821 } else {
822 ObjectArray<Object>* oa = a->AsObjectArray<Object>();
823 for (int i = 0; i < count; ++i) {
Elliott Hughesf03b8f62011-12-02 14:26:25 -0800824 Object* element = oa->Get(offset + i);
Elliott Hughes24437992011-11-30 14:49:33 -0800825 JDWP::JdwpTag specific_tag = (element != NULL) ? TagFromObject(element) : tag;
826 expandBufAdd1(pReply, specific_tag);
827 expandBufAddObjectId(pReply, gRegistry->Add(element));
828 }
829 }
830
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -0800831 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700832}
833
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -0800834JDWP::JdwpError Dbg::SetArrayElements(JDWP::ObjectId arrayId, int offset, int count, const uint8_t* src) {
835 JDWP::JdwpError status;
836 Array* a = DecodeArray(arrayId, status);
837 if (a == NULL) {
838 return status;
839 }
Elliott Hughesf03b8f62011-12-02 14:26:25 -0800840
841 if (offset < 0 || count < 0 || offset > a->GetLength() || a->GetLength() - offset < count) {
842 LOG(WARNING) << __FUNCTION__ << " access out of bounds: offset=" << offset << "; count=" << count;
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -0800843 return JDWP::ERR_INVALID_LENGTH;
Elliott Hughesf03b8f62011-12-02 14:26:25 -0800844 }
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800845 std::string descriptor(ClassHelper(a->GetClass()).GetDescriptor());
Elliott Hughesf03b8f62011-12-02 14:26:25 -0800846 JDWP::JdwpTag tag = BasicTagFromDescriptor(descriptor.c_str() + 1);
847
848 if (IsPrimitiveTag(tag)) {
849 size_t width = GetTagWidth(tag);
Elliott Hughesf03b8f62011-12-02 14:26:25 -0800850 if (width == 8) {
Ian Rogersa15e67d2012-02-28 13:51:55 -0800851 uint8_t* dst = &(reinterpret_cast<uint8_t*>(a->GetRawData(sizeof(uint64_t)))[offset * width]);
Elliott Hughesf03b8f62011-12-02 14:26:25 -0800852 for (int i = 0; i < count; ++i) {
853 // Handle potentially non-aligned memory access one byte at a time for ARM's benefit.
854 uint64_t value;
855 for (size_t j = 0; j < sizeof(uint64_t); ++j) reinterpret_cast<uint8_t*>(&value)[j] = src[j];
856 src += sizeof(uint64_t);
857 JDWP::Write8BE(&dst, value);
858 }
859 } else if (width == 4) {
Ian Rogersa15e67d2012-02-28 13:51:55 -0800860 uint8_t* dst = &(reinterpret_cast<uint8_t*>(a->GetRawData(sizeof(uint32_t)))[offset * width]);
Elliott Hughesf03b8f62011-12-02 14:26:25 -0800861 const uint32_t* src4 = reinterpret_cast<const uint32_t*>(src);
862 for (int i = 0; i < count; ++i) JDWP::Write4BE(&dst, src4[i]);
863 } else if (width == 2) {
Ian Rogersa15e67d2012-02-28 13:51:55 -0800864 uint8_t* dst = &(reinterpret_cast<uint8_t*>(a->GetRawData(sizeof(uint16_t)))[offset * width]);
Elliott Hughesf03b8f62011-12-02 14:26:25 -0800865 const uint16_t* src2 = reinterpret_cast<const uint16_t*>(src);
866 for (int i = 0; i < count; ++i) JDWP::Write2BE(&dst, src2[i]);
867 } else {
Ian Rogersa15e67d2012-02-28 13:51:55 -0800868 uint8_t* dst = &(reinterpret_cast<uint8_t*>(a->GetRawData(sizeof(uint8_t)))[offset * width]);
Elliott Hughesf03b8f62011-12-02 14:26:25 -0800869 memcpy(&dst[offset * width], src, count * width);
870 }
871 } else {
872 ObjectArray<Object>* oa = a->AsObjectArray<Object>();
873 for (int i = 0; i < count; ++i) {
874 JDWP::ObjectId id = JDWP::ReadObjectId(&src);
Elliott Hughes436e3722012-02-17 20:01:47 -0800875 Object* o = gRegistry->Get<Object*>(id);
876 if (o == kInvalidObject) {
877 return JDWP::ERR_INVALID_OBJECT;
878 }
879 oa->Set(offset + i, o);
Elliott Hughesf03b8f62011-12-02 14:26:25 -0800880 }
881 }
882
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -0800883 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700884}
885
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -0800886JDWP::ObjectId Dbg::CreateString(const std::string& str) {
887 return gRegistry->Add(String::AllocFromModifiedUtf8(str.c_str()));
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700888}
889
Elliott Hughes436e3722012-02-17 20:01:47 -0800890JDWP::JdwpError Dbg::CreateObject(JDWP::RefTypeId classId, JDWP::ObjectId& new_object) {
891 JDWP::JdwpError status;
892 Class* c = DecodeClass(classId, status);
893 if (c == NULL) {
894 return status;
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -0800895 }
Elliott Hughes436e3722012-02-17 20:01:47 -0800896 new_object = gRegistry->Add(c->AllocObject());
897 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700898}
899
Elliott Hughesbf13d362011-12-08 15:51:37 -0800900/*
901 * Used by Eclipse's "Display" view to evaluate "new byte[5]" to get "(byte[]) [0, 0, 0, 0, 0]".
902 */
Elliott Hughes436e3722012-02-17 20:01:47 -0800903JDWP::JdwpError Dbg::CreateArrayObject(JDWP::RefTypeId arrayClassId, uint32_t length, JDWP::ObjectId& new_array) {
904 JDWP::JdwpError status;
905 Class* c = DecodeClass(arrayClassId, status);
906 if (c == NULL) {
907 return status;
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -0800908 }
Elliott Hughes436e3722012-02-17 20:01:47 -0800909 new_array = gRegistry->Add(Array::Alloc(c, length));
910 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700911}
912
913bool Dbg::MatchType(JDWP::RefTypeId instClassId, JDWP::RefTypeId classId) {
Elliott Hughes436e3722012-02-17 20:01:47 -0800914 JDWP::JdwpError status;
915 Class* c1 = DecodeClass(instClassId, status);
Elliott Hughesa656a0f2012-02-21 18:03:44 -0800916 CHECK(c1 != NULL);
Elliott Hughes436e3722012-02-17 20:01:47 -0800917 Class* c2 = DecodeClass(classId, status);
Elliott Hughesa656a0f2012-02-21 18:03:44 -0800918 CHECK(c2 != NULL);
919 return c1->IsAssignableFrom(c2);
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700920}
921
Elliott Hughes86964332012-02-15 19:37:42 -0800922static JDWP::FieldId ToFieldId(const Field* f) {
Elliott Hughes03181a82011-11-17 17:22:21 -0800923#ifdef MOVING_GARBAGE_COLLECTOR
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700924 UNIMPLEMENTED(FATAL);
Elliott Hughes03181a82011-11-17 17:22:21 -0800925#else
926 return static_cast<JDWP::FieldId>(reinterpret_cast<uintptr_t>(f));
927#endif
928}
929
Elliott Hughes86964332012-02-15 19:37:42 -0800930static JDWP::MethodId ToMethodId(const Method* m) {
Elliott Hughes03181a82011-11-17 17:22:21 -0800931#ifdef MOVING_GARBAGE_COLLECTOR
932 UNIMPLEMENTED(FATAL);
933#else
934 return static_cast<JDWP::MethodId>(reinterpret_cast<uintptr_t>(m));
935#endif
936}
937
Elliott Hughes86964332012-02-15 19:37:42 -0800938static Field* FromFieldId(JDWP::FieldId fid) {
Elliott Hughesaed4be92011-12-02 16:16:23 -0800939#ifdef MOVING_GARBAGE_COLLECTOR
940 UNIMPLEMENTED(FATAL);
941#else
942 return reinterpret_cast<Field*>(static_cast<uintptr_t>(fid));
943#endif
944}
945
Elliott Hughes86964332012-02-15 19:37:42 -0800946static Method* FromMethodId(JDWP::MethodId mid) {
Elliott Hughes03181a82011-11-17 17:22:21 -0800947#ifdef MOVING_GARBAGE_COLLECTOR
948 UNIMPLEMENTED(FATAL);
949#else
950 return reinterpret_cast<Method*>(static_cast<uintptr_t>(mid));
951#endif
952}
953
Elliott Hughes86964332012-02-15 19:37:42 -0800954static void SetLocation(JDWP::JdwpLocation& location, Method* m, uintptr_t native_pc) {
Elliott Hughes91bf6cd2012-02-14 17:27:48 -0800955 if (m == NULL) {
956 memset(&location, 0, sizeof(location));
957 } else {
958 Class* c = m->GetDeclaringClass();
959 location.typeTag = c->IsInterface() ? JDWP::TT_INTERFACE : JDWP::TT_CLASS;
960 location.classId = gRegistry->Add(c);
961 location.methodId = ToMethodId(m);
Elliott Hughes972a47b2012-02-21 18:16:06 -0800962 location.dex_pc = m->IsNative() ? -1 : m->ToDexPC(native_pc);
Elliott Hughes91bf6cd2012-02-14 17:27:48 -0800963 }
Elliott Hughesd07986f2011-12-06 18:27:45 -0800964}
965
Elliott Hughes436e3722012-02-17 20:01:47 -0800966std::string Dbg::GetMethodName(JDWP::RefTypeId, JDWP::MethodId methodId) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800967 Method* m = FromMethodId(methodId);
968 return MethodHelper(m).GetName();
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700969}
970
Elliott Hughesa2e54f62011-11-17 13:01:30 -0800971/*
972 * Augment the access flags for synthetic methods and fields by setting
973 * the (as described by the spec) "0xf0000000 bit". Also, strip out any
974 * flags not specified by the Java programming language.
975 */
976static uint32_t MangleAccessFlags(uint32_t accessFlags) {
977 accessFlags &= kAccJavaFlagsMask;
978 if ((accessFlags & kAccSynthetic) != 0) {
979 accessFlags |= 0xf0000000;
980 }
981 return accessFlags;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700982}
983
Elliott Hughesdbb40792011-11-18 17:05:22 -0800984static const uint16_t kEclipseWorkaroundSlot = 1000;
985
986/*
987 * Eclipse appears to expect that the "this" reference is in slot zero.
988 * If it's not, the "variables" display will show two copies of "this",
989 * possibly because it gets "this" from SF.ThisObject and then displays
990 * all locals with nonzero slot numbers.
991 *
992 * So, we remap the item in slot 0 to 1000, and remap "this" to zero. On
993 * SF.GetValues / SF.SetValues we map them back.
Elliott Hughesc5b734a2011-12-01 17:20:58 -0800994 *
995 * TODO: jdb uses the value to determine whether a variable is a local or an argument,
996 * by checking whether it's less than the number of arguments. To make that work, we'd
997 * have to "mangle" all the arguments to come first, not just the implicit argument 'this'.
Elliott Hughesdbb40792011-11-18 17:05:22 -0800998 */
999static uint16_t MangleSlot(uint16_t slot, const char* name) {
1000 uint16_t newSlot = slot;
1001 if (strcmp(name, "this") == 0) {
1002 newSlot = 0;
1003 } else if (slot == 0) {
1004 newSlot = kEclipseWorkaroundSlot;
1005 }
1006 return newSlot;
1007}
1008
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08001009static uint16_t DemangleSlot(uint16_t slot, Method* m) {
Elliott Hughesdbb40792011-11-18 17:05:22 -08001010 if (slot == kEclipseWorkaroundSlot) {
Elliott Hughes68fdbd02011-11-29 19:22:47 -08001011 return 0;
Elliott Hughesdbb40792011-11-18 17:05:22 -08001012 } else if (slot == 0) {
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08001013 const DexFile::CodeItem* code_item = MethodHelper(m).GetCodeItem();
1014 CHECK(code_item != NULL);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001015 return code_item->registers_size_ - code_item->ins_size_;
Elliott Hughesdbb40792011-11-18 17:05:22 -08001016 }
Elliott Hughes68fdbd02011-11-29 19:22:47 -08001017 return slot;
Elliott Hughesdbb40792011-11-18 17:05:22 -08001018}
1019
Elliott Hughes436e3722012-02-17 20:01:47 -08001020JDWP::JdwpError Dbg::OutputDeclaredFields(JDWP::RefTypeId classId, bool with_generic, JDWP::ExpandBuf* pReply) {
1021 JDWP::JdwpError status;
1022 Class* c = DecodeClass(classId, status);
1023 if (c == NULL) {
1024 return status;
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -08001025 }
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001026
1027 size_t instance_field_count = c->NumInstanceFields();
1028 size_t static_field_count = c->NumStaticFields();
1029
1030 expandBufAdd4BE(pReply, instance_field_count + static_field_count);
1031
1032 for (size_t i = 0; i < instance_field_count + static_field_count; ++i) {
1033 Field* f = (i < instance_field_count) ? c->GetInstanceField(i) : c->GetStaticField(i - instance_field_count);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001034 FieldHelper fh(f);
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001035 expandBufAddFieldId(pReply, ToFieldId(f));
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001036 expandBufAddUtf8String(pReply, fh.GetName());
1037 expandBufAddUtf8String(pReply, fh.GetTypeDescriptor());
Elliott Hughesc5b734a2011-12-01 17:20:58 -08001038 if (with_generic) {
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001039 static const char genericSignature[1] = "";
1040 expandBufAddUtf8String(pReply, genericSignature);
1041 }
1042 expandBufAdd4BE(pReply, MangleAccessFlags(f->GetAccessFlags()));
1043 }
Elliott Hughes436e3722012-02-17 20:01:47 -08001044 return JDWP::ERR_NONE;
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001045}
1046
Elliott Hughes436e3722012-02-17 20:01:47 -08001047JDWP::JdwpError Dbg::OutputDeclaredMethods(JDWP::RefTypeId classId, bool with_generic, JDWP::ExpandBuf* pReply) {
1048 JDWP::JdwpError status;
1049 Class* c = DecodeClass(classId, status);
1050 if (c == NULL) {
1051 return status;
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -08001052 }
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001053
1054 size_t direct_method_count = c->NumDirectMethods();
1055 size_t virtual_method_count = c->NumVirtualMethods();
1056
1057 expandBufAdd4BE(pReply, direct_method_count + virtual_method_count);
1058
1059 for (size_t i = 0; i < direct_method_count + virtual_method_count; ++i) {
1060 Method* m = (i < direct_method_count) ? c->GetDirectMethod(i) : c->GetVirtualMethod(i - direct_method_count);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001061 MethodHelper mh(m);
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001062 expandBufAddMethodId(pReply, ToMethodId(m));
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001063 expandBufAddUtf8String(pReply, mh.GetName());
Elliott Hughes4740cdf2011-12-07 14:07:12 -08001064 expandBufAddUtf8String(pReply, mh.GetSignature());
Elliott Hughesc5b734a2011-12-01 17:20:58 -08001065 if (with_generic) {
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001066 static const char genericSignature[1] = "";
1067 expandBufAddUtf8String(pReply, genericSignature);
1068 }
1069 expandBufAdd4BE(pReply, MangleAccessFlags(m->GetAccessFlags()));
1070 }
Elliott Hughes436e3722012-02-17 20:01:47 -08001071 return JDWP::ERR_NONE;
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001072}
1073
Elliott Hughes436e3722012-02-17 20:01:47 -08001074JDWP::JdwpError Dbg::OutputDeclaredInterfaces(JDWP::RefTypeId classId, JDWP::ExpandBuf* pReply) {
1075 JDWP::JdwpError status;
1076 Class* c = DecodeClass(classId, status);
1077 if (c == NULL) {
1078 return status;
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -08001079 }
Elliott Hughes436e3722012-02-17 20:01:47 -08001080
1081 ClassHelper kh(c);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001082 size_t interface_count = kh.NumInterfaces();
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001083 expandBufAdd4BE(pReply, interface_count);
1084 for (size_t i = 0; i < interface_count; ++i) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001085 expandBufAddRefTypeId(pReply, gRegistry->Add(kh.GetInterface(i)));
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001086 }
Elliott Hughes436e3722012-02-17 20:01:47 -08001087 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001088}
1089
Elliott Hughes436e3722012-02-17 20:01:47 -08001090void Dbg::OutputLineTable(JDWP::RefTypeId, JDWP::MethodId methodId, JDWP::ExpandBuf* pReply) {
Elliott Hughes03181a82011-11-17 17:22:21 -08001091 struct DebugCallbackContext {
1092 int numItems;
1093 JDWP::ExpandBuf* pReply;
1094
Elliott Hughes2435a572012-02-17 16:07:41 -08001095 static bool Callback(void* context, uint32_t address, uint32_t line_number) {
Elliott Hughes03181a82011-11-17 17:22:21 -08001096 DebugCallbackContext* pContext = reinterpret_cast<DebugCallbackContext*>(context);
1097 expandBufAdd8BE(pContext->pReply, address);
Elliott Hughes2435a572012-02-17 16:07:41 -08001098 expandBufAdd4BE(pContext->pReply, line_number);
Elliott Hughes03181a82011-11-17 17:22:21 -08001099 pContext->numItems++;
1100 return true;
1101 }
1102 };
1103
1104 Method* m = FromMethodId(methodId);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001105 MethodHelper mh(m);
Elliott Hughes03181a82011-11-17 17:22:21 -08001106 uint64_t start, end;
1107 if (m->IsNative()) {
1108 start = -1;
1109 end = -1;
1110 } else {
1111 start = 0;
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001112 // TODO: what are the units supposed to be? *2?
1113 end = mh.GetCodeItem()->insns_size_in_code_units_;
Elliott Hughes03181a82011-11-17 17:22:21 -08001114 }
1115
1116 expandBufAdd8BE(pReply, start);
1117 expandBufAdd8BE(pReply, end);
1118
1119 // Add numLines later
1120 size_t numLinesOffset = expandBufGetLength(pReply);
1121 expandBufAdd4BE(pReply, 0);
1122
1123 DebugCallbackContext context;
1124 context.numItems = 0;
1125 context.pReply = pReply;
1126
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001127 mh.GetDexFile().DecodeDebugInfo(mh.GetCodeItem(), m->IsStatic(), m->GetDexMethodIndex(),
1128 DebugCallbackContext::Callback, NULL, &context);
Elliott Hughes03181a82011-11-17 17:22:21 -08001129
1130 JDWP::Set4BE(expandBufGetBuffer(pReply) + numLinesOffset, context.numItems);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001131}
1132
Elliott Hughes436e3722012-02-17 20:01:47 -08001133void Dbg::OutputVariableTable(JDWP::RefTypeId, JDWP::MethodId methodId, bool with_generic, JDWP::ExpandBuf* pReply) {
Elliott Hughesdbb40792011-11-18 17:05:22 -08001134 struct DebugCallbackContext {
Elliott Hughesdbb40792011-11-18 17:05:22 -08001135 JDWP::ExpandBuf* pReply;
Elliott Hughesc5b734a2011-12-01 17:20:58 -08001136 size_t variable_count;
1137 bool with_generic;
Elliott Hughesdbb40792011-11-18 17:05:22 -08001138
Elliott Hughesc5b734a2011-12-01 17:20:58 -08001139 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 -08001140 DebugCallbackContext* pContext = reinterpret_cast<DebugCallbackContext*>(context);
1141
Elliott Hughesad3da692012-02-24 16:51:35 -08001142 VLOG(jdwp) << StringPrintf(" %2zd: %d(%d) '%s' '%s' '%s' actual slot=%d mangled slot=%d", pContext->variable_count, startAddress, endAddress - startAddress, name, descriptor, signature, slot, MangleSlot(slot, name));
Elliott Hughesdbb40792011-11-18 17:05:22 -08001143
Elliott Hughes68fdbd02011-11-29 19:22:47 -08001144 slot = MangleSlot(slot, name);
1145
Elliott Hughesdbb40792011-11-18 17:05:22 -08001146 expandBufAdd8BE(pContext->pReply, startAddress);
1147 expandBufAddUtf8String(pContext->pReply, name);
1148 expandBufAddUtf8String(pContext->pReply, descriptor);
Elliott Hughesc5b734a2011-12-01 17:20:58 -08001149 if (pContext->with_generic) {
Elliott Hughesdbb40792011-11-18 17:05:22 -08001150 expandBufAddUtf8String(pContext->pReply, signature);
1151 }
1152 expandBufAdd4BE(pContext->pReply, endAddress - startAddress);
1153 expandBufAdd4BE(pContext->pReply, slot);
1154
Elliott Hughesc5b734a2011-12-01 17:20:58 -08001155 ++pContext->variable_count;
Elliott Hughesdbb40792011-11-18 17:05:22 -08001156 }
1157 };
1158
1159 Method* m = FromMethodId(methodId);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001160 MethodHelper mh(m);
1161 const DexFile::CodeItem* code_item = mh.GetCodeItem();
Elliott Hughesdbb40792011-11-18 17:05:22 -08001162
Elliott Hughesc5b734a2011-12-01 17:20:58 -08001163 // arg_count considers doubles and longs to take 2 units.
1164 // variable_count considers everything to take 1 unit.
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001165 std::string shorty(mh.GetShorty());
Elliott Hughesc5b734a2011-12-01 17:20:58 -08001166 expandBufAdd4BE(pReply, m->NumArgRegisters(shorty));
Elliott Hughesdbb40792011-11-18 17:05:22 -08001167
Elliott Hughesc5b734a2011-12-01 17:20:58 -08001168 // We don't know the total number of variables yet, so leave a blank and update it later.
1169 size_t variable_count_offset = expandBufGetLength(pReply);
Elliott Hughesdbb40792011-11-18 17:05:22 -08001170 expandBufAdd4BE(pReply, 0);
1171
1172 DebugCallbackContext context;
Elliott Hughesdbb40792011-11-18 17:05:22 -08001173 context.pReply = pReply;
Elliott Hughesc5b734a2011-12-01 17:20:58 -08001174 context.variable_count = 0;
1175 context.with_generic = with_generic;
Elliott Hughesdbb40792011-11-18 17:05:22 -08001176
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001177 mh.GetDexFile().DecodeDebugInfo(code_item, m->IsStatic(), m->GetDexMethodIndex(), NULL,
1178 DebugCallbackContext::Callback, &context);
Elliott Hughesdbb40792011-11-18 17:05:22 -08001179
Elliott Hughesc5b734a2011-12-01 17:20:58 -08001180 JDWP::Set4BE(expandBufGetBuffer(pReply) + variable_count_offset, context.variable_count);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001181}
1182
Elliott Hughesaed4be92011-12-02 16:16:23 -08001183JDWP::JdwpTag Dbg::GetFieldBasicTag(JDWP::FieldId fieldId) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001184 return BasicTagFromDescriptor(FieldHelper(FromFieldId(fieldId)).GetTypeDescriptor());
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001185}
1186
Elliott Hughesaed4be92011-12-02 16:16:23 -08001187JDWP::JdwpTag Dbg::GetStaticFieldBasicTag(JDWP::FieldId fieldId) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001188 return BasicTagFromDescriptor(FieldHelper(FromFieldId(fieldId)).GetTypeDescriptor());
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001189}
1190
Elliott Hughes0cf74332012-02-23 23:14:00 -08001191static JDWP::JdwpError GetFieldValueImpl(JDWP::RefTypeId refTypeId, JDWP::ObjectId objectId, JDWP::FieldId fieldId, JDWP::ExpandBuf* pReply, bool is_static) {
1192 JDWP::JdwpError status;
1193 Class* c = DecodeClass(refTypeId, status);
1194 if (refTypeId != 0 && c == NULL) {
1195 return status;
1196 }
1197
Elliott Hughesaed4be92011-12-02 16:16:23 -08001198 Object* o = gRegistry->Get<Object*>(objectId);
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08001199 if ((!is_static && o == NULL) || o == kInvalidObject) {
1200 return JDWP::ERR_INVALID_OBJECT;
1201 }
Elliott Hughesaed4be92011-12-02 16:16:23 -08001202 Field* f = FromFieldId(fieldId);
Elliott Hughes0cf74332012-02-23 23:14:00 -08001203
1204 Class* receiver_class = c;
1205 if (receiver_class == NULL && o != NULL) {
1206 receiver_class = o->GetClass();
1207 }
1208 // TODO: should we give up now if receiver_class is NULL?
1209 if (receiver_class != NULL && !f->GetDeclaringClass()->IsAssignableFrom(receiver_class)) {
1210 LOG(INFO) << "ERR_INVALID_FIELDID: " << PrettyField(f) << " " << PrettyClass(receiver_class);
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08001211 return JDWP::ERR_INVALID_FIELDID;
1212 }
Elliott Hughesaed4be92011-12-02 16:16:23 -08001213
Elliott Hughes0cf74332012-02-23 23:14:00 -08001214 // The RI only enforces the static/non-static mismatch in one direction.
1215 // TODO: should we change the tests and check both?
1216 if (is_static) {
1217 if (!f->IsStatic()) {
1218 return JDWP::ERR_INVALID_FIELDID;
1219 }
1220 } else {
1221 if (f->IsStatic()) {
1222 LOG(WARNING) << "Ignoring non-NULL receiver for ObjectReference.SetValues on static field " << PrettyField(f);
1223 o = NULL;
1224 }
1225 }
1226
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001227 JDWP::JdwpTag tag = BasicTagFromDescriptor(FieldHelper(f).GetTypeDescriptor());
Elliott Hughesaed4be92011-12-02 16:16:23 -08001228
1229 if (IsPrimitiveTag(tag)) {
1230 expandBufAdd1(pReply, tag);
1231 if (tag == JDWP::JT_BOOLEAN || tag == JDWP::JT_BYTE) {
1232 expandBufAdd1(pReply, f->Get32(o));
1233 } else if (tag == JDWP::JT_CHAR || tag == JDWP::JT_SHORT) {
1234 expandBufAdd2BE(pReply, f->Get32(o));
1235 } else if (tag == JDWP::JT_FLOAT || tag == JDWP::JT_INT) {
1236 expandBufAdd4BE(pReply, f->Get32(o));
1237 } else if (tag == JDWP::JT_DOUBLE || tag == JDWP::JT_LONG) {
1238 expandBufAdd8BE(pReply, f->Get64(o));
1239 } else {
Elliott Hughes3d30d9b2011-12-07 17:35:48 -08001240 LOG(FATAL) << "Unknown tag: " << tag;
Elliott Hughesaed4be92011-12-02 16:16:23 -08001241 }
1242 } else {
1243 Object* value = f->GetObject(o);
1244 expandBufAdd1(pReply, TagFromObject(value));
1245 expandBufAddObjectId(pReply, gRegistry->Add(value));
1246 }
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08001247 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001248}
1249
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08001250JDWP::JdwpError Dbg::GetFieldValue(JDWP::ObjectId objectId, JDWP::FieldId fieldId, JDWP::ExpandBuf* pReply) {
Elliott Hughes0cf74332012-02-23 23:14:00 -08001251 return GetFieldValueImpl(0, objectId, fieldId, pReply, false);
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08001252}
1253
Elliott Hughes0cf74332012-02-23 23:14:00 -08001254JDWP::JdwpError Dbg::GetStaticFieldValue(JDWP::RefTypeId refTypeId, JDWP::FieldId fieldId, JDWP::ExpandBuf* pReply) {
1255 return GetFieldValueImpl(refTypeId, 0, fieldId, pReply, true);
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08001256}
1257
1258static JDWP::JdwpError SetFieldValueImpl(JDWP::ObjectId objectId, JDWP::FieldId fieldId, uint64_t value, int width, bool is_static) {
Elliott Hughesaed4be92011-12-02 16:16:23 -08001259 Object* o = gRegistry->Get<Object*>(objectId);
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08001260 if ((!is_static && o == NULL) || o == kInvalidObject) {
1261 return JDWP::ERR_INVALID_OBJECT;
1262 }
Elliott Hughesaed4be92011-12-02 16:16:23 -08001263 Field* f = FromFieldId(fieldId);
Elliott Hughes0cf74332012-02-23 23:14:00 -08001264
1265 // The RI only enforces the static/non-static mismatch in one direction.
1266 // TODO: should we change the tests and check both?
1267 if (is_static) {
1268 if (!f->IsStatic()) {
1269 return JDWP::ERR_INVALID_FIELDID;
1270 }
1271 } else {
1272 if (f->IsStatic()) {
1273 LOG(WARNING) << "Ignoring non-NULL receiver for ObjectReference.SetValues on static field " << PrettyField(f);
1274 o = NULL;
1275 }
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08001276 }
Elliott Hughesaed4be92011-12-02 16:16:23 -08001277
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001278 JDWP::JdwpTag tag = BasicTagFromDescriptor(FieldHelper(f).GetTypeDescriptor());
Elliott Hughesaed4be92011-12-02 16:16:23 -08001279
1280 if (IsPrimitiveTag(tag)) {
1281 if (tag == JDWP::JT_DOUBLE || tag == JDWP::JT_LONG) {
Elliott Hughes1bac54f2012-03-16 12:48:31 -07001282 CHECK_EQ(width, 8);
Elliott Hughesaed4be92011-12-02 16:16:23 -08001283 f->Set64(o, value);
1284 } else {
Elliott Hughes1bac54f2012-03-16 12:48:31 -07001285 CHECK_LE(width, 4);
Elliott Hughesaed4be92011-12-02 16:16:23 -08001286 f->Set32(o, value);
1287 }
1288 } else {
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -08001289 Object* v = gRegistry->Get<Object*>(value);
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08001290 if (v == kInvalidObject) {
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -08001291 return JDWP::ERR_INVALID_OBJECT;
1292 }
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08001293 if (v != NULL) {
1294 Class* field_type = FieldHelper(f).GetType();
1295 if (!field_type->IsAssignableFrom(v->GetClass())) {
1296 return JDWP::ERR_INVALID_OBJECT;
1297 }
1298 }
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -08001299 f->SetObject(o, v);
Elliott Hughesaed4be92011-12-02 16:16:23 -08001300 }
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -08001301
1302 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001303}
1304
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08001305JDWP::JdwpError Dbg::SetFieldValue(JDWP::ObjectId objectId, JDWP::FieldId fieldId, uint64_t value, int width) {
1306 return SetFieldValueImpl(objectId, fieldId, value, width, false);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001307}
1308
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -08001309JDWP::JdwpError Dbg::SetStaticFieldValue(JDWP::FieldId fieldId, uint64_t value, int width) {
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08001310 return SetFieldValueImpl(0, fieldId, value, width, true);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001311}
1312
Elliott Hughes68fdbd02011-11-29 19:22:47 -08001313std::string Dbg::StringToUtf8(JDWP::ObjectId strId) {
1314 String* s = gRegistry->Get<String*>(strId);
1315 return s->ToModifiedUtf8();
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001316}
1317
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001318bool Dbg::GetThreadName(JDWP::ObjectId threadId, std::string& name) {
1319 ScopedThreadListLock thread_list_lock;
1320 Thread* thread = DecodeThread(threadId);
1321 if (thread == NULL) {
1322 return false;
1323 }
Elliott Hughesffb465f2012-03-01 18:46:05 -08001324 thread->GetThreadName(name);
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001325 return true;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001326}
1327
Elliott Hughes2435a572012-02-17 16:07:41 -08001328JDWP::JdwpError Dbg::GetThreadGroup(JDWP::ObjectId threadId, JDWP::ExpandBuf* pReply) {
Elliott Hughes499c5132011-11-17 14:55:11 -08001329 Object* thread = gRegistry->Get<Object*>(threadId);
Elliott Hughes436e3722012-02-17 20:01:47 -08001330 if (thread == kInvalidObject) {
Elliott Hughes2435a572012-02-17 16:07:41 -08001331 return JDWP::ERR_INVALID_OBJECT;
1332 }
1333
1334 // Okay, so it's an object, but is it actually a thread?
Elliott Hughes436e3722012-02-17 20:01:47 -08001335 if (DecodeThread(threadId) == NULL) {
Elliott Hughes2435a572012-02-17 16:07:41 -08001336 return JDWP::ERR_INVALID_THREAD;
1337 }
Elliott Hughes499c5132011-11-17 14:55:11 -08001338
1339 Class* c = Runtime::Current()->GetClassLinker()->FindSystemClass("Ljava/lang/Thread;");
1340 CHECK(c != NULL);
1341 Field* f = c->FindInstanceField("group", "Ljava/lang/ThreadGroup;");
1342 CHECK(f != NULL);
1343 Object* group = f->GetObject(thread);
1344 CHECK(group != NULL);
Elliott Hughes2435a572012-02-17 16:07:41 -08001345 JDWP::ObjectId thread_group_id = gRegistry->Add(group);
1346
1347 expandBufAddObjectId(pReply, thread_group_id);
1348 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001349}
1350
Elliott Hughes499c5132011-11-17 14:55:11 -08001351std::string Dbg::GetThreadGroupName(JDWP::ObjectId threadGroupId) {
1352 Object* thread_group = gRegistry->Get<Object*>(threadGroupId);
1353 CHECK(thread_group != NULL);
1354
1355 Class* c = Runtime::Current()->GetClassLinker()->FindSystemClass("Ljava/lang/ThreadGroup;");
1356 CHECK(c != NULL);
1357 Field* f = c->FindInstanceField("name", "Ljava/lang/String;");
1358 CHECK(f != NULL);
1359 String* s = reinterpret_cast<String*>(f->GetObject(thread_group));
1360 return s->ToModifiedUtf8();
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001361}
1362
1363JDWP::ObjectId Dbg::GetThreadGroupParent(JDWP::ObjectId threadGroupId) {
Elliott Hughes4e235312011-12-02 11:34:15 -08001364 Object* thread_group = gRegistry->Get<Object*>(threadGroupId);
1365 CHECK(thread_group != NULL);
1366
1367 Class* c = Runtime::Current()->GetClassLinker()->FindSystemClass("Ljava/lang/ThreadGroup;");
1368 CHECK(c != NULL);
1369 Field* f = c->FindInstanceField("parent", "Ljava/lang/ThreadGroup;");
1370 CHECK(f != NULL);
1371 Object* parent = f->GetObject(thread_group);
1372 return gRegistry->Add(parent);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001373}
1374
1375JDWP::ObjectId Dbg::GetSystemThreadGroupId() {
Elliott Hughes462c9442012-03-23 18:47:50 -07001376 return gRegistry->Add(Thread::GetSystemThreadGroup());
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001377}
1378
1379JDWP::ObjectId Dbg::GetMainThreadGroupId() {
Elliott Hughes462c9442012-03-23 18:47:50 -07001380 return gRegistry->Add(Thread::GetMainThreadGroup());
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001381}
1382
Elliott Hughes3d30d9b2011-12-07 17:35:48 -08001383bool Dbg::GetThreadStatus(JDWP::ObjectId threadId, JDWP::JdwpThreadStatus* pThreadStatus, JDWP::JdwpSuspendStatus* pSuspendStatus) {
Elliott Hughes499c5132011-11-17 14:55:11 -08001384 ScopedThreadListLock thread_list_lock;
1385
1386 Thread* thread = DecodeThread(threadId);
1387 if (thread == NULL) {
1388 return false;
1389 }
1390
Elliott Hughes3ce4b262012-02-24 11:24:02 -08001391 // TODO: if we're in Thread.sleep(long), we should return TS_SLEEPING,
1392 // even if it's implemented using Object.wait(long).
Elliott Hughes499c5132011-11-17 14:55:11 -08001393 switch (thread->GetState()) {
Elliott Hughes34e06962012-04-09 13:55:55 -07001394 case kTerminated: *pThreadStatus = JDWP::TS_ZOMBIE; break;
1395 case kRunnable: *pThreadStatus = JDWP::TS_RUNNING; break;
1396 case kTimedWaiting: *pThreadStatus = JDWP::TS_WAIT; break;
1397 case kBlocked: *pThreadStatus = JDWP::TS_MONITOR; break;
1398 case kWaiting: *pThreadStatus = JDWP::TS_WAIT; break;
1399 case kStarting: *pThreadStatus = JDWP::TS_ZOMBIE; break;
1400 case kNative: *pThreadStatus = JDWP::TS_RUNNING; break;
1401 case kVmWait: *pThreadStatus = JDWP::TS_WAIT; break;
1402 case kSuspended: *pThreadStatus = JDWP::TS_RUNNING; break;
Elliott Hughescf2b2d42012-03-27 17:11:42 -07001403 // Don't add a 'default' here so the compiler can spot incompatible enum changes.
Elliott Hughes499c5132011-11-17 14:55:11 -08001404 }
1405
Elliott Hughes3d30d9b2011-12-07 17:35:48 -08001406 *pSuspendStatus = (thread->IsSuspended() ? JDWP::SUSPEND_STATUS_SUSPENDED : JDWP::SUSPEND_STATUS_NOT_SUSPENDED);
Elliott Hughes499c5132011-11-17 14:55:11 -08001407
1408 return true;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001409}
1410
Elliott Hughes2435a572012-02-17 16:07:41 -08001411JDWP::JdwpError Dbg::GetThreadSuspendCount(JDWP::ObjectId threadId, JDWP::ExpandBuf* pReply) {
1412 Thread* thread = DecodeThread(threadId);
1413 if (thread == NULL) {
1414 return JDWP::ERR_INVALID_THREAD;
1415 }
1416 expandBufAdd4BE(pReply, thread->GetSuspendCount());
1417 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001418}
1419
1420bool Dbg::ThreadExists(JDWP::ObjectId threadId) {
Elliott Hughes761928d2011-11-16 18:33:03 -08001421 return DecodeThread(threadId) != NULL;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001422}
1423
1424bool Dbg::IsSuspended(JDWP::ObjectId threadId) {
Elliott Hughes761928d2011-11-16 18:33:03 -08001425 return DecodeThread(threadId)->IsSuspended();
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001426}
1427
Elliott Hughesa2155262011-11-16 16:26:58 -08001428void Dbg::GetThreadGroupThreadsImpl(Object* thread_group, JDWP::ObjectId** ppThreadIds, uint32_t* pThreadCount) {
1429 struct ThreadListVisitor {
1430 static void Visit(Thread* t, void* arg) {
1431 reinterpret_cast<ThreadListVisitor*>(arg)->Visit(t);
1432 }
1433
1434 void Visit(Thread* t) {
1435 if (t == Dbg::GetDebugThread()) {
1436 // Skip the JDWP thread. Some debuggers get bent out of shape when they can't suspend and
1437 // query all threads, so it's easier if we just don't tell them about this thread.
1438 return;
1439 }
1440 if (thread_group == NULL || t->GetThreadGroup() == thread_group) {
1441 threads.push_back(gRegistry->Add(t->GetPeer()));
1442 }
1443 }
1444
1445 Object* thread_group;
1446 std::vector<JDWP::ObjectId> threads;
1447 };
1448
1449 ThreadListVisitor tlv;
1450 tlv.thread_group = thread_group;
1451
1452 {
1453 ScopedThreadListLock thread_list_lock;
1454 Runtime::Current()->GetThreadList()->ForEach(ThreadListVisitor::Visit, &tlv);
1455 }
1456
1457 *pThreadCount = tlv.threads.size();
1458 if (*pThreadCount == 0) {
1459 *ppThreadIds = NULL;
1460 } else {
1461 *ppThreadIds = new JDWP::ObjectId[*pThreadCount];
1462 for (size_t i = 0; i < *pThreadCount; ++i) {
1463 (*ppThreadIds)[i] = tlv.threads[i];
1464 }
1465 }
1466}
1467
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001468void Dbg::GetThreadGroupThreads(JDWP::ObjectId threadGroupId, JDWP::ObjectId** ppThreadIds, uint32_t* pThreadCount) {
Elliott Hughesa2155262011-11-16 16:26:58 -08001469 GetThreadGroupThreadsImpl(gRegistry->Get<Object*>(threadGroupId), ppThreadIds, pThreadCount);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001470}
1471
1472void Dbg::GetAllThreads(JDWP::ObjectId** ppThreadIds, uint32_t* pThreadCount) {
Elliott Hughesa2155262011-11-16 16:26:58 -08001473 GetThreadGroupThreadsImpl(NULL, ppThreadIds, pThreadCount);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001474}
1475
Elliott Hughes86964332012-02-15 19:37:42 -08001476static int GetStackDepth(Thread* thread) {
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001477 struct CountStackDepthVisitor : public Thread::StackVisitor {
1478 CountStackDepthVisitor() : depth(0) {}
Elliott Hughes530fa002012-03-12 11:44:49 -07001479 bool VisitFrame(const Frame& f, uintptr_t) {
Elliott Hughesf8a2df72011-12-01 12:19:54 -08001480 if (f.HasMethod()) {
1481 ++depth;
1482 }
Elliott Hughes530fa002012-03-12 11:44:49 -07001483 return true;
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001484 }
1485 size_t depth;
1486 };
1487 CountStackDepthVisitor visitor;
Elliott Hughes86964332012-02-15 19:37:42 -08001488 thread->WalkStack(&visitor);
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001489 return visitor.depth;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001490}
1491
Elliott Hughes86964332012-02-15 19:37:42 -08001492int Dbg::GetThreadFrameCount(JDWP::ObjectId threadId) {
1493 ScopedThreadListLock thread_list_lock;
1494 return GetStackDepth(DecodeThread(threadId));
1495}
1496
Elliott Hughes530fa002012-03-12 11:44:49 -07001497void Dbg::GetThreadFrame(JDWP::ObjectId threadId, int desired_frame_number, JDWP::FrameId* pFrameId, JDWP::JdwpLocation* pLoc) {
Elliott Hughes03181a82011-11-17 17:22:21 -08001498 ScopedThreadListLock thread_list_lock;
1499 struct GetFrameVisitor : public Thread::StackVisitor {
1500 GetFrameVisitor(int desired_frame_number, JDWP::FrameId* pFrameId, JDWP::JdwpLocation* pLoc)
Elliott Hughes530fa002012-03-12 11:44:49 -07001501 : depth(0), desired_frame_number(desired_frame_number), pFrameId(pFrameId), pLoc(pLoc) {
Elliott Hughes03181a82011-11-17 17:22:21 -08001502 }
Elliott Hughes530fa002012-03-12 11:44:49 -07001503 bool VisitFrame(const Frame& f, uintptr_t pc) {
Elliott Hughes03181a82011-11-17 17:22:21 -08001504 if (!f.HasMethod()) {
Elliott Hughes530fa002012-03-12 11:44:49 -07001505 return true; // The debugger can't do anything useful with a frame that has no Method*.
Elliott Hughes03181a82011-11-17 17:22:21 -08001506 }
Elliott Hughes03181a82011-11-17 17:22:21 -08001507 if (depth == desired_frame_number) {
1508 *pFrameId = reinterpret_cast<JDWP::FrameId>(f.GetSP());
Elliott Hughesd07986f2011-12-06 18:27:45 -08001509 SetLocation(*pLoc, f.GetMethod(), pc);
Elliott Hughes530fa002012-03-12 11:44:49 -07001510 return false;
Elliott Hughes03181a82011-11-17 17:22:21 -08001511 }
1512 ++depth;
Elliott Hughes530fa002012-03-12 11:44:49 -07001513 return true;
Elliott Hughes03181a82011-11-17 17:22:21 -08001514 }
Elliott Hughes03181a82011-11-17 17:22:21 -08001515 int depth;
1516 int desired_frame_number;
1517 JDWP::FrameId* pFrameId;
1518 JDWP::JdwpLocation* pLoc;
1519 };
1520 GetFrameVisitor visitor(desired_frame_number, pFrameId, pLoc);
1521 visitor.desired_frame_number = desired_frame_number;
1522 DecodeThread(threadId)->WalkStack(&visitor);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001523}
1524
1525JDWP::ObjectId Dbg::GetThreadSelfId() {
Elliott Hughes475fc232011-10-25 15:00:35 -07001526 return gRegistry->Add(Thread::Current()->GetPeer());
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001527}
1528
Elliott Hughes475fc232011-10-25 15:00:35 -07001529void Dbg::SuspendVM() {
Elliott Hughes34e06962012-04-09 13:55:55 -07001530 ScopedThreadStateChange tsc(Thread::Current(), kRunnable); // TODO: do we really want to change back? should the JDWP thread be Runnable usually?
Elliott Hughes475fc232011-10-25 15:00:35 -07001531 Runtime::Current()->GetThreadList()->SuspendAll(true);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001532}
1533
1534void Dbg::ResumeVM() {
Elliott Hughes475fc232011-10-25 15:00:35 -07001535 Runtime::Current()->GetThreadList()->ResumeAll(true);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001536}
1537
1538void Dbg::SuspendThread(JDWP::ObjectId threadId) {
Elliott Hughes4e235312011-12-02 11:34:15 -08001539 Object* peer = gRegistry->Get<Object*>(threadId);
1540 ScopedThreadListLock thread_list_lock;
1541 Thread* thread = Thread::FromManagedThread(peer);
1542 if (thread == NULL) {
1543 LOG(WARNING) << "No such thread for suspend: " << peer;
1544 return;
1545 }
1546 Runtime::Current()->GetThreadList()->Suspend(thread, true);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001547}
1548
1549void Dbg::ResumeThread(JDWP::ObjectId threadId) {
Elliott Hughes4e235312011-12-02 11:34:15 -08001550 Object* peer = gRegistry->Get<Object*>(threadId);
1551 ScopedThreadListLock thread_list_lock;
1552 Thread* thread = Thread::FromManagedThread(peer);
1553 if (thread == NULL) {
1554 LOG(WARNING) << "No such thread for resume: " << peer;
1555 return;
1556 }
1557 Runtime::Current()->GetThreadList()->Resume(thread, true);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001558}
1559
1560void Dbg::SuspendSelf() {
Elliott Hughes475fc232011-10-25 15:00:35 -07001561 Runtime::Current()->GetThreadList()->SuspendSelfForDebugger();
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001562}
1563
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08001564static Object* GetThis(Frame& f) {
Elliott Hughes86b00102011-12-05 17:54:26 -08001565 Method* m = f.GetMethod();
Elliott Hughes86b00102011-12-05 17:54:26 -08001566 Object* o = NULL;
1567 if (!m->IsNative() && !m->IsStatic()) {
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08001568 uint16_t reg = DemangleSlot(0, m);
Elliott Hughes86b00102011-12-05 17:54:26 -08001569 o = reinterpret_cast<Object*>(f.GetVReg(m, reg));
1570 }
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08001571 return o;
1572}
1573
1574void Dbg::GetThisObject(JDWP::FrameId frameId, JDWP::ObjectId* pThisId) {
1575 Method** sp = reinterpret_cast<Method**>(frameId);
1576 Frame f(sp);
1577 Object* o = GetThis(f);
Elliott Hughes86b00102011-12-05 17:54:26 -08001578 *pThisId = gRegistry->Add(o);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001579}
1580
Elliott Hughes1bac54f2012-03-16 12:48:31 -07001581void 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 -08001582 Method** sp = reinterpret_cast<Method**>(frameId);
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08001583 Frame f(sp);
Elliott Hughes68fdbd02011-11-29 19:22:47 -08001584 Method* m = f.GetMethod();
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08001585 uint16_t reg = DemangleSlot(slot, m);
Elliott Hughes68fdbd02011-11-29 19:22:47 -08001586
Ian Rogers776ac1f2012-04-13 23:36:36 -07001587#if defined(ART_USE_LLVM_COMPILER)
1588 UNIMPLEMENTED(FATAL);
1589#else
Elliott Hughes68fdbd02011-11-29 19:22:47 -08001590 const VmapTable vmap_table(m->GetVmapTableRaw());
1591 uint32_t vmap_offset;
1592 if (vmap_table.IsInContext(reg, vmap_offset)) {
Elliott Hughes3d30d9b2011-12-07 17:35:48 -08001593 UNIMPLEMENTED(FATAL) << "Don't know how to pull locals from callee save frames: " << vmap_offset;
Elliott Hughes68fdbd02011-11-29 19:22:47 -08001594 }
Ian Rogers776ac1f2012-04-13 23:36:36 -07001595#endif
Elliott Hughesdbb40792011-11-18 17:05:22 -08001596
Elliott Hughesad3da692012-02-24 16:51:35 -08001597 // TODO: check that the tag is compatible with the actual type of the slot!
1598
Elliott Hughesdbb40792011-11-18 17:05:22 -08001599 switch (tag) {
1600 case JDWP::JT_BOOLEAN:
1601 {
Elliott Hughescccd84f2011-12-05 16:51:54 -08001602 CHECK_EQ(width, 1U);
Elliott Hughes1bba14f2011-12-01 18:00:36 -08001603 uint32_t intVal = f.GetVReg(m, reg);
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08001604 VLOG(jdwp) << "get boolean local " << reg << " = " << intVal;
Elliott Hughesdbb40792011-11-18 17:05:22 -08001605 JDWP::Set1(buf+1, intVal != 0);
1606 }
1607 break;
1608 case JDWP::JT_BYTE:
1609 {
Elliott Hughescccd84f2011-12-05 16:51:54 -08001610 CHECK_EQ(width, 1U);
Elliott Hughes1bba14f2011-12-01 18:00:36 -08001611 uint32_t intVal = f.GetVReg(m, reg);
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08001612 VLOG(jdwp) << "get byte local " << reg << " = " << intVal;
Elliott Hughesdbb40792011-11-18 17:05:22 -08001613 JDWP::Set1(buf+1, intVal);
1614 }
1615 break;
1616 case JDWP::JT_SHORT:
1617 case JDWP::JT_CHAR:
1618 {
Elliott Hughescccd84f2011-12-05 16:51:54 -08001619 CHECK_EQ(width, 2U);
Elliott Hughes1bba14f2011-12-01 18:00:36 -08001620 uint32_t intVal = f.GetVReg(m, reg);
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08001621 VLOG(jdwp) << "get short/char local " << reg << " = " << intVal;
Elliott Hughesdbb40792011-11-18 17:05:22 -08001622 JDWP::Set2BE(buf+1, intVal);
1623 }
1624 break;
1625 case JDWP::JT_INT:
1626 case JDWP::JT_FLOAT:
1627 {
Elliott Hughescccd84f2011-12-05 16:51:54 -08001628 CHECK_EQ(width, 4U);
Elliott Hughes1bba14f2011-12-01 18:00:36 -08001629 uint32_t intVal = f.GetVReg(m, reg);
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08001630 VLOG(jdwp) << "get int/float local " << reg << " = " << intVal;
Elliott Hughesdbb40792011-11-18 17:05:22 -08001631 JDWP::Set4BE(buf+1, intVal);
1632 }
1633 break;
1634 case JDWP::JT_ARRAY:
1635 {
Elliott Hughescccd84f2011-12-05 16:51:54 -08001636 CHECK_EQ(width, sizeof(JDWP::ObjectId));
Elliott Hughes68fdbd02011-11-29 19:22:47 -08001637 Object* o = reinterpret_cast<Object*>(f.GetVReg(m, reg));
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08001638 VLOG(jdwp) << "get array local " << reg << " = " << o;
Elliott Hughes88c5c352012-03-15 18:49:48 -07001639 if (!Runtime::Current()->GetHeap()->IsHeapAddress(o)) {
Elliott Hughes3d30d9b2011-12-07 17:35:48 -08001640 LOG(FATAL) << "Register " << reg << " expected to hold array: " << o;
Elliott Hughesdbb40792011-11-18 17:05:22 -08001641 }
1642 JDWP::SetObjectId(buf+1, gRegistry->Add(o));
1643 }
1644 break;
Elliott Hughesad3da692012-02-24 16:51:35 -08001645 case JDWP::JT_CLASS_LOADER:
1646 case JDWP::JT_CLASS_OBJECT:
Elliott Hughesdbb40792011-11-18 17:05:22 -08001647 case JDWP::JT_OBJECT:
Elliott Hughesad3da692012-02-24 16:51:35 -08001648 case JDWP::JT_STRING:
1649 case JDWP::JT_THREAD:
1650 case JDWP::JT_THREAD_GROUP:
Elliott Hughesdbb40792011-11-18 17:05:22 -08001651 {
Elliott Hughescccd84f2011-12-05 16:51:54 -08001652 CHECK_EQ(width, sizeof(JDWP::ObjectId));
Elliott Hughes68fdbd02011-11-29 19:22:47 -08001653 Object* o = reinterpret_cast<Object*>(f.GetVReg(m, reg));
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08001654 VLOG(jdwp) << "get object local " << reg << " = " << o;
Elliott Hughes88c5c352012-03-15 18:49:48 -07001655 if (!Runtime::Current()->GetHeap()->IsHeapAddress(o)) {
Elliott Hughes3d30d9b2011-12-07 17:35:48 -08001656 LOG(FATAL) << "Register " << reg << " expected to hold object: " << o;
Elliott Hughesdbb40792011-11-18 17:05:22 -08001657 }
1658 tag = TagFromObject(o);
1659 JDWP::SetObjectId(buf+1, gRegistry->Add(o));
1660 }
1661 break;
1662 case JDWP::JT_DOUBLE:
1663 case JDWP::JT_LONG:
1664 {
Elliott Hughescccd84f2011-12-05 16:51:54 -08001665 CHECK_EQ(width, 8U);
Elliott Hughes1bba14f2011-12-01 18:00:36 -08001666 uint32_t lo = f.GetVReg(m, reg);
1667 uint64_t hi = f.GetVReg(m, reg + 1);
1668 uint64_t longVal = (hi << 32) | lo;
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08001669 VLOG(jdwp) << "get double/long local " << hi << ":" << lo << " = " << longVal;
Elliott Hughesdbb40792011-11-18 17:05:22 -08001670 JDWP::Set8BE(buf+1, longVal);
1671 }
1672 break;
1673 default:
Elliott Hughes3d30d9b2011-12-07 17:35:48 -08001674 LOG(FATAL) << "Unknown tag " << tag;
Elliott Hughesdbb40792011-11-18 17:05:22 -08001675 break;
1676 }
1677
1678 // Prepend tag, which may have been updated.
1679 JDWP::Set1(buf, tag);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001680}
1681
Elliott Hughes1bac54f2012-03-16 12:48:31 -07001682void 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 -08001683 Method** sp = reinterpret_cast<Method**>(frameId);
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08001684 Frame f(sp);
Elliott Hughescccd84f2011-12-05 16:51:54 -08001685 Method* m = f.GetMethod();
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08001686 uint16_t reg = DemangleSlot(slot, m);
Elliott Hughescccd84f2011-12-05 16:51:54 -08001687
Ian Rogers776ac1f2012-04-13 23:36:36 -07001688#if defined(ART_USE_LLVM_COMPILER)
1689 UNIMPLEMENTED(FATAL);
1690#else
Elliott Hughescccd84f2011-12-05 16:51:54 -08001691 const VmapTable vmap_table(m->GetVmapTableRaw());
1692 uint32_t vmap_offset;
1693 if (vmap_table.IsInContext(reg, vmap_offset)) {
Elliott Hughes3d30d9b2011-12-07 17:35:48 -08001694 UNIMPLEMENTED(FATAL) << "Don't know how to pull locals from callee save frames: " << vmap_offset;
Elliott Hughescccd84f2011-12-05 16:51:54 -08001695 }
Ian Rogers776ac1f2012-04-13 23:36:36 -07001696#endif
Elliott Hughescccd84f2011-12-05 16:51:54 -08001697
Elliott Hughesad3da692012-02-24 16:51:35 -08001698 // TODO: check that the tag is compatible with the actual type of the slot!
1699
Elliott Hughescccd84f2011-12-05 16:51:54 -08001700 switch (tag) {
1701 case JDWP::JT_BOOLEAN:
1702 case JDWP::JT_BYTE:
1703 CHECK_EQ(width, 1U);
1704 f.SetVReg(m, reg, static_cast<uint32_t>(value));
1705 break;
1706 case JDWP::JT_SHORT:
1707 case JDWP::JT_CHAR:
1708 CHECK_EQ(width, 2U);
1709 f.SetVReg(m, reg, static_cast<uint32_t>(value));
1710 break;
1711 case JDWP::JT_INT:
1712 case JDWP::JT_FLOAT:
1713 CHECK_EQ(width, 4U);
1714 f.SetVReg(m, reg, static_cast<uint32_t>(value));
1715 break;
1716 case JDWP::JT_ARRAY:
1717 case JDWP::JT_OBJECT:
1718 case JDWP::JT_STRING:
1719 {
1720 CHECK_EQ(width, sizeof(JDWP::ObjectId));
1721 Object* o = gRegistry->Get<Object*>(static_cast<JDWP::ObjectId>(value));
Elliott Hughesad3da692012-02-24 16:51:35 -08001722 if (o == kInvalidObject) {
1723 UNIMPLEMENTED(FATAL) << "return an error code when given an invalid object to store";
1724 }
Elliott Hughescccd84f2011-12-05 16:51:54 -08001725 f.SetVReg(m, reg, static_cast<uint32_t>(reinterpret_cast<uintptr_t>(o)));
1726 }
1727 break;
1728 case JDWP::JT_DOUBLE:
1729 case JDWP::JT_LONG:
1730 CHECK_EQ(width, 8U);
1731 f.SetVReg(m, reg, static_cast<uint32_t>(value));
1732 f.SetVReg(m, reg + 1, static_cast<uint32_t>(value >> 32));
1733 break;
1734 default:
Elliott Hughes3d30d9b2011-12-07 17:35:48 -08001735 LOG(FATAL) << "Unknown tag " << tag;
Elliott Hughescccd84f2011-12-05 16:51:54 -08001736 break;
1737 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001738}
1739
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08001740void Dbg::PostLocationEvent(const Method* m, int dex_pc, Object* this_object, int event_flags) {
1741 Class* c = m->GetDeclaringClass();
1742
1743 JDWP::JdwpLocation location;
1744 location.typeTag = c->IsInterface() ? JDWP::TT_INTERFACE : JDWP::TT_CLASS;
1745 location.classId = gRegistry->Add(c);
1746 location.methodId = ToMethodId(m);
Elliott Hughes972a47b2012-02-21 18:16:06 -08001747 location.dex_pc = m->IsNative() ? -1 : dex_pc;
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08001748
1749 // Note we use "NoReg" so we don't keep track of references that are
1750 // never actually sent to the debugger. 'this_id' is only used to
1751 // compare against registered events...
1752 JDWP::ObjectId this_id = static_cast<JDWP::ObjectId>(reinterpret_cast<uintptr_t>(this_object));
1753 if (gJdwpState->PostLocationEvent(&location, this_id, event_flags)) {
1754 // ...unless there's a registered event, in which case we
1755 // need to really track the class and 'this'.
1756 gRegistry->Add(c);
1757 gRegistry->Add(this_object);
1758 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001759}
1760
Elliott Hughesd07986f2011-12-06 18:27:45 -08001761void Dbg::PostException(Method** sp, Method* throwMethod, uintptr_t throwNativePc, Method* catchMethod, uintptr_t catchNativePc, Object* exception) {
Elliott Hughesc0f09332012-03-26 13:27:06 -07001762 if (!IsDebuggerActive()) {
Ian Rogers0ad5bb82011-12-07 10:16:32 -08001763 return;
1764 }
Elliott Hughes4740cdf2011-12-07 14:07:12 -08001765
Elliott Hughesd07986f2011-12-06 18:27:45 -08001766 JDWP::JdwpLocation throw_location;
1767 SetLocation(throw_location, throwMethod, throwNativePc);
1768 JDWP::JdwpLocation catch_location;
1769 SetLocation(catch_location, catchMethod, catchNativePc);
1770
1771 // We need 'this' for InstanceOnly filters.
1772 JDWP::ObjectId this_id;
1773 GetThisObject(reinterpret_cast<JDWP::FrameId>(sp), &this_id);
1774
1775 /*
1776 * Hand the event to the JDWP exception handler. Note we're using the
1777 * "NoReg" objectID on the exception, which is not strictly correct --
1778 * the exception object WILL be passed up to the debugger if the
1779 * debugger is interested in the event. We do this because the current
1780 * implementation of the debugger object registry never throws anything
1781 * away, and some people were experiencing a fatal build up of exception
1782 * objects when dealing with certain libraries.
1783 */
1784 JDWP::ObjectId exception_id = static_cast<JDWP::ObjectId>(reinterpret_cast<uintptr_t>(exception));
1785 JDWP::RefTypeId exception_class_id = gRegistry->Add(exception->GetClass());
1786
1787 gJdwpState->PostException(&throw_location, exception_id, exception_class_id, &catch_location, this_id);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001788}
1789
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001790void Dbg::PostClassPrepare(Class* c) {
Elliott Hughesc0f09332012-03-26 13:27:06 -07001791 if (!IsDebuggerActive()) {
Elliott Hughes4740cdf2011-12-07 14:07:12 -08001792 return;
1793 }
1794
Elliott Hughes3d30d9b2011-12-07 17:35:48 -08001795 // OLD-TODO - we currently always send both "verified" and "prepared" since
Elliott Hughes4740cdf2011-12-07 14:07:12 -08001796 // debuggers seem to like that. There might be some advantage to honesty,
1797 // since the class may not yet be verified.
1798 int state = JDWP::CS_VERIFIED | JDWP::CS_PREPARED;
1799 JDWP::JdwpTypeTag tag = c->IsInterface() ? JDWP::TT_INTERFACE : JDWP::TT_CLASS;
1800 gJdwpState->PostClassPrepare(tag, gRegistry->Add(c), ClassHelper(c).GetDescriptor(), state);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001801}
1802
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08001803void Dbg::UpdateDebugger(int32_t dex_pc, Thread* self, Method** sp) {
Elliott Hughesc0f09332012-03-26 13:27:06 -07001804 if (!IsDebuggerActive() || dex_pc == -2 /* fake method exit */) {
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08001805 return;
1806 }
1807
Elliott Hughes86964332012-02-15 19:37:42 -08001808 Frame f(sp);
1809 f.Next(); // Skip callee save frame.
1810 Method* m = f.GetMethod();
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08001811
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08001812 if (dex_pc == -1) {
Elliott Hughes2aa2e392012-02-17 17:15:43 -08001813 // We use a pc of -1 to represent method entry, since we might branch back to pc 0 later.
1814 // This means that for this special notification, there can't be anything else interesting
1815 // going on, so we're done already.
1816 Dbg::PostLocationEvent(m, 0, GetThis(f), kMethodEntry);
1817 return;
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08001818 }
1819
Elliott Hughes2aa2e392012-02-17 17:15:43 -08001820 int event_flags = 0;
1821
Elliott Hughes86964332012-02-15 19:37:42 -08001822 if (IsBreakpoint(m, dex_pc)) {
1823 event_flags |= kBreakpoint;
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08001824 }
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08001825
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08001826 // If the debugger is single-stepping one of our threads, check to
1827 // see if we're that thread and we've reached a step point.
Elliott Hughes86964332012-02-15 19:37:42 -08001828 if (gSingleStepControl.is_active && gSingleStepControl.thread == self) {
1829 CHECK(!m->IsNative());
1830 if (gSingleStepControl.step_depth == JDWP::SD_INTO) {
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08001831 // Step into method calls. We break when the line number
1832 // or method pointer changes. If we're in SS_MIN mode, we
1833 // always stop.
Elliott Hughes86964332012-02-15 19:37:42 -08001834 if (gSingleStepControl.method != m) {
1835 event_flags |= kSingleStep;
1836 VLOG(jdwp) << "SS new method";
1837 } else if (gSingleStepControl.step_size == JDWP::SS_MIN) {
1838 event_flags |= kSingleStep;
1839 VLOG(jdwp) << "SS new instruction";
Elliott Hughes2435a572012-02-17 16:07:41 -08001840 } else if (gSingleStepControl.dex_pcs.find(dex_pc) == gSingleStepControl.dex_pcs.end()) {
1841 event_flags |= kSingleStep;
1842 VLOG(jdwp) << "SS new line";
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08001843 }
Elliott Hughes86964332012-02-15 19:37:42 -08001844 } else if (gSingleStepControl.step_depth == JDWP::SD_OVER) {
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08001845 // Step over method calls. We break when the line number is
1846 // different and the frame depth is <= the original frame
1847 // depth. (We can't just compare on the method, because we
1848 // might get unrolled past it by an exception, and it's tricky
1849 // to identify recursion.)
Elliott Hughes86964332012-02-15 19:37:42 -08001850
1851 // TODO: can we just use the value of 'sp'?
1852 int stack_depth = GetStackDepth(self);
1853
1854 if (stack_depth < gSingleStepControl.stack_depth) {
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08001855 // popped up one or more frames, always trigger
Elliott Hughes86964332012-02-15 19:37:42 -08001856 event_flags |= kSingleStep;
1857 VLOG(jdwp) << "SS method pop";
1858 } else if (stack_depth == gSingleStepControl.stack_depth) {
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08001859 // same depth, see if we moved
Elliott Hughes86964332012-02-15 19:37:42 -08001860 if (gSingleStepControl.step_size == JDWP::SS_MIN) {
1861 event_flags |= kSingleStep;
1862 VLOG(jdwp) << "SS new instruction";
Elliott Hughes2435a572012-02-17 16:07:41 -08001863 } else if (gSingleStepControl.dex_pcs.find(dex_pc) == gSingleStepControl.dex_pcs.end()) {
1864 event_flags |= kSingleStep;
1865 VLOG(jdwp) << "SS new line";
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08001866 }
1867 }
1868 } else {
Elliott Hughes86964332012-02-15 19:37:42 -08001869 CHECK_EQ(gSingleStepControl.step_depth, JDWP::SD_OUT);
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08001870 // Return from the current method. We break when the frame
1871 // depth pops up.
1872
1873 // This differs from the "method exit" break in that it stops
1874 // with the PC at the next instruction in the returned-to
1875 // function, rather than the end of the returning function.
Elliott Hughes86964332012-02-15 19:37:42 -08001876
1877 // TODO: can we just use the value of 'sp'?
1878 int stack_depth = GetStackDepth(self);
1879 if (stack_depth < gSingleStepControl.stack_depth) {
1880 event_flags |= kSingleStep;
1881 VLOG(jdwp) << "SS method pop";
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08001882 }
1883 }
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08001884 }
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08001885
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08001886 // Check to see if this is a "return" instruction. JDWP says we should
1887 // send the event *after* the code has been executed, but it also says
1888 // the location we provide is the last instruction. Since the "return"
1889 // instruction has no interesting side effects, we should be safe.
1890 // (We can't just move this down to the returnFromMethod label because
1891 // we potentially need to combine it with other events.)
1892 // We're also not supposed to generate a method exit event if the method
1893 // terminates "with a thrown exception".
Elliott Hughes86964332012-02-15 19:37:42 -08001894 if (dex_pc >= 0) {
1895 const DexFile::CodeItem* code_item = MethodHelper(m).GetCodeItem();
1896 CHECK(code_item != NULL);
1897 CHECK_LT(dex_pc, static_cast<int32_t>(code_item->insns_size_in_code_units_));
1898 if (Instruction::At(&code_item->insns_[dex_pc])->IsReturn()) {
1899 event_flags |= kMethodExit;
1900 }
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08001901 }
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08001902
1903 // If there's something interesting going on, see if it matches one
1904 // of the debugger filters.
1905 if (event_flags != 0) {
Elliott Hughes86964332012-02-15 19:37:42 -08001906 Dbg::PostLocationEvent(m, dex_pc, GetThis(f), event_flags);
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08001907 }
1908}
1909
Elliott Hughes86964332012-02-15 19:37:42 -08001910void Dbg::WatchLocation(const JDWP::JdwpLocation* location) {
1911 MutexLock mu(gBreakpointsLock);
1912 Method* m = FromMethodId(location->methodId);
Elliott Hughes972a47b2012-02-21 18:16:06 -08001913 gBreakpoints.push_back(Breakpoint(m, location->dex_pc));
Elliott Hughes86964332012-02-15 19:37:42 -08001914 VLOG(jdwp) << "Set breakpoint #" << (gBreakpoints.size() - 1) << ": " << gBreakpoints[gBreakpoints.size() - 1];
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001915}
1916
Elliott Hughes86964332012-02-15 19:37:42 -08001917void Dbg::UnwatchLocation(const JDWP::JdwpLocation* location) {
1918 MutexLock mu(gBreakpointsLock);
1919 Method* m = FromMethodId(location->methodId);
1920 for (size_t i = 0; i < gBreakpoints.size(); ++i) {
Elliott Hughes972a47b2012-02-21 18:16:06 -08001921 if (gBreakpoints[i].method == m && gBreakpoints[i].dex_pc == location->dex_pc) {
Elliott Hughes86964332012-02-15 19:37:42 -08001922 VLOG(jdwp) << "Removed breakpoint #" << i << ": " << gBreakpoints[i];
1923 gBreakpoints.erase(gBreakpoints.begin() + i);
1924 return;
1925 }
1926 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001927}
1928
Elliott Hughes2435a572012-02-17 16:07:41 -08001929JDWP::JdwpError Dbg::ConfigureStep(JDWP::ObjectId threadId, JDWP::JdwpStepSize step_size, JDWP::JdwpStepDepth step_depth) {
Elliott Hughes86964332012-02-15 19:37:42 -08001930 Thread* thread = DecodeThread(threadId);
Elliott Hughes2435a572012-02-17 16:07:41 -08001931 if (thread == NULL) {
1932 return JDWP::ERR_INVALID_THREAD;
1933 }
Elliott Hughes86964332012-02-15 19:37:42 -08001934
1935 // TODO: there's no theoretical reason why we couldn't support single-stepping
1936 // of multiple threads at once, but we never did so historically.
1937 if (gSingleStepControl.thread != NULL && thread != gSingleStepControl.thread) {
1938 LOG(WARNING) << "single-step already active for " << *gSingleStepControl.thread
1939 << "; switching to " << *thread;
1940 }
1941
Elliott Hughes2435a572012-02-17 16:07:41 -08001942 //
1943 // Work out what Method* we're in, the current line number, and how deep the stack currently
1944 // is for step-out.
1945 //
1946
Elliott Hughes86964332012-02-15 19:37:42 -08001947 struct SingleStepStackVisitor : public Thread::StackVisitor {
1948 SingleStepStackVisitor() {
1949 gSingleStepControl.method = NULL;
1950 gSingleStepControl.stack_depth = 0;
1951 }
Elliott Hughes530fa002012-03-12 11:44:49 -07001952 bool VisitFrame(const Frame& f, uintptr_t pc) {
Elliott Hughes86964332012-02-15 19:37:42 -08001953 if (f.HasMethod()) {
1954 ++gSingleStepControl.stack_depth;
1955 if (gSingleStepControl.method == NULL) {
Elliott Hughes2435a572012-02-17 16:07:41 -08001956 const Method* m = f.GetMethod();
1957 const DexCache* dex_cache = m->GetDeclaringClass()->GetDexCache();
1958 gSingleStepControl.method = m;
1959 gSingleStepControl.line_number = -1;
1960 if (dex_cache != NULL) {
1961 const DexFile& dex_file = Runtime::Current()->GetClassLinker()->FindDexFile(dex_cache);
1962 gSingleStepControl.line_number = dex_file.GetLineNumFromPC(m, m->ToDexPC(pc));
1963 }
Elliott Hughes86964332012-02-15 19:37:42 -08001964 }
1965 }
Elliott Hughes530fa002012-03-12 11:44:49 -07001966 return true;
Elliott Hughes86964332012-02-15 19:37:42 -08001967 }
1968 };
1969 SingleStepStackVisitor visitor;
1970 thread->WalkStack(&visitor);
1971
Elliott Hughes2435a572012-02-17 16:07:41 -08001972 //
1973 // Find the dex_pc values that correspond to the current line, for line-based single-stepping.
1974 //
1975
1976 struct DebugCallbackContext {
1977 DebugCallbackContext() {
1978 last_pc_valid = false;
1979 last_pc = 0;
Elliott Hughes2435a572012-02-17 16:07:41 -08001980 }
1981
1982 static bool Callback(void* raw_context, uint32_t address, uint32_t line_number) {
1983 DebugCallbackContext* context = reinterpret_cast<DebugCallbackContext*>(raw_context);
1984 if (static_cast<int32_t>(line_number) == gSingleStepControl.line_number) {
1985 if (!context->last_pc_valid) {
1986 // Everything from this address until the next line change is ours.
1987 context->last_pc = address;
1988 context->last_pc_valid = true;
1989 }
1990 // Otherwise, if we're already in a valid range for this line,
1991 // just keep going (shouldn't really happen)...
1992 } else if (context->last_pc_valid) { // and the line number is new
1993 // Add everything from the last entry up until here to the set
1994 for (uint32_t dex_pc = context->last_pc; dex_pc < address; ++dex_pc) {
1995 gSingleStepControl.dex_pcs.insert(dex_pc);
1996 }
1997 context->last_pc_valid = false;
1998 }
1999 return false; // There may be multiple entries for any given line.
2000 }
2001
2002 ~DebugCallbackContext() {
2003 // If the line number was the last in the position table...
2004 if (last_pc_valid) {
2005 size_t end = MethodHelper(gSingleStepControl.method).GetCodeItem()->insns_size_in_code_units_;
2006 for (uint32_t dex_pc = last_pc; dex_pc < end; ++dex_pc) {
2007 gSingleStepControl.dex_pcs.insert(dex_pc);
2008 }
2009 }
2010 }
2011
2012 bool last_pc_valid;
2013 uint32_t last_pc;
2014 };
Elliott Hughes3e2e1a22012-02-21 11:33:41 -08002015 gSingleStepControl.dex_pcs.clear();
Elliott Hughes2435a572012-02-17 16:07:41 -08002016 const Method* m = gSingleStepControl.method;
Elliott Hughes3e2e1a22012-02-21 11:33:41 -08002017 if (m->IsNative()) {
2018 gSingleStepControl.line_number = -1;
2019 } else {
2020 DebugCallbackContext context;
2021 MethodHelper mh(m);
2022 mh.GetDexFile().DecodeDebugInfo(mh.GetCodeItem(), m->IsStatic(), m->GetDexMethodIndex(),
2023 DebugCallbackContext::Callback, NULL, &context);
2024 }
Elliott Hughes2435a572012-02-17 16:07:41 -08002025
2026 //
2027 // Everything else...
2028 //
2029
Elliott Hughes86964332012-02-15 19:37:42 -08002030 gSingleStepControl.thread = thread;
2031 gSingleStepControl.step_size = step_size;
2032 gSingleStepControl.step_depth = step_depth;
2033 gSingleStepControl.is_active = true;
2034
Elliott Hughes2435a572012-02-17 16:07:41 -08002035 if (VLOG_IS_ON(jdwp)) {
2036 VLOG(jdwp) << "Single-step thread: " << *gSingleStepControl.thread;
2037 VLOG(jdwp) << "Single-step step size: " << gSingleStepControl.step_size;
2038 VLOG(jdwp) << "Single-step step depth: " << gSingleStepControl.step_depth;
2039 VLOG(jdwp) << "Single-step current method: " << PrettyMethod(gSingleStepControl.method);
2040 VLOG(jdwp) << "Single-step current line: " << gSingleStepControl.line_number;
2041 VLOG(jdwp) << "Single-step current stack depth: " << gSingleStepControl.stack_depth;
2042 VLOG(jdwp) << "Single-step dex_pc values:";
2043 for (std::set<uint32_t>::iterator it = gSingleStepControl.dex_pcs.begin() ; it != gSingleStepControl.dex_pcs.end(); ++it) {
Elliott Hughes229feb72012-02-23 13:33:29 -08002044 VLOG(jdwp) << StringPrintf(" %#x", *it);
Elliott Hughes2435a572012-02-17 16:07:41 -08002045 }
2046 }
2047
2048 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002049}
2050
Elliott Hughes1bac54f2012-03-16 12:48:31 -07002051void Dbg::UnconfigureStep(JDWP::ObjectId /*threadId*/) {
Elliott Hughes86964332012-02-15 19:37:42 -08002052 gSingleStepControl.is_active = false;
2053 gSingleStepControl.thread = NULL;
Elliott Hughes2435a572012-02-17 16:07:41 -08002054 gSingleStepControl.dex_pcs.clear();
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002055}
2056
Elliott Hughes45651fd2012-02-21 15:48:20 -08002057static char JdwpTagToShortyChar(JDWP::JdwpTag tag) {
2058 switch (tag) {
2059 default:
2060 LOG(FATAL) << "unknown JDWP tag: " << PrintableChar(tag);
2061
2062 // Primitives.
2063 case JDWP::JT_BYTE: return 'B';
2064 case JDWP::JT_CHAR: return 'C';
2065 case JDWP::JT_FLOAT: return 'F';
2066 case JDWP::JT_DOUBLE: return 'D';
2067 case JDWP::JT_INT: return 'I';
2068 case JDWP::JT_LONG: return 'J';
2069 case JDWP::JT_SHORT: return 'S';
2070 case JDWP::JT_VOID: return 'V';
2071 case JDWP::JT_BOOLEAN: return 'Z';
2072
2073 // Reference types.
2074 case JDWP::JT_ARRAY:
2075 case JDWP::JT_OBJECT:
2076 case JDWP::JT_STRING:
2077 case JDWP::JT_THREAD:
2078 case JDWP::JT_THREAD_GROUP:
2079 case JDWP::JT_CLASS_LOADER:
2080 case JDWP::JT_CLASS_OBJECT:
2081 return 'L';
2082 }
2083}
2084
2085JDWP::JdwpError Dbg::InvokeMethod(JDWP::ObjectId threadId, JDWP::ObjectId objectId, JDWP::RefTypeId classId, JDWP::MethodId methodId, uint32_t arg_count, uint64_t* arg_values, JDWP::JdwpTag* arg_types, uint32_t options, JDWP::JdwpTag* pResultTag, uint64_t* pResultValue, JDWP::ObjectId* pExceptionId) {
Elliott Hughesd07986f2011-12-06 18:27:45 -08002086 ThreadList* thread_list = Runtime::Current()->GetThreadList();
2087
2088 Thread* targetThread = NULL;
2089 DebugInvokeReq* req = NULL;
2090 {
2091 ScopedThreadListLock thread_list_lock;
2092 targetThread = DecodeThread(threadId);
2093 if (targetThread == NULL) {
2094 LOG(ERROR) << "InvokeMethod request for non-existent thread " << threadId;
2095 return JDWP::ERR_INVALID_THREAD;
2096 }
2097 req = targetThread->GetInvokeReq();
2098 if (!req->ready) {
2099 LOG(ERROR) << "InvokeMethod request for thread not stopped by event: " << *targetThread;
2100 return JDWP::ERR_INVALID_THREAD;
2101 }
2102
2103 /*
2104 * We currently have a bug where we don't successfully resume the
2105 * target thread if the suspend count is too deep. We're expected to
2106 * require one "resume" for each "suspend", but when asked to execute
2107 * a method we have to resume fully and then re-suspend it back to the
2108 * same level. (The easiest way to cause this is to type "suspend"
2109 * multiple times in jdb.)
2110 *
2111 * It's unclear what this means when the event specifies "resume all"
2112 * and some threads are suspended more deeply than others. This is
2113 * a rare problem, so for now we just prevent it from hanging forever
2114 * by rejecting the method invocation request. Without this, we will
2115 * be stuck waiting on a suspended thread.
2116 */
2117 int suspend_count = targetThread->GetSuspendCount();
2118 if (suspend_count > 1) {
2119 LOG(ERROR) << *targetThread << " suspend count too deep for method invocation: " << suspend_count;
2120 return JDWP::ERR_THREAD_SUSPENDED; // Probably not expected here.
2121 }
2122
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08002123 JDWP::JdwpError status;
Elliott Hughes45651fd2012-02-21 15:48:20 -08002124 Object* receiver = gRegistry->Get<Object*>(objectId);
2125 if (receiver == kInvalidObject) {
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08002126 return JDWP::ERR_INVALID_OBJECT;
2127 }
Elliott Hughes45651fd2012-02-21 15:48:20 -08002128
2129 Object* thread = gRegistry->Get<Object*>(threadId);
2130 if (thread == kInvalidObject) {
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08002131 return JDWP::ERR_INVALID_OBJECT;
2132 }
Elliott Hughes45651fd2012-02-21 15:48:20 -08002133 // TODO: check that 'thread' is actually a java.lang.Thread!
2134
2135 Class* c = DecodeClass(classId, status);
2136 if (c == NULL) {
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08002137 return status;
2138 }
Elliott Hughes45651fd2012-02-21 15:48:20 -08002139
2140 Method* m = FromMethodId(methodId);
2141 if (m->IsStatic() != (receiver == NULL)) {
2142 return JDWP::ERR_INVALID_METHODID;
2143 }
2144 if (m->IsStatic()) {
2145 if (m->GetDeclaringClass() != c) {
2146 return JDWP::ERR_INVALID_METHODID;
2147 }
2148 } else {
2149 if (!m->GetDeclaringClass()->IsAssignableFrom(c)) {
2150 return JDWP::ERR_INVALID_METHODID;
2151 }
2152 }
2153
2154 // Check the argument list matches the method.
2155 MethodHelper mh(m);
2156 if (mh.GetShortyLength() - 1 != arg_count) {
2157 return JDWP::ERR_ILLEGAL_ARGUMENT;
2158 }
2159 const char* shorty = mh.GetShorty();
2160 for (size_t i = 0; i < arg_count; ++i) {
2161 if (shorty[i + 1] != JdwpTagToShortyChar(arg_types[i])) {
2162 return JDWP::ERR_ILLEGAL_ARGUMENT;
2163 }
2164 }
2165
2166 req->receiver_ = receiver;
2167 req->thread_ = thread;
2168 req->class_ = c;
2169 req->method_ = m;
2170 req->arg_count_ = arg_count;
2171 req->arg_values_ = arg_values;
Elliott Hughesd07986f2011-12-06 18:27:45 -08002172 req->options_ = options;
2173 req->invoke_needed_ = true;
2174 }
2175
2176 // The fact that we've released the thread list lock is a bit risky --- if the thread goes
2177 // away we're sitting high and dry -- but we must release this before the ResumeAllThreads
2178 // call, and it's unwise to hold it during WaitForSuspend.
2179
2180 {
2181 /*
2182 * We change our (JDWP thread) status, which should be THREAD_RUNNING,
Elliott Hughes81ff3182012-03-23 20:35:56 -07002183 * so we can suspend for a GC if the invoke request causes us to
Elliott Hughesd07986f2011-12-06 18:27:45 -08002184 * run out of memory. It's also a good idea to change it before locking
2185 * the invokeReq mutex, although that should never be held for long.
2186 */
Elliott Hughes34e06962012-04-09 13:55:55 -07002187 ScopedThreadStateChange tsc(Thread::Current(), kVmWait);
Elliott Hughesd07986f2011-12-06 18:27:45 -08002188
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08002189 VLOG(jdwp) << " Transferring control to event thread";
Elliott Hughesd07986f2011-12-06 18:27:45 -08002190 {
2191 MutexLock mu(req->lock_);
2192
2193 if ((options & JDWP::INVOKE_SINGLE_THREADED) == 0) {
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08002194 VLOG(jdwp) << " Resuming all threads";
Elliott Hughesd07986f2011-12-06 18:27:45 -08002195 thread_list->ResumeAll(true);
2196 } else {
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08002197 VLOG(jdwp) << " Resuming event thread only";
Elliott Hughesd07986f2011-12-06 18:27:45 -08002198 thread_list->Resume(targetThread, true);
2199 }
2200
2201 // Wait for the request to finish executing.
2202 while (req->invoke_needed_) {
2203 req->cond_.Wait(req->lock_);
2204 }
2205 }
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08002206 VLOG(jdwp) << " Control has returned from event thread";
Elliott Hughesd07986f2011-12-06 18:27:45 -08002207
2208 /* wait for thread to re-suspend itself */
2209 targetThread->WaitUntilSuspended();
2210 //dvmWaitForSuspend(targetThread);
2211 }
2212
2213 /*
2214 * Suspend the threads. We waited for the target thread to suspend
2215 * itself, so all we need to do is suspend the others.
2216 *
2217 * The suspendAllThreads() call will double-suspend the event thread,
2218 * so we want to resume the target thread once to keep the books straight.
2219 */
2220 if ((options & JDWP::INVOKE_SINGLE_THREADED) == 0) {
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08002221 VLOG(jdwp) << " Suspending all threads";
Elliott Hughesd07986f2011-12-06 18:27:45 -08002222 thread_list->SuspendAll(true);
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08002223 VLOG(jdwp) << " Resuming event thread to balance the count";
Elliott Hughesd07986f2011-12-06 18:27:45 -08002224 thread_list->Resume(targetThread, true);
2225 }
2226
2227 // Copy the result.
2228 *pResultTag = req->result_tag;
2229 if (IsPrimitiveTag(req->result_tag)) {
Elliott Hughesf24d3ce2012-04-11 17:43:37 -07002230 *pResultValue = req->result_value.GetJ();
Elliott Hughesd07986f2011-12-06 18:27:45 -08002231 } else {
Elliott Hughesf24d3ce2012-04-11 17:43:37 -07002232 *pResultValue = gRegistry->Add(req->result_value.GetL());
Elliott Hughesd07986f2011-12-06 18:27:45 -08002233 }
2234 *pExceptionId = req->exception;
2235 return req->error;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002236}
2237
2238void Dbg::ExecuteMethod(DebugInvokeReq* pReq) {
Elliott Hughesd07986f2011-12-06 18:27:45 -08002239 Thread* self = Thread::Current();
2240
Elliott Hughes81ff3182012-03-23 20:35:56 -07002241 // We can be called while an exception is pending. We need
Elliott Hughesd07986f2011-12-06 18:27:45 -08002242 // to preserve that across the method invocation.
2243 SirtRef<Throwable> old_exception(self->GetException());
2244 self->ClearException();
2245
Elliott Hughes34e06962012-04-09 13:55:55 -07002246 ScopedThreadStateChange tsc(self, kRunnable);
Elliott Hughesd07986f2011-12-06 18:27:45 -08002247
2248 // Translate the method through the vtable, unless the debugger wants to suppress it.
2249 Method* m = pReq->method_;
2250 if ((pReq->options_ & JDWP::INVOKE_NONVIRTUAL) == 0 && pReq->receiver_ != NULL) {
Elliott Hughes45651fd2012-02-21 15:48:20 -08002251 Method* actual_method = pReq->class_->FindVirtualMethodForVirtualOrInterface(pReq->method_);
2252 if (actual_method != m) {
2253 VLOG(jdwp) << "ExecuteMethod translated " << PrettyMethod(m) << " to " << PrettyMethod(actual_method);
2254 m = actual_method;
2255 }
Elliott Hughesd07986f2011-12-06 18:27:45 -08002256 }
Elliott Hughes45651fd2012-02-21 15:48:20 -08002257 VLOG(jdwp) << "ExecuteMethod " << PrettyMethod(m);
Elliott Hughesd07986f2011-12-06 18:27:45 -08002258 CHECK(m != NULL);
2259
2260 CHECK_EQ(sizeof(jvalue), sizeof(uint64_t));
2261
Elliott Hughes45651fd2012-02-21 15:48:20 -08002262 LOG(INFO) << "self=" << self << " pReq->receiver_=" << pReq->receiver_ << " m=" << m << " #" << pReq->arg_count_ << " " << pReq->arg_values_;
2263 pReq->result_value = InvokeWithJValues(self, pReq->receiver_, m, reinterpret_cast<JValue*>(pReq->arg_values_));
Elliott Hughesd07986f2011-12-06 18:27:45 -08002264
2265 pReq->exception = gRegistry->Add(self->GetException());
2266 pReq->result_tag = BasicTagFromDescriptor(MethodHelper(m).GetShorty());
2267 if (pReq->exception != 0) {
2268 Object* exc = self->GetException();
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08002269 VLOG(jdwp) << " JDWP invocation returning with exception=" << exc << " " << PrettyTypeOf(exc);
Elliott Hughesd07986f2011-12-06 18:27:45 -08002270 self->ClearException();
Elliott Hughesf24d3ce2012-04-11 17:43:37 -07002271 pReq->result_value.SetJ(0);
Elliott Hughesd07986f2011-12-06 18:27:45 -08002272 } else if (pReq->result_tag == JDWP::JT_OBJECT) {
2273 /* if no exception thrown, examine object result more closely */
Elliott Hughesf24d3ce2012-04-11 17:43:37 -07002274 JDWP::JdwpTag new_tag = TagFromObject(pReq->result_value.GetL());
Elliott Hughesd07986f2011-12-06 18:27:45 -08002275 if (new_tag != pReq->result_tag) {
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08002276 VLOG(jdwp) << " JDWP promoted result from " << pReq->result_tag << " to " << new_tag;
Elliott Hughesd07986f2011-12-06 18:27:45 -08002277 pReq->result_tag = new_tag;
2278 }
2279
2280 /*
2281 * Register the object. We don't actually need an ObjectId yet,
2282 * but we do need to be sure that the GC won't move or discard the
2283 * object when we switch out of RUNNING. The ObjectId conversion
2284 * will add the object to the "do not touch" list.
2285 *
2286 * We can't use the "tracked allocation" mechanism here because
2287 * the object is going to be handed off to a different thread.
2288 */
Elliott Hughesf24d3ce2012-04-11 17:43:37 -07002289 gRegistry->Add(pReq->result_value.GetL());
Elliott Hughesd07986f2011-12-06 18:27:45 -08002290 }
2291
2292 if (old_exception.get() != NULL) {
2293 self->SetException(old_exception.get());
2294 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002295}
2296
Elliott Hughesd07986f2011-12-06 18:27:45 -08002297/*
2298 * Register an object ID that might not have been registered previously.
2299 *
2300 * Normally this wouldn't happen -- the conversion to an ObjectId would
2301 * have added the object to the registry -- but in some cases (e.g.
2302 * throwing exceptions) we really want to do the registration late.
2303 */
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002304void Dbg::RegisterObjectId(JDWP::ObjectId id) {
Elliott Hughesd07986f2011-12-06 18:27:45 -08002305 gRegistry->Add(reinterpret_cast<Object*>(id));
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002306}
2307
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07002308/*
2309 * "buf" contains a full JDWP packet, possibly with multiple chunks. We
2310 * need to process each, accumulate the replies, and ship the whole thing
2311 * back.
2312 *
2313 * Returns "true" if we have a reply. The reply buffer is newly allocated,
2314 * and includes the chunk type/length, followed by the data.
2315 *
Elliott Hughes3d30d9b2011-12-07 17:35:48 -08002316 * OLD-TODO: we currently assume that the request and reply include a single
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07002317 * chunk. If this becomes inconvenient we will need to adapt.
2318 */
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002319bool Dbg::DdmHandlePacket(const uint8_t* buf, int dataLen, uint8_t** pReplyBuf, int* pReplyLen) {
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07002320 CHECK_GE(dataLen, 0);
2321
2322 Thread* self = Thread::Current();
2323 JNIEnv* env = self->GetJniEnv();
2324
Elliott Hughes844f9a02012-01-24 20:19:58 -08002325 static jclass Chunk_class = CacheClass(env, "org/apache/harmony/dalvik/ddmc/Chunk");
2326 static jclass DdmServer_class = CacheClass(env, "org/apache/harmony/dalvik/ddmc/DdmServer");
2327 static jmethodID dispatch_mid = env->GetStaticMethodID(DdmServer_class, "dispatch", "(I[BII)Lorg/apache/harmony/dalvik/ddmc/Chunk;");
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07002328 static jfieldID data_fid = env->GetFieldID(Chunk_class, "data", "[B");
2329 static jfieldID length_fid = env->GetFieldID(Chunk_class, "length", "I");
2330 static jfieldID offset_fid = env->GetFieldID(Chunk_class, "offset", "I");
2331 static jfieldID type_fid = env->GetFieldID(Chunk_class, "type", "I");
2332
2333 // Create a byte[] corresponding to 'buf'.
Elliott Hughes6a5bd492011-10-28 14:33:57 -07002334 ScopedLocalRef<jbyteArray> dataArray(env, env->NewByteArray(dataLen));
2335 if (dataArray.get() == NULL) {
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07002336 LOG(WARNING) << "byte[] allocation failed: " << dataLen;
2337 env->ExceptionClear();
2338 return false;
2339 }
Elliott Hughes6a5bd492011-10-28 14:33:57 -07002340 env->SetByteArrayRegion(dataArray.get(), 0, dataLen, reinterpret_cast<const jbyte*>(buf));
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07002341
2342 const int kChunkHdrLen = 8;
2343
2344 // Run through and find all chunks. [Currently just find the first.]
Elliott Hughes6a5bd492011-10-28 14:33:57 -07002345 ScopedByteArrayRO contents(env, dataArray.get());
Elliott Hughesf7c3b662011-10-27 12:04:56 -07002346 jint type = JDWP::Get4BE(reinterpret_cast<const uint8_t*>(&contents[0]));
2347 jint length = JDWP::Get4BE(reinterpret_cast<const uint8_t*>(&contents[4]));
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07002348 jint offset = kChunkHdrLen;
2349 if (offset + length > dataLen) {
2350 LOG(WARNING) << StringPrintf("bad chunk found (len=%u pktLen=%d)", length, dataLen);
2351 return false;
2352 }
2353
2354 // Call "private static Chunk dispatch(int type, byte[] data, int offset, int length)".
Elliott Hughes6a5bd492011-10-28 14:33:57 -07002355 ScopedLocalRef<jobject> chunk(env, env->CallStaticObjectMethod(DdmServer_class, dispatch_mid, type, dataArray.get(), offset, length));
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07002356 if (env->ExceptionCheck()) {
2357 LOG(INFO) << StringPrintf("Exception thrown by dispatcher for 0x%08x", type);
2358 env->ExceptionDescribe();
2359 env->ExceptionClear();
2360 return false;
2361 }
2362
Elliott Hughes6a5bd492011-10-28 14:33:57 -07002363 if (chunk.get() == NULL) {
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07002364 return false;
2365 }
2366
2367 /*
2368 * Pull the pieces out of the chunk. We copy the results into a
2369 * newly-allocated buffer that the caller can free. We don't want to
2370 * continue using the Chunk object because nothing has a reference to it.
2371 *
2372 * We could avoid this by returning type/data/offset/length and having
2373 * the caller be aware of the object lifetime issues, but that
Elliott Hughes81ff3182012-03-23 20:35:56 -07002374 * integrates the JDWP code more tightly into the rest of the runtime, and doesn't work
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07002375 * if we have responses for multiple chunks.
2376 *
2377 * So we're pretty much stuck with copying data around multiple times.
2378 */
Elliott Hughes6a5bd492011-10-28 14:33:57 -07002379 ScopedLocalRef<jbyteArray> replyData(env, reinterpret_cast<jbyteArray>(env->GetObjectField(chunk.get(), data_fid)));
2380 length = env->GetIntField(chunk.get(), length_fid);
2381 offset = env->GetIntField(chunk.get(), offset_fid);
2382 type = env->GetIntField(chunk.get(), type_fid);
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07002383
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08002384 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 -07002385 if (length == 0 || replyData.get() == NULL) {
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07002386 return false;
2387 }
2388
Elliott Hughes6a5bd492011-10-28 14:33:57 -07002389 jsize replyLength = env->GetArrayLength(replyData.get());
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07002390 if (offset + length > replyLength) {
2391 LOG(WARNING) << StringPrintf("chunk off=%d len=%d exceeds reply array len %d", offset, length, replyLength);
2392 return false;
2393 }
2394
2395 uint8_t* reply = new uint8_t[length + kChunkHdrLen];
2396 if (reply == NULL) {
2397 LOG(WARNING) << "malloc failed: " << (length + kChunkHdrLen);
2398 return false;
2399 }
Elliott Hughesf7c3b662011-10-27 12:04:56 -07002400 JDWP::Set4BE(reply + 0, type);
2401 JDWP::Set4BE(reply + 4, length);
Elliott Hughes6a5bd492011-10-28 14:33:57 -07002402 env->GetByteArrayRegion(replyData.get(), offset, length, reinterpret_cast<jbyte*>(reply + kChunkHdrLen));
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07002403
2404 *pReplyBuf = reply;
2405 *pReplyLen = length + kChunkHdrLen;
2406
Elliott Hughesba8eee12012-01-24 20:25:24 -08002407 VLOG(jdwp) << StringPrintf("dvmHandleDdm returning type=%.4s buf=%p len=%d", reinterpret_cast<char*>(reply), reply, length);
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07002408 return true;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002409}
2410
Elliott Hughesa2155262011-11-16 16:26:58 -08002411void Dbg::DdmBroadcast(bool connect) {
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08002412 VLOG(jdwp) << "Broadcasting DDM " << (connect ? "connect" : "disconnect") << "...";
Elliott Hughes47fce012011-10-25 18:37:19 -07002413
2414 Thread* self = Thread::Current();
Elliott Hughes34e06962012-04-09 13:55:55 -07002415 if (self->GetState() != kRunnable) {
Elliott Hughes47fce012011-10-25 18:37:19 -07002416 LOG(ERROR) << "DDM broadcast in thread state " << self->GetState();
2417 /* try anyway? */
2418 }
2419
2420 JNIEnv* env = self->GetJniEnv();
Elliott Hughes844f9a02012-01-24 20:19:58 -08002421 static jclass DdmServer_class = CacheClass(env, "org/apache/harmony/dalvik/ddmc/DdmServer");
Elliott Hughes47fce012011-10-25 18:37:19 -07002422 static jmethodID broadcast_mid = env->GetStaticMethodID(DdmServer_class, "broadcast", "(I)V");
2423 jint event = connect ? 1 /*DdmServer.CONNECTED*/ : 2 /*DdmServer.DISCONNECTED*/;
2424 env->CallStaticVoidMethod(DdmServer_class, broadcast_mid, event);
2425 if (env->ExceptionCheck()) {
2426 LOG(ERROR) << "DdmServer.broadcast " << event << " failed";
2427 env->ExceptionDescribe();
2428 env->ExceptionClear();
2429 }
2430}
2431
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002432void Dbg::DdmConnected() {
Elliott Hughesa2155262011-11-16 16:26:58 -08002433 Dbg::DdmBroadcast(true);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002434}
2435
2436void Dbg::DdmDisconnected() {
Elliott Hughesa2155262011-11-16 16:26:58 -08002437 Dbg::DdmBroadcast(false);
Elliott Hughes47fce012011-10-25 18:37:19 -07002438 gDdmThreadNotification = false;
2439}
2440
2441/*
Elliott Hughes82188472011-11-07 18:11:48 -08002442 * Send a notification when a thread starts, stops, or changes its name.
Elliott Hughes47fce012011-10-25 18:37:19 -07002443 *
2444 * Because we broadcast the full set of threads when the notifications are
2445 * first enabled, it's possible for "thread" to be actively executing.
2446 */
Elliott Hughes82188472011-11-07 18:11:48 -08002447void Dbg::DdmSendThreadNotification(Thread* t, uint32_t type) {
Elliott Hughes47fce012011-10-25 18:37:19 -07002448 if (!gDdmThreadNotification) {
2449 return;
2450 }
2451
Elliott Hughes82188472011-11-07 18:11:48 -08002452 if (type == CHUNK_TYPE("THDE")) {
Elliott Hughes47fce012011-10-25 18:37:19 -07002453 uint8_t buf[4];
Elliott Hughesf7c3b662011-10-27 12:04:56 -07002454 JDWP::Set4BE(&buf[0], t->GetThinLockId());
Elliott Hughes47fce012011-10-25 18:37:19 -07002455 Dbg::DdmSendChunk(CHUNK_TYPE("THDE"), 4, buf);
Elliott Hughes82188472011-11-07 18:11:48 -08002456 } else {
2457 CHECK(type == CHUNK_TYPE("THCR") || type == CHUNK_TYPE("THNM")) << type;
Elliott Hughes899e7892012-01-24 14:57:32 -08002458 SirtRef<String> name(t->GetThreadName());
Elliott Hughes82188472011-11-07 18:11:48 -08002459 size_t char_count = (name.get() != NULL) ? name->GetLength() : 0;
2460 const jchar* chars = name->GetCharArray()->GetData();
2461
Elliott Hughes21f32d72011-11-09 17:44:13 -08002462 std::vector<uint8_t> bytes;
Elliott Hughes545a0642011-11-08 19:10:03 -08002463 JDWP::Append4BE(bytes, t->GetThinLockId());
2464 JDWP::AppendUtf16BE(bytes, chars, char_count);
Elliott Hughes21f32d72011-11-09 17:44:13 -08002465 CHECK_EQ(bytes.size(), char_count*2 + sizeof(uint32_t)*2);
2466 Dbg::DdmSendChunk(type, bytes);
Elliott Hughes47fce012011-10-25 18:37:19 -07002467 }
2468}
2469
Elliott Hughesa2155262011-11-16 16:26:58 -08002470static void DdmSendThreadStartCallback(Thread* t, void*) {
Elliott Hughes82188472011-11-07 18:11:48 -08002471 Dbg::DdmSendThreadNotification(t, CHUNK_TYPE("THCR"));
Elliott Hughes47fce012011-10-25 18:37:19 -07002472}
2473
2474void Dbg::DdmSetThreadNotification(bool enable) {
2475 // We lock the thread list to avoid sending duplicate events or missing
2476 // a thread change. We should be okay holding this lock while sending
2477 // the messages out. (We have to hold it while accessing a live thread.)
Elliott Hughesbbd9d832011-11-07 14:40:00 -08002478 ScopedThreadListLock thread_list_lock;
Elliott Hughes47fce012011-10-25 18:37:19 -07002479
2480 gDdmThreadNotification = enable;
2481 if (enable) {
Elliott Hughesbfe487b2011-10-26 15:48:55 -07002482 Runtime::Current()->GetThreadList()->ForEach(DdmSendThreadStartCallback, NULL);
Elliott Hughes47fce012011-10-25 18:37:19 -07002483 }
2484}
2485
Elliott Hughesa2155262011-11-16 16:26:58 -08002486void Dbg::PostThreadStartOrStop(Thread* t, uint32_t type) {
Elliott Hughesc0f09332012-03-26 13:27:06 -07002487 if (IsDebuggerActive()) {
Elliott Hughes47fce012011-10-25 18:37:19 -07002488 JDWP::ObjectId id = gRegistry->Add(t->GetPeer());
Elliott Hughes82188472011-11-07 18:11:48 -08002489 gJdwpState->PostThreadChange(id, type == CHUNK_TYPE("THCR"));
Elliott Hughesc0f09332012-03-26 13:27:06 -07002490 // If this thread's just joined the party while we're already debugging, make sure it knows
2491 // to give us updates when it's running.
2492 t->SetDebuggerUpdatesEnabled(true);
Elliott Hughes47fce012011-10-25 18:37:19 -07002493 }
Elliott Hughes82188472011-11-07 18:11:48 -08002494 Dbg::DdmSendThreadNotification(t, type);
Elliott Hughes47fce012011-10-25 18:37:19 -07002495}
2496
2497void Dbg::PostThreadStart(Thread* t) {
Elliott Hughesa2155262011-11-16 16:26:58 -08002498 Dbg::PostThreadStartOrStop(t, CHUNK_TYPE("THCR"));
Elliott Hughes47fce012011-10-25 18:37:19 -07002499}
2500
2501void Dbg::PostThreadDeath(Thread* t) {
Elliott Hughesa2155262011-11-16 16:26:58 -08002502 Dbg::PostThreadStartOrStop(t, CHUNK_TYPE("THDE"));
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002503}
2504
Elliott Hughes82188472011-11-07 18:11:48 -08002505void Dbg::DdmSendChunk(uint32_t type, size_t byte_count, const uint8_t* buf) {
Elliott Hughes3bb81562011-10-21 18:52:59 -07002506 CHECK(buf != NULL);
2507 iovec vec[1];
2508 vec[0].iov_base = reinterpret_cast<void*>(const_cast<uint8_t*>(buf));
2509 vec[0].iov_len = byte_count;
2510 Dbg::DdmSendChunkV(type, vec, 1);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002511}
2512
Elliott Hughes21f32d72011-11-09 17:44:13 -08002513void Dbg::DdmSendChunk(uint32_t type, const std::vector<uint8_t>& bytes) {
2514 DdmSendChunk(type, bytes.size(), &bytes[0]);
2515}
2516
Elliott Hughescccd84f2011-12-05 16:51:54 -08002517void Dbg::DdmSendChunkV(uint32_t type, const struct iovec* iov, int iov_count) {
Elliott Hughes3bb81562011-10-21 18:52:59 -07002518 if (gJdwpState == NULL) {
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08002519 VLOG(jdwp) << "Debugger thread not active, ignoring DDM send: " << type;
Elliott Hughes3bb81562011-10-21 18:52:59 -07002520 } else {
Elliott Hughescccd84f2011-12-05 16:51:54 -08002521 gJdwpState->DdmSendChunkV(type, iov, iov_count);
Elliott Hughes3bb81562011-10-21 18:52:59 -07002522 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002523}
2524
Elliott Hughes767a1472011-10-26 18:49:02 -07002525int Dbg::DdmHandleHpifChunk(HpifWhen when) {
2526 if (when == HPIF_WHEN_NOW) {
Elliott Hughes7162ad92011-10-27 14:08:42 -07002527 DdmSendHeapInfo(when);
Elliott Hughes767a1472011-10-26 18:49:02 -07002528 return true;
2529 }
2530
2531 if (when != HPIF_WHEN_NEVER && when != HPIF_WHEN_NEXT_GC && when != HPIF_WHEN_EVERY_GC) {
2532 LOG(ERROR) << "invalid HpifWhen value: " << static_cast<int>(when);
2533 return false;
2534 }
2535
2536 gDdmHpifWhen = when;
2537 return true;
2538}
2539
2540bool Dbg::DdmHandleHpsgNhsgChunk(Dbg::HpsgWhen when, Dbg::HpsgWhat what, bool native) {
2541 if (when != HPSG_WHEN_NEVER && when != HPSG_WHEN_EVERY_GC) {
2542 LOG(ERROR) << "invalid HpsgWhen value: " << static_cast<int>(when);
2543 return false;
2544 }
2545
2546 if (what != HPSG_WHAT_MERGED_OBJECTS && what != HPSG_WHAT_DISTINCT_OBJECTS) {
2547 LOG(ERROR) << "invalid HpsgWhat value: " << static_cast<int>(what);
2548 return false;
2549 }
2550
2551 if (native) {
2552 gDdmNhsgWhen = when;
2553 gDdmNhsgWhat = what;
2554 } else {
2555 gDdmHpsgWhen = when;
2556 gDdmHpsgWhat = what;
2557 }
2558 return true;
2559}
2560
Elliott Hughes7162ad92011-10-27 14:08:42 -07002561void Dbg::DdmSendHeapInfo(HpifWhen reason) {
2562 // If there's a one-shot 'when', reset it.
2563 if (reason == gDdmHpifWhen) {
2564 if (gDdmHpifWhen == HPIF_WHEN_NEXT_GC) {
2565 gDdmHpifWhen = HPIF_WHEN_NEVER;
2566 }
2567 }
2568
2569 /*
2570 * Chunk HPIF (client --> server)
2571 *
2572 * Heap Info. General information about the heap,
2573 * suitable for a summary display.
2574 *
2575 * [u4]: number of heaps
2576 *
2577 * For each heap:
2578 * [u4]: heap ID
2579 * [u8]: timestamp in ms since Unix epoch
2580 * [u1]: capture reason (same as 'when' value from server)
2581 * [u4]: max heap size in bytes (-Xmx)
2582 * [u4]: current heap size in bytes
2583 * [u4]: current number of bytes allocated
2584 * [u4]: current number of objects allocated
2585 */
2586 uint8_t heap_count = 1;
Elliott Hughesb3bd5f02012-03-08 21:05:27 -08002587 Heap* heap = Runtime::Current()->GetHeap();
Elliott Hughes21f32d72011-11-09 17:44:13 -08002588 std::vector<uint8_t> bytes;
Elliott Hughes545a0642011-11-08 19:10:03 -08002589 JDWP::Append4BE(bytes, heap_count);
2590 JDWP::Append4BE(bytes, 1); // Heap id (bogus; we only have one heap).
2591 JDWP::Append8BE(bytes, MilliTime());
2592 JDWP::Append1BE(bytes, reason);
Elliott Hughesb3bd5f02012-03-08 21:05:27 -08002593 JDWP::Append4BE(bytes, heap->GetMaxMemory()); // Max allowed heap size in bytes.
2594 JDWP::Append4BE(bytes, heap->GetTotalMemory()); // Current heap size in bytes.
2595 JDWP::Append4BE(bytes, heap->GetBytesAllocated());
2596 JDWP::Append4BE(bytes, heap->GetObjectsAllocated());
Elliott Hughes21f32d72011-11-09 17:44:13 -08002597 CHECK_EQ(bytes.size(), 4U + (heap_count * (4 + 8 + 1 + 4 + 4 + 4 + 4)));
2598 Dbg::DdmSendChunk(CHUNK_TYPE("HPIF"), bytes);
Elliott Hughes767a1472011-10-26 18:49:02 -07002599}
2600
Elliott Hughes6a5bd492011-10-28 14:33:57 -07002601enum HpsgSolidity {
2602 SOLIDITY_FREE = 0,
2603 SOLIDITY_HARD = 1,
2604 SOLIDITY_SOFT = 2,
2605 SOLIDITY_WEAK = 3,
2606 SOLIDITY_PHANTOM = 4,
2607 SOLIDITY_FINALIZABLE = 5,
2608 SOLIDITY_SWEEP = 6,
2609};
2610
2611enum HpsgKind {
2612 KIND_OBJECT = 0,
2613 KIND_CLASS_OBJECT = 1,
2614 KIND_ARRAY_1 = 2,
2615 KIND_ARRAY_2 = 3,
2616 KIND_ARRAY_4 = 4,
2617 KIND_ARRAY_8 = 5,
2618 KIND_UNKNOWN = 6,
2619 KIND_NATIVE = 7,
2620};
2621
2622#define HPSG_PARTIAL (1<<7)
2623#define HPSG_STATE(solidity, kind) ((uint8_t)((((kind) & 0x7) << 3) | ((solidity) & 0x7)))
2624
Ian Rogers30fab402012-01-23 15:43:46 -08002625class HeapChunkContext {
2626 public:
Elliott Hughes6a5bd492011-10-28 14:33:57 -07002627 // Maximum chunk size. Obtain this from the formula:
2628 // (((maximum_heap_size / ALLOCATION_UNIT_SIZE) + 255) / 256) * 2
2629 HeapChunkContext(bool merge, bool native)
Ian Rogers30fab402012-01-23 15:43:46 -08002630 : buf_(16384 - 16),
2631 type_(0),
2632 merge_(merge) {
Elliott Hughes6a5bd492011-10-28 14:33:57 -07002633 Reset();
2634 if (native) {
Ian Rogers30fab402012-01-23 15:43:46 -08002635 type_ = CHUNK_TYPE("NHSG");
Elliott Hughes6a5bd492011-10-28 14:33:57 -07002636 } else {
Ian Rogers30fab402012-01-23 15:43:46 -08002637 type_ = merge ? CHUNK_TYPE("HPSG") : CHUNK_TYPE("HPSO");
Elliott Hughes6a5bd492011-10-28 14:33:57 -07002638 }
2639 }
2640
2641 ~HeapChunkContext() {
Ian Rogers30fab402012-01-23 15:43:46 -08002642 if (p_ > &buf_[0]) {
Elliott Hughes6a5bd492011-10-28 14:33:57 -07002643 Flush();
2644 }
2645 }
2646
2647 void EnsureHeader(const void* chunk_ptr) {
Ian Rogers30fab402012-01-23 15:43:46 -08002648 if (!needHeader_) {
Elliott Hughes6a5bd492011-10-28 14:33:57 -07002649 return;
2650 }
2651
2652 // Start a new HPSx chunk.
Ian Rogers30fab402012-01-23 15:43:46 -08002653 JDWP::Write4BE(&p_, 1); // Heap id (bogus; we only have one heap).
2654 JDWP::Write1BE(&p_, 8); // Size of allocation unit, in bytes.
Elliott Hughes6a5bd492011-10-28 14:33:57 -07002655
Ian Rogers30fab402012-01-23 15:43:46 -08002656 JDWP::Write4BE(&p_, reinterpret_cast<uintptr_t>(chunk_ptr)); // virtual address of segment start.
2657 JDWP::Write4BE(&p_, 0); // offset of this piece (relative to the virtual address).
Elliott Hughes6a5bd492011-10-28 14:33:57 -07002658 // [u4]: length of piece, in allocation units
2659 // 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 -08002660 pieceLenField_ = p_;
2661 JDWP::Write4BE(&p_, 0x55555555);
2662 needHeader_ = false;
Elliott Hughes6a5bd492011-10-28 14:33:57 -07002663 }
2664
2665 void Flush() {
2666 // Patch the "length of piece" field.
Ian Rogers30fab402012-01-23 15:43:46 -08002667 CHECK_LE(&buf_[0], pieceLenField_);
2668 CHECK_LE(pieceLenField_, p_);
2669 JDWP::Set4BE(pieceLenField_, totalAllocationUnits_);
Elliott Hughes6a5bd492011-10-28 14:33:57 -07002670
Ian Rogers30fab402012-01-23 15:43:46 -08002671 Dbg::DdmSendChunk(type_, p_ - &buf_[0], &buf_[0]);
Elliott Hughes6a5bd492011-10-28 14:33:57 -07002672 Reset();
2673 }
2674
Ian Rogers30fab402012-01-23 15:43:46 -08002675 static void HeapChunkCallback(void* start, void* end, size_t used_bytes, void* arg) {
2676 reinterpret_cast<HeapChunkContext*>(arg)->HeapChunkCallback(start, end, used_bytes);
Elliott Hughesa2155262011-11-16 16:26:58 -08002677 }
2678
Elliott Hughes6a5bd492011-10-28 14:33:57 -07002679 private:
Elliott Hughesa2155262011-11-16 16:26:58 -08002680 enum { ALLOCATION_UNIT_SIZE = 8 };
2681
Elliott Hughes6a5bd492011-10-28 14:33:57 -07002682 void Reset() {
Ian Rogers30fab402012-01-23 15:43:46 -08002683 p_ = &buf_[0];
2684 totalAllocationUnits_ = 0;
2685 needHeader_ = true;
2686 pieceLenField_ = NULL;
Elliott Hughes6a5bd492011-10-28 14:33:57 -07002687 }
2688
Elliott Hughes1bac54f2012-03-16 12:48:31 -07002689 void HeapChunkCallback(void* start, void* /*end*/, size_t used_bytes) {
Ian Rogers30fab402012-01-23 15:43:46 -08002690 // Note: heap call backs cannot manipulate the heap upon which they are crawling, care is taken
2691 // in the following code not to allocate memory, by ensuring buf_ is of the correct size
2692
2693 const void* user_ptr = used_bytes > 0 ? const_cast<void*>(start) : NULL;
2694 // from malloc.c mem2chunk(mem)
2695 const void* chunk_ptr =
2696 reinterpret_cast<const void*>(reinterpret_cast<const char*>(const_cast<void*>(start)) -
2697 (2 * sizeof(size_t)));
2698 // from malloc.c chunksize
2699 size_t chunk_len = (*reinterpret_cast<size_t* const*>(chunk_ptr))[1] & ~7;
2700
2701
2702 //size_t chunk_len = malloc_usable_size(user_ptr);
Elliott Hughesa2155262011-11-16 16:26:58 -08002703 CHECK_EQ((chunk_len & (ALLOCATION_UNIT_SIZE-1)), 0U);
Elliott Hughes6a5bd492011-10-28 14:33:57 -07002704
Elliott Hughesa2155262011-11-16 16:26:58 -08002705 /* Make sure there's enough room left in the buffer.
2706 * We need to use two bytes for every fractional 256
2707 * allocation units used by the chunk.
2708 */
2709 {
2710 size_t needed = (((chunk_len/ALLOCATION_UNIT_SIZE + 255) / 256) * 2);
Ian Rogers30fab402012-01-23 15:43:46 -08002711 size_t bytesLeft = buf_.size() - (size_t)(p_ - &buf_[0]);
Elliott Hughesa2155262011-11-16 16:26:58 -08002712 if (bytesLeft < needed) {
2713 Flush();
2714 }
Elliott Hughes6a5bd492011-10-28 14:33:57 -07002715
Ian Rogers30fab402012-01-23 15:43:46 -08002716 bytesLeft = buf_.size() - (size_t)(p_ - &buf_[0]);
Elliott Hughesa2155262011-11-16 16:26:58 -08002717 if (bytesLeft < needed) {
Elliott Hughes3d30d9b2011-12-07 17:35:48 -08002718 LOG(WARNING) << "Chunk is too big to transmit (chunk_len=" << chunk_len << ", " << needed << " bytes)";
Elliott Hughesa2155262011-11-16 16:26:58 -08002719 return;
2720 }
2721 }
2722
2723 // OLD-TODO: notice when there's a gap and start a new heap, or at least a new range.
2724 EnsureHeader(chunk_ptr);
2725
2726 // Determine the type of this chunk.
2727 // OLD-TODO: if context.merge, see if this chunk is different from the last chunk.
2728 // If it's the same, we should combine them.
Ian Rogers30fab402012-01-23 15:43:46 -08002729 uint8_t state = ExamineObject(reinterpret_cast<const Object*>(user_ptr), (type_ == CHUNK_TYPE("NHSG")));
Elliott Hughesa2155262011-11-16 16:26:58 -08002730
2731 // Write out the chunk description.
2732 chunk_len /= ALLOCATION_UNIT_SIZE; // convert to allocation units
Ian Rogers30fab402012-01-23 15:43:46 -08002733 totalAllocationUnits_ += chunk_len;
Elliott Hughesa2155262011-11-16 16:26:58 -08002734 while (chunk_len > 256) {
Ian Rogers30fab402012-01-23 15:43:46 -08002735 *p_++ = state | HPSG_PARTIAL;
2736 *p_++ = 255; // length - 1
Elliott Hughesa2155262011-11-16 16:26:58 -08002737 chunk_len -= 256;
2738 }
Ian Rogers30fab402012-01-23 15:43:46 -08002739 *p_++ = state;
2740 *p_++ = chunk_len - 1;
Elliott Hughes6a5bd492011-10-28 14:33:57 -07002741 }
2742
Elliott Hughesa2155262011-11-16 16:26:58 -08002743 uint8_t ExamineObject(const Object* o, bool is_native_heap) {
2744 if (o == NULL) {
2745 return HPSG_STATE(SOLIDITY_FREE, 0);
2746 }
Elliott Hughes6a5bd492011-10-28 14:33:57 -07002747
Elliott Hughesa2155262011-11-16 16:26:58 -08002748 // It's an allocated chunk. Figure out what it is.
Elliott Hughes6a5bd492011-10-28 14:33:57 -07002749
Elliott Hughesa2155262011-11-16 16:26:58 -08002750 // If we're looking at the native heap, we'll just return
2751 // (SOLIDITY_HARD, KIND_NATIVE) for all allocated chunks.
Elliott Hughesb3bd5f02012-03-08 21:05:27 -08002752 if (is_native_heap || !Runtime::Current()->GetHeap()->IsLiveObjectLocked(o)) {
Elliott Hughesa2155262011-11-16 16:26:58 -08002753 return HPSG_STATE(SOLIDITY_HARD, KIND_NATIVE);
2754 }
2755
2756 Class* c = o->GetClass();
2757 if (c == NULL) {
2758 // The object was probably just created but hasn't been initialized yet.
2759 return HPSG_STATE(SOLIDITY_HARD, KIND_OBJECT);
2760 }
2761
Elliott Hughesb3bd5f02012-03-08 21:05:27 -08002762 if (!Runtime::Current()->GetHeap()->IsHeapAddress(c)) {
Elliott Hughes3d30d9b2011-12-07 17:35:48 -08002763 LOG(WARNING) << "Invalid class for managed heap object: " << o << " " << c;
Elliott Hughesa2155262011-11-16 16:26:58 -08002764 return HPSG_STATE(SOLIDITY_HARD, KIND_UNKNOWN);
2765 }
2766
2767 if (c->IsClassClass()) {
2768 return HPSG_STATE(SOLIDITY_HARD, KIND_CLASS_OBJECT);
2769 }
2770
2771 if (c->IsArrayClass()) {
2772 if (o->IsObjectArray()) {
2773 return HPSG_STATE(SOLIDITY_HARD, KIND_ARRAY_4);
2774 }
2775 switch (c->GetComponentSize()) {
2776 case 1: return HPSG_STATE(SOLIDITY_HARD, KIND_ARRAY_1);
2777 case 2: return HPSG_STATE(SOLIDITY_HARD, KIND_ARRAY_2);
2778 case 4: return HPSG_STATE(SOLIDITY_HARD, KIND_ARRAY_4);
2779 case 8: return HPSG_STATE(SOLIDITY_HARD, KIND_ARRAY_8);
2780 }
2781 }
2782
Elliott Hughes6a5bd492011-10-28 14:33:57 -07002783 return HPSG_STATE(SOLIDITY_HARD, KIND_OBJECT);
2784 }
2785
Ian Rogers30fab402012-01-23 15:43:46 -08002786 std::vector<uint8_t> buf_;
2787 uint8_t* p_;
2788 uint8_t* pieceLenField_;
2789 size_t totalAllocationUnits_;
2790 uint32_t type_;
2791 bool merge_;
2792 bool needHeader_;
2793
Elliott Hughesa2155262011-11-16 16:26:58 -08002794 DISALLOW_COPY_AND_ASSIGN(HeapChunkContext);
2795};
Elliott Hughes6a5bd492011-10-28 14:33:57 -07002796
2797void Dbg::DdmSendHeapSegments(bool native) {
2798 Dbg::HpsgWhen when;
2799 Dbg::HpsgWhat what;
2800 if (!native) {
2801 when = gDdmHpsgWhen;
2802 what = gDdmHpsgWhat;
2803 } else {
2804 when = gDdmNhsgWhen;
2805 what = gDdmNhsgWhat;
2806 }
2807 if (when == HPSG_WHEN_NEVER) {
2808 return;
2809 }
2810
2811 // Figure out what kind of chunks we'll be sending.
2812 CHECK(what == HPSG_WHAT_MERGED_OBJECTS || what == HPSG_WHAT_DISTINCT_OBJECTS) << static_cast<int>(what);
2813
2814 // First, send a heap start chunk.
2815 uint8_t heap_id[4];
2816 JDWP::Set4BE(&heap_id[0], 1); // Heap id (bogus; we only have one heap).
2817 Dbg::DdmSendChunk(native ? CHUNK_TYPE("NHST") : CHUNK_TYPE("HPST"), sizeof(heap_id), heap_id);
2818
2819 // Send a series of heap segment chunks.
Elliott Hughesa2155262011-11-16 16:26:58 -08002820 HeapChunkContext context((what == HPSG_WHAT_MERGED_OBJECTS), native);
2821 if (native) {
Ian Rogers30fab402012-01-23 15:43:46 -08002822 // TODO: enable when bionic has moved to dlmalloc 2.8.5
2823 // dlmalloc_inspect_all(HeapChunkContext::HeapChunkCallback, &context);
2824 UNIMPLEMENTED(WARNING) << "Native heap send heap segments";
Elliott Hughesa2155262011-11-16 16:26:58 -08002825 } else {
Elliott Hughesb3bd5f02012-03-08 21:05:27 -08002826 Heap* heap = Runtime::Current()->GetHeap();
2827 heap->GetAllocSpace()->Walk(HeapChunkContext::HeapChunkCallback, &context);
Elliott Hughesa2155262011-11-16 16:26:58 -08002828 }
Elliott Hughes6a5bd492011-10-28 14:33:57 -07002829
2830 // Finally, send a heap end chunk.
2831 Dbg::DdmSendChunk(native ? CHUNK_TYPE("NHEN") : CHUNK_TYPE("HPEN"), sizeof(heap_id), heap_id);
Elliott Hughes767a1472011-10-26 18:49:02 -07002832}
2833
Elliott Hughes545a0642011-11-08 19:10:03 -08002834void Dbg::SetAllocTrackingEnabled(bool enabled) {
2835 MutexLock mu(gAllocTrackerLock);
2836 if (enabled) {
2837 if (recent_allocation_records_ == NULL) {
2838 LOG(INFO) << "Enabling alloc tracker (" << kNumAllocRecords << " entries, "
2839 << kMaxAllocRecordStackDepth << " frames --> "
2840 << (sizeof(AllocRecord) * kNumAllocRecords) << " bytes)";
2841 gAllocRecordHead = gAllocRecordCount = 0;
2842 recent_allocation_records_ = new AllocRecord[kNumAllocRecords];
2843 CHECK(recent_allocation_records_ != NULL);
2844 }
2845 } else {
2846 delete[] recent_allocation_records_;
2847 recent_allocation_records_ = NULL;
2848 }
2849}
2850
2851struct AllocRecordStackVisitor : public Thread::StackVisitor {
Elliott Hughesba8eee12012-01-24 20:25:24 -08002852 explicit AllocRecordStackVisitor(AllocRecord* record) : record(record), depth(0) {
Elliott Hughes545a0642011-11-08 19:10:03 -08002853 }
2854
Elliott Hughes530fa002012-03-12 11:44:49 -07002855 bool VisitFrame(const Frame& f, uintptr_t pc) {
Elliott Hughes545a0642011-11-08 19:10:03 -08002856 if (depth >= kMaxAllocRecordStackDepth) {
Elliott Hughes530fa002012-03-12 11:44:49 -07002857 return false;
Elliott Hughes545a0642011-11-08 19:10:03 -08002858 }
Elliott Hughes530fa002012-03-12 11:44:49 -07002859 if (f.HasMethod()) {
2860 record->stack[depth].method = f.GetMethod();
2861 record->stack[depth].raw_pc = pc;
2862 ++depth;
Elliott Hughes545a0642011-11-08 19:10:03 -08002863 }
Elliott Hughes530fa002012-03-12 11:44:49 -07002864 return true;
Elliott Hughes545a0642011-11-08 19:10:03 -08002865 }
2866
2867 ~AllocRecordStackVisitor() {
2868 // Clear out any unused stack trace elements.
2869 for (; depth < kMaxAllocRecordStackDepth; ++depth) {
2870 record->stack[depth].method = NULL;
2871 record->stack[depth].raw_pc = 0;
2872 }
2873 }
2874
2875 AllocRecord* record;
2876 size_t depth;
2877};
2878
2879void Dbg::RecordAllocation(Class* type, size_t byte_count) {
2880 Thread* self = Thread::Current();
2881 CHECK(self != NULL);
2882
2883 MutexLock mu(gAllocTrackerLock);
2884 if (recent_allocation_records_ == NULL) {
2885 return;
2886 }
2887
2888 // Advance and clip.
2889 if (++gAllocRecordHead == kNumAllocRecords) {
2890 gAllocRecordHead = 0;
2891 }
2892
2893 // Fill in the basics.
2894 AllocRecord* record = &recent_allocation_records_[gAllocRecordHead];
2895 record->type = type;
2896 record->byte_count = byte_count;
2897 record->thin_lock_id = self->GetThinLockId();
2898
2899 // Fill in the stack trace.
2900 AllocRecordStackVisitor visitor(record);
2901 self->WalkStack(&visitor);
2902
2903 if (gAllocRecordCount < kNumAllocRecords) {
2904 ++gAllocRecordCount;
2905 }
2906}
2907
2908/*
2909 * Return the index of the head element.
2910 *
2911 * We point at the most-recently-written record, so if allocRecordCount is 1
2912 * we want to use the current element. Take "head+1" and subtract count
2913 * from it.
2914 *
2915 * We need to handle underflow in our circular buffer, so we add
2916 * kNumAllocRecords and then mask it back down.
2917 */
2918inline static int headIndex() {
2919 return (gAllocRecordHead+1 + kNumAllocRecords - gAllocRecordCount) & (kNumAllocRecords-1);
2920}
2921
2922void Dbg::DumpRecentAllocations() {
2923 MutexLock mu(gAllocTrackerLock);
2924 if (recent_allocation_records_ == NULL) {
2925 LOG(INFO) << "Not recording tracked allocations";
2926 return;
2927 }
2928
2929 // "i" is the head of the list. We want to start at the end of the
2930 // list and move forward to the tail.
2931 size_t i = headIndex();
2932 size_t count = gAllocRecordCount;
2933
2934 LOG(INFO) << "Tracked allocations, (head=" << gAllocRecordHead << " count=" << count << ")";
2935 while (count--) {
2936 AllocRecord* record = &recent_allocation_records_[i];
2937
Elliott Hughesaa6e1cd2012-01-18 19:26:06 -08002938 LOG(INFO) << StringPrintf(" T=%-2d %6zd ", record->thin_lock_id, record->byte_count)
Elliott Hughes545a0642011-11-08 19:10:03 -08002939 << PrettyClass(record->type);
2940
2941 for (size_t stack_frame = 0; stack_frame < kMaxAllocRecordStackDepth; ++stack_frame) {
2942 const Method* m = record->stack[stack_frame].method;
2943 if (m == NULL) {
2944 break;
2945 }
2946 LOG(INFO) << " " << PrettyMethod(m) << " line " << record->stack[stack_frame].LineNumber();
2947 }
2948
2949 // pause periodically to help logcat catch up
2950 if ((count % 5) == 0) {
2951 usleep(40000);
2952 }
2953
2954 i = (i + 1) & (kNumAllocRecords-1);
2955 }
2956}
2957
2958class StringTable {
2959 public:
2960 StringTable() {
2961 }
2962
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002963 void Add(const char* s) {
Elliott Hughes545a0642011-11-08 19:10:03 -08002964 table_.insert(s);
2965 }
2966
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002967 size_t IndexOf(const char* s) {
Elliott Hughes545a0642011-11-08 19:10:03 -08002968 return std::distance(table_.begin(), table_.find(s));
2969 }
2970
2971 size_t Size() {
2972 return table_.size();
2973 }
2974
2975 void WriteTo(std::vector<uint8_t>& bytes) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002976 typedef std::set<const char*>::const_iterator It; // TODO: C++0x auto
Elliott Hughes545a0642011-11-08 19:10:03 -08002977 for (It it = table_.begin(); it != table_.end(); ++it) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002978 const char* s = *it;
2979 size_t s_len = CountModifiedUtf8Chars(s);
2980 UniquePtr<uint16_t> s_utf16(new uint16_t[s_len]);
2981 ConvertModifiedUtf8ToUtf16(s_utf16.get(), s);
2982 JDWP::AppendUtf16BE(bytes, s_utf16.get(), s_len);
Elliott Hughes545a0642011-11-08 19:10:03 -08002983 }
2984 }
2985
2986 private:
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002987 std::set<const char*> table_;
Elliott Hughes545a0642011-11-08 19:10:03 -08002988 DISALLOW_COPY_AND_ASSIGN(StringTable);
2989};
2990
2991/*
2992 * The data we send to DDMS contains everything we have recorded.
2993 *
2994 * Message header (all values big-endian):
2995 * (1b) message header len (to allow future expansion); includes itself
2996 * (1b) entry header len
2997 * (1b) stack frame len
2998 * (2b) number of entries
2999 * (4b) offset to string table from start of message
3000 * (2b) number of class name strings
3001 * (2b) number of method name strings
3002 * (2b) number of source file name strings
3003 * For each entry:
3004 * (4b) total allocation size
3005 * (2b) threadId
3006 * (2b) allocated object's class name index
3007 * (1b) stack depth
3008 * For each stack frame:
3009 * (2b) method's class name
3010 * (2b) method name
3011 * (2b) method source file
3012 * (2b) line number, clipped to 32767; -2 if native; -1 if no source
3013 * (xb) class name strings
3014 * (xb) method name strings
3015 * (xb) source file strings
3016 *
3017 * As with other DDM traffic, strings are sent as a 4-byte length
3018 * followed by UTF-16 data.
3019 *
3020 * We send up 16-bit unsigned indexes into string tables. In theory there
3021 * can be (kMaxAllocRecordStackDepth * kNumAllocRecords) unique strings in
3022 * each table, but in practice there should be far fewer.
3023 *
3024 * The chief reason for using a string table here is to keep the size of
3025 * the DDMS message to a minimum. This is partly to make the protocol
3026 * efficient, but also because we have to form the whole thing up all at
3027 * once in a memory buffer.
3028 *
3029 * We use separate string tables for class names, method names, and source
3030 * files to keep the indexes small. There will generally be no overlap
3031 * between the contents of these tables.
3032 */
3033jbyteArray Dbg::GetRecentAllocations() {
3034 if (false) {
3035 DumpRecentAllocations();
3036 }
3037
3038 MutexLock mu(gAllocTrackerLock);
3039
3040 /*
3041 * Part 1: generate string tables.
3042 */
3043 StringTable class_names;
3044 StringTable method_names;
3045 StringTable filenames;
3046
3047 int count = gAllocRecordCount;
3048 int idx = headIndex();
3049 while (count--) {
3050 AllocRecord* record = &recent_allocation_records_[idx];
3051
Elliott Hughes91250e02011-12-13 22:30:35 -08003052 class_names.Add(ClassHelper(record->type).GetDescriptor());
Elliott Hughes545a0642011-11-08 19:10:03 -08003053
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08003054 MethodHelper mh;
Elliott Hughes545a0642011-11-08 19:10:03 -08003055 for (size_t i = 0; i < kMaxAllocRecordStackDepth; i++) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08003056 Method* m = record->stack[i].method;
3057 mh.ChangeMethod(m);
Elliott Hughes545a0642011-11-08 19:10:03 -08003058 if (m != NULL) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08003059 class_names.Add(mh.GetDeclaringClassDescriptor());
3060 method_names.Add(mh.GetName());
3061 filenames.Add(mh.GetDeclaringClassSourceFile());
Elliott Hughes545a0642011-11-08 19:10:03 -08003062 }
3063 }
3064
3065 idx = (idx + 1) & (kNumAllocRecords-1);
3066 }
3067
3068 LOG(INFO) << "allocation records: " << gAllocRecordCount;
3069
3070 /*
3071 * Part 2: allocate a buffer and generate the output.
3072 */
3073 std::vector<uint8_t> bytes;
3074
3075 // (1b) message header len (to allow future expansion); includes itself
3076 // (1b) entry header len
3077 // (1b) stack frame len
3078 const int kMessageHeaderLen = 15;
3079 const int kEntryHeaderLen = 9;
3080 const int kStackFrameLen = 8;
3081 JDWP::Append1BE(bytes, kMessageHeaderLen);
3082 JDWP::Append1BE(bytes, kEntryHeaderLen);
3083 JDWP::Append1BE(bytes, kStackFrameLen);
3084
3085 // (2b) number of entries
3086 // (4b) offset to string table from start of message
3087 // (2b) number of class name strings
3088 // (2b) number of method name strings
3089 // (2b) number of source file name strings
3090 JDWP::Append2BE(bytes, gAllocRecordCount);
3091 size_t string_table_offset = bytes.size();
3092 JDWP::Append4BE(bytes, 0); // We'll patch this later...
3093 JDWP::Append2BE(bytes, class_names.Size());
3094 JDWP::Append2BE(bytes, method_names.Size());
3095 JDWP::Append2BE(bytes, filenames.Size());
3096
3097 count = gAllocRecordCount;
3098 idx = headIndex();
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08003099 ClassHelper kh;
Elliott Hughes545a0642011-11-08 19:10:03 -08003100 while (count--) {
3101 // For each entry:
3102 // (4b) total allocation size
3103 // (2b) thread id
3104 // (2b) allocated object's class name index
3105 // (1b) stack depth
3106 AllocRecord* record = &recent_allocation_records_[idx];
3107 size_t stack_depth = record->GetDepth();
3108 JDWP::Append4BE(bytes, record->byte_count);
3109 JDWP::Append2BE(bytes, record->thin_lock_id);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08003110 kh.ChangeClass(record->type);
Elliott Hughes91250e02011-12-13 22:30:35 -08003111 JDWP::Append2BE(bytes, class_names.IndexOf(kh.GetDescriptor()));
Elliott Hughes545a0642011-11-08 19:10:03 -08003112 JDWP::Append1BE(bytes, stack_depth);
3113
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08003114 MethodHelper mh;
Elliott Hughes545a0642011-11-08 19:10:03 -08003115 for (size_t stack_frame = 0; stack_frame < stack_depth; ++stack_frame) {
3116 // For each stack frame:
3117 // (2b) method's class name
3118 // (2b) method name
3119 // (2b) method source file
3120 // (2b) line number, clipped to 32767; -2 if native; -1 if no source
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08003121 mh.ChangeMethod(record->stack[stack_frame].method);
3122 JDWP::Append2BE(bytes, class_names.IndexOf(mh.GetDeclaringClassDescriptor()));
3123 JDWP::Append2BE(bytes, method_names.IndexOf(mh.GetName()));
3124 JDWP::Append2BE(bytes, filenames.IndexOf(mh.GetDeclaringClassSourceFile()));
Elliott Hughes545a0642011-11-08 19:10:03 -08003125 JDWP::Append2BE(bytes, record->stack[stack_frame].LineNumber());
3126 }
3127
3128 idx = (idx + 1) & (kNumAllocRecords-1);
3129 }
3130
3131 // (xb) class name strings
3132 // (xb) method name strings
3133 // (xb) source file strings
3134 JDWP::Set4BE(&bytes[string_table_offset], bytes.size());
3135 class_names.WriteTo(bytes);
3136 method_names.WriteTo(bytes);
3137 filenames.WriteTo(bytes);
3138
3139 JNIEnv* env = Thread::Current()->GetJniEnv();
3140 jbyteArray result = env->NewByteArray(bytes.size());
3141 if (result != NULL) {
3142 env->SetByteArrayRegion(result, 0, bytes.size(), reinterpret_cast<const jbyte*>(&bytes[0]));
3143 }
3144 return result;
3145}
3146
Elliott Hughes872d4ec2011-10-21 17:07:15 -07003147} // namespace art