blob: d43291edebbc3f9e59e0d3960072147a797386b2 [file] [log] [blame]
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001/*
2 * Copyright (C) 2008 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17#include "debugger.h"
18
Elliott Hughes3bb81562011-10-21 18:52:59 -070019#include <sys/uio.h>
20
Elliott Hughes545a0642011-11-08 19:10:03 -080021#include <set>
22
23#include "class_linker.h"
Elliott Hughes1bba14f2011-12-01 18:00:36 -080024#include "class_loader.h"
Ian Rogers776ac1f2012-04-13 23:36:36 -070025#include "dex_instruction.h"
Mathieu Chartier1c23e1e2012-10-12 14:14:11 -070026#include "gc/large_object_space.h"
27#include "gc/space.h"
Ian Rogers2bcb4a42012-11-08 10:39:18 -080028#include "oat/runtime/context.h"
Ian Rogers6d4d9fc2011-11-30 16:24:48 -080029#include "object_utils.h"
Elliott Hughesa0e18062012-04-13 15:59:59 -070030#include "safe_map.h"
Elliott Hughes6a5bd492011-10-28 14:33:57 -070031#include "ScopedLocalRef.h"
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -070032#include "ScopedPrimitiveArray.h"
Ian Rogers00f7d0e2012-07-19 15:28:27 -070033#include "scoped_thread_state_change.h"
Ian Rogers1f539342012-10-03 21:09:42 -070034#include "sirt_ref.h"
Elliott Hughes47fce012011-10-25 18:37:19 -070035#include "stack_indirect_reference_table.h"
Elliott Hughes475fc232011-10-25 15:00:35 -070036#include "thread_list.h"
Elliott Hugheseac76672012-05-24 21:56:51 -070037#include "well_known_classes.h"
Elliott Hughes475fc232011-10-25 15:00:35 -070038
Elliott Hughes872d4ec2011-10-21 17:07:15 -070039namespace art {
40
Elliott Hughes545a0642011-11-08 19:10:03 -080041static const size_t kMaxAllocRecordStackDepth = 16; // Max 255.
42static const size_t kNumAllocRecords = 512; // Must be power of 2.
43
Elliott Hughes436e3722012-02-17 20:01:47 -080044static const uintptr_t kInvalidId = 1;
45static const Object* kInvalidObject = reinterpret_cast<Object*>(kInvalidId);
46
Elliott Hughes475fc232011-10-25 15:00:35 -070047class ObjectRegistry {
48 public:
49 ObjectRegistry() : lock_("ObjectRegistry lock") {
50 }
51
52 JDWP::ObjectId Add(Object* o) {
53 if (o == NULL) {
54 return 0;
55 }
56 JDWP::ObjectId id = static_cast<JDWP::ObjectId>(reinterpret_cast<uintptr_t>(o));
Ian Rogers50b35e22012-10-04 10:09:15 -070057 MutexLock mu(Thread::Current(), lock_);
Elliott Hughesa0e18062012-04-13 15:59:59 -070058 map_.Overwrite(id, o);
Elliott Hughes475fc232011-10-25 15:00:35 -070059 return id;
60 }
61
Elliott Hughes234ab152011-10-26 14:02:26 -070062 void Clear() {
Ian Rogers50b35e22012-10-04 10:09:15 -070063 MutexLock mu(Thread::Current(), lock_);
Elliott Hughes234ab152011-10-26 14:02:26 -070064 LOG(DEBUG) << "Debugger has detached; object registry had " << map_.size() << " entries";
65 map_.clear();
66 }
67
Elliott Hughes475fc232011-10-25 15:00:35 -070068 bool Contains(JDWP::ObjectId id) {
Ian Rogers50b35e22012-10-04 10:09:15 -070069 MutexLock mu(Thread::Current(), lock_);
Elliott Hughes475fc232011-10-25 15:00:35 -070070 return map_.find(id) != map_.end();
71 }
72
Elliott Hughesa2155262011-11-16 16:26:58 -080073 template<typename T> T Get(JDWP::ObjectId id) {
Elliott Hughes436e3722012-02-17 20:01:47 -080074 if (id == 0) {
75 return NULL;
76 }
77
Ian Rogers50b35e22012-10-04 10:09:15 -070078 MutexLock mu(Thread::Current(), lock_);
Elliott Hughesa0e18062012-04-13 15:59:59 -070079 typedef SafeMap<JDWP::ObjectId, Object*>::iterator It; // C++0x auto
Elliott Hughesa2155262011-11-16 16:26:58 -080080 It it = map_.find(id);
Elliott Hughes436e3722012-02-17 20:01:47 -080081 return (it != map_.end()) ? reinterpret_cast<T>(it->second) : reinterpret_cast<T>(kInvalidId);
Elliott Hughesa2155262011-11-16 16:26:58 -080082 }
83
Elliott Hughesbfe487b2011-10-26 15:48:55 -070084 void VisitRoots(Heap::RootVisitor* visitor, void* arg) {
Ian Rogers50b35e22012-10-04 10:09:15 -070085 MutexLock mu(Thread::Current(), lock_);
Elliott Hughesa0e18062012-04-13 15:59:59 -070086 typedef SafeMap<JDWP::ObjectId, Object*>::iterator It; // C++0x auto
Elliott Hughesbfe487b2011-10-26 15:48:55 -070087 for (It it = map_.begin(); it != map_.end(); ++it) {
88 visitor(it->second, arg);
89 }
90 }
91
Elliott Hughes475fc232011-10-25 15:00:35 -070092 private:
Ian Rogers00f7d0e2012-07-19 15:28:27 -070093 Mutex lock_ DEFAULT_MUTEX_ACQUIRED_AFTER;
Elliott Hughesa0e18062012-04-13 15:59:59 -070094 SafeMap<JDWP::ObjectId, Object*> map_;
Elliott Hughes475fc232011-10-25 15:00:35 -070095};
96
Elliott Hughes545a0642011-11-08 19:10:03 -080097struct AllocRecordStackTraceElement {
Mathieu Chartier66f19252012-09-18 08:57:04 -070098 AbstractMethod* method;
Ian Rogers0399dde2012-06-06 17:09:28 -070099 uint32_t dex_pc;
Elliott Hughes545a0642011-11-08 19:10:03 -0800100
Ian Rogersb726dcb2012-09-05 08:57:23 -0700101 int32_t LineNumber() const SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Ian Rogers0399dde2012-06-06 17:09:28 -0700102 return MethodHelper(method).GetLineNumFromDexPC(dex_pc);
Elliott Hughes545a0642011-11-08 19:10:03 -0800103 }
104};
105
106struct AllocRecord {
107 Class* type;
108 size_t byte_count;
109 uint16_t thin_lock_id;
110 AllocRecordStackTraceElement stack[kMaxAllocRecordStackDepth]; // Unused entries have NULL method.
111
112 size_t GetDepth() {
113 size_t depth = 0;
114 while (depth < kMaxAllocRecordStackDepth && stack[depth].method != NULL) {
115 ++depth;
116 }
117 return depth;
118 }
119};
120
Elliott Hughes86964332012-02-15 19:37:42 -0800121struct Breakpoint {
Mathieu Chartier66f19252012-09-18 08:57:04 -0700122 AbstractMethod* method;
Elliott Hughesa656a0f2012-02-21 18:03:44 -0800123 uint32_t dex_pc;
Mathieu Chartier66f19252012-09-18 08:57:04 -0700124 Breakpoint(AbstractMethod* method, uint32_t dex_pc) : method(method), dex_pc(dex_pc) {}
Elliott Hughes86964332012-02-15 19:37:42 -0800125};
126
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700127static std::ostream& operator<<(std::ostream& os, const Breakpoint& rhs)
Ian Rogersb726dcb2012-09-05 08:57:23 -0700128 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Elliott Hughes229feb72012-02-23 13:33:29 -0800129 os << StringPrintf("Breakpoint[%s @%#x]", PrettyMethod(rhs.method).c_str(), rhs.dex_pc);
Elliott Hughes86964332012-02-15 19:37:42 -0800130 return os;
131}
132
133struct SingleStepControl {
134 // Are we single-stepping right now?
135 bool is_active;
136 Thread* thread;
137
138 JDWP::JdwpStepSize step_size;
139 JDWP::JdwpStepDepth step_depth;
140
Mathieu Chartier66f19252012-09-18 08:57:04 -0700141 const AbstractMethod* method;
Elliott Hughes2435a572012-02-17 16:07:41 -0800142 int32_t line_number; // Or -1 for native methods.
143 std::set<uint32_t> dex_pcs;
Elliott Hughes86964332012-02-15 19:37:42 -0800144 int stack_depth;
145};
146
Elliott Hughes4ffd3132011-10-24 12:06:42 -0700147// JDWP is allowed unless the Zygote forbids it.
148static bool gJdwpAllowed = true;
149
Elliott Hughesc0f09332012-03-26 13:27:06 -0700150// Was there a -Xrunjdwp or -agentlib:jdwp= argument on the command line?
Elliott Hughes3bb81562011-10-21 18:52:59 -0700151static bool gJdwpConfigured = false;
152
Elliott Hughesc0f09332012-03-26 13:27:06 -0700153// Broken-down JDWP options. (Only valid if IsJdwpConfigured() is true.)
Elliott Hughes376a7a02011-10-24 18:35:55 -0700154static JDWP::JdwpOptions gJdwpOptions;
Elliott Hughes3bb81562011-10-21 18:52:59 -0700155
156// Runtime JDWP state.
157static JDWP::JdwpState* gJdwpState = NULL;
158static bool gDebuggerConnected; // debugger or DDMS is connected.
159static bool gDebuggerActive; // debugger is making requests.
Elliott Hughes86964332012-02-15 19:37:42 -0800160static bool gDisposed; // debugger called VirtualMachine.Dispose, so we should drop the connection.
Elliott Hughes3bb81562011-10-21 18:52:59 -0700161
Elliott Hughes47fce012011-10-25 18:37:19 -0700162static bool gDdmThreadNotification = false;
163
Elliott Hughes767a1472011-10-26 18:49:02 -0700164// DDMS GC-related settings.
165static Dbg::HpifWhen gDdmHpifWhen = Dbg::HPIF_WHEN_NEVER;
166static Dbg::HpsgWhen gDdmHpsgWhen = Dbg::HPSG_WHEN_NEVER;
167static Dbg::HpsgWhat gDdmHpsgWhat;
168static Dbg::HpsgWhen gDdmNhsgWhen = Dbg::HPSG_WHEN_NEVER;
169static Dbg::HpsgWhat gDdmNhsgWhat;
170
Elliott Hughes475fc232011-10-25 15:00:35 -0700171static ObjectRegistry* gRegistry = NULL;
172
Elliott Hughes545a0642011-11-08 19:10:03 -0800173// Recent allocation tracking.
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700174static Mutex gAllocTrackerLock DEFAULT_MUTEX_ACQUIRED_AFTER ("AllocTracker lock");
Elliott Hughesf8349362012-06-18 15:00:06 -0700175AllocRecord* Dbg::recent_allocation_records_ PT_GUARDED_BY(gAllocTrackerLock) = NULL; // TODO: CircularBuffer<AllocRecord>
176static size_t gAllocRecordHead GUARDED_BY(gAllocTrackerLock) = 0;
177static size_t gAllocRecordCount GUARDED_BY(gAllocTrackerLock) = 0;
Elliott Hughes545a0642011-11-08 19:10:03 -0800178
Elliott Hughes86964332012-02-15 19:37:42 -0800179// Breakpoints and single-stepping.
jeffhao09bfc6a2012-12-11 18:11:43 -0800180static std::vector<Breakpoint> gBreakpoints GUARDED_BY(Locks::breakpoint_lock_);
181static SingleStepControl gSingleStepControl GUARDED_BY(Locks::breakpoint_lock_);
Elliott Hughes86964332012-02-15 19:37:42 -0800182
Mathieu Chartier66f19252012-09-18 08:57:04 -0700183static bool IsBreakpoint(AbstractMethod* m, uint32_t dex_pc)
jeffhao09bfc6a2012-12-11 18:11:43 -0800184 LOCKS_EXCLUDED(Locks::breakpoint_lock_)
Ian Rogersb726dcb2012-09-05 08:57:23 -0700185 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
jeffhao09bfc6a2012-12-11 18:11:43 -0800186 MutexLock mu(Thread::Current(), *Locks::breakpoint_lock_);
Elliott Hughes86964332012-02-15 19:37:42 -0800187 for (size_t i = 0; i < gBreakpoints.size(); ++i) {
Elliott Hughesa656a0f2012-02-21 18:03:44 -0800188 if (gBreakpoints[i].method == m && gBreakpoints[i].dex_pc == dex_pc) {
Elliott Hughes86964332012-02-15 19:37:42 -0800189 VLOG(jdwp) << "Hit breakpoint #" << i << ": " << gBreakpoints[i];
190 return true;
191 }
192 }
193 return false;
194}
195
Elliott Hughes9e0c1752013-01-09 14:02:58 -0800196static bool IsSuspendedForDebugger(ScopedObjectAccessUnchecked& soa, Thread* thread) {
197 MutexLock mu(soa.Self(), *Locks::thread_suspend_count_lock_);
198 // A thread may be suspended for GC; in this code, we really want to know whether
199 // there's a debugger suspension active.
200 return thread->IsSuspended() && thread->GetDebugSuspendCount() > 0;
201}
202
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700203static Array* DecodeArray(JDWP::RefTypeId id, JDWP::JdwpError& status)
Ian Rogersb726dcb2012-09-05 08:57:23 -0700204 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Elliott Hughes436e3722012-02-17 20:01:47 -0800205 Object* o = gRegistry->Get<Object*>(id);
206 if (o == NULL || o == kInvalidObject) {
207 status = JDWP::ERR_INVALID_OBJECT;
208 return NULL;
209 }
210 if (!o->IsArrayInstance()) {
211 status = JDWP::ERR_INVALID_ARRAY;
212 return NULL;
213 }
214 status = JDWP::ERR_NONE;
215 return o->AsArray();
216}
217
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700218static Class* DecodeClass(JDWP::RefTypeId id, JDWP::JdwpError& status)
Ian Rogersb726dcb2012-09-05 08:57:23 -0700219 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Elliott Hughes436e3722012-02-17 20:01:47 -0800220 Object* o = gRegistry->Get<Object*>(id);
221 if (o == NULL || o == kInvalidObject) {
222 status = JDWP::ERR_INVALID_OBJECT;
223 return NULL;
224 }
225 if (!o->IsClass()) {
226 status = JDWP::ERR_INVALID_CLASS;
227 return NULL;
228 }
229 status = JDWP::ERR_NONE;
230 return o->AsClass();
231}
232
Elliott Hughes221229c2013-01-08 18:17:50 -0800233static JDWP::JdwpError DecodeThread(ScopedObjectAccessUnchecked& soa, JDWP::ObjectId thread_id, Thread*& thread)
jeffhaoa77f0f62012-12-05 17:19:31 -0800234 EXCLUSIVE_LOCKS_REQUIRED(Locks::thread_list_lock_)
Ian Rogersb726dcb2012-09-05 08:57:23 -0700235 LOCKS_EXCLUDED(Locks::thread_suspend_count_lock_)
236 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Elliott Hughes221229c2013-01-08 18:17:50 -0800237 Object* thread_peer = gRegistry->Get<Object*>(thread_id);
Elliott Hughes436e3722012-02-17 20:01:47 -0800238 if (thread_peer == NULL || thread_peer == kInvalidObject) {
Elliott Hughes221229c2013-01-08 18:17:50 -0800239 // This isn't even an object.
240 return JDWP::ERR_INVALID_OBJECT;
Elliott Hughes436e3722012-02-17 20:01:47 -0800241 }
Elliott Hughes221229c2013-01-08 18:17:50 -0800242
243 Class* java_lang_Thread = soa.Decode<Class*>(WellKnownClasses::java_lang_Thread);
244 if (!java_lang_Thread->IsAssignableFrom(thread_peer->GetClass())) {
245 // This isn't a thread.
246 return JDWP::ERR_INVALID_THREAD;
247 }
248
249 thread = Thread::FromManagedThread(soa, thread_peer);
250 if (thread == NULL) {
251 // This is a java.lang.Thread without a Thread*. Must be a zombie.
252 return JDWP::ERR_THREAD_NOT_ALIVE;
253 }
254 return JDWP::ERR_NONE;
Elliott Hughes436e3722012-02-17 20:01:47 -0800255}
256
Elliott Hughes24437992011-11-30 14:49:33 -0800257static JDWP::JdwpTag BasicTagFromDescriptor(const char* descriptor) {
258 // JDWP deliberately uses the descriptor characters' ASCII values for its enum.
259 // Note that by "basic" we mean that we don't get more specific than JT_OBJECT.
260 return static_cast<JDWP::JdwpTag>(descriptor[0]);
261}
262
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700263static JDWP::JdwpTag TagFromClass(Class* c)
Ian Rogersb726dcb2012-09-05 08:57:23 -0700264 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Elliott Hughes86b00102011-12-05 17:54:26 -0800265 CHECK(c != NULL);
Elliott Hughes24437992011-11-30 14:49:33 -0800266 if (c->IsArrayClass()) {
267 return JDWP::JT_ARRAY;
268 }
269
Elliott Hughes3d30d9b2011-12-07 17:35:48 -0800270 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
Elliott Hughes24437992011-11-30 14:49:33 -0800271 if (c->IsStringClass()) {
272 return JDWP::JT_STRING;
273 } else if (c->IsClassClass()) {
274 return JDWP::JT_CLASS_OBJECT;
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -0800275 } else if (class_linker->FindSystemClass("Ljava/lang/Thread;")->IsAssignableFrom(c)) {
Elliott Hughes24437992011-11-30 14:49:33 -0800276 return JDWP::JT_THREAD;
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -0800277 } else if (class_linker->FindSystemClass("Ljava/lang/ThreadGroup;")->IsAssignableFrom(c)) {
Elliott Hughes24437992011-11-30 14:49:33 -0800278 return JDWP::JT_THREAD_GROUP;
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -0800279 } else if (class_linker->FindSystemClass("Ljava/lang/ClassLoader;")->IsAssignableFrom(c)) {
Elliott Hughes24437992011-11-30 14:49:33 -0800280 return JDWP::JT_CLASS_LOADER;
Elliott Hughes24437992011-11-30 14:49:33 -0800281 } else {
282 return JDWP::JT_OBJECT;
283 }
284}
285
286/*
287 * Objects declared to hold Object might actually hold a more specific
288 * type. The debugger may take a special interest in these (e.g. it
289 * wants to display the contents of Strings), so we want to return an
290 * appropriate tag.
291 *
292 * Null objects are tagged JT_OBJECT.
293 */
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700294static JDWP::JdwpTag TagFromObject(const Object* o)
Ian Rogersb726dcb2012-09-05 08:57:23 -0700295 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Elliott Hughes24437992011-11-30 14:49:33 -0800296 return (o == NULL) ? JDWP::JT_OBJECT : TagFromClass(o->GetClass());
297}
298
299static bool IsPrimitiveTag(JDWP::JdwpTag tag) {
300 switch (tag) {
301 case JDWP::JT_BOOLEAN:
302 case JDWP::JT_BYTE:
303 case JDWP::JT_CHAR:
304 case JDWP::JT_FLOAT:
305 case JDWP::JT_DOUBLE:
306 case JDWP::JT_INT:
307 case JDWP::JT_LONG:
308 case JDWP::JT_SHORT:
309 case JDWP::JT_VOID:
310 return true;
311 default:
312 return false;
313 }
314}
315
Elliott Hughes3bb81562011-10-21 18:52:59 -0700316/*
317 * Handle one of the JDWP name/value pairs.
318 *
319 * JDWP options are:
320 * help: if specified, show help message and bail
321 * transport: may be dt_socket or dt_shmem
322 * address: for dt_socket, "host:port", or just "port" when listening
323 * server: if "y", wait for debugger to attach; if "n", attach to debugger
324 * timeout: how long to wait for debugger to connect / listen
325 *
326 * Useful with server=n (these aren't supported yet):
327 * onthrow=<exception-name>: connect to debugger when exception thrown
328 * onuncaught=y|n: connect to debugger when uncaught exception thrown
329 * launch=<command-line>: launch the debugger itself
330 *
331 * The "transport" option is required, as is "address" if server=n.
332 */
333static bool ParseJdwpOption(const std::string& name, const std::string& value) {
334 if (name == "transport") {
335 if (value == "dt_socket") {
Elliott Hughes376a7a02011-10-24 18:35:55 -0700336 gJdwpOptions.transport = JDWP::kJdwpTransportSocket;
Elliott Hughes3bb81562011-10-21 18:52:59 -0700337 } else if (value == "dt_android_adb") {
Elliott Hughes376a7a02011-10-24 18:35:55 -0700338 gJdwpOptions.transport = JDWP::kJdwpTransportAndroidAdb;
Elliott Hughes3bb81562011-10-21 18:52:59 -0700339 } else {
340 LOG(ERROR) << "JDWP transport not supported: " << value;
341 return false;
342 }
343 } else if (name == "server") {
344 if (value == "n") {
Elliott Hughes376a7a02011-10-24 18:35:55 -0700345 gJdwpOptions.server = false;
Elliott Hughes3bb81562011-10-21 18:52:59 -0700346 } else if (value == "y") {
Elliott Hughes376a7a02011-10-24 18:35:55 -0700347 gJdwpOptions.server = true;
Elliott Hughes3bb81562011-10-21 18:52:59 -0700348 } else {
349 LOG(ERROR) << "JDWP option 'server' must be 'y' or 'n'";
350 return false;
351 }
352 } else if (name == "suspend") {
353 if (value == "n") {
Elliott Hughes376a7a02011-10-24 18:35:55 -0700354 gJdwpOptions.suspend = false;
Elliott Hughes3bb81562011-10-21 18:52:59 -0700355 } else if (value == "y") {
Elliott Hughes376a7a02011-10-24 18:35:55 -0700356 gJdwpOptions.suspend = true;
Elliott Hughes3bb81562011-10-21 18:52:59 -0700357 } else {
358 LOG(ERROR) << "JDWP option 'suspend' must be 'y' or 'n'";
359 return false;
360 }
361 } else if (name == "address") {
362 /* this is either <port> or <host>:<port> */
363 std::string port_string;
Elliott Hughes376a7a02011-10-24 18:35:55 -0700364 gJdwpOptions.host.clear();
Elliott Hughes3bb81562011-10-21 18:52:59 -0700365 std::string::size_type colon = value.find(':');
366 if (colon != std::string::npos) {
Elliott Hughes376a7a02011-10-24 18:35:55 -0700367 gJdwpOptions.host = value.substr(0, colon);
Elliott Hughes3bb81562011-10-21 18:52:59 -0700368 port_string = value.substr(colon + 1);
369 } else {
370 port_string = value;
371 }
372 if (port_string.empty()) {
373 LOG(ERROR) << "JDWP address missing port: " << value;
374 return false;
375 }
376 char* end;
Elliott Hughesba8eee12012-01-24 20:25:24 -0800377 uint64_t port = strtoul(port_string.c_str(), &end, 10);
378 if (*end != '\0' || port > 0xffff) {
Elliott Hughes3bb81562011-10-21 18:52:59 -0700379 LOG(ERROR) << "JDWP address has junk in port field: " << value;
380 return false;
381 }
Elliott Hughes376a7a02011-10-24 18:35:55 -0700382 gJdwpOptions.port = port;
Elliott Hughes3bb81562011-10-21 18:52:59 -0700383 } else if (name == "launch" || name == "onthrow" || name == "oncaught" || name == "timeout") {
384 /* valid but unsupported */
385 LOG(INFO) << "Ignoring JDWP option '" << name << "'='" << value << "'";
386 } else {
387 LOG(INFO) << "Ignoring unrecognized JDWP option '" << name << "'='" << value << "'";
388 }
389
390 return true;
391}
392
393/*
394 * Parse the latter half of a -Xrunjdwp/-agentlib:jdwp= string, e.g.:
395 * "transport=dt_socket,address=8000,server=y,suspend=n"
396 */
397bool Dbg::ParseJdwpOptions(const std::string& options) {
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -0800398 VLOG(jdwp) << "ParseJdwpOptions: " << options;
Elliott Hughes47fce012011-10-25 18:37:19 -0700399
Elliott Hughes3bb81562011-10-21 18:52:59 -0700400 std::vector<std::string> pairs;
401 Split(options, ',', pairs);
402
403 for (size_t i = 0; i < pairs.size(); ++i) {
404 std::string::size_type equals = pairs[i].find('=');
405 if (equals == std::string::npos) {
406 LOG(ERROR) << "Can't parse JDWP option '" << pairs[i] << "' in '" << options << "'";
407 return false;
408 }
409 ParseJdwpOption(pairs[i].substr(0, equals), pairs[i].substr(equals + 1));
410 }
411
Elliott Hughes376a7a02011-10-24 18:35:55 -0700412 if (gJdwpOptions.transport == JDWP::kJdwpTransportUnknown) {
Elliott Hughes3bb81562011-10-21 18:52:59 -0700413 LOG(ERROR) << "Must specify JDWP transport: " << options;
414 }
Elliott Hughes376a7a02011-10-24 18:35:55 -0700415 if (!gJdwpOptions.server && (gJdwpOptions.host.empty() || gJdwpOptions.port == 0)) {
Elliott Hughes3bb81562011-10-21 18:52:59 -0700416 LOG(ERROR) << "Must specify JDWP host and port when server=n: " << options;
417 return false;
418 }
419
420 gJdwpConfigured = true;
421 return true;
422}
423
Elliott Hughesd1cc8362011-10-24 16:58:50 -0700424void Dbg::StartJdwp() {
Elliott Hughesc0f09332012-03-26 13:27:06 -0700425 if (!gJdwpAllowed || !IsJdwpConfigured()) {
Elliott Hughes376a7a02011-10-24 18:35:55 -0700426 // No JDWP for you!
427 return;
428 }
429
Elliott Hughes475fc232011-10-25 15:00:35 -0700430 CHECK(gRegistry == NULL);
431 gRegistry = new ObjectRegistry;
432
Elliott Hughesd1cc8362011-10-24 16:58:50 -0700433 // Init JDWP if the debugger is enabled. This may connect out to a
434 // debugger, passively listen for a debugger, or block waiting for a
435 // debugger.
Elliott Hughes376a7a02011-10-24 18:35:55 -0700436 gJdwpState = JDWP::JdwpState::Create(&gJdwpOptions);
437 if (gJdwpState == NULL) {
Elliott Hughesf8a2df72011-12-01 12:19:54 -0800438 // We probably failed because some other process has the port already, which means that
439 // if we don't abort the user is likely to think they're talking to us when they're actually
440 // talking to that other process.
Elliott Hughes3d30d9b2011-12-07 17:35:48 -0800441 LOG(FATAL) << "Debugger thread failed to initialize";
Elliott Hughesd1cc8362011-10-24 16:58:50 -0700442 }
443
444 // If a debugger has already attached, send the "welcome" message.
445 // This may cause us to suspend all threads.
Elliott Hughes376a7a02011-10-24 18:35:55 -0700446 if (gJdwpState->IsActive()) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700447 ScopedObjectAccess soa(Thread::Current());
Elliott Hughes376a7a02011-10-24 18:35:55 -0700448 if (!gJdwpState->PostVMStart()) {
Elliott Hughes3d30d9b2011-12-07 17:35:48 -0800449 LOG(WARNING) << "Failed to post 'start' message to debugger";
Elliott Hughesd1cc8362011-10-24 16:58:50 -0700450 }
451 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700452}
453
Elliott Hughesd1cc8362011-10-24 16:58:50 -0700454void Dbg::StopJdwp() {
Elliott Hughes376a7a02011-10-24 18:35:55 -0700455 delete gJdwpState;
Elliott Hughes475fc232011-10-25 15:00:35 -0700456 delete gRegistry;
457 gRegistry = NULL;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700458}
459
Elliott Hughes767a1472011-10-26 18:49:02 -0700460void Dbg::GcDidFinish() {
461 if (gDdmHpifWhen != HPIF_WHEN_NEVER) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700462 ScopedObjectAccess soa(Thread::Current());
Elliott Hughes81ff3182012-03-23 20:35:56 -0700463 LOG(DEBUG) << "Sending heap info to DDM";
Elliott Hughes7162ad92011-10-27 14:08:42 -0700464 DdmSendHeapInfo(gDdmHpifWhen);
Elliott Hughes767a1472011-10-26 18:49:02 -0700465 }
466 if (gDdmHpsgWhen != HPSG_WHEN_NEVER) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700467 ScopedObjectAccess soa(Thread::Current());
Elliott Hughes81ff3182012-03-23 20:35:56 -0700468 LOG(DEBUG) << "Dumping heap to DDM";
Elliott Hughes6a5bd492011-10-28 14:33:57 -0700469 DdmSendHeapSegments(false);
Elliott Hughes767a1472011-10-26 18:49:02 -0700470 }
471 if (gDdmNhsgWhen != HPSG_WHEN_NEVER) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700472 ScopedObjectAccess soa(Thread::Current());
Elliott Hughes767a1472011-10-26 18:49:02 -0700473 LOG(DEBUG) << "Dumping native heap to DDM";
Elliott Hughes6a5bd492011-10-28 14:33:57 -0700474 DdmSendHeapSegments(true);
Elliott Hughes767a1472011-10-26 18:49:02 -0700475 }
476}
477
Elliott Hughes4ffd3132011-10-24 12:06:42 -0700478void Dbg::SetJdwpAllowed(bool allowed) {
479 gJdwpAllowed = allowed;
480}
481
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700482DebugInvokeReq* Dbg::GetInvokeReq() {
Elliott Hughes475fc232011-10-25 15:00:35 -0700483 return Thread::Current()->GetInvokeReq();
484}
485
486Thread* Dbg::GetDebugThread() {
487 return (gJdwpState != NULL) ? gJdwpState->GetDebugThread() : NULL;
488}
489
490void Dbg::ClearWaitForEventThread() {
491 gJdwpState->ClearWaitForEventThread();
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700492}
493
494void Dbg::Connected() {
Elliott Hughes3bb81562011-10-21 18:52:59 -0700495 CHECK(!gDebuggerConnected);
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -0800496 VLOG(jdwp) << "JDWP has attached";
Elliott Hughes3bb81562011-10-21 18:52:59 -0700497 gDebuggerConnected = true;
Elliott Hughes86964332012-02-15 19:37:42 -0800498 gDisposed = false;
499}
500
501void Dbg::Disposed() {
502 gDisposed = true;
503}
504
505bool Dbg::IsDisposed() {
506 return gDisposed;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700507}
508
Elliott Hughesc0f09332012-03-26 13:27:06 -0700509static void SetDebuggerUpdatesEnabledCallback(Thread* t, void* user_data) {
510 t->SetDebuggerUpdatesEnabled(*reinterpret_cast<bool*>(user_data));
511}
512
513static void SetDebuggerUpdatesEnabled(bool enabled) {
Ian Rogers50b35e22012-10-04 10:09:15 -0700514 MutexLock mu(Thread::Current(), *Locks::thread_list_lock_);
Elliott Hughesf8349362012-06-18 15:00:06 -0700515 Runtime::Current()->GetThreadList()->ForEach(SetDebuggerUpdatesEnabledCallback, &enabled);
Elliott Hughesc0f09332012-03-26 13:27:06 -0700516}
517
Elliott Hughesa2155262011-11-16 16:26:58 -0800518void Dbg::GoActive() {
519 // Enable all debugging features, including scans for breakpoints.
520 // This is a no-op if we're already active.
521 // Only called from the JDWP handler thread.
522 if (gDebuggerActive) {
523 return;
524 }
525
526 LOG(INFO) << "Debugger is active";
527
Elliott Hughesc0f09332012-03-26 13:27:06 -0700528 {
529 // TODO: dalvik only warned if there were breakpoints left over. clear in Dbg::Disconnected?
jeffhao09bfc6a2012-12-11 18:11:43 -0800530 MutexLock mu(Thread::Current(), *Locks::breakpoint_lock_);
Elliott Hughesc0f09332012-03-26 13:27:06 -0700531 CHECK_EQ(gBreakpoints.size(), 0U);
532 }
Elliott Hughesa2155262011-11-16 16:26:58 -0800533
534 gDebuggerActive = true;
Elliott Hughesc0f09332012-03-26 13:27:06 -0700535 SetDebuggerUpdatesEnabled(true);
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700536}
537
538void Dbg::Disconnected() {
Elliott Hughes234ab152011-10-26 14:02:26 -0700539 CHECK(gDebuggerConnected);
540
Elliott Hughesc0f09332012-03-26 13:27:06 -0700541 LOG(INFO) << "Debugger is no longer active";
Elliott Hughes234ab152011-10-26 14:02:26 -0700542
Elliott Hughesc0f09332012-03-26 13:27:06 -0700543 gDebuggerActive = false;
544 SetDebuggerUpdatesEnabled(false);
Elliott Hughes234ab152011-10-26 14:02:26 -0700545
546 gRegistry->Clear();
547 gDebuggerConnected = false;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700548}
549
Elliott Hughesc0f09332012-03-26 13:27:06 -0700550bool Dbg::IsDebuggerActive() {
Elliott Hughes3bb81562011-10-21 18:52:59 -0700551 return gDebuggerActive;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700552}
553
Elliott Hughesc0f09332012-03-26 13:27:06 -0700554bool Dbg::IsJdwpConfigured() {
Elliott Hughes3bb81562011-10-21 18:52:59 -0700555 return gJdwpConfigured;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700556}
557
558int64_t Dbg::LastDebuggerActivity() {
Elliott Hughesca951522011-12-05 12:01:32 -0800559 return gJdwpState->LastDebuggerActivity();
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700560}
561
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700562void Dbg::UndoDebuggerSuspensions() {
Elliott Hughes234ab152011-10-26 14:02:26 -0700563 Runtime::Current()->GetThreadList()->UndoDebuggerSuspensions();
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700564}
565
566void Dbg::Exit(int status) {
Elliott Hughes1bba14f2011-12-01 18:00:36 -0800567 exit(status); // This is all dalvik did.
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700568}
569
Elliott Hughesbfe487b2011-10-26 15:48:55 -0700570void Dbg::VisitRoots(Heap::RootVisitor* visitor, void* arg) {
571 if (gRegistry != NULL) {
572 gRegistry->VisitRoots(visitor, arg);
573 }
574}
575
Elliott Hughes88d63092013-01-09 09:55:54 -0800576std::string Dbg::GetClassName(JDWP::RefTypeId class_id) {
577 Object* o = gRegistry->Get<Object*>(class_id);
Elliott Hughes436e3722012-02-17 20:01:47 -0800578 if (o == NULL) {
579 return "NULL";
580 }
581 if (o == kInvalidObject) {
Elliott Hughes88d63092013-01-09 09:55:54 -0800582 return StringPrintf("invalid object %p", reinterpret_cast<void*>(class_id));
Elliott Hughes436e3722012-02-17 20:01:47 -0800583 }
584 if (!o->IsClass()) {
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -0800585 return StringPrintf("non-class %p", o); // This is only used for debugging output anyway.
586 }
Elliott Hughesc308a5d2012-02-16 17:12:06 -0800587 return DescriptorToName(ClassHelper(o->AsClass()).GetDescriptor());
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700588}
589
Elliott Hughes88d63092013-01-09 09:55:54 -0800590JDWP::JdwpError Dbg::GetClassObject(JDWP::RefTypeId id, JDWP::ObjectId& class_object_id) {
Elliott Hughes436e3722012-02-17 20:01:47 -0800591 JDWP::JdwpError status;
592 Class* c = DecodeClass(id, status);
593 if (c == NULL) {
594 return status;
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -0800595 }
Elliott Hughes88d63092013-01-09 09:55:54 -0800596 class_object_id = gRegistry->Add(c);
Elliott Hughes436e3722012-02-17 20:01:47 -0800597 return JDWP::ERR_NONE;
Elliott Hughes86964332012-02-15 19:37:42 -0800598}
599
Elliott Hughes88d63092013-01-09 09:55:54 -0800600JDWP::JdwpError Dbg::GetSuperclass(JDWP::RefTypeId id, JDWP::RefTypeId& superclass_id) {
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -0800601 JDWP::JdwpError status;
602 Class* c = DecodeClass(id, status);
603 if (c == NULL) {
604 return status;
605 }
606 if (c->IsInterface()) {
607 // http://code.google.com/p/android/issues/detail?id=20856
Elliott Hughes88d63092013-01-09 09:55:54 -0800608 superclass_id = 0;
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -0800609 } else {
Elliott Hughes88d63092013-01-09 09:55:54 -0800610 superclass_id = gRegistry->Add(c->GetSuperClass());
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -0800611 }
612 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700613}
614
Elliott Hughes436e3722012-02-17 20:01:47 -0800615JDWP::JdwpError Dbg::GetClassLoader(JDWP::RefTypeId id, JDWP::ExpandBuf* pReply) {
Elliott Hughes1bba14f2011-12-01 18:00:36 -0800616 Object* o = gRegistry->Get<Object*>(id);
Elliott Hughes436e3722012-02-17 20:01:47 -0800617 if (o == NULL || o == kInvalidObject) {
618 return JDWP::ERR_INVALID_OBJECT;
619 }
620 expandBufAddObjectId(pReply, gRegistry->Add(o->GetClass()->GetClassLoader()));
621 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700622}
623
Elliott Hughes436e3722012-02-17 20:01:47 -0800624JDWP::JdwpError Dbg::GetModifiers(JDWP::RefTypeId id, JDWP::ExpandBuf* pReply) {
625 JDWP::JdwpError status;
626 Class* c = DecodeClass(id, status);
627 if (c == NULL) {
628 return status;
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -0800629 }
Elliott Hughes436e3722012-02-17 20:01:47 -0800630
631 uint32_t access_flags = c->GetAccessFlags() & kAccJavaFlagsMask;
632
633 // Set ACC_SUPER; dex files don't contain this flag, but all classes are supposed to have it set.
634 // Class.getModifiers doesn't return it, but JDWP does, so we set it here.
635 access_flags |= kAccSuper;
636
637 expandBufAdd4BE(pReply, access_flags);
638
639 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700640}
641
Elliott Hughes88d63092013-01-09 09:55:54 -0800642JDWP::JdwpError Dbg::GetReflectedType(JDWP::RefTypeId class_id, JDWP::ExpandBuf* pReply) {
Elliott Hughes436e3722012-02-17 20:01:47 -0800643 JDWP::JdwpError status;
Elliott Hughes88d63092013-01-09 09:55:54 -0800644 Class* c = DecodeClass(class_id, status);
Elliott Hughes436e3722012-02-17 20:01:47 -0800645 if (c == NULL) {
646 return status;
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -0800647 }
Elliott Hughes436e3722012-02-17 20:01:47 -0800648
649 expandBufAdd1(pReply, c->IsInterface() ? JDWP::TT_INTERFACE : JDWP::TT_CLASS);
Elliott Hughes88d63092013-01-09 09:55:54 -0800650 expandBufAddRefTypeId(pReply, class_id);
Elliott Hughes436e3722012-02-17 20:01:47 -0800651 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700652}
653
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -0800654void Dbg::GetClassList(std::vector<JDWP::RefTypeId>& classes) {
Elliott Hughesa2155262011-11-16 16:26:58 -0800655 // Get the complete list of reference classes (i.e. all classes except
656 // the primitive types).
657 // Returns a newly-allocated buffer full of RefTypeId values.
658 struct ClassListCreator {
Elliott Hughesba8eee12012-01-24 20:25:24 -0800659 explicit ClassListCreator(std::vector<JDWP::RefTypeId>& classes) : classes(classes) {
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -0800660 }
661
Elliott Hughesa2155262011-11-16 16:26:58 -0800662 static bool Visit(Class* c, void* arg) {
663 return reinterpret_cast<ClassListCreator*>(arg)->Visit(c);
664 }
665
666 bool Visit(Class* c) {
667 if (!c->IsPrimitive()) {
668 classes.push_back(static_cast<JDWP::RefTypeId>(gRegistry->Add(c)));
669 }
670 return true;
671 }
672
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -0800673 std::vector<JDWP::RefTypeId>& classes;
Elliott Hughesa2155262011-11-16 16:26:58 -0800674 };
675
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -0800676 ClassListCreator clc(classes);
Elliott Hughesa2155262011-11-16 16:26:58 -0800677 Runtime::Current()->GetClassLinker()->VisitClasses(ClassListCreator::Visit, &clc);
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700678}
679
Elliott Hughes88d63092013-01-09 09:55:54 -0800680JDWP::JdwpError Dbg::GetClassInfo(JDWP::RefTypeId class_id, JDWP::JdwpTypeTag* pTypeTag, uint32_t* pStatus, std::string* pDescriptor) {
Elliott Hughes436e3722012-02-17 20:01:47 -0800681 JDWP::JdwpError status;
Elliott Hughes88d63092013-01-09 09:55:54 -0800682 Class* c = DecodeClass(class_id, status);
Elliott Hughes436e3722012-02-17 20:01:47 -0800683 if (c == NULL) {
684 return status;
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -0800685 }
686
Elliott Hughesa2155262011-11-16 16:26:58 -0800687 if (c->IsArrayClass()) {
688 *pStatus = JDWP::CS_VERIFIED | JDWP::CS_PREPARED;
689 *pTypeTag = JDWP::TT_ARRAY;
690 } else {
691 if (c->IsErroneous()) {
692 *pStatus = JDWP::CS_ERROR;
693 } else {
694 *pStatus = JDWP::CS_VERIFIED | JDWP::CS_PREPARED | JDWP::CS_INITIALIZED;
695 }
696 *pTypeTag = c->IsInterface() ? JDWP::TT_INTERFACE : JDWP::TT_CLASS;
697 }
698
699 if (pDescriptor != NULL) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800700 *pDescriptor = ClassHelper(c).GetDescriptor();
Elliott Hughesa2155262011-11-16 16:26:58 -0800701 }
Elliott Hughes436e3722012-02-17 20:01:47 -0800702 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700703}
704
Elliott Hughesc3b77c72011-12-15 20:56:48 -0800705void Dbg::FindLoadedClassBySignature(const char* descriptor, std::vector<JDWP::RefTypeId>& ids) {
Elliott Hughes6fa602d2011-12-02 17:54:25 -0800706 std::vector<Class*> classes;
707 Runtime::Current()->GetClassLinker()->LookupClasses(descriptor, classes);
708 ids.clear();
709 for (size_t i = 0; i < classes.size(); ++i) {
710 ids.push_back(gRegistry->Add(classes[i]));
711 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700712}
713
Elliott Hughes88d63092013-01-09 09:55:54 -0800714JDWP::JdwpError Dbg::GetReferenceType(JDWP::ObjectId object_id, JDWP::ExpandBuf* pReply) {
715 Object* o = gRegistry->Get<Object*>(object_id);
Elliott Hughes436e3722012-02-17 20:01:47 -0800716 if (o == NULL || o == kInvalidObject) {
Elliott Hughes2435a572012-02-17 16:07:41 -0800717 return JDWP::ERR_INVALID_OBJECT;
Elliott Hughes499c5132011-11-17 14:55:11 -0800718 }
Elliott Hughes2435a572012-02-17 16:07:41 -0800719
720 JDWP::JdwpTypeTag type_tag;
721 if (o->GetClass()->IsArrayClass()) {
722 type_tag = JDWP::TT_ARRAY;
723 } else if (o->GetClass()->IsInterface()) {
724 type_tag = JDWP::TT_INTERFACE;
725 } else {
726 type_tag = JDWP::TT_CLASS;
727 }
728 JDWP::RefTypeId type_id = gRegistry->Add(o->GetClass());
729
730 expandBufAdd1(pReply, type_tag);
731 expandBufAddRefTypeId(pReply, type_id);
732
733 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700734}
735
Elliott Hughes88d63092013-01-09 09:55:54 -0800736JDWP::JdwpError Dbg::GetSignature(JDWP::RefTypeId class_id, std::string& signature) {
Elliott Hughes1fe7afb2012-02-13 17:23:03 -0800737 JDWP::JdwpError status;
Elliott Hughes88d63092013-01-09 09:55:54 -0800738 Class* c = DecodeClass(class_id, status);
Elliott Hughes1fe7afb2012-02-13 17:23:03 -0800739 if (c == NULL) {
740 return status;
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -0800741 }
Elliott Hughes1fe7afb2012-02-13 17:23:03 -0800742 signature = ClassHelper(c).GetDescriptor();
743 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700744}
745
Elliott Hughes88d63092013-01-09 09:55:54 -0800746JDWP::JdwpError Dbg::GetSourceFile(JDWP::RefTypeId class_id, std::string& result) {
Elliott Hughes436e3722012-02-17 20:01:47 -0800747 JDWP::JdwpError status;
Elliott Hughes88d63092013-01-09 09:55:54 -0800748 Class* c = DecodeClass(class_id, status);
Elliott Hughes436e3722012-02-17 20:01:47 -0800749 if (c == NULL) {
750 return status;
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -0800751 }
Elliott Hughes436e3722012-02-17 20:01:47 -0800752 result = ClassHelper(c).GetSourceFile();
753 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700754}
755
Elliott Hughes88d63092013-01-09 09:55:54 -0800756JDWP::JdwpError Dbg::GetObjectTag(JDWP::ObjectId object_id, uint8_t& tag) {
757 Object* o = gRegistry->Get<Object*>(object_id);
Elliott Hughes546b9862012-06-20 16:06:13 -0700758 if (o == kInvalidObject) {
759 return JDWP::ERR_INVALID_OBJECT;
760 }
761 tag = TagFromObject(o);
762 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700763}
764
Elliott Hughesaed4be92011-12-02 16:16:23 -0800765size_t Dbg::GetTagWidth(JDWP::JdwpTag tag) {
Elliott Hughesdbb40792011-11-18 17:05:22 -0800766 switch (tag) {
767 case JDWP::JT_VOID:
768 return 0;
769 case JDWP::JT_BYTE:
770 case JDWP::JT_BOOLEAN:
771 return 1;
772 case JDWP::JT_CHAR:
773 case JDWP::JT_SHORT:
774 return 2;
775 case JDWP::JT_FLOAT:
776 case JDWP::JT_INT:
777 return 4;
778 case JDWP::JT_ARRAY:
779 case JDWP::JT_OBJECT:
780 case JDWP::JT_STRING:
781 case JDWP::JT_THREAD:
782 case JDWP::JT_THREAD_GROUP:
783 case JDWP::JT_CLASS_LOADER:
784 case JDWP::JT_CLASS_OBJECT:
785 return sizeof(JDWP::ObjectId);
786 case JDWP::JT_DOUBLE:
787 case JDWP::JT_LONG:
788 return 8;
789 default:
Elliott Hughes3d30d9b2011-12-07 17:35:48 -0800790 LOG(FATAL) << "Unknown tag " << tag;
Elliott Hughesdbb40792011-11-18 17:05:22 -0800791 return -1;
792 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700793}
794
Elliott Hughes88d63092013-01-09 09:55:54 -0800795JDWP::JdwpError Dbg::GetArrayLength(JDWP::ObjectId array_id, int& length) {
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -0800796 JDWP::JdwpError status;
Elliott Hughes88d63092013-01-09 09:55:54 -0800797 Array* a = DecodeArray(array_id, status);
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -0800798 if (a == NULL) {
799 return status;
Elliott Hughes24437992011-11-30 14:49:33 -0800800 }
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -0800801 length = a->GetLength();
802 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700803}
804
Elliott Hughes88d63092013-01-09 09:55:54 -0800805JDWP::JdwpError Dbg::OutputArray(JDWP::ObjectId array_id, int offset, int count, JDWP::ExpandBuf* pReply) {
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -0800806 JDWP::JdwpError status;
Elliott Hughes88d63092013-01-09 09:55:54 -0800807 Array* a = DecodeArray(array_id, status);
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -0800808 if (a == NULL) {
809 return status;
810 }
Elliott Hughes24437992011-11-30 14:49:33 -0800811
812 if (offset < 0 || count < 0 || offset > a->GetLength() || a->GetLength() - offset < count) {
813 LOG(WARNING) << __FUNCTION__ << " access out of bounds: offset=" << offset << "; count=" << count;
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -0800814 return JDWP::ERR_INVALID_LENGTH;
Elliott Hughes24437992011-11-30 14:49:33 -0800815 }
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800816 std::string descriptor(ClassHelper(a->GetClass()).GetDescriptor());
Elliott Hughes24437992011-11-30 14:49:33 -0800817 JDWP::JdwpTag tag = BasicTagFromDescriptor(descriptor.c_str() + 1);
818
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -0800819 expandBufAdd1(pReply, tag);
820 expandBufAdd4BE(pReply, count);
821
Elliott Hughes24437992011-11-30 14:49:33 -0800822 if (IsPrimitiveTag(tag)) {
823 size_t width = GetTagWidth(tag);
Elliott Hughes24437992011-11-30 14:49:33 -0800824 uint8_t* dst = expandBufAddSpace(pReply, count * width);
825 if (width == 8) {
Ian Rogersa15e67d2012-02-28 13:51:55 -0800826 const uint64_t* src8 = reinterpret_cast<uint64_t*>(a->GetRawData(sizeof(uint64_t)));
Elliott Hughes24437992011-11-30 14:49:33 -0800827 for (int i = 0; i < count; ++i) JDWP::Write8BE(&dst, src8[offset + i]);
828 } else if (width == 4) {
Ian Rogersa15e67d2012-02-28 13:51:55 -0800829 const uint32_t* src4 = reinterpret_cast<uint32_t*>(a->GetRawData(sizeof(uint32_t)));
Elliott Hughes24437992011-11-30 14:49:33 -0800830 for (int i = 0; i < count; ++i) JDWP::Write4BE(&dst, src4[offset + i]);
831 } else if (width == 2) {
Ian Rogersa15e67d2012-02-28 13:51:55 -0800832 const uint16_t* src2 = reinterpret_cast<uint16_t*>(a->GetRawData(sizeof(uint16_t)));
Elliott Hughes24437992011-11-30 14:49:33 -0800833 for (int i = 0; i < count; ++i) JDWP::Write2BE(&dst, src2[offset + i]);
834 } else {
Ian Rogersa15e67d2012-02-28 13:51:55 -0800835 const uint8_t* src = reinterpret_cast<uint8_t*>(a->GetRawData(sizeof(uint8_t)));
Elliott Hughes24437992011-11-30 14:49:33 -0800836 memcpy(dst, &src[offset * width], count * width);
837 }
838 } else {
839 ObjectArray<Object>* oa = a->AsObjectArray<Object>();
840 for (int i = 0; i < count; ++i) {
Elliott Hughesf03b8f62011-12-02 14:26:25 -0800841 Object* element = oa->Get(offset + i);
Elliott Hughes24437992011-11-30 14:49:33 -0800842 JDWP::JdwpTag specific_tag = (element != NULL) ? TagFromObject(element) : tag;
843 expandBufAdd1(pReply, specific_tag);
844 expandBufAddObjectId(pReply, gRegistry->Add(element));
845 }
846 }
847
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -0800848 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700849}
850
Elliott Hughes88d63092013-01-09 09:55:54 -0800851JDWP::JdwpError Dbg::SetArrayElements(JDWP::ObjectId array_id, int offset, int count,
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700852 const uint8_t* src)
Ian Rogersb726dcb2012-09-05 08:57:23 -0700853 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -0800854 JDWP::JdwpError status;
Elliott Hughes88d63092013-01-09 09:55:54 -0800855 Array* a = DecodeArray(array_id, status);
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -0800856 if (a == NULL) {
857 return status;
858 }
Elliott Hughesf03b8f62011-12-02 14:26:25 -0800859
860 if (offset < 0 || count < 0 || offset > a->GetLength() || a->GetLength() - offset < count) {
861 LOG(WARNING) << __FUNCTION__ << " access out of bounds: offset=" << offset << "; count=" << count;
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -0800862 return JDWP::ERR_INVALID_LENGTH;
Elliott Hughesf03b8f62011-12-02 14:26:25 -0800863 }
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800864 std::string descriptor(ClassHelper(a->GetClass()).GetDescriptor());
Elliott Hughesf03b8f62011-12-02 14:26:25 -0800865 JDWP::JdwpTag tag = BasicTagFromDescriptor(descriptor.c_str() + 1);
866
867 if (IsPrimitiveTag(tag)) {
868 size_t width = GetTagWidth(tag);
Elliott Hughesf03b8f62011-12-02 14:26:25 -0800869 if (width == 8) {
Ian Rogersa15e67d2012-02-28 13:51:55 -0800870 uint8_t* dst = &(reinterpret_cast<uint8_t*>(a->GetRawData(sizeof(uint64_t)))[offset * width]);
Elliott Hughesf03b8f62011-12-02 14:26:25 -0800871 for (int i = 0; i < count; ++i) {
872 // Handle potentially non-aligned memory access one byte at a time for ARM's benefit.
873 uint64_t value;
874 for (size_t j = 0; j < sizeof(uint64_t); ++j) reinterpret_cast<uint8_t*>(&value)[j] = src[j];
875 src += sizeof(uint64_t);
876 JDWP::Write8BE(&dst, value);
877 }
878 } else if (width == 4) {
Ian Rogersa15e67d2012-02-28 13:51:55 -0800879 uint8_t* dst = &(reinterpret_cast<uint8_t*>(a->GetRawData(sizeof(uint32_t)))[offset * width]);
Elliott Hughesf03b8f62011-12-02 14:26:25 -0800880 const uint32_t* src4 = reinterpret_cast<const uint32_t*>(src);
881 for (int i = 0; i < count; ++i) JDWP::Write4BE(&dst, src4[i]);
882 } else if (width == 2) {
Ian Rogersa15e67d2012-02-28 13:51:55 -0800883 uint8_t* dst = &(reinterpret_cast<uint8_t*>(a->GetRawData(sizeof(uint16_t)))[offset * width]);
Elliott Hughesf03b8f62011-12-02 14:26:25 -0800884 const uint16_t* src2 = reinterpret_cast<const uint16_t*>(src);
885 for (int i = 0; i < count; ++i) JDWP::Write2BE(&dst, src2[i]);
886 } else {
Ian Rogersa15e67d2012-02-28 13:51:55 -0800887 uint8_t* dst = &(reinterpret_cast<uint8_t*>(a->GetRawData(sizeof(uint8_t)))[offset * width]);
Elliott Hughesf03b8f62011-12-02 14:26:25 -0800888 memcpy(&dst[offset * width], src, count * width);
889 }
890 } else {
891 ObjectArray<Object>* oa = a->AsObjectArray<Object>();
892 for (int i = 0; i < count; ++i) {
893 JDWP::ObjectId id = JDWP::ReadObjectId(&src);
Elliott Hughes436e3722012-02-17 20:01:47 -0800894 Object* o = gRegistry->Get<Object*>(id);
895 if (o == kInvalidObject) {
896 return JDWP::ERR_INVALID_OBJECT;
897 }
898 oa->Set(offset + i, o);
Elliott Hughesf03b8f62011-12-02 14:26:25 -0800899 }
900 }
901
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -0800902 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700903}
904
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -0800905JDWP::ObjectId Dbg::CreateString(const std::string& str) {
Ian Rogers50b35e22012-10-04 10:09:15 -0700906 return gRegistry->Add(String::AllocFromModifiedUtf8(Thread::Current(), str.c_str()));
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700907}
908
Elliott Hughes88d63092013-01-09 09:55:54 -0800909JDWP::JdwpError Dbg::CreateObject(JDWP::RefTypeId class_id, JDWP::ObjectId& new_object) {
Elliott Hughes436e3722012-02-17 20:01:47 -0800910 JDWP::JdwpError status;
Elliott Hughes88d63092013-01-09 09:55:54 -0800911 Class* c = DecodeClass(class_id, status);
Elliott Hughes436e3722012-02-17 20:01:47 -0800912 if (c == NULL) {
913 return status;
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -0800914 }
Ian Rogers50b35e22012-10-04 10:09:15 -0700915 new_object = gRegistry->Add(c->AllocObject(Thread::Current()));
Elliott Hughes436e3722012-02-17 20:01:47 -0800916 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700917}
918
Elliott Hughesbf13d362011-12-08 15:51:37 -0800919/*
920 * Used by Eclipse's "Display" view to evaluate "new byte[5]" to get "(byte[]) [0, 0, 0, 0, 0]".
921 */
Elliott Hughes88d63092013-01-09 09:55:54 -0800922JDWP::JdwpError Dbg::CreateArrayObject(JDWP::RefTypeId array_class_id, uint32_t length,
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700923 JDWP::ObjectId& new_array) {
Elliott Hughes436e3722012-02-17 20:01:47 -0800924 JDWP::JdwpError status;
Elliott Hughes88d63092013-01-09 09:55:54 -0800925 Class* c = DecodeClass(array_class_id, status);
Elliott Hughes436e3722012-02-17 20:01:47 -0800926 if (c == NULL) {
927 return status;
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -0800928 }
Ian Rogers50b35e22012-10-04 10:09:15 -0700929 new_array = gRegistry->Add(Array::Alloc(Thread::Current(), c, length));
Elliott Hughes436e3722012-02-17 20:01:47 -0800930 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700931}
932
Elliott Hughes88d63092013-01-09 09:55:54 -0800933bool Dbg::MatchType(JDWP::RefTypeId instance_class_id, JDWP::RefTypeId class_id) {
Elliott Hughes436e3722012-02-17 20:01:47 -0800934 JDWP::JdwpError status;
Elliott Hughes88d63092013-01-09 09:55:54 -0800935 Class* c1 = DecodeClass(instance_class_id, status);
Elliott Hughesa656a0f2012-02-21 18:03:44 -0800936 CHECK(c1 != NULL);
Elliott Hughes88d63092013-01-09 09:55:54 -0800937 Class* c2 = DecodeClass(class_id, status);
Elliott Hughesa656a0f2012-02-21 18:03:44 -0800938 CHECK(c2 != NULL);
939 return c1->IsAssignableFrom(c2);
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700940}
941
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700942static JDWP::FieldId ToFieldId(const Field* f)
Ian Rogersb726dcb2012-09-05 08:57:23 -0700943 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Elliott Hughes03181a82011-11-17 17:22:21 -0800944#ifdef MOVING_GARBAGE_COLLECTOR
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700945 UNIMPLEMENTED(FATAL);
Elliott Hughes03181a82011-11-17 17:22:21 -0800946#else
947 return static_cast<JDWP::FieldId>(reinterpret_cast<uintptr_t>(f));
948#endif
949}
950
Mathieu Chartier66f19252012-09-18 08:57:04 -0700951static JDWP::MethodId ToMethodId(const AbstractMethod* m)
Ian Rogersb726dcb2012-09-05 08:57:23 -0700952 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Elliott Hughes03181a82011-11-17 17:22:21 -0800953#ifdef MOVING_GARBAGE_COLLECTOR
954 UNIMPLEMENTED(FATAL);
955#else
956 return static_cast<JDWP::MethodId>(reinterpret_cast<uintptr_t>(m));
957#endif
958}
959
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700960static Field* FromFieldId(JDWP::FieldId fid)
Ian Rogersb726dcb2012-09-05 08:57:23 -0700961 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Elliott Hughesaed4be92011-12-02 16:16:23 -0800962#ifdef MOVING_GARBAGE_COLLECTOR
963 UNIMPLEMENTED(FATAL);
964#else
965 return reinterpret_cast<Field*>(static_cast<uintptr_t>(fid));
966#endif
967}
968
Mathieu Chartier66f19252012-09-18 08:57:04 -0700969static AbstractMethod* FromMethodId(JDWP::MethodId mid)
Ian Rogersb726dcb2012-09-05 08:57:23 -0700970 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Elliott Hughes03181a82011-11-17 17:22:21 -0800971#ifdef MOVING_GARBAGE_COLLECTOR
972 UNIMPLEMENTED(FATAL);
973#else
Mathieu Chartier66f19252012-09-18 08:57:04 -0700974 return reinterpret_cast<AbstractMethod*>(static_cast<uintptr_t>(mid));
Elliott Hughes03181a82011-11-17 17:22:21 -0800975#endif
976}
977
Mathieu Chartier66f19252012-09-18 08:57:04 -0700978static void SetLocation(JDWP::JdwpLocation& location, AbstractMethod* m, uint32_t dex_pc)
Ian Rogersb726dcb2012-09-05 08:57:23 -0700979 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Elliott Hughes91bf6cd2012-02-14 17:27:48 -0800980 if (m == NULL) {
981 memset(&location, 0, sizeof(location));
982 } else {
983 Class* c = m->GetDeclaringClass();
Elliott Hughes74847412012-06-20 18:10:21 -0700984 location.type_tag = c->IsInterface() ? JDWP::TT_INTERFACE : JDWP::TT_CLASS;
985 location.class_id = gRegistry->Add(c);
986 location.method_id = ToMethodId(m);
Ian Rogers0399dde2012-06-06 17:09:28 -0700987 location.dex_pc = dex_pc;
Elliott Hughes91bf6cd2012-02-14 17:27:48 -0800988 }
Elliott Hughesd07986f2011-12-06 18:27:45 -0800989}
990
Elliott Hughes88d63092013-01-09 09:55:54 -0800991std::string Dbg::GetMethodName(JDWP::RefTypeId, JDWP::MethodId method_id)
Ian Rogersb726dcb2012-09-05 08:57:23 -0700992 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Elliott Hughes88d63092013-01-09 09:55:54 -0800993 AbstractMethod* m = FromMethodId(method_id);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800994 return MethodHelper(m).GetName();
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700995}
996
Elliott Hughesa2e54f62011-11-17 13:01:30 -0800997/*
998 * Augment the access flags for synthetic methods and fields by setting
999 * the (as described by the spec) "0xf0000000 bit". Also, strip out any
1000 * flags not specified by the Java programming language.
1001 */
1002static uint32_t MangleAccessFlags(uint32_t accessFlags) {
1003 accessFlags &= kAccJavaFlagsMask;
1004 if ((accessFlags & kAccSynthetic) != 0) {
1005 accessFlags |= 0xf0000000;
1006 }
1007 return accessFlags;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001008}
1009
Elliott Hughesdbb40792011-11-18 17:05:22 -08001010static const uint16_t kEclipseWorkaroundSlot = 1000;
1011
1012/*
1013 * Eclipse appears to expect that the "this" reference is in slot zero.
1014 * If it's not, the "variables" display will show two copies of "this",
1015 * possibly because it gets "this" from SF.ThisObject and then displays
1016 * all locals with nonzero slot numbers.
1017 *
1018 * So, we remap the item in slot 0 to 1000, and remap "this" to zero. On
1019 * SF.GetValues / SF.SetValues we map them back.
Elliott Hughesc5b734a2011-12-01 17:20:58 -08001020 *
1021 * TODO: jdb uses the value to determine whether a variable is a local or an argument,
1022 * by checking whether it's less than the number of arguments. To make that work, we'd
1023 * have to "mangle" all the arguments to come first, not just the implicit argument 'this'.
Elliott Hughesdbb40792011-11-18 17:05:22 -08001024 */
1025static uint16_t MangleSlot(uint16_t slot, const char* name) {
1026 uint16_t newSlot = slot;
1027 if (strcmp(name, "this") == 0) {
1028 newSlot = 0;
1029 } else if (slot == 0) {
1030 newSlot = kEclipseWorkaroundSlot;
1031 }
1032 return newSlot;
1033}
1034
Mathieu Chartier66f19252012-09-18 08:57:04 -07001035static uint16_t DemangleSlot(uint16_t slot, AbstractMethod* m)
Ian Rogersb726dcb2012-09-05 08:57:23 -07001036 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Elliott Hughesdbb40792011-11-18 17:05:22 -08001037 if (slot == kEclipseWorkaroundSlot) {
Elliott Hughes68fdbd02011-11-29 19:22:47 -08001038 return 0;
Elliott Hughesdbb40792011-11-18 17:05:22 -08001039 } else if (slot == 0) {
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08001040 const DexFile::CodeItem* code_item = MethodHelper(m).GetCodeItem();
Elliott Hughescaf76542012-06-28 16:08:22 -07001041 CHECK(code_item != NULL) << PrettyMethod(m);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001042 return code_item->registers_size_ - code_item->ins_size_;
Elliott Hughesdbb40792011-11-18 17:05:22 -08001043 }
Elliott Hughes68fdbd02011-11-29 19:22:47 -08001044 return slot;
Elliott Hughesdbb40792011-11-18 17:05:22 -08001045}
1046
Elliott Hughes88d63092013-01-09 09:55:54 -08001047JDWP::JdwpError Dbg::OutputDeclaredFields(JDWP::RefTypeId class_id, bool with_generic, JDWP::ExpandBuf* pReply) {
Elliott Hughes436e3722012-02-17 20:01:47 -08001048 JDWP::JdwpError status;
Elliott Hughes88d63092013-01-09 09:55:54 -08001049 Class* c = DecodeClass(class_id, status);
Elliott Hughes436e3722012-02-17 20:01:47 -08001050 if (c == NULL) {
1051 return status;
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -08001052 }
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001053
1054 size_t instance_field_count = c->NumInstanceFields();
1055 size_t static_field_count = c->NumStaticFields();
1056
1057 expandBufAdd4BE(pReply, instance_field_count + static_field_count);
1058
1059 for (size_t i = 0; i < instance_field_count + static_field_count; ++i) {
1060 Field* f = (i < instance_field_count) ? c->GetInstanceField(i) : c->GetStaticField(i - instance_field_count);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001061 FieldHelper fh(f);
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001062 expandBufAddFieldId(pReply, ToFieldId(f));
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001063 expandBufAddUtf8String(pReply, fh.GetName());
1064 expandBufAddUtf8String(pReply, fh.GetTypeDescriptor());
Elliott Hughesc5b734a2011-12-01 17:20:58 -08001065 if (with_generic) {
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001066 static const char genericSignature[1] = "";
1067 expandBufAddUtf8String(pReply, genericSignature);
1068 }
1069 expandBufAdd4BE(pReply, MangleAccessFlags(f->GetAccessFlags()));
1070 }
Elliott Hughes436e3722012-02-17 20:01:47 -08001071 return JDWP::ERR_NONE;
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001072}
1073
Elliott Hughes88d63092013-01-09 09:55:54 -08001074JDWP::JdwpError Dbg::OutputDeclaredMethods(JDWP::RefTypeId class_id, bool with_generic,
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001075 JDWP::ExpandBuf* pReply) {
Elliott Hughes436e3722012-02-17 20:01:47 -08001076 JDWP::JdwpError status;
Elliott Hughes88d63092013-01-09 09:55:54 -08001077 Class* c = DecodeClass(class_id, status);
Elliott Hughes436e3722012-02-17 20:01:47 -08001078 if (c == NULL) {
1079 return status;
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -08001080 }
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001081
1082 size_t direct_method_count = c->NumDirectMethods();
1083 size_t virtual_method_count = c->NumVirtualMethods();
1084
1085 expandBufAdd4BE(pReply, direct_method_count + virtual_method_count);
1086
1087 for (size_t i = 0; i < direct_method_count + virtual_method_count; ++i) {
Mathieu Chartier66f19252012-09-18 08:57:04 -07001088 AbstractMethod* m = (i < direct_method_count) ? c->GetDirectMethod(i) : c->GetVirtualMethod(i - direct_method_count);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001089 MethodHelper mh(m);
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001090 expandBufAddMethodId(pReply, ToMethodId(m));
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001091 expandBufAddUtf8String(pReply, mh.GetName());
Elliott Hughes4740cdf2011-12-07 14:07:12 -08001092 expandBufAddUtf8String(pReply, mh.GetSignature());
Elliott Hughesc5b734a2011-12-01 17:20:58 -08001093 if (with_generic) {
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001094 static const char genericSignature[1] = "";
1095 expandBufAddUtf8String(pReply, genericSignature);
1096 }
1097 expandBufAdd4BE(pReply, MangleAccessFlags(m->GetAccessFlags()));
1098 }
Elliott Hughes436e3722012-02-17 20:01:47 -08001099 return JDWP::ERR_NONE;
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001100}
1101
Elliott Hughes88d63092013-01-09 09:55:54 -08001102JDWP::JdwpError Dbg::OutputDeclaredInterfaces(JDWP::RefTypeId class_id, JDWP::ExpandBuf* pReply) {
Elliott Hughes436e3722012-02-17 20:01:47 -08001103 JDWP::JdwpError status;
Elliott Hughes88d63092013-01-09 09:55:54 -08001104 Class* c = DecodeClass(class_id, status);
Elliott Hughes436e3722012-02-17 20:01:47 -08001105 if (c == NULL) {
1106 return status;
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -08001107 }
Elliott Hughes436e3722012-02-17 20:01:47 -08001108
1109 ClassHelper kh(c);
Ian Rogersd24e2642012-06-06 21:21:43 -07001110 size_t interface_count = kh.NumDirectInterfaces();
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001111 expandBufAdd4BE(pReply, interface_count);
1112 for (size_t i = 0; i < interface_count; ++i) {
Ian Rogersd24e2642012-06-06 21:21:43 -07001113 expandBufAddRefTypeId(pReply, gRegistry->Add(kh.GetDirectInterface(i)));
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001114 }
Elliott Hughes436e3722012-02-17 20:01:47 -08001115 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001116}
1117
Elliott Hughes88d63092013-01-09 09:55:54 -08001118void Dbg::OutputLineTable(JDWP::RefTypeId, JDWP::MethodId method_id, JDWP::ExpandBuf* pReply)
Ian Rogersb726dcb2012-09-05 08:57:23 -07001119 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Elliott Hughes03181a82011-11-17 17:22:21 -08001120 struct DebugCallbackContext {
1121 int numItems;
1122 JDWP::ExpandBuf* pReply;
1123
Elliott Hughes2435a572012-02-17 16:07:41 -08001124 static bool Callback(void* context, uint32_t address, uint32_t line_number) {
Elliott Hughes03181a82011-11-17 17:22:21 -08001125 DebugCallbackContext* pContext = reinterpret_cast<DebugCallbackContext*>(context);
1126 expandBufAdd8BE(pContext->pReply, address);
Elliott Hughes2435a572012-02-17 16:07:41 -08001127 expandBufAdd4BE(pContext->pReply, line_number);
Elliott Hughes03181a82011-11-17 17:22:21 -08001128 pContext->numItems++;
1129 return true;
1130 }
1131 };
Elliott Hughes88d63092013-01-09 09:55:54 -08001132 AbstractMethod* m = FromMethodId(method_id);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001133 MethodHelper mh(m);
Elliott Hughes03181a82011-11-17 17:22:21 -08001134 uint64_t start, end;
1135 if (m->IsNative()) {
1136 start = -1;
1137 end = -1;
1138 } else {
1139 start = 0;
jeffhao14f0db92012-12-14 17:50:42 -08001140 // Return the index of the last instruction
1141 end = mh.GetCodeItem()->insns_size_in_code_units_ - 1;
Elliott Hughes03181a82011-11-17 17:22:21 -08001142 }
1143
1144 expandBufAdd8BE(pReply, start);
1145 expandBufAdd8BE(pReply, end);
1146
1147 // Add numLines later
1148 size_t numLinesOffset = expandBufGetLength(pReply);
1149 expandBufAdd4BE(pReply, 0);
1150
1151 DebugCallbackContext context;
1152 context.numItems = 0;
1153 context.pReply = pReply;
1154
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001155 mh.GetDexFile().DecodeDebugInfo(mh.GetCodeItem(), m->IsStatic(), m->GetDexMethodIndex(),
1156 DebugCallbackContext::Callback, NULL, &context);
Elliott Hughes03181a82011-11-17 17:22:21 -08001157
1158 JDWP::Set4BE(expandBufGetBuffer(pReply) + numLinesOffset, context.numItems);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001159}
1160
Elliott Hughes88d63092013-01-09 09:55:54 -08001161void Dbg::OutputVariableTable(JDWP::RefTypeId, JDWP::MethodId method_id, bool with_generic, JDWP::ExpandBuf* pReply) {
Elliott Hughesdbb40792011-11-18 17:05:22 -08001162 struct DebugCallbackContext {
Elliott Hughesdbb40792011-11-18 17:05:22 -08001163 JDWP::ExpandBuf* pReply;
Elliott Hughesc5b734a2011-12-01 17:20:58 -08001164 size_t variable_count;
1165 bool with_generic;
Elliott Hughesdbb40792011-11-18 17:05:22 -08001166
Elliott Hughesc5b734a2011-12-01 17:20:58 -08001167 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 -08001168 DebugCallbackContext* pContext = reinterpret_cast<DebugCallbackContext*>(context);
1169
Elliott Hughesad3da692012-02-24 16:51:35 -08001170 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 -08001171
Elliott Hughes68fdbd02011-11-29 19:22:47 -08001172 slot = MangleSlot(slot, name);
1173
Elliott Hughesdbb40792011-11-18 17:05:22 -08001174 expandBufAdd8BE(pContext->pReply, startAddress);
1175 expandBufAddUtf8String(pContext->pReply, name);
1176 expandBufAddUtf8String(pContext->pReply, descriptor);
Elliott Hughesc5b734a2011-12-01 17:20:58 -08001177 if (pContext->with_generic) {
Elliott Hughesdbb40792011-11-18 17:05:22 -08001178 expandBufAddUtf8String(pContext->pReply, signature);
1179 }
1180 expandBufAdd4BE(pContext->pReply, endAddress - startAddress);
1181 expandBufAdd4BE(pContext->pReply, slot);
1182
Elliott Hughesc5b734a2011-12-01 17:20:58 -08001183 ++pContext->variable_count;
Elliott Hughesdbb40792011-11-18 17:05:22 -08001184 }
1185 };
Elliott Hughes88d63092013-01-09 09:55:54 -08001186 AbstractMethod* m = FromMethodId(method_id);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001187 MethodHelper mh(m);
1188 const DexFile::CodeItem* code_item = mh.GetCodeItem();
Elliott Hughesdbb40792011-11-18 17:05:22 -08001189
Elliott Hughesc5b734a2011-12-01 17:20:58 -08001190 // arg_count considers doubles and longs to take 2 units.
1191 // variable_count considers everything to take 1 unit.
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001192 std::string shorty(mh.GetShorty());
Ian Rogers2fa6b2e2012-10-17 00:10:17 -07001193 expandBufAdd4BE(pReply, AbstractMethod::NumArgRegisters(shorty));
Elliott Hughesdbb40792011-11-18 17:05:22 -08001194
Elliott Hughesc5b734a2011-12-01 17:20:58 -08001195 // We don't know the total number of variables yet, so leave a blank and update it later.
1196 size_t variable_count_offset = expandBufGetLength(pReply);
Elliott Hughesdbb40792011-11-18 17:05:22 -08001197 expandBufAdd4BE(pReply, 0);
1198
1199 DebugCallbackContext context;
Elliott Hughesdbb40792011-11-18 17:05:22 -08001200 context.pReply = pReply;
Elliott Hughesc5b734a2011-12-01 17:20:58 -08001201 context.variable_count = 0;
1202 context.with_generic = with_generic;
Elliott Hughesdbb40792011-11-18 17:05:22 -08001203
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001204 mh.GetDexFile().DecodeDebugInfo(code_item, m->IsStatic(), m->GetDexMethodIndex(), NULL,
1205 DebugCallbackContext::Callback, &context);
Elliott Hughesdbb40792011-11-18 17:05:22 -08001206
Elliott Hughesc5b734a2011-12-01 17:20:58 -08001207 JDWP::Set4BE(expandBufGetBuffer(pReply) + variable_count_offset, context.variable_count);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001208}
1209
Elliott Hughes88d63092013-01-09 09:55:54 -08001210JDWP::JdwpTag Dbg::GetFieldBasicTag(JDWP::FieldId field_id) {
1211 return BasicTagFromDescriptor(FieldHelper(FromFieldId(field_id)).GetTypeDescriptor());
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001212}
1213
Elliott Hughes88d63092013-01-09 09:55:54 -08001214JDWP::JdwpTag Dbg::GetStaticFieldBasicTag(JDWP::FieldId field_id) {
1215 return BasicTagFromDescriptor(FieldHelper(FromFieldId(field_id)).GetTypeDescriptor());
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001216}
1217
Elliott Hughes88d63092013-01-09 09:55:54 -08001218static JDWP::JdwpError GetFieldValueImpl(JDWP::RefTypeId ref_type_id, JDWP::ObjectId object_id,
1219 JDWP::FieldId field_id, JDWP::ExpandBuf* pReply,
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001220 bool is_static)
Ian Rogersb726dcb2012-09-05 08:57:23 -07001221 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Elliott Hughes0cf74332012-02-23 23:14:00 -08001222 JDWP::JdwpError status;
Elliott Hughes88d63092013-01-09 09:55:54 -08001223 Class* c = DecodeClass(ref_type_id, status);
1224 if (ref_type_id != 0 && c == NULL) {
Elliott Hughes0cf74332012-02-23 23:14:00 -08001225 return status;
1226 }
1227
Elliott Hughes88d63092013-01-09 09:55:54 -08001228 Object* o = gRegistry->Get<Object*>(object_id);
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08001229 if ((!is_static && o == NULL) || o == kInvalidObject) {
1230 return JDWP::ERR_INVALID_OBJECT;
1231 }
Elliott Hughes88d63092013-01-09 09:55:54 -08001232 Field* f = FromFieldId(field_id);
Elliott Hughes0cf74332012-02-23 23:14:00 -08001233
1234 Class* receiver_class = c;
1235 if (receiver_class == NULL && o != NULL) {
1236 receiver_class = o->GetClass();
1237 }
1238 // TODO: should we give up now if receiver_class is NULL?
1239 if (receiver_class != NULL && !f->GetDeclaringClass()->IsAssignableFrom(receiver_class)) {
1240 LOG(INFO) << "ERR_INVALID_FIELDID: " << PrettyField(f) << " " << PrettyClass(receiver_class);
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08001241 return JDWP::ERR_INVALID_FIELDID;
1242 }
Elliott Hughesaed4be92011-12-02 16:16:23 -08001243
Elliott Hughes0cf74332012-02-23 23:14:00 -08001244 // The RI only enforces the static/non-static mismatch in one direction.
1245 // TODO: should we change the tests and check both?
1246 if (is_static) {
1247 if (!f->IsStatic()) {
1248 return JDWP::ERR_INVALID_FIELDID;
1249 }
1250 } else {
1251 if (f->IsStatic()) {
1252 LOG(WARNING) << "Ignoring non-NULL receiver for ObjectReference.SetValues on static field " << PrettyField(f);
Elliott Hughes0cf74332012-02-23 23:14:00 -08001253 }
1254 }
jeffhao0dfbb7e2012-11-28 15:26:03 -08001255 if (f->IsStatic()) {
1256 o = f->GetDeclaringClass();
1257 }
Elliott Hughes0cf74332012-02-23 23:14:00 -08001258
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001259 JDWP::JdwpTag tag = BasicTagFromDescriptor(FieldHelper(f).GetTypeDescriptor());
Elliott Hughesaed4be92011-12-02 16:16:23 -08001260
1261 if (IsPrimitiveTag(tag)) {
1262 expandBufAdd1(pReply, tag);
1263 if (tag == JDWP::JT_BOOLEAN || tag == JDWP::JT_BYTE) {
1264 expandBufAdd1(pReply, f->Get32(o));
1265 } else if (tag == JDWP::JT_CHAR || tag == JDWP::JT_SHORT) {
1266 expandBufAdd2BE(pReply, f->Get32(o));
1267 } else if (tag == JDWP::JT_FLOAT || tag == JDWP::JT_INT) {
1268 expandBufAdd4BE(pReply, f->Get32(o));
1269 } else if (tag == JDWP::JT_DOUBLE || tag == JDWP::JT_LONG) {
1270 expandBufAdd8BE(pReply, f->Get64(o));
1271 } else {
Elliott Hughes3d30d9b2011-12-07 17:35:48 -08001272 LOG(FATAL) << "Unknown tag: " << tag;
Elliott Hughesaed4be92011-12-02 16:16:23 -08001273 }
1274 } else {
1275 Object* value = f->GetObject(o);
1276 expandBufAdd1(pReply, TagFromObject(value));
1277 expandBufAddObjectId(pReply, gRegistry->Add(value));
1278 }
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08001279 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001280}
1281
Elliott Hughes88d63092013-01-09 09:55:54 -08001282JDWP::JdwpError Dbg::GetFieldValue(JDWP::ObjectId object_id, JDWP::FieldId field_id,
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001283 JDWP::ExpandBuf* pReply) {
Elliott Hughes88d63092013-01-09 09:55:54 -08001284 return GetFieldValueImpl(0, object_id, field_id, pReply, false);
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08001285}
1286
Elliott Hughes88d63092013-01-09 09:55:54 -08001287JDWP::JdwpError Dbg::GetStaticFieldValue(JDWP::RefTypeId ref_type_id, JDWP::FieldId field_id, JDWP::ExpandBuf* pReply) {
1288 return GetFieldValueImpl(ref_type_id, 0, field_id, pReply, true);
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08001289}
1290
Elliott Hughes88d63092013-01-09 09:55:54 -08001291static JDWP::JdwpError SetFieldValueImpl(JDWP::ObjectId object_id, JDWP::FieldId field_id,
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001292 uint64_t value, int width, bool is_static)
Ian Rogersb726dcb2012-09-05 08:57:23 -07001293 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Elliott Hughes88d63092013-01-09 09:55:54 -08001294 Object* o = gRegistry->Get<Object*>(object_id);
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08001295 if ((!is_static && o == NULL) || o == kInvalidObject) {
1296 return JDWP::ERR_INVALID_OBJECT;
1297 }
Elliott Hughes88d63092013-01-09 09:55:54 -08001298 Field* f = FromFieldId(field_id);
Elliott Hughes0cf74332012-02-23 23:14:00 -08001299
1300 // The RI only enforces the static/non-static mismatch in one direction.
1301 // TODO: should we change the tests and check both?
1302 if (is_static) {
1303 if (!f->IsStatic()) {
1304 return JDWP::ERR_INVALID_FIELDID;
1305 }
1306 } else {
1307 if (f->IsStatic()) {
1308 LOG(WARNING) << "Ignoring non-NULL receiver for ObjectReference.SetValues on static field " << PrettyField(f);
Elliott Hughes0cf74332012-02-23 23:14:00 -08001309 }
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08001310 }
jeffhao0dfbb7e2012-11-28 15:26:03 -08001311 if (f->IsStatic()) {
1312 o = f->GetDeclaringClass();
1313 }
Elliott Hughesaed4be92011-12-02 16:16:23 -08001314
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001315 JDWP::JdwpTag tag = BasicTagFromDescriptor(FieldHelper(f).GetTypeDescriptor());
Elliott Hughesaed4be92011-12-02 16:16:23 -08001316
1317 if (IsPrimitiveTag(tag)) {
1318 if (tag == JDWP::JT_DOUBLE || tag == JDWP::JT_LONG) {
Elliott Hughes1bac54f2012-03-16 12:48:31 -07001319 CHECK_EQ(width, 8);
Elliott Hughesaed4be92011-12-02 16:16:23 -08001320 f->Set64(o, value);
1321 } else {
Elliott Hughes1bac54f2012-03-16 12:48:31 -07001322 CHECK_LE(width, 4);
Elliott Hughesaed4be92011-12-02 16:16:23 -08001323 f->Set32(o, value);
1324 }
1325 } else {
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -08001326 Object* v = gRegistry->Get<Object*>(value);
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08001327 if (v == kInvalidObject) {
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -08001328 return JDWP::ERR_INVALID_OBJECT;
1329 }
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08001330 if (v != NULL) {
1331 Class* field_type = FieldHelper(f).GetType();
1332 if (!field_type->IsAssignableFrom(v->GetClass())) {
1333 return JDWP::ERR_INVALID_OBJECT;
1334 }
1335 }
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -08001336 f->SetObject(o, v);
Elliott Hughesaed4be92011-12-02 16:16:23 -08001337 }
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -08001338
1339 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001340}
1341
Elliott Hughes88d63092013-01-09 09:55:54 -08001342JDWP::JdwpError Dbg::SetFieldValue(JDWP::ObjectId object_id, JDWP::FieldId field_id, uint64_t value,
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001343 int width) {
Elliott Hughes88d63092013-01-09 09:55:54 -08001344 return SetFieldValueImpl(object_id, field_id, value, width, false);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001345}
1346
Elliott Hughes88d63092013-01-09 09:55:54 -08001347JDWP::JdwpError Dbg::SetStaticFieldValue(JDWP::FieldId field_id, uint64_t value, int width) {
1348 return SetFieldValueImpl(0, field_id, value, width, true);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001349}
1350
Elliott Hughes88d63092013-01-09 09:55:54 -08001351std::string Dbg::StringToUtf8(JDWP::ObjectId string_id) {
1352 String* s = gRegistry->Get<String*>(string_id);
Elliott Hughes68fdbd02011-11-29 19:22:47 -08001353 return s->ToModifiedUtf8();
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001354}
1355
Elliott Hughes221229c2013-01-08 18:17:50 -08001356JDWP::JdwpError Dbg::GetThreadName(JDWP::ObjectId thread_id, std::string& name) {
jeffhaoa77f0f62012-12-05 17:19:31 -08001357 ScopedObjectAccessUnchecked soa(Thread::Current());
1358 MutexLock mu(soa.Self(), *Locks::thread_list_lock_);
Elliott Hughes221229c2013-01-08 18:17:50 -08001359 Thread* thread;
1360 JDWP::JdwpError error = DecodeThread(soa, thread_id, thread);
1361 if (error != JDWP::ERR_NONE && error != JDWP::ERR_THREAD_NOT_ALIVE) {
1362 return error;
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001363 }
Elliott Hughes221229c2013-01-08 18:17:50 -08001364
1365 // We still need to report the zombie threads' names, so we can't just call Thread::GetThreadName.
1366 Object* thread_object = gRegistry->Get<Object*>(thread_id);
1367 Field* java_lang_Thread_name_field = soa.DecodeField(WellKnownClasses::java_lang_Thread_name);
1368 String* s = reinterpret_cast<String*>(java_lang_Thread_name_field->GetObject(thread_object));
1369 if (s != NULL) {
1370 name = s->ToModifiedUtf8();
1371 }
1372 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001373}
1374
Elliott Hughes221229c2013-01-08 18:17:50 -08001375JDWP::JdwpError Dbg::GetThreadGroup(JDWP::ObjectId thread_id, JDWP::ExpandBuf* pReply) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001376 ScopedObjectAccess soa(Thread::Current());
Elliott Hughes221229c2013-01-08 18:17:50 -08001377 Object* thread_object = gRegistry->Get<Object*>(thread_id);
1378 if (thread_object == kInvalidObject) {
Elliott Hughes2435a572012-02-17 16:07:41 -08001379 return JDWP::ERR_INVALID_OBJECT;
1380 }
1381
1382 // Okay, so it's an object, but is it actually a thread?
Ian Rogers50b35e22012-10-04 10:09:15 -07001383 MutexLock mu(soa.Self(), *Locks::thread_list_lock_);
Elliott Hughes221229c2013-01-08 18:17:50 -08001384 Thread* thread;
1385 JDWP::JdwpError error = DecodeThread(soa, thread_id, thread);
1386 if (error == JDWP::ERR_THREAD_NOT_ALIVE) {
1387 // Zombie threads are in the null group.
1388 expandBufAddObjectId(pReply, JDWP::ObjectId(0));
1389 return JDWP::ERR_NONE;
1390 }
1391 if (error != JDWP::ERR_NONE) {
1392 return error;
Elliott Hughes2435a572012-02-17 16:07:41 -08001393 }
Elliott Hughes499c5132011-11-17 14:55:11 -08001394
1395 Class* c = Runtime::Current()->GetClassLinker()->FindSystemClass("Ljava/lang/Thread;");
1396 CHECK(c != NULL);
1397 Field* f = c->FindInstanceField("group", "Ljava/lang/ThreadGroup;");
1398 CHECK(f != NULL);
Elliott Hughes221229c2013-01-08 18:17:50 -08001399 Object* group = f->GetObject(thread_object);
Elliott Hughes499c5132011-11-17 14:55:11 -08001400 CHECK(group != NULL);
Elliott Hughes2435a572012-02-17 16:07:41 -08001401 JDWP::ObjectId thread_group_id = gRegistry->Add(group);
1402
1403 expandBufAddObjectId(pReply, thread_group_id);
1404 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001405}
1406
Elliott Hughes88d63092013-01-09 09:55:54 -08001407std::string Dbg::GetThreadGroupName(JDWP::ObjectId thread_group_id) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001408 ScopedObjectAccess soa(Thread::Current());
Elliott Hughes88d63092013-01-09 09:55:54 -08001409 Object* thread_group = gRegistry->Get<Object*>(thread_group_id);
Elliott Hughes499c5132011-11-17 14:55:11 -08001410 CHECK(thread_group != NULL);
1411
1412 Class* c = Runtime::Current()->GetClassLinker()->FindSystemClass("Ljava/lang/ThreadGroup;");
1413 CHECK(c != NULL);
1414 Field* f = c->FindInstanceField("name", "Ljava/lang/String;");
1415 CHECK(f != NULL);
1416 String* s = reinterpret_cast<String*>(f->GetObject(thread_group));
1417 return s->ToModifiedUtf8();
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001418}
1419
Elliott Hughes88d63092013-01-09 09:55:54 -08001420JDWP::ObjectId Dbg::GetThreadGroupParent(JDWP::ObjectId thread_group_id) {
1421 Object* thread_group = gRegistry->Get<Object*>(thread_group_id);
Elliott Hughes4e235312011-12-02 11:34:15 -08001422 CHECK(thread_group != NULL);
1423
1424 Class* c = Runtime::Current()->GetClassLinker()->FindSystemClass("Ljava/lang/ThreadGroup;");
1425 CHECK(c != NULL);
1426 Field* f = c->FindInstanceField("parent", "Ljava/lang/ThreadGroup;");
1427 CHECK(f != NULL);
1428 Object* parent = f->GetObject(thread_group);
1429 return gRegistry->Add(parent);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001430}
1431
1432JDWP::ObjectId Dbg::GetSystemThreadGroupId() {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001433 ScopedObjectAccessUnchecked soa(Thread::Current());
jeffhao0dfbb7e2012-11-28 15:26:03 -08001434 Field* f = soa.DecodeField(WellKnownClasses::java_lang_ThreadGroup_systemThreadGroup);
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
1439JDWP::ObjectId Dbg::GetMainThreadGroupId() {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001440 ScopedObjectAccess soa(Thread::Current());
jeffhao0dfbb7e2012-11-28 15:26:03 -08001441 Field* f = soa.DecodeField(WellKnownClasses::java_lang_ThreadGroup_mainThreadGroup);
1442 Object* group = f->GetObject(f->GetDeclaringClass());
Ian Rogers365c1022012-06-22 15:05:28 -07001443 return gRegistry->Add(group);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001444}
1445
Elliott Hughes221229c2013-01-08 18:17:50 -08001446JDWP::JdwpError Dbg::GetThreadStatus(JDWP::ObjectId thread_id, JDWP::JdwpThreadStatus* pThreadStatus, JDWP::JdwpSuspendStatus* pSuspendStatus) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001447 ScopedObjectAccess soa(Thread::Current());
Elliott Hughes499c5132011-11-17 14:55:11 -08001448
Elliott Hughes9e0c1752013-01-09 14:02:58 -08001449 *pSuspendStatus = JDWP::SUSPEND_STATUS_NOT_SUSPENDED;
1450
Ian Rogers50b35e22012-10-04 10:09:15 -07001451 MutexLock mu(soa.Self(), *Locks::thread_list_lock_);
Elliott Hughes221229c2013-01-08 18:17:50 -08001452 Thread* thread;
1453 JDWP::JdwpError error = DecodeThread(soa, thread_id, thread);
1454 if (error != JDWP::ERR_NONE) {
1455 if (error == JDWP::ERR_THREAD_NOT_ALIVE) {
1456 *pThreadStatus = JDWP::TS_ZOMBIE;
Elliott Hughes221229c2013-01-08 18:17:50 -08001457 return JDWP::ERR_NONE;
1458 }
1459 return error;
Elliott Hughes499c5132011-11-17 14:55:11 -08001460 }
1461
Elliott Hughes9e0c1752013-01-09 14:02:58 -08001462 if (IsSuspendedForDebugger(soa, thread)) {
1463 *pSuspendStatus = JDWP::SUSPEND_STATUS_SUSPENDED;
Elliott Hughes499c5132011-11-17 14:55:11 -08001464 }
1465
Elliott Hughes9e0c1752013-01-09 14:02:58 -08001466 switch (thread->GetState()) {
1467 case kBlocked: *pThreadStatus = JDWP::TS_MONITOR; break;
1468 case kNative: *pThreadStatus = JDWP::TS_RUNNING; break;
1469 case kRunnable: *pThreadStatus = JDWP::TS_RUNNING; break;
1470 case kSleeping: *pThreadStatus = JDWP::TS_SLEEPING; break;
1471 case kStarting: *pThreadStatus = JDWP::TS_ZOMBIE; break;
1472 case kSuspended: *pThreadStatus = JDWP::TS_RUNNING; break;
1473 case kTerminated: *pThreadStatus = JDWP::TS_ZOMBIE; break;
1474 case kTimedWaiting: *pThreadStatus = JDWP::TS_WAIT; break;
1475 case kWaitingForDebuggerSend: *pThreadStatus = JDWP::TS_WAIT; break;
1476 case kWaitingForDebuggerSuspension: *pThreadStatus = JDWP::TS_WAIT; break;
1477 case kWaitingForDebuggerToAttach: *pThreadStatus = JDWP::TS_WAIT; break;
1478 case kWaitingForGcToComplete: *pThreadStatus = JDWP::TS_WAIT; break;
1479 case kWaitingForJniOnLoad: *pThreadStatus = JDWP::TS_WAIT; break;
1480 case kWaitingForSignalCatcherOutput: *pThreadStatus = JDWP::TS_WAIT; break;
1481 case kWaitingInMainDebuggerLoop: *pThreadStatus = JDWP::TS_WAIT; break;
1482 case kWaitingInMainSignalCatcherLoop: *pThreadStatus = JDWP::TS_WAIT; break;
1483 case kWaitingPerformingGc: *pThreadStatus = JDWP::TS_WAIT; break;
1484 case kWaiting: *pThreadStatus = JDWP::TS_WAIT; break;
1485 // Don't add a 'default' here so the compiler can spot incompatible enum changes.
1486 }
Elliott Hughes221229c2013-01-08 18:17:50 -08001487 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001488}
1489
Elliott Hughes221229c2013-01-08 18:17:50 -08001490JDWP::JdwpError Dbg::GetThreadDebugSuspendCount(JDWP::ObjectId thread_id, JDWP::ExpandBuf* pReply) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001491 ScopedObjectAccess soa(Thread::Current());
Ian Rogers50b35e22012-10-04 10:09:15 -07001492 MutexLock mu(soa.Self(), *Locks::thread_list_lock_);
Elliott Hughes221229c2013-01-08 18:17:50 -08001493 Thread* thread;
1494 JDWP::JdwpError error = DecodeThread(soa, thread_id, thread);
1495 if (error != JDWP::ERR_NONE) {
1496 return error;
Elliott Hughes2435a572012-02-17 16:07:41 -08001497 }
Ian Rogers50b35e22012-10-04 10:09:15 -07001498 MutexLock mu2(soa.Self(), *Locks::thread_suspend_count_lock_);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001499 expandBufAdd4BE(pReply, thread->GetDebugSuspendCount());
Elliott Hughes2435a572012-02-17 16:07:41 -08001500 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001501}
1502
Elliott Hughescaf76542012-06-28 16:08:22 -07001503void Dbg::GetThreads(JDWP::ObjectId thread_group_id, std::vector<JDWP::ObjectId>& thread_ids) {
Ian Rogers365c1022012-06-22 15:05:28 -07001504 class ThreadListVisitor {
1505 public:
jeffhao0dfbb7e2012-11-28 15:26:03 -08001506 ThreadListVisitor(const ScopedObjectAccessUnchecked& soa, Object* desired_thread_group,
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001507 std::vector<JDWP::ObjectId>& thread_ids)
Ian Rogersb726dcb2012-09-05 08:57:23 -07001508 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_)
jeffhao0dfbb7e2012-11-28 15:26:03 -08001509 : soa_(soa), desired_thread_group_(desired_thread_group), thread_ids_(thread_ids) {}
Ian Rogers365c1022012-06-22 15:05:28 -07001510
Elliott Hughesa2155262011-11-16 16:26:58 -08001511 static void Visit(Thread* t, void* arg) {
1512 reinterpret_cast<ThreadListVisitor*>(arg)->Visit(t);
1513 }
1514
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001515 // TODO: Enable annotalysis. We know lock is held in constructor, but abstraction confuses
1516 // annotalysis.
1517 void Visit(Thread* t) NO_THREAD_SAFETY_ANALYSIS {
Elliott Hughesa2155262011-11-16 16:26:58 -08001518 if (t == Dbg::GetDebugThread()) {
1519 // Skip the JDWP thread. Some debuggers get bent out of shape when they can't suspend and
1520 // query all threads, so it's easier if we just don't tell them about this thread.
1521 return;
1522 }
Ian Rogerscfaa4552012-11-26 21:00:08 -08001523 Object* peer = t->GetPeer();
jeffhao0dfbb7e2012-11-28 15:26:03 -08001524 if (IsInDesiredThreadGroup(peer)) {
Ian Rogers120f1c72012-09-28 17:17:10 -07001525 thread_ids_.push_back(gRegistry->Add(peer));
Elliott Hughesa2155262011-11-16 16:26:58 -08001526 }
1527 }
1528
Ian Rogers365c1022012-06-22 15:05:28 -07001529 private:
jeffhao0dfbb7e2012-11-28 15:26:03 -08001530 bool IsInDesiredThreadGroup(Object* peer)
1531 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
jeffhao0dfbb7e2012-11-28 15:26:03 -08001532 // peer might be NULL if the thread is still starting up.
1533 if (peer == NULL) {
1534 // We can't tell the debugger about this thread yet.
1535 // TODO: if we identified threads to the debugger by their Thread*
1536 // rather than their peer's Object*, we could fix this.
1537 // Doing so might help us report ZOMBIE threads too.
1538 return false;
1539 }
jeffhaoc1e04902012-12-13 12:41:10 -08001540 // Do we want threads from all thread groups?
1541 if (desired_thread_group_ == NULL) {
1542 return true;
1543 }
jeffhao0dfbb7e2012-11-28 15:26:03 -08001544 Object* group = soa_.DecodeField(WellKnownClasses::java_lang_Thread_group)->GetObject(peer);
1545 return (group == desired_thread_group_);
1546 }
1547
Mathieu Chartierdbe6f462012-09-25 16:54:50 -07001548 const ScopedObjectAccessUnchecked& soa_;
jeffhao0dfbb7e2012-11-28 15:26:03 -08001549 Object* const desired_thread_group_;
Elliott Hughescaf76542012-06-28 16:08:22 -07001550 std::vector<JDWP::ObjectId>& thread_ids_;
Elliott Hughesa2155262011-11-16 16:26:58 -08001551 };
1552
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001553 ScopedObjectAccessUnchecked soa(Thread::Current());
Elliott Hughescaf76542012-06-28 16:08:22 -07001554 Object* thread_group = gRegistry->Get<Object*>(thread_group_id);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001555 ThreadListVisitor tlv(soa, thread_group, thread_ids);
Ian Rogers50b35e22012-10-04 10:09:15 -07001556 MutexLock mu(soa.Self(), *Locks::thread_list_lock_);
Elliott Hughesf8349362012-06-18 15:00:06 -07001557 Runtime::Current()->GetThreadList()->ForEach(ThreadListVisitor::Visit, &tlv);
Elliott Hughescaf76542012-06-28 16:08:22 -07001558}
Elliott Hughesa2155262011-11-16 16:26:58 -08001559
Elliott Hughescaf76542012-06-28 16:08:22 -07001560void Dbg::GetChildThreadGroups(JDWP::ObjectId thread_group_id, std::vector<JDWP::ObjectId>& child_thread_group_ids) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001561 ScopedObjectAccess soa(Thread::Current());
Elliott Hughescaf76542012-06-28 16:08:22 -07001562 Object* thread_group = gRegistry->Get<Object*>(thread_group_id);
1563
1564 // Get the ArrayList<ThreadGroup> "groups" out of this thread group...
1565 Field* groups_field = thread_group->GetClass()->FindInstanceField("groups", "Ljava/util/List;");
1566 Object* groups_array_list = groups_field->GetObject(thread_group);
1567
1568 // Get the array and size out of the ArrayList<ThreadGroup>...
1569 Field* array_field = groups_array_list->GetClass()->FindInstanceField("array", "[Ljava/lang/Object;");
1570 Field* size_field = groups_array_list->GetClass()->FindInstanceField("size", "I");
1571 ObjectArray<Object>* groups_array = array_field->GetObject(groups_array_list)->AsObjectArray<Object>();
1572 const int32_t size = size_field->GetInt(groups_array_list);
1573
1574 // Copy the first 'size' elements out of the array into the result.
1575 for (int32_t i = 0; i < size; ++i) {
1576 child_thread_group_ids.push_back(gRegistry->Add(groups_array->Get(i)));
Elliott Hughesa2155262011-11-16 16:26:58 -08001577 }
1578}
1579
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001580static int GetStackDepth(Thread* thread)
Ian Rogersb726dcb2012-09-05 08:57:23 -07001581 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Ian Rogers0399dde2012-06-06 17:09:28 -07001582 struct CountStackDepthVisitor : public StackVisitor {
1583 CountStackDepthVisitor(const ManagedStack* stack,
Ian Rogers306057f2012-11-26 12:45:53 -08001584 const std::deque<InstrumentationStackFrame>* instrumentation_stack)
jeffhao725a9572012-11-13 18:20:12 -08001585 : StackVisitor(stack, instrumentation_stack, NULL), depth(0) {}
Ian Rogers0399dde2012-06-06 17:09:28 -07001586
1587 bool VisitFrame() {
1588 if (!GetMethod()->IsRuntimeMethod()) {
Elliott Hughesf8a2df72011-12-01 12:19:54 -08001589 ++depth;
1590 }
Elliott Hughes530fa002012-03-12 11:44:49 -07001591 return true;
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001592 }
1593 size_t depth;
1594 };
Elliott Hughes08fc03a2012-06-26 17:34:00 -07001595
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001596 if (kIsDebugBuild) {
Ian Rogers50b35e22012-10-04 10:09:15 -07001597 MutexLock mu(Thread::Current(), *Locks::thread_suspend_count_lock_);
jeffhao09bfc6a2012-12-11 18:11:43 -08001598 CHECK(thread == Thread::Current() || thread->IsSuspended());
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001599 }
jeffhao725a9572012-11-13 18:20:12 -08001600 CountStackDepthVisitor visitor(thread->GetManagedStack(), thread->GetInstrumentationStack());
Ian Rogers0399dde2012-06-06 17:09:28 -07001601 visitor.WalkStack();
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001602 return visitor.depth;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001603}
1604
Elliott Hughes221229c2013-01-08 18:17:50 -08001605JDWP::JdwpError Dbg::GetThreadFrameCount(JDWP::ObjectId thread_id, size_t& result) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001606 ScopedObjectAccess soa(Thread::Current());
jeffhaoa77f0f62012-12-05 17:19:31 -08001607 MutexLock mu(soa.Self(), *Locks::thread_list_lock_);
Elliott Hughes221229c2013-01-08 18:17:50 -08001608 Thread* thread;
1609 JDWP::JdwpError error = DecodeThread(soa, thread_id, thread);
1610 if (error != JDWP::ERR_NONE) {
1611 return error;
1612 }
Elliott Hughesf15f4a02013-01-09 10:09:38 -08001613 if (!IsSuspendedForDebugger(soa, thread)) {
1614 return JDWP::ERR_THREAD_NOT_SUSPENDED;
1615 }
Elliott Hughes221229c2013-01-08 18:17:50 -08001616 result = GetStackDepth(thread);
1617 return JDWP::ERR_NONE;
Elliott Hughes86964332012-02-15 19:37:42 -08001618}
1619
Ian Rogers306057f2012-11-26 12:45:53 -08001620JDWP::JdwpError Dbg::GetThreadFrames(JDWP::ObjectId thread_id, size_t start_frame,
1621 size_t frame_count, JDWP::ExpandBuf* buf) {
Elliott Hughes6e9d22c2012-06-22 15:02:37 -07001622 class GetFrameVisitor : public StackVisitor {
1623 public:
Ian Rogers306057f2012-11-26 12:45:53 -08001624 GetFrameVisitor(const ManagedStack* stack,
1625 const std::deque<InstrumentationStackFrame>* instrumentation_stack,
Elliott Hughes6e9d22c2012-06-22 15:02:37 -07001626 size_t start_frame, size_t frame_count, JDWP::ExpandBuf* buf)
Ian Rogersb726dcb2012-09-05 08:57:23 -07001627 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_)
jeffhao725a9572012-11-13 18:20:12 -08001628 : StackVisitor(stack, instrumentation_stack, NULL), depth_(0),
Elliott Hughes6e9d22c2012-06-22 15:02:37 -07001629 start_frame_(start_frame), frame_count_(frame_count), buf_(buf) {
1630 expandBufAdd4BE(buf_, frame_count_);
Elliott Hughes03181a82011-11-17 17:22:21 -08001631 }
Ian Rogers0399dde2012-06-06 17:09:28 -07001632
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001633 // TODO: Enable annotalysis. We know lock is held in constructor, but abstraction confuses
1634 // annotalysis.
1635 virtual bool VisitFrame() NO_THREAD_SAFETY_ANALYSIS {
Ian Rogers0399dde2012-06-06 17:09:28 -07001636 if (GetMethod()->IsRuntimeMethod()) {
Elliott Hughes530fa002012-03-12 11:44:49 -07001637 return true; // The debugger can't do anything useful with a frame that has no Method*.
Elliott Hughes03181a82011-11-17 17:22:21 -08001638 }
Elliott Hughes6e9d22c2012-06-22 15:02:37 -07001639 if (depth_ >= start_frame_ + frame_count_) {
Elliott Hughes530fa002012-03-12 11:44:49 -07001640 return false;
Elliott Hughes03181a82011-11-17 17:22:21 -08001641 }
Elliott Hughes6e9d22c2012-06-22 15:02:37 -07001642 if (depth_ >= start_frame_) {
1643 JDWP::FrameId frame_id(GetFrameId());
1644 JDWP::JdwpLocation location;
1645 SetLocation(location, GetMethod(), GetDexPc());
Elliott Hughes7baf96f2012-06-22 16:33:50 -07001646 VLOG(jdwp) << StringPrintf(" Frame %3zd: id=%3lld ", depth_, frame_id) << location;
Elliott Hughes6e9d22c2012-06-22 15:02:37 -07001647 expandBufAdd8BE(buf_, frame_id);
1648 expandBufAddLocation(buf_, location);
1649 }
1650 ++depth_;
Elliott Hughes530fa002012-03-12 11:44:49 -07001651 return true;
Elliott Hughes03181a82011-11-17 17:22:21 -08001652 }
Elliott Hughes6e9d22c2012-06-22 15:02:37 -07001653
1654 private:
1655 size_t depth_;
1656 const size_t start_frame_;
1657 const size_t frame_count_;
1658 JDWP::ExpandBuf* buf_;
Elliott Hughes03181a82011-11-17 17:22:21 -08001659 };
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001660
1661 ScopedObjectAccessUnchecked soa(Thread::Current());
jeffhaoa77f0f62012-12-05 17:19:31 -08001662 MutexLock mu(soa.Self(), *Locks::thread_list_lock_);
Elliott Hughes221229c2013-01-08 18:17:50 -08001663 Thread* thread;
1664 JDWP::JdwpError error = DecodeThread(soa, thread_id, thread);
1665 if (error != JDWP::ERR_NONE) {
1666 return error;
1667 }
Elliott Hughesf15f4a02013-01-09 10:09:38 -08001668 if (!IsSuspendedForDebugger(soa, thread)) {
1669 return JDWP::ERR_THREAD_NOT_SUSPENDED;
1670 }
Ian Rogers306057f2012-11-26 12:45:53 -08001671 GetFrameVisitor visitor(thread->GetManagedStack(), thread->GetInstrumentationStack(),
1672 start_frame, frame_count, buf);
Ian Rogers0399dde2012-06-06 17:09:28 -07001673 visitor.WalkStack();
Elliott Hughes6e9d22c2012-06-22 15:02:37 -07001674 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001675}
1676
1677JDWP::ObjectId Dbg::GetThreadSelfId() {
Mathieu Chartierdbe6f462012-09-25 16:54:50 -07001678 ScopedObjectAccessUnchecked soa(Thread::Current());
Ian Rogerscfaa4552012-11-26 21:00:08 -08001679 return gRegistry->Add(soa.Self()->GetPeer());
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001680}
1681
Elliott Hughes475fc232011-10-25 15:00:35 -07001682void Dbg::SuspendVM() {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001683 Runtime::Current()->GetThreadList()->SuspendAllForDebugger();
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001684}
1685
1686void Dbg::ResumeVM() {
Elliott Hughesc61a2672012-06-21 14:52:29 -07001687 Runtime::Current()->GetThreadList()->UndoDebuggerSuspensions();
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001688}
1689
Elliott Hughes221229c2013-01-08 18:17:50 -08001690JDWP::JdwpError Dbg::SuspendThread(JDWP::ObjectId thread_id, bool request_suspension) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001691
1692 bool timeout;
1693 ScopedLocalRef<jobject> peer(Thread::Current()->GetJniEnv(), NULL);
1694 {
1695 ScopedObjectAccess soa(Thread::Current());
Elliott Hughes221229c2013-01-08 18:17:50 -08001696 peer.reset(soa.AddLocalReference<jobject>(gRegistry->Get<Object*>(thread_id)));
Elliott Hughes4e235312011-12-02 11:34:15 -08001697 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001698 if (peer.get() == NULL) {
Elliott Hughes221229c2013-01-08 18:17:50 -08001699 LOG(WARNING) << "No such thread for suspend: " << thread_id;
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001700 return JDWP::ERR_THREAD_NOT_ALIVE;
1701 }
1702 // Suspend thread to build stack trace.
1703 Thread* thread = Thread::SuspendForDebugger(peer.get(), request_suspension, &timeout);
1704 if (thread != NULL) {
1705 return JDWP::ERR_NONE;
1706 } else if (timeout) {
1707 return JDWP::ERR_INTERNAL;
1708 } else {
1709 return JDWP::ERR_THREAD_NOT_ALIVE;
1710 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001711}
1712
Elliott Hughes221229c2013-01-08 18:17:50 -08001713void Dbg::ResumeThread(JDWP::ObjectId thread_id) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001714 ScopedObjectAccessUnchecked soa(Thread::Current());
Elliott Hughes221229c2013-01-08 18:17:50 -08001715 Object* peer = gRegistry->Get<Object*>(thread_id);
jeffhaoa77f0f62012-12-05 17:19:31 -08001716 Thread* thread;
1717 {
1718 MutexLock mu(soa.Self(), *Locks::thread_list_lock_);
1719 thread = Thread::FromManagedThread(soa, peer);
1720 }
Elliott Hughes4e235312011-12-02 11:34:15 -08001721 if (thread == NULL) {
1722 LOG(WARNING) << "No such thread for resume: " << peer;
1723 return;
1724 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001725 bool needs_resume;
1726 {
Ian Rogers50b35e22012-10-04 10:09:15 -07001727 MutexLock mu2(soa.Self(), *Locks::thread_suspend_count_lock_);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001728 needs_resume = thread->GetSuspendCount() > 0;
1729 }
1730 if (needs_resume) {
Elliott Hughes546b9862012-06-20 16:06:13 -07001731 Runtime::Current()->GetThreadList()->Resume(thread, true);
1732 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001733}
1734
1735void Dbg::SuspendSelf() {
Elliott Hughes475fc232011-10-25 15:00:35 -07001736 Runtime::Current()->GetThreadList()->SuspendSelfForDebugger();
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001737}
1738
Ian Rogers0399dde2012-06-06 17:09:28 -07001739struct GetThisVisitor : public StackVisitor {
Ian Rogers306057f2012-11-26 12:45:53 -08001740 GetThisVisitor(const ManagedStack* stack,
1741 const std::deque<InstrumentationStackFrame>* instrumentation_stack,
Elliott Hughes88d63092013-01-09 09:55:54 -08001742 Context* context, JDWP::FrameId frame_id)
Ian Rogersb726dcb2012-09-05 08:57:23 -07001743 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_)
Elliott Hughes88d63092013-01-09 09:55:54 -08001744 : StackVisitor(stack, instrumentation_stack, context), this_object(NULL), frame_id(frame_id) {}
Ian Rogers0399dde2012-06-06 17:09:28 -07001745
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001746 // TODO: Enable annotalysis. We know lock is held in constructor, but abstraction confuses
1747 // annotalysis.
1748 virtual bool VisitFrame() NO_THREAD_SAFETY_ANALYSIS {
Elliott Hughes6e9d22c2012-06-22 15:02:37 -07001749 if (frame_id != GetFrameId()) {
Ian Rogers0399dde2012-06-06 17:09:28 -07001750 return true; // continue
1751 }
Mathieu Chartier66f19252012-09-18 08:57:04 -07001752 AbstractMethod* m = GetMethod();
Ian Rogers0399dde2012-06-06 17:09:28 -07001753 if (m->IsNative() || m->IsStatic()) {
Elliott Hughes6e9d22c2012-06-22 15:02:37 -07001754 this_object = NULL;
Ian Rogers0399dde2012-06-06 17:09:28 -07001755 } else {
1756 uint16_t reg = DemangleSlot(0, m);
Ian Rogers2bcb4a42012-11-08 10:39:18 -08001757 this_object = reinterpret_cast<Object*>(GetVReg(m, reg, kReferenceVReg));
Ian Rogers0399dde2012-06-06 17:09:28 -07001758 }
1759 return false;
Elliott Hughes86b00102011-12-05 17:54:26 -08001760 }
Ian Rogers0399dde2012-06-06 17:09:28 -07001761
Elliott Hughes6e9d22c2012-06-22 15:02:37 -07001762 Object* this_object;
1763 JDWP::FrameId frame_id;
Ian Rogers0399dde2012-06-06 17:09:28 -07001764};
1765
Mathieu Chartier66f19252012-09-18 08:57:04 -07001766static Object* GetThis(Thread* self, AbstractMethod* m, size_t frame_id)
Ian Rogersb726dcb2012-09-05 08:57:23 -07001767 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Elliott Hughescaf76542012-06-28 16:08:22 -07001768 // TODO: should we return the 'this' we passed through to non-static native methods?
Ian Rogers0399dde2012-06-06 17:09:28 -07001769 if (m->IsNative() || m->IsStatic()) {
1770 return NULL;
1771 }
Elliott Hughescaf76542012-06-28 16:08:22 -07001772
Ian Rogers0399dde2012-06-06 17:09:28 -07001773 UniquePtr<Context> context(Context::Create());
jeffhao725a9572012-11-13 18:20:12 -08001774 GetThisVisitor visitor(self->GetManagedStack(), self->GetInstrumentationStack(), context.get(), frame_id);
Elliott Hughescaf76542012-06-28 16:08:22 -07001775 visitor.WalkStack();
1776 return visitor.this_object;
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08001777}
1778
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001779JDWP::JdwpError Dbg::GetThisObject(JDWP::ObjectId thread_id, JDWP::FrameId frame_id,
1780 JDWP::ObjectId* result) {
1781 ScopedObjectAccessUnchecked soa(Thread::Current());
1782 Thread* thread;
1783 {
Ian Rogers50b35e22012-10-04 10:09:15 -07001784 MutexLock mu(soa.Self(), *Locks::thread_list_lock_);
Elliott Hughes221229c2013-01-08 18:17:50 -08001785 JDWP::JdwpError error = DecodeThread(soa, thread_id, thread);
1786 if (error != JDWP::ERR_NONE) {
1787 return error;
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001788 }
Elliott Hughes9e0c1752013-01-09 14:02:58 -08001789 if (!IsSuspendedForDebugger(soa, thread)) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001790 return JDWP::ERR_THREAD_NOT_SUSPENDED;
1791 }
Elliott Hughes6e9d22c2012-06-22 15:02:37 -07001792 }
Elliott Hughescaf76542012-06-28 16:08:22 -07001793 UniquePtr<Context> context(Context::Create());
jeffhao725a9572012-11-13 18:20:12 -08001794 GetThisVisitor visitor(thread->GetManagedStack(), thread->GetInstrumentationStack(), context.get(), frame_id);
Ian Rogers0399dde2012-06-06 17:09:28 -07001795 visitor.WalkStack();
Elliott Hughes6e9d22c2012-06-22 15:02:37 -07001796 *result = gRegistry->Add(visitor.this_object);
1797 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001798}
1799
Elliott Hughes88d63092013-01-09 09:55:54 -08001800void Dbg::GetLocalValue(JDWP::ObjectId thread_id, JDWP::FrameId frame_id, int slot, JDWP::JdwpTag tag,
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001801 uint8_t* buf, size_t width) {
Ian Rogers0399dde2012-06-06 17:09:28 -07001802 struct GetLocalVisitor : public StackVisitor {
Ian Rogers306057f2012-11-26 12:45:53 -08001803 GetLocalVisitor(const ManagedStack* stack,
1804 const std::deque<InstrumentationStackFrame>* instrumentation_stack,
Elliott Hughes88d63092013-01-09 09:55:54 -08001805 Context* context, JDWP::FrameId frame_id, int slot, JDWP::JdwpTag tag,
Ian Rogersca190662012-06-26 15:45:57 -07001806 uint8_t* buf, size_t width)
Ian Rogersb726dcb2012-09-05 08:57:23 -07001807 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_)
Elliott Hughes88d63092013-01-09 09:55:54 -08001808 : StackVisitor(stack, instrumentation_stack, context), frame_id_(frame_id), slot_(slot), tag_(tag),
Ian Rogersca190662012-06-26 15:45:57 -07001809 buf_(buf), width_(width) {}
1810
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001811 // TODO: Enable annotalysis. We know lock is held in constructor, but abstraction confuses
1812 // annotalysis.
1813 bool VisitFrame() NO_THREAD_SAFETY_ANALYSIS {
Ian Rogers0399dde2012-06-06 17:09:28 -07001814 if (GetFrameId() != frame_id_) {
1815 return true; // Not our frame, carry on.
Elliott Hughesdbb40792011-11-18 17:05:22 -08001816 }
Ian Rogers0399dde2012-06-06 17:09:28 -07001817 // TODO: check that the tag is compatible with the actual type of the slot!
Mathieu Chartier66f19252012-09-18 08:57:04 -07001818 AbstractMethod* m = GetMethod();
Ian Rogers0399dde2012-06-06 17:09:28 -07001819 uint16_t reg = DemangleSlot(slot_, m);
Elliott Hughesdbb40792011-11-18 17:05:22 -08001820
Ian Rogers0399dde2012-06-06 17:09:28 -07001821 switch (tag_) {
1822 case JDWP::JT_BOOLEAN:
1823 {
1824 CHECK_EQ(width_, 1U);
Ian Rogers2bcb4a42012-11-08 10:39:18 -08001825 uint32_t intVal = GetVReg(m, reg, kIntVReg);
Ian Rogers0399dde2012-06-06 17:09:28 -07001826 VLOG(jdwp) << "get boolean local " << reg << " = " << intVal;
1827 JDWP::Set1(buf_+1, intVal != 0);
1828 }
1829 break;
1830 case JDWP::JT_BYTE:
1831 {
1832 CHECK_EQ(width_, 1U);
Ian Rogers2bcb4a42012-11-08 10:39:18 -08001833 uint32_t intVal = GetVReg(m, reg, kIntVReg);
Ian Rogers0399dde2012-06-06 17:09:28 -07001834 VLOG(jdwp) << "get byte local " << reg << " = " << intVal;
1835 JDWP::Set1(buf_+1, intVal);
1836 }
1837 break;
1838 case JDWP::JT_SHORT:
1839 case JDWP::JT_CHAR:
1840 {
1841 CHECK_EQ(width_, 2U);
Ian Rogers2bcb4a42012-11-08 10:39:18 -08001842 uint32_t intVal = GetVReg(m, reg, kIntVReg);
Ian Rogers0399dde2012-06-06 17:09:28 -07001843 VLOG(jdwp) << "get short/char local " << reg << " = " << intVal;
1844 JDWP::Set2BE(buf_+1, intVal);
1845 }
1846 break;
1847 case JDWP::JT_INT:
Ian Rogers2bcb4a42012-11-08 10:39:18 -08001848 {
1849 CHECK_EQ(width_, 4U);
1850 uint32_t intVal = GetVReg(m, reg, kIntVReg);
1851 VLOG(jdwp) << "get int local " << reg << " = " << intVal;
1852 JDWP::Set4BE(buf_+1, intVal);
1853 }
1854 break;
Ian Rogers0399dde2012-06-06 17:09:28 -07001855 case JDWP::JT_FLOAT:
1856 {
1857 CHECK_EQ(width_, 4U);
Ian Rogers2bcb4a42012-11-08 10:39:18 -08001858 uint32_t intVal = GetVReg(m, reg, kFloatVReg);
Ian Rogers0399dde2012-06-06 17:09:28 -07001859 VLOG(jdwp) << "get int/float local " << reg << " = " << intVal;
1860 JDWP::Set4BE(buf_+1, intVal);
1861 }
1862 break;
1863 case JDWP::JT_ARRAY:
1864 {
1865 CHECK_EQ(width_, sizeof(JDWP::ObjectId));
Ian Rogers2bcb4a42012-11-08 10:39:18 -08001866 Object* o = reinterpret_cast<Object*>(GetVReg(m, reg, kReferenceVReg));
Ian Rogers0399dde2012-06-06 17:09:28 -07001867 VLOG(jdwp) << "get array local " << reg << " = " << o;
1868 if (!Runtime::Current()->GetHeap()->IsHeapAddress(o)) {
1869 LOG(FATAL) << "Register " << reg << " expected to hold array: " << o;
1870 }
1871 JDWP::SetObjectId(buf_+1, gRegistry->Add(o));
1872 }
1873 break;
1874 case JDWP::JT_CLASS_LOADER:
1875 case JDWP::JT_CLASS_OBJECT:
1876 case JDWP::JT_OBJECT:
1877 case JDWP::JT_STRING:
1878 case JDWP::JT_THREAD:
1879 case JDWP::JT_THREAD_GROUP:
1880 {
1881 CHECK_EQ(width_, sizeof(JDWP::ObjectId));
Ian Rogers2bcb4a42012-11-08 10:39:18 -08001882 Object* o = reinterpret_cast<Object*>(GetVReg(m, reg, kReferenceVReg));
Ian Rogers0399dde2012-06-06 17:09:28 -07001883 VLOG(jdwp) << "get object local " << reg << " = " << o;
1884 if (!Runtime::Current()->GetHeap()->IsHeapAddress(o)) {
1885 LOG(FATAL) << "Register " << reg << " expected to hold object: " << o;
1886 }
1887 tag_ = TagFromObject(o);
1888 JDWP::SetObjectId(buf_+1, gRegistry->Add(o));
1889 }
1890 break;
1891 case JDWP::JT_DOUBLE:
Ian Rogers2bcb4a42012-11-08 10:39:18 -08001892 {
1893 CHECK_EQ(width_, 8U);
1894 uint32_t lo = GetVReg(m, reg, kDoubleLoVReg);
1895 uint64_t hi = GetVReg(m, reg + 1, kDoubleHiVReg);
1896 uint64_t longVal = (hi << 32) | lo;
1897 VLOG(jdwp) << "get double/long local " << hi << ":" << lo << " = " << longVal;
1898 JDWP::Set8BE(buf_+1, longVal);
1899 }
1900 break;
Ian Rogers0399dde2012-06-06 17:09:28 -07001901 case JDWP::JT_LONG:
1902 {
1903 CHECK_EQ(width_, 8U);
Ian Rogers2bcb4a42012-11-08 10:39:18 -08001904 uint32_t lo = GetVReg(m, reg, kLongLoVReg);
1905 uint64_t hi = GetVReg(m, reg + 1, kLongHiVReg);
Ian Rogers0399dde2012-06-06 17:09:28 -07001906 uint64_t longVal = (hi << 32) | lo;
1907 VLOG(jdwp) << "get double/long local " << hi << ":" << lo << " = " << longVal;
1908 JDWP::Set8BE(buf_+1, longVal);
1909 }
1910 break;
1911 default:
1912 LOG(FATAL) << "Unknown tag " << tag_;
1913 break;
1914 }
1915
1916 // Prepend tag, which may have been updated.
1917 JDWP::Set1(buf_, tag_);
1918 return false;
1919 }
1920
1921 const JDWP::FrameId frame_id_;
1922 const int slot_;
1923 JDWP::JdwpTag tag_;
1924 uint8_t* const buf_;
1925 const size_t width_;
1926 };
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001927
1928 ScopedObjectAccessUnchecked soa(Thread::Current());
jeffhaoa77f0f62012-12-05 17:19:31 -08001929 MutexLock mu(soa.Self(), *Locks::thread_list_lock_);
Elliott Hughes221229c2013-01-08 18:17:50 -08001930 Thread* thread;
1931 JDWP::JdwpError error = DecodeThread(soa, thread_id, thread);
1932 if (error != JDWP::ERR_NONE) {
1933 return;
1934 }
Ian Rogers0399dde2012-06-06 17:09:28 -07001935 UniquePtr<Context> context(Context::Create());
jeffhao725a9572012-11-13 18:20:12 -08001936 GetLocalVisitor visitor(thread->GetManagedStack(), thread->GetInstrumentationStack(), context.get(),
Elliott Hughes88d63092013-01-09 09:55:54 -08001937 frame_id, slot, tag, buf, width);
Ian Rogers0399dde2012-06-06 17:09:28 -07001938 visitor.WalkStack();
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001939}
1940
Elliott Hughes88d63092013-01-09 09:55:54 -08001941void Dbg::SetLocalValue(JDWP::ObjectId thread_id, JDWP::FrameId frame_id, int slot, JDWP::JdwpTag tag,
Ian Rogers0399dde2012-06-06 17:09:28 -07001942 uint64_t value, size_t width) {
1943 struct SetLocalVisitor : public StackVisitor {
Ian Rogers306057f2012-11-26 12:45:53 -08001944 SetLocalVisitor(const ManagedStack* stack, const std::deque<InstrumentationStackFrame>* instrumentation_stack, Context* context,
Ian Rogers0399dde2012-06-06 17:09:28 -07001945 JDWP::FrameId frame_id, int slot, JDWP::JdwpTag tag, uint64_t value,
Ian Rogersca190662012-06-26 15:45:57 -07001946 size_t width)
Ian Rogersb726dcb2012-09-05 08:57:23 -07001947 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_)
jeffhao725a9572012-11-13 18:20:12 -08001948 : StackVisitor(stack, instrumentation_stack, context),
Elliott Hughes08fc03a2012-06-26 17:34:00 -07001949 frame_id_(frame_id), slot_(slot), tag_(tag), value_(value), width_(width) {}
Ian Rogersca190662012-06-26 15:45:57 -07001950
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001951 // TODO: Enable annotalysis. We know lock is held in constructor, but abstraction confuses
1952 // annotalysis.
1953 bool VisitFrame() NO_THREAD_SAFETY_ANALYSIS {
Ian Rogers0399dde2012-06-06 17:09:28 -07001954 if (GetFrameId() != frame_id_) {
1955 return true; // Not our frame, carry on.
1956 }
1957 // TODO: check that the tag is compatible with the actual type of the slot!
Mathieu Chartier66f19252012-09-18 08:57:04 -07001958 AbstractMethod* m = GetMethod();
Ian Rogers0399dde2012-06-06 17:09:28 -07001959 uint16_t reg = DemangleSlot(slot_, m);
1960
1961 switch (tag_) {
1962 case JDWP::JT_BOOLEAN:
1963 case JDWP::JT_BYTE:
1964 CHECK_EQ(width_, 1U);
Ian Rogers2bcb4a42012-11-08 10:39:18 -08001965 SetVReg(m, reg, static_cast<uint32_t>(value_), kIntVReg);
Ian Rogers0399dde2012-06-06 17:09:28 -07001966 break;
1967 case JDWP::JT_SHORT:
1968 case JDWP::JT_CHAR:
1969 CHECK_EQ(width_, 2U);
Ian Rogers2bcb4a42012-11-08 10:39:18 -08001970 SetVReg(m, reg, static_cast<uint32_t>(value_), kIntVReg);
Ian Rogers0399dde2012-06-06 17:09:28 -07001971 break;
1972 case JDWP::JT_INT:
Ian Rogers2bcb4a42012-11-08 10:39:18 -08001973 CHECK_EQ(width_, 4U);
1974 SetVReg(m, reg, static_cast<uint32_t>(value_), kIntVReg);
1975 break;
Ian Rogers0399dde2012-06-06 17:09:28 -07001976 case JDWP::JT_FLOAT:
1977 CHECK_EQ(width_, 4U);
Ian Rogers2bcb4a42012-11-08 10:39:18 -08001978 SetVReg(m, reg, static_cast<uint32_t>(value_), kFloatVReg);
Ian Rogers0399dde2012-06-06 17:09:28 -07001979 break;
1980 case JDWP::JT_ARRAY:
1981 case JDWP::JT_OBJECT:
1982 case JDWP::JT_STRING:
1983 {
1984 CHECK_EQ(width_, sizeof(JDWP::ObjectId));
1985 Object* o = gRegistry->Get<Object*>(static_cast<JDWP::ObjectId>(value_));
1986 if (o == kInvalidObject) {
1987 UNIMPLEMENTED(FATAL) << "return an error code when given an invalid object to store";
1988 }
Ian Rogers2bcb4a42012-11-08 10:39:18 -08001989 SetVReg(m, reg, static_cast<uint32_t>(reinterpret_cast<uintptr_t>(o)), kReferenceVReg);
Ian Rogers0399dde2012-06-06 17:09:28 -07001990 }
1991 break;
1992 case JDWP::JT_DOUBLE:
Ian Rogers2bcb4a42012-11-08 10:39:18 -08001993 CHECK_EQ(width_, 8U);
1994 SetVReg(m, reg, static_cast<uint32_t>(value_), kDoubleLoVReg);
1995 SetVReg(m, reg + 1, static_cast<uint32_t>(value_ >> 32), kDoubleHiVReg);
1996 break;
Ian Rogers0399dde2012-06-06 17:09:28 -07001997 case JDWP::JT_LONG:
1998 CHECK_EQ(width_, 8U);
Ian Rogers2bcb4a42012-11-08 10:39:18 -08001999 SetVReg(m, reg, static_cast<uint32_t>(value_), kLongLoVReg);
2000 SetVReg(m, reg + 1, static_cast<uint32_t>(value_ >> 32), kLongHiVReg);
Ian Rogers0399dde2012-06-06 17:09:28 -07002001 break;
2002 default:
2003 LOG(FATAL) << "Unknown tag " << tag_;
2004 break;
2005 }
2006 return false;
2007 }
2008
2009 const JDWP::FrameId frame_id_;
2010 const int slot_;
2011 const JDWP::JdwpTag tag_;
2012 const uint64_t value_;
2013 const size_t width_;
2014 };
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002015
2016 ScopedObjectAccessUnchecked soa(Thread::Current());
jeffhaoa77f0f62012-12-05 17:19:31 -08002017 MutexLock mu(soa.Self(), *Locks::thread_list_lock_);
Elliott Hughes221229c2013-01-08 18:17:50 -08002018 Thread* thread;
2019 JDWP::JdwpError error = DecodeThread(soa, thread_id, thread);
2020 if (error != JDWP::ERR_NONE) {
2021 return;
2022 }
Elliott Hughes08fc03a2012-06-26 17:34:00 -07002023 UniquePtr<Context> context(Context::Create());
jeffhao725a9572012-11-13 18:20:12 -08002024 SetLocalVisitor visitor(thread->GetManagedStack(), thread->GetInstrumentationStack(), context.get(),
Elliott Hughes88d63092013-01-09 09:55:54 -08002025 frame_id, slot, tag, value, width);
Ian Rogers0399dde2012-06-06 17:09:28 -07002026 visitor.WalkStack();
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002027}
2028
Mathieu Chartier66f19252012-09-18 08:57:04 -07002029void Dbg::PostLocationEvent(const AbstractMethod* m, int dex_pc, Object* this_object, int event_flags) {
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08002030 Class* c = m->GetDeclaringClass();
2031
2032 JDWP::JdwpLocation location;
Elliott Hughes74847412012-06-20 18:10:21 -07002033 location.type_tag = c->IsInterface() ? JDWP::TT_INTERFACE : JDWP::TT_CLASS;
2034 location.class_id = gRegistry->Add(c);
2035 location.method_id = ToMethodId(m);
Elliott Hughes972a47b2012-02-21 18:16:06 -08002036 location.dex_pc = m->IsNative() ? -1 : dex_pc;
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08002037
2038 // Note we use "NoReg" so we don't keep track of references that are
2039 // never actually sent to the debugger. 'this_id' is only used to
2040 // compare against registered events...
2041 JDWP::ObjectId this_id = static_cast<JDWP::ObjectId>(reinterpret_cast<uintptr_t>(this_object));
2042 if (gJdwpState->PostLocationEvent(&location, this_id, event_flags)) {
2043 // ...unless there's a registered event, in which case we
2044 // need to really track the class and 'this'.
2045 gRegistry->Add(c);
2046 gRegistry->Add(this_object);
2047 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002048}
2049
Elliott Hughescaf76542012-06-28 16:08:22 -07002050void Dbg::PostException(Thread* thread,
Mathieu Chartier66f19252012-09-18 08:57:04 -07002051 JDWP::FrameId throw_frame_id, AbstractMethod* throw_method, uint32_t throw_dex_pc,
2052 AbstractMethod* catch_method, uint32_t catch_dex_pc, Throwable* exception) {
Elliott Hughesc0f09332012-03-26 13:27:06 -07002053 if (!IsDebuggerActive()) {
Ian Rogers0ad5bb82011-12-07 10:16:32 -08002054 return;
2055 }
Elliott Hughes4740cdf2011-12-07 14:07:12 -08002056
Elliott Hughesd07986f2011-12-06 18:27:45 -08002057 JDWP::JdwpLocation throw_location;
Elliott Hughescaf76542012-06-28 16:08:22 -07002058 SetLocation(throw_location, throw_method, throw_dex_pc);
Elliott Hughesd07986f2011-12-06 18:27:45 -08002059 JDWP::JdwpLocation catch_location;
Elliott Hughescaf76542012-06-28 16:08:22 -07002060 SetLocation(catch_location, catch_method, catch_dex_pc);
Elliott Hughesd07986f2011-12-06 18:27:45 -08002061
2062 // We need 'this' for InstanceOnly filters.
Elliott Hughescaf76542012-06-28 16:08:22 -07002063 UniquePtr<Context> context(Context::Create());
jeffhao725a9572012-11-13 18:20:12 -08002064 GetThisVisitor visitor(thread->GetManagedStack(), thread->GetInstrumentationStack(), context.get(), throw_frame_id);
Elliott Hughescaf76542012-06-28 16:08:22 -07002065 visitor.WalkStack();
2066 JDWP::ObjectId this_id = gRegistry->Add(visitor.this_object);
Elliott Hughesd07986f2011-12-06 18:27:45 -08002067
2068 /*
2069 * Hand the event to the JDWP exception handler. Note we're using the
2070 * "NoReg" objectID on the exception, which is not strictly correct --
2071 * the exception object WILL be passed up to the debugger if the
2072 * debugger is interested in the event. We do this because the current
2073 * implementation of the debugger object registry never throws anything
2074 * away, and some people were experiencing a fatal build up of exception
2075 * objects when dealing with certain libraries.
2076 */
2077 JDWP::ObjectId exception_id = static_cast<JDWP::ObjectId>(reinterpret_cast<uintptr_t>(exception));
2078 JDWP::RefTypeId exception_class_id = gRegistry->Add(exception->GetClass());
2079
2080 gJdwpState->PostException(&throw_location, exception_id, exception_class_id, &catch_location, this_id);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002081}
2082
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002083void Dbg::PostClassPrepare(Class* c) {
Elliott Hughesc0f09332012-03-26 13:27:06 -07002084 if (!IsDebuggerActive()) {
Elliott Hughes4740cdf2011-12-07 14:07:12 -08002085 return;
2086 }
2087
Elliott Hughes3d30d9b2011-12-07 17:35:48 -08002088 // OLD-TODO - we currently always send both "verified" and "prepared" since
Elliott Hughes4740cdf2011-12-07 14:07:12 -08002089 // debuggers seem to like that. There might be some advantage to honesty,
2090 // since the class may not yet be verified.
2091 int state = JDWP::CS_VERIFIED | JDWP::CS_PREPARED;
2092 JDWP::JdwpTypeTag tag = c->IsInterface() ? JDWP::TT_INTERFACE : JDWP::TT_CLASS;
2093 gJdwpState->PostClassPrepare(tag, gRegistry->Add(c), ClassHelper(c).GetDescriptor(), state);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002094}
2095
Elliott Hughescaf76542012-06-28 16:08:22 -07002096void Dbg::UpdateDebugger(int32_t dex_pc, Thread* self) {
Elliott Hughesc0f09332012-03-26 13:27:06 -07002097 if (!IsDebuggerActive() || dex_pc == -2 /* fake method exit */) {
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08002098 return;
2099 }
2100
Elliott Hughescaf76542012-06-28 16:08:22 -07002101 size_t frame_id;
Mathieu Chartier66f19252012-09-18 08:57:04 -07002102 AbstractMethod* m = self->GetCurrentMethod(NULL, &frame_id);
Elliott Hughescaf76542012-06-28 16:08:22 -07002103 //LOG(INFO) << "UpdateDebugger " << PrettyMethod(m) << "@" << dex_pc << " frame " << frame_id;
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08002104
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08002105 if (dex_pc == -1) {
Elliott Hughes2aa2e392012-02-17 17:15:43 -08002106 // We use a pc of -1 to represent method entry, since we might branch back to pc 0 later.
2107 // This means that for this special notification, there can't be anything else interesting
2108 // going on, so we're done already.
Elliott Hughescaf76542012-06-28 16:08:22 -07002109 Dbg::PostLocationEvent(m, 0, GetThis(self, m, frame_id), kMethodEntry);
Elliott Hughes2aa2e392012-02-17 17:15:43 -08002110 return;
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08002111 }
2112
Elliott Hughes2aa2e392012-02-17 17:15:43 -08002113 int event_flags = 0;
2114
Elliott Hughes86964332012-02-15 19:37:42 -08002115 if (IsBreakpoint(m, dex_pc)) {
2116 event_flags |= kBreakpoint;
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08002117 }
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08002118
jeffhao09bfc6a2012-12-11 18:11:43 -08002119 {
2120 // If the debugger is single-stepping one of our threads, check to
2121 // see if we're that thread and we've reached a step point.
2122 MutexLock mu(Thread::Current(), *Locks::breakpoint_lock_);
2123 if (gSingleStepControl.is_active && gSingleStepControl.thread == self) {
2124 CHECK(!m->IsNative());
2125 if (gSingleStepControl.step_depth == JDWP::SD_INTO) {
2126 // Step into method calls. We break when the line number
2127 // or method pointer changes. If we're in SS_MIN mode, we
2128 // always stop.
2129 if (gSingleStepControl.method != m) {
2130 event_flags |= kSingleStep;
2131 VLOG(jdwp) << "SS new method";
2132 } else if (gSingleStepControl.step_size == JDWP::SS_MIN) {
Elliott Hughes86964332012-02-15 19:37:42 -08002133 event_flags |= kSingleStep;
2134 VLOG(jdwp) << "SS new instruction";
Elliott Hughes2435a572012-02-17 16:07:41 -08002135 } else if (gSingleStepControl.dex_pcs.find(dex_pc) == gSingleStepControl.dex_pcs.end()) {
2136 event_flags |= kSingleStep;
2137 VLOG(jdwp) << "SS new line";
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08002138 }
jeffhao09bfc6a2012-12-11 18:11:43 -08002139 } else if (gSingleStepControl.step_depth == JDWP::SD_OVER) {
2140 // Step over method calls. We break when the line number is
2141 // different and the frame depth is <= the original frame
2142 // depth. (We can't just compare on the method, because we
2143 // might get unrolled past it by an exception, and it's tricky
2144 // to identify recursion.)
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08002145
jeffhao09bfc6a2012-12-11 18:11:43 -08002146 int stack_depth = GetStackDepth(self);
Elliott Hughes86964332012-02-15 19:37:42 -08002147
jeffhao09bfc6a2012-12-11 18:11:43 -08002148 if (stack_depth < gSingleStepControl.stack_depth) {
2149 // popped up one or more frames, always trigger
2150 event_flags |= kSingleStep;
2151 VLOG(jdwp) << "SS method pop";
2152 } else if (stack_depth == gSingleStepControl.stack_depth) {
2153 // same depth, see if we moved
2154 if (gSingleStepControl.step_size == JDWP::SS_MIN) {
2155 event_flags |= kSingleStep;
2156 VLOG(jdwp) << "SS new instruction";
2157 } else if (gSingleStepControl.dex_pcs.find(dex_pc) == gSingleStepControl.dex_pcs.end()) {
2158 event_flags |= kSingleStep;
2159 VLOG(jdwp) << "SS new line";
2160 }
2161 }
2162 } else {
2163 CHECK_EQ(gSingleStepControl.step_depth, JDWP::SD_OUT);
2164 // Return from the current method. We break when the frame
2165 // depth pops up.
2166
2167 // This differs from the "method exit" break in that it stops
2168 // with the PC at the next instruction in the returned-to
2169 // function, rather than the end of the returning function.
2170
2171 int stack_depth = GetStackDepth(self);
2172 if (stack_depth < gSingleStepControl.stack_depth) {
2173 event_flags |= kSingleStep;
2174 VLOG(jdwp) << "SS method pop";
2175 }
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08002176 }
2177 }
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08002178 }
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08002179
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08002180 // Check to see if this is a "return" instruction. JDWP says we should
2181 // send the event *after* the code has been executed, but it also says
2182 // the location we provide is the last instruction. Since the "return"
2183 // instruction has no interesting side effects, we should be safe.
2184 // (We can't just move this down to the returnFromMethod label because
2185 // we potentially need to combine it with other events.)
2186 // We're also not supposed to generate a method exit event if the method
2187 // terminates "with a thrown exception".
Elliott Hughes86964332012-02-15 19:37:42 -08002188 if (dex_pc >= 0) {
2189 const DexFile::CodeItem* code_item = MethodHelper(m).GetCodeItem();
Elliott Hughescaf76542012-06-28 16:08:22 -07002190 CHECK(code_item != NULL) << PrettyMethod(m) << " @" << dex_pc;
Elliott Hughes86964332012-02-15 19:37:42 -08002191 CHECK_LT(dex_pc, static_cast<int32_t>(code_item->insns_size_in_code_units_));
2192 if (Instruction::At(&code_item->insns_[dex_pc])->IsReturn()) {
2193 event_flags |= kMethodExit;
2194 }
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08002195 }
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08002196
2197 // If there's something interesting going on, see if it matches one
2198 // of the debugger filters.
2199 if (event_flags != 0) {
Elliott Hughescaf76542012-06-28 16:08:22 -07002200 Dbg::PostLocationEvent(m, dex_pc, GetThis(self, m, frame_id), event_flags);
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08002201 }
2202}
2203
Elliott Hughes86964332012-02-15 19:37:42 -08002204void Dbg::WatchLocation(const JDWP::JdwpLocation* location) {
jeffhao09bfc6a2012-12-11 18:11:43 -08002205 MutexLock mu(Thread::Current(), *Locks::breakpoint_lock_);
Mathieu Chartier66f19252012-09-18 08:57:04 -07002206 AbstractMethod* m = FromMethodId(location->method_id);
Elliott Hughes972a47b2012-02-21 18:16:06 -08002207 gBreakpoints.push_back(Breakpoint(m, location->dex_pc));
Elliott Hughes86964332012-02-15 19:37:42 -08002208 VLOG(jdwp) << "Set breakpoint #" << (gBreakpoints.size() - 1) << ": " << gBreakpoints[gBreakpoints.size() - 1];
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002209}
2210
Elliott Hughes86964332012-02-15 19:37:42 -08002211void Dbg::UnwatchLocation(const JDWP::JdwpLocation* location) {
jeffhao09bfc6a2012-12-11 18:11:43 -08002212 MutexLock mu(Thread::Current(), *Locks::breakpoint_lock_);
Mathieu Chartier66f19252012-09-18 08:57:04 -07002213 AbstractMethod* m = FromMethodId(location->method_id);
Elliott Hughes86964332012-02-15 19:37:42 -08002214 for (size_t i = 0; i < gBreakpoints.size(); ++i) {
Elliott Hughes972a47b2012-02-21 18:16:06 -08002215 if (gBreakpoints[i].method == m && gBreakpoints[i].dex_pc == location->dex_pc) {
Elliott Hughes86964332012-02-15 19:37:42 -08002216 VLOG(jdwp) << "Removed breakpoint #" << i << ": " << gBreakpoints[i];
2217 gBreakpoints.erase(gBreakpoints.begin() + i);
2218 return;
2219 }
2220 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002221}
2222
Elliott Hughes221229c2013-01-08 18:17:50 -08002223JDWP::JdwpError Dbg::ConfigureStep(JDWP::ObjectId thread_id, JDWP::JdwpStepSize step_size,
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002224 JDWP::JdwpStepDepth step_depth) {
2225 ScopedObjectAccessUnchecked soa(Thread::Current());
jeffhaoa77f0f62012-12-05 17:19:31 -08002226 MutexLock mu(soa.Self(), *Locks::thread_list_lock_);
Elliott Hughes221229c2013-01-08 18:17:50 -08002227 Thread* thread;
2228 JDWP::JdwpError error = DecodeThread(soa, thread_id, thread);
2229 if (error != JDWP::ERR_NONE) {
2230 return error;
Elliott Hughes2435a572012-02-17 16:07:41 -08002231 }
Elliott Hughes86964332012-02-15 19:37:42 -08002232
jeffhao09bfc6a2012-12-11 18:11:43 -08002233 MutexLock mu2(soa.Self(), *Locks::breakpoint_lock_);
Elliott Hughes86964332012-02-15 19:37:42 -08002234 // TODO: there's no theoretical reason why we couldn't support single-stepping
2235 // of multiple threads at once, but we never did so historically.
2236 if (gSingleStepControl.thread != NULL && thread != gSingleStepControl.thread) {
2237 LOG(WARNING) << "single-step already active for " << *gSingleStepControl.thread
2238 << "; switching to " << *thread;
2239 }
2240
Elliott Hughes2435a572012-02-17 16:07:41 -08002241 //
2242 // Work out what Method* we're in, the current line number, and how deep the stack currently
2243 // is for step-out.
2244 //
2245
Ian Rogers0399dde2012-06-06 17:09:28 -07002246 struct SingleStepStackVisitor : public StackVisitor {
2247 SingleStepStackVisitor(const ManagedStack* stack,
Ian Rogers306057f2012-11-26 12:45:53 -08002248 const std::deque<InstrumentationStackFrame>* instrumentation_stack)
jeffhao09bfc6a2012-12-11 18:11:43 -08002249 EXCLUSIVE_LOCKS_REQUIRED(Locks::breakpoint_lock_)
Ian Rogersb726dcb2012-09-05 08:57:23 -07002250 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_)
jeffhao725a9572012-11-13 18:20:12 -08002251 : StackVisitor(stack, instrumentation_stack, NULL) {
Elliott Hughes86964332012-02-15 19:37:42 -08002252 gSingleStepControl.method = NULL;
2253 gSingleStepControl.stack_depth = 0;
2254 }
Ian Rogersca190662012-06-26 15:45:57 -07002255
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002256 // TODO: Enable annotalysis. We know lock is held in constructor, but abstraction confuses
2257 // annotalysis.
2258 bool VisitFrame() NO_THREAD_SAFETY_ANALYSIS {
jeffhao09bfc6a2012-12-11 18:11:43 -08002259 Locks::breakpoint_lock_->AssertHeld(Thread::Current());
Mathieu Chartier66f19252012-09-18 08:57:04 -07002260 const AbstractMethod* m = GetMethod();
Ian Rogers0399dde2012-06-06 17:09:28 -07002261 if (!m->IsRuntimeMethod()) {
Elliott Hughes86964332012-02-15 19:37:42 -08002262 ++gSingleStepControl.stack_depth;
2263 if (gSingleStepControl.method == NULL) {
Elliott Hughes2435a572012-02-17 16:07:41 -08002264 const DexCache* dex_cache = m->GetDeclaringClass()->GetDexCache();
2265 gSingleStepControl.method = m;
2266 gSingleStepControl.line_number = -1;
2267 if (dex_cache != NULL) {
Ian Rogers4445a7e2012-10-05 17:19:13 -07002268 const DexFile& dex_file = *dex_cache->GetDexFile();
Ian Rogers0399dde2012-06-06 17:09:28 -07002269 gSingleStepControl.line_number = dex_file.GetLineNumFromPC(m, GetDexPc());
Elliott Hughes2435a572012-02-17 16:07:41 -08002270 }
Elliott Hughes86964332012-02-15 19:37:42 -08002271 }
2272 }
Elliott Hughes530fa002012-03-12 11:44:49 -07002273 return true;
Elliott Hughes86964332012-02-15 19:37:42 -08002274 }
2275 };
jeffhao725a9572012-11-13 18:20:12 -08002276 SingleStepStackVisitor visitor(thread->GetManagedStack(), thread->GetInstrumentationStack());
Ian Rogers0399dde2012-06-06 17:09:28 -07002277 visitor.WalkStack();
Elliott Hughes86964332012-02-15 19:37:42 -08002278
Elliott Hughes2435a572012-02-17 16:07:41 -08002279 //
2280 // Find the dex_pc values that correspond to the current line, for line-based single-stepping.
2281 //
2282
2283 struct DebugCallbackContext {
jeffhao09bfc6a2012-12-11 18:11:43 -08002284 DebugCallbackContext() EXCLUSIVE_LOCKS_REQUIRED(Locks::breakpoint_lock_) {
Elliott Hughes2435a572012-02-17 16:07:41 -08002285 last_pc_valid = false;
2286 last_pc = 0;
Elliott Hughes2435a572012-02-17 16:07:41 -08002287 }
2288
jeffhao09bfc6a2012-12-11 18:11:43 -08002289 // TODO: Enable annotalysis. We know lock is held in constructor, but abstraction confuses
2290 // annotalysis.
2291 static bool Callback(void* raw_context, uint32_t address, uint32_t line_number) NO_THREAD_SAFETY_ANALYSIS {
2292 Locks::breakpoint_lock_->AssertHeld(Thread::Current());
Elliott Hughes2435a572012-02-17 16:07:41 -08002293 DebugCallbackContext* context = reinterpret_cast<DebugCallbackContext*>(raw_context);
2294 if (static_cast<int32_t>(line_number) == gSingleStepControl.line_number) {
2295 if (!context->last_pc_valid) {
2296 // Everything from this address until the next line change is ours.
2297 context->last_pc = address;
2298 context->last_pc_valid = true;
2299 }
2300 // Otherwise, if we're already in a valid range for this line,
2301 // just keep going (shouldn't really happen)...
2302 } else if (context->last_pc_valid) { // and the line number is new
2303 // Add everything from the last entry up until here to the set
2304 for (uint32_t dex_pc = context->last_pc; dex_pc < address; ++dex_pc) {
2305 gSingleStepControl.dex_pcs.insert(dex_pc);
2306 }
2307 context->last_pc_valid = false;
2308 }
2309 return false; // There may be multiple entries for any given line.
2310 }
2311
jeffhao09bfc6a2012-12-11 18:11:43 -08002312 // TODO: Enable annotalysis. We know lock is held in constructor, but abstraction confuses
2313 // annotalysis.
2314 ~DebugCallbackContext() NO_THREAD_SAFETY_ANALYSIS {
2315 Locks::breakpoint_lock_->AssertHeld(Thread::Current());
Elliott Hughes2435a572012-02-17 16:07:41 -08002316 // If the line number was the last in the position table...
2317 if (last_pc_valid) {
2318 size_t end = MethodHelper(gSingleStepControl.method).GetCodeItem()->insns_size_in_code_units_;
2319 for (uint32_t dex_pc = last_pc; dex_pc < end; ++dex_pc) {
2320 gSingleStepControl.dex_pcs.insert(dex_pc);
2321 }
2322 }
2323 }
2324
2325 bool last_pc_valid;
2326 uint32_t last_pc;
2327 };
Elliott Hughes3e2e1a22012-02-21 11:33:41 -08002328 gSingleStepControl.dex_pcs.clear();
Mathieu Chartier66f19252012-09-18 08:57:04 -07002329 const AbstractMethod* m = gSingleStepControl.method;
Elliott Hughes3e2e1a22012-02-21 11:33:41 -08002330 if (m->IsNative()) {
2331 gSingleStepControl.line_number = -1;
2332 } else {
2333 DebugCallbackContext context;
2334 MethodHelper mh(m);
2335 mh.GetDexFile().DecodeDebugInfo(mh.GetCodeItem(), m->IsStatic(), m->GetDexMethodIndex(),
2336 DebugCallbackContext::Callback, NULL, &context);
2337 }
Elliott Hughes2435a572012-02-17 16:07:41 -08002338
2339 //
2340 // Everything else...
2341 //
2342
Elliott Hughes86964332012-02-15 19:37:42 -08002343 gSingleStepControl.thread = thread;
2344 gSingleStepControl.step_size = step_size;
2345 gSingleStepControl.step_depth = step_depth;
2346 gSingleStepControl.is_active = true;
2347
Elliott Hughes2435a572012-02-17 16:07:41 -08002348 if (VLOG_IS_ON(jdwp)) {
2349 VLOG(jdwp) << "Single-step thread: " << *gSingleStepControl.thread;
2350 VLOG(jdwp) << "Single-step step size: " << gSingleStepControl.step_size;
2351 VLOG(jdwp) << "Single-step step depth: " << gSingleStepControl.step_depth;
2352 VLOG(jdwp) << "Single-step current method: " << PrettyMethod(gSingleStepControl.method);
2353 VLOG(jdwp) << "Single-step current line: " << gSingleStepControl.line_number;
2354 VLOG(jdwp) << "Single-step current stack depth: " << gSingleStepControl.stack_depth;
2355 VLOG(jdwp) << "Single-step dex_pc values:";
2356 for (std::set<uint32_t>::iterator it = gSingleStepControl.dex_pcs.begin() ; it != gSingleStepControl.dex_pcs.end(); ++it) {
Elliott Hughes229feb72012-02-23 13:33:29 -08002357 VLOG(jdwp) << StringPrintf(" %#x", *it);
Elliott Hughes2435a572012-02-17 16:07:41 -08002358 }
2359 }
2360
2361 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002362}
2363
Elliott Hughes221229c2013-01-08 18:17:50 -08002364void Dbg::UnconfigureStep(JDWP::ObjectId /*thread_id*/) {
jeffhao09bfc6a2012-12-11 18:11:43 -08002365 MutexLock mu(Thread::Current(), *Locks::breakpoint_lock_);
Elliott Hughesf8349362012-06-18 15:00:06 -07002366
Elliott Hughes86964332012-02-15 19:37:42 -08002367 gSingleStepControl.is_active = false;
2368 gSingleStepControl.thread = NULL;
Elliott Hughes2435a572012-02-17 16:07:41 -08002369 gSingleStepControl.dex_pcs.clear();
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002370}
2371
Elliott Hughes45651fd2012-02-21 15:48:20 -08002372static char JdwpTagToShortyChar(JDWP::JdwpTag tag) {
2373 switch (tag) {
2374 default:
2375 LOG(FATAL) << "unknown JDWP tag: " << PrintableChar(tag);
2376
2377 // Primitives.
2378 case JDWP::JT_BYTE: return 'B';
2379 case JDWP::JT_CHAR: return 'C';
2380 case JDWP::JT_FLOAT: return 'F';
2381 case JDWP::JT_DOUBLE: return 'D';
2382 case JDWP::JT_INT: return 'I';
2383 case JDWP::JT_LONG: return 'J';
2384 case JDWP::JT_SHORT: return 'S';
2385 case JDWP::JT_VOID: return 'V';
2386 case JDWP::JT_BOOLEAN: return 'Z';
2387
2388 // Reference types.
2389 case JDWP::JT_ARRAY:
2390 case JDWP::JT_OBJECT:
2391 case JDWP::JT_STRING:
2392 case JDWP::JT_THREAD:
2393 case JDWP::JT_THREAD_GROUP:
2394 case JDWP::JT_CLASS_LOADER:
2395 case JDWP::JT_CLASS_OBJECT:
2396 return 'L';
2397 }
2398}
2399
Elliott Hughes88d63092013-01-09 09:55:54 -08002400JDWP::JdwpError Dbg::InvokeMethod(JDWP::ObjectId thread_id, JDWP::ObjectId object_id,
2401 JDWP::RefTypeId class_id, JDWP::MethodId method_id,
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002402 uint32_t arg_count, uint64_t* arg_values,
2403 JDWP::JdwpTag* arg_types, uint32_t options,
2404 JDWP::JdwpTag* pResultTag, uint64_t* pResultValue,
2405 JDWP::ObjectId* pExceptionId) {
Elliott Hughesd07986f2011-12-06 18:27:45 -08002406 ThreadList* thread_list = Runtime::Current()->GetThreadList();
2407
2408 Thread* targetThread = NULL;
2409 DebugInvokeReq* req = NULL;
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002410 Thread* self = Thread::Current();
Elliott Hughesd07986f2011-12-06 18:27:45 -08002411 {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002412 ScopedObjectAccessUnchecked soa(self);
Ian Rogers50b35e22012-10-04 10:09:15 -07002413 MutexLock mu(soa.Self(), *Locks::thread_list_lock_);
Elliott Hughes221229c2013-01-08 18:17:50 -08002414 JDWP::JdwpError error = DecodeThread(soa, thread_id, targetThread);
2415 if (error != JDWP::ERR_NONE) {
2416 LOG(ERROR) << "InvokeMethod request for invalid thread id " << thread_id;
2417 return error;
Elliott Hughesd07986f2011-12-06 18:27:45 -08002418 }
2419 req = targetThread->GetInvokeReq();
2420 if (!req->ready) {
2421 LOG(ERROR) << "InvokeMethod request for thread not stopped by event: " << *targetThread;
2422 return JDWP::ERR_INVALID_THREAD;
2423 }
2424
2425 /*
2426 * We currently have a bug where we don't successfully resume the
2427 * target thread if the suspend count is too deep. We're expected to
2428 * require one "resume" for each "suspend", but when asked to execute
2429 * a method we have to resume fully and then re-suspend it back to the
2430 * same level. (The easiest way to cause this is to type "suspend"
2431 * multiple times in jdb.)
2432 *
2433 * It's unclear what this means when the event specifies "resume all"
2434 * and some threads are suspended more deeply than others. This is
2435 * a rare problem, so for now we just prevent it from hanging forever
2436 * by rejecting the method invocation request. Without this, we will
2437 * be stuck waiting on a suspended thread.
2438 */
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002439 int suspend_count;
2440 {
Ian Rogers50b35e22012-10-04 10:09:15 -07002441 MutexLock mu2(soa.Self(), *Locks::thread_suspend_count_lock_);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002442 suspend_count = targetThread->GetSuspendCount();
2443 }
Elliott Hughesd07986f2011-12-06 18:27:45 -08002444 if (suspend_count > 1) {
2445 LOG(ERROR) << *targetThread << " suspend count too deep for method invocation: " << suspend_count;
2446 return JDWP::ERR_THREAD_SUSPENDED; // Probably not expected here.
2447 }
2448
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08002449 JDWP::JdwpError status;
Elliott Hughes88d63092013-01-09 09:55:54 -08002450 Object* receiver = gRegistry->Get<Object*>(object_id);
Elliott Hughes45651fd2012-02-21 15:48:20 -08002451 if (receiver == kInvalidObject) {
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08002452 return JDWP::ERR_INVALID_OBJECT;
2453 }
Elliott Hughes45651fd2012-02-21 15:48:20 -08002454
Elliott Hughes221229c2013-01-08 18:17:50 -08002455 Object* thread = gRegistry->Get<Object*>(thread_id);
Elliott Hughes45651fd2012-02-21 15:48:20 -08002456 if (thread == kInvalidObject) {
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08002457 return JDWP::ERR_INVALID_OBJECT;
2458 }
Elliott Hughes45651fd2012-02-21 15:48:20 -08002459 // TODO: check that 'thread' is actually a java.lang.Thread!
2460
Elliott Hughes88d63092013-01-09 09:55:54 -08002461 Class* c = DecodeClass(class_id, status);
Elliott Hughes45651fd2012-02-21 15:48:20 -08002462 if (c == NULL) {
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08002463 return status;
2464 }
Elliott Hughes45651fd2012-02-21 15:48:20 -08002465
Elliott Hughes88d63092013-01-09 09:55:54 -08002466 AbstractMethod* m = FromMethodId(method_id);
Elliott Hughes45651fd2012-02-21 15:48:20 -08002467 if (m->IsStatic() != (receiver == NULL)) {
2468 return JDWP::ERR_INVALID_METHODID;
2469 }
2470 if (m->IsStatic()) {
2471 if (m->GetDeclaringClass() != c) {
2472 return JDWP::ERR_INVALID_METHODID;
2473 }
2474 } else {
2475 if (!m->GetDeclaringClass()->IsAssignableFrom(c)) {
2476 return JDWP::ERR_INVALID_METHODID;
2477 }
2478 }
2479
2480 // Check the argument list matches the method.
2481 MethodHelper mh(m);
2482 if (mh.GetShortyLength() - 1 != arg_count) {
2483 return JDWP::ERR_ILLEGAL_ARGUMENT;
2484 }
2485 const char* shorty = mh.GetShorty();
2486 for (size_t i = 0; i < arg_count; ++i) {
2487 if (shorty[i + 1] != JdwpTagToShortyChar(arg_types[i])) {
2488 return JDWP::ERR_ILLEGAL_ARGUMENT;
2489 }
2490 }
2491
2492 req->receiver_ = receiver;
2493 req->thread_ = thread;
2494 req->class_ = c;
2495 req->method_ = m;
2496 req->arg_count_ = arg_count;
2497 req->arg_values_ = arg_values;
Elliott Hughesd07986f2011-12-06 18:27:45 -08002498 req->options_ = options;
2499 req->invoke_needed_ = true;
2500 }
2501
2502 // The fact that we've released the thread list lock is a bit risky --- if the thread goes
2503 // away we're sitting high and dry -- but we must release this before the ResumeAllThreads
2504 // call, and it's unwise to hold it during WaitForSuspend.
2505
2506 {
2507 /*
2508 * We change our (JDWP thread) status, which should be THREAD_RUNNING,
Elliott Hughes81ff3182012-03-23 20:35:56 -07002509 * so we can suspend for a GC if the invoke request causes us to
Elliott Hughesd07986f2011-12-06 18:27:45 -08002510 * run out of memory. It's also a good idea to change it before locking
2511 * the invokeReq mutex, although that should never be held for long.
2512 */
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002513 self->TransitionFromRunnableToSuspended(kWaitingForDebuggerSend);
Elliott Hughesd07986f2011-12-06 18:27:45 -08002514
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08002515 VLOG(jdwp) << " Transferring control to event thread";
Elliott Hughesd07986f2011-12-06 18:27:45 -08002516 {
Ian Rogers50b35e22012-10-04 10:09:15 -07002517 MutexLock mu(self, req->lock_);
Elliott Hughesd07986f2011-12-06 18:27:45 -08002518
2519 if ((options & JDWP::INVOKE_SINGLE_THREADED) == 0) {
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08002520 VLOG(jdwp) << " Resuming all threads";
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002521 thread_list->UndoDebuggerSuspensions();
Elliott Hughesd07986f2011-12-06 18:27:45 -08002522 } else {
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08002523 VLOG(jdwp) << " Resuming event thread only";
Elliott Hughesd07986f2011-12-06 18:27:45 -08002524 thread_list->Resume(targetThread, true);
2525 }
2526
2527 // Wait for the request to finish executing.
2528 while (req->invoke_needed_) {
Ian Rogersc604d732012-10-14 16:09:54 -07002529 req->cond_.Wait(self);
Elliott Hughesd07986f2011-12-06 18:27:45 -08002530 }
2531 }
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08002532 VLOG(jdwp) << " Control has returned from event thread";
Elliott Hughesd07986f2011-12-06 18:27:45 -08002533
2534 /* wait for thread to re-suspend itself */
Elliott Hughes221229c2013-01-08 18:17:50 -08002535 SuspendThread(thread_id, false /* request_suspension */ );
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002536 self->TransitionFromSuspendedToRunnable();
Elliott Hughesd07986f2011-12-06 18:27:45 -08002537 }
2538
2539 /*
2540 * Suspend the threads. We waited for the target thread to suspend
2541 * itself, so all we need to do is suspend the others.
2542 *
2543 * The suspendAllThreads() call will double-suspend the event thread,
2544 * so we want to resume the target thread once to keep the books straight.
2545 */
2546 if ((options & JDWP::INVOKE_SINGLE_THREADED) == 0) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002547 self->TransitionFromRunnableToSuspended(kWaitingForDebuggerSuspension);
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08002548 VLOG(jdwp) << " Suspending all threads";
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002549 thread_list->SuspendAllForDebugger();
2550 self->TransitionFromSuspendedToRunnable();
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08002551 VLOG(jdwp) << " Resuming event thread to balance the count";
Elliott Hughesd07986f2011-12-06 18:27:45 -08002552 thread_list->Resume(targetThread, true);
2553 }
2554
2555 // Copy the result.
2556 *pResultTag = req->result_tag;
2557 if (IsPrimitiveTag(req->result_tag)) {
Elliott Hughesf24d3ce2012-04-11 17:43:37 -07002558 *pResultValue = req->result_value.GetJ();
Elliott Hughesd07986f2011-12-06 18:27:45 -08002559 } else {
Elliott Hughesf24d3ce2012-04-11 17:43:37 -07002560 *pResultValue = gRegistry->Add(req->result_value.GetL());
Elliott Hughesd07986f2011-12-06 18:27:45 -08002561 }
2562 *pExceptionId = req->exception;
2563 return req->error;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002564}
2565
2566void Dbg::ExecuteMethod(DebugInvokeReq* pReq) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002567 ScopedObjectAccess soa(Thread::Current());
Elliott Hughesd07986f2011-12-06 18:27:45 -08002568
Elliott Hughes81ff3182012-03-23 20:35:56 -07002569 // We can be called while an exception is pending. We need
Elliott Hughesd07986f2011-12-06 18:27:45 -08002570 // to preserve that across the method invocation.
Ian Rogers1f539342012-10-03 21:09:42 -07002571 SirtRef<Throwable> old_exception(soa.Self(), soa.Self()->GetException());
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002572 soa.Self()->ClearException();
Elliott Hughesd07986f2011-12-06 18:27:45 -08002573
2574 // Translate the method through the vtable, unless the debugger wants to suppress it.
Mathieu Chartier66f19252012-09-18 08:57:04 -07002575 AbstractMethod* m = pReq->method_;
Elliott Hughesd07986f2011-12-06 18:27:45 -08002576 if ((pReq->options_ & JDWP::INVOKE_NONVIRTUAL) == 0 && pReq->receiver_ != NULL) {
Mathieu Chartier66f19252012-09-18 08:57:04 -07002577 AbstractMethod* actual_method = pReq->class_->FindVirtualMethodForVirtualOrInterface(pReq->method_);
Elliott Hughes45651fd2012-02-21 15:48:20 -08002578 if (actual_method != m) {
2579 VLOG(jdwp) << "ExecuteMethod translated " << PrettyMethod(m) << " to " << PrettyMethod(actual_method);
2580 m = actual_method;
2581 }
Elliott Hughesd07986f2011-12-06 18:27:45 -08002582 }
Elliott Hughes45651fd2012-02-21 15:48:20 -08002583 VLOG(jdwp) << "ExecuteMethod " << PrettyMethod(m);
Elliott Hughesd07986f2011-12-06 18:27:45 -08002584 CHECK(m != NULL);
2585
2586 CHECK_EQ(sizeof(jvalue), sizeof(uint64_t));
2587
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002588 LOG(INFO) << "self=" << soa.Self() << " pReq->receiver_=" << pReq->receiver_ << " m=" << m
2589 << " #" << pReq->arg_count_ << " " << pReq->arg_values_;
2590 pReq->result_value = InvokeWithJValues(soa, pReq->receiver_, m,
2591 reinterpret_cast<JValue*>(pReq->arg_values_));
Elliott Hughesd07986f2011-12-06 18:27:45 -08002592
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002593 pReq->exception = gRegistry->Add(soa.Self()->GetException());
Elliott Hughesd07986f2011-12-06 18:27:45 -08002594 pReq->result_tag = BasicTagFromDescriptor(MethodHelper(m).GetShorty());
2595 if (pReq->exception != 0) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002596 Object* exc = soa.Self()->GetException();
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08002597 VLOG(jdwp) << " JDWP invocation returning with exception=" << exc << " " << PrettyTypeOf(exc);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002598 soa.Self()->ClearException();
Elliott Hughesf24d3ce2012-04-11 17:43:37 -07002599 pReq->result_value.SetJ(0);
Elliott Hughesd07986f2011-12-06 18:27:45 -08002600 } else if (pReq->result_tag == JDWP::JT_OBJECT) {
2601 /* if no exception thrown, examine object result more closely */
Elliott Hughesf24d3ce2012-04-11 17:43:37 -07002602 JDWP::JdwpTag new_tag = TagFromObject(pReq->result_value.GetL());
Elliott Hughesd07986f2011-12-06 18:27:45 -08002603 if (new_tag != pReq->result_tag) {
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08002604 VLOG(jdwp) << " JDWP promoted result from " << pReq->result_tag << " to " << new_tag;
Elliott Hughesd07986f2011-12-06 18:27:45 -08002605 pReq->result_tag = new_tag;
2606 }
2607
2608 /*
2609 * Register the object. We don't actually need an ObjectId yet,
2610 * but we do need to be sure that the GC won't move or discard the
2611 * object when we switch out of RUNNING. The ObjectId conversion
2612 * will add the object to the "do not touch" list.
2613 *
2614 * We can't use the "tracked allocation" mechanism here because
2615 * the object is going to be handed off to a different thread.
2616 */
Elliott Hughesf24d3ce2012-04-11 17:43:37 -07002617 gRegistry->Add(pReq->result_value.GetL());
Elliott Hughesd07986f2011-12-06 18:27:45 -08002618 }
2619
2620 if (old_exception.get() != NULL) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002621 soa.Self()->SetException(old_exception.get());
Elliott Hughesd07986f2011-12-06 18:27:45 -08002622 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002623}
2624
Elliott Hughesd07986f2011-12-06 18:27:45 -08002625/*
2626 * Register an object ID that might not have been registered previously.
2627 *
2628 * Normally this wouldn't happen -- the conversion to an ObjectId would
2629 * have added the object to the registry -- but in some cases (e.g.
2630 * throwing exceptions) we really want to do the registration late.
2631 */
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002632void Dbg::RegisterObjectId(JDWP::ObjectId id) {
Elliott Hughesd07986f2011-12-06 18:27:45 -08002633 gRegistry->Add(reinterpret_cast<Object*>(id));
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002634}
2635
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07002636/*
2637 * "buf" contains a full JDWP packet, possibly with multiple chunks. We
2638 * need to process each, accumulate the replies, and ship the whole thing
2639 * back.
2640 *
2641 * Returns "true" if we have a reply. The reply buffer is newly allocated,
2642 * and includes the chunk type/length, followed by the data.
2643 *
Elliott Hughes3d30d9b2011-12-07 17:35:48 -08002644 * OLD-TODO: we currently assume that the request and reply include a single
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07002645 * chunk. If this becomes inconvenient we will need to adapt.
2646 */
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002647bool Dbg::DdmHandlePacket(const uint8_t* buf, int dataLen, uint8_t** pReplyBuf, int* pReplyLen) {
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07002648 CHECK_GE(dataLen, 0);
2649
2650 Thread* self = Thread::Current();
2651 JNIEnv* env = self->GetJniEnv();
2652
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07002653 // Create a byte[] corresponding to 'buf'.
Elliott Hughes6a5bd492011-10-28 14:33:57 -07002654 ScopedLocalRef<jbyteArray> dataArray(env, env->NewByteArray(dataLen));
2655 if (dataArray.get() == NULL) {
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07002656 LOG(WARNING) << "byte[] allocation failed: " << dataLen;
2657 env->ExceptionClear();
2658 return false;
2659 }
Elliott Hughes6a5bd492011-10-28 14:33:57 -07002660 env->SetByteArrayRegion(dataArray.get(), 0, dataLen, reinterpret_cast<const jbyte*>(buf));
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07002661
2662 const int kChunkHdrLen = 8;
2663
2664 // Run through and find all chunks. [Currently just find the first.]
Elliott Hughes6a5bd492011-10-28 14:33:57 -07002665 ScopedByteArrayRO contents(env, dataArray.get());
Elliott Hughesf7c3b662011-10-27 12:04:56 -07002666 jint type = JDWP::Get4BE(reinterpret_cast<const uint8_t*>(&contents[0]));
2667 jint length = JDWP::Get4BE(reinterpret_cast<const uint8_t*>(&contents[4]));
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07002668 jint offset = kChunkHdrLen;
2669 if (offset + length > dataLen) {
2670 LOG(WARNING) << StringPrintf("bad chunk found (len=%u pktLen=%d)", length, dataLen);
2671 return false;
2672 }
2673
2674 // Call "private static Chunk dispatch(int type, byte[] data, int offset, int length)".
Elliott Hugheseac76672012-05-24 21:56:51 -07002675 ScopedLocalRef<jobject> chunk(env, env->CallStaticObjectMethod(WellKnownClasses::org_apache_harmony_dalvik_ddmc_DdmServer,
2676 WellKnownClasses::org_apache_harmony_dalvik_ddmc_DdmServer_dispatch,
2677 type, dataArray.get(), offset, length));
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07002678 if (env->ExceptionCheck()) {
2679 LOG(INFO) << StringPrintf("Exception thrown by dispatcher for 0x%08x", type);
2680 env->ExceptionDescribe();
2681 env->ExceptionClear();
2682 return false;
2683 }
2684
Elliott Hughes6a5bd492011-10-28 14:33:57 -07002685 if (chunk.get() == NULL) {
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07002686 return false;
2687 }
2688
2689 /*
2690 * Pull the pieces out of the chunk. We copy the results into a
2691 * newly-allocated buffer that the caller can free. We don't want to
2692 * continue using the Chunk object because nothing has a reference to it.
2693 *
2694 * We could avoid this by returning type/data/offset/length and having
2695 * the caller be aware of the object lifetime issues, but that
Elliott Hughes81ff3182012-03-23 20:35:56 -07002696 * integrates the JDWP code more tightly into the rest of the runtime, and doesn't work
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07002697 * if we have responses for multiple chunks.
2698 *
2699 * So we're pretty much stuck with copying data around multiple times.
2700 */
Elliott Hugheseac76672012-05-24 21:56:51 -07002701 ScopedLocalRef<jbyteArray> replyData(env, reinterpret_cast<jbyteArray>(env->GetObjectField(chunk.get(), WellKnownClasses::org_apache_harmony_dalvik_ddmc_Chunk_data)));
2702 length = env->GetIntField(chunk.get(), WellKnownClasses::org_apache_harmony_dalvik_ddmc_Chunk_length);
2703 offset = env->GetIntField(chunk.get(), WellKnownClasses::org_apache_harmony_dalvik_ddmc_Chunk_offset);
2704 type = env->GetIntField(chunk.get(), WellKnownClasses::org_apache_harmony_dalvik_ddmc_Chunk_type);
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07002705
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08002706 VLOG(jdwp) << StringPrintf("DDM reply: type=0x%08x data=%p offset=%d length=%d", type, replyData.get(), offset, length);
Elliott Hughes6a5bd492011-10-28 14:33:57 -07002707 if (length == 0 || replyData.get() == NULL) {
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07002708 return false;
2709 }
2710
Elliott Hughes6a5bd492011-10-28 14:33:57 -07002711 jsize replyLength = env->GetArrayLength(replyData.get());
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07002712 if (offset + length > replyLength) {
2713 LOG(WARNING) << StringPrintf("chunk off=%d len=%d exceeds reply array len %d", offset, length, replyLength);
2714 return false;
2715 }
2716
2717 uint8_t* reply = new uint8_t[length + kChunkHdrLen];
2718 if (reply == NULL) {
2719 LOG(WARNING) << "malloc failed: " << (length + kChunkHdrLen);
2720 return false;
2721 }
Elliott Hughesf7c3b662011-10-27 12:04:56 -07002722 JDWP::Set4BE(reply + 0, type);
2723 JDWP::Set4BE(reply + 4, length);
Elliott Hughes6a5bd492011-10-28 14:33:57 -07002724 env->GetByteArrayRegion(replyData.get(), offset, length, reinterpret_cast<jbyte*>(reply + kChunkHdrLen));
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07002725
2726 *pReplyBuf = reply;
2727 *pReplyLen = length + kChunkHdrLen;
2728
Elliott Hughesba8eee12012-01-24 20:25:24 -08002729 VLOG(jdwp) << StringPrintf("dvmHandleDdm returning type=%.4s buf=%p len=%d", reinterpret_cast<char*>(reply), reply, length);
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07002730 return true;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002731}
2732
Elliott Hughesa2155262011-11-16 16:26:58 -08002733void Dbg::DdmBroadcast(bool connect) {
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08002734 VLOG(jdwp) << "Broadcasting DDM " << (connect ? "connect" : "disconnect") << "...";
Elliott Hughes47fce012011-10-25 18:37:19 -07002735
2736 Thread* self = Thread::Current();
Ian Rogers50b35e22012-10-04 10:09:15 -07002737 if (self->GetState() != kRunnable) {
2738 LOG(ERROR) << "DDM broadcast in thread state " << self->GetState();
2739 /* try anyway? */
Elliott Hughes47fce012011-10-25 18:37:19 -07002740 }
2741
2742 JNIEnv* env = self->GetJniEnv();
Elliott Hughes47fce012011-10-25 18:37:19 -07002743 jint event = connect ? 1 /*DdmServer.CONNECTED*/ : 2 /*DdmServer.DISCONNECTED*/;
Elliott Hugheseac76672012-05-24 21:56:51 -07002744 env->CallStaticVoidMethod(WellKnownClasses::org_apache_harmony_dalvik_ddmc_DdmServer,
2745 WellKnownClasses::org_apache_harmony_dalvik_ddmc_DdmServer_broadcast,
2746 event);
Elliott Hughes47fce012011-10-25 18:37:19 -07002747 if (env->ExceptionCheck()) {
2748 LOG(ERROR) << "DdmServer.broadcast " << event << " failed";
2749 env->ExceptionDescribe();
2750 env->ExceptionClear();
2751 }
2752}
2753
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002754void Dbg::DdmConnected() {
Elliott Hughesa2155262011-11-16 16:26:58 -08002755 Dbg::DdmBroadcast(true);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002756}
2757
2758void Dbg::DdmDisconnected() {
Elliott Hughesa2155262011-11-16 16:26:58 -08002759 Dbg::DdmBroadcast(false);
Elliott Hughes47fce012011-10-25 18:37:19 -07002760 gDdmThreadNotification = false;
2761}
2762
2763/*
Elliott Hughes82188472011-11-07 18:11:48 -08002764 * Send a notification when a thread starts, stops, or changes its name.
Elliott Hughes47fce012011-10-25 18:37:19 -07002765 *
2766 * Because we broadcast the full set of threads when the notifications are
2767 * first enabled, it's possible for "thread" to be actively executing.
2768 */
Elliott Hughes82188472011-11-07 18:11:48 -08002769void Dbg::DdmSendThreadNotification(Thread* t, uint32_t type) {
Elliott Hughes47fce012011-10-25 18:37:19 -07002770 if (!gDdmThreadNotification) {
2771 return;
2772 }
2773
Elliott Hughes82188472011-11-07 18:11:48 -08002774 if (type == CHUNK_TYPE("THDE")) {
Elliott Hughes47fce012011-10-25 18:37:19 -07002775 uint8_t buf[4];
Elliott Hughesf7c3b662011-10-27 12:04:56 -07002776 JDWP::Set4BE(&buf[0], t->GetThinLockId());
Elliott Hughes47fce012011-10-25 18:37:19 -07002777 Dbg::DdmSendChunk(CHUNK_TYPE("THDE"), 4, buf);
Elliott Hughes82188472011-11-07 18:11:48 -08002778 } else {
2779 CHECK(type == CHUNK_TYPE("THCR") || type == CHUNK_TYPE("THNM")) << type;
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002780 ScopedObjectAccessUnchecked soa(Thread::Current());
Ian Rogers1f539342012-10-03 21:09:42 -07002781 SirtRef<String> name(soa.Self(), t->GetThreadName(soa));
Elliott Hughes82188472011-11-07 18:11:48 -08002782 size_t char_count = (name.get() != NULL) ? name->GetLength() : 0;
jeffhao725a9572012-11-13 18:20:12 -08002783 const jchar* chars = (name.get() != NULL) ? name->GetCharArray()->GetData() : NULL;
Elliott Hughes82188472011-11-07 18:11:48 -08002784
Elliott Hughes21f32d72011-11-09 17:44:13 -08002785 std::vector<uint8_t> bytes;
Elliott Hughes545a0642011-11-08 19:10:03 -08002786 JDWP::Append4BE(bytes, t->GetThinLockId());
2787 JDWP::AppendUtf16BE(bytes, chars, char_count);
Elliott Hughes21f32d72011-11-09 17:44:13 -08002788 CHECK_EQ(bytes.size(), char_count*2 + sizeof(uint32_t)*2);
2789 Dbg::DdmSendChunk(type, bytes);
Elliott Hughes47fce012011-10-25 18:37:19 -07002790 }
2791}
2792
Elliott Hughes47fce012011-10-25 18:37:19 -07002793void Dbg::DdmSetThreadNotification(bool enable) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002794 // Enable/disable thread notifications.
Elliott Hughes47fce012011-10-25 18:37:19 -07002795 gDdmThreadNotification = enable;
2796 if (enable) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002797 // Suspend the VM then post thread start notifications for all threads. Threads attaching will
2798 // see a suspension in progress and block until that ends. They then post their own start
2799 // notification.
2800 SuspendVM();
2801 std::list<Thread*> threads;
Ian Rogers50b35e22012-10-04 10:09:15 -07002802 Thread* self = Thread::Current();
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002803 {
Ian Rogers50b35e22012-10-04 10:09:15 -07002804 MutexLock mu(self, *Locks::thread_list_lock_);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002805 threads = Runtime::Current()->GetThreadList()->GetList();
2806 }
2807 {
Ian Rogers50b35e22012-10-04 10:09:15 -07002808 ScopedObjectAccess soa(self);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002809 typedef std::list<Thread*>::const_iterator It; // TODO: C++0x auto
2810 for (It it = threads.begin(), end = threads.end(); it != end; ++it) {
2811 Dbg::DdmSendThreadNotification(*it, CHUNK_TYPE("THCR"));
2812 }
2813 }
2814 ResumeVM();
Elliott Hughes47fce012011-10-25 18:37:19 -07002815 }
2816}
2817
Elliott Hughesa2155262011-11-16 16:26:58 -08002818void Dbg::PostThreadStartOrStop(Thread* t, uint32_t type) {
Elliott Hughesc0f09332012-03-26 13:27:06 -07002819 if (IsDebuggerActive()) {
Mathieu Chartierdbe6f462012-09-25 16:54:50 -07002820 ScopedObjectAccessUnchecked soa(Thread::Current());
Ian Rogerscfaa4552012-11-26 21:00:08 -08002821 JDWP::ObjectId id = gRegistry->Add(t->GetPeer());
Elliott Hughes82188472011-11-07 18:11:48 -08002822 gJdwpState->PostThreadChange(id, type == CHUNK_TYPE("THCR"));
Elliott Hughesc0f09332012-03-26 13:27:06 -07002823 // If this thread's just joined the party while we're already debugging, make sure it knows
2824 // to give us updates when it's running.
2825 t->SetDebuggerUpdatesEnabled(true);
Elliott Hughes47fce012011-10-25 18:37:19 -07002826 }
Elliott Hughes82188472011-11-07 18:11:48 -08002827 Dbg::DdmSendThreadNotification(t, type);
Elliott Hughes47fce012011-10-25 18:37:19 -07002828}
2829
2830void Dbg::PostThreadStart(Thread* t) {
Elliott Hughesa2155262011-11-16 16:26:58 -08002831 Dbg::PostThreadStartOrStop(t, CHUNK_TYPE("THCR"));
Elliott Hughes47fce012011-10-25 18:37:19 -07002832}
2833
2834void Dbg::PostThreadDeath(Thread* t) {
Elliott Hughesa2155262011-11-16 16:26:58 -08002835 Dbg::PostThreadStartOrStop(t, CHUNK_TYPE("THDE"));
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002836}
2837
Elliott Hughes82188472011-11-07 18:11:48 -08002838void Dbg::DdmSendChunk(uint32_t type, size_t byte_count, const uint8_t* buf) {
Elliott Hughes3bb81562011-10-21 18:52:59 -07002839 CHECK(buf != NULL);
2840 iovec vec[1];
2841 vec[0].iov_base = reinterpret_cast<void*>(const_cast<uint8_t*>(buf));
2842 vec[0].iov_len = byte_count;
2843 Dbg::DdmSendChunkV(type, vec, 1);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002844}
2845
Elliott Hughes21f32d72011-11-09 17:44:13 -08002846void Dbg::DdmSendChunk(uint32_t type, const std::vector<uint8_t>& bytes) {
2847 DdmSendChunk(type, bytes.size(), &bytes[0]);
2848}
2849
Elliott Hughescccd84f2011-12-05 16:51:54 -08002850void Dbg::DdmSendChunkV(uint32_t type, const struct iovec* iov, int iov_count) {
Elliott Hughes3bb81562011-10-21 18:52:59 -07002851 if (gJdwpState == NULL) {
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08002852 VLOG(jdwp) << "Debugger thread not active, ignoring DDM send: " << type;
Elliott Hughes3bb81562011-10-21 18:52:59 -07002853 } else {
Elliott Hughescccd84f2011-12-05 16:51:54 -08002854 gJdwpState->DdmSendChunkV(type, iov, iov_count);
Elliott Hughes3bb81562011-10-21 18:52:59 -07002855 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002856}
2857
Elliott Hughes767a1472011-10-26 18:49:02 -07002858int Dbg::DdmHandleHpifChunk(HpifWhen when) {
2859 if (when == HPIF_WHEN_NOW) {
Elliott Hughes7162ad92011-10-27 14:08:42 -07002860 DdmSendHeapInfo(when);
Elliott Hughes767a1472011-10-26 18:49:02 -07002861 return true;
2862 }
2863
2864 if (when != HPIF_WHEN_NEVER && when != HPIF_WHEN_NEXT_GC && when != HPIF_WHEN_EVERY_GC) {
2865 LOG(ERROR) << "invalid HpifWhen value: " << static_cast<int>(when);
2866 return false;
2867 }
2868
2869 gDdmHpifWhen = when;
2870 return true;
2871}
2872
2873bool Dbg::DdmHandleHpsgNhsgChunk(Dbg::HpsgWhen when, Dbg::HpsgWhat what, bool native) {
2874 if (when != HPSG_WHEN_NEVER && when != HPSG_WHEN_EVERY_GC) {
2875 LOG(ERROR) << "invalid HpsgWhen value: " << static_cast<int>(when);
2876 return false;
2877 }
2878
2879 if (what != HPSG_WHAT_MERGED_OBJECTS && what != HPSG_WHAT_DISTINCT_OBJECTS) {
2880 LOG(ERROR) << "invalid HpsgWhat value: " << static_cast<int>(what);
2881 return false;
2882 }
2883
2884 if (native) {
2885 gDdmNhsgWhen = when;
2886 gDdmNhsgWhat = what;
2887 } else {
2888 gDdmHpsgWhen = when;
2889 gDdmHpsgWhat = what;
2890 }
2891 return true;
2892}
2893
Elliott Hughes7162ad92011-10-27 14:08:42 -07002894void Dbg::DdmSendHeapInfo(HpifWhen reason) {
2895 // If there's a one-shot 'when', reset it.
2896 if (reason == gDdmHpifWhen) {
2897 if (gDdmHpifWhen == HPIF_WHEN_NEXT_GC) {
2898 gDdmHpifWhen = HPIF_WHEN_NEVER;
2899 }
2900 }
2901
2902 /*
2903 * Chunk HPIF (client --> server)
2904 *
2905 * Heap Info. General information about the heap,
2906 * suitable for a summary display.
2907 *
2908 * [u4]: number of heaps
2909 *
2910 * For each heap:
2911 * [u4]: heap ID
2912 * [u8]: timestamp in ms since Unix epoch
2913 * [u1]: capture reason (same as 'when' value from server)
2914 * [u4]: max heap size in bytes (-Xmx)
2915 * [u4]: current heap size in bytes
2916 * [u4]: current number of bytes allocated
2917 * [u4]: current number of objects allocated
2918 */
2919 uint8_t heap_count = 1;
Elliott Hughesb3bd5f02012-03-08 21:05:27 -08002920 Heap* heap = Runtime::Current()->GetHeap();
Elliott Hughes21f32d72011-11-09 17:44:13 -08002921 std::vector<uint8_t> bytes;
Elliott Hughes545a0642011-11-08 19:10:03 -08002922 JDWP::Append4BE(bytes, heap_count);
2923 JDWP::Append4BE(bytes, 1); // Heap id (bogus; we only have one heap).
2924 JDWP::Append8BE(bytes, MilliTime());
2925 JDWP::Append1BE(bytes, reason);
Elliott Hughesb3bd5f02012-03-08 21:05:27 -08002926 JDWP::Append4BE(bytes, heap->GetMaxMemory()); // Max allowed heap size in bytes.
2927 JDWP::Append4BE(bytes, heap->GetTotalMemory()); // Current heap size in bytes.
2928 JDWP::Append4BE(bytes, heap->GetBytesAllocated());
2929 JDWP::Append4BE(bytes, heap->GetObjectsAllocated());
Elliott Hughes21f32d72011-11-09 17:44:13 -08002930 CHECK_EQ(bytes.size(), 4U + (heap_count * (4 + 8 + 1 + 4 + 4 + 4 + 4)));
2931 Dbg::DdmSendChunk(CHUNK_TYPE("HPIF"), bytes);
Elliott Hughes767a1472011-10-26 18:49:02 -07002932}
2933
Elliott Hughes6a5bd492011-10-28 14:33:57 -07002934enum HpsgSolidity {
2935 SOLIDITY_FREE = 0,
2936 SOLIDITY_HARD = 1,
2937 SOLIDITY_SOFT = 2,
2938 SOLIDITY_WEAK = 3,
2939 SOLIDITY_PHANTOM = 4,
2940 SOLIDITY_FINALIZABLE = 5,
2941 SOLIDITY_SWEEP = 6,
2942};
2943
2944enum HpsgKind {
2945 KIND_OBJECT = 0,
2946 KIND_CLASS_OBJECT = 1,
2947 KIND_ARRAY_1 = 2,
2948 KIND_ARRAY_2 = 3,
2949 KIND_ARRAY_4 = 4,
2950 KIND_ARRAY_8 = 5,
2951 KIND_UNKNOWN = 6,
2952 KIND_NATIVE = 7,
2953};
2954
2955#define HPSG_PARTIAL (1<<7)
2956#define HPSG_STATE(solidity, kind) ((uint8_t)((((kind) & 0x7) << 3) | ((solidity) & 0x7)))
2957
Ian Rogers30fab402012-01-23 15:43:46 -08002958class HeapChunkContext {
2959 public:
Elliott Hughes6a5bd492011-10-28 14:33:57 -07002960 // Maximum chunk size. Obtain this from the formula:
2961 // (((maximum_heap_size / ALLOCATION_UNIT_SIZE) + 255) / 256) * 2
2962 HeapChunkContext(bool merge, bool native)
Ian Rogers30fab402012-01-23 15:43:46 -08002963 : buf_(16384 - 16),
2964 type_(0),
2965 merge_(merge) {
Elliott Hughes6a5bd492011-10-28 14:33:57 -07002966 Reset();
2967 if (native) {
Ian Rogers30fab402012-01-23 15:43:46 -08002968 type_ = CHUNK_TYPE("NHSG");
Elliott Hughes6a5bd492011-10-28 14:33:57 -07002969 } else {
Ian Rogers30fab402012-01-23 15:43:46 -08002970 type_ = merge ? CHUNK_TYPE("HPSG") : CHUNK_TYPE("HPSO");
Elliott Hughes6a5bd492011-10-28 14:33:57 -07002971 }
2972 }
2973
2974 ~HeapChunkContext() {
Ian Rogers30fab402012-01-23 15:43:46 -08002975 if (p_ > &buf_[0]) {
Elliott Hughes6a5bd492011-10-28 14:33:57 -07002976 Flush();
2977 }
2978 }
2979
2980 void EnsureHeader(const void* chunk_ptr) {
Ian Rogers30fab402012-01-23 15:43:46 -08002981 if (!needHeader_) {
Elliott Hughes6a5bd492011-10-28 14:33:57 -07002982 return;
2983 }
2984
2985 // Start a new HPSx chunk.
Ian Rogers30fab402012-01-23 15:43:46 -08002986 JDWP::Write4BE(&p_, 1); // Heap id (bogus; we only have one heap).
2987 JDWP::Write1BE(&p_, 8); // Size of allocation unit, in bytes.
Elliott Hughes6a5bd492011-10-28 14:33:57 -07002988
Ian Rogers30fab402012-01-23 15:43:46 -08002989 JDWP::Write4BE(&p_, reinterpret_cast<uintptr_t>(chunk_ptr)); // virtual address of segment start.
2990 JDWP::Write4BE(&p_, 0); // offset of this piece (relative to the virtual address).
Elliott Hughes6a5bd492011-10-28 14:33:57 -07002991 // [u4]: length of piece, in allocation units
2992 // We won't know this until we're done, so save the offset and stuff in a dummy value.
Ian Rogers30fab402012-01-23 15:43:46 -08002993 pieceLenField_ = p_;
2994 JDWP::Write4BE(&p_, 0x55555555);
2995 needHeader_ = false;
Elliott Hughes6a5bd492011-10-28 14:33:57 -07002996 }
2997
Ian Rogersb726dcb2012-09-05 08:57:23 -07002998 void Flush() SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Elliott Hughes6a5bd492011-10-28 14:33:57 -07002999 // Patch the "length of piece" field.
Ian Rogers30fab402012-01-23 15:43:46 -08003000 CHECK_LE(&buf_[0], pieceLenField_);
3001 CHECK_LE(pieceLenField_, p_);
3002 JDWP::Set4BE(pieceLenField_, totalAllocationUnits_);
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003003
Ian Rogers30fab402012-01-23 15:43:46 -08003004 Dbg::DdmSendChunk(type_, p_ - &buf_[0], &buf_[0]);
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003005 Reset();
3006 }
3007
Ian Rogers00f7d0e2012-07-19 15:28:27 -07003008 static void HeapChunkCallback(void* start, void* end, size_t used_bytes, void* arg)
Ian Rogersb726dcb2012-09-05 08:57:23 -07003009 SHARED_LOCKS_REQUIRED(Locks::heap_bitmap_lock_,
3010 Locks::mutator_lock_) {
Ian Rogers30fab402012-01-23 15:43:46 -08003011 reinterpret_cast<HeapChunkContext*>(arg)->HeapChunkCallback(start, end, used_bytes);
Elliott Hughesa2155262011-11-16 16:26:58 -08003012 }
3013
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003014 private:
Elliott Hughesa2155262011-11-16 16:26:58 -08003015 enum { ALLOCATION_UNIT_SIZE = 8 };
3016
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003017 void Reset() {
Ian Rogers30fab402012-01-23 15:43:46 -08003018 p_ = &buf_[0];
Ian Rogers15bf2d32012-08-28 17:33:04 -07003019 startOfNextMemoryChunk_ = NULL;
Ian Rogers30fab402012-01-23 15:43:46 -08003020 totalAllocationUnits_ = 0;
3021 needHeader_ = true;
3022 pieceLenField_ = NULL;
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003023 }
3024
Ian Rogers00f7d0e2012-07-19 15:28:27 -07003025 void HeapChunkCallback(void* start, void* /*end*/, size_t used_bytes)
Ian Rogersb726dcb2012-09-05 08:57:23 -07003026 SHARED_LOCKS_REQUIRED(Locks::heap_bitmap_lock_,
3027 Locks::mutator_lock_) {
Ian Rogers30fab402012-01-23 15:43:46 -08003028 // Note: heap call backs cannot manipulate the heap upon which they are crawling, care is taken
3029 // in the following code not to allocate memory, by ensuring buf_ is of the correct size
Ian Rogers15bf2d32012-08-28 17:33:04 -07003030 if (used_bytes == 0) {
3031 if (start == NULL) {
3032 // Reset for start of new heap.
3033 startOfNextMemoryChunk_ = NULL;
3034 Flush();
3035 }
3036 // Only process in use memory so that free region information
3037 // also includes dlmalloc book keeping.
Elliott Hughesa2155262011-11-16 16:26:58 -08003038 return;
Elliott Hughesa2155262011-11-16 16:26:58 -08003039 }
3040
Ian Rogers15bf2d32012-08-28 17:33:04 -07003041 /* If we're looking at the native heap, we'll just return
3042 * (SOLIDITY_HARD, KIND_NATIVE) for all allocated chunks
3043 */
3044 bool native = type_ == CHUNK_TYPE("NHSG");
3045
3046 if (startOfNextMemoryChunk_ != NULL) {
3047 // Transmit any pending free memory. Native free memory of
3048 // over kMaxFreeLen could be because of the use of mmaps, so
3049 // don't report. If not free memory then start a new segment.
3050 bool flush = true;
3051 if (start > startOfNextMemoryChunk_) {
3052 const size_t kMaxFreeLen = 2 * kPageSize;
3053 void* freeStart = startOfNextMemoryChunk_;
3054 void* freeEnd = start;
3055 size_t freeLen = (char*)freeEnd - (char*)freeStart;
3056 if (!native || freeLen < kMaxFreeLen) {
3057 AppendChunk(HPSG_STATE(SOLIDITY_FREE, 0), freeStart, freeLen);
3058 flush = false;
3059 }
3060 }
3061 if (flush) {
3062 startOfNextMemoryChunk_ = NULL;
3063 Flush();
3064 }
3065 }
3066 const Object *obj = (const Object *)start;
Elliott Hughesa2155262011-11-16 16:26:58 -08003067
3068 // Determine the type of this chunk.
3069 // OLD-TODO: if context.merge, see if this chunk is different from the last chunk.
3070 // If it's the same, we should combine them.
Ian Rogers15bf2d32012-08-28 17:33:04 -07003071 uint8_t state = ExamineObject(obj, native);
3072 // dlmalloc's chunk header is 2 * sizeof(size_t), but if the previous chunk is in use for an
3073 // allocation then the first sizeof(size_t) may belong to it.
3074 const size_t dlMallocOverhead = sizeof(size_t);
3075 AppendChunk(state, start, used_bytes + dlMallocOverhead);
3076 startOfNextMemoryChunk_ = (char*)start + used_bytes + dlMallocOverhead;
3077 }
Elliott Hughesa2155262011-11-16 16:26:58 -08003078
Ian Rogers15bf2d32012-08-28 17:33:04 -07003079 void AppendChunk(uint8_t state, void* ptr, size_t length)
Ian Rogersb726dcb2012-09-05 08:57:23 -07003080 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Ian Rogers15bf2d32012-08-28 17:33:04 -07003081 // Make sure there's enough room left in the buffer.
3082 // We need to use two bytes for every fractional 256 allocation units used by the chunk plus
3083 // 17 bytes for any header.
3084 size_t needed = (((length/ALLOCATION_UNIT_SIZE + 255) / 256) * 2) + 17;
3085 size_t bytesLeft = buf_.size() - (size_t)(p_ - &buf_[0]);
3086 if (bytesLeft < needed) {
3087 Flush();
3088 }
3089
3090 bytesLeft = buf_.size() - (size_t)(p_ - &buf_[0]);
3091 if (bytesLeft < needed) {
3092 LOG(WARNING) << "Chunk is too big to transmit (chunk_len=" << length << ", "
3093 << needed << " bytes)";
3094 return;
3095 }
3096 EnsureHeader(ptr);
Elliott Hughesa2155262011-11-16 16:26:58 -08003097 // Write out the chunk description.
Ian Rogers15bf2d32012-08-28 17:33:04 -07003098 length /= ALLOCATION_UNIT_SIZE; // Convert to allocation units.
3099 totalAllocationUnits_ += length;
3100 while (length > 256) {
Ian Rogers30fab402012-01-23 15:43:46 -08003101 *p_++ = state | HPSG_PARTIAL;
3102 *p_++ = 255; // length - 1
Ian Rogers15bf2d32012-08-28 17:33:04 -07003103 length -= 256;
Elliott Hughesa2155262011-11-16 16:26:58 -08003104 }
Ian Rogers30fab402012-01-23 15:43:46 -08003105 *p_++ = state;
Ian Rogers15bf2d32012-08-28 17:33:04 -07003106 *p_++ = length - 1;
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003107 }
3108
Ian Rogers5bfa60f2012-09-02 21:17:56 -07003109 uint8_t ExamineObject(const Object* o, bool is_native_heap)
Ian Rogersb726dcb2012-09-05 08:57:23 -07003110 SHARED_LOCKS_REQUIRED(Locks::heap_bitmap_lock_) {
Elliott Hughesa2155262011-11-16 16:26:58 -08003111 if (o == NULL) {
3112 return HPSG_STATE(SOLIDITY_FREE, 0);
3113 }
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003114
Elliott Hughesa2155262011-11-16 16:26:58 -08003115 // It's an allocated chunk. Figure out what it is.
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003116
Elliott Hughesa2155262011-11-16 16:26:58 -08003117 // If we're looking at the native heap, we'll just return
3118 // (SOLIDITY_HARD, KIND_NATIVE) for all allocated chunks.
Ian Rogers00f7d0e2012-07-19 15:28:27 -07003119 if (is_native_heap) {
Elliott Hughesa2155262011-11-16 16:26:58 -08003120 return HPSG_STATE(SOLIDITY_HARD, KIND_NATIVE);
3121 }
3122
Ian Rogers5bfa60f2012-09-02 21:17:56 -07003123 if (!Runtime::Current()->GetHeap()->IsLiveObjectLocked(o)) {
Ian Rogers15bf2d32012-08-28 17:33:04 -07003124 return HPSG_STATE(SOLIDITY_HARD, KIND_NATIVE);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07003125 }
3126
Elliott Hughesa2155262011-11-16 16:26:58 -08003127 Class* c = o->GetClass();
3128 if (c == NULL) {
3129 // The object was probably just created but hasn't been initialized yet.
3130 return HPSG_STATE(SOLIDITY_HARD, KIND_OBJECT);
3131 }
3132
Elliott Hughesb3bd5f02012-03-08 21:05:27 -08003133 if (!Runtime::Current()->GetHeap()->IsHeapAddress(c)) {
Ian Rogers15bf2d32012-08-28 17:33:04 -07003134 LOG(ERROR) << "Invalid class for managed heap object: " << o << " " << c;
Elliott Hughesa2155262011-11-16 16:26:58 -08003135 return HPSG_STATE(SOLIDITY_HARD, KIND_UNKNOWN);
3136 }
3137
3138 if (c->IsClassClass()) {
3139 return HPSG_STATE(SOLIDITY_HARD, KIND_CLASS_OBJECT);
3140 }
3141
3142 if (c->IsArrayClass()) {
3143 if (o->IsObjectArray()) {
3144 return HPSG_STATE(SOLIDITY_HARD, KIND_ARRAY_4);
3145 }
3146 switch (c->GetComponentSize()) {
3147 case 1: return HPSG_STATE(SOLIDITY_HARD, KIND_ARRAY_1);
3148 case 2: return HPSG_STATE(SOLIDITY_HARD, KIND_ARRAY_2);
3149 case 4: return HPSG_STATE(SOLIDITY_HARD, KIND_ARRAY_4);
3150 case 8: return HPSG_STATE(SOLIDITY_HARD, KIND_ARRAY_8);
3151 }
3152 }
3153
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003154 return HPSG_STATE(SOLIDITY_HARD, KIND_OBJECT);
3155 }
3156
Ian Rogers30fab402012-01-23 15:43:46 -08003157 std::vector<uint8_t> buf_;
3158 uint8_t* p_;
3159 uint8_t* pieceLenField_;
Ian Rogers15bf2d32012-08-28 17:33:04 -07003160 void* startOfNextMemoryChunk_;
Ian Rogers30fab402012-01-23 15:43:46 -08003161 size_t totalAllocationUnits_;
3162 uint32_t type_;
3163 bool merge_;
3164 bool needHeader_;
3165
Elliott Hughesa2155262011-11-16 16:26:58 -08003166 DISALLOW_COPY_AND_ASSIGN(HeapChunkContext);
3167};
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003168
3169void Dbg::DdmSendHeapSegments(bool native) {
3170 Dbg::HpsgWhen when;
3171 Dbg::HpsgWhat what;
3172 if (!native) {
3173 when = gDdmHpsgWhen;
3174 what = gDdmHpsgWhat;
3175 } else {
3176 when = gDdmNhsgWhen;
3177 what = gDdmNhsgWhat;
3178 }
3179 if (when == HPSG_WHEN_NEVER) {
3180 return;
3181 }
3182
3183 // Figure out what kind of chunks we'll be sending.
3184 CHECK(what == HPSG_WHAT_MERGED_OBJECTS || what == HPSG_WHAT_DISTINCT_OBJECTS) << static_cast<int>(what);
3185
3186 // First, send a heap start chunk.
3187 uint8_t heap_id[4];
3188 JDWP::Set4BE(&heap_id[0], 1); // Heap id (bogus; we only have one heap).
3189 Dbg::DdmSendChunk(native ? CHUNK_TYPE("NHST") : CHUNK_TYPE("HPST"), sizeof(heap_id), heap_id);
3190
3191 // Send a series of heap segment chunks.
Elliott Hughesa2155262011-11-16 16:26:58 -08003192 HeapChunkContext context((what == HPSG_WHAT_MERGED_OBJECTS), native);
3193 if (native) {
Ian Rogers30fab402012-01-23 15:43:46 -08003194 // TODO: enable when bionic has moved to dlmalloc 2.8.5
3195 // dlmalloc_inspect_all(HeapChunkContext::HeapChunkCallback, &context);
3196 UNIMPLEMENTED(WARNING) << "Native heap send heap segments";
Elliott Hughesa2155262011-11-16 16:26:58 -08003197 } else {
Elliott Hughesb3bd5f02012-03-08 21:05:27 -08003198 Heap* heap = Runtime::Current()->GetHeap();
Mathieu Chartierfd678be2012-08-30 14:50:54 -07003199 const Spaces& spaces = heap->GetSpaces();
Ian Rogers50b35e22012-10-04 10:09:15 -07003200 Thread* self = Thread::Current();
Mathieu Chartierfd678be2012-08-30 14:50:54 -07003201 for (Spaces::const_iterator cur = spaces.begin(); cur != spaces.end(); ++cur) {
Mathieu Chartierb062fdd2012-07-03 09:51:48 -07003202 if ((*cur)->IsAllocSpace()) {
Ian Rogers50b35e22012-10-04 10:09:15 -07003203 ReaderMutexLock mu(self, *Locks::heap_bitmap_lock_);
Mathieu Chartierb062fdd2012-07-03 09:51:48 -07003204 (*cur)->AsAllocSpace()->Walk(HeapChunkContext::HeapChunkCallback, &context);
3205 }
3206 }
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -07003207 // Walk the large objects, these are not in the AllocSpace.
3208 heap->GetLargeObjectsSpace()->Walk(HeapChunkContext::HeapChunkCallback, &context);
Elliott Hughesa2155262011-11-16 16:26:58 -08003209 }
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003210
3211 // Finally, send a heap end chunk.
3212 Dbg::DdmSendChunk(native ? CHUNK_TYPE("NHEN") : CHUNK_TYPE("HPEN"), sizeof(heap_id), heap_id);
Elliott Hughes767a1472011-10-26 18:49:02 -07003213}
3214
Elliott Hughes545a0642011-11-08 19:10:03 -08003215void Dbg::SetAllocTrackingEnabled(bool enabled) {
Ian Rogers50b35e22012-10-04 10:09:15 -07003216 MutexLock mu(Thread::Current(), gAllocTrackerLock);
Elliott Hughes545a0642011-11-08 19:10:03 -08003217 if (enabled) {
3218 if (recent_allocation_records_ == NULL) {
3219 LOG(INFO) << "Enabling alloc tracker (" << kNumAllocRecords << " entries, "
3220 << kMaxAllocRecordStackDepth << " frames --> "
3221 << (sizeof(AllocRecord) * kNumAllocRecords) << " bytes)";
3222 gAllocRecordHead = gAllocRecordCount = 0;
3223 recent_allocation_records_ = new AllocRecord[kNumAllocRecords];
3224 CHECK(recent_allocation_records_ != NULL);
3225 }
3226 } else {
3227 delete[] recent_allocation_records_;
3228 recent_allocation_records_ = NULL;
3229 }
3230}
3231
Ian Rogers0399dde2012-06-06 17:09:28 -07003232struct AllocRecordStackVisitor : public StackVisitor {
3233 AllocRecordStackVisitor(const ManagedStack* stack,
Ian Rogers306057f2012-11-26 12:45:53 -08003234 const std::deque<InstrumentationStackFrame>* instrumentation_stack,
3235 AllocRecord* record)
Ian Rogersb726dcb2012-09-05 08:57:23 -07003236 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_)
jeffhao725a9572012-11-13 18:20:12 -08003237 : StackVisitor(stack, instrumentation_stack, NULL), record(record), depth(0) {}
Elliott Hughes545a0642011-11-08 19:10:03 -08003238
Ian Rogers00f7d0e2012-07-19 15:28:27 -07003239 // TODO: Enable annotalysis. We know lock is held in constructor, but abstraction confuses
3240 // annotalysis.
3241 bool VisitFrame() NO_THREAD_SAFETY_ANALYSIS {
Elliott Hughes545a0642011-11-08 19:10:03 -08003242 if (depth >= kMaxAllocRecordStackDepth) {
Elliott Hughes530fa002012-03-12 11:44:49 -07003243 return false;
Elliott Hughes545a0642011-11-08 19:10:03 -08003244 }
Mathieu Chartier66f19252012-09-18 08:57:04 -07003245 AbstractMethod* m = GetMethod();
Ian Rogers0399dde2012-06-06 17:09:28 -07003246 if (!m->IsRuntimeMethod()) {
3247 record->stack[depth].method = m;
3248 record->stack[depth].dex_pc = GetDexPc();
Elliott Hughes530fa002012-03-12 11:44:49 -07003249 ++depth;
Elliott Hughes545a0642011-11-08 19:10:03 -08003250 }
Elliott Hughes530fa002012-03-12 11:44:49 -07003251 return true;
Elliott Hughes545a0642011-11-08 19:10:03 -08003252 }
3253
3254 ~AllocRecordStackVisitor() {
3255 // Clear out any unused stack trace elements.
3256 for (; depth < kMaxAllocRecordStackDepth; ++depth) {
3257 record->stack[depth].method = NULL;
Ian Rogers0399dde2012-06-06 17:09:28 -07003258 record->stack[depth].dex_pc = 0;
Elliott Hughes545a0642011-11-08 19:10:03 -08003259 }
3260 }
3261
3262 AllocRecord* record;
3263 size_t depth;
3264};
3265
3266void Dbg::RecordAllocation(Class* type, size_t byte_count) {
3267 Thread* self = Thread::Current();
3268 CHECK(self != NULL);
3269
Ian Rogers50b35e22012-10-04 10:09:15 -07003270 MutexLock mu(self, gAllocTrackerLock);
Elliott Hughes545a0642011-11-08 19:10:03 -08003271 if (recent_allocation_records_ == NULL) {
3272 return;
3273 }
3274
3275 // Advance and clip.
3276 if (++gAllocRecordHead == kNumAllocRecords) {
3277 gAllocRecordHead = 0;
3278 }
3279
3280 // Fill in the basics.
3281 AllocRecord* record = &recent_allocation_records_[gAllocRecordHead];
3282 record->type = type;
3283 record->byte_count = byte_count;
3284 record->thin_lock_id = self->GetThinLockId();
3285
3286 // Fill in the stack trace.
jeffhao725a9572012-11-13 18:20:12 -08003287 AllocRecordStackVisitor visitor(self->GetManagedStack(), self->GetInstrumentationStack(), record);
Ian Rogers0399dde2012-06-06 17:09:28 -07003288 visitor.WalkStack();
Elliott Hughes545a0642011-11-08 19:10:03 -08003289
3290 if (gAllocRecordCount < kNumAllocRecords) {
3291 ++gAllocRecordCount;
3292 }
3293}
3294
Elliott Hughesa8f93cb2012-06-08 17:08:48 -07003295// Returns the index of the head element.
3296//
3297// We point at the most-recently-written record, so if gAllocRecordCount is 1
3298// we want to use the current element. Take "head+1" and subtract count
3299// from it.
3300//
3301// We need to handle underflow in our circular buffer, so we add
3302// kNumAllocRecords and then mask it back down.
Elliott Hughesf8349362012-06-18 15:00:06 -07003303static inline int HeadIndex() EXCLUSIVE_LOCKS_REQUIRED(gAllocTrackerLock) {
Elliott Hughes545a0642011-11-08 19:10:03 -08003304 return (gAllocRecordHead+1 + kNumAllocRecords - gAllocRecordCount) & (kNumAllocRecords-1);
3305}
3306
3307void Dbg::DumpRecentAllocations() {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07003308 ScopedObjectAccess soa(Thread::Current());
Ian Rogers50b35e22012-10-04 10:09:15 -07003309 MutexLock mu(soa.Self(), gAllocTrackerLock);
Elliott Hughes545a0642011-11-08 19:10:03 -08003310 if (recent_allocation_records_ == NULL) {
3311 LOG(INFO) << "Not recording tracked allocations";
3312 return;
3313 }
3314
3315 // "i" is the head of the list. We want to start at the end of the
3316 // list and move forward to the tail.
Elliott Hughesa8f93cb2012-06-08 17:08:48 -07003317 size_t i = HeadIndex();
Elliott Hughes545a0642011-11-08 19:10:03 -08003318 size_t count = gAllocRecordCount;
3319
3320 LOG(INFO) << "Tracked allocations, (head=" << gAllocRecordHead << " count=" << count << ")";
3321 while (count--) {
3322 AllocRecord* record = &recent_allocation_records_[i];
3323
Elliott Hughesa8f93cb2012-06-08 17:08:48 -07003324 LOG(INFO) << StringPrintf(" Thread %-2d %6zd bytes ", record->thin_lock_id, record->byte_count)
Elliott Hughes545a0642011-11-08 19:10:03 -08003325 << PrettyClass(record->type);
3326
3327 for (size_t stack_frame = 0; stack_frame < kMaxAllocRecordStackDepth; ++stack_frame) {
Mathieu Chartier66f19252012-09-18 08:57:04 -07003328 const AbstractMethod* m = record->stack[stack_frame].method;
Elliott Hughes545a0642011-11-08 19:10:03 -08003329 if (m == NULL) {
3330 break;
3331 }
3332 LOG(INFO) << " " << PrettyMethod(m) << " line " << record->stack[stack_frame].LineNumber();
3333 }
3334
3335 // pause periodically to help logcat catch up
3336 if ((count % 5) == 0) {
3337 usleep(40000);
3338 }
3339
3340 i = (i + 1) & (kNumAllocRecords-1);
3341 }
3342}
3343
3344class StringTable {
3345 public:
3346 StringTable() {
3347 }
3348
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08003349 void Add(const char* s) {
Elliott Hughes545a0642011-11-08 19:10:03 -08003350 table_.insert(s);
3351 }
3352
Elliott Hughesa8f93cb2012-06-08 17:08:48 -07003353 size_t IndexOf(const char* s) const {
3354 typedef std::set<std::string>::const_iterator It; // TODO: C++0x auto
3355 It it = table_.find(s);
3356 if (it == table_.end()) {
3357 LOG(FATAL) << "IndexOf(\"" << s << "\") failed";
3358 }
3359 return std::distance(table_.begin(), it);
Elliott Hughes545a0642011-11-08 19:10:03 -08003360 }
3361
Elliott Hughesa8f93cb2012-06-08 17:08:48 -07003362 size_t Size() const {
Elliott Hughes545a0642011-11-08 19:10:03 -08003363 return table_.size();
3364 }
3365
Elliott Hughesa8f93cb2012-06-08 17:08:48 -07003366 void WriteTo(std::vector<uint8_t>& bytes) const {
3367 typedef std::set<std::string>::const_iterator It; // TODO: C++0x auto
Elliott Hughes545a0642011-11-08 19:10:03 -08003368 for (It it = table_.begin(); it != table_.end(); ++it) {
Elliott Hughesa8f93cb2012-06-08 17:08:48 -07003369 const char* s = (*it).c_str();
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08003370 size_t s_len = CountModifiedUtf8Chars(s);
3371 UniquePtr<uint16_t> s_utf16(new uint16_t[s_len]);
3372 ConvertModifiedUtf8ToUtf16(s_utf16.get(), s);
3373 JDWP::AppendUtf16BE(bytes, s_utf16.get(), s_len);
Elliott Hughes545a0642011-11-08 19:10:03 -08003374 }
3375 }
3376
3377 private:
Elliott Hughesa8f93cb2012-06-08 17:08:48 -07003378 std::set<std::string> table_;
Elliott Hughes545a0642011-11-08 19:10:03 -08003379 DISALLOW_COPY_AND_ASSIGN(StringTable);
3380};
3381
3382/*
3383 * The data we send to DDMS contains everything we have recorded.
3384 *
3385 * Message header (all values big-endian):
3386 * (1b) message header len (to allow future expansion); includes itself
3387 * (1b) entry header len
3388 * (1b) stack frame len
3389 * (2b) number of entries
3390 * (4b) offset to string table from start of message
3391 * (2b) number of class name strings
3392 * (2b) number of method name strings
3393 * (2b) number of source file name strings
3394 * For each entry:
3395 * (4b) total allocation size
Elliott Hughes221229c2013-01-08 18:17:50 -08003396 * (2b) thread id
Elliott Hughes545a0642011-11-08 19:10:03 -08003397 * (2b) allocated object's class name index
3398 * (1b) stack depth
3399 * For each stack frame:
3400 * (2b) method's class name
3401 * (2b) method name
3402 * (2b) method source file
3403 * (2b) line number, clipped to 32767; -2 if native; -1 if no source
3404 * (xb) class name strings
3405 * (xb) method name strings
3406 * (xb) source file strings
3407 *
3408 * As with other DDM traffic, strings are sent as a 4-byte length
3409 * followed by UTF-16 data.
3410 *
3411 * We send up 16-bit unsigned indexes into string tables. In theory there
3412 * can be (kMaxAllocRecordStackDepth * kNumAllocRecords) unique strings in
3413 * each table, but in practice there should be far fewer.
3414 *
3415 * The chief reason for using a string table here is to keep the size of
3416 * the DDMS message to a minimum. This is partly to make the protocol
3417 * efficient, but also because we have to form the whole thing up all at
3418 * once in a memory buffer.
3419 *
3420 * We use separate string tables for class names, method names, and source
3421 * files to keep the indexes small. There will generally be no overlap
3422 * between the contents of these tables.
3423 */
3424jbyteArray Dbg::GetRecentAllocations() {
3425 if (false) {
3426 DumpRecentAllocations();
3427 }
3428
Ian Rogers50b35e22012-10-04 10:09:15 -07003429 Thread* self = Thread::Current();
3430 MutexLock mu(self, gAllocTrackerLock);
Elliott Hughes545a0642011-11-08 19:10:03 -08003431
Elliott Hughesa8f93cb2012-06-08 17:08:48 -07003432 //
3433 // Part 1: generate string tables.
3434 //
Elliott Hughes545a0642011-11-08 19:10:03 -08003435 StringTable class_names;
3436 StringTable method_names;
3437 StringTable filenames;
3438
3439 int count = gAllocRecordCount;
Elliott Hughesa8f93cb2012-06-08 17:08:48 -07003440 int idx = HeadIndex();
Elliott Hughes545a0642011-11-08 19:10:03 -08003441 while (count--) {
3442 AllocRecord* record = &recent_allocation_records_[idx];
3443
Elliott Hughes91250e02011-12-13 22:30:35 -08003444 class_names.Add(ClassHelper(record->type).GetDescriptor());
Elliott Hughes545a0642011-11-08 19:10:03 -08003445
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08003446 MethodHelper mh;
Elliott Hughes545a0642011-11-08 19:10:03 -08003447 for (size_t i = 0; i < kMaxAllocRecordStackDepth; i++) {
Mathieu Chartier66f19252012-09-18 08:57:04 -07003448 AbstractMethod* m = record->stack[i].method;
Elliott Hughes545a0642011-11-08 19:10:03 -08003449 if (m != NULL) {
Ian Rogersba377812012-05-28 21:16:29 -07003450 mh.ChangeMethod(m);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08003451 class_names.Add(mh.GetDeclaringClassDescriptor());
3452 method_names.Add(mh.GetName());
3453 filenames.Add(mh.GetDeclaringClassSourceFile());
Elliott Hughes545a0642011-11-08 19:10:03 -08003454 }
3455 }
3456
3457 idx = (idx + 1) & (kNumAllocRecords-1);
3458 }
3459
3460 LOG(INFO) << "allocation records: " << gAllocRecordCount;
3461
Elliott Hughesa8f93cb2012-06-08 17:08:48 -07003462 //
3463 // Part 2: allocate a buffer and generate the output.
3464 //
Elliott Hughes545a0642011-11-08 19:10:03 -08003465 std::vector<uint8_t> bytes;
3466
3467 // (1b) message header len (to allow future expansion); includes itself
3468 // (1b) entry header len
3469 // (1b) stack frame len
3470 const int kMessageHeaderLen = 15;
3471 const int kEntryHeaderLen = 9;
3472 const int kStackFrameLen = 8;
3473 JDWP::Append1BE(bytes, kMessageHeaderLen);
3474 JDWP::Append1BE(bytes, kEntryHeaderLen);
3475 JDWP::Append1BE(bytes, kStackFrameLen);
3476
3477 // (2b) number of entries
3478 // (4b) offset to string table from start of message
3479 // (2b) number of class name strings
3480 // (2b) number of method name strings
3481 // (2b) number of source file name strings
3482 JDWP::Append2BE(bytes, gAllocRecordCount);
3483 size_t string_table_offset = bytes.size();
3484 JDWP::Append4BE(bytes, 0); // We'll patch this later...
3485 JDWP::Append2BE(bytes, class_names.Size());
3486 JDWP::Append2BE(bytes, method_names.Size());
3487 JDWP::Append2BE(bytes, filenames.Size());
3488
3489 count = gAllocRecordCount;
Elliott Hughesa8f93cb2012-06-08 17:08:48 -07003490 idx = HeadIndex();
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08003491 ClassHelper kh;
Elliott Hughes545a0642011-11-08 19:10:03 -08003492 while (count--) {
3493 // For each entry:
3494 // (4b) total allocation size
3495 // (2b) thread id
3496 // (2b) allocated object's class name index
3497 // (1b) stack depth
3498 AllocRecord* record = &recent_allocation_records_[idx];
3499 size_t stack_depth = record->GetDepth();
Elliott Hughesa8f93cb2012-06-08 17:08:48 -07003500 kh.ChangeClass(record->type);
3501 size_t allocated_object_class_name_index = class_names.IndexOf(kh.GetDescriptor());
Elliott Hughes545a0642011-11-08 19:10:03 -08003502 JDWP::Append4BE(bytes, record->byte_count);
3503 JDWP::Append2BE(bytes, record->thin_lock_id);
Elliott Hughesa8f93cb2012-06-08 17:08:48 -07003504 JDWP::Append2BE(bytes, allocated_object_class_name_index);
Elliott Hughes545a0642011-11-08 19:10:03 -08003505 JDWP::Append1BE(bytes, stack_depth);
3506
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08003507 MethodHelper mh;
Elliott Hughes545a0642011-11-08 19:10:03 -08003508 for (size_t stack_frame = 0; stack_frame < stack_depth; ++stack_frame) {
3509 // For each stack frame:
3510 // (2b) method's class name
3511 // (2b) method name
3512 // (2b) method source file
3513 // (2b) line number, clipped to 32767; -2 if native; -1 if no source
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08003514 mh.ChangeMethod(record->stack[stack_frame].method);
Elliott Hughesa8f93cb2012-06-08 17:08:48 -07003515 size_t class_name_index = class_names.IndexOf(mh.GetDeclaringClassDescriptor());
3516 size_t method_name_index = method_names.IndexOf(mh.GetName());
3517 size_t file_name_index = filenames.IndexOf(mh.GetDeclaringClassSourceFile());
3518 JDWP::Append2BE(bytes, class_name_index);
3519 JDWP::Append2BE(bytes, method_name_index);
3520 JDWP::Append2BE(bytes, file_name_index);
Elliott Hughes545a0642011-11-08 19:10:03 -08003521 JDWP::Append2BE(bytes, record->stack[stack_frame].LineNumber());
3522 }
3523
3524 idx = (idx + 1) & (kNumAllocRecords-1);
3525 }
3526
3527 // (xb) class name strings
3528 // (xb) method name strings
3529 // (xb) source file strings
3530 JDWP::Set4BE(&bytes[string_table_offset], bytes.size());
3531 class_names.WriteTo(bytes);
3532 method_names.WriteTo(bytes);
3533 filenames.WriteTo(bytes);
3534
Ian Rogers50b35e22012-10-04 10:09:15 -07003535 JNIEnv* env = self->GetJniEnv();
Elliott Hughes545a0642011-11-08 19:10:03 -08003536 jbyteArray result = env->NewByteArray(bytes.size());
3537 if (result != NULL) {
3538 env->SetByteArrayRegion(result, 0, bytes.size(), reinterpret_cast<const jbyte*>(&bytes[0]));
3539 }
3540 return result;
3541}
3542
Elliott Hughes872d4ec2011-10-21 17:07:15 -07003543} // namespace art