blob: e549f2197881e58a6e67507b8d41fed8bd820a04 [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 Hughes88d63092013-01-09 09:55:54 -0800672JDWP::JdwpError Dbg::GetReflectedType(JDWP::RefTypeId class_id, JDWP::ExpandBuf* pReply) {
Elliott Hughes436e3722012-02-17 20:01:47 -0800673 JDWP::JdwpError status;
Elliott Hughes88d63092013-01-09 09:55:54 -0800674 Class* c = DecodeClass(class_id, status);
Elliott Hughes436e3722012-02-17 20:01:47 -0800675 if (c == NULL) {
676 return status;
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -0800677 }
Elliott Hughes436e3722012-02-17 20:01:47 -0800678
679 expandBufAdd1(pReply, c->IsInterface() ? JDWP::TT_INTERFACE : JDWP::TT_CLASS);
Elliott Hughes88d63092013-01-09 09:55:54 -0800680 expandBufAddRefTypeId(pReply, class_id);
Elliott Hughes436e3722012-02-17 20:01:47 -0800681 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700682}
683
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -0800684void Dbg::GetClassList(std::vector<JDWP::RefTypeId>& classes) {
Elliott Hughesa2155262011-11-16 16:26:58 -0800685 // Get the complete list of reference classes (i.e. all classes except
686 // the primitive types).
687 // Returns a newly-allocated buffer full of RefTypeId values.
688 struct ClassListCreator {
Elliott Hughesba8eee12012-01-24 20:25:24 -0800689 explicit ClassListCreator(std::vector<JDWP::RefTypeId>& classes) : classes(classes) {
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -0800690 }
691
Elliott Hughesa2155262011-11-16 16:26:58 -0800692 static bool Visit(Class* c, void* arg) {
693 return reinterpret_cast<ClassListCreator*>(arg)->Visit(c);
694 }
695
696 bool Visit(Class* c) {
697 if (!c->IsPrimitive()) {
698 classes.push_back(static_cast<JDWP::RefTypeId>(gRegistry->Add(c)));
699 }
700 return true;
701 }
702
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -0800703 std::vector<JDWP::RefTypeId>& classes;
Elliott Hughesa2155262011-11-16 16:26:58 -0800704 };
705
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -0800706 ClassListCreator clc(classes);
Elliott Hughesa2155262011-11-16 16:26:58 -0800707 Runtime::Current()->GetClassLinker()->VisitClasses(ClassListCreator::Visit, &clc);
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700708}
709
Elliott Hughes88d63092013-01-09 09:55:54 -0800710JDWP::JdwpError Dbg::GetClassInfo(JDWP::RefTypeId class_id, JDWP::JdwpTypeTag* pTypeTag, uint32_t* pStatus, std::string* pDescriptor) {
Elliott Hughes436e3722012-02-17 20:01:47 -0800711 JDWP::JdwpError status;
Elliott Hughes88d63092013-01-09 09:55:54 -0800712 Class* c = DecodeClass(class_id, status);
Elliott Hughes436e3722012-02-17 20:01:47 -0800713 if (c == NULL) {
714 return status;
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -0800715 }
716
Elliott Hughesa2155262011-11-16 16:26:58 -0800717 if (c->IsArrayClass()) {
718 *pStatus = JDWP::CS_VERIFIED | JDWP::CS_PREPARED;
719 *pTypeTag = JDWP::TT_ARRAY;
720 } else {
721 if (c->IsErroneous()) {
722 *pStatus = JDWP::CS_ERROR;
723 } else {
724 *pStatus = JDWP::CS_VERIFIED | JDWP::CS_PREPARED | JDWP::CS_INITIALIZED;
725 }
726 *pTypeTag = c->IsInterface() ? JDWP::TT_INTERFACE : JDWP::TT_CLASS;
727 }
728
729 if (pDescriptor != NULL) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800730 *pDescriptor = ClassHelper(c).GetDescriptor();
Elliott Hughesa2155262011-11-16 16:26:58 -0800731 }
Elliott Hughes436e3722012-02-17 20:01:47 -0800732 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700733}
734
Elliott Hughesc3b77c72011-12-15 20:56:48 -0800735void Dbg::FindLoadedClassBySignature(const char* descriptor, std::vector<JDWP::RefTypeId>& ids) {
Elliott Hughes6fa602d2011-12-02 17:54:25 -0800736 std::vector<Class*> classes;
737 Runtime::Current()->GetClassLinker()->LookupClasses(descriptor, classes);
738 ids.clear();
739 for (size_t i = 0; i < classes.size(); ++i) {
740 ids.push_back(gRegistry->Add(classes[i]));
741 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700742}
743
Elliott Hughes88d63092013-01-09 09:55:54 -0800744JDWP::JdwpError Dbg::GetReferenceType(JDWP::ObjectId object_id, JDWP::ExpandBuf* pReply) {
745 Object* o = gRegistry->Get<Object*>(object_id);
Elliott Hughes436e3722012-02-17 20:01:47 -0800746 if (o == NULL || o == kInvalidObject) {
Elliott Hughes2435a572012-02-17 16:07:41 -0800747 return JDWP::ERR_INVALID_OBJECT;
Elliott Hughes499c5132011-11-17 14:55:11 -0800748 }
Elliott Hughes2435a572012-02-17 16:07:41 -0800749
750 JDWP::JdwpTypeTag type_tag;
751 if (o->GetClass()->IsArrayClass()) {
752 type_tag = JDWP::TT_ARRAY;
753 } else if (o->GetClass()->IsInterface()) {
754 type_tag = JDWP::TT_INTERFACE;
755 } else {
756 type_tag = JDWP::TT_CLASS;
757 }
758 JDWP::RefTypeId type_id = gRegistry->Add(o->GetClass());
759
760 expandBufAdd1(pReply, type_tag);
761 expandBufAddRefTypeId(pReply, type_id);
762
763 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700764}
765
Elliott Hughes88d63092013-01-09 09:55:54 -0800766JDWP::JdwpError Dbg::GetSignature(JDWP::RefTypeId class_id, std::string& signature) {
Elliott Hughes1fe7afb2012-02-13 17:23:03 -0800767 JDWP::JdwpError status;
Elliott Hughes88d63092013-01-09 09:55:54 -0800768 Class* c = DecodeClass(class_id, status);
Elliott Hughes1fe7afb2012-02-13 17:23:03 -0800769 if (c == NULL) {
770 return status;
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -0800771 }
Elliott Hughes1fe7afb2012-02-13 17:23:03 -0800772 signature = ClassHelper(c).GetDescriptor();
773 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700774}
775
Elliott Hughes88d63092013-01-09 09:55:54 -0800776JDWP::JdwpError Dbg::GetSourceFile(JDWP::RefTypeId class_id, std::string& result) {
Elliott Hughes436e3722012-02-17 20:01:47 -0800777 JDWP::JdwpError status;
Elliott Hughes88d63092013-01-09 09:55:54 -0800778 Class* c = DecodeClass(class_id, status);
Elliott Hughes436e3722012-02-17 20:01:47 -0800779 if (c == NULL) {
780 return status;
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -0800781 }
Elliott Hughes436e3722012-02-17 20:01:47 -0800782 result = ClassHelper(c).GetSourceFile();
783 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700784}
785
Elliott Hughes88d63092013-01-09 09:55:54 -0800786JDWP::JdwpError Dbg::GetObjectTag(JDWP::ObjectId object_id, uint8_t& tag) {
787 Object* o = gRegistry->Get<Object*>(object_id);
Elliott Hughes546b9862012-06-20 16:06:13 -0700788 if (o == kInvalidObject) {
789 return JDWP::ERR_INVALID_OBJECT;
790 }
791 tag = TagFromObject(o);
792 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700793}
794
Elliott Hughesaed4be92011-12-02 16:16:23 -0800795size_t Dbg::GetTagWidth(JDWP::JdwpTag tag) {
Elliott Hughesdbb40792011-11-18 17:05:22 -0800796 switch (tag) {
797 case JDWP::JT_VOID:
798 return 0;
799 case JDWP::JT_BYTE:
800 case JDWP::JT_BOOLEAN:
801 return 1;
802 case JDWP::JT_CHAR:
803 case JDWP::JT_SHORT:
804 return 2;
805 case JDWP::JT_FLOAT:
806 case JDWP::JT_INT:
807 return 4;
808 case JDWP::JT_ARRAY:
809 case JDWP::JT_OBJECT:
810 case JDWP::JT_STRING:
811 case JDWP::JT_THREAD:
812 case JDWP::JT_THREAD_GROUP:
813 case JDWP::JT_CLASS_LOADER:
814 case JDWP::JT_CLASS_OBJECT:
815 return sizeof(JDWP::ObjectId);
816 case JDWP::JT_DOUBLE:
817 case JDWP::JT_LONG:
818 return 8;
819 default:
Elliott Hughes3d30d9b2011-12-07 17:35:48 -0800820 LOG(FATAL) << "Unknown tag " << tag;
Elliott Hughesdbb40792011-11-18 17:05:22 -0800821 return -1;
822 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700823}
824
Elliott Hughes88d63092013-01-09 09:55:54 -0800825JDWP::JdwpError Dbg::GetArrayLength(JDWP::ObjectId array_id, int& length) {
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -0800826 JDWP::JdwpError status;
Elliott Hughes88d63092013-01-09 09:55:54 -0800827 Array* a = DecodeArray(array_id, status);
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -0800828 if (a == NULL) {
829 return status;
Elliott Hughes24437992011-11-30 14:49:33 -0800830 }
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -0800831 length = a->GetLength();
832 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700833}
834
Elliott Hughes88d63092013-01-09 09:55:54 -0800835JDWP::JdwpError Dbg::OutputArray(JDWP::ObjectId array_id, int offset, int count, JDWP::ExpandBuf* pReply) {
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -0800836 JDWP::JdwpError status;
Elliott Hughes88d63092013-01-09 09:55:54 -0800837 Array* a = DecodeArray(array_id, status);
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -0800838 if (a == NULL) {
839 return status;
840 }
Elliott Hughes24437992011-11-30 14:49:33 -0800841
842 if (offset < 0 || count < 0 || offset > a->GetLength() || a->GetLength() - offset < count) {
843 LOG(WARNING) << __FUNCTION__ << " access out of bounds: offset=" << offset << "; count=" << count;
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -0800844 return JDWP::ERR_INVALID_LENGTH;
Elliott Hughes24437992011-11-30 14:49:33 -0800845 }
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800846 std::string descriptor(ClassHelper(a->GetClass()).GetDescriptor());
Elliott Hughes24437992011-11-30 14:49:33 -0800847 JDWP::JdwpTag tag = BasicTagFromDescriptor(descriptor.c_str() + 1);
848
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -0800849 expandBufAdd1(pReply, tag);
850 expandBufAdd4BE(pReply, count);
851
Elliott Hughes24437992011-11-30 14:49:33 -0800852 if (IsPrimitiveTag(tag)) {
853 size_t width = GetTagWidth(tag);
Elliott Hughes24437992011-11-30 14:49:33 -0800854 uint8_t* dst = expandBufAddSpace(pReply, count * width);
855 if (width == 8) {
Ian Rogersa15e67d2012-02-28 13:51:55 -0800856 const uint64_t* src8 = reinterpret_cast<uint64_t*>(a->GetRawData(sizeof(uint64_t)));
Elliott Hughes24437992011-11-30 14:49:33 -0800857 for (int i = 0; i < count; ++i) JDWP::Write8BE(&dst, src8[offset + i]);
858 } else if (width == 4) {
Ian Rogersa15e67d2012-02-28 13:51:55 -0800859 const uint32_t* src4 = reinterpret_cast<uint32_t*>(a->GetRawData(sizeof(uint32_t)));
Elliott Hughes24437992011-11-30 14:49:33 -0800860 for (int i = 0; i < count; ++i) JDWP::Write4BE(&dst, src4[offset + i]);
861 } else if (width == 2) {
Ian Rogersa15e67d2012-02-28 13:51:55 -0800862 const uint16_t* src2 = reinterpret_cast<uint16_t*>(a->GetRawData(sizeof(uint16_t)));
Elliott Hughes24437992011-11-30 14:49:33 -0800863 for (int i = 0; i < count; ++i) JDWP::Write2BE(&dst, src2[offset + i]);
864 } else {
Ian Rogersa15e67d2012-02-28 13:51:55 -0800865 const uint8_t* src = reinterpret_cast<uint8_t*>(a->GetRawData(sizeof(uint8_t)));
Elliott Hughes24437992011-11-30 14:49:33 -0800866 memcpy(dst, &src[offset * width], count * width);
867 }
868 } else {
869 ObjectArray<Object>* oa = a->AsObjectArray<Object>();
870 for (int i = 0; i < count; ++i) {
Elliott Hughesf03b8f62011-12-02 14:26:25 -0800871 Object* element = oa->Get(offset + i);
Elliott Hughes24437992011-11-30 14:49:33 -0800872 JDWP::JdwpTag specific_tag = (element != NULL) ? TagFromObject(element) : tag;
873 expandBufAdd1(pReply, specific_tag);
874 expandBufAddObjectId(pReply, gRegistry->Add(element));
875 }
876 }
877
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -0800878 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700879}
880
Elliott Hughes88d63092013-01-09 09:55:54 -0800881JDWP::JdwpError Dbg::SetArrayElements(JDWP::ObjectId array_id, int offset, int count,
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700882 const uint8_t* src)
Ian Rogersb726dcb2012-09-05 08:57:23 -0700883 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -0800884 JDWP::JdwpError status;
Elliott Hughes88d63092013-01-09 09:55:54 -0800885 Array* a = DecodeArray(array_id, status);
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -0800886 if (a == NULL) {
887 return status;
888 }
Elliott Hughesf03b8f62011-12-02 14:26:25 -0800889
890 if (offset < 0 || count < 0 || offset > a->GetLength() || a->GetLength() - offset < count) {
891 LOG(WARNING) << __FUNCTION__ << " access out of bounds: offset=" << offset << "; count=" << count;
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -0800892 return JDWP::ERR_INVALID_LENGTH;
Elliott Hughesf03b8f62011-12-02 14:26:25 -0800893 }
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800894 std::string descriptor(ClassHelper(a->GetClass()).GetDescriptor());
Elliott Hughesf03b8f62011-12-02 14:26:25 -0800895 JDWP::JdwpTag tag = BasicTagFromDescriptor(descriptor.c_str() + 1);
896
897 if (IsPrimitiveTag(tag)) {
898 size_t width = GetTagWidth(tag);
Elliott Hughesf03b8f62011-12-02 14:26:25 -0800899 if (width == 8) {
Ian Rogersa15e67d2012-02-28 13:51:55 -0800900 uint8_t* dst = &(reinterpret_cast<uint8_t*>(a->GetRawData(sizeof(uint64_t)))[offset * width]);
Elliott Hughesf03b8f62011-12-02 14:26:25 -0800901 for (int i = 0; i < count; ++i) {
902 // Handle potentially non-aligned memory access one byte at a time for ARM's benefit.
903 uint64_t value;
904 for (size_t j = 0; j < sizeof(uint64_t); ++j) reinterpret_cast<uint8_t*>(&value)[j] = src[j];
905 src += sizeof(uint64_t);
906 JDWP::Write8BE(&dst, value);
907 }
908 } else if (width == 4) {
Ian Rogersa15e67d2012-02-28 13:51:55 -0800909 uint8_t* dst = &(reinterpret_cast<uint8_t*>(a->GetRawData(sizeof(uint32_t)))[offset * width]);
Elliott Hughesf03b8f62011-12-02 14:26:25 -0800910 const uint32_t* src4 = reinterpret_cast<const uint32_t*>(src);
911 for (int i = 0; i < count; ++i) JDWP::Write4BE(&dst, src4[i]);
912 } else if (width == 2) {
Ian Rogersa15e67d2012-02-28 13:51:55 -0800913 uint8_t* dst = &(reinterpret_cast<uint8_t*>(a->GetRawData(sizeof(uint16_t)))[offset * width]);
Elliott Hughesf03b8f62011-12-02 14:26:25 -0800914 const uint16_t* src2 = reinterpret_cast<const uint16_t*>(src);
915 for (int i = 0; i < count; ++i) JDWP::Write2BE(&dst, src2[i]);
916 } else {
Ian Rogersa15e67d2012-02-28 13:51:55 -0800917 uint8_t* dst = &(reinterpret_cast<uint8_t*>(a->GetRawData(sizeof(uint8_t)))[offset * width]);
Elliott Hughesf03b8f62011-12-02 14:26:25 -0800918 memcpy(&dst[offset * width], src, count * width);
919 }
920 } else {
921 ObjectArray<Object>* oa = a->AsObjectArray<Object>();
922 for (int i = 0; i < count; ++i) {
923 JDWP::ObjectId id = JDWP::ReadObjectId(&src);
Elliott Hughes436e3722012-02-17 20:01:47 -0800924 Object* o = gRegistry->Get<Object*>(id);
925 if (o == kInvalidObject) {
926 return JDWP::ERR_INVALID_OBJECT;
927 }
928 oa->Set(offset + i, o);
Elliott Hughesf03b8f62011-12-02 14:26:25 -0800929 }
930 }
931
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -0800932 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700933}
934
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -0800935JDWP::ObjectId Dbg::CreateString(const std::string& str) {
Ian Rogers50b35e22012-10-04 10:09:15 -0700936 return gRegistry->Add(String::AllocFromModifiedUtf8(Thread::Current(), str.c_str()));
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700937}
938
Elliott Hughes88d63092013-01-09 09:55:54 -0800939JDWP::JdwpError Dbg::CreateObject(JDWP::RefTypeId class_id, JDWP::ObjectId& new_object) {
Elliott Hughes436e3722012-02-17 20:01:47 -0800940 JDWP::JdwpError status;
Elliott Hughes88d63092013-01-09 09:55:54 -0800941 Class* c = DecodeClass(class_id, status);
Elliott Hughes436e3722012-02-17 20:01:47 -0800942 if (c == NULL) {
943 return status;
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -0800944 }
Ian Rogers50b35e22012-10-04 10:09:15 -0700945 new_object = gRegistry->Add(c->AllocObject(Thread::Current()));
Elliott Hughes436e3722012-02-17 20:01:47 -0800946 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700947}
948
Elliott Hughesbf13d362011-12-08 15:51:37 -0800949/*
950 * Used by Eclipse's "Display" view to evaluate "new byte[5]" to get "(byte[]) [0, 0, 0, 0, 0]".
951 */
Elliott Hughes88d63092013-01-09 09:55:54 -0800952JDWP::JdwpError Dbg::CreateArrayObject(JDWP::RefTypeId array_class_id, uint32_t length,
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700953 JDWP::ObjectId& new_array) {
Elliott Hughes436e3722012-02-17 20:01:47 -0800954 JDWP::JdwpError status;
Elliott Hughes88d63092013-01-09 09:55:54 -0800955 Class* c = DecodeClass(array_class_id, status);
Elliott Hughes436e3722012-02-17 20:01:47 -0800956 if (c == NULL) {
957 return status;
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -0800958 }
Ian Rogers50b35e22012-10-04 10:09:15 -0700959 new_array = gRegistry->Add(Array::Alloc(Thread::Current(), c, length));
Elliott Hughes436e3722012-02-17 20:01:47 -0800960 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700961}
962
Elliott Hughes88d63092013-01-09 09:55:54 -0800963bool Dbg::MatchType(JDWP::RefTypeId instance_class_id, JDWP::RefTypeId class_id) {
Elliott Hughes436e3722012-02-17 20:01:47 -0800964 JDWP::JdwpError status;
Elliott Hughes88d63092013-01-09 09:55:54 -0800965 Class* c1 = DecodeClass(instance_class_id, status);
Elliott Hughesa656a0f2012-02-21 18:03:44 -0800966 CHECK(c1 != NULL);
Elliott Hughes88d63092013-01-09 09:55:54 -0800967 Class* c2 = DecodeClass(class_id, status);
Elliott Hughesa656a0f2012-02-21 18:03:44 -0800968 CHECK(c2 != NULL);
969 return c1->IsAssignableFrom(c2);
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700970}
971
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700972static JDWP::FieldId ToFieldId(const Field* f)
Ian Rogersb726dcb2012-09-05 08:57:23 -0700973 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Elliott Hughes03181a82011-11-17 17:22:21 -0800974#ifdef MOVING_GARBAGE_COLLECTOR
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700975 UNIMPLEMENTED(FATAL);
Elliott Hughes03181a82011-11-17 17:22:21 -0800976#else
977 return static_cast<JDWP::FieldId>(reinterpret_cast<uintptr_t>(f));
978#endif
979}
980
Mathieu Chartier66f19252012-09-18 08:57:04 -0700981static JDWP::MethodId ToMethodId(const AbstractMethod* m)
Ian Rogersb726dcb2012-09-05 08:57:23 -0700982 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Elliott Hughes03181a82011-11-17 17:22:21 -0800983#ifdef MOVING_GARBAGE_COLLECTOR
984 UNIMPLEMENTED(FATAL);
985#else
986 return static_cast<JDWP::MethodId>(reinterpret_cast<uintptr_t>(m));
987#endif
988}
989
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700990static Field* FromFieldId(JDWP::FieldId fid)
Ian Rogersb726dcb2012-09-05 08:57:23 -0700991 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Elliott Hughesaed4be92011-12-02 16:16:23 -0800992#ifdef MOVING_GARBAGE_COLLECTOR
993 UNIMPLEMENTED(FATAL);
994#else
995 return reinterpret_cast<Field*>(static_cast<uintptr_t>(fid));
996#endif
997}
998
Mathieu Chartier66f19252012-09-18 08:57:04 -0700999static AbstractMethod* FromMethodId(JDWP::MethodId mid)
Ian Rogersb726dcb2012-09-05 08:57:23 -07001000 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Elliott Hughes03181a82011-11-17 17:22:21 -08001001#ifdef MOVING_GARBAGE_COLLECTOR
1002 UNIMPLEMENTED(FATAL);
1003#else
Mathieu Chartier66f19252012-09-18 08:57:04 -07001004 return reinterpret_cast<AbstractMethod*>(static_cast<uintptr_t>(mid));
Elliott Hughes03181a82011-11-17 17:22:21 -08001005#endif
1006}
1007
Mathieu Chartier66f19252012-09-18 08:57:04 -07001008static void SetLocation(JDWP::JdwpLocation& location, AbstractMethod* m, uint32_t dex_pc)
Ian Rogersb726dcb2012-09-05 08:57:23 -07001009 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08001010 if (m == NULL) {
1011 memset(&location, 0, sizeof(location));
1012 } else {
1013 Class* c = m->GetDeclaringClass();
Elliott Hughes74847412012-06-20 18:10:21 -07001014 location.type_tag = c->IsInterface() ? JDWP::TT_INTERFACE : JDWP::TT_CLASS;
1015 location.class_id = gRegistry->Add(c);
1016 location.method_id = ToMethodId(m);
Ian Rogers0399dde2012-06-06 17:09:28 -07001017 location.dex_pc = dex_pc;
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08001018 }
Elliott Hughesd07986f2011-12-06 18:27:45 -08001019}
1020
Elliott Hughes88d63092013-01-09 09:55:54 -08001021std::string Dbg::GetMethodName(JDWP::RefTypeId, JDWP::MethodId method_id)
Ian Rogersb726dcb2012-09-05 08:57:23 -07001022 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Elliott Hughes88d63092013-01-09 09:55:54 -08001023 AbstractMethod* m = FromMethodId(method_id);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001024 return MethodHelper(m).GetName();
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001025}
1026
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001027/*
1028 * Augment the access flags for synthetic methods and fields by setting
1029 * the (as described by the spec) "0xf0000000 bit". Also, strip out any
1030 * flags not specified by the Java programming language.
1031 */
1032static uint32_t MangleAccessFlags(uint32_t accessFlags) {
1033 accessFlags &= kAccJavaFlagsMask;
1034 if ((accessFlags & kAccSynthetic) != 0) {
1035 accessFlags |= 0xf0000000;
1036 }
1037 return accessFlags;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001038}
1039
Elliott Hughesdbb40792011-11-18 17:05:22 -08001040static const uint16_t kEclipseWorkaroundSlot = 1000;
1041
1042/*
1043 * Eclipse appears to expect that the "this" reference is in slot zero.
1044 * If it's not, the "variables" display will show two copies of "this",
1045 * possibly because it gets "this" from SF.ThisObject and then displays
1046 * all locals with nonzero slot numbers.
1047 *
1048 * So, we remap the item in slot 0 to 1000, and remap "this" to zero. On
1049 * SF.GetValues / SF.SetValues we map them back.
Elliott Hughesc5b734a2011-12-01 17:20:58 -08001050 *
1051 * TODO: jdb uses the value to determine whether a variable is a local or an argument,
1052 * by checking whether it's less than the number of arguments. To make that work, we'd
1053 * have to "mangle" all the arguments to come first, not just the implicit argument 'this'.
Elliott Hughesdbb40792011-11-18 17:05:22 -08001054 */
1055static uint16_t MangleSlot(uint16_t slot, const char* name) {
1056 uint16_t newSlot = slot;
1057 if (strcmp(name, "this") == 0) {
1058 newSlot = 0;
1059 } else if (slot == 0) {
1060 newSlot = kEclipseWorkaroundSlot;
1061 }
1062 return newSlot;
1063}
1064
Mathieu Chartier66f19252012-09-18 08:57:04 -07001065static uint16_t DemangleSlot(uint16_t slot, AbstractMethod* m)
Ian Rogersb726dcb2012-09-05 08:57:23 -07001066 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Elliott Hughesdbb40792011-11-18 17:05:22 -08001067 if (slot == kEclipseWorkaroundSlot) {
Elliott Hughes68fdbd02011-11-29 19:22:47 -08001068 return 0;
Elliott Hughesdbb40792011-11-18 17:05:22 -08001069 } else if (slot == 0) {
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08001070 const DexFile::CodeItem* code_item = MethodHelper(m).GetCodeItem();
Elliott Hughescaf76542012-06-28 16:08:22 -07001071 CHECK(code_item != NULL) << PrettyMethod(m);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001072 return code_item->registers_size_ - code_item->ins_size_;
Elliott Hughesdbb40792011-11-18 17:05:22 -08001073 }
Elliott Hughes68fdbd02011-11-29 19:22:47 -08001074 return slot;
Elliott Hughesdbb40792011-11-18 17:05:22 -08001075}
1076
Elliott Hughes88d63092013-01-09 09:55:54 -08001077JDWP::JdwpError Dbg::OutputDeclaredFields(JDWP::RefTypeId class_id, bool with_generic, JDWP::ExpandBuf* pReply) {
Elliott Hughes436e3722012-02-17 20:01:47 -08001078 JDWP::JdwpError status;
Elliott Hughes88d63092013-01-09 09:55:54 -08001079 Class* c = DecodeClass(class_id, status);
Elliott Hughes436e3722012-02-17 20:01:47 -08001080 if (c == NULL) {
1081 return status;
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -08001082 }
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001083
1084 size_t instance_field_count = c->NumInstanceFields();
1085 size_t static_field_count = c->NumStaticFields();
1086
1087 expandBufAdd4BE(pReply, instance_field_count + static_field_count);
1088
1089 for (size_t i = 0; i < instance_field_count + static_field_count; ++i) {
1090 Field* f = (i < instance_field_count) ? c->GetInstanceField(i) : c->GetStaticField(i - instance_field_count);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001091 FieldHelper fh(f);
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001092 expandBufAddFieldId(pReply, ToFieldId(f));
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001093 expandBufAddUtf8String(pReply, fh.GetName());
1094 expandBufAddUtf8String(pReply, fh.GetTypeDescriptor());
Elliott Hughesc5b734a2011-12-01 17:20:58 -08001095 if (with_generic) {
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001096 static const char genericSignature[1] = "";
1097 expandBufAddUtf8String(pReply, genericSignature);
1098 }
1099 expandBufAdd4BE(pReply, MangleAccessFlags(f->GetAccessFlags()));
1100 }
Elliott Hughes436e3722012-02-17 20:01:47 -08001101 return JDWP::ERR_NONE;
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001102}
1103
Elliott Hughes88d63092013-01-09 09:55:54 -08001104JDWP::JdwpError Dbg::OutputDeclaredMethods(JDWP::RefTypeId class_id, bool with_generic,
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001105 JDWP::ExpandBuf* pReply) {
Elliott Hughes436e3722012-02-17 20:01:47 -08001106 JDWP::JdwpError status;
Elliott Hughes88d63092013-01-09 09:55:54 -08001107 Class* c = DecodeClass(class_id, status);
Elliott Hughes436e3722012-02-17 20:01:47 -08001108 if (c == NULL) {
1109 return status;
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -08001110 }
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001111
1112 size_t direct_method_count = c->NumDirectMethods();
1113 size_t virtual_method_count = c->NumVirtualMethods();
1114
1115 expandBufAdd4BE(pReply, direct_method_count + virtual_method_count);
1116
1117 for (size_t i = 0; i < direct_method_count + virtual_method_count; ++i) {
Mathieu Chartier66f19252012-09-18 08:57:04 -07001118 AbstractMethod* m = (i < direct_method_count) ? c->GetDirectMethod(i) : c->GetVirtualMethod(i - direct_method_count);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001119 MethodHelper mh(m);
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001120 expandBufAddMethodId(pReply, ToMethodId(m));
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001121 expandBufAddUtf8String(pReply, mh.GetName());
Elliott Hughes4740cdf2011-12-07 14:07:12 -08001122 expandBufAddUtf8String(pReply, mh.GetSignature());
Elliott Hughesc5b734a2011-12-01 17:20:58 -08001123 if (with_generic) {
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001124 static const char genericSignature[1] = "";
1125 expandBufAddUtf8String(pReply, genericSignature);
1126 }
1127 expandBufAdd4BE(pReply, MangleAccessFlags(m->GetAccessFlags()));
1128 }
Elliott Hughes436e3722012-02-17 20:01:47 -08001129 return JDWP::ERR_NONE;
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001130}
1131
Elliott Hughes88d63092013-01-09 09:55:54 -08001132JDWP::JdwpError Dbg::OutputDeclaredInterfaces(JDWP::RefTypeId class_id, JDWP::ExpandBuf* pReply) {
Elliott Hughes436e3722012-02-17 20:01:47 -08001133 JDWP::JdwpError status;
Elliott Hughes88d63092013-01-09 09:55:54 -08001134 Class* c = DecodeClass(class_id, status);
Elliott Hughes436e3722012-02-17 20:01:47 -08001135 if (c == NULL) {
1136 return status;
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -08001137 }
Elliott Hughes436e3722012-02-17 20:01:47 -08001138
1139 ClassHelper kh(c);
Ian Rogersd24e2642012-06-06 21:21:43 -07001140 size_t interface_count = kh.NumDirectInterfaces();
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001141 expandBufAdd4BE(pReply, interface_count);
1142 for (size_t i = 0; i < interface_count; ++i) {
Ian Rogersd24e2642012-06-06 21:21:43 -07001143 expandBufAddRefTypeId(pReply, gRegistry->Add(kh.GetDirectInterface(i)));
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001144 }
Elliott Hughes436e3722012-02-17 20:01:47 -08001145 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001146}
1147
Elliott Hughes88d63092013-01-09 09:55:54 -08001148void Dbg::OutputLineTable(JDWP::RefTypeId, JDWP::MethodId method_id, JDWP::ExpandBuf* pReply)
Ian Rogersb726dcb2012-09-05 08:57:23 -07001149 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Elliott Hughes03181a82011-11-17 17:22:21 -08001150 struct DebugCallbackContext {
1151 int numItems;
1152 JDWP::ExpandBuf* pReply;
1153
Elliott Hughes2435a572012-02-17 16:07:41 -08001154 static bool Callback(void* context, uint32_t address, uint32_t line_number) {
Elliott Hughes03181a82011-11-17 17:22:21 -08001155 DebugCallbackContext* pContext = reinterpret_cast<DebugCallbackContext*>(context);
1156 expandBufAdd8BE(pContext->pReply, address);
Elliott Hughes2435a572012-02-17 16:07:41 -08001157 expandBufAdd4BE(pContext->pReply, line_number);
Elliott Hughes03181a82011-11-17 17:22:21 -08001158 pContext->numItems++;
1159 return true;
1160 }
1161 };
Elliott Hughes88d63092013-01-09 09:55:54 -08001162 AbstractMethod* m = FromMethodId(method_id);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001163 MethodHelper mh(m);
Elliott Hughes03181a82011-11-17 17:22:21 -08001164 uint64_t start, end;
1165 if (m->IsNative()) {
1166 start = -1;
1167 end = -1;
1168 } else {
1169 start = 0;
jeffhao14f0db92012-12-14 17:50:42 -08001170 // Return the index of the last instruction
1171 end = mh.GetCodeItem()->insns_size_in_code_units_ - 1;
Elliott Hughes03181a82011-11-17 17:22:21 -08001172 }
1173
1174 expandBufAdd8BE(pReply, start);
1175 expandBufAdd8BE(pReply, end);
1176
1177 // Add numLines later
1178 size_t numLinesOffset = expandBufGetLength(pReply);
1179 expandBufAdd4BE(pReply, 0);
1180
1181 DebugCallbackContext context;
1182 context.numItems = 0;
1183 context.pReply = pReply;
1184
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001185 mh.GetDexFile().DecodeDebugInfo(mh.GetCodeItem(), m->IsStatic(), m->GetDexMethodIndex(),
1186 DebugCallbackContext::Callback, NULL, &context);
Elliott Hughes03181a82011-11-17 17:22:21 -08001187
1188 JDWP::Set4BE(expandBufGetBuffer(pReply) + numLinesOffset, context.numItems);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001189}
1190
Elliott Hughes88d63092013-01-09 09:55:54 -08001191void Dbg::OutputVariableTable(JDWP::RefTypeId, JDWP::MethodId method_id, bool with_generic, JDWP::ExpandBuf* pReply) {
Elliott Hughesdbb40792011-11-18 17:05:22 -08001192 struct DebugCallbackContext {
Elliott Hughesdbb40792011-11-18 17:05:22 -08001193 JDWP::ExpandBuf* pReply;
Elliott Hughesc5b734a2011-12-01 17:20:58 -08001194 size_t variable_count;
1195 bool with_generic;
Elliott Hughesdbb40792011-11-18 17:05:22 -08001196
Elliott Hughesc5b734a2011-12-01 17:20:58 -08001197 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 -08001198 DebugCallbackContext* pContext = reinterpret_cast<DebugCallbackContext*>(context);
1199
Elliott Hughesad3da692012-02-24 16:51:35 -08001200 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 -08001201
Elliott Hughes68fdbd02011-11-29 19:22:47 -08001202 slot = MangleSlot(slot, name);
1203
Elliott Hughesdbb40792011-11-18 17:05:22 -08001204 expandBufAdd8BE(pContext->pReply, startAddress);
1205 expandBufAddUtf8String(pContext->pReply, name);
1206 expandBufAddUtf8String(pContext->pReply, descriptor);
Elliott Hughesc5b734a2011-12-01 17:20:58 -08001207 if (pContext->with_generic) {
Elliott Hughesdbb40792011-11-18 17:05:22 -08001208 expandBufAddUtf8String(pContext->pReply, signature);
1209 }
1210 expandBufAdd4BE(pContext->pReply, endAddress - startAddress);
1211 expandBufAdd4BE(pContext->pReply, slot);
1212
Elliott Hughesc5b734a2011-12-01 17:20:58 -08001213 ++pContext->variable_count;
Elliott Hughesdbb40792011-11-18 17:05:22 -08001214 }
1215 };
Elliott Hughes88d63092013-01-09 09:55:54 -08001216 AbstractMethod* m = FromMethodId(method_id);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001217 MethodHelper mh(m);
1218 const DexFile::CodeItem* code_item = mh.GetCodeItem();
Elliott Hughesdbb40792011-11-18 17:05:22 -08001219
Elliott Hughesc5b734a2011-12-01 17:20:58 -08001220 // arg_count considers doubles and longs to take 2 units.
1221 // variable_count considers everything to take 1 unit.
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001222 std::string shorty(mh.GetShorty());
Ian Rogers2fa6b2e2012-10-17 00:10:17 -07001223 expandBufAdd4BE(pReply, AbstractMethod::NumArgRegisters(shorty));
Elliott Hughesdbb40792011-11-18 17:05:22 -08001224
Elliott Hughesc5b734a2011-12-01 17:20:58 -08001225 // We don't know the total number of variables yet, so leave a blank and update it later.
1226 size_t variable_count_offset = expandBufGetLength(pReply);
Elliott Hughesdbb40792011-11-18 17:05:22 -08001227 expandBufAdd4BE(pReply, 0);
1228
1229 DebugCallbackContext context;
Elliott Hughesdbb40792011-11-18 17:05:22 -08001230 context.pReply = pReply;
Elliott Hughesc5b734a2011-12-01 17:20:58 -08001231 context.variable_count = 0;
1232 context.with_generic = with_generic;
Elliott Hughesdbb40792011-11-18 17:05:22 -08001233
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001234 mh.GetDexFile().DecodeDebugInfo(code_item, m->IsStatic(), m->GetDexMethodIndex(), NULL,
1235 DebugCallbackContext::Callback, &context);
Elliott Hughesdbb40792011-11-18 17:05:22 -08001236
Elliott Hughesc5b734a2011-12-01 17:20:58 -08001237 JDWP::Set4BE(expandBufGetBuffer(pReply) + variable_count_offset, context.variable_count);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001238}
1239
Elliott Hughes88d63092013-01-09 09:55:54 -08001240JDWP::JdwpTag Dbg::GetFieldBasicTag(JDWP::FieldId field_id) {
1241 return BasicTagFromDescriptor(FieldHelper(FromFieldId(field_id)).GetTypeDescriptor());
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001242}
1243
Elliott Hughes88d63092013-01-09 09:55:54 -08001244JDWP::JdwpTag Dbg::GetStaticFieldBasicTag(JDWP::FieldId field_id) {
1245 return BasicTagFromDescriptor(FieldHelper(FromFieldId(field_id)).GetTypeDescriptor());
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001246}
1247
Elliott Hughes88d63092013-01-09 09:55:54 -08001248static JDWP::JdwpError GetFieldValueImpl(JDWP::RefTypeId ref_type_id, JDWP::ObjectId object_id,
1249 JDWP::FieldId field_id, JDWP::ExpandBuf* pReply,
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001250 bool is_static)
Ian Rogersb726dcb2012-09-05 08:57:23 -07001251 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Elliott Hughes0cf74332012-02-23 23:14:00 -08001252 JDWP::JdwpError status;
Elliott Hughes88d63092013-01-09 09:55:54 -08001253 Class* c = DecodeClass(ref_type_id, status);
1254 if (ref_type_id != 0 && c == NULL) {
Elliott Hughes0cf74332012-02-23 23:14:00 -08001255 return status;
1256 }
1257
Elliott Hughes88d63092013-01-09 09:55:54 -08001258 Object* o = gRegistry->Get<Object*>(object_id);
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08001259 if ((!is_static && o == NULL) || o == kInvalidObject) {
1260 return JDWP::ERR_INVALID_OBJECT;
1261 }
Elliott Hughes88d63092013-01-09 09:55:54 -08001262 Field* f = FromFieldId(field_id);
Elliott Hughes0cf74332012-02-23 23:14:00 -08001263
1264 Class* receiver_class = c;
1265 if (receiver_class == NULL && o != NULL) {
1266 receiver_class = o->GetClass();
1267 }
1268 // TODO: should we give up now if receiver_class is NULL?
1269 if (receiver_class != NULL && !f->GetDeclaringClass()->IsAssignableFrom(receiver_class)) {
1270 LOG(INFO) << "ERR_INVALID_FIELDID: " << PrettyField(f) << " " << PrettyClass(receiver_class);
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08001271 return JDWP::ERR_INVALID_FIELDID;
1272 }
Elliott Hughesaed4be92011-12-02 16:16:23 -08001273
Elliott Hughes0cf74332012-02-23 23:14:00 -08001274 // The RI only enforces the static/non-static mismatch in one direction.
1275 // TODO: should we change the tests and check both?
1276 if (is_static) {
1277 if (!f->IsStatic()) {
1278 return JDWP::ERR_INVALID_FIELDID;
1279 }
1280 } else {
1281 if (f->IsStatic()) {
1282 LOG(WARNING) << "Ignoring non-NULL receiver for ObjectReference.SetValues on static field " << PrettyField(f);
Elliott Hughes0cf74332012-02-23 23:14:00 -08001283 }
1284 }
jeffhao0dfbb7e2012-11-28 15:26:03 -08001285 if (f->IsStatic()) {
1286 o = f->GetDeclaringClass();
1287 }
Elliott Hughes0cf74332012-02-23 23:14:00 -08001288
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001289 JDWP::JdwpTag tag = BasicTagFromDescriptor(FieldHelper(f).GetTypeDescriptor());
Elliott Hughesaed4be92011-12-02 16:16:23 -08001290
1291 if (IsPrimitiveTag(tag)) {
1292 expandBufAdd1(pReply, tag);
1293 if (tag == JDWP::JT_BOOLEAN || tag == JDWP::JT_BYTE) {
1294 expandBufAdd1(pReply, f->Get32(o));
1295 } else if (tag == JDWP::JT_CHAR || tag == JDWP::JT_SHORT) {
1296 expandBufAdd2BE(pReply, f->Get32(o));
1297 } else if (tag == JDWP::JT_FLOAT || tag == JDWP::JT_INT) {
1298 expandBufAdd4BE(pReply, f->Get32(o));
1299 } else if (tag == JDWP::JT_DOUBLE || tag == JDWP::JT_LONG) {
1300 expandBufAdd8BE(pReply, f->Get64(o));
1301 } else {
Elliott Hughes3d30d9b2011-12-07 17:35:48 -08001302 LOG(FATAL) << "Unknown tag: " << tag;
Elliott Hughesaed4be92011-12-02 16:16:23 -08001303 }
1304 } else {
1305 Object* value = f->GetObject(o);
1306 expandBufAdd1(pReply, TagFromObject(value));
1307 expandBufAddObjectId(pReply, gRegistry->Add(value));
1308 }
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08001309 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001310}
1311
Elliott Hughes88d63092013-01-09 09:55:54 -08001312JDWP::JdwpError Dbg::GetFieldValue(JDWP::ObjectId object_id, JDWP::FieldId field_id,
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001313 JDWP::ExpandBuf* pReply) {
Elliott Hughes88d63092013-01-09 09:55:54 -08001314 return GetFieldValueImpl(0, object_id, field_id, pReply, false);
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08001315}
1316
Elliott Hughes88d63092013-01-09 09:55:54 -08001317JDWP::JdwpError Dbg::GetStaticFieldValue(JDWP::RefTypeId ref_type_id, JDWP::FieldId field_id, JDWP::ExpandBuf* pReply) {
1318 return GetFieldValueImpl(ref_type_id, 0, field_id, pReply, true);
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08001319}
1320
Elliott Hughes88d63092013-01-09 09:55:54 -08001321static JDWP::JdwpError SetFieldValueImpl(JDWP::ObjectId object_id, JDWP::FieldId field_id,
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001322 uint64_t value, int width, bool is_static)
Ian Rogersb726dcb2012-09-05 08:57:23 -07001323 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Elliott Hughes88d63092013-01-09 09:55:54 -08001324 Object* o = gRegistry->Get<Object*>(object_id);
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08001325 if ((!is_static && o == NULL) || o == kInvalidObject) {
1326 return JDWP::ERR_INVALID_OBJECT;
1327 }
Elliott Hughes88d63092013-01-09 09:55:54 -08001328 Field* f = FromFieldId(field_id);
Elliott Hughes0cf74332012-02-23 23:14:00 -08001329
1330 // The RI only enforces the static/non-static mismatch in one direction.
1331 // TODO: should we change the tests and check both?
1332 if (is_static) {
1333 if (!f->IsStatic()) {
1334 return JDWP::ERR_INVALID_FIELDID;
1335 }
1336 } else {
1337 if (f->IsStatic()) {
1338 LOG(WARNING) << "Ignoring non-NULL receiver for ObjectReference.SetValues on static field " << PrettyField(f);
Elliott Hughes0cf74332012-02-23 23:14:00 -08001339 }
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08001340 }
jeffhao0dfbb7e2012-11-28 15:26:03 -08001341 if (f->IsStatic()) {
1342 o = f->GetDeclaringClass();
1343 }
Elliott Hughesaed4be92011-12-02 16:16:23 -08001344
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001345 JDWP::JdwpTag tag = BasicTagFromDescriptor(FieldHelper(f).GetTypeDescriptor());
Elliott Hughesaed4be92011-12-02 16:16:23 -08001346
1347 if (IsPrimitiveTag(tag)) {
1348 if (tag == JDWP::JT_DOUBLE || tag == JDWP::JT_LONG) {
Elliott Hughes1bac54f2012-03-16 12:48:31 -07001349 CHECK_EQ(width, 8);
Elliott Hughesaed4be92011-12-02 16:16:23 -08001350 f->Set64(o, value);
1351 } else {
Elliott Hughes1bac54f2012-03-16 12:48:31 -07001352 CHECK_LE(width, 4);
Elliott Hughesaed4be92011-12-02 16:16:23 -08001353 f->Set32(o, value);
1354 }
1355 } else {
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -08001356 Object* v = gRegistry->Get<Object*>(value);
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08001357 if (v == kInvalidObject) {
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -08001358 return JDWP::ERR_INVALID_OBJECT;
1359 }
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08001360 if (v != NULL) {
1361 Class* field_type = FieldHelper(f).GetType();
1362 if (!field_type->IsAssignableFrom(v->GetClass())) {
1363 return JDWP::ERR_INVALID_OBJECT;
1364 }
1365 }
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -08001366 f->SetObject(o, v);
Elliott Hughesaed4be92011-12-02 16:16:23 -08001367 }
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -08001368
1369 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001370}
1371
Elliott Hughes88d63092013-01-09 09:55:54 -08001372JDWP::JdwpError Dbg::SetFieldValue(JDWP::ObjectId object_id, JDWP::FieldId field_id, uint64_t value,
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001373 int width) {
Elliott Hughes88d63092013-01-09 09:55:54 -08001374 return SetFieldValueImpl(object_id, field_id, value, width, false);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001375}
1376
Elliott Hughes88d63092013-01-09 09:55:54 -08001377JDWP::JdwpError Dbg::SetStaticFieldValue(JDWP::FieldId field_id, uint64_t value, int width) {
1378 return SetFieldValueImpl(0, field_id, value, width, true);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001379}
1380
Elliott Hughes88d63092013-01-09 09:55:54 -08001381std::string Dbg::StringToUtf8(JDWP::ObjectId string_id) {
1382 String* s = gRegistry->Get<String*>(string_id);
Elliott Hughes68fdbd02011-11-29 19:22:47 -08001383 return s->ToModifiedUtf8();
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001384}
1385
Elliott Hughes221229c2013-01-08 18:17:50 -08001386JDWP::JdwpError Dbg::GetThreadName(JDWP::ObjectId thread_id, std::string& name) {
jeffhaoa77f0f62012-12-05 17:19:31 -08001387 ScopedObjectAccessUnchecked soa(Thread::Current());
1388 MutexLock mu(soa.Self(), *Locks::thread_list_lock_);
Elliott Hughes221229c2013-01-08 18:17:50 -08001389 Thread* thread;
1390 JDWP::JdwpError error = DecodeThread(soa, thread_id, thread);
1391 if (error != JDWP::ERR_NONE && error != JDWP::ERR_THREAD_NOT_ALIVE) {
1392 return error;
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001393 }
Elliott Hughes221229c2013-01-08 18:17:50 -08001394
1395 // We still need to report the zombie threads' names, so we can't just call Thread::GetThreadName.
1396 Object* thread_object = gRegistry->Get<Object*>(thread_id);
1397 Field* java_lang_Thread_name_field = soa.DecodeField(WellKnownClasses::java_lang_Thread_name);
1398 String* s = reinterpret_cast<String*>(java_lang_Thread_name_field->GetObject(thread_object));
1399 if (s != NULL) {
1400 name = s->ToModifiedUtf8();
1401 }
1402 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001403}
1404
Elliott Hughes221229c2013-01-08 18:17:50 -08001405JDWP::JdwpError Dbg::GetThreadGroup(JDWP::ObjectId thread_id, JDWP::ExpandBuf* pReply) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001406 ScopedObjectAccess soa(Thread::Current());
Elliott Hughes221229c2013-01-08 18:17:50 -08001407 Object* thread_object = gRegistry->Get<Object*>(thread_id);
1408 if (thread_object == kInvalidObject) {
Elliott Hughes2435a572012-02-17 16:07:41 -08001409 return JDWP::ERR_INVALID_OBJECT;
1410 }
1411
1412 // Okay, so it's an object, but is it actually a thread?
Ian Rogers50b35e22012-10-04 10:09:15 -07001413 MutexLock mu(soa.Self(), *Locks::thread_list_lock_);
Elliott Hughes221229c2013-01-08 18:17:50 -08001414 Thread* thread;
1415 JDWP::JdwpError error = DecodeThread(soa, thread_id, thread);
1416 if (error == JDWP::ERR_THREAD_NOT_ALIVE) {
1417 // Zombie threads are in the null group.
1418 expandBufAddObjectId(pReply, JDWP::ObjectId(0));
1419 return JDWP::ERR_NONE;
1420 }
1421 if (error != JDWP::ERR_NONE) {
1422 return error;
Elliott Hughes2435a572012-02-17 16:07:41 -08001423 }
Elliott Hughes499c5132011-11-17 14:55:11 -08001424
1425 Class* c = Runtime::Current()->GetClassLinker()->FindSystemClass("Ljava/lang/Thread;");
1426 CHECK(c != NULL);
1427 Field* f = c->FindInstanceField("group", "Ljava/lang/ThreadGroup;");
1428 CHECK(f != NULL);
Elliott Hughes221229c2013-01-08 18:17:50 -08001429 Object* group = f->GetObject(thread_object);
Elliott Hughes499c5132011-11-17 14:55:11 -08001430 CHECK(group != NULL);
Elliott Hughes2435a572012-02-17 16:07:41 -08001431 JDWP::ObjectId thread_group_id = gRegistry->Add(group);
1432
1433 expandBufAddObjectId(pReply, thread_group_id);
1434 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001435}
1436
Elliott Hughes88d63092013-01-09 09:55:54 -08001437std::string Dbg::GetThreadGroupName(JDWP::ObjectId thread_group_id) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001438 ScopedObjectAccess soa(Thread::Current());
Elliott Hughes88d63092013-01-09 09:55:54 -08001439 Object* thread_group = gRegistry->Get<Object*>(thread_group_id);
Elliott Hughes499c5132011-11-17 14:55:11 -08001440 CHECK(thread_group != NULL);
1441
1442 Class* c = Runtime::Current()->GetClassLinker()->FindSystemClass("Ljava/lang/ThreadGroup;");
1443 CHECK(c != NULL);
1444 Field* f = c->FindInstanceField("name", "Ljava/lang/String;");
1445 CHECK(f != NULL);
1446 String* s = reinterpret_cast<String*>(f->GetObject(thread_group));
1447 return s->ToModifiedUtf8();
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001448}
1449
Elliott Hughes88d63092013-01-09 09:55:54 -08001450JDWP::ObjectId Dbg::GetThreadGroupParent(JDWP::ObjectId thread_group_id) {
1451 Object* thread_group = gRegistry->Get<Object*>(thread_group_id);
Elliott Hughes4e235312011-12-02 11:34:15 -08001452 CHECK(thread_group != NULL);
1453
1454 Class* c = Runtime::Current()->GetClassLinker()->FindSystemClass("Ljava/lang/ThreadGroup;");
1455 CHECK(c != NULL);
1456 Field* f = c->FindInstanceField("parent", "Ljava/lang/ThreadGroup;");
1457 CHECK(f != NULL);
1458 Object* parent = f->GetObject(thread_group);
1459 return gRegistry->Add(parent);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001460}
1461
1462JDWP::ObjectId Dbg::GetSystemThreadGroupId() {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001463 ScopedObjectAccessUnchecked soa(Thread::Current());
jeffhao0dfbb7e2012-11-28 15:26:03 -08001464 Field* f = soa.DecodeField(WellKnownClasses::java_lang_ThreadGroup_systemThreadGroup);
1465 Object* group = f->GetObject(f->GetDeclaringClass());
Ian Rogers365c1022012-06-22 15:05:28 -07001466 return gRegistry->Add(group);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001467}
1468
1469JDWP::ObjectId Dbg::GetMainThreadGroupId() {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001470 ScopedObjectAccess soa(Thread::Current());
jeffhao0dfbb7e2012-11-28 15:26:03 -08001471 Field* f = soa.DecodeField(WellKnownClasses::java_lang_ThreadGroup_mainThreadGroup);
1472 Object* group = f->GetObject(f->GetDeclaringClass());
Ian Rogers365c1022012-06-22 15:05:28 -07001473 return gRegistry->Add(group);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001474}
1475
Elliott Hughes221229c2013-01-08 18:17:50 -08001476JDWP::JdwpError Dbg::GetThreadStatus(JDWP::ObjectId thread_id, JDWP::JdwpThreadStatus* pThreadStatus, JDWP::JdwpSuspendStatus* pSuspendStatus) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001477 ScopedObjectAccess soa(Thread::Current());
Elliott Hughes499c5132011-11-17 14:55:11 -08001478
Elliott Hughes9e0c1752013-01-09 14:02:58 -08001479 *pSuspendStatus = JDWP::SUSPEND_STATUS_NOT_SUSPENDED;
1480
Ian Rogers50b35e22012-10-04 10:09:15 -07001481 MutexLock mu(soa.Self(), *Locks::thread_list_lock_);
Elliott Hughes221229c2013-01-08 18:17:50 -08001482 Thread* thread;
1483 JDWP::JdwpError error = DecodeThread(soa, thread_id, thread);
1484 if (error != JDWP::ERR_NONE) {
1485 if (error == JDWP::ERR_THREAD_NOT_ALIVE) {
1486 *pThreadStatus = JDWP::TS_ZOMBIE;
Elliott Hughes221229c2013-01-08 18:17:50 -08001487 return JDWP::ERR_NONE;
1488 }
1489 return error;
Elliott Hughes499c5132011-11-17 14:55:11 -08001490 }
1491
Elliott Hughes9e0c1752013-01-09 14:02:58 -08001492 if (IsSuspendedForDebugger(soa, thread)) {
1493 *pSuspendStatus = JDWP::SUSPEND_STATUS_SUSPENDED;
Elliott Hughes499c5132011-11-17 14:55:11 -08001494 }
1495
Elliott Hughes9e0c1752013-01-09 14:02:58 -08001496 switch (thread->GetState()) {
1497 case kBlocked: *pThreadStatus = JDWP::TS_MONITOR; break;
1498 case kNative: *pThreadStatus = JDWP::TS_RUNNING; break;
1499 case kRunnable: *pThreadStatus = JDWP::TS_RUNNING; break;
1500 case kSleeping: *pThreadStatus = JDWP::TS_SLEEPING; break;
1501 case kStarting: *pThreadStatus = JDWP::TS_ZOMBIE; break;
1502 case kSuspended: *pThreadStatus = JDWP::TS_RUNNING; break;
1503 case kTerminated: *pThreadStatus = JDWP::TS_ZOMBIE; break;
1504 case kTimedWaiting: *pThreadStatus = JDWP::TS_WAIT; break;
1505 case kWaitingForDebuggerSend: *pThreadStatus = JDWP::TS_WAIT; break;
1506 case kWaitingForDebuggerSuspension: *pThreadStatus = JDWP::TS_WAIT; break;
1507 case kWaitingForDebuggerToAttach: *pThreadStatus = JDWP::TS_WAIT; break;
1508 case kWaitingForGcToComplete: *pThreadStatus = JDWP::TS_WAIT; break;
1509 case kWaitingForJniOnLoad: *pThreadStatus = JDWP::TS_WAIT; break;
1510 case kWaitingForSignalCatcherOutput: *pThreadStatus = JDWP::TS_WAIT; break;
1511 case kWaitingInMainDebuggerLoop: *pThreadStatus = JDWP::TS_WAIT; break;
1512 case kWaitingInMainSignalCatcherLoop: *pThreadStatus = JDWP::TS_WAIT; break;
1513 case kWaitingPerformingGc: *pThreadStatus = JDWP::TS_WAIT; break;
1514 case kWaiting: *pThreadStatus = JDWP::TS_WAIT; break;
1515 // Don't add a 'default' here so the compiler can spot incompatible enum changes.
1516 }
Elliott Hughes221229c2013-01-08 18:17:50 -08001517 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001518}
1519
Elliott Hughes221229c2013-01-08 18:17:50 -08001520JDWP::JdwpError Dbg::GetThreadDebugSuspendCount(JDWP::ObjectId thread_id, JDWP::ExpandBuf* pReply) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001521 ScopedObjectAccess soa(Thread::Current());
Ian Rogers50b35e22012-10-04 10:09:15 -07001522 MutexLock mu(soa.Self(), *Locks::thread_list_lock_);
Elliott Hughes221229c2013-01-08 18:17:50 -08001523 Thread* thread;
1524 JDWP::JdwpError error = DecodeThread(soa, thread_id, thread);
1525 if (error != JDWP::ERR_NONE) {
1526 return error;
Elliott Hughes2435a572012-02-17 16:07:41 -08001527 }
Ian Rogers50b35e22012-10-04 10:09:15 -07001528 MutexLock mu2(soa.Self(), *Locks::thread_suspend_count_lock_);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001529 expandBufAdd4BE(pReply, thread->GetDebugSuspendCount());
Elliott Hughes2435a572012-02-17 16:07:41 -08001530 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001531}
1532
Elliott Hughescaf76542012-06-28 16:08:22 -07001533void Dbg::GetThreads(JDWP::ObjectId thread_group_id, std::vector<JDWP::ObjectId>& thread_ids) {
Ian Rogers365c1022012-06-22 15:05:28 -07001534 class ThreadListVisitor {
1535 public:
jeffhao0dfbb7e2012-11-28 15:26:03 -08001536 ThreadListVisitor(const ScopedObjectAccessUnchecked& soa, Object* desired_thread_group,
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001537 std::vector<JDWP::ObjectId>& thread_ids)
Ian Rogersb726dcb2012-09-05 08:57:23 -07001538 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_)
jeffhao0dfbb7e2012-11-28 15:26:03 -08001539 : soa_(soa), desired_thread_group_(desired_thread_group), thread_ids_(thread_ids) {}
Ian Rogers365c1022012-06-22 15:05:28 -07001540
Elliott Hughesa2155262011-11-16 16:26:58 -08001541 static void Visit(Thread* t, void* arg) {
1542 reinterpret_cast<ThreadListVisitor*>(arg)->Visit(t);
1543 }
1544
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001545 // TODO: Enable annotalysis. We know lock is held in constructor, but abstraction confuses
1546 // annotalysis.
1547 void Visit(Thread* t) NO_THREAD_SAFETY_ANALYSIS {
Elliott Hughesa2155262011-11-16 16:26:58 -08001548 if (t == Dbg::GetDebugThread()) {
1549 // Skip the JDWP thread. Some debuggers get bent out of shape when they can't suspend and
1550 // query all threads, so it's easier if we just don't tell them about this thread.
1551 return;
1552 }
Ian Rogerscfaa4552012-11-26 21:00:08 -08001553 Object* peer = t->GetPeer();
jeffhao0dfbb7e2012-11-28 15:26:03 -08001554 if (IsInDesiredThreadGroup(peer)) {
Ian Rogers120f1c72012-09-28 17:17:10 -07001555 thread_ids_.push_back(gRegistry->Add(peer));
Elliott Hughesa2155262011-11-16 16:26:58 -08001556 }
1557 }
1558
Ian Rogers365c1022012-06-22 15:05:28 -07001559 private:
jeffhao0dfbb7e2012-11-28 15:26:03 -08001560 bool IsInDesiredThreadGroup(Object* peer)
1561 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
jeffhao0dfbb7e2012-11-28 15:26:03 -08001562 // peer might be NULL if the thread is still starting up.
1563 if (peer == NULL) {
1564 // We can't tell the debugger about this thread yet.
1565 // TODO: if we identified threads to the debugger by their Thread*
1566 // rather than their peer's Object*, we could fix this.
1567 // Doing so might help us report ZOMBIE threads too.
1568 return false;
1569 }
jeffhaoc1e04902012-12-13 12:41:10 -08001570 // Do we want threads from all thread groups?
1571 if (desired_thread_group_ == NULL) {
1572 return true;
1573 }
jeffhao0dfbb7e2012-11-28 15:26:03 -08001574 Object* group = soa_.DecodeField(WellKnownClasses::java_lang_Thread_group)->GetObject(peer);
1575 return (group == desired_thread_group_);
1576 }
1577
Mathieu Chartierdbe6f462012-09-25 16:54:50 -07001578 const ScopedObjectAccessUnchecked& soa_;
jeffhao0dfbb7e2012-11-28 15:26:03 -08001579 Object* const desired_thread_group_;
Elliott Hughescaf76542012-06-28 16:08:22 -07001580 std::vector<JDWP::ObjectId>& thread_ids_;
Elliott Hughesa2155262011-11-16 16:26:58 -08001581 };
1582
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001583 ScopedObjectAccessUnchecked soa(Thread::Current());
Elliott Hughescaf76542012-06-28 16:08:22 -07001584 Object* thread_group = gRegistry->Get<Object*>(thread_group_id);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001585 ThreadListVisitor tlv(soa, thread_group, thread_ids);
Ian Rogers50b35e22012-10-04 10:09:15 -07001586 MutexLock mu(soa.Self(), *Locks::thread_list_lock_);
Elliott Hughesf8349362012-06-18 15:00:06 -07001587 Runtime::Current()->GetThreadList()->ForEach(ThreadListVisitor::Visit, &tlv);
Elliott Hughescaf76542012-06-28 16:08:22 -07001588}
Elliott Hughesa2155262011-11-16 16:26:58 -08001589
Elliott Hughescaf76542012-06-28 16:08:22 -07001590void Dbg::GetChildThreadGroups(JDWP::ObjectId thread_group_id, std::vector<JDWP::ObjectId>& child_thread_group_ids) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001591 ScopedObjectAccess soa(Thread::Current());
Elliott Hughescaf76542012-06-28 16:08:22 -07001592 Object* thread_group = gRegistry->Get<Object*>(thread_group_id);
1593
1594 // Get the ArrayList<ThreadGroup> "groups" out of this thread group...
1595 Field* groups_field = thread_group->GetClass()->FindInstanceField("groups", "Ljava/util/List;");
1596 Object* groups_array_list = groups_field->GetObject(thread_group);
1597
1598 // Get the array and size out of the ArrayList<ThreadGroup>...
1599 Field* array_field = groups_array_list->GetClass()->FindInstanceField("array", "[Ljava/lang/Object;");
1600 Field* size_field = groups_array_list->GetClass()->FindInstanceField("size", "I");
1601 ObjectArray<Object>* groups_array = array_field->GetObject(groups_array_list)->AsObjectArray<Object>();
1602 const int32_t size = size_field->GetInt(groups_array_list);
1603
1604 // Copy the first 'size' elements out of the array into the result.
1605 for (int32_t i = 0; i < size; ++i) {
1606 child_thread_group_ids.push_back(gRegistry->Add(groups_array->Get(i)));
Elliott Hughesa2155262011-11-16 16:26:58 -08001607 }
1608}
1609
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001610static int GetStackDepth(Thread* thread)
Ian Rogersb726dcb2012-09-05 08:57:23 -07001611 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Ian Rogers0399dde2012-06-06 17:09:28 -07001612 struct CountStackDepthVisitor : public StackVisitor {
1613 CountStackDepthVisitor(const ManagedStack* stack,
Ian Rogers306057f2012-11-26 12:45:53 -08001614 const std::deque<InstrumentationStackFrame>* instrumentation_stack)
jeffhao725a9572012-11-13 18:20:12 -08001615 : StackVisitor(stack, instrumentation_stack, NULL), depth(0) {}
Ian Rogers0399dde2012-06-06 17:09:28 -07001616
1617 bool VisitFrame() {
1618 if (!GetMethod()->IsRuntimeMethod()) {
Elliott Hughesf8a2df72011-12-01 12:19:54 -08001619 ++depth;
1620 }
Elliott Hughes530fa002012-03-12 11:44:49 -07001621 return true;
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001622 }
1623 size_t depth;
1624 };
Elliott Hughes08fc03a2012-06-26 17:34:00 -07001625
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001626 if (kIsDebugBuild) {
Ian Rogers50b35e22012-10-04 10:09:15 -07001627 MutexLock mu(Thread::Current(), *Locks::thread_suspend_count_lock_);
jeffhao09bfc6a2012-12-11 18:11:43 -08001628 CHECK(thread == Thread::Current() || thread->IsSuspended());
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001629 }
jeffhao725a9572012-11-13 18:20:12 -08001630 CountStackDepthVisitor visitor(thread->GetManagedStack(), thread->GetInstrumentationStack());
Ian Rogers0399dde2012-06-06 17:09:28 -07001631 visitor.WalkStack();
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001632 return visitor.depth;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001633}
1634
Elliott Hughes221229c2013-01-08 18:17:50 -08001635JDWP::JdwpError Dbg::GetThreadFrameCount(JDWP::ObjectId thread_id, size_t& result) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001636 ScopedObjectAccess soa(Thread::Current());
jeffhaoa77f0f62012-12-05 17:19:31 -08001637 MutexLock mu(soa.Self(), *Locks::thread_list_lock_);
Elliott Hughes221229c2013-01-08 18:17:50 -08001638 Thread* thread;
1639 JDWP::JdwpError error = DecodeThread(soa, thread_id, thread);
1640 if (error != JDWP::ERR_NONE) {
1641 return error;
1642 }
Elliott Hughesf15f4a02013-01-09 10:09:38 -08001643 if (!IsSuspendedForDebugger(soa, thread)) {
1644 return JDWP::ERR_THREAD_NOT_SUSPENDED;
1645 }
Elliott Hughes221229c2013-01-08 18:17:50 -08001646 result = GetStackDepth(thread);
1647 return JDWP::ERR_NONE;
Elliott Hughes86964332012-02-15 19:37:42 -08001648}
1649
Ian Rogers306057f2012-11-26 12:45:53 -08001650JDWP::JdwpError Dbg::GetThreadFrames(JDWP::ObjectId thread_id, size_t start_frame,
1651 size_t frame_count, JDWP::ExpandBuf* buf) {
Elliott Hughes6e9d22c2012-06-22 15:02:37 -07001652 class GetFrameVisitor : public StackVisitor {
1653 public:
Ian Rogers306057f2012-11-26 12:45:53 -08001654 GetFrameVisitor(const ManagedStack* stack,
1655 const std::deque<InstrumentationStackFrame>* instrumentation_stack,
Elliott Hughes6e9d22c2012-06-22 15:02:37 -07001656 size_t start_frame, size_t frame_count, JDWP::ExpandBuf* buf)
Ian Rogersb726dcb2012-09-05 08:57:23 -07001657 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_)
jeffhao725a9572012-11-13 18:20:12 -08001658 : StackVisitor(stack, instrumentation_stack, NULL), depth_(0),
Elliott Hughes6e9d22c2012-06-22 15:02:37 -07001659 start_frame_(start_frame), frame_count_(frame_count), buf_(buf) {
1660 expandBufAdd4BE(buf_, frame_count_);
Elliott Hughes03181a82011-11-17 17:22:21 -08001661 }
Ian Rogers0399dde2012-06-06 17:09:28 -07001662
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001663 // TODO: Enable annotalysis. We know lock is held in constructor, but abstraction confuses
1664 // annotalysis.
1665 virtual bool VisitFrame() NO_THREAD_SAFETY_ANALYSIS {
Ian Rogers0399dde2012-06-06 17:09:28 -07001666 if (GetMethod()->IsRuntimeMethod()) {
Elliott Hughes530fa002012-03-12 11:44:49 -07001667 return true; // The debugger can't do anything useful with a frame that has no Method*.
Elliott Hughes03181a82011-11-17 17:22:21 -08001668 }
Elliott Hughes6e9d22c2012-06-22 15:02:37 -07001669 if (depth_ >= start_frame_ + frame_count_) {
Elliott Hughes530fa002012-03-12 11:44:49 -07001670 return false;
Elliott Hughes03181a82011-11-17 17:22:21 -08001671 }
Elliott Hughes6e9d22c2012-06-22 15:02:37 -07001672 if (depth_ >= start_frame_) {
1673 JDWP::FrameId frame_id(GetFrameId());
1674 JDWP::JdwpLocation location;
1675 SetLocation(location, GetMethod(), GetDexPc());
Elliott Hughes7baf96f2012-06-22 16:33:50 -07001676 VLOG(jdwp) << StringPrintf(" Frame %3zd: id=%3lld ", depth_, frame_id) << location;
Elliott Hughes6e9d22c2012-06-22 15:02:37 -07001677 expandBufAdd8BE(buf_, frame_id);
1678 expandBufAddLocation(buf_, location);
1679 }
1680 ++depth_;
Elliott Hughes530fa002012-03-12 11:44:49 -07001681 return true;
Elliott Hughes03181a82011-11-17 17:22:21 -08001682 }
Elliott Hughes6e9d22c2012-06-22 15:02:37 -07001683
1684 private:
1685 size_t depth_;
1686 const size_t start_frame_;
1687 const size_t frame_count_;
1688 JDWP::ExpandBuf* buf_;
Elliott Hughes03181a82011-11-17 17:22:21 -08001689 };
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001690
1691 ScopedObjectAccessUnchecked soa(Thread::Current());
jeffhaoa77f0f62012-12-05 17:19:31 -08001692 MutexLock mu(soa.Self(), *Locks::thread_list_lock_);
Elliott Hughes221229c2013-01-08 18:17:50 -08001693 Thread* thread;
1694 JDWP::JdwpError error = DecodeThread(soa, thread_id, thread);
1695 if (error != JDWP::ERR_NONE) {
1696 return error;
1697 }
Elliott Hughesf15f4a02013-01-09 10:09:38 -08001698 if (!IsSuspendedForDebugger(soa, thread)) {
1699 return JDWP::ERR_THREAD_NOT_SUSPENDED;
1700 }
Ian Rogers306057f2012-11-26 12:45:53 -08001701 GetFrameVisitor visitor(thread->GetManagedStack(), thread->GetInstrumentationStack(),
1702 start_frame, frame_count, buf);
Ian Rogers0399dde2012-06-06 17:09:28 -07001703 visitor.WalkStack();
Elliott Hughes6e9d22c2012-06-22 15:02:37 -07001704 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001705}
1706
1707JDWP::ObjectId Dbg::GetThreadSelfId() {
Mathieu Chartierdbe6f462012-09-25 16:54:50 -07001708 ScopedObjectAccessUnchecked soa(Thread::Current());
Ian Rogerscfaa4552012-11-26 21:00:08 -08001709 return gRegistry->Add(soa.Self()->GetPeer());
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001710}
1711
Elliott Hughes475fc232011-10-25 15:00:35 -07001712void Dbg::SuspendVM() {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001713 Runtime::Current()->GetThreadList()->SuspendAllForDebugger();
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001714}
1715
1716void Dbg::ResumeVM() {
Elliott Hughesc61a2672012-06-21 14:52:29 -07001717 Runtime::Current()->GetThreadList()->UndoDebuggerSuspensions();
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001718}
1719
Elliott Hughes221229c2013-01-08 18:17:50 -08001720JDWP::JdwpError Dbg::SuspendThread(JDWP::ObjectId thread_id, bool request_suspension) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001721 ScopedLocalRef<jobject> peer(Thread::Current()->GetJniEnv(), NULL);
1722 {
1723 ScopedObjectAccess soa(Thread::Current());
Elliott Hughes221229c2013-01-08 18:17:50 -08001724 peer.reset(soa.AddLocalReference<jobject>(gRegistry->Get<Object*>(thread_id)));
Elliott Hughes4e235312011-12-02 11:34:15 -08001725 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001726 if (peer.get() == NULL) {
Elliott Hughes221229c2013-01-08 18:17:50 -08001727 LOG(WARNING) << "No such thread for suspend: " << thread_id;
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001728 return JDWP::ERR_THREAD_NOT_ALIVE;
1729 }
1730 // Suspend thread to build stack trace.
Elliott Hughesf327e072013-01-09 16:01:26 -08001731 bool timed_out;
1732 Thread* thread = Thread::SuspendForDebugger(peer.get(), request_suspension, &timed_out);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001733 if (thread != NULL) {
1734 return JDWP::ERR_NONE;
Elliott Hughesf327e072013-01-09 16:01:26 -08001735 } else if (timed_out) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001736 return JDWP::ERR_INTERNAL;
1737 } else {
1738 return JDWP::ERR_THREAD_NOT_ALIVE;
1739 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001740}
1741
Elliott Hughes221229c2013-01-08 18:17:50 -08001742void Dbg::ResumeThread(JDWP::ObjectId thread_id) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001743 ScopedObjectAccessUnchecked soa(Thread::Current());
Elliott Hughes221229c2013-01-08 18:17:50 -08001744 Object* peer = gRegistry->Get<Object*>(thread_id);
jeffhaoa77f0f62012-12-05 17:19:31 -08001745 Thread* thread;
1746 {
1747 MutexLock mu(soa.Self(), *Locks::thread_list_lock_);
1748 thread = Thread::FromManagedThread(soa, peer);
1749 }
Elliott Hughes4e235312011-12-02 11:34:15 -08001750 if (thread == NULL) {
1751 LOG(WARNING) << "No such thread for resume: " << peer;
1752 return;
1753 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001754 bool needs_resume;
1755 {
Ian Rogers50b35e22012-10-04 10:09:15 -07001756 MutexLock mu2(soa.Self(), *Locks::thread_suspend_count_lock_);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001757 needs_resume = thread->GetSuspendCount() > 0;
1758 }
1759 if (needs_resume) {
Elliott Hughes546b9862012-06-20 16:06:13 -07001760 Runtime::Current()->GetThreadList()->Resume(thread, true);
1761 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001762}
1763
1764void Dbg::SuspendSelf() {
Elliott Hughes475fc232011-10-25 15:00:35 -07001765 Runtime::Current()->GetThreadList()->SuspendSelfForDebugger();
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001766}
1767
Ian Rogers0399dde2012-06-06 17:09:28 -07001768struct GetThisVisitor : public StackVisitor {
Ian Rogers306057f2012-11-26 12:45:53 -08001769 GetThisVisitor(const ManagedStack* stack,
1770 const std::deque<InstrumentationStackFrame>* instrumentation_stack,
Elliott Hughes88d63092013-01-09 09:55:54 -08001771 Context* context, JDWP::FrameId frame_id)
Ian Rogersb726dcb2012-09-05 08:57:23 -07001772 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_)
Elliott Hughes88d63092013-01-09 09:55:54 -08001773 : StackVisitor(stack, instrumentation_stack, context), this_object(NULL), frame_id(frame_id) {}
Ian Rogers0399dde2012-06-06 17:09:28 -07001774
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001775 // TODO: Enable annotalysis. We know lock is held in constructor, but abstraction confuses
1776 // annotalysis.
1777 virtual bool VisitFrame() NO_THREAD_SAFETY_ANALYSIS {
Elliott Hughes6e9d22c2012-06-22 15:02:37 -07001778 if (frame_id != GetFrameId()) {
Ian Rogers0399dde2012-06-06 17:09:28 -07001779 return true; // continue
1780 }
Mathieu Chartier66f19252012-09-18 08:57:04 -07001781 AbstractMethod* m = GetMethod();
Ian Rogers0399dde2012-06-06 17:09:28 -07001782 if (m->IsNative() || m->IsStatic()) {
Elliott Hughes6e9d22c2012-06-22 15:02:37 -07001783 this_object = NULL;
Ian Rogers0399dde2012-06-06 17:09:28 -07001784 } else {
1785 uint16_t reg = DemangleSlot(0, m);
Ian Rogers2bcb4a42012-11-08 10:39:18 -08001786 this_object = reinterpret_cast<Object*>(GetVReg(m, reg, kReferenceVReg));
Ian Rogers0399dde2012-06-06 17:09:28 -07001787 }
1788 return false;
Elliott Hughes86b00102011-12-05 17:54:26 -08001789 }
Ian Rogers0399dde2012-06-06 17:09:28 -07001790
Elliott Hughes6e9d22c2012-06-22 15:02:37 -07001791 Object* this_object;
1792 JDWP::FrameId frame_id;
Ian Rogers0399dde2012-06-06 17:09:28 -07001793};
1794
Mathieu Chartier66f19252012-09-18 08:57:04 -07001795static Object* GetThis(Thread* self, AbstractMethod* m, size_t frame_id)
Ian Rogersb726dcb2012-09-05 08:57:23 -07001796 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Elliott Hughescaf76542012-06-28 16:08:22 -07001797 // TODO: should we return the 'this' we passed through to non-static native methods?
Ian Rogers0399dde2012-06-06 17:09:28 -07001798 if (m->IsNative() || m->IsStatic()) {
1799 return NULL;
1800 }
Elliott Hughescaf76542012-06-28 16:08:22 -07001801
Ian Rogers0399dde2012-06-06 17:09:28 -07001802 UniquePtr<Context> context(Context::Create());
jeffhao725a9572012-11-13 18:20:12 -08001803 GetThisVisitor visitor(self->GetManagedStack(), self->GetInstrumentationStack(), context.get(), frame_id);
Elliott Hughescaf76542012-06-28 16:08:22 -07001804 visitor.WalkStack();
1805 return visitor.this_object;
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08001806}
1807
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001808JDWP::JdwpError Dbg::GetThisObject(JDWP::ObjectId thread_id, JDWP::FrameId frame_id,
1809 JDWP::ObjectId* result) {
1810 ScopedObjectAccessUnchecked soa(Thread::Current());
1811 Thread* thread;
1812 {
Ian Rogers50b35e22012-10-04 10:09:15 -07001813 MutexLock mu(soa.Self(), *Locks::thread_list_lock_);
Elliott Hughes221229c2013-01-08 18:17:50 -08001814 JDWP::JdwpError error = DecodeThread(soa, thread_id, thread);
1815 if (error != JDWP::ERR_NONE) {
1816 return error;
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001817 }
Elliott Hughes9e0c1752013-01-09 14:02:58 -08001818 if (!IsSuspendedForDebugger(soa, thread)) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001819 return JDWP::ERR_THREAD_NOT_SUSPENDED;
1820 }
Elliott Hughes6e9d22c2012-06-22 15:02:37 -07001821 }
Elliott Hughescaf76542012-06-28 16:08:22 -07001822 UniquePtr<Context> context(Context::Create());
jeffhao725a9572012-11-13 18:20:12 -08001823 GetThisVisitor visitor(thread->GetManagedStack(), thread->GetInstrumentationStack(), context.get(), frame_id);
Ian Rogers0399dde2012-06-06 17:09:28 -07001824 visitor.WalkStack();
Elliott Hughes6e9d22c2012-06-22 15:02:37 -07001825 *result = gRegistry->Add(visitor.this_object);
1826 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001827}
1828
Elliott Hughes88d63092013-01-09 09:55:54 -08001829void Dbg::GetLocalValue(JDWP::ObjectId thread_id, JDWP::FrameId frame_id, int slot, JDWP::JdwpTag tag,
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001830 uint8_t* buf, size_t width) {
Ian Rogers0399dde2012-06-06 17:09:28 -07001831 struct GetLocalVisitor : public StackVisitor {
Ian Rogers306057f2012-11-26 12:45:53 -08001832 GetLocalVisitor(const ManagedStack* stack,
1833 const std::deque<InstrumentationStackFrame>* instrumentation_stack,
Elliott Hughes88d63092013-01-09 09:55:54 -08001834 Context* context, JDWP::FrameId frame_id, int slot, JDWP::JdwpTag tag,
Ian Rogersca190662012-06-26 15:45:57 -07001835 uint8_t* buf, size_t width)
Ian Rogersb726dcb2012-09-05 08:57:23 -07001836 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_)
Elliott Hughes88d63092013-01-09 09:55:54 -08001837 : StackVisitor(stack, instrumentation_stack, context), frame_id_(frame_id), slot_(slot), tag_(tag),
Ian Rogersca190662012-06-26 15:45:57 -07001838 buf_(buf), width_(width) {}
1839
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001840 // TODO: Enable annotalysis. We know lock is held in constructor, but abstraction confuses
1841 // annotalysis.
1842 bool VisitFrame() NO_THREAD_SAFETY_ANALYSIS {
Ian Rogers0399dde2012-06-06 17:09:28 -07001843 if (GetFrameId() != frame_id_) {
1844 return true; // Not our frame, carry on.
Elliott Hughesdbb40792011-11-18 17:05:22 -08001845 }
Ian Rogers0399dde2012-06-06 17:09:28 -07001846 // TODO: check that the tag is compatible with the actual type of the slot!
Mathieu Chartier66f19252012-09-18 08:57:04 -07001847 AbstractMethod* m = GetMethod();
Ian Rogers0399dde2012-06-06 17:09:28 -07001848 uint16_t reg = DemangleSlot(slot_, m);
Elliott Hughesdbb40792011-11-18 17:05:22 -08001849
Ian Rogers0399dde2012-06-06 17:09:28 -07001850 switch (tag_) {
1851 case JDWP::JT_BOOLEAN:
1852 {
1853 CHECK_EQ(width_, 1U);
Ian Rogers2bcb4a42012-11-08 10:39:18 -08001854 uint32_t intVal = GetVReg(m, reg, kIntVReg);
Ian Rogers0399dde2012-06-06 17:09:28 -07001855 VLOG(jdwp) << "get boolean local " << reg << " = " << intVal;
1856 JDWP::Set1(buf_+1, intVal != 0);
1857 }
1858 break;
1859 case JDWP::JT_BYTE:
1860 {
1861 CHECK_EQ(width_, 1U);
Ian Rogers2bcb4a42012-11-08 10:39:18 -08001862 uint32_t intVal = GetVReg(m, reg, kIntVReg);
Ian Rogers0399dde2012-06-06 17:09:28 -07001863 VLOG(jdwp) << "get byte local " << reg << " = " << intVal;
1864 JDWP::Set1(buf_+1, intVal);
1865 }
1866 break;
1867 case JDWP::JT_SHORT:
1868 case JDWP::JT_CHAR:
1869 {
1870 CHECK_EQ(width_, 2U);
Ian Rogers2bcb4a42012-11-08 10:39:18 -08001871 uint32_t intVal = GetVReg(m, reg, kIntVReg);
Ian Rogers0399dde2012-06-06 17:09:28 -07001872 VLOG(jdwp) << "get short/char local " << reg << " = " << intVal;
1873 JDWP::Set2BE(buf_+1, intVal);
1874 }
1875 break;
1876 case JDWP::JT_INT:
Ian Rogers2bcb4a42012-11-08 10:39:18 -08001877 {
1878 CHECK_EQ(width_, 4U);
1879 uint32_t intVal = GetVReg(m, reg, kIntVReg);
1880 VLOG(jdwp) << "get int local " << reg << " = " << intVal;
1881 JDWP::Set4BE(buf_+1, intVal);
1882 }
1883 break;
Ian Rogers0399dde2012-06-06 17:09:28 -07001884 case JDWP::JT_FLOAT:
1885 {
1886 CHECK_EQ(width_, 4U);
Ian Rogers2bcb4a42012-11-08 10:39:18 -08001887 uint32_t intVal = GetVReg(m, reg, kFloatVReg);
Ian Rogers0399dde2012-06-06 17:09:28 -07001888 VLOG(jdwp) << "get int/float local " << reg << " = " << intVal;
1889 JDWP::Set4BE(buf_+1, intVal);
1890 }
1891 break;
1892 case JDWP::JT_ARRAY:
1893 {
1894 CHECK_EQ(width_, sizeof(JDWP::ObjectId));
Ian Rogers2bcb4a42012-11-08 10:39:18 -08001895 Object* o = reinterpret_cast<Object*>(GetVReg(m, reg, kReferenceVReg));
Ian Rogers0399dde2012-06-06 17:09:28 -07001896 VLOG(jdwp) << "get array local " << reg << " = " << o;
1897 if (!Runtime::Current()->GetHeap()->IsHeapAddress(o)) {
1898 LOG(FATAL) << "Register " << reg << " expected to hold array: " << o;
1899 }
1900 JDWP::SetObjectId(buf_+1, gRegistry->Add(o));
1901 }
1902 break;
1903 case JDWP::JT_CLASS_LOADER:
1904 case JDWP::JT_CLASS_OBJECT:
1905 case JDWP::JT_OBJECT:
1906 case JDWP::JT_STRING:
1907 case JDWP::JT_THREAD:
1908 case JDWP::JT_THREAD_GROUP:
1909 {
1910 CHECK_EQ(width_, sizeof(JDWP::ObjectId));
Ian Rogers2bcb4a42012-11-08 10:39:18 -08001911 Object* o = reinterpret_cast<Object*>(GetVReg(m, reg, kReferenceVReg));
Ian Rogers0399dde2012-06-06 17:09:28 -07001912 VLOG(jdwp) << "get object local " << reg << " = " << o;
1913 if (!Runtime::Current()->GetHeap()->IsHeapAddress(o)) {
1914 LOG(FATAL) << "Register " << reg << " expected to hold object: " << o;
1915 }
1916 tag_ = TagFromObject(o);
1917 JDWP::SetObjectId(buf_+1, gRegistry->Add(o));
1918 }
1919 break;
1920 case JDWP::JT_DOUBLE:
Ian Rogers2bcb4a42012-11-08 10:39:18 -08001921 {
1922 CHECK_EQ(width_, 8U);
1923 uint32_t lo = GetVReg(m, reg, kDoubleLoVReg);
1924 uint64_t hi = GetVReg(m, reg + 1, kDoubleHiVReg);
1925 uint64_t longVal = (hi << 32) | lo;
1926 VLOG(jdwp) << "get double/long local " << hi << ":" << lo << " = " << longVal;
1927 JDWP::Set8BE(buf_+1, longVal);
1928 }
1929 break;
Ian Rogers0399dde2012-06-06 17:09:28 -07001930 case JDWP::JT_LONG:
1931 {
1932 CHECK_EQ(width_, 8U);
Ian Rogers2bcb4a42012-11-08 10:39:18 -08001933 uint32_t lo = GetVReg(m, reg, kLongLoVReg);
1934 uint64_t hi = GetVReg(m, reg + 1, kLongHiVReg);
Ian Rogers0399dde2012-06-06 17:09:28 -07001935 uint64_t longVal = (hi << 32) | lo;
1936 VLOG(jdwp) << "get double/long local " << hi << ":" << lo << " = " << longVal;
1937 JDWP::Set8BE(buf_+1, longVal);
1938 }
1939 break;
1940 default:
1941 LOG(FATAL) << "Unknown tag " << tag_;
1942 break;
1943 }
1944
1945 // Prepend tag, which may have been updated.
1946 JDWP::Set1(buf_, tag_);
1947 return false;
1948 }
1949
1950 const JDWP::FrameId frame_id_;
1951 const int slot_;
1952 JDWP::JdwpTag tag_;
1953 uint8_t* const buf_;
1954 const size_t width_;
1955 };
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001956
1957 ScopedObjectAccessUnchecked soa(Thread::Current());
jeffhaoa77f0f62012-12-05 17:19:31 -08001958 MutexLock mu(soa.Self(), *Locks::thread_list_lock_);
Elliott Hughes221229c2013-01-08 18:17:50 -08001959 Thread* thread;
1960 JDWP::JdwpError error = DecodeThread(soa, thread_id, thread);
1961 if (error != JDWP::ERR_NONE) {
1962 return;
1963 }
Ian Rogers0399dde2012-06-06 17:09:28 -07001964 UniquePtr<Context> context(Context::Create());
jeffhao725a9572012-11-13 18:20:12 -08001965 GetLocalVisitor visitor(thread->GetManagedStack(), thread->GetInstrumentationStack(), context.get(),
Elliott Hughes88d63092013-01-09 09:55:54 -08001966 frame_id, slot, tag, buf, width);
Ian Rogers0399dde2012-06-06 17:09:28 -07001967 visitor.WalkStack();
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001968}
1969
Elliott Hughes88d63092013-01-09 09:55:54 -08001970void Dbg::SetLocalValue(JDWP::ObjectId thread_id, JDWP::FrameId frame_id, int slot, JDWP::JdwpTag tag,
Ian Rogers0399dde2012-06-06 17:09:28 -07001971 uint64_t value, size_t width) {
1972 struct SetLocalVisitor : public StackVisitor {
Ian Rogers306057f2012-11-26 12:45:53 -08001973 SetLocalVisitor(const ManagedStack* stack, const std::deque<InstrumentationStackFrame>* instrumentation_stack, Context* context,
Ian Rogers0399dde2012-06-06 17:09:28 -07001974 JDWP::FrameId frame_id, int slot, JDWP::JdwpTag tag, uint64_t value,
Ian Rogersca190662012-06-26 15:45:57 -07001975 size_t width)
Ian Rogersb726dcb2012-09-05 08:57:23 -07001976 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_)
jeffhao725a9572012-11-13 18:20:12 -08001977 : StackVisitor(stack, instrumentation_stack, context),
Elliott Hughes08fc03a2012-06-26 17:34:00 -07001978 frame_id_(frame_id), slot_(slot), tag_(tag), value_(value), width_(width) {}
Ian Rogersca190662012-06-26 15:45:57 -07001979
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001980 // TODO: Enable annotalysis. We know lock is held in constructor, but abstraction confuses
1981 // annotalysis.
1982 bool VisitFrame() NO_THREAD_SAFETY_ANALYSIS {
Ian Rogers0399dde2012-06-06 17:09:28 -07001983 if (GetFrameId() != frame_id_) {
1984 return true; // Not our frame, carry on.
1985 }
1986 // TODO: check that the tag is compatible with the actual type of the slot!
Mathieu Chartier66f19252012-09-18 08:57:04 -07001987 AbstractMethod* m = GetMethod();
Ian Rogers0399dde2012-06-06 17:09:28 -07001988 uint16_t reg = DemangleSlot(slot_, m);
1989
1990 switch (tag_) {
1991 case JDWP::JT_BOOLEAN:
1992 case JDWP::JT_BYTE:
1993 CHECK_EQ(width_, 1U);
Ian Rogers2bcb4a42012-11-08 10:39:18 -08001994 SetVReg(m, reg, static_cast<uint32_t>(value_), kIntVReg);
Ian Rogers0399dde2012-06-06 17:09:28 -07001995 break;
1996 case JDWP::JT_SHORT:
1997 case JDWP::JT_CHAR:
1998 CHECK_EQ(width_, 2U);
Ian Rogers2bcb4a42012-11-08 10:39:18 -08001999 SetVReg(m, reg, static_cast<uint32_t>(value_), kIntVReg);
Ian Rogers0399dde2012-06-06 17:09:28 -07002000 break;
2001 case JDWP::JT_INT:
Ian Rogers2bcb4a42012-11-08 10:39:18 -08002002 CHECK_EQ(width_, 4U);
2003 SetVReg(m, reg, static_cast<uint32_t>(value_), kIntVReg);
2004 break;
Ian Rogers0399dde2012-06-06 17:09:28 -07002005 case JDWP::JT_FLOAT:
2006 CHECK_EQ(width_, 4U);
Ian Rogers2bcb4a42012-11-08 10:39:18 -08002007 SetVReg(m, reg, static_cast<uint32_t>(value_), kFloatVReg);
Ian Rogers0399dde2012-06-06 17:09:28 -07002008 break;
2009 case JDWP::JT_ARRAY:
2010 case JDWP::JT_OBJECT:
2011 case JDWP::JT_STRING:
2012 {
2013 CHECK_EQ(width_, sizeof(JDWP::ObjectId));
2014 Object* o = gRegistry->Get<Object*>(static_cast<JDWP::ObjectId>(value_));
2015 if (o == kInvalidObject) {
2016 UNIMPLEMENTED(FATAL) << "return an error code when given an invalid object to store";
2017 }
Ian Rogers2bcb4a42012-11-08 10:39:18 -08002018 SetVReg(m, reg, static_cast<uint32_t>(reinterpret_cast<uintptr_t>(o)), kReferenceVReg);
Ian Rogers0399dde2012-06-06 17:09:28 -07002019 }
2020 break;
2021 case JDWP::JT_DOUBLE:
Ian Rogers2bcb4a42012-11-08 10:39:18 -08002022 CHECK_EQ(width_, 8U);
2023 SetVReg(m, reg, static_cast<uint32_t>(value_), kDoubleLoVReg);
2024 SetVReg(m, reg + 1, static_cast<uint32_t>(value_ >> 32), kDoubleHiVReg);
2025 break;
Ian Rogers0399dde2012-06-06 17:09:28 -07002026 case JDWP::JT_LONG:
2027 CHECK_EQ(width_, 8U);
Ian Rogers2bcb4a42012-11-08 10:39:18 -08002028 SetVReg(m, reg, static_cast<uint32_t>(value_), kLongLoVReg);
2029 SetVReg(m, reg + 1, static_cast<uint32_t>(value_ >> 32), kLongHiVReg);
Ian Rogers0399dde2012-06-06 17:09:28 -07002030 break;
2031 default:
2032 LOG(FATAL) << "Unknown tag " << tag_;
2033 break;
2034 }
2035 return false;
2036 }
2037
2038 const JDWP::FrameId frame_id_;
2039 const int slot_;
2040 const JDWP::JdwpTag tag_;
2041 const uint64_t value_;
2042 const size_t width_;
2043 };
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002044
2045 ScopedObjectAccessUnchecked soa(Thread::Current());
jeffhaoa77f0f62012-12-05 17:19:31 -08002046 MutexLock mu(soa.Self(), *Locks::thread_list_lock_);
Elliott Hughes221229c2013-01-08 18:17:50 -08002047 Thread* thread;
2048 JDWP::JdwpError error = DecodeThread(soa, thread_id, thread);
2049 if (error != JDWP::ERR_NONE) {
2050 return;
2051 }
Elliott Hughes08fc03a2012-06-26 17:34:00 -07002052 UniquePtr<Context> context(Context::Create());
jeffhao725a9572012-11-13 18:20:12 -08002053 SetLocalVisitor visitor(thread->GetManagedStack(), thread->GetInstrumentationStack(), context.get(),
Elliott Hughes88d63092013-01-09 09:55:54 -08002054 frame_id, slot, tag, value, width);
Ian Rogers0399dde2012-06-06 17:09:28 -07002055 visitor.WalkStack();
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002056}
2057
Mathieu Chartier66f19252012-09-18 08:57:04 -07002058void Dbg::PostLocationEvent(const AbstractMethod* m, int dex_pc, Object* this_object, int event_flags) {
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08002059 Class* c = m->GetDeclaringClass();
2060
2061 JDWP::JdwpLocation location;
Elliott Hughes74847412012-06-20 18:10:21 -07002062 location.type_tag = c->IsInterface() ? JDWP::TT_INTERFACE : JDWP::TT_CLASS;
2063 location.class_id = gRegistry->Add(c);
2064 location.method_id = ToMethodId(m);
Elliott Hughes972a47b2012-02-21 18:16:06 -08002065 location.dex_pc = m->IsNative() ? -1 : dex_pc;
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08002066
2067 // Note we use "NoReg" so we don't keep track of references that are
2068 // never actually sent to the debugger. 'this_id' is only used to
2069 // compare against registered events...
2070 JDWP::ObjectId this_id = static_cast<JDWP::ObjectId>(reinterpret_cast<uintptr_t>(this_object));
2071 if (gJdwpState->PostLocationEvent(&location, this_id, event_flags)) {
2072 // ...unless there's a registered event, in which case we
2073 // need to really track the class and 'this'.
2074 gRegistry->Add(c);
2075 gRegistry->Add(this_object);
2076 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002077}
2078
Elliott Hughescaf76542012-06-28 16:08:22 -07002079void Dbg::PostException(Thread* thread,
Mathieu Chartier66f19252012-09-18 08:57:04 -07002080 JDWP::FrameId throw_frame_id, AbstractMethod* throw_method, uint32_t throw_dex_pc,
2081 AbstractMethod* catch_method, uint32_t catch_dex_pc, Throwable* exception) {
Elliott Hughesc0f09332012-03-26 13:27:06 -07002082 if (!IsDebuggerActive()) {
Ian Rogers0ad5bb82011-12-07 10:16:32 -08002083 return;
2084 }
Elliott Hughes4740cdf2011-12-07 14:07:12 -08002085
Elliott Hughesd07986f2011-12-06 18:27:45 -08002086 JDWP::JdwpLocation throw_location;
Elliott Hughescaf76542012-06-28 16:08:22 -07002087 SetLocation(throw_location, throw_method, throw_dex_pc);
Elliott Hughesd07986f2011-12-06 18:27:45 -08002088 JDWP::JdwpLocation catch_location;
Elliott Hughescaf76542012-06-28 16:08:22 -07002089 SetLocation(catch_location, catch_method, catch_dex_pc);
Elliott Hughesd07986f2011-12-06 18:27:45 -08002090
2091 // We need 'this' for InstanceOnly filters.
Elliott Hughescaf76542012-06-28 16:08:22 -07002092 UniquePtr<Context> context(Context::Create());
jeffhao725a9572012-11-13 18:20:12 -08002093 GetThisVisitor visitor(thread->GetManagedStack(), thread->GetInstrumentationStack(), context.get(), throw_frame_id);
Elliott Hughescaf76542012-06-28 16:08:22 -07002094 visitor.WalkStack();
2095 JDWP::ObjectId this_id = gRegistry->Add(visitor.this_object);
Elliott Hughesd07986f2011-12-06 18:27:45 -08002096
2097 /*
2098 * Hand the event to the JDWP exception handler. Note we're using the
2099 * "NoReg" objectID on the exception, which is not strictly correct --
2100 * the exception object WILL be passed up to the debugger if the
2101 * debugger is interested in the event. We do this because the current
2102 * implementation of the debugger object registry never throws anything
2103 * away, and some people were experiencing a fatal build up of exception
2104 * objects when dealing with certain libraries.
2105 */
2106 JDWP::ObjectId exception_id = static_cast<JDWP::ObjectId>(reinterpret_cast<uintptr_t>(exception));
2107 JDWP::RefTypeId exception_class_id = gRegistry->Add(exception->GetClass());
2108
2109 gJdwpState->PostException(&throw_location, exception_id, exception_class_id, &catch_location, this_id);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002110}
2111
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002112void Dbg::PostClassPrepare(Class* c) {
Elliott Hughesc0f09332012-03-26 13:27:06 -07002113 if (!IsDebuggerActive()) {
Elliott Hughes4740cdf2011-12-07 14:07:12 -08002114 return;
2115 }
2116
Elliott Hughes3d30d9b2011-12-07 17:35:48 -08002117 // OLD-TODO - we currently always send both "verified" and "prepared" since
Elliott Hughes4740cdf2011-12-07 14:07:12 -08002118 // debuggers seem to like that. There might be some advantage to honesty,
2119 // since the class may not yet be verified.
2120 int state = JDWP::CS_VERIFIED | JDWP::CS_PREPARED;
2121 JDWP::JdwpTypeTag tag = c->IsInterface() ? JDWP::TT_INTERFACE : JDWP::TT_CLASS;
2122 gJdwpState->PostClassPrepare(tag, gRegistry->Add(c), ClassHelper(c).GetDescriptor(), state);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002123}
2124
Elliott Hughescaf76542012-06-28 16:08:22 -07002125void Dbg::UpdateDebugger(int32_t dex_pc, Thread* self) {
Elliott Hughesc0f09332012-03-26 13:27:06 -07002126 if (!IsDebuggerActive() || dex_pc == -2 /* fake method exit */) {
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08002127 return;
2128 }
2129
Elliott Hughescaf76542012-06-28 16:08:22 -07002130 size_t frame_id;
Mathieu Chartier66f19252012-09-18 08:57:04 -07002131 AbstractMethod* m = self->GetCurrentMethod(NULL, &frame_id);
Elliott Hughescaf76542012-06-28 16:08:22 -07002132 //LOG(INFO) << "UpdateDebugger " << PrettyMethod(m) << "@" << dex_pc << " frame " << frame_id;
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08002133
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08002134 if (dex_pc == -1) {
Elliott Hughes2aa2e392012-02-17 17:15:43 -08002135 // We use a pc of -1 to represent method entry, since we might branch back to pc 0 later.
2136 // This means that for this special notification, there can't be anything else interesting
2137 // going on, so we're done already.
Elliott Hughescaf76542012-06-28 16:08:22 -07002138 Dbg::PostLocationEvent(m, 0, GetThis(self, m, frame_id), kMethodEntry);
Elliott Hughes2aa2e392012-02-17 17:15:43 -08002139 return;
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08002140 }
2141
Elliott Hughes2aa2e392012-02-17 17:15:43 -08002142 int event_flags = 0;
2143
Elliott Hughes86964332012-02-15 19:37:42 -08002144 if (IsBreakpoint(m, dex_pc)) {
2145 event_flags |= kBreakpoint;
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08002146 }
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08002147
jeffhao09bfc6a2012-12-11 18:11:43 -08002148 {
2149 // If the debugger is single-stepping one of our threads, check to
2150 // see if we're that thread and we've reached a step point.
2151 MutexLock mu(Thread::Current(), *Locks::breakpoint_lock_);
2152 if (gSingleStepControl.is_active && gSingleStepControl.thread == self) {
2153 CHECK(!m->IsNative());
2154 if (gSingleStepControl.step_depth == JDWP::SD_INTO) {
2155 // Step into method calls. We break when the line number
2156 // or method pointer changes. If we're in SS_MIN mode, we
2157 // always stop.
2158 if (gSingleStepControl.method != m) {
2159 event_flags |= kSingleStep;
2160 VLOG(jdwp) << "SS new method";
2161 } else if (gSingleStepControl.step_size == JDWP::SS_MIN) {
Elliott Hughes86964332012-02-15 19:37:42 -08002162 event_flags |= kSingleStep;
2163 VLOG(jdwp) << "SS new instruction";
Elliott Hughes2435a572012-02-17 16:07:41 -08002164 } else if (gSingleStepControl.dex_pcs.find(dex_pc) == gSingleStepControl.dex_pcs.end()) {
2165 event_flags |= kSingleStep;
2166 VLOG(jdwp) << "SS new line";
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08002167 }
jeffhao09bfc6a2012-12-11 18:11:43 -08002168 } else if (gSingleStepControl.step_depth == JDWP::SD_OVER) {
2169 // Step over method calls. We break when the line number is
2170 // different and the frame depth is <= the original frame
2171 // depth. (We can't just compare on the method, because we
2172 // might get unrolled past it by an exception, and it's tricky
2173 // to identify recursion.)
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08002174
jeffhao09bfc6a2012-12-11 18:11:43 -08002175 int stack_depth = GetStackDepth(self);
Elliott Hughes86964332012-02-15 19:37:42 -08002176
jeffhao09bfc6a2012-12-11 18:11:43 -08002177 if (stack_depth < gSingleStepControl.stack_depth) {
2178 // popped up one or more frames, always trigger
2179 event_flags |= kSingleStep;
2180 VLOG(jdwp) << "SS method pop";
2181 } else if (stack_depth == gSingleStepControl.stack_depth) {
2182 // same depth, see if we moved
2183 if (gSingleStepControl.step_size == JDWP::SS_MIN) {
2184 event_flags |= kSingleStep;
2185 VLOG(jdwp) << "SS new instruction";
2186 } else if (gSingleStepControl.dex_pcs.find(dex_pc) == gSingleStepControl.dex_pcs.end()) {
2187 event_flags |= kSingleStep;
2188 VLOG(jdwp) << "SS new line";
2189 }
2190 }
2191 } else {
2192 CHECK_EQ(gSingleStepControl.step_depth, JDWP::SD_OUT);
2193 // Return from the current method. We break when the frame
2194 // depth pops up.
2195
2196 // This differs from the "method exit" break in that it stops
2197 // with the PC at the next instruction in the returned-to
2198 // function, rather than the end of the returning function.
2199
2200 int stack_depth = GetStackDepth(self);
2201 if (stack_depth < gSingleStepControl.stack_depth) {
2202 event_flags |= kSingleStep;
2203 VLOG(jdwp) << "SS method pop";
2204 }
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08002205 }
2206 }
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08002207 }
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08002208
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08002209 // Check to see if this is a "return" instruction. JDWP says we should
2210 // send the event *after* the code has been executed, but it also says
2211 // the location we provide is the last instruction. Since the "return"
2212 // instruction has no interesting side effects, we should be safe.
2213 // (We can't just move this down to the returnFromMethod label because
2214 // we potentially need to combine it with other events.)
2215 // We're also not supposed to generate a method exit event if the method
2216 // terminates "with a thrown exception".
Elliott Hughes86964332012-02-15 19:37:42 -08002217 if (dex_pc >= 0) {
2218 const DexFile::CodeItem* code_item = MethodHelper(m).GetCodeItem();
Elliott Hughescaf76542012-06-28 16:08:22 -07002219 CHECK(code_item != NULL) << PrettyMethod(m) << " @" << dex_pc;
Elliott Hughes86964332012-02-15 19:37:42 -08002220 CHECK_LT(dex_pc, static_cast<int32_t>(code_item->insns_size_in_code_units_));
2221 if (Instruction::At(&code_item->insns_[dex_pc])->IsReturn()) {
2222 event_flags |= kMethodExit;
2223 }
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08002224 }
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08002225
2226 // If there's something interesting going on, see if it matches one
2227 // of the debugger filters.
2228 if (event_flags != 0) {
Elliott Hughescaf76542012-06-28 16:08:22 -07002229 Dbg::PostLocationEvent(m, dex_pc, GetThis(self, m, frame_id), event_flags);
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08002230 }
2231}
2232
Elliott Hughes86964332012-02-15 19:37:42 -08002233void Dbg::WatchLocation(const JDWP::JdwpLocation* location) {
jeffhao09bfc6a2012-12-11 18:11:43 -08002234 MutexLock mu(Thread::Current(), *Locks::breakpoint_lock_);
Mathieu Chartier66f19252012-09-18 08:57:04 -07002235 AbstractMethod* m = FromMethodId(location->method_id);
Elliott Hughes972a47b2012-02-21 18:16:06 -08002236 gBreakpoints.push_back(Breakpoint(m, location->dex_pc));
Elliott Hughes86964332012-02-15 19:37:42 -08002237 VLOG(jdwp) << "Set breakpoint #" << (gBreakpoints.size() - 1) << ": " << gBreakpoints[gBreakpoints.size() - 1];
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002238}
2239
Elliott Hughes86964332012-02-15 19:37:42 -08002240void Dbg::UnwatchLocation(const JDWP::JdwpLocation* location) {
jeffhao09bfc6a2012-12-11 18:11:43 -08002241 MutexLock mu(Thread::Current(), *Locks::breakpoint_lock_);
Mathieu Chartier66f19252012-09-18 08:57:04 -07002242 AbstractMethod* m = FromMethodId(location->method_id);
Elliott Hughes86964332012-02-15 19:37:42 -08002243 for (size_t i = 0; i < gBreakpoints.size(); ++i) {
Elliott Hughes972a47b2012-02-21 18:16:06 -08002244 if (gBreakpoints[i].method == m && gBreakpoints[i].dex_pc == location->dex_pc) {
Elliott Hughes86964332012-02-15 19:37:42 -08002245 VLOG(jdwp) << "Removed breakpoint #" << i << ": " << gBreakpoints[i];
2246 gBreakpoints.erase(gBreakpoints.begin() + i);
2247 return;
2248 }
2249 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002250}
2251
Elliott Hughes221229c2013-01-08 18:17:50 -08002252JDWP::JdwpError Dbg::ConfigureStep(JDWP::ObjectId thread_id, JDWP::JdwpStepSize step_size,
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002253 JDWP::JdwpStepDepth step_depth) {
2254 ScopedObjectAccessUnchecked soa(Thread::Current());
jeffhaoa77f0f62012-12-05 17:19:31 -08002255 MutexLock mu(soa.Self(), *Locks::thread_list_lock_);
Elliott Hughes221229c2013-01-08 18:17:50 -08002256 Thread* thread;
2257 JDWP::JdwpError error = DecodeThread(soa, thread_id, thread);
2258 if (error != JDWP::ERR_NONE) {
2259 return error;
Elliott Hughes2435a572012-02-17 16:07:41 -08002260 }
Elliott Hughes86964332012-02-15 19:37:42 -08002261
jeffhao09bfc6a2012-12-11 18:11:43 -08002262 MutexLock mu2(soa.Self(), *Locks::breakpoint_lock_);
Elliott Hughes86964332012-02-15 19:37:42 -08002263 // TODO: there's no theoretical reason why we couldn't support single-stepping
2264 // of multiple threads at once, but we never did so historically.
2265 if (gSingleStepControl.thread != NULL && thread != gSingleStepControl.thread) {
2266 LOG(WARNING) << "single-step already active for " << *gSingleStepControl.thread
2267 << "; switching to " << *thread;
2268 }
2269
Elliott Hughes2435a572012-02-17 16:07:41 -08002270 //
2271 // Work out what Method* we're in, the current line number, and how deep the stack currently
2272 // is for step-out.
2273 //
2274
Ian Rogers0399dde2012-06-06 17:09:28 -07002275 struct SingleStepStackVisitor : public StackVisitor {
2276 SingleStepStackVisitor(const ManagedStack* stack,
Ian Rogers306057f2012-11-26 12:45:53 -08002277 const std::deque<InstrumentationStackFrame>* instrumentation_stack)
jeffhao09bfc6a2012-12-11 18:11:43 -08002278 EXCLUSIVE_LOCKS_REQUIRED(Locks::breakpoint_lock_)
Ian Rogersb726dcb2012-09-05 08:57:23 -07002279 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_)
jeffhao725a9572012-11-13 18:20:12 -08002280 : StackVisitor(stack, instrumentation_stack, NULL) {
Elliott Hughes86964332012-02-15 19:37:42 -08002281 gSingleStepControl.method = NULL;
2282 gSingleStepControl.stack_depth = 0;
2283 }
Ian Rogersca190662012-06-26 15:45:57 -07002284
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002285 // TODO: Enable annotalysis. We know lock is held in constructor, but abstraction confuses
2286 // annotalysis.
2287 bool VisitFrame() NO_THREAD_SAFETY_ANALYSIS {
jeffhao09bfc6a2012-12-11 18:11:43 -08002288 Locks::breakpoint_lock_->AssertHeld(Thread::Current());
Mathieu Chartier66f19252012-09-18 08:57:04 -07002289 const AbstractMethod* m = GetMethod();
Ian Rogers0399dde2012-06-06 17:09:28 -07002290 if (!m->IsRuntimeMethod()) {
Elliott Hughes86964332012-02-15 19:37:42 -08002291 ++gSingleStepControl.stack_depth;
2292 if (gSingleStepControl.method == NULL) {
Elliott Hughes2435a572012-02-17 16:07:41 -08002293 const DexCache* dex_cache = m->GetDeclaringClass()->GetDexCache();
2294 gSingleStepControl.method = m;
2295 gSingleStepControl.line_number = -1;
2296 if (dex_cache != NULL) {
Ian Rogers4445a7e2012-10-05 17:19:13 -07002297 const DexFile& dex_file = *dex_cache->GetDexFile();
Ian Rogers0399dde2012-06-06 17:09:28 -07002298 gSingleStepControl.line_number = dex_file.GetLineNumFromPC(m, GetDexPc());
Elliott Hughes2435a572012-02-17 16:07:41 -08002299 }
Elliott Hughes86964332012-02-15 19:37:42 -08002300 }
2301 }
Elliott Hughes530fa002012-03-12 11:44:49 -07002302 return true;
Elliott Hughes86964332012-02-15 19:37:42 -08002303 }
2304 };
jeffhao725a9572012-11-13 18:20:12 -08002305 SingleStepStackVisitor visitor(thread->GetManagedStack(), thread->GetInstrumentationStack());
Ian Rogers0399dde2012-06-06 17:09:28 -07002306 visitor.WalkStack();
Elliott Hughes86964332012-02-15 19:37:42 -08002307
Elliott Hughes2435a572012-02-17 16:07:41 -08002308 //
2309 // Find the dex_pc values that correspond to the current line, for line-based single-stepping.
2310 //
2311
2312 struct DebugCallbackContext {
jeffhao09bfc6a2012-12-11 18:11:43 -08002313 DebugCallbackContext() EXCLUSIVE_LOCKS_REQUIRED(Locks::breakpoint_lock_) {
Elliott Hughes2435a572012-02-17 16:07:41 -08002314 last_pc_valid = false;
2315 last_pc = 0;
Elliott Hughes2435a572012-02-17 16:07:41 -08002316 }
2317
jeffhao09bfc6a2012-12-11 18:11:43 -08002318 // TODO: Enable annotalysis. We know lock is held in constructor, but abstraction confuses
2319 // annotalysis.
2320 static bool Callback(void* raw_context, uint32_t address, uint32_t line_number) NO_THREAD_SAFETY_ANALYSIS {
2321 Locks::breakpoint_lock_->AssertHeld(Thread::Current());
Elliott Hughes2435a572012-02-17 16:07:41 -08002322 DebugCallbackContext* context = reinterpret_cast<DebugCallbackContext*>(raw_context);
2323 if (static_cast<int32_t>(line_number) == gSingleStepControl.line_number) {
2324 if (!context->last_pc_valid) {
2325 // Everything from this address until the next line change is ours.
2326 context->last_pc = address;
2327 context->last_pc_valid = true;
2328 }
2329 // Otherwise, if we're already in a valid range for this line,
2330 // just keep going (shouldn't really happen)...
2331 } else if (context->last_pc_valid) { // and the line number is new
2332 // Add everything from the last entry up until here to the set
2333 for (uint32_t dex_pc = context->last_pc; dex_pc < address; ++dex_pc) {
2334 gSingleStepControl.dex_pcs.insert(dex_pc);
2335 }
2336 context->last_pc_valid = false;
2337 }
2338 return false; // There may be multiple entries for any given line.
2339 }
2340
jeffhao09bfc6a2012-12-11 18:11:43 -08002341 // TODO: Enable annotalysis. We know lock is held in constructor, but abstraction confuses
2342 // annotalysis.
2343 ~DebugCallbackContext() NO_THREAD_SAFETY_ANALYSIS {
2344 Locks::breakpoint_lock_->AssertHeld(Thread::Current());
Elliott Hughes2435a572012-02-17 16:07:41 -08002345 // If the line number was the last in the position table...
2346 if (last_pc_valid) {
2347 size_t end = MethodHelper(gSingleStepControl.method).GetCodeItem()->insns_size_in_code_units_;
2348 for (uint32_t dex_pc = last_pc; dex_pc < end; ++dex_pc) {
2349 gSingleStepControl.dex_pcs.insert(dex_pc);
2350 }
2351 }
2352 }
2353
2354 bool last_pc_valid;
2355 uint32_t last_pc;
2356 };
Elliott Hughes3e2e1a22012-02-21 11:33:41 -08002357 gSingleStepControl.dex_pcs.clear();
Mathieu Chartier66f19252012-09-18 08:57:04 -07002358 const AbstractMethod* m = gSingleStepControl.method;
Elliott Hughes3e2e1a22012-02-21 11:33:41 -08002359 if (m->IsNative()) {
2360 gSingleStepControl.line_number = -1;
2361 } else {
2362 DebugCallbackContext context;
2363 MethodHelper mh(m);
2364 mh.GetDexFile().DecodeDebugInfo(mh.GetCodeItem(), m->IsStatic(), m->GetDexMethodIndex(),
2365 DebugCallbackContext::Callback, NULL, &context);
2366 }
Elliott Hughes2435a572012-02-17 16:07:41 -08002367
2368 //
2369 // Everything else...
2370 //
2371
Elliott Hughes86964332012-02-15 19:37:42 -08002372 gSingleStepControl.thread = thread;
2373 gSingleStepControl.step_size = step_size;
2374 gSingleStepControl.step_depth = step_depth;
2375 gSingleStepControl.is_active = true;
2376
Elliott Hughes2435a572012-02-17 16:07:41 -08002377 if (VLOG_IS_ON(jdwp)) {
2378 VLOG(jdwp) << "Single-step thread: " << *gSingleStepControl.thread;
2379 VLOG(jdwp) << "Single-step step size: " << gSingleStepControl.step_size;
2380 VLOG(jdwp) << "Single-step step depth: " << gSingleStepControl.step_depth;
2381 VLOG(jdwp) << "Single-step current method: " << PrettyMethod(gSingleStepControl.method);
2382 VLOG(jdwp) << "Single-step current line: " << gSingleStepControl.line_number;
2383 VLOG(jdwp) << "Single-step current stack depth: " << gSingleStepControl.stack_depth;
2384 VLOG(jdwp) << "Single-step dex_pc values:";
2385 for (std::set<uint32_t>::iterator it = gSingleStepControl.dex_pcs.begin() ; it != gSingleStepControl.dex_pcs.end(); ++it) {
Elliott Hughes229feb72012-02-23 13:33:29 -08002386 VLOG(jdwp) << StringPrintf(" %#x", *it);
Elliott Hughes2435a572012-02-17 16:07:41 -08002387 }
2388 }
2389
2390 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002391}
2392
Elliott Hughes221229c2013-01-08 18:17:50 -08002393void Dbg::UnconfigureStep(JDWP::ObjectId /*thread_id*/) {
jeffhao09bfc6a2012-12-11 18:11:43 -08002394 MutexLock mu(Thread::Current(), *Locks::breakpoint_lock_);
Elliott Hughesf8349362012-06-18 15:00:06 -07002395
Elliott Hughes86964332012-02-15 19:37:42 -08002396 gSingleStepControl.is_active = false;
2397 gSingleStepControl.thread = NULL;
Elliott Hughes2435a572012-02-17 16:07:41 -08002398 gSingleStepControl.dex_pcs.clear();
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002399}
2400
Elliott Hughes45651fd2012-02-21 15:48:20 -08002401static char JdwpTagToShortyChar(JDWP::JdwpTag tag) {
2402 switch (tag) {
2403 default:
2404 LOG(FATAL) << "unknown JDWP tag: " << PrintableChar(tag);
2405
2406 // Primitives.
2407 case JDWP::JT_BYTE: return 'B';
2408 case JDWP::JT_CHAR: return 'C';
2409 case JDWP::JT_FLOAT: return 'F';
2410 case JDWP::JT_DOUBLE: return 'D';
2411 case JDWP::JT_INT: return 'I';
2412 case JDWP::JT_LONG: return 'J';
2413 case JDWP::JT_SHORT: return 'S';
2414 case JDWP::JT_VOID: return 'V';
2415 case JDWP::JT_BOOLEAN: return 'Z';
2416
2417 // Reference types.
2418 case JDWP::JT_ARRAY:
2419 case JDWP::JT_OBJECT:
2420 case JDWP::JT_STRING:
2421 case JDWP::JT_THREAD:
2422 case JDWP::JT_THREAD_GROUP:
2423 case JDWP::JT_CLASS_LOADER:
2424 case JDWP::JT_CLASS_OBJECT:
2425 return 'L';
2426 }
2427}
2428
Elliott Hughes88d63092013-01-09 09:55:54 -08002429JDWP::JdwpError Dbg::InvokeMethod(JDWP::ObjectId thread_id, JDWP::ObjectId object_id,
2430 JDWP::RefTypeId class_id, JDWP::MethodId method_id,
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002431 uint32_t arg_count, uint64_t* arg_values,
2432 JDWP::JdwpTag* arg_types, uint32_t options,
2433 JDWP::JdwpTag* pResultTag, uint64_t* pResultValue,
2434 JDWP::ObjectId* pExceptionId) {
Elliott Hughesd07986f2011-12-06 18:27:45 -08002435 ThreadList* thread_list = Runtime::Current()->GetThreadList();
2436
2437 Thread* targetThread = NULL;
2438 DebugInvokeReq* req = NULL;
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002439 Thread* self = Thread::Current();
Elliott Hughesd07986f2011-12-06 18:27:45 -08002440 {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002441 ScopedObjectAccessUnchecked soa(self);
Ian Rogers50b35e22012-10-04 10:09:15 -07002442 MutexLock mu(soa.Self(), *Locks::thread_list_lock_);
Elliott Hughes221229c2013-01-08 18:17:50 -08002443 JDWP::JdwpError error = DecodeThread(soa, thread_id, targetThread);
2444 if (error != JDWP::ERR_NONE) {
2445 LOG(ERROR) << "InvokeMethod request for invalid thread id " << thread_id;
2446 return error;
Elliott Hughesd07986f2011-12-06 18:27:45 -08002447 }
2448 req = targetThread->GetInvokeReq();
2449 if (!req->ready) {
2450 LOG(ERROR) << "InvokeMethod request for thread not stopped by event: " << *targetThread;
2451 return JDWP::ERR_INVALID_THREAD;
2452 }
2453
2454 /*
2455 * We currently have a bug where we don't successfully resume the
2456 * target thread if the suspend count is too deep. We're expected to
2457 * require one "resume" for each "suspend", but when asked to execute
2458 * a method we have to resume fully and then re-suspend it back to the
2459 * same level. (The easiest way to cause this is to type "suspend"
2460 * multiple times in jdb.)
2461 *
2462 * It's unclear what this means when the event specifies "resume all"
2463 * and some threads are suspended more deeply than others. This is
2464 * a rare problem, so for now we just prevent it from hanging forever
2465 * by rejecting the method invocation request. Without this, we will
2466 * be stuck waiting on a suspended thread.
2467 */
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002468 int suspend_count;
2469 {
Ian Rogers50b35e22012-10-04 10:09:15 -07002470 MutexLock mu2(soa.Self(), *Locks::thread_suspend_count_lock_);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002471 suspend_count = targetThread->GetSuspendCount();
2472 }
Elliott Hughesd07986f2011-12-06 18:27:45 -08002473 if (suspend_count > 1) {
2474 LOG(ERROR) << *targetThread << " suspend count too deep for method invocation: " << suspend_count;
2475 return JDWP::ERR_THREAD_SUSPENDED; // Probably not expected here.
2476 }
2477
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08002478 JDWP::JdwpError status;
Elliott Hughes88d63092013-01-09 09:55:54 -08002479 Object* receiver = gRegistry->Get<Object*>(object_id);
Elliott Hughes45651fd2012-02-21 15:48:20 -08002480 if (receiver == kInvalidObject) {
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08002481 return JDWP::ERR_INVALID_OBJECT;
2482 }
Elliott Hughes45651fd2012-02-21 15:48:20 -08002483
Elliott Hughes221229c2013-01-08 18:17:50 -08002484 Object* thread = gRegistry->Get<Object*>(thread_id);
Elliott Hughes45651fd2012-02-21 15:48:20 -08002485 if (thread == kInvalidObject) {
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08002486 return JDWP::ERR_INVALID_OBJECT;
2487 }
Elliott Hughes45651fd2012-02-21 15:48:20 -08002488 // TODO: check that 'thread' is actually a java.lang.Thread!
2489
Elliott Hughes88d63092013-01-09 09:55:54 -08002490 Class* c = DecodeClass(class_id, status);
Elliott Hughes45651fd2012-02-21 15:48:20 -08002491 if (c == NULL) {
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08002492 return status;
2493 }
Elliott Hughes45651fd2012-02-21 15:48:20 -08002494
Elliott Hughes88d63092013-01-09 09:55:54 -08002495 AbstractMethod* m = FromMethodId(method_id);
Elliott Hughes45651fd2012-02-21 15:48:20 -08002496 if (m->IsStatic() != (receiver == NULL)) {
2497 return JDWP::ERR_INVALID_METHODID;
2498 }
2499 if (m->IsStatic()) {
2500 if (m->GetDeclaringClass() != c) {
2501 return JDWP::ERR_INVALID_METHODID;
2502 }
2503 } else {
2504 if (!m->GetDeclaringClass()->IsAssignableFrom(c)) {
2505 return JDWP::ERR_INVALID_METHODID;
2506 }
2507 }
2508
2509 // Check the argument list matches the method.
2510 MethodHelper mh(m);
2511 if (mh.GetShortyLength() - 1 != arg_count) {
2512 return JDWP::ERR_ILLEGAL_ARGUMENT;
2513 }
2514 const char* shorty = mh.GetShorty();
2515 for (size_t i = 0; i < arg_count; ++i) {
2516 if (shorty[i + 1] != JdwpTagToShortyChar(arg_types[i])) {
2517 return JDWP::ERR_ILLEGAL_ARGUMENT;
2518 }
2519 }
2520
2521 req->receiver_ = receiver;
2522 req->thread_ = thread;
2523 req->class_ = c;
2524 req->method_ = m;
2525 req->arg_count_ = arg_count;
2526 req->arg_values_ = arg_values;
Elliott Hughesd07986f2011-12-06 18:27:45 -08002527 req->options_ = options;
2528 req->invoke_needed_ = true;
2529 }
2530
2531 // The fact that we've released the thread list lock is a bit risky --- if the thread goes
2532 // away we're sitting high and dry -- but we must release this before the ResumeAllThreads
2533 // call, and it's unwise to hold it during WaitForSuspend.
2534
2535 {
2536 /*
2537 * We change our (JDWP thread) status, which should be THREAD_RUNNING,
Elliott Hughes81ff3182012-03-23 20:35:56 -07002538 * so we can suspend for a GC if the invoke request causes us to
Elliott Hughesd07986f2011-12-06 18:27:45 -08002539 * run out of memory. It's also a good idea to change it before locking
2540 * the invokeReq mutex, although that should never be held for long.
2541 */
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002542 self->TransitionFromRunnableToSuspended(kWaitingForDebuggerSend);
Elliott Hughesd07986f2011-12-06 18:27:45 -08002543
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08002544 VLOG(jdwp) << " Transferring control to event thread";
Elliott Hughesd07986f2011-12-06 18:27:45 -08002545 {
Ian Rogers50b35e22012-10-04 10:09:15 -07002546 MutexLock mu(self, req->lock_);
Elliott Hughesd07986f2011-12-06 18:27:45 -08002547
2548 if ((options & JDWP::INVOKE_SINGLE_THREADED) == 0) {
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08002549 VLOG(jdwp) << " Resuming all threads";
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002550 thread_list->UndoDebuggerSuspensions();
Elliott Hughesd07986f2011-12-06 18:27:45 -08002551 } else {
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08002552 VLOG(jdwp) << " Resuming event thread only";
Elliott Hughesd07986f2011-12-06 18:27:45 -08002553 thread_list->Resume(targetThread, true);
2554 }
2555
2556 // Wait for the request to finish executing.
2557 while (req->invoke_needed_) {
Ian Rogersc604d732012-10-14 16:09:54 -07002558 req->cond_.Wait(self);
Elliott Hughesd07986f2011-12-06 18:27:45 -08002559 }
2560 }
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08002561 VLOG(jdwp) << " Control has returned from event thread";
Elliott Hughesd07986f2011-12-06 18:27:45 -08002562
2563 /* wait for thread to re-suspend itself */
Elliott Hughes221229c2013-01-08 18:17:50 -08002564 SuspendThread(thread_id, false /* request_suspension */ );
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002565 self->TransitionFromSuspendedToRunnable();
Elliott Hughesd07986f2011-12-06 18:27:45 -08002566 }
2567
2568 /*
2569 * Suspend the threads. We waited for the target thread to suspend
2570 * itself, so all we need to do is suspend the others.
2571 *
2572 * The suspendAllThreads() call will double-suspend the event thread,
2573 * so we want to resume the target thread once to keep the books straight.
2574 */
2575 if ((options & JDWP::INVOKE_SINGLE_THREADED) == 0) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002576 self->TransitionFromRunnableToSuspended(kWaitingForDebuggerSuspension);
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08002577 VLOG(jdwp) << " Suspending all threads";
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002578 thread_list->SuspendAllForDebugger();
2579 self->TransitionFromSuspendedToRunnable();
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08002580 VLOG(jdwp) << " Resuming event thread to balance the count";
Elliott Hughesd07986f2011-12-06 18:27:45 -08002581 thread_list->Resume(targetThread, true);
2582 }
2583
2584 // Copy the result.
2585 *pResultTag = req->result_tag;
2586 if (IsPrimitiveTag(req->result_tag)) {
Elliott Hughesf24d3ce2012-04-11 17:43:37 -07002587 *pResultValue = req->result_value.GetJ();
Elliott Hughesd07986f2011-12-06 18:27:45 -08002588 } else {
Elliott Hughesf24d3ce2012-04-11 17:43:37 -07002589 *pResultValue = gRegistry->Add(req->result_value.GetL());
Elliott Hughesd07986f2011-12-06 18:27:45 -08002590 }
2591 *pExceptionId = req->exception;
2592 return req->error;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002593}
2594
2595void Dbg::ExecuteMethod(DebugInvokeReq* pReq) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002596 ScopedObjectAccess soa(Thread::Current());
Elliott Hughesd07986f2011-12-06 18:27:45 -08002597
Elliott Hughes81ff3182012-03-23 20:35:56 -07002598 // We can be called while an exception is pending. We need
Elliott Hughesd07986f2011-12-06 18:27:45 -08002599 // to preserve that across the method invocation.
Ian Rogers1f539342012-10-03 21:09:42 -07002600 SirtRef<Throwable> old_exception(soa.Self(), soa.Self()->GetException());
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002601 soa.Self()->ClearException();
Elliott Hughesd07986f2011-12-06 18:27:45 -08002602
2603 // Translate the method through the vtable, unless the debugger wants to suppress it.
Mathieu Chartier66f19252012-09-18 08:57:04 -07002604 AbstractMethod* m = pReq->method_;
Elliott Hughesd07986f2011-12-06 18:27:45 -08002605 if ((pReq->options_ & JDWP::INVOKE_NONVIRTUAL) == 0 && pReq->receiver_ != NULL) {
Mathieu Chartier66f19252012-09-18 08:57:04 -07002606 AbstractMethod* actual_method = pReq->class_->FindVirtualMethodForVirtualOrInterface(pReq->method_);
Elliott Hughes45651fd2012-02-21 15:48:20 -08002607 if (actual_method != m) {
2608 VLOG(jdwp) << "ExecuteMethod translated " << PrettyMethod(m) << " to " << PrettyMethod(actual_method);
2609 m = actual_method;
2610 }
Elliott Hughesd07986f2011-12-06 18:27:45 -08002611 }
Elliott Hughes45651fd2012-02-21 15:48:20 -08002612 VLOG(jdwp) << "ExecuteMethod " << PrettyMethod(m);
Elliott Hughesd07986f2011-12-06 18:27:45 -08002613 CHECK(m != NULL);
2614
2615 CHECK_EQ(sizeof(jvalue), sizeof(uint64_t));
2616
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002617 LOG(INFO) << "self=" << soa.Self() << " pReq->receiver_=" << pReq->receiver_ << " m=" << m
2618 << " #" << pReq->arg_count_ << " " << pReq->arg_values_;
2619 pReq->result_value = InvokeWithJValues(soa, pReq->receiver_, m,
2620 reinterpret_cast<JValue*>(pReq->arg_values_));
Elliott Hughesd07986f2011-12-06 18:27:45 -08002621
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002622 pReq->exception = gRegistry->Add(soa.Self()->GetException());
Elliott Hughesd07986f2011-12-06 18:27:45 -08002623 pReq->result_tag = BasicTagFromDescriptor(MethodHelper(m).GetShorty());
2624 if (pReq->exception != 0) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002625 Object* exc = soa.Self()->GetException();
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08002626 VLOG(jdwp) << " JDWP invocation returning with exception=" << exc << " " << PrettyTypeOf(exc);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002627 soa.Self()->ClearException();
Elliott Hughesf24d3ce2012-04-11 17:43:37 -07002628 pReq->result_value.SetJ(0);
Elliott Hughesd07986f2011-12-06 18:27:45 -08002629 } else if (pReq->result_tag == JDWP::JT_OBJECT) {
2630 /* if no exception thrown, examine object result more closely */
Elliott Hughesf24d3ce2012-04-11 17:43:37 -07002631 JDWP::JdwpTag new_tag = TagFromObject(pReq->result_value.GetL());
Elliott Hughesd07986f2011-12-06 18:27:45 -08002632 if (new_tag != pReq->result_tag) {
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08002633 VLOG(jdwp) << " JDWP promoted result from " << pReq->result_tag << " to " << new_tag;
Elliott Hughesd07986f2011-12-06 18:27:45 -08002634 pReq->result_tag = new_tag;
2635 }
2636
2637 /*
2638 * Register the object. We don't actually need an ObjectId yet,
2639 * but we do need to be sure that the GC won't move or discard the
2640 * object when we switch out of RUNNING. The ObjectId conversion
2641 * will add the object to the "do not touch" list.
2642 *
2643 * We can't use the "tracked allocation" mechanism here because
2644 * the object is going to be handed off to a different thread.
2645 */
Elliott Hughesf24d3ce2012-04-11 17:43:37 -07002646 gRegistry->Add(pReq->result_value.GetL());
Elliott Hughesd07986f2011-12-06 18:27:45 -08002647 }
2648
2649 if (old_exception.get() != NULL) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002650 soa.Self()->SetException(old_exception.get());
Elliott Hughesd07986f2011-12-06 18:27:45 -08002651 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002652}
2653
Elliott Hughesd07986f2011-12-06 18:27:45 -08002654/*
2655 * Register an object ID that might not have been registered previously.
2656 *
2657 * Normally this wouldn't happen -- the conversion to an ObjectId would
2658 * have added the object to the registry -- but in some cases (e.g.
2659 * throwing exceptions) we really want to do the registration late.
2660 */
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002661void Dbg::RegisterObjectId(JDWP::ObjectId id) {
Elliott Hughesd07986f2011-12-06 18:27:45 -08002662 gRegistry->Add(reinterpret_cast<Object*>(id));
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002663}
2664
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07002665/*
2666 * "buf" contains a full JDWP packet, possibly with multiple chunks. We
2667 * need to process each, accumulate the replies, and ship the whole thing
2668 * back.
2669 *
2670 * Returns "true" if we have a reply. The reply buffer is newly allocated,
2671 * and includes the chunk type/length, followed by the data.
2672 *
Elliott Hughes3d30d9b2011-12-07 17:35:48 -08002673 * OLD-TODO: we currently assume that the request and reply include a single
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07002674 * chunk. If this becomes inconvenient we will need to adapt.
2675 */
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002676bool Dbg::DdmHandlePacket(const uint8_t* buf, int dataLen, uint8_t** pReplyBuf, int* pReplyLen) {
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07002677 CHECK_GE(dataLen, 0);
2678
2679 Thread* self = Thread::Current();
2680 JNIEnv* env = self->GetJniEnv();
2681
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07002682 // Create a byte[] corresponding to 'buf'.
Elliott Hughes6a5bd492011-10-28 14:33:57 -07002683 ScopedLocalRef<jbyteArray> dataArray(env, env->NewByteArray(dataLen));
2684 if (dataArray.get() == NULL) {
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07002685 LOG(WARNING) << "byte[] allocation failed: " << dataLen;
2686 env->ExceptionClear();
2687 return false;
2688 }
Elliott Hughes6a5bd492011-10-28 14:33:57 -07002689 env->SetByteArrayRegion(dataArray.get(), 0, dataLen, reinterpret_cast<const jbyte*>(buf));
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07002690
2691 const int kChunkHdrLen = 8;
2692
2693 // Run through and find all chunks. [Currently just find the first.]
Elliott Hughes6a5bd492011-10-28 14:33:57 -07002694 ScopedByteArrayRO contents(env, dataArray.get());
Elliott Hughesf7c3b662011-10-27 12:04:56 -07002695 jint type = JDWP::Get4BE(reinterpret_cast<const uint8_t*>(&contents[0]));
2696 jint length = JDWP::Get4BE(reinterpret_cast<const uint8_t*>(&contents[4]));
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07002697 jint offset = kChunkHdrLen;
2698 if (offset + length > dataLen) {
2699 LOG(WARNING) << StringPrintf("bad chunk found (len=%u pktLen=%d)", length, dataLen);
2700 return false;
2701 }
2702
2703 // Call "private static Chunk dispatch(int type, byte[] data, int offset, int length)".
Elliott Hugheseac76672012-05-24 21:56:51 -07002704 ScopedLocalRef<jobject> chunk(env, env->CallStaticObjectMethod(WellKnownClasses::org_apache_harmony_dalvik_ddmc_DdmServer,
2705 WellKnownClasses::org_apache_harmony_dalvik_ddmc_DdmServer_dispatch,
2706 type, dataArray.get(), offset, length));
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07002707 if (env->ExceptionCheck()) {
2708 LOG(INFO) << StringPrintf("Exception thrown by dispatcher for 0x%08x", type);
2709 env->ExceptionDescribe();
2710 env->ExceptionClear();
2711 return false;
2712 }
2713
Elliott Hughes6a5bd492011-10-28 14:33:57 -07002714 if (chunk.get() == NULL) {
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07002715 return false;
2716 }
2717
2718 /*
2719 * Pull the pieces out of the chunk. We copy the results into a
2720 * newly-allocated buffer that the caller can free. We don't want to
2721 * continue using the Chunk object because nothing has a reference to it.
2722 *
2723 * We could avoid this by returning type/data/offset/length and having
2724 * the caller be aware of the object lifetime issues, but that
Elliott Hughes81ff3182012-03-23 20:35:56 -07002725 * integrates the JDWP code more tightly into the rest of the runtime, and doesn't work
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07002726 * if we have responses for multiple chunks.
2727 *
2728 * So we're pretty much stuck with copying data around multiple times.
2729 */
Elliott Hugheseac76672012-05-24 21:56:51 -07002730 ScopedLocalRef<jbyteArray> replyData(env, reinterpret_cast<jbyteArray>(env->GetObjectField(chunk.get(), WellKnownClasses::org_apache_harmony_dalvik_ddmc_Chunk_data)));
2731 length = env->GetIntField(chunk.get(), WellKnownClasses::org_apache_harmony_dalvik_ddmc_Chunk_length);
2732 offset = env->GetIntField(chunk.get(), WellKnownClasses::org_apache_harmony_dalvik_ddmc_Chunk_offset);
2733 type = env->GetIntField(chunk.get(), WellKnownClasses::org_apache_harmony_dalvik_ddmc_Chunk_type);
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07002734
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08002735 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 -07002736 if (length == 0 || replyData.get() == NULL) {
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07002737 return false;
2738 }
2739
Elliott Hughes6a5bd492011-10-28 14:33:57 -07002740 jsize replyLength = env->GetArrayLength(replyData.get());
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07002741 if (offset + length > replyLength) {
2742 LOG(WARNING) << StringPrintf("chunk off=%d len=%d exceeds reply array len %d", offset, length, replyLength);
2743 return false;
2744 }
2745
2746 uint8_t* reply = new uint8_t[length + kChunkHdrLen];
2747 if (reply == NULL) {
2748 LOG(WARNING) << "malloc failed: " << (length + kChunkHdrLen);
2749 return false;
2750 }
Elliott Hughesf7c3b662011-10-27 12:04:56 -07002751 JDWP::Set4BE(reply + 0, type);
2752 JDWP::Set4BE(reply + 4, length);
Elliott Hughes6a5bd492011-10-28 14:33:57 -07002753 env->GetByteArrayRegion(replyData.get(), offset, length, reinterpret_cast<jbyte*>(reply + kChunkHdrLen));
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07002754
2755 *pReplyBuf = reply;
2756 *pReplyLen = length + kChunkHdrLen;
2757
Elliott Hughesba8eee12012-01-24 20:25:24 -08002758 VLOG(jdwp) << StringPrintf("dvmHandleDdm returning type=%.4s buf=%p len=%d", reinterpret_cast<char*>(reply), reply, length);
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07002759 return true;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002760}
2761
Elliott Hughesa2155262011-11-16 16:26:58 -08002762void Dbg::DdmBroadcast(bool connect) {
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08002763 VLOG(jdwp) << "Broadcasting DDM " << (connect ? "connect" : "disconnect") << "...";
Elliott Hughes47fce012011-10-25 18:37:19 -07002764
2765 Thread* self = Thread::Current();
Ian Rogers50b35e22012-10-04 10:09:15 -07002766 if (self->GetState() != kRunnable) {
2767 LOG(ERROR) << "DDM broadcast in thread state " << self->GetState();
2768 /* try anyway? */
Elliott Hughes47fce012011-10-25 18:37:19 -07002769 }
2770
2771 JNIEnv* env = self->GetJniEnv();
Elliott Hughes47fce012011-10-25 18:37:19 -07002772 jint event = connect ? 1 /*DdmServer.CONNECTED*/ : 2 /*DdmServer.DISCONNECTED*/;
Elliott Hugheseac76672012-05-24 21:56:51 -07002773 env->CallStaticVoidMethod(WellKnownClasses::org_apache_harmony_dalvik_ddmc_DdmServer,
2774 WellKnownClasses::org_apache_harmony_dalvik_ddmc_DdmServer_broadcast,
2775 event);
Elliott Hughes47fce012011-10-25 18:37:19 -07002776 if (env->ExceptionCheck()) {
2777 LOG(ERROR) << "DdmServer.broadcast " << event << " failed";
2778 env->ExceptionDescribe();
2779 env->ExceptionClear();
2780 }
2781}
2782
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002783void Dbg::DdmConnected() {
Elliott Hughesa2155262011-11-16 16:26:58 -08002784 Dbg::DdmBroadcast(true);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002785}
2786
2787void Dbg::DdmDisconnected() {
Elliott Hughesa2155262011-11-16 16:26:58 -08002788 Dbg::DdmBroadcast(false);
Elliott Hughes47fce012011-10-25 18:37:19 -07002789 gDdmThreadNotification = false;
2790}
2791
2792/*
Elliott Hughes82188472011-11-07 18:11:48 -08002793 * Send a notification when a thread starts, stops, or changes its name.
Elliott Hughes47fce012011-10-25 18:37:19 -07002794 *
2795 * Because we broadcast the full set of threads when the notifications are
2796 * first enabled, it's possible for "thread" to be actively executing.
2797 */
Elliott Hughes82188472011-11-07 18:11:48 -08002798void Dbg::DdmSendThreadNotification(Thread* t, uint32_t type) {
Elliott Hughes47fce012011-10-25 18:37:19 -07002799 if (!gDdmThreadNotification) {
2800 return;
2801 }
2802
Elliott Hughes82188472011-11-07 18:11:48 -08002803 if (type == CHUNK_TYPE("THDE")) {
Elliott Hughes47fce012011-10-25 18:37:19 -07002804 uint8_t buf[4];
Elliott Hughesf7c3b662011-10-27 12:04:56 -07002805 JDWP::Set4BE(&buf[0], t->GetThinLockId());
Elliott Hughes47fce012011-10-25 18:37:19 -07002806 Dbg::DdmSendChunk(CHUNK_TYPE("THDE"), 4, buf);
Elliott Hughes82188472011-11-07 18:11:48 -08002807 } else {
2808 CHECK(type == CHUNK_TYPE("THCR") || type == CHUNK_TYPE("THNM")) << type;
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002809 ScopedObjectAccessUnchecked soa(Thread::Current());
Ian Rogers1f539342012-10-03 21:09:42 -07002810 SirtRef<String> name(soa.Self(), t->GetThreadName(soa));
Elliott Hughes82188472011-11-07 18:11:48 -08002811 size_t char_count = (name.get() != NULL) ? name->GetLength() : 0;
jeffhao725a9572012-11-13 18:20:12 -08002812 const jchar* chars = (name.get() != NULL) ? name->GetCharArray()->GetData() : NULL;
Elliott Hughes82188472011-11-07 18:11:48 -08002813
Elliott Hughes21f32d72011-11-09 17:44:13 -08002814 std::vector<uint8_t> bytes;
Elliott Hughes545a0642011-11-08 19:10:03 -08002815 JDWP::Append4BE(bytes, t->GetThinLockId());
2816 JDWP::AppendUtf16BE(bytes, chars, char_count);
Elliott Hughes21f32d72011-11-09 17:44:13 -08002817 CHECK_EQ(bytes.size(), char_count*2 + sizeof(uint32_t)*2);
2818 Dbg::DdmSendChunk(type, bytes);
Elliott Hughes47fce012011-10-25 18:37:19 -07002819 }
2820}
2821
Elliott Hughes47fce012011-10-25 18:37:19 -07002822void Dbg::DdmSetThreadNotification(bool enable) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002823 // Enable/disable thread notifications.
Elliott Hughes47fce012011-10-25 18:37:19 -07002824 gDdmThreadNotification = enable;
2825 if (enable) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002826 // Suspend the VM then post thread start notifications for all threads. Threads attaching will
2827 // see a suspension in progress and block until that ends. They then post their own start
2828 // notification.
2829 SuspendVM();
2830 std::list<Thread*> threads;
Ian Rogers50b35e22012-10-04 10:09:15 -07002831 Thread* self = Thread::Current();
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002832 {
Ian Rogers50b35e22012-10-04 10:09:15 -07002833 MutexLock mu(self, *Locks::thread_list_lock_);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002834 threads = Runtime::Current()->GetThreadList()->GetList();
2835 }
2836 {
Ian Rogers50b35e22012-10-04 10:09:15 -07002837 ScopedObjectAccess soa(self);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002838 typedef std::list<Thread*>::const_iterator It; // TODO: C++0x auto
2839 for (It it = threads.begin(), end = threads.end(); it != end; ++it) {
2840 Dbg::DdmSendThreadNotification(*it, CHUNK_TYPE("THCR"));
2841 }
2842 }
2843 ResumeVM();
Elliott Hughes47fce012011-10-25 18:37:19 -07002844 }
2845}
2846
Elliott Hughesa2155262011-11-16 16:26:58 -08002847void Dbg::PostThreadStartOrStop(Thread* t, uint32_t type) {
Elliott Hughesc0f09332012-03-26 13:27:06 -07002848 if (IsDebuggerActive()) {
Mathieu Chartierdbe6f462012-09-25 16:54:50 -07002849 ScopedObjectAccessUnchecked soa(Thread::Current());
Ian Rogerscfaa4552012-11-26 21:00:08 -08002850 JDWP::ObjectId id = gRegistry->Add(t->GetPeer());
Elliott Hughes82188472011-11-07 18:11:48 -08002851 gJdwpState->PostThreadChange(id, type == CHUNK_TYPE("THCR"));
Elliott Hughesc0f09332012-03-26 13:27:06 -07002852 // If this thread's just joined the party while we're already debugging, make sure it knows
2853 // to give us updates when it's running.
2854 t->SetDebuggerUpdatesEnabled(true);
Elliott Hughes47fce012011-10-25 18:37:19 -07002855 }
Elliott Hughes82188472011-11-07 18:11:48 -08002856 Dbg::DdmSendThreadNotification(t, type);
Elliott Hughes47fce012011-10-25 18:37:19 -07002857}
2858
2859void Dbg::PostThreadStart(Thread* t) {
Elliott Hughesa2155262011-11-16 16:26:58 -08002860 Dbg::PostThreadStartOrStop(t, CHUNK_TYPE("THCR"));
Elliott Hughes47fce012011-10-25 18:37:19 -07002861}
2862
2863void Dbg::PostThreadDeath(Thread* t) {
Elliott Hughesa2155262011-11-16 16:26:58 -08002864 Dbg::PostThreadStartOrStop(t, CHUNK_TYPE("THDE"));
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002865}
2866
Elliott Hughes82188472011-11-07 18:11:48 -08002867void Dbg::DdmSendChunk(uint32_t type, size_t byte_count, const uint8_t* buf) {
Elliott Hughes3bb81562011-10-21 18:52:59 -07002868 CHECK(buf != NULL);
2869 iovec vec[1];
2870 vec[0].iov_base = reinterpret_cast<void*>(const_cast<uint8_t*>(buf));
2871 vec[0].iov_len = byte_count;
2872 Dbg::DdmSendChunkV(type, vec, 1);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002873}
2874
Elliott Hughes21f32d72011-11-09 17:44:13 -08002875void Dbg::DdmSendChunk(uint32_t type, const std::vector<uint8_t>& bytes) {
2876 DdmSendChunk(type, bytes.size(), &bytes[0]);
2877}
2878
Elliott Hughescccd84f2011-12-05 16:51:54 -08002879void Dbg::DdmSendChunkV(uint32_t type, const struct iovec* iov, int iov_count) {
Elliott Hughes3bb81562011-10-21 18:52:59 -07002880 if (gJdwpState == NULL) {
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08002881 VLOG(jdwp) << "Debugger thread not active, ignoring DDM send: " << type;
Elliott Hughes3bb81562011-10-21 18:52:59 -07002882 } else {
Elliott Hughescccd84f2011-12-05 16:51:54 -08002883 gJdwpState->DdmSendChunkV(type, iov, iov_count);
Elliott Hughes3bb81562011-10-21 18:52:59 -07002884 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002885}
2886
Elliott Hughes767a1472011-10-26 18:49:02 -07002887int Dbg::DdmHandleHpifChunk(HpifWhen when) {
2888 if (when == HPIF_WHEN_NOW) {
Elliott Hughes7162ad92011-10-27 14:08:42 -07002889 DdmSendHeapInfo(when);
Elliott Hughes767a1472011-10-26 18:49:02 -07002890 return true;
2891 }
2892
2893 if (when != HPIF_WHEN_NEVER && when != HPIF_WHEN_NEXT_GC && when != HPIF_WHEN_EVERY_GC) {
2894 LOG(ERROR) << "invalid HpifWhen value: " << static_cast<int>(when);
2895 return false;
2896 }
2897
2898 gDdmHpifWhen = when;
2899 return true;
2900}
2901
2902bool Dbg::DdmHandleHpsgNhsgChunk(Dbg::HpsgWhen when, Dbg::HpsgWhat what, bool native) {
2903 if (when != HPSG_WHEN_NEVER && when != HPSG_WHEN_EVERY_GC) {
2904 LOG(ERROR) << "invalid HpsgWhen value: " << static_cast<int>(when);
2905 return false;
2906 }
2907
2908 if (what != HPSG_WHAT_MERGED_OBJECTS && what != HPSG_WHAT_DISTINCT_OBJECTS) {
2909 LOG(ERROR) << "invalid HpsgWhat value: " << static_cast<int>(what);
2910 return false;
2911 }
2912
2913 if (native) {
2914 gDdmNhsgWhen = when;
2915 gDdmNhsgWhat = what;
2916 } else {
2917 gDdmHpsgWhen = when;
2918 gDdmHpsgWhat = what;
2919 }
2920 return true;
2921}
2922
Elliott Hughes7162ad92011-10-27 14:08:42 -07002923void Dbg::DdmSendHeapInfo(HpifWhen reason) {
2924 // If there's a one-shot 'when', reset it.
2925 if (reason == gDdmHpifWhen) {
2926 if (gDdmHpifWhen == HPIF_WHEN_NEXT_GC) {
2927 gDdmHpifWhen = HPIF_WHEN_NEVER;
2928 }
2929 }
2930
2931 /*
2932 * Chunk HPIF (client --> server)
2933 *
2934 * Heap Info. General information about the heap,
2935 * suitable for a summary display.
2936 *
2937 * [u4]: number of heaps
2938 *
2939 * For each heap:
2940 * [u4]: heap ID
2941 * [u8]: timestamp in ms since Unix epoch
2942 * [u1]: capture reason (same as 'when' value from server)
2943 * [u4]: max heap size in bytes (-Xmx)
2944 * [u4]: current heap size in bytes
2945 * [u4]: current number of bytes allocated
2946 * [u4]: current number of objects allocated
2947 */
2948 uint8_t heap_count = 1;
Elliott Hughesb3bd5f02012-03-08 21:05:27 -08002949 Heap* heap = Runtime::Current()->GetHeap();
Elliott Hughes21f32d72011-11-09 17:44:13 -08002950 std::vector<uint8_t> bytes;
Elliott Hughes545a0642011-11-08 19:10:03 -08002951 JDWP::Append4BE(bytes, heap_count);
2952 JDWP::Append4BE(bytes, 1); // Heap id (bogus; we only have one heap).
2953 JDWP::Append8BE(bytes, MilliTime());
2954 JDWP::Append1BE(bytes, reason);
Elliott Hughesb3bd5f02012-03-08 21:05:27 -08002955 JDWP::Append4BE(bytes, heap->GetMaxMemory()); // Max allowed heap size in bytes.
2956 JDWP::Append4BE(bytes, heap->GetTotalMemory()); // Current heap size in bytes.
2957 JDWP::Append4BE(bytes, heap->GetBytesAllocated());
2958 JDWP::Append4BE(bytes, heap->GetObjectsAllocated());
Elliott Hughes21f32d72011-11-09 17:44:13 -08002959 CHECK_EQ(bytes.size(), 4U + (heap_count * (4 + 8 + 1 + 4 + 4 + 4 + 4)));
2960 Dbg::DdmSendChunk(CHUNK_TYPE("HPIF"), bytes);
Elliott Hughes767a1472011-10-26 18:49:02 -07002961}
2962
Elliott Hughes6a5bd492011-10-28 14:33:57 -07002963enum HpsgSolidity {
2964 SOLIDITY_FREE = 0,
2965 SOLIDITY_HARD = 1,
2966 SOLIDITY_SOFT = 2,
2967 SOLIDITY_WEAK = 3,
2968 SOLIDITY_PHANTOM = 4,
2969 SOLIDITY_FINALIZABLE = 5,
2970 SOLIDITY_SWEEP = 6,
2971};
2972
2973enum HpsgKind {
2974 KIND_OBJECT = 0,
2975 KIND_CLASS_OBJECT = 1,
2976 KIND_ARRAY_1 = 2,
2977 KIND_ARRAY_2 = 3,
2978 KIND_ARRAY_4 = 4,
2979 KIND_ARRAY_8 = 5,
2980 KIND_UNKNOWN = 6,
2981 KIND_NATIVE = 7,
2982};
2983
2984#define HPSG_PARTIAL (1<<7)
2985#define HPSG_STATE(solidity, kind) ((uint8_t)((((kind) & 0x7) << 3) | ((solidity) & 0x7)))
2986
Ian Rogers30fab402012-01-23 15:43:46 -08002987class HeapChunkContext {
2988 public:
Elliott Hughes6a5bd492011-10-28 14:33:57 -07002989 // Maximum chunk size. Obtain this from the formula:
2990 // (((maximum_heap_size / ALLOCATION_UNIT_SIZE) + 255) / 256) * 2
2991 HeapChunkContext(bool merge, bool native)
Ian Rogers30fab402012-01-23 15:43:46 -08002992 : buf_(16384 - 16),
2993 type_(0),
2994 merge_(merge) {
Elliott Hughes6a5bd492011-10-28 14:33:57 -07002995 Reset();
2996 if (native) {
Ian Rogers30fab402012-01-23 15:43:46 -08002997 type_ = CHUNK_TYPE("NHSG");
Elliott Hughes6a5bd492011-10-28 14:33:57 -07002998 } else {
Ian Rogers30fab402012-01-23 15:43:46 -08002999 type_ = merge ? CHUNK_TYPE("HPSG") : CHUNK_TYPE("HPSO");
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003000 }
3001 }
3002
3003 ~HeapChunkContext() {
Ian Rogers30fab402012-01-23 15:43:46 -08003004 if (p_ > &buf_[0]) {
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003005 Flush();
3006 }
3007 }
3008
3009 void EnsureHeader(const void* chunk_ptr) {
Ian Rogers30fab402012-01-23 15:43:46 -08003010 if (!needHeader_) {
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003011 return;
3012 }
3013
3014 // Start a new HPSx chunk.
Ian Rogers30fab402012-01-23 15:43:46 -08003015 JDWP::Write4BE(&p_, 1); // Heap id (bogus; we only have one heap).
3016 JDWP::Write1BE(&p_, 8); // Size of allocation unit, in bytes.
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003017
Ian Rogers30fab402012-01-23 15:43:46 -08003018 JDWP::Write4BE(&p_, reinterpret_cast<uintptr_t>(chunk_ptr)); // virtual address of segment start.
3019 JDWP::Write4BE(&p_, 0); // offset of this piece (relative to the virtual address).
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003020 // [u4]: length of piece, in allocation units
3021 // 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 -08003022 pieceLenField_ = p_;
3023 JDWP::Write4BE(&p_, 0x55555555);
3024 needHeader_ = false;
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003025 }
3026
Ian Rogersb726dcb2012-09-05 08:57:23 -07003027 void Flush() SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003028 // Patch the "length of piece" field.
Ian Rogers30fab402012-01-23 15:43:46 -08003029 CHECK_LE(&buf_[0], pieceLenField_);
3030 CHECK_LE(pieceLenField_, p_);
3031 JDWP::Set4BE(pieceLenField_, totalAllocationUnits_);
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003032
Ian Rogers30fab402012-01-23 15:43:46 -08003033 Dbg::DdmSendChunk(type_, p_ - &buf_[0], &buf_[0]);
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003034 Reset();
3035 }
3036
Ian Rogers00f7d0e2012-07-19 15:28:27 -07003037 static void HeapChunkCallback(void* start, void* end, size_t used_bytes, void* arg)
Ian Rogersb726dcb2012-09-05 08:57:23 -07003038 SHARED_LOCKS_REQUIRED(Locks::heap_bitmap_lock_,
3039 Locks::mutator_lock_) {
Ian Rogers30fab402012-01-23 15:43:46 -08003040 reinterpret_cast<HeapChunkContext*>(arg)->HeapChunkCallback(start, end, used_bytes);
Elliott Hughesa2155262011-11-16 16:26:58 -08003041 }
3042
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003043 private:
Elliott Hughesa2155262011-11-16 16:26:58 -08003044 enum { ALLOCATION_UNIT_SIZE = 8 };
3045
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003046 void Reset() {
Ian Rogers30fab402012-01-23 15:43:46 -08003047 p_ = &buf_[0];
Ian Rogers15bf2d32012-08-28 17:33:04 -07003048 startOfNextMemoryChunk_ = NULL;
Ian Rogers30fab402012-01-23 15:43:46 -08003049 totalAllocationUnits_ = 0;
3050 needHeader_ = true;
3051 pieceLenField_ = NULL;
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003052 }
3053
Ian Rogers00f7d0e2012-07-19 15:28:27 -07003054 void HeapChunkCallback(void* start, void* /*end*/, size_t used_bytes)
Ian Rogersb726dcb2012-09-05 08:57:23 -07003055 SHARED_LOCKS_REQUIRED(Locks::heap_bitmap_lock_,
3056 Locks::mutator_lock_) {
Ian Rogers30fab402012-01-23 15:43:46 -08003057 // Note: heap call backs cannot manipulate the heap upon which they are crawling, care is taken
3058 // in the following code not to allocate memory, by ensuring buf_ is of the correct size
Ian Rogers15bf2d32012-08-28 17:33:04 -07003059 if (used_bytes == 0) {
3060 if (start == NULL) {
3061 // Reset for start of new heap.
3062 startOfNextMemoryChunk_ = NULL;
3063 Flush();
3064 }
3065 // Only process in use memory so that free region information
3066 // also includes dlmalloc book keeping.
Elliott Hughesa2155262011-11-16 16:26:58 -08003067 return;
Elliott Hughesa2155262011-11-16 16:26:58 -08003068 }
3069
Ian Rogers15bf2d32012-08-28 17:33:04 -07003070 /* If we're looking at the native heap, we'll just return
3071 * (SOLIDITY_HARD, KIND_NATIVE) for all allocated chunks
3072 */
3073 bool native = type_ == CHUNK_TYPE("NHSG");
3074
3075 if (startOfNextMemoryChunk_ != NULL) {
3076 // Transmit any pending free memory. Native free memory of
3077 // over kMaxFreeLen could be because of the use of mmaps, so
3078 // don't report. If not free memory then start a new segment.
3079 bool flush = true;
3080 if (start > startOfNextMemoryChunk_) {
3081 const size_t kMaxFreeLen = 2 * kPageSize;
3082 void* freeStart = startOfNextMemoryChunk_;
3083 void* freeEnd = start;
3084 size_t freeLen = (char*)freeEnd - (char*)freeStart;
3085 if (!native || freeLen < kMaxFreeLen) {
3086 AppendChunk(HPSG_STATE(SOLIDITY_FREE, 0), freeStart, freeLen);
3087 flush = false;
3088 }
3089 }
3090 if (flush) {
3091 startOfNextMemoryChunk_ = NULL;
3092 Flush();
3093 }
3094 }
3095 const Object *obj = (const Object *)start;
Elliott Hughesa2155262011-11-16 16:26:58 -08003096
3097 // Determine the type of this chunk.
3098 // OLD-TODO: if context.merge, see if this chunk is different from the last chunk.
3099 // If it's the same, we should combine them.
Ian Rogers15bf2d32012-08-28 17:33:04 -07003100 uint8_t state = ExamineObject(obj, native);
3101 // dlmalloc's chunk header is 2 * sizeof(size_t), but if the previous chunk is in use for an
3102 // allocation then the first sizeof(size_t) may belong to it.
3103 const size_t dlMallocOverhead = sizeof(size_t);
3104 AppendChunk(state, start, used_bytes + dlMallocOverhead);
3105 startOfNextMemoryChunk_ = (char*)start + used_bytes + dlMallocOverhead;
3106 }
Elliott Hughesa2155262011-11-16 16:26:58 -08003107
Ian Rogers15bf2d32012-08-28 17:33:04 -07003108 void AppendChunk(uint8_t state, void* ptr, size_t length)
Ian Rogersb726dcb2012-09-05 08:57:23 -07003109 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Ian Rogers15bf2d32012-08-28 17:33:04 -07003110 // Make sure there's enough room left in the buffer.
3111 // We need to use two bytes for every fractional 256 allocation units used by the chunk plus
3112 // 17 bytes for any header.
3113 size_t needed = (((length/ALLOCATION_UNIT_SIZE + 255) / 256) * 2) + 17;
3114 size_t bytesLeft = buf_.size() - (size_t)(p_ - &buf_[0]);
3115 if (bytesLeft < needed) {
3116 Flush();
3117 }
3118
3119 bytesLeft = buf_.size() - (size_t)(p_ - &buf_[0]);
3120 if (bytesLeft < needed) {
3121 LOG(WARNING) << "Chunk is too big to transmit (chunk_len=" << length << ", "
3122 << needed << " bytes)";
3123 return;
3124 }
3125 EnsureHeader(ptr);
Elliott Hughesa2155262011-11-16 16:26:58 -08003126 // Write out the chunk description.
Ian Rogers15bf2d32012-08-28 17:33:04 -07003127 length /= ALLOCATION_UNIT_SIZE; // Convert to allocation units.
3128 totalAllocationUnits_ += length;
3129 while (length > 256) {
Ian Rogers30fab402012-01-23 15:43:46 -08003130 *p_++ = state | HPSG_PARTIAL;
3131 *p_++ = 255; // length - 1
Ian Rogers15bf2d32012-08-28 17:33:04 -07003132 length -= 256;
Elliott Hughesa2155262011-11-16 16:26:58 -08003133 }
Ian Rogers30fab402012-01-23 15:43:46 -08003134 *p_++ = state;
Ian Rogers15bf2d32012-08-28 17:33:04 -07003135 *p_++ = length - 1;
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003136 }
3137
Ian Rogers5bfa60f2012-09-02 21:17:56 -07003138 uint8_t ExamineObject(const Object* o, bool is_native_heap)
Ian Rogersb726dcb2012-09-05 08:57:23 -07003139 SHARED_LOCKS_REQUIRED(Locks::heap_bitmap_lock_) {
Elliott Hughesa2155262011-11-16 16:26:58 -08003140 if (o == NULL) {
3141 return HPSG_STATE(SOLIDITY_FREE, 0);
3142 }
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003143
Elliott Hughesa2155262011-11-16 16:26:58 -08003144 // It's an allocated chunk. Figure out what it is.
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003145
Elliott Hughesa2155262011-11-16 16:26:58 -08003146 // If we're looking at the native heap, we'll just return
3147 // (SOLIDITY_HARD, KIND_NATIVE) for all allocated chunks.
Ian Rogers00f7d0e2012-07-19 15:28:27 -07003148 if (is_native_heap) {
Elliott Hughesa2155262011-11-16 16:26:58 -08003149 return HPSG_STATE(SOLIDITY_HARD, KIND_NATIVE);
3150 }
3151
Ian Rogers5bfa60f2012-09-02 21:17:56 -07003152 if (!Runtime::Current()->GetHeap()->IsLiveObjectLocked(o)) {
Ian Rogers15bf2d32012-08-28 17:33:04 -07003153 return HPSG_STATE(SOLIDITY_HARD, KIND_NATIVE);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07003154 }
3155
Elliott Hughesa2155262011-11-16 16:26:58 -08003156 Class* c = o->GetClass();
3157 if (c == NULL) {
3158 // The object was probably just created but hasn't been initialized yet.
3159 return HPSG_STATE(SOLIDITY_HARD, KIND_OBJECT);
3160 }
3161
Elliott Hughesb3bd5f02012-03-08 21:05:27 -08003162 if (!Runtime::Current()->GetHeap()->IsHeapAddress(c)) {
Ian Rogers15bf2d32012-08-28 17:33:04 -07003163 LOG(ERROR) << "Invalid class for managed heap object: " << o << " " << c;
Elliott Hughesa2155262011-11-16 16:26:58 -08003164 return HPSG_STATE(SOLIDITY_HARD, KIND_UNKNOWN);
3165 }
3166
3167 if (c->IsClassClass()) {
3168 return HPSG_STATE(SOLIDITY_HARD, KIND_CLASS_OBJECT);
3169 }
3170
3171 if (c->IsArrayClass()) {
3172 if (o->IsObjectArray()) {
3173 return HPSG_STATE(SOLIDITY_HARD, KIND_ARRAY_4);
3174 }
3175 switch (c->GetComponentSize()) {
3176 case 1: return HPSG_STATE(SOLIDITY_HARD, KIND_ARRAY_1);
3177 case 2: return HPSG_STATE(SOLIDITY_HARD, KIND_ARRAY_2);
3178 case 4: return HPSG_STATE(SOLIDITY_HARD, KIND_ARRAY_4);
3179 case 8: return HPSG_STATE(SOLIDITY_HARD, KIND_ARRAY_8);
3180 }
3181 }
3182
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003183 return HPSG_STATE(SOLIDITY_HARD, KIND_OBJECT);
3184 }
3185
Ian Rogers30fab402012-01-23 15:43:46 -08003186 std::vector<uint8_t> buf_;
3187 uint8_t* p_;
3188 uint8_t* pieceLenField_;
Ian Rogers15bf2d32012-08-28 17:33:04 -07003189 void* startOfNextMemoryChunk_;
Ian Rogers30fab402012-01-23 15:43:46 -08003190 size_t totalAllocationUnits_;
3191 uint32_t type_;
3192 bool merge_;
3193 bool needHeader_;
3194
Elliott Hughesa2155262011-11-16 16:26:58 -08003195 DISALLOW_COPY_AND_ASSIGN(HeapChunkContext);
3196};
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003197
3198void Dbg::DdmSendHeapSegments(bool native) {
3199 Dbg::HpsgWhen when;
3200 Dbg::HpsgWhat what;
3201 if (!native) {
3202 when = gDdmHpsgWhen;
3203 what = gDdmHpsgWhat;
3204 } else {
3205 when = gDdmNhsgWhen;
3206 what = gDdmNhsgWhat;
3207 }
3208 if (when == HPSG_WHEN_NEVER) {
3209 return;
3210 }
3211
3212 // Figure out what kind of chunks we'll be sending.
3213 CHECK(what == HPSG_WHAT_MERGED_OBJECTS || what == HPSG_WHAT_DISTINCT_OBJECTS) << static_cast<int>(what);
3214
3215 // First, send a heap start chunk.
3216 uint8_t heap_id[4];
3217 JDWP::Set4BE(&heap_id[0], 1); // Heap id (bogus; we only have one heap).
3218 Dbg::DdmSendChunk(native ? CHUNK_TYPE("NHST") : CHUNK_TYPE("HPST"), sizeof(heap_id), heap_id);
3219
3220 // Send a series of heap segment chunks.
Elliott Hughesa2155262011-11-16 16:26:58 -08003221 HeapChunkContext context((what == HPSG_WHAT_MERGED_OBJECTS), native);
3222 if (native) {
Ian Rogers30fab402012-01-23 15:43:46 -08003223 // TODO: enable when bionic has moved to dlmalloc 2.8.5
3224 // dlmalloc_inspect_all(HeapChunkContext::HeapChunkCallback, &context);
3225 UNIMPLEMENTED(WARNING) << "Native heap send heap segments";
Elliott Hughesa2155262011-11-16 16:26:58 -08003226 } else {
Elliott Hughesb3bd5f02012-03-08 21:05:27 -08003227 Heap* heap = Runtime::Current()->GetHeap();
Mathieu Chartierfd678be2012-08-30 14:50:54 -07003228 const Spaces& spaces = heap->GetSpaces();
Ian Rogers50b35e22012-10-04 10:09:15 -07003229 Thread* self = Thread::Current();
Mathieu Chartierfd678be2012-08-30 14:50:54 -07003230 for (Spaces::const_iterator cur = spaces.begin(); cur != spaces.end(); ++cur) {
Mathieu Chartierb062fdd2012-07-03 09:51:48 -07003231 if ((*cur)->IsAllocSpace()) {
Ian Rogers50b35e22012-10-04 10:09:15 -07003232 ReaderMutexLock mu(self, *Locks::heap_bitmap_lock_);
Mathieu Chartierb062fdd2012-07-03 09:51:48 -07003233 (*cur)->AsAllocSpace()->Walk(HeapChunkContext::HeapChunkCallback, &context);
3234 }
3235 }
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -07003236 // Walk the large objects, these are not in the AllocSpace.
3237 heap->GetLargeObjectsSpace()->Walk(HeapChunkContext::HeapChunkCallback, &context);
Elliott Hughesa2155262011-11-16 16:26:58 -08003238 }
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003239
3240 // Finally, send a heap end chunk.
3241 Dbg::DdmSendChunk(native ? CHUNK_TYPE("NHEN") : CHUNK_TYPE("HPEN"), sizeof(heap_id), heap_id);
Elliott Hughes767a1472011-10-26 18:49:02 -07003242}
3243
Elliott Hughes545a0642011-11-08 19:10:03 -08003244void Dbg::SetAllocTrackingEnabled(bool enabled) {
Ian Rogers50b35e22012-10-04 10:09:15 -07003245 MutexLock mu(Thread::Current(), gAllocTrackerLock);
Elliott Hughes545a0642011-11-08 19:10:03 -08003246 if (enabled) {
3247 if (recent_allocation_records_ == NULL) {
3248 LOG(INFO) << "Enabling alloc tracker (" << kNumAllocRecords << " entries, "
3249 << kMaxAllocRecordStackDepth << " frames --> "
3250 << (sizeof(AllocRecord) * kNumAllocRecords) << " bytes)";
3251 gAllocRecordHead = gAllocRecordCount = 0;
3252 recent_allocation_records_ = new AllocRecord[kNumAllocRecords];
3253 CHECK(recent_allocation_records_ != NULL);
3254 }
3255 } else {
3256 delete[] recent_allocation_records_;
3257 recent_allocation_records_ = NULL;
3258 }
3259}
3260
Ian Rogers0399dde2012-06-06 17:09:28 -07003261struct AllocRecordStackVisitor : public StackVisitor {
3262 AllocRecordStackVisitor(const ManagedStack* stack,
Ian Rogers306057f2012-11-26 12:45:53 -08003263 const std::deque<InstrumentationStackFrame>* instrumentation_stack,
3264 AllocRecord* record)
Ian Rogersb726dcb2012-09-05 08:57:23 -07003265 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_)
jeffhao725a9572012-11-13 18:20:12 -08003266 : StackVisitor(stack, instrumentation_stack, NULL), record(record), depth(0) {}
Elliott Hughes545a0642011-11-08 19:10:03 -08003267
Ian Rogers00f7d0e2012-07-19 15:28:27 -07003268 // TODO: Enable annotalysis. We know lock is held in constructor, but abstraction confuses
3269 // annotalysis.
3270 bool VisitFrame() NO_THREAD_SAFETY_ANALYSIS {
Elliott Hughes545a0642011-11-08 19:10:03 -08003271 if (depth >= kMaxAllocRecordStackDepth) {
Elliott Hughes530fa002012-03-12 11:44:49 -07003272 return false;
Elliott Hughes545a0642011-11-08 19:10:03 -08003273 }
Mathieu Chartier66f19252012-09-18 08:57:04 -07003274 AbstractMethod* m = GetMethod();
Ian Rogers0399dde2012-06-06 17:09:28 -07003275 if (!m->IsRuntimeMethod()) {
3276 record->stack[depth].method = m;
3277 record->stack[depth].dex_pc = GetDexPc();
Elliott Hughes530fa002012-03-12 11:44:49 -07003278 ++depth;
Elliott Hughes545a0642011-11-08 19:10:03 -08003279 }
Elliott Hughes530fa002012-03-12 11:44:49 -07003280 return true;
Elliott Hughes545a0642011-11-08 19:10:03 -08003281 }
3282
3283 ~AllocRecordStackVisitor() {
3284 // Clear out any unused stack trace elements.
3285 for (; depth < kMaxAllocRecordStackDepth; ++depth) {
3286 record->stack[depth].method = NULL;
Ian Rogers0399dde2012-06-06 17:09:28 -07003287 record->stack[depth].dex_pc = 0;
Elliott Hughes545a0642011-11-08 19:10:03 -08003288 }
3289 }
3290
3291 AllocRecord* record;
3292 size_t depth;
3293};
3294
3295void Dbg::RecordAllocation(Class* type, size_t byte_count) {
3296 Thread* self = Thread::Current();
3297 CHECK(self != NULL);
3298
Ian Rogers50b35e22012-10-04 10:09:15 -07003299 MutexLock mu(self, gAllocTrackerLock);
Elliott Hughes545a0642011-11-08 19:10:03 -08003300 if (recent_allocation_records_ == NULL) {
3301 return;
3302 }
3303
3304 // Advance and clip.
3305 if (++gAllocRecordHead == kNumAllocRecords) {
3306 gAllocRecordHead = 0;
3307 }
3308
3309 // Fill in the basics.
3310 AllocRecord* record = &recent_allocation_records_[gAllocRecordHead];
3311 record->type = type;
3312 record->byte_count = byte_count;
3313 record->thin_lock_id = self->GetThinLockId();
3314
3315 // Fill in the stack trace.
jeffhao725a9572012-11-13 18:20:12 -08003316 AllocRecordStackVisitor visitor(self->GetManagedStack(), self->GetInstrumentationStack(), record);
Ian Rogers0399dde2012-06-06 17:09:28 -07003317 visitor.WalkStack();
Elliott Hughes545a0642011-11-08 19:10:03 -08003318
3319 if (gAllocRecordCount < kNumAllocRecords) {
3320 ++gAllocRecordCount;
3321 }
3322}
3323
Elliott Hughesa8f93cb2012-06-08 17:08:48 -07003324// Returns the index of the head element.
3325//
3326// We point at the most-recently-written record, so if gAllocRecordCount is 1
3327// we want to use the current element. Take "head+1" and subtract count
3328// from it.
3329//
3330// We need to handle underflow in our circular buffer, so we add
3331// kNumAllocRecords and then mask it back down.
Elliott Hughesf8349362012-06-18 15:00:06 -07003332static inline int HeadIndex() EXCLUSIVE_LOCKS_REQUIRED(gAllocTrackerLock) {
Elliott Hughes545a0642011-11-08 19:10:03 -08003333 return (gAllocRecordHead+1 + kNumAllocRecords - gAllocRecordCount) & (kNumAllocRecords-1);
3334}
3335
3336void Dbg::DumpRecentAllocations() {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07003337 ScopedObjectAccess soa(Thread::Current());
Ian Rogers50b35e22012-10-04 10:09:15 -07003338 MutexLock mu(soa.Self(), gAllocTrackerLock);
Elliott Hughes545a0642011-11-08 19:10:03 -08003339 if (recent_allocation_records_ == NULL) {
3340 LOG(INFO) << "Not recording tracked allocations";
3341 return;
3342 }
3343
3344 // "i" is the head of the list. We want to start at the end of the
3345 // list and move forward to the tail.
Elliott Hughesa8f93cb2012-06-08 17:08:48 -07003346 size_t i = HeadIndex();
Elliott Hughes545a0642011-11-08 19:10:03 -08003347 size_t count = gAllocRecordCount;
3348
3349 LOG(INFO) << "Tracked allocations, (head=" << gAllocRecordHead << " count=" << count << ")";
3350 while (count--) {
3351 AllocRecord* record = &recent_allocation_records_[i];
3352
Elliott Hughesa8f93cb2012-06-08 17:08:48 -07003353 LOG(INFO) << StringPrintf(" Thread %-2d %6zd bytes ", record->thin_lock_id, record->byte_count)
Elliott Hughes545a0642011-11-08 19:10:03 -08003354 << PrettyClass(record->type);
3355
3356 for (size_t stack_frame = 0; stack_frame < kMaxAllocRecordStackDepth; ++stack_frame) {
Mathieu Chartier66f19252012-09-18 08:57:04 -07003357 const AbstractMethod* m = record->stack[stack_frame].method;
Elliott Hughes545a0642011-11-08 19:10:03 -08003358 if (m == NULL) {
3359 break;
3360 }
3361 LOG(INFO) << " " << PrettyMethod(m) << " line " << record->stack[stack_frame].LineNumber();
3362 }
3363
3364 // pause periodically to help logcat catch up
3365 if ((count % 5) == 0) {
3366 usleep(40000);
3367 }
3368
3369 i = (i + 1) & (kNumAllocRecords-1);
3370 }
3371}
3372
3373class StringTable {
3374 public:
3375 StringTable() {
3376 }
3377
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08003378 void Add(const char* s) {
Elliott Hughes545a0642011-11-08 19:10:03 -08003379 table_.insert(s);
3380 }
3381
Elliott Hughesa8f93cb2012-06-08 17:08:48 -07003382 size_t IndexOf(const char* s) const {
3383 typedef std::set<std::string>::const_iterator It; // TODO: C++0x auto
3384 It it = table_.find(s);
3385 if (it == table_.end()) {
3386 LOG(FATAL) << "IndexOf(\"" << s << "\") failed";
3387 }
3388 return std::distance(table_.begin(), it);
Elliott Hughes545a0642011-11-08 19:10:03 -08003389 }
3390
Elliott Hughesa8f93cb2012-06-08 17:08:48 -07003391 size_t Size() const {
Elliott Hughes545a0642011-11-08 19:10:03 -08003392 return table_.size();
3393 }
3394
Elliott Hughesa8f93cb2012-06-08 17:08:48 -07003395 void WriteTo(std::vector<uint8_t>& bytes) const {
3396 typedef std::set<std::string>::const_iterator It; // TODO: C++0x auto
Elliott Hughes545a0642011-11-08 19:10:03 -08003397 for (It it = table_.begin(); it != table_.end(); ++it) {
Elliott Hughesa8f93cb2012-06-08 17:08:48 -07003398 const char* s = (*it).c_str();
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08003399 size_t s_len = CountModifiedUtf8Chars(s);
3400 UniquePtr<uint16_t> s_utf16(new uint16_t[s_len]);
3401 ConvertModifiedUtf8ToUtf16(s_utf16.get(), s);
3402 JDWP::AppendUtf16BE(bytes, s_utf16.get(), s_len);
Elliott Hughes545a0642011-11-08 19:10:03 -08003403 }
3404 }
3405
3406 private:
Elliott Hughesa8f93cb2012-06-08 17:08:48 -07003407 std::set<std::string> table_;
Elliott Hughes545a0642011-11-08 19:10:03 -08003408 DISALLOW_COPY_AND_ASSIGN(StringTable);
3409};
3410
3411/*
3412 * The data we send to DDMS contains everything we have recorded.
3413 *
3414 * Message header (all values big-endian):
3415 * (1b) message header len (to allow future expansion); includes itself
3416 * (1b) entry header len
3417 * (1b) stack frame len
3418 * (2b) number of entries
3419 * (4b) offset to string table from start of message
3420 * (2b) number of class name strings
3421 * (2b) number of method name strings
3422 * (2b) number of source file name strings
3423 * For each entry:
3424 * (4b) total allocation size
Elliott Hughes221229c2013-01-08 18:17:50 -08003425 * (2b) thread id
Elliott Hughes545a0642011-11-08 19:10:03 -08003426 * (2b) allocated object's class name index
3427 * (1b) stack depth
3428 * For each stack frame:
3429 * (2b) method's class name
3430 * (2b) method name
3431 * (2b) method source file
3432 * (2b) line number, clipped to 32767; -2 if native; -1 if no source
3433 * (xb) class name strings
3434 * (xb) method name strings
3435 * (xb) source file strings
3436 *
3437 * As with other DDM traffic, strings are sent as a 4-byte length
3438 * followed by UTF-16 data.
3439 *
3440 * We send up 16-bit unsigned indexes into string tables. In theory there
3441 * can be (kMaxAllocRecordStackDepth * kNumAllocRecords) unique strings in
3442 * each table, but in practice there should be far fewer.
3443 *
3444 * The chief reason for using a string table here is to keep the size of
3445 * the DDMS message to a minimum. This is partly to make the protocol
3446 * efficient, but also because we have to form the whole thing up all at
3447 * once in a memory buffer.
3448 *
3449 * We use separate string tables for class names, method names, and source
3450 * files to keep the indexes small. There will generally be no overlap
3451 * between the contents of these tables.
3452 */
3453jbyteArray Dbg::GetRecentAllocations() {
3454 if (false) {
3455 DumpRecentAllocations();
3456 }
3457
Ian Rogers50b35e22012-10-04 10:09:15 -07003458 Thread* self = Thread::Current();
3459 MutexLock mu(self, gAllocTrackerLock);
Elliott Hughes545a0642011-11-08 19:10:03 -08003460
Elliott Hughesa8f93cb2012-06-08 17:08:48 -07003461 //
3462 // Part 1: generate string tables.
3463 //
Elliott Hughes545a0642011-11-08 19:10:03 -08003464 StringTable class_names;
3465 StringTable method_names;
3466 StringTable filenames;
3467
3468 int count = gAllocRecordCount;
Elliott Hughesa8f93cb2012-06-08 17:08:48 -07003469 int idx = HeadIndex();
Elliott Hughes545a0642011-11-08 19:10:03 -08003470 while (count--) {
3471 AllocRecord* record = &recent_allocation_records_[idx];
3472
Elliott Hughes91250e02011-12-13 22:30:35 -08003473 class_names.Add(ClassHelper(record->type).GetDescriptor());
Elliott Hughes545a0642011-11-08 19:10:03 -08003474
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08003475 MethodHelper mh;
Elliott Hughes545a0642011-11-08 19:10:03 -08003476 for (size_t i = 0; i < kMaxAllocRecordStackDepth; i++) {
Mathieu Chartier66f19252012-09-18 08:57:04 -07003477 AbstractMethod* m = record->stack[i].method;
Elliott Hughes545a0642011-11-08 19:10:03 -08003478 if (m != NULL) {
Ian Rogersba377812012-05-28 21:16:29 -07003479 mh.ChangeMethod(m);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08003480 class_names.Add(mh.GetDeclaringClassDescriptor());
3481 method_names.Add(mh.GetName());
3482 filenames.Add(mh.GetDeclaringClassSourceFile());
Elliott Hughes545a0642011-11-08 19:10:03 -08003483 }
3484 }
3485
3486 idx = (idx + 1) & (kNumAllocRecords-1);
3487 }
3488
3489 LOG(INFO) << "allocation records: " << gAllocRecordCount;
3490
Elliott Hughesa8f93cb2012-06-08 17:08:48 -07003491 //
3492 // Part 2: allocate a buffer and generate the output.
3493 //
Elliott Hughes545a0642011-11-08 19:10:03 -08003494 std::vector<uint8_t> bytes;
3495
3496 // (1b) message header len (to allow future expansion); includes itself
3497 // (1b) entry header len
3498 // (1b) stack frame len
3499 const int kMessageHeaderLen = 15;
3500 const int kEntryHeaderLen = 9;
3501 const int kStackFrameLen = 8;
3502 JDWP::Append1BE(bytes, kMessageHeaderLen);
3503 JDWP::Append1BE(bytes, kEntryHeaderLen);
3504 JDWP::Append1BE(bytes, kStackFrameLen);
3505
3506 // (2b) number of entries
3507 // (4b) offset to string table from start of message
3508 // (2b) number of class name strings
3509 // (2b) number of method name strings
3510 // (2b) number of source file name strings
3511 JDWP::Append2BE(bytes, gAllocRecordCount);
3512 size_t string_table_offset = bytes.size();
3513 JDWP::Append4BE(bytes, 0); // We'll patch this later...
3514 JDWP::Append2BE(bytes, class_names.Size());
3515 JDWP::Append2BE(bytes, method_names.Size());
3516 JDWP::Append2BE(bytes, filenames.Size());
3517
3518 count = gAllocRecordCount;
Elliott Hughesa8f93cb2012-06-08 17:08:48 -07003519 idx = HeadIndex();
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08003520 ClassHelper kh;
Elliott Hughes545a0642011-11-08 19:10:03 -08003521 while (count--) {
3522 // For each entry:
3523 // (4b) total allocation size
3524 // (2b) thread id
3525 // (2b) allocated object's class name index
3526 // (1b) stack depth
3527 AllocRecord* record = &recent_allocation_records_[idx];
3528 size_t stack_depth = record->GetDepth();
Elliott Hughesa8f93cb2012-06-08 17:08:48 -07003529 kh.ChangeClass(record->type);
3530 size_t allocated_object_class_name_index = class_names.IndexOf(kh.GetDescriptor());
Elliott Hughes545a0642011-11-08 19:10:03 -08003531 JDWP::Append4BE(bytes, record->byte_count);
3532 JDWP::Append2BE(bytes, record->thin_lock_id);
Elliott Hughesa8f93cb2012-06-08 17:08:48 -07003533 JDWP::Append2BE(bytes, allocated_object_class_name_index);
Elliott Hughes545a0642011-11-08 19:10:03 -08003534 JDWP::Append1BE(bytes, stack_depth);
3535
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08003536 MethodHelper mh;
Elliott Hughes545a0642011-11-08 19:10:03 -08003537 for (size_t stack_frame = 0; stack_frame < stack_depth; ++stack_frame) {
3538 // For each stack frame:
3539 // (2b) method's class name
3540 // (2b) method name
3541 // (2b) method source file
3542 // (2b) line number, clipped to 32767; -2 if native; -1 if no source
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08003543 mh.ChangeMethod(record->stack[stack_frame].method);
Elliott Hughesa8f93cb2012-06-08 17:08:48 -07003544 size_t class_name_index = class_names.IndexOf(mh.GetDeclaringClassDescriptor());
3545 size_t method_name_index = method_names.IndexOf(mh.GetName());
3546 size_t file_name_index = filenames.IndexOf(mh.GetDeclaringClassSourceFile());
3547 JDWP::Append2BE(bytes, class_name_index);
3548 JDWP::Append2BE(bytes, method_name_index);
3549 JDWP::Append2BE(bytes, file_name_index);
Elliott Hughes545a0642011-11-08 19:10:03 -08003550 JDWP::Append2BE(bytes, record->stack[stack_frame].LineNumber());
3551 }
3552
3553 idx = (idx + 1) & (kNumAllocRecords-1);
3554 }
3555
3556 // (xb) class name strings
3557 // (xb) method name strings
3558 // (xb) source file strings
3559 JDWP::Set4BE(&bytes[string_table_offset], bytes.size());
3560 class_names.WriteTo(bytes);
3561 method_names.WriteTo(bytes);
3562 filenames.WriteTo(bytes);
3563
Ian Rogers50b35e22012-10-04 10:09:15 -07003564 JNIEnv* env = self->GetJniEnv();
Elliott Hughes545a0642011-11-08 19:10:03 -08003565 jbyteArray result = env->NewByteArray(bytes.size());
3566 if (result != NULL) {
3567 env->SetByteArrayRegion(result, 0, bytes.size(), reinterpret_cast<const jbyte*>(&bytes[0]));
3568 }
3569 return result;
3570}
3571
Elliott Hughes872d4ec2011-10-21 17:07:15 -07003572} // namespace art