blob: 87243275dc1b3bbd9ad22020c2caadb9bee9fdcb [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 Hughes4993bbc2013-01-10 15:41:25 -0800672JDWP::JdwpError Dbg::GetOwnedMonitors(JDWP::ObjectId thread_id, std::vector<JDWP::ObjectId>& monitors)
673 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
674 ScopedObjectAccessUnchecked soa(Thread::Current());
675 MutexLock mu(soa.Self(), *Locks::thread_list_lock_);
676 Thread* thread;
677 JDWP::JdwpError error = DecodeThread(soa, thread_id, thread);
678 if (error != JDWP::ERR_NONE) {
679 return error;
680 }
681 if (!IsSuspendedForDebugger(soa, thread)) {
682 return JDWP::ERR_THREAD_NOT_SUSPENDED;
683 }
684
685 struct OwnedMonitorVisitor : public StackVisitor {
686 OwnedMonitorVisitor(const ManagedStack* stack,
687 const std::deque<InstrumentationStackFrame>* instrumentation_stack)
688 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_)
689 : StackVisitor(stack, instrumentation_stack, NULL) {}
690
691 // TODO: Enable annotalysis. We know lock is held in constructor, but abstraction confuses
692 // annotalysis.
693 bool VisitFrame() NO_THREAD_SAFETY_ANALYSIS {
694 if (!GetMethod()->IsRuntimeMethod()) {
695 Monitor::VisitLocks(this, AppendOwnedMonitors, this);
696 }
697 return true;
698 }
699
700 static void AppendOwnedMonitors(Object* owned_monitor, void* context) {
701 reinterpret_cast<OwnedMonitorVisitor*>(context)->monitors.push_back(owned_monitor);
702 }
703
704 std::vector<Object*> monitors;
705 };
706 OwnedMonitorVisitor visitor(thread->GetManagedStack(), thread->GetInstrumentationStack());
707 visitor.WalkStack();
708
709 for (size_t i = 0; i < visitor.monitors.size(); ++i) {
710 monitors.push_back(gRegistry->Add(visitor.monitors[i]));
711 }
712
713 return JDWP::ERR_NONE;
714}
715
Elliott Hughesf9501702013-01-11 11:22:27 -0800716JDWP::JdwpError Dbg::GetContendedMonitor(JDWP::ObjectId thread_id, JDWP::ObjectId& contended_monitor)
717 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
718 ScopedObjectAccessUnchecked soa(Thread::Current());
719 MutexLock mu(soa.Self(), *Locks::thread_list_lock_);
720 Thread* thread;
721 JDWP::JdwpError error = DecodeThread(soa, thread_id, thread);
722 if (error != JDWP::ERR_NONE) {
723 return error;
724 }
725 if (!IsSuspendedForDebugger(soa, thread)) {
726 return JDWP::ERR_THREAD_NOT_SUSPENDED;
727 }
728
729 contended_monitor = gRegistry->Add(Monitor::GetContendedMonitor(thread));
730
731 return JDWP::ERR_NONE;
732}
733
Elliott Hughes88d63092013-01-09 09:55:54 -0800734JDWP::JdwpError Dbg::GetReflectedType(JDWP::RefTypeId class_id, JDWP::ExpandBuf* pReply) {
Elliott Hughes436e3722012-02-17 20:01:47 -0800735 JDWP::JdwpError status;
Elliott Hughes88d63092013-01-09 09:55:54 -0800736 Class* c = DecodeClass(class_id, status);
Elliott Hughes436e3722012-02-17 20:01:47 -0800737 if (c == NULL) {
738 return status;
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -0800739 }
Elliott Hughes436e3722012-02-17 20:01:47 -0800740
741 expandBufAdd1(pReply, c->IsInterface() ? JDWP::TT_INTERFACE : JDWP::TT_CLASS);
Elliott Hughes88d63092013-01-09 09:55:54 -0800742 expandBufAddRefTypeId(pReply, class_id);
Elliott Hughes436e3722012-02-17 20:01:47 -0800743 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700744}
745
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -0800746void Dbg::GetClassList(std::vector<JDWP::RefTypeId>& classes) {
Elliott Hughesa2155262011-11-16 16:26:58 -0800747 // Get the complete list of reference classes (i.e. all classes except
748 // the primitive types).
749 // Returns a newly-allocated buffer full of RefTypeId values.
750 struct ClassListCreator {
Elliott Hughesba8eee12012-01-24 20:25:24 -0800751 explicit ClassListCreator(std::vector<JDWP::RefTypeId>& classes) : classes(classes) {
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -0800752 }
753
Elliott Hughesa2155262011-11-16 16:26:58 -0800754 static bool Visit(Class* c, void* arg) {
755 return reinterpret_cast<ClassListCreator*>(arg)->Visit(c);
756 }
757
758 bool Visit(Class* c) {
759 if (!c->IsPrimitive()) {
760 classes.push_back(static_cast<JDWP::RefTypeId>(gRegistry->Add(c)));
761 }
762 return true;
763 }
764
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -0800765 std::vector<JDWP::RefTypeId>& classes;
Elliott Hughesa2155262011-11-16 16:26:58 -0800766 };
767
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -0800768 ClassListCreator clc(classes);
Elliott Hughesa2155262011-11-16 16:26:58 -0800769 Runtime::Current()->GetClassLinker()->VisitClasses(ClassListCreator::Visit, &clc);
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700770}
771
Elliott Hughes88d63092013-01-09 09:55:54 -0800772JDWP::JdwpError Dbg::GetClassInfo(JDWP::RefTypeId class_id, JDWP::JdwpTypeTag* pTypeTag, uint32_t* pStatus, std::string* pDescriptor) {
Elliott Hughes436e3722012-02-17 20:01:47 -0800773 JDWP::JdwpError status;
Elliott Hughes88d63092013-01-09 09:55:54 -0800774 Class* c = DecodeClass(class_id, status);
Elliott Hughes436e3722012-02-17 20:01:47 -0800775 if (c == NULL) {
776 return status;
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -0800777 }
778
Elliott Hughesa2155262011-11-16 16:26:58 -0800779 if (c->IsArrayClass()) {
780 *pStatus = JDWP::CS_VERIFIED | JDWP::CS_PREPARED;
781 *pTypeTag = JDWP::TT_ARRAY;
782 } else {
783 if (c->IsErroneous()) {
784 *pStatus = JDWP::CS_ERROR;
785 } else {
786 *pStatus = JDWP::CS_VERIFIED | JDWP::CS_PREPARED | JDWP::CS_INITIALIZED;
787 }
788 *pTypeTag = c->IsInterface() ? JDWP::TT_INTERFACE : JDWP::TT_CLASS;
789 }
790
791 if (pDescriptor != NULL) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800792 *pDescriptor = ClassHelper(c).GetDescriptor();
Elliott Hughesa2155262011-11-16 16:26:58 -0800793 }
Elliott Hughes436e3722012-02-17 20:01:47 -0800794 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700795}
796
Elliott Hughesc3b77c72011-12-15 20:56:48 -0800797void Dbg::FindLoadedClassBySignature(const char* descriptor, std::vector<JDWP::RefTypeId>& ids) {
Elliott Hughes6fa602d2011-12-02 17:54:25 -0800798 std::vector<Class*> classes;
799 Runtime::Current()->GetClassLinker()->LookupClasses(descriptor, classes);
800 ids.clear();
801 for (size_t i = 0; i < classes.size(); ++i) {
802 ids.push_back(gRegistry->Add(classes[i]));
803 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700804}
805
Elliott Hughes88d63092013-01-09 09:55:54 -0800806JDWP::JdwpError Dbg::GetReferenceType(JDWP::ObjectId object_id, JDWP::ExpandBuf* pReply) {
807 Object* o = gRegistry->Get<Object*>(object_id);
Elliott Hughes436e3722012-02-17 20:01:47 -0800808 if (o == NULL || o == kInvalidObject) {
Elliott Hughes2435a572012-02-17 16:07:41 -0800809 return JDWP::ERR_INVALID_OBJECT;
Elliott Hughes499c5132011-11-17 14:55:11 -0800810 }
Elliott Hughes2435a572012-02-17 16:07:41 -0800811
812 JDWP::JdwpTypeTag type_tag;
813 if (o->GetClass()->IsArrayClass()) {
814 type_tag = JDWP::TT_ARRAY;
815 } else if (o->GetClass()->IsInterface()) {
816 type_tag = JDWP::TT_INTERFACE;
817 } else {
818 type_tag = JDWP::TT_CLASS;
819 }
820 JDWP::RefTypeId type_id = gRegistry->Add(o->GetClass());
821
822 expandBufAdd1(pReply, type_tag);
823 expandBufAddRefTypeId(pReply, type_id);
824
825 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700826}
827
Elliott Hughes88d63092013-01-09 09:55:54 -0800828JDWP::JdwpError Dbg::GetSignature(JDWP::RefTypeId class_id, std::string& signature) {
Elliott Hughes1fe7afb2012-02-13 17:23:03 -0800829 JDWP::JdwpError status;
Elliott Hughes88d63092013-01-09 09:55:54 -0800830 Class* c = DecodeClass(class_id, status);
Elliott Hughes1fe7afb2012-02-13 17:23:03 -0800831 if (c == NULL) {
832 return status;
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -0800833 }
Elliott Hughes1fe7afb2012-02-13 17:23:03 -0800834 signature = ClassHelper(c).GetDescriptor();
835 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700836}
837
Elliott Hughes88d63092013-01-09 09:55:54 -0800838JDWP::JdwpError Dbg::GetSourceFile(JDWP::RefTypeId class_id, std::string& result) {
Elliott Hughes436e3722012-02-17 20:01:47 -0800839 JDWP::JdwpError status;
Elliott Hughes88d63092013-01-09 09:55:54 -0800840 Class* c = DecodeClass(class_id, status);
Elliott Hughes436e3722012-02-17 20:01:47 -0800841 if (c == NULL) {
842 return status;
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -0800843 }
Elliott Hughes436e3722012-02-17 20:01:47 -0800844 result = ClassHelper(c).GetSourceFile();
845 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700846}
847
Elliott Hughes88d63092013-01-09 09:55:54 -0800848JDWP::JdwpError Dbg::GetObjectTag(JDWP::ObjectId object_id, uint8_t& tag) {
849 Object* o = gRegistry->Get<Object*>(object_id);
Elliott Hughes546b9862012-06-20 16:06:13 -0700850 if (o == kInvalidObject) {
851 return JDWP::ERR_INVALID_OBJECT;
852 }
853 tag = TagFromObject(o);
854 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700855}
856
Elliott Hughesaed4be92011-12-02 16:16:23 -0800857size_t Dbg::GetTagWidth(JDWP::JdwpTag tag) {
Elliott Hughesdbb40792011-11-18 17:05:22 -0800858 switch (tag) {
859 case JDWP::JT_VOID:
860 return 0;
861 case JDWP::JT_BYTE:
862 case JDWP::JT_BOOLEAN:
863 return 1;
864 case JDWP::JT_CHAR:
865 case JDWP::JT_SHORT:
866 return 2;
867 case JDWP::JT_FLOAT:
868 case JDWP::JT_INT:
869 return 4;
870 case JDWP::JT_ARRAY:
871 case JDWP::JT_OBJECT:
872 case JDWP::JT_STRING:
873 case JDWP::JT_THREAD:
874 case JDWP::JT_THREAD_GROUP:
875 case JDWP::JT_CLASS_LOADER:
876 case JDWP::JT_CLASS_OBJECT:
877 return sizeof(JDWP::ObjectId);
878 case JDWP::JT_DOUBLE:
879 case JDWP::JT_LONG:
880 return 8;
881 default:
Elliott Hughes3d30d9b2011-12-07 17:35:48 -0800882 LOG(FATAL) << "Unknown tag " << tag;
Elliott Hughesdbb40792011-11-18 17:05:22 -0800883 return -1;
884 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700885}
886
Elliott Hughes88d63092013-01-09 09:55:54 -0800887JDWP::JdwpError Dbg::GetArrayLength(JDWP::ObjectId array_id, int& length) {
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -0800888 JDWP::JdwpError status;
Elliott Hughes88d63092013-01-09 09:55:54 -0800889 Array* a = DecodeArray(array_id, status);
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -0800890 if (a == NULL) {
891 return status;
Elliott Hughes24437992011-11-30 14:49:33 -0800892 }
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -0800893 length = a->GetLength();
894 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700895}
896
Elliott Hughes88d63092013-01-09 09:55:54 -0800897JDWP::JdwpError Dbg::OutputArray(JDWP::ObjectId array_id, int offset, int count, JDWP::ExpandBuf* pReply) {
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -0800898 JDWP::JdwpError status;
Elliott Hughes88d63092013-01-09 09:55:54 -0800899 Array* a = DecodeArray(array_id, status);
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -0800900 if (a == NULL) {
901 return status;
902 }
Elliott Hughes24437992011-11-30 14:49:33 -0800903
904 if (offset < 0 || count < 0 || offset > a->GetLength() || a->GetLength() - offset < count) {
905 LOG(WARNING) << __FUNCTION__ << " access out of bounds: offset=" << offset << "; count=" << count;
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -0800906 return JDWP::ERR_INVALID_LENGTH;
Elliott Hughes24437992011-11-30 14:49:33 -0800907 }
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800908 std::string descriptor(ClassHelper(a->GetClass()).GetDescriptor());
Elliott Hughes24437992011-11-30 14:49:33 -0800909 JDWP::JdwpTag tag = BasicTagFromDescriptor(descriptor.c_str() + 1);
910
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -0800911 expandBufAdd1(pReply, tag);
912 expandBufAdd4BE(pReply, count);
913
Elliott Hughes24437992011-11-30 14:49:33 -0800914 if (IsPrimitiveTag(tag)) {
915 size_t width = GetTagWidth(tag);
Elliott Hughes24437992011-11-30 14:49:33 -0800916 uint8_t* dst = expandBufAddSpace(pReply, count * width);
917 if (width == 8) {
Ian Rogersa15e67d2012-02-28 13:51:55 -0800918 const uint64_t* src8 = reinterpret_cast<uint64_t*>(a->GetRawData(sizeof(uint64_t)));
Elliott Hughes24437992011-11-30 14:49:33 -0800919 for (int i = 0; i < count; ++i) JDWP::Write8BE(&dst, src8[offset + i]);
920 } else if (width == 4) {
Ian Rogersa15e67d2012-02-28 13:51:55 -0800921 const uint32_t* src4 = reinterpret_cast<uint32_t*>(a->GetRawData(sizeof(uint32_t)));
Elliott Hughes24437992011-11-30 14:49:33 -0800922 for (int i = 0; i < count; ++i) JDWP::Write4BE(&dst, src4[offset + i]);
923 } else if (width == 2) {
Ian Rogersa15e67d2012-02-28 13:51:55 -0800924 const uint16_t* src2 = reinterpret_cast<uint16_t*>(a->GetRawData(sizeof(uint16_t)));
Elliott Hughes24437992011-11-30 14:49:33 -0800925 for (int i = 0; i < count; ++i) JDWP::Write2BE(&dst, src2[offset + i]);
926 } else {
Ian Rogersa15e67d2012-02-28 13:51:55 -0800927 const uint8_t* src = reinterpret_cast<uint8_t*>(a->GetRawData(sizeof(uint8_t)));
Elliott Hughes24437992011-11-30 14:49:33 -0800928 memcpy(dst, &src[offset * width], count * width);
929 }
930 } else {
931 ObjectArray<Object>* oa = a->AsObjectArray<Object>();
932 for (int i = 0; i < count; ++i) {
Elliott Hughesf03b8f62011-12-02 14:26:25 -0800933 Object* element = oa->Get(offset + i);
Elliott Hughes24437992011-11-30 14:49:33 -0800934 JDWP::JdwpTag specific_tag = (element != NULL) ? TagFromObject(element) : tag;
935 expandBufAdd1(pReply, specific_tag);
936 expandBufAddObjectId(pReply, gRegistry->Add(element));
937 }
938 }
939
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -0800940 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700941}
942
Elliott Hughes88d63092013-01-09 09:55:54 -0800943JDWP::JdwpError Dbg::SetArrayElements(JDWP::ObjectId array_id, int offset, int count,
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700944 const uint8_t* src)
Ian Rogersb726dcb2012-09-05 08:57:23 -0700945 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -0800946 JDWP::JdwpError status;
Elliott Hughes88d63092013-01-09 09:55:54 -0800947 Array* a = DecodeArray(array_id, status);
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -0800948 if (a == NULL) {
949 return status;
950 }
Elliott Hughesf03b8f62011-12-02 14:26:25 -0800951
952 if (offset < 0 || count < 0 || offset > a->GetLength() || a->GetLength() - offset < count) {
953 LOG(WARNING) << __FUNCTION__ << " access out of bounds: offset=" << offset << "; count=" << count;
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -0800954 return JDWP::ERR_INVALID_LENGTH;
Elliott Hughesf03b8f62011-12-02 14:26:25 -0800955 }
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800956 std::string descriptor(ClassHelper(a->GetClass()).GetDescriptor());
Elliott Hughesf03b8f62011-12-02 14:26:25 -0800957 JDWP::JdwpTag tag = BasicTagFromDescriptor(descriptor.c_str() + 1);
958
959 if (IsPrimitiveTag(tag)) {
960 size_t width = GetTagWidth(tag);
Elliott Hughesf03b8f62011-12-02 14:26:25 -0800961 if (width == 8) {
Ian Rogersa15e67d2012-02-28 13:51:55 -0800962 uint8_t* dst = &(reinterpret_cast<uint8_t*>(a->GetRawData(sizeof(uint64_t)))[offset * width]);
Elliott Hughesf03b8f62011-12-02 14:26:25 -0800963 for (int i = 0; i < count; ++i) {
964 // Handle potentially non-aligned memory access one byte at a time for ARM's benefit.
965 uint64_t value;
966 for (size_t j = 0; j < sizeof(uint64_t); ++j) reinterpret_cast<uint8_t*>(&value)[j] = src[j];
967 src += sizeof(uint64_t);
968 JDWP::Write8BE(&dst, value);
969 }
970 } else if (width == 4) {
Ian Rogersa15e67d2012-02-28 13:51:55 -0800971 uint8_t* dst = &(reinterpret_cast<uint8_t*>(a->GetRawData(sizeof(uint32_t)))[offset * width]);
Elliott Hughesf03b8f62011-12-02 14:26:25 -0800972 const uint32_t* src4 = reinterpret_cast<const uint32_t*>(src);
973 for (int i = 0; i < count; ++i) JDWP::Write4BE(&dst, src4[i]);
974 } else if (width == 2) {
Ian Rogersa15e67d2012-02-28 13:51:55 -0800975 uint8_t* dst = &(reinterpret_cast<uint8_t*>(a->GetRawData(sizeof(uint16_t)))[offset * width]);
Elliott Hughesf03b8f62011-12-02 14:26:25 -0800976 const uint16_t* src2 = reinterpret_cast<const uint16_t*>(src);
977 for (int i = 0; i < count; ++i) JDWP::Write2BE(&dst, src2[i]);
978 } else {
Ian Rogersa15e67d2012-02-28 13:51:55 -0800979 uint8_t* dst = &(reinterpret_cast<uint8_t*>(a->GetRawData(sizeof(uint8_t)))[offset * width]);
Elliott Hughesf03b8f62011-12-02 14:26:25 -0800980 memcpy(&dst[offset * width], src, count * width);
981 }
982 } else {
983 ObjectArray<Object>* oa = a->AsObjectArray<Object>();
984 for (int i = 0; i < count; ++i) {
985 JDWP::ObjectId id = JDWP::ReadObjectId(&src);
Elliott Hughes436e3722012-02-17 20:01:47 -0800986 Object* o = gRegistry->Get<Object*>(id);
987 if (o == kInvalidObject) {
988 return JDWP::ERR_INVALID_OBJECT;
989 }
990 oa->Set(offset + i, o);
Elliott Hughesf03b8f62011-12-02 14:26:25 -0800991 }
992 }
993
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -0800994 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700995}
996
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -0800997JDWP::ObjectId Dbg::CreateString(const std::string& str) {
Ian Rogers50b35e22012-10-04 10:09:15 -0700998 return gRegistry->Add(String::AllocFromModifiedUtf8(Thread::Current(), str.c_str()));
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700999}
1000
Elliott Hughes88d63092013-01-09 09:55:54 -08001001JDWP::JdwpError Dbg::CreateObject(JDWP::RefTypeId class_id, JDWP::ObjectId& new_object) {
Elliott Hughes436e3722012-02-17 20:01:47 -08001002 JDWP::JdwpError status;
Elliott Hughes88d63092013-01-09 09:55:54 -08001003 Class* c = DecodeClass(class_id, status);
Elliott Hughes436e3722012-02-17 20:01:47 -08001004 if (c == NULL) {
1005 return status;
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -08001006 }
Ian Rogers50b35e22012-10-04 10:09:15 -07001007 new_object = gRegistry->Add(c->AllocObject(Thread::Current()));
Elliott Hughes436e3722012-02-17 20:01:47 -08001008 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001009}
1010
Elliott Hughesbf13d362011-12-08 15:51:37 -08001011/*
1012 * Used by Eclipse's "Display" view to evaluate "new byte[5]" to get "(byte[]) [0, 0, 0, 0, 0]".
1013 */
Elliott Hughes88d63092013-01-09 09:55:54 -08001014JDWP::JdwpError Dbg::CreateArrayObject(JDWP::RefTypeId array_class_id, uint32_t length,
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001015 JDWP::ObjectId& new_array) {
Elliott Hughes436e3722012-02-17 20:01:47 -08001016 JDWP::JdwpError status;
Elliott Hughes88d63092013-01-09 09:55:54 -08001017 Class* c = DecodeClass(array_class_id, status);
Elliott Hughes436e3722012-02-17 20:01:47 -08001018 if (c == NULL) {
1019 return status;
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -08001020 }
Ian Rogers50b35e22012-10-04 10:09:15 -07001021 new_array = gRegistry->Add(Array::Alloc(Thread::Current(), c, length));
Elliott Hughes436e3722012-02-17 20:01:47 -08001022 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001023}
1024
Elliott Hughes88d63092013-01-09 09:55:54 -08001025bool Dbg::MatchType(JDWP::RefTypeId instance_class_id, JDWP::RefTypeId class_id) {
Elliott Hughes436e3722012-02-17 20:01:47 -08001026 JDWP::JdwpError status;
Elliott Hughes88d63092013-01-09 09:55:54 -08001027 Class* c1 = DecodeClass(instance_class_id, status);
Elliott Hughesa656a0f2012-02-21 18:03:44 -08001028 CHECK(c1 != NULL);
Elliott Hughes88d63092013-01-09 09:55:54 -08001029 Class* c2 = DecodeClass(class_id, status);
Elliott Hughesa656a0f2012-02-21 18:03:44 -08001030 CHECK(c2 != NULL);
1031 return c1->IsAssignableFrom(c2);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001032}
1033
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001034static JDWP::FieldId ToFieldId(const Field* f)
Ian Rogersb726dcb2012-09-05 08:57:23 -07001035 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Elliott Hughes03181a82011-11-17 17:22:21 -08001036#ifdef MOVING_GARBAGE_COLLECTOR
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001037 UNIMPLEMENTED(FATAL);
Elliott Hughes03181a82011-11-17 17:22:21 -08001038#else
1039 return static_cast<JDWP::FieldId>(reinterpret_cast<uintptr_t>(f));
1040#endif
1041}
1042
Mathieu Chartier66f19252012-09-18 08:57:04 -07001043static JDWP::MethodId ToMethodId(const AbstractMethod* m)
Ian Rogersb726dcb2012-09-05 08:57:23 -07001044 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Elliott Hughes03181a82011-11-17 17:22:21 -08001045#ifdef MOVING_GARBAGE_COLLECTOR
1046 UNIMPLEMENTED(FATAL);
1047#else
1048 return static_cast<JDWP::MethodId>(reinterpret_cast<uintptr_t>(m));
1049#endif
1050}
1051
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001052static Field* FromFieldId(JDWP::FieldId fid)
Ian Rogersb726dcb2012-09-05 08:57:23 -07001053 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Elliott Hughesaed4be92011-12-02 16:16:23 -08001054#ifdef MOVING_GARBAGE_COLLECTOR
1055 UNIMPLEMENTED(FATAL);
1056#else
1057 return reinterpret_cast<Field*>(static_cast<uintptr_t>(fid));
1058#endif
1059}
1060
Mathieu Chartier66f19252012-09-18 08:57:04 -07001061static AbstractMethod* FromMethodId(JDWP::MethodId mid)
Ian Rogersb726dcb2012-09-05 08:57:23 -07001062 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Elliott Hughes03181a82011-11-17 17:22:21 -08001063#ifdef MOVING_GARBAGE_COLLECTOR
1064 UNIMPLEMENTED(FATAL);
1065#else
Mathieu Chartier66f19252012-09-18 08:57:04 -07001066 return reinterpret_cast<AbstractMethod*>(static_cast<uintptr_t>(mid));
Elliott Hughes03181a82011-11-17 17:22:21 -08001067#endif
1068}
1069
Mathieu Chartier66f19252012-09-18 08:57:04 -07001070static void SetLocation(JDWP::JdwpLocation& location, AbstractMethod* m, uint32_t dex_pc)
Ian Rogersb726dcb2012-09-05 08:57:23 -07001071 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08001072 if (m == NULL) {
1073 memset(&location, 0, sizeof(location));
1074 } else {
1075 Class* c = m->GetDeclaringClass();
Elliott Hughes74847412012-06-20 18:10:21 -07001076 location.type_tag = c->IsInterface() ? JDWP::TT_INTERFACE : JDWP::TT_CLASS;
1077 location.class_id = gRegistry->Add(c);
1078 location.method_id = ToMethodId(m);
Ian Rogers0399dde2012-06-06 17:09:28 -07001079 location.dex_pc = dex_pc;
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08001080 }
Elliott Hughesd07986f2011-12-06 18:27:45 -08001081}
1082
Elliott Hughes88d63092013-01-09 09:55:54 -08001083std::string Dbg::GetMethodName(JDWP::RefTypeId, JDWP::MethodId method_id)
Ian Rogersb726dcb2012-09-05 08:57:23 -07001084 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Elliott Hughes88d63092013-01-09 09:55:54 -08001085 AbstractMethod* m = FromMethodId(method_id);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001086 return MethodHelper(m).GetName();
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001087}
1088
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001089/*
1090 * Augment the access flags for synthetic methods and fields by setting
1091 * the (as described by the spec) "0xf0000000 bit". Also, strip out any
1092 * flags not specified by the Java programming language.
1093 */
1094static uint32_t MangleAccessFlags(uint32_t accessFlags) {
1095 accessFlags &= kAccJavaFlagsMask;
1096 if ((accessFlags & kAccSynthetic) != 0) {
1097 accessFlags |= 0xf0000000;
1098 }
1099 return accessFlags;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001100}
1101
Elliott Hughesdbb40792011-11-18 17:05:22 -08001102static const uint16_t kEclipseWorkaroundSlot = 1000;
1103
1104/*
1105 * Eclipse appears to expect that the "this" reference is in slot zero.
1106 * If it's not, the "variables" display will show two copies of "this",
1107 * possibly because it gets "this" from SF.ThisObject and then displays
1108 * all locals with nonzero slot numbers.
1109 *
1110 * So, we remap the item in slot 0 to 1000, and remap "this" to zero. On
1111 * SF.GetValues / SF.SetValues we map them back.
Elliott Hughesc5b734a2011-12-01 17:20:58 -08001112 *
1113 * TODO: jdb uses the value to determine whether a variable is a local or an argument,
1114 * by checking whether it's less than the number of arguments. To make that work, we'd
1115 * have to "mangle" all the arguments to come first, not just the implicit argument 'this'.
Elliott Hughesdbb40792011-11-18 17:05:22 -08001116 */
1117static uint16_t MangleSlot(uint16_t slot, const char* name) {
1118 uint16_t newSlot = slot;
1119 if (strcmp(name, "this") == 0) {
1120 newSlot = 0;
1121 } else if (slot == 0) {
1122 newSlot = kEclipseWorkaroundSlot;
1123 }
1124 return newSlot;
1125}
1126
Mathieu Chartier66f19252012-09-18 08:57:04 -07001127static uint16_t DemangleSlot(uint16_t slot, AbstractMethod* m)
Ian Rogersb726dcb2012-09-05 08:57:23 -07001128 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Elliott Hughesdbb40792011-11-18 17:05:22 -08001129 if (slot == kEclipseWorkaroundSlot) {
Elliott Hughes68fdbd02011-11-29 19:22:47 -08001130 return 0;
Elliott Hughesdbb40792011-11-18 17:05:22 -08001131 } else if (slot == 0) {
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08001132 const DexFile::CodeItem* code_item = MethodHelper(m).GetCodeItem();
Elliott Hughescaf76542012-06-28 16:08:22 -07001133 CHECK(code_item != NULL) << PrettyMethod(m);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001134 return code_item->registers_size_ - code_item->ins_size_;
Elliott Hughesdbb40792011-11-18 17:05:22 -08001135 }
Elliott Hughes68fdbd02011-11-29 19:22:47 -08001136 return slot;
Elliott Hughesdbb40792011-11-18 17:05:22 -08001137}
1138
Elliott Hughes88d63092013-01-09 09:55:54 -08001139JDWP::JdwpError Dbg::OutputDeclaredFields(JDWP::RefTypeId class_id, bool with_generic, JDWP::ExpandBuf* pReply) {
Elliott Hughes436e3722012-02-17 20:01:47 -08001140 JDWP::JdwpError status;
Elliott Hughes88d63092013-01-09 09:55:54 -08001141 Class* c = DecodeClass(class_id, status);
Elliott Hughes436e3722012-02-17 20:01:47 -08001142 if (c == NULL) {
1143 return status;
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -08001144 }
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001145
1146 size_t instance_field_count = c->NumInstanceFields();
1147 size_t static_field_count = c->NumStaticFields();
1148
1149 expandBufAdd4BE(pReply, instance_field_count + static_field_count);
1150
1151 for (size_t i = 0; i < instance_field_count + static_field_count; ++i) {
1152 Field* f = (i < instance_field_count) ? c->GetInstanceField(i) : c->GetStaticField(i - instance_field_count);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001153 FieldHelper fh(f);
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001154 expandBufAddFieldId(pReply, ToFieldId(f));
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001155 expandBufAddUtf8String(pReply, fh.GetName());
1156 expandBufAddUtf8String(pReply, fh.GetTypeDescriptor());
Elliott Hughesc5b734a2011-12-01 17:20:58 -08001157 if (with_generic) {
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001158 static const char genericSignature[1] = "";
1159 expandBufAddUtf8String(pReply, genericSignature);
1160 }
1161 expandBufAdd4BE(pReply, MangleAccessFlags(f->GetAccessFlags()));
1162 }
Elliott Hughes436e3722012-02-17 20:01:47 -08001163 return JDWP::ERR_NONE;
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001164}
1165
Elliott Hughes88d63092013-01-09 09:55:54 -08001166JDWP::JdwpError Dbg::OutputDeclaredMethods(JDWP::RefTypeId class_id, bool with_generic,
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001167 JDWP::ExpandBuf* pReply) {
Elliott Hughes436e3722012-02-17 20:01:47 -08001168 JDWP::JdwpError status;
Elliott Hughes88d63092013-01-09 09:55:54 -08001169 Class* c = DecodeClass(class_id, status);
Elliott Hughes436e3722012-02-17 20:01:47 -08001170 if (c == NULL) {
1171 return status;
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -08001172 }
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001173
1174 size_t direct_method_count = c->NumDirectMethods();
1175 size_t virtual_method_count = c->NumVirtualMethods();
1176
1177 expandBufAdd4BE(pReply, direct_method_count + virtual_method_count);
1178
1179 for (size_t i = 0; i < direct_method_count + virtual_method_count; ++i) {
Mathieu Chartier66f19252012-09-18 08:57:04 -07001180 AbstractMethod* m = (i < direct_method_count) ? c->GetDirectMethod(i) : c->GetVirtualMethod(i - direct_method_count);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001181 MethodHelper mh(m);
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001182 expandBufAddMethodId(pReply, ToMethodId(m));
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001183 expandBufAddUtf8String(pReply, mh.GetName());
Elliott Hughes4740cdf2011-12-07 14:07:12 -08001184 expandBufAddUtf8String(pReply, mh.GetSignature());
Elliott Hughesc5b734a2011-12-01 17:20:58 -08001185 if (with_generic) {
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001186 static const char genericSignature[1] = "";
1187 expandBufAddUtf8String(pReply, genericSignature);
1188 }
1189 expandBufAdd4BE(pReply, MangleAccessFlags(m->GetAccessFlags()));
1190 }
Elliott Hughes436e3722012-02-17 20:01:47 -08001191 return JDWP::ERR_NONE;
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001192}
1193
Elliott Hughes88d63092013-01-09 09:55:54 -08001194JDWP::JdwpError Dbg::OutputDeclaredInterfaces(JDWP::RefTypeId class_id, JDWP::ExpandBuf* pReply) {
Elliott Hughes436e3722012-02-17 20:01:47 -08001195 JDWP::JdwpError status;
Elliott Hughes88d63092013-01-09 09:55:54 -08001196 Class* c = DecodeClass(class_id, status);
Elliott Hughes436e3722012-02-17 20:01:47 -08001197 if (c == NULL) {
1198 return status;
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -08001199 }
Elliott Hughes436e3722012-02-17 20:01:47 -08001200
1201 ClassHelper kh(c);
Ian Rogersd24e2642012-06-06 21:21:43 -07001202 size_t interface_count = kh.NumDirectInterfaces();
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001203 expandBufAdd4BE(pReply, interface_count);
1204 for (size_t i = 0; i < interface_count; ++i) {
Ian Rogersd24e2642012-06-06 21:21:43 -07001205 expandBufAddRefTypeId(pReply, gRegistry->Add(kh.GetDirectInterface(i)));
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001206 }
Elliott Hughes436e3722012-02-17 20:01:47 -08001207 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001208}
1209
Elliott Hughes88d63092013-01-09 09:55:54 -08001210void Dbg::OutputLineTable(JDWP::RefTypeId, JDWP::MethodId method_id, JDWP::ExpandBuf* pReply)
Ian Rogersb726dcb2012-09-05 08:57:23 -07001211 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Elliott Hughes03181a82011-11-17 17:22:21 -08001212 struct DebugCallbackContext {
1213 int numItems;
1214 JDWP::ExpandBuf* pReply;
1215
Elliott Hughes2435a572012-02-17 16:07:41 -08001216 static bool Callback(void* context, uint32_t address, uint32_t line_number) {
Elliott Hughes03181a82011-11-17 17:22:21 -08001217 DebugCallbackContext* pContext = reinterpret_cast<DebugCallbackContext*>(context);
1218 expandBufAdd8BE(pContext->pReply, address);
Elliott Hughes2435a572012-02-17 16:07:41 -08001219 expandBufAdd4BE(pContext->pReply, line_number);
Elliott Hughes03181a82011-11-17 17:22:21 -08001220 pContext->numItems++;
1221 return true;
1222 }
1223 };
Elliott Hughes88d63092013-01-09 09:55:54 -08001224 AbstractMethod* m = FromMethodId(method_id);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001225 MethodHelper mh(m);
Elliott Hughes03181a82011-11-17 17:22:21 -08001226 uint64_t start, end;
1227 if (m->IsNative()) {
1228 start = -1;
1229 end = -1;
1230 } else {
1231 start = 0;
jeffhao14f0db92012-12-14 17:50:42 -08001232 // Return the index of the last instruction
1233 end = mh.GetCodeItem()->insns_size_in_code_units_ - 1;
Elliott Hughes03181a82011-11-17 17:22:21 -08001234 }
1235
1236 expandBufAdd8BE(pReply, start);
1237 expandBufAdd8BE(pReply, end);
1238
1239 // Add numLines later
1240 size_t numLinesOffset = expandBufGetLength(pReply);
1241 expandBufAdd4BE(pReply, 0);
1242
1243 DebugCallbackContext context;
1244 context.numItems = 0;
1245 context.pReply = pReply;
1246
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001247 mh.GetDexFile().DecodeDebugInfo(mh.GetCodeItem(), m->IsStatic(), m->GetDexMethodIndex(),
1248 DebugCallbackContext::Callback, NULL, &context);
Elliott Hughes03181a82011-11-17 17:22:21 -08001249
1250 JDWP::Set4BE(expandBufGetBuffer(pReply) + numLinesOffset, context.numItems);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001251}
1252
Elliott Hughes88d63092013-01-09 09:55:54 -08001253void Dbg::OutputVariableTable(JDWP::RefTypeId, JDWP::MethodId method_id, bool with_generic, JDWP::ExpandBuf* pReply) {
Elliott Hughesdbb40792011-11-18 17:05:22 -08001254 struct DebugCallbackContext {
Elliott Hughesdbb40792011-11-18 17:05:22 -08001255 JDWP::ExpandBuf* pReply;
Elliott Hughesc5b734a2011-12-01 17:20:58 -08001256 size_t variable_count;
1257 bool with_generic;
Elliott Hughesdbb40792011-11-18 17:05:22 -08001258
Elliott Hughesc5b734a2011-12-01 17:20:58 -08001259 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 -08001260 DebugCallbackContext* pContext = reinterpret_cast<DebugCallbackContext*>(context);
1261
Elliott Hughesad3da692012-02-24 16:51:35 -08001262 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 -08001263
Elliott Hughes68fdbd02011-11-29 19:22:47 -08001264 slot = MangleSlot(slot, name);
1265
Elliott Hughesdbb40792011-11-18 17:05:22 -08001266 expandBufAdd8BE(pContext->pReply, startAddress);
1267 expandBufAddUtf8String(pContext->pReply, name);
1268 expandBufAddUtf8String(pContext->pReply, descriptor);
Elliott Hughesc5b734a2011-12-01 17:20:58 -08001269 if (pContext->with_generic) {
Elliott Hughesdbb40792011-11-18 17:05:22 -08001270 expandBufAddUtf8String(pContext->pReply, signature);
1271 }
1272 expandBufAdd4BE(pContext->pReply, endAddress - startAddress);
1273 expandBufAdd4BE(pContext->pReply, slot);
1274
Elliott Hughesc5b734a2011-12-01 17:20:58 -08001275 ++pContext->variable_count;
Elliott Hughesdbb40792011-11-18 17:05:22 -08001276 }
1277 };
Elliott Hughes88d63092013-01-09 09:55:54 -08001278 AbstractMethod* m = FromMethodId(method_id);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001279 MethodHelper mh(m);
1280 const DexFile::CodeItem* code_item = mh.GetCodeItem();
Elliott Hughesdbb40792011-11-18 17:05:22 -08001281
Elliott Hughesc5b734a2011-12-01 17:20:58 -08001282 // arg_count considers doubles and longs to take 2 units.
1283 // variable_count considers everything to take 1 unit.
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001284 std::string shorty(mh.GetShorty());
Ian Rogers2fa6b2e2012-10-17 00:10:17 -07001285 expandBufAdd4BE(pReply, AbstractMethod::NumArgRegisters(shorty));
Elliott Hughesdbb40792011-11-18 17:05:22 -08001286
Elliott Hughesc5b734a2011-12-01 17:20:58 -08001287 // We don't know the total number of variables yet, so leave a blank and update it later.
1288 size_t variable_count_offset = expandBufGetLength(pReply);
Elliott Hughesdbb40792011-11-18 17:05:22 -08001289 expandBufAdd4BE(pReply, 0);
1290
1291 DebugCallbackContext context;
Elliott Hughesdbb40792011-11-18 17:05:22 -08001292 context.pReply = pReply;
Elliott Hughesc5b734a2011-12-01 17:20:58 -08001293 context.variable_count = 0;
1294 context.with_generic = with_generic;
Elliott Hughesdbb40792011-11-18 17:05:22 -08001295
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001296 mh.GetDexFile().DecodeDebugInfo(code_item, m->IsStatic(), m->GetDexMethodIndex(), NULL,
1297 DebugCallbackContext::Callback, &context);
Elliott Hughesdbb40792011-11-18 17:05:22 -08001298
Elliott Hughesc5b734a2011-12-01 17:20:58 -08001299 JDWP::Set4BE(expandBufGetBuffer(pReply) + variable_count_offset, context.variable_count);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001300}
1301
Elliott Hughes88d63092013-01-09 09:55:54 -08001302JDWP::JdwpTag Dbg::GetFieldBasicTag(JDWP::FieldId field_id) {
1303 return BasicTagFromDescriptor(FieldHelper(FromFieldId(field_id)).GetTypeDescriptor());
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001304}
1305
Elliott Hughes88d63092013-01-09 09:55:54 -08001306JDWP::JdwpTag Dbg::GetStaticFieldBasicTag(JDWP::FieldId field_id) {
1307 return BasicTagFromDescriptor(FieldHelper(FromFieldId(field_id)).GetTypeDescriptor());
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001308}
1309
Elliott Hughes88d63092013-01-09 09:55:54 -08001310static JDWP::JdwpError GetFieldValueImpl(JDWP::RefTypeId ref_type_id, JDWP::ObjectId object_id,
1311 JDWP::FieldId field_id, JDWP::ExpandBuf* pReply,
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001312 bool is_static)
Ian Rogersb726dcb2012-09-05 08:57:23 -07001313 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Elliott Hughes0cf74332012-02-23 23:14:00 -08001314 JDWP::JdwpError status;
Elliott Hughes88d63092013-01-09 09:55:54 -08001315 Class* c = DecodeClass(ref_type_id, status);
1316 if (ref_type_id != 0 && c == NULL) {
Elliott Hughes0cf74332012-02-23 23:14:00 -08001317 return status;
1318 }
1319
Elliott Hughes88d63092013-01-09 09:55:54 -08001320 Object* o = gRegistry->Get<Object*>(object_id);
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08001321 if ((!is_static && o == NULL) || o == kInvalidObject) {
1322 return JDWP::ERR_INVALID_OBJECT;
1323 }
Elliott Hughes88d63092013-01-09 09:55:54 -08001324 Field* f = FromFieldId(field_id);
Elliott Hughes0cf74332012-02-23 23:14:00 -08001325
1326 Class* receiver_class = c;
1327 if (receiver_class == NULL && o != NULL) {
1328 receiver_class = o->GetClass();
1329 }
1330 // TODO: should we give up now if receiver_class is NULL?
1331 if (receiver_class != NULL && !f->GetDeclaringClass()->IsAssignableFrom(receiver_class)) {
1332 LOG(INFO) << "ERR_INVALID_FIELDID: " << PrettyField(f) << " " << PrettyClass(receiver_class);
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08001333 return JDWP::ERR_INVALID_FIELDID;
1334 }
Elliott Hughesaed4be92011-12-02 16:16:23 -08001335
Elliott Hughes0cf74332012-02-23 23:14:00 -08001336 // The RI only enforces the static/non-static mismatch in one direction.
1337 // TODO: should we change the tests and check both?
1338 if (is_static) {
1339 if (!f->IsStatic()) {
1340 return JDWP::ERR_INVALID_FIELDID;
1341 }
1342 } else {
1343 if (f->IsStatic()) {
1344 LOG(WARNING) << "Ignoring non-NULL receiver for ObjectReference.SetValues on static field " << PrettyField(f);
Elliott Hughes0cf74332012-02-23 23:14:00 -08001345 }
1346 }
jeffhao0dfbb7e2012-11-28 15:26:03 -08001347 if (f->IsStatic()) {
1348 o = f->GetDeclaringClass();
1349 }
Elliott Hughes0cf74332012-02-23 23:14:00 -08001350
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001351 JDWP::JdwpTag tag = BasicTagFromDescriptor(FieldHelper(f).GetTypeDescriptor());
Elliott Hughesaed4be92011-12-02 16:16:23 -08001352
1353 if (IsPrimitiveTag(tag)) {
1354 expandBufAdd1(pReply, tag);
1355 if (tag == JDWP::JT_BOOLEAN || tag == JDWP::JT_BYTE) {
1356 expandBufAdd1(pReply, f->Get32(o));
1357 } else if (tag == JDWP::JT_CHAR || tag == JDWP::JT_SHORT) {
1358 expandBufAdd2BE(pReply, f->Get32(o));
1359 } else if (tag == JDWP::JT_FLOAT || tag == JDWP::JT_INT) {
1360 expandBufAdd4BE(pReply, f->Get32(o));
1361 } else if (tag == JDWP::JT_DOUBLE || tag == JDWP::JT_LONG) {
1362 expandBufAdd8BE(pReply, f->Get64(o));
1363 } else {
Elliott Hughes3d30d9b2011-12-07 17:35:48 -08001364 LOG(FATAL) << "Unknown tag: " << tag;
Elliott Hughesaed4be92011-12-02 16:16:23 -08001365 }
1366 } else {
1367 Object* value = f->GetObject(o);
1368 expandBufAdd1(pReply, TagFromObject(value));
1369 expandBufAddObjectId(pReply, gRegistry->Add(value));
1370 }
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08001371 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001372}
1373
Elliott Hughes88d63092013-01-09 09:55:54 -08001374JDWP::JdwpError Dbg::GetFieldValue(JDWP::ObjectId object_id, JDWP::FieldId field_id,
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001375 JDWP::ExpandBuf* pReply) {
Elliott Hughes88d63092013-01-09 09:55:54 -08001376 return GetFieldValueImpl(0, object_id, field_id, pReply, false);
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08001377}
1378
Elliott Hughes88d63092013-01-09 09:55:54 -08001379JDWP::JdwpError Dbg::GetStaticFieldValue(JDWP::RefTypeId ref_type_id, JDWP::FieldId field_id, JDWP::ExpandBuf* pReply) {
1380 return GetFieldValueImpl(ref_type_id, 0, field_id, pReply, true);
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08001381}
1382
Elliott Hughes88d63092013-01-09 09:55:54 -08001383static JDWP::JdwpError SetFieldValueImpl(JDWP::ObjectId object_id, JDWP::FieldId field_id,
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001384 uint64_t value, int width, bool is_static)
Ian Rogersb726dcb2012-09-05 08:57:23 -07001385 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Elliott Hughes88d63092013-01-09 09:55:54 -08001386 Object* o = gRegistry->Get<Object*>(object_id);
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08001387 if ((!is_static && o == NULL) || o == kInvalidObject) {
1388 return JDWP::ERR_INVALID_OBJECT;
1389 }
Elliott Hughes88d63092013-01-09 09:55:54 -08001390 Field* f = FromFieldId(field_id);
Elliott Hughes0cf74332012-02-23 23:14:00 -08001391
1392 // The RI only enforces the static/non-static mismatch in one direction.
1393 // TODO: should we change the tests and check both?
1394 if (is_static) {
1395 if (!f->IsStatic()) {
1396 return JDWP::ERR_INVALID_FIELDID;
1397 }
1398 } else {
1399 if (f->IsStatic()) {
1400 LOG(WARNING) << "Ignoring non-NULL receiver for ObjectReference.SetValues on static field " << PrettyField(f);
Elliott Hughes0cf74332012-02-23 23:14:00 -08001401 }
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08001402 }
jeffhao0dfbb7e2012-11-28 15:26:03 -08001403 if (f->IsStatic()) {
1404 o = f->GetDeclaringClass();
1405 }
Elliott Hughesaed4be92011-12-02 16:16:23 -08001406
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001407 JDWP::JdwpTag tag = BasicTagFromDescriptor(FieldHelper(f).GetTypeDescriptor());
Elliott Hughesaed4be92011-12-02 16:16:23 -08001408
1409 if (IsPrimitiveTag(tag)) {
1410 if (tag == JDWP::JT_DOUBLE || tag == JDWP::JT_LONG) {
Elliott Hughes1bac54f2012-03-16 12:48:31 -07001411 CHECK_EQ(width, 8);
Elliott Hughesaed4be92011-12-02 16:16:23 -08001412 f->Set64(o, value);
1413 } else {
Elliott Hughes1bac54f2012-03-16 12:48:31 -07001414 CHECK_LE(width, 4);
Elliott Hughesaed4be92011-12-02 16:16:23 -08001415 f->Set32(o, value);
1416 }
1417 } else {
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -08001418 Object* v = gRegistry->Get<Object*>(value);
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08001419 if (v == kInvalidObject) {
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -08001420 return JDWP::ERR_INVALID_OBJECT;
1421 }
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08001422 if (v != NULL) {
1423 Class* field_type = FieldHelper(f).GetType();
1424 if (!field_type->IsAssignableFrom(v->GetClass())) {
1425 return JDWP::ERR_INVALID_OBJECT;
1426 }
1427 }
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -08001428 f->SetObject(o, v);
Elliott Hughesaed4be92011-12-02 16:16:23 -08001429 }
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -08001430
1431 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001432}
1433
Elliott Hughes88d63092013-01-09 09:55:54 -08001434JDWP::JdwpError Dbg::SetFieldValue(JDWP::ObjectId object_id, JDWP::FieldId field_id, uint64_t value,
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001435 int width) {
Elliott Hughes88d63092013-01-09 09:55:54 -08001436 return SetFieldValueImpl(object_id, field_id, value, width, false);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001437}
1438
Elliott Hughes88d63092013-01-09 09:55:54 -08001439JDWP::JdwpError Dbg::SetStaticFieldValue(JDWP::FieldId field_id, uint64_t value, int width) {
1440 return SetFieldValueImpl(0, field_id, value, width, true);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001441}
1442
Elliott Hughes88d63092013-01-09 09:55:54 -08001443std::string Dbg::StringToUtf8(JDWP::ObjectId string_id) {
1444 String* s = gRegistry->Get<String*>(string_id);
Elliott Hughes68fdbd02011-11-29 19:22:47 -08001445 return s->ToModifiedUtf8();
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001446}
1447
Elliott Hughes221229c2013-01-08 18:17:50 -08001448JDWP::JdwpError Dbg::GetThreadName(JDWP::ObjectId thread_id, std::string& name) {
jeffhaoa77f0f62012-12-05 17:19:31 -08001449 ScopedObjectAccessUnchecked soa(Thread::Current());
1450 MutexLock mu(soa.Self(), *Locks::thread_list_lock_);
Elliott Hughes221229c2013-01-08 18:17:50 -08001451 Thread* thread;
1452 JDWP::JdwpError error = DecodeThread(soa, thread_id, thread);
1453 if (error != JDWP::ERR_NONE && error != JDWP::ERR_THREAD_NOT_ALIVE) {
1454 return error;
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001455 }
Elliott Hughes221229c2013-01-08 18:17:50 -08001456
1457 // We still need to report the zombie threads' names, so we can't just call Thread::GetThreadName.
1458 Object* thread_object = gRegistry->Get<Object*>(thread_id);
1459 Field* java_lang_Thread_name_field = soa.DecodeField(WellKnownClasses::java_lang_Thread_name);
1460 String* s = reinterpret_cast<String*>(java_lang_Thread_name_field->GetObject(thread_object));
1461 if (s != NULL) {
1462 name = s->ToModifiedUtf8();
1463 }
1464 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001465}
1466
Elliott Hughes221229c2013-01-08 18:17:50 -08001467JDWP::JdwpError Dbg::GetThreadGroup(JDWP::ObjectId thread_id, JDWP::ExpandBuf* pReply) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001468 ScopedObjectAccess soa(Thread::Current());
Elliott Hughes221229c2013-01-08 18:17:50 -08001469 Object* thread_object = gRegistry->Get<Object*>(thread_id);
1470 if (thread_object == kInvalidObject) {
Elliott Hughes2435a572012-02-17 16:07:41 -08001471 return JDWP::ERR_INVALID_OBJECT;
1472 }
1473
1474 // Okay, so it's an object, but is it actually a thread?
Ian Rogers50b35e22012-10-04 10:09:15 -07001475 MutexLock mu(soa.Self(), *Locks::thread_list_lock_);
Elliott Hughes221229c2013-01-08 18:17:50 -08001476 Thread* thread;
1477 JDWP::JdwpError error = DecodeThread(soa, thread_id, thread);
1478 if (error == JDWP::ERR_THREAD_NOT_ALIVE) {
1479 // Zombie threads are in the null group.
1480 expandBufAddObjectId(pReply, JDWP::ObjectId(0));
1481 return JDWP::ERR_NONE;
1482 }
1483 if (error != JDWP::ERR_NONE) {
1484 return error;
Elliott Hughes2435a572012-02-17 16:07:41 -08001485 }
Elliott Hughes499c5132011-11-17 14:55:11 -08001486
1487 Class* c = Runtime::Current()->GetClassLinker()->FindSystemClass("Ljava/lang/Thread;");
1488 CHECK(c != NULL);
1489 Field* f = c->FindInstanceField("group", "Ljava/lang/ThreadGroup;");
1490 CHECK(f != NULL);
Elliott Hughes221229c2013-01-08 18:17:50 -08001491 Object* group = f->GetObject(thread_object);
Elliott Hughes499c5132011-11-17 14:55:11 -08001492 CHECK(group != NULL);
Elliott Hughes2435a572012-02-17 16:07:41 -08001493 JDWP::ObjectId thread_group_id = gRegistry->Add(group);
1494
1495 expandBufAddObjectId(pReply, thread_group_id);
1496 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001497}
1498
Elliott Hughes88d63092013-01-09 09:55:54 -08001499std::string Dbg::GetThreadGroupName(JDWP::ObjectId thread_group_id) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001500 ScopedObjectAccess soa(Thread::Current());
Elliott Hughes88d63092013-01-09 09:55:54 -08001501 Object* thread_group = gRegistry->Get<Object*>(thread_group_id);
Elliott Hughes499c5132011-11-17 14:55:11 -08001502 CHECK(thread_group != NULL);
1503
1504 Class* c = Runtime::Current()->GetClassLinker()->FindSystemClass("Ljava/lang/ThreadGroup;");
1505 CHECK(c != NULL);
1506 Field* f = c->FindInstanceField("name", "Ljava/lang/String;");
1507 CHECK(f != NULL);
1508 String* s = reinterpret_cast<String*>(f->GetObject(thread_group));
1509 return s->ToModifiedUtf8();
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001510}
1511
Elliott Hughes88d63092013-01-09 09:55:54 -08001512JDWP::ObjectId Dbg::GetThreadGroupParent(JDWP::ObjectId thread_group_id) {
1513 Object* thread_group = gRegistry->Get<Object*>(thread_group_id);
Elliott Hughes4e235312011-12-02 11:34:15 -08001514 CHECK(thread_group != NULL);
1515
1516 Class* c = Runtime::Current()->GetClassLinker()->FindSystemClass("Ljava/lang/ThreadGroup;");
1517 CHECK(c != NULL);
1518 Field* f = c->FindInstanceField("parent", "Ljava/lang/ThreadGroup;");
1519 CHECK(f != NULL);
1520 Object* parent = f->GetObject(thread_group);
1521 return gRegistry->Add(parent);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001522}
1523
1524JDWP::ObjectId Dbg::GetSystemThreadGroupId() {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001525 ScopedObjectAccessUnchecked soa(Thread::Current());
jeffhao0dfbb7e2012-11-28 15:26:03 -08001526 Field* f = soa.DecodeField(WellKnownClasses::java_lang_ThreadGroup_systemThreadGroup);
1527 Object* group = f->GetObject(f->GetDeclaringClass());
Ian Rogers365c1022012-06-22 15:05:28 -07001528 return gRegistry->Add(group);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001529}
1530
1531JDWP::ObjectId Dbg::GetMainThreadGroupId() {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001532 ScopedObjectAccess soa(Thread::Current());
jeffhao0dfbb7e2012-11-28 15:26:03 -08001533 Field* f = soa.DecodeField(WellKnownClasses::java_lang_ThreadGroup_mainThreadGroup);
1534 Object* group = f->GetObject(f->GetDeclaringClass());
Ian Rogers365c1022012-06-22 15:05:28 -07001535 return gRegistry->Add(group);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001536}
1537
Elliott Hughes221229c2013-01-08 18:17:50 -08001538JDWP::JdwpError Dbg::GetThreadStatus(JDWP::ObjectId thread_id, JDWP::JdwpThreadStatus* pThreadStatus, JDWP::JdwpSuspendStatus* pSuspendStatus) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001539 ScopedObjectAccess soa(Thread::Current());
Elliott Hughes499c5132011-11-17 14:55:11 -08001540
Elliott Hughes9e0c1752013-01-09 14:02:58 -08001541 *pSuspendStatus = JDWP::SUSPEND_STATUS_NOT_SUSPENDED;
1542
Ian Rogers50b35e22012-10-04 10:09:15 -07001543 MutexLock mu(soa.Self(), *Locks::thread_list_lock_);
Elliott Hughes221229c2013-01-08 18:17:50 -08001544 Thread* thread;
1545 JDWP::JdwpError error = DecodeThread(soa, thread_id, thread);
1546 if (error != JDWP::ERR_NONE) {
1547 if (error == JDWP::ERR_THREAD_NOT_ALIVE) {
1548 *pThreadStatus = JDWP::TS_ZOMBIE;
Elliott Hughes221229c2013-01-08 18:17:50 -08001549 return JDWP::ERR_NONE;
1550 }
1551 return error;
Elliott Hughes499c5132011-11-17 14:55:11 -08001552 }
1553
Elliott Hughes9e0c1752013-01-09 14:02:58 -08001554 if (IsSuspendedForDebugger(soa, thread)) {
1555 *pSuspendStatus = JDWP::SUSPEND_STATUS_SUSPENDED;
Elliott Hughes499c5132011-11-17 14:55:11 -08001556 }
1557
Elliott Hughes9e0c1752013-01-09 14:02:58 -08001558 switch (thread->GetState()) {
1559 case kBlocked: *pThreadStatus = JDWP::TS_MONITOR; break;
1560 case kNative: *pThreadStatus = JDWP::TS_RUNNING; break;
1561 case kRunnable: *pThreadStatus = JDWP::TS_RUNNING; break;
1562 case kSleeping: *pThreadStatus = JDWP::TS_SLEEPING; break;
1563 case kStarting: *pThreadStatus = JDWP::TS_ZOMBIE; break;
1564 case kSuspended: *pThreadStatus = JDWP::TS_RUNNING; break;
1565 case kTerminated: *pThreadStatus = JDWP::TS_ZOMBIE; break;
1566 case kTimedWaiting: *pThreadStatus = JDWP::TS_WAIT; break;
1567 case kWaitingForDebuggerSend: *pThreadStatus = JDWP::TS_WAIT; break;
1568 case kWaitingForDebuggerSuspension: *pThreadStatus = JDWP::TS_WAIT; break;
1569 case kWaitingForDebuggerToAttach: *pThreadStatus = JDWP::TS_WAIT; break;
1570 case kWaitingForGcToComplete: *pThreadStatus = JDWP::TS_WAIT; break;
1571 case kWaitingForJniOnLoad: *pThreadStatus = JDWP::TS_WAIT; break;
1572 case kWaitingForSignalCatcherOutput: *pThreadStatus = JDWP::TS_WAIT; break;
1573 case kWaitingInMainDebuggerLoop: *pThreadStatus = JDWP::TS_WAIT; break;
1574 case kWaitingInMainSignalCatcherLoop: *pThreadStatus = JDWP::TS_WAIT; break;
1575 case kWaitingPerformingGc: *pThreadStatus = JDWP::TS_WAIT; break;
1576 case kWaiting: *pThreadStatus = JDWP::TS_WAIT; break;
1577 // Don't add a 'default' here so the compiler can spot incompatible enum changes.
1578 }
Elliott Hughes221229c2013-01-08 18:17:50 -08001579 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001580}
1581
Elliott Hughes221229c2013-01-08 18:17:50 -08001582JDWP::JdwpError Dbg::GetThreadDebugSuspendCount(JDWP::ObjectId thread_id, JDWP::ExpandBuf* pReply) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001583 ScopedObjectAccess soa(Thread::Current());
Ian Rogers50b35e22012-10-04 10:09:15 -07001584 MutexLock mu(soa.Self(), *Locks::thread_list_lock_);
Elliott Hughes221229c2013-01-08 18:17:50 -08001585 Thread* thread;
1586 JDWP::JdwpError error = DecodeThread(soa, thread_id, thread);
1587 if (error != JDWP::ERR_NONE) {
1588 return error;
Elliott Hughes2435a572012-02-17 16:07:41 -08001589 }
Ian Rogers50b35e22012-10-04 10:09:15 -07001590 MutexLock mu2(soa.Self(), *Locks::thread_suspend_count_lock_);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001591 expandBufAdd4BE(pReply, thread->GetDebugSuspendCount());
Elliott Hughes2435a572012-02-17 16:07:41 -08001592 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001593}
1594
Elliott Hughesf9501702013-01-11 11:22:27 -08001595JDWP::JdwpError Dbg::Interrupt(JDWP::ObjectId thread_id) {
1596 ScopedObjectAccess soa(Thread::Current());
1597 MutexLock mu(soa.Self(), *Locks::thread_list_lock_);
1598 Thread* thread;
1599 JDWP::JdwpError error = DecodeThread(soa, thread_id, thread);
1600 if (error != JDWP::ERR_NONE) {
1601 return error;
1602 }
1603 thread->Interrupt();
1604 return JDWP::ERR_NONE;
1605}
1606
Elliott Hughescaf76542012-06-28 16:08:22 -07001607void Dbg::GetThreads(JDWP::ObjectId thread_group_id, std::vector<JDWP::ObjectId>& thread_ids) {
Ian Rogers365c1022012-06-22 15:05:28 -07001608 class ThreadListVisitor {
1609 public:
jeffhao0dfbb7e2012-11-28 15:26:03 -08001610 ThreadListVisitor(const ScopedObjectAccessUnchecked& soa, Object* desired_thread_group,
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001611 std::vector<JDWP::ObjectId>& thread_ids)
Ian Rogersb726dcb2012-09-05 08:57:23 -07001612 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_)
jeffhao0dfbb7e2012-11-28 15:26:03 -08001613 : soa_(soa), desired_thread_group_(desired_thread_group), thread_ids_(thread_ids) {}
Ian Rogers365c1022012-06-22 15:05:28 -07001614
Elliott Hughesa2155262011-11-16 16:26:58 -08001615 static void Visit(Thread* t, void* arg) {
1616 reinterpret_cast<ThreadListVisitor*>(arg)->Visit(t);
1617 }
1618
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001619 // TODO: Enable annotalysis. We know lock is held in constructor, but abstraction confuses
1620 // annotalysis.
1621 void Visit(Thread* t) NO_THREAD_SAFETY_ANALYSIS {
Elliott Hughesa2155262011-11-16 16:26:58 -08001622 if (t == Dbg::GetDebugThread()) {
1623 // Skip the JDWP thread. Some debuggers get bent out of shape when they can't suspend and
1624 // query all threads, so it's easier if we just don't tell them about this thread.
1625 return;
1626 }
Ian Rogerscfaa4552012-11-26 21:00:08 -08001627 Object* peer = t->GetPeer();
jeffhao0dfbb7e2012-11-28 15:26:03 -08001628 if (IsInDesiredThreadGroup(peer)) {
Ian Rogers120f1c72012-09-28 17:17:10 -07001629 thread_ids_.push_back(gRegistry->Add(peer));
Elliott Hughesa2155262011-11-16 16:26:58 -08001630 }
1631 }
1632
Ian Rogers365c1022012-06-22 15:05:28 -07001633 private:
jeffhao0dfbb7e2012-11-28 15:26:03 -08001634 bool IsInDesiredThreadGroup(Object* peer)
1635 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
jeffhao0dfbb7e2012-11-28 15:26:03 -08001636 // peer might be NULL if the thread is still starting up.
1637 if (peer == NULL) {
1638 // We can't tell the debugger about this thread yet.
1639 // TODO: if we identified threads to the debugger by their Thread*
1640 // rather than their peer's Object*, we could fix this.
1641 // Doing so might help us report ZOMBIE threads too.
1642 return false;
1643 }
jeffhaoc1e04902012-12-13 12:41:10 -08001644 // Do we want threads from all thread groups?
1645 if (desired_thread_group_ == NULL) {
1646 return true;
1647 }
jeffhao0dfbb7e2012-11-28 15:26:03 -08001648 Object* group = soa_.DecodeField(WellKnownClasses::java_lang_Thread_group)->GetObject(peer);
1649 return (group == desired_thread_group_);
1650 }
1651
Mathieu Chartierdbe6f462012-09-25 16:54:50 -07001652 const ScopedObjectAccessUnchecked& soa_;
jeffhao0dfbb7e2012-11-28 15:26:03 -08001653 Object* const desired_thread_group_;
Elliott Hughescaf76542012-06-28 16:08:22 -07001654 std::vector<JDWP::ObjectId>& thread_ids_;
Elliott Hughesa2155262011-11-16 16:26:58 -08001655 };
1656
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001657 ScopedObjectAccessUnchecked soa(Thread::Current());
Elliott Hughescaf76542012-06-28 16:08:22 -07001658 Object* thread_group = gRegistry->Get<Object*>(thread_group_id);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001659 ThreadListVisitor tlv(soa, thread_group, thread_ids);
Ian Rogers50b35e22012-10-04 10:09:15 -07001660 MutexLock mu(soa.Self(), *Locks::thread_list_lock_);
Elliott Hughesf8349362012-06-18 15:00:06 -07001661 Runtime::Current()->GetThreadList()->ForEach(ThreadListVisitor::Visit, &tlv);
Elliott Hughescaf76542012-06-28 16:08:22 -07001662}
Elliott Hughesa2155262011-11-16 16:26:58 -08001663
Elliott Hughescaf76542012-06-28 16:08:22 -07001664void Dbg::GetChildThreadGroups(JDWP::ObjectId thread_group_id, std::vector<JDWP::ObjectId>& child_thread_group_ids) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001665 ScopedObjectAccess soa(Thread::Current());
Elliott Hughescaf76542012-06-28 16:08:22 -07001666 Object* thread_group = gRegistry->Get<Object*>(thread_group_id);
1667
1668 // Get the ArrayList<ThreadGroup> "groups" out of this thread group...
1669 Field* groups_field = thread_group->GetClass()->FindInstanceField("groups", "Ljava/util/List;");
1670 Object* groups_array_list = groups_field->GetObject(thread_group);
1671
1672 // Get the array and size out of the ArrayList<ThreadGroup>...
1673 Field* array_field = groups_array_list->GetClass()->FindInstanceField("array", "[Ljava/lang/Object;");
1674 Field* size_field = groups_array_list->GetClass()->FindInstanceField("size", "I");
1675 ObjectArray<Object>* groups_array = array_field->GetObject(groups_array_list)->AsObjectArray<Object>();
1676 const int32_t size = size_field->GetInt(groups_array_list);
1677
1678 // Copy the first 'size' elements out of the array into the result.
1679 for (int32_t i = 0; i < size; ++i) {
1680 child_thread_group_ids.push_back(gRegistry->Add(groups_array->Get(i)));
Elliott Hughesa2155262011-11-16 16:26:58 -08001681 }
1682}
1683
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001684static int GetStackDepth(Thread* thread)
Ian Rogersb726dcb2012-09-05 08:57:23 -07001685 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Ian Rogers0399dde2012-06-06 17:09:28 -07001686 struct CountStackDepthVisitor : public StackVisitor {
1687 CountStackDepthVisitor(const ManagedStack* stack,
Ian Rogers306057f2012-11-26 12:45:53 -08001688 const std::deque<InstrumentationStackFrame>* instrumentation_stack)
jeffhao725a9572012-11-13 18:20:12 -08001689 : StackVisitor(stack, instrumentation_stack, NULL), depth(0) {}
Ian Rogers0399dde2012-06-06 17:09:28 -07001690
1691 bool VisitFrame() {
1692 if (!GetMethod()->IsRuntimeMethod()) {
Elliott Hughesf8a2df72011-12-01 12:19:54 -08001693 ++depth;
1694 }
Elliott Hughes530fa002012-03-12 11:44:49 -07001695 return true;
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001696 }
1697 size_t depth;
1698 };
Elliott Hughes08fc03a2012-06-26 17:34:00 -07001699
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001700 if (kIsDebugBuild) {
Ian Rogers50b35e22012-10-04 10:09:15 -07001701 MutexLock mu(Thread::Current(), *Locks::thread_suspend_count_lock_);
jeffhao09bfc6a2012-12-11 18:11:43 -08001702 CHECK(thread == Thread::Current() || thread->IsSuspended());
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001703 }
jeffhao725a9572012-11-13 18:20:12 -08001704 CountStackDepthVisitor visitor(thread->GetManagedStack(), thread->GetInstrumentationStack());
Ian Rogers0399dde2012-06-06 17:09:28 -07001705 visitor.WalkStack();
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001706 return visitor.depth;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001707}
1708
Elliott Hughes221229c2013-01-08 18:17:50 -08001709JDWP::JdwpError Dbg::GetThreadFrameCount(JDWP::ObjectId thread_id, size_t& result) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001710 ScopedObjectAccess soa(Thread::Current());
jeffhaoa77f0f62012-12-05 17:19:31 -08001711 MutexLock mu(soa.Self(), *Locks::thread_list_lock_);
Elliott Hughes221229c2013-01-08 18:17:50 -08001712 Thread* thread;
1713 JDWP::JdwpError error = DecodeThread(soa, thread_id, thread);
1714 if (error != JDWP::ERR_NONE) {
1715 return error;
1716 }
Elliott Hughesf15f4a02013-01-09 10:09:38 -08001717 if (!IsSuspendedForDebugger(soa, thread)) {
1718 return JDWP::ERR_THREAD_NOT_SUSPENDED;
1719 }
Elliott Hughes221229c2013-01-08 18:17:50 -08001720 result = GetStackDepth(thread);
1721 return JDWP::ERR_NONE;
Elliott Hughes86964332012-02-15 19:37:42 -08001722}
1723
Ian Rogers306057f2012-11-26 12:45:53 -08001724JDWP::JdwpError Dbg::GetThreadFrames(JDWP::ObjectId thread_id, size_t start_frame,
1725 size_t frame_count, JDWP::ExpandBuf* buf) {
Elliott Hughes6e9d22c2012-06-22 15:02:37 -07001726 class GetFrameVisitor : public StackVisitor {
1727 public:
Ian Rogers306057f2012-11-26 12:45:53 -08001728 GetFrameVisitor(const ManagedStack* stack,
1729 const std::deque<InstrumentationStackFrame>* instrumentation_stack,
Elliott Hughes6e9d22c2012-06-22 15:02:37 -07001730 size_t start_frame, size_t frame_count, JDWP::ExpandBuf* buf)
Ian Rogersb726dcb2012-09-05 08:57:23 -07001731 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_)
jeffhao725a9572012-11-13 18:20:12 -08001732 : StackVisitor(stack, instrumentation_stack, NULL), depth_(0),
Elliott Hughes6e9d22c2012-06-22 15:02:37 -07001733 start_frame_(start_frame), frame_count_(frame_count), buf_(buf) {
1734 expandBufAdd4BE(buf_, frame_count_);
Elliott Hughes03181a82011-11-17 17:22:21 -08001735 }
Ian Rogers0399dde2012-06-06 17:09:28 -07001736
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001737 // TODO: Enable annotalysis. We know lock is held in constructor, but abstraction confuses
1738 // annotalysis.
1739 virtual bool VisitFrame() NO_THREAD_SAFETY_ANALYSIS {
Ian Rogers0399dde2012-06-06 17:09:28 -07001740 if (GetMethod()->IsRuntimeMethod()) {
Elliott Hughes530fa002012-03-12 11:44:49 -07001741 return true; // The debugger can't do anything useful with a frame that has no Method*.
Elliott Hughes03181a82011-11-17 17:22:21 -08001742 }
Elliott Hughes6e9d22c2012-06-22 15:02:37 -07001743 if (depth_ >= start_frame_ + frame_count_) {
Elliott Hughes530fa002012-03-12 11:44:49 -07001744 return false;
Elliott Hughes03181a82011-11-17 17:22:21 -08001745 }
Elliott Hughes6e9d22c2012-06-22 15:02:37 -07001746 if (depth_ >= start_frame_) {
1747 JDWP::FrameId frame_id(GetFrameId());
1748 JDWP::JdwpLocation location;
1749 SetLocation(location, GetMethod(), GetDexPc());
Elliott Hughes7baf96f2012-06-22 16:33:50 -07001750 VLOG(jdwp) << StringPrintf(" Frame %3zd: id=%3lld ", depth_, frame_id) << location;
Elliott Hughes6e9d22c2012-06-22 15:02:37 -07001751 expandBufAdd8BE(buf_, frame_id);
1752 expandBufAddLocation(buf_, location);
1753 }
1754 ++depth_;
Elliott Hughes530fa002012-03-12 11:44:49 -07001755 return true;
Elliott Hughes03181a82011-11-17 17:22:21 -08001756 }
Elliott Hughes6e9d22c2012-06-22 15:02:37 -07001757
1758 private:
1759 size_t depth_;
1760 const size_t start_frame_;
1761 const size_t frame_count_;
1762 JDWP::ExpandBuf* buf_;
Elliott Hughes03181a82011-11-17 17:22:21 -08001763 };
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001764
1765 ScopedObjectAccessUnchecked soa(Thread::Current());
jeffhaoa77f0f62012-12-05 17:19:31 -08001766 MutexLock mu(soa.Self(), *Locks::thread_list_lock_);
Elliott Hughes221229c2013-01-08 18:17:50 -08001767 Thread* thread;
1768 JDWP::JdwpError error = DecodeThread(soa, thread_id, thread);
1769 if (error != JDWP::ERR_NONE) {
1770 return error;
1771 }
Elliott Hughesf15f4a02013-01-09 10:09:38 -08001772 if (!IsSuspendedForDebugger(soa, thread)) {
1773 return JDWP::ERR_THREAD_NOT_SUSPENDED;
1774 }
Ian Rogers306057f2012-11-26 12:45:53 -08001775 GetFrameVisitor visitor(thread->GetManagedStack(), thread->GetInstrumentationStack(),
1776 start_frame, frame_count, buf);
Ian Rogers0399dde2012-06-06 17:09:28 -07001777 visitor.WalkStack();
Elliott Hughes6e9d22c2012-06-22 15:02:37 -07001778 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001779}
1780
1781JDWP::ObjectId Dbg::GetThreadSelfId() {
Mathieu Chartierdbe6f462012-09-25 16:54:50 -07001782 ScopedObjectAccessUnchecked soa(Thread::Current());
Ian Rogerscfaa4552012-11-26 21:00:08 -08001783 return gRegistry->Add(soa.Self()->GetPeer());
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001784}
1785
Elliott Hughes475fc232011-10-25 15:00:35 -07001786void Dbg::SuspendVM() {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001787 Runtime::Current()->GetThreadList()->SuspendAllForDebugger();
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001788}
1789
1790void Dbg::ResumeVM() {
Elliott Hughesc61a2672012-06-21 14:52:29 -07001791 Runtime::Current()->GetThreadList()->UndoDebuggerSuspensions();
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001792}
1793
Elliott Hughes221229c2013-01-08 18:17:50 -08001794JDWP::JdwpError Dbg::SuspendThread(JDWP::ObjectId thread_id, bool request_suspension) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001795 ScopedLocalRef<jobject> peer(Thread::Current()->GetJniEnv(), NULL);
1796 {
1797 ScopedObjectAccess soa(Thread::Current());
Elliott Hughes221229c2013-01-08 18:17:50 -08001798 peer.reset(soa.AddLocalReference<jobject>(gRegistry->Get<Object*>(thread_id)));
Elliott Hughes4e235312011-12-02 11:34:15 -08001799 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001800 if (peer.get() == NULL) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001801 return JDWP::ERR_THREAD_NOT_ALIVE;
1802 }
1803 // Suspend thread to build stack trace.
Elliott Hughesf327e072013-01-09 16:01:26 -08001804 bool timed_out;
1805 Thread* thread = Thread::SuspendForDebugger(peer.get(), request_suspension, &timed_out);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001806 if (thread != NULL) {
1807 return JDWP::ERR_NONE;
Elliott Hughesf327e072013-01-09 16:01:26 -08001808 } else if (timed_out) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001809 return JDWP::ERR_INTERNAL;
1810 } else {
1811 return JDWP::ERR_THREAD_NOT_ALIVE;
1812 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001813}
1814
Elliott Hughes221229c2013-01-08 18:17:50 -08001815void Dbg::ResumeThread(JDWP::ObjectId thread_id) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001816 ScopedObjectAccessUnchecked soa(Thread::Current());
Elliott Hughes221229c2013-01-08 18:17:50 -08001817 Object* peer = gRegistry->Get<Object*>(thread_id);
jeffhaoa77f0f62012-12-05 17:19:31 -08001818 Thread* thread;
1819 {
1820 MutexLock mu(soa.Self(), *Locks::thread_list_lock_);
1821 thread = Thread::FromManagedThread(soa, peer);
1822 }
Elliott Hughes4e235312011-12-02 11:34:15 -08001823 if (thread == NULL) {
1824 LOG(WARNING) << "No such thread for resume: " << peer;
1825 return;
1826 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001827 bool needs_resume;
1828 {
Ian Rogers50b35e22012-10-04 10:09:15 -07001829 MutexLock mu2(soa.Self(), *Locks::thread_suspend_count_lock_);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001830 needs_resume = thread->GetSuspendCount() > 0;
1831 }
1832 if (needs_resume) {
Elliott Hughes546b9862012-06-20 16:06:13 -07001833 Runtime::Current()->GetThreadList()->Resume(thread, true);
1834 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001835}
1836
1837void Dbg::SuspendSelf() {
Elliott Hughes475fc232011-10-25 15:00:35 -07001838 Runtime::Current()->GetThreadList()->SuspendSelfForDebugger();
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001839}
1840
Ian Rogers0399dde2012-06-06 17:09:28 -07001841struct GetThisVisitor : public StackVisitor {
Ian Rogers306057f2012-11-26 12:45:53 -08001842 GetThisVisitor(const ManagedStack* stack,
1843 const std::deque<InstrumentationStackFrame>* instrumentation_stack,
Elliott Hughes88d63092013-01-09 09:55:54 -08001844 Context* context, JDWP::FrameId frame_id)
Ian Rogersb726dcb2012-09-05 08:57:23 -07001845 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_)
Elliott Hughes88d63092013-01-09 09:55:54 -08001846 : StackVisitor(stack, instrumentation_stack, context), this_object(NULL), frame_id(frame_id) {}
Ian Rogers0399dde2012-06-06 17:09:28 -07001847
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001848 // TODO: Enable annotalysis. We know lock is held in constructor, but abstraction confuses
1849 // annotalysis.
1850 virtual bool VisitFrame() NO_THREAD_SAFETY_ANALYSIS {
Elliott Hughes6e9d22c2012-06-22 15:02:37 -07001851 if (frame_id != GetFrameId()) {
Ian Rogers0399dde2012-06-06 17:09:28 -07001852 return true; // continue
1853 }
Mathieu Chartier66f19252012-09-18 08:57:04 -07001854 AbstractMethod* m = GetMethod();
Ian Rogers0399dde2012-06-06 17:09:28 -07001855 if (m->IsNative() || m->IsStatic()) {
Elliott Hughes6e9d22c2012-06-22 15:02:37 -07001856 this_object = NULL;
Ian Rogers0399dde2012-06-06 17:09:28 -07001857 } else {
1858 uint16_t reg = DemangleSlot(0, m);
Ian Rogers2bcb4a42012-11-08 10:39:18 -08001859 this_object = reinterpret_cast<Object*>(GetVReg(m, reg, kReferenceVReg));
Ian Rogers0399dde2012-06-06 17:09:28 -07001860 }
1861 return false;
Elliott Hughes86b00102011-12-05 17:54:26 -08001862 }
Ian Rogers0399dde2012-06-06 17:09:28 -07001863
Elliott Hughes6e9d22c2012-06-22 15:02:37 -07001864 Object* this_object;
1865 JDWP::FrameId frame_id;
Ian Rogers0399dde2012-06-06 17:09:28 -07001866};
1867
Mathieu Chartier66f19252012-09-18 08:57:04 -07001868static Object* GetThis(Thread* self, AbstractMethod* m, size_t frame_id)
Ian Rogersb726dcb2012-09-05 08:57:23 -07001869 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Elliott Hughescaf76542012-06-28 16:08:22 -07001870 // TODO: should we return the 'this' we passed through to non-static native methods?
Ian Rogers0399dde2012-06-06 17:09:28 -07001871 if (m->IsNative() || m->IsStatic()) {
1872 return NULL;
1873 }
Elliott Hughescaf76542012-06-28 16:08:22 -07001874
Ian Rogers0399dde2012-06-06 17:09:28 -07001875 UniquePtr<Context> context(Context::Create());
jeffhao725a9572012-11-13 18:20:12 -08001876 GetThisVisitor visitor(self->GetManagedStack(), self->GetInstrumentationStack(), context.get(), frame_id);
Elliott Hughescaf76542012-06-28 16:08:22 -07001877 visitor.WalkStack();
1878 return visitor.this_object;
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08001879}
1880
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001881JDWP::JdwpError Dbg::GetThisObject(JDWP::ObjectId thread_id, JDWP::FrameId frame_id,
1882 JDWP::ObjectId* result) {
1883 ScopedObjectAccessUnchecked soa(Thread::Current());
1884 Thread* thread;
1885 {
Ian Rogers50b35e22012-10-04 10:09:15 -07001886 MutexLock mu(soa.Self(), *Locks::thread_list_lock_);
Elliott Hughes221229c2013-01-08 18:17:50 -08001887 JDWP::JdwpError error = DecodeThread(soa, thread_id, thread);
1888 if (error != JDWP::ERR_NONE) {
1889 return error;
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001890 }
Elliott Hughes9e0c1752013-01-09 14:02:58 -08001891 if (!IsSuspendedForDebugger(soa, thread)) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001892 return JDWP::ERR_THREAD_NOT_SUSPENDED;
1893 }
Elliott Hughes6e9d22c2012-06-22 15:02:37 -07001894 }
Elliott Hughescaf76542012-06-28 16:08:22 -07001895 UniquePtr<Context> context(Context::Create());
jeffhao725a9572012-11-13 18:20:12 -08001896 GetThisVisitor visitor(thread->GetManagedStack(), thread->GetInstrumentationStack(), context.get(), frame_id);
Ian Rogers0399dde2012-06-06 17:09:28 -07001897 visitor.WalkStack();
Elliott Hughes6e9d22c2012-06-22 15:02:37 -07001898 *result = gRegistry->Add(visitor.this_object);
1899 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001900}
1901
Elliott Hughes88d63092013-01-09 09:55:54 -08001902void Dbg::GetLocalValue(JDWP::ObjectId thread_id, JDWP::FrameId frame_id, int slot, JDWP::JdwpTag tag,
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001903 uint8_t* buf, size_t width) {
Ian Rogers0399dde2012-06-06 17:09:28 -07001904 struct GetLocalVisitor : public StackVisitor {
Ian Rogers306057f2012-11-26 12:45:53 -08001905 GetLocalVisitor(const ManagedStack* stack,
1906 const std::deque<InstrumentationStackFrame>* instrumentation_stack,
Elliott Hughes88d63092013-01-09 09:55:54 -08001907 Context* context, JDWP::FrameId frame_id, int slot, JDWP::JdwpTag tag,
Ian Rogersca190662012-06-26 15:45:57 -07001908 uint8_t* buf, size_t width)
Ian Rogersb726dcb2012-09-05 08:57:23 -07001909 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_)
Elliott Hughes88d63092013-01-09 09:55:54 -08001910 : StackVisitor(stack, instrumentation_stack, context), frame_id_(frame_id), slot_(slot), tag_(tag),
Ian Rogersca190662012-06-26 15:45:57 -07001911 buf_(buf), width_(width) {}
1912
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001913 // TODO: Enable annotalysis. We know lock is held in constructor, but abstraction confuses
1914 // annotalysis.
1915 bool VisitFrame() NO_THREAD_SAFETY_ANALYSIS {
Ian Rogers0399dde2012-06-06 17:09:28 -07001916 if (GetFrameId() != frame_id_) {
1917 return true; // Not our frame, carry on.
Elliott Hughesdbb40792011-11-18 17:05:22 -08001918 }
Ian Rogers0399dde2012-06-06 17:09:28 -07001919 // TODO: check that the tag is compatible with the actual type of the slot!
Mathieu Chartier66f19252012-09-18 08:57:04 -07001920 AbstractMethod* m = GetMethod();
Ian Rogers0399dde2012-06-06 17:09:28 -07001921 uint16_t reg = DemangleSlot(slot_, m);
Elliott Hughesdbb40792011-11-18 17:05:22 -08001922
Ian Rogers0399dde2012-06-06 17:09:28 -07001923 switch (tag_) {
1924 case JDWP::JT_BOOLEAN:
1925 {
1926 CHECK_EQ(width_, 1U);
Ian Rogers2bcb4a42012-11-08 10:39:18 -08001927 uint32_t intVal = GetVReg(m, reg, kIntVReg);
Ian Rogers0399dde2012-06-06 17:09:28 -07001928 VLOG(jdwp) << "get boolean local " << reg << " = " << intVal;
1929 JDWP::Set1(buf_+1, intVal != 0);
1930 }
1931 break;
1932 case JDWP::JT_BYTE:
1933 {
1934 CHECK_EQ(width_, 1U);
Ian Rogers2bcb4a42012-11-08 10:39:18 -08001935 uint32_t intVal = GetVReg(m, reg, kIntVReg);
Ian Rogers0399dde2012-06-06 17:09:28 -07001936 VLOG(jdwp) << "get byte local " << reg << " = " << intVal;
1937 JDWP::Set1(buf_+1, intVal);
1938 }
1939 break;
1940 case JDWP::JT_SHORT:
1941 case JDWP::JT_CHAR:
1942 {
1943 CHECK_EQ(width_, 2U);
Ian Rogers2bcb4a42012-11-08 10:39:18 -08001944 uint32_t intVal = GetVReg(m, reg, kIntVReg);
Ian Rogers0399dde2012-06-06 17:09:28 -07001945 VLOG(jdwp) << "get short/char local " << reg << " = " << intVal;
1946 JDWP::Set2BE(buf_+1, intVal);
1947 }
1948 break;
1949 case JDWP::JT_INT:
Ian Rogers2bcb4a42012-11-08 10:39:18 -08001950 {
1951 CHECK_EQ(width_, 4U);
1952 uint32_t intVal = GetVReg(m, reg, kIntVReg);
1953 VLOG(jdwp) << "get int local " << reg << " = " << intVal;
1954 JDWP::Set4BE(buf_+1, intVal);
1955 }
1956 break;
Ian Rogers0399dde2012-06-06 17:09:28 -07001957 case JDWP::JT_FLOAT:
1958 {
1959 CHECK_EQ(width_, 4U);
Ian Rogers2bcb4a42012-11-08 10:39:18 -08001960 uint32_t intVal = GetVReg(m, reg, kFloatVReg);
Ian Rogers0399dde2012-06-06 17:09:28 -07001961 VLOG(jdwp) << "get int/float local " << reg << " = " << intVal;
1962 JDWP::Set4BE(buf_+1, intVal);
1963 }
1964 break;
1965 case JDWP::JT_ARRAY:
1966 {
1967 CHECK_EQ(width_, sizeof(JDWP::ObjectId));
Ian Rogers2bcb4a42012-11-08 10:39:18 -08001968 Object* o = reinterpret_cast<Object*>(GetVReg(m, reg, kReferenceVReg));
Ian Rogers0399dde2012-06-06 17:09:28 -07001969 VLOG(jdwp) << "get array local " << reg << " = " << o;
1970 if (!Runtime::Current()->GetHeap()->IsHeapAddress(o)) {
1971 LOG(FATAL) << "Register " << reg << " expected to hold array: " << o;
1972 }
1973 JDWP::SetObjectId(buf_+1, gRegistry->Add(o));
1974 }
1975 break;
1976 case JDWP::JT_CLASS_LOADER:
1977 case JDWP::JT_CLASS_OBJECT:
1978 case JDWP::JT_OBJECT:
1979 case JDWP::JT_STRING:
1980 case JDWP::JT_THREAD:
1981 case JDWP::JT_THREAD_GROUP:
1982 {
1983 CHECK_EQ(width_, sizeof(JDWP::ObjectId));
Ian Rogers2bcb4a42012-11-08 10:39:18 -08001984 Object* o = reinterpret_cast<Object*>(GetVReg(m, reg, kReferenceVReg));
Ian Rogers0399dde2012-06-06 17:09:28 -07001985 VLOG(jdwp) << "get object local " << reg << " = " << o;
1986 if (!Runtime::Current()->GetHeap()->IsHeapAddress(o)) {
1987 LOG(FATAL) << "Register " << reg << " expected to hold object: " << o;
1988 }
1989 tag_ = TagFromObject(o);
1990 JDWP::SetObjectId(buf_+1, gRegistry->Add(o));
1991 }
1992 break;
1993 case JDWP::JT_DOUBLE:
Ian Rogers2bcb4a42012-11-08 10:39:18 -08001994 {
1995 CHECK_EQ(width_, 8U);
1996 uint32_t lo = GetVReg(m, reg, kDoubleLoVReg);
1997 uint64_t hi = GetVReg(m, reg + 1, kDoubleHiVReg);
1998 uint64_t longVal = (hi << 32) | lo;
1999 VLOG(jdwp) << "get double/long local " << hi << ":" << lo << " = " << longVal;
2000 JDWP::Set8BE(buf_+1, longVal);
2001 }
2002 break;
Ian Rogers0399dde2012-06-06 17:09:28 -07002003 case JDWP::JT_LONG:
2004 {
2005 CHECK_EQ(width_, 8U);
Ian Rogers2bcb4a42012-11-08 10:39:18 -08002006 uint32_t lo = GetVReg(m, reg, kLongLoVReg);
2007 uint64_t hi = GetVReg(m, reg + 1, kLongHiVReg);
Ian Rogers0399dde2012-06-06 17:09:28 -07002008 uint64_t longVal = (hi << 32) | lo;
2009 VLOG(jdwp) << "get double/long local " << hi << ":" << lo << " = " << longVal;
2010 JDWP::Set8BE(buf_+1, longVal);
2011 }
2012 break;
2013 default:
2014 LOG(FATAL) << "Unknown tag " << tag_;
2015 break;
2016 }
2017
2018 // Prepend tag, which may have been updated.
2019 JDWP::Set1(buf_, tag_);
2020 return false;
2021 }
2022
2023 const JDWP::FrameId frame_id_;
2024 const int slot_;
2025 JDWP::JdwpTag tag_;
2026 uint8_t* const buf_;
2027 const size_t width_;
2028 };
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002029
2030 ScopedObjectAccessUnchecked soa(Thread::Current());
jeffhaoa77f0f62012-12-05 17:19:31 -08002031 MutexLock mu(soa.Self(), *Locks::thread_list_lock_);
Elliott Hughes221229c2013-01-08 18:17:50 -08002032 Thread* thread;
2033 JDWP::JdwpError error = DecodeThread(soa, thread_id, thread);
2034 if (error != JDWP::ERR_NONE) {
2035 return;
2036 }
Ian Rogers0399dde2012-06-06 17:09:28 -07002037 UniquePtr<Context> context(Context::Create());
jeffhao725a9572012-11-13 18:20:12 -08002038 GetLocalVisitor visitor(thread->GetManagedStack(), thread->GetInstrumentationStack(), context.get(),
Elliott Hughes88d63092013-01-09 09:55:54 -08002039 frame_id, slot, tag, buf, width);
Ian Rogers0399dde2012-06-06 17:09:28 -07002040 visitor.WalkStack();
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002041}
2042
Elliott Hughes88d63092013-01-09 09:55:54 -08002043void Dbg::SetLocalValue(JDWP::ObjectId thread_id, JDWP::FrameId frame_id, int slot, JDWP::JdwpTag tag,
Ian Rogers0399dde2012-06-06 17:09:28 -07002044 uint64_t value, size_t width) {
2045 struct SetLocalVisitor : public StackVisitor {
Ian Rogers306057f2012-11-26 12:45:53 -08002046 SetLocalVisitor(const ManagedStack* stack, const std::deque<InstrumentationStackFrame>* instrumentation_stack, Context* context,
Ian Rogers0399dde2012-06-06 17:09:28 -07002047 JDWP::FrameId frame_id, int slot, JDWP::JdwpTag tag, uint64_t value,
Ian Rogersca190662012-06-26 15:45:57 -07002048 size_t width)
Ian Rogersb726dcb2012-09-05 08:57:23 -07002049 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_)
jeffhao725a9572012-11-13 18:20:12 -08002050 : StackVisitor(stack, instrumentation_stack, context),
Elliott Hughes08fc03a2012-06-26 17:34:00 -07002051 frame_id_(frame_id), slot_(slot), tag_(tag), value_(value), width_(width) {}
Ian Rogersca190662012-06-26 15:45:57 -07002052
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002053 // TODO: Enable annotalysis. We know lock is held in constructor, but abstraction confuses
2054 // annotalysis.
2055 bool VisitFrame() NO_THREAD_SAFETY_ANALYSIS {
Ian Rogers0399dde2012-06-06 17:09:28 -07002056 if (GetFrameId() != frame_id_) {
2057 return true; // Not our frame, carry on.
2058 }
2059 // TODO: check that the tag is compatible with the actual type of the slot!
Mathieu Chartier66f19252012-09-18 08:57:04 -07002060 AbstractMethod* m = GetMethod();
Ian Rogers0399dde2012-06-06 17:09:28 -07002061 uint16_t reg = DemangleSlot(slot_, m);
2062
2063 switch (tag_) {
2064 case JDWP::JT_BOOLEAN:
2065 case JDWP::JT_BYTE:
2066 CHECK_EQ(width_, 1U);
Ian Rogers2bcb4a42012-11-08 10:39:18 -08002067 SetVReg(m, reg, static_cast<uint32_t>(value_), kIntVReg);
Ian Rogers0399dde2012-06-06 17:09:28 -07002068 break;
2069 case JDWP::JT_SHORT:
2070 case JDWP::JT_CHAR:
2071 CHECK_EQ(width_, 2U);
Ian Rogers2bcb4a42012-11-08 10:39:18 -08002072 SetVReg(m, reg, static_cast<uint32_t>(value_), kIntVReg);
Ian Rogers0399dde2012-06-06 17:09:28 -07002073 break;
2074 case JDWP::JT_INT:
Ian Rogers2bcb4a42012-11-08 10:39:18 -08002075 CHECK_EQ(width_, 4U);
2076 SetVReg(m, reg, static_cast<uint32_t>(value_), kIntVReg);
2077 break;
Ian Rogers0399dde2012-06-06 17:09:28 -07002078 case JDWP::JT_FLOAT:
2079 CHECK_EQ(width_, 4U);
Ian Rogers2bcb4a42012-11-08 10:39:18 -08002080 SetVReg(m, reg, static_cast<uint32_t>(value_), kFloatVReg);
Ian Rogers0399dde2012-06-06 17:09:28 -07002081 break;
2082 case JDWP::JT_ARRAY:
2083 case JDWP::JT_OBJECT:
2084 case JDWP::JT_STRING:
2085 {
2086 CHECK_EQ(width_, sizeof(JDWP::ObjectId));
2087 Object* o = gRegistry->Get<Object*>(static_cast<JDWP::ObjectId>(value_));
2088 if (o == kInvalidObject) {
2089 UNIMPLEMENTED(FATAL) << "return an error code when given an invalid object to store";
2090 }
Ian Rogers2bcb4a42012-11-08 10:39:18 -08002091 SetVReg(m, reg, static_cast<uint32_t>(reinterpret_cast<uintptr_t>(o)), kReferenceVReg);
Ian Rogers0399dde2012-06-06 17:09:28 -07002092 }
2093 break;
2094 case JDWP::JT_DOUBLE:
Ian Rogers2bcb4a42012-11-08 10:39:18 -08002095 CHECK_EQ(width_, 8U);
2096 SetVReg(m, reg, static_cast<uint32_t>(value_), kDoubleLoVReg);
2097 SetVReg(m, reg + 1, static_cast<uint32_t>(value_ >> 32), kDoubleHiVReg);
2098 break;
Ian Rogers0399dde2012-06-06 17:09:28 -07002099 case JDWP::JT_LONG:
2100 CHECK_EQ(width_, 8U);
Ian Rogers2bcb4a42012-11-08 10:39:18 -08002101 SetVReg(m, reg, static_cast<uint32_t>(value_), kLongLoVReg);
2102 SetVReg(m, reg + 1, static_cast<uint32_t>(value_ >> 32), kLongHiVReg);
Ian Rogers0399dde2012-06-06 17:09:28 -07002103 break;
2104 default:
2105 LOG(FATAL) << "Unknown tag " << tag_;
2106 break;
2107 }
2108 return false;
2109 }
2110
2111 const JDWP::FrameId frame_id_;
2112 const int slot_;
2113 const JDWP::JdwpTag tag_;
2114 const uint64_t value_;
2115 const size_t width_;
2116 };
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002117
2118 ScopedObjectAccessUnchecked soa(Thread::Current());
jeffhaoa77f0f62012-12-05 17:19:31 -08002119 MutexLock mu(soa.Self(), *Locks::thread_list_lock_);
Elliott Hughes221229c2013-01-08 18:17:50 -08002120 Thread* thread;
2121 JDWP::JdwpError error = DecodeThread(soa, thread_id, thread);
2122 if (error != JDWP::ERR_NONE) {
2123 return;
2124 }
Elliott Hughes08fc03a2012-06-26 17:34:00 -07002125 UniquePtr<Context> context(Context::Create());
jeffhao725a9572012-11-13 18:20:12 -08002126 SetLocalVisitor visitor(thread->GetManagedStack(), thread->GetInstrumentationStack(), context.get(),
Elliott Hughes88d63092013-01-09 09:55:54 -08002127 frame_id, slot, tag, value, width);
Ian Rogers0399dde2012-06-06 17:09:28 -07002128 visitor.WalkStack();
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002129}
2130
Mathieu Chartier66f19252012-09-18 08:57:04 -07002131void Dbg::PostLocationEvent(const AbstractMethod* m, int dex_pc, Object* this_object, int event_flags) {
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08002132 Class* c = m->GetDeclaringClass();
2133
2134 JDWP::JdwpLocation location;
Elliott Hughes74847412012-06-20 18:10:21 -07002135 location.type_tag = c->IsInterface() ? JDWP::TT_INTERFACE : JDWP::TT_CLASS;
2136 location.class_id = gRegistry->Add(c);
2137 location.method_id = ToMethodId(m);
Elliott Hughes972a47b2012-02-21 18:16:06 -08002138 location.dex_pc = m->IsNative() ? -1 : dex_pc;
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08002139
2140 // Note we use "NoReg" so we don't keep track of references that are
2141 // never actually sent to the debugger. 'this_id' is only used to
2142 // compare against registered events...
2143 JDWP::ObjectId this_id = static_cast<JDWP::ObjectId>(reinterpret_cast<uintptr_t>(this_object));
2144 if (gJdwpState->PostLocationEvent(&location, this_id, event_flags)) {
2145 // ...unless there's a registered event, in which case we
2146 // need to really track the class and 'this'.
2147 gRegistry->Add(c);
2148 gRegistry->Add(this_object);
2149 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002150}
2151
Elliott Hughescaf76542012-06-28 16:08:22 -07002152void Dbg::PostException(Thread* thread,
Mathieu Chartier66f19252012-09-18 08:57:04 -07002153 JDWP::FrameId throw_frame_id, AbstractMethod* throw_method, uint32_t throw_dex_pc,
2154 AbstractMethod* catch_method, uint32_t catch_dex_pc, Throwable* exception) {
Elliott Hughesc0f09332012-03-26 13:27:06 -07002155 if (!IsDebuggerActive()) {
Ian Rogers0ad5bb82011-12-07 10:16:32 -08002156 return;
2157 }
Elliott Hughes4740cdf2011-12-07 14:07:12 -08002158
Elliott Hughesd07986f2011-12-06 18:27:45 -08002159 JDWP::JdwpLocation throw_location;
Elliott Hughescaf76542012-06-28 16:08:22 -07002160 SetLocation(throw_location, throw_method, throw_dex_pc);
Elliott Hughesd07986f2011-12-06 18:27:45 -08002161 JDWP::JdwpLocation catch_location;
Elliott Hughescaf76542012-06-28 16:08:22 -07002162 SetLocation(catch_location, catch_method, catch_dex_pc);
Elliott Hughesd07986f2011-12-06 18:27:45 -08002163
2164 // We need 'this' for InstanceOnly filters.
Elliott Hughescaf76542012-06-28 16:08:22 -07002165 UniquePtr<Context> context(Context::Create());
jeffhao725a9572012-11-13 18:20:12 -08002166 GetThisVisitor visitor(thread->GetManagedStack(), thread->GetInstrumentationStack(), context.get(), throw_frame_id);
Elliott Hughescaf76542012-06-28 16:08:22 -07002167 visitor.WalkStack();
2168 JDWP::ObjectId this_id = gRegistry->Add(visitor.this_object);
Elliott Hughesd07986f2011-12-06 18:27:45 -08002169
2170 /*
2171 * Hand the event to the JDWP exception handler. Note we're using the
2172 * "NoReg" objectID on the exception, which is not strictly correct --
2173 * the exception object WILL be passed up to the debugger if the
2174 * debugger is interested in the event. We do this because the current
2175 * implementation of the debugger object registry never throws anything
2176 * away, and some people were experiencing a fatal build up of exception
2177 * objects when dealing with certain libraries.
2178 */
2179 JDWP::ObjectId exception_id = static_cast<JDWP::ObjectId>(reinterpret_cast<uintptr_t>(exception));
2180 JDWP::RefTypeId exception_class_id = gRegistry->Add(exception->GetClass());
2181
2182 gJdwpState->PostException(&throw_location, exception_id, exception_class_id, &catch_location, this_id);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002183}
2184
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002185void Dbg::PostClassPrepare(Class* c) {
Elliott Hughesc0f09332012-03-26 13:27:06 -07002186 if (!IsDebuggerActive()) {
Elliott Hughes4740cdf2011-12-07 14:07:12 -08002187 return;
2188 }
2189
Elliott Hughes3d30d9b2011-12-07 17:35:48 -08002190 // OLD-TODO - we currently always send both "verified" and "prepared" since
Elliott Hughes4740cdf2011-12-07 14:07:12 -08002191 // debuggers seem to like that. There might be some advantage to honesty,
2192 // since the class may not yet be verified.
2193 int state = JDWP::CS_VERIFIED | JDWP::CS_PREPARED;
2194 JDWP::JdwpTypeTag tag = c->IsInterface() ? JDWP::TT_INTERFACE : JDWP::TT_CLASS;
2195 gJdwpState->PostClassPrepare(tag, gRegistry->Add(c), ClassHelper(c).GetDescriptor(), state);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002196}
2197
Elliott Hughescaf76542012-06-28 16:08:22 -07002198void Dbg::UpdateDebugger(int32_t dex_pc, Thread* self) {
Elliott Hughesc0f09332012-03-26 13:27:06 -07002199 if (!IsDebuggerActive() || dex_pc == -2 /* fake method exit */) {
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08002200 return;
2201 }
2202
Elliott Hughescaf76542012-06-28 16:08:22 -07002203 size_t frame_id;
Mathieu Chartier66f19252012-09-18 08:57:04 -07002204 AbstractMethod* m = self->GetCurrentMethod(NULL, &frame_id);
Elliott Hughescaf76542012-06-28 16:08:22 -07002205 //LOG(INFO) << "UpdateDebugger " << PrettyMethod(m) << "@" << dex_pc << " frame " << frame_id;
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08002206
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08002207 if (dex_pc == -1) {
Elliott Hughes2aa2e392012-02-17 17:15:43 -08002208 // We use a pc of -1 to represent method entry, since we might branch back to pc 0 later.
2209 // This means that for this special notification, there can't be anything else interesting
2210 // going on, so we're done already.
Elliott Hughescaf76542012-06-28 16:08:22 -07002211 Dbg::PostLocationEvent(m, 0, GetThis(self, m, frame_id), kMethodEntry);
Elliott Hughes2aa2e392012-02-17 17:15:43 -08002212 return;
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08002213 }
2214
Elliott Hughes2aa2e392012-02-17 17:15:43 -08002215 int event_flags = 0;
2216
Elliott Hughes86964332012-02-15 19:37:42 -08002217 if (IsBreakpoint(m, dex_pc)) {
2218 event_flags |= kBreakpoint;
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08002219 }
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08002220
jeffhao09bfc6a2012-12-11 18:11:43 -08002221 {
2222 // If the debugger is single-stepping one of our threads, check to
2223 // see if we're that thread and we've reached a step point.
2224 MutexLock mu(Thread::Current(), *Locks::breakpoint_lock_);
2225 if (gSingleStepControl.is_active && gSingleStepControl.thread == self) {
2226 CHECK(!m->IsNative());
2227 if (gSingleStepControl.step_depth == JDWP::SD_INTO) {
2228 // Step into method calls. We break when the line number
2229 // or method pointer changes. If we're in SS_MIN mode, we
2230 // always stop.
2231 if (gSingleStepControl.method != m) {
2232 event_flags |= kSingleStep;
2233 VLOG(jdwp) << "SS new method";
2234 } else if (gSingleStepControl.step_size == JDWP::SS_MIN) {
Elliott Hughes86964332012-02-15 19:37:42 -08002235 event_flags |= kSingleStep;
2236 VLOG(jdwp) << "SS new instruction";
Elliott Hughes2435a572012-02-17 16:07:41 -08002237 } else if (gSingleStepControl.dex_pcs.find(dex_pc) == gSingleStepControl.dex_pcs.end()) {
2238 event_flags |= kSingleStep;
2239 VLOG(jdwp) << "SS new line";
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08002240 }
jeffhao09bfc6a2012-12-11 18:11:43 -08002241 } else if (gSingleStepControl.step_depth == JDWP::SD_OVER) {
2242 // Step over method calls. We break when the line number is
2243 // different and the frame depth is <= the original frame
2244 // depth. (We can't just compare on the method, because we
2245 // might get unrolled past it by an exception, and it's tricky
2246 // to identify recursion.)
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08002247
jeffhao09bfc6a2012-12-11 18:11:43 -08002248 int stack_depth = GetStackDepth(self);
Elliott Hughes86964332012-02-15 19:37:42 -08002249
jeffhao09bfc6a2012-12-11 18:11:43 -08002250 if (stack_depth < gSingleStepControl.stack_depth) {
2251 // popped up one or more frames, always trigger
2252 event_flags |= kSingleStep;
2253 VLOG(jdwp) << "SS method pop";
2254 } else if (stack_depth == gSingleStepControl.stack_depth) {
2255 // same depth, see if we moved
2256 if (gSingleStepControl.step_size == JDWP::SS_MIN) {
2257 event_flags |= kSingleStep;
2258 VLOG(jdwp) << "SS new instruction";
2259 } else if (gSingleStepControl.dex_pcs.find(dex_pc) == gSingleStepControl.dex_pcs.end()) {
2260 event_flags |= kSingleStep;
2261 VLOG(jdwp) << "SS new line";
2262 }
2263 }
2264 } else {
2265 CHECK_EQ(gSingleStepControl.step_depth, JDWP::SD_OUT);
2266 // Return from the current method. We break when the frame
2267 // depth pops up.
2268
2269 // This differs from the "method exit" break in that it stops
2270 // with the PC at the next instruction in the returned-to
2271 // function, rather than the end of the returning function.
2272
2273 int stack_depth = GetStackDepth(self);
2274 if (stack_depth < gSingleStepControl.stack_depth) {
2275 event_flags |= kSingleStep;
2276 VLOG(jdwp) << "SS method pop";
2277 }
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08002278 }
2279 }
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08002280 }
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08002281
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08002282 // Check to see if this is a "return" instruction. JDWP says we should
2283 // send the event *after* the code has been executed, but it also says
2284 // the location we provide is the last instruction. Since the "return"
2285 // instruction has no interesting side effects, we should be safe.
2286 // (We can't just move this down to the returnFromMethod label because
2287 // we potentially need to combine it with other events.)
2288 // We're also not supposed to generate a method exit event if the method
2289 // terminates "with a thrown exception".
Elliott Hughes86964332012-02-15 19:37:42 -08002290 if (dex_pc >= 0) {
2291 const DexFile::CodeItem* code_item = MethodHelper(m).GetCodeItem();
Elliott Hughescaf76542012-06-28 16:08:22 -07002292 CHECK(code_item != NULL) << PrettyMethod(m) << " @" << dex_pc;
Elliott Hughes86964332012-02-15 19:37:42 -08002293 CHECK_LT(dex_pc, static_cast<int32_t>(code_item->insns_size_in_code_units_));
2294 if (Instruction::At(&code_item->insns_[dex_pc])->IsReturn()) {
2295 event_flags |= kMethodExit;
2296 }
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08002297 }
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08002298
2299 // If there's something interesting going on, see if it matches one
2300 // of the debugger filters.
2301 if (event_flags != 0) {
Elliott Hughescaf76542012-06-28 16:08:22 -07002302 Dbg::PostLocationEvent(m, dex_pc, GetThis(self, m, frame_id), event_flags);
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08002303 }
2304}
2305
Elliott Hughes86964332012-02-15 19:37:42 -08002306void Dbg::WatchLocation(const JDWP::JdwpLocation* location) {
jeffhao09bfc6a2012-12-11 18:11:43 -08002307 MutexLock mu(Thread::Current(), *Locks::breakpoint_lock_);
Mathieu Chartier66f19252012-09-18 08:57:04 -07002308 AbstractMethod* m = FromMethodId(location->method_id);
Elliott Hughes972a47b2012-02-21 18:16:06 -08002309 gBreakpoints.push_back(Breakpoint(m, location->dex_pc));
Elliott Hughes86964332012-02-15 19:37:42 -08002310 VLOG(jdwp) << "Set breakpoint #" << (gBreakpoints.size() - 1) << ": " << gBreakpoints[gBreakpoints.size() - 1];
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002311}
2312
Elliott Hughes86964332012-02-15 19:37:42 -08002313void Dbg::UnwatchLocation(const JDWP::JdwpLocation* location) {
jeffhao09bfc6a2012-12-11 18:11:43 -08002314 MutexLock mu(Thread::Current(), *Locks::breakpoint_lock_);
Mathieu Chartier66f19252012-09-18 08:57:04 -07002315 AbstractMethod* m = FromMethodId(location->method_id);
Elliott Hughes86964332012-02-15 19:37:42 -08002316 for (size_t i = 0; i < gBreakpoints.size(); ++i) {
Elliott Hughes972a47b2012-02-21 18:16:06 -08002317 if (gBreakpoints[i].method == m && gBreakpoints[i].dex_pc == location->dex_pc) {
Elliott Hughes86964332012-02-15 19:37:42 -08002318 VLOG(jdwp) << "Removed breakpoint #" << i << ": " << gBreakpoints[i];
2319 gBreakpoints.erase(gBreakpoints.begin() + i);
2320 return;
2321 }
2322 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002323}
2324
Elliott Hughes221229c2013-01-08 18:17:50 -08002325JDWP::JdwpError Dbg::ConfigureStep(JDWP::ObjectId thread_id, JDWP::JdwpStepSize step_size,
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002326 JDWP::JdwpStepDepth step_depth) {
2327 ScopedObjectAccessUnchecked soa(Thread::Current());
jeffhaoa77f0f62012-12-05 17:19:31 -08002328 MutexLock mu(soa.Self(), *Locks::thread_list_lock_);
Elliott Hughes221229c2013-01-08 18:17:50 -08002329 Thread* thread;
2330 JDWP::JdwpError error = DecodeThread(soa, thread_id, thread);
2331 if (error != JDWP::ERR_NONE) {
2332 return error;
Elliott Hughes2435a572012-02-17 16:07:41 -08002333 }
Elliott Hughes86964332012-02-15 19:37:42 -08002334
jeffhao09bfc6a2012-12-11 18:11:43 -08002335 MutexLock mu2(soa.Self(), *Locks::breakpoint_lock_);
Elliott Hughes86964332012-02-15 19:37:42 -08002336 // TODO: there's no theoretical reason why we couldn't support single-stepping
2337 // of multiple threads at once, but we never did so historically.
2338 if (gSingleStepControl.thread != NULL && thread != gSingleStepControl.thread) {
2339 LOG(WARNING) << "single-step already active for " << *gSingleStepControl.thread
2340 << "; switching to " << *thread;
2341 }
2342
Elliott Hughes2435a572012-02-17 16:07:41 -08002343 //
2344 // Work out what Method* we're in, the current line number, and how deep the stack currently
2345 // is for step-out.
2346 //
2347
Ian Rogers0399dde2012-06-06 17:09:28 -07002348 struct SingleStepStackVisitor : public StackVisitor {
2349 SingleStepStackVisitor(const ManagedStack* stack,
Ian Rogers306057f2012-11-26 12:45:53 -08002350 const std::deque<InstrumentationStackFrame>* instrumentation_stack)
jeffhao09bfc6a2012-12-11 18:11:43 -08002351 EXCLUSIVE_LOCKS_REQUIRED(Locks::breakpoint_lock_)
Ian Rogersb726dcb2012-09-05 08:57:23 -07002352 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_)
jeffhao725a9572012-11-13 18:20:12 -08002353 : StackVisitor(stack, instrumentation_stack, NULL) {
Elliott Hughes86964332012-02-15 19:37:42 -08002354 gSingleStepControl.method = NULL;
2355 gSingleStepControl.stack_depth = 0;
2356 }
Ian Rogersca190662012-06-26 15:45:57 -07002357
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002358 // TODO: Enable annotalysis. We know lock is held in constructor, but abstraction confuses
2359 // annotalysis.
2360 bool VisitFrame() NO_THREAD_SAFETY_ANALYSIS {
jeffhao09bfc6a2012-12-11 18:11:43 -08002361 Locks::breakpoint_lock_->AssertHeld(Thread::Current());
Mathieu Chartier66f19252012-09-18 08:57:04 -07002362 const AbstractMethod* m = GetMethod();
Ian Rogers0399dde2012-06-06 17:09:28 -07002363 if (!m->IsRuntimeMethod()) {
Elliott Hughes86964332012-02-15 19:37:42 -08002364 ++gSingleStepControl.stack_depth;
2365 if (gSingleStepControl.method == NULL) {
Elliott Hughes2435a572012-02-17 16:07:41 -08002366 const DexCache* dex_cache = m->GetDeclaringClass()->GetDexCache();
2367 gSingleStepControl.method = m;
2368 gSingleStepControl.line_number = -1;
2369 if (dex_cache != NULL) {
Ian Rogers4445a7e2012-10-05 17:19:13 -07002370 const DexFile& dex_file = *dex_cache->GetDexFile();
Ian Rogers0399dde2012-06-06 17:09:28 -07002371 gSingleStepControl.line_number = dex_file.GetLineNumFromPC(m, GetDexPc());
Elliott Hughes2435a572012-02-17 16:07:41 -08002372 }
Elliott Hughes86964332012-02-15 19:37:42 -08002373 }
2374 }
Elliott Hughes530fa002012-03-12 11:44:49 -07002375 return true;
Elliott Hughes86964332012-02-15 19:37:42 -08002376 }
2377 };
jeffhao725a9572012-11-13 18:20:12 -08002378 SingleStepStackVisitor visitor(thread->GetManagedStack(), thread->GetInstrumentationStack());
Ian Rogers0399dde2012-06-06 17:09:28 -07002379 visitor.WalkStack();
Elliott Hughes86964332012-02-15 19:37:42 -08002380
Elliott Hughes2435a572012-02-17 16:07:41 -08002381 //
2382 // Find the dex_pc values that correspond to the current line, for line-based single-stepping.
2383 //
2384
2385 struct DebugCallbackContext {
jeffhao09bfc6a2012-12-11 18:11:43 -08002386 DebugCallbackContext() EXCLUSIVE_LOCKS_REQUIRED(Locks::breakpoint_lock_) {
Elliott Hughes2435a572012-02-17 16:07:41 -08002387 last_pc_valid = false;
2388 last_pc = 0;
Elliott Hughes2435a572012-02-17 16:07:41 -08002389 }
2390
jeffhao09bfc6a2012-12-11 18:11:43 -08002391 // TODO: Enable annotalysis. We know lock is held in constructor, but abstraction confuses
2392 // annotalysis.
2393 static bool Callback(void* raw_context, uint32_t address, uint32_t line_number) NO_THREAD_SAFETY_ANALYSIS {
2394 Locks::breakpoint_lock_->AssertHeld(Thread::Current());
Elliott Hughes2435a572012-02-17 16:07:41 -08002395 DebugCallbackContext* context = reinterpret_cast<DebugCallbackContext*>(raw_context);
2396 if (static_cast<int32_t>(line_number) == gSingleStepControl.line_number) {
2397 if (!context->last_pc_valid) {
2398 // Everything from this address until the next line change is ours.
2399 context->last_pc = address;
2400 context->last_pc_valid = true;
2401 }
2402 // Otherwise, if we're already in a valid range for this line,
2403 // just keep going (shouldn't really happen)...
2404 } else if (context->last_pc_valid) { // and the line number is new
2405 // Add everything from the last entry up until here to the set
2406 for (uint32_t dex_pc = context->last_pc; dex_pc < address; ++dex_pc) {
2407 gSingleStepControl.dex_pcs.insert(dex_pc);
2408 }
2409 context->last_pc_valid = false;
2410 }
2411 return false; // There may be multiple entries for any given line.
2412 }
2413
jeffhao09bfc6a2012-12-11 18:11:43 -08002414 // TODO: Enable annotalysis. We know lock is held in constructor, but abstraction confuses
2415 // annotalysis.
2416 ~DebugCallbackContext() NO_THREAD_SAFETY_ANALYSIS {
2417 Locks::breakpoint_lock_->AssertHeld(Thread::Current());
Elliott Hughes2435a572012-02-17 16:07:41 -08002418 // If the line number was the last in the position table...
2419 if (last_pc_valid) {
2420 size_t end = MethodHelper(gSingleStepControl.method).GetCodeItem()->insns_size_in_code_units_;
2421 for (uint32_t dex_pc = last_pc; dex_pc < end; ++dex_pc) {
2422 gSingleStepControl.dex_pcs.insert(dex_pc);
2423 }
2424 }
2425 }
2426
2427 bool last_pc_valid;
2428 uint32_t last_pc;
2429 };
Elliott Hughes3e2e1a22012-02-21 11:33:41 -08002430 gSingleStepControl.dex_pcs.clear();
Mathieu Chartier66f19252012-09-18 08:57:04 -07002431 const AbstractMethod* m = gSingleStepControl.method;
Elliott Hughes3e2e1a22012-02-21 11:33:41 -08002432 if (m->IsNative()) {
2433 gSingleStepControl.line_number = -1;
2434 } else {
2435 DebugCallbackContext context;
2436 MethodHelper mh(m);
2437 mh.GetDexFile().DecodeDebugInfo(mh.GetCodeItem(), m->IsStatic(), m->GetDexMethodIndex(),
2438 DebugCallbackContext::Callback, NULL, &context);
2439 }
Elliott Hughes2435a572012-02-17 16:07:41 -08002440
2441 //
2442 // Everything else...
2443 //
2444
Elliott Hughes86964332012-02-15 19:37:42 -08002445 gSingleStepControl.thread = thread;
2446 gSingleStepControl.step_size = step_size;
2447 gSingleStepControl.step_depth = step_depth;
2448 gSingleStepControl.is_active = true;
2449
Elliott Hughes2435a572012-02-17 16:07:41 -08002450 if (VLOG_IS_ON(jdwp)) {
2451 VLOG(jdwp) << "Single-step thread: " << *gSingleStepControl.thread;
2452 VLOG(jdwp) << "Single-step step size: " << gSingleStepControl.step_size;
2453 VLOG(jdwp) << "Single-step step depth: " << gSingleStepControl.step_depth;
2454 VLOG(jdwp) << "Single-step current method: " << PrettyMethod(gSingleStepControl.method);
2455 VLOG(jdwp) << "Single-step current line: " << gSingleStepControl.line_number;
2456 VLOG(jdwp) << "Single-step current stack depth: " << gSingleStepControl.stack_depth;
2457 VLOG(jdwp) << "Single-step dex_pc values:";
2458 for (std::set<uint32_t>::iterator it = gSingleStepControl.dex_pcs.begin() ; it != gSingleStepControl.dex_pcs.end(); ++it) {
Elliott Hughes229feb72012-02-23 13:33:29 -08002459 VLOG(jdwp) << StringPrintf(" %#x", *it);
Elliott Hughes2435a572012-02-17 16:07:41 -08002460 }
2461 }
2462
2463 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002464}
2465
Elliott Hughes221229c2013-01-08 18:17:50 -08002466void Dbg::UnconfigureStep(JDWP::ObjectId /*thread_id*/) {
jeffhao09bfc6a2012-12-11 18:11:43 -08002467 MutexLock mu(Thread::Current(), *Locks::breakpoint_lock_);
Elliott Hughesf8349362012-06-18 15:00:06 -07002468
Elliott Hughes86964332012-02-15 19:37:42 -08002469 gSingleStepControl.is_active = false;
2470 gSingleStepControl.thread = NULL;
Elliott Hughes2435a572012-02-17 16:07:41 -08002471 gSingleStepControl.dex_pcs.clear();
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002472}
2473
Elliott Hughes45651fd2012-02-21 15:48:20 -08002474static char JdwpTagToShortyChar(JDWP::JdwpTag tag) {
2475 switch (tag) {
2476 default:
2477 LOG(FATAL) << "unknown JDWP tag: " << PrintableChar(tag);
2478
2479 // Primitives.
2480 case JDWP::JT_BYTE: return 'B';
2481 case JDWP::JT_CHAR: return 'C';
2482 case JDWP::JT_FLOAT: return 'F';
2483 case JDWP::JT_DOUBLE: return 'D';
2484 case JDWP::JT_INT: return 'I';
2485 case JDWP::JT_LONG: return 'J';
2486 case JDWP::JT_SHORT: return 'S';
2487 case JDWP::JT_VOID: return 'V';
2488 case JDWP::JT_BOOLEAN: return 'Z';
2489
2490 // Reference types.
2491 case JDWP::JT_ARRAY:
2492 case JDWP::JT_OBJECT:
2493 case JDWP::JT_STRING:
2494 case JDWP::JT_THREAD:
2495 case JDWP::JT_THREAD_GROUP:
2496 case JDWP::JT_CLASS_LOADER:
2497 case JDWP::JT_CLASS_OBJECT:
2498 return 'L';
2499 }
2500}
2501
Elliott Hughes88d63092013-01-09 09:55:54 -08002502JDWP::JdwpError Dbg::InvokeMethod(JDWP::ObjectId thread_id, JDWP::ObjectId object_id,
2503 JDWP::RefTypeId class_id, JDWP::MethodId method_id,
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002504 uint32_t arg_count, uint64_t* arg_values,
2505 JDWP::JdwpTag* arg_types, uint32_t options,
2506 JDWP::JdwpTag* pResultTag, uint64_t* pResultValue,
2507 JDWP::ObjectId* pExceptionId) {
Elliott Hughesd07986f2011-12-06 18:27:45 -08002508 ThreadList* thread_list = Runtime::Current()->GetThreadList();
2509
2510 Thread* targetThread = NULL;
2511 DebugInvokeReq* req = NULL;
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002512 Thread* self = Thread::Current();
Elliott Hughesd07986f2011-12-06 18:27:45 -08002513 {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002514 ScopedObjectAccessUnchecked soa(self);
Ian Rogers50b35e22012-10-04 10:09:15 -07002515 MutexLock mu(soa.Self(), *Locks::thread_list_lock_);
Elliott Hughes221229c2013-01-08 18:17:50 -08002516 JDWP::JdwpError error = DecodeThread(soa, thread_id, targetThread);
2517 if (error != JDWP::ERR_NONE) {
2518 LOG(ERROR) << "InvokeMethod request for invalid thread id " << thread_id;
2519 return error;
Elliott Hughesd07986f2011-12-06 18:27:45 -08002520 }
2521 req = targetThread->GetInvokeReq();
2522 if (!req->ready) {
2523 LOG(ERROR) << "InvokeMethod request for thread not stopped by event: " << *targetThread;
2524 return JDWP::ERR_INVALID_THREAD;
2525 }
2526
2527 /*
2528 * We currently have a bug where we don't successfully resume the
2529 * target thread if the suspend count is too deep. We're expected to
2530 * require one "resume" for each "suspend", but when asked to execute
2531 * a method we have to resume fully and then re-suspend it back to the
2532 * same level. (The easiest way to cause this is to type "suspend"
2533 * multiple times in jdb.)
2534 *
2535 * It's unclear what this means when the event specifies "resume all"
2536 * and some threads are suspended more deeply than others. This is
2537 * a rare problem, so for now we just prevent it from hanging forever
2538 * by rejecting the method invocation request. Without this, we will
2539 * be stuck waiting on a suspended thread.
2540 */
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002541 int suspend_count;
2542 {
Ian Rogers50b35e22012-10-04 10:09:15 -07002543 MutexLock mu2(soa.Self(), *Locks::thread_suspend_count_lock_);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002544 suspend_count = targetThread->GetSuspendCount();
2545 }
Elliott Hughesd07986f2011-12-06 18:27:45 -08002546 if (suspend_count > 1) {
2547 LOG(ERROR) << *targetThread << " suspend count too deep for method invocation: " << suspend_count;
2548 return JDWP::ERR_THREAD_SUSPENDED; // Probably not expected here.
2549 }
2550
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08002551 JDWP::JdwpError status;
Elliott Hughes88d63092013-01-09 09:55:54 -08002552 Object* receiver = gRegistry->Get<Object*>(object_id);
Elliott Hughes45651fd2012-02-21 15:48:20 -08002553 if (receiver == kInvalidObject) {
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08002554 return JDWP::ERR_INVALID_OBJECT;
2555 }
Elliott Hughes45651fd2012-02-21 15:48:20 -08002556
Elliott Hughes221229c2013-01-08 18:17:50 -08002557 Object* thread = gRegistry->Get<Object*>(thread_id);
Elliott Hughes45651fd2012-02-21 15:48:20 -08002558 if (thread == kInvalidObject) {
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08002559 return JDWP::ERR_INVALID_OBJECT;
2560 }
Elliott Hughes45651fd2012-02-21 15:48:20 -08002561 // TODO: check that 'thread' is actually a java.lang.Thread!
2562
Elliott Hughes88d63092013-01-09 09:55:54 -08002563 Class* c = DecodeClass(class_id, status);
Elliott Hughes45651fd2012-02-21 15:48:20 -08002564 if (c == NULL) {
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08002565 return status;
2566 }
Elliott Hughes45651fd2012-02-21 15:48:20 -08002567
Elliott Hughes88d63092013-01-09 09:55:54 -08002568 AbstractMethod* m = FromMethodId(method_id);
Elliott Hughes45651fd2012-02-21 15:48:20 -08002569 if (m->IsStatic() != (receiver == NULL)) {
2570 return JDWP::ERR_INVALID_METHODID;
2571 }
2572 if (m->IsStatic()) {
2573 if (m->GetDeclaringClass() != c) {
2574 return JDWP::ERR_INVALID_METHODID;
2575 }
2576 } else {
2577 if (!m->GetDeclaringClass()->IsAssignableFrom(c)) {
2578 return JDWP::ERR_INVALID_METHODID;
2579 }
2580 }
2581
2582 // Check the argument list matches the method.
2583 MethodHelper mh(m);
2584 if (mh.GetShortyLength() - 1 != arg_count) {
2585 return JDWP::ERR_ILLEGAL_ARGUMENT;
2586 }
2587 const char* shorty = mh.GetShorty();
2588 for (size_t i = 0; i < arg_count; ++i) {
2589 if (shorty[i + 1] != JdwpTagToShortyChar(arg_types[i])) {
2590 return JDWP::ERR_ILLEGAL_ARGUMENT;
2591 }
2592 }
2593
2594 req->receiver_ = receiver;
2595 req->thread_ = thread;
2596 req->class_ = c;
2597 req->method_ = m;
2598 req->arg_count_ = arg_count;
2599 req->arg_values_ = arg_values;
Elliott Hughesd07986f2011-12-06 18:27:45 -08002600 req->options_ = options;
2601 req->invoke_needed_ = true;
2602 }
2603
2604 // The fact that we've released the thread list lock is a bit risky --- if the thread goes
2605 // away we're sitting high and dry -- but we must release this before the ResumeAllThreads
2606 // call, and it's unwise to hold it during WaitForSuspend.
2607
2608 {
2609 /*
2610 * We change our (JDWP thread) status, which should be THREAD_RUNNING,
Elliott Hughes81ff3182012-03-23 20:35:56 -07002611 * so we can suspend for a GC if the invoke request causes us to
Elliott Hughesd07986f2011-12-06 18:27:45 -08002612 * run out of memory. It's also a good idea to change it before locking
2613 * the invokeReq mutex, although that should never be held for long.
2614 */
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002615 self->TransitionFromRunnableToSuspended(kWaitingForDebuggerSend);
Elliott Hughesd07986f2011-12-06 18:27:45 -08002616
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08002617 VLOG(jdwp) << " Transferring control to event thread";
Elliott Hughesd07986f2011-12-06 18:27:45 -08002618 {
Ian Rogers50b35e22012-10-04 10:09:15 -07002619 MutexLock mu(self, req->lock_);
Elliott Hughesd07986f2011-12-06 18:27:45 -08002620
2621 if ((options & JDWP::INVOKE_SINGLE_THREADED) == 0) {
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08002622 VLOG(jdwp) << " Resuming all threads";
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002623 thread_list->UndoDebuggerSuspensions();
Elliott Hughesd07986f2011-12-06 18:27:45 -08002624 } else {
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08002625 VLOG(jdwp) << " Resuming event thread only";
Elliott Hughesd07986f2011-12-06 18:27:45 -08002626 thread_list->Resume(targetThread, true);
2627 }
2628
2629 // Wait for the request to finish executing.
2630 while (req->invoke_needed_) {
Ian Rogersc604d732012-10-14 16:09:54 -07002631 req->cond_.Wait(self);
Elliott Hughesd07986f2011-12-06 18:27:45 -08002632 }
2633 }
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08002634 VLOG(jdwp) << " Control has returned from event thread";
Elliott Hughesd07986f2011-12-06 18:27:45 -08002635
2636 /* wait for thread to re-suspend itself */
Elliott Hughes221229c2013-01-08 18:17:50 -08002637 SuspendThread(thread_id, false /* request_suspension */ );
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002638 self->TransitionFromSuspendedToRunnable();
Elliott Hughesd07986f2011-12-06 18:27:45 -08002639 }
2640
2641 /*
2642 * Suspend the threads. We waited for the target thread to suspend
2643 * itself, so all we need to do is suspend the others.
2644 *
2645 * The suspendAllThreads() call will double-suspend the event thread,
2646 * so we want to resume the target thread once to keep the books straight.
2647 */
2648 if ((options & JDWP::INVOKE_SINGLE_THREADED) == 0) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002649 self->TransitionFromRunnableToSuspended(kWaitingForDebuggerSuspension);
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08002650 VLOG(jdwp) << " Suspending all threads";
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002651 thread_list->SuspendAllForDebugger();
2652 self->TransitionFromSuspendedToRunnable();
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08002653 VLOG(jdwp) << " Resuming event thread to balance the count";
Elliott Hughesd07986f2011-12-06 18:27:45 -08002654 thread_list->Resume(targetThread, true);
2655 }
2656
2657 // Copy the result.
2658 *pResultTag = req->result_tag;
2659 if (IsPrimitiveTag(req->result_tag)) {
Elliott Hughesf24d3ce2012-04-11 17:43:37 -07002660 *pResultValue = req->result_value.GetJ();
Elliott Hughesd07986f2011-12-06 18:27:45 -08002661 } else {
Elliott Hughesf24d3ce2012-04-11 17:43:37 -07002662 *pResultValue = gRegistry->Add(req->result_value.GetL());
Elliott Hughesd07986f2011-12-06 18:27:45 -08002663 }
2664 *pExceptionId = req->exception;
2665 return req->error;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002666}
2667
2668void Dbg::ExecuteMethod(DebugInvokeReq* pReq) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002669 ScopedObjectAccess soa(Thread::Current());
Elliott Hughesd07986f2011-12-06 18:27:45 -08002670
Elliott Hughes81ff3182012-03-23 20:35:56 -07002671 // We can be called while an exception is pending. We need
Elliott Hughesd07986f2011-12-06 18:27:45 -08002672 // to preserve that across the method invocation.
Ian Rogers1f539342012-10-03 21:09:42 -07002673 SirtRef<Throwable> old_exception(soa.Self(), soa.Self()->GetException());
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002674 soa.Self()->ClearException();
Elliott Hughesd07986f2011-12-06 18:27:45 -08002675
2676 // Translate the method through the vtable, unless the debugger wants to suppress it.
Mathieu Chartier66f19252012-09-18 08:57:04 -07002677 AbstractMethod* m = pReq->method_;
Elliott Hughesd07986f2011-12-06 18:27:45 -08002678 if ((pReq->options_ & JDWP::INVOKE_NONVIRTUAL) == 0 && pReq->receiver_ != NULL) {
Mathieu Chartier66f19252012-09-18 08:57:04 -07002679 AbstractMethod* actual_method = pReq->class_->FindVirtualMethodForVirtualOrInterface(pReq->method_);
Elliott Hughes45651fd2012-02-21 15:48:20 -08002680 if (actual_method != m) {
2681 VLOG(jdwp) << "ExecuteMethod translated " << PrettyMethod(m) << " to " << PrettyMethod(actual_method);
2682 m = actual_method;
2683 }
Elliott Hughesd07986f2011-12-06 18:27:45 -08002684 }
Elliott Hughes45651fd2012-02-21 15:48:20 -08002685 VLOG(jdwp) << "ExecuteMethod " << PrettyMethod(m);
Elliott Hughesd07986f2011-12-06 18:27:45 -08002686 CHECK(m != NULL);
2687
2688 CHECK_EQ(sizeof(jvalue), sizeof(uint64_t));
2689
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002690 LOG(INFO) << "self=" << soa.Self() << " pReq->receiver_=" << pReq->receiver_ << " m=" << m
2691 << " #" << pReq->arg_count_ << " " << pReq->arg_values_;
2692 pReq->result_value = InvokeWithJValues(soa, pReq->receiver_, m,
2693 reinterpret_cast<JValue*>(pReq->arg_values_));
Elliott Hughesd07986f2011-12-06 18:27:45 -08002694
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002695 pReq->exception = gRegistry->Add(soa.Self()->GetException());
Elliott Hughesd07986f2011-12-06 18:27:45 -08002696 pReq->result_tag = BasicTagFromDescriptor(MethodHelper(m).GetShorty());
2697 if (pReq->exception != 0) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002698 Object* exc = soa.Self()->GetException();
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08002699 VLOG(jdwp) << " JDWP invocation returning with exception=" << exc << " " << PrettyTypeOf(exc);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002700 soa.Self()->ClearException();
Elliott Hughesf24d3ce2012-04-11 17:43:37 -07002701 pReq->result_value.SetJ(0);
Elliott Hughesd07986f2011-12-06 18:27:45 -08002702 } else if (pReq->result_tag == JDWP::JT_OBJECT) {
2703 /* if no exception thrown, examine object result more closely */
Elliott Hughesf24d3ce2012-04-11 17:43:37 -07002704 JDWP::JdwpTag new_tag = TagFromObject(pReq->result_value.GetL());
Elliott Hughesd07986f2011-12-06 18:27:45 -08002705 if (new_tag != pReq->result_tag) {
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08002706 VLOG(jdwp) << " JDWP promoted result from " << pReq->result_tag << " to " << new_tag;
Elliott Hughesd07986f2011-12-06 18:27:45 -08002707 pReq->result_tag = new_tag;
2708 }
2709
2710 /*
2711 * Register the object. We don't actually need an ObjectId yet,
2712 * but we do need to be sure that the GC won't move or discard the
2713 * object when we switch out of RUNNING. The ObjectId conversion
2714 * will add the object to the "do not touch" list.
2715 *
2716 * We can't use the "tracked allocation" mechanism here because
2717 * the object is going to be handed off to a different thread.
2718 */
Elliott Hughesf24d3ce2012-04-11 17:43:37 -07002719 gRegistry->Add(pReq->result_value.GetL());
Elliott Hughesd07986f2011-12-06 18:27:45 -08002720 }
2721
2722 if (old_exception.get() != NULL) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002723 soa.Self()->SetException(old_exception.get());
Elliott Hughesd07986f2011-12-06 18:27:45 -08002724 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002725}
2726
Elliott Hughesd07986f2011-12-06 18:27:45 -08002727/*
2728 * Register an object ID that might not have been registered previously.
2729 *
2730 * Normally this wouldn't happen -- the conversion to an ObjectId would
2731 * have added the object to the registry -- but in some cases (e.g.
2732 * throwing exceptions) we really want to do the registration late.
2733 */
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002734void Dbg::RegisterObjectId(JDWP::ObjectId id) {
Elliott Hughesd07986f2011-12-06 18:27:45 -08002735 gRegistry->Add(reinterpret_cast<Object*>(id));
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002736}
2737
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07002738/*
2739 * "buf" contains a full JDWP packet, possibly with multiple chunks. We
2740 * need to process each, accumulate the replies, and ship the whole thing
2741 * back.
2742 *
2743 * Returns "true" if we have a reply. The reply buffer is newly allocated,
2744 * and includes the chunk type/length, followed by the data.
2745 *
Elliott Hughes3d30d9b2011-12-07 17:35:48 -08002746 * OLD-TODO: we currently assume that the request and reply include a single
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07002747 * chunk. If this becomes inconvenient we will need to adapt.
2748 */
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002749bool Dbg::DdmHandlePacket(const uint8_t* buf, int dataLen, uint8_t** pReplyBuf, int* pReplyLen) {
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07002750 CHECK_GE(dataLen, 0);
2751
2752 Thread* self = Thread::Current();
2753 JNIEnv* env = self->GetJniEnv();
2754
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07002755 // Create a byte[] corresponding to 'buf'.
Elliott Hughes6a5bd492011-10-28 14:33:57 -07002756 ScopedLocalRef<jbyteArray> dataArray(env, env->NewByteArray(dataLen));
2757 if (dataArray.get() == NULL) {
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07002758 LOG(WARNING) << "byte[] allocation failed: " << dataLen;
2759 env->ExceptionClear();
2760 return false;
2761 }
Elliott Hughes6a5bd492011-10-28 14:33:57 -07002762 env->SetByteArrayRegion(dataArray.get(), 0, dataLen, reinterpret_cast<const jbyte*>(buf));
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07002763
2764 const int kChunkHdrLen = 8;
2765
2766 // Run through and find all chunks. [Currently just find the first.]
Elliott Hughes6a5bd492011-10-28 14:33:57 -07002767 ScopedByteArrayRO contents(env, dataArray.get());
Elliott Hughesf7c3b662011-10-27 12:04:56 -07002768 jint type = JDWP::Get4BE(reinterpret_cast<const uint8_t*>(&contents[0]));
2769 jint length = JDWP::Get4BE(reinterpret_cast<const uint8_t*>(&contents[4]));
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07002770 jint offset = kChunkHdrLen;
2771 if (offset + length > dataLen) {
2772 LOG(WARNING) << StringPrintf("bad chunk found (len=%u pktLen=%d)", length, dataLen);
2773 return false;
2774 }
2775
2776 // Call "private static Chunk dispatch(int type, byte[] data, int offset, int length)".
Elliott Hugheseac76672012-05-24 21:56:51 -07002777 ScopedLocalRef<jobject> chunk(env, env->CallStaticObjectMethod(WellKnownClasses::org_apache_harmony_dalvik_ddmc_DdmServer,
2778 WellKnownClasses::org_apache_harmony_dalvik_ddmc_DdmServer_dispatch,
2779 type, dataArray.get(), offset, length));
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07002780 if (env->ExceptionCheck()) {
2781 LOG(INFO) << StringPrintf("Exception thrown by dispatcher for 0x%08x", type);
2782 env->ExceptionDescribe();
2783 env->ExceptionClear();
2784 return false;
2785 }
2786
Elliott Hughes6a5bd492011-10-28 14:33:57 -07002787 if (chunk.get() == NULL) {
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07002788 return false;
2789 }
2790
2791 /*
2792 * Pull the pieces out of the chunk. We copy the results into a
2793 * newly-allocated buffer that the caller can free. We don't want to
2794 * continue using the Chunk object because nothing has a reference to it.
2795 *
2796 * We could avoid this by returning type/data/offset/length and having
2797 * the caller be aware of the object lifetime issues, but that
Elliott Hughes81ff3182012-03-23 20:35:56 -07002798 * integrates the JDWP code more tightly into the rest of the runtime, and doesn't work
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07002799 * if we have responses for multiple chunks.
2800 *
2801 * So we're pretty much stuck with copying data around multiple times.
2802 */
Elliott Hugheseac76672012-05-24 21:56:51 -07002803 ScopedLocalRef<jbyteArray> replyData(env, reinterpret_cast<jbyteArray>(env->GetObjectField(chunk.get(), WellKnownClasses::org_apache_harmony_dalvik_ddmc_Chunk_data)));
2804 length = env->GetIntField(chunk.get(), WellKnownClasses::org_apache_harmony_dalvik_ddmc_Chunk_length);
2805 offset = env->GetIntField(chunk.get(), WellKnownClasses::org_apache_harmony_dalvik_ddmc_Chunk_offset);
2806 type = env->GetIntField(chunk.get(), WellKnownClasses::org_apache_harmony_dalvik_ddmc_Chunk_type);
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07002807
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08002808 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 -07002809 if (length == 0 || replyData.get() == NULL) {
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07002810 return false;
2811 }
2812
Elliott Hughes6a5bd492011-10-28 14:33:57 -07002813 jsize replyLength = env->GetArrayLength(replyData.get());
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07002814 if (offset + length > replyLength) {
2815 LOG(WARNING) << StringPrintf("chunk off=%d len=%d exceeds reply array len %d", offset, length, replyLength);
2816 return false;
2817 }
2818
2819 uint8_t* reply = new uint8_t[length + kChunkHdrLen];
2820 if (reply == NULL) {
2821 LOG(WARNING) << "malloc failed: " << (length + kChunkHdrLen);
2822 return false;
2823 }
Elliott Hughesf7c3b662011-10-27 12:04:56 -07002824 JDWP::Set4BE(reply + 0, type);
2825 JDWP::Set4BE(reply + 4, length);
Elliott Hughes6a5bd492011-10-28 14:33:57 -07002826 env->GetByteArrayRegion(replyData.get(), offset, length, reinterpret_cast<jbyte*>(reply + kChunkHdrLen));
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07002827
2828 *pReplyBuf = reply;
2829 *pReplyLen = length + kChunkHdrLen;
2830
Elliott Hughesba8eee12012-01-24 20:25:24 -08002831 VLOG(jdwp) << StringPrintf("dvmHandleDdm returning type=%.4s buf=%p len=%d", reinterpret_cast<char*>(reply), reply, length);
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07002832 return true;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002833}
2834
Elliott Hughesa2155262011-11-16 16:26:58 -08002835void Dbg::DdmBroadcast(bool connect) {
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08002836 VLOG(jdwp) << "Broadcasting DDM " << (connect ? "connect" : "disconnect") << "...";
Elliott Hughes47fce012011-10-25 18:37:19 -07002837
2838 Thread* self = Thread::Current();
Ian Rogers50b35e22012-10-04 10:09:15 -07002839 if (self->GetState() != kRunnable) {
2840 LOG(ERROR) << "DDM broadcast in thread state " << self->GetState();
2841 /* try anyway? */
Elliott Hughes47fce012011-10-25 18:37:19 -07002842 }
2843
2844 JNIEnv* env = self->GetJniEnv();
Elliott Hughes47fce012011-10-25 18:37:19 -07002845 jint event = connect ? 1 /*DdmServer.CONNECTED*/ : 2 /*DdmServer.DISCONNECTED*/;
Elliott Hugheseac76672012-05-24 21:56:51 -07002846 env->CallStaticVoidMethod(WellKnownClasses::org_apache_harmony_dalvik_ddmc_DdmServer,
2847 WellKnownClasses::org_apache_harmony_dalvik_ddmc_DdmServer_broadcast,
2848 event);
Elliott Hughes47fce012011-10-25 18:37:19 -07002849 if (env->ExceptionCheck()) {
2850 LOG(ERROR) << "DdmServer.broadcast " << event << " failed";
2851 env->ExceptionDescribe();
2852 env->ExceptionClear();
2853 }
2854}
2855
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002856void Dbg::DdmConnected() {
Elliott Hughesa2155262011-11-16 16:26:58 -08002857 Dbg::DdmBroadcast(true);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002858}
2859
2860void Dbg::DdmDisconnected() {
Elliott Hughesa2155262011-11-16 16:26:58 -08002861 Dbg::DdmBroadcast(false);
Elliott Hughes47fce012011-10-25 18:37:19 -07002862 gDdmThreadNotification = false;
2863}
2864
2865/*
Elliott Hughes82188472011-11-07 18:11:48 -08002866 * Send a notification when a thread starts, stops, or changes its name.
Elliott Hughes47fce012011-10-25 18:37:19 -07002867 *
2868 * Because we broadcast the full set of threads when the notifications are
2869 * first enabled, it's possible for "thread" to be actively executing.
2870 */
Elliott Hughes82188472011-11-07 18:11:48 -08002871void Dbg::DdmSendThreadNotification(Thread* t, uint32_t type) {
Elliott Hughes47fce012011-10-25 18:37:19 -07002872 if (!gDdmThreadNotification) {
2873 return;
2874 }
2875
Elliott Hughes82188472011-11-07 18:11:48 -08002876 if (type == CHUNK_TYPE("THDE")) {
Elliott Hughes47fce012011-10-25 18:37:19 -07002877 uint8_t buf[4];
Elliott Hughesf7c3b662011-10-27 12:04:56 -07002878 JDWP::Set4BE(&buf[0], t->GetThinLockId());
Elliott Hughes47fce012011-10-25 18:37:19 -07002879 Dbg::DdmSendChunk(CHUNK_TYPE("THDE"), 4, buf);
Elliott Hughes82188472011-11-07 18:11:48 -08002880 } else {
2881 CHECK(type == CHUNK_TYPE("THCR") || type == CHUNK_TYPE("THNM")) << type;
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002882 ScopedObjectAccessUnchecked soa(Thread::Current());
Ian Rogers1f539342012-10-03 21:09:42 -07002883 SirtRef<String> name(soa.Self(), t->GetThreadName(soa));
Elliott Hughes82188472011-11-07 18:11:48 -08002884 size_t char_count = (name.get() != NULL) ? name->GetLength() : 0;
jeffhao725a9572012-11-13 18:20:12 -08002885 const jchar* chars = (name.get() != NULL) ? name->GetCharArray()->GetData() : NULL;
Elliott Hughes82188472011-11-07 18:11:48 -08002886
Elliott Hughes21f32d72011-11-09 17:44:13 -08002887 std::vector<uint8_t> bytes;
Elliott Hughes545a0642011-11-08 19:10:03 -08002888 JDWP::Append4BE(bytes, t->GetThinLockId());
2889 JDWP::AppendUtf16BE(bytes, chars, char_count);
Elliott Hughes21f32d72011-11-09 17:44:13 -08002890 CHECK_EQ(bytes.size(), char_count*2 + sizeof(uint32_t)*2);
2891 Dbg::DdmSendChunk(type, bytes);
Elliott Hughes47fce012011-10-25 18:37:19 -07002892 }
2893}
2894
Elliott Hughes47fce012011-10-25 18:37:19 -07002895void Dbg::DdmSetThreadNotification(bool enable) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002896 // Enable/disable thread notifications.
Elliott Hughes47fce012011-10-25 18:37:19 -07002897 gDdmThreadNotification = enable;
2898 if (enable) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002899 // Suspend the VM then post thread start notifications for all threads. Threads attaching will
2900 // see a suspension in progress and block until that ends. They then post their own start
2901 // notification.
2902 SuspendVM();
2903 std::list<Thread*> threads;
Ian Rogers50b35e22012-10-04 10:09:15 -07002904 Thread* self = Thread::Current();
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002905 {
Ian Rogers50b35e22012-10-04 10:09:15 -07002906 MutexLock mu(self, *Locks::thread_list_lock_);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002907 threads = Runtime::Current()->GetThreadList()->GetList();
2908 }
2909 {
Ian Rogers50b35e22012-10-04 10:09:15 -07002910 ScopedObjectAccess soa(self);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002911 typedef std::list<Thread*>::const_iterator It; // TODO: C++0x auto
2912 for (It it = threads.begin(), end = threads.end(); it != end; ++it) {
2913 Dbg::DdmSendThreadNotification(*it, CHUNK_TYPE("THCR"));
2914 }
2915 }
2916 ResumeVM();
Elliott Hughes47fce012011-10-25 18:37:19 -07002917 }
2918}
2919
Elliott Hughesa2155262011-11-16 16:26:58 -08002920void Dbg::PostThreadStartOrStop(Thread* t, uint32_t type) {
Elliott Hughesc0f09332012-03-26 13:27:06 -07002921 if (IsDebuggerActive()) {
Mathieu Chartierdbe6f462012-09-25 16:54:50 -07002922 ScopedObjectAccessUnchecked soa(Thread::Current());
Ian Rogerscfaa4552012-11-26 21:00:08 -08002923 JDWP::ObjectId id = gRegistry->Add(t->GetPeer());
Elliott Hughes82188472011-11-07 18:11:48 -08002924 gJdwpState->PostThreadChange(id, type == CHUNK_TYPE("THCR"));
Elliott Hughesc0f09332012-03-26 13:27:06 -07002925 // If this thread's just joined the party while we're already debugging, make sure it knows
2926 // to give us updates when it's running.
2927 t->SetDebuggerUpdatesEnabled(true);
Elliott Hughes47fce012011-10-25 18:37:19 -07002928 }
Elliott Hughes82188472011-11-07 18:11:48 -08002929 Dbg::DdmSendThreadNotification(t, type);
Elliott Hughes47fce012011-10-25 18:37:19 -07002930}
2931
2932void Dbg::PostThreadStart(Thread* t) {
Elliott Hughesa2155262011-11-16 16:26:58 -08002933 Dbg::PostThreadStartOrStop(t, CHUNK_TYPE("THCR"));
Elliott Hughes47fce012011-10-25 18:37:19 -07002934}
2935
2936void Dbg::PostThreadDeath(Thread* t) {
Elliott Hughesa2155262011-11-16 16:26:58 -08002937 Dbg::PostThreadStartOrStop(t, CHUNK_TYPE("THDE"));
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002938}
2939
Elliott Hughes82188472011-11-07 18:11:48 -08002940void Dbg::DdmSendChunk(uint32_t type, size_t byte_count, const uint8_t* buf) {
Elliott Hughes3bb81562011-10-21 18:52:59 -07002941 CHECK(buf != NULL);
2942 iovec vec[1];
2943 vec[0].iov_base = reinterpret_cast<void*>(const_cast<uint8_t*>(buf));
2944 vec[0].iov_len = byte_count;
2945 Dbg::DdmSendChunkV(type, vec, 1);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002946}
2947
Elliott Hughes21f32d72011-11-09 17:44:13 -08002948void Dbg::DdmSendChunk(uint32_t type, const std::vector<uint8_t>& bytes) {
2949 DdmSendChunk(type, bytes.size(), &bytes[0]);
2950}
2951
Elliott Hughescccd84f2011-12-05 16:51:54 -08002952void Dbg::DdmSendChunkV(uint32_t type, const struct iovec* iov, int iov_count) {
Elliott Hughes3bb81562011-10-21 18:52:59 -07002953 if (gJdwpState == NULL) {
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08002954 VLOG(jdwp) << "Debugger thread not active, ignoring DDM send: " << type;
Elliott Hughes3bb81562011-10-21 18:52:59 -07002955 } else {
Elliott Hughescccd84f2011-12-05 16:51:54 -08002956 gJdwpState->DdmSendChunkV(type, iov, iov_count);
Elliott Hughes3bb81562011-10-21 18:52:59 -07002957 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002958}
2959
Elliott Hughes767a1472011-10-26 18:49:02 -07002960int Dbg::DdmHandleHpifChunk(HpifWhen when) {
2961 if (when == HPIF_WHEN_NOW) {
Elliott Hughes7162ad92011-10-27 14:08:42 -07002962 DdmSendHeapInfo(when);
Elliott Hughes767a1472011-10-26 18:49:02 -07002963 return true;
2964 }
2965
2966 if (when != HPIF_WHEN_NEVER && when != HPIF_WHEN_NEXT_GC && when != HPIF_WHEN_EVERY_GC) {
2967 LOG(ERROR) << "invalid HpifWhen value: " << static_cast<int>(when);
2968 return false;
2969 }
2970
2971 gDdmHpifWhen = when;
2972 return true;
2973}
2974
2975bool Dbg::DdmHandleHpsgNhsgChunk(Dbg::HpsgWhen when, Dbg::HpsgWhat what, bool native) {
2976 if (when != HPSG_WHEN_NEVER && when != HPSG_WHEN_EVERY_GC) {
2977 LOG(ERROR) << "invalid HpsgWhen value: " << static_cast<int>(when);
2978 return false;
2979 }
2980
2981 if (what != HPSG_WHAT_MERGED_OBJECTS && what != HPSG_WHAT_DISTINCT_OBJECTS) {
2982 LOG(ERROR) << "invalid HpsgWhat value: " << static_cast<int>(what);
2983 return false;
2984 }
2985
2986 if (native) {
2987 gDdmNhsgWhen = when;
2988 gDdmNhsgWhat = what;
2989 } else {
2990 gDdmHpsgWhen = when;
2991 gDdmHpsgWhat = what;
2992 }
2993 return true;
2994}
2995
Elliott Hughes7162ad92011-10-27 14:08:42 -07002996void Dbg::DdmSendHeapInfo(HpifWhen reason) {
2997 // If there's a one-shot 'when', reset it.
2998 if (reason == gDdmHpifWhen) {
2999 if (gDdmHpifWhen == HPIF_WHEN_NEXT_GC) {
3000 gDdmHpifWhen = HPIF_WHEN_NEVER;
3001 }
3002 }
3003
3004 /*
3005 * Chunk HPIF (client --> server)
3006 *
3007 * Heap Info. General information about the heap,
3008 * suitable for a summary display.
3009 *
3010 * [u4]: number of heaps
3011 *
3012 * For each heap:
3013 * [u4]: heap ID
3014 * [u8]: timestamp in ms since Unix epoch
3015 * [u1]: capture reason (same as 'when' value from server)
3016 * [u4]: max heap size in bytes (-Xmx)
3017 * [u4]: current heap size in bytes
3018 * [u4]: current number of bytes allocated
3019 * [u4]: current number of objects allocated
3020 */
3021 uint8_t heap_count = 1;
Elliott Hughesb3bd5f02012-03-08 21:05:27 -08003022 Heap* heap = Runtime::Current()->GetHeap();
Elliott Hughes21f32d72011-11-09 17:44:13 -08003023 std::vector<uint8_t> bytes;
Elliott Hughes545a0642011-11-08 19:10:03 -08003024 JDWP::Append4BE(bytes, heap_count);
3025 JDWP::Append4BE(bytes, 1); // Heap id (bogus; we only have one heap).
3026 JDWP::Append8BE(bytes, MilliTime());
3027 JDWP::Append1BE(bytes, reason);
Elliott Hughesb3bd5f02012-03-08 21:05:27 -08003028 JDWP::Append4BE(bytes, heap->GetMaxMemory()); // Max allowed heap size in bytes.
3029 JDWP::Append4BE(bytes, heap->GetTotalMemory()); // Current heap size in bytes.
3030 JDWP::Append4BE(bytes, heap->GetBytesAllocated());
3031 JDWP::Append4BE(bytes, heap->GetObjectsAllocated());
Elliott Hughes21f32d72011-11-09 17:44:13 -08003032 CHECK_EQ(bytes.size(), 4U + (heap_count * (4 + 8 + 1 + 4 + 4 + 4 + 4)));
3033 Dbg::DdmSendChunk(CHUNK_TYPE("HPIF"), bytes);
Elliott Hughes767a1472011-10-26 18:49:02 -07003034}
3035
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003036enum HpsgSolidity {
3037 SOLIDITY_FREE = 0,
3038 SOLIDITY_HARD = 1,
3039 SOLIDITY_SOFT = 2,
3040 SOLIDITY_WEAK = 3,
3041 SOLIDITY_PHANTOM = 4,
3042 SOLIDITY_FINALIZABLE = 5,
3043 SOLIDITY_SWEEP = 6,
3044};
3045
3046enum HpsgKind {
3047 KIND_OBJECT = 0,
3048 KIND_CLASS_OBJECT = 1,
3049 KIND_ARRAY_1 = 2,
3050 KIND_ARRAY_2 = 3,
3051 KIND_ARRAY_4 = 4,
3052 KIND_ARRAY_8 = 5,
3053 KIND_UNKNOWN = 6,
3054 KIND_NATIVE = 7,
3055};
3056
3057#define HPSG_PARTIAL (1<<7)
3058#define HPSG_STATE(solidity, kind) ((uint8_t)((((kind) & 0x7) << 3) | ((solidity) & 0x7)))
3059
Ian Rogers30fab402012-01-23 15:43:46 -08003060class HeapChunkContext {
3061 public:
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003062 // Maximum chunk size. Obtain this from the formula:
3063 // (((maximum_heap_size / ALLOCATION_UNIT_SIZE) + 255) / 256) * 2
3064 HeapChunkContext(bool merge, bool native)
Ian Rogers30fab402012-01-23 15:43:46 -08003065 : buf_(16384 - 16),
3066 type_(0),
3067 merge_(merge) {
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003068 Reset();
3069 if (native) {
Ian Rogers30fab402012-01-23 15:43:46 -08003070 type_ = CHUNK_TYPE("NHSG");
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003071 } else {
Ian Rogers30fab402012-01-23 15:43:46 -08003072 type_ = merge ? CHUNK_TYPE("HPSG") : CHUNK_TYPE("HPSO");
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003073 }
3074 }
3075
3076 ~HeapChunkContext() {
Ian Rogers30fab402012-01-23 15:43:46 -08003077 if (p_ > &buf_[0]) {
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003078 Flush();
3079 }
3080 }
3081
3082 void EnsureHeader(const void* chunk_ptr) {
Ian Rogers30fab402012-01-23 15:43:46 -08003083 if (!needHeader_) {
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003084 return;
3085 }
3086
3087 // Start a new HPSx chunk.
Ian Rogers30fab402012-01-23 15:43:46 -08003088 JDWP::Write4BE(&p_, 1); // Heap id (bogus; we only have one heap).
3089 JDWP::Write1BE(&p_, 8); // Size of allocation unit, in bytes.
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003090
Ian Rogers30fab402012-01-23 15:43:46 -08003091 JDWP::Write4BE(&p_, reinterpret_cast<uintptr_t>(chunk_ptr)); // virtual address of segment start.
3092 JDWP::Write4BE(&p_, 0); // offset of this piece (relative to the virtual address).
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003093 // [u4]: length of piece, in allocation units
3094 // 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 -08003095 pieceLenField_ = p_;
3096 JDWP::Write4BE(&p_, 0x55555555);
3097 needHeader_ = false;
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003098 }
3099
Ian Rogersb726dcb2012-09-05 08:57:23 -07003100 void Flush() SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003101 // Patch the "length of piece" field.
Ian Rogers30fab402012-01-23 15:43:46 -08003102 CHECK_LE(&buf_[0], pieceLenField_);
3103 CHECK_LE(pieceLenField_, p_);
3104 JDWP::Set4BE(pieceLenField_, totalAllocationUnits_);
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003105
Ian Rogers30fab402012-01-23 15:43:46 -08003106 Dbg::DdmSendChunk(type_, p_ - &buf_[0], &buf_[0]);
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003107 Reset();
3108 }
3109
Ian Rogers00f7d0e2012-07-19 15:28:27 -07003110 static void HeapChunkCallback(void* start, void* end, size_t used_bytes, void* arg)
Ian Rogersb726dcb2012-09-05 08:57:23 -07003111 SHARED_LOCKS_REQUIRED(Locks::heap_bitmap_lock_,
3112 Locks::mutator_lock_) {
Ian Rogers30fab402012-01-23 15:43:46 -08003113 reinterpret_cast<HeapChunkContext*>(arg)->HeapChunkCallback(start, end, used_bytes);
Elliott Hughesa2155262011-11-16 16:26:58 -08003114 }
3115
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003116 private:
Elliott Hughesa2155262011-11-16 16:26:58 -08003117 enum { ALLOCATION_UNIT_SIZE = 8 };
3118
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003119 void Reset() {
Ian Rogers30fab402012-01-23 15:43:46 -08003120 p_ = &buf_[0];
Ian Rogers15bf2d32012-08-28 17:33:04 -07003121 startOfNextMemoryChunk_ = NULL;
Ian Rogers30fab402012-01-23 15:43:46 -08003122 totalAllocationUnits_ = 0;
3123 needHeader_ = true;
3124 pieceLenField_ = NULL;
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003125 }
3126
Ian Rogers00f7d0e2012-07-19 15:28:27 -07003127 void HeapChunkCallback(void* start, void* /*end*/, size_t used_bytes)
Ian Rogersb726dcb2012-09-05 08:57:23 -07003128 SHARED_LOCKS_REQUIRED(Locks::heap_bitmap_lock_,
3129 Locks::mutator_lock_) {
Ian Rogers30fab402012-01-23 15:43:46 -08003130 // Note: heap call backs cannot manipulate the heap upon which they are crawling, care is taken
3131 // in the following code not to allocate memory, by ensuring buf_ is of the correct size
Ian Rogers15bf2d32012-08-28 17:33:04 -07003132 if (used_bytes == 0) {
3133 if (start == NULL) {
3134 // Reset for start of new heap.
3135 startOfNextMemoryChunk_ = NULL;
3136 Flush();
3137 }
3138 // Only process in use memory so that free region information
3139 // also includes dlmalloc book keeping.
Elliott Hughesa2155262011-11-16 16:26:58 -08003140 return;
Elliott Hughesa2155262011-11-16 16:26:58 -08003141 }
3142
Ian Rogers15bf2d32012-08-28 17:33:04 -07003143 /* If we're looking at the native heap, we'll just return
3144 * (SOLIDITY_HARD, KIND_NATIVE) for all allocated chunks
3145 */
3146 bool native = type_ == CHUNK_TYPE("NHSG");
3147
3148 if (startOfNextMemoryChunk_ != NULL) {
3149 // Transmit any pending free memory. Native free memory of
3150 // over kMaxFreeLen could be because of the use of mmaps, so
3151 // don't report. If not free memory then start a new segment.
3152 bool flush = true;
3153 if (start > startOfNextMemoryChunk_) {
3154 const size_t kMaxFreeLen = 2 * kPageSize;
3155 void* freeStart = startOfNextMemoryChunk_;
3156 void* freeEnd = start;
3157 size_t freeLen = (char*)freeEnd - (char*)freeStart;
3158 if (!native || freeLen < kMaxFreeLen) {
3159 AppendChunk(HPSG_STATE(SOLIDITY_FREE, 0), freeStart, freeLen);
3160 flush = false;
3161 }
3162 }
3163 if (flush) {
3164 startOfNextMemoryChunk_ = NULL;
3165 Flush();
3166 }
3167 }
3168 const Object *obj = (const Object *)start;
Elliott Hughesa2155262011-11-16 16:26:58 -08003169
3170 // Determine the type of this chunk.
3171 // OLD-TODO: if context.merge, see if this chunk is different from the last chunk.
3172 // If it's the same, we should combine them.
Ian Rogers15bf2d32012-08-28 17:33:04 -07003173 uint8_t state = ExamineObject(obj, native);
3174 // dlmalloc's chunk header is 2 * sizeof(size_t), but if the previous chunk is in use for an
3175 // allocation then the first sizeof(size_t) may belong to it.
3176 const size_t dlMallocOverhead = sizeof(size_t);
3177 AppendChunk(state, start, used_bytes + dlMallocOverhead);
3178 startOfNextMemoryChunk_ = (char*)start + used_bytes + dlMallocOverhead;
3179 }
Elliott Hughesa2155262011-11-16 16:26:58 -08003180
Ian Rogers15bf2d32012-08-28 17:33:04 -07003181 void AppendChunk(uint8_t state, void* ptr, size_t length)
Ian Rogersb726dcb2012-09-05 08:57:23 -07003182 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Ian Rogers15bf2d32012-08-28 17:33:04 -07003183 // Make sure there's enough room left in the buffer.
3184 // We need to use two bytes for every fractional 256 allocation units used by the chunk plus
3185 // 17 bytes for any header.
3186 size_t needed = (((length/ALLOCATION_UNIT_SIZE + 255) / 256) * 2) + 17;
3187 size_t bytesLeft = buf_.size() - (size_t)(p_ - &buf_[0]);
3188 if (bytesLeft < needed) {
3189 Flush();
3190 }
3191
3192 bytesLeft = buf_.size() - (size_t)(p_ - &buf_[0]);
3193 if (bytesLeft < needed) {
3194 LOG(WARNING) << "Chunk is too big to transmit (chunk_len=" << length << ", "
3195 << needed << " bytes)";
3196 return;
3197 }
3198 EnsureHeader(ptr);
Elliott Hughesa2155262011-11-16 16:26:58 -08003199 // Write out the chunk description.
Ian Rogers15bf2d32012-08-28 17:33:04 -07003200 length /= ALLOCATION_UNIT_SIZE; // Convert to allocation units.
3201 totalAllocationUnits_ += length;
3202 while (length > 256) {
Ian Rogers30fab402012-01-23 15:43:46 -08003203 *p_++ = state | HPSG_PARTIAL;
3204 *p_++ = 255; // length - 1
Ian Rogers15bf2d32012-08-28 17:33:04 -07003205 length -= 256;
Elliott Hughesa2155262011-11-16 16:26:58 -08003206 }
Ian Rogers30fab402012-01-23 15:43:46 -08003207 *p_++ = state;
Ian Rogers15bf2d32012-08-28 17:33:04 -07003208 *p_++ = length - 1;
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003209 }
3210
Ian Rogers5bfa60f2012-09-02 21:17:56 -07003211 uint8_t ExamineObject(const Object* o, bool is_native_heap)
Ian Rogersb726dcb2012-09-05 08:57:23 -07003212 SHARED_LOCKS_REQUIRED(Locks::heap_bitmap_lock_) {
Elliott Hughesa2155262011-11-16 16:26:58 -08003213 if (o == NULL) {
3214 return HPSG_STATE(SOLIDITY_FREE, 0);
3215 }
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003216
Elliott Hughesa2155262011-11-16 16:26:58 -08003217 // It's an allocated chunk. Figure out what it is.
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003218
Elliott Hughesa2155262011-11-16 16:26:58 -08003219 // If we're looking at the native heap, we'll just return
3220 // (SOLIDITY_HARD, KIND_NATIVE) for all allocated chunks.
Ian Rogers00f7d0e2012-07-19 15:28:27 -07003221 if (is_native_heap) {
Elliott Hughesa2155262011-11-16 16:26:58 -08003222 return HPSG_STATE(SOLIDITY_HARD, KIND_NATIVE);
3223 }
3224
Ian Rogers5bfa60f2012-09-02 21:17:56 -07003225 if (!Runtime::Current()->GetHeap()->IsLiveObjectLocked(o)) {
Ian Rogers15bf2d32012-08-28 17:33:04 -07003226 return HPSG_STATE(SOLIDITY_HARD, KIND_NATIVE);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07003227 }
3228
Elliott Hughesa2155262011-11-16 16:26:58 -08003229 Class* c = o->GetClass();
3230 if (c == NULL) {
3231 // The object was probably just created but hasn't been initialized yet.
3232 return HPSG_STATE(SOLIDITY_HARD, KIND_OBJECT);
3233 }
3234
Elliott Hughesb3bd5f02012-03-08 21:05:27 -08003235 if (!Runtime::Current()->GetHeap()->IsHeapAddress(c)) {
Ian Rogers15bf2d32012-08-28 17:33:04 -07003236 LOG(ERROR) << "Invalid class for managed heap object: " << o << " " << c;
Elliott Hughesa2155262011-11-16 16:26:58 -08003237 return HPSG_STATE(SOLIDITY_HARD, KIND_UNKNOWN);
3238 }
3239
3240 if (c->IsClassClass()) {
3241 return HPSG_STATE(SOLIDITY_HARD, KIND_CLASS_OBJECT);
3242 }
3243
3244 if (c->IsArrayClass()) {
3245 if (o->IsObjectArray()) {
3246 return HPSG_STATE(SOLIDITY_HARD, KIND_ARRAY_4);
3247 }
3248 switch (c->GetComponentSize()) {
3249 case 1: return HPSG_STATE(SOLIDITY_HARD, KIND_ARRAY_1);
3250 case 2: return HPSG_STATE(SOLIDITY_HARD, KIND_ARRAY_2);
3251 case 4: return HPSG_STATE(SOLIDITY_HARD, KIND_ARRAY_4);
3252 case 8: return HPSG_STATE(SOLIDITY_HARD, KIND_ARRAY_8);
3253 }
3254 }
3255
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003256 return HPSG_STATE(SOLIDITY_HARD, KIND_OBJECT);
3257 }
3258
Ian Rogers30fab402012-01-23 15:43:46 -08003259 std::vector<uint8_t> buf_;
3260 uint8_t* p_;
3261 uint8_t* pieceLenField_;
Ian Rogers15bf2d32012-08-28 17:33:04 -07003262 void* startOfNextMemoryChunk_;
Ian Rogers30fab402012-01-23 15:43:46 -08003263 size_t totalAllocationUnits_;
3264 uint32_t type_;
3265 bool merge_;
3266 bool needHeader_;
3267
Elliott Hughesa2155262011-11-16 16:26:58 -08003268 DISALLOW_COPY_AND_ASSIGN(HeapChunkContext);
3269};
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003270
3271void Dbg::DdmSendHeapSegments(bool native) {
3272 Dbg::HpsgWhen when;
3273 Dbg::HpsgWhat what;
3274 if (!native) {
3275 when = gDdmHpsgWhen;
3276 what = gDdmHpsgWhat;
3277 } else {
3278 when = gDdmNhsgWhen;
3279 what = gDdmNhsgWhat;
3280 }
3281 if (when == HPSG_WHEN_NEVER) {
3282 return;
3283 }
3284
3285 // Figure out what kind of chunks we'll be sending.
3286 CHECK(what == HPSG_WHAT_MERGED_OBJECTS || what == HPSG_WHAT_DISTINCT_OBJECTS) << static_cast<int>(what);
3287
3288 // First, send a heap start chunk.
3289 uint8_t heap_id[4];
3290 JDWP::Set4BE(&heap_id[0], 1); // Heap id (bogus; we only have one heap).
3291 Dbg::DdmSendChunk(native ? CHUNK_TYPE("NHST") : CHUNK_TYPE("HPST"), sizeof(heap_id), heap_id);
3292
3293 // Send a series of heap segment chunks.
Elliott Hughesa2155262011-11-16 16:26:58 -08003294 HeapChunkContext context((what == HPSG_WHAT_MERGED_OBJECTS), native);
3295 if (native) {
Ian Rogers30fab402012-01-23 15:43:46 -08003296 // TODO: enable when bionic has moved to dlmalloc 2.8.5
3297 // dlmalloc_inspect_all(HeapChunkContext::HeapChunkCallback, &context);
3298 UNIMPLEMENTED(WARNING) << "Native heap send heap segments";
Elliott Hughesa2155262011-11-16 16:26:58 -08003299 } else {
Elliott Hughesb3bd5f02012-03-08 21:05:27 -08003300 Heap* heap = Runtime::Current()->GetHeap();
Mathieu Chartierfd678be2012-08-30 14:50:54 -07003301 const Spaces& spaces = heap->GetSpaces();
Ian Rogers50b35e22012-10-04 10:09:15 -07003302 Thread* self = Thread::Current();
Mathieu Chartierfd678be2012-08-30 14:50:54 -07003303 for (Spaces::const_iterator cur = spaces.begin(); cur != spaces.end(); ++cur) {
Mathieu Chartierb062fdd2012-07-03 09:51:48 -07003304 if ((*cur)->IsAllocSpace()) {
Ian Rogers50b35e22012-10-04 10:09:15 -07003305 ReaderMutexLock mu(self, *Locks::heap_bitmap_lock_);
Mathieu Chartierb062fdd2012-07-03 09:51:48 -07003306 (*cur)->AsAllocSpace()->Walk(HeapChunkContext::HeapChunkCallback, &context);
3307 }
3308 }
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -07003309 // Walk the large objects, these are not in the AllocSpace.
3310 heap->GetLargeObjectsSpace()->Walk(HeapChunkContext::HeapChunkCallback, &context);
Elliott Hughesa2155262011-11-16 16:26:58 -08003311 }
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003312
3313 // Finally, send a heap end chunk.
3314 Dbg::DdmSendChunk(native ? CHUNK_TYPE("NHEN") : CHUNK_TYPE("HPEN"), sizeof(heap_id), heap_id);
Elliott Hughes767a1472011-10-26 18:49:02 -07003315}
3316
Elliott Hughes545a0642011-11-08 19:10:03 -08003317void Dbg::SetAllocTrackingEnabled(bool enabled) {
Ian Rogers50b35e22012-10-04 10:09:15 -07003318 MutexLock mu(Thread::Current(), gAllocTrackerLock);
Elliott Hughes545a0642011-11-08 19:10:03 -08003319 if (enabled) {
3320 if (recent_allocation_records_ == NULL) {
3321 LOG(INFO) << "Enabling alloc tracker (" << kNumAllocRecords << " entries, "
3322 << kMaxAllocRecordStackDepth << " frames --> "
3323 << (sizeof(AllocRecord) * kNumAllocRecords) << " bytes)";
3324 gAllocRecordHead = gAllocRecordCount = 0;
3325 recent_allocation_records_ = new AllocRecord[kNumAllocRecords];
3326 CHECK(recent_allocation_records_ != NULL);
3327 }
3328 } else {
3329 delete[] recent_allocation_records_;
3330 recent_allocation_records_ = NULL;
3331 }
3332}
3333
Ian Rogers0399dde2012-06-06 17:09:28 -07003334struct AllocRecordStackVisitor : public StackVisitor {
3335 AllocRecordStackVisitor(const ManagedStack* stack,
Ian Rogers306057f2012-11-26 12:45:53 -08003336 const std::deque<InstrumentationStackFrame>* instrumentation_stack,
3337 AllocRecord* record)
Ian Rogersb726dcb2012-09-05 08:57:23 -07003338 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_)
jeffhao725a9572012-11-13 18:20:12 -08003339 : StackVisitor(stack, instrumentation_stack, NULL), record(record), depth(0) {}
Elliott Hughes545a0642011-11-08 19:10:03 -08003340
Ian Rogers00f7d0e2012-07-19 15:28:27 -07003341 // TODO: Enable annotalysis. We know lock is held in constructor, but abstraction confuses
3342 // annotalysis.
3343 bool VisitFrame() NO_THREAD_SAFETY_ANALYSIS {
Elliott Hughes545a0642011-11-08 19:10:03 -08003344 if (depth >= kMaxAllocRecordStackDepth) {
Elliott Hughes530fa002012-03-12 11:44:49 -07003345 return false;
Elliott Hughes545a0642011-11-08 19:10:03 -08003346 }
Mathieu Chartier66f19252012-09-18 08:57:04 -07003347 AbstractMethod* m = GetMethod();
Ian Rogers0399dde2012-06-06 17:09:28 -07003348 if (!m->IsRuntimeMethod()) {
3349 record->stack[depth].method = m;
3350 record->stack[depth].dex_pc = GetDexPc();
Elliott Hughes530fa002012-03-12 11:44:49 -07003351 ++depth;
Elliott Hughes545a0642011-11-08 19:10:03 -08003352 }
Elliott Hughes530fa002012-03-12 11:44:49 -07003353 return true;
Elliott Hughes545a0642011-11-08 19:10:03 -08003354 }
3355
3356 ~AllocRecordStackVisitor() {
3357 // Clear out any unused stack trace elements.
3358 for (; depth < kMaxAllocRecordStackDepth; ++depth) {
3359 record->stack[depth].method = NULL;
Ian Rogers0399dde2012-06-06 17:09:28 -07003360 record->stack[depth].dex_pc = 0;
Elliott Hughes545a0642011-11-08 19:10:03 -08003361 }
3362 }
3363
3364 AllocRecord* record;
3365 size_t depth;
3366};
3367
3368void Dbg::RecordAllocation(Class* type, size_t byte_count) {
3369 Thread* self = Thread::Current();
3370 CHECK(self != NULL);
3371
Ian Rogers50b35e22012-10-04 10:09:15 -07003372 MutexLock mu(self, gAllocTrackerLock);
Elliott Hughes545a0642011-11-08 19:10:03 -08003373 if (recent_allocation_records_ == NULL) {
3374 return;
3375 }
3376
3377 // Advance and clip.
3378 if (++gAllocRecordHead == kNumAllocRecords) {
3379 gAllocRecordHead = 0;
3380 }
3381
3382 // Fill in the basics.
3383 AllocRecord* record = &recent_allocation_records_[gAllocRecordHead];
3384 record->type = type;
3385 record->byte_count = byte_count;
3386 record->thin_lock_id = self->GetThinLockId();
3387
3388 // Fill in the stack trace.
jeffhao725a9572012-11-13 18:20:12 -08003389 AllocRecordStackVisitor visitor(self->GetManagedStack(), self->GetInstrumentationStack(), record);
Ian Rogers0399dde2012-06-06 17:09:28 -07003390 visitor.WalkStack();
Elliott Hughes545a0642011-11-08 19:10:03 -08003391
3392 if (gAllocRecordCount < kNumAllocRecords) {
3393 ++gAllocRecordCount;
3394 }
3395}
3396
Elliott Hughesa8f93cb2012-06-08 17:08:48 -07003397// Returns the index of the head element.
3398//
3399// We point at the most-recently-written record, so if gAllocRecordCount is 1
3400// we want to use the current element. Take "head+1" and subtract count
3401// from it.
3402//
3403// We need to handle underflow in our circular buffer, so we add
3404// kNumAllocRecords and then mask it back down.
Elliott Hughesf8349362012-06-18 15:00:06 -07003405static inline int HeadIndex() EXCLUSIVE_LOCKS_REQUIRED(gAllocTrackerLock) {
Elliott Hughes545a0642011-11-08 19:10:03 -08003406 return (gAllocRecordHead+1 + kNumAllocRecords - gAllocRecordCount) & (kNumAllocRecords-1);
3407}
3408
3409void Dbg::DumpRecentAllocations() {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07003410 ScopedObjectAccess soa(Thread::Current());
Ian Rogers50b35e22012-10-04 10:09:15 -07003411 MutexLock mu(soa.Self(), gAllocTrackerLock);
Elliott Hughes545a0642011-11-08 19:10:03 -08003412 if (recent_allocation_records_ == NULL) {
3413 LOG(INFO) << "Not recording tracked allocations";
3414 return;
3415 }
3416
3417 // "i" is the head of the list. We want to start at the end of the
3418 // list and move forward to the tail.
Elliott Hughesa8f93cb2012-06-08 17:08:48 -07003419 size_t i = HeadIndex();
Elliott Hughes545a0642011-11-08 19:10:03 -08003420 size_t count = gAllocRecordCount;
3421
3422 LOG(INFO) << "Tracked allocations, (head=" << gAllocRecordHead << " count=" << count << ")";
3423 while (count--) {
3424 AllocRecord* record = &recent_allocation_records_[i];
3425
Elliott Hughesa8f93cb2012-06-08 17:08:48 -07003426 LOG(INFO) << StringPrintf(" Thread %-2d %6zd bytes ", record->thin_lock_id, record->byte_count)
Elliott Hughes545a0642011-11-08 19:10:03 -08003427 << PrettyClass(record->type);
3428
3429 for (size_t stack_frame = 0; stack_frame < kMaxAllocRecordStackDepth; ++stack_frame) {
Mathieu Chartier66f19252012-09-18 08:57:04 -07003430 const AbstractMethod* m = record->stack[stack_frame].method;
Elliott Hughes545a0642011-11-08 19:10:03 -08003431 if (m == NULL) {
3432 break;
3433 }
3434 LOG(INFO) << " " << PrettyMethod(m) << " line " << record->stack[stack_frame].LineNumber();
3435 }
3436
3437 // pause periodically to help logcat catch up
3438 if ((count % 5) == 0) {
3439 usleep(40000);
3440 }
3441
3442 i = (i + 1) & (kNumAllocRecords-1);
3443 }
3444}
3445
3446class StringTable {
3447 public:
3448 StringTable() {
3449 }
3450
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08003451 void Add(const char* s) {
Elliott Hughes545a0642011-11-08 19:10:03 -08003452 table_.insert(s);
3453 }
3454
Elliott Hughesa8f93cb2012-06-08 17:08:48 -07003455 size_t IndexOf(const char* s) const {
3456 typedef std::set<std::string>::const_iterator It; // TODO: C++0x auto
3457 It it = table_.find(s);
3458 if (it == table_.end()) {
3459 LOG(FATAL) << "IndexOf(\"" << s << "\") failed";
3460 }
3461 return std::distance(table_.begin(), it);
Elliott Hughes545a0642011-11-08 19:10:03 -08003462 }
3463
Elliott Hughesa8f93cb2012-06-08 17:08:48 -07003464 size_t Size() const {
Elliott Hughes545a0642011-11-08 19:10:03 -08003465 return table_.size();
3466 }
3467
Elliott Hughesa8f93cb2012-06-08 17:08:48 -07003468 void WriteTo(std::vector<uint8_t>& bytes) const {
3469 typedef std::set<std::string>::const_iterator It; // TODO: C++0x auto
Elliott Hughes545a0642011-11-08 19:10:03 -08003470 for (It it = table_.begin(); it != table_.end(); ++it) {
Elliott Hughesa8f93cb2012-06-08 17:08:48 -07003471 const char* s = (*it).c_str();
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08003472 size_t s_len = CountModifiedUtf8Chars(s);
3473 UniquePtr<uint16_t> s_utf16(new uint16_t[s_len]);
3474 ConvertModifiedUtf8ToUtf16(s_utf16.get(), s);
3475 JDWP::AppendUtf16BE(bytes, s_utf16.get(), s_len);
Elliott Hughes545a0642011-11-08 19:10:03 -08003476 }
3477 }
3478
3479 private:
Elliott Hughesa8f93cb2012-06-08 17:08:48 -07003480 std::set<std::string> table_;
Elliott Hughes545a0642011-11-08 19:10:03 -08003481 DISALLOW_COPY_AND_ASSIGN(StringTable);
3482};
3483
3484/*
3485 * The data we send to DDMS contains everything we have recorded.
3486 *
3487 * Message header (all values big-endian):
3488 * (1b) message header len (to allow future expansion); includes itself
3489 * (1b) entry header len
3490 * (1b) stack frame len
3491 * (2b) number of entries
3492 * (4b) offset to string table from start of message
3493 * (2b) number of class name strings
3494 * (2b) number of method name strings
3495 * (2b) number of source file name strings
3496 * For each entry:
3497 * (4b) total allocation size
Elliott Hughes221229c2013-01-08 18:17:50 -08003498 * (2b) thread id
Elliott Hughes545a0642011-11-08 19:10:03 -08003499 * (2b) allocated object's class name index
3500 * (1b) stack depth
3501 * For each stack frame:
3502 * (2b) method's class name
3503 * (2b) method name
3504 * (2b) method source file
3505 * (2b) line number, clipped to 32767; -2 if native; -1 if no source
3506 * (xb) class name strings
3507 * (xb) method name strings
3508 * (xb) source file strings
3509 *
3510 * As with other DDM traffic, strings are sent as a 4-byte length
3511 * followed by UTF-16 data.
3512 *
3513 * We send up 16-bit unsigned indexes into string tables. In theory there
3514 * can be (kMaxAllocRecordStackDepth * kNumAllocRecords) unique strings in
3515 * each table, but in practice there should be far fewer.
3516 *
3517 * The chief reason for using a string table here is to keep the size of
3518 * the DDMS message to a minimum. This is partly to make the protocol
3519 * efficient, but also because we have to form the whole thing up all at
3520 * once in a memory buffer.
3521 *
3522 * We use separate string tables for class names, method names, and source
3523 * files to keep the indexes small. There will generally be no overlap
3524 * between the contents of these tables.
3525 */
3526jbyteArray Dbg::GetRecentAllocations() {
3527 if (false) {
3528 DumpRecentAllocations();
3529 }
3530
Ian Rogers50b35e22012-10-04 10:09:15 -07003531 Thread* self = Thread::Current();
3532 MutexLock mu(self, gAllocTrackerLock);
Elliott Hughes545a0642011-11-08 19:10:03 -08003533
Elliott Hughesa8f93cb2012-06-08 17:08:48 -07003534 //
3535 // Part 1: generate string tables.
3536 //
Elliott Hughes545a0642011-11-08 19:10:03 -08003537 StringTable class_names;
3538 StringTable method_names;
3539 StringTable filenames;
3540
3541 int count = gAllocRecordCount;
Elliott Hughesa8f93cb2012-06-08 17:08:48 -07003542 int idx = HeadIndex();
Elliott Hughes545a0642011-11-08 19:10:03 -08003543 while (count--) {
3544 AllocRecord* record = &recent_allocation_records_[idx];
3545
Elliott Hughes91250e02011-12-13 22:30:35 -08003546 class_names.Add(ClassHelper(record->type).GetDescriptor());
Elliott Hughes545a0642011-11-08 19:10:03 -08003547
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08003548 MethodHelper mh;
Elliott Hughes545a0642011-11-08 19:10:03 -08003549 for (size_t i = 0; i < kMaxAllocRecordStackDepth; i++) {
Mathieu Chartier66f19252012-09-18 08:57:04 -07003550 AbstractMethod* m = record->stack[i].method;
Elliott Hughes545a0642011-11-08 19:10:03 -08003551 if (m != NULL) {
Ian Rogersba377812012-05-28 21:16:29 -07003552 mh.ChangeMethod(m);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08003553 class_names.Add(mh.GetDeclaringClassDescriptor());
3554 method_names.Add(mh.GetName());
3555 filenames.Add(mh.GetDeclaringClassSourceFile());
Elliott Hughes545a0642011-11-08 19:10:03 -08003556 }
3557 }
3558
3559 idx = (idx + 1) & (kNumAllocRecords-1);
3560 }
3561
3562 LOG(INFO) << "allocation records: " << gAllocRecordCount;
3563
Elliott Hughesa8f93cb2012-06-08 17:08:48 -07003564 //
3565 // Part 2: allocate a buffer and generate the output.
3566 //
Elliott Hughes545a0642011-11-08 19:10:03 -08003567 std::vector<uint8_t> bytes;
3568
3569 // (1b) message header len (to allow future expansion); includes itself
3570 // (1b) entry header len
3571 // (1b) stack frame len
3572 const int kMessageHeaderLen = 15;
3573 const int kEntryHeaderLen = 9;
3574 const int kStackFrameLen = 8;
3575 JDWP::Append1BE(bytes, kMessageHeaderLen);
3576 JDWP::Append1BE(bytes, kEntryHeaderLen);
3577 JDWP::Append1BE(bytes, kStackFrameLen);
3578
3579 // (2b) number of entries
3580 // (4b) offset to string table from start of message
3581 // (2b) number of class name strings
3582 // (2b) number of method name strings
3583 // (2b) number of source file name strings
3584 JDWP::Append2BE(bytes, gAllocRecordCount);
3585 size_t string_table_offset = bytes.size();
3586 JDWP::Append4BE(bytes, 0); // We'll patch this later...
3587 JDWP::Append2BE(bytes, class_names.Size());
3588 JDWP::Append2BE(bytes, method_names.Size());
3589 JDWP::Append2BE(bytes, filenames.Size());
3590
3591 count = gAllocRecordCount;
Elliott Hughesa8f93cb2012-06-08 17:08:48 -07003592 idx = HeadIndex();
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08003593 ClassHelper kh;
Elliott Hughes545a0642011-11-08 19:10:03 -08003594 while (count--) {
3595 // For each entry:
3596 // (4b) total allocation size
3597 // (2b) thread id
3598 // (2b) allocated object's class name index
3599 // (1b) stack depth
3600 AllocRecord* record = &recent_allocation_records_[idx];
3601 size_t stack_depth = record->GetDepth();
Elliott Hughesa8f93cb2012-06-08 17:08:48 -07003602 kh.ChangeClass(record->type);
3603 size_t allocated_object_class_name_index = class_names.IndexOf(kh.GetDescriptor());
Elliott Hughes545a0642011-11-08 19:10:03 -08003604 JDWP::Append4BE(bytes, record->byte_count);
3605 JDWP::Append2BE(bytes, record->thin_lock_id);
Elliott Hughesa8f93cb2012-06-08 17:08:48 -07003606 JDWP::Append2BE(bytes, allocated_object_class_name_index);
Elliott Hughes545a0642011-11-08 19:10:03 -08003607 JDWP::Append1BE(bytes, stack_depth);
3608
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08003609 MethodHelper mh;
Elliott Hughes545a0642011-11-08 19:10:03 -08003610 for (size_t stack_frame = 0; stack_frame < stack_depth; ++stack_frame) {
3611 // For each stack frame:
3612 // (2b) method's class name
3613 // (2b) method name
3614 // (2b) method source file
3615 // (2b) line number, clipped to 32767; -2 if native; -1 if no source
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08003616 mh.ChangeMethod(record->stack[stack_frame].method);
Elliott Hughesa8f93cb2012-06-08 17:08:48 -07003617 size_t class_name_index = class_names.IndexOf(mh.GetDeclaringClassDescriptor());
3618 size_t method_name_index = method_names.IndexOf(mh.GetName());
3619 size_t file_name_index = filenames.IndexOf(mh.GetDeclaringClassSourceFile());
3620 JDWP::Append2BE(bytes, class_name_index);
3621 JDWP::Append2BE(bytes, method_name_index);
3622 JDWP::Append2BE(bytes, file_name_index);
Elliott Hughes545a0642011-11-08 19:10:03 -08003623 JDWP::Append2BE(bytes, record->stack[stack_frame].LineNumber());
3624 }
3625
3626 idx = (idx + 1) & (kNumAllocRecords-1);
3627 }
3628
3629 // (xb) class name strings
3630 // (xb) method name strings
3631 // (xb) source file strings
3632 JDWP::Set4BE(&bytes[string_table_offset], bytes.size());
3633 class_names.WriteTo(bytes);
3634 method_names.WriteTo(bytes);
3635 filenames.WriteTo(bytes);
3636
Ian Rogers50b35e22012-10-04 10:09:15 -07003637 JNIEnv* env = self->GetJniEnv();
Elliott Hughes545a0642011-11-08 19:10:03 -08003638 jbyteArray result = env->NewByteArray(bytes.size());
3639 if (result != NULL) {
3640 env->SetByteArrayRegion(result, 0, bytes.size(), reinterpret_cast<const jbyte*>(&bytes[0]));
3641 }
3642 return result;
3643}
3644
Elliott Hughes872d4ec2011-10-21 17:07:15 -07003645} // namespace art