blob: e928b46a6a4f6a302701fdf9deb8786c23f6a3cd [file] [log] [blame]
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001/*
2 * Copyright (C) 2008 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17#include "debugger.h"
18
Elliott Hughes3bb81562011-10-21 18:52:59 -070019#include <sys/uio.h>
20
Elliott Hughes545a0642011-11-08 19:10:03 -080021#include <set>
22
23#include "class_linker.h"
Elliott Hughes1bba14f2011-12-01 18:00:36 -080024#include "class_loader.h"
Ian Rogers776ac1f2012-04-13 23:36:36 -070025#include "dex_instruction.h"
26#if !defined(ART_USE_LLVM_COMPILER)
27#include "oat/runtime/context.h" // For VmapTable
28#endif
Ian Rogers6d4d9fc2011-11-30 16:24:48 -080029#include "object_utils.h"
Elliott Hughesa0e18062012-04-13 15:59:59 -070030#include "safe_map.h"
31#include "scoped_thread_list_lock.h"
Elliott Hughes6a5bd492011-10-28 14:33:57 -070032#include "ScopedLocalRef.h"
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -070033#include "ScopedPrimitiveArray.h"
Ian Rogers30fab402012-01-23 15:43:46 -080034#include "space.h"
Elliott Hughes47fce012011-10-25 18:37:19 -070035#include "stack_indirect_reference_table.h"
Elliott Hughes475fc232011-10-25 15:00:35 -070036#include "thread_list.h"
Elliott Hugheseac76672012-05-24 21:56:51 -070037#include "well_known_classes.h"
Elliott Hughes475fc232011-10-25 15:00:35 -070038
Elliott Hughes6a5bd492011-10-28 14:33:57 -070039extern "C" void dlmalloc_walk_heap(void(*)(const void*, size_t, const void*, size_t, void*), void*);
40#ifndef HAVE_ANDROID_OS
41void dlmalloc_walk_heap(void(*)(const void*, size_t, const void*, size_t, void*), void*) {
42 // No-op for glibc.
43}
44#endif
45
Elliott Hughes872d4ec2011-10-21 17:07:15 -070046namespace art {
47
Elliott Hughes545a0642011-11-08 19:10:03 -080048static const size_t kMaxAllocRecordStackDepth = 16; // Max 255.
49static const size_t kNumAllocRecords = 512; // Must be power of 2.
50
Elliott Hughes436e3722012-02-17 20:01:47 -080051static const uintptr_t kInvalidId = 1;
52static const Object* kInvalidObject = reinterpret_cast<Object*>(kInvalidId);
53
Elliott Hughes475fc232011-10-25 15:00:35 -070054class ObjectRegistry {
55 public:
56 ObjectRegistry() : lock_("ObjectRegistry lock") {
57 }
58
59 JDWP::ObjectId Add(Object* o) {
60 if (o == NULL) {
61 return 0;
62 }
63 JDWP::ObjectId id = static_cast<JDWP::ObjectId>(reinterpret_cast<uintptr_t>(o));
64 MutexLock mu(lock_);
Elliott Hughesa0e18062012-04-13 15:59:59 -070065 map_.Overwrite(id, o);
Elliott Hughes475fc232011-10-25 15:00:35 -070066 return id;
67 }
68
Elliott Hughes234ab152011-10-26 14:02:26 -070069 void Clear() {
70 MutexLock mu(lock_);
71 LOG(DEBUG) << "Debugger has detached; object registry had " << map_.size() << " entries";
72 map_.clear();
73 }
74
Elliott Hughes475fc232011-10-25 15:00:35 -070075 bool Contains(JDWP::ObjectId id) {
76 MutexLock mu(lock_);
77 return map_.find(id) != map_.end();
78 }
79
Elliott Hughesa2155262011-11-16 16:26:58 -080080 template<typename T> T Get(JDWP::ObjectId id) {
Elliott Hughes436e3722012-02-17 20:01:47 -080081 if (id == 0) {
82 return NULL;
83 }
84
Elliott Hughesa2155262011-11-16 16:26:58 -080085 MutexLock mu(lock_);
Elliott Hughesa0e18062012-04-13 15:59:59 -070086 typedef SafeMap<JDWP::ObjectId, Object*>::iterator It; // C++0x auto
Elliott Hughesa2155262011-11-16 16:26:58 -080087 It it = map_.find(id);
Elliott Hughes436e3722012-02-17 20:01:47 -080088 return (it != map_.end()) ? reinterpret_cast<T>(it->second) : reinterpret_cast<T>(kInvalidId);
Elliott Hughesa2155262011-11-16 16:26:58 -080089 }
90
Elliott Hughesbfe487b2011-10-26 15:48:55 -070091 void VisitRoots(Heap::RootVisitor* visitor, void* arg) {
92 MutexLock mu(lock_);
Elliott Hughesa0e18062012-04-13 15:59:59 -070093 typedef SafeMap<JDWP::ObjectId, Object*>::iterator It; // C++0x auto
Elliott Hughesbfe487b2011-10-26 15:48:55 -070094 for (It it = map_.begin(); it != map_.end(); ++it) {
95 visitor(it->second, arg);
96 }
97 }
98
Elliott Hughes475fc232011-10-25 15:00:35 -070099 private:
100 Mutex lock_;
Elliott Hughesa0e18062012-04-13 15:59:59 -0700101 SafeMap<JDWP::ObjectId, Object*> map_;
Elliott Hughes475fc232011-10-25 15:00:35 -0700102};
103
Elliott Hughes545a0642011-11-08 19:10:03 -0800104struct AllocRecordStackTraceElement {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800105 Method* method;
Elliott Hughes545a0642011-11-08 19:10:03 -0800106 uintptr_t raw_pc;
107
108 int32_t LineNumber() const {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800109 return MethodHelper(method).GetLineNumFromNativePC(raw_pc);
Elliott Hughes545a0642011-11-08 19:10:03 -0800110 }
111};
112
113struct AllocRecord {
114 Class* type;
115 size_t byte_count;
116 uint16_t thin_lock_id;
117 AllocRecordStackTraceElement stack[kMaxAllocRecordStackDepth]; // Unused entries have NULL method.
118
119 size_t GetDepth() {
120 size_t depth = 0;
121 while (depth < kMaxAllocRecordStackDepth && stack[depth].method != NULL) {
122 ++depth;
123 }
124 return depth;
125 }
126};
127
Elliott Hughes86964332012-02-15 19:37:42 -0800128struct Breakpoint {
129 Method* method;
Elliott Hughesa656a0f2012-02-21 18:03:44 -0800130 uint32_t dex_pc;
131 Breakpoint(Method* method, uint32_t dex_pc) : method(method), dex_pc(dex_pc) {}
Elliott Hughes86964332012-02-15 19:37:42 -0800132};
133
134static std::ostream& operator<<(std::ostream& os, const Breakpoint& rhs) {
Elliott Hughes229feb72012-02-23 13:33:29 -0800135 os << StringPrintf("Breakpoint[%s @%#x]", PrettyMethod(rhs.method).c_str(), rhs.dex_pc);
Elliott Hughes86964332012-02-15 19:37:42 -0800136 return os;
137}
138
139struct SingleStepControl {
140 // Are we single-stepping right now?
141 bool is_active;
142 Thread* thread;
143
144 JDWP::JdwpStepSize step_size;
145 JDWP::JdwpStepDepth step_depth;
146
147 const Method* method;
Elliott Hughes2435a572012-02-17 16:07:41 -0800148 int32_t line_number; // Or -1 for native methods.
149 std::set<uint32_t> dex_pcs;
Elliott Hughes86964332012-02-15 19:37:42 -0800150 int stack_depth;
151};
152
Elliott Hughes4ffd3132011-10-24 12:06:42 -0700153// JDWP is allowed unless the Zygote forbids it.
154static bool gJdwpAllowed = true;
155
Elliott Hughesc0f09332012-03-26 13:27:06 -0700156// Was there a -Xrunjdwp or -agentlib:jdwp= argument on the command line?
Elliott Hughes3bb81562011-10-21 18:52:59 -0700157static bool gJdwpConfigured = false;
158
Elliott Hughesc0f09332012-03-26 13:27:06 -0700159// Broken-down JDWP options. (Only valid if IsJdwpConfigured() is true.)
Elliott Hughes376a7a02011-10-24 18:35:55 -0700160static JDWP::JdwpOptions gJdwpOptions;
Elliott Hughes3bb81562011-10-21 18:52:59 -0700161
162// Runtime JDWP state.
163static JDWP::JdwpState* gJdwpState = NULL;
164static bool gDebuggerConnected; // debugger or DDMS is connected.
165static bool gDebuggerActive; // debugger is making requests.
Elliott Hughes86964332012-02-15 19:37:42 -0800166static bool gDisposed; // debugger called VirtualMachine.Dispose, so we should drop the connection.
Elliott Hughes3bb81562011-10-21 18:52:59 -0700167
Elliott Hughes47fce012011-10-25 18:37:19 -0700168static bool gDdmThreadNotification = false;
169
Elliott Hughes767a1472011-10-26 18:49:02 -0700170// DDMS GC-related settings.
171static Dbg::HpifWhen gDdmHpifWhen = Dbg::HPIF_WHEN_NEVER;
172static Dbg::HpsgWhen gDdmHpsgWhen = Dbg::HPSG_WHEN_NEVER;
173static Dbg::HpsgWhat gDdmHpsgWhat;
174static Dbg::HpsgWhen gDdmNhsgWhen = Dbg::HPSG_WHEN_NEVER;
175static Dbg::HpsgWhat gDdmNhsgWhat;
176
Elliott Hughes475fc232011-10-25 15:00:35 -0700177static ObjectRegistry* gRegistry = NULL;
178
Elliott Hughes545a0642011-11-08 19:10:03 -0800179// Recent allocation tracking.
180static Mutex gAllocTrackerLock("AllocTracker lock");
181AllocRecord* Dbg::recent_allocation_records_ = NULL; // TODO: CircularBuffer<AllocRecord>
182static size_t gAllocRecordHead = 0;
183static size_t gAllocRecordCount = 0;
184
Elliott Hughes86964332012-02-15 19:37:42 -0800185// Breakpoints and single-stepping.
186static Mutex gBreakpointsLock("breakpoints lock");
187static std::vector<Breakpoint> gBreakpoints;
188static SingleStepControl gSingleStepControl;
189
190static bool IsBreakpoint(Method* m, uint32_t dex_pc) {
191 MutexLock mu(gBreakpointsLock);
192 for (size_t i = 0; i < gBreakpoints.size(); ++i) {
Elliott Hughesa656a0f2012-02-21 18:03:44 -0800193 if (gBreakpoints[i].method == m && gBreakpoints[i].dex_pc == dex_pc) {
Elliott Hughes86964332012-02-15 19:37:42 -0800194 VLOG(jdwp) << "Hit breakpoint #" << i << ": " << gBreakpoints[i];
195 return true;
196 }
197 }
198 return false;
199}
200
Elliott Hughes436e3722012-02-17 20:01:47 -0800201static Array* DecodeArray(JDWP::RefTypeId id, JDWP::JdwpError& status) {
202 Object* o = gRegistry->Get<Object*>(id);
203 if (o == NULL || o == kInvalidObject) {
204 status = JDWP::ERR_INVALID_OBJECT;
205 return NULL;
206 }
207 if (!o->IsArrayInstance()) {
208 status = JDWP::ERR_INVALID_ARRAY;
209 return NULL;
210 }
211 status = JDWP::ERR_NONE;
212 return o->AsArray();
213}
214
215static Class* DecodeClass(JDWP::RefTypeId id, JDWP::JdwpError& status) {
216 Object* o = gRegistry->Get<Object*>(id);
217 if (o == NULL || o == kInvalidObject) {
218 status = JDWP::ERR_INVALID_OBJECT;
219 return NULL;
220 }
221 if (!o->IsClass()) {
222 status = JDWP::ERR_INVALID_CLASS;
223 return NULL;
224 }
225 status = JDWP::ERR_NONE;
226 return o->AsClass();
227}
228
229static Thread* DecodeThread(JDWP::ObjectId threadId) {
230 Object* thread_peer = gRegistry->Get<Object*>(threadId);
231 if (thread_peer == NULL || thread_peer == kInvalidObject) {
232 return NULL;
233 }
234 return Thread::FromManagedThread(thread_peer);
235}
236
Elliott Hughes24437992011-11-30 14:49:33 -0800237static JDWP::JdwpTag BasicTagFromDescriptor(const char* descriptor) {
238 // JDWP deliberately uses the descriptor characters' ASCII values for its enum.
239 // Note that by "basic" we mean that we don't get more specific than JT_OBJECT.
240 return static_cast<JDWP::JdwpTag>(descriptor[0]);
241}
242
243static JDWP::JdwpTag TagFromClass(Class* c) {
Elliott Hughes86b00102011-12-05 17:54:26 -0800244 CHECK(c != NULL);
Elliott Hughes24437992011-11-30 14:49:33 -0800245 if (c->IsArrayClass()) {
246 return JDWP::JT_ARRAY;
247 }
248
Elliott Hughes3d30d9b2011-12-07 17:35:48 -0800249 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
Elliott Hughes24437992011-11-30 14:49:33 -0800250 if (c->IsStringClass()) {
251 return JDWP::JT_STRING;
252 } else if (c->IsClassClass()) {
253 return JDWP::JT_CLASS_OBJECT;
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -0800254 } else if (class_linker->FindSystemClass("Ljava/lang/Thread;")->IsAssignableFrom(c)) {
Elliott Hughes24437992011-11-30 14:49:33 -0800255 return JDWP::JT_THREAD;
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -0800256 } else if (class_linker->FindSystemClass("Ljava/lang/ThreadGroup;")->IsAssignableFrom(c)) {
Elliott Hughes24437992011-11-30 14:49:33 -0800257 return JDWP::JT_THREAD_GROUP;
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -0800258 } else if (class_linker->FindSystemClass("Ljava/lang/ClassLoader;")->IsAssignableFrom(c)) {
Elliott Hughes24437992011-11-30 14:49:33 -0800259 return JDWP::JT_CLASS_LOADER;
Elliott Hughes24437992011-11-30 14:49:33 -0800260 } else {
261 return JDWP::JT_OBJECT;
262 }
263}
264
265/*
266 * Objects declared to hold Object might actually hold a more specific
267 * type. The debugger may take a special interest in these (e.g. it
268 * wants to display the contents of Strings), so we want to return an
269 * appropriate tag.
270 *
271 * Null objects are tagged JT_OBJECT.
272 */
273static JDWP::JdwpTag TagFromObject(const Object* o) {
274 return (o == NULL) ? JDWP::JT_OBJECT : TagFromClass(o->GetClass());
275}
276
277static bool IsPrimitiveTag(JDWP::JdwpTag tag) {
278 switch (tag) {
279 case JDWP::JT_BOOLEAN:
280 case JDWP::JT_BYTE:
281 case JDWP::JT_CHAR:
282 case JDWP::JT_FLOAT:
283 case JDWP::JT_DOUBLE:
284 case JDWP::JT_INT:
285 case JDWP::JT_LONG:
286 case JDWP::JT_SHORT:
287 case JDWP::JT_VOID:
288 return true;
289 default:
290 return false;
291 }
292}
293
Elliott Hughes3bb81562011-10-21 18:52:59 -0700294/*
295 * Handle one of the JDWP name/value pairs.
296 *
297 * JDWP options are:
298 * help: if specified, show help message and bail
299 * transport: may be dt_socket or dt_shmem
300 * address: for dt_socket, "host:port", or just "port" when listening
301 * server: if "y", wait for debugger to attach; if "n", attach to debugger
302 * timeout: how long to wait for debugger to connect / listen
303 *
304 * Useful with server=n (these aren't supported yet):
305 * onthrow=<exception-name>: connect to debugger when exception thrown
306 * onuncaught=y|n: connect to debugger when uncaught exception thrown
307 * launch=<command-line>: launch the debugger itself
308 *
309 * The "transport" option is required, as is "address" if server=n.
310 */
311static bool ParseJdwpOption(const std::string& name, const std::string& value) {
312 if (name == "transport") {
313 if (value == "dt_socket") {
Elliott Hughes376a7a02011-10-24 18:35:55 -0700314 gJdwpOptions.transport = JDWP::kJdwpTransportSocket;
Elliott Hughes3bb81562011-10-21 18:52:59 -0700315 } else if (value == "dt_android_adb") {
Elliott Hughes376a7a02011-10-24 18:35:55 -0700316 gJdwpOptions.transport = JDWP::kJdwpTransportAndroidAdb;
Elliott Hughes3bb81562011-10-21 18:52:59 -0700317 } else {
318 LOG(ERROR) << "JDWP transport not supported: " << value;
319 return false;
320 }
321 } else if (name == "server") {
322 if (value == "n") {
Elliott Hughes376a7a02011-10-24 18:35:55 -0700323 gJdwpOptions.server = false;
Elliott Hughes3bb81562011-10-21 18:52:59 -0700324 } else if (value == "y") {
Elliott Hughes376a7a02011-10-24 18:35:55 -0700325 gJdwpOptions.server = true;
Elliott Hughes3bb81562011-10-21 18:52:59 -0700326 } else {
327 LOG(ERROR) << "JDWP option 'server' must be 'y' or 'n'";
328 return false;
329 }
330 } else if (name == "suspend") {
331 if (value == "n") {
Elliott Hughes376a7a02011-10-24 18:35:55 -0700332 gJdwpOptions.suspend = false;
Elliott Hughes3bb81562011-10-21 18:52:59 -0700333 } else if (value == "y") {
Elliott Hughes376a7a02011-10-24 18:35:55 -0700334 gJdwpOptions.suspend = true;
Elliott Hughes3bb81562011-10-21 18:52:59 -0700335 } else {
336 LOG(ERROR) << "JDWP option 'suspend' must be 'y' or 'n'";
337 return false;
338 }
339 } else if (name == "address") {
340 /* this is either <port> or <host>:<port> */
341 std::string port_string;
Elliott Hughes376a7a02011-10-24 18:35:55 -0700342 gJdwpOptions.host.clear();
Elliott Hughes3bb81562011-10-21 18:52:59 -0700343 std::string::size_type colon = value.find(':');
344 if (colon != std::string::npos) {
Elliott Hughes376a7a02011-10-24 18:35:55 -0700345 gJdwpOptions.host = value.substr(0, colon);
Elliott Hughes3bb81562011-10-21 18:52:59 -0700346 port_string = value.substr(colon + 1);
347 } else {
348 port_string = value;
349 }
350 if (port_string.empty()) {
351 LOG(ERROR) << "JDWP address missing port: " << value;
352 return false;
353 }
354 char* end;
Elliott Hughesba8eee12012-01-24 20:25:24 -0800355 uint64_t port = strtoul(port_string.c_str(), &end, 10);
356 if (*end != '\0' || port > 0xffff) {
Elliott Hughes3bb81562011-10-21 18:52:59 -0700357 LOG(ERROR) << "JDWP address has junk in port field: " << value;
358 return false;
359 }
Elliott Hughes376a7a02011-10-24 18:35:55 -0700360 gJdwpOptions.port = port;
Elliott Hughes3bb81562011-10-21 18:52:59 -0700361 } else if (name == "launch" || name == "onthrow" || name == "oncaught" || name == "timeout") {
362 /* valid but unsupported */
363 LOG(INFO) << "Ignoring JDWP option '" << name << "'='" << value << "'";
364 } else {
365 LOG(INFO) << "Ignoring unrecognized JDWP option '" << name << "'='" << value << "'";
366 }
367
368 return true;
369}
370
371/*
372 * Parse the latter half of a -Xrunjdwp/-agentlib:jdwp= string, e.g.:
373 * "transport=dt_socket,address=8000,server=y,suspend=n"
374 */
375bool Dbg::ParseJdwpOptions(const std::string& options) {
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -0800376 VLOG(jdwp) << "ParseJdwpOptions: " << options;
Elliott Hughes47fce012011-10-25 18:37:19 -0700377
Elliott Hughes3bb81562011-10-21 18:52:59 -0700378 std::vector<std::string> pairs;
379 Split(options, ',', pairs);
380
381 for (size_t i = 0; i < pairs.size(); ++i) {
382 std::string::size_type equals = pairs[i].find('=');
383 if (equals == std::string::npos) {
384 LOG(ERROR) << "Can't parse JDWP option '" << pairs[i] << "' in '" << options << "'";
385 return false;
386 }
387 ParseJdwpOption(pairs[i].substr(0, equals), pairs[i].substr(equals + 1));
388 }
389
Elliott Hughes376a7a02011-10-24 18:35:55 -0700390 if (gJdwpOptions.transport == JDWP::kJdwpTransportUnknown) {
Elliott Hughes3bb81562011-10-21 18:52:59 -0700391 LOG(ERROR) << "Must specify JDWP transport: " << options;
392 }
Elliott Hughes376a7a02011-10-24 18:35:55 -0700393 if (!gJdwpOptions.server && (gJdwpOptions.host.empty() || gJdwpOptions.port == 0)) {
Elliott Hughes3bb81562011-10-21 18:52:59 -0700394 LOG(ERROR) << "Must specify JDWP host and port when server=n: " << options;
395 return false;
396 }
397
398 gJdwpConfigured = true;
399 return true;
400}
401
Elliott Hughesd1cc8362011-10-24 16:58:50 -0700402void Dbg::StartJdwp() {
Elliott Hughesc0f09332012-03-26 13:27:06 -0700403 if (!gJdwpAllowed || !IsJdwpConfigured()) {
Elliott Hughes376a7a02011-10-24 18:35:55 -0700404 // No JDWP for you!
405 return;
406 }
407
Elliott Hughes475fc232011-10-25 15:00:35 -0700408 CHECK(gRegistry == NULL);
409 gRegistry = new ObjectRegistry;
410
Elliott Hughesd1cc8362011-10-24 16:58:50 -0700411 // Init JDWP if the debugger is enabled. This may connect out to a
412 // debugger, passively listen for a debugger, or block waiting for a
413 // debugger.
Elliott Hughes376a7a02011-10-24 18:35:55 -0700414 gJdwpState = JDWP::JdwpState::Create(&gJdwpOptions);
415 if (gJdwpState == NULL) {
Elliott Hughesf8a2df72011-12-01 12:19:54 -0800416 // We probably failed because some other process has the port already, which means that
417 // if we don't abort the user is likely to think they're talking to us when they're actually
418 // talking to that other process.
Elliott Hughes3d30d9b2011-12-07 17:35:48 -0800419 LOG(FATAL) << "Debugger thread failed to initialize";
Elliott Hughesd1cc8362011-10-24 16:58:50 -0700420 }
421
422 // If a debugger has already attached, send the "welcome" message.
423 // This may cause us to suspend all threads.
Elliott Hughes376a7a02011-10-24 18:35:55 -0700424 if (gJdwpState->IsActive()) {
Elliott Hughes34e06962012-04-09 13:55:55 -0700425 //ScopedThreadStateChange tsc(Thread::Current(), kRunnable);
Elliott Hughes376a7a02011-10-24 18:35:55 -0700426 if (!gJdwpState->PostVMStart()) {
Elliott Hughes3d30d9b2011-12-07 17:35:48 -0800427 LOG(WARNING) << "Failed to post 'start' message to debugger";
Elliott Hughesd1cc8362011-10-24 16:58:50 -0700428 }
429 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700430}
431
Elliott Hughesd1cc8362011-10-24 16:58:50 -0700432void Dbg::StopJdwp() {
Elliott Hughes376a7a02011-10-24 18:35:55 -0700433 delete gJdwpState;
Elliott Hughes475fc232011-10-25 15:00:35 -0700434 delete gRegistry;
435 gRegistry = NULL;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700436}
437
Elliott Hughes767a1472011-10-26 18:49:02 -0700438void Dbg::GcDidFinish() {
439 if (gDdmHpifWhen != HPIF_WHEN_NEVER) {
Elliott Hughes81ff3182012-03-23 20:35:56 -0700440 LOG(DEBUG) << "Sending heap info to DDM";
Elliott Hughes7162ad92011-10-27 14:08:42 -0700441 DdmSendHeapInfo(gDdmHpifWhen);
Elliott Hughes767a1472011-10-26 18:49:02 -0700442 }
443 if (gDdmHpsgWhen != HPSG_WHEN_NEVER) {
Elliott Hughes81ff3182012-03-23 20:35:56 -0700444 LOG(DEBUG) << "Dumping heap to DDM";
Elliott Hughes6a5bd492011-10-28 14:33:57 -0700445 DdmSendHeapSegments(false);
Elliott Hughes767a1472011-10-26 18:49:02 -0700446 }
447 if (gDdmNhsgWhen != HPSG_WHEN_NEVER) {
448 LOG(DEBUG) << "Dumping native heap to DDM";
Elliott Hughes6a5bd492011-10-28 14:33:57 -0700449 DdmSendHeapSegments(true);
Elliott Hughes767a1472011-10-26 18:49:02 -0700450 }
451}
452
Elliott Hughes4ffd3132011-10-24 12:06:42 -0700453void Dbg::SetJdwpAllowed(bool allowed) {
454 gJdwpAllowed = allowed;
455}
456
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700457DebugInvokeReq* Dbg::GetInvokeReq() {
Elliott Hughes475fc232011-10-25 15:00:35 -0700458 return Thread::Current()->GetInvokeReq();
459}
460
461Thread* Dbg::GetDebugThread() {
462 return (gJdwpState != NULL) ? gJdwpState->GetDebugThread() : NULL;
463}
464
465void Dbg::ClearWaitForEventThread() {
466 gJdwpState->ClearWaitForEventThread();
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700467}
468
469void Dbg::Connected() {
Elliott Hughes3bb81562011-10-21 18:52:59 -0700470 CHECK(!gDebuggerConnected);
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -0800471 VLOG(jdwp) << "JDWP has attached";
Elliott Hughes3bb81562011-10-21 18:52:59 -0700472 gDebuggerConnected = true;
Elliott Hughes86964332012-02-15 19:37:42 -0800473 gDisposed = false;
474}
475
476void Dbg::Disposed() {
477 gDisposed = true;
478}
479
480bool Dbg::IsDisposed() {
481 return gDisposed;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700482}
483
Elliott Hughesc0f09332012-03-26 13:27:06 -0700484static void SetDebuggerUpdatesEnabledCallback(Thread* t, void* user_data) {
485 t->SetDebuggerUpdatesEnabled(*reinterpret_cast<bool*>(user_data));
486}
487
488static void SetDebuggerUpdatesEnabled(bool enabled) {
489 Runtime* runtime = Runtime::Current();
490 ScopedThreadListLock thread_list_lock;
491 runtime->GetThreadList()->ForEach(SetDebuggerUpdatesEnabledCallback, &enabled);
492}
493
Elliott Hughesa2155262011-11-16 16:26:58 -0800494void Dbg::GoActive() {
495 // Enable all debugging features, including scans for breakpoints.
496 // This is a no-op if we're already active.
497 // Only called from the JDWP handler thread.
498 if (gDebuggerActive) {
499 return;
500 }
501
502 LOG(INFO) << "Debugger is active";
503
Elliott Hughesc0f09332012-03-26 13:27:06 -0700504 {
505 // TODO: dalvik only warned if there were breakpoints left over. clear in Dbg::Disconnected?
506 MutexLock mu(gBreakpointsLock);
507 CHECK_EQ(gBreakpoints.size(), 0U);
508 }
Elliott Hughesa2155262011-11-16 16:26:58 -0800509
510 gDebuggerActive = true;
Elliott Hughesc0f09332012-03-26 13:27:06 -0700511 SetDebuggerUpdatesEnabled(true);
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700512}
513
514void Dbg::Disconnected() {
Elliott Hughes234ab152011-10-26 14:02:26 -0700515 CHECK(gDebuggerConnected);
516
Elliott Hughesc0f09332012-03-26 13:27:06 -0700517 LOG(INFO) << "Debugger is no longer active";
Elliott Hughes234ab152011-10-26 14:02:26 -0700518
Elliott Hughesc0f09332012-03-26 13:27:06 -0700519 gDebuggerActive = false;
520 SetDebuggerUpdatesEnabled(false);
Elliott Hughes234ab152011-10-26 14:02:26 -0700521
522 gRegistry->Clear();
523 gDebuggerConnected = false;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700524}
525
Elliott Hughesc0f09332012-03-26 13:27:06 -0700526bool Dbg::IsDebuggerActive() {
Elliott Hughes3bb81562011-10-21 18:52:59 -0700527 return gDebuggerActive;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700528}
529
Elliott Hughesc0f09332012-03-26 13:27:06 -0700530bool Dbg::IsJdwpConfigured() {
Elliott Hughes3bb81562011-10-21 18:52:59 -0700531 return gJdwpConfigured;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700532}
533
534int64_t Dbg::LastDebuggerActivity() {
Elliott Hughesca951522011-12-05 12:01:32 -0800535 return gJdwpState->LastDebuggerActivity();
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700536}
537
538int Dbg::ThreadRunning() {
Elliott Hughes34e06962012-04-09 13:55:55 -0700539 return static_cast<int>(Thread::Current()->SetState(kRunnable));
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700540}
541
542int Dbg::ThreadWaiting() {
Elliott Hughes34e06962012-04-09 13:55:55 -0700543 return static_cast<int>(Thread::Current()->SetState(kVmWait));
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700544}
545
Elliott Hughes6ba581a2011-10-25 11:45:35 -0700546int Dbg::ThreadContinuing(int new_state) {
Elliott Hughes34e06962012-04-09 13:55:55 -0700547 return static_cast<int>(Thread::Current()->SetState(static_cast<ThreadState>(new_state)));
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700548}
549
550void Dbg::UndoDebuggerSuspensions() {
Elliott Hughes234ab152011-10-26 14:02:26 -0700551 Runtime::Current()->GetThreadList()->UndoDebuggerSuspensions();
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700552}
553
554void Dbg::Exit(int status) {
Elliott Hughes1bba14f2011-12-01 18:00:36 -0800555 exit(status); // This is all dalvik did.
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700556}
557
Elliott Hughesbfe487b2011-10-26 15:48:55 -0700558void Dbg::VisitRoots(Heap::RootVisitor* visitor, void* arg) {
559 if (gRegistry != NULL) {
560 gRegistry->VisitRoots(visitor, arg);
561 }
562}
563
Elliott Hughesc308a5d2012-02-16 17:12:06 -0800564std::string Dbg::GetClassName(JDWP::RefTypeId classId) {
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -0800565 Object* o = gRegistry->Get<Object*>(classId);
Elliott Hughes436e3722012-02-17 20:01:47 -0800566 if (o == NULL) {
567 return "NULL";
568 }
569 if (o == kInvalidObject) {
570 return StringPrintf("invalid object %p", reinterpret_cast<void*>(classId));
571 }
572 if (!o->IsClass()) {
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -0800573 return StringPrintf("non-class %p", o); // This is only used for debugging output anyway.
574 }
Elliott Hughesc308a5d2012-02-16 17:12:06 -0800575 return DescriptorToName(ClassHelper(o->AsClass()).GetDescriptor());
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700576}
577
Elliott Hughes436e3722012-02-17 20:01:47 -0800578JDWP::JdwpError Dbg::GetClassObject(JDWP::RefTypeId id, JDWP::ObjectId& classObjectId) {
579 JDWP::JdwpError status;
580 Class* c = DecodeClass(id, status);
581 if (c == NULL) {
582 return status;
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -0800583 }
Elliott Hughes436e3722012-02-17 20:01:47 -0800584 classObjectId = gRegistry->Add(c);
585 return JDWP::ERR_NONE;
Elliott Hughes86964332012-02-15 19:37:42 -0800586}
587
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -0800588JDWP::JdwpError Dbg::GetSuperclass(JDWP::RefTypeId id, JDWP::RefTypeId& superclassId) {
589 JDWP::JdwpError status;
590 Class* c = DecodeClass(id, status);
591 if (c == NULL) {
592 return status;
593 }
594 if (c->IsInterface()) {
595 // http://code.google.com/p/android/issues/detail?id=20856
Elliott Hughesa0933622012-04-17 10:46:02 -0700596 superclassId = 0;
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -0800597 } else {
598 superclassId = gRegistry->Add(c->GetSuperClass());
599 }
600 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700601}
602
Elliott Hughes436e3722012-02-17 20:01:47 -0800603JDWP::JdwpError Dbg::GetClassLoader(JDWP::RefTypeId id, JDWP::ExpandBuf* pReply) {
Elliott Hughes1bba14f2011-12-01 18:00:36 -0800604 Object* o = gRegistry->Get<Object*>(id);
Elliott Hughes436e3722012-02-17 20:01:47 -0800605 if (o == NULL || o == kInvalidObject) {
606 return JDWP::ERR_INVALID_OBJECT;
607 }
608 expandBufAddObjectId(pReply, gRegistry->Add(o->GetClass()->GetClassLoader()));
609 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700610}
611
Elliott Hughes436e3722012-02-17 20:01:47 -0800612JDWP::JdwpError Dbg::GetModifiers(JDWP::RefTypeId id, JDWP::ExpandBuf* pReply) {
613 JDWP::JdwpError status;
614 Class* c = DecodeClass(id, status);
615 if (c == NULL) {
616 return status;
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -0800617 }
Elliott Hughes436e3722012-02-17 20:01:47 -0800618
619 uint32_t access_flags = c->GetAccessFlags() & kAccJavaFlagsMask;
620
621 // Set ACC_SUPER; dex files don't contain this flag, but all classes are supposed to have it set.
622 // Class.getModifiers doesn't return it, but JDWP does, so we set it here.
623 access_flags |= kAccSuper;
624
625 expandBufAdd4BE(pReply, access_flags);
626
627 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700628}
629
Elliott Hughes436e3722012-02-17 20:01:47 -0800630JDWP::JdwpError Dbg::GetReflectedType(JDWP::RefTypeId classId, JDWP::ExpandBuf* pReply) {
631 JDWP::JdwpError status;
632 Class* c = DecodeClass(classId, status);
633 if (c == NULL) {
634 return status;
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -0800635 }
Elliott Hughes436e3722012-02-17 20:01:47 -0800636
637 expandBufAdd1(pReply, c->IsInterface() ? JDWP::TT_INTERFACE : JDWP::TT_CLASS);
638 expandBufAddRefTypeId(pReply, classId);
639 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700640}
641
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -0800642void Dbg::GetClassList(std::vector<JDWP::RefTypeId>& classes) {
Elliott Hughesa2155262011-11-16 16:26:58 -0800643 // Get the complete list of reference classes (i.e. all classes except
644 // the primitive types).
645 // Returns a newly-allocated buffer full of RefTypeId values.
646 struct ClassListCreator {
Elliott Hughesba8eee12012-01-24 20:25:24 -0800647 explicit ClassListCreator(std::vector<JDWP::RefTypeId>& classes) : classes(classes) {
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -0800648 }
649
Elliott Hughesa2155262011-11-16 16:26:58 -0800650 static bool Visit(Class* c, void* arg) {
651 return reinterpret_cast<ClassListCreator*>(arg)->Visit(c);
652 }
653
654 bool Visit(Class* c) {
655 if (!c->IsPrimitive()) {
656 classes.push_back(static_cast<JDWP::RefTypeId>(gRegistry->Add(c)));
657 }
658 return true;
659 }
660
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -0800661 std::vector<JDWP::RefTypeId>& classes;
Elliott Hughesa2155262011-11-16 16:26:58 -0800662 };
663
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -0800664 ClassListCreator clc(classes);
Elliott Hughesa2155262011-11-16 16:26:58 -0800665 Runtime::Current()->GetClassLinker()->VisitClasses(ClassListCreator::Visit, &clc);
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700666}
667
Elliott Hughes436e3722012-02-17 20:01:47 -0800668JDWP::JdwpError Dbg::GetClassInfo(JDWP::RefTypeId classId, JDWP::JdwpTypeTag* pTypeTag, uint32_t* pStatus, std::string* pDescriptor) {
669 JDWP::JdwpError status;
670 Class* c = DecodeClass(classId, status);
671 if (c == NULL) {
672 return status;
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -0800673 }
674
Elliott Hughesa2155262011-11-16 16:26:58 -0800675 if (c->IsArrayClass()) {
676 *pStatus = JDWP::CS_VERIFIED | JDWP::CS_PREPARED;
677 *pTypeTag = JDWP::TT_ARRAY;
678 } else {
679 if (c->IsErroneous()) {
680 *pStatus = JDWP::CS_ERROR;
681 } else {
682 *pStatus = JDWP::CS_VERIFIED | JDWP::CS_PREPARED | JDWP::CS_INITIALIZED;
683 }
684 *pTypeTag = c->IsInterface() ? JDWP::TT_INTERFACE : JDWP::TT_CLASS;
685 }
686
687 if (pDescriptor != NULL) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800688 *pDescriptor = ClassHelper(c).GetDescriptor();
Elliott Hughesa2155262011-11-16 16:26:58 -0800689 }
Elliott Hughes436e3722012-02-17 20:01:47 -0800690 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700691}
692
Elliott Hughesc3b77c72011-12-15 20:56:48 -0800693void Dbg::FindLoadedClassBySignature(const char* descriptor, std::vector<JDWP::RefTypeId>& ids) {
Elliott Hughes6fa602d2011-12-02 17:54:25 -0800694 std::vector<Class*> classes;
695 Runtime::Current()->GetClassLinker()->LookupClasses(descriptor, classes);
696 ids.clear();
697 for (size_t i = 0; i < classes.size(); ++i) {
698 ids.push_back(gRegistry->Add(classes[i]));
699 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700700}
701
Elliott Hughes2435a572012-02-17 16:07:41 -0800702JDWP::JdwpError Dbg::GetReferenceType(JDWP::ObjectId objectId, JDWP::ExpandBuf* pReply) {
Elliott Hughes499c5132011-11-17 14:55:11 -0800703 Object* o = gRegistry->Get<Object*>(objectId);
Elliott Hughes436e3722012-02-17 20:01:47 -0800704 if (o == NULL || o == kInvalidObject) {
Elliott Hughes2435a572012-02-17 16:07:41 -0800705 return JDWP::ERR_INVALID_OBJECT;
Elliott Hughes499c5132011-11-17 14:55:11 -0800706 }
Elliott Hughes2435a572012-02-17 16:07:41 -0800707
708 JDWP::JdwpTypeTag type_tag;
709 if (o->GetClass()->IsArrayClass()) {
710 type_tag = JDWP::TT_ARRAY;
711 } else if (o->GetClass()->IsInterface()) {
712 type_tag = JDWP::TT_INTERFACE;
713 } else {
714 type_tag = JDWP::TT_CLASS;
715 }
716 JDWP::RefTypeId type_id = gRegistry->Add(o->GetClass());
717
718 expandBufAdd1(pReply, type_tag);
719 expandBufAddRefTypeId(pReply, type_id);
720
721 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700722}
723
Elliott Hughes436e3722012-02-17 20:01:47 -0800724JDWP::JdwpError Dbg::GetSignature(JDWP::RefTypeId classId, std::string& signature) {
Elliott Hughes1fe7afb2012-02-13 17:23:03 -0800725 JDWP::JdwpError status;
Elliott Hughes436e3722012-02-17 20:01:47 -0800726 Class* c = DecodeClass(classId, status);
Elliott Hughes1fe7afb2012-02-13 17:23:03 -0800727 if (c == NULL) {
728 return status;
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -0800729 }
Elliott Hughes1fe7afb2012-02-13 17:23:03 -0800730 signature = ClassHelper(c).GetDescriptor();
731 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700732}
733
Elliott Hughes436e3722012-02-17 20:01:47 -0800734JDWP::JdwpError Dbg::GetSourceFile(JDWP::RefTypeId classId, std::string& result) {
735 JDWP::JdwpError status;
736 Class* c = DecodeClass(classId, status);
737 if (c == NULL) {
738 return status;
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -0800739 }
Elliott Hughes436e3722012-02-17 20:01:47 -0800740 result = ClassHelper(c).GetSourceFile();
741 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700742}
743
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700744uint8_t Dbg::GetObjectTag(JDWP::ObjectId objectId) {
Elliott Hughes24437992011-11-30 14:49:33 -0800745 Object* o = gRegistry->Get<Object*>(objectId);
746 return TagFromObject(o);
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700747}
748
Elliott Hughesaed4be92011-12-02 16:16:23 -0800749size_t Dbg::GetTagWidth(JDWP::JdwpTag tag) {
Elliott Hughesdbb40792011-11-18 17:05:22 -0800750 switch (tag) {
751 case JDWP::JT_VOID:
752 return 0;
753 case JDWP::JT_BYTE:
754 case JDWP::JT_BOOLEAN:
755 return 1;
756 case JDWP::JT_CHAR:
757 case JDWP::JT_SHORT:
758 return 2;
759 case JDWP::JT_FLOAT:
760 case JDWP::JT_INT:
761 return 4;
762 case JDWP::JT_ARRAY:
763 case JDWP::JT_OBJECT:
764 case JDWP::JT_STRING:
765 case JDWP::JT_THREAD:
766 case JDWP::JT_THREAD_GROUP:
767 case JDWP::JT_CLASS_LOADER:
768 case JDWP::JT_CLASS_OBJECT:
769 return sizeof(JDWP::ObjectId);
770 case JDWP::JT_DOUBLE:
771 case JDWP::JT_LONG:
772 return 8;
773 default:
Elliott Hughes3d30d9b2011-12-07 17:35:48 -0800774 LOG(FATAL) << "Unknown tag " << tag;
Elliott Hughesdbb40792011-11-18 17:05:22 -0800775 return -1;
776 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700777}
778
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -0800779JDWP::JdwpError Dbg::GetArrayLength(JDWP::ObjectId arrayId, int& length) {
780 JDWP::JdwpError status;
781 Array* a = DecodeArray(arrayId, status);
782 if (a == NULL) {
783 return status;
Elliott Hughes24437992011-11-30 14:49:33 -0800784 }
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -0800785 length = a->GetLength();
786 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700787}
788
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -0800789JDWP::JdwpError Dbg::OutputArray(JDWP::ObjectId arrayId, int offset, int count, JDWP::ExpandBuf* pReply) {
790 JDWP::JdwpError status;
791 Array* a = DecodeArray(arrayId, status);
792 if (a == NULL) {
793 return status;
794 }
Elliott Hughes24437992011-11-30 14:49:33 -0800795
796 if (offset < 0 || count < 0 || offset > a->GetLength() || a->GetLength() - offset < count) {
797 LOG(WARNING) << __FUNCTION__ << " access out of bounds: offset=" << offset << "; count=" << count;
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -0800798 return JDWP::ERR_INVALID_LENGTH;
Elliott Hughes24437992011-11-30 14:49:33 -0800799 }
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800800 std::string descriptor(ClassHelper(a->GetClass()).GetDescriptor());
Elliott Hughes24437992011-11-30 14:49:33 -0800801 JDWP::JdwpTag tag = BasicTagFromDescriptor(descriptor.c_str() + 1);
802
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -0800803 expandBufAdd1(pReply, tag);
804 expandBufAdd4BE(pReply, count);
805
Elliott Hughes24437992011-11-30 14:49:33 -0800806 if (IsPrimitiveTag(tag)) {
807 size_t width = GetTagWidth(tag);
Elliott Hughes24437992011-11-30 14:49:33 -0800808 uint8_t* dst = expandBufAddSpace(pReply, count * width);
809 if (width == 8) {
Ian Rogersa15e67d2012-02-28 13:51:55 -0800810 const uint64_t* src8 = reinterpret_cast<uint64_t*>(a->GetRawData(sizeof(uint64_t)));
Elliott Hughes24437992011-11-30 14:49:33 -0800811 for (int i = 0; i < count; ++i) JDWP::Write8BE(&dst, src8[offset + i]);
812 } else if (width == 4) {
Ian Rogersa15e67d2012-02-28 13:51:55 -0800813 const uint32_t* src4 = reinterpret_cast<uint32_t*>(a->GetRawData(sizeof(uint32_t)));
Elliott Hughes24437992011-11-30 14:49:33 -0800814 for (int i = 0; i < count; ++i) JDWP::Write4BE(&dst, src4[offset + i]);
815 } else if (width == 2) {
Ian Rogersa15e67d2012-02-28 13:51:55 -0800816 const uint16_t* src2 = reinterpret_cast<uint16_t*>(a->GetRawData(sizeof(uint16_t)));
Elliott Hughes24437992011-11-30 14:49:33 -0800817 for (int i = 0; i < count; ++i) JDWP::Write2BE(&dst, src2[offset + i]);
818 } else {
Ian Rogersa15e67d2012-02-28 13:51:55 -0800819 const uint8_t* src = reinterpret_cast<uint8_t*>(a->GetRawData(sizeof(uint8_t)));
Elliott Hughes24437992011-11-30 14:49:33 -0800820 memcpy(dst, &src[offset * width], count * width);
821 }
822 } else {
823 ObjectArray<Object>* oa = a->AsObjectArray<Object>();
824 for (int i = 0; i < count; ++i) {
Elliott Hughesf03b8f62011-12-02 14:26:25 -0800825 Object* element = oa->Get(offset + i);
Elliott Hughes24437992011-11-30 14:49:33 -0800826 JDWP::JdwpTag specific_tag = (element != NULL) ? TagFromObject(element) : tag;
827 expandBufAdd1(pReply, specific_tag);
828 expandBufAddObjectId(pReply, gRegistry->Add(element));
829 }
830 }
831
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -0800832 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700833}
834
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -0800835JDWP::JdwpError Dbg::SetArrayElements(JDWP::ObjectId arrayId, int offset, int count, const uint8_t* src) {
836 JDWP::JdwpError status;
837 Array* a = DecodeArray(arrayId, status);
838 if (a == NULL) {
839 return status;
840 }
Elliott Hughesf03b8f62011-12-02 14:26:25 -0800841
842 if (offset < 0 || count < 0 || offset > a->GetLength() || a->GetLength() - offset < count) {
843 LOG(WARNING) << __FUNCTION__ << " access out of bounds: offset=" << offset << "; count=" << count;
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -0800844 return JDWP::ERR_INVALID_LENGTH;
Elliott Hughesf03b8f62011-12-02 14:26:25 -0800845 }
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800846 std::string descriptor(ClassHelper(a->GetClass()).GetDescriptor());
Elliott Hughesf03b8f62011-12-02 14:26:25 -0800847 JDWP::JdwpTag tag = BasicTagFromDescriptor(descriptor.c_str() + 1);
848
849 if (IsPrimitiveTag(tag)) {
850 size_t width = GetTagWidth(tag);
Elliott Hughesf03b8f62011-12-02 14:26:25 -0800851 if (width == 8) {
Ian Rogersa15e67d2012-02-28 13:51:55 -0800852 uint8_t* dst = &(reinterpret_cast<uint8_t*>(a->GetRawData(sizeof(uint64_t)))[offset * width]);
Elliott Hughesf03b8f62011-12-02 14:26:25 -0800853 for (int i = 0; i < count; ++i) {
854 // Handle potentially non-aligned memory access one byte at a time for ARM's benefit.
855 uint64_t value;
856 for (size_t j = 0; j < sizeof(uint64_t); ++j) reinterpret_cast<uint8_t*>(&value)[j] = src[j];
857 src += sizeof(uint64_t);
858 JDWP::Write8BE(&dst, value);
859 }
860 } else if (width == 4) {
Ian Rogersa15e67d2012-02-28 13:51:55 -0800861 uint8_t* dst = &(reinterpret_cast<uint8_t*>(a->GetRawData(sizeof(uint32_t)))[offset * width]);
Elliott Hughesf03b8f62011-12-02 14:26:25 -0800862 const uint32_t* src4 = reinterpret_cast<const uint32_t*>(src);
863 for (int i = 0; i < count; ++i) JDWP::Write4BE(&dst, src4[i]);
864 } else if (width == 2) {
Ian Rogersa15e67d2012-02-28 13:51:55 -0800865 uint8_t* dst = &(reinterpret_cast<uint8_t*>(a->GetRawData(sizeof(uint16_t)))[offset * width]);
Elliott Hughesf03b8f62011-12-02 14:26:25 -0800866 const uint16_t* src2 = reinterpret_cast<const uint16_t*>(src);
867 for (int i = 0; i < count; ++i) JDWP::Write2BE(&dst, src2[i]);
868 } else {
Ian Rogersa15e67d2012-02-28 13:51:55 -0800869 uint8_t* dst = &(reinterpret_cast<uint8_t*>(a->GetRawData(sizeof(uint8_t)))[offset * width]);
Elliott Hughesf03b8f62011-12-02 14:26:25 -0800870 memcpy(&dst[offset * width], src, count * width);
871 }
872 } else {
873 ObjectArray<Object>* oa = a->AsObjectArray<Object>();
874 for (int i = 0; i < count; ++i) {
875 JDWP::ObjectId id = JDWP::ReadObjectId(&src);
Elliott Hughes436e3722012-02-17 20:01:47 -0800876 Object* o = gRegistry->Get<Object*>(id);
877 if (o == kInvalidObject) {
878 return JDWP::ERR_INVALID_OBJECT;
879 }
880 oa->Set(offset + i, o);
Elliott Hughesf03b8f62011-12-02 14:26:25 -0800881 }
882 }
883
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -0800884 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700885}
886
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -0800887JDWP::ObjectId Dbg::CreateString(const std::string& str) {
888 return gRegistry->Add(String::AllocFromModifiedUtf8(str.c_str()));
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700889}
890
Elliott Hughes436e3722012-02-17 20:01:47 -0800891JDWP::JdwpError Dbg::CreateObject(JDWP::RefTypeId classId, JDWP::ObjectId& new_object) {
892 JDWP::JdwpError status;
893 Class* c = DecodeClass(classId, status);
894 if (c == NULL) {
895 return status;
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -0800896 }
Elliott Hughes436e3722012-02-17 20:01:47 -0800897 new_object = gRegistry->Add(c->AllocObject());
898 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700899}
900
Elliott Hughesbf13d362011-12-08 15:51:37 -0800901/*
902 * Used by Eclipse's "Display" view to evaluate "new byte[5]" to get "(byte[]) [0, 0, 0, 0, 0]".
903 */
Elliott Hughes436e3722012-02-17 20:01:47 -0800904JDWP::JdwpError Dbg::CreateArrayObject(JDWP::RefTypeId arrayClassId, uint32_t length, JDWP::ObjectId& new_array) {
905 JDWP::JdwpError status;
906 Class* c = DecodeClass(arrayClassId, status);
907 if (c == NULL) {
908 return status;
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -0800909 }
Elliott Hughes436e3722012-02-17 20:01:47 -0800910 new_array = gRegistry->Add(Array::Alloc(c, length));
911 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700912}
913
914bool Dbg::MatchType(JDWP::RefTypeId instClassId, JDWP::RefTypeId classId) {
Elliott Hughes436e3722012-02-17 20:01:47 -0800915 JDWP::JdwpError status;
916 Class* c1 = DecodeClass(instClassId, status);
Elliott Hughesa656a0f2012-02-21 18:03:44 -0800917 CHECK(c1 != NULL);
Elliott Hughes436e3722012-02-17 20:01:47 -0800918 Class* c2 = DecodeClass(classId, status);
Elliott Hughesa656a0f2012-02-21 18:03:44 -0800919 CHECK(c2 != NULL);
920 return c1->IsAssignableFrom(c2);
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700921}
922
Elliott Hughes86964332012-02-15 19:37:42 -0800923static JDWP::FieldId ToFieldId(const Field* f) {
Elliott Hughes03181a82011-11-17 17:22:21 -0800924#ifdef MOVING_GARBAGE_COLLECTOR
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700925 UNIMPLEMENTED(FATAL);
Elliott Hughes03181a82011-11-17 17:22:21 -0800926#else
927 return static_cast<JDWP::FieldId>(reinterpret_cast<uintptr_t>(f));
928#endif
929}
930
Elliott Hughes86964332012-02-15 19:37:42 -0800931static JDWP::MethodId ToMethodId(const Method* m) {
Elliott Hughes03181a82011-11-17 17:22:21 -0800932#ifdef MOVING_GARBAGE_COLLECTOR
933 UNIMPLEMENTED(FATAL);
934#else
935 return static_cast<JDWP::MethodId>(reinterpret_cast<uintptr_t>(m));
936#endif
937}
938
Elliott Hughes86964332012-02-15 19:37:42 -0800939static Field* FromFieldId(JDWP::FieldId fid) {
Elliott Hughesaed4be92011-12-02 16:16:23 -0800940#ifdef MOVING_GARBAGE_COLLECTOR
941 UNIMPLEMENTED(FATAL);
942#else
943 return reinterpret_cast<Field*>(static_cast<uintptr_t>(fid));
944#endif
945}
946
Elliott Hughes86964332012-02-15 19:37:42 -0800947static Method* FromMethodId(JDWP::MethodId mid) {
Elliott Hughes03181a82011-11-17 17:22:21 -0800948#ifdef MOVING_GARBAGE_COLLECTOR
949 UNIMPLEMENTED(FATAL);
950#else
951 return reinterpret_cast<Method*>(static_cast<uintptr_t>(mid));
952#endif
953}
954
Elliott Hughes86964332012-02-15 19:37:42 -0800955static void SetLocation(JDWP::JdwpLocation& location, Method* m, uintptr_t native_pc) {
Elliott Hughes91bf6cd2012-02-14 17:27:48 -0800956 if (m == NULL) {
957 memset(&location, 0, sizeof(location));
958 } else {
959 Class* c = m->GetDeclaringClass();
960 location.typeTag = c->IsInterface() ? JDWP::TT_INTERFACE : JDWP::TT_CLASS;
961 location.classId = gRegistry->Add(c);
962 location.methodId = ToMethodId(m);
Elliott Hughes972a47b2012-02-21 18:16:06 -0800963 location.dex_pc = m->IsNative() ? -1 : m->ToDexPC(native_pc);
Elliott Hughes91bf6cd2012-02-14 17:27:48 -0800964 }
Elliott Hughesd07986f2011-12-06 18:27:45 -0800965}
966
Elliott Hughes436e3722012-02-17 20:01:47 -0800967std::string Dbg::GetMethodName(JDWP::RefTypeId, JDWP::MethodId methodId) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800968 Method* m = FromMethodId(methodId);
969 return MethodHelper(m).GetName();
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700970}
971
Elliott Hughesa2e54f62011-11-17 13:01:30 -0800972/*
973 * Augment the access flags for synthetic methods and fields by setting
974 * the (as described by the spec) "0xf0000000 bit". Also, strip out any
975 * flags not specified by the Java programming language.
976 */
977static uint32_t MangleAccessFlags(uint32_t accessFlags) {
978 accessFlags &= kAccJavaFlagsMask;
979 if ((accessFlags & kAccSynthetic) != 0) {
980 accessFlags |= 0xf0000000;
981 }
982 return accessFlags;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700983}
984
Elliott Hughesdbb40792011-11-18 17:05:22 -0800985static const uint16_t kEclipseWorkaroundSlot = 1000;
986
987/*
988 * Eclipse appears to expect that the "this" reference is in slot zero.
989 * If it's not, the "variables" display will show two copies of "this",
990 * possibly because it gets "this" from SF.ThisObject and then displays
991 * all locals with nonzero slot numbers.
992 *
993 * So, we remap the item in slot 0 to 1000, and remap "this" to zero. On
994 * SF.GetValues / SF.SetValues we map them back.
Elliott Hughesc5b734a2011-12-01 17:20:58 -0800995 *
996 * TODO: jdb uses the value to determine whether a variable is a local or an argument,
997 * by checking whether it's less than the number of arguments. To make that work, we'd
998 * have to "mangle" all the arguments to come first, not just the implicit argument 'this'.
Elliott Hughesdbb40792011-11-18 17:05:22 -0800999 */
1000static uint16_t MangleSlot(uint16_t slot, const char* name) {
1001 uint16_t newSlot = slot;
1002 if (strcmp(name, "this") == 0) {
1003 newSlot = 0;
1004 } else if (slot == 0) {
1005 newSlot = kEclipseWorkaroundSlot;
1006 }
1007 return newSlot;
1008}
1009
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08001010static uint16_t DemangleSlot(uint16_t slot, Method* m) {
Elliott Hughesdbb40792011-11-18 17:05:22 -08001011 if (slot == kEclipseWorkaroundSlot) {
Elliott Hughes68fdbd02011-11-29 19:22:47 -08001012 return 0;
Elliott Hughesdbb40792011-11-18 17:05:22 -08001013 } else if (slot == 0) {
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08001014 const DexFile::CodeItem* code_item = MethodHelper(m).GetCodeItem();
1015 CHECK(code_item != NULL);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001016 return code_item->registers_size_ - code_item->ins_size_;
Elliott Hughesdbb40792011-11-18 17:05:22 -08001017 }
Elliott Hughes68fdbd02011-11-29 19:22:47 -08001018 return slot;
Elliott Hughesdbb40792011-11-18 17:05:22 -08001019}
1020
Elliott Hughes436e3722012-02-17 20:01:47 -08001021JDWP::JdwpError Dbg::OutputDeclaredFields(JDWP::RefTypeId classId, bool with_generic, JDWP::ExpandBuf* pReply) {
1022 JDWP::JdwpError status;
1023 Class* c = DecodeClass(classId, status);
1024 if (c == NULL) {
1025 return status;
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -08001026 }
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001027
1028 size_t instance_field_count = c->NumInstanceFields();
1029 size_t static_field_count = c->NumStaticFields();
1030
1031 expandBufAdd4BE(pReply, instance_field_count + static_field_count);
1032
1033 for (size_t i = 0; i < instance_field_count + static_field_count; ++i) {
1034 Field* f = (i < instance_field_count) ? c->GetInstanceField(i) : c->GetStaticField(i - instance_field_count);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001035 FieldHelper fh(f);
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001036 expandBufAddFieldId(pReply, ToFieldId(f));
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001037 expandBufAddUtf8String(pReply, fh.GetName());
1038 expandBufAddUtf8String(pReply, fh.GetTypeDescriptor());
Elliott Hughesc5b734a2011-12-01 17:20:58 -08001039 if (with_generic) {
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001040 static const char genericSignature[1] = "";
1041 expandBufAddUtf8String(pReply, genericSignature);
1042 }
1043 expandBufAdd4BE(pReply, MangleAccessFlags(f->GetAccessFlags()));
1044 }
Elliott Hughes436e3722012-02-17 20:01:47 -08001045 return JDWP::ERR_NONE;
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001046}
1047
Elliott Hughes436e3722012-02-17 20:01:47 -08001048JDWP::JdwpError Dbg::OutputDeclaredMethods(JDWP::RefTypeId classId, bool with_generic, JDWP::ExpandBuf* pReply) {
1049 JDWP::JdwpError status;
1050 Class* c = DecodeClass(classId, status);
1051 if (c == NULL) {
1052 return status;
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -08001053 }
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001054
1055 size_t direct_method_count = c->NumDirectMethods();
1056 size_t virtual_method_count = c->NumVirtualMethods();
1057
1058 expandBufAdd4BE(pReply, direct_method_count + virtual_method_count);
1059
1060 for (size_t i = 0; i < direct_method_count + virtual_method_count; ++i) {
1061 Method* m = (i < direct_method_count) ? c->GetDirectMethod(i) : c->GetVirtualMethod(i - direct_method_count);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001062 MethodHelper mh(m);
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001063 expandBufAddMethodId(pReply, ToMethodId(m));
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001064 expandBufAddUtf8String(pReply, mh.GetName());
Elliott Hughes4740cdf2011-12-07 14:07:12 -08001065 expandBufAddUtf8String(pReply, mh.GetSignature());
Elliott Hughesc5b734a2011-12-01 17:20:58 -08001066 if (with_generic) {
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001067 static const char genericSignature[1] = "";
1068 expandBufAddUtf8String(pReply, genericSignature);
1069 }
1070 expandBufAdd4BE(pReply, MangleAccessFlags(m->GetAccessFlags()));
1071 }
Elliott Hughes436e3722012-02-17 20:01:47 -08001072 return JDWP::ERR_NONE;
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001073}
1074
Elliott Hughes436e3722012-02-17 20:01:47 -08001075JDWP::JdwpError Dbg::OutputDeclaredInterfaces(JDWP::RefTypeId classId, JDWP::ExpandBuf* pReply) {
1076 JDWP::JdwpError status;
1077 Class* c = DecodeClass(classId, status);
1078 if (c == NULL) {
1079 return status;
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -08001080 }
Elliott Hughes436e3722012-02-17 20:01:47 -08001081
1082 ClassHelper kh(c);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001083 size_t interface_count = kh.NumInterfaces();
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001084 expandBufAdd4BE(pReply, interface_count);
1085 for (size_t i = 0; i < interface_count; ++i) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001086 expandBufAddRefTypeId(pReply, gRegistry->Add(kh.GetInterface(i)));
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001087 }
Elliott Hughes436e3722012-02-17 20:01:47 -08001088 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001089}
1090
Elliott Hughes436e3722012-02-17 20:01:47 -08001091void Dbg::OutputLineTable(JDWP::RefTypeId, JDWP::MethodId methodId, JDWP::ExpandBuf* pReply) {
Elliott Hughes03181a82011-11-17 17:22:21 -08001092 struct DebugCallbackContext {
1093 int numItems;
1094 JDWP::ExpandBuf* pReply;
1095
Elliott Hughes2435a572012-02-17 16:07:41 -08001096 static bool Callback(void* context, uint32_t address, uint32_t line_number) {
Elliott Hughes03181a82011-11-17 17:22:21 -08001097 DebugCallbackContext* pContext = reinterpret_cast<DebugCallbackContext*>(context);
1098 expandBufAdd8BE(pContext->pReply, address);
Elliott Hughes2435a572012-02-17 16:07:41 -08001099 expandBufAdd4BE(pContext->pReply, line_number);
Elliott Hughes03181a82011-11-17 17:22:21 -08001100 pContext->numItems++;
1101 return true;
1102 }
1103 };
1104
1105 Method* m = FromMethodId(methodId);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001106 MethodHelper mh(m);
Elliott Hughes03181a82011-11-17 17:22:21 -08001107 uint64_t start, end;
1108 if (m->IsNative()) {
1109 start = -1;
1110 end = -1;
1111 } else {
1112 start = 0;
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001113 // TODO: what are the units supposed to be? *2?
1114 end = mh.GetCodeItem()->insns_size_in_code_units_;
Elliott Hughes03181a82011-11-17 17:22:21 -08001115 }
1116
1117 expandBufAdd8BE(pReply, start);
1118 expandBufAdd8BE(pReply, end);
1119
1120 // Add numLines later
1121 size_t numLinesOffset = expandBufGetLength(pReply);
1122 expandBufAdd4BE(pReply, 0);
1123
1124 DebugCallbackContext context;
1125 context.numItems = 0;
1126 context.pReply = pReply;
1127
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001128 mh.GetDexFile().DecodeDebugInfo(mh.GetCodeItem(), m->IsStatic(), m->GetDexMethodIndex(),
1129 DebugCallbackContext::Callback, NULL, &context);
Elliott Hughes03181a82011-11-17 17:22:21 -08001130
1131 JDWP::Set4BE(expandBufGetBuffer(pReply) + numLinesOffset, context.numItems);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001132}
1133
Elliott Hughes436e3722012-02-17 20:01:47 -08001134void Dbg::OutputVariableTable(JDWP::RefTypeId, JDWP::MethodId methodId, bool with_generic, JDWP::ExpandBuf* pReply) {
Elliott Hughesdbb40792011-11-18 17:05:22 -08001135 struct DebugCallbackContext {
Elliott Hughesdbb40792011-11-18 17:05:22 -08001136 JDWP::ExpandBuf* pReply;
Elliott Hughesc5b734a2011-12-01 17:20:58 -08001137 size_t variable_count;
1138 bool with_generic;
Elliott Hughesdbb40792011-11-18 17:05:22 -08001139
Elliott Hughesc5b734a2011-12-01 17:20:58 -08001140 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 -08001141 DebugCallbackContext* pContext = reinterpret_cast<DebugCallbackContext*>(context);
1142
Elliott Hughesad3da692012-02-24 16:51:35 -08001143 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 -08001144
Elliott Hughes68fdbd02011-11-29 19:22:47 -08001145 slot = MangleSlot(slot, name);
1146
Elliott Hughesdbb40792011-11-18 17:05:22 -08001147 expandBufAdd8BE(pContext->pReply, startAddress);
1148 expandBufAddUtf8String(pContext->pReply, name);
1149 expandBufAddUtf8String(pContext->pReply, descriptor);
Elliott Hughesc5b734a2011-12-01 17:20:58 -08001150 if (pContext->with_generic) {
Elliott Hughesdbb40792011-11-18 17:05:22 -08001151 expandBufAddUtf8String(pContext->pReply, signature);
1152 }
1153 expandBufAdd4BE(pContext->pReply, endAddress - startAddress);
1154 expandBufAdd4BE(pContext->pReply, slot);
1155
Elliott Hughesc5b734a2011-12-01 17:20:58 -08001156 ++pContext->variable_count;
Elliott Hughesdbb40792011-11-18 17:05:22 -08001157 }
1158 };
1159
1160 Method* m = FromMethodId(methodId);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001161 MethodHelper mh(m);
1162 const DexFile::CodeItem* code_item = mh.GetCodeItem();
Elliott Hughesdbb40792011-11-18 17:05:22 -08001163
Elliott Hughesc5b734a2011-12-01 17:20:58 -08001164 // arg_count considers doubles and longs to take 2 units.
1165 // variable_count considers everything to take 1 unit.
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001166 std::string shorty(mh.GetShorty());
Elliott Hughesc5b734a2011-12-01 17:20:58 -08001167 expandBufAdd4BE(pReply, m->NumArgRegisters(shorty));
Elliott Hughesdbb40792011-11-18 17:05:22 -08001168
Elliott Hughesc5b734a2011-12-01 17:20:58 -08001169 // We don't know the total number of variables yet, so leave a blank and update it later.
1170 size_t variable_count_offset = expandBufGetLength(pReply);
Elliott Hughesdbb40792011-11-18 17:05:22 -08001171 expandBufAdd4BE(pReply, 0);
1172
1173 DebugCallbackContext context;
Elliott Hughesdbb40792011-11-18 17:05:22 -08001174 context.pReply = pReply;
Elliott Hughesc5b734a2011-12-01 17:20:58 -08001175 context.variable_count = 0;
1176 context.with_generic = with_generic;
Elliott Hughesdbb40792011-11-18 17:05:22 -08001177
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001178 mh.GetDexFile().DecodeDebugInfo(code_item, m->IsStatic(), m->GetDexMethodIndex(), NULL,
1179 DebugCallbackContext::Callback, &context);
Elliott Hughesdbb40792011-11-18 17:05:22 -08001180
Elliott Hughesc5b734a2011-12-01 17:20:58 -08001181 JDWP::Set4BE(expandBufGetBuffer(pReply) + variable_count_offset, context.variable_count);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001182}
1183
Elliott Hughesaed4be92011-12-02 16:16:23 -08001184JDWP::JdwpTag Dbg::GetFieldBasicTag(JDWP::FieldId fieldId) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001185 return BasicTagFromDescriptor(FieldHelper(FromFieldId(fieldId)).GetTypeDescriptor());
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001186}
1187
Elliott Hughesaed4be92011-12-02 16:16:23 -08001188JDWP::JdwpTag Dbg::GetStaticFieldBasicTag(JDWP::FieldId fieldId) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001189 return BasicTagFromDescriptor(FieldHelper(FromFieldId(fieldId)).GetTypeDescriptor());
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001190}
1191
Elliott Hughes0cf74332012-02-23 23:14:00 -08001192static JDWP::JdwpError GetFieldValueImpl(JDWP::RefTypeId refTypeId, JDWP::ObjectId objectId, JDWP::FieldId fieldId, JDWP::ExpandBuf* pReply, bool is_static) {
1193 JDWP::JdwpError status;
1194 Class* c = DecodeClass(refTypeId, status);
1195 if (refTypeId != 0 && c == NULL) {
1196 return status;
1197 }
1198
Elliott Hughesaed4be92011-12-02 16:16:23 -08001199 Object* o = gRegistry->Get<Object*>(objectId);
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08001200 if ((!is_static && o == NULL) || o == kInvalidObject) {
1201 return JDWP::ERR_INVALID_OBJECT;
1202 }
Elliott Hughesaed4be92011-12-02 16:16:23 -08001203 Field* f = FromFieldId(fieldId);
Elliott Hughes0cf74332012-02-23 23:14:00 -08001204
1205 Class* receiver_class = c;
1206 if (receiver_class == NULL && o != NULL) {
1207 receiver_class = o->GetClass();
1208 }
1209 // TODO: should we give up now if receiver_class is NULL?
1210 if (receiver_class != NULL && !f->GetDeclaringClass()->IsAssignableFrom(receiver_class)) {
1211 LOG(INFO) << "ERR_INVALID_FIELDID: " << PrettyField(f) << " " << PrettyClass(receiver_class);
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08001212 return JDWP::ERR_INVALID_FIELDID;
1213 }
Elliott Hughesaed4be92011-12-02 16:16:23 -08001214
Elliott Hughes0cf74332012-02-23 23:14:00 -08001215 // The RI only enforces the static/non-static mismatch in one direction.
1216 // TODO: should we change the tests and check both?
1217 if (is_static) {
1218 if (!f->IsStatic()) {
1219 return JDWP::ERR_INVALID_FIELDID;
1220 }
1221 } else {
1222 if (f->IsStatic()) {
1223 LOG(WARNING) << "Ignoring non-NULL receiver for ObjectReference.SetValues on static field " << PrettyField(f);
1224 o = NULL;
1225 }
1226 }
1227
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001228 JDWP::JdwpTag tag = BasicTagFromDescriptor(FieldHelper(f).GetTypeDescriptor());
Elliott Hughesaed4be92011-12-02 16:16:23 -08001229
1230 if (IsPrimitiveTag(tag)) {
1231 expandBufAdd1(pReply, tag);
1232 if (tag == JDWP::JT_BOOLEAN || tag == JDWP::JT_BYTE) {
1233 expandBufAdd1(pReply, f->Get32(o));
1234 } else if (tag == JDWP::JT_CHAR || tag == JDWP::JT_SHORT) {
1235 expandBufAdd2BE(pReply, f->Get32(o));
1236 } else if (tag == JDWP::JT_FLOAT || tag == JDWP::JT_INT) {
1237 expandBufAdd4BE(pReply, f->Get32(o));
1238 } else if (tag == JDWP::JT_DOUBLE || tag == JDWP::JT_LONG) {
1239 expandBufAdd8BE(pReply, f->Get64(o));
1240 } else {
Elliott Hughes3d30d9b2011-12-07 17:35:48 -08001241 LOG(FATAL) << "Unknown tag: " << tag;
Elliott Hughesaed4be92011-12-02 16:16:23 -08001242 }
1243 } else {
1244 Object* value = f->GetObject(o);
1245 expandBufAdd1(pReply, TagFromObject(value));
1246 expandBufAddObjectId(pReply, gRegistry->Add(value));
1247 }
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08001248 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001249}
1250
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08001251JDWP::JdwpError Dbg::GetFieldValue(JDWP::ObjectId objectId, JDWP::FieldId fieldId, JDWP::ExpandBuf* pReply) {
Elliott Hughes0cf74332012-02-23 23:14:00 -08001252 return GetFieldValueImpl(0, objectId, fieldId, pReply, false);
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08001253}
1254
Elliott Hughes0cf74332012-02-23 23:14:00 -08001255JDWP::JdwpError Dbg::GetStaticFieldValue(JDWP::RefTypeId refTypeId, JDWP::FieldId fieldId, JDWP::ExpandBuf* pReply) {
1256 return GetFieldValueImpl(refTypeId, 0, fieldId, pReply, true);
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08001257}
1258
1259static JDWP::JdwpError SetFieldValueImpl(JDWP::ObjectId objectId, JDWP::FieldId fieldId, uint64_t value, int width, bool is_static) {
Elliott Hughesaed4be92011-12-02 16:16:23 -08001260 Object* o = gRegistry->Get<Object*>(objectId);
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08001261 if ((!is_static && o == NULL) || o == kInvalidObject) {
1262 return JDWP::ERR_INVALID_OBJECT;
1263 }
Elliott Hughesaed4be92011-12-02 16:16:23 -08001264 Field* f = FromFieldId(fieldId);
Elliott Hughes0cf74332012-02-23 23:14:00 -08001265
1266 // The RI only enforces the static/non-static mismatch in one direction.
1267 // TODO: should we change the tests and check both?
1268 if (is_static) {
1269 if (!f->IsStatic()) {
1270 return JDWP::ERR_INVALID_FIELDID;
1271 }
1272 } else {
1273 if (f->IsStatic()) {
1274 LOG(WARNING) << "Ignoring non-NULL receiver for ObjectReference.SetValues on static field " << PrettyField(f);
1275 o = NULL;
1276 }
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08001277 }
Elliott Hughesaed4be92011-12-02 16:16:23 -08001278
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001279 JDWP::JdwpTag tag = BasicTagFromDescriptor(FieldHelper(f).GetTypeDescriptor());
Elliott Hughesaed4be92011-12-02 16:16:23 -08001280
1281 if (IsPrimitiveTag(tag)) {
1282 if (tag == JDWP::JT_DOUBLE || tag == JDWP::JT_LONG) {
Elliott Hughes1bac54f2012-03-16 12:48:31 -07001283 CHECK_EQ(width, 8);
Elliott Hughesaed4be92011-12-02 16:16:23 -08001284 f->Set64(o, value);
1285 } else {
Elliott Hughes1bac54f2012-03-16 12:48:31 -07001286 CHECK_LE(width, 4);
Elliott Hughesaed4be92011-12-02 16:16:23 -08001287 f->Set32(o, value);
1288 }
1289 } else {
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -08001290 Object* v = gRegistry->Get<Object*>(value);
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08001291 if (v == kInvalidObject) {
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -08001292 return JDWP::ERR_INVALID_OBJECT;
1293 }
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08001294 if (v != NULL) {
1295 Class* field_type = FieldHelper(f).GetType();
1296 if (!field_type->IsAssignableFrom(v->GetClass())) {
1297 return JDWP::ERR_INVALID_OBJECT;
1298 }
1299 }
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -08001300 f->SetObject(o, v);
Elliott Hughesaed4be92011-12-02 16:16:23 -08001301 }
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -08001302
1303 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001304}
1305
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08001306JDWP::JdwpError Dbg::SetFieldValue(JDWP::ObjectId objectId, JDWP::FieldId fieldId, uint64_t value, int width) {
1307 return SetFieldValueImpl(objectId, fieldId, value, width, false);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001308}
1309
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -08001310JDWP::JdwpError Dbg::SetStaticFieldValue(JDWP::FieldId fieldId, uint64_t value, int width) {
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08001311 return SetFieldValueImpl(0, fieldId, value, width, true);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001312}
1313
Elliott Hughes68fdbd02011-11-29 19:22:47 -08001314std::string Dbg::StringToUtf8(JDWP::ObjectId strId) {
1315 String* s = gRegistry->Get<String*>(strId);
1316 return s->ToModifiedUtf8();
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001317}
1318
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001319bool Dbg::GetThreadName(JDWP::ObjectId threadId, std::string& name) {
1320 ScopedThreadListLock thread_list_lock;
1321 Thread* thread = DecodeThread(threadId);
1322 if (thread == NULL) {
1323 return false;
1324 }
Elliott Hughesffb465f2012-03-01 18:46:05 -08001325 thread->GetThreadName(name);
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001326 return true;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001327}
1328
Elliott Hughes2435a572012-02-17 16:07:41 -08001329JDWP::JdwpError Dbg::GetThreadGroup(JDWP::ObjectId threadId, JDWP::ExpandBuf* pReply) {
Elliott Hughes499c5132011-11-17 14:55:11 -08001330 Object* thread = gRegistry->Get<Object*>(threadId);
Elliott Hughes436e3722012-02-17 20:01:47 -08001331 if (thread == kInvalidObject) {
Elliott Hughes2435a572012-02-17 16:07:41 -08001332 return JDWP::ERR_INVALID_OBJECT;
1333 }
1334
1335 // Okay, so it's an object, but is it actually a thread?
Elliott Hughes436e3722012-02-17 20:01:47 -08001336 if (DecodeThread(threadId) == NULL) {
Elliott Hughes2435a572012-02-17 16:07:41 -08001337 return JDWP::ERR_INVALID_THREAD;
1338 }
Elliott Hughes499c5132011-11-17 14:55:11 -08001339
1340 Class* c = Runtime::Current()->GetClassLinker()->FindSystemClass("Ljava/lang/Thread;");
1341 CHECK(c != NULL);
1342 Field* f = c->FindInstanceField("group", "Ljava/lang/ThreadGroup;");
1343 CHECK(f != NULL);
1344 Object* group = f->GetObject(thread);
1345 CHECK(group != NULL);
Elliott Hughes2435a572012-02-17 16:07:41 -08001346 JDWP::ObjectId thread_group_id = gRegistry->Add(group);
1347
1348 expandBufAddObjectId(pReply, thread_group_id);
1349 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001350}
1351
Elliott Hughes499c5132011-11-17 14:55:11 -08001352std::string Dbg::GetThreadGroupName(JDWP::ObjectId threadGroupId) {
1353 Object* thread_group = gRegistry->Get<Object*>(threadGroupId);
1354 CHECK(thread_group != NULL);
1355
1356 Class* c = Runtime::Current()->GetClassLinker()->FindSystemClass("Ljava/lang/ThreadGroup;");
1357 CHECK(c != NULL);
1358 Field* f = c->FindInstanceField("name", "Ljava/lang/String;");
1359 CHECK(f != NULL);
1360 String* s = reinterpret_cast<String*>(f->GetObject(thread_group));
1361 return s->ToModifiedUtf8();
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001362}
1363
1364JDWP::ObjectId Dbg::GetThreadGroupParent(JDWP::ObjectId threadGroupId) {
Elliott Hughes4e235312011-12-02 11:34:15 -08001365 Object* thread_group = gRegistry->Get<Object*>(threadGroupId);
1366 CHECK(thread_group != NULL);
1367
1368 Class* c = Runtime::Current()->GetClassLinker()->FindSystemClass("Ljava/lang/ThreadGroup;");
1369 CHECK(c != NULL);
1370 Field* f = c->FindInstanceField("parent", "Ljava/lang/ThreadGroup;");
1371 CHECK(f != NULL);
1372 Object* parent = f->GetObject(thread_group);
1373 return gRegistry->Add(parent);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001374}
1375
1376JDWP::ObjectId Dbg::GetSystemThreadGroupId() {
Elliott Hughes462c9442012-03-23 18:47:50 -07001377 return gRegistry->Add(Thread::GetSystemThreadGroup());
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001378}
1379
1380JDWP::ObjectId Dbg::GetMainThreadGroupId() {
Elliott Hughes462c9442012-03-23 18:47:50 -07001381 return gRegistry->Add(Thread::GetMainThreadGroup());
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001382}
1383
Elliott Hughes3d30d9b2011-12-07 17:35:48 -08001384bool Dbg::GetThreadStatus(JDWP::ObjectId threadId, JDWP::JdwpThreadStatus* pThreadStatus, JDWP::JdwpSuspendStatus* pSuspendStatus) {
Elliott Hughes499c5132011-11-17 14:55:11 -08001385 ScopedThreadListLock thread_list_lock;
1386
1387 Thread* thread = DecodeThread(threadId);
1388 if (thread == NULL) {
1389 return false;
1390 }
1391
Elliott Hughes3ce4b262012-02-24 11:24:02 -08001392 // TODO: if we're in Thread.sleep(long), we should return TS_SLEEPING,
1393 // even if it's implemented using Object.wait(long).
Elliott Hughes499c5132011-11-17 14:55:11 -08001394 switch (thread->GetState()) {
Elliott Hughes34e06962012-04-09 13:55:55 -07001395 case kTerminated: *pThreadStatus = JDWP::TS_ZOMBIE; break;
1396 case kRunnable: *pThreadStatus = JDWP::TS_RUNNING; break;
1397 case kTimedWaiting: *pThreadStatus = JDWP::TS_WAIT; break;
1398 case kBlocked: *pThreadStatus = JDWP::TS_MONITOR; break;
1399 case kWaiting: *pThreadStatus = JDWP::TS_WAIT; break;
1400 case kStarting: *pThreadStatus = JDWP::TS_ZOMBIE; break;
1401 case kNative: *pThreadStatus = JDWP::TS_RUNNING; break;
1402 case kVmWait: *pThreadStatus = JDWP::TS_WAIT; break;
1403 case kSuspended: *pThreadStatus = JDWP::TS_RUNNING; break;
Elliott Hughescf2b2d42012-03-27 17:11:42 -07001404 // Don't add a 'default' here so the compiler can spot incompatible enum changes.
Elliott Hughes499c5132011-11-17 14:55:11 -08001405 }
1406
Elliott Hughes3d30d9b2011-12-07 17:35:48 -08001407 *pSuspendStatus = (thread->IsSuspended() ? JDWP::SUSPEND_STATUS_SUSPENDED : JDWP::SUSPEND_STATUS_NOT_SUSPENDED);
Elliott Hughes499c5132011-11-17 14:55:11 -08001408
1409 return true;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001410}
1411
Elliott Hughes2435a572012-02-17 16:07:41 -08001412JDWP::JdwpError Dbg::GetThreadSuspendCount(JDWP::ObjectId threadId, JDWP::ExpandBuf* pReply) {
1413 Thread* thread = DecodeThread(threadId);
1414 if (thread == NULL) {
1415 return JDWP::ERR_INVALID_THREAD;
1416 }
1417 expandBufAdd4BE(pReply, thread->GetSuspendCount());
1418 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001419}
1420
1421bool Dbg::ThreadExists(JDWP::ObjectId threadId) {
Elliott Hughes761928d2011-11-16 18:33:03 -08001422 return DecodeThread(threadId) != NULL;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001423}
1424
1425bool Dbg::IsSuspended(JDWP::ObjectId threadId) {
Elliott Hughes761928d2011-11-16 18:33:03 -08001426 return DecodeThread(threadId)->IsSuspended();
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001427}
1428
Elliott Hughesa2155262011-11-16 16:26:58 -08001429void Dbg::GetThreadGroupThreadsImpl(Object* thread_group, JDWP::ObjectId** ppThreadIds, uint32_t* pThreadCount) {
1430 struct ThreadListVisitor {
1431 static void Visit(Thread* t, void* arg) {
1432 reinterpret_cast<ThreadListVisitor*>(arg)->Visit(t);
1433 }
1434
1435 void Visit(Thread* t) {
1436 if (t == Dbg::GetDebugThread()) {
1437 // Skip the JDWP thread. Some debuggers get bent out of shape when they can't suspend and
1438 // query all threads, so it's easier if we just don't tell them about this thread.
1439 return;
1440 }
1441 if (thread_group == NULL || t->GetThreadGroup() == thread_group) {
1442 threads.push_back(gRegistry->Add(t->GetPeer()));
1443 }
1444 }
1445
1446 Object* thread_group;
1447 std::vector<JDWP::ObjectId> threads;
1448 };
1449
1450 ThreadListVisitor tlv;
1451 tlv.thread_group = thread_group;
1452
1453 {
1454 ScopedThreadListLock thread_list_lock;
1455 Runtime::Current()->GetThreadList()->ForEach(ThreadListVisitor::Visit, &tlv);
1456 }
1457
1458 *pThreadCount = tlv.threads.size();
1459 if (*pThreadCount == 0) {
1460 *ppThreadIds = NULL;
1461 } else {
1462 *ppThreadIds = new JDWP::ObjectId[*pThreadCount];
1463 for (size_t i = 0; i < *pThreadCount; ++i) {
1464 (*ppThreadIds)[i] = tlv.threads[i];
1465 }
1466 }
1467}
1468
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001469void Dbg::GetThreadGroupThreads(JDWP::ObjectId threadGroupId, JDWP::ObjectId** ppThreadIds, uint32_t* pThreadCount) {
Elliott Hughesa2155262011-11-16 16:26:58 -08001470 GetThreadGroupThreadsImpl(gRegistry->Get<Object*>(threadGroupId), ppThreadIds, pThreadCount);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001471}
1472
1473void Dbg::GetAllThreads(JDWP::ObjectId** ppThreadIds, uint32_t* pThreadCount) {
Elliott Hughesa2155262011-11-16 16:26:58 -08001474 GetThreadGroupThreadsImpl(NULL, ppThreadIds, pThreadCount);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001475}
1476
Elliott Hughes86964332012-02-15 19:37:42 -08001477static int GetStackDepth(Thread* thread) {
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001478 struct CountStackDepthVisitor : public Thread::StackVisitor {
1479 CountStackDepthVisitor() : depth(0) {}
Elliott Hughes530fa002012-03-12 11:44:49 -07001480 bool VisitFrame(const Frame& f, uintptr_t) {
Elliott Hughesf8a2df72011-12-01 12:19:54 -08001481 if (f.HasMethod()) {
1482 ++depth;
1483 }
Elliott Hughes530fa002012-03-12 11:44:49 -07001484 return true;
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001485 }
1486 size_t depth;
1487 };
1488 CountStackDepthVisitor visitor;
Elliott Hughes86964332012-02-15 19:37:42 -08001489 thread->WalkStack(&visitor);
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001490 return visitor.depth;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001491}
1492
Elliott Hughes86964332012-02-15 19:37:42 -08001493int Dbg::GetThreadFrameCount(JDWP::ObjectId threadId) {
1494 ScopedThreadListLock thread_list_lock;
1495 return GetStackDepth(DecodeThread(threadId));
1496}
1497
Elliott Hughes530fa002012-03-12 11:44:49 -07001498void Dbg::GetThreadFrame(JDWP::ObjectId threadId, int desired_frame_number, JDWP::FrameId* pFrameId, JDWP::JdwpLocation* pLoc) {
Elliott Hughes03181a82011-11-17 17:22:21 -08001499 ScopedThreadListLock thread_list_lock;
1500 struct GetFrameVisitor : public Thread::StackVisitor {
1501 GetFrameVisitor(int desired_frame_number, JDWP::FrameId* pFrameId, JDWP::JdwpLocation* pLoc)
Elliott Hughes530fa002012-03-12 11:44:49 -07001502 : depth(0), desired_frame_number(desired_frame_number), pFrameId(pFrameId), pLoc(pLoc) {
Elliott Hughes03181a82011-11-17 17:22:21 -08001503 }
Elliott Hughes530fa002012-03-12 11:44:49 -07001504 bool VisitFrame(const Frame& f, uintptr_t pc) {
Elliott Hughes03181a82011-11-17 17:22:21 -08001505 if (!f.HasMethod()) {
Elliott Hughes530fa002012-03-12 11:44:49 -07001506 return true; // The debugger can't do anything useful with a frame that has no Method*.
Elliott Hughes03181a82011-11-17 17:22:21 -08001507 }
Elliott Hughes03181a82011-11-17 17:22:21 -08001508 if (depth == desired_frame_number) {
1509 *pFrameId = reinterpret_cast<JDWP::FrameId>(f.GetSP());
Elliott Hughesd07986f2011-12-06 18:27:45 -08001510 SetLocation(*pLoc, f.GetMethod(), pc);
Elliott Hughes530fa002012-03-12 11:44:49 -07001511 return false;
Elliott Hughes03181a82011-11-17 17:22:21 -08001512 }
1513 ++depth;
Elliott Hughes530fa002012-03-12 11:44:49 -07001514 return true;
Elliott Hughes03181a82011-11-17 17:22:21 -08001515 }
Elliott Hughes03181a82011-11-17 17:22:21 -08001516 int depth;
1517 int desired_frame_number;
1518 JDWP::FrameId* pFrameId;
1519 JDWP::JdwpLocation* pLoc;
1520 };
1521 GetFrameVisitor visitor(desired_frame_number, pFrameId, pLoc);
1522 visitor.desired_frame_number = desired_frame_number;
1523 DecodeThread(threadId)->WalkStack(&visitor);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001524}
1525
1526JDWP::ObjectId Dbg::GetThreadSelfId() {
Elliott Hughes475fc232011-10-25 15:00:35 -07001527 return gRegistry->Add(Thread::Current()->GetPeer());
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001528}
1529
Elliott Hughes475fc232011-10-25 15:00:35 -07001530void Dbg::SuspendVM() {
Elliott Hughes34e06962012-04-09 13:55:55 -07001531 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 -07001532 Runtime::Current()->GetThreadList()->SuspendAll(true);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001533}
1534
1535void Dbg::ResumeVM() {
Elliott Hughes475fc232011-10-25 15:00:35 -07001536 Runtime::Current()->GetThreadList()->ResumeAll(true);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001537}
1538
1539void Dbg::SuspendThread(JDWP::ObjectId threadId) {
Elliott Hughes4e235312011-12-02 11:34:15 -08001540 Object* peer = gRegistry->Get<Object*>(threadId);
1541 ScopedThreadListLock thread_list_lock;
1542 Thread* thread = Thread::FromManagedThread(peer);
1543 if (thread == NULL) {
1544 LOG(WARNING) << "No such thread for suspend: " << peer;
1545 return;
1546 }
1547 Runtime::Current()->GetThreadList()->Suspend(thread, true);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001548}
1549
1550void Dbg::ResumeThread(JDWP::ObjectId threadId) {
Elliott Hughes4e235312011-12-02 11:34:15 -08001551 Object* peer = gRegistry->Get<Object*>(threadId);
1552 ScopedThreadListLock thread_list_lock;
1553 Thread* thread = Thread::FromManagedThread(peer);
1554 if (thread == NULL) {
1555 LOG(WARNING) << "No such thread for resume: " << peer;
1556 return;
1557 }
1558 Runtime::Current()->GetThreadList()->Resume(thread, true);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001559}
1560
1561void Dbg::SuspendSelf() {
Elliott Hughes475fc232011-10-25 15:00:35 -07001562 Runtime::Current()->GetThreadList()->SuspendSelfForDebugger();
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001563}
1564
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08001565static Object* GetThis(Frame& f) {
Elliott Hughes86b00102011-12-05 17:54:26 -08001566 Method* m = f.GetMethod();
Elliott Hughes86b00102011-12-05 17:54:26 -08001567 Object* o = NULL;
1568 if (!m->IsNative() && !m->IsStatic()) {
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08001569 uint16_t reg = DemangleSlot(0, m);
Elliott Hughes86b00102011-12-05 17:54:26 -08001570 o = reinterpret_cast<Object*>(f.GetVReg(m, reg));
1571 }
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08001572 return o;
1573}
1574
1575void Dbg::GetThisObject(JDWP::FrameId frameId, JDWP::ObjectId* pThisId) {
1576 Method** sp = reinterpret_cast<Method**>(frameId);
1577 Frame f(sp);
1578 Object* o = GetThis(f);
Elliott Hughes86b00102011-12-05 17:54:26 -08001579 *pThisId = gRegistry->Add(o);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001580}
1581
Elliott Hughes1bac54f2012-03-16 12:48:31 -07001582void 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 -08001583 Method** sp = reinterpret_cast<Method**>(frameId);
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08001584 Frame f(sp);
Elliott Hughes68fdbd02011-11-29 19:22:47 -08001585 Method* m = f.GetMethod();
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08001586 uint16_t reg = DemangleSlot(slot, m);
Elliott Hughes68fdbd02011-11-29 19:22:47 -08001587
Ian Rogers776ac1f2012-04-13 23:36:36 -07001588#if defined(ART_USE_LLVM_COMPILER)
1589 UNIMPLEMENTED(FATAL);
1590#else
Elliott Hughes68fdbd02011-11-29 19:22:47 -08001591 const VmapTable vmap_table(m->GetVmapTableRaw());
1592 uint32_t vmap_offset;
1593 if (vmap_table.IsInContext(reg, vmap_offset)) {
Elliott Hughes3d30d9b2011-12-07 17:35:48 -08001594 UNIMPLEMENTED(FATAL) << "Don't know how to pull locals from callee save frames: " << vmap_offset;
Elliott Hughes68fdbd02011-11-29 19:22:47 -08001595 }
Ian Rogers776ac1f2012-04-13 23:36:36 -07001596#endif
Elliott Hughesdbb40792011-11-18 17:05:22 -08001597
Elliott Hughesad3da692012-02-24 16:51:35 -08001598 // TODO: check that the tag is compatible with the actual type of the slot!
1599
Elliott Hughesdbb40792011-11-18 17:05:22 -08001600 switch (tag) {
1601 case JDWP::JT_BOOLEAN:
1602 {
Elliott Hughescccd84f2011-12-05 16:51:54 -08001603 CHECK_EQ(width, 1U);
Elliott Hughes1bba14f2011-12-01 18:00:36 -08001604 uint32_t intVal = f.GetVReg(m, reg);
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08001605 VLOG(jdwp) << "get boolean local " << reg << " = " << intVal;
Elliott Hughesdbb40792011-11-18 17:05:22 -08001606 JDWP::Set1(buf+1, intVal != 0);
1607 }
1608 break;
1609 case JDWP::JT_BYTE:
1610 {
Elliott Hughescccd84f2011-12-05 16:51:54 -08001611 CHECK_EQ(width, 1U);
Elliott Hughes1bba14f2011-12-01 18:00:36 -08001612 uint32_t intVal = f.GetVReg(m, reg);
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08001613 VLOG(jdwp) << "get byte local " << reg << " = " << intVal;
Elliott Hughesdbb40792011-11-18 17:05:22 -08001614 JDWP::Set1(buf+1, intVal);
1615 }
1616 break;
1617 case JDWP::JT_SHORT:
1618 case JDWP::JT_CHAR:
1619 {
Elliott Hughescccd84f2011-12-05 16:51:54 -08001620 CHECK_EQ(width, 2U);
Elliott Hughes1bba14f2011-12-01 18:00:36 -08001621 uint32_t intVal = f.GetVReg(m, reg);
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08001622 VLOG(jdwp) << "get short/char local " << reg << " = " << intVal;
Elliott Hughesdbb40792011-11-18 17:05:22 -08001623 JDWP::Set2BE(buf+1, intVal);
1624 }
1625 break;
1626 case JDWP::JT_INT:
1627 case JDWP::JT_FLOAT:
1628 {
Elliott Hughescccd84f2011-12-05 16:51:54 -08001629 CHECK_EQ(width, 4U);
Elliott Hughes1bba14f2011-12-01 18:00:36 -08001630 uint32_t intVal = f.GetVReg(m, reg);
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08001631 VLOG(jdwp) << "get int/float local " << reg << " = " << intVal;
Elliott Hughesdbb40792011-11-18 17:05:22 -08001632 JDWP::Set4BE(buf+1, intVal);
1633 }
1634 break;
1635 case JDWP::JT_ARRAY:
1636 {
Elliott Hughescccd84f2011-12-05 16:51:54 -08001637 CHECK_EQ(width, sizeof(JDWP::ObjectId));
Elliott Hughes68fdbd02011-11-29 19:22:47 -08001638 Object* o = reinterpret_cast<Object*>(f.GetVReg(m, reg));
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08001639 VLOG(jdwp) << "get array local " << reg << " = " << o;
Elliott Hughes88c5c352012-03-15 18:49:48 -07001640 if (!Runtime::Current()->GetHeap()->IsHeapAddress(o)) {
Elliott Hughes3d30d9b2011-12-07 17:35:48 -08001641 LOG(FATAL) << "Register " << reg << " expected to hold array: " << o;
Elliott Hughesdbb40792011-11-18 17:05:22 -08001642 }
1643 JDWP::SetObjectId(buf+1, gRegistry->Add(o));
1644 }
1645 break;
Elliott Hughesad3da692012-02-24 16:51:35 -08001646 case JDWP::JT_CLASS_LOADER:
1647 case JDWP::JT_CLASS_OBJECT:
Elliott Hughesdbb40792011-11-18 17:05:22 -08001648 case JDWP::JT_OBJECT:
Elliott Hughesad3da692012-02-24 16:51:35 -08001649 case JDWP::JT_STRING:
1650 case JDWP::JT_THREAD:
1651 case JDWP::JT_THREAD_GROUP:
Elliott Hughesdbb40792011-11-18 17:05:22 -08001652 {
Elliott Hughescccd84f2011-12-05 16:51:54 -08001653 CHECK_EQ(width, sizeof(JDWP::ObjectId));
Elliott Hughes68fdbd02011-11-29 19:22:47 -08001654 Object* o = reinterpret_cast<Object*>(f.GetVReg(m, reg));
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08001655 VLOG(jdwp) << "get object local " << reg << " = " << o;
Elliott Hughes88c5c352012-03-15 18:49:48 -07001656 if (!Runtime::Current()->GetHeap()->IsHeapAddress(o)) {
Elliott Hughes3d30d9b2011-12-07 17:35:48 -08001657 LOG(FATAL) << "Register " << reg << " expected to hold object: " << o;
Elliott Hughesdbb40792011-11-18 17:05:22 -08001658 }
1659 tag = TagFromObject(o);
1660 JDWP::SetObjectId(buf+1, gRegistry->Add(o));
1661 }
1662 break;
1663 case JDWP::JT_DOUBLE:
1664 case JDWP::JT_LONG:
1665 {
Elliott Hughescccd84f2011-12-05 16:51:54 -08001666 CHECK_EQ(width, 8U);
Elliott Hughes1bba14f2011-12-01 18:00:36 -08001667 uint32_t lo = f.GetVReg(m, reg);
1668 uint64_t hi = f.GetVReg(m, reg + 1);
1669 uint64_t longVal = (hi << 32) | lo;
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08001670 VLOG(jdwp) << "get double/long local " << hi << ":" << lo << " = " << longVal;
Elliott Hughesdbb40792011-11-18 17:05:22 -08001671 JDWP::Set8BE(buf+1, longVal);
1672 }
1673 break;
1674 default:
Elliott Hughes3d30d9b2011-12-07 17:35:48 -08001675 LOG(FATAL) << "Unknown tag " << tag;
Elliott Hughesdbb40792011-11-18 17:05:22 -08001676 break;
1677 }
1678
1679 // Prepend tag, which may have been updated.
1680 JDWP::Set1(buf, tag);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001681}
1682
Elliott Hughes1bac54f2012-03-16 12:48:31 -07001683void 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 -08001684 Method** sp = reinterpret_cast<Method**>(frameId);
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08001685 Frame f(sp);
Elliott Hughescccd84f2011-12-05 16:51:54 -08001686 Method* m = f.GetMethod();
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08001687 uint16_t reg = DemangleSlot(slot, m);
Elliott Hughescccd84f2011-12-05 16:51:54 -08001688
Ian Rogers776ac1f2012-04-13 23:36:36 -07001689#if defined(ART_USE_LLVM_COMPILER)
1690 UNIMPLEMENTED(FATAL);
1691#else
Elliott Hughescccd84f2011-12-05 16:51:54 -08001692 const VmapTable vmap_table(m->GetVmapTableRaw());
1693 uint32_t vmap_offset;
1694 if (vmap_table.IsInContext(reg, vmap_offset)) {
Elliott Hughes3d30d9b2011-12-07 17:35:48 -08001695 UNIMPLEMENTED(FATAL) << "Don't know how to pull locals from callee save frames: " << vmap_offset;
Elliott Hughescccd84f2011-12-05 16:51:54 -08001696 }
Ian Rogers776ac1f2012-04-13 23:36:36 -07001697#endif
Elliott Hughescccd84f2011-12-05 16:51:54 -08001698
Elliott Hughesad3da692012-02-24 16:51:35 -08001699 // TODO: check that the tag is compatible with the actual type of the slot!
1700
Elliott Hughescccd84f2011-12-05 16:51:54 -08001701 switch (tag) {
1702 case JDWP::JT_BOOLEAN:
1703 case JDWP::JT_BYTE:
1704 CHECK_EQ(width, 1U);
1705 f.SetVReg(m, reg, static_cast<uint32_t>(value));
1706 break;
1707 case JDWP::JT_SHORT:
1708 case JDWP::JT_CHAR:
1709 CHECK_EQ(width, 2U);
1710 f.SetVReg(m, reg, static_cast<uint32_t>(value));
1711 break;
1712 case JDWP::JT_INT:
1713 case JDWP::JT_FLOAT:
1714 CHECK_EQ(width, 4U);
1715 f.SetVReg(m, reg, static_cast<uint32_t>(value));
1716 break;
1717 case JDWP::JT_ARRAY:
1718 case JDWP::JT_OBJECT:
1719 case JDWP::JT_STRING:
1720 {
1721 CHECK_EQ(width, sizeof(JDWP::ObjectId));
1722 Object* o = gRegistry->Get<Object*>(static_cast<JDWP::ObjectId>(value));
Elliott Hughesad3da692012-02-24 16:51:35 -08001723 if (o == kInvalidObject) {
1724 UNIMPLEMENTED(FATAL) << "return an error code when given an invalid object to store";
1725 }
Elliott Hughescccd84f2011-12-05 16:51:54 -08001726 f.SetVReg(m, reg, static_cast<uint32_t>(reinterpret_cast<uintptr_t>(o)));
1727 }
1728 break;
1729 case JDWP::JT_DOUBLE:
1730 case JDWP::JT_LONG:
1731 CHECK_EQ(width, 8U);
1732 f.SetVReg(m, reg, static_cast<uint32_t>(value));
1733 f.SetVReg(m, reg + 1, static_cast<uint32_t>(value >> 32));
1734 break;
1735 default:
Elliott Hughes3d30d9b2011-12-07 17:35:48 -08001736 LOG(FATAL) << "Unknown tag " << tag;
Elliott Hughescccd84f2011-12-05 16:51:54 -08001737 break;
1738 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001739}
1740
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08001741void Dbg::PostLocationEvent(const Method* m, int dex_pc, Object* this_object, int event_flags) {
1742 Class* c = m->GetDeclaringClass();
1743
1744 JDWP::JdwpLocation location;
1745 location.typeTag = c->IsInterface() ? JDWP::TT_INTERFACE : JDWP::TT_CLASS;
1746 location.classId = gRegistry->Add(c);
1747 location.methodId = ToMethodId(m);
Elliott Hughes972a47b2012-02-21 18:16:06 -08001748 location.dex_pc = m->IsNative() ? -1 : dex_pc;
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08001749
1750 // Note we use "NoReg" so we don't keep track of references that are
1751 // never actually sent to the debugger. 'this_id' is only used to
1752 // compare against registered events...
1753 JDWP::ObjectId this_id = static_cast<JDWP::ObjectId>(reinterpret_cast<uintptr_t>(this_object));
1754 if (gJdwpState->PostLocationEvent(&location, this_id, event_flags)) {
1755 // ...unless there's a registered event, in which case we
1756 // need to really track the class and 'this'.
1757 gRegistry->Add(c);
1758 gRegistry->Add(this_object);
1759 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001760}
1761
Elliott Hughesd07986f2011-12-06 18:27:45 -08001762void Dbg::PostException(Method** sp, Method* throwMethod, uintptr_t throwNativePc, Method* catchMethod, uintptr_t catchNativePc, Object* exception) {
Elliott Hughesc0f09332012-03-26 13:27:06 -07001763 if (!IsDebuggerActive()) {
Ian Rogers0ad5bb82011-12-07 10:16:32 -08001764 return;
1765 }
Elliott Hughes4740cdf2011-12-07 14:07:12 -08001766
Elliott Hughesd07986f2011-12-06 18:27:45 -08001767 JDWP::JdwpLocation throw_location;
1768 SetLocation(throw_location, throwMethod, throwNativePc);
1769 JDWP::JdwpLocation catch_location;
1770 SetLocation(catch_location, catchMethod, catchNativePc);
1771
1772 // We need 'this' for InstanceOnly filters.
1773 JDWP::ObjectId this_id;
1774 GetThisObject(reinterpret_cast<JDWP::FrameId>(sp), &this_id);
1775
1776 /*
1777 * Hand the event to the JDWP exception handler. Note we're using the
1778 * "NoReg" objectID on the exception, which is not strictly correct --
1779 * the exception object WILL be passed up to the debugger if the
1780 * debugger is interested in the event. We do this because the current
1781 * implementation of the debugger object registry never throws anything
1782 * away, and some people were experiencing a fatal build up of exception
1783 * objects when dealing with certain libraries.
1784 */
1785 JDWP::ObjectId exception_id = static_cast<JDWP::ObjectId>(reinterpret_cast<uintptr_t>(exception));
1786 JDWP::RefTypeId exception_class_id = gRegistry->Add(exception->GetClass());
1787
1788 gJdwpState->PostException(&throw_location, exception_id, exception_class_id, &catch_location, this_id);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001789}
1790
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001791void Dbg::PostClassPrepare(Class* c) {
Elliott Hughesc0f09332012-03-26 13:27:06 -07001792 if (!IsDebuggerActive()) {
Elliott Hughes4740cdf2011-12-07 14:07:12 -08001793 return;
1794 }
1795
Elliott Hughes3d30d9b2011-12-07 17:35:48 -08001796 // OLD-TODO - we currently always send both "verified" and "prepared" since
Elliott Hughes4740cdf2011-12-07 14:07:12 -08001797 // debuggers seem to like that. There might be some advantage to honesty,
1798 // since the class may not yet be verified.
1799 int state = JDWP::CS_VERIFIED | JDWP::CS_PREPARED;
1800 JDWP::JdwpTypeTag tag = c->IsInterface() ? JDWP::TT_INTERFACE : JDWP::TT_CLASS;
1801 gJdwpState->PostClassPrepare(tag, gRegistry->Add(c), ClassHelper(c).GetDescriptor(), state);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001802}
1803
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08001804void Dbg::UpdateDebugger(int32_t dex_pc, Thread* self, Method** sp) {
Elliott Hughesc0f09332012-03-26 13:27:06 -07001805 if (!IsDebuggerActive() || dex_pc == -2 /* fake method exit */) {
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08001806 return;
1807 }
1808
Elliott Hughes86964332012-02-15 19:37:42 -08001809 Frame f(sp);
1810 f.Next(); // Skip callee save frame.
1811 Method* m = f.GetMethod();
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08001812
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08001813 if (dex_pc == -1) {
Elliott Hughes2aa2e392012-02-17 17:15:43 -08001814 // We use a pc of -1 to represent method entry, since we might branch back to pc 0 later.
1815 // This means that for this special notification, there can't be anything else interesting
1816 // going on, so we're done already.
1817 Dbg::PostLocationEvent(m, 0, GetThis(f), kMethodEntry);
1818 return;
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08001819 }
1820
Elliott Hughes2aa2e392012-02-17 17:15:43 -08001821 int event_flags = 0;
1822
Elliott Hughes86964332012-02-15 19:37:42 -08001823 if (IsBreakpoint(m, dex_pc)) {
1824 event_flags |= kBreakpoint;
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08001825 }
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08001826
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08001827 // If the debugger is single-stepping one of our threads, check to
1828 // see if we're that thread and we've reached a step point.
Elliott Hughes86964332012-02-15 19:37:42 -08001829 if (gSingleStepControl.is_active && gSingleStepControl.thread == self) {
1830 CHECK(!m->IsNative());
1831 if (gSingleStepControl.step_depth == JDWP::SD_INTO) {
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08001832 // Step into method calls. We break when the line number
1833 // or method pointer changes. If we're in SS_MIN mode, we
1834 // always stop.
Elliott Hughes86964332012-02-15 19:37:42 -08001835 if (gSingleStepControl.method != m) {
1836 event_flags |= kSingleStep;
1837 VLOG(jdwp) << "SS new method";
1838 } else if (gSingleStepControl.step_size == JDWP::SS_MIN) {
1839 event_flags |= kSingleStep;
1840 VLOG(jdwp) << "SS new instruction";
Elliott Hughes2435a572012-02-17 16:07:41 -08001841 } else if (gSingleStepControl.dex_pcs.find(dex_pc) == gSingleStepControl.dex_pcs.end()) {
1842 event_flags |= kSingleStep;
1843 VLOG(jdwp) << "SS new line";
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08001844 }
Elliott Hughes86964332012-02-15 19:37:42 -08001845 } else if (gSingleStepControl.step_depth == JDWP::SD_OVER) {
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08001846 // Step over method calls. We break when the line number is
1847 // different and the frame depth is <= the original frame
1848 // depth. (We can't just compare on the method, because we
1849 // might get unrolled past it by an exception, and it's tricky
1850 // to identify recursion.)
Elliott Hughes86964332012-02-15 19:37:42 -08001851
1852 // TODO: can we just use the value of 'sp'?
1853 int stack_depth = GetStackDepth(self);
1854
1855 if (stack_depth < gSingleStepControl.stack_depth) {
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08001856 // popped up one or more frames, always trigger
Elliott Hughes86964332012-02-15 19:37:42 -08001857 event_flags |= kSingleStep;
1858 VLOG(jdwp) << "SS method pop";
1859 } else if (stack_depth == gSingleStepControl.stack_depth) {
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08001860 // same depth, see if we moved
Elliott Hughes86964332012-02-15 19:37:42 -08001861 if (gSingleStepControl.step_size == JDWP::SS_MIN) {
1862 event_flags |= kSingleStep;
1863 VLOG(jdwp) << "SS new instruction";
Elliott Hughes2435a572012-02-17 16:07:41 -08001864 } else if (gSingleStepControl.dex_pcs.find(dex_pc) == gSingleStepControl.dex_pcs.end()) {
1865 event_flags |= kSingleStep;
1866 VLOG(jdwp) << "SS new line";
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08001867 }
1868 }
1869 } else {
Elliott Hughes86964332012-02-15 19:37:42 -08001870 CHECK_EQ(gSingleStepControl.step_depth, JDWP::SD_OUT);
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08001871 // Return from the current method. We break when the frame
1872 // depth pops up.
1873
1874 // This differs from the "method exit" break in that it stops
1875 // with the PC at the next instruction in the returned-to
1876 // function, rather than the end of the returning function.
Elliott Hughes86964332012-02-15 19:37:42 -08001877
1878 // TODO: can we just use the value of 'sp'?
1879 int stack_depth = GetStackDepth(self);
1880 if (stack_depth < gSingleStepControl.stack_depth) {
1881 event_flags |= kSingleStep;
1882 VLOG(jdwp) << "SS method pop";
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08001883 }
1884 }
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08001885 }
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08001886
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08001887 // Check to see if this is a "return" instruction. JDWP says we should
1888 // send the event *after* the code has been executed, but it also says
1889 // the location we provide is the last instruction. Since the "return"
1890 // instruction has no interesting side effects, we should be safe.
1891 // (We can't just move this down to the returnFromMethod label because
1892 // we potentially need to combine it with other events.)
1893 // We're also not supposed to generate a method exit event if the method
1894 // terminates "with a thrown exception".
Elliott Hughes86964332012-02-15 19:37:42 -08001895 if (dex_pc >= 0) {
1896 const DexFile::CodeItem* code_item = MethodHelper(m).GetCodeItem();
1897 CHECK(code_item != NULL);
1898 CHECK_LT(dex_pc, static_cast<int32_t>(code_item->insns_size_in_code_units_));
1899 if (Instruction::At(&code_item->insns_[dex_pc])->IsReturn()) {
1900 event_flags |= kMethodExit;
1901 }
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08001902 }
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08001903
1904 // If there's something interesting going on, see if it matches one
1905 // of the debugger filters.
1906 if (event_flags != 0) {
Elliott Hughes86964332012-02-15 19:37:42 -08001907 Dbg::PostLocationEvent(m, dex_pc, GetThis(f), event_flags);
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08001908 }
1909}
1910
Elliott Hughes86964332012-02-15 19:37:42 -08001911void Dbg::WatchLocation(const JDWP::JdwpLocation* location) {
1912 MutexLock mu(gBreakpointsLock);
1913 Method* m = FromMethodId(location->methodId);
Elliott Hughes972a47b2012-02-21 18:16:06 -08001914 gBreakpoints.push_back(Breakpoint(m, location->dex_pc));
Elliott Hughes86964332012-02-15 19:37:42 -08001915 VLOG(jdwp) << "Set breakpoint #" << (gBreakpoints.size() - 1) << ": " << gBreakpoints[gBreakpoints.size() - 1];
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001916}
1917
Elliott Hughes86964332012-02-15 19:37:42 -08001918void Dbg::UnwatchLocation(const JDWP::JdwpLocation* location) {
1919 MutexLock mu(gBreakpointsLock);
1920 Method* m = FromMethodId(location->methodId);
1921 for (size_t i = 0; i < gBreakpoints.size(); ++i) {
Elliott Hughes972a47b2012-02-21 18:16:06 -08001922 if (gBreakpoints[i].method == m && gBreakpoints[i].dex_pc == location->dex_pc) {
Elliott Hughes86964332012-02-15 19:37:42 -08001923 VLOG(jdwp) << "Removed breakpoint #" << i << ": " << gBreakpoints[i];
1924 gBreakpoints.erase(gBreakpoints.begin() + i);
1925 return;
1926 }
1927 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001928}
1929
Elliott Hughes2435a572012-02-17 16:07:41 -08001930JDWP::JdwpError Dbg::ConfigureStep(JDWP::ObjectId threadId, JDWP::JdwpStepSize step_size, JDWP::JdwpStepDepth step_depth) {
Elliott Hughes86964332012-02-15 19:37:42 -08001931 Thread* thread = DecodeThread(threadId);
Elliott Hughes2435a572012-02-17 16:07:41 -08001932 if (thread == NULL) {
1933 return JDWP::ERR_INVALID_THREAD;
1934 }
Elliott Hughes86964332012-02-15 19:37:42 -08001935
1936 // TODO: there's no theoretical reason why we couldn't support single-stepping
1937 // of multiple threads at once, but we never did so historically.
1938 if (gSingleStepControl.thread != NULL && thread != gSingleStepControl.thread) {
1939 LOG(WARNING) << "single-step already active for " << *gSingleStepControl.thread
1940 << "; switching to " << *thread;
1941 }
1942
Elliott Hughes2435a572012-02-17 16:07:41 -08001943 //
1944 // Work out what Method* we're in, the current line number, and how deep the stack currently
1945 // is for step-out.
1946 //
1947
Elliott Hughes86964332012-02-15 19:37:42 -08001948 struct SingleStepStackVisitor : public Thread::StackVisitor {
1949 SingleStepStackVisitor() {
1950 gSingleStepControl.method = NULL;
1951 gSingleStepControl.stack_depth = 0;
1952 }
Elliott Hughes530fa002012-03-12 11:44:49 -07001953 bool VisitFrame(const Frame& f, uintptr_t pc) {
Elliott Hughes86964332012-02-15 19:37:42 -08001954 if (f.HasMethod()) {
1955 ++gSingleStepControl.stack_depth;
1956 if (gSingleStepControl.method == NULL) {
Elliott Hughes2435a572012-02-17 16:07:41 -08001957 const Method* m = f.GetMethod();
1958 const DexCache* dex_cache = m->GetDeclaringClass()->GetDexCache();
1959 gSingleStepControl.method = m;
1960 gSingleStepControl.line_number = -1;
1961 if (dex_cache != NULL) {
1962 const DexFile& dex_file = Runtime::Current()->GetClassLinker()->FindDexFile(dex_cache);
1963 gSingleStepControl.line_number = dex_file.GetLineNumFromPC(m, m->ToDexPC(pc));
1964 }
Elliott Hughes86964332012-02-15 19:37:42 -08001965 }
1966 }
Elliott Hughes530fa002012-03-12 11:44:49 -07001967 return true;
Elliott Hughes86964332012-02-15 19:37:42 -08001968 }
1969 };
1970 SingleStepStackVisitor visitor;
1971 thread->WalkStack(&visitor);
1972
Elliott Hughes2435a572012-02-17 16:07:41 -08001973 //
1974 // Find the dex_pc values that correspond to the current line, for line-based single-stepping.
1975 //
1976
1977 struct DebugCallbackContext {
1978 DebugCallbackContext() {
1979 last_pc_valid = false;
1980 last_pc = 0;
Elliott Hughes2435a572012-02-17 16:07:41 -08001981 }
1982
1983 static bool Callback(void* raw_context, uint32_t address, uint32_t line_number) {
1984 DebugCallbackContext* context = reinterpret_cast<DebugCallbackContext*>(raw_context);
1985 if (static_cast<int32_t>(line_number) == gSingleStepControl.line_number) {
1986 if (!context->last_pc_valid) {
1987 // Everything from this address until the next line change is ours.
1988 context->last_pc = address;
1989 context->last_pc_valid = true;
1990 }
1991 // Otherwise, if we're already in a valid range for this line,
1992 // just keep going (shouldn't really happen)...
1993 } else if (context->last_pc_valid) { // and the line number is new
1994 // Add everything from the last entry up until here to the set
1995 for (uint32_t dex_pc = context->last_pc; dex_pc < address; ++dex_pc) {
1996 gSingleStepControl.dex_pcs.insert(dex_pc);
1997 }
1998 context->last_pc_valid = false;
1999 }
2000 return false; // There may be multiple entries for any given line.
2001 }
2002
2003 ~DebugCallbackContext() {
2004 // If the line number was the last in the position table...
2005 if (last_pc_valid) {
2006 size_t end = MethodHelper(gSingleStepControl.method).GetCodeItem()->insns_size_in_code_units_;
2007 for (uint32_t dex_pc = last_pc; dex_pc < end; ++dex_pc) {
2008 gSingleStepControl.dex_pcs.insert(dex_pc);
2009 }
2010 }
2011 }
2012
2013 bool last_pc_valid;
2014 uint32_t last_pc;
2015 };
Elliott Hughes3e2e1a22012-02-21 11:33:41 -08002016 gSingleStepControl.dex_pcs.clear();
Elliott Hughes2435a572012-02-17 16:07:41 -08002017 const Method* m = gSingleStepControl.method;
Elliott Hughes3e2e1a22012-02-21 11:33:41 -08002018 if (m->IsNative()) {
2019 gSingleStepControl.line_number = -1;
2020 } else {
2021 DebugCallbackContext context;
2022 MethodHelper mh(m);
2023 mh.GetDexFile().DecodeDebugInfo(mh.GetCodeItem(), m->IsStatic(), m->GetDexMethodIndex(),
2024 DebugCallbackContext::Callback, NULL, &context);
2025 }
Elliott Hughes2435a572012-02-17 16:07:41 -08002026
2027 //
2028 // Everything else...
2029 //
2030
Elliott Hughes86964332012-02-15 19:37:42 -08002031 gSingleStepControl.thread = thread;
2032 gSingleStepControl.step_size = step_size;
2033 gSingleStepControl.step_depth = step_depth;
2034 gSingleStepControl.is_active = true;
2035
Elliott Hughes2435a572012-02-17 16:07:41 -08002036 if (VLOG_IS_ON(jdwp)) {
2037 VLOG(jdwp) << "Single-step thread: " << *gSingleStepControl.thread;
2038 VLOG(jdwp) << "Single-step step size: " << gSingleStepControl.step_size;
2039 VLOG(jdwp) << "Single-step step depth: " << gSingleStepControl.step_depth;
2040 VLOG(jdwp) << "Single-step current method: " << PrettyMethod(gSingleStepControl.method);
2041 VLOG(jdwp) << "Single-step current line: " << gSingleStepControl.line_number;
2042 VLOG(jdwp) << "Single-step current stack depth: " << gSingleStepControl.stack_depth;
2043 VLOG(jdwp) << "Single-step dex_pc values:";
2044 for (std::set<uint32_t>::iterator it = gSingleStepControl.dex_pcs.begin() ; it != gSingleStepControl.dex_pcs.end(); ++it) {
Elliott Hughes229feb72012-02-23 13:33:29 -08002045 VLOG(jdwp) << StringPrintf(" %#x", *it);
Elliott Hughes2435a572012-02-17 16:07:41 -08002046 }
2047 }
2048
2049 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002050}
2051
Elliott Hughes1bac54f2012-03-16 12:48:31 -07002052void Dbg::UnconfigureStep(JDWP::ObjectId /*threadId*/) {
Elliott Hughes86964332012-02-15 19:37:42 -08002053 gSingleStepControl.is_active = false;
2054 gSingleStepControl.thread = NULL;
Elliott Hughes2435a572012-02-17 16:07:41 -08002055 gSingleStepControl.dex_pcs.clear();
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002056}
2057
Elliott Hughes45651fd2012-02-21 15:48:20 -08002058static char JdwpTagToShortyChar(JDWP::JdwpTag tag) {
2059 switch (tag) {
2060 default:
2061 LOG(FATAL) << "unknown JDWP tag: " << PrintableChar(tag);
2062
2063 // Primitives.
2064 case JDWP::JT_BYTE: return 'B';
2065 case JDWP::JT_CHAR: return 'C';
2066 case JDWP::JT_FLOAT: return 'F';
2067 case JDWP::JT_DOUBLE: return 'D';
2068 case JDWP::JT_INT: return 'I';
2069 case JDWP::JT_LONG: return 'J';
2070 case JDWP::JT_SHORT: return 'S';
2071 case JDWP::JT_VOID: return 'V';
2072 case JDWP::JT_BOOLEAN: return 'Z';
2073
2074 // Reference types.
2075 case JDWP::JT_ARRAY:
2076 case JDWP::JT_OBJECT:
2077 case JDWP::JT_STRING:
2078 case JDWP::JT_THREAD:
2079 case JDWP::JT_THREAD_GROUP:
2080 case JDWP::JT_CLASS_LOADER:
2081 case JDWP::JT_CLASS_OBJECT:
2082 return 'L';
2083 }
2084}
2085
2086JDWP::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 -08002087 ThreadList* thread_list = Runtime::Current()->GetThreadList();
2088
2089 Thread* targetThread = NULL;
2090 DebugInvokeReq* req = NULL;
2091 {
2092 ScopedThreadListLock thread_list_lock;
2093 targetThread = DecodeThread(threadId);
2094 if (targetThread == NULL) {
2095 LOG(ERROR) << "InvokeMethod request for non-existent thread " << threadId;
2096 return JDWP::ERR_INVALID_THREAD;
2097 }
2098 req = targetThread->GetInvokeReq();
2099 if (!req->ready) {
2100 LOG(ERROR) << "InvokeMethod request for thread not stopped by event: " << *targetThread;
2101 return JDWP::ERR_INVALID_THREAD;
2102 }
2103
2104 /*
2105 * We currently have a bug where we don't successfully resume the
2106 * target thread if the suspend count is too deep. We're expected to
2107 * require one "resume" for each "suspend", but when asked to execute
2108 * a method we have to resume fully and then re-suspend it back to the
2109 * same level. (The easiest way to cause this is to type "suspend"
2110 * multiple times in jdb.)
2111 *
2112 * It's unclear what this means when the event specifies "resume all"
2113 * and some threads are suspended more deeply than others. This is
2114 * a rare problem, so for now we just prevent it from hanging forever
2115 * by rejecting the method invocation request. Without this, we will
2116 * be stuck waiting on a suspended thread.
2117 */
2118 int suspend_count = targetThread->GetSuspendCount();
2119 if (suspend_count > 1) {
2120 LOG(ERROR) << *targetThread << " suspend count too deep for method invocation: " << suspend_count;
2121 return JDWP::ERR_THREAD_SUSPENDED; // Probably not expected here.
2122 }
2123
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08002124 JDWP::JdwpError status;
Elliott Hughes45651fd2012-02-21 15:48:20 -08002125 Object* receiver = gRegistry->Get<Object*>(objectId);
2126 if (receiver == kInvalidObject) {
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08002127 return JDWP::ERR_INVALID_OBJECT;
2128 }
Elliott Hughes45651fd2012-02-21 15:48:20 -08002129
2130 Object* thread = gRegistry->Get<Object*>(threadId);
2131 if (thread == kInvalidObject) {
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08002132 return JDWP::ERR_INVALID_OBJECT;
2133 }
Elliott Hughes45651fd2012-02-21 15:48:20 -08002134 // TODO: check that 'thread' is actually a java.lang.Thread!
2135
2136 Class* c = DecodeClass(classId, status);
2137 if (c == NULL) {
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08002138 return status;
2139 }
Elliott Hughes45651fd2012-02-21 15:48:20 -08002140
2141 Method* m = FromMethodId(methodId);
2142 if (m->IsStatic() != (receiver == NULL)) {
2143 return JDWP::ERR_INVALID_METHODID;
2144 }
2145 if (m->IsStatic()) {
2146 if (m->GetDeclaringClass() != c) {
2147 return JDWP::ERR_INVALID_METHODID;
2148 }
2149 } else {
2150 if (!m->GetDeclaringClass()->IsAssignableFrom(c)) {
2151 return JDWP::ERR_INVALID_METHODID;
2152 }
2153 }
2154
2155 // Check the argument list matches the method.
2156 MethodHelper mh(m);
2157 if (mh.GetShortyLength() - 1 != arg_count) {
2158 return JDWP::ERR_ILLEGAL_ARGUMENT;
2159 }
2160 const char* shorty = mh.GetShorty();
2161 for (size_t i = 0; i < arg_count; ++i) {
2162 if (shorty[i + 1] != JdwpTagToShortyChar(arg_types[i])) {
2163 return JDWP::ERR_ILLEGAL_ARGUMENT;
2164 }
2165 }
2166
2167 req->receiver_ = receiver;
2168 req->thread_ = thread;
2169 req->class_ = c;
2170 req->method_ = m;
2171 req->arg_count_ = arg_count;
2172 req->arg_values_ = arg_values;
Elliott Hughesd07986f2011-12-06 18:27:45 -08002173 req->options_ = options;
2174 req->invoke_needed_ = true;
2175 }
2176
2177 // The fact that we've released the thread list lock is a bit risky --- if the thread goes
2178 // away we're sitting high and dry -- but we must release this before the ResumeAllThreads
2179 // call, and it's unwise to hold it during WaitForSuspend.
2180
2181 {
2182 /*
2183 * We change our (JDWP thread) status, which should be THREAD_RUNNING,
Elliott Hughes81ff3182012-03-23 20:35:56 -07002184 * so we can suspend for a GC if the invoke request causes us to
Elliott Hughesd07986f2011-12-06 18:27:45 -08002185 * run out of memory. It's also a good idea to change it before locking
2186 * the invokeReq mutex, although that should never be held for long.
2187 */
Elliott Hughes34e06962012-04-09 13:55:55 -07002188 ScopedThreadStateChange tsc(Thread::Current(), kVmWait);
Elliott Hughesd07986f2011-12-06 18:27:45 -08002189
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08002190 VLOG(jdwp) << " Transferring control to event thread";
Elliott Hughesd07986f2011-12-06 18:27:45 -08002191 {
2192 MutexLock mu(req->lock_);
2193
2194 if ((options & JDWP::INVOKE_SINGLE_THREADED) == 0) {
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08002195 VLOG(jdwp) << " Resuming all threads";
Elliott Hughesd07986f2011-12-06 18:27:45 -08002196 thread_list->ResumeAll(true);
2197 } else {
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08002198 VLOG(jdwp) << " Resuming event thread only";
Elliott Hughesd07986f2011-12-06 18:27:45 -08002199 thread_list->Resume(targetThread, true);
2200 }
2201
2202 // Wait for the request to finish executing.
2203 while (req->invoke_needed_) {
2204 req->cond_.Wait(req->lock_);
2205 }
2206 }
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08002207 VLOG(jdwp) << " Control has returned from event thread";
Elliott Hughesd07986f2011-12-06 18:27:45 -08002208
2209 /* wait for thread to re-suspend itself */
2210 targetThread->WaitUntilSuspended();
2211 //dvmWaitForSuspend(targetThread);
2212 }
2213
2214 /*
2215 * Suspend the threads. We waited for the target thread to suspend
2216 * itself, so all we need to do is suspend the others.
2217 *
2218 * The suspendAllThreads() call will double-suspend the event thread,
2219 * so we want to resume the target thread once to keep the books straight.
2220 */
2221 if ((options & JDWP::INVOKE_SINGLE_THREADED) == 0) {
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08002222 VLOG(jdwp) << " Suspending all threads";
Elliott Hughesd07986f2011-12-06 18:27:45 -08002223 thread_list->SuspendAll(true);
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08002224 VLOG(jdwp) << " Resuming event thread to balance the count";
Elliott Hughesd07986f2011-12-06 18:27:45 -08002225 thread_list->Resume(targetThread, true);
2226 }
2227
2228 // Copy the result.
2229 *pResultTag = req->result_tag;
2230 if (IsPrimitiveTag(req->result_tag)) {
Elliott Hughesf24d3ce2012-04-11 17:43:37 -07002231 *pResultValue = req->result_value.GetJ();
Elliott Hughesd07986f2011-12-06 18:27:45 -08002232 } else {
Elliott Hughesf24d3ce2012-04-11 17:43:37 -07002233 *pResultValue = gRegistry->Add(req->result_value.GetL());
Elliott Hughesd07986f2011-12-06 18:27:45 -08002234 }
2235 *pExceptionId = req->exception;
2236 return req->error;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002237}
2238
2239void Dbg::ExecuteMethod(DebugInvokeReq* pReq) {
Elliott Hughesd07986f2011-12-06 18:27:45 -08002240 Thread* self = Thread::Current();
2241
Elliott Hughes81ff3182012-03-23 20:35:56 -07002242 // We can be called while an exception is pending. We need
Elliott Hughesd07986f2011-12-06 18:27:45 -08002243 // to preserve that across the method invocation.
2244 SirtRef<Throwable> old_exception(self->GetException());
2245 self->ClearException();
2246
Elliott Hughes34e06962012-04-09 13:55:55 -07002247 ScopedThreadStateChange tsc(self, kRunnable);
Elliott Hughesd07986f2011-12-06 18:27:45 -08002248
2249 // Translate the method through the vtable, unless the debugger wants to suppress it.
2250 Method* m = pReq->method_;
2251 if ((pReq->options_ & JDWP::INVOKE_NONVIRTUAL) == 0 && pReq->receiver_ != NULL) {
Elliott Hughes45651fd2012-02-21 15:48:20 -08002252 Method* actual_method = pReq->class_->FindVirtualMethodForVirtualOrInterface(pReq->method_);
2253 if (actual_method != m) {
2254 VLOG(jdwp) << "ExecuteMethod translated " << PrettyMethod(m) << " to " << PrettyMethod(actual_method);
2255 m = actual_method;
2256 }
Elliott Hughesd07986f2011-12-06 18:27:45 -08002257 }
Elliott Hughes45651fd2012-02-21 15:48:20 -08002258 VLOG(jdwp) << "ExecuteMethod " << PrettyMethod(m);
Elliott Hughesd07986f2011-12-06 18:27:45 -08002259 CHECK(m != NULL);
2260
2261 CHECK_EQ(sizeof(jvalue), sizeof(uint64_t));
2262
Elliott Hughes45651fd2012-02-21 15:48:20 -08002263 LOG(INFO) << "self=" << self << " pReq->receiver_=" << pReq->receiver_ << " m=" << m << " #" << pReq->arg_count_ << " " << pReq->arg_values_;
2264 pReq->result_value = InvokeWithJValues(self, pReq->receiver_, m, reinterpret_cast<JValue*>(pReq->arg_values_));
Elliott Hughesd07986f2011-12-06 18:27:45 -08002265
2266 pReq->exception = gRegistry->Add(self->GetException());
2267 pReq->result_tag = BasicTagFromDescriptor(MethodHelper(m).GetShorty());
2268 if (pReq->exception != 0) {
2269 Object* exc = self->GetException();
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08002270 VLOG(jdwp) << " JDWP invocation returning with exception=" << exc << " " << PrettyTypeOf(exc);
Elliott Hughesd07986f2011-12-06 18:27:45 -08002271 self->ClearException();
Elliott Hughesf24d3ce2012-04-11 17:43:37 -07002272 pReq->result_value.SetJ(0);
Elliott Hughesd07986f2011-12-06 18:27:45 -08002273 } else if (pReq->result_tag == JDWP::JT_OBJECT) {
2274 /* if no exception thrown, examine object result more closely */
Elliott Hughesf24d3ce2012-04-11 17:43:37 -07002275 JDWP::JdwpTag new_tag = TagFromObject(pReq->result_value.GetL());
Elliott Hughesd07986f2011-12-06 18:27:45 -08002276 if (new_tag != pReq->result_tag) {
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08002277 VLOG(jdwp) << " JDWP promoted result from " << pReq->result_tag << " to " << new_tag;
Elliott Hughesd07986f2011-12-06 18:27:45 -08002278 pReq->result_tag = new_tag;
2279 }
2280
2281 /*
2282 * Register the object. We don't actually need an ObjectId yet,
2283 * but we do need to be sure that the GC won't move or discard the
2284 * object when we switch out of RUNNING. The ObjectId conversion
2285 * will add the object to the "do not touch" list.
2286 *
2287 * We can't use the "tracked allocation" mechanism here because
2288 * the object is going to be handed off to a different thread.
2289 */
Elliott Hughesf24d3ce2012-04-11 17:43:37 -07002290 gRegistry->Add(pReq->result_value.GetL());
Elliott Hughesd07986f2011-12-06 18:27:45 -08002291 }
2292
2293 if (old_exception.get() != NULL) {
2294 self->SetException(old_exception.get());
2295 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002296}
2297
Elliott Hughesd07986f2011-12-06 18:27:45 -08002298/*
2299 * Register an object ID that might not have been registered previously.
2300 *
2301 * Normally this wouldn't happen -- the conversion to an ObjectId would
2302 * have added the object to the registry -- but in some cases (e.g.
2303 * throwing exceptions) we really want to do the registration late.
2304 */
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002305void Dbg::RegisterObjectId(JDWP::ObjectId id) {
Elliott Hughesd07986f2011-12-06 18:27:45 -08002306 gRegistry->Add(reinterpret_cast<Object*>(id));
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002307}
2308
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07002309/*
2310 * "buf" contains a full JDWP packet, possibly with multiple chunks. We
2311 * need to process each, accumulate the replies, and ship the whole thing
2312 * back.
2313 *
2314 * Returns "true" if we have a reply. The reply buffer is newly allocated,
2315 * and includes the chunk type/length, followed by the data.
2316 *
Elliott Hughes3d30d9b2011-12-07 17:35:48 -08002317 * OLD-TODO: we currently assume that the request and reply include a single
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07002318 * chunk. If this becomes inconvenient we will need to adapt.
2319 */
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002320bool Dbg::DdmHandlePacket(const uint8_t* buf, int dataLen, uint8_t** pReplyBuf, int* pReplyLen) {
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07002321 CHECK_GE(dataLen, 0);
2322
2323 Thread* self = Thread::Current();
2324 JNIEnv* env = self->GetJniEnv();
2325
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07002326 // Create a byte[] corresponding to 'buf'.
Elliott Hughes6a5bd492011-10-28 14:33:57 -07002327 ScopedLocalRef<jbyteArray> dataArray(env, env->NewByteArray(dataLen));
2328 if (dataArray.get() == NULL) {
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07002329 LOG(WARNING) << "byte[] allocation failed: " << dataLen;
2330 env->ExceptionClear();
2331 return false;
2332 }
Elliott Hughes6a5bd492011-10-28 14:33:57 -07002333 env->SetByteArrayRegion(dataArray.get(), 0, dataLen, reinterpret_cast<const jbyte*>(buf));
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07002334
2335 const int kChunkHdrLen = 8;
2336
2337 // Run through and find all chunks. [Currently just find the first.]
Elliott Hughes6a5bd492011-10-28 14:33:57 -07002338 ScopedByteArrayRO contents(env, dataArray.get());
Elliott Hughesf7c3b662011-10-27 12:04:56 -07002339 jint type = JDWP::Get4BE(reinterpret_cast<const uint8_t*>(&contents[0]));
2340 jint length = JDWP::Get4BE(reinterpret_cast<const uint8_t*>(&contents[4]));
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07002341 jint offset = kChunkHdrLen;
2342 if (offset + length > dataLen) {
2343 LOG(WARNING) << StringPrintf("bad chunk found (len=%u pktLen=%d)", length, dataLen);
2344 return false;
2345 }
2346
2347 // Call "private static Chunk dispatch(int type, byte[] data, int offset, int length)".
Elliott Hugheseac76672012-05-24 21:56:51 -07002348 ScopedLocalRef<jobject> chunk(env, env->CallStaticObjectMethod(WellKnownClasses::org_apache_harmony_dalvik_ddmc_DdmServer,
2349 WellKnownClasses::org_apache_harmony_dalvik_ddmc_DdmServer_dispatch,
2350 type, dataArray.get(), offset, length));
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07002351 if (env->ExceptionCheck()) {
2352 LOG(INFO) << StringPrintf("Exception thrown by dispatcher for 0x%08x", type);
2353 env->ExceptionDescribe();
2354 env->ExceptionClear();
2355 return false;
2356 }
2357
Elliott Hughes6a5bd492011-10-28 14:33:57 -07002358 if (chunk.get() == NULL) {
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07002359 return false;
2360 }
2361
2362 /*
2363 * Pull the pieces out of the chunk. We copy the results into a
2364 * newly-allocated buffer that the caller can free. We don't want to
2365 * continue using the Chunk object because nothing has a reference to it.
2366 *
2367 * We could avoid this by returning type/data/offset/length and having
2368 * the caller be aware of the object lifetime issues, but that
Elliott Hughes81ff3182012-03-23 20:35:56 -07002369 * integrates the JDWP code more tightly into the rest of the runtime, and doesn't work
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07002370 * if we have responses for multiple chunks.
2371 *
2372 * So we're pretty much stuck with copying data around multiple times.
2373 */
Elliott Hugheseac76672012-05-24 21:56:51 -07002374 ScopedLocalRef<jbyteArray> replyData(env, reinterpret_cast<jbyteArray>(env->GetObjectField(chunk.get(), WellKnownClasses::org_apache_harmony_dalvik_ddmc_Chunk_data)));
2375 length = env->GetIntField(chunk.get(), WellKnownClasses::org_apache_harmony_dalvik_ddmc_Chunk_length);
2376 offset = env->GetIntField(chunk.get(), WellKnownClasses::org_apache_harmony_dalvik_ddmc_Chunk_offset);
2377 type = env->GetIntField(chunk.get(), WellKnownClasses::org_apache_harmony_dalvik_ddmc_Chunk_type);
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07002378
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08002379 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 -07002380 if (length == 0 || replyData.get() == NULL) {
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07002381 return false;
2382 }
2383
Elliott Hughes6a5bd492011-10-28 14:33:57 -07002384 jsize replyLength = env->GetArrayLength(replyData.get());
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07002385 if (offset + length > replyLength) {
2386 LOG(WARNING) << StringPrintf("chunk off=%d len=%d exceeds reply array len %d", offset, length, replyLength);
2387 return false;
2388 }
2389
2390 uint8_t* reply = new uint8_t[length + kChunkHdrLen];
2391 if (reply == NULL) {
2392 LOG(WARNING) << "malloc failed: " << (length + kChunkHdrLen);
2393 return false;
2394 }
Elliott Hughesf7c3b662011-10-27 12:04:56 -07002395 JDWP::Set4BE(reply + 0, type);
2396 JDWP::Set4BE(reply + 4, length);
Elliott Hughes6a5bd492011-10-28 14:33:57 -07002397 env->GetByteArrayRegion(replyData.get(), offset, length, reinterpret_cast<jbyte*>(reply + kChunkHdrLen));
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07002398
2399 *pReplyBuf = reply;
2400 *pReplyLen = length + kChunkHdrLen;
2401
Elliott Hughesba8eee12012-01-24 20:25:24 -08002402 VLOG(jdwp) << StringPrintf("dvmHandleDdm returning type=%.4s buf=%p len=%d", reinterpret_cast<char*>(reply), reply, length);
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07002403 return true;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002404}
2405
Elliott Hughesa2155262011-11-16 16:26:58 -08002406void Dbg::DdmBroadcast(bool connect) {
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08002407 VLOG(jdwp) << "Broadcasting DDM " << (connect ? "connect" : "disconnect") << "...";
Elliott Hughes47fce012011-10-25 18:37:19 -07002408
2409 Thread* self = Thread::Current();
Elliott Hughes34e06962012-04-09 13:55:55 -07002410 if (self->GetState() != kRunnable) {
Elliott Hughes47fce012011-10-25 18:37:19 -07002411 LOG(ERROR) << "DDM broadcast in thread state " << self->GetState();
2412 /* try anyway? */
2413 }
2414
2415 JNIEnv* env = self->GetJniEnv();
Elliott Hughes47fce012011-10-25 18:37:19 -07002416 jint event = connect ? 1 /*DdmServer.CONNECTED*/ : 2 /*DdmServer.DISCONNECTED*/;
Elliott Hugheseac76672012-05-24 21:56:51 -07002417 env->CallStaticVoidMethod(WellKnownClasses::org_apache_harmony_dalvik_ddmc_DdmServer,
2418 WellKnownClasses::org_apache_harmony_dalvik_ddmc_DdmServer_broadcast,
2419 event);
Elliott Hughes47fce012011-10-25 18:37:19 -07002420 if (env->ExceptionCheck()) {
2421 LOG(ERROR) << "DdmServer.broadcast " << event << " failed";
2422 env->ExceptionDescribe();
2423 env->ExceptionClear();
2424 }
2425}
2426
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002427void Dbg::DdmConnected() {
Elliott Hughesa2155262011-11-16 16:26:58 -08002428 Dbg::DdmBroadcast(true);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002429}
2430
2431void Dbg::DdmDisconnected() {
Elliott Hughesa2155262011-11-16 16:26:58 -08002432 Dbg::DdmBroadcast(false);
Elliott Hughes47fce012011-10-25 18:37:19 -07002433 gDdmThreadNotification = false;
2434}
2435
2436/*
Elliott Hughes82188472011-11-07 18:11:48 -08002437 * Send a notification when a thread starts, stops, or changes its name.
Elliott Hughes47fce012011-10-25 18:37:19 -07002438 *
2439 * Because we broadcast the full set of threads when the notifications are
2440 * first enabled, it's possible for "thread" to be actively executing.
2441 */
Elliott Hughes82188472011-11-07 18:11:48 -08002442void Dbg::DdmSendThreadNotification(Thread* t, uint32_t type) {
Elliott Hughes47fce012011-10-25 18:37:19 -07002443 if (!gDdmThreadNotification) {
2444 return;
2445 }
2446
Elliott Hughes82188472011-11-07 18:11:48 -08002447 if (type == CHUNK_TYPE("THDE")) {
Elliott Hughes47fce012011-10-25 18:37:19 -07002448 uint8_t buf[4];
Elliott Hughesf7c3b662011-10-27 12:04:56 -07002449 JDWP::Set4BE(&buf[0], t->GetThinLockId());
Elliott Hughes47fce012011-10-25 18:37:19 -07002450 Dbg::DdmSendChunk(CHUNK_TYPE("THDE"), 4, buf);
Elliott Hughes82188472011-11-07 18:11:48 -08002451 } else {
2452 CHECK(type == CHUNK_TYPE("THCR") || type == CHUNK_TYPE("THNM")) << type;
Elliott Hughes899e7892012-01-24 14:57:32 -08002453 SirtRef<String> name(t->GetThreadName());
Elliott Hughes82188472011-11-07 18:11:48 -08002454 size_t char_count = (name.get() != NULL) ? name->GetLength() : 0;
2455 const jchar* chars = name->GetCharArray()->GetData();
2456
Elliott Hughes21f32d72011-11-09 17:44:13 -08002457 std::vector<uint8_t> bytes;
Elliott Hughes545a0642011-11-08 19:10:03 -08002458 JDWP::Append4BE(bytes, t->GetThinLockId());
2459 JDWP::AppendUtf16BE(bytes, chars, char_count);
Elliott Hughes21f32d72011-11-09 17:44:13 -08002460 CHECK_EQ(bytes.size(), char_count*2 + sizeof(uint32_t)*2);
2461 Dbg::DdmSendChunk(type, bytes);
Elliott Hughes47fce012011-10-25 18:37:19 -07002462 }
2463}
2464
Elliott Hughesa2155262011-11-16 16:26:58 -08002465static void DdmSendThreadStartCallback(Thread* t, void*) {
Elliott Hughes82188472011-11-07 18:11:48 -08002466 Dbg::DdmSendThreadNotification(t, CHUNK_TYPE("THCR"));
Elliott Hughes47fce012011-10-25 18:37:19 -07002467}
2468
2469void Dbg::DdmSetThreadNotification(bool enable) {
2470 // We lock the thread list to avoid sending duplicate events or missing
2471 // a thread change. We should be okay holding this lock while sending
2472 // the messages out. (We have to hold it while accessing a live thread.)
Elliott Hughesbbd9d832011-11-07 14:40:00 -08002473 ScopedThreadListLock thread_list_lock;
Elliott Hughes47fce012011-10-25 18:37:19 -07002474
2475 gDdmThreadNotification = enable;
2476 if (enable) {
Elliott Hughesbfe487b2011-10-26 15:48:55 -07002477 Runtime::Current()->GetThreadList()->ForEach(DdmSendThreadStartCallback, NULL);
Elliott Hughes47fce012011-10-25 18:37:19 -07002478 }
2479}
2480
Elliott Hughesa2155262011-11-16 16:26:58 -08002481void Dbg::PostThreadStartOrStop(Thread* t, uint32_t type) {
Elliott Hughesc0f09332012-03-26 13:27:06 -07002482 if (IsDebuggerActive()) {
Elliott Hughes47fce012011-10-25 18:37:19 -07002483 JDWP::ObjectId id = gRegistry->Add(t->GetPeer());
Elliott Hughes82188472011-11-07 18:11:48 -08002484 gJdwpState->PostThreadChange(id, type == CHUNK_TYPE("THCR"));
Elliott Hughesc0f09332012-03-26 13:27:06 -07002485 // If this thread's just joined the party while we're already debugging, make sure it knows
2486 // to give us updates when it's running.
2487 t->SetDebuggerUpdatesEnabled(true);
Elliott Hughes47fce012011-10-25 18:37:19 -07002488 }
Elliott Hughes82188472011-11-07 18:11:48 -08002489 Dbg::DdmSendThreadNotification(t, type);
Elliott Hughes47fce012011-10-25 18:37:19 -07002490}
2491
2492void Dbg::PostThreadStart(Thread* t) {
Elliott Hughesa2155262011-11-16 16:26:58 -08002493 Dbg::PostThreadStartOrStop(t, CHUNK_TYPE("THCR"));
Elliott Hughes47fce012011-10-25 18:37:19 -07002494}
2495
2496void Dbg::PostThreadDeath(Thread* t) {
Elliott Hughesa2155262011-11-16 16:26:58 -08002497 Dbg::PostThreadStartOrStop(t, CHUNK_TYPE("THDE"));
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002498}
2499
Elliott Hughes82188472011-11-07 18:11:48 -08002500void Dbg::DdmSendChunk(uint32_t type, size_t byte_count, const uint8_t* buf) {
Elliott Hughes3bb81562011-10-21 18:52:59 -07002501 CHECK(buf != NULL);
2502 iovec vec[1];
2503 vec[0].iov_base = reinterpret_cast<void*>(const_cast<uint8_t*>(buf));
2504 vec[0].iov_len = byte_count;
2505 Dbg::DdmSendChunkV(type, vec, 1);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002506}
2507
Elliott Hughes21f32d72011-11-09 17:44:13 -08002508void Dbg::DdmSendChunk(uint32_t type, const std::vector<uint8_t>& bytes) {
2509 DdmSendChunk(type, bytes.size(), &bytes[0]);
2510}
2511
Elliott Hughescccd84f2011-12-05 16:51:54 -08002512void Dbg::DdmSendChunkV(uint32_t type, const struct iovec* iov, int iov_count) {
Elliott Hughes3bb81562011-10-21 18:52:59 -07002513 if (gJdwpState == NULL) {
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08002514 VLOG(jdwp) << "Debugger thread not active, ignoring DDM send: " << type;
Elliott Hughes3bb81562011-10-21 18:52:59 -07002515 } else {
Elliott Hughescccd84f2011-12-05 16:51:54 -08002516 gJdwpState->DdmSendChunkV(type, iov, iov_count);
Elliott Hughes3bb81562011-10-21 18:52:59 -07002517 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002518}
2519
Elliott Hughes767a1472011-10-26 18:49:02 -07002520int Dbg::DdmHandleHpifChunk(HpifWhen when) {
2521 if (when == HPIF_WHEN_NOW) {
Elliott Hughes7162ad92011-10-27 14:08:42 -07002522 DdmSendHeapInfo(when);
Elliott Hughes767a1472011-10-26 18:49:02 -07002523 return true;
2524 }
2525
2526 if (when != HPIF_WHEN_NEVER && when != HPIF_WHEN_NEXT_GC && when != HPIF_WHEN_EVERY_GC) {
2527 LOG(ERROR) << "invalid HpifWhen value: " << static_cast<int>(when);
2528 return false;
2529 }
2530
2531 gDdmHpifWhen = when;
2532 return true;
2533}
2534
2535bool Dbg::DdmHandleHpsgNhsgChunk(Dbg::HpsgWhen when, Dbg::HpsgWhat what, bool native) {
2536 if (when != HPSG_WHEN_NEVER && when != HPSG_WHEN_EVERY_GC) {
2537 LOG(ERROR) << "invalid HpsgWhen value: " << static_cast<int>(when);
2538 return false;
2539 }
2540
2541 if (what != HPSG_WHAT_MERGED_OBJECTS && what != HPSG_WHAT_DISTINCT_OBJECTS) {
2542 LOG(ERROR) << "invalid HpsgWhat value: " << static_cast<int>(what);
2543 return false;
2544 }
2545
2546 if (native) {
2547 gDdmNhsgWhen = when;
2548 gDdmNhsgWhat = what;
2549 } else {
2550 gDdmHpsgWhen = when;
2551 gDdmHpsgWhat = what;
2552 }
2553 return true;
2554}
2555
Elliott Hughes7162ad92011-10-27 14:08:42 -07002556void Dbg::DdmSendHeapInfo(HpifWhen reason) {
2557 // If there's a one-shot 'when', reset it.
2558 if (reason == gDdmHpifWhen) {
2559 if (gDdmHpifWhen == HPIF_WHEN_NEXT_GC) {
2560 gDdmHpifWhen = HPIF_WHEN_NEVER;
2561 }
2562 }
2563
2564 /*
2565 * Chunk HPIF (client --> server)
2566 *
2567 * Heap Info. General information about the heap,
2568 * suitable for a summary display.
2569 *
2570 * [u4]: number of heaps
2571 *
2572 * For each heap:
2573 * [u4]: heap ID
2574 * [u8]: timestamp in ms since Unix epoch
2575 * [u1]: capture reason (same as 'when' value from server)
2576 * [u4]: max heap size in bytes (-Xmx)
2577 * [u4]: current heap size in bytes
2578 * [u4]: current number of bytes allocated
2579 * [u4]: current number of objects allocated
2580 */
2581 uint8_t heap_count = 1;
Elliott Hughesb3bd5f02012-03-08 21:05:27 -08002582 Heap* heap = Runtime::Current()->GetHeap();
Elliott Hughes21f32d72011-11-09 17:44:13 -08002583 std::vector<uint8_t> bytes;
Elliott Hughes545a0642011-11-08 19:10:03 -08002584 JDWP::Append4BE(bytes, heap_count);
2585 JDWP::Append4BE(bytes, 1); // Heap id (bogus; we only have one heap).
2586 JDWP::Append8BE(bytes, MilliTime());
2587 JDWP::Append1BE(bytes, reason);
Elliott Hughesb3bd5f02012-03-08 21:05:27 -08002588 JDWP::Append4BE(bytes, heap->GetMaxMemory()); // Max allowed heap size in bytes.
2589 JDWP::Append4BE(bytes, heap->GetTotalMemory()); // Current heap size in bytes.
2590 JDWP::Append4BE(bytes, heap->GetBytesAllocated());
2591 JDWP::Append4BE(bytes, heap->GetObjectsAllocated());
Elliott Hughes21f32d72011-11-09 17:44:13 -08002592 CHECK_EQ(bytes.size(), 4U + (heap_count * (4 + 8 + 1 + 4 + 4 + 4 + 4)));
2593 Dbg::DdmSendChunk(CHUNK_TYPE("HPIF"), bytes);
Elliott Hughes767a1472011-10-26 18:49:02 -07002594}
2595
Elliott Hughes6a5bd492011-10-28 14:33:57 -07002596enum HpsgSolidity {
2597 SOLIDITY_FREE = 0,
2598 SOLIDITY_HARD = 1,
2599 SOLIDITY_SOFT = 2,
2600 SOLIDITY_WEAK = 3,
2601 SOLIDITY_PHANTOM = 4,
2602 SOLIDITY_FINALIZABLE = 5,
2603 SOLIDITY_SWEEP = 6,
2604};
2605
2606enum HpsgKind {
2607 KIND_OBJECT = 0,
2608 KIND_CLASS_OBJECT = 1,
2609 KIND_ARRAY_1 = 2,
2610 KIND_ARRAY_2 = 3,
2611 KIND_ARRAY_4 = 4,
2612 KIND_ARRAY_8 = 5,
2613 KIND_UNKNOWN = 6,
2614 KIND_NATIVE = 7,
2615};
2616
2617#define HPSG_PARTIAL (1<<7)
2618#define HPSG_STATE(solidity, kind) ((uint8_t)((((kind) & 0x7) << 3) | ((solidity) & 0x7)))
2619
Ian Rogers30fab402012-01-23 15:43:46 -08002620class HeapChunkContext {
2621 public:
Elliott Hughes6a5bd492011-10-28 14:33:57 -07002622 // Maximum chunk size. Obtain this from the formula:
2623 // (((maximum_heap_size / ALLOCATION_UNIT_SIZE) + 255) / 256) * 2
2624 HeapChunkContext(bool merge, bool native)
Ian Rogers30fab402012-01-23 15:43:46 -08002625 : buf_(16384 - 16),
2626 type_(0),
2627 merge_(merge) {
Elliott Hughes6a5bd492011-10-28 14:33:57 -07002628 Reset();
2629 if (native) {
Ian Rogers30fab402012-01-23 15:43:46 -08002630 type_ = CHUNK_TYPE("NHSG");
Elliott Hughes6a5bd492011-10-28 14:33:57 -07002631 } else {
Ian Rogers30fab402012-01-23 15:43:46 -08002632 type_ = merge ? CHUNK_TYPE("HPSG") : CHUNK_TYPE("HPSO");
Elliott Hughes6a5bd492011-10-28 14:33:57 -07002633 }
2634 }
2635
2636 ~HeapChunkContext() {
Ian Rogers30fab402012-01-23 15:43:46 -08002637 if (p_ > &buf_[0]) {
Elliott Hughes6a5bd492011-10-28 14:33:57 -07002638 Flush();
2639 }
2640 }
2641
2642 void EnsureHeader(const void* chunk_ptr) {
Ian Rogers30fab402012-01-23 15:43:46 -08002643 if (!needHeader_) {
Elliott Hughes6a5bd492011-10-28 14:33:57 -07002644 return;
2645 }
2646
2647 // Start a new HPSx chunk.
Ian Rogers30fab402012-01-23 15:43:46 -08002648 JDWP::Write4BE(&p_, 1); // Heap id (bogus; we only have one heap).
2649 JDWP::Write1BE(&p_, 8); // Size of allocation unit, in bytes.
Elliott Hughes6a5bd492011-10-28 14:33:57 -07002650
Ian Rogers30fab402012-01-23 15:43:46 -08002651 JDWP::Write4BE(&p_, reinterpret_cast<uintptr_t>(chunk_ptr)); // virtual address of segment start.
2652 JDWP::Write4BE(&p_, 0); // offset of this piece (relative to the virtual address).
Elliott Hughes6a5bd492011-10-28 14:33:57 -07002653 // [u4]: length of piece, in allocation units
2654 // 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 -08002655 pieceLenField_ = p_;
2656 JDWP::Write4BE(&p_, 0x55555555);
2657 needHeader_ = false;
Elliott Hughes6a5bd492011-10-28 14:33:57 -07002658 }
2659
2660 void Flush() {
2661 // Patch the "length of piece" field.
Ian Rogers30fab402012-01-23 15:43:46 -08002662 CHECK_LE(&buf_[0], pieceLenField_);
2663 CHECK_LE(pieceLenField_, p_);
2664 JDWP::Set4BE(pieceLenField_, totalAllocationUnits_);
Elliott Hughes6a5bd492011-10-28 14:33:57 -07002665
Ian Rogers30fab402012-01-23 15:43:46 -08002666 Dbg::DdmSendChunk(type_, p_ - &buf_[0], &buf_[0]);
Elliott Hughes6a5bd492011-10-28 14:33:57 -07002667 Reset();
2668 }
2669
Ian Rogers30fab402012-01-23 15:43:46 -08002670 static void HeapChunkCallback(void* start, void* end, size_t used_bytes, void* arg) {
2671 reinterpret_cast<HeapChunkContext*>(arg)->HeapChunkCallback(start, end, used_bytes);
Elliott Hughesa2155262011-11-16 16:26:58 -08002672 }
2673
Elliott Hughes6a5bd492011-10-28 14:33:57 -07002674 private:
Elliott Hughesa2155262011-11-16 16:26:58 -08002675 enum { ALLOCATION_UNIT_SIZE = 8 };
2676
Elliott Hughes6a5bd492011-10-28 14:33:57 -07002677 void Reset() {
Ian Rogers30fab402012-01-23 15:43:46 -08002678 p_ = &buf_[0];
2679 totalAllocationUnits_ = 0;
2680 needHeader_ = true;
2681 pieceLenField_ = NULL;
Elliott Hughes6a5bd492011-10-28 14:33:57 -07002682 }
2683
Elliott Hughes1bac54f2012-03-16 12:48:31 -07002684 void HeapChunkCallback(void* start, void* /*end*/, size_t used_bytes) {
Ian Rogers30fab402012-01-23 15:43:46 -08002685 // Note: heap call backs cannot manipulate the heap upon which they are crawling, care is taken
2686 // in the following code not to allocate memory, by ensuring buf_ is of the correct size
2687
2688 const void* user_ptr = used_bytes > 0 ? const_cast<void*>(start) : NULL;
2689 // from malloc.c mem2chunk(mem)
2690 const void* chunk_ptr =
2691 reinterpret_cast<const void*>(reinterpret_cast<const char*>(const_cast<void*>(start)) -
2692 (2 * sizeof(size_t)));
2693 // from malloc.c chunksize
2694 size_t chunk_len = (*reinterpret_cast<size_t* const*>(chunk_ptr))[1] & ~7;
2695
2696
2697 //size_t chunk_len = malloc_usable_size(user_ptr);
Elliott Hughesa2155262011-11-16 16:26:58 -08002698 CHECK_EQ((chunk_len & (ALLOCATION_UNIT_SIZE-1)), 0U);
Elliott Hughes6a5bd492011-10-28 14:33:57 -07002699
Elliott Hughesa2155262011-11-16 16:26:58 -08002700 /* Make sure there's enough room left in the buffer.
2701 * We need to use two bytes for every fractional 256
2702 * allocation units used by the chunk.
2703 */
2704 {
2705 size_t needed = (((chunk_len/ALLOCATION_UNIT_SIZE + 255) / 256) * 2);
Ian Rogers30fab402012-01-23 15:43:46 -08002706 size_t bytesLeft = buf_.size() - (size_t)(p_ - &buf_[0]);
Elliott Hughesa2155262011-11-16 16:26:58 -08002707 if (bytesLeft < needed) {
2708 Flush();
2709 }
Elliott Hughes6a5bd492011-10-28 14:33:57 -07002710
Ian Rogers30fab402012-01-23 15:43:46 -08002711 bytesLeft = buf_.size() - (size_t)(p_ - &buf_[0]);
Elliott Hughesa2155262011-11-16 16:26:58 -08002712 if (bytesLeft < needed) {
Elliott Hughes3d30d9b2011-12-07 17:35:48 -08002713 LOG(WARNING) << "Chunk is too big to transmit (chunk_len=" << chunk_len << ", " << needed << " bytes)";
Elliott Hughesa2155262011-11-16 16:26:58 -08002714 return;
2715 }
2716 }
2717
2718 // OLD-TODO: notice when there's a gap and start a new heap, or at least a new range.
2719 EnsureHeader(chunk_ptr);
2720
2721 // Determine the type of this chunk.
2722 // OLD-TODO: if context.merge, see if this chunk is different from the last chunk.
2723 // If it's the same, we should combine them.
Ian Rogers30fab402012-01-23 15:43:46 -08002724 uint8_t state = ExamineObject(reinterpret_cast<const Object*>(user_ptr), (type_ == CHUNK_TYPE("NHSG")));
Elliott Hughesa2155262011-11-16 16:26:58 -08002725
2726 // Write out the chunk description.
2727 chunk_len /= ALLOCATION_UNIT_SIZE; // convert to allocation units
Ian Rogers30fab402012-01-23 15:43:46 -08002728 totalAllocationUnits_ += chunk_len;
Elliott Hughesa2155262011-11-16 16:26:58 -08002729 while (chunk_len > 256) {
Ian Rogers30fab402012-01-23 15:43:46 -08002730 *p_++ = state | HPSG_PARTIAL;
2731 *p_++ = 255; // length - 1
Elliott Hughesa2155262011-11-16 16:26:58 -08002732 chunk_len -= 256;
2733 }
Ian Rogers30fab402012-01-23 15:43:46 -08002734 *p_++ = state;
2735 *p_++ = chunk_len - 1;
Elliott Hughes6a5bd492011-10-28 14:33:57 -07002736 }
2737
Elliott Hughesa2155262011-11-16 16:26:58 -08002738 uint8_t ExamineObject(const Object* o, bool is_native_heap) {
2739 if (o == NULL) {
2740 return HPSG_STATE(SOLIDITY_FREE, 0);
2741 }
Elliott Hughes6a5bd492011-10-28 14:33:57 -07002742
Elliott Hughesa2155262011-11-16 16:26:58 -08002743 // It's an allocated chunk. Figure out what it is.
Elliott Hughes6a5bd492011-10-28 14:33:57 -07002744
Elliott Hughesa2155262011-11-16 16:26:58 -08002745 // If we're looking at the native heap, we'll just return
2746 // (SOLIDITY_HARD, KIND_NATIVE) for all allocated chunks.
Elliott Hughesb3bd5f02012-03-08 21:05:27 -08002747 if (is_native_heap || !Runtime::Current()->GetHeap()->IsLiveObjectLocked(o)) {
Elliott Hughesa2155262011-11-16 16:26:58 -08002748 return HPSG_STATE(SOLIDITY_HARD, KIND_NATIVE);
2749 }
2750
2751 Class* c = o->GetClass();
2752 if (c == NULL) {
2753 // The object was probably just created but hasn't been initialized yet.
2754 return HPSG_STATE(SOLIDITY_HARD, KIND_OBJECT);
2755 }
2756
Elliott Hughesb3bd5f02012-03-08 21:05:27 -08002757 if (!Runtime::Current()->GetHeap()->IsHeapAddress(c)) {
Elliott Hughes3d30d9b2011-12-07 17:35:48 -08002758 LOG(WARNING) << "Invalid class for managed heap object: " << o << " " << c;
Elliott Hughesa2155262011-11-16 16:26:58 -08002759 return HPSG_STATE(SOLIDITY_HARD, KIND_UNKNOWN);
2760 }
2761
2762 if (c->IsClassClass()) {
2763 return HPSG_STATE(SOLIDITY_HARD, KIND_CLASS_OBJECT);
2764 }
2765
2766 if (c->IsArrayClass()) {
2767 if (o->IsObjectArray()) {
2768 return HPSG_STATE(SOLIDITY_HARD, KIND_ARRAY_4);
2769 }
2770 switch (c->GetComponentSize()) {
2771 case 1: return HPSG_STATE(SOLIDITY_HARD, KIND_ARRAY_1);
2772 case 2: return HPSG_STATE(SOLIDITY_HARD, KIND_ARRAY_2);
2773 case 4: return HPSG_STATE(SOLIDITY_HARD, KIND_ARRAY_4);
2774 case 8: return HPSG_STATE(SOLIDITY_HARD, KIND_ARRAY_8);
2775 }
2776 }
2777
Elliott Hughes6a5bd492011-10-28 14:33:57 -07002778 return HPSG_STATE(SOLIDITY_HARD, KIND_OBJECT);
2779 }
2780
Ian Rogers30fab402012-01-23 15:43:46 -08002781 std::vector<uint8_t> buf_;
2782 uint8_t* p_;
2783 uint8_t* pieceLenField_;
2784 size_t totalAllocationUnits_;
2785 uint32_t type_;
2786 bool merge_;
2787 bool needHeader_;
2788
Elliott Hughesa2155262011-11-16 16:26:58 -08002789 DISALLOW_COPY_AND_ASSIGN(HeapChunkContext);
2790};
Elliott Hughes6a5bd492011-10-28 14:33:57 -07002791
2792void Dbg::DdmSendHeapSegments(bool native) {
2793 Dbg::HpsgWhen when;
2794 Dbg::HpsgWhat what;
2795 if (!native) {
2796 when = gDdmHpsgWhen;
2797 what = gDdmHpsgWhat;
2798 } else {
2799 when = gDdmNhsgWhen;
2800 what = gDdmNhsgWhat;
2801 }
2802 if (when == HPSG_WHEN_NEVER) {
2803 return;
2804 }
2805
2806 // Figure out what kind of chunks we'll be sending.
2807 CHECK(what == HPSG_WHAT_MERGED_OBJECTS || what == HPSG_WHAT_DISTINCT_OBJECTS) << static_cast<int>(what);
2808
2809 // First, send a heap start chunk.
2810 uint8_t heap_id[4];
2811 JDWP::Set4BE(&heap_id[0], 1); // Heap id (bogus; we only have one heap).
2812 Dbg::DdmSendChunk(native ? CHUNK_TYPE("NHST") : CHUNK_TYPE("HPST"), sizeof(heap_id), heap_id);
2813
2814 // Send a series of heap segment chunks.
Elliott Hughesa2155262011-11-16 16:26:58 -08002815 HeapChunkContext context((what == HPSG_WHAT_MERGED_OBJECTS), native);
2816 if (native) {
Ian Rogers30fab402012-01-23 15:43:46 -08002817 // TODO: enable when bionic has moved to dlmalloc 2.8.5
2818 // dlmalloc_inspect_all(HeapChunkContext::HeapChunkCallback, &context);
2819 UNIMPLEMENTED(WARNING) << "Native heap send heap segments";
Elliott Hughesa2155262011-11-16 16:26:58 -08002820 } else {
Elliott Hughesb3bd5f02012-03-08 21:05:27 -08002821 Heap* heap = Runtime::Current()->GetHeap();
2822 heap->GetAllocSpace()->Walk(HeapChunkContext::HeapChunkCallback, &context);
Elliott Hughesa2155262011-11-16 16:26:58 -08002823 }
Elliott Hughes6a5bd492011-10-28 14:33:57 -07002824
2825 // Finally, send a heap end chunk.
2826 Dbg::DdmSendChunk(native ? CHUNK_TYPE("NHEN") : CHUNK_TYPE("HPEN"), sizeof(heap_id), heap_id);
Elliott Hughes767a1472011-10-26 18:49:02 -07002827}
2828
Elliott Hughes545a0642011-11-08 19:10:03 -08002829void Dbg::SetAllocTrackingEnabled(bool enabled) {
2830 MutexLock mu(gAllocTrackerLock);
2831 if (enabled) {
2832 if (recent_allocation_records_ == NULL) {
2833 LOG(INFO) << "Enabling alloc tracker (" << kNumAllocRecords << " entries, "
2834 << kMaxAllocRecordStackDepth << " frames --> "
2835 << (sizeof(AllocRecord) * kNumAllocRecords) << " bytes)";
2836 gAllocRecordHead = gAllocRecordCount = 0;
2837 recent_allocation_records_ = new AllocRecord[kNumAllocRecords];
2838 CHECK(recent_allocation_records_ != NULL);
2839 }
2840 } else {
2841 delete[] recent_allocation_records_;
2842 recent_allocation_records_ = NULL;
2843 }
2844}
2845
2846struct AllocRecordStackVisitor : public Thread::StackVisitor {
Elliott Hughesba8eee12012-01-24 20:25:24 -08002847 explicit AllocRecordStackVisitor(AllocRecord* record) : record(record), depth(0) {
Elliott Hughes545a0642011-11-08 19:10:03 -08002848 }
2849
Elliott Hughes530fa002012-03-12 11:44:49 -07002850 bool VisitFrame(const Frame& f, uintptr_t pc) {
Elliott Hughes545a0642011-11-08 19:10:03 -08002851 if (depth >= kMaxAllocRecordStackDepth) {
Elliott Hughes530fa002012-03-12 11:44:49 -07002852 return false;
Elliott Hughes545a0642011-11-08 19:10:03 -08002853 }
Elliott Hughes530fa002012-03-12 11:44:49 -07002854 if (f.HasMethod()) {
2855 record->stack[depth].method = f.GetMethod();
2856 record->stack[depth].raw_pc = pc;
2857 ++depth;
Elliott Hughes545a0642011-11-08 19:10:03 -08002858 }
Elliott Hughes530fa002012-03-12 11:44:49 -07002859 return true;
Elliott Hughes545a0642011-11-08 19:10:03 -08002860 }
2861
2862 ~AllocRecordStackVisitor() {
2863 // Clear out any unused stack trace elements.
2864 for (; depth < kMaxAllocRecordStackDepth; ++depth) {
2865 record->stack[depth].method = NULL;
2866 record->stack[depth].raw_pc = 0;
2867 }
2868 }
2869
2870 AllocRecord* record;
2871 size_t depth;
2872};
2873
2874void Dbg::RecordAllocation(Class* type, size_t byte_count) {
2875 Thread* self = Thread::Current();
2876 CHECK(self != NULL);
2877
2878 MutexLock mu(gAllocTrackerLock);
2879 if (recent_allocation_records_ == NULL) {
2880 return;
2881 }
2882
2883 // Advance and clip.
2884 if (++gAllocRecordHead == kNumAllocRecords) {
2885 gAllocRecordHead = 0;
2886 }
2887
2888 // Fill in the basics.
2889 AllocRecord* record = &recent_allocation_records_[gAllocRecordHead];
2890 record->type = type;
2891 record->byte_count = byte_count;
2892 record->thin_lock_id = self->GetThinLockId();
2893
2894 // Fill in the stack trace.
2895 AllocRecordStackVisitor visitor(record);
2896 self->WalkStack(&visitor);
2897
2898 if (gAllocRecordCount < kNumAllocRecords) {
2899 ++gAllocRecordCount;
2900 }
2901}
2902
2903/*
2904 * Return the index of the head element.
2905 *
2906 * We point at the most-recently-written record, so if allocRecordCount is 1
2907 * we want to use the current element. Take "head+1" and subtract count
2908 * from it.
2909 *
2910 * We need to handle underflow in our circular buffer, so we add
2911 * kNumAllocRecords and then mask it back down.
2912 */
2913inline static int headIndex() {
2914 return (gAllocRecordHead+1 + kNumAllocRecords - gAllocRecordCount) & (kNumAllocRecords-1);
2915}
2916
2917void Dbg::DumpRecentAllocations() {
2918 MutexLock mu(gAllocTrackerLock);
2919 if (recent_allocation_records_ == NULL) {
2920 LOG(INFO) << "Not recording tracked allocations";
2921 return;
2922 }
2923
2924 // "i" is the head of the list. We want to start at the end of the
2925 // list and move forward to the tail.
2926 size_t i = headIndex();
2927 size_t count = gAllocRecordCount;
2928
2929 LOG(INFO) << "Tracked allocations, (head=" << gAllocRecordHead << " count=" << count << ")";
2930 while (count--) {
2931 AllocRecord* record = &recent_allocation_records_[i];
2932
Elliott Hughesaa6e1cd2012-01-18 19:26:06 -08002933 LOG(INFO) << StringPrintf(" T=%-2d %6zd ", record->thin_lock_id, record->byte_count)
Elliott Hughes545a0642011-11-08 19:10:03 -08002934 << PrettyClass(record->type);
2935
2936 for (size_t stack_frame = 0; stack_frame < kMaxAllocRecordStackDepth; ++stack_frame) {
2937 const Method* m = record->stack[stack_frame].method;
2938 if (m == NULL) {
2939 break;
2940 }
2941 LOG(INFO) << " " << PrettyMethod(m) << " line " << record->stack[stack_frame].LineNumber();
2942 }
2943
2944 // pause periodically to help logcat catch up
2945 if ((count % 5) == 0) {
2946 usleep(40000);
2947 }
2948
2949 i = (i + 1) & (kNumAllocRecords-1);
2950 }
2951}
2952
2953class StringTable {
2954 public:
2955 StringTable() {
2956 }
2957
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002958 void Add(const char* s) {
Elliott Hughes545a0642011-11-08 19:10:03 -08002959 table_.insert(s);
2960 }
2961
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002962 size_t IndexOf(const char* s) {
Elliott Hughes545a0642011-11-08 19:10:03 -08002963 return std::distance(table_.begin(), table_.find(s));
2964 }
2965
2966 size_t Size() {
2967 return table_.size();
2968 }
2969
2970 void WriteTo(std::vector<uint8_t>& bytes) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002971 typedef std::set<const char*>::const_iterator It; // TODO: C++0x auto
Elliott Hughes545a0642011-11-08 19:10:03 -08002972 for (It it = table_.begin(); it != table_.end(); ++it) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002973 const char* s = *it;
2974 size_t s_len = CountModifiedUtf8Chars(s);
2975 UniquePtr<uint16_t> s_utf16(new uint16_t[s_len]);
2976 ConvertModifiedUtf8ToUtf16(s_utf16.get(), s);
2977 JDWP::AppendUtf16BE(bytes, s_utf16.get(), s_len);
Elliott Hughes545a0642011-11-08 19:10:03 -08002978 }
2979 }
2980
2981 private:
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002982 std::set<const char*> table_;
Elliott Hughes545a0642011-11-08 19:10:03 -08002983 DISALLOW_COPY_AND_ASSIGN(StringTable);
2984};
2985
2986/*
2987 * The data we send to DDMS contains everything we have recorded.
2988 *
2989 * Message header (all values big-endian):
2990 * (1b) message header len (to allow future expansion); includes itself
2991 * (1b) entry header len
2992 * (1b) stack frame len
2993 * (2b) number of entries
2994 * (4b) offset to string table from start of message
2995 * (2b) number of class name strings
2996 * (2b) number of method name strings
2997 * (2b) number of source file name strings
2998 * For each entry:
2999 * (4b) total allocation size
3000 * (2b) threadId
3001 * (2b) allocated object's class name index
3002 * (1b) stack depth
3003 * For each stack frame:
3004 * (2b) method's class name
3005 * (2b) method name
3006 * (2b) method source file
3007 * (2b) line number, clipped to 32767; -2 if native; -1 if no source
3008 * (xb) class name strings
3009 * (xb) method name strings
3010 * (xb) source file strings
3011 *
3012 * As with other DDM traffic, strings are sent as a 4-byte length
3013 * followed by UTF-16 data.
3014 *
3015 * We send up 16-bit unsigned indexes into string tables. In theory there
3016 * can be (kMaxAllocRecordStackDepth * kNumAllocRecords) unique strings in
3017 * each table, but in practice there should be far fewer.
3018 *
3019 * The chief reason for using a string table here is to keep the size of
3020 * the DDMS message to a minimum. This is partly to make the protocol
3021 * efficient, but also because we have to form the whole thing up all at
3022 * once in a memory buffer.
3023 *
3024 * We use separate string tables for class names, method names, and source
3025 * files to keep the indexes small. There will generally be no overlap
3026 * between the contents of these tables.
3027 */
3028jbyteArray Dbg::GetRecentAllocations() {
3029 if (false) {
3030 DumpRecentAllocations();
3031 }
3032
3033 MutexLock mu(gAllocTrackerLock);
3034
3035 /*
3036 * Part 1: generate string tables.
3037 */
3038 StringTable class_names;
3039 StringTable method_names;
3040 StringTable filenames;
3041
3042 int count = gAllocRecordCount;
3043 int idx = headIndex();
3044 while (count--) {
3045 AllocRecord* record = &recent_allocation_records_[idx];
3046
Elliott Hughes91250e02011-12-13 22:30:35 -08003047 class_names.Add(ClassHelper(record->type).GetDescriptor());
Elliott Hughes545a0642011-11-08 19:10:03 -08003048
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08003049 MethodHelper mh;
Elliott Hughes545a0642011-11-08 19:10:03 -08003050 for (size_t i = 0; i < kMaxAllocRecordStackDepth; i++) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08003051 Method* m = record->stack[i].method;
Elliott Hughes545a0642011-11-08 19:10:03 -08003052 if (m != NULL) {
Ian Rogersba377812012-05-28 21:16:29 -07003053 mh.ChangeMethod(m);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08003054 class_names.Add(mh.GetDeclaringClassDescriptor());
3055 method_names.Add(mh.GetName());
3056 filenames.Add(mh.GetDeclaringClassSourceFile());
Elliott Hughes545a0642011-11-08 19:10:03 -08003057 }
3058 }
3059
3060 idx = (idx + 1) & (kNumAllocRecords-1);
3061 }
3062
3063 LOG(INFO) << "allocation records: " << gAllocRecordCount;
3064
3065 /*
3066 * Part 2: allocate a buffer and generate the output.
3067 */
3068 std::vector<uint8_t> bytes;
3069
3070 // (1b) message header len (to allow future expansion); includes itself
3071 // (1b) entry header len
3072 // (1b) stack frame len
3073 const int kMessageHeaderLen = 15;
3074 const int kEntryHeaderLen = 9;
3075 const int kStackFrameLen = 8;
3076 JDWP::Append1BE(bytes, kMessageHeaderLen);
3077 JDWP::Append1BE(bytes, kEntryHeaderLen);
3078 JDWP::Append1BE(bytes, kStackFrameLen);
3079
3080 // (2b) number of entries
3081 // (4b) offset to string table from start of message
3082 // (2b) number of class name strings
3083 // (2b) number of method name strings
3084 // (2b) number of source file name strings
3085 JDWP::Append2BE(bytes, gAllocRecordCount);
3086 size_t string_table_offset = bytes.size();
3087 JDWP::Append4BE(bytes, 0); // We'll patch this later...
3088 JDWP::Append2BE(bytes, class_names.Size());
3089 JDWP::Append2BE(bytes, method_names.Size());
3090 JDWP::Append2BE(bytes, filenames.Size());
3091
3092 count = gAllocRecordCount;
3093 idx = headIndex();
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08003094 ClassHelper kh;
Elliott Hughes545a0642011-11-08 19:10:03 -08003095 while (count--) {
3096 // For each entry:
3097 // (4b) total allocation size
3098 // (2b) thread id
3099 // (2b) allocated object's class name index
3100 // (1b) stack depth
3101 AllocRecord* record = &recent_allocation_records_[idx];
3102 size_t stack_depth = record->GetDepth();
3103 JDWP::Append4BE(bytes, record->byte_count);
3104 JDWP::Append2BE(bytes, record->thin_lock_id);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08003105 kh.ChangeClass(record->type);
Elliott Hughes91250e02011-12-13 22:30:35 -08003106 JDWP::Append2BE(bytes, class_names.IndexOf(kh.GetDescriptor()));
Elliott Hughes545a0642011-11-08 19:10:03 -08003107 JDWP::Append1BE(bytes, stack_depth);
3108
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08003109 MethodHelper mh;
Elliott Hughes545a0642011-11-08 19:10:03 -08003110 for (size_t stack_frame = 0; stack_frame < stack_depth; ++stack_frame) {
3111 // For each stack frame:
3112 // (2b) method's class name
3113 // (2b) method name
3114 // (2b) method source file
3115 // (2b) line number, clipped to 32767; -2 if native; -1 if no source
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08003116 mh.ChangeMethod(record->stack[stack_frame].method);
3117 JDWP::Append2BE(bytes, class_names.IndexOf(mh.GetDeclaringClassDescriptor()));
3118 JDWP::Append2BE(bytes, method_names.IndexOf(mh.GetName()));
3119 JDWP::Append2BE(bytes, filenames.IndexOf(mh.GetDeclaringClassSourceFile()));
Elliott Hughes545a0642011-11-08 19:10:03 -08003120 JDWP::Append2BE(bytes, record->stack[stack_frame].LineNumber());
3121 }
3122
3123 idx = (idx + 1) & (kNumAllocRecords-1);
3124 }
3125
3126 // (xb) class name strings
3127 // (xb) method name strings
3128 // (xb) source file strings
3129 JDWP::Set4BE(&bytes[string_table_offset], bytes.size());
3130 class_names.WriteTo(bytes);
3131 method_names.WriteTo(bytes);
3132 filenames.WriteTo(bytes);
3133
3134 JNIEnv* env = Thread::Current()->GetJniEnv();
3135 jbyteArray result = env->NewByteArray(bytes.size());
3136 if (result != NULL) {
3137 env->SetByteArrayRegion(result, 0, bytes.size(), reinterpret_cast<const jbyte*>(&bytes[0]));
3138 }
3139 return result;
3140}
3141
Elliott Hughes872d4ec2011-10-21 17:07:15 -07003142} // namespace art