blob: cd52f8260a06619ac6cb0b069a93f88109373493 [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"
Ian Rogers365c1022012-06-22 15:05:28 -070031#include "scoped_jni_thread_state.h"
Elliott Hughesa0e18062012-04-13 15:59:59 -070032#include "scoped_thread_list_lock.h"
Elliott Hughes6a5bd492011-10-28 14:33:57 -070033#include "ScopedLocalRef.h"
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -070034#include "ScopedPrimitiveArray.h"
Ian Rogers30fab402012-01-23 15:43:46 -080035#include "space.h"
Elliott Hughes47fce012011-10-25 18:37:19 -070036#include "stack_indirect_reference_table.h"
Elliott Hughes475fc232011-10-25 15:00:35 -070037#include "thread_list.h"
Elliott Hugheseac76672012-05-24 21:56:51 -070038#include "well_known_classes.h"
Elliott Hughes475fc232011-10-25 15:00:35 -070039
Elliott Hughes872d4ec2011-10-21 17:07:15 -070040namespace art {
41
Elliott Hughes545a0642011-11-08 19:10:03 -080042static const size_t kMaxAllocRecordStackDepth = 16; // Max 255.
43static const size_t kNumAllocRecords = 512; // Must be power of 2.
44
Elliott Hughes436e3722012-02-17 20:01:47 -080045static const uintptr_t kInvalidId = 1;
46static const Object* kInvalidObject = reinterpret_cast<Object*>(kInvalidId);
47
Elliott Hughes475fc232011-10-25 15:00:35 -070048class ObjectRegistry {
49 public:
50 ObjectRegistry() : lock_("ObjectRegistry lock") {
51 }
52
53 JDWP::ObjectId Add(Object* o) {
54 if (o == NULL) {
55 return 0;
56 }
57 JDWP::ObjectId id = static_cast<JDWP::ObjectId>(reinterpret_cast<uintptr_t>(o));
58 MutexLock mu(lock_);
Elliott Hughesa0e18062012-04-13 15:59:59 -070059 map_.Overwrite(id, o);
Elliott Hughes475fc232011-10-25 15:00:35 -070060 return id;
61 }
62
Elliott Hughes234ab152011-10-26 14:02:26 -070063 void Clear() {
64 MutexLock mu(lock_);
65 LOG(DEBUG) << "Debugger has detached; object registry had " << map_.size() << " entries";
66 map_.clear();
67 }
68
Elliott Hughes475fc232011-10-25 15:00:35 -070069 bool Contains(JDWP::ObjectId id) {
70 MutexLock mu(lock_);
71 return map_.find(id) != map_.end();
72 }
73
Elliott Hughesa2155262011-11-16 16:26:58 -080074 template<typename T> T Get(JDWP::ObjectId id) {
Elliott Hughes436e3722012-02-17 20:01:47 -080075 if (id == 0) {
76 return NULL;
77 }
78
Elliott Hughesa2155262011-11-16 16:26:58 -080079 MutexLock mu(lock_);
Elliott Hughesa0e18062012-04-13 15:59:59 -070080 typedef SafeMap<JDWP::ObjectId, Object*>::iterator It; // C++0x auto
Elliott Hughesa2155262011-11-16 16:26:58 -080081 It it = map_.find(id);
Elliott Hughes436e3722012-02-17 20:01:47 -080082 return (it != map_.end()) ? reinterpret_cast<T>(it->second) : reinterpret_cast<T>(kInvalidId);
Elliott Hughesa2155262011-11-16 16:26:58 -080083 }
84
Elliott Hughesbfe487b2011-10-26 15:48:55 -070085 void VisitRoots(Heap::RootVisitor* visitor, void* arg) {
86 MutexLock mu(lock_);
Elliott Hughesa0e18062012-04-13 15:59:59 -070087 typedef SafeMap<JDWP::ObjectId, Object*>::iterator It; // C++0x auto
Elliott Hughesbfe487b2011-10-26 15:48:55 -070088 for (It it = map_.begin(); it != map_.end(); ++it) {
89 visitor(it->second, arg);
90 }
91 }
92
Elliott Hughes475fc232011-10-25 15:00:35 -070093 private:
94 Mutex lock_;
Elliott Hughesa0e18062012-04-13 15:59:59 -070095 SafeMap<JDWP::ObjectId, Object*> map_;
Elliott Hughes475fc232011-10-25 15:00:35 -070096};
97
Elliott Hughes545a0642011-11-08 19:10:03 -080098struct AllocRecordStackTraceElement {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -080099 Method* method;
Ian Rogers0399dde2012-06-06 17:09:28 -0700100 uint32_t dex_pc;
Elliott Hughes545a0642011-11-08 19:10:03 -0800101
102 int32_t LineNumber() const {
Ian Rogers0399dde2012-06-06 17:09:28 -0700103 return MethodHelper(method).GetLineNumFromDexPC(dex_pc);
Elliott Hughes545a0642011-11-08 19:10:03 -0800104 }
105};
106
107struct AllocRecord {
108 Class* type;
109 size_t byte_count;
110 uint16_t thin_lock_id;
111 AllocRecordStackTraceElement stack[kMaxAllocRecordStackDepth]; // Unused entries have NULL method.
112
113 size_t GetDepth() {
114 size_t depth = 0;
115 while (depth < kMaxAllocRecordStackDepth && stack[depth].method != NULL) {
116 ++depth;
117 }
118 return depth;
119 }
120};
121
Elliott Hughes86964332012-02-15 19:37:42 -0800122struct Breakpoint {
123 Method* method;
Elliott Hughesa656a0f2012-02-21 18:03:44 -0800124 uint32_t dex_pc;
125 Breakpoint(Method* method, uint32_t dex_pc) : method(method), dex_pc(dex_pc) {}
Elliott Hughes86964332012-02-15 19:37:42 -0800126};
127
128static std::ostream& operator<<(std::ostream& os, const Breakpoint& rhs) {
Elliott Hughes229feb72012-02-23 13:33:29 -0800129 os << StringPrintf("Breakpoint[%s @%#x]", PrettyMethod(rhs.method).c_str(), rhs.dex_pc);
Elliott Hughes86964332012-02-15 19:37:42 -0800130 return os;
131}
132
133struct SingleStepControl {
134 // Are we single-stepping right now?
135 bool is_active;
136 Thread* thread;
137
138 JDWP::JdwpStepSize step_size;
139 JDWP::JdwpStepDepth step_depth;
140
141 const Method* method;
Elliott Hughes2435a572012-02-17 16:07:41 -0800142 int32_t line_number; // Or -1 for native methods.
143 std::set<uint32_t> dex_pcs;
Elliott Hughes86964332012-02-15 19:37:42 -0800144 int stack_depth;
145};
146
Elliott Hughes4ffd3132011-10-24 12:06:42 -0700147// JDWP is allowed unless the Zygote forbids it.
148static bool gJdwpAllowed = true;
149
Elliott Hughesc0f09332012-03-26 13:27:06 -0700150// Was there a -Xrunjdwp or -agentlib:jdwp= argument on the command line?
Elliott Hughes3bb81562011-10-21 18:52:59 -0700151static bool gJdwpConfigured = false;
152
Elliott Hughesc0f09332012-03-26 13:27:06 -0700153// Broken-down JDWP options. (Only valid if IsJdwpConfigured() is true.)
Elliott Hughes376a7a02011-10-24 18:35:55 -0700154static JDWP::JdwpOptions gJdwpOptions;
Elliott Hughes3bb81562011-10-21 18:52:59 -0700155
156// Runtime JDWP state.
157static JDWP::JdwpState* gJdwpState = NULL;
158static bool gDebuggerConnected; // debugger or DDMS is connected.
159static bool gDebuggerActive; // debugger is making requests.
Elliott Hughes86964332012-02-15 19:37:42 -0800160static bool gDisposed; // debugger called VirtualMachine.Dispose, so we should drop the connection.
Elliott Hughes3bb81562011-10-21 18:52:59 -0700161
Elliott Hughes47fce012011-10-25 18:37:19 -0700162static bool gDdmThreadNotification = false;
163
Elliott Hughes767a1472011-10-26 18:49:02 -0700164// DDMS GC-related settings.
165static Dbg::HpifWhen gDdmHpifWhen = Dbg::HPIF_WHEN_NEVER;
166static Dbg::HpsgWhen gDdmHpsgWhen = Dbg::HPSG_WHEN_NEVER;
167static Dbg::HpsgWhat gDdmHpsgWhat;
168static Dbg::HpsgWhen gDdmNhsgWhen = Dbg::HPSG_WHEN_NEVER;
169static Dbg::HpsgWhat gDdmNhsgWhat;
170
Elliott Hughes475fc232011-10-25 15:00:35 -0700171static ObjectRegistry* gRegistry = NULL;
172
Elliott Hughes545a0642011-11-08 19:10:03 -0800173// Recent allocation tracking.
174static Mutex gAllocTrackerLock("AllocTracker lock");
Elliott Hughesf8349362012-06-18 15:00:06 -0700175AllocRecord* Dbg::recent_allocation_records_ PT_GUARDED_BY(gAllocTrackerLock) = NULL; // TODO: CircularBuffer<AllocRecord>
176static size_t gAllocRecordHead GUARDED_BY(gAllocTrackerLock) = 0;
177static size_t gAllocRecordCount GUARDED_BY(gAllocTrackerLock) = 0;
Elliott Hughes545a0642011-11-08 19:10:03 -0800178
Elliott Hughes86964332012-02-15 19:37:42 -0800179// Breakpoints and single-stepping.
180static Mutex gBreakpointsLock("breakpoints lock");
Elliott Hughesf8349362012-06-18 15:00:06 -0700181static std::vector<Breakpoint> gBreakpoints GUARDED_BY(gBreakpointsLock);
182static SingleStepControl gSingleStepControl GUARDED_BY(gBreakpointsLock);
Elliott Hughes86964332012-02-15 19:37:42 -0800183
184static bool IsBreakpoint(Method* m, uint32_t dex_pc) {
185 MutexLock mu(gBreakpointsLock);
186 for (size_t i = 0; i < gBreakpoints.size(); ++i) {
Elliott Hughesa656a0f2012-02-21 18:03:44 -0800187 if (gBreakpoints[i].method == m && gBreakpoints[i].dex_pc == dex_pc) {
Elliott Hughes86964332012-02-15 19:37:42 -0800188 VLOG(jdwp) << "Hit breakpoint #" << i << ": " << gBreakpoints[i];
189 return true;
190 }
191 }
192 return false;
193}
194
Elliott Hughes436e3722012-02-17 20:01:47 -0800195static Array* DecodeArray(JDWP::RefTypeId id, JDWP::JdwpError& status) {
196 Object* o = gRegistry->Get<Object*>(id);
197 if (o == NULL || o == kInvalidObject) {
198 status = JDWP::ERR_INVALID_OBJECT;
199 return NULL;
200 }
201 if (!o->IsArrayInstance()) {
202 status = JDWP::ERR_INVALID_ARRAY;
203 return NULL;
204 }
205 status = JDWP::ERR_NONE;
206 return o->AsArray();
207}
208
209static Class* DecodeClass(JDWP::RefTypeId id, JDWP::JdwpError& status) {
210 Object* o = gRegistry->Get<Object*>(id);
211 if (o == NULL || o == kInvalidObject) {
212 status = JDWP::ERR_INVALID_OBJECT;
213 return NULL;
214 }
215 if (!o->IsClass()) {
216 status = JDWP::ERR_INVALID_CLASS;
217 return NULL;
218 }
219 status = JDWP::ERR_NONE;
220 return o->AsClass();
221}
222
223static Thread* DecodeThread(JDWP::ObjectId threadId) {
Ian Rogers365c1022012-06-22 15:05:28 -0700224 ScopedJniThreadState ts(Thread::Current());
Elliott Hughes436e3722012-02-17 20:01:47 -0800225 Object* thread_peer = gRegistry->Get<Object*>(threadId);
226 if (thread_peer == NULL || thread_peer == kInvalidObject) {
227 return NULL;
228 }
Ian Rogers365c1022012-06-22 15:05:28 -0700229 return Thread::FromManagedThread(ts, thread_peer);
Elliott Hughes436e3722012-02-17 20:01:47 -0800230}
231
Elliott Hughes24437992011-11-30 14:49:33 -0800232static JDWP::JdwpTag BasicTagFromDescriptor(const char* descriptor) {
233 // JDWP deliberately uses the descriptor characters' ASCII values for its enum.
234 // Note that by "basic" we mean that we don't get more specific than JT_OBJECT.
235 return static_cast<JDWP::JdwpTag>(descriptor[0]);
236}
237
238static JDWP::JdwpTag TagFromClass(Class* c) {
Elliott Hughes86b00102011-12-05 17:54:26 -0800239 CHECK(c != NULL);
Elliott Hughes24437992011-11-30 14:49:33 -0800240 if (c->IsArrayClass()) {
241 return JDWP::JT_ARRAY;
242 }
243
Elliott Hughes3d30d9b2011-12-07 17:35:48 -0800244 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
Elliott Hughes24437992011-11-30 14:49:33 -0800245 if (c->IsStringClass()) {
246 return JDWP::JT_STRING;
247 } else if (c->IsClassClass()) {
248 return JDWP::JT_CLASS_OBJECT;
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -0800249 } else if (class_linker->FindSystemClass("Ljava/lang/Thread;")->IsAssignableFrom(c)) {
Elliott Hughes24437992011-11-30 14:49:33 -0800250 return JDWP::JT_THREAD;
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -0800251 } else if (class_linker->FindSystemClass("Ljava/lang/ThreadGroup;")->IsAssignableFrom(c)) {
Elliott Hughes24437992011-11-30 14:49:33 -0800252 return JDWP::JT_THREAD_GROUP;
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -0800253 } else if (class_linker->FindSystemClass("Ljava/lang/ClassLoader;")->IsAssignableFrom(c)) {
Elliott Hughes24437992011-11-30 14:49:33 -0800254 return JDWP::JT_CLASS_LOADER;
Elliott Hughes24437992011-11-30 14:49:33 -0800255 } else {
256 return JDWP::JT_OBJECT;
257 }
258}
259
260/*
261 * Objects declared to hold Object might actually hold a more specific
262 * type. The debugger may take a special interest in these (e.g. it
263 * wants to display the contents of Strings), so we want to return an
264 * appropriate tag.
265 *
266 * Null objects are tagged JT_OBJECT.
267 */
268static JDWP::JdwpTag TagFromObject(const Object* o) {
269 return (o == NULL) ? JDWP::JT_OBJECT : TagFromClass(o->GetClass());
270}
271
272static bool IsPrimitiveTag(JDWP::JdwpTag tag) {
273 switch (tag) {
274 case JDWP::JT_BOOLEAN:
275 case JDWP::JT_BYTE:
276 case JDWP::JT_CHAR:
277 case JDWP::JT_FLOAT:
278 case JDWP::JT_DOUBLE:
279 case JDWP::JT_INT:
280 case JDWP::JT_LONG:
281 case JDWP::JT_SHORT:
282 case JDWP::JT_VOID:
283 return true;
284 default:
285 return false;
286 }
287}
288
Elliott Hughes3bb81562011-10-21 18:52:59 -0700289/*
290 * Handle one of the JDWP name/value pairs.
291 *
292 * JDWP options are:
293 * help: if specified, show help message and bail
294 * transport: may be dt_socket or dt_shmem
295 * address: for dt_socket, "host:port", or just "port" when listening
296 * server: if "y", wait for debugger to attach; if "n", attach to debugger
297 * timeout: how long to wait for debugger to connect / listen
298 *
299 * Useful with server=n (these aren't supported yet):
300 * onthrow=<exception-name>: connect to debugger when exception thrown
301 * onuncaught=y|n: connect to debugger when uncaught exception thrown
302 * launch=<command-line>: launch the debugger itself
303 *
304 * The "transport" option is required, as is "address" if server=n.
305 */
306static bool ParseJdwpOption(const std::string& name, const std::string& value) {
307 if (name == "transport") {
308 if (value == "dt_socket") {
Elliott Hughes376a7a02011-10-24 18:35:55 -0700309 gJdwpOptions.transport = JDWP::kJdwpTransportSocket;
Elliott Hughes3bb81562011-10-21 18:52:59 -0700310 } else if (value == "dt_android_adb") {
Elliott Hughes376a7a02011-10-24 18:35:55 -0700311 gJdwpOptions.transport = JDWP::kJdwpTransportAndroidAdb;
Elliott Hughes3bb81562011-10-21 18:52:59 -0700312 } else {
313 LOG(ERROR) << "JDWP transport not supported: " << value;
314 return false;
315 }
316 } else if (name == "server") {
317 if (value == "n") {
Elliott Hughes376a7a02011-10-24 18:35:55 -0700318 gJdwpOptions.server = false;
Elliott Hughes3bb81562011-10-21 18:52:59 -0700319 } else if (value == "y") {
Elliott Hughes376a7a02011-10-24 18:35:55 -0700320 gJdwpOptions.server = true;
Elliott Hughes3bb81562011-10-21 18:52:59 -0700321 } else {
322 LOG(ERROR) << "JDWP option 'server' must be 'y' or 'n'";
323 return false;
324 }
325 } else if (name == "suspend") {
326 if (value == "n") {
Elliott Hughes376a7a02011-10-24 18:35:55 -0700327 gJdwpOptions.suspend = false;
Elliott Hughes3bb81562011-10-21 18:52:59 -0700328 } else if (value == "y") {
Elliott Hughes376a7a02011-10-24 18:35:55 -0700329 gJdwpOptions.suspend = true;
Elliott Hughes3bb81562011-10-21 18:52:59 -0700330 } else {
331 LOG(ERROR) << "JDWP option 'suspend' must be 'y' or 'n'";
332 return false;
333 }
334 } else if (name == "address") {
335 /* this is either <port> or <host>:<port> */
336 std::string port_string;
Elliott Hughes376a7a02011-10-24 18:35:55 -0700337 gJdwpOptions.host.clear();
Elliott Hughes3bb81562011-10-21 18:52:59 -0700338 std::string::size_type colon = value.find(':');
339 if (colon != std::string::npos) {
Elliott Hughes376a7a02011-10-24 18:35:55 -0700340 gJdwpOptions.host = value.substr(0, colon);
Elliott Hughes3bb81562011-10-21 18:52:59 -0700341 port_string = value.substr(colon + 1);
342 } else {
343 port_string = value;
344 }
345 if (port_string.empty()) {
346 LOG(ERROR) << "JDWP address missing port: " << value;
347 return false;
348 }
349 char* end;
Elliott Hughesba8eee12012-01-24 20:25:24 -0800350 uint64_t port = strtoul(port_string.c_str(), &end, 10);
351 if (*end != '\0' || port > 0xffff) {
Elliott Hughes3bb81562011-10-21 18:52:59 -0700352 LOG(ERROR) << "JDWP address has junk in port field: " << value;
353 return false;
354 }
Elliott Hughes376a7a02011-10-24 18:35:55 -0700355 gJdwpOptions.port = port;
Elliott Hughes3bb81562011-10-21 18:52:59 -0700356 } else if (name == "launch" || name == "onthrow" || name == "oncaught" || name == "timeout") {
357 /* valid but unsupported */
358 LOG(INFO) << "Ignoring JDWP option '" << name << "'='" << value << "'";
359 } else {
360 LOG(INFO) << "Ignoring unrecognized JDWP option '" << name << "'='" << value << "'";
361 }
362
363 return true;
364}
365
366/*
367 * Parse the latter half of a -Xrunjdwp/-agentlib:jdwp= string, e.g.:
368 * "transport=dt_socket,address=8000,server=y,suspend=n"
369 */
370bool Dbg::ParseJdwpOptions(const std::string& options) {
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -0800371 VLOG(jdwp) << "ParseJdwpOptions: " << options;
Elliott Hughes47fce012011-10-25 18:37:19 -0700372
Elliott Hughes3bb81562011-10-21 18:52:59 -0700373 std::vector<std::string> pairs;
374 Split(options, ',', pairs);
375
376 for (size_t i = 0; i < pairs.size(); ++i) {
377 std::string::size_type equals = pairs[i].find('=');
378 if (equals == std::string::npos) {
379 LOG(ERROR) << "Can't parse JDWP option '" << pairs[i] << "' in '" << options << "'";
380 return false;
381 }
382 ParseJdwpOption(pairs[i].substr(0, equals), pairs[i].substr(equals + 1));
383 }
384
Elliott Hughes376a7a02011-10-24 18:35:55 -0700385 if (gJdwpOptions.transport == JDWP::kJdwpTransportUnknown) {
Elliott Hughes3bb81562011-10-21 18:52:59 -0700386 LOG(ERROR) << "Must specify JDWP transport: " << options;
387 }
Elliott Hughes376a7a02011-10-24 18:35:55 -0700388 if (!gJdwpOptions.server && (gJdwpOptions.host.empty() || gJdwpOptions.port == 0)) {
Elliott Hughes3bb81562011-10-21 18:52:59 -0700389 LOG(ERROR) << "Must specify JDWP host and port when server=n: " << options;
390 return false;
391 }
392
393 gJdwpConfigured = true;
394 return true;
395}
396
Elliott Hughesd1cc8362011-10-24 16:58:50 -0700397void Dbg::StartJdwp() {
Elliott Hughesc0f09332012-03-26 13:27:06 -0700398 if (!gJdwpAllowed || !IsJdwpConfigured()) {
Elliott Hughes376a7a02011-10-24 18:35:55 -0700399 // No JDWP for you!
400 return;
401 }
402
Elliott Hughes475fc232011-10-25 15:00:35 -0700403 CHECK(gRegistry == NULL);
404 gRegistry = new ObjectRegistry;
405
Elliott Hughesd1cc8362011-10-24 16:58:50 -0700406 // Init JDWP if the debugger is enabled. This may connect out to a
407 // debugger, passively listen for a debugger, or block waiting for a
408 // debugger.
Elliott Hughes376a7a02011-10-24 18:35:55 -0700409 gJdwpState = JDWP::JdwpState::Create(&gJdwpOptions);
410 if (gJdwpState == NULL) {
Elliott Hughesf8a2df72011-12-01 12:19:54 -0800411 // We probably failed because some other process has the port already, which means that
412 // if we don't abort the user is likely to think they're talking to us when they're actually
413 // talking to that other process.
Elliott Hughes3d30d9b2011-12-07 17:35:48 -0800414 LOG(FATAL) << "Debugger thread failed to initialize";
Elliott Hughesd1cc8362011-10-24 16:58:50 -0700415 }
416
417 // If a debugger has already attached, send the "welcome" message.
418 // This may cause us to suspend all threads.
Elliott Hughes376a7a02011-10-24 18:35:55 -0700419 if (gJdwpState->IsActive()) {
Elliott Hughes34e06962012-04-09 13:55:55 -0700420 //ScopedThreadStateChange tsc(Thread::Current(), kRunnable);
Elliott Hughes376a7a02011-10-24 18:35:55 -0700421 if (!gJdwpState->PostVMStart()) {
Elliott Hughes3d30d9b2011-12-07 17:35:48 -0800422 LOG(WARNING) << "Failed to post 'start' message to debugger";
Elliott Hughesd1cc8362011-10-24 16:58:50 -0700423 }
424 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700425}
426
Elliott Hughesd1cc8362011-10-24 16:58:50 -0700427void Dbg::StopJdwp() {
Elliott Hughes376a7a02011-10-24 18:35:55 -0700428 delete gJdwpState;
Elliott Hughes475fc232011-10-25 15:00:35 -0700429 delete gRegistry;
430 gRegistry = NULL;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700431}
432
Elliott Hughes767a1472011-10-26 18:49:02 -0700433void Dbg::GcDidFinish() {
434 if (gDdmHpifWhen != HPIF_WHEN_NEVER) {
Elliott Hughes81ff3182012-03-23 20:35:56 -0700435 LOG(DEBUG) << "Sending heap info to DDM";
Elliott Hughes7162ad92011-10-27 14:08:42 -0700436 DdmSendHeapInfo(gDdmHpifWhen);
Elliott Hughes767a1472011-10-26 18:49:02 -0700437 }
438 if (gDdmHpsgWhen != HPSG_WHEN_NEVER) {
Elliott Hughes81ff3182012-03-23 20:35:56 -0700439 LOG(DEBUG) << "Dumping heap to DDM";
Elliott Hughes6a5bd492011-10-28 14:33:57 -0700440 DdmSendHeapSegments(false);
Elliott Hughes767a1472011-10-26 18:49:02 -0700441 }
442 if (gDdmNhsgWhen != HPSG_WHEN_NEVER) {
443 LOG(DEBUG) << "Dumping native heap to DDM";
Elliott Hughes6a5bd492011-10-28 14:33:57 -0700444 DdmSendHeapSegments(true);
Elliott Hughes767a1472011-10-26 18:49:02 -0700445 }
446}
447
Elliott Hughes4ffd3132011-10-24 12:06:42 -0700448void Dbg::SetJdwpAllowed(bool allowed) {
449 gJdwpAllowed = allowed;
450}
451
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700452DebugInvokeReq* Dbg::GetInvokeReq() {
Elliott Hughes475fc232011-10-25 15:00:35 -0700453 return Thread::Current()->GetInvokeReq();
454}
455
456Thread* Dbg::GetDebugThread() {
457 return (gJdwpState != NULL) ? gJdwpState->GetDebugThread() : NULL;
458}
459
460void Dbg::ClearWaitForEventThread() {
461 gJdwpState->ClearWaitForEventThread();
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700462}
463
464void Dbg::Connected() {
Elliott Hughes3bb81562011-10-21 18:52:59 -0700465 CHECK(!gDebuggerConnected);
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -0800466 VLOG(jdwp) << "JDWP has attached";
Elliott Hughes3bb81562011-10-21 18:52:59 -0700467 gDebuggerConnected = true;
Elliott Hughes86964332012-02-15 19:37:42 -0800468 gDisposed = false;
469}
470
471void Dbg::Disposed() {
472 gDisposed = true;
473}
474
475bool Dbg::IsDisposed() {
476 return gDisposed;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700477}
478
Elliott Hughesc0f09332012-03-26 13:27:06 -0700479static void SetDebuggerUpdatesEnabledCallback(Thread* t, void* user_data) {
480 t->SetDebuggerUpdatesEnabled(*reinterpret_cast<bool*>(user_data));
481}
482
483static void SetDebuggerUpdatesEnabled(bool enabled) {
Elliott Hughesf8349362012-06-18 15:00:06 -0700484 Runtime::Current()->GetThreadList()->ForEach(SetDebuggerUpdatesEnabledCallback, &enabled);
Elliott Hughesc0f09332012-03-26 13:27:06 -0700485}
486
Elliott Hughesa2155262011-11-16 16:26:58 -0800487void Dbg::GoActive() {
488 // Enable all debugging features, including scans for breakpoints.
489 // This is a no-op if we're already active.
490 // Only called from the JDWP handler thread.
491 if (gDebuggerActive) {
492 return;
493 }
494
495 LOG(INFO) << "Debugger is active";
496
Elliott Hughesc0f09332012-03-26 13:27:06 -0700497 {
498 // TODO: dalvik only warned if there were breakpoints left over. clear in Dbg::Disconnected?
499 MutexLock mu(gBreakpointsLock);
500 CHECK_EQ(gBreakpoints.size(), 0U);
501 }
Elliott Hughesa2155262011-11-16 16:26:58 -0800502
503 gDebuggerActive = true;
Elliott Hughesc0f09332012-03-26 13:27:06 -0700504 SetDebuggerUpdatesEnabled(true);
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700505}
506
507void Dbg::Disconnected() {
Elliott Hughes234ab152011-10-26 14:02:26 -0700508 CHECK(gDebuggerConnected);
509
Elliott Hughesc0f09332012-03-26 13:27:06 -0700510 LOG(INFO) << "Debugger is no longer active";
Elliott Hughes234ab152011-10-26 14:02:26 -0700511
Elliott Hughesc0f09332012-03-26 13:27:06 -0700512 gDebuggerActive = false;
513 SetDebuggerUpdatesEnabled(false);
Elliott Hughes234ab152011-10-26 14:02:26 -0700514
515 gRegistry->Clear();
516 gDebuggerConnected = false;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700517}
518
Elliott Hughesc0f09332012-03-26 13:27:06 -0700519bool Dbg::IsDebuggerActive() {
Elliott Hughes3bb81562011-10-21 18:52:59 -0700520 return gDebuggerActive;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700521}
522
Elliott Hughesc0f09332012-03-26 13:27:06 -0700523bool Dbg::IsJdwpConfigured() {
Elliott Hughes3bb81562011-10-21 18:52:59 -0700524 return gJdwpConfigured;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700525}
526
527int64_t Dbg::LastDebuggerActivity() {
Elliott Hughesca951522011-12-05 12:01:32 -0800528 return gJdwpState->LastDebuggerActivity();
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700529}
530
531int Dbg::ThreadRunning() {
Elliott Hughes34e06962012-04-09 13:55:55 -0700532 return static_cast<int>(Thread::Current()->SetState(kRunnable));
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700533}
534
535int Dbg::ThreadWaiting() {
Elliott Hughes34e06962012-04-09 13:55:55 -0700536 return static_cast<int>(Thread::Current()->SetState(kVmWait));
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700537}
538
Elliott Hughes6ba581a2011-10-25 11:45:35 -0700539int Dbg::ThreadContinuing(int new_state) {
Elliott Hughes34e06962012-04-09 13:55:55 -0700540 return static_cast<int>(Thread::Current()->SetState(static_cast<ThreadState>(new_state)));
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700541}
542
543void Dbg::UndoDebuggerSuspensions() {
Elliott Hughes234ab152011-10-26 14:02:26 -0700544 Runtime::Current()->GetThreadList()->UndoDebuggerSuspensions();
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700545}
546
547void Dbg::Exit(int status) {
Elliott Hughes1bba14f2011-12-01 18:00:36 -0800548 exit(status); // This is all dalvik did.
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700549}
550
Elliott Hughesbfe487b2011-10-26 15:48:55 -0700551void Dbg::VisitRoots(Heap::RootVisitor* visitor, void* arg) {
552 if (gRegistry != NULL) {
553 gRegistry->VisitRoots(visitor, arg);
554 }
555}
556
Elliott Hughesc308a5d2012-02-16 17:12:06 -0800557std::string Dbg::GetClassName(JDWP::RefTypeId classId) {
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -0800558 Object* o = gRegistry->Get<Object*>(classId);
Elliott Hughes436e3722012-02-17 20:01:47 -0800559 if (o == NULL) {
560 return "NULL";
561 }
562 if (o == kInvalidObject) {
563 return StringPrintf("invalid object %p", reinterpret_cast<void*>(classId));
564 }
565 if (!o->IsClass()) {
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -0800566 return StringPrintf("non-class %p", o); // This is only used for debugging output anyway.
567 }
Elliott Hughesc308a5d2012-02-16 17:12:06 -0800568 return DescriptorToName(ClassHelper(o->AsClass()).GetDescriptor());
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700569}
570
Elliott Hughes436e3722012-02-17 20:01:47 -0800571JDWP::JdwpError Dbg::GetClassObject(JDWP::RefTypeId id, JDWP::ObjectId& classObjectId) {
572 JDWP::JdwpError status;
573 Class* c = DecodeClass(id, status);
574 if (c == NULL) {
575 return status;
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -0800576 }
Elliott Hughes436e3722012-02-17 20:01:47 -0800577 classObjectId = gRegistry->Add(c);
578 return JDWP::ERR_NONE;
Elliott Hughes86964332012-02-15 19:37:42 -0800579}
580
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -0800581JDWP::JdwpError Dbg::GetSuperclass(JDWP::RefTypeId id, JDWP::RefTypeId& superclassId) {
582 JDWP::JdwpError status;
583 Class* c = DecodeClass(id, status);
584 if (c == NULL) {
585 return status;
586 }
587 if (c->IsInterface()) {
588 // http://code.google.com/p/android/issues/detail?id=20856
Elliott Hughesa0933622012-04-17 10:46:02 -0700589 superclassId = 0;
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -0800590 } else {
591 superclassId = gRegistry->Add(c->GetSuperClass());
592 }
593 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700594}
595
Elliott Hughes436e3722012-02-17 20:01:47 -0800596JDWP::JdwpError Dbg::GetClassLoader(JDWP::RefTypeId id, JDWP::ExpandBuf* pReply) {
Elliott Hughes1bba14f2011-12-01 18:00:36 -0800597 Object* o = gRegistry->Get<Object*>(id);
Elliott Hughes436e3722012-02-17 20:01:47 -0800598 if (o == NULL || o == kInvalidObject) {
599 return JDWP::ERR_INVALID_OBJECT;
600 }
601 expandBufAddObjectId(pReply, gRegistry->Add(o->GetClass()->GetClassLoader()));
602 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700603}
604
Elliott Hughes436e3722012-02-17 20:01:47 -0800605JDWP::JdwpError Dbg::GetModifiers(JDWP::RefTypeId id, JDWP::ExpandBuf* pReply) {
606 JDWP::JdwpError status;
607 Class* c = DecodeClass(id, status);
608 if (c == NULL) {
609 return status;
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -0800610 }
Elliott Hughes436e3722012-02-17 20:01:47 -0800611
612 uint32_t access_flags = c->GetAccessFlags() & kAccJavaFlagsMask;
613
614 // Set ACC_SUPER; dex files don't contain this flag, but all classes are supposed to have it set.
615 // Class.getModifiers doesn't return it, but JDWP does, so we set it here.
616 access_flags |= kAccSuper;
617
618 expandBufAdd4BE(pReply, access_flags);
619
620 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700621}
622
Elliott Hughes436e3722012-02-17 20:01:47 -0800623JDWP::JdwpError Dbg::GetReflectedType(JDWP::RefTypeId classId, JDWP::ExpandBuf* pReply) {
624 JDWP::JdwpError status;
625 Class* c = DecodeClass(classId, status);
626 if (c == NULL) {
627 return status;
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -0800628 }
Elliott Hughes436e3722012-02-17 20:01:47 -0800629
630 expandBufAdd1(pReply, c->IsInterface() ? JDWP::TT_INTERFACE : JDWP::TT_CLASS);
631 expandBufAddRefTypeId(pReply, classId);
632 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700633}
634
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -0800635void Dbg::GetClassList(std::vector<JDWP::RefTypeId>& classes) {
Elliott Hughesa2155262011-11-16 16:26:58 -0800636 // Get the complete list of reference classes (i.e. all classes except
637 // the primitive types).
638 // Returns a newly-allocated buffer full of RefTypeId values.
639 struct ClassListCreator {
Elliott Hughesba8eee12012-01-24 20:25:24 -0800640 explicit ClassListCreator(std::vector<JDWP::RefTypeId>& classes) : classes(classes) {
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -0800641 }
642
Elliott Hughesa2155262011-11-16 16:26:58 -0800643 static bool Visit(Class* c, void* arg) {
644 return reinterpret_cast<ClassListCreator*>(arg)->Visit(c);
645 }
646
647 bool Visit(Class* c) {
648 if (!c->IsPrimitive()) {
649 classes.push_back(static_cast<JDWP::RefTypeId>(gRegistry->Add(c)));
650 }
651 return true;
652 }
653
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -0800654 std::vector<JDWP::RefTypeId>& classes;
Elliott Hughesa2155262011-11-16 16:26:58 -0800655 };
656
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -0800657 ClassListCreator clc(classes);
Elliott Hughesa2155262011-11-16 16:26:58 -0800658 Runtime::Current()->GetClassLinker()->VisitClasses(ClassListCreator::Visit, &clc);
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700659}
660
Elliott Hughes436e3722012-02-17 20:01:47 -0800661JDWP::JdwpError Dbg::GetClassInfo(JDWP::RefTypeId classId, JDWP::JdwpTypeTag* pTypeTag, uint32_t* pStatus, std::string* pDescriptor) {
662 JDWP::JdwpError status;
663 Class* c = DecodeClass(classId, status);
664 if (c == NULL) {
665 return status;
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -0800666 }
667
Elliott Hughesa2155262011-11-16 16:26:58 -0800668 if (c->IsArrayClass()) {
669 *pStatus = JDWP::CS_VERIFIED | JDWP::CS_PREPARED;
670 *pTypeTag = JDWP::TT_ARRAY;
671 } else {
672 if (c->IsErroneous()) {
673 *pStatus = JDWP::CS_ERROR;
674 } else {
675 *pStatus = JDWP::CS_VERIFIED | JDWP::CS_PREPARED | JDWP::CS_INITIALIZED;
676 }
677 *pTypeTag = c->IsInterface() ? JDWP::TT_INTERFACE : JDWP::TT_CLASS;
678 }
679
680 if (pDescriptor != NULL) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800681 *pDescriptor = ClassHelper(c).GetDescriptor();
Elliott Hughesa2155262011-11-16 16:26:58 -0800682 }
Elliott Hughes436e3722012-02-17 20:01:47 -0800683 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700684}
685
Elliott Hughesc3b77c72011-12-15 20:56:48 -0800686void Dbg::FindLoadedClassBySignature(const char* descriptor, std::vector<JDWP::RefTypeId>& ids) {
Elliott Hughes6fa602d2011-12-02 17:54:25 -0800687 std::vector<Class*> classes;
688 Runtime::Current()->GetClassLinker()->LookupClasses(descriptor, classes);
689 ids.clear();
690 for (size_t i = 0; i < classes.size(); ++i) {
691 ids.push_back(gRegistry->Add(classes[i]));
692 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700693}
694
Elliott Hughes2435a572012-02-17 16:07:41 -0800695JDWP::JdwpError Dbg::GetReferenceType(JDWP::ObjectId objectId, JDWP::ExpandBuf* pReply) {
Elliott Hughes499c5132011-11-17 14:55:11 -0800696 Object* o = gRegistry->Get<Object*>(objectId);
Elliott Hughes436e3722012-02-17 20:01:47 -0800697 if (o == NULL || o == kInvalidObject) {
Elliott Hughes2435a572012-02-17 16:07:41 -0800698 return JDWP::ERR_INVALID_OBJECT;
Elliott Hughes499c5132011-11-17 14:55:11 -0800699 }
Elliott Hughes2435a572012-02-17 16:07:41 -0800700
701 JDWP::JdwpTypeTag type_tag;
702 if (o->GetClass()->IsArrayClass()) {
703 type_tag = JDWP::TT_ARRAY;
704 } else if (o->GetClass()->IsInterface()) {
705 type_tag = JDWP::TT_INTERFACE;
706 } else {
707 type_tag = JDWP::TT_CLASS;
708 }
709 JDWP::RefTypeId type_id = gRegistry->Add(o->GetClass());
710
711 expandBufAdd1(pReply, type_tag);
712 expandBufAddRefTypeId(pReply, type_id);
713
714 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700715}
716
Elliott Hughes436e3722012-02-17 20:01:47 -0800717JDWP::JdwpError Dbg::GetSignature(JDWP::RefTypeId classId, std::string& signature) {
Elliott Hughes1fe7afb2012-02-13 17:23:03 -0800718 JDWP::JdwpError status;
Elliott Hughes436e3722012-02-17 20:01:47 -0800719 Class* c = DecodeClass(classId, status);
Elliott Hughes1fe7afb2012-02-13 17:23:03 -0800720 if (c == NULL) {
721 return status;
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -0800722 }
Elliott Hughes1fe7afb2012-02-13 17:23:03 -0800723 signature = ClassHelper(c).GetDescriptor();
724 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700725}
726
Elliott Hughes436e3722012-02-17 20:01:47 -0800727JDWP::JdwpError Dbg::GetSourceFile(JDWP::RefTypeId classId, std::string& result) {
728 JDWP::JdwpError status;
729 Class* c = DecodeClass(classId, status);
730 if (c == NULL) {
731 return status;
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -0800732 }
Elliott Hughes436e3722012-02-17 20:01:47 -0800733 result = ClassHelper(c).GetSourceFile();
734 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700735}
736
Elliott Hughes546b9862012-06-20 16:06:13 -0700737JDWP::JdwpError Dbg::GetObjectTag(JDWP::ObjectId objectId, uint8_t& tag) {
Elliott Hughes24437992011-11-30 14:49:33 -0800738 Object* o = gRegistry->Get<Object*>(objectId);
Elliott Hughes546b9862012-06-20 16:06:13 -0700739 if (o == kInvalidObject) {
740 return JDWP::ERR_INVALID_OBJECT;
741 }
742 tag = TagFromObject(o);
743 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700744}
745
Elliott Hughesaed4be92011-12-02 16:16:23 -0800746size_t Dbg::GetTagWidth(JDWP::JdwpTag tag) {
Elliott Hughesdbb40792011-11-18 17:05:22 -0800747 switch (tag) {
748 case JDWP::JT_VOID:
749 return 0;
750 case JDWP::JT_BYTE:
751 case JDWP::JT_BOOLEAN:
752 return 1;
753 case JDWP::JT_CHAR:
754 case JDWP::JT_SHORT:
755 return 2;
756 case JDWP::JT_FLOAT:
757 case JDWP::JT_INT:
758 return 4;
759 case JDWP::JT_ARRAY:
760 case JDWP::JT_OBJECT:
761 case JDWP::JT_STRING:
762 case JDWP::JT_THREAD:
763 case JDWP::JT_THREAD_GROUP:
764 case JDWP::JT_CLASS_LOADER:
765 case JDWP::JT_CLASS_OBJECT:
766 return sizeof(JDWP::ObjectId);
767 case JDWP::JT_DOUBLE:
768 case JDWP::JT_LONG:
769 return 8;
770 default:
Elliott Hughes3d30d9b2011-12-07 17:35:48 -0800771 LOG(FATAL) << "Unknown tag " << tag;
Elliott Hughesdbb40792011-11-18 17:05:22 -0800772 return -1;
773 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700774}
775
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -0800776JDWP::JdwpError Dbg::GetArrayLength(JDWP::ObjectId arrayId, int& length) {
777 JDWP::JdwpError status;
778 Array* a = DecodeArray(arrayId, status);
779 if (a == NULL) {
780 return status;
Elliott Hughes24437992011-11-30 14:49:33 -0800781 }
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -0800782 length = a->GetLength();
783 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700784}
785
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -0800786JDWP::JdwpError Dbg::OutputArray(JDWP::ObjectId arrayId, int offset, int count, JDWP::ExpandBuf* pReply) {
787 JDWP::JdwpError status;
788 Array* a = DecodeArray(arrayId, status);
789 if (a == NULL) {
790 return status;
791 }
Elliott Hughes24437992011-11-30 14:49:33 -0800792
793 if (offset < 0 || count < 0 || offset > a->GetLength() || a->GetLength() - offset < count) {
794 LOG(WARNING) << __FUNCTION__ << " access out of bounds: offset=" << offset << "; count=" << count;
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -0800795 return JDWP::ERR_INVALID_LENGTH;
Elliott Hughes24437992011-11-30 14:49:33 -0800796 }
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800797 std::string descriptor(ClassHelper(a->GetClass()).GetDescriptor());
Elliott Hughes24437992011-11-30 14:49:33 -0800798 JDWP::JdwpTag tag = BasicTagFromDescriptor(descriptor.c_str() + 1);
799
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -0800800 expandBufAdd1(pReply, tag);
801 expandBufAdd4BE(pReply, count);
802
Elliott Hughes24437992011-11-30 14:49:33 -0800803 if (IsPrimitiveTag(tag)) {
804 size_t width = GetTagWidth(tag);
Elliott Hughes24437992011-11-30 14:49:33 -0800805 uint8_t* dst = expandBufAddSpace(pReply, count * width);
806 if (width == 8) {
Ian Rogersa15e67d2012-02-28 13:51:55 -0800807 const uint64_t* src8 = reinterpret_cast<uint64_t*>(a->GetRawData(sizeof(uint64_t)));
Elliott Hughes24437992011-11-30 14:49:33 -0800808 for (int i = 0; i < count; ++i) JDWP::Write8BE(&dst, src8[offset + i]);
809 } else if (width == 4) {
Ian Rogersa15e67d2012-02-28 13:51:55 -0800810 const uint32_t* src4 = reinterpret_cast<uint32_t*>(a->GetRawData(sizeof(uint32_t)));
Elliott Hughes24437992011-11-30 14:49:33 -0800811 for (int i = 0; i < count; ++i) JDWP::Write4BE(&dst, src4[offset + i]);
812 } else if (width == 2) {
Ian Rogersa15e67d2012-02-28 13:51:55 -0800813 const uint16_t* src2 = reinterpret_cast<uint16_t*>(a->GetRawData(sizeof(uint16_t)));
Elliott Hughes24437992011-11-30 14:49:33 -0800814 for (int i = 0; i < count; ++i) JDWP::Write2BE(&dst, src2[offset + i]);
815 } else {
Ian Rogersa15e67d2012-02-28 13:51:55 -0800816 const uint8_t* src = reinterpret_cast<uint8_t*>(a->GetRawData(sizeof(uint8_t)));
Elliott Hughes24437992011-11-30 14:49:33 -0800817 memcpy(dst, &src[offset * width], count * width);
818 }
819 } else {
820 ObjectArray<Object>* oa = a->AsObjectArray<Object>();
821 for (int i = 0; i < count; ++i) {
Elliott Hughesf03b8f62011-12-02 14:26:25 -0800822 Object* element = oa->Get(offset + i);
Elliott Hughes24437992011-11-30 14:49:33 -0800823 JDWP::JdwpTag specific_tag = (element != NULL) ? TagFromObject(element) : tag;
824 expandBufAdd1(pReply, specific_tag);
825 expandBufAddObjectId(pReply, gRegistry->Add(element));
826 }
827 }
828
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -0800829 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700830}
831
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -0800832JDWP::JdwpError Dbg::SetArrayElements(JDWP::ObjectId arrayId, int offset, int count, const uint8_t* src) {
833 JDWP::JdwpError status;
834 Array* a = DecodeArray(arrayId, status);
835 if (a == NULL) {
836 return status;
837 }
Elliott Hughesf03b8f62011-12-02 14:26:25 -0800838
839 if (offset < 0 || count < 0 || offset > a->GetLength() || a->GetLength() - offset < count) {
840 LOG(WARNING) << __FUNCTION__ << " access out of bounds: offset=" << offset << "; count=" << count;
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -0800841 return JDWP::ERR_INVALID_LENGTH;
Elliott Hughesf03b8f62011-12-02 14:26:25 -0800842 }
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800843 std::string descriptor(ClassHelper(a->GetClass()).GetDescriptor());
Elliott Hughesf03b8f62011-12-02 14:26:25 -0800844 JDWP::JdwpTag tag = BasicTagFromDescriptor(descriptor.c_str() + 1);
845
846 if (IsPrimitiveTag(tag)) {
847 size_t width = GetTagWidth(tag);
Elliott Hughesf03b8f62011-12-02 14:26:25 -0800848 if (width == 8) {
Ian Rogersa15e67d2012-02-28 13:51:55 -0800849 uint8_t* dst = &(reinterpret_cast<uint8_t*>(a->GetRawData(sizeof(uint64_t)))[offset * width]);
Elliott Hughesf03b8f62011-12-02 14:26:25 -0800850 for (int i = 0; i < count; ++i) {
851 // Handle potentially non-aligned memory access one byte at a time for ARM's benefit.
852 uint64_t value;
853 for (size_t j = 0; j < sizeof(uint64_t); ++j) reinterpret_cast<uint8_t*>(&value)[j] = src[j];
854 src += sizeof(uint64_t);
855 JDWP::Write8BE(&dst, value);
856 }
857 } else if (width == 4) {
Ian Rogersa15e67d2012-02-28 13:51:55 -0800858 uint8_t* dst = &(reinterpret_cast<uint8_t*>(a->GetRawData(sizeof(uint32_t)))[offset * width]);
Elliott Hughesf03b8f62011-12-02 14:26:25 -0800859 const uint32_t* src4 = reinterpret_cast<const uint32_t*>(src);
860 for (int i = 0; i < count; ++i) JDWP::Write4BE(&dst, src4[i]);
861 } else if (width == 2) {
Ian Rogersa15e67d2012-02-28 13:51:55 -0800862 uint8_t* dst = &(reinterpret_cast<uint8_t*>(a->GetRawData(sizeof(uint16_t)))[offset * width]);
Elliott Hughesf03b8f62011-12-02 14:26:25 -0800863 const uint16_t* src2 = reinterpret_cast<const uint16_t*>(src);
864 for (int i = 0; i < count; ++i) JDWP::Write2BE(&dst, src2[i]);
865 } else {
Ian Rogersa15e67d2012-02-28 13:51:55 -0800866 uint8_t* dst = &(reinterpret_cast<uint8_t*>(a->GetRawData(sizeof(uint8_t)))[offset * width]);
Elliott Hughesf03b8f62011-12-02 14:26:25 -0800867 memcpy(&dst[offset * width], src, count * width);
868 }
869 } else {
870 ObjectArray<Object>* oa = a->AsObjectArray<Object>();
871 for (int i = 0; i < count; ++i) {
872 JDWP::ObjectId id = JDWP::ReadObjectId(&src);
Elliott Hughes436e3722012-02-17 20:01:47 -0800873 Object* o = gRegistry->Get<Object*>(id);
874 if (o == kInvalidObject) {
875 return JDWP::ERR_INVALID_OBJECT;
876 }
877 oa->Set(offset + i, o);
Elliott Hughesf03b8f62011-12-02 14:26:25 -0800878 }
879 }
880
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -0800881 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700882}
883
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -0800884JDWP::ObjectId Dbg::CreateString(const std::string& str) {
885 return gRegistry->Add(String::AllocFromModifiedUtf8(str.c_str()));
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700886}
887
Elliott Hughes436e3722012-02-17 20:01:47 -0800888JDWP::JdwpError Dbg::CreateObject(JDWP::RefTypeId classId, JDWP::ObjectId& new_object) {
889 JDWP::JdwpError status;
890 Class* c = DecodeClass(classId, status);
891 if (c == NULL) {
892 return status;
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -0800893 }
Elliott Hughes436e3722012-02-17 20:01:47 -0800894 new_object = gRegistry->Add(c->AllocObject());
895 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700896}
897
Elliott Hughesbf13d362011-12-08 15:51:37 -0800898/*
899 * Used by Eclipse's "Display" view to evaluate "new byte[5]" to get "(byte[]) [0, 0, 0, 0, 0]".
900 */
Elliott Hughes436e3722012-02-17 20:01:47 -0800901JDWP::JdwpError Dbg::CreateArrayObject(JDWP::RefTypeId arrayClassId, uint32_t length, JDWP::ObjectId& new_array) {
902 JDWP::JdwpError status;
903 Class* c = DecodeClass(arrayClassId, status);
904 if (c == NULL) {
905 return status;
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -0800906 }
Elliott Hughes436e3722012-02-17 20:01:47 -0800907 new_array = gRegistry->Add(Array::Alloc(c, length));
908 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700909}
910
911bool Dbg::MatchType(JDWP::RefTypeId instClassId, JDWP::RefTypeId classId) {
Elliott Hughes436e3722012-02-17 20:01:47 -0800912 JDWP::JdwpError status;
913 Class* c1 = DecodeClass(instClassId, status);
Elliott Hughesa656a0f2012-02-21 18:03:44 -0800914 CHECK(c1 != NULL);
Elliott Hughes436e3722012-02-17 20:01:47 -0800915 Class* c2 = DecodeClass(classId, status);
Elliott Hughesa656a0f2012-02-21 18:03:44 -0800916 CHECK(c2 != NULL);
917 return c1->IsAssignableFrom(c2);
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700918}
919
Elliott Hughes86964332012-02-15 19:37:42 -0800920static JDWP::FieldId ToFieldId(const Field* f) {
Elliott Hughes03181a82011-11-17 17:22:21 -0800921#ifdef MOVING_GARBAGE_COLLECTOR
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700922 UNIMPLEMENTED(FATAL);
Elliott Hughes03181a82011-11-17 17:22:21 -0800923#else
924 return static_cast<JDWP::FieldId>(reinterpret_cast<uintptr_t>(f));
925#endif
926}
927
Elliott Hughes86964332012-02-15 19:37:42 -0800928static JDWP::MethodId ToMethodId(const Method* m) {
Elliott Hughes03181a82011-11-17 17:22:21 -0800929#ifdef MOVING_GARBAGE_COLLECTOR
930 UNIMPLEMENTED(FATAL);
931#else
932 return static_cast<JDWP::MethodId>(reinterpret_cast<uintptr_t>(m));
933#endif
934}
935
Elliott Hughes86964332012-02-15 19:37:42 -0800936static Field* FromFieldId(JDWP::FieldId fid) {
Elliott Hughesaed4be92011-12-02 16:16:23 -0800937#ifdef MOVING_GARBAGE_COLLECTOR
938 UNIMPLEMENTED(FATAL);
939#else
940 return reinterpret_cast<Field*>(static_cast<uintptr_t>(fid));
941#endif
942}
943
Elliott Hughes86964332012-02-15 19:37:42 -0800944static Method* FromMethodId(JDWP::MethodId mid) {
Elliott Hughes03181a82011-11-17 17:22:21 -0800945#ifdef MOVING_GARBAGE_COLLECTOR
946 UNIMPLEMENTED(FATAL);
947#else
948 return reinterpret_cast<Method*>(static_cast<uintptr_t>(mid));
949#endif
950}
951
Ian Rogers0399dde2012-06-06 17:09:28 -0700952static void SetLocation(JDWP::JdwpLocation& location, Method* m, uint32_t dex_pc) {
Elliott Hughes91bf6cd2012-02-14 17:27:48 -0800953 if (m == NULL) {
954 memset(&location, 0, sizeof(location));
955 } else {
956 Class* c = m->GetDeclaringClass();
Elliott Hughes74847412012-06-20 18:10:21 -0700957 location.type_tag = c->IsInterface() ? JDWP::TT_INTERFACE : JDWP::TT_CLASS;
958 location.class_id = gRegistry->Add(c);
959 location.method_id = ToMethodId(m);
Ian Rogers0399dde2012-06-06 17:09:28 -0700960 location.dex_pc = dex_pc;
Elliott Hughes91bf6cd2012-02-14 17:27:48 -0800961 }
Elliott Hughesd07986f2011-12-06 18:27:45 -0800962}
963
Elliott Hughes436e3722012-02-17 20:01:47 -0800964std::string Dbg::GetMethodName(JDWP::RefTypeId, JDWP::MethodId methodId) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800965 Method* m = FromMethodId(methodId);
966 return MethodHelper(m).GetName();
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700967}
968
Elliott Hughesa2e54f62011-11-17 13:01:30 -0800969/*
970 * Augment the access flags for synthetic methods and fields by setting
971 * the (as described by the spec) "0xf0000000 bit". Also, strip out any
972 * flags not specified by the Java programming language.
973 */
974static uint32_t MangleAccessFlags(uint32_t accessFlags) {
975 accessFlags &= kAccJavaFlagsMask;
976 if ((accessFlags & kAccSynthetic) != 0) {
977 accessFlags |= 0xf0000000;
978 }
979 return accessFlags;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700980}
981
Elliott Hughesdbb40792011-11-18 17:05:22 -0800982static const uint16_t kEclipseWorkaroundSlot = 1000;
983
984/*
985 * Eclipse appears to expect that the "this" reference is in slot zero.
986 * If it's not, the "variables" display will show two copies of "this",
987 * possibly because it gets "this" from SF.ThisObject and then displays
988 * all locals with nonzero slot numbers.
989 *
990 * So, we remap the item in slot 0 to 1000, and remap "this" to zero. On
991 * SF.GetValues / SF.SetValues we map them back.
Elliott Hughesc5b734a2011-12-01 17:20:58 -0800992 *
993 * TODO: jdb uses the value to determine whether a variable is a local or an argument,
994 * by checking whether it's less than the number of arguments. To make that work, we'd
995 * have to "mangle" all the arguments to come first, not just the implicit argument 'this'.
Elliott Hughesdbb40792011-11-18 17:05:22 -0800996 */
997static uint16_t MangleSlot(uint16_t slot, const char* name) {
998 uint16_t newSlot = slot;
999 if (strcmp(name, "this") == 0) {
1000 newSlot = 0;
1001 } else if (slot == 0) {
1002 newSlot = kEclipseWorkaroundSlot;
1003 }
1004 return newSlot;
1005}
1006
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08001007static uint16_t DemangleSlot(uint16_t slot, Method* m) {
Elliott Hughesdbb40792011-11-18 17:05:22 -08001008 if (slot == kEclipseWorkaroundSlot) {
Elliott Hughes68fdbd02011-11-29 19:22:47 -08001009 return 0;
Elliott Hughesdbb40792011-11-18 17:05:22 -08001010 } else if (slot == 0) {
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08001011 const DexFile::CodeItem* code_item = MethodHelper(m).GetCodeItem();
Elliott Hughescaf76542012-06-28 16:08:22 -07001012 CHECK(code_item != NULL) << PrettyMethod(m);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001013 return code_item->registers_size_ - code_item->ins_size_;
Elliott Hughesdbb40792011-11-18 17:05:22 -08001014 }
Elliott Hughes68fdbd02011-11-29 19:22:47 -08001015 return slot;
Elliott Hughesdbb40792011-11-18 17:05:22 -08001016}
1017
Elliott Hughes436e3722012-02-17 20:01:47 -08001018JDWP::JdwpError Dbg::OutputDeclaredFields(JDWP::RefTypeId classId, bool with_generic, JDWP::ExpandBuf* pReply) {
1019 JDWP::JdwpError status;
1020 Class* c = DecodeClass(classId, status);
1021 if (c == NULL) {
1022 return status;
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -08001023 }
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001024
1025 size_t instance_field_count = c->NumInstanceFields();
1026 size_t static_field_count = c->NumStaticFields();
1027
1028 expandBufAdd4BE(pReply, instance_field_count + static_field_count);
1029
1030 for (size_t i = 0; i < instance_field_count + static_field_count; ++i) {
1031 Field* f = (i < instance_field_count) ? c->GetInstanceField(i) : c->GetStaticField(i - instance_field_count);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001032 FieldHelper fh(f);
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001033 expandBufAddFieldId(pReply, ToFieldId(f));
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001034 expandBufAddUtf8String(pReply, fh.GetName());
1035 expandBufAddUtf8String(pReply, fh.GetTypeDescriptor());
Elliott Hughesc5b734a2011-12-01 17:20:58 -08001036 if (with_generic) {
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001037 static const char genericSignature[1] = "";
1038 expandBufAddUtf8String(pReply, genericSignature);
1039 }
1040 expandBufAdd4BE(pReply, MangleAccessFlags(f->GetAccessFlags()));
1041 }
Elliott Hughes436e3722012-02-17 20:01:47 -08001042 return JDWP::ERR_NONE;
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001043}
1044
Elliott Hughes436e3722012-02-17 20:01:47 -08001045JDWP::JdwpError Dbg::OutputDeclaredMethods(JDWP::RefTypeId classId, bool with_generic, JDWP::ExpandBuf* pReply) {
1046 JDWP::JdwpError status;
1047 Class* c = DecodeClass(classId, status);
1048 if (c == NULL) {
1049 return status;
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -08001050 }
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001051
1052 size_t direct_method_count = c->NumDirectMethods();
1053 size_t virtual_method_count = c->NumVirtualMethods();
1054
1055 expandBufAdd4BE(pReply, direct_method_count + virtual_method_count);
1056
1057 for (size_t i = 0; i < direct_method_count + virtual_method_count; ++i) {
1058 Method* m = (i < direct_method_count) ? c->GetDirectMethod(i) : c->GetVirtualMethod(i - direct_method_count);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001059 MethodHelper mh(m);
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001060 expandBufAddMethodId(pReply, ToMethodId(m));
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001061 expandBufAddUtf8String(pReply, mh.GetName());
Elliott Hughes4740cdf2011-12-07 14:07:12 -08001062 expandBufAddUtf8String(pReply, mh.GetSignature());
Elliott Hughesc5b734a2011-12-01 17:20:58 -08001063 if (with_generic) {
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001064 static const char genericSignature[1] = "";
1065 expandBufAddUtf8String(pReply, genericSignature);
1066 }
1067 expandBufAdd4BE(pReply, MangleAccessFlags(m->GetAccessFlags()));
1068 }
Elliott Hughes436e3722012-02-17 20:01:47 -08001069 return JDWP::ERR_NONE;
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001070}
1071
Elliott Hughes436e3722012-02-17 20:01:47 -08001072JDWP::JdwpError Dbg::OutputDeclaredInterfaces(JDWP::RefTypeId classId, JDWP::ExpandBuf* pReply) {
1073 JDWP::JdwpError status;
1074 Class* c = DecodeClass(classId, status);
1075 if (c == NULL) {
1076 return status;
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -08001077 }
Elliott Hughes436e3722012-02-17 20:01:47 -08001078
1079 ClassHelper kh(c);
Ian Rogersd24e2642012-06-06 21:21:43 -07001080 size_t interface_count = kh.NumDirectInterfaces();
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001081 expandBufAdd4BE(pReply, interface_count);
1082 for (size_t i = 0; i < interface_count; ++i) {
Ian Rogersd24e2642012-06-06 21:21:43 -07001083 expandBufAddRefTypeId(pReply, gRegistry->Add(kh.GetDirectInterface(i)));
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001084 }
Elliott Hughes436e3722012-02-17 20:01:47 -08001085 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001086}
1087
Elliott Hughes436e3722012-02-17 20:01:47 -08001088void Dbg::OutputLineTable(JDWP::RefTypeId, JDWP::MethodId methodId, JDWP::ExpandBuf* pReply) {
Elliott Hughes03181a82011-11-17 17:22:21 -08001089 struct DebugCallbackContext {
1090 int numItems;
1091 JDWP::ExpandBuf* pReply;
1092
Elliott Hughes2435a572012-02-17 16:07:41 -08001093 static bool Callback(void* context, uint32_t address, uint32_t line_number) {
Elliott Hughes03181a82011-11-17 17:22:21 -08001094 DebugCallbackContext* pContext = reinterpret_cast<DebugCallbackContext*>(context);
1095 expandBufAdd8BE(pContext->pReply, address);
Elliott Hughes2435a572012-02-17 16:07:41 -08001096 expandBufAdd4BE(pContext->pReply, line_number);
Elliott Hughes03181a82011-11-17 17:22:21 -08001097 pContext->numItems++;
1098 return true;
1099 }
1100 };
1101
1102 Method* m = FromMethodId(methodId);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001103 MethodHelper mh(m);
Elliott Hughes03181a82011-11-17 17:22:21 -08001104 uint64_t start, end;
1105 if (m->IsNative()) {
1106 start = -1;
1107 end = -1;
1108 } else {
1109 start = 0;
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001110 // TODO: what are the units supposed to be? *2?
1111 end = mh.GetCodeItem()->insns_size_in_code_units_;
Elliott Hughes03181a82011-11-17 17:22:21 -08001112 }
1113
1114 expandBufAdd8BE(pReply, start);
1115 expandBufAdd8BE(pReply, end);
1116
1117 // Add numLines later
1118 size_t numLinesOffset = expandBufGetLength(pReply);
1119 expandBufAdd4BE(pReply, 0);
1120
1121 DebugCallbackContext context;
1122 context.numItems = 0;
1123 context.pReply = pReply;
1124
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001125 mh.GetDexFile().DecodeDebugInfo(mh.GetCodeItem(), m->IsStatic(), m->GetDexMethodIndex(),
1126 DebugCallbackContext::Callback, NULL, &context);
Elliott Hughes03181a82011-11-17 17:22:21 -08001127
1128 JDWP::Set4BE(expandBufGetBuffer(pReply) + numLinesOffset, context.numItems);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001129}
1130
Elliott Hughes436e3722012-02-17 20:01:47 -08001131void Dbg::OutputVariableTable(JDWP::RefTypeId, JDWP::MethodId methodId, bool with_generic, JDWP::ExpandBuf* pReply) {
Elliott Hughesdbb40792011-11-18 17:05:22 -08001132 struct DebugCallbackContext {
Elliott Hughesdbb40792011-11-18 17:05:22 -08001133 JDWP::ExpandBuf* pReply;
Elliott Hughesc5b734a2011-12-01 17:20:58 -08001134 size_t variable_count;
1135 bool with_generic;
Elliott Hughesdbb40792011-11-18 17:05:22 -08001136
Elliott Hughesc5b734a2011-12-01 17:20:58 -08001137 static void Callback(void* context, uint16_t slot, uint32_t startAddress, uint32_t endAddress, const char* name, const char* descriptor, const char* signature) {
Elliott Hughesdbb40792011-11-18 17:05:22 -08001138 DebugCallbackContext* pContext = reinterpret_cast<DebugCallbackContext*>(context);
1139
Elliott Hughesad3da692012-02-24 16:51:35 -08001140 VLOG(jdwp) << StringPrintf(" %2zd: %d(%d) '%s' '%s' '%s' actual slot=%d mangled slot=%d", pContext->variable_count, startAddress, endAddress - startAddress, name, descriptor, signature, slot, MangleSlot(slot, name));
Elliott Hughesdbb40792011-11-18 17:05:22 -08001141
Elliott Hughes68fdbd02011-11-29 19:22:47 -08001142 slot = MangleSlot(slot, name);
1143
Elliott Hughesdbb40792011-11-18 17:05:22 -08001144 expandBufAdd8BE(pContext->pReply, startAddress);
1145 expandBufAddUtf8String(pContext->pReply, name);
1146 expandBufAddUtf8String(pContext->pReply, descriptor);
Elliott Hughesc5b734a2011-12-01 17:20:58 -08001147 if (pContext->with_generic) {
Elliott Hughesdbb40792011-11-18 17:05:22 -08001148 expandBufAddUtf8String(pContext->pReply, signature);
1149 }
1150 expandBufAdd4BE(pContext->pReply, endAddress - startAddress);
1151 expandBufAdd4BE(pContext->pReply, slot);
1152
Elliott Hughesc5b734a2011-12-01 17:20:58 -08001153 ++pContext->variable_count;
Elliott Hughesdbb40792011-11-18 17:05:22 -08001154 }
1155 };
1156
1157 Method* m = FromMethodId(methodId);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001158 MethodHelper mh(m);
1159 const DexFile::CodeItem* code_item = mh.GetCodeItem();
Elliott Hughesdbb40792011-11-18 17:05:22 -08001160
Elliott Hughesc5b734a2011-12-01 17:20:58 -08001161 // arg_count considers doubles and longs to take 2 units.
1162 // variable_count considers everything to take 1 unit.
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001163 std::string shorty(mh.GetShorty());
Elliott Hughesc5b734a2011-12-01 17:20:58 -08001164 expandBufAdd4BE(pReply, m->NumArgRegisters(shorty));
Elliott Hughesdbb40792011-11-18 17:05:22 -08001165
Elliott Hughesc5b734a2011-12-01 17:20:58 -08001166 // We don't know the total number of variables yet, so leave a blank and update it later.
1167 size_t variable_count_offset = expandBufGetLength(pReply);
Elliott Hughesdbb40792011-11-18 17:05:22 -08001168 expandBufAdd4BE(pReply, 0);
1169
1170 DebugCallbackContext context;
Elliott Hughesdbb40792011-11-18 17:05:22 -08001171 context.pReply = pReply;
Elliott Hughesc5b734a2011-12-01 17:20:58 -08001172 context.variable_count = 0;
1173 context.with_generic = with_generic;
Elliott Hughesdbb40792011-11-18 17:05:22 -08001174
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001175 mh.GetDexFile().DecodeDebugInfo(code_item, m->IsStatic(), m->GetDexMethodIndex(), NULL,
1176 DebugCallbackContext::Callback, &context);
Elliott Hughesdbb40792011-11-18 17:05:22 -08001177
Elliott Hughesc5b734a2011-12-01 17:20:58 -08001178 JDWP::Set4BE(expandBufGetBuffer(pReply) + variable_count_offset, context.variable_count);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001179}
1180
Elliott Hughesaed4be92011-12-02 16:16:23 -08001181JDWP::JdwpTag Dbg::GetFieldBasicTag(JDWP::FieldId fieldId) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001182 return BasicTagFromDescriptor(FieldHelper(FromFieldId(fieldId)).GetTypeDescriptor());
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001183}
1184
Elliott Hughesaed4be92011-12-02 16:16:23 -08001185JDWP::JdwpTag Dbg::GetStaticFieldBasicTag(JDWP::FieldId fieldId) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001186 return BasicTagFromDescriptor(FieldHelper(FromFieldId(fieldId)).GetTypeDescriptor());
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001187}
1188
Elliott Hughes0cf74332012-02-23 23:14:00 -08001189static JDWP::JdwpError GetFieldValueImpl(JDWP::RefTypeId refTypeId, JDWP::ObjectId objectId, JDWP::FieldId fieldId, JDWP::ExpandBuf* pReply, bool is_static) {
1190 JDWP::JdwpError status;
1191 Class* c = DecodeClass(refTypeId, status);
1192 if (refTypeId != 0 && c == NULL) {
1193 return status;
1194 }
1195
Elliott Hughesaed4be92011-12-02 16:16:23 -08001196 Object* o = gRegistry->Get<Object*>(objectId);
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08001197 if ((!is_static && o == NULL) || o == kInvalidObject) {
1198 return JDWP::ERR_INVALID_OBJECT;
1199 }
Elliott Hughesaed4be92011-12-02 16:16:23 -08001200 Field* f = FromFieldId(fieldId);
Elliott Hughes0cf74332012-02-23 23:14:00 -08001201
1202 Class* receiver_class = c;
1203 if (receiver_class == NULL && o != NULL) {
1204 receiver_class = o->GetClass();
1205 }
1206 // TODO: should we give up now if receiver_class is NULL?
1207 if (receiver_class != NULL && !f->GetDeclaringClass()->IsAssignableFrom(receiver_class)) {
1208 LOG(INFO) << "ERR_INVALID_FIELDID: " << PrettyField(f) << " " << PrettyClass(receiver_class);
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08001209 return JDWP::ERR_INVALID_FIELDID;
1210 }
Elliott Hughesaed4be92011-12-02 16:16:23 -08001211
Elliott Hughes0cf74332012-02-23 23:14:00 -08001212 // The RI only enforces the static/non-static mismatch in one direction.
1213 // TODO: should we change the tests and check both?
1214 if (is_static) {
1215 if (!f->IsStatic()) {
1216 return JDWP::ERR_INVALID_FIELDID;
1217 }
1218 } else {
1219 if (f->IsStatic()) {
1220 LOG(WARNING) << "Ignoring non-NULL receiver for ObjectReference.SetValues on static field " << PrettyField(f);
1221 o = NULL;
1222 }
1223 }
1224
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001225 JDWP::JdwpTag tag = BasicTagFromDescriptor(FieldHelper(f).GetTypeDescriptor());
Elliott Hughesaed4be92011-12-02 16:16:23 -08001226
1227 if (IsPrimitiveTag(tag)) {
1228 expandBufAdd1(pReply, tag);
1229 if (tag == JDWP::JT_BOOLEAN || tag == JDWP::JT_BYTE) {
1230 expandBufAdd1(pReply, f->Get32(o));
1231 } else if (tag == JDWP::JT_CHAR || tag == JDWP::JT_SHORT) {
1232 expandBufAdd2BE(pReply, f->Get32(o));
1233 } else if (tag == JDWP::JT_FLOAT || tag == JDWP::JT_INT) {
1234 expandBufAdd4BE(pReply, f->Get32(o));
1235 } else if (tag == JDWP::JT_DOUBLE || tag == JDWP::JT_LONG) {
1236 expandBufAdd8BE(pReply, f->Get64(o));
1237 } else {
Elliott Hughes3d30d9b2011-12-07 17:35:48 -08001238 LOG(FATAL) << "Unknown tag: " << tag;
Elliott Hughesaed4be92011-12-02 16:16:23 -08001239 }
1240 } else {
1241 Object* value = f->GetObject(o);
1242 expandBufAdd1(pReply, TagFromObject(value));
1243 expandBufAddObjectId(pReply, gRegistry->Add(value));
1244 }
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08001245 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001246}
1247
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08001248JDWP::JdwpError Dbg::GetFieldValue(JDWP::ObjectId objectId, JDWP::FieldId fieldId, JDWP::ExpandBuf* pReply) {
Elliott Hughes0cf74332012-02-23 23:14:00 -08001249 return GetFieldValueImpl(0, objectId, fieldId, pReply, false);
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08001250}
1251
Elliott Hughes0cf74332012-02-23 23:14:00 -08001252JDWP::JdwpError Dbg::GetStaticFieldValue(JDWP::RefTypeId refTypeId, JDWP::FieldId fieldId, JDWP::ExpandBuf* pReply) {
1253 return GetFieldValueImpl(refTypeId, 0, fieldId, pReply, true);
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08001254}
1255
1256static JDWP::JdwpError SetFieldValueImpl(JDWP::ObjectId objectId, JDWP::FieldId fieldId, uint64_t value, int width, bool is_static) {
Elliott Hughesaed4be92011-12-02 16:16:23 -08001257 Object* o = gRegistry->Get<Object*>(objectId);
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08001258 if ((!is_static && o == NULL) || o == kInvalidObject) {
1259 return JDWP::ERR_INVALID_OBJECT;
1260 }
Elliott Hughesaed4be92011-12-02 16:16:23 -08001261 Field* f = FromFieldId(fieldId);
Elliott Hughes0cf74332012-02-23 23:14:00 -08001262
1263 // The RI only enforces the static/non-static mismatch in one direction.
1264 // TODO: should we change the tests and check both?
1265 if (is_static) {
1266 if (!f->IsStatic()) {
1267 return JDWP::ERR_INVALID_FIELDID;
1268 }
1269 } else {
1270 if (f->IsStatic()) {
1271 LOG(WARNING) << "Ignoring non-NULL receiver for ObjectReference.SetValues on static field " << PrettyField(f);
1272 o = NULL;
1273 }
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08001274 }
Elliott Hughesaed4be92011-12-02 16:16:23 -08001275
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001276 JDWP::JdwpTag tag = BasicTagFromDescriptor(FieldHelper(f).GetTypeDescriptor());
Elliott Hughesaed4be92011-12-02 16:16:23 -08001277
1278 if (IsPrimitiveTag(tag)) {
1279 if (tag == JDWP::JT_DOUBLE || tag == JDWP::JT_LONG) {
Elliott Hughes1bac54f2012-03-16 12:48:31 -07001280 CHECK_EQ(width, 8);
Elliott Hughesaed4be92011-12-02 16:16:23 -08001281 f->Set64(o, value);
1282 } else {
Elliott Hughes1bac54f2012-03-16 12:48:31 -07001283 CHECK_LE(width, 4);
Elliott Hughesaed4be92011-12-02 16:16:23 -08001284 f->Set32(o, value);
1285 }
1286 } else {
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -08001287 Object* v = gRegistry->Get<Object*>(value);
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08001288 if (v == kInvalidObject) {
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -08001289 return JDWP::ERR_INVALID_OBJECT;
1290 }
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08001291 if (v != NULL) {
1292 Class* field_type = FieldHelper(f).GetType();
1293 if (!field_type->IsAssignableFrom(v->GetClass())) {
1294 return JDWP::ERR_INVALID_OBJECT;
1295 }
1296 }
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -08001297 f->SetObject(o, v);
Elliott Hughesaed4be92011-12-02 16:16:23 -08001298 }
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -08001299
1300 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001301}
1302
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08001303JDWP::JdwpError Dbg::SetFieldValue(JDWP::ObjectId objectId, JDWP::FieldId fieldId, uint64_t value, int width) {
1304 return SetFieldValueImpl(objectId, fieldId, value, width, false);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001305}
1306
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -08001307JDWP::JdwpError Dbg::SetStaticFieldValue(JDWP::FieldId fieldId, uint64_t value, int width) {
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08001308 return SetFieldValueImpl(0, fieldId, value, width, true);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001309}
1310
Elliott Hughes68fdbd02011-11-29 19:22:47 -08001311std::string Dbg::StringToUtf8(JDWP::ObjectId strId) {
1312 String* s = gRegistry->Get<String*>(strId);
1313 return s->ToModifiedUtf8();
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001314}
1315
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001316bool Dbg::GetThreadName(JDWP::ObjectId threadId, std::string& name) {
1317 ScopedThreadListLock thread_list_lock;
1318 Thread* thread = DecodeThread(threadId);
1319 if (thread == NULL) {
1320 return false;
1321 }
Elliott Hughesffb465f2012-03-01 18:46:05 -08001322 thread->GetThreadName(name);
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001323 return true;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001324}
1325
Elliott Hughes2435a572012-02-17 16:07:41 -08001326JDWP::JdwpError Dbg::GetThreadGroup(JDWP::ObjectId threadId, JDWP::ExpandBuf* pReply) {
Elliott Hughes499c5132011-11-17 14:55:11 -08001327 Object* thread = gRegistry->Get<Object*>(threadId);
Elliott Hughes436e3722012-02-17 20:01:47 -08001328 if (thread == kInvalidObject) {
Elliott Hughes2435a572012-02-17 16:07:41 -08001329 return JDWP::ERR_INVALID_OBJECT;
1330 }
1331
1332 // Okay, so it's an object, but is it actually a thread?
Elliott Hughes436e3722012-02-17 20:01:47 -08001333 if (DecodeThread(threadId) == NULL) {
Elliott Hughes2435a572012-02-17 16:07:41 -08001334 return JDWP::ERR_INVALID_THREAD;
1335 }
Elliott Hughes499c5132011-11-17 14:55:11 -08001336
1337 Class* c = Runtime::Current()->GetClassLinker()->FindSystemClass("Ljava/lang/Thread;");
1338 CHECK(c != NULL);
1339 Field* f = c->FindInstanceField("group", "Ljava/lang/ThreadGroup;");
1340 CHECK(f != NULL);
1341 Object* group = f->GetObject(thread);
1342 CHECK(group != NULL);
Elliott Hughes2435a572012-02-17 16:07:41 -08001343 JDWP::ObjectId thread_group_id = gRegistry->Add(group);
1344
1345 expandBufAddObjectId(pReply, thread_group_id);
1346 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001347}
1348
Elliott Hughes499c5132011-11-17 14:55:11 -08001349std::string Dbg::GetThreadGroupName(JDWP::ObjectId threadGroupId) {
1350 Object* thread_group = gRegistry->Get<Object*>(threadGroupId);
1351 CHECK(thread_group != NULL);
1352
1353 Class* c = Runtime::Current()->GetClassLinker()->FindSystemClass("Ljava/lang/ThreadGroup;");
1354 CHECK(c != NULL);
1355 Field* f = c->FindInstanceField("name", "Ljava/lang/String;");
1356 CHECK(f != NULL);
1357 String* s = reinterpret_cast<String*>(f->GetObject(thread_group));
1358 return s->ToModifiedUtf8();
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001359}
1360
1361JDWP::ObjectId Dbg::GetThreadGroupParent(JDWP::ObjectId threadGroupId) {
Elliott Hughes4e235312011-12-02 11:34:15 -08001362 Object* thread_group = gRegistry->Get<Object*>(threadGroupId);
1363 CHECK(thread_group != NULL);
1364
1365 Class* c = Runtime::Current()->GetClassLinker()->FindSystemClass("Ljava/lang/ThreadGroup;");
1366 CHECK(c != NULL);
1367 Field* f = c->FindInstanceField("parent", "Ljava/lang/ThreadGroup;");
1368 CHECK(f != NULL);
1369 Object* parent = f->GetObject(thread_group);
1370 return gRegistry->Add(parent);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001371}
1372
1373JDWP::ObjectId Dbg::GetSystemThreadGroupId() {
Ian Rogers365c1022012-06-22 15:05:28 -07001374 ScopedJniThreadState ts(Thread::Current());
1375 Object* group =
1376 ts.DecodeField(WellKnownClasses::java_lang_ThreadGroup_systemThreadGroup)->GetObject(NULL);
1377 return gRegistry->Add(group);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001378}
1379
1380JDWP::ObjectId Dbg::GetMainThreadGroupId() {
Ian Rogers365c1022012-06-22 15:05:28 -07001381 ScopedJniThreadState ts(Thread::Current());
1382 Object* group =
1383 ts.DecodeField(WellKnownClasses::java_lang_ThreadGroup_mainThreadGroup)->GetObject(NULL);
1384 return gRegistry->Add(group);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001385}
1386
Elliott Hughes3d30d9b2011-12-07 17:35:48 -08001387bool Dbg::GetThreadStatus(JDWP::ObjectId threadId, JDWP::JdwpThreadStatus* pThreadStatus, JDWP::JdwpSuspendStatus* pSuspendStatus) {
Elliott Hughes499c5132011-11-17 14:55:11 -08001388 ScopedThreadListLock thread_list_lock;
1389
1390 Thread* thread = DecodeThread(threadId);
1391 if (thread == NULL) {
1392 return false;
1393 }
1394
Elliott Hughes3ce4b262012-02-24 11:24:02 -08001395 // TODO: if we're in Thread.sleep(long), we should return TS_SLEEPING,
1396 // even if it's implemented using Object.wait(long).
Elliott Hughes499c5132011-11-17 14:55:11 -08001397 switch (thread->GetState()) {
Elliott Hughes34e06962012-04-09 13:55:55 -07001398 case kTerminated: *pThreadStatus = JDWP::TS_ZOMBIE; break;
1399 case kRunnable: *pThreadStatus = JDWP::TS_RUNNING; break;
1400 case kTimedWaiting: *pThreadStatus = JDWP::TS_WAIT; break;
1401 case kBlocked: *pThreadStatus = JDWP::TS_MONITOR; break;
1402 case kWaiting: *pThreadStatus = JDWP::TS_WAIT; break;
1403 case kStarting: *pThreadStatus = JDWP::TS_ZOMBIE; break;
1404 case kNative: *pThreadStatus = JDWP::TS_RUNNING; break;
1405 case kVmWait: *pThreadStatus = JDWP::TS_WAIT; break;
1406 case kSuspended: *pThreadStatus = JDWP::TS_RUNNING; break;
Elliott Hughescf2b2d42012-03-27 17:11:42 -07001407 // Don't add a 'default' here so the compiler can spot incompatible enum changes.
Elliott Hughes499c5132011-11-17 14:55:11 -08001408 }
1409
Elliott Hughes3d30d9b2011-12-07 17:35:48 -08001410 *pSuspendStatus = (thread->IsSuspended() ? JDWP::SUSPEND_STATUS_SUSPENDED : JDWP::SUSPEND_STATUS_NOT_SUSPENDED);
Elliott Hughes499c5132011-11-17 14:55:11 -08001411
1412 return true;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001413}
1414
Elliott Hughes2435a572012-02-17 16:07:41 -08001415JDWP::JdwpError Dbg::GetThreadSuspendCount(JDWP::ObjectId threadId, JDWP::ExpandBuf* pReply) {
1416 Thread* thread = DecodeThread(threadId);
1417 if (thread == NULL) {
1418 return JDWP::ERR_INVALID_THREAD;
1419 }
1420 expandBufAdd4BE(pReply, thread->GetSuspendCount());
1421 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001422}
1423
1424bool Dbg::ThreadExists(JDWP::ObjectId threadId) {
Elliott Hughes761928d2011-11-16 18:33:03 -08001425 return DecodeThread(threadId) != NULL;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001426}
1427
1428bool Dbg::IsSuspended(JDWP::ObjectId threadId) {
Elliott Hughes761928d2011-11-16 18:33:03 -08001429 return DecodeThread(threadId)->IsSuspended();
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001430}
1431
Elliott Hughescaf76542012-06-28 16:08:22 -07001432void Dbg::GetThreads(JDWP::ObjectId thread_group_id, std::vector<JDWP::ObjectId>& thread_ids) {
Ian Rogers365c1022012-06-22 15:05:28 -07001433 class ThreadListVisitor {
1434 public:
Elliott Hughescaf76542012-06-28 16:08:22 -07001435 ThreadListVisitor(const ScopedJniThreadState& ts, Object* thread_group, std::vector<JDWP::ObjectId>& thread_ids)
1436 : ts_(ts), thread_group_(thread_group), thread_ids_(thread_ids) {}
Ian Rogers365c1022012-06-22 15:05:28 -07001437
Elliott Hughesa2155262011-11-16 16:26:58 -08001438 static void Visit(Thread* t, void* arg) {
1439 reinterpret_cast<ThreadListVisitor*>(arg)->Visit(t);
1440 }
1441
1442 void Visit(Thread* t) {
1443 if (t == Dbg::GetDebugThread()) {
1444 // Skip the JDWP thread. Some debuggers get bent out of shape when they can't suspend and
1445 // query all threads, so it's easier if we just don't tell them about this thread.
1446 return;
1447 }
Ian Rogers365c1022012-06-22 15:05:28 -07001448 if (thread_group_ == NULL || t->GetThreadGroup(ts_) == thread_group_) {
Elliott Hughescaf76542012-06-28 16:08:22 -07001449 thread_ids_.push_back(gRegistry->Add(t->GetPeer()));
Elliott Hughesa2155262011-11-16 16:26:58 -08001450 }
1451 }
1452
Ian Rogers365c1022012-06-22 15:05:28 -07001453 private:
1454 const ScopedJniThreadState& ts_;
1455 Object* const thread_group_;
Elliott Hughescaf76542012-06-28 16:08:22 -07001456 std::vector<JDWP::ObjectId>& thread_ids_;
Elliott Hughesa2155262011-11-16 16:26:58 -08001457 };
1458
Ian Rogers365c1022012-06-22 15:05:28 -07001459 ScopedJniThreadState ts(Thread::Current());
Elliott Hughescaf76542012-06-28 16:08:22 -07001460 Object* thread_group = gRegistry->Get<Object*>(thread_group_id);
1461 ThreadListVisitor tlv(ts, thread_group, thread_ids);
Elliott Hughesf8349362012-06-18 15:00:06 -07001462 Runtime::Current()->GetThreadList()->ForEach(ThreadListVisitor::Visit, &tlv);
Elliott Hughescaf76542012-06-28 16:08:22 -07001463}
Elliott Hughesa2155262011-11-16 16:26:58 -08001464
Elliott Hughescaf76542012-06-28 16:08:22 -07001465void Dbg::GetChildThreadGroups(JDWP::ObjectId thread_group_id, std::vector<JDWP::ObjectId>& child_thread_group_ids) {
1466 ScopedJniThreadState ts(Thread::Current());
1467 Object* thread_group = gRegistry->Get<Object*>(thread_group_id);
1468
1469 // Get the ArrayList<ThreadGroup> "groups" out of this thread group...
1470 Field* groups_field = thread_group->GetClass()->FindInstanceField("groups", "Ljava/util/List;");
1471 Object* groups_array_list = groups_field->GetObject(thread_group);
1472
1473 // Get the array and size out of the ArrayList<ThreadGroup>...
1474 Field* array_field = groups_array_list->GetClass()->FindInstanceField("array", "[Ljava/lang/Object;");
1475 Field* size_field = groups_array_list->GetClass()->FindInstanceField("size", "I");
1476 ObjectArray<Object>* groups_array = array_field->GetObject(groups_array_list)->AsObjectArray<Object>();
1477 const int32_t size = size_field->GetInt(groups_array_list);
1478
1479 // Copy the first 'size' elements out of the array into the result.
1480 for (int32_t i = 0; i < size; ++i) {
1481 child_thread_group_ids.push_back(gRegistry->Add(groups_array->Get(i)));
Elliott Hughesa2155262011-11-16 16:26:58 -08001482 }
1483}
1484
Elliott Hughes86964332012-02-15 19:37:42 -08001485static int GetStackDepth(Thread* thread) {
Ian Rogers0399dde2012-06-06 17:09:28 -07001486 struct CountStackDepthVisitor : public StackVisitor {
1487 CountStackDepthVisitor(const ManagedStack* stack,
Ian Rogersca190662012-06-26 15:45:57 -07001488 const std::vector<TraceStackFrame>* trace_stack)
Elliott Hughes08fc03a2012-06-26 17:34:00 -07001489 : StackVisitor(stack, trace_stack, NULL), depth(0) {}
Ian Rogers0399dde2012-06-06 17:09:28 -07001490
1491 bool VisitFrame() {
1492 if (!GetMethod()->IsRuntimeMethod()) {
Elliott Hughesf8a2df72011-12-01 12:19:54 -08001493 ++depth;
1494 }
Elliott Hughes530fa002012-03-12 11:44:49 -07001495 return true;
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001496 }
1497 size_t depth;
1498 };
Elliott Hughes08fc03a2012-06-26 17:34:00 -07001499
Ian Rogers0399dde2012-06-06 17:09:28 -07001500 CountStackDepthVisitor visitor(thread->GetManagedStack(), thread->GetTraceStack());
1501 visitor.WalkStack();
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001502 return visitor.depth;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001503}
1504
Elliott Hughes86964332012-02-15 19:37:42 -08001505int Dbg::GetThreadFrameCount(JDWP::ObjectId threadId) {
1506 ScopedThreadListLock thread_list_lock;
1507 return GetStackDepth(DecodeThread(threadId));
1508}
1509
Elliott Hughes6e9d22c2012-06-22 15:02:37 -07001510JDWP::JdwpError Dbg::GetThreadFrames(JDWP::ObjectId thread_id, size_t start_frame, size_t frame_count, JDWP::ExpandBuf* buf) {
Elliott Hughes03181a82011-11-17 17:22:21 -08001511 ScopedThreadListLock thread_list_lock;
Elliott Hughes6e9d22c2012-06-22 15:02:37 -07001512 class GetFrameVisitor : public StackVisitor {
1513 public:
Ian Rogers0399dde2012-06-06 17:09:28 -07001514 GetFrameVisitor(const ManagedStack* stack, const std::vector<TraceStackFrame>* trace_stack,
Elliott Hughes6e9d22c2012-06-22 15:02:37 -07001515 size_t start_frame, size_t frame_count, JDWP::ExpandBuf* buf)
Elliott Hughes08fc03a2012-06-26 17:34:00 -07001516 : StackVisitor(stack, trace_stack, NULL), depth_(0),
Elliott Hughes6e9d22c2012-06-22 15:02:37 -07001517 start_frame_(start_frame), frame_count_(frame_count), buf_(buf) {
1518 expandBufAdd4BE(buf_, frame_count_);
Elliott Hughes03181a82011-11-17 17:22:21 -08001519 }
Ian Rogers0399dde2012-06-06 17:09:28 -07001520
1521 bool VisitFrame() {
1522 if (GetMethod()->IsRuntimeMethod()) {
Elliott Hughes530fa002012-03-12 11:44:49 -07001523 return true; // The debugger can't do anything useful with a frame that has no Method*.
Elliott Hughes03181a82011-11-17 17:22:21 -08001524 }
Elliott Hughes6e9d22c2012-06-22 15:02:37 -07001525 if (depth_ >= start_frame_ + frame_count_) {
Elliott Hughes530fa002012-03-12 11:44:49 -07001526 return false;
Elliott Hughes03181a82011-11-17 17:22:21 -08001527 }
Elliott Hughes6e9d22c2012-06-22 15:02:37 -07001528 if (depth_ >= start_frame_) {
1529 JDWP::FrameId frame_id(GetFrameId());
1530 JDWP::JdwpLocation location;
1531 SetLocation(location, GetMethod(), GetDexPc());
Elliott Hughes7baf96f2012-06-22 16:33:50 -07001532 VLOG(jdwp) << StringPrintf(" Frame %3zd: id=%3lld ", depth_, frame_id) << location;
Elliott Hughes6e9d22c2012-06-22 15:02:37 -07001533 expandBufAdd8BE(buf_, frame_id);
1534 expandBufAddLocation(buf_, location);
1535 }
1536 ++depth_;
Elliott Hughes530fa002012-03-12 11:44:49 -07001537 return true;
Elliott Hughes03181a82011-11-17 17:22:21 -08001538 }
Elliott Hughes6e9d22c2012-06-22 15:02:37 -07001539
1540 private:
1541 size_t depth_;
1542 const size_t start_frame_;
1543 const size_t frame_count_;
1544 JDWP::ExpandBuf* buf_;
Elliott Hughes03181a82011-11-17 17:22:21 -08001545 };
Elliott Hughes6e9d22c2012-06-22 15:02:37 -07001546 Thread* thread = DecodeThread(thread_id);
1547 GetFrameVisitor visitor(thread->GetManagedStack(), thread->GetTraceStack(), start_frame, frame_count, buf);
Ian Rogers0399dde2012-06-06 17:09:28 -07001548 visitor.WalkStack();
Elliott Hughes6e9d22c2012-06-22 15:02:37 -07001549 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001550}
1551
1552JDWP::ObjectId Dbg::GetThreadSelfId() {
Elliott Hughes475fc232011-10-25 15:00:35 -07001553 return gRegistry->Add(Thread::Current()->GetPeer());
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001554}
1555
Elliott Hughes475fc232011-10-25 15:00:35 -07001556void Dbg::SuspendVM() {
Elliott Hughes34e06962012-04-09 13:55:55 -07001557 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 -07001558 Runtime::Current()->GetThreadList()->SuspendAll(true);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001559}
1560
1561void Dbg::ResumeVM() {
Elliott Hughesc61a2672012-06-21 14:52:29 -07001562 Runtime::Current()->GetThreadList()->UndoDebuggerSuspensions();
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001563}
1564
1565void Dbg::SuspendThread(JDWP::ObjectId threadId) {
Ian Rogers365c1022012-06-22 15:05:28 -07001566 ScopedJniThreadState ts(Thread::Current());
Elliott Hughes4e235312011-12-02 11:34:15 -08001567 Object* peer = gRegistry->Get<Object*>(threadId);
1568 ScopedThreadListLock thread_list_lock;
Ian Rogers365c1022012-06-22 15:05:28 -07001569 Thread* thread = Thread::FromManagedThread(ts, peer);
Elliott Hughes4e235312011-12-02 11:34:15 -08001570 if (thread == NULL) {
1571 LOG(WARNING) << "No such thread for suspend: " << peer;
1572 return;
1573 }
1574 Runtime::Current()->GetThreadList()->Suspend(thread, true);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001575}
1576
1577void Dbg::ResumeThread(JDWP::ObjectId threadId) {
Ian Rogers365c1022012-06-22 15:05:28 -07001578 ScopedJniThreadState ts(Thread::Current());
Elliott Hughes4e235312011-12-02 11:34:15 -08001579 Object* peer = gRegistry->Get<Object*>(threadId);
1580 ScopedThreadListLock thread_list_lock;
Ian Rogers365c1022012-06-22 15:05:28 -07001581 Thread* thread = Thread::FromManagedThread(ts, peer);
Elliott Hughes4e235312011-12-02 11:34:15 -08001582 if (thread == NULL) {
1583 LOG(WARNING) << "No such thread for resume: " << peer;
1584 return;
1585 }
Elliott Hughes546b9862012-06-20 16:06:13 -07001586 if (thread->GetSuspendCount() > 0) {
1587 Runtime::Current()->GetThreadList()->Resume(thread, true);
1588 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001589}
1590
1591void Dbg::SuspendSelf() {
Elliott Hughes475fc232011-10-25 15:00:35 -07001592 Runtime::Current()->GetThreadList()->SuspendSelfForDebugger();
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001593}
1594
Ian Rogers0399dde2012-06-06 17:09:28 -07001595struct GetThisVisitor : public StackVisitor {
1596 GetThisVisitor(const ManagedStack* stack, const std::vector<TraceStackFrame>* trace_stack,
Elliott Hughes6e9d22c2012-06-22 15:02:37 -07001597 Context* context, JDWP::FrameId frameId)
1598 : StackVisitor(stack, trace_stack, context), this_object(NULL), frame_id(frameId) {}
Ian Rogers0399dde2012-06-06 17:09:28 -07001599
1600 virtual bool VisitFrame() {
Elliott Hughes6e9d22c2012-06-22 15:02:37 -07001601 if (frame_id != GetFrameId()) {
Ian Rogers0399dde2012-06-06 17:09:28 -07001602 return true; // continue
1603 }
1604 Method* m = GetMethod();
1605 if (m->IsNative() || m->IsStatic()) {
Elliott Hughes6e9d22c2012-06-22 15:02:37 -07001606 this_object = NULL;
Ian Rogers0399dde2012-06-06 17:09:28 -07001607 } else {
1608 uint16_t reg = DemangleSlot(0, m);
Elliott Hughes6e9d22c2012-06-22 15:02:37 -07001609 this_object = reinterpret_cast<Object*>(GetVReg(m, reg));
Ian Rogers0399dde2012-06-06 17:09:28 -07001610 }
1611 return false;
Elliott Hughes86b00102011-12-05 17:54:26 -08001612 }
Ian Rogers0399dde2012-06-06 17:09:28 -07001613
Elliott Hughes6e9d22c2012-06-22 15:02:37 -07001614 Object* this_object;
1615 JDWP::FrameId frame_id;
Ian Rogers0399dde2012-06-06 17:09:28 -07001616};
1617
Elliott Hughescaf76542012-06-28 16:08:22 -07001618static Object* GetThis(Thread* self, Method* m, size_t frame_id) {
1619 // TODO: should we return the 'this' we passed through to non-static native methods?
Ian Rogers0399dde2012-06-06 17:09:28 -07001620 if (m->IsNative() || m->IsStatic()) {
1621 return NULL;
1622 }
Elliott Hughescaf76542012-06-28 16:08:22 -07001623
Ian Rogers0399dde2012-06-06 17:09:28 -07001624 UniquePtr<Context> context(Context::Create());
Elliott Hughescaf76542012-06-28 16:08:22 -07001625 GetThisVisitor visitor(self->GetManagedStack(), self->GetTraceStack(), context.get(), frame_id);
1626 visitor.WalkStack();
1627 return visitor.this_object;
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08001628}
1629
Elliott Hughes6e9d22c2012-06-22 15:02:37 -07001630JDWP::JdwpError Dbg::GetThisObject(JDWP::ObjectId thread_id, JDWP::FrameId frame_id, JDWP::ObjectId* result) {
Elliott Hughes6e9d22c2012-06-22 15:02:37 -07001631 Thread* thread = DecodeThread(thread_id);
1632 if (thread == NULL) {
1633 return JDWP::ERR_INVALID_THREAD;
1634 }
Elliott Hughescaf76542012-06-28 16:08:22 -07001635
1636 UniquePtr<Context> context(Context::Create());
Elliott Hughes6e9d22c2012-06-22 15:02:37 -07001637 GetThisVisitor visitor(thread->GetManagedStack(), thread->GetTraceStack(), context.get(), frame_id);
Ian Rogers0399dde2012-06-06 17:09:28 -07001638 visitor.WalkStack();
Elliott Hughes6e9d22c2012-06-22 15:02:37 -07001639 *result = gRegistry->Add(visitor.this_object);
1640 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001641}
1642
Elliott Hughes6e9d22c2012-06-22 15:02:37 -07001643void Dbg::GetLocalValue(JDWP::ObjectId threadId, JDWP::FrameId frameId, int slot, JDWP::JdwpTag tag, uint8_t* buf, size_t width) {
Ian Rogers0399dde2012-06-06 17:09:28 -07001644 struct GetLocalVisitor : public StackVisitor {
1645 GetLocalVisitor(const ManagedStack* stack, const std::vector<TraceStackFrame>* trace_stack,
1646 Context* context, JDWP::FrameId frameId, int slot, JDWP::JdwpTag tag,
Ian Rogersca190662012-06-26 15:45:57 -07001647 uint8_t* buf, size_t width)
1648 : StackVisitor(stack, trace_stack, context), frame_id_(frameId), slot_(slot), tag_(tag),
1649 buf_(buf), width_(width) {}
1650
Ian Rogers0399dde2012-06-06 17:09:28 -07001651 bool VisitFrame() {
1652 if (GetFrameId() != frame_id_) {
1653 return true; // Not our frame, carry on.
Elliott Hughesdbb40792011-11-18 17:05:22 -08001654 }
Ian Rogers0399dde2012-06-06 17:09:28 -07001655 // TODO: check that the tag is compatible with the actual type of the slot!
1656 Method* m = GetMethod();
1657 uint16_t reg = DemangleSlot(slot_, m);
Elliott Hughesdbb40792011-11-18 17:05:22 -08001658
Ian Rogers0399dde2012-06-06 17:09:28 -07001659 switch (tag_) {
1660 case JDWP::JT_BOOLEAN:
1661 {
1662 CHECK_EQ(width_, 1U);
1663 uint32_t intVal = GetVReg(m, reg);
1664 VLOG(jdwp) << "get boolean local " << reg << " = " << intVal;
1665 JDWP::Set1(buf_+1, intVal != 0);
1666 }
1667 break;
1668 case JDWP::JT_BYTE:
1669 {
1670 CHECK_EQ(width_, 1U);
1671 uint32_t intVal = GetVReg(m, reg);
1672 VLOG(jdwp) << "get byte local " << reg << " = " << intVal;
1673 JDWP::Set1(buf_+1, intVal);
1674 }
1675 break;
1676 case JDWP::JT_SHORT:
1677 case JDWP::JT_CHAR:
1678 {
1679 CHECK_EQ(width_, 2U);
1680 uint32_t intVal = GetVReg(m, reg);
1681 VLOG(jdwp) << "get short/char local " << reg << " = " << intVal;
1682 JDWP::Set2BE(buf_+1, intVal);
1683 }
1684 break;
1685 case JDWP::JT_INT:
1686 case JDWP::JT_FLOAT:
1687 {
1688 CHECK_EQ(width_, 4U);
1689 uint32_t intVal = GetVReg(m, reg);
1690 VLOG(jdwp) << "get int/float local " << reg << " = " << intVal;
1691 JDWP::Set4BE(buf_+1, intVal);
1692 }
1693 break;
1694 case JDWP::JT_ARRAY:
1695 {
1696 CHECK_EQ(width_, sizeof(JDWP::ObjectId));
1697 Object* o = reinterpret_cast<Object*>(GetVReg(m, reg));
1698 VLOG(jdwp) << "get array local " << reg << " = " << o;
1699 if (!Runtime::Current()->GetHeap()->IsHeapAddress(o)) {
1700 LOG(FATAL) << "Register " << reg << " expected to hold array: " << o;
1701 }
1702 JDWP::SetObjectId(buf_+1, gRegistry->Add(o));
1703 }
1704 break;
1705 case JDWP::JT_CLASS_LOADER:
1706 case JDWP::JT_CLASS_OBJECT:
1707 case JDWP::JT_OBJECT:
1708 case JDWP::JT_STRING:
1709 case JDWP::JT_THREAD:
1710 case JDWP::JT_THREAD_GROUP:
1711 {
1712 CHECK_EQ(width_, sizeof(JDWP::ObjectId));
1713 Object* o = reinterpret_cast<Object*>(GetVReg(m, reg));
1714 VLOG(jdwp) << "get object local " << reg << " = " << o;
1715 if (!Runtime::Current()->GetHeap()->IsHeapAddress(o)) {
1716 LOG(FATAL) << "Register " << reg << " expected to hold object: " << o;
1717 }
1718 tag_ = TagFromObject(o);
1719 JDWP::SetObjectId(buf_+1, gRegistry->Add(o));
1720 }
1721 break;
1722 case JDWP::JT_DOUBLE:
1723 case JDWP::JT_LONG:
1724 {
1725 CHECK_EQ(width_, 8U);
1726 uint32_t lo = GetVReg(m, reg);
1727 uint64_t hi = GetVReg(m, reg + 1);
1728 uint64_t longVal = (hi << 32) | lo;
1729 VLOG(jdwp) << "get double/long local " << hi << ":" << lo << " = " << longVal;
1730 JDWP::Set8BE(buf_+1, longVal);
1731 }
1732 break;
1733 default:
1734 LOG(FATAL) << "Unknown tag " << tag_;
1735 break;
1736 }
1737
1738 // Prepend tag, which may have been updated.
1739 JDWP::Set1(buf_, tag_);
1740 return false;
1741 }
1742
1743 const JDWP::FrameId frame_id_;
1744 const int slot_;
1745 JDWP::JdwpTag tag_;
1746 uint8_t* const buf_;
1747 const size_t width_;
1748 };
1749 Thread* thread = DecodeThread(threadId);
1750 UniquePtr<Context> context(Context::Create());
1751 GetLocalVisitor visitor(thread->GetManagedStack(), thread->GetTraceStack(), context.get(),
1752 frameId, slot, tag, buf, width);
1753 visitor.WalkStack();
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001754}
1755
Ian Rogers0399dde2012-06-06 17:09:28 -07001756void Dbg::SetLocalValue(JDWP::ObjectId threadId, JDWP::FrameId frameId, int slot, JDWP::JdwpTag tag,
1757 uint64_t value, size_t width) {
1758 struct SetLocalVisitor : public StackVisitor {
Elliott Hughes08fc03a2012-06-26 17:34:00 -07001759 SetLocalVisitor(const ManagedStack* stack, const std::vector<TraceStackFrame>* trace_stack, Context* context,
Ian Rogers0399dde2012-06-06 17:09:28 -07001760 JDWP::FrameId frame_id, int slot, JDWP::JdwpTag tag, uint64_t value,
Ian Rogersca190662012-06-26 15:45:57 -07001761 size_t width)
Elliott Hughes08fc03a2012-06-26 17:34:00 -07001762 : StackVisitor(stack, trace_stack, context),
1763 frame_id_(frame_id), slot_(slot), tag_(tag), value_(value), width_(width) {}
Ian Rogersca190662012-06-26 15:45:57 -07001764
Ian Rogers0399dde2012-06-06 17:09:28 -07001765 bool VisitFrame() {
1766 if (GetFrameId() != frame_id_) {
1767 return true; // Not our frame, carry on.
1768 }
1769 // TODO: check that the tag is compatible with the actual type of the slot!
1770 Method* m = GetMethod();
1771 uint16_t reg = DemangleSlot(slot_, m);
1772
1773 switch (tag_) {
1774 case JDWP::JT_BOOLEAN:
1775 case JDWP::JT_BYTE:
1776 CHECK_EQ(width_, 1U);
1777 SetVReg(m, reg, static_cast<uint32_t>(value_));
1778 break;
1779 case JDWP::JT_SHORT:
1780 case JDWP::JT_CHAR:
1781 CHECK_EQ(width_, 2U);
1782 SetVReg(m, reg, static_cast<uint32_t>(value_));
1783 break;
1784 case JDWP::JT_INT:
1785 case JDWP::JT_FLOAT:
1786 CHECK_EQ(width_, 4U);
1787 SetVReg(m, reg, static_cast<uint32_t>(value_));
1788 break;
1789 case JDWP::JT_ARRAY:
1790 case JDWP::JT_OBJECT:
1791 case JDWP::JT_STRING:
1792 {
1793 CHECK_EQ(width_, sizeof(JDWP::ObjectId));
1794 Object* o = gRegistry->Get<Object*>(static_cast<JDWP::ObjectId>(value_));
1795 if (o == kInvalidObject) {
1796 UNIMPLEMENTED(FATAL) << "return an error code when given an invalid object to store";
1797 }
1798 SetVReg(m, reg, static_cast<uint32_t>(reinterpret_cast<uintptr_t>(o)));
1799 }
1800 break;
1801 case JDWP::JT_DOUBLE:
1802 case JDWP::JT_LONG:
1803 CHECK_EQ(width_, 8U);
1804 SetVReg(m, reg, static_cast<uint32_t>(value_));
1805 SetVReg(m, reg + 1, static_cast<uint32_t>(value_ >> 32));
1806 break;
1807 default:
1808 LOG(FATAL) << "Unknown tag " << tag_;
1809 break;
1810 }
1811 return false;
1812 }
1813
1814 const JDWP::FrameId frame_id_;
1815 const int slot_;
1816 const JDWP::JdwpTag tag_;
1817 const uint64_t value_;
1818 const size_t width_;
1819 };
1820 Thread* thread = DecodeThread(threadId);
Elliott Hughes08fc03a2012-06-26 17:34:00 -07001821 UniquePtr<Context> context(Context::Create());
1822 SetLocalVisitor visitor(thread->GetManagedStack(), thread->GetTraceStack(), context.get(),
1823 frameId, slot, tag, value, width);
Ian Rogers0399dde2012-06-06 17:09:28 -07001824 visitor.WalkStack();
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001825}
1826
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08001827void Dbg::PostLocationEvent(const Method* m, int dex_pc, Object* this_object, int event_flags) {
1828 Class* c = m->GetDeclaringClass();
1829
1830 JDWP::JdwpLocation location;
Elliott Hughes74847412012-06-20 18:10:21 -07001831 location.type_tag = c->IsInterface() ? JDWP::TT_INTERFACE : JDWP::TT_CLASS;
1832 location.class_id = gRegistry->Add(c);
1833 location.method_id = ToMethodId(m);
Elliott Hughes972a47b2012-02-21 18:16:06 -08001834 location.dex_pc = m->IsNative() ? -1 : dex_pc;
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08001835
1836 // Note we use "NoReg" so we don't keep track of references that are
1837 // never actually sent to the debugger. 'this_id' is only used to
1838 // compare against registered events...
1839 JDWP::ObjectId this_id = static_cast<JDWP::ObjectId>(reinterpret_cast<uintptr_t>(this_object));
1840 if (gJdwpState->PostLocationEvent(&location, this_id, event_flags)) {
1841 // ...unless there's a registered event, in which case we
1842 // need to really track the class and 'this'.
1843 gRegistry->Add(c);
1844 gRegistry->Add(this_object);
1845 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001846}
1847
Elliott Hughescaf76542012-06-28 16:08:22 -07001848void Dbg::PostException(Thread* thread,
1849 JDWP::FrameId throw_frame_id, Method* throw_method, uint32_t throw_dex_pc,
1850 Method* catch_method, uint32_t catch_dex_pc, Throwable* exception) {
Elliott Hughesc0f09332012-03-26 13:27:06 -07001851 if (!IsDebuggerActive()) {
Ian Rogers0ad5bb82011-12-07 10:16:32 -08001852 return;
1853 }
Elliott Hughes4740cdf2011-12-07 14:07:12 -08001854
Elliott Hughesd07986f2011-12-06 18:27:45 -08001855 JDWP::JdwpLocation throw_location;
Elliott Hughescaf76542012-06-28 16:08:22 -07001856 SetLocation(throw_location, throw_method, throw_dex_pc);
Elliott Hughesd07986f2011-12-06 18:27:45 -08001857 JDWP::JdwpLocation catch_location;
Elliott Hughescaf76542012-06-28 16:08:22 -07001858 SetLocation(catch_location, catch_method, catch_dex_pc);
Elliott Hughesd07986f2011-12-06 18:27:45 -08001859
1860 // We need 'this' for InstanceOnly filters.
Elliott Hughescaf76542012-06-28 16:08:22 -07001861 UniquePtr<Context> context(Context::Create());
1862 GetThisVisitor visitor(thread->GetManagedStack(), thread->GetTraceStack(), context.get(), throw_frame_id);
1863 visitor.WalkStack();
1864 JDWP::ObjectId this_id = gRegistry->Add(visitor.this_object);
Elliott Hughesd07986f2011-12-06 18:27:45 -08001865
1866 /*
1867 * Hand the event to the JDWP exception handler. Note we're using the
1868 * "NoReg" objectID on the exception, which is not strictly correct --
1869 * the exception object WILL be passed up to the debugger if the
1870 * debugger is interested in the event. We do this because the current
1871 * implementation of the debugger object registry never throws anything
1872 * away, and some people were experiencing a fatal build up of exception
1873 * objects when dealing with certain libraries.
1874 */
1875 JDWP::ObjectId exception_id = static_cast<JDWP::ObjectId>(reinterpret_cast<uintptr_t>(exception));
1876 JDWP::RefTypeId exception_class_id = gRegistry->Add(exception->GetClass());
1877
1878 gJdwpState->PostException(&throw_location, exception_id, exception_class_id, &catch_location, this_id);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001879}
1880
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001881void Dbg::PostClassPrepare(Class* c) {
Elliott Hughesc0f09332012-03-26 13:27:06 -07001882 if (!IsDebuggerActive()) {
Elliott Hughes4740cdf2011-12-07 14:07:12 -08001883 return;
1884 }
1885
Elliott Hughes3d30d9b2011-12-07 17:35:48 -08001886 // OLD-TODO - we currently always send both "verified" and "prepared" since
Elliott Hughes4740cdf2011-12-07 14:07:12 -08001887 // debuggers seem to like that. There might be some advantage to honesty,
1888 // since the class may not yet be verified.
1889 int state = JDWP::CS_VERIFIED | JDWP::CS_PREPARED;
1890 JDWP::JdwpTypeTag tag = c->IsInterface() ? JDWP::TT_INTERFACE : JDWP::TT_CLASS;
1891 gJdwpState->PostClassPrepare(tag, gRegistry->Add(c), ClassHelper(c).GetDescriptor(), state);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001892}
1893
Elliott Hughescaf76542012-06-28 16:08:22 -07001894void Dbg::UpdateDebugger(int32_t dex_pc, Thread* self) {
Elliott Hughesc0f09332012-03-26 13:27:06 -07001895 if (!IsDebuggerActive() || dex_pc == -2 /* fake method exit */) {
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08001896 return;
1897 }
1898
Elliott Hughescaf76542012-06-28 16:08:22 -07001899 size_t frame_id;
1900 Method* m = self->GetCurrentMethod(NULL, &frame_id);
1901 //LOG(INFO) << "UpdateDebugger " << PrettyMethod(m) << "@" << dex_pc << " frame " << frame_id;
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08001902
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08001903 if (dex_pc == -1) {
Elliott Hughes2aa2e392012-02-17 17:15:43 -08001904 // We use a pc of -1 to represent method entry, since we might branch back to pc 0 later.
1905 // This means that for this special notification, there can't be anything else interesting
1906 // going on, so we're done already.
Elliott Hughescaf76542012-06-28 16:08:22 -07001907 Dbg::PostLocationEvent(m, 0, GetThis(self, m, frame_id), kMethodEntry);
Elliott Hughes2aa2e392012-02-17 17:15:43 -08001908 return;
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08001909 }
1910
Elliott Hughes2aa2e392012-02-17 17:15:43 -08001911 int event_flags = 0;
1912
Elliott Hughes86964332012-02-15 19:37:42 -08001913 if (IsBreakpoint(m, dex_pc)) {
1914 event_flags |= kBreakpoint;
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08001915 }
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08001916
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08001917 // If the debugger is single-stepping one of our threads, check to
1918 // see if we're that thread and we've reached a step point.
Elliott Hughesf8349362012-06-18 15:00:06 -07001919 MutexLock mu(gBreakpointsLock);
Elliott Hughes86964332012-02-15 19:37:42 -08001920 if (gSingleStepControl.is_active && gSingleStepControl.thread == self) {
1921 CHECK(!m->IsNative());
1922 if (gSingleStepControl.step_depth == JDWP::SD_INTO) {
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08001923 // Step into method calls. We break when the line number
1924 // or method pointer changes. If we're in SS_MIN mode, we
1925 // always stop.
Elliott Hughes86964332012-02-15 19:37:42 -08001926 if (gSingleStepControl.method != m) {
1927 event_flags |= kSingleStep;
1928 VLOG(jdwp) << "SS new method";
1929 } else if (gSingleStepControl.step_size == JDWP::SS_MIN) {
1930 event_flags |= kSingleStep;
1931 VLOG(jdwp) << "SS new instruction";
Elliott Hughes2435a572012-02-17 16:07:41 -08001932 } else if (gSingleStepControl.dex_pcs.find(dex_pc) == gSingleStepControl.dex_pcs.end()) {
1933 event_flags |= kSingleStep;
1934 VLOG(jdwp) << "SS new line";
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08001935 }
Elliott Hughes86964332012-02-15 19:37:42 -08001936 } else if (gSingleStepControl.step_depth == JDWP::SD_OVER) {
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08001937 // Step over method calls. We break when the line number is
1938 // different and the frame depth is <= the original frame
1939 // depth. (We can't just compare on the method, because we
1940 // might get unrolled past it by an exception, and it's tricky
1941 // to identify recursion.)
Elliott Hughes86964332012-02-15 19:37:42 -08001942
1943 // TODO: can we just use the value of 'sp'?
1944 int stack_depth = GetStackDepth(self);
1945
1946 if (stack_depth < gSingleStepControl.stack_depth) {
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08001947 // popped up one or more frames, always trigger
Elliott Hughes86964332012-02-15 19:37:42 -08001948 event_flags |= kSingleStep;
1949 VLOG(jdwp) << "SS method pop";
1950 } else if (stack_depth == gSingleStepControl.stack_depth) {
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08001951 // same depth, see if we moved
Elliott Hughes86964332012-02-15 19:37:42 -08001952 if (gSingleStepControl.step_size == JDWP::SS_MIN) {
1953 event_flags |= kSingleStep;
1954 VLOG(jdwp) << "SS new instruction";
Elliott Hughes2435a572012-02-17 16:07:41 -08001955 } else if (gSingleStepControl.dex_pcs.find(dex_pc) == gSingleStepControl.dex_pcs.end()) {
1956 event_flags |= kSingleStep;
1957 VLOG(jdwp) << "SS new line";
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08001958 }
1959 }
1960 } else {
Elliott Hughes86964332012-02-15 19:37:42 -08001961 CHECK_EQ(gSingleStepControl.step_depth, JDWP::SD_OUT);
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08001962 // Return from the current method. We break when the frame
1963 // depth pops up.
1964
1965 // This differs from the "method exit" break in that it stops
1966 // with the PC at the next instruction in the returned-to
1967 // function, rather than the end of the returning function.
Elliott Hughes86964332012-02-15 19:37:42 -08001968
1969 // TODO: can we just use the value of 'sp'?
1970 int stack_depth = GetStackDepth(self);
1971 if (stack_depth < gSingleStepControl.stack_depth) {
1972 event_flags |= kSingleStep;
1973 VLOG(jdwp) << "SS method pop";
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08001974 }
1975 }
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08001976 }
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08001977
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08001978 // Check to see if this is a "return" instruction. JDWP says we should
1979 // send the event *after* the code has been executed, but it also says
1980 // the location we provide is the last instruction. Since the "return"
1981 // instruction has no interesting side effects, we should be safe.
1982 // (We can't just move this down to the returnFromMethod label because
1983 // we potentially need to combine it with other events.)
1984 // We're also not supposed to generate a method exit event if the method
1985 // terminates "with a thrown exception".
Elliott Hughes86964332012-02-15 19:37:42 -08001986 if (dex_pc >= 0) {
1987 const DexFile::CodeItem* code_item = MethodHelper(m).GetCodeItem();
Elliott Hughescaf76542012-06-28 16:08:22 -07001988 CHECK(code_item != NULL) << PrettyMethod(m) << " @" << dex_pc;
Elliott Hughes86964332012-02-15 19:37:42 -08001989 CHECK_LT(dex_pc, static_cast<int32_t>(code_item->insns_size_in_code_units_));
1990 if (Instruction::At(&code_item->insns_[dex_pc])->IsReturn()) {
1991 event_flags |= kMethodExit;
1992 }
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08001993 }
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08001994
1995 // If there's something interesting going on, see if it matches one
1996 // of the debugger filters.
1997 if (event_flags != 0) {
Elliott Hughescaf76542012-06-28 16:08:22 -07001998 Dbg::PostLocationEvent(m, dex_pc, GetThis(self, m, frame_id), event_flags);
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08001999 }
2000}
2001
Elliott Hughes86964332012-02-15 19:37:42 -08002002void Dbg::WatchLocation(const JDWP::JdwpLocation* location) {
2003 MutexLock mu(gBreakpointsLock);
Elliott Hughes74847412012-06-20 18:10:21 -07002004 Method* m = FromMethodId(location->method_id);
Elliott Hughes972a47b2012-02-21 18:16:06 -08002005 gBreakpoints.push_back(Breakpoint(m, location->dex_pc));
Elliott Hughes86964332012-02-15 19:37:42 -08002006 VLOG(jdwp) << "Set breakpoint #" << (gBreakpoints.size() - 1) << ": " << gBreakpoints[gBreakpoints.size() - 1];
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002007}
2008
Elliott Hughes86964332012-02-15 19:37:42 -08002009void Dbg::UnwatchLocation(const JDWP::JdwpLocation* location) {
2010 MutexLock mu(gBreakpointsLock);
Elliott Hughes74847412012-06-20 18:10:21 -07002011 Method* m = FromMethodId(location->method_id);
Elliott Hughes86964332012-02-15 19:37:42 -08002012 for (size_t i = 0; i < gBreakpoints.size(); ++i) {
Elliott Hughes972a47b2012-02-21 18:16:06 -08002013 if (gBreakpoints[i].method == m && gBreakpoints[i].dex_pc == location->dex_pc) {
Elliott Hughes86964332012-02-15 19:37:42 -08002014 VLOG(jdwp) << "Removed breakpoint #" << i << ": " << gBreakpoints[i];
2015 gBreakpoints.erase(gBreakpoints.begin() + i);
2016 return;
2017 }
2018 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002019}
2020
Elliott Hughes2435a572012-02-17 16:07:41 -08002021JDWP::JdwpError Dbg::ConfigureStep(JDWP::ObjectId threadId, JDWP::JdwpStepSize step_size, JDWP::JdwpStepDepth step_depth) {
Elliott Hughes86964332012-02-15 19:37:42 -08002022 Thread* thread = DecodeThread(threadId);
Elliott Hughes2435a572012-02-17 16:07:41 -08002023 if (thread == NULL) {
2024 return JDWP::ERR_INVALID_THREAD;
2025 }
Elliott Hughes86964332012-02-15 19:37:42 -08002026
Elliott Hughesf8349362012-06-18 15:00:06 -07002027 MutexLock mu(gBreakpointsLock);
2028
Elliott Hughes86964332012-02-15 19:37:42 -08002029 // TODO: there's no theoretical reason why we couldn't support single-stepping
2030 // of multiple threads at once, but we never did so historically.
2031 if (gSingleStepControl.thread != NULL && thread != gSingleStepControl.thread) {
2032 LOG(WARNING) << "single-step already active for " << *gSingleStepControl.thread
2033 << "; switching to " << *thread;
2034 }
2035
Elliott Hughes2435a572012-02-17 16:07:41 -08002036 //
2037 // Work out what Method* we're in, the current line number, and how deep the stack currently
2038 // is for step-out.
2039 //
2040
Ian Rogers0399dde2012-06-06 17:09:28 -07002041 struct SingleStepStackVisitor : public StackVisitor {
2042 SingleStepStackVisitor(const ManagedStack* stack,
Ian Rogersca190662012-06-26 15:45:57 -07002043 const std::vector<TraceStackFrame>* trace_stack)
Elliott Hughes08fc03a2012-06-26 17:34:00 -07002044 : StackVisitor(stack, trace_stack, NULL) {
Elliott Hughesf8349362012-06-18 15:00:06 -07002045 MutexLock mu(gBreakpointsLock); // Keep GCC happy.
Elliott Hughes86964332012-02-15 19:37:42 -08002046 gSingleStepControl.method = NULL;
2047 gSingleStepControl.stack_depth = 0;
2048 }
Ian Rogersca190662012-06-26 15:45:57 -07002049
Ian Rogers0399dde2012-06-06 17:09:28 -07002050 bool VisitFrame() {
Elliott Hughesf8349362012-06-18 15:00:06 -07002051 MutexLock mu(gBreakpointsLock); // Keep GCC happy.
Ian Rogers0399dde2012-06-06 17:09:28 -07002052 const Method* m = GetMethod();
2053 if (!m->IsRuntimeMethod()) {
Elliott Hughes86964332012-02-15 19:37:42 -08002054 ++gSingleStepControl.stack_depth;
2055 if (gSingleStepControl.method == NULL) {
Elliott Hughes2435a572012-02-17 16:07:41 -08002056 const DexCache* dex_cache = m->GetDeclaringClass()->GetDexCache();
2057 gSingleStepControl.method = m;
2058 gSingleStepControl.line_number = -1;
2059 if (dex_cache != NULL) {
2060 const DexFile& dex_file = Runtime::Current()->GetClassLinker()->FindDexFile(dex_cache);
Ian Rogers0399dde2012-06-06 17:09:28 -07002061 gSingleStepControl.line_number = dex_file.GetLineNumFromPC(m, GetDexPc());
Elliott Hughes2435a572012-02-17 16:07:41 -08002062 }
Elliott Hughes86964332012-02-15 19:37:42 -08002063 }
2064 }
Elliott Hughes530fa002012-03-12 11:44:49 -07002065 return true;
Elliott Hughes86964332012-02-15 19:37:42 -08002066 }
2067 };
Ian Rogers0399dde2012-06-06 17:09:28 -07002068 SingleStepStackVisitor visitor(thread->GetManagedStack(), thread->GetTraceStack());
2069 visitor.WalkStack();
Elliott Hughes86964332012-02-15 19:37:42 -08002070
Elliott Hughes2435a572012-02-17 16:07:41 -08002071 //
2072 // Find the dex_pc values that correspond to the current line, for line-based single-stepping.
2073 //
2074
2075 struct DebugCallbackContext {
2076 DebugCallbackContext() {
2077 last_pc_valid = false;
2078 last_pc = 0;
Elliott Hughes2435a572012-02-17 16:07:41 -08002079 }
2080
2081 static bool Callback(void* raw_context, uint32_t address, uint32_t line_number) {
Elliott Hughesf8349362012-06-18 15:00:06 -07002082 MutexLock mu(gBreakpointsLock); // Keep GCC happy.
Elliott Hughes2435a572012-02-17 16:07:41 -08002083 DebugCallbackContext* context = reinterpret_cast<DebugCallbackContext*>(raw_context);
2084 if (static_cast<int32_t>(line_number) == gSingleStepControl.line_number) {
2085 if (!context->last_pc_valid) {
2086 // Everything from this address until the next line change is ours.
2087 context->last_pc = address;
2088 context->last_pc_valid = true;
2089 }
2090 // Otherwise, if we're already in a valid range for this line,
2091 // just keep going (shouldn't really happen)...
2092 } else if (context->last_pc_valid) { // and the line number is new
2093 // Add everything from the last entry up until here to the set
2094 for (uint32_t dex_pc = context->last_pc; dex_pc < address; ++dex_pc) {
2095 gSingleStepControl.dex_pcs.insert(dex_pc);
2096 }
2097 context->last_pc_valid = false;
2098 }
2099 return false; // There may be multiple entries for any given line.
2100 }
2101
2102 ~DebugCallbackContext() {
Elliott Hughesf8349362012-06-18 15:00:06 -07002103 MutexLock mu(gBreakpointsLock); // Keep GCC happy.
Elliott Hughes2435a572012-02-17 16:07:41 -08002104 // If the line number was the last in the position table...
2105 if (last_pc_valid) {
2106 size_t end = MethodHelper(gSingleStepControl.method).GetCodeItem()->insns_size_in_code_units_;
2107 for (uint32_t dex_pc = last_pc; dex_pc < end; ++dex_pc) {
2108 gSingleStepControl.dex_pcs.insert(dex_pc);
2109 }
2110 }
2111 }
2112
2113 bool last_pc_valid;
2114 uint32_t last_pc;
2115 };
Elliott Hughes3e2e1a22012-02-21 11:33:41 -08002116 gSingleStepControl.dex_pcs.clear();
Elliott Hughes2435a572012-02-17 16:07:41 -08002117 const Method* m = gSingleStepControl.method;
Elliott Hughes3e2e1a22012-02-21 11:33:41 -08002118 if (m->IsNative()) {
2119 gSingleStepControl.line_number = -1;
2120 } else {
2121 DebugCallbackContext context;
2122 MethodHelper mh(m);
2123 mh.GetDexFile().DecodeDebugInfo(mh.GetCodeItem(), m->IsStatic(), m->GetDexMethodIndex(),
2124 DebugCallbackContext::Callback, NULL, &context);
2125 }
Elliott Hughes2435a572012-02-17 16:07:41 -08002126
2127 //
2128 // Everything else...
2129 //
2130
Elliott Hughes86964332012-02-15 19:37:42 -08002131 gSingleStepControl.thread = thread;
2132 gSingleStepControl.step_size = step_size;
2133 gSingleStepControl.step_depth = step_depth;
2134 gSingleStepControl.is_active = true;
2135
Elliott Hughes2435a572012-02-17 16:07:41 -08002136 if (VLOG_IS_ON(jdwp)) {
2137 VLOG(jdwp) << "Single-step thread: " << *gSingleStepControl.thread;
2138 VLOG(jdwp) << "Single-step step size: " << gSingleStepControl.step_size;
2139 VLOG(jdwp) << "Single-step step depth: " << gSingleStepControl.step_depth;
2140 VLOG(jdwp) << "Single-step current method: " << PrettyMethod(gSingleStepControl.method);
2141 VLOG(jdwp) << "Single-step current line: " << gSingleStepControl.line_number;
2142 VLOG(jdwp) << "Single-step current stack depth: " << gSingleStepControl.stack_depth;
2143 VLOG(jdwp) << "Single-step dex_pc values:";
2144 for (std::set<uint32_t>::iterator it = gSingleStepControl.dex_pcs.begin() ; it != gSingleStepControl.dex_pcs.end(); ++it) {
Elliott Hughes229feb72012-02-23 13:33:29 -08002145 VLOG(jdwp) << StringPrintf(" %#x", *it);
Elliott Hughes2435a572012-02-17 16:07:41 -08002146 }
2147 }
2148
2149 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002150}
2151
Elliott Hughes1bac54f2012-03-16 12:48:31 -07002152void Dbg::UnconfigureStep(JDWP::ObjectId /*threadId*/) {
Elliott Hughesf8349362012-06-18 15:00:06 -07002153 MutexLock mu(gBreakpointsLock);
2154
Elliott Hughes86964332012-02-15 19:37:42 -08002155 gSingleStepControl.is_active = false;
2156 gSingleStepControl.thread = NULL;
Elliott Hughes2435a572012-02-17 16:07:41 -08002157 gSingleStepControl.dex_pcs.clear();
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002158}
2159
Elliott Hughes45651fd2012-02-21 15:48:20 -08002160static char JdwpTagToShortyChar(JDWP::JdwpTag tag) {
2161 switch (tag) {
2162 default:
2163 LOG(FATAL) << "unknown JDWP tag: " << PrintableChar(tag);
2164
2165 // Primitives.
2166 case JDWP::JT_BYTE: return 'B';
2167 case JDWP::JT_CHAR: return 'C';
2168 case JDWP::JT_FLOAT: return 'F';
2169 case JDWP::JT_DOUBLE: return 'D';
2170 case JDWP::JT_INT: return 'I';
2171 case JDWP::JT_LONG: return 'J';
2172 case JDWP::JT_SHORT: return 'S';
2173 case JDWP::JT_VOID: return 'V';
2174 case JDWP::JT_BOOLEAN: return 'Z';
2175
2176 // Reference types.
2177 case JDWP::JT_ARRAY:
2178 case JDWP::JT_OBJECT:
2179 case JDWP::JT_STRING:
2180 case JDWP::JT_THREAD:
2181 case JDWP::JT_THREAD_GROUP:
2182 case JDWP::JT_CLASS_LOADER:
2183 case JDWP::JT_CLASS_OBJECT:
2184 return 'L';
2185 }
2186}
2187
2188JDWP::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 -08002189 ThreadList* thread_list = Runtime::Current()->GetThreadList();
2190
2191 Thread* targetThread = NULL;
2192 DebugInvokeReq* req = NULL;
2193 {
2194 ScopedThreadListLock thread_list_lock;
2195 targetThread = DecodeThread(threadId);
2196 if (targetThread == NULL) {
2197 LOG(ERROR) << "InvokeMethod request for non-existent thread " << threadId;
2198 return JDWP::ERR_INVALID_THREAD;
2199 }
2200 req = targetThread->GetInvokeReq();
2201 if (!req->ready) {
2202 LOG(ERROR) << "InvokeMethod request for thread not stopped by event: " << *targetThread;
2203 return JDWP::ERR_INVALID_THREAD;
2204 }
2205
2206 /*
2207 * We currently have a bug where we don't successfully resume the
2208 * target thread if the suspend count is too deep. We're expected to
2209 * require one "resume" for each "suspend", but when asked to execute
2210 * a method we have to resume fully and then re-suspend it back to the
2211 * same level. (The easiest way to cause this is to type "suspend"
2212 * multiple times in jdb.)
2213 *
2214 * It's unclear what this means when the event specifies "resume all"
2215 * and some threads are suspended more deeply than others. This is
2216 * a rare problem, so for now we just prevent it from hanging forever
2217 * by rejecting the method invocation request. Without this, we will
2218 * be stuck waiting on a suspended thread.
2219 */
2220 int suspend_count = targetThread->GetSuspendCount();
2221 if (suspend_count > 1) {
2222 LOG(ERROR) << *targetThread << " suspend count too deep for method invocation: " << suspend_count;
2223 return JDWP::ERR_THREAD_SUSPENDED; // Probably not expected here.
2224 }
2225
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08002226 JDWP::JdwpError status;
Elliott Hughes45651fd2012-02-21 15:48:20 -08002227 Object* receiver = gRegistry->Get<Object*>(objectId);
2228 if (receiver == kInvalidObject) {
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08002229 return JDWP::ERR_INVALID_OBJECT;
2230 }
Elliott Hughes45651fd2012-02-21 15:48:20 -08002231
2232 Object* thread = gRegistry->Get<Object*>(threadId);
2233 if (thread == kInvalidObject) {
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08002234 return JDWP::ERR_INVALID_OBJECT;
2235 }
Elliott Hughes45651fd2012-02-21 15:48:20 -08002236 // TODO: check that 'thread' is actually a java.lang.Thread!
2237
2238 Class* c = DecodeClass(classId, status);
2239 if (c == NULL) {
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08002240 return status;
2241 }
Elliott Hughes45651fd2012-02-21 15:48:20 -08002242
2243 Method* m = FromMethodId(methodId);
2244 if (m->IsStatic() != (receiver == NULL)) {
2245 return JDWP::ERR_INVALID_METHODID;
2246 }
2247 if (m->IsStatic()) {
2248 if (m->GetDeclaringClass() != c) {
2249 return JDWP::ERR_INVALID_METHODID;
2250 }
2251 } else {
2252 if (!m->GetDeclaringClass()->IsAssignableFrom(c)) {
2253 return JDWP::ERR_INVALID_METHODID;
2254 }
2255 }
2256
2257 // Check the argument list matches the method.
2258 MethodHelper mh(m);
2259 if (mh.GetShortyLength() - 1 != arg_count) {
2260 return JDWP::ERR_ILLEGAL_ARGUMENT;
2261 }
2262 const char* shorty = mh.GetShorty();
2263 for (size_t i = 0; i < arg_count; ++i) {
2264 if (shorty[i + 1] != JdwpTagToShortyChar(arg_types[i])) {
2265 return JDWP::ERR_ILLEGAL_ARGUMENT;
2266 }
2267 }
2268
2269 req->receiver_ = receiver;
2270 req->thread_ = thread;
2271 req->class_ = c;
2272 req->method_ = m;
2273 req->arg_count_ = arg_count;
2274 req->arg_values_ = arg_values;
Elliott Hughesd07986f2011-12-06 18:27:45 -08002275 req->options_ = options;
2276 req->invoke_needed_ = true;
2277 }
2278
2279 // The fact that we've released the thread list lock is a bit risky --- if the thread goes
2280 // away we're sitting high and dry -- but we must release this before the ResumeAllThreads
2281 // call, and it's unwise to hold it during WaitForSuspend.
2282
2283 {
2284 /*
2285 * We change our (JDWP thread) status, which should be THREAD_RUNNING,
Elliott Hughes81ff3182012-03-23 20:35:56 -07002286 * so we can suspend for a GC if the invoke request causes us to
Elliott Hughesd07986f2011-12-06 18:27:45 -08002287 * run out of memory. It's also a good idea to change it before locking
2288 * the invokeReq mutex, although that should never be held for long.
2289 */
Elliott Hughes34e06962012-04-09 13:55:55 -07002290 ScopedThreadStateChange tsc(Thread::Current(), kVmWait);
Elliott Hughesd07986f2011-12-06 18:27:45 -08002291
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08002292 VLOG(jdwp) << " Transferring control to event thread";
Elliott Hughesd07986f2011-12-06 18:27:45 -08002293 {
2294 MutexLock mu(req->lock_);
2295
2296 if ((options & JDWP::INVOKE_SINGLE_THREADED) == 0) {
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08002297 VLOG(jdwp) << " Resuming all threads";
Elliott Hughesd07986f2011-12-06 18:27:45 -08002298 thread_list->ResumeAll(true);
2299 } else {
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08002300 VLOG(jdwp) << " Resuming event thread only";
Elliott Hughesd07986f2011-12-06 18:27:45 -08002301 thread_list->Resume(targetThread, true);
2302 }
2303
2304 // Wait for the request to finish executing.
2305 while (req->invoke_needed_) {
2306 req->cond_.Wait(req->lock_);
2307 }
2308 }
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08002309 VLOG(jdwp) << " Control has returned from event thread";
Elliott Hughesd07986f2011-12-06 18:27:45 -08002310
2311 /* wait for thread to re-suspend itself */
2312 targetThread->WaitUntilSuspended();
2313 //dvmWaitForSuspend(targetThread);
2314 }
2315
2316 /*
2317 * Suspend the threads. We waited for the target thread to suspend
2318 * itself, so all we need to do is suspend the others.
2319 *
2320 * The suspendAllThreads() call will double-suspend the event thread,
2321 * so we want to resume the target thread once to keep the books straight.
2322 */
2323 if ((options & JDWP::INVOKE_SINGLE_THREADED) == 0) {
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08002324 VLOG(jdwp) << " Suspending all threads";
Elliott Hughesd07986f2011-12-06 18:27:45 -08002325 thread_list->SuspendAll(true);
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08002326 VLOG(jdwp) << " Resuming event thread to balance the count";
Elliott Hughesd07986f2011-12-06 18:27:45 -08002327 thread_list->Resume(targetThread, true);
2328 }
2329
2330 // Copy the result.
2331 *pResultTag = req->result_tag;
2332 if (IsPrimitiveTag(req->result_tag)) {
Elliott Hughesf24d3ce2012-04-11 17:43:37 -07002333 *pResultValue = req->result_value.GetJ();
Elliott Hughesd07986f2011-12-06 18:27:45 -08002334 } else {
Elliott Hughesf24d3ce2012-04-11 17:43:37 -07002335 *pResultValue = gRegistry->Add(req->result_value.GetL());
Elliott Hughesd07986f2011-12-06 18:27:45 -08002336 }
2337 *pExceptionId = req->exception;
2338 return req->error;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002339}
2340
2341void Dbg::ExecuteMethod(DebugInvokeReq* pReq) {
Ian Rogers365c1022012-06-22 15:05:28 -07002342 ScopedJniThreadState ts(Thread::Current());
Elliott Hughesd07986f2011-12-06 18:27:45 -08002343
Elliott Hughes81ff3182012-03-23 20:35:56 -07002344 // We can be called while an exception is pending. We need
Elliott Hughesd07986f2011-12-06 18:27:45 -08002345 // to preserve that across the method invocation.
Ian Rogers365c1022012-06-22 15:05:28 -07002346 SirtRef<Throwable> old_exception(ts.Self()->GetException());
2347 ts.Self()->ClearException();
Elliott Hughesd07986f2011-12-06 18:27:45 -08002348
2349 // Translate the method through the vtable, unless the debugger wants to suppress it.
2350 Method* m = pReq->method_;
2351 if ((pReq->options_ & JDWP::INVOKE_NONVIRTUAL) == 0 && pReq->receiver_ != NULL) {
Elliott Hughes45651fd2012-02-21 15:48:20 -08002352 Method* actual_method = pReq->class_->FindVirtualMethodForVirtualOrInterface(pReq->method_);
2353 if (actual_method != m) {
2354 VLOG(jdwp) << "ExecuteMethod translated " << PrettyMethod(m) << " to " << PrettyMethod(actual_method);
2355 m = actual_method;
2356 }
Elliott Hughesd07986f2011-12-06 18:27:45 -08002357 }
Elliott Hughes45651fd2012-02-21 15:48:20 -08002358 VLOG(jdwp) << "ExecuteMethod " << PrettyMethod(m);
Elliott Hughesd07986f2011-12-06 18:27:45 -08002359 CHECK(m != NULL);
2360
2361 CHECK_EQ(sizeof(jvalue), sizeof(uint64_t));
2362
Ian Rogers365c1022012-06-22 15:05:28 -07002363 LOG(INFO) << "self=" << ts.Self() << " pReq->receiver_=" << pReq->receiver_ << " m=" << m << " #" << pReq->arg_count_ << " " << pReq->arg_values_;
2364 pReq->result_value = InvokeWithJValues(ts, pReq->receiver_, m, reinterpret_cast<JValue*>(pReq->arg_values_));
Elliott Hughesd07986f2011-12-06 18:27:45 -08002365
Ian Rogers365c1022012-06-22 15:05:28 -07002366 pReq->exception = gRegistry->Add(ts.Self()->GetException());
Elliott Hughesd07986f2011-12-06 18:27:45 -08002367 pReq->result_tag = BasicTagFromDescriptor(MethodHelper(m).GetShorty());
2368 if (pReq->exception != 0) {
Ian Rogers365c1022012-06-22 15:05:28 -07002369 Object* exc = ts.Self()->GetException();
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08002370 VLOG(jdwp) << " JDWP invocation returning with exception=" << exc << " " << PrettyTypeOf(exc);
Ian Rogers365c1022012-06-22 15:05:28 -07002371 ts.Self()->ClearException();
Elliott Hughesf24d3ce2012-04-11 17:43:37 -07002372 pReq->result_value.SetJ(0);
Elliott Hughesd07986f2011-12-06 18:27:45 -08002373 } else if (pReq->result_tag == JDWP::JT_OBJECT) {
2374 /* if no exception thrown, examine object result more closely */
Elliott Hughesf24d3ce2012-04-11 17:43:37 -07002375 JDWP::JdwpTag new_tag = TagFromObject(pReq->result_value.GetL());
Elliott Hughesd07986f2011-12-06 18:27:45 -08002376 if (new_tag != pReq->result_tag) {
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08002377 VLOG(jdwp) << " JDWP promoted result from " << pReq->result_tag << " to " << new_tag;
Elliott Hughesd07986f2011-12-06 18:27:45 -08002378 pReq->result_tag = new_tag;
2379 }
2380
2381 /*
2382 * Register the object. We don't actually need an ObjectId yet,
2383 * but we do need to be sure that the GC won't move or discard the
2384 * object when we switch out of RUNNING. The ObjectId conversion
2385 * will add the object to the "do not touch" list.
2386 *
2387 * We can't use the "tracked allocation" mechanism here because
2388 * the object is going to be handed off to a different thread.
2389 */
Elliott Hughesf24d3ce2012-04-11 17:43:37 -07002390 gRegistry->Add(pReq->result_value.GetL());
Elliott Hughesd07986f2011-12-06 18:27:45 -08002391 }
2392
2393 if (old_exception.get() != NULL) {
Ian Rogers365c1022012-06-22 15:05:28 -07002394 ts.Self()->SetException(old_exception.get());
Elliott Hughesd07986f2011-12-06 18:27:45 -08002395 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002396}
2397
Elliott Hughesd07986f2011-12-06 18:27:45 -08002398/*
2399 * Register an object ID that might not have been registered previously.
2400 *
2401 * Normally this wouldn't happen -- the conversion to an ObjectId would
2402 * have added the object to the registry -- but in some cases (e.g.
2403 * throwing exceptions) we really want to do the registration late.
2404 */
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002405void Dbg::RegisterObjectId(JDWP::ObjectId id) {
Elliott Hughesd07986f2011-12-06 18:27:45 -08002406 gRegistry->Add(reinterpret_cast<Object*>(id));
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002407}
2408
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07002409/*
2410 * "buf" contains a full JDWP packet, possibly with multiple chunks. We
2411 * need to process each, accumulate the replies, and ship the whole thing
2412 * back.
2413 *
2414 * Returns "true" if we have a reply. The reply buffer is newly allocated,
2415 * and includes the chunk type/length, followed by the data.
2416 *
Elliott Hughes3d30d9b2011-12-07 17:35:48 -08002417 * OLD-TODO: we currently assume that the request and reply include a single
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07002418 * chunk. If this becomes inconvenient we will need to adapt.
2419 */
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002420bool Dbg::DdmHandlePacket(const uint8_t* buf, int dataLen, uint8_t** pReplyBuf, int* pReplyLen) {
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07002421 CHECK_GE(dataLen, 0);
2422
2423 Thread* self = Thread::Current();
2424 JNIEnv* env = self->GetJniEnv();
2425
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07002426 // Create a byte[] corresponding to 'buf'.
Elliott Hughes6a5bd492011-10-28 14:33:57 -07002427 ScopedLocalRef<jbyteArray> dataArray(env, env->NewByteArray(dataLen));
2428 if (dataArray.get() == NULL) {
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07002429 LOG(WARNING) << "byte[] allocation failed: " << dataLen;
2430 env->ExceptionClear();
2431 return false;
2432 }
Elliott Hughes6a5bd492011-10-28 14:33:57 -07002433 env->SetByteArrayRegion(dataArray.get(), 0, dataLen, reinterpret_cast<const jbyte*>(buf));
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07002434
2435 const int kChunkHdrLen = 8;
2436
2437 // Run through and find all chunks. [Currently just find the first.]
Elliott Hughes6a5bd492011-10-28 14:33:57 -07002438 ScopedByteArrayRO contents(env, dataArray.get());
Elliott Hughesf7c3b662011-10-27 12:04:56 -07002439 jint type = JDWP::Get4BE(reinterpret_cast<const uint8_t*>(&contents[0]));
2440 jint length = JDWP::Get4BE(reinterpret_cast<const uint8_t*>(&contents[4]));
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07002441 jint offset = kChunkHdrLen;
2442 if (offset + length > dataLen) {
2443 LOG(WARNING) << StringPrintf("bad chunk found (len=%u pktLen=%d)", length, dataLen);
2444 return false;
2445 }
2446
2447 // Call "private static Chunk dispatch(int type, byte[] data, int offset, int length)".
Elliott Hugheseac76672012-05-24 21:56:51 -07002448 ScopedLocalRef<jobject> chunk(env, env->CallStaticObjectMethod(WellKnownClasses::org_apache_harmony_dalvik_ddmc_DdmServer,
2449 WellKnownClasses::org_apache_harmony_dalvik_ddmc_DdmServer_dispatch,
2450 type, dataArray.get(), offset, length));
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07002451 if (env->ExceptionCheck()) {
2452 LOG(INFO) << StringPrintf("Exception thrown by dispatcher for 0x%08x", type);
2453 env->ExceptionDescribe();
2454 env->ExceptionClear();
2455 return false;
2456 }
2457
Elliott Hughes6a5bd492011-10-28 14:33:57 -07002458 if (chunk.get() == NULL) {
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07002459 return false;
2460 }
2461
2462 /*
2463 * Pull the pieces out of the chunk. We copy the results into a
2464 * newly-allocated buffer that the caller can free. We don't want to
2465 * continue using the Chunk object because nothing has a reference to it.
2466 *
2467 * We could avoid this by returning type/data/offset/length and having
2468 * the caller be aware of the object lifetime issues, but that
Elliott Hughes81ff3182012-03-23 20:35:56 -07002469 * integrates the JDWP code more tightly into the rest of the runtime, and doesn't work
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07002470 * if we have responses for multiple chunks.
2471 *
2472 * So we're pretty much stuck with copying data around multiple times.
2473 */
Elliott Hugheseac76672012-05-24 21:56:51 -07002474 ScopedLocalRef<jbyteArray> replyData(env, reinterpret_cast<jbyteArray>(env->GetObjectField(chunk.get(), WellKnownClasses::org_apache_harmony_dalvik_ddmc_Chunk_data)));
2475 length = env->GetIntField(chunk.get(), WellKnownClasses::org_apache_harmony_dalvik_ddmc_Chunk_length);
2476 offset = env->GetIntField(chunk.get(), WellKnownClasses::org_apache_harmony_dalvik_ddmc_Chunk_offset);
2477 type = env->GetIntField(chunk.get(), WellKnownClasses::org_apache_harmony_dalvik_ddmc_Chunk_type);
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07002478
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08002479 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 -07002480 if (length == 0 || replyData.get() == NULL) {
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07002481 return false;
2482 }
2483
Elliott Hughes6a5bd492011-10-28 14:33:57 -07002484 jsize replyLength = env->GetArrayLength(replyData.get());
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07002485 if (offset + length > replyLength) {
2486 LOG(WARNING) << StringPrintf("chunk off=%d len=%d exceeds reply array len %d", offset, length, replyLength);
2487 return false;
2488 }
2489
2490 uint8_t* reply = new uint8_t[length + kChunkHdrLen];
2491 if (reply == NULL) {
2492 LOG(WARNING) << "malloc failed: " << (length + kChunkHdrLen);
2493 return false;
2494 }
Elliott Hughesf7c3b662011-10-27 12:04:56 -07002495 JDWP::Set4BE(reply + 0, type);
2496 JDWP::Set4BE(reply + 4, length);
Elliott Hughes6a5bd492011-10-28 14:33:57 -07002497 env->GetByteArrayRegion(replyData.get(), offset, length, reinterpret_cast<jbyte*>(reply + kChunkHdrLen));
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07002498
2499 *pReplyBuf = reply;
2500 *pReplyLen = length + kChunkHdrLen;
2501
Elliott Hughesba8eee12012-01-24 20:25:24 -08002502 VLOG(jdwp) << StringPrintf("dvmHandleDdm returning type=%.4s buf=%p len=%d", reinterpret_cast<char*>(reply), reply, length);
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07002503 return true;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002504}
2505
Elliott Hughesa2155262011-11-16 16:26:58 -08002506void Dbg::DdmBroadcast(bool connect) {
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08002507 VLOG(jdwp) << "Broadcasting DDM " << (connect ? "connect" : "disconnect") << "...";
Elliott Hughes47fce012011-10-25 18:37:19 -07002508
2509 Thread* self = Thread::Current();
Elliott Hughes34e06962012-04-09 13:55:55 -07002510 if (self->GetState() != kRunnable) {
Elliott Hughes47fce012011-10-25 18:37:19 -07002511 LOG(ERROR) << "DDM broadcast in thread state " << self->GetState();
2512 /* try anyway? */
2513 }
2514
2515 JNIEnv* env = self->GetJniEnv();
Elliott Hughes47fce012011-10-25 18:37:19 -07002516 jint event = connect ? 1 /*DdmServer.CONNECTED*/ : 2 /*DdmServer.DISCONNECTED*/;
Elliott Hugheseac76672012-05-24 21:56:51 -07002517 env->CallStaticVoidMethod(WellKnownClasses::org_apache_harmony_dalvik_ddmc_DdmServer,
2518 WellKnownClasses::org_apache_harmony_dalvik_ddmc_DdmServer_broadcast,
2519 event);
Elliott Hughes47fce012011-10-25 18:37:19 -07002520 if (env->ExceptionCheck()) {
2521 LOG(ERROR) << "DdmServer.broadcast " << event << " failed";
2522 env->ExceptionDescribe();
2523 env->ExceptionClear();
2524 }
2525}
2526
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002527void Dbg::DdmConnected() {
Elliott Hughesa2155262011-11-16 16:26:58 -08002528 Dbg::DdmBroadcast(true);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002529}
2530
2531void Dbg::DdmDisconnected() {
Elliott Hughesa2155262011-11-16 16:26:58 -08002532 Dbg::DdmBroadcast(false);
Elliott Hughes47fce012011-10-25 18:37:19 -07002533 gDdmThreadNotification = false;
2534}
2535
2536/*
Elliott Hughes82188472011-11-07 18:11:48 -08002537 * Send a notification when a thread starts, stops, or changes its name.
Elliott Hughes47fce012011-10-25 18:37:19 -07002538 *
2539 * Because we broadcast the full set of threads when the notifications are
2540 * first enabled, it's possible for "thread" to be actively executing.
2541 */
Elliott Hughes82188472011-11-07 18:11:48 -08002542void Dbg::DdmSendThreadNotification(Thread* t, uint32_t type) {
Elliott Hughes47fce012011-10-25 18:37:19 -07002543 if (!gDdmThreadNotification) {
2544 return;
2545 }
2546
Elliott Hughes82188472011-11-07 18:11:48 -08002547 if (type == CHUNK_TYPE("THDE")) {
Elliott Hughes47fce012011-10-25 18:37:19 -07002548 uint8_t buf[4];
Elliott Hughesf7c3b662011-10-27 12:04:56 -07002549 JDWP::Set4BE(&buf[0], t->GetThinLockId());
Elliott Hughes47fce012011-10-25 18:37:19 -07002550 Dbg::DdmSendChunk(CHUNK_TYPE("THDE"), 4, buf);
Elliott Hughes82188472011-11-07 18:11:48 -08002551 } else {
2552 CHECK(type == CHUNK_TYPE("THCR") || type == CHUNK_TYPE("THNM")) << type;
Ian Rogers365c1022012-06-22 15:05:28 -07002553 ScopedJniThreadState ts(Thread::Current());
2554 SirtRef<String> name(t->GetThreadName(ts));
Elliott Hughes82188472011-11-07 18:11:48 -08002555 size_t char_count = (name.get() != NULL) ? name->GetLength() : 0;
2556 const jchar* chars = name->GetCharArray()->GetData();
2557
Elliott Hughes21f32d72011-11-09 17:44:13 -08002558 std::vector<uint8_t> bytes;
Elliott Hughes545a0642011-11-08 19:10:03 -08002559 JDWP::Append4BE(bytes, t->GetThinLockId());
2560 JDWP::AppendUtf16BE(bytes, chars, char_count);
Elliott Hughes21f32d72011-11-09 17:44:13 -08002561 CHECK_EQ(bytes.size(), char_count*2 + sizeof(uint32_t)*2);
2562 Dbg::DdmSendChunk(type, bytes);
Elliott Hughes47fce012011-10-25 18:37:19 -07002563 }
2564}
2565
Elliott Hughesa2155262011-11-16 16:26:58 -08002566static void DdmSendThreadStartCallback(Thread* t, void*) {
Elliott Hughes82188472011-11-07 18:11:48 -08002567 Dbg::DdmSendThreadNotification(t, CHUNK_TYPE("THCR"));
Elliott Hughes47fce012011-10-25 18:37:19 -07002568}
2569
2570void Dbg::DdmSetThreadNotification(bool enable) {
2571 // We lock the thread list to avoid sending duplicate events or missing
2572 // a thread change. We should be okay holding this lock while sending
2573 // the messages out. (We have to hold it while accessing a live thread.)
Elliott Hughesbbd9d832011-11-07 14:40:00 -08002574 ScopedThreadListLock thread_list_lock;
Elliott Hughes47fce012011-10-25 18:37:19 -07002575
2576 gDdmThreadNotification = enable;
2577 if (enable) {
Elliott Hughesbfe487b2011-10-26 15:48:55 -07002578 Runtime::Current()->GetThreadList()->ForEach(DdmSendThreadStartCallback, NULL);
Elliott Hughes47fce012011-10-25 18:37:19 -07002579 }
2580}
2581
Elliott Hughesa2155262011-11-16 16:26:58 -08002582void Dbg::PostThreadStartOrStop(Thread* t, uint32_t type) {
Elliott Hughesc0f09332012-03-26 13:27:06 -07002583 if (IsDebuggerActive()) {
Elliott Hughes47fce012011-10-25 18:37:19 -07002584 JDWP::ObjectId id = gRegistry->Add(t->GetPeer());
Elliott Hughes82188472011-11-07 18:11:48 -08002585 gJdwpState->PostThreadChange(id, type == CHUNK_TYPE("THCR"));
Elliott Hughesc0f09332012-03-26 13:27:06 -07002586 // If this thread's just joined the party while we're already debugging, make sure it knows
2587 // to give us updates when it's running.
2588 t->SetDebuggerUpdatesEnabled(true);
Elliott Hughes47fce012011-10-25 18:37:19 -07002589 }
Elliott Hughes82188472011-11-07 18:11:48 -08002590 Dbg::DdmSendThreadNotification(t, type);
Elliott Hughes47fce012011-10-25 18:37:19 -07002591}
2592
2593void Dbg::PostThreadStart(Thread* t) {
Elliott Hughesa2155262011-11-16 16:26:58 -08002594 Dbg::PostThreadStartOrStop(t, CHUNK_TYPE("THCR"));
Elliott Hughes47fce012011-10-25 18:37:19 -07002595}
2596
2597void Dbg::PostThreadDeath(Thread* t) {
Elliott Hughesa2155262011-11-16 16:26:58 -08002598 Dbg::PostThreadStartOrStop(t, CHUNK_TYPE("THDE"));
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002599}
2600
Elliott Hughes82188472011-11-07 18:11:48 -08002601void Dbg::DdmSendChunk(uint32_t type, size_t byte_count, const uint8_t* buf) {
Elliott Hughes3bb81562011-10-21 18:52:59 -07002602 CHECK(buf != NULL);
2603 iovec vec[1];
2604 vec[0].iov_base = reinterpret_cast<void*>(const_cast<uint8_t*>(buf));
2605 vec[0].iov_len = byte_count;
2606 Dbg::DdmSendChunkV(type, vec, 1);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002607}
2608
Elliott Hughes21f32d72011-11-09 17:44:13 -08002609void Dbg::DdmSendChunk(uint32_t type, const std::vector<uint8_t>& bytes) {
2610 DdmSendChunk(type, bytes.size(), &bytes[0]);
2611}
2612
Elliott Hughescccd84f2011-12-05 16:51:54 -08002613void Dbg::DdmSendChunkV(uint32_t type, const struct iovec* iov, int iov_count) {
Elliott Hughes3bb81562011-10-21 18:52:59 -07002614 if (gJdwpState == NULL) {
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08002615 VLOG(jdwp) << "Debugger thread not active, ignoring DDM send: " << type;
Elliott Hughes3bb81562011-10-21 18:52:59 -07002616 } else {
Elliott Hughescccd84f2011-12-05 16:51:54 -08002617 gJdwpState->DdmSendChunkV(type, iov, iov_count);
Elliott Hughes3bb81562011-10-21 18:52:59 -07002618 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002619}
2620
Elliott Hughes767a1472011-10-26 18:49:02 -07002621int Dbg::DdmHandleHpifChunk(HpifWhen when) {
2622 if (when == HPIF_WHEN_NOW) {
Elliott Hughes7162ad92011-10-27 14:08:42 -07002623 DdmSendHeapInfo(when);
Elliott Hughes767a1472011-10-26 18:49:02 -07002624 return true;
2625 }
2626
2627 if (when != HPIF_WHEN_NEVER && when != HPIF_WHEN_NEXT_GC && when != HPIF_WHEN_EVERY_GC) {
2628 LOG(ERROR) << "invalid HpifWhen value: " << static_cast<int>(when);
2629 return false;
2630 }
2631
2632 gDdmHpifWhen = when;
2633 return true;
2634}
2635
2636bool Dbg::DdmHandleHpsgNhsgChunk(Dbg::HpsgWhen when, Dbg::HpsgWhat what, bool native) {
2637 if (when != HPSG_WHEN_NEVER && when != HPSG_WHEN_EVERY_GC) {
2638 LOG(ERROR) << "invalid HpsgWhen value: " << static_cast<int>(when);
2639 return false;
2640 }
2641
2642 if (what != HPSG_WHAT_MERGED_OBJECTS && what != HPSG_WHAT_DISTINCT_OBJECTS) {
2643 LOG(ERROR) << "invalid HpsgWhat value: " << static_cast<int>(what);
2644 return false;
2645 }
2646
2647 if (native) {
2648 gDdmNhsgWhen = when;
2649 gDdmNhsgWhat = what;
2650 } else {
2651 gDdmHpsgWhen = when;
2652 gDdmHpsgWhat = what;
2653 }
2654 return true;
2655}
2656
Elliott Hughes7162ad92011-10-27 14:08:42 -07002657void Dbg::DdmSendHeapInfo(HpifWhen reason) {
2658 // If there's a one-shot 'when', reset it.
2659 if (reason == gDdmHpifWhen) {
2660 if (gDdmHpifWhen == HPIF_WHEN_NEXT_GC) {
2661 gDdmHpifWhen = HPIF_WHEN_NEVER;
2662 }
2663 }
2664
2665 /*
2666 * Chunk HPIF (client --> server)
2667 *
2668 * Heap Info. General information about the heap,
2669 * suitable for a summary display.
2670 *
2671 * [u4]: number of heaps
2672 *
2673 * For each heap:
2674 * [u4]: heap ID
2675 * [u8]: timestamp in ms since Unix epoch
2676 * [u1]: capture reason (same as 'when' value from server)
2677 * [u4]: max heap size in bytes (-Xmx)
2678 * [u4]: current heap size in bytes
2679 * [u4]: current number of bytes allocated
2680 * [u4]: current number of objects allocated
2681 */
2682 uint8_t heap_count = 1;
Elliott Hughesb3bd5f02012-03-08 21:05:27 -08002683 Heap* heap = Runtime::Current()->GetHeap();
Elliott Hughes21f32d72011-11-09 17:44:13 -08002684 std::vector<uint8_t> bytes;
Elliott Hughes545a0642011-11-08 19:10:03 -08002685 JDWP::Append4BE(bytes, heap_count);
2686 JDWP::Append4BE(bytes, 1); // Heap id (bogus; we only have one heap).
2687 JDWP::Append8BE(bytes, MilliTime());
2688 JDWP::Append1BE(bytes, reason);
Elliott Hughesb3bd5f02012-03-08 21:05:27 -08002689 JDWP::Append4BE(bytes, heap->GetMaxMemory()); // Max allowed heap size in bytes.
2690 JDWP::Append4BE(bytes, heap->GetTotalMemory()); // Current heap size in bytes.
2691 JDWP::Append4BE(bytes, heap->GetBytesAllocated());
2692 JDWP::Append4BE(bytes, heap->GetObjectsAllocated());
Elliott Hughes21f32d72011-11-09 17:44:13 -08002693 CHECK_EQ(bytes.size(), 4U + (heap_count * (4 + 8 + 1 + 4 + 4 + 4 + 4)));
2694 Dbg::DdmSendChunk(CHUNK_TYPE("HPIF"), bytes);
Elliott Hughes767a1472011-10-26 18:49:02 -07002695}
2696
Elliott Hughes6a5bd492011-10-28 14:33:57 -07002697enum HpsgSolidity {
2698 SOLIDITY_FREE = 0,
2699 SOLIDITY_HARD = 1,
2700 SOLIDITY_SOFT = 2,
2701 SOLIDITY_WEAK = 3,
2702 SOLIDITY_PHANTOM = 4,
2703 SOLIDITY_FINALIZABLE = 5,
2704 SOLIDITY_SWEEP = 6,
2705};
2706
2707enum HpsgKind {
2708 KIND_OBJECT = 0,
2709 KIND_CLASS_OBJECT = 1,
2710 KIND_ARRAY_1 = 2,
2711 KIND_ARRAY_2 = 3,
2712 KIND_ARRAY_4 = 4,
2713 KIND_ARRAY_8 = 5,
2714 KIND_UNKNOWN = 6,
2715 KIND_NATIVE = 7,
2716};
2717
2718#define HPSG_PARTIAL (1<<7)
2719#define HPSG_STATE(solidity, kind) ((uint8_t)((((kind) & 0x7) << 3) | ((solidity) & 0x7)))
2720
Ian Rogers30fab402012-01-23 15:43:46 -08002721class HeapChunkContext {
2722 public:
Elliott Hughes6a5bd492011-10-28 14:33:57 -07002723 // Maximum chunk size. Obtain this from the formula:
2724 // (((maximum_heap_size / ALLOCATION_UNIT_SIZE) + 255) / 256) * 2
2725 HeapChunkContext(bool merge, bool native)
Ian Rogers30fab402012-01-23 15:43:46 -08002726 : buf_(16384 - 16),
2727 type_(0),
2728 merge_(merge) {
Elliott Hughes6a5bd492011-10-28 14:33:57 -07002729 Reset();
2730 if (native) {
Ian Rogers30fab402012-01-23 15:43:46 -08002731 type_ = CHUNK_TYPE("NHSG");
Elliott Hughes6a5bd492011-10-28 14:33:57 -07002732 } else {
Ian Rogers30fab402012-01-23 15:43:46 -08002733 type_ = merge ? CHUNK_TYPE("HPSG") : CHUNK_TYPE("HPSO");
Elliott Hughes6a5bd492011-10-28 14:33:57 -07002734 }
2735 }
2736
2737 ~HeapChunkContext() {
Ian Rogers30fab402012-01-23 15:43:46 -08002738 if (p_ > &buf_[0]) {
Elliott Hughes6a5bd492011-10-28 14:33:57 -07002739 Flush();
2740 }
2741 }
2742
2743 void EnsureHeader(const void* chunk_ptr) {
Ian Rogers30fab402012-01-23 15:43:46 -08002744 if (!needHeader_) {
Elliott Hughes6a5bd492011-10-28 14:33:57 -07002745 return;
2746 }
2747
2748 // Start a new HPSx chunk.
Ian Rogers30fab402012-01-23 15:43:46 -08002749 JDWP::Write4BE(&p_, 1); // Heap id (bogus; we only have one heap).
2750 JDWP::Write1BE(&p_, 8); // Size of allocation unit, in bytes.
Elliott Hughes6a5bd492011-10-28 14:33:57 -07002751
Ian Rogers30fab402012-01-23 15:43:46 -08002752 JDWP::Write4BE(&p_, reinterpret_cast<uintptr_t>(chunk_ptr)); // virtual address of segment start.
2753 JDWP::Write4BE(&p_, 0); // offset of this piece (relative to the virtual address).
Elliott Hughes6a5bd492011-10-28 14:33:57 -07002754 // [u4]: length of piece, in allocation units
2755 // 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 -08002756 pieceLenField_ = p_;
2757 JDWP::Write4BE(&p_, 0x55555555);
2758 needHeader_ = false;
Elliott Hughes6a5bd492011-10-28 14:33:57 -07002759 }
2760
2761 void Flush() {
2762 // Patch the "length of piece" field.
Ian Rogers30fab402012-01-23 15:43:46 -08002763 CHECK_LE(&buf_[0], pieceLenField_);
2764 CHECK_LE(pieceLenField_, p_);
2765 JDWP::Set4BE(pieceLenField_, totalAllocationUnits_);
Elliott Hughes6a5bd492011-10-28 14:33:57 -07002766
Ian Rogers30fab402012-01-23 15:43:46 -08002767 Dbg::DdmSendChunk(type_, p_ - &buf_[0], &buf_[0]);
Elliott Hughes6a5bd492011-10-28 14:33:57 -07002768 Reset();
2769 }
2770
Ian Rogers30fab402012-01-23 15:43:46 -08002771 static void HeapChunkCallback(void* start, void* end, size_t used_bytes, void* arg) {
2772 reinterpret_cast<HeapChunkContext*>(arg)->HeapChunkCallback(start, end, used_bytes);
Elliott Hughesa2155262011-11-16 16:26:58 -08002773 }
2774
Elliott Hughes6a5bd492011-10-28 14:33:57 -07002775 private:
Elliott Hughesa2155262011-11-16 16:26:58 -08002776 enum { ALLOCATION_UNIT_SIZE = 8 };
2777
Elliott Hughes6a5bd492011-10-28 14:33:57 -07002778 void Reset() {
Ian Rogers30fab402012-01-23 15:43:46 -08002779 p_ = &buf_[0];
2780 totalAllocationUnits_ = 0;
2781 needHeader_ = true;
2782 pieceLenField_ = NULL;
Elliott Hughes6a5bd492011-10-28 14:33:57 -07002783 }
2784
Elliott Hughes1bac54f2012-03-16 12:48:31 -07002785 void HeapChunkCallback(void* start, void* /*end*/, size_t used_bytes) {
Ian Rogers30fab402012-01-23 15:43:46 -08002786 // Note: heap call backs cannot manipulate the heap upon which they are crawling, care is taken
2787 // in the following code not to allocate memory, by ensuring buf_ is of the correct size
2788
Elliott Hughes741c9fa2012-06-08 15:51:32 -07002789 void* user_ptr = used_bytes > 0 ? start : NULL;
2790 size_t chunk_len = mspace_usable_size(user_ptr);
Ian Rogers30fab402012-01-23 15:43:46 -08002791
Elliott Hughes741c9fa2012-06-08 15:51:32 -07002792 // Make sure there's enough room left in the buffer.
2793 // We need to use two bytes for every fractional 256 allocation units used by the chunk.
Elliott Hughesa2155262011-11-16 16:26:58 -08002794 {
2795 size_t needed = (((chunk_len/ALLOCATION_UNIT_SIZE + 255) / 256) * 2);
Ian Rogers30fab402012-01-23 15:43:46 -08002796 size_t bytesLeft = buf_.size() - (size_t)(p_ - &buf_[0]);
Elliott Hughesa2155262011-11-16 16:26:58 -08002797 if (bytesLeft < needed) {
2798 Flush();
2799 }
Elliott Hughes6a5bd492011-10-28 14:33:57 -07002800
Ian Rogers30fab402012-01-23 15:43:46 -08002801 bytesLeft = buf_.size() - (size_t)(p_ - &buf_[0]);
Elliott Hughesa2155262011-11-16 16:26:58 -08002802 if (bytesLeft < needed) {
Elliott Hughes3d30d9b2011-12-07 17:35:48 -08002803 LOG(WARNING) << "Chunk is too big to transmit (chunk_len=" << chunk_len << ", " << needed << " bytes)";
Elliott Hughesa2155262011-11-16 16:26:58 -08002804 return;
2805 }
2806 }
2807
2808 // OLD-TODO: notice when there's a gap and start a new heap, or at least a new range.
Elliott Hughes741c9fa2012-06-08 15:51:32 -07002809 EnsureHeader(start);
Elliott Hughesa2155262011-11-16 16:26:58 -08002810
2811 // Determine the type of this chunk.
2812 // OLD-TODO: if context.merge, see if this chunk is different from the last chunk.
2813 // If it's the same, we should combine them.
Ian Rogers30fab402012-01-23 15:43:46 -08002814 uint8_t state = ExamineObject(reinterpret_cast<const Object*>(user_ptr), (type_ == CHUNK_TYPE("NHSG")));
Elliott Hughesa2155262011-11-16 16:26:58 -08002815
2816 // Write out the chunk description.
2817 chunk_len /= ALLOCATION_UNIT_SIZE; // convert to allocation units
Ian Rogers30fab402012-01-23 15:43:46 -08002818 totalAllocationUnits_ += chunk_len;
Elliott Hughesa2155262011-11-16 16:26:58 -08002819 while (chunk_len > 256) {
Ian Rogers30fab402012-01-23 15:43:46 -08002820 *p_++ = state | HPSG_PARTIAL;
2821 *p_++ = 255; // length - 1
Elliott Hughesa2155262011-11-16 16:26:58 -08002822 chunk_len -= 256;
2823 }
Ian Rogers30fab402012-01-23 15:43:46 -08002824 *p_++ = state;
2825 *p_++ = chunk_len - 1;
Elliott Hughes6a5bd492011-10-28 14:33:57 -07002826 }
2827
Elliott Hughesa2155262011-11-16 16:26:58 -08002828 uint8_t ExamineObject(const Object* o, bool is_native_heap) {
2829 if (o == NULL) {
2830 return HPSG_STATE(SOLIDITY_FREE, 0);
2831 }
Elliott Hughes6a5bd492011-10-28 14:33:57 -07002832
Elliott Hughesa2155262011-11-16 16:26:58 -08002833 // It's an allocated chunk. Figure out what it is.
Elliott Hughes6a5bd492011-10-28 14:33:57 -07002834
Elliott Hughesa2155262011-11-16 16:26:58 -08002835 // If we're looking at the native heap, we'll just return
2836 // (SOLIDITY_HARD, KIND_NATIVE) for all allocated chunks.
Elliott Hughesb3bd5f02012-03-08 21:05:27 -08002837 if (is_native_heap || !Runtime::Current()->GetHeap()->IsLiveObjectLocked(o)) {
Elliott Hughesa2155262011-11-16 16:26:58 -08002838 return HPSG_STATE(SOLIDITY_HARD, KIND_NATIVE);
2839 }
2840
2841 Class* c = o->GetClass();
2842 if (c == NULL) {
2843 // The object was probably just created but hasn't been initialized yet.
2844 return HPSG_STATE(SOLIDITY_HARD, KIND_OBJECT);
2845 }
2846
Elliott Hughesb3bd5f02012-03-08 21:05:27 -08002847 if (!Runtime::Current()->GetHeap()->IsHeapAddress(c)) {
Elliott Hughes3d30d9b2011-12-07 17:35:48 -08002848 LOG(WARNING) << "Invalid class for managed heap object: " << o << " " << c;
Elliott Hughesa2155262011-11-16 16:26:58 -08002849 return HPSG_STATE(SOLIDITY_HARD, KIND_UNKNOWN);
2850 }
2851
2852 if (c->IsClassClass()) {
2853 return HPSG_STATE(SOLIDITY_HARD, KIND_CLASS_OBJECT);
2854 }
2855
2856 if (c->IsArrayClass()) {
2857 if (o->IsObjectArray()) {
2858 return HPSG_STATE(SOLIDITY_HARD, KIND_ARRAY_4);
2859 }
2860 switch (c->GetComponentSize()) {
2861 case 1: return HPSG_STATE(SOLIDITY_HARD, KIND_ARRAY_1);
2862 case 2: return HPSG_STATE(SOLIDITY_HARD, KIND_ARRAY_2);
2863 case 4: return HPSG_STATE(SOLIDITY_HARD, KIND_ARRAY_4);
2864 case 8: return HPSG_STATE(SOLIDITY_HARD, KIND_ARRAY_8);
2865 }
2866 }
2867
Elliott Hughes6a5bd492011-10-28 14:33:57 -07002868 return HPSG_STATE(SOLIDITY_HARD, KIND_OBJECT);
2869 }
2870
Ian Rogers30fab402012-01-23 15:43:46 -08002871 std::vector<uint8_t> buf_;
2872 uint8_t* p_;
2873 uint8_t* pieceLenField_;
2874 size_t totalAllocationUnits_;
2875 uint32_t type_;
2876 bool merge_;
2877 bool needHeader_;
2878
Elliott Hughesa2155262011-11-16 16:26:58 -08002879 DISALLOW_COPY_AND_ASSIGN(HeapChunkContext);
2880};
Elliott Hughes6a5bd492011-10-28 14:33:57 -07002881
2882void Dbg::DdmSendHeapSegments(bool native) {
2883 Dbg::HpsgWhen when;
2884 Dbg::HpsgWhat what;
2885 if (!native) {
2886 when = gDdmHpsgWhen;
2887 what = gDdmHpsgWhat;
2888 } else {
2889 when = gDdmNhsgWhen;
2890 what = gDdmNhsgWhat;
2891 }
2892 if (when == HPSG_WHEN_NEVER) {
2893 return;
2894 }
2895
2896 // Figure out what kind of chunks we'll be sending.
2897 CHECK(what == HPSG_WHAT_MERGED_OBJECTS || what == HPSG_WHAT_DISTINCT_OBJECTS) << static_cast<int>(what);
2898
2899 // First, send a heap start chunk.
2900 uint8_t heap_id[4];
2901 JDWP::Set4BE(&heap_id[0], 1); // Heap id (bogus; we only have one heap).
2902 Dbg::DdmSendChunk(native ? CHUNK_TYPE("NHST") : CHUNK_TYPE("HPST"), sizeof(heap_id), heap_id);
2903
2904 // Send a series of heap segment chunks.
Elliott Hughesa2155262011-11-16 16:26:58 -08002905 HeapChunkContext context((what == HPSG_WHAT_MERGED_OBJECTS), native);
2906 if (native) {
Ian Rogers30fab402012-01-23 15:43:46 -08002907 // TODO: enable when bionic has moved to dlmalloc 2.8.5
2908 // dlmalloc_inspect_all(HeapChunkContext::HeapChunkCallback, &context);
2909 UNIMPLEMENTED(WARNING) << "Native heap send heap segments";
Elliott Hughesa2155262011-11-16 16:26:58 -08002910 } else {
Elliott Hughesb3bd5f02012-03-08 21:05:27 -08002911 Heap* heap = Runtime::Current()->GetHeap();
Mathieu Chartierb062fdd2012-07-03 09:51:48 -07002912 typedef std::vector<Space*> SpaceVec;
2913 const SpaceVec& spaces = heap->GetSpaces();
2914 for (SpaceVec::const_iterator cur = spaces.begin(); cur != spaces.end(); ++cur) {
2915 if ((*cur)->IsAllocSpace()) {
2916 (*cur)->AsAllocSpace()->Walk(HeapChunkContext::HeapChunkCallback, &context);
2917 }
2918 }
Elliott Hughesa2155262011-11-16 16:26:58 -08002919 }
Elliott Hughes6a5bd492011-10-28 14:33:57 -07002920
2921 // Finally, send a heap end chunk.
2922 Dbg::DdmSendChunk(native ? CHUNK_TYPE("NHEN") : CHUNK_TYPE("HPEN"), sizeof(heap_id), heap_id);
Elliott Hughes767a1472011-10-26 18:49:02 -07002923}
2924
Elliott Hughes545a0642011-11-08 19:10:03 -08002925void Dbg::SetAllocTrackingEnabled(bool enabled) {
2926 MutexLock mu(gAllocTrackerLock);
2927 if (enabled) {
2928 if (recent_allocation_records_ == NULL) {
2929 LOG(INFO) << "Enabling alloc tracker (" << kNumAllocRecords << " entries, "
2930 << kMaxAllocRecordStackDepth << " frames --> "
2931 << (sizeof(AllocRecord) * kNumAllocRecords) << " bytes)";
2932 gAllocRecordHead = gAllocRecordCount = 0;
2933 recent_allocation_records_ = new AllocRecord[kNumAllocRecords];
2934 CHECK(recent_allocation_records_ != NULL);
2935 }
2936 } else {
2937 delete[] recent_allocation_records_;
2938 recent_allocation_records_ = NULL;
2939 }
2940}
2941
Ian Rogers0399dde2012-06-06 17:09:28 -07002942struct AllocRecordStackVisitor : public StackVisitor {
2943 AllocRecordStackVisitor(const ManagedStack* stack,
Ian Rogersca190662012-06-26 15:45:57 -07002944 const std::vector<TraceStackFrame>* trace_stack, AllocRecord* record)
Elliott Hughes08fc03a2012-06-26 17:34:00 -07002945 : StackVisitor(stack, trace_stack, NULL), record(record), depth(0) {}
Elliott Hughes545a0642011-11-08 19:10:03 -08002946
Ian Rogers0399dde2012-06-06 17:09:28 -07002947 bool VisitFrame() {
Elliott Hughes545a0642011-11-08 19:10:03 -08002948 if (depth >= kMaxAllocRecordStackDepth) {
Elliott Hughes530fa002012-03-12 11:44:49 -07002949 return false;
Elliott Hughes545a0642011-11-08 19:10:03 -08002950 }
Ian Rogers0399dde2012-06-06 17:09:28 -07002951 Method* m = GetMethod();
2952 if (!m->IsRuntimeMethod()) {
2953 record->stack[depth].method = m;
2954 record->stack[depth].dex_pc = GetDexPc();
Elliott Hughes530fa002012-03-12 11:44:49 -07002955 ++depth;
Elliott Hughes545a0642011-11-08 19:10:03 -08002956 }
Elliott Hughes530fa002012-03-12 11:44:49 -07002957 return true;
Elliott Hughes545a0642011-11-08 19:10:03 -08002958 }
2959
2960 ~AllocRecordStackVisitor() {
2961 // Clear out any unused stack trace elements.
2962 for (; depth < kMaxAllocRecordStackDepth; ++depth) {
2963 record->stack[depth].method = NULL;
Ian Rogers0399dde2012-06-06 17:09:28 -07002964 record->stack[depth].dex_pc = 0;
Elliott Hughes545a0642011-11-08 19:10:03 -08002965 }
2966 }
2967
2968 AllocRecord* record;
2969 size_t depth;
2970};
2971
2972void Dbg::RecordAllocation(Class* type, size_t byte_count) {
2973 Thread* self = Thread::Current();
2974 CHECK(self != NULL);
2975
2976 MutexLock mu(gAllocTrackerLock);
2977 if (recent_allocation_records_ == NULL) {
2978 return;
2979 }
2980
2981 // Advance and clip.
2982 if (++gAllocRecordHead == kNumAllocRecords) {
2983 gAllocRecordHead = 0;
2984 }
2985
2986 // Fill in the basics.
2987 AllocRecord* record = &recent_allocation_records_[gAllocRecordHead];
2988 record->type = type;
2989 record->byte_count = byte_count;
2990 record->thin_lock_id = self->GetThinLockId();
2991
2992 // Fill in the stack trace.
Ian Rogers0399dde2012-06-06 17:09:28 -07002993 AllocRecordStackVisitor visitor(self->GetManagedStack(), self->GetTraceStack(), record);
2994 visitor.WalkStack();
Elliott Hughes545a0642011-11-08 19:10:03 -08002995
2996 if (gAllocRecordCount < kNumAllocRecords) {
2997 ++gAllocRecordCount;
2998 }
2999}
3000
Elliott Hughesa8f93cb2012-06-08 17:08:48 -07003001// Returns the index of the head element.
3002//
3003// We point at the most-recently-written record, so if gAllocRecordCount is 1
3004// we want to use the current element. Take "head+1" and subtract count
3005// from it.
3006//
3007// We need to handle underflow in our circular buffer, so we add
3008// kNumAllocRecords and then mask it back down.
Elliott Hughesf8349362012-06-18 15:00:06 -07003009static inline int HeadIndex() EXCLUSIVE_LOCKS_REQUIRED(gAllocTrackerLock) {
Elliott Hughes545a0642011-11-08 19:10:03 -08003010 return (gAllocRecordHead+1 + kNumAllocRecords - gAllocRecordCount) & (kNumAllocRecords-1);
3011}
3012
3013void Dbg::DumpRecentAllocations() {
3014 MutexLock mu(gAllocTrackerLock);
3015 if (recent_allocation_records_ == NULL) {
3016 LOG(INFO) << "Not recording tracked allocations";
3017 return;
3018 }
3019
3020 // "i" is the head of the list. We want to start at the end of the
3021 // list and move forward to the tail.
Elliott Hughesa8f93cb2012-06-08 17:08:48 -07003022 size_t i = HeadIndex();
Elliott Hughes545a0642011-11-08 19:10:03 -08003023 size_t count = gAllocRecordCount;
3024
3025 LOG(INFO) << "Tracked allocations, (head=" << gAllocRecordHead << " count=" << count << ")";
3026 while (count--) {
3027 AllocRecord* record = &recent_allocation_records_[i];
3028
Elliott Hughesa8f93cb2012-06-08 17:08:48 -07003029 LOG(INFO) << StringPrintf(" Thread %-2d %6zd bytes ", record->thin_lock_id, record->byte_count)
Elliott Hughes545a0642011-11-08 19:10:03 -08003030 << PrettyClass(record->type);
3031
3032 for (size_t stack_frame = 0; stack_frame < kMaxAllocRecordStackDepth; ++stack_frame) {
3033 const Method* m = record->stack[stack_frame].method;
3034 if (m == NULL) {
3035 break;
3036 }
3037 LOG(INFO) << " " << PrettyMethod(m) << " line " << record->stack[stack_frame].LineNumber();
3038 }
3039
3040 // pause periodically to help logcat catch up
3041 if ((count % 5) == 0) {
3042 usleep(40000);
3043 }
3044
3045 i = (i + 1) & (kNumAllocRecords-1);
3046 }
3047}
3048
3049class StringTable {
3050 public:
3051 StringTable() {
3052 }
3053
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08003054 void Add(const char* s) {
Elliott Hughes545a0642011-11-08 19:10:03 -08003055 table_.insert(s);
3056 }
3057
Elliott Hughesa8f93cb2012-06-08 17:08:48 -07003058 size_t IndexOf(const char* s) const {
3059 typedef std::set<std::string>::const_iterator It; // TODO: C++0x auto
3060 It it = table_.find(s);
3061 if (it == table_.end()) {
3062 LOG(FATAL) << "IndexOf(\"" << s << "\") failed";
3063 }
3064 return std::distance(table_.begin(), it);
Elliott Hughes545a0642011-11-08 19:10:03 -08003065 }
3066
Elliott Hughesa8f93cb2012-06-08 17:08:48 -07003067 size_t Size() const {
Elliott Hughes545a0642011-11-08 19:10:03 -08003068 return table_.size();
3069 }
3070
Elliott Hughesa8f93cb2012-06-08 17:08:48 -07003071 void WriteTo(std::vector<uint8_t>& bytes) const {
3072 typedef std::set<std::string>::const_iterator It; // TODO: C++0x auto
Elliott Hughes545a0642011-11-08 19:10:03 -08003073 for (It it = table_.begin(); it != table_.end(); ++it) {
Elliott Hughesa8f93cb2012-06-08 17:08:48 -07003074 const char* s = (*it).c_str();
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08003075 size_t s_len = CountModifiedUtf8Chars(s);
3076 UniquePtr<uint16_t> s_utf16(new uint16_t[s_len]);
3077 ConvertModifiedUtf8ToUtf16(s_utf16.get(), s);
3078 JDWP::AppendUtf16BE(bytes, s_utf16.get(), s_len);
Elliott Hughes545a0642011-11-08 19:10:03 -08003079 }
3080 }
3081
3082 private:
Elliott Hughesa8f93cb2012-06-08 17:08:48 -07003083 std::set<std::string> table_;
Elliott Hughes545a0642011-11-08 19:10:03 -08003084 DISALLOW_COPY_AND_ASSIGN(StringTable);
3085};
3086
3087/*
3088 * The data we send to DDMS contains everything we have recorded.
3089 *
3090 * Message header (all values big-endian):
3091 * (1b) message header len (to allow future expansion); includes itself
3092 * (1b) entry header len
3093 * (1b) stack frame len
3094 * (2b) number of entries
3095 * (4b) offset to string table from start of message
3096 * (2b) number of class name strings
3097 * (2b) number of method name strings
3098 * (2b) number of source file name strings
3099 * For each entry:
3100 * (4b) total allocation size
3101 * (2b) threadId
3102 * (2b) allocated object's class name index
3103 * (1b) stack depth
3104 * For each stack frame:
3105 * (2b) method's class name
3106 * (2b) method name
3107 * (2b) method source file
3108 * (2b) line number, clipped to 32767; -2 if native; -1 if no source
3109 * (xb) class name strings
3110 * (xb) method name strings
3111 * (xb) source file strings
3112 *
3113 * As with other DDM traffic, strings are sent as a 4-byte length
3114 * followed by UTF-16 data.
3115 *
3116 * We send up 16-bit unsigned indexes into string tables. In theory there
3117 * can be (kMaxAllocRecordStackDepth * kNumAllocRecords) unique strings in
3118 * each table, but in practice there should be far fewer.
3119 *
3120 * The chief reason for using a string table here is to keep the size of
3121 * the DDMS message to a minimum. This is partly to make the protocol
3122 * efficient, but also because we have to form the whole thing up all at
3123 * once in a memory buffer.
3124 *
3125 * We use separate string tables for class names, method names, and source
3126 * files to keep the indexes small. There will generally be no overlap
3127 * between the contents of these tables.
3128 */
3129jbyteArray Dbg::GetRecentAllocations() {
3130 if (false) {
3131 DumpRecentAllocations();
3132 }
3133
3134 MutexLock mu(gAllocTrackerLock);
3135
Elliott Hughesa8f93cb2012-06-08 17:08:48 -07003136 //
3137 // Part 1: generate string tables.
3138 //
Elliott Hughes545a0642011-11-08 19:10:03 -08003139 StringTable class_names;
3140 StringTable method_names;
3141 StringTable filenames;
3142
3143 int count = gAllocRecordCount;
Elliott Hughesa8f93cb2012-06-08 17:08:48 -07003144 int idx = HeadIndex();
Elliott Hughes545a0642011-11-08 19:10:03 -08003145 while (count--) {
3146 AllocRecord* record = &recent_allocation_records_[idx];
3147
Elliott Hughes91250e02011-12-13 22:30:35 -08003148 class_names.Add(ClassHelper(record->type).GetDescriptor());
Elliott Hughes545a0642011-11-08 19:10:03 -08003149
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08003150 MethodHelper mh;
Elliott Hughes545a0642011-11-08 19:10:03 -08003151 for (size_t i = 0; i < kMaxAllocRecordStackDepth; i++) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08003152 Method* m = record->stack[i].method;
Elliott Hughes545a0642011-11-08 19:10:03 -08003153 if (m != NULL) {
Ian Rogersba377812012-05-28 21:16:29 -07003154 mh.ChangeMethod(m);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08003155 class_names.Add(mh.GetDeclaringClassDescriptor());
3156 method_names.Add(mh.GetName());
3157 filenames.Add(mh.GetDeclaringClassSourceFile());
Elliott Hughes545a0642011-11-08 19:10:03 -08003158 }
3159 }
3160
3161 idx = (idx + 1) & (kNumAllocRecords-1);
3162 }
3163
3164 LOG(INFO) << "allocation records: " << gAllocRecordCount;
3165
Elliott Hughesa8f93cb2012-06-08 17:08:48 -07003166 //
3167 // Part 2: allocate a buffer and generate the output.
3168 //
Elliott Hughes545a0642011-11-08 19:10:03 -08003169 std::vector<uint8_t> bytes;
3170
3171 // (1b) message header len (to allow future expansion); includes itself
3172 // (1b) entry header len
3173 // (1b) stack frame len
3174 const int kMessageHeaderLen = 15;
3175 const int kEntryHeaderLen = 9;
3176 const int kStackFrameLen = 8;
3177 JDWP::Append1BE(bytes, kMessageHeaderLen);
3178 JDWP::Append1BE(bytes, kEntryHeaderLen);
3179 JDWP::Append1BE(bytes, kStackFrameLen);
3180
3181 // (2b) number of entries
3182 // (4b) offset to string table from start of message
3183 // (2b) number of class name strings
3184 // (2b) number of method name strings
3185 // (2b) number of source file name strings
3186 JDWP::Append2BE(bytes, gAllocRecordCount);
3187 size_t string_table_offset = bytes.size();
3188 JDWP::Append4BE(bytes, 0); // We'll patch this later...
3189 JDWP::Append2BE(bytes, class_names.Size());
3190 JDWP::Append2BE(bytes, method_names.Size());
3191 JDWP::Append2BE(bytes, filenames.Size());
3192
3193 count = gAllocRecordCount;
Elliott Hughesa8f93cb2012-06-08 17:08:48 -07003194 idx = HeadIndex();
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08003195 ClassHelper kh;
Elliott Hughes545a0642011-11-08 19:10:03 -08003196 while (count--) {
3197 // For each entry:
3198 // (4b) total allocation size
3199 // (2b) thread id
3200 // (2b) allocated object's class name index
3201 // (1b) stack depth
3202 AllocRecord* record = &recent_allocation_records_[idx];
3203 size_t stack_depth = record->GetDepth();
Elliott Hughesa8f93cb2012-06-08 17:08:48 -07003204 kh.ChangeClass(record->type);
3205 size_t allocated_object_class_name_index = class_names.IndexOf(kh.GetDescriptor());
Elliott Hughes545a0642011-11-08 19:10:03 -08003206 JDWP::Append4BE(bytes, record->byte_count);
3207 JDWP::Append2BE(bytes, record->thin_lock_id);
Elliott Hughesa8f93cb2012-06-08 17:08:48 -07003208 JDWP::Append2BE(bytes, allocated_object_class_name_index);
Elliott Hughes545a0642011-11-08 19:10:03 -08003209 JDWP::Append1BE(bytes, stack_depth);
3210
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08003211 MethodHelper mh;
Elliott Hughes545a0642011-11-08 19:10:03 -08003212 for (size_t stack_frame = 0; stack_frame < stack_depth; ++stack_frame) {
3213 // For each stack frame:
3214 // (2b) method's class name
3215 // (2b) method name
3216 // (2b) method source file
3217 // (2b) line number, clipped to 32767; -2 if native; -1 if no source
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08003218 mh.ChangeMethod(record->stack[stack_frame].method);
Elliott Hughesa8f93cb2012-06-08 17:08:48 -07003219 size_t class_name_index = class_names.IndexOf(mh.GetDeclaringClassDescriptor());
3220 size_t method_name_index = method_names.IndexOf(mh.GetName());
3221 size_t file_name_index = filenames.IndexOf(mh.GetDeclaringClassSourceFile());
3222 JDWP::Append2BE(bytes, class_name_index);
3223 JDWP::Append2BE(bytes, method_name_index);
3224 JDWP::Append2BE(bytes, file_name_index);
Elliott Hughes545a0642011-11-08 19:10:03 -08003225 JDWP::Append2BE(bytes, record->stack[stack_frame].LineNumber());
3226 }
3227
3228 idx = (idx + 1) & (kNumAllocRecords-1);
3229 }
3230
3231 // (xb) class name strings
3232 // (xb) method name strings
3233 // (xb) source file strings
3234 JDWP::Set4BE(&bytes[string_table_offset], bytes.size());
3235 class_names.WriteTo(bytes);
3236 method_names.WriteTo(bytes);
3237 filenames.WriteTo(bytes);
3238
3239 JNIEnv* env = Thread::Current()->GetJniEnv();
3240 jbyteArray result = env->NewByteArray(bytes.size());
3241 if (result != NULL) {
3242 env->SetByteArrayRegion(result, 0, bytes.size(), reinterpret_cast<const jbyte*>(&bytes[0]));
3243 }
3244 return result;
3245}
3246
Elliott Hughes872d4ec2011-10-21 17:07:15 -07003247} // namespace art