blob: 1ddb525f66eb97eb8da989cf41312ae137102c11 [file] [log] [blame]
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001/*
2 * Copyright (C) 2008 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17#include "debugger.h"
18
Elliott Hughes3bb81562011-10-21 18:52:59 -070019#include <sys/uio.h>
20
Elliott Hughes545a0642011-11-08 19:10:03 -080021#include <set>
22
23#include "class_linker.h"
Elliott Hughes1bba14f2011-12-01 18:00:36 -080024#include "class_loader.h"
Ian Rogers776ac1f2012-04-13 23:36:36 -070025#include "dex_instruction.h"
Mathieu Chartier1c23e1e2012-10-12 14:14:11 -070026#include "gc/large_object_space.h"
27#include "gc/space.h"
Ian Rogers2bcb4a42012-11-08 10:39:18 -080028#include "oat/runtime/context.h"
Ian Rogers6d4d9fc2011-11-30 16:24:48 -080029#include "object_utils.h"
Elliott Hughesa0e18062012-04-13 15:59:59 -070030#include "safe_map.h"
Elliott Hughes6a5bd492011-10-28 14:33:57 -070031#include "ScopedLocalRef.h"
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -070032#include "ScopedPrimitiveArray.h"
Ian Rogers00f7d0e2012-07-19 15:28:27 -070033#include "scoped_thread_state_change.h"
Ian Rogers1f539342012-10-03 21:09:42 -070034#include "sirt_ref.h"
Elliott Hughes47fce012011-10-25 18:37:19 -070035#include "stack_indirect_reference_table.h"
Elliott Hughes475fc232011-10-25 15:00:35 -070036#include "thread_list.h"
Elliott Hugheseac76672012-05-24 21:56:51 -070037#include "well_known_classes.h"
Elliott Hughes475fc232011-10-25 15:00:35 -070038
Elliott Hughes872d4ec2011-10-21 17:07:15 -070039namespace art {
40
Elliott Hughes545a0642011-11-08 19:10:03 -080041static const size_t kMaxAllocRecordStackDepth = 16; // Max 255.
42static const size_t kNumAllocRecords = 512; // Must be power of 2.
43
Elliott Hughes436e3722012-02-17 20:01:47 -080044static const uintptr_t kInvalidId = 1;
45static const Object* kInvalidObject = reinterpret_cast<Object*>(kInvalidId);
46
Elliott Hughes475fc232011-10-25 15:00:35 -070047class ObjectRegistry {
48 public:
49 ObjectRegistry() : lock_("ObjectRegistry lock") {
50 }
51
52 JDWP::ObjectId Add(Object* o) {
53 if (o == NULL) {
54 return 0;
55 }
56 JDWP::ObjectId id = static_cast<JDWP::ObjectId>(reinterpret_cast<uintptr_t>(o));
Ian Rogers50b35e22012-10-04 10:09:15 -070057 MutexLock mu(Thread::Current(), lock_);
Elliott Hughesa0e18062012-04-13 15:59:59 -070058 map_.Overwrite(id, o);
Elliott Hughes475fc232011-10-25 15:00:35 -070059 return id;
60 }
61
Elliott Hughes234ab152011-10-26 14:02:26 -070062 void Clear() {
Ian Rogers50b35e22012-10-04 10:09:15 -070063 MutexLock mu(Thread::Current(), lock_);
Elliott Hughes234ab152011-10-26 14:02:26 -070064 LOG(DEBUG) << "Debugger has detached; object registry had " << map_.size() << " entries";
65 map_.clear();
66 }
67
Elliott Hughes475fc232011-10-25 15:00:35 -070068 bool Contains(JDWP::ObjectId id) {
Ian Rogers50b35e22012-10-04 10:09:15 -070069 MutexLock mu(Thread::Current(), lock_);
Elliott Hughes475fc232011-10-25 15:00:35 -070070 return map_.find(id) != map_.end();
71 }
72
Elliott Hughesa2155262011-11-16 16:26:58 -080073 template<typename T> T Get(JDWP::ObjectId id) {
Elliott Hughes436e3722012-02-17 20:01:47 -080074 if (id == 0) {
75 return NULL;
76 }
77
Ian Rogers50b35e22012-10-04 10:09:15 -070078 MutexLock mu(Thread::Current(), lock_);
Elliott Hughesa0e18062012-04-13 15:59:59 -070079 typedef SafeMap<JDWP::ObjectId, Object*>::iterator It; // C++0x auto
Elliott Hughesa2155262011-11-16 16:26:58 -080080 It it = map_.find(id);
Elliott Hughes436e3722012-02-17 20:01:47 -080081 return (it != map_.end()) ? reinterpret_cast<T>(it->second) : reinterpret_cast<T>(kInvalidId);
Elliott Hughesa2155262011-11-16 16:26:58 -080082 }
83
Elliott Hughesbfe487b2011-10-26 15:48:55 -070084 void VisitRoots(Heap::RootVisitor* visitor, void* arg) {
Ian Rogers50b35e22012-10-04 10:09:15 -070085 MutexLock mu(Thread::Current(), lock_);
Elliott Hughesa0e18062012-04-13 15:59:59 -070086 typedef SafeMap<JDWP::ObjectId, Object*>::iterator It; // C++0x auto
Elliott Hughesbfe487b2011-10-26 15:48:55 -070087 for (It it = map_.begin(); it != map_.end(); ++it) {
88 visitor(it->second, arg);
89 }
90 }
91
Elliott Hughes475fc232011-10-25 15:00:35 -070092 private:
Ian Rogers00f7d0e2012-07-19 15:28:27 -070093 Mutex lock_ DEFAULT_MUTEX_ACQUIRED_AFTER;
Elliott Hughesa0e18062012-04-13 15:59:59 -070094 SafeMap<JDWP::ObjectId, Object*> map_;
Elliott Hughes475fc232011-10-25 15:00:35 -070095};
96
Elliott Hughes545a0642011-11-08 19:10:03 -080097struct AllocRecordStackTraceElement {
Mathieu Chartier66f19252012-09-18 08:57:04 -070098 AbstractMethod* method;
Ian Rogers0399dde2012-06-06 17:09:28 -070099 uint32_t dex_pc;
Elliott Hughes545a0642011-11-08 19:10:03 -0800100
Ian Rogersb726dcb2012-09-05 08:57:23 -0700101 int32_t LineNumber() const SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Ian Rogers0399dde2012-06-06 17:09:28 -0700102 return MethodHelper(method).GetLineNumFromDexPC(dex_pc);
Elliott Hughes545a0642011-11-08 19:10:03 -0800103 }
104};
105
106struct AllocRecord {
107 Class* type;
108 size_t byte_count;
109 uint16_t thin_lock_id;
110 AllocRecordStackTraceElement stack[kMaxAllocRecordStackDepth]; // Unused entries have NULL method.
111
112 size_t GetDepth() {
113 size_t depth = 0;
114 while (depth < kMaxAllocRecordStackDepth && stack[depth].method != NULL) {
115 ++depth;
116 }
117 return depth;
118 }
119};
120
Elliott Hughes86964332012-02-15 19:37:42 -0800121struct Breakpoint {
Mathieu Chartier66f19252012-09-18 08:57:04 -0700122 AbstractMethod* method;
Elliott Hughesa656a0f2012-02-21 18:03:44 -0800123 uint32_t dex_pc;
Mathieu Chartier66f19252012-09-18 08:57:04 -0700124 Breakpoint(AbstractMethod* method, uint32_t dex_pc) : method(method), dex_pc(dex_pc) {}
Elliott Hughes86964332012-02-15 19:37:42 -0800125};
126
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700127static std::ostream& operator<<(std::ostream& os, const Breakpoint& rhs)
Ian Rogersb726dcb2012-09-05 08:57:23 -0700128 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Elliott Hughes229feb72012-02-23 13:33:29 -0800129 os << StringPrintf("Breakpoint[%s @%#x]", PrettyMethod(rhs.method).c_str(), rhs.dex_pc);
Elliott Hughes86964332012-02-15 19:37:42 -0800130 return os;
131}
132
133struct SingleStepControl {
134 // Are we single-stepping right now?
135 bool is_active;
136 Thread* thread;
137
138 JDWP::JdwpStepSize step_size;
139 JDWP::JdwpStepDepth step_depth;
140
Mathieu Chartier66f19252012-09-18 08:57:04 -0700141 const AbstractMethod* method;
Elliott Hughes2435a572012-02-17 16:07:41 -0800142 int32_t line_number; // Or -1 for native methods.
143 std::set<uint32_t> dex_pcs;
Elliott Hughes86964332012-02-15 19:37:42 -0800144 int stack_depth;
145};
146
Elliott Hughes4ffd3132011-10-24 12:06:42 -0700147// JDWP is allowed unless the Zygote forbids it.
148static bool gJdwpAllowed = true;
149
Elliott Hughesc0f09332012-03-26 13:27:06 -0700150// Was there a -Xrunjdwp or -agentlib:jdwp= argument on the command line?
Elliott Hughes3bb81562011-10-21 18:52:59 -0700151static bool gJdwpConfigured = false;
152
Elliott Hughesc0f09332012-03-26 13:27:06 -0700153// Broken-down JDWP options. (Only valid if IsJdwpConfigured() is true.)
Elliott Hughes376a7a02011-10-24 18:35:55 -0700154static JDWP::JdwpOptions gJdwpOptions;
Elliott Hughes3bb81562011-10-21 18:52:59 -0700155
156// Runtime JDWP state.
157static JDWP::JdwpState* gJdwpState = NULL;
158static bool gDebuggerConnected; // debugger or DDMS is connected.
159static bool gDebuggerActive; // debugger is making requests.
Elliott Hughes86964332012-02-15 19:37:42 -0800160static bool gDisposed; // debugger called VirtualMachine.Dispose, so we should drop the connection.
Elliott Hughes3bb81562011-10-21 18:52:59 -0700161
Elliott Hughes47fce012011-10-25 18:37:19 -0700162static bool gDdmThreadNotification = false;
163
Elliott Hughes767a1472011-10-26 18:49:02 -0700164// DDMS GC-related settings.
165static Dbg::HpifWhen gDdmHpifWhen = Dbg::HPIF_WHEN_NEVER;
166static Dbg::HpsgWhen gDdmHpsgWhen = Dbg::HPSG_WHEN_NEVER;
167static Dbg::HpsgWhat gDdmHpsgWhat;
168static Dbg::HpsgWhen gDdmNhsgWhen = Dbg::HPSG_WHEN_NEVER;
169static Dbg::HpsgWhat gDdmNhsgWhat;
170
Elliott Hughes475fc232011-10-25 15:00:35 -0700171static ObjectRegistry* gRegistry = NULL;
172
Elliott Hughes545a0642011-11-08 19:10:03 -0800173// Recent allocation tracking.
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700174static Mutex gAllocTrackerLock DEFAULT_MUTEX_ACQUIRED_AFTER ("AllocTracker lock");
Elliott Hughesf8349362012-06-18 15:00:06 -0700175AllocRecord* Dbg::recent_allocation_records_ PT_GUARDED_BY(gAllocTrackerLock) = NULL; // TODO: CircularBuffer<AllocRecord>
176static size_t gAllocRecordHead GUARDED_BY(gAllocTrackerLock) = 0;
177static size_t gAllocRecordCount GUARDED_BY(gAllocTrackerLock) = 0;
Elliott Hughes545a0642011-11-08 19:10:03 -0800178
Elliott Hughes86964332012-02-15 19:37:42 -0800179// Breakpoints and single-stepping.
jeffhao09bfc6a2012-12-11 18:11:43 -0800180static std::vector<Breakpoint> gBreakpoints GUARDED_BY(Locks::breakpoint_lock_);
181static SingleStepControl gSingleStepControl GUARDED_BY(Locks::breakpoint_lock_);
Elliott Hughes86964332012-02-15 19:37:42 -0800182
Mathieu Chartier66f19252012-09-18 08:57:04 -0700183static bool IsBreakpoint(AbstractMethod* m, uint32_t dex_pc)
jeffhao09bfc6a2012-12-11 18:11:43 -0800184 LOCKS_EXCLUDED(Locks::breakpoint_lock_)
Ian Rogersb726dcb2012-09-05 08:57:23 -0700185 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
jeffhao09bfc6a2012-12-11 18:11:43 -0800186 MutexLock mu(Thread::Current(), *Locks::breakpoint_lock_);
Elliott Hughes86964332012-02-15 19:37:42 -0800187 for (size_t i = 0; i < gBreakpoints.size(); ++i) {
Elliott Hughesa656a0f2012-02-21 18:03:44 -0800188 if (gBreakpoints[i].method == m && gBreakpoints[i].dex_pc == dex_pc) {
Elliott Hughes86964332012-02-15 19:37:42 -0800189 VLOG(jdwp) << "Hit breakpoint #" << i << ": " << gBreakpoints[i];
190 return true;
191 }
192 }
193 return false;
194}
195
Elliott Hughes9e0c1752013-01-09 14:02:58 -0800196static bool IsSuspendedForDebugger(ScopedObjectAccessUnchecked& soa, Thread* thread) {
197 MutexLock mu(soa.Self(), *Locks::thread_suspend_count_lock_);
198 // A thread may be suspended for GC; in this code, we really want to know whether
199 // there's a debugger suspension active.
200 return thread->IsSuspended() && thread->GetDebugSuspendCount() > 0;
201}
202
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700203static Array* DecodeArray(JDWP::RefTypeId id, JDWP::JdwpError& status)
Ian Rogersb726dcb2012-09-05 08:57:23 -0700204 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Elliott Hughes436e3722012-02-17 20:01:47 -0800205 Object* o = gRegistry->Get<Object*>(id);
206 if (o == NULL || o == kInvalidObject) {
207 status = JDWP::ERR_INVALID_OBJECT;
208 return NULL;
209 }
210 if (!o->IsArrayInstance()) {
211 status = JDWP::ERR_INVALID_ARRAY;
212 return NULL;
213 }
214 status = JDWP::ERR_NONE;
215 return o->AsArray();
216}
217
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700218static Class* DecodeClass(JDWP::RefTypeId id, JDWP::JdwpError& status)
Ian Rogersb726dcb2012-09-05 08:57:23 -0700219 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Elliott Hughes436e3722012-02-17 20:01:47 -0800220 Object* o = gRegistry->Get<Object*>(id);
221 if (o == NULL || o == kInvalidObject) {
222 status = JDWP::ERR_INVALID_OBJECT;
223 return NULL;
224 }
225 if (!o->IsClass()) {
226 status = JDWP::ERR_INVALID_CLASS;
227 return NULL;
228 }
229 status = JDWP::ERR_NONE;
230 return o->AsClass();
231}
232
Elliott Hughes221229c2013-01-08 18:17:50 -0800233static JDWP::JdwpError DecodeThread(ScopedObjectAccessUnchecked& soa, JDWP::ObjectId thread_id, Thread*& thread)
jeffhaoa77f0f62012-12-05 17:19:31 -0800234 EXCLUSIVE_LOCKS_REQUIRED(Locks::thread_list_lock_)
Ian Rogersb726dcb2012-09-05 08:57:23 -0700235 LOCKS_EXCLUDED(Locks::thread_suspend_count_lock_)
236 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Elliott Hughes221229c2013-01-08 18:17:50 -0800237 Object* thread_peer = gRegistry->Get<Object*>(thread_id);
Elliott Hughes436e3722012-02-17 20:01:47 -0800238 if (thread_peer == NULL || thread_peer == kInvalidObject) {
Elliott Hughes221229c2013-01-08 18:17:50 -0800239 // This isn't even an object.
240 return JDWP::ERR_INVALID_OBJECT;
Elliott Hughes436e3722012-02-17 20:01:47 -0800241 }
Elliott Hughes221229c2013-01-08 18:17:50 -0800242
243 Class* java_lang_Thread = soa.Decode<Class*>(WellKnownClasses::java_lang_Thread);
244 if (!java_lang_Thread->IsAssignableFrom(thread_peer->GetClass())) {
245 // This isn't a thread.
246 return JDWP::ERR_INVALID_THREAD;
247 }
248
249 thread = Thread::FromManagedThread(soa, thread_peer);
250 if (thread == NULL) {
251 // This is a java.lang.Thread without a Thread*. Must be a zombie.
252 return JDWP::ERR_THREAD_NOT_ALIVE;
253 }
254 return JDWP::ERR_NONE;
Elliott Hughes436e3722012-02-17 20:01:47 -0800255}
256
Elliott Hughes24437992011-11-30 14:49:33 -0800257static JDWP::JdwpTag BasicTagFromDescriptor(const char* descriptor) {
258 // JDWP deliberately uses the descriptor characters' ASCII values for its enum.
259 // Note that by "basic" we mean that we don't get more specific than JT_OBJECT.
260 return static_cast<JDWP::JdwpTag>(descriptor[0]);
261}
262
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700263static JDWP::JdwpTag TagFromClass(Class* c)
Ian Rogersb726dcb2012-09-05 08:57:23 -0700264 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Elliott Hughes86b00102011-12-05 17:54:26 -0800265 CHECK(c != NULL);
Elliott Hughes24437992011-11-30 14:49:33 -0800266 if (c->IsArrayClass()) {
267 return JDWP::JT_ARRAY;
268 }
269
Elliott Hughes3d30d9b2011-12-07 17:35:48 -0800270 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
Elliott Hughes24437992011-11-30 14:49:33 -0800271 if (c->IsStringClass()) {
272 return JDWP::JT_STRING;
273 } else if (c->IsClassClass()) {
274 return JDWP::JT_CLASS_OBJECT;
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -0800275 } else if (class_linker->FindSystemClass("Ljava/lang/Thread;")->IsAssignableFrom(c)) {
Elliott Hughes24437992011-11-30 14:49:33 -0800276 return JDWP::JT_THREAD;
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -0800277 } else if (class_linker->FindSystemClass("Ljava/lang/ThreadGroup;")->IsAssignableFrom(c)) {
Elliott Hughes24437992011-11-30 14:49:33 -0800278 return JDWP::JT_THREAD_GROUP;
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -0800279 } else if (class_linker->FindSystemClass("Ljava/lang/ClassLoader;")->IsAssignableFrom(c)) {
Elliott Hughes24437992011-11-30 14:49:33 -0800280 return JDWP::JT_CLASS_LOADER;
Elliott Hughes24437992011-11-30 14:49:33 -0800281 } else {
282 return JDWP::JT_OBJECT;
283 }
284}
285
286/*
287 * Objects declared to hold Object might actually hold a more specific
288 * type. The debugger may take a special interest in these (e.g. it
289 * wants to display the contents of Strings), so we want to return an
290 * appropriate tag.
291 *
292 * Null objects are tagged JT_OBJECT.
293 */
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700294static JDWP::JdwpTag TagFromObject(const Object* o)
Ian Rogersb726dcb2012-09-05 08:57:23 -0700295 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Elliott Hughes24437992011-11-30 14:49:33 -0800296 return (o == NULL) ? JDWP::JT_OBJECT : TagFromClass(o->GetClass());
297}
298
299static bool IsPrimitiveTag(JDWP::JdwpTag tag) {
300 switch (tag) {
301 case JDWP::JT_BOOLEAN:
302 case JDWP::JT_BYTE:
303 case JDWP::JT_CHAR:
304 case JDWP::JT_FLOAT:
305 case JDWP::JT_DOUBLE:
306 case JDWP::JT_INT:
307 case JDWP::JT_LONG:
308 case JDWP::JT_SHORT:
309 case JDWP::JT_VOID:
310 return true;
311 default:
312 return false;
313 }
314}
315
Elliott Hughes3bb81562011-10-21 18:52:59 -0700316/*
317 * Handle one of the JDWP name/value pairs.
318 *
319 * JDWP options are:
320 * help: if specified, show help message and bail
321 * transport: may be dt_socket or dt_shmem
322 * address: for dt_socket, "host:port", or just "port" when listening
323 * server: if "y", wait for debugger to attach; if "n", attach to debugger
324 * timeout: how long to wait for debugger to connect / listen
325 *
326 * Useful with server=n (these aren't supported yet):
327 * onthrow=<exception-name>: connect to debugger when exception thrown
328 * onuncaught=y|n: connect to debugger when uncaught exception thrown
329 * launch=<command-line>: launch the debugger itself
330 *
331 * The "transport" option is required, as is "address" if server=n.
332 */
333static bool ParseJdwpOption(const std::string& name, const std::string& value) {
334 if (name == "transport") {
335 if (value == "dt_socket") {
Elliott Hughes376a7a02011-10-24 18:35:55 -0700336 gJdwpOptions.transport = JDWP::kJdwpTransportSocket;
Elliott Hughes3bb81562011-10-21 18:52:59 -0700337 } else if (value == "dt_android_adb") {
Elliott Hughes376a7a02011-10-24 18:35:55 -0700338 gJdwpOptions.transport = JDWP::kJdwpTransportAndroidAdb;
Elliott Hughes3bb81562011-10-21 18:52:59 -0700339 } else {
340 LOG(ERROR) << "JDWP transport not supported: " << value;
341 return false;
342 }
343 } else if (name == "server") {
344 if (value == "n") {
Elliott Hughes376a7a02011-10-24 18:35:55 -0700345 gJdwpOptions.server = false;
Elliott Hughes3bb81562011-10-21 18:52:59 -0700346 } else if (value == "y") {
Elliott Hughes376a7a02011-10-24 18:35:55 -0700347 gJdwpOptions.server = true;
Elliott Hughes3bb81562011-10-21 18:52:59 -0700348 } else {
349 LOG(ERROR) << "JDWP option 'server' must be 'y' or 'n'";
350 return false;
351 }
352 } else if (name == "suspend") {
353 if (value == "n") {
Elliott Hughes376a7a02011-10-24 18:35:55 -0700354 gJdwpOptions.suspend = false;
Elliott Hughes3bb81562011-10-21 18:52:59 -0700355 } else if (value == "y") {
Elliott Hughes376a7a02011-10-24 18:35:55 -0700356 gJdwpOptions.suspend = true;
Elliott Hughes3bb81562011-10-21 18:52:59 -0700357 } else {
358 LOG(ERROR) << "JDWP option 'suspend' must be 'y' or 'n'";
359 return false;
360 }
361 } else if (name == "address") {
362 /* this is either <port> or <host>:<port> */
363 std::string port_string;
Elliott Hughes376a7a02011-10-24 18:35:55 -0700364 gJdwpOptions.host.clear();
Elliott Hughes3bb81562011-10-21 18:52:59 -0700365 std::string::size_type colon = value.find(':');
366 if (colon != std::string::npos) {
Elliott Hughes376a7a02011-10-24 18:35:55 -0700367 gJdwpOptions.host = value.substr(0, colon);
Elliott Hughes3bb81562011-10-21 18:52:59 -0700368 port_string = value.substr(colon + 1);
369 } else {
370 port_string = value;
371 }
372 if (port_string.empty()) {
373 LOG(ERROR) << "JDWP address missing port: " << value;
374 return false;
375 }
376 char* end;
Elliott Hughesba8eee12012-01-24 20:25:24 -0800377 uint64_t port = strtoul(port_string.c_str(), &end, 10);
378 if (*end != '\0' || port > 0xffff) {
Elliott Hughes3bb81562011-10-21 18:52:59 -0700379 LOG(ERROR) << "JDWP address has junk in port field: " << value;
380 return false;
381 }
Elliott Hughes376a7a02011-10-24 18:35:55 -0700382 gJdwpOptions.port = port;
Elliott Hughes3bb81562011-10-21 18:52:59 -0700383 } else if (name == "launch" || name == "onthrow" || name == "oncaught" || name == "timeout") {
384 /* valid but unsupported */
385 LOG(INFO) << "Ignoring JDWP option '" << name << "'='" << value << "'";
386 } else {
387 LOG(INFO) << "Ignoring unrecognized JDWP option '" << name << "'='" << value << "'";
388 }
389
390 return true;
391}
392
393/*
394 * Parse the latter half of a -Xrunjdwp/-agentlib:jdwp= string, e.g.:
395 * "transport=dt_socket,address=8000,server=y,suspend=n"
396 */
397bool Dbg::ParseJdwpOptions(const std::string& options) {
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -0800398 VLOG(jdwp) << "ParseJdwpOptions: " << options;
Elliott Hughes47fce012011-10-25 18:37:19 -0700399
Elliott Hughes3bb81562011-10-21 18:52:59 -0700400 std::vector<std::string> pairs;
401 Split(options, ',', pairs);
402
403 for (size_t i = 0; i < pairs.size(); ++i) {
404 std::string::size_type equals = pairs[i].find('=');
405 if (equals == std::string::npos) {
406 LOG(ERROR) << "Can't parse JDWP option '" << pairs[i] << "' in '" << options << "'";
407 return false;
408 }
409 ParseJdwpOption(pairs[i].substr(0, equals), pairs[i].substr(equals + 1));
410 }
411
Elliott Hughes376a7a02011-10-24 18:35:55 -0700412 if (gJdwpOptions.transport == JDWP::kJdwpTransportUnknown) {
Elliott Hughes3bb81562011-10-21 18:52:59 -0700413 LOG(ERROR) << "Must specify JDWP transport: " << options;
414 }
Elliott Hughes376a7a02011-10-24 18:35:55 -0700415 if (!gJdwpOptions.server && (gJdwpOptions.host.empty() || gJdwpOptions.port == 0)) {
Elliott Hughes3bb81562011-10-21 18:52:59 -0700416 LOG(ERROR) << "Must specify JDWP host and port when server=n: " << options;
417 return false;
418 }
419
420 gJdwpConfigured = true;
421 return true;
422}
423
Elliott Hughesd1cc8362011-10-24 16:58:50 -0700424void Dbg::StartJdwp() {
Elliott Hughesc0f09332012-03-26 13:27:06 -0700425 if (!gJdwpAllowed || !IsJdwpConfigured()) {
Elliott Hughes376a7a02011-10-24 18:35:55 -0700426 // No JDWP for you!
427 return;
428 }
429
Elliott Hughes475fc232011-10-25 15:00:35 -0700430 CHECK(gRegistry == NULL);
431 gRegistry = new ObjectRegistry;
432
Elliott Hughesd1cc8362011-10-24 16:58:50 -0700433 // Init JDWP if the debugger is enabled. This may connect out to a
434 // debugger, passively listen for a debugger, or block waiting for a
435 // debugger.
Elliott Hughes376a7a02011-10-24 18:35:55 -0700436 gJdwpState = JDWP::JdwpState::Create(&gJdwpOptions);
437 if (gJdwpState == NULL) {
Elliott Hughesf8a2df72011-12-01 12:19:54 -0800438 // We probably failed because some other process has the port already, which means that
439 // if we don't abort the user is likely to think they're talking to us when they're actually
440 // talking to that other process.
Elliott Hughes3d30d9b2011-12-07 17:35:48 -0800441 LOG(FATAL) << "Debugger thread failed to initialize";
Elliott Hughesd1cc8362011-10-24 16:58:50 -0700442 }
443
444 // If a debugger has already attached, send the "welcome" message.
445 // This may cause us to suspend all threads.
Elliott Hughes376a7a02011-10-24 18:35:55 -0700446 if (gJdwpState->IsActive()) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700447 ScopedObjectAccess soa(Thread::Current());
Elliott Hughes376a7a02011-10-24 18:35:55 -0700448 if (!gJdwpState->PostVMStart()) {
Elliott Hughes3d30d9b2011-12-07 17:35:48 -0800449 LOG(WARNING) << "Failed to post 'start' message to debugger";
Elliott Hughesd1cc8362011-10-24 16:58:50 -0700450 }
451 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700452}
453
Elliott Hughesd1cc8362011-10-24 16:58:50 -0700454void Dbg::StopJdwp() {
Elliott Hughes376a7a02011-10-24 18:35:55 -0700455 delete gJdwpState;
Elliott Hughes475fc232011-10-25 15:00:35 -0700456 delete gRegistry;
457 gRegistry = NULL;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700458}
459
Elliott Hughes767a1472011-10-26 18:49:02 -0700460void Dbg::GcDidFinish() {
461 if (gDdmHpifWhen != HPIF_WHEN_NEVER) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700462 ScopedObjectAccess soa(Thread::Current());
Elliott Hughes81ff3182012-03-23 20:35:56 -0700463 LOG(DEBUG) << "Sending heap info to DDM";
Elliott Hughes7162ad92011-10-27 14:08:42 -0700464 DdmSendHeapInfo(gDdmHpifWhen);
Elliott Hughes767a1472011-10-26 18:49:02 -0700465 }
466 if (gDdmHpsgWhen != HPSG_WHEN_NEVER) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700467 ScopedObjectAccess soa(Thread::Current());
Elliott Hughes81ff3182012-03-23 20:35:56 -0700468 LOG(DEBUG) << "Dumping heap to DDM";
Elliott Hughes6a5bd492011-10-28 14:33:57 -0700469 DdmSendHeapSegments(false);
Elliott Hughes767a1472011-10-26 18:49:02 -0700470 }
471 if (gDdmNhsgWhen != HPSG_WHEN_NEVER) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700472 ScopedObjectAccess soa(Thread::Current());
Elliott Hughes767a1472011-10-26 18:49:02 -0700473 LOG(DEBUG) << "Dumping native heap to DDM";
Elliott Hughes6a5bd492011-10-28 14:33:57 -0700474 DdmSendHeapSegments(true);
Elliott Hughes767a1472011-10-26 18:49:02 -0700475 }
476}
477
Elliott Hughes4ffd3132011-10-24 12:06:42 -0700478void Dbg::SetJdwpAllowed(bool allowed) {
479 gJdwpAllowed = allowed;
480}
481
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700482DebugInvokeReq* Dbg::GetInvokeReq() {
Elliott Hughes475fc232011-10-25 15:00:35 -0700483 return Thread::Current()->GetInvokeReq();
484}
485
486Thread* Dbg::GetDebugThread() {
487 return (gJdwpState != NULL) ? gJdwpState->GetDebugThread() : NULL;
488}
489
490void Dbg::ClearWaitForEventThread() {
491 gJdwpState->ClearWaitForEventThread();
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700492}
493
494void Dbg::Connected() {
Elliott Hughes3bb81562011-10-21 18:52:59 -0700495 CHECK(!gDebuggerConnected);
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -0800496 VLOG(jdwp) << "JDWP has attached";
Elliott Hughes3bb81562011-10-21 18:52:59 -0700497 gDebuggerConnected = true;
Elliott Hughes86964332012-02-15 19:37:42 -0800498 gDisposed = false;
499}
500
501void Dbg::Disposed() {
502 gDisposed = true;
503}
504
505bool Dbg::IsDisposed() {
506 return gDisposed;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700507}
508
Elliott Hughesc0f09332012-03-26 13:27:06 -0700509static void SetDebuggerUpdatesEnabledCallback(Thread* t, void* user_data) {
510 t->SetDebuggerUpdatesEnabled(*reinterpret_cast<bool*>(user_data));
511}
512
513static void SetDebuggerUpdatesEnabled(bool enabled) {
Ian Rogers50b35e22012-10-04 10:09:15 -0700514 MutexLock mu(Thread::Current(), *Locks::thread_list_lock_);
Elliott Hughesf8349362012-06-18 15:00:06 -0700515 Runtime::Current()->GetThreadList()->ForEach(SetDebuggerUpdatesEnabledCallback, &enabled);
Elliott Hughesc0f09332012-03-26 13:27:06 -0700516}
517
Elliott Hughesa2155262011-11-16 16:26:58 -0800518void Dbg::GoActive() {
519 // Enable all debugging features, including scans for breakpoints.
520 // This is a no-op if we're already active.
521 // Only called from the JDWP handler thread.
522 if (gDebuggerActive) {
523 return;
524 }
525
526 LOG(INFO) << "Debugger is active";
527
Elliott Hughesc0f09332012-03-26 13:27:06 -0700528 {
529 // TODO: dalvik only warned if there were breakpoints left over. clear in Dbg::Disconnected?
jeffhao09bfc6a2012-12-11 18:11:43 -0800530 MutexLock mu(Thread::Current(), *Locks::breakpoint_lock_);
Elliott Hughesc0f09332012-03-26 13:27:06 -0700531 CHECK_EQ(gBreakpoints.size(), 0U);
532 }
Elliott Hughesa2155262011-11-16 16:26:58 -0800533
534 gDebuggerActive = true;
Elliott Hughesc0f09332012-03-26 13:27:06 -0700535 SetDebuggerUpdatesEnabled(true);
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700536}
537
538void Dbg::Disconnected() {
Elliott Hughes234ab152011-10-26 14:02:26 -0700539 CHECK(gDebuggerConnected);
540
Elliott Hughesc0f09332012-03-26 13:27:06 -0700541 LOG(INFO) << "Debugger is no longer active";
Elliott Hughes234ab152011-10-26 14:02:26 -0700542
Elliott Hughesc0f09332012-03-26 13:27:06 -0700543 gDebuggerActive = false;
544 SetDebuggerUpdatesEnabled(false);
Elliott Hughes234ab152011-10-26 14:02:26 -0700545
546 gRegistry->Clear();
547 gDebuggerConnected = false;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700548}
549
Elliott Hughesc0f09332012-03-26 13:27:06 -0700550bool Dbg::IsDebuggerActive() {
Elliott Hughes3bb81562011-10-21 18:52:59 -0700551 return gDebuggerActive;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700552}
553
Elliott Hughesc0f09332012-03-26 13:27:06 -0700554bool Dbg::IsJdwpConfigured() {
Elliott Hughes3bb81562011-10-21 18:52:59 -0700555 return gJdwpConfigured;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700556}
557
558int64_t Dbg::LastDebuggerActivity() {
Elliott Hughesca951522011-12-05 12:01:32 -0800559 return gJdwpState->LastDebuggerActivity();
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700560}
561
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700562void Dbg::UndoDebuggerSuspensions() {
Elliott Hughes234ab152011-10-26 14:02:26 -0700563 Runtime::Current()->GetThreadList()->UndoDebuggerSuspensions();
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700564}
565
566void Dbg::Exit(int status) {
Elliott Hughes1bba14f2011-12-01 18:00:36 -0800567 exit(status); // This is all dalvik did.
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700568}
569
Elliott Hughesbfe487b2011-10-26 15:48:55 -0700570void Dbg::VisitRoots(Heap::RootVisitor* visitor, void* arg) {
571 if (gRegistry != NULL) {
572 gRegistry->VisitRoots(visitor, arg);
573 }
574}
575
Elliott Hughes88d63092013-01-09 09:55:54 -0800576std::string Dbg::GetClassName(JDWP::RefTypeId class_id) {
577 Object* o = gRegistry->Get<Object*>(class_id);
Elliott Hughes436e3722012-02-17 20:01:47 -0800578 if (o == NULL) {
579 return "NULL";
580 }
581 if (o == kInvalidObject) {
Elliott Hughes88d63092013-01-09 09:55:54 -0800582 return StringPrintf("invalid object %p", reinterpret_cast<void*>(class_id));
Elliott Hughes436e3722012-02-17 20:01:47 -0800583 }
584 if (!o->IsClass()) {
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -0800585 return StringPrintf("non-class %p", o); // This is only used for debugging output anyway.
586 }
Elliott Hughesc308a5d2012-02-16 17:12:06 -0800587 return DescriptorToName(ClassHelper(o->AsClass()).GetDescriptor());
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700588}
589
Elliott Hughes88d63092013-01-09 09:55:54 -0800590JDWP::JdwpError Dbg::GetClassObject(JDWP::RefTypeId id, JDWP::ObjectId& class_object_id) {
Elliott Hughes436e3722012-02-17 20:01:47 -0800591 JDWP::JdwpError status;
592 Class* c = DecodeClass(id, status);
593 if (c == NULL) {
594 return status;
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -0800595 }
Elliott Hughes88d63092013-01-09 09:55:54 -0800596 class_object_id = gRegistry->Add(c);
Elliott Hughes436e3722012-02-17 20:01:47 -0800597 return JDWP::ERR_NONE;
Elliott Hughes86964332012-02-15 19:37:42 -0800598}
599
Elliott Hughes88d63092013-01-09 09:55:54 -0800600JDWP::JdwpError Dbg::GetSuperclass(JDWP::RefTypeId id, JDWP::RefTypeId& superclass_id) {
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -0800601 JDWP::JdwpError status;
602 Class* c = DecodeClass(id, status);
603 if (c == NULL) {
604 return status;
605 }
606 if (c->IsInterface()) {
607 // http://code.google.com/p/android/issues/detail?id=20856
Elliott Hughes88d63092013-01-09 09:55:54 -0800608 superclass_id = 0;
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -0800609 } else {
Elliott Hughes88d63092013-01-09 09:55:54 -0800610 superclass_id = gRegistry->Add(c->GetSuperClass());
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -0800611 }
612 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700613}
614
Elliott Hughes436e3722012-02-17 20:01:47 -0800615JDWP::JdwpError Dbg::GetClassLoader(JDWP::RefTypeId id, JDWP::ExpandBuf* pReply) {
Elliott Hughes1bba14f2011-12-01 18:00:36 -0800616 Object* o = gRegistry->Get<Object*>(id);
Elliott Hughes436e3722012-02-17 20:01:47 -0800617 if (o == NULL || o == kInvalidObject) {
618 return JDWP::ERR_INVALID_OBJECT;
619 }
620 expandBufAddObjectId(pReply, gRegistry->Add(o->GetClass()->GetClassLoader()));
621 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700622}
623
Elliott Hughes436e3722012-02-17 20:01:47 -0800624JDWP::JdwpError Dbg::GetModifiers(JDWP::RefTypeId id, JDWP::ExpandBuf* pReply) {
625 JDWP::JdwpError status;
626 Class* c = DecodeClass(id, status);
627 if (c == NULL) {
628 return status;
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -0800629 }
Elliott Hughes436e3722012-02-17 20:01:47 -0800630
631 uint32_t access_flags = c->GetAccessFlags() & kAccJavaFlagsMask;
632
633 // Set ACC_SUPER; dex files don't contain this flag, but all classes are supposed to have it set.
634 // Class.getModifiers doesn't return it, but JDWP does, so we set it here.
635 access_flags |= kAccSuper;
636
637 expandBufAdd4BE(pReply, access_flags);
638
639 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700640}
641
Elliott Hughesf327e072013-01-09 16:01:26 -0800642JDWP::JdwpError Dbg::GetMonitorInfo(JDWP::ObjectId object_id, JDWP::ExpandBuf* reply)
643 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
644 Object* o = gRegistry->Get<Object*>(object_id);
645 if (o == NULL || o == kInvalidObject) {
646 return JDWP::ERR_INVALID_OBJECT;
647 }
648
649 // Ensure all threads are suspended while we read objects' lock words.
650 Thread* self = Thread::Current();
651 Locks::mutator_lock_->SharedUnlock(self);
652 Locks::mutator_lock_->ExclusiveLock(self);
653
654 MonitorInfo monitor_info(o);
655
656 Locks::mutator_lock_->ExclusiveUnlock(self);
657 Locks::mutator_lock_->SharedLock(self);
658
659 if (monitor_info.owner != NULL) {
660 expandBufAddObjectId(reply, gRegistry->Add(monitor_info.owner->GetPeer()));
661 } else {
662 expandBufAddObjectId(reply, gRegistry->Add(NULL));
663 }
664 expandBufAdd4BE(reply, monitor_info.entry_count);
665 expandBufAdd4BE(reply, monitor_info.waiters.size());
666 for (size_t i = 0; i < monitor_info.waiters.size(); ++i) {
667 expandBufAddObjectId(reply, gRegistry->Add(monitor_info.waiters[i]->GetPeer()));
668 }
669 return JDWP::ERR_NONE;
670}
671
Elliott Hughes734b8c62013-01-11 15:32:45 -0800672JDWP::JdwpError Dbg::GetOwnedMonitors(JDWP::ObjectId thread_id,
673 std::vector<JDWP::ObjectId>& monitors,
674 std::vector<uint32_t>& stack_depths)
Elliott Hughes4993bbc2013-01-10 15:41:25 -0800675 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
676 ScopedObjectAccessUnchecked soa(Thread::Current());
677 MutexLock mu(soa.Self(), *Locks::thread_list_lock_);
678 Thread* thread;
679 JDWP::JdwpError error = DecodeThread(soa, thread_id, thread);
680 if (error != JDWP::ERR_NONE) {
681 return error;
682 }
683 if (!IsSuspendedForDebugger(soa, thread)) {
684 return JDWP::ERR_THREAD_NOT_SUSPENDED;
685 }
686
687 struct OwnedMonitorVisitor : public StackVisitor {
688 OwnedMonitorVisitor(const ManagedStack* stack,
689 const std::deque<InstrumentationStackFrame>* instrumentation_stack)
690 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_)
Elliott Hughes734b8c62013-01-11 15:32:45 -0800691 : StackVisitor(stack, instrumentation_stack, NULL), current_stack_depth(0) {}
Elliott Hughes4993bbc2013-01-10 15:41:25 -0800692
693 // TODO: Enable annotalysis. We know lock is held in constructor, but abstraction confuses
694 // annotalysis.
695 bool VisitFrame() NO_THREAD_SAFETY_ANALYSIS {
696 if (!GetMethod()->IsRuntimeMethod()) {
697 Monitor::VisitLocks(this, AppendOwnedMonitors, this);
Elliott Hughes734b8c62013-01-11 15:32:45 -0800698 ++current_stack_depth;
Elliott Hughes4993bbc2013-01-10 15:41:25 -0800699 }
700 return true;
701 }
702
703 static void AppendOwnedMonitors(Object* owned_monitor, void* context) {
Elliott Hughes734b8c62013-01-11 15:32:45 -0800704 OwnedMonitorVisitor* visitor = reinterpret_cast<OwnedMonitorVisitor*>(context);
705 visitor->monitors.push_back(owned_monitor);
706 visitor->stack_depths.push_back(visitor->current_stack_depth);
Elliott Hughes4993bbc2013-01-10 15:41:25 -0800707 }
708
Elliott Hughes734b8c62013-01-11 15:32:45 -0800709 size_t current_stack_depth;
Elliott Hughes4993bbc2013-01-10 15:41:25 -0800710 std::vector<Object*> monitors;
Elliott Hughes734b8c62013-01-11 15:32:45 -0800711 std::vector<uint32_t> stack_depths;
Elliott Hughes4993bbc2013-01-10 15:41:25 -0800712 };
713 OwnedMonitorVisitor visitor(thread->GetManagedStack(), thread->GetInstrumentationStack());
714 visitor.WalkStack();
715
716 for (size_t i = 0; i < visitor.monitors.size(); ++i) {
717 monitors.push_back(gRegistry->Add(visitor.monitors[i]));
Elliott Hughes734b8c62013-01-11 15:32:45 -0800718 stack_depths.push_back(visitor.stack_depths[i]);
Elliott Hughes4993bbc2013-01-10 15:41:25 -0800719 }
720
721 return JDWP::ERR_NONE;
722}
723
Elliott Hughesf9501702013-01-11 11:22:27 -0800724JDWP::JdwpError Dbg::GetContendedMonitor(JDWP::ObjectId thread_id, JDWP::ObjectId& contended_monitor)
725 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
726 ScopedObjectAccessUnchecked soa(Thread::Current());
727 MutexLock mu(soa.Self(), *Locks::thread_list_lock_);
728 Thread* thread;
729 JDWP::JdwpError error = DecodeThread(soa, thread_id, thread);
730 if (error != JDWP::ERR_NONE) {
731 return error;
732 }
733 if (!IsSuspendedForDebugger(soa, thread)) {
734 return JDWP::ERR_THREAD_NOT_SUSPENDED;
735 }
736
737 contended_monitor = gRegistry->Add(Monitor::GetContendedMonitor(thread));
738
739 return JDWP::ERR_NONE;
740}
741
Elliott Hughes88d63092013-01-09 09:55:54 -0800742JDWP::JdwpError Dbg::GetReflectedType(JDWP::RefTypeId class_id, JDWP::ExpandBuf* pReply) {
Elliott Hughes436e3722012-02-17 20:01:47 -0800743 JDWP::JdwpError status;
Elliott Hughes88d63092013-01-09 09:55:54 -0800744 Class* c = DecodeClass(class_id, status);
Elliott Hughes436e3722012-02-17 20:01:47 -0800745 if (c == NULL) {
746 return status;
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -0800747 }
Elliott Hughes436e3722012-02-17 20:01:47 -0800748
749 expandBufAdd1(pReply, c->IsInterface() ? JDWP::TT_INTERFACE : JDWP::TT_CLASS);
Elliott Hughes88d63092013-01-09 09:55:54 -0800750 expandBufAddRefTypeId(pReply, class_id);
Elliott Hughes436e3722012-02-17 20:01:47 -0800751 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700752}
753
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -0800754void Dbg::GetClassList(std::vector<JDWP::RefTypeId>& classes) {
Elliott Hughesa2155262011-11-16 16:26:58 -0800755 // Get the complete list of reference classes (i.e. all classes except
756 // the primitive types).
757 // Returns a newly-allocated buffer full of RefTypeId values.
758 struct ClassListCreator {
Elliott Hughesba8eee12012-01-24 20:25:24 -0800759 explicit ClassListCreator(std::vector<JDWP::RefTypeId>& classes) : classes(classes) {
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -0800760 }
761
Elliott Hughesa2155262011-11-16 16:26:58 -0800762 static bool Visit(Class* c, void* arg) {
763 return reinterpret_cast<ClassListCreator*>(arg)->Visit(c);
764 }
765
766 bool Visit(Class* c) {
767 if (!c->IsPrimitive()) {
768 classes.push_back(static_cast<JDWP::RefTypeId>(gRegistry->Add(c)));
769 }
770 return true;
771 }
772
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -0800773 std::vector<JDWP::RefTypeId>& classes;
Elliott Hughesa2155262011-11-16 16:26:58 -0800774 };
775
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -0800776 ClassListCreator clc(classes);
Elliott Hughesa2155262011-11-16 16:26:58 -0800777 Runtime::Current()->GetClassLinker()->VisitClasses(ClassListCreator::Visit, &clc);
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700778}
779
Elliott Hughes88d63092013-01-09 09:55:54 -0800780JDWP::JdwpError Dbg::GetClassInfo(JDWP::RefTypeId class_id, JDWP::JdwpTypeTag* pTypeTag, uint32_t* pStatus, std::string* pDescriptor) {
Elliott Hughes436e3722012-02-17 20:01:47 -0800781 JDWP::JdwpError status;
Elliott Hughes88d63092013-01-09 09:55:54 -0800782 Class* c = DecodeClass(class_id, status);
Elliott Hughes436e3722012-02-17 20:01:47 -0800783 if (c == NULL) {
784 return status;
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -0800785 }
786
Elliott Hughesa2155262011-11-16 16:26:58 -0800787 if (c->IsArrayClass()) {
788 *pStatus = JDWP::CS_VERIFIED | JDWP::CS_PREPARED;
789 *pTypeTag = JDWP::TT_ARRAY;
790 } else {
791 if (c->IsErroneous()) {
792 *pStatus = JDWP::CS_ERROR;
793 } else {
794 *pStatus = JDWP::CS_VERIFIED | JDWP::CS_PREPARED | JDWP::CS_INITIALIZED;
795 }
796 *pTypeTag = c->IsInterface() ? JDWP::TT_INTERFACE : JDWP::TT_CLASS;
797 }
798
799 if (pDescriptor != NULL) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800800 *pDescriptor = ClassHelper(c).GetDescriptor();
Elliott Hughesa2155262011-11-16 16:26:58 -0800801 }
Elliott Hughes436e3722012-02-17 20:01:47 -0800802 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700803}
804
Elliott Hughesc3b77c72011-12-15 20:56:48 -0800805void Dbg::FindLoadedClassBySignature(const char* descriptor, std::vector<JDWP::RefTypeId>& ids) {
Elliott Hughes6fa602d2011-12-02 17:54:25 -0800806 std::vector<Class*> classes;
807 Runtime::Current()->GetClassLinker()->LookupClasses(descriptor, classes);
808 ids.clear();
809 for (size_t i = 0; i < classes.size(); ++i) {
810 ids.push_back(gRegistry->Add(classes[i]));
811 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700812}
813
Elliott Hughes88d63092013-01-09 09:55:54 -0800814JDWP::JdwpError Dbg::GetReferenceType(JDWP::ObjectId object_id, JDWP::ExpandBuf* pReply) {
815 Object* o = gRegistry->Get<Object*>(object_id);
Elliott Hughes436e3722012-02-17 20:01:47 -0800816 if (o == NULL || o == kInvalidObject) {
Elliott Hughes2435a572012-02-17 16:07:41 -0800817 return JDWP::ERR_INVALID_OBJECT;
Elliott Hughes499c5132011-11-17 14:55:11 -0800818 }
Elliott Hughes2435a572012-02-17 16:07:41 -0800819
820 JDWP::JdwpTypeTag type_tag;
821 if (o->GetClass()->IsArrayClass()) {
822 type_tag = JDWP::TT_ARRAY;
823 } else if (o->GetClass()->IsInterface()) {
824 type_tag = JDWP::TT_INTERFACE;
825 } else {
826 type_tag = JDWP::TT_CLASS;
827 }
828 JDWP::RefTypeId type_id = gRegistry->Add(o->GetClass());
829
830 expandBufAdd1(pReply, type_tag);
831 expandBufAddRefTypeId(pReply, type_id);
832
833 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700834}
835
Elliott Hughes88d63092013-01-09 09:55:54 -0800836JDWP::JdwpError Dbg::GetSignature(JDWP::RefTypeId class_id, std::string& signature) {
Elliott Hughes1fe7afb2012-02-13 17:23:03 -0800837 JDWP::JdwpError status;
Elliott Hughes88d63092013-01-09 09:55:54 -0800838 Class* c = DecodeClass(class_id, status);
Elliott Hughes1fe7afb2012-02-13 17:23:03 -0800839 if (c == NULL) {
840 return status;
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -0800841 }
Elliott Hughes1fe7afb2012-02-13 17:23:03 -0800842 signature = ClassHelper(c).GetDescriptor();
843 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700844}
845
Elliott Hughes88d63092013-01-09 09:55:54 -0800846JDWP::JdwpError Dbg::GetSourceFile(JDWP::RefTypeId class_id, std::string& result) {
Elliott Hughes436e3722012-02-17 20:01:47 -0800847 JDWP::JdwpError status;
Elliott Hughes88d63092013-01-09 09:55:54 -0800848 Class* c = DecodeClass(class_id, status);
Elliott Hughes436e3722012-02-17 20:01:47 -0800849 if (c == NULL) {
850 return status;
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -0800851 }
Elliott Hughes436e3722012-02-17 20:01:47 -0800852 result = ClassHelper(c).GetSourceFile();
853 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700854}
855
Elliott Hughes88d63092013-01-09 09:55:54 -0800856JDWP::JdwpError Dbg::GetObjectTag(JDWP::ObjectId object_id, uint8_t& tag) {
857 Object* o = gRegistry->Get<Object*>(object_id);
Elliott Hughes546b9862012-06-20 16:06:13 -0700858 if (o == kInvalidObject) {
859 return JDWP::ERR_INVALID_OBJECT;
860 }
861 tag = TagFromObject(o);
862 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700863}
864
Elliott Hughesaed4be92011-12-02 16:16:23 -0800865size_t Dbg::GetTagWidth(JDWP::JdwpTag tag) {
Elliott Hughesdbb40792011-11-18 17:05:22 -0800866 switch (tag) {
867 case JDWP::JT_VOID:
868 return 0;
869 case JDWP::JT_BYTE:
870 case JDWP::JT_BOOLEAN:
871 return 1;
872 case JDWP::JT_CHAR:
873 case JDWP::JT_SHORT:
874 return 2;
875 case JDWP::JT_FLOAT:
876 case JDWP::JT_INT:
877 return 4;
878 case JDWP::JT_ARRAY:
879 case JDWP::JT_OBJECT:
880 case JDWP::JT_STRING:
881 case JDWP::JT_THREAD:
882 case JDWP::JT_THREAD_GROUP:
883 case JDWP::JT_CLASS_LOADER:
884 case JDWP::JT_CLASS_OBJECT:
885 return sizeof(JDWP::ObjectId);
886 case JDWP::JT_DOUBLE:
887 case JDWP::JT_LONG:
888 return 8;
889 default:
Elliott Hughes3d30d9b2011-12-07 17:35:48 -0800890 LOG(FATAL) << "Unknown tag " << tag;
Elliott Hughesdbb40792011-11-18 17:05:22 -0800891 return -1;
892 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700893}
894
Elliott Hughes88d63092013-01-09 09:55:54 -0800895JDWP::JdwpError Dbg::GetArrayLength(JDWP::ObjectId array_id, int& length) {
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -0800896 JDWP::JdwpError status;
Elliott Hughes88d63092013-01-09 09:55:54 -0800897 Array* a = DecodeArray(array_id, status);
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -0800898 if (a == NULL) {
899 return status;
Elliott Hughes24437992011-11-30 14:49:33 -0800900 }
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -0800901 length = a->GetLength();
902 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700903}
904
Elliott Hughes88d63092013-01-09 09:55:54 -0800905JDWP::JdwpError Dbg::OutputArray(JDWP::ObjectId array_id, int offset, int count, JDWP::ExpandBuf* pReply) {
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -0800906 JDWP::JdwpError status;
Elliott Hughes88d63092013-01-09 09:55:54 -0800907 Array* a = DecodeArray(array_id, status);
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -0800908 if (a == NULL) {
909 return status;
910 }
Elliott Hughes24437992011-11-30 14:49:33 -0800911
912 if (offset < 0 || count < 0 || offset > a->GetLength() || a->GetLength() - offset < count) {
913 LOG(WARNING) << __FUNCTION__ << " access out of bounds: offset=" << offset << "; count=" << count;
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -0800914 return JDWP::ERR_INVALID_LENGTH;
Elliott Hughes24437992011-11-30 14:49:33 -0800915 }
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800916 std::string descriptor(ClassHelper(a->GetClass()).GetDescriptor());
Elliott Hughes24437992011-11-30 14:49:33 -0800917 JDWP::JdwpTag tag = BasicTagFromDescriptor(descriptor.c_str() + 1);
918
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -0800919 expandBufAdd1(pReply, tag);
920 expandBufAdd4BE(pReply, count);
921
Elliott Hughes24437992011-11-30 14:49:33 -0800922 if (IsPrimitiveTag(tag)) {
923 size_t width = GetTagWidth(tag);
Elliott Hughes24437992011-11-30 14:49:33 -0800924 uint8_t* dst = expandBufAddSpace(pReply, count * width);
925 if (width == 8) {
Ian Rogersa15e67d2012-02-28 13:51:55 -0800926 const uint64_t* src8 = reinterpret_cast<uint64_t*>(a->GetRawData(sizeof(uint64_t)));
Elliott Hughes24437992011-11-30 14:49:33 -0800927 for (int i = 0; i < count; ++i) JDWP::Write8BE(&dst, src8[offset + i]);
928 } else if (width == 4) {
Ian Rogersa15e67d2012-02-28 13:51:55 -0800929 const uint32_t* src4 = reinterpret_cast<uint32_t*>(a->GetRawData(sizeof(uint32_t)));
Elliott Hughes24437992011-11-30 14:49:33 -0800930 for (int i = 0; i < count; ++i) JDWP::Write4BE(&dst, src4[offset + i]);
931 } else if (width == 2) {
Ian Rogersa15e67d2012-02-28 13:51:55 -0800932 const uint16_t* src2 = reinterpret_cast<uint16_t*>(a->GetRawData(sizeof(uint16_t)));
Elliott Hughes24437992011-11-30 14:49:33 -0800933 for (int i = 0; i < count; ++i) JDWP::Write2BE(&dst, src2[offset + i]);
934 } else {
Ian Rogersa15e67d2012-02-28 13:51:55 -0800935 const uint8_t* src = reinterpret_cast<uint8_t*>(a->GetRawData(sizeof(uint8_t)));
Elliott Hughes24437992011-11-30 14:49:33 -0800936 memcpy(dst, &src[offset * width], count * width);
937 }
938 } else {
939 ObjectArray<Object>* oa = a->AsObjectArray<Object>();
940 for (int i = 0; i < count; ++i) {
Elliott Hughesf03b8f62011-12-02 14:26:25 -0800941 Object* element = oa->Get(offset + i);
Elliott Hughes24437992011-11-30 14:49:33 -0800942 JDWP::JdwpTag specific_tag = (element != NULL) ? TagFromObject(element) : tag;
943 expandBufAdd1(pReply, specific_tag);
944 expandBufAddObjectId(pReply, gRegistry->Add(element));
945 }
946 }
947
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -0800948 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700949}
950
Elliott Hughes88d63092013-01-09 09:55:54 -0800951JDWP::JdwpError Dbg::SetArrayElements(JDWP::ObjectId array_id, int offset, int count,
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700952 const uint8_t* src)
Ian Rogersb726dcb2012-09-05 08:57:23 -0700953 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -0800954 JDWP::JdwpError status;
Elliott Hughes88d63092013-01-09 09:55:54 -0800955 Array* a = DecodeArray(array_id, status);
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -0800956 if (a == NULL) {
957 return status;
958 }
Elliott Hughesf03b8f62011-12-02 14:26:25 -0800959
960 if (offset < 0 || count < 0 || offset > a->GetLength() || a->GetLength() - offset < count) {
961 LOG(WARNING) << __FUNCTION__ << " access out of bounds: offset=" << offset << "; count=" << count;
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -0800962 return JDWP::ERR_INVALID_LENGTH;
Elliott Hughesf03b8f62011-12-02 14:26:25 -0800963 }
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800964 std::string descriptor(ClassHelper(a->GetClass()).GetDescriptor());
Elliott Hughesf03b8f62011-12-02 14:26:25 -0800965 JDWP::JdwpTag tag = BasicTagFromDescriptor(descriptor.c_str() + 1);
966
967 if (IsPrimitiveTag(tag)) {
968 size_t width = GetTagWidth(tag);
Elliott Hughesf03b8f62011-12-02 14:26:25 -0800969 if (width == 8) {
Ian Rogersa15e67d2012-02-28 13:51:55 -0800970 uint8_t* dst = &(reinterpret_cast<uint8_t*>(a->GetRawData(sizeof(uint64_t)))[offset * width]);
Elliott Hughesf03b8f62011-12-02 14:26:25 -0800971 for (int i = 0; i < count; ++i) {
972 // Handle potentially non-aligned memory access one byte at a time for ARM's benefit.
973 uint64_t value;
974 for (size_t j = 0; j < sizeof(uint64_t); ++j) reinterpret_cast<uint8_t*>(&value)[j] = src[j];
975 src += sizeof(uint64_t);
976 JDWP::Write8BE(&dst, value);
977 }
978 } else if (width == 4) {
Ian Rogersa15e67d2012-02-28 13:51:55 -0800979 uint8_t* dst = &(reinterpret_cast<uint8_t*>(a->GetRawData(sizeof(uint32_t)))[offset * width]);
Elliott Hughesf03b8f62011-12-02 14:26:25 -0800980 const uint32_t* src4 = reinterpret_cast<const uint32_t*>(src);
981 for (int i = 0; i < count; ++i) JDWP::Write4BE(&dst, src4[i]);
982 } else if (width == 2) {
Ian Rogersa15e67d2012-02-28 13:51:55 -0800983 uint8_t* dst = &(reinterpret_cast<uint8_t*>(a->GetRawData(sizeof(uint16_t)))[offset * width]);
Elliott Hughesf03b8f62011-12-02 14:26:25 -0800984 const uint16_t* src2 = reinterpret_cast<const uint16_t*>(src);
985 for (int i = 0; i < count; ++i) JDWP::Write2BE(&dst, src2[i]);
986 } else {
Ian Rogersa15e67d2012-02-28 13:51:55 -0800987 uint8_t* dst = &(reinterpret_cast<uint8_t*>(a->GetRawData(sizeof(uint8_t)))[offset * width]);
Elliott Hughesf03b8f62011-12-02 14:26:25 -0800988 memcpy(&dst[offset * width], src, count * width);
989 }
990 } else {
991 ObjectArray<Object>* oa = a->AsObjectArray<Object>();
992 for (int i = 0; i < count; ++i) {
993 JDWP::ObjectId id = JDWP::ReadObjectId(&src);
Elliott Hughes436e3722012-02-17 20:01:47 -0800994 Object* o = gRegistry->Get<Object*>(id);
995 if (o == kInvalidObject) {
996 return JDWP::ERR_INVALID_OBJECT;
997 }
998 oa->Set(offset + i, o);
Elliott Hughesf03b8f62011-12-02 14:26:25 -0800999 }
1000 }
1001
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -08001002 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001003}
1004
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -08001005JDWP::ObjectId Dbg::CreateString(const std::string& str) {
Ian Rogers50b35e22012-10-04 10:09:15 -07001006 return gRegistry->Add(String::AllocFromModifiedUtf8(Thread::Current(), str.c_str()));
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001007}
1008
Elliott Hughes88d63092013-01-09 09:55:54 -08001009JDWP::JdwpError Dbg::CreateObject(JDWP::RefTypeId class_id, JDWP::ObjectId& new_object) {
Elliott Hughes436e3722012-02-17 20:01:47 -08001010 JDWP::JdwpError status;
Elliott Hughes88d63092013-01-09 09:55:54 -08001011 Class* c = DecodeClass(class_id, status);
Elliott Hughes436e3722012-02-17 20:01:47 -08001012 if (c == NULL) {
1013 return status;
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -08001014 }
Ian Rogers50b35e22012-10-04 10:09:15 -07001015 new_object = gRegistry->Add(c->AllocObject(Thread::Current()));
Elliott Hughes436e3722012-02-17 20:01:47 -08001016 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001017}
1018
Elliott Hughesbf13d362011-12-08 15:51:37 -08001019/*
1020 * Used by Eclipse's "Display" view to evaluate "new byte[5]" to get "(byte[]) [0, 0, 0, 0, 0]".
1021 */
Elliott Hughes88d63092013-01-09 09:55:54 -08001022JDWP::JdwpError Dbg::CreateArrayObject(JDWP::RefTypeId array_class_id, uint32_t length,
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001023 JDWP::ObjectId& new_array) {
Elliott Hughes436e3722012-02-17 20:01:47 -08001024 JDWP::JdwpError status;
Elliott Hughes88d63092013-01-09 09:55:54 -08001025 Class* c = DecodeClass(array_class_id, status);
Elliott Hughes436e3722012-02-17 20:01:47 -08001026 if (c == NULL) {
1027 return status;
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -08001028 }
Ian Rogers50b35e22012-10-04 10:09:15 -07001029 new_array = gRegistry->Add(Array::Alloc(Thread::Current(), c, length));
Elliott Hughes436e3722012-02-17 20:01:47 -08001030 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001031}
1032
Elliott Hughes88d63092013-01-09 09:55:54 -08001033bool Dbg::MatchType(JDWP::RefTypeId instance_class_id, JDWP::RefTypeId class_id) {
Elliott Hughes436e3722012-02-17 20:01:47 -08001034 JDWP::JdwpError status;
Elliott Hughes88d63092013-01-09 09:55:54 -08001035 Class* c1 = DecodeClass(instance_class_id, status);
Elliott Hughesa656a0f2012-02-21 18:03:44 -08001036 CHECK(c1 != NULL);
Elliott Hughes88d63092013-01-09 09:55:54 -08001037 Class* c2 = DecodeClass(class_id, status);
Elliott Hughesa656a0f2012-02-21 18:03:44 -08001038 CHECK(c2 != NULL);
1039 return c1->IsAssignableFrom(c2);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001040}
1041
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001042static JDWP::FieldId ToFieldId(const Field* f)
Ian Rogersb726dcb2012-09-05 08:57:23 -07001043 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Elliott Hughes03181a82011-11-17 17:22:21 -08001044#ifdef MOVING_GARBAGE_COLLECTOR
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001045 UNIMPLEMENTED(FATAL);
Elliott Hughes03181a82011-11-17 17:22:21 -08001046#else
1047 return static_cast<JDWP::FieldId>(reinterpret_cast<uintptr_t>(f));
1048#endif
1049}
1050
Mathieu Chartier66f19252012-09-18 08:57:04 -07001051static JDWP::MethodId ToMethodId(const AbstractMethod* m)
Ian Rogersb726dcb2012-09-05 08:57:23 -07001052 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Elliott Hughes03181a82011-11-17 17:22:21 -08001053#ifdef MOVING_GARBAGE_COLLECTOR
1054 UNIMPLEMENTED(FATAL);
1055#else
1056 return static_cast<JDWP::MethodId>(reinterpret_cast<uintptr_t>(m));
1057#endif
1058}
1059
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001060static Field* FromFieldId(JDWP::FieldId fid)
Ian Rogersb726dcb2012-09-05 08:57:23 -07001061 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Elliott Hughesaed4be92011-12-02 16:16:23 -08001062#ifdef MOVING_GARBAGE_COLLECTOR
1063 UNIMPLEMENTED(FATAL);
1064#else
1065 return reinterpret_cast<Field*>(static_cast<uintptr_t>(fid));
1066#endif
1067}
1068
Mathieu Chartier66f19252012-09-18 08:57:04 -07001069static AbstractMethod* FromMethodId(JDWP::MethodId mid)
Ian Rogersb726dcb2012-09-05 08:57:23 -07001070 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Elliott Hughes03181a82011-11-17 17:22:21 -08001071#ifdef MOVING_GARBAGE_COLLECTOR
1072 UNIMPLEMENTED(FATAL);
1073#else
Mathieu Chartier66f19252012-09-18 08:57:04 -07001074 return reinterpret_cast<AbstractMethod*>(static_cast<uintptr_t>(mid));
Elliott Hughes03181a82011-11-17 17:22:21 -08001075#endif
1076}
1077
Mathieu Chartier66f19252012-09-18 08:57:04 -07001078static void SetLocation(JDWP::JdwpLocation& location, AbstractMethod* m, uint32_t dex_pc)
Ian Rogersb726dcb2012-09-05 08:57:23 -07001079 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08001080 if (m == NULL) {
1081 memset(&location, 0, sizeof(location));
1082 } else {
1083 Class* c = m->GetDeclaringClass();
Elliott Hughes74847412012-06-20 18:10:21 -07001084 location.type_tag = c->IsInterface() ? JDWP::TT_INTERFACE : JDWP::TT_CLASS;
1085 location.class_id = gRegistry->Add(c);
1086 location.method_id = ToMethodId(m);
Ian Rogers0399dde2012-06-06 17:09:28 -07001087 location.dex_pc = dex_pc;
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08001088 }
Elliott Hughesd07986f2011-12-06 18:27:45 -08001089}
1090
Elliott Hughes88d63092013-01-09 09:55:54 -08001091std::string Dbg::GetMethodName(JDWP::RefTypeId, JDWP::MethodId method_id)
Ian Rogersb726dcb2012-09-05 08:57:23 -07001092 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Elliott Hughes88d63092013-01-09 09:55:54 -08001093 AbstractMethod* m = FromMethodId(method_id);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001094 return MethodHelper(m).GetName();
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001095}
1096
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001097/*
1098 * Augment the access flags for synthetic methods and fields by setting
1099 * the (as described by the spec) "0xf0000000 bit". Also, strip out any
1100 * flags not specified by the Java programming language.
1101 */
1102static uint32_t MangleAccessFlags(uint32_t accessFlags) {
1103 accessFlags &= kAccJavaFlagsMask;
1104 if ((accessFlags & kAccSynthetic) != 0) {
1105 accessFlags |= 0xf0000000;
1106 }
1107 return accessFlags;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001108}
1109
Elliott Hughesdbb40792011-11-18 17:05:22 -08001110static const uint16_t kEclipseWorkaroundSlot = 1000;
1111
1112/*
1113 * Eclipse appears to expect that the "this" reference is in slot zero.
1114 * If it's not, the "variables" display will show two copies of "this",
1115 * possibly because it gets "this" from SF.ThisObject and then displays
1116 * all locals with nonzero slot numbers.
1117 *
1118 * So, we remap the item in slot 0 to 1000, and remap "this" to zero. On
1119 * SF.GetValues / SF.SetValues we map them back.
Elliott Hughesc5b734a2011-12-01 17:20:58 -08001120 *
1121 * TODO: jdb uses the value to determine whether a variable is a local or an argument,
1122 * by checking whether it's less than the number of arguments. To make that work, we'd
1123 * have to "mangle" all the arguments to come first, not just the implicit argument 'this'.
Elliott Hughesdbb40792011-11-18 17:05:22 -08001124 */
1125static uint16_t MangleSlot(uint16_t slot, const char* name) {
1126 uint16_t newSlot = slot;
1127 if (strcmp(name, "this") == 0) {
1128 newSlot = 0;
1129 } else if (slot == 0) {
1130 newSlot = kEclipseWorkaroundSlot;
1131 }
1132 return newSlot;
1133}
1134
Mathieu Chartier66f19252012-09-18 08:57:04 -07001135static uint16_t DemangleSlot(uint16_t slot, AbstractMethod* m)
Ian Rogersb726dcb2012-09-05 08:57:23 -07001136 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Elliott Hughesdbb40792011-11-18 17:05:22 -08001137 if (slot == kEclipseWorkaroundSlot) {
Elliott Hughes68fdbd02011-11-29 19:22:47 -08001138 return 0;
Elliott Hughesdbb40792011-11-18 17:05:22 -08001139 } else if (slot == 0) {
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08001140 const DexFile::CodeItem* code_item = MethodHelper(m).GetCodeItem();
Elliott Hughescaf76542012-06-28 16:08:22 -07001141 CHECK(code_item != NULL) << PrettyMethod(m);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001142 return code_item->registers_size_ - code_item->ins_size_;
Elliott Hughesdbb40792011-11-18 17:05:22 -08001143 }
Elliott Hughes68fdbd02011-11-29 19:22:47 -08001144 return slot;
Elliott Hughesdbb40792011-11-18 17:05:22 -08001145}
1146
Elliott Hughes88d63092013-01-09 09:55:54 -08001147JDWP::JdwpError Dbg::OutputDeclaredFields(JDWP::RefTypeId class_id, bool with_generic, JDWP::ExpandBuf* pReply) {
Elliott Hughes436e3722012-02-17 20:01:47 -08001148 JDWP::JdwpError status;
Elliott Hughes88d63092013-01-09 09:55:54 -08001149 Class* c = DecodeClass(class_id, status);
Elliott Hughes436e3722012-02-17 20:01:47 -08001150 if (c == NULL) {
1151 return status;
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -08001152 }
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001153
1154 size_t instance_field_count = c->NumInstanceFields();
1155 size_t static_field_count = c->NumStaticFields();
1156
1157 expandBufAdd4BE(pReply, instance_field_count + static_field_count);
1158
1159 for (size_t i = 0; i < instance_field_count + static_field_count; ++i) {
1160 Field* f = (i < instance_field_count) ? c->GetInstanceField(i) : c->GetStaticField(i - instance_field_count);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001161 FieldHelper fh(f);
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001162 expandBufAddFieldId(pReply, ToFieldId(f));
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001163 expandBufAddUtf8String(pReply, fh.GetName());
1164 expandBufAddUtf8String(pReply, fh.GetTypeDescriptor());
Elliott Hughesc5b734a2011-12-01 17:20:58 -08001165 if (with_generic) {
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001166 static const char genericSignature[1] = "";
1167 expandBufAddUtf8String(pReply, genericSignature);
1168 }
1169 expandBufAdd4BE(pReply, MangleAccessFlags(f->GetAccessFlags()));
1170 }
Elliott Hughes436e3722012-02-17 20:01:47 -08001171 return JDWP::ERR_NONE;
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001172}
1173
Elliott Hughes88d63092013-01-09 09:55:54 -08001174JDWP::JdwpError Dbg::OutputDeclaredMethods(JDWP::RefTypeId class_id, bool with_generic,
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001175 JDWP::ExpandBuf* pReply) {
Elliott Hughes436e3722012-02-17 20:01:47 -08001176 JDWP::JdwpError status;
Elliott Hughes88d63092013-01-09 09:55:54 -08001177 Class* c = DecodeClass(class_id, status);
Elliott Hughes436e3722012-02-17 20:01:47 -08001178 if (c == NULL) {
1179 return status;
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -08001180 }
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001181
1182 size_t direct_method_count = c->NumDirectMethods();
1183 size_t virtual_method_count = c->NumVirtualMethods();
1184
1185 expandBufAdd4BE(pReply, direct_method_count + virtual_method_count);
1186
1187 for (size_t i = 0; i < direct_method_count + virtual_method_count; ++i) {
Mathieu Chartier66f19252012-09-18 08:57:04 -07001188 AbstractMethod* m = (i < direct_method_count) ? c->GetDirectMethod(i) : c->GetVirtualMethod(i - direct_method_count);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001189 MethodHelper mh(m);
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001190 expandBufAddMethodId(pReply, ToMethodId(m));
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001191 expandBufAddUtf8String(pReply, mh.GetName());
Elliott Hughes4740cdf2011-12-07 14:07:12 -08001192 expandBufAddUtf8String(pReply, mh.GetSignature());
Elliott Hughesc5b734a2011-12-01 17:20:58 -08001193 if (with_generic) {
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001194 static const char genericSignature[1] = "";
1195 expandBufAddUtf8String(pReply, genericSignature);
1196 }
1197 expandBufAdd4BE(pReply, MangleAccessFlags(m->GetAccessFlags()));
1198 }
Elliott Hughes436e3722012-02-17 20:01:47 -08001199 return JDWP::ERR_NONE;
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001200}
1201
Elliott Hughes88d63092013-01-09 09:55:54 -08001202JDWP::JdwpError Dbg::OutputDeclaredInterfaces(JDWP::RefTypeId class_id, JDWP::ExpandBuf* pReply) {
Elliott Hughes436e3722012-02-17 20:01:47 -08001203 JDWP::JdwpError status;
Elliott Hughes88d63092013-01-09 09:55:54 -08001204 Class* c = DecodeClass(class_id, status);
Elliott Hughes436e3722012-02-17 20:01:47 -08001205 if (c == NULL) {
1206 return status;
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -08001207 }
Elliott Hughes436e3722012-02-17 20:01:47 -08001208
1209 ClassHelper kh(c);
Ian Rogersd24e2642012-06-06 21:21:43 -07001210 size_t interface_count = kh.NumDirectInterfaces();
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001211 expandBufAdd4BE(pReply, interface_count);
1212 for (size_t i = 0; i < interface_count; ++i) {
Ian Rogersd24e2642012-06-06 21:21:43 -07001213 expandBufAddRefTypeId(pReply, gRegistry->Add(kh.GetDirectInterface(i)));
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001214 }
Elliott Hughes436e3722012-02-17 20:01:47 -08001215 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001216}
1217
Elliott Hughes88d63092013-01-09 09:55:54 -08001218void Dbg::OutputLineTable(JDWP::RefTypeId, JDWP::MethodId method_id, JDWP::ExpandBuf* pReply)
Ian Rogersb726dcb2012-09-05 08:57:23 -07001219 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Elliott Hughes03181a82011-11-17 17:22:21 -08001220 struct DebugCallbackContext {
1221 int numItems;
1222 JDWP::ExpandBuf* pReply;
1223
Elliott Hughes2435a572012-02-17 16:07:41 -08001224 static bool Callback(void* context, uint32_t address, uint32_t line_number) {
Elliott Hughes03181a82011-11-17 17:22:21 -08001225 DebugCallbackContext* pContext = reinterpret_cast<DebugCallbackContext*>(context);
1226 expandBufAdd8BE(pContext->pReply, address);
Elliott Hughes2435a572012-02-17 16:07:41 -08001227 expandBufAdd4BE(pContext->pReply, line_number);
Elliott Hughes03181a82011-11-17 17:22:21 -08001228 pContext->numItems++;
1229 return true;
1230 }
1231 };
Elliott Hughes88d63092013-01-09 09:55:54 -08001232 AbstractMethod* m = FromMethodId(method_id);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001233 MethodHelper mh(m);
Elliott Hughes03181a82011-11-17 17:22:21 -08001234 uint64_t start, end;
1235 if (m->IsNative()) {
1236 start = -1;
1237 end = -1;
1238 } else {
1239 start = 0;
jeffhao14f0db92012-12-14 17:50:42 -08001240 // Return the index of the last instruction
1241 end = mh.GetCodeItem()->insns_size_in_code_units_ - 1;
Elliott Hughes03181a82011-11-17 17:22:21 -08001242 }
1243
1244 expandBufAdd8BE(pReply, start);
1245 expandBufAdd8BE(pReply, end);
1246
1247 // Add numLines later
1248 size_t numLinesOffset = expandBufGetLength(pReply);
1249 expandBufAdd4BE(pReply, 0);
1250
1251 DebugCallbackContext context;
1252 context.numItems = 0;
1253 context.pReply = pReply;
1254
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001255 mh.GetDexFile().DecodeDebugInfo(mh.GetCodeItem(), m->IsStatic(), m->GetDexMethodIndex(),
1256 DebugCallbackContext::Callback, NULL, &context);
Elliott Hughes03181a82011-11-17 17:22:21 -08001257
1258 JDWP::Set4BE(expandBufGetBuffer(pReply) + numLinesOffset, context.numItems);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001259}
1260
Elliott Hughes88d63092013-01-09 09:55:54 -08001261void Dbg::OutputVariableTable(JDWP::RefTypeId, JDWP::MethodId method_id, bool with_generic, JDWP::ExpandBuf* pReply) {
Elliott Hughesdbb40792011-11-18 17:05:22 -08001262 struct DebugCallbackContext {
Elliott Hughesdbb40792011-11-18 17:05:22 -08001263 JDWP::ExpandBuf* pReply;
Elliott Hughesc5b734a2011-12-01 17:20:58 -08001264 size_t variable_count;
1265 bool with_generic;
Elliott Hughesdbb40792011-11-18 17:05:22 -08001266
Elliott Hughesc5b734a2011-12-01 17:20:58 -08001267 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 -08001268 DebugCallbackContext* pContext = reinterpret_cast<DebugCallbackContext*>(context);
1269
Elliott Hughesad3da692012-02-24 16:51:35 -08001270 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 -08001271
Elliott Hughes68fdbd02011-11-29 19:22:47 -08001272 slot = MangleSlot(slot, name);
1273
Elliott Hughesdbb40792011-11-18 17:05:22 -08001274 expandBufAdd8BE(pContext->pReply, startAddress);
1275 expandBufAddUtf8String(pContext->pReply, name);
1276 expandBufAddUtf8String(pContext->pReply, descriptor);
Elliott Hughesc5b734a2011-12-01 17:20:58 -08001277 if (pContext->with_generic) {
Elliott Hughesdbb40792011-11-18 17:05:22 -08001278 expandBufAddUtf8String(pContext->pReply, signature);
1279 }
1280 expandBufAdd4BE(pContext->pReply, endAddress - startAddress);
1281 expandBufAdd4BE(pContext->pReply, slot);
1282
Elliott Hughesc5b734a2011-12-01 17:20:58 -08001283 ++pContext->variable_count;
Elliott Hughesdbb40792011-11-18 17:05:22 -08001284 }
1285 };
Elliott Hughes88d63092013-01-09 09:55:54 -08001286 AbstractMethod* m = FromMethodId(method_id);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001287 MethodHelper mh(m);
1288 const DexFile::CodeItem* code_item = mh.GetCodeItem();
Elliott Hughesdbb40792011-11-18 17:05:22 -08001289
Elliott Hughesc5b734a2011-12-01 17:20:58 -08001290 // arg_count considers doubles and longs to take 2 units.
1291 // variable_count considers everything to take 1 unit.
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001292 std::string shorty(mh.GetShorty());
Ian Rogers2fa6b2e2012-10-17 00:10:17 -07001293 expandBufAdd4BE(pReply, AbstractMethod::NumArgRegisters(shorty));
Elliott Hughesdbb40792011-11-18 17:05:22 -08001294
Elliott Hughesc5b734a2011-12-01 17:20:58 -08001295 // We don't know the total number of variables yet, so leave a blank and update it later.
1296 size_t variable_count_offset = expandBufGetLength(pReply);
Elliott Hughesdbb40792011-11-18 17:05:22 -08001297 expandBufAdd4BE(pReply, 0);
1298
1299 DebugCallbackContext context;
Elliott Hughesdbb40792011-11-18 17:05:22 -08001300 context.pReply = pReply;
Elliott Hughesc5b734a2011-12-01 17:20:58 -08001301 context.variable_count = 0;
1302 context.with_generic = with_generic;
Elliott Hughesdbb40792011-11-18 17:05:22 -08001303
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001304 mh.GetDexFile().DecodeDebugInfo(code_item, m->IsStatic(), m->GetDexMethodIndex(), NULL,
1305 DebugCallbackContext::Callback, &context);
Elliott Hughesdbb40792011-11-18 17:05:22 -08001306
Elliott Hughesc5b734a2011-12-01 17:20:58 -08001307 JDWP::Set4BE(expandBufGetBuffer(pReply) + variable_count_offset, context.variable_count);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001308}
1309
Elliott Hughes88d63092013-01-09 09:55:54 -08001310JDWP::JdwpTag Dbg::GetFieldBasicTag(JDWP::FieldId field_id) {
1311 return BasicTagFromDescriptor(FieldHelper(FromFieldId(field_id)).GetTypeDescriptor());
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001312}
1313
Elliott Hughes88d63092013-01-09 09:55:54 -08001314JDWP::JdwpTag Dbg::GetStaticFieldBasicTag(JDWP::FieldId field_id) {
1315 return BasicTagFromDescriptor(FieldHelper(FromFieldId(field_id)).GetTypeDescriptor());
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001316}
1317
Elliott Hughes88d63092013-01-09 09:55:54 -08001318static JDWP::JdwpError GetFieldValueImpl(JDWP::RefTypeId ref_type_id, JDWP::ObjectId object_id,
1319 JDWP::FieldId field_id, JDWP::ExpandBuf* pReply,
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001320 bool is_static)
Ian Rogersb726dcb2012-09-05 08:57:23 -07001321 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Elliott Hughes0cf74332012-02-23 23:14:00 -08001322 JDWP::JdwpError status;
Elliott Hughes88d63092013-01-09 09:55:54 -08001323 Class* c = DecodeClass(ref_type_id, status);
1324 if (ref_type_id != 0 && c == NULL) {
Elliott Hughes0cf74332012-02-23 23:14:00 -08001325 return status;
1326 }
1327
Elliott Hughes88d63092013-01-09 09:55:54 -08001328 Object* o = gRegistry->Get<Object*>(object_id);
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08001329 if ((!is_static && o == NULL) || o == kInvalidObject) {
1330 return JDWP::ERR_INVALID_OBJECT;
1331 }
Elliott Hughes88d63092013-01-09 09:55:54 -08001332 Field* f = FromFieldId(field_id);
Elliott Hughes0cf74332012-02-23 23:14:00 -08001333
1334 Class* receiver_class = c;
1335 if (receiver_class == NULL && o != NULL) {
1336 receiver_class = o->GetClass();
1337 }
1338 // TODO: should we give up now if receiver_class is NULL?
1339 if (receiver_class != NULL && !f->GetDeclaringClass()->IsAssignableFrom(receiver_class)) {
1340 LOG(INFO) << "ERR_INVALID_FIELDID: " << PrettyField(f) << " " << PrettyClass(receiver_class);
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08001341 return JDWP::ERR_INVALID_FIELDID;
1342 }
Elliott Hughesaed4be92011-12-02 16:16:23 -08001343
Elliott Hughes0cf74332012-02-23 23:14:00 -08001344 // The RI only enforces the static/non-static mismatch in one direction.
1345 // TODO: should we change the tests and check both?
1346 if (is_static) {
1347 if (!f->IsStatic()) {
1348 return JDWP::ERR_INVALID_FIELDID;
1349 }
1350 } else {
1351 if (f->IsStatic()) {
1352 LOG(WARNING) << "Ignoring non-NULL receiver for ObjectReference.SetValues on static field " << PrettyField(f);
Elliott Hughes0cf74332012-02-23 23:14:00 -08001353 }
1354 }
jeffhao0dfbb7e2012-11-28 15:26:03 -08001355 if (f->IsStatic()) {
1356 o = f->GetDeclaringClass();
1357 }
Elliott Hughes0cf74332012-02-23 23:14:00 -08001358
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001359 JDWP::JdwpTag tag = BasicTagFromDescriptor(FieldHelper(f).GetTypeDescriptor());
Elliott Hughesaed4be92011-12-02 16:16:23 -08001360
1361 if (IsPrimitiveTag(tag)) {
1362 expandBufAdd1(pReply, tag);
1363 if (tag == JDWP::JT_BOOLEAN || tag == JDWP::JT_BYTE) {
1364 expandBufAdd1(pReply, f->Get32(o));
1365 } else if (tag == JDWP::JT_CHAR || tag == JDWP::JT_SHORT) {
1366 expandBufAdd2BE(pReply, f->Get32(o));
1367 } else if (tag == JDWP::JT_FLOAT || tag == JDWP::JT_INT) {
1368 expandBufAdd4BE(pReply, f->Get32(o));
1369 } else if (tag == JDWP::JT_DOUBLE || tag == JDWP::JT_LONG) {
1370 expandBufAdd8BE(pReply, f->Get64(o));
1371 } else {
Elliott Hughes3d30d9b2011-12-07 17:35:48 -08001372 LOG(FATAL) << "Unknown tag: " << tag;
Elliott Hughesaed4be92011-12-02 16:16:23 -08001373 }
1374 } else {
1375 Object* value = f->GetObject(o);
1376 expandBufAdd1(pReply, TagFromObject(value));
1377 expandBufAddObjectId(pReply, gRegistry->Add(value));
1378 }
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08001379 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001380}
1381
Elliott Hughes88d63092013-01-09 09:55:54 -08001382JDWP::JdwpError Dbg::GetFieldValue(JDWP::ObjectId object_id, JDWP::FieldId field_id,
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001383 JDWP::ExpandBuf* pReply) {
Elliott Hughes88d63092013-01-09 09:55:54 -08001384 return GetFieldValueImpl(0, object_id, field_id, pReply, false);
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08001385}
1386
Elliott Hughes88d63092013-01-09 09:55:54 -08001387JDWP::JdwpError Dbg::GetStaticFieldValue(JDWP::RefTypeId ref_type_id, JDWP::FieldId field_id, JDWP::ExpandBuf* pReply) {
1388 return GetFieldValueImpl(ref_type_id, 0, field_id, pReply, true);
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08001389}
1390
Elliott Hughes88d63092013-01-09 09:55:54 -08001391static JDWP::JdwpError SetFieldValueImpl(JDWP::ObjectId object_id, JDWP::FieldId field_id,
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001392 uint64_t value, int width, bool is_static)
Ian Rogersb726dcb2012-09-05 08:57:23 -07001393 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Elliott Hughes88d63092013-01-09 09:55:54 -08001394 Object* o = gRegistry->Get<Object*>(object_id);
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08001395 if ((!is_static && o == NULL) || o == kInvalidObject) {
1396 return JDWP::ERR_INVALID_OBJECT;
1397 }
Elliott Hughes88d63092013-01-09 09:55:54 -08001398 Field* f = FromFieldId(field_id);
Elliott Hughes0cf74332012-02-23 23:14:00 -08001399
1400 // The RI only enforces the static/non-static mismatch in one direction.
1401 // TODO: should we change the tests and check both?
1402 if (is_static) {
1403 if (!f->IsStatic()) {
1404 return JDWP::ERR_INVALID_FIELDID;
1405 }
1406 } else {
1407 if (f->IsStatic()) {
1408 LOG(WARNING) << "Ignoring non-NULL receiver for ObjectReference.SetValues on static field " << PrettyField(f);
Elliott Hughes0cf74332012-02-23 23:14:00 -08001409 }
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08001410 }
jeffhao0dfbb7e2012-11-28 15:26:03 -08001411 if (f->IsStatic()) {
1412 o = f->GetDeclaringClass();
1413 }
Elliott Hughesaed4be92011-12-02 16:16:23 -08001414
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001415 JDWP::JdwpTag tag = BasicTagFromDescriptor(FieldHelper(f).GetTypeDescriptor());
Elliott Hughesaed4be92011-12-02 16:16:23 -08001416
1417 if (IsPrimitiveTag(tag)) {
1418 if (tag == JDWP::JT_DOUBLE || tag == JDWP::JT_LONG) {
Elliott Hughes1bac54f2012-03-16 12:48:31 -07001419 CHECK_EQ(width, 8);
Elliott Hughesaed4be92011-12-02 16:16:23 -08001420 f->Set64(o, value);
1421 } else {
Elliott Hughes1bac54f2012-03-16 12:48:31 -07001422 CHECK_LE(width, 4);
Elliott Hughesaed4be92011-12-02 16:16:23 -08001423 f->Set32(o, value);
1424 }
1425 } else {
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -08001426 Object* v = gRegistry->Get<Object*>(value);
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08001427 if (v == kInvalidObject) {
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -08001428 return JDWP::ERR_INVALID_OBJECT;
1429 }
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08001430 if (v != NULL) {
1431 Class* field_type = FieldHelper(f).GetType();
1432 if (!field_type->IsAssignableFrom(v->GetClass())) {
1433 return JDWP::ERR_INVALID_OBJECT;
1434 }
1435 }
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -08001436 f->SetObject(o, v);
Elliott Hughesaed4be92011-12-02 16:16:23 -08001437 }
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -08001438
1439 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001440}
1441
Elliott Hughes88d63092013-01-09 09:55:54 -08001442JDWP::JdwpError Dbg::SetFieldValue(JDWP::ObjectId object_id, JDWP::FieldId field_id, uint64_t value,
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001443 int width) {
Elliott Hughes88d63092013-01-09 09:55:54 -08001444 return SetFieldValueImpl(object_id, field_id, value, width, false);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001445}
1446
Elliott Hughes88d63092013-01-09 09:55:54 -08001447JDWP::JdwpError Dbg::SetStaticFieldValue(JDWP::FieldId field_id, uint64_t value, int width) {
1448 return SetFieldValueImpl(0, field_id, value, width, true);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001449}
1450
Elliott Hughes88d63092013-01-09 09:55:54 -08001451std::string Dbg::StringToUtf8(JDWP::ObjectId string_id) {
1452 String* s = gRegistry->Get<String*>(string_id);
Elliott Hughes68fdbd02011-11-29 19:22:47 -08001453 return s->ToModifiedUtf8();
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001454}
1455
Elliott Hughes221229c2013-01-08 18:17:50 -08001456JDWP::JdwpError Dbg::GetThreadName(JDWP::ObjectId thread_id, std::string& name) {
jeffhaoa77f0f62012-12-05 17:19:31 -08001457 ScopedObjectAccessUnchecked soa(Thread::Current());
1458 MutexLock mu(soa.Self(), *Locks::thread_list_lock_);
Elliott Hughes221229c2013-01-08 18:17:50 -08001459 Thread* thread;
1460 JDWP::JdwpError error = DecodeThread(soa, thread_id, thread);
1461 if (error != JDWP::ERR_NONE && error != JDWP::ERR_THREAD_NOT_ALIVE) {
1462 return error;
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001463 }
Elliott Hughes221229c2013-01-08 18:17:50 -08001464
1465 // We still need to report the zombie threads' names, so we can't just call Thread::GetThreadName.
1466 Object* thread_object = gRegistry->Get<Object*>(thread_id);
1467 Field* java_lang_Thread_name_field = soa.DecodeField(WellKnownClasses::java_lang_Thread_name);
1468 String* s = reinterpret_cast<String*>(java_lang_Thread_name_field->GetObject(thread_object));
1469 if (s != NULL) {
1470 name = s->ToModifiedUtf8();
1471 }
1472 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001473}
1474
Elliott Hughes221229c2013-01-08 18:17:50 -08001475JDWP::JdwpError Dbg::GetThreadGroup(JDWP::ObjectId thread_id, JDWP::ExpandBuf* pReply) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001476 ScopedObjectAccess soa(Thread::Current());
Elliott Hughes221229c2013-01-08 18:17:50 -08001477 Object* thread_object = gRegistry->Get<Object*>(thread_id);
1478 if (thread_object == kInvalidObject) {
Elliott Hughes2435a572012-02-17 16:07:41 -08001479 return JDWP::ERR_INVALID_OBJECT;
1480 }
1481
1482 // Okay, so it's an object, but is it actually a thread?
Ian Rogers50b35e22012-10-04 10:09:15 -07001483 MutexLock mu(soa.Self(), *Locks::thread_list_lock_);
Elliott Hughes221229c2013-01-08 18:17:50 -08001484 Thread* thread;
1485 JDWP::JdwpError error = DecodeThread(soa, thread_id, thread);
1486 if (error == JDWP::ERR_THREAD_NOT_ALIVE) {
1487 // Zombie threads are in the null group.
1488 expandBufAddObjectId(pReply, JDWP::ObjectId(0));
1489 return JDWP::ERR_NONE;
1490 }
1491 if (error != JDWP::ERR_NONE) {
1492 return error;
Elliott Hughes2435a572012-02-17 16:07:41 -08001493 }
Elliott Hughes499c5132011-11-17 14:55:11 -08001494
1495 Class* c = Runtime::Current()->GetClassLinker()->FindSystemClass("Ljava/lang/Thread;");
1496 CHECK(c != NULL);
1497 Field* f = c->FindInstanceField("group", "Ljava/lang/ThreadGroup;");
1498 CHECK(f != NULL);
Elliott Hughes221229c2013-01-08 18:17:50 -08001499 Object* group = f->GetObject(thread_object);
Elliott Hughes499c5132011-11-17 14:55:11 -08001500 CHECK(group != NULL);
Elliott Hughes2435a572012-02-17 16:07:41 -08001501 JDWP::ObjectId thread_group_id = gRegistry->Add(group);
1502
1503 expandBufAddObjectId(pReply, thread_group_id);
1504 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001505}
1506
Elliott Hughes88d63092013-01-09 09:55:54 -08001507std::string Dbg::GetThreadGroupName(JDWP::ObjectId thread_group_id) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001508 ScopedObjectAccess soa(Thread::Current());
Elliott Hughes88d63092013-01-09 09:55:54 -08001509 Object* thread_group = gRegistry->Get<Object*>(thread_group_id);
Elliott Hughes499c5132011-11-17 14:55:11 -08001510 CHECK(thread_group != NULL);
1511
1512 Class* c = Runtime::Current()->GetClassLinker()->FindSystemClass("Ljava/lang/ThreadGroup;");
1513 CHECK(c != NULL);
1514 Field* f = c->FindInstanceField("name", "Ljava/lang/String;");
1515 CHECK(f != NULL);
1516 String* s = reinterpret_cast<String*>(f->GetObject(thread_group));
1517 return s->ToModifiedUtf8();
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001518}
1519
Elliott Hughes88d63092013-01-09 09:55:54 -08001520JDWP::ObjectId Dbg::GetThreadGroupParent(JDWP::ObjectId thread_group_id) {
1521 Object* thread_group = gRegistry->Get<Object*>(thread_group_id);
Elliott Hughes4e235312011-12-02 11:34:15 -08001522 CHECK(thread_group != NULL);
1523
1524 Class* c = Runtime::Current()->GetClassLinker()->FindSystemClass("Ljava/lang/ThreadGroup;");
1525 CHECK(c != NULL);
1526 Field* f = c->FindInstanceField("parent", "Ljava/lang/ThreadGroup;");
1527 CHECK(f != NULL);
1528 Object* parent = f->GetObject(thread_group);
1529 return gRegistry->Add(parent);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001530}
1531
1532JDWP::ObjectId Dbg::GetSystemThreadGroupId() {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001533 ScopedObjectAccessUnchecked soa(Thread::Current());
jeffhao0dfbb7e2012-11-28 15:26:03 -08001534 Field* f = soa.DecodeField(WellKnownClasses::java_lang_ThreadGroup_systemThreadGroup);
1535 Object* group = f->GetObject(f->GetDeclaringClass());
Ian Rogers365c1022012-06-22 15:05:28 -07001536 return gRegistry->Add(group);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001537}
1538
1539JDWP::ObjectId Dbg::GetMainThreadGroupId() {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001540 ScopedObjectAccess soa(Thread::Current());
jeffhao0dfbb7e2012-11-28 15:26:03 -08001541 Field* f = soa.DecodeField(WellKnownClasses::java_lang_ThreadGroup_mainThreadGroup);
1542 Object* group = f->GetObject(f->GetDeclaringClass());
Ian Rogers365c1022012-06-22 15:05:28 -07001543 return gRegistry->Add(group);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001544}
1545
Elliott Hughes221229c2013-01-08 18:17:50 -08001546JDWP::JdwpError Dbg::GetThreadStatus(JDWP::ObjectId thread_id, JDWP::JdwpThreadStatus* pThreadStatus, JDWP::JdwpSuspendStatus* pSuspendStatus) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001547 ScopedObjectAccess soa(Thread::Current());
Elliott Hughes499c5132011-11-17 14:55:11 -08001548
Elliott Hughes9e0c1752013-01-09 14:02:58 -08001549 *pSuspendStatus = JDWP::SUSPEND_STATUS_NOT_SUSPENDED;
1550
Ian Rogers50b35e22012-10-04 10:09:15 -07001551 MutexLock mu(soa.Self(), *Locks::thread_list_lock_);
Elliott Hughes221229c2013-01-08 18:17:50 -08001552 Thread* thread;
1553 JDWP::JdwpError error = DecodeThread(soa, thread_id, thread);
1554 if (error != JDWP::ERR_NONE) {
1555 if (error == JDWP::ERR_THREAD_NOT_ALIVE) {
1556 *pThreadStatus = JDWP::TS_ZOMBIE;
Elliott Hughes221229c2013-01-08 18:17:50 -08001557 return JDWP::ERR_NONE;
1558 }
1559 return error;
Elliott Hughes499c5132011-11-17 14:55:11 -08001560 }
1561
Elliott Hughes9e0c1752013-01-09 14:02:58 -08001562 if (IsSuspendedForDebugger(soa, thread)) {
1563 *pSuspendStatus = JDWP::SUSPEND_STATUS_SUSPENDED;
Elliott Hughes499c5132011-11-17 14:55:11 -08001564 }
1565
Elliott Hughes9e0c1752013-01-09 14:02:58 -08001566 switch (thread->GetState()) {
1567 case kBlocked: *pThreadStatus = JDWP::TS_MONITOR; break;
1568 case kNative: *pThreadStatus = JDWP::TS_RUNNING; break;
1569 case kRunnable: *pThreadStatus = JDWP::TS_RUNNING; break;
1570 case kSleeping: *pThreadStatus = JDWP::TS_SLEEPING; break;
1571 case kStarting: *pThreadStatus = JDWP::TS_ZOMBIE; break;
1572 case kSuspended: *pThreadStatus = JDWP::TS_RUNNING; break;
1573 case kTerminated: *pThreadStatus = JDWP::TS_ZOMBIE; break;
1574 case kTimedWaiting: *pThreadStatus = JDWP::TS_WAIT; break;
1575 case kWaitingForDebuggerSend: *pThreadStatus = JDWP::TS_WAIT; break;
1576 case kWaitingForDebuggerSuspension: *pThreadStatus = JDWP::TS_WAIT; break;
1577 case kWaitingForDebuggerToAttach: *pThreadStatus = JDWP::TS_WAIT; break;
1578 case kWaitingForGcToComplete: *pThreadStatus = JDWP::TS_WAIT; break;
1579 case kWaitingForJniOnLoad: *pThreadStatus = JDWP::TS_WAIT; break;
1580 case kWaitingForSignalCatcherOutput: *pThreadStatus = JDWP::TS_WAIT; break;
1581 case kWaitingInMainDebuggerLoop: *pThreadStatus = JDWP::TS_WAIT; break;
1582 case kWaitingInMainSignalCatcherLoop: *pThreadStatus = JDWP::TS_WAIT; break;
1583 case kWaitingPerformingGc: *pThreadStatus = JDWP::TS_WAIT; break;
1584 case kWaiting: *pThreadStatus = JDWP::TS_WAIT; break;
1585 // Don't add a 'default' here so the compiler can spot incompatible enum changes.
1586 }
Elliott Hughes221229c2013-01-08 18:17:50 -08001587 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001588}
1589
Elliott Hughes221229c2013-01-08 18:17:50 -08001590JDWP::JdwpError Dbg::GetThreadDebugSuspendCount(JDWP::ObjectId thread_id, JDWP::ExpandBuf* pReply) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001591 ScopedObjectAccess soa(Thread::Current());
Ian Rogers50b35e22012-10-04 10:09:15 -07001592 MutexLock mu(soa.Self(), *Locks::thread_list_lock_);
Elliott Hughes221229c2013-01-08 18:17:50 -08001593 Thread* thread;
1594 JDWP::JdwpError error = DecodeThread(soa, thread_id, thread);
1595 if (error != JDWP::ERR_NONE) {
1596 return error;
Elliott Hughes2435a572012-02-17 16:07:41 -08001597 }
Ian Rogers50b35e22012-10-04 10:09:15 -07001598 MutexLock mu2(soa.Self(), *Locks::thread_suspend_count_lock_);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001599 expandBufAdd4BE(pReply, thread->GetDebugSuspendCount());
Elliott Hughes2435a572012-02-17 16:07:41 -08001600 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001601}
1602
Elliott Hughesf9501702013-01-11 11:22:27 -08001603JDWP::JdwpError Dbg::Interrupt(JDWP::ObjectId thread_id) {
1604 ScopedObjectAccess soa(Thread::Current());
1605 MutexLock mu(soa.Self(), *Locks::thread_list_lock_);
1606 Thread* thread;
1607 JDWP::JdwpError error = DecodeThread(soa, thread_id, thread);
1608 if (error != JDWP::ERR_NONE) {
1609 return error;
1610 }
1611 thread->Interrupt();
1612 return JDWP::ERR_NONE;
1613}
1614
Elliott Hughescaf76542012-06-28 16:08:22 -07001615void Dbg::GetThreads(JDWP::ObjectId thread_group_id, std::vector<JDWP::ObjectId>& thread_ids) {
Ian Rogers365c1022012-06-22 15:05:28 -07001616 class ThreadListVisitor {
1617 public:
jeffhao0dfbb7e2012-11-28 15:26:03 -08001618 ThreadListVisitor(const ScopedObjectAccessUnchecked& soa, Object* desired_thread_group,
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001619 std::vector<JDWP::ObjectId>& thread_ids)
Ian Rogersb726dcb2012-09-05 08:57:23 -07001620 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_)
jeffhao0dfbb7e2012-11-28 15:26:03 -08001621 : soa_(soa), desired_thread_group_(desired_thread_group), thread_ids_(thread_ids) {}
Ian Rogers365c1022012-06-22 15:05:28 -07001622
Elliott Hughesa2155262011-11-16 16:26:58 -08001623 static void Visit(Thread* t, void* arg) {
1624 reinterpret_cast<ThreadListVisitor*>(arg)->Visit(t);
1625 }
1626
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001627 // TODO: Enable annotalysis. We know lock is held in constructor, but abstraction confuses
1628 // annotalysis.
1629 void Visit(Thread* t) NO_THREAD_SAFETY_ANALYSIS {
Elliott Hughesa2155262011-11-16 16:26:58 -08001630 if (t == Dbg::GetDebugThread()) {
1631 // Skip the JDWP thread. Some debuggers get bent out of shape when they can't suspend and
1632 // query all threads, so it's easier if we just don't tell them about this thread.
1633 return;
1634 }
Ian Rogerscfaa4552012-11-26 21:00:08 -08001635 Object* peer = t->GetPeer();
jeffhao0dfbb7e2012-11-28 15:26:03 -08001636 if (IsInDesiredThreadGroup(peer)) {
Ian Rogers120f1c72012-09-28 17:17:10 -07001637 thread_ids_.push_back(gRegistry->Add(peer));
Elliott Hughesa2155262011-11-16 16:26:58 -08001638 }
1639 }
1640
Ian Rogers365c1022012-06-22 15:05:28 -07001641 private:
jeffhao0dfbb7e2012-11-28 15:26:03 -08001642 bool IsInDesiredThreadGroup(Object* peer)
1643 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
jeffhao0dfbb7e2012-11-28 15:26:03 -08001644 // peer might be NULL if the thread is still starting up.
1645 if (peer == NULL) {
1646 // We can't tell the debugger about this thread yet.
1647 // TODO: if we identified threads to the debugger by their Thread*
1648 // rather than their peer's Object*, we could fix this.
1649 // Doing so might help us report ZOMBIE threads too.
1650 return false;
1651 }
jeffhaoc1e04902012-12-13 12:41:10 -08001652 // Do we want threads from all thread groups?
1653 if (desired_thread_group_ == NULL) {
1654 return true;
1655 }
jeffhao0dfbb7e2012-11-28 15:26:03 -08001656 Object* group = soa_.DecodeField(WellKnownClasses::java_lang_Thread_group)->GetObject(peer);
1657 return (group == desired_thread_group_);
1658 }
1659
Mathieu Chartierdbe6f462012-09-25 16:54:50 -07001660 const ScopedObjectAccessUnchecked& soa_;
jeffhao0dfbb7e2012-11-28 15:26:03 -08001661 Object* const desired_thread_group_;
Elliott Hughescaf76542012-06-28 16:08:22 -07001662 std::vector<JDWP::ObjectId>& thread_ids_;
Elliott Hughesa2155262011-11-16 16:26:58 -08001663 };
1664
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001665 ScopedObjectAccessUnchecked soa(Thread::Current());
Elliott Hughescaf76542012-06-28 16:08:22 -07001666 Object* thread_group = gRegistry->Get<Object*>(thread_group_id);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001667 ThreadListVisitor tlv(soa, thread_group, thread_ids);
Ian Rogers50b35e22012-10-04 10:09:15 -07001668 MutexLock mu(soa.Self(), *Locks::thread_list_lock_);
Elliott Hughesf8349362012-06-18 15:00:06 -07001669 Runtime::Current()->GetThreadList()->ForEach(ThreadListVisitor::Visit, &tlv);
Elliott Hughescaf76542012-06-28 16:08:22 -07001670}
Elliott Hughesa2155262011-11-16 16:26:58 -08001671
Elliott Hughescaf76542012-06-28 16:08:22 -07001672void Dbg::GetChildThreadGroups(JDWP::ObjectId thread_group_id, std::vector<JDWP::ObjectId>& child_thread_group_ids) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001673 ScopedObjectAccess soa(Thread::Current());
Elliott Hughescaf76542012-06-28 16:08:22 -07001674 Object* thread_group = gRegistry->Get<Object*>(thread_group_id);
1675
1676 // Get the ArrayList<ThreadGroup> "groups" out of this thread group...
1677 Field* groups_field = thread_group->GetClass()->FindInstanceField("groups", "Ljava/util/List;");
1678 Object* groups_array_list = groups_field->GetObject(thread_group);
1679
1680 // Get the array and size out of the ArrayList<ThreadGroup>...
1681 Field* array_field = groups_array_list->GetClass()->FindInstanceField("array", "[Ljava/lang/Object;");
1682 Field* size_field = groups_array_list->GetClass()->FindInstanceField("size", "I");
1683 ObjectArray<Object>* groups_array = array_field->GetObject(groups_array_list)->AsObjectArray<Object>();
1684 const int32_t size = size_field->GetInt(groups_array_list);
1685
1686 // Copy the first 'size' elements out of the array into the result.
1687 for (int32_t i = 0; i < size; ++i) {
1688 child_thread_group_ids.push_back(gRegistry->Add(groups_array->Get(i)));
Elliott Hughesa2155262011-11-16 16:26:58 -08001689 }
1690}
1691
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001692static int GetStackDepth(Thread* thread)
Ian Rogersb726dcb2012-09-05 08:57:23 -07001693 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Ian Rogers0399dde2012-06-06 17:09:28 -07001694 struct CountStackDepthVisitor : public StackVisitor {
1695 CountStackDepthVisitor(const ManagedStack* stack,
Ian Rogers306057f2012-11-26 12:45:53 -08001696 const std::deque<InstrumentationStackFrame>* instrumentation_stack)
jeffhao725a9572012-11-13 18:20:12 -08001697 : StackVisitor(stack, instrumentation_stack, NULL), depth(0) {}
Ian Rogers0399dde2012-06-06 17:09:28 -07001698
1699 bool VisitFrame() {
1700 if (!GetMethod()->IsRuntimeMethod()) {
Elliott Hughesf8a2df72011-12-01 12:19:54 -08001701 ++depth;
1702 }
Elliott Hughes530fa002012-03-12 11:44:49 -07001703 return true;
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001704 }
1705 size_t depth;
1706 };
Elliott Hughes08fc03a2012-06-26 17:34:00 -07001707
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001708 if (kIsDebugBuild) {
Ian Rogers50b35e22012-10-04 10:09:15 -07001709 MutexLock mu(Thread::Current(), *Locks::thread_suspend_count_lock_);
jeffhao09bfc6a2012-12-11 18:11:43 -08001710 CHECK(thread == Thread::Current() || thread->IsSuspended());
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001711 }
jeffhao725a9572012-11-13 18:20:12 -08001712 CountStackDepthVisitor visitor(thread->GetManagedStack(), thread->GetInstrumentationStack());
Ian Rogers0399dde2012-06-06 17:09:28 -07001713 visitor.WalkStack();
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001714 return visitor.depth;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001715}
1716
Elliott Hughes221229c2013-01-08 18:17:50 -08001717JDWP::JdwpError Dbg::GetThreadFrameCount(JDWP::ObjectId thread_id, size_t& result) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001718 ScopedObjectAccess soa(Thread::Current());
jeffhaoa77f0f62012-12-05 17:19:31 -08001719 MutexLock mu(soa.Self(), *Locks::thread_list_lock_);
Elliott Hughes221229c2013-01-08 18:17:50 -08001720 Thread* thread;
1721 JDWP::JdwpError error = DecodeThread(soa, thread_id, thread);
1722 if (error != JDWP::ERR_NONE) {
1723 return error;
1724 }
Elliott Hughesf15f4a02013-01-09 10:09:38 -08001725 if (!IsSuspendedForDebugger(soa, thread)) {
1726 return JDWP::ERR_THREAD_NOT_SUSPENDED;
1727 }
Elliott Hughes221229c2013-01-08 18:17:50 -08001728 result = GetStackDepth(thread);
1729 return JDWP::ERR_NONE;
Elliott Hughes86964332012-02-15 19:37:42 -08001730}
1731
Ian Rogers306057f2012-11-26 12:45:53 -08001732JDWP::JdwpError Dbg::GetThreadFrames(JDWP::ObjectId thread_id, size_t start_frame,
1733 size_t frame_count, JDWP::ExpandBuf* buf) {
Elliott Hughes6e9d22c2012-06-22 15:02:37 -07001734 class GetFrameVisitor : public StackVisitor {
1735 public:
Ian Rogers306057f2012-11-26 12:45:53 -08001736 GetFrameVisitor(const ManagedStack* stack,
1737 const std::deque<InstrumentationStackFrame>* instrumentation_stack,
Elliott Hughes6e9d22c2012-06-22 15:02:37 -07001738 size_t start_frame, size_t frame_count, JDWP::ExpandBuf* buf)
Ian Rogersb726dcb2012-09-05 08:57:23 -07001739 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_)
jeffhao725a9572012-11-13 18:20:12 -08001740 : StackVisitor(stack, instrumentation_stack, NULL), depth_(0),
Elliott Hughes6e9d22c2012-06-22 15:02:37 -07001741 start_frame_(start_frame), frame_count_(frame_count), buf_(buf) {
1742 expandBufAdd4BE(buf_, frame_count_);
Elliott Hughes03181a82011-11-17 17:22:21 -08001743 }
Ian Rogers0399dde2012-06-06 17:09:28 -07001744
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001745 // TODO: Enable annotalysis. We know lock is held in constructor, but abstraction confuses
1746 // annotalysis.
1747 virtual bool VisitFrame() NO_THREAD_SAFETY_ANALYSIS {
Ian Rogers0399dde2012-06-06 17:09:28 -07001748 if (GetMethod()->IsRuntimeMethod()) {
Elliott Hughes530fa002012-03-12 11:44:49 -07001749 return true; // The debugger can't do anything useful with a frame that has no Method*.
Elliott Hughes03181a82011-11-17 17:22:21 -08001750 }
Elliott Hughes6e9d22c2012-06-22 15:02:37 -07001751 if (depth_ >= start_frame_ + frame_count_) {
Elliott Hughes530fa002012-03-12 11:44:49 -07001752 return false;
Elliott Hughes03181a82011-11-17 17:22:21 -08001753 }
Elliott Hughes6e9d22c2012-06-22 15:02:37 -07001754 if (depth_ >= start_frame_) {
1755 JDWP::FrameId frame_id(GetFrameId());
1756 JDWP::JdwpLocation location;
1757 SetLocation(location, GetMethod(), GetDexPc());
Elliott Hughes7baf96f2012-06-22 16:33:50 -07001758 VLOG(jdwp) << StringPrintf(" Frame %3zd: id=%3lld ", depth_, frame_id) << location;
Elliott Hughes6e9d22c2012-06-22 15:02:37 -07001759 expandBufAdd8BE(buf_, frame_id);
1760 expandBufAddLocation(buf_, location);
1761 }
1762 ++depth_;
Elliott Hughes530fa002012-03-12 11:44:49 -07001763 return true;
Elliott Hughes03181a82011-11-17 17:22:21 -08001764 }
Elliott Hughes6e9d22c2012-06-22 15:02:37 -07001765
1766 private:
1767 size_t depth_;
1768 const size_t start_frame_;
1769 const size_t frame_count_;
1770 JDWP::ExpandBuf* buf_;
Elliott Hughes03181a82011-11-17 17:22:21 -08001771 };
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001772
1773 ScopedObjectAccessUnchecked soa(Thread::Current());
jeffhaoa77f0f62012-12-05 17:19:31 -08001774 MutexLock mu(soa.Self(), *Locks::thread_list_lock_);
Elliott Hughes221229c2013-01-08 18:17:50 -08001775 Thread* thread;
1776 JDWP::JdwpError error = DecodeThread(soa, thread_id, thread);
1777 if (error != JDWP::ERR_NONE) {
1778 return error;
1779 }
Elliott Hughesf15f4a02013-01-09 10:09:38 -08001780 if (!IsSuspendedForDebugger(soa, thread)) {
1781 return JDWP::ERR_THREAD_NOT_SUSPENDED;
1782 }
Ian Rogers306057f2012-11-26 12:45:53 -08001783 GetFrameVisitor visitor(thread->GetManagedStack(), thread->GetInstrumentationStack(),
1784 start_frame, frame_count, buf);
Ian Rogers0399dde2012-06-06 17:09:28 -07001785 visitor.WalkStack();
Elliott Hughes6e9d22c2012-06-22 15:02:37 -07001786 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001787}
1788
1789JDWP::ObjectId Dbg::GetThreadSelfId() {
Mathieu Chartierdbe6f462012-09-25 16:54:50 -07001790 ScopedObjectAccessUnchecked soa(Thread::Current());
Ian Rogerscfaa4552012-11-26 21:00:08 -08001791 return gRegistry->Add(soa.Self()->GetPeer());
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001792}
1793
Elliott Hughes475fc232011-10-25 15:00:35 -07001794void Dbg::SuspendVM() {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001795 Runtime::Current()->GetThreadList()->SuspendAllForDebugger();
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001796}
1797
1798void Dbg::ResumeVM() {
Elliott Hughesc61a2672012-06-21 14:52:29 -07001799 Runtime::Current()->GetThreadList()->UndoDebuggerSuspensions();
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001800}
1801
Elliott Hughes221229c2013-01-08 18:17:50 -08001802JDWP::JdwpError Dbg::SuspendThread(JDWP::ObjectId thread_id, bool request_suspension) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001803 ScopedLocalRef<jobject> peer(Thread::Current()->GetJniEnv(), NULL);
1804 {
1805 ScopedObjectAccess soa(Thread::Current());
Elliott Hughes221229c2013-01-08 18:17:50 -08001806 peer.reset(soa.AddLocalReference<jobject>(gRegistry->Get<Object*>(thread_id)));
Elliott Hughes4e235312011-12-02 11:34:15 -08001807 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001808 if (peer.get() == NULL) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001809 return JDWP::ERR_THREAD_NOT_ALIVE;
1810 }
1811 // Suspend thread to build stack trace.
Elliott Hughesf327e072013-01-09 16:01:26 -08001812 bool timed_out;
1813 Thread* thread = Thread::SuspendForDebugger(peer.get(), request_suspension, &timed_out);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001814 if (thread != NULL) {
1815 return JDWP::ERR_NONE;
Elliott Hughesf327e072013-01-09 16:01:26 -08001816 } else if (timed_out) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001817 return JDWP::ERR_INTERNAL;
1818 } else {
1819 return JDWP::ERR_THREAD_NOT_ALIVE;
1820 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001821}
1822
Elliott Hughes221229c2013-01-08 18:17:50 -08001823void Dbg::ResumeThread(JDWP::ObjectId thread_id) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001824 ScopedObjectAccessUnchecked soa(Thread::Current());
Elliott Hughes221229c2013-01-08 18:17:50 -08001825 Object* peer = gRegistry->Get<Object*>(thread_id);
jeffhaoa77f0f62012-12-05 17:19:31 -08001826 Thread* thread;
1827 {
1828 MutexLock mu(soa.Self(), *Locks::thread_list_lock_);
1829 thread = Thread::FromManagedThread(soa, peer);
1830 }
Elliott Hughes4e235312011-12-02 11:34:15 -08001831 if (thread == NULL) {
1832 LOG(WARNING) << "No such thread for resume: " << peer;
1833 return;
1834 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001835 bool needs_resume;
1836 {
Ian Rogers50b35e22012-10-04 10:09:15 -07001837 MutexLock mu2(soa.Self(), *Locks::thread_suspend_count_lock_);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001838 needs_resume = thread->GetSuspendCount() > 0;
1839 }
1840 if (needs_resume) {
Elliott Hughes546b9862012-06-20 16:06:13 -07001841 Runtime::Current()->GetThreadList()->Resume(thread, true);
1842 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001843}
1844
1845void Dbg::SuspendSelf() {
Elliott Hughes475fc232011-10-25 15:00:35 -07001846 Runtime::Current()->GetThreadList()->SuspendSelfForDebugger();
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001847}
1848
Ian Rogers0399dde2012-06-06 17:09:28 -07001849struct GetThisVisitor : public StackVisitor {
Ian Rogers306057f2012-11-26 12:45:53 -08001850 GetThisVisitor(const ManagedStack* stack,
1851 const std::deque<InstrumentationStackFrame>* instrumentation_stack,
Elliott Hughes88d63092013-01-09 09:55:54 -08001852 Context* context, JDWP::FrameId frame_id)
Ian Rogersb726dcb2012-09-05 08:57:23 -07001853 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_)
Elliott Hughes88d63092013-01-09 09:55:54 -08001854 : StackVisitor(stack, instrumentation_stack, context), this_object(NULL), frame_id(frame_id) {}
Ian Rogers0399dde2012-06-06 17:09:28 -07001855
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001856 // TODO: Enable annotalysis. We know lock is held in constructor, but abstraction confuses
1857 // annotalysis.
1858 virtual bool VisitFrame() NO_THREAD_SAFETY_ANALYSIS {
Elliott Hughes6e9d22c2012-06-22 15:02:37 -07001859 if (frame_id != GetFrameId()) {
Ian Rogers0399dde2012-06-06 17:09:28 -07001860 return true; // continue
1861 }
Mathieu Chartier66f19252012-09-18 08:57:04 -07001862 AbstractMethod* m = GetMethod();
Ian Rogers0399dde2012-06-06 17:09:28 -07001863 if (m->IsNative() || m->IsStatic()) {
Elliott Hughes6e9d22c2012-06-22 15:02:37 -07001864 this_object = NULL;
Ian Rogers0399dde2012-06-06 17:09:28 -07001865 } else {
1866 uint16_t reg = DemangleSlot(0, m);
Ian Rogers2bcb4a42012-11-08 10:39:18 -08001867 this_object = reinterpret_cast<Object*>(GetVReg(m, reg, kReferenceVReg));
Ian Rogers0399dde2012-06-06 17:09:28 -07001868 }
1869 return false;
Elliott Hughes86b00102011-12-05 17:54:26 -08001870 }
Ian Rogers0399dde2012-06-06 17:09:28 -07001871
Elliott Hughes6e9d22c2012-06-22 15:02:37 -07001872 Object* this_object;
1873 JDWP::FrameId frame_id;
Ian Rogers0399dde2012-06-06 17:09:28 -07001874};
1875
Mathieu Chartier66f19252012-09-18 08:57:04 -07001876static Object* GetThis(Thread* self, AbstractMethod* m, size_t frame_id)
Ian Rogersb726dcb2012-09-05 08:57:23 -07001877 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Elliott Hughescaf76542012-06-28 16:08:22 -07001878 // TODO: should we return the 'this' we passed through to non-static native methods?
Ian Rogers0399dde2012-06-06 17:09:28 -07001879 if (m->IsNative() || m->IsStatic()) {
1880 return NULL;
1881 }
Elliott Hughescaf76542012-06-28 16:08:22 -07001882
Ian Rogers0399dde2012-06-06 17:09:28 -07001883 UniquePtr<Context> context(Context::Create());
jeffhao725a9572012-11-13 18:20:12 -08001884 GetThisVisitor visitor(self->GetManagedStack(), self->GetInstrumentationStack(), context.get(), frame_id);
Elliott Hughescaf76542012-06-28 16:08:22 -07001885 visitor.WalkStack();
1886 return visitor.this_object;
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08001887}
1888
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001889JDWP::JdwpError Dbg::GetThisObject(JDWP::ObjectId thread_id, JDWP::FrameId frame_id,
1890 JDWP::ObjectId* result) {
1891 ScopedObjectAccessUnchecked soa(Thread::Current());
1892 Thread* thread;
1893 {
Ian Rogers50b35e22012-10-04 10:09:15 -07001894 MutexLock mu(soa.Self(), *Locks::thread_list_lock_);
Elliott Hughes221229c2013-01-08 18:17:50 -08001895 JDWP::JdwpError error = DecodeThread(soa, thread_id, thread);
1896 if (error != JDWP::ERR_NONE) {
1897 return error;
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001898 }
Elliott Hughes9e0c1752013-01-09 14:02:58 -08001899 if (!IsSuspendedForDebugger(soa, thread)) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001900 return JDWP::ERR_THREAD_NOT_SUSPENDED;
1901 }
Elliott Hughes6e9d22c2012-06-22 15:02:37 -07001902 }
Elliott Hughescaf76542012-06-28 16:08:22 -07001903 UniquePtr<Context> context(Context::Create());
jeffhao725a9572012-11-13 18:20:12 -08001904 GetThisVisitor visitor(thread->GetManagedStack(), thread->GetInstrumentationStack(), context.get(), frame_id);
Ian Rogers0399dde2012-06-06 17:09:28 -07001905 visitor.WalkStack();
Elliott Hughes6e9d22c2012-06-22 15:02:37 -07001906 *result = gRegistry->Add(visitor.this_object);
1907 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001908}
1909
Elliott Hughes88d63092013-01-09 09:55:54 -08001910void Dbg::GetLocalValue(JDWP::ObjectId thread_id, JDWP::FrameId frame_id, int slot, JDWP::JdwpTag tag,
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001911 uint8_t* buf, size_t width) {
Ian Rogers0399dde2012-06-06 17:09:28 -07001912 struct GetLocalVisitor : public StackVisitor {
Ian Rogers306057f2012-11-26 12:45:53 -08001913 GetLocalVisitor(const ManagedStack* stack,
1914 const std::deque<InstrumentationStackFrame>* instrumentation_stack,
Elliott Hughes88d63092013-01-09 09:55:54 -08001915 Context* context, JDWP::FrameId frame_id, int slot, JDWP::JdwpTag tag,
Ian Rogersca190662012-06-26 15:45:57 -07001916 uint8_t* buf, size_t width)
Ian Rogersb726dcb2012-09-05 08:57:23 -07001917 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_)
Elliott Hughes88d63092013-01-09 09:55:54 -08001918 : StackVisitor(stack, instrumentation_stack, context), frame_id_(frame_id), slot_(slot), tag_(tag),
Ian Rogersca190662012-06-26 15:45:57 -07001919 buf_(buf), width_(width) {}
1920
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001921 // TODO: Enable annotalysis. We know lock is held in constructor, but abstraction confuses
1922 // annotalysis.
1923 bool VisitFrame() NO_THREAD_SAFETY_ANALYSIS {
Ian Rogers0399dde2012-06-06 17:09:28 -07001924 if (GetFrameId() != frame_id_) {
1925 return true; // Not our frame, carry on.
Elliott Hughesdbb40792011-11-18 17:05:22 -08001926 }
Ian Rogers0399dde2012-06-06 17:09:28 -07001927 // TODO: check that the tag is compatible with the actual type of the slot!
Mathieu Chartier66f19252012-09-18 08:57:04 -07001928 AbstractMethod* m = GetMethod();
Ian Rogers0399dde2012-06-06 17:09:28 -07001929 uint16_t reg = DemangleSlot(slot_, m);
Elliott Hughesdbb40792011-11-18 17:05:22 -08001930
Ian Rogers0399dde2012-06-06 17:09:28 -07001931 switch (tag_) {
1932 case JDWP::JT_BOOLEAN:
1933 {
1934 CHECK_EQ(width_, 1U);
Ian Rogers2bcb4a42012-11-08 10:39:18 -08001935 uint32_t intVal = GetVReg(m, reg, kIntVReg);
Ian Rogers0399dde2012-06-06 17:09:28 -07001936 VLOG(jdwp) << "get boolean local " << reg << " = " << intVal;
1937 JDWP::Set1(buf_+1, intVal != 0);
1938 }
1939 break;
1940 case JDWP::JT_BYTE:
1941 {
1942 CHECK_EQ(width_, 1U);
Ian Rogers2bcb4a42012-11-08 10:39:18 -08001943 uint32_t intVal = GetVReg(m, reg, kIntVReg);
Ian Rogers0399dde2012-06-06 17:09:28 -07001944 VLOG(jdwp) << "get byte local " << reg << " = " << intVal;
1945 JDWP::Set1(buf_+1, intVal);
1946 }
1947 break;
1948 case JDWP::JT_SHORT:
1949 case JDWP::JT_CHAR:
1950 {
1951 CHECK_EQ(width_, 2U);
Ian Rogers2bcb4a42012-11-08 10:39:18 -08001952 uint32_t intVal = GetVReg(m, reg, kIntVReg);
Ian Rogers0399dde2012-06-06 17:09:28 -07001953 VLOG(jdwp) << "get short/char local " << reg << " = " << intVal;
1954 JDWP::Set2BE(buf_+1, intVal);
1955 }
1956 break;
1957 case JDWP::JT_INT:
Ian Rogers2bcb4a42012-11-08 10:39:18 -08001958 {
1959 CHECK_EQ(width_, 4U);
1960 uint32_t intVal = GetVReg(m, reg, kIntVReg);
1961 VLOG(jdwp) << "get int local " << reg << " = " << intVal;
1962 JDWP::Set4BE(buf_+1, intVal);
1963 }
1964 break;
Ian Rogers0399dde2012-06-06 17:09:28 -07001965 case JDWP::JT_FLOAT:
1966 {
1967 CHECK_EQ(width_, 4U);
Ian Rogers2bcb4a42012-11-08 10:39:18 -08001968 uint32_t intVal = GetVReg(m, reg, kFloatVReg);
Ian Rogers0399dde2012-06-06 17:09:28 -07001969 VLOG(jdwp) << "get int/float local " << reg << " = " << intVal;
1970 JDWP::Set4BE(buf_+1, intVal);
1971 }
1972 break;
1973 case JDWP::JT_ARRAY:
1974 {
1975 CHECK_EQ(width_, sizeof(JDWP::ObjectId));
Ian Rogers2bcb4a42012-11-08 10:39:18 -08001976 Object* o = reinterpret_cast<Object*>(GetVReg(m, reg, kReferenceVReg));
Ian Rogers0399dde2012-06-06 17:09:28 -07001977 VLOG(jdwp) << "get array local " << reg << " = " << o;
1978 if (!Runtime::Current()->GetHeap()->IsHeapAddress(o)) {
1979 LOG(FATAL) << "Register " << reg << " expected to hold array: " << o;
1980 }
1981 JDWP::SetObjectId(buf_+1, gRegistry->Add(o));
1982 }
1983 break;
1984 case JDWP::JT_CLASS_LOADER:
1985 case JDWP::JT_CLASS_OBJECT:
1986 case JDWP::JT_OBJECT:
1987 case JDWP::JT_STRING:
1988 case JDWP::JT_THREAD:
1989 case JDWP::JT_THREAD_GROUP:
1990 {
1991 CHECK_EQ(width_, sizeof(JDWP::ObjectId));
Ian Rogers2bcb4a42012-11-08 10:39:18 -08001992 Object* o = reinterpret_cast<Object*>(GetVReg(m, reg, kReferenceVReg));
Ian Rogers0399dde2012-06-06 17:09:28 -07001993 VLOG(jdwp) << "get object local " << reg << " = " << o;
1994 if (!Runtime::Current()->GetHeap()->IsHeapAddress(o)) {
1995 LOG(FATAL) << "Register " << reg << " expected to hold object: " << o;
1996 }
1997 tag_ = TagFromObject(o);
1998 JDWP::SetObjectId(buf_+1, gRegistry->Add(o));
1999 }
2000 break;
2001 case JDWP::JT_DOUBLE:
Ian Rogers2bcb4a42012-11-08 10:39:18 -08002002 {
2003 CHECK_EQ(width_, 8U);
2004 uint32_t lo = GetVReg(m, reg, kDoubleLoVReg);
2005 uint64_t hi = GetVReg(m, reg + 1, kDoubleHiVReg);
2006 uint64_t longVal = (hi << 32) | lo;
2007 VLOG(jdwp) << "get double/long local " << hi << ":" << lo << " = " << longVal;
2008 JDWP::Set8BE(buf_+1, longVal);
2009 }
2010 break;
Ian Rogers0399dde2012-06-06 17:09:28 -07002011 case JDWP::JT_LONG:
2012 {
2013 CHECK_EQ(width_, 8U);
Ian Rogers2bcb4a42012-11-08 10:39:18 -08002014 uint32_t lo = GetVReg(m, reg, kLongLoVReg);
2015 uint64_t hi = GetVReg(m, reg + 1, kLongHiVReg);
Ian Rogers0399dde2012-06-06 17:09:28 -07002016 uint64_t longVal = (hi << 32) | lo;
2017 VLOG(jdwp) << "get double/long local " << hi << ":" << lo << " = " << longVal;
2018 JDWP::Set8BE(buf_+1, longVal);
2019 }
2020 break;
2021 default:
2022 LOG(FATAL) << "Unknown tag " << tag_;
2023 break;
2024 }
2025
2026 // Prepend tag, which may have been updated.
2027 JDWP::Set1(buf_, tag_);
2028 return false;
2029 }
2030
2031 const JDWP::FrameId frame_id_;
2032 const int slot_;
2033 JDWP::JdwpTag tag_;
2034 uint8_t* const buf_;
2035 const size_t width_;
2036 };
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002037
2038 ScopedObjectAccessUnchecked soa(Thread::Current());
jeffhaoa77f0f62012-12-05 17:19:31 -08002039 MutexLock mu(soa.Self(), *Locks::thread_list_lock_);
Elliott Hughes221229c2013-01-08 18:17:50 -08002040 Thread* thread;
2041 JDWP::JdwpError error = DecodeThread(soa, thread_id, thread);
2042 if (error != JDWP::ERR_NONE) {
2043 return;
2044 }
Ian Rogers0399dde2012-06-06 17:09:28 -07002045 UniquePtr<Context> context(Context::Create());
jeffhao725a9572012-11-13 18:20:12 -08002046 GetLocalVisitor visitor(thread->GetManagedStack(), thread->GetInstrumentationStack(), context.get(),
Elliott Hughes88d63092013-01-09 09:55:54 -08002047 frame_id, slot, tag, buf, width);
Ian Rogers0399dde2012-06-06 17:09:28 -07002048 visitor.WalkStack();
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002049}
2050
Elliott Hughes88d63092013-01-09 09:55:54 -08002051void Dbg::SetLocalValue(JDWP::ObjectId thread_id, JDWP::FrameId frame_id, int slot, JDWP::JdwpTag tag,
Ian Rogers0399dde2012-06-06 17:09:28 -07002052 uint64_t value, size_t width) {
2053 struct SetLocalVisitor : public StackVisitor {
Ian Rogers306057f2012-11-26 12:45:53 -08002054 SetLocalVisitor(const ManagedStack* stack, const std::deque<InstrumentationStackFrame>* instrumentation_stack, Context* context,
Ian Rogers0399dde2012-06-06 17:09:28 -07002055 JDWP::FrameId frame_id, int slot, JDWP::JdwpTag tag, uint64_t value,
Ian Rogersca190662012-06-26 15:45:57 -07002056 size_t width)
Ian Rogersb726dcb2012-09-05 08:57:23 -07002057 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_)
jeffhao725a9572012-11-13 18:20:12 -08002058 : StackVisitor(stack, instrumentation_stack, context),
Elliott Hughes08fc03a2012-06-26 17:34:00 -07002059 frame_id_(frame_id), slot_(slot), tag_(tag), value_(value), width_(width) {}
Ian Rogersca190662012-06-26 15:45:57 -07002060
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002061 // TODO: Enable annotalysis. We know lock is held in constructor, but abstraction confuses
2062 // annotalysis.
2063 bool VisitFrame() NO_THREAD_SAFETY_ANALYSIS {
Ian Rogers0399dde2012-06-06 17:09:28 -07002064 if (GetFrameId() != frame_id_) {
2065 return true; // Not our frame, carry on.
2066 }
2067 // TODO: check that the tag is compatible with the actual type of the slot!
Mathieu Chartier66f19252012-09-18 08:57:04 -07002068 AbstractMethod* m = GetMethod();
Ian Rogers0399dde2012-06-06 17:09:28 -07002069 uint16_t reg = DemangleSlot(slot_, m);
2070
2071 switch (tag_) {
2072 case JDWP::JT_BOOLEAN:
2073 case JDWP::JT_BYTE:
2074 CHECK_EQ(width_, 1U);
Ian Rogers2bcb4a42012-11-08 10:39:18 -08002075 SetVReg(m, reg, static_cast<uint32_t>(value_), kIntVReg);
Ian Rogers0399dde2012-06-06 17:09:28 -07002076 break;
2077 case JDWP::JT_SHORT:
2078 case JDWP::JT_CHAR:
2079 CHECK_EQ(width_, 2U);
Ian Rogers2bcb4a42012-11-08 10:39:18 -08002080 SetVReg(m, reg, static_cast<uint32_t>(value_), kIntVReg);
Ian Rogers0399dde2012-06-06 17:09:28 -07002081 break;
2082 case JDWP::JT_INT:
Ian Rogers2bcb4a42012-11-08 10:39:18 -08002083 CHECK_EQ(width_, 4U);
2084 SetVReg(m, reg, static_cast<uint32_t>(value_), kIntVReg);
2085 break;
Ian Rogers0399dde2012-06-06 17:09:28 -07002086 case JDWP::JT_FLOAT:
2087 CHECK_EQ(width_, 4U);
Ian Rogers2bcb4a42012-11-08 10:39:18 -08002088 SetVReg(m, reg, static_cast<uint32_t>(value_), kFloatVReg);
Ian Rogers0399dde2012-06-06 17:09:28 -07002089 break;
2090 case JDWP::JT_ARRAY:
2091 case JDWP::JT_OBJECT:
2092 case JDWP::JT_STRING:
2093 {
2094 CHECK_EQ(width_, sizeof(JDWP::ObjectId));
2095 Object* o = gRegistry->Get<Object*>(static_cast<JDWP::ObjectId>(value_));
2096 if (o == kInvalidObject) {
2097 UNIMPLEMENTED(FATAL) << "return an error code when given an invalid object to store";
2098 }
Ian Rogers2bcb4a42012-11-08 10:39:18 -08002099 SetVReg(m, reg, static_cast<uint32_t>(reinterpret_cast<uintptr_t>(o)), kReferenceVReg);
Ian Rogers0399dde2012-06-06 17:09:28 -07002100 }
2101 break;
2102 case JDWP::JT_DOUBLE:
Ian Rogers2bcb4a42012-11-08 10:39:18 -08002103 CHECK_EQ(width_, 8U);
2104 SetVReg(m, reg, static_cast<uint32_t>(value_), kDoubleLoVReg);
2105 SetVReg(m, reg + 1, static_cast<uint32_t>(value_ >> 32), kDoubleHiVReg);
2106 break;
Ian Rogers0399dde2012-06-06 17:09:28 -07002107 case JDWP::JT_LONG:
2108 CHECK_EQ(width_, 8U);
Ian Rogers2bcb4a42012-11-08 10:39:18 -08002109 SetVReg(m, reg, static_cast<uint32_t>(value_), kLongLoVReg);
2110 SetVReg(m, reg + 1, static_cast<uint32_t>(value_ >> 32), kLongHiVReg);
Ian Rogers0399dde2012-06-06 17:09:28 -07002111 break;
2112 default:
2113 LOG(FATAL) << "Unknown tag " << tag_;
2114 break;
2115 }
2116 return false;
2117 }
2118
2119 const JDWP::FrameId frame_id_;
2120 const int slot_;
2121 const JDWP::JdwpTag tag_;
2122 const uint64_t value_;
2123 const size_t width_;
2124 };
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002125
2126 ScopedObjectAccessUnchecked soa(Thread::Current());
jeffhaoa77f0f62012-12-05 17:19:31 -08002127 MutexLock mu(soa.Self(), *Locks::thread_list_lock_);
Elliott Hughes221229c2013-01-08 18:17:50 -08002128 Thread* thread;
2129 JDWP::JdwpError error = DecodeThread(soa, thread_id, thread);
2130 if (error != JDWP::ERR_NONE) {
2131 return;
2132 }
Elliott Hughes08fc03a2012-06-26 17:34:00 -07002133 UniquePtr<Context> context(Context::Create());
jeffhao725a9572012-11-13 18:20:12 -08002134 SetLocalVisitor visitor(thread->GetManagedStack(), thread->GetInstrumentationStack(), context.get(),
Elliott Hughes88d63092013-01-09 09:55:54 -08002135 frame_id, slot, tag, value, width);
Ian Rogers0399dde2012-06-06 17:09:28 -07002136 visitor.WalkStack();
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002137}
2138
Mathieu Chartier66f19252012-09-18 08:57:04 -07002139void Dbg::PostLocationEvent(const AbstractMethod* m, int dex_pc, Object* this_object, int event_flags) {
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08002140 Class* c = m->GetDeclaringClass();
2141
2142 JDWP::JdwpLocation location;
Elliott Hughes74847412012-06-20 18:10:21 -07002143 location.type_tag = c->IsInterface() ? JDWP::TT_INTERFACE : JDWP::TT_CLASS;
2144 location.class_id = gRegistry->Add(c);
2145 location.method_id = ToMethodId(m);
Elliott Hughes972a47b2012-02-21 18:16:06 -08002146 location.dex_pc = m->IsNative() ? -1 : dex_pc;
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08002147
2148 // Note we use "NoReg" so we don't keep track of references that are
2149 // never actually sent to the debugger. 'this_id' is only used to
2150 // compare against registered events...
2151 JDWP::ObjectId this_id = static_cast<JDWP::ObjectId>(reinterpret_cast<uintptr_t>(this_object));
2152 if (gJdwpState->PostLocationEvent(&location, this_id, event_flags)) {
2153 // ...unless there's a registered event, in which case we
2154 // need to really track the class and 'this'.
2155 gRegistry->Add(c);
2156 gRegistry->Add(this_object);
2157 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002158}
2159
Elliott Hughescaf76542012-06-28 16:08:22 -07002160void Dbg::PostException(Thread* thread,
Mathieu Chartier66f19252012-09-18 08:57:04 -07002161 JDWP::FrameId throw_frame_id, AbstractMethod* throw_method, uint32_t throw_dex_pc,
2162 AbstractMethod* catch_method, uint32_t catch_dex_pc, Throwable* exception) {
Elliott Hughesc0f09332012-03-26 13:27:06 -07002163 if (!IsDebuggerActive()) {
Ian Rogers0ad5bb82011-12-07 10:16:32 -08002164 return;
2165 }
Elliott Hughes4740cdf2011-12-07 14:07:12 -08002166
Elliott Hughesd07986f2011-12-06 18:27:45 -08002167 JDWP::JdwpLocation throw_location;
Elliott Hughescaf76542012-06-28 16:08:22 -07002168 SetLocation(throw_location, throw_method, throw_dex_pc);
Elliott Hughesd07986f2011-12-06 18:27:45 -08002169 JDWP::JdwpLocation catch_location;
Elliott Hughescaf76542012-06-28 16:08:22 -07002170 SetLocation(catch_location, catch_method, catch_dex_pc);
Elliott Hughesd07986f2011-12-06 18:27:45 -08002171
2172 // We need 'this' for InstanceOnly filters.
Elliott Hughescaf76542012-06-28 16:08:22 -07002173 UniquePtr<Context> context(Context::Create());
jeffhao725a9572012-11-13 18:20:12 -08002174 GetThisVisitor visitor(thread->GetManagedStack(), thread->GetInstrumentationStack(), context.get(), throw_frame_id);
Elliott Hughescaf76542012-06-28 16:08:22 -07002175 visitor.WalkStack();
2176 JDWP::ObjectId this_id = gRegistry->Add(visitor.this_object);
Elliott Hughesd07986f2011-12-06 18:27:45 -08002177
2178 /*
2179 * Hand the event to the JDWP exception handler. Note we're using the
2180 * "NoReg" objectID on the exception, which is not strictly correct --
2181 * the exception object WILL be passed up to the debugger if the
2182 * debugger is interested in the event. We do this because the current
2183 * implementation of the debugger object registry never throws anything
2184 * away, and some people were experiencing a fatal build up of exception
2185 * objects when dealing with certain libraries.
2186 */
2187 JDWP::ObjectId exception_id = static_cast<JDWP::ObjectId>(reinterpret_cast<uintptr_t>(exception));
2188 JDWP::RefTypeId exception_class_id = gRegistry->Add(exception->GetClass());
2189
2190 gJdwpState->PostException(&throw_location, exception_id, exception_class_id, &catch_location, this_id);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002191}
2192
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002193void Dbg::PostClassPrepare(Class* c) {
Elliott Hughesc0f09332012-03-26 13:27:06 -07002194 if (!IsDebuggerActive()) {
Elliott Hughes4740cdf2011-12-07 14:07:12 -08002195 return;
2196 }
2197
Elliott Hughes3d30d9b2011-12-07 17:35:48 -08002198 // OLD-TODO - we currently always send both "verified" and "prepared" since
Elliott Hughes4740cdf2011-12-07 14:07:12 -08002199 // debuggers seem to like that. There might be some advantage to honesty,
2200 // since the class may not yet be verified.
2201 int state = JDWP::CS_VERIFIED | JDWP::CS_PREPARED;
2202 JDWP::JdwpTypeTag tag = c->IsInterface() ? JDWP::TT_INTERFACE : JDWP::TT_CLASS;
2203 gJdwpState->PostClassPrepare(tag, gRegistry->Add(c), ClassHelper(c).GetDescriptor(), state);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002204}
2205
Elliott Hughescaf76542012-06-28 16:08:22 -07002206void Dbg::UpdateDebugger(int32_t dex_pc, Thread* self) {
Elliott Hughesc0f09332012-03-26 13:27:06 -07002207 if (!IsDebuggerActive() || dex_pc == -2 /* fake method exit */) {
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08002208 return;
2209 }
2210
Elliott Hughescaf76542012-06-28 16:08:22 -07002211 size_t frame_id;
Mathieu Chartier66f19252012-09-18 08:57:04 -07002212 AbstractMethod* m = self->GetCurrentMethod(NULL, &frame_id);
Elliott Hughescaf76542012-06-28 16:08:22 -07002213 //LOG(INFO) << "UpdateDebugger " << PrettyMethod(m) << "@" << dex_pc << " frame " << frame_id;
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08002214
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08002215 if (dex_pc == -1) {
Elliott Hughes2aa2e392012-02-17 17:15:43 -08002216 // We use a pc of -1 to represent method entry, since we might branch back to pc 0 later.
2217 // This means that for this special notification, there can't be anything else interesting
2218 // going on, so we're done already.
Elliott Hughescaf76542012-06-28 16:08:22 -07002219 Dbg::PostLocationEvent(m, 0, GetThis(self, m, frame_id), kMethodEntry);
Elliott Hughes2aa2e392012-02-17 17:15:43 -08002220 return;
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08002221 }
2222
Elliott Hughes2aa2e392012-02-17 17:15:43 -08002223 int event_flags = 0;
2224
Elliott Hughes86964332012-02-15 19:37:42 -08002225 if (IsBreakpoint(m, dex_pc)) {
2226 event_flags |= kBreakpoint;
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08002227 }
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08002228
jeffhao09bfc6a2012-12-11 18:11:43 -08002229 {
2230 // If the debugger is single-stepping one of our threads, check to
2231 // see if we're that thread and we've reached a step point.
2232 MutexLock mu(Thread::Current(), *Locks::breakpoint_lock_);
2233 if (gSingleStepControl.is_active && gSingleStepControl.thread == self) {
2234 CHECK(!m->IsNative());
2235 if (gSingleStepControl.step_depth == JDWP::SD_INTO) {
2236 // Step into method calls. We break when the line number
2237 // or method pointer changes. If we're in SS_MIN mode, we
2238 // always stop.
2239 if (gSingleStepControl.method != m) {
2240 event_flags |= kSingleStep;
2241 VLOG(jdwp) << "SS new method";
2242 } else if (gSingleStepControl.step_size == JDWP::SS_MIN) {
Elliott Hughes86964332012-02-15 19:37:42 -08002243 event_flags |= kSingleStep;
2244 VLOG(jdwp) << "SS new instruction";
Elliott Hughes2435a572012-02-17 16:07:41 -08002245 } else if (gSingleStepControl.dex_pcs.find(dex_pc) == gSingleStepControl.dex_pcs.end()) {
2246 event_flags |= kSingleStep;
2247 VLOG(jdwp) << "SS new line";
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08002248 }
jeffhao09bfc6a2012-12-11 18:11:43 -08002249 } else if (gSingleStepControl.step_depth == JDWP::SD_OVER) {
2250 // Step over method calls. We break when the line number is
2251 // different and the frame depth is <= the original frame
2252 // depth. (We can't just compare on the method, because we
2253 // might get unrolled past it by an exception, and it's tricky
2254 // to identify recursion.)
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08002255
jeffhao09bfc6a2012-12-11 18:11:43 -08002256 int stack_depth = GetStackDepth(self);
Elliott Hughes86964332012-02-15 19:37:42 -08002257
jeffhao09bfc6a2012-12-11 18:11:43 -08002258 if (stack_depth < gSingleStepControl.stack_depth) {
2259 // popped up one or more frames, always trigger
2260 event_flags |= kSingleStep;
2261 VLOG(jdwp) << "SS method pop";
2262 } else if (stack_depth == gSingleStepControl.stack_depth) {
2263 // same depth, see if we moved
2264 if (gSingleStepControl.step_size == JDWP::SS_MIN) {
2265 event_flags |= kSingleStep;
2266 VLOG(jdwp) << "SS new instruction";
2267 } else if (gSingleStepControl.dex_pcs.find(dex_pc) == gSingleStepControl.dex_pcs.end()) {
2268 event_flags |= kSingleStep;
2269 VLOG(jdwp) << "SS new line";
2270 }
2271 }
2272 } else {
2273 CHECK_EQ(gSingleStepControl.step_depth, JDWP::SD_OUT);
2274 // Return from the current method. We break when the frame
2275 // depth pops up.
2276
2277 // This differs from the "method exit" break in that it stops
2278 // with the PC at the next instruction in the returned-to
2279 // function, rather than the end of the returning function.
2280
2281 int stack_depth = GetStackDepth(self);
2282 if (stack_depth < gSingleStepControl.stack_depth) {
2283 event_flags |= kSingleStep;
2284 VLOG(jdwp) << "SS method pop";
2285 }
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08002286 }
2287 }
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08002288 }
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08002289
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08002290 // Check to see if this is a "return" instruction. JDWP says we should
2291 // send the event *after* the code has been executed, but it also says
2292 // the location we provide is the last instruction. Since the "return"
2293 // instruction has no interesting side effects, we should be safe.
2294 // (We can't just move this down to the returnFromMethod label because
2295 // we potentially need to combine it with other events.)
2296 // We're also not supposed to generate a method exit event if the method
2297 // terminates "with a thrown exception".
Elliott Hughes86964332012-02-15 19:37:42 -08002298 if (dex_pc >= 0) {
2299 const DexFile::CodeItem* code_item = MethodHelper(m).GetCodeItem();
Elliott Hughescaf76542012-06-28 16:08:22 -07002300 CHECK(code_item != NULL) << PrettyMethod(m) << " @" << dex_pc;
Elliott Hughes86964332012-02-15 19:37:42 -08002301 CHECK_LT(dex_pc, static_cast<int32_t>(code_item->insns_size_in_code_units_));
2302 if (Instruction::At(&code_item->insns_[dex_pc])->IsReturn()) {
2303 event_flags |= kMethodExit;
2304 }
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08002305 }
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08002306
2307 // If there's something interesting going on, see if it matches one
2308 // of the debugger filters.
2309 if (event_flags != 0) {
Elliott Hughescaf76542012-06-28 16:08:22 -07002310 Dbg::PostLocationEvent(m, dex_pc, GetThis(self, m, frame_id), event_flags);
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08002311 }
2312}
2313
Elliott Hughes86964332012-02-15 19:37:42 -08002314void Dbg::WatchLocation(const JDWP::JdwpLocation* location) {
jeffhao09bfc6a2012-12-11 18:11:43 -08002315 MutexLock mu(Thread::Current(), *Locks::breakpoint_lock_);
Mathieu Chartier66f19252012-09-18 08:57:04 -07002316 AbstractMethod* m = FromMethodId(location->method_id);
Elliott Hughes972a47b2012-02-21 18:16:06 -08002317 gBreakpoints.push_back(Breakpoint(m, location->dex_pc));
Elliott Hughes86964332012-02-15 19:37:42 -08002318 VLOG(jdwp) << "Set breakpoint #" << (gBreakpoints.size() - 1) << ": " << gBreakpoints[gBreakpoints.size() - 1];
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002319}
2320
Elliott Hughes86964332012-02-15 19:37:42 -08002321void Dbg::UnwatchLocation(const JDWP::JdwpLocation* location) {
jeffhao09bfc6a2012-12-11 18:11:43 -08002322 MutexLock mu(Thread::Current(), *Locks::breakpoint_lock_);
Mathieu Chartier66f19252012-09-18 08:57:04 -07002323 AbstractMethod* m = FromMethodId(location->method_id);
Elliott Hughes86964332012-02-15 19:37:42 -08002324 for (size_t i = 0; i < gBreakpoints.size(); ++i) {
Elliott Hughes972a47b2012-02-21 18:16:06 -08002325 if (gBreakpoints[i].method == m && gBreakpoints[i].dex_pc == location->dex_pc) {
Elliott Hughes86964332012-02-15 19:37:42 -08002326 VLOG(jdwp) << "Removed breakpoint #" << i << ": " << gBreakpoints[i];
2327 gBreakpoints.erase(gBreakpoints.begin() + i);
2328 return;
2329 }
2330 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002331}
2332
Elliott Hughes221229c2013-01-08 18:17:50 -08002333JDWP::JdwpError Dbg::ConfigureStep(JDWP::ObjectId thread_id, JDWP::JdwpStepSize step_size,
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002334 JDWP::JdwpStepDepth step_depth) {
2335 ScopedObjectAccessUnchecked soa(Thread::Current());
jeffhaoa77f0f62012-12-05 17:19:31 -08002336 MutexLock mu(soa.Self(), *Locks::thread_list_lock_);
Elliott Hughes221229c2013-01-08 18:17:50 -08002337 Thread* thread;
2338 JDWP::JdwpError error = DecodeThread(soa, thread_id, thread);
2339 if (error != JDWP::ERR_NONE) {
2340 return error;
Elliott Hughes2435a572012-02-17 16:07:41 -08002341 }
Elliott Hughes86964332012-02-15 19:37:42 -08002342
jeffhao09bfc6a2012-12-11 18:11:43 -08002343 MutexLock mu2(soa.Self(), *Locks::breakpoint_lock_);
Elliott Hughes86964332012-02-15 19:37:42 -08002344 // TODO: there's no theoretical reason why we couldn't support single-stepping
2345 // of multiple threads at once, but we never did so historically.
2346 if (gSingleStepControl.thread != NULL && thread != gSingleStepControl.thread) {
2347 LOG(WARNING) << "single-step already active for " << *gSingleStepControl.thread
2348 << "; switching to " << *thread;
2349 }
2350
Elliott Hughes2435a572012-02-17 16:07:41 -08002351 //
2352 // Work out what Method* we're in, the current line number, and how deep the stack currently
2353 // is for step-out.
2354 //
2355
Ian Rogers0399dde2012-06-06 17:09:28 -07002356 struct SingleStepStackVisitor : public StackVisitor {
2357 SingleStepStackVisitor(const ManagedStack* stack,
Ian Rogers306057f2012-11-26 12:45:53 -08002358 const std::deque<InstrumentationStackFrame>* instrumentation_stack)
jeffhao09bfc6a2012-12-11 18:11:43 -08002359 EXCLUSIVE_LOCKS_REQUIRED(Locks::breakpoint_lock_)
Ian Rogersb726dcb2012-09-05 08:57:23 -07002360 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_)
jeffhao725a9572012-11-13 18:20:12 -08002361 : StackVisitor(stack, instrumentation_stack, NULL) {
Elliott Hughes86964332012-02-15 19:37:42 -08002362 gSingleStepControl.method = NULL;
2363 gSingleStepControl.stack_depth = 0;
2364 }
Ian Rogersca190662012-06-26 15:45:57 -07002365
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002366 // TODO: Enable annotalysis. We know lock is held in constructor, but abstraction confuses
2367 // annotalysis.
2368 bool VisitFrame() NO_THREAD_SAFETY_ANALYSIS {
jeffhao09bfc6a2012-12-11 18:11:43 -08002369 Locks::breakpoint_lock_->AssertHeld(Thread::Current());
Mathieu Chartier66f19252012-09-18 08:57:04 -07002370 const AbstractMethod* m = GetMethod();
Ian Rogers0399dde2012-06-06 17:09:28 -07002371 if (!m->IsRuntimeMethod()) {
Elliott Hughes86964332012-02-15 19:37:42 -08002372 ++gSingleStepControl.stack_depth;
2373 if (gSingleStepControl.method == NULL) {
Elliott Hughes2435a572012-02-17 16:07:41 -08002374 const DexCache* dex_cache = m->GetDeclaringClass()->GetDexCache();
2375 gSingleStepControl.method = m;
2376 gSingleStepControl.line_number = -1;
2377 if (dex_cache != NULL) {
Ian Rogers4445a7e2012-10-05 17:19:13 -07002378 const DexFile& dex_file = *dex_cache->GetDexFile();
Ian Rogers0399dde2012-06-06 17:09:28 -07002379 gSingleStepControl.line_number = dex_file.GetLineNumFromPC(m, GetDexPc());
Elliott Hughes2435a572012-02-17 16:07:41 -08002380 }
Elliott Hughes86964332012-02-15 19:37:42 -08002381 }
2382 }
Elliott Hughes530fa002012-03-12 11:44:49 -07002383 return true;
Elliott Hughes86964332012-02-15 19:37:42 -08002384 }
2385 };
jeffhao725a9572012-11-13 18:20:12 -08002386 SingleStepStackVisitor visitor(thread->GetManagedStack(), thread->GetInstrumentationStack());
Ian Rogers0399dde2012-06-06 17:09:28 -07002387 visitor.WalkStack();
Elliott Hughes86964332012-02-15 19:37:42 -08002388
Elliott Hughes2435a572012-02-17 16:07:41 -08002389 //
2390 // Find the dex_pc values that correspond to the current line, for line-based single-stepping.
2391 //
2392
2393 struct DebugCallbackContext {
jeffhao09bfc6a2012-12-11 18:11:43 -08002394 DebugCallbackContext() EXCLUSIVE_LOCKS_REQUIRED(Locks::breakpoint_lock_) {
Elliott Hughes2435a572012-02-17 16:07:41 -08002395 last_pc_valid = false;
2396 last_pc = 0;
Elliott Hughes2435a572012-02-17 16:07:41 -08002397 }
2398
jeffhao09bfc6a2012-12-11 18:11:43 -08002399 // TODO: Enable annotalysis. We know lock is held in constructor, but abstraction confuses
2400 // annotalysis.
2401 static bool Callback(void* raw_context, uint32_t address, uint32_t line_number) NO_THREAD_SAFETY_ANALYSIS {
2402 Locks::breakpoint_lock_->AssertHeld(Thread::Current());
Elliott Hughes2435a572012-02-17 16:07:41 -08002403 DebugCallbackContext* context = reinterpret_cast<DebugCallbackContext*>(raw_context);
2404 if (static_cast<int32_t>(line_number) == gSingleStepControl.line_number) {
2405 if (!context->last_pc_valid) {
2406 // Everything from this address until the next line change is ours.
2407 context->last_pc = address;
2408 context->last_pc_valid = true;
2409 }
2410 // Otherwise, if we're already in a valid range for this line,
2411 // just keep going (shouldn't really happen)...
2412 } else if (context->last_pc_valid) { // and the line number is new
2413 // Add everything from the last entry up until here to the set
2414 for (uint32_t dex_pc = context->last_pc; dex_pc < address; ++dex_pc) {
2415 gSingleStepControl.dex_pcs.insert(dex_pc);
2416 }
2417 context->last_pc_valid = false;
2418 }
2419 return false; // There may be multiple entries for any given line.
2420 }
2421
jeffhao09bfc6a2012-12-11 18:11:43 -08002422 // TODO: Enable annotalysis. We know lock is held in constructor, but abstraction confuses
2423 // annotalysis.
2424 ~DebugCallbackContext() NO_THREAD_SAFETY_ANALYSIS {
2425 Locks::breakpoint_lock_->AssertHeld(Thread::Current());
Elliott Hughes2435a572012-02-17 16:07:41 -08002426 // If the line number was the last in the position table...
2427 if (last_pc_valid) {
2428 size_t end = MethodHelper(gSingleStepControl.method).GetCodeItem()->insns_size_in_code_units_;
2429 for (uint32_t dex_pc = last_pc; dex_pc < end; ++dex_pc) {
2430 gSingleStepControl.dex_pcs.insert(dex_pc);
2431 }
2432 }
2433 }
2434
2435 bool last_pc_valid;
2436 uint32_t last_pc;
2437 };
Elliott Hughes3e2e1a22012-02-21 11:33:41 -08002438 gSingleStepControl.dex_pcs.clear();
Mathieu Chartier66f19252012-09-18 08:57:04 -07002439 const AbstractMethod* m = gSingleStepControl.method;
Elliott Hughes3e2e1a22012-02-21 11:33:41 -08002440 if (m->IsNative()) {
2441 gSingleStepControl.line_number = -1;
2442 } else {
2443 DebugCallbackContext context;
2444 MethodHelper mh(m);
2445 mh.GetDexFile().DecodeDebugInfo(mh.GetCodeItem(), m->IsStatic(), m->GetDexMethodIndex(),
2446 DebugCallbackContext::Callback, NULL, &context);
2447 }
Elliott Hughes2435a572012-02-17 16:07:41 -08002448
2449 //
2450 // Everything else...
2451 //
2452
Elliott Hughes86964332012-02-15 19:37:42 -08002453 gSingleStepControl.thread = thread;
2454 gSingleStepControl.step_size = step_size;
2455 gSingleStepControl.step_depth = step_depth;
2456 gSingleStepControl.is_active = true;
2457
Elliott Hughes2435a572012-02-17 16:07:41 -08002458 if (VLOG_IS_ON(jdwp)) {
2459 VLOG(jdwp) << "Single-step thread: " << *gSingleStepControl.thread;
2460 VLOG(jdwp) << "Single-step step size: " << gSingleStepControl.step_size;
2461 VLOG(jdwp) << "Single-step step depth: " << gSingleStepControl.step_depth;
2462 VLOG(jdwp) << "Single-step current method: " << PrettyMethod(gSingleStepControl.method);
2463 VLOG(jdwp) << "Single-step current line: " << gSingleStepControl.line_number;
2464 VLOG(jdwp) << "Single-step current stack depth: " << gSingleStepControl.stack_depth;
2465 VLOG(jdwp) << "Single-step dex_pc values:";
2466 for (std::set<uint32_t>::iterator it = gSingleStepControl.dex_pcs.begin() ; it != gSingleStepControl.dex_pcs.end(); ++it) {
Elliott Hughes229feb72012-02-23 13:33:29 -08002467 VLOG(jdwp) << StringPrintf(" %#x", *it);
Elliott Hughes2435a572012-02-17 16:07:41 -08002468 }
2469 }
2470
2471 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002472}
2473
Elliott Hughes221229c2013-01-08 18:17:50 -08002474void Dbg::UnconfigureStep(JDWP::ObjectId /*thread_id*/) {
jeffhao09bfc6a2012-12-11 18:11:43 -08002475 MutexLock mu(Thread::Current(), *Locks::breakpoint_lock_);
Elliott Hughesf8349362012-06-18 15:00:06 -07002476
Elliott Hughes86964332012-02-15 19:37:42 -08002477 gSingleStepControl.is_active = false;
2478 gSingleStepControl.thread = NULL;
Elliott Hughes2435a572012-02-17 16:07:41 -08002479 gSingleStepControl.dex_pcs.clear();
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002480}
2481
Elliott Hughes45651fd2012-02-21 15:48:20 -08002482static char JdwpTagToShortyChar(JDWP::JdwpTag tag) {
2483 switch (tag) {
2484 default:
2485 LOG(FATAL) << "unknown JDWP tag: " << PrintableChar(tag);
2486
2487 // Primitives.
2488 case JDWP::JT_BYTE: return 'B';
2489 case JDWP::JT_CHAR: return 'C';
2490 case JDWP::JT_FLOAT: return 'F';
2491 case JDWP::JT_DOUBLE: return 'D';
2492 case JDWP::JT_INT: return 'I';
2493 case JDWP::JT_LONG: return 'J';
2494 case JDWP::JT_SHORT: return 'S';
2495 case JDWP::JT_VOID: return 'V';
2496 case JDWP::JT_BOOLEAN: return 'Z';
2497
2498 // Reference types.
2499 case JDWP::JT_ARRAY:
2500 case JDWP::JT_OBJECT:
2501 case JDWP::JT_STRING:
2502 case JDWP::JT_THREAD:
2503 case JDWP::JT_THREAD_GROUP:
2504 case JDWP::JT_CLASS_LOADER:
2505 case JDWP::JT_CLASS_OBJECT:
2506 return 'L';
2507 }
2508}
2509
Elliott Hughes88d63092013-01-09 09:55:54 -08002510JDWP::JdwpError Dbg::InvokeMethod(JDWP::ObjectId thread_id, JDWP::ObjectId object_id,
2511 JDWP::RefTypeId class_id, JDWP::MethodId method_id,
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002512 uint32_t arg_count, uint64_t* arg_values,
2513 JDWP::JdwpTag* arg_types, uint32_t options,
2514 JDWP::JdwpTag* pResultTag, uint64_t* pResultValue,
2515 JDWP::ObjectId* pExceptionId) {
Elliott Hughesd07986f2011-12-06 18:27:45 -08002516 ThreadList* thread_list = Runtime::Current()->GetThreadList();
2517
2518 Thread* targetThread = NULL;
2519 DebugInvokeReq* req = NULL;
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002520 Thread* self = Thread::Current();
Elliott Hughesd07986f2011-12-06 18:27:45 -08002521 {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002522 ScopedObjectAccessUnchecked soa(self);
Ian Rogers50b35e22012-10-04 10:09:15 -07002523 MutexLock mu(soa.Self(), *Locks::thread_list_lock_);
Elliott Hughes221229c2013-01-08 18:17:50 -08002524 JDWP::JdwpError error = DecodeThread(soa, thread_id, targetThread);
2525 if (error != JDWP::ERR_NONE) {
2526 LOG(ERROR) << "InvokeMethod request for invalid thread id " << thread_id;
2527 return error;
Elliott Hughesd07986f2011-12-06 18:27:45 -08002528 }
2529 req = targetThread->GetInvokeReq();
2530 if (!req->ready) {
2531 LOG(ERROR) << "InvokeMethod request for thread not stopped by event: " << *targetThread;
2532 return JDWP::ERR_INVALID_THREAD;
2533 }
2534
2535 /*
2536 * We currently have a bug where we don't successfully resume the
2537 * target thread if the suspend count is too deep. We're expected to
2538 * require one "resume" for each "suspend", but when asked to execute
2539 * a method we have to resume fully and then re-suspend it back to the
2540 * same level. (The easiest way to cause this is to type "suspend"
2541 * multiple times in jdb.)
2542 *
2543 * It's unclear what this means when the event specifies "resume all"
2544 * and some threads are suspended more deeply than others. This is
2545 * a rare problem, so for now we just prevent it from hanging forever
2546 * by rejecting the method invocation request. Without this, we will
2547 * be stuck waiting on a suspended thread.
2548 */
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002549 int suspend_count;
2550 {
Ian Rogers50b35e22012-10-04 10:09:15 -07002551 MutexLock mu2(soa.Self(), *Locks::thread_suspend_count_lock_);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002552 suspend_count = targetThread->GetSuspendCount();
2553 }
Elliott Hughesd07986f2011-12-06 18:27:45 -08002554 if (suspend_count > 1) {
2555 LOG(ERROR) << *targetThread << " suspend count too deep for method invocation: " << suspend_count;
2556 return JDWP::ERR_THREAD_SUSPENDED; // Probably not expected here.
2557 }
2558
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08002559 JDWP::JdwpError status;
Elliott Hughes88d63092013-01-09 09:55:54 -08002560 Object* receiver = gRegistry->Get<Object*>(object_id);
Elliott Hughes45651fd2012-02-21 15:48:20 -08002561 if (receiver == kInvalidObject) {
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08002562 return JDWP::ERR_INVALID_OBJECT;
2563 }
Elliott Hughes45651fd2012-02-21 15:48:20 -08002564
Elliott Hughes221229c2013-01-08 18:17:50 -08002565 Object* thread = gRegistry->Get<Object*>(thread_id);
Elliott Hughes45651fd2012-02-21 15:48:20 -08002566 if (thread == kInvalidObject) {
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08002567 return JDWP::ERR_INVALID_OBJECT;
2568 }
Elliott Hughes45651fd2012-02-21 15:48:20 -08002569 // TODO: check that 'thread' is actually a java.lang.Thread!
2570
Elliott Hughes88d63092013-01-09 09:55:54 -08002571 Class* c = DecodeClass(class_id, status);
Elliott Hughes45651fd2012-02-21 15:48:20 -08002572 if (c == NULL) {
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08002573 return status;
2574 }
Elliott Hughes45651fd2012-02-21 15:48:20 -08002575
Elliott Hughes88d63092013-01-09 09:55:54 -08002576 AbstractMethod* m = FromMethodId(method_id);
Elliott Hughes45651fd2012-02-21 15:48:20 -08002577 if (m->IsStatic() != (receiver == NULL)) {
2578 return JDWP::ERR_INVALID_METHODID;
2579 }
2580 if (m->IsStatic()) {
2581 if (m->GetDeclaringClass() != c) {
2582 return JDWP::ERR_INVALID_METHODID;
2583 }
2584 } else {
2585 if (!m->GetDeclaringClass()->IsAssignableFrom(c)) {
2586 return JDWP::ERR_INVALID_METHODID;
2587 }
2588 }
2589
2590 // Check the argument list matches the method.
2591 MethodHelper mh(m);
2592 if (mh.GetShortyLength() - 1 != arg_count) {
2593 return JDWP::ERR_ILLEGAL_ARGUMENT;
2594 }
2595 const char* shorty = mh.GetShorty();
2596 for (size_t i = 0; i < arg_count; ++i) {
2597 if (shorty[i + 1] != JdwpTagToShortyChar(arg_types[i])) {
2598 return JDWP::ERR_ILLEGAL_ARGUMENT;
2599 }
2600 }
2601
2602 req->receiver_ = receiver;
2603 req->thread_ = thread;
2604 req->class_ = c;
2605 req->method_ = m;
2606 req->arg_count_ = arg_count;
2607 req->arg_values_ = arg_values;
Elliott Hughesd07986f2011-12-06 18:27:45 -08002608 req->options_ = options;
2609 req->invoke_needed_ = true;
2610 }
2611
2612 // The fact that we've released the thread list lock is a bit risky --- if the thread goes
2613 // away we're sitting high and dry -- but we must release this before the ResumeAllThreads
2614 // call, and it's unwise to hold it during WaitForSuspend.
2615
2616 {
2617 /*
2618 * We change our (JDWP thread) status, which should be THREAD_RUNNING,
Elliott Hughes81ff3182012-03-23 20:35:56 -07002619 * so we can suspend for a GC if the invoke request causes us to
Elliott Hughesd07986f2011-12-06 18:27:45 -08002620 * run out of memory. It's also a good idea to change it before locking
2621 * the invokeReq mutex, although that should never be held for long.
2622 */
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002623 self->TransitionFromRunnableToSuspended(kWaitingForDebuggerSend);
Elliott Hughesd07986f2011-12-06 18:27:45 -08002624
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08002625 VLOG(jdwp) << " Transferring control to event thread";
Elliott Hughesd07986f2011-12-06 18:27:45 -08002626 {
Ian Rogers50b35e22012-10-04 10:09:15 -07002627 MutexLock mu(self, req->lock_);
Elliott Hughesd07986f2011-12-06 18:27:45 -08002628
2629 if ((options & JDWP::INVOKE_SINGLE_THREADED) == 0) {
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08002630 VLOG(jdwp) << " Resuming all threads";
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002631 thread_list->UndoDebuggerSuspensions();
Elliott Hughesd07986f2011-12-06 18:27:45 -08002632 } else {
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08002633 VLOG(jdwp) << " Resuming event thread only";
Elliott Hughesd07986f2011-12-06 18:27:45 -08002634 thread_list->Resume(targetThread, true);
2635 }
2636
2637 // Wait for the request to finish executing.
2638 while (req->invoke_needed_) {
Ian Rogersc604d732012-10-14 16:09:54 -07002639 req->cond_.Wait(self);
Elliott Hughesd07986f2011-12-06 18:27:45 -08002640 }
2641 }
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08002642 VLOG(jdwp) << " Control has returned from event thread";
Elliott Hughesd07986f2011-12-06 18:27:45 -08002643
2644 /* wait for thread to re-suspend itself */
Elliott Hughes221229c2013-01-08 18:17:50 -08002645 SuspendThread(thread_id, false /* request_suspension */ );
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002646 self->TransitionFromSuspendedToRunnable();
Elliott Hughesd07986f2011-12-06 18:27:45 -08002647 }
2648
2649 /*
2650 * Suspend the threads. We waited for the target thread to suspend
2651 * itself, so all we need to do is suspend the others.
2652 *
2653 * The suspendAllThreads() call will double-suspend the event thread,
2654 * so we want to resume the target thread once to keep the books straight.
2655 */
2656 if ((options & JDWP::INVOKE_SINGLE_THREADED) == 0) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002657 self->TransitionFromRunnableToSuspended(kWaitingForDebuggerSuspension);
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08002658 VLOG(jdwp) << " Suspending all threads";
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002659 thread_list->SuspendAllForDebugger();
2660 self->TransitionFromSuspendedToRunnable();
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08002661 VLOG(jdwp) << " Resuming event thread to balance the count";
Elliott Hughesd07986f2011-12-06 18:27:45 -08002662 thread_list->Resume(targetThread, true);
2663 }
2664
2665 // Copy the result.
2666 *pResultTag = req->result_tag;
2667 if (IsPrimitiveTag(req->result_tag)) {
Elliott Hughesf24d3ce2012-04-11 17:43:37 -07002668 *pResultValue = req->result_value.GetJ();
Elliott Hughesd07986f2011-12-06 18:27:45 -08002669 } else {
Elliott Hughesf24d3ce2012-04-11 17:43:37 -07002670 *pResultValue = gRegistry->Add(req->result_value.GetL());
Elliott Hughesd07986f2011-12-06 18:27:45 -08002671 }
2672 *pExceptionId = req->exception;
2673 return req->error;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002674}
2675
2676void Dbg::ExecuteMethod(DebugInvokeReq* pReq) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002677 ScopedObjectAccess soa(Thread::Current());
Elliott Hughesd07986f2011-12-06 18:27:45 -08002678
Elliott Hughes81ff3182012-03-23 20:35:56 -07002679 // We can be called while an exception is pending. We need
Elliott Hughesd07986f2011-12-06 18:27:45 -08002680 // to preserve that across the method invocation.
Ian Rogers1f539342012-10-03 21:09:42 -07002681 SirtRef<Throwable> old_exception(soa.Self(), soa.Self()->GetException());
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002682 soa.Self()->ClearException();
Elliott Hughesd07986f2011-12-06 18:27:45 -08002683
2684 // Translate the method through the vtable, unless the debugger wants to suppress it.
Mathieu Chartier66f19252012-09-18 08:57:04 -07002685 AbstractMethod* m = pReq->method_;
Elliott Hughesd07986f2011-12-06 18:27:45 -08002686 if ((pReq->options_ & JDWP::INVOKE_NONVIRTUAL) == 0 && pReq->receiver_ != NULL) {
Mathieu Chartier66f19252012-09-18 08:57:04 -07002687 AbstractMethod* actual_method = pReq->class_->FindVirtualMethodForVirtualOrInterface(pReq->method_);
Elliott Hughes45651fd2012-02-21 15:48:20 -08002688 if (actual_method != m) {
2689 VLOG(jdwp) << "ExecuteMethod translated " << PrettyMethod(m) << " to " << PrettyMethod(actual_method);
2690 m = actual_method;
2691 }
Elliott Hughesd07986f2011-12-06 18:27:45 -08002692 }
Elliott Hughes45651fd2012-02-21 15:48:20 -08002693 VLOG(jdwp) << "ExecuteMethod " << PrettyMethod(m);
Elliott Hughesd07986f2011-12-06 18:27:45 -08002694 CHECK(m != NULL);
2695
2696 CHECK_EQ(sizeof(jvalue), sizeof(uint64_t));
2697
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002698 LOG(INFO) << "self=" << soa.Self() << " pReq->receiver_=" << pReq->receiver_ << " m=" << m
2699 << " #" << pReq->arg_count_ << " " << pReq->arg_values_;
2700 pReq->result_value = InvokeWithJValues(soa, pReq->receiver_, m,
2701 reinterpret_cast<JValue*>(pReq->arg_values_));
Elliott Hughesd07986f2011-12-06 18:27:45 -08002702
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002703 pReq->exception = gRegistry->Add(soa.Self()->GetException());
Elliott Hughesd07986f2011-12-06 18:27:45 -08002704 pReq->result_tag = BasicTagFromDescriptor(MethodHelper(m).GetShorty());
2705 if (pReq->exception != 0) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002706 Object* exc = soa.Self()->GetException();
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08002707 VLOG(jdwp) << " JDWP invocation returning with exception=" << exc << " " << PrettyTypeOf(exc);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002708 soa.Self()->ClearException();
Elliott Hughesf24d3ce2012-04-11 17:43:37 -07002709 pReq->result_value.SetJ(0);
Elliott Hughesd07986f2011-12-06 18:27:45 -08002710 } else if (pReq->result_tag == JDWP::JT_OBJECT) {
2711 /* if no exception thrown, examine object result more closely */
Elliott Hughesf24d3ce2012-04-11 17:43:37 -07002712 JDWP::JdwpTag new_tag = TagFromObject(pReq->result_value.GetL());
Elliott Hughesd07986f2011-12-06 18:27:45 -08002713 if (new_tag != pReq->result_tag) {
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08002714 VLOG(jdwp) << " JDWP promoted result from " << pReq->result_tag << " to " << new_tag;
Elliott Hughesd07986f2011-12-06 18:27:45 -08002715 pReq->result_tag = new_tag;
2716 }
2717
2718 /*
2719 * Register the object. We don't actually need an ObjectId yet,
2720 * but we do need to be sure that the GC won't move or discard the
2721 * object when we switch out of RUNNING. The ObjectId conversion
2722 * will add the object to the "do not touch" list.
2723 *
2724 * We can't use the "tracked allocation" mechanism here because
2725 * the object is going to be handed off to a different thread.
2726 */
Elliott Hughesf24d3ce2012-04-11 17:43:37 -07002727 gRegistry->Add(pReq->result_value.GetL());
Elliott Hughesd07986f2011-12-06 18:27:45 -08002728 }
2729
2730 if (old_exception.get() != NULL) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002731 soa.Self()->SetException(old_exception.get());
Elliott Hughesd07986f2011-12-06 18:27:45 -08002732 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002733}
2734
Elliott Hughesd07986f2011-12-06 18:27:45 -08002735/*
2736 * Register an object ID that might not have been registered previously.
2737 *
2738 * Normally this wouldn't happen -- the conversion to an ObjectId would
2739 * have added the object to the registry -- but in some cases (e.g.
2740 * throwing exceptions) we really want to do the registration late.
2741 */
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002742void Dbg::RegisterObjectId(JDWP::ObjectId id) {
Elliott Hughesd07986f2011-12-06 18:27:45 -08002743 gRegistry->Add(reinterpret_cast<Object*>(id));
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002744}
2745
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07002746/*
2747 * "buf" contains a full JDWP packet, possibly with multiple chunks. We
2748 * need to process each, accumulate the replies, and ship the whole thing
2749 * back.
2750 *
2751 * Returns "true" if we have a reply. The reply buffer is newly allocated,
2752 * and includes the chunk type/length, followed by the data.
2753 *
Elliott Hughes3d30d9b2011-12-07 17:35:48 -08002754 * OLD-TODO: we currently assume that the request and reply include a single
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07002755 * chunk. If this becomes inconvenient we will need to adapt.
2756 */
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002757bool Dbg::DdmHandlePacket(const uint8_t* buf, int dataLen, uint8_t** pReplyBuf, int* pReplyLen) {
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07002758 CHECK_GE(dataLen, 0);
2759
2760 Thread* self = Thread::Current();
2761 JNIEnv* env = self->GetJniEnv();
2762
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07002763 // Create a byte[] corresponding to 'buf'.
Elliott Hughes6a5bd492011-10-28 14:33:57 -07002764 ScopedLocalRef<jbyteArray> dataArray(env, env->NewByteArray(dataLen));
2765 if (dataArray.get() == NULL) {
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07002766 LOG(WARNING) << "byte[] allocation failed: " << dataLen;
2767 env->ExceptionClear();
2768 return false;
2769 }
Elliott Hughes6a5bd492011-10-28 14:33:57 -07002770 env->SetByteArrayRegion(dataArray.get(), 0, dataLen, reinterpret_cast<const jbyte*>(buf));
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07002771
2772 const int kChunkHdrLen = 8;
2773
2774 // Run through and find all chunks. [Currently just find the first.]
Elliott Hughes6a5bd492011-10-28 14:33:57 -07002775 ScopedByteArrayRO contents(env, dataArray.get());
Elliott Hughesf7c3b662011-10-27 12:04:56 -07002776 jint type = JDWP::Get4BE(reinterpret_cast<const uint8_t*>(&contents[0]));
2777 jint length = JDWP::Get4BE(reinterpret_cast<const uint8_t*>(&contents[4]));
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07002778 jint offset = kChunkHdrLen;
2779 if (offset + length > dataLen) {
2780 LOG(WARNING) << StringPrintf("bad chunk found (len=%u pktLen=%d)", length, dataLen);
2781 return false;
2782 }
2783
2784 // Call "private static Chunk dispatch(int type, byte[] data, int offset, int length)".
Elliott Hugheseac76672012-05-24 21:56:51 -07002785 ScopedLocalRef<jobject> chunk(env, env->CallStaticObjectMethod(WellKnownClasses::org_apache_harmony_dalvik_ddmc_DdmServer,
2786 WellKnownClasses::org_apache_harmony_dalvik_ddmc_DdmServer_dispatch,
2787 type, dataArray.get(), offset, length));
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07002788 if (env->ExceptionCheck()) {
2789 LOG(INFO) << StringPrintf("Exception thrown by dispatcher for 0x%08x", type);
2790 env->ExceptionDescribe();
2791 env->ExceptionClear();
2792 return false;
2793 }
2794
Elliott Hughes6a5bd492011-10-28 14:33:57 -07002795 if (chunk.get() == NULL) {
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07002796 return false;
2797 }
2798
2799 /*
2800 * Pull the pieces out of the chunk. We copy the results into a
2801 * newly-allocated buffer that the caller can free. We don't want to
2802 * continue using the Chunk object because nothing has a reference to it.
2803 *
2804 * We could avoid this by returning type/data/offset/length and having
2805 * the caller be aware of the object lifetime issues, but that
Elliott Hughes81ff3182012-03-23 20:35:56 -07002806 * integrates the JDWP code more tightly into the rest of the runtime, and doesn't work
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07002807 * if we have responses for multiple chunks.
2808 *
2809 * So we're pretty much stuck with copying data around multiple times.
2810 */
Elliott Hugheseac76672012-05-24 21:56:51 -07002811 ScopedLocalRef<jbyteArray> replyData(env, reinterpret_cast<jbyteArray>(env->GetObjectField(chunk.get(), WellKnownClasses::org_apache_harmony_dalvik_ddmc_Chunk_data)));
2812 length = env->GetIntField(chunk.get(), WellKnownClasses::org_apache_harmony_dalvik_ddmc_Chunk_length);
2813 offset = env->GetIntField(chunk.get(), WellKnownClasses::org_apache_harmony_dalvik_ddmc_Chunk_offset);
2814 type = env->GetIntField(chunk.get(), WellKnownClasses::org_apache_harmony_dalvik_ddmc_Chunk_type);
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07002815
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08002816 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 -07002817 if (length == 0 || replyData.get() == NULL) {
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07002818 return false;
2819 }
2820
Elliott Hughes6a5bd492011-10-28 14:33:57 -07002821 jsize replyLength = env->GetArrayLength(replyData.get());
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07002822 if (offset + length > replyLength) {
2823 LOG(WARNING) << StringPrintf("chunk off=%d len=%d exceeds reply array len %d", offset, length, replyLength);
2824 return false;
2825 }
2826
2827 uint8_t* reply = new uint8_t[length + kChunkHdrLen];
2828 if (reply == NULL) {
2829 LOG(WARNING) << "malloc failed: " << (length + kChunkHdrLen);
2830 return false;
2831 }
Elliott Hughesf7c3b662011-10-27 12:04:56 -07002832 JDWP::Set4BE(reply + 0, type);
2833 JDWP::Set4BE(reply + 4, length);
Elliott Hughes6a5bd492011-10-28 14:33:57 -07002834 env->GetByteArrayRegion(replyData.get(), offset, length, reinterpret_cast<jbyte*>(reply + kChunkHdrLen));
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07002835
2836 *pReplyBuf = reply;
2837 *pReplyLen = length + kChunkHdrLen;
2838
Elliott Hughesba8eee12012-01-24 20:25:24 -08002839 VLOG(jdwp) << StringPrintf("dvmHandleDdm returning type=%.4s buf=%p len=%d", reinterpret_cast<char*>(reply), reply, length);
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07002840 return true;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002841}
2842
Elliott Hughesa2155262011-11-16 16:26:58 -08002843void Dbg::DdmBroadcast(bool connect) {
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08002844 VLOG(jdwp) << "Broadcasting DDM " << (connect ? "connect" : "disconnect") << "...";
Elliott Hughes47fce012011-10-25 18:37:19 -07002845
2846 Thread* self = Thread::Current();
Ian Rogers50b35e22012-10-04 10:09:15 -07002847 if (self->GetState() != kRunnable) {
2848 LOG(ERROR) << "DDM broadcast in thread state " << self->GetState();
2849 /* try anyway? */
Elliott Hughes47fce012011-10-25 18:37:19 -07002850 }
2851
2852 JNIEnv* env = self->GetJniEnv();
Elliott Hughes47fce012011-10-25 18:37:19 -07002853 jint event = connect ? 1 /*DdmServer.CONNECTED*/ : 2 /*DdmServer.DISCONNECTED*/;
Elliott Hugheseac76672012-05-24 21:56:51 -07002854 env->CallStaticVoidMethod(WellKnownClasses::org_apache_harmony_dalvik_ddmc_DdmServer,
2855 WellKnownClasses::org_apache_harmony_dalvik_ddmc_DdmServer_broadcast,
2856 event);
Elliott Hughes47fce012011-10-25 18:37:19 -07002857 if (env->ExceptionCheck()) {
2858 LOG(ERROR) << "DdmServer.broadcast " << event << " failed";
2859 env->ExceptionDescribe();
2860 env->ExceptionClear();
2861 }
2862}
2863
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002864void Dbg::DdmConnected() {
Elliott Hughesa2155262011-11-16 16:26:58 -08002865 Dbg::DdmBroadcast(true);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002866}
2867
2868void Dbg::DdmDisconnected() {
Elliott Hughesa2155262011-11-16 16:26:58 -08002869 Dbg::DdmBroadcast(false);
Elliott Hughes47fce012011-10-25 18:37:19 -07002870 gDdmThreadNotification = false;
2871}
2872
2873/*
Elliott Hughes82188472011-11-07 18:11:48 -08002874 * Send a notification when a thread starts, stops, or changes its name.
Elliott Hughes47fce012011-10-25 18:37:19 -07002875 *
2876 * Because we broadcast the full set of threads when the notifications are
2877 * first enabled, it's possible for "thread" to be actively executing.
2878 */
Elliott Hughes82188472011-11-07 18:11:48 -08002879void Dbg::DdmSendThreadNotification(Thread* t, uint32_t type) {
Elliott Hughes47fce012011-10-25 18:37:19 -07002880 if (!gDdmThreadNotification) {
2881 return;
2882 }
2883
Elliott Hughes82188472011-11-07 18:11:48 -08002884 if (type == CHUNK_TYPE("THDE")) {
Elliott Hughes47fce012011-10-25 18:37:19 -07002885 uint8_t buf[4];
Elliott Hughesf7c3b662011-10-27 12:04:56 -07002886 JDWP::Set4BE(&buf[0], t->GetThinLockId());
Elliott Hughes47fce012011-10-25 18:37:19 -07002887 Dbg::DdmSendChunk(CHUNK_TYPE("THDE"), 4, buf);
Elliott Hughes82188472011-11-07 18:11:48 -08002888 } else {
2889 CHECK(type == CHUNK_TYPE("THCR") || type == CHUNK_TYPE("THNM")) << type;
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002890 ScopedObjectAccessUnchecked soa(Thread::Current());
Ian Rogers1f539342012-10-03 21:09:42 -07002891 SirtRef<String> name(soa.Self(), t->GetThreadName(soa));
Elliott Hughes82188472011-11-07 18:11:48 -08002892 size_t char_count = (name.get() != NULL) ? name->GetLength() : 0;
jeffhao725a9572012-11-13 18:20:12 -08002893 const jchar* chars = (name.get() != NULL) ? name->GetCharArray()->GetData() : NULL;
Elliott Hughes82188472011-11-07 18:11:48 -08002894
Elliott Hughes21f32d72011-11-09 17:44:13 -08002895 std::vector<uint8_t> bytes;
Elliott Hughes545a0642011-11-08 19:10:03 -08002896 JDWP::Append4BE(bytes, t->GetThinLockId());
2897 JDWP::AppendUtf16BE(bytes, chars, char_count);
Elliott Hughes21f32d72011-11-09 17:44:13 -08002898 CHECK_EQ(bytes.size(), char_count*2 + sizeof(uint32_t)*2);
2899 Dbg::DdmSendChunk(type, bytes);
Elliott Hughes47fce012011-10-25 18:37:19 -07002900 }
2901}
2902
Elliott Hughes47fce012011-10-25 18:37:19 -07002903void Dbg::DdmSetThreadNotification(bool enable) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002904 // Enable/disable thread notifications.
Elliott Hughes47fce012011-10-25 18:37:19 -07002905 gDdmThreadNotification = enable;
2906 if (enable) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002907 // Suspend the VM then post thread start notifications for all threads. Threads attaching will
2908 // see a suspension in progress and block until that ends. They then post their own start
2909 // notification.
2910 SuspendVM();
2911 std::list<Thread*> threads;
Ian Rogers50b35e22012-10-04 10:09:15 -07002912 Thread* self = Thread::Current();
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002913 {
Ian Rogers50b35e22012-10-04 10:09:15 -07002914 MutexLock mu(self, *Locks::thread_list_lock_);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002915 threads = Runtime::Current()->GetThreadList()->GetList();
2916 }
2917 {
Ian Rogers50b35e22012-10-04 10:09:15 -07002918 ScopedObjectAccess soa(self);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002919 typedef std::list<Thread*>::const_iterator It; // TODO: C++0x auto
2920 for (It it = threads.begin(), end = threads.end(); it != end; ++it) {
2921 Dbg::DdmSendThreadNotification(*it, CHUNK_TYPE("THCR"));
2922 }
2923 }
2924 ResumeVM();
Elliott Hughes47fce012011-10-25 18:37:19 -07002925 }
2926}
2927
Elliott Hughesa2155262011-11-16 16:26:58 -08002928void Dbg::PostThreadStartOrStop(Thread* t, uint32_t type) {
Elliott Hughesc0f09332012-03-26 13:27:06 -07002929 if (IsDebuggerActive()) {
Mathieu Chartierdbe6f462012-09-25 16:54:50 -07002930 ScopedObjectAccessUnchecked soa(Thread::Current());
Ian Rogerscfaa4552012-11-26 21:00:08 -08002931 JDWP::ObjectId id = gRegistry->Add(t->GetPeer());
Elliott Hughes82188472011-11-07 18:11:48 -08002932 gJdwpState->PostThreadChange(id, type == CHUNK_TYPE("THCR"));
Elliott Hughesc0f09332012-03-26 13:27:06 -07002933 // If this thread's just joined the party while we're already debugging, make sure it knows
2934 // to give us updates when it's running.
2935 t->SetDebuggerUpdatesEnabled(true);
Elliott Hughes47fce012011-10-25 18:37:19 -07002936 }
Elliott Hughes82188472011-11-07 18:11:48 -08002937 Dbg::DdmSendThreadNotification(t, type);
Elliott Hughes47fce012011-10-25 18:37:19 -07002938}
2939
2940void Dbg::PostThreadStart(Thread* t) {
Elliott Hughesa2155262011-11-16 16:26:58 -08002941 Dbg::PostThreadStartOrStop(t, CHUNK_TYPE("THCR"));
Elliott Hughes47fce012011-10-25 18:37:19 -07002942}
2943
2944void Dbg::PostThreadDeath(Thread* t) {
Elliott Hughesa2155262011-11-16 16:26:58 -08002945 Dbg::PostThreadStartOrStop(t, CHUNK_TYPE("THDE"));
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002946}
2947
Elliott Hughes82188472011-11-07 18:11:48 -08002948void Dbg::DdmSendChunk(uint32_t type, size_t byte_count, const uint8_t* buf) {
Elliott Hughes3bb81562011-10-21 18:52:59 -07002949 CHECK(buf != NULL);
2950 iovec vec[1];
2951 vec[0].iov_base = reinterpret_cast<void*>(const_cast<uint8_t*>(buf));
2952 vec[0].iov_len = byte_count;
2953 Dbg::DdmSendChunkV(type, vec, 1);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002954}
2955
Elliott Hughes21f32d72011-11-09 17:44:13 -08002956void Dbg::DdmSendChunk(uint32_t type, const std::vector<uint8_t>& bytes) {
2957 DdmSendChunk(type, bytes.size(), &bytes[0]);
2958}
2959
Elliott Hughescccd84f2011-12-05 16:51:54 -08002960void Dbg::DdmSendChunkV(uint32_t type, const struct iovec* iov, int iov_count) {
Elliott Hughes3bb81562011-10-21 18:52:59 -07002961 if (gJdwpState == NULL) {
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08002962 VLOG(jdwp) << "Debugger thread not active, ignoring DDM send: " << type;
Elliott Hughes3bb81562011-10-21 18:52:59 -07002963 } else {
Elliott Hughescccd84f2011-12-05 16:51:54 -08002964 gJdwpState->DdmSendChunkV(type, iov, iov_count);
Elliott Hughes3bb81562011-10-21 18:52:59 -07002965 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002966}
2967
Elliott Hughes767a1472011-10-26 18:49:02 -07002968int Dbg::DdmHandleHpifChunk(HpifWhen when) {
2969 if (when == HPIF_WHEN_NOW) {
Elliott Hughes7162ad92011-10-27 14:08:42 -07002970 DdmSendHeapInfo(when);
Elliott Hughes767a1472011-10-26 18:49:02 -07002971 return true;
2972 }
2973
2974 if (when != HPIF_WHEN_NEVER && when != HPIF_WHEN_NEXT_GC && when != HPIF_WHEN_EVERY_GC) {
2975 LOG(ERROR) << "invalid HpifWhen value: " << static_cast<int>(when);
2976 return false;
2977 }
2978
2979 gDdmHpifWhen = when;
2980 return true;
2981}
2982
2983bool Dbg::DdmHandleHpsgNhsgChunk(Dbg::HpsgWhen when, Dbg::HpsgWhat what, bool native) {
2984 if (when != HPSG_WHEN_NEVER && when != HPSG_WHEN_EVERY_GC) {
2985 LOG(ERROR) << "invalid HpsgWhen value: " << static_cast<int>(when);
2986 return false;
2987 }
2988
2989 if (what != HPSG_WHAT_MERGED_OBJECTS && what != HPSG_WHAT_DISTINCT_OBJECTS) {
2990 LOG(ERROR) << "invalid HpsgWhat value: " << static_cast<int>(what);
2991 return false;
2992 }
2993
2994 if (native) {
2995 gDdmNhsgWhen = when;
2996 gDdmNhsgWhat = what;
2997 } else {
2998 gDdmHpsgWhen = when;
2999 gDdmHpsgWhat = what;
3000 }
3001 return true;
3002}
3003
Elliott Hughes7162ad92011-10-27 14:08:42 -07003004void Dbg::DdmSendHeapInfo(HpifWhen reason) {
3005 // If there's a one-shot 'when', reset it.
3006 if (reason == gDdmHpifWhen) {
3007 if (gDdmHpifWhen == HPIF_WHEN_NEXT_GC) {
3008 gDdmHpifWhen = HPIF_WHEN_NEVER;
3009 }
3010 }
3011
3012 /*
3013 * Chunk HPIF (client --> server)
3014 *
3015 * Heap Info. General information about the heap,
3016 * suitable for a summary display.
3017 *
3018 * [u4]: number of heaps
3019 *
3020 * For each heap:
3021 * [u4]: heap ID
3022 * [u8]: timestamp in ms since Unix epoch
3023 * [u1]: capture reason (same as 'when' value from server)
3024 * [u4]: max heap size in bytes (-Xmx)
3025 * [u4]: current heap size in bytes
3026 * [u4]: current number of bytes allocated
3027 * [u4]: current number of objects allocated
3028 */
3029 uint8_t heap_count = 1;
Elliott Hughesb3bd5f02012-03-08 21:05:27 -08003030 Heap* heap = Runtime::Current()->GetHeap();
Elliott Hughes21f32d72011-11-09 17:44:13 -08003031 std::vector<uint8_t> bytes;
Elliott Hughes545a0642011-11-08 19:10:03 -08003032 JDWP::Append4BE(bytes, heap_count);
3033 JDWP::Append4BE(bytes, 1); // Heap id (bogus; we only have one heap).
3034 JDWP::Append8BE(bytes, MilliTime());
3035 JDWP::Append1BE(bytes, reason);
Elliott Hughesb3bd5f02012-03-08 21:05:27 -08003036 JDWP::Append4BE(bytes, heap->GetMaxMemory()); // Max allowed heap size in bytes.
3037 JDWP::Append4BE(bytes, heap->GetTotalMemory()); // Current heap size in bytes.
3038 JDWP::Append4BE(bytes, heap->GetBytesAllocated());
3039 JDWP::Append4BE(bytes, heap->GetObjectsAllocated());
Elliott Hughes21f32d72011-11-09 17:44:13 -08003040 CHECK_EQ(bytes.size(), 4U + (heap_count * (4 + 8 + 1 + 4 + 4 + 4 + 4)));
3041 Dbg::DdmSendChunk(CHUNK_TYPE("HPIF"), bytes);
Elliott Hughes767a1472011-10-26 18:49:02 -07003042}
3043
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003044enum HpsgSolidity {
3045 SOLIDITY_FREE = 0,
3046 SOLIDITY_HARD = 1,
3047 SOLIDITY_SOFT = 2,
3048 SOLIDITY_WEAK = 3,
3049 SOLIDITY_PHANTOM = 4,
3050 SOLIDITY_FINALIZABLE = 5,
3051 SOLIDITY_SWEEP = 6,
3052};
3053
3054enum HpsgKind {
3055 KIND_OBJECT = 0,
3056 KIND_CLASS_OBJECT = 1,
3057 KIND_ARRAY_1 = 2,
3058 KIND_ARRAY_2 = 3,
3059 KIND_ARRAY_4 = 4,
3060 KIND_ARRAY_8 = 5,
3061 KIND_UNKNOWN = 6,
3062 KIND_NATIVE = 7,
3063};
3064
3065#define HPSG_PARTIAL (1<<7)
3066#define HPSG_STATE(solidity, kind) ((uint8_t)((((kind) & 0x7) << 3) | ((solidity) & 0x7)))
3067
Ian Rogers30fab402012-01-23 15:43:46 -08003068class HeapChunkContext {
3069 public:
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003070 // Maximum chunk size. Obtain this from the formula:
3071 // (((maximum_heap_size / ALLOCATION_UNIT_SIZE) + 255) / 256) * 2
3072 HeapChunkContext(bool merge, bool native)
Ian Rogers30fab402012-01-23 15:43:46 -08003073 : buf_(16384 - 16),
3074 type_(0),
3075 merge_(merge) {
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003076 Reset();
3077 if (native) {
Ian Rogers30fab402012-01-23 15:43:46 -08003078 type_ = CHUNK_TYPE("NHSG");
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003079 } else {
Ian Rogers30fab402012-01-23 15:43:46 -08003080 type_ = merge ? CHUNK_TYPE("HPSG") : CHUNK_TYPE("HPSO");
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003081 }
3082 }
3083
3084 ~HeapChunkContext() {
Ian Rogers30fab402012-01-23 15:43:46 -08003085 if (p_ > &buf_[0]) {
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003086 Flush();
3087 }
3088 }
3089
3090 void EnsureHeader(const void* chunk_ptr) {
Ian Rogers30fab402012-01-23 15:43:46 -08003091 if (!needHeader_) {
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003092 return;
3093 }
3094
3095 // Start a new HPSx chunk.
Ian Rogers30fab402012-01-23 15:43:46 -08003096 JDWP::Write4BE(&p_, 1); // Heap id (bogus; we only have one heap).
3097 JDWP::Write1BE(&p_, 8); // Size of allocation unit, in bytes.
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003098
Ian Rogers30fab402012-01-23 15:43:46 -08003099 JDWP::Write4BE(&p_, reinterpret_cast<uintptr_t>(chunk_ptr)); // virtual address of segment start.
3100 JDWP::Write4BE(&p_, 0); // offset of this piece (relative to the virtual address).
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003101 // [u4]: length of piece, in allocation units
3102 // 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 -08003103 pieceLenField_ = p_;
3104 JDWP::Write4BE(&p_, 0x55555555);
3105 needHeader_ = false;
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003106 }
3107
Ian Rogersb726dcb2012-09-05 08:57:23 -07003108 void Flush() SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003109 // Patch the "length of piece" field.
Ian Rogers30fab402012-01-23 15:43:46 -08003110 CHECK_LE(&buf_[0], pieceLenField_);
3111 CHECK_LE(pieceLenField_, p_);
3112 JDWP::Set4BE(pieceLenField_, totalAllocationUnits_);
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003113
Ian Rogers30fab402012-01-23 15:43:46 -08003114 Dbg::DdmSendChunk(type_, p_ - &buf_[0], &buf_[0]);
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003115 Reset();
3116 }
3117
Ian Rogers00f7d0e2012-07-19 15:28:27 -07003118 static void HeapChunkCallback(void* start, void* end, size_t used_bytes, void* arg)
Ian Rogersb726dcb2012-09-05 08:57:23 -07003119 SHARED_LOCKS_REQUIRED(Locks::heap_bitmap_lock_,
3120 Locks::mutator_lock_) {
Ian Rogers30fab402012-01-23 15:43:46 -08003121 reinterpret_cast<HeapChunkContext*>(arg)->HeapChunkCallback(start, end, used_bytes);
Elliott Hughesa2155262011-11-16 16:26:58 -08003122 }
3123
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003124 private:
Elliott Hughesa2155262011-11-16 16:26:58 -08003125 enum { ALLOCATION_UNIT_SIZE = 8 };
3126
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003127 void Reset() {
Ian Rogers30fab402012-01-23 15:43:46 -08003128 p_ = &buf_[0];
Ian Rogers15bf2d32012-08-28 17:33:04 -07003129 startOfNextMemoryChunk_ = NULL;
Ian Rogers30fab402012-01-23 15:43:46 -08003130 totalAllocationUnits_ = 0;
3131 needHeader_ = true;
3132 pieceLenField_ = NULL;
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003133 }
3134
Ian Rogers00f7d0e2012-07-19 15:28:27 -07003135 void HeapChunkCallback(void* start, void* /*end*/, size_t used_bytes)
Ian Rogersb726dcb2012-09-05 08:57:23 -07003136 SHARED_LOCKS_REQUIRED(Locks::heap_bitmap_lock_,
3137 Locks::mutator_lock_) {
Ian Rogers30fab402012-01-23 15:43:46 -08003138 // Note: heap call backs cannot manipulate the heap upon which they are crawling, care is taken
3139 // in the following code not to allocate memory, by ensuring buf_ is of the correct size
Ian Rogers15bf2d32012-08-28 17:33:04 -07003140 if (used_bytes == 0) {
3141 if (start == NULL) {
3142 // Reset for start of new heap.
3143 startOfNextMemoryChunk_ = NULL;
3144 Flush();
3145 }
3146 // Only process in use memory so that free region information
3147 // also includes dlmalloc book keeping.
Elliott Hughesa2155262011-11-16 16:26:58 -08003148 return;
Elliott Hughesa2155262011-11-16 16:26:58 -08003149 }
3150
Ian Rogers15bf2d32012-08-28 17:33:04 -07003151 /* If we're looking at the native heap, we'll just return
3152 * (SOLIDITY_HARD, KIND_NATIVE) for all allocated chunks
3153 */
3154 bool native = type_ == CHUNK_TYPE("NHSG");
3155
3156 if (startOfNextMemoryChunk_ != NULL) {
3157 // Transmit any pending free memory. Native free memory of
3158 // over kMaxFreeLen could be because of the use of mmaps, so
3159 // don't report. If not free memory then start a new segment.
3160 bool flush = true;
3161 if (start > startOfNextMemoryChunk_) {
3162 const size_t kMaxFreeLen = 2 * kPageSize;
3163 void* freeStart = startOfNextMemoryChunk_;
3164 void* freeEnd = start;
3165 size_t freeLen = (char*)freeEnd - (char*)freeStart;
3166 if (!native || freeLen < kMaxFreeLen) {
3167 AppendChunk(HPSG_STATE(SOLIDITY_FREE, 0), freeStart, freeLen);
3168 flush = false;
3169 }
3170 }
3171 if (flush) {
3172 startOfNextMemoryChunk_ = NULL;
3173 Flush();
3174 }
3175 }
3176 const Object *obj = (const Object *)start;
Elliott Hughesa2155262011-11-16 16:26:58 -08003177
3178 // Determine the type of this chunk.
3179 // OLD-TODO: if context.merge, see if this chunk is different from the last chunk.
3180 // If it's the same, we should combine them.
Ian Rogers15bf2d32012-08-28 17:33:04 -07003181 uint8_t state = ExamineObject(obj, native);
3182 // dlmalloc's chunk header is 2 * sizeof(size_t), but if the previous chunk is in use for an
3183 // allocation then the first sizeof(size_t) may belong to it.
3184 const size_t dlMallocOverhead = sizeof(size_t);
3185 AppendChunk(state, start, used_bytes + dlMallocOverhead);
3186 startOfNextMemoryChunk_ = (char*)start + used_bytes + dlMallocOverhead;
3187 }
Elliott Hughesa2155262011-11-16 16:26:58 -08003188
Ian Rogers15bf2d32012-08-28 17:33:04 -07003189 void AppendChunk(uint8_t state, void* ptr, size_t length)
Ian Rogersb726dcb2012-09-05 08:57:23 -07003190 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Ian Rogers15bf2d32012-08-28 17:33:04 -07003191 // Make sure there's enough room left in the buffer.
3192 // We need to use two bytes for every fractional 256 allocation units used by the chunk plus
3193 // 17 bytes for any header.
3194 size_t needed = (((length/ALLOCATION_UNIT_SIZE + 255) / 256) * 2) + 17;
3195 size_t bytesLeft = buf_.size() - (size_t)(p_ - &buf_[0]);
3196 if (bytesLeft < needed) {
3197 Flush();
3198 }
3199
3200 bytesLeft = buf_.size() - (size_t)(p_ - &buf_[0]);
3201 if (bytesLeft < needed) {
3202 LOG(WARNING) << "Chunk is too big to transmit (chunk_len=" << length << ", "
3203 << needed << " bytes)";
3204 return;
3205 }
3206 EnsureHeader(ptr);
Elliott Hughesa2155262011-11-16 16:26:58 -08003207 // Write out the chunk description.
Ian Rogers15bf2d32012-08-28 17:33:04 -07003208 length /= ALLOCATION_UNIT_SIZE; // Convert to allocation units.
3209 totalAllocationUnits_ += length;
3210 while (length > 256) {
Ian Rogers30fab402012-01-23 15:43:46 -08003211 *p_++ = state | HPSG_PARTIAL;
3212 *p_++ = 255; // length - 1
Ian Rogers15bf2d32012-08-28 17:33:04 -07003213 length -= 256;
Elliott Hughesa2155262011-11-16 16:26:58 -08003214 }
Ian Rogers30fab402012-01-23 15:43:46 -08003215 *p_++ = state;
Ian Rogers15bf2d32012-08-28 17:33:04 -07003216 *p_++ = length - 1;
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003217 }
3218
Ian Rogers5bfa60f2012-09-02 21:17:56 -07003219 uint8_t ExamineObject(const Object* o, bool is_native_heap)
Ian Rogersb726dcb2012-09-05 08:57:23 -07003220 SHARED_LOCKS_REQUIRED(Locks::heap_bitmap_lock_) {
Elliott Hughesa2155262011-11-16 16:26:58 -08003221 if (o == NULL) {
3222 return HPSG_STATE(SOLIDITY_FREE, 0);
3223 }
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003224
Elliott Hughesa2155262011-11-16 16:26:58 -08003225 // It's an allocated chunk. Figure out what it is.
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003226
Elliott Hughesa2155262011-11-16 16:26:58 -08003227 // If we're looking at the native heap, we'll just return
3228 // (SOLIDITY_HARD, KIND_NATIVE) for all allocated chunks.
Ian Rogers00f7d0e2012-07-19 15:28:27 -07003229 if (is_native_heap) {
Elliott Hughesa2155262011-11-16 16:26:58 -08003230 return HPSG_STATE(SOLIDITY_HARD, KIND_NATIVE);
3231 }
3232
Ian Rogers5bfa60f2012-09-02 21:17:56 -07003233 if (!Runtime::Current()->GetHeap()->IsLiveObjectLocked(o)) {
Ian Rogers15bf2d32012-08-28 17:33:04 -07003234 return HPSG_STATE(SOLIDITY_HARD, KIND_NATIVE);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07003235 }
3236
Elliott Hughesa2155262011-11-16 16:26:58 -08003237 Class* c = o->GetClass();
3238 if (c == NULL) {
3239 // The object was probably just created but hasn't been initialized yet.
3240 return HPSG_STATE(SOLIDITY_HARD, KIND_OBJECT);
3241 }
3242
Elliott Hughesb3bd5f02012-03-08 21:05:27 -08003243 if (!Runtime::Current()->GetHeap()->IsHeapAddress(c)) {
Ian Rogers15bf2d32012-08-28 17:33:04 -07003244 LOG(ERROR) << "Invalid class for managed heap object: " << o << " " << c;
Elliott Hughesa2155262011-11-16 16:26:58 -08003245 return HPSG_STATE(SOLIDITY_HARD, KIND_UNKNOWN);
3246 }
3247
3248 if (c->IsClassClass()) {
3249 return HPSG_STATE(SOLIDITY_HARD, KIND_CLASS_OBJECT);
3250 }
3251
3252 if (c->IsArrayClass()) {
3253 if (o->IsObjectArray()) {
3254 return HPSG_STATE(SOLIDITY_HARD, KIND_ARRAY_4);
3255 }
3256 switch (c->GetComponentSize()) {
3257 case 1: return HPSG_STATE(SOLIDITY_HARD, KIND_ARRAY_1);
3258 case 2: return HPSG_STATE(SOLIDITY_HARD, KIND_ARRAY_2);
3259 case 4: return HPSG_STATE(SOLIDITY_HARD, KIND_ARRAY_4);
3260 case 8: return HPSG_STATE(SOLIDITY_HARD, KIND_ARRAY_8);
3261 }
3262 }
3263
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003264 return HPSG_STATE(SOLIDITY_HARD, KIND_OBJECT);
3265 }
3266
Ian Rogers30fab402012-01-23 15:43:46 -08003267 std::vector<uint8_t> buf_;
3268 uint8_t* p_;
3269 uint8_t* pieceLenField_;
Ian Rogers15bf2d32012-08-28 17:33:04 -07003270 void* startOfNextMemoryChunk_;
Ian Rogers30fab402012-01-23 15:43:46 -08003271 size_t totalAllocationUnits_;
3272 uint32_t type_;
3273 bool merge_;
3274 bool needHeader_;
3275
Elliott Hughesa2155262011-11-16 16:26:58 -08003276 DISALLOW_COPY_AND_ASSIGN(HeapChunkContext);
3277};
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003278
3279void Dbg::DdmSendHeapSegments(bool native) {
3280 Dbg::HpsgWhen when;
3281 Dbg::HpsgWhat what;
3282 if (!native) {
3283 when = gDdmHpsgWhen;
3284 what = gDdmHpsgWhat;
3285 } else {
3286 when = gDdmNhsgWhen;
3287 what = gDdmNhsgWhat;
3288 }
3289 if (when == HPSG_WHEN_NEVER) {
3290 return;
3291 }
3292
3293 // Figure out what kind of chunks we'll be sending.
3294 CHECK(what == HPSG_WHAT_MERGED_OBJECTS || what == HPSG_WHAT_DISTINCT_OBJECTS) << static_cast<int>(what);
3295
3296 // First, send a heap start chunk.
3297 uint8_t heap_id[4];
3298 JDWP::Set4BE(&heap_id[0], 1); // Heap id (bogus; we only have one heap).
3299 Dbg::DdmSendChunk(native ? CHUNK_TYPE("NHST") : CHUNK_TYPE("HPST"), sizeof(heap_id), heap_id);
3300
3301 // Send a series of heap segment chunks.
Elliott Hughesa2155262011-11-16 16:26:58 -08003302 HeapChunkContext context((what == HPSG_WHAT_MERGED_OBJECTS), native);
3303 if (native) {
Ian Rogers30fab402012-01-23 15:43:46 -08003304 // TODO: enable when bionic has moved to dlmalloc 2.8.5
3305 // dlmalloc_inspect_all(HeapChunkContext::HeapChunkCallback, &context);
3306 UNIMPLEMENTED(WARNING) << "Native heap send heap segments";
Elliott Hughesa2155262011-11-16 16:26:58 -08003307 } else {
Elliott Hughesb3bd5f02012-03-08 21:05:27 -08003308 Heap* heap = Runtime::Current()->GetHeap();
Mathieu Chartierfd678be2012-08-30 14:50:54 -07003309 const Spaces& spaces = heap->GetSpaces();
Ian Rogers50b35e22012-10-04 10:09:15 -07003310 Thread* self = Thread::Current();
Mathieu Chartierfd678be2012-08-30 14:50:54 -07003311 for (Spaces::const_iterator cur = spaces.begin(); cur != spaces.end(); ++cur) {
Mathieu Chartierb062fdd2012-07-03 09:51:48 -07003312 if ((*cur)->IsAllocSpace()) {
Ian Rogers50b35e22012-10-04 10:09:15 -07003313 ReaderMutexLock mu(self, *Locks::heap_bitmap_lock_);
Mathieu Chartierb062fdd2012-07-03 09:51:48 -07003314 (*cur)->AsAllocSpace()->Walk(HeapChunkContext::HeapChunkCallback, &context);
3315 }
3316 }
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -07003317 // Walk the large objects, these are not in the AllocSpace.
3318 heap->GetLargeObjectsSpace()->Walk(HeapChunkContext::HeapChunkCallback, &context);
Elliott Hughesa2155262011-11-16 16:26:58 -08003319 }
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003320
3321 // Finally, send a heap end chunk.
3322 Dbg::DdmSendChunk(native ? CHUNK_TYPE("NHEN") : CHUNK_TYPE("HPEN"), sizeof(heap_id), heap_id);
Elliott Hughes767a1472011-10-26 18:49:02 -07003323}
3324
Elliott Hughes545a0642011-11-08 19:10:03 -08003325void Dbg::SetAllocTrackingEnabled(bool enabled) {
Ian Rogers50b35e22012-10-04 10:09:15 -07003326 MutexLock mu(Thread::Current(), gAllocTrackerLock);
Elliott Hughes545a0642011-11-08 19:10:03 -08003327 if (enabled) {
3328 if (recent_allocation_records_ == NULL) {
3329 LOG(INFO) << "Enabling alloc tracker (" << kNumAllocRecords << " entries, "
3330 << kMaxAllocRecordStackDepth << " frames --> "
3331 << (sizeof(AllocRecord) * kNumAllocRecords) << " bytes)";
3332 gAllocRecordHead = gAllocRecordCount = 0;
3333 recent_allocation_records_ = new AllocRecord[kNumAllocRecords];
3334 CHECK(recent_allocation_records_ != NULL);
3335 }
3336 } else {
3337 delete[] recent_allocation_records_;
3338 recent_allocation_records_ = NULL;
3339 }
3340}
3341
Ian Rogers0399dde2012-06-06 17:09:28 -07003342struct AllocRecordStackVisitor : public StackVisitor {
3343 AllocRecordStackVisitor(const ManagedStack* stack,
Ian Rogers306057f2012-11-26 12:45:53 -08003344 const std::deque<InstrumentationStackFrame>* instrumentation_stack,
3345 AllocRecord* record)
Ian Rogersb726dcb2012-09-05 08:57:23 -07003346 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_)
jeffhao725a9572012-11-13 18:20:12 -08003347 : StackVisitor(stack, instrumentation_stack, NULL), record(record), depth(0) {}
Elliott Hughes545a0642011-11-08 19:10:03 -08003348
Ian Rogers00f7d0e2012-07-19 15:28:27 -07003349 // TODO: Enable annotalysis. We know lock is held in constructor, but abstraction confuses
3350 // annotalysis.
3351 bool VisitFrame() NO_THREAD_SAFETY_ANALYSIS {
Elliott Hughes545a0642011-11-08 19:10:03 -08003352 if (depth >= kMaxAllocRecordStackDepth) {
Elliott Hughes530fa002012-03-12 11:44:49 -07003353 return false;
Elliott Hughes545a0642011-11-08 19:10:03 -08003354 }
Mathieu Chartier66f19252012-09-18 08:57:04 -07003355 AbstractMethod* m = GetMethod();
Ian Rogers0399dde2012-06-06 17:09:28 -07003356 if (!m->IsRuntimeMethod()) {
3357 record->stack[depth].method = m;
3358 record->stack[depth].dex_pc = GetDexPc();
Elliott Hughes530fa002012-03-12 11:44:49 -07003359 ++depth;
Elliott Hughes545a0642011-11-08 19:10:03 -08003360 }
Elliott Hughes530fa002012-03-12 11:44:49 -07003361 return true;
Elliott Hughes545a0642011-11-08 19:10:03 -08003362 }
3363
3364 ~AllocRecordStackVisitor() {
3365 // Clear out any unused stack trace elements.
3366 for (; depth < kMaxAllocRecordStackDepth; ++depth) {
3367 record->stack[depth].method = NULL;
Ian Rogers0399dde2012-06-06 17:09:28 -07003368 record->stack[depth].dex_pc = 0;
Elliott Hughes545a0642011-11-08 19:10:03 -08003369 }
3370 }
3371
3372 AllocRecord* record;
3373 size_t depth;
3374};
3375
3376void Dbg::RecordAllocation(Class* type, size_t byte_count) {
3377 Thread* self = Thread::Current();
3378 CHECK(self != NULL);
3379
Ian Rogers50b35e22012-10-04 10:09:15 -07003380 MutexLock mu(self, gAllocTrackerLock);
Elliott Hughes545a0642011-11-08 19:10:03 -08003381 if (recent_allocation_records_ == NULL) {
3382 return;
3383 }
3384
3385 // Advance and clip.
3386 if (++gAllocRecordHead == kNumAllocRecords) {
3387 gAllocRecordHead = 0;
3388 }
3389
3390 // Fill in the basics.
3391 AllocRecord* record = &recent_allocation_records_[gAllocRecordHead];
3392 record->type = type;
3393 record->byte_count = byte_count;
3394 record->thin_lock_id = self->GetThinLockId();
3395
3396 // Fill in the stack trace.
jeffhao725a9572012-11-13 18:20:12 -08003397 AllocRecordStackVisitor visitor(self->GetManagedStack(), self->GetInstrumentationStack(), record);
Ian Rogers0399dde2012-06-06 17:09:28 -07003398 visitor.WalkStack();
Elliott Hughes545a0642011-11-08 19:10:03 -08003399
3400 if (gAllocRecordCount < kNumAllocRecords) {
3401 ++gAllocRecordCount;
3402 }
3403}
3404
Elliott Hughesa8f93cb2012-06-08 17:08:48 -07003405// Returns the index of the head element.
3406//
3407// We point at the most-recently-written record, so if gAllocRecordCount is 1
3408// we want to use the current element. Take "head+1" and subtract count
3409// from it.
3410//
3411// We need to handle underflow in our circular buffer, so we add
3412// kNumAllocRecords and then mask it back down.
Elliott Hughesf8349362012-06-18 15:00:06 -07003413static inline int HeadIndex() EXCLUSIVE_LOCKS_REQUIRED(gAllocTrackerLock) {
Elliott Hughes545a0642011-11-08 19:10:03 -08003414 return (gAllocRecordHead+1 + kNumAllocRecords - gAllocRecordCount) & (kNumAllocRecords-1);
3415}
3416
3417void Dbg::DumpRecentAllocations() {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07003418 ScopedObjectAccess soa(Thread::Current());
Ian Rogers50b35e22012-10-04 10:09:15 -07003419 MutexLock mu(soa.Self(), gAllocTrackerLock);
Elliott Hughes545a0642011-11-08 19:10:03 -08003420 if (recent_allocation_records_ == NULL) {
3421 LOG(INFO) << "Not recording tracked allocations";
3422 return;
3423 }
3424
3425 // "i" is the head of the list. We want to start at the end of the
3426 // list and move forward to the tail.
Elliott Hughesa8f93cb2012-06-08 17:08:48 -07003427 size_t i = HeadIndex();
Elliott Hughes545a0642011-11-08 19:10:03 -08003428 size_t count = gAllocRecordCount;
3429
3430 LOG(INFO) << "Tracked allocations, (head=" << gAllocRecordHead << " count=" << count << ")";
3431 while (count--) {
3432 AllocRecord* record = &recent_allocation_records_[i];
3433
Elliott Hughesa8f93cb2012-06-08 17:08:48 -07003434 LOG(INFO) << StringPrintf(" Thread %-2d %6zd bytes ", record->thin_lock_id, record->byte_count)
Elliott Hughes545a0642011-11-08 19:10:03 -08003435 << PrettyClass(record->type);
3436
3437 for (size_t stack_frame = 0; stack_frame < kMaxAllocRecordStackDepth; ++stack_frame) {
Mathieu Chartier66f19252012-09-18 08:57:04 -07003438 const AbstractMethod* m = record->stack[stack_frame].method;
Elliott Hughes545a0642011-11-08 19:10:03 -08003439 if (m == NULL) {
3440 break;
3441 }
3442 LOG(INFO) << " " << PrettyMethod(m) << " line " << record->stack[stack_frame].LineNumber();
3443 }
3444
3445 // pause periodically to help logcat catch up
3446 if ((count % 5) == 0) {
3447 usleep(40000);
3448 }
3449
3450 i = (i + 1) & (kNumAllocRecords-1);
3451 }
3452}
3453
3454class StringTable {
3455 public:
3456 StringTable() {
3457 }
3458
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08003459 void Add(const char* s) {
Elliott Hughes545a0642011-11-08 19:10:03 -08003460 table_.insert(s);
3461 }
3462
Elliott Hughesa8f93cb2012-06-08 17:08:48 -07003463 size_t IndexOf(const char* s) const {
3464 typedef std::set<std::string>::const_iterator It; // TODO: C++0x auto
3465 It it = table_.find(s);
3466 if (it == table_.end()) {
3467 LOG(FATAL) << "IndexOf(\"" << s << "\") failed";
3468 }
3469 return std::distance(table_.begin(), it);
Elliott Hughes545a0642011-11-08 19:10:03 -08003470 }
3471
Elliott Hughesa8f93cb2012-06-08 17:08:48 -07003472 size_t Size() const {
Elliott Hughes545a0642011-11-08 19:10:03 -08003473 return table_.size();
3474 }
3475
Elliott Hughesa8f93cb2012-06-08 17:08:48 -07003476 void WriteTo(std::vector<uint8_t>& bytes) const {
3477 typedef std::set<std::string>::const_iterator It; // TODO: C++0x auto
Elliott Hughes545a0642011-11-08 19:10:03 -08003478 for (It it = table_.begin(); it != table_.end(); ++it) {
Elliott Hughesa8f93cb2012-06-08 17:08:48 -07003479 const char* s = (*it).c_str();
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08003480 size_t s_len = CountModifiedUtf8Chars(s);
3481 UniquePtr<uint16_t> s_utf16(new uint16_t[s_len]);
3482 ConvertModifiedUtf8ToUtf16(s_utf16.get(), s);
3483 JDWP::AppendUtf16BE(bytes, s_utf16.get(), s_len);
Elliott Hughes545a0642011-11-08 19:10:03 -08003484 }
3485 }
3486
3487 private:
Elliott Hughesa8f93cb2012-06-08 17:08:48 -07003488 std::set<std::string> table_;
Elliott Hughes545a0642011-11-08 19:10:03 -08003489 DISALLOW_COPY_AND_ASSIGN(StringTable);
3490};
3491
3492/*
3493 * The data we send to DDMS contains everything we have recorded.
3494 *
3495 * Message header (all values big-endian):
3496 * (1b) message header len (to allow future expansion); includes itself
3497 * (1b) entry header len
3498 * (1b) stack frame len
3499 * (2b) number of entries
3500 * (4b) offset to string table from start of message
3501 * (2b) number of class name strings
3502 * (2b) number of method name strings
3503 * (2b) number of source file name strings
3504 * For each entry:
3505 * (4b) total allocation size
Elliott Hughes221229c2013-01-08 18:17:50 -08003506 * (2b) thread id
Elliott Hughes545a0642011-11-08 19:10:03 -08003507 * (2b) allocated object's class name index
3508 * (1b) stack depth
3509 * For each stack frame:
3510 * (2b) method's class name
3511 * (2b) method name
3512 * (2b) method source file
3513 * (2b) line number, clipped to 32767; -2 if native; -1 if no source
3514 * (xb) class name strings
3515 * (xb) method name strings
3516 * (xb) source file strings
3517 *
3518 * As with other DDM traffic, strings are sent as a 4-byte length
3519 * followed by UTF-16 data.
3520 *
3521 * We send up 16-bit unsigned indexes into string tables. In theory there
3522 * can be (kMaxAllocRecordStackDepth * kNumAllocRecords) unique strings in
3523 * each table, but in practice there should be far fewer.
3524 *
3525 * The chief reason for using a string table here is to keep the size of
3526 * the DDMS message to a minimum. This is partly to make the protocol
3527 * efficient, but also because we have to form the whole thing up all at
3528 * once in a memory buffer.
3529 *
3530 * We use separate string tables for class names, method names, and source
3531 * files to keep the indexes small. There will generally be no overlap
3532 * between the contents of these tables.
3533 */
3534jbyteArray Dbg::GetRecentAllocations() {
3535 if (false) {
3536 DumpRecentAllocations();
3537 }
3538
Ian Rogers50b35e22012-10-04 10:09:15 -07003539 Thread* self = Thread::Current();
3540 MutexLock mu(self, gAllocTrackerLock);
Elliott Hughes545a0642011-11-08 19:10:03 -08003541
Elliott Hughesa8f93cb2012-06-08 17:08:48 -07003542 //
3543 // Part 1: generate string tables.
3544 //
Elliott Hughes545a0642011-11-08 19:10:03 -08003545 StringTable class_names;
3546 StringTable method_names;
3547 StringTable filenames;
3548
3549 int count = gAllocRecordCount;
Elliott Hughesa8f93cb2012-06-08 17:08:48 -07003550 int idx = HeadIndex();
Elliott Hughes545a0642011-11-08 19:10:03 -08003551 while (count--) {
3552 AllocRecord* record = &recent_allocation_records_[idx];
3553
Elliott Hughes91250e02011-12-13 22:30:35 -08003554 class_names.Add(ClassHelper(record->type).GetDescriptor());
Elliott Hughes545a0642011-11-08 19:10:03 -08003555
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08003556 MethodHelper mh;
Elliott Hughes545a0642011-11-08 19:10:03 -08003557 for (size_t i = 0; i < kMaxAllocRecordStackDepth; i++) {
Mathieu Chartier66f19252012-09-18 08:57:04 -07003558 AbstractMethod* m = record->stack[i].method;
Elliott Hughes545a0642011-11-08 19:10:03 -08003559 if (m != NULL) {
Ian Rogersba377812012-05-28 21:16:29 -07003560 mh.ChangeMethod(m);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08003561 class_names.Add(mh.GetDeclaringClassDescriptor());
3562 method_names.Add(mh.GetName());
3563 filenames.Add(mh.GetDeclaringClassSourceFile());
Elliott Hughes545a0642011-11-08 19:10:03 -08003564 }
3565 }
3566
3567 idx = (idx + 1) & (kNumAllocRecords-1);
3568 }
3569
3570 LOG(INFO) << "allocation records: " << gAllocRecordCount;
3571
Elliott Hughesa8f93cb2012-06-08 17:08:48 -07003572 //
3573 // Part 2: allocate a buffer and generate the output.
3574 //
Elliott Hughes545a0642011-11-08 19:10:03 -08003575 std::vector<uint8_t> bytes;
3576
3577 // (1b) message header len (to allow future expansion); includes itself
3578 // (1b) entry header len
3579 // (1b) stack frame len
3580 const int kMessageHeaderLen = 15;
3581 const int kEntryHeaderLen = 9;
3582 const int kStackFrameLen = 8;
3583 JDWP::Append1BE(bytes, kMessageHeaderLen);
3584 JDWP::Append1BE(bytes, kEntryHeaderLen);
3585 JDWP::Append1BE(bytes, kStackFrameLen);
3586
3587 // (2b) number of entries
3588 // (4b) offset to string table from start of message
3589 // (2b) number of class name strings
3590 // (2b) number of method name strings
3591 // (2b) number of source file name strings
3592 JDWP::Append2BE(bytes, gAllocRecordCount);
3593 size_t string_table_offset = bytes.size();
3594 JDWP::Append4BE(bytes, 0); // We'll patch this later...
3595 JDWP::Append2BE(bytes, class_names.Size());
3596 JDWP::Append2BE(bytes, method_names.Size());
3597 JDWP::Append2BE(bytes, filenames.Size());
3598
3599 count = gAllocRecordCount;
Elliott Hughesa8f93cb2012-06-08 17:08:48 -07003600 idx = HeadIndex();
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08003601 ClassHelper kh;
Elliott Hughes545a0642011-11-08 19:10:03 -08003602 while (count--) {
3603 // For each entry:
3604 // (4b) total allocation size
3605 // (2b) thread id
3606 // (2b) allocated object's class name index
3607 // (1b) stack depth
3608 AllocRecord* record = &recent_allocation_records_[idx];
3609 size_t stack_depth = record->GetDepth();
Elliott Hughesa8f93cb2012-06-08 17:08:48 -07003610 kh.ChangeClass(record->type);
3611 size_t allocated_object_class_name_index = class_names.IndexOf(kh.GetDescriptor());
Elliott Hughes545a0642011-11-08 19:10:03 -08003612 JDWP::Append4BE(bytes, record->byte_count);
3613 JDWP::Append2BE(bytes, record->thin_lock_id);
Elliott Hughesa8f93cb2012-06-08 17:08:48 -07003614 JDWP::Append2BE(bytes, allocated_object_class_name_index);
Elliott Hughes545a0642011-11-08 19:10:03 -08003615 JDWP::Append1BE(bytes, stack_depth);
3616
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08003617 MethodHelper mh;
Elliott Hughes545a0642011-11-08 19:10:03 -08003618 for (size_t stack_frame = 0; stack_frame < stack_depth; ++stack_frame) {
3619 // For each stack frame:
3620 // (2b) method's class name
3621 // (2b) method name
3622 // (2b) method source file
3623 // (2b) line number, clipped to 32767; -2 if native; -1 if no source
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08003624 mh.ChangeMethod(record->stack[stack_frame].method);
Elliott Hughesa8f93cb2012-06-08 17:08:48 -07003625 size_t class_name_index = class_names.IndexOf(mh.GetDeclaringClassDescriptor());
3626 size_t method_name_index = method_names.IndexOf(mh.GetName());
3627 size_t file_name_index = filenames.IndexOf(mh.GetDeclaringClassSourceFile());
3628 JDWP::Append2BE(bytes, class_name_index);
3629 JDWP::Append2BE(bytes, method_name_index);
3630 JDWP::Append2BE(bytes, file_name_index);
Elliott Hughes545a0642011-11-08 19:10:03 -08003631 JDWP::Append2BE(bytes, record->stack[stack_frame].LineNumber());
3632 }
3633
3634 idx = (idx + 1) & (kNumAllocRecords-1);
3635 }
3636
3637 // (xb) class name strings
3638 // (xb) method name strings
3639 // (xb) source file strings
3640 JDWP::Set4BE(&bytes[string_table_offset], bytes.size());
3641 class_names.WriteTo(bytes);
3642 method_names.WriteTo(bytes);
3643 filenames.WriteTo(bytes);
3644
Ian Rogers50b35e22012-10-04 10:09:15 -07003645 JNIEnv* env = self->GetJniEnv();
Elliott Hughes545a0642011-11-08 19:10:03 -08003646 jbyteArray result = env->NewByteArray(bytes.size());
3647 if (result != NULL) {
3648 env->SetByteArrayRegion(result, 0, bytes.size(), reinterpret_cast<const jbyte*>(&bytes[0]));
3649 }
3650 return result;
3651}
3652
Elliott Hughes872d4ec2011-10-21 17:07:15 -07003653} // namespace art