blob: 85ebf660a8537e234133d4ed2dd97af79a5ed2fc [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
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700196static Array* DecodeArray(JDWP::RefTypeId id, JDWP::JdwpError& status)
Ian Rogersb726dcb2012-09-05 08:57:23 -0700197 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Elliott Hughes436e3722012-02-17 20:01:47 -0800198 Object* o = gRegistry->Get<Object*>(id);
199 if (o == NULL || o == kInvalidObject) {
200 status = JDWP::ERR_INVALID_OBJECT;
201 return NULL;
202 }
203 if (!o->IsArrayInstance()) {
204 status = JDWP::ERR_INVALID_ARRAY;
205 return NULL;
206 }
207 status = JDWP::ERR_NONE;
208 return o->AsArray();
209}
210
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700211static Class* DecodeClass(JDWP::RefTypeId id, JDWP::JdwpError& status)
Ian Rogersb726dcb2012-09-05 08:57:23 -0700212 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Elliott Hughes436e3722012-02-17 20:01:47 -0800213 Object* o = gRegistry->Get<Object*>(id);
214 if (o == NULL || o == kInvalidObject) {
215 status = JDWP::ERR_INVALID_OBJECT;
216 return NULL;
217 }
218 if (!o->IsClass()) {
219 status = JDWP::ERR_INVALID_CLASS;
220 return NULL;
221 }
222 status = JDWP::ERR_NONE;
223 return o->AsClass();
224}
225
Elliott Hughes221229c2013-01-08 18:17:50 -0800226static JDWP::JdwpError DecodeThread(ScopedObjectAccessUnchecked& soa, JDWP::ObjectId thread_id, Thread*& thread)
jeffhaoa77f0f62012-12-05 17:19:31 -0800227 EXCLUSIVE_LOCKS_REQUIRED(Locks::thread_list_lock_)
Ian Rogersb726dcb2012-09-05 08:57:23 -0700228 LOCKS_EXCLUDED(Locks::thread_suspend_count_lock_)
229 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Elliott Hughes221229c2013-01-08 18:17:50 -0800230 Object* thread_peer = gRegistry->Get<Object*>(thread_id);
Elliott Hughes436e3722012-02-17 20:01:47 -0800231 if (thread_peer == NULL || thread_peer == kInvalidObject) {
Elliott Hughes221229c2013-01-08 18:17:50 -0800232 // This isn't even an object.
233 return JDWP::ERR_INVALID_OBJECT;
Elliott Hughes436e3722012-02-17 20:01:47 -0800234 }
Elliott Hughes221229c2013-01-08 18:17:50 -0800235
236 Class* java_lang_Thread = soa.Decode<Class*>(WellKnownClasses::java_lang_Thread);
237 if (!java_lang_Thread->IsAssignableFrom(thread_peer->GetClass())) {
238 // This isn't a thread.
239 return JDWP::ERR_INVALID_THREAD;
240 }
241
242 thread = Thread::FromManagedThread(soa, thread_peer);
243 if (thread == NULL) {
244 // This is a java.lang.Thread without a Thread*. Must be a zombie.
245 return JDWP::ERR_THREAD_NOT_ALIVE;
246 }
247 return JDWP::ERR_NONE;
Elliott Hughes436e3722012-02-17 20:01:47 -0800248}
249
Elliott Hughes24437992011-11-30 14:49:33 -0800250static JDWP::JdwpTag BasicTagFromDescriptor(const char* descriptor) {
251 // JDWP deliberately uses the descriptor characters' ASCII values for its enum.
252 // Note that by "basic" we mean that we don't get more specific than JT_OBJECT.
253 return static_cast<JDWP::JdwpTag>(descriptor[0]);
254}
255
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700256static JDWP::JdwpTag TagFromClass(Class* c)
Ian Rogersb726dcb2012-09-05 08:57:23 -0700257 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Elliott Hughes86b00102011-12-05 17:54:26 -0800258 CHECK(c != NULL);
Elliott Hughes24437992011-11-30 14:49:33 -0800259 if (c->IsArrayClass()) {
260 return JDWP::JT_ARRAY;
261 }
262
Elliott Hughes3d30d9b2011-12-07 17:35:48 -0800263 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
Elliott Hughes24437992011-11-30 14:49:33 -0800264 if (c->IsStringClass()) {
265 return JDWP::JT_STRING;
266 } else if (c->IsClassClass()) {
267 return JDWP::JT_CLASS_OBJECT;
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -0800268 } else if (class_linker->FindSystemClass("Ljava/lang/Thread;")->IsAssignableFrom(c)) {
Elliott Hughes24437992011-11-30 14:49:33 -0800269 return JDWP::JT_THREAD;
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -0800270 } else if (class_linker->FindSystemClass("Ljava/lang/ThreadGroup;")->IsAssignableFrom(c)) {
Elliott Hughes24437992011-11-30 14:49:33 -0800271 return JDWP::JT_THREAD_GROUP;
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -0800272 } else if (class_linker->FindSystemClass("Ljava/lang/ClassLoader;")->IsAssignableFrom(c)) {
Elliott Hughes24437992011-11-30 14:49:33 -0800273 return JDWP::JT_CLASS_LOADER;
Elliott Hughes24437992011-11-30 14:49:33 -0800274 } else {
275 return JDWP::JT_OBJECT;
276 }
277}
278
279/*
280 * Objects declared to hold Object might actually hold a more specific
281 * type. The debugger may take a special interest in these (e.g. it
282 * wants to display the contents of Strings), so we want to return an
283 * appropriate tag.
284 *
285 * Null objects are tagged JT_OBJECT.
286 */
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700287static JDWP::JdwpTag TagFromObject(const Object* o)
Ian Rogersb726dcb2012-09-05 08:57:23 -0700288 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Elliott Hughes24437992011-11-30 14:49:33 -0800289 return (o == NULL) ? JDWP::JT_OBJECT : TagFromClass(o->GetClass());
290}
291
292static bool IsPrimitiveTag(JDWP::JdwpTag tag) {
293 switch (tag) {
294 case JDWP::JT_BOOLEAN:
295 case JDWP::JT_BYTE:
296 case JDWP::JT_CHAR:
297 case JDWP::JT_FLOAT:
298 case JDWP::JT_DOUBLE:
299 case JDWP::JT_INT:
300 case JDWP::JT_LONG:
301 case JDWP::JT_SHORT:
302 case JDWP::JT_VOID:
303 return true;
304 default:
305 return false;
306 }
307}
308
Elliott Hughes3bb81562011-10-21 18:52:59 -0700309/*
310 * Handle one of the JDWP name/value pairs.
311 *
312 * JDWP options are:
313 * help: if specified, show help message and bail
314 * transport: may be dt_socket or dt_shmem
315 * address: for dt_socket, "host:port", or just "port" when listening
316 * server: if "y", wait for debugger to attach; if "n", attach to debugger
317 * timeout: how long to wait for debugger to connect / listen
318 *
319 * Useful with server=n (these aren't supported yet):
320 * onthrow=<exception-name>: connect to debugger when exception thrown
321 * onuncaught=y|n: connect to debugger when uncaught exception thrown
322 * launch=<command-line>: launch the debugger itself
323 *
324 * The "transport" option is required, as is "address" if server=n.
325 */
326static bool ParseJdwpOption(const std::string& name, const std::string& value) {
327 if (name == "transport") {
328 if (value == "dt_socket") {
Elliott Hughes376a7a02011-10-24 18:35:55 -0700329 gJdwpOptions.transport = JDWP::kJdwpTransportSocket;
Elliott Hughes3bb81562011-10-21 18:52:59 -0700330 } else if (value == "dt_android_adb") {
Elliott Hughes376a7a02011-10-24 18:35:55 -0700331 gJdwpOptions.transport = JDWP::kJdwpTransportAndroidAdb;
Elliott Hughes3bb81562011-10-21 18:52:59 -0700332 } else {
333 LOG(ERROR) << "JDWP transport not supported: " << value;
334 return false;
335 }
336 } else if (name == "server") {
337 if (value == "n") {
Elliott Hughes376a7a02011-10-24 18:35:55 -0700338 gJdwpOptions.server = false;
Elliott Hughes3bb81562011-10-21 18:52:59 -0700339 } else if (value == "y") {
Elliott Hughes376a7a02011-10-24 18:35:55 -0700340 gJdwpOptions.server = true;
Elliott Hughes3bb81562011-10-21 18:52:59 -0700341 } else {
342 LOG(ERROR) << "JDWP option 'server' must be 'y' or 'n'";
343 return false;
344 }
345 } else if (name == "suspend") {
346 if (value == "n") {
Elliott Hughes376a7a02011-10-24 18:35:55 -0700347 gJdwpOptions.suspend = false;
Elliott Hughes3bb81562011-10-21 18:52:59 -0700348 } else if (value == "y") {
Elliott Hughes376a7a02011-10-24 18:35:55 -0700349 gJdwpOptions.suspend = true;
Elliott Hughes3bb81562011-10-21 18:52:59 -0700350 } else {
351 LOG(ERROR) << "JDWP option 'suspend' must be 'y' or 'n'";
352 return false;
353 }
354 } else if (name == "address") {
355 /* this is either <port> or <host>:<port> */
356 std::string port_string;
Elliott Hughes376a7a02011-10-24 18:35:55 -0700357 gJdwpOptions.host.clear();
Elliott Hughes3bb81562011-10-21 18:52:59 -0700358 std::string::size_type colon = value.find(':');
359 if (colon != std::string::npos) {
Elliott Hughes376a7a02011-10-24 18:35:55 -0700360 gJdwpOptions.host = value.substr(0, colon);
Elliott Hughes3bb81562011-10-21 18:52:59 -0700361 port_string = value.substr(colon + 1);
362 } else {
363 port_string = value;
364 }
365 if (port_string.empty()) {
366 LOG(ERROR) << "JDWP address missing port: " << value;
367 return false;
368 }
369 char* end;
Elliott Hughesba8eee12012-01-24 20:25:24 -0800370 uint64_t port = strtoul(port_string.c_str(), &end, 10);
371 if (*end != '\0' || port > 0xffff) {
Elliott Hughes3bb81562011-10-21 18:52:59 -0700372 LOG(ERROR) << "JDWP address has junk in port field: " << value;
373 return false;
374 }
Elliott Hughes376a7a02011-10-24 18:35:55 -0700375 gJdwpOptions.port = port;
Elliott Hughes3bb81562011-10-21 18:52:59 -0700376 } else if (name == "launch" || name == "onthrow" || name == "oncaught" || name == "timeout") {
377 /* valid but unsupported */
378 LOG(INFO) << "Ignoring JDWP option '" << name << "'='" << value << "'";
379 } else {
380 LOG(INFO) << "Ignoring unrecognized JDWP option '" << name << "'='" << value << "'";
381 }
382
383 return true;
384}
385
386/*
387 * Parse the latter half of a -Xrunjdwp/-agentlib:jdwp= string, e.g.:
388 * "transport=dt_socket,address=8000,server=y,suspend=n"
389 */
390bool Dbg::ParseJdwpOptions(const std::string& options) {
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -0800391 VLOG(jdwp) << "ParseJdwpOptions: " << options;
Elliott Hughes47fce012011-10-25 18:37:19 -0700392
Elliott Hughes3bb81562011-10-21 18:52:59 -0700393 std::vector<std::string> pairs;
394 Split(options, ',', pairs);
395
396 for (size_t i = 0; i < pairs.size(); ++i) {
397 std::string::size_type equals = pairs[i].find('=');
398 if (equals == std::string::npos) {
399 LOG(ERROR) << "Can't parse JDWP option '" << pairs[i] << "' in '" << options << "'";
400 return false;
401 }
402 ParseJdwpOption(pairs[i].substr(0, equals), pairs[i].substr(equals + 1));
403 }
404
Elliott Hughes376a7a02011-10-24 18:35:55 -0700405 if (gJdwpOptions.transport == JDWP::kJdwpTransportUnknown) {
Elliott Hughes3bb81562011-10-21 18:52:59 -0700406 LOG(ERROR) << "Must specify JDWP transport: " << options;
407 }
Elliott Hughes376a7a02011-10-24 18:35:55 -0700408 if (!gJdwpOptions.server && (gJdwpOptions.host.empty() || gJdwpOptions.port == 0)) {
Elliott Hughes3bb81562011-10-21 18:52:59 -0700409 LOG(ERROR) << "Must specify JDWP host and port when server=n: " << options;
410 return false;
411 }
412
413 gJdwpConfigured = true;
414 return true;
415}
416
Elliott Hughesd1cc8362011-10-24 16:58:50 -0700417void Dbg::StartJdwp() {
Elliott Hughesc0f09332012-03-26 13:27:06 -0700418 if (!gJdwpAllowed || !IsJdwpConfigured()) {
Elliott Hughes376a7a02011-10-24 18:35:55 -0700419 // No JDWP for you!
420 return;
421 }
422
Elliott Hughes475fc232011-10-25 15:00:35 -0700423 CHECK(gRegistry == NULL);
424 gRegistry = new ObjectRegistry;
425
Elliott Hughesd1cc8362011-10-24 16:58:50 -0700426 // Init JDWP if the debugger is enabled. This may connect out to a
427 // debugger, passively listen for a debugger, or block waiting for a
428 // debugger.
Elliott Hughes376a7a02011-10-24 18:35:55 -0700429 gJdwpState = JDWP::JdwpState::Create(&gJdwpOptions);
430 if (gJdwpState == NULL) {
Elliott Hughesf8a2df72011-12-01 12:19:54 -0800431 // We probably failed because some other process has the port already, which means that
432 // if we don't abort the user is likely to think they're talking to us when they're actually
433 // talking to that other process.
Elliott Hughes3d30d9b2011-12-07 17:35:48 -0800434 LOG(FATAL) << "Debugger thread failed to initialize";
Elliott Hughesd1cc8362011-10-24 16:58:50 -0700435 }
436
437 // If a debugger has already attached, send the "welcome" message.
438 // This may cause us to suspend all threads.
Elliott Hughes376a7a02011-10-24 18:35:55 -0700439 if (gJdwpState->IsActive()) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700440 ScopedObjectAccess soa(Thread::Current());
Elliott Hughes376a7a02011-10-24 18:35:55 -0700441 if (!gJdwpState->PostVMStart()) {
Elliott Hughes3d30d9b2011-12-07 17:35:48 -0800442 LOG(WARNING) << "Failed to post 'start' message to debugger";
Elliott Hughesd1cc8362011-10-24 16:58:50 -0700443 }
444 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700445}
446
Elliott Hughesd1cc8362011-10-24 16:58:50 -0700447void Dbg::StopJdwp() {
Elliott Hughes376a7a02011-10-24 18:35:55 -0700448 delete gJdwpState;
Elliott Hughes475fc232011-10-25 15:00:35 -0700449 delete gRegistry;
450 gRegistry = NULL;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700451}
452
Elliott Hughes767a1472011-10-26 18:49:02 -0700453void Dbg::GcDidFinish() {
454 if (gDdmHpifWhen != HPIF_WHEN_NEVER) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700455 ScopedObjectAccess soa(Thread::Current());
Elliott Hughes81ff3182012-03-23 20:35:56 -0700456 LOG(DEBUG) << "Sending heap info to DDM";
Elliott Hughes7162ad92011-10-27 14:08:42 -0700457 DdmSendHeapInfo(gDdmHpifWhen);
Elliott Hughes767a1472011-10-26 18:49:02 -0700458 }
459 if (gDdmHpsgWhen != HPSG_WHEN_NEVER) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700460 ScopedObjectAccess soa(Thread::Current());
Elliott Hughes81ff3182012-03-23 20:35:56 -0700461 LOG(DEBUG) << "Dumping heap to DDM";
Elliott Hughes6a5bd492011-10-28 14:33:57 -0700462 DdmSendHeapSegments(false);
Elliott Hughes767a1472011-10-26 18:49:02 -0700463 }
464 if (gDdmNhsgWhen != HPSG_WHEN_NEVER) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700465 ScopedObjectAccess soa(Thread::Current());
Elliott Hughes767a1472011-10-26 18:49:02 -0700466 LOG(DEBUG) << "Dumping native heap to DDM";
Elliott Hughes6a5bd492011-10-28 14:33:57 -0700467 DdmSendHeapSegments(true);
Elliott Hughes767a1472011-10-26 18:49:02 -0700468 }
469}
470
Elliott Hughes4ffd3132011-10-24 12:06:42 -0700471void Dbg::SetJdwpAllowed(bool allowed) {
472 gJdwpAllowed = allowed;
473}
474
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700475DebugInvokeReq* Dbg::GetInvokeReq() {
Elliott Hughes475fc232011-10-25 15:00:35 -0700476 return Thread::Current()->GetInvokeReq();
477}
478
479Thread* Dbg::GetDebugThread() {
480 return (gJdwpState != NULL) ? gJdwpState->GetDebugThread() : NULL;
481}
482
483void Dbg::ClearWaitForEventThread() {
484 gJdwpState->ClearWaitForEventThread();
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700485}
486
487void Dbg::Connected() {
Elliott Hughes3bb81562011-10-21 18:52:59 -0700488 CHECK(!gDebuggerConnected);
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -0800489 VLOG(jdwp) << "JDWP has attached";
Elliott Hughes3bb81562011-10-21 18:52:59 -0700490 gDebuggerConnected = true;
Elliott Hughes86964332012-02-15 19:37:42 -0800491 gDisposed = false;
492}
493
494void Dbg::Disposed() {
495 gDisposed = true;
496}
497
498bool Dbg::IsDisposed() {
499 return gDisposed;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700500}
501
Elliott Hughesc0f09332012-03-26 13:27:06 -0700502static void SetDebuggerUpdatesEnabledCallback(Thread* t, void* user_data) {
503 t->SetDebuggerUpdatesEnabled(*reinterpret_cast<bool*>(user_data));
504}
505
506static void SetDebuggerUpdatesEnabled(bool enabled) {
Ian Rogers50b35e22012-10-04 10:09:15 -0700507 MutexLock mu(Thread::Current(), *Locks::thread_list_lock_);
Elliott Hughesf8349362012-06-18 15:00:06 -0700508 Runtime::Current()->GetThreadList()->ForEach(SetDebuggerUpdatesEnabledCallback, &enabled);
Elliott Hughesc0f09332012-03-26 13:27:06 -0700509}
510
Elliott Hughesa2155262011-11-16 16:26:58 -0800511void Dbg::GoActive() {
512 // Enable all debugging features, including scans for breakpoints.
513 // This is a no-op if we're already active.
514 // Only called from the JDWP handler thread.
515 if (gDebuggerActive) {
516 return;
517 }
518
519 LOG(INFO) << "Debugger is active";
520
Elliott Hughesc0f09332012-03-26 13:27:06 -0700521 {
522 // TODO: dalvik only warned if there were breakpoints left over. clear in Dbg::Disconnected?
jeffhao09bfc6a2012-12-11 18:11:43 -0800523 MutexLock mu(Thread::Current(), *Locks::breakpoint_lock_);
Elliott Hughesc0f09332012-03-26 13:27:06 -0700524 CHECK_EQ(gBreakpoints.size(), 0U);
525 }
Elliott Hughesa2155262011-11-16 16:26:58 -0800526
527 gDebuggerActive = true;
Elliott Hughesc0f09332012-03-26 13:27:06 -0700528 SetDebuggerUpdatesEnabled(true);
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700529}
530
531void Dbg::Disconnected() {
Elliott Hughes234ab152011-10-26 14:02:26 -0700532 CHECK(gDebuggerConnected);
533
Elliott Hughesc0f09332012-03-26 13:27:06 -0700534 LOG(INFO) << "Debugger is no longer active";
Elliott Hughes234ab152011-10-26 14:02:26 -0700535
Elliott Hughesc0f09332012-03-26 13:27:06 -0700536 gDebuggerActive = false;
537 SetDebuggerUpdatesEnabled(false);
Elliott Hughes234ab152011-10-26 14:02:26 -0700538
539 gRegistry->Clear();
540 gDebuggerConnected = false;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700541}
542
Elliott Hughesc0f09332012-03-26 13:27:06 -0700543bool Dbg::IsDebuggerActive() {
Elliott Hughes3bb81562011-10-21 18:52:59 -0700544 return gDebuggerActive;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700545}
546
Elliott Hughesc0f09332012-03-26 13:27:06 -0700547bool Dbg::IsJdwpConfigured() {
Elliott Hughes3bb81562011-10-21 18:52:59 -0700548 return gJdwpConfigured;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700549}
550
551int64_t Dbg::LastDebuggerActivity() {
Elliott Hughesca951522011-12-05 12:01:32 -0800552 return gJdwpState->LastDebuggerActivity();
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700553}
554
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700555void Dbg::UndoDebuggerSuspensions() {
Elliott Hughes234ab152011-10-26 14:02:26 -0700556 Runtime::Current()->GetThreadList()->UndoDebuggerSuspensions();
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700557}
558
559void Dbg::Exit(int status) {
Elliott Hughes1bba14f2011-12-01 18:00:36 -0800560 exit(status); // This is all dalvik did.
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700561}
562
Elliott Hughesbfe487b2011-10-26 15:48:55 -0700563void Dbg::VisitRoots(Heap::RootVisitor* visitor, void* arg) {
564 if (gRegistry != NULL) {
565 gRegistry->VisitRoots(visitor, arg);
566 }
567}
568
Elliott Hughes88d63092013-01-09 09:55:54 -0800569std::string Dbg::GetClassName(JDWP::RefTypeId class_id) {
570 Object* o = gRegistry->Get<Object*>(class_id);
Elliott Hughes436e3722012-02-17 20:01:47 -0800571 if (o == NULL) {
572 return "NULL";
573 }
574 if (o == kInvalidObject) {
Elliott Hughes88d63092013-01-09 09:55:54 -0800575 return StringPrintf("invalid object %p", reinterpret_cast<void*>(class_id));
Elliott Hughes436e3722012-02-17 20:01:47 -0800576 }
577 if (!o->IsClass()) {
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -0800578 return StringPrintf("non-class %p", o); // This is only used for debugging output anyway.
579 }
Elliott Hughesc308a5d2012-02-16 17:12:06 -0800580 return DescriptorToName(ClassHelper(o->AsClass()).GetDescriptor());
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700581}
582
Elliott Hughes88d63092013-01-09 09:55:54 -0800583JDWP::JdwpError Dbg::GetClassObject(JDWP::RefTypeId id, JDWP::ObjectId& class_object_id) {
Elliott Hughes436e3722012-02-17 20:01:47 -0800584 JDWP::JdwpError status;
585 Class* c = DecodeClass(id, status);
586 if (c == NULL) {
587 return status;
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -0800588 }
Elliott Hughes88d63092013-01-09 09:55:54 -0800589 class_object_id = gRegistry->Add(c);
Elliott Hughes436e3722012-02-17 20:01:47 -0800590 return JDWP::ERR_NONE;
Elliott Hughes86964332012-02-15 19:37:42 -0800591}
592
Elliott Hughes88d63092013-01-09 09:55:54 -0800593JDWP::JdwpError Dbg::GetSuperclass(JDWP::RefTypeId id, JDWP::RefTypeId& superclass_id) {
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -0800594 JDWP::JdwpError status;
595 Class* c = DecodeClass(id, status);
596 if (c == NULL) {
597 return status;
598 }
599 if (c->IsInterface()) {
600 // http://code.google.com/p/android/issues/detail?id=20856
Elliott Hughes88d63092013-01-09 09:55:54 -0800601 superclass_id = 0;
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -0800602 } else {
Elliott Hughes88d63092013-01-09 09:55:54 -0800603 superclass_id = gRegistry->Add(c->GetSuperClass());
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -0800604 }
605 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700606}
607
Elliott Hughes436e3722012-02-17 20:01:47 -0800608JDWP::JdwpError Dbg::GetClassLoader(JDWP::RefTypeId id, JDWP::ExpandBuf* pReply) {
Elliott Hughes1bba14f2011-12-01 18:00:36 -0800609 Object* o = gRegistry->Get<Object*>(id);
Elliott Hughes436e3722012-02-17 20:01:47 -0800610 if (o == NULL || o == kInvalidObject) {
611 return JDWP::ERR_INVALID_OBJECT;
612 }
613 expandBufAddObjectId(pReply, gRegistry->Add(o->GetClass()->GetClassLoader()));
614 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700615}
616
Elliott Hughes436e3722012-02-17 20:01:47 -0800617JDWP::JdwpError Dbg::GetModifiers(JDWP::RefTypeId id, JDWP::ExpandBuf* pReply) {
618 JDWP::JdwpError status;
619 Class* c = DecodeClass(id, status);
620 if (c == NULL) {
621 return status;
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -0800622 }
Elliott Hughes436e3722012-02-17 20:01:47 -0800623
624 uint32_t access_flags = c->GetAccessFlags() & kAccJavaFlagsMask;
625
626 // Set ACC_SUPER; dex files don't contain this flag, but all classes are supposed to have it set.
627 // Class.getModifiers doesn't return it, but JDWP does, so we set it here.
628 access_flags |= kAccSuper;
629
630 expandBufAdd4BE(pReply, access_flags);
631
632 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700633}
634
Elliott Hughes88d63092013-01-09 09:55:54 -0800635JDWP::JdwpError Dbg::GetReflectedType(JDWP::RefTypeId class_id, JDWP::ExpandBuf* pReply) {
Elliott Hughes436e3722012-02-17 20:01:47 -0800636 JDWP::JdwpError status;
Elliott Hughes88d63092013-01-09 09:55:54 -0800637 Class* c = DecodeClass(class_id, status);
Elliott Hughes436e3722012-02-17 20:01:47 -0800638 if (c == NULL) {
639 return status;
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -0800640 }
Elliott Hughes436e3722012-02-17 20:01:47 -0800641
642 expandBufAdd1(pReply, c->IsInterface() ? JDWP::TT_INTERFACE : JDWP::TT_CLASS);
Elliott Hughes88d63092013-01-09 09:55:54 -0800643 expandBufAddRefTypeId(pReply, class_id);
Elliott Hughes436e3722012-02-17 20:01:47 -0800644 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700645}
646
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -0800647void Dbg::GetClassList(std::vector<JDWP::RefTypeId>& classes) {
Elliott Hughesa2155262011-11-16 16:26:58 -0800648 // Get the complete list of reference classes (i.e. all classes except
649 // the primitive types).
650 // Returns a newly-allocated buffer full of RefTypeId values.
651 struct ClassListCreator {
Elliott Hughesba8eee12012-01-24 20:25:24 -0800652 explicit ClassListCreator(std::vector<JDWP::RefTypeId>& classes) : classes(classes) {
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -0800653 }
654
Elliott Hughesa2155262011-11-16 16:26:58 -0800655 static bool Visit(Class* c, void* arg) {
656 return reinterpret_cast<ClassListCreator*>(arg)->Visit(c);
657 }
658
659 bool Visit(Class* c) {
660 if (!c->IsPrimitive()) {
661 classes.push_back(static_cast<JDWP::RefTypeId>(gRegistry->Add(c)));
662 }
663 return true;
664 }
665
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -0800666 std::vector<JDWP::RefTypeId>& classes;
Elliott Hughesa2155262011-11-16 16:26:58 -0800667 };
668
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -0800669 ClassListCreator clc(classes);
Elliott Hughesa2155262011-11-16 16:26:58 -0800670 Runtime::Current()->GetClassLinker()->VisitClasses(ClassListCreator::Visit, &clc);
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700671}
672
Elliott Hughes88d63092013-01-09 09:55:54 -0800673JDWP::JdwpError Dbg::GetClassInfo(JDWP::RefTypeId class_id, JDWP::JdwpTypeTag* pTypeTag, uint32_t* pStatus, std::string* pDescriptor) {
Elliott Hughes436e3722012-02-17 20:01:47 -0800674 JDWP::JdwpError status;
Elliott Hughes88d63092013-01-09 09:55:54 -0800675 Class* c = DecodeClass(class_id, status);
Elliott Hughes436e3722012-02-17 20:01:47 -0800676 if (c == NULL) {
677 return status;
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -0800678 }
679
Elliott Hughesa2155262011-11-16 16:26:58 -0800680 if (c->IsArrayClass()) {
681 *pStatus = JDWP::CS_VERIFIED | JDWP::CS_PREPARED;
682 *pTypeTag = JDWP::TT_ARRAY;
683 } else {
684 if (c->IsErroneous()) {
685 *pStatus = JDWP::CS_ERROR;
686 } else {
687 *pStatus = JDWP::CS_VERIFIED | JDWP::CS_PREPARED | JDWP::CS_INITIALIZED;
688 }
689 *pTypeTag = c->IsInterface() ? JDWP::TT_INTERFACE : JDWP::TT_CLASS;
690 }
691
692 if (pDescriptor != NULL) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800693 *pDescriptor = ClassHelper(c).GetDescriptor();
Elliott Hughesa2155262011-11-16 16:26:58 -0800694 }
Elliott Hughes436e3722012-02-17 20:01:47 -0800695 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700696}
697
Elliott Hughesc3b77c72011-12-15 20:56:48 -0800698void Dbg::FindLoadedClassBySignature(const char* descriptor, std::vector<JDWP::RefTypeId>& ids) {
Elliott Hughes6fa602d2011-12-02 17:54:25 -0800699 std::vector<Class*> classes;
700 Runtime::Current()->GetClassLinker()->LookupClasses(descriptor, classes);
701 ids.clear();
702 for (size_t i = 0; i < classes.size(); ++i) {
703 ids.push_back(gRegistry->Add(classes[i]));
704 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700705}
706
Elliott Hughes88d63092013-01-09 09:55:54 -0800707JDWP::JdwpError Dbg::GetReferenceType(JDWP::ObjectId object_id, JDWP::ExpandBuf* pReply) {
708 Object* o = gRegistry->Get<Object*>(object_id);
Elliott Hughes436e3722012-02-17 20:01:47 -0800709 if (o == NULL || o == kInvalidObject) {
Elliott Hughes2435a572012-02-17 16:07:41 -0800710 return JDWP::ERR_INVALID_OBJECT;
Elliott Hughes499c5132011-11-17 14:55:11 -0800711 }
Elliott Hughes2435a572012-02-17 16:07:41 -0800712
713 JDWP::JdwpTypeTag type_tag;
714 if (o->GetClass()->IsArrayClass()) {
715 type_tag = JDWP::TT_ARRAY;
716 } else if (o->GetClass()->IsInterface()) {
717 type_tag = JDWP::TT_INTERFACE;
718 } else {
719 type_tag = JDWP::TT_CLASS;
720 }
721 JDWP::RefTypeId type_id = gRegistry->Add(o->GetClass());
722
723 expandBufAdd1(pReply, type_tag);
724 expandBufAddRefTypeId(pReply, type_id);
725
726 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700727}
728
Elliott Hughes88d63092013-01-09 09:55:54 -0800729JDWP::JdwpError Dbg::GetSignature(JDWP::RefTypeId class_id, std::string& signature) {
Elliott Hughes1fe7afb2012-02-13 17:23:03 -0800730 JDWP::JdwpError status;
Elliott Hughes88d63092013-01-09 09:55:54 -0800731 Class* c = DecodeClass(class_id, status);
Elliott Hughes1fe7afb2012-02-13 17:23:03 -0800732 if (c == NULL) {
733 return status;
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -0800734 }
Elliott Hughes1fe7afb2012-02-13 17:23:03 -0800735 signature = ClassHelper(c).GetDescriptor();
736 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700737}
738
Elliott Hughes88d63092013-01-09 09:55:54 -0800739JDWP::JdwpError Dbg::GetSourceFile(JDWP::RefTypeId class_id, std::string& result) {
Elliott Hughes436e3722012-02-17 20:01:47 -0800740 JDWP::JdwpError status;
Elliott Hughes88d63092013-01-09 09:55:54 -0800741 Class* c = DecodeClass(class_id, status);
Elliott Hughes436e3722012-02-17 20:01:47 -0800742 if (c == NULL) {
743 return status;
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -0800744 }
Elliott Hughes436e3722012-02-17 20:01:47 -0800745 result = ClassHelper(c).GetSourceFile();
746 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700747}
748
Elliott Hughes88d63092013-01-09 09:55:54 -0800749JDWP::JdwpError Dbg::GetObjectTag(JDWP::ObjectId object_id, uint8_t& tag) {
750 Object* o = gRegistry->Get<Object*>(object_id);
Elliott Hughes546b9862012-06-20 16:06:13 -0700751 if (o == kInvalidObject) {
752 return JDWP::ERR_INVALID_OBJECT;
753 }
754 tag = TagFromObject(o);
755 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700756}
757
Elliott Hughesaed4be92011-12-02 16:16:23 -0800758size_t Dbg::GetTagWidth(JDWP::JdwpTag tag) {
Elliott Hughesdbb40792011-11-18 17:05:22 -0800759 switch (tag) {
760 case JDWP::JT_VOID:
761 return 0;
762 case JDWP::JT_BYTE:
763 case JDWP::JT_BOOLEAN:
764 return 1;
765 case JDWP::JT_CHAR:
766 case JDWP::JT_SHORT:
767 return 2;
768 case JDWP::JT_FLOAT:
769 case JDWP::JT_INT:
770 return 4;
771 case JDWP::JT_ARRAY:
772 case JDWP::JT_OBJECT:
773 case JDWP::JT_STRING:
774 case JDWP::JT_THREAD:
775 case JDWP::JT_THREAD_GROUP:
776 case JDWP::JT_CLASS_LOADER:
777 case JDWP::JT_CLASS_OBJECT:
778 return sizeof(JDWP::ObjectId);
779 case JDWP::JT_DOUBLE:
780 case JDWP::JT_LONG:
781 return 8;
782 default:
Elliott Hughes3d30d9b2011-12-07 17:35:48 -0800783 LOG(FATAL) << "Unknown tag " << tag;
Elliott Hughesdbb40792011-11-18 17:05:22 -0800784 return -1;
785 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700786}
787
Elliott Hughes88d63092013-01-09 09:55:54 -0800788JDWP::JdwpError Dbg::GetArrayLength(JDWP::ObjectId array_id, int& length) {
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -0800789 JDWP::JdwpError status;
Elliott Hughes88d63092013-01-09 09:55:54 -0800790 Array* a = DecodeArray(array_id, status);
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -0800791 if (a == NULL) {
792 return status;
Elliott Hughes24437992011-11-30 14:49:33 -0800793 }
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -0800794 length = a->GetLength();
795 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700796}
797
Elliott Hughes88d63092013-01-09 09:55:54 -0800798JDWP::JdwpError Dbg::OutputArray(JDWP::ObjectId array_id, int offset, int count, JDWP::ExpandBuf* pReply) {
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -0800799 JDWP::JdwpError status;
Elliott Hughes88d63092013-01-09 09:55:54 -0800800 Array* a = DecodeArray(array_id, status);
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -0800801 if (a == NULL) {
802 return status;
803 }
Elliott Hughes24437992011-11-30 14:49:33 -0800804
805 if (offset < 0 || count < 0 || offset > a->GetLength() || a->GetLength() - offset < count) {
806 LOG(WARNING) << __FUNCTION__ << " access out of bounds: offset=" << offset << "; count=" << count;
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -0800807 return JDWP::ERR_INVALID_LENGTH;
Elliott Hughes24437992011-11-30 14:49:33 -0800808 }
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800809 std::string descriptor(ClassHelper(a->GetClass()).GetDescriptor());
Elliott Hughes24437992011-11-30 14:49:33 -0800810 JDWP::JdwpTag tag = BasicTagFromDescriptor(descriptor.c_str() + 1);
811
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -0800812 expandBufAdd1(pReply, tag);
813 expandBufAdd4BE(pReply, count);
814
Elliott Hughes24437992011-11-30 14:49:33 -0800815 if (IsPrimitiveTag(tag)) {
816 size_t width = GetTagWidth(tag);
Elliott Hughes24437992011-11-30 14:49:33 -0800817 uint8_t* dst = expandBufAddSpace(pReply, count * width);
818 if (width == 8) {
Ian Rogersa15e67d2012-02-28 13:51:55 -0800819 const uint64_t* src8 = reinterpret_cast<uint64_t*>(a->GetRawData(sizeof(uint64_t)));
Elliott Hughes24437992011-11-30 14:49:33 -0800820 for (int i = 0; i < count; ++i) JDWP::Write8BE(&dst, src8[offset + i]);
821 } else if (width == 4) {
Ian Rogersa15e67d2012-02-28 13:51:55 -0800822 const uint32_t* src4 = reinterpret_cast<uint32_t*>(a->GetRawData(sizeof(uint32_t)));
Elliott Hughes24437992011-11-30 14:49:33 -0800823 for (int i = 0; i < count; ++i) JDWP::Write4BE(&dst, src4[offset + i]);
824 } else if (width == 2) {
Ian Rogersa15e67d2012-02-28 13:51:55 -0800825 const uint16_t* src2 = reinterpret_cast<uint16_t*>(a->GetRawData(sizeof(uint16_t)));
Elliott Hughes24437992011-11-30 14:49:33 -0800826 for (int i = 0; i < count; ++i) JDWP::Write2BE(&dst, src2[offset + i]);
827 } else {
Ian Rogersa15e67d2012-02-28 13:51:55 -0800828 const uint8_t* src = reinterpret_cast<uint8_t*>(a->GetRawData(sizeof(uint8_t)));
Elliott Hughes24437992011-11-30 14:49:33 -0800829 memcpy(dst, &src[offset * width], count * width);
830 }
831 } else {
832 ObjectArray<Object>* oa = a->AsObjectArray<Object>();
833 for (int i = 0; i < count; ++i) {
Elliott Hughesf03b8f62011-12-02 14:26:25 -0800834 Object* element = oa->Get(offset + i);
Elliott Hughes24437992011-11-30 14:49:33 -0800835 JDWP::JdwpTag specific_tag = (element != NULL) ? TagFromObject(element) : tag;
836 expandBufAdd1(pReply, specific_tag);
837 expandBufAddObjectId(pReply, gRegistry->Add(element));
838 }
839 }
840
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -0800841 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700842}
843
Elliott Hughes88d63092013-01-09 09:55:54 -0800844JDWP::JdwpError Dbg::SetArrayElements(JDWP::ObjectId array_id, int offset, int count,
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700845 const uint8_t* src)
Ian Rogersb726dcb2012-09-05 08:57:23 -0700846 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -0800847 JDWP::JdwpError status;
Elliott Hughes88d63092013-01-09 09:55:54 -0800848 Array* a = DecodeArray(array_id, status);
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -0800849 if (a == NULL) {
850 return status;
851 }
Elliott Hughesf03b8f62011-12-02 14:26:25 -0800852
853 if (offset < 0 || count < 0 || offset > a->GetLength() || a->GetLength() - offset < count) {
854 LOG(WARNING) << __FUNCTION__ << " access out of bounds: offset=" << offset << "; count=" << count;
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -0800855 return JDWP::ERR_INVALID_LENGTH;
Elliott Hughesf03b8f62011-12-02 14:26:25 -0800856 }
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800857 std::string descriptor(ClassHelper(a->GetClass()).GetDescriptor());
Elliott Hughesf03b8f62011-12-02 14:26:25 -0800858 JDWP::JdwpTag tag = BasicTagFromDescriptor(descriptor.c_str() + 1);
859
860 if (IsPrimitiveTag(tag)) {
861 size_t width = GetTagWidth(tag);
Elliott Hughesf03b8f62011-12-02 14:26:25 -0800862 if (width == 8) {
Ian Rogersa15e67d2012-02-28 13:51:55 -0800863 uint8_t* dst = &(reinterpret_cast<uint8_t*>(a->GetRawData(sizeof(uint64_t)))[offset * width]);
Elliott Hughesf03b8f62011-12-02 14:26:25 -0800864 for (int i = 0; i < count; ++i) {
865 // Handle potentially non-aligned memory access one byte at a time for ARM's benefit.
866 uint64_t value;
867 for (size_t j = 0; j < sizeof(uint64_t); ++j) reinterpret_cast<uint8_t*>(&value)[j] = src[j];
868 src += sizeof(uint64_t);
869 JDWP::Write8BE(&dst, value);
870 }
871 } else if (width == 4) {
Ian Rogersa15e67d2012-02-28 13:51:55 -0800872 uint8_t* dst = &(reinterpret_cast<uint8_t*>(a->GetRawData(sizeof(uint32_t)))[offset * width]);
Elliott Hughesf03b8f62011-12-02 14:26:25 -0800873 const uint32_t* src4 = reinterpret_cast<const uint32_t*>(src);
874 for (int i = 0; i < count; ++i) JDWP::Write4BE(&dst, src4[i]);
875 } else if (width == 2) {
Ian Rogersa15e67d2012-02-28 13:51:55 -0800876 uint8_t* dst = &(reinterpret_cast<uint8_t*>(a->GetRawData(sizeof(uint16_t)))[offset * width]);
Elliott Hughesf03b8f62011-12-02 14:26:25 -0800877 const uint16_t* src2 = reinterpret_cast<const uint16_t*>(src);
878 for (int i = 0; i < count; ++i) JDWP::Write2BE(&dst, src2[i]);
879 } else {
Ian Rogersa15e67d2012-02-28 13:51:55 -0800880 uint8_t* dst = &(reinterpret_cast<uint8_t*>(a->GetRawData(sizeof(uint8_t)))[offset * width]);
Elliott Hughesf03b8f62011-12-02 14:26:25 -0800881 memcpy(&dst[offset * width], src, count * width);
882 }
883 } else {
884 ObjectArray<Object>* oa = a->AsObjectArray<Object>();
885 for (int i = 0; i < count; ++i) {
886 JDWP::ObjectId id = JDWP::ReadObjectId(&src);
Elliott Hughes436e3722012-02-17 20:01:47 -0800887 Object* o = gRegistry->Get<Object*>(id);
888 if (o == kInvalidObject) {
889 return JDWP::ERR_INVALID_OBJECT;
890 }
891 oa->Set(offset + i, o);
Elliott Hughesf03b8f62011-12-02 14:26:25 -0800892 }
893 }
894
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -0800895 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700896}
897
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -0800898JDWP::ObjectId Dbg::CreateString(const std::string& str) {
Ian Rogers50b35e22012-10-04 10:09:15 -0700899 return gRegistry->Add(String::AllocFromModifiedUtf8(Thread::Current(), str.c_str()));
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700900}
901
Elliott Hughes88d63092013-01-09 09:55:54 -0800902JDWP::JdwpError Dbg::CreateObject(JDWP::RefTypeId class_id, JDWP::ObjectId& new_object) {
Elliott Hughes436e3722012-02-17 20:01:47 -0800903 JDWP::JdwpError status;
Elliott Hughes88d63092013-01-09 09:55:54 -0800904 Class* c = DecodeClass(class_id, status);
Elliott Hughes436e3722012-02-17 20:01:47 -0800905 if (c == NULL) {
906 return status;
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -0800907 }
Ian Rogers50b35e22012-10-04 10:09:15 -0700908 new_object = gRegistry->Add(c->AllocObject(Thread::Current()));
Elliott Hughes436e3722012-02-17 20:01:47 -0800909 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700910}
911
Elliott Hughesbf13d362011-12-08 15:51:37 -0800912/*
913 * Used by Eclipse's "Display" view to evaluate "new byte[5]" to get "(byte[]) [0, 0, 0, 0, 0]".
914 */
Elliott Hughes88d63092013-01-09 09:55:54 -0800915JDWP::JdwpError Dbg::CreateArrayObject(JDWP::RefTypeId array_class_id, uint32_t length,
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700916 JDWP::ObjectId& new_array) {
Elliott Hughes436e3722012-02-17 20:01:47 -0800917 JDWP::JdwpError status;
Elliott Hughes88d63092013-01-09 09:55:54 -0800918 Class* c = DecodeClass(array_class_id, status);
Elliott Hughes436e3722012-02-17 20:01:47 -0800919 if (c == NULL) {
920 return status;
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -0800921 }
Ian Rogers50b35e22012-10-04 10:09:15 -0700922 new_array = gRegistry->Add(Array::Alloc(Thread::Current(), c, length));
Elliott Hughes436e3722012-02-17 20:01:47 -0800923 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700924}
925
Elliott Hughes88d63092013-01-09 09:55:54 -0800926bool Dbg::MatchType(JDWP::RefTypeId instance_class_id, JDWP::RefTypeId class_id) {
Elliott Hughes436e3722012-02-17 20:01:47 -0800927 JDWP::JdwpError status;
Elliott Hughes88d63092013-01-09 09:55:54 -0800928 Class* c1 = DecodeClass(instance_class_id, status);
Elliott Hughesa656a0f2012-02-21 18:03:44 -0800929 CHECK(c1 != NULL);
Elliott Hughes88d63092013-01-09 09:55:54 -0800930 Class* c2 = DecodeClass(class_id, status);
Elliott Hughesa656a0f2012-02-21 18:03:44 -0800931 CHECK(c2 != NULL);
932 return c1->IsAssignableFrom(c2);
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700933}
934
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700935static JDWP::FieldId ToFieldId(const Field* f)
Ian Rogersb726dcb2012-09-05 08:57:23 -0700936 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Elliott Hughes03181a82011-11-17 17:22:21 -0800937#ifdef MOVING_GARBAGE_COLLECTOR
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700938 UNIMPLEMENTED(FATAL);
Elliott Hughes03181a82011-11-17 17:22:21 -0800939#else
940 return static_cast<JDWP::FieldId>(reinterpret_cast<uintptr_t>(f));
941#endif
942}
943
Mathieu Chartier66f19252012-09-18 08:57:04 -0700944static JDWP::MethodId ToMethodId(const AbstractMethod* m)
Ian Rogersb726dcb2012-09-05 08:57:23 -0700945 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Elliott Hughes03181a82011-11-17 17:22:21 -0800946#ifdef MOVING_GARBAGE_COLLECTOR
947 UNIMPLEMENTED(FATAL);
948#else
949 return static_cast<JDWP::MethodId>(reinterpret_cast<uintptr_t>(m));
950#endif
951}
952
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700953static Field* FromFieldId(JDWP::FieldId fid)
Ian Rogersb726dcb2012-09-05 08:57:23 -0700954 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Elliott Hughesaed4be92011-12-02 16:16:23 -0800955#ifdef MOVING_GARBAGE_COLLECTOR
956 UNIMPLEMENTED(FATAL);
957#else
958 return reinterpret_cast<Field*>(static_cast<uintptr_t>(fid));
959#endif
960}
961
Mathieu Chartier66f19252012-09-18 08:57:04 -0700962static AbstractMethod* FromMethodId(JDWP::MethodId mid)
Ian Rogersb726dcb2012-09-05 08:57:23 -0700963 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Elliott Hughes03181a82011-11-17 17:22:21 -0800964#ifdef MOVING_GARBAGE_COLLECTOR
965 UNIMPLEMENTED(FATAL);
966#else
Mathieu Chartier66f19252012-09-18 08:57:04 -0700967 return reinterpret_cast<AbstractMethod*>(static_cast<uintptr_t>(mid));
Elliott Hughes03181a82011-11-17 17:22:21 -0800968#endif
969}
970
Mathieu Chartier66f19252012-09-18 08:57:04 -0700971static void SetLocation(JDWP::JdwpLocation& location, AbstractMethod* m, uint32_t dex_pc)
Ian Rogersb726dcb2012-09-05 08:57:23 -0700972 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Elliott Hughes91bf6cd2012-02-14 17:27:48 -0800973 if (m == NULL) {
974 memset(&location, 0, sizeof(location));
975 } else {
976 Class* c = m->GetDeclaringClass();
Elliott Hughes74847412012-06-20 18:10:21 -0700977 location.type_tag = c->IsInterface() ? JDWP::TT_INTERFACE : JDWP::TT_CLASS;
978 location.class_id = gRegistry->Add(c);
979 location.method_id = ToMethodId(m);
Ian Rogers0399dde2012-06-06 17:09:28 -0700980 location.dex_pc = dex_pc;
Elliott Hughes91bf6cd2012-02-14 17:27:48 -0800981 }
Elliott Hughesd07986f2011-12-06 18:27:45 -0800982}
983
Elliott Hughes88d63092013-01-09 09:55:54 -0800984std::string Dbg::GetMethodName(JDWP::RefTypeId, JDWP::MethodId method_id)
Ian Rogersb726dcb2012-09-05 08:57:23 -0700985 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Elliott Hughes88d63092013-01-09 09:55:54 -0800986 AbstractMethod* m = FromMethodId(method_id);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800987 return MethodHelper(m).GetName();
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700988}
989
Elliott Hughesa2e54f62011-11-17 13:01:30 -0800990/*
991 * Augment the access flags for synthetic methods and fields by setting
992 * the (as described by the spec) "0xf0000000 bit". Also, strip out any
993 * flags not specified by the Java programming language.
994 */
995static uint32_t MangleAccessFlags(uint32_t accessFlags) {
996 accessFlags &= kAccJavaFlagsMask;
997 if ((accessFlags & kAccSynthetic) != 0) {
998 accessFlags |= 0xf0000000;
999 }
1000 return accessFlags;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001001}
1002
Elliott Hughesdbb40792011-11-18 17:05:22 -08001003static const uint16_t kEclipseWorkaroundSlot = 1000;
1004
1005/*
1006 * Eclipse appears to expect that the "this" reference is in slot zero.
1007 * If it's not, the "variables" display will show two copies of "this",
1008 * possibly because it gets "this" from SF.ThisObject and then displays
1009 * all locals with nonzero slot numbers.
1010 *
1011 * So, we remap the item in slot 0 to 1000, and remap "this" to zero. On
1012 * SF.GetValues / SF.SetValues we map them back.
Elliott Hughesc5b734a2011-12-01 17:20:58 -08001013 *
1014 * TODO: jdb uses the value to determine whether a variable is a local or an argument,
1015 * by checking whether it's less than the number of arguments. To make that work, we'd
1016 * have to "mangle" all the arguments to come first, not just the implicit argument 'this'.
Elliott Hughesdbb40792011-11-18 17:05:22 -08001017 */
1018static uint16_t MangleSlot(uint16_t slot, const char* name) {
1019 uint16_t newSlot = slot;
1020 if (strcmp(name, "this") == 0) {
1021 newSlot = 0;
1022 } else if (slot == 0) {
1023 newSlot = kEclipseWorkaroundSlot;
1024 }
1025 return newSlot;
1026}
1027
Mathieu Chartier66f19252012-09-18 08:57:04 -07001028static uint16_t DemangleSlot(uint16_t slot, AbstractMethod* m)
Ian Rogersb726dcb2012-09-05 08:57:23 -07001029 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Elliott Hughesdbb40792011-11-18 17:05:22 -08001030 if (slot == kEclipseWorkaroundSlot) {
Elliott Hughes68fdbd02011-11-29 19:22:47 -08001031 return 0;
Elliott Hughesdbb40792011-11-18 17:05:22 -08001032 } else if (slot == 0) {
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08001033 const DexFile::CodeItem* code_item = MethodHelper(m).GetCodeItem();
Elliott Hughescaf76542012-06-28 16:08:22 -07001034 CHECK(code_item != NULL) << PrettyMethod(m);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001035 return code_item->registers_size_ - code_item->ins_size_;
Elliott Hughesdbb40792011-11-18 17:05:22 -08001036 }
Elliott Hughes68fdbd02011-11-29 19:22:47 -08001037 return slot;
Elliott Hughesdbb40792011-11-18 17:05:22 -08001038}
1039
Elliott Hughes88d63092013-01-09 09:55:54 -08001040JDWP::JdwpError Dbg::OutputDeclaredFields(JDWP::RefTypeId class_id, bool with_generic, JDWP::ExpandBuf* pReply) {
Elliott Hughes436e3722012-02-17 20:01:47 -08001041 JDWP::JdwpError status;
Elliott Hughes88d63092013-01-09 09:55:54 -08001042 Class* c = DecodeClass(class_id, status);
Elliott Hughes436e3722012-02-17 20:01:47 -08001043 if (c == NULL) {
1044 return status;
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -08001045 }
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001046
1047 size_t instance_field_count = c->NumInstanceFields();
1048 size_t static_field_count = c->NumStaticFields();
1049
1050 expandBufAdd4BE(pReply, instance_field_count + static_field_count);
1051
1052 for (size_t i = 0; i < instance_field_count + static_field_count; ++i) {
1053 Field* f = (i < instance_field_count) ? c->GetInstanceField(i) : c->GetStaticField(i - instance_field_count);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001054 FieldHelper fh(f);
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001055 expandBufAddFieldId(pReply, ToFieldId(f));
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001056 expandBufAddUtf8String(pReply, fh.GetName());
1057 expandBufAddUtf8String(pReply, fh.GetTypeDescriptor());
Elliott Hughesc5b734a2011-12-01 17:20:58 -08001058 if (with_generic) {
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001059 static const char genericSignature[1] = "";
1060 expandBufAddUtf8String(pReply, genericSignature);
1061 }
1062 expandBufAdd4BE(pReply, MangleAccessFlags(f->GetAccessFlags()));
1063 }
Elliott Hughes436e3722012-02-17 20:01:47 -08001064 return JDWP::ERR_NONE;
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001065}
1066
Elliott Hughes88d63092013-01-09 09:55:54 -08001067JDWP::JdwpError Dbg::OutputDeclaredMethods(JDWP::RefTypeId class_id, bool with_generic,
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001068 JDWP::ExpandBuf* pReply) {
Elliott Hughes436e3722012-02-17 20:01:47 -08001069 JDWP::JdwpError status;
Elliott Hughes88d63092013-01-09 09:55:54 -08001070 Class* c = DecodeClass(class_id, status);
Elliott Hughes436e3722012-02-17 20:01:47 -08001071 if (c == NULL) {
1072 return status;
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -08001073 }
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001074
1075 size_t direct_method_count = c->NumDirectMethods();
1076 size_t virtual_method_count = c->NumVirtualMethods();
1077
1078 expandBufAdd4BE(pReply, direct_method_count + virtual_method_count);
1079
1080 for (size_t i = 0; i < direct_method_count + virtual_method_count; ++i) {
Mathieu Chartier66f19252012-09-18 08:57:04 -07001081 AbstractMethod* m = (i < direct_method_count) ? c->GetDirectMethod(i) : c->GetVirtualMethod(i - direct_method_count);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001082 MethodHelper mh(m);
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001083 expandBufAddMethodId(pReply, ToMethodId(m));
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001084 expandBufAddUtf8String(pReply, mh.GetName());
Elliott Hughes4740cdf2011-12-07 14:07:12 -08001085 expandBufAddUtf8String(pReply, mh.GetSignature());
Elliott Hughesc5b734a2011-12-01 17:20:58 -08001086 if (with_generic) {
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001087 static const char genericSignature[1] = "";
1088 expandBufAddUtf8String(pReply, genericSignature);
1089 }
1090 expandBufAdd4BE(pReply, MangleAccessFlags(m->GetAccessFlags()));
1091 }
Elliott Hughes436e3722012-02-17 20:01:47 -08001092 return JDWP::ERR_NONE;
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001093}
1094
Elliott Hughes88d63092013-01-09 09:55:54 -08001095JDWP::JdwpError Dbg::OutputDeclaredInterfaces(JDWP::RefTypeId class_id, JDWP::ExpandBuf* pReply) {
Elliott Hughes436e3722012-02-17 20:01:47 -08001096 JDWP::JdwpError status;
Elliott Hughes88d63092013-01-09 09:55:54 -08001097 Class* c = DecodeClass(class_id, status);
Elliott Hughes436e3722012-02-17 20:01:47 -08001098 if (c == NULL) {
1099 return status;
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -08001100 }
Elliott Hughes436e3722012-02-17 20:01:47 -08001101
1102 ClassHelper kh(c);
Ian Rogersd24e2642012-06-06 21:21:43 -07001103 size_t interface_count = kh.NumDirectInterfaces();
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001104 expandBufAdd4BE(pReply, interface_count);
1105 for (size_t i = 0; i < interface_count; ++i) {
Ian Rogersd24e2642012-06-06 21:21:43 -07001106 expandBufAddRefTypeId(pReply, gRegistry->Add(kh.GetDirectInterface(i)));
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001107 }
Elliott Hughes436e3722012-02-17 20:01:47 -08001108 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001109}
1110
Elliott Hughes88d63092013-01-09 09:55:54 -08001111void Dbg::OutputLineTable(JDWP::RefTypeId, JDWP::MethodId method_id, JDWP::ExpandBuf* pReply)
Ian Rogersb726dcb2012-09-05 08:57:23 -07001112 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Elliott Hughes03181a82011-11-17 17:22:21 -08001113 struct DebugCallbackContext {
1114 int numItems;
1115 JDWP::ExpandBuf* pReply;
1116
Elliott Hughes2435a572012-02-17 16:07:41 -08001117 static bool Callback(void* context, uint32_t address, uint32_t line_number) {
Elliott Hughes03181a82011-11-17 17:22:21 -08001118 DebugCallbackContext* pContext = reinterpret_cast<DebugCallbackContext*>(context);
1119 expandBufAdd8BE(pContext->pReply, address);
Elliott Hughes2435a572012-02-17 16:07:41 -08001120 expandBufAdd4BE(pContext->pReply, line_number);
Elliott Hughes03181a82011-11-17 17:22:21 -08001121 pContext->numItems++;
1122 return true;
1123 }
1124 };
Elliott Hughes88d63092013-01-09 09:55:54 -08001125 AbstractMethod* m = FromMethodId(method_id);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001126 MethodHelper mh(m);
Elliott Hughes03181a82011-11-17 17:22:21 -08001127 uint64_t start, end;
1128 if (m->IsNative()) {
1129 start = -1;
1130 end = -1;
1131 } else {
1132 start = 0;
jeffhao14f0db92012-12-14 17:50:42 -08001133 // Return the index of the last instruction
1134 end = mh.GetCodeItem()->insns_size_in_code_units_ - 1;
Elliott Hughes03181a82011-11-17 17:22:21 -08001135 }
1136
1137 expandBufAdd8BE(pReply, start);
1138 expandBufAdd8BE(pReply, end);
1139
1140 // Add numLines later
1141 size_t numLinesOffset = expandBufGetLength(pReply);
1142 expandBufAdd4BE(pReply, 0);
1143
1144 DebugCallbackContext context;
1145 context.numItems = 0;
1146 context.pReply = pReply;
1147
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001148 mh.GetDexFile().DecodeDebugInfo(mh.GetCodeItem(), m->IsStatic(), m->GetDexMethodIndex(),
1149 DebugCallbackContext::Callback, NULL, &context);
Elliott Hughes03181a82011-11-17 17:22:21 -08001150
1151 JDWP::Set4BE(expandBufGetBuffer(pReply) + numLinesOffset, context.numItems);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001152}
1153
Elliott Hughes88d63092013-01-09 09:55:54 -08001154void Dbg::OutputVariableTable(JDWP::RefTypeId, JDWP::MethodId method_id, bool with_generic, JDWP::ExpandBuf* pReply) {
Elliott Hughesdbb40792011-11-18 17:05:22 -08001155 struct DebugCallbackContext {
Elliott Hughesdbb40792011-11-18 17:05:22 -08001156 JDWP::ExpandBuf* pReply;
Elliott Hughesc5b734a2011-12-01 17:20:58 -08001157 size_t variable_count;
1158 bool with_generic;
Elliott Hughesdbb40792011-11-18 17:05:22 -08001159
Elliott Hughesc5b734a2011-12-01 17:20:58 -08001160 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 -08001161 DebugCallbackContext* pContext = reinterpret_cast<DebugCallbackContext*>(context);
1162
Elliott Hughesad3da692012-02-24 16:51:35 -08001163 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 -08001164
Elliott Hughes68fdbd02011-11-29 19:22:47 -08001165 slot = MangleSlot(slot, name);
1166
Elliott Hughesdbb40792011-11-18 17:05:22 -08001167 expandBufAdd8BE(pContext->pReply, startAddress);
1168 expandBufAddUtf8String(pContext->pReply, name);
1169 expandBufAddUtf8String(pContext->pReply, descriptor);
Elliott Hughesc5b734a2011-12-01 17:20:58 -08001170 if (pContext->with_generic) {
Elliott Hughesdbb40792011-11-18 17:05:22 -08001171 expandBufAddUtf8String(pContext->pReply, signature);
1172 }
1173 expandBufAdd4BE(pContext->pReply, endAddress - startAddress);
1174 expandBufAdd4BE(pContext->pReply, slot);
1175
Elliott Hughesc5b734a2011-12-01 17:20:58 -08001176 ++pContext->variable_count;
Elliott Hughesdbb40792011-11-18 17:05:22 -08001177 }
1178 };
Elliott Hughes88d63092013-01-09 09:55:54 -08001179 AbstractMethod* m = FromMethodId(method_id);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001180 MethodHelper mh(m);
1181 const DexFile::CodeItem* code_item = mh.GetCodeItem();
Elliott Hughesdbb40792011-11-18 17:05:22 -08001182
Elliott Hughesc5b734a2011-12-01 17:20:58 -08001183 // arg_count considers doubles and longs to take 2 units.
1184 // variable_count considers everything to take 1 unit.
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001185 std::string shorty(mh.GetShorty());
Ian Rogers2fa6b2e2012-10-17 00:10:17 -07001186 expandBufAdd4BE(pReply, AbstractMethod::NumArgRegisters(shorty));
Elliott Hughesdbb40792011-11-18 17:05:22 -08001187
Elliott Hughesc5b734a2011-12-01 17:20:58 -08001188 // We don't know the total number of variables yet, so leave a blank and update it later.
1189 size_t variable_count_offset = expandBufGetLength(pReply);
Elliott Hughesdbb40792011-11-18 17:05:22 -08001190 expandBufAdd4BE(pReply, 0);
1191
1192 DebugCallbackContext context;
Elliott Hughesdbb40792011-11-18 17:05:22 -08001193 context.pReply = pReply;
Elliott Hughesc5b734a2011-12-01 17:20:58 -08001194 context.variable_count = 0;
1195 context.with_generic = with_generic;
Elliott Hughesdbb40792011-11-18 17:05:22 -08001196
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001197 mh.GetDexFile().DecodeDebugInfo(code_item, m->IsStatic(), m->GetDexMethodIndex(), NULL,
1198 DebugCallbackContext::Callback, &context);
Elliott Hughesdbb40792011-11-18 17:05:22 -08001199
Elliott Hughesc5b734a2011-12-01 17:20:58 -08001200 JDWP::Set4BE(expandBufGetBuffer(pReply) + variable_count_offset, context.variable_count);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001201}
1202
Elliott Hughes88d63092013-01-09 09:55:54 -08001203JDWP::JdwpTag Dbg::GetFieldBasicTag(JDWP::FieldId field_id) {
1204 return BasicTagFromDescriptor(FieldHelper(FromFieldId(field_id)).GetTypeDescriptor());
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001205}
1206
Elliott Hughes88d63092013-01-09 09:55:54 -08001207JDWP::JdwpTag Dbg::GetStaticFieldBasicTag(JDWP::FieldId field_id) {
1208 return BasicTagFromDescriptor(FieldHelper(FromFieldId(field_id)).GetTypeDescriptor());
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001209}
1210
Elliott Hughes88d63092013-01-09 09:55:54 -08001211static JDWP::JdwpError GetFieldValueImpl(JDWP::RefTypeId ref_type_id, JDWP::ObjectId object_id,
1212 JDWP::FieldId field_id, JDWP::ExpandBuf* pReply,
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001213 bool is_static)
Ian Rogersb726dcb2012-09-05 08:57:23 -07001214 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Elliott Hughes0cf74332012-02-23 23:14:00 -08001215 JDWP::JdwpError status;
Elliott Hughes88d63092013-01-09 09:55:54 -08001216 Class* c = DecodeClass(ref_type_id, status);
1217 if (ref_type_id != 0 && c == NULL) {
Elliott Hughes0cf74332012-02-23 23:14:00 -08001218 return status;
1219 }
1220
Elliott Hughes88d63092013-01-09 09:55:54 -08001221 Object* o = gRegistry->Get<Object*>(object_id);
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08001222 if ((!is_static && o == NULL) || o == kInvalidObject) {
1223 return JDWP::ERR_INVALID_OBJECT;
1224 }
Elliott Hughes88d63092013-01-09 09:55:54 -08001225 Field* f = FromFieldId(field_id);
Elliott Hughes0cf74332012-02-23 23:14:00 -08001226
1227 Class* receiver_class = c;
1228 if (receiver_class == NULL && o != NULL) {
1229 receiver_class = o->GetClass();
1230 }
1231 // TODO: should we give up now if receiver_class is NULL?
1232 if (receiver_class != NULL && !f->GetDeclaringClass()->IsAssignableFrom(receiver_class)) {
1233 LOG(INFO) << "ERR_INVALID_FIELDID: " << PrettyField(f) << " " << PrettyClass(receiver_class);
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08001234 return JDWP::ERR_INVALID_FIELDID;
1235 }
Elliott Hughesaed4be92011-12-02 16:16:23 -08001236
Elliott Hughes0cf74332012-02-23 23:14:00 -08001237 // The RI only enforces the static/non-static mismatch in one direction.
1238 // TODO: should we change the tests and check both?
1239 if (is_static) {
1240 if (!f->IsStatic()) {
1241 return JDWP::ERR_INVALID_FIELDID;
1242 }
1243 } else {
1244 if (f->IsStatic()) {
1245 LOG(WARNING) << "Ignoring non-NULL receiver for ObjectReference.SetValues on static field " << PrettyField(f);
Elliott Hughes0cf74332012-02-23 23:14:00 -08001246 }
1247 }
jeffhao0dfbb7e2012-11-28 15:26:03 -08001248 if (f->IsStatic()) {
1249 o = f->GetDeclaringClass();
1250 }
Elliott Hughes0cf74332012-02-23 23:14:00 -08001251
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001252 JDWP::JdwpTag tag = BasicTagFromDescriptor(FieldHelper(f).GetTypeDescriptor());
Elliott Hughesaed4be92011-12-02 16:16:23 -08001253
1254 if (IsPrimitiveTag(tag)) {
1255 expandBufAdd1(pReply, tag);
1256 if (tag == JDWP::JT_BOOLEAN || tag == JDWP::JT_BYTE) {
1257 expandBufAdd1(pReply, f->Get32(o));
1258 } else if (tag == JDWP::JT_CHAR || tag == JDWP::JT_SHORT) {
1259 expandBufAdd2BE(pReply, f->Get32(o));
1260 } else if (tag == JDWP::JT_FLOAT || tag == JDWP::JT_INT) {
1261 expandBufAdd4BE(pReply, f->Get32(o));
1262 } else if (tag == JDWP::JT_DOUBLE || tag == JDWP::JT_LONG) {
1263 expandBufAdd8BE(pReply, f->Get64(o));
1264 } else {
Elliott Hughes3d30d9b2011-12-07 17:35:48 -08001265 LOG(FATAL) << "Unknown tag: " << tag;
Elliott Hughesaed4be92011-12-02 16:16:23 -08001266 }
1267 } else {
1268 Object* value = f->GetObject(o);
1269 expandBufAdd1(pReply, TagFromObject(value));
1270 expandBufAddObjectId(pReply, gRegistry->Add(value));
1271 }
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08001272 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001273}
1274
Elliott Hughes88d63092013-01-09 09:55:54 -08001275JDWP::JdwpError Dbg::GetFieldValue(JDWP::ObjectId object_id, JDWP::FieldId field_id,
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001276 JDWP::ExpandBuf* pReply) {
Elliott Hughes88d63092013-01-09 09:55:54 -08001277 return GetFieldValueImpl(0, object_id, field_id, pReply, false);
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08001278}
1279
Elliott Hughes88d63092013-01-09 09:55:54 -08001280JDWP::JdwpError Dbg::GetStaticFieldValue(JDWP::RefTypeId ref_type_id, JDWP::FieldId field_id, JDWP::ExpandBuf* pReply) {
1281 return GetFieldValueImpl(ref_type_id, 0, field_id, pReply, true);
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08001282}
1283
Elliott Hughes88d63092013-01-09 09:55:54 -08001284static JDWP::JdwpError SetFieldValueImpl(JDWP::ObjectId object_id, JDWP::FieldId field_id,
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001285 uint64_t value, int width, bool is_static)
Ian Rogersb726dcb2012-09-05 08:57:23 -07001286 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Elliott Hughes88d63092013-01-09 09:55:54 -08001287 Object* o = gRegistry->Get<Object*>(object_id);
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08001288 if ((!is_static && o == NULL) || o == kInvalidObject) {
1289 return JDWP::ERR_INVALID_OBJECT;
1290 }
Elliott Hughes88d63092013-01-09 09:55:54 -08001291 Field* f = FromFieldId(field_id);
Elliott Hughes0cf74332012-02-23 23:14:00 -08001292
1293 // The RI only enforces the static/non-static mismatch in one direction.
1294 // TODO: should we change the tests and check both?
1295 if (is_static) {
1296 if (!f->IsStatic()) {
1297 return JDWP::ERR_INVALID_FIELDID;
1298 }
1299 } else {
1300 if (f->IsStatic()) {
1301 LOG(WARNING) << "Ignoring non-NULL receiver for ObjectReference.SetValues on static field " << PrettyField(f);
Elliott Hughes0cf74332012-02-23 23:14:00 -08001302 }
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08001303 }
jeffhao0dfbb7e2012-11-28 15:26:03 -08001304 if (f->IsStatic()) {
1305 o = f->GetDeclaringClass();
1306 }
Elliott Hughesaed4be92011-12-02 16:16:23 -08001307
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001308 JDWP::JdwpTag tag = BasicTagFromDescriptor(FieldHelper(f).GetTypeDescriptor());
Elliott Hughesaed4be92011-12-02 16:16:23 -08001309
1310 if (IsPrimitiveTag(tag)) {
1311 if (tag == JDWP::JT_DOUBLE || tag == JDWP::JT_LONG) {
Elliott Hughes1bac54f2012-03-16 12:48:31 -07001312 CHECK_EQ(width, 8);
Elliott Hughesaed4be92011-12-02 16:16:23 -08001313 f->Set64(o, value);
1314 } else {
Elliott Hughes1bac54f2012-03-16 12:48:31 -07001315 CHECK_LE(width, 4);
Elliott Hughesaed4be92011-12-02 16:16:23 -08001316 f->Set32(o, value);
1317 }
1318 } else {
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -08001319 Object* v = gRegistry->Get<Object*>(value);
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08001320 if (v == kInvalidObject) {
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -08001321 return JDWP::ERR_INVALID_OBJECT;
1322 }
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08001323 if (v != NULL) {
1324 Class* field_type = FieldHelper(f).GetType();
1325 if (!field_type->IsAssignableFrom(v->GetClass())) {
1326 return JDWP::ERR_INVALID_OBJECT;
1327 }
1328 }
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -08001329 f->SetObject(o, v);
Elliott Hughesaed4be92011-12-02 16:16:23 -08001330 }
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -08001331
1332 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001333}
1334
Elliott Hughes88d63092013-01-09 09:55:54 -08001335JDWP::JdwpError Dbg::SetFieldValue(JDWP::ObjectId object_id, JDWP::FieldId field_id, uint64_t value,
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001336 int width) {
Elliott Hughes88d63092013-01-09 09:55:54 -08001337 return SetFieldValueImpl(object_id, field_id, value, width, false);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001338}
1339
Elliott Hughes88d63092013-01-09 09:55:54 -08001340JDWP::JdwpError Dbg::SetStaticFieldValue(JDWP::FieldId field_id, uint64_t value, int width) {
1341 return SetFieldValueImpl(0, field_id, value, width, true);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001342}
1343
Elliott Hughes88d63092013-01-09 09:55:54 -08001344std::string Dbg::StringToUtf8(JDWP::ObjectId string_id) {
1345 String* s = gRegistry->Get<String*>(string_id);
Elliott Hughes68fdbd02011-11-29 19:22:47 -08001346 return s->ToModifiedUtf8();
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001347}
1348
Elliott Hughes221229c2013-01-08 18:17:50 -08001349JDWP::JdwpError Dbg::GetThreadName(JDWP::ObjectId thread_id, std::string& name) {
jeffhaoa77f0f62012-12-05 17:19:31 -08001350 ScopedObjectAccessUnchecked soa(Thread::Current());
1351 MutexLock mu(soa.Self(), *Locks::thread_list_lock_);
Elliott Hughes221229c2013-01-08 18:17:50 -08001352 Thread* thread;
1353 JDWP::JdwpError error = DecodeThread(soa, thread_id, thread);
1354 if (error != JDWP::ERR_NONE && error != JDWP::ERR_THREAD_NOT_ALIVE) {
1355 return error;
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001356 }
Elliott Hughes221229c2013-01-08 18:17:50 -08001357
1358 // We still need to report the zombie threads' names, so we can't just call Thread::GetThreadName.
1359 Object* thread_object = gRegistry->Get<Object*>(thread_id);
1360 Field* java_lang_Thread_name_field = soa.DecodeField(WellKnownClasses::java_lang_Thread_name);
1361 String* s = reinterpret_cast<String*>(java_lang_Thread_name_field->GetObject(thread_object));
1362 if (s != NULL) {
1363 name = s->ToModifiedUtf8();
1364 }
1365 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001366}
1367
Elliott Hughes221229c2013-01-08 18:17:50 -08001368JDWP::JdwpError Dbg::GetThreadGroup(JDWP::ObjectId thread_id, JDWP::ExpandBuf* pReply) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001369 ScopedObjectAccess soa(Thread::Current());
Elliott Hughes221229c2013-01-08 18:17:50 -08001370 Object* thread_object = gRegistry->Get<Object*>(thread_id);
1371 if (thread_object == kInvalidObject) {
Elliott Hughes2435a572012-02-17 16:07:41 -08001372 return JDWP::ERR_INVALID_OBJECT;
1373 }
1374
1375 // Okay, so it's an object, but is it actually a thread?
Ian Rogers50b35e22012-10-04 10:09:15 -07001376 MutexLock mu(soa.Self(), *Locks::thread_list_lock_);
Elliott Hughes221229c2013-01-08 18:17:50 -08001377 Thread* thread;
1378 JDWP::JdwpError error = DecodeThread(soa, thread_id, thread);
1379 if (error == JDWP::ERR_THREAD_NOT_ALIVE) {
1380 // Zombie threads are in the null group.
1381 expandBufAddObjectId(pReply, JDWP::ObjectId(0));
1382 return JDWP::ERR_NONE;
1383 }
1384 if (error != JDWP::ERR_NONE) {
1385 return error;
Elliott Hughes2435a572012-02-17 16:07:41 -08001386 }
Elliott Hughes499c5132011-11-17 14:55:11 -08001387
1388 Class* c = Runtime::Current()->GetClassLinker()->FindSystemClass("Ljava/lang/Thread;");
1389 CHECK(c != NULL);
1390 Field* f = c->FindInstanceField("group", "Ljava/lang/ThreadGroup;");
1391 CHECK(f != NULL);
Elliott Hughes221229c2013-01-08 18:17:50 -08001392 Object* group = f->GetObject(thread_object);
Elliott Hughes499c5132011-11-17 14:55:11 -08001393 CHECK(group != NULL);
Elliott Hughes2435a572012-02-17 16:07:41 -08001394 JDWP::ObjectId thread_group_id = gRegistry->Add(group);
1395
1396 expandBufAddObjectId(pReply, thread_group_id);
1397 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001398}
1399
Elliott Hughes88d63092013-01-09 09:55:54 -08001400std::string Dbg::GetThreadGroupName(JDWP::ObjectId thread_group_id) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001401 ScopedObjectAccess soa(Thread::Current());
Elliott Hughes88d63092013-01-09 09:55:54 -08001402 Object* thread_group = gRegistry->Get<Object*>(thread_group_id);
Elliott Hughes499c5132011-11-17 14:55:11 -08001403 CHECK(thread_group != NULL);
1404
1405 Class* c = Runtime::Current()->GetClassLinker()->FindSystemClass("Ljava/lang/ThreadGroup;");
1406 CHECK(c != NULL);
1407 Field* f = c->FindInstanceField("name", "Ljava/lang/String;");
1408 CHECK(f != NULL);
1409 String* s = reinterpret_cast<String*>(f->GetObject(thread_group));
1410 return s->ToModifiedUtf8();
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001411}
1412
Elliott Hughes88d63092013-01-09 09:55:54 -08001413JDWP::ObjectId Dbg::GetThreadGroupParent(JDWP::ObjectId thread_group_id) {
1414 Object* thread_group = gRegistry->Get<Object*>(thread_group_id);
Elliott Hughes4e235312011-12-02 11:34:15 -08001415 CHECK(thread_group != NULL);
1416
1417 Class* c = Runtime::Current()->GetClassLinker()->FindSystemClass("Ljava/lang/ThreadGroup;");
1418 CHECK(c != NULL);
1419 Field* f = c->FindInstanceField("parent", "Ljava/lang/ThreadGroup;");
1420 CHECK(f != NULL);
1421 Object* parent = f->GetObject(thread_group);
1422 return gRegistry->Add(parent);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001423}
1424
1425JDWP::ObjectId Dbg::GetSystemThreadGroupId() {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001426 ScopedObjectAccessUnchecked soa(Thread::Current());
jeffhao0dfbb7e2012-11-28 15:26:03 -08001427 Field* f = soa.DecodeField(WellKnownClasses::java_lang_ThreadGroup_systemThreadGroup);
1428 Object* group = f->GetObject(f->GetDeclaringClass());
Ian Rogers365c1022012-06-22 15:05:28 -07001429 return gRegistry->Add(group);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001430}
1431
1432JDWP::ObjectId Dbg::GetMainThreadGroupId() {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001433 ScopedObjectAccess soa(Thread::Current());
jeffhao0dfbb7e2012-11-28 15:26:03 -08001434 Field* f = soa.DecodeField(WellKnownClasses::java_lang_ThreadGroup_mainThreadGroup);
1435 Object* group = f->GetObject(f->GetDeclaringClass());
Ian Rogers365c1022012-06-22 15:05:28 -07001436 return gRegistry->Add(group);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001437}
1438
Elliott Hughes221229c2013-01-08 18:17:50 -08001439JDWP::JdwpError Dbg::GetThreadStatus(JDWP::ObjectId thread_id, JDWP::JdwpThreadStatus* pThreadStatus, JDWP::JdwpSuspendStatus* pSuspendStatus) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001440 ScopedObjectAccess soa(Thread::Current());
Elliott Hughes499c5132011-11-17 14:55:11 -08001441
Ian Rogers50b35e22012-10-04 10:09:15 -07001442 MutexLock mu(soa.Self(), *Locks::thread_list_lock_);
Elliott Hughes221229c2013-01-08 18:17:50 -08001443 Thread* thread;
1444 JDWP::JdwpError error = DecodeThread(soa, thread_id, thread);
1445 if (error != JDWP::ERR_NONE) {
1446 if (error == JDWP::ERR_THREAD_NOT_ALIVE) {
1447 *pThreadStatus = JDWP::TS_ZOMBIE;
1448 *pSuspendStatus = JDWP::SUSPEND_STATUS_NOT_SUSPENDED;
1449 return JDWP::ERR_NONE;
1450 }
1451 return error;
Elliott Hughes499c5132011-11-17 14:55:11 -08001452 }
1453
Ian Rogers50b35e22012-10-04 10:09:15 -07001454 MutexLock mu2(soa.Self(), *Locks::thread_suspend_count_lock_);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001455
Elliott Hughes499c5132011-11-17 14:55:11 -08001456 switch (thread->GetState()) {
Elliott Hughes34e06962012-04-09 13:55:55 -07001457 case kTerminated: *pThreadStatus = JDWP::TS_ZOMBIE; break;
1458 case kRunnable: *pThreadStatus = JDWP::TS_RUNNING; break;
1459 case kTimedWaiting: *pThreadStatus = JDWP::TS_WAIT; break;
Elliott Hughes4cd121e2013-01-07 17:35:41 -08001460 case kSleeping: *pThreadStatus = JDWP::TS_SLEEPING; break;
Elliott Hughes34e06962012-04-09 13:55:55 -07001461 case kBlocked: *pThreadStatus = JDWP::TS_MONITOR; break;
1462 case kWaiting: *pThreadStatus = JDWP::TS_WAIT; break;
1463 case kStarting: *pThreadStatus = JDWP::TS_ZOMBIE; break;
1464 case kNative: *pThreadStatus = JDWP::TS_RUNNING; break;
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001465 case kWaitingForGcToComplete: // Fall-through.
1466 case kWaitingPerformingGc: // Fall-through.
1467 case kWaitingForDebuggerSend: // Fall-through.
1468 case kWaitingForDebuggerToAttach: // Fall-through.
1469 case kWaitingInMainDebuggerLoop: // Fall-through.
1470 case kWaitingForDebuggerSuspension: // Fall-through.
1471 case kWaitingForJniOnLoad: // Fall-through.
1472 case kWaitingForSignalCatcherOutput: // Fall-through.
1473 case kWaitingInMainSignalCatcherLoop:
1474 *pThreadStatus = JDWP::TS_WAIT; break;
Elliott Hughes34e06962012-04-09 13:55:55 -07001475 case kSuspended: *pThreadStatus = JDWP::TS_RUNNING; break;
Elliott Hughescf2b2d42012-03-27 17:11:42 -07001476 // Don't add a 'default' here so the compiler can spot incompatible enum changes.
Elliott Hughes499c5132011-11-17 14:55:11 -08001477 }
1478
Elliott Hughes3d30d9b2011-12-07 17:35:48 -08001479 *pSuspendStatus = (thread->IsSuspended() ? JDWP::SUSPEND_STATUS_SUSPENDED : JDWP::SUSPEND_STATUS_NOT_SUSPENDED);
Elliott Hughes499c5132011-11-17 14:55:11 -08001480
Elliott Hughes221229c2013-01-08 18:17:50 -08001481 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001482}
1483
Elliott Hughes221229c2013-01-08 18:17:50 -08001484JDWP::JdwpError Dbg::GetThreadDebugSuspendCount(JDWP::ObjectId thread_id, JDWP::ExpandBuf* pReply) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001485 ScopedObjectAccess soa(Thread::Current());
Ian Rogers50b35e22012-10-04 10:09:15 -07001486 MutexLock mu(soa.Self(), *Locks::thread_list_lock_);
Elliott Hughes221229c2013-01-08 18:17:50 -08001487 Thread* thread;
1488 JDWP::JdwpError error = DecodeThread(soa, thread_id, thread);
1489 if (error != JDWP::ERR_NONE) {
1490 return error;
Elliott Hughes2435a572012-02-17 16:07:41 -08001491 }
Ian Rogers50b35e22012-10-04 10:09:15 -07001492 MutexLock mu2(soa.Self(), *Locks::thread_suspend_count_lock_);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001493 expandBufAdd4BE(pReply, thread->GetDebugSuspendCount());
Elliott Hughes2435a572012-02-17 16:07:41 -08001494 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001495}
1496
Elliott Hughescaf76542012-06-28 16:08:22 -07001497void Dbg::GetThreads(JDWP::ObjectId thread_group_id, std::vector<JDWP::ObjectId>& thread_ids) {
Ian Rogers365c1022012-06-22 15:05:28 -07001498 class ThreadListVisitor {
1499 public:
jeffhao0dfbb7e2012-11-28 15:26:03 -08001500 ThreadListVisitor(const ScopedObjectAccessUnchecked& soa, Object* desired_thread_group,
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001501 std::vector<JDWP::ObjectId>& thread_ids)
Ian Rogersb726dcb2012-09-05 08:57:23 -07001502 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_)
jeffhao0dfbb7e2012-11-28 15:26:03 -08001503 : soa_(soa), desired_thread_group_(desired_thread_group), thread_ids_(thread_ids) {}
Ian Rogers365c1022012-06-22 15:05:28 -07001504
Elliott Hughesa2155262011-11-16 16:26:58 -08001505 static void Visit(Thread* t, void* arg) {
1506 reinterpret_cast<ThreadListVisitor*>(arg)->Visit(t);
1507 }
1508
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001509 // TODO: Enable annotalysis. We know lock is held in constructor, but abstraction confuses
1510 // annotalysis.
1511 void Visit(Thread* t) NO_THREAD_SAFETY_ANALYSIS {
Elliott Hughesa2155262011-11-16 16:26:58 -08001512 if (t == Dbg::GetDebugThread()) {
1513 // Skip the JDWP thread. Some debuggers get bent out of shape when they can't suspend and
1514 // query all threads, so it's easier if we just don't tell them about this thread.
1515 return;
1516 }
Ian Rogerscfaa4552012-11-26 21:00:08 -08001517 Object* peer = t->GetPeer();
jeffhao0dfbb7e2012-11-28 15:26:03 -08001518 if (IsInDesiredThreadGroup(peer)) {
Ian Rogers120f1c72012-09-28 17:17:10 -07001519 thread_ids_.push_back(gRegistry->Add(peer));
Elliott Hughesa2155262011-11-16 16:26:58 -08001520 }
1521 }
1522
Ian Rogers365c1022012-06-22 15:05:28 -07001523 private:
jeffhao0dfbb7e2012-11-28 15:26:03 -08001524 bool IsInDesiredThreadGroup(Object* peer)
1525 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
jeffhao0dfbb7e2012-11-28 15:26:03 -08001526 // peer might be NULL if the thread is still starting up.
1527 if (peer == NULL) {
1528 // We can't tell the debugger about this thread yet.
1529 // TODO: if we identified threads to the debugger by their Thread*
1530 // rather than their peer's Object*, we could fix this.
1531 // Doing so might help us report ZOMBIE threads too.
1532 return false;
1533 }
jeffhaoc1e04902012-12-13 12:41:10 -08001534 // Do we want threads from all thread groups?
1535 if (desired_thread_group_ == NULL) {
1536 return true;
1537 }
jeffhao0dfbb7e2012-11-28 15:26:03 -08001538 Object* group = soa_.DecodeField(WellKnownClasses::java_lang_Thread_group)->GetObject(peer);
1539 return (group == desired_thread_group_);
1540 }
1541
Mathieu Chartierdbe6f462012-09-25 16:54:50 -07001542 const ScopedObjectAccessUnchecked& soa_;
jeffhao0dfbb7e2012-11-28 15:26:03 -08001543 Object* const desired_thread_group_;
Elliott Hughescaf76542012-06-28 16:08:22 -07001544 std::vector<JDWP::ObjectId>& thread_ids_;
Elliott Hughesa2155262011-11-16 16:26:58 -08001545 };
1546
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001547 ScopedObjectAccessUnchecked soa(Thread::Current());
Elliott Hughescaf76542012-06-28 16:08:22 -07001548 Object* thread_group = gRegistry->Get<Object*>(thread_group_id);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001549 ThreadListVisitor tlv(soa, thread_group, thread_ids);
Ian Rogers50b35e22012-10-04 10:09:15 -07001550 MutexLock mu(soa.Self(), *Locks::thread_list_lock_);
Elliott Hughesf8349362012-06-18 15:00:06 -07001551 Runtime::Current()->GetThreadList()->ForEach(ThreadListVisitor::Visit, &tlv);
Elliott Hughescaf76542012-06-28 16:08:22 -07001552}
Elliott Hughesa2155262011-11-16 16:26:58 -08001553
Elliott Hughescaf76542012-06-28 16:08:22 -07001554void Dbg::GetChildThreadGroups(JDWP::ObjectId thread_group_id, std::vector<JDWP::ObjectId>& child_thread_group_ids) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001555 ScopedObjectAccess soa(Thread::Current());
Elliott Hughescaf76542012-06-28 16:08:22 -07001556 Object* thread_group = gRegistry->Get<Object*>(thread_group_id);
1557
1558 // Get the ArrayList<ThreadGroup> "groups" out of this thread group...
1559 Field* groups_field = thread_group->GetClass()->FindInstanceField("groups", "Ljava/util/List;");
1560 Object* groups_array_list = groups_field->GetObject(thread_group);
1561
1562 // Get the array and size out of the ArrayList<ThreadGroup>...
1563 Field* array_field = groups_array_list->GetClass()->FindInstanceField("array", "[Ljava/lang/Object;");
1564 Field* size_field = groups_array_list->GetClass()->FindInstanceField("size", "I");
1565 ObjectArray<Object>* groups_array = array_field->GetObject(groups_array_list)->AsObjectArray<Object>();
1566 const int32_t size = size_field->GetInt(groups_array_list);
1567
1568 // Copy the first 'size' elements out of the array into the result.
1569 for (int32_t i = 0; i < size; ++i) {
1570 child_thread_group_ids.push_back(gRegistry->Add(groups_array->Get(i)));
Elliott Hughesa2155262011-11-16 16:26:58 -08001571 }
1572}
1573
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001574static int GetStackDepth(Thread* thread)
Ian Rogersb726dcb2012-09-05 08:57:23 -07001575 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Ian Rogers0399dde2012-06-06 17:09:28 -07001576 struct CountStackDepthVisitor : public StackVisitor {
1577 CountStackDepthVisitor(const ManagedStack* stack,
Ian Rogers306057f2012-11-26 12:45:53 -08001578 const std::deque<InstrumentationStackFrame>* instrumentation_stack)
jeffhao725a9572012-11-13 18:20:12 -08001579 : StackVisitor(stack, instrumentation_stack, NULL), depth(0) {}
Ian Rogers0399dde2012-06-06 17:09:28 -07001580
1581 bool VisitFrame() {
1582 if (!GetMethod()->IsRuntimeMethod()) {
Elliott Hughesf8a2df72011-12-01 12:19:54 -08001583 ++depth;
1584 }
Elliott Hughes530fa002012-03-12 11:44:49 -07001585 return true;
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001586 }
1587 size_t depth;
1588 };
Elliott Hughes08fc03a2012-06-26 17:34:00 -07001589
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001590 if (kIsDebugBuild) {
Ian Rogers50b35e22012-10-04 10:09:15 -07001591 MutexLock mu(Thread::Current(), *Locks::thread_suspend_count_lock_);
jeffhao09bfc6a2012-12-11 18:11:43 -08001592 CHECK(thread == Thread::Current() || thread->IsSuspended());
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001593 }
jeffhao725a9572012-11-13 18:20:12 -08001594 CountStackDepthVisitor visitor(thread->GetManagedStack(), thread->GetInstrumentationStack());
Ian Rogers0399dde2012-06-06 17:09:28 -07001595 visitor.WalkStack();
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001596 return visitor.depth;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001597}
1598
Elliott Hughesf15f4a02013-01-09 10:09:38 -08001599static bool IsSuspendedForDebugger(ScopedObjectAccessUnchecked& soa, Thread* thread) {
1600 MutexLock mu(soa.Self(), *Locks::thread_suspend_count_lock_);
1601 return thread->IsSuspended() && thread->GetDebugSuspendCount() > 0;
1602}
1603
Elliott Hughes221229c2013-01-08 18:17:50 -08001604JDWP::JdwpError Dbg::GetThreadFrameCount(JDWP::ObjectId thread_id, size_t& result) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001605 ScopedObjectAccess soa(Thread::Current());
jeffhaoa77f0f62012-12-05 17:19:31 -08001606 MutexLock mu(soa.Self(), *Locks::thread_list_lock_);
Elliott Hughes221229c2013-01-08 18:17:50 -08001607 Thread* thread;
1608 JDWP::JdwpError error = DecodeThread(soa, thread_id, thread);
1609 if (error != JDWP::ERR_NONE) {
1610 return error;
1611 }
Elliott Hughesf15f4a02013-01-09 10:09:38 -08001612 if (!IsSuspendedForDebugger(soa, thread)) {
1613 return JDWP::ERR_THREAD_NOT_SUSPENDED;
1614 }
Elliott Hughes221229c2013-01-08 18:17:50 -08001615 result = GetStackDepth(thread);
1616 return JDWP::ERR_NONE;
Elliott Hughes86964332012-02-15 19:37:42 -08001617}
1618
Ian Rogers306057f2012-11-26 12:45:53 -08001619JDWP::JdwpError Dbg::GetThreadFrames(JDWP::ObjectId thread_id, size_t start_frame,
1620 size_t frame_count, JDWP::ExpandBuf* buf) {
Elliott Hughes6e9d22c2012-06-22 15:02:37 -07001621 class GetFrameVisitor : public StackVisitor {
1622 public:
Ian Rogers306057f2012-11-26 12:45:53 -08001623 GetFrameVisitor(const ManagedStack* stack,
1624 const std::deque<InstrumentationStackFrame>* instrumentation_stack,
Elliott Hughes6e9d22c2012-06-22 15:02:37 -07001625 size_t start_frame, size_t frame_count, JDWP::ExpandBuf* buf)
Ian Rogersb726dcb2012-09-05 08:57:23 -07001626 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_)
jeffhao725a9572012-11-13 18:20:12 -08001627 : StackVisitor(stack, instrumentation_stack, NULL), depth_(0),
Elliott Hughes6e9d22c2012-06-22 15:02:37 -07001628 start_frame_(start_frame), frame_count_(frame_count), buf_(buf) {
1629 expandBufAdd4BE(buf_, frame_count_);
Elliott Hughes03181a82011-11-17 17:22:21 -08001630 }
Ian Rogers0399dde2012-06-06 17:09:28 -07001631
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001632 // TODO: Enable annotalysis. We know lock is held in constructor, but abstraction confuses
1633 // annotalysis.
1634 virtual bool VisitFrame() NO_THREAD_SAFETY_ANALYSIS {
Ian Rogers0399dde2012-06-06 17:09:28 -07001635 if (GetMethod()->IsRuntimeMethod()) {
Elliott Hughes530fa002012-03-12 11:44:49 -07001636 return true; // The debugger can't do anything useful with a frame that has no Method*.
Elliott Hughes03181a82011-11-17 17:22:21 -08001637 }
Elliott Hughes6e9d22c2012-06-22 15:02:37 -07001638 if (depth_ >= start_frame_ + frame_count_) {
Elliott Hughes530fa002012-03-12 11:44:49 -07001639 return false;
Elliott Hughes03181a82011-11-17 17:22:21 -08001640 }
Elliott Hughes6e9d22c2012-06-22 15:02:37 -07001641 if (depth_ >= start_frame_) {
1642 JDWP::FrameId frame_id(GetFrameId());
1643 JDWP::JdwpLocation location;
1644 SetLocation(location, GetMethod(), GetDexPc());
Elliott Hughes7baf96f2012-06-22 16:33:50 -07001645 VLOG(jdwp) << StringPrintf(" Frame %3zd: id=%3lld ", depth_, frame_id) << location;
Elliott Hughes6e9d22c2012-06-22 15:02:37 -07001646 expandBufAdd8BE(buf_, frame_id);
1647 expandBufAddLocation(buf_, location);
1648 }
1649 ++depth_;
Elliott Hughes530fa002012-03-12 11:44:49 -07001650 return true;
Elliott Hughes03181a82011-11-17 17:22:21 -08001651 }
Elliott Hughes6e9d22c2012-06-22 15:02:37 -07001652
1653 private:
1654 size_t depth_;
1655 const size_t start_frame_;
1656 const size_t frame_count_;
1657 JDWP::ExpandBuf* buf_;
Elliott Hughes03181a82011-11-17 17:22:21 -08001658 };
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001659
1660 ScopedObjectAccessUnchecked soa(Thread::Current());
jeffhaoa77f0f62012-12-05 17:19:31 -08001661 MutexLock mu(soa.Self(), *Locks::thread_list_lock_);
Elliott Hughes221229c2013-01-08 18:17:50 -08001662 Thread* thread;
1663 JDWP::JdwpError error = DecodeThread(soa, thread_id, thread);
1664 if (error != JDWP::ERR_NONE) {
1665 return error;
1666 }
Elliott Hughesf15f4a02013-01-09 10:09:38 -08001667 if (!IsSuspendedForDebugger(soa, thread)) {
1668 return JDWP::ERR_THREAD_NOT_SUSPENDED;
1669 }
Ian Rogers306057f2012-11-26 12:45:53 -08001670 GetFrameVisitor visitor(thread->GetManagedStack(), thread->GetInstrumentationStack(),
1671 start_frame, frame_count, buf);
Ian Rogers0399dde2012-06-06 17:09:28 -07001672 visitor.WalkStack();
Elliott Hughes6e9d22c2012-06-22 15:02:37 -07001673 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001674}
1675
1676JDWP::ObjectId Dbg::GetThreadSelfId() {
Mathieu Chartierdbe6f462012-09-25 16:54:50 -07001677 ScopedObjectAccessUnchecked soa(Thread::Current());
Ian Rogerscfaa4552012-11-26 21:00:08 -08001678 return gRegistry->Add(soa.Self()->GetPeer());
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001679}
1680
Elliott Hughes475fc232011-10-25 15:00:35 -07001681void Dbg::SuspendVM() {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001682 Runtime::Current()->GetThreadList()->SuspendAllForDebugger();
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001683}
1684
1685void Dbg::ResumeVM() {
Elliott Hughesc61a2672012-06-21 14:52:29 -07001686 Runtime::Current()->GetThreadList()->UndoDebuggerSuspensions();
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001687}
1688
Elliott Hughes221229c2013-01-08 18:17:50 -08001689JDWP::JdwpError Dbg::SuspendThread(JDWP::ObjectId thread_id, bool request_suspension) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001690
1691 bool timeout;
1692 ScopedLocalRef<jobject> peer(Thread::Current()->GetJniEnv(), NULL);
1693 {
1694 ScopedObjectAccess soa(Thread::Current());
Elliott Hughes221229c2013-01-08 18:17:50 -08001695 peer.reset(soa.AddLocalReference<jobject>(gRegistry->Get<Object*>(thread_id)));
Elliott Hughes4e235312011-12-02 11:34:15 -08001696 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001697 if (peer.get() == NULL) {
Elliott Hughes221229c2013-01-08 18:17:50 -08001698 LOG(WARNING) << "No such thread for suspend: " << thread_id;
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001699 return JDWP::ERR_THREAD_NOT_ALIVE;
1700 }
1701 // Suspend thread to build stack trace.
1702 Thread* thread = Thread::SuspendForDebugger(peer.get(), request_suspension, &timeout);
1703 if (thread != NULL) {
1704 return JDWP::ERR_NONE;
1705 } else if (timeout) {
1706 return JDWP::ERR_INTERNAL;
1707 } else {
1708 return JDWP::ERR_THREAD_NOT_ALIVE;
1709 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001710}
1711
Elliott Hughes221229c2013-01-08 18:17:50 -08001712void Dbg::ResumeThread(JDWP::ObjectId thread_id) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001713 ScopedObjectAccessUnchecked soa(Thread::Current());
Elliott Hughes221229c2013-01-08 18:17:50 -08001714 Object* peer = gRegistry->Get<Object*>(thread_id);
jeffhaoa77f0f62012-12-05 17:19:31 -08001715 Thread* thread;
1716 {
1717 MutexLock mu(soa.Self(), *Locks::thread_list_lock_);
1718 thread = Thread::FromManagedThread(soa, peer);
1719 }
Elliott Hughes4e235312011-12-02 11:34:15 -08001720 if (thread == NULL) {
1721 LOG(WARNING) << "No such thread for resume: " << peer;
1722 return;
1723 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001724 bool needs_resume;
1725 {
Ian Rogers50b35e22012-10-04 10:09:15 -07001726 MutexLock mu2(soa.Self(), *Locks::thread_suspend_count_lock_);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001727 needs_resume = thread->GetSuspendCount() > 0;
1728 }
1729 if (needs_resume) {
Elliott Hughes546b9862012-06-20 16:06:13 -07001730 Runtime::Current()->GetThreadList()->Resume(thread, true);
1731 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001732}
1733
1734void Dbg::SuspendSelf() {
Elliott Hughes475fc232011-10-25 15:00:35 -07001735 Runtime::Current()->GetThreadList()->SuspendSelfForDebugger();
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001736}
1737
Ian Rogers0399dde2012-06-06 17:09:28 -07001738struct GetThisVisitor : public StackVisitor {
Ian Rogers306057f2012-11-26 12:45:53 -08001739 GetThisVisitor(const ManagedStack* stack,
1740 const std::deque<InstrumentationStackFrame>* instrumentation_stack,
Elliott Hughes88d63092013-01-09 09:55:54 -08001741 Context* context, JDWP::FrameId frame_id)
Ian Rogersb726dcb2012-09-05 08:57:23 -07001742 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_)
Elliott Hughes88d63092013-01-09 09:55:54 -08001743 : StackVisitor(stack, instrumentation_stack, context), this_object(NULL), frame_id(frame_id) {}
Ian Rogers0399dde2012-06-06 17:09:28 -07001744
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001745 // TODO: Enable annotalysis. We know lock is held in constructor, but abstraction confuses
1746 // annotalysis.
1747 virtual bool VisitFrame() NO_THREAD_SAFETY_ANALYSIS {
Elliott Hughes6e9d22c2012-06-22 15:02:37 -07001748 if (frame_id != GetFrameId()) {
Ian Rogers0399dde2012-06-06 17:09:28 -07001749 return true; // continue
1750 }
Mathieu Chartier66f19252012-09-18 08:57:04 -07001751 AbstractMethod* m = GetMethod();
Ian Rogers0399dde2012-06-06 17:09:28 -07001752 if (m->IsNative() || m->IsStatic()) {
Elliott Hughes6e9d22c2012-06-22 15:02:37 -07001753 this_object = NULL;
Ian Rogers0399dde2012-06-06 17:09:28 -07001754 } else {
1755 uint16_t reg = DemangleSlot(0, m);
Ian Rogers2bcb4a42012-11-08 10:39:18 -08001756 this_object = reinterpret_cast<Object*>(GetVReg(m, reg, kReferenceVReg));
Ian Rogers0399dde2012-06-06 17:09:28 -07001757 }
1758 return false;
Elliott Hughes86b00102011-12-05 17:54:26 -08001759 }
Ian Rogers0399dde2012-06-06 17:09:28 -07001760
Elliott Hughes6e9d22c2012-06-22 15:02:37 -07001761 Object* this_object;
1762 JDWP::FrameId frame_id;
Ian Rogers0399dde2012-06-06 17:09:28 -07001763};
1764
Mathieu Chartier66f19252012-09-18 08:57:04 -07001765static Object* GetThis(Thread* self, AbstractMethod* m, size_t frame_id)
Ian Rogersb726dcb2012-09-05 08:57:23 -07001766 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Elliott Hughescaf76542012-06-28 16:08:22 -07001767 // TODO: should we return the 'this' we passed through to non-static native methods?
Ian Rogers0399dde2012-06-06 17:09:28 -07001768 if (m->IsNative() || m->IsStatic()) {
1769 return NULL;
1770 }
Elliott Hughescaf76542012-06-28 16:08:22 -07001771
Ian Rogers0399dde2012-06-06 17:09:28 -07001772 UniquePtr<Context> context(Context::Create());
jeffhao725a9572012-11-13 18:20:12 -08001773 GetThisVisitor visitor(self->GetManagedStack(), self->GetInstrumentationStack(), context.get(), frame_id);
Elliott Hughescaf76542012-06-28 16:08:22 -07001774 visitor.WalkStack();
1775 return visitor.this_object;
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08001776}
1777
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001778JDWP::JdwpError Dbg::GetThisObject(JDWP::ObjectId thread_id, JDWP::FrameId frame_id,
1779 JDWP::ObjectId* result) {
1780 ScopedObjectAccessUnchecked soa(Thread::Current());
1781 Thread* thread;
1782 {
Ian Rogers50b35e22012-10-04 10:09:15 -07001783 MutexLock mu(soa.Self(), *Locks::thread_list_lock_);
Elliott Hughes221229c2013-01-08 18:17:50 -08001784 JDWP::JdwpError error = DecodeThread(soa, thread_id, thread);
1785 if (error != JDWP::ERR_NONE) {
1786 return error;
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001787 }
Ian Rogers50b35e22012-10-04 10:09:15 -07001788 MutexLock mu2(soa.Self(), *Locks::thread_suspend_count_lock_);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001789 if (!thread->IsSuspended()) {
1790 return JDWP::ERR_THREAD_NOT_SUSPENDED;
1791 }
Elliott Hughes6e9d22c2012-06-22 15:02:37 -07001792 }
Elliott Hughescaf76542012-06-28 16:08:22 -07001793 UniquePtr<Context> context(Context::Create());
jeffhao725a9572012-11-13 18:20:12 -08001794 GetThisVisitor visitor(thread->GetManagedStack(), thread->GetInstrumentationStack(), context.get(), frame_id);
Ian Rogers0399dde2012-06-06 17:09:28 -07001795 visitor.WalkStack();
Elliott Hughes6e9d22c2012-06-22 15:02:37 -07001796 *result = gRegistry->Add(visitor.this_object);
1797 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001798}
1799
Elliott Hughes88d63092013-01-09 09:55:54 -08001800void Dbg::GetLocalValue(JDWP::ObjectId thread_id, JDWP::FrameId frame_id, int slot, JDWP::JdwpTag tag,
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001801 uint8_t* buf, size_t width) {
Ian Rogers0399dde2012-06-06 17:09:28 -07001802 struct GetLocalVisitor : public StackVisitor {
Ian Rogers306057f2012-11-26 12:45:53 -08001803 GetLocalVisitor(const ManagedStack* stack,
1804 const std::deque<InstrumentationStackFrame>* instrumentation_stack,
Elliott Hughes88d63092013-01-09 09:55:54 -08001805 Context* context, JDWP::FrameId frame_id, int slot, JDWP::JdwpTag tag,
Ian Rogersca190662012-06-26 15:45:57 -07001806 uint8_t* buf, size_t width)
Ian Rogersb726dcb2012-09-05 08:57:23 -07001807 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_)
Elliott Hughes88d63092013-01-09 09:55:54 -08001808 : StackVisitor(stack, instrumentation_stack, context), frame_id_(frame_id), slot_(slot), tag_(tag),
Ian Rogersca190662012-06-26 15:45:57 -07001809 buf_(buf), width_(width) {}
1810
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001811 // TODO: Enable annotalysis. We know lock is held in constructor, but abstraction confuses
1812 // annotalysis.
1813 bool VisitFrame() NO_THREAD_SAFETY_ANALYSIS {
Ian Rogers0399dde2012-06-06 17:09:28 -07001814 if (GetFrameId() != frame_id_) {
1815 return true; // Not our frame, carry on.
Elliott Hughesdbb40792011-11-18 17:05:22 -08001816 }
Ian Rogers0399dde2012-06-06 17:09:28 -07001817 // TODO: check that the tag is compatible with the actual type of the slot!
Mathieu Chartier66f19252012-09-18 08:57:04 -07001818 AbstractMethod* m = GetMethod();
Ian Rogers0399dde2012-06-06 17:09:28 -07001819 uint16_t reg = DemangleSlot(slot_, m);
Elliott Hughesdbb40792011-11-18 17:05:22 -08001820
Ian Rogers0399dde2012-06-06 17:09:28 -07001821 switch (tag_) {
1822 case JDWP::JT_BOOLEAN:
1823 {
1824 CHECK_EQ(width_, 1U);
Ian Rogers2bcb4a42012-11-08 10:39:18 -08001825 uint32_t intVal = GetVReg(m, reg, kIntVReg);
Ian Rogers0399dde2012-06-06 17:09:28 -07001826 VLOG(jdwp) << "get boolean local " << reg << " = " << intVal;
1827 JDWP::Set1(buf_+1, intVal != 0);
1828 }
1829 break;
1830 case JDWP::JT_BYTE:
1831 {
1832 CHECK_EQ(width_, 1U);
Ian Rogers2bcb4a42012-11-08 10:39:18 -08001833 uint32_t intVal = GetVReg(m, reg, kIntVReg);
Ian Rogers0399dde2012-06-06 17:09:28 -07001834 VLOG(jdwp) << "get byte local " << reg << " = " << intVal;
1835 JDWP::Set1(buf_+1, intVal);
1836 }
1837 break;
1838 case JDWP::JT_SHORT:
1839 case JDWP::JT_CHAR:
1840 {
1841 CHECK_EQ(width_, 2U);
Ian Rogers2bcb4a42012-11-08 10:39:18 -08001842 uint32_t intVal = GetVReg(m, reg, kIntVReg);
Ian Rogers0399dde2012-06-06 17:09:28 -07001843 VLOG(jdwp) << "get short/char local " << reg << " = " << intVal;
1844 JDWP::Set2BE(buf_+1, intVal);
1845 }
1846 break;
1847 case JDWP::JT_INT:
Ian Rogers2bcb4a42012-11-08 10:39:18 -08001848 {
1849 CHECK_EQ(width_, 4U);
1850 uint32_t intVal = GetVReg(m, reg, kIntVReg);
1851 VLOG(jdwp) << "get int local " << reg << " = " << intVal;
1852 JDWP::Set4BE(buf_+1, intVal);
1853 }
1854 break;
Ian Rogers0399dde2012-06-06 17:09:28 -07001855 case JDWP::JT_FLOAT:
1856 {
1857 CHECK_EQ(width_, 4U);
Ian Rogers2bcb4a42012-11-08 10:39:18 -08001858 uint32_t intVal = GetVReg(m, reg, kFloatVReg);
Ian Rogers0399dde2012-06-06 17:09:28 -07001859 VLOG(jdwp) << "get int/float local " << reg << " = " << intVal;
1860 JDWP::Set4BE(buf_+1, intVal);
1861 }
1862 break;
1863 case JDWP::JT_ARRAY:
1864 {
1865 CHECK_EQ(width_, sizeof(JDWP::ObjectId));
Ian Rogers2bcb4a42012-11-08 10:39:18 -08001866 Object* o = reinterpret_cast<Object*>(GetVReg(m, reg, kReferenceVReg));
Ian Rogers0399dde2012-06-06 17:09:28 -07001867 VLOG(jdwp) << "get array local " << reg << " = " << o;
1868 if (!Runtime::Current()->GetHeap()->IsHeapAddress(o)) {
1869 LOG(FATAL) << "Register " << reg << " expected to hold array: " << o;
1870 }
1871 JDWP::SetObjectId(buf_+1, gRegistry->Add(o));
1872 }
1873 break;
1874 case JDWP::JT_CLASS_LOADER:
1875 case JDWP::JT_CLASS_OBJECT:
1876 case JDWP::JT_OBJECT:
1877 case JDWP::JT_STRING:
1878 case JDWP::JT_THREAD:
1879 case JDWP::JT_THREAD_GROUP:
1880 {
1881 CHECK_EQ(width_, sizeof(JDWP::ObjectId));
Ian Rogers2bcb4a42012-11-08 10:39:18 -08001882 Object* o = reinterpret_cast<Object*>(GetVReg(m, reg, kReferenceVReg));
Ian Rogers0399dde2012-06-06 17:09:28 -07001883 VLOG(jdwp) << "get object local " << reg << " = " << o;
1884 if (!Runtime::Current()->GetHeap()->IsHeapAddress(o)) {
1885 LOG(FATAL) << "Register " << reg << " expected to hold object: " << o;
1886 }
1887 tag_ = TagFromObject(o);
1888 JDWP::SetObjectId(buf_+1, gRegistry->Add(o));
1889 }
1890 break;
1891 case JDWP::JT_DOUBLE:
Ian Rogers2bcb4a42012-11-08 10:39:18 -08001892 {
1893 CHECK_EQ(width_, 8U);
1894 uint32_t lo = GetVReg(m, reg, kDoubleLoVReg);
1895 uint64_t hi = GetVReg(m, reg + 1, kDoubleHiVReg);
1896 uint64_t longVal = (hi << 32) | lo;
1897 VLOG(jdwp) << "get double/long local " << hi << ":" << lo << " = " << longVal;
1898 JDWP::Set8BE(buf_+1, longVal);
1899 }
1900 break;
Ian Rogers0399dde2012-06-06 17:09:28 -07001901 case JDWP::JT_LONG:
1902 {
1903 CHECK_EQ(width_, 8U);
Ian Rogers2bcb4a42012-11-08 10:39:18 -08001904 uint32_t lo = GetVReg(m, reg, kLongLoVReg);
1905 uint64_t hi = GetVReg(m, reg + 1, kLongHiVReg);
Ian Rogers0399dde2012-06-06 17:09:28 -07001906 uint64_t longVal = (hi << 32) | lo;
1907 VLOG(jdwp) << "get double/long local " << hi << ":" << lo << " = " << longVal;
1908 JDWP::Set8BE(buf_+1, longVal);
1909 }
1910 break;
1911 default:
1912 LOG(FATAL) << "Unknown tag " << tag_;
1913 break;
1914 }
1915
1916 // Prepend tag, which may have been updated.
1917 JDWP::Set1(buf_, tag_);
1918 return false;
1919 }
1920
1921 const JDWP::FrameId frame_id_;
1922 const int slot_;
1923 JDWP::JdwpTag tag_;
1924 uint8_t* const buf_;
1925 const size_t width_;
1926 };
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001927
1928 ScopedObjectAccessUnchecked soa(Thread::Current());
jeffhaoa77f0f62012-12-05 17:19:31 -08001929 MutexLock mu(soa.Self(), *Locks::thread_list_lock_);
Elliott Hughes221229c2013-01-08 18:17:50 -08001930 Thread* thread;
1931 JDWP::JdwpError error = DecodeThread(soa, thread_id, thread);
1932 if (error != JDWP::ERR_NONE) {
1933 return;
1934 }
Ian Rogers0399dde2012-06-06 17:09:28 -07001935 UniquePtr<Context> context(Context::Create());
jeffhao725a9572012-11-13 18:20:12 -08001936 GetLocalVisitor visitor(thread->GetManagedStack(), thread->GetInstrumentationStack(), context.get(),
Elliott Hughes88d63092013-01-09 09:55:54 -08001937 frame_id, slot, tag, buf, width);
Ian Rogers0399dde2012-06-06 17:09:28 -07001938 visitor.WalkStack();
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001939}
1940
Elliott Hughes88d63092013-01-09 09:55:54 -08001941void Dbg::SetLocalValue(JDWP::ObjectId thread_id, JDWP::FrameId frame_id, int slot, JDWP::JdwpTag tag,
Ian Rogers0399dde2012-06-06 17:09:28 -07001942 uint64_t value, size_t width) {
1943 struct SetLocalVisitor : public StackVisitor {
Ian Rogers306057f2012-11-26 12:45:53 -08001944 SetLocalVisitor(const ManagedStack* stack, const std::deque<InstrumentationStackFrame>* instrumentation_stack, Context* context,
Ian Rogers0399dde2012-06-06 17:09:28 -07001945 JDWP::FrameId frame_id, int slot, JDWP::JdwpTag tag, uint64_t value,
Ian Rogersca190662012-06-26 15:45:57 -07001946 size_t width)
Ian Rogersb726dcb2012-09-05 08:57:23 -07001947 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_)
jeffhao725a9572012-11-13 18:20:12 -08001948 : StackVisitor(stack, instrumentation_stack, context),
Elliott Hughes08fc03a2012-06-26 17:34:00 -07001949 frame_id_(frame_id), slot_(slot), tag_(tag), value_(value), width_(width) {}
Ian Rogersca190662012-06-26 15:45:57 -07001950
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001951 // TODO: Enable annotalysis. We know lock is held in constructor, but abstraction confuses
1952 // annotalysis.
1953 bool VisitFrame() NO_THREAD_SAFETY_ANALYSIS {
Ian Rogers0399dde2012-06-06 17:09:28 -07001954 if (GetFrameId() != frame_id_) {
1955 return true; // Not our frame, carry on.
1956 }
1957 // TODO: check that the tag is compatible with the actual type of the slot!
Mathieu Chartier66f19252012-09-18 08:57:04 -07001958 AbstractMethod* m = GetMethod();
Ian Rogers0399dde2012-06-06 17:09:28 -07001959 uint16_t reg = DemangleSlot(slot_, m);
1960
1961 switch (tag_) {
1962 case JDWP::JT_BOOLEAN:
1963 case JDWP::JT_BYTE:
1964 CHECK_EQ(width_, 1U);
Ian Rogers2bcb4a42012-11-08 10:39:18 -08001965 SetVReg(m, reg, static_cast<uint32_t>(value_), kIntVReg);
Ian Rogers0399dde2012-06-06 17:09:28 -07001966 break;
1967 case JDWP::JT_SHORT:
1968 case JDWP::JT_CHAR:
1969 CHECK_EQ(width_, 2U);
Ian Rogers2bcb4a42012-11-08 10:39:18 -08001970 SetVReg(m, reg, static_cast<uint32_t>(value_), kIntVReg);
Ian Rogers0399dde2012-06-06 17:09:28 -07001971 break;
1972 case JDWP::JT_INT:
Ian Rogers2bcb4a42012-11-08 10:39:18 -08001973 CHECK_EQ(width_, 4U);
1974 SetVReg(m, reg, static_cast<uint32_t>(value_), kIntVReg);
1975 break;
Ian Rogers0399dde2012-06-06 17:09:28 -07001976 case JDWP::JT_FLOAT:
1977 CHECK_EQ(width_, 4U);
Ian Rogers2bcb4a42012-11-08 10:39:18 -08001978 SetVReg(m, reg, static_cast<uint32_t>(value_), kFloatVReg);
Ian Rogers0399dde2012-06-06 17:09:28 -07001979 break;
1980 case JDWP::JT_ARRAY:
1981 case JDWP::JT_OBJECT:
1982 case JDWP::JT_STRING:
1983 {
1984 CHECK_EQ(width_, sizeof(JDWP::ObjectId));
1985 Object* o = gRegistry->Get<Object*>(static_cast<JDWP::ObjectId>(value_));
1986 if (o == kInvalidObject) {
1987 UNIMPLEMENTED(FATAL) << "return an error code when given an invalid object to store";
1988 }
Ian Rogers2bcb4a42012-11-08 10:39:18 -08001989 SetVReg(m, reg, static_cast<uint32_t>(reinterpret_cast<uintptr_t>(o)), kReferenceVReg);
Ian Rogers0399dde2012-06-06 17:09:28 -07001990 }
1991 break;
1992 case JDWP::JT_DOUBLE:
Ian Rogers2bcb4a42012-11-08 10:39:18 -08001993 CHECK_EQ(width_, 8U);
1994 SetVReg(m, reg, static_cast<uint32_t>(value_), kDoubleLoVReg);
1995 SetVReg(m, reg + 1, static_cast<uint32_t>(value_ >> 32), kDoubleHiVReg);
1996 break;
Ian Rogers0399dde2012-06-06 17:09:28 -07001997 case JDWP::JT_LONG:
1998 CHECK_EQ(width_, 8U);
Ian Rogers2bcb4a42012-11-08 10:39:18 -08001999 SetVReg(m, reg, static_cast<uint32_t>(value_), kLongLoVReg);
2000 SetVReg(m, reg + 1, static_cast<uint32_t>(value_ >> 32), kLongHiVReg);
Ian Rogers0399dde2012-06-06 17:09:28 -07002001 break;
2002 default:
2003 LOG(FATAL) << "Unknown tag " << tag_;
2004 break;
2005 }
2006 return false;
2007 }
2008
2009 const JDWP::FrameId frame_id_;
2010 const int slot_;
2011 const JDWP::JdwpTag tag_;
2012 const uint64_t value_;
2013 const size_t width_;
2014 };
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002015
2016 ScopedObjectAccessUnchecked soa(Thread::Current());
jeffhaoa77f0f62012-12-05 17:19:31 -08002017 MutexLock mu(soa.Self(), *Locks::thread_list_lock_);
Elliott Hughes221229c2013-01-08 18:17:50 -08002018 Thread* thread;
2019 JDWP::JdwpError error = DecodeThread(soa, thread_id, thread);
2020 if (error != JDWP::ERR_NONE) {
2021 return;
2022 }
Elliott Hughes08fc03a2012-06-26 17:34:00 -07002023 UniquePtr<Context> context(Context::Create());
jeffhao725a9572012-11-13 18:20:12 -08002024 SetLocalVisitor visitor(thread->GetManagedStack(), thread->GetInstrumentationStack(), context.get(),
Elliott Hughes88d63092013-01-09 09:55:54 -08002025 frame_id, slot, tag, value, width);
Ian Rogers0399dde2012-06-06 17:09:28 -07002026 visitor.WalkStack();
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002027}
2028
Mathieu Chartier66f19252012-09-18 08:57:04 -07002029void Dbg::PostLocationEvent(const AbstractMethod* m, int dex_pc, Object* this_object, int event_flags) {
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08002030 Class* c = m->GetDeclaringClass();
2031
2032 JDWP::JdwpLocation location;
Elliott Hughes74847412012-06-20 18:10:21 -07002033 location.type_tag = c->IsInterface() ? JDWP::TT_INTERFACE : JDWP::TT_CLASS;
2034 location.class_id = gRegistry->Add(c);
2035 location.method_id = ToMethodId(m);
Elliott Hughes972a47b2012-02-21 18:16:06 -08002036 location.dex_pc = m->IsNative() ? -1 : dex_pc;
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08002037
2038 // Note we use "NoReg" so we don't keep track of references that are
2039 // never actually sent to the debugger. 'this_id' is only used to
2040 // compare against registered events...
2041 JDWP::ObjectId this_id = static_cast<JDWP::ObjectId>(reinterpret_cast<uintptr_t>(this_object));
2042 if (gJdwpState->PostLocationEvent(&location, this_id, event_flags)) {
2043 // ...unless there's a registered event, in which case we
2044 // need to really track the class and 'this'.
2045 gRegistry->Add(c);
2046 gRegistry->Add(this_object);
2047 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002048}
2049
Elliott Hughescaf76542012-06-28 16:08:22 -07002050void Dbg::PostException(Thread* thread,
Mathieu Chartier66f19252012-09-18 08:57:04 -07002051 JDWP::FrameId throw_frame_id, AbstractMethod* throw_method, uint32_t throw_dex_pc,
2052 AbstractMethod* catch_method, uint32_t catch_dex_pc, Throwable* exception) {
Elliott Hughesc0f09332012-03-26 13:27:06 -07002053 if (!IsDebuggerActive()) {
Ian Rogers0ad5bb82011-12-07 10:16:32 -08002054 return;
2055 }
Elliott Hughes4740cdf2011-12-07 14:07:12 -08002056
Elliott Hughesd07986f2011-12-06 18:27:45 -08002057 JDWP::JdwpLocation throw_location;
Elliott Hughescaf76542012-06-28 16:08:22 -07002058 SetLocation(throw_location, throw_method, throw_dex_pc);
Elliott Hughesd07986f2011-12-06 18:27:45 -08002059 JDWP::JdwpLocation catch_location;
Elliott Hughescaf76542012-06-28 16:08:22 -07002060 SetLocation(catch_location, catch_method, catch_dex_pc);
Elliott Hughesd07986f2011-12-06 18:27:45 -08002061
2062 // We need 'this' for InstanceOnly filters.
Elliott Hughescaf76542012-06-28 16:08:22 -07002063 UniquePtr<Context> context(Context::Create());
jeffhao725a9572012-11-13 18:20:12 -08002064 GetThisVisitor visitor(thread->GetManagedStack(), thread->GetInstrumentationStack(), context.get(), throw_frame_id);
Elliott Hughescaf76542012-06-28 16:08:22 -07002065 visitor.WalkStack();
2066 JDWP::ObjectId this_id = gRegistry->Add(visitor.this_object);
Elliott Hughesd07986f2011-12-06 18:27:45 -08002067
2068 /*
2069 * Hand the event to the JDWP exception handler. Note we're using the
2070 * "NoReg" objectID on the exception, which is not strictly correct --
2071 * the exception object WILL be passed up to the debugger if the
2072 * debugger is interested in the event. We do this because the current
2073 * implementation of the debugger object registry never throws anything
2074 * away, and some people were experiencing a fatal build up of exception
2075 * objects when dealing with certain libraries.
2076 */
2077 JDWP::ObjectId exception_id = static_cast<JDWP::ObjectId>(reinterpret_cast<uintptr_t>(exception));
2078 JDWP::RefTypeId exception_class_id = gRegistry->Add(exception->GetClass());
2079
2080 gJdwpState->PostException(&throw_location, exception_id, exception_class_id, &catch_location, this_id);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002081}
2082
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002083void Dbg::PostClassPrepare(Class* c) {
Elliott Hughesc0f09332012-03-26 13:27:06 -07002084 if (!IsDebuggerActive()) {
Elliott Hughes4740cdf2011-12-07 14:07:12 -08002085 return;
2086 }
2087
Elliott Hughes3d30d9b2011-12-07 17:35:48 -08002088 // OLD-TODO - we currently always send both "verified" and "prepared" since
Elliott Hughes4740cdf2011-12-07 14:07:12 -08002089 // debuggers seem to like that. There might be some advantage to honesty,
2090 // since the class may not yet be verified.
2091 int state = JDWP::CS_VERIFIED | JDWP::CS_PREPARED;
2092 JDWP::JdwpTypeTag tag = c->IsInterface() ? JDWP::TT_INTERFACE : JDWP::TT_CLASS;
2093 gJdwpState->PostClassPrepare(tag, gRegistry->Add(c), ClassHelper(c).GetDescriptor(), state);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002094}
2095
Elliott Hughescaf76542012-06-28 16:08:22 -07002096void Dbg::UpdateDebugger(int32_t dex_pc, Thread* self) {
Elliott Hughesc0f09332012-03-26 13:27:06 -07002097 if (!IsDebuggerActive() || dex_pc == -2 /* fake method exit */) {
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08002098 return;
2099 }
2100
Elliott Hughescaf76542012-06-28 16:08:22 -07002101 size_t frame_id;
Mathieu Chartier66f19252012-09-18 08:57:04 -07002102 AbstractMethod* m = self->GetCurrentMethod(NULL, &frame_id);
Elliott Hughescaf76542012-06-28 16:08:22 -07002103 //LOG(INFO) << "UpdateDebugger " << PrettyMethod(m) << "@" << dex_pc << " frame " << frame_id;
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08002104
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08002105 if (dex_pc == -1) {
Elliott Hughes2aa2e392012-02-17 17:15:43 -08002106 // We use a pc of -1 to represent method entry, since we might branch back to pc 0 later.
2107 // This means that for this special notification, there can't be anything else interesting
2108 // going on, so we're done already.
Elliott Hughescaf76542012-06-28 16:08:22 -07002109 Dbg::PostLocationEvent(m, 0, GetThis(self, m, frame_id), kMethodEntry);
Elliott Hughes2aa2e392012-02-17 17:15:43 -08002110 return;
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08002111 }
2112
Elliott Hughes2aa2e392012-02-17 17:15:43 -08002113 int event_flags = 0;
2114
Elliott Hughes86964332012-02-15 19:37:42 -08002115 if (IsBreakpoint(m, dex_pc)) {
2116 event_flags |= kBreakpoint;
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08002117 }
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08002118
jeffhao09bfc6a2012-12-11 18:11:43 -08002119 {
2120 // If the debugger is single-stepping one of our threads, check to
2121 // see if we're that thread and we've reached a step point.
2122 MutexLock mu(Thread::Current(), *Locks::breakpoint_lock_);
2123 if (gSingleStepControl.is_active && gSingleStepControl.thread == self) {
2124 CHECK(!m->IsNative());
2125 if (gSingleStepControl.step_depth == JDWP::SD_INTO) {
2126 // Step into method calls. We break when the line number
2127 // or method pointer changes. If we're in SS_MIN mode, we
2128 // always stop.
2129 if (gSingleStepControl.method != m) {
2130 event_flags |= kSingleStep;
2131 VLOG(jdwp) << "SS new method";
2132 } else if (gSingleStepControl.step_size == JDWP::SS_MIN) {
Elliott Hughes86964332012-02-15 19:37:42 -08002133 event_flags |= kSingleStep;
2134 VLOG(jdwp) << "SS new instruction";
Elliott Hughes2435a572012-02-17 16:07:41 -08002135 } else if (gSingleStepControl.dex_pcs.find(dex_pc) == gSingleStepControl.dex_pcs.end()) {
2136 event_flags |= kSingleStep;
2137 VLOG(jdwp) << "SS new line";
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08002138 }
jeffhao09bfc6a2012-12-11 18:11:43 -08002139 } else if (gSingleStepControl.step_depth == JDWP::SD_OVER) {
2140 // Step over method calls. We break when the line number is
2141 // different and the frame depth is <= the original frame
2142 // depth. (We can't just compare on the method, because we
2143 // might get unrolled past it by an exception, and it's tricky
2144 // to identify recursion.)
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08002145
jeffhao09bfc6a2012-12-11 18:11:43 -08002146 int stack_depth = GetStackDepth(self);
Elliott Hughes86964332012-02-15 19:37:42 -08002147
jeffhao09bfc6a2012-12-11 18:11:43 -08002148 if (stack_depth < gSingleStepControl.stack_depth) {
2149 // popped up one or more frames, always trigger
2150 event_flags |= kSingleStep;
2151 VLOG(jdwp) << "SS method pop";
2152 } else if (stack_depth == gSingleStepControl.stack_depth) {
2153 // same depth, see if we moved
2154 if (gSingleStepControl.step_size == JDWP::SS_MIN) {
2155 event_flags |= kSingleStep;
2156 VLOG(jdwp) << "SS new instruction";
2157 } else if (gSingleStepControl.dex_pcs.find(dex_pc) == gSingleStepControl.dex_pcs.end()) {
2158 event_flags |= kSingleStep;
2159 VLOG(jdwp) << "SS new line";
2160 }
2161 }
2162 } else {
2163 CHECK_EQ(gSingleStepControl.step_depth, JDWP::SD_OUT);
2164 // Return from the current method. We break when the frame
2165 // depth pops up.
2166
2167 // This differs from the "method exit" break in that it stops
2168 // with the PC at the next instruction in the returned-to
2169 // function, rather than the end of the returning function.
2170
2171 int stack_depth = GetStackDepth(self);
2172 if (stack_depth < gSingleStepControl.stack_depth) {
2173 event_flags |= kSingleStep;
2174 VLOG(jdwp) << "SS method pop";
2175 }
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08002176 }
2177 }
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08002178 }
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08002179
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08002180 // Check to see if this is a "return" instruction. JDWP says we should
2181 // send the event *after* the code has been executed, but it also says
2182 // the location we provide is the last instruction. Since the "return"
2183 // instruction has no interesting side effects, we should be safe.
2184 // (We can't just move this down to the returnFromMethod label because
2185 // we potentially need to combine it with other events.)
2186 // We're also not supposed to generate a method exit event if the method
2187 // terminates "with a thrown exception".
Elliott Hughes86964332012-02-15 19:37:42 -08002188 if (dex_pc >= 0) {
2189 const DexFile::CodeItem* code_item = MethodHelper(m).GetCodeItem();
Elliott Hughescaf76542012-06-28 16:08:22 -07002190 CHECK(code_item != NULL) << PrettyMethod(m) << " @" << dex_pc;
Elliott Hughes86964332012-02-15 19:37:42 -08002191 CHECK_LT(dex_pc, static_cast<int32_t>(code_item->insns_size_in_code_units_));
2192 if (Instruction::At(&code_item->insns_[dex_pc])->IsReturn()) {
2193 event_flags |= kMethodExit;
2194 }
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08002195 }
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08002196
2197 // If there's something interesting going on, see if it matches one
2198 // of the debugger filters.
2199 if (event_flags != 0) {
Elliott Hughescaf76542012-06-28 16:08:22 -07002200 Dbg::PostLocationEvent(m, dex_pc, GetThis(self, m, frame_id), event_flags);
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08002201 }
2202}
2203
Elliott Hughes86964332012-02-15 19:37:42 -08002204void Dbg::WatchLocation(const JDWP::JdwpLocation* location) {
jeffhao09bfc6a2012-12-11 18:11:43 -08002205 MutexLock mu(Thread::Current(), *Locks::breakpoint_lock_);
Mathieu Chartier66f19252012-09-18 08:57:04 -07002206 AbstractMethod* m = FromMethodId(location->method_id);
Elliott Hughes972a47b2012-02-21 18:16:06 -08002207 gBreakpoints.push_back(Breakpoint(m, location->dex_pc));
Elliott Hughes86964332012-02-15 19:37:42 -08002208 VLOG(jdwp) << "Set breakpoint #" << (gBreakpoints.size() - 1) << ": " << gBreakpoints[gBreakpoints.size() - 1];
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002209}
2210
Elliott Hughes86964332012-02-15 19:37:42 -08002211void Dbg::UnwatchLocation(const JDWP::JdwpLocation* location) {
jeffhao09bfc6a2012-12-11 18:11:43 -08002212 MutexLock mu(Thread::Current(), *Locks::breakpoint_lock_);
Mathieu Chartier66f19252012-09-18 08:57:04 -07002213 AbstractMethod* m = FromMethodId(location->method_id);
Elliott Hughes86964332012-02-15 19:37:42 -08002214 for (size_t i = 0; i < gBreakpoints.size(); ++i) {
Elliott Hughes972a47b2012-02-21 18:16:06 -08002215 if (gBreakpoints[i].method == m && gBreakpoints[i].dex_pc == location->dex_pc) {
Elliott Hughes86964332012-02-15 19:37:42 -08002216 VLOG(jdwp) << "Removed breakpoint #" << i << ": " << gBreakpoints[i];
2217 gBreakpoints.erase(gBreakpoints.begin() + i);
2218 return;
2219 }
2220 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002221}
2222
Elliott Hughes221229c2013-01-08 18:17:50 -08002223JDWP::JdwpError Dbg::ConfigureStep(JDWP::ObjectId thread_id, JDWP::JdwpStepSize step_size,
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002224 JDWP::JdwpStepDepth step_depth) {
2225 ScopedObjectAccessUnchecked soa(Thread::Current());
jeffhaoa77f0f62012-12-05 17:19:31 -08002226 MutexLock mu(soa.Self(), *Locks::thread_list_lock_);
Elliott Hughes221229c2013-01-08 18:17:50 -08002227 Thread* thread;
2228 JDWP::JdwpError error = DecodeThread(soa, thread_id, thread);
2229 if (error != JDWP::ERR_NONE) {
2230 return error;
Elliott Hughes2435a572012-02-17 16:07:41 -08002231 }
Elliott Hughes86964332012-02-15 19:37:42 -08002232
jeffhao09bfc6a2012-12-11 18:11:43 -08002233 MutexLock mu2(soa.Self(), *Locks::breakpoint_lock_);
Elliott Hughes86964332012-02-15 19:37:42 -08002234 // TODO: there's no theoretical reason why we couldn't support single-stepping
2235 // of multiple threads at once, but we never did so historically.
2236 if (gSingleStepControl.thread != NULL && thread != gSingleStepControl.thread) {
2237 LOG(WARNING) << "single-step already active for " << *gSingleStepControl.thread
2238 << "; switching to " << *thread;
2239 }
2240
Elliott Hughes2435a572012-02-17 16:07:41 -08002241 //
2242 // Work out what Method* we're in, the current line number, and how deep the stack currently
2243 // is for step-out.
2244 //
2245
Ian Rogers0399dde2012-06-06 17:09:28 -07002246 struct SingleStepStackVisitor : public StackVisitor {
2247 SingleStepStackVisitor(const ManagedStack* stack,
Ian Rogers306057f2012-11-26 12:45:53 -08002248 const std::deque<InstrumentationStackFrame>* instrumentation_stack)
jeffhao09bfc6a2012-12-11 18:11:43 -08002249 EXCLUSIVE_LOCKS_REQUIRED(Locks::breakpoint_lock_)
Ian Rogersb726dcb2012-09-05 08:57:23 -07002250 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_)
jeffhao725a9572012-11-13 18:20:12 -08002251 : StackVisitor(stack, instrumentation_stack, NULL) {
Elliott Hughes86964332012-02-15 19:37:42 -08002252 gSingleStepControl.method = NULL;
2253 gSingleStepControl.stack_depth = 0;
2254 }
Ian Rogersca190662012-06-26 15:45:57 -07002255
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002256 // TODO: Enable annotalysis. We know lock is held in constructor, but abstraction confuses
2257 // annotalysis.
2258 bool VisitFrame() NO_THREAD_SAFETY_ANALYSIS {
jeffhao09bfc6a2012-12-11 18:11:43 -08002259 Locks::breakpoint_lock_->AssertHeld(Thread::Current());
Mathieu Chartier66f19252012-09-18 08:57:04 -07002260 const AbstractMethod* m = GetMethod();
Ian Rogers0399dde2012-06-06 17:09:28 -07002261 if (!m->IsRuntimeMethod()) {
Elliott Hughes86964332012-02-15 19:37:42 -08002262 ++gSingleStepControl.stack_depth;
2263 if (gSingleStepControl.method == NULL) {
Elliott Hughes2435a572012-02-17 16:07:41 -08002264 const DexCache* dex_cache = m->GetDeclaringClass()->GetDexCache();
2265 gSingleStepControl.method = m;
2266 gSingleStepControl.line_number = -1;
2267 if (dex_cache != NULL) {
Ian Rogers4445a7e2012-10-05 17:19:13 -07002268 const DexFile& dex_file = *dex_cache->GetDexFile();
Ian Rogers0399dde2012-06-06 17:09:28 -07002269 gSingleStepControl.line_number = dex_file.GetLineNumFromPC(m, GetDexPc());
Elliott Hughes2435a572012-02-17 16:07:41 -08002270 }
Elliott Hughes86964332012-02-15 19:37:42 -08002271 }
2272 }
Elliott Hughes530fa002012-03-12 11:44:49 -07002273 return true;
Elliott Hughes86964332012-02-15 19:37:42 -08002274 }
2275 };
jeffhao725a9572012-11-13 18:20:12 -08002276 SingleStepStackVisitor visitor(thread->GetManagedStack(), thread->GetInstrumentationStack());
Ian Rogers0399dde2012-06-06 17:09:28 -07002277 visitor.WalkStack();
Elliott Hughes86964332012-02-15 19:37:42 -08002278
Elliott Hughes2435a572012-02-17 16:07:41 -08002279 //
2280 // Find the dex_pc values that correspond to the current line, for line-based single-stepping.
2281 //
2282
2283 struct DebugCallbackContext {
jeffhao09bfc6a2012-12-11 18:11:43 -08002284 DebugCallbackContext() EXCLUSIVE_LOCKS_REQUIRED(Locks::breakpoint_lock_) {
Elliott Hughes2435a572012-02-17 16:07:41 -08002285 last_pc_valid = false;
2286 last_pc = 0;
Elliott Hughes2435a572012-02-17 16:07:41 -08002287 }
2288
jeffhao09bfc6a2012-12-11 18:11:43 -08002289 // TODO: Enable annotalysis. We know lock is held in constructor, but abstraction confuses
2290 // annotalysis.
2291 static bool Callback(void* raw_context, uint32_t address, uint32_t line_number) NO_THREAD_SAFETY_ANALYSIS {
2292 Locks::breakpoint_lock_->AssertHeld(Thread::Current());
Elliott Hughes2435a572012-02-17 16:07:41 -08002293 DebugCallbackContext* context = reinterpret_cast<DebugCallbackContext*>(raw_context);
2294 if (static_cast<int32_t>(line_number) == gSingleStepControl.line_number) {
2295 if (!context->last_pc_valid) {
2296 // Everything from this address until the next line change is ours.
2297 context->last_pc = address;
2298 context->last_pc_valid = true;
2299 }
2300 // Otherwise, if we're already in a valid range for this line,
2301 // just keep going (shouldn't really happen)...
2302 } else if (context->last_pc_valid) { // and the line number is new
2303 // Add everything from the last entry up until here to the set
2304 for (uint32_t dex_pc = context->last_pc; dex_pc < address; ++dex_pc) {
2305 gSingleStepControl.dex_pcs.insert(dex_pc);
2306 }
2307 context->last_pc_valid = false;
2308 }
2309 return false; // There may be multiple entries for any given line.
2310 }
2311
jeffhao09bfc6a2012-12-11 18:11:43 -08002312 // TODO: Enable annotalysis. We know lock is held in constructor, but abstraction confuses
2313 // annotalysis.
2314 ~DebugCallbackContext() NO_THREAD_SAFETY_ANALYSIS {
2315 Locks::breakpoint_lock_->AssertHeld(Thread::Current());
Elliott Hughes2435a572012-02-17 16:07:41 -08002316 // If the line number was the last in the position table...
2317 if (last_pc_valid) {
2318 size_t end = MethodHelper(gSingleStepControl.method).GetCodeItem()->insns_size_in_code_units_;
2319 for (uint32_t dex_pc = last_pc; dex_pc < end; ++dex_pc) {
2320 gSingleStepControl.dex_pcs.insert(dex_pc);
2321 }
2322 }
2323 }
2324
2325 bool last_pc_valid;
2326 uint32_t last_pc;
2327 };
Elliott Hughes3e2e1a22012-02-21 11:33:41 -08002328 gSingleStepControl.dex_pcs.clear();
Mathieu Chartier66f19252012-09-18 08:57:04 -07002329 const AbstractMethod* m = gSingleStepControl.method;
Elliott Hughes3e2e1a22012-02-21 11:33:41 -08002330 if (m->IsNative()) {
2331 gSingleStepControl.line_number = -1;
2332 } else {
2333 DebugCallbackContext context;
2334 MethodHelper mh(m);
2335 mh.GetDexFile().DecodeDebugInfo(mh.GetCodeItem(), m->IsStatic(), m->GetDexMethodIndex(),
2336 DebugCallbackContext::Callback, NULL, &context);
2337 }
Elliott Hughes2435a572012-02-17 16:07:41 -08002338
2339 //
2340 // Everything else...
2341 //
2342
Elliott Hughes86964332012-02-15 19:37:42 -08002343 gSingleStepControl.thread = thread;
2344 gSingleStepControl.step_size = step_size;
2345 gSingleStepControl.step_depth = step_depth;
2346 gSingleStepControl.is_active = true;
2347
Elliott Hughes2435a572012-02-17 16:07:41 -08002348 if (VLOG_IS_ON(jdwp)) {
2349 VLOG(jdwp) << "Single-step thread: " << *gSingleStepControl.thread;
2350 VLOG(jdwp) << "Single-step step size: " << gSingleStepControl.step_size;
2351 VLOG(jdwp) << "Single-step step depth: " << gSingleStepControl.step_depth;
2352 VLOG(jdwp) << "Single-step current method: " << PrettyMethod(gSingleStepControl.method);
2353 VLOG(jdwp) << "Single-step current line: " << gSingleStepControl.line_number;
2354 VLOG(jdwp) << "Single-step current stack depth: " << gSingleStepControl.stack_depth;
2355 VLOG(jdwp) << "Single-step dex_pc values:";
2356 for (std::set<uint32_t>::iterator it = gSingleStepControl.dex_pcs.begin() ; it != gSingleStepControl.dex_pcs.end(); ++it) {
Elliott Hughes229feb72012-02-23 13:33:29 -08002357 VLOG(jdwp) << StringPrintf(" %#x", *it);
Elliott Hughes2435a572012-02-17 16:07:41 -08002358 }
2359 }
2360
2361 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002362}
2363
Elliott Hughes221229c2013-01-08 18:17:50 -08002364void Dbg::UnconfigureStep(JDWP::ObjectId /*thread_id*/) {
jeffhao09bfc6a2012-12-11 18:11:43 -08002365 MutexLock mu(Thread::Current(), *Locks::breakpoint_lock_);
Elliott Hughesf8349362012-06-18 15:00:06 -07002366
Elliott Hughes86964332012-02-15 19:37:42 -08002367 gSingleStepControl.is_active = false;
2368 gSingleStepControl.thread = NULL;
Elliott Hughes2435a572012-02-17 16:07:41 -08002369 gSingleStepControl.dex_pcs.clear();
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002370}
2371
Elliott Hughes45651fd2012-02-21 15:48:20 -08002372static char JdwpTagToShortyChar(JDWP::JdwpTag tag) {
2373 switch (tag) {
2374 default:
2375 LOG(FATAL) << "unknown JDWP tag: " << PrintableChar(tag);
2376
2377 // Primitives.
2378 case JDWP::JT_BYTE: return 'B';
2379 case JDWP::JT_CHAR: return 'C';
2380 case JDWP::JT_FLOAT: return 'F';
2381 case JDWP::JT_DOUBLE: return 'D';
2382 case JDWP::JT_INT: return 'I';
2383 case JDWP::JT_LONG: return 'J';
2384 case JDWP::JT_SHORT: return 'S';
2385 case JDWP::JT_VOID: return 'V';
2386 case JDWP::JT_BOOLEAN: return 'Z';
2387
2388 // Reference types.
2389 case JDWP::JT_ARRAY:
2390 case JDWP::JT_OBJECT:
2391 case JDWP::JT_STRING:
2392 case JDWP::JT_THREAD:
2393 case JDWP::JT_THREAD_GROUP:
2394 case JDWP::JT_CLASS_LOADER:
2395 case JDWP::JT_CLASS_OBJECT:
2396 return 'L';
2397 }
2398}
2399
Elliott Hughes88d63092013-01-09 09:55:54 -08002400JDWP::JdwpError Dbg::InvokeMethod(JDWP::ObjectId thread_id, JDWP::ObjectId object_id,
2401 JDWP::RefTypeId class_id, JDWP::MethodId method_id,
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002402 uint32_t arg_count, uint64_t* arg_values,
2403 JDWP::JdwpTag* arg_types, uint32_t options,
2404 JDWP::JdwpTag* pResultTag, uint64_t* pResultValue,
2405 JDWP::ObjectId* pExceptionId) {
Elliott Hughesd07986f2011-12-06 18:27:45 -08002406 ThreadList* thread_list = Runtime::Current()->GetThreadList();
2407
2408 Thread* targetThread = NULL;
2409 DebugInvokeReq* req = NULL;
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002410 Thread* self = Thread::Current();
Elliott Hughesd07986f2011-12-06 18:27:45 -08002411 {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002412 ScopedObjectAccessUnchecked soa(self);
Ian Rogers50b35e22012-10-04 10:09:15 -07002413 MutexLock mu(soa.Self(), *Locks::thread_list_lock_);
Elliott Hughes221229c2013-01-08 18:17:50 -08002414 JDWP::JdwpError error = DecodeThread(soa, thread_id, targetThread);
2415 if (error != JDWP::ERR_NONE) {
2416 LOG(ERROR) << "InvokeMethod request for invalid thread id " << thread_id;
2417 return error;
Elliott Hughesd07986f2011-12-06 18:27:45 -08002418 }
2419 req = targetThread->GetInvokeReq();
2420 if (!req->ready) {
2421 LOG(ERROR) << "InvokeMethod request for thread not stopped by event: " << *targetThread;
2422 return JDWP::ERR_INVALID_THREAD;
2423 }
2424
2425 /*
2426 * We currently have a bug where we don't successfully resume the
2427 * target thread if the suspend count is too deep. We're expected to
2428 * require one "resume" for each "suspend", but when asked to execute
2429 * a method we have to resume fully and then re-suspend it back to the
2430 * same level. (The easiest way to cause this is to type "suspend"
2431 * multiple times in jdb.)
2432 *
2433 * It's unclear what this means when the event specifies "resume all"
2434 * and some threads are suspended more deeply than others. This is
2435 * a rare problem, so for now we just prevent it from hanging forever
2436 * by rejecting the method invocation request. Without this, we will
2437 * be stuck waiting on a suspended thread.
2438 */
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002439 int suspend_count;
2440 {
Ian Rogers50b35e22012-10-04 10:09:15 -07002441 MutexLock mu2(soa.Self(), *Locks::thread_suspend_count_lock_);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002442 suspend_count = targetThread->GetSuspendCount();
2443 }
Elliott Hughesd07986f2011-12-06 18:27:45 -08002444 if (suspend_count > 1) {
2445 LOG(ERROR) << *targetThread << " suspend count too deep for method invocation: " << suspend_count;
2446 return JDWP::ERR_THREAD_SUSPENDED; // Probably not expected here.
2447 }
2448
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08002449 JDWP::JdwpError status;
Elliott Hughes88d63092013-01-09 09:55:54 -08002450 Object* receiver = gRegistry->Get<Object*>(object_id);
Elliott Hughes45651fd2012-02-21 15:48:20 -08002451 if (receiver == kInvalidObject) {
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08002452 return JDWP::ERR_INVALID_OBJECT;
2453 }
Elliott Hughes45651fd2012-02-21 15:48:20 -08002454
Elliott Hughes221229c2013-01-08 18:17:50 -08002455 Object* thread = gRegistry->Get<Object*>(thread_id);
Elliott Hughes45651fd2012-02-21 15:48:20 -08002456 if (thread == kInvalidObject) {
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08002457 return JDWP::ERR_INVALID_OBJECT;
2458 }
Elliott Hughes45651fd2012-02-21 15:48:20 -08002459 // TODO: check that 'thread' is actually a java.lang.Thread!
2460
Elliott Hughes88d63092013-01-09 09:55:54 -08002461 Class* c = DecodeClass(class_id, status);
Elliott Hughes45651fd2012-02-21 15:48:20 -08002462 if (c == NULL) {
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08002463 return status;
2464 }
Elliott Hughes45651fd2012-02-21 15:48:20 -08002465
Elliott Hughes88d63092013-01-09 09:55:54 -08002466 AbstractMethod* m = FromMethodId(method_id);
Elliott Hughes45651fd2012-02-21 15:48:20 -08002467 if (m->IsStatic() != (receiver == NULL)) {
2468 return JDWP::ERR_INVALID_METHODID;
2469 }
2470 if (m->IsStatic()) {
2471 if (m->GetDeclaringClass() != c) {
2472 return JDWP::ERR_INVALID_METHODID;
2473 }
2474 } else {
2475 if (!m->GetDeclaringClass()->IsAssignableFrom(c)) {
2476 return JDWP::ERR_INVALID_METHODID;
2477 }
2478 }
2479
2480 // Check the argument list matches the method.
2481 MethodHelper mh(m);
2482 if (mh.GetShortyLength() - 1 != arg_count) {
2483 return JDWP::ERR_ILLEGAL_ARGUMENT;
2484 }
2485 const char* shorty = mh.GetShorty();
2486 for (size_t i = 0; i < arg_count; ++i) {
2487 if (shorty[i + 1] != JdwpTagToShortyChar(arg_types[i])) {
2488 return JDWP::ERR_ILLEGAL_ARGUMENT;
2489 }
2490 }
2491
2492 req->receiver_ = receiver;
2493 req->thread_ = thread;
2494 req->class_ = c;
2495 req->method_ = m;
2496 req->arg_count_ = arg_count;
2497 req->arg_values_ = arg_values;
Elliott Hughesd07986f2011-12-06 18:27:45 -08002498 req->options_ = options;
2499 req->invoke_needed_ = true;
2500 }
2501
2502 // The fact that we've released the thread list lock is a bit risky --- if the thread goes
2503 // away we're sitting high and dry -- but we must release this before the ResumeAllThreads
2504 // call, and it's unwise to hold it during WaitForSuspend.
2505
2506 {
2507 /*
2508 * We change our (JDWP thread) status, which should be THREAD_RUNNING,
Elliott Hughes81ff3182012-03-23 20:35:56 -07002509 * so we can suspend for a GC if the invoke request causes us to
Elliott Hughesd07986f2011-12-06 18:27:45 -08002510 * run out of memory. It's also a good idea to change it before locking
2511 * the invokeReq mutex, although that should never be held for long.
2512 */
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002513 self->TransitionFromRunnableToSuspended(kWaitingForDebuggerSend);
Elliott Hughesd07986f2011-12-06 18:27:45 -08002514
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08002515 VLOG(jdwp) << " Transferring control to event thread";
Elliott Hughesd07986f2011-12-06 18:27:45 -08002516 {
Ian Rogers50b35e22012-10-04 10:09:15 -07002517 MutexLock mu(self, req->lock_);
Elliott Hughesd07986f2011-12-06 18:27:45 -08002518
2519 if ((options & JDWP::INVOKE_SINGLE_THREADED) == 0) {
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08002520 VLOG(jdwp) << " Resuming all threads";
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002521 thread_list->UndoDebuggerSuspensions();
Elliott Hughesd07986f2011-12-06 18:27:45 -08002522 } else {
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08002523 VLOG(jdwp) << " Resuming event thread only";
Elliott Hughesd07986f2011-12-06 18:27:45 -08002524 thread_list->Resume(targetThread, true);
2525 }
2526
2527 // Wait for the request to finish executing.
2528 while (req->invoke_needed_) {
Ian Rogersc604d732012-10-14 16:09:54 -07002529 req->cond_.Wait(self);
Elliott Hughesd07986f2011-12-06 18:27:45 -08002530 }
2531 }
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08002532 VLOG(jdwp) << " Control has returned from event thread";
Elliott Hughesd07986f2011-12-06 18:27:45 -08002533
2534 /* wait for thread to re-suspend itself */
Elliott Hughes221229c2013-01-08 18:17:50 -08002535 SuspendThread(thread_id, false /* request_suspension */ );
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002536 self->TransitionFromSuspendedToRunnable();
Elliott Hughesd07986f2011-12-06 18:27:45 -08002537 }
2538
2539 /*
2540 * Suspend the threads. We waited for the target thread to suspend
2541 * itself, so all we need to do is suspend the others.
2542 *
2543 * The suspendAllThreads() call will double-suspend the event thread,
2544 * so we want to resume the target thread once to keep the books straight.
2545 */
2546 if ((options & JDWP::INVOKE_SINGLE_THREADED) == 0) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002547 self->TransitionFromRunnableToSuspended(kWaitingForDebuggerSuspension);
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08002548 VLOG(jdwp) << " Suspending all threads";
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002549 thread_list->SuspendAllForDebugger();
2550 self->TransitionFromSuspendedToRunnable();
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08002551 VLOG(jdwp) << " Resuming event thread to balance the count";
Elliott Hughesd07986f2011-12-06 18:27:45 -08002552 thread_list->Resume(targetThread, true);
2553 }
2554
2555 // Copy the result.
2556 *pResultTag = req->result_tag;
2557 if (IsPrimitiveTag(req->result_tag)) {
Elliott Hughesf24d3ce2012-04-11 17:43:37 -07002558 *pResultValue = req->result_value.GetJ();
Elliott Hughesd07986f2011-12-06 18:27:45 -08002559 } else {
Elliott Hughesf24d3ce2012-04-11 17:43:37 -07002560 *pResultValue = gRegistry->Add(req->result_value.GetL());
Elliott Hughesd07986f2011-12-06 18:27:45 -08002561 }
2562 *pExceptionId = req->exception;
2563 return req->error;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002564}
2565
2566void Dbg::ExecuteMethod(DebugInvokeReq* pReq) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002567 ScopedObjectAccess soa(Thread::Current());
Elliott Hughesd07986f2011-12-06 18:27:45 -08002568
Elliott Hughes81ff3182012-03-23 20:35:56 -07002569 // We can be called while an exception is pending. We need
Elliott Hughesd07986f2011-12-06 18:27:45 -08002570 // to preserve that across the method invocation.
Ian Rogers1f539342012-10-03 21:09:42 -07002571 SirtRef<Throwable> old_exception(soa.Self(), soa.Self()->GetException());
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002572 soa.Self()->ClearException();
Elliott Hughesd07986f2011-12-06 18:27:45 -08002573
2574 // Translate the method through the vtable, unless the debugger wants to suppress it.
Mathieu Chartier66f19252012-09-18 08:57:04 -07002575 AbstractMethod* m = pReq->method_;
Elliott Hughesd07986f2011-12-06 18:27:45 -08002576 if ((pReq->options_ & JDWP::INVOKE_NONVIRTUAL) == 0 && pReq->receiver_ != NULL) {
Mathieu Chartier66f19252012-09-18 08:57:04 -07002577 AbstractMethod* actual_method = pReq->class_->FindVirtualMethodForVirtualOrInterface(pReq->method_);
Elliott Hughes45651fd2012-02-21 15:48:20 -08002578 if (actual_method != m) {
2579 VLOG(jdwp) << "ExecuteMethod translated " << PrettyMethod(m) << " to " << PrettyMethod(actual_method);
2580 m = actual_method;
2581 }
Elliott Hughesd07986f2011-12-06 18:27:45 -08002582 }
Elliott Hughes45651fd2012-02-21 15:48:20 -08002583 VLOG(jdwp) << "ExecuteMethod " << PrettyMethod(m);
Elliott Hughesd07986f2011-12-06 18:27:45 -08002584 CHECK(m != NULL);
2585
2586 CHECK_EQ(sizeof(jvalue), sizeof(uint64_t));
2587
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002588 LOG(INFO) << "self=" << soa.Self() << " pReq->receiver_=" << pReq->receiver_ << " m=" << m
2589 << " #" << pReq->arg_count_ << " " << pReq->arg_values_;
2590 pReq->result_value = InvokeWithJValues(soa, pReq->receiver_, m,
2591 reinterpret_cast<JValue*>(pReq->arg_values_));
Elliott Hughesd07986f2011-12-06 18:27:45 -08002592
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002593 pReq->exception = gRegistry->Add(soa.Self()->GetException());
Elliott Hughesd07986f2011-12-06 18:27:45 -08002594 pReq->result_tag = BasicTagFromDescriptor(MethodHelper(m).GetShorty());
2595 if (pReq->exception != 0) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002596 Object* exc = soa.Self()->GetException();
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08002597 VLOG(jdwp) << " JDWP invocation returning with exception=" << exc << " " << PrettyTypeOf(exc);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002598 soa.Self()->ClearException();
Elliott Hughesf24d3ce2012-04-11 17:43:37 -07002599 pReq->result_value.SetJ(0);
Elliott Hughesd07986f2011-12-06 18:27:45 -08002600 } else if (pReq->result_tag == JDWP::JT_OBJECT) {
2601 /* if no exception thrown, examine object result more closely */
Elliott Hughesf24d3ce2012-04-11 17:43:37 -07002602 JDWP::JdwpTag new_tag = TagFromObject(pReq->result_value.GetL());
Elliott Hughesd07986f2011-12-06 18:27:45 -08002603 if (new_tag != pReq->result_tag) {
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08002604 VLOG(jdwp) << " JDWP promoted result from " << pReq->result_tag << " to " << new_tag;
Elliott Hughesd07986f2011-12-06 18:27:45 -08002605 pReq->result_tag = new_tag;
2606 }
2607
2608 /*
2609 * Register the object. We don't actually need an ObjectId yet,
2610 * but we do need to be sure that the GC won't move or discard the
2611 * object when we switch out of RUNNING. The ObjectId conversion
2612 * will add the object to the "do not touch" list.
2613 *
2614 * We can't use the "tracked allocation" mechanism here because
2615 * the object is going to be handed off to a different thread.
2616 */
Elliott Hughesf24d3ce2012-04-11 17:43:37 -07002617 gRegistry->Add(pReq->result_value.GetL());
Elliott Hughesd07986f2011-12-06 18:27:45 -08002618 }
2619
2620 if (old_exception.get() != NULL) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002621 soa.Self()->SetException(old_exception.get());
Elliott Hughesd07986f2011-12-06 18:27:45 -08002622 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002623}
2624
Elliott Hughesd07986f2011-12-06 18:27:45 -08002625/*
2626 * Register an object ID that might not have been registered previously.
2627 *
2628 * Normally this wouldn't happen -- the conversion to an ObjectId would
2629 * have added the object to the registry -- but in some cases (e.g.
2630 * throwing exceptions) we really want to do the registration late.
2631 */
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002632void Dbg::RegisterObjectId(JDWP::ObjectId id) {
Elliott Hughesd07986f2011-12-06 18:27:45 -08002633 gRegistry->Add(reinterpret_cast<Object*>(id));
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002634}
2635
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07002636/*
2637 * "buf" contains a full JDWP packet, possibly with multiple chunks. We
2638 * need to process each, accumulate the replies, and ship the whole thing
2639 * back.
2640 *
2641 * Returns "true" if we have a reply. The reply buffer is newly allocated,
2642 * and includes the chunk type/length, followed by the data.
2643 *
Elliott Hughes3d30d9b2011-12-07 17:35:48 -08002644 * OLD-TODO: we currently assume that the request and reply include a single
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07002645 * chunk. If this becomes inconvenient we will need to adapt.
2646 */
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002647bool Dbg::DdmHandlePacket(const uint8_t* buf, int dataLen, uint8_t** pReplyBuf, int* pReplyLen) {
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07002648 CHECK_GE(dataLen, 0);
2649
2650 Thread* self = Thread::Current();
2651 JNIEnv* env = self->GetJniEnv();
2652
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07002653 // Create a byte[] corresponding to 'buf'.
Elliott Hughes6a5bd492011-10-28 14:33:57 -07002654 ScopedLocalRef<jbyteArray> dataArray(env, env->NewByteArray(dataLen));
2655 if (dataArray.get() == NULL) {
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07002656 LOG(WARNING) << "byte[] allocation failed: " << dataLen;
2657 env->ExceptionClear();
2658 return false;
2659 }
Elliott Hughes6a5bd492011-10-28 14:33:57 -07002660 env->SetByteArrayRegion(dataArray.get(), 0, dataLen, reinterpret_cast<const jbyte*>(buf));
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07002661
2662 const int kChunkHdrLen = 8;
2663
2664 // Run through and find all chunks. [Currently just find the first.]
Elliott Hughes6a5bd492011-10-28 14:33:57 -07002665 ScopedByteArrayRO contents(env, dataArray.get());
Elliott Hughesf7c3b662011-10-27 12:04:56 -07002666 jint type = JDWP::Get4BE(reinterpret_cast<const uint8_t*>(&contents[0]));
2667 jint length = JDWP::Get4BE(reinterpret_cast<const uint8_t*>(&contents[4]));
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07002668 jint offset = kChunkHdrLen;
2669 if (offset + length > dataLen) {
2670 LOG(WARNING) << StringPrintf("bad chunk found (len=%u pktLen=%d)", length, dataLen);
2671 return false;
2672 }
2673
2674 // Call "private static Chunk dispatch(int type, byte[] data, int offset, int length)".
Elliott Hugheseac76672012-05-24 21:56:51 -07002675 ScopedLocalRef<jobject> chunk(env, env->CallStaticObjectMethod(WellKnownClasses::org_apache_harmony_dalvik_ddmc_DdmServer,
2676 WellKnownClasses::org_apache_harmony_dalvik_ddmc_DdmServer_dispatch,
2677 type, dataArray.get(), offset, length));
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07002678 if (env->ExceptionCheck()) {
2679 LOG(INFO) << StringPrintf("Exception thrown by dispatcher for 0x%08x", type);
2680 env->ExceptionDescribe();
2681 env->ExceptionClear();
2682 return false;
2683 }
2684
Elliott Hughes6a5bd492011-10-28 14:33:57 -07002685 if (chunk.get() == NULL) {
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07002686 return false;
2687 }
2688
2689 /*
2690 * Pull the pieces out of the chunk. We copy the results into a
2691 * newly-allocated buffer that the caller can free. We don't want to
2692 * continue using the Chunk object because nothing has a reference to it.
2693 *
2694 * We could avoid this by returning type/data/offset/length and having
2695 * the caller be aware of the object lifetime issues, but that
Elliott Hughes81ff3182012-03-23 20:35:56 -07002696 * integrates the JDWP code more tightly into the rest of the runtime, and doesn't work
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07002697 * if we have responses for multiple chunks.
2698 *
2699 * So we're pretty much stuck with copying data around multiple times.
2700 */
Elliott Hugheseac76672012-05-24 21:56:51 -07002701 ScopedLocalRef<jbyteArray> replyData(env, reinterpret_cast<jbyteArray>(env->GetObjectField(chunk.get(), WellKnownClasses::org_apache_harmony_dalvik_ddmc_Chunk_data)));
2702 length = env->GetIntField(chunk.get(), WellKnownClasses::org_apache_harmony_dalvik_ddmc_Chunk_length);
2703 offset = env->GetIntField(chunk.get(), WellKnownClasses::org_apache_harmony_dalvik_ddmc_Chunk_offset);
2704 type = env->GetIntField(chunk.get(), WellKnownClasses::org_apache_harmony_dalvik_ddmc_Chunk_type);
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07002705
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08002706 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 -07002707 if (length == 0 || replyData.get() == NULL) {
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07002708 return false;
2709 }
2710
Elliott Hughes6a5bd492011-10-28 14:33:57 -07002711 jsize replyLength = env->GetArrayLength(replyData.get());
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07002712 if (offset + length > replyLength) {
2713 LOG(WARNING) << StringPrintf("chunk off=%d len=%d exceeds reply array len %d", offset, length, replyLength);
2714 return false;
2715 }
2716
2717 uint8_t* reply = new uint8_t[length + kChunkHdrLen];
2718 if (reply == NULL) {
2719 LOG(WARNING) << "malloc failed: " << (length + kChunkHdrLen);
2720 return false;
2721 }
Elliott Hughesf7c3b662011-10-27 12:04:56 -07002722 JDWP::Set4BE(reply + 0, type);
2723 JDWP::Set4BE(reply + 4, length);
Elliott Hughes6a5bd492011-10-28 14:33:57 -07002724 env->GetByteArrayRegion(replyData.get(), offset, length, reinterpret_cast<jbyte*>(reply + kChunkHdrLen));
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07002725
2726 *pReplyBuf = reply;
2727 *pReplyLen = length + kChunkHdrLen;
2728
Elliott Hughesba8eee12012-01-24 20:25:24 -08002729 VLOG(jdwp) << StringPrintf("dvmHandleDdm returning type=%.4s buf=%p len=%d", reinterpret_cast<char*>(reply), reply, length);
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07002730 return true;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002731}
2732
Elliott Hughesa2155262011-11-16 16:26:58 -08002733void Dbg::DdmBroadcast(bool connect) {
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08002734 VLOG(jdwp) << "Broadcasting DDM " << (connect ? "connect" : "disconnect") << "...";
Elliott Hughes47fce012011-10-25 18:37:19 -07002735
2736 Thread* self = Thread::Current();
Ian Rogers50b35e22012-10-04 10:09:15 -07002737 if (self->GetState() != kRunnable) {
2738 LOG(ERROR) << "DDM broadcast in thread state " << self->GetState();
2739 /* try anyway? */
Elliott Hughes47fce012011-10-25 18:37:19 -07002740 }
2741
2742 JNIEnv* env = self->GetJniEnv();
Elliott Hughes47fce012011-10-25 18:37:19 -07002743 jint event = connect ? 1 /*DdmServer.CONNECTED*/ : 2 /*DdmServer.DISCONNECTED*/;
Elliott Hugheseac76672012-05-24 21:56:51 -07002744 env->CallStaticVoidMethod(WellKnownClasses::org_apache_harmony_dalvik_ddmc_DdmServer,
2745 WellKnownClasses::org_apache_harmony_dalvik_ddmc_DdmServer_broadcast,
2746 event);
Elliott Hughes47fce012011-10-25 18:37:19 -07002747 if (env->ExceptionCheck()) {
2748 LOG(ERROR) << "DdmServer.broadcast " << event << " failed";
2749 env->ExceptionDescribe();
2750 env->ExceptionClear();
2751 }
2752}
2753
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002754void Dbg::DdmConnected() {
Elliott Hughesa2155262011-11-16 16:26:58 -08002755 Dbg::DdmBroadcast(true);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002756}
2757
2758void Dbg::DdmDisconnected() {
Elliott Hughesa2155262011-11-16 16:26:58 -08002759 Dbg::DdmBroadcast(false);
Elliott Hughes47fce012011-10-25 18:37:19 -07002760 gDdmThreadNotification = false;
2761}
2762
2763/*
Elliott Hughes82188472011-11-07 18:11:48 -08002764 * Send a notification when a thread starts, stops, or changes its name.
Elliott Hughes47fce012011-10-25 18:37:19 -07002765 *
2766 * Because we broadcast the full set of threads when the notifications are
2767 * first enabled, it's possible for "thread" to be actively executing.
2768 */
Elliott Hughes82188472011-11-07 18:11:48 -08002769void Dbg::DdmSendThreadNotification(Thread* t, uint32_t type) {
Elliott Hughes47fce012011-10-25 18:37:19 -07002770 if (!gDdmThreadNotification) {
2771 return;
2772 }
2773
Elliott Hughes82188472011-11-07 18:11:48 -08002774 if (type == CHUNK_TYPE("THDE")) {
Elliott Hughes47fce012011-10-25 18:37:19 -07002775 uint8_t buf[4];
Elliott Hughesf7c3b662011-10-27 12:04:56 -07002776 JDWP::Set4BE(&buf[0], t->GetThinLockId());
Elliott Hughes47fce012011-10-25 18:37:19 -07002777 Dbg::DdmSendChunk(CHUNK_TYPE("THDE"), 4, buf);
Elliott Hughes82188472011-11-07 18:11:48 -08002778 } else {
2779 CHECK(type == CHUNK_TYPE("THCR") || type == CHUNK_TYPE("THNM")) << type;
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002780 ScopedObjectAccessUnchecked soa(Thread::Current());
Ian Rogers1f539342012-10-03 21:09:42 -07002781 SirtRef<String> name(soa.Self(), t->GetThreadName(soa));
Elliott Hughes82188472011-11-07 18:11:48 -08002782 size_t char_count = (name.get() != NULL) ? name->GetLength() : 0;
jeffhao725a9572012-11-13 18:20:12 -08002783 const jchar* chars = (name.get() != NULL) ? name->GetCharArray()->GetData() : NULL;
Elliott Hughes82188472011-11-07 18:11:48 -08002784
Elliott Hughes21f32d72011-11-09 17:44:13 -08002785 std::vector<uint8_t> bytes;
Elliott Hughes545a0642011-11-08 19:10:03 -08002786 JDWP::Append4BE(bytes, t->GetThinLockId());
2787 JDWP::AppendUtf16BE(bytes, chars, char_count);
Elliott Hughes21f32d72011-11-09 17:44:13 -08002788 CHECK_EQ(bytes.size(), char_count*2 + sizeof(uint32_t)*2);
2789 Dbg::DdmSendChunk(type, bytes);
Elliott Hughes47fce012011-10-25 18:37:19 -07002790 }
2791}
2792
Elliott Hughes47fce012011-10-25 18:37:19 -07002793void Dbg::DdmSetThreadNotification(bool enable) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002794 // Enable/disable thread notifications.
Elliott Hughes47fce012011-10-25 18:37:19 -07002795 gDdmThreadNotification = enable;
2796 if (enable) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002797 // Suspend the VM then post thread start notifications for all threads. Threads attaching will
2798 // see a suspension in progress and block until that ends. They then post their own start
2799 // notification.
2800 SuspendVM();
2801 std::list<Thread*> threads;
Ian Rogers50b35e22012-10-04 10:09:15 -07002802 Thread* self = Thread::Current();
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002803 {
Ian Rogers50b35e22012-10-04 10:09:15 -07002804 MutexLock mu(self, *Locks::thread_list_lock_);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002805 threads = Runtime::Current()->GetThreadList()->GetList();
2806 }
2807 {
Ian Rogers50b35e22012-10-04 10:09:15 -07002808 ScopedObjectAccess soa(self);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002809 typedef std::list<Thread*>::const_iterator It; // TODO: C++0x auto
2810 for (It it = threads.begin(), end = threads.end(); it != end; ++it) {
2811 Dbg::DdmSendThreadNotification(*it, CHUNK_TYPE("THCR"));
2812 }
2813 }
2814 ResumeVM();
Elliott Hughes47fce012011-10-25 18:37:19 -07002815 }
2816}
2817
Elliott Hughesa2155262011-11-16 16:26:58 -08002818void Dbg::PostThreadStartOrStop(Thread* t, uint32_t type) {
Elliott Hughesc0f09332012-03-26 13:27:06 -07002819 if (IsDebuggerActive()) {
Mathieu Chartierdbe6f462012-09-25 16:54:50 -07002820 ScopedObjectAccessUnchecked soa(Thread::Current());
Ian Rogerscfaa4552012-11-26 21:00:08 -08002821 JDWP::ObjectId id = gRegistry->Add(t->GetPeer());
Elliott Hughes82188472011-11-07 18:11:48 -08002822 gJdwpState->PostThreadChange(id, type == CHUNK_TYPE("THCR"));
Elliott Hughesc0f09332012-03-26 13:27:06 -07002823 // If this thread's just joined the party while we're already debugging, make sure it knows
2824 // to give us updates when it's running.
2825 t->SetDebuggerUpdatesEnabled(true);
Elliott Hughes47fce012011-10-25 18:37:19 -07002826 }
Elliott Hughes82188472011-11-07 18:11:48 -08002827 Dbg::DdmSendThreadNotification(t, type);
Elliott Hughes47fce012011-10-25 18:37:19 -07002828}
2829
2830void Dbg::PostThreadStart(Thread* t) {
Elliott Hughesa2155262011-11-16 16:26:58 -08002831 Dbg::PostThreadStartOrStop(t, CHUNK_TYPE("THCR"));
Elliott Hughes47fce012011-10-25 18:37:19 -07002832}
2833
2834void Dbg::PostThreadDeath(Thread* t) {
Elliott Hughesa2155262011-11-16 16:26:58 -08002835 Dbg::PostThreadStartOrStop(t, CHUNK_TYPE("THDE"));
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002836}
2837
Elliott Hughes82188472011-11-07 18:11:48 -08002838void Dbg::DdmSendChunk(uint32_t type, size_t byte_count, const uint8_t* buf) {
Elliott Hughes3bb81562011-10-21 18:52:59 -07002839 CHECK(buf != NULL);
2840 iovec vec[1];
2841 vec[0].iov_base = reinterpret_cast<void*>(const_cast<uint8_t*>(buf));
2842 vec[0].iov_len = byte_count;
2843 Dbg::DdmSendChunkV(type, vec, 1);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002844}
2845
Elliott Hughes21f32d72011-11-09 17:44:13 -08002846void Dbg::DdmSendChunk(uint32_t type, const std::vector<uint8_t>& bytes) {
2847 DdmSendChunk(type, bytes.size(), &bytes[0]);
2848}
2849
Elliott Hughescccd84f2011-12-05 16:51:54 -08002850void Dbg::DdmSendChunkV(uint32_t type, const struct iovec* iov, int iov_count) {
Elliott Hughes3bb81562011-10-21 18:52:59 -07002851 if (gJdwpState == NULL) {
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08002852 VLOG(jdwp) << "Debugger thread not active, ignoring DDM send: " << type;
Elliott Hughes3bb81562011-10-21 18:52:59 -07002853 } else {
Elliott Hughescccd84f2011-12-05 16:51:54 -08002854 gJdwpState->DdmSendChunkV(type, iov, iov_count);
Elliott Hughes3bb81562011-10-21 18:52:59 -07002855 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002856}
2857
Elliott Hughes767a1472011-10-26 18:49:02 -07002858int Dbg::DdmHandleHpifChunk(HpifWhen when) {
2859 if (when == HPIF_WHEN_NOW) {
Elliott Hughes7162ad92011-10-27 14:08:42 -07002860 DdmSendHeapInfo(when);
Elliott Hughes767a1472011-10-26 18:49:02 -07002861 return true;
2862 }
2863
2864 if (when != HPIF_WHEN_NEVER && when != HPIF_WHEN_NEXT_GC && when != HPIF_WHEN_EVERY_GC) {
2865 LOG(ERROR) << "invalid HpifWhen value: " << static_cast<int>(when);
2866 return false;
2867 }
2868
2869 gDdmHpifWhen = when;
2870 return true;
2871}
2872
2873bool Dbg::DdmHandleHpsgNhsgChunk(Dbg::HpsgWhen when, Dbg::HpsgWhat what, bool native) {
2874 if (when != HPSG_WHEN_NEVER && when != HPSG_WHEN_EVERY_GC) {
2875 LOG(ERROR) << "invalid HpsgWhen value: " << static_cast<int>(when);
2876 return false;
2877 }
2878
2879 if (what != HPSG_WHAT_MERGED_OBJECTS && what != HPSG_WHAT_DISTINCT_OBJECTS) {
2880 LOG(ERROR) << "invalid HpsgWhat value: " << static_cast<int>(what);
2881 return false;
2882 }
2883
2884 if (native) {
2885 gDdmNhsgWhen = when;
2886 gDdmNhsgWhat = what;
2887 } else {
2888 gDdmHpsgWhen = when;
2889 gDdmHpsgWhat = what;
2890 }
2891 return true;
2892}
2893
Elliott Hughes7162ad92011-10-27 14:08:42 -07002894void Dbg::DdmSendHeapInfo(HpifWhen reason) {
2895 // If there's a one-shot 'when', reset it.
2896 if (reason == gDdmHpifWhen) {
2897 if (gDdmHpifWhen == HPIF_WHEN_NEXT_GC) {
2898 gDdmHpifWhen = HPIF_WHEN_NEVER;
2899 }
2900 }
2901
2902 /*
2903 * Chunk HPIF (client --> server)
2904 *
2905 * Heap Info. General information about the heap,
2906 * suitable for a summary display.
2907 *
2908 * [u4]: number of heaps
2909 *
2910 * For each heap:
2911 * [u4]: heap ID
2912 * [u8]: timestamp in ms since Unix epoch
2913 * [u1]: capture reason (same as 'when' value from server)
2914 * [u4]: max heap size in bytes (-Xmx)
2915 * [u4]: current heap size in bytes
2916 * [u4]: current number of bytes allocated
2917 * [u4]: current number of objects allocated
2918 */
2919 uint8_t heap_count = 1;
Elliott Hughesb3bd5f02012-03-08 21:05:27 -08002920 Heap* heap = Runtime::Current()->GetHeap();
Elliott Hughes21f32d72011-11-09 17:44:13 -08002921 std::vector<uint8_t> bytes;
Elliott Hughes545a0642011-11-08 19:10:03 -08002922 JDWP::Append4BE(bytes, heap_count);
2923 JDWP::Append4BE(bytes, 1); // Heap id (bogus; we only have one heap).
2924 JDWP::Append8BE(bytes, MilliTime());
2925 JDWP::Append1BE(bytes, reason);
Elliott Hughesb3bd5f02012-03-08 21:05:27 -08002926 JDWP::Append4BE(bytes, heap->GetMaxMemory()); // Max allowed heap size in bytes.
2927 JDWP::Append4BE(bytes, heap->GetTotalMemory()); // Current heap size in bytes.
2928 JDWP::Append4BE(bytes, heap->GetBytesAllocated());
2929 JDWP::Append4BE(bytes, heap->GetObjectsAllocated());
Elliott Hughes21f32d72011-11-09 17:44:13 -08002930 CHECK_EQ(bytes.size(), 4U + (heap_count * (4 + 8 + 1 + 4 + 4 + 4 + 4)));
2931 Dbg::DdmSendChunk(CHUNK_TYPE("HPIF"), bytes);
Elliott Hughes767a1472011-10-26 18:49:02 -07002932}
2933
Elliott Hughes6a5bd492011-10-28 14:33:57 -07002934enum HpsgSolidity {
2935 SOLIDITY_FREE = 0,
2936 SOLIDITY_HARD = 1,
2937 SOLIDITY_SOFT = 2,
2938 SOLIDITY_WEAK = 3,
2939 SOLIDITY_PHANTOM = 4,
2940 SOLIDITY_FINALIZABLE = 5,
2941 SOLIDITY_SWEEP = 6,
2942};
2943
2944enum HpsgKind {
2945 KIND_OBJECT = 0,
2946 KIND_CLASS_OBJECT = 1,
2947 KIND_ARRAY_1 = 2,
2948 KIND_ARRAY_2 = 3,
2949 KIND_ARRAY_4 = 4,
2950 KIND_ARRAY_8 = 5,
2951 KIND_UNKNOWN = 6,
2952 KIND_NATIVE = 7,
2953};
2954
2955#define HPSG_PARTIAL (1<<7)
2956#define HPSG_STATE(solidity, kind) ((uint8_t)((((kind) & 0x7) << 3) | ((solidity) & 0x7)))
2957
Ian Rogers30fab402012-01-23 15:43:46 -08002958class HeapChunkContext {
2959 public:
Elliott Hughes6a5bd492011-10-28 14:33:57 -07002960 // Maximum chunk size. Obtain this from the formula:
2961 // (((maximum_heap_size / ALLOCATION_UNIT_SIZE) + 255) / 256) * 2
2962 HeapChunkContext(bool merge, bool native)
Ian Rogers30fab402012-01-23 15:43:46 -08002963 : buf_(16384 - 16),
2964 type_(0),
2965 merge_(merge) {
Elliott Hughes6a5bd492011-10-28 14:33:57 -07002966 Reset();
2967 if (native) {
Ian Rogers30fab402012-01-23 15:43:46 -08002968 type_ = CHUNK_TYPE("NHSG");
Elliott Hughes6a5bd492011-10-28 14:33:57 -07002969 } else {
Ian Rogers30fab402012-01-23 15:43:46 -08002970 type_ = merge ? CHUNK_TYPE("HPSG") : CHUNK_TYPE("HPSO");
Elliott Hughes6a5bd492011-10-28 14:33:57 -07002971 }
2972 }
2973
2974 ~HeapChunkContext() {
Ian Rogers30fab402012-01-23 15:43:46 -08002975 if (p_ > &buf_[0]) {
Elliott Hughes6a5bd492011-10-28 14:33:57 -07002976 Flush();
2977 }
2978 }
2979
2980 void EnsureHeader(const void* chunk_ptr) {
Ian Rogers30fab402012-01-23 15:43:46 -08002981 if (!needHeader_) {
Elliott Hughes6a5bd492011-10-28 14:33:57 -07002982 return;
2983 }
2984
2985 // Start a new HPSx chunk.
Ian Rogers30fab402012-01-23 15:43:46 -08002986 JDWP::Write4BE(&p_, 1); // Heap id (bogus; we only have one heap).
2987 JDWP::Write1BE(&p_, 8); // Size of allocation unit, in bytes.
Elliott Hughes6a5bd492011-10-28 14:33:57 -07002988
Ian Rogers30fab402012-01-23 15:43:46 -08002989 JDWP::Write4BE(&p_, reinterpret_cast<uintptr_t>(chunk_ptr)); // virtual address of segment start.
2990 JDWP::Write4BE(&p_, 0); // offset of this piece (relative to the virtual address).
Elliott Hughes6a5bd492011-10-28 14:33:57 -07002991 // [u4]: length of piece, in allocation units
2992 // 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 -08002993 pieceLenField_ = p_;
2994 JDWP::Write4BE(&p_, 0x55555555);
2995 needHeader_ = false;
Elliott Hughes6a5bd492011-10-28 14:33:57 -07002996 }
2997
Ian Rogersb726dcb2012-09-05 08:57:23 -07002998 void Flush() SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Elliott Hughes6a5bd492011-10-28 14:33:57 -07002999 // Patch the "length of piece" field.
Ian Rogers30fab402012-01-23 15:43:46 -08003000 CHECK_LE(&buf_[0], pieceLenField_);
3001 CHECK_LE(pieceLenField_, p_);
3002 JDWP::Set4BE(pieceLenField_, totalAllocationUnits_);
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003003
Ian Rogers30fab402012-01-23 15:43:46 -08003004 Dbg::DdmSendChunk(type_, p_ - &buf_[0], &buf_[0]);
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003005 Reset();
3006 }
3007
Ian Rogers00f7d0e2012-07-19 15:28:27 -07003008 static void HeapChunkCallback(void* start, void* end, size_t used_bytes, void* arg)
Ian Rogersb726dcb2012-09-05 08:57:23 -07003009 SHARED_LOCKS_REQUIRED(Locks::heap_bitmap_lock_,
3010 Locks::mutator_lock_) {
Ian Rogers30fab402012-01-23 15:43:46 -08003011 reinterpret_cast<HeapChunkContext*>(arg)->HeapChunkCallback(start, end, used_bytes);
Elliott Hughesa2155262011-11-16 16:26:58 -08003012 }
3013
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003014 private:
Elliott Hughesa2155262011-11-16 16:26:58 -08003015 enum { ALLOCATION_UNIT_SIZE = 8 };
3016
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003017 void Reset() {
Ian Rogers30fab402012-01-23 15:43:46 -08003018 p_ = &buf_[0];
Ian Rogers15bf2d32012-08-28 17:33:04 -07003019 startOfNextMemoryChunk_ = NULL;
Ian Rogers30fab402012-01-23 15:43:46 -08003020 totalAllocationUnits_ = 0;
3021 needHeader_ = true;
3022 pieceLenField_ = NULL;
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003023 }
3024
Ian Rogers00f7d0e2012-07-19 15:28:27 -07003025 void HeapChunkCallback(void* start, void* /*end*/, size_t used_bytes)
Ian Rogersb726dcb2012-09-05 08:57:23 -07003026 SHARED_LOCKS_REQUIRED(Locks::heap_bitmap_lock_,
3027 Locks::mutator_lock_) {
Ian Rogers30fab402012-01-23 15:43:46 -08003028 // Note: heap call backs cannot manipulate the heap upon which they are crawling, care is taken
3029 // in the following code not to allocate memory, by ensuring buf_ is of the correct size
Ian Rogers15bf2d32012-08-28 17:33:04 -07003030 if (used_bytes == 0) {
3031 if (start == NULL) {
3032 // Reset for start of new heap.
3033 startOfNextMemoryChunk_ = NULL;
3034 Flush();
3035 }
3036 // Only process in use memory so that free region information
3037 // also includes dlmalloc book keeping.
Elliott Hughesa2155262011-11-16 16:26:58 -08003038 return;
Elliott Hughesa2155262011-11-16 16:26:58 -08003039 }
3040
Ian Rogers15bf2d32012-08-28 17:33:04 -07003041 /* If we're looking at the native heap, we'll just return
3042 * (SOLIDITY_HARD, KIND_NATIVE) for all allocated chunks
3043 */
3044 bool native = type_ == CHUNK_TYPE("NHSG");
3045
3046 if (startOfNextMemoryChunk_ != NULL) {
3047 // Transmit any pending free memory. Native free memory of
3048 // over kMaxFreeLen could be because of the use of mmaps, so
3049 // don't report. If not free memory then start a new segment.
3050 bool flush = true;
3051 if (start > startOfNextMemoryChunk_) {
3052 const size_t kMaxFreeLen = 2 * kPageSize;
3053 void* freeStart = startOfNextMemoryChunk_;
3054 void* freeEnd = start;
3055 size_t freeLen = (char*)freeEnd - (char*)freeStart;
3056 if (!native || freeLen < kMaxFreeLen) {
3057 AppendChunk(HPSG_STATE(SOLIDITY_FREE, 0), freeStart, freeLen);
3058 flush = false;
3059 }
3060 }
3061 if (flush) {
3062 startOfNextMemoryChunk_ = NULL;
3063 Flush();
3064 }
3065 }
3066 const Object *obj = (const Object *)start;
Elliott Hughesa2155262011-11-16 16:26:58 -08003067
3068 // Determine the type of this chunk.
3069 // OLD-TODO: if context.merge, see if this chunk is different from the last chunk.
3070 // If it's the same, we should combine them.
Ian Rogers15bf2d32012-08-28 17:33:04 -07003071 uint8_t state = ExamineObject(obj, native);
3072 // dlmalloc's chunk header is 2 * sizeof(size_t), but if the previous chunk is in use for an
3073 // allocation then the first sizeof(size_t) may belong to it.
3074 const size_t dlMallocOverhead = sizeof(size_t);
3075 AppendChunk(state, start, used_bytes + dlMallocOverhead);
3076 startOfNextMemoryChunk_ = (char*)start + used_bytes + dlMallocOverhead;
3077 }
Elliott Hughesa2155262011-11-16 16:26:58 -08003078
Ian Rogers15bf2d32012-08-28 17:33:04 -07003079 void AppendChunk(uint8_t state, void* ptr, size_t length)
Ian Rogersb726dcb2012-09-05 08:57:23 -07003080 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Ian Rogers15bf2d32012-08-28 17:33:04 -07003081 // Make sure there's enough room left in the buffer.
3082 // We need to use two bytes for every fractional 256 allocation units used by the chunk plus
3083 // 17 bytes for any header.
3084 size_t needed = (((length/ALLOCATION_UNIT_SIZE + 255) / 256) * 2) + 17;
3085 size_t bytesLeft = buf_.size() - (size_t)(p_ - &buf_[0]);
3086 if (bytesLeft < needed) {
3087 Flush();
3088 }
3089
3090 bytesLeft = buf_.size() - (size_t)(p_ - &buf_[0]);
3091 if (bytesLeft < needed) {
3092 LOG(WARNING) << "Chunk is too big to transmit (chunk_len=" << length << ", "
3093 << needed << " bytes)";
3094 return;
3095 }
3096 EnsureHeader(ptr);
Elliott Hughesa2155262011-11-16 16:26:58 -08003097 // Write out the chunk description.
Ian Rogers15bf2d32012-08-28 17:33:04 -07003098 length /= ALLOCATION_UNIT_SIZE; // Convert to allocation units.
3099 totalAllocationUnits_ += length;
3100 while (length > 256) {
Ian Rogers30fab402012-01-23 15:43:46 -08003101 *p_++ = state | HPSG_PARTIAL;
3102 *p_++ = 255; // length - 1
Ian Rogers15bf2d32012-08-28 17:33:04 -07003103 length -= 256;
Elliott Hughesa2155262011-11-16 16:26:58 -08003104 }
Ian Rogers30fab402012-01-23 15:43:46 -08003105 *p_++ = state;
Ian Rogers15bf2d32012-08-28 17:33:04 -07003106 *p_++ = length - 1;
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003107 }
3108
Ian Rogers5bfa60f2012-09-02 21:17:56 -07003109 uint8_t ExamineObject(const Object* o, bool is_native_heap)
Ian Rogersb726dcb2012-09-05 08:57:23 -07003110 SHARED_LOCKS_REQUIRED(Locks::heap_bitmap_lock_) {
Elliott Hughesa2155262011-11-16 16:26:58 -08003111 if (o == NULL) {
3112 return HPSG_STATE(SOLIDITY_FREE, 0);
3113 }
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003114
Elliott Hughesa2155262011-11-16 16:26:58 -08003115 // It's an allocated chunk. Figure out what it is.
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003116
Elliott Hughesa2155262011-11-16 16:26:58 -08003117 // If we're looking at the native heap, we'll just return
3118 // (SOLIDITY_HARD, KIND_NATIVE) for all allocated chunks.
Ian Rogers00f7d0e2012-07-19 15:28:27 -07003119 if (is_native_heap) {
Elliott Hughesa2155262011-11-16 16:26:58 -08003120 return HPSG_STATE(SOLIDITY_HARD, KIND_NATIVE);
3121 }
3122
Ian Rogers5bfa60f2012-09-02 21:17:56 -07003123 if (!Runtime::Current()->GetHeap()->IsLiveObjectLocked(o)) {
Ian Rogers15bf2d32012-08-28 17:33:04 -07003124 return HPSG_STATE(SOLIDITY_HARD, KIND_NATIVE);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07003125 }
3126
Elliott Hughesa2155262011-11-16 16:26:58 -08003127 Class* c = o->GetClass();
3128 if (c == NULL) {
3129 // The object was probably just created but hasn't been initialized yet.
3130 return HPSG_STATE(SOLIDITY_HARD, KIND_OBJECT);
3131 }
3132
Elliott Hughesb3bd5f02012-03-08 21:05:27 -08003133 if (!Runtime::Current()->GetHeap()->IsHeapAddress(c)) {
Ian Rogers15bf2d32012-08-28 17:33:04 -07003134 LOG(ERROR) << "Invalid class for managed heap object: " << o << " " << c;
Elliott Hughesa2155262011-11-16 16:26:58 -08003135 return HPSG_STATE(SOLIDITY_HARD, KIND_UNKNOWN);
3136 }
3137
3138 if (c->IsClassClass()) {
3139 return HPSG_STATE(SOLIDITY_HARD, KIND_CLASS_OBJECT);
3140 }
3141
3142 if (c->IsArrayClass()) {
3143 if (o->IsObjectArray()) {
3144 return HPSG_STATE(SOLIDITY_HARD, KIND_ARRAY_4);
3145 }
3146 switch (c->GetComponentSize()) {
3147 case 1: return HPSG_STATE(SOLIDITY_HARD, KIND_ARRAY_1);
3148 case 2: return HPSG_STATE(SOLIDITY_HARD, KIND_ARRAY_2);
3149 case 4: return HPSG_STATE(SOLIDITY_HARD, KIND_ARRAY_4);
3150 case 8: return HPSG_STATE(SOLIDITY_HARD, KIND_ARRAY_8);
3151 }
3152 }
3153
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003154 return HPSG_STATE(SOLIDITY_HARD, KIND_OBJECT);
3155 }
3156
Ian Rogers30fab402012-01-23 15:43:46 -08003157 std::vector<uint8_t> buf_;
3158 uint8_t* p_;
3159 uint8_t* pieceLenField_;
Ian Rogers15bf2d32012-08-28 17:33:04 -07003160 void* startOfNextMemoryChunk_;
Ian Rogers30fab402012-01-23 15:43:46 -08003161 size_t totalAllocationUnits_;
3162 uint32_t type_;
3163 bool merge_;
3164 bool needHeader_;
3165
Elliott Hughesa2155262011-11-16 16:26:58 -08003166 DISALLOW_COPY_AND_ASSIGN(HeapChunkContext);
3167};
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003168
3169void Dbg::DdmSendHeapSegments(bool native) {
3170 Dbg::HpsgWhen when;
3171 Dbg::HpsgWhat what;
3172 if (!native) {
3173 when = gDdmHpsgWhen;
3174 what = gDdmHpsgWhat;
3175 } else {
3176 when = gDdmNhsgWhen;
3177 what = gDdmNhsgWhat;
3178 }
3179 if (when == HPSG_WHEN_NEVER) {
3180 return;
3181 }
3182
3183 // Figure out what kind of chunks we'll be sending.
3184 CHECK(what == HPSG_WHAT_MERGED_OBJECTS || what == HPSG_WHAT_DISTINCT_OBJECTS) << static_cast<int>(what);
3185
3186 // First, send a heap start chunk.
3187 uint8_t heap_id[4];
3188 JDWP::Set4BE(&heap_id[0], 1); // Heap id (bogus; we only have one heap).
3189 Dbg::DdmSendChunk(native ? CHUNK_TYPE("NHST") : CHUNK_TYPE("HPST"), sizeof(heap_id), heap_id);
3190
3191 // Send a series of heap segment chunks.
Elliott Hughesa2155262011-11-16 16:26:58 -08003192 HeapChunkContext context((what == HPSG_WHAT_MERGED_OBJECTS), native);
3193 if (native) {
Ian Rogers30fab402012-01-23 15:43:46 -08003194 // TODO: enable when bionic has moved to dlmalloc 2.8.5
3195 // dlmalloc_inspect_all(HeapChunkContext::HeapChunkCallback, &context);
3196 UNIMPLEMENTED(WARNING) << "Native heap send heap segments";
Elliott Hughesa2155262011-11-16 16:26:58 -08003197 } else {
Elliott Hughesb3bd5f02012-03-08 21:05:27 -08003198 Heap* heap = Runtime::Current()->GetHeap();
Mathieu Chartierfd678be2012-08-30 14:50:54 -07003199 const Spaces& spaces = heap->GetSpaces();
Ian Rogers50b35e22012-10-04 10:09:15 -07003200 Thread* self = Thread::Current();
Mathieu Chartierfd678be2012-08-30 14:50:54 -07003201 for (Spaces::const_iterator cur = spaces.begin(); cur != spaces.end(); ++cur) {
Mathieu Chartierb062fdd2012-07-03 09:51:48 -07003202 if ((*cur)->IsAllocSpace()) {
Ian Rogers50b35e22012-10-04 10:09:15 -07003203 ReaderMutexLock mu(self, *Locks::heap_bitmap_lock_);
Mathieu Chartierb062fdd2012-07-03 09:51:48 -07003204 (*cur)->AsAllocSpace()->Walk(HeapChunkContext::HeapChunkCallback, &context);
3205 }
3206 }
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -07003207 // Walk the large objects, these are not in the AllocSpace.
3208 heap->GetLargeObjectsSpace()->Walk(HeapChunkContext::HeapChunkCallback, &context);
Elliott Hughesa2155262011-11-16 16:26:58 -08003209 }
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003210
3211 // Finally, send a heap end chunk.
3212 Dbg::DdmSendChunk(native ? CHUNK_TYPE("NHEN") : CHUNK_TYPE("HPEN"), sizeof(heap_id), heap_id);
Elliott Hughes767a1472011-10-26 18:49:02 -07003213}
3214
Elliott Hughes545a0642011-11-08 19:10:03 -08003215void Dbg::SetAllocTrackingEnabled(bool enabled) {
Ian Rogers50b35e22012-10-04 10:09:15 -07003216 MutexLock mu(Thread::Current(), gAllocTrackerLock);
Elliott Hughes545a0642011-11-08 19:10:03 -08003217 if (enabled) {
3218 if (recent_allocation_records_ == NULL) {
3219 LOG(INFO) << "Enabling alloc tracker (" << kNumAllocRecords << " entries, "
3220 << kMaxAllocRecordStackDepth << " frames --> "
3221 << (sizeof(AllocRecord) * kNumAllocRecords) << " bytes)";
3222 gAllocRecordHead = gAllocRecordCount = 0;
3223 recent_allocation_records_ = new AllocRecord[kNumAllocRecords];
3224 CHECK(recent_allocation_records_ != NULL);
3225 }
3226 } else {
3227 delete[] recent_allocation_records_;
3228 recent_allocation_records_ = NULL;
3229 }
3230}
3231
Ian Rogers0399dde2012-06-06 17:09:28 -07003232struct AllocRecordStackVisitor : public StackVisitor {
3233 AllocRecordStackVisitor(const ManagedStack* stack,
Ian Rogers306057f2012-11-26 12:45:53 -08003234 const std::deque<InstrumentationStackFrame>* instrumentation_stack,
3235 AllocRecord* record)
Ian Rogersb726dcb2012-09-05 08:57:23 -07003236 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_)
jeffhao725a9572012-11-13 18:20:12 -08003237 : StackVisitor(stack, instrumentation_stack, NULL), record(record), depth(0) {}
Elliott Hughes545a0642011-11-08 19:10:03 -08003238
Ian Rogers00f7d0e2012-07-19 15:28:27 -07003239 // TODO: Enable annotalysis. We know lock is held in constructor, but abstraction confuses
3240 // annotalysis.
3241 bool VisitFrame() NO_THREAD_SAFETY_ANALYSIS {
Elliott Hughes545a0642011-11-08 19:10:03 -08003242 if (depth >= kMaxAllocRecordStackDepth) {
Elliott Hughes530fa002012-03-12 11:44:49 -07003243 return false;
Elliott Hughes545a0642011-11-08 19:10:03 -08003244 }
Mathieu Chartier66f19252012-09-18 08:57:04 -07003245 AbstractMethod* m = GetMethod();
Ian Rogers0399dde2012-06-06 17:09:28 -07003246 if (!m->IsRuntimeMethod()) {
3247 record->stack[depth].method = m;
3248 record->stack[depth].dex_pc = GetDexPc();
Elliott Hughes530fa002012-03-12 11:44:49 -07003249 ++depth;
Elliott Hughes545a0642011-11-08 19:10:03 -08003250 }
Elliott Hughes530fa002012-03-12 11:44:49 -07003251 return true;
Elliott Hughes545a0642011-11-08 19:10:03 -08003252 }
3253
3254 ~AllocRecordStackVisitor() {
3255 // Clear out any unused stack trace elements.
3256 for (; depth < kMaxAllocRecordStackDepth; ++depth) {
3257 record->stack[depth].method = NULL;
Ian Rogers0399dde2012-06-06 17:09:28 -07003258 record->stack[depth].dex_pc = 0;
Elliott Hughes545a0642011-11-08 19:10:03 -08003259 }
3260 }
3261
3262 AllocRecord* record;
3263 size_t depth;
3264};
3265
3266void Dbg::RecordAllocation(Class* type, size_t byte_count) {
3267 Thread* self = Thread::Current();
3268 CHECK(self != NULL);
3269
Ian Rogers50b35e22012-10-04 10:09:15 -07003270 MutexLock mu(self, gAllocTrackerLock);
Elliott Hughes545a0642011-11-08 19:10:03 -08003271 if (recent_allocation_records_ == NULL) {
3272 return;
3273 }
3274
3275 // Advance and clip.
3276 if (++gAllocRecordHead == kNumAllocRecords) {
3277 gAllocRecordHead = 0;
3278 }
3279
3280 // Fill in the basics.
3281 AllocRecord* record = &recent_allocation_records_[gAllocRecordHead];
3282 record->type = type;
3283 record->byte_count = byte_count;
3284 record->thin_lock_id = self->GetThinLockId();
3285
3286 // Fill in the stack trace.
jeffhao725a9572012-11-13 18:20:12 -08003287 AllocRecordStackVisitor visitor(self->GetManagedStack(), self->GetInstrumentationStack(), record);
Ian Rogers0399dde2012-06-06 17:09:28 -07003288 visitor.WalkStack();
Elliott Hughes545a0642011-11-08 19:10:03 -08003289
3290 if (gAllocRecordCount < kNumAllocRecords) {
3291 ++gAllocRecordCount;
3292 }
3293}
3294
Elliott Hughesa8f93cb2012-06-08 17:08:48 -07003295// Returns the index of the head element.
3296//
3297// We point at the most-recently-written record, so if gAllocRecordCount is 1
3298// we want to use the current element. Take "head+1" and subtract count
3299// from it.
3300//
3301// We need to handle underflow in our circular buffer, so we add
3302// kNumAllocRecords and then mask it back down.
Elliott Hughesf8349362012-06-18 15:00:06 -07003303static inline int HeadIndex() EXCLUSIVE_LOCKS_REQUIRED(gAllocTrackerLock) {
Elliott Hughes545a0642011-11-08 19:10:03 -08003304 return (gAllocRecordHead+1 + kNumAllocRecords - gAllocRecordCount) & (kNumAllocRecords-1);
3305}
3306
3307void Dbg::DumpRecentAllocations() {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07003308 ScopedObjectAccess soa(Thread::Current());
Ian Rogers50b35e22012-10-04 10:09:15 -07003309 MutexLock mu(soa.Self(), gAllocTrackerLock);
Elliott Hughes545a0642011-11-08 19:10:03 -08003310 if (recent_allocation_records_ == NULL) {
3311 LOG(INFO) << "Not recording tracked allocations";
3312 return;
3313 }
3314
3315 // "i" is the head of the list. We want to start at the end of the
3316 // list and move forward to the tail.
Elliott Hughesa8f93cb2012-06-08 17:08:48 -07003317 size_t i = HeadIndex();
Elliott Hughes545a0642011-11-08 19:10:03 -08003318 size_t count = gAllocRecordCount;
3319
3320 LOG(INFO) << "Tracked allocations, (head=" << gAllocRecordHead << " count=" << count << ")";
3321 while (count--) {
3322 AllocRecord* record = &recent_allocation_records_[i];
3323
Elliott Hughesa8f93cb2012-06-08 17:08:48 -07003324 LOG(INFO) << StringPrintf(" Thread %-2d %6zd bytes ", record->thin_lock_id, record->byte_count)
Elliott Hughes545a0642011-11-08 19:10:03 -08003325 << PrettyClass(record->type);
3326
3327 for (size_t stack_frame = 0; stack_frame < kMaxAllocRecordStackDepth; ++stack_frame) {
Mathieu Chartier66f19252012-09-18 08:57:04 -07003328 const AbstractMethod* m = record->stack[stack_frame].method;
Elliott Hughes545a0642011-11-08 19:10:03 -08003329 if (m == NULL) {
3330 break;
3331 }
3332 LOG(INFO) << " " << PrettyMethod(m) << " line " << record->stack[stack_frame].LineNumber();
3333 }
3334
3335 // pause periodically to help logcat catch up
3336 if ((count % 5) == 0) {
3337 usleep(40000);
3338 }
3339
3340 i = (i + 1) & (kNumAllocRecords-1);
3341 }
3342}
3343
3344class StringTable {
3345 public:
3346 StringTable() {
3347 }
3348
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08003349 void Add(const char* s) {
Elliott Hughes545a0642011-11-08 19:10:03 -08003350 table_.insert(s);
3351 }
3352
Elliott Hughesa8f93cb2012-06-08 17:08:48 -07003353 size_t IndexOf(const char* s) const {
3354 typedef std::set<std::string>::const_iterator It; // TODO: C++0x auto
3355 It it = table_.find(s);
3356 if (it == table_.end()) {
3357 LOG(FATAL) << "IndexOf(\"" << s << "\") failed";
3358 }
3359 return std::distance(table_.begin(), it);
Elliott Hughes545a0642011-11-08 19:10:03 -08003360 }
3361
Elliott Hughesa8f93cb2012-06-08 17:08:48 -07003362 size_t Size() const {
Elliott Hughes545a0642011-11-08 19:10:03 -08003363 return table_.size();
3364 }
3365
Elliott Hughesa8f93cb2012-06-08 17:08:48 -07003366 void WriteTo(std::vector<uint8_t>& bytes) const {
3367 typedef std::set<std::string>::const_iterator It; // TODO: C++0x auto
Elliott Hughes545a0642011-11-08 19:10:03 -08003368 for (It it = table_.begin(); it != table_.end(); ++it) {
Elliott Hughesa8f93cb2012-06-08 17:08:48 -07003369 const char* s = (*it).c_str();
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08003370 size_t s_len = CountModifiedUtf8Chars(s);
3371 UniquePtr<uint16_t> s_utf16(new uint16_t[s_len]);
3372 ConvertModifiedUtf8ToUtf16(s_utf16.get(), s);
3373 JDWP::AppendUtf16BE(bytes, s_utf16.get(), s_len);
Elliott Hughes545a0642011-11-08 19:10:03 -08003374 }
3375 }
3376
3377 private:
Elliott Hughesa8f93cb2012-06-08 17:08:48 -07003378 std::set<std::string> table_;
Elliott Hughes545a0642011-11-08 19:10:03 -08003379 DISALLOW_COPY_AND_ASSIGN(StringTable);
3380};
3381
3382/*
3383 * The data we send to DDMS contains everything we have recorded.
3384 *
3385 * Message header (all values big-endian):
3386 * (1b) message header len (to allow future expansion); includes itself
3387 * (1b) entry header len
3388 * (1b) stack frame len
3389 * (2b) number of entries
3390 * (4b) offset to string table from start of message
3391 * (2b) number of class name strings
3392 * (2b) number of method name strings
3393 * (2b) number of source file name strings
3394 * For each entry:
3395 * (4b) total allocation size
Elliott Hughes221229c2013-01-08 18:17:50 -08003396 * (2b) thread id
Elliott Hughes545a0642011-11-08 19:10:03 -08003397 * (2b) allocated object's class name index
3398 * (1b) stack depth
3399 * For each stack frame:
3400 * (2b) method's class name
3401 * (2b) method name
3402 * (2b) method source file
3403 * (2b) line number, clipped to 32767; -2 if native; -1 if no source
3404 * (xb) class name strings
3405 * (xb) method name strings
3406 * (xb) source file strings
3407 *
3408 * As with other DDM traffic, strings are sent as a 4-byte length
3409 * followed by UTF-16 data.
3410 *
3411 * We send up 16-bit unsigned indexes into string tables. In theory there
3412 * can be (kMaxAllocRecordStackDepth * kNumAllocRecords) unique strings in
3413 * each table, but in practice there should be far fewer.
3414 *
3415 * The chief reason for using a string table here is to keep the size of
3416 * the DDMS message to a minimum. This is partly to make the protocol
3417 * efficient, but also because we have to form the whole thing up all at
3418 * once in a memory buffer.
3419 *
3420 * We use separate string tables for class names, method names, and source
3421 * files to keep the indexes small. There will generally be no overlap
3422 * between the contents of these tables.
3423 */
3424jbyteArray Dbg::GetRecentAllocations() {
3425 if (false) {
3426 DumpRecentAllocations();
3427 }
3428
Ian Rogers50b35e22012-10-04 10:09:15 -07003429 Thread* self = Thread::Current();
3430 MutexLock mu(self, gAllocTrackerLock);
Elliott Hughes545a0642011-11-08 19:10:03 -08003431
Elliott Hughesa8f93cb2012-06-08 17:08:48 -07003432 //
3433 // Part 1: generate string tables.
3434 //
Elliott Hughes545a0642011-11-08 19:10:03 -08003435 StringTable class_names;
3436 StringTable method_names;
3437 StringTable filenames;
3438
3439 int count = gAllocRecordCount;
Elliott Hughesa8f93cb2012-06-08 17:08:48 -07003440 int idx = HeadIndex();
Elliott Hughes545a0642011-11-08 19:10:03 -08003441 while (count--) {
3442 AllocRecord* record = &recent_allocation_records_[idx];
3443
Elliott Hughes91250e02011-12-13 22:30:35 -08003444 class_names.Add(ClassHelper(record->type).GetDescriptor());
Elliott Hughes545a0642011-11-08 19:10:03 -08003445
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08003446 MethodHelper mh;
Elliott Hughes545a0642011-11-08 19:10:03 -08003447 for (size_t i = 0; i < kMaxAllocRecordStackDepth; i++) {
Mathieu Chartier66f19252012-09-18 08:57:04 -07003448 AbstractMethod* m = record->stack[i].method;
Elliott Hughes545a0642011-11-08 19:10:03 -08003449 if (m != NULL) {
Ian Rogersba377812012-05-28 21:16:29 -07003450 mh.ChangeMethod(m);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08003451 class_names.Add(mh.GetDeclaringClassDescriptor());
3452 method_names.Add(mh.GetName());
3453 filenames.Add(mh.GetDeclaringClassSourceFile());
Elliott Hughes545a0642011-11-08 19:10:03 -08003454 }
3455 }
3456
3457 idx = (idx + 1) & (kNumAllocRecords-1);
3458 }
3459
3460 LOG(INFO) << "allocation records: " << gAllocRecordCount;
3461
Elliott Hughesa8f93cb2012-06-08 17:08:48 -07003462 //
3463 // Part 2: allocate a buffer and generate the output.
3464 //
Elliott Hughes545a0642011-11-08 19:10:03 -08003465 std::vector<uint8_t> bytes;
3466
3467 // (1b) message header len (to allow future expansion); includes itself
3468 // (1b) entry header len
3469 // (1b) stack frame len
3470 const int kMessageHeaderLen = 15;
3471 const int kEntryHeaderLen = 9;
3472 const int kStackFrameLen = 8;
3473 JDWP::Append1BE(bytes, kMessageHeaderLen);
3474 JDWP::Append1BE(bytes, kEntryHeaderLen);
3475 JDWP::Append1BE(bytes, kStackFrameLen);
3476
3477 // (2b) number of entries
3478 // (4b) offset to string table from start of message
3479 // (2b) number of class name strings
3480 // (2b) number of method name strings
3481 // (2b) number of source file name strings
3482 JDWP::Append2BE(bytes, gAllocRecordCount);
3483 size_t string_table_offset = bytes.size();
3484 JDWP::Append4BE(bytes, 0); // We'll patch this later...
3485 JDWP::Append2BE(bytes, class_names.Size());
3486 JDWP::Append2BE(bytes, method_names.Size());
3487 JDWP::Append2BE(bytes, filenames.Size());
3488
3489 count = gAllocRecordCount;
Elliott Hughesa8f93cb2012-06-08 17:08:48 -07003490 idx = HeadIndex();
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08003491 ClassHelper kh;
Elliott Hughes545a0642011-11-08 19:10:03 -08003492 while (count--) {
3493 // For each entry:
3494 // (4b) total allocation size
3495 // (2b) thread id
3496 // (2b) allocated object's class name index
3497 // (1b) stack depth
3498 AllocRecord* record = &recent_allocation_records_[idx];
3499 size_t stack_depth = record->GetDepth();
Elliott Hughesa8f93cb2012-06-08 17:08:48 -07003500 kh.ChangeClass(record->type);
3501 size_t allocated_object_class_name_index = class_names.IndexOf(kh.GetDescriptor());
Elliott Hughes545a0642011-11-08 19:10:03 -08003502 JDWP::Append4BE(bytes, record->byte_count);
3503 JDWP::Append2BE(bytes, record->thin_lock_id);
Elliott Hughesa8f93cb2012-06-08 17:08:48 -07003504 JDWP::Append2BE(bytes, allocated_object_class_name_index);
Elliott Hughes545a0642011-11-08 19:10:03 -08003505 JDWP::Append1BE(bytes, stack_depth);
3506
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08003507 MethodHelper mh;
Elliott Hughes545a0642011-11-08 19:10:03 -08003508 for (size_t stack_frame = 0; stack_frame < stack_depth; ++stack_frame) {
3509 // For each stack frame:
3510 // (2b) method's class name
3511 // (2b) method name
3512 // (2b) method source file
3513 // (2b) line number, clipped to 32767; -2 if native; -1 if no source
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08003514 mh.ChangeMethod(record->stack[stack_frame].method);
Elliott Hughesa8f93cb2012-06-08 17:08:48 -07003515 size_t class_name_index = class_names.IndexOf(mh.GetDeclaringClassDescriptor());
3516 size_t method_name_index = method_names.IndexOf(mh.GetName());
3517 size_t file_name_index = filenames.IndexOf(mh.GetDeclaringClassSourceFile());
3518 JDWP::Append2BE(bytes, class_name_index);
3519 JDWP::Append2BE(bytes, method_name_index);
3520 JDWP::Append2BE(bytes, file_name_index);
Elliott Hughes545a0642011-11-08 19:10:03 -08003521 JDWP::Append2BE(bytes, record->stack[stack_frame].LineNumber());
3522 }
3523
3524 idx = (idx + 1) & (kNumAllocRecords-1);
3525 }
3526
3527 // (xb) class name strings
3528 // (xb) method name strings
3529 // (xb) source file strings
3530 JDWP::Set4BE(&bytes[string_table_offset], bytes.size());
3531 class_names.WriteTo(bytes);
3532 method_names.WriteTo(bytes);
3533 filenames.WriteTo(bytes);
3534
Ian Rogers50b35e22012-10-04 10:09:15 -07003535 JNIEnv* env = self->GetJniEnv();
Elliott Hughes545a0642011-11-08 19:10:03 -08003536 jbyteArray result = env->NewByteArray(bytes.size());
3537 if (result != NULL) {
3538 env->SetByteArrayRegion(result, 0, bytes.size(), reinterpret_cast<const jbyte*>(&bytes[0]));
3539 }
3540 return result;
3541}
3542
Elliott Hughes872d4ec2011-10-21 17:07:15 -07003543} // namespace art