blob: 158be0ba3c1c53a93124f7486cc3a37d4c2e2d9c [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"
Mathieu Chartier1c23e1e2012-10-12 14:14:11 -070026#include "gc/large_object_space.h"
27#include "gc/space.h"
Ian Rogers2bcb4a42012-11-08 10:39:18 -080028#include "oat/runtime/context.h"
Ian Rogers6d4d9fc2011-11-30 16:24:48 -080029#include "object_utils.h"
Elliott Hughesa0e18062012-04-13 15:59:59 -070030#include "safe_map.h"
Elliott Hughes6a5bd492011-10-28 14:33:57 -070031#include "ScopedLocalRef.h"
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -070032#include "ScopedPrimitiveArray.h"
Ian Rogers00f7d0e2012-07-19 15:28:27 -070033#include "scoped_thread_state_change.h"
Ian Rogers1f539342012-10-03 21:09:42 -070034#include "sirt_ref.h"
Elliott Hughes47fce012011-10-25 18:37:19 -070035#include "stack_indirect_reference_table.h"
Elliott Hughes475fc232011-10-25 15:00:35 -070036#include "thread_list.h"
Elliott Hugheseac76672012-05-24 21:56:51 -070037#include "well_known_classes.h"
Elliott Hughes475fc232011-10-25 15:00:35 -070038
Elliott Hughes872d4ec2011-10-21 17:07:15 -070039namespace art {
40
Elliott Hughes545a0642011-11-08 19:10:03 -080041static const size_t kMaxAllocRecordStackDepth = 16; // Max 255.
42static const size_t kNumAllocRecords = 512; // Must be power of 2.
43
Elliott Hughes436e3722012-02-17 20:01:47 -080044static const uintptr_t kInvalidId = 1;
45static const Object* kInvalidObject = reinterpret_cast<Object*>(kInvalidId);
46
Elliott Hughes475fc232011-10-25 15:00:35 -070047class ObjectRegistry {
48 public:
49 ObjectRegistry() : lock_("ObjectRegistry lock") {
50 }
51
52 JDWP::ObjectId Add(Object* o) {
53 if (o == NULL) {
54 return 0;
55 }
56 JDWP::ObjectId id = static_cast<JDWP::ObjectId>(reinterpret_cast<uintptr_t>(o));
Ian Rogers50b35e22012-10-04 10:09:15 -070057 MutexLock mu(Thread::Current(), lock_);
Elliott Hughesa0e18062012-04-13 15:59:59 -070058 map_.Overwrite(id, o);
Elliott Hughes475fc232011-10-25 15:00:35 -070059 return id;
60 }
61
Elliott Hughes234ab152011-10-26 14:02:26 -070062 void Clear() {
Ian Rogers50b35e22012-10-04 10:09:15 -070063 MutexLock mu(Thread::Current(), lock_);
Elliott Hughes234ab152011-10-26 14:02:26 -070064 LOG(DEBUG) << "Debugger has detached; object registry had " << map_.size() << " entries";
65 map_.clear();
66 }
67
Elliott Hughes475fc232011-10-25 15:00:35 -070068 bool Contains(JDWP::ObjectId id) {
Ian Rogers50b35e22012-10-04 10:09:15 -070069 MutexLock mu(Thread::Current(), lock_);
Elliott Hughes475fc232011-10-25 15:00:35 -070070 return map_.find(id) != map_.end();
71 }
72
Elliott Hughesa2155262011-11-16 16:26:58 -080073 template<typename T> T Get(JDWP::ObjectId id) {
Elliott Hughes436e3722012-02-17 20:01:47 -080074 if (id == 0) {
75 return NULL;
76 }
77
Ian Rogers50b35e22012-10-04 10:09:15 -070078 MutexLock mu(Thread::Current(), lock_);
Elliott Hughesa0e18062012-04-13 15:59:59 -070079 typedef SafeMap<JDWP::ObjectId, Object*>::iterator It; // C++0x auto
Elliott Hughesa2155262011-11-16 16:26:58 -080080 It it = map_.find(id);
Elliott Hughes436e3722012-02-17 20:01:47 -080081 return (it != map_.end()) ? reinterpret_cast<T>(it->second) : reinterpret_cast<T>(kInvalidId);
Elliott Hughesa2155262011-11-16 16:26:58 -080082 }
83
Elliott Hughesbfe487b2011-10-26 15:48:55 -070084 void VisitRoots(Heap::RootVisitor* visitor, void* arg) {
Ian Rogers50b35e22012-10-04 10:09:15 -070085 MutexLock mu(Thread::Current(), lock_);
Elliott Hughesa0e18062012-04-13 15:59:59 -070086 typedef SafeMap<JDWP::ObjectId, Object*>::iterator It; // C++0x auto
Elliott Hughesbfe487b2011-10-26 15:48:55 -070087 for (It it = map_.begin(); it != map_.end(); ++it) {
88 visitor(it->second, arg);
89 }
90 }
91
Elliott Hughes475fc232011-10-25 15:00:35 -070092 private:
Ian Rogers00f7d0e2012-07-19 15:28:27 -070093 Mutex lock_ DEFAULT_MUTEX_ACQUIRED_AFTER;
Elliott Hughesa0e18062012-04-13 15:59:59 -070094 SafeMap<JDWP::ObjectId, Object*> map_;
Elliott Hughes475fc232011-10-25 15:00:35 -070095};
96
Elliott Hughes545a0642011-11-08 19:10:03 -080097struct AllocRecordStackTraceElement {
Mathieu Chartier66f19252012-09-18 08:57:04 -070098 AbstractMethod* method;
Ian Rogers0399dde2012-06-06 17:09:28 -070099 uint32_t dex_pc;
Elliott Hughes545a0642011-11-08 19:10:03 -0800100
Ian Rogersb726dcb2012-09-05 08:57:23 -0700101 int32_t LineNumber() const SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Ian Rogers0399dde2012-06-06 17:09:28 -0700102 return MethodHelper(method).GetLineNumFromDexPC(dex_pc);
Elliott Hughes545a0642011-11-08 19:10:03 -0800103 }
104};
105
106struct AllocRecord {
107 Class* type;
108 size_t byte_count;
109 uint16_t thin_lock_id;
110 AllocRecordStackTraceElement stack[kMaxAllocRecordStackDepth]; // Unused entries have NULL method.
111
112 size_t GetDepth() {
113 size_t depth = 0;
114 while (depth < kMaxAllocRecordStackDepth && stack[depth].method != NULL) {
115 ++depth;
116 }
117 return depth;
118 }
119};
120
Elliott Hughes86964332012-02-15 19:37:42 -0800121struct Breakpoint {
Mathieu Chartier66f19252012-09-18 08:57:04 -0700122 AbstractMethod* method;
Elliott Hughesa656a0f2012-02-21 18:03:44 -0800123 uint32_t dex_pc;
Mathieu Chartier66f19252012-09-18 08:57:04 -0700124 Breakpoint(AbstractMethod* method, uint32_t dex_pc) : method(method), dex_pc(dex_pc) {}
Elliott Hughes86964332012-02-15 19:37:42 -0800125};
126
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700127static std::ostream& operator<<(std::ostream& os, const Breakpoint& rhs)
Ian Rogersb726dcb2012-09-05 08:57:23 -0700128 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
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
Mathieu Chartier66f19252012-09-18 08:57:04 -0700141 const AbstractMethod* 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.
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700174static Mutex gAllocTrackerLock DEFAULT_MUTEX_ACQUIRED_AFTER ("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.
jeffhao09bfc6a2012-12-11 18:11:43 -0800180static std::vector<Breakpoint> gBreakpoints GUARDED_BY(Locks::breakpoint_lock_);
181static SingleStepControl gSingleStepControl GUARDED_BY(Locks::breakpoint_lock_);
Elliott Hughes86964332012-02-15 19:37:42 -0800182
Mathieu Chartier66f19252012-09-18 08:57:04 -0700183static bool IsBreakpoint(AbstractMethod* m, uint32_t dex_pc)
jeffhao09bfc6a2012-12-11 18:11:43 -0800184 LOCKS_EXCLUDED(Locks::breakpoint_lock_)
Ian Rogersb726dcb2012-09-05 08:57:23 -0700185 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
jeffhao09bfc6a2012-12-11 18:11:43 -0800186 MutexLock mu(Thread::Current(), *Locks::breakpoint_lock_);
Elliott Hughes86964332012-02-15 19:37:42 -0800187 for (size_t i = 0; i < gBreakpoints.size(); ++i) {
Elliott Hughesa656a0f2012-02-21 18:03:44 -0800188 if (gBreakpoints[i].method == m && gBreakpoints[i].dex_pc == dex_pc) {
Elliott Hughes86964332012-02-15 19:37:42 -0800189 VLOG(jdwp) << "Hit breakpoint #" << i << ": " << gBreakpoints[i];
190 return true;
191 }
192 }
193 return false;
194}
195
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700196static Array* DecodeArray(JDWP::RefTypeId id, JDWP::JdwpError& status)
Ian Rogersb726dcb2012-09-05 08:57:23 -0700197 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Elliott Hughes436e3722012-02-17 20:01:47 -0800198 Object* o = gRegistry->Get<Object*>(id);
199 if (o == NULL || o == kInvalidObject) {
200 status = JDWP::ERR_INVALID_OBJECT;
201 return NULL;
202 }
203 if (!o->IsArrayInstance()) {
204 status = JDWP::ERR_INVALID_ARRAY;
205 return NULL;
206 }
207 status = JDWP::ERR_NONE;
208 return o->AsArray();
209}
210
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700211static Class* DecodeClass(JDWP::RefTypeId id, JDWP::JdwpError& status)
Ian Rogersb726dcb2012-09-05 08:57:23 -0700212 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Elliott Hughes436e3722012-02-17 20:01:47 -0800213 Object* o = gRegistry->Get<Object*>(id);
214 if (o == NULL || o == kInvalidObject) {
215 status = JDWP::ERR_INVALID_OBJECT;
216 return NULL;
217 }
218 if (!o->IsClass()) {
219 status = JDWP::ERR_INVALID_CLASS;
220 return NULL;
221 }
222 status = JDWP::ERR_NONE;
223 return o->AsClass();
224}
225
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700226static Thread* DecodeThread(ScopedObjectAccessUnchecked& soa, JDWP::ObjectId threadId)
jeffhaoa77f0f62012-12-05 17:19:31 -0800227 EXCLUSIVE_LOCKS_REQUIRED(Locks::thread_list_lock_)
Ian Rogersb726dcb2012-09-05 08:57:23 -0700228 LOCKS_EXCLUDED(Locks::thread_suspend_count_lock_)
229 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Elliott Hughes436e3722012-02-17 20:01:47 -0800230 Object* thread_peer = gRegistry->Get<Object*>(threadId);
231 if (thread_peer == NULL || thread_peer == kInvalidObject) {
232 return NULL;
233 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700234 Thread* thread = Thread::FromManagedThread(soa, thread_peer);
235 return thread;
Elliott Hughes436e3722012-02-17 20:01:47 -0800236}
237
Elliott Hughes24437992011-11-30 14:49:33 -0800238static JDWP::JdwpTag BasicTagFromDescriptor(const char* descriptor) {
239 // JDWP deliberately uses the descriptor characters' ASCII values for its enum.
240 // Note that by "basic" we mean that we don't get more specific than JT_OBJECT.
241 return static_cast<JDWP::JdwpTag>(descriptor[0]);
242}
243
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700244static JDWP::JdwpTag TagFromClass(Class* c)
Ian Rogersb726dcb2012-09-05 08:57:23 -0700245 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Elliott Hughes86b00102011-12-05 17:54:26 -0800246 CHECK(c != NULL);
Elliott Hughes24437992011-11-30 14:49:33 -0800247 if (c->IsArrayClass()) {
248 return JDWP::JT_ARRAY;
249 }
250
Elliott Hughes3d30d9b2011-12-07 17:35:48 -0800251 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
Elliott Hughes24437992011-11-30 14:49:33 -0800252 if (c->IsStringClass()) {
253 return JDWP::JT_STRING;
254 } else if (c->IsClassClass()) {
255 return JDWP::JT_CLASS_OBJECT;
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -0800256 } else if (class_linker->FindSystemClass("Ljava/lang/Thread;")->IsAssignableFrom(c)) {
Elliott Hughes24437992011-11-30 14:49:33 -0800257 return JDWP::JT_THREAD;
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -0800258 } else if (class_linker->FindSystemClass("Ljava/lang/ThreadGroup;")->IsAssignableFrom(c)) {
Elliott Hughes24437992011-11-30 14:49:33 -0800259 return JDWP::JT_THREAD_GROUP;
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -0800260 } else if (class_linker->FindSystemClass("Ljava/lang/ClassLoader;")->IsAssignableFrom(c)) {
Elliott Hughes24437992011-11-30 14:49:33 -0800261 return JDWP::JT_CLASS_LOADER;
Elliott Hughes24437992011-11-30 14:49:33 -0800262 } else {
263 return JDWP::JT_OBJECT;
264 }
265}
266
267/*
268 * Objects declared to hold Object might actually hold a more specific
269 * type. The debugger may take a special interest in these (e.g. it
270 * wants to display the contents of Strings), so we want to return an
271 * appropriate tag.
272 *
273 * Null objects are tagged JT_OBJECT.
274 */
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700275static JDWP::JdwpTag TagFromObject(const Object* o)
Ian Rogersb726dcb2012-09-05 08:57:23 -0700276 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Elliott Hughes24437992011-11-30 14:49:33 -0800277 return (o == NULL) ? JDWP::JT_OBJECT : TagFromClass(o->GetClass());
278}
279
280static bool IsPrimitiveTag(JDWP::JdwpTag tag) {
281 switch (tag) {
282 case JDWP::JT_BOOLEAN:
283 case JDWP::JT_BYTE:
284 case JDWP::JT_CHAR:
285 case JDWP::JT_FLOAT:
286 case JDWP::JT_DOUBLE:
287 case JDWP::JT_INT:
288 case JDWP::JT_LONG:
289 case JDWP::JT_SHORT:
290 case JDWP::JT_VOID:
291 return true;
292 default:
293 return false;
294 }
295}
296
Elliott Hughes3bb81562011-10-21 18:52:59 -0700297/*
298 * Handle one of the JDWP name/value pairs.
299 *
300 * JDWP options are:
301 * help: if specified, show help message and bail
302 * transport: may be dt_socket or dt_shmem
303 * address: for dt_socket, "host:port", or just "port" when listening
304 * server: if "y", wait for debugger to attach; if "n", attach to debugger
305 * timeout: how long to wait for debugger to connect / listen
306 *
307 * Useful with server=n (these aren't supported yet):
308 * onthrow=<exception-name>: connect to debugger when exception thrown
309 * onuncaught=y|n: connect to debugger when uncaught exception thrown
310 * launch=<command-line>: launch the debugger itself
311 *
312 * The "transport" option is required, as is "address" if server=n.
313 */
314static bool ParseJdwpOption(const std::string& name, const std::string& value) {
315 if (name == "transport") {
316 if (value == "dt_socket") {
Elliott Hughes376a7a02011-10-24 18:35:55 -0700317 gJdwpOptions.transport = JDWP::kJdwpTransportSocket;
Elliott Hughes3bb81562011-10-21 18:52:59 -0700318 } else if (value == "dt_android_adb") {
Elliott Hughes376a7a02011-10-24 18:35:55 -0700319 gJdwpOptions.transport = JDWP::kJdwpTransportAndroidAdb;
Elliott Hughes3bb81562011-10-21 18:52:59 -0700320 } else {
321 LOG(ERROR) << "JDWP transport not supported: " << value;
322 return false;
323 }
324 } else if (name == "server") {
325 if (value == "n") {
Elliott Hughes376a7a02011-10-24 18:35:55 -0700326 gJdwpOptions.server = false;
Elliott Hughes3bb81562011-10-21 18:52:59 -0700327 } else if (value == "y") {
Elliott Hughes376a7a02011-10-24 18:35:55 -0700328 gJdwpOptions.server = true;
Elliott Hughes3bb81562011-10-21 18:52:59 -0700329 } else {
330 LOG(ERROR) << "JDWP option 'server' must be 'y' or 'n'";
331 return false;
332 }
333 } else if (name == "suspend") {
334 if (value == "n") {
Elliott Hughes376a7a02011-10-24 18:35:55 -0700335 gJdwpOptions.suspend = false;
Elliott Hughes3bb81562011-10-21 18:52:59 -0700336 } else if (value == "y") {
Elliott Hughes376a7a02011-10-24 18:35:55 -0700337 gJdwpOptions.suspend = true;
Elliott Hughes3bb81562011-10-21 18:52:59 -0700338 } else {
339 LOG(ERROR) << "JDWP option 'suspend' must be 'y' or 'n'";
340 return false;
341 }
342 } else if (name == "address") {
343 /* this is either <port> or <host>:<port> */
344 std::string port_string;
Elliott Hughes376a7a02011-10-24 18:35:55 -0700345 gJdwpOptions.host.clear();
Elliott Hughes3bb81562011-10-21 18:52:59 -0700346 std::string::size_type colon = value.find(':');
347 if (colon != std::string::npos) {
Elliott Hughes376a7a02011-10-24 18:35:55 -0700348 gJdwpOptions.host = value.substr(0, colon);
Elliott Hughes3bb81562011-10-21 18:52:59 -0700349 port_string = value.substr(colon + 1);
350 } else {
351 port_string = value;
352 }
353 if (port_string.empty()) {
354 LOG(ERROR) << "JDWP address missing port: " << value;
355 return false;
356 }
357 char* end;
Elliott Hughesba8eee12012-01-24 20:25:24 -0800358 uint64_t port = strtoul(port_string.c_str(), &end, 10);
359 if (*end != '\0' || port > 0xffff) {
Elliott Hughes3bb81562011-10-21 18:52:59 -0700360 LOG(ERROR) << "JDWP address has junk in port field: " << value;
361 return false;
362 }
Elliott Hughes376a7a02011-10-24 18:35:55 -0700363 gJdwpOptions.port = port;
Elliott Hughes3bb81562011-10-21 18:52:59 -0700364 } else if (name == "launch" || name == "onthrow" || name == "oncaught" || name == "timeout") {
365 /* valid but unsupported */
366 LOG(INFO) << "Ignoring JDWP option '" << name << "'='" << value << "'";
367 } else {
368 LOG(INFO) << "Ignoring unrecognized JDWP option '" << name << "'='" << value << "'";
369 }
370
371 return true;
372}
373
374/*
375 * Parse the latter half of a -Xrunjdwp/-agentlib:jdwp= string, e.g.:
376 * "transport=dt_socket,address=8000,server=y,suspend=n"
377 */
378bool Dbg::ParseJdwpOptions(const std::string& options) {
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -0800379 VLOG(jdwp) << "ParseJdwpOptions: " << options;
Elliott Hughes47fce012011-10-25 18:37:19 -0700380
Elliott Hughes3bb81562011-10-21 18:52:59 -0700381 std::vector<std::string> pairs;
382 Split(options, ',', pairs);
383
384 for (size_t i = 0; i < pairs.size(); ++i) {
385 std::string::size_type equals = pairs[i].find('=');
386 if (equals == std::string::npos) {
387 LOG(ERROR) << "Can't parse JDWP option '" << pairs[i] << "' in '" << options << "'";
388 return false;
389 }
390 ParseJdwpOption(pairs[i].substr(0, equals), pairs[i].substr(equals + 1));
391 }
392
Elliott Hughes376a7a02011-10-24 18:35:55 -0700393 if (gJdwpOptions.transport == JDWP::kJdwpTransportUnknown) {
Elliott Hughes3bb81562011-10-21 18:52:59 -0700394 LOG(ERROR) << "Must specify JDWP transport: " << options;
395 }
Elliott Hughes376a7a02011-10-24 18:35:55 -0700396 if (!gJdwpOptions.server && (gJdwpOptions.host.empty() || gJdwpOptions.port == 0)) {
Elliott Hughes3bb81562011-10-21 18:52:59 -0700397 LOG(ERROR) << "Must specify JDWP host and port when server=n: " << options;
398 return false;
399 }
400
401 gJdwpConfigured = true;
402 return true;
403}
404
Elliott Hughesd1cc8362011-10-24 16:58:50 -0700405void Dbg::StartJdwp() {
Elliott Hughesc0f09332012-03-26 13:27:06 -0700406 if (!gJdwpAllowed || !IsJdwpConfigured()) {
Elliott Hughes376a7a02011-10-24 18:35:55 -0700407 // No JDWP for you!
408 return;
409 }
410
Elliott Hughes475fc232011-10-25 15:00:35 -0700411 CHECK(gRegistry == NULL);
412 gRegistry = new ObjectRegistry;
413
Elliott Hughesd1cc8362011-10-24 16:58:50 -0700414 // Init JDWP if the debugger is enabled. This may connect out to a
415 // debugger, passively listen for a debugger, or block waiting for a
416 // debugger.
Elliott Hughes376a7a02011-10-24 18:35:55 -0700417 gJdwpState = JDWP::JdwpState::Create(&gJdwpOptions);
418 if (gJdwpState == NULL) {
Elliott Hughesf8a2df72011-12-01 12:19:54 -0800419 // We probably failed because some other process has the port already, which means that
420 // if we don't abort the user is likely to think they're talking to us when they're actually
421 // talking to that other process.
Elliott Hughes3d30d9b2011-12-07 17:35:48 -0800422 LOG(FATAL) << "Debugger thread failed to initialize";
Elliott Hughesd1cc8362011-10-24 16:58:50 -0700423 }
424
425 // If a debugger has already attached, send the "welcome" message.
426 // This may cause us to suspend all threads.
Elliott Hughes376a7a02011-10-24 18:35:55 -0700427 if (gJdwpState->IsActive()) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700428 ScopedObjectAccess soa(Thread::Current());
Elliott Hughes376a7a02011-10-24 18:35:55 -0700429 if (!gJdwpState->PostVMStart()) {
Elliott Hughes3d30d9b2011-12-07 17:35:48 -0800430 LOG(WARNING) << "Failed to post 'start' message to debugger";
Elliott Hughesd1cc8362011-10-24 16:58:50 -0700431 }
432 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700433}
434
Elliott Hughesd1cc8362011-10-24 16:58:50 -0700435void Dbg::StopJdwp() {
Elliott Hughes376a7a02011-10-24 18:35:55 -0700436 delete gJdwpState;
Elliott Hughes475fc232011-10-25 15:00:35 -0700437 delete gRegistry;
438 gRegistry = NULL;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700439}
440
Elliott Hughes767a1472011-10-26 18:49:02 -0700441void Dbg::GcDidFinish() {
442 if (gDdmHpifWhen != HPIF_WHEN_NEVER) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700443 ScopedObjectAccess soa(Thread::Current());
Elliott Hughes81ff3182012-03-23 20:35:56 -0700444 LOG(DEBUG) << "Sending heap info to DDM";
Elliott Hughes7162ad92011-10-27 14:08:42 -0700445 DdmSendHeapInfo(gDdmHpifWhen);
Elliott Hughes767a1472011-10-26 18:49:02 -0700446 }
447 if (gDdmHpsgWhen != HPSG_WHEN_NEVER) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700448 ScopedObjectAccess soa(Thread::Current());
Elliott Hughes81ff3182012-03-23 20:35:56 -0700449 LOG(DEBUG) << "Dumping heap to DDM";
Elliott Hughes6a5bd492011-10-28 14:33:57 -0700450 DdmSendHeapSegments(false);
Elliott Hughes767a1472011-10-26 18:49:02 -0700451 }
452 if (gDdmNhsgWhen != HPSG_WHEN_NEVER) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700453 ScopedObjectAccess soa(Thread::Current());
Elliott Hughes767a1472011-10-26 18:49:02 -0700454 LOG(DEBUG) << "Dumping native heap to DDM";
Elliott Hughes6a5bd492011-10-28 14:33:57 -0700455 DdmSendHeapSegments(true);
Elliott Hughes767a1472011-10-26 18:49:02 -0700456 }
457}
458
Elliott Hughes4ffd3132011-10-24 12:06:42 -0700459void Dbg::SetJdwpAllowed(bool allowed) {
460 gJdwpAllowed = allowed;
461}
462
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700463DebugInvokeReq* Dbg::GetInvokeReq() {
Elliott Hughes475fc232011-10-25 15:00:35 -0700464 return Thread::Current()->GetInvokeReq();
465}
466
467Thread* Dbg::GetDebugThread() {
468 return (gJdwpState != NULL) ? gJdwpState->GetDebugThread() : NULL;
469}
470
471void Dbg::ClearWaitForEventThread() {
472 gJdwpState->ClearWaitForEventThread();
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700473}
474
475void Dbg::Connected() {
Elliott Hughes3bb81562011-10-21 18:52:59 -0700476 CHECK(!gDebuggerConnected);
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -0800477 VLOG(jdwp) << "JDWP has attached";
Elliott Hughes3bb81562011-10-21 18:52:59 -0700478 gDebuggerConnected = true;
Elliott Hughes86964332012-02-15 19:37:42 -0800479 gDisposed = false;
480}
481
482void Dbg::Disposed() {
483 gDisposed = true;
484}
485
486bool Dbg::IsDisposed() {
487 return gDisposed;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700488}
489
Elliott Hughesc0f09332012-03-26 13:27:06 -0700490static void SetDebuggerUpdatesEnabledCallback(Thread* t, void* user_data) {
491 t->SetDebuggerUpdatesEnabled(*reinterpret_cast<bool*>(user_data));
492}
493
494static void SetDebuggerUpdatesEnabled(bool enabled) {
Ian Rogers50b35e22012-10-04 10:09:15 -0700495 MutexLock mu(Thread::Current(), *Locks::thread_list_lock_);
Elliott Hughesf8349362012-06-18 15:00:06 -0700496 Runtime::Current()->GetThreadList()->ForEach(SetDebuggerUpdatesEnabledCallback, &enabled);
Elliott Hughesc0f09332012-03-26 13:27:06 -0700497}
498
Elliott Hughesa2155262011-11-16 16:26:58 -0800499void Dbg::GoActive() {
500 // Enable all debugging features, including scans for breakpoints.
501 // This is a no-op if we're already active.
502 // Only called from the JDWP handler thread.
503 if (gDebuggerActive) {
504 return;
505 }
506
507 LOG(INFO) << "Debugger is active";
508
Elliott Hughesc0f09332012-03-26 13:27:06 -0700509 {
510 // TODO: dalvik only warned if there were breakpoints left over. clear in Dbg::Disconnected?
jeffhao09bfc6a2012-12-11 18:11:43 -0800511 MutexLock mu(Thread::Current(), *Locks::breakpoint_lock_);
Elliott Hughesc0f09332012-03-26 13:27:06 -0700512 CHECK_EQ(gBreakpoints.size(), 0U);
513 }
Elliott Hughesa2155262011-11-16 16:26:58 -0800514
515 gDebuggerActive = true;
Elliott Hughesc0f09332012-03-26 13:27:06 -0700516 SetDebuggerUpdatesEnabled(true);
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700517}
518
519void Dbg::Disconnected() {
Elliott Hughes234ab152011-10-26 14:02:26 -0700520 CHECK(gDebuggerConnected);
521
Elliott Hughesc0f09332012-03-26 13:27:06 -0700522 LOG(INFO) << "Debugger is no longer active";
Elliott Hughes234ab152011-10-26 14:02:26 -0700523
Elliott Hughesc0f09332012-03-26 13:27:06 -0700524 gDebuggerActive = false;
525 SetDebuggerUpdatesEnabled(false);
Elliott Hughes234ab152011-10-26 14:02:26 -0700526
527 gRegistry->Clear();
528 gDebuggerConnected = false;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700529}
530
Elliott Hughesc0f09332012-03-26 13:27:06 -0700531bool Dbg::IsDebuggerActive() {
Elliott Hughes3bb81562011-10-21 18:52:59 -0700532 return gDebuggerActive;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700533}
534
Elliott Hughesc0f09332012-03-26 13:27:06 -0700535bool Dbg::IsJdwpConfigured() {
Elliott Hughes3bb81562011-10-21 18:52:59 -0700536 return gJdwpConfigured;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700537}
538
539int64_t Dbg::LastDebuggerActivity() {
Elliott Hughesca951522011-12-05 12:01:32 -0800540 return gJdwpState->LastDebuggerActivity();
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700541}
542
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700543void 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
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700832JDWP::JdwpError Dbg::SetArrayElements(JDWP::ObjectId arrayId, int offset, int count,
833 const uint8_t* src)
Ian Rogersb726dcb2012-09-05 08:57:23 -0700834 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -0800835 JDWP::JdwpError status;
836 Array* a = DecodeArray(arrayId, status);
837 if (a == NULL) {
838 return status;
839 }
Elliott Hughesf03b8f62011-12-02 14:26:25 -0800840
841 if (offset < 0 || count < 0 || offset > a->GetLength() || a->GetLength() - offset < count) {
842 LOG(WARNING) << __FUNCTION__ << " access out of bounds: offset=" << offset << "; count=" << count;
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -0800843 return JDWP::ERR_INVALID_LENGTH;
Elliott Hughesf03b8f62011-12-02 14:26:25 -0800844 }
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800845 std::string descriptor(ClassHelper(a->GetClass()).GetDescriptor());
Elliott Hughesf03b8f62011-12-02 14:26:25 -0800846 JDWP::JdwpTag tag = BasicTagFromDescriptor(descriptor.c_str() + 1);
847
848 if (IsPrimitiveTag(tag)) {
849 size_t width = GetTagWidth(tag);
Elliott Hughesf03b8f62011-12-02 14:26:25 -0800850 if (width == 8) {
Ian Rogersa15e67d2012-02-28 13:51:55 -0800851 uint8_t* dst = &(reinterpret_cast<uint8_t*>(a->GetRawData(sizeof(uint64_t)))[offset * width]);
Elliott Hughesf03b8f62011-12-02 14:26:25 -0800852 for (int i = 0; i < count; ++i) {
853 // Handle potentially non-aligned memory access one byte at a time for ARM's benefit.
854 uint64_t value;
855 for (size_t j = 0; j < sizeof(uint64_t); ++j) reinterpret_cast<uint8_t*>(&value)[j] = src[j];
856 src += sizeof(uint64_t);
857 JDWP::Write8BE(&dst, value);
858 }
859 } else if (width == 4) {
Ian Rogersa15e67d2012-02-28 13:51:55 -0800860 uint8_t* dst = &(reinterpret_cast<uint8_t*>(a->GetRawData(sizeof(uint32_t)))[offset * width]);
Elliott Hughesf03b8f62011-12-02 14:26:25 -0800861 const uint32_t* src4 = reinterpret_cast<const uint32_t*>(src);
862 for (int i = 0; i < count; ++i) JDWP::Write4BE(&dst, src4[i]);
863 } else if (width == 2) {
Ian Rogersa15e67d2012-02-28 13:51:55 -0800864 uint8_t* dst = &(reinterpret_cast<uint8_t*>(a->GetRawData(sizeof(uint16_t)))[offset * width]);
Elliott Hughesf03b8f62011-12-02 14:26:25 -0800865 const uint16_t* src2 = reinterpret_cast<const uint16_t*>(src);
866 for (int i = 0; i < count; ++i) JDWP::Write2BE(&dst, src2[i]);
867 } else {
Ian Rogersa15e67d2012-02-28 13:51:55 -0800868 uint8_t* dst = &(reinterpret_cast<uint8_t*>(a->GetRawData(sizeof(uint8_t)))[offset * width]);
Elliott Hughesf03b8f62011-12-02 14:26:25 -0800869 memcpy(&dst[offset * width], src, count * width);
870 }
871 } else {
872 ObjectArray<Object>* oa = a->AsObjectArray<Object>();
873 for (int i = 0; i < count; ++i) {
874 JDWP::ObjectId id = JDWP::ReadObjectId(&src);
Elliott Hughes436e3722012-02-17 20:01:47 -0800875 Object* o = gRegistry->Get<Object*>(id);
876 if (o == kInvalidObject) {
877 return JDWP::ERR_INVALID_OBJECT;
878 }
879 oa->Set(offset + i, o);
Elliott Hughesf03b8f62011-12-02 14:26:25 -0800880 }
881 }
882
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -0800883 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700884}
885
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -0800886JDWP::ObjectId Dbg::CreateString(const std::string& str) {
Ian Rogers50b35e22012-10-04 10:09:15 -0700887 return gRegistry->Add(String::AllocFromModifiedUtf8(Thread::Current(), str.c_str()));
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700888}
889
Elliott Hughes436e3722012-02-17 20:01:47 -0800890JDWP::JdwpError Dbg::CreateObject(JDWP::RefTypeId classId, JDWP::ObjectId& new_object) {
891 JDWP::JdwpError status;
892 Class* c = DecodeClass(classId, status);
893 if (c == NULL) {
894 return status;
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -0800895 }
Ian Rogers50b35e22012-10-04 10:09:15 -0700896 new_object = gRegistry->Add(c->AllocObject(Thread::Current()));
Elliott Hughes436e3722012-02-17 20:01:47 -0800897 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700898}
899
Elliott Hughesbf13d362011-12-08 15:51:37 -0800900/*
901 * Used by Eclipse's "Display" view to evaluate "new byte[5]" to get "(byte[]) [0, 0, 0, 0, 0]".
902 */
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700903JDWP::JdwpError Dbg::CreateArrayObject(JDWP::RefTypeId arrayClassId, uint32_t length,
904 JDWP::ObjectId& new_array) {
Elliott Hughes436e3722012-02-17 20:01:47 -0800905 JDWP::JdwpError status;
906 Class* c = DecodeClass(arrayClassId, status);
907 if (c == NULL) {
908 return status;
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -0800909 }
Ian Rogers50b35e22012-10-04 10:09:15 -0700910 new_array = gRegistry->Add(Array::Alloc(Thread::Current(), c, length));
Elliott Hughes436e3722012-02-17 20:01:47 -0800911 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700912}
913
914bool Dbg::MatchType(JDWP::RefTypeId instClassId, JDWP::RefTypeId classId) {
Elliott Hughes436e3722012-02-17 20:01:47 -0800915 JDWP::JdwpError status;
916 Class* c1 = DecodeClass(instClassId, status);
Elliott Hughesa656a0f2012-02-21 18:03:44 -0800917 CHECK(c1 != NULL);
Elliott Hughes436e3722012-02-17 20:01:47 -0800918 Class* c2 = DecodeClass(classId, status);
Elliott Hughesa656a0f2012-02-21 18:03:44 -0800919 CHECK(c2 != NULL);
920 return c1->IsAssignableFrom(c2);
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700921}
922
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700923static JDWP::FieldId ToFieldId(const Field* f)
Ian Rogersb726dcb2012-09-05 08:57:23 -0700924 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Elliott Hughes03181a82011-11-17 17:22:21 -0800925#ifdef MOVING_GARBAGE_COLLECTOR
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700926 UNIMPLEMENTED(FATAL);
Elliott Hughes03181a82011-11-17 17:22:21 -0800927#else
928 return static_cast<JDWP::FieldId>(reinterpret_cast<uintptr_t>(f));
929#endif
930}
931
Mathieu Chartier66f19252012-09-18 08:57:04 -0700932static JDWP::MethodId ToMethodId(const AbstractMethod* m)
Ian Rogersb726dcb2012-09-05 08:57:23 -0700933 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Elliott Hughes03181a82011-11-17 17:22:21 -0800934#ifdef MOVING_GARBAGE_COLLECTOR
935 UNIMPLEMENTED(FATAL);
936#else
937 return static_cast<JDWP::MethodId>(reinterpret_cast<uintptr_t>(m));
938#endif
939}
940
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700941static Field* FromFieldId(JDWP::FieldId fid)
Ian Rogersb726dcb2012-09-05 08:57:23 -0700942 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Elliott Hughesaed4be92011-12-02 16:16:23 -0800943#ifdef MOVING_GARBAGE_COLLECTOR
944 UNIMPLEMENTED(FATAL);
945#else
946 return reinterpret_cast<Field*>(static_cast<uintptr_t>(fid));
947#endif
948}
949
Mathieu Chartier66f19252012-09-18 08:57:04 -0700950static AbstractMethod* FromMethodId(JDWP::MethodId mid)
Ian Rogersb726dcb2012-09-05 08:57:23 -0700951 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Elliott Hughes03181a82011-11-17 17:22:21 -0800952#ifdef MOVING_GARBAGE_COLLECTOR
953 UNIMPLEMENTED(FATAL);
954#else
Mathieu Chartier66f19252012-09-18 08:57:04 -0700955 return reinterpret_cast<AbstractMethod*>(static_cast<uintptr_t>(mid));
Elliott Hughes03181a82011-11-17 17:22:21 -0800956#endif
957}
958
Mathieu Chartier66f19252012-09-18 08:57:04 -0700959static void SetLocation(JDWP::JdwpLocation& location, AbstractMethod* m, uint32_t dex_pc)
Ian Rogersb726dcb2012-09-05 08:57:23 -0700960 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Elliott Hughes91bf6cd2012-02-14 17:27:48 -0800961 if (m == NULL) {
962 memset(&location, 0, sizeof(location));
963 } else {
964 Class* c = m->GetDeclaringClass();
Elliott Hughes74847412012-06-20 18:10:21 -0700965 location.type_tag = c->IsInterface() ? JDWP::TT_INTERFACE : JDWP::TT_CLASS;
966 location.class_id = gRegistry->Add(c);
967 location.method_id = ToMethodId(m);
Ian Rogers0399dde2012-06-06 17:09:28 -0700968 location.dex_pc = dex_pc;
Elliott Hughes91bf6cd2012-02-14 17:27:48 -0800969 }
Elliott Hughesd07986f2011-12-06 18:27:45 -0800970}
971
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700972std::string Dbg::GetMethodName(JDWP::RefTypeId, JDWP::MethodId methodId)
Ian Rogersb726dcb2012-09-05 08:57:23 -0700973 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Mathieu Chartier66f19252012-09-18 08:57:04 -0700974 AbstractMethod* m = FromMethodId(methodId);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800975 return MethodHelper(m).GetName();
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700976}
977
Elliott Hughesa2e54f62011-11-17 13:01:30 -0800978/*
979 * Augment the access flags for synthetic methods and fields by setting
980 * the (as described by the spec) "0xf0000000 bit". Also, strip out any
981 * flags not specified by the Java programming language.
982 */
983static uint32_t MangleAccessFlags(uint32_t accessFlags) {
984 accessFlags &= kAccJavaFlagsMask;
985 if ((accessFlags & kAccSynthetic) != 0) {
986 accessFlags |= 0xf0000000;
987 }
988 return accessFlags;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700989}
990
Elliott Hughesdbb40792011-11-18 17:05:22 -0800991static const uint16_t kEclipseWorkaroundSlot = 1000;
992
993/*
994 * Eclipse appears to expect that the "this" reference is in slot zero.
995 * If it's not, the "variables" display will show two copies of "this",
996 * possibly because it gets "this" from SF.ThisObject and then displays
997 * all locals with nonzero slot numbers.
998 *
999 * So, we remap the item in slot 0 to 1000, and remap "this" to zero. On
1000 * SF.GetValues / SF.SetValues we map them back.
Elliott Hughesc5b734a2011-12-01 17:20:58 -08001001 *
1002 * TODO: jdb uses the value to determine whether a variable is a local or an argument,
1003 * by checking whether it's less than the number of arguments. To make that work, we'd
1004 * have to "mangle" all the arguments to come first, not just the implicit argument 'this'.
Elliott Hughesdbb40792011-11-18 17:05:22 -08001005 */
1006static uint16_t MangleSlot(uint16_t slot, const char* name) {
1007 uint16_t newSlot = slot;
1008 if (strcmp(name, "this") == 0) {
1009 newSlot = 0;
1010 } else if (slot == 0) {
1011 newSlot = kEclipseWorkaroundSlot;
1012 }
1013 return newSlot;
1014}
1015
Mathieu Chartier66f19252012-09-18 08:57:04 -07001016static uint16_t DemangleSlot(uint16_t slot, AbstractMethod* m)
Ian Rogersb726dcb2012-09-05 08:57:23 -07001017 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Elliott Hughesdbb40792011-11-18 17:05:22 -08001018 if (slot == kEclipseWorkaroundSlot) {
Elliott Hughes68fdbd02011-11-29 19:22:47 -08001019 return 0;
Elliott Hughesdbb40792011-11-18 17:05:22 -08001020 } else if (slot == 0) {
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08001021 const DexFile::CodeItem* code_item = MethodHelper(m).GetCodeItem();
Elliott Hughescaf76542012-06-28 16:08:22 -07001022 CHECK(code_item != NULL) << PrettyMethod(m);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001023 return code_item->registers_size_ - code_item->ins_size_;
Elliott Hughesdbb40792011-11-18 17:05:22 -08001024 }
Elliott Hughes68fdbd02011-11-29 19:22:47 -08001025 return slot;
Elliott Hughesdbb40792011-11-18 17:05:22 -08001026}
1027
Elliott Hughes436e3722012-02-17 20:01:47 -08001028JDWP::JdwpError Dbg::OutputDeclaredFields(JDWP::RefTypeId classId, bool with_generic, JDWP::ExpandBuf* pReply) {
1029 JDWP::JdwpError status;
1030 Class* c = DecodeClass(classId, status);
1031 if (c == NULL) {
1032 return status;
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -08001033 }
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001034
1035 size_t instance_field_count = c->NumInstanceFields();
1036 size_t static_field_count = c->NumStaticFields();
1037
1038 expandBufAdd4BE(pReply, instance_field_count + static_field_count);
1039
1040 for (size_t i = 0; i < instance_field_count + static_field_count; ++i) {
1041 Field* f = (i < instance_field_count) ? c->GetInstanceField(i) : c->GetStaticField(i - instance_field_count);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001042 FieldHelper fh(f);
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001043 expandBufAddFieldId(pReply, ToFieldId(f));
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001044 expandBufAddUtf8String(pReply, fh.GetName());
1045 expandBufAddUtf8String(pReply, fh.GetTypeDescriptor());
Elliott Hughesc5b734a2011-12-01 17:20:58 -08001046 if (with_generic) {
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001047 static const char genericSignature[1] = "";
1048 expandBufAddUtf8String(pReply, genericSignature);
1049 }
1050 expandBufAdd4BE(pReply, MangleAccessFlags(f->GetAccessFlags()));
1051 }
Elliott Hughes436e3722012-02-17 20:01:47 -08001052 return JDWP::ERR_NONE;
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001053}
1054
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001055JDWP::JdwpError Dbg::OutputDeclaredMethods(JDWP::RefTypeId classId, bool with_generic,
1056 JDWP::ExpandBuf* pReply) {
Elliott Hughes436e3722012-02-17 20:01:47 -08001057 JDWP::JdwpError status;
1058 Class* c = DecodeClass(classId, status);
1059 if (c == NULL) {
1060 return status;
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -08001061 }
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001062
1063 size_t direct_method_count = c->NumDirectMethods();
1064 size_t virtual_method_count = c->NumVirtualMethods();
1065
1066 expandBufAdd4BE(pReply, direct_method_count + virtual_method_count);
1067
1068 for (size_t i = 0; i < direct_method_count + virtual_method_count; ++i) {
Mathieu Chartier66f19252012-09-18 08:57:04 -07001069 AbstractMethod* m = (i < direct_method_count) ? c->GetDirectMethod(i) : c->GetVirtualMethod(i - direct_method_count);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001070 MethodHelper mh(m);
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001071 expandBufAddMethodId(pReply, ToMethodId(m));
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001072 expandBufAddUtf8String(pReply, mh.GetName());
Elliott Hughes4740cdf2011-12-07 14:07:12 -08001073 expandBufAddUtf8String(pReply, mh.GetSignature());
Elliott Hughesc5b734a2011-12-01 17:20:58 -08001074 if (with_generic) {
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001075 static const char genericSignature[1] = "";
1076 expandBufAddUtf8String(pReply, genericSignature);
1077 }
1078 expandBufAdd4BE(pReply, MangleAccessFlags(m->GetAccessFlags()));
1079 }
Elliott Hughes436e3722012-02-17 20:01:47 -08001080 return JDWP::ERR_NONE;
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001081}
1082
Elliott Hughes436e3722012-02-17 20:01:47 -08001083JDWP::JdwpError Dbg::OutputDeclaredInterfaces(JDWP::RefTypeId classId, JDWP::ExpandBuf* pReply) {
1084 JDWP::JdwpError status;
1085 Class* c = DecodeClass(classId, status);
1086 if (c == NULL) {
1087 return status;
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -08001088 }
Elliott Hughes436e3722012-02-17 20:01:47 -08001089
1090 ClassHelper kh(c);
Ian Rogersd24e2642012-06-06 21:21:43 -07001091 size_t interface_count = kh.NumDirectInterfaces();
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001092 expandBufAdd4BE(pReply, interface_count);
1093 for (size_t i = 0; i < interface_count; ++i) {
Ian Rogersd24e2642012-06-06 21:21:43 -07001094 expandBufAddRefTypeId(pReply, gRegistry->Add(kh.GetDirectInterface(i)));
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001095 }
Elliott Hughes436e3722012-02-17 20:01:47 -08001096 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001097}
1098
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001099void Dbg::OutputLineTable(JDWP::RefTypeId, JDWP::MethodId methodId, JDWP::ExpandBuf* pReply)
Ian Rogersb726dcb2012-09-05 08:57:23 -07001100 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Elliott Hughes03181a82011-11-17 17:22:21 -08001101 struct DebugCallbackContext {
1102 int numItems;
1103 JDWP::ExpandBuf* pReply;
1104
Elliott Hughes2435a572012-02-17 16:07:41 -08001105 static bool Callback(void* context, uint32_t address, uint32_t line_number) {
Elliott Hughes03181a82011-11-17 17:22:21 -08001106 DebugCallbackContext* pContext = reinterpret_cast<DebugCallbackContext*>(context);
1107 expandBufAdd8BE(pContext->pReply, address);
Elliott Hughes2435a572012-02-17 16:07:41 -08001108 expandBufAdd4BE(pContext->pReply, line_number);
Elliott Hughes03181a82011-11-17 17:22:21 -08001109 pContext->numItems++;
1110 return true;
1111 }
1112 };
Mathieu Chartier66f19252012-09-18 08:57:04 -07001113 AbstractMethod* m = FromMethodId(methodId);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001114 MethodHelper mh(m);
Elliott Hughes03181a82011-11-17 17:22:21 -08001115 uint64_t start, end;
1116 if (m->IsNative()) {
1117 start = -1;
1118 end = -1;
1119 } else {
1120 start = 0;
jeffhao14f0db92012-12-14 17:50:42 -08001121 // Return the index of the last instruction
1122 end = mh.GetCodeItem()->insns_size_in_code_units_ - 1;
Elliott Hughes03181a82011-11-17 17:22:21 -08001123 }
1124
1125 expandBufAdd8BE(pReply, start);
1126 expandBufAdd8BE(pReply, end);
1127
1128 // Add numLines later
1129 size_t numLinesOffset = expandBufGetLength(pReply);
1130 expandBufAdd4BE(pReply, 0);
1131
1132 DebugCallbackContext context;
1133 context.numItems = 0;
1134 context.pReply = pReply;
1135
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001136 mh.GetDexFile().DecodeDebugInfo(mh.GetCodeItem(), m->IsStatic(), m->GetDexMethodIndex(),
1137 DebugCallbackContext::Callback, NULL, &context);
Elliott Hughes03181a82011-11-17 17:22:21 -08001138
1139 JDWP::Set4BE(expandBufGetBuffer(pReply) + numLinesOffset, context.numItems);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001140}
1141
Elliott Hughes436e3722012-02-17 20:01:47 -08001142void Dbg::OutputVariableTable(JDWP::RefTypeId, JDWP::MethodId methodId, bool with_generic, JDWP::ExpandBuf* pReply) {
Elliott Hughesdbb40792011-11-18 17:05:22 -08001143 struct DebugCallbackContext {
Elliott Hughesdbb40792011-11-18 17:05:22 -08001144 JDWP::ExpandBuf* pReply;
Elliott Hughesc5b734a2011-12-01 17:20:58 -08001145 size_t variable_count;
1146 bool with_generic;
Elliott Hughesdbb40792011-11-18 17:05:22 -08001147
Elliott Hughesc5b734a2011-12-01 17:20:58 -08001148 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 -08001149 DebugCallbackContext* pContext = reinterpret_cast<DebugCallbackContext*>(context);
1150
Elliott Hughesad3da692012-02-24 16:51:35 -08001151 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 -08001152
Elliott Hughes68fdbd02011-11-29 19:22:47 -08001153 slot = MangleSlot(slot, name);
1154
Elliott Hughesdbb40792011-11-18 17:05:22 -08001155 expandBufAdd8BE(pContext->pReply, startAddress);
1156 expandBufAddUtf8String(pContext->pReply, name);
1157 expandBufAddUtf8String(pContext->pReply, descriptor);
Elliott Hughesc5b734a2011-12-01 17:20:58 -08001158 if (pContext->with_generic) {
Elliott Hughesdbb40792011-11-18 17:05:22 -08001159 expandBufAddUtf8String(pContext->pReply, signature);
1160 }
1161 expandBufAdd4BE(pContext->pReply, endAddress - startAddress);
1162 expandBufAdd4BE(pContext->pReply, slot);
1163
Elliott Hughesc5b734a2011-12-01 17:20:58 -08001164 ++pContext->variable_count;
Elliott Hughesdbb40792011-11-18 17:05:22 -08001165 }
1166 };
Mathieu Chartier66f19252012-09-18 08:57:04 -07001167 AbstractMethod* m = FromMethodId(methodId);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001168 MethodHelper mh(m);
1169 const DexFile::CodeItem* code_item = mh.GetCodeItem();
Elliott Hughesdbb40792011-11-18 17:05:22 -08001170
Elliott Hughesc5b734a2011-12-01 17:20:58 -08001171 // arg_count considers doubles and longs to take 2 units.
1172 // variable_count considers everything to take 1 unit.
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001173 std::string shorty(mh.GetShorty());
Ian Rogers2fa6b2e2012-10-17 00:10:17 -07001174 expandBufAdd4BE(pReply, AbstractMethod::NumArgRegisters(shorty));
Elliott Hughesdbb40792011-11-18 17:05:22 -08001175
Elliott Hughesc5b734a2011-12-01 17:20:58 -08001176 // We don't know the total number of variables yet, so leave a blank and update it later.
1177 size_t variable_count_offset = expandBufGetLength(pReply);
Elliott Hughesdbb40792011-11-18 17:05:22 -08001178 expandBufAdd4BE(pReply, 0);
1179
1180 DebugCallbackContext context;
Elliott Hughesdbb40792011-11-18 17:05:22 -08001181 context.pReply = pReply;
Elliott Hughesc5b734a2011-12-01 17:20:58 -08001182 context.variable_count = 0;
1183 context.with_generic = with_generic;
Elliott Hughesdbb40792011-11-18 17:05:22 -08001184
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001185 mh.GetDexFile().DecodeDebugInfo(code_item, m->IsStatic(), m->GetDexMethodIndex(), NULL,
1186 DebugCallbackContext::Callback, &context);
Elliott Hughesdbb40792011-11-18 17:05:22 -08001187
Elliott Hughesc5b734a2011-12-01 17:20:58 -08001188 JDWP::Set4BE(expandBufGetBuffer(pReply) + variable_count_offset, context.variable_count);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001189}
1190
Elliott Hughesaed4be92011-12-02 16:16:23 -08001191JDWP::JdwpTag Dbg::GetFieldBasicTag(JDWP::FieldId fieldId) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001192 return BasicTagFromDescriptor(FieldHelper(FromFieldId(fieldId)).GetTypeDescriptor());
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001193}
1194
Elliott Hughesaed4be92011-12-02 16:16:23 -08001195JDWP::JdwpTag Dbg::GetStaticFieldBasicTag(JDWP::FieldId fieldId) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001196 return BasicTagFromDescriptor(FieldHelper(FromFieldId(fieldId)).GetTypeDescriptor());
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001197}
1198
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001199static JDWP::JdwpError GetFieldValueImpl(JDWP::RefTypeId refTypeId, JDWP::ObjectId objectId,
1200 JDWP::FieldId fieldId, JDWP::ExpandBuf* pReply,
1201 bool is_static)
Ian Rogersb726dcb2012-09-05 08:57:23 -07001202 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Elliott Hughes0cf74332012-02-23 23:14:00 -08001203 JDWP::JdwpError status;
1204 Class* c = DecodeClass(refTypeId, status);
1205 if (refTypeId != 0 && c == NULL) {
1206 return status;
1207 }
1208
Elliott Hughesaed4be92011-12-02 16:16:23 -08001209 Object* o = gRegistry->Get<Object*>(objectId);
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08001210 if ((!is_static && o == NULL) || o == kInvalidObject) {
1211 return JDWP::ERR_INVALID_OBJECT;
1212 }
Elliott Hughesaed4be92011-12-02 16:16:23 -08001213 Field* f = FromFieldId(fieldId);
Elliott Hughes0cf74332012-02-23 23:14:00 -08001214
1215 Class* receiver_class = c;
1216 if (receiver_class == NULL && o != NULL) {
1217 receiver_class = o->GetClass();
1218 }
1219 // TODO: should we give up now if receiver_class is NULL?
1220 if (receiver_class != NULL && !f->GetDeclaringClass()->IsAssignableFrom(receiver_class)) {
1221 LOG(INFO) << "ERR_INVALID_FIELDID: " << PrettyField(f) << " " << PrettyClass(receiver_class);
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08001222 return JDWP::ERR_INVALID_FIELDID;
1223 }
Elliott Hughesaed4be92011-12-02 16:16:23 -08001224
Elliott Hughes0cf74332012-02-23 23:14:00 -08001225 // The RI only enforces the static/non-static mismatch in one direction.
1226 // TODO: should we change the tests and check both?
1227 if (is_static) {
1228 if (!f->IsStatic()) {
1229 return JDWP::ERR_INVALID_FIELDID;
1230 }
1231 } else {
1232 if (f->IsStatic()) {
1233 LOG(WARNING) << "Ignoring non-NULL receiver for ObjectReference.SetValues on static field " << PrettyField(f);
Elliott Hughes0cf74332012-02-23 23:14:00 -08001234 }
1235 }
jeffhao0dfbb7e2012-11-28 15:26:03 -08001236 if (f->IsStatic()) {
1237 o = f->GetDeclaringClass();
1238 }
Elliott Hughes0cf74332012-02-23 23:14:00 -08001239
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001240 JDWP::JdwpTag tag = BasicTagFromDescriptor(FieldHelper(f).GetTypeDescriptor());
Elliott Hughesaed4be92011-12-02 16:16:23 -08001241
1242 if (IsPrimitiveTag(tag)) {
1243 expandBufAdd1(pReply, tag);
1244 if (tag == JDWP::JT_BOOLEAN || tag == JDWP::JT_BYTE) {
1245 expandBufAdd1(pReply, f->Get32(o));
1246 } else if (tag == JDWP::JT_CHAR || tag == JDWP::JT_SHORT) {
1247 expandBufAdd2BE(pReply, f->Get32(o));
1248 } else if (tag == JDWP::JT_FLOAT || tag == JDWP::JT_INT) {
1249 expandBufAdd4BE(pReply, f->Get32(o));
1250 } else if (tag == JDWP::JT_DOUBLE || tag == JDWP::JT_LONG) {
1251 expandBufAdd8BE(pReply, f->Get64(o));
1252 } else {
Elliott Hughes3d30d9b2011-12-07 17:35:48 -08001253 LOG(FATAL) << "Unknown tag: " << tag;
Elliott Hughesaed4be92011-12-02 16:16:23 -08001254 }
1255 } else {
1256 Object* value = f->GetObject(o);
1257 expandBufAdd1(pReply, TagFromObject(value));
1258 expandBufAddObjectId(pReply, gRegistry->Add(value));
1259 }
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08001260 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001261}
1262
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001263JDWP::JdwpError Dbg::GetFieldValue(JDWP::ObjectId objectId, JDWP::FieldId fieldId,
1264 JDWP::ExpandBuf* pReply) {
Elliott Hughes0cf74332012-02-23 23:14:00 -08001265 return GetFieldValueImpl(0, objectId, fieldId, pReply, false);
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08001266}
1267
Elliott Hughes0cf74332012-02-23 23:14:00 -08001268JDWP::JdwpError Dbg::GetStaticFieldValue(JDWP::RefTypeId refTypeId, JDWP::FieldId fieldId, JDWP::ExpandBuf* pReply) {
1269 return GetFieldValueImpl(refTypeId, 0, fieldId, pReply, true);
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08001270}
1271
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001272static JDWP::JdwpError SetFieldValueImpl(JDWP::ObjectId objectId, JDWP::FieldId fieldId,
1273 uint64_t value, int width, bool is_static)
Ian Rogersb726dcb2012-09-05 08:57:23 -07001274 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Elliott Hughesaed4be92011-12-02 16:16:23 -08001275 Object* o = gRegistry->Get<Object*>(objectId);
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08001276 if ((!is_static && o == NULL) || o == kInvalidObject) {
1277 return JDWP::ERR_INVALID_OBJECT;
1278 }
Elliott Hughesaed4be92011-12-02 16:16:23 -08001279 Field* f = FromFieldId(fieldId);
Elliott Hughes0cf74332012-02-23 23:14:00 -08001280
1281 // The RI only enforces the static/non-static mismatch in one direction.
1282 // TODO: should we change the tests and check both?
1283 if (is_static) {
1284 if (!f->IsStatic()) {
1285 return JDWP::ERR_INVALID_FIELDID;
1286 }
1287 } else {
1288 if (f->IsStatic()) {
1289 LOG(WARNING) << "Ignoring non-NULL receiver for ObjectReference.SetValues on static field " << PrettyField(f);
Elliott Hughes0cf74332012-02-23 23:14:00 -08001290 }
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08001291 }
jeffhao0dfbb7e2012-11-28 15:26:03 -08001292 if (f->IsStatic()) {
1293 o = f->GetDeclaringClass();
1294 }
Elliott Hughesaed4be92011-12-02 16:16:23 -08001295
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001296 JDWP::JdwpTag tag = BasicTagFromDescriptor(FieldHelper(f).GetTypeDescriptor());
Elliott Hughesaed4be92011-12-02 16:16:23 -08001297
1298 if (IsPrimitiveTag(tag)) {
1299 if (tag == JDWP::JT_DOUBLE || tag == JDWP::JT_LONG) {
Elliott Hughes1bac54f2012-03-16 12:48:31 -07001300 CHECK_EQ(width, 8);
Elliott Hughesaed4be92011-12-02 16:16:23 -08001301 f->Set64(o, value);
1302 } else {
Elliott Hughes1bac54f2012-03-16 12:48:31 -07001303 CHECK_LE(width, 4);
Elliott Hughesaed4be92011-12-02 16:16:23 -08001304 f->Set32(o, value);
1305 }
1306 } else {
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -08001307 Object* v = gRegistry->Get<Object*>(value);
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08001308 if (v == kInvalidObject) {
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -08001309 return JDWP::ERR_INVALID_OBJECT;
1310 }
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08001311 if (v != NULL) {
1312 Class* field_type = FieldHelper(f).GetType();
1313 if (!field_type->IsAssignableFrom(v->GetClass())) {
1314 return JDWP::ERR_INVALID_OBJECT;
1315 }
1316 }
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -08001317 f->SetObject(o, v);
Elliott Hughesaed4be92011-12-02 16:16:23 -08001318 }
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -08001319
1320 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001321}
1322
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001323JDWP::JdwpError Dbg::SetFieldValue(JDWP::ObjectId objectId, JDWP::FieldId fieldId, uint64_t value,
1324 int width) {
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08001325 return SetFieldValueImpl(objectId, fieldId, value, width, false);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001326}
1327
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -08001328JDWP::JdwpError Dbg::SetStaticFieldValue(JDWP::FieldId fieldId, uint64_t value, int width) {
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08001329 return SetFieldValueImpl(0, fieldId, value, width, true);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001330}
1331
Elliott Hughes68fdbd02011-11-29 19:22:47 -08001332std::string Dbg::StringToUtf8(JDWP::ObjectId strId) {
1333 String* s = gRegistry->Get<String*>(strId);
1334 return s->ToModifiedUtf8();
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001335}
1336
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001337bool Dbg::GetThreadName(JDWP::ObjectId threadId, std::string& name) {
jeffhaoa77f0f62012-12-05 17:19:31 -08001338 ScopedObjectAccessUnchecked soa(Thread::Current());
1339 MutexLock mu(soa.Self(), *Locks::thread_list_lock_);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001340 Thread* thread = DecodeThread(soa, threadId);
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001341 if (thread == NULL) {
1342 return false;
1343 }
Elliott Hughesffb465f2012-03-01 18:46:05 -08001344 thread->GetThreadName(name);
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001345 return true;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001346}
1347
Elliott Hughes2435a572012-02-17 16:07:41 -08001348JDWP::JdwpError Dbg::GetThreadGroup(JDWP::ObjectId threadId, JDWP::ExpandBuf* pReply) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001349 ScopedObjectAccess soa(Thread::Current());
Elliott Hughes499c5132011-11-17 14:55:11 -08001350 Object* thread = gRegistry->Get<Object*>(threadId);
Elliott Hughes436e3722012-02-17 20:01:47 -08001351 if (thread == kInvalidObject) {
Elliott Hughes2435a572012-02-17 16:07:41 -08001352 return JDWP::ERR_INVALID_OBJECT;
1353 }
1354
1355 // Okay, so it's an object, but is it actually a thread?
Ian Rogers50b35e22012-10-04 10:09:15 -07001356 MutexLock mu(soa.Self(), *Locks::thread_list_lock_);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001357 if (DecodeThread(soa, threadId) == NULL) {
Elliott Hughes2435a572012-02-17 16:07:41 -08001358 return JDWP::ERR_INVALID_THREAD;
1359 }
Elliott Hughes499c5132011-11-17 14:55:11 -08001360
1361 Class* c = Runtime::Current()->GetClassLinker()->FindSystemClass("Ljava/lang/Thread;");
1362 CHECK(c != NULL);
1363 Field* f = c->FindInstanceField("group", "Ljava/lang/ThreadGroup;");
1364 CHECK(f != NULL);
1365 Object* group = f->GetObject(thread);
1366 CHECK(group != NULL);
Elliott Hughes2435a572012-02-17 16:07:41 -08001367 JDWP::ObjectId thread_group_id = gRegistry->Add(group);
1368
1369 expandBufAddObjectId(pReply, thread_group_id);
1370 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001371}
1372
Elliott Hughes499c5132011-11-17 14:55:11 -08001373std::string Dbg::GetThreadGroupName(JDWP::ObjectId threadGroupId) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001374 ScopedObjectAccess soa(Thread::Current());
Elliott Hughes499c5132011-11-17 14:55:11 -08001375 Object* thread_group = gRegistry->Get<Object*>(threadGroupId);
1376 CHECK(thread_group != NULL);
1377
1378 Class* c = Runtime::Current()->GetClassLinker()->FindSystemClass("Ljava/lang/ThreadGroup;");
1379 CHECK(c != NULL);
1380 Field* f = c->FindInstanceField("name", "Ljava/lang/String;");
1381 CHECK(f != NULL);
1382 String* s = reinterpret_cast<String*>(f->GetObject(thread_group));
1383 return s->ToModifiedUtf8();
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001384}
1385
1386JDWP::ObjectId Dbg::GetThreadGroupParent(JDWP::ObjectId threadGroupId) {
Elliott Hughes4e235312011-12-02 11:34:15 -08001387 Object* thread_group = gRegistry->Get<Object*>(threadGroupId);
1388 CHECK(thread_group != NULL);
1389
1390 Class* c = Runtime::Current()->GetClassLinker()->FindSystemClass("Ljava/lang/ThreadGroup;");
1391 CHECK(c != NULL);
1392 Field* f = c->FindInstanceField("parent", "Ljava/lang/ThreadGroup;");
1393 CHECK(f != NULL);
1394 Object* parent = f->GetObject(thread_group);
1395 return gRegistry->Add(parent);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001396}
1397
1398JDWP::ObjectId Dbg::GetSystemThreadGroupId() {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001399 ScopedObjectAccessUnchecked soa(Thread::Current());
jeffhao0dfbb7e2012-11-28 15:26:03 -08001400 Field* f = soa.DecodeField(WellKnownClasses::java_lang_ThreadGroup_systemThreadGroup);
1401 Object* group = f->GetObject(f->GetDeclaringClass());
Ian Rogers365c1022012-06-22 15:05:28 -07001402 return gRegistry->Add(group);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001403}
1404
1405JDWP::ObjectId Dbg::GetMainThreadGroupId() {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001406 ScopedObjectAccess soa(Thread::Current());
jeffhao0dfbb7e2012-11-28 15:26:03 -08001407 Field* f = soa.DecodeField(WellKnownClasses::java_lang_ThreadGroup_mainThreadGroup);
1408 Object* group = f->GetObject(f->GetDeclaringClass());
Ian Rogers365c1022012-06-22 15:05:28 -07001409 return gRegistry->Add(group);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001410}
1411
Elliott Hughes3d30d9b2011-12-07 17:35:48 -08001412bool Dbg::GetThreadStatus(JDWP::ObjectId threadId, JDWP::JdwpThreadStatus* pThreadStatus, JDWP::JdwpSuspendStatus* pSuspendStatus) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001413 ScopedObjectAccess soa(Thread::Current());
Elliott Hughes499c5132011-11-17 14:55:11 -08001414
Ian Rogers50b35e22012-10-04 10:09:15 -07001415 MutexLock mu(soa.Self(), *Locks::thread_list_lock_);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001416 Thread* thread = DecodeThread(soa, threadId);
Elliott Hughes499c5132011-11-17 14:55:11 -08001417 if (thread == NULL) {
1418 return false;
1419 }
1420
Ian Rogers50b35e22012-10-04 10:09:15 -07001421 MutexLock mu2(soa.Self(), *Locks::thread_suspend_count_lock_);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001422
Elliott Hughes499c5132011-11-17 14:55:11 -08001423 switch (thread->GetState()) {
Elliott Hughes34e06962012-04-09 13:55:55 -07001424 case kTerminated: *pThreadStatus = JDWP::TS_ZOMBIE; break;
1425 case kRunnable: *pThreadStatus = JDWP::TS_RUNNING; break;
1426 case kTimedWaiting: *pThreadStatus = JDWP::TS_WAIT; break;
1427 case kBlocked: *pThreadStatus = JDWP::TS_MONITOR; break;
1428 case kWaiting: *pThreadStatus = JDWP::TS_WAIT; break;
1429 case kStarting: *pThreadStatus = JDWP::TS_ZOMBIE; break;
1430 case kNative: *pThreadStatus = JDWP::TS_RUNNING; break;
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001431 case kWaitingForGcToComplete: // Fall-through.
1432 case kWaitingPerformingGc: // Fall-through.
1433 case kWaitingForDebuggerSend: // Fall-through.
1434 case kWaitingForDebuggerToAttach: // Fall-through.
1435 case kWaitingInMainDebuggerLoop: // Fall-through.
1436 case kWaitingForDebuggerSuspension: // Fall-through.
1437 case kWaitingForJniOnLoad: // Fall-through.
1438 case kWaitingForSignalCatcherOutput: // Fall-through.
1439 case kWaitingInMainSignalCatcherLoop:
1440 *pThreadStatus = JDWP::TS_WAIT; break;
Elliott Hughes34e06962012-04-09 13:55:55 -07001441 case kSuspended: *pThreadStatus = JDWP::TS_RUNNING; break;
Elliott Hughescf2b2d42012-03-27 17:11:42 -07001442 // Don't add a 'default' here so the compiler can spot incompatible enum changes.
Elliott Hughes499c5132011-11-17 14:55:11 -08001443 }
1444
jeffhaoe5fe0f72013-01-04 17:05:30 -08001445 if (thread->GetState() == kTimedWaiting) {
1446 // Since Thread.sleep is implemented using Object.wait, see if Thread.sleep
1447 // is on the stack and change state to TS_SLEEPING if it is.
1448 struct SleepMethodVisitor : public StackVisitor {
1449 SleepMethodVisitor(const ManagedStack* stack,
1450 const std::deque<InstrumentationStackFrame>* instrumentation_stack)
1451 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_)
1452 : StackVisitor(stack, instrumentation_stack, NULL), found_(false) {}
1453
1454 virtual bool VisitFrame() SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
1455 std::string name(PrettyMethod(GetMethod(), false));
1456 if (name == "java.lang.Thread.sleep") {
1457 found_ = true;
1458 return false;
1459 }
1460 return true;
1461 }
1462
1463 bool found_;
1464 };
1465
1466 SleepMethodVisitor visitor(thread->GetManagedStack(), thread->GetInstrumentationStack());
1467 visitor.WalkStack(false);
1468 if (visitor.found_) {
1469 *pThreadStatus = JDWP::TS_SLEEPING;
1470 }
1471 }
1472
Elliott Hughes3d30d9b2011-12-07 17:35:48 -08001473 *pSuspendStatus = (thread->IsSuspended() ? JDWP::SUSPEND_STATUS_SUSPENDED : JDWP::SUSPEND_STATUS_NOT_SUSPENDED);
Elliott Hughes499c5132011-11-17 14:55:11 -08001474
1475 return true;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001476}
1477
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001478JDWP::JdwpError Dbg::GetThreadDebugSuspendCount(JDWP::ObjectId threadId, JDWP::ExpandBuf* pReply) {
1479 ScopedObjectAccess soa(Thread::Current());
1480
Ian Rogers50b35e22012-10-04 10:09:15 -07001481 MutexLock mu(soa.Self(), *Locks::thread_list_lock_);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001482 Thread* thread = DecodeThread(soa, threadId);
Elliott Hughes2435a572012-02-17 16:07:41 -08001483 if (thread == NULL) {
1484 return JDWP::ERR_INVALID_THREAD;
1485 }
Ian Rogers50b35e22012-10-04 10:09:15 -07001486 MutexLock mu2(soa.Self(), *Locks::thread_suspend_count_lock_);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001487 expandBufAdd4BE(pReply, thread->GetDebugSuspendCount());
Elliott Hughes2435a572012-02-17 16:07:41 -08001488 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001489}
1490
1491bool Dbg::ThreadExists(JDWP::ObjectId threadId) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001492 ScopedObjectAccess soa(Thread::Current());
Ian Rogers50b35e22012-10-04 10:09:15 -07001493 MutexLock mu(soa.Self(), *Locks::thread_list_lock_);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001494 return DecodeThread(soa, threadId) != NULL;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001495}
1496
1497bool Dbg::IsSuspended(JDWP::ObjectId threadId) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001498 ScopedObjectAccess soa(Thread::Current());
Ian Rogers50b35e22012-10-04 10:09:15 -07001499 MutexLock mu(soa.Self(), *Locks::thread_list_lock_);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001500 Thread* thread = DecodeThread(soa, threadId);
1501 CHECK(thread != NULL);
Ian Rogers50b35e22012-10-04 10:09:15 -07001502 MutexLock mu2(soa.Self(), *Locks::thread_suspend_count_lock_);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001503 return thread->IsSuspended();
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001504}
1505
Elliott Hughescaf76542012-06-28 16:08:22 -07001506void Dbg::GetThreads(JDWP::ObjectId thread_group_id, std::vector<JDWP::ObjectId>& thread_ids) {
Ian Rogers365c1022012-06-22 15:05:28 -07001507 class ThreadListVisitor {
1508 public:
jeffhao0dfbb7e2012-11-28 15:26:03 -08001509 ThreadListVisitor(const ScopedObjectAccessUnchecked& soa, Object* desired_thread_group,
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001510 std::vector<JDWP::ObjectId>& thread_ids)
Ian Rogersb726dcb2012-09-05 08:57:23 -07001511 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_)
jeffhao0dfbb7e2012-11-28 15:26:03 -08001512 : soa_(soa), desired_thread_group_(desired_thread_group), thread_ids_(thread_ids) {}
Ian Rogers365c1022012-06-22 15:05:28 -07001513
Elliott Hughesa2155262011-11-16 16:26:58 -08001514 static void Visit(Thread* t, void* arg) {
1515 reinterpret_cast<ThreadListVisitor*>(arg)->Visit(t);
1516 }
1517
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001518 // TODO: Enable annotalysis. We know lock is held in constructor, but abstraction confuses
1519 // annotalysis.
1520 void Visit(Thread* t) NO_THREAD_SAFETY_ANALYSIS {
Elliott Hughesa2155262011-11-16 16:26:58 -08001521 if (t == Dbg::GetDebugThread()) {
1522 // Skip the JDWP thread. Some debuggers get bent out of shape when they can't suspend and
1523 // query all threads, so it's easier if we just don't tell them about this thread.
1524 return;
1525 }
Ian Rogerscfaa4552012-11-26 21:00:08 -08001526 Object* peer = t->GetPeer();
jeffhao0dfbb7e2012-11-28 15:26:03 -08001527 if (IsInDesiredThreadGroup(peer)) {
Ian Rogers120f1c72012-09-28 17:17:10 -07001528 thread_ids_.push_back(gRegistry->Add(peer));
Elliott Hughesa2155262011-11-16 16:26:58 -08001529 }
1530 }
1531
Ian Rogers365c1022012-06-22 15:05:28 -07001532 private:
jeffhao0dfbb7e2012-11-28 15:26:03 -08001533 bool IsInDesiredThreadGroup(Object* peer)
1534 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
jeffhao0dfbb7e2012-11-28 15:26:03 -08001535 // peer might be NULL if the thread is still starting up.
1536 if (peer == NULL) {
1537 // We can't tell the debugger about this thread yet.
1538 // TODO: if we identified threads to the debugger by their Thread*
1539 // rather than their peer's Object*, we could fix this.
1540 // Doing so might help us report ZOMBIE threads too.
1541 return false;
1542 }
jeffhaoc1e04902012-12-13 12:41:10 -08001543 // Do we want threads from all thread groups?
1544 if (desired_thread_group_ == NULL) {
1545 return true;
1546 }
jeffhao0dfbb7e2012-11-28 15:26:03 -08001547 Object* group = soa_.DecodeField(WellKnownClasses::java_lang_Thread_group)->GetObject(peer);
1548 return (group == desired_thread_group_);
1549 }
1550
Mathieu Chartierdbe6f462012-09-25 16:54:50 -07001551 const ScopedObjectAccessUnchecked& soa_;
jeffhao0dfbb7e2012-11-28 15:26:03 -08001552 Object* const desired_thread_group_;
Elliott Hughescaf76542012-06-28 16:08:22 -07001553 std::vector<JDWP::ObjectId>& thread_ids_;
Elliott Hughesa2155262011-11-16 16:26:58 -08001554 };
1555
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001556 ScopedObjectAccessUnchecked soa(Thread::Current());
Elliott Hughescaf76542012-06-28 16:08:22 -07001557 Object* thread_group = gRegistry->Get<Object*>(thread_group_id);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001558 ThreadListVisitor tlv(soa, thread_group, thread_ids);
Ian Rogers50b35e22012-10-04 10:09:15 -07001559 MutexLock mu(soa.Self(), *Locks::thread_list_lock_);
Elliott Hughesf8349362012-06-18 15:00:06 -07001560 Runtime::Current()->GetThreadList()->ForEach(ThreadListVisitor::Visit, &tlv);
Elliott Hughescaf76542012-06-28 16:08:22 -07001561}
Elliott Hughesa2155262011-11-16 16:26:58 -08001562
Elliott Hughescaf76542012-06-28 16:08:22 -07001563void Dbg::GetChildThreadGroups(JDWP::ObjectId thread_group_id, std::vector<JDWP::ObjectId>& child_thread_group_ids) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001564 ScopedObjectAccess soa(Thread::Current());
Elliott Hughescaf76542012-06-28 16:08:22 -07001565 Object* thread_group = gRegistry->Get<Object*>(thread_group_id);
1566
1567 // Get the ArrayList<ThreadGroup> "groups" out of this thread group...
1568 Field* groups_field = thread_group->GetClass()->FindInstanceField("groups", "Ljava/util/List;");
1569 Object* groups_array_list = groups_field->GetObject(thread_group);
1570
1571 // Get the array and size out of the ArrayList<ThreadGroup>...
1572 Field* array_field = groups_array_list->GetClass()->FindInstanceField("array", "[Ljava/lang/Object;");
1573 Field* size_field = groups_array_list->GetClass()->FindInstanceField("size", "I");
1574 ObjectArray<Object>* groups_array = array_field->GetObject(groups_array_list)->AsObjectArray<Object>();
1575 const int32_t size = size_field->GetInt(groups_array_list);
1576
1577 // Copy the first 'size' elements out of the array into the result.
1578 for (int32_t i = 0; i < size; ++i) {
1579 child_thread_group_ids.push_back(gRegistry->Add(groups_array->Get(i)));
Elliott Hughesa2155262011-11-16 16:26:58 -08001580 }
1581}
1582
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001583static int GetStackDepth(Thread* thread)
Ian Rogersb726dcb2012-09-05 08:57:23 -07001584 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Ian Rogers0399dde2012-06-06 17:09:28 -07001585 struct CountStackDepthVisitor : public StackVisitor {
1586 CountStackDepthVisitor(const ManagedStack* stack,
Ian Rogers306057f2012-11-26 12:45:53 -08001587 const std::deque<InstrumentationStackFrame>* instrumentation_stack)
jeffhao725a9572012-11-13 18:20:12 -08001588 : StackVisitor(stack, instrumentation_stack, NULL), depth(0) {}
Ian Rogers0399dde2012-06-06 17:09:28 -07001589
1590 bool VisitFrame() {
1591 if (!GetMethod()->IsRuntimeMethod()) {
Elliott Hughesf8a2df72011-12-01 12:19:54 -08001592 ++depth;
1593 }
Elliott Hughes530fa002012-03-12 11:44:49 -07001594 return true;
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001595 }
1596 size_t depth;
1597 };
Elliott Hughes08fc03a2012-06-26 17:34:00 -07001598
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001599 if (kIsDebugBuild) {
Ian Rogers50b35e22012-10-04 10:09:15 -07001600 MutexLock mu(Thread::Current(), *Locks::thread_suspend_count_lock_);
jeffhao09bfc6a2012-12-11 18:11:43 -08001601 CHECK(thread == Thread::Current() || thread->IsSuspended());
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001602 }
jeffhao725a9572012-11-13 18:20:12 -08001603 CountStackDepthVisitor visitor(thread->GetManagedStack(), thread->GetInstrumentationStack());
Ian Rogers0399dde2012-06-06 17:09:28 -07001604 visitor.WalkStack();
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001605 return visitor.depth;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001606}
1607
Elliott Hughes86964332012-02-15 19:37:42 -08001608int Dbg::GetThreadFrameCount(JDWP::ObjectId threadId) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001609 ScopedObjectAccess soa(Thread::Current());
jeffhaoa77f0f62012-12-05 17:19:31 -08001610 MutexLock mu(soa.Self(), *Locks::thread_list_lock_);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001611 return GetStackDepth(DecodeThread(soa, threadId));
Elliott Hughes86964332012-02-15 19:37:42 -08001612}
1613
Ian Rogers306057f2012-11-26 12:45:53 -08001614JDWP::JdwpError Dbg::GetThreadFrames(JDWP::ObjectId thread_id, size_t start_frame,
1615 size_t frame_count, JDWP::ExpandBuf* buf) {
Elliott Hughes6e9d22c2012-06-22 15:02:37 -07001616 class GetFrameVisitor : public StackVisitor {
1617 public:
Ian Rogers306057f2012-11-26 12:45:53 -08001618 GetFrameVisitor(const ManagedStack* stack,
1619 const std::deque<InstrumentationStackFrame>* instrumentation_stack,
Elliott Hughes6e9d22c2012-06-22 15:02:37 -07001620 size_t start_frame, size_t frame_count, JDWP::ExpandBuf* buf)
Ian Rogersb726dcb2012-09-05 08:57:23 -07001621 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_)
jeffhao725a9572012-11-13 18:20:12 -08001622 : StackVisitor(stack, instrumentation_stack, NULL), depth_(0),
Elliott Hughes6e9d22c2012-06-22 15:02:37 -07001623 start_frame_(start_frame), frame_count_(frame_count), buf_(buf) {
1624 expandBufAdd4BE(buf_, frame_count_);
Elliott Hughes03181a82011-11-17 17:22:21 -08001625 }
Ian Rogers0399dde2012-06-06 17:09:28 -07001626
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001627 // TODO: Enable annotalysis. We know lock is held in constructor, but abstraction confuses
1628 // annotalysis.
1629 virtual bool VisitFrame() NO_THREAD_SAFETY_ANALYSIS {
Ian Rogers0399dde2012-06-06 17:09:28 -07001630 if (GetMethod()->IsRuntimeMethod()) {
Elliott Hughes530fa002012-03-12 11:44:49 -07001631 return true; // The debugger can't do anything useful with a frame that has no Method*.
Elliott Hughes03181a82011-11-17 17:22:21 -08001632 }
Elliott Hughes6e9d22c2012-06-22 15:02:37 -07001633 if (depth_ >= start_frame_ + frame_count_) {
Elliott Hughes530fa002012-03-12 11:44:49 -07001634 return false;
Elliott Hughes03181a82011-11-17 17:22:21 -08001635 }
Elliott Hughes6e9d22c2012-06-22 15:02:37 -07001636 if (depth_ >= start_frame_) {
1637 JDWP::FrameId frame_id(GetFrameId());
1638 JDWP::JdwpLocation location;
1639 SetLocation(location, GetMethod(), GetDexPc());
Elliott Hughes7baf96f2012-06-22 16:33:50 -07001640 VLOG(jdwp) << StringPrintf(" Frame %3zd: id=%3lld ", depth_, frame_id) << location;
Elliott Hughes6e9d22c2012-06-22 15:02:37 -07001641 expandBufAdd8BE(buf_, frame_id);
1642 expandBufAddLocation(buf_, location);
1643 }
1644 ++depth_;
Elliott Hughes530fa002012-03-12 11:44:49 -07001645 return true;
Elliott Hughes03181a82011-11-17 17:22:21 -08001646 }
Elliott Hughes6e9d22c2012-06-22 15:02:37 -07001647
1648 private:
1649 size_t depth_;
1650 const size_t start_frame_;
1651 const size_t frame_count_;
1652 JDWP::ExpandBuf* buf_;
Elliott Hughes03181a82011-11-17 17:22:21 -08001653 };
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001654
1655 ScopedObjectAccessUnchecked soa(Thread::Current());
jeffhaoa77f0f62012-12-05 17:19:31 -08001656 MutexLock mu(soa.Self(), *Locks::thread_list_lock_);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001657 Thread* thread = DecodeThread(soa, thread_id); // Caller already checked thread is suspended.
Ian Rogers306057f2012-11-26 12:45:53 -08001658 GetFrameVisitor visitor(thread->GetManagedStack(), thread->GetInstrumentationStack(),
1659 start_frame, frame_count, buf);
Ian Rogers0399dde2012-06-06 17:09:28 -07001660 visitor.WalkStack();
Elliott Hughes6e9d22c2012-06-22 15:02:37 -07001661 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001662}
1663
1664JDWP::ObjectId Dbg::GetThreadSelfId() {
Mathieu Chartierdbe6f462012-09-25 16:54:50 -07001665 ScopedObjectAccessUnchecked soa(Thread::Current());
Ian Rogerscfaa4552012-11-26 21:00:08 -08001666 return gRegistry->Add(soa.Self()->GetPeer());
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001667}
1668
Elliott Hughes475fc232011-10-25 15:00:35 -07001669void Dbg::SuspendVM() {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001670 Runtime::Current()->GetThreadList()->SuspendAllForDebugger();
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001671}
1672
1673void Dbg::ResumeVM() {
Elliott Hughesc61a2672012-06-21 14:52:29 -07001674 Runtime::Current()->GetThreadList()->UndoDebuggerSuspensions();
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001675}
1676
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001677JDWP::JdwpError Dbg::SuspendThread(JDWP::ObjectId threadId, bool request_suspension) {
1678
1679 bool timeout;
1680 ScopedLocalRef<jobject> peer(Thread::Current()->GetJniEnv(), NULL);
1681 {
1682 ScopedObjectAccess soa(Thread::Current());
1683 peer.reset(soa.AddLocalReference<jobject>(gRegistry->Get<Object*>(threadId)));
Elliott Hughes4e235312011-12-02 11:34:15 -08001684 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001685 if (peer.get() == NULL) {
1686 LOG(WARNING) << "No such thread for suspend: " << threadId;
1687 return JDWP::ERR_THREAD_NOT_ALIVE;
1688 }
1689 // Suspend thread to build stack trace.
1690 Thread* thread = Thread::SuspendForDebugger(peer.get(), request_suspension, &timeout);
1691 if (thread != NULL) {
1692 return JDWP::ERR_NONE;
1693 } else if (timeout) {
1694 return JDWP::ERR_INTERNAL;
1695 } else {
1696 return JDWP::ERR_THREAD_NOT_ALIVE;
1697 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001698}
1699
1700void Dbg::ResumeThread(JDWP::ObjectId threadId) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001701 ScopedObjectAccessUnchecked soa(Thread::Current());
Elliott Hughes4e235312011-12-02 11:34:15 -08001702 Object* peer = gRegistry->Get<Object*>(threadId);
jeffhaoa77f0f62012-12-05 17:19:31 -08001703 Thread* thread;
1704 {
1705 MutexLock mu(soa.Self(), *Locks::thread_list_lock_);
1706 thread = Thread::FromManagedThread(soa, peer);
1707 }
Elliott Hughes4e235312011-12-02 11:34:15 -08001708 if (thread == NULL) {
1709 LOG(WARNING) << "No such thread for resume: " << peer;
1710 return;
1711 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001712 bool needs_resume;
1713 {
Ian Rogers50b35e22012-10-04 10:09:15 -07001714 MutexLock mu2(soa.Self(), *Locks::thread_suspend_count_lock_);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001715 needs_resume = thread->GetSuspendCount() > 0;
1716 }
1717 if (needs_resume) {
Elliott Hughes546b9862012-06-20 16:06:13 -07001718 Runtime::Current()->GetThreadList()->Resume(thread, true);
1719 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001720}
1721
1722void Dbg::SuspendSelf() {
Elliott Hughes475fc232011-10-25 15:00:35 -07001723 Runtime::Current()->GetThreadList()->SuspendSelfForDebugger();
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001724}
1725
Ian Rogers0399dde2012-06-06 17:09:28 -07001726struct GetThisVisitor : public StackVisitor {
Ian Rogers306057f2012-11-26 12:45:53 -08001727 GetThisVisitor(const ManagedStack* stack,
1728 const std::deque<InstrumentationStackFrame>* instrumentation_stack,
Elliott Hughes6e9d22c2012-06-22 15:02:37 -07001729 Context* context, JDWP::FrameId frameId)
Ian Rogersb726dcb2012-09-05 08:57:23 -07001730 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_)
jeffhao725a9572012-11-13 18:20:12 -08001731 : StackVisitor(stack, instrumentation_stack, context), this_object(NULL), frame_id(frameId) {}
Ian Rogers0399dde2012-06-06 17:09:28 -07001732
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001733 // TODO: Enable annotalysis. We know lock is held in constructor, but abstraction confuses
1734 // annotalysis.
1735 virtual bool VisitFrame() NO_THREAD_SAFETY_ANALYSIS {
Elliott Hughes6e9d22c2012-06-22 15:02:37 -07001736 if (frame_id != GetFrameId()) {
Ian Rogers0399dde2012-06-06 17:09:28 -07001737 return true; // continue
1738 }
Mathieu Chartier66f19252012-09-18 08:57:04 -07001739 AbstractMethod* m = GetMethod();
Ian Rogers0399dde2012-06-06 17:09:28 -07001740 if (m->IsNative() || m->IsStatic()) {
Elliott Hughes6e9d22c2012-06-22 15:02:37 -07001741 this_object = NULL;
Ian Rogers0399dde2012-06-06 17:09:28 -07001742 } else {
1743 uint16_t reg = DemangleSlot(0, m);
Ian Rogers2bcb4a42012-11-08 10:39:18 -08001744 this_object = reinterpret_cast<Object*>(GetVReg(m, reg, kReferenceVReg));
Ian Rogers0399dde2012-06-06 17:09:28 -07001745 }
1746 return false;
Elliott Hughes86b00102011-12-05 17:54:26 -08001747 }
Ian Rogers0399dde2012-06-06 17:09:28 -07001748
Elliott Hughes6e9d22c2012-06-22 15:02:37 -07001749 Object* this_object;
1750 JDWP::FrameId frame_id;
Ian Rogers0399dde2012-06-06 17:09:28 -07001751};
1752
Mathieu Chartier66f19252012-09-18 08:57:04 -07001753static Object* GetThis(Thread* self, AbstractMethod* m, size_t frame_id)
Ian Rogersb726dcb2012-09-05 08:57:23 -07001754 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Elliott Hughescaf76542012-06-28 16:08:22 -07001755 // TODO: should we return the 'this' we passed through to non-static native methods?
Ian Rogers0399dde2012-06-06 17:09:28 -07001756 if (m->IsNative() || m->IsStatic()) {
1757 return NULL;
1758 }
Elliott Hughescaf76542012-06-28 16:08:22 -07001759
Ian Rogers0399dde2012-06-06 17:09:28 -07001760 UniquePtr<Context> context(Context::Create());
jeffhao725a9572012-11-13 18:20:12 -08001761 GetThisVisitor visitor(self->GetManagedStack(), self->GetInstrumentationStack(), context.get(), frame_id);
Elliott Hughescaf76542012-06-28 16:08:22 -07001762 visitor.WalkStack();
1763 return visitor.this_object;
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08001764}
1765
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001766JDWP::JdwpError Dbg::GetThisObject(JDWP::ObjectId thread_id, JDWP::FrameId frame_id,
1767 JDWP::ObjectId* result) {
1768 ScopedObjectAccessUnchecked soa(Thread::Current());
1769 Thread* thread;
1770 {
Ian Rogers50b35e22012-10-04 10:09:15 -07001771 MutexLock mu(soa.Self(), *Locks::thread_list_lock_);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001772 thread = DecodeThread(soa, thread_id);
1773 if (thread == NULL) {
1774 return JDWP::ERR_INVALID_THREAD;
1775 }
Ian Rogers50b35e22012-10-04 10:09:15 -07001776 MutexLock mu2(soa.Self(), *Locks::thread_suspend_count_lock_);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001777 if (!thread->IsSuspended()) {
1778 return JDWP::ERR_THREAD_NOT_SUSPENDED;
1779 }
Elliott Hughes6e9d22c2012-06-22 15:02:37 -07001780 }
Elliott Hughescaf76542012-06-28 16:08:22 -07001781 UniquePtr<Context> context(Context::Create());
jeffhao725a9572012-11-13 18:20:12 -08001782 GetThisVisitor visitor(thread->GetManagedStack(), thread->GetInstrumentationStack(), context.get(), frame_id);
Ian Rogers0399dde2012-06-06 17:09:28 -07001783 visitor.WalkStack();
Elliott Hughes6e9d22c2012-06-22 15:02:37 -07001784 *result = gRegistry->Add(visitor.this_object);
1785 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001786}
1787
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001788void Dbg::GetLocalValue(JDWP::ObjectId threadId, JDWP::FrameId frameId, int slot, JDWP::JdwpTag tag,
1789 uint8_t* buf, size_t width) {
Ian Rogers0399dde2012-06-06 17:09:28 -07001790 struct GetLocalVisitor : public StackVisitor {
Ian Rogers306057f2012-11-26 12:45:53 -08001791 GetLocalVisitor(const ManagedStack* stack,
1792 const std::deque<InstrumentationStackFrame>* instrumentation_stack,
Ian Rogers0399dde2012-06-06 17:09:28 -07001793 Context* context, JDWP::FrameId frameId, int slot, JDWP::JdwpTag tag,
Ian Rogersca190662012-06-26 15:45:57 -07001794 uint8_t* buf, size_t width)
Ian Rogersb726dcb2012-09-05 08:57:23 -07001795 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_)
jeffhao725a9572012-11-13 18:20:12 -08001796 : StackVisitor(stack, instrumentation_stack, context), frame_id_(frameId), slot_(slot), tag_(tag),
Ian Rogersca190662012-06-26 15:45:57 -07001797 buf_(buf), width_(width) {}
1798
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001799 // TODO: Enable annotalysis. We know lock is held in constructor, but abstraction confuses
1800 // annotalysis.
1801 bool VisitFrame() NO_THREAD_SAFETY_ANALYSIS {
Ian Rogers0399dde2012-06-06 17:09:28 -07001802 if (GetFrameId() != frame_id_) {
1803 return true; // Not our frame, carry on.
Elliott Hughesdbb40792011-11-18 17:05:22 -08001804 }
Ian Rogers0399dde2012-06-06 17:09:28 -07001805 // TODO: check that the tag is compatible with the actual type of the slot!
Mathieu Chartier66f19252012-09-18 08:57:04 -07001806 AbstractMethod* m = GetMethod();
Ian Rogers0399dde2012-06-06 17:09:28 -07001807 uint16_t reg = DemangleSlot(slot_, m);
Elliott Hughesdbb40792011-11-18 17:05:22 -08001808
Ian Rogers0399dde2012-06-06 17:09:28 -07001809 switch (tag_) {
1810 case JDWP::JT_BOOLEAN:
1811 {
1812 CHECK_EQ(width_, 1U);
Ian Rogers2bcb4a42012-11-08 10:39:18 -08001813 uint32_t intVal = GetVReg(m, reg, kIntVReg);
Ian Rogers0399dde2012-06-06 17:09:28 -07001814 VLOG(jdwp) << "get boolean local " << reg << " = " << intVal;
1815 JDWP::Set1(buf_+1, intVal != 0);
1816 }
1817 break;
1818 case JDWP::JT_BYTE:
1819 {
1820 CHECK_EQ(width_, 1U);
Ian Rogers2bcb4a42012-11-08 10:39:18 -08001821 uint32_t intVal = GetVReg(m, reg, kIntVReg);
Ian Rogers0399dde2012-06-06 17:09:28 -07001822 VLOG(jdwp) << "get byte local " << reg << " = " << intVal;
1823 JDWP::Set1(buf_+1, intVal);
1824 }
1825 break;
1826 case JDWP::JT_SHORT:
1827 case JDWP::JT_CHAR:
1828 {
1829 CHECK_EQ(width_, 2U);
Ian Rogers2bcb4a42012-11-08 10:39:18 -08001830 uint32_t intVal = GetVReg(m, reg, kIntVReg);
Ian Rogers0399dde2012-06-06 17:09:28 -07001831 VLOG(jdwp) << "get short/char local " << reg << " = " << intVal;
1832 JDWP::Set2BE(buf_+1, intVal);
1833 }
1834 break;
1835 case JDWP::JT_INT:
Ian Rogers2bcb4a42012-11-08 10:39:18 -08001836 {
1837 CHECK_EQ(width_, 4U);
1838 uint32_t intVal = GetVReg(m, reg, kIntVReg);
1839 VLOG(jdwp) << "get int local " << reg << " = " << intVal;
1840 JDWP::Set4BE(buf_+1, intVal);
1841 }
1842 break;
Ian Rogers0399dde2012-06-06 17:09:28 -07001843 case JDWP::JT_FLOAT:
1844 {
1845 CHECK_EQ(width_, 4U);
Ian Rogers2bcb4a42012-11-08 10:39:18 -08001846 uint32_t intVal = GetVReg(m, reg, kFloatVReg);
Ian Rogers0399dde2012-06-06 17:09:28 -07001847 VLOG(jdwp) << "get int/float local " << reg << " = " << intVal;
1848 JDWP::Set4BE(buf_+1, intVal);
1849 }
1850 break;
1851 case JDWP::JT_ARRAY:
1852 {
1853 CHECK_EQ(width_, sizeof(JDWP::ObjectId));
Ian Rogers2bcb4a42012-11-08 10:39:18 -08001854 Object* o = reinterpret_cast<Object*>(GetVReg(m, reg, kReferenceVReg));
Ian Rogers0399dde2012-06-06 17:09:28 -07001855 VLOG(jdwp) << "get array local " << reg << " = " << o;
1856 if (!Runtime::Current()->GetHeap()->IsHeapAddress(o)) {
1857 LOG(FATAL) << "Register " << reg << " expected to hold array: " << o;
1858 }
1859 JDWP::SetObjectId(buf_+1, gRegistry->Add(o));
1860 }
1861 break;
1862 case JDWP::JT_CLASS_LOADER:
1863 case JDWP::JT_CLASS_OBJECT:
1864 case JDWP::JT_OBJECT:
1865 case JDWP::JT_STRING:
1866 case JDWP::JT_THREAD:
1867 case JDWP::JT_THREAD_GROUP:
1868 {
1869 CHECK_EQ(width_, sizeof(JDWP::ObjectId));
Ian Rogers2bcb4a42012-11-08 10:39:18 -08001870 Object* o = reinterpret_cast<Object*>(GetVReg(m, reg, kReferenceVReg));
Ian Rogers0399dde2012-06-06 17:09:28 -07001871 VLOG(jdwp) << "get object local " << reg << " = " << o;
1872 if (!Runtime::Current()->GetHeap()->IsHeapAddress(o)) {
1873 LOG(FATAL) << "Register " << reg << " expected to hold object: " << o;
1874 }
1875 tag_ = TagFromObject(o);
1876 JDWP::SetObjectId(buf_+1, gRegistry->Add(o));
1877 }
1878 break;
1879 case JDWP::JT_DOUBLE:
Ian Rogers2bcb4a42012-11-08 10:39:18 -08001880 {
1881 CHECK_EQ(width_, 8U);
1882 uint32_t lo = GetVReg(m, reg, kDoubleLoVReg);
1883 uint64_t hi = GetVReg(m, reg + 1, kDoubleHiVReg);
1884 uint64_t longVal = (hi << 32) | lo;
1885 VLOG(jdwp) << "get double/long local " << hi << ":" << lo << " = " << longVal;
1886 JDWP::Set8BE(buf_+1, longVal);
1887 }
1888 break;
Ian Rogers0399dde2012-06-06 17:09:28 -07001889 case JDWP::JT_LONG:
1890 {
1891 CHECK_EQ(width_, 8U);
Ian Rogers2bcb4a42012-11-08 10:39:18 -08001892 uint32_t lo = GetVReg(m, reg, kLongLoVReg);
1893 uint64_t hi = GetVReg(m, reg + 1, kLongHiVReg);
Ian Rogers0399dde2012-06-06 17:09:28 -07001894 uint64_t longVal = (hi << 32) | lo;
1895 VLOG(jdwp) << "get double/long local " << hi << ":" << lo << " = " << longVal;
1896 JDWP::Set8BE(buf_+1, longVal);
1897 }
1898 break;
1899 default:
1900 LOG(FATAL) << "Unknown tag " << tag_;
1901 break;
1902 }
1903
1904 // Prepend tag, which may have been updated.
1905 JDWP::Set1(buf_, tag_);
1906 return false;
1907 }
1908
1909 const JDWP::FrameId frame_id_;
1910 const int slot_;
1911 JDWP::JdwpTag tag_;
1912 uint8_t* const buf_;
1913 const size_t width_;
1914 };
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001915
1916 ScopedObjectAccessUnchecked soa(Thread::Current());
jeffhaoa77f0f62012-12-05 17:19:31 -08001917 MutexLock mu(soa.Self(), *Locks::thread_list_lock_);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001918 Thread* thread = DecodeThread(soa, threadId);
Ian Rogers0399dde2012-06-06 17:09:28 -07001919 UniquePtr<Context> context(Context::Create());
jeffhao725a9572012-11-13 18:20:12 -08001920 GetLocalVisitor visitor(thread->GetManagedStack(), thread->GetInstrumentationStack(), context.get(),
Ian Rogers0399dde2012-06-06 17:09:28 -07001921 frameId, slot, tag, buf, width);
1922 visitor.WalkStack();
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001923}
1924
Ian Rogers0399dde2012-06-06 17:09:28 -07001925void Dbg::SetLocalValue(JDWP::ObjectId threadId, JDWP::FrameId frameId, int slot, JDWP::JdwpTag tag,
1926 uint64_t value, size_t width) {
1927 struct SetLocalVisitor : public StackVisitor {
Ian Rogers306057f2012-11-26 12:45:53 -08001928 SetLocalVisitor(const ManagedStack* stack, const std::deque<InstrumentationStackFrame>* instrumentation_stack, Context* context,
Ian Rogers0399dde2012-06-06 17:09:28 -07001929 JDWP::FrameId frame_id, int slot, JDWP::JdwpTag tag, uint64_t value,
Ian Rogersca190662012-06-26 15:45:57 -07001930 size_t width)
Ian Rogersb726dcb2012-09-05 08:57:23 -07001931 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_)
jeffhao725a9572012-11-13 18:20:12 -08001932 : StackVisitor(stack, instrumentation_stack, context),
Elliott Hughes08fc03a2012-06-26 17:34:00 -07001933 frame_id_(frame_id), slot_(slot), tag_(tag), value_(value), width_(width) {}
Ian Rogersca190662012-06-26 15:45:57 -07001934
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001935 // TODO: Enable annotalysis. We know lock is held in constructor, but abstraction confuses
1936 // annotalysis.
1937 bool VisitFrame() NO_THREAD_SAFETY_ANALYSIS {
Ian Rogers0399dde2012-06-06 17:09:28 -07001938 if (GetFrameId() != frame_id_) {
1939 return true; // Not our frame, carry on.
1940 }
1941 // TODO: check that the tag is compatible with the actual type of the slot!
Mathieu Chartier66f19252012-09-18 08:57:04 -07001942 AbstractMethod* m = GetMethod();
Ian Rogers0399dde2012-06-06 17:09:28 -07001943 uint16_t reg = DemangleSlot(slot_, m);
1944
1945 switch (tag_) {
1946 case JDWP::JT_BOOLEAN:
1947 case JDWP::JT_BYTE:
1948 CHECK_EQ(width_, 1U);
Ian Rogers2bcb4a42012-11-08 10:39:18 -08001949 SetVReg(m, reg, static_cast<uint32_t>(value_), kIntVReg);
Ian Rogers0399dde2012-06-06 17:09:28 -07001950 break;
1951 case JDWP::JT_SHORT:
1952 case JDWP::JT_CHAR:
1953 CHECK_EQ(width_, 2U);
Ian Rogers2bcb4a42012-11-08 10:39:18 -08001954 SetVReg(m, reg, static_cast<uint32_t>(value_), kIntVReg);
Ian Rogers0399dde2012-06-06 17:09:28 -07001955 break;
1956 case JDWP::JT_INT:
Ian Rogers2bcb4a42012-11-08 10:39:18 -08001957 CHECK_EQ(width_, 4U);
1958 SetVReg(m, reg, static_cast<uint32_t>(value_), kIntVReg);
1959 break;
Ian Rogers0399dde2012-06-06 17:09:28 -07001960 case JDWP::JT_FLOAT:
1961 CHECK_EQ(width_, 4U);
Ian Rogers2bcb4a42012-11-08 10:39:18 -08001962 SetVReg(m, reg, static_cast<uint32_t>(value_), kFloatVReg);
Ian Rogers0399dde2012-06-06 17:09:28 -07001963 break;
1964 case JDWP::JT_ARRAY:
1965 case JDWP::JT_OBJECT:
1966 case JDWP::JT_STRING:
1967 {
1968 CHECK_EQ(width_, sizeof(JDWP::ObjectId));
1969 Object* o = gRegistry->Get<Object*>(static_cast<JDWP::ObjectId>(value_));
1970 if (o == kInvalidObject) {
1971 UNIMPLEMENTED(FATAL) << "return an error code when given an invalid object to store";
1972 }
Ian Rogers2bcb4a42012-11-08 10:39:18 -08001973 SetVReg(m, reg, static_cast<uint32_t>(reinterpret_cast<uintptr_t>(o)), kReferenceVReg);
Ian Rogers0399dde2012-06-06 17:09:28 -07001974 }
1975 break;
1976 case JDWP::JT_DOUBLE:
Ian Rogers2bcb4a42012-11-08 10:39:18 -08001977 CHECK_EQ(width_, 8U);
1978 SetVReg(m, reg, static_cast<uint32_t>(value_), kDoubleLoVReg);
1979 SetVReg(m, reg + 1, static_cast<uint32_t>(value_ >> 32), kDoubleHiVReg);
1980 break;
Ian Rogers0399dde2012-06-06 17:09:28 -07001981 case JDWP::JT_LONG:
1982 CHECK_EQ(width_, 8U);
Ian Rogers2bcb4a42012-11-08 10:39:18 -08001983 SetVReg(m, reg, static_cast<uint32_t>(value_), kLongLoVReg);
1984 SetVReg(m, reg + 1, static_cast<uint32_t>(value_ >> 32), kLongHiVReg);
Ian Rogers0399dde2012-06-06 17:09:28 -07001985 break;
1986 default:
1987 LOG(FATAL) << "Unknown tag " << tag_;
1988 break;
1989 }
1990 return false;
1991 }
1992
1993 const JDWP::FrameId frame_id_;
1994 const int slot_;
1995 const JDWP::JdwpTag tag_;
1996 const uint64_t value_;
1997 const size_t width_;
1998 };
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001999
2000 ScopedObjectAccessUnchecked soa(Thread::Current());
jeffhaoa77f0f62012-12-05 17:19:31 -08002001 MutexLock mu(soa.Self(), *Locks::thread_list_lock_);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002002 Thread* thread = DecodeThread(soa, threadId);
Elliott Hughes08fc03a2012-06-26 17:34:00 -07002003 UniquePtr<Context> context(Context::Create());
jeffhao725a9572012-11-13 18:20:12 -08002004 SetLocalVisitor visitor(thread->GetManagedStack(), thread->GetInstrumentationStack(), context.get(),
Elliott Hughes08fc03a2012-06-26 17:34:00 -07002005 frameId, slot, tag, value, width);
Ian Rogers0399dde2012-06-06 17:09:28 -07002006 visitor.WalkStack();
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002007}
2008
Mathieu Chartier66f19252012-09-18 08:57:04 -07002009void Dbg::PostLocationEvent(const AbstractMethod* m, int dex_pc, Object* this_object, int event_flags) {
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08002010 Class* c = m->GetDeclaringClass();
2011
2012 JDWP::JdwpLocation location;
Elliott Hughes74847412012-06-20 18:10:21 -07002013 location.type_tag = c->IsInterface() ? JDWP::TT_INTERFACE : JDWP::TT_CLASS;
2014 location.class_id = gRegistry->Add(c);
2015 location.method_id = ToMethodId(m);
Elliott Hughes972a47b2012-02-21 18:16:06 -08002016 location.dex_pc = m->IsNative() ? -1 : dex_pc;
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08002017
2018 // Note we use "NoReg" so we don't keep track of references that are
2019 // never actually sent to the debugger. 'this_id' is only used to
2020 // compare against registered events...
2021 JDWP::ObjectId this_id = static_cast<JDWP::ObjectId>(reinterpret_cast<uintptr_t>(this_object));
2022 if (gJdwpState->PostLocationEvent(&location, this_id, event_flags)) {
2023 // ...unless there's a registered event, in which case we
2024 // need to really track the class and 'this'.
2025 gRegistry->Add(c);
2026 gRegistry->Add(this_object);
2027 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002028}
2029
Elliott Hughescaf76542012-06-28 16:08:22 -07002030void Dbg::PostException(Thread* thread,
Mathieu Chartier66f19252012-09-18 08:57:04 -07002031 JDWP::FrameId throw_frame_id, AbstractMethod* throw_method, uint32_t throw_dex_pc,
2032 AbstractMethod* catch_method, uint32_t catch_dex_pc, Throwable* exception) {
Elliott Hughesc0f09332012-03-26 13:27:06 -07002033 if (!IsDebuggerActive()) {
Ian Rogers0ad5bb82011-12-07 10:16:32 -08002034 return;
2035 }
Elliott Hughes4740cdf2011-12-07 14:07:12 -08002036
Elliott Hughesd07986f2011-12-06 18:27:45 -08002037 JDWP::JdwpLocation throw_location;
Elliott Hughescaf76542012-06-28 16:08:22 -07002038 SetLocation(throw_location, throw_method, throw_dex_pc);
Elliott Hughesd07986f2011-12-06 18:27:45 -08002039 JDWP::JdwpLocation catch_location;
Elliott Hughescaf76542012-06-28 16:08:22 -07002040 SetLocation(catch_location, catch_method, catch_dex_pc);
Elliott Hughesd07986f2011-12-06 18:27:45 -08002041
2042 // We need 'this' for InstanceOnly filters.
Elliott Hughescaf76542012-06-28 16:08:22 -07002043 UniquePtr<Context> context(Context::Create());
jeffhao725a9572012-11-13 18:20:12 -08002044 GetThisVisitor visitor(thread->GetManagedStack(), thread->GetInstrumentationStack(), context.get(), throw_frame_id);
Elliott Hughescaf76542012-06-28 16:08:22 -07002045 visitor.WalkStack();
2046 JDWP::ObjectId this_id = gRegistry->Add(visitor.this_object);
Elliott Hughesd07986f2011-12-06 18:27:45 -08002047
2048 /*
2049 * Hand the event to the JDWP exception handler. Note we're using the
2050 * "NoReg" objectID on the exception, which is not strictly correct --
2051 * the exception object WILL be passed up to the debugger if the
2052 * debugger is interested in the event. We do this because the current
2053 * implementation of the debugger object registry never throws anything
2054 * away, and some people were experiencing a fatal build up of exception
2055 * objects when dealing with certain libraries.
2056 */
2057 JDWP::ObjectId exception_id = static_cast<JDWP::ObjectId>(reinterpret_cast<uintptr_t>(exception));
2058 JDWP::RefTypeId exception_class_id = gRegistry->Add(exception->GetClass());
2059
2060 gJdwpState->PostException(&throw_location, exception_id, exception_class_id, &catch_location, this_id);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002061}
2062
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002063void Dbg::PostClassPrepare(Class* c) {
Elliott Hughesc0f09332012-03-26 13:27:06 -07002064 if (!IsDebuggerActive()) {
Elliott Hughes4740cdf2011-12-07 14:07:12 -08002065 return;
2066 }
2067
Elliott Hughes3d30d9b2011-12-07 17:35:48 -08002068 // OLD-TODO - we currently always send both "verified" and "prepared" since
Elliott Hughes4740cdf2011-12-07 14:07:12 -08002069 // debuggers seem to like that. There might be some advantage to honesty,
2070 // since the class may not yet be verified.
2071 int state = JDWP::CS_VERIFIED | JDWP::CS_PREPARED;
2072 JDWP::JdwpTypeTag tag = c->IsInterface() ? JDWP::TT_INTERFACE : JDWP::TT_CLASS;
2073 gJdwpState->PostClassPrepare(tag, gRegistry->Add(c), ClassHelper(c).GetDescriptor(), state);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002074}
2075
Elliott Hughescaf76542012-06-28 16:08:22 -07002076void Dbg::UpdateDebugger(int32_t dex_pc, Thread* self) {
Elliott Hughesc0f09332012-03-26 13:27:06 -07002077 if (!IsDebuggerActive() || dex_pc == -2 /* fake method exit */) {
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08002078 return;
2079 }
2080
Elliott Hughescaf76542012-06-28 16:08:22 -07002081 size_t frame_id;
Mathieu Chartier66f19252012-09-18 08:57:04 -07002082 AbstractMethod* m = self->GetCurrentMethod(NULL, &frame_id);
Elliott Hughescaf76542012-06-28 16:08:22 -07002083 //LOG(INFO) << "UpdateDebugger " << PrettyMethod(m) << "@" << dex_pc << " frame " << frame_id;
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08002084
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08002085 if (dex_pc == -1) {
Elliott Hughes2aa2e392012-02-17 17:15:43 -08002086 // We use a pc of -1 to represent method entry, since we might branch back to pc 0 later.
2087 // This means that for this special notification, there can't be anything else interesting
2088 // going on, so we're done already.
Elliott Hughescaf76542012-06-28 16:08:22 -07002089 Dbg::PostLocationEvent(m, 0, GetThis(self, m, frame_id), kMethodEntry);
Elliott Hughes2aa2e392012-02-17 17:15:43 -08002090 return;
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08002091 }
2092
Elliott Hughes2aa2e392012-02-17 17:15:43 -08002093 int event_flags = 0;
2094
Elliott Hughes86964332012-02-15 19:37:42 -08002095 if (IsBreakpoint(m, dex_pc)) {
2096 event_flags |= kBreakpoint;
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08002097 }
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08002098
jeffhao09bfc6a2012-12-11 18:11:43 -08002099 {
2100 // If the debugger is single-stepping one of our threads, check to
2101 // see if we're that thread and we've reached a step point.
2102 MutexLock mu(Thread::Current(), *Locks::breakpoint_lock_);
2103 if (gSingleStepControl.is_active && gSingleStepControl.thread == self) {
2104 CHECK(!m->IsNative());
2105 if (gSingleStepControl.step_depth == JDWP::SD_INTO) {
2106 // Step into method calls. We break when the line number
2107 // or method pointer changes. If we're in SS_MIN mode, we
2108 // always stop.
2109 if (gSingleStepControl.method != m) {
2110 event_flags |= kSingleStep;
2111 VLOG(jdwp) << "SS new method";
2112 } else if (gSingleStepControl.step_size == JDWP::SS_MIN) {
Elliott Hughes86964332012-02-15 19:37:42 -08002113 event_flags |= kSingleStep;
2114 VLOG(jdwp) << "SS new instruction";
Elliott Hughes2435a572012-02-17 16:07:41 -08002115 } else if (gSingleStepControl.dex_pcs.find(dex_pc) == gSingleStepControl.dex_pcs.end()) {
2116 event_flags |= kSingleStep;
2117 VLOG(jdwp) << "SS new line";
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08002118 }
jeffhao09bfc6a2012-12-11 18:11:43 -08002119 } else if (gSingleStepControl.step_depth == JDWP::SD_OVER) {
2120 // Step over method calls. We break when the line number is
2121 // different and the frame depth is <= the original frame
2122 // depth. (We can't just compare on the method, because we
2123 // might get unrolled past it by an exception, and it's tricky
2124 // to identify recursion.)
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08002125
jeffhao09bfc6a2012-12-11 18:11:43 -08002126 int stack_depth = GetStackDepth(self);
Elliott Hughes86964332012-02-15 19:37:42 -08002127
jeffhao09bfc6a2012-12-11 18:11:43 -08002128 if (stack_depth < gSingleStepControl.stack_depth) {
2129 // popped up one or more frames, always trigger
2130 event_flags |= kSingleStep;
2131 VLOG(jdwp) << "SS method pop";
2132 } else if (stack_depth == gSingleStepControl.stack_depth) {
2133 // same depth, see if we moved
2134 if (gSingleStepControl.step_size == JDWP::SS_MIN) {
2135 event_flags |= kSingleStep;
2136 VLOG(jdwp) << "SS new instruction";
2137 } else if (gSingleStepControl.dex_pcs.find(dex_pc) == gSingleStepControl.dex_pcs.end()) {
2138 event_flags |= kSingleStep;
2139 VLOG(jdwp) << "SS new line";
2140 }
2141 }
2142 } else {
2143 CHECK_EQ(gSingleStepControl.step_depth, JDWP::SD_OUT);
2144 // Return from the current method. We break when the frame
2145 // depth pops up.
2146
2147 // This differs from the "method exit" break in that it stops
2148 // with the PC at the next instruction in the returned-to
2149 // function, rather than the end of the returning function.
2150
2151 int stack_depth = GetStackDepth(self);
2152 if (stack_depth < gSingleStepControl.stack_depth) {
2153 event_flags |= kSingleStep;
2154 VLOG(jdwp) << "SS method pop";
2155 }
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08002156 }
2157 }
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08002158 }
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08002159
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08002160 // Check to see if this is a "return" instruction. JDWP says we should
2161 // send the event *after* the code has been executed, but it also says
2162 // the location we provide is the last instruction. Since the "return"
2163 // instruction has no interesting side effects, we should be safe.
2164 // (We can't just move this down to the returnFromMethod label because
2165 // we potentially need to combine it with other events.)
2166 // We're also not supposed to generate a method exit event if the method
2167 // terminates "with a thrown exception".
Elliott Hughes86964332012-02-15 19:37:42 -08002168 if (dex_pc >= 0) {
2169 const DexFile::CodeItem* code_item = MethodHelper(m).GetCodeItem();
Elliott Hughescaf76542012-06-28 16:08:22 -07002170 CHECK(code_item != NULL) << PrettyMethod(m) << " @" << dex_pc;
Elliott Hughes86964332012-02-15 19:37:42 -08002171 CHECK_LT(dex_pc, static_cast<int32_t>(code_item->insns_size_in_code_units_));
2172 if (Instruction::At(&code_item->insns_[dex_pc])->IsReturn()) {
2173 event_flags |= kMethodExit;
2174 }
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08002175 }
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08002176
2177 // If there's something interesting going on, see if it matches one
2178 // of the debugger filters.
2179 if (event_flags != 0) {
Elliott Hughescaf76542012-06-28 16:08:22 -07002180 Dbg::PostLocationEvent(m, dex_pc, GetThis(self, m, frame_id), event_flags);
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08002181 }
2182}
2183
Elliott Hughes86964332012-02-15 19:37:42 -08002184void Dbg::WatchLocation(const JDWP::JdwpLocation* location) {
jeffhao09bfc6a2012-12-11 18:11:43 -08002185 MutexLock mu(Thread::Current(), *Locks::breakpoint_lock_);
Mathieu Chartier66f19252012-09-18 08:57:04 -07002186 AbstractMethod* m = FromMethodId(location->method_id);
Elliott Hughes972a47b2012-02-21 18:16:06 -08002187 gBreakpoints.push_back(Breakpoint(m, location->dex_pc));
Elliott Hughes86964332012-02-15 19:37:42 -08002188 VLOG(jdwp) << "Set breakpoint #" << (gBreakpoints.size() - 1) << ": " << gBreakpoints[gBreakpoints.size() - 1];
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002189}
2190
Elliott Hughes86964332012-02-15 19:37:42 -08002191void Dbg::UnwatchLocation(const JDWP::JdwpLocation* location) {
jeffhao09bfc6a2012-12-11 18:11:43 -08002192 MutexLock mu(Thread::Current(), *Locks::breakpoint_lock_);
Mathieu Chartier66f19252012-09-18 08:57:04 -07002193 AbstractMethod* m = FromMethodId(location->method_id);
Elliott Hughes86964332012-02-15 19:37:42 -08002194 for (size_t i = 0; i < gBreakpoints.size(); ++i) {
Elliott Hughes972a47b2012-02-21 18:16:06 -08002195 if (gBreakpoints[i].method == m && gBreakpoints[i].dex_pc == location->dex_pc) {
Elliott Hughes86964332012-02-15 19:37:42 -08002196 VLOG(jdwp) << "Removed breakpoint #" << i << ": " << gBreakpoints[i];
2197 gBreakpoints.erase(gBreakpoints.begin() + i);
2198 return;
2199 }
2200 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002201}
2202
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002203JDWP::JdwpError Dbg::ConfigureStep(JDWP::ObjectId threadId, JDWP::JdwpStepSize step_size,
2204 JDWP::JdwpStepDepth step_depth) {
2205 ScopedObjectAccessUnchecked soa(Thread::Current());
jeffhaoa77f0f62012-12-05 17:19:31 -08002206 MutexLock mu(soa.Self(), *Locks::thread_list_lock_);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002207 Thread* thread = DecodeThread(soa, threadId);
Elliott Hughes2435a572012-02-17 16:07:41 -08002208 if (thread == NULL) {
2209 return JDWP::ERR_INVALID_THREAD;
2210 }
Elliott Hughes86964332012-02-15 19:37:42 -08002211
jeffhao09bfc6a2012-12-11 18:11:43 -08002212 MutexLock mu2(soa.Self(), *Locks::breakpoint_lock_);
Elliott Hughes86964332012-02-15 19:37:42 -08002213 // TODO: there's no theoretical reason why we couldn't support single-stepping
2214 // of multiple threads at once, but we never did so historically.
2215 if (gSingleStepControl.thread != NULL && thread != gSingleStepControl.thread) {
2216 LOG(WARNING) << "single-step already active for " << *gSingleStepControl.thread
2217 << "; switching to " << *thread;
2218 }
2219
Elliott Hughes2435a572012-02-17 16:07:41 -08002220 //
2221 // Work out what Method* we're in, the current line number, and how deep the stack currently
2222 // is for step-out.
2223 //
2224
Ian Rogers0399dde2012-06-06 17:09:28 -07002225 struct SingleStepStackVisitor : public StackVisitor {
2226 SingleStepStackVisitor(const ManagedStack* stack,
Ian Rogers306057f2012-11-26 12:45:53 -08002227 const std::deque<InstrumentationStackFrame>* instrumentation_stack)
jeffhao09bfc6a2012-12-11 18:11:43 -08002228 EXCLUSIVE_LOCKS_REQUIRED(Locks::breakpoint_lock_)
Ian Rogersb726dcb2012-09-05 08:57:23 -07002229 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_)
jeffhao725a9572012-11-13 18:20:12 -08002230 : StackVisitor(stack, instrumentation_stack, NULL) {
Elliott Hughes86964332012-02-15 19:37:42 -08002231 gSingleStepControl.method = NULL;
2232 gSingleStepControl.stack_depth = 0;
2233 }
Ian Rogersca190662012-06-26 15:45:57 -07002234
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002235 // TODO: Enable annotalysis. We know lock is held in constructor, but abstraction confuses
2236 // annotalysis.
2237 bool VisitFrame() NO_THREAD_SAFETY_ANALYSIS {
jeffhao09bfc6a2012-12-11 18:11:43 -08002238 Locks::breakpoint_lock_->AssertHeld(Thread::Current());
Mathieu Chartier66f19252012-09-18 08:57:04 -07002239 const AbstractMethod* m = GetMethod();
Ian Rogers0399dde2012-06-06 17:09:28 -07002240 if (!m->IsRuntimeMethod()) {
Elliott Hughes86964332012-02-15 19:37:42 -08002241 ++gSingleStepControl.stack_depth;
2242 if (gSingleStepControl.method == NULL) {
Elliott Hughes2435a572012-02-17 16:07:41 -08002243 const DexCache* dex_cache = m->GetDeclaringClass()->GetDexCache();
2244 gSingleStepControl.method = m;
2245 gSingleStepControl.line_number = -1;
2246 if (dex_cache != NULL) {
Ian Rogers4445a7e2012-10-05 17:19:13 -07002247 const DexFile& dex_file = *dex_cache->GetDexFile();
Ian Rogers0399dde2012-06-06 17:09:28 -07002248 gSingleStepControl.line_number = dex_file.GetLineNumFromPC(m, GetDexPc());
Elliott Hughes2435a572012-02-17 16:07:41 -08002249 }
Elliott Hughes86964332012-02-15 19:37:42 -08002250 }
2251 }
Elliott Hughes530fa002012-03-12 11:44:49 -07002252 return true;
Elliott Hughes86964332012-02-15 19:37:42 -08002253 }
2254 };
jeffhao725a9572012-11-13 18:20:12 -08002255 SingleStepStackVisitor visitor(thread->GetManagedStack(), thread->GetInstrumentationStack());
Ian Rogers0399dde2012-06-06 17:09:28 -07002256 visitor.WalkStack();
Elliott Hughes86964332012-02-15 19:37:42 -08002257
Elliott Hughes2435a572012-02-17 16:07:41 -08002258 //
2259 // Find the dex_pc values that correspond to the current line, for line-based single-stepping.
2260 //
2261
2262 struct DebugCallbackContext {
jeffhao09bfc6a2012-12-11 18:11:43 -08002263 DebugCallbackContext() EXCLUSIVE_LOCKS_REQUIRED(Locks::breakpoint_lock_) {
Elliott Hughes2435a572012-02-17 16:07:41 -08002264 last_pc_valid = false;
2265 last_pc = 0;
Elliott Hughes2435a572012-02-17 16:07:41 -08002266 }
2267
jeffhao09bfc6a2012-12-11 18:11:43 -08002268 // TODO: Enable annotalysis. We know lock is held in constructor, but abstraction confuses
2269 // annotalysis.
2270 static bool Callback(void* raw_context, uint32_t address, uint32_t line_number) NO_THREAD_SAFETY_ANALYSIS {
2271 Locks::breakpoint_lock_->AssertHeld(Thread::Current());
Elliott Hughes2435a572012-02-17 16:07:41 -08002272 DebugCallbackContext* context = reinterpret_cast<DebugCallbackContext*>(raw_context);
2273 if (static_cast<int32_t>(line_number) == gSingleStepControl.line_number) {
2274 if (!context->last_pc_valid) {
2275 // Everything from this address until the next line change is ours.
2276 context->last_pc = address;
2277 context->last_pc_valid = true;
2278 }
2279 // Otherwise, if we're already in a valid range for this line,
2280 // just keep going (shouldn't really happen)...
2281 } else if (context->last_pc_valid) { // and the line number is new
2282 // Add everything from the last entry up until here to the set
2283 for (uint32_t dex_pc = context->last_pc; dex_pc < address; ++dex_pc) {
2284 gSingleStepControl.dex_pcs.insert(dex_pc);
2285 }
2286 context->last_pc_valid = false;
2287 }
2288 return false; // There may be multiple entries for any given line.
2289 }
2290
jeffhao09bfc6a2012-12-11 18:11:43 -08002291 // TODO: Enable annotalysis. We know lock is held in constructor, but abstraction confuses
2292 // annotalysis.
2293 ~DebugCallbackContext() NO_THREAD_SAFETY_ANALYSIS {
2294 Locks::breakpoint_lock_->AssertHeld(Thread::Current());
Elliott Hughes2435a572012-02-17 16:07:41 -08002295 // If the line number was the last in the position table...
2296 if (last_pc_valid) {
2297 size_t end = MethodHelper(gSingleStepControl.method).GetCodeItem()->insns_size_in_code_units_;
2298 for (uint32_t dex_pc = last_pc; dex_pc < end; ++dex_pc) {
2299 gSingleStepControl.dex_pcs.insert(dex_pc);
2300 }
2301 }
2302 }
2303
2304 bool last_pc_valid;
2305 uint32_t last_pc;
2306 };
Elliott Hughes3e2e1a22012-02-21 11:33:41 -08002307 gSingleStepControl.dex_pcs.clear();
Mathieu Chartier66f19252012-09-18 08:57:04 -07002308 const AbstractMethod* m = gSingleStepControl.method;
Elliott Hughes3e2e1a22012-02-21 11:33:41 -08002309 if (m->IsNative()) {
2310 gSingleStepControl.line_number = -1;
2311 } else {
2312 DebugCallbackContext context;
2313 MethodHelper mh(m);
2314 mh.GetDexFile().DecodeDebugInfo(mh.GetCodeItem(), m->IsStatic(), m->GetDexMethodIndex(),
2315 DebugCallbackContext::Callback, NULL, &context);
2316 }
Elliott Hughes2435a572012-02-17 16:07:41 -08002317
2318 //
2319 // Everything else...
2320 //
2321
Elliott Hughes86964332012-02-15 19:37:42 -08002322 gSingleStepControl.thread = thread;
2323 gSingleStepControl.step_size = step_size;
2324 gSingleStepControl.step_depth = step_depth;
2325 gSingleStepControl.is_active = true;
2326
Elliott Hughes2435a572012-02-17 16:07:41 -08002327 if (VLOG_IS_ON(jdwp)) {
2328 VLOG(jdwp) << "Single-step thread: " << *gSingleStepControl.thread;
2329 VLOG(jdwp) << "Single-step step size: " << gSingleStepControl.step_size;
2330 VLOG(jdwp) << "Single-step step depth: " << gSingleStepControl.step_depth;
2331 VLOG(jdwp) << "Single-step current method: " << PrettyMethod(gSingleStepControl.method);
2332 VLOG(jdwp) << "Single-step current line: " << gSingleStepControl.line_number;
2333 VLOG(jdwp) << "Single-step current stack depth: " << gSingleStepControl.stack_depth;
2334 VLOG(jdwp) << "Single-step dex_pc values:";
2335 for (std::set<uint32_t>::iterator it = gSingleStepControl.dex_pcs.begin() ; it != gSingleStepControl.dex_pcs.end(); ++it) {
Elliott Hughes229feb72012-02-23 13:33:29 -08002336 VLOG(jdwp) << StringPrintf(" %#x", *it);
Elliott Hughes2435a572012-02-17 16:07:41 -08002337 }
2338 }
2339
2340 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002341}
2342
Elliott Hughes1bac54f2012-03-16 12:48:31 -07002343void Dbg::UnconfigureStep(JDWP::ObjectId /*threadId*/) {
jeffhao09bfc6a2012-12-11 18:11:43 -08002344 MutexLock mu(Thread::Current(), *Locks::breakpoint_lock_);
Elliott Hughesf8349362012-06-18 15:00:06 -07002345
Elliott Hughes86964332012-02-15 19:37:42 -08002346 gSingleStepControl.is_active = false;
2347 gSingleStepControl.thread = NULL;
Elliott Hughes2435a572012-02-17 16:07:41 -08002348 gSingleStepControl.dex_pcs.clear();
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002349}
2350
Elliott Hughes45651fd2012-02-21 15:48:20 -08002351static char JdwpTagToShortyChar(JDWP::JdwpTag tag) {
2352 switch (tag) {
2353 default:
2354 LOG(FATAL) << "unknown JDWP tag: " << PrintableChar(tag);
2355
2356 // Primitives.
2357 case JDWP::JT_BYTE: return 'B';
2358 case JDWP::JT_CHAR: return 'C';
2359 case JDWP::JT_FLOAT: return 'F';
2360 case JDWP::JT_DOUBLE: return 'D';
2361 case JDWP::JT_INT: return 'I';
2362 case JDWP::JT_LONG: return 'J';
2363 case JDWP::JT_SHORT: return 'S';
2364 case JDWP::JT_VOID: return 'V';
2365 case JDWP::JT_BOOLEAN: return 'Z';
2366
2367 // Reference types.
2368 case JDWP::JT_ARRAY:
2369 case JDWP::JT_OBJECT:
2370 case JDWP::JT_STRING:
2371 case JDWP::JT_THREAD:
2372 case JDWP::JT_THREAD_GROUP:
2373 case JDWP::JT_CLASS_LOADER:
2374 case JDWP::JT_CLASS_OBJECT:
2375 return 'L';
2376 }
2377}
2378
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002379JDWP::JdwpError Dbg::InvokeMethod(JDWP::ObjectId threadId, JDWP::ObjectId objectId,
2380 JDWP::RefTypeId classId, JDWP::MethodId methodId,
2381 uint32_t arg_count, uint64_t* arg_values,
2382 JDWP::JdwpTag* arg_types, uint32_t options,
2383 JDWP::JdwpTag* pResultTag, uint64_t* pResultValue,
2384 JDWP::ObjectId* pExceptionId) {
Elliott Hughesd07986f2011-12-06 18:27:45 -08002385 ThreadList* thread_list = Runtime::Current()->GetThreadList();
2386
2387 Thread* targetThread = NULL;
2388 DebugInvokeReq* req = NULL;
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002389 Thread* self = Thread::Current();
Elliott Hughesd07986f2011-12-06 18:27:45 -08002390 {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002391 ScopedObjectAccessUnchecked soa(self);
Ian Rogers50b35e22012-10-04 10:09:15 -07002392 MutexLock mu(soa.Self(), *Locks::thread_list_lock_);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002393 targetThread = DecodeThread(soa, threadId);
Elliott Hughesd07986f2011-12-06 18:27:45 -08002394 if (targetThread == NULL) {
2395 LOG(ERROR) << "InvokeMethod request for non-existent thread " << threadId;
2396 return JDWP::ERR_INVALID_THREAD;
2397 }
2398 req = targetThread->GetInvokeReq();
2399 if (!req->ready) {
2400 LOG(ERROR) << "InvokeMethod request for thread not stopped by event: " << *targetThread;
2401 return JDWP::ERR_INVALID_THREAD;
2402 }
2403
2404 /*
2405 * We currently have a bug where we don't successfully resume the
2406 * target thread if the suspend count is too deep. We're expected to
2407 * require one "resume" for each "suspend", but when asked to execute
2408 * a method we have to resume fully and then re-suspend it back to the
2409 * same level. (The easiest way to cause this is to type "suspend"
2410 * multiple times in jdb.)
2411 *
2412 * It's unclear what this means when the event specifies "resume all"
2413 * and some threads are suspended more deeply than others. This is
2414 * a rare problem, so for now we just prevent it from hanging forever
2415 * by rejecting the method invocation request. Without this, we will
2416 * be stuck waiting on a suspended thread.
2417 */
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002418 int suspend_count;
2419 {
Ian Rogers50b35e22012-10-04 10:09:15 -07002420 MutexLock mu2(soa.Self(), *Locks::thread_suspend_count_lock_);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002421 suspend_count = targetThread->GetSuspendCount();
2422 }
Elliott Hughesd07986f2011-12-06 18:27:45 -08002423 if (suspend_count > 1) {
2424 LOG(ERROR) << *targetThread << " suspend count too deep for method invocation: " << suspend_count;
2425 return JDWP::ERR_THREAD_SUSPENDED; // Probably not expected here.
2426 }
2427
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08002428 JDWP::JdwpError status;
Elliott Hughes45651fd2012-02-21 15:48:20 -08002429 Object* receiver = gRegistry->Get<Object*>(objectId);
2430 if (receiver == kInvalidObject) {
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08002431 return JDWP::ERR_INVALID_OBJECT;
2432 }
Elliott Hughes45651fd2012-02-21 15:48:20 -08002433
2434 Object* thread = gRegistry->Get<Object*>(threadId);
2435 if (thread == kInvalidObject) {
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08002436 return JDWP::ERR_INVALID_OBJECT;
2437 }
Elliott Hughes45651fd2012-02-21 15:48:20 -08002438 // TODO: check that 'thread' is actually a java.lang.Thread!
2439
2440 Class* c = DecodeClass(classId, status);
2441 if (c == NULL) {
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08002442 return status;
2443 }
Elliott Hughes45651fd2012-02-21 15:48:20 -08002444
Mathieu Chartier66f19252012-09-18 08:57:04 -07002445 AbstractMethod* m = FromMethodId(methodId);
Elliott Hughes45651fd2012-02-21 15:48:20 -08002446 if (m->IsStatic() != (receiver == NULL)) {
2447 return JDWP::ERR_INVALID_METHODID;
2448 }
2449 if (m->IsStatic()) {
2450 if (m->GetDeclaringClass() != c) {
2451 return JDWP::ERR_INVALID_METHODID;
2452 }
2453 } else {
2454 if (!m->GetDeclaringClass()->IsAssignableFrom(c)) {
2455 return JDWP::ERR_INVALID_METHODID;
2456 }
2457 }
2458
2459 // Check the argument list matches the method.
2460 MethodHelper mh(m);
2461 if (mh.GetShortyLength() - 1 != arg_count) {
2462 return JDWP::ERR_ILLEGAL_ARGUMENT;
2463 }
2464 const char* shorty = mh.GetShorty();
2465 for (size_t i = 0; i < arg_count; ++i) {
2466 if (shorty[i + 1] != JdwpTagToShortyChar(arg_types[i])) {
2467 return JDWP::ERR_ILLEGAL_ARGUMENT;
2468 }
2469 }
2470
2471 req->receiver_ = receiver;
2472 req->thread_ = thread;
2473 req->class_ = c;
2474 req->method_ = m;
2475 req->arg_count_ = arg_count;
2476 req->arg_values_ = arg_values;
Elliott Hughesd07986f2011-12-06 18:27:45 -08002477 req->options_ = options;
2478 req->invoke_needed_ = true;
2479 }
2480
2481 // The fact that we've released the thread list lock is a bit risky --- if the thread goes
2482 // away we're sitting high and dry -- but we must release this before the ResumeAllThreads
2483 // call, and it's unwise to hold it during WaitForSuspend.
2484
2485 {
2486 /*
2487 * We change our (JDWP thread) status, which should be THREAD_RUNNING,
Elliott Hughes81ff3182012-03-23 20:35:56 -07002488 * so we can suspend for a GC if the invoke request causes us to
Elliott Hughesd07986f2011-12-06 18:27:45 -08002489 * run out of memory. It's also a good idea to change it before locking
2490 * the invokeReq mutex, although that should never be held for long.
2491 */
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002492 self->TransitionFromRunnableToSuspended(kWaitingForDebuggerSend);
Elliott Hughesd07986f2011-12-06 18:27:45 -08002493
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08002494 VLOG(jdwp) << " Transferring control to event thread";
Elliott Hughesd07986f2011-12-06 18:27:45 -08002495 {
Ian Rogers50b35e22012-10-04 10:09:15 -07002496 MutexLock mu(self, req->lock_);
Elliott Hughesd07986f2011-12-06 18:27:45 -08002497
2498 if ((options & JDWP::INVOKE_SINGLE_THREADED) == 0) {
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08002499 VLOG(jdwp) << " Resuming all threads";
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002500 thread_list->UndoDebuggerSuspensions();
Elliott Hughesd07986f2011-12-06 18:27:45 -08002501 } else {
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08002502 VLOG(jdwp) << " Resuming event thread only";
Elliott Hughesd07986f2011-12-06 18:27:45 -08002503 thread_list->Resume(targetThread, true);
2504 }
2505
2506 // Wait for the request to finish executing.
2507 while (req->invoke_needed_) {
Ian Rogersc604d732012-10-14 16:09:54 -07002508 req->cond_.Wait(self);
Elliott Hughesd07986f2011-12-06 18:27:45 -08002509 }
2510 }
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08002511 VLOG(jdwp) << " Control has returned from event thread";
Elliott Hughesd07986f2011-12-06 18:27:45 -08002512
2513 /* wait for thread to re-suspend itself */
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002514 SuspendThread(threadId, false /* request_suspension */ );
2515 self->TransitionFromSuspendedToRunnable();
Elliott Hughesd07986f2011-12-06 18:27:45 -08002516 }
2517
2518 /*
2519 * Suspend the threads. We waited for the target thread to suspend
2520 * itself, so all we need to do is suspend the others.
2521 *
2522 * The suspendAllThreads() call will double-suspend the event thread,
2523 * so we want to resume the target thread once to keep the books straight.
2524 */
2525 if ((options & JDWP::INVOKE_SINGLE_THREADED) == 0) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002526 self->TransitionFromRunnableToSuspended(kWaitingForDebuggerSuspension);
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08002527 VLOG(jdwp) << " Suspending all threads";
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002528 thread_list->SuspendAllForDebugger();
2529 self->TransitionFromSuspendedToRunnable();
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08002530 VLOG(jdwp) << " Resuming event thread to balance the count";
Elliott Hughesd07986f2011-12-06 18:27:45 -08002531 thread_list->Resume(targetThread, true);
2532 }
2533
2534 // Copy the result.
2535 *pResultTag = req->result_tag;
2536 if (IsPrimitiveTag(req->result_tag)) {
Elliott Hughesf24d3ce2012-04-11 17:43:37 -07002537 *pResultValue = req->result_value.GetJ();
Elliott Hughesd07986f2011-12-06 18:27:45 -08002538 } else {
Elliott Hughesf24d3ce2012-04-11 17:43:37 -07002539 *pResultValue = gRegistry->Add(req->result_value.GetL());
Elliott Hughesd07986f2011-12-06 18:27:45 -08002540 }
2541 *pExceptionId = req->exception;
2542 return req->error;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002543}
2544
2545void Dbg::ExecuteMethod(DebugInvokeReq* pReq) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002546 ScopedObjectAccess soa(Thread::Current());
Elliott Hughesd07986f2011-12-06 18:27:45 -08002547
Elliott Hughes81ff3182012-03-23 20:35:56 -07002548 // We can be called while an exception is pending. We need
Elliott Hughesd07986f2011-12-06 18:27:45 -08002549 // to preserve that across the method invocation.
Ian Rogers1f539342012-10-03 21:09:42 -07002550 SirtRef<Throwable> old_exception(soa.Self(), soa.Self()->GetException());
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002551 soa.Self()->ClearException();
Elliott Hughesd07986f2011-12-06 18:27:45 -08002552
2553 // Translate the method through the vtable, unless the debugger wants to suppress it.
Mathieu Chartier66f19252012-09-18 08:57:04 -07002554 AbstractMethod* m = pReq->method_;
Elliott Hughesd07986f2011-12-06 18:27:45 -08002555 if ((pReq->options_ & JDWP::INVOKE_NONVIRTUAL) == 0 && pReq->receiver_ != NULL) {
Mathieu Chartier66f19252012-09-18 08:57:04 -07002556 AbstractMethod* actual_method = pReq->class_->FindVirtualMethodForVirtualOrInterface(pReq->method_);
Elliott Hughes45651fd2012-02-21 15:48:20 -08002557 if (actual_method != m) {
2558 VLOG(jdwp) << "ExecuteMethod translated " << PrettyMethod(m) << " to " << PrettyMethod(actual_method);
2559 m = actual_method;
2560 }
Elliott Hughesd07986f2011-12-06 18:27:45 -08002561 }
Elliott Hughes45651fd2012-02-21 15:48:20 -08002562 VLOG(jdwp) << "ExecuteMethod " << PrettyMethod(m);
Elliott Hughesd07986f2011-12-06 18:27:45 -08002563 CHECK(m != NULL);
2564
2565 CHECK_EQ(sizeof(jvalue), sizeof(uint64_t));
2566
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002567 LOG(INFO) << "self=" << soa.Self() << " pReq->receiver_=" << pReq->receiver_ << " m=" << m
2568 << " #" << pReq->arg_count_ << " " << pReq->arg_values_;
2569 pReq->result_value = InvokeWithJValues(soa, pReq->receiver_, m,
2570 reinterpret_cast<JValue*>(pReq->arg_values_));
Elliott Hughesd07986f2011-12-06 18:27:45 -08002571
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002572 pReq->exception = gRegistry->Add(soa.Self()->GetException());
Elliott Hughesd07986f2011-12-06 18:27:45 -08002573 pReq->result_tag = BasicTagFromDescriptor(MethodHelper(m).GetShorty());
2574 if (pReq->exception != 0) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002575 Object* exc = soa.Self()->GetException();
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08002576 VLOG(jdwp) << " JDWP invocation returning with exception=" << exc << " " << PrettyTypeOf(exc);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002577 soa.Self()->ClearException();
Elliott Hughesf24d3ce2012-04-11 17:43:37 -07002578 pReq->result_value.SetJ(0);
Elliott Hughesd07986f2011-12-06 18:27:45 -08002579 } else if (pReq->result_tag == JDWP::JT_OBJECT) {
2580 /* if no exception thrown, examine object result more closely */
Elliott Hughesf24d3ce2012-04-11 17:43:37 -07002581 JDWP::JdwpTag new_tag = TagFromObject(pReq->result_value.GetL());
Elliott Hughesd07986f2011-12-06 18:27:45 -08002582 if (new_tag != pReq->result_tag) {
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08002583 VLOG(jdwp) << " JDWP promoted result from " << pReq->result_tag << " to " << new_tag;
Elliott Hughesd07986f2011-12-06 18:27:45 -08002584 pReq->result_tag = new_tag;
2585 }
2586
2587 /*
2588 * Register the object. We don't actually need an ObjectId yet,
2589 * but we do need to be sure that the GC won't move or discard the
2590 * object when we switch out of RUNNING. The ObjectId conversion
2591 * will add the object to the "do not touch" list.
2592 *
2593 * We can't use the "tracked allocation" mechanism here because
2594 * the object is going to be handed off to a different thread.
2595 */
Elliott Hughesf24d3ce2012-04-11 17:43:37 -07002596 gRegistry->Add(pReq->result_value.GetL());
Elliott Hughesd07986f2011-12-06 18:27:45 -08002597 }
2598
2599 if (old_exception.get() != NULL) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002600 soa.Self()->SetException(old_exception.get());
Elliott Hughesd07986f2011-12-06 18:27:45 -08002601 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002602}
2603
Elliott Hughesd07986f2011-12-06 18:27:45 -08002604/*
2605 * Register an object ID that might not have been registered previously.
2606 *
2607 * Normally this wouldn't happen -- the conversion to an ObjectId would
2608 * have added the object to the registry -- but in some cases (e.g.
2609 * throwing exceptions) we really want to do the registration late.
2610 */
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002611void Dbg::RegisterObjectId(JDWP::ObjectId id) {
Elliott Hughesd07986f2011-12-06 18:27:45 -08002612 gRegistry->Add(reinterpret_cast<Object*>(id));
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002613}
2614
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07002615/*
2616 * "buf" contains a full JDWP packet, possibly with multiple chunks. We
2617 * need to process each, accumulate the replies, and ship the whole thing
2618 * back.
2619 *
2620 * Returns "true" if we have a reply. The reply buffer is newly allocated,
2621 * and includes the chunk type/length, followed by the data.
2622 *
Elliott Hughes3d30d9b2011-12-07 17:35:48 -08002623 * OLD-TODO: we currently assume that the request and reply include a single
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07002624 * chunk. If this becomes inconvenient we will need to adapt.
2625 */
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002626bool Dbg::DdmHandlePacket(const uint8_t* buf, int dataLen, uint8_t** pReplyBuf, int* pReplyLen) {
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07002627 CHECK_GE(dataLen, 0);
2628
2629 Thread* self = Thread::Current();
2630 JNIEnv* env = self->GetJniEnv();
2631
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07002632 // Create a byte[] corresponding to 'buf'.
Elliott Hughes6a5bd492011-10-28 14:33:57 -07002633 ScopedLocalRef<jbyteArray> dataArray(env, env->NewByteArray(dataLen));
2634 if (dataArray.get() == NULL) {
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07002635 LOG(WARNING) << "byte[] allocation failed: " << dataLen;
2636 env->ExceptionClear();
2637 return false;
2638 }
Elliott Hughes6a5bd492011-10-28 14:33:57 -07002639 env->SetByteArrayRegion(dataArray.get(), 0, dataLen, reinterpret_cast<const jbyte*>(buf));
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07002640
2641 const int kChunkHdrLen = 8;
2642
2643 // Run through and find all chunks. [Currently just find the first.]
Elliott Hughes6a5bd492011-10-28 14:33:57 -07002644 ScopedByteArrayRO contents(env, dataArray.get());
Elliott Hughesf7c3b662011-10-27 12:04:56 -07002645 jint type = JDWP::Get4BE(reinterpret_cast<const uint8_t*>(&contents[0]));
2646 jint length = JDWP::Get4BE(reinterpret_cast<const uint8_t*>(&contents[4]));
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07002647 jint offset = kChunkHdrLen;
2648 if (offset + length > dataLen) {
2649 LOG(WARNING) << StringPrintf("bad chunk found (len=%u pktLen=%d)", length, dataLen);
2650 return false;
2651 }
2652
2653 // Call "private static Chunk dispatch(int type, byte[] data, int offset, int length)".
Elliott Hugheseac76672012-05-24 21:56:51 -07002654 ScopedLocalRef<jobject> chunk(env, env->CallStaticObjectMethod(WellKnownClasses::org_apache_harmony_dalvik_ddmc_DdmServer,
2655 WellKnownClasses::org_apache_harmony_dalvik_ddmc_DdmServer_dispatch,
2656 type, dataArray.get(), offset, length));
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07002657 if (env->ExceptionCheck()) {
2658 LOG(INFO) << StringPrintf("Exception thrown by dispatcher for 0x%08x", type);
2659 env->ExceptionDescribe();
2660 env->ExceptionClear();
2661 return false;
2662 }
2663
Elliott Hughes6a5bd492011-10-28 14:33:57 -07002664 if (chunk.get() == NULL) {
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07002665 return false;
2666 }
2667
2668 /*
2669 * Pull the pieces out of the chunk. We copy the results into a
2670 * newly-allocated buffer that the caller can free. We don't want to
2671 * continue using the Chunk object because nothing has a reference to it.
2672 *
2673 * We could avoid this by returning type/data/offset/length and having
2674 * the caller be aware of the object lifetime issues, but that
Elliott Hughes81ff3182012-03-23 20:35:56 -07002675 * integrates the JDWP code more tightly into the rest of the runtime, and doesn't work
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07002676 * if we have responses for multiple chunks.
2677 *
2678 * So we're pretty much stuck with copying data around multiple times.
2679 */
Elliott Hugheseac76672012-05-24 21:56:51 -07002680 ScopedLocalRef<jbyteArray> replyData(env, reinterpret_cast<jbyteArray>(env->GetObjectField(chunk.get(), WellKnownClasses::org_apache_harmony_dalvik_ddmc_Chunk_data)));
2681 length = env->GetIntField(chunk.get(), WellKnownClasses::org_apache_harmony_dalvik_ddmc_Chunk_length);
2682 offset = env->GetIntField(chunk.get(), WellKnownClasses::org_apache_harmony_dalvik_ddmc_Chunk_offset);
2683 type = env->GetIntField(chunk.get(), WellKnownClasses::org_apache_harmony_dalvik_ddmc_Chunk_type);
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07002684
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08002685 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 -07002686 if (length == 0 || replyData.get() == NULL) {
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07002687 return false;
2688 }
2689
Elliott Hughes6a5bd492011-10-28 14:33:57 -07002690 jsize replyLength = env->GetArrayLength(replyData.get());
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07002691 if (offset + length > replyLength) {
2692 LOG(WARNING) << StringPrintf("chunk off=%d len=%d exceeds reply array len %d", offset, length, replyLength);
2693 return false;
2694 }
2695
2696 uint8_t* reply = new uint8_t[length + kChunkHdrLen];
2697 if (reply == NULL) {
2698 LOG(WARNING) << "malloc failed: " << (length + kChunkHdrLen);
2699 return false;
2700 }
Elliott Hughesf7c3b662011-10-27 12:04:56 -07002701 JDWP::Set4BE(reply + 0, type);
2702 JDWP::Set4BE(reply + 4, length);
Elliott Hughes6a5bd492011-10-28 14:33:57 -07002703 env->GetByteArrayRegion(replyData.get(), offset, length, reinterpret_cast<jbyte*>(reply + kChunkHdrLen));
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07002704
2705 *pReplyBuf = reply;
2706 *pReplyLen = length + kChunkHdrLen;
2707
Elliott Hughesba8eee12012-01-24 20:25:24 -08002708 VLOG(jdwp) << StringPrintf("dvmHandleDdm returning type=%.4s buf=%p len=%d", reinterpret_cast<char*>(reply), reply, length);
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07002709 return true;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002710}
2711
Elliott Hughesa2155262011-11-16 16:26:58 -08002712void Dbg::DdmBroadcast(bool connect) {
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08002713 VLOG(jdwp) << "Broadcasting DDM " << (connect ? "connect" : "disconnect") << "...";
Elliott Hughes47fce012011-10-25 18:37:19 -07002714
2715 Thread* self = Thread::Current();
Ian Rogers50b35e22012-10-04 10:09:15 -07002716 if (self->GetState() != kRunnable) {
2717 LOG(ERROR) << "DDM broadcast in thread state " << self->GetState();
2718 /* try anyway? */
Elliott Hughes47fce012011-10-25 18:37:19 -07002719 }
2720
2721 JNIEnv* env = self->GetJniEnv();
Elliott Hughes47fce012011-10-25 18:37:19 -07002722 jint event = connect ? 1 /*DdmServer.CONNECTED*/ : 2 /*DdmServer.DISCONNECTED*/;
Elliott Hugheseac76672012-05-24 21:56:51 -07002723 env->CallStaticVoidMethod(WellKnownClasses::org_apache_harmony_dalvik_ddmc_DdmServer,
2724 WellKnownClasses::org_apache_harmony_dalvik_ddmc_DdmServer_broadcast,
2725 event);
Elliott Hughes47fce012011-10-25 18:37:19 -07002726 if (env->ExceptionCheck()) {
2727 LOG(ERROR) << "DdmServer.broadcast " << event << " failed";
2728 env->ExceptionDescribe();
2729 env->ExceptionClear();
2730 }
2731}
2732
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002733void Dbg::DdmConnected() {
Elliott Hughesa2155262011-11-16 16:26:58 -08002734 Dbg::DdmBroadcast(true);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002735}
2736
2737void Dbg::DdmDisconnected() {
Elliott Hughesa2155262011-11-16 16:26:58 -08002738 Dbg::DdmBroadcast(false);
Elliott Hughes47fce012011-10-25 18:37:19 -07002739 gDdmThreadNotification = false;
2740}
2741
2742/*
Elliott Hughes82188472011-11-07 18:11:48 -08002743 * Send a notification when a thread starts, stops, or changes its name.
Elliott Hughes47fce012011-10-25 18:37:19 -07002744 *
2745 * Because we broadcast the full set of threads when the notifications are
2746 * first enabled, it's possible for "thread" to be actively executing.
2747 */
Elliott Hughes82188472011-11-07 18:11:48 -08002748void Dbg::DdmSendThreadNotification(Thread* t, uint32_t type) {
Elliott Hughes47fce012011-10-25 18:37:19 -07002749 if (!gDdmThreadNotification) {
2750 return;
2751 }
2752
Elliott Hughes82188472011-11-07 18:11:48 -08002753 if (type == CHUNK_TYPE("THDE")) {
Elliott Hughes47fce012011-10-25 18:37:19 -07002754 uint8_t buf[4];
Elliott Hughesf7c3b662011-10-27 12:04:56 -07002755 JDWP::Set4BE(&buf[0], t->GetThinLockId());
Elliott Hughes47fce012011-10-25 18:37:19 -07002756 Dbg::DdmSendChunk(CHUNK_TYPE("THDE"), 4, buf);
Elliott Hughes82188472011-11-07 18:11:48 -08002757 } else {
2758 CHECK(type == CHUNK_TYPE("THCR") || type == CHUNK_TYPE("THNM")) << type;
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002759 ScopedObjectAccessUnchecked soa(Thread::Current());
Ian Rogers1f539342012-10-03 21:09:42 -07002760 SirtRef<String> name(soa.Self(), t->GetThreadName(soa));
Elliott Hughes82188472011-11-07 18:11:48 -08002761 size_t char_count = (name.get() != NULL) ? name->GetLength() : 0;
jeffhao725a9572012-11-13 18:20:12 -08002762 const jchar* chars = (name.get() != NULL) ? name->GetCharArray()->GetData() : NULL;
Elliott Hughes82188472011-11-07 18:11:48 -08002763
Elliott Hughes21f32d72011-11-09 17:44:13 -08002764 std::vector<uint8_t> bytes;
Elliott Hughes545a0642011-11-08 19:10:03 -08002765 JDWP::Append4BE(bytes, t->GetThinLockId());
2766 JDWP::AppendUtf16BE(bytes, chars, char_count);
Elliott Hughes21f32d72011-11-09 17:44:13 -08002767 CHECK_EQ(bytes.size(), char_count*2 + sizeof(uint32_t)*2);
2768 Dbg::DdmSendChunk(type, bytes);
Elliott Hughes47fce012011-10-25 18:37:19 -07002769 }
2770}
2771
Elliott Hughes47fce012011-10-25 18:37:19 -07002772void Dbg::DdmSetThreadNotification(bool enable) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002773 // Enable/disable thread notifications.
Elliott Hughes47fce012011-10-25 18:37:19 -07002774 gDdmThreadNotification = enable;
2775 if (enable) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002776 // Suspend the VM then post thread start notifications for all threads. Threads attaching will
2777 // see a suspension in progress and block until that ends. They then post their own start
2778 // notification.
2779 SuspendVM();
2780 std::list<Thread*> threads;
Ian Rogers50b35e22012-10-04 10:09:15 -07002781 Thread* self = Thread::Current();
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002782 {
Ian Rogers50b35e22012-10-04 10:09:15 -07002783 MutexLock mu(self, *Locks::thread_list_lock_);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002784 threads = Runtime::Current()->GetThreadList()->GetList();
2785 }
2786 {
Ian Rogers50b35e22012-10-04 10:09:15 -07002787 ScopedObjectAccess soa(self);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002788 typedef std::list<Thread*>::const_iterator It; // TODO: C++0x auto
2789 for (It it = threads.begin(), end = threads.end(); it != end; ++it) {
2790 Dbg::DdmSendThreadNotification(*it, CHUNK_TYPE("THCR"));
2791 }
2792 }
2793 ResumeVM();
Elliott Hughes47fce012011-10-25 18:37:19 -07002794 }
2795}
2796
Elliott Hughesa2155262011-11-16 16:26:58 -08002797void Dbg::PostThreadStartOrStop(Thread* t, uint32_t type) {
Elliott Hughesc0f09332012-03-26 13:27:06 -07002798 if (IsDebuggerActive()) {
Mathieu Chartierdbe6f462012-09-25 16:54:50 -07002799 ScopedObjectAccessUnchecked soa(Thread::Current());
Ian Rogerscfaa4552012-11-26 21:00:08 -08002800 JDWP::ObjectId id = gRegistry->Add(t->GetPeer());
Elliott Hughes82188472011-11-07 18:11:48 -08002801 gJdwpState->PostThreadChange(id, type == CHUNK_TYPE("THCR"));
Elliott Hughesc0f09332012-03-26 13:27:06 -07002802 // If this thread's just joined the party while we're already debugging, make sure it knows
2803 // to give us updates when it's running.
2804 t->SetDebuggerUpdatesEnabled(true);
Elliott Hughes47fce012011-10-25 18:37:19 -07002805 }
Elliott Hughes82188472011-11-07 18:11:48 -08002806 Dbg::DdmSendThreadNotification(t, type);
Elliott Hughes47fce012011-10-25 18:37:19 -07002807}
2808
2809void Dbg::PostThreadStart(Thread* t) {
Elliott Hughesa2155262011-11-16 16:26:58 -08002810 Dbg::PostThreadStartOrStop(t, CHUNK_TYPE("THCR"));
Elliott Hughes47fce012011-10-25 18:37:19 -07002811}
2812
2813void Dbg::PostThreadDeath(Thread* t) {
Elliott Hughesa2155262011-11-16 16:26:58 -08002814 Dbg::PostThreadStartOrStop(t, CHUNK_TYPE("THDE"));
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002815}
2816
Elliott Hughes82188472011-11-07 18:11:48 -08002817void Dbg::DdmSendChunk(uint32_t type, size_t byte_count, const uint8_t* buf) {
Elliott Hughes3bb81562011-10-21 18:52:59 -07002818 CHECK(buf != NULL);
2819 iovec vec[1];
2820 vec[0].iov_base = reinterpret_cast<void*>(const_cast<uint8_t*>(buf));
2821 vec[0].iov_len = byte_count;
2822 Dbg::DdmSendChunkV(type, vec, 1);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002823}
2824
Elliott Hughes21f32d72011-11-09 17:44:13 -08002825void Dbg::DdmSendChunk(uint32_t type, const std::vector<uint8_t>& bytes) {
2826 DdmSendChunk(type, bytes.size(), &bytes[0]);
2827}
2828
Elliott Hughescccd84f2011-12-05 16:51:54 -08002829void Dbg::DdmSendChunkV(uint32_t type, const struct iovec* iov, int iov_count) {
Elliott Hughes3bb81562011-10-21 18:52:59 -07002830 if (gJdwpState == NULL) {
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08002831 VLOG(jdwp) << "Debugger thread not active, ignoring DDM send: " << type;
Elliott Hughes3bb81562011-10-21 18:52:59 -07002832 } else {
Elliott Hughescccd84f2011-12-05 16:51:54 -08002833 gJdwpState->DdmSendChunkV(type, iov, iov_count);
Elliott Hughes3bb81562011-10-21 18:52:59 -07002834 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002835}
2836
Elliott Hughes767a1472011-10-26 18:49:02 -07002837int Dbg::DdmHandleHpifChunk(HpifWhen when) {
2838 if (when == HPIF_WHEN_NOW) {
Elliott Hughes7162ad92011-10-27 14:08:42 -07002839 DdmSendHeapInfo(when);
Elliott Hughes767a1472011-10-26 18:49:02 -07002840 return true;
2841 }
2842
2843 if (when != HPIF_WHEN_NEVER && when != HPIF_WHEN_NEXT_GC && when != HPIF_WHEN_EVERY_GC) {
2844 LOG(ERROR) << "invalid HpifWhen value: " << static_cast<int>(when);
2845 return false;
2846 }
2847
2848 gDdmHpifWhen = when;
2849 return true;
2850}
2851
2852bool Dbg::DdmHandleHpsgNhsgChunk(Dbg::HpsgWhen when, Dbg::HpsgWhat what, bool native) {
2853 if (when != HPSG_WHEN_NEVER && when != HPSG_WHEN_EVERY_GC) {
2854 LOG(ERROR) << "invalid HpsgWhen value: " << static_cast<int>(when);
2855 return false;
2856 }
2857
2858 if (what != HPSG_WHAT_MERGED_OBJECTS && what != HPSG_WHAT_DISTINCT_OBJECTS) {
2859 LOG(ERROR) << "invalid HpsgWhat value: " << static_cast<int>(what);
2860 return false;
2861 }
2862
2863 if (native) {
2864 gDdmNhsgWhen = when;
2865 gDdmNhsgWhat = what;
2866 } else {
2867 gDdmHpsgWhen = when;
2868 gDdmHpsgWhat = what;
2869 }
2870 return true;
2871}
2872
Elliott Hughes7162ad92011-10-27 14:08:42 -07002873void Dbg::DdmSendHeapInfo(HpifWhen reason) {
2874 // If there's a one-shot 'when', reset it.
2875 if (reason == gDdmHpifWhen) {
2876 if (gDdmHpifWhen == HPIF_WHEN_NEXT_GC) {
2877 gDdmHpifWhen = HPIF_WHEN_NEVER;
2878 }
2879 }
2880
2881 /*
2882 * Chunk HPIF (client --> server)
2883 *
2884 * Heap Info. General information about the heap,
2885 * suitable for a summary display.
2886 *
2887 * [u4]: number of heaps
2888 *
2889 * For each heap:
2890 * [u4]: heap ID
2891 * [u8]: timestamp in ms since Unix epoch
2892 * [u1]: capture reason (same as 'when' value from server)
2893 * [u4]: max heap size in bytes (-Xmx)
2894 * [u4]: current heap size in bytes
2895 * [u4]: current number of bytes allocated
2896 * [u4]: current number of objects allocated
2897 */
2898 uint8_t heap_count = 1;
Elliott Hughesb3bd5f02012-03-08 21:05:27 -08002899 Heap* heap = Runtime::Current()->GetHeap();
Elliott Hughes21f32d72011-11-09 17:44:13 -08002900 std::vector<uint8_t> bytes;
Elliott Hughes545a0642011-11-08 19:10:03 -08002901 JDWP::Append4BE(bytes, heap_count);
2902 JDWP::Append4BE(bytes, 1); // Heap id (bogus; we only have one heap).
2903 JDWP::Append8BE(bytes, MilliTime());
2904 JDWP::Append1BE(bytes, reason);
Elliott Hughesb3bd5f02012-03-08 21:05:27 -08002905 JDWP::Append4BE(bytes, heap->GetMaxMemory()); // Max allowed heap size in bytes.
2906 JDWP::Append4BE(bytes, heap->GetTotalMemory()); // Current heap size in bytes.
2907 JDWP::Append4BE(bytes, heap->GetBytesAllocated());
2908 JDWP::Append4BE(bytes, heap->GetObjectsAllocated());
Elliott Hughes21f32d72011-11-09 17:44:13 -08002909 CHECK_EQ(bytes.size(), 4U + (heap_count * (4 + 8 + 1 + 4 + 4 + 4 + 4)));
2910 Dbg::DdmSendChunk(CHUNK_TYPE("HPIF"), bytes);
Elliott Hughes767a1472011-10-26 18:49:02 -07002911}
2912
Elliott Hughes6a5bd492011-10-28 14:33:57 -07002913enum HpsgSolidity {
2914 SOLIDITY_FREE = 0,
2915 SOLIDITY_HARD = 1,
2916 SOLIDITY_SOFT = 2,
2917 SOLIDITY_WEAK = 3,
2918 SOLIDITY_PHANTOM = 4,
2919 SOLIDITY_FINALIZABLE = 5,
2920 SOLIDITY_SWEEP = 6,
2921};
2922
2923enum HpsgKind {
2924 KIND_OBJECT = 0,
2925 KIND_CLASS_OBJECT = 1,
2926 KIND_ARRAY_1 = 2,
2927 KIND_ARRAY_2 = 3,
2928 KIND_ARRAY_4 = 4,
2929 KIND_ARRAY_8 = 5,
2930 KIND_UNKNOWN = 6,
2931 KIND_NATIVE = 7,
2932};
2933
2934#define HPSG_PARTIAL (1<<7)
2935#define HPSG_STATE(solidity, kind) ((uint8_t)((((kind) & 0x7) << 3) | ((solidity) & 0x7)))
2936
Ian Rogers30fab402012-01-23 15:43:46 -08002937class HeapChunkContext {
2938 public:
Elliott Hughes6a5bd492011-10-28 14:33:57 -07002939 // Maximum chunk size. Obtain this from the formula:
2940 // (((maximum_heap_size / ALLOCATION_UNIT_SIZE) + 255) / 256) * 2
2941 HeapChunkContext(bool merge, bool native)
Ian Rogers30fab402012-01-23 15:43:46 -08002942 : buf_(16384 - 16),
2943 type_(0),
2944 merge_(merge) {
Elliott Hughes6a5bd492011-10-28 14:33:57 -07002945 Reset();
2946 if (native) {
Ian Rogers30fab402012-01-23 15:43:46 -08002947 type_ = CHUNK_TYPE("NHSG");
Elliott Hughes6a5bd492011-10-28 14:33:57 -07002948 } else {
Ian Rogers30fab402012-01-23 15:43:46 -08002949 type_ = merge ? CHUNK_TYPE("HPSG") : CHUNK_TYPE("HPSO");
Elliott Hughes6a5bd492011-10-28 14:33:57 -07002950 }
2951 }
2952
2953 ~HeapChunkContext() {
Ian Rogers30fab402012-01-23 15:43:46 -08002954 if (p_ > &buf_[0]) {
Elliott Hughes6a5bd492011-10-28 14:33:57 -07002955 Flush();
2956 }
2957 }
2958
2959 void EnsureHeader(const void* chunk_ptr) {
Ian Rogers30fab402012-01-23 15:43:46 -08002960 if (!needHeader_) {
Elliott Hughes6a5bd492011-10-28 14:33:57 -07002961 return;
2962 }
2963
2964 // Start a new HPSx chunk.
Ian Rogers30fab402012-01-23 15:43:46 -08002965 JDWP::Write4BE(&p_, 1); // Heap id (bogus; we only have one heap).
2966 JDWP::Write1BE(&p_, 8); // Size of allocation unit, in bytes.
Elliott Hughes6a5bd492011-10-28 14:33:57 -07002967
Ian Rogers30fab402012-01-23 15:43:46 -08002968 JDWP::Write4BE(&p_, reinterpret_cast<uintptr_t>(chunk_ptr)); // virtual address of segment start.
2969 JDWP::Write4BE(&p_, 0); // offset of this piece (relative to the virtual address).
Elliott Hughes6a5bd492011-10-28 14:33:57 -07002970 // [u4]: length of piece, in allocation units
2971 // 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 -08002972 pieceLenField_ = p_;
2973 JDWP::Write4BE(&p_, 0x55555555);
2974 needHeader_ = false;
Elliott Hughes6a5bd492011-10-28 14:33:57 -07002975 }
2976
Ian Rogersb726dcb2012-09-05 08:57:23 -07002977 void Flush() SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Elliott Hughes6a5bd492011-10-28 14:33:57 -07002978 // Patch the "length of piece" field.
Ian Rogers30fab402012-01-23 15:43:46 -08002979 CHECK_LE(&buf_[0], pieceLenField_);
2980 CHECK_LE(pieceLenField_, p_);
2981 JDWP::Set4BE(pieceLenField_, totalAllocationUnits_);
Elliott Hughes6a5bd492011-10-28 14:33:57 -07002982
Ian Rogers30fab402012-01-23 15:43:46 -08002983 Dbg::DdmSendChunk(type_, p_ - &buf_[0], &buf_[0]);
Elliott Hughes6a5bd492011-10-28 14:33:57 -07002984 Reset();
2985 }
2986
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002987 static void HeapChunkCallback(void* start, void* end, size_t used_bytes, void* arg)
Ian Rogersb726dcb2012-09-05 08:57:23 -07002988 SHARED_LOCKS_REQUIRED(Locks::heap_bitmap_lock_,
2989 Locks::mutator_lock_) {
Ian Rogers30fab402012-01-23 15:43:46 -08002990 reinterpret_cast<HeapChunkContext*>(arg)->HeapChunkCallback(start, end, used_bytes);
Elliott Hughesa2155262011-11-16 16:26:58 -08002991 }
2992
Elliott Hughes6a5bd492011-10-28 14:33:57 -07002993 private:
Elliott Hughesa2155262011-11-16 16:26:58 -08002994 enum { ALLOCATION_UNIT_SIZE = 8 };
2995
Elliott Hughes6a5bd492011-10-28 14:33:57 -07002996 void Reset() {
Ian Rogers30fab402012-01-23 15:43:46 -08002997 p_ = &buf_[0];
Ian Rogers15bf2d32012-08-28 17:33:04 -07002998 startOfNextMemoryChunk_ = NULL;
Ian Rogers30fab402012-01-23 15:43:46 -08002999 totalAllocationUnits_ = 0;
3000 needHeader_ = true;
3001 pieceLenField_ = NULL;
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003002 }
3003
Ian Rogers00f7d0e2012-07-19 15:28:27 -07003004 void HeapChunkCallback(void* start, void* /*end*/, size_t used_bytes)
Ian Rogersb726dcb2012-09-05 08:57:23 -07003005 SHARED_LOCKS_REQUIRED(Locks::heap_bitmap_lock_,
3006 Locks::mutator_lock_) {
Ian Rogers30fab402012-01-23 15:43:46 -08003007 // Note: heap call backs cannot manipulate the heap upon which they are crawling, care is taken
3008 // in the following code not to allocate memory, by ensuring buf_ is of the correct size
Ian Rogers15bf2d32012-08-28 17:33:04 -07003009 if (used_bytes == 0) {
3010 if (start == NULL) {
3011 // Reset for start of new heap.
3012 startOfNextMemoryChunk_ = NULL;
3013 Flush();
3014 }
3015 // Only process in use memory so that free region information
3016 // also includes dlmalloc book keeping.
Elliott Hughesa2155262011-11-16 16:26:58 -08003017 return;
Elliott Hughesa2155262011-11-16 16:26:58 -08003018 }
3019
Ian Rogers15bf2d32012-08-28 17:33:04 -07003020 /* If we're looking at the native heap, we'll just return
3021 * (SOLIDITY_HARD, KIND_NATIVE) for all allocated chunks
3022 */
3023 bool native = type_ == CHUNK_TYPE("NHSG");
3024
3025 if (startOfNextMemoryChunk_ != NULL) {
3026 // Transmit any pending free memory. Native free memory of
3027 // over kMaxFreeLen could be because of the use of mmaps, so
3028 // don't report. If not free memory then start a new segment.
3029 bool flush = true;
3030 if (start > startOfNextMemoryChunk_) {
3031 const size_t kMaxFreeLen = 2 * kPageSize;
3032 void* freeStart = startOfNextMemoryChunk_;
3033 void* freeEnd = start;
3034 size_t freeLen = (char*)freeEnd - (char*)freeStart;
3035 if (!native || freeLen < kMaxFreeLen) {
3036 AppendChunk(HPSG_STATE(SOLIDITY_FREE, 0), freeStart, freeLen);
3037 flush = false;
3038 }
3039 }
3040 if (flush) {
3041 startOfNextMemoryChunk_ = NULL;
3042 Flush();
3043 }
3044 }
3045 const Object *obj = (const Object *)start;
Elliott Hughesa2155262011-11-16 16:26:58 -08003046
3047 // Determine the type of this chunk.
3048 // OLD-TODO: if context.merge, see if this chunk is different from the last chunk.
3049 // If it's the same, we should combine them.
Ian Rogers15bf2d32012-08-28 17:33:04 -07003050 uint8_t state = ExamineObject(obj, native);
3051 // dlmalloc's chunk header is 2 * sizeof(size_t), but if the previous chunk is in use for an
3052 // allocation then the first sizeof(size_t) may belong to it.
3053 const size_t dlMallocOverhead = sizeof(size_t);
3054 AppendChunk(state, start, used_bytes + dlMallocOverhead);
3055 startOfNextMemoryChunk_ = (char*)start + used_bytes + dlMallocOverhead;
3056 }
Elliott Hughesa2155262011-11-16 16:26:58 -08003057
Ian Rogers15bf2d32012-08-28 17:33:04 -07003058 void AppendChunk(uint8_t state, void* ptr, size_t length)
Ian Rogersb726dcb2012-09-05 08:57:23 -07003059 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Ian Rogers15bf2d32012-08-28 17:33:04 -07003060 // Make sure there's enough room left in the buffer.
3061 // We need to use two bytes for every fractional 256 allocation units used by the chunk plus
3062 // 17 bytes for any header.
3063 size_t needed = (((length/ALLOCATION_UNIT_SIZE + 255) / 256) * 2) + 17;
3064 size_t bytesLeft = buf_.size() - (size_t)(p_ - &buf_[0]);
3065 if (bytesLeft < needed) {
3066 Flush();
3067 }
3068
3069 bytesLeft = buf_.size() - (size_t)(p_ - &buf_[0]);
3070 if (bytesLeft < needed) {
3071 LOG(WARNING) << "Chunk is too big to transmit (chunk_len=" << length << ", "
3072 << needed << " bytes)";
3073 return;
3074 }
3075 EnsureHeader(ptr);
Elliott Hughesa2155262011-11-16 16:26:58 -08003076 // Write out the chunk description.
Ian Rogers15bf2d32012-08-28 17:33:04 -07003077 length /= ALLOCATION_UNIT_SIZE; // Convert to allocation units.
3078 totalAllocationUnits_ += length;
3079 while (length > 256) {
Ian Rogers30fab402012-01-23 15:43:46 -08003080 *p_++ = state | HPSG_PARTIAL;
3081 *p_++ = 255; // length - 1
Ian Rogers15bf2d32012-08-28 17:33:04 -07003082 length -= 256;
Elliott Hughesa2155262011-11-16 16:26:58 -08003083 }
Ian Rogers30fab402012-01-23 15:43:46 -08003084 *p_++ = state;
Ian Rogers15bf2d32012-08-28 17:33:04 -07003085 *p_++ = length - 1;
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003086 }
3087
Ian Rogers5bfa60f2012-09-02 21:17:56 -07003088 uint8_t ExamineObject(const Object* o, bool is_native_heap)
Ian Rogersb726dcb2012-09-05 08:57:23 -07003089 SHARED_LOCKS_REQUIRED(Locks::heap_bitmap_lock_) {
Elliott Hughesa2155262011-11-16 16:26:58 -08003090 if (o == NULL) {
3091 return HPSG_STATE(SOLIDITY_FREE, 0);
3092 }
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003093
Elliott Hughesa2155262011-11-16 16:26:58 -08003094 // It's an allocated chunk. Figure out what it is.
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003095
Elliott Hughesa2155262011-11-16 16:26:58 -08003096 // If we're looking at the native heap, we'll just return
3097 // (SOLIDITY_HARD, KIND_NATIVE) for all allocated chunks.
Ian Rogers00f7d0e2012-07-19 15:28:27 -07003098 if (is_native_heap) {
Elliott Hughesa2155262011-11-16 16:26:58 -08003099 return HPSG_STATE(SOLIDITY_HARD, KIND_NATIVE);
3100 }
3101
Ian Rogers5bfa60f2012-09-02 21:17:56 -07003102 if (!Runtime::Current()->GetHeap()->IsLiveObjectLocked(o)) {
Ian Rogers15bf2d32012-08-28 17:33:04 -07003103 return HPSG_STATE(SOLIDITY_HARD, KIND_NATIVE);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07003104 }
3105
Elliott Hughesa2155262011-11-16 16:26:58 -08003106 Class* c = o->GetClass();
3107 if (c == NULL) {
3108 // The object was probably just created but hasn't been initialized yet.
3109 return HPSG_STATE(SOLIDITY_HARD, KIND_OBJECT);
3110 }
3111
Elliott Hughesb3bd5f02012-03-08 21:05:27 -08003112 if (!Runtime::Current()->GetHeap()->IsHeapAddress(c)) {
Ian Rogers15bf2d32012-08-28 17:33:04 -07003113 LOG(ERROR) << "Invalid class for managed heap object: " << o << " " << c;
Elliott Hughesa2155262011-11-16 16:26:58 -08003114 return HPSG_STATE(SOLIDITY_HARD, KIND_UNKNOWN);
3115 }
3116
3117 if (c->IsClassClass()) {
3118 return HPSG_STATE(SOLIDITY_HARD, KIND_CLASS_OBJECT);
3119 }
3120
3121 if (c->IsArrayClass()) {
3122 if (o->IsObjectArray()) {
3123 return HPSG_STATE(SOLIDITY_HARD, KIND_ARRAY_4);
3124 }
3125 switch (c->GetComponentSize()) {
3126 case 1: return HPSG_STATE(SOLIDITY_HARD, KIND_ARRAY_1);
3127 case 2: return HPSG_STATE(SOLIDITY_HARD, KIND_ARRAY_2);
3128 case 4: return HPSG_STATE(SOLIDITY_HARD, KIND_ARRAY_4);
3129 case 8: return HPSG_STATE(SOLIDITY_HARD, KIND_ARRAY_8);
3130 }
3131 }
3132
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003133 return HPSG_STATE(SOLIDITY_HARD, KIND_OBJECT);
3134 }
3135
Ian Rogers30fab402012-01-23 15:43:46 -08003136 std::vector<uint8_t> buf_;
3137 uint8_t* p_;
3138 uint8_t* pieceLenField_;
Ian Rogers15bf2d32012-08-28 17:33:04 -07003139 void* startOfNextMemoryChunk_;
Ian Rogers30fab402012-01-23 15:43:46 -08003140 size_t totalAllocationUnits_;
3141 uint32_t type_;
3142 bool merge_;
3143 bool needHeader_;
3144
Elliott Hughesa2155262011-11-16 16:26:58 -08003145 DISALLOW_COPY_AND_ASSIGN(HeapChunkContext);
3146};
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003147
3148void Dbg::DdmSendHeapSegments(bool native) {
3149 Dbg::HpsgWhen when;
3150 Dbg::HpsgWhat what;
3151 if (!native) {
3152 when = gDdmHpsgWhen;
3153 what = gDdmHpsgWhat;
3154 } else {
3155 when = gDdmNhsgWhen;
3156 what = gDdmNhsgWhat;
3157 }
3158 if (when == HPSG_WHEN_NEVER) {
3159 return;
3160 }
3161
3162 // Figure out what kind of chunks we'll be sending.
3163 CHECK(what == HPSG_WHAT_MERGED_OBJECTS || what == HPSG_WHAT_DISTINCT_OBJECTS) << static_cast<int>(what);
3164
3165 // First, send a heap start chunk.
3166 uint8_t heap_id[4];
3167 JDWP::Set4BE(&heap_id[0], 1); // Heap id (bogus; we only have one heap).
3168 Dbg::DdmSendChunk(native ? CHUNK_TYPE("NHST") : CHUNK_TYPE("HPST"), sizeof(heap_id), heap_id);
3169
3170 // Send a series of heap segment chunks.
Elliott Hughesa2155262011-11-16 16:26:58 -08003171 HeapChunkContext context((what == HPSG_WHAT_MERGED_OBJECTS), native);
3172 if (native) {
Ian Rogers30fab402012-01-23 15:43:46 -08003173 // TODO: enable when bionic has moved to dlmalloc 2.8.5
3174 // dlmalloc_inspect_all(HeapChunkContext::HeapChunkCallback, &context);
3175 UNIMPLEMENTED(WARNING) << "Native heap send heap segments";
Elliott Hughesa2155262011-11-16 16:26:58 -08003176 } else {
Elliott Hughesb3bd5f02012-03-08 21:05:27 -08003177 Heap* heap = Runtime::Current()->GetHeap();
Mathieu Chartierfd678be2012-08-30 14:50:54 -07003178 const Spaces& spaces = heap->GetSpaces();
Ian Rogers50b35e22012-10-04 10:09:15 -07003179 Thread* self = Thread::Current();
Mathieu Chartierfd678be2012-08-30 14:50:54 -07003180 for (Spaces::const_iterator cur = spaces.begin(); cur != spaces.end(); ++cur) {
Mathieu Chartierb062fdd2012-07-03 09:51:48 -07003181 if ((*cur)->IsAllocSpace()) {
Ian Rogers50b35e22012-10-04 10:09:15 -07003182 ReaderMutexLock mu(self, *Locks::heap_bitmap_lock_);
Mathieu Chartierb062fdd2012-07-03 09:51:48 -07003183 (*cur)->AsAllocSpace()->Walk(HeapChunkContext::HeapChunkCallback, &context);
3184 }
3185 }
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -07003186 // Walk the large objects, these are not in the AllocSpace.
3187 heap->GetLargeObjectsSpace()->Walk(HeapChunkContext::HeapChunkCallback, &context);
Elliott Hughesa2155262011-11-16 16:26:58 -08003188 }
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003189
3190 // Finally, send a heap end chunk.
3191 Dbg::DdmSendChunk(native ? CHUNK_TYPE("NHEN") : CHUNK_TYPE("HPEN"), sizeof(heap_id), heap_id);
Elliott Hughes767a1472011-10-26 18:49:02 -07003192}
3193
Elliott Hughes545a0642011-11-08 19:10:03 -08003194void Dbg::SetAllocTrackingEnabled(bool enabled) {
Ian Rogers50b35e22012-10-04 10:09:15 -07003195 MutexLock mu(Thread::Current(), gAllocTrackerLock);
Elliott Hughes545a0642011-11-08 19:10:03 -08003196 if (enabled) {
3197 if (recent_allocation_records_ == NULL) {
3198 LOG(INFO) << "Enabling alloc tracker (" << kNumAllocRecords << " entries, "
3199 << kMaxAllocRecordStackDepth << " frames --> "
3200 << (sizeof(AllocRecord) * kNumAllocRecords) << " bytes)";
3201 gAllocRecordHead = gAllocRecordCount = 0;
3202 recent_allocation_records_ = new AllocRecord[kNumAllocRecords];
3203 CHECK(recent_allocation_records_ != NULL);
3204 }
3205 } else {
3206 delete[] recent_allocation_records_;
3207 recent_allocation_records_ = NULL;
3208 }
3209}
3210
Ian Rogers0399dde2012-06-06 17:09:28 -07003211struct AllocRecordStackVisitor : public StackVisitor {
3212 AllocRecordStackVisitor(const ManagedStack* stack,
Ian Rogers306057f2012-11-26 12:45:53 -08003213 const std::deque<InstrumentationStackFrame>* instrumentation_stack,
3214 AllocRecord* record)
Ian Rogersb726dcb2012-09-05 08:57:23 -07003215 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_)
jeffhao725a9572012-11-13 18:20:12 -08003216 : StackVisitor(stack, instrumentation_stack, NULL), record(record), depth(0) {}
Elliott Hughes545a0642011-11-08 19:10:03 -08003217
Ian Rogers00f7d0e2012-07-19 15:28:27 -07003218 // TODO: Enable annotalysis. We know lock is held in constructor, but abstraction confuses
3219 // annotalysis.
3220 bool VisitFrame() NO_THREAD_SAFETY_ANALYSIS {
Elliott Hughes545a0642011-11-08 19:10:03 -08003221 if (depth >= kMaxAllocRecordStackDepth) {
Elliott Hughes530fa002012-03-12 11:44:49 -07003222 return false;
Elliott Hughes545a0642011-11-08 19:10:03 -08003223 }
Mathieu Chartier66f19252012-09-18 08:57:04 -07003224 AbstractMethod* m = GetMethod();
Ian Rogers0399dde2012-06-06 17:09:28 -07003225 if (!m->IsRuntimeMethod()) {
3226 record->stack[depth].method = m;
3227 record->stack[depth].dex_pc = GetDexPc();
Elliott Hughes530fa002012-03-12 11:44:49 -07003228 ++depth;
Elliott Hughes545a0642011-11-08 19:10:03 -08003229 }
Elliott Hughes530fa002012-03-12 11:44:49 -07003230 return true;
Elliott Hughes545a0642011-11-08 19:10:03 -08003231 }
3232
3233 ~AllocRecordStackVisitor() {
3234 // Clear out any unused stack trace elements.
3235 for (; depth < kMaxAllocRecordStackDepth; ++depth) {
3236 record->stack[depth].method = NULL;
Ian Rogers0399dde2012-06-06 17:09:28 -07003237 record->stack[depth].dex_pc = 0;
Elliott Hughes545a0642011-11-08 19:10:03 -08003238 }
3239 }
3240
3241 AllocRecord* record;
3242 size_t depth;
3243};
3244
3245void Dbg::RecordAllocation(Class* type, size_t byte_count) {
3246 Thread* self = Thread::Current();
3247 CHECK(self != NULL);
3248
Ian Rogers50b35e22012-10-04 10:09:15 -07003249 MutexLock mu(self, gAllocTrackerLock);
Elliott Hughes545a0642011-11-08 19:10:03 -08003250 if (recent_allocation_records_ == NULL) {
3251 return;
3252 }
3253
3254 // Advance and clip.
3255 if (++gAllocRecordHead == kNumAllocRecords) {
3256 gAllocRecordHead = 0;
3257 }
3258
3259 // Fill in the basics.
3260 AllocRecord* record = &recent_allocation_records_[gAllocRecordHead];
3261 record->type = type;
3262 record->byte_count = byte_count;
3263 record->thin_lock_id = self->GetThinLockId();
3264
3265 // Fill in the stack trace.
jeffhao725a9572012-11-13 18:20:12 -08003266 AllocRecordStackVisitor visitor(self->GetManagedStack(), self->GetInstrumentationStack(), record);
Ian Rogers0399dde2012-06-06 17:09:28 -07003267 visitor.WalkStack();
Elliott Hughes545a0642011-11-08 19:10:03 -08003268
3269 if (gAllocRecordCount < kNumAllocRecords) {
3270 ++gAllocRecordCount;
3271 }
3272}
3273
Elliott Hughesa8f93cb2012-06-08 17:08:48 -07003274// Returns the index of the head element.
3275//
3276// We point at the most-recently-written record, so if gAllocRecordCount is 1
3277// we want to use the current element. Take "head+1" and subtract count
3278// from it.
3279//
3280// We need to handle underflow in our circular buffer, so we add
3281// kNumAllocRecords and then mask it back down.
Elliott Hughesf8349362012-06-18 15:00:06 -07003282static inline int HeadIndex() EXCLUSIVE_LOCKS_REQUIRED(gAllocTrackerLock) {
Elliott Hughes545a0642011-11-08 19:10:03 -08003283 return (gAllocRecordHead+1 + kNumAllocRecords - gAllocRecordCount) & (kNumAllocRecords-1);
3284}
3285
3286void Dbg::DumpRecentAllocations() {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07003287 ScopedObjectAccess soa(Thread::Current());
Ian Rogers50b35e22012-10-04 10:09:15 -07003288 MutexLock mu(soa.Self(), gAllocTrackerLock);
Elliott Hughes545a0642011-11-08 19:10:03 -08003289 if (recent_allocation_records_ == NULL) {
3290 LOG(INFO) << "Not recording tracked allocations";
3291 return;
3292 }
3293
3294 // "i" is the head of the list. We want to start at the end of the
3295 // list and move forward to the tail.
Elliott Hughesa8f93cb2012-06-08 17:08:48 -07003296 size_t i = HeadIndex();
Elliott Hughes545a0642011-11-08 19:10:03 -08003297 size_t count = gAllocRecordCount;
3298
3299 LOG(INFO) << "Tracked allocations, (head=" << gAllocRecordHead << " count=" << count << ")";
3300 while (count--) {
3301 AllocRecord* record = &recent_allocation_records_[i];
3302
Elliott Hughesa8f93cb2012-06-08 17:08:48 -07003303 LOG(INFO) << StringPrintf(" Thread %-2d %6zd bytes ", record->thin_lock_id, record->byte_count)
Elliott Hughes545a0642011-11-08 19:10:03 -08003304 << PrettyClass(record->type);
3305
3306 for (size_t stack_frame = 0; stack_frame < kMaxAllocRecordStackDepth; ++stack_frame) {
Mathieu Chartier66f19252012-09-18 08:57:04 -07003307 const AbstractMethod* m = record->stack[stack_frame].method;
Elliott Hughes545a0642011-11-08 19:10:03 -08003308 if (m == NULL) {
3309 break;
3310 }
3311 LOG(INFO) << " " << PrettyMethod(m) << " line " << record->stack[stack_frame].LineNumber();
3312 }
3313
3314 // pause periodically to help logcat catch up
3315 if ((count % 5) == 0) {
3316 usleep(40000);
3317 }
3318
3319 i = (i + 1) & (kNumAllocRecords-1);
3320 }
3321}
3322
3323class StringTable {
3324 public:
3325 StringTable() {
3326 }
3327
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08003328 void Add(const char* s) {
Elliott Hughes545a0642011-11-08 19:10:03 -08003329 table_.insert(s);
3330 }
3331
Elliott Hughesa8f93cb2012-06-08 17:08:48 -07003332 size_t IndexOf(const char* s) const {
3333 typedef std::set<std::string>::const_iterator It; // TODO: C++0x auto
3334 It it = table_.find(s);
3335 if (it == table_.end()) {
3336 LOG(FATAL) << "IndexOf(\"" << s << "\") failed";
3337 }
3338 return std::distance(table_.begin(), it);
Elliott Hughes545a0642011-11-08 19:10:03 -08003339 }
3340
Elliott Hughesa8f93cb2012-06-08 17:08:48 -07003341 size_t Size() const {
Elliott Hughes545a0642011-11-08 19:10:03 -08003342 return table_.size();
3343 }
3344
Elliott Hughesa8f93cb2012-06-08 17:08:48 -07003345 void WriteTo(std::vector<uint8_t>& bytes) const {
3346 typedef std::set<std::string>::const_iterator It; // TODO: C++0x auto
Elliott Hughes545a0642011-11-08 19:10:03 -08003347 for (It it = table_.begin(); it != table_.end(); ++it) {
Elliott Hughesa8f93cb2012-06-08 17:08:48 -07003348 const char* s = (*it).c_str();
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08003349 size_t s_len = CountModifiedUtf8Chars(s);
3350 UniquePtr<uint16_t> s_utf16(new uint16_t[s_len]);
3351 ConvertModifiedUtf8ToUtf16(s_utf16.get(), s);
3352 JDWP::AppendUtf16BE(bytes, s_utf16.get(), s_len);
Elliott Hughes545a0642011-11-08 19:10:03 -08003353 }
3354 }
3355
3356 private:
Elliott Hughesa8f93cb2012-06-08 17:08:48 -07003357 std::set<std::string> table_;
Elliott Hughes545a0642011-11-08 19:10:03 -08003358 DISALLOW_COPY_AND_ASSIGN(StringTable);
3359};
3360
3361/*
3362 * The data we send to DDMS contains everything we have recorded.
3363 *
3364 * Message header (all values big-endian):
3365 * (1b) message header len (to allow future expansion); includes itself
3366 * (1b) entry header len
3367 * (1b) stack frame len
3368 * (2b) number of entries
3369 * (4b) offset to string table from start of message
3370 * (2b) number of class name strings
3371 * (2b) number of method name strings
3372 * (2b) number of source file name strings
3373 * For each entry:
3374 * (4b) total allocation size
3375 * (2b) threadId
3376 * (2b) allocated object's class name index
3377 * (1b) stack depth
3378 * For each stack frame:
3379 * (2b) method's class name
3380 * (2b) method name
3381 * (2b) method source file
3382 * (2b) line number, clipped to 32767; -2 if native; -1 if no source
3383 * (xb) class name strings
3384 * (xb) method name strings
3385 * (xb) source file strings
3386 *
3387 * As with other DDM traffic, strings are sent as a 4-byte length
3388 * followed by UTF-16 data.
3389 *
3390 * We send up 16-bit unsigned indexes into string tables. In theory there
3391 * can be (kMaxAllocRecordStackDepth * kNumAllocRecords) unique strings in
3392 * each table, but in practice there should be far fewer.
3393 *
3394 * The chief reason for using a string table here is to keep the size of
3395 * the DDMS message to a minimum. This is partly to make the protocol
3396 * efficient, but also because we have to form the whole thing up all at
3397 * once in a memory buffer.
3398 *
3399 * We use separate string tables for class names, method names, and source
3400 * files to keep the indexes small. There will generally be no overlap
3401 * between the contents of these tables.
3402 */
3403jbyteArray Dbg::GetRecentAllocations() {
3404 if (false) {
3405 DumpRecentAllocations();
3406 }
3407
Ian Rogers50b35e22012-10-04 10:09:15 -07003408 Thread* self = Thread::Current();
3409 MutexLock mu(self, gAllocTrackerLock);
Elliott Hughes545a0642011-11-08 19:10:03 -08003410
Elliott Hughesa8f93cb2012-06-08 17:08:48 -07003411 //
3412 // Part 1: generate string tables.
3413 //
Elliott Hughes545a0642011-11-08 19:10:03 -08003414 StringTable class_names;
3415 StringTable method_names;
3416 StringTable filenames;
3417
3418 int count = gAllocRecordCount;
Elliott Hughesa8f93cb2012-06-08 17:08:48 -07003419 int idx = HeadIndex();
Elliott Hughes545a0642011-11-08 19:10:03 -08003420 while (count--) {
3421 AllocRecord* record = &recent_allocation_records_[idx];
3422
Elliott Hughes91250e02011-12-13 22:30:35 -08003423 class_names.Add(ClassHelper(record->type).GetDescriptor());
Elliott Hughes545a0642011-11-08 19:10:03 -08003424
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08003425 MethodHelper mh;
Elliott Hughes545a0642011-11-08 19:10:03 -08003426 for (size_t i = 0; i < kMaxAllocRecordStackDepth; i++) {
Mathieu Chartier66f19252012-09-18 08:57:04 -07003427 AbstractMethod* m = record->stack[i].method;
Elliott Hughes545a0642011-11-08 19:10:03 -08003428 if (m != NULL) {
Ian Rogersba377812012-05-28 21:16:29 -07003429 mh.ChangeMethod(m);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08003430 class_names.Add(mh.GetDeclaringClassDescriptor());
3431 method_names.Add(mh.GetName());
3432 filenames.Add(mh.GetDeclaringClassSourceFile());
Elliott Hughes545a0642011-11-08 19:10:03 -08003433 }
3434 }
3435
3436 idx = (idx + 1) & (kNumAllocRecords-1);
3437 }
3438
3439 LOG(INFO) << "allocation records: " << gAllocRecordCount;
3440
Elliott Hughesa8f93cb2012-06-08 17:08:48 -07003441 //
3442 // Part 2: allocate a buffer and generate the output.
3443 //
Elliott Hughes545a0642011-11-08 19:10:03 -08003444 std::vector<uint8_t> bytes;
3445
3446 // (1b) message header len (to allow future expansion); includes itself
3447 // (1b) entry header len
3448 // (1b) stack frame len
3449 const int kMessageHeaderLen = 15;
3450 const int kEntryHeaderLen = 9;
3451 const int kStackFrameLen = 8;
3452 JDWP::Append1BE(bytes, kMessageHeaderLen);
3453 JDWP::Append1BE(bytes, kEntryHeaderLen);
3454 JDWP::Append1BE(bytes, kStackFrameLen);
3455
3456 // (2b) number of entries
3457 // (4b) offset to string table from start of message
3458 // (2b) number of class name strings
3459 // (2b) number of method name strings
3460 // (2b) number of source file name strings
3461 JDWP::Append2BE(bytes, gAllocRecordCount);
3462 size_t string_table_offset = bytes.size();
3463 JDWP::Append4BE(bytes, 0); // We'll patch this later...
3464 JDWP::Append2BE(bytes, class_names.Size());
3465 JDWP::Append2BE(bytes, method_names.Size());
3466 JDWP::Append2BE(bytes, filenames.Size());
3467
3468 count = gAllocRecordCount;
Elliott Hughesa8f93cb2012-06-08 17:08:48 -07003469 idx = HeadIndex();
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08003470 ClassHelper kh;
Elliott Hughes545a0642011-11-08 19:10:03 -08003471 while (count--) {
3472 // For each entry:
3473 // (4b) total allocation size
3474 // (2b) thread id
3475 // (2b) allocated object's class name index
3476 // (1b) stack depth
3477 AllocRecord* record = &recent_allocation_records_[idx];
3478 size_t stack_depth = record->GetDepth();
Elliott Hughesa8f93cb2012-06-08 17:08:48 -07003479 kh.ChangeClass(record->type);
3480 size_t allocated_object_class_name_index = class_names.IndexOf(kh.GetDescriptor());
Elliott Hughes545a0642011-11-08 19:10:03 -08003481 JDWP::Append4BE(bytes, record->byte_count);
3482 JDWP::Append2BE(bytes, record->thin_lock_id);
Elliott Hughesa8f93cb2012-06-08 17:08:48 -07003483 JDWP::Append2BE(bytes, allocated_object_class_name_index);
Elliott Hughes545a0642011-11-08 19:10:03 -08003484 JDWP::Append1BE(bytes, stack_depth);
3485
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08003486 MethodHelper mh;
Elliott Hughes545a0642011-11-08 19:10:03 -08003487 for (size_t stack_frame = 0; stack_frame < stack_depth; ++stack_frame) {
3488 // For each stack frame:
3489 // (2b) method's class name
3490 // (2b) method name
3491 // (2b) method source file
3492 // (2b) line number, clipped to 32767; -2 if native; -1 if no source
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08003493 mh.ChangeMethod(record->stack[stack_frame].method);
Elliott Hughesa8f93cb2012-06-08 17:08:48 -07003494 size_t class_name_index = class_names.IndexOf(mh.GetDeclaringClassDescriptor());
3495 size_t method_name_index = method_names.IndexOf(mh.GetName());
3496 size_t file_name_index = filenames.IndexOf(mh.GetDeclaringClassSourceFile());
3497 JDWP::Append2BE(bytes, class_name_index);
3498 JDWP::Append2BE(bytes, method_name_index);
3499 JDWP::Append2BE(bytes, file_name_index);
Elliott Hughes545a0642011-11-08 19:10:03 -08003500 JDWP::Append2BE(bytes, record->stack[stack_frame].LineNumber());
3501 }
3502
3503 idx = (idx + 1) & (kNumAllocRecords-1);
3504 }
3505
3506 // (xb) class name strings
3507 // (xb) method name strings
3508 // (xb) source file strings
3509 JDWP::Set4BE(&bytes[string_table_offset], bytes.size());
3510 class_names.WriteTo(bytes);
3511 method_names.WriteTo(bytes);
3512 filenames.WriteTo(bytes);
3513
Ian Rogers50b35e22012-10-04 10:09:15 -07003514 JNIEnv* env = self->GetJniEnv();
Elliott Hughes545a0642011-11-08 19:10:03 -08003515 jbyteArray result = env->NewByteArray(bytes.size());
3516 if (result != NULL) {
3517 env->SetByteArrayRegion(result, 0, bytes.size(), reinterpret_cast<const jbyte*>(&bytes[0]));
3518 }
3519 return result;
3520}
3521
Elliott Hughes872d4ec2011-10-21 17:07:15 -07003522} // namespace art