blob: 672b660138db85b45d1232ec2fc0f1d73797cc32 [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.
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700180static Mutex gBreakpointsLock DEFAULT_MUTEX_ACQUIRED_AFTER ("breakpoints lock");
Elliott Hughesf8349362012-06-18 15:00:06 -0700181static std::vector<Breakpoint> gBreakpoints GUARDED_BY(gBreakpointsLock);
182static SingleStepControl gSingleStepControl GUARDED_BY(gBreakpointsLock);
Elliott Hughes86964332012-02-15 19:37:42 -0800183
Mathieu Chartier66f19252012-09-18 08:57:04 -0700184static bool IsBreakpoint(AbstractMethod* m, uint32_t dex_pc)
Ian Rogersb726dcb2012-09-05 08:57:23 -0700185 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Ian Rogers50b35e22012-10-04 10:09:15 -0700186 MutexLock mu(Thread::Current(), gBreakpointsLock);
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)
Ian Rogersb726dcb2012-09-05 08:57:23 -0700227 LOCKS_EXCLUDED(Locks::thread_suspend_count_lock_)
228 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Elliott Hughes436e3722012-02-17 20:01:47 -0800229 Object* thread_peer = gRegistry->Get<Object*>(threadId);
230 if (thread_peer == NULL || thread_peer == kInvalidObject) {
231 return NULL;
232 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700233 Thread* thread = Thread::FromManagedThread(soa, thread_peer);
234 return thread;
Elliott Hughes436e3722012-02-17 20:01:47 -0800235}
236
Elliott Hughes24437992011-11-30 14:49:33 -0800237static JDWP::JdwpTag BasicTagFromDescriptor(const char* descriptor) {
238 // JDWP deliberately uses the descriptor characters' ASCII values for its enum.
239 // Note that by "basic" we mean that we don't get more specific than JT_OBJECT.
240 return static_cast<JDWP::JdwpTag>(descriptor[0]);
241}
242
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700243static JDWP::JdwpTag TagFromClass(Class* c)
Ian Rogersb726dcb2012-09-05 08:57:23 -0700244 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Elliott Hughes86b00102011-12-05 17:54:26 -0800245 CHECK(c != NULL);
Elliott Hughes24437992011-11-30 14:49:33 -0800246 if (c->IsArrayClass()) {
247 return JDWP::JT_ARRAY;
248 }
249
Elliott Hughes3d30d9b2011-12-07 17:35:48 -0800250 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
Elliott Hughes24437992011-11-30 14:49:33 -0800251 if (c->IsStringClass()) {
252 return JDWP::JT_STRING;
253 } else if (c->IsClassClass()) {
254 return JDWP::JT_CLASS_OBJECT;
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -0800255 } else if (class_linker->FindSystemClass("Ljava/lang/Thread;")->IsAssignableFrom(c)) {
Elliott Hughes24437992011-11-30 14:49:33 -0800256 return JDWP::JT_THREAD;
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -0800257 } else if (class_linker->FindSystemClass("Ljava/lang/ThreadGroup;")->IsAssignableFrom(c)) {
Elliott Hughes24437992011-11-30 14:49:33 -0800258 return JDWP::JT_THREAD_GROUP;
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -0800259 } else if (class_linker->FindSystemClass("Ljava/lang/ClassLoader;")->IsAssignableFrom(c)) {
Elliott Hughes24437992011-11-30 14:49:33 -0800260 return JDWP::JT_CLASS_LOADER;
Elliott Hughes24437992011-11-30 14:49:33 -0800261 } else {
262 return JDWP::JT_OBJECT;
263 }
264}
265
266/*
267 * Objects declared to hold Object might actually hold a more specific
268 * type. The debugger may take a special interest in these (e.g. it
269 * wants to display the contents of Strings), so we want to return an
270 * appropriate tag.
271 *
272 * Null objects are tagged JT_OBJECT.
273 */
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700274static JDWP::JdwpTag TagFromObject(const Object* o)
Ian Rogersb726dcb2012-09-05 08:57:23 -0700275 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Elliott Hughes24437992011-11-30 14:49:33 -0800276 return (o == NULL) ? JDWP::JT_OBJECT : TagFromClass(o->GetClass());
277}
278
279static bool IsPrimitiveTag(JDWP::JdwpTag tag) {
280 switch (tag) {
281 case JDWP::JT_BOOLEAN:
282 case JDWP::JT_BYTE:
283 case JDWP::JT_CHAR:
284 case JDWP::JT_FLOAT:
285 case JDWP::JT_DOUBLE:
286 case JDWP::JT_INT:
287 case JDWP::JT_LONG:
288 case JDWP::JT_SHORT:
289 case JDWP::JT_VOID:
290 return true;
291 default:
292 return false;
293 }
294}
295
Elliott Hughes3bb81562011-10-21 18:52:59 -0700296/*
297 * Handle one of the JDWP name/value pairs.
298 *
299 * JDWP options are:
300 * help: if specified, show help message and bail
301 * transport: may be dt_socket or dt_shmem
302 * address: for dt_socket, "host:port", or just "port" when listening
303 * server: if "y", wait for debugger to attach; if "n", attach to debugger
304 * timeout: how long to wait for debugger to connect / listen
305 *
306 * Useful with server=n (these aren't supported yet):
307 * onthrow=<exception-name>: connect to debugger when exception thrown
308 * onuncaught=y|n: connect to debugger when uncaught exception thrown
309 * launch=<command-line>: launch the debugger itself
310 *
311 * The "transport" option is required, as is "address" if server=n.
312 */
313static bool ParseJdwpOption(const std::string& name, const std::string& value) {
314 if (name == "transport") {
315 if (value == "dt_socket") {
Elliott Hughes376a7a02011-10-24 18:35:55 -0700316 gJdwpOptions.transport = JDWP::kJdwpTransportSocket;
Elliott Hughes3bb81562011-10-21 18:52:59 -0700317 } else if (value == "dt_android_adb") {
Elliott Hughes376a7a02011-10-24 18:35:55 -0700318 gJdwpOptions.transport = JDWP::kJdwpTransportAndroidAdb;
Elliott Hughes3bb81562011-10-21 18:52:59 -0700319 } else {
320 LOG(ERROR) << "JDWP transport not supported: " << value;
321 return false;
322 }
323 } else if (name == "server") {
324 if (value == "n") {
Elliott Hughes376a7a02011-10-24 18:35:55 -0700325 gJdwpOptions.server = false;
Elliott Hughes3bb81562011-10-21 18:52:59 -0700326 } else if (value == "y") {
Elliott Hughes376a7a02011-10-24 18:35:55 -0700327 gJdwpOptions.server = true;
Elliott Hughes3bb81562011-10-21 18:52:59 -0700328 } else {
329 LOG(ERROR) << "JDWP option 'server' must be 'y' or 'n'";
330 return false;
331 }
332 } else if (name == "suspend") {
333 if (value == "n") {
Elliott Hughes376a7a02011-10-24 18:35:55 -0700334 gJdwpOptions.suspend = false;
Elliott Hughes3bb81562011-10-21 18:52:59 -0700335 } else if (value == "y") {
Elliott Hughes376a7a02011-10-24 18:35:55 -0700336 gJdwpOptions.suspend = true;
Elliott Hughes3bb81562011-10-21 18:52:59 -0700337 } else {
338 LOG(ERROR) << "JDWP option 'suspend' must be 'y' or 'n'";
339 return false;
340 }
341 } else if (name == "address") {
342 /* this is either <port> or <host>:<port> */
343 std::string port_string;
Elliott Hughes376a7a02011-10-24 18:35:55 -0700344 gJdwpOptions.host.clear();
Elliott Hughes3bb81562011-10-21 18:52:59 -0700345 std::string::size_type colon = value.find(':');
346 if (colon != std::string::npos) {
Elliott Hughes376a7a02011-10-24 18:35:55 -0700347 gJdwpOptions.host = value.substr(0, colon);
Elliott Hughes3bb81562011-10-21 18:52:59 -0700348 port_string = value.substr(colon + 1);
349 } else {
350 port_string = value;
351 }
352 if (port_string.empty()) {
353 LOG(ERROR) << "JDWP address missing port: " << value;
354 return false;
355 }
356 char* end;
Elliott Hughesba8eee12012-01-24 20:25:24 -0800357 uint64_t port = strtoul(port_string.c_str(), &end, 10);
358 if (*end != '\0' || port > 0xffff) {
Elliott Hughes3bb81562011-10-21 18:52:59 -0700359 LOG(ERROR) << "JDWP address has junk in port field: " << value;
360 return false;
361 }
Elliott Hughes376a7a02011-10-24 18:35:55 -0700362 gJdwpOptions.port = port;
Elliott Hughes3bb81562011-10-21 18:52:59 -0700363 } else if (name == "launch" || name == "onthrow" || name == "oncaught" || name == "timeout") {
364 /* valid but unsupported */
365 LOG(INFO) << "Ignoring JDWP option '" << name << "'='" << value << "'";
366 } else {
367 LOG(INFO) << "Ignoring unrecognized JDWP option '" << name << "'='" << value << "'";
368 }
369
370 return true;
371}
372
373/*
374 * Parse the latter half of a -Xrunjdwp/-agentlib:jdwp= string, e.g.:
375 * "transport=dt_socket,address=8000,server=y,suspend=n"
376 */
377bool Dbg::ParseJdwpOptions(const std::string& options) {
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -0800378 VLOG(jdwp) << "ParseJdwpOptions: " << options;
Elliott Hughes47fce012011-10-25 18:37:19 -0700379
Elliott Hughes3bb81562011-10-21 18:52:59 -0700380 std::vector<std::string> pairs;
381 Split(options, ',', pairs);
382
383 for (size_t i = 0; i < pairs.size(); ++i) {
384 std::string::size_type equals = pairs[i].find('=');
385 if (equals == std::string::npos) {
386 LOG(ERROR) << "Can't parse JDWP option '" << pairs[i] << "' in '" << options << "'";
387 return false;
388 }
389 ParseJdwpOption(pairs[i].substr(0, equals), pairs[i].substr(equals + 1));
390 }
391
Elliott Hughes376a7a02011-10-24 18:35:55 -0700392 if (gJdwpOptions.transport == JDWP::kJdwpTransportUnknown) {
Elliott Hughes3bb81562011-10-21 18:52:59 -0700393 LOG(ERROR) << "Must specify JDWP transport: " << options;
394 }
Elliott Hughes376a7a02011-10-24 18:35:55 -0700395 if (!gJdwpOptions.server && (gJdwpOptions.host.empty() || gJdwpOptions.port == 0)) {
Elliott Hughes3bb81562011-10-21 18:52:59 -0700396 LOG(ERROR) << "Must specify JDWP host and port when server=n: " << options;
397 return false;
398 }
399
400 gJdwpConfigured = true;
401 return true;
402}
403
Elliott Hughesd1cc8362011-10-24 16:58:50 -0700404void Dbg::StartJdwp() {
Elliott Hughesc0f09332012-03-26 13:27:06 -0700405 if (!gJdwpAllowed || !IsJdwpConfigured()) {
Elliott Hughes376a7a02011-10-24 18:35:55 -0700406 // No JDWP for you!
407 return;
408 }
409
Elliott Hughes475fc232011-10-25 15:00:35 -0700410 CHECK(gRegistry == NULL);
411 gRegistry = new ObjectRegistry;
412
Elliott Hughesd1cc8362011-10-24 16:58:50 -0700413 // Init JDWP if the debugger is enabled. This may connect out to a
414 // debugger, passively listen for a debugger, or block waiting for a
415 // debugger.
Elliott Hughes376a7a02011-10-24 18:35:55 -0700416 gJdwpState = JDWP::JdwpState::Create(&gJdwpOptions);
417 if (gJdwpState == NULL) {
Elliott Hughesf8a2df72011-12-01 12:19:54 -0800418 // We probably failed because some other process has the port already, which means that
419 // if we don't abort the user is likely to think they're talking to us when they're actually
420 // talking to that other process.
Elliott Hughes3d30d9b2011-12-07 17:35:48 -0800421 LOG(FATAL) << "Debugger thread failed to initialize";
Elliott Hughesd1cc8362011-10-24 16:58:50 -0700422 }
423
424 // If a debugger has already attached, send the "welcome" message.
425 // This may cause us to suspend all threads.
Elliott Hughes376a7a02011-10-24 18:35:55 -0700426 if (gJdwpState->IsActive()) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700427 ScopedObjectAccess soa(Thread::Current());
Elliott Hughes376a7a02011-10-24 18:35:55 -0700428 if (!gJdwpState->PostVMStart()) {
Elliott Hughes3d30d9b2011-12-07 17:35:48 -0800429 LOG(WARNING) << "Failed to post 'start' message to debugger";
Elliott Hughesd1cc8362011-10-24 16:58:50 -0700430 }
431 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700432}
433
Elliott Hughesd1cc8362011-10-24 16:58:50 -0700434void Dbg::StopJdwp() {
Elliott Hughes376a7a02011-10-24 18:35:55 -0700435 delete gJdwpState;
Elliott Hughes475fc232011-10-25 15:00:35 -0700436 delete gRegistry;
437 gRegistry = NULL;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700438}
439
Elliott Hughes767a1472011-10-26 18:49:02 -0700440void Dbg::GcDidFinish() {
441 if (gDdmHpifWhen != HPIF_WHEN_NEVER) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700442 ScopedObjectAccess soa(Thread::Current());
Elliott Hughes81ff3182012-03-23 20:35:56 -0700443 LOG(DEBUG) << "Sending heap info to DDM";
Elliott Hughes7162ad92011-10-27 14:08:42 -0700444 DdmSendHeapInfo(gDdmHpifWhen);
Elliott Hughes767a1472011-10-26 18:49:02 -0700445 }
446 if (gDdmHpsgWhen != HPSG_WHEN_NEVER) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700447 ScopedObjectAccess soa(Thread::Current());
Elliott Hughes81ff3182012-03-23 20:35:56 -0700448 LOG(DEBUG) << "Dumping heap to DDM";
Elliott Hughes6a5bd492011-10-28 14:33:57 -0700449 DdmSendHeapSegments(false);
Elliott Hughes767a1472011-10-26 18:49:02 -0700450 }
451 if (gDdmNhsgWhen != HPSG_WHEN_NEVER) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700452 ScopedObjectAccess soa(Thread::Current());
Elliott Hughes767a1472011-10-26 18:49:02 -0700453 LOG(DEBUG) << "Dumping native heap to DDM";
Elliott Hughes6a5bd492011-10-28 14:33:57 -0700454 DdmSendHeapSegments(true);
Elliott Hughes767a1472011-10-26 18:49:02 -0700455 }
456}
457
Elliott Hughes4ffd3132011-10-24 12:06:42 -0700458void Dbg::SetJdwpAllowed(bool allowed) {
459 gJdwpAllowed = allowed;
460}
461
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700462DebugInvokeReq* Dbg::GetInvokeReq() {
Elliott Hughes475fc232011-10-25 15:00:35 -0700463 return Thread::Current()->GetInvokeReq();
464}
465
466Thread* Dbg::GetDebugThread() {
467 return (gJdwpState != NULL) ? gJdwpState->GetDebugThread() : NULL;
468}
469
470void Dbg::ClearWaitForEventThread() {
471 gJdwpState->ClearWaitForEventThread();
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700472}
473
474void Dbg::Connected() {
Elliott Hughes3bb81562011-10-21 18:52:59 -0700475 CHECK(!gDebuggerConnected);
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -0800476 VLOG(jdwp) << "JDWP has attached";
Elliott Hughes3bb81562011-10-21 18:52:59 -0700477 gDebuggerConnected = true;
Elliott Hughes86964332012-02-15 19:37:42 -0800478 gDisposed = false;
479}
480
481void Dbg::Disposed() {
482 gDisposed = true;
483}
484
485bool Dbg::IsDisposed() {
486 return gDisposed;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700487}
488
Elliott Hughesc0f09332012-03-26 13:27:06 -0700489static void SetDebuggerUpdatesEnabledCallback(Thread* t, void* user_data) {
490 t->SetDebuggerUpdatesEnabled(*reinterpret_cast<bool*>(user_data));
491}
492
493static void SetDebuggerUpdatesEnabled(bool enabled) {
Ian Rogers50b35e22012-10-04 10:09:15 -0700494 MutexLock mu(Thread::Current(), *Locks::thread_list_lock_);
Elliott Hughesf8349362012-06-18 15:00:06 -0700495 Runtime::Current()->GetThreadList()->ForEach(SetDebuggerUpdatesEnabledCallback, &enabled);
Elliott Hughesc0f09332012-03-26 13:27:06 -0700496}
497
Elliott Hughesa2155262011-11-16 16:26:58 -0800498void Dbg::GoActive() {
499 // Enable all debugging features, including scans for breakpoints.
500 // This is a no-op if we're already active.
501 // Only called from the JDWP handler thread.
502 if (gDebuggerActive) {
503 return;
504 }
505
506 LOG(INFO) << "Debugger is active";
507
Elliott Hughesc0f09332012-03-26 13:27:06 -0700508 {
509 // TODO: dalvik only warned if there were breakpoints left over. clear in Dbg::Disconnected?
Ian Rogers50b35e22012-10-04 10:09:15 -0700510 MutexLock mu(Thread::Current(), gBreakpointsLock);
Elliott Hughesc0f09332012-03-26 13:27:06 -0700511 CHECK_EQ(gBreakpoints.size(), 0U);
512 }
Elliott Hughesa2155262011-11-16 16:26:58 -0800513
514 gDebuggerActive = true;
Elliott Hughesc0f09332012-03-26 13:27:06 -0700515 SetDebuggerUpdatesEnabled(true);
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700516}
517
518void Dbg::Disconnected() {
Elliott Hughes234ab152011-10-26 14:02:26 -0700519 CHECK(gDebuggerConnected);
520
Elliott Hughesc0f09332012-03-26 13:27:06 -0700521 LOG(INFO) << "Debugger is no longer active";
Elliott Hughes234ab152011-10-26 14:02:26 -0700522
Elliott Hughesc0f09332012-03-26 13:27:06 -0700523 gDebuggerActive = false;
524 SetDebuggerUpdatesEnabled(false);
Elliott Hughes234ab152011-10-26 14:02:26 -0700525
526 gRegistry->Clear();
527 gDebuggerConnected = false;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700528}
529
Elliott Hughesc0f09332012-03-26 13:27:06 -0700530bool Dbg::IsDebuggerActive() {
Elliott Hughes3bb81562011-10-21 18:52:59 -0700531 return gDebuggerActive;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700532}
533
Elliott Hughesc0f09332012-03-26 13:27:06 -0700534bool Dbg::IsJdwpConfigured() {
Elliott Hughes3bb81562011-10-21 18:52:59 -0700535 return gJdwpConfigured;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700536}
537
538int64_t Dbg::LastDebuggerActivity() {
Elliott Hughesca951522011-12-05 12:01:32 -0800539 return gJdwpState->LastDebuggerActivity();
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700540}
541
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700542void Dbg::UndoDebuggerSuspensions() {
Elliott Hughes234ab152011-10-26 14:02:26 -0700543 Runtime::Current()->GetThreadList()->UndoDebuggerSuspensions();
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700544}
545
546void Dbg::Exit(int status) {
Elliott Hughes1bba14f2011-12-01 18:00:36 -0800547 exit(status); // This is all dalvik did.
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700548}
549
Elliott Hughesbfe487b2011-10-26 15:48:55 -0700550void Dbg::VisitRoots(Heap::RootVisitor* visitor, void* arg) {
551 if (gRegistry != NULL) {
552 gRegistry->VisitRoots(visitor, arg);
553 }
554}
555
Elliott Hughesc308a5d2012-02-16 17:12:06 -0800556std::string Dbg::GetClassName(JDWP::RefTypeId classId) {
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -0800557 Object* o = gRegistry->Get<Object*>(classId);
Elliott Hughes436e3722012-02-17 20:01:47 -0800558 if (o == NULL) {
559 return "NULL";
560 }
561 if (o == kInvalidObject) {
562 return StringPrintf("invalid object %p", reinterpret_cast<void*>(classId));
563 }
564 if (!o->IsClass()) {
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -0800565 return StringPrintf("non-class %p", o); // This is only used for debugging output anyway.
566 }
Elliott Hughesc308a5d2012-02-16 17:12:06 -0800567 return DescriptorToName(ClassHelper(o->AsClass()).GetDescriptor());
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700568}
569
Elliott Hughes436e3722012-02-17 20:01:47 -0800570JDWP::JdwpError Dbg::GetClassObject(JDWP::RefTypeId id, JDWP::ObjectId& classObjectId) {
571 JDWP::JdwpError status;
572 Class* c = DecodeClass(id, status);
573 if (c == NULL) {
574 return status;
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -0800575 }
Elliott Hughes436e3722012-02-17 20:01:47 -0800576 classObjectId = gRegistry->Add(c);
577 return JDWP::ERR_NONE;
Elliott Hughes86964332012-02-15 19:37:42 -0800578}
579
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -0800580JDWP::JdwpError Dbg::GetSuperclass(JDWP::RefTypeId id, JDWP::RefTypeId& superclassId) {
581 JDWP::JdwpError status;
582 Class* c = DecodeClass(id, status);
583 if (c == NULL) {
584 return status;
585 }
586 if (c->IsInterface()) {
587 // http://code.google.com/p/android/issues/detail?id=20856
Elliott Hughesa0933622012-04-17 10:46:02 -0700588 superclassId = 0;
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -0800589 } else {
590 superclassId = gRegistry->Add(c->GetSuperClass());
591 }
592 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700593}
594
Elliott Hughes436e3722012-02-17 20:01:47 -0800595JDWP::JdwpError Dbg::GetClassLoader(JDWP::RefTypeId id, JDWP::ExpandBuf* pReply) {
Elliott Hughes1bba14f2011-12-01 18:00:36 -0800596 Object* o = gRegistry->Get<Object*>(id);
Elliott Hughes436e3722012-02-17 20:01:47 -0800597 if (o == NULL || o == kInvalidObject) {
598 return JDWP::ERR_INVALID_OBJECT;
599 }
600 expandBufAddObjectId(pReply, gRegistry->Add(o->GetClass()->GetClassLoader()));
601 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700602}
603
Elliott Hughes436e3722012-02-17 20:01:47 -0800604JDWP::JdwpError Dbg::GetModifiers(JDWP::RefTypeId id, JDWP::ExpandBuf* pReply) {
605 JDWP::JdwpError status;
606 Class* c = DecodeClass(id, status);
607 if (c == NULL) {
608 return status;
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -0800609 }
Elliott Hughes436e3722012-02-17 20:01:47 -0800610
611 uint32_t access_flags = c->GetAccessFlags() & kAccJavaFlagsMask;
612
613 // Set ACC_SUPER; dex files don't contain this flag, but all classes are supposed to have it set.
614 // Class.getModifiers doesn't return it, but JDWP does, so we set it here.
615 access_flags |= kAccSuper;
616
617 expandBufAdd4BE(pReply, access_flags);
618
619 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700620}
621
Elliott Hughes436e3722012-02-17 20:01:47 -0800622JDWP::JdwpError Dbg::GetReflectedType(JDWP::RefTypeId classId, JDWP::ExpandBuf* pReply) {
623 JDWP::JdwpError status;
624 Class* c = DecodeClass(classId, status);
625 if (c == NULL) {
626 return status;
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -0800627 }
Elliott Hughes436e3722012-02-17 20:01:47 -0800628
629 expandBufAdd1(pReply, c->IsInterface() ? JDWP::TT_INTERFACE : JDWP::TT_CLASS);
630 expandBufAddRefTypeId(pReply, classId);
631 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700632}
633
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -0800634void Dbg::GetClassList(std::vector<JDWP::RefTypeId>& classes) {
Elliott Hughesa2155262011-11-16 16:26:58 -0800635 // Get the complete list of reference classes (i.e. all classes except
636 // the primitive types).
637 // Returns a newly-allocated buffer full of RefTypeId values.
638 struct ClassListCreator {
Elliott Hughesba8eee12012-01-24 20:25:24 -0800639 explicit ClassListCreator(std::vector<JDWP::RefTypeId>& classes) : classes(classes) {
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -0800640 }
641
Elliott Hughesa2155262011-11-16 16:26:58 -0800642 static bool Visit(Class* c, void* arg) {
643 return reinterpret_cast<ClassListCreator*>(arg)->Visit(c);
644 }
645
646 bool Visit(Class* c) {
647 if (!c->IsPrimitive()) {
648 classes.push_back(static_cast<JDWP::RefTypeId>(gRegistry->Add(c)));
649 }
650 return true;
651 }
652
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -0800653 std::vector<JDWP::RefTypeId>& classes;
Elliott Hughesa2155262011-11-16 16:26:58 -0800654 };
655
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -0800656 ClassListCreator clc(classes);
Elliott Hughesa2155262011-11-16 16:26:58 -0800657 Runtime::Current()->GetClassLinker()->VisitClasses(ClassListCreator::Visit, &clc);
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700658}
659
Elliott Hughes436e3722012-02-17 20:01:47 -0800660JDWP::JdwpError Dbg::GetClassInfo(JDWP::RefTypeId classId, JDWP::JdwpTypeTag* pTypeTag, uint32_t* pStatus, std::string* pDescriptor) {
661 JDWP::JdwpError status;
662 Class* c = DecodeClass(classId, status);
663 if (c == NULL) {
664 return status;
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -0800665 }
666
Elliott Hughesa2155262011-11-16 16:26:58 -0800667 if (c->IsArrayClass()) {
668 *pStatus = JDWP::CS_VERIFIED | JDWP::CS_PREPARED;
669 *pTypeTag = JDWP::TT_ARRAY;
670 } else {
671 if (c->IsErroneous()) {
672 *pStatus = JDWP::CS_ERROR;
673 } else {
674 *pStatus = JDWP::CS_VERIFIED | JDWP::CS_PREPARED | JDWP::CS_INITIALIZED;
675 }
676 *pTypeTag = c->IsInterface() ? JDWP::TT_INTERFACE : JDWP::TT_CLASS;
677 }
678
679 if (pDescriptor != NULL) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800680 *pDescriptor = ClassHelper(c).GetDescriptor();
Elliott Hughesa2155262011-11-16 16:26:58 -0800681 }
Elliott Hughes436e3722012-02-17 20:01:47 -0800682 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700683}
684
Elliott Hughesc3b77c72011-12-15 20:56:48 -0800685void Dbg::FindLoadedClassBySignature(const char* descriptor, std::vector<JDWP::RefTypeId>& ids) {
Elliott Hughes6fa602d2011-12-02 17:54:25 -0800686 std::vector<Class*> classes;
687 Runtime::Current()->GetClassLinker()->LookupClasses(descriptor, classes);
688 ids.clear();
689 for (size_t i = 0; i < classes.size(); ++i) {
690 ids.push_back(gRegistry->Add(classes[i]));
691 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700692}
693
Elliott Hughes2435a572012-02-17 16:07:41 -0800694JDWP::JdwpError Dbg::GetReferenceType(JDWP::ObjectId objectId, JDWP::ExpandBuf* pReply) {
Elliott Hughes499c5132011-11-17 14:55:11 -0800695 Object* o = gRegistry->Get<Object*>(objectId);
Elliott Hughes436e3722012-02-17 20:01:47 -0800696 if (o == NULL || o == kInvalidObject) {
Elliott Hughes2435a572012-02-17 16:07:41 -0800697 return JDWP::ERR_INVALID_OBJECT;
Elliott Hughes499c5132011-11-17 14:55:11 -0800698 }
Elliott Hughes2435a572012-02-17 16:07:41 -0800699
700 JDWP::JdwpTypeTag type_tag;
701 if (o->GetClass()->IsArrayClass()) {
702 type_tag = JDWP::TT_ARRAY;
703 } else if (o->GetClass()->IsInterface()) {
704 type_tag = JDWP::TT_INTERFACE;
705 } else {
706 type_tag = JDWP::TT_CLASS;
707 }
708 JDWP::RefTypeId type_id = gRegistry->Add(o->GetClass());
709
710 expandBufAdd1(pReply, type_tag);
711 expandBufAddRefTypeId(pReply, type_id);
712
713 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700714}
715
Elliott Hughes436e3722012-02-17 20:01:47 -0800716JDWP::JdwpError Dbg::GetSignature(JDWP::RefTypeId classId, std::string& signature) {
Elliott Hughes1fe7afb2012-02-13 17:23:03 -0800717 JDWP::JdwpError status;
Elliott Hughes436e3722012-02-17 20:01:47 -0800718 Class* c = DecodeClass(classId, status);
Elliott Hughes1fe7afb2012-02-13 17:23:03 -0800719 if (c == NULL) {
720 return status;
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -0800721 }
Elliott Hughes1fe7afb2012-02-13 17:23:03 -0800722 signature = ClassHelper(c).GetDescriptor();
723 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700724}
725
Elliott Hughes436e3722012-02-17 20:01:47 -0800726JDWP::JdwpError Dbg::GetSourceFile(JDWP::RefTypeId classId, std::string& result) {
727 JDWP::JdwpError status;
728 Class* c = DecodeClass(classId, status);
729 if (c == NULL) {
730 return status;
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -0800731 }
Elliott Hughes436e3722012-02-17 20:01:47 -0800732 result = ClassHelper(c).GetSourceFile();
733 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700734}
735
Elliott Hughes546b9862012-06-20 16:06:13 -0700736JDWP::JdwpError Dbg::GetObjectTag(JDWP::ObjectId objectId, uint8_t& tag) {
Elliott Hughes24437992011-11-30 14:49:33 -0800737 Object* o = gRegistry->Get<Object*>(objectId);
Elliott Hughes546b9862012-06-20 16:06:13 -0700738 if (o == kInvalidObject) {
739 return JDWP::ERR_INVALID_OBJECT;
740 }
741 tag = TagFromObject(o);
742 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700743}
744
Elliott Hughesaed4be92011-12-02 16:16:23 -0800745size_t Dbg::GetTagWidth(JDWP::JdwpTag tag) {
Elliott Hughesdbb40792011-11-18 17:05:22 -0800746 switch (tag) {
747 case JDWP::JT_VOID:
748 return 0;
749 case JDWP::JT_BYTE:
750 case JDWP::JT_BOOLEAN:
751 return 1;
752 case JDWP::JT_CHAR:
753 case JDWP::JT_SHORT:
754 return 2;
755 case JDWP::JT_FLOAT:
756 case JDWP::JT_INT:
757 return 4;
758 case JDWP::JT_ARRAY:
759 case JDWP::JT_OBJECT:
760 case JDWP::JT_STRING:
761 case JDWP::JT_THREAD:
762 case JDWP::JT_THREAD_GROUP:
763 case JDWP::JT_CLASS_LOADER:
764 case JDWP::JT_CLASS_OBJECT:
765 return sizeof(JDWP::ObjectId);
766 case JDWP::JT_DOUBLE:
767 case JDWP::JT_LONG:
768 return 8;
769 default:
Elliott Hughes3d30d9b2011-12-07 17:35:48 -0800770 LOG(FATAL) << "Unknown tag " << tag;
Elliott Hughesdbb40792011-11-18 17:05:22 -0800771 return -1;
772 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700773}
774
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -0800775JDWP::JdwpError Dbg::GetArrayLength(JDWP::ObjectId arrayId, int& length) {
776 JDWP::JdwpError status;
777 Array* a = DecodeArray(arrayId, status);
778 if (a == NULL) {
779 return status;
Elliott Hughes24437992011-11-30 14:49:33 -0800780 }
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -0800781 length = a->GetLength();
782 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700783}
784
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -0800785JDWP::JdwpError Dbg::OutputArray(JDWP::ObjectId arrayId, int offset, int count, JDWP::ExpandBuf* pReply) {
786 JDWP::JdwpError status;
787 Array* a = DecodeArray(arrayId, status);
788 if (a == NULL) {
789 return status;
790 }
Elliott Hughes24437992011-11-30 14:49:33 -0800791
792 if (offset < 0 || count < 0 || offset > a->GetLength() || a->GetLength() - offset < count) {
793 LOG(WARNING) << __FUNCTION__ << " access out of bounds: offset=" << offset << "; count=" << count;
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -0800794 return JDWP::ERR_INVALID_LENGTH;
Elliott Hughes24437992011-11-30 14:49:33 -0800795 }
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800796 std::string descriptor(ClassHelper(a->GetClass()).GetDescriptor());
Elliott Hughes24437992011-11-30 14:49:33 -0800797 JDWP::JdwpTag tag = BasicTagFromDescriptor(descriptor.c_str() + 1);
798
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -0800799 expandBufAdd1(pReply, tag);
800 expandBufAdd4BE(pReply, count);
801
Elliott Hughes24437992011-11-30 14:49:33 -0800802 if (IsPrimitiveTag(tag)) {
803 size_t width = GetTagWidth(tag);
Elliott Hughes24437992011-11-30 14:49:33 -0800804 uint8_t* dst = expandBufAddSpace(pReply, count * width);
805 if (width == 8) {
Ian Rogersa15e67d2012-02-28 13:51:55 -0800806 const uint64_t* src8 = reinterpret_cast<uint64_t*>(a->GetRawData(sizeof(uint64_t)));
Elliott Hughes24437992011-11-30 14:49:33 -0800807 for (int i = 0; i < count; ++i) JDWP::Write8BE(&dst, src8[offset + i]);
808 } else if (width == 4) {
Ian Rogersa15e67d2012-02-28 13:51:55 -0800809 const uint32_t* src4 = reinterpret_cast<uint32_t*>(a->GetRawData(sizeof(uint32_t)));
Elliott Hughes24437992011-11-30 14:49:33 -0800810 for (int i = 0; i < count; ++i) JDWP::Write4BE(&dst, src4[offset + i]);
811 } else if (width == 2) {
Ian Rogersa15e67d2012-02-28 13:51:55 -0800812 const uint16_t* src2 = reinterpret_cast<uint16_t*>(a->GetRawData(sizeof(uint16_t)));
Elliott Hughes24437992011-11-30 14:49:33 -0800813 for (int i = 0; i < count; ++i) JDWP::Write2BE(&dst, src2[offset + i]);
814 } else {
Ian Rogersa15e67d2012-02-28 13:51:55 -0800815 const uint8_t* src = reinterpret_cast<uint8_t*>(a->GetRawData(sizeof(uint8_t)));
Elliott Hughes24437992011-11-30 14:49:33 -0800816 memcpy(dst, &src[offset * width], count * width);
817 }
818 } else {
819 ObjectArray<Object>* oa = a->AsObjectArray<Object>();
820 for (int i = 0; i < count; ++i) {
Elliott Hughesf03b8f62011-12-02 14:26:25 -0800821 Object* element = oa->Get(offset + i);
Elliott Hughes24437992011-11-30 14:49:33 -0800822 JDWP::JdwpTag specific_tag = (element != NULL) ? TagFromObject(element) : tag;
823 expandBufAdd1(pReply, specific_tag);
824 expandBufAddObjectId(pReply, gRegistry->Add(element));
825 }
826 }
827
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -0800828 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700829}
830
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700831JDWP::JdwpError Dbg::SetArrayElements(JDWP::ObjectId arrayId, int offset, int count,
832 const uint8_t* src)
Ian Rogersb726dcb2012-09-05 08:57:23 -0700833 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -0800834 JDWP::JdwpError status;
835 Array* a = DecodeArray(arrayId, status);
836 if (a == NULL) {
837 return status;
838 }
Elliott Hughesf03b8f62011-12-02 14:26:25 -0800839
840 if (offset < 0 || count < 0 || offset > a->GetLength() || a->GetLength() - offset < count) {
841 LOG(WARNING) << __FUNCTION__ << " access out of bounds: offset=" << offset << "; count=" << count;
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -0800842 return JDWP::ERR_INVALID_LENGTH;
Elliott Hughesf03b8f62011-12-02 14:26:25 -0800843 }
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800844 std::string descriptor(ClassHelper(a->GetClass()).GetDescriptor());
Elliott Hughesf03b8f62011-12-02 14:26:25 -0800845 JDWP::JdwpTag tag = BasicTagFromDescriptor(descriptor.c_str() + 1);
846
847 if (IsPrimitiveTag(tag)) {
848 size_t width = GetTagWidth(tag);
Elliott Hughesf03b8f62011-12-02 14:26:25 -0800849 if (width == 8) {
Ian Rogersa15e67d2012-02-28 13:51:55 -0800850 uint8_t* dst = &(reinterpret_cast<uint8_t*>(a->GetRawData(sizeof(uint64_t)))[offset * width]);
Elliott Hughesf03b8f62011-12-02 14:26:25 -0800851 for (int i = 0; i < count; ++i) {
852 // Handle potentially non-aligned memory access one byte at a time for ARM's benefit.
853 uint64_t value;
854 for (size_t j = 0; j < sizeof(uint64_t); ++j) reinterpret_cast<uint8_t*>(&value)[j] = src[j];
855 src += sizeof(uint64_t);
856 JDWP::Write8BE(&dst, value);
857 }
858 } else if (width == 4) {
Ian Rogersa15e67d2012-02-28 13:51:55 -0800859 uint8_t* dst = &(reinterpret_cast<uint8_t*>(a->GetRawData(sizeof(uint32_t)))[offset * width]);
Elliott Hughesf03b8f62011-12-02 14:26:25 -0800860 const uint32_t* src4 = reinterpret_cast<const uint32_t*>(src);
861 for (int i = 0; i < count; ++i) JDWP::Write4BE(&dst, src4[i]);
862 } else if (width == 2) {
Ian Rogersa15e67d2012-02-28 13:51:55 -0800863 uint8_t* dst = &(reinterpret_cast<uint8_t*>(a->GetRawData(sizeof(uint16_t)))[offset * width]);
Elliott Hughesf03b8f62011-12-02 14:26:25 -0800864 const uint16_t* src2 = reinterpret_cast<const uint16_t*>(src);
865 for (int i = 0; i < count; ++i) JDWP::Write2BE(&dst, src2[i]);
866 } else {
Ian Rogersa15e67d2012-02-28 13:51:55 -0800867 uint8_t* dst = &(reinterpret_cast<uint8_t*>(a->GetRawData(sizeof(uint8_t)))[offset * width]);
Elliott Hughesf03b8f62011-12-02 14:26:25 -0800868 memcpy(&dst[offset * width], src, count * width);
869 }
870 } else {
871 ObjectArray<Object>* oa = a->AsObjectArray<Object>();
872 for (int i = 0; i < count; ++i) {
873 JDWP::ObjectId id = JDWP::ReadObjectId(&src);
Elliott Hughes436e3722012-02-17 20:01:47 -0800874 Object* o = gRegistry->Get<Object*>(id);
875 if (o == kInvalidObject) {
876 return JDWP::ERR_INVALID_OBJECT;
877 }
878 oa->Set(offset + i, o);
Elliott Hughesf03b8f62011-12-02 14:26:25 -0800879 }
880 }
881
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -0800882 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700883}
884
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -0800885JDWP::ObjectId Dbg::CreateString(const std::string& str) {
Ian Rogers50b35e22012-10-04 10:09:15 -0700886 return gRegistry->Add(String::AllocFromModifiedUtf8(Thread::Current(), str.c_str()));
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700887}
888
Elliott Hughes436e3722012-02-17 20:01:47 -0800889JDWP::JdwpError Dbg::CreateObject(JDWP::RefTypeId classId, JDWP::ObjectId& new_object) {
890 JDWP::JdwpError status;
891 Class* c = DecodeClass(classId, status);
892 if (c == NULL) {
893 return status;
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -0800894 }
Ian Rogers50b35e22012-10-04 10:09:15 -0700895 new_object = gRegistry->Add(c->AllocObject(Thread::Current()));
Elliott Hughes436e3722012-02-17 20:01:47 -0800896 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700897}
898
Elliott Hughesbf13d362011-12-08 15:51:37 -0800899/*
900 * Used by Eclipse's "Display" view to evaluate "new byte[5]" to get "(byte[]) [0, 0, 0, 0, 0]".
901 */
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700902JDWP::JdwpError Dbg::CreateArrayObject(JDWP::RefTypeId arrayClassId, uint32_t length,
903 JDWP::ObjectId& new_array) {
Elliott Hughes436e3722012-02-17 20:01:47 -0800904 JDWP::JdwpError status;
905 Class* c = DecodeClass(arrayClassId, status);
906 if (c == NULL) {
907 return status;
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -0800908 }
Ian Rogers50b35e22012-10-04 10:09:15 -0700909 new_array = gRegistry->Add(Array::Alloc(Thread::Current(), c, length));
Elliott Hughes436e3722012-02-17 20:01:47 -0800910 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700911}
912
913bool Dbg::MatchType(JDWP::RefTypeId instClassId, JDWP::RefTypeId classId) {
Elliott Hughes436e3722012-02-17 20:01:47 -0800914 JDWP::JdwpError status;
915 Class* c1 = DecodeClass(instClassId, status);
Elliott Hughesa656a0f2012-02-21 18:03:44 -0800916 CHECK(c1 != NULL);
Elliott Hughes436e3722012-02-17 20:01:47 -0800917 Class* c2 = DecodeClass(classId, status);
Elliott Hughesa656a0f2012-02-21 18:03:44 -0800918 CHECK(c2 != NULL);
919 return c1->IsAssignableFrom(c2);
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700920}
921
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700922static JDWP::FieldId ToFieldId(const Field* f)
Ian Rogersb726dcb2012-09-05 08:57:23 -0700923 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Elliott Hughes03181a82011-11-17 17:22:21 -0800924#ifdef MOVING_GARBAGE_COLLECTOR
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700925 UNIMPLEMENTED(FATAL);
Elliott Hughes03181a82011-11-17 17:22:21 -0800926#else
927 return static_cast<JDWP::FieldId>(reinterpret_cast<uintptr_t>(f));
928#endif
929}
930
Mathieu Chartier66f19252012-09-18 08:57:04 -0700931static JDWP::MethodId ToMethodId(const AbstractMethod* m)
Ian Rogersb726dcb2012-09-05 08:57:23 -0700932 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Elliott Hughes03181a82011-11-17 17:22:21 -0800933#ifdef MOVING_GARBAGE_COLLECTOR
934 UNIMPLEMENTED(FATAL);
935#else
936 return static_cast<JDWP::MethodId>(reinterpret_cast<uintptr_t>(m));
937#endif
938}
939
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700940static Field* FromFieldId(JDWP::FieldId fid)
Ian Rogersb726dcb2012-09-05 08:57:23 -0700941 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Elliott Hughesaed4be92011-12-02 16:16:23 -0800942#ifdef MOVING_GARBAGE_COLLECTOR
943 UNIMPLEMENTED(FATAL);
944#else
945 return reinterpret_cast<Field*>(static_cast<uintptr_t>(fid));
946#endif
947}
948
Mathieu Chartier66f19252012-09-18 08:57:04 -0700949static AbstractMethod* FromMethodId(JDWP::MethodId mid)
Ian Rogersb726dcb2012-09-05 08:57:23 -0700950 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Elliott Hughes03181a82011-11-17 17:22:21 -0800951#ifdef MOVING_GARBAGE_COLLECTOR
952 UNIMPLEMENTED(FATAL);
953#else
Mathieu Chartier66f19252012-09-18 08:57:04 -0700954 return reinterpret_cast<AbstractMethod*>(static_cast<uintptr_t>(mid));
Elliott Hughes03181a82011-11-17 17:22:21 -0800955#endif
956}
957
Mathieu Chartier66f19252012-09-18 08:57:04 -0700958static void SetLocation(JDWP::JdwpLocation& location, AbstractMethod* m, uint32_t dex_pc)
Ian Rogersb726dcb2012-09-05 08:57:23 -0700959 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Elliott Hughes91bf6cd2012-02-14 17:27:48 -0800960 if (m == NULL) {
961 memset(&location, 0, sizeof(location));
962 } else {
963 Class* c = m->GetDeclaringClass();
Elliott Hughes74847412012-06-20 18:10:21 -0700964 location.type_tag = c->IsInterface() ? JDWP::TT_INTERFACE : JDWP::TT_CLASS;
965 location.class_id = gRegistry->Add(c);
966 location.method_id = ToMethodId(m);
Ian Rogers0399dde2012-06-06 17:09:28 -0700967 location.dex_pc = dex_pc;
Elliott Hughes91bf6cd2012-02-14 17:27:48 -0800968 }
Elliott Hughesd07986f2011-12-06 18:27:45 -0800969}
970
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700971std::string Dbg::GetMethodName(JDWP::RefTypeId, JDWP::MethodId methodId)
Ian Rogersb726dcb2012-09-05 08:57:23 -0700972 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Mathieu Chartier66f19252012-09-18 08:57:04 -0700973 AbstractMethod* m = FromMethodId(methodId);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800974 return MethodHelper(m).GetName();
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700975}
976
Elliott Hughesa2e54f62011-11-17 13:01:30 -0800977/*
978 * Augment the access flags for synthetic methods and fields by setting
979 * the (as described by the spec) "0xf0000000 bit". Also, strip out any
980 * flags not specified by the Java programming language.
981 */
982static uint32_t MangleAccessFlags(uint32_t accessFlags) {
983 accessFlags &= kAccJavaFlagsMask;
984 if ((accessFlags & kAccSynthetic) != 0) {
985 accessFlags |= 0xf0000000;
986 }
987 return accessFlags;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700988}
989
Elliott Hughesdbb40792011-11-18 17:05:22 -0800990static const uint16_t kEclipseWorkaroundSlot = 1000;
991
992/*
993 * Eclipse appears to expect that the "this" reference is in slot zero.
994 * If it's not, the "variables" display will show two copies of "this",
995 * possibly because it gets "this" from SF.ThisObject and then displays
996 * all locals with nonzero slot numbers.
997 *
998 * So, we remap the item in slot 0 to 1000, and remap "this" to zero. On
999 * SF.GetValues / SF.SetValues we map them back.
Elliott Hughesc5b734a2011-12-01 17:20:58 -08001000 *
1001 * TODO: jdb uses the value to determine whether a variable is a local or an argument,
1002 * by checking whether it's less than the number of arguments. To make that work, we'd
1003 * have to "mangle" all the arguments to come first, not just the implicit argument 'this'.
Elliott Hughesdbb40792011-11-18 17:05:22 -08001004 */
1005static uint16_t MangleSlot(uint16_t slot, const char* name) {
1006 uint16_t newSlot = slot;
1007 if (strcmp(name, "this") == 0) {
1008 newSlot = 0;
1009 } else if (slot == 0) {
1010 newSlot = kEclipseWorkaroundSlot;
1011 }
1012 return newSlot;
1013}
1014
Mathieu Chartier66f19252012-09-18 08:57:04 -07001015static uint16_t DemangleSlot(uint16_t slot, AbstractMethod* m)
Ian Rogersb726dcb2012-09-05 08:57:23 -07001016 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Elliott Hughesdbb40792011-11-18 17:05:22 -08001017 if (slot == kEclipseWorkaroundSlot) {
Elliott Hughes68fdbd02011-11-29 19:22:47 -08001018 return 0;
Elliott Hughesdbb40792011-11-18 17:05:22 -08001019 } else if (slot == 0) {
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08001020 const DexFile::CodeItem* code_item = MethodHelper(m).GetCodeItem();
Elliott Hughescaf76542012-06-28 16:08:22 -07001021 CHECK(code_item != NULL) << PrettyMethod(m);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001022 return code_item->registers_size_ - code_item->ins_size_;
Elliott Hughesdbb40792011-11-18 17:05:22 -08001023 }
Elliott Hughes68fdbd02011-11-29 19:22:47 -08001024 return slot;
Elliott Hughesdbb40792011-11-18 17:05:22 -08001025}
1026
Elliott Hughes436e3722012-02-17 20:01:47 -08001027JDWP::JdwpError Dbg::OutputDeclaredFields(JDWP::RefTypeId classId, bool with_generic, JDWP::ExpandBuf* pReply) {
1028 JDWP::JdwpError status;
1029 Class* c = DecodeClass(classId, status);
1030 if (c == NULL) {
1031 return status;
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -08001032 }
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001033
1034 size_t instance_field_count = c->NumInstanceFields();
1035 size_t static_field_count = c->NumStaticFields();
1036
1037 expandBufAdd4BE(pReply, instance_field_count + static_field_count);
1038
1039 for (size_t i = 0; i < instance_field_count + static_field_count; ++i) {
1040 Field* f = (i < instance_field_count) ? c->GetInstanceField(i) : c->GetStaticField(i - instance_field_count);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001041 FieldHelper fh(f);
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001042 expandBufAddFieldId(pReply, ToFieldId(f));
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001043 expandBufAddUtf8String(pReply, fh.GetName());
1044 expandBufAddUtf8String(pReply, fh.GetTypeDescriptor());
Elliott Hughesc5b734a2011-12-01 17:20:58 -08001045 if (with_generic) {
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001046 static const char genericSignature[1] = "";
1047 expandBufAddUtf8String(pReply, genericSignature);
1048 }
1049 expandBufAdd4BE(pReply, MangleAccessFlags(f->GetAccessFlags()));
1050 }
Elliott Hughes436e3722012-02-17 20:01:47 -08001051 return JDWP::ERR_NONE;
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001052}
1053
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001054JDWP::JdwpError Dbg::OutputDeclaredMethods(JDWP::RefTypeId classId, bool with_generic,
1055 JDWP::ExpandBuf* pReply) {
Elliott Hughes436e3722012-02-17 20:01:47 -08001056 JDWP::JdwpError status;
1057 Class* c = DecodeClass(classId, status);
1058 if (c == NULL) {
1059 return status;
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -08001060 }
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001061
1062 size_t direct_method_count = c->NumDirectMethods();
1063 size_t virtual_method_count = c->NumVirtualMethods();
1064
1065 expandBufAdd4BE(pReply, direct_method_count + virtual_method_count);
1066
1067 for (size_t i = 0; i < direct_method_count + virtual_method_count; ++i) {
Mathieu Chartier66f19252012-09-18 08:57:04 -07001068 AbstractMethod* m = (i < direct_method_count) ? c->GetDirectMethod(i) : c->GetVirtualMethod(i - direct_method_count);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001069 MethodHelper mh(m);
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001070 expandBufAddMethodId(pReply, ToMethodId(m));
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001071 expandBufAddUtf8String(pReply, mh.GetName());
Elliott Hughes4740cdf2011-12-07 14:07:12 -08001072 expandBufAddUtf8String(pReply, mh.GetSignature());
Elliott Hughesc5b734a2011-12-01 17:20:58 -08001073 if (with_generic) {
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001074 static const char genericSignature[1] = "";
1075 expandBufAddUtf8String(pReply, genericSignature);
1076 }
1077 expandBufAdd4BE(pReply, MangleAccessFlags(m->GetAccessFlags()));
1078 }
Elliott Hughes436e3722012-02-17 20:01:47 -08001079 return JDWP::ERR_NONE;
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001080}
1081
Elliott Hughes436e3722012-02-17 20:01:47 -08001082JDWP::JdwpError Dbg::OutputDeclaredInterfaces(JDWP::RefTypeId classId, JDWP::ExpandBuf* pReply) {
1083 JDWP::JdwpError status;
1084 Class* c = DecodeClass(classId, status);
1085 if (c == NULL) {
1086 return status;
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -08001087 }
Elliott Hughes436e3722012-02-17 20:01:47 -08001088
1089 ClassHelper kh(c);
Ian Rogersd24e2642012-06-06 21:21:43 -07001090 size_t interface_count = kh.NumDirectInterfaces();
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001091 expandBufAdd4BE(pReply, interface_count);
1092 for (size_t i = 0; i < interface_count; ++i) {
Ian Rogersd24e2642012-06-06 21:21:43 -07001093 expandBufAddRefTypeId(pReply, gRegistry->Add(kh.GetDirectInterface(i)));
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001094 }
Elliott Hughes436e3722012-02-17 20:01:47 -08001095 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001096}
1097
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001098void Dbg::OutputLineTable(JDWP::RefTypeId, JDWP::MethodId methodId, JDWP::ExpandBuf* pReply)
Ian Rogersb726dcb2012-09-05 08:57:23 -07001099 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Elliott Hughes03181a82011-11-17 17:22:21 -08001100 struct DebugCallbackContext {
1101 int numItems;
1102 JDWP::ExpandBuf* pReply;
1103
Elliott Hughes2435a572012-02-17 16:07:41 -08001104 static bool Callback(void* context, uint32_t address, uint32_t line_number) {
Elliott Hughes03181a82011-11-17 17:22:21 -08001105 DebugCallbackContext* pContext = reinterpret_cast<DebugCallbackContext*>(context);
1106 expandBufAdd8BE(pContext->pReply, address);
Elliott Hughes2435a572012-02-17 16:07:41 -08001107 expandBufAdd4BE(pContext->pReply, line_number);
Elliott Hughes03181a82011-11-17 17:22:21 -08001108 pContext->numItems++;
1109 return true;
1110 }
1111 };
Mathieu Chartier66f19252012-09-18 08:57:04 -07001112 AbstractMethod* m = FromMethodId(methodId);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001113 MethodHelper mh(m);
Elliott Hughes03181a82011-11-17 17:22:21 -08001114 uint64_t start, end;
1115 if (m->IsNative()) {
1116 start = -1;
1117 end = -1;
1118 } else {
1119 start = 0;
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001120 // TODO: what are the units supposed to be? *2?
1121 end = mh.GetCodeItem()->insns_size_in_code_units_;
Elliott Hughes03181a82011-11-17 17:22:21 -08001122 }
1123
1124 expandBufAdd8BE(pReply, start);
1125 expandBufAdd8BE(pReply, end);
1126
1127 // Add numLines later
1128 size_t numLinesOffset = expandBufGetLength(pReply);
1129 expandBufAdd4BE(pReply, 0);
1130
1131 DebugCallbackContext context;
1132 context.numItems = 0;
1133 context.pReply = pReply;
1134
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001135 mh.GetDexFile().DecodeDebugInfo(mh.GetCodeItem(), m->IsStatic(), m->GetDexMethodIndex(),
1136 DebugCallbackContext::Callback, NULL, &context);
Elliott Hughes03181a82011-11-17 17:22:21 -08001137
1138 JDWP::Set4BE(expandBufGetBuffer(pReply) + numLinesOffset, context.numItems);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001139}
1140
Elliott Hughes436e3722012-02-17 20:01:47 -08001141void Dbg::OutputVariableTable(JDWP::RefTypeId, JDWP::MethodId methodId, bool with_generic, JDWP::ExpandBuf* pReply) {
Elliott Hughesdbb40792011-11-18 17:05:22 -08001142 struct DebugCallbackContext {
Elliott Hughesdbb40792011-11-18 17:05:22 -08001143 JDWP::ExpandBuf* pReply;
Elliott Hughesc5b734a2011-12-01 17:20:58 -08001144 size_t variable_count;
1145 bool with_generic;
Elliott Hughesdbb40792011-11-18 17:05:22 -08001146
Elliott Hughesc5b734a2011-12-01 17:20:58 -08001147 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 -08001148 DebugCallbackContext* pContext = reinterpret_cast<DebugCallbackContext*>(context);
1149
Elliott Hughesad3da692012-02-24 16:51:35 -08001150 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 -08001151
Elliott Hughes68fdbd02011-11-29 19:22:47 -08001152 slot = MangleSlot(slot, name);
1153
Elliott Hughesdbb40792011-11-18 17:05:22 -08001154 expandBufAdd8BE(pContext->pReply, startAddress);
1155 expandBufAddUtf8String(pContext->pReply, name);
1156 expandBufAddUtf8String(pContext->pReply, descriptor);
Elliott Hughesc5b734a2011-12-01 17:20:58 -08001157 if (pContext->with_generic) {
Elliott Hughesdbb40792011-11-18 17:05:22 -08001158 expandBufAddUtf8String(pContext->pReply, signature);
1159 }
1160 expandBufAdd4BE(pContext->pReply, endAddress - startAddress);
1161 expandBufAdd4BE(pContext->pReply, slot);
1162
Elliott Hughesc5b734a2011-12-01 17:20:58 -08001163 ++pContext->variable_count;
Elliott Hughesdbb40792011-11-18 17:05:22 -08001164 }
1165 };
Mathieu Chartier66f19252012-09-18 08:57:04 -07001166 AbstractMethod* m = FromMethodId(methodId);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001167 MethodHelper mh(m);
1168 const DexFile::CodeItem* code_item = mh.GetCodeItem();
Elliott Hughesdbb40792011-11-18 17:05:22 -08001169
Elliott Hughesc5b734a2011-12-01 17:20:58 -08001170 // arg_count considers doubles and longs to take 2 units.
1171 // variable_count considers everything to take 1 unit.
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001172 std::string shorty(mh.GetShorty());
Ian Rogers2fa6b2e2012-10-17 00:10:17 -07001173 expandBufAdd4BE(pReply, AbstractMethod::NumArgRegisters(shorty));
Elliott Hughesdbb40792011-11-18 17:05:22 -08001174
Elliott Hughesc5b734a2011-12-01 17:20:58 -08001175 // We don't know the total number of variables yet, so leave a blank and update it later.
1176 size_t variable_count_offset = expandBufGetLength(pReply);
Elliott Hughesdbb40792011-11-18 17:05:22 -08001177 expandBufAdd4BE(pReply, 0);
1178
1179 DebugCallbackContext context;
Elliott Hughesdbb40792011-11-18 17:05:22 -08001180 context.pReply = pReply;
Elliott Hughesc5b734a2011-12-01 17:20:58 -08001181 context.variable_count = 0;
1182 context.with_generic = with_generic;
Elliott Hughesdbb40792011-11-18 17:05:22 -08001183
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001184 mh.GetDexFile().DecodeDebugInfo(code_item, m->IsStatic(), m->GetDexMethodIndex(), NULL,
1185 DebugCallbackContext::Callback, &context);
Elliott Hughesdbb40792011-11-18 17:05:22 -08001186
Elliott Hughesc5b734a2011-12-01 17:20:58 -08001187 JDWP::Set4BE(expandBufGetBuffer(pReply) + variable_count_offset, context.variable_count);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001188}
1189
Elliott Hughesaed4be92011-12-02 16:16:23 -08001190JDWP::JdwpTag Dbg::GetFieldBasicTag(JDWP::FieldId fieldId) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001191 return BasicTagFromDescriptor(FieldHelper(FromFieldId(fieldId)).GetTypeDescriptor());
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001192}
1193
Elliott Hughesaed4be92011-12-02 16:16:23 -08001194JDWP::JdwpTag Dbg::GetStaticFieldBasicTag(JDWP::FieldId fieldId) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001195 return BasicTagFromDescriptor(FieldHelper(FromFieldId(fieldId)).GetTypeDescriptor());
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001196}
1197
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001198static JDWP::JdwpError GetFieldValueImpl(JDWP::RefTypeId refTypeId, JDWP::ObjectId objectId,
1199 JDWP::FieldId fieldId, JDWP::ExpandBuf* pReply,
1200 bool is_static)
Ian Rogersb726dcb2012-09-05 08:57:23 -07001201 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Elliott Hughes0cf74332012-02-23 23:14:00 -08001202 JDWP::JdwpError status;
1203 Class* c = DecodeClass(refTypeId, status);
1204 if (refTypeId != 0 && c == NULL) {
1205 return status;
1206 }
1207
Elliott Hughesaed4be92011-12-02 16:16:23 -08001208 Object* o = gRegistry->Get<Object*>(objectId);
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08001209 if ((!is_static && o == NULL) || o == kInvalidObject) {
1210 return JDWP::ERR_INVALID_OBJECT;
1211 }
Elliott Hughesaed4be92011-12-02 16:16:23 -08001212 Field* f = FromFieldId(fieldId);
Elliott Hughes0cf74332012-02-23 23:14:00 -08001213
1214 Class* receiver_class = c;
1215 if (receiver_class == NULL && o != NULL) {
1216 receiver_class = o->GetClass();
1217 }
1218 // TODO: should we give up now if receiver_class is NULL?
1219 if (receiver_class != NULL && !f->GetDeclaringClass()->IsAssignableFrom(receiver_class)) {
1220 LOG(INFO) << "ERR_INVALID_FIELDID: " << PrettyField(f) << " " << PrettyClass(receiver_class);
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08001221 return JDWP::ERR_INVALID_FIELDID;
1222 }
Elliott Hughesaed4be92011-12-02 16:16:23 -08001223
Elliott Hughes0cf74332012-02-23 23:14:00 -08001224 // The RI only enforces the static/non-static mismatch in one direction.
1225 // TODO: should we change the tests and check both?
1226 if (is_static) {
1227 if (!f->IsStatic()) {
1228 return JDWP::ERR_INVALID_FIELDID;
1229 }
1230 } else {
1231 if (f->IsStatic()) {
1232 LOG(WARNING) << "Ignoring non-NULL receiver for ObjectReference.SetValues on static field " << PrettyField(f);
Elliott Hughes0cf74332012-02-23 23:14:00 -08001233 }
1234 }
jeffhao0dfbb7e2012-11-28 15:26:03 -08001235 if (f->IsStatic()) {
1236 o = f->GetDeclaringClass();
1237 }
Elliott Hughes0cf74332012-02-23 23:14:00 -08001238
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001239 JDWP::JdwpTag tag = BasicTagFromDescriptor(FieldHelper(f).GetTypeDescriptor());
Elliott Hughesaed4be92011-12-02 16:16:23 -08001240
1241 if (IsPrimitiveTag(tag)) {
1242 expandBufAdd1(pReply, tag);
1243 if (tag == JDWP::JT_BOOLEAN || tag == JDWP::JT_BYTE) {
1244 expandBufAdd1(pReply, f->Get32(o));
1245 } else if (tag == JDWP::JT_CHAR || tag == JDWP::JT_SHORT) {
1246 expandBufAdd2BE(pReply, f->Get32(o));
1247 } else if (tag == JDWP::JT_FLOAT || tag == JDWP::JT_INT) {
1248 expandBufAdd4BE(pReply, f->Get32(o));
1249 } else if (tag == JDWP::JT_DOUBLE || tag == JDWP::JT_LONG) {
1250 expandBufAdd8BE(pReply, f->Get64(o));
1251 } else {
Elliott Hughes3d30d9b2011-12-07 17:35:48 -08001252 LOG(FATAL) << "Unknown tag: " << tag;
Elliott Hughesaed4be92011-12-02 16:16:23 -08001253 }
1254 } else {
1255 Object* value = f->GetObject(o);
1256 expandBufAdd1(pReply, TagFromObject(value));
1257 expandBufAddObjectId(pReply, gRegistry->Add(value));
1258 }
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08001259 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001260}
1261
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001262JDWP::JdwpError Dbg::GetFieldValue(JDWP::ObjectId objectId, JDWP::FieldId fieldId,
1263 JDWP::ExpandBuf* pReply) {
Elliott Hughes0cf74332012-02-23 23:14:00 -08001264 return GetFieldValueImpl(0, objectId, fieldId, pReply, false);
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08001265}
1266
Elliott Hughes0cf74332012-02-23 23:14:00 -08001267JDWP::JdwpError Dbg::GetStaticFieldValue(JDWP::RefTypeId refTypeId, JDWP::FieldId fieldId, JDWP::ExpandBuf* pReply) {
1268 return GetFieldValueImpl(refTypeId, 0, fieldId, pReply, true);
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08001269}
1270
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001271static JDWP::JdwpError SetFieldValueImpl(JDWP::ObjectId objectId, JDWP::FieldId fieldId,
1272 uint64_t value, int width, bool is_static)
Ian Rogersb726dcb2012-09-05 08:57:23 -07001273 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Elliott Hughesaed4be92011-12-02 16:16:23 -08001274 Object* o = gRegistry->Get<Object*>(objectId);
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08001275 if ((!is_static && o == NULL) || o == kInvalidObject) {
1276 return JDWP::ERR_INVALID_OBJECT;
1277 }
Elliott Hughesaed4be92011-12-02 16:16:23 -08001278 Field* f = FromFieldId(fieldId);
Elliott Hughes0cf74332012-02-23 23:14:00 -08001279
1280 // The RI only enforces the static/non-static mismatch in one direction.
1281 // TODO: should we change the tests and check both?
1282 if (is_static) {
1283 if (!f->IsStatic()) {
1284 return JDWP::ERR_INVALID_FIELDID;
1285 }
1286 } else {
1287 if (f->IsStatic()) {
1288 LOG(WARNING) << "Ignoring non-NULL receiver for ObjectReference.SetValues on static field " << PrettyField(f);
Elliott Hughes0cf74332012-02-23 23:14:00 -08001289 }
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08001290 }
jeffhao0dfbb7e2012-11-28 15:26:03 -08001291 if (f->IsStatic()) {
1292 o = f->GetDeclaringClass();
1293 }
Elliott Hughesaed4be92011-12-02 16:16:23 -08001294
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001295 JDWP::JdwpTag tag = BasicTagFromDescriptor(FieldHelper(f).GetTypeDescriptor());
Elliott Hughesaed4be92011-12-02 16:16:23 -08001296
1297 if (IsPrimitiveTag(tag)) {
1298 if (tag == JDWP::JT_DOUBLE || tag == JDWP::JT_LONG) {
Elliott Hughes1bac54f2012-03-16 12:48:31 -07001299 CHECK_EQ(width, 8);
Elliott Hughesaed4be92011-12-02 16:16:23 -08001300 f->Set64(o, value);
1301 } else {
Elliott Hughes1bac54f2012-03-16 12:48:31 -07001302 CHECK_LE(width, 4);
Elliott Hughesaed4be92011-12-02 16:16:23 -08001303 f->Set32(o, value);
1304 }
1305 } else {
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -08001306 Object* v = gRegistry->Get<Object*>(value);
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08001307 if (v == kInvalidObject) {
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -08001308 return JDWP::ERR_INVALID_OBJECT;
1309 }
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08001310 if (v != NULL) {
1311 Class* field_type = FieldHelper(f).GetType();
1312 if (!field_type->IsAssignableFrom(v->GetClass())) {
1313 return JDWP::ERR_INVALID_OBJECT;
1314 }
1315 }
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -08001316 f->SetObject(o, v);
Elliott Hughesaed4be92011-12-02 16:16:23 -08001317 }
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -08001318
1319 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001320}
1321
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001322JDWP::JdwpError Dbg::SetFieldValue(JDWP::ObjectId objectId, JDWP::FieldId fieldId, uint64_t value,
1323 int width) {
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08001324 return SetFieldValueImpl(objectId, fieldId, value, width, false);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001325}
1326
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -08001327JDWP::JdwpError Dbg::SetStaticFieldValue(JDWP::FieldId fieldId, uint64_t value, int width) {
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08001328 return SetFieldValueImpl(0, fieldId, value, width, true);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001329}
1330
Elliott Hughes68fdbd02011-11-29 19:22:47 -08001331std::string Dbg::StringToUtf8(JDWP::ObjectId strId) {
1332 String* s = gRegistry->Get<String*>(strId);
1333 return s->ToModifiedUtf8();
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001334}
1335
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001336bool Dbg::GetThreadName(JDWP::ObjectId threadId, std::string& name) {
Ian Rogers50b35e22012-10-04 10:09:15 -07001337 Thread* self = Thread::Current();
1338 MutexLock mu(self, *Locks::thread_list_lock_);
1339 ScopedObjectAccessUnchecked soa(self);
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 Hughes3ce4b262012-02-24 11:24:02 -08001423 // TODO: if we're in Thread.sleep(long), we should return TS_SLEEPING,
1424 // even if it's implemented using Object.wait(long).
Elliott Hughes499c5132011-11-17 14:55:11 -08001425 switch (thread->GetState()) {
Elliott Hughes34e06962012-04-09 13:55:55 -07001426 case kTerminated: *pThreadStatus = JDWP::TS_ZOMBIE; break;
1427 case kRunnable: *pThreadStatus = JDWP::TS_RUNNING; break;
1428 case kTimedWaiting: *pThreadStatus = JDWP::TS_WAIT; break;
1429 case kBlocked: *pThreadStatus = JDWP::TS_MONITOR; break;
1430 case kWaiting: *pThreadStatus = JDWP::TS_WAIT; break;
1431 case kStarting: *pThreadStatus = JDWP::TS_ZOMBIE; break;
1432 case kNative: *pThreadStatus = JDWP::TS_RUNNING; break;
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001433 case kWaitingForGcToComplete: // Fall-through.
1434 case kWaitingPerformingGc: // Fall-through.
1435 case kWaitingForDebuggerSend: // Fall-through.
1436 case kWaitingForDebuggerToAttach: // Fall-through.
1437 case kWaitingInMainDebuggerLoop: // Fall-through.
1438 case kWaitingForDebuggerSuspension: // Fall-through.
1439 case kWaitingForJniOnLoad: // Fall-through.
1440 case kWaitingForSignalCatcherOutput: // Fall-through.
1441 case kWaitingInMainSignalCatcherLoop:
1442 *pThreadStatus = JDWP::TS_WAIT; break;
Elliott Hughes34e06962012-04-09 13:55:55 -07001443 case kSuspended: *pThreadStatus = JDWP::TS_RUNNING; break;
Elliott Hughescf2b2d42012-03-27 17:11:42 -07001444 // Don't add a 'default' here so the compiler can spot incompatible enum changes.
Elliott Hughes499c5132011-11-17 14:55:11 -08001445 }
1446
Elliott Hughes3d30d9b2011-12-07 17:35:48 -08001447 *pSuspendStatus = (thread->IsSuspended() ? JDWP::SUSPEND_STATUS_SUSPENDED : JDWP::SUSPEND_STATUS_NOT_SUSPENDED);
Elliott Hughes499c5132011-11-17 14:55:11 -08001448
1449 return true;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001450}
1451
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001452JDWP::JdwpError Dbg::GetThreadDebugSuspendCount(JDWP::ObjectId threadId, JDWP::ExpandBuf* pReply) {
1453 ScopedObjectAccess soa(Thread::Current());
1454
Ian Rogers50b35e22012-10-04 10:09:15 -07001455 MutexLock mu(soa.Self(), *Locks::thread_list_lock_);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001456 Thread* thread = DecodeThread(soa, threadId);
Elliott Hughes2435a572012-02-17 16:07:41 -08001457 if (thread == NULL) {
1458 return JDWP::ERR_INVALID_THREAD;
1459 }
Ian Rogers50b35e22012-10-04 10:09:15 -07001460 MutexLock mu2(soa.Self(), *Locks::thread_suspend_count_lock_);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001461 expandBufAdd4BE(pReply, thread->GetDebugSuspendCount());
Elliott Hughes2435a572012-02-17 16:07:41 -08001462 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001463}
1464
1465bool Dbg::ThreadExists(JDWP::ObjectId threadId) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001466 ScopedObjectAccess soa(Thread::Current());
Ian Rogers50b35e22012-10-04 10:09:15 -07001467 MutexLock mu(soa.Self(), *Locks::thread_list_lock_);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001468 return DecodeThread(soa, threadId) != NULL;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001469}
1470
1471bool Dbg::IsSuspended(JDWP::ObjectId threadId) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001472 ScopedObjectAccess soa(Thread::Current());
Ian Rogers50b35e22012-10-04 10:09:15 -07001473 MutexLock mu(soa.Self(), *Locks::thread_list_lock_);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001474 Thread* thread = DecodeThread(soa, threadId);
1475 CHECK(thread != NULL);
Ian Rogers50b35e22012-10-04 10:09:15 -07001476 MutexLock mu2(soa.Self(), *Locks::thread_suspend_count_lock_);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001477 return thread->IsSuspended();
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001478}
1479
Elliott Hughescaf76542012-06-28 16:08:22 -07001480void Dbg::GetThreads(JDWP::ObjectId thread_group_id, std::vector<JDWP::ObjectId>& thread_ids) {
Ian Rogers365c1022012-06-22 15:05:28 -07001481 class ThreadListVisitor {
1482 public:
jeffhao0dfbb7e2012-11-28 15:26:03 -08001483 ThreadListVisitor(const ScopedObjectAccessUnchecked& soa, Object* desired_thread_group,
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001484 std::vector<JDWP::ObjectId>& thread_ids)
Ian Rogersb726dcb2012-09-05 08:57:23 -07001485 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_)
jeffhao0dfbb7e2012-11-28 15:26:03 -08001486 : soa_(soa), desired_thread_group_(desired_thread_group), thread_ids_(thread_ids) {}
Ian Rogers365c1022012-06-22 15:05:28 -07001487
Elliott Hughesa2155262011-11-16 16:26:58 -08001488 static void Visit(Thread* t, void* arg) {
1489 reinterpret_cast<ThreadListVisitor*>(arg)->Visit(t);
1490 }
1491
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001492 // TODO: Enable annotalysis. We know lock is held in constructor, but abstraction confuses
1493 // annotalysis.
1494 void Visit(Thread* t) NO_THREAD_SAFETY_ANALYSIS {
Elliott Hughesa2155262011-11-16 16:26:58 -08001495 if (t == Dbg::GetDebugThread()) {
1496 // Skip the JDWP thread. Some debuggers get bent out of shape when they can't suspend and
1497 // query all threads, so it's easier if we just don't tell them about this thread.
1498 return;
1499 }
Ian Rogerscfaa4552012-11-26 21:00:08 -08001500 Object* peer = t->GetPeer();
jeffhao0dfbb7e2012-11-28 15:26:03 -08001501 if (IsInDesiredThreadGroup(peer)) {
Ian Rogers120f1c72012-09-28 17:17:10 -07001502 thread_ids_.push_back(gRegistry->Add(peer));
Elliott Hughesa2155262011-11-16 16:26:58 -08001503 }
1504 }
1505
Ian Rogers365c1022012-06-22 15:05:28 -07001506 private:
jeffhao0dfbb7e2012-11-28 15:26:03 -08001507 bool IsInDesiredThreadGroup(Object* peer)
1508 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
1509 // Do we want threads from all thread groups?
1510 if (desired_thread_group_ == NULL) {
1511 return true;
1512 }
1513 // peer might be NULL if the thread is still starting up.
1514 if (peer == NULL) {
1515 // We can't tell the debugger about this thread yet.
1516 // TODO: if we identified threads to the debugger by their Thread*
1517 // rather than their peer's Object*, we could fix this.
1518 // Doing so might help us report ZOMBIE threads too.
1519 return false;
1520 }
1521 Object* group = soa_.DecodeField(WellKnownClasses::java_lang_Thread_group)->GetObject(peer);
1522 return (group == desired_thread_group_);
1523 }
1524
Mathieu Chartierdbe6f462012-09-25 16:54:50 -07001525 const ScopedObjectAccessUnchecked& soa_;
jeffhao0dfbb7e2012-11-28 15:26:03 -08001526 Object* const desired_thread_group_;
Elliott Hughescaf76542012-06-28 16:08:22 -07001527 std::vector<JDWP::ObjectId>& thread_ids_;
Elliott Hughesa2155262011-11-16 16:26:58 -08001528 };
1529
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001530 ScopedObjectAccessUnchecked soa(Thread::Current());
Elliott Hughescaf76542012-06-28 16:08:22 -07001531 Object* thread_group = gRegistry->Get<Object*>(thread_group_id);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001532 ThreadListVisitor tlv(soa, thread_group, thread_ids);
Ian Rogers50b35e22012-10-04 10:09:15 -07001533 MutexLock mu(soa.Self(), *Locks::thread_list_lock_);
Elliott Hughesf8349362012-06-18 15:00:06 -07001534 Runtime::Current()->GetThreadList()->ForEach(ThreadListVisitor::Visit, &tlv);
Elliott Hughescaf76542012-06-28 16:08:22 -07001535}
Elliott Hughesa2155262011-11-16 16:26:58 -08001536
Elliott Hughescaf76542012-06-28 16:08:22 -07001537void Dbg::GetChildThreadGroups(JDWP::ObjectId thread_group_id, std::vector<JDWP::ObjectId>& child_thread_group_ids) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001538 ScopedObjectAccess soa(Thread::Current());
Elliott Hughescaf76542012-06-28 16:08:22 -07001539 Object* thread_group = gRegistry->Get<Object*>(thread_group_id);
1540
1541 // Get the ArrayList<ThreadGroup> "groups" out of this thread group...
1542 Field* groups_field = thread_group->GetClass()->FindInstanceField("groups", "Ljava/util/List;");
1543 Object* groups_array_list = groups_field->GetObject(thread_group);
1544
1545 // Get the array and size out of the ArrayList<ThreadGroup>...
1546 Field* array_field = groups_array_list->GetClass()->FindInstanceField("array", "[Ljava/lang/Object;");
1547 Field* size_field = groups_array_list->GetClass()->FindInstanceField("size", "I");
1548 ObjectArray<Object>* groups_array = array_field->GetObject(groups_array_list)->AsObjectArray<Object>();
1549 const int32_t size = size_field->GetInt(groups_array_list);
1550
1551 // Copy the first 'size' elements out of the array into the result.
1552 for (int32_t i = 0; i < size; ++i) {
1553 child_thread_group_ids.push_back(gRegistry->Add(groups_array->Get(i)));
Elliott Hughesa2155262011-11-16 16:26:58 -08001554 }
1555}
1556
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001557static int GetStackDepth(Thread* thread)
Ian Rogersb726dcb2012-09-05 08:57:23 -07001558 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Ian Rogers0399dde2012-06-06 17:09:28 -07001559 struct CountStackDepthVisitor : public StackVisitor {
1560 CountStackDepthVisitor(const ManagedStack* stack,
jeffhao725a9572012-11-13 18:20:12 -08001561 const std::vector<InstrumentationStackFrame>* instrumentation_stack)
1562 : StackVisitor(stack, instrumentation_stack, NULL), depth(0) {}
Ian Rogers0399dde2012-06-06 17:09:28 -07001563
1564 bool VisitFrame() {
1565 if (!GetMethod()->IsRuntimeMethod()) {
Elliott Hughesf8a2df72011-12-01 12:19:54 -08001566 ++depth;
1567 }
Elliott Hughes530fa002012-03-12 11:44:49 -07001568 return true;
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001569 }
1570 size_t depth;
1571 };
Elliott Hughes08fc03a2012-06-26 17:34:00 -07001572
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001573 if (kIsDebugBuild) {
Ian Rogers50b35e22012-10-04 10:09:15 -07001574 MutexLock mu(Thread::Current(), *Locks::thread_suspend_count_lock_);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001575 CHECK(thread->IsSuspended());
1576 }
jeffhao725a9572012-11-13 18:20:12 -08001577 CountStackDepthVisitor visitor(thread->GetManagedStack(), thread->GetInstrumentationStack());
Ian Rogers0399dde2012-06-06 17:09:28 -07001578 visitor.WalkStack();
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001579 return visitor.depth;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001580}
1581
Elliott Hughes86964332012-02-15 19:37:42 -08001582int Dbg::GetThreadFrameCount(JDWP::ObjectId threadId) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001583 ScopedObjectAccess soa(Thread::Current());
1584 return GetStackDepth(DecodeThread(soa, threadId));
Elliott Hughes86964332012-02-15 19:37:42 -08001585}
1586
Elliott Hughes6e9d22c2012-06-22 15:02:37 -07001587JDWP::JdwpError Dbg::GetThreadFrames(JDWP::ObjectId thread_id, size_t start_frame, size_t frame_count, JDWP::ExpandBuf* buf) {
Elliott Hughes6e9d22c2012-06-22 15:02:37 -07001588 class GetFrameVisitor : public StackVisitor {
1589 public:
jeffhao725a9572012-11-13 18:20:12 -08001590 GetFrameVisitor(const ManagedStack* stack, const std::vector<InstrumentationStackFrame>* instrumentation_stack,
Elliott Hughes6e9d22c2012-06-22 15:02:37 -07001591 size_t start_frame, size_t frame_count, JDWP::ExpandBuf* buf)
Ian Rogersb726dcb2012-09-05 08:57:23 -07001592 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_)
jeffhao725a9572012-11-13 18:20:12 -08001593 : StackVisitor(stack, instrumentation_stack, NULL), depth_(0),
Elliott Hughes6e9d22c2012-06-22 15:02:37 -07001594 start_frame_(start_frame), frame_count_(frame_count), buf_(buf) {
1595 expandBufAdd4BE(buf_, frame_count_);
Elliott Hughes03181a82011-11-17 17:22:21 -08001596 }
Ian Rogers0399dde2012-06-06 17:09:28 -07001597
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001598 // TODO: Enable annotalysis. We know lock is held in constructor, but abstraction confuses
1599 // annotalysis.
1600 virtual bool VisitFrame() NO_THREAD_SAFETY_ANALYSIS {
Ian Rogers0399dde2012-06-06 17:09:28 -07001601 if (GetMethod()->IsRuntimeMethod()) {
Elliott Hughes530fa002012-03-12 11:44:49 -07001602 return true; // The debugger can't do anything useful with a frame that has no Method*.
Elliott Hughes03181a82011-11-17 17:22:21 -08001603 }
Elliott Hughes6e9d22c2012-06-22 15:02:37 -07001604 if (depth_ >= start_frame_ + frame_count_) {
Elliott Hughes530fa002012-03-12 11:44:49 -07001605 return false;
Elliott Hughes03181a82011-11-17 17:22:21 -08001606 }
Elliott Hughes6e9d22c2012-06-22 15:02:37 -07001607 if (depth_ >= start_frame_) {
1608 JDWP::FrameId frame_id(GetFrameId());
1609 JDWP::JdwpLocation location;
1610 SetLocation(location, GetMethod(), GetDexPc());
Elliott Hughes7baf96f2012-06-22 16:33:50 -07001611 VLOG(jdwp) << StringPrintf(" Frame %3zd: id=%3lld ", depth_, frame_id) << location;
Elliott Hughes6e9d22c2012-06-22 15:02:37 -07001612 expandBufAdd8BE(buf_, frame_id);
1613 expandBufAddLocation(buf_, location);
1614 }
1615 ++depth_;
Elliott Hughes530fa002012-03-12 11:44:49 -07001616 return true;
Elliott Hughes03181a82011-11-17 17:22:21 -08001617 }
Elliott Hughes6e9d22c2012-06-22 15:02:37 -07001618
1619 private:
1620 size_t depth_;
1621 const size_t start_frame_;
1622 const size_t frame_count_;
1623 JDWP::ExpandBuf* buf_;
Elliott Hughes03181a82011-11-17 17:22:21 -08001624 };
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001625
1626 ScopedObjectAccessUnchecked soa(Thread::Current());
1627 Thread* thread = DecodeThread(soa, thread_id); // Caller already checked thread is suspended.
jeffhao725a9572012-11-13 18:20:12 -08001628 GetFrameVisitor visitor(thread->GetManagedStack(), thread->GetInstrumentationStack(), start_frame, frame_count, buf);
Ian Rogers0399dde2012-06-06 17:09:28 -07001629 visitor.WalkStack();
Elliott Hughes6e9d22c2012-06-22 15:02:37 -07001630 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001631}
1632
1633JDWP::ObjectId Dbg::GetThreadSelfId() {
Mathieu Chartierdbe6f462012-09-25 16:54:50 -07001634 ScopedObjectAccessUnchecked soa(Thread::Current());
Ian Rogerscfaa4552012-11-26 21:00:08 -08001635 return gRegistry->Add(soa.Self()->GetPeer());
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001636}
1637
Elliott Hughes475fc232011-10-25 15:00:35 -07001638void Dbg::SuspendVM() {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001639 Runtime::Current()->GetThreadList()->SuspendAllForDebugger();
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001640}
1641
1642void Dbg::ResumeVM() {
Elliott Hughesc61a2672012-06-21 14:52:29 -07001643 Runtime::Current()->GetThreadList()->UndoDebuggerSuspensions();
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001644}
1645
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001646JDWP::JdwpError Dbg::SuspendThread(JDWP::ObjectId threadId, bool request_suspension) {
1647
1648 bool timeout;
1649 ScopedLocalRef<jobject> peer(Thread::Current()->GetJniEnv(), NULL);
1650 {
1651 ScopedObjectAccess soa(Thread::Current());
1652 peer.reset(soa.AddLocalReference<jobject>(gRegistry->Get<Object*>(threadId)));
Elliott Hughes4e235312011-12-02 11:34:15 -08001653 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001654 if (peer.get() == NULL) {
1655 LOG(WARNING) << "No such thread for suspend: " << threadId;
1656 return JDWP::ERR_THREAD_NOT_ALIVE;
1657 }
1658 // Suspend thread to build stack trace.
1659 Thread* thread = Thread::SuspendForDebugger(peer.get(), request_suspension, &timeout);
1660 if (thread != NULL) {
1661 return JDWP::ERR_NONE;
1662 } else if (timeout) {
1663 return JDWP::ERR_INTERNAL;
1664 } else {
1665 return JDWP::ERR_THREAD_NOT_ALIVE;
1666 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001667}
1668
1669void Dbg::ResumeThread(JDWP::ObjectId threadId) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001670 ScopedObjectAccessUnchecked soa(Thread::Current());
Elliott Hughes4e235312011-12-02 11:34:15 -08001671 Object* peer = gRegistry->Get<Object*>(threadId);
Ian Rogers50b35e22012-10-04 10:09:15 -07001672 MutexLock mu(soa.Self(), *Locks::thread_list_lock_);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001673 Thread* thread = Thread::FromManagedThread(soa, peer);
Elliott Hughes4e235312011-12-02 11:34:15 -08001674 if (thread == NULL) {
1675 LOG(WARNING) << "No such thread for resume: " << peer;
1676 return;
1677 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001678 bool needs_resume;
1679 {
Ian Rogers50b35e22012-10-04 10:09:15 -07001680 MutexLock mu2(soa.Self(), *Locks::thread_suspend_count_lock_);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001681 needs_resume = thread->GetSuspendCount() > 0;
1682 }
1683 if (needs_resume) {
Elliott Hughes546b9862012-06-20 16:06:13 -07001684 Runtime::Current()->GetThreadList()->Resume(thread, true);
1685 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001686}
1687
1688void Dbg::SuspendSelf() {
Elliott Hughes475fc232011-10-25 15:00:35 -07001689 Runtime::Current()->GetThreadList()->SuspendSelfForDebugger();
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001690}
1691
Ian Rogers0399dde2012-06-06 17:09:28 -07001692struct GetThisVisitor : public StackVisitor {
jeffhao725a9572012-11-13 18:20:12 -08001693 GetThisVisitor(const ManagedStack* stack, const std::vector<InstrumentationStackFrame>* instrumentation_stack,
Elliott Hughes6e9d22c2012-06-22 15:02:37 -07001694 Context* context, JDWP::FrameId frameId)
Ian Rogersb726dcb2012-09-05 08:57:23 -07001695 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_)
jeffhao725a9572012-11-13 18:20:12 -08001696 : StackVisitor(stack, instrumentation_stack, context), this_object(NULL), frame_id(frameId) {}
Ian Rogers0399dde2012-06-06 17:09:28 -07001697
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001698 // TODO: Enable annotalysis. We know lock is held in constructor, but abstraction confuses
1699 // annotalysis.
1700 virtual bool VisitFrame() NO_THREAD_SAFETY_ANALYSIS {
Elliott Hughes6e9d22c2012-06-22 15:02:37 -07001701 if (frame_id != GetFrameId()) {
Ian Rogers0399dde2012-06-06 17:09:28 -07001702 return true; // continue
1703 }
Mathieu Chartier66f19252012-09-18 08:57:04 -07001704 AbstractMethod* m = GetMethod();
Ian Rogers0399dde2012-06-06 17:09:28 -07001705 if (m->IsNative() || m->IsStatic()) {
Elliott Hughes6e9d22c2012-06-22 15:02:37 -07001706 this_object = NULL;
Ian Rogers0399dde2012-06-06 17:09:28 -07001707 } else {
1708 uint16_t reg = DemangleSlot(0, m);
Ian Rogers2bcb4a42012-11-08 10:39:18 -08001709 this_object = reinterpret_cast<Object*>(GetVReg(m, reg, kReferenceVReg));
Ian Rogers0399dde2012-06-06 17:09:28 -07001710 }
1711 return false;
Elliott Hughes86b00102011-12-05 17:54:26 -08001712 }
Ian Rogers0399dde2012-06-06 17:09:28 -07001713
Elliott Hughes6e9d22c2012-06-22 15:02:37 -07001714 Object* this_object;
1715 JDWP::FrameId frame_id;
Ian Rogers0399dde2012-06-06 17:09:28 -07001716};
1717
Mathieu Chartier66f19252012-09-18 08:57:04 -07001718static Object* GetThis(Thread* self, AbstractMethod* m, size_t frame_id)
Ian Rogersb726dcb2012-09-05 08:57:23 -07001719 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Elliott Hughescaf76542012-06-28 16:08:22 -07001720 // TODO: should we return the 'this' we passed through to non-static native methods?
Ian Rogers0399dde2012-06-06 17:09:28 -07001721 if (m->IsNative() || m->IsStatic()) {
1722 return NULL;
1723 }
Elliott Hughescaf76542012-06-28 16:08:22 -07001724
Ian Rogers0399dde2012-06-06 17:09:28 -07001725 UniquePtr<Context> context(Context::Create());
jeffhao725a9572012-11-13 18:20:12 -08001726 GetThisVisitor visitor(self->GetManagedStack(), self->GetInstrumentationStack(), context.get(), frame_id);
Elliott Hughescaf76542012-06-28 16:08:22 -07001727 visitor.WalkStack();
1728 return visitor.this_object;
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08001729}
1730
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001731JDWP::JdwpError Dbg::GetThisObject(JDWP::ObjectId thread_id, JDWP::FrameId frame_id,
1732 JDWP::ObjectId* result) {
1733 ScopedObjectAccessUnchecked soa(Thread::Current());
1734 Thread* thread;
1735 {
Ian Rogers50b35e22012-10-04 10:09:15 -07001736 MutexLock mu(soa.Self(), *Locks::thread_list_lock_);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001737 thread = DecodeThread(soa, thread_id);
1738 if (thread == NULL) {
1739 return JDWP::ERR_INVALID_THREAD;
1740 }
Ian Rogers50b35e22012-10-04 10:09:15 -07001741 MutexLock mu2(soa.Self(), *Locks::thread_suspend_count_lock_);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001742 if (!thread->IsSuspended()) {
1743 return JDWP::ERR_THREAD_NOT_SUSPENDED;
1744 }
Elliott Hughes6e9d22c2012-06-22 15:02:37 -07001745 }
Elliott Hughescaf76542012-06-28 16:08:22 -07001746 UniquePtr<Context> context(Context::Create());
jeffhao725a9572012-11-13 18:20:12 -08001747 GetThisVisitor visitor(thread->GetManagedStack(), thread->GetInstrumentationStack(), context.get(), frame_id);
Ian Rogers0399dde2012-06-06 17:09:28 -07001748 visitor.WalkStack();
Elliott Hughes6e9d22c2012-06-22 15:02:37 -07001749 *result = gRegistry->Add(visitor.this_object);
1750 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001751}
1752
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001753void Dbg::GetLocalValue(JDWP::ObjectId threadId, JDWP::FrameId frameId, int slot, JDWP::JdwpTag tag,
1754 uint8_t* buf, size_t width) {
Ian Rogers0399dde2012-06-06 17:09:28 -07001755 struct GetLocalVisitor : public StackVisitor {
jeffhao725a9572012-11-13 18:20:12 -08001756 GetLocalVisitor(const ManagedStack* stack, const std::vector<InstrumentationStackFrame>* instrumentation_stack,
Ian Rogers0399dde2012-06-06 17:09:28 -07001757 Context* context, JDWP::FrameId frameId, int slot, JDWP::JdwpTag tag,
Ian Rogersca190662012-06-26 15:45:57 -07001758 uint8_t* buf, size_t width)
Ian Rogersb726dcb2012-09-05 08:57:23 -07001759 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_)
jeffhao725a9572012-11-13 18:20:12 -08001760 : StackVisitor(stack, instrumentation_stack, context), frame_id_(frameId), slot_(slot), tag_(tag),
Ian Rogersca190662012-06-26 15:45:57 -07001761 buf_(buf), width_(width) {}
1762
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001763 // TODO: Enable annotalysis. We know lock is held in constructor, but abstraction confuses
1764 // annotalysis.
1765 bool VisitFrame() NO_THREAD_SAFETY_ANALYSIS {
Ian Rogers0399dde2012-06-06 17:09:28 -07001766 if (GetFrameId() != frame_id_) {
1767 return true; // Not our frame, carry on.
Elliott Hughesdbb40792011-11-18 17:05:22 -08001768 }
Ian Rogers0399dde2012-06-06 17:09:28 -07001769 // TODO: check that the tag is compatible with the actual type of the slot!
Mathieu Chartier66f19252012-09-18 08:57:04 -07001770 AbstractMethod* m = GetMethod();
Ian Rogers0399dde2012-06-06 17:09:28 -07001771 uint16_t reg = DemangleSlot(slot_, m);
Elliott Hughesdbb40792011-11-18 17:05:22 -08001772
Ian Rogers0399dde2012-06-06 17:09:28 -07001773 switch (tag_) {
1774 case JDWP::JT_BOOLEAN:
1775 {
1776 CHECK_EQ(width_, 1U);
Ian Rogers2bcb4a42012-11-08 10:39:18 -08001777 uint32_t intVal = GetVReg(m, reg, kIntVReg);
Ian Rogers0399dde2012-06-06 17:09:28 -07001778 VLOG(jdwp) << "get boolean local " << reg << " = " << intVal;
1779 JDWP::Set1(buf_+1, intVal != 0);
1780 }
1781 break;
1782 case JDWP::JT_BYTE:
1783 {
1784 CHECK_EQ(width_, 1U);
Ian Rogers2bcb4a42012-11-08 10:39:18 -08001785 uint32_t intVal = GetVReg(m, reg, kIntVReg);
Ian Rogers0399dde2012-06-06 17:09:28 -07001786 VLOG(jdwp) << "get byte local " << reg << " = " << intVal;
1787 JDWP::Set1(buf_+1, intVal);
1788 }
1789 break;
1790 case JDWP::JT_SHORT:
1791 case JDWP::JT_CHAR:
1792 {
1793 CHECK_EQ(width_, 2U);
Ian Rogers2bcb4a42012-11-08 10:39:18 -08001794 uint32_t intVal = GetVReg(m, reg, kIntVReg);
Ian Rogers0399dde2012-06-06 17:09:28 -07001795 VLOG(jdwp) << "get short/char local " << reg << " = " << intVal;
1796 JDWP::Set2BE(buf_+1, intVal);
1797 }
1798 break;
1799 case JDWP::JT_INT:
Ian Rogers2bcb4a42012-11-08 10:39:18 -08001800 {
1801 CHECK_EQ(width_, 4U);
1802 uint32_t intVal = GetVReg(m, reg, kIntVReg);
1803 VLOG(jdwp) << "get int local " << reg << " = " << intVal;
1804 JDWP::Set4BE(buf_+1, intVal);
1805 }
1806 break;
Ian Rogers0399dde2012-06-06 17:09:28 -07001807 case JDWP::JT_FLOAT:
1808 {
1809 CHECK_EQ(width_, 4U);
Ian Rogers2bcb4a42012-11-08 10:39:18 -08001810 uint32_t intVal = GetVReg(m, reg, kFloatVReg);
Ian Rogers0399dde2012-06-06 17:09:28 -07001811 VLOG(jdwp) << "get int/float local " << reg << " = " << intVal;
1812 JDWP::Set4BE(buf_+1, intVal);
1813 }
1814 break;
1815 case JDWP::JT_ARRAY:
1816 {
1817 CHECK_EQ(width_, sizeof(JDWP::ObjectId));
Ian Rogers2bcb4a42012-11-08 10:39:18 -08001818 Object* o = reinterpret_cast<Object*>(GetVReg(m, reg, kReferenceVReg));
Ian Rogers0399dde2012-06-06 17:09:28 -07001819 VLOG(jdwp) << "get array local " << reg << " = " << o;
1820 if (!Runtime::Current()->GetHeap()->IsHeapAddress(o)) {
1821 LOG(FATAL) << "Register " << reg << " expected to hold array: " << o;
1822 }
1823 JDWP::SetObjectId(buf_+1, gRegistry->Add(o));
1824 }
1825 break;
1826 case JDWP::JT_CLASS_LOADER:
1827 case JDWP::JT_CLASS_OBJECT:
1828 case JDWP::JT_OBJECT:
1829 case JDWP::JT_STRING:
1830 case JDWP::JT_THREAD:
1831 case JDWP::JT_THREAD_GROUP:
1832 {
1833 CHECK_EQ(width_, sizeof(JDWP::ObjectId));
Ian Rogers2bcb4a42012-11-08 10:39:18 -08001834 Object* o = reinterpret_cast<Object*>(GetVReg(m, reg, kReferenceVReg));
Ian Rogers0399dde2012-06-06 17:09:28 -07001835 VLOG(jdwp) << "get object local " << reg << " = " << o;
1836 if (!Runtime::Current()->GetHeap()->IsHeapAddress(o)) {
1837 LOG(FATAL) << "Register " << reg << " expected to hold object: " << o;
1838 }
1839 tag_ = TagFromObject(o);
1840 JDWP::SetObjectId(buf_+1, gRegistry->Add(o));
1841 }
1842 break;
1843 case JDWP::JT_DOUBLE:
Ian Rogers2bcb4a42012-11-08 10:39:18 -08001844 {
1845 CHECK_EQ(width_, 8U);
1846 uint32_t lo = GetVReg(m, reg, kDoubleLoVReg);
1847 uint64_t hi = GetVReg(m, reg + 1, kDoubleHiVReg);
1848 uint64_t longVal = (hi << 32) | lo;
1849 VLOG(jdwp) << "get double/long local " << hi << ":" << lo << " = " << longVal;
1850 JDWP::Set8BE(buf_+1, longVal);
1851 }
1852 break;
Ian Rogers0399dde2012-06-06 17:09:28 -07001853 case JDWP::JT_LONG:
1854 {
1855 CHECK_EQ(width_, 8U);
Ian Rogers2bcb4a42012-11-08 10:39:18 -08001856 uint32_t lo = GetVReg(m, reg, kLongLoVReg);
1857 uint64_t hi = GetVReg(m, reg + 1, kLongHiVReg);
Ian Rogers0399dde2012-06-06 17:09:28 -07001858 uint64_t longVal = (hi << 32) | lo;
1859 VLOG(jdwp) << "get double/long local " << hi << ":" << lo << " = " << longVal;
1860 JDWP::Set8BE(buf_+1, longVal);
1861 }
1862 break;
1863 default:
1864 LOG(FATAL) << "Unknown tag " << tag_;
1865 break;
1866 }
1867
1868 // Prepend tag, which may have been updated.
1869 JDWP::Set1(buf_, tag_);
1870 return false;
1871 }
1872
1873 const JDWP::FrameId frame_id_;
1874 const int slot_;
1875 JDWP::JdwpTag tag_;
1876 uint8_t* const buf_;
1877 const size_t width_;
1878 };
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001879
1880 ScopedObjectAccessUnchecked soa(Thread::Current());
1881 Thread* thread = DecodeThread(soa, threadId);
Ian Rogers0399dde2012-06-06 17:09:28 -07001882 UniquePtr<Context> context(Context::Create());
jeffhao725a9572012-11-13 18:20:12 -08001883 GetLocalVisitor visitor(thread->GetManagedStack(), thread->GetInstrumentationStack(), context.get(),
Ian Rogers0399dde2012-06-06 17:09:28 -07001884 frameId, slot, tag, buf, width);
1885 visitor.WalkStack();
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001886}
1887
Ian Rogers0399dde2012-06-06 17:09:28 -07001888void Dbg::SetLocalValue(JDWP::ObjectId threadId, JDWP::FrameId frameId, int slot, JDWP::JdwpTag tag,
1889 uint64_t value, size_t width) {
1890 struct SetLocalVisitor : public StackVisitor {
jeffhao725a9572012-11-13 18:20:12 -08001891 SetLocalVisitor(const ManagedStack* stack, const std::vector<InstrumentationStackFrame>* instrumentation_stack, Context* context,
Ian Rogers0399dde2012-06-06 17:09:28 -07001892 JDWP::FrameId frame_id, int slot, JDWP::JdwpTag tag, uint64_t value,
Ian Rogersca190662012-06-26 15:45:57 -07001893 size_t width)
Ian Rogersb726dcb2012-09-05 08:57:23 -07001894 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_)
jeffhao725a9572012-11-13 18:20:12 -08001895 : StackVisitor(stack, instrumentation_stack, context),
Elliott Hughes08fc03a2012-06-26 17:34:00 -07001896 frame_id_(frame_id), slot_(slot), tag_(tag), value_(value), width_(width) {}
Ian Rogersca190662012-06-26 15:45:57 -07001897
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001898 // TODO: Enable annotalysis. We know lock is held in constructor, but abstraction confuses
1899 // annotalysis.
1900 bool VisitFrame() NO_THREAD_SAFETY_ANALYSIS {
Ian Rogers0399dde2012-06-06 17:09:28 -07001901 if (GetFrameId() != frame_id_) {
1902 return true; // Not our frame, carry on.
1903 }
1904 // TODO: check that the tag is compatible with the actual type of the slot!
Mathieu Chartier66f19252012-09-18 08:57:04 -07001905 AbstractMethod* m = GetMethod();
Ian Rogers0399dde2012-06-06 17:09:28 -07001906 uint16_t reg = DemangleSlot(slot_, m);
1907
1908 switch (tag_) {
1909 case JDWP::JT_BOOLEAN:
1910 case JDWP::JT_BYTE:
1911 CHECK_EQ(width_, 1U);
Ian Rogers2bcb4a42012-11-08 10:39:18 -08001912 SetVReg(m, reg, static_cast<uint32_t>(value_), kIntVReg);
Ian Rogers0399dde2012-06-06 17:09:28 -07001913 break;
1914 case JDWP::JT_SHORT:
1915 case JDWP::JT_CHAR:
1916 CHECK_EQ(width_, 2U);
Ian Rogers2bcb4a42012-11-08 10:39:18 -08001917 SetVReg(m, reg, static_cast<uint32_t>(value_), kIntVReg);
Ian Rogers0399dde2012-06-06 17:09:28 -07001918 break;
1919 case JDWP::JT_INT:
Ian Rogers2bcb4a42012-11-08 10:39:18 -08001920 CHECK_EQ(width_, 4U);
1921 SetVReg(m, reg, static_cast<uint32_t>(value_), kIntVReg);
1922 break;
Ian Rogers0399dde2012-06-06 17:09:28 -07001923 case JDWP::JT_FLOAT:
1924 CHECK_EQ(width_, 4U);
Ian Rogers2bcb4a42012-11-08 10:39:18 -08001925 SetVReg(m, reg, static_cast<uint32_t>(value_), kFloatVReg);
Ian Rogers0399dde2012-06-06 17:09:28 -07001926 break;
1927 case JDWP::JT_ARRAY:
1928 case JDWP::JT_OBJECT:
1929 case JDWP::JT_STRING:
1930 {
1931 CHECK_EQ(width_, sizeof(JDWP::ObjectId));
1932 Object* o = gRegistry->Get<Object*>(static_cast<JDWP::ObjectId>(value_));
1933 if (o == kInvalidObject) {
1934 UNIMPLEMENTED(FATAL) << "return an error code when given an invalid object to store";
1935 }
Ian Rogers2bcb4a42012-11-08 10:39:18 -08001936 SetVReg(m, reg, static_cast<uint32_t>(reinterpret_cast<uintptr_t>(o)), kReferenceVReg);
Ian Rogers0399dde2012-06-06 17:09:28 -07001937 }
1938 break;
1939 case JDWP::JT_DOUBLE:
Ian Rogers2bcb4a42012-11-08 10:39:18 -08001940 CHECK_EQ(width_, 8U);
1941 SetVReg(m, reg, static_cast<uint32_t>(value_), kDoubleLoVReg);
1942 SetVReg(m, reg + 1, static_cast<uint32_t>(value_ >> 32), kDoubleHiVReg);
1943 break;
Ian Rogers0399dde2012-06-06 17:09:28 -07001944 case JDWP::JT_LONG:
1945 CHECK_EQ(width_, 8U);
Ian Rogers2bcb4a42012-11-08 10:39:18 -08001946 SetVReg(m, reg, static_cast<uint32_t>(value_), kLongLoVReg);
1947 SetVReg(m, reg + 1, static_cast<uint32_t>(value_ >> 32), kLongHiVReg);
Ian Rogers0399dde2012-06-06 17:09:28 -07001948 break;
1949 default:
1950 LOG(FATAL) << "Unknown tag " << tag_;
1951 break;
1952 }
1953 return false;
1954 }
1955
1956 const JDWP::FrameId frame_id_;
1957 const int slot_;
1958 const JDWP::JdwpTag tag_;
1959 const uint64_t value_;
1960 const size_t width_;
1961 };
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001962
1963 ScopedObjectAccessUnchecked soa(Thread::Current());
1964 Thread* thread = DecodeThread(soa, threadId);
Elliott Hughes08fc03a2012-06-26 17:34:00 -07001965 UniquePtr<Context> context(Context::Create());
jeffhao725a9572012-11-13 18:20:12 -08001966 SetLocalVisitor visitor(thread->GetManagedStack(), thread->GetInstrumentationStack(), context.get(),
Elliott Hughes08fc03a2012-06-26 17:34:00 -07001967 frameId, slot, tag, value, width);
Ian Rogers0399dde2012-06-06 17:09:28 -07001968 visitor.WalkStack();
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001969}
1970
Mathieu Chartier66f19252012-09-18 08:57:04 -07001971void Dbg::PostLocationEvent(const AbstractMethod* m, int dex_pc, Object* this_object, int event_flags) {
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08001972 Class* c = m->GetDeclaringClass();
1973
1974 JDWP::JdwpLocation location;
Elliott Hughes74847412012-06-20 18:10:21 -07001975 location.type_tag = c->IsInterface() ? JDWP::TT_INTERFACE : JDWP::TT_CLASS;
1976 location.class_id = gRegistry->Add(c);
1977 location.method_id = ToMethodId(m);
Elliott Hughes972a47b2012-02-21 18:16:06 -08001978 location.dex_pc = m->IsNative() ? -1 : dex_pc;
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08001979
1980 // Note we use "NoReg" so we don't keep track of references that are
1981 // never actually sent to the debugger. 'this_id' is only used to
1982 // compare against registered events...
1983 JDWP::ObjectId this_id = static_cast<JDWP::ObjectId>(reinterpret_cast<uintptr_t>(this_object));
1984 if (gJdwpState->PostLocationEvent(&location, this_id, event_flags)) {
1985 // ...unless there's a registered event, in which case we
1986 // need to really track the class and 'this'.
1987 gRegistry->Add(c);
1988 gRegistry->Add(this_object);
1989 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001990}
1991
Elliott Hughescaf76542012-06-28 16:08:22 -07001992void Dbg::PostException(Thread* thread,
Mathieu Chartier66f19252012-09-18 08:57:04 -07001993 JDWP::FrameId throw_frame_id, AbstractMethod* throw_method, uint32_t throw_dex_pc,
1994 AbstractMethod* catch_method, uint32_t catch_dex_pc, Throwable* exception) {
Elliott Hughesc0f09332012-03-26 13:27:06 -07001995 if (!IsDebuggerActive()) {
Ian Rogers0ad5bb82011-12-07 10:16:32 -08001996 return;
1997 }
Elliott Hughes4740cdf2011-12-07 14:07:12 -08001998
Elliott Hughesd07986f2011-12-06 18:27:45 -08001999 JDWP::JdwpLocation throw_location;
Elliott Hughescaf76542012-06-28 16:08:22 -07002000 SetLocation(throw_location, throw_method, throw_dex_pc);
Elliott Hughesd07986f2011-12-06 18:27:45 -08002001 JDWP::JdwpLocation catch_location;
Elliott Hughescaf76542012-06-28 16:08:22 -07002002 SetLocation(catch_location, catch_method, catch_dex_pc);
Elliott Hughesd07986f2011-12-06 18:27:45 -08002003
2004 // We need 'this' for InstanceOnly filters.
Elliott Hughescaf76542012-06-28 16:08:22 -07002005 UniquePtr<Context> context(Context::Create());
jeffhao725a9572012-11-13 18:20:12 -08002006 GetThisVisitor visitor(thread->GetManagedStack(), thread->GetInstrumentationStack(), context.get(), throw_frame_id);
Elliott Hughescaf76542012-06-28 16:08:22 -07002007 visitor.WalkStack();
2008 JDWP::ObjectId this_id = gRegistry->Add(visitor.this_object);
Elliott Hughesd07986f2011-12-06 18:27:45 -08002009
2010 /*
2011 * Hand the event to the JDWP exception handler. Note we're using the
2012 * "NoReg" objectID on the exception, which is not strictly correct --
2013 * the exception object WILL be passed up to the debugger if the
2014 * debugger is interested in the event. We do this because the current
2015 * implementation of the debugger object registry never throws anything
2016 * away, and some people were experiencing a fatal build up of exception
2017 * objects when dealing with certain libraries.
2018 */
2019 JDWP::ObjectId exception_id = static_cast<JDWP::ObjectId>(reinterpret_cast<uintptr_t>(exception));
2020 JDWP::RefTypeId exception_class_id = gRegistry->Add(exception->GetClass());
2021
2022 gJdwpState->PostException(&throw_location, exception_id, exception_class_id, &catch_location, this_id);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002023}
2024
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002025void Dbg::PostClassPrepare(Class* c) {
Elliott Hughesc0f09332012-03-26 13:27:06 -07002026 if (!IsDebuggerActive()) {
Elliott Hughes4740cdf2011-12-07 14:07:12 -08002027 return;
2028 }
2029
Elliott Hughes3d30d9b2011-12-07 17:35:48 -08002030 // OLD-TODO - we currently always send both "verified" and "prepared" since
Elliott Hughes4740cdf2011-12-07 14:07:12 -08002031 // debuggers seem to like that. There might be some advantage to honesty,
2032 // since the class may not yet be verified.
2033 int state = JDWP::CS_VERIFIED | JDWP::CS_PREPARED;
2034 JDWP::JdwpTypeTag tag = c->IsInterface() ? JDWP::TT_INTERFACE : JDWP::TT_CLASS;
2035 gJdwpState->PostClassPrepare(tag, gRegistry->Add(c), ClassHelper(c).GetDescriptor(), state);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002036}
2037
Elliott Hughescaf76542012-06-28 16:08:22 -07002038void Dbg::UpdateDebugger(int32_t dex_pc, Thread* self) {
Elliott Hughesc0f09332012-03-26 13:27:06 -07002039 if (!IsDebuggerActive() || dex_pc == -2 /* fake method exit */) {
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08002040 return;
2041 }
2042
Elliott Hughescaf76542012-06-28 16:08:22 -07002043 size_t frame_id;
Mathieu Chartier66f19252012-09-18 08:57:04 -07002044 AbstractMethod* m = self->GetCurrentMethod(NULL, &frame_id);
Elliott Hughescaf76542012-06-28 16:08:22 -07002045 //LOG(INFO) << "UpdateDebugger " << PrettyMethod(m) << "@" << dex_pc << " frame " << frame_id;
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08002046
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08002047 if (dex_pc == -1) {
Elliott Hughes2aa2e392012-02-17 17:15:43 -08002048 // We use a pc of -1 to represent method entry, since we might branch back to pc 0 later.
2049 // This means that for this special notification, there can't be anything else interesting
2050 // going on, so we're done already.
Elliott Hughescaf76542012-06-28 16:08:22 -07002051 Dbg::PostLocationEvent(m, 0, GetThis(self, m, frame_id), kMethodEntry);
Elliott Hughes2aa2e392012-02-17 17:15:43 -08002052 return;
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08002053 }
2054
Elliott Hughes2aa2e392012-02-17 17:15:43 -08002055 int event_flags = 0;
2056
Elliott Hughes86964332012-02-15 19:37:42 -08002057 if (IsBreakpoint(m, dex_pc)) {
2058 event_flags |= kBreakpoint;
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08002059 }
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08002060
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08002061 // If the debugger is single-stepping one of our threads, check to
2062 // see if we're that thread and we've reached a step point.
Ian Rogers50b35e22012-10-04 10:09:15 -07002063 MutexLock mu(Thread::Current(), gBreakpointsLock);
Elliott Hughes86964332012-02-15 19:37:42 -08002064 if (gSingleStepControl.is_active && gSingleStepControl.thread == self) {
2065 CHECK(!m->IsNative());
2066 if (gSingleStepControl.step_depth == JDWP::SD_INTO) {
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08002067 // Step into method calls. We break when the line number
2068 // or method pointer changes. If we're in SS_MIN mode, we
2069 // always stop.
Elliott Hughes86964332012-02-15 19:37:42 -08002070 if (gSingleStepControl.method != m) {
2071 event_flags |= kSingleStep;
2072 VLOG(jdwp) << "SS new method";
2073 } else if (gSingleStepControl.step_size == JDWP::SS_MIN) {
2074 event_flags |= kSingleStep;
2075 VLOG(jdwp) << "SS new instruction";
Elliott Hughes2435a572012-02-17 16:07:41 -08002076 } else if (gSingleStepControl.dex_pcs.find(dex_pc) == gSingleStepControl.dex_pcs.end()) {
2077 event_flags |= kSingleStep;
2078 VLOG(jdwp) << "SS new line";
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08002079 }
Elliott Hughes86964332012-02-15 19:37:42 -08002080 } else if (gSingleStepControl.step_depth == JDWP::SD_OVER) {
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08002081 // Step over method calls. We break when the line number is
2082 // different and the frame depth is <= the original frame
2083 // depth. (We can't just compare on the method, because we
2084 // might get unrolled past it by an exception, and it's tricky
2085 // to identify recursion.)
Elliott Hughes86964332012-02-15 19:37:42 -08002086
2087 // TODO: can we just use the value of 'sp'?
2088 int stack_depth = GetStackDepth(self);
2089
2090 if (stack_depth < gSingleStepControl.stack_depth) {
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08002091 // popped up one or more frames, always trigger
Elliott Hughes86964332012-02-15 19:37:42 -08002092 event_flags |= kSingleStep;
2093 VLOG(jdwp) << "SS method pop";
2094 } else if (stack_depth == gSingleStepControl.stack_depth) {
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08002095 // same depth, see if we moved
Elliott Hughes86964332012-02-15 19:37:42 -08002096 if (gSingleStepControl.step_size == JDWP::SS_MIN) {
2097 event_flags |= kSingleStep;
2098 VLOG(jdwp) << "SS new instruction";
Elliott Hughes2435a572012-02-17 16:07:41 -08002099 } else if (gSingleStepControl.dex_pcs.find(dex_pc) == gSingleStepControl.dex_pcs.end()) {
2100 event_flags |= kSingleStep;
2101 VLOG(jdwp) << "SS new line";
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08002102 }
2103 }
2104 } else {
Elliott Hughes86964332012-02-15 19:37:42 -08002105 CHECK_EQ(gSingleStepControl.step_depth, JDWP::SD_OUT);
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08002106 // Return from the current method. We break when the frame
2107 // depth pops up.
2108
2109 // This differs from the "method exit" break in that it stops
2110 // with the PC at the next instruction in the returned-to
2111 // function, rather than the end of the returning function.
Elliott Hughes86964332012-02-15 19:37:42 -08002112
2113 // TODO: can we just use the value of 'sp'?
2114 int stack_depth = GetStackDepth(self);
2115 if (stack_depth < gSingleStepControl.stack_depth) {
2116 event_flags |= kSingleStep;
2117 VLOG(jdwp) << "SS method pop";
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08002118 }
2119 }
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08002120 }
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08002121
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08002122 // Check to see if this is a "return" instruction. JDWP says we should
2123 // send the event *after* the code has been executed, but it also says
2124 // the location we provide is the last instruction. Since the "return"
2125 // instruction has no interesting side effects, we should be safe.
2126 // (We can't just move this down to the returnFromMethod label because
2127 // we potentially need to combine it with other events.)
2128 // We're also not supposed to generate a method exit event if the method
2129 // terminates "with a thrown exception".
Elliott Hughes86964332012-02-15 19:37:42 -08002130 if (dex_pc >= 0) {
2131 const DexFile::CodeItem* code_item = MethodHelper(m).GetCodeItem();
Elliott Hughescaf76542012-06-28 16:08:22 -07002132 CHECK(code_item != NULL) << PrettyMethod(m) << " @" << dex_pc;
Elliott Hughes86964332012-02-15 19:37:42 -08002133 CHECK_LT(dex_pc, static_cast<int32_t>(code_item->insns_size_in_code_units_));
2134 if (Instruction::At(&code_item->insns_[dex_pc])->IsReturn()) {
2135 event_flags |= kMethodExit;
2136 }
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08002137 }
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08002138
2139 // If there's something interesting going on, see if it matches one
2140 // of the debugger filters.
2141 if (event_flags != 0) {
Elliott Hughescaf76542012-06-28 16:08:22 -07002142 Dbg::PostLocationEvent(m, dex_pc, GetThis(self, m, frame_id), event_flags);
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08002143 }
2144}
2145
Elliott Hughes86964332012-02-15 19:37:42 -08002146void Dbg::WatchLocation(const JDWP::JdwpLocation* location) {
Ian Rogers50b35e22012-10-04 10:09:15 -07002147 MutexLock mu(Thread::Current(), gBreakpointsLock);
Mathieu Chartier66f19252012-09-18 08:57:04 -07002148 AbstractMethod* m = FromMethodId(location->method_id);
Elliott Hughes972a47b2012-02-21 18:16:06 -08002149 gBreakpoints.push_back(Breakpoint(m, location->dex_pc));
Elliott Hughes86964332012-02-15 19:37:42 -08002150 VLOG(jdwp) << "Set breakpoint #" << (gBreakpoints.size() - 1) << ": " << gBreakpoints[gBreakpoints.size() - 1];
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002151}
2152
Elliott Hughes86964332012-02-15 19:37:42 -08002153void Dbg::UnwatchLocation(const JDWP::JdwpLocation* location) {
Ian Rogers50b35e22012-10-04 10:09:15 -07002154 MutexLock mu(Thread::Current(), gBreakpointsLock);
Mathieu Chartier66f19252012-09-18 08:57:04 -07002155 AbstractMethod* m = FromMethodId(location->method_id);
Elliott Hughes86964332012-02-15 19:37:42 -08002156 for (size_t i = 0; i < gBreakpoints.size(); ++i) {
Elliott Hughes972a47b2012-02-21 18:16:06 -08002157 if (gBreakpoints[i].method == m && gBreakpoints[i].dex_pc == location->dex_pc) {
Elliott Hughes86964332012-02-15 19:37:42 -08002158 VLOG(jdwp) << "Removed breakpoint #" << i << ": " << gBreakpoints[i];
2159 gBreakpoints.erase(gBreakpoints.begin() + i);
2160 return;
2161 }
2162 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002163}
2164
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002165JDWP::JdwpError Dbg::ConfigureStep(JDWP::ObjectId threadId, JDWP::JdwpStepSize step_size,
2166 JDWP::JdwpStepDepth step_depth) {
2167 ScopedObjectAccessUnchecked soa(Thread::Current());
2168 Thread* thread = DecodeThread(soa, threadId);
Elliott Hughes2435a572012-02-17 16:07:41 -08002169 if (thread == NULL) {
2170 return JDWP::ERR_INVALID_THREAD;
2171 }
Elliott Hughes86964332012-02-15 19:37:42 -08002172
Ian Rogers50b35e22012-10-04 10:09:15 -07002173 MutexLock mu(soa.Self(), gBreakpointsLock);
Elliott Hughes86964332012-02-15 19:37:42 -08002174 // TODO: there's no theoretical reason why we couldn't support single-stepping
2175 // of multiple threads at once, but we never did so historically.
2176 if (gSingleStepControl.thread != NULL && thread != gSingleStepControl.thread) {
2177 LOG(WARNING) << "single-step already active for " << *gSingleStepControl.thread
2178 << "; switching to " << *thread;
2179 }
2180
Elliott Hughes2435a572012-02-17 16:07:41 -08002181 //
2182 // Work out what Method* we're in, the current line number, and how deep the stack currently
2183 // is for step-out.
2184 //
2185
Ian Rogers0399dde2012-06-06 17:09:28 -07002186 struct SingleStepStackVisitor : public StackVisitor {
2187 SingleStepStackVisitor(const ManagedStack* stack,
jeffhao725a9572012-11-13 18:20:12 -08002188 const std::vector<InstrumentationStackFrame>* instrumentation_stack)
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002189 EXCLUSIVE_LOCKS_REQUIRED(gBreakpointsLock)
Ian Rogersb726dcb2012-09-05 08:57:23 -07002190 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_)
jeffhao725a9572012-11-13 18:20:12 -08002191 : StackVisitor(stack, instrumentation_stack, NULL) {
Ian Rogers50b35e22012-10-04 10:09:15 -07002192 gBreakpointsLock.AssertHeld(Thread::Current());
Elliott Hughes86964332012-02-15 19:37:42 -08002193 gSingleStepControl.method = NULL;
2194 gSingleStepControl.stack_depth = 0;
2195 }
Ian Rogersca190662012-06-26 15:45:57 -07002196
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002197 // TODO: Enable annotalysis. We know lock is held in constructor, but abstraction confuses
2198 // annotalysis.
2199 bool VisitFrame() NO_THREAD_SAFETY_ANALYSIS {
Ian Rogers50b35e22012-10-04 10:09:15 -07002200 gBreakpointsLock.AssertHeld(Thread::Current());
Mathieu Chartier66f19252012-09-18 08:57:04 -07002201 const AbstractMethod* m = GetMethod();
Ian Rogers0399dde2012-06-06 17:09:28 -07002202 if (!m->IsRuntimeMethod()) {
Elliott Hughes86964332012-02-15 19:37:42 -08002203 ++gSingleStepControl.stack_depth;
2204 if (gSingleStepControl.method == NULL) {
Elliott Hughes2435a572012-02-17 16:07:41 -08002205 const DexCache* dex_cache = m->GetDeclaringClass()->GetDexCache();
2206 gSingleStepControl.method = m;
2207 gSingleStepControl.line_number = -1;
2208 if (dex_cache != NULL) {
Ian Rogers4445a7e2012-10-05 17:19:13 -07002209 const DexFile& dex_file = *dex_cache->GetDexFile();
Ian Rogers0399dde2012-06-06 17:09:28 -07002210 gSingleStepControl.line_number = dex_file.GetLineNumFromPC(m, GetDexPc());
Elliott Hughes2435a572012-02-17 16:07:41 -08002211 }
Elliott Hughes86964332012-02-15 19:37:42 -08002212 }
2213 }
Elliott Hughes530fa002012-03-12 11:44:49 -07002214 return true;
Elliott Hughes86964332012-02-15 19:37:42 -08002215 }
2216 };
jeffhao725a9572012-11-13 18:20:12 -08002217 SingleStepStackVisitor visitor(thread->GetManagedStack(), thread->GetInstrumentationStack());
Ian Rogers0399dde2012-06-06 17:09:28 -07002218 visitor.WalkStack();
Elliott Hughes86964332012-02-15 19:37:42 -08002219
Elliott Hughes2435a572012-02-17 16:07:41 -08002220 //
2221 // Find the dex_pc values that correspond to the current line, for line-based single-stepping.
2222 //
2223
2224 struct DebugCallbackContext {
2225 DebugCallbackContext() {
2226 last_pc_valid = false;
2227 last_pc = 0;
Elliott Hughes2435a572012-02-17 16:07:41 -08002228 }
2229
2230 static bool Callback(void* raw_context, uint32_t address, uint32_t line_number) {
Ian Rogers50b35e22012-10-04 10:09:15 -07002231 MutexLock mu(Thread::Current(), gBreakpointsLock); // Keep GCC happy.
Elliott Hughes2435a572012-02-17 16:07:41 -08002232 DebugCallbackContext* context = reinterpret_cast<DebugCallbackContext*>(raw_context);
2233 if (static_cast<int32_t>(line_number) == gSingleStepControl.line_number) {
2234 if (!context->last_pc_valid) {
2235 // Everything from this address until the next line change is ours.
2236 context->last_pc = address;
2237 context->last_pc_valid = true;
2238 }
2239 // Otherwise, if we're already in a valid range for this line,
2240 // just keep going (shouldn't really happen)...
2241 } else if (context->last_pc_valid) { // and the line number is new
2242 // Add everything from the last entry up until here to the set
2243 for (uint32_t dex_pc = context->last_pc; dex_pc < address; ++dex_pc) {
2244 gSingleStepControl.dex_pcs.insert(dex_pc);
2245 }
2246 context->last_pc_valid = false;
2247 }
2248 return false; // There may be multiple entries for any given line.
2249 }
2250
2251 ~DebugCallbackContext() {
Ian Rogers50b35e22012-10-04 10:09:15 -07002252 MutexLock mu(Thread::Current(), gBreakpointsLock); // Keep GCC happy.
Elliott Hughes2435a572012-02-17 16:07:41 -08002253 // If the line number was the last in the position table...
2254 if (last_pc_valid) {
2255 size_t end = MethodHelper(gSingleStepControl.method).GetCodeItem()->insns_size_in_code_units_;
2256 for (uint32_t dex_pc = last_pc; dex_pc < end; ++dex_pc) {
2257 gSingleStepControl.dex_pcs.insert(dex_pc);
2258 }
2259 }
2260 }
2261
2262 bool last_pc_valid;
2263 uint32_t last_pc;
2264 };
Elliott Hughes3e2e1a22012-02-21 11:33:41 -08002265 gSingleStepControl.dex_pcs.clear();
Mathieu Chartier66f19252012-09-18 08:57:04 -07002266 const AbstractMethod* m = gSingleStepControl.method;
Elliott Hughes3e2e1a22012-02-21 11:33:41 -08002267 if (m->IsNative()) {
2268 gSingleStepControl.line_number = -1;
2269 } else {
2270 DebugCallbackContext context;
2271 MethodHelper mh(m);
2272 mh.GetDexFile().DecodeDebugInfo(mh.GetCodeItem(), m->IsStatic(), m->GetDexMethodIndex(),
2273 DebugCallbackContext::Callback, NULL, &context);
2274 }
Elliott Hughes2435a572012-02-17 16:07:41 -08002275
2276 //
2277 // Everything else...
2278 //
2279
Elliott Hughes86964332012-02-15 19:37:42 -08002280 gSingleStepControl.thread = thread;
2281 gSingleStepControl.step_size = step_size;
2282 gSingleStepControl.step_depth = step_depth;
2283 gSingleStepControl.is_active = true;
2284
Elliott Hughes2435a572012-02-17 16:07:41 -08002285 if (VLOG_IS_ON(jdwp)) {
2286 VLOG(jdwp) << "Single-step thread: " << *gSingleStepControl.thread;
2287 VLOG(jdwp) << "Single-step step size: " << gSingleStepControl.step_size;
2288 VLOG(jdwp) << "Single-step step depth: " << gSingleStepControl.step_depth;
2289 VLOG(jdwp) << "Single-step current method: " << PrettyMethod(gSingleStepControl.method);
2290 VLOG(jdwp) << "Single-step current line: " << gSingleStepControl.line_number;
2291 VLOG(jdwp) << "Single-step current stack depth: " << gSingleStepControl.stack_depth;
2292 VLOG(jdwp) << "Single-step dex_pc values:";
2293 for (std::set<uint32_t>::iterator it = gSingleStepControl.dex_pcs.begin() ; it != gSingleStepControl.dex_pcs.end(); ++it) {
Elliott Hughes229feb72012-02-23 13:33:29 -08002294 VLOG(jdwp) << StringPrintf(" %#x", *it);
Elliott Hughes2435a572012-02-17 16:07:41 -08002295 }
2296 }
2297
2298 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002299}
2300
Elliott Hughes1bac54f2012-03-16 12:48:31 -07002301void Dbg::UnconfigureStep(JDWP::ObjectId /*threadId*/) {
Ian Rogers50b35e22012-10-04 10:09:15 -07002302 MutexLock mu(Thread::Current(), gBreakpointsLock);
Elliott Hughesf8349362012-06-18 15:00:06 -07002303
Elliott Hughes86964332012-02-15 19:37:42 -08002304 gSingleStepControl.is_active = false;
2305 gSingleStepControl.thread = NULL;
Elliott Hughes2435a572012-02-17 16:07:41 -08002306 gSingleStepControl.dex_pcs.clear();
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002307}
2308
Elliott Hughes45651fd2012-02-21 15:48:20 -08002309static char JdwpTagToShortyChar(JDWP::JdwpTag tag) {
2310 switch (tag) {
2311 default:
2312 LOG(FATAL) << "unknown JDWP tag: " << PrintableChar(tag);
2313
2314 // Primitives.
2315 case JDWP::JT_BYTE: return 'B';
2316 case JDWP::JT_CHAR: return 'C';
2317 case JDWP::JT_FLOAT: return 'F';
2318 case JDWP::JT_DOUBLE: return 'D';
2319 case JDWP::JT_INT: return 'I';
2320 case JDWP::JT_LONG: return 'J';
2321 case JDWP::JT_SHORT: return 'S';
2322 case JDWP::JT_VOID: return 'V';
2323 case JDWP::JT_BOOLEAN: return 'Z';
2324
2325 // Reference types.
2326 case JDWP::JT_ARRAY:
2327 case JDWP::JT_OBJECT:
2328 case JDWP::JT_STRING:
2329 case JDWP::JT_THREAD:
2330 case JDWP::JT_THREAD_GROUP:
2331 case JDWP::JT_CLASS_LOADER:
2332 case JDWP::JT_CLASS_OBJECT:
2333 return 'L';
2334 }
2335}
2336
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002337JDWP::JdwpError Dbg::InvokeMethod(JDWP::ObjectId threadId, JDWP::ObjectId objectId,
2338 JDWP::RefTypeId classId, JDWP::MethodId methodId,
2339 uint32_t arg_count, uint64_t* arg_values,
2340 JDWP::JdwpTag* arg_types, uint32_t options,
2341 JDWP::JdwpTag* pResultTag, uint64_t* pResultValue,
2342 JDWP::ObjectId* pExceptionId) {
Elliott Hughesd07986f2011-12-06 18:27:45 -08002343 ThreadList* thread_list = Runtime::Current()->GetThreadList();
2344
2345 Thread* targetThread = NULL;
2346 DebugInvokeReq* req = NULL;
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002347 Thread* self = Thread::Current();
Elliott Hughesd07986f2011-12-06 18:27:45 -08002348 {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002349 ScopedObjectAccessUnchecked soa(self);
Ian Rogers50b35e22012-10-04 10:09:15 -07002350 MutexLock mu(soa.Self(), *Locks::thread_list_lock_);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002351 targetThread = DecodeThread(soa, threadId);
Elliott Hughesd07986f2011-12-06 18:27:45 -08002352 if (targetThread == NULL) {
2353 LOG(ERROR) << "InvokeMethod request for non-existent thread " << threadId;
2354 return JDWP::ERR_INVALID_THREAD;
2355 }
2356 req = targetThread->GetInvokeReq();
2357 if (!req->ready) {
2358 LOG(ERROR) << "InvokeMethod request for thread not stopped by event: " << *targetThread;
2359 return JDWP::ERR_INVALID_THREAD;
2360 }
2361
2362 /*
2363 * We currently have a bug where we don't successfully resume the
2364 * target thread if the suspend count is too deep. We're expected to
2365 * require one "resume" for each "suspend", but when asked to execute
2366 * a method we have to resume fully and then re-suspend it back to the
2367 * same level. (The easiest way to cause this is to type "suspend"
2368 * multiple times in jdb.)
2369 *
2370 * It's unclear what this means when the event specifies "resume all"
2371 * and some threads are suspended more deeply than others. This is
2372 * a rare problem, so for now we just prevent it from hanging forever
2373 * by rejecting the method invocation request. Without this, we will
2374 * be stuck waiting on a suspended thread.
2375 */
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002376 int suspend_count;
2377 {
Ian Rogers50b35e22012-10-04 10:09:15 -07002378 MutexLock mu2(soa.Self(), *Locks::thread_suspend_count_lock_);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002379 suspend_count = targetThread->GetSuspendCount();
2380 }
Elliott Hughesd07986f2011-12-06 18:27:45 -08002381 if (suspend_count > 1) {
2382 LOG(ERROR) << *targetThread << " suspend count too deep for method invocation: " << suspend_count;
2383 return JDWP::ERR_THREAD_SUSPENDED; // Probably not expected here.
2384 }
2385
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08002386 JDWP::JdwpError status;
Elliott Hughes45651fd2012-02-21 15:48:20 -08002387 Object* receiver = gRegistry->Get<Object*>(objectId);
2388 if (receiver == kInvalidObject) {
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08002389 return JDWP::ERR_INVALID_OBJECT;
2390 }
Elliott Hughes45651fd2012-02-21 15:48:20 -08002391
2392 Object* thread = gRegistry->Get<Object*>(threadId);
2393 if (thread == kInvalidObject) {
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08002394 return JDWP::ERR_INVALID_OBJECT;
2395 }
Elliott Hughes45651fd2012-02-21 15:48:20 -08002396 // TODO: check that 'thread' is actually a java.lang.Thread!
2397
2398 Class* c = DecodeClass(classId, status);
2399 if (c == NULL) {
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08002400 return status;
2401 }
Elliott Hughes45651fd2012-02-21 15:48:20 -08002402
Mathieu Chartier66f19252012-09-18 08:57:04 -07002403 AbstractMethod* m = FromMethodId(methodId);
Elliott Hughes45651fd2012-02-21 15:48:20 -08002404 if (m->IsStatic() != (receiver == NULL)) {
2405 return JDWP::ERR_INVALID_METHODID;
2406 }
2407 if (m->IsStatic()) {
2408 if (m->GetDeclaringClass() != c) {
2409 return JDWP::ERR_INVALID_METHODID;
2410 }
2411 } else {
2412 if (!m->GetDeclaringClass()->IsAssignableFrom(c)) {
2413 return JDWP::ERR_INVALID_METHODID;
2414 }
2415 }
2416
2417 // Check the argument list matches the method.
2418 MethodHelper mh(m);
2419 if (mh.GetShortyLength() - 1 != arg_count) {
2420 return JDWP::ERR_ILLEGAL_ARGUMENT;
2421 }
2422 const char* shorty = mh.GetShorty();
2423 for (size_t i = 0; i < arg_count; ++i) {
2424 if (shorty[i + 1] != JdwpTagToShortyChar(arg_types[i])) {
2425 return JDWP::ERR_ILLEGAL_ARGUMENT;
2426 }
2427 }
2428
2429 req->receiver_ = receiver;
2430 req->thread_ = thread;
2431 req->class_ = c;
2432 req->method_ = m;
2433 req->arg_count_ = arg_count;
2434 req->arg_values_ = arg_values;
Elliott Hughesd07986f2011-12-06 18:27:45 -08002435 req->options_ = options;
2436 req->invoke_needed_ = true;
2437 }
2438
2439 // The fact that we've released the thread list lock is a bit risky --- if the thread goes
2440 // away we're sitting high and dry -- but we must release this before the ResumeAllThreads
2441 // call, and it's unwise to hold it during WaitForSuspend.
2442
2443 {
2444 /*
2445 * We change our (JDWP thread) status, which should be THREAD_RUNNING,
Elliott Hughes81ff3182012-03-23 20:35:56 -07002446 * so we can suspend for a GC if the invoke request causes us to
Elliott Hughesd07986f2011-12-06 18:27:45 -08002447 * run out of memory. It's also a good idea to change it before locking
2448 * the invokeReq mutex, although that should never be held for long.
2449 */
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002450 self->TransitionFromRunnableToSuspended(kWaitingForDebuggerSend);
Elliott Hughesd07986f2011-12-06 18:27:45 -08002451
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08002452 VLOG(jdwp) << " Transferring control to event thread";
Elliott Hughesd07986f2011-12-06 18:27:45 -08002453 {
Ian Rogers50b35e22012-10-04 10:09:15 -07002454 MutexLock mu(self, req->lock_);
Elliott Hughesd07986f2011-12-06 18:27:45 -08002455
2456 if ((options & JDWP::INVOKE_SINGLE_THREADED) == 0) {
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08002457 VLOG(jdwp) << " Resuming all threads";
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002458 thread_list->UndoDebuggerSuspensions();
Elliott Hughesd07986f2011-12-06 18:27:45 -08002459 } else {
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08002460 VLOG(jdwp) << " Resuming event thread only";
Elliott Hughesd07986f2011-12-06 18:27:45 -08002461 thread_list->Resume(targetThread, true);
2462 }
2463
2464 // Wait for the request to finish executing.
2465 while (req->invoke_needed_) {
Ian Rogersc604d732012-10-14 16:09:54 -07002466 req->cond_.Wait(self);
Elliott Hughesd07986f2011-12-06 18:27:45 -08002467 }
2468 }
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08002469 VLOG(jdwp) << " Control has returned from event thread";
Elliott Hughesd07986f2011-12-06 18:27:45 -08002470
2471 /* wait for thread to re-suspend itself */
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002472 SuspendThread(threadId, false /* request_suspension */ );
2473 self->TransitionFromSuspendedToRunnable();
Elliott Hughesd07986f2011-12-06 18:27:45 -08002474 }
2475
2476 /*
2477 * Suspend the threads. We waited for the target thread to suspend
2478 * itself, so all we need to do is suspend the others.
2479 *
2480 * The suspendAllThreads() call will double-suspend the event thread,
2481 * so we want to resume the target thread once to keep the books straight.
2482 */
2483 if ((options & JDWP::INVOKE_SINGLE_THREADED) == 0) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002484 self->TransitionFromRunnableToSuspended(kWaitingForDebuggerSuspension);
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08002485 VLOG(jdwp) << " Suspending all threads";
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002486 thread_list->SuspendAllForDebugger();
2487 self->TransitionFromSuspendedToRunnable();
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08002488 VLOG(jdwp) << " Resuming event thread to balance the count";
Elliott Hughesd07986f2011-12-06 18:27:45 -08002489 thread_list->Resume(targetThread, true);
2490 }
2491
2492 // Copy the result.
2493 *pResultTag = req->result_tag;
2494 if (IsPrimitiveTag(req->result_tag)) {
Elliott Hughesf24d3ce2012-04-11 17:43:37 -07002495 *pResultValue = req->result_value.GetJ();
Elliott Hughesd07986f2011-12-06 18:27:45 -08002496 } else {
Elliott Hughesf24d3ce2012-04-11 17:43:37 -07002497 *pResultValue = gRegistry->Add(req->result_value.GetL());
Elliott Hughesd07986f2011-12-06 18:27:45 -08002498 }
2499 *pExceptionId = req->exception;
2500 return req->error;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002501}
2502
2503void Dbg::ExecuteMethod(DebugInvokeReq* pReq) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002504 ScopedObjectAccess soa(Thread::Current());
Elliott Hughesd07986f2011-12-06 18:27:45 -08002505
Elliott Hughes81ff3182012-03-23 20:35:56 -07002506 // We can be called while an exception is pending. We need
Elliott Hughesd07986f2011-12-06 18:27:45 -08002507 // to preserve that across the method invocation.
Ian Rogers1f539342012-10-03 21:09:42 -07002508 SirtRef<Throwable> old_exception(soa.Self(), soa.Self()->GetException());
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002509 soa.Self()->ClearException();
Elliott Hughesd07986f2011-12-06 18:27:45 -08002510
2511 // Translate the method through the vtable, unless the debugger wants to suppress it.
Mathieu Chartier66f19252012-09-18 08:57:04 -07002512 AbstractMethod* m = pReq->method_;
Elliott Hughesd07986f2011-12-06 18:27:45 -08002513 if ((pReq->options_ & JDWP::INVOKE_NONVIRTUAL) == 0 && pReq->receiver_ != NULL) {
Mathieu Chartier66f19252012-09-18 08:57:04 -07002514 AbstractMethod* actual_method = pReq->class_->FindVirtualMethodForVirtualOrInterface(pReq->method_);
Elliott Hughes45651fd2012-02-21 15:48:20 -08002515 if (actual_method != m) {
2516 VLOG(jdwp) << "ExecuteMethod translated " << PrettyMethod(m) << " to " << PrettyMethod(actual_method);
2517 m = actual_method;
2518 }
Elliott Hughesd07986f2011-12-06 18:27:45 -08002519 }
Elliott Hughes45651fd2012-02-21 15:48:20 -08002520 VLOG(jdwp) << "ExecuteMethod " << PrettyMethod(m);
Elliott Hughesd07986f2011-12-06 18:27:45 -08002521 CHECK(m != NULL);
2522
2523 CHECK_EQ(sizeof(jvalue), sizeof(uint64_t));
2524
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002525 LOG(INFO) << "self=" << soa.Self() << " pReq->receiver_=" << pReq->receiver_ << " m=" << m
2526 << " #" << pReq->arg_count_ << " " << pReq->arg_values_;
2527 pReq->result_value = InvokeWithJValues(soa, pReq->receiver_, m,
2528 reinterpret_cast<JValue*>(pReq->arg_values_));
Elliott Hughesd07986f2011-12-06 18:27:45 -08002529
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002530 pReq->exception = gRegistry->Add(soa.Self()->GetException());
Elliott Hughesd07986f2011-12-06 18:27:45 -08002531 pReq->result_tag = BasicTagFromDescriptor(MethodHelper(m).GetShorty());
2532 if (pReq->exception != 0) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002533 Object* exc = soa.Self()->GetException();
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08002534 VLOG(jdwp) << " JDWP invocation returning with exception=" << exc << " " << PrettyTypeOf(exc);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002535 soa.Self()->ClearException();
Elliott Hughesf24d3ce2012-04-11 17:43:37 -07002536 pReq->result_value.SetJ(0);
Elliott Hughesd07986f2011-12-06 18:27:45 -08002537 } else if (pReq->result_tag == JDWP::JT_OBJECT) {
2538 /* if no exception thrown, examine object result more closely */
Elliott Hughesf24d3ce2012-04-11 17:43:37 -07002539 JDWP::JdwpTag new_tag = TagFromObject(pReq->result_value.GetL());
Elliott Hughesd07986f2011-12-06 18:27:45 -08002540 if (new_tag != pReq->result_tag) {
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08002541 VLOG(jdwp) << " JDWP promoted result from " << pReq->result_tag << " to " << new_tag;
Elliott Hughesd07986f2011-12-06 18:27:45 -08002542 pReq->result_tag = new_tag;
2543 }
2544
2545 /*
2546 * Register the object. We don't actually need an ObjectId yet,
2547 * but we do need to be sure that the GC won't move or discard the
2548 * object when we switch out of RUNNING. The ObjectId conversion
2549 * will add the object to the "do not touch" list.
2550 *
2551 * We can't use the "tracked allocation" mechanism here because
2552 * the object is going to be handed off to a different thread.
2553 */
Elliott Hughesf24d3ce2012-04-11 17:43:37 -07002554 gRegistry->Add(pReq->result_value.GetL());
Elliott Hughesd07986f2011-12-06 18:27:45 -08002555 }
2556
2557 if (old_exception.get() != NULL) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002558 soa.Self()->SetException(old_exception.get());
Elliott Hughesd07986f2011-12-06 18:27:45 -08002559 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002560}
2561
Elliott Hughesd07986f2011-12-06 18:27:45 -08002562/*
2563 * Register an object ID that might not have been registered previously.
2564 *
2565 * Normally this wouldn't happen -- the conversion to an ObjectId would
2566 * have added the object to the registry -- but in some cases (e.g.
2567 * throwing exceptions) we really want to do the registration late.
2568 */
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002569void Dbg::RegisterObjectId(JDWP::ObjectId id) {
Elliott Hughesd07986f2011-12-06 18:27:45 -08002570 gRegistry->Add(reinterpret_cast<Object*>(id));
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002571}
2572
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07002573/*
2574 * "buf" contains a full JDWP packet, possibly with multiple chunks. We
2575 * need to process each, accumulate the replies, and ship the whole thing
2576 * back.
2577 *
2578 * Returns "true" if we have a reply. The reply buffer is newly allocated,
2579 * and includes the chunk type/length, followed by the data.
2580 *
Elliott Hughes3d30d9b2011-12-07 17:35:48 -08002581 * OLD-TODO: we currently assume that the request and reply include a single
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07002582 * chunk. If this becomes inconvenient we will need to adapt.
2583 */
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002584bool Dbg::DdmHandlePacket(const uint8_t* buf, int dataLen, uint8_t** pReplyBuf, int* pReplyLen) {
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07002585 CHECK_GE(dataLen, 0);
2586
2587 Thread* self = Thread::Current();
2588 JNIEnv* env = self->GetJniEnv();
2589
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07002590 // Create a byte[] corresponding to 'buf'.
Elliott Hughes6a5bd492011-10-28 14:33:57 -07002591 ScopedLocalRef<jbyteArray> dataArray(env, env->NewByteArray(dataLen));
2592 if (dataArray.get() == NULL) {
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07002593 LOG(WARNING) << "byte[] allocation failed: " << dataLen;
2594 env->ExceptionClear();
2595 return false;
2596 }
Elliott Hughes6a5bd492011-10-28 14:33:57 -07002597 env->SetByteArrayRegion(dataArray.get(), 0, dataLen, reinterpret_cast<const jbyte*>(buf));
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07002598
2599 const int kChunkHdrLen = 8;
2600
2601 // Run through and find all chunks. [Currently just find the first.]
Elliott Hughes6a5bd492011-10-28 14:33:57 -07002602 ScopedByteArrayRO contents(env, dataArray.get());
Elliott Hughesf7c3b662011-10-27 12:04:56 -07002603 jint type = JDWP::Get4BE(reinterpret_cast<const uint8_t*>(&contents[0]));
2604 jint length = JDWP::Get4BE(reinterpret_cast<const uint8_t*>(&contents[4]));
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07002605 jint offset = kChunkHdrLen;
2606 if (offset + length > dataLen) {
2607 LOG(WARNING) << StringPrintf("bad chunk found (len=%u pktLen=%d)", length, dataLen);
2608 return false;
2609 }
2610
2611 // Call "private static Chunk dispatch(int type, byte[] data, int offset, int length)".
Elliott Hugheseac76672012-05-24 21:56:51 -07002612 ScopedLocalRef<jobject> chunk(env, env->CallStaticObjectMethod(WellKnownClasses::org_apache_harmony_dalvik_ddmc_DdmServer,
2613 WellKnownClasses::org_apache_harmony_dalvik_ddmc_DdmServer_dispatch,
2614 type, dataArray.get(), offset, length));
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07002615 if (env->ExceptionCheck()) {
2616 LOG(INFO) << StringPrintf("Exception thrown by dispatcher for 0x%08x", type);
2617 env->ExceptionDescribe();
2618 env->ExceptionClear();
2619 return false;
2620 }
2621
Elliott Hughes6a5bd492011-10-28 14:33:57 -07002622 if (chunk.get() == NULL) {
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07002623 return false;
2624 }
2625
2626 /*
2627 * Pull the pieces out of the chunk. We copy the results into a
2628 * newly-allocated buffer that the caller can free. We don't want to
2629 * continue using the Chunk object because nothing has a reference to it.
2630 *
2631 * We could avoid this by returning type/data/offset/length and having
2632 * the caller be aware of the object lifetime issues, but that
Elliott Hughes81ff3182012-03-23 20:35:56 -07002633 * integrates the JDWP code more tightly into the rest of the runtime, and doesn't work
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07002634 * if we have responses for multiple chunks.
2635 *
2636 * So we're pretty much stuck with copying data around multiple times.
2637 */
Elliott Hugheseac76672012-05-24 21:56:51 -07002638 ScopedLocalRef<jbyteArray> replyData(env, reinterpret_cast<jbyteArray>(env->GetObjectField(chunk.get(), WellKnownClasses::org_apache_harmony_dalvik_ddmc_Chunk_data)));
2639 length = env->GetIntField(chunk.get(), WellKnownClasses::org_apache_harmony_dalvik_ddmc_Chunk_length);
2640 offset = env->GetIntField(chunk.get(), WellKnownClasses::org_apache_harmony_dalvik_ddmc_Chunk_offset);
2641 type = env->GetIntField(chunk.get(), WellKnownClasses::org_apache_harmony_dalvik_ddmc_Chunk_type);
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07002642
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08002643 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 -07002644 if (length == 0 || replyData.get() == NULL) {
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07002645 return false;
2646 }
2647
Elliott Hughes6a5bd492011-10-28 14:33:57 -07002648 jsize replyLength = env->GetArrayLength(replyData.get());
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07002649 if (offset + length > replyLength) {
2650 LOG(WARNING) << StringPrintf("chunk off=%d len=%d exceeds reply array len %d", offset, length, replyLength);
2651 return false;
2652 }
2653
2654 uint8_t* reply = new uint8_t[length + kChunkHdrLen];
2655 if (reply == NULL) {
2656 LOG(WARNING) << "malloc failed: " << (length + kChunkHdrLen);
2657 return false;
2658 }
Elliott Hughesf7c3b662011-10-27 12:04:56 -07002659 JDWP::Set4BE(reply + 0, type);
2660 JDWP::Set4BE(reply + 4, length);
Elliott Hughes6a5bd492011-10-28 14:33:57 -07002661 env->GetByteArrayRegion(replyData.get(), offset, length, reinterpret_cast<jbyte*>(reply + kChunkHdrLen));
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07002662
2663 *pReplyBuf = reply;
2664 *pReplyLen = length + kChunkHdrLen;
2665
Elliott Hughesba8eee12012-01-24 20:25:24 -08002666 VLOG(jdwp) << StringPrintf("dvmHandleDdm returning type=%.4s buf=%p len=%d", reinterpret_cast<char*>(reply), reply, length);
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07002667 return true;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002668}
2669
Elliott Hughesa2155262011-11-16 16:26:58 -08002670void Dbg::DdmBroadcast(bool connect) {
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08002671 VLOG(jdwp) << "Broadcasting DDM " << (connect ? "connect" : "disconnect") << "...";
Elliott Hughes47fce012011-10-25 18:37:19 -07002672
2673 Thread* self = Thread::Current();
Ian Rogers50b35e22012-10-04 10:09:15 -07002674 if (self->GetState() != kRunnable) {
2675 LOG(ERROR) << "DDM broadcast in thread state " << self->GetState();
2676 /* try anyway? */
Elliott Hughes47fce012011-10-25 18:37:19 -07002677 }
2678
2679 JNIEnv* env = self->GetJniEnv();
Elliott Hughes47fce012011-10-25 18:37:19 -07002680 jint event = connect ? 1 /*DdmServer.CONNECTED*/ : 2 /*DdmServer.DISCONNECTED*/;
Elliott Hugheseac76672012-05-24 21:56:51 -07002681 env->CallStaticVoidMethod(WellKnownClasses::org_apache_harmony_dalvik_ddmc_DdmServer,
2682 WellKnownClasses::org_apache_harmony_dalvik_ddmc_DdmServer_broadcast,
2683 event);
Elliott Hughes47fce012011-10-25 18:37:19 -07002684 if (env->ExceptionCheck()) {
2685 LOG(ERROR) << "DdmServer.broadcast " << event << " failed";
2686 env->ExceptionDescribe();
2687 env->ExceptionClear();
2688 }
2689}
2690
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002691void Dbg::DdmConnected() {
Elliott Hughesa2155262011-11-16 16:26:58 -08002692 Dbg::DdmBroadcast(true);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002693}
2694
2695void Dbg::DdmDisconnected() {
Elliott Hughesa2155262011-11-16 16:26:58 -08002696 Dbg::DdmBroadcast(false);
Elliott Hughes47fce012011-10-25 18:37:19 -07002697 gDdmThreadNotification = false;
2698}
2699
2700/*
Elliott Hughes82188472011-11-07 18:11:48 -08002701 * Send a notification when a thread starts, stops, or changes its name.
Elliott Hughes47fce012011-10-25 18:37:19 -07002702 *
2703 * Because we broadcast the full set of threads when the notifications are
2704 * first enabled, it's possible for "thread" to be actively executing.
2705 */
Elliott Hughes82188472011-11-07 18:11:48 -08002706void Dbg::DdmSendThreadNotification(Thread* t, uint32_t type) {
Elliott Hughes47fce012011-10-25 18:37:19 -07002707 if (!gDdmThreadNotification) {
2708 return;
2709 }
2710
Elliott Hughes82188472011-11-07 18:11:48 -08002711 if (type == CHUNK_TYPE("THDE")) {
Elliott Hughes47fce012011-10-25 18:37:19 -07002712 uint8_t buf[4];
Elliott Hughesf7c3b662011-10-27 12:04:56 -07002713 JDWP::Set4BE(&buf[0], t->GetThinLockId());
Elliott Hughes47fce012011-10-25 18:37:19 -07002714 Dbg::DdmSendChunk(CHUNK_TYPE("THDE"), 4, buf);
Elliott Hughes82188472011-11-07 18:11:48 -08002715 } else {
2716 CHECK(type == CHUNK_TYPE("THCR") || type == CHUNK_TYPE("THNM")) << type;
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002717 ScopedObjectAccessUnchecked soa(Thread::Current());
Ian Rogers1f539342012-10-03 21:09:42 -07002718 SirtRef<String> name(soa.Self(), t->GetThreadName(soa));
Elliott Hughes82188472011-11-07 18:11:48 -08002719 size_t char_count = (name.get() != NULL) ? name->GetLength() : 0;
jeffhao725a9572012-11-13 18:20:12 -08002720 const jchar* chars = (name.get() != NULL) ? name->GetCharArray()->GetData() : NULL;
Elliott Hughes82188472011-11-07 18:11:48 -08002721
Elliott Hughes21f32d72011-11-09 17:44:13 -08002722 std::vector<uint8_t> bytes;
Elliott Hughes545a0642011-11-08 19:10:03 -08002723 JDWP::Append4BE(bytes, t->GetThinLockId());
2724 JDWP::AppendUtf16BE(bytes, chars, char_count);
Elliott Hughes21f32d72011-11-09 17:44:13 -08002725 CHECK_EQ(bytes.size(), char_count*2 + sizeof(uint32_t)*2);
2726 Dbg::DdmSendChunk(type, bytes);
Elliott Hughes47fce012011-10-25 18:37:19 -07002727 }
2728}
2729
Elliott Hughes47fce012011-10-25 18:37:19 -07002730void Dbg::DdmSetThreadNotification(bool enable) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002731 // Enable/disable thread notifications.
Elliott Hughes47fce012011-10-25 18:37:19 -07002732 gDdmThreadNotification = enable;
2733 if (enable) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002734 // Suspend the VM then post thread start notifications for all threads. Threads attaching will
2735 // see a suspension in progress and block until that ends. They then post their own start
2736 // notification.
2737 SuspendVM();
2738 std::list<Thread*> threads;
Ian Rogers50b35e22012-10-04 10:09:15 -07002739 Thread* self = Thread::Current();
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002740 {
Ian Rogers50b35e22012-10-04 10:09:15 -07002741 MutexLock mu(self, *Locks::thread_list_lock_);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002742 threads = Runtime::Current()->GetThreadList()->GetList();
2743 }
2744 {
Ian Rogers50b35e22012-10-04 10:09:15 -07002745 ScopedObjectAccess soa(self);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002746 typedef std::list<Thread*>::const_iterator It; // TODO: C++0x auto
2747 for (It it = threads.begin(), end = threads.end(); it != end; ++it) {
2748 Dbg::DdmSendThreadNotification(*it, CHUNK_TYPE("THCR"));
2749 }
2750 }
2751 ResumeVM();
Elliott Hughes47fce012011-10-25 18:37:19 -07002752 }
2753}
2754
Elliott Hughesa2155262011-11-16 16:26:58 -08002755void Dbg::PostThreadStartOrStop(Thread* t, uint32_t type) {
Elliott Hughesc0f09332012-03-26 13:27:06 -07002756 if (IsDebuggerActive()) {
Mathieu Chartierdbe6f462012-09-25 16:54:50 -07002757 ScopedObjectAccessUnchecked soa(Thread::Current());
Ian Rogerscfaa4552012-11-26 21:00:08 -08002758 JDWP::ObjectId id = gRegistry->Add(t->GetPeer());
Elliott Hughes82188472011-11-07 18:11:48 -08002759 gJdwpState->PostThreadChange(id, type == CHUNK_TYPE("THCR"));
Elliott Hughesc0f09332012-03-26 13:27:06 -07002760 // If this thread's just joined the party while we're already debugging, make sure it knows
2761 // to give us updates when it's running.
2762 t->SetDebuggerUpdatesEnabled(true);
Elliott Hughes47fce012011-10-25 18:37:19 -07002763 }
Elliott Hughes82188472011-11-07 18:11:48 -08002764 Dbg::DdmSendThreadNotification(t, type);
Elliott Hughes47fce012011-10-25 18:37:19 -07002765}
2766
2767void Dbg::PostThreadStart(Thread* t) {
Elliott Hughesa2155262011-11-16 16:26:58 -08002768 Dbg::PostThreadStartOrStop(t, CHUNK_TYPE("THCR"));
Elliott Hughes47fce012011-10-25 18:37:19 -07002769}
2770
2771void Dbg::PostThreadDeath(Thread* t) {
Elliott Hughesa2155262011-11-16 16:26:58 -08002772 Dbg::PostThreadStartOrStop(t, CHUNK_TYPE("THDE"));
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002773}
2774
Elliott Hughes82188472011-11-07 18:11:48 -08002775void Dbg::DdmSendChunk(uint32_t type, size_t byte_count, const uint8_t* buf) {
Elliott Hughes3bb81562011-10-21 18:52:59 -07002776 CHECK(buf != NULL);
2777 iovec vec[1];
2778 vec[0].iov_base = reinterpret_cast<void*>(const_cast<uint8_t*>(buf));
2779 vec[0].iov_len = byte_count;
2780 Dbg::DdmSendChunkV(type, vec, 1);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002781}
2782
Elliott Hughes21f32d72011-11-09 17:44:13 -08002783void Dbg::DdmSendChunk(uint32_t type, const std::vector<uint8_t>& bytes) {
2784 DdmSendChunk(type, bytes.size(), &bytes[0]);
2785}
2786
Elliott Hughescccd84f2011-12-05 16:51:54 -08002787void Dbg::DdmSendChunkV(uint32_t type, const struct iovec* iov, int iov_count) {
Elliott Hughes3bb81562011-10-21 18:52:59 -07002788 if (gJdwpState == NULL) {
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08002789 VLOG(jdwp) << "Debugger thread not active, ignoring DDM send: " << type;
Elliott Hughes3bb81562011-10-21 18:52:59 -07002790 } else {
Elliott Hughescccd84f2011-12-05 16:51:54 -08002791 gJdwpState->DdmSendChunkV(type, iov, iov_count);
Elliott Hughes3bb81562011-10-21 18:52:59 -07002792 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002793}
2794
Elliott Hughes767a1472011-10-26 18:49:02 -07002795int Dbg::DdmHandleHpifChunk(HpifWhen when) {
2796 if (when == HPIF_WHEN_NOW) {
Elliott Hughes7162ad92011-10-27 14:08:42 -07002797 DdmSendHeapInfo(when);
Elliott Hughes767a1472011-10-26 18:49:02 -07002798 return true;
2799 }
2800
2801 if (when != HPIF_WHEN_NEVER && when != HPIF_WHEN_NEXT_GC && when != HPIF_WHEN_EVERY_GC) {
2802 LOG(ERROR) << "invalid HpifWhen value: " << static_cast<int>(when);
2803 return false;
2804 }
2805
2806 gDdmHpifWhen = when;
2807 return true;
2808}
2809
2810bool Dbg::DdmHandleHpsgNhsgChunk(Dbg::HpsgWhen when, Dbg::HpsgWhat what, bool native) {
2811 if (when != HPSG_WHEN_NEVER && when != HPSG_WHEN_EVERY_GC) {
2812 LOG(ERROR) << "invalid HpsgWhen value: " << static_cast<int>(when);
2813 return false;
2814 }
2815
2816 if (what != HPSG_WHAT_MERGED_OBJECTS && what != HPSG_WHAT_DISTINCT_OBJECTS) {
2817 LOG(ERROR) << "invalid HpsgWhat value: " << static_cast<int>(what);
2818 return false;
2819 }
2820
2821 if (native) {
2822 gDdmNhsgWhen = when;
2823 gDdmNhsgWhat = what;
2824 } else {
2825 gDdmHpsgWhen = when;
2826 gDdmHpsgWhat = what;
2827 }
2828 return true;
2829}
2830
Elliott Hughes7162ad92011-10-27 14:08:42 -07002831void Dbg::DdmSendHeapInfo(HpifWhen reason) {
2832 // If there's a one-shot 'when', reset it.
2833 if (reason == gDdmHpifWhen) {
2834 if (gDdmHpifWhen == HPIF_WHEN_NEXT_GC) {
2835 gDdmHpifWhen = HPIF_WHEN_NEVER;
2836 }
2837 }
2838
2839 /*
2840 * Chunk HPIF (client --> server)
2841 *
2842 * Heap Info. General information about the heap,
2843 * suitable for a summary display.
2844 *
2845 * [u4]: number of heaps
2846 *
2847 * For each heap:
2848 * [u4]: heap ID
2849 * [u8]: timestamp in ms since Unix epoch
2850 * [u1]: capture reason (same as 'when' value from server)
2851 * [u4]: max heap size in bytes (-Xmx)
2852 * [u4]: current heap size in bytes
2853 * [u4]: current number of bytes allocated
2854 * [u4]: current number of objects allocated
2855 */
2856 uint8_t heap_count = 1;
Elliott Hughesb3bd5f02012-03-08 21:05:27 -08002857 Heap* heap = Runtime::Current()->GetHeap();
Elliott Hughes21f32d72011-11-09 17:44:13 -08002858 std::vector<uint8_t> bytes;
Elliott Hughes545a0642011-11-08 19:10:03 -08002859 JDWP::Append4BE(bytes, heap_count);
2860 JDWP::Append4BE(bytes, 1); // Heap id (bogus; we only have one heap).
2861 JDWP::Append8BE(bytes, MilliTime());
2862 JDWP::Append1BE(bytes, reason);
Elliott Hughesb3bd5f02012-03-08 21:05:27 -08002863 JDWP::Append4BE(bytes, heap->GetMaxMemory()); // Max allowed heap size in bytes.
2864 JDWP::Append4BE(bytes, heap->GetTotalMemory()); // Current heap size in bytes.
2865 JDWP::Append4BE(bytes, heap->GetBytesAllocated());
2866 JDWP::Append4BE(bytes, heap->GetObjectsAllocated());
Elliott Hughes21f32d72011-11-09 17:44:13 -08002867 CHECK_EQ(bytes.size(), 4U + (heap_count * (4 + 8 + 1 + 4 + 4 + 4 + 4)));
2868 Dbg::DdmSendChunk(CHUNK_TYPE("HPIF"), bytes);
Elliott Hughes767a1472011-10-26 18:49:02 -07002869}
2870
Elliott Hughes6a5bd492011-10-28 14:33:57 -07002871enum HpsgSolidity {
2872 SOLIDITY_FREE = 0,
2873 SOLIDITY_HARD = 1,
2874 SOLIDITY_SOFT = 2,
2875 SOLIDITY_WEAK = 3,
2876 SOLIDITY_PHANTOM = 4,
2877 SOLIDITY_FINALIZABLE = 5,
2878 SOLIDITY_SWEEP = 6,
2879};
2880
2881enum HpsgKind {
2882 KIND_OBJECT = 0,
2883 KIND_CLASS_OBJECT = 1,
2884 KIND_ARRAY_1 = 2,
2885 KIND_ARRAY_2 = 3,
2886 KIND_ARRAY_4 = 4,
2887 KIND_ARRAY_8 = 5,
2888 KIND_UNKNOWN = 6,
2889 KIND_NATIVE = 7,
2890};
2891
2892#define HPSG_PARTIAL (1<<7)
2893#define HPSG_STATE(solidity, kind) ((uint8_t)((((kind) & 0x7) << 3) | ((solidity) & 0x7)))
2894
Ian Rogers30fab402012-01-23 15:43:46 -08002895class HeapChunkContext {
2896 public:
Elliott Hughes6a5bd492011-10-28 14:33:57 -07002897 // Maximum chunk size. Obtain this from the formula:
2898 // (((maximum_heap_size / ALLOCATION_UNIT_SIZE) + 255) / 256) * 2
2899 HeapChunkContext(bool merge, bool native)
Ian Rogers30fab402012-01-23 15:43:46 -08002900 : buf_(16384 - 16),
2901 type_(0),
2902 merge_(merge) {
Elliott Hughes6a5bd492011-10-28 14:33:57 -07002903 Reset();
2904 if (native) {
Ian Rogers30fab402012-01-23 15:43:46 -08002905 type_ = CHUNK_TYPE("NHSG");
Elliott Hughes6a5bd492011-10-28 14:33:57 -07002906 } else {
Ian Rogers30fab402012-01-23 15:43:46 -08002907 type_ = merge ? CHUNK_TYPE("HPSG") : CHUNK_TYPE("HPSO");
Elliott Hughes6a5bd492011-10-28 14:33:57 -07002908 }
2909 }
2910
2911 ~HeapChunkContext() {
Ian Rogers30fab402012-01-23 15:43:46 -08002912 if (p_ > &buf_[0]) {
Elliott Hughes6a5bd492011-10-28 14:33:57 -07002913 Flush();
2914 }
2915 }
2916
2917 void EnsureHeader(const void* chunk_ptr) {
Ian Rogers30fab402012-01-23 15:43:46 -08002918 if (!needHeader_) {
Elliott Hughes6a5bd492011-10-28 14:33:57 -07002919 return;
2920 }
2921
2922 // Start a new HPSx chunk.
Ian Rogers30fab402012-01-23 15:43:46 -08002923 JDWP::Write4BE(&p_, 1); // Heap id (bogus; we only have one heap).
2924 JDWP::Write1BE(&p_, 8); // Size of allocation unit, in bytes.
Elliott Hughes6a5bd492011-10-28 14:33:57 -07002925
Ian Rogers30fab402012-01-23 15:43:46 -08002926 JDWP::Write4BE(&p_, reinterpret_cast<uintptr_t>(chunk_ptr)); // virtual address of segment start.
2927 JDWP::Write4BE(&p_, 0); // offset of this piece (relative to the virtual address).
Elliott Hughes6a5bd492011-10-28 14:33:57 -07002928 // [u4]: length of piece, in allocation units
2929 // 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 -08002930 pieceLenField_ = p_;
2931 JDWP::Write4BE(&p_, 0x55555555);
2932 needHeader_ = false;
Elliott Hughes6a5bd492011-10-28 14:33:57 -07002933 }
2934
Ian Rogersb726dcb2012-09-05 08:57:23 -07002935 void Flush() SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Elliott Hughes6a5bd492011-10-28 14:33:57 -07002936 // Patch the "length of piece" field.
Ian Rogers30fab402012-01-23 15:43:46 -08002937 CHECK_LE(&buf_[0], pieceLenField_);
2938 CHECK_LE(pieceLenField_, p_);
2939 JDWP::Set4BE(pieceLenField_, totalAllocationUnits_);
Elliott Hughes6a5bd492011-10-28 14:33:57 -07002940
Ian Rogers30fab402012-01-23 15:43:46 -08002941 Dbg::DdmSendChunk(type_, p_ - &buf_[0], &buf_[0]);
Elliott Hughes6a5bd492011-10-28 14:33:57 -07002942 Reset();
2943 }
2944
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002945 static void HeapChunkCallback(void* start, void* end, size_t used_bytes, void* arg)
Ian Rogersb726dcb2012-09-05 08:57:23 -07002946 SHARED_LOCKS_REQUIRED(Locks::heap_bitmap_lock_,
2947 Locks::mutator_lock_) {
Ian Rogers30fab402012-01-23 15:43:46 -08002948 reinterpret_cast<HeapChunkContext*>(arg)->HeapChunkCallback(start, end, used_bytes);
Elliott Hughesa2155262011-11-16 16:26:58 -08002949 }
2950
Elliott Hughes6a5bd492011-10-28 14:33:57 -07002951 private:
Elliott Hughesa2155262011-11-16 16:26:58 -08002952 enum { ALLOCATION_UNIT_SIZE = 8 };
2953
Elliott Hughes6a5bd492011-10-28 14:33:57 -07002954 void Reset() {
Ian Rogers30fab402012-01-23 15:43:46 -08002955 p_ = &buf_[0];
Ian Rogers15bf2d32012-08-28 17:33:04 -07002956 startOfNextMemoryChunk_ = NULL;
Ian Rogers30fab402012-01-23 15:43:46 -08002957 totalAllocationUnits_ = 0;
2958 needHeader_ = true;
2959 pieceLenField_ = NULL;
Elliott Hughes6a5bd492011-10-28 14:33:57 -07002960 }
2961
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002962 void HeapChunkCallback(void* start, void* /*end*/, size_t used_bytes)
Ian Rogersb726dcb2012-09-05 08:57:23 -07002963 SHARED_LOCKS_REQUIRED(Locks::heap_bitmap_lock_,
2964 Locks::mutator_lock_) {
Ian Rogers30fab402012-01-23 15:43:46 -08002965 // Note: heap call backs cannot manipulate the heap upon which they are crawling, care is taken
2966 // in the following code not to allocate memory, by ensuring buf_ is of the correct size
Ian Rogers15bf2d32012-08-28 17:33:04 -07002967 if (used_bytes == 0) {
2968 if (start == NULL) {
2969 // Reset for start of new heap.
2970 startOfNextMemoryChunk_ = NULL;
2971 Flush();
2972 }
2973 // Only process in use memory so that free region information
2974 // also includes dlmalloc book keeping.
Elliott Hughesa2155262011-11-16 16:26:58 -08002975 return;
Elliott Hughesa2155262011-11-16 16:26:58 -08002976 }
2977
Ian Rogers15bf2d32012-08-28 17:33:04 -07002978 /* If we're looking at the native heap, we'll just return
2979 * (SOLIDITY_HARD, KIND_NATIVE) for all allocated chunks
2980 */
2981 bool native = type_ == CHUNK_TYPE("NHSG");
2982
2983 if (startOfNextMemoryChunk_ != NULL) {
2984 // Transmit any pending free memory. Native free memory of
2985 // over kMaxFreeLen could be because of the use of mmaps, so
2986 // don't report. If not free memory then start a new segment.
2987 bool flush = true;
2988 if (start > startOfNextMemoryChunk_) {
2989 const size_t kMaxFreeLen = 2 * kPageSize;
2990 void* freeStart = startOfNextMemoryChunk_;
2991 void* freeEnd = start;
2992 size_t freeLen = (char*)freeEnd - (char*)freeStart;
2993 if (!native || freeLen < kMaxFreeLen) {
2994 AppendChunk(HPSG_STATE(SOLIDITY_FREE, 0), freeStart, freeLen);
2995 flush = false;
2996 }
2997 }
2998 if (flush) {
2999 startOfNextMemoryChunk_ = NULL;
3000 Flush();
3001 }
3002 }
3003 const Object *obj = (const Object *)start;
Elliott Hughesa2155262011-11-16 16:26:58 -08003004
3005 // Determine the type of this chunk.
3006 // OLD-TODO: if context.merge, see if this chunk is different from the last chunk.
3007 // If it's the same, we should combine them.
Ian Rogers15bf2d32012-08-28 17:33:04 -07003008 uint8_t state = ExamineObject(obj, native);
3009 // dlmalloc's chunk header is 2 * sizeof(size_t), but if the previous chunk is in use for an
3010 // allocation then the first sizeof(size_t) may belong to it.
3011 const size_t dlMallocOverhead = sizeof(size_t);
3012 AppendChunk(state, start, used_bytes + dlMallocOverhead);
3013 startOfNextMemoryChunk_ = (char*)start + used_bytes + dlMallocOverhead;
3014 }
Elliott Hughesa2155262011-11-16 16:26:58 -08003015
Ian Rogers15bf2d32012-08-28 17:33:04 -07003016 void AppendChunk(uint8_t state, void* ptr, size_t length)
Ian Rogersb726dcb2012-09-05 08:57:23 -07003017 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Ian Rogers15bf2d32012-08-28 17:33:04 -07003018 // Make sure there's enough room left in the buffer.
3019 // We need to use two bytes for every fractional 256 allocation units used by the chunk plus
3020 // 17 bytes for any header.
3021 size_t needed = (((length/ALLOCATION_UNIT_SIZE + 255) / 256) * 2) + 17;
3022 size_t bytesLeft = buf_.size() - (size_t)(p_ - &buf_[0]);
3023 if (bytesLeft < needed) {
3024 Flush();
3025 }
3026
3027 bytesLeft = buf_.size() - (size_t)(p_ - &buf_[0]);
3028 if (bytesLeft < needed) {
3029 LOG(WARNING) << "Chunk is too big to transmit (chunk_len=" << length << ", "
3030 << needed << " bytes)";
3031 return;
3032 }
3033 EnsureHeader(ptr);
Elliott Hughesa2155262011-11-16 16:26:58 -08003034 // Write out the chunk description.
Ian Rogers15bf2d32012-08-28 17:33:04 -07003035 length /= ALLOCATION_UNIT_SIZE; // Convert to allocation units.
3036 totalAllocationUnits_ += length;
3037 while (length > 256) {
Ian Rogers30fab402012-01-23 15:43:46 -08003038 *p_++ = state | HPSG_PARTIAL;
3039 *p_++ = 255; // length - 1
Ian Rogers15bf2d32012-08-28 17:33:04 -07003040 length -= 256;
Elliott Hughesa2155262011-11-16 16:26:58 -08003041 }
Ian Rogers30fab402012-01-23 15:43:46 -08003042 *p_++ = state;
Ian Rogers15bf2d32012-08-28 17:33:04 -07003043 *p_++ = length - 1;
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003044 }
3045
Ian Rogers5bfa60f2012-09-02 21:17:56 -07003046 uint8_t ExamineObject(const Object* o, bool is_native_heap)
Ian Rogersb726dcb2012-09-05 08:57:23 -07003047 SHARED_LOCKS_REQUIRED(Locks::heap_bitmap_lock_) {
Elliott Hughesa2155262011-11-16 16:26:58 -08003048 if (o == NULL) {
3049 return HPSG_STATE(SOLIDITY_FREE, 0);
3050 }
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003051
Elliott Hughesa2155262011-11-16 16:26:58 -08003052 // It's an allocated chunk. Figure out what it is.
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003053
Elliott Hughesa2155262011-11-16 16:26:58 -08003054 // If we're looking at the native heap, we'll just return
3055 // (SOLIDITY_HARD, KIND_NATIVE) for all allocated chunks.
Ian Rogers00f7d0e2012-07-19 15:28:27 -07003056 if (is_native_heap) {
Elliott Hughesa2155262011-11-16 16:26:58 -08003057 return HPSG_STATE(SOLIDITY_HARD, KIND_NATIVE);
3058 }
3059
Ian Rogers5bfa60f2012-09-02 21:17:56 -07003060 if (!Runtime::Current()->GetHeap()->IsLiveObjectLocked(o)) {
Ian Rogers15bf2d32012-08-28 17:33:04 -07003061 return HPSG_STATE(SOLIDITY_HARD, KIND_NATIVE);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07003062 }
3063
Elliott Hughesa2155262011-11-16 16:26:58 -08003064 Class* c = o->GetClass();
3065 if (c == NULL) {
3066 // The object was probably just created but hasn't been initialized yet.
3067 return HPSG_STATE(SOLIDITY_HARD, KIND_OBJECT);
3068 }
3069
Elliott Hughesb3bd5f02012-03-08 21:05:27 -08003070 if (!Runtime::Current()->GetHeap()->IsHeapAddress(c)) {
Ian Rogers15bf2d32012-08-28 17:33:04 -07003071 LOG(ERROR) << "Invalid class for managed heap object: " << o << " " << c;
Elliott Hughesa2155262011-11-16 16:26:58 -08003072 return HPSG_STATE(SOLIDITY_HARD, KIND_UNKNOWN);
3073 }
3074
3075 if (c->IsClassClass()) {
3076 return HPSG_STATE(SOLIDITY_HARD, KIND_CLASS_OBJECT);
3077 }
3078
3079 if (c->IsArrayClass()) {
3080 if (o->IsObjectArray()) {
3081 return HPSG_STATE(SOLIDITY_HARD, KIND_ARRAY_4);
3082 }
3083 switch (c->GetComponentSize()) {
3084 case 1: return HPSG_STATE(SOLIDITY_HARD, KIND_ARRAY_1);
3085 case 2: return HPSG_STATE(SOLIDITY_HARD, KIND_ARRAY_2);
3086 case 4: return HPSG_STATE(SOLIDITY_HARD, KIND_ARRAY_4);
3087 case 8: return HPSG_STATE(SOLIDITY_HARD, KIND_ARRAY_8);
3088 }
3089 }
3090
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003091 return HPSG_STATE(SOLIDITY_HARD, KIND_OBJECT);
3092 }
3093
Ian Rogers30fab402012-01-23 15:43:46 -08003094 std::vector<uint8_t> buf_;
3095 uint8_t* p_;
3096 uint8_t* pieceLenField_;
Ian Rogers15bf2d32012-08-28 17:33:04 -07003097 void* startOfNextMemoryChunk_;
Ian Rogers30fab402012-01-23 15:43:46 -08003098 size_t totalAllocationUnits_;
3099 uint32_t type_;
3100 bool merge_;
3101 bool needHeader_;
3102
Elliott Hughesa2155262011-11-16 16:26:58 -08003103 DISALLOW_COPY_AND_ASSIGN(HeapChunkContext);
3104};
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003105
3106void Dbg::DdmSendHeapSegments(bool native) {
3107 Dbg::HpsgWhen when;
3108 Dbg::HpsgWhat what;
3109 if (!native) {
3110 when = gDdmHpsgWhen;
3111 what = gDdmHpsgWhat;
3112 } else {
3113 when = gDdmNhsgWhen;
3114 what = gDdmNhsgWhat;
3115 }
3116 if (when == HPSG_WHEN_NEVER) {
3117 return;
3118 }
3119
3120 // Figure out what kind of chunks we'll be sending.
3121 CHECK(what == HPSG_WHAT_MERGED_OBJECTS || what == HPSG_WHAT_DISTINCT_OBJECTS) << static_cast<int>(what);
3122
3123 // First, send a heap start chunk.
3124 uint8_t heap_id[4];
3125 JDWP::Set4BE(&heap_id[0], 1); // Heap id (bogus; we only have one heap).
3126 Dbg::DdmSendChunk(native ? CHUNK_TYPE("NHST") : CHUNK_TYPE("HPST"), sizeof(heap_id), heap_id);
3127
3128 // Send a series of heap segment chunks.
Elliott Hughesa2155262011-11-16 16:26:58 -08003129 HeapChunkContext context((what == HPSG_WHAT_MERGED_OBJECTS), native);
3130 if (native) {
Ian Rogers30fab402012-01-23 15:43:46 -08003131 // TODO: enable when bionic has moved to dlmalloc 2.8.5
3132 // dlmalloc_inspect_all(HeapChunkContext::HeapChunkCallback, &context);
3133 UNIMPLEMENTED(WARNING) << "Native heap send heap segments";
Elliott Hughesa2155262011-11-16 16:26:58 -08003134 } else {
Elliott Hughesb3bd5f02012-03-08 21:05:27 -08003135 Heap* heap = Runtime::Current()->GetHeap();
Mathieu Chartierfd678be2012-08-30 14:50:54 -07003136 const Spaces& spaces = heap->GetSpaces();
Ian Rogers50b35e22012-10-04 10:09:15 -07003137 Thread* self = Thread::Current();
Mathieu Chartierfd678be2012-08-30 14:50:54 -07003138 for (Spaces::const_iterator cur = spaces.begin(); cur != spaces.end(); ++cur) {
Mathieu Chartierb062fdd2012-07-03 09:51:48 -07003139 if ((*cur)->IsAllocSpace()) {
Ian Rogers50b35e22012-10-04 10:09:15 -07003140 ReaderMutexLock mu(self, *Locks::heap_bitmap_lock_);
Mathieu Chartierb062fdd2012-07-03 09:51:48 -07003141 (*cur)->AsAllocSpace()->Walk(HeapChunkContext::HeapChunkCallback, &context);
3142 }
3143 }
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -07003144 // Walk the large objects, these are not in the AllocSpace.
3145 heap->GetLargeObjectsSpace()->Walk(HeapChunkContext::HeapChunkCallback, &context);
Elliott Hughesa2155262011-11-16 16:26:58 -08003146 }
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003147
3148 // Finally, send a heap end chunk.
3149 Dbg::DdmSendChunk(native ? CHUNK_TYPE("NHEN") : CHUNK_TYPE("HPEN"), sizeof(heap_id), heap_id);
Elliott Hughes767a1472011-10-26 18:49:02 -07003150}
3151
Elliott Hughes545a0642011-11-08 19:10:03 -08003152void Dbg::SetAllocTrackingEnabled(bool enabled) {
Ian Rogers50b35e22012-10-04 10:09:15 -07003153 MutexLock mu(Thread::Current(), gAllocTrackerLock);
Elliott Hughes545a0642011-11-08 19:10:03 -08003154 if (enabled) {
3155 if (recent_allocation_records_ == NULL) {
3156 LOG(INFO) << "Enabling alloc tracker (" << kNumAllocRecords << " entries, "
3157 << kMaxAllocRecordStackDepth << " frames --> "
3158 << (sizeof(AllocRecord) * kNumAllocRecords) << " bytes)";
3159 gAllocRecordHead = gAllocRecordCount = 0;
3160 recent_allocation_records_ = new AllocRecord[kNumAllocRecords];
3161 CHECK(recent_allocation_records_ != NULL);
3162 }
3163 } else {
3164 delete[] recent_allocation_records_;
3165 recent_allocation_records_ = NULL;
3166 }
3167}
3168
Ian Rogers0399dde2012-06-06 17:09:28 -07003169struct AllocRecordStackVisitor : public StackVisitor {
3170 AllocRecordStackVisitor(const ManagedStack* stack,
jeffhao725a9572012-11-13 18:20:12 -08003171 const std::vector<InstrumentationStackFrame>* instrumentation_stack, AllocRecord* record)
Ian Rogersb726dcb2012-09-05 08:57:23 -07003172 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_)
jeffhao725a9572012-11-13 18:20:12 -08003173 : StackVisitor(stack, instrumentation_stack, NULL), record(record), depth(0) {}
Elliott Hughes545a0642011-11-08 19:10:03 -08003174
Ian Rogers00f7d0e2012-07-19 15:28:27 -07003175 // TODO: Enable annotalysis. We know lock is held in constructor, but abstraction confuses
3176 // annotalysis.
3177 bool VisitFrame() NO_THREAD_SAFETY_ANALYSIS {
Elliott Hughes545a0642011-11-08 19:10:03 -08003178 if (depth >= kMaxAllocRecordStackDepth) {
Elliott Hughes530fa002012-03-12 11:44:49 -07003179 return false;
Elliott Hughes545a0642011-11-08 19:10:03 -08003180 }
Mathieu Chartier66f19252012-09-18 08:57:04 -07003181 AbstractMethod* m = GetMethod();
Ian Rogers0399dde2012-06-06 17:09:28 -07003182 if (!m->IsRuntimeMethod()) {
3183 record->stack[depth].method = m;
3184 record->stack[depth].dex_pc = GetDexPc();
Elliott Hughes530fa002012-03-12 11:44:49 -07003185 ++depth;
Elliott Hughes545a0642011-11-08 19:10:03 -08003186 }
Elliott Hughes530fa002012-03-12 11:44:49 -07003187 return true;
Elliott Hughes545a0642011-11-08 19:10:03 -08003188 }
3189
3190 ~AllocRecordStackVisitor() {
3191 // Clear out any unused stack trace elements.
3192 for (; depth < kMaxAllocRecordStackDepth; ++depth) {
3193 record->stack[depth].method = NULL;
Ian Rogers0399dde2012-06-06 17:09:28 -07003194 record->stack[depth].dex_pc = 0;
Elliott Hughes545a0642011-11-08 19:10:03 -08003195 }
3196 }
3197
3198 AllocRecord* record;
3199 size_t depth;
3200};
3201
3202void Dbg::RecordAllocation(Class* type, size_t byte_count) {
3203 Thread* self = Thread::Current();
3204 CHECK(self != NULL);
3205
Ian Rogers50b35e22012-10-04 10:09:15 -07003206 MutexLock mu(self, gAllocTrackerLock);
Elliott Hughes545a0642011-11-08 19:10:03 -08003207 if (recent_allocation_records_ == NULL) {
3208 return;
3209 }
3210
3211 // Advance and clip.
3212 if (++gAllocRecordHead == kNumAllocRecords) {
3213 gAllocRecordHead = 0;
3214 }
3215
3216 // Fill in the basics.
3217 AllocRecord* record = &recent_allocation_records_[gAllocRecordHead];
3218 record->type = type;
3219 record->byte_count = byte_count;
3220 record->thin_lock_id = self->GetThinLockId();
3221
3222 // Fill in the stack trace.
jeffhao725a9572012-11-13 18:20:12 -08003223 AllocRecordStackVisitor visitor(self->GetManagedStack(), self->GetInstrumentationStack(), record);
Ian Rogers0399dde2012-06-06 17:09:28 -07003224 visitor.WalkStack();
Elliott Hughes545a0642011-11-08 19:10:03 -08003225
3226 if (gAllocRecordCount < kNumAllocRecords) {
3227 ++gAllocRecordCount;
3228 }
3229}
3230
Elliott Hughesa8f93cb2012-06-08 17:08:48 -07003231// Returns the index of the head element.
3232//
3233// We point at the most-recently-written record, so if gAllocRecordCount is 1
3234// we want to use the current element. Take "head+1" and subtract count
3235// from it.
3236//
3237// We need to handle underflow in our circular buffer, so we add
3238// kNumAllocRecords and then mask it back down.
Elliott Hughesf8349362012-06-18 15:00:06 -07003239static inline int HeadIndex() EXCLUSIVE_LOCKS_REQUIRED(gAllocTrackerLock) {
Elliott Hughes545a0642011-11-08 19:10:03 -08003240 return (gAllocRecordHead+1 + kNumAllocRecords - gAllocRecordCount) & (kNumAllocRecords-1);
3241}
3242
3243void Dbg::DumpRecentAllocations() {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07003244 ScopedObjectAccess soa(Thread::Current());
Ian Rogers50b35e22012-10-04 10:09:15 -07003245 MutexLock mu(soa.Self(), gAllocTrackerLock);
Elliott Hughes545a0642011-11-08 19:10:03 -08003246 if (recent_allocation_records_ == NULL) {
3247 LOG(INFO) << "Not recording tracked allocations";
3248 return;
3249 }
3250
3251 // "i" is the head of the list. We want to start at the end of the
3252 // list and move forward to the tail.
Elliott Hughesa8f93cb2012-06-08 17:08:48 -07003253 size_t i = HeadIndex();
Elliott Hughes545a0642011-11-08 19:10:03 -08003254 size_t count = gAllocRecordCount;
3255
3256 LOG(INFO) << "Tracked allocations, (head=" << gAllocRecordHead << " count=" << count << ")";
3257 while (count--) {
3258 AllocRecord* record = &recent_allocation_records_[i];
3259
Elliott Hughesa8f93cb2012-06-08 17:08:48 -07003260 LOG(INFO) << StringPrintf(" Thread %-2d %6zd bytes ", record->thin_lock_id, record->byte_count)
Elliott Hughes545a0642011-11-08 19:10:03 -08003261 << PrettyClass(record->type);
3262
3263 for (size_t stack_frame = 0; stack_frame < kMaxAllocRecordStackDepth; ++stack_frame) {
Mathieu Chartier66f19252012-09-18 08:57:04 -07003264 const AbstractMethod* m = record->stack[stack_frame].method;
Elliott Hughes545a0642011-11-08 19:10:03 -08003265 if (m == NULL) {
3266 break;
3267 }
3268 LOG(INFO) << " " << PrettyMethod(m) << " line " << record->stack[stack_frame].LineNumber();
3269 }
3270
3271 // pause periodically to help logcat catch up
3272 if ((count % 5) == 0) {
3273 usleep(40000);
3274 }
3275
3276 i = (i + 1) & (kNumAllocRecords-1);
3277 }
3278}
3279
3280class StringTable {
3281 public:
3282 StringTable() {
3283 }
3284
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08003285 void Add(const char* s) {
Elliott Hughes545a0642011-11-08 19:10:03 -08003286 table_.insert(s);
3287 }
3288
Elliott Hughesa8f93cb2012-06-08 17:08:48 -07003289 size_t IndexOf(const char* s) const {
3290 typedef std::set<std::string>::const_iterator It; // TODO: C++0x auto
3291 It it = table_.find(s);
3292 if (it == table_.end()) {
3293 LOG(FATAL) << "IndexOf(\"" << s << "\") failed";
3294 }
3295 return std::distance(table_.begin(), it);
Elliott Hughes545a0642011-11-08 19:10:03 -08003296 }
3297
Elliott Hughesa8f93cb2012-06-08 17:08:48 -07003298 size_t Size() const {
Elliott Hughes545a0642011-11-08 19:10:03 -08003299 return table_.size();
3300 }
3301
Elliott Hughesa8f93cb2012-06-08 17:08:48 -07003302 void WriteTo(std::vector<uint8_t>& bytes) const {
3303 typedef std::set<std::string>::const_iterator It; // TODO: C++0x auto
Elliott Hughes545a0642011-11-08 19:10:03 -08003304 for (It it = table_.begin(); it != table_.end(); ++it) {
Elliott Hughesa8f93cb2012-06-08 17:08:48 -07003305 const char* s = (*it).c_str();
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08003306 size_t s_len = CountModifiedUtf8Chars(s);
3307 UniquePtr<uint16_t> s_utf16(new uint16_t[s_len]);
3308 ConvertModifiedUtf8ToUtf16(s_utf16.get(), s);
3309 JDWP::AppendUtf16BE(bytes, s_utf16.get(), s_len);
Elliott Hughes545a0642011-11-08 19:10:03 -08003310 }
3311 }
3312
3313 private:
Elliott Hughesa8f93cb2012-06-08 17:08:48 -07003314 std::set<std::string> table_;
Elliott Hughes545a0642011-11-08 19:10:03 -08003315 DISALLOW_COPY_AND_ASSIGN(StringTable);
3316};
3317
3318/*
3319 * The data we send to DDMS contains everything we have recorded.
3320 *
3321 * Message header (all values big-endian):
3322 * (1b) message header len (to allow future expansion); includes itself
3323 * (1b) entry header len
3324 * (1b) stack frame len
3325 * (2b) number of entries
3326 * (4b) offset to string table from start of message
3327 * (2b) number of class name strings
3328 * (2b) number of method name strings
3329 * (2b) number of source file name strings
3330 * For each entry:
3331 * (4b) total allocation size
3332 * (2b) threadId
3333 * (2b) allocated object's class name index
3334 * (1b) stack depth
3335 * For each stack frame:
3336 * (2b) method's class name
3337 * (2b) method name
3338 * (2b) method source file
3339 * (2b) line number, clipped to 32767; -2 if native; -1 if no source
3340 * (xb) class name strings
3341 * (xb) method name strings
3342 * (xb) source file strings
3343 *
3344 * As with other DDM traffic, strings are sent as a 4-byte length
3345 * followed by UTF-16 data.
3346 *
3347 * We send up 16-bit unsigned indexes into string tables. In theory there
3348 * can be (kMaxAllocRecordStackDepth * kNumAllocRecords) unique strings in
3349 * each table, but in practice there should be far fewer.
3350 *
3351 * The chief reason for using a string table here is to keep the size of
3352 * the DDMS message to a minimum. This is partly to make the protocol
3353 * efficient, but also because we have to form the whole thing up all at
3354 * once in a memory buffer.
3355 *
3356 * We use separate string tables for class names, method names, and source
3357 * files to keep the indexes small. There will generally be no overlap
3358 * between the contents of these tables.
3359 */
3360jbyteArray Dbg::GetRecentAllocations() {
3361 if (false) {
3362 DumpRecentAllocations();
3363 }
3364
Ian Rogers50b35e22012-10-04 10:09:15 -07003365 Thread* self = Thread::Current();
3366 MutexLock mu(self, gAllocTrackerLock);
Elliott Hughes545a0642011-11-08 19:10:03 -08003367
Elliott Hughesa8f93cb2012-06-08 17:08:48 -07003368 //
3369 // Part 1: generate string tables.
3370 //
Elliott Hughes545a0642011-11-08 19:10:03 -08003371 StringTable class_names;
3372 StringTable method_names;
3373 StringTable filenames;
3374
3375 int count = gAllocRecordCount;
Elliott Hughesa8f93cb2012-06-08 17:08:48 -07003376 int idx = HeadIndex();
Elliott Hughes545a0642011-11-08 19:10:03 -08003377 while (count--) {
3378 AllocRecord* record = &recent_allocation_records_[idx];
3379
Elliott Hughes91250e02011-12-13 22:30:35 -08003380 class_names.Add(ClassHelper(record->type).GetDescriptor());
Elliott Hughes545a0642011-11-08 19:10:03 -08003381
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08003382 MethodHelper mh;
Elliott Hughes545a0642011-11-08 19:10:03 -08003383 for (size_t i = 0; i < kMaxAllocRecordStackDepth; i++) {
Mathieu Chartier66f19252012-09-18 08:57:04 -07003384 AbstractMethod* m = record->stack[i].method;
Elliott Hughes545a0642011-11-08 19:10:03 -08003385 if (m != NULL) {
Ian Rogersba377812012-05-28 21:16:29 -07003386 mh.ChangeMethod(m);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08003387 class_names.Add(mh.GetDeclaringClassDescriptor());
3388 method_names.Add(mh.GetName());
3389 filenames.Add(mh.GetDeclaringClassSourceFile());
Elliott Hughes545a0642011-11-08 19:10:03 -08003390 }
3391 }
3392
3393 idx = (idx + 1) & (kNumAllocRecords-1);
3394 }
3395
3396 LOG(INFO) << "allocation records: " << gAllocRecordCount;
3397
Elliott Hughesa8f93cb2012-06-08 17:08:48 -07003398 //
3399 // Part 2: allocate a buffer and generate the output.
3400 //
Elliott Hughes545a0642011-11-08 19:10:03 -08003401 std::vector<uint8_t> bytes;
3402
3403 // (1b) message header len (to allow future expansion); includes itself
3404 // (1b) entry header len
3405 // (1b) stack frame len
3406 const int kMessageHeaderLen = 15;
3407 const int kEntryHeaderLen = 9;
3408 const int kStackFrameLen = 8;
3409 JDWP::Append1BE(bytes, kMessageHeaderLen);
3410 JDWP::Append1BE(bytes, kEntryHeaderLen);
3411 JDWP::Append1BE(bytes, kStackFrameLen);
3412
3413 // (2b) number of entries
3414 // (4b) offset to string table from start of message
3415 // (2b) number of class name strings
3416 // (2b) number of method name strings
3417 // (2b) number of source file name strings
3418 JDWP::Append2BE(bytes, gAllocRecordCount);
3419 size_t string_table_offset = bytes.size();
3420 JDWP::Append4BE(bytes, 0); // We'll patch this later...
3421 JDWP::Append2BE(bytes, class_names.Size());
3422 JDWP::Append2BE(bytes, method_names.Size());
3423 JDWP::Append2BE(bytes, filenames.Size());
3424
3425 count = gAllocRecordCount;
Elliott Hughesa8f93cb2012-06-08 17:08:48 -07003426 idx = HeadIndex();
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08003427 ClassHelper kh;
Elliott Hughes545a0642011-11-08 19:10:03 -08003428 while (count--) {
3429 // For each entry:
3430 // (4b) total allocation size
3431 // (2b) thread id
3432 // (2b) allocated object's class name index
3433 // (1b) stack depth
3434 AllocRecord* record = &recent_allocation_records_[idx];
3435 size_t stack_depth = record->GetDepth();
Elliott Hughesa8f93cb2012-06-08 17:08:48 -07003436 kh.ChangeClass(record->type);
3437 size_t allocated_object_class_name_index = class_names.IndexOf(kh.GetDescriptor());
Elliott Hughes545a0642011-11-08 19:10:03 -08003438 JDWP::Append4BE(bytes, record->byte_count);
3439 JDWP::Append2BE(bytes, record->thin_lock_id);
Elliott Hughesa8f93cb2012-06-08 17:08:48 -07003440 JDWP::Append2BE(bytes, allocated_object_class_name_index);
Elliott Hughes545a0642011-11-08 19:10:03 -08003441 JDWP::Append1BE(bytes, stack_depth);
3442
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08003443 MethodHelper mh;
Elliott Hughes545a0642011-11-08 19:10:03 -08003444 for (size_t stack_frame = 0; stack_frame < stack_depth; ++stack_frame) {
3445 // For each stack frame:
3446 // (2b) method's class name
3447 // (2b) method name
3448 // (2b) method source file
3449 // (2b) line number, clipped to 32767; -2 if native; -1 if no source
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08003450 mh.ChangeMethod(record->stack[stack_frame].method);
Elliott Hughesa8f93cb2012-06-08 17:08:48 -07003451 size_t class_name_index = class_names.IndexOf(mh.GetDeclaringClassDescriptor());
3452 size_t method_name_index = method_names.IndexOf(mh.GetName());
3453 size_t file_name_index = filenames.IndexOf(mh.GetDeclaringClassSourceFile());
3454 JDWP::Append2BE(bytes, class_name_index);
3455 JDWP::Append2BE(bytes, method_name_index);
3456 JDWP::Append2BE(bytes, file_name_index);
Elliott Hughes545a0642011-11-08 19:10:03 -08003457 JDWP::Append2BE(bytes, record->stack[stack_frame].LineNumber());
3458 }
3459
3460 idx = (idx + 1) & (kNumAllocRecords-1);
3461 }
3462
3463 // (xb) class name strings
3464 // (xb) method name strings
3465 // (xb) source file strings
3466 JDWP::Set4BE(&bytes[string_table_offset], bytes.size());
3467 class_names.WriteTo(bytes);
3468 method_names.WriteTo(bytes);
3469 filenames.WriteTo(bytes);
3470
Ian Rogers50b35e22012-10-04 10:09:15 -07003471 JNIEnv* env = self->GetJniEnv();
Elliott Hughes545a0642011-11-08 19:10:03 -08003472 jbyteArray result = env->NewByteArray(bytes.size());
3473 if (result != NULL) {
3474 env->SetByteArrayRegion(result, 0, bytes.size(), reinterpret_cast<const jbyte*>(&bytes[0]));
3475 }
3476 return result;
3477}
3478
Elliott Hughes872d4ec2011-10-21 17:07:15 -07003479} // namespace art