blob: fe9bc491c17091e56d5b7515ee4eb60b06744d60 [file] [log] [blame]
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001/*
2 * Copyright (C) 2008 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17#include "debugger.h"
18
Elliott Hughes3bb81562011-10-21 18:52:59 -070019#include <sys/uio.h>
20
Elliott Hughes545a0642011-11-08 19:10:03 -080021#include <set>
22
23#include "class_linker.h"
Elliott Hughes1bba14f2011-12-01 18:00:36 -080024#include "class_loader.h"
Elliott Hughes86964332012-02-15 19:37:42 -080025#include "dex_verifier.h" // For Instruction.
Ian Rogers57b86d42012-03-27 16:05:41 -070026#include "oat/runtime/context.h"
Ian Rogers6d4d9fc2011-11-30 16:24:48 -080027#include "object_utils.h"
Elliott Hughesa0e18062012-04-13 15:59:59 -070028#include "safe_map.h"
29#include "scoped_thread_list_lock.h"
Elliott Hughes6a5bd492011-10-28 14:33:57 -070030#include "ScopedLocalRef.h"
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -070031#include "ScopedPrimitiveArray.h"
Ian Rogers30fab402012-01-23 15:43:46 -080032#include "space.h"
Elliott Hughes47fce012011-10-25 18:37:19 -070033#include "stack_indirect_reference_table.h"
Elliott Hughes475fc232011-10-25 15:00:35 -070034#include "thread_list.h"
35
Elliott Hughes6a5bd492011-10-28 14:33:57 -070036extern "C" void dlmalloc_walk_heap(void(*)(const void*, size_t, const void*, size_t, void*), void*);
37#ifndef HAVE_ANDROID_OS
38void dlmalloc_walk_heap(void(*)(const void*, size_t, const void*, size_t, void*), void*) {
39 // No-op for glibc.
40}
41#endif
42
Elliott Hughes872d4ec2011-10-21 17:07:15 -070043namespace art {
44
Elliott Hughes545a0642011-11-08 19:10:03 -080045static const size_t kMaxAllocRecordStackDepth = 16; // Max 255.
46static const size_t kNumAllocRecords = 512; // Must be power of 2.
47
Elliott Hughes436e3722012-02-17 20:01:47 -080048static const uintptr_t kInvalidId = 1;
49static const Object* kInvalidObject = reinterpret_cast<Object*>(kInvalidId);
50
Elliott Hughes475fc232011-10-25 15:00:35 -070051class ObjectRegistry {
52 public:
53 ObjectRegistry() : lock_("ObjectRegistry lock") {
54 }
55
56 JDWP::ObjectId Add(Object* o) {
57 if (o == NULL) {
58 return 0;
59 }
60 JDWP::ObjectId id = static_cast<JDWP::ObjectId>(reinterpret_cast<uintptr_t>(o));
61 MutexLock mu(lock_);
Elliott Hughesa0e18062012-04-13 15:59:59 -070062 map_.Overwrite(id, o);
Elliott Hughes475fc232011-10-25 15:00:35 -070063 return id;
64 }
65
Elliott Hughes234ab152011-10-26 14:02:26 -070066 void Clear() {
67 MutexLock mu(lock_);
68 LOG(DEBUG) << "Debugger has detached; object registry had " << map_.size() << " entries";
69 map_.clear();
70 }
71
Elliott Hughes475fc232011-10-25 15:00:35 -070072 bool Contains(JDWP::ObjectId id) {
73 MutexLock mu(lock_);
74 return map_.find(id) != map_.end();
75 }
76
Elliott Hughesa2155262011-11-16 16:26:58 -080077 template<typename T> T Get(JDWP::ObjectId id) {
Elliott Hughes436e3722012-02-17 20:01:47 -080078 if (id == 0) {
79 return NULL;
80 }
81
Elliott Hughesa2155262011-11-16 16:26:58 -080082 MutexLock mu(lock_);
Elliott Hughesa0e18062012-04-13 15:59:59 -070083 typedef SafeMap<JDWP::ObjectId, Object*>::iterator It; // C++0x auto
Elliott Hughesa2155262011-11-16 16:26:58 -080084 It it = map_.find(id);
Elliott Hughes436e3722012-02-17 20:01:47 -080085 return (it != map_.end()) ? reinterpret_cast<T>(it->second) : reinterpret_cast<T>(kInvalidId);
Elliott Hughesa2155262011-11-16 16:26:58 -080086 }
87
Elliott Hughesbfe487b2011-10-26 15:48:55 -070088 void VisitRoots(Heap::RootVisitor* visitor, void* arg) {
89 MutexLock mu(lock_);
Elliott Hughesa0e18062012-04-13 15:59:59 -070090 typedef SafeMap<JDWP::ObjectId, Object*>::iterator It; // C++0x auto
Elliott Hughesbfe487b2011-10-26 15:48:55 -070091 for (It it = map_.begin(); it != map_.end(); ++it) {
92 visitor(it->second, arg);
93 }
94 }
95
Elliott Hughes475fc232011-10-25 15:00:35 -070096 private:
97 Mutex lock_;
Elliott Hughesa0e18062012-04-13 15:59:59 -070098 SafeMap<JDWP::ObjectId, Object*> map_;
Elliott Hughes475fc232011-10-25 15:00:35 -070099};
100
Elliott Hughes545a0642011-11-08 19:10:03 -0800101struct AllocRecordStackTraceElement {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800102 Method* method;
Elliott Hughes545a0642011-11-08 19:10:03 -0800103 uintptr_t raw_pc;
104
105 int32_t LineNumber() const {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800106 return MethodHelper(method).GetLineNumFromNativePC(raw_pc);
Elliott Hughes545a0642011-11-08 19:10:03 -0800107 }
108};
109
110struct AllocRecord {
111 Class* type;
112 size_t byte_count;
113 uint16_t thin_lock_id;
114 AllocRecordStackTraceElement stack[kMaxAllocRecordStackDepth]; // Unused entries have NULL method.
115
116 size_t GetDepth() {
117 size_t depth = 0;
118 while (depth < kMaxAllocRecordStackDepth && stack[depth].method != NULL) {
119 ++depth;
120 }
121 return depth;
122 }
123};
124
Elliott Hughes86964332012-02-15 19:37:42 -0800125struct Breakpoint {
126 Method* method;
Elliott Hughesa656a0f2012-02-21 18:03:44 -0800127 uint32_t dex_pc;
128 Breakpoint(Method* method, uint32_t dex_pc) : method(method), dex_pc(dex_pc) {}
Elliott Hughes86964332012-02-15 19:37:42 -0800129};
130
131static std::ostream& operator<<(std::ostream& os, const Breakpoint& rhs) {
Elliott Hughes229feb72012-02-23 13:33:29 -0800132 os << StringPrintf("Breakpoint[%s @%#x]", PrettyMethod(rhs.method).c_str(), rhs.dex_pc);
Elliott Hughes86964332012-02-15 19:37:42 -0800133 return os;
134}
135
136struct SingleStepControl {
137 // Are we single-stepping right now?
138 bool is_active;
139 Thread* thread;
140
141 JDWP::JdwpStepSize step_size;
142 JDWP::JdwpStepDepth step_depth;
143
144 const Method* method;
Elliott Hughes2435a572012-02-17 16:07:41 -0800145 int32_t line_number; // Or -1 for native methods.
146 std::set<uint32_t> dex_pcs;
Elliott Hughes86964332012-02-15 19:37:42 -0800147 int stack_depth;
148};
149
Elliott Hughes4ffd3132011-10-24 12:06:42 -0700150// JDWP is allowed unless the Zygote forbids it.
151static bool gJdwpAllowed = true;
152
Elliott Hughesc0f09332012-03-26 13:27:06 -0700153// Was there a -Xrunjdwp or -agentlib:jdwp= argument on the command line?
Elliott Hughes3bb81562011-10-21 18:52:59 -0700154static bool gJdwpConfigured = false;
155
Elliott Hughesc0f09332012-03-26 13:27:06 -0700156// Broken-down JDWP options. (Only valid if IsJdwpConfigured() is true.)
Elliott Hughes376a7a02011-10-24 18:35:55 -0700157static JDWP::JdwpOptions gJdwpOptions;
Elliott Hughes3bb81562011-10-21 18:52:59 -0700158
159// Runtime JDWP state.
160static JDWP::JdwpState* gJdwpState = NULL;
161static bool gDebuggerConnected; // debugger or DDMS is connected.
162static bool gDebuggerActive; // debugger is making requests.
Elliott Hughes86964332012-02-15 19:37:42 -0800163static bool gDisposed; // debugger called VirtualMachine.Dispose, so we should drop the connection.
Elliott Hughes3bb81562011-10-21 18:52:59 -0700164
Elliott Hughes47fce012011-10-25 18:37:19 -0700165static bool gDdmThreadNotification = false;
166
Elliott Hughes767a1472011-10-26 18:49:02 -0700167// DDMS GC-related settings.
168static Dbg::HpifWhen gDdmHpifWhen = Dbg::HPIF_WHEN_NEVER;
169static Dbg::HpsgWhen gDdmHpsgWhen = Dbg::HPSG_WHEN_NEVER;
170static Dbg::HpsgWhat gDdmHpsgWhat;
171static Dbg::HpsgWhen gDdmNhsgWhen = Dbg::HPSG_WHEN_NEVER;
172static Dbg::HpsgWhat gDdmNhsgWhat;
173
Elliott Hughes475fc232011-10-25 15:00:35 -0700174static ObjectRegistry* gRegistry = NULL;
175
Elliott Hughes545a0642011-11-08 19:10:03 -0800176// Recent allocation tracking.
177static Mutex gAllocTrackerLock("AllocTracker lock");
178AllocRecord* Dbg::recent_allocation_records_ = NULL; // TODO: CircularBuffer<AllocRecord>
179static size_t gAllocRecordHead = 0;
180static size_t gAllocRecordCount = 0;
181
Elliott Hughes86964332012-02-15 19:37:42 -0800182// Breakpoints and single-stepping.
183static Mutex gBreakpointsLock("breakpoints lock");
184static std::vector<Breakpoint> gBreakpoints;
185static SingleStepControl gSingleStepControl;
186
187static bool IsBreakpoint(Method* m, uint32_t dex_pc) {
188 MutexLock mu(gBreakpointsLock);
189 for (size_t i = 0; i < gBreakpoints.size(); ++i) {
Elliott Hughesa656a0f2012-02-21 18:03:44 -0800190 if (gBreakpoints[i].method == m && gBreakpoints[i].dex_pc == dex_pc) {
Elliott Hughes86964332012-02-15 19:37:42 -0800191 VLOG(jdwp) << "Hit breakpoint #" << i << ": " << gBreakpoints[i];
192 return true;
193 }
194 }
195 return false;
196}
197
Elliott Hughes436e3722012-02-17 20:01:47 -0800198static Array* DecodeArray(JDWP::RefTypeId id, JDWP::JdwpError& status) {
199 Object* o = gRegistry->Get<Object*>(id);
200 if (o == NULL || o == kInvalidObject) {
201 status = JDWP::ERR_INVALID_OBJECT;
202 return NULL;
203 }
204 if (!o->IsArrayInstance()) {
205 status = JDWP::ERR_INVALID_ARRAY;
206 return NULL;
207 }
208 status = JDWP::ERR_NONE;
209 return o->AsArray();
210}
211
212static Class* DecodeClass(JDWP::RefTypeId id, JDWP::JdwpError& status) {
213 Object* o = gRegistry->Get<Object*>(id);
214 if (o == NULL || o == kInvalidObject) {
215 status = JDWP::ERR_INVALID_OBJECT;
216 return NULL;
217 }
218 if (!o->IsClass()) {
219 status = JDWP::ERR_INVALID_CLASS;
220 return NULL;
221 }
222 status = JDWP::ERR_NONE;
223 return o->AsClass();
224}
225
226static Thread* DecodeThread(JDWP::ObjectId threadId) {
227 Object* thread_peer = gRegistry->Get<Object*>(threadId);
228 if (thread_peer == NULL || thread_peer == kInvalidObject) {
229 return NULL;
230 }
231 return Thread::FromManagedThread(thread_peer);
232}
233
Elliott Hughes24437992011-11-30 14:49:33 -0800234static JDWP::JdwpTag BasicTagFromDescriptor(const char* descriptor) {
235 // JDWP deliberately uses the descriptor characters' ASCII values for its enum.
236 // Note that by "basic" we mean that we don't get more specific than JT_OBJECT.
237 return static_cast<JDWP::JdwpTag>(descriptor[0]);
238}
239
240static JDWP::JdwpTag TagFromClass(Class* c) {
Elliott Hughes86b00102011-12-05 17:54:26 -0800241 CHECK(c != NULL);
Elliott Hughes24437992011-11-30 14:49:33 -0800242 if (c->IsArrayClass()) {
243 return JDWP::JT_ARRAY;
244 }
245
Elliott Hughes3d30d9b2011-12-07 17:35:48 -0800246 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
Elliott Hughes24437992011-11-30 14:49:33 -0800247 if (c->IsStringClass()) {
248 return JDWP::JT_STRING;
249 } else if (c->IsClassClass()) {
250 return JDWP::JT_CLASS_OBJECT;
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -0800251 } else if (class_linker->FindSystemClass("Ljava/lang/Thread;")->IsAssignableFrom(c)) {
Elliott Hughes24437992011-11-30 14:49:33 -0800252 return JDWP::JT_THREAD;
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -0800253 } else if (class_linker->FindSystemClass("Ljava/lang/ThreadGroup;")->IsAssignableFrom(c)) {
Elliott Hughes24437992011-11-30 14:49:33 -0800254 return JDWP::JT_THREAD_GROUP;
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -0800255 } else if (class_linker->FindSystemClass("Ljava/lang/ClassLoader;")->IsAssignableFrom(c)) {
Elliott Hughes24437992011-11-30 14:49:33 -0800256 return JDWP::JT_CLASS_LOADER;
Elliott Hughes24437992011-11-30 14:49:33 -0800257 } else {
258 return JDWP::JT_OBJECT;
259 }
260}
261
262/*
263 * Objects declared to hold Object might actually hold a more specific
264 * type. The debugger may take a special interest in these (e.g. it
265 * wants to display the contents of Strings), so we want to return an
266 * appropriate tag.
267 *
268 * Null objects are tagged JT_OBJECT.
269 */
270static JDWP::JdwpTag TagFromObject(const Object* o) {
271 return (o == NULL) ? JDWP::JT_OBJECT : TagFromClass(o->GetClass());
272}
273
274static bool IsPrimitiveTag(JDWP::JdwpTag tag) {
275 switch (tag) {
276 case JDWP::JT_BOOLEAN:
277 case JDWP::JT_BYTE:
278 case JDWP::JT_CHAR:
279 case JDWP::JT_FLOAT:
280 case JDWP::JT_DOUBLE:
281 case JDWP::JT_INT:
282 case JDWP::JT_LONG:
283 case JDWP::JT_SHORT:
284 case JDWP::JT_VOID:
285 return true;
286 default:
287 return false;
288 }
289}
290
Elliott Hughes3bb81562011-10-21 18:52:59 -0700291/*
292 * Handle one of the JDWP name/value pairs.
293 *
294 * JDWP options are:
295 * help: if specified, show help message and bail
296 * transport: may be dt_socket or dt_shmem
297 * address: for dt_socket, "host:port", or just "port" when listening
298 * server: if "y", wait for debugger to attach; if "n", attach to debugger
299 * timeout: how long to wait for debugger to connect / listen
300 *
301 * Useful with server=n (these aren't supported yet):
302 * onthrow=<exception-name>: connect to debugger when exception thrown
303 * onuncaught=y|n: connect to debugger when uncaught exception thrown
304 * launch=<command-line>: launch the debugger itself
305 *
306 * The "transport" option is required, as is "address" if server=n.
307 */
308static bool ParseJdwpOption(const std::string& name, const std::string& value) {
309 if (name == "transport") {
310 if (value == "dt_socket") {
Elliott Hughes376a7a02011-10-24 18:35:55 -0700311 gJdwpOptions.transport = JDWP::kJdwpTransportSocket;
Elliott Hughes3bb81562011-10-21 18:52:59 -0700312 } else if (value == "dt_android_adb") {
Elliott Hughes376a7a02011-10-24 18:35:55 -0700313 gJdwpOptions.transport = JDWP::kJdwpTransportAndroidAdb;
Elliott Hughes3bb81562011-10-21 18:52:59 -0700314 } else {
315 LOG(ERROR) << "JDWP transport not supported: " << value;
316 return false;
317 }
318 } else if (name == "server") {
319 if (value == "n") {
Elliott Hughes376a7a02011-10-24 18:35:55 -0700320 gJdwpOptions.server = false;
Elliott Hughes3bb81562011-10-21 18:52:59 -0700321 } else if (value == "y") {
Elliott Hughes376a7a02011-10-24 18:35:55 -0700322 gJdwpOptions.server = true;
Elliott Hughes3bb81562011-10-21 18:52:59 -0700323 } else {
324 LOG(ERROR) << "JDWP option 'server' must be 'y' or 'n'";
325 return false;
326 }
327 } else if (name == "suspend") {
328 if (value == "n") {
Elliott Hughes376a7a02011-10-24 18:35:55 -0700329 gJdwpOptions.suspend = false;
Elliott Hughes3bb81562011-10-21 18:52:59 -0700330 } else if (value == "y") {
Elliott Hughes376a7a02011-10-24 18:35:55 -0700331 gJdwpOptions.suspend = true;
Elliott Hughes3bb81562011-10-21 18:52:59 -0700332 } else {
333 LOG(ERROR) << "JDWP option 'suspend' must be 'y' or 'n'";
334 return false;
335 }
336 } else if (name == "address") {
337 /* this is either <port> or <host>:<port> */
338 std::string port_string;
Elliott Hughes376a7a02011-10-24 18:35:55 -0700339 gJdwpOptions.host.clear();
Elliott Hughes3bb81562011-10-21 18:52:59 -0700340 std::string::size_type colon = value.find(':');
341 if (colon != std::string::npos) {
Elliott Hughes376a7a02011-10-24 18:35:55 -0700342 gJdwpOptions.host = value.substr(0, colon);
Elliott Hughes3bb81562011-10-21 18:52:59 -0700343 port_string = value.substr(colon + 1);
344 } else {
345 port_string = value;
346 }
347 if (port_string.empty()) {
348 LOG(ERROR) << "JDWP address missing port: " << value;
349 return false;
350 }
351 char* end;
Elliott Hughesba8eee12012-01-24 20:25:24 -0800352 uint64_t port = strtoul(port_string.c_str(), &end, 10);
353 if (*end != '\0' || port > 0xffff) {
Elliott Hughes3bb81562011-10-21 18:52:59 -0700354 LOG(ERROR) << "JDWP address has junk in port field: " << value;
355 return false;
356 }
Elliott Hughes376a7a02011-10-24 18:35:55 -0700357 gJdwpOptions.port = port;
Elliott Hughes3bb81562011-10-21 18:52:59 -0700358 } else if (name == "launch" || name == "onthrow" || name == "oncaught" || name == "timeout") {
359 /* valid but unsupported */
360 LOG(INFO) << "Ignoring JDWP option '" << name << "'='" << value << "'";
361 } else {
362 LOG(INFO) << "Ignoring unrecognized JDWP option '" << name << "'='" << value << "'";
363 }
364
365 return true;
366}
367
368/*
369 * Parse the latter half of a -Xrunjdwp/-agentlib:jdwp= string, e.g.:
370 * "transport=dt_socket,address=8000,server=y,suspend=n"
371 */
372bool Dbg::ParseJdwpOptions(const std::string& options) {
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -0800373 VLOG(jdwp) << "ParseJdwpOptions: " << options;
Elliott Hughes47fce012011-10-25 18:37:19 -0700374
Elliott Hughes3bb81562011-10-21 18:52:59 -0700375 std::vector<std::string> pairs;
376 Split(options, ',', pairs);
377
378 for (size_t i = 0; i < pairs.size(); ++i) {
379 std::string::size_type equals = pairs[i].find('=');
380 if (equals == std::string::npos) {
381 LOG(ERROR) << "Can't parse JDWP option '" << pairs[i] << "' in '" << options << "'";
382 return false;
383 }
384 ParseJdwpOption(pairs[i].substr(0, equals), pairs[i].substr(equals + 1));
385 }
386
Elliott Hughes376a7a02011-10-24 18:35:55 -0700387 if (gJdwpOptions.transport == JDWP::kJdwpTransportUnknown) {
Elliott Hughes3bb81562011-10-21 18:52:59 -0700388 LOG(ERROR) << "Must specify JDWP transport: " << options;
389 }
Elliott Hughes376a7a02011-10-24 18:35:55 -0700390 if (!gJdwpOptions.server && (gJdwpOptions.host.empty() || gJdwpOptions.port == 0)) {
Elliott Hughes3bb81562011-10-21 18:52:59 -0700391 LOG(ERROR) << "Must specify JDWP host and port when server=n: " << options;
392 return false;
393 }
394
395 gJdwpConfigured = true;
396 return true;
397}
398
Elliott Hughesd1cc8362011-10-24 16:58:50 -0700399void Dbg::StartJdwp() {
Elliott Hughesc0f09332012-03-26 13:27:06 -0700400 if (!gJdwpAllowed || !IsJdwpConfigured()) {
Elliott Hughes376a7a02011-10-24 18:35:55 -0700401 // No JDWP for you!
402 return;
403 }
404
Elliott Hughes475fc232011-10-25 15:00:35 -0700405 CHECK(gRegistry == NULL);
406 gRegistry = new ObjectRegistry;
407
Elliott Hughesd1cc8362011-10-24 16:58:50 -0700408 // Init JDWP if the debugger is enabled. This may connect out to a
409 // debugger, passively listen for a debugger, or block waiting for a
410 // debugger.
Elliott Hughes376a7a02011-10-24 18:35:55 -0700411 gJdwpState = JDWP::JdwpState::Create(&gJdwpOptions);
412 if (gJdwpState == NULL) {
Elliott Hughesf8a2df72011-12-01 12:19:54 -0800413 // We probably failed because some other process has the port already, which means that
414 // if we don't abort the user is likely to think they're talking to us when they're actually
415 // talking to that other process.
Elliott Hughes3d30d9b2011-12-07 17:35:48 -0800416 LOG(FATAL) << "Debugger thread failed to initialize";
Elliott Hughesd1cc8362011-10-24 16:58:50 -0700417 }
418
419 // If a debugger has already attached, send the "welcome" message.
420 // This may cause us to suspend all threads.
Elliott Hughes376a7a02011-10-24 18:35:55 -0700421 if (gJdwpState->IsActive()) {
Elliott Hughes34e06962012-04-09 13:55:55 -0700422 //ScopedThreadStateChange tsc(Thread::Current(), kRunnable);
Elliott Hughes376a7a02011-10-24 18:35:55 -0700423 if (!gJdwpState->PostVMStart()) {
Elliott Hughes3d30d9b2011-12-07 17:35:48 -0800424 LOG(WARNING) << "Failed to post 'start' message to debugger";
Elliott Hughesd1cc8362011-10-24 16:58:50 -0700425 }
426 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700427}
428
Elliott Hughesd1cc8362011-10-24 16:58:50 -0700429void Dbg::StopJdwp() {
Elliott Hughes376a7a02011-10-24 18:35:55 -0700430 delete gJdwpState;
Elliott Hughes475fc232011-10-25 15:00:35 -0700431 delete gRegistry;
432 gRegistry = NULL;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700433}
434
Elliott Hughes767a1472011-10-26 18:49:02 -0700435void Dbg::GcDidFinish() {
436 if (gDdmHpifWhen != HPIF_WHEN_NEVER) {
Elliott Hughes81ff3182012-03-23 20:35:56 -0700437 LOG(DEBUG) << "Sending heap info to DDM";
Elliott Hughes7162ad92011-10-27 14:08:42 -0700438 DdmSendHeapInfo(gDdmHpifWhen);
Elliott Hughes767a1472011-10-26 18:49:02 -0700439 }
440 if (gDdmHpsgWhen != HPSG_WHEN_NEVER) {
Elliott Hughes81ff3182012-03-23 20:35:56 -0700441 LOG(DEBUG) << "Dumping heap to DDM";
Elliott Hughes6a5bd492011-10-28 14:33:57 -0700442 DdmSendHeapSegments(false);
Elliott Hughes767a1472011-10-26 18:49:02 -0700443 }
444 if (gDdmNhsgWhen != HPSG_WHEN_NEVER) {
445 LOG(DEBUG) << "Dumping native heap to DDM";
Elliott Hughes6a5bd492011-10-28 14:33:57 -0700446 DdmSendHeapSegments(true);
Elliott Hughes767a1472011-10-26 18:49:02 -0700447 }
448}
449
Elliott Hughes4ffd3132011-10-24 12:06:42 -0700450void Dbg::SetJdwpAllowed(bool allowed) {
451 gJdwpAllowed = allowed;
452}
453
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700454DebugInvokeReq* Dbg::GetInvokeReq() {
Elliott Hughes475fc232011-10-25 15:00:35 -0700455 return Thread::Current()->GetInvokeReq();
456}
457
458Thread* Dbg::GetDebugThread() {
459 return (gJdwpState != NULL) ? gJdwpState->GetDebugThread() : NULL;
460}
461
462void Dbg::ClearWaitForEventThread() {
463 gJdwpState->ClearWaitForEventThread();
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700464}
465
466void Dbg::Connected() {
Elliott Hughes3bb81562011-10-21 18:52:59 -0700467 CHECK(!gDebuggerConnected);
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -0800468 VLOG(jdwp) << "JDWP has attached";
Elliott Hughes3bb81562011-10-21 18:52:59 -0700469 gDebuggerConnected = true;
Elliott Hughes86964332012-02-15 19:37:42 -0800470 gDisposed = false;
471}
472
473void Dbg::Disposed() {
474 gDisposed = true;
475}
476
477bool Dbg::IsDisposed() {
478 return gDisposed;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700479}
480
Elliott Hughesc0f09332012-03-26 13:27:06 -0700481static void SetDebuggerUpdatesEnabledCallback(Thread* t, void* user_data) {
482 t->SetDebuggerUpdatesEnabled(*reinterpret_cast<bool*>(user_data));
483}
484
485static void SetDebuggerUpdatesEnabled(bool enabled) {
486 Runtime* runtime = Runtime::Current();
487 ScopedThreadListLock thread_list_lock;
488 runtime->GetThreadList()->ForEach(SetDebuggerUpdatesEnabledCallback, &enabled);
489}
490
Elliott Hughesa2155262011-11-16 16:26:58 -0800491void Dbg::GoActive() {
492 // Enable all debugging features, including scans for breakpoints.
493 // This is a no-op if we're already active.
494 // Only called from the JDWP handler thread.
495 if (gDebuggerActive) {
496 return;
497 }
498
499 LOG(INFO) << "Debugger is active";
500
Elliott Hughesc0f09332012-03-26 13:27:06 -0700501 {
502 // TODO: dalvik only warned if there were breakpoints left over. clear in Dbg::Disconnected?
503 MutexLock mu(gBreakpointsLock);
504 CHECK_EQ(gBreakpoints.size(), 0U);
505 }
Elliott Hughesa2155262011-11-16 16:26:58 -0800506
507 gDebuggerActive = true;
Elliott Hughesc0f09332012-03-26 13:27:06 -0700508 SetDebuggerUpdatesEnabled(true);
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700509}
510
511void Dbg::Disconnected() {
Elliott Hughes234ab152011-10-26 14:02:26 -0700512 CHECK(gDebuggerConnected);
513
Elliott Hughesc0f09332012-03-26 13:27:06 -0700514 LOG(INFO) << "Debugger is no longer active";
Elliott Hughes234ab152011-10-26 14:02:26 -0700515
Elliott Hughesc0f09332012-03-26 13:27:06 -0700516 gDebuggerActive = false;
517 SetDebuggerUpdatesEnabled(false);
Elliott Hughes234ab152011-10-26 14:02:26 -0700518
519 gRegistry->Clear();
520 gDebuggerConnected = false;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700521}
522
Elliott Hughesc0f09332012-03-26 13:27:06 -0700523bool Dbg::IsDebuggerActive() {
Elliott Hughes3bb81562011-10-21 18:52:59 -0700524 return gDebuggerActive;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700525}
526
Elliott Hughesc0f09332012-03-26 13:27:06 -0700527bool Dbg::IsJdwpConfigured() {
Elliott Hughes3bb81562011-10-21 18:52:59 -0700528 return gJdwpConfigured;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700529}
530
531int64_t Dbg::LastDebuggerActivity() {
Elliott Hughesca951522011-12-05 12:01:32 -0800532 return gJdwpState->LastDebuggerActivity();
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700533}
534
535int Dbg::ThreadRunning() {
Elliott Hughes34e06962012-04-09 13:55:55 -0700536 return static_cast<int>(Thread::Current()->SetState(kRunnable));
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700537}
538
539int Dbg::ThreadWaiting() {
Elliott Hughes34e06962012-04-09 13:55:55 -0700540 return static_cast<int>(Thread::Current()->SetState(kVmWait));
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700541}
542
Elliott Hughes6ba581a2011-10-25 11:45:35 -0700543int Dbg::ThreadContinuing(int new_state) {
Elliott Hughes34e06962012-04-09 13:55:55 -0700544 return static_cast<int>(Thread::Current()->SetState(static_cast<ThreadState>(new_state)));
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700545}
546
547void Dbg::UndoDebuggerSuspensions() {
Elliott Hughes234ab152011-10-26 14:02:26 -0700548 Runtime::Current()->GetThreadList()->UndoDebuggerSuspensions();
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700549}
550
551void Dbg::Exit(int status) {
Elliott Hughes1bba14f2011-12-01 18:00:36 -0800552 exit(status); // This is all dalvik did.
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700553}
554
Elliott Hughesbfe487b2011-10-26 15:48:55 -0700555void Dbg::VisitRoots(Heap::RootVisitor* visitor, void* arg) {
556 if (gRegistry != NULL) {
557 gRegistry->VisitRoots(visitor, arg);
558 }
559}
560
Elliott Hughesc308a5d2012-02-16 17:12:06 -0800561std::string Dbg::GetClassName(JDWP::RefTypeId classId) {
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -0800562 Object* o = gRegistry->Get<Object*>(classId);
Elliott Hughes436e3722012-02-17 20:01:47 -0800563 if (o == NULL) {
564 return "NULL";
565 }
566 if (o == kInvalidObject) {
567 return StringPrintf("invalid object %p", reinterpret_cast<void*>(classId));
568 }
569 if (!o->IsClass()) {
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -0800570 return StringPrintf("non-class %p", o); // This is only used for debugging output anyway.
571 }
Elliott Hughesc308a5d2012-02-16 17:12:06 -0800572 return DescriptorToName(ClassHelper(o->AsClass()).GetDescriptor());
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700573}
574
Elliott Hughes436e3722012-02-17 20:01:47 -0800575JDWP::JdwpError Dbg::GetClassObject(JDWP::RefTypeId id, JDWP::ObjectId& classObjectId) {
576 JDWP::JdwpError status;
577 Class* c = DecodeClass(id, status);
578 if (c == NULL) {
579 return status;
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -0800580 }
Elliott Hughes436e3722012-02-17 20:01:47 -0800581 classObjectId = gRegistry->Add(c);
582 return JDWP::ERR_NONE;
Elliott Hughes86964332012-02-15 19:37:42 -0800583}
584
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -0800585JDWP::JdwpError Dbg::GetSuperclass(JDWP::RefTypeId id, JDWP::RefTypeId& superclassId) {
586 JDWP::JdwpError status;
587 Class* c = DecodeClass(id, status);
588 if (c == NULL) {
589 return status;
590 }
591 if (c->IsInterface()) {
592 // http://code.google.com/p/android/issues/detail?id=20856
593 superclassId = NULL;
594 } else {
595 superclassId = gRegistry->Add(c->GetSuperClass());
596 }
597 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700598}
599
Elliott Hughes436e3722012-02-17 20:01:47 -0800600JDWP::JdwpError Dbg::GetClassLoader(JDWP::RefTypeId id, JDWP::ExpandBuf* pReply) {
Elliott Hughes1bba14f2011-12-01 18:00:36 -0800601 Object* o = gRegistry->Get<Object*>(id);
Elliott Hughes436e3722012-02-17 20:01:47 -0800602 if (o == NULL || o == kInvalidObject) {
603 return JDWP::ERR_INVALID_OBJECT;
604 }
605 expandBufAddObjectId(pReply, gRegistry->Add(o->GetClass()->GetClassLoader()));
606 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700607}
608
Elliott Hughes436e3722012-02-17 20:01:47 -0800609JDWP::JdwpError Dbg::GetModifiers(JDWP::RefTypeId id, JDWP::ExpandBuf* pReply) {
610 JDWP::JdwpError status;
611 Class* c = DecodeClass(id, status);
612 if (c == NULL) {
613 return status;
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -0800614 }
Elliott Hughes436e3722012-02-17 20:01:47 -0800615
616 uint32_t access_flags = c->GetAccessFlags() & kAccJavaFlagsMask;
617
618 // Set ACC_SUPER; dex files don't contain this flag, but all classes are supposed to have it set.
619 // Class.getModifiers doesn't return it, but JDWP does, so we set it here.
620 access_flags |= kAccSuper;
621
622 expandBufAdd4BE(pReply, access_flags);
623
624 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700625}
626
Elliott Hughes436e3722012-02-17 20:01:47 -0800627JDWP::JdwpError Dbg::GetReflectedType(JDWP::RefTypeId classId, JDWP::ExpandBuf* pReply) {
628 JDWP::JdwpError status;
629 Class* c = DecodeClass(classId, status);
630 if (c == NULL) {
631 return status;
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -0800632 }
Elliott Hughes436e3722012-02-17 20:01:47 -0800633
634 expandBufAdd1(pReply, c->IsInterface() ? JDWP::TT_INTERFACE : JDWP::TT_CLASS);
635 expandBufAddRefTypeId(pReply, classId);
636 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700637}
638
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -0800639void Dbg::GetClassList(std::vector<JDWP::RefTypeId>& classes) {
Elliott Hughesa2155262011-11-16 16:26:58 -0800640 // Get the complete list of reference classes (i.e. all classes except
641 // the primitive types).
642 // Returns a newly-allocated buffer full of RefTypeId values.
643 struct ClassListCreator {
Elliott Hughesba8eee12012-01-24 20:25:24 -0800644 explicit ClassListCreator(std::vector<JDWP::RefTypeId>& classes) : classes(classes) {
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -0800645 }
646
Elliott Hughesa2155262011-11-16 16:26:58 -0800647 static bool Visit(Class* c, void* arg) {
648 return reinterpret_cast<ClassListCreator*>(arg)->Visit(c);
649 }
650
651 bool Visit(Class* c) {
652 if (!c->IsPrimitive()) {
653 classes.push_back(static_cast<JDWP::RefTypeId>(gRegistry->Add(c)));
654 }
655 return true;
656 }
657
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -0800658 std::vector<JDWP::RefTypeId>& classes;
Elliott Hughesa2155262011-11-16 16:26:58 -0800659 };
660
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -0800661 ClassListCreator clc(classes);
Elliott Hughesa2155262011-11-16 16:26:58 -0800662 Runtime::Current()->GetClassLinker()->VisitClasses(ClassListCreator::Visit, &clc);
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700663}
664
Elliott Hughes436e3722012-02-17 20:01:47 -0800665JDWP::JdwpError Dbg::GetClassInfo(JDWP::RefTypeId classId, JDWP::JdwpTypeTag* pTypeTag, uint32_t* pStatus, std::string* pDescriptor) {
666 JDWP::JdwpError status;
667 Class* c = DecodeClass(classId, status);
668 if (c == NULL) {
669 return status;
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -0800670 }
671
Elliott Hughesa2155262011-11-16 16:26:58 -0800672 if (c->IsArrayClass()) {
673 *pStatus = JDWP::CS_VERIFIED | JDWP::CS_PREPARED;
674 *pTypeTag = JDWP::TT_ARRAY;
675 } else {
676 if (c->IsErroneous()) {
677 *pStatus = JDWP::CS_ERROR;
678 } else {
679 *pStatus = JDWP::CS_VERIFIED | JDWP::CS_PREPARED | JDWP::CS_INITIALIZED;
680 }
681 *pTypeTag = c->IsInterface() ? JDWP::TT_INTERFACE : JDWP::TT_CLASS;
682 }
683
684 if (pDescriptor != NULL) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800685 *pDescriptor = ClassHelper(c).GetDescriptor();
Elliott Hughesa2155262011-11-16 16:26:58 -0800686 }
Elliott Hughes436e3722012-02-17 20:01:47 -0800687 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700688}
689
Elliott Hughesc3b77c72011-12-15 20:56:48 -0800690void Dbg::FindLoadedClassBySignature(const char* descriptor, std::vector<JDWP::RefTypeId>& ids) {
Elliott Hughes6fa602d2011-12-02 17:54:25 -0800691 std::vector<Class*> classes;
692 Runtime::Current()->GetClassLinker()->LookupClasses(descriptor, classes);
693 ids.clear();
694 for (size_t i = 0; i < classes.size(); ++i) {
695 ids.push_back(gRegistry->Add(classes[i]));
696 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700697}
698
Elliott Hughes2435a572012-02-17 16:07:41 -0800699JDWP::JdwpError Dbg::GetReferenceType(JDWP::ObjectId objectId, JDWP::ExpandBuf* pReply) {
Elliott Hughes499c5132011-11-17 14:55:11 -0800700 Object* o = gRegistry->Get<Object*>(objectId);
Elliott Hughes436e3722012-02-17 20:01:47 -0800701 if (o == NULL || o == kInvalidObject) {
Elliott Hughes2435a572012-02-17 16:07:41 -0800702 return JDWP::ERR_INVALID_OBJECT;
Elliott Hughes499c5132011-11-17 14:55:11 -0800703 }
Elliott Hughes2435a572012-02-17 16:07:41 -0800704
705 JDWP::JdwpTypeTag type_tag;
706 if (o->GetClass()->IsArrayClass()) {
707 type_tag = JDWP::TT_ARRAY;
708 } else if (o->GetClass()->IsInterface()) {
709 type_tag = JDWP::TT_INTERFACE;
710 } else {
711 type_tag = JDWP::TT_CLASS;
712 }
713 JDWP::RefTypeId type_id = gRegistry->Add(o->GetClass());
714
715 expandBufAdd1(pReply, type_tag);
716 expandBufAddRefTypeId(pReply, type_id);
717
718 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700719}
720
Elliott Hughes436e3722012-02-17 20:01:47 -0800721JDWP::JdwpError Dbg::GetSignature(JDWP::RefTypeId classId, std::string& signature) {
Elliott Hughes1fe7afb2012-02-13 17:23:03 -0800722 JDWP::JdwpError status;
Elliott Hughes436e3722012-02-17 20:01:47 -0800723 Class* c = DecodeClass(classId, status);
Elliott Hughes1fe7afb2012-02-13 17:23:03 -0800724 if (c == NULL) {
725 return status;
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -0800726 }
Elliott Hughes1fe7afb2012-02-13 17:23:03 -0800727 signature = ClassHelper(c).GetDescriptor();
728 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700729}
730
Elliott Hughes436e3722012-02-17 20:01:47 -0800731JDWP::JdwpError Dbg::GetSourceFile(JDWP::RefTypeId classId, std::string& result) {
732 JDWP::JdwpError status;
733 Class* c = DecodeClass(classId, status);
734 if (c == NULL) {
735 return status;
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -0800736 }
Elliott Hughes436e3722012-02-17 20:01:47 -0800737 result = ClassHelper(c).GetSourceFile();
738 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700739}
740
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700741uint8_t Dbg::GetObjectTag(JDWP::ObjectId objectId) {
Elliott Hughes24437992011-11-30 14:49:33 -0800742 Object* o = gRegistry->Get<Object*>(objectId);
743 return TagFromObject(o);
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700744}
745
Elliott Hughesaed4be92011-12-02 16:16:23 -0800746size_t Dbg::GetTagWidth(JDWP::JdwpTag tag) {
Elliott Hughesdbb40792011-11-18 17:05:22 -0800747 switch (tag) {
748 case JDWP::JT_VOID:
749 return 0;
750 case JDWP::JT_BYTE:
751 case JDWP::JT_BOOLEAN:
752 return 1;
753 case JDWP::JT_CHAR:
754 case JDWP::JT_SHORT:
755 return 2;
756 case JDWP::JT_FLOAT:
757 case JDWP::JT_INT:
758 return 4;
759 case JDWP::JT_ARRAY:
760 case JDWP::JT_OBJECT:
761 case JDWP::JT_STRING:
762 case JDWP::JT_THREAD:
763 case JDWP::JT_THREAD_GROUP:
764 case JDWP::JT_CLASS_LOADER:
765 case JDWP::JT_CLASS_OBJECT:
766 return sizeof(JDWP::ObjectId);
767 case JDWP::JT_DOUBLE:
768 case JDWP::JT_LONG:
769 return 8;
770 default:
Elliott Hughes3d30d9b2011-12-07 17:35:48 -0800771 LOG(FATAL) << "Unknown tag " << tag;
Elliott Hughesdbb40792011-11-18 17:05:22 -0800772 return -1;
773 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700774}
775
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -0800776JDWP::JdwpError Dbg::GetArrayLength(JDWP::ObjectId arrayId, int& length) {
777 JDWP::JdwpError status;
778 Array* a = DecodeArray(arrayId, status);
779 if (a == NULL) {
780 return status;
Elliott Hughes24437992011-11-30 14:49:33 -0800781 }
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -0800782 length = a->GetLength();
783 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700784}
785
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -0800786JDWP::JdwpError Dbg::OutputArray(JDWP::ObjectId arrayId, int offset, int count, JDWP::ExpandBuf* pReply) {
787 JDWP::JdwpError status;
788 Array* a = DecodeArray(arrayId, status);
789 if (a == NULL) {
790 return status;
791 }
Elliott Hughes24437992011-11-30 14:49:33 -0800792
793 if (offset < 0 || count < 0 || offset > a->GetLength() || a->GetLength() - offset < count) {
794 LOG(WARNING) << __FUNCTION__ << " access out of bounds: offset=" << offset << "; count=" << count;
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -0800795 return JDWP::ERR_INVALID_LENGTH;
Elliott Hughes24437992011-11-30 14:49:33 -0800796 }
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800797 std::string descriptor(ClassHelper(a->GetClass()).GetDescriptor());
Elliott Hughes24437992011-11-30 14:49:33 -0800798 JDWP::JdwpTag tag = BasicTagFromDescriptor(descriptor.c_str() + 1);
799
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -0800800 expandBufAdd1(pReply, tag);
801 expandBufAdd4BE(pReply, count);
802
Elliott Hughes24437992011-11-30 14:49:33 -0800803 if (IsPrimitiveTag(tag)) {
804 size_t width = GetTagWidth(tag);
Elliott Hughes24437992011-11-30 14:49:33 -0800805 uint8_t* dst = expandBufAddSpace(pReply, count * width);
806 if (width == 8) {
Ian Rogersa15e67d2012-02-28 13:51:55 -0800807 const uint64_t* src8 = reinterpret_cast<uint64_t*>(a->GetRawData(sizeof(uint64_t)));
Elliott Hughes24437992011-11-30 14:49:33 -0800808 for (int i = 0; i < count; ++i) JDWP::Write8BE(&dst, src8[offset + i]);
809 } else if (width == 4) {
Ian Rogersa15e67d2012-02-28 13:51:55 -0800810 const uint32_t* src4 = reinterpret_cast<uint32_t*>(a->GetRawData(sizeof(uint32_t)));
Elliott Hughes24437992011-11-30 14:49:33 -0800811 for (int i = 0; i < count; ++i) JDWP::Write4BE(&dst, src4[offset + i]);
812 } else if (width == 2) {
Ian Rogersa15e67d2012-02-28 13:51:55 -0800813 const uint16_t* src2 = reinterpret_cast<uint16_t*>(a->GetRawData(sizeof(uint16_t)));
Elliott Hughes24437992011-11-30 14:49:33 -0800814 for (int i = 0; i < count; ++i) JDWP::Write2BE(&dst, src2[offset + i]);
815 } else {
Ian Rogersa15e67d2012-02-28 13:51:55 -0800816 const uint8_t* src = reinterpret_cast<uint8_t*>(a->GetRawData(sizeof(uint8_t)));
Elliott Hughes24437992011-11-30 14:49:33 -0800817 memcpy(dst, &src[offset * width], count * width);
818 }
819 } else {
820 ObjectArray<Object>* oa = a->AsObjectArray<Object>();
821 for (int i = 0; i < count; ++i) {
Elliott Hughesf03b8f62011-12-02 14:26:25 -0800822 Object* element = oa->Get(offset + i);
Elliott Hughes24437992011-11-30 14:49:33 -0800823 JDWP::JdwpTag specific_tag = (element != NULL) ? TagFromObject(element) : tag;
824 expandBufAdd1(pReply, specific_tag);
825 expandBufAddObjectId(pReply, gRegistry->Add(element));
826 }
827 }
828
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -0800829 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700830}
831
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -0800832JDWP::JdwpError Dbg::SetArrayElements(JDWP::ObjectId arrayId, int offset, int count, const uint8_t* src) {
833 JDWP::JdwpError status;
834 Array* a = DecodeArray(arrayId, status);
835 if (a == NULL) {
836 return status;
837 }
Elliott Hughesf03b8f62011-12-02 14:26:25 -0800838
839 if (offset < 0 || count < 0 || offset > a->GetLength() || a->GetLength() - offset < count) {
840 LOG(WARNING) << __FUNCTION__ << " access out of bounds: offset=" << offset << "; count=" << count;
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -0800841 return JDWP::ERR_INVALID_LENGTH;
Elliott Hughesf03b8f62011-12-02 14:26:25 -0800842 }
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800843 std::string descriptor(ClassHelper(a->GetClass()).GetDescriptor());
Elliott Hughesf03b8f62011-12-02 14:26:25 -0800844 JDWP::JdwpTag tag = BasicTagFromDescriptor(descriptor.c_str() + 1);
845
846 if (IsPrimitiveTag(tag)) {
847 size_t width = GetTagWidth(tag);
Elliott Hughesf03b8f62011-12-02 14:26:25 -0800848 if (width == 8) {
Ian Rogersa15e67d2012-02-28 13:51:55 -0800849 uint8_t* dst = &(reinterpret_cast<uint8_t*>(a->GetRawData(sizeof(uint64_t)))[offset * width]);
Elliott Hughesf03b8f62011-12-02 14:26:25 -0800850 for (int i = 0; i < count; ++i) {
851 // Handle potentially non-aligned memory access one byte at a time for ARM's benefit.
852 uint64_t value;
853 for (size_t j = 0; j < sizeof(uint64_t); ++j) reinterpret_cast<uint8_t*>(&value)[j] = src[j];
854 src += sizeof(uint64_t);
855 JDWP::Write8BE(&dst, value);
856 }
857 } else if (width == 4) {
Ian Rogersa15e67d2012-02-28 13:51:55 -0800858 uint8_t* dst = &(reinterpret_cast<uint8_t*>(a->GetRawData(sizeof(uint32_t)))[offset * width]);
Elliott Hughesf03b8f62011-12-02 14:26:25 -0800859 const uint32_t* src4 = reinterpret_cast<const uint32_t*>(src);
860 for (int i = 0; i < count; ++i) JDWP::Write4BE(&dst, src4[i]);
861 } else if (width == 2) {
Ian Rogersa15e67d2012-02-28 13:51:55 -0800862 uint8_t* dst = &(reinterpret_cast<uint8_t*>(a->GetRawData(sizeof(uint16_t)))[offset * width]);
Elliott Hughesf03b8f62011-12-02 14:26:25 -0800863 const uint16_t* src2 = reinterpret_cast<const uint16_t*>(src);
864 for (int i = 0; i < count; ++i) JDWP::Write2BE(&dst, src2[i]);
865 } else {
Ian Rogersa15e67d2012-02-28 13:51:55 -0800866 uint8_t* dst = &(reinterpret_cast<uint8_t*>(a->GetRawData(sizeof(uint8_t)))[offset * width]);
Elliott Hughesf03b8f62011-12-02 14:26:25 -0800867 memcpy(&dst[offset * width], src, count * width);
868 }
869 } else {
870 ObjectArray<Object>* oa = a->AsObjectArray<Object>();
871 for (int i = 0; i < count; ++i) {
872 JDWP::ObjectId id = JDWP::ReadObjectId(&src);
Elliott Hughes436e3722012-02-17 20:01:47 -0800873 Object* o = gRegistry->Get<Object*>(id);
874 if (o == kInvalidObject) {
875 return JDWP::ERR_INVALID_OBJECT;
876 }
877 oa->Set(offset + i, o);
Elliott Hughesf03b8f62011-12-02 14:26:25 -0800878 }
879 }
880
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -0800881 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700882}
883
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -0800884JDWP::ObjectId Dbg::CreateString(const std::string& str) {
885 return gRegistry->Add(String::AllocFromModifiedUtf8(str.c_str()));
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700886}
887
Elliott Hughes436e3722012-02-17 20:01:47 -0800888JDWP::JdwpError Dbg::CreateObject(JDWP::RefTypeId classId, JDWP::ObjectId& new_object) {
889 JDWP::JdwpError status;
890 Class* c = DecodeClass(classId, status);
891 if (c == NULL) {
892 return status;
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -0800893 }
Elliott Hughes436e3722012-02-17 20:01:47 -0800894 new_object = gRegistry->Add(c->AllocObject());
895 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700896}
897
Elliott Hughesbf13d362011-12-08 15:51:37 -0800898/*
899 * Used by Eclipse's "Display" view to evaluate "new byte[5]" to get "(byte[]) [0, 0, 0, 0, 0]".
900 */
Elliott Hughes436e3722012-02-17 20:01:47 -0800901JDWP::JdwpError Dbg::CreateArrayObject(JDWP::RefTypeId arrayClassId, uint32_t length, JDWP::ObjectId& new_array) {
902 JDWP::JdwpError status;
903 Class* c = DecodeClass(arrayClassId, status);
904 if (c == NULL) {
905 return status;
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -0800906 }
Elliott Hughes436e3722012-02-17 20:01:47 -0800907 new_array = gRegistry->Add(Array::Alloc(c, length));
908 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700909}
910
911bool Dbg::MatchType(JDWP::RefTypeId instClassId, JDWP::RefTypeId classId) {
Elliott Hughes436e3722012-02-17 20:01:47 -0800912 JDWP::JdwpError status;
913 Class* c1 = DecodeClass(instClassId, status);
Elliott Hughesa656a0f2012-02-21 18:03:44 -0800914 CHECK(c1 != NULL);
Elliott Hughes436e3722012-02-17 20:01:47 -0800915 Class* c2 = DecodeClass(classId, status);
Elliott Hughesa656a0f2012-02-21 18:03:44 -0800916 CHECK(c2 != NULL);
917 return c1->IsAssignableFrom(c2);
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700918}
919
Elliott Hughes86964332012-02-15 19:37:42 -0800920static JDWP::FieldId ToFieldId(const Field* f) {
Elliott Hughes03181a82011-11-17 17:22:21 -0800921#ifdef MOVING_GARBAGE_COLLECTOR
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700922 UNIMPLEMENTED(FATAL);
Elliott Hughes03181a82011-11-17 17:22:21 -0800923#else
924 return static_cast<JDWP::FieldId>(reinterpret_cast<uintptr_t>(f));
925#endif
926}
927
Elliott Hughes86964332012-02-15 19:37:42 -0800928static JDWP::MethodId ToMethodId(const Method* m) {
Elliott Hughes03181a82011-11-17 17:22:21 -0800929#ifdef MOVING_GARBAGE_COLLECTOR
930 UNIMPLEMENTED(FATAL);
931#else
932 return static_cast<JDWP::MethodId>(reinterpret_cast<uintptr_t>(m));
933#endif
934}
935
Elliott Hughes86964332012-02-15 19:37:42 -0800936static Field* FromFieldId(JDWP::FieldId fid) {
Elliott Hughesaed4be92011-12-02 16:16:23 -0800937#ifdef MOVING_GARBAGE_COLLECTOR
938 UNIMPLEMENTED(FATAL);
939#else
940 return reinterpret_cast<Field*>(static_cast<uintptr_t>(fid));
941#endif
942}
943
Elliott Hughes86964332012-02-15 19:37:42 -0800944static Method* FromMethodId(JDWP::MethodId mid) {
Elliott Hughes03181a82011-11-17 17:22:21 -0800945#ifdef MOVING_GARBAGE_COLLECTOR
946 UNIMPLEMENTED(FATAL);
947#else
948 return reinterpret_cast<Method*>(static_cast<uintptr_t>(mid));
949#endif
950}
951
Elliott Hughes86964332012-02-15 19:37:42 -0800952static void SetLocation(JDWP::JdwpLocation& location, Method* m, uintptr_t native_pc) {
Elliott Hughes91bf6cd2012-02-14 17:27:48 -0800953 if (m == NULL) {
954 memset(&location, 0, sizeof(location));
955 } else {
956 Class* c = m->GetDeclaringClass();
957 location.typeTag = c->IsInterface() ? JDWP::TT_INTERFACE : JDWP::TT_CLASS;
958 location.classId = gRegistry->Add(c);
959 location.methodId = ToMethodId(m);
Elliott Hughes972a47b2012-02-21 18:16:06 -0800960 location.dex_pc = m->IsNative() ? -1 : m->ToDexPC(native_pc);
Elliott Hughes91bf6cd2012-02-14 17:27:48 -0800961 }
Elliott Hughesd07986f2011-12-06 18:27:45 -0800962}
963
Elliott Hughes436e3722012-02-17 20:01:47 -0800964std::string Dbg::GetMethodName(JDWP::RefTypeId, JDWP::MethodId methodId) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800965 Method* m = FromMethodId(methodId);
966 return MethodHelper(m).GetName();
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700967}
968
Elliott Hughesa2e54f62011-11-17 13:01:30 -0800969/*
970 * Augment the access flags for synthetic methods and fields by setting
971 * the (as described by the spec) "0xf0000000 bit". Also, strip out any
972 * flags not specified by the Java programming language.
973 */
974static uint32_t MangleAccessFlags(uint32_t accessFlags) {
975 accessFlags &= kAccJavaFlagsMask;
976 if ((accessFlags & kAccSynthetic) != 0) {
977 accessFlags |= 0xf0000000;
978 }
979 return accessFlags;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700980}
981
Elliott Hughesdbb40792011-11-18 17:05:22 -0800982static const uint16_t kEclipseWorkaroundSlot = 1000;
983
984/*
985 * Eclipse appears to expect that the "this" reference is in slot zero.
986 * If it's not, the "variables" display will show two copies of "this",
987 * possibly because it gets "this" from SF.ThisObject and then displays
988 * all locals with nonzero slot numbers.
989 *
990 * So, we remap the item in slot 0 to 1000, and remap "this" to zero. On
991 * SF.GetValues / SF.SetValues we map them back.
Elliott Hughesc5b734a2011-12-01 17:20:58 -0800992 *
993 * TODO: jdb uses the value to determine whether a variable is a local or an argument,
994 * by checking whether it's less than the number of arguments. To make that work, we'd
995 * have to "mangle" all the arguments to come first, not just the implicit argument 'this'.
Elliott Hughesdbb40792011-11-18 17:05:22 -0800996 */
997static uint16_t MangleSlot(uint16_t slot, const char* name) {
998 uint16_t newSlot = slot;
999 if (strcmp(name, "this") == 0) {
1000 newSlot = 0;
1001 } else if (slot == 0) {
1002 newSlot = kEclipseWorkaroundSlot;
1003 }
1004 return newSlot;
1005}
1006
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08001007static uint16_t DemangleSlot(uint16_t slot, Method* m) {
Elliott Hughesdbb40792011-11-18 17:05:22 -08001008 if (slot == kEclipseWorkaroundSlot) {
Elliott Hughes68fdbd02011-11-29 19:22:47 -08001009 return 0;
Elliott Hughesdbb40792011-11-18 17:05:22 -08001010 } else if (slot == 0) {
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08001011 const DexFile::CodeItem* code_item = MethodHelper(m).GetCodeItem();
1012 CHECK(code_item != NULL);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001013 return code_item->registers_size_ - code_item->ins_size_;
Elliott Hughesdbb40792011-11-18 17:05:22 -08001014 }
Elliott Hughes68fdbd02011-11-29 19:22:47 -08001015 return slot;
Elliott Hughesdbb40792011-11-18 17:05:22 -08001016}
1017
Elliott Hughes436e3722012-02-17 20:01:47 -08001018JDWP::JdwpError Dbg::OutputDeclaredFields(JDWP::RefTypeId classId, bool with_generic, JDWP::ExpandBuf* pReply) {
1019 JDWP::JdwpError status;
1020 Class* c = DecodeClass(classId, status);
1021 if (c == NULL) {
1022 return status;
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -08001023 }
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001024
1025 size_t instance_field_count = c->NumInstanceFields();
1026 size_t static_field_count = c->NumStaticFields();
1027
1028 expandBufAdd4BE(pReply, instance_field_count + static_field_count);
1029
1030 for (size_t i = 0; i < instance_field_count + static_field_count; ++i) {
1031 Field* f = (i < instance_field_count) ? c->GetInstanceField(i) : c->GetStaticField(i - instance_field_count);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001032 FieldHelper fh(f);
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001033 expandBufAddFieldId(pReply, ToFieldId(f));
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001034 expandBufAddUtf8String(pReply, fh.GetName());
1035 expandBufAddUtf8String(pReply, fh.GetTypeDescriptor());
Elliott Hughesc5b734a2011-12-01 17:20:58 -08001036 if (with_generic) {
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001037 static const char genericSignature[1] = "";
1038 expandBufAddUtf8String(pReply, genericSignature);
1039 }
1040 expandBufAdd4BE(pReply, MangleAccessFlags(f->GetAccessFlags()));
1041 }
Elliott Hughes436e3722012-02-17 20:01:47 -08001042 return JDWP::ERR_NONE;
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001043}
1044
Elliott Hughes436e3722012-02-17 20:01:47 -08001045JDWP::JdwpError Dbg::OutputDeclaredMethods(JDWP::RefTypeId classId, bool with_generic, JDWP::ExpandBuf* pReply) {
1046 JDWP::JdwpError status;
1047 Class* c = DecodeClass(classId, status);
1048 if (c == NULL) {
1049 return status;
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -08001050 }
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001051
1052 size_t direct_method_count = c->NumDirectMethods();
1053 size_t virtual_method_count = c->NumVirtualMethods();
1054
1055 expandBufAdd4BE(pReply, direct_method_count + virtual_method_count);
1056
1057 for (size_t i = 0; i < direct_method_count + virtual_method_count; ++i) {
1058 Method* m = (i < direct_method_count) ? c->GetDirectMethod(i) : c->GetVirtualMethod(i - direct_method_count);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001059 MethodHelper mh(m);
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001060 expandBufAddMethodId(pReply, ToMethodId(m));
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001061 expandBufAddUtf8String(pReply, mh.GetName());
Elliott Hughes4740cdf2011-12-07 14:07:12 -08001062 expandBufAddUtf8String(pReply, mh.GetSignature());
Elliott Hughesc5b734a2011-12-01 17:20:58 -08001063 if (with_generic) {
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001064 static const char genericSignature[1] = "";
1065 expandBufAddUtf8String(pReply, genericSignature);
1066 }
1067 expandBufAdd4BE(pReply, MangleAccessFlags(m->GetAccessFlags()));
1068 }
Elliott Hughes436e3722012-02-17 20:01:47 -08001069 return JDWP::ERR_NONE;
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001070}
1071
Elliott Hughes436e3722012-02-17 20:01:47 -08001072JDWP::JdwpError Dbg::OutputDeclaredInterfaces(JDWP::RefTypeId classId, JDWP::ExpandBuf* pReply) {
1073 JDWP::JdwpError status;
1074 Class* c = DecodeClass(classId, status);
1075 if (c == NULL) {
1076 return status;
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -08001077 }
Elliott Hughes436e3722012-02-17 20:01:47 -08001078
1079 ClassHelper kh(c);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001080 size_t interface_count = kh.NumInterfaces();
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001081 expandBufAdd4BE(pReply, interface_count);
1082 for (size_t i = 0; i < interface_count; ++i) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001083 expandBufAddRefTypeId(pReply, gRegistry->Add(kh.GetInterface(i)));
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001084 }
Elliott Hughes436e3722012-02-17 20:01:47 -08001085 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001086}
1087
Elliott Hughes436e3722012-02-17 20:01:47 -08001088void Dbg::OutputLineTable(JDWP::RefTypeId, JDWP::MethodId methodId, JDWP::ExpandBuf* pReply) {
Elliott Hughes03181a82011-11-17 17:22:21 -08001089 struct DebugCallbackContext {
1090 int numItems;
1091 JDWP::ExpandBuf* pReply;
1092
Elliott Hughes2435a572012-02-17 16:07:41 -08001093 static bool Callback(void* context, uint32_t address, uint32_t line_number) {
Elliott Hughes03181a82011-11-17 17:22:21 -08001094 DebugCallbackContext* pContext = reinterpret_cast<DebugCallbackContext*>(context);
1095 expandBufAdd8BE(pContext->pReply, address);
Elliott Hughes2435a572012-02-17 16:07:41 -08001096 expandBufAdd4BE(pContext->pReply, line_number);
Elliott Hughes03181a82011-11-17 17:22:21 -08001097 pContext->numItems++;
1098 return true;
1099 }
1100 };
1101
1102 Method* m = FromMethodId(methodId);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001103 MethodHelper mh(m);
Elliott Hughes03181a82011-11-17 17:22:21 -08001104 uint64_t start, end;
1105 if (m->IsNative()) {
1106 start = -1;
1107 end = -1;
1108 } else {
1109 start = 0;
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001110 // TODO: what are the units supposed to be? *2?
1111 end = mh.GetCodeItem()->insns_size_in_code_units_;
Elliott Hughes03181a82011-11-17 17:22:21 -08001112 }
1113
1114 expandBufAdd8BE(pReply, start);
1115 expandBufAdd8BE(pReply, end);
1116
1117 // Add numLines later
1118 size_t numLinesOffset = expandBufGetLength(pReply);
1119 expandBufAdd4BE(pReply, 0);
1120
1121 DebugCallbackContext context;
1122 context.numItems = 0;
1123 context.pReply = pReply;
1124
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001125 mh.GetDexFile().DecodeDebugInfo(mh.GetCodeItem(), m->IsStatic(), m->GetDexMethodIndex(),
1126 DebugCallbackContext::Callback, NULL, &context);
Elliott Hughes03181a82011-11-17 17:22:21 -08001127
1128 JDWP::Set4BE(expandBufGetBuffer(pReply) + numLinesOffset, context.numItems);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001129}
1130
Elliott Hughes436e3722012-02-17 20:01:47 -08001131void Dbg::OutputVariableTable(JDWP::RefTypeId, JDWP::MethodId methodId, bool with_generic, JDWP::ExpandBuf* pReply) {
Elliott Hughesdbb40792011-11-18 17:05:22 -08001132 struct DebugCallbackContext {
Elliott Hughesdbb40792011-11-18 17:05:22 -08001133 JDWP::ExpandBuf* pReply;
Elliott Hughesc5b734a2011-12-01 17:20:58 -08001134 size_t variable_count;
1135 bool with_generic;
Elliott Hughesdbb40792011-11-18 17:05:22 -08001136
Elliott Hughesc5b734a2011-12-01 17:20:58 -08001137 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 -08001138 DebugCallbackContext* pContext = reinterpret_cast<DebugCallbackContext*>(context);
1139
Elliott Hughesad3da692012-02-24 16:51:35 -08001140 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 -08001141
Elliott Hughes68fdbd02011-11-29 19:22:47 -08001142 slot = MangleSlot(slot, name);
1143
Elliott Hughesdbb40792011-11-18 17:05:22 -08001144 expandBufAdd8BE(pContext->pReply, startAddress);
1145 expandBufAddUtf8String(pContext->pReply, name);
1146 expandBufAddUtf8String(pContext->pReply, descriptor);
Elliott Hughesc5b734a2011-12-01 17:20:58 -08001147 if (pContext->with_generic) {
Elliott Hughesdbb40792011-11-18 17:05:22 -08001148 expandBufAddUtf8String(pContext->pReply, signature);
1149 }
1150 expandBufAdd4BE(pContext->pReply, endAddress - startAddress);
1151 expandBufAdd4BE(pContext->pReply, slot);
1152
Elliott Hughesc5b734a2011-12-01 17:20:58 -08001153 ++pContext->variable_count;
Elliott Hughesdbb40792011-11-18 17:05:22 -08001154 }
1155 };
1156
1157 Method* m = FromMethodId(methodId);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001158 MethodHelper mh(m);
1159 const DexFile::CodeItem* code_item = mh.GetCodeItem();
Elliott Hughesdbb40792011-11-18 17:05:22 -08001160
Elliott Hughesc5b734a2011-12-01 17:20:58 -08001161 // arg_count considers doubles and longs to take 2 units.
1162 // variable_count considers everything to take 1 unit.
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001163 std::string shorty(mh.GetShorty());
Elliott Hughesc5b734a2011-12-01 17:20:58 -08001164 expandBufAdd4BE(pReply, m->NumArgRegisters(shorty));
Elliott Hughesdbb40792011-11-18 17:05:22 -08001165
Elliott Hughesc5b734a2011-12-01 17:20:58 -08001166 // We don't know the total number of variables yet, so leave a blank and update it later.
1167 size_t variable_count_offset = expandBufGetLength(pReply);
Elliott Hughesdbb40792011-11-18 17:05:22 -08001168 expandBufAdd4BE(pReply, 0);
1169
1170 DebugCallbackContext context;
Elliott Hughesdbb40792011-11-18 17:05:22 -08001171 context.pReply = pReply;
Elliott Hughesc5b734a2011-12-01 17:20:58 -08001172 context.variable_count = 0;
1173 context.with_generic = with_generic;
Elliott Hughesdbb40792011-11-18 17:05:22 -08001174
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001175 mh.GetDexFile().DecodeDebugInfo(code_item, m->IsStatic(), m->GetDexMethodIndex(), NULL,
1176 DebugCallbackContext::Callback, &context);
Elliott Hughesdbb40792011-11-18 17:05:22 -08001177
Elliott Hughesc5b734a2011-12-01 17:20:58 -08001178 JDWP::Set4BE(expandBufGetBuffer(pReply) + variable_count_offset, context.variable_count);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001179}
1180
Elliott Hughesaed4be92011-12-02 16:16:23 -08001181JDWP::JdwpTag Dbg::GetFieldBasicTag(JDWP::FieldId fieldId) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001182 return BasicTagFromDescriptor(FieldHelper(FromFieldId(fieldId)).GetTypeDescriptor());
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001183}
1184
Elliott Hughesaed4be92011-12-02 16:16:23 -08001185JDWP::JdwpTag Dbg::GetStaticFieldBasicTag(JDWP::FieldId fieldId) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001186 return BasicTagFromDescriptor(FieldHelper(FromFieldId(fieldId)).GetTypeDescriptor());
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001187}
1188
Elliott Hughes0cf74332012-02-23 23:14:00 -08001189static JDWP::JdwpError GetFieldValueImpl(JDWP::RefTypeId refTypeId, JDWP::ObjectId objectId, JDWP::FieldId fieldId, JDWP::ExpandBuf* pReply, bool is_static) {
1190 JDWP::JdwpError status;
1191 Class* c = DecodeClass(refTypeId, status);
1192 if (refTypeId != 0 && c == NULL) {
1193 return status;
1194 }
1195
Elliott Hughesaed4be92011-12-02 16:16:23 -08001196 Object* o = gRegistry->Get<Object*>(objectId);
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08001197 if ((!is_static && o == NULL) || o == kInvalidObject) {
1198 return JDWP::ERR_INVALID_OBJECT;
1199 }
Elliott Hughesaed4be92011-12-02 16:16:23 -08001200 Field* f = FromFieldId(fieldId);
Elliott Hughes0cf74332012-02-23 23:14:00 -08001201
1202 Class* receiver_class = c;
1203 if (receiver_class == NULL && o != NULL) {
1204 receiver_class = o->GetClass();
1205 }
1206 // TODO: should we give up now if receiver_class is NULL?
1207 if (receiver_class != NULL && !f->GetDeclaringClass()->IsAssignableFrom(receiver_class)) {
1208 LOG(INFO) << "ERR_INVALID_FIELDID: " << PrettyField(f) << " " << PrettyClass(receiver_class);
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08001209 return JDWP::ERR_INVALID_FIELDID;
1210 }
Elliott Hughesaed4be92011-12-02 16:16:23 -08001211
Elliott Hughes0cf74332012-02-23 23:14:00 -08001212 // The RI only enforces the static/non-static mismatch in one direction.
1213 // TODO: should we change the tests and check both?
1214 if (is_static) {
1215 if (!f->IsStatic()) {
1216 return JDWP::ERR_INVALID_FIELDID;
1217 }
1218 } else {
1219 if (f->IsStatic()) {
1220 LOG(WARNING) << "Ignoring non-NULL receiver for ObjectReference.SetValues on static field " << PrettyField(f);
1221 o = NULL;
1222 }
1223 }
1224
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001225 JDWP::JdwpTag tag = BasicTagFromDescriptor(FieldHelper(f).GetTypeDescriptor());
Elliott Hughesaed4be92011-12-02 16:16:23 -08001226
1227 if (IsPrimitiveTag(tag)) {
1228 expandBufAdd1(pReply, tag);
1229 if (tag == JDWP::JT_BOOLEAN || tag == JDWP::JT_BYTE) {
1230 expandBufAdd1(pReply, f->Get32(o));
1231 } else if (tag == JDWP::JT_CHAR || tag == JDWP::JT_SHORT) {
1232 expandBufAdd2BE(pReply, f->Get32(o));
1233 } else if (tag == JDWP::JT_FLOAT || tag == JDWP::JT_INT) {
1234 expandBufAdd4BE(pReply, f->Get32(o));
1235 } else if (tag == JDWP::JT_DOUBLE || tag == JDWP::JT_LONG) {
1236 expandBufAdd8BE(pReply, f->Get64(o));
1237 } else {
Elliott Hughes3d30d9b2011-12-07 17:35:48 -08001238 LOG(FATAL) << "Unknown tag: " << tag;
Elliott Hughesaed4be92011-12-02 16:16:23 -08001239 }
1240 } else {
1241 Object* value = f->GetObject(o);
1242 expandBufAdd1(pReply, TagFromObject(value));
1243 expandBufAddObjectId(pReply, gRegistry->Add(value));
1244 }
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08001245 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001246}
1247
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08001248JDWP::JdwpError Dbg::GetFieldValue(JDWP::ObjectId objectId, JDWP::FieldId fieldId, JDWP::ExpandBuf* pReply) {
Elliott Hughes0cf74332012-02-23 23:14:00 -08001249 return GetFieldValueImpl(0, objectId, fieldId, pReply, false);
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08001250}
1251
Elliott Hughes0cf74332012-02-23 23:14:00 -08001252JDWP::JdwpError Dbg::GetStaticFieldValue(JDWP::RefTypeId refTypeId, JDWP::FieldId fieldId, JDWP::ExpandBuf* pReply) {
1253 return GetFieldValueImpl(refTypeId, 0, fieldId, pReply, true);
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08001254}
1255
1256static JDWP::JdwpError SetFieldValueImpl(JDWP::ObjectId objectId, JDWP::FieldId fieldId, uint64_t value, int width, bool is_static) {
Elliott Hughesaed4be92011-12-02 16:16:23 -08001257 Object* o = gRegistry->Get<Object*>(objectId);
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08001258 if ((!is_static && o == NULL) || o == kInvalidObject) {
1259 return JDWP::ERR_INVALID_OBJECT;
1260 }
Elliott Hughesaed4be92011-12-02 16:16:23 -08001261 Field* f = FromFieldId(fieldId);
Elliott Hughes0cf74332012-02-23 23:14:00 -08001262
1263 // The RI only enforces the static/non-static mismatch in one direction.
1264 // TODO: should we change the tests and check both?
1265 if (is_static) {
1266 if (!f->IsStatic()) {
1267 return JDWP::ERR_INVALID_FIELDID;
1268 }
1269 } else {
1270 if (f->IsStatic()) {
1271 LOG(WARNING) << "Ignoring non-NULL receiver for ObjectReference.SetValues on static field " << PrettyField(f);
1272 o = NULL;
1273 }
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08001274 }
Elliott Hughesaed4be92011-12-02 16:16:23 -08001275
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001276 JDWP::JdwpTag tag = BasicTagFromDescriptor(FieldHelper(f).GetTypeDescriptor());
Elliott Hughesaed4be92011-12-02 16:16:23 -08001277
1278 if (IsPrimitiveTag(tag)) {
1279 if (tag == JDWP::JT_DOUBLE || tag == JDWP::JT_LONG) {
Elliott Hughes1bac54f2012-03-16 12:48:31 -07001280 CHECK_EQ(width, 8);
Elliott Hughesaed4be92011-12-02 16:16:23 -08001281 f->Set64(o, value);
1282 } else {
Elliott Hughes1bac54f2012-03-16 12:48:31 -07001283 CHECK_LE(width, 4);
Elliott Hughesaed4be92011-12-02 16:16:23 -08001284 f->Set32(o, value);
1285 }
1286 } else {
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -08001287 Object* v = gRegistry->Get<Object*>(value);
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08001288 if (v == kInvalidObject) {
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -08001289 return JDWP::ERR_INVALID_OBJECT;
1290 }
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08001291 if (v != NULL) {
1292 Class* field_type = FieldHelper(f).GetType();
1293 if (!field_type->IsAssignableFrom(v->GetClass())) {
1294 return JDWP::ERR_INVALID_OBJECT;
1295 }
1296 }
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -08001297 f->SetObject(o, v);
Elliott Hughesaed4be92011-12-02 16:16:23 -08001298 }
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -08001299
1300 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001301}
1302
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08001303JDWP::JdwpError Dbg::SetFieldValue(JDWP::ObjectId objectId, JDWP::FieldId fieldId, uint64_t value, int width) {
1304 return SetFieldValueImpl(objectId, fieldId, value, width, false);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001305}
1306
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -08001307JDWP::JdwpError Dbg::SetStaticFieldValue(JDWP::FieldId fieldId, uint64_t value, int width) {
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08001308 return SetFieldValueImpl(0, fieldId, value, width, true);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001309}
1310
Elliott Hughes68fdbd02011-11-29 19:22:47 -08001311std::string Dbg::StringToUtf8(JDWP::ObjectId strId) {
1312 String* s = gRegistry->Get<String*>(strId);
1313 return s->ToModifiedUtf8();
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001314}
1315
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001316bool Dbg::GetThreadName(JDWP::ObjectId threadId, std::string& name) {
1317 ScopedThreadListLock thread_list_lock;
1318 Thread* thread = DecodeThread(threadId);
1319 if (thread == NULL) {
1320 return false;
1321 }
Elliott Hughesffb465f2012-03-01 18:46:05 -08001322 thread->GetThreadName(name);
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001323 return true;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001324}
1325
Elliott Hughes2435a572012-02-17 16:07:41 -08001326JDWP::JdwpError Dbg::GetThreadGroup(JDWP::ObjectId threadId, JDWP::ExpandBuf* pReply) {
Elliott Hughes499c5132011-11-17 14:55:11 -08001327 Object* thread = gRegistry->Get<Object*>(threadId);
Elliott Hughes436e3722012-02-17 20:01:47 -08001328 if (thread == kInvalidObject) {
Elliott Hughes2435a572012-02-17 16:07:41 -08001329 return JDWP::ERR_INVALID_OBJECT;
1330 }
1331
1332 // Okay, so it's an object, but is it actually a thread?
Elliott Hughes436e3722012-02-17 20:01:47 -08001333 if (DecodeThread(threadId) == NULL) {
Elliott Hughes2435a572012-02-17 16:07:41 -08001334 return JDWP::ERR_INVALID_THREAD;
1335 }
Elliott Hughes499c5132011-11-17 14:55:11 -08001336
1337 Class* c = Runtime::Current()->GetClassLinker()->FindSystemClass("Ljava/lang/Thread;");
1338 CHECK(c != NULL);
1339 Field* f = c->FindInstanceField("group", "Ljava/lang/ThreadGroup;");
1340 CHECK(f != NULL);
1341 Object* group = f->GetObject(thread);
1342 CHECK(group != NULL);
Elliott Hughes2435a572012-02-17 16:07:41 -08001343 JDWP::ObjectId thread_group_id = gRegistry->Add(group);
1344
1345 expandBufAddObjectId(pReply, thread_group_id);
1346 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001347}
1348
Elliott Hughes499c5132011-11-17 14:55:11 -08001349std::string Dbg::GetThreadGroupName(JDWP::ObjectId threadGroupId) {
1350 Object* thread_group = gRegistry->Get<Object*>(threadGroupId);
1351 CHECK(thread_group != NULL);
1352
1353 Class* c = Runtime::Current()->GetClassLinker()->FindSystemClass("Ljava/lang/ThreadGroup;");
1354 CHECK(c != NULL);
1355 Field* f = c->FindInstanceField("name", "Ljava/lang/String;");
1356 CHECK(f != NULL);
1357 String* s = reinterpret_cast<String*>(f->GetObject(thread_group));
1358 return s->ToModifiedUtf8();
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001359}
1360
1361JDWP::ObjectId Dbg::GetThreadGroupParent(JDWP::ObjectId threadGroupId) {
Elliott Hughes4e235312011-12-02 11:34:15 -08001362 Object* thread_group = gRegistry->Get<Object*>(threadGroupId);
1363 CHECK(thread_group != NULL);
1364
1365 Class* c = Runtime::Current()->GetClassLinker()->FindSystemClass("Ljava/lang/ThreadGroup;");
1366 CHECK(c != NULL);
1367 Field* f = c->FindInstanceField("parent", "Ljava/lang/ThreadGroup;");
1368 CHECK(f != NULL);
1369 Object* parent = f->GetObject(thread_group);
1370 return gRegistry->Add(parent);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001371}
1372
1373JDWP::ObjectId Dbg::GetSystemThreadGroupId() {
Elliott Hughes462c9442012-03-23 18:47:50 -07001374 return gRegistry->Add(Thread::GetSystemThreadGroup());
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001375}
1376
1377JDWP::ObjectId Dbg::GetMainThreadGroupId() {
Elliott Hughes462c9442012-03-23 18:47:50 -07001378 return gRegistry->Add(Thread::GetMainThreadGroup());
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001379}
1380
Elliott Hughes3d30d9b2011-12-07 17:35:48 -08001381bool Dbg::GetThreadStatus(JDWP::ObjectId threadId, JDWP::JdwpThreadStatus* pThreadStatus, JDWP::JdwpSuspendStatus* pSuspendStatus) {
Elliott Hughes499c5132011-11-17 14:55:11 -08001382 ScopedThreadListLock thread_list_lock;
1383
1384 Thread* thread = DecodeThread(threadId);
1385 if (thread == NULL) {
1386 return false;
1387 }
1388
Elliott Hughes3ce4b262012-02-24 11:24:02 -08001389 // TODO: if we're in Thread.sleep(long), we should return TS_SLEEPING,
1390 // even if it's implemented using Object.wait(long).
Elliott Hughes499c5132011-11-17 14:55:11 -08001391 switch (thread->GetState()) {
Elliott Hughes34e06962012-04-09 13:55:55 -07001392 case kTerminated: *pThreadStatus = JDWP::TS_ZOMBIE; break;
1393 case kRunnable: *pThreadStatus = JDWP::TS_RUNNING; break;
1394 case kTimedWaiting: *pThreadStatus = JDWP::TS_WAIT; break;
1395 case kBlocked: *pThreadStatus = JDWP::TS_MONITOR; break;
1396 case kWaiting: *pThreadStatus = JDWP::TS_WAIT; break;
1397 case kStarting: *pThreadStatus = JDWP::TS_ZOMBIE; break;
1398 case kNative: *pThreadStatus = JDWP::TS_RUNNING; break;
1399 case kVmWait: *pThreadStatus = JDWP::TS_WAIT; break;
1400 case kSuspended: *pThreadStatus = JDWP::TS_RUNNING; break;
Elliott Hughescf2b2d42012-03-27 17:11:42 -07001401 // Don't add a 'default' here so the compiler can spot incompatible enum changes.
Elliott Hughes499c5132011-11-17 14:55:11 -08001402 }
1403
Elliott Hughes3d30d9b2011-12-07 17:35:48 -08001404 *pSuspendStatus = (thread->IsSuspended() ? JDWP::SUSPEND_STATUS_SUSPENDED : JDWP::SUSPEND_STATUS_NOT_SUSPENDED);
Elliott Hughes499c5132011-11-17 14:55:11 -08001405
1406 return true;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001407}
1408
Elliott Hughes2435a572012-02-17 16:07:41 -08001409JDWP::JdwpError Dbg::GetThreadSuspendCount(JDWP::ObjectId threadId, JDWP::ExpandBuf* pReply) {
1410 Thread* thread = DecodeThread(threadId);
1411 if (thread == NULL) {
1412 return JDWP::ERR_INVALID_THREAD;
1413 }
1414 expandBufAdd4BE(pReply, thread->GetSuspendCount());
1415 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001416}
1417
1418bool Dbg::ThreadExists(JDWP::ObjectId threadId) {
Elliott Hughes761928d2011-11-16 18:33:03 -08001419 return DecodeThread(threadId) != NULL;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001420}
1421
1422bool Dbg::IsSuspended(JDWP::ObjectId threadId) {
Elliott Hughes761928d2011-11-16 18:33:03 -08001423 return DecodeThread(threadId)->IsSuspended();
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001424}
1425
Elliott Hughesa2155262011-11-16 16:26:58 -08001426void Dbg::GetThreadGroupThreadsImpl(Object* thread_group, JDWP::ObjectId** ppThreadIds, uint32_t* pThreadCount) {
1427 struct ThreadListVisitor {
1428 static void Visit(Thread* t, void* arg) {
1429 reinterpret_cast<ThreadListVisitor*>(arg)->Visit(t);
1430 }
1431
1432 void Visit(Thread* t) {
1433 if (t == Dbg::GetDebugThread()) {
1434 // Skip the JDWP thread. Some debuggers get bent out of shape when they can't suspend and
1435 // query all threads, so it's easier if we just don't tell them about this thread.
1436 return;
1437 }
1438 if (thread_group == NULL || t->GetThreadGroup() == thread_group) {
1439 threads.push_back(gRegistry->Add(t->GetPeer()));
1440 }
1441 }
1442
1443 Object* thread_group;
1444 std::vector<JDWP::ObjectId> threads;
1445 };
1446
1447 ThreadListVisitor tlv;
1448 tlv.thread_group = thread_group;
1449
1450 {
1451 ScopedThreadListLock thread_list_lock;
1452 Runtime::Current()->GetThreadList()->ForEach(ThreadListVisitor::Visit, &tlv);
1453 }
1454
1455 *pThreadCount = tlv.threads.size();
1456 if (*pThreadCount == 0) {
1457 *ppThreadIds = NULL;
1458 } else {
1459 *ppThreadIds = new JDWP::ObjectId[*pThreadCount];
1460 for (size_t i = 0; i < *pThreadCount; ++i) {
1461 (*ppThreadIds)[i] = tlv.threads[i];
1462 }
1463 }
1464}
1465
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001466void Dbg::GetThreadGroupThreads(JDWP::ObjectId threadGroupId, JDWP::ObjectId** ppThreadIds, uint32_t* pThreadCount) {
Elliott Hughesa2155262011-11-16 16:26:58 -08001467 GetThreadGroupThreadsImpl(gRegistry->Get<Object*>(threadGroupId), ppThreadIds, pThreadCount);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001468}
1469
1470void Dbg::GetAllThreads(JDWP::ObjectId** ppThreadIds, uint32_t* pThreadCount) {
Elliott Hughesa2155262011-11-16 16:26:58 -08001471 GetThreadGroupThreadsImpl(NULL, ppThreadIds, pThreadCount);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001472}
1473
Elliott Hughes86964332012-02-15 19:37:42 -08001474static int GetStackDepth(Thread* thread) {
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001475 struct CountStackDepthVisitor : public Thread::StackVisitor {
1476 CountStackDepthVisitor() : depth(0) {}
Elliott Hughes530fa002012-03-12 11:44:49 -07001477 bool VisitFrame(const Frame& f, uintptr_t) {
Elliott Hughesf8a2df72011-12-01 12:19:54 -08001478 if (f.HasMethod()) {
1479 ++depth;
1480 }
Elliott Hughes530fa002012-03-12 11:44:49 -07001481 return true;
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001482 }
1483 size_t depth;
1484 };
1485 CountStackDepthVisitor visitor;
Elliott Hughes86964332012-02-15 19:37:42 -08001486 thread->WalkStack(&visitor);
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001487 return visitor.depth;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001488}
1489
Elliott Hughes86964332012-02-15 19:37:42 -08001490int Dbg::GetThreadFrameCount(JDWP::ObjectId threadId) {
1491 ScopedThreadListLock thread_list_lock;
1492 return GetStackDepth(DecodeThread(threadId));
1493}
1494
Elliott Hughes530fa002012-03-12 11:44:49 -07001495void Dbg::GetThreadFrame(JDWP::ObjectId threadId, int desired_frame_number, JDWP::FrameId* pFrameId, JDWP::JdwpLocation* pLoc) {
Elliott Hughes03181a82011-11-17 17:22:21 -08001496 ScopedThreadListLock thread_list_lock;
1497 struct GetFrameVisitor : public Thread::StackVisitor {
1498 GetFrameVisitor(int desired_frame_number, JDWP::FrameId* pFrameId, JDWP::JdwpLocation* pLoc)
Elliott Hughes530fa002012-03-12 11:44:49 -07001499 : depth(0), desired_frame_number(desired_frame_number), pFrameId(pFrameId), pLoc(pLoc) {
Elliott Hughes03181a82011-11-17 17:22:21 -08001500 }
Elliott Hughes530fa002012-03-12 11:44:49 -07001501 bool VisitFrame(const Frame& f, uintptr_t pc) {
Elliott Hughes03181a82011-11-17 17:22:21 -08001502 if (!f.HasMethod()) {
Elliott Hughes530fa002012-03-12 11:44:49 -07001503 return true; // The debugger can't do anything useful with a frame that has no Method*.
Elliott Hughes03181a82011-11-17 17:22:21 -08001504 }
Elliott Hughes03181a82011-11-17 17:22:21 -08001505 if (depth == desired_frame_number) {
1506 *pFrameId = reinterpret_cast<JDWP::FrameId>(f.GetSP());
Elliott Hughesd07986f2011-12-06 18:27:45 -08001507 SetLocation(*pLoc, f.GetMethod(), pc);
Elliott Hughes530fa002012-03-12 11:44:49 -07001508 return false;
Elliott Hughes03181a82011-11-17 17:22:21 -08001509 }
1510 ++depth;
Elliott Hughes530fa002012-03-12 11:44:49 -07001511 return true;
Elliott Hughes03181a82011-11-17 17:22:21 -08001512 }
Elliott Hughes03181a82011-11-17 17:22:21 -08001513 int depth;
1514 int desired_frame_number;
1515 JDWP::FrameId* pFrameId;
1516 JDWP::JdwpLocation* pLoc;
1517 };
1518 GetFrameVisitor visitor(desired_frame_number, pFrameId, pLoc);
1519 visitor.desired_frame_number = desired_frame_number;
1520 DecodeThread(threadId)->WalkStack(&visitor);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001521}
1522
1523JDWP::ObjectId Dbg::GetThreadSelfId() {
Elliott Hughes475fc232011-10-25 15:00:35 -07001524 return gRegistry->Add(Thread::Current()->GetPeer());
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001525}
1526
Elliott Hughes475fc232011-10-25 15:00:35 -07001527void Dbg::SuspendVM() {
Elliott Hughes34e06962012-04-09 13:55:55 -07001528 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 -07001529 Runtime::Current()->GetThreadList()->SuspendAll(true);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001530}
1531
1532void Dbg::ResumeVM() {
Elliott Hughes475fc232011-10-25 15:00:35 -07001533 Runtime::Current()->GetThreadList()->ResumeAll(true);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001534}
1535
1536void Dbg::SuspendThread(JDWP::ObjectId threadId) {
Elliott Hughes4e235312011-12-02 11:34:15 -08001537 Object* peer = gRegistry->Get<Object*>(threadId);
1538 ScopedThreadListLock thread_list_lock;
1539 Thread* thread = Thread::FromManagedThread(peer);
1540 if (thread == NULL) {
1541 LOG(WARNING) << "No such thread for suspend: " << peer;
1542 return;
1543 }
1544 Runtime::Current()->GetThreadList()->Suspend(thread, true);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001545}
1546
1547void Dbg::ResumeThread(JDWP::ObjectId threadId) {
Elliott Hughes4e235312011-12-02 11:34:15 -08001548 Object* peer = gRegistry->Get<Object*>(threadId);
1549 ScopedThreadListLock thread_list_lock;
1550 Thread* thread = Thread::FromManagedThread(peer);
1551 if (thread == NULL) {
1552 LOG(WARNING) << "No such thread for resume: " << peer;
1553 return;
1554 }
1555 Runtime::Current()->GetThreadList()->Resume(thread, true);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001556}
1557
1558void Dbg::SuspendSelf() {
Elliott Hughes475fc232011-10-25 15:00:35 -07001559 Runtime::Current()->GetThreadList()->SuspendSelfForDebugger();
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001560}
1561
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08001562static Object* GetThis(Frame& f) {
Elliott Hughes86b00102011-12-05 17:54:26 -08001563 Method* m = f.GetMethod();
Elliott Hughes86b00102011-12-05 17:54:26 -08001564 Object* o = NULL;
1565 if (!m->IsNative() && !m->IsStatic()) {
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08001566 uint16_t reg = DemangleSlot(0, m);
Elliott Hughes86b00102011-12-05 17:54:26 -08001567 o = reinterpret_cast<Object*>(f.GetVReg(m, reg));
1568 }
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08001569 return o;
1570}
1571
1572void Dbg::GetThisObject(JDWP::FrameId frameId, JDWP::ObjectId* pThisId) {
1573 Method** sp = reinterpret_cast<Method**>(frameId);
1574 Frame f(sp);
1575 Object* o = GetThis(f);
Elliott Hughes86b00102011-12-05 17:54:26 -08001576 *pThisId = gRegistry->Add(o);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001577}
1578
Elliott Hughes1bac54f2012-03-16 12:48:31 -07001579void 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 -08001580 Method** sp = reinterpret_cast<Method**>(frameId);
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08001581 Frame f(sp);
Elliott Hughes68fdbd02011-11-29 19:22:47 -08001582 Method* m = f.GetMethod();
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08001583 uint16_t reg = DemangleSlot(slot, m);
Elliott Hughes68fdbd02011-11-29 19:22:47 -08001584
1585 const VmapTable vmap_table(m->GetVmapTableRaw());
1586 uint32_t vmap_offset;
1587 if (vmap_table.IsInContext(reg, vmap_offset)) {
Elliott Hughes3d30d9b2011-12-07 17:35:48 -08001588 UNIMPLEMENTED(FATAL) << "Don't know how to pull locals from callee save frames: " << vmap_offset;
Elliott Hughes68fdbd02011-11-29 19:22:47 -08001589 }
Elliott Hughesdbb40792011-11-18 17:05:22 -08001590
Elliott Hughesad3da692012-02-24 16:51:35 -08001591 // TODO: check that the tag is compatible with the actual type of the slot!
1592
Elliott Hughesdbb40792011-11-18 17:05:22 -08001593 switch (tag) {
1594 case JDWP::JT_BOOLEAN:
1595 {
Elliott Hughescccd84f2011-12-05 16:51:54 -08001596 CHECK_EQ(width, 1U);
Elliott Hughes1bba14f2011-12-01 18:00:36 -08001597 uint32_t intVal = f.GetVReg(m, reg);
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08001598 VLOG(jdwp) << "get boolean local " << reg << " = " << intVal;
Elliott Hughesdbb40792011-11-18 17:05:22 -08001599 JDWP::Set1(buf+1, intVal != 0);
1600 }
1601 break;
1602 case JDWP::JT_BYTE:
1603 {
Elliott Hughescccd84f2011-12-05 16:51:54 -08001604 CHECK_EQ(width, 1U);
Elliott Hughes1bba14f2011-12-01 18:00:36 -08001605 uint32_t intVal = f.GetVReg(m, reg);
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08001606 VLOG(jdwp) << "get byte local " << reg << " = " << intVal;
Elliott Hughesdbb40792011-11-18 17:05:22 -08001607 JDWP::Set1(buf+1, intVal);
1608 }
1609 break;
1610 case JDWP::JT_SHORT:
1611 case JDWP::JT_CHAR:
1612 {
Elliott Hughescccd84f2011-12-05 16:51:54 -08001613 CHECK_EQ(width, 2U);
Elliott Hughes1bba14f2011-12-01 18:00:36 -08001614 uint32_t intVal = f.GetVReg(m, reg);
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08001615 VLOG(jdwp) << "get short/char local " << reg << " = " << intVal;
Elliott Hughesdbb40792011-11-18 17:05:22 -08001616 JDWP::Set2BE(buf+1, intVal);
1617 }
1618 break;
1619 case JDWP::JT_INT:
1620 case JDWP::JT_FLOAT:
1621 {
Elliott Hughescccd84f2011-12-05 16:51:54 -08001622 CHECK_EQ(width, 4U);
Elliott Hughes1bba14f2011-12-01 18:00:36 -08001623 uint32_t intVal = f.GetVReg(m, reg);
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08001624 VLOG(jdwp) << "get int/float local " << reg << " = " << intVal;
Elliott Hughesdbb40792011-11-18 17:05:22 -08001625 JDWP::Set4BE(buf+1, intVal);
1626 }
1627 break;
1628 case JDWP::JT_ARRAY:
1629 {
Elliott Hughescccd84f2011-12-05 16:51:54 -08001630 CHECK_EQ(width, sizeof(JDWP::ObjectId));
Elliott Hughes68fdbd02011-11-29 19:22:47 -08001631 Object* o = reinterpret_cast<Object*>(f.GetVReg(m, reg));
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08001632 VLOG(jdwp) << "get array local " << reg << " = " << o;
Elliott Hughes88c5c352012-03-15 18:49:48 -07001633 if (!Runtime::Current()->GetHeap()->IsHeapAddress(o)) {
Elliott Hughes3d30d9b2011-12-07 17:35:48 -08001634 LOG(FATAL) << "Register " << reg << " expected to hold array: " << o;
Elliott Hughesdbb40792011-11-18 17:05:22 -08001635 }
1636 JDWP::SetObjectId(buf+1, gRegistry->Add(o));
1637 }
1638 break;
Elliott Hughesad3da692012-02-24 16:51:35 -08001639 case JDWP::JT_CLASS_LOADER:
1640 case JDWP::JT_CLASS_OBJECT:
Elliott Hughesdbb40792011-11-18 17:05:22 -08001641 case JDWP::JT_OBJECT:
Elliott Hughesad3da692012-02-24 16:51:35 -08001642 case JDWP::JT_STRING:
1643 case JDWP::JT_THREAD:
1644 case JDWP::JT_THREAD_GROUP:
Elliott Hughesdbb40792011-11-18 17:05:22 -08001645 {
Elliott Hughescccd84f2011-12-05 16:51:54 -08001646 CHECK_EQ(width, sizeof(JDWP::ObjectId));
Elliott Hughes68fdbd02011-11-29 19:22:47 -08001647 Object* o = reinterpret_cast<Object*>(f.GetVReg(m, reg));
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08001648 VLOG(jdwp) << "get object local " << reg << " = " << o;
Elliott Hughes88c5c352012-03-15 18:49:48 -07001649 if (!Runtime::Current()->GetHeap()->IsHeapAddress(o)) {
Elliott Hughes3d30d9b2011-12-07 17:35:48 -08001650 LOG(FATAL) << "Register " << reg << " expected to hold object: " << o;
Elliott Hughesdbb40792011-11-18 17:05:22 -08001651 }
1652 tag = TagFromObject(o);
1653 JDWP::SetObjectId(buf+1, gRegistry->Add(o));
1654 }
1655 break;
1656 case JDWP::JT_DOUBLE:
1657 case JDWP::JT_LONG:
1658 {
Elliott Hughescccd84f2011-12-05 16:51:54 -08001659 CHECK_EQ(width, 8U);
Elliott Hughes1bba14f2011-12-01 18:00:36 -08001660 uint32_t lo = f.GetVReg(m, reg);
1661 uint64_t hi = f.GetVReg(m, reg + 1);
1662 uint64_t longVal = (hi << 32) | lo;
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08001663 VLOG(jdwp) << "get double/long local " << hi << ":" << lo << " = " << longVal;
Elliott Hughesdbb40792011-11-18 17:05:22 -08001664 JDWP::Set8BE(buf+1, longVal);
1665 }
1666 break;
1667 default:
Elliott Hughes3d30d9b2011-12-07 17:35:48 -08001668 LOG(FATAL) << "Unknown tag " << tag;
Elliott Hughesdbb40792011-11-18 17:05:22 -08001669 break;
1670 }
1671
1672 // Prepend tag, which may have been updated.
1673 JDWP::Set1(buf, tag);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001674}
1675
Elliott Hughes1bac54f2012-03-16 12:48:31 -07001676void 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 -08001677 Method** sp = reinterpret_cast<Method**>(frameId);
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08001678 Frame f(sp);
Elliott Hughescccd84f2011-12-05 16:51:54 -08001679 Method* m = f.GetMethod();
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08001680 uint16_t reg = DemangleSlot(slot, m);
Elliott Hughescccd84f2011-12-05 16:51:54 -08001681
1682 const VmapTable vmap_table(m->GetVmapTableRaw());
1683 uint32_t vmap_offset;
1684 if (vmap_table.IsInContext(reg, vmap_offset)) {
Elliott Hughes3d30d9b2011-12-07 17:35:48 -08001685 UNIMPLEMENTED(FATAL) << "Don't know how to pull locals from callee save frames: " << vmap_offset;
Elliott Hughescccd84f2011-12-05 16:51:54 -08001686 }
1687
Elliott Hughesad3da692012-02-24 16:51:35 -08001688 // TODO: check that the tag is compatible with the actual type of the slot!
1689
Elliott Hughescccd84f2011-12-05 16:51:54 -08001690 switch (tag) {
1691 case JDWP::JT_BOOLEAN:
1692 case JDWP::JT_BYTE:
1693 CHECK_EQ(width, 1U);
1694 f.SetVReg(m, reg, static_cast<uint32_t>(value));
1695 break;
1696 case JDWP::JT_SHORT:
1697 case JDWP::JT_CHAR:
1698 CHECK_EQ(width, 2U);
1699 f.SetVReg(m, reg, static_cast<uint32_t>(value));
1700 break;
1701 case JDWP::JT_INT:
1702 case JDWP::JT_FLOAT:
1703 CHECK_EQ(width, 4U);
1704 f.SetVReg(m, reg, static_cast<uint32_t>(value));
1705 break;
1706 case JDWP::JT_ARRAY:
1707 case JDWP::JT_OBJECT:
1708 case JDWP::JT_STRING:
1709 {
1710 CHECK_EQ(width, sizeof(JDWP::ObjectId));
1711 Object* o = gRegistry->Get<Object*>(static_cast<JDWP::ObjectId>(value));
Elliott Hughesad3da692012-02-24 16:51:35 -08001712 if (o == kInvalidObject) {
1713 UNIMPLEMENTED(FATAL) << "return an error code when given an invalid object to store";
1714 }
Elliott Hughescccd84f2011-12-05 16:51:54 -08001715 f.SetVReg(m, reg, static_cast<uint32_t>(reinterpret_cast<uintptr_t>(o)));
1716 }
1717 break;
1718 case JDWP::JT_DOUBLE:
1719 case JDWP::JT_LONG:
1720 CHECK_EQ(width, 8U);
1721 f.SetVReg(m, reg, static_cast<uint32_t>(value));
1722 f.SetVReg(m, reg + 1, static_cast<uint32_t>(value >> 32));
1723 break;
1724 default:
Elliott Hughes3d30d9b2011-12-07 17:35:48 -08001725 LOG(FATAL) << "Unknown tag " << tag;
Elliott Hughescccd84f2011-12-05 16:51:54 -08001726 break;
1727 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001728}
1729
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08001730void Dbg::PostLocationEvent(const Method* m, int dex_pc, Object* this_object, int event_flags) {
1731 Class* c = m->GetDeclaringClass();
1732
1733 JDWP::JdwpLocation location;
1734 location.typeTag = c->IsInterface() ? JDWP::TT_INTERFACE : JDWP::TT_CLASS;
1735 location.classId = gRegistry->Add(c);
1736 location.methodId = ToMethodId(m);
Elliott Hughes972a47b2012-02-21 18:16:06 -08001737 location.dex_pc = m->IsNative() ? -1 : dex_pc;
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08001738
1739 // Note we use "NoReg" so we don't keep track of references that are
1740 // never actually sent to the debugger. 'this_id' is only used to
1741 // compare against registered events...
1742 JDWP::ObjectId this_id = static_cast<JDWP::ObjectId>(reinterpret_cast<uintptr_t>(this_object));
1743 if (gJdwpState->PostLocationEvent(&location, this_id, event_flags)) {
1744 // ...unless there's a registered event, in which case we
1745 // need to really track the class and 'this'.
1746 gRegistry->Add(c);
1747 gRegistry->Add(this_object);
1748 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001749}
1750
Elliott Hughesd07986f2011-12-06 18:27:45 -08001751void Dbg::PostException(Method** sp, Method* throwMethod, uintptr_t throwNativePc, Method* catchMethod, uintptr_t catchNativePc, Object* exception) {
Elliott Hughesc0f09332012-03-26 13:27:06 -07001752 if (!IsDebuggerActive()) {
Ian Rogers0ad5bb82011-12-07 10:16:32 -08001753 return;
1754 }
Elliott Hughes4740cdf2011-12-07 14:07:12 -08001755
Elliott Hughesd07986f2011-12-06 18:27:45 -08001756 JDWP::JdwpLocation throw_location;
1757 SetLocation(throw_location, throwMethod, throwNativePc);
1758 JDWP::JdwpLocation catch_location;
1759 SetLocation(catch_location, catchMethod, catchNativePc);
1760
1761 // We need 'this' for InstanceOnly filters.
1762 JDWP::ObjectId this_id;
1763 GetThisObject(reinterpret_cast<JDWP::FrameId>(sp), &this_id);
1764
1765 /*
1766 * Hand the event to the JDWP exception handler. Note we're using the
1767 * "NoReg" objectID on the exception, which is not strictly correct --
1768 * the exception object WILL be passed up to the debugger if the
1769 * debugger is interested in the event. We do this because the current
1770 * implementation of the debugger object registry never throws anything
1771 * away, and some people were experiencing a fatal build up of exception
1772 * objects when dealing with certain libraries.
1773 */
1774 JDWP::ObjectId exception_id = static_cast<JDWP::ObjectId>(reinterpret_cast<uintptr_t>(exception));
1775 JDWP::RefTypeId exception_class_id = gRegistry->Add(exception->GetClass());
1776
1777 gJdwpState->PostException(&throw_location, exception_id, exception_class_id, &catch_location, this_id);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001778}
1779
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001780void Dbg::PostClassPrepare(Class* c) {
Elliott Hughesc0f09332012-03-26 13:27:06 -07001781 if (!IsDebuggerActive()) {
Elliott Hughes4740cdf2011-12-07 14:07:12 -08001782 return;
1783 }
1784
Elliott Hughes3d30d9b2011-12-07 17:35:48 -08001785 // OLD-TODO - we currently always send both "verified" and "prepared" since
Elliott Hughes4740cdf2011-12-07 14:07:12 -08001786 // debuggers seem to like that. There might be some advantage to honesty,
1787 // since the class may not yet be verified.
1788 int state = JDWP::CS_VERIFIED | JDWP::CS_PREPARED;
1789 JDWP::JdwpTypeTag tag = c->IsInterface() ? JDWP::TT_INTERFACE : JDWP::TT_CLASS;
1790 gJdwpState->PostClassPrepare(tag, gRegistry->Add(c), ClassHelper(c).GetDescriptor(), state);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001791}
1792
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08001793void Dbg::UpdateDebugger(int32_t dex_pc, Thread* self, Method** sp) {
Elliott Hughesc0f09332012-03-26 13:27:06 -07001794 if (!IsDebuggerActive() || dex_pc == -2 /* fake method exit */) {
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08001795 return;
1796 }
1797
Elliott Hughes86964332012-02-15 19:37:42 -08001798 Frame f(sp);
1799 f.Next(); // Skip callee save frame.
1800 Method* m = f.GetMethod();
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08001801
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08001802 if (dex_pc == -1) {
Elliott Hughes2aa2e392012-02-17 17:15:43 -08001803 // We use a pc of -1 to represent method entry, since we might branch back to pc 0 later.
1804 // This means that for this special notification, there can't be anything else interesting
1805 // going on, so we're done already.
1806 Dbg::PostLocationEvent(m, 0, GetThis(f), kMethodEntry);
1807 return;
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08001808 }
1809
Elliott Hughes2aa2e392012-02-17 17:15:43 -08001810 int event_flags = 0;
1811
Elliott Hughes86964332012-02-15 19:37:42 -08001812 if (IsBreakpoint(m, dex_pc)) {
1813 event_flags |= kBreakpoint;
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08001814 }
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08001815
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08001816 // If the debugger is single-stepping one of our threads, check to
1817 // see if we're that thread and we've reached a step point.
Elliott Hughes86964332012-02-15 19:37:42 -08001818 if (gSingleStepControl.is_active && gSingleStepControl.thread == self) {
1819 CHECK(!m->IsNative());
1820 if (gSingleStepControl.step_depth == JDWP::SD_INTO) {
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08001821 // Step into method calls. We break when the line number
1822 // or method pointer changes. If we're in SS_MIN mode, we
1823 // always stop.
Elliott Hughes86964332012-02-15 19:37:42 -08001824 if (gSingleStepControl.method != m) {
1825 event_flags |= kSingleStep;
1826 VLOG(jdwp) << "SS new method";
1827 } else if (gSingleStepControl.step_size == JDWP::SS_MIN) {
1828 event_flags |= kSingleStep;
1829 VLOG(jdwp) << "SS new instruction";
Elliott Hughes2435a572012-02-17 16:07:41 -08001830 } else if (gSingleStepControl.dex_pcs.find(dex_pc) == gSingleStepControl.dex_pcs.end()) {
1831 event_flags |= kSingleStep;
1832 VLOG(jdwp) << "SS new line";
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08001833 }
Elliott Hughes86964332012-02-15 19:37:42 -08001834 } else if (gSingleStepControl.step_depth == JDWP::SD_OVER) {
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08001835 // Step over method calls. We break when the line number is
1836 // different and the frame depth is <= the original frame
1837 // depth. (We can't just compare on the method, because we
1838 // might get unrolled past it by an exception, and it's tricky
1839 // to identify recursion.)
Elliott Hughes86964332012-02-15 19:37:42 -08001840
1841 // TODO: can we just use the value of 'sp'?
1842 int stack_depth = GetStackDepth(self);
1843
1844 if (stack_depth < gSingleStepControl.stack_depth) {
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08001845 // popped up one or more frames, always trigger
Elliott Hughes86964332012-02-15 19:37:42 -08001846 event_flags |= kSingleStep;
1847 VLOG(jdwp) << "SS method pop";
1848 } else if (stack_depth == gSingleStepControl.stack_depth) {
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08001849 // same depth, see if we moved
Elliott Hughes86964332012-02-15 19:37:42 -08001850 if (gSingleStepControl.step_size == JDWP::SS_MIN) {
1851 event_flags |= kSingleStep;
1852 VLOG(jdwp) << "SS new instruction";
Elliott Hughes2435a572012-02-17 16:07:41 -08001853 } else if (gSingleStepControl.dex_pcs.find(dex_pc) == gSingleStepControl.dex_pcs.end()) {
1854 event_flags |= kSingleStep;
1855 VLOG(jdwp) << "SS new line";
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08001856 }
1857 }
1858 } else {
Elliott Hughes86964332012-02-15 19:37:42 -08001859 CHECK_EQ(gSingleStepControl.step_depth, JDWP::SD_OUT);
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08001860 // Return from the current method. We break when the frame
1861 // depth pops up.
1862
1863 // This differs from the "method exit" break in that it stops
1864 // with the PC at the next instruction in the returned-to
1865 // function, rather than the end of the returning function.
Elliott Hughes86964332012-02-15 19:37:42 -08001866
1867 // TODO: can we just use the value of 'sp'?
1868 int stack_depth = GetStackDepth(self);
1869 if (stack_depth < gSingleStepControl.stack_depth) {
1870 event_flags |= kSingleStep;
1871 VLOG(jdwp) << "SS method pop";
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08001872 }
1873 }
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08001874 }
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08001875
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08001876 // Check to see if this is a "return" instruction. JDWP says we should
1877 // send the event *after* the code has been executed, but it also says
1878 // the location we provide is the last instruction. Since the "return"
1879 // instruction has no interesting side effects, we should be safe.
1880 // (We can't just move this down to the returnFromMethod label because
1881 // we potentially need to combine it with other events.)
1882 // We're also not supposed to generate a method exit event if the method
1883 // terminates "with a thrown exception".
Elliott Hughes86964332012-02-15 19:37:42 -08001884 if (dex_pc >= 0) {
1885 const DexFile::CodeItem* code_item = MethodHelper(m).GetCodeItem();
1886 CHECK(code_item != NULL);
1887 CHECK_LT(dex_pc, static_cast<int32_t>(code_item->insns_size_in_code_units_));
1888 if (Instruction::At(&code_item->insns_[dex_pc])->IsReturn()) {
1889 event_flags |= kMethodExit;
1890 }
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08001891 }
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08001892
1893 // If there's something interesting going on, see if it matches one
1894 // of the debugger filters.
1895 if (event_flags != 0) {
Elliott Hughes86964332012-02-15 19:37:42 -08001896 Dbg::PostLocationEvent(m, dex_pc, GetThis(f), event_flags);
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08001897 }
1898}
1899
Elliott Hughes86964332012-02-15 19:37:42 -08001900void Dbg::WatchLocation(const JDWP::JdwpLocation* location) {
1901 MutexLock mu(gBreakpointsLock);
1902 Method* m = FromMethodId(location->methodId);
Elliott Hughes972a47b2012-02-21 18:16:06 -08001903 gBreakpoints.push_back(Breakpoint(m, location->dex_pc));
Elliott Hughes86964332012-02-15 19:37:42 -08001904 VLOG(jdwp) << "Set breakpoint #" << (gBreakpoints.size() - 1) << ": " << gBreakpoints[gBreakpoints.size() - 1];
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001905}
1906
Elliott Hughes86964332012-02-15 19:37:42 -08001907void Dbg::UnwatchLocation(const JDWP::JdwpLocation* location) {
1908 MutexLock mu(gBreakpointsLock);
1909 Method* m = FromMethodId(location->methodId);
1910 for (size_t i = 0; i < gBreakpoints.size(); ++i) {
Elliott Hughes972a47b2012-02-21 18:16:06 -08001911 if (gBreakpoints[i].method == m && gBreakpoints[i].dex_pc == location->dex_pc) {
Elliott Hughes86964332012-02-15 19:37:42 -08001912 VLOG(jdwp) << "Removed breakpoint #" << i << ": " << gBreakpoints[i];
1913 gBreakpoints.erase(gBreakpoints.begin() + i);
1914 return;
1915 }
1916 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001917}
1918
Elliott Hughes2435a572012-02-17 16:07:41 -08001919JDWP::JdwpError Dbg::ConfigureStep(JDWP::ObjectId threadId, JDWP::JdwpStepSize step_size, JDWP::JdwpStepDepth step_depth) {
Elliott Hughes86964332012-02-15 19:37:42 -08001920 Thread* thread = DecodeThread(threadId);
Elliott Hughes2435a572012-02-17 16:07:41 -08001921 if (thread == NULL) {
1922 return JDWP::ERR_INVALID_THREAD;
1923 }
Elliott Hughes86964332012-02-15 19:37:42 -08001924
1925 // TODO: there's no theoretical reason why we couldn't support single-stepping
1926 // of multiple threads at once, but we never did so historically.
1927 if (gSingleStepControl.thread != NULL && thread != gSingleStepControl.thread) {
1928 LOG(WARNING) << "single-step already active for " << *gSingleStepControl.thread
1929 << "; switching to " << *thread;
1930 }
1931
Elliott Hughes2435a572012-02-17 16:07:41 -08001932 //
1933 // Work out what Method* we're in, the current line number, and how deep the stack currently
1934 // is for step-out.
1935 //
1936
Elliott Hughes86964332012-02-15 19:37:42 -08001937 struct SingleStepStackVisitor : public Thread::StackVisitor {
1938 SingleStepStackVisitor() {
1939 gSingleStepControl.method = NULL;
1940 gSingleStepControl.stack_depth = 0;
1941 }
Elliott Hughes530fa002012-03-12 11:44:49 -07001942 bool VisitFrame(const Frame& f, uintptr_t pc) {
Elliott Hughes86964332012-02-15 19:37:42 -08001943 if (f.HasMethod()) {
1944 ++gSingleStepControl.stack_depth;
1945 if (gSingleStepControl.method == NULL) {
Elliott Hughes2435a572012-02-17 16:07:41 -08001946 const Method* m = f.GetMethod();
1947 const DexCache* dex_cache = m->GetDeclaringClass()->GetDexCache();
1948 gSingleStepControl.method = m;
1949 gSingleStepControl.line_number = -1;
1950 if (dex_cache != NULL) {
1951 const DexFile& dex_file = Runtime::Current()->GetClassLinker()->FindDexFile(dex_cache);
1952 gSingleStepControl.line_number = dex_file.GetLineNumFromPC(m, m->ToDexPC(pc));
1953 }
Elliott Hughes86964332012-02-15 19:37:42 -08001954 }
1955 }
Elliott Hughes530fa002012-03-12 11:44:49 -07001956 return true;
Elliott Hughes86964332012-02-15 19:37:42 -08001957 }
1958 };
1959 SingleStepStackVisitor visitor;
1960 thread->WalkStack(&visitor);
1961
Elliott Hughes2435a572012-02-17 16:07:41 -08001962 //
1963 // Find the dex_pc values that correspond to the current line, for line-based single-stepping.
1964 //
1965
1966 struct DebugCallbackContext {
1967 DebugCallbackContext() {
1968 last_pc_valid = false;
1969 last_pc = 0;
Elliott Hughes2435a572012-02-17 16:07:41 -08001970 }
1971
1972 static bool Callback(void* raw_context, uint32_t address, uint32_t line_number) {
1973 DebugCallbackContext* context = reinterpret_cast<DebugCallbackContext*>(raw_context);
1974 if (static_cast<int32_t>(line_number) == gSingleStepControl.line_number) {
1975 if (!context->last_pc_valid) {
1976 // Everything from this address until the next line change is ours.
1977 context->last_pc = address;
1978 context->last_pc_valid = true;
1979 }
1980 // Otherwise, if we're already in a valid range for this line,
1981 // just keep going (shouldn't really happen)...
1982 } else if (context->last_pc_valid) { // and the line number is new
1983 // Add everything from the last entry up until here to the set
1984 for (uint32_t dex_pc = context->last_pc; dex_pc < address; ++dex_pc) {
1985 gSingleStepControl.dex_pcs.insert(dex_pc);
1986 }
1987 context->last_pc_valid = false;
1988 }
1989 return false; // There may be multiple entries for any given line.
1990 }
1991
1992 ~DebugCallbackContext() {
1993 // If the line number was the last in the position table...
1994 if (last_pc_valid) {
1995 size_t end = MethodHelper(gSingleStepControl.method).GetCodeItem()->insns_size_in_code_units_;
1996 for (uint32_t dex_pc = last_pc; dex_pc < end; ++dex_pc) {
1997 gSingleStepControl.dex_pcs.insert(dex_pc);
1998 }
1999 }
2000 }
2001
2002 bool last_pc_valid;
2003 uint32_t last_pc;
2004 };
Elliott Hughes3e2e1a22012-02-21 11:33:41 -08002005 gSingleStepControl.dex_pcs.clear();
Elliott Hughes2435a572012-02-17 16:07:41 -08002006 const Method* m = gSingleStepControl.method;
Elliott Hughes3e2e1a22012-02-21 11:33:41 -08002007 if (m->IsNative()) {
2008 gSingleStepControl.line_number = -1;
2009 } else {
2010 DebugCallbackContext context;
2011 MethodHelper mh(m);
2012 mh.GetDexFile().DecodeDebugInfo(mh.GetCodeItem(), m->IsStatic(), m->GetDexMethodIndex(),
2013 DebugCallbackContext::Callback, NULL, &context);
2014 }
Elliott Hughes2435a572012-02-17 16:07:41 -08002015
2016 //
2017 // Everything else...
2018 //
2019
Elliott Hughes86964332012-02-15 19:37:42 -08002020 gSingleStepControl.thread = thread;
2021 gSingleStepControl.step_size = step_size;
2022 gSingleStepControl.step_depth = step_depth;
2023 gSingleStepControl.is_active = true;
2024
Elliott Hughes2435a572012-02-17 16:07:41 -08002025 if (VLOG_IS_ON(jdwp)) {
2026 VLOG(jdwp) << "Single-step thread: " << *gSingleStepControl.thread;
2027 VLOG(jdwp) << "Single-step step size: " << gSingleStepControl.step_size;
2028 VLOG(jdwp) << "Single-step step depth: " << gSingleStepControl.step_depth;
2029 VLOG(jdwp) << "Single-step current method: " << PrettyMethod(gSingleStepControl.method);
2030 VLOG(jdwp) << "Single-step current line: " << gSingleStepControl.line_number;
2031 VLOG(jdwp) << "Single-step current stack depth: " << gSingleStepControl.stack_depth;
2032 VLOG(jdwp) << "Single-step dex_pc values:";
2033 for (std::set<uint32_t>::iterator it = gSingleStepControl.dex_pcs.begin() ; it != gSingleStepControl.dex_pcs.end(); ++it) {
Elliott Hughes229feb72012-02-23 13:33:29 -08002034 VLOG(jdwp) << StringPrintf(" %#x", *it);
Elliott Hughes2435a572012-02-17 16:07:41 -08002035 }
2036 }
2037
2038 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002039}
2040
Elliott Hughes1bac54f2012-03-16 12:48:31 -07002041void Dbg::UnconfigureStep(JDWP::ObjectId /*threadId*/) {
Elliott Hughes86964332012-02-15 19:37:42 -08002042 gSingleStepControl.is_active = false;
2043 gSingleStepControl.thread = NULL;
Elliott Hughes2435a572012-02-17 16:07:41 -08002044 gSingleStepControl.dex_pcs.clear();
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002045}
2046
Elliott Hughes45651fd2012-02-21 15:48:20 -08002047static char JdwpTagToShortyChar(JDWP::JdwpTag tag) {
2048 switch (tag) {
2049 default:
2050 LOG(FATAL) << "unknown JDWP tag: " << PrintableChar(tag);
2051
2052 // Primitives.
2053 case JDWP::JT_BYTE: return 'B';
2054 case JDWP::JT_CHAR: return 'C';
2055 case JDWP::JT_FLOAT: return 'F';
2056 case JDWP::JT_DOUBLE: return 'D';
2057 case JDWP::JT_INT: return 'I';
2058 case JDWP::JT_LONG: return 'J';
2059 case JDWP::JT_SHORT: return 'S';
2060 case JDWP::JT_VOID: return 'V';
2061 case JDWP::JT_BOOLEAN: return 'Z';
2062
2063 // Reference types.
2064 case JDWP::JT_ARRAY:
2065 case JDWP::JT_OBJECT:
2066 case JDWP::JT_STRING:
2067 case JDWP::JT_THREAD:
2068 case JDWP::JT_THREAD_GROUP:
2069 case JDWP::JT_CLASS_LOADER:
2070 case JDWP::JT_CLASS_OBJECT:
2071 return 'L';
2072 }
2073}
2074
2075JDWP::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 -08002076 ThreadList* thread_list = Runtime::Current()->GetThreadList();
2077
2078 Thread* targetThread = NULL;
2079 DebugInvokeReq* req = NULL;
2080 {
2081 ScopedThreadListLock thread_list_lock;
2082 targetThread = DecodeThread(threadId);
2083 if (targetThread == NULL) {
2084 LOG(ERROR) << "InvokeMethod request for non-existent thread " << threadId;
2085 return JDWP::ERR_INVALID_THREAD;
2086 }
2087 req = targetThread->GetInvokeReq();
2088 if (!req->ready) {
2089 LOG(ERROR) << "InvokeMethod request for thread not stopped by event: " << *targetThread;
2090 return JDWP::ERR_INVALID_THREAD;
2091 }
2092
2093 /*
2094 * We currently have a bug where we don't successfully resume the
2095 * target thread if the suspend count is too deep. We're expected to
2096 * require one "resume" for each "suspend", but when asked to execute
2097 * a method we have to resume fully and then re-suspend it back to the
2098 * same level. (The easiest way to cause this is to type "suspend"
2099 * multiple times in jdb.)
2100 *
2101 * It's unclear what this means when the event specifies "resume all"
2102 * and some threads are suspended more deeply than others. This is
2103 * a rare problem, so for now we just prevent it from hanging forever
2104 * by rejecting the method invocation request. Without this, we will
2105 * be stuck waiting on a suspended thread.
2106 */
2107 int suspend_count = targetThread->GetSuspendCount();
2108 if (suspend_count > 1) {
2109 LOG(ERROR) << *targetThread << " suspend count too deep for method invocation: " << suspend_count;
2110 return JDWP::ERR_THREAD_SUSPENDED; // Probably not expected here.
2111 }
2112
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08002113 JDWP::JdwpError status;
Elliott Hughes45651fd2012-02-21 15:48:20 -08002114 Object* receiver = gRegistry->Get<Object*>(objectId);
2115 if (receiver == kInvalidObject) {
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08002116 return JDWP::ERR_INVALID_OBJECT;
2117 }
Elliott Hughes45651fd2012-02-21 15:48:20 -08002118
2119 Object* thread = gRegistry->Get<Object*>(threadId);
2120 if (thread == kInvalidObject) {
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08002121 return JDWP::ERR_INVALID_OBJECT;
2122 }
Elliott Hughes45651fd2012-02-21 15:48:20 -08002123 // TODO: check that 'thread' is actually a java.lang.Thread!
2124
2125 Class* c = DecodeClass(classId, status);
2126 if (c == NULL) {
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08002127 return status;
2128 }
Elliott Hughes45651fd2012-02-21 15:48:20 -08002129
2130 Method* m = FromMethodId(methodId);
2131 if (m->IsStatic() != (receiver == NULL)) {
2132 return JDWP::ERR_INVALID_METHODID;
2133 }
2134 if (m->IsStatic()) {
2135 if (m->GetDeclaringClass() != c) {
2136 return JDWP::ERR_INVALID_METHODID;
2137 }
2138 } else {
2139 if (!m->GetDeclaringClass()->IsAssignableFrom(c)) {
2140 return JDWP::ERR_INVALID_METHODID;
2141 }
2142 }
2143
2144 // Check the argument list matches the method.
2145 MethodHelper mh(m);
2146 if (mh.GetShortyLength() - 1 != arg_count) {
2147 return JDWP::ERR_ILLEGAL_ARGUMENT;
2148 }
2149 const char* shorty = mh.GetShorty();
2150 for (size_t i = 0; i < arg_count; ++i) {
2151 if (shorty[i + 1] != JdwpTagToShortyChar(arg_types[i])) {
2152 return JDWP::ERR_ILLEGAL_ARGUMENT;
2153 }
2154 }
2155
2156 req->receiver_ = receiver;
2157 req->thread_ = thread;
2158 req->class_ = c;
2159 req->method_ = m;
2160 req->arg_count_ = arg_count;
2161 req->arg_values_ = arg_values;
Elliott Hughesd07986f2011-12-06 18:27:45 -08002162 req->options_ = options;
2163 req->invoke_needed_ = true;
2164 }
2165
2166 // The fact that we've released the thread list lock is a bit risky --- if the thread goes
2167 // away we're sitting high and dry -- but we must release this before the ResumeAllThreads
2168 // call, and it's unwise to hold it during WaitForSuspend.
2169
2170 {
2171 /*
2172 * We change our (JDWP thread) status, which should be THREAD_RUNNING,
Elliott Hughes81ff3182012-03-23 20:35:56 -07002173 * so we can suspend for a GC if the invoke request causes us to
Elliott Hughesd07986f2011-12-06 18:27:45 -08002174 * run out of memory. It's also a good idea to change it before locking
2175 * the invokeReq mutex, although that should never be held for long.
2176 */
Elliott Hughes34e06962012-04-09 13:55:55 -07002177 ScopedThreadStateChange tsc(Thread::Current(), kVmWait);
Elliott Hughesd07986f2011-12-06 18:27:45 -08002178
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08002179 VLOG(jdwp) << " Transferring control to event thread";
Elliott Hughesd07986f2011-12-06 18:27:45 -08002180 {
2181 MutexLock mu(req->lock_);
2182
2183 if ((options & JDWP::INVOKE_SINGLE_THREADED) == 0) {
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08002184 VLOG(jdwp) << " Resuming all threads";
Elliott Hughesd07986f2011-12-06 18:27:45 -08002185 thread_list->ResumeAll(true);
2186 } else {
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08002187 VLOG(jdwp) << " Resuming event thread only";
Elliott Hughesd07986f2011-12-06 18:27:45 -08002188 thread_list->Resume(targetThread, true);
2189 }
2190
2191 // Wait for the request to finish executing.
2192 while (req->invoke_needed_) {
2193 req->cond_.Wait(req->lock_);
2194 }
2195 }
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08002196 VLOG(jdwp) << " Control has returned from event thread";
Elliott Hughesd07986f2011-12-06 18:27:45 -08002197
2198 /* wait for thread to re-suspend itself */
2199 targetThread->WaitUntilSuspended();
2200 //dvmWaitForSuspend(targetThread);
2201 }
2202
2203 /*
2204 * Suspend the threads. We waited for the target thread to suspend
2205 * itself, so all we need to do is suspend the others.
2206 *
2207 * The suspendAllThreads() call will double-suspend the event thread,
2208 * so we want to resume the target thread once to keep the books straight.
2209 */
2210 if ((options & JDWP::INVOKE_SINGLE_THREADED) == 0) {
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08002211 VLOG(jdwp) << " Suspending all threads";
Elliott Hughesd07986f2011-12-06 18:27:45 -08002212 thread_list->SuspendAll(true);
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08002213 VLOG(jdwp) << " Resuming event thread to balance the count";
Elliott Hughesd07986f2011-12-06 18:27:45 -08002214 thread_list->Resume(targetThread, true);
2215 }
2216
2217 // Copy the result.
2218 *pResultTag = req->result_tag;
2219 if (IsPrimitiveTag(req->result_tag)) {
Elliott Hughesf24d3ce2012-04-11 17:43:37 -07002220 *pResultValue = req->result_value.GetJ();
Elliott Hughesd07986f2011-12-06 18:27:45 -08002221 } else {
Elliott Hughesf24d3ce2012-04-11 17:43:37 -07002222 *pResultValue = gRegistry->Add(req->result_value.GetL());
Elliott Hughesd07986f2011-12-06 18:27:45 -08002223 }
2224 *pExceptionId = req->exception;
2225 return req->error;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002226}
2227
2228void Dbg::ExecuteMethod(DebugInvokeReq* pReq) {
Elliott Hughesd07986f2011-12-06 18:27:45 -08002229 Thread* self = Thread::Current();
2230
Elliott Hughes81ff3182012-03-23 20:35:56 -07002231 // We can be called while an exception is pending. We need
Elliott Hughesd07986f2011-12-06 18:27:45 -08002232 // to preserve that across the method invocation.
2233 SirtRef<Throwable> old_exception(self->GetException());
2234 self->ClearException();
2235
Elliott Hughes34e06962012-04-09 13:55:55 -07002236 ScopedThreadStateChange tsc(self, kRunnable);
Elliott Hughesd07986f2011-12-06 18:27:45 -08002237
2238 // Translate the method through the vtable, unless the debugger wants to suppress it.
2239 Method* m = pReq->method_;
2240 if ((pReq->options_ & JDWP::INVOKE_NONVIRTUAL) == 0 && pReq->receiver_ != NULL) {
Elliott Hughes45651fd2012-02-21 15:48:20 -08002241 Method* actual_method = pReq->class_->FindVirtualMethodForVirtualOrInterface(pReq->method_);
2242 if (actual_method != m) {
2243 VLOG(jdwp) << "ExecuteMethod translated " << PrettyMethod(m) << " to " << PrettyMethod(actual_method);
2244 m = actual_method;
2245 }
Elliott Hughesd07986f2011-12-06 18:27:45 -08002246 }
Elliott Hughes45651fd2012-02-21 15:48:20 -08002247 VLOG(jdwp) << "ExecuteMethod " << PrettyMethod(m);
Elliott Hughesd07986f2011-12-06 18:27:45 -08002248 CHECK(m != NULL);
2249
2250 CHECK_EQ(sizeof(jvalue), sizeof(uint64_t));
2251
Elliott Hughes45651fd2012-02-21 15:48:20 -08002252 LOG(INFO) << "self=" << self << " pReq->receiver_=" << pReq->receiver_ << " m=" << m << " #" << pReq->arg_count_ << " " << pReq->arg_values_;
2253 pReq->result_value = InvokeWithJValues(self, pReq->receiver_, m, reinterpret_cast<JValue*>(pReq->arg_values_));
Elliott Hughesd07986f2011-12-06 18:27:45 -08002254
2255 pReq->exception = gRegistry->Add(self->GetException());
2256 pReq->result_tag = BasicTagFromDescriptor(MethodHelper(m).GetShorty());
2257 if (pReq->exception != 0) {
2258 Object* exc = self->GetException();
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08002259 VLOG(jdwp) << " JDWP invocation returning with exception=" << exc << " " << PrettyTypeOf(exc);
Elliott Hughesd07986f2011-12-06 18:27:45 -08002260 self->ClearException();
Elliott Hughesf24d3ce2012-04-11 17:43:37 -07002261 pReq->result_value.SetJ(0);
Elliott Hughesd07986f2011-12-06 18:27:45 -08002262 } else if (pReq->result_tag == JDWP::JT_OBJECT) {
2263 /* if no exception thrown, examine object result more closely */
Elliott Hughesf24d3ce2012-04-11 17:43:37 -07002264 JDWP::JdwpTag new_tag = TagFromObject(pReq->result_value.GetL());
Elliott Hughesd07986f2011-12-06 18:27:45 -08002265 if (new_tag != pReq->result_tag) {
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08002266 VLOG(jdwp) << " JDWP promoted result from " << pReq->result_tag << " to " << new_tag;
Elliott Hughesd07986f2011-12-06 18:27:45 -08002267 pReq->result_tag = new_tag;
2268 }
2269
2270 /*
2271 * Register the object. We don't actually need an ObjectId yet,
2272 * but we do need to be sure that the GC won't move or discard the
2273 * object when we switch out of RUNNING. The ObjectId conversion
2274 * will add the object to the "do not touch" list.
2275 *
2276 * We can't use the "tracked allocation" mechanism here because
2277 * the object is going to be handed off to a different thread.
2278 */
Elliott Hughesf24d3ce2012-04-11 17:43:37 -07002279 gRegistry->Add(pReq->result_value.GetL());
Elliott Hughesd07986f2011-12-06 18:27:45 -08002280 }
2281
2282 if (old_exception.get() != NULL) {
2283 self->SetException(old_exception.get());
2284 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002285}
2286
Elliott Hughesd07986f2011-12-06 18:27:45 -08002287/*
2288 * Register an object ID that might not have been registered previously.
2289 *
2290 * Normally this wouldn't happen -- the conversion to an ObjectId would
2291 * have added the object to the registry -- but in some cases (e.g.
2292 * throwing exceptions) we really want to do the registration late.
2293 */
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002294void Dbg::RegisterObjectId(JDWP::ObjectId id) {
Elliott Hughesd07986f2011-12-06 18:27:45 -08002295 gRegistry->Add(reinterpret_cast<Object*>(id));
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002296}
2297
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07002298/*
2299 * "buf" contains a full JDWP packet, possibly with multiple chunks. We
2300 * need to process each, accumulate the replies, and ship the whole thing
2301 * back.
2302 *
2303 * Returns "true" if we have a reply. The reply buffer is newly allocated,
2304 * and includes the chunk type/length, followed by the data.
2305 *
Elliott Hughes3d30d9b2011-12-07 17:35:48 -08002306 * OLD-TODO: we currently assume that the request and reply include a single
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07002307 * chunk. If this becomes inconvenient we will need to adapt.
2308 */
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002309bool Dbg::DdmHandlePacket(const uint8_t* buf, int dataLen, uint8_t** pReplyBuf, int* pReplyLen) {
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07002310 CHECK_GE(dataLen, 0);
2311
2312 Thread* self = Thread::Current();
2313 JNIEnv* env = self->GetJniEnv();
2314
Elliott Hughes844f9a02012-01-24 20:19:58 -08002315 static jclass Chunk_class = CacheClass(env, "org/apache/harmony/dalvik/ddmc/Chunk");
2316 static jclass DdmServer_class = CacheClass(env, "org/apache/harmony/dalvik/ddmc/DdmServer");
2317 static jmethodID dispatch_mid = env->GetStaticMethodID(DdmServer_class, "dispatch", "(I[BII)Lorg/apache/harmony/dalvik/ddmc/Chunk;");
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07002318 static jfieldID data_fid = env->GetFieldID(Chunk_class, "data", "[B");
2319 static jfieldID length_fid = env->GetFieldID(Chunk_class, "length", "I");
2320 static jfieldID offset_fid = env->GetFieldID(Chunk_class, "offset", "I");
2321 static jfieldID type_fid = env->GetFieldID(Chunk_class, "type", "I");
2322
2323 // Create a byte[] corresponding to 'buf'.
Elliott Hughes6a5bd492011-10-28 14:33:57 -07002324 ScopedLocalRef<jbyteArray> dataArray(env, env->NewByteArray(dataLen));
2325 if (dataArray.get() == NULL) {
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07002326 LOG(WARNING) << "byte[] allocation failed: " << dataLen;
2327 env->ExceptionClear();
2328 return false;
2329 }
Elliott Hughes6a5bd492011-10-28 14:33:57 -07002330 env->SetByteArrayRegion(dataArray.get(), 0, dataLen, reinterpret_cast<const jbyte*>(buf));
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07002331
2332 const int kChunkHdrLen = 8;
2333
2334 // Run through and find all chunks. [Currently just find the first.]
Elliott Hughes6a5bd492011-10-28 14:33:57 -07002335 ScopedByteArrayRO contents(env, dataArray.get());
Elliott Hughesf7c3b662011-10-27 12:04:56 -07002336 jint type = JDWP::Get4BE(reinterpret_cast<const uint8_t*>(&contents[0]));
2337 jint length = JDWP::Get4BE(reinterpret_cast<const uint8_t*>(&contents[4]));
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07002338 jint offset = kChunkHdrLen;
2339 if (offset + length > dataLen) {
2340 LOG(WARNING) << StringPrintf("bad chunk found (len=%u pktLen=%d)", length, dataLen);
2341 return false;
2342 }
2343
2344 // Call "private static Chunk dispatch(int type, byte[] data, int offset, int length)".
Elliott Hughes6a5bd492011-10-28 14:33:57 -07002345 ScopedLocalRef<jobject> chunk(env, env->CallStaticObjectMethod(DdmServer_class, dispatch_mid, type, dataArray.get(), offset, length));
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07002346 if (env->ExceptionCheck()) {
2347 LOG(INFO) << StringPrintf("Exception thrown by dispatcher for 0x%08x", type);
2348 env->ExceptionDescribe();
2349 env->ExceptionClear();
2350 return false;
2351 }
2352
Elliott Hughes6a5bd492011-10-28 14:33:57 -07002353 if (chunk.get() == NULL) {
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07002354 return false;
2355 }
2356
2357 /*
2358 * Pull the pieces out of the chunk. We copy the results into a
2359 * newly-allocated buffer that the caller can free. We don't want to
2360 * continue using the Chunk object because nothing has a reference to it.
2361 *
2362 * We could avoid this by returning type/data/offset/length and having
2363 * the caller be aware of the object lifetime issues, but that
Elliott Hughes81ff3182012-03-23 20:35:56 -07002364 * integrates the JDWP code more tightly into the rest of the runtime, and doesn't work
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07002365 * if we have responses for multiple chunks.
2366 *
2367 * So we're pretty much stuck with copying data around multiple times.
2368 */
Elliott Hughes6a5bd492011-10-28 14:33:57 -07002369 ScopedLocalRef<jbyteArray> replyData(env, reinterpret_cast<jbyteArray>(env->GetObjectField(chunk.get(), data_fid)));
2370 length = env->GetIntField(chunk.get(), length_fid);
2371 offset = env->GetIntField(chunk.get(), offset_fid);
2372 type = env->GetIntField(chunk.get(), type_fid);
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07002373
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08002374 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 -07002375 if (length == 0 || replyData.get() == NULL) {
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07002376 return false;
2377 }
2378
Elliott Hughes6a5bd492011-10-28 14:33:57 -07002379 jsize replyLength = env->GetArrayLength(replyData.get());
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07002380 if (offset + length > replyLength) {
2381 LOG(WARNING) << StringPrintf("chunk off=%d len=%d exceeds reply array len %d", offset, length, replyLength);
2382 return false;
2383 }
2384
2385 uint8_t* reply = new uint8_t[length + kChunkHdrLen];
2386 if (reply == NULL) {
2387 LOG(WARNING) << "malloc failed: " << (length + kChunkHdrLen);
2388 return false;
2389 }
Elliott Hughesf7c3b662011-10-27 12:04:56 -07002390 JDWP::Set4BE(reply + 0, type);
2391 JDWP::Set4BE(reply + 4, length);
Elliott Hughes6a5bd492011-10-28 14:33:57 -07002392 env->GetByteArrayRegion(replyData.get(), offset, length, reinterpret_cast<jbyte*>(reply + kChunkHdrLen));
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07002393
2394 *pReplyBuf = reply;
2395 *pReplyLen = length + kChunkHdrLen;
2396
Elliott Hughesba8eee12012-01-24 20:25:24 -08002397 VLOG(jdwp) << StringPrintf("dvmHandleDdm returning type=%.4s buf=%p len=%d", reinterpret_cast<char*>(reply), reply, length);
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07002398 return true;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002399}
2400
Elliott Hughesa2155262011-11-16 16:26:58 -08002401void Dbg::DdmBroadcast(bool connect) {
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08002402 VLOG(jdwp) << "Broadcasting DDM " << (connect ? "connect" : "disconnect") << "...";
Elliott Hughes47fce012011-10-25 18:37:19 -07002403
2404 Thread* self = Thread::Current();
Elliott Hughes34e06962012-04-09 13:55:55 -07002405 if (self->GetState() != kRunnable) {
Elliott Hughes47fce012011-10-25 18:37:19 -07002406 LOG(ERROR) << "DDM broadcast in thread state " << self->GetState();
2407 /* try anyway? */
2408 }
2409
2410 JNIEnv* env = self->GetJniEnv();
Elliott Hughes844f9a02012-01-24 20:19:58 -08002411 static jclass DdmServer_class = CacheClass(env, "org/apache/harmony/dalvik/ddmc/DdmServer");
Elliott Hughes47fce012011-10-25 18:37:19 -07002412 static jmethodID broadcast_mid = env->GetStaticMethodID(DdmServer_class, "broadcast", "(I)V");
2413 jint event = connect ? 1 /*DdmServer.CONNECTED*/ : 2 /*DdmServer.DISCONNECTED*/;
2414 env->CallStaticVoidMethod(DdmServer_class, broadcast_mid, event);
2415 if (env->ExceptionCheck()) {
2416 LOG(ERROR) << "DdmServer.broadcast " << event << " failed";
2417 env->ExceptionDescribe();
2418 env->ExceptionClear();
2419 }
2420}
2421
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002422void Dbg::DdmConnected() {
Elliott Hughesa2155262011-11-16 16:26:58 -08002423 Dbg::DdmBroadcast(true);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002424}
2425
2426void Dbg::DdmDisconnected() {
Elliott Hughesa2155262011-11-16 16:26:58 -08002427 Dbg::DdmBroadcast(false);
Elliott Hughes47fce012011-10-25 18:37:19 -07002428 gDdmThreadNotification = false;
2429}
2430
2431/*
Elliott Hughes82188472011-11-07 18:11:48 -08002432 * Send a notification when a thread starts, stops, or changes its name.
Elliott Hughes47fce012011-10-25 18:37:19 -07002433 *
2434 * Because we broadcast the full set of threads when the notifications are
2435 * first enabled, it's possible for "thread" to be actively executing.
2436 */
Elliott Hughes82188472011-11-07 18:11:48 -08002437void Dbg::DdmSendThreadNotification(Thread* t, uint32_t type) {
Elliott Hughes47fce012011-10-25 18:37:19 -07002438 if (!gDdmThreadNotification) {
2439 return;
2440 }
2441
Elliott Hughes82188472011-11-07 18:11:48 -08002442 if (type == CHUNK_TYPE("THDE")) {
Elliott Hughes47fce012011-10-25 18:37:19 -07002443 uint8_t buf[4];
Elliott Hughesf7c3b662011-10-27 12:04:56 -07002444 JDWP::Set4BE(&buf[0], t->GetThinLockId());
Elliott Hughes47fce012011-10-25 18:37:19 -07002445 Dbg::DdmSendChunk(CHUNK_TYPE("THDE"), 4, buf);
Elliott Hughes82188472011-11-07 18:11:48 -08002446 } else {
2447 CHECK(type == CHUNK_TYPE("THCR") || type == CHUNK_TYPE("THNM")) << type;
Elliott Hughes899e7892012-01-24 14:57:32 -08002448 SirtRef<String> name(t->GetThreadName());
Elliott Hughes82188472011-11-07 18:11:48 -08002449 size_t char_count = (name.get() != NULL) ? name->GetLength() : 0;
2450 const jchar* chars = name->GetCharArray()->GetData();
2451
Elliott Hughes21f32d72011-11-09 17:44:13 -08002452 std::vector<uint8_t> bytes;
Elliott Hughes545a0642011-11-08 19:10:03 -08002453 JDWP::Append4BE(bytes, t->GetThinLockId());
2454 JDWP::AppendUtf16BE(bytes, chars, char_count);
Elliott Hughes21f32d72011-11-09 17:44:13 -08002455 CHECK_EQ(bytes.size(), char_count*2 + sizeof(uint32_t)*2);
2456 Dbg::DdmSendChunk(type, bytes);
Elliott Hughes47fce012011-10-25 18:37:19 -07002457 }
2458}
2459
Elliott Hughesa2155262011-11-16 16:26:58 -08002460static void DdmSendThreadStartCallback(Thread* t, void*) {
Elliott Hughes82188472011-11-07 18:11:48 -08002461 Dbg::DdmSendThreadNotification(t, CHUNK_TYPE("THCR"));
Elliott Hughes47fce012011-10-25 18:37:19 -07002462}
2463
2464void Dbg::DdmSetThreadNotification(bool enable) {
2465 // We lock the thread list to avoid sending duplicate events or missing
2466 // a thread change. We should be okay holding this lock while sending
2467 // the messages out. (We have to hold it while accessing a live thread.)
Elliott Hughesbbd9d832011-11-07 14:40:00 -08002468 ScopedThreadListLock thread_list_lock;
Elliott Hughes47fce012011-10-25 18:37:19 -07002469
2470 gDdmThreadNotification = enable;
2471 if (enable) {
Elliott Hughesbfe487b2011-10-26 15:48:55 -07002472 Runtime::Current()->GetThreadList()->ForEach(DdmSendThreadStartCallback, NULL);
Elliott Hughes47fce012011-10-25 18:37:19 -07002473 }
2474}
2475
Elliott Hughesa2155262011-11-16 16:26:58 -08002476void Dbg::PostThreadStartOrStop(Thread* t, uint32_t type) {
Elliott Hughesc0f09332012-03-26 13:27:06 -07002477 if (IsDebuggerActive()) {
Elliott Hughes47fce012011-10-25 18:37:19 -07002478 JDWP::ObjectId id = gRegistry->Add(t->GetPeer());
Elliott Hughes82188472011-11-07 18:11:48 -08002479 gJdwpState->PostThreadChange(id, type == CHUNK_TYPE("THCR"));
Elliott Hughesc0f09332012-03-26 13:27:06 -07002480 // If this thread's just joined the party while we're already debugging, make sure it knows
2481 // to give us updates when it's running.
2482 t->SetDebuggerUpdatesEnabled(true);
Elliott Hughes47fce012011-10-25 18:37:19 -07002483 }
Elliott Hughes82188472011-11-07 18:11:48 -08002484 Dbg::DdmSendThreadNotification(t, type);
Elliott Hughes47fce012011-10-25 18:37:19 -07002485}
2486
2487void Dbg::PostThreadStart(Thread* t) {
Elliott Hughesa2155262011-11-16 16:26:58 -08002488 Dbg::PostThreadStartOrStop(t, CHUNK_TYPE("THCR"));
Elliott Hughes47fce012011-10-25 18:37:19 -07002489}
2490
2491void Dbg::PostThreadDeath(Thread* t) {
Elliott Hughesa2155262011-11-16 16:26:58 -08002492 Dbg::PostThreadStartOrStop(t, CHUNK_TYPE("THDE"));
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002493}
2494
Elliott Hughes82188472011-11-07 18:11:48 -08002495void Dbg::DdmSendChunk(uint32_t type, size_t byte_count, const uint8_t* buf) {
Elliott Hughes3bb81562011-10-21 18:52:59 -07002496 CHECK(buf != NULL);
2497 iovec vec[1];
2498 vec[0].iov_base = reinterpret_cast<void*>(const_cast<uint8_t*>(buf));
2499 vec[0].iov_len = byte_count;
2500 Dbg::DdmSendChunkV(type, vec, 1);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002501}
2502
Elliott Hughes21f32d72011-11-09 17:44:13 -08002503void Dbg::DdmSendChunk(uint32_t type, const std::vector<uint8_t>& bytes) {
2504 DdmSendChunk(type, bytes.size(), &bytes[0]);
2505}
2506
Elliott Hughescccd84f2011-12-05 16:51:54 -08002507void Dbg::DdmSendChunkV(uint32_t type, const struct iovec* iov, int iov_count) {
Elliott Hughes3bb81562011-10-21 18:52:59 -07002508 if (gJdwpState == NULL) {
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08002509 VLOG(jdwp) << "Debugger thread not active, ignoring DDM send: " << type;
Elliott Hughes3bb81562011-10-21 18:52:59 -07002510 } else {
Elliott Hughescccd84f2011-12-05 16:51:54 -08002511 gJdwpState->DdmSendChunkV(type, iov, iov_count);
Elliott Hughes3bb81562011-10-21 18:52:59 -07002512 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002513}
2514
Elliott Hughes767a1472011-10-26 18:49:02 -07002515int Dbg::DdmHandleHpifChunk(HpifWhen when) {
2516 if (when == HPIF_WHEN_NOW) {
Elliott Hughes7162ad92011-10-27 14:08:42 -07002517 DdmSendHeapInfo(when);
Elliott Hughes767a1472011-10-26 18:49:02 -07002518 return true;
2519 }
2520
2521 if (when != HPIF_WHEN_NEVER && when != HPIF_WHEN_NEXT_GC && when != HPIF_WHEN_EVERY_GC) {
2522 LOG(ERROR) << "invalid HpifWhen value: " << static_cast<int>(when);
2523 return false;
2524 }
2525
2526 gDdmHpifWhen = when;
2527 return true;
2528}
2529
2530bool Dbg::DdmHandleHpsgNhsgChunk(Dbg::HpsgWhen when, Dbg::HpsgWhat what, bool native) {
2531 if (when != HPSG_WHEN_NEVER && when != HPSG_WHEN_EVERY_GC) {
2532 LOG(ERROR) << "invalid HpsgWhen value: " << static_cast<int>(when);
2533 return false;
2534 }
2535
2536 if (what != HPSG_WHAT_MERGED_OBJECTS && what != HPSG_WHAT_DISTINCT_OBJECTS) {
2537 LOG(ERROR) << "invalid HpsgWhat value: " << static_cast<int>(what);
2538 return false;
2539 }
2540
2541 if (native) {
2542 gDdmNhsgWhen = when;
2543 gDdmNhsgWhat = what;
2544 } else {
2545 gDdmHpsgWhen = when;
2546 gDdmHpsgWhat = what;
2547 }
2548 return true;
2549}
2550
Elliott Hughes7162ad92011-10-27 14:08:42 -07002551void Dbg::DdmSendHeapInfo(HpifWhen reason) {
2552 // If there's a one-shot 'when', reset it.
2553 if (reason == gDdmHpifWhen) {
2554 if (gDdmHpifWhen == HPIF_WHEN_NEXT_GC) {
2555 gDdmHpifWhen = HPIF_WHEN_NEVER;
2556 }
2557 }
2558
2559 /*
2560 * Chunk HPIF (client --> server)
2561 *
2562 * Heap Info. General information about the heap,
2563 * suitable for a summary display.
2564 *
2565 * [u4]: number of heaps
2566 *
2567 * For each heap:
2568 * [u4]: heap ID
2569 * [u8]: timestamp in ms since Unix epoch
2570 * [u1]: capture reason (same as 'when' value from server)
2571 * [u4]: max heap size in bytes (-Xmx)
2572 * [u4]: current heap size in bytes
2573 * [u4]: current number of bytes allocated
2574 * [u4]: current number of objects allocated
2575 */
2576 uint8_t heap_count = 1;
Elliott Hughesb3bd5f02012-03-08 21:05:27 -08002577 Heap* heap = Runtime::Current()->GetHeap();
Elliott Hughes21f32d72011-11-09 17:44:13 -08002578 std::vector<uint8_t> bytes;
Elliott Hughes545a0642011-11-08 19:10:03 -08002579 JDWP::Append4BE(bytes, heap_count);
2580 JDWP::Append4BE(bytes, 1); // Heap id (bogus; we only have one heap).
2581 JDWP::Append8BE(bytes, MilliTime());
2582 JDWP::Append1BE(bytes, reason);
Elliott Hughesb3bd5f02012-03-08 21:05:27 -08002583 JDWP::Append4BE(bytes, heap->GetMaxMemory()); // Max allowed heap size in bytes.
2584 JDWP::Append4BE(bytes, heap->GetTotalMemory()); // Current heap size in bytes.
2585 JDWP::Append4BE(bytes, heap->GetBytesAllocated());
2586 JDWP::Append4BE(bytes, heap->GetObjectsAllocated());
Elliott Hughes21f32d72011-11-09 17:44:13 -08002587 CHECK_EQ(bytes.size(), 4U + (heap_count * (4 + 8 + 1 + 4 + 4 + 4 + 4)));
2588 Dbg::DdmSendChunk(CHUNK_TYPE("HPIF"), bytes);
Elliott Hughes767a1472011-10-26 18:49:02 -07002589}
2590
Elliott Hughes6a5bd492011-10-28 14:33:57 -07002591enum HpsgSolidity {
2592 SOLIDITY_FREE = 0,
2593 SOLIDITY_HARD = 1,
2594 SOLIDITY_SOFT = 2,
2595 SOLIDITY_WEAK = 3,
2596 SOLIDITY_PHANTOM = 4,
2597 SOLIDITY_FINALIZABLE = 5,
2598 SOLIDITY_SWEEP = 6,
2599};
2600
2601enum HpsgKind {
2602 KIND_OBJECT = 0,
2603 KIND_CLASS_OBJECT = 1,
2604 KIND_ARRAY_1 = 2,
2605 KIND_ARRAY_2 = 3,
2606 KIND_ARRAY_4 = 4,
2607 KIND_ARRAY_8 = 5,
2608 KIND_UNKNOWN = 6,
2609 KIND_NATIVE = 7,
2610};
2611
2612#define HPSG_PARTIAL (1<<7)
2613#define HPSG_STATE(solidity, kind) ((uint8_t)((((kind) & 0x7) << 3) | ((solidity) & 0x7)))
2614
Ian Rogers30fab402012-01-23 15:43:46 -08002615class HeapChunkContext {
2616 public:
Elliott Hughes6a5bd492011-10-28 14:33:57 -07002617 // Maximum chunk size. Obtain this from the formula:
2618 // (((maximum_heap_size / ALLOCATION_UNIT_SIZE) + 255) / 256) * 2
2619 HeapChunkContext(bool merge, bool native)
Ian Rogers30fab402012-01-23 15:43:46 -08002620 : buf_(16384 - 16),
2621 type_(0),
2622 merge_(merge) {
Elliott Hughes6a5bd492011-10-28 14:33:57 -07002623 Reset();
2624 if (native) {
Ian Rogers30fab402012-01-23 15:43:46 -08002625 type_ = CHUNK_TYPE("NHSG");
Elliott Hughes6a5bd492011-10-28 14:33:57 -07002626 } else {
Ian Rogers30fab402012-01-23 15:43:46 -08002627 type_ = merge ? CHUNK_TYPE("HPSG") : CHUNK_TYPE("HPSO");
Elliott Hughes6a5bd492011-10-28 14:33:57 -07002628 }
2629 }
2630
2631 ~HeapChunkContext() {
Ian Rogers30fab402012-01-23 15:43:46 -08002632 if (p_ > &buf_[0]) {
Elliott Hughes6a5bd492011-10-28 14:33:57 -07002633 Flush();
2634 }
2635 }
2636
2637 void EnsureHeader(const void* chunk_ptr) {
Ian Rogers30fab402012-01-23 15:43:46 -08002638 if (!needHeader_) {
Elliott Hughes6a5bd492011-10-28 14:33:57 -07002639 return;
2640 }
2641
2642 // Start a new HPSx chunk.
Ian Rogers30fab402012-01-23 15:43:46 -08002643 JDWP::Write4BE(&p_, 1); // Heap id (bogus; we only have one heap).
2644 JDWP::Write1BE(&p_, 8); // Size of allocation unit, in bytes.
Elliott Hughes6a5bd492011-10-28 14:33:57 -07002645
Ian Rogers30fab402012-01-23 15:43:46 -08002646 JDWP::Write4BE(&p_, reinterpret_cast<uintptr_t>(chunk_ptr)); // virtual address of segment start.
2647 JDWP::Write4BE(&p_, 0); // offset of this piece (relative to the virtual address).
Elliott Hughes6a5bd492011-10-28 14:33:57 -07002648 // [u4]: length of piece, in allocation units
2649 // 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 -08002650 pieceLenField_ = p_;
2651 JDWP::Write4BE(&p_, 0x55555555);
2652 needHeader_ = false;
Elliott Hughes6a5bd492011-10-28 14:33:57 -07002653 }
2654
2655 void Flush() {
2656 // Patch the "length of piece" field.
Ian Rogers30fab402012-01-23 15:43:46 -08002657 CHECK_LE(&buf_[0], pieceLenField_);
2658 CHECK_LE(pieceLenField_, p_);
2659 JDWP::Set4BE(pieceLenField_, totalAllocationUnits_);
Elliott Hughes6a5bd492011-10-28 14:33:57 -07002660
Ian Rogers30fab402012-01-23 15:43:46 -08002661 Dbg::DdmSendChunk(type_, p_ - &buf_[0], &buf_[0]);
Elliott Hughes6a5bd492011-10-28 14:33:57 -07002662 Reset();
2663 }
2664
Ian Rogers30fab402012-01-23 15:43:46 -08002665 static void HeapChunkCallback(void* start, void* end, size_t used_bytes, void* arg) {
2666 reinterpret_cast<HeapChunkContext*>(arg)->HeapChunkCallback(start, end, used_bytes);
Elliott Hughesa2155262011-11-16 16:26:58 -08002667 }
2668
Elliott Hughes6a5bd492011-10-28 14:33:57 -07002669 private:
Elliott Hughesa2155262011-11-16 16:26:58 -08002670 enum { ALLOCATION_UNIT_SIZE = 8 };
2671
Elliott Hughes6a5bd492011-10-28 14:33:57 -07002672 void Reset() {
Ian Rogers30fab402012-01-23 15:43:46 -08002673 p_ = &buf_[0];
2674 totalAllocationUnits_ = 0;
2675 needHeader_ = true;
2676 pieceLenField_ = NULL;
Elliott Hughes6a5bd492011-10-28 14:33:57 -07002677 }
2678
Elliott Hughes1bac54f2012-03-16 12:48:31 -07002679 void HeapChunkCallback(void* start, void* /*end*/, size_t used_bytes) {
Ian Rogers30fab402012-01-23 15:43:46 -08002680 // Note: heap call backs cannot manipulate the heap upon which they are crawling, care is taken
2681 // in the following code not to allocate memory, by ensuring buf_ is of the correct size
2682
2683 const void* user_ptr = used_bytes > 0 ? const_cast<void*>(start) : NULL;
2684 // from malloc.c mem2chunk(mem)
2685 const void* chunk_ptr =
2686 reinterpret_cast<const void*>(reinterpret_cast<const char*>(const_cast<void*>(start)) -
2687 (2 * sizeof(size_t)));
2688 // from malloc.c chunksize
2689 size_t chunk_len = (*reinterpret_cast<size_t* const*>(chunk_ptr))[1] & ~7;
2690
2691
2692 //size_t chunk_len = malloc_usable_size(user_ptr);
Elliott Hughesa2155262011-11-16 16:26:58 -08002693 CHECK_EQ((chunk_len & (ALLOCATION_UNIT_SIZE-1)), 0U);
Elliott Hughes6a5bd492011-10-28 14:33:57 -07002694
Elliott Hughesa2155262011-11-16 16:26:58 -08002695 /* Make sure there's enough room left in the buffer.
2696 * We need to use two bytes for every fractional 256
2697 * allocation units used by the chunk.
2698 */
2699 {
2700 size_t needed = (((chunk_len/ALLOCATION_UNIT_SIZE + 255) / 256) * 2);
Ian Rogers30fab402012-01-23 15:43:46 -08002701 size_t bytesLeft = buf_.size() - (size_t)(p_ - &buf_[0]);
Elliott Hughesa2155262011-11-16 16:26:58 -08002702 if (bytesLeft < needed) {
2703 Flush();
2704 }
Elliott Hughes6a5bd492011-10-28 14:33:57 -07002705
Ian Rogers30fab402012-01-23 15:43:46 -08002706 bytesLeft = buf_.size() - (size_t)(p_ - &buf_[0]);
Elliott Hughesa2155262011-11-16 16:26:58 -08002707 if (bytesLeft < needed) {
Elliott Hughes3d30d9b2011-12-07 17:35:48 -08002708 LOG(WARNING) << "Chunk is too big to transmit (chunk_len=" << chunk_len << ", " << needed << " bytes)";
Elliott Hughesa2155262011-11-16 16:26:58 -08002709 return;
2710 }
2711 }
2712
2713 // OLD-TODO: notice when there's a gap and start a new heap, or at least a new range.
2714 EnsureHeader(chunk_ptr);
2715
2716 // Determine the type of this chunk.
2717 // OLD-TODO: if context.merge, see if this chunk is different from the last chunk.
2718 // If it's the same, we should combine them.
Ian Rogers30fab402012-01-23 15:43:46 -08002719 uint8_t state = ExamineObject(reinterpret_cast<const Object*>(user_ptr), (type_ == CHUNK_TYPE("NHSG")));
Elliott Hughesa2155262011-11-16 16:26:58 -08002720
2721 // Write out the chunk description.
2722 chunk_len /= ALLOCATION_UNIT_SIZE; // convert to allocation units
Ian Rogers30fab402012-01-23 15:43:46 -08002723 totalAllocationUnits_ += chunk_len;
Elliott Hughesa2155262011-11-16 16:26:58 -08002724 while (chunk_len > 256) {
Ian Rogers30fab402012-01-23 15:43:46 -08002725 *p_++ = state | HPSG_PARTIAL;
2726 *p_++ = 255; // length - 1
Elliott Hughesa2155262011-11-16 16:26:58 -08002727 chunk_len -= 256;
2728 }
Ian Rogers30fab402012-01-23 15:43:46 -08002729 *p_++ = state;
2730 *p_++ = chunk_len - 1;
Elliott Hughes6a5bd492011-10-28 14:33:57 -07002731 }
2732
Elliott Hughesa2155262011-11-16 16:26:58 -08002733 uint8_t ExamineObject(const Object* o, bool is_native_heap) {
2734 if (o == NULL) {
2735 return HPSG_STATE(SOLIDITY_FREE, 0);
2736 }
Elliott Hughes6a5bd492011-10-28 14:33:57 -07002737
Elliott Hughesa2155262011-11-16 16:26:58 -08002738 // It's an allocated chunk. Figure out what it is.
Elliott Hughes6a5bd492011-10-28 14:33:57 -07002739
Elliott Hughesa2155262011-11-16 16:26:58 -08002740 // If we're looking at the native heap, we'll just return
2741 // (SOLIDITY_HARD, KIND_NATIVE) for all allocated chunks.
Elliott Hughesb3bd5f02012-03-08 21:05:27 -08002742 if (is_native_heap || !Runtime::Current()->GetHeap()->IsLiveObjectLocked(o)) {
Elliott Hughesa2155262011-11-16 16:26:58 -08002743 return HPSG_STATE(SOLIDITY_HARD, KIND_NATIVE);
2744 }
2745
2746 Class* c = o->GetClass();
2747 if (c == NULL) {
2748 // The object was probably just created but hasn't been initialized yet.
2749 return HPSG_STATE(SOLIDITY_HARD, KIND_OBJECT);
2750 }
2751
Elliott Hughesb3bd5f02012-03-08 21:05:27 -08002752 if (!Runtime::Current()->GetHeap()->IsHeapAddress(c)) {
Elliott Hughes3d30d9b2011-12-07 17:35:48 -08002753 LOG(WARNING) << "Invalid class for managed heap object: " << o << " " << c;
Elliott Hughesa2155262011-11-16 16:26:58 -08002754 return HPSG_STATE(SOLIDITY_HARD, KIND_UNKNOWN);
2755 }
2756
2757 if (c->IsClassClass()) {
2758 return HPSG_STATE(SOLIDITY_HARD, KIND_CLASS_OBJECT);
2759 }
2760
2761 if (c->IsArrayClass()) {
2762 if (o->IsObjectArray()) {
2763 return HPSG_STATE(SOLIDITY_HARD, KIND_ARRAY_4);
2764 }
2765 switch (c->GetComponentSize()) {
2766 case 1: return HPSG_STATE(SOLIDITY_HARD, KIND_ARRAY_1);
2767 case 2: return HPSG_STATE(SOLIDITY_HARD, KIND_ARRAY_2);
2768 case 4: return HPSG_STATE(SOLIDITY_HARD, KIND_ARRAY_4);
2769 case 8: return HPSG_STATE(SOLIDITY_HARD, KIND_ARRAY_8);
2770 }
2771 }
2772
Elliott Hughes6a5bd492011-10-28 14:33:57 -07002773 return HPSG_STATE(SOLIDITY_HARD, KIND_OBJECT);
2774 }
2775
Ian Rogers30fab402012-01-23 15:43:46 -08002776 std::vector<uint8_t> buf_;
2777 uint8_t* p_;
2778 uint8_t* pieceLenField_;
2779 size_t totalAllocationUnits_;
2780 uint32_t type_;
2781 bool merge_;
2782 bool needHeader_;
2783
Elliott Hughesa2155262011-11-16 16:26:58 -08002784 DISALLOW_COPY_AND_ASSIGN(HeapChunkContext);
2785};
Elliott Hughes6a5bd492011-10-28 14:33:57 -07002786
2787void Dbg::DdmSendHeapSegments(bool native) {
2788 Dbg::HpsgWhen when;
2789 Dbg::HpsgWhat what;
2790 if (!native) {
2791 when = gDdmHpsgWhen;
2792 what = gDdmHpsgWhat;
2793 } else {
2794 when = gDdmNhsgWhen;
2795 what = gDdmNhsgWhat;
2796 }
2797 if (when == HPSG_WHEN_NEVER) {
2798 return;
2799 }
2800
2801 // Figure out what kind of chunks we'll be sending.
2802 CHECK(what == HPSG_WHAT_MERGED_OBJECTS || what == HPSG_WHAT_DISTINCT_OBJECTS) << static_cast<int>(what);
2803
2804 // First, send a heap start chunk.
2805 uint8_t heap_id[4];
2806 JDWP::Set4BE(&heap_id[0], 1); // Heap id (bogus; we only have one heap).
2807 Dbg::DdmSendChunk(native ? CHUNK_TYPE("NHST") : CHUNK_TYPE("HPST"), sizeof(heap_id), heap_id);
2808
2809 // Send a series of heap segment chunks.
Elliott Hughesa2155262011-11-16 16:26:58 -08002810 HeapChunkContext context((what == HPSG_WHAT_MERGED_OBJECTS), native);
2811 if (native) {
Ian Rogers30fab402012-01-23 15:43:46 -08002812 // TODO: enable when bionic has moved to dlmalloc 2.8.5
2813 // dlmalloc_inspect_all(HeapChunkContext::HeapChunkCallback, &context);
2814 UNIMPLEMENTED(WARNING) << "Native heap send heap segments";
Elliott Hughesa2155262011-11-16 16:26:58 -08002815 } else {
Elliott Hughesb3bd5f02012-03-08 21:05:27 -08002816 Heap* heap = Runtime::Current()->GetHeap();
2817 heap->GetAllocSpace()->Walk(HeapChunkContext::HeapChunkCallback, &context);
Elliott Hughesa2155262011-11-16 16:26:58 -08002818 }
Elliott Hughes6a5bd492011-10-28 14:33:57 -07002819
2820 // Finally, send a heap end chunk.
2821 Dbg::DdmSendChunk(native ? CHUNK_TYPE("NHEN") : CHUNK_TYPE("HPEN"), sizeof(heap_id), heap_id);
Elliott Hughes767a1472011-10-26 18:49:02 -07002822}
2823
Elliott Hughes545a0642011-11-08 19:10:03 -08002824void Dbg::SetAllocTrackingEnabled(bool enabled) {
2825 MutexLock mu(gAllocTrackerLock);
2826 if (enabled) {
2827 if (recent_allocation_records_ == NULL) {
2828 LOG(INFO) << "Enabling alloc tracker (" << kNumAllocRecords << " entries, "
2829 << kMaxAllocRecordStackDepth << " frames --> "
2830 << (sizeof(AllocRecord) * kNumAllocRecords) << " bytes)";
2831 gAllocRecordHead = gAllocRecordCount = 0;
2832 recent_allocation_records_ = new AllocRecord[kNumAllocRecords];
2833 CHECK(recent_allocation_records_ != NULL);
2834 }
2835 } else {
2836 delete[] recent_allocation_records_;
2837 recent_allocation_records_ = NULL;
2838 }
2839}
2840
2841struct AllocRecordStackVisitor : public Thread::StackVisitor {
Elliott Hughesba8eee12012-01-24 20:25:24 -08002842 explicit AllocRecordStackVisitor(AllocRecord* record) : record(record), depth(0) {
Elliott Hughes545a0642011-11-08 19:10:03 -08002843 }
2844
Elliott Hughes530fa002012-03-12 11:44:49 -07002845 bool VisitFrame(const Frame& f, uintptr_t pc) {
Elliott Hughes545a0642011-11-08 19:10:03 -08002846 if (depth >= kMaxAllocRecordStackDepth) {
Elliott Hughes530fa002012-03-12 11:44:49 -07002847 return false;
Elliott Hughes545a0642011-11-08 19:10:03 -08002848 }
Elliott Hughes530fa002012-03-12 11:44:49 -07002849 if (f.HasMethod()) {
2850 record->stack[depth].method = f.GetMethod();
2851 record->stack[depth].raw_pc = pc;
2852 ++depth;
Elliott Hughes545a0642011-11-08 19:10:03 -08002853 }
Elliott Hughes530fa002012-03-12 11:44:49 -07002854 return true;
Elliott Hughes545a0642011-11-08 19:10:03 -08002855 }
2856
2857 ~AllocRecordStackVisitor() {
2858 // Clear out any unused stack trace elements.
2859 for (; depth < kMaxAllocRecordStackDepth; ++depth) {
2860 record->stack[depth].method = NULL;
2861 record->stack[depth].raw_pc = 0;
2862 }
2863 }
2864
2865 AllocRecord* record;
2866 size_t depth;
2867};
2868
2869void Dbg::RecordAllocation(Class* type, size_t byte_count) {
2870 Thread* self = Thread::Current();
2871 CHECK(self != NULL);
2872
2873 MutexLock mu(gAllocTrackerLock);
2874 if (recent_allocation_records_ == NULL) {
2875 return;
2876 }
2877
2878 // Advance and clip.
2879 if (++gAllocRecordHead == kNumAllocRecords) {
2880 gAllocRecordHead = 0;
2881 }
2882
2883 // Fill in the basics.
2884 AllocRecord* record = &recent_allocation_records_[gAllocRecordHead];
2885 record->type = type;
2886 record->byte_count = byte_count;
2887 record->thin_lock_id = self->GetThinLockId();
2888
2889 // Fill in the stack trace.
2890 AllocRecordStackVisitor visitor(record);
2891 self->WalkStack(&visitor);
2892
2893 if (gAllocRecordCount < kNumAllocRecords) {
2894 ++gAllocRecordCount;
2895 }
2896}
2897
2898/*
2899 * Return the index of the head element.
2900 *
2901 * We point at the most-recently-written record, so if allocRecordCount is 1
2902 * we want to use the current element. Take "head+1" and subtract count
2903 * from it.
2904 *
2905 * We need to handle underflow in our circular buffer, so we add
2906 * kNumAllocRecords and then mask it back down.
2907 */
2908inline static int headIndex() {
2909 return (gAllocRecordHead+1 + kNumAllocRecords - gAllocRecordCount) & (kNumAllocRecords-1);
2910}
2911
2912void Dbg::DumpRecentAllocations() {
2913 MutexLock mu(gAllocTrackerLock);
2914 if (recent_allocation_records_ == NULL) {
2915 LOG(INFO) << "Not recording tracked allocations";
2916 return;
2917 }
2918
2919 // "i" is the head of the list. We want to start at the end of the
2920 // list and move forward to the tail.
2921 size_t i = headIndex();
2922 size_t count = gAllocRecordCount;
2923
2924 LOG(INFO) << "Tracked allocations, (head=" << gAllocRecordHead << " count=" << count << ")";
2925 while (count--) {
2926 AllocRecord* record = &recent_allocation_records_[i];
2927
Elliott Hughesaa6e1cd2012-01-18 19:26:06 -08002928 LOG(INFO) << StringPrintf(" T=%-2d %6zd ", record->thin_lock_id, record->byte_count)
Elliott Hughes545a0642011-11-08 19:10:03 -08002929 << PrettyClass(record->type);
2930
2931 for (size_t stack_frame = 0; stack_frame < kMaxAllocRecordStackDepth; ++stack_frame) {
2932 const Method* m = record->stack[stack_frame].method;
2933 if (m == NULL) {
2934 break;
2935 }
2936 LOG(INFO) << " " << PrettyMethod(m) << " line " << record->stack[stack_frame].LineNumber();
2937 }
2938
2939 // pause periodically to help logcat catch up
2940 if ((count % 5) == 0) {
2941 usleep(40000);
2942 }
2943
2944 i = (i + 1) & (kNumAllocRecords-1);
2945 }
2946}
2947
2948class StringTable {
2949 public:
2950 StringTable() {
2951 }
2952
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002953 void Add(const char* s) {
Elliott Hughes545a0642011-11-08 19:10:03 -08002954 table_.insert(s);
2955 }
2956
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002957 size_t IndexOf(const char* s) {
Elliott Hughes545a0642011-11-08 19:10:03 -08002958 return std::distance(table_.begin(), table_.find(s));
2959 }
2960
2961 size_t Size() {
2962 return table_.size();
2963 }
2964
2965 void WriteTo(std::vector<uint8_t>& bytes) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002966 typedef std::set<const char*>::const_iterator It; // TODO: C++0x auto
Elliott Hughes545a0642011-11-08 19:10:03 -08002967 for (It it = table_.begin(); it != table_.end(); ++it) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002968 const char* s = *it;
2969 size_t s_len = CountModifiedUtf8Chars(s);
2970 UniquePtr<uint16_t> s_utf16(new uint16_t[s_len]);
2971 ConvertModifiedUtf8ToUtf16(s_utf16.get(), s);
2972 JDWP::AppendUtf16BE(bytes, s_utf16.get(), s_len);
Elliott Hughes545a0642011-11-08 19:10:03 -08002973 }
2974 }
2975
2976 private:
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002977 std::set<const char*> table_;
Elliott Hughes545a0642011-11-08 19:10:03 -08002978 DISALLOW_COPY_AND_ASSIGN(StringTable);
2979};
2980
2981/*
2982 * The data we send to DDMS contains everything we have recorded.
2983 *
2984 * Message header (all values big-endian):
2985 * (1b) message header len (to allow future expansion); includes itself
2986 * (1b) entry header len
2987 * (1b) stack frame len
2988 * (2b) number of entries
2989 * (4b) offset to string table from start of message
2990 * (2b) number of class name strings
2991 * (2b) number of method name strings
2992 * (2b) number of source file name strings
2993 * For each entry:
2994 * (4b) total allocation size
2995 * (2b) threadId
2996 * (2b) allocated object's class name index
2997 * (1b) stack depth
2998 * For each stack frame:
2999 * (2b) method's class name
3000 * (2b) method name
3001 * (2b) method source file
3002 * (2b) line number, clipped to 32767; -2 if native; -1 if no source
3003 * (xb) class name strings
3004 * (xb) method name strings
3005 * (xb) source file strings
3006 *
3007 * As with other DDM traffic, strings are sent as a 4-byte length
3008 * followed by UTF-16 data.
3009 *
3010 * We send up 16-bit unsigned indexes into string tables. In theory there
3011 * can be (kMaxAllocRecordStackDepth * kNumAllocRecords) unique strings in
3012 * each table, but in practice there should be far fewer.
3013 *
3014 * The chief reason for using a string table here is to keep the size of
3015 * the DDMS message to a minimum. This is partly to make the protocol
3016 * efficient, but also because we have to form the whole thing up all at
3017 * once in a memory buffer.
3018 *
3019 * We use separate string tables for class names, method names, and source
3020 * files to keep the indexes small. There will generally be no overlap
3021 * between the contents of these tables.
3022 */
3023jbyteArray Dbg::GetRecentAllocations() {
3024 if (false) {
3025 DumpRecentAllocations();
3026 }
3027
3028 MutexLock mu(gAllocTrackerLock);
3029
3030 /*
3031 * Part 1: generate string tables.
3032 */
3033 StringTable class_names;
3034 StringTable method_names;
3035 StringTable filenames;
3036
3037 int count = gAllocRecordCount;
3038 int idx = headIndex();
3039 while (count--) {
3040 AllocRecord* record = &recent_allocation_records_[idx];
3041
Elliott Hughes91250e02011-12-13 22:30:35 -08003042 class_names.Add(ClassHelper(record->type).GetDescriptor());
Elliott Hughes545a0642011-11-08 19:10:03 -08003043
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08003044 MethodHelper mh;
Elliott Hughes545a0642011-11-08 19:10:03 -08003045 for (size_t i = 0; i < kMaxAllocRecordStackDepth; i++) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08003046 Method* m = record->stack[i].method;
3047 mh.ChangeMethod(m);
Elliott Hughes545a0642011-11-08 19:10:03 -08003048 if (m != NULL) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08003049 class_names.Add(mh.GetDeclaringClassDescriptor());
3050 method_names.Add(mh.GetName());
3051 filenames.Add(mh.GetDeclaringClassSourceFile());
Elliott Hughes545a0642011-11-08 19:10:03 -08003052 }
3053 }
3054
3055 idx = (idx + 1) & (kNumAllocRecords-1);
3056 }
3057
3058 LOG(INFO) << "allocation records: " << gAllocRecordCount;
3059
3060 /*
3061 * Part 2: allocate a buffer and generate the output.
3062 */
3063 std::vector<uint8_t> bytes;
3064
3065 // (1b) message header len (to allow future expansion); includes itself
3066 // (1b) entry header len
3067 // (1b) stack frame len
3068 const int kMessageHeaderLen = 15;
3069 const int kEntryHeaderLen = 9;
3070 const int kStackFrameLen = 8;
3071 JDWP::Append1BE(bytes, kMessageHeaderLen);
3072 JDWP::Append1BE(bytes, kEntryHeaderLen);
3073 JDWP::Append1BE(bytes, kStackFrameLen);
3074
3075 // (2b) number of entries
3076 // (4b) offset to string table from start of message
3077 // (2b) number of class name strings
3078 // (2b) number of method name strings
3079 // (2b) number of source file name strings
3080 JDWP::Append2BE(bytes, gAllocRecordCount);
3081 size_t string_table_offset = bytes.size();
3082 JDWP::Append4BE(bytes, 0); // We'll patch this later...
3083 JDWP::Append2BE(bytes, class_names.Size());
3084 JDWP::Append2BE(bytes, method_names.Size());
3085 JDWP::Append2BE(bytes, filenames.Size());
3086
3087 count = gAllocRecordCount;
3088 idx = headIndex();
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08003089 ClassHelper kh;
Elliott Hughes545a0642011-11-08 19:10:03 -08003090 while (count--) {
3091 // For each entry:
3092 // (4b) total allocation size
3093 // (2b) thread id
3094 // (2b) allocated object's class name index
3095 // (1b) stack depth
3096 AllocRecord* record = &recent_allocation_records_[idx];
3097 size_t stack_depth = record->GetDepth();
3098 JDWP::Append4BE(bytes, record->byte_count);
3099 JDWP::Append2BE(bytes, record->thin_lock_id);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08003100 kh.ChangeClass(record->type);
Elliott Hughes91250e02011-12-13 22:30:35 -08003101 JDWP::Append2BE(bytes, class_names.IndexOf(kh.GetDescriptor()));
Elliott Hughes545a0642011-11-08 19:10:03 -08003102 JDWP::Append1BE(bytes, stack_depth);
3103
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08003104 MethodHelper mh;
Elliott Hughes545a0642011-11-08 19:10:03 -08003105 for (size_t stack_frame = 0; stack_frame < stack_depth; ++stack_frame) {
3106 // For each stack frame:
3107 // (2b) method's class name
3108 // (2b) method name
3109 // (2b) method source file
3110 // (2b) line number, clipped to 32767; -2 if native; -1 if no source
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08003111 mh.ChangeMethod(record->stack[stack_frame].method);
3112 JDWP::Append2BE(bytes, class_names.IndexOf(mh.GetDeclaringClassDescriptor()));
3113 JDWP::Append2BE(bytes, method_names.IndexOf(mh.GetName()));
3114 JDWP::Append2BE(bytes, filenames.IndexOf(mh.GetDeclaringClassSourceFile()));
Elliott Hughes545a0642011-11-08 19:10:03 -08003115 JDWP::Append2BE(bytes, record->stack[stack_frame].LineNumber());
3116 }
3117
3118 idx = (idx + 1) & (kNumAllocRecords-1);
3119 }
3120
3121 // (xb) class name strings
3122 // (xb) method name strings
3123 // (xb) source file strings
3124 JDWP::Set4BE(&bytes[string_table_offset], bytes.size());
3125 class_names.WriteTo(bytes);
3126 method_names.WriteTo(bytes);
3127 filenames.WriteTo(bytes);
3128
3129 JNIEnv* env = Thread::Current()->GetJniEnv();
3130 jbyteArray result = env->NewByteArray(bytes.size());
3131 if (result != NULL) {
3132 env->SetByteArrayRegion(result, 0, bytes.size(), reinterpret_cast<const jbyte*>(&bytes[0]));
3133 }
3134 return result;
3135}
3136
Elliott Hughes872d4ec2011-10-21 17:07:15 -07003137} // namespace art