blob: cdc2178341486962375d5b335ab2193733407804 [file] [log] [blame]
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001/*
2 * Copyright (C) 2008 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17#include "debugger.h"
18
Elliott Hughes3bb81562011-10-21 18:52:59 -070019#include <sys/uio.h>
20
Elliott Hughes545a0642011-11-08 19:10:03 -080021#include <set>
22
23#include "class_linker.h"
Elliott Hughes1bba14f2011-12-01 18:00:36 -080024#include "class_loader.h"
Ian Rogers776ac1f2012-04-13 23:36:36 -070025#include "dex_instruction.h"
Mathieu Chartier1c23e1e2012-10-12 14:14:11 -070026#include "gc/large_object_space.h"
27#include "gc/space.h"
Ian Rogers2bcb4a42012-11-08 10:39:18 -080028#include "oat/runtime/context.h"
Ian Rogers6d4d9fc2011-11-30 16:24:48 -080029#include "object_utils.h"
Elliott Hughesa0e18062012-04-13 15:59:59 -070030#include "safe_map.h"
Elliott Hughes6a5bd492011-10-28 14:33:57 -070031#include "ScopedLocalRef.h"
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -070032#include "ScopedPrimitiveArray.h"
Ian Rogers00f7d0e2012-07-19 15:28:27 -070033#include "scoped_thread_state_change.h"
Ian Rogers1f539342012-10-03 21:09:42 -070034#include "sirt_ref.h"
Elliott Hughes47fce012011-10-25 18:37:19 -070035#include "stack_indirect_reference_table.h"
Elliott Hughes475fc232011-10-25 15:00:35 -070036#include "thread_list.h"
Elliott Hugheseac76672012-05-24 21:56:51 -070037#include "well_known_classes.h"
Elliott Hughes475fc232011-10-25 15:00:35 -070038
Elliott Hughes872d4ec2011-10-21 17:07:15 -070039namespace art {
40
Elliott Hughes545a0642011-11-08 19:10:03 -080041static const size_t kMaxAllocRecordStackDepth = 16; // Max 255.
42static const size_t kNumAllocRecords = 512; // Must be power of 2.
43
Elliott Hughes436e3722012-02-17 20:01:47 -080044static const uintptr_t kInvalidId = 1;
45static const Object* kInvalidObject = reinterpret_cast<Object*>(kInvalidId);
46
Elliott Hughes475fc232011-10-25 15:00:35 -070047class ObjectRegistry {
48 public:
49 ObjectRegistry() : lock_("ObjectRegistry lock") {
50 }
51
52 JDWP::ObjectId Add(Object* o) {
53 if (o == NULL) {
54 return 0;
55 }
56 JDWP::ObjectId id = static_cast<JDWP::ObjectId>(reinterpret_cast<uintptr_t>(o));
Ian Rogers50b35e22012-10-04 10:09:15 -070057 MutexLock mu(Thread::Current(), lock_);
Elliott Hughesa0e18062012-04-13 15:59:59 -070058 map_.Overwrite(id, o);
Elliott Hughes475fc232011-10-25 15:00:35 -070059 return id;
60 }
61
Elliott Hughes234ab152011-10-26 14:02:26 -070062 void Clear() {
Ian Rogers50b35e22012-10-04 10:09:15 -070063 MutexLock mu(Thread::Current(), lock_);
Elliott Hughes234ab152011-10-26 14:02:26 -070064 LOG(DEBUG) << "Debugger has detached; object registry had " << map_.size() << " entries";
65 map_.clear();
66 }
67
Elliott Hughes475fc232011-10-25 15:00:35 -070068 bool Contains(JDWP::ObjectId id) {
Ian Rogers50b35e22012-10-04 10:09:15 -070069 MutexLock mu(Thread::Current(), lock_);
Elliott Hughes475fc232011-10-25 15:00:35 -070070 return map_.find(id) != map_.end();
71 }
72
Elliott Hughesa2155262011-11-16 16:26:58 -080073 template<typename T> T Get(JDWP::ObjectId id) {
Elliott Hughes436e3722012-02-17 20:01:47 -080074 if (id == 0) {
75 return NULL;
76 }
77
Ian Rogers50b35e22012-10-04 10:09:15 -070078 MutexLock mu(Thread::Current(), lock_);
Elliott Hughesa0e18062012-04-13 15:59:59 -070079 typedef SafeMap<JDWP::ObjectId, Object*>::iterator It; // C++0x auto
Elliott Hughesa2155262011-11-16 16:26:58 -080080 It it = map_.find(id);
Elliott Hughes436e3722012-02-17 20:01:47 -080081 return (it != map_.end()) ? reinterpret_cast<T>(it->second) : reinterpret_cast<T>(kInvalidId);
Elliott Hughesa2155262011-11-16 16:26:58 -080082 }
83
Elliott Hughesbfe487b2011-10-26 15:48:55 -070084 void VisitRoots(Heap::RootVisitor* visitor, void* arg) {
Ian Rogers50b35e22012-10-04 10:09:15 -070085 MutexLock mu(Thread::Current(), lock_);
Elliott Hughesa0e18062012-04-13 15:59:59 -070086 typedef SafeMap<JDWP::ObjectId, Object*>::iterator It; // C++0x auto
Elliott Hughesbfe487b2011-10-26 15:48:55 -070087 for (It it = map_.begin(); it != map_.end(); ++it) {
88 visitor(it->second, arg);
89 }
90 }
91
Elliott Hughes475fc232011-10-25 15:00:35 -070092 private:
Ian Rogers00f7d0e2012-07-19 15:28:27 -070093 Mutex lock_ DEFAULT_MUTEX_ACQUIRED_AFTER;
Elliott Hughesa0e18062012-04-13 15:59:59 -070094 SafeMap<JDWP::ObjectId, Object*> map_;
Elliott Hughes475fc232011-10-25 15:00:35 -070095};
96
Elliott Hughes545a0642011-11-08 19:10:03 -080097struct AllocRecordStackTraceElement {
Mathieu Chartier66f19252012-09-18 08:57:04 -070098 AbstractMethod* method;
Ian Rogers0399dde2012-06-06 17:09:28 -070099 uint32_t dex_pc;
Elliott Hughes545a0642011-11-08 19:10:03 -0800100
Ian Rogersb726dcb2012-09-05 08:57:23 -0700101 int32_t LineNumber() const SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Ian Rogers0399dde2012-06-06 17:09:28 -0700102 return MethodHelper(method).GetLineNumFromDexPC(dex_pc);
Elliott Hughes545a0642011-11-08 19:10:03 -0800103 }
104};
105
106struct AllocRecord {
107 Class* type;
108 size_t byte_count;
109 uint16_t thin_lock_id;
110 AllocRecordStackTraceElement stack[kMaxAllocRecordStackDepth]; // Unused entries have NULL method.
111
112 size_t GetDepth() {
113 size_t depth = 0;
114 while (depth < kMaxAllocRecordStackDepth && stack[depth].method != NULL) {
115 ++depth;
116 }
117 return depth;
118 }
119};
120
Elliott Hughes86964332012-02-15 19:37:42 -0800121struct Breakpoint {
Mathieu Chartier66f19252012-09-18 08:57:04 -0700122 AbstractMethod* method;
Elliott Hughesa656a0f2012-02-21 18:03:44 -0800123 uint32_t dex_pc;
Mathieu Chartier66f19252012-09-18 08:57:04 -0700124 Breakpoint(AbstractMethod* method, uint32_t dex_pc) : method(method), dex_pc(dex_pc) {}
Elliott Hughes86964332012-02-15 19:37:42 -0800125};
126
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700127static std::ostream& operator<<(std::ostream& os, const Breakpoint& rhs)
Ian Rogersb726dcb2012-09-05 08:57:23 -0700128 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Elliott Hughes229feb72012-02-23 13:33:29 -0800129 os << StringPrintf("Breakpoint[%s @%#x]", PrettyMethod(rhs.method).c_str(), rhs.dex_pc);
Elliott Hughes86964332012-02-15 19:37:42 -0800130 return os;
131}
132
133struct SingleStepControl {
134 // Are we single-stepping right now?
135 bool is_active;
136 Thread* thread;
137
138 JDWP::JdwpStepSize step_size;
139 JDWP::JdwpStepDepth step_depth;
140
Mathieu Chartier66f19252012-09-18 08:57:04 -0700141 const AbstractMethod* method;
Elliott Hughes2435a572012-02-17 16:07:41 -0800142 int32_t line_number; // Or -1 for native methods.
143 std::set<uint32_t> dex_pcs;
Elliott Hughes86964332012-02-15 19:37:42 -0800144 int stack_depth;
145};
146
Elliott Hughes4ffd3132011-10-24 12:06:42 -0700147// JDWP is allowed unless the Zygote forbids it.
148static bool gJdwpAllowed = true;
149
Elliott Hughesc0f09332012-03-26 13:27:06 -0700150// Was there a -Xrunjdwp or -agentlib:jdwp= argument on the command line?
Elliott Hughes3bb81562011-10-21 18:52:59 -0700151static bool gJdwpConfigured = false;
152
Elliott Hughesc0f09332012-03-26 13:27:06 -0700153// Broken-down JDWP options. (Only valid if IsJdwpConfigured() is true.)
Elliott Hughes376a7a02011-10-24 18:35:55 -0700154static JDWP::JdwpOptions gJdwpOptions;
Elliott Hughes3bb81562011-10-21 18:52:59 -0700155
156// Runtime JDWP state.
157static JDWP::JdwpState* gJdwpState = NULL;
158static bool gDebuggerConnected; // debugger or DDMS is connected.
159static bool gDebuggerActive; // debugger is making requests.
Elliott Hughes86964332012-02-15 19:37:42 -0800160static bool gDisposed; // debugger called VirtualMachine.Dispose, so we should drop the connection.
Elliott Hughes3bb81562011-10-21 18:52:59 -0700161
Elliott Hughes47fce012011-10-25 18:37:19 -0700162static bool gDdmThreadNotification = false;
163
Elliott Hughes767a1472011-10-26 18:49:02 -0700164// DDMS GC-related settings.
165static Dbg::HpifWhen gDdmHpifWhen = Dbg::HPIF_WHEN_NEVER;
166static Dbg::HpsgWhen gDdmHpsgWhen = Dbg::HPSG_WHEN_NEVER;
167static Dbg::HpsgWhat gDdmHpsgWhat;
168static Dbg::HpsgWhen gDdmNhsgWhen = Dbg::HPSG_WHEN_NEVER;
169static Dbg::HpsgWhat gDdmNhsgWhat;
170
Elliott Hughes475fc232011-10-25 15:00:35 -0700171static ObjectRegistry* gRegistry = NULL;
172
Elliott Hughes545a0642011-11-08 19:10:03 -0800173// Recent allocation tracking.
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700174static Mutex gAllocTrackerLock DEFAULT_MUTEX_ACQUIRED_AFTER ("AllocTracker lock");
Elliott Hughesf8349362012-06-18 15:00:06 -0700175AllocRecord* Dbg::recent_allocation_records_ PT_GUARDED_BY(gAllocTrackerLock) = NULL; // TODO: CircularBuffer<AllocRecord>
176static size_t gAllocRecordHead GUARDED_BY(gAllocTrackerLock) = 0;
177static size_t gAllocRecordCount GUARDED_BY(gAllocTrackerLock) = 0;
Elliott Hughes545a0642011-11-08 19:10:03 -0800178
Elliott Hughes86964332012-02-15 19:37:42 -0800179// Breakpoints and single-stepping.
jeffhao09bfc6a2012-12-11 18:11:43 -0800180static std::vector<Breakpoint> gBreakpoints GUARDED_BY(Locks::breakpoint_lock_);
181static SingleStepControl gSingleStepControl GUARDED_BY(Locks::breakpoint_lock_);
Elliott Hughes86964332012-02-15 19:37:42 -0800182
Mathieu Chartier66f19252012-09-18 08:57:04 -0700183static bool IsBreakpoint(AbstractMethod* m, uint32_t dex_pc)
jeffhao09bfc6a2012-12-11 18:11:43 -0800184 LOCKS_EXCLUDED(Locks::breakpoint_lock_)
Ian Rogersb726dcb2012-09-05 08:57:23 -0700185 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
jeffhao09bfc6a2012-12-11 18:11:43 -0800186 MutexLock mu(Thread::Current(), *Locks::breakpoint_lock_);
Elliott Hughes86964332012-02-15 19:37:42 -0800187 for (size_t i = 0; i < gBreakpoints.size(); ++i) {
Elliott Hughesa656a0f2012-02-21 18:03:44 -0800188 if (gBreakpoints[i].method == m && gBreakpoints[i].dex_pc == dex_pc) {
Elliott Hughes86964332012-02-15 19:37:42 -0800189 VLOG(jdwp) << "Hit breakpoint #" << i << ": " << gBreakpoints[i];
190 return true;
191 }
192 }
193 return false;
194}
195
Elliott Hughes9e0c1752013-01-09 14:02:58 -0800196static bool IsSuspendedForDebugger(ScopedObjectAccessUnchecked& soa, Thread* thread) {
197 MutexLock mu(soa.Self(), *Locks::thread_suspend_count_lock_);
198 // A thread may be suspended for GC; in this code, we really want to know whether
199 // there's a debugger suspension active.
200 return thread->IsSuspended() && thread->GetDebugSuspendCount() > 0;
201}
202
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700203static Array* DecodeArray(JDWP::RefTypeId id, JDWP::JdwpError& status)
Ian Rogersb726dcb2012-09-05 08:57:23 -0700204 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Elliott Hughes436e3722012-02-17 20:01:47 -0800205 Object* o = gRegistry->Get<Object*>(id);
206 if (o == NULL || o == kInvalidObject) {
207 status = JDWP::ERR_INVALID_OBJECT;
208 return NULL;
209 }
210 if (!o->IsArrayInstance()) {
211 status = JDWP::ERR_INVALID_ARRAY;
212 return NULL;
213 }
214 status = JDWP::ERR_NONE;
215 return o->AsArray();
216}
217
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700218static Class* DecodeClass(JDWP::RefTypeId id, JDWP::JdwpError& status)
Ian Rogersb726dcb2012-09-05 08:57:23 -0700219 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Elliott Hughes436e3722012-02-17 20:01:47 -0800220 Object* o = gRegistry->Get<Object*>(id);
221 if (o == NULL || o == kInvalidObject) {
222 status = JDWP::ERR_INVALID_OBJECT;
223 return NULL;
224 }
225 if (!o->IsClass()) {
226 status = JDWP::ERR_INVALID_CLASS;
227 return NULL;
228 }
229 status = JDWP::ERR_NONE;
230 return o->AsClass();
231}
232
Elliott Hughes221229c2013-01-08 18:17:50 -0800233static JDWP::JdwpError DecodeThread(ScopedObjectAccessUnchecked& soa, JDWP::ObjectId thread_id, Thread*& thread)
jeffhaoa77f0f62012-12-05 17:19:31 -0800234 EXCLUSIVE_LOCKS_REQUIRED(Locks::thread_list_lock_)
Ian Rogersb726dcb2012-09-05 08:57:23 -0700235 LOCKS_EXCLUDED(Locks::thread_suspend_count_lock_)
236 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Elliott Hughes221229c2013-01-08 18:17:50 -0800237 Object* thread_peer = gRegistry->Get<Object*>(thread_id);
Elliott Hughes436e3722012-02-17 20:01:47 -0800238 if (thread_peer == NULL || thread_peer == kInvalidObject) {
Elliott Hughes221229c2013-01-08 18:17:50 -0800239 // This isn't even an object.
240 return JDWP::ERR_INVALID_OBJECT;
Elliott Hughes436e3722012-02-17 20:01:47 -0800241 }
Elliott Hughes221229c2013-01-08 18:17:50 -0800242
243 Class* java_lang_Thread = soa.Decode<Class*>(WellKnownClasses::java_lang_Thread);
244 if (!java_lang_Thread->IsAssignableFrom(thread_peer->GetClass())) {
245 // This isn't a thread.
246 return JDWP::ERR_INVALID_THREAD;
247 }
248
249 thread = Thread::FromManagedThread(soa, thread_peer);
250 if (thread == NULL) {
251 // This is a java.lang.Thread without a Thread*. Must be a zombie.
252 return JDWP::ERR_THREAD_NOT_ALIVE;
253 }
254 return JDWP::ERR_NONE;
Elliott Hughes436e3722012-02-17 20:01:47 -0800255}
256
Elliott Hughes24437992011-11-30 14:49:33 -0800257static JDWP::JdwpTag BasicTagFromDescriptor(const char* descriptor) {
258 // JDWP deliberately uses the descriptor characters' ASCII values for its enum.
259 // Note that by "basic" we mean that we don't get more specific than JT_OBJECT.
260 return static_cast<JDWP::JdwpTag>(descriptor[0]);
261}
262
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700263static JDWP::JdwpTag TagFromClass(Class* c)
Ian Rogersb726dcb2012-09-05 08:57:23 -0700264 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Elliott Hughes86b00102011-12-05 17:54:26 -0800265 CHECK(c != NULL);
Elliott Hughes24437992011-11-30 14:49:33 -0800266 if (c->IsArrayClass()) {
267 return JDWP::JT_ARRAY;
268 }
269
Elliott Hughes3d30d9b2011-12-07 17:35:48 -0800270 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
Elliott Hughes24437992011-11-30 14:49:33 -0800271 if (c->IsStringClass()) {
272 return JDWP::JT_STRING;
273 } else if (c->IsClassClass()) {
274 return JDWP::JT_CLASS_OBJECT;
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -0800275 } else if (class_linker->FindSystemClass("Ljava/lang/Thread;")->IsAssignableFrom(c)) {
Elliott Hughes24437992011-11-30 14:49:33 -0800276 return JDWP::JT_THREAD;
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -0800277 } else if (class_linker->FindSystemClass("Ljava/lang/ThreadGroup;")->IsAssignableFrom(c)) {
Elliott Hughes24437992011-11-30 14:49:33 -0800278 return JDWP::JT_THREAD_GROUP;
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -0800279 } else if (class_linker->FindSystemClass("Ljava/lang/ClassLoader;")->IsAssignableFrom(c)) {
Elliott Hughes24437992011-11-30 14:49:33 -0800280 return JDWP::JT_CLASS_LOADER;
Elliott Hughes24437992011-11-30 14:49:33 -0800281 } else {
282 return JDWP::JT_OBJECT;
283 }
284}
285
286/*
287 * Objects declared to hold Object might actually hold a more specific
288 * type. The debugger may take a special interest in these (e.g. it
289 * wants to display the contents of Strings), so we want to return an
290 * appropriate tag.
291 *
292 * Null objects are tagged JT_OBJECT.
293 */
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700294static JDWP::JdwpTag TagFromObject(const Object* o)
Ian Rogersb726dcb2012-09-05 08:57:23 -0700295 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Elliott Hughes24437992011-11-30 14:49:33 -0800296 return (o == NULL) ? JDWP::JT_OBJECT : TagFromClass(o->GetClass());
297}
298
299static bool IsPrimitiveTag(JDWP::JdwpTag tag) {
300 switch (tag) {
301 case JDWP::JT_BOOLEAN:
302 case JDWP::JT_BYTE:
303 case JDWP::JT_CHAR:
304 case JDWP::JT_FLOAT:
305 case JDWP::JT_DOUBLE:
306 case JDWP::JT_INT:
307 case JDWP::JT_LONG:
308 case JDWP::JT_SHORT:
309 case JDWP::JT_VOID:
310 return true;
311 default:
312 return false;
313 }
314}
315
Elliott Hughes3bb81562011-10-21 18:52:59 -0700316/*
317 * Handle one of the JDWP name/value pairs.
318 *
319 * JDWP options are:
320 * help: if specified, show help message and bail
321 * transport: may be dt_socket or dt_shmem
322 * address: for dt_socket, "host:port", or just "port" when listening
323 * server: if "y", wait for debugger to attach; if "n", attach to debugger
324 * timeout: how long to wait for debugger to connect / listen
325 *
326 * Useful with server=n (these aren't supported yet):
327 * onthrow=<exception-name>: connect to debugger when exception thrown
328 * onuncaught=y|n: connect to debugger when uncaught exception thrown
329 * launch=<command-line>: launch the debugger itself
330 *
331 * The "transport" option is required, as is "address" if server=n.
332 */
333static bool ParseJdwpOption(const std::string& name, const std::string& value) {
334 if (name == "transport") {
335 if (value == "dt_socket") {
Elliott Hughes376a7a02011-10-24 18:35:55 -0700336 gJdwpOptions.transport = JDWP::kJdwpTransportSocket;
Elliott Hughes3bb81562011-10-21 18:52:59 -0700337 } else if (value == "dt_android_adb") {
Elliott Hughes376a7a02011-10-24 18:35:55 -0700338 gJdwpOptions.transport = JDWP::kJdwpTransportAndroidAdb;
Elliott Hughes3bb81562011-10-21 18:52:59 -0700339 } else {
340 LOG(ERROR) << "JDWP transport not supported: " << value;
341 return false;
342 }
343 } else if (name == "server") {
344 if (value == "n") {
Elliott Hughes376a7a02011-10-24 18:35:55 -0700345 gJdwpOptions.server = false;
Elliott Hughes3bb81562011-10-21 18:52:59 -0700346 } else if (value == "y") {
Elliott Hughes376a7a02011-10-24 18:35:55 -0700347 gJdwpOptions.server = true;
Elliott Hughes3bb81562011-10-21 18:52:59 -0700348 } else {
349 LOG(ERROR) << "JDWP option 'server' must be 'y' or 'n'";
350 return false;
351 }
352 } else if (name == "suspend") {
353 if (value == "n") {
Elliott Hughes376a7a02011-10-24 18:35:55 -0700354 gJdwpOptions.suspend = false;
Elliott Hughes3bb81562011-10-21 18:52:59 -0700355 } else if (value == "y") {
Elliott Hughes376a7a02011-10-24 18:35:55 -0700356 gJdwpOptions.suspend = true;
Elliott Hughes3bb81562011-10-21 18:52:59 -0700357 } else {
358 LOG(ERROR) << "JDWP option 'suspend' must be 'y' or 'n'";
359 return false;
360 }
361 } else if (name == "address") {
362 /* this is either <port> or <host>:<port> */
363 std::string port_string;
Elliott Hughes376a7a02011-10-24 18:35:55 -0700364 gJdwpOptions.host.clear();
Elliott Hughes3bb81562011-10-21 18:52:59 -0700365 std::string::size_type colon = value.find(':');
366 if (colon != std::string::npos) {
Elliott Hughes376a7a02011-10-24 18:35:55 -0700367 gJdwpOptions.host = value.substr(0, colon);
Elliott Hughes3bb81562011-10-21 18:52:59 -0700368 port_string = value.substr(colon + 1);
369 } else {
370 port_string = value;
371 }
372 if (port_string.empty()) {
373 LOG(ERROR) << "JDWP address missing port: " << value;
374 return false;
375 }
376 char* end;
Elliott Hughesba8eee12012-01-24 20:25:24 -0800377 uint64_t port = strtoul(port_string.c_str(), &end, 10);
378 if (*end != '\0' || port > 0xffff) {
Elliott Hughes3bb81562011-10-21 18:52:59 -0700379 LOG(ERROR) << "JDWP address has junk in port field: " << value;
380 return false;
381 }
Elliott Hughes376a7a02011-10-24 18:35:55 -0700382 gJdwpOptions.port = port;
Elliott Hughes3bb81562011-10-21 18:52:59 -0700383 } else if (name == "launch" || name == "onthrow" || name == "oncaught" || name == "timeout") {
384 /* valid but unsupported */
385 LOG(INFO) << "Ignoring JDWP option '" << name << "'='" << value << "'";
386 } else {
387 LOG(INFO) << "Ignoring unrecognized JDWP option '" << name << "'='" << value << "'";
388 }
389
390 return true;
391}
392
393/*
394 * Parse the latter half of a -Xrunjdwp/-agentlib:jdwp= string, e.g.:
395 * "transport=dt_socket,address=8000,server=y,suspend=n"
396 */
397bool Dbg::ParseJdwpOptions(const std::string& options) {
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -0800398 VLOG(jdwp) << "ParseJdwpOptions: " << options;
Elliott Hughes47fce012011-10-25 18:37:19 -0700399
Elliott Hughes3bb81562011-10-21 18:52:59 -0700400 std::vector<std::string> pairs;
401 Split(options, ',', pairs);
402
403 for (size_t i = 0; i < pairs.size(); ++i) {
404 std::string::size_type equals = pairs[i].find('=');
405 if (equals == std::string::npos) {
406 LOG(ERROR) << "Can't parse JDWP option '" << pairs[i] << "' in '" << options << "'";
407 return false;
408 }
409 ParseJdwpOption(pairs[i].substr(0, equals), pairs[i].substr(equals + 1));
410 }
411
Elliott Hughes376a7a02011-10-24 18:35:55 -0700412 if (gJdwpOptions.transport == JDWP::kJdwpTransportUnknown) {
Elliott Hughes3bb81562011-10-21 18:52:59 -0700413 LOG(ERROR) << "Must specify JDWP transport: " << options;
414 }
Elliott Hughes376a7a02011-10-24 18:35:55 -0700415 if (!gJdwpOptions.server && (gJdwpOptions.host.empty() || gJdwpOptions.port == 0)) {
Elliott Hughes3bb81562011-10-21 18:52:59 -0700416 LOG(ERROR) << "Must specify JDWP host and port when server=n: " << options;
417 return false;
418 }
419
420 gJdwpConfigured = true;
421 return true;
422}
423
Elliott Hughesd1cc8362011-10-24 16:58:50 -0700424void Dbg::StartJdwp() {
Elliott Hughesc0f09332012-03-26 13:27:06 -0700425 if (!gJdwpAllowed || !IsJdwpConfigured()) {
Elliott Hughes376a7a02011-10-24 18:35:55 -0700426 // No JDWP for you!
427 return;
428 }
429
Elliott Hughes475fc232011-10-25 15:00:35 -0700430 CHECK(gRegistry == NULL);
431 gRegistry = new ObjectRegistry;
432
Elliott Hughesd1cc8362011-10-24 16:58:50 -0700433 // Init JDWP if the debugger is enabled. This may connect out to a
434 // debugger, passively listen for a debugger, or block waiting for a
435 // debugger.
Elliott Hughes376a7a02011-10-24 18:35:55 -0700436 gJdwpState = JDWP::JdwpState::Create(&gJdwpOptions);
437 if (gJdwpState == NULL) {
Elliott Hughesf8a2df72011-12-01 12:19:54 -0800438 // We probably failed because some other process has the port already, which means that
439 // if we don't abort the user is likely to think they're talking to us when they're actually
440 // talking to that other process.
Elliott Hughes3d30d9b2011-12-07 17:35:48 -0800441 LOG(FATAL) << "Debugger thread failed to initialize";
Elliott Hughesd1cc8362011-10-24 16:58:50 -0700442 }
443
444 // If a debugger has already attached, send the "welcome" message.
445 // This may cause us to suspend all threads.
Elliott Hughes376a7a02011-10-24 18:35:55 -0700446 if (gJdwpState->IsActive()) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700447 ScopedObjectAccess soa(Thread::Current());
Elliott Hughes376a7a02011-10-24 18:35:55 -0700448 if (!gJdwpState->PostVMStart()) {
Elliott Hughes3d30d9b2011-12-07 17:35:48 -0800449 LOG(WARNING) << "Failed to post 'start' message to debugger";
Elliott Hughesd1cc8362011-10-24 16:58:50 -0700450 }
451 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700452}
453
Elliott Hughesd1cc8362011-10-24 16:58:50 -0700454void Dbg::StopJdwp() {
Elliott Hughes376a7a02011-10-24 18:35:55 -0700455 delete gJdwpState;
Elliott Hughes475fc232011-10-25 15:00:35 -0700456 delete gRegistry;
457 gRegistry = NULL;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700458}
459
Elliott Hughes767a1472011-10-26 18:49:02 -0700460void Dbg::GcDidFinish() {
461 if (gDdmHpifWhen != HPIF_WHEN_NEVER) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700462 ScopedObjectAccess soa(Thread::Current());
Elliott Hughes81ff3182012-03-23 20:35:56 -0700463 LOG(DEBUG) << "Sending heap info to DDM";
Elliott Hughes7162ad92011-10-27 14:08:42 -0700464 DdmSendHeapInfo(gDdmHpifWhen);
Elliott Hughes767a1472011-10-26 18:49:02 -0700465 }
466 if (gDdmHpsgWhen != HPSG_WHEN_NEVER) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700467 ScopedObjectAccess soa(Thread::Current());
Elliott Hughes81ff3182012-03-23 20:35:56 -0700468 LOG(DEBUG) << "Dumping heap to DDM";
Elliott Hughes6a5bd492011-10-28 14:33:57 -0700469 DdmSendHeapSegments(false);
Elliott Hughes767a1472011-10-26 18:49:02 -0700470 }
471 if (gDdmNhsgWhen != HPSG_WHEN_NEVER) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700472 ScopedObjectAccess soa(Thread::Current());
Elliott Hughes767a1472011-10-26 18:49:02 -0700473 LOG(DEBUG) << "Dumping native heap to DDM";
Elliott Hughes6a5bd492011-10-28 14:33:57 -0700474 DdmSendHeapSegments(true);
Elliott Hughes767a1472011-10-26 18:49:02 -0700475 }
476}
477
Elliott Hughes4ffd3132011-10-24 12:06:42 -0700478void Dbg::SetJdwpAllowed(bool allowed) {
479 gJdwpAllowed = allowed;
480}
481
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700482DebugInvokeReq* Dbg::GetInvokeReq() {
Elliott Hughes475fc232011-10-25 15:00:35 -0700483 return Thread::Current()->GetInvokeReq();
484}
485
486Thread* Dbg::GetDebugThread() {
487 return (gJdwpState != NULL) ? gJdwpState->GetDebugThread() : NULL;
488}
489
490void Dbg::ClearWaitForEventThread() {
491 gJdwpState->ClearWaitForEventThread();
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700492}
493
494void Dbg::Connected() {
Elliott Hughes3bb81562011-10-21 18:52:59 -0700495 CHECK(!gDebuggerConnected);
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -0800496 VLOG(jdwp) << "JDWP has attached";
Elliott Hughes3bb81562011-10-21 18:52:59 -0700497 gDebuggerConnected = true;
Elliott Hughes86964332012-02-15 19:37:42 -0800498 gDisposed = false;
499}
500
501void Dbg::Disposed() {
502 gDisposed = true;
503}
504
505bool Dbg::IsDisposed() {
506 return gDisposed;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700507}
508
Elliott Hughesc0f09332012-03-26 13:27:06 -0700509static void SetDebuggerUpdatesEnabledCallback(Thread* t, void* user_data) {
510 t->SetDebuggerUpdatesEnabled(*reinterpret_cast<bool*>(user_data));
511}
512
513static void SetDebuggerUpdatesEnabled(bool enabled) {
Ian Rogers50b35e22012-10-04 10:09:15 -0700514 MutexLock mu(Thread::Current(), *Locks::thread_list_lock_);
Elliott Hughesf8349362012-06-18 15:00:06 -0700515 Runtime::Current()->GetThreadList()->ForEach(SetDebuggerUpdatesEnabledCallback, &enabled);
Elliott Hughesc0f09332012-03-26 13:27:06 -0700516}
517
Elliott Hughesa2155262011-11-16 16:26:58 -0800518void Dbg::GoActive() {
519 // Enable all debugging features, including scans for breakpoints.
520 // This is a no-op if we're already active.
521 // Only called from the JDWP handler thread.
522 if (gDebuggerActive) {
523 return;
524 }
525
526 LOG(INFO) << "Debugger is active";
527
Elliott Hughesc0f09332012-03-26 13:27:06 -0700528 {
529 // TODO: dalvik only warned if there were breakpoints left over. clear in Dbg::Disconnected?
jeffhao09bfc6a2012-12-11 18:11:43 -0800530 MutexLock mu(Thread::Current(), *Locks::breakpoint_lock_);
Elliott Hughesc0f09332012-03-26 13:27:06 -0700531 CHECK_EQ(gBreakpoints.size(), 0U);
532 }
Elliott Hughesa2155262011-11-16 16:26:58 -0800533
534 gDebuggerActive = true;
Elliott Hughesc0f09332012-03-26 13:27:06 -0700535 SetDebuggerUpdatesEnabled(true);
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700536}
537
538void Dbg::Disconnected() {
Elliott Hughes234ab152011-10-26 14:02:26 -0700539 CHECK(gDebuggerConnected);
540
Elliott Hughesc0f09332012-03-26 13:27:06 -0700541 LOG(INFO) << "Debugger is no longer active";
Elliott Hughes234ab152011-10-26 14:02:26 -0700542
Elliott Hughesc0f09332012-03-26 13:27:06 -0700543 gDebuggerActive = false;
544 SetDebuggerUpdatesEnabled(false);
Elliott Hughes234ab152011-10-26 14:02:26 -0700545
546 gRegistry->Clear();
547 gDebuggerConnected = false;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700548}
549
Elliott Hughesc0f09332012-03-26 13:27:06 -0700550bool Dbg::IsDebuggerActive() {
Elliott Hughes3bb81562011-10-21 18:52:59 -0700551 return gDebuggerActive;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700552}
553
Elliott Hughesc0f09332012-03-26 13:27:06 -0700554bool Dbg::IsJdwpConfigured() {
Elliott Hughes3bb81562011-10-21 18:52:59 -0700555 return gJdwpConfigured;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700556}
557
558int64_t Dbg::LastDebuggerActivity() {
Elliott Hughesca951522011-12-05 12:01:32 -0800559 return gJdwpState->LastDebuggerActivity();
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700560}
561
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700562void Dbg::UndoDebuggerSuspensions() {
Elliott Hughes234ab152011-10-26 14:02:26 -0700563 Runtime::Current()->GetThreadList()->UndoDebuggerSuspensions();
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700564}
565
566void Dbg::Exit(int status) {
Elliott Hughes1bba14f2011-12-01 18:00:36 -0800567 exit(status); // This is all dalvik did.
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700568}
569
Elliott Hughesbfe487b2011-10-26 15:48:55 -0700570void Dbg::VisitRoots(Heap::RootVisitor* visitor, void* arg) {
571 if (gRegistry != NULL) {
572 gRegistry->VisitRoots(visitor, arg);
573 }
574}
575
Elliott Hughes88d63092013-01-09 09:55:54 -0800576std::string Dbg::GetClassName(JDWP::RefTypeId class_id) {
577 Object* o = gRegistry->Get<Object*>(class_id);
Elliott Hughes436e3722012-02-17 20:01:47 -0800578 if (o == NULL) {
579 return "NULL";
580 }
581 if (o == kInvalidObject) {
Elliott Hughes88d63092013-01-09 09:55:54 -0800582 return StringPrintf("invalid object %p", reinterpret_cast<void*>(class_id));
Elliott Hughes436e3722012-02-17 20:01:47 -0800583 }
584 if (!o->IsClass()) {
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -0800585 return StringPrintf("non-class %p", o); // This is only used for debugging output anyway.
586 }
Elliott Hughesc308a5d2012-02-16 17:12:06 -0800587 return DescriptorToName(ClassHelper(o->AsClass()).GetDescriptor());
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700588}
589
Elliott Hughes88d63092013-01-09 09:55:54 -0800590JDWP::JdwpError Dbg::GetClassObject(JDWP::RefTypeId id, JDWP::ObjectId& class_object_id) {
Elliott Hughes436e3722012-02-17 20:01:47 -0800591 JDWP::JdwpError status;
592 Class* c = DecodeClass(id, status);
593 if (c == NULL) {
594 return status;
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -0800595 }
Elliott Hughes88d63092013-01-09 09:55:54 -0800596 class_object_id = gRegistry->Add(c);
Elliott Hughes436e3722012-02-17 20:01:47 -0800597 return JDWP::ERR_NONE;
Elliott Hughes86964332012-02-15 19:37:42 -0800598}
599
Elliott Hughes88d63092013-01-09 09:55:54 -0800600JDWP::JdwpError Dbg::GetSuperclass(JDWP::RefTypeId id, JDWP::RefTypeId& superclass_id) {
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -0800601 JDWP::JdwpError status;
602 Class* c = DecodeClass(id, status);
603 if (c == NULL) {
604 return status;
605 }
606 if (c->IsInterface()) {
607 // http://code.google.com/p/android/issues/detail?id=20856
Elliott Hughes88d63092013-01-09 09:55:54 -0800608 superclass_id = 0;
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -0800609 } else {
Elliott Hughes88d63092013-01-09 09:55:54 -0800610 superclass_id = gRegistry->Add(c->GetSuperClass());
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -0800611 }
612 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700613}
614
Elliott Hughes436e3722012-02-17 20:01:47 -0800615JDWP::JdwpError Dbg::GetClassLoader(JDWP::RefTypeId id, JDWP::ExpandBuf* pReply) {
Elliott Hughes1bba14f2011-12-01 18:00:36 -0800616 Object* o = gRegistry->Get<Object*>(id);
Elliott Hughes436e3722012-02-17 20:01:47 -0800617 if (o == NULL || o == kInvalidObject) {
618 return JDWP::ERR_INVALID_OBJECT;
619 }
620 expandBufAddObjectId(pReply, gRegistry->Add(o->GetClass()->GetClassLoader()));
621 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700622}
623
Elliott Hughes436e3722012-02-17 20:01:47 -0800624JDWP::JdwpError Dbg::GetModifiers(JDWP::RefTypeId id, JDWP::ExpandBuf* pReply) {
625 JDWP::JdwpError status;
626 Class* c = DecodeClass(id, status);
627 if (c == NULL) {
628 return status;
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -0800629 }
Elliott Hughes436e3722012-02-17 20:01:47 -0800630
631 uint32_t access_flags = c->GetAccessFlags() & kAccJavaFlagsMask;
632
633 // Set ACC_SUPER; dex files don't contain this flag, but all classes are supposed to have it set.
634 // Class.getModifiers doesn't return it, but JDWP does, so we set it here.
635 access_flags |= kAccSuper;
636
637 expandBufAdd4BE(pReply, access_flags);
638
639 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700640}
641
Elliott Hughesf327e072013-01-09 16:01:26 -0800642JDWP::JdwpError Dbg::GetMonitorInfo(JDWP::ObjectId object_id, JDWP::ExpandBuf* reply)
643 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
644 Object* o = gRegistry->Get<Object*>(object_id);
645 if (o == NULL || o == kInvalidObject) {
646 return JDWP::ERR_INVALID_OBJECT;
647 }
648
649 // Ensure all threads are suspended while we read objects' lock words.
650 Thread* self = Thread::Current();
651 Locks::mutator_lock_->SharedUnlock(self);
652 Locks::mutator_lock_->ExclusiveLock(self);
653
654 MonitorInfo monitor_info(o);
655
656 Locks::mutator_lock_->ExclusiveUnlock(self);
657 Locks::mutator_lock_->SharedLock(self);
658
659 if (monitor_info.owner != NULL) {
660 expandBufAddObjectId(reply, gRegistry->Add(monitor_info.owner->GetPeer()));
661 } else {
662 expandBufAddObjectId(reply, gRegistry->Add(NULL));
663 }
664 expandBufAdd4BE(reply, monitor_info.entry_count);
665 expandBufAdd4BE(reply, monitor_info.waiters.size());
666 for (size_t i = 0; i < monitor_info.waiters.size(); ++i) {
667 expandBufAddObjectId(reply, gRegistry->Add(monitor_info.waiters[i]->GetPeer()));
668 }
669 return JDWP::ERR_NONE;
670}
671
Elliott Hughes734b8c62013-01-11 15:32:45 -0800672JDWP::JdwpError Dbg::GetOwnedMonitors(JDWP::ObjectId thread_id,
673 std::vector<JDWP::ObjectId>& monitors,
674 std::vector<uint32_t>& stack_depths)
Elliott Hughes4993bbc2013-01-10 15:41:25 -0800675 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
676 ScopedObjectAccessUnchecked soa(Thread::Current());
677 MutexLock mu(soa.Self(), *Locks::thread_list_lock_);
678 Thread* thread;
679 JDWP::JdwpError error = DecodeThread(soa, thread_id, thread);
680 if (error != JDWP::ERR_NONE) {
681 return error;
682 }
683 if (!IsSuspendedForDebugger(soa, thread)) {
684 return JDWP::ERR_THREAD_NOT_SUSPENDED;
685 }
686
687 struct OwnedMonitorVisitor : public StackVisitor {
688 OwnedMonitorVisitor(const ManagedStack* stack,
689 const std::deque<InstrumentationStackFrame>* instrumentation_stack)
690 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_)
Elliott Hughes734b8c62013-01-11 15:32:45 -0800691 : StackVisitor(stack, instrumentation_stack, NULL), current_stack_depth(0) {}
Elliott Hughes4993bbc2013-01-10 15:41:25 -0800692
693 // TODO: Enable annotalysis. We know lock is held in constructor, but abstraction confuses
694 // annotalysis.
695 bool VisitFrame() NO_THREAD_SAFETY_ANALYSIS {
696 if (!GetMethod()->IsRuntimeMethod()) {
697 Monitor::VisitLocks(this, AppendOwnedMonitors, this);
Elliott Hughes734b8c62013-01-11 15:32:45 -0800698 ++current_stack_depth;
Elliott Hughes4993bbc2013-01-10 15:41:25 -0800699 }
700 return true;
701 }
702
703 static void AppendOwnedMonitors(Object* owned_monitor, void* context) {
Elliott Hughes734b8c62013-01-11 15:32:45 -0800704 OwnedMonitorVisitor* visitor = reinterpret_cast<OwnedMonitorVisitor*>(context);
705 visitor->monitors.push_back(owned_monitor);
706 visitor->stack_depths.push_back(visitor->current_stack_depth);
Elliott Hughes4993bbc2013-01-10 15:41:25 -0800707 }
708
Elliott Hughes734b8c62013-01-11 15:32:45 -0800709 size_t current_stack_depth;
Elliott Hughes4993bbc2013-01-10 15:41:25 -0800710 std::vector<Object*> monitors;
Elliott Hughes734b8c62013-01-11 15:32:45 -0800711 std::vector<uint32_t> stack_depths;
Elliott Hughes4993bbc2013-01-10 15:41:25 -0800712 };
713 OwnedMonitorVisitor visitor(thread->GetManagedStack(), thread->GetInstrumentationStack());
714 visitor.WalkStack();
715
716 for (size_t i = 0; i < visitor.monitors.size(); ++i) {
717 monitors.push_back(gRegistry->Add(visitor.monitors[i]));
Elliott Hughes734b8c62013-01-11 15:32:45 -0800718 stack_depths.push_back(visitor.stack_depths[i]);
Elliott Hughes4993bbc2013-01-10 15:41:25 -0800719 }
720
721 return JDWP::ERR_NONE;
722}
723
Elliott Hughesf9501702013-01-11 11:22:27 -0800724JDWP::JdwpError Dbg::GetContendedMonitor(JDWP::ObjectId thread_id, JDWP::ObjectId& contended_monitor)
725 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
726 ScopedObjectAccessUnchecked soa(Thread::Current());
727 MutexLock mu(soa.Self(), *Locks::thread_list_lock_);
728 Thread* thread;
729 JDWP::JdwpError error = DecodeThread(soa, thread_id, thread);
730 if (error != JDWP::ERR_NONE) {
731 return error;
732 }
733 if (!IsSuspendedForDebugger(soa, thread)) {
734 return JDWP::ERR_THREAD_NOT_SUSPENDED;
735 }
736
737 contended_monitor = gRegistry->Add(Monitor::GetContendedMonitor(thread));
738
739 return JDWP::ERR_NONE;
740}
741
Elliott Hughesec0f83d2013-01-15 16:54:08 -0800742JDWP::JdwpError Dbg::GetInstanceCounts(const std::vector<JDWP::RefTypeId>& class_ids,
743 std::vector<uint64_t>& counts)
744 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
745
746 std::vector<Class*> classes;
747 counts.clear();
748 for (size_t i = 0; i < class_ids.size(); ++i) {
749 JDWP::JdwpError status;
750 Class* c = DecodeClass(class_ids[i], status);
751 if (c == NULL) {
752 return status;
753 }
754 classes.push_back(c);
755 counts.push_back(0);
756 }
757
758 Runtime::Current()->GetHeap()->CountInstances(classes, false, &counts[0]);
759 return JDWP::ERR_NONE;
760}
761
Elliott Hughes3b78c942013-01-15 17:35:41 -0800762JDWP::JdwpError Dbg::GetInstances(JDWP::RefTypeId class_id, int32_t max_count, std::vector<JDWP::ObjectId>& instances)
763 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
764 JDWP::JdwpError status;
765 Class* c = DecodeClass(class_id, status);
766 if (c == NULL) {
767 return status;
768 }
769
770 std::vector<Object*> raw_instances;
771 Runtime::Current()->GetHeap()->GetInstances(c, max_count, raw_instances);
772 for (size_t i = 0; i < raw_instances.size(); ++i) {
773 instances.push_back(gRegistry->Add(raw_instances[i]));
774 }
775 return JDWP::ERR_NONE;
776}
777
Elliott Hughes0cbaff52013-01-16 15:28:01 -0800778JDWP::JdwpError Dbg::GetReferringObjects(JDWP::ObjectId object_id, int32_t max_count,
779 std::vector<JDWP::ObjectId>& referring_objects)
780 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
781 Object* o = gRegistry->Get<Object*>(object_id);
782 if (o == NULL || o == kInvalidObject) {
783 return JDWP::ERR_INVALID_OBJECT;
784 }
785
786 std::vector<Object*> raw_instances;
787 Runtime::Current()->GetHeap()->GetReferringObjects(o, max_count, raw_instances);
788 for (size_t i = 0; i < raw_instances.size(); ++i) {
789 referring_objects.push_back(gRegistry->Add(raw_instances[i]));
790 }
791 return JDWP::ERR_NONE;
792}
793
Elliott Hughes88d63092013-01-09 09:55:54 -0800794JDWP::JdwpError Dbg::GetReflectedType(JDWP::RefTypeId class_id, JDWP::ExpandBuf* pReply) {
Elliott Hughes436e3722012-02-17 20:01:47 -0800795 JDWP::JdwpError status;
Elliott Hughes88d63092013-01-09 09:55:54 -0800796 Class* c = DecodeClass(class_id, status);
Elliott Hughes436e3722012-02-17 20:01:47 -0800797 if (c == NULL) {
798 return status;
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -0800799 }
Elliott Hughes436e3722012-02-17 20:01:47 -0800800
801 expandBufAdd1(pReply, c->IsInterface() ? JDWP::TT_INTERFACE : JDWP::TT_CLASS);
Elliott Hughes88d63092013-01-09 09:55:54 -0800802 expandBufAddRefTypeId(pReply, class_id);
Elliott Hughes436e3722012-02-17 20:01:47 -0800803 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700804}
805
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -0800806void Dbg::GetClassList(std::vector<JDWP::RefTypeId>& classes) {
Elliott Hughesa2155262011-11-16 16:26:58 -0800807 // Get the complete list of reference classes (i.e. all classes except
808 // the primitive types).
809 // Returns a newly-allocated buffer full of RefTypeId values.
810 struct ClassListCreator {
Elliott Hughesba8eee12012-01-24 20:25:24 -0800811 explicit ClassListCreator(std::vector<JDWP::RefTypeId>& classes) : classes(classes) {
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -0800812 }
813
Elliott Hughesa2155262011-11-16 16:26:58 -0800814 static bool Visit(Class* c, void* arg) {
815 return reinterpret_cast<ClassListCreator*>(arg)->Visit(c);
816 }
817
818 bool Visit(Class* c) {
819 if (!c->IsPrimitive()) {
820 classes.push_back(static_cast<JDWP::RefTypeId>(gRegistry->Add(c)));
821 }
822 return true;
823 }
824
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -0800825 std::vector<JDWP::RefTypeId>& classes;
Elliott Hughesa2155262011-11-16 16:26:58 -0800826 };
827
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -0800828 ClassListCreator clc(classes);
Elliott Hughesa2155262011-11-16 16:26:58 -0800829 Runtime::Current()->GetClassLinker()->VisitClasses(ClassListCreator::Visit, &clc);
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700830}
831
Elliott Hughes88d63092013-01-09 09:55:54 -0800832JDWP::JdwpError Dbg::GetClassInfo(JDWP::RefTypeId class_id, JDWP::JdwpTypeTag* pTypeTag, uint32_t* pStatus, std::string* pDescriptor) {
Elliott Hughes436e3722012-02-17 20:01:47 -0800833 JDWP::JdwpError status;
Elliott Hughes88d63092013-01-09 09:55:54 -0800834 Class* c = DecodeClass(class_id, status);
Elliott Hughes436e3722012-02-17 20:01:47 -0800835 if (c == NULL) {
836 return status;
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -0800837 }
838
Elliott Hughesa2155262011-11-16 16:26:58 -0800839 if (c->IsArrayClass()) {
840 *pStatus = JDWP::CS_VERIFIED | JDWP::CS_PREPARED;
841 *pTypeTag = JDWP::TT_ARRAY;
842 } else {
843 if (c->IsErroneous()) {
844 *pStatus = JDWP::CS_ERROR;
845 } else {
846 *pStatus = JDWP::CS_VERIFIED | JDWP::CS_PREPARED | JDWP::CS_INITIALIZED;
847 }
848 *pTypeTag = c->IsInterface() ? JDWP::TT_INTERFACE : JDWP::TT_CLASS;
849 }
850
851 if (pDescriptor != NULL) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800852 *pDescriptor = ClassHelper(c).GetDescriptor();
Elliott Hughesa2155262011-11-16 16:26:58 -0800853 }
Elliott Hughes436e3722012-02-17 20:01:47 -0800854 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700855}
856
Elliott Hughesc3b77c72011-12-15 20:56:48 -0800857void Dbg::FindLoadedClassBySignature(const char* descriptor, std::vector<JDWP::RefTypeId>& ids) {
Elliott Hughes6fa602d2011-12-02 17:54:25 -0800858 std::vector<Class*> classes;
859 Runtime::Current()->GetClassLinker()->LookupClasses(descriptor, classes);
860 ids.clear();
861 for (size_t i = 0; i < classes.size(); ++i) {
862 ids.push_back(gRegistry->Add(classes[i]));
863 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700864}
865
Elliott Hughes88d63092013-01-09 09:55:54 -0800866JDWP::JdwpError Dbg::GetReferenceType(JDWP::ObjectId object_id, JDWP::ExpandBuf* pReply) {
867 Object* o = gRegistry->Get<Object*>(object_id);
Elliott Hughes436e3722012-02-17 20:01:47 -0800868 if (o == NULL || o == kInvalidObject) {
Elliott Hughes2435a572012-02-17 16:07:41 -0800869 return JDWP::ERR_INVALID_OBJECT;
Elliott Hughes499c5132011-11-17 14:55:11 -0800870 }
Elliott Hughes2435a572012-02-17 16:07:41 -0800871
872 JDWP::JdwpTypeTag type_tag;
873 if (o->GetClass()->IsArrayClass()) {
874 type_tag = JDWP::TT_ARRAY;
875 } else if (o->GetClass()->IsInterface()) {
876 type_tag = JDWP::TT_INTERFACE;
877 } else {
878 type_tag = JDWP::TT_CLASS;
879 }
880 JDWP::RefTypeId type_id = gRegistry->Add(o->GetClass());
881
882 expandBufAdd1(pReply, type_tag);
883 expandBufAddRefTypeId(pReply, type_id);
884
885 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700886}
887
Elliott Hughes88d63092013-01-09 09:55:54 -0800888JDWP::JdwpError Dbg::GetSignature(JDWP::RefTypeId class_id, std::string& signature) {
Elliott Hughes1fe7afb2012-02-13 17:23:03 -0800889 JDWP::JdwpError status;
Elliott Hughes88d63092013-01-09 09:55:54 -0800890 Class* c = DecodeClass(class_id, status);
Elliott Hughes1fe7afb2012-02-13 17:23:03 -0800891 if (c == NULL) {
892 return status;
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -0800893 }
Elliott Hughes1fe7afb2012-02-13 17:23:03 -0800894 signature = ClassHelper(c).GetDescriptor();
895 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700896}
897
Elliott Hughes88d63092013-01-09 09:55:54 -0800898JDWP::JdwpError Dbg::GetSourceFile(JDWP::RefTypeId class_id, std::string& result) {
Elliott Hughes436e3722012-02-17 20:01:47 -0800899 JDWP::JdwpError status;
Elliott Hughes88d63092013-01-09 09:55:54 -0800900 Class* c = DecodeClass(class_id, status);
Elliott Hughes436e3722012-02-17 20:01:47 -0800901 if (c == NULL) {
902 return status;
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -0800903 }
Elliott Hughes436e3722012-02-17 20:01:47 -0800904 result = ClassHelper(c).GetSourceFile();
905 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700906}
907
Elliott Hughes88d63092013-01-09 09:55:54 -0800908JDWP::JdwpError Dbg::GetObjectTag(JDWP::ObjectId object_id, uint8_t& tag) {
909 Object* o = gRegistry->Get<Object*>(object_id);
Elliott Hughes546b9862012-06-20 16:06:13 -0700910 if (o == kInvalidObject) {
911 return JDWP::ERR_INVALID_OBJECT;
912 }
913 tag = TagFromObject(o);
914 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700915}
916
Elliott Hughesaed4be92011-12-02 16:16:23 -0800917size_t Dbg::GetTagWidth(JDWP::JdwpTag tag) {
Elliott Hughesdbb40792011-11-18 17:05:22 -0800918 switch (tag) {
919 case JDWP::JT_VOID:
920 return 0;
921 case JDWP::JT_BYTE:
922 case JDWP::JT_BOOLEAN:
923 return 1;
924 case JDWP::JT_CHAR:
925 case JDWP::JT_SHORT:
926 return 2;
927 case JDWP::JT_FLOAT:
928 case JDWP::JT_INT:
929 return 4;
930 case JDWP::JT_ARRAY:
931 case JDWP::JT_OBJECT:
932 case JDWP::JT_STRING:
933 case JDWP::JT_THREAD:
934 case JDWP::JT_THREAD_GROUP:
935 case JDWP::JT_CLASS_LOADER:
936 case JDWP::JT_CLASS_OBJECT:
937 return sizeof(JDWP::ObjectId);
938 case JDWP::JT_DOUBLE:
939 case JDWP::JT_LONG:
940 return 8;
941 default:
Elliott Hughes3d30d9b2011-12-07 17:35:48 -0800942 LOG(FATAL) << "Unknown tag " << tag;
Elliott Hughesdbb40792011-11-18 17:05:22 -0800943 return -1;
944 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700945}
946
Elliott Hughes88d63092013-01-09 09:55:54 -0800947JDWP::JdwpError Dbg::GetArrayLength(JDWP::ObjectId array_id, int& length) {
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -0800948 JDWP::JdwpError status;
Elliott Hughes88d63092013-01-09 09:55:54 -0800949 Array* a = DecodeArray(array_id, status);
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -0800950 if (a == NULL) {
951 return status;
Elliott Hughes24437992011-11-30 14:49:33 -0800952 }
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -0800953 length = a->GetLength();
954 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700955}
956
Elliott Hughes88d63092013-01-09 09:55:54 -0800957JDWP::JdwpError Dbg::OutputArray(JDWP::ObjectId array_id, int offset, int count, JDWP::ExpandBuf* pReply) {
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -0800958 JDWP::JdwpError status;
Elliott Hughes88d63092013-01-09 09:55:54 -0800959 Array* a = DecodeArray(array_id, status);
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -0800960 if (a == NULL) {
961 return status;
962 }
Elliott Hughes24437992011-11-30 14:49:33 -0800963
964 if (offset < 0 || count < 0 || offset > a->GetLength() || a->GetLength() - offset < count) {
965 LOG(WARNING) << __FUNCTION__ << " access out of bounds: offset=" << offset << "; count=" << count;
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -0800966 return JDWP::ERR_INVALID_LENGTH;
Elliott Hughes24437992011-11-30 14:49:33 -0800967 }
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800968 std::string descriptor(ClassHelper(a->GetClass()).GetDescriptor());
Elliott Hughes24437992011-11-30 14:49:33 -0800969 JDWP::JdwpTag tag = BasicTagFromDescriptor(descriptor.c_str() + 1);
970
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -0800971 expandBufAdd1(pReply, tag);
972 expandBufAdd4BE(pReply, count);
973
Elliott Hughes24437992011-11-30 14:49:33 -0800974 if (IsPrimitiveTag(tag)) {
975 size_t width = GetTagWidth(tag);
Elliott Hughes24437992011-11-30 14:49:33 -0800976 uint8_t* dst = expandBufAddSpace(pReply, count * width);
977 if (width == 8) {
Ian Rogersa15e67d2012-02-28 13:51:55 -0800978 const uint64_t* src8 = reinterpret_cast<uint64_t*>(a->GetRawData(sizeof(uint64_t)));
Elliott Hughes24437992011-11-30 14:49:33 -0800979 for (int i = 0; i < count; ++i) JDWP::Write8BE(&dst, src8[offset + i]);
980 } else if (width == 4) {
Ian Rogersa15e67d2012-02-28 13:51:55 -0800981 const uint32_t* src4 = reinterpret_cast<uint32_t*>(a->GetRawData(sizeof(uint32_t)));
Elliott Hughes24437992011-11-30 14:49:33 -0800982 for (int i = 0; i < count; ++i) JDWP::Write4BE(&dst, src4[offset + i]);
983 } else if (width == 2) {
Ian Rogersa15e67d2012-02-28 13:51:55 -0800984 const uint16_t* src2 = reinterpret_cast<uint16_t*>(a->GetRawData(sizeof(uint16_t)));
Elliott Hughes24437992011-11-30 14:49:33 -0800985 for (int i = 0; i < count; ++i) JDWP::Write2BE(&dst, src2[offset + i]);
986 } else {
Ian Rogersa15e67d2012-02-28 13:51:55 -0800987 const uint8_t* src = reinterpret_cast<uint8_t*>(a->GetRawData(sizeof(uint8_t)));
Elliott Hughes24437992011-11-30 14:49:33 -0800988 memcpy(dst, &src[offset * width], count * width);
989 }
990 } else {
991 ObjectArray<Object>* oa = a->AsObjectArray<Object>();
992 for (int i = 0; i < count; ++i) {
Elliott Hughesf03b8f62011-12-02 14:26:25 -0800993 Object* element = oa->Get(offset + i);
Elliott Hughes24437992011-11-30 14:49:33 -0800994 JDWP::JdwpTag specific_tag = (element != NULL) ? TagFromObject(element) : tag;
995 expandBufAdd1(pReply, specific_tag);
996 expandBufAddObjectId(pReply, gRegistry->Add(element));
997 }
998 }
999
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -08001000 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001001}
1002
Elliott Hughes88d63092013-01-09 09:55:54 -08001003JDWP::JdwpError Dbg::SetArrayElements(JDWP::ObjectId array_id, int offset, int count,
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001004 const uint8_t* src)
Ian Rogersb726dcb2012-09-05 08:57:23 -07001005 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -08001006 JDWP::JdwpError status;
Elliott Hughes88d63092013-01-09 09:55:54 -08001007 Array* a = DecodeArray(array_id, status);
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -08001008 if (a == NULL) {
1009 return status;
1010 }
Elliott Hughesf03b8f62011-12-02 14:26:25 -08001011
1012 if (offset < 0 || count < 0 || offset > a->GetLength() || a->GetLength() - offset < count) {
1013 LOG(WARNING) << __FUNCTION__ << " access out of bounds: offset=" << offset << "; count=" << count;
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -08001014 return JDWP::ERR_INVALID_LENGTH;
Elliott Hughesf03b8f62011-12-02 14:26:25 -08001015 }
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001016 std::string descriptor(ClassHelper(a->GetClass()).GetDescriptor());
Elliott Hughesf03b8f62011-12-02 14:26:25 -08001017 JDWP::JdwpTag tag = BasicTagFromDescriptor(descriptor.c_str() + 1);
1018
1019 if (IsPrimitiveTag(tag)) {
1020 size_t width = GetTagWidth(tag);
Elliott Hughesf03b8f62011-12-02 14:26:25 -08001021 if (width == 8) {
Ian Rogersa15e67d2012-02-28 13:51:55 -08001022 uint8_t* dst = &(reinterpret_cast<uint8_t*>(a->GetRawData(sizeof(uint64_t)))[offset * width]);
Elliott Hughesf03b8f62011-12-02 14:26:25 -08001023 for (int i = 0; i < count; ++i) {
1024 // Handle potentially non-aligned memory access one byte at a time for ARM's benefit.
1025 uint64_t value;
1026 for (size_t j = 0; j < sizeof(uint64_t); ++j) reinterpret_cast<uint8_t*>(&value)[j] = src[j];
1027 src += sizeof(uint64_t);
1028 JDWP::Write8BE(&dst, value);
1029 }
1030 } else if (width == 4) {
Ian Rogersa15e67d2012-02-28 13:51:55 -08001031 uint8_t* dst = &(reinterpret_cast<uint8_t*>(a->GetRawData(sizeof(uint32_t)))[offset * width]);
Elliott Hughesf03b8f62011-12-02 14:26:25 -08001032 const uint32_t* src4 = reinterpret_cast<const uint32_t*>(src);
1033 for (int i = 0; i < count; ++i) JDWP::Write4BE(&dst, src4[i]);
1034 } else if (width == 2) {
Ian Rogersa15e67d2012-02-28 13:51:55 -08001035 uint8_t* dst = &(reinterpret_cast<uint8_t*>(a->GetRawData(sizeof(uint16_t)))[offset * width]);
Elliott Hughesf03b8f62011-12-02 14:26:25 -08001036 const uint16_t* src2 = reinterpret_cast<const uint16_t*>(src);
1037 for (int i = 0; i < count; ++i) JDWP::Write2BE(&dst, src2[i]);
1038 } else {
Ian Rogersa15e67d2012-02-28 13:51:55 -08001039 uint8_t* dst = &(reinterpret_cast<uint8_t*>(a->GetRawData(sizeof(uint8_t)))[offset * width]);
Elliott Hughesf03b8f62011-12-02 14:26:25 -08001040 memcpy(&dst[offset * width], src, count * width);
1041 }
1042 } else {
1043 ObjectArray<Object>* oa = a->AsObjectArray<Object>();
1044 for (int i = 0; i < count; ++i) {
1045 JDWP::ObjectId id = JDWP::ReadObjectId(&src);
Elliott Hughes436e3722012-02-17 20:01:47 -08001046 Object* o = gRegistry->Get<Object*>(id);
1047 if (o == kInvalidObject) {
1048 return JDWP::ERR_INVALID_OBJECT;
1049 }
1050 oa->Set(offset + i, o);
Elliott Hughesf03b8f62011-12-02 14:26:25 -08001051 }
1052 }
1053
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -08001054 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001055}
1056
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -08001057JDWP::ObjectId Dbg::CreateString(const std::string& str) {
Ian Rogers50b35e22012-10-04 10:09:15 -07001058 return gRegistry->Add(String::AllocFromModifiedUtf8(Thread::Current(), str.c_str()));
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001059}
1060
Elliott Hughes88d63092013-01-09 09:55:54 -08001061JDWP::JdwpError Dbg::CreateObject(JDWP::RefTypeId class_id, JDWP::ObjectId& new_object) {
Elliott Hughes436e3722012-02-17 20:01:47 -08001062 JDWP::JdwpError status;
Elliott Hughes88d63092013-01-09 09:55:54 -08001063 Class* c = DecodeClass(class_id, status);
Elliott Hughes436e3722012-02-17 20:01:47 -08001064 if (c == NULL) {
1065 return status;
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -08001066 }
Ian Rogers50b35e22012-10-04 10:09:15 -07001067 new_object = gRegistry->Add(c->AllocObject(Thread::Current()));
Elliott Hughes436e3722012-02-17 20:01:47 -08001068 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001069}
1070
Elliott Hughesbf13d362011-12-08 15:51:37 -08001071/*
1072 * Used by Eclipse's "Display" view to evaluate "new byte[5]" to get "(byte[]) [0, 0, 0, 0, 0]".
1073 */
Elliott Hughes88d63092013-01-09 09:55:54 -08001074JDWP::JdwpError Dbg::CreateArrayObject(JDWP::RefTypeId array_class_id, uint32_t length,
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001075 JDWP::ObjectId& new_array) {
Elliott Hughes436e3722012-02-17 20:01:47 -08001076 JDWP::JdwpError status;
Elliott Hughes88d63092013-01-09 09:55:54 -08001077 Class* c = DecodeClass(array_class_id, status);
Elliott Hughes436e3722012-02-17 20:01:47 -08001078 if (c == NULL) {
1079 return status;
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -08001080 }
Ian Rogers50b35e22012-10-04 10:09:15 -07001081 new_array = gRegistry->Add(Array::Alloc(Thread::Current(), c, length));
Elliott Hughes436e3722012-02-17 20:01:47 -08001082 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001083}
1084
Elliott Hughes88d63092013-01-09 09:55:54 -08001085bool Dbg::MatchType(JDWP::RefTypeId instance_class_id, JDWP::RefTypeId class_id) {
Elliott Hughes436e3722012-02-17 20:01:47 -08001086 JDWP::JdwpError status;
Elliott Hughes88d63092013-01-09 09:55:54 -08001087 Class* c1 = DecodeClass(instance_class_id, status);
Elliott Hughesa656a0f2012-02-21 18:03:44 -08001088 CHECK(c1 != NULL);
Elliott Hughes88d63092013-01-09 09:55:54 -08001089 Class* c2 = DecodeClass(class_id, status);
Elliott Hughesa656a0f2012-02-21 18:03:44 -08001090 CHECK(c2 != NULL);
1091 return c1->IsAssignableFrom(c2);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001092}
1093
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001094static JDWP::FieldId ToFieldId(const Field* f)
Ian Rogersb726dcb2012-09-05 08:57:23 -07001095 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Elliott Hughes03181a82011-11-17 17:22:21 -08001096#ifdef MOVING_GARBAGE_COLLECTOR
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001097 UNIMPLEMENTED(FATAL);
Elliott Hughes03181a82011-11-17 17:22:21 -08001098#else
1099 return static_cast<JDWP::FieldId>(reinterpret_cast<uintptr_t>(f));
1100#endif
1101}
1102
Mathieu Chartier66f19252012-09-18 08:57:04 -07001103static JDWP::MethodId ToMethodId(const AbstractMethod* m)
Ian Rogersb726dcb2012-09-05 08:57:23 -07001104 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Elliott Hughes03181a82011-11-17 17:22:21 -08001105#ifdef MOVING_GARBAGE_COLLECTOR
1106 UNIMPLEMENTED(FATAL);
1107#else
1108 return static_cast<JDWP::MethodId>(reinterpret_cast<uintptr_t>(m));
1109#endif
1110}
1111
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001112static Field* FromFieldId(JDWP::FieldId fid)
Ian Rogersb726dcb2012-09-05 08:57:23 -07001113 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Elliott Hughesaed4be92011-12-02 16:16:23 -08001114#ifdef MOVING_GARBAGE_COLLECTOR
1115 UNIMPLEMENTED(FATAL);
1116#else
1117 return reinterpret_cast<Field*>(static_cast<uintptr_t>(fid));
1118#endif
1119}
1120
Mathieu Chartier66f19252012-09-18 08:57:04 -07001121static AbstractMethod* FromMethodId(JDWP::MethodId mid)
Ian Rogersb726dcb2012-09-05 08:57:23 -07001122 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Elliott Hughes03181a82011-11-17 17:22:21 -08001123#ifdef MOVING_GARBAGE_COLLECTOR
1124 UNIMPLEMENTED(FATAL);
1125#else
Mathieu Chartier66f19252012-09-18 08:57:04 -07001126 return reinterpret_cast<AbstractMethod*>(static_cast<uintptr_t>(mid));
Elliott Hughes03181a82011-11-17 17:22:21 -08001127#endif
1128}
1129
Mathieu Chartier66f19252012-09-18 08:57:04 -07001130static void SetLocation(JDWP::JdwpLocation& location, AbstractMethod* m, uint32_t dex_pc)
Ian Rogersb726dcb2012-09-05 08:57:23 -07001131 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08001132 if (m == NULL) {
1133 memset(&location, 0, sizeof(location));
1134 } else {
1135 Class* c = m->GetDeclaringClass();
Elliott Hughes74847412012-06-20 18:10:21 -07001136 location.type_tag = c->IsInterface() ? JDWP::TT_INTERFACE : JDWP::TT_CLASS;
1137 location.class_id = gRegistry->Add(c);
1138 location.method_id = ToMethodId(m);
Ian Rogers0399dde2012-06-06 17:09:28 -07001139 location.dex_pc = dex_pc;
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08001140 }
Elliott Hughesd07986f2011-12-06 18:27:45 -08001141}
1142
Elliott Hughesa96836a2013-01-17 12:27:49 -08001143std::string Dbg::GetMethodName(JDWP::MethodId method_id)
Ian Rogersb726dcb2012-09-05 08:57:23 -07001144 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Elliott Hughes88d63092013-01-09 09:55:54 -08001145 AbstractMethod* m = FromMethodId(method_id);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001146 return MethodHelper(m).GetName();
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001147}
1148
Elliott Hughesa96836a2013-01-17 12:27:49 -08001149std::string Dbg::GetFieldName(JDWP::FieldId field_id)
1150 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
1151 Field* f = FromFieldId(field_id);
1152 return FieldHelper(f).GetName();
1153}
1154
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001155/*
1156 * Augment the access flags for synthetic methods and fields by setting
1157 * the (as described by the spec) "0xf0000000 bit". Also, strip out any
1158 * flags not specified by the Java programming language.
1159 */
1160static uint32_t MangleAccessFlags(uint32_t accessFlags) {
1161 accessFlags &= kAccJavaFlagsMask;
1162 if ((accessFlags & kAccSynthetic) != 0) {
1163 accessFlags |= 0xf0000000;
1164 }
1165 return accessFlags;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001166}
1167
Elliott Hughesdbb40792011-11-18 17:05:22 -08001168static const uint16_t kEclipseWorkaroundSlot = 1000;
1169
1170/*
1171 * Eclipse appears to expect that the "this" reference is in slot zero.
1172 * If it's not, the "variables" display will show two copies of "this",
1173 * possibly because it gets "this" from SF.ThisObject and then displays
1174 * all locals with nonzero slot numbers.
1175 *
1176 * So, we remap the item in slot 0 to 1000, and remap "this" to zero. On
1177 * SF.GetValues / SF.SetValues we map them back.
Elliott Hughesc5b734a2011-12-01 17:20:58 -08001178 *
1179 * TODO: jdb uses the value to determine whether a variable is a local or an argument,
1180 * by checking whether it's less than the number of arguments. To make that work, we'd
1181 * have to "mangle" all the arguments to come first, not just the implicit argument 'this'.
Elliott Hughesdbb40792011-11-18 17:05:22 -08001182 */
1183static uint16_t MangleSlot(uint16_t slot, const char* name) {
1184 uint16_t newSlot = slot;
1185 if (strcmp(name, "this") == 0) {
1186 newSlot = 0;
1187 } else if (slot == 0) {
1188 newSlot = kEclipseWorkaroundSlot;
1189 }
1190 return newSlot;
1191}
1192
Mathieu Chartier66f19252012-09-18 08:57:04 -07001193static uint16_t DemangleSlot(uint16_t slot, AbstractMethod* m)
Ian Rogersb726dcb2012-09-05 08:57:23 -07001194 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Elliott Hughesdbb40792011-11-18 17:05:22 -08001195 if (slot == kEclipseWorkaroundSlot) {
Elliott Hughes68fdbd02011-11-29 19:22:47 -08001196 return 0;
Elliott Hughesdbb40792011-11-18 17:05:22 -08001197 } else if (slot == 0) {
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08001198 const DexFile::CodeItem* code_item = MethodHelper(m).GetCodeItem();
Elliott Hughescaf76542012-06-28 16:08:22 -07001199 CHECK(code_item != NULL) << PrettyMethod(m);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001200 return code_item->registers_size_ - code_item->ins_size_;
Elliott Hughesdbb40792011-11-18 17:05:22 -08001201 }
Elliott Hughes68fdbd02011-11-29 19:22:47 -08001202 return slot;
Elliott Hughesdbb40792011-11-18 17:05:22 -08001203}
1204
Elliott Hughes88d63092013-01-09 09:55:54 -08001205JDWP::JdwpError Dbg::OutputDeclaredFields(JDWP::RefTypeId class_id, bool with_generic, JDWP::ExpandBuf* pReply) {
Elliott Hughes436e3722012-02-17 20:01:47 -08001206 JDWP::JdwpError status;
Elliott Hughes88d63092013-01-09 09:55:54 -08001207 Class* c = DecodeClass(class_id, status);
Elliott Hughes436e3722012-02-17 20:01:47 -08001208 if (c == NULL) {
1209 return status;
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -08001210 }
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001211
1212 size_t instance_field_count = c->NumInstanceFields();
1213 size_t static_field_count = c->NumStaticFields();
1214
1215 expandBufAdd4BE(pReply, instance_field_count + static_field_count);
1216
1217 for (size_t i = 0; i < instance_field_count + static_field_count; ++i) {
1218 Field* f = (i < instance_field_count) ? c->GetInstanceField(i) : c->GetStaticField(i - instance_field_count);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001219 FieldHelper fh(f);
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001220 expandBufAddFieldId(pReply, ToFieldId(f));
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001221 expandBufAddUtf8String(pReply, fh.GetName());
1222 expandBufAddUtf8String(pReply, fh.GetTypeDescriptor());
Elliott Hughesc5b734a2011-12-01 17:20:58 -08001223 if (with_generic) {
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001224 static const char genericSignature[1] = "";
1225 expandBufAddUtf8String(pReply, genericSignature);
1226 }
1227 expandBufAdd4BE(pReply, MangleAccessFlags(f->GetAccessFlags()));
1228 }
Elliott Hughes436e3722012-02-17 20:01:47 -08001229 return JDWP::ERR_NONE;
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001230}
1231
Elliott Hughes88d63092013-01-09 09:55:54 -08001232JDWP::JdwpError Dbg::OutputDeclaredMethods(JDWP::RefTypeId class_id, bool with_generic,
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001233 JDWP::ExpandBuf* pReply) {
Elliott Hughes436e3722012-02-17 20:01:47 -08001234 JDWP::JdwpError status;
Elliott Hughes88d63092013-01-09 09:55:54 -08001235 Class* c = DecodeClass(class_id, status);
Elliott Hughes436e3722012-02-17 20:01:47 -08001236 if (c == NULL) {
1237 return status;
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -08001238 }
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001239
1240 size_t direct_method_count = c->NumDirectMethods();
1241 size_t virtual_method_count = c->NumVirtualMethods();
1242
1243 expandBufAdd4BE(pReply, direct_method_count + virtual_method_count);
1244
1245 for (size_t i = 0; i < direct_method_count + virtual_method_count; ++i) {
Mathieu Chartier66f19252012-09-18 08:57:04 -07001246 AbstractMethod* m = (i < direct_method_count) ? c->GetDirectMethod(i) : c->GetVirtualMethod(i - direct_method_count);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001247 MethodHelper mh(m);
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001248 expandBufAddMethodId(pReply, ToMethodId(m));
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001249 expandBufAddUtf8String(pReply, mh.GetName());
Elliott Hughes4740cdf2011-12-07 14:07:12 -08001250 expandBufAddUtf8String(pReply, mh.GetSignature());
Elliott Hughesc5b734a2011-12-01 17:20:58 -08001251 if (with_generic) {
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001252 static const char genericSignature[1] = "";
1253 expandBufAddUtf8String(pReply, genericSignature);
1254 }
1255 expandBufAdd4BE(pReply, MangleAccessFlags(m->GetAccessFlags()));
1256 }
Elliott Hughes436e3722012-02-17 20:01:47 -08001257 return JDWP::ERR_NONE;
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001258}
1259
Elliott Hughes88d63092013-01-09 09:55:54 -08001260JDWP::JdwpError Dbg::OutputDeclaredInterfaces(JDWP::RefTypeId class_id, JDWP::ExpandBuf* pReply) {
Elliott Hughes436e3722012-02-17 20:01:47 -08001261 JDWP::JdwpError status;
Elliott Hughes88d63092013-01-09 09:55:54 -08001262 Class* c = DecodeClass(class_id, status);
Elliott Hughes436e3722012-02-17 20:01:47 -08001263 if (c == NULL) {
1264 return status;
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -08001265 }
Elliott Hughes436e3722012-02-17 20:01:47 -08001266
1267 ClassHelper kh(c);
Ian Rogersd24e2642012-06-06 21:21:43 -07001268 size_t interface_count = kh.NumDirectInterfaces();
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001269 expandBufAdd4BE(pReply, interface_count);
1270 for (size_t i = 0; i < interface_count; ++i) {
Ian Rogersd24e2642012-06-06 21:21:43 -07001271 expandBufAddRefTypeId(pReply, gRegistry->Add(kh.GetDirectInterface(i)));
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001272 }
Elliott Hughes436e3722012-02-17 20:01:47 -08001273 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001274}
1275
Elliott Hughes88d63092013-01-09 09:55:54 -08001276void Dbg::OutputLineTable(JDWP::RefTypeId, JDWP::MethodId method_id, JDWP::ExpandBuf* pReply)
Ian Rogersb726dcb2012-09-05 08:57:23 -07001277 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Elliott Hughes03181a82011-11-17 17:22:21 -08001278 struct DebugCallbackContext {
1279 int numItems;
1280 JDWP::ExpandBuf* pReply;
1281
Elliott Hughes2435a572012-02-17 16:07:41 -08001282 static bool Callback(void* context, uint32_t address, uint32_t line_number) {
Elliott Hughes03181a82011-11-17 17:22:21 -08001283 DebugCallbackContext* pContext = reinterpret_cast<DebugCallbackContext*>(context);
1284 expandBufAdd8BE(pContext->pReply, address);
Elliott Hughes2435a572012-02-17 16:07:41 -08001285 expandBufAdd4BE(pContext->pReply, line_number);
Elliott Hughes03181a82011-11-17 17:22:21 -08001286 pContext->numItems++;
1287 return true;
1288 }
1289 };
Elliott Hughes88d63092013-01-09 09:55:54 -08001290 AbstractMethod* m = FromMethodId(method_id);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001291 MethodHelper mh(m);
Elliott Hughes03181a82011-11-17 17:22:21 -08001292 uint64_t start, end;
1293 if (m->IsNative()) {
1294 start = -1;
1295 end = -1;
1296 } else {
1297 start = 0;
jeffhao14f0db92012-12-14 17:50:42 -08001298 // Return the index of the last instruction
1299 end = mh.GetCodeItem()->insns_size_in_code_units_ - 1;
Elliott Hughes03181a82011-11-17 17:22:21 -08001300 }
1301
1302 expandBufAdd8BE(pReply, start);
1303 expandBufAdd8BE(pReply, end);
1304
1305 // Add numLines later
1306 size_t numLinesOffset = expandBufGetLength(pReply);
1307 expandBufAdd4BE(pReply, 0);
1308
1309 DebugCallbackContext context;
1310 context.numItems = 0;
1311 context.pReply = pReply;
1312
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001313 mh.GetDexFile().DecodeDebugInfo(mh.GetCodeItem(), m->IsStatic(), m->GetDexMethodIndex(),
1314 DebugCallbackContext::Callback, NULL, &context);
Elliott Hughes03181a82011-11-17 17:22:21 -08001315
1316 JDWP::Set4BE(expandBufGetBuffer(pReply) + numLinesOffset, context.numItems);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001317}
1318
Elliott Hughes88d63092013-01-09 09:55:54 -08001319void Dbg::OutputVariableTable(JDWP::RefTypeId, JDWP::MethodId method_id, bool with_generic, JDWP::ExpandBuf* pReply) {
Elliott Hughesdbb40792011-11-18 17:05:22 -08001320 struct DebugCallbackContext {
Elliott Hughesdbb40792011-11-18 17:05:22 -08001321 JDWP::ExpandBuf* pReply;
Elliott Hughesc5b734a2011-12-01 17:20:58 -08001322 size_t variable_count;
1323 bool with_generic;
Elliott Hughesdbb40792011-11-18 17:05:22 -08001324
Elliott Hughesc5b734a2011-12-01 17:20:58 -08001325 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 -08001326 DebugCallbackContext* pContext = reinterpret_cast<DebugCallbackContext*>(context);
1327
Elliott Hughesad3da692012-02-24 16:51:35 -08001328 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 -08001329
Elliott Hughes68fdbd02011-11-29 19:22:47 -08001330 slot = MangleSlot(slot, name);
1331
Elliott Hughesdbb40792011-11-18 17:05:22 -08001332 expandBufAdd8BE(pContext->pReply, startAddress);
1333 expandBufAddUtf8String(pContext->pReply, name);
1334 expandBufAddUtf8String(pContext->pReply, descriptor);
Elliott Hughesc5b734a2011-12-01 17:20:58 -08001335 if (pContext->with_generic) {
Elliott Hughesdbb40792011-11-18 17:05:22 -08001336 expandBufAddUtf8String(pContext->pReply, signature);
1337 }
1338 expandBufAdd4BE(pContext->pReply, endAddress - startAddress);
1339 expandBufAdd4BE(pContext->pReply, slot);
1340
Elliott Hughesc5b734a2011-12-01 17:20:58 -08001341 ++pContext->variable_count;
Elliott Hughesdbb40792011-11-18 17:05:22 -08001342 }
1343 };
Elliott Hughes88d63092013-01-09 09:55:54 -08001344 AbstractMethod* m = FromMethodId(method_id);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001345 MethodHelper mh(m);
1346 const DexFile::CodeItem* code_item = mh.GetCodeItem();
Elliott Hughesdbb40792011-11-18 17:05:22 -08001347
Elliott Hughesc5b734a2011-12-01 17:20:58 -08001348 // arg_count considers doubles and longs to take 2 units.
1349 // variable_count considers everything to take 1 unit.
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001350 std::string shorty(mh.GetShorty());
Ian Rogers2fa6b2e2012-10-17 00:10:17 -07001351 expandBufAdd4BE(pReply, AbstractMethod::NumArgRegisters(shorty));
Elliott Hughesdbb40792011-11-18 17:05:22 -08001352
Elliott Hughesc5b734a2011-12-01 17:20:58 -08001353 // We don't know the total number of variables yet, so leave a blank and update it later.
1354 size_t variable_count_offset = expandBufGetLength(pReply);
Elliott Hughesdbb40792011-11-18 17:05:22 -08001355 expandBufAdd4BE(pReply, 0);
1356
1357 DebugCallbackContext context;
Elliott Hughesdbb40792011-11-18 17:05:22 -08001358 context.pReply = pReply;
Elliott Hughesc5b734a2011-12-01 17:20:58 -08001359 context.variable_count = 0;
1360 context.with_generic = with_generic;
Elliott Hughesdbb40792011-11-18 17:05:22 -08001361
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001362 mh.GetDexFile().DecodeDebugInfo(code_item, m->IsStatic(), m->GetDexMethodIndex(), NULL,
1363 DebugCallbackContext::Callback, &context);
Elliott Hughesdbb40792011-11-18 17:05:22 -08001364
Elliott Hughesc5b734a2011-12-01 17:20:58 -08001365 JDWP::Set4BE(expandBufGetBuffer(pReply) + variable_count_offset, context.variable_count);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001366}
1367
Elliott Hughes9777ba22013-01-17 09:04:19 -08001368JDWP::JdwpError Dbg::GetBytecodes(JDWP::RefTypeId, JDWP::MethodId method_id,
1369 std::vector<uint8_t>& bytecodes)
1370 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
1371 AbstractMethod* m = FromMethodId(method_id);
1372 if (m == NULL) {
1373 return JDWP::ERR_INVALID_METHODID;
1374 }
1375 MethodHelper mh(m);
1376 const DexFile::CodeItem* code_item = mh.GetCodeItem();
1377 size_t byte_count = code_item->insns_size_in_code_units_ * 2;
1378 const uint8_t* begin = reinterpret_cast<const uint8_t*>(code_item->insns_);
1379 const uint8_t* end = begin + byte_count;
1380 for (const uint8_t* p = begin; p != end; ++p) {
1381 bytecodes.push_back(*p);
1382 }
1383 return JDWP::ERR_NONE;
1384}
1385
Elliott Hughes88d63092013-01-09 09:55:54 -08001386JDWP::JdwpTag Dbg::GetFieldBasicTag(JDWP::FieldId field_id) {
1387 return BasicTagFromDescriptor(FieldHelper(FromFieldId(field_id)).GetTypeDescriptor());
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001388}
1389
Elliott Hughes88d63092013-01-09 09:55:54 -08001390JDWP::JdwpTag Dbg::GetStaticFieldBasicTag(JDWP::FieldId field_id) {
1391 return BasicTagFromDescriptor(FieldHelper(FromFieldId(field_id)).GetTypeDescriptor());
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001392}
1393
Elliott Hughes88d63092013-01-09 09:55:54 -08001394static JDWP::JdwpError GetFieldValueImpl(JDWP::RefTypeId ref_type_id, JDWP::ObjectId object_id,
1395 JDWP::FieldId field_id, JDWP::ExpandBuf* pReply,
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001396 bool is_static)
Ian Rogersb726dcb2012-09-05 08:57:23 -07001397 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Elliott Hughes0cf74332012-02-23 23:14:00 -08001398 JDWP::JdwpError status;
Elliott Hughes88d63092013-01-09 09:55:54 -08001399 Class* c = DecodeClass(ref_type_id, status);
1400 if (ref_type_id != 0 && c == NULL) {
Elliott Hughes0cf74332012-02-23 23:14:00 -08001401 return status;
1402 }
1403
Elliott Hughes88d63092013-01-09 09:55:54 -08001404 Object* o = gRegistry->Get<Object*>(object_id);
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08001405 if ((!is_static && o == NULL) || o == kInvalidObject) {
1406 return JDWP::ERR_INVALID_OBJECT;
1407 }
Elliott Hughes88d63092013-01-09 09:55:54 -08001408 Field* f = FromFieldId(field_id);
Elliott Hughes0cf74332012-02-23 23:14:00 -08001409
1410 Class* receiver_class = c;
1411 if (receiver_class == NULL && o != NULL) {
1412 receiver_class = o->GetClass();
1413 }
1414 // TODO: should we give up now if receiver_class is NULL?
1415 if (receiver_class != NULL && !f->GetDeclaringClass()->IsAssignableFrom(receiver_class)) {
1416 LOG(INFO) << "ERR_INVALID_FIELDID: " << PrettyField(f) << " " << PrettyClass(receiver_class);
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08001417 return JDWP::ERR_INVALID_FIELDID;
1418 }
Elliott Hughesaed4be92011-12-02 16:16:23 -08001419
Elliott Hughes0cf74332012-02-23 23:14:00 -08001420 // The RI only enforces the static/non-static mismatch in one direction.
1421 // TODO: should we change the tests and check both?
1422 if (is_static) {
1423 if (!f->IsStatic()) {
1424 return JDWP::ERR_INVALID_FIELDID;
1425 }
1426 } else {
1427 if (f->IsStatic()) {
1428 LOG(WARNING) << "Ignoring non-NULL receiver for ObjectReference.SetValues on static field " << PrettyField(f);
Elliott Hughes0cf74332012-02-23 23:14:00 -08001429 }
1430 }
jeffhao0dfbb7e2012-11-28 15:26:03 -08001431 if (f->IsStatic()) {
1432 o = f->GetDeclaringClass();
1433 }
Elliott Hughes0cf74332012-02-23 23:14:00 -08001434
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001435 JDWP::JdwpTag tag = BasicTagFromDescriptor(FieldHelper(f).GetTypeDescriptor());
Elliott Hughesaed4be92011-12-02 16:16:23 -08001436
1437 if (IsPrimitiveTag(tag)) {
1438 expandBufAdd1(pReply, tag);
1439 if (tag == JDWP::JT_BOOLEAN || tag == JDWP::JT_BYTE) {
1440 expandBufAdd1(pReply, f->Get32(o));
1441 } else if (tag == JDWP::JT_CHAR || tag == JDWP::JT_SHORT) {
1442 expandBufAdd2BE(pReply, f->Get32(o));
1443 } else if (tag == JDWP::JT_FLOAT || tag == JDWP::JT_INT) {
1444 expandBufAdd4BE(pReply, f->Get32(o));
1445 } else if (tag == JDWP::JT_DOUBLE || tag == JDWP::JT_LONG) {
1446 expandBufAdd8BE(pReply, f->Get64(o));
1447 } else {
Elliott Hughes3d30d9b2011-12-07 17:35:48 -08001448 LOG(FATAL) << "Unknown tag: " << tag;
Elliott Hughesaed4be92011-12-02 16:16:23 -08001449 }
1450 } else {
1451 Object* value = f->GetObject(o);
1452 expandBufAdd1(pReply, TagFromObject(value));
1453 expandBufAddObjectId(pReply, gRegistry->Add(value));
1454 }
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08001455 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001456}
1457
Elliott Hughes88d63092013-01-09 09:55:54 -08001458JDWP::JdwpError Dbg::GetFieldValue(JDWP::ObjectId object_id, JDWP::FieldId field_id,
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001459 JDWP::ExpandBuf* pReply) {
Elliott Hughes88d63092013-01-09 09:55:54 -08001460 return GetFieldValueImpl(0, object_id, field_id, pReply, false);
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08001461}
1462
Elliott Hughes88d63092013-01-09 09:55:54 -08001463JDWP::JdwpError Dbg::GetStaticFieldValue(JDWP::RefTypeId ref_type_id, JDWP::FieldId field_id, JDWP::ExpandBuf* pReply) {
1464 return GetFieldValueImpl(ref_type_id, 0, field_id, pReply, true);
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08001465}
1466
Elliott Hughes88d63092013-01-09 09:55:54 -08001467static JDWP::JdwpError SetFieldValueImpl(JDWP::ObjectId object_id, JDWP::FieldId field_id,
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001468 uint64_t value, int width, bool is_static)
Ian Rogersb726dcb2012-09-05 08:57:23 -07001469 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Elliott Hughes88d63092013-01-09 09:55:54 -08001470 Object* o = gRegistry->Get<Object*>(object_id);
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08001471 if ((!is_static && o == NULL) || o == kInvalidObject) {
1472 return JDWP::ERR_INVALID_OBJECT;
1473 }
Elliott Hughes88d63092013-01-09 09:55:54 -08001474 Field* f = FromFieldId(field_id);
Elliott Hughes0cf74332012-02-23 23:14:00 -08001475
1476 // The RI only enforces the static/non-static mismatch in one direction.
1477 // TODO: should we change the tests and check both?
1478 if (is_static) {
1479 if (!f->IsStatic()) {
1480 return JDWP::ERR_INVALID_FIELDID;
1481 }
1482 } else {
1483 if (f->IsStatic()) {
1484 LOG(WARNING) << "Ignoring non-NULL receiver for ObjectReference.SetValues on static field " << PrettyField(f);
Elliott Hughes0cf74332012-02-23 23:14:00 -08001485 }
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08001486 }
jeffhao0dfbb7e2012-11-28 15:26:03 -08001487 if (f->IsStatic()) {
1488 o = f->GetDeclaringClass();
1489 }
Elliott Hughesaed4be92011-12-02 16:16:23 -08001490
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001491 JDWP::JdwpTag tag = BasicTagFromDescriptor(FieldHelper(f).GetTypeDescriptor());
Elliott Hughesaed4be92011-12-02 16:16:23 -08001492
1493 if (IsPrimitiveTag(tag)) {
1494 if (tag == JDWP::JT_DOUBLE || tag == JDWP::JT_LONG) {
Elliott Hughes1bac54f2012-03-16 12:48:31 -07001495 CHECK_EQ(width, 8);
Elliott Hughesaed4be92011-12-02 16:16:23 -08001496 f->Set64(o, value);
1497 } else {
Elliott Hughes1bac54f2012-03-16 12:48:31 -07001498 CHECK_LE(width, 4);
Elliott Hughesaed4be92011-12-02 16:16:23 -08001499 f->Set32(o, value);
1500 }
1501 } else {
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -08001502 Object* v = gRegistry->Get<Object*>(value);
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08001503 if (v == kInvalidObject) {
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -08001504 return JDWP::ERR_INVALID_OBJECT;
1505 }
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08001506 if (v != NULL) {
1507 Class* field_type = FieldHelper(f).GetType();
1508 if (!field_type->IsAssignableFrom(v->GetClass())) {
1509 return JDWP::ERR_INVALID_OBJECT;
1510 }
1511 }
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -08001512 f->SetObject(o, v);
Elliott Hughesaed4be92011-12-02 16:16:23 -08001513 }
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -08001514
1515 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001516}
1517
Elliott Hughes88d63092013-01-09 09:55:54 -08001518JDWP::JdwpError Dbg::SetFieldValue(JDWP::ObjectId object_id, JDWP::FieldId field_id, uint64_t value,
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001519 int width) {
Elliott Hughes88d63092013-01-09 09:55:54 -08001520 return SetFieldValueImpl(object_id, field_id, value, width, false);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001521}
1522
Elliott Hughes88d63092013-01-09 09:55:54 -08001523JDWP::JdwpError Dbg::SetStaticFieldValue(JDWP::FieldId field_id, uint64_t value, int width) {
1524 return SetFieldValueImpl(0, field_id, value, width, true);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001525}
1526
Elliott Hughes88d63092013-01-09 09:55:54 -08001527std::string Dbg::StringToUtf8(JDWP::ObjectId string_id) {
1528 String* s = gRegistry->Get<String*>(string_id);
Elliott Hughes68fdbd02011-11-29 19:22:47 -08001529 return s->ToModifiedUtf8();
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001530}
1531
Elliott Hughes221229c2013-01-08 18:17:50 -08001532JDWP::JdwpError Dbg::GetThreadName(JDWP::ObjectId thread_id, std::string& name) {
jeffhaoa77f0f62012-12-05 17:19:31 -08001533 ScopedObjectAccessUnchecked soa(Thread::Current());
1534 MutexLock mu(soa.Self(), *Locks::thread_list_lock_);
Elliott Hughes221229c2013-01-08 18:17:50 -08001535 Thread* thread;
1536 JDWP::JdwpError error = DecodeThread(soa, thread_id, thread);
1537 if (error != JDWP::ERR_NONE && error != JDWP::ERR_THREAD_NOT_ALIVE) {
1538 return error;
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001539 }
Elliott Hughes221229c2013-01-08 18:17:50 -08001540
1541 // We still need to report the zombie threads' names, so we can't just call Thread::GetThreadName.
1542 Object* thread_object = gRegistry->Get<Object*>(thread_id);
1543 Field* java_lang_Thread_name_field = soa.DecodeField(WellKnownClasses::java_lang_Thread_name);
1544 String* s = reinterpret_cast<String*>(java_lang_Thread_name_field->GetObject(thread_object));
1545 if (s != NULL) {
1546 name = s->ToModifiedUtf8();
1547 }
1548 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001549}
1550
Elliott Hughes221229c2013-01-08 18:17:50 -08001551JDWP::JdwpError Dbg::GetThreadGroup(JDWP::ObjectId thread_id, JDWP::ExpandBuf* pReply) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001552 ScopedObjectAccess soa(Thread::Current());
Elliott Hughes221229c2013-01-08 18:17:50 -08001553 Object* thread_object = gRegistry->Get<Object*>(thread_id);
1554 if (thread_object == kInvalidObject) {
Elliott Hughes2435a572012-02-17 16:07:41 -08001555 return JDWP::ERR_INVALID_OBJECT;
1556 }
1557
1558 // Okay, so it's an object, but is it actually a thread?
Ian Rogers50b35e22012-10-04 10:09:15 -07001559 MutexLock mu(soa.Self(), *Locks::thread_list_lock_);
Elliott Hughes221229c2013-01-08 18:17:50 -08001560 Thread* thread;
1561 JDWP::JdwpError error = DecodeThread(soa, thread_id, thread);
1562 if (error == JDWP::ERR_THREAD_NOT_ALIVE) {
1563 // Zombie threads are in the null group.
1564 expandBufAddObjectId(pReply, JDWP::ObjectId(0));
1565 return JDWP::ERR_NONE;
1566 }
1567 if (error != JDWP::ERR_NONE) {
1568 return error;
Elliott Hughes2435a572012-02-17 16:07:41 -08001569 }
Elliott Hughes499c5132011-11-17 14:55:11 -08001570
1571 Class* c = Runtime::Current()->GetClassLinker()->FindSystemClass("Ljava/lang/Thread;");
1572 CHECK(c != NULL);
1573 Field* f = c->FindInstanceField("group", "Ljava/lang/ThreadGroup;");
1574 CHECK(f != NULL);
Elliott Hughes221229c2013-01-08 18:17:50 -08001575 Object* group = f->GetObject(thread_object);
Elliott Hughes499c5132011-11-17 14:55:11 -08001576 CHECK(group != NULL);
Elliott Hughes2435a572012-02-17 16:07:41 -08001577 JDWP::ObjectId thread_group_id = gRegistry->Add(group);
1578
1579 expandBufAddObjectId(pReply, thread_group_id);
1580 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001581}
1582
Elliott Hughes88d63092013-01-09 09:55:54 -08001583std::string Dbg::GetThreadGroupName(JDWP::ObjectId thread_group_id) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001584 ScopedObjectAccess soa(Thread::Current());
Elliott Hughes88d63092013-01-09 09:55:54 -08001585 Object* thread_group = gRegistry->Get<Object*>(thread_group_id);
Elliott Hughes499c5132011-11-17 14:55:11 -08001586 CHECK(thread_group != NULL);
1587
1588 Class* c = Runtime::Current()->GetClassLinker()->FindSystemClass("Ljava/lang/ThreadGroup;");
1589 CHECK(c != NULL);
1590 Field* f = c->FindInstanceField("name", "Ljava/lang/String;");
1591 CHECK(f != NULL);
1592 String* s = reinterpret_cast<String*>(f->GetObject(thread_group));
1593 return s->ToModifiedUtf8();
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001594}
1595
Elliott Hughes88d63092013-01-09 09:55:54 -08001596JDWP::ObjectId Dbg::GetThreadGroupParent(JDWP::ObjectId thread_group_id) {
1597 Object* thread_group = gRegistry->Get<Object*>(thread_group_id);
Elliott Hughes4e235312011-12-02 11:34:15 -08001598 CHECK(thread_group != NULL);
1599
1600 Class* c = Runtime::Current()->GetClassLinker()->FindSystemClass("Ljava/lang/ThreadGroup;");
1601 CHECK(c != NULL);
1602 Field* f = c->FindInstanceField("parent", "Ljava/lang/ThreadGroup;");
1603 CHECK(f != NULL);
1604 Object* parent = f->GetObject(thread_group);
1605 return gRegistry->Add(parent);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001606}
1607
1608JDWP::ObjectId Dbg::GetSystemThreadGroupId() {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001609 ScopedObjectAccessUnchecked soa(Thread::Current());
jeffhao0dfbb7e2012-11-28 15:26:03 -08001610 Field* f = soa.DecodeField(WellKnownClasses::java_lang_ThreadGroup_systemThreadGroup);
1611 Object* group = f->GetObject(f->GetDeclaringClass());
Ian Rogers365c1022012-06-22 15:05:28 -07001612 return gRegistry->Add(group);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001613}
1614
1615JDWP::ObjectId Dbg::GetMainThreadGroupId() {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001616 ScopedObjectAccess soa(Thread::Current());
jeffhao0dfbb7e2012-11-28 15:26:03 -08001617 Field* f = soa.DecodeField(WellKnownClasses::java_lang_ThreadGroup_mainThreadGroup);
1618 Object* group = f->GetObject(f->GetDeclaringClass());
Ian Rogers365c1022012-06-22 15:05:28 -07001619 return gRegistry->Add(group);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001620}
1621
Elliott Hughes221229c2013-01-08 18:17:50 -08001622JDWP::JdwpError Dbg::GetThreadStatus(JDWP::ObjectId thread_id, JDWP::JdwpThreadStatus* pThreadStatus, JDWP::JdwpSuspendStatus* pSuspendStatus) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001623 ScopedObjectAccess soa(Thread::Current());
Elliott Hughes499c5132011-11-17 14:55:11 -08001624
Elliott Hughes9e0c1752013-01-09 14:02:58 -08001625 *pSuspendStatus = JDWP::SUSPEND_STATUS_NOT_SUSPENDED;
1626
Ian Rogers50b35e22012-10-04 10:09:15 -07001627 MutexLock mu(soa.Self(), *Locks::thread_list_lock_);
Elliott Hughes221229c2013-01-08 18:17:50 -08001628 Thread* thread;
1629 JDWP::JdwpError error = DecodeThread(soa, thread_id, thread);
1630 if (error != JDWP::ERR_NONE) {
1631 if (error == JDWP::ERR_THREAD_NOT_ALIVE) {
1632 *pThreadStatus = JDWP::TS_ZOMBIE;
Elliott Hughes221229c2013-01-08 18:17:50 -08001633 return JDWP::ERR_NONE;
1634 }
1635 return error;
Elliott Hughes499c5132011-11-17 14:55:11 -08001636 }
1637
Elliott Hughes9e0c1752013-01-09 14:02:58 -08001638 if (IsSuspendedForDebugger(soa, thread)) {
1639 *pSuspendStatus = JDWP::SUSPEND_STATUS_SUSPENDED;
Elliott Hughes499c5132011-11-17 14:55:11 -08001640 }
1641
Elliott Hughes9e0c1752013-01-09 14:02:58 -08001642 switch (thread->GetState()) {
1643 case kBlocked: *pThreadStatus = JDWP::TS_MONITOR; break;
1644 case kNative: *pThreadStatus = JDWP::TS_RUNNING; break;
1645 case kRunnable: *pThreadStatus = JDWP::TS_RUNNING; break;
1646 case kSleeping: *pThreadStatus = JDWP::TS_SLEEPING; break;
1647 case kStarting: *pThreadStatus = JDWP::TS_ZOMBIE; break;
1648 case kSuspended: *pThreadStatus = JDWP::TS_RUNNING; break;
1649 case kTerminated: *pThreadStatus = JDWP::TS_ZOMBIE; break;
1650 case kTimedWaiting: *pThreadStatus = JDWP::TS_WAIT; break;
1651 case kWaitingForDebuggerSend: *pThreadStatus = JDWP::TS_WAIT; break;
1652 case kWaitingForDebuggerSuspension: *pThreadStatus = JDWP::TS_WAIT; break;
1653 case kWaitingForDebuggerToAttach: *pThreadStatus = JDWP::TS_WAIT; break;
1654 case kWaitingForGcToComplete: *pThreadStatus = JDWP::TS_WAIT; break;
1655 case kWaitingForJniOnLoad: *pThreadStatus = JDWP::TS_WAIT; break;
1656 case kWaitingForSignalCatcherOutput: *pThreadStatus = JDWP::TS_WAIT; break;
1657 case kWaitingInMainDebuggerLoop: *pThreadStatus = JDWP::TS_WAIT; break;
1658 case kWaitingInMainSignalCatcherLoop: *pThreadStatus = JDWP::TS_WAIT; break;
1659 case kWaitingPerformingGc: *pThreadStatus = JDWP::TS_WAIT; break;
1660 case kWaiting: *pThreadStatus = JDWP::TS_WAIT; break;
1661 // Don't add a 'default' here so the compiler can spot incompatible enum changes.
1662 }
Elliott Hughes221229c2013-01-08 18:17:50 -08001663 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001664}
1665
Elliott Hughes221229c2013-01-08 18:17:50 -08001666JDWP::JdwpError Dbg::GetThreadDebugSuspendCount(JDWP::ObjectId thread_id, JDWP::ExpandBuf* pReply) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001667 ScopedObjectAccess soa(Thread::Current());
Ian Rogers50b35e22012-10-04 10:09:15 -07001668 MutexLock mu(soa.Self(), *Locks::thread_list_lock_);
Elliott Hughes221229c2013-01-08 18:17:50 -08001669 Thread* thread;
1670 JDWP::JdwpError error = DecodeThread(soa, thread_id, thread);
1671 if (error != JDWP::ERR_NONE) {
1672 return error;
Elliott Hughes2435a572012-02-17 16:07:41 -08001673 }
Ian Rogers50b35e22012-10-04 10:09:15 -07001674 MutexLock mu2(soa.Self(), *Locks::thread_suspend_count_lock_);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001675 expandBufAdd4BE(pReply, thread->GetDebugSuspendCount());
Elliott Hughes2435a572012-02-17 16:07:41 -08001676 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001677}
1678
Elliott Hughesf9501702013-01-11 11:22:27 -08001679JDWP::JdwpError Dbg::Interrupt(JDWP::ObjectId thread_id) {
1680 ScopedObjectAccess soa(Thread::Current());
1681 MutexLock mu(soa.Self(), *Locks::thread_list_lock_);
1682 Thread* thread;
1683 JDWP::JdwpError error = DecodeThread(soa, thread_id, thread);
1684 if (error != JDWP::ERR_NONE) {
1685 return error;
1686 }
1687 thread->Interrupt();
1688 return JDWP::ERR_NONE;
1689}
1690
Elliott Hughescaf76542012-06-28 16:08:22 -07001691void Dbg::GetThreads(JDWP::ObjectId thread_group_id, std::vector<JDWP::ObjectId>& thread_ids) {
Ian Rogers365c1022012-06-22 15:05:28 -07001692 class ThreadListVisitor {
1693 public:
jeffhao0dfbb7e2012-11-28 15:26:03 -08001694 ThreadListVisitor(const ScopedObjectAccessUnchecked& soa, Object* desired_thread_group,
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001695 std::vector<JDWP::ObjectId>& thread_ids)
Ian Rogersb726dcb2012-09-05 08:57:23 -07001696 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_)
jeffhao0dfbb7e2012-11-28 15:26:03 -08001697 : soa_(soa), desired_thread_group_(desired_thread_group), thread_ids_(thread_ids) {}
Ian Rogers365c1022012-06-22 15:05:28 -07001698
Elliott Hughesa2155262011-11-16 16:26:58 -08001699 static void Visit(Thread* t, void* arg) {
1700 reinterpret_cast<ThreadListVisitor*>(arg)->Visit(t);
1701 }
1702
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001703 // TODO: Enable annotalysis. We know lock is held in constructor, but abstraction confuses
1704 // annotalysis.
1705 void Visit(Thread* t) NO_THREAD_SAFETY_ANALYSIS {
Elliott Hughesa2155262011-11-16 16:26:58 -08001706 if (t == Dbg::GetDebugThread()) {
1707 // Skip the JDWP thread. Some debuggers get bent out of shape when they can't suspend and
1708 // query all threads, so it's easier if we just don't tell them about this thread.
1709 return;
1710 }
Ian Rogerscfaa4552012-11-26 21:00:08 -08001711 Object* peer = t->GetPeer();
jeffhao0dfbb7e2012-11-28 15:26:03 -08001712 if (IsInDesiredThreadGroup(peer)) {
Ian Rogers120f1c72012-09-28 17:17:10 -07001713 thread_ids_.push_back(gRegistry->Add(peer));
Elliott Hughesa2155262011-11-16 16:26:58 -08001714 }
1715 }
1716
Ian Rogers365c1022012-06-22 15:05:28 -07001717 private:
jeffhao0dfbb7e2012-11-28 15:26:03 -08001718 bool IsInDesiredThreadGroup(Object* peer)
1719 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
jeffhao0dfbb7e2012-11-28 15:26:03 -08001720 // peer might be NULL if the thread is still starting up.
1721 if (peer == NULL) {
1722 // We can't tell the debugger about this thread yet.
1723 // TODO: if we identified threads to the debugger by their Thread*
1724 // rather than their peer's Object*, we could fix this.
1725 // Doing so might help us report ZOMBIE threads too.
1726 return false;
1727 }
jeffhaoc1e04902012-12-13 12:41:10 -08001728 // Do we want threads from all thread groups?
1729 if (desired_thread_group_ == NULL) {
1730 return true;
1731 }
jeffhao0dfbb7e2012-11-28 15:26:03 -08001732 Object* group = soa_.DecodeField(WellKnownClasses::java_lang_Thread_group)->GetObject(peer);
1733 return (group == desired_thread_group_);
1734 }
1735
Mathieu Chartierdbe6f462012-09-25 16:54:50 -07001736 const ScopedObjectAccessUnchecked& soa_;
jeffhao0dfbb7e2012-11-28 15:26:03 -08001737 Object* const desired_thread_group_;
Elliott Hughescaf76542012-06-28 16:08:22 -07001738 std::vector<JDWP::ObjectId>& thread_ids_;
Elliott Hughesa2155262011-11-16 16:26:58 -08001739 };
1740
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001741 ScopedObjectAccessUnchecked soa(Thread::Current());
Elliott Hughescaf76542012-06-28 16:08:22 -07001742 Object* thread_group = gRegistry->Get<Object*>(thread_group_id);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001743 ThreadListVisitor tlv(soa, thread_group, thread_ids);
Ian Rogers50b35e22012-10-04 10:09:15 -07001744 MutexLock mu(soa.Self(), *Locks::thread_list_lock_);
Elliott Hughesf8349362012-06-18 15:00:06 -07001745 Runtime::Current()->GetThreadList()->ForEach(ThreadListVisitor::Visit, &tlv);
Elliott Hughescaf76542012-06-28 16:08:22 -07001746}
Elliott Hughesa2155262011-11-16 16:26:58 -08001747
Elliott Hughescaf76542012-06-28 16:08:22 -07001748void Dbg::GetChildThreadGroups(JDWP::ObjectId thread_group_id, std::vector<JDWP::ObjectId>& child_thread_group_ids) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001749 ScopedObjectAccess soa(Thread::Current());
Elliott Hughescaf76542012-06-28 16:08:22 -07001750 Object* thread_group = gRegistry->Get<Object*>(thread_group_id);
1751
1752 // Get the ArrayList<ThreadGroup> "groups" out of this thread group...
1753 Field* groups_field = thread_group->GetClass()->FindInstanceField("groups", "Ljava/util/List;");
1754 Object* groups_array_list = groups_field->GetObject(thread_group);
1755
1756 // Get the array and size out of the ArrayList<ThreadGroup>...
1757 Field* array_field = groups_array_list->GetClass()->FindInstanceField("array", "[Ljava/lang/Object;");
1758 Field* size_field = groups_array_list->GetClass()->FindInstanceField("size", "I");
1759 ObjectArray<Object>* groups_array = array_field->GetObject(groups_array_list)->AsObjectArray<Object>();
1760 const int32_t size = size_field->GetInt(groups_array_list);
1761
1762 // Copy the first 'size' elements out of the array into the result.
1763 for (int32_t i = 0; i < size; ++i) {
1764 child_thread_group_ids.push_back(gRegistry->Add(groups_array->Get(i)));
Elliott Hughesa2155262011-11-16 16:26:58 -08001765 }
1766}
1767
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001768static int GetStackDepth(Thread* thread)
Ian Rogersb726dcb2012-09-05 08:57:23 -07001769 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Ian Rogers0399dde2012-06-06 17:09:28 -07001770 struct CountStackDepthVisitor : public StackVisitor {
1771 CountStackDepthVisitor(const ManagedStack* stack,
Ian Rogers306057f2012-11-26 12:45:53 -08001772 const std::deque<InstrumentationStackFrame>* instrumentation_stack)
jeffhao725a9572012-11-13 18:20:12 -08001773 : StackVisitor(stack, instrumentation_stack, NULL), depth(0) {}
Ian Rogers0399dde2012-06-06 17:09:28 -07001774
1775 bool VisitFrame() {
1776 if (!GetMethod()->IsRuntimeMethod()) {
Elliott Hughesf8a2df72011-12-01 12:19:54 -08001777 ++depth;
1778 }
Elliott Hughes530fa002012-03-12 11:44:49 -07001779 return true;
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001780 }
1781 size_t depth;
1782 };
Elliott Hughes08fc03a2012-06-26 17:34:00 -07001783
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001784 if (kIsDebugBuild) {
Ian Rogers50b35e22012-10-04 10:09:15 -07001785 MutexLock mu(Thread::Current(), *Locks::thread_suspend_count_lock_);
jeffhao09bfc6a2012-12-11 18:11:43 -08001786 CHECK(thread == Thread::Current() || thread->IsSuspended());
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001787 }
jeffhao725a9572012-11-13 18:20:12 -08001788 CountStackDepthVisitor visitor(thread->GetManagedStack(), thread->GetInstrumentationStack());
Ian Rogers0399dde2012-06-06 17:09:28 -07001789 visitor.WalkStack();
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001790 return visitor.depth;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001791}
1792
Elliott Hughes221229c2013-01-08 18:17:50 -08001793JDWP::JdwpError Dbg::GetThreadFrameCount(JDWP::ObjectId thread_id, size_t& result) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001794 ScopedObjectAccess soa(Thread::Current());
jeffhaoa77f0f62012-12-05 17:19:31 -08001795 MutexLock mu(soa.Self(), *Locks::thread_list_lock_);
Elliott Hughes221229c2013-01-08 18:17:50 -08001796 Thread* thread;
1797 JDWP::JdwpError error = DecodeThread(soa, thread_id, thread);
1798 if (error != JDWP::ERR_NONE) {
1799 return error;
1800 }
Elliott Hughesf15f4a02013-01-09 10:09:38 -08001801 if (!IsSuspendedForDebugger(soa, thread)) {
1802 return JDWP::ERR_THREAD_NOT_SUSPENDED;
1803 }
Elliott Hughes221229c2013-01-08 18:17:50 -08001804 result = GetStackDepth(thread);
1805 return JDWP::ERR_NONE;
Elliott Hughes86964332012-02-15 19:37:42 -08001806}
1807
Ian Rogers306057f2012-11-26 12:45:53 -08001808JDWP::JdwpError Dbg::GetThreadFrames(JDWP::ObjectId thread_id, size_t start_frame,
1809 size_t frame_count, JDWP::ExpandBuf* buf) {
Elliott Hughes6e9d22c2012-06-22 15:02:37 -07001810 class GetFrameVisitor : public StackVisitor {
1811 public:
Ian Rogers306057f2012-11-26 12:45:53 -08001812 GetFrameVisitor(const ManagedStack* stack,
1813 const std::deque<InstrumentationStackFrame>* instrumentation_stack,
Elliott Hughes6e9d22c2012-06-22 15:02:37 -07001814 size_t start_frame, size_t frame_count, JDWP::ExpandBuf* buf)
Ian Rogersb726dcb2012-09-05 08:57:23 -07001815 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_)
jeffhao725a9572012-11-13 18:20:12 -08001816 : StackVisitor(stack, instrumentation_stack, NULL), depth_(0),
Elliott Hughes6e9d22c2012-06-22 15:02:37 -07001817 start_frame_(start_frame), frame_count_(frame_count), buf_(buf) {
1818 expandBufAdd4BE(buf_, frame_count_);
Elliott Hughes03181a82011-11-17 17:22:21 -08001819 }
Ian Rogers0399dde2012-06-06 17:09:28 -07001820
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001821 // TODO: Enable annotalysis. We know lock is held in constructor, but abstraction confuses
1822 // annotalysis.
1823 virtual bool VisitFrame() NO_THREAD_SAFETY_ANALYSIS {
Ian Rogers0399dde2012-06-06 17:09:28 -07001824 if (GetMethod()->IsRuntimeMethod()) {
Elliott Hughes530fa002012-03-12 11:44:49 -07001825 return true; // The debugger can't do anything useful with a frame that has no Method*.
Elliott Hughes03181a82011-11-17 17:22:21 -08001826 }
Elliott Hughes6e9d22c2012-06-22 15:02:37 -07001827 if (depth_ >= start_frame_ + frame_count_) {
Elliott Hughes530fa002012-03-12 11:44:49 -07001828 return false;
Elliott Hughes03181a82011-11-17 17:22:21 -08001829 }
Elliott Hughes6e9d22c2012-06-22 15:02:37 -07001830 if (depth_ >= start_frame_) {
1831 JDWP::FrameId frame_id(GetFrameId());
1832 JDWP::JdwpLocation location;
1833 SetLocation(location, GetMethod(), GetDexPc());
Elliott Hughes7baf96f2012-06-22 16:33:50 -07001834 VLOG(jdwp) << StringPrintf(" Frame %3zd: id=%3lld ", depth_, frame_id) << location;
Elliott Hughes6e9d22c2012-06-22 15:02:37 -07001835 expandBufAdd8BE(buf_, frame_id);
1836 expandBufAddLocation(buf_, location);
1837 }
1838 ++depth_;
Elliott Hughes530fa002012-03-12 11:44:49 -07001839 return true;
Elliott Hughes03181a82011-11-17 17:22:21 -08001840 }
Elliott Hughes6e9d22c2012-06-22 15:02:37 -07001841
1842 private:
1843 size_t depth_;
1844 const size_t start_frame_;
1845 const size_t frame_count_;
1846 JDWP::ExpandBuf* buf_;
Elliott Hughes03181a82011-11-17 17:22:21 -08001847 };
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001848
1849 ScopedObjectAccessUnchecked soa(Thread::Current());
jeffhaoa77f0f62012-12-05 17:19:31 -08001850 MutexLock mu(soa.Self(), *Locks::thread_list_lock_);
Elliott Hughes221229c2013-01-08 18:17:50 -08001851 Thread* thread;
1852 JDWP::JdwpError error = DecodeThread(soa, thread_id, thread);
1853 if (error != JDWP::ERR_NONE) {
1854 return error;
1855 }
Elliott Hughesf15f4a02013-01-09 10:09:38 -08001856 if (!IsSuspendedForDebugger(soa, thread)) {
1857 return JDWP::ERR_THREAD_NOT_SUSPENDED;
1858 }
Ian Rogers306057f2012-11-26 12:45:53 -08001859 GetFrameVisitor visitor(thread->GetManagedStack(), thread->GetInstrumentationStack(),
1860 start_frame, frame_count, buf);
Ian Rogers0399dde2012-06-06 17:09:28 -07001861 visitor.WalkStack();
Elliott Hughes6e9d22c2012-06-22 15:02:37 -07001862 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001863}
1864
1865JDWP::ObjectId Dbg::GetThreadSelfId() {
Mathieu Chartierdbe6f462012-09-25 16:54:50 -07001866 ScopedObjectAccessUnchecked soa(Thread::Current());
Ian Rogerscfaa4552012-11-26 21:00:08 -08001867 return gRegistry->Add(soa.Self()->GetPeer());
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001868}
1869
Elliott Hughes475fc232011-10-25 15:00:35 -07001870void Dbg::SuspendVM() {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001871 Runtime::Current()->GetThreadList()->SuspendAllForDebugger();
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001872}
1873
1874void Dbg::ResumeVM() {
Elliott Hughesc61a2672012-06-21 14:52:29 -07001875 Runtime::Current()->GetThreadList()->UndoDebuggerSuspensions();
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001876}
1877
Elliott Hughes221229c2013-01-08 18:17:50 -08001878JDWP::JdwpError Dbg::SuspendThread(JDWP::ObjectId thread_id, bool request_suspension) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001879 ScopedLocalRef<jobject> peer(Thread::Current()->GetJniEnv(), NULL);
1880 {
1881 ScopedObjectAccess soa(Thread::Current());
Elliott Hughes221229c2013-01-08 18:17:50 -08001882 peer.reset(soa.AddLocalReference<jobject>(gRegistry->Get<Object*>(thread_id)));
Elliott Hughes4e235312011-12-02 11:34:15 -08001883 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001884 if (peer.get() == NULL) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001885 return JDWP::ERR_THREAD_NOT_ALIVE;
1886 }
1887 // Suspend thread to build stack trace.
Elliott Hughesf327e072013-01-09 16:01:26 -08001888 bool timed_out;
1889 Thread* thread = Thread::SuspendForDebugger(peer.get(), request_suspension, &timed_out);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001890 if (thread != NULL) {
1891 return JDWP::ERR_NONE;
Elliott Hughesf327e072013-01-09 16:01:26 -08001892 } else if (timed_out) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001893 return JDWP::ERR_INTERNAL;
1894 } else {
1895 return JDWP::ERR_THREAD_NOT_ALIVE;
1896 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001897}
1898
Elliott Hughes221229c2013-01-08 18:17:50 -08001899void Dbg::ResumeThread(JDWP::ObjectId thread_id) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001900 ScopedObjectAccessUnchecked soa(Thread::Current());
Elliott Hughes221229c2013-01-08 18:17:50 -08001901 Object* peer = gRegistry->Get<Object*>(thread_id);
jeffhaoa77f0f62012-12-05 17:19:31 -08001902 Thread* thread;
1903 {
1904 MutexLock mu(soa.Self(), *Locks::thread_list_lock_);
1905 thread = Thread::FromManagedThread(soa, peer);
1906 }
Elliott Hughes4e235312011-12-02 11:34:15 -08001907 if (thread == NULL) {
1908 LOG(WARNING) << "No such thread for resume: " << peer;
1909 return;
1910 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001911 bool needs_resume;
1912 {
Ian Rogers50b35e22012-10-04 10:09:15 -07001913 MutexLock mu2(soa.Self(), *Locks::thread_suspend_count_lock_);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001914 needs_resume = thread->GetSuspendCount() > 0;
1915 }
1916 if (needs_resume) {
Elliott Hughes546b9862012-06-20 16:06:13 -07001917 Runtime::Current()->GetThreadList()->Resume(thread, true);
1918 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001919}
1920
1921void Dbg::SuspendSelf() {
Elliott Hughes475fc232011-10-25 15:00:35 -07001922 Runtime::Current()->GetThreadList()->SuspendSelfForDebugger();
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001923}
1924
Ian Rogers0399dde2012-06-06 17:09:28 -07001925struct GetThisVisitor : public StackVisitor {
Ian Rogers306057f2012-11-26 12:45:53 -08001926 GetThisVisitor(const ManagedStack* stack,
1927 const std::deque<InstrumentationStackFrame>* instrumentation_stack,
Elliott Hughes88d63092013-01-09 09:55:54 -08001928 Context* context, JDWP::FrameId frame_id)
Ian Rogersb726dcb2012-09-05 08:57:23 -07001929 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_)
Elliott Hughes88d63092013-01-09 09:55:54 -08001930 : StackVisitor(stack, instrumentation_stack, context), this_object(NULL), frame_id(frame_id) {}
Ian Rogers0399dde2012-06-06 17:09:28 -07001931
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001932 // TODO: Enable annotalysis. We know lock is held in constructor, but abstraction confuses
1933 // annotalysis.
1934 virtual bool VisitFrame() NO_THREAD_SAFETY_ANALYSIS {
Elliott Hughes6e9d22c2012-06-22 15:02:37 -07001935 if (frame_id != GetFrameId()) {
Ian Rogers0399dde2012-06-06 17:09:28 -07001936 return true; // continue
1937 }
Mathieu Chartier66f19252012-09-18 08:57:04 -07001938 AbstractMethod* m = GetMethod();
Ian Rogers0399dde2012-06-06 17:09:28 -07001939 if (m->IsNative() || m->IsStatic()) {
Elliott Hughes6e9d22c2012-06-22 15:02:37 -07001940 this_object = NULL;
Ian Rogers0399dde2012-06-06 17:09:28 -07001941 } else {
1942 uint16_t reg = DemangleSlot(0, m);
Ian Rogers2bcb4a42012-11-08 10:39:18 -08001943 this_object = reinterpret_cast<Object*>(GetVReg(m, reg, kReferenceVReg));
Ian Rogers0399dde2012-06-06 17:09:28 -07001944 }
1945 return false;
Elliott Hughes86b00102011-12-05 17:54:26 -08001946 }
Ian Rogers0399dde2012-06-06 17:09:28 -07001947
Elliott Hughes6e9d22c2012-06-22 15:02:37 -07001948 Object* this_object;
1949 JDWP::FrameId frame_id;
Ian Rogers0399dde2012-06-06 17:09:28 -07001950};
1951
Mathieu Chartier66f19252012-09-18 08:57:04 -07001952static Object* GetThis(Thread* self, AbstractMethod* m, size_t frame_id)
Ian Rogersb726dcb2012-09-05 08:57:23 -07001953 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Elliott Hughescaf76542012-06-28 16:08:22 -07001954 // TODO: should we return the 'this' we passed through to non-static native methods?
Ian Rogers0399dde2012-06-06 17:09:28 -07001955 if (m->IsNative() || m->IsStatic()) {
1956 return NULL;
1957 }
Elliott Hughescaf76542012-06-28 16:08:22 -07001958
Ian Rogers0399dde2012-06-06 17:09:28 -07001959 UniquePtr<Context> context(Context::Create());
jeffhao725a9572012-11-13 18:20:12 -08001960 GetThisVisitor visitor(self->GetManagedStack(), self->GetInstrumentationStack(), context.get(), frame_id);
Elliott Hughescaf76542012-06-28 16:08:22 -07001961 visitor.WalkStack();
1962 return visitor.this_object;
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08001963}
1964
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001965JDWP::JdwpError Dbg::GetThisObject(JDWP::ObjectId thread_id, JDWP::FrameId frame_id,
1966 JDWP::ObjectId* result) {
1967 ScopedObjectAccessUnchecked soa(Thread::Current());
1968 Thread* thread;
1969 {
Ian Rogers50b35e22012-10-04 10:09:15 -07001970 MutexLock mu(soa.Self(), *Locks::thread_list_lock_);
Elliott Hughes221229c2013-01-08 18:17:50 -08001971 JDWP::JdwpError error = DecodeThread(soa, thread_id, thread);
1972 if (error != JDWP::ERR_NONE) {
1973 return error;
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001974 }
Elliott Hughes9e0c1752013-01-09 14:02:58 -08001975 if (!IsSuspendedForDebugger(soa, thread)) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001976 return JDWP::ERR_THREAD_NOT_SUSPENDED;
1977 }
Elliott Hughes6e9d22c2012-06-22 15:02:37 -07001978 }
Elliott Hughescaf76542012-06-28 16:08:22 -07001979 UniquePtr<Context> context(Context::Create());
jeffhao725a9572012-11-13 18:20:12 -08001980 GetThisVisitor visitor(thread->GetManagedStack(), thread->GetInstrumentationStack(), context.get(), frame_id);
Ian Rogers0399dde2012-06-06 17:09:28 -07001981 visitor.WalkStack();
Elliott Hughes6e9d22c2012-06-22 15:02:37 -07001982 *result = gRegistry->Add(visitor.this_object);
1983 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001984}
1985
Elliott Hughes88d63092013-01-09 09:55:54 -08001986void Dbg::GetLocalValue(JDWP::ObjectId thread_id, JDWP::FrameId frame_id, int slot, JDWP::JdwpTag tag,
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001987 uint8_t* buf, size_t width) {
Ian Rogers0399dde2012-06-06 17:09:28 -07001988 struct GetLocalVisitor : public StackVisitor {
Ian Rogers306057f2012-11-26 12:45:53 -08001989 GetLocalVisitor(const ManagedStack* stack,
1990 const std::deque<InstrumentationStackFrame>* instrumentation_stack,
Elliott Hughes88d63092013-01-09 09:55:54 -08001991 Context* context, JDWP::FrameId frame_id, int slot, JDWP::JdwpTag tag,
Ian Rogersca190662012-06-26 15:45:57 -07001992 uint8_t* buf, size_t width)
Ian Rogersb726dcb2012-09-05 08:57:23 -07001993 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_)
Elliott Hughes88d63092013-01-09 09:55:54 -08001994 : StackVisitor(stack, instrumentation_stack, context), frame_id_(frame_id), slot_(slot), tag_(tag),
Ian Rogersca190662012-06-26 15:45:57 -07001995 buf_(buf), width_(width) {}
1996
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001997 // TODO: Enable annotalysis. We know lock is held in constructor, but abstraction confuses
1998 // annotalysis.
1999 bool VisitFrame() NO_THREAD_SAFETY_ANALYSIS {
Ian Rogers0399dde2012-06-06 17:09:28 -07002000 if (GetFrameId() != frame_id_) {
2001 return true; // Not our frame, carry on.
Elliott Hughesdbb40792011-11-18 17:05:22 -08002002 }
Ian Rogers0399dde2012-06-06 17:09:28 -07002003 // TODO: check that the tag is compatible with the actual type of the slot!
Mathieu Chartier66f19252012-09-18 08:57:04 -07002004 AbstractMethod* m = GetMethod();
Ian Rogers0399dde2012-06-06 17:09:28 -07002005 uint16_t reg = DemangleSlot(slot_, m);
Elliott Hughesdbb40792011-11-18 17:05:22 -08002006
Ian Rogers0399dde2012-06-06 17:09:28 -07002007 switch (tag_) {
2008 case JDWP::JT_BOOLEAN:
2009 {
2010 CHECK_EQ(width_, 1U);
Ian Rogers2bcb4a42012-11-08 10:39:18 -08002011 uint32_t intVal = GetVReg(m, reg, kIntVReg);
Ian Rogers0399dde2012-06-06 17:09:28 -07002012 VLOG(jdwp) << "get boolean local " << reg << " = " << intVal;
2013 JDWP::Set1(buf_+1, intVal != 0);
2014 }
2015 break;
2016 case JDWP::JT_BYTE:
2017 {
2018 CHECK_EQ(width_, 1U);
Ian Rogers2bcb4a42012-11-08 10:39:18 -08002019 uint32_t intVal = GetVReg(m, reg, kIntVReg);
Ian Rogers0399dde2012-06-06 17:09:28 -07002020 VLOG(jdwp) << "get byte local " << reg << " = " << intVal;
2021 JDWP::Set1(buf_+1, intVal);
2022 }
2023 break;
2024 case JDWP::JT_SHORT:
2025 case JDWP::JT_CHAR:
2026 {
2027 CHECK_EQ(width_, 2U);
Ian Rogers2bcb4a42012-11-08 10:39:18 -08002028 uint32_t intVal = GetVReg(m, reg, kIntVReg);
Ian Rogers0399dde2012-06-06 17:09:28 -07002029 VLOG(jdwp) << "get short/char local " << reg << " = " << intVal;
2030 JDWP::Set2BE(buf_+1, intVal);
2031 }
2032 break;
2033 case JDWP::JT_INT:
Ian Rogers2bcb4a42012-11-08 10:39:18 -08002034 {
2035 CHECK_EQ(width_, 4U);
2036 uint32_t intVal = GetVReg(m, reg, kIntVReg);
2037 VLOG(jdwp) << "get int local " << reg << " = " << intVal;
2038 JDWP::Set4BE(buf_+1, intVal);
2039 }
2040 break;
Ian Rogers0399dde2012-06-06 17:09:28 -07002041 case JDWP::JT_FLOAT:
2042 {
2043 CHECK_EQ(width_, 4U);
Ian Rogers2bcb4a42012-11-08 10:39:18 -08002044 uint32_t intVal = GetVReg(m, reg, kFloatVReg);
Ian Rogers0399dde2012-06-06 17:09:28 -07002045 VLOG(jdwp) << "get int/float local " << reg << " = " << intVal;
2046 JDWP::Set4BE(buf_+1, intVal);
2047 }
2048 break;
2049 case JDWP::JT_ARRAY:
2050 {
2051 CHECK_EQ(width_, sizeof(JDWP::ObjectId));
Ian Rogers2bcb4a42012-11-08 10:39:18 -08002052 Object* o = reinterpret_cast<Object*>(GetVReg(m, reg, kReferenceVReg));
Ian Rogers0399dde2012-06-06 17:09:28 -07002053 VLOG(jdwp) << "get array local " << reg << " = " << o;
2054 if (!Runtime::Current()->GetHeap()->IsHeapAddress(o)) {
2055 LOG(FATAL) << "Register " << reg << " expected to hold array: " << o;
2056 }
2057 JDWP::SetObjectId(buf_+1, gRegistry->Add(o));
2058 }
2059 break;
2060 case JDWP::JT_CLASS_LOADER:
2061 case JDWP::JT_CLASS_OBJECT:
2062 case JDWP::JT_OBJECT:
2063 case JDWP::JT_STRING:
2064 case JDWP::JT_THREAD:
2065 case JDWP::JT_THREAD_GROUP:
2066 {
2067 CHECK_EQ(width_, sizeof(JDWP::ObjectId));
Ian Rogers2bcb4a42012-11-08 10:39:18 -08002068 Object* o = reinterpret_cast<Object*>(GetVReg(m, reg, kReferenceVReg));
Ian Rogers0399dde2012-06-06 17:09:28 -07002069 VLOG(jdwp) << "get object local " << reg << " = " << o;
2070 if (!Runtime::Current()->GetHeap()->IsHeapAddress(o)) {
2071 LOG(FATAL) << "Register " << reg << " expected to hold object: " << o;
2072 }
2073 tag_ = TagFromObject(o);
2074 JDWP::SetObjectId(buf_+1, gRegistry->Add(o));
2075 }
2076 break;
2077 case JDWP::JT_DOUBLE:
Ian Rogers2bcb4a42012-11-08 10:39:18 -08002078 {
2079 CHECK_EQ(width_, 8U);
2080 uint32_t lo = GetVReg(m, reg, kDoubleLoVReg);
2081 uint64_t hi = GetVReg(m, reg + 1, kDoubleHiVReg);
2082 uint64_t longVal = (hi << 32) | lo;
2083 VLOG(jdwp) << "get double/long local " << hi << ":" << lo << " = " << longVal;
2084 JDWP::Set8BE(buf_+1, longVal);
2085 }
2086 break;
Ian Rogers0399dde2012-06-06 17:09:28 -07002087 case JDWP::JT_LONG:
2088 {
2089 CHECK_EQ(width_, 8U);
Ian Rogers2bcb4a42012-11-08 10:39:18 -08002090 uint32_t lo = GetVReg(m, reg, kLongLoVReg);
2091 uint64_t hi = GetVReg(m, reg + 1, kLongHiVReg);
Ian Rogers0399dde2012-06-06 17:09:28 -07002092 uint64_t longVal = (hi << 32) | lo;
2093 VLOG(jdwp) << "get double/long local " << hi << ":" << lo << " = " << longVal;
2094 JDWP::Set8BE(buf_+1, longVal);
2095 }
2096 break;
2097 default:
2098 LOG(FATAL) << "Unknown tag " << tag_;
2099 break;
2100 }
2101
2102 // Prepend tag, which may have been updated.
2103 JDWP::Set1(buf_, tag_);
2104 return false;
2105 }
2106
2107 const JDWP::FrameId frame_id_;
2108 const int slot_;
2109 JDWP::JdwpTag tag_;
2110 uint8_t* const buf_;
2111 const size_t width_;
2112 };
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002113
2114 ScopedObjectAccessUnchecked soa(Thread::Current());
jeffhaoa77f0f62012-12-05 17:19:31 -08002115 MutexLock mu(soa.Self(), *Locks::thread_list_lock_);
Elliott Hughes221229c2013-01-08 18:17:50 -08002116 Thread* thread;
2117 JDWP::JdwpError error = DecodeThread(soa, thread_id, thread);
2118 if (error != JDWP::ERR_NONE) {
2119 return;
2120 }
Ian Rogers0399dde2012-06-06 17:09:28 -07002121 UniquePtr<Context> context(Context::Create());
jeffhao725a9572012-11-13 18:20:12 -08002122 GetLocalVisitor visitor(thread->GetManagedStack(), thread->GetInstrumentationStack(), context.get(),
Elliott Hughes88d63092013-01-09 09:55:54 -08002123 frame_id, slot, tag, buf, width);
Ian Rogers0399dde2012-06-06 17:09:28 -07002124 visitor.WalkStack();
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002125}
2126
Elliott Hughes88d63092013-01-09 09:55:54 -08002127void Dbg::SetLocalValue(JDWP::ObjectId thread_id, JDWP::FrameId frame_id, int slot, JDWP::JdwpTag tag,
Ian Rogers0399dde2012-06-06 17:09:28 -07002128 uint64_t value, size_t width) {
2129 struct SetLocalVisitor : public StackVisitor {
Ian Rogers306057f2012-11-26 12:45:53 -08002130 SetLocalVisitor(const ManagedStack* stack, const std::deque<InstrumentationStackFrame>* instrumentation_stack, Context* context,
Ian Rogers0399dde2012-06-06 17:09:28 -07002131 JDWP::FrameId frame_id, int slot, JDWP::JdwpTag tag, uint64_t value,
Ian Rogersca190662012-06-26 15:45:57 -07002132 size_t width)
Ian Rogersb726dcb2012-09-05 08:57:23 -07002133 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_)
jeffhao725a9572012-11-13 18:20:12 -08002134 : StackVisitor(stack, instrumentation_stack, context),
Elliott Hughes08fc03a2012-06-26 17:34:00 -07002135 frame_id_(frame_id), slot_(slot), tag_(tag), value_(value), width_(width) {}
Ian Rogersca190662012-06-26 15:45:57 -07002136
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002137 // TODO: Enable annotalysis. We know lock is held in constructor, but abstraction confuses
2138 // annotalysis.
2139 bool VisitFrame() NO_THREAD_SAFETY_ANALYSIS {
Ian Rogers0399dde2012-06-06 17:09:28 -07002140 if (GetFrameId() != frame_id_) {
2141 return true; // Not our frame, carry on.
2142 }
2143 // TODO: check that the tag is compatible with the actual type of the slot!
Mathieu Chartier66f19252012-09-18 08:57:04 -07002144 AbstractMethod* m = GetMethod();
Ian Rogers0399dde2012-06-06 17:09:28 -07002145 uint16_t reg = DemangleSlot(slot_, m);
2146
2147 switch (tag_) {
2148 case JDWP::JT_BOOLEAN:
2149 case JDWP::JT_BYTE:
2150 CHECK_EQ(width_, 1U);
Ian Rogers2bcb4a42012-11-08 10:39:18 -08002151 SetVReg(m, reg, static_cast<uint32_t>(value_), kIntVReg);
Ian Rogers0399dde2012-06-06 17:09:28 -07002152 break;
2153 case JDWP::JT_SHORT:
2154 case JDWP::JT_CHAR:
2155 CHECK_EQ(width_, 2U);
Ian Rogers2bcb4a42012-11-08 10:39:18 -08002156 SetVReg(m, reg, static_cast<uint32_t>(value_), kIntVReg);
Ian Rogers0399dde2012-06-06 17:09:28 -07002157 break;
2158 case JDWP::JT_INT:
Ian Rogers2bcb4a42012-11-08 10:39:18 -08002159 CHECK_EQ(width_, 4U);
2160 SetVReg(m, reg, static_cast<uint32_t>(value_), kIntVReg);
2161 break;
Ian Rogers0399dde2012-06-06 17:09:28 -07002162 case JDWP::JT_FLOAT:
2163 CHECK_EQ(width_, 4U);
Ian Rogers2bcb4a42012-11-08 10:39:18 -08002164 SetVReg(m, reg, static_cast<uint32_t>(value_), kFloatVReg);
Ian Rogers0399dde2012-06-06 17:09:28 -07002165 break;
2166 case JDWP::JT_ARRAY:
2167 case JDWP::JT_OBJECT:
2168 case JDWP::JT_STRING:
2169 {
2170 CHECK_EQ(width_, sizeof(JDWP::ObjectId));
2171 Object* o = gRegistry->Get<Object*>(static_cast<JDWP::ObjectId>(value_));
2172 if (o == kInvalidObject) {
2173 UNIMPLEMENTED(FATAL) << "return an error code when given an invalid object to store";
2174 }
Ian Rogers2bcb4a42012-11-08 10:39:18 -08002175 SetVReg(m, reg, static_cast<uint32_t>(reinterpret_cast<uintptr_t>(o)), kReferenceVReg);
Ian Rogers0399dde2012-06-06 17:09:28 -07002176 }
2177 break;
2178 case JDWP::JT_DOUBLE:
Ian Rogers2bcb4a42012-11-08 10:39:18 -08002179 CHECK_EQ(width_, 8U);
2180 SetVReg(m, reg, static_cast<uint32_t>(value_), kDoubleLoVReg);
2181 SetVReg(m, reg + 1, static_cast<uint32_t>(value_ >> 32), kDoubleHiVReg);
2182 break;
Ian Rogers0399dde2012-06-06 17:09:28 -07002183 case JDWP::JT_LONG:
2184 CHECK_EQ(width_, 8U);
Ian Rogers2bcb4a42012-11-08 10:39:18 -08002185 SetVReg(m, reg, static_cast<uint32_t>(value_), kLongLoVReg);
2186 SetVReg(m, reg + 1, static_cast<uint32_t>(value_ >> 32), kLongHiVReg);
Ian Rogers0399dde2012-06-06 17:09:28 -07002187 break;
2188 default:
2189 LOG(FATAL) << "Unknown tag " << tag_;
2190 break;
2191 }
2192 return false;
2193 }
2194
2195 const JDWP::FrameId frame_id_;
2196 const int slot_;
2197 const JDWP::JdwpTag tag_;
2198 const uint64_t value_;
2199 const size_t width_;
2200 };
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002201
2202 ScopedObjectAccessUnchecked soa(Thread::Current());
jeffhaoa77f0f62012-12-05 17:19:31 -08002203 MutexLock mu(soa.Self(), *Locks::thread_list_lock_);
Elliott Hughes221229c2013-01-08 18:17:50 -08002204 Thread* thread;
2205 JDWP::JdwpError error = DecodeThread(soa, thread_id, thread);
2206 if (error != JDWP::ERR_NONE) {
2207 return;
2208 }
Elliott Hughes08fc03a2012-06-26 17:34:00 -07002209 UniquePtr<Context> context(Context::Create());
jeffhao725a9572012-11-13 18:20:12 -08002210 SetLocalVisitor visitor(thread->GetManagedStack(), thread->GetInstrumentationStack(), context.get(),
Elliott Hughes88d63092013-01-09 09:55:54 -08002211 frame_id, slot, tag, value, width);
Ian Rogers0399dde2012-06-06 17:09:28 -07002212 visitor.WalkStack();
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002213}
2214
Mathieu Chartier66f19252012-09-18 08:57:04 -07002215void Dbg::PostLocationEvent(const AbstractMethod* m, int dex_pc, Object* this_object, int event_flags) {
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08002216 Class* c = m->GetDeclaringClass();
2217
2218 JDWP::JdwpLocation location;
Elliott Hughes74847412012-06-20 18:10:21 -07002219 location.type_tag = c->IsInterface() ? JDWP::TT_INTERFACE : JDWP::TT_CLASS;
2220 location.class_id = gRegistry->Add(c);
2221 location.method_id = ToMethodId(m);
Elliott Hughes972a47b2012-02-21 18:16:06 -08002222 location.dex_pc = m->IsNative() ? -1 : dex_pc;
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08002223
2224 // Note we use "NoReg" so we don't keep track of references that are
2225 // never actually sent to the debugger. 'this_id' is only used to
2226 // compare against registered events...
2227 JDWP::ObjectId this_id = static_cast<JDWP::ObjectId>(reinterpret_cast<uintptr_t>(this_object));
2228 if (gJdwpState->PostLocationEvent(&location, this_id, event_flags)) {
2229 // ...unless there's a registered event, in which case we
2230 // need to really track the class and 'this'.
2231 gRegistry->Add(c);
2232 gRegistry->Add(this_object);
2233 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002234}
2235
Elliott Hughescaf76542012-06-28 16:08:22 -07002236void Dbg::PostException(Thread* thread,
Mathieu Chartier66f19252012-09-18 08:57:04 -07002237 JDWP::FrameId throw_frame_id, AbstractMethod* throw_method, uint32_t throw_dex_pc,
2238 AbstractMethod* catch_method, uint32_t catch_dex_pc, Throwable* exception) {
Elliott Hughesc0f09332012-03-26 13:27:06 -07002239 if (!IsDebuggerActive()) {
Ian Rogers0ad5bb82011-12-07 10:16:32 -08002240 return;
2241 }
Elliott Hughes4740cdf2011-12-07 14:07:12 -08002242
Elliott Hughesd07986f2011-12-06 18:27:45 -08002243 JDWP::JdwpLocation throw_location;
Elliott Hughescaf76542012-06-28 16:08:22 -07002244 SetLocation(throw_location, throw_method, throw_dex_pc);
Elliott Hughesd07986f2011-12-06 18:27:45 -08002245 JDWP::JdwpLocation catch_location;
Elliott Hughescaf76542012-06-28 16:08:22 -07002246 SetLocation(catch_location, catch_method, catch_dex_pc);
Elliott Hughesd07986f2011-12-06 18:27:45 -08002247
2248 // We need 'this' for InstanceOnly filters.
Elliott Hughescaf76542012-06-28 16:08:22 -07002249 UniquePtr<Context> context(Context::Create());
jeffhao725a9572012-11-13 18:20:12 -08002250 GetThisVisitor visitor(thread->GetManagedStack(), thread->GetInstrumentationStack(), context.get(), throw_frame_id);
Elliott Hughescaf76542012-06-28 16:08:22 -07002251 visitor.WalkStack();
2252 JDWP::ObjectId this_id = gRegistry->Add(visitor.this_object);
Elliott Hughesd07986f2011-12-06 18:27:45 -08002253
2254 /*
2255 * Hand the event to the JDWP exception handler. Note we're using the
2256 * "NoReg" objectID on the exception, which is not strictly correct --
2257 * the exception object WILL be passed up to the debugger if the
2258 * debugger is interested in the event. We do this because the current
2259 * implementation of the debugger object registry never throws anything
2260 * away, and some people were experiencing a fatal build up of exception
2261 * objects when dealing with certain libraries.
2262 */
2263 JDWP::ObjectId exception_id = static_cast<JDWP::ObjectId>(reinterpret_cast<uintptr_t>(exception));
2264 JDWP::RefTypeId exception_class_id = gRegistry->Add(exception->GetClass());
2265
2266 gJdwpState->PostException(&throw_location, exception_id, exception_class_id, &catch_location, this_id);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002267}
2268
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002269void Dbg::PostClassPrepare(Class* c) {
Elliott Hughesc0f09332012-03-26 13:27:06 -07002270 if (!IsDebuggerActive()) {
Elliott Hughes4740cdf2011-12-07 14:07:12 -08002271 return;
2272 }
2273
Elliott Hughes3d30d9b2011-12-07 17:35:48 -08002274 // OLD-TODO - we currently always send both "verified" and "prepared" since
Elliott Hughes4740cdf2011-12-07 14:07:12 -08002275 // debuggers seem to like that. There might be some advantage to honesty,
2276 // since the class may not yet be verified.
2277 int state = JDWP::CS_VERIFIED | JDWP::CS_PREPARED;
2278 JDWP::JdwpTypeTag tag = c->IsInterface() ? JDWP::TT_INTERFACE : JDWP::TT_CLASS;
2279 gJdwpState->PostClassPrepare(tag, gRegistry->Add(c), ClassHelper(c).GetDescriptor(), state);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002280}
2281
Elliott Hughescaf76542012-06-28 16:08:22 -07002282void Dbg::UpdateDebugger(int32_t dex_pc, Thread* self) {
Elliott Hughesc0f09332012-03-26 13:27:06 -07002283 if (!IsDebuggerActive() || dex_pc == -2 /* fake method exit */) {
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08002284 return;
2285 }
2286
Elliott Hughescaf76542012-06-28 16:08:22 -07002287 size_t frame_id;
Mathieu Chartier66f19252012-09-18 08:57:04 -07002288 AbstractMethod* m = self->GetCurrentMethod(NULL, &frame_id);
Elliott Hughescaf76542012-06-28 16:08:22 -07002289 //LOG(INFO) << "UpdateDebugger " << PrettyMethod(m) << "@" << dex_pc << " frame " << frame_id;
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08002290
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08002291 if (dex_pc == -1) {
Elliott Hughes2aa2e392012-02-17 17:15:43 -08002292 // We use a pc of -1 to represent method entry, since we might branch back to pc 0 later.
2293 // This means that for this special notification, there can't be anything else interesting
2294 // going on, so we're done already.
Elliott Hughescaf76542012-06-28 16:08:22 -07002295 Dbg::PostLocationEvent(m, 0, GetThis(self, m, frame_id), kMethodEntry);
Elliott Hughes2aa2e392012-02-17 17:15:43 -08002296 return;
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08002297 }
2298
Elliott Hughes2aa2e392012-02-17 17:15:43 -08002299 int event_flags = 0;
2300
Elliott Hughes86964332012-02-15 19:37:42 -08002301 if (IsBreakpoint(m, dex_pc)) {
2302 event_flags |= kBreakpoint;
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08002303 }
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08002304
jeffhao09bfc6a2012-12-11 18:11:43 -08002305 {
2306 // If the debugger is single-stepping one of our threads, check to
2307 // see if we're that thread and we've reached a step point.
2308 MutexLock mu(Thread::Current(), *Locks::breakpoint_lock_);
2309 if (gSingleStepControl.is_active && gSingleStepControl.thread == self) {
2310 CHECK(!m->IsNative());
2311 if (gSingleStepControl.step_depth == JDWP::SD_INTO) {
2312 // Step into method calls. We break when the line number
2313 // or method pointer changes. If we're in SS_MIN mode, we
2314 // always stop.
2315 if (gSingleStepControl.method != m) {
2316 event_flags |= kSingleStep;
2317 VLOG(jdwp) << "SS new method";
2318 } else if (gSingleStepControl.step_size == JDWP::SS_MIN) {
Elliott Hughes86964332012-02-15 19:37:42 -08002319 event_flags |= kSingleStep;
2320 VLOG(jdwp) << "SS new instruction";
Elliott Hughes2435a572012-02-17 16:07:41 -08002321 } else if (gSingleStepControl.dex_pcs.find(dex_pc) == gSingleStepControl.dex_pcs.end()) {
2322 event_flags |= kSingleStep;
2323 VLOG(jdwp) << "SS new line";
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08002324 }
jeffhao09bfc6a2012-12-11 18:11:43 -08002325 } else if (gSingleStepControl.step_depth == JDWP::SD_OVER) {
2326 // Step over method calls. We break when the line number is
2327 // different and the frame depth is <= the original frame
2328 // depth. (We can't just compare on the method, because we
2329 // might get unrolled past it by an exception, and it's tricky
2330 // to identify recursion.)
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08002331
jeffhao09bfc6a2012-12-11 18:11:43 -08002332 int stack_depth = GetStackDepth(self);
Elliott Hughes86964332012-02-15 19:37:42 -08002333
jeffhao09bfc6a2012-12-11 18:11:43 -08002334 if (stack_depth < gSingleStepControl.stack_depth) {
2335 // popped up one or more frames, always trigger
2336 event_flags |= kSingleStep;
2337 VLOG(jdwp) << "SS method pop";
2338 } else if (stack_depth == gSingleStepControl.stack_depth) {
2339 // same depth, see if we moved
2340 if (gSingleStepControl.step_size == JDWP::SS_MIN) {
2341 event_flags |= kSingleStep;
2342 VLOG(jdwp) << "SS new instruction";
2343 } else if (gSingleStepControl.dex_pcs.find(dex_pc) == gSingleStepControl.dex_pcs.end()) {
2344 event_flags |= kSingleStep;
2345 VLOG(jdwp) << "SS new line";
2346 }
2347 }
2348 } else {
2349 CHECK_EQ(gSingleStepControl.step_depth, JDWP::SD_OUT);
2350 // Return from the current method. We break when the frame
2351 // depth pops up.
2352
2353 // This differs from the "method exit" break in that it stops
2354 // with the PC at the next instruction in the returned-to
2355 // function, rather than the end of the returning function.
2356
2357 int stack_depth = GetStackDepth(self);
2358 if (stack_depth < gSingleStepControl.stack_depth) {
2359 event_flags |= kSingleStep;
2360 VLOG(jdwp) << "SS method pop";
2361 }
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08002362 }
2363 }
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08002364 }
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08002365
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08002366 // Check to see if this is a "return" instruction. JDWP says we should
2367 // send the event *after* the code has been executed, but it also says
2368 // the location we provide is the last instruction. Since the "return"
2369 // instruction has no interesting side effects, we should be safe.
2370 // (We can't just move this down to the returnFromMethod label because
2371 // we potentially need to combine it with other events.)
2372 // We're also not supposed to generate a method exit event if the method
2373 // terminates "with a thrown exception".
Elliott Hughes86964332012-02-15 19:37:42 -08002374 if (dex_pc >= 0) {
2375 const DexFile::CodeItem* code_item = MethodHelper(m).GetCodeItem();
Elliott Hughescaf76542012-06-28 16:08:22 -07002376 CHECK(code_item != NULL) << PrettyMethod(m) << " @" << dex_pc;
Elliott Hughes86964332012-02-15 19:37:42 -08002377 CHECK_LT(dex_pc, static_cast<int32_t>(code_item->insns_size_in_code_units_));
2378 if (Instruction::At(&code_item->insns_[dex_pc])->IsReturn()) {
2379 event_flags |= kMethodExit;
2380 }
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08002381 }
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08002382
2383 // If there's something interesting going on, see if it matches one
2384 // of the debugger filters.
2385 if (event_flags != 0) {
Elliott Hughescaf76542012-06-28 16:08:22 -07002386 Dbg::PostLocationEvent(m, dex_pc, GetThis(self, m, frame_id), event_flags);
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08002387 }
2388}
2389
Elliott Hughes86964332012-02-15 19:37:42 -08002390void Dbg::WatchLocation(const JDWP::JdwpLocation* location) {
jeffhao09bfc6a2012-12-11 18:11:43 -08002391 MutexLock mu(Thread::Current(), *Locks::breakpoint_lock_);
Mathieu Chartier66f19252012-09-18 08:57:04 -07002392 AbstractMethod* m = FromMethodId(location->method_id);
Elliott Hughes972a47b2012-02-21 18:16:06 -08002393 gBreakpoints.push_back(Breakpoint(m, location->dex_pc));
Elliott Hughes86964332012-02-15 19:37:42 -08002394 VLOG(jdwp) << "Set breakpoint #" << (gBreakpoints.size() - 1) << ": " << gBreakpoints[gBreakpoints.size() - 1];
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002395}
2396
Elliott Hughes86964332012-02-15 19:37:42 -08002397void Dbg::UnwatchLocation(const JDWP::JdwpLocation* location) {
jeffhao09bfc6a2012-12-11 18:11:43 -08002398 MutexLock mu(Thread::Current(), *Locks::breakpoint_lock_);
Mathieu Chartier66f19252012-09-18 08:57:04 -07002399 AbstractMethod* m = FromMethodId(location->method_id);
Elliott Hughes86964332012-02-15 19:37:42 -08002400 for (size_t i = 0; i < gBreakpoints.size(); ++i) {
Elliott Hughes972a47b2012-02-21 18:16:06 -08002401 if (gBreakpoints[i].method == m && gBreakpoints[i].dex_pc == location->dex_pc) {
Elliott Hughes86964332012-02-15 19:37:42 -08002402 VLOG(jdwp) << "Removed breakpoint #" << i << ": " << gBreakpoints[i];
2403 gBreakpoints.erase(gBreakpoints.begin() + i);
2404 return;
2405 }
2406 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002407}
2408
Elliott Hughes221229c2013-01-08 18:17:50 -08002409JDWP::JdwpError Dbg::ConfigureStep(JDWP::ObjectId thread_id, JDWP::JdwpStepSize step_size,
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002410 JDWP::JdwpStepDepth step_depth) {
2411 ScopedObjectAccessUnchecked soa(Thread::Current());
jeffhaoa77f0f62012-12-05 17:19:31 -08002412 MutexLock mu(soa.Self(), *Locks::thread_list_lock_);
Elliott Hughes221229c2013-01-08 18:17:50 -08002413 Thread* thread;
2414 JDWP::JdwpError error = DecodeThread(soa, thread_id, thread);
2415 if (error != JDWP::ERR_NONE) {
2416 return error;
Elliott Hughes2435a572012-02-17 16:07:41 -08002417 }
Elliott Hughes86964332012-02-15 19:37:42 -08002418
jeffhao09bfc6a2012-12-11 18:11:43 -08002419 MutexLock mu2(soa.Self(), *Locks::breakpoint_lock_);
Elliott Hughes86964332012-02-15 19:37:42 -08002420 // TODO: there's no theoretical reason why we couldn't support single-stepping
2421 // of multiple threads at once, but we never did so historically.
2422 if (gSingleStepControl.thread != NULL && thread != gSingleStepControl.thread) {
2423 LOG(WARNING) << "single-step already active for " << *gSingleStepControl.thread
2424 << "; switching to " << *thread;
2425 }
2426
Elliott Hughes2435a572012-02-17 16:07:41 -08002427 //
2428 // Work out what Method* we're in, the current line number, and how deep the stack currently
2429 // is for step-out.
2430 //
2431
Ian Rogers0399dde2012-06-06 17:09:28 -07002432 struct SingleStepStackVisitor : public StackVisitor {
2433 SingleStepStackVisitor(const ManagedStack* stack,
Ian Rogers306057f2012-11-26 12:45:53 -08002434 const std::deque<InstrumentationStackFrame>* instrumentation_stack)
jeffhao09bfc6a2012-12-11 18:11:43 -08002435 EXCLUSIVE_LOCKS_REQUIRED(Locks::breakpoint_lock_)
Ian Rogersb726dcb2012-09-05 08:57:23 -07002436 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_)
jeffhao725a9572012-11-13 18:20:12 -08002437 : StackVisitor(stack, instrumentation_stack, NULL) {
Elliott Hughes86964332012-02-15 19:37:42 -08002438 gSingleStepControl.method = NULL;
2439 gSingleStepControl.stack_depth = 0;
2440 }
Ian Rogersca190662012-06-26 15:45:57 -07002441
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002442 // TODO: Enable annotalysis. We know lock is held in constructor, but abstraction confuses
2443 // annotalysis.
2444 bool VisitFrame() NO_THREAD_SAFETY_ANALYSIS {
jeffhao09bfc6a2012-12-11 18:11:43 -08002445 Locks::breakpoint_lock_->AssertHeld(Thread::Current());
Mathieu Chartier66f19252012-09-18 08:57:04 -07002446 const AbstractMethod* m = GetMethod();
Ian Rogers0399dde2012-06-06 17:09:28 -07002447 if (!m->IsRuntimeMethod()) {
Elliott Hughes86964332012-02-15 19:37:42 -08002448 ++gSingleStepControl.stack_depth;
2449 if (gSingleStepControl.method == NULL) {
Elliott Hughes2435a572012-02-17 16:07:41 -08002450 const DexCache* dex_cache = m->GetDeclaringClass()->GetDexCache();
2451 gSingleStepControl.method = m;
2452 gSingleStepControl.line_number = -1;
2453 if (dex_cache != NULL) {
Ian Rogers4445a7e2012-10-05 17:19:13 -07002454 const DexFile& dex_file = *dex_cache->GetDexFile();
Ian Rogers0399dde2012-06-06 17:09:28 -07002455 gSingleStepControl.line_number = dex_file.GetLineNumFromPC(m, GetDexPc());
Elliott Hughes2435a572012-02-17 16:07:41 -08002456 }
Elliott Hughes86964332012-02-15 19:37:42 -08002457 }
2458 }
Elliott Hughes530fa002012-03-12 11:44:49 -07002459 return true;
Elliott Hughes86964332012-02-15 19:37:42 -08002460 }
2461 };
jeffhao725a9572012-11-13 18:20:12 -08002462 SingleStepStackVisitor visitor(thread->GetManagedStack(), thread->GetInstrumentationStack());
Ian Rogers0399dde2012-06-06 17:09:28 -07002463 visitor.WalkStack();
Elliott Hughes86964332012-02-15 19:37:42 -08002464
Elliott Hughes2435a572012-02-17 16:07:41 -08002465 //
2466 // Find the dex_pc values that correspond to the current line, for line-based single-stepping.
2467 //
2468
2469 struct DebugCallbackContext {
jeffhao09bfc6a2012-12-11 18:11:43 -08002470 DebugCallbackContext() EXCLUSIVE_LOCKS_REQUIRED(Locks::breakpoint_lock_) {
Elliott Hughes2435a572012-02-17 16:07:41 -08002471 last_pc_valid = false;
2472 last_pc = 0;
Elliott Hughes2435a572012-02-17 16:07:41 -08002473 }
2474
jeffhao09bfc6a2012-12-11 18:11:43 -08002475 // TODO: Enable annotalysis. We know lock is held in constructor, but abstraction confuses
2476 // annotalysis.
2477 static bool Callback(void* raw_context, uint32_t address, uint32_t line_number) NO_THREAD_SAFETY_ANALYSIS {
2478 Locks::breakpoint_lock_->AssertHeld(Thread::Current());
Elliott Hughes2435a572012-02-17 16:07:41 -08002479 DebugCallbackContext* context = reinterpret_cast<DebugCallbackContext*>(raw_context);
2480 if (static_cast<int32_t>(line_number) == gSingleStepControl.line_number) {
2481 if (!context->last_pc_valid) {
2482 // Everything from this address until the next line change is ours.
2483 context->last_pc = address;
2484 context->last_pc_valid = true;
2485 }
2486 // Otherwise, if we're already in a valid range for this line,
2487 // just keep going (shouldn't really happen)...
2488 } else if (context->last_pc_valid) { // and the line number is new
2489 // Add everything from the last entry up until here to the set
2490 for (uint32_t dex_pc = context->last_pc; dex_pc < address; ++dex_pc) {
2491 gSingleStepControl.dex_pcs.insert(dex_pc);
2492 }
2493 context->last_pc_valid = false;
2494 }
2495 return false; // There may be multiple entries for any given line.
2496 }
2497
jeffhao09bfc6a2012-12-11 18:11:43 -08002498 // TODO: Enable annotalysis. We know lock is held in constructor, but abstraction confuses
2499 // annotalysis.
2500 ~DebugCallbackContext() NO_THREAD_SAFETY_ANALYSIS {
2501 Locks::breakpoint_lock_->AssertHeld(Thread::Current());
Elliott Hughes2435a572012-02-17 16:07:41 -08002502 // If the line number was the last in the position table...
2503 if (last_pc_valid) {
2504 size_t end = MethodHelper(gSingleStepControl.method).GetCodeItem()->insns_size_in_code_units_;
2505 for (uint32_t dex_pc = last_pc; dex_pc < end; ++dex_pc) {
2506 gSingleStepControl.dex_pcs.insert(dex_pc);
2507 }
2508 }
2509 }
2510
2511 bool last_pc_valid;
2512 uint32_t last_pc;
2513 };
Elliott Hughes3e2e1a22012-02-21 11:33:41 -08002514 gSingleStepControl.dex_pcs.clear();
Mathieu Chartier66f19252012-09-18 08:57:04 -07002515 const AbstractMethod* m = gSingleStepControl.method;
Elliott Hughes3e2e1a22012-02-21 11:33:41 -08002516 if (m->IsNative()) {
2517 gSingleStepControl.line_number = -1;
2518 } else {
2519 DebugCallbackContext context;
2520 MethodHelper mh(m);
2521 mh.GetDexFile().DecodeDebugInfo(mh.GetCodeItem(), m->IsStatic(), m->GetDexMethodIndex(),
2522 DebugCallbackContext::Callback, NULL, &context);
2523 }
Elliott Hughes2435a572012-02-17 16:07:41 -08002524
2525 //
2526 // Everything else...
2527 //
2528
Elliott Hughes86964332012-02-15 19:37:42 -08002529 gSingleStepControl.thread = thread;
2530 gSingleStepControl.step_size = step_size;
2531 gSingleStepControl.step_depth = step_depth;
2532 gSingleStepControl.is_active = true;
2533
Elliott Hughes2435a572012-02-17 16:07:41 -08002534 if (VLOG_IS_ON(jdwp)) {
2535 VLOG(jdwp) << "Single-step thread: " << *gSingleStepControl.thread;
2536 VLOG(jdwp) << "Single-step step size: " << gSingleStepControl.step_size;
2537 VLOG(jdwp) << "Single-step step depth: " << gSingleStepControl.step_depth;
2538 VLOG(jdwp) << "Single-step current method: " << PrettyMethod(gSingleStepControl.method);
2539 VLOG(jdwp) << "Single-step current line: " << gSingleStepControl.line_number;
2540 VLOG(jdwp) << "Single-step current stack depth: " << gSingleStepControl.stack_depth;
2541 VLOG(jdwp) << "Single-step dex_pc values:";
2542 for (std::set<uint32_t>::iterator it = gSingleStepControl.dex_pcs.begin() ; it != gSingleStepControl.dex_pcs.end(); ++it) {
Elliott Hughes229feb72012-02-23 13:33:29 -08002543 VLOG(jdwp) << StringPrintf(" %#x", *it);
Elliott Hughes2435a572012-02-17 16:07:41 -08002544 }
2545 }
2546
2547 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002548}
2549
Elliott Hughes221229c2013-01-08 18:17:50 -08002550void Dbg::UnconfigureStep(JDWP::ObjectId /*thread_id*/) {
jeffhao09bfc6a2012-12-11 18:11:43 -08002551 MutexLock mu(Thread::Current(), *Locks::breakpoint_lock_);
Elliott Hughesf8349362012-06-18 15:00:06 -07002552
Elliott Hughes86964332012-02-15 19:37:42 -08002553 gSingleStepControl.is_active = false;
2554 gSingleStepControl.thread = NULL;
Elliott Hughes2435a572012-02-17 16:07:41 -08002555 gSingleStepControl.dex_pcs.clear();
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002556}
2557
Elliott Hughes45651fd2012-02-21 15:48:20 -08002558static char JdwpTagToShortyChar(JDWP::JdwpTag tag) {
2559 switch (tag) {
2560 default:
2561 LOG(FATAL) << "unknown JDWP tag: " << PrintableChar(tag);
2562
2563 // Primitives.
2564 case JDWP::JT_BYTE: return 'B';
2565 case JDWP::JT_CHAR: return 'C';
2566 case JDWP::JT_FLOAT: return 'F';
2567 case JDWP::JT_DOUBLE: return 'D';
2568 case JDWP::JT_INT: return 'I';
2569 case JDWP::JT_LONG: return 'J';
2570 case JDWP::JT_SHORT: return 'S';
2571 case JDWP::JT_VOID: return 'V';
2572 case JDWP::JT_BOOLEAN: return 'Z';
2573
2574 // Reference types.
2575 case JDWP::JT_ARRAY:
2576 case JDWP::JT_OBJECT:
2577 case JDWP::JT_STRING:
2578 case JDWP::JT_THREAD:
2579 case JDWP::JT_THREAD_GROUP:
2580 case JDWP::JT_CLASS_LOADER:
2581 case JDWP::JT_CLASS_OBJECT:
2582 return 'L';
2583 }
2584}
2585
Elliott Hughes88d63092013-01-09 09:55:54 -08002586JDWP::JdwpError Dbg::InvokeMethod(JDWP::ObjectId thread_id, JDWP::ObjectId object_id,
2587 JDWP::RefTypeId class_id, JDWP::MethodId method_id,
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002588 uint32_t arg_count, uint64_t* arg_values,
2589 JDWP::JdwpTag* arg_types, uint32_t options,
2590 JDWP::JdwpTag* pResultTag, uint64_t* pResultValue,
2591 JDWP::ObjectId* pExceptionId) {
Elliott Hughesd07986f2011-12-06 18:27:45 -08002592 ThreadList* thread_list = Runtime::Current()->GetThreadList();
2593
2594 Thread* targetThread = NULL;
2595 DebugInvokeReq* req = NULL;
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002596 Thread* self = Thread::Current();
Elliott Hughesd07986f2011-12-06 18:27:45 -08002597 {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002598 ScopedObjectAccessUnchecked soa(self);
Ian Rogers50b35e22012-10-04 10:09:15 -07002599 MutexLock mu(soa.Self(), *Locks::thread_list_lock_);
Elliott Hughes221229c2013-01-08 18:17:50 -08002600 JDWP::JdwpError error = DecodeThread(soa, thread_id, targetThread);
2601 if (error != JDWP::ERR_NONE) {
2602 LOG(ERROR) << "InvokeMethod request for invalid thread id " << thread_id;
2603 return error;
Elliott Hughesd07986f2011-12-06 18:27:45 -08002604 }
2605 req = targetThread->GetInvokeReq();
2606 if (!req->ready) {
2607 LOG(ERROR) << "InvokeMethod request for thread not stopped by event: " << *targetThread;
2608 return JDWP::ERR_INVALID_THREAD;
2609 }
2610
2611 /*
2612 * We currently have a bug where we don't successfully resume the
2613 * target thread if the suspend count is too deep. We're expected to
2614 * require one "resume" for each "suspend", but when asked to execute
2615 * a method we have to resume fully and then re-suspend it back to the
2616 * same level. (The easiest way to cause this is to type "suspend"
2617 * multiple times in jdb.)
2618 *
2619 * It's unclear what this means when the event specifies "resume all"
2620 * and some threads are suspended more deeply than others. This is
2621 * a rare problem, so for now we just prevent it from hanging forever
2622 * by rejecting the method invocation request. Without this, we will
2623 * be stuck waiting on a suspended thread.
2624 */
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002625 int suspend_count;
2626 {
Ian Rogers50b35e22012-10-04 10:09:15 -07002627 MutexLock mu2(soa.Self(), *Locks::thread_suspend_count_lock_);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002628 suspend_count = targetThread->GetSuspendCount();
2629 }
Elliott Hughesd07986f2011-12-06 18:27:45 -08002630 if (suspend_count > 1) {
2631 LOG(ERROR) << *targetThread << " suspend count too deep for method invocation: " << suspend_count;
2632 return JDWP::ERR_THREAD_SUSPENDED; // Probably not expected here.
2633 }
2634
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08002635 JDWP::JdwpError status;
Elliott Hughes88d63092013-01-09 09:55:54 -08002636 Object* receiver = gRegistry->Get<Object*>(object_id);
Elliott Hughes45651fd2012-02-21 15:48:20 -08002637 if (receiver == kInvalidObject) {
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08002638 return JDWP::ERR_INVALID_OBJECT;
2639 }
Elliott Hughes45651fd2012-02-21 15:48:20 -08002640
Elliott Hughes221229c2013-01-08 18:17:50 -08002641 Object* thread = gRegistry->Get<Object*>(thread_id);
Elliott Hughes45651fd2012-02-21 15:48:20 -08002642 if (thread == kInvalidObject) {
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08002643 return JDWP::ERR_INVALID_OBJECT;
2644 }
Elliott Hughes45651fd2012-02-21 15:48:20 -08002645 // TODO: check that 'thread' is actually a java.lang.Thread!
2646
Elliott Hughes88d63092013-01-09 09:55:54 -08002647 Class* c = DecodeClass(class_id, status);
Elliott Hughes45651fd2012-02-21 15:48:20 -08002648 if (c == NULL) {
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08002649 return status;
2650 }
Elliott Hughes45651fd2012-02-21 15:48:20 -08002651
Elliott Hughes88d63092013-01-09 09:55:54 -08002652 AbstractMethod* m = FromMethodId(method_id);
Elliott Hughes45651fd2012-02-21 15:48:20 -08002653 if (m->IsStatic() != (receiver == NULL)) {
2654 return JDWP::ERR_INVALID_METHODID;
2655 }
2656 if (m->IsStatic()) {
2657 if (m->GetDeclaringClass() != c) {
2658 return JDWP::ERR_INVALID_METHODID;
2659 }
2660 } else {
2661 if (!m->GetDeclaringClass()->IsAssignableFrom(c)) {
2662 return JDWP::ERR_INVALID_METHODID;
2663 }
2664 }
2665
2666 // Check the argument list matches the method.
2667 MethodHelper mh(m);
2668 if (mh.GetShortyLength() - 1 != arg_count) {
2669 return JDWP::ERR_ILLEGAL_ARGUMENT;
2670 }
2671 const char* shorty = mh.GetShorty();
2672 for (size_t i = 0; i < arg_count; ++i) {
2673 if (shorty[i + 1] != JdwpTagToShortyChar(arg_types[i])) {
2674 return JDWP::ERR_ILLEGAL_ARGUMENT;
2675 }
2676 }
2677
2678 req->receiver_ = receiver;
2679 req->thread_ = thread;
2680 req->class_ = c;
2681 req->method_ = m;
2682 req->arg_count_ = arg_count;
2683 req->arg_values_ = arg_values;
Elliott Hughesd07986f2011-12-06 18:27:45 -08002684 req->options_ = options;
2685 req->invoke_needed_ = true;
2686 }
2687
2688 // The fact that we've released the thread list lock is a bit risky --- if the thread goes
2689 // away we're sitting high and dry -- but we must release this before the ResumeAllThreads
2690 // call, and it's unwise to hold it during WaitForSuspend.
2691
2692 {
2693 /*
2694 * We change our (JDWP thread) status, which should be THREAD_RUNNING,
Elliott Hughes81ff3182012-03-23 20:35:56 -07002695 * so we can suspend for a GC if the invoke request causes us to
Elliott Hughesd07986f2011-12-06 18:27:45 -08002696 * run out of memory. It's also a good idea to change it before locking
2697 * the invokeReq mutex, although that should never be held for long.
2698 */
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002699 self->TransitionFromRunnableToSuspended(kWaitingForDebuggerSend);
Elliott Hughesd07986f2011-12-06 18:27:45 -08002700
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08002701 VLOG(jdwp) << " Transferring control to event thread";
Elliott Hughesd07986f2011-12-06 18:27:45 -08002702 {
Ian Rogers50b35e22012-10-04 10:09:15 -07002703 MutexLock mu(self, req->lock_);
Elliott Hughesd07986f2011-12-06 18:27:45 -08002704
2705 if ((options & JDWP::INVOKE_SINGLE_THREADED) == 0) {
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08002706 VLOG(jdwp) << " Resuming all threads";
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002707 thread_list->UndoDebuggerSuspensions();
Elliott Hughesd07986f2011-12-06 18:27:45 -08002708 } else {
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08002709 VLOG(jdwp) << " Resuming event thread only";
Elliott Hughesd07986f2011-12-06 18:27:45 -08002710 thread_list->Resume(targetThread, true);
2711 }
2712
2713 // Wait for the request to finish executing.
2714 while (req->invoke_needed_) {
Ian Rogersc604d732012-10-14 16:09:54 -07002715 req->cond_.Wait(self);
Elliott Hughesd07986f2011-12-06 18:27:45 -08002716 }
2717 }
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08002718 VLOG(jdwp) << " Control has returned from event thread";
Elliott Hughesd07986f2011-12-06 18:27:45 -08002719
2720 /* wait for thread to re-suspend itself */
Elliott Hughes221229c2013-01-08 18:17:50 -08002721 SuspendThread(thread_id, false /* request_suspension */ );
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002722 self->TransitionFromSuspendedToRunnable();
Elliott Hughesd07986f2011-12-06 18:27:45 -08002723 }
2724
2725 /*
2726 * Suspend the threads. We waited for the target thread to suspend
2727 * itself, so all we need to do is suspend the others.
2728 *
2729 * The suspendAllThreads() call will double-suspend the event thread,
2730 * so we want to resume the target thread once to keep the books straight.
2731 */
2732 if ((options & JDWP::INVOKE_SINGLE_THREADED) == 0) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002733 self->TransitionFromRunnableToSuspended(kWaitingForDebuggerSuspension);
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08002734 VLOG(jdwp) << " Suspending all threads";
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002735 thread_list->SuspendAllForDebugger();
2736 self->TransitionFromSuspendedToRunnable();
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08002737 VLOG(jdwp) << " Resuming event thread to balance the count";
Elliott Hughesd07986f2011-12-06 18:27:45 -08002738 thread_list->Resume(targetThread, true);
2739 }
2740
2741 // Copy the result.
2742 *pResultTag = req->result_tag;
2743 if (IsPrimitiveTag(req->result_tag)) {
Elliott Hughesf24d3ce2012-04-11 17:43:37 -07002744 *pResultValue = req->result_value.GetJ();
Elliott Hughesd07986f2011-12-06 18:27:45 -08002745 } else {
Elliott Hughesf24d3ce2012-04-11 17:43:37 -07002746 *pResultValue = gRegistry->Add(req->result_value.GetL());
Elliott Hughesd07986f2011-12-06 18:27:45 -08002747 }
2748 *pExceptionId = req->exception;
2749 return req->error;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002750}
2751
2752void Dbg::ExecuteMethod(DebugInvokeReq* pReq) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002753 ScopedObjectAccess soa(Thread::Current());
Elliott Hughesd07986f2011-12-06 18:27:45 -08002754
Elliott Hughes81ff3182012-03-23 20:35:56 -07002755 // We can be called while an exception is pending. We need
Elliott Hughesd07986f2011-12-06 18:27:45 -08002756 // to preserve that across the method invocation.
Ian Rogers1f539342012-10-03 21:09:42 -07002757 SirtRef<Throwable> old_exception(soa.Self(), soa.Self()->GetException());
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002758 soa.Self()->ClearException();
Elliott Hughesd07986f2011-12-06 18:27:45 -08002759
2760 // Translate the method through the vtable, unless the debugger wants to suppress it.
Mathieu Chartier66f19252012-09-18 08:57:04 -07002761 AbstractMethod* m = pReq->method_;
Elliott Hughesd07986f2011-12-06 18:27:45 -08002762 if ((pReq->options_ & JDWP::INVOKE_NONVIRTUAL) == 0 && pReq->receiver_ != NULL) {
Mathieu Chartier66f19252012-09-18 08:57:04 -07002763 AbstractMethod* actual_method = pReq->class_->FindVirtualMethodForVirtualOrInterface(pReq->method_);
Elliott Hughes45651fd2012-02-21 15:48:20 -08002764 if (actual_method != m) {
2765 VLOG(jdwp) << "ExecuteMethod translated " << PrettyMethod(m) << " to " << PrettyMethod(actual_method);
2766 m = actual_method;
2767 }
Elliott Hughesd07986f2011-12-06 18:27:45 -08002768 }
Elliott Hughes45651fd2012-02-21 15:48:20 -08002769 VLOG(jdwp) << "ExecuteMethod " << PrettyMethod(m);
Elliott Hughesd07986f2011-12-06 18:27:45 -08002770 CHECK(m != NULL);
2771
2772 CHECK_EQ(sizeof(jvalue), sizeof(uint64_t));
2773
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002774 LOG(INFO) << "self=" << soa.Self() << " pReq->receiver_=" << pReq->receiver_ << " m=" << m
2775 << " #" << pReq->arg_count_ << " " << pReq->arg_values_;
2776 pReq->result_value = InvokeWithJValues(soa, pReq->receiver_, m,
2777 reinterpret_cast<JValue*>(pReq->arg_values_));
Elliott Hughesd07986f2011-12-06 18:27:45 -08002778
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002779 pReq->exception = gRegistry->Add(soa.Self()->GetException());
Elliott Hughesd07986f2011-12-06 18:27:45 -08002780 pReq->result_tag = BasicTagFromDescriptor(MethodHelper(m).GetShorty());
2781 if (pReq->exception != 0) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002782 Object* exc = soa.Self()->GetException();
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08002783 VLOG(jdwp) << " JDWP invocation returning with exception=" << exc << " " << PrettyTypeOf(exc);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002784 soa.Self()->ClearException();
Elliott Hughesf24d3ce2012-04-11 17:43:37 -07002785 pReq->result_value.SetJ(0);
Elliott Hughesd07986f2011-12-06 18:27:45 -08002786 } else if (pReq->result_tag == JDWP::JT_OBJECT) {
2787 /* if no exception thrown, examine object result more closely */
Elliott Hughesf24d3ce2012-04-11 17:43:37 -07002788 JDWP::JdwpTag new_tag = TagFromObject(pReq->result_value.GetL());
Elliott Hughesd07986f2011-12-06 18:27:45 -08002789 if (new_tag != pReq->result_tag) {
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08002790 VLOG(jdwp) << " JDWP promoted result from " << pReq->result_tag << " to " << new_tag;
Elliott Hughesd07986f2011-12-06 18:27:45 -08002791 pReq->result_tag = new_tag;
2792 }
2793
2794 /*
2795 * Register the object. We don't actually need an ObjectId yet,
2796 * but we do need to be sure that the GC won't move or discard the
2797 * object when we switch out of RUNNING. The ObjectId conversion
2798 * will add the object to the "do not touch" list.
2799 *
2800 * We can't use the "tracked allocation" mechanism here because
2801 * the object is going to be handed off to a different thread.
2802 */
Elliott Hughesf24d3ce2012-04-11 17:43:37 -07002803 gRegistry->Add(pReq->result_value.GetL());
Elliott Hughesd07986f2011-12-06 18:27:45 -08002804 }
2805
2806 if (old_exception.get() != NULL) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002807 soa.Self()->SetException(old_exception.get());
Elliott Hughesd07986f2011-12-06 18:27:45 -08002808 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002809}
2810
Elliott Hughesd07986f2011-12-06 18:27:45 -08002811/*
2812 * Register an object ID that might not have been registered previously.
2813 *
2814 * Normally this wouldn't happen -- the conversion to an ObjectId would
2815 * have added the object to the registry -- but in some cases (e.g.
2816 * throwing exceptions) we really want to do the registration late.
2817 */
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002818void Dbg::RegisterObjectId(JDWP::ObjectId id) {
Elliott Hughesd07986f2011-12-06 18:27:45 -08002819 gRegistry->Add(reinterpret_cast<Object*>(id));
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002820}
2821
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07002822/*
2823 * "buf" contains a full JDWP packet, possibly with multiple chunks. We
2824 * need to process each, accumulate the replies, and ship the whole thing
2825 * back.
2826 *
2827 * Returns "true" if we have a reply. The reply buffer is newly allocated,
2828 * and includes the chunk type/length, followed by the data.
2829 *
Elliott Hughes3d30d9b2011-12-07 17:35:48 -08002830 * OLD-TODO: we currently assume that the request and reply include a single
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07002831 * chunk. If this becomes inconvenient we will need to adapt.
2832 */
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002833bool Dbg::DdmHandlePacket(const uint8_t* buf, int dataLen, uint8_t** pReplyBuf, int* pReplyLen) {
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07002834 CHECK_GE(dataLen, 0);
2835
2836 Thread* self = Thread::Current();
2837 JNIEnv* env = self->GetJniEnv();
2838
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07002839 // Create a byte[] corresponding to 'buf'.
Elliott Hughes6a5bd492011-10-28 14:33:57 -07002840 ScopedLocalRef<jbyteArray> dataArray(env, env->NewByteArray(dataLen));
2841 if (dataArray.get() == NULL) {
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07002842 LOG(WARNING) << "byte[] allocation failed: " << dataLen;
2843 env->ExceptionClear();
2844 return false;
2845 }
Elliott Hughes6a5bd492011-10-28 14:33:57 -07002846 env->SetByteArrayRegion(dataArray.get(), 0, dataLen, reinterpret_cast<const jbyte*>(buf));
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07002847
2848 const int kChunkHdrLen = 8;
2849
2850 // Run through and find all chunks. [Currently just find the first.]
Elliott Hughes6a5bd492011-10-28 14:33:57 -07002851 ScopedByteArrayRO contents(env, dataArray.get());
Elliott Hughesf7c3b662011-10-27 12:04:56 -07002852 jint type = JDWP::Get4BE(reinterpret_cast<const uint8_t*>(&contents[0]));
2853 jint length = JDWP::Get4BE(reinterpret_cast<const uint8_t*>(&contents[4]));
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07002854 jint offset = kChunkHdrLen;
2855 if (offset + length > dataLen) {
2856 LOG(WARNING) << StringPrintf("bad chunk found (len=%u pktLen=%d)", length, dataLen);
2857 return false;
2858 }
2859
2860 // Call "private static Chunk dispatch(int type, byte[] data, int offset, int length)".
Elliott Hugheseac76672012-05-24 21:56:51 -07002861 ScopedLocalRef<jobject> chunk(env, env->CallStaticObjectMethod(WellKnownClasses::org_apache_harmony_dalvik_ddmc_DdmServer,
2862 WellKnownClasses::org_apache_harmony_dalvik_ddmc_DdmServer_dispatch,
2863 type, dataArray.get(), offset, length));
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07002864 if (env->ExceptionCheck()) {
2865 LOG(INFO) << StringPrintf("Exception thrown by dispatcher for 0x%08x", type);
2866 env->ExceptionDescribe();
2867 env->ExceptionClear();
2868 return false;
2869 }
2870
Elliott Hughes6a5bd492011-10-28 14:33:57 -07002871 if (chunk.get() == NULL) {
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07002872 return false;
2873 }
2874
2875 /*
2876 * Pull the pieces out of the chunk. We copy the results into a
2877 * newly-allocated buffer that the caller can free. We don't want to
2878 * continue using the Chunk object because nothing has a reference to it.
2879 *
2880 * We could avoid this by returning type/data/offset/length and having
2881 * the caller be aware of the object lifetime issues, but that
Elliott Hughes81ff3182012-03-23 20:35:56 -07002882 * integrates the JDWP code more tightly into the rest of the runtime, and doesn't work
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07002883 * if we have responses for multiple chunks.
2884 *
2885 * So we're pretty much stuck with copying data around multiple times.
2886 */
Elliott Hugheseac76672012-05-24 21:56:51 -07002887 ScopedLocalRef<jbyteArray> replyData(env, reinterpret_cast<jbyteArray>(env->GetObjectField(chunk.get(), WellKnownClasses::org_apache_harmony_dalvik_ddmc_Chunk_data)));
2888 length = env->GetIntField(chunk.get(), WellKnownClasses::org_apache_harmony_dalvik_ddmc_Chunk_length);
2889 offset = env->GetIntField(chunk.get(), WellKnownClasses::org_apache_harmony_dalvik_ddmc_Chunk_offset);
2890 type = env->GetIntField(chunk.get(), WellKnownClasses::org_apache_harmony_dalvik_ddmc_Chunk_type);
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07002891
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08002892 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 -07002893 if (length == 0 || replyData.get() == NULL) {
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07002894 return false;
2895 }
2896
Elliott Hughes6a5bd492011-10-28 14:33:57 -07002897 jsize replyLength = env->GetArrayLength(replyData.get());
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07002898 if (offset + length > replyLength) {
2899 LOG(WARNING) << StringPrintf("chunk off=%d len=%d exceeds reply array len %d", offset, length, replyLength);
2900 return false;
2901 }
2902
2903 uint8_t* reply = new uint8_t[length + kChunkHdrLen];
2904 if (reply == NULL) {
2905 LOG(WARNING) << "malloc failed: " << (length + kChunkHdrLen);
2906 return false;
2907 }
Elliott Hughesf7c3b662011-10-27 12:04:56 -07002908 JDWP::Set4BE(reply + 0, type);
2909 JDWP::Set4BE(reply + 4, length);
Elliott Hughes6a5bd492011-10-28 14:33:57 -07002910 env->GetByteArrayRegion(replyData.get(), offset, length, reinterpret_cast<jbyte*>(reply + kChunkHdrLen));
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07002911
2912 *pReplyBuf = reply;
2913 *pReplyLen = length + kChunkHdrLen;
2914
Elliott Hughesba8eee12012-01-24 20:25:24 -08002915 VLOG(jdwp) << StringPrintf("dvmHandleDdm returning type=%.4s buf=%p len=%d", reinterpret_cast<char*>(reply), reply, length);
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07002916 return true;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002917}
2918
Elliott Hughesa2155262011-11-16 16:26:58 -08002919void Dbg::DdmBroadcast(bool connect) {
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08002920 VLOG(jdwp) << "Broadcasting DDM " << (connect ? "connect" : "disconnect") << "...";
Elliott Hughes47fce012011-10-25 18:37:19 -07002921
2922 Thread* self = Thread::Current();
Ian Rogers50b35e22012-10-04 10:09:15 -07002923 if (self->GetState() != kRunnable) {
2924 LOG(ERROR) << "DDM broadcast in thread state " << self->GetState();
2925 /* try anyway? */
Elliott Hughes47fce012011-10-25 18:37:19 -07002926 }
2927
2928 JNIEnv* env = self->GetJniEnv();
Elliott Hughes47fce012011-10-25 18:37:19 -07002929 jint event = connect ? 1 /*DdmServer.CONNECTED*/ : 2 /*DdmServer.DISCONNECTED*/;
Elliott Hugheseac76672012-05-24 21:56:51 -07002930 env->CallStaticVoidMethod(WellKnownClasses::org_apache_harmony_dalvik_ddmc_DdmServer,
2931 WellKnownClasses::org_apache_harmony_dalvik_ddmc_DdmServer_broadcast,
2932 event);
Elliott Hughes47fce012011-10-25 18:37:19 -07002933 if (env->ExceptionCheck()) {
2934 LOG(ERROR) << "DdmServer.broadcast " << event << " failed";
2935 env->ExceptionDescribe();
2936 env->ExceptionClear();
2937 }
2938}
2939
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002940void Dbg::DdmConnected() {
Elliott Hughesa2155262011-11-16 16:26:58 -08002941 Dbg::DdmBroadcast(true);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002942}
2943
2944void Dbg::DdmDisconnected() {
Elliott Hughesa2155262011-11-16 16:26:58 -08002945 Dbg::DdmBroadcast(false);
Elliott Hughes47fce012011-10-25 18:37:19 -07002946 gDdmThreadNotification = false;
2947}
2948
2949/*
Elliott Hughes82188472011-11-07 18:11:48 -08002950 * Send a notification when a thread starts, stops, or changes its name.
Elliott Hughes47fce012011-10-25 18:37:19 -07002951 *
2952 * Because we broadcast the full set of threads when the notifications are
2953 * first enabled, it's possible for "thread" to be actively executing.
2954 */
Elliott Hughes82188472011-11-07 18:11:48 -08002955void Dbg::DdmSendThreadNotification(Thread* t, uint32_t type) {
Elliott Hughes47fce012011-10-25 18:37:19 -07002956 if (!gDdmThreadNotification) {
2957 return;
2958 }
2959
Elliott Hughes82188472011-11-07 18:11:48 -08002960 if (type == CHUNK_TYPE("THDE")) {
Elliott Hughes47fce012011-10-25 18:37:19 -07002961 uint8_t buf[4];
Elliott Hughesf7c3b662011-10-27 12:04:56 -07002962 JDWP::Set4BE(&buf[0], t->GetThinLockId());
Elliott Hughes47fce012011-10-25 18:37:19 -07002963 Dbg::DdmSendChunk(CHUNK_TYPE("THDE"), 4, buf);
Elliott Hughes82188472011-11-07 18:11:48 -08002964 } else {
2965 CHECK(type == CHUNK_TYPE("THCR") || type == CHUNK_TYPE("THNM")) << type;
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002966 ScopedObjectAccessUnchecked soa(Thread::Current());
Ian Rogers1f539342012-10-03 21:09:42 -07002967 SirtRef<String> name(soa.Self(), t->GetThreadName(soa));
Elliott Hughes82188472011-11-07 18:11:48 -08002968 size_t char_count = (name.get() != NULL) ? name->GetLength() : 0;
jeffhao725a9572012-11-13 18:20:12 -08002969 const jchar* chars = (name.get() != NULL) ? name->GetCharArray()->GetData() : NULL;
Elliott Hughes82188472011-11-07 18:11:48 -08002970
Elliott Hughes21f32d72011-11-09 17:44:13 -08002971 std::vector<uint8_t> bytes;
Elliott Hughes545a0642011-11-08 19:10:03 -08002972 JDWP::Append4BE(bytes, t->GetThinLockId());
2973 JDWP::AppendUtf16BE(bytes, chars, char_count);
Elliott Hughes21f32d72011-11-09 17:44:13 -08002974 CHECK_EQ(bytes.size(), char_count*2 + sizeof(uint32_t)*2);
2975 Dbg::DdmSendChunk(type, bytes);
Elliott Hughes47fce012011-10-25 18:37:19 -07002976 }
2977}
2978
Elliott Hughes47fce012011-10-25 18:37:19 -07002979void Dbg::DdmSetThreadNotification(bool enable) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002980 // Enable/disable thread notifications.
Elliott Hughes47fce012011-10-25 18:37:19 -07002981 gDdmThreadNotification = enable;
2982 if (enable) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002983 // Suspend the VM then post thread start notifications for all threads. Threads attaching will
2984 // see a suspension in progress and block until that ends. They then post their own start
2985 // notification.
2986 SuspendVM();
2987 std::list<Thread*> threads;
Ian Rogers50b35e22012-10-04 10:09:15 -07002988 Thread* self = Thread::Current();
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002989 {
Ian Rogers50b35e22012-10-04 10:09:15 -07002990 MutexLock mu(self, *Locks::thread_list_lock_);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002991 threads = Runtime::Current()->GetThreadList()->GetList();
2992 }
2993 {
Ian Rogers50b35e22012-10-04 10:09:15 -07002994 ScopedObjectAccess soa(self);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002995 typedef std::list<Thread*>::const_iterator It; // TODO: C++0x auto
2996 for (It it = threads.begin(), end = threads.end(); it != end; ++it) {
2997 Dbg::DdmSendThreadNotification(*it, CHUNK_TYPE("THCR"));
2998 }
2999 }
3000 ResumeVM();
Elliott Hughes47fce012011-10-25 18:37:19 -07003001 }
3002}
3003
Elliott Hughesa2155262011-11-16 16:26:58 -08003004void Dbg::PostThreadStartOrStop(Thread* t, uint32_t type) {
Elliott Hughesc0f09332012-03-26 13:27:06 -07003005 if (IsDebuggerActive()) {
Mathieu Chartierdbe6f462012-09-25 16:54:50 -07003006 ScopedObjectAccessUnchecked soa(Thread::Current());
Ian Rogerscfaa4552012-11-26 21:00:08 -08003007 JDWP::ObjectId id = gRegistry->Add(t->GetPeer());
Elliott Hughes82188472011-11-07 18:11:48 -08003008 gJdwpState->PostThreadChange(id, type == CHUNK_TYPE("THCR"));
Elliott Hughesc0f09332012-03-26 13:27:06 -07003009 // If this thread's just joined the party while we're already debugging, make sure it knows
3010 // to give us updates when it's running.
3011 t->SetDebuggerUpdatesEnabled(true);
Elliott Hughes47fce012011-10-25 18:37:19 -07003012 }
Elliott Hughes82188472011-11-07 18:11:48 -08003013 Dbg::DdmSendThreadNotification(t, type);
Elliott Hughes47fce012011-10-25 18:37:19 -07003014}
3015
3016void Dbg::PostThreadStart(Thread* t) {
Elliott Hughesa2155262011-11-16 16:26:58 -08003017 Dbg::PostThreadStartOrStop(t, CHUNK_TYPE("THCR"));
Elliott Hughes47fce012011-10-25 18:37:19 -07003018}
3019
3020void Dbg::PostThreadDeath(Thread* t) {
Elliott Hughesa2155262011-11-16 16:26:58 -08003021 Dbg::PostThreadStartOrStop(t, CHUNK_TYPE("THDE"));
Elliott Hughes872d4ec2011-10-21 17:07:15 -07003022}
3023
Elliott Hughes82188472011-11-07 18:11:48 -08003024void Dbg::DdmSendChunk(uint32_t type, size_t byte_count, const uint8_t* buf) {
Elliott Hughes3bb81562011-10-21 18:52:59 -07003025 CHECK(buf != NULL);
3026 iovec vec[1];
3027 vec[0].iov_base = reinterpret_cast<void*>(const_cast<uint8_t*>(buf));
3028 vec[0].iov_len = byte_count;
3029 Dbg::DdmSendChunkV(type, vec, 1);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07003030}
3031
Elliott Hughes21f32d72011-11-09 17:44:13 -08003032void Dbg::DdmSendChunk(uint32_t type, const std::vector<uint8_t>& bytes) {
3033 DdmSendChunk(type, bytes.size(), &bytes[0]);
3034}
3035
Elliott Hughescccd84f2011-12-05 16:51:54 -08003036void Dbg::DdmSendChunkV(uint32_t type, const struct iovec* iov, int iov_count) {
Elliott Hughes3bb81562011-10-21 18:52:59 -07003037 if (gJdwpState == NULL) {
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08003038 VLOG(jdwp) << "Debugger thread not active, ignoring DDM send: " << type;
Elliott Hughes3bb81562011-10-21 18:52:59 -07003039 } else {
Elliott Hughescccd84f2011-12-05 16:51:54 -08003040 gJdwpState->DdmSendChunkV(type, iov, iov_count);
Elliott Hughes3bb81562011-10-21 18:52:59 -07003041 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -07003042}
3043
Elliott Hughes767a1472011-10-26 18:49:02 -07003044int Dbg::DdmHandleHpifChunk(HpifWhen when) {
3045 if (when == HPIF_WHEN_NOW) {
Elliott Hughes7162ad92011-10-27 14:08:42 -07003046 DdmSendHeapInfo(when);
Elliott Hughes767a1472011-10-26 18:49:02 -07003047 return true;
3048 }
3049
3050 if (when != HPIF_WHEN_NEVER && when != HPIF_WHEN_NEXT_GC && when != HPIF_WHEN_EVERY_GC) {
3051 LOG(ERROR) << "invalid HpifWhen value: " << static_cast<int>(when);
3052 return false;
3053 }
3054
3055 gDdmHpifWhen = when;
3056 return true;
3057}
3058
3059bool Dbg::DdmHandleHpsgNhsgChunk(Dbg::HpsgWhen when, Dbg::HpsgWhat what, bool native) {
3060 if (when != HPSG_WHEN_NEVER && when != HPSG_WHEN_EVERY_GC) {
3061 LOG(ERROR) << "invalid HpsgWhen value: " << static_cast<int>(when);
3062 return false;
3063 }
3064
3065 if (what != HPSG_WHAT_MERGED_OBJECTS && what != HPSG_WHAT_DISTINCT_OBJECTS) {
3066 LOG(ERROR) << "invalid HpsgWhat value: " << static_cast<int>(what);
3067 return false;
3068 }
3069
3070 if (native) {
3071 gDdmNhsgWhen = when;
3072 gDdmNhsgWhat = what;
3073 } else {
3074 gDdmHpsgWhen = when;
3075 gDdmHpsgWhat = what;
3076 }
3077 return true;
3078}
3079
Elliott Hughes7162ad92011-10-27 14:08:42 -07003080void Dbg::DdmSendHeapInfo(HpifWhen reason) {
3081 // If there's a one-shot 'when', reset it.
3082 if (reason == gDdmHpifWhen) {
3083 if (gDdmHpifWhen == HPIF_WHEN_NEXT_GC) {
3084 gDdmHpifWhen = HPIF_WHEN_NEVER;
3085 }
3086 }
3087
3088 /*
3089 * Chunk HPIF (client --> server)
3090 *
3091 * Heap Info. General information about the heap,
3092 * suitable for a summary display.
3093 *
3094 * [u4]: number of heaps
3095 *
3096 * For each heap:
3097 * [u4]: heap ID
3098 * [u8]: timestamp in ms since Unix epoch
3099 * [u1]: capture reason (same as 'when' value from server)
3100 * [u4]: max heap size in bytes (-Xmx)
3101 * [u4]: current heap size in bytes
3102 * [u4]: current number of bytes allocated
3103 * [u4]: current number of objects allocated
3104 */
3105 uint8_t heap_count = 1;
Elliott Hughesb3bd5f02012-03-08 21:05:27 -08003106 Heap* heap = Runtime::Current()->GetHeap();
Elliott Hughes21f32d72011-11-09 17:44:13 -08003107 std::vector<uint8_t> bytes;
Elliott Hughes545a0642011-11-08 19:10:03 -08003108 JDWP::Append4BE(bytes, heap_count);
3109 JDWP::Append4BE(bytes, 1); // Heap id (bogus; we only have one heap).
3110 JDWP::Append8BE(bytes, MilliTime());
3111 JDWP::Append1BE(bytes, reason);
Elliott Hughesb3bd5f02012-03-08 21:05:27 -08003112 JDWP::Append4BE(bytes, heap->GetMaxMemory()); // Max allowed heap size in bytes.
3113 JDWP::Append4BE(bytes, heap->GetTotalMemory()); // Current heap size in bytes.
3114 JDWP::Append4BE(bytes, heap->GetBytesAllocated());
3115 JDWP::Append4BE(bytes, heap->GetObjectsAllocated());
Elliott Hughes21f32d72011-11-09 17:44:13 -08003116 CHECK_EQ(bytes.size(), 4U + (heap_count * (4 + 8 + 1 + 4 + 4 + 4 + 4)));
3117 Dbg::DdmSendChunk(CHUNK_TYPE("HPIF"), bytes);
Elliott Hughes767a1472011-10-26 18:49:02 -07003118}
3119
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003120enum HpsgSolidity {
3121 SOLIDITY_FREE = 0,
3122 SOLIDITY_HARD = 1,
3123 SOLIDITY_SOFT = 2,
3124 SOLIDITY_WEAK = 3,
3125 SOLIDITY_PHANTOM = 4,
3126 SOLIDITY_FINALIZABLE = 5,
3127 SOLIDITY_SWEEP = 6,
3128};
3129
3130enum HpsgKind {
3131 KIND_OBJECT = 0,
3132 KIND_CLASS_OBJECT = 1,
3133 KIND_ARRAY_1 = 2,
3134 KIND_ARRAY_2 = 3,
3135 KIND_ARRAY_4 = 4,
3136 KIND_ARRAY_8 = 5,
3137 KIND_UNKNOWN = 6,
3138 KIND_NATIVE = 7,
3139};
3140
3141#define HPSG_PARTIAL (1<<7)
3142#define HPSG_STATE(solidity, kind) ((uint8_t)((((kind) & 0x7) << 3) | ((solidity) & 0x7)))
3143
Ian Rogers30fab402012-01-23 15:43:46 -08003144class HeapChunkContext {
3145 public:
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003146 // Maximum chunk size. Obtain this from the formula:
3147 // (((maximum_heap_size / ALLOCATION_UNIT_SIZE) + 255) / 256) * 2
3148 HeapChunkContext(bool merge, bool native)
Ian Rogers30fab402012-01-23 15:43:46 -08003149 : buf_(16384 - 16),
3150 type_(0),
3151 merge_(merge) {
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003152 Reset();
3153 if (native) {
Ian Rogers30fab402012-01-23 15:43:46 -08003154 type_ = CHUNK_TYPE("NHSG");
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003155 } else {
Ian Rogers30fab402012-01-23 15:43:46 -08003156 type_ = merge ? CHUNK_TYPE("HPSG") : CHUNK_TYPE("HPSO");
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003157 }
3158 }
3159
3160 ~HeapChunkContext() {
Ian Rogers30fab402012-01-23 15:43:46 -08003161 if (p_ > &buf_[0]) {
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003162 Flush();
3163 }
3164 }
3165
3166 void EnsureHeader(const void* chunk_ptr) {
Ian Rogers30fab402012-01-23 15:43:46 -08003167 if (!needHeader_) {
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003168 return;
3169 }
3170
3171 // Start a new HPSx chunk.
Ian Rogers30fab402012-01-23 15:43:46 -08003172 JDWP::Write4BE(&p_, 1); // Heap id (bogus; we only have one heap).
3173 JDWP::Write1BE(&p_, 8); // Size of allocation unit, in bytes.
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003174
Ian Rogers30fab402012-01-23 15:43:46 -08003175 JDWP::Write4BE(&p_, reinterpret_cast<uintptr_t>(chunk_ptr)); // virtual address of segment start.
3176 JDWP::Write4BE(&p_, 0); // offset of this piece (relative to the virtual address).
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003177 // [u4]: length of piece, in allocation units
3178 // 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 -08003179 pieceLenField_ = p_;
3180 JDWP::Write4BE(&p_, 0x55555555);
3181 needHeader_ = false;
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003182 }
3183
Ian Rogersb726dcb2012-09-05 08:57:23 -07003184 void Flush() SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Ian Rogersd636b062013-01-18 17:51:18 -08003185 if (pieceLenField_ == NULL) {
3186 // Flush immediately post Reset (maybe back-to-back Flush). Ignore.
3187 CHECK(needHeader_);
3188 return;
3189 }
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003190 // Patch the "length of piece" field.
Ian Rogers30fab402012-01-23 15:43:46 -08003191 CHECK_LE(&buf_[0], pieceLenField_);
3192 CHECK_LE(pieceLenField_, p_);
3193 JDWP::Set4BE(pieceLenField_, totalAllocationUnits_);
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003194
Ian Rogers30fab402012-01-23 15:43:46 -08003195 Dbg::DdmSendChunk(type_, p_ - &buf_[0], &buf_[0]);
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003196 Reset();
3197 }
3198
Ian Rogers00f7d0e2012-07-19 15:28:27 -07003199 static void HeapChunkCallback(void* start, void* end, size_t used_bytes, void* arg)
Ian Rogersb726dcb2012-09-05 08:57:23 -07003200 SHARED_LOCKS_REQUIRED(Locks::heap_bitmap_lock_,
3201 Locks::mutator_lock_) {
Ian Rogers30fab402012-01-23 15:43:46 -08003202 reinterpret_cast<HeapChunkContext*>(arg)->HeapChunkCallback(start, end, used_bytes);
Elliott Hughesa2155262011-11-16 16:26:58 -08003203 }
3204
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003205 private:
Elliott Hughesa2155262011-11-16 16:26:58 -08003206 enum { ALLOCATION_UNIT_SIZE = 8 };
3207
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003208 void Reset() {
Ian Rogers30fab402012-01-23 15:43:46 -08003209 p_ = &buf_[0];
Ian Rogers15bf2d32012-08-28 17:33:04 -07003210 startOfNextMemoryChunk_ = NULL;
Ian Rogers30fab402012-01-23 15:43:46 -08003211 totalAllocationUnits_ = 0;
3212 needHeader_ = true;
3213 pieceLenField_ = NULL;
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003214 }
3215
Ian Rogers00f7d0e2012-07-19 15:28:27 -07003216 void HeapChunkCallback(void* start, void* /*end*/, size_t used_bytes)
Ian Rogersb726dcb2012-09-05 08:57:23 -07003217 SHARED_LOCKS_REQUIRED(Locks::heap_bitmap_lock_,
3218 Locks::mutator_lock_) {
Ian Rogers30fab402012-01-23 15:43:46 -08003219 // Note: heap call backs cannot manipulate the heap upon which they are crawling, care is taken
3220 // in the following code not to allocate memory, by ensuring buf_ is of the correct size
Ian Rogers15bf2d32012-08-28 17:33:04 -07003221 if (used_bytes == 0) {
3222 if (start == NULL) {
3223 // Reset for start of new heap.
3224 startOfNextMemoryChunk_ = NULL;
3225 Flush();
3226 }
3227 // Only process in use memory so that free region information
3228 // also includes dlmalloc book keeping.
Elliott Hughesa2155262011-11-16 16:26:58 -08003229 return;
Elliott Hughesa2155262011-11-16 16:26:58 -08003230 }
3231
Ian Rogers15bf2d32012-08-28 17:33:04 -07003232 /* If we're looking at the native heap, we'll just return
3233 * (SOLIDITY_HARD, KIND_NATIVE) for all allocated chunks
3234 */
3235 bool native = type_ == CHUNK_TYPE("NHSG");
3236
3237 if (startOfNextMemoryChunk_ != NULL) {
3238 // Transmit any pending free memory. Native free memory of
3239 // over kMaxFreeLen could be because of the use of mmaps, so
3240 // don't report. If not free memory then start a new segment.
3241 bool flush = true;
3242 if (start > startOfNextMemoryChunk_) {
3243 const size_t kMaxFreeLen = 2 * kPageSize;
3244 void* freeStart = startOfNextMemoryChunk_;
3245 void* freeEnd = start;
3246 size_t freeLen = (char*)freeEnd - (char*)freeStart;
3247 if (!native || freeLen < kMaxFreeLen) {
3248 AppendChunk(HPSG_STATE(SOLIDITY_FREE, 0), freeStart, freeLen);
3249 flush = false;
3250 }
3251 }
3252 if (flush) {
3253 startOfNextMemoryChunk_ = NULL;
3254 Flush();
3255 }
3256 }
3257 const Object *obj = (const Object *)start;
Elliott Hughesa2155262011-11-16 16:26:58 -08003258
3259 // Determine the type of this chunk.
3260 // OLD-TODO: if context.merge, see if this chunk is different from the last chunk.
3261 // If it's the same, we should combine them.
Ian Rogers15bf2d32012-08-28 17:33:04 -07003262 uint8_t state = ExamineObject(obj, native);
3263 // dlmalloc's chunk header is 2 * sizeof(size_t), but if the previous chunk is in use for an
3264 // allocation then the first sizeof(size_t) may belong to it.
3265 const size_t dlMallocOverhead = sizeof(size_t);
3266 AppendChunk(state, start, used_bytes + dlMallocOverhead);
3267 startOfNextMemoryChunk_ = (char*)start + used_bytes + dlMallocOverhead;
3268 }
Elliott Hughesa2155262011-11-16 16:26:58 -08003269
Ian Rogers15bf2d32012-08-28 17:33:04 -07003270 void AppendChunk(uint8_t state, void* ptr, size_t length)
Ian Rogersb726dcb2012-09-05 08:57:23 -07003271 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Ian Rogers15bf2d32012-08-28 17:33:04 -07003272 // Make sure there's enough room left in the buffer.
3273 // We need to use two bytes for every fractional 256 allocation units used by the chunk plus
3274 // 17 bytes for any header.
3275 size_t needed = (((length/ALLOCATION_UNIT_SIZE + 255) / 256) * 2) + 17;
3276 size_t bytesLeft = buf_.size() - (size_t)(p_ - &buf_[0]);
3277 if (bytesLeft < needed) {
3278 Flush();
3279 }
3280
3281 bytesLeft = buf_.size() - (size_t)(p_ - &buf_[0]);
3282 if (bytesLeft < needed) {
3283 LOG(WARNING) << "Chunk is too big to transmit (chunk_len=" << length << ", "
3284 << needed << " bytes)";
3285 return;
3286 }
3287 EnsureHeader(ptr);
Elliott Hughesa2155262011-11-16 16:26:58 -08003288 // Write out the chunk description.
Ian Rogers15bf2d32012-08-28 17:33:04 -07003289 length /= ALLOCATION_UNIT_SIZE; // Convert to allocation units.
3290 totalAllocationUnits_ += length;
3291 while (length > 256) {
Ian Rogers30fab402012-01-23 15:43:46 -08003292 *p_++ = state | HPSG_PARTIAL;
3293 *p_++ = 255; // length - 1
Ian Rogers15bf2d32012-08-28 17:33:04 -07003294 length -= 256;
Elliott Hughesa2155262011-11-16 16:26:58 -08003295 }
Ian Rogers30fab402012-01-23 15:43:46 -08003296 *p_++ = state;
Ian Rogers15bf2d32012-08-28 17:33:04 -07003297 *p_++ = length - 1;
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003298 }
3299
Ian Rogers5bfa60f2012-09-02 21:17:56 -07003300 uint8_t ExamineObject(const Object* o, bool is_native_heap)
Ian Rogersb726dcb2012-09-05 08:57:23 -07003301 SHARED_LOCKS_REQUIRED(Locks::heap_bitmap_lock_) {
Elliott Hughesa2155262011-11-16 16:26:58 -08003302 if (o == NULL) {
3303 return HPSG_STATE(SOLIDITY_FREE, 0);
3304 }
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003305
Elliott Hughesa2155262011-11-16 16:26:58 -08003306 // It's an allocated chunk. Figure out what it is.
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003307
Elliott Hughesa2155262011-11-16 16:26:58 -08003308 // If we're looking at the native heap, we'll just return
3309 // (SOLIDITY_HARD, KIND_NATIVE) for all allocated chunks.
Ian Rogers00f7d0e2012-07-19 15:28:27 -07003310 if (is_native_heap) {
Elliott Hughesa2155262011-11-16 16:26:58 -08003311 return HPSG_STATE(SOLIDITY_HARD, KIND_NATIVE);
3312 }
3313
Ian Rogers5bfa60f2012-09-02 21:17:56 -07003314 if (!Runtime::Current()->GetHeap()->IsLiveObjectLocked(o)) {
Ian Rogers15bf2d32012-08-28 17:33:04 -07003315 return HPSG_STATE(SOLIDITY_HARD, KIND_NATIVE);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07003316 }
3317
Elliott Hughesa2155262011-11-16 16:26:58 -08003318 Class* c = o->GetClass();
3319 if (c == NULL) {
3320 // The object was probably just created but hasn't been initialized yet.
3321 return HPSG_STATE(SOLIDITY_HARD, KIND_OBJECT);
3322 }
3323
Elliott Hughesb3bd5f02012-03-08 21:05:27 -08003324 if (!Runtime::Current()->GetHeap()->IsHeapAddress(c)) {
Ian Rogers15bf2d32012-08-28 17:33:04 -07003325 LOG(ERROR) << "Invalid class for managed heap object: " << o << " " << c;
Elliott Hughesa2155262011-11-16 16:26:58 -08003326 return HPSG_STATE(SOLIDITY_HARD, KIND_UNKNOWN);
3327 }
3328
3329 if (c->IsClassClass()) {
3330 return HPSG_STATE(SOLIDITY_HARD, KIND_CLASS_OBJECT);
3331 }
3332
3333 if (c->IsArrayClass()) {
3334 if (o->IsObjectArray()) {
3335 return HPSG_STATE(SOLIDITY_HARD, KIND_ARRAY_4);
3336 }
3337 switch (c->GetComponentSize()) {
3338 case 1: return HPSG_STATE(SOLIDITY_HARD, KIND_ARRAY_1);
3339 case 2: return HPSG_STATE(SOLIDITY_HARD, KIND_ARRAY_2);
3340 case 4: return HPSG_STATE(SOLIDITY_HARD, KIND_ARRAY_4);
3341 case 8: return HPSG_STATE(SOLIDITY_HARD, KIND_ARRAY_8);
3342 }
3343 }
3344
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003345 return HPSG_STATE(SOLIDITY_HARD, KIND_OBJECT);
3346 }
3347
Ian Rogers30fab402012-01-23 15:43:46 -08003348 std::vector<uint8_t> buf_;
3349 uint8_t* p_;
3350 uint8_t* pieceLenField_;
Ian Rogers15bf2d32012-08-28 17:33:04 -07003351 void* startOfNextMemoryChunk_;
Ian Rogers30fab402012-01-23 15:43:46 -08003352 size_t totalAllocationUnits_;
3353 uint32_t type_;
3354 bool merge_;
3355 bool needHeader_;
3356
Elliott Hughesa2155262011-11-16 16:26:58 -08003357 DISALLOW_COPY_AND_ASSIGN(HeapChunkContext);
3358};
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003359
3360void Dbg::DdmSendHeapSegments(bool native) {
3361 Dbg::HpsgWhen when;
3362 Dbg::HpsgWhat what;
3363 if (!native) {
3364 when = gDdmHpsgWhen;
3365 what = gDdmHpsgWhat;
3366 } else {
3367 when = gDdmNhsgWhen;
3368 what = gDdmNhsgWhat;
3369 }
3370 if (when == HPSG_WHEN_NEVER) {
3371 return;
3372 }
3373
3374 // Figure out what kind of chunks we'll be sending.
3375 CHECK(what == HPSG_WHAT_MERGED_OBJECTS || what == HPSG_WHAT_DISTINCT_OBJECTS) << static_cast<int>(what);
3376
3377 // First, send a heap start chunk.
3378 uint8_t heap_id[4];
3379 JDWP::Set4BE(&heap_id[0], 1); // Heap id (bogus; we only have one heap).
3380 Dbg::DdmSendChunk(native ? CHUNK_TYPE("NHST") : CHUNK_TYPE("HPST"), sizeof(heap_id), heap_id);
3381
3382 // Send a series of heap segment chunks.
Elliott Hughesa2155262011-11-16 16:26:58 -08003383 HeapChunkContext context((what == HPSG_WHAT_MERGED_OBJECTS), native);
3384 if (native) {
Ian Rogers30fab402012-01-23 15:43:46 -08003385 // TODO: enable when bionic has moved to dlmalloc 2.8.5
3386 // dlmalloc_inspect_all(HeapChunkContext::HeapChunkCallback, &context);
3387 UNIMPLEMENTED(WARNING) << "Native heap send heap segments";
Elliott Hughesa2155262011-11-16 16:26:58 -08003388 } else {
Elliott Hughesb3bd5f02012-03-08 21:05:27 -08003389 Heap* heap = Runtime::Current()->GetHeap();
Mathieu Chartierfd678be2012-08-30 14:50:54 -07003390 const Spaces& spaces = heap->GetSpaces();
Ian Rogers50b35e22012-10-04 10:09:15 -07003391 Thread* self = Thread::Current();
Mathieu Chartierfd678be2012-08-30 14:50:54 -07003392 for (Spaces::const_iterator cur = spaces.begin(); cur != spaces.end(); ++cur) {
Mathieu Chartierb062fdd2012-07-03 09:51:48 -07003393 if ((*cur)->IsAllocSpace()) {
Ian Rogers50b35e22012-10-04 10:09:15 -07003394 ReaderMutexLock mu(self, *Locks::heap_bitmap_lock_);
Mathieu Chartierb062fdd2012-07-03 09:51:48 -07003395 (*cur)->AsAllocSpace()->Walk(HeapChunkContext::HeapChunkCallback, &context);
3396 }
3397 }
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -07003398 // Walk the large objects, these are not in the AllocSpace.
3399 heap->GetLargeObjectsSpace()->Walk(HeapChunkContext::HeapChunkCallback, &context);
Elliott Hughesa2155262011-11-16 16:26:58 -08003400 }
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003401
3402 // Finally, send a heap end chunk.
3403 Dbg::DdmSendChunk(native ? CHUNK_TYPE("NHEN") : CHUNK_TYPE("HPEN"), sizeof(heap_id), heap_id);
Elliott Hughes767a1472011-10-26 18:49:02 -07003404}
3405
Elliott Hughes545a0642011-11-08 19:10:03 -08003406void Dbg::SetAllocTrackingEnabled(bool enabled) {
Ian Rogers50b35e22012-10-04 10:09:15 -07003407 MutexLock mu(Thread::Current(), gAllocTrackerLock);
Elliott Hughes545a0642011-11-08 19:10:03 -08003408 if (enabled) {
3409 if (recent_allocation_records_ == NULL) {
3410 LOG(INFO) << "Enabling alloc tracker (" << kNumAllocRecords << " entries, "
3411 << kMaxAllocRecordStackDepth << " frames --> "
3412 << (sizeof(AllocRecord) * kNumAllocRecords) << " bytes)";
3413 gAllocRecordHead = gAllocRecordCount = 0;
3414 recent_allocation_records_ = new AllocRecord[kNumAllocRecords];
3415 CHECK(recent_allocation_records_ != NULL);
3416 }
3417 } else {
3418 delete[] recent_allocation_records_;
3419 recent_allocation_records_ = NULL;
3420 }
3421}
3422
Ian Rogers0399dde2012-06-06 17:09:28 -07003423struct AllocRecordStackVisitor : public StackVisitor {
3424 AllocRecordStackVisitor(const ManagedStack* stack,
Ian Rogers306057f2012-11-26 12:45:53 -08003425 const std::deque<InstrumentationStackFrame>* instrumentation_stack,
3426 AllocRecord* record)
Ian Rogersb726dcb2012-09-05 08:57:23 -07003427 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_)
jeffhao725a9572012-11-13 18:20:12 -08003428 : StackVisitor(stack, instrumentation_stack, NULL), record(record), depth(0) {}
Elliott Hughes545a0642011-11-08 19:10:03 -08003429
Ian Rogers00f7d0e2012-07-19 15:28:27 -07003430 // TODO: Enable annotalysis. We know lock is held in constructor, but abstraction confuses
3431 // annotalysis.
3432 bool VisitFrame() NO_THREAD_SAFETY_ANALYSIS {
Elliott Hughes545a0642011-11-08 19:10:03 -08003433 if (depth >= kMaxAllocRecordStackDepth) {
Elliott Hughes530fa002012-03-12 11:44:49 -07003434 return false;
Elliott Hughes545a0642011-11-08 19:10:03 -08003435 }
Mathieu Chartier66f19252012-09-18 08:57:04 -07003436 AbstractMethod* m = GetMethod();
Ian Rogers0399dde2012-06-06 17:09:28 -07003437 if (!m->IsRuntimeMethod()) {
3438 record->stack[depth].method = m;
3439 record->stack[depth].dex_pc = GetDexPc();
Elliott Hughes530fa002012-03-12 11:44:49 -07003440 ++depth;
Elliott Hughes545a0642011-11-08 19:10:03 -08003441 }
Elliott Hughes530fa002012-03-12 11:44:49 -07003442 return true;
Elliott Hughes545a0642011-11-08 19:10:03 -08003443 }
3444
3445 ~AllocRecordStackVisitor() {
3446 // Clear out any unused stack trace elements.
3447 for (; depth < kMaxAllocRecordStackDepth; ++depth) {
3448 record->stack[depth].method = NULL;
Ian Rogers0399dde2012-06-06 17:09:28 -07003449 record->stack[depth].dex_pc = 0;
Elliott Hughes545a0642011-11-08 19:10:03 -08003450 }
3451 }
3452
3453 AllocRecord* record;
3454 size_t depth;
3455};
3456
3457void Dbg::RecordAllocation(Class* type, size_t byte_count) {
3458 Thread* self = Thread::Current();
3459 CHECK(self != NULL);
3460
Ian Rogers50b35e22012-10-04 10:09:15 -07003461 MutexLock mu(self, gAllocTrackerLock);
Elliott Hughes545a0642011-11-08 19:10:03 -08003462 if (recent_allocation_records_ == NULL) {
3463 return;
3464 }
3465
3466 // Advance and clip.
3467 if (++gAllocRecordHead == kNumAllocRecords) {
3468 gAllocRecordHead = 0;
3469 }
3470
3471 // Fill in the basics.
3472 AllocRecord* record = &recent_allocation_records_[gAllocRecordHead];
3473 record->type = type;
3474 record->byte_count = byte_count;
3475 record->thin_lock_id = self->GetThinLockId();
3476
3477 // Fill in the stack trace.
jeffhao725a9572012-11-13 18:20:12 -08003478 AllocRecordStackVisitor visitor(self->GetManagedStack(), self->GetInstrumentationStack(), record);
Ian Rogers0399dde2012-06-06 17:09:28 -07003479 visitor.WalkStack();
Elliott Hughes545a0642011-11-08 19:10:03 -08003480
3481 if (gAllocRecordCount < kNumAllocRecords) {
3482 ++gAllocRecordCount;
3483 }
3484}
3485
Elliott Hughesa8f93cb2012-06-08 17:08:48 -07003486// Returns the index of the head element.
3487//
3488// We point at the most-recently-written record, so if gAllocRecordCount is 1
3489// we want to use the current element. Take "head+1" and subtract count
3490// from it.
3491//
3492// We need to handle underflow in our circular buffer, so we add
3493// kNumAllocRecords and then mask it back down.
Elliott Hughesf8349362012-06-18 15:00:06 -07003494static inline int HeadIndex() EXCLUSIVE_LOCKS_REQUIRED(gAllocTrackerLock) {
Elliott Hughes545a0642011-11-08 19:10:03 -08003495 return (gAllocRecordHead+1 + kNumAllocRecords - gAllocRecordCount) & (kNumAllocRecords-1);
3496}
3497
3498void Dbg::DumpRecentAllocations() {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07003499 ScopedObjectAccess soa(Thread::Current());
Ian Rogers50b35e22012-10-04 10:09:15 -07003500 MutexLock mu(soa.Self(), gAllocTrackerLock);
Elliott Hughes545a0642011-11-08 19:10:03 -08003501 if (recent_allocation_records_ == NULL) {
3502 LOG(INFO) << "Not recording tracked allocations";
3503 return;
3504 }
3505
3506 // "i" is the head of the list. We want to start at the end of the
3507 // list and move forward to the tail.
Elliott Hughesa8f93cb2012-06-08 17:08:48 -07003508 size_t i = HeadIndex();
Elliott Hughes545a0642011-11-08 19:10:03 -08003509 size_t count = gAllocRecordCount;
3510
3511 LOG(INFO) << "Tracked allocations, (head=" << gAllocRecordHead << " count=" << count << ")";
3512 while (count--) {
3513 AllocRecord* record = &recent_allocation_records_[i];
3514
Elliott Hughesa8f93cb2012-06-08 17:08:48 -07003515 LOG(INFO) << StringPrintf(" Thread %-2d %6zd bytes ", record->thin_lock_id, record->byte_count)
Elliott Hughes545a0642011-11-08 19:10:03 -08003516 << PrettyClass(record->type);
3517
3518 for (size_t stack_frame = 0; stack_frame < kMaxAllocRecordStackDepth; ++stack_frame) {
Mathieu Chartier66f19252012-09-18 08:57:04 -07003519 const AbstractMethod* m = record->stack[stack_frame].method;
Elliott Hughes545a0642011-11-08 19:10:03 -08003520 if (m == NULL) {
3521 break;
3522 }
3523 LOG(INFO) << " " << PrettyMethod(m) << " line " << record->stack[stack_frame].LineNumber();
3524 }
3525
3526 // pause periodically to help logcat catch up
3527 if ((count % 5) == 0) {
3528 usleep(40000);
3529 }
3530
3531 i = (i + 1) & (kNumAllocRecords-1);
3532 }
3533}
3534
3535class StringTable {
3536 public:
3537 StringTable() {
3538 }
3539
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08003540 void Add(const char* s) {
Elliott Hughes545a0642011-11-08 19:10:03 -08003541 table_.insert(s);
3542 }
3543
Elliott Hughesa8f93cb2012-06-08 17:08:48 -07003544 size_t IndexOf(const char* s) const {
3545 typedef std::set<std::string>::const_iterator It; // TODO: C++0x auto
3546 It it = table_.find(s);
3547 if (it == table_.end()) {
3548 LOG(FATAL) << "IndexOf(\"" << s << "\") failed";
3549 }
3550 return std::distance(table_.begin(), it);
Elliott Hughes545a0642011-11-08 19:10:03 -08003551 }
3552
Elliott Hughesa8f93cb2012-06-08 17:08:48 -07003553 size_t Size() const {
Elliott Hughes545a0642011-11-08 19:10:03 -08003554 return table_.size();
3555 }
3556
Elliott Hughesa8f93cb2012-06-08 17:08:48 -07003557 void WriteTo(std::vector<uint8_t>& bytes) const {
3558 typedef std::set<std::string>::const_iterator It; // TODO: C++0x auto
Elliott Hughes545a0642011-11-08 19:10:03 -08003559 for (It it = table_.begin(); it != table_.end(); ++it) {
Elliott Hughesa8f93cb2012-06-08 17:08:48 -07003560 const char* s = (*it).c_str();
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08003561 size_t s_len = CountModifiedUtf8Chars(s);
3562 UniquePtr<uint16_t> s_utf16(new uint16_t[s_len]);
3563 ConvertModifiedUtf8ToUtf16(s_utf16.get(), s);
3564 JDWP::AppendUtf16BE(bytes, s_utf16.get(), s_len);
Elliott Hughes545a0642011-11-08 19:10:03 -08003565 }
3566 }
3567
3568 private:
Elliott Hughesa8f93cb2012-06-08 17:08:48 -07003569 std::set<std::string> table_;
Elliott Hughes545a0642011-11-08 19:10:03 -08003570 DISALLOW_COPY_AND_ASSIGN(StringTable);
3571};
3572
3573/*
3574 * The data we send to DDMS contains everything we have recorded.
3575 *
3576 * Message header (all values big-endian):
3577 * (1b) message header len (to allow future expansion); includes itself
3578 * (1b) entry header len
3579 * (1b) stack frame len
3580 * (2b) number of entries
3581 * (4b) offset to string table from start of message
3582 * (2b) number of class name strings
3583 * (2b) number of method name strings
3584 * (2b) number of source file name strings
3585 * For each entry:
3586 * (4b) total allocation size
Elliott Hughes221229c2013-01-08 18:17:50 -08003587 * (2b) thread id
Elliott Hughes545a0642011-11-08 19:10:03 -08003588 * (2b) allocated object's class name index
3589 * (1b) stack depth
3590 * For each stack frame:
3591 * (2b) method's class name
3592 * (2b) method name
3593 * (2b) method source file
3594 * (2b) line number, clipped to 32767; -2 if native; -1 if no source
3595 * (xb) class name strings
3596 * (xb) method name strings
3597 * (xb) source file strings
3598 *
3599 * As with other DDM traffic, strings are sent as a 4-byte length
3600 * followed by UTF-16 data.
3601 *
3602 * We send up 16-bit unsigned indexes into string tables. In theory there
3603 * can be (kMaxAllocRecordStackDepth * kNumAllocRecords) unique strings in
3604 * each table, but in practice there should be far fewer.
3605 *
3606 * The chief reason for using a string table here is to keep the size of
3607 * the DDMS message to a minimum. This is partly to make the protocol
3608 * efficient, but also because we have to form the whole thing up all at
3609 * once in a memory buffer.
3610 *
3611 * We use separate string tables for class names, method names, and source
3612 * files to keep the indexes small. There will generally be no overlap
3613 * between the contents of these tables.
3614 */
3615jbyteArray Dbg::GetRecentAllocations() {
3616 if (false) {
3617 DumpRecentAllocations();
3618 }
3619
Ian Rogers50b35e22012-10-04 10:09:15 -07003620 Thread* self = Thread::Current();
3621 MutexLock mu(self, gAllocTrackerLock);
Elliott Hughes545a0642011-11-08 19:10:03 -08003622
Elliott Hughesa8f93cb2012-06-08 17:08:48 -07003623 //
3624 // Part 1: generate string tables.
3625 //
Elliott Hughes545a0642011-11-08 19:10:03 -08003626 StringTable class_names;
3627 StringTable method_names;
3628 StringTable filenames;
3629
3630 int count = gAllocRecordCount;
Elliott Hughesa8f93cb2012-06-08 17:08:48 -07003631 int idx = HeadIndex();
Elliott Hughes545a0642011-11-08 19:10:03 -08003632 while (count--) {
3633 AllocRecord* record = &recent_allocation_records_[idx];
3634
Elliott Hughes91250e02011-12-13 22:30:35 -08003635 class_names.Add(ClassHelper(record->type).GetDescriptor());
Elliott Hughes545a0642011-11-08 19:10:03 -08003636
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08003637 MethodHelper mh;
Elliott Hughes545a0642011-11-08 19:10:03 -08003638 for (size_t i = 0; i < kMaxAllocRecordStackDepth; i++) {
Mathieu Chartier66f19252012-09-18 08:57:04 -07003639 AbstractMethod* m = record->stack[i].method;
Elliott Hughes545a0642011-11-08 19:10:03 -08003640 if (m != NULL) {
Ian Rogersba377812012-05-28 21:16:29 -07003641 mh.ChangeMethod(m);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08003642 class_names.Add(mh.GetDeclaringClassDescriptor());
3643 method_names.Add(mh.GetName());
3644 filenames.Add(mh.GetDeclaringClassSourceFile());
Elliott Hughes545a0642011-11-08 19:10:03 -08003645 }
3646 }
3647
3648 idx = (idx + 1) & (kNumAllocRecords-1);
3649 }
3650
3651 LOG(INFO) << "allocation records: " << gAllocRecordCount;
3652
Elliott Hughesa8f93cb2012-06-08 17:08:48 -07003653 //
3654 // Part 2: allocate a buffer and generate the output.
3655 //
Elliott Hughes545a0642011-11-08 19:10:03 -08003656 std::vector<uint8_t> bytes;
3657
3658 // (1b) message header len (to allow future expansion); includes itself
3659 // (1b) entry header len
3660 // (1b) stack frame len
3661 const int kMessageHeaderLen = 15;
3662 const int kEntryHeaderLen = 9;
3663 const int kStackFrameLen = 8;
3664 JDWP::Append1BE(bytes, kMessageHeaderLen);
3665 JDWP::Append1BE(bytes, kEntryHeaderLen);
3666 JDWP::Append1BE(bytes, kStackFrameLen);
3667
3668 // (2b) number of entries
3669 // (4b) offset to string table from start of message
3670 // (2b) number of class name strings
3671 // (2b) number of method name strings
3672 // (2b) number of source file name strings
3673 JDWP::Append2BE(bytes, gAllocRecordCount);
3674 size_t string_table_offset = bytes.size();
3675 JDWP::Append4BE(bytes, 0); // We'll patch this later...
3676 JDWP::Append2BE(bytes, class_names.Size());
3677 JDWP::Append2BE(bytes, method_names.Size());
3678 JDWP::Append2BE(bytes, filenames.Size());
3679
3680 count = gAllocRecordCount;
Elliott Hughesa8f93cb2012-06-08 17:08:48 -07003681 idx = HeadIndex();
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08003682 ClassHelper kh;
Elliott Hughes545a0642011-11-08 19:10:03 -08003683 while (count--) {
3684 // For each entry:
3685 // (4b) total allocation size
3686 // (2b) thread id
3687 // (2b) allocated object's class name index
3688 // (1b) stack depth
3689 AllocRecord* record = &recent_allocation_records_[idx];
3690 size_t stack_depth = record->GetDepth();
Elliott Hughesa8f93cb2012-06-08 17:08:48 -07003691 kh.ChangeClass(record->type);
3692 size_t allocated_object_class_name_index = class_names.IndexOf(kh.GetDescriptor());
Elliott Hughes545a0642011-11-08 19:10:03 -08003693 JDWP::Append4BE(bytes, record->byte_count);
3694 JDWP::Append2BE(bytes, record->thin_lock_id);
Elliott Hughesa8f93cb2012-06-08 17:08:48 -07003695 JDWP::Append2BE(bytes, allocated_object_class_name_index);
Elliott Hughes545a0642011-11-08 19:10:03 -08003696 JDWP::Append1BE(bytes, stack_depth);
3697
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08003698 MethodHelper mh;
Elliott Hughes545a0642011-11-08 19:10:03 -08003699 for (size_t stack_frame = 0; stack_frame < stack_depth; ++stack_frame) {
3700 // For each stack frame:
3701 // (2b) method's class name
3702 // (2b) method name
3703 // (2b) method source file
3704 // (2b) line number, clipped to 32767; -2 if native; -1 if no source
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08003705 mh.ChangeMethod(record->stack[stack_frame].method);
Elliott Hughesa8f93cb2012-06-08 17:08:48 -07003706 size_t class_name_index = class_names.IndexOf(mh.GetDeclaringClassDescriptor());
3707 size_t method_name_index = method_names.IndexOf(mh.GetName());
3708 size_t file_name_index = filenames.IndexOf(mh.GetDeclaringClassSourceFile());
3709 JDWP::Append2BE(bytes, class_name_index);
3710 JDWP::Append2BE(bytes, method_name_index);
3711 JDWP::Append2BE(bytes, file_name_index);
Elliott Hughes545a0642011-11-08 19:10:03 -08003712 JDWP::Append2BE(bytes, record->stack[stack_frame].LineNumber());
3713 }
3714
3715 idx = (idx + 1) & (kNumAllocRecords-1);
3716 }
3717
3718 // (xb) class name strings
3719 // (xb) method name strings
3720 // (xb) source file strings
3721 JDWP::Set4BE(&bytes[string_table_offset], bytes.size());
3722 class_names.WriteTo(bytes);
3723 method_names.WriteTo(bytes);
3724 filenames.WriteTo(bytes);
3725
Ian Rogers50b35e22012-10-04 10:09:15 -07003726 JNIEnv* env = self->GetJniEnv();
Elliott Hughes545a0642011-11-08 19:10:03 -08003727 jbyteArray result = env->NewByteArray(bytes.size());
3728 if (result != NULL) {
3729 env->SetByteArrayRegion(result, 0, bytes.size(), reinterpret_cast<const jbyte*>(&bytes[0]));
3730 }
3731 return result;
3732}
3733
Elliott Hughes872d4ec2011-10-21 17:07:15 -07003734} // namespace art