blob: deef32288ae3d261a23a1e903cc35b3d2f327fef [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 Hughes221229c2013-01-08 18:17:50 -08001497JDWP::JdwpError Dbg::IsSuspended(JDWP::ObjectId thread_id, bool& result) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001498 ScopedObjectAccess soa(Thread::Current());
Ian Rogers50b35e22012-10-04 10:09:15 -07001499 MutexLock mu(soa.Self(), *Locks::thread_list_lock_);
Elliott Hughes221229c2013-01-08 18:17:50 -08001500 Thread* thread;
1501 JDWP::JdwpError error = DecodeThread(soa, thread_id, thread);
1502 if (error != JDWP::ERR_NONE) {
1503 return error;
1504 }
Ian Rogers50b35e22012-10-04 10:09:15 -07001505 MutexLock mu2(soa.Self(), *Locks::thread_suspend_count_lock_);
Elliott Hughes221229c2013-01-08 18:17:50 -08001506 result = thread->IsSuspended();
1507 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001508}
1509
Elliott Hughescaf76542012-06-28 16:08:22 -07001510void Dbg::GetThreads(JDWP::ObjectId thread_group_id, std::vector<JDWP::ObjectId>& thread_ids) {
Ian Rogers365c1022012-06-22 15:05:28 -07001511 class ThreadListVisitor {
1512 public:
jeffhao0dfbb7e2012-11-28 15:26:03 -08001513 ThreadListVisitor(const ScopedObjectAccessUnchecked& soa, Object* desired_thread_group,
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001514 std::vector<JDWP::ObjectId>& thread_ids)
Ian Rogersb726dcb2012-09-05 08:57:23 -07001515 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_)
jeffhao0dfbb7e2012-11-28 15:26:03 -08001516 : soa_(soa), desired_thread_group_(desired_thread_group), thread_ids_(thread_ids) {}
Ian Rogers365c1022012-06-22 15:05:28 -07001517
Elliott Hughesa2155262011-11-16 16:26:58 -08001518 static void Visit(Thread* t, void* arg) {
1519 reinterpret_cast<ThreadListVisitor*>(arg)->Visit(t);
1520 }
1521
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001522 // TODO: Enable annotalysis. We know lock is held in constructor, but abstraction confuses
1523 // annotalysis.
1524 void Visit(Thread* t) NO_THREAD_SAFETY_ANALYSIS {
Elliott Hughesa2155262011-11-16 16:26:58 -08001525 if (t == Dbg::GetDebugThread()) {
1526 // Skip the JDWP thread. Some debuggers get bent out of shape when they can't suspend and
1527 // query all threads, so it's easier if we just don't tell them about this thread.
1528 return;
1529 }
Ian Rogerscfaa4552012-11-26 21:00:08 -08001530 Object* peer = t->GetPeer();
jeffhao0dfbb7e2012-11-28 15:26:03 -08001531 if (IsInDesiredThreadGroup(peer)) {
Ian Rogers120f1c72012-09-28 17:17:10 -07001532 thread_ids_.push_back(gRegistry->Add(peer));
Elliott Hughesa2155262011-11-16 16:26:58 -08001533 }
1534 }
1535
Ian Rogers365c1022012-06-22 15:05:28 -07001536 private:
jeffhao0dfbb7e2012-11-28 15:26:03 -08001537 bool IsInDesiredThreadGroup(Object* peer)
1538 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
jeffhao0dfbb7e2012-11-28 15:26:03 -08001539 // peer might be NULL if the thread is still starting up.
1540 if (peer == NULL) {
1541 // We can't tell the debugger about this thread yet.
1542 // TODO: if we identified threads to the debugger by their Thread*
1543 // rather than their peer's Object*, we could fix this.
1544 // Doing so might help us report ZOMBIE threads too.
1545 return false;
1546 }
jeffhaoc1e04902012-12-13 12:41:10 -08001547 // Do we want threads from all thread groups?
1548 if (desired_thread_group_ == NULL) {
1549 return true;
1550 }
jeffhao0dfbb7e2012-11-28 15:26:03 -08001551 Object* group = soa_.DecodeField(WellKnownClasses::java_lang_Thread_group)->GetObject(peer);
1552 return (group == desired_thread_group_);
1553 }
1554
Mathieu Chartierdbe6f462012-09-25 16:54:50 -07001555 const ScopedObjectAccessUnchecked& soa_;
jeffhao0dfbb7e2012-11-28 15:26:03 -08001556 Object* const desired_thread_group_;
Elliott Hughescaf76542012-06-28 16:08:22 -07001557 std::vector<JDWP::ObjectId>& thread_ids_;
Elliott Hughesa2155262011-11-16 16:26:58 -08001558 };
1559
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001560 ScopedObjectAccessUnchecked soa(Thread::Current());
Elliott Hughescaf76542012-06-28 16:08:22 -07001561 Object* thread_group = gRegistry->Get<Object*>(thread_group_id);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001562 ThreadListVisitor tlv(soa, thread_group, thread_ids);
Ian Rogers50b35e22012-10-04 10:09:15 -07001563 MutexLock mu(soa.Self(), *Locks::thread_list_lock_);
Elliott Hughesf8349362012-06-18 15:00:06 -07001564 Runtime::Current()->GetThreadList()->ForEach(ThreadListVisitor::Visit, &tlv);
Elliott Hughescaf76542012-06-28 16:08:22 -07001565}
Elliott Hughesa2155262011-11-16 16:26:58 -08001566
Elliott Hughescaf76542012-06-28 16:08:22 -07001567void Dbg::GetChildThreadGroups(JDWP::ObjectId thread_group_id, std::vector<JDWP::ObjectId>& child_thread_group_ids) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001568 ScopedObjectAccess soa(Thread::Current());
Elliott Hughescaf76542012-06-28 16:08:22 -07001569 Object* thread_group = gRegistry->Get<Object*>(thread_group_id);
1570
1571 // Get the ArrayList<ThreadGroup> "groups" out of this thread group...
1572 Field* groups_field = thread_group->GetClass()->FindInstanceField("groups", "Ljava/util/List;");
1573 Object* groups_array_list = groups_field->GetObject(thread_group);
1574
1575 // Get the array and size out of the ArrayList<ThreadGroup>...
1576 Field* array_field = groups_array_list->GetClass()->FindInstanceField("array", "[Ljava/lang/Object;");
1577 Field* size_field = groups_array_list->GetClass()->FindInstanceField("size", "I");
1578 ObjectArray<Object>* groups_array = array_field->GetObject(groups_array_list)->AsObjectArray<Object>();
1579 const int32_t size = size_field->GetInt(groups_array_list);
1580
1581 // Copy the first 'size' elements out of the array into the result.
1582 for (int32_t i = 0; i < size; ++i) {
1583 child_thread_group_ids.push_back(gRegistry->Add(groups_array->Get(i)));
Elliott Hughesa2155262011-11-16 16:26:58 -08001584 }
1585}
1586
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001587static int GetStackDepth(Thread* thread)
Ian Rogersb726dcb2012-09-05 08:57:23 -07001588 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Ian Rogers0399dde2012-06-06 17:09:28 -07001589 struct CountStackDepthVisitor : public StackVisitor {
1590 CountStackDepthVisitor(const ManagedStack* stack,
Ian Rogers306057f2012-11-26 12:45:53 -08001591 const std::deque<InstrumentationStackFrame>* instrumentation_stack)
jeffhao725a9572012-11-13 18:20:12 -08001592 : StackVisitor(stack, instrumentation_stack, NULL), depth(0) {}
Ian Rogers0399dde2012-06-06 17:09:28 -07001593
1594 bool VisitFrame() {
1595 if (!GetMethod()->IsRuntimeMethod()) {
Elliott Hughesf8a2df72011-12-01 12:19:54 -08001596 ++depth;
1597 }
Elliott Hughes530fa002012-03-12 11:44:49 -07001598 return true;
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001599 }
1600 size_t depth;
1601 };
Elliott Hughes08fc03a2012-06-26 17:34:00 -07001602
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001603 if (kIsDebugBuild) {
Ian Rogers50b35e22012-10-04 10:09:15 -07001604 MutexLock mu(Thread::Current(), *Locks::thread_suspend_count_lock_);
jeffhao09bfc6a2012-12-11 18:11:43 -08001605 CHECK(thread == Thread::Current() || thread->IsSuspended());
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001606 }
jeffhao725a9572012-11-13 18:20:12 -08001607 CountStackDepthVisitor visitor(thread->GetManagedStack(), thread->GetInstrumentationStack());
Ian Rogers0399dde2012-06-06 17:09:28 -07001608 visitor.WalkStack();
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001609 return visitor.depth;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001610}
1611
Elliott Hughes221229c2013-01-08 18:17:50 -08001612JDWP::JdwpError Dbg::GetThreadFrameCount(JDWP::ObjectId thread_id, size_t& result) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001613 ScopedObjectAccess soa(Thread::Current());
jeffhaoa77f0f62012-12-05 17:19:31 -08001614 MutexLock mu(soa.Self(), *Locks::thread_list_lock_);
Elliott Hughes221229c2013-01-08 18:17:50 -08001615 Thread* thread;
1616 JDWP::JdwpError error = DecodeThread(soa, thread_id, thread);
1617 if (error != JDWP::ERR_NONE) {
1618 return error;
1619 }
1620 result = GetStackDepth(thread);
1621 return JDWP::ERR_NONE;
Elliott Hughes86964332012-02-15 19:37:42 -08001622}
1623
Ian Rogers306057f2012-11-26 12:45:53 -08001624JDWP::JdwpError Dbg::GetThreadFrames(JDWP::ObjectId thread_id, size_t start_frame,
1625 size_t frame_count, JDWP::ExpandBuf* buf) {
Elliott Hughes6e9d22c2012-06-22 15:02:37 -07001626 class GetFrameVisitor : public StackVisitor {
1627 public:
Ian Rogers306057f2012-11-26 12:45:53 -08001628 GetFrameVisitor(const ManagedStack* stack,
1629 const std::deque<InstrumentationStackFrame>* instrumentation_stack,
Elliott Hughes6e9d22c2012-06-22 15:02:37 -07001630 size_t start_frame, size_t frame_count, JDWP::ExpandBuf* buf)
Ian Rogersb726dcb2012-09-05 08:57:23 -07001631 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_)
jeffhao725a9572012-11-13 18:20:12 -08001632 : StackVisitor(stack, instrumentation_stack, NULL), depth_(0),
Elliott Hughes6e9d22c2012-06-22 15:02:37 -07001633 start_frame_(start_frame), frame_count_(frame_count), buf_(buf) {
1634 expandBufAdd4BE(buf_, frame_count_);
Elliott Hughes03181a82011-11-17 17:22:21 -08001635 }
Ian Rogers0399dde2012-06-06 17:09:28 -07001636
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001637 // TODO: Enable annotalysis. We know lock is held in constructor, but abstraction confuses
1638 // annotalysis.
1639 virtual bool VisitFrame() NO_THREAD_SAFETY_ANALYSIS {
Ian Rogers0399dde2012-06-06 17:09:28 -07001640 if (GetMethod()->IsRuntimeMethod()) {
Elliott Hughes530fa002012-03-12 11:44:49 -07001641 return true; // The debugger can't do anything useful with a frame that has no Method*.
Elliott Hughes03181a82011-11-17 17:22:21 -08001642 }
Elliott Hughes6e9d22c2012-06-22 15:02:37 -07001643 if (depth_ >= start_frame_ + frame_count_) {
Elliott Hughes530fa002012-03-12 11:44:49 -07001644 return false;
Elliott Hughes03181a82011-11-17 17:22:21 -08001645 }
Elliott Hughes6e9d22c2012-06-22 15:02:37 -07001646 if (depth_ >= start_frame_) {
1647 JDWP::FrameId frame_id(GetFrameId());
1648 JDWP::JdwpLocation location;
1649 SetLocation(location, GetMethod(), GetDexPc());
Elliott Hughes7baf96f2012-06-22 16:33:50 -07001650 VLOG(jdwp) << StringPrintf(" Frame %3zd: id=%3lld ", depth_, frame_id) << location;
Elliott Hughes6e9d22c2012-06-22 15:02:37 -07001651 expandBufAdd8BE(buf_, frame_id);
1652 expandBufAddLocation(buf_, location);
1653 }
1654 ++depth_;
Elliott Hughes530fa002012-03-12 11:44:49 -07001655 return true;
Elliott Hughes03181a82011-11-17 17:22:21 -08001656 }
Elliott Hughes6e9d22c2012-06-22 15:02:37 -07001657
1658 private:
1659 size_t depth_;
1660 const size_t start_frame_;
1661 const size_t frame_count_;
1662 JDWP::ExpandBuf* buf_;
Elliott Hughes03181a82011-11-17 17:22:21 -08001663 };
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001664
Elliott Hughes221229c2013-01-08 18:17:50 -08001665 // Caller already checked thread is suspended.
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001666 ScopedObjectAccessUnchecked soa(Thread::Current());
jeffhaoa77f0f62012-12-05 17:19:31 -08001667 MutexLock mu(soa.Self(), *Locks::thread_list_lock_);
Elliott Hughes221229c2013-01-08 18:17:50 -08001668 Thread* thread;
1669 JDWP::JdwpError error = DecodeThread(soa, thread_id, thread);
1670 if (error != JDWP::ERR_NONE) {
1671 return error;
1672 }
Ian Rogers306057f2012-11-26 12:45:53 -08001673 GetFrameVisitor visitor(thread->GetManagedStack(), thread->GetInstrumentationStack(),
1674 start_frame, frame_count, buf);
Ian Rogers0399dde2012-06-06 17:09:28 -07001675 visitor.WalkStack();
Elliott Hughes6e9d22c2012-06-22 15:02:37 -07001676 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001677}
1678
1679JDWP::ObjectId Dbg::GetThreadSelfId() {
Mathieu Chartierdbe6f462012-09-25 16:54:50 -07001680 ScopedObjectAccessUnchecked soa(Thread::Current());
Ian Rogerscfaa4552012-11-26 21:00:08 -08001681 return gRegistry->Add(soa.Self()->GetPeer());
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001682}
1683
Elliott Hughes475fc232011-10-25 15:00:35 -07001684void Dbg::SuspendVM() {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001685 Runtime::Current()->GetThreadList()->SuspendAllForDebugger();
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001686}
1687
1688void Dbg::ResumeVM() {
Elliott Hughesc61a2672012-06-21 14:52:29 -07001689 Runtime::Current()->GetThreadList()->UndoDebuggerSuspensions();
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001690}
1691
Elliott Hughes221229c2013-01-08 18:17:50 -08001692JDWP::JdwpError Dbg::SuspendThread(JDWP::ObjectId thread_id, bool request_suspension) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001693
1694 bool timeout;
1695 ScopedLocalRef<jobject> peer(Thread::Current()->GetJniEnv(), NULL);
1696 {
1697 ScopedObjectAccess soa(Thread::Current());
Elliott Hughes221229c2013-01-08 18:17:50 -08001698 peer.reset(soa.AddLocalReference<jobject>(gRegistry->Get<Object*>(thread_id)));
Elliott Hughes4e235312011-12-02 11:34:15 -08001699 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001700 if (peer.get() == NULL) {
Elliott Hughes221229c2013-01-08 18:17:50 -08001701 LOG(WARNING) << "No such thread for suspend: " << thread_id;
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001702 return JDWP::ERR_THREAD_NOT_ALIVE;
1703 }
1704 // Suspend thread to build stack trace.
1705 Thread* thread = Thread::SuspendForDebugger(peer.get(), request_suspension, &timeout);
1706 if (thread != NULL) {
1707 return JDWP::ERR_NONE;
1708 } else if (timeout) {
1709 return JDWP::ERR_INTERNAL;
1710 } else {
1711 return JDWP::ERR_THREAD_NOT_ALIVE;
1712 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001713}
1714
Elliott Hughes221229c2013-01-08 18:17:50 -08001715void Dbg::ResumeThread(JDWP::ObjectId thread_id) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001716 ScopedObjectAccessUnchecked soa(Thread::Current());
Elliott Hughes221229c2013-01-08 18:17:50 -08001717 Object* peer = gRegistry->Get<Object*>(thread_id);
jeffhaoa77f0f62012-12-05 17:19:31 -08001718 Thread* thread;
1719 {
1720 MutexLock mu(soa.Self(), *Locks::thread_list_lock_);
1721 thread = Thread::FromManagedThread(soa, peer);
1722 }
Elliott Hughes4e235312011-12-02 11:34:15 -08001723 if (thread == NULL) {
1724 LOG(WARNING) << "No such thread for resume: " << peer;
1725 return;
1726 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001727 bool needs_resume;
1728 {
Ian Rogers50b35e22012-10-04 10:09:15 -07001729 MutexLock mu2(soa.Self(), *Locks::thread_suspend_count_lock_);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001730 needs_resume = thread->GetSuspendCount() > 0;
1731 }
1732 if (needs_resume) {
Elliott Hughes546b9862012-06-20 16:06:13 -07001733 Runtime::Current()->GetThreadList()->Resume(thread, true);
1734 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001735}
1736
1737void Dbg::SuspendSelf() {
Elliott Hughes475fc232011-10-25 15:00:35 -07001738 Runtime::Current()->GetThreadList()->SuspendSelfForDebugger();
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001739}
1740
Ian Rogers0399dde2012-06-06 17:09:28 -07001741struct GetThisVisitor : public StackVisitor {
Ian Rogers306057f2012-11-26 12:45:53 -08001742 GetThisVisitor(const ManagedStack* stack,
1743 const std::deque<InstrumentationStackFrame>* instrumentation_stack,
Elliott Hughes88d63092013-01-09 09:55:54 -08001744 Context* context, JDWP::FrameId frame_id)
Ian Rogersb726dcb2012-09-05 08:57:23 -07001745 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_)
Elliott Hughes88d63092013-01-09 09:55:54 -08001746 : StackVisitor(stack, instrumentation_stack, context), this_object(NULL), frame_id(frame_id) {}
Ian Rogers0399dde2012-06-06 17:09:28 -07001747
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001748 // TODO: Enable annotalysis. We know lock is held in constructor, but abstraction confuses
1749 // annotalysis.
1750 virtual bool VisitFrame() NO_THREAD_SAFETY_ANALYSIS {
Elliott Hughes6e9d22c2012-06-22 15:02:37 -07001751 if (frame_id != GetFrameId()) {
Ian Rogers0399dde2012-06-06 17:09:28 -07001752 return true; // continue
1753 }
Mathieu Chartier66f19252012-09-18 08:57:04 -07001754 AbstractMethod* m = GetMethod();
Ian Rogers0399dde2012-06-06 17:09:28 -07001755 if (m->IsNative() || m->IsStatic()) {
Elliott Hughes6e9d22c2012-06-22 15:02:37 -07001756 this_object = NULL;
Ian Rogers0399dde2012-06-06 17:09:28 -07001757 } else {
1758 uint16_t reg = DemangleSlot(0, m);
Ian Rogers2bcb4a42012-11-08 10:39:18 -08001759 this_object = reinterpret_cast<Object*>(GetVReg(m, reg, kReferenceVReg));
Ian Rogers0399dde2012-06-06 17:09:28 -07001760 }
1761 return false;
Elliott Hughes86b00102011-12-05 17:54:26 -08001762 }
Ian Rogers0399dde2012-06-06 17:09:28 -07001763
Elliott Hughes6e9d22c2012-06-22 15:02:37 -07001764 Object* this_object;
1765 JDWP::FrameId frame_id;
Ian Rogers0399dde2012-06-06 17:09:28 -07001766};
1767
Mathieu Chartier66f19252012-09-18 08:57:04 -07001768static Object* GetThis(Thread* self, AbstractMethod* m, size_t frame_id)
Ian Rogersb726dcb2012-09-05 08:57:23 -07001769 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Elliott Hughescaf76542012-06-28 16:08:22 -07001770 // TODO: should we return the 'this' we passed through to non-static native methods?
Ian Rogers0399dde2012-06-06 17:09:28 -07001771 if (m->IsNative() || m->IsStatic()) {
1772 return NULL;
1773 }
Elliott Hughescaf76542012-06-28 16:08:22 -07001774
Ian Rogers0399dde2012-06-06 17:09:28 -07001775 UniquePtr<Context> context(Context::Create());
jeffhao725a9572012-11-13 18:20:12 -08001776 GetThisVisitor visitor(self->GetManagedStack(), self->GetInstrumentationStack(), context.get(), frame_id);
Elliott Hughescaf76542012-06-28 16:08:22 -07001777 visitor.WalkStack();
1778 return visitor.this_object;
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08001779}
1780
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001781JDWP::JdwpError Dbg::GetThisObject(JDWP::ObjectId thread_id, JDWP::FrameId frame_id,
1782 JDWP::ObjectId* result) {
1783 ScopedObjectAccessUnchecked soa(Thread::Current());
1784 Thread* thread;
1785 {
Ian Rogers50b35e22012-10-04 10:09:15 -07001786 MutexLock mu(soa.Self(), *Locks::thread_list_lock_);
Elliott Hughes221229c2013-01-08 18:17:50 -08001787 JDWP::JdwpError error = DecodeThread(soa, thread_id, thread);
1788 if (error != JDWP::ERR_NONE) {
1789 return error;
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001790 }
Ian Rogers50b35e22012-10-04 10:09:15 -07001791 MutexLock mu2(soa.Self(), *Locks::thread_suspend_count_lock_);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001792 if (!thread->IsSuspended()) {
1793 return JDWP::ERR_THREAD_NOT_SUSPENDED;
1794 }
Elliott Hughes6e9d22c2012-06-22 15:02:37 -07001795 }
Elliott Hughescaf76542012-06-28 16:08:22 -07001796 UniquePtr<Context> context(Context::Create());
jeffhao725a9572012-11-13 18:20:12 -08001797 GetThisVisitor visitor(thread->GetManagedStack(), thread->GetInstrumentationStack(), context.get(), frame_id);
Ian Rogers0399dde2012-06-06 17:09:28 -07001798 visitor.WalkStack();
Elliott Hughes6e9d22c2012-06-22 15:02:37 -07001799 *result = gRegistry->Add(visitor.this_object);
1800 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001801}
1802
Elliott Hughes88d63092013-01-09 09:55:54 -08001803void Dbg::GetLocalValue(JDWP::ObjectId thread_id, JDWP::FrameId frame_id, int slot, JDWP::JdwpTag tag,
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001804 uint8_t* buf, size_t width) {
Ian Rogers0399dde2012-06-06 17:09:28 -07001805 struct GetLocalVisitor : public StackVisitor {
Ian Rogers306057f2012-11-26 12:45:53 -08001806 GetLocalVisitor(const ManagedStack* stack,
1807 const std::deque<InstrumentationStackFrame>* instrumentation_stack,
Elliott Hughes88d63092013-01-09 09:55:54 -08001808 Context* context, JDWP::FrameId frame_id, int slot, JDWP::JdwpTag tag,
Ian Rogersca190662012-06-26 15:45:57 -07001809 uint8_t* buf, size_t width)
Ian Rogersb726dcb2012-09-05 08:57:23 -07001810 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_)
Elliott Hughes88d63092013-01-09 09:55:54 -08001811 : StackVisitor(stack, instrumentation_stack, context), frame_id_(frame_id), slot_(slot), tag_(tag),
Ian Rogersca190662012-06-26 15:45:57 -07001812 buf_(buf), width_(width) {}
1813
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001814 // TODO: Enable annotalysis. We know lock is held in constructor, but abstraction confuses
1815 // annotalysis.
1816 bool VisitFrame() NO_THREAD_SAFETY_ANALYSIS {
Ian Rogers0399dde2012-06-06 17:09:28 -07001817 if (GetFrameId() != frame_id_) {
1818 return true; // Not our frame, carry on.
Elliott Hughesdbb40792011-11-18 17:05:22 -08001819 }
Ian Rogers0399dde2012-06-06 17:09:28 -07001820 // TODO: check that the tag is compatible with the actual type of the slot!
Mathieu Chartier66f19252012-09-18 08:57:04 -07001821 AbstractMethod* m = GetMethod();
Ian Rogers0399dde2012-06-06 17:09:28 -07001822 uint16_t reg = DemangleSlot(slot_, m);
Elliott Hughesdbb40792011-11-18 17:05:22 -08001823
Ian Rogers0399dde2012-06-06 17:09:28 -07001824 switch (tag_) {
1825 case JDWP::JT_BOOLEAN:
1826 {
1827 CHECK_EQ(width_, 1U);
Ian Rogers2bcb4a42012-11-08 10:39:18 -08001828 uint32_t intVal = GetVReg(m, reg, kIntVReg);
Ian Rogers0399dde2012-06-06 17:09:28 -07001829 VLOG(jdwp) << "get boolean local " << reg << " = " << intVal;
1830 JDWP::Set1(buf_+1, intVal != 0);
1831 }
1832 break;
1833 case JDWP::JT_BYTE:
1834 {
1835 CHECK_EQ(width_, 1U);
Ian Rogers2bcb4a42012-11-08 10:39:18 -08001836 uint32_t intVal = GetVReg(m, reg, kIntVReg);
Ian Rogers0399dde2012-06-06 17:09:28 -07001837 VLOG(jdwp) << "get byte local " << reg << " = " << intVal;
1838 JDWP::Set1(buf_+1, intVal);
1839 }
1840 break;
1841 case JDWP::JT_SHORT:
1842 case JDWP::JT_CHAR:
1843 {
1844 CHECK_EQ(width_, 2U);
Ian Rogers2bcb4a42012-11-08 10:39:18 -08001845 uint32_t intVal = GetVReg(m, reg, kIntVReg);
Ian Rogers0399dde2012-06-06 17:09:28 -07001846 VLOG(jdwp) << "get short/char local " << reg << " = " << intVal;
1847 JDWP::Set2BE(buf_+1, intVal);
1848 }
1849 break;
1850 case JDWP::JT_INT:
Ian Rogers2bcb4a42012-11-08 10:39:18 -08001851 {
1852 CHECK_EQ(width_, 4U);
1853 uint32_t intVal = GetVReg(m, reg, kIntVReg);
1854 VLOG(jdwp) << "get int local " << reg << " = " << intVal;
1855 JDWP::Set4BE(buf_+1, intVal);
1856 }
1857 break;
Ian Rogers0399dde2012-06-06 17:09:28 -07001858 case JDWP::JT_FLOAT:
1859 {
1860 CHECK_EQ(width_, 4U);
Ian Rogers2bcb4a42012-11-08 10:39:18 -08001861 uint32_t intVal = GetVReg(m, reg, kFloatVReg);
Ian Rogers0399dde2012-06-06 17:09:28 -07001862 VLOG(jdwp) << "get int/float local " << reg << " = " << intVal;
1863 JDWP::Set4BE(buf_+1, intVal);
1864 }
1865 break;
1866 case JDWP::JT_ARRAY:
1867 {
1868 CHECK_EQ(width_, sizeof(JDWP::ObjectId));
Ian Rogers2bcb4a42012-11-08 10:39:18 -08001869 Object* o = reinterpret_cast<Object*>(GetVReg(m, reg, kReferenceVReg));
Ian Rogers0399dde2012-06-06 17:09:28 -07001870 VLOG(jdwp) << "get array local " << reg << " = " << o;
1871 if (!Runtime::Current()->GetHeap()->IsHeapAddress(o)) {
1872 LOG(FATAL) << "Register " << reg << " expected to hold array: " << o;
1873 }
1874 JDWP::SetObjectId(buf_+1, gRegistry->Add(o));
1875 }
1876 break;
1877 case JDWP::JT_CLASS_LOADER:
1878 case JDWP::JT_CLASS_OBJECT:
1879 case JDWP::JT_OBJECT:
1880 case JDWP::JT_STRING:
1881 case JDWP::JT_THREAD:
1882 case JDWP::JT_THREAD_GROUP:
1883 {
1884 CHECK_EQ(width_, sizeof(JDWP::ObjectId));
Ian Rogers2bcb4a42012-11-08 10:39:18 -08001885 Object* o = reinterpret_cast<Object*>(GetVReg(m, reg, kReferenceVReg));
Ian Rogers0399dde2012-06-06 17:09:28 -07001886 VLOG(jdwp) << "get object local " << reg << " = " << o;
1887 if (!Runtime::Current()->GetHeap()->IsHeapAddress(o)) {
1888 LOG(FATAL) << "Register " << reg << " expected to hold object: " << o;
1889 }
1890 tag_ = TagFromObject(o);
1891 JDWP::SetObjectId(buf_+1, gRegistry->Add(o));
1892 }
1893 break;
1894 case JDWP::JT_DOUBLE:
Ian Rogers2bcb4a42012-11-08 10:39:18 -08001895 {
1896 CHECK_EQ(width_, 8U);
1897 uint32_t lo = GetVReg(m, reg, kDoubleLoVReg);
1898 uint64_t hi = GetVReg(m, reg + 1, kDoubleHiVReg);
1899 uint64_t longVal = (hi << 32) | lo;
1900 VLOG(jdwp) << "get double/long local " << hi << ":" << lo << " = " << longVal;
1901 JDWP::Set8BE(buf_+1, longVal);
1902 }
1903 break;
Ian Rogers0399dde2012-06-06 17:09:28 -07001904 case JDWP::JT_LONG:
1905 {
1906 CHECK_EQ(width_, 8U);
Ian Rogers2bcb4a42012-11-08 10:39:18 -08001907 uint32_t lo = GetVReg(m, reg, kLongLoVReg);
1908 uint64_t hi = GetVReg(m, reg + 1, kLongHiVReg);
Ian Rogers0399dde2012-06-06 17:09:28 -07001909 uint64_t longVal = (hi << 32) | lo;
1910 VLOG(jdwp) << "get double/long local " << hi << ":" << lo << " = " << longVal;
1911 JDWP::Set8BE(buf_+1, longVal);
1912 }
1913 break;
1914 default:
1915 LOG(FATAL) << "Unknown tag " << tag_;
1916 break;
1917 }
1918
1919 // Prepend tag, which may have been updated.
1920 JDWP::Set1(buf_, tag_);
1921 return false;
1922 }
1923
1924 const JDWP::FrameId frame_id_;
1925 const int slot_;
1926 JDWP::JdwpTag tag_;
1927 uint8_t* const buf_;
1928 const size_t width_;
1929 };
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001930
1931 ScopedObjectAccessUnchecked soa(Thread::Current());
jeffhaoa77f0f62012-12-05 17:19:31 -08001932 MutexLock mu(soa.Self(), *Locks::thread_list_lock_);
Elliott Hughes221229c2013-01-08 18:17:50 -08001933 Thread* thread;
1934 JDWP::JdwpError error = DecodeThread(soa, thread_id, thread);
1935 if (error != JDWP::ERR_NONE) {
1936 return;
1937 }
Ian Rogers0399dde2012-06-06 17:09:28 -07001938 UniquePtr<Context> context(Context::Create());
jeffhao725a9572012-11-13 18:20:12 -08001939 GetLocalVisitor visitor(thread->GetManagedStack(), thread->GetInstrumentationStack(), context.get(),
Elliott Hughes88d63092013-01-09 09:55:54 -08001940 frame_id, slot, tag, buf, width);
Ian Rogers0399dde2012-06-06 17:09:28 -07001941 visitor.WalkStack();
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001942}
1943
Elliott Hughes88d63092013-01-09 09:55:54 -08001944void Dbg::SetLocalValue(JDWP::ObjectId thread_id, JDWP::FrameId frame_id, int slot, JDWP::JdwpTag tag,
Ian Rogers0399dde2012-06-06 17:09:28 -07001945 uint64_t value, size_t width) {
1946 struct SetLocalVisitor : public StackVisitor {
Ian Rogers306057f2012-11-26 12:45:53 -08001947 SetLocalVisitor(const ManagedStack* stack, const std::deque<InstrumentationStackFrame>* instrumentation_stack, Context* context,
Ian Rogers0399dde2012-06-06 17:09:28 -07001948 JDWP::FrameId frame_id, int slot, JDWP::JdwpTag tag, uint64_t value,
Ian Rogersca190662012-06-26 15:45:57 -07001949 size_t width)
Ian Rogersb726dcb2012-09-05 08:57:23 -07001950 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_)
jeffhao725a9572012-11-13 18:20:12 -08001951 : StackVisitor(stack, instrumentation_stack, context),
Elliott Hughes08fc03a2012-06-26 17:34:00 -07001952 frame_id_(frame_id), slot_(slot), tag_(tag), value_(value), width_(width) {}
Ian Rogersca190662012-06-26 15:45:57 -07001953
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001954 // TODO: Enable annotalysis. We know lock is held in constructor, but abstraction confuses
1955 // annotalysis.
1956 bool VisitFrame() NO_THREAD_SAFETY_ANALYSIS {
Ian Rogers0399dde2012-06-06 17:09:28 -07001957 if (GetFrameId() != frame_id_) {
1958 return true; // Not our frame, carry on.
1959 }
1960 // TODO: check that the tag is compatible with the actual type of the slot!
Mathieu Chartier66f19252012-09-18 08:57:04 -07001961 AbstractMethod* m = GetMethod();
Ian Rogers0399dde2012-06-06 17:09:28 -07001962 uint16_t reg = DemangleSlot(slot_, m);
1963
1964 switch (tag_) {
1965 case JDWP::JT_BOOLEAN:
1966 case JDWP::JT_BYTE:
1967 CHECK_EQ(width_, 1U);
Ian Rogers2bcb4a42012-11-08 10:39:18 -08001968 SetVReg(m, reg, static_cast<uint32_t>(value_), kIntVReg);
Ian Rogers0399dde2012-06-06 17:09:28 -07001969 break;
1970 case JDWP::JT_SHORT:
1971 case JDWP::JT_CHAR:
1972 CHECK_EQ(width_, 2U);
Ian Rogers2bcb4a42012-11-08 10:39:18 -08001973 SetVReg(m, reg, static_cast<uint32_t>(value_), kIntVReg);
Ian Rogers0399dde2012-06-06 17:09:28 -07001974 break;
1975 case JDWP::JT_INT:
Ian Rogers2bcb4a42012-11-08 10:39:18 -08001976 CHECK_EQ(width_, 4U);
1977 SetVReg(m, reg, static_cast<uint32_t>(value_), kIntVReg);
1978 break;
Ian Rogers0399dde2012-06-06 17:09:28 -07001979 case JDWP::JT_FLOAT:
1980 CHECK_EQ(width_, 4U);
Ian Rogers2bcb4a42012-11-08 10:39:18 -08001981 SetVReg(m, reg, static_cast<uint32_t>(value_), kFloatVReg);
Ian Rogers0399dde2012-06-06 17:09:28 -07001982 break;
1983 case JDWP::JT_ARRAY:
1984 case JDWP::JT_OBJECT:
1985 case JDWP::JT_STRING:
1986 {
1987 CHECK_EQ(width_, sizeof(JDWP::ObjectId));
1988 Object* o = gRegistry->Get<Object*>(static_cast<JDWP::ObjectId>(value_));
1989 if (o == kInvalidObject) {
1990 UNIMPLEMENTED(FATAL) << "return an error code when given an invalid object to store";
1991 }
Ian Rogers2bcb4a42012-11-08 10:39:18 -08001992 SetVReg(m, reg, static_cast<uint32_t>(reinterpret_cast<uintptr_t>(o)), kReferenceVReg);
Ian Rogers0399dde2012-06-06 17:09:28 -07001993 }
1994 break;
1995 case JDWP::JT_DOUBLE:
Ian Rogers2bcb4a42012-11-08 10:39:18 -08001996 CHECK_EQ(width_, 8U);
1997 SetVReg(m, reg, static_cast<uint32_t>(value_), kDoubleLoVReg);
1998 SetVReg(m, reg + 1, static_cast<uint32_t>(value_ >> 32), kDoubleHiVReg);
1999 break;
Ian Rogers0399dde2012-06-06 17:09:28 -07002000 case JDWP::JT_LONG:
2001 CHECK_EQ(width_, 8U);
Ian Rogers2bcb4a42012-11-08 10:39:18 -08002002 SetVReg(m, reg, static_cast<uint32_t>(value_), kLongLoVReg);
2003 SetVReg(m, reg + 1, static_cast<uint32_t>(value_ >> 32), kLongHiVReg);
Ian Rogers0399dde2012-06-06 17:09:28 -07002004 break;
2005 default:
2006 LOG(FATAL) << "Unknown tag " << tag_;
2007 break;
2008 }
2009 return false;
2010 }
2011
2012 const JDWP::FrameId frame_id_;
2013 const int slot_;
2014 const JDWP::JdwpTag tag_;
2015 const uint64_t value_;
2016 const size_t width_;
2017 };
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002018
2019 ScopedObjectAccessUnchecked soa(Thread::Current());
jeffhaoa77f0f62012-12-05 17:19:31 -08002020 MutexLock mu(soa.Self(), *Locks::thread_list_lock_);
Elliott Hughes221229c2013-01-08 18:17:50 -08002021 Thread* thread;
2022 JDWP::JdwpError error = DecodeThread(soa, thread_id, thread);
2023 if (error != JDWP::ERR_NONE) {
2024 return;
2025 }
Elliott Hughes08fc03a2012-06-26 17:34:00 -07002026 UniquePtr<Context> context(Context::Create());
jeffhao725a9572012-11-13 18:20:12 -08002027 SetLocalVisitor visitor(thread->GetManagedStack(), thread->GetInstrumentationStack(), context.get(),
Elliott Hughes88d63092013-01-09 09:55:54 -08002028 frame_id, slot, tag, value, width);
Ian Rogers0399dde2012-06-06 17:09:28 -07002029 visitor.WalkStack();
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002030}
2031
Mathieu Chartier66f19252012-09-18 08:57:04 -07002032void Dbg::PostLocationEvent(const AbstractMethod* m, int dex_pc, Object* this_object, int event_flags) {
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08002033 Class* c = m->GetDeclaringClass();
2034
2035 JDWP::JdwpLocation location;
Elliott Hughes74847412012-06-20 18:10:21 -07002036 location.type_tag = c->IsInterface() ? JDWP::TT_INTERFACE : JDWP::TT_CLASS;
2037 location.class_id = gRegistry->Add(c);
2038 location.method_id = ToMethodId(m);
Elliott Hughes972a47b2012-02-21 18:16:06 -08002039 location.dex_pc = m->IsNative() ? -1 : dex_pc;
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08002040
2041 // Note we use "NoReg" so we don't keep track of references that are
2042 // never actually sent to the debugger. 'this_id' is only used to
2043 // compare against registered events...
2044 JDWP::ObjectId this_id = static_cast<JDWP::ObjectId>(reinterpret_cast<uintptr_t>(this_object));
2045 if (gJdwpState->PostLocationEvent(&location, this_id, event_flags)) {
2046 // ...unless there's a registered event, in which case we
2047 // need to really track the class and 'this'.
2048 gRegistry->Add(c);
2049 gRegistry->Add(this_object);
2050 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002051}
2052
Elliott Hughescaf76542012-06-28 16:08:22 -07002053void Dbg::PostException(Thread* thread,
Mathieu Chartier66f19252012-09-18 08:57:04 -07002054 JDWP::FrameId throw_frame_id, AbstractMethod* throw_method, uint32_t throw_dex_pc,
2055 AbstractMethod* catch_method, uint32_t catch_dex_pc, Throwable* exception) {
Elliott Hughesc0f09332012-03-26 13:27:06 -07002056 if (!IsDebuggerActive()) {
Ian Rogers0ad5bb82011-12-07 10:16:32 -08002057 return;
2058 }
Elliott Hughes4740cdf2011-12-07 14:07:12 -08002059
Elliott Hughesd07986f2011-12-06 18:27:45 -08002060 JDWP::JdwpLocation throw_location;
Elliott Hughescaf76542012-06-28 16:08:22 -07002061 SetLocation(throw_location, throw_method, throw_dex_pc);
Elliott Hughesd07986f2011-12-06 18:27:45 -08002062 JDWP::JdwpLocation catch_location;
Elliott Hughescaf76542012-06-28 16:08:22 -07002063 SetLocation(catch_location, catch_method, catch_dex_pc);
Elliott Hughesd07986f2011-12-06 18:27:45 -08002064
2065 // We need 'this' for InstanceOnly filters.
Elliott Hughescaf76542012-06-28 16:08:22 -07002066 UniquePtr<Context> context(Context::Create());
jeffhao725a9572012-11-13 18:20:12 -08002067 GetThisVisitor visitor(thread->GetManagedStack(), thread->GetInstrumentationStack(), context.get(), throw_frame_id);
Elliott Hughescaf76542012-06-28 16:08:22 -07002068 visitor.WalkStack();
2069 JDWP::ObjectId this_id = gRegistry->Add(visitor.this_object);
Elliott Hughesd07986f2011-12-06 18:27:45 -08002070
2071 /*
2072 * Hand the event to the JDWP exception handler. Note we're using the
2073 * "NoReg" objectID on the exception, which is not strictly correct --
2074 * the exception object WILL be passed up to the debugger if the
2075 * debugger is interested in the event. We do this because the current
2076 * implementation of the debugger object registry never throws anything
2077 * away, and some people were experiencing a fatal build up of exception
2078 * objects when dealing with certain libraries.
2079 */
2080 JDWP::ObjectId exception_id = static_cast<JDWP::ObjectId>(reinterpret_cast<uintptr_t>(exception));
2081 JDWP::RefTypeId exception_class_id = gRegistry->Add(exception->GetClass());
2082
2083 gJdwpState->PostException(&throw_location, exception_id, exception_class_id, &catch_location, this_id);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002084}
2085
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002086void Dbg::PostClassPrepare(Class* c) {
Elliott Hughesc0f09332012-03-26 13:27:06 -07002087 if (!IsDebuggerActive()) {
Elliott Hughes4740cdf2011-12-07 14:07:12 -08002088 return;
2089 }
2090
Elliott Hughes3d30d9b2011-12-07 17:35:48 -08002091 // OLD-TODO - we currently always send both "verified" and "prepared" since
Elliott Hughes4740cdf2011-12-07 14:07:12 -08002092 // debuggers seem to like that. There might be some advantage to honesty,
2093 // since the class may not yet be verified.
2094 int state = JDWP::CS_VERIFIED | JDWP::CS_PREPARED;
2095 JDWP::JdwpTypeTag tag = c->IsInterface() ? JDWP::TT_INTERFACE : JDWP::TT_CLASS;
2096 gJdwpState->PostClassPrepare(tag, gRegistry->Add(c), ClassHelper(c).GetDescriptor(), state);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002097}
2098
Elliott Hughescaf76542012-06-28 16:08:22 -07002099void Dbg::UpdateDebugger(int32_t dex_pc, Thread* self) {
Elliott Hughesc0f09332012-03-26 13:27:06 -07002100 if (!IsDebuggerActive() || dex_pc == -2 /* fake method exit */) {
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08002101 return;
2102 }
2103
Elliott Hughescaf76542012-06-28 16:08:22 -07002104 size_t frame_id;
Mathieu Chartier66f19252012-09-18 08:57:04 -07002105 AbstractMethod* m = self->GetCurrentMethod(NULL, &frame_id);
Elliott Hughescaf76542012-06-28 16:08:22 -07002106 //LOG(INFO) << "UpdateDebugger " << PrettyMethod(m) << "@" << dex_pc << " frame " << frame_id;
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08002107
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08002108 if (dex_pc == -1) {
Elliott Hughes2aa2e392012-02-17 17:15:43 -08002109 // We use a pc of -1 to represent method entry, since we might branch back to pc 0 later.
2110 // This means that for this special notification, there can't be anything else interesting
2111 // going on, so we're done already.
Elliott Hughescaf76542012-06-28 16:08:22 -07002112 Dbg::PostLocationEvent(m, 0, GetThis(self, m, frame_id), kMethodEntry);
Elliott Hughes2aa2e392012-02-17 17:15:43 -08002113 return;
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08002114 }
2115
Elliott Hughes2aa2e392012-02-17 17:15:43 -08002116 int event_flags = 0;
2117
Elliott Hughes86964332012-02-15 19:37:42 -08002118 if (IsBreakpoint(m, dex_pc)) {
2119 event_flags |= kBreakpoint;
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08002120 }
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08002121
jeffhao09bfc6a2012-12-11 18:11:43 -08002122 {
2123 // If the debugger is single-stepping one of our threads, check to
2124 // see if we're that thread and we've reached a step point.
2125 MutexLock mu(Thread::Current(), *Locks::breakpoint_lock_);
2126 if (gSingleStepControl.is_active && gSingleStepControl.thread == self) {
2127 CHECK(!m->IsNative());
2128 if (gSingleStepControl.step_depth == JDWP::SD_INTO) {
2129 // Step into method calls. We break when the line number
2130 // or method pointer changes. If we're in SS_MIN mode, we
2131 // always stop.
2132 if (gSingleStepControl.method != m) {
2133 event_flags |= kSingleStep;
2134 VLOG(jdwp) << "SS new method";
2135 } else if (gSingleStepControl.step_size == JDWP::SS_MIN) {
Elliott Hughes86964332012-02-15 19:37:42 -08002136 event_flags |= kSingleStep;
2137 VLOG(jdwp) << "SS new instruction";
Elliott Hughes2435a572012-02-17 16:07:41 -08002138 } else if (gSingleStepControl.dex_pcs.find(dex_pc) == gSingleStepControl.dex_pcs.end()) {
2139 event_flags |= kSingleStep;
2140 VLOG(jdwp) << "SS new line";
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08002141 }
jeffhao09bfc6a2012-12-11 18:11:43 -08002142 } else if (gSingleStepControl.step_depth == JDWP::SD_OVER) {
2143 // Step over method calls. We break when the line number is
2144 // different and the frame depth is <= the original frame
2145 // depth. (We can't just compare on the method, because we
2146 // might get unrolled past it by an exception, and it's tricky
2147 // to identify recursion.)
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08002148
jeffhao09bfc6a2012-12-11 18:11:43 -08002149 int stack_depth = GetStackDepth(self);
Elliott Hughes86964332012-02-15 19:37:42 -08002150
jeffhao09bfc6a2012-12-11 18:11:43 -08002151 if (stack_depth < gSingleStepControl.stack_depth) {
2152 // popped up one or more frames, always trigger
2153 event_flags |= kSingleStep;
2154 VLOG(jdwp) << "SS method pop";
2155 } else if (stack_depth == gSingleStepControl.stack_depth) {
2156 // same depth, see if we moved
2157 if (gSingleStepControl.step_size == JDWP::SS_MIN) {
2158 event_flags |= kSingleStep;
2159 VLOG(jdwp) << "SS new instruction";
2160 } else if (gSingleStepControl.dex_pcs.find(dex_pc) == gSingleStepControl.dex_pcs.end()) {
2161 event_flags |= kSingleStep;
2162 VLOG(jdwp) << "SS new line";
2163 }
2164 }
2165 } else {
2166 CHECK_EQ(gSingleStepControl.step_depth, JDWP::SD_OUT);
2167 // Return from the current method. We break when the frame
2168 // depth pops up.
2169
2170 // This differs from the "method exit" break in that it stops
2171 // with the PC at the next instruction in the returned-to
2172 // function, rather than the end of the returning function.
2173
2174 int stack_depth = GetStackDepth(self);
2175 if (stack_depth < gSingleStepControl.stack_depth) {
2176 event_flags |= kSingleStep;
2177 VLOG(jdwp) << "SS method pop";
2178 }
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08002179 }
2180 }
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08002181 }
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08002182
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08002183 // Check to see if this is a "return" instruction. JDWP says we should
2184 // send the event *after* the code has been executed, but it also says
2185 // the location we provide is the last instruction. Since the "return"
2186 // instruction has no interesting side effects, we should be safe.
2187 // (We can't just move this down to the returnFromMethod label because
2188 // we potentially need to combine it with other events.)
2189 // We're also not supposed to generate a method exit event if the method
2190 // terminates "with a thrown exception".
Elliott Hughes86964332012-02-15 19:37:42 -08002191 if (dex_pc >= 0) {
2192 const DexFile::CodeItem* code_item = MethodHelper(m).GetCodeItem();
Elliott Hughescaf76542012-06-28 16:08:22 -07002193 CHECK(code_item != NULL) << PrettyMethod(m) << " @" << dex_pc;
Elliott Hughes86964332012-02-15 19:37:42 -08002194 CHECK_LT(dex_pc, static_cast<int32_t>(code_item->insns_size_in_code_units_));
2195 if (Instruction::At(&code_item->insns_[dex_pc])->IsReturn()) {
2196 event_flags |= kMethodExit;
2197 }
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08002198 }
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08002199
2200 // If there's something interesting going on, see if it matches one
2201 // of the debugger filters.
2202 if (event_flags != 0) {
Elliott Hughescaf76542012-06-28 16:08:22 -07002203 Dbg::PostLocationEvent(m, dex_pc, GetThis(self, m, frame_id), event_flags);
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08002204 }
2205}
2206
Elliott Hughes86964332012-02-15 19:37:42 -08002207void Dbg::WatchLocation(const JDWP::JdwpLocation* location) {
jeffhao09bfc6a2012-12-11 18:11:43 -08002208 MutexLock mu(Thread::Current(), *Locks::breakpoint_lock_);
Mathieu Chartier66f19252012-09-18 08:57:04 -07002209 AbstractMethod* m = FromMethodId(location->method_id);
Elliott Hughes972a47b2012-02-21 18:16:06 -08002210 gBreakpoints.push_back(Breakpoint(m, location->dex_pc));
Elliott Hughes86964332012-02-15 19:37:42 -08002211 VLOG(jdwp) << "Set breakpoint #" << (gBreakpoints.size() - 1) << ": " << gBreakpoints[gBreakpoints.size() - 1];
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002212}
2213
Elliott Hughes86964332012-02-15 19:37:42 -08002214void Dbg::UnwatchLocation(const JDWP::JdwpLocation* location) {
jeffhao09bfc6a2012-12-11 18:11:43 -08002215 MutexLock mu(Thread::Current(), *Locks::breakpoint_lock_);
Mathieu Chartier66f19252012-09-18 08:57:04 -07002216 AbstractMethod* m = FromMethodId(location->method_id);
Elliott Hughes86964332012-02-15 19:37:42 -08002217 for (size_t i = 0; i < gBreakpoints.size(); ++i) {
Elliott Hughes972a47b2012-02-21 18:16:06 -08002218 if (gBreakpoints[i].method == m && gBreakpoints[i].dex_pc == location->dex_pc) {
Elliott Hughes86964332012-02-15 19:37:42 -08002219 VLOG(jdwp) << "Removed breakpoint #" << i << ": " << gBreakpoints[i];
2220 gBreakpoints.erase(gBreakpoints.begin() + i);
2221 return;
2222 }
2223 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002224}
2225
Elliott Hughes221229c2013-01-08 18:17:50 -08002226JDWP::JdwpError Dbg::ConfigureStep(JDWP::ObjectId thread_id, JDWP::JdwpStepSize step_size,
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002227 JDWP::JdwpStepDepth step_depth) {
2228 ScopedObjectAccessUnchecked soa(Thread::Current());
jeffhaoa77f0f62012-12-05 17:19:31 -08002229 MutexLock mu(soa.Self(), *Locks::thread_list_lock_);
Elliott Hughes221229c2013-01-08 18:17:50 -08002230 Thread* thread;
2231 JDWP::JdwpError error = DecodeThread(soa, thread_id, thread);
2232 if (error != JDWP::ERR_NONE) {
2233 return error;
Elliott Hughes2435a572012-02-17 16:07:41 -08002234 }
Elliott Hughes86964332012-02-15 19:37:42 -08002235
jeffhao09bfc6a2012-12-11 18:11:43 -08002236 MutexLock mu2(soa.Self(), *Locks::breakpoint_lock_);
Elliott Hughes86964332012-02-15 19:37:42 -08002237 // TODO: there's no theoretical reason why we couldn't support single-stepping
2238 // of multiple threads at once, but we never did so historically.
2239 if (gSingleStepControl.thread != NULL && thread != gSingleStepControl.thread) {
2240 LOG(WARNING) << "single-step already active for " << *gSingleStepControl.thread
2241 << "; switching to " << *thread;
2242 }
2243
Elliott Hughes2435a572012-02-17 16:07:41 -08002244 //
2245 // Work out what Method* we're in, the current line number, and how deep the stack currently
2246 // is for step-out.
2247 //
2248
Ian Rogers0399dde2012-06-06 17:09:28 -07002249 struct SingleStepStackVisitor : public StackVisitor {
2250 SingleStepStackVisitor(const ManagedStack* stack,
Ian Rogers306057f2012-11-26 12:45:53 -08002251 const std::deque<InstrumentationStackFrame>* instrumentation_stack)
jeffhao09bfc6a2012-12-11 18:11:43 -08002252 EXCLUSIVE_LOCKS_REQUIRED(Locks::breakpoint_lock_)
Ian Rogersb726dcb2012-09-05 08:57:23 -07002253 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_)
jeffhao725a9572012-11-13 18:20:12 -08002254 : StackVisitor(stack, instrumentation_stack, NULL) {
Elliott Hughes86964332012-02-15 19:37:42 -08002255 gSingleStepControl.method = NULL;
2256 gSingleStepControl.stack_depth = 0;
2257 }
Ian Rogersca190662012-06-26 15:45:57 -07002258
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002259 // TODO: Enable annotalysis. We know lock is held in constructor, but abstraction confuses
2260 // annotalysis.
2261 bool VisitFrame() NO_THREAD_SAFETY_ANALYSIS {
jeffhao09bfc6a2012-12-11 18:11:43 -08002262 Locks::breakpoint_lock_->AssertHeld(Thread::Current());
Mathieu Chartier66f19252012-09-18 08:57:04 -07002263 const AbstractMethod* m = GetMethod();
Ian Rogers0399dde2012-06-06 17:09:28 -07002264 if (!m->IsRuntimeMethod()) {
Elliott Hughes86964332012-02-15 19:37:42 -08002265 ++gSingleStepControl.stack_depth;
2266 if (gSingleStepControl.method == NULL) {
Elliott Hughes2435a572012-02-17 16:07:41 -08002267 const DexCache* dex_cache = m->GetDeclaringClass()->GetDexCache();
2268 gSingleStepControl.method = m;
2269 gSingleStepControl.line_number = -1;
2270 if (dex_cache != NULL) {
Ian Rogers4445a7e2012-10-05 17:19:13 -07002271 const DexFile& dex_file = *dex_cache->GetDexFile();
Ian Rogers0399dde2012-06-06 17:09:28 -07002272 gSingleStepControl.line_number = dex_file.GetLineNumFromPC(m, GetDexPc());
Elliott Hughes2435a572012-02-17 16:07:41 -08002273 }
Elliott Hughes86964332012-02-15 19:37:42 -08002274 }
2275 }
Elliott Hughes530fa002012-03-12 11:44:49 -07002276 return true;
Elliott Hughes86964332012-02-15 19:37:42 -08002277 }
2278 };
jeffhao725a9572012-11-13 18:20:12 -08002279 SingleStepStackVisitor visitor(thread->GetManagedStack(), thread->GetInstrumentationStack());
Ian Rogers0399dde2012-06-06 17:09:28 -07002280 visitor.WalkStack();
Elliott Hughes86964332012-02-15 19:37:42 -08002281
Elliott Hughes2435a572012-02-17 16:07:41 -08002282 //
2283 // Find the dex_pc values that correspond to the current line, for line-based single-stepping.
2284 //
2285
2286 struct DebugCallbackContext {
jeffhao09bfc6a2012-12-11 18:11:43 -08002287 DebugCallbackContext() EXCLUSIVE_LOCKS_REQUIRED(Locks::breakpoint_lock_) {
Elliott Hughes2435a572012-02-17 16:07:41 -08002288 last_pc_valid = false;
2289 last_pc = 0;
Elliott Hughes2435a572012-02-17 16:07:41 -08002290 }
2291
jeffhao09bfc6a2012-12-11 18:11:43 -08002292 // TODO: Enable annotalysis. We know lock is held in constructor, but abstraction confuses
2293 // annotalysis.
2294 static bool Callback(void* raw_context, uint32_t address, uint32_t line_number) NO_THREAD_SAFETY_ANALYSIS {
2295 Locks::breakpoint_lock_->AssertHeld(Thread::Current());
Elliott Hughes2435a572012-02-17 16:07:41 -08002296 DebugCallbackContext* context = reinterpret_cast<DebugCallbackContext*>(raw_context);
2297 if (static_cast<int32_t>(line_number) == gSingleStepControl.line_number) {
2298 if (!context->last_pc_valid) {
2299 // Everything from this address until the next line change is ours.
2300 context->last_pc = address;
2301 context->last_pc_valid = true;
2302 }
2303 // Otherwise, if we're already in a valid range for this line,
2304 // just keep going (shouldn't really happen)...
2305 } else if (context->last_pc_valid) { // and the line number is new
2306 // Add everything from the last entry up until here to the set
2307 for (uint32_t dex_pc = context->last_pc; dex_pc < address; ++dex_pc) {
2308 gSingleStepControl.dex_pcs.insert(dex_pc);
2309 }
2310 context->last_pc_valid = false;
2311 }
2312 return false; // There may be multiple entries for any given line.
2313 }
2314
jeffhao09bfc6a2012-12-11 18:11:43 -08002315 // TODO: Enable annotalysis. We know lock is held in constructor, but abstraction confuses
2316 // annotalysis.
2317 ~DebugCallbackContext() NO_THREAD_SAFETY_ANALYSIS {
2318 Locks::breakpoint_lock_->AssertHeld(Thread::Current());
Elliott Hughes2435a572012-02-17 16:07:41 -08002319 // If the line number was the last in the position table...
2320 if (last_pc_valid) {
2321 size_t end = MethodHelper(gSingleStepControl.method).GetCodeItem()->insns_size_in_code_units_;
2322 for (uint32_t dex_pc = last_pc; dex_pc < end; ++dex_pc) {
2323 gSingleStepControl.dex_pcs.insert(dex_pc);
2324 }
2325 }
2326 }
2327
2328 bool last_pc_valid;
2329 uint32_t last_pc;
2330 };
Elliott Hughes3e2e1a22012-02-21 11:33:41 -08002331 gSingleStepControl.dex_pcs.clear();
Mathieu Chartier66f19252012-09-18 08:57:04 -07002332 const AbstractMethod* m = gSingleStepControl.method;
Elliott Hughes3e2e1a22012-02-21 11:33:41 -08002333 if (m->IsNative()) {
2334 gSingleStepControl.line_number = -1;
2335 } else {
2336 DebugCallbackContext context;
2337 MethodHelper mh(m);
2338 mh.GetDexFile().DecodeDebugInfo(mh.GetCodeItem(), m->IsStatic(), m->GetDexMethodIndex(),
2339 DebugCallbackContext::Callback, NULL, &context);
2340 }
Elliott Hughes2435a572012-02-17 16:07:41 -08002341
2342 //
2343 // Everything else...
2344 //
2345
Elliott Hughes86964332012-02-15 19:37:42 -08002346 gSingleStepControl.thread = thread;
2347 gSingleStepControl.step_size = step_size;
2348 gSingleStepControl.step_depth = step_depth;
2349 gSingleStepControl.is_active = true;
2350
Elliott Hughes2435a572012-02-17 16:07:41 -08002351 if (VLOG_IS_ON(jdwp)) {
2352 VLOG(jdwp) << "Single-step thread: " << *gSingleStepControl.thread;
2353 VLOG(jdwp) << "Single-step step size: " << gSingleStepControl.step_size;
2354 VLOG(jdwp) << "Single-step step depth: " << gSingleStepControl.step_depth;
2355 VLOG(jdwp) << "Single-step current method: " << PrettyMethod(gSingleStepControl.method);
2356 VLOG(jdwp) << "Single-step current line: " << gSingleStepControl.line_number;
2357 VLOG(jdwp) << "Single-step current stack depth: " << gSingleStepControl.stack_depth;
2358 VLOG(jdwp) << "Single-step dex_pc values:";
2359 for (std::set<uint32_t>::iterator it = gSingleStepControl.dex_pcs.begin() ; it != gSingleStepControl.dex_pcs.end(); ++it) {
Elliott Hughes229feb72012-02-23 13:33:29 -08002360 VLOG(jdwp) << StringPrintf(" %#x", *it);
Elliott Hughes2435a572012-02-17 16:07:41 -08002361 }
2362 }
2363
2364 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002365}
2366
Elliott Hughes221229c2013-01-08 18:17:50 -08002367void Dbg::UnconfigureStep(JDWP::ObjectId /*thread_id*/) {
jeffhao09bfc6a2012-12-11 18:11:43 -08002368 MutexLock mu(Thread::Current(), *Locks::breakpoint_lock_);
Elliott Hughesf8349362012-06-18 15:00:06 -07002369
Elliott Hughes86964332012-02-15 19:37:42 -08002370 gSingleStepControl.is_active = false;
2371 gSingleStepControl.thread = NULL;
Elliott Hughes2435a572012-02-17 16:07:41 -08002372 gSingleStepControl.dex_pcs.clear();
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002373}
2374
Elliott Hughes45651fd2012-02-21 15:48:20 -08002375static char JdwpTagToShortyChar(JDWP::JdwpTag tag) {
2376 switch (tag) {
2377 default:
2378 LOG(FATAL) << "unknown JDWP tag: " << PrintableChar(tag);
2379
2380 // Primitives.
2381 case JDWP::JT_BYTE: return 'B';
2382 case JDWP::JT_CHAR: return 'C';
2383 case JDWP::JT_FLOAT: return 'F';
2384 case JDWP::JT_DOUBLE: return 'D';
2385 case JDWP::JT_INT: return 'I';
2386 case JDWP::JT_LONG: return 'J';
2387 case JDWP::JT_SHORT: return 'S';
2388 case JDWP::JT_VOID: return 'V';
2389 case JDWP::JT_BOOLEAN: return 'Z';
2390
2391 // Reference types.
2392 case JDWP::JT_ARRAY:
2393 case JDWP::JT_OBJECT:
2394 case JDWP::JT_STRING:
2395 case JDWP::JT_THREAD:
2396 case JDWP::JT_THREAD_GROUP:
2397 case JDWP::JT_CLASS_LOADER:
2398 case JDWP::JT_CLASS_OBJECT:
2399 return 'L';
2400 }
2401}
2402
Elliott Hughes88d63092013-01-09 09:55:54 -08002403JDWP::JdwpError Dbg::InvokeMethod(JDWP::ObjectId thread_id, JDWP::ObjectId object_id,
2404 JDWP::RefTypeId class_id, JDWP::MethodId method_id,
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002405 uint32_t arg_count, uint64_t* arg_values,
2406 JDWP::JdwpTag* arg_types, uint32_t options,
2407 JDWP::JdwpTag* pResultTag, uint64_t* pResultValue,
2408 JDWP::ObjectId* pExceptionId) {
Elliott Hughesd07986f2011-12-06 18:27:45 -08002409 ThreadList* thread_list = Runtime::Current()->GetThreadList();
2410
2411 Thread* targetThread = NULL;
2412 DebugInvokeReq* req = NULL;
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002413 Thread* self = Thread::Current();
Elliott Hughesd07986f2011-12-06 18:27:45 -08002414 {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002415 ScopedObjectAccessUnchecked soa(self);
Ian Rogers50b35e22012-10-04 10:09:15 -07002416 MutexLock mu(soa.Self(), *Locks::thread_list_lock_);
Elliott Hughes221229c2013-01-08 18:17:50 -08002417 JDWP::JdwpError error = DecodeThread(soa, thread_id, targetThread);
2418 if (error != JDWP::ERR_NONE) {
2419 LOG(ERROR) << "InvokeMethod request for invalid thread id " << thread_id;
2420 return error;
Elliott Hughesd07986f2011-12-06 18:27:45 -08002421 }
2422 req = targetThread->GetInvokeReq();
2423 if (!req->ready) {
2424 LOG(ERROR) << "InvokeMethod request for thread not stopped by event: " << *targetThread;
2425 return JDWP::ERR_INVALID_THREAD;
2426 }
2427
2428 /*
2429 * We currently have a bug where we don't successfully resume the
2430 * target thread if the suspend count is too deep. We're expected to
2431 * require one "resume" for each "suspend", but when asked to execute
2432 * a method we have to resume fully and then re-suspend it back to the
2433 * same level. (The easiest way to cause this is to type "suspend"
2434 * multiple times in jdb.)
2435 *
2436 * It's unclear what this means when the event specifies "resume all"
2437 * and some threads are suspended more deeply than others. This is
2438 * a rare problem, so for now we just prevent it from hanging forever
2439 * by rejecting the method invocation request. Without this, we will
2440 * be stuck waiting on a suspended thread.
2441 */
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002442 int suspend_count;
2443 {
Ian Rogers50b35e22012-10-04 10:09:15 -07002444 MutexLock mu2(soa.Self(), *Locks::thread_suspend_count_lock_);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002445 suspend_count = targetThread->GetSuspendCount();
2446 }
Elliott Hughesd07986f2011-12-06 18:27:45 -08002447 if (suspend_count > 1) {
2448 LOG(ERROR) << *targetThread << " suspend count too deep for method invocation: " << suspend_count;
2449 return JDWP::ERR_THREAD_SUSPENDED; // Probably not expected here.
2450 }
2451
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08002452 JDWP::JdwpError status;
Elliott Hughes88d63092013-01-09 09:55:54 -08002453 Object* receiver = gRegistry->Get<Object*>(object_id);
Elliott Hughes45651fd2012-02-21 15:48:20 -08002454 if (receiver == kInvalidObject) {
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08002455 return JDWP::ERR_INVALID_OBJECT;
2456 }
Elliott Hughes45651fd2012-02-21 15:48:20 -08002457
Elliott Hughes221229c2013-01-08 18:17:50 -08002458 Object* thread = gRegistry->Get<Object*>(thread_id);
Elliott Hughes45651fd2012-02-21 15:48:20 -08002459 if (thread == kInvalidObject) {
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08002460 return JDWP::ERR_INVALID_OBJECT;
2461 }
Elliott Hughes45651fd2012-02-21 15:48:20 -08002462 // TODO: check that 'thread' is actually a java.lang.Thread!
2463
Elliott Hughes88d63092013-01-09 09:55:54 -08002464 Class* c = DecodeClass(class_id, status);
Elliott Hughes45651fd2012-02-21 15:48:20 -08002465 if (c == NULL) {
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08002466 return status;
2467 }
Elliott Hughes45651fd2012-02-21 15:48:20 -08002468
Elliott Hughes88d63092013-01-09 09:55:54 -08002469 AbstractMethod* m = FromMethodId(method_id);
Elliott Hughes45651fd2012-02-21 15:48:20 -08002470 if (m->IsStatic() != (receiver == NULL)) {
2471 return JDWP::ERR_INVALID_METHODID;
2472 }
2473 if (m->IsStatic()) {
2474 if (m->GetDeclaringClass() != c) {
2475 return JDWP::ERR_INVALID_METHODID;
2476 }
2477 } else {
2478 if (!m->GetDeclaringClass()->IsAssignableFrom(c)) {
2479 return JDWP::ERR_INVALID_METHODID;
2480 }
2481 }
2482
2483 // Check the argument list matches the method.
2484 MethodHelper mh(m);
2485 if (mh.GetShortyLength() - 1 != arg_count) {
2486 return JDWP::ERR_ILLEGAL_ARGUMENT;
2487 }
2488 const char* shorty = mh.GetShorty();
2489 for (size_t i = 0; i < arg_count; ++i) {
2490 if (shorty[i + 1] != JdwpTagToShortyChar(arg_types[i])) {
2491 return JDWP::ERR_ILLEGAL_ARGUMENT;
2492 }
2493 }
2494
2495 req->receiver_ = receiver;
2496 req->thread_ = thread;
2497 req->class_ = c;
2498 req->method_ = m;
2499 req->arg_count_ = arg_count;
2500 req->arg_values_ = arg_values;
Elliott Hughesd07986f2011-12-06 18:27:45 -08002501 req->options_ = options;
2502 req->invoke_needed_ = true;
2503 }
2504
2505 // The fact that we've released the thread list lock is a bit risky --- if the thread goes
2506 // away we're sitting high and dry -- but we must release this before the ResumeAllThreads
2507 // call, and it's unwise to hold it during WaitForSuspend.
2508
2509 {
2510 /*
2511 * We change our (JDWP thread) status, which should be THREAD_RUNNING,
Elliott Hughes81ff3182012-03-23 20:35:56 -07002512 * so we can suspend for a GC if the invoke request causes us to
Elliott Hughesd07986f2011-12-06 18:27:45 -08002513 * run out of memory. It's also a good idea to change it before locking
2514 * the invokeReq mutex, although that should never be held for long.
2515 */
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002516 self->TransitionFromRunnableToSuspended(kWaitingForDebuggerSend);
Elliott Hughesd07986f2011-12-06 18:27:45 -08002517
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08002518 VLOG(jdwp) << " Transferring control to event thread";
Elliott Hughesd07986f2011-12-06 18:27:45 -08002519 {
Ian Rogers50b35e22012-10-04 10:09:15 -07002520 MutexLock mu(self, req->lock_);
Elliott Hughesd07986f2011-12-06 18:27:45 -08002521
2522 if ((options & JDWP::INVOKE_SINGLE_THREADED) == 0) {
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08002523 VLOG(jdwp) << " Resuming all threads";
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002524 thread_list->UndoDebuggerSuspensions();
Elliott Hughesd07986f2011-12-06 18:27:45 -08002525 } else {
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08002526 VLOG(jdwp) << " Resuming event thread only";
Elliott Hughesd07986f2011-12-06 18:27:45 -08002527 thread_list->Resume(targetThread, true);
2528 }
2529
2530 // Wait for the request to finish executing.
2531 while (req->invoke_needed_) {
Ian Rogersc604d732012-10-14 16:09:54 -07002532 req->cond_.Wait(self);
Elliott Hughesd07986f2011-12-06 18:27:45 -08002533 }
2534 }
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08002535 VLOG(jdwp) << " Control has returned from event thread";
Elliott Hughesd07986f2011-12-06 18:27:45 -08002536
2537 /* wait for thread to re-suspend itself */
Elliott Hughes221229c2013-01-08 18:17:50 -08002538 SuspendThread(thread_id, false /* request_suspension */ );
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002539 self->TransitionFromSuspendedToRunnable();
Elliott Hughesd07986f2011-12-06 18:27:45 -08002540 }
2541
2542 /*
2543 * Suspend the threads. We waited for the target thread to suspend
2544 * itself, so all we need to do is suspend the others.
2545 *
2546 * The suspendAllThreads() call will double-suspend the event thread,
2547 * so we want to resume the target thread once to keep the books straight.
2548 */
2549 if ((options & JDWP::INVOKE_SINGLE_THREADED) == 0) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002550 self->TransitionFromRunnableToSuspended(kWaitingForDebuggerSuspension);
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08002551 VLOG(jdwp) << " Suspending all threads";
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002552 thread_list->SuspendAllForDebugger();
2553 self->TransitionFromSuspendedToRunnable();
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08002554 VLOG(jdwp) << " Resuming event thread to balance the count";
Elliott Hughesd07986f2011-12-06 18:27:45 -08002555 thread_list->Resume(targetThread, true);
2556 }
2557
2558 // Copy the result.
2559 *pResultTag = req->result_tag;
2560 if (IsPrimitiveTag(req->result_tag)) {
Elliott Hughesf24d3ce2012-04-11 17:43:37 -07002561 *pResultValue = req->result_value.GetJ();
Elliott Hughesd07986f2011-12-06 18:27:45 -08002562 } else {
Elliott Hughesf24d3ce2012-04-11 17:43:37 -07002563 *pResultValue = gRegistry->Add(req->result_value.GetL());
Elliott Hughesd07986f2011-12-06 18:27:45 -08002564 }
2565 *pExceptionId = req->exception;
2566 return req->error;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002567}
2568
2569void Dbg::ExecuteMethod(DebugInvokeReq* pReq) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002570 ScopedObjectAccess soa(Thread::Current());
Elliott Hughesd07986f2011-12-06 18:27:45 -08002571
Elliott Hughes81ff3182012-03-23 20:35:56 -07002572 // We can be called while an exception is pending. We need
Elliott Hughesd07986f2011-12-06 18:27:45 -08002573 // to preserve that across the method invocation.
Ian Rogers1f539342012-10-03 21:09:42 -07002574 SirtRef<Throwable> old_exception(soa.Self(), soa.Self()->GetException());
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002575 soa.Self()->ClearException();
Elliott Hughesd07986f2011-12-06 18:27:45 -08002576
2577 // Translate the method through the vtable, unless the debugger wants to suppress it.
Mathieu Chartier66f19252012-09-18 08:57:04 -07002578 AbstractMethod* m = pReq->method_;
Elliott Hughesd07986f2011-12-06 18:27:45 -08002579 if ((pReq->options_ & JDWP::INVOKE_NONVIRTUAL) == 0 && pReq->receiver_ != NULL) {
Mathieu Chartier66f19252012-09-18 08:57:04 -07002580 AbstractMethod* actual_method = pReq->class_->FindVirtualMethodForVirtualOrInterface(pReq->method_);
Elliott Hughes45651fd2012-02-21 15:48:20 -08002581 if (actual_method != m) {
2582 VLOG(jdwp) << "ExecuteMethod translated " << PrettyMethod(m) << " to " << PrettyMethod(actual_method);
2583 m = actual_method;
2584 }
Elliott Hughesd07986f2011-12-06 18:27:45 -08002585 }
Elliott Hughes45651fd2012-02-21 15:48:20 -08002586 VLOG(jdwp) << "ExecuteMethod " << PrettyMethod(m);
Elliott Hughesd07986f2011-12-06 18:27:45 -08002587 CHECK(m != NULL);
2588
2589 CHECK_EQ(sizeof(jvalue), sizeof(uint64_t));
2590
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002591 LOG(INFO) << "self=" << soa.Self() << " pReq->receiver_=" << pReq->receiver_ << " m=" << m
2592 << " #" << pReq->arg_count_ << " " << pReq->arg_values_;
2593 pReq->result_value = InvokeWithJValues(soa, pReq->receiver_, m,
2594 reinterpret_cast<JValue*>(pReq->arg_values_));
Elliott Hughesd07986f2011-12-06 18:27:45 -08002595
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002596 pReq->exception = gRegistry->Add(soa.Self()->GetException());
Elliott Hughesd07986f2011-12-06 18:27:45 -08002597 pReq->result_tag = BasicTagFromDescriptor(MethodHelper(m).GetShorty());
2598 if (pReq->exception != 0) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002599 Object* exc = soa.Self()->GetException();
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08002600 VLOG(jdwp) << " JDWP invocation returning with exception=" << exc << " " << PrettyTypeOf(exc);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002601 soa.Self()->ClearException();
Elliott Hughesf24d3ce2012-04-11 17:43:37 -07002602 pReq->result_value.SetJ(0);
Elliott Hughesd07986f2011-12-06 18:27:45 -08002603 } else if (pReq->result_tag == JDWP::JT_OBJECT) {
2604 /* if no exception thrown, examine object result more closely */
Elliott Hughesf24d3ce2012-04-11 17:43:37 -07002605 JDWP::JdwpTag new_tag = TagFromObject(pReq->result_value.GetL());
Elliott Hughesd07986f2011-12-06 18:27:45 -08002606 if (new_tag != pReq->result_tag) {
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08002607 VLOG(jdwp) << " JDWP promoted result from " << pReq->result_tag << " to " << new_tag;
Elliott Hughesd07986f2011-12-06 18:27:45 -08002608 pReq->result_tag = new_tag;
2609 }
2610
2611 /*
2612 * Register the object. We don't actually need an ObjectId yet,
2613 * but we do need to be sure that the GC won't move or discard the
2614 * object when we switch out of RUNNING. The ObjectId conversion
2615 * will add the object to the "do not touch" list.
2616 *
2617 * We can't use the "tracked allocation" mechanism here because
2618 * the object is going to be handed off to a different thread.
2619 */
Elliott Hughesf24d3ce2012-04-11 17:43:37 -07002620 gRegistry->Add(pReq->result_value.GetL());
Elliott Hughesd07986f2011-12-06 18:27:45 -08002621 }
2622
2623 if (old_exception.get() != NULL) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002624 soa.Self()->SetException(old_exception.get());
Elliott Hughesd07986f2011-12-06 18:27:45 -08002625 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002626}
2627
Elliott Hughesd07986f2011-12-06 18:27:45 -08002628/*
2629 * Register an object ID that might not have been registered previously.
2630 *
2631 * Normally this wouldn't happen -- the conversion to an ObjectId would
2632 * have added the object to the registry -- but in some cases (e.g.
2633 * throwing exceptions) we really want to do the registration late.
2634 */
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002635void Dbg::RegisterObjectId(JDWP::ObjectId id) {
Elliott Hughesd07986f2011-12-06 18:27:45 -08002636 gRegistry->Add(reinterpret_cast<Object*>(id));
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002637}
2638
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07002639/*
2640 * "buf" contains a full JDWP packet, possibly with multiple chunks. We
2641 * need to process each, accumulate the replies, and ship the whole thing
2642 * back.
2643 *
2644 * Returns "true" if we have a reply. The reply buffer is newly allocated,
2645 * and includes the chunk type/length, followed by the data.
2646 *
Elliott Hughes3d30d9b2011-12-07 17:35:48 -08002647 * OLD-TODO: we currently assume that the request and reply include a single
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07002648 * chunk. If this becomes inconvenient we will need to adapt.
2649 */
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002650bool Dbg::DdmHandlePacket(const uint8_t* buf, int dataLen, uint8_t** pReplyBuf, int* pReplyLen) {
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07002651 CHECK_GE(dataLen, 0);
2652
2653 Thread* self = Thread::Current();
2654 JNIEnv* env = self->GetJniEnv();
2655
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07002656 // Create a byte[] corresponding to 'buf'.
Elliott Hughes6a5bd492011-10-28 14:33:57 -07002657 ScopedLocalRef<jbyteArray> dataArray(env, env->NewByteArray(dataLen));
2658 if (dataArray.get() == NULL) {
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07002659 LOG(WARNING) << "byte[] allocation failed: " << dataLen;
2660 env->ExceptionClear();
2661 return false;
2662 }
Elliott Hughes6a5bd492011-10-28 14:33:57 -07002663 env->SetByteArrayRegion(dataArray.get(), 0, dataLen, reinterpret_cast<const jbyte*>(buf));
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07002664
2665 const int kChunkHdrLen = 8;
2666
2667 // Run through and find all chunks. [Currently just find the first.]
Elliott Hughes6a5bd492011-10-28 14:33:57 -07002668 ScopedByteArrayRO contents(env, dataArray.get());
Elliott Hughesf7c3b662011-10-27 12:04:56 -07002669 jint type = JDWP::Get4BE(reinterpret_cast<const uint8_t*>(&contents[0]));
2670 jint length = JDWP::Get4BE(reinterpret_cast<const uint8_t*>(&contents[4]));
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07002671 jint offset = kChunkHdrLen;
2672 if (offset + length > dataLen) {
2673 LOG(WARNING) << StringPrintf("bad chunk found (len=%u pktLen=%d)", length, dataLen);
2674 return false;
2675 }
2676
2677 // Call "private static Chunk dispatch(int type, byte[] data, int offset, int length)".
Elliott Hugheseac76672012-05-24 21:56:51 -07002678 ScopedLocalRef<jobject> chunk(env, env->CallStaticObjectMethod(WellKnownClasses::org_apache_harmony_dalvik_ddmc_DdmServer,
2679 WellKnownClasses::org_apache_harmony_dalvik_ddmc_DdmServer_dispatch,
2680 type, dataArray.get(), offset, length));
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07002681 if (env->ExceptionCheck()) {
2682 LOG(INFO) << StringPrintf("Exception thrown by dispatcher for 0x%08x", type);
2683 env->ExceptionDescribe();
2684 env->ExceptionClear();
2685 return false;
2686 }
2687
Elliott Hughes6a5bd492011-10-28 14:33:57 -07002688 if (chunk.get() == NULL) {
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07002689 return false;
2690 }
2691
2692 /*
2693 * Pull the pieces out of the chunk. We copy the results into a
2694 * newly-allocated buffer that the caller can free. We don't want to
2695 * continue using the Chunk object because nothing has a reference to it.
2696 *
2697 * We could avoid this by returning type/data/offset/length and having
2698 * the caller be aware of the object lifetime issues, but that
Elliott Hughes81ff3182012-03-23 20:35:56 -07002699 * integrates the JDWP code more tightly into the rest of the runtime, and doesn't work
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07002700 * if we have responses for multiple chunks.
2701 *
2702 * So we're pretty much stuck with copying data around multiple times.
2703 */
Elliott Hugheseac76672012-05-24 21:56:51 -07002704 ScopedLocalRef<jbyteArray> replyData(env, reinterpret_cast<jbyteArray>(env->GetObjectField(chunk.get(), WellKnownClasses::org_apache_harmony_dalvik_ddmc_Chunk_data)));
2705 length = env->GetIntField(chunk.get(), WellKnownClasses::org_apache_harmony_dalvik_ddmc_Chunk_length);
2706 offset = env->GetIntField(chunk.get(), WellKnownClasses::org_apache_harmony_dalvik_ddmc_Chunk_offset);
2707 type = env->GetIntField(chunk.get(), WellKnownClasses::org_apache_harmony_dalvik_ddmc_Chunk_type);
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07002708
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08002709 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 -07002710 if (length == 0 || replyData.get() == NULL) {
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07002711 return false;
2712 }
2713
Elliott Hughes6a5bd492011-10-28 14:33:57 -07002714 jsize replyLength = env->GetArrayLength(replyData.get());
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07002715 if (offset + length > replyLength) {
2716 LOG(WARNING) << StringPrintf("chunk off=%d len=%d exceeds reply array len %d", offset, length, replyLength);
2717 return false;
2718 }
2719
2720 uint8_t* reply = new uint8_t[length + kChunkHdrLen];
2721 if (reply == NULL) {
2722 LOG(WARNING) << "malloc failed: " << (length + kChunkHdrLen);
2723 return false;
2724 }
Elliott Hughesf7c3b662011-10-27 12:04:56 -07002725 JDWP::Set4BE(reply + 0, type);
2726 JDWP::Set4BE(reply + 4, length);
Elliott Hughes6a5bd492011-10-28 14:33:57 -07002727 env->GetByteArrayRegion(replyData.get(), offset, length, reinterpret_cast<jbyte*>(reply + kChunkHdrLen));
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07002728
2729 *pReplyBuf = reply;
2730 *pReplyLen = length + kChunkHdrLen;
2731
Elliott Hughesba8eee12012-01-24 20:25:24 -08002732 VLOG(jdwp) << StringPrintf("dvmHandleDdm returning type=%.4s buf=%p len=%d", reinterpret_cast<char*>(reply), reply, length);
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07002733 return true;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002734}
2735
Elliott Hughesa2155262011-11-16 16:26:58 -08002736void Dbg::DdmBroadcast(bool connect) {
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08002737 VLOG(jdwp) << "Broadcasting DDM " << (connect ? "connect" : "disconnect") << "...";
Elliott Hughes47fce012011-10-25 18:37:19 -07002738
2739 Thread* self = Thread::Current();
Ian Rogers50b35e22012-10-04 10:09:15 -07002740 if (self->GetState() != kRunnable) {
2741 LOG(ERROR) << "DDM broadcast in thread state " << self->GetState();
2742 /* try anyway? */
Elliott Hughes47fce012011-10-25 18:37:19 -07002743 }
2744
2745 JNIEnv* env = self->GetJniEnv();
Elliott Hughes47fce012011-10-25 18:37:19 -07002746 jint event = connect ? 1 /*DdmServer.CONNECTED*/ : 2 /*DdmServer.DISCONNECTED*/;
Elliott Hugheseac76672012-05-24 21:56:51 -07002747 env->CallStaticVoidMethod(WellKnownClasses::org_apache_harmony_dalvik_ddmc_DdmServer,
2748 WellKnownClasses::org_apache_harmony_dalvik_ddmc_DdmServer_broadcast,
2749 event);
Elliott Hughes47fce012011-10-25 18:37:19 -07002750 if (env->ExceptionCheck()) {
2751 LOG(ERROR) << "DdmServer.broadcast " << event << " failed";
2752 env->ExceptionDescribe();
2753 env->ExceptionClear();
2754 }
2755}
2756
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002757void Dbg::DdmConnected() {
Elliott Hughesa2155262011-11-16 16:26:58 -08002758 Dbg::DdmBroadcast(true);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002759}
2760
2761void Dbg::DdmDisconnected() {
Elliott Hughesa2155262011-11-16 16:26:58 -08002762 Dbg::DdmBroadcast(false);
Elliott Hughes47fce012011-10-25 18:37:19 -07002763 gDdmThreadNotification = false;
2764}
2765
2766/*
Elliott Hughes82188472011-11-07 18:11:48 -08002767 * Send a notification when a thread starts, stops, or changes its name.
Elliott Hughes47fce012011-10-25 18:37:19 -07002768 *
2769 * Because we broadcast the full set of threads when the notifications are
2770 * first enabled, it's possible for "thread" to be actively executing.
2771 */
Elliott Hughes82188472011-11-07 18:11:48 -08002772void Dbg::DdmSendThreadNotification(Thread* t, uint32_t type) {
Elliott Hughes47fce012011-10-25 18:37:19 -07002773 if (!gDdmThreadNotification) {
2774 return;
2775 }
2776
Elliott Hughes82188472011-11-07 18:11:48 -08002777 if (type == CHUNK_TYPE("THDE")) {
Elliott Hughes47fce012011-10-25 18:37:19 -07002778 uint8_t buf[4];
Elliott Hughesf7c3b662011-10-27 12:04:56 -07002779 JDWP::Set4BE(&buf[0], t->GetThinLockId());
Elliott Hughes47fce012011-10-25 18:37:19 -07002780 Dbg::DdmSendChunk(CHUNK_TYPE("THDE"), 4, buf);
Elliott Hughes82188472011-11-07 18:11:48 -08002781 } else {
2782 CHECK(type == CHUNK_TYPE("THCR") || type == CHUNK_TYPE("THNM")) << type;
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002783 ScopedObjectAccessUnchecked soa(Thread::Current());
Ian Rogers1f539342012-10-03 21:09:42 -07002784 SirtRef<String> name(soa.Self(), t->GetThreadName(soa));
Elliott Hughes82188472011-11-07 18:11:48 -08002785 size_t char_count = (name.get() != NULL) ? name->GetLength() : 0;
jeffhao725a9572012-11-13 18:20:12 -08002786 const jchar* chars = (name.get() != NULL) ? name->GetCharArray()->GetData() : NULL;
Elliott Hughes82188472011-11-07 18:11:48 -08002787
Elliott Hughes21f32d72011-11-09 17:44:13 -08002788 std::vector<uint8_t> bytes;
Elliott Hughes545a0642011-11-08 19:10:03 -08002789 JDWP::Append4BE(bytes, t->GetThinLockId());
2790 JDWP::AppendUtf16BE(bytes, chars, char_count);
Elliott Hughes21f32d72011-11-09 17:44:13 -08002791 CHECK_EQ(bytes.size(), char_count*2 + sizeof(uint32_t)*2);
2792 Dbg::DdmSendChunk(type, bytes);
Elliott Hughes47fce012011-10-25 18:37:19 -07002793 }
2794}
2795
Elliott Hughes47fce012011-10-25 18:37:19 -07002796void Dbg::DdmSetThreadNotification(bool enable) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002797 // Enable/disable thread notifications.
Elliott Hughes47fce012011-10-25 18:37:19 -07002798 gDdmThreadNotification = enable;
2799 if (enable) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002800 // Suspend the VM then post thread start notifications for all threads. Threads attaching will
2801 // see a suspension in progress and block until that ends. They then post their own start
2802 // notification.
2803 SuspendVM();
2804 std::list<Thread*> threads;
Ian Rogers50b35e22012-10-04 10:09:15 -07002805 Thread* self = Thread::Current();
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002806 {
Ian Rogers50b35e22012-10-04 10:09:15 -07002807 MutexLock mu(self, *Locks::thread_list_lock_);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002808 threads = Runtime::Current()->GetThreadList()->GetList();
2809 }
2810 {
Ian Rogers50b35e22012-10-04 10:09:15 -07002811 ScopedObjectAccess soa(self);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002812 typedef std::list<Thread*>::const_iterator It; // TODO: C++0x auto
2813 for (It it = threads.begin(), end = threads.end(); it != end; ++it) {
2814 Dbg::DdmSendThreadNotification(*it, CHUNK_TYPE("THCR"));
2815 }
2816 }
2817 ResumeVM();
Elliott Hughes47fce012011-10-25 18:37:19 -07002818 }
2819}
2820
Elliott Hughesa2155262011-11-16 16:26:58 -08002821void Dbg::PostThreadStartOrStop(Thread* t, uint32_t type) {
Elliott Hughesc0f09332012-03-26 13:27:06 -07002822 if (IsDebuggerActive()) {
Mathieu Chartierdbe6f462012-09-25 16:54:50 -07002823 ScopedObjectAccessUnchecked soa(Thread::Current());
Ian Rogerscfaa4552012-11-26 21:00:08 -08002824 JDWP::ObjectId id = gRegistry->Add(t->GetPeer());
Elliott Hughes82188472011-11-07 18:11:48 -08002825 gJdwpState->PostThreadChange(id, type == CHUNK_TYPE("THCR"));
Elliott Hughesc0f09332012-03-26 13:27:06 -07002826 // If this thread's just joined the party while we're already debugging, make sure it knows
2827 // to give us updates when it's running.
2828 t->SetDebuggerUpdatesEnabled(true);
Elliott Hughes47fce012011-10-25 18:37:19 -07002829 }
Elliott Hughes82188472011-11-07 18:11:48 -08002830 Dbg::DdmSendThreadNotification(t, type);
Elliott Hughes47fce012011-10-25 18:37:19 -07002831}
2832
2833void Dbg::PostThreadStart(Thread* t) {
Elliott Hughesa2155262011-11-16 16:26:58 -08002834 Dbg::PostThreadStartOrStop(t, CHUNK_TYPE("THCR"));
Elliott Hughes47fce012011-10-25 18:37:19 -07002835}
2836
2837void Dbg::PostThreadDeath(Thread* t) {
Elliott Hughesa2155262011-11-16 16:26:58 -08002838 Dbg::PostThreadStartOrStop(t, CHUNK_TYPE("THDE"));
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002839}
2840
Elliott Hughes82188472011-11-07 18:11:48 -08002841void Dbg::DdmSendChunk(uint32_t type, size_t byte_count, const uint8_t* buf) {
Elliott Hughes3bb81562011-10-21 18:52:59 -07002842 CHECK(buf != NULL);
2843 iovec vec[1];
2844 vec[0].iov_base = reinterpret_cast<void*>(const_cast<uint8_t*>(buf));
2845 vec[0].iov_len = byte_count;
2846 Dbg::DdmSendChunkV(type, vec, 1);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002847}
2848
Elliott Hughes21f32d72011-11-09 17:44:13 -08002849void Dbg::DdmSendChunk(uint32_t type, const std::vector<uint8_t>& bytes) {
2850 DdmSendChunk(type, bytes.size(), &bytes[0]);
2851}
2852
Elliott Hughescccd84f2011-12-05 16:51:54 -08002853void Dbg::DdmSendChunkV(uint32_t type, const struct iovec* iov, int iov_count) {
Elliott Hughes3bb81562011-10-21 18:52:59 -07002854 if (gJdwpState == NULL) {
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08002855 VLOG(jdwp) << "Debugger thread not active, ignoring DDM send: " << type;
Elliott Hughes3bb81562011-10-21 18:52:59 -07002856 } else {
Elliott Hughescccd84f2011-12-05 16:51:54 -08002857 gJdwpState->DdmSendChunkV(type, iov, iov_count);
Elliott Hughes3bb81562011-10-21 18:52:59 -07002858 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002859}
2860
Elliott Hughes767a1472011-10-26 18:49:02 -07002861int Dbg::DdmHandleHpifChunk(HpifWhen when) {
2862 if (when == HPIF_WHEN_NOW) {
Elliott Hughes7162ad92011-10-27 14:08:42 -07002863 DdmSendHeapInfo(when);
Elliott Hughes767a1472011-10-26 18:49:02 -07002864 return true;
2865 }
2866
2867 if (when != HPIF_WHEN_NEVER && when != HPIF_WHEN_NEXT_GC && when != HPIF_WHEN_EVERY_GC) {
2868 LOG(ERROR) << "invalid HpifWhen value: " << static_cast<int>(when);
2869 return false;
2870 }
2871
2872 gDdmHpifWhen = when;
2873 return true;
2874}
2875
2876bool Dbg::DdmHandleHpsgNhsgChunk(Dbg::HpsgWhen when, Dbg::HpsgWhat what, bool native) {
2877 if (when != HPSG_WHEN_NEVER && when != HPSG_WHEN_EVERY_GC) {
2878 LOG(ERROR) << "invalid HpsgWhen value: " << static_cast<int>(when);
2879 return false;
2880 }
2881
2882 if (what != HPSG_WHAT_MERGED_OBJECTS && what != HPSG_WHAT_DISTINCT_OBJECTS) {
2883 LOG(ERROR) << "invalid HpsgWhat value: " << static_cast<int>(what);
2884 return false;
2885 }
2886
2887 if (native) {
2888 gDdmNhsgWhen = when;
2889 gDdmNhsgWhat = what;
2890 } else {
2891 gDdmHpsgWhen = when;
2892 gDdmHpsgWhat = what;
2893 }
2894 return true;
2895}
2896
Elliott Hughes7162ad92011-10-27 14:08:42 -07002897void Dbg::DdmSendHeapInfo(HpifWhen reason) {
2898 // If there's a one-shot 'when', reset it.
2899 if (reason == gDdmHpifWhen) {
2900 if (gDdmHpifWhen == HPIF_WHEN_NEXT_GC) {
2901 gDdmHpifWhen = HPIF_WHEN_NEVER;
2902 }
2903 }
2904
2905 /*
2906 * Chunk HPIF (client --> server)
2907 *
2908 * Heap Info. General information about the heap,
2909 * suitable for a summary display.
2910 *
2911 * [u4]: number of heaps
2912 *
2913 * For each heap:
2914 * [u4]: heap ID
2915 * [u8]: timestamp in ms since Unix epoch
2916 * [u1]: capture reason (same as 'when' value from server)
2917 * [u4]: max heap size in bytes (-Xmx)
2918 * [u4]: current heap size in bytes
2919 * [u4]: current number of bytes allocated
2920 * [u4]: current number of objects allocated
2921 */
2922 uint8_t heap_count = 1;
Elliott Hughesb3bd5f02012-03-08 21:05:27 -08002923 Heap* heap = Runtime::Current()->GetHeap();
Elliott Hughes21f32d72011-11-09 17:44:13 -08002924 std::vector<uint8_t> bytes;
Elliott Hughes545a0642011-11-08 19:10:03 -08002925 JDWP::Append4BE(bytes, heap_count);
2926 JDWP::Append4BE(bytes, 1); // Heap id (bogus; we only have one heap).
2927 JDWP::Append8BE(bytes, MilliTime());
2928 JDWP::Append1BE(bytes, reason);
Elliott Hughesb3bd5f02012-03-08 21:05:27 -08002929 JDWP::Append4BE(bytes, heap->GetMaxMemory()); // Max allowed heap size in bytes.
2930 JDWP::Append4BE(bytes, heap->GetTotalMemory()); // Current heap size in bytes.
2931 JDWP::Append4BE(bytes, heap->GetBytesAllocated());
2932 JDWP::Append4BE(bytes, heap->GetObjectsAllocated());
Elliott Hughes21f32d72011-11-09 17:44:13 -08002933 CHECK_EQ(bytes.size(), 4U + (heap_count * (4 + 8 + 1 + 4 + 4 + 4 + 4)));
2934 Dbg::DdmSendChunk(CHUNK_TYPE("HPIF"), bytes);
Elliott Hughes767a1472011-10-26 18:49:02 -07002935}
2936
Elliott Hughes6a5bd492011-10-28 14:33:57 -07002937enum HpsgSolidity {
2938 SOLIDITY_FREE = 0,
2939 SOLIDITY_HARD = 1,
2940 SOLIDITY_SOFT = 2,
2941 SOLIDITY_WEAK = 3,
2942 SOLIDITY_PHANTOM = 4,
2943 SOLIDITY_FINALIZABLE = 5,
2944 SOLIDITY_SWEEP = 6,
2945};
2946
2947enum HpsgKind {
2948 KIND_OBJECT = 0,
2949 KIND_CLASS_OBJECT = 1,
2950 KIND_ARRAY_1 = 2,
2951 KIND_ARRAY_2 = 3,
2952 KIND_ARRAY_4 = 4,
2953 KIND_ARRAY_8 = 5,
2954 KIND_UNKNOWN = 6,
2955 KIND_NATIVE = 7,
2956};
2957
2958#define HPSG_PARTIAL (1<<7)
2959#define HPSG_STATE(solidity, kind) ((uint8_t)((((kind) & 0x7) << 3) | ((solidity) & 0x7)))
2960
Ian Rogers30fab402012-01-23 15:43:46 -08002961class HeapChunkContext {
2962 public:
Elliott Hughes6a5bd492011-10-28 14:33:57 -07002963 // Maximum chunk size. Obtain this from the formula:
2964 // (((maximum_heap_size / ALLOCATION_UNIT_SIZE) + 255) / 256) * 2
2965 HeapChunkContext(bool merge, bool native)
Ian Rogers30fab402012-01-23 15:43:46 -08002966 : buf_(16384 - 16),
2967 type_(0),
2968 merge_(merge) {
Elliott Hughes6a5bd492011-10-28 14:33:57 -07002969 Reset();
2970 if (native) {
Ian Rogers30fab402012-01-23 15:43:46 -08002971 type_ = CHUNK_TYPE("NHSG");
Elliott Hughes6a5bd492011-10-28 14:33:57 -07002972 } else {
Ian Rogers30fab402012-01-23 15:43:46 -08002973 type_ = merge ? CHUNK_TYPE("HPSG") : CHUNK_TYPE("HPSO");
Elliott Hughes6a5bd492011-10-28 14:33:57 -07002974 }
2975 }
2976
2977 ~HeapChunkContext() {
Ian Rogers30fab402012-01-23 15:43:46 -08002978 if (p_ > &buf_[0]) {
Elliott Hughes6a5bd492011-10-28 14:33:57 -07002979 Flush();
2980 }
2981 }
2982
2983 void EnsureHeader(const void* chunk_ptr) {
Ian Rogers30fab402012-01-23 15:43:46 -08002984 if (!needHeader_) {
Elliott Hughes6a5bd492011-10-28 14:33:57 -07002985 return;
2986 }
2987
2988 // Start a new HPSx chunk.
Ian Rogers30fab402012-01-23 15:43:46 -08002989 JDWP::Write4BE(&p_, 1); // Heap id (bogus; we only have one heap).
2990 JDWP::Write1BE(&p_, 8); // Size of allocation unit, in bytes.
Elliott Hughes6a5bd492011-10-28 14:33:57 -07002991
Ian Rogers30fab402012-01-23 15:43:46 -08002992 JDWP::Write4BE(&p_, reinterpret_cast<uintptr_t>(chunk_ptr)); // virtual address of segment start.
2993 JDWP::Write4BE(&p_, 0); // offset of this piece (relative to the virtual address).
Elliott Hughes6a5bd492011-10-28 14:33:57 -07002994 // [u4]: length of piece, in allocation units
2995 // 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 -08002996 pieceLenField_ = p_;
2997 JDWP::Write4BE(&p_, 0x55555555);
2998 needHeader_ = false;
Elliott Hughes6a5bd492011-10-28 14:33:57 -07002999 }
3000
Ian Rogersb726dcb2012-09-05 08:57:23 -07003001 void Flush() SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003002 // Patch the "length of piece" field.
Ian Rogers30fab402012-01-23 15:43:46 -08003003 CHECK_LE(&buf_[0], pieceLenField_);
3004 CHECK_LE(pieceLenField_, p_);
3005 JDWP::Set4BE(pieceLenField_, totalAllocationUnits_);
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003006
Ian Rogers30fab402012-01-23 15:43:46 -08003007 Dbg::DdmSendChunk(type_, p_ - &buf_[0], &buf_[0]);
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003008 Reset();
3009 }
3010
Ian Rogers00f7d0e2012-07-19 15:28:27 -07003011 static void HeapChunkCallback(void* start, void* end, size_t used_bytes, void* arg)
Ian Rogersb726dcb2012-09-05 08:57:23 -07003012 SHARED_LOCKS_REQUIRED(Locks::heap_bitmap_lock_,
3013 Locks::mutator_lock_) {
Ian Rogers30fab402012-01-23 15:43:46 -08003014 reinterpret_cast<HeapChunkContext*>(arg)->HeapChunkCallback(start, end, used_bytes);
Elliott Hughesa2155262011-11-16 16:26:58 -08003015 }
3016
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003017 private:
Elliott Hughesa2155262011-11-16 16:26:58 -08003018 enum { ALLOCATION_UNIT_SIZE = 8 };
3019
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003020 void Reset() {
Ian Rogers30fab402012-01-23 15:43:46 -08003021 p_ = &buf_[0];
Ian Rogers15bf2d32012-08-28 17:33:04 -07003022 startOfNextMemoryChunk_ = NULL;
Ian Rogers30fab402012-01-23 15:43:46 -08003023 totalAllocationUnits_ = 0;
3024 needHeader_ = true;
3025 pieceLenField_ = NULL;
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003026 }
3027
Ian Rogers00f7d0e2012-07-19 15:28:27 -07003028 void HeapChunkCallback(void* start, void* /*end*/, size_t used_bytes)
Ian Rogersb726dcb2012-09-05 08:57:23 -07003029 SHARED_LOCKS_REQUIRED(Locks::heap_bitmap_lock_,
3030 Locks::mutator_lock_) {
Ian Rogers30fab402012-01-23 15:43:46 -08003031 // Note: heap call backs cannot manipulate the heap upon which they are crawling, care is taken
3032 // in the following code not to allocate memory, by ensuring buf_ is of the correct size
Ian Rogers15bf2d32012-08-28 17:33:04 -07003033 if (used_bytes == 0) {
3034 if (start == NULL) {
3035 // Reset for start of new heap.
3036 startOfNextMemoryChunk_ = NULL;
3037 Flush();
3038 }
3039 // Only process in use memory so that free region information
3040 // also includes dlmalloc book keeping.
Elliott Hughesa2155262011-11-16 16:26:58 -08003041 return;
Elliott Hughesa2155262011-11-16 16:26:58 -08003042 }
3043
Ian Rogers15bf2d32012-08-28 17:33:04 -07003044 /* If we're looking at the native heap, we'll just return
3045 * (SOLIDITY_HARD, KIND_NATIVE) for all allocated chunks
3046 */
3047 bool native = type_ == CHUNK_TYPE("NHSG");
3048
3049 if (startOfNextMemoryChunk_ != NULL) {
3050 // Transmit any pending free memory. Native free memory of
3051 // over kMaxFreeLen could be because of the use of mmaps, so
3052 // don't report. If not free memory then start a new segment.
3053 bool flush = true;
3054 if (start > startOfNextMemoryChunk_) {
3055 const size_t kMaxFreeLen = 2 * kPageSize;
3056 void* freeStart = startOfNextMemoryChunk_;
3057 void* freeEnd = start;
3058 size_t freeLen = (char*)freeEnd - (char*)freeStart;
3059 if (!native || freeLen < kMaxFreeLen) {
3060 AppendChunk(HPSG_STATE(SOLIDITY_FREE, 0), freeStart, freeLen);
3061 flush = false;
3062 }
3063 }
3064 if (flush) {
3065 startOfNextMemoryChunk_ = NULL;
3066 Flush();
3067 }
3068 }
3069 const Object *obj = (const Object *)start;
Elliott Hughesa2155262011-11-16 16:26:58 -08003070
3071 // Determine the type of this chunk.
3072 // OLD-TODO: if context.merge, see if this chunk is different from the last chunk.
3073 // If it's the same, we should combine them.
Ian Rogers15bf2d32012-08-28 17:33:04 -07003074 uint8_t state = ExamineObject(obj, native);
3075 // dlmalloc's chunk header is 2 * sizeof(size_t), but if the previous chunk is in use for an
3076 // allocation then the first sizeof(size_t) may belong to it.
3077 const size_t dlMallocOverhead = sizeof(size_t);
3078 AppendChunk(state, start, used_bytes + dlMallocOverhead);
3079 startOfNextMemoryChunk_ = (char*)start + used_bytes + dlMallocOverhead;
3080 }
Elliott Hughesa2155262011-11-16 16:26:58 -08003081
Ian Rogers15bf2d32012-08-28 17:33:04 -07003082 void AppendChunk(uint8_t state, void* ptr, size_t length)
Ian Rogersb726dcb2012-09-05 08:57:23 -07003083 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Ian Rogers15bf2d32012-08-28 17:33:04 -07003084 // Make sure there's enough room left in the buffer.
3085 // We need to use two bytes for every fractional 256 allocation units used by the chunk plus
3086 // 17 bytes for any header.
3087 size_t needed = (((length/ALLOCATION_UNIT_SIZE + 255) / 256) * 2) + 17;
3088 size_t bytesLeft = buf_.size() - (size_t)(p_ - &buf_[0]);
3089 if (bytesLeft < needed) {
3090 Flush();
3091 }
3092
3093 bytesLeft = buf_.size() - (size_t)(p_ - &buf_[0]);
3094 if (bytesLeft < needed) {
3095 LOG(WARNING) << "Chunk is too big to transmit (chunk_len=" << length << ", "
3096 << needed << " bytes)";
3097 return;
3098 }
3099 EnsureHeader(ptr);
Elliott Hughesa2155262011-11-16 16:26:58 -08003100 // Write out the chunk description.
Ian Rogers15bf2d32012-08-28 17:33:04 -07003101 length /= ALLOCATION_UNIT_SIZE; // Convert to allocation units.
3102 totalAllocationUnits_ += length;
3103 while (length > 256) {
Ian Rogers30fab402012-01-23 15:43:46 -08003104 *p_++ = state | HPSG_PARTIAL;
3105 *p_++ = 255; // length - 1
Ian Rogers15bf2d32012-08-28 17:33:04 -07003106 length -= 256;
Elliott Hughesa2155262011-11-16 16:26:58 -08003107 }
Ian Rogers30fab402012-01-23 15:43:46 -08003108 *p_++ = state;
Ian Rogers15bf2d32012-08-28 17:33:04 -07003109 *p_++ = length - 1;
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003110 }
3111
Ian Rogers5bfa60f2012-09-02 21:17:56 -07003112 uint8_t ExamineObject(const Object* o, bool is_native_heap)
Ian Rogersb726dcb2012-09-05 08:57:23 -07003113 SHARED_LOCKS_REQUIRED(Locks::heap_bitmap_lock_) {
Elliott Hughesa2155262011-11-16 16:26:58 -08003114 if (o == NULL) {
3115 return HPSG_STATE(SOLIDITY_FREE, 0);
3116 }
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003117
Elliott Hughesa2155262011-11-16 16:26:58 -08003118 // It's an allocated chunk. Figure out what it is.
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003119
Elliott Hughesa2155262011-11-16 16:26:58 -08003120 // If we're looking at the native heap, we'll just return
3121 // (SOLIDITY_HARD, KIND_NATIVE) for all allocated chunks.
Ian Rogers00f7d0e2012-07-19 15:28:27 -07003122 if (is_native_heap) {
Elliott Hughesa2155262011-11-16 16:26:58 -08003123 return HPSG_STATE(SOLIDITY_HARD, KIND_NATIVE);
3124 }
3125
Ian Rogers5bfa60f2012-09-02 21:17:56 -07003126 if (!Runtime::Current()->GetHeap()->IsLiveObjectLocked(o)) {
Ian Rogers15bf2d32012-08-28 17:33:04 -07003127 return HPSG_STATE(SOLIDITY_HARD, KIND_NATIVE);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07003128 }
3129
Elliott Hughesa2155262011-11-16 16:26:58 -08003130 Class* c = o->GetClass();
3131 if (c == NULL) {
3132 // The object was probably just created but hasn't been initialized yet.
3133 return HPSG_STATE(SOLIDITY_HARD, KIND_OBJECT);
3134 }
3135
Elliott Hughesb3bd5f02012-03-08 21:05:27 -08003136 if (!Runtime::Current()->GetHeap()->IsHeapAddress(c)) {
Ian Rogers15bf2d32012-08-28 17:33:04 -07003137 LOG(ERROR) << "Invalid class for managed heap object: " << o << " " << c;
Elliott Hughesa2155262011-11-16 16:26:58 -08003138 return HPSG_STATE(SOLIDITY_HARD, KIND_UNKNOWN);
3139 }
3140
3141 if (c->IsClassClass()) {
3142 return HPSG_STATE(SOLIDITY_HARD, KIND_CLASS_OBJECT);
3143 }
3144
3145 if (c->IsArrayClass()) {
3146 if (o->IsObjectArray()) {
3147 return HPSG_STATE(SOLIDITY_HARD, KIND_ARRAY_4);
3148 }
3149 switch (c->GetComponentSize()) {
3150 case 1: return HPSG_STATE(SOLIDITY_HARD, KIND_ARRAY_1);
3151 case 2: return HPSG_STATE(SOLIDITY_HARD, KIND_ARRAY_2);
3152 case 4: return HPSG_STATE(SOLIDITY_HARD, KIND_ARRAY_4);
3153 case 8: return HPSG_STATE(SOLIDITY_HARD, KIND_ARRAY_8);
3154 }
3155 }
3156
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003157 return HPSG_STATE(SOLIDITY_HARD, KIND_OBJECT);
3158 }
3159
Ian Rogers30fab402012-01-23 15:43:46 -08003160 std::vector<uint8_t> buf_;
3161 uint8_t* p_;
3162 uint8_t* pieceLenField_;
Ian Rogers15bf2d32012-08-28 17:33:04 -07003163 void* startOfNextMemoryChunk_;
Ian Rogers30fab402012-01-23 15:43:46 -08003164 size_t totalAllocationUnits_;
3165 uint32_t type_;
3166 bool merge_;
3167 bool needHeader_;
3168
Elliott Hughesa2155262011-11-16 16:26:58 -08003169 DISALLOW_COPY_AND_ASSIGN(HeapChunkContext);
3170};
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003171
3172void Dbg::DdmSendHeapSegments(bool native) {
3173 Dbg::HpsgWhen when;
3174 Dbg::HpsgWhat what;
3175 if (!native) {
3176 when = gDdmHpsgWhen;
3177 what = gDdmHpsgWhat;
3178 } else {
3179 when = gDdmNhsgWhen;
3180 what = gDdmNhsgWhat;
3181 }
3182 if (when == HPSG_WHEN_NEVER) {
3183 return;
3184 }
3185
3186 // Figure out what kind of chunks we'll be sending.
3187 CHECK(what == HPSG_WHAT_MERGED_OBJECTS || what == HPSG_WHAT_DISTINCT_OBJECTS) << static_cast<int>(what);
3188
3189 // First, send a heap start chunk.
3190 uint8_t heap_id[4];
3191 JDWP::Set4BE(&heap_id[0], 1); // Heap id (bogus; we only have one heap).
3192 Dbg::DdmSendChunk(native ? CHUNK_TYPE("NHST") : CHUNK_TYPE("HPST"), sizeof(heap_id), heap_id);
3193
3194 // Send a series of heap segment chunks.
Elliott Hughesa2155262011-11-16 16:26:58 -08003195 HeapChunkContext context((what == HPSG_WHAT_MERGED_OBJECTS), native);
3196 if (native) {
Ian Rogers30fab402012-01-23 15:43:46 -08003197 // TODO: enable when bionic has moved to dlmalloc 2.8.5
3198 // dlmalloc_inspect_all(HeapChunkContext::HeapChunkCallback, &context);
3199 UNIMPLEMENTED(WARNING) << "Native heap send heap segments";
Elliott Hughesa2155262011-11-16 16:26:58 -08003200 } else {
Elliott Hughesb3bd5f02012-03-08 21:05:27 -08003201 Heap* heap = Runtime::Current()->GetHeap();
Mathieu Chartierfd678be2012-08-30 14:50:54 -07003202 const Spaces& spaces = heap->GetSpaces();
Ian Rogers50b35e22012-10-04 10:09:15 -07003203 Thread* self = Thread::Current();
Mathieu Chartierfd678be2012-08-30 14:50:54 -07003204 for (Spaces::const_iterator cur = spaces.begin(); cur != spaces.end(); ++cur) {
Mathieu Chartierb062fdd2012-07-03 09:51:48 -07003205 if ((*cur)->IsAllocSpace()) {
Ian Rogers50b35e22012-10-04 10:09:15 -07003206 ReaderMutexLock mu(self, *Locks::heap_bitmap_lock_);
Mathieu Chartierb062fdd2012-07-03 09:51:48 -07003207 (*cur)->AsAllocSpace()->Walk(HeapChunkContext::HeapChunkCallback, &context);
3208 }
3209 }
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -07003210 // Walk the large objects, these are not in the AllocSpace.
3211 heap->GetLargeObjectsSpace()->Walk(HeapChunkContext::HeapChunkCallback, &context);
Elliott Hughesa2155262011-11-16 16:26:58 -08003212 }
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003213
3214 // Finally, send a heap end chunk.
3215 Dbg::DdmSendChunk(native ? CHUNK_TYPE("NHEN") : CHUNK_TYPE("HPEN"), sizeof(heap_id), heap_id);
Elliott Hughes767a1472011-10-26 18:49:02 -07003216}
3217
Elliott Hughes545a0642011-11-08 19:10:03 -08003218void Dbg::SetAllocTrackingEnabled(bool enabled) {
Ian Rogers50b35e22012-10-04 10:09:15 -07003219 MutexLock mu(Thread::Current(), gAllocTrackerLock);
Elliott Hughes545a0642011-11-08 19:10:03 -08003220 if (enabled) {
3221 if (recent_allocation_records_ == NULL) {
3222 LOG(INFO) << "Enabling alloc tracker (" << kNumAllocRecords << " entries, "
3223 << kMaxAllocRecordStackDepth << " frames --> "
3224 << (sizeof(AllocRecord) * kNumAllocRecords) << " bytes)";
3225 gAllocRecordHead = gAllocRecordCount = 0;
3226 recent_allocation_records_ = new AllocRecord[kNumAllocRecords];
3227 CHECK(recent_allocation_records_ != NULL);
3228 }
3229 } else {
3230 delete[] recent_allocation_records_;
3231 recent_allocation_records_ = NULL;
3232 }
3233}
3234
Ian Rogers0399dde2012-06-06 17:09:28 -07003235struct AllocRecordStackVisitor : public StackVisitor {
3236 AllocRecordStackVisitor(const ManagedStack* stack,
Ian Rogers306057f2012-11-26 12:45:53 -08003237 const std::deque<InstrumentationStackFrame>* instrumentation_stack,
3238 AllocRecord* record)
Ian Rogersb726dcb2012-09-05 08:57:23 -07003239 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_)
jeffhao725a9572012-11-13 18:20:12 -08003240 : StackVisitor(stack, instrumentation_stack, NULL), record(record), depth(0) {}
Elliott Hughes545a0642011-11-08 19:10:03 -08003241
Ian Rogers00f7d0e2012-07-19 15:28:27 -07003242 // TODO: Enable annotalysis. We know lock is held in constructor, but abstraction confuses
3243 // annotalysis.
3244 bool VisitFrame() NO_THREAD_SAFETY_ANALYSIS {
Elliott Hughes545a0642011-11-08 19:10:03 -08003245 if (depth >= kMaxAllocRecordStackDepth) {
Elliott Hughes530fa002012-03-12 11:44:49 -07003246 return false;
Elliott Hughes545a0642011-11-08 19:10:03 -08003247 }
Mathieu Chartier66f19252012-09-18 08:57:04 -07003248 AbstractMethod* m = GetMethod();
Ian Rogers0399dde2012-06-06 17:09:28 -07003249 if (!m->IsRuntimeMethod()) {
3250 record->stack[depth].method = m;
3251 record->stack[depth].dex_pc = GetDexPc();
Elliott Hughes530fa002012-03-12 11:44:49 -07003252 ++depth;
Elliott Hughes545a0642011-11-08 19:10:03 -08003253 }
Elliott Hughes530fa002012-03-12 11:44:49 -07003254 return true;
Elliott Hughes545a0642011-11-08 19:10:03 -08003255 }
3256
3257 ~AllocRecordStackVisitor() {
3258 // Clear out any unused stack trace elements.
3259 for (; depth < kMaxAllocRecordStackDepth; ++depth) {
3260 record->stack[depth].method = NULL;
Ian Rogers0399dde2012-06-06 17:09:28 -07003261 record->stack[depth].dex_pc = 0;
Elliott Hughes545a0642011-11-08 19:10:03 -08003262 }
3263 }
3264
3265 AllocRecord* record;
3266 size_t depth;
3267};
3268
3269void Dbg::RecordAllocation(Class* type, size_t byte_count) {
3270 Thread* self = Thread::Current();
3271 CHECK(self != NULL);
3272
Ian Rogers50b35e22012-10-04 10:09:15 -07003273 MutexLock mu(self, gAllocTrackerLock);
Elliott Hughes545a0642011-11-08 19:10:03 -08003274 if (recent_allocation_records_ == NULL) {
3275 return;
3276 }
3277
3278 // Advance and clip.
3279 if (++gAllocRecordHead == kNumAllocRecords) {
3280 gAllocRecordHead = 0;
3281 }
3282
3283 // Fill in the basics.
3284 AllocRecord* record = &recent_allocation_records_[gAllocRecordHead];
3285 record->type = type;
3286 record->byte_count = byte_count;
3287 record->thin_lock_id = self->GetThinLockId();
3288
3289 // Fill in the stack trace.
jeffhao725a9572012-11-13 18:20:12 -08003290 AllocRecordStackVisitor visitor(self->GetManagedStack(), self->GetInstrumentationStack(), record);
Ian Rogers0399dde2012-06-06 17:09:28 -07003291 visitor.WalkStack();
Elliott Hughes545a0642011-11-08 19:10:03 -08003292
3293 if (gAllocRecordCount < kNumAllocRecords) {
3294 ++gAllocRecordCount;
3295 }
3296}
3297
Elliott Hughesa8f93cb2012-06-08 17:08:48 -07003298// Returns the index of the head element.
3299//
3300// We point at the most-recently-written record, so if gAllocRecordCount is 1
3301// we want to use the current element. Take "head+1" and subtract count
3302// from it.
3303//
3304// We need to handle underflow in our circular buffer, so we add
3305// kNumAllocRecords and then mask it back down.
Elliott Hughesf8349362012-06-18 15:00:06 -07003306static inline int HeadIndex() EXCLUSIVE_LOCKS_REQUIRED(gAllocTrackerLock) {
Elliott Hughes545a0642011-11-08 19:10:03 -08003307 return (gAllocRecordHead+1 + kNumAllocRecords - gAllocRecordCount) & (kNumAllocRecords-1);
3308}
3309
3310void Dbg::DumpRecentAllocations() {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07003311 ScopedObjectAccess soa(Thread::Current());
Ian Rogers50b35e22012-10-04 10:09:15 -07003312 MutexLock mu(soa.Self(), gAllocTrackerLock);
Elliott Hughes545a0642011-11-08 19:10:03 -08003313 if (recent_allocation_records_ == NULL) {
3314 LOG(INFO) << "Not recording tracked allocations";
3315 return;
3316 }
3317
3318 // "i" is the head of the list. We want to start at the end of the
3319 // list and move forward to the tail.
Elliott Hughesa8f93cb2012-06-08 17:08:48 -07003320 size_t i = HeadIndex();
Elliott Hughes545a0642011-11-08 19:10:03 -08003321 size_t count = gAllocRecordCount;
3322
3323 LOG(INFO) << "Tracked allocations, (head=" << gAllocRecordHead << " count=" << count << ")";
3324 while (count--) {
3325 AllocRecord* record = &recent_allocation_records_[i];
3326
Elliott Hughesa8f93cb2012-06-08 17:08:48 -07003327 LOG(INFO) << StringPrintf(" Thread %-2d %6zd bytes ", record->thin_lock_id, record->byte_count)
Elliott Hughes545a0642011-11-08 19:10:03 -08003328 << PrettyClass(record->type);
3329
3330 for (size_t stack_frame = 0; stack_frame < kMaxAllocRecordStackDepth; ++stack_frame) {
Mathieu Chartier66f19252012-09-18 08:57:04 -07003331 const AbstractMethod* m = record->stack[stack_frame].method;
Elliott Hughes545a0642011-11-08 19:10:03 -08003332 if (m == NULL) {
3333 break;
3334 }
3335 LOG(INFO) << " " << PrettyMethod(m) << " line " << record->stack[stack_frame].LineNumber();
3336 }
3337
3338 // pause periodically to help logcat catch up
3339 if ((count % 5) == 0) {
3340 usleep(40000);
3341 }
3342
3343 i = (i + 1) & (kNumAllocRecords-1);
3344 }
3345}
3346
3347class StringTable {
3348 public:
3349 StringTable() {
3350 }
3351
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08003352 void Add(const char* s) {
Elliott Hughes545a0642011-11-08 19:10:03 -08003353 table_.insert(s);
3354 }
3355
Elliott Hughesa8f93cb2012-06-08 17:08:48 -07003356 size_t IndexOf(const char* s) const {
3357 typedef std::set<std::string>::const_iterator It; // TODO: C++0x auto
3358 It it = table_.find(s);
3359 if (it == table_.end()) {
3360 LOG(FATAL) << "IndexOf(\"" << s << "\") failed";
3361 }
3362 return std::distance(table_.begin(), it);
Elliott Hughes545a0642011-11-08 19:10:03 -08003363 }
3364
Elliott Hughesa8f93cb2012-06-08 17:08:48 -07003365 size_t Size() const {
Elliott Hughes545a0642011-11-08 19:10:03 -08003366 return table_.size();
3367 }
3368
Elliott Hughesa8f93cb2012-06-08 17:08:48 -07003369 void WriteTo(std::vector<uint8_t>& bytes) const {
3370 typedef std::set<std::string>::const_iterator It; // TODO: C++0x auto
Elliott Hughes545a0642011-11-08 19:10:03 -08003371 for (It it = table_.begin(); it != table_.end(); ++it) {
Elliott Hughesa8f93cb2012-06-08 17:08:48 -07003372 const char* s = (*it).c_str();
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08003373 size_t s_len = CountModifiedUtf8Chars(s);
3374 UniquePtr<uint16_t> s_utf16(new uint16_t[s_len]);
3375 ConvertModifiedUtf8ToUtf16(s_utf16.get(), s);
3376 JDWP::AppendUtf16BE(bytes, s_utf16.get(), s_len);
Elliott Hughes545a0642011-11-08 19:10:03 -08003377 }
3378 }
3379
3380 private:
Elliott Hughesa8f93cb2012-06-08 17:08:48 -07003381 std::set<std::string> table_;
Elliott Hughes545a0642011-11-08 19:10:03 -08003382 DISALLOW_COPY_AND_ASSIGN(StringTable);
3383};
3384
3385/*
3386 * The data we send to DDMS contains everything we have recorded.
3387 *
3388 * Message header (all values big-endian):
3389 * (1b) message header len (to allow future expansion); includes itself
3390 * (1b) entry header len
3391 * (1b) stack frame len
3392 * (2b) number of entries
3393 * (4b) offset to string table from start of message
3394 * (2b) number of class name strings
3395 * (2b) number of method name strings
3396 * (2b) number of source file name strings
3397 * For each entry:
3398 * (4b) total allocation size
Elliott Hughes221229c2013-01-08 18:17:50 -08003399 * (2b) thread id
Elliott Hughes545a0642011-11-08 19:10:03 -08003400 * (2b) allocated object's class name index
3401 * (1b) stack depth
3402 * For each stack frame:
3403 * (2b) method's class name
3404 * (2b) method name
3405 * (2b) method source file
3406 * (2b) line number, clipped to 32767; -2 if native; -1 if no source
3407 * (xb) class name strings
3408 * (xb) method name strings
3409 * (xb) source file strings
3410 *
3411 * As with other DDM traffic, strings are sent as a 4-byte length
3412 * followed by UTF-16 data.
3413 *
3414 * We send up 16-bit unsigned indexes into string tables. In theory there
3415 * can be (kMaxAllocRecordStackDepth * kNumAllocRecords) unique strings in
3416 * each table, but in practice there should be far fewer.
3417 *
3418 * The chief reason for using a string table here is to keep the size of
3419 * the DDMS message to a minimum. This is partly to make the protocol
3420 * efficient, but also because we have to form the whole thing up all at
3421 * once in a memory buffer.
3422 *
3423 * We use separate string tables for class names, method names, and source
3424 * files to keep the indexes small. There will generally be no overlap
3425 * between the contents of these tables.
3426 */
3427jbyteArray Dbg::GetRecentAllocations() {
3428 if (false) {
3429 DumpRecentAllocations();
3430 }
3431
Ian Rogers50b35e22012-10-04 10:09:15 -07003432 Thread* self = Thread::Current();
3433 MutexLock mu(self, gAllocTrackerLock);
Elliott Hughes545a0642011-11-08 19:10:03 -08003434
Elliott Hughesa8f93cb2012-06-08 17:08:48 -07003435 //
3436 // Part 1: generate string tables.
3437 //
Elliott Hughes545a0642011-11-08 19:10:03 -08003438 StringTable class_names;
3439 StringTable method_names;
3440 StringTable filenames;
3441
3442 int count = gAllocRecordCount;
Elliott Hughesa8f93cb2012-06-08 17:08:48 -07003443 int idx = HeadIndex();
Elliott Hughes545a0642011-11-08 19:10:03 -08003444 while (count--) {
3445 AllocRecord* record = &recent_allocation_records_[idx];
3446
Elliott Hughes91250e02011-12-13 22:30:35 -08003447 class_names.Add(ClassHelper(record->type).GetDescriptor());
Elliott Hughes545a0642011-11-08 19:10:03 -08003448
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08003449 MethodHelper mh;
Elliott Hughes545a0642011-11-08 19:10:03 -08003450 for (size_t i = 0; i < kMaxAllocRecordStackDepth; i++) {
Mathieu Chartier66f19252012-09-18 08:57:04 -07003451 AbstractMethod* m = record->stack[i].method;
Elliott Hughes545a0642011-11-08 19:10:03 -08003452 if (m != NULL) {
Ian Rogersba377812012-05-28 21:16:29 -07003453 mh.ChangeMethod(m);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08003454 class_names.Add(mh.GetDeclaringClassDescriptor());
3455 method_names.Add(mh.GetName());
3456 filenames.Add(mh.GetDeclaringClassSourceFile());
Elliott Hughes545a0642011-11-08 19:10:03 -08003457 }
3458 }
3459
3460 idx = (idx + 1) & (kNumAllocRecords-1);
3461 }
3462
3463 LOG(INFO) << "allocation records: " << gAllocRecordCount;
3464
Elliott Hughesa8f93cb2012-06-08 17:08:48 -07003465 //
3466 // Part 2: allocate a buffer and generate the output.
3467 //
Elliott Hughes545a0642011-11-08 19:10:03 -08003468 std::vector<uint8_t> bytes;
3469
3470 // (1b) message header len (to allow future expansion); includes itself
3471 // (1b) entry header len
3472 // (1b) stack frame len
3473 const int kMessageHeaderLen = 15;
3474 const int kEntryHeaderLen = 9;
3475 const int kStackFrameLen = 8;
3476 JDWP::Append1BE(bytes, kMessageHeaderLen);
3477 JDWP::Append1BE(bytes, kEntryHeaderLen);
3478 JDWP::Append1BE(bytes, kStackFrameLen);
3479
3480 // (2b) number of entries
3481 // (4b) offset to string table from start of message
3482 // (2b) number of class name strings
3483 // (2b) number of method name strings
3484 // (2b) number of source file name strings
3485 JDWP::Append2BE(bytes, gAllocRecordCount);
3486 size_t string_table_offset = bytes.size();
3487 JDWP::Append4BE(bytes, 0); // We'll patch this later...
3488 JDWP::Append2BE(bytes, class_names.Size());
3489 JDWP::Append2BE(bytes, method_names.Size());
3490 JDWP::Append2BE(bytes, filenames.Size());
3491
3492 count = gAllocRecordCount;
Elliott Hughesa8f93cb2012-06-08 17:08:48 -07003493 idx = HeadIndex();
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08003494 ClassHelper kh;
Elliott Hughes545a0642011-11-08 19:10:03 -08003495 while (count--) {
3496 // For each entry:
3497 // (4b) total allocation size
3498 // (2b) thread id
3499 // (2b) allocated object's class name index
3500 // (1b) stack depth
3501 AllocRecord* record = &recent_allocation_records_[idx];
3502 size_t stack_depth = record->GetDepth();
Elliott Hughesa8f93cb2012-06-08 17:08:48 -07003503 kh.ChangeClass(record->type);
3504 size_t allocated_object_class_name_index = class_names.IndexOf(kh.GetDescriptor());
Elliott Hughes545a0642011-11-08 19:10:03 -08003505 JDWP::Append4BE(bytes, record->byte_count);
3506 JDWP::Append2BE(bytes, record->thin_lock_id);
Elliott Hughesa8f93cb2012-06-08 17:08:48 -07003507 JDWP::Append2BE(bytes, allocated_object_class_name_index);
Elliott Hughes545a0642011-11-08 19:10:03 -08003508 JDWP::Append1BE(bytes, stack_depth);
3509
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08003510 MethodHelper mh;
Elliott Hughes545a0642011-11-08 19:10:03 -08003511 for (size_t stack_frame = 0; stack_frame < stack_depth; ++stack_frame) {
3512 // For each stack frame:
3513 // (2b) method's class name
3514 // (2b) method name
3515 // (2b) method source file
3516 // (2b) line number, clipped to 32767; -2 if native; -1 if no source
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08003517 mh.ChangeMethod(record->stack[stack_frame].method);
Elliott Hughesa8f93cb2012-06-08 17:08:48 -07003518 size_t class_name_index = class_names.IndexOf(mh.GetDeclaringClassDescriptor());
3519 size_t method_name_index = method_names.IndexOf(mh.GetName());
3520 size_t file_name_index = filenames.IndexOf(mh.GetDeclaringClassSourceFile());
3521 JDWP::Append2BE(bytes, class_name_index);
3522 JDWP::Append2BE(bytes, method_name_index);
3523 JDWP::Append2BE(bytes, file_name_index);
Elliott Hughes545a0642011-11-08 19:10:03 -08003524 JDWP::Append2BE(bytes, record->stack[stack_frame].LineNumber());
3525 }
3526
3527 idx = (idx + 1) & (kNumAllocRecords-1);
3528 }
3529
3530 // (xb) class name strings
3531 // (xb) method name strings
3532 // (xb) source file strings
3533 JDWP::Set4BE(&bytes[string_table_offset], bytes.size());
3534 class_names.WriteTo(bytes);
3535 method_names.WriteTo(bytes);
3536 filenames.WriteTo(bytes);
3537
Ian Rogers50b35e22012-10-04 10:09:15 -07003538 JNIEnv* env = self->GetJniEnv();
Elliott Hughes545a0642011-11-08 19:10:03 -08003539 jbyteArray result = env->NewByteArray(bytes.size());
3540 if (result != NULL) {
3541 env->SetByteArrayRegion(result, 0, bytes.size(), reinterpret_cast<const jbyte*>(&bytes[0]));
3542 }
3543 return result;
3544}
3545
Elliott Hughes872d4ec2011-10-21 17:07:15 -07003546} // namespace art