blob: a2de602a0710a0b949b8676f7d68919119661491 [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
Ian Rogers166db042013-07-26 12:05:57 -070023#include "arch/context.h"
Elliott Hughes545a0642011-11-08 19:10:03 -080024#include "class_linker.h"
Ian Rogers2dd0e2c2013-01-24 12:42:14 -080025#include "class_linker-inl.h"
Ian Rogers4f6ad8a2013-03-18 15:27:28 -070026#include "dex_file-inl.h"
Ian Rogers776ac1f2012-04-13 23:36:36 -070027#include "dex_instruction.h"
Ian Rogers1d54e732013-05-02 21:10:01 -070028#include "gc/accounting/card_table-inl.h"
29#include "gc/space/large_object_space.h"
30#include "gc/space/space-inl.h"
Jeff Hao5d917302013-02-27 17:57:33 -080031#include "invoke_arg_array_builder.h"
Elliott Hughes64f574f2013-02-20 14:57:12 -080032#include "jdwp/object_registry.h"
Brian Carlstromea46f952013-07-30 01:26:50 -070033#include "mirror/art_field-inl.h"
34#include "mirror/art_method-inl.h"
Ian Rogers2dd0e2c2013-01-24 12:42:14 -080035#include "mirror/class.h"
36#include "mirror/class-inl.h"
37#include "mirror/class_loader.h"
Ian Rogers2dd0e2c2013-01-24 12:42:14 -080038#include "mirror/object-inl.h"
39#include "mirror/object_array-inl.h"
40#include "mirror/throwable.h"
Ian Rogers6d4d9fc2011-11-30 16:24:48 -080041#include "object_utils.h"
Elliott Hughesa0e18062012-04-13 15:59:59 -070042#include "safe_map.h"
Elliott Hughes64f574f2013-02-20 14:57:12 -080043#include "scoped_thread_state_change.h"
Elliott Hughes6a5bd492011-10-28 14:33:57 -070044#include "ScopedLocalRef.h"
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -070045#include "ScopedPrimitiveArray.h"
Ian Rogers1f539342012-10-03 21:09:42 -070046#include "sirt_ref.h"
Elliott Hughes47fce012011-10-25 18:37:19 -070047#include "stack_indirect_reference_table.h"
Elliott Hughes475fc232011-10-25 15:00:35 -070048#include "thread_list.h"
Ian Rogers62d6c772013-02-27 08:32:07 -080049#include "throw_location.h"
Ian Rogers2dd0e2c2013-01-24 12:42:14 -080050#include "utf.h"
Elliott Hugheseac76672012-05-24 21:56:51 -070051#include "well_known_classes.h"
Elliott Hughes475fc232011-10-25 15:00:35 -070052
Brian Carlstrom3d92d522013-07-12 09:03:08 -070053#ifdef HAVE_ANDROID_OS
54#include "cutils/properties.h"
55#endif
56
Elliott Hughes872d4ec2011-10-21 17:07:15 -070057namespace art {
58
Brian Carlstrom7934ac22013-07-26 10:54:15 -070059static const size_t kMaxAllocRecordStackDepth = 16; // Max 255.
60static const size_t kDefaultNumAllocRecords = 64*1024; // Must be a power of 2.
Elliott Hughes475fc232011-10-25 15:00:35 -070061
Elliott Hughes545a0642011-11-08 19:10:03 -080062struct AllocRecordStackTraceElement {
Brian Carlstromea46f952013-07-30 01:26:50 -070063 mirror::ArtMethod* method;
Ian Rogers0399dde2012-06-06 17:09:28 -070064 uint32_t dex_pc;
Elliott Hughes545a0642011-11-08 19:10:03 -080065
Ian Rogersb726dcb2012-09-05 08:57:23 -070066 int32_t LineNumber() const SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Ian Rogers0399dde2012-06-06 17:09:28 -070067 return MethodHelper(method).GetLineNumFromDexPC(dex_pc);
Elliott Hughes545a0642011-11-08 19:10:03 -080068 }
69};
70
71struct AllocRecord {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -080072 mirror::Class* type;
Elliott Hughes545a0642011-11-08 19:10:03 -080073 size_t byte_count;
74 uint16_t thin_lock_id;
Brian Carlstrom7934ac22013-07-26 10:54:15 -070075 AllocRecordStackTraceElement stack[kMaxAllocRecordStackDepth]; // Unused entries have NULL method.
Elliott Hughes545a0642011-11-08 19:10:03 -080076
77 size_t GetDepth() {
78 size_t depth = 0;
79 while (depth < kMaxAllocRecordStackDepth && stack[depth].method != NULL) {
80 ++depth;
81 }
82 return depth;
83 }
84};
85
Elliott Hughes86964332012-02-15 19:37:42 -080086struct Breakpoint {
Brian Carlstromea46f952013-07-30 01:26:50 -070087 mirror::ArtMethod* method;
Elliott Hughesa656a0f2012-02-21 18:03:44 -080088 uint32_t dex_pc;
Brian Carlstromea46f952013-07-30 01:26:50 -070089 Breakpoint(mirror::ArtMethod* method, uint32_t dex_pc) : method(method), dex_pc(dex_pc) {}
Elliott Hughes86964332012-02-15 19:37:42 -080090};
91
Ian Rogers00f7d0e2012-07-19 15:28:27 -070092static std::ostream& operator<<(std::ostream& os, const Breakpoint& rhs)
Ian Rogersb726dcb2012-09-05 08:57:23 -070093 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Elliott Hughes229feb72012-02-23 13:33:29 -080094 os << StringPrintf("Breakpoint[%s @%#x]", PrettyMethod(rhs.method).c_str(), rhs.dex_pc);
Elliott Hughes86964332012-02-15 19:37:42 -080095 return os;
96}
97
98struct SingleStepControl {
99 // Are we single-stepping right now?
100 bool is_active;
101 Thread* thread;
102
103 JDWP::JdwpStepSize step_size;
104 JDWP::JdwpStepDepth step_depth;
105
Brian Carlstromea46f952013-07-30 01:26:50 -0700106 const mirror::ArtMethod* method;
Brian Carlstrom7934ac22013-07-26 10:54:15 -0700107 int32_t line_number; // Or -1 for native methods.
Elliott Hughes2435a572012-02-17 16:07:41 -0800108 std::set<uint32_t> dex_pcs;
Elliott Hughes86964332012-02-15 19:37:42 -0800109 int stack_depth;
110};
111
Ian Rogers62d6c772013-02-27 08:32:07 -0800112class DebugInstrumentationListener : public instrumentation::InstrumentationListener {
113 public:
114 DebugInstrumentationListener() {}
115 virtual ~DebugInstrumentationListener() {}
116
117 virtual void MethodEntered(Thread* thread, mirror::Object* this_object,
Brian Carlstromea46f952013-07-30 01:26:50 -0700118 const mirror::ArtMethod* method, uint32_t dex_pc)
Ian Rogers62d6c772013-02-27 08:32:07 -0800119 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
120 if (method->IsNative()) {
121 // TODO: post location events is a suspension point and native method entry stubs aren't.
122 return;
123 }
124 Dbg::PostLocationEvent(method, 0, this_object, Dbg::kMethodEntry);
125 }
126
127 virtual void MethodExited(Thread* thread, mirror::Object* this_object,
Brian Carlstromea46f952013-07-30 01:26:50 -0700128 const mirror::ArtMethod* method,
Ian Rogers62d6c772013-02-27 08:32:07 -0800129 uint32_t dex_pc, const JValue& return_value)
130 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
131 UNUSED(return_value);
132 if (method->IsNative()) {
133 // TODO: post location events is a suspension point and native method entry stubs aren't.
134 return;
135 }
136 Dbg::PostLocationEvent(method, dex_pc, this_object, Dbg::kMethodExit);
137 }
138
Sebastien Hertz51db44a2013-11-19 10:00:29 +0100139 virtual void MethodUnwind(Thread* thread, mirror::Object* this_object,
140 const mirror::ArtMethod* method, uint32_t dex_pc)
141 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Ian Rogers62d6c772013-02-27 08:32:07 -0800142 // We're not recorded to listen to this kind of event, so complain.
143 LOG(ERROR) << "Unexpected method unwind event in debugger " << PrettyMethod(method)
Sebastien Hertz51db44a2013-11-19 10:00:29 +0100144 << " " << dex_pc;
Ian Rogers62d6c772013-02-27 08:32:07 -0800145 }
146
147 virtual void DexPcMoved(Thread* thread, mirror::Object* this_object,
Brian Carlstromea46f952013-07-30 01:26:50 -0700148 const mirror::ArtMethod* method, uint32_t new_dex_pc)
Ian Rogers62d6c772013-02-27 08:32:07 -0800149 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
150 Dbg::UpdateDebugger(thread, this_object, method, new_dex_pc);
151 }
152
153 virtual void ExceptionCaught(Thread* thread, const ThrowLocation& throw_location,
Brian Carlstromea46f952013-07-30 01:26:50 -0700154 mirror::ArtMethod* catch_method, uint32_t catch_dex_pc,
Ian Rogers62d6c772013-02-27 08:32:07 -0800155 mirror::Throwable* exception_object)
156 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
157 Dbg::PostException(thread, throw_location, catch_method, catch_dex_pc, exception_object);
158 }
Ian Rogers62d6c772013-02-27 08:32:07 -0800159} gDebugInstrumentationListener;
160
Elliott Hughes4ffd3132011-10-24 12:06:42 -0700161// JDWP is allowed unless the Zygote forbids it.
162static bool gJdwpAllowed = true;
163
Elliott Hughesc0f09332012-03-26 13:27:06 -0700164// Was there a -Xrunjdwp or -agentlib:jdwp= argument on the command line?
Elliott Hughes3bb81562011-10-21 18:52:59 -0700165static bool gJdwpConfigured = false;
166
Elliott Hughesc0f09332012-03-26 13:27:06 -0700167// Broken-down JDWP options. (Only valid if IsJdwpConfigured() is true.)
Elliott Hughes376a7a02011-10-24 18:35:55 -0700168static JDWP::JdwpOptions gJdwpOptions;
Elliott Hughes3bb81562011-10-21 18:52:59 -0700169
170// Runtime JDWP state.
171static JDWP::JdwpState* gJdwpState = NULL;
172static bool gDebuggerConnected; // debugger or DDMS is connected.
173static bool gDebuggerActive; // debugger is making requests.
Elliott Hughes86964332012-02-15 19:37:42 -0800174static bool gDisposed; // debugger called VirtualMachine.Dispose, so we should drop the connection.
Elliott Hughes3bb81562011-10-21 18:52:59 -0700175
Elliott Hughes47fce012011-10-25 18:37:19 -0700176static bool gDdmThreadNotification = false;
177
Elliott Hughes767a1472011-10-26 18:49:02 -0700178// DDMS GC-related settings.
179static Dbg::HpifWhen gDdmHpifWhen = Dbg::HPIF_WHEN_NEVER;
180static Dbg::HpsgWhen gDdmHpsgWhen = Dbg::HPSG_WHEN_NEVER;
181static Dbg::HpsgWhat gDdmHpsgWhat;
182static Dbg::HpsgWhen gDdmNhsgWhen = Dbg::HPSG_WHEN_NEVER;
183static Dbg::HpsgWhat gDdmNhsgWhat;
184
Elliott Hughes475fc232011-10-25 15:00:35 -0700185static ObjectRegistry* gRegistry = NULL;
186
Elliott Hughes545a0642011-11-08 19:10:03 -0800187// Recent allocation tracking.
Brian Carlstromdf629502013-07-17 22:39:56 -0700188static Mutex gAllocTrackerLock DEFAULT_MUTEX_ACQUIRED_AFTER("AllocTracker lock");
Brian Carlstrom7934ac22013-07-26 10:54:15 -0700189AllocRecord* Dbg::recent_allocation_records_ PT_GUARDED_BY(gAllocTrackerLock) = NULL; // TODO: CircularBuffer<AllocRecord>
Elliott Hughesb1a58792013-07-11 18:10:58 -0700190static size_t gAllocRecordMax GUARDED_BY(gAllocTrackerLock) = 0;
Elliott Hughesf8349362012-06-18 15:00:06 -0700191static size_t gAllocRecordHead GUARDED_BY(gAllocTrackerLock) = 0;
192static size_t gAllocRecordCount GUARDED_BY(gAllocTrackerLock) = 0;
Elliott Hughes545a0642011-11-08 19:10:03 -0800193
Elliott Hughes86964332012-02-15 19:37:42 -0800194// Breakpoints and single-stepping.
jeffhao09bfc6a2012-12-11 18:11:43 -0800195static std::vector<Breakpoint> gBreakpoints GUARDED_BY(Locks::breakpoint_lock_);
196static SingleStepControl gSingleStepControl GUARDED_BY(Locks::breakpoint_lock_);
Elliott Hughes86964332012-02-15 19:37:42 -0800197
Brian Carlstromea46f952013-07-30 01:26:50 -0700198static bool IsBreakpoint(const mirror::ArtMethod* m, uint32_t dex_pc)
jeffhao09bfc6a2012-12-11 18:11:43 -0800199 LOCKS_EXCLUDED(Locks::breakpoint_lock_)
Ian Rogersb726dcb2012-09-05 08:57:23 -0700200 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
jeffhao09bfc6a2012-12-11 18:11:43 -0800201 MutexLock mu(Thread::Current(), *Locks::breakpoint_lock_);
Elliott Hughes86964332012-02-15 19:37:42 -0800202 for (size_t i = 0; i < gBreakpoints.size(); ++i) {
Elliott Hughesa656a0f2012-02-21 18:03:44 -0800203 if (gBreakpoints[i].method == m && gBreakpoints[i].dex_pc == dex_pc) {
Elliott Hughes86964332012-02-15 19:37:42 -0800204 VLOG(jdwp) << "Hit breakpoint #" << i << ": " << gBreakpoints[i];
205 return true;
206 }
207 }
208 return false;
209}
210
Elliott Hughes9e0c1752013-01-09 14:02:58 -0800211static bool IsSuspendedForDebugger(ScopedObjectAccessUnchecked& soa, Thread* thread) {
212 MutexLock mu(soa.Self(), *Locks::thread_suspend_count_lock_);
213 // A thread may be suspended for GC; in this code, we really want to know whether
214 // there's a debugger suspension active.
215 return thread->IsSuspended() && thread->GetDebugSuspendCount() > 0;
216}
217
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800218static mirror::Array* DecodeArray(JDWP::RefTypeId id, JDWP::JdwpError& status)
Ian Rogersb726dcb2012-09-05 08:57:23 -0700219 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800220 mirror::Object* o = gRegistry->Get<mirror::Object*>(id);
Elliott Hughes64f574f2013-02-20 14:57:12 -0800221 if (o == NULL || o == ObjectRegistry::kInvalidObject) {
Elliott Hughes436e3722012-02-17 20:01:47 -0800222 status = JDWP::ERR_INVALID_OBJECT;
223 return NULL;
224 }
225 if (!o->IsArrayInstance()) {
226 status = JDWP::ERR_INVALID_ARRAY;
227 return NULL;
228 }
229 status = JDWP::ERR_NONE;
230 return o->AsArray();
231}
232
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800233static mirror::Class* DecodeClass(JDWP::RefTypeId id, JDWP::JdwpError& status)
Ian Rogersb726dcb2012-09-05 08:57:23 -0700234 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800235 mirror::Object* o = gRegistry->Get<mirror::Object*>(id);
Elliott Hughes64f574f2013-02-20 14:57:12 -0800236 if (o == NULL || o == ObjectRegistry::kInvalidObject) {
Elliott Hughes436e3722012-02-17 20:01:47 -0800237 status = JDWP::ERR_INVALID_OBJECT;
238 return NULL;
239 }
240 if (!o->IsClass()) {
241 status = JDWP::ERR_INVALID_CLASS;
242 return NULL;
243 }
244 status = JDWP::ERR_NONE;
245 return o->AsClass();
246}
247
Elliott Hughes221229c2013-01-08 18:17:50 -0800248static JDWP::JdwpError DecodeThread(ScopedObjectAccessUnchecked& soa, JDWP::ObjectId thread_id, Thread*& thread)
jeffhaoa77f0f62012-12-05 17:19:31 -0800249 EXCLUSIVE_LOCKS_REQUIRED(Locks::thread_list_lock_)
Ian Rogersb726dcb2012-09-05 08:57:23 -0700250 LOCKS_EXCLUDED(Locks::thread_suspend_count_lock_)
251 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800252 mirror::Object* thread_peer = gRegistry->Get<mirror::Object*>(thread_id);
Elliott Hughes64f574f2013-02-20 14:57:12 -0800253 if (thread_peer == NULL || thread_peer == ObjectRegistry::kInvalidObject) {
Elliott Hughes221229c2013-01-08 18:17:50 -0800254 // This isn't even an object.
255 return JDWP::ERR_INVALID_OBJECT;
Elliott Hughes436e3722012-02-17 20:01:47 -0800256 }
Elliott Hughes221229c2013-01-08 18:17:50 -0800257
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800258 mirror::Class* java_lang_Thread = soa.Decode<mirror::Class*>(WellKnownClasses::java_lang_Thread);
Elliott Hughes221229c2013-01-08 18:17:50 -0800259 if (!java_lang_Thread->IsAssignableFrom(thread_peer->GetClass())) {
260 // This isn't a thread.
261 return JDWP::ERR_INVALID_THREAD;
262 }
263
264 thread = Thread::FromManagedThread(soa, thread_peer);
265 if (thread == NULL) {
266 // This is a java.lang.Thread without a Thread*. Must be a zombie.
267 return JDWP::ERR_THREAD_NOT_ALIVE;
268 }
269 return JDWP::ERR_NONE;
Elliott Hughes436e3722012-02-17 20:01:47 -0800270}
271
Elliott Hughes24437992011-11-30 14:49:33 -0800272static JDWP::JdwpTag BasicTagFromDescriptor(const char* descriptor) {
273 // JDWP deliberately uses the descriptor characters' ASCII values for its enum.
274 // Note that by "basic" we mean that we don't get more specific than JT_OBJECT.
275 return static_cast<JDWP::JdwpTag>(descriptor[0]);
276}
277
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800278static JDWP::JdwpTag TagFromClass(mirror::Class* c)
Ian Rogersb726dcb2012-09-05 08:57:23 -0700279 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Elliott Hughes86b00102011-12-05 17:54:26 -0800280 CHECK(c != NULL);
Elliott Hughes24437992011-11-30 14:49:33 -0800281 if (c->IsArrayClass()) {
282 return JDWP::JT_ARRAY;
283 }
284
Elliott Hughes3d30d9b2011-12-07 17:35:48 -0800285 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
Elliott Hughes24437992011-11-30 14:49:33 -0800286 if (c->IsStringClass()) {
287 return JDWP::JT_STRING;
288 } else if (c->IsClassClass()) {
289 return JDWP::JT_CLASS_OBJECT;
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -0800290 } else if (class_linker->FindSystemClass("Ljava/lang/Thread;")->IsAssignableFrom(c)) {
Elliott Hughes24437992011-11-30 14:49:33 -0800291 return JDWP::JT_THREAD;
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -0800292 } else if (class_linker->FindSystemClass("Ljava/lang/ThreadGroup;")->IsAssignableFrom(c)) {
Elliott Hughes24437992011-11-30 14:49:33 -0800293 return JDWP::JT_THREAD_GROUP;
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -0800294 } else if (class_linker->FindSystemClass("Ljava/lang/ClassLoader;")->IsAssignableFrom(c)) {
Elliott Hughes24437992011-11-30 14:49:33 -0800295 return JDWP::JT_CLASS_LOADER;
Elliott Hughes24437992011-11-30 14:49:33 -0800296 } else {
297 return JDWP::JT_OBJECT;
298 }
299}
300
301/*
302 * Objects declared to hold Object might actually hold a more specific
303 * type. The debugger may take a special interest in these (e.g. it
304 * wants to display the contents of Strings), so we want to return an
305 * appropriate tag.
306 *
307 * Null objects are tagged JT_OBJECT.
308 */
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800309static JDWP::JdwpTag TagFromObject(const mirror::Object* o)
Ian Rogersb726dcb2012-09-05 08:57:23 -0700310 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Elliott Hughes24437992011-11-30 14:49:33 -0800311 return (o == NULL) ? JDWP::JT_OBJECT : TagFromClass(o->GetClass());
312}
313
314static bool IsPrimitiveTag(JDWP::JdwpTag tag) {
315 switch (tag) {
316 case JDWP::JT_BOOLEAN:
317 case JDWP::JT_BYTE:
318 case JDWP::JT_CHAR:
319 case JDWP::JT_FLOAT:
320 case JDWP::JT_DOUBLE:
321 case JDWP::JT_INT:
322 case JDWP::JT_LONG:
323 case JDWP::JT_SHORT:
324 case JDWP::JT_VOID:
325 return true;
326 default:
327 return false;
328 }
329}
330
Elliott Hughes3bb81562011-10-21 18:52:59 -0700331/*
332 * Handle one of the JDWP name/value pairs.
333 *
334 * JDWP options are:
335 * help: if specified, show help message and bail
336 * transport: may be dt_socket or dt_shmem
337 * address: for dt_socket, "host:port", or just "port" when listening
338 * server: if "y", wait for debugger to attach; if "n", attach to debugger
339 * timeout: how long to wait for debugger to connect / listen
340 *
341 * Useful with server=n (these aren't supported yet):
342 * onthrow=<exception-name>: connect to debugger when exception thrown
343 * onuncaught=y|n: connect to debugger when uncaught exception thrown
344 * launch=<command-line>: launch the debugger itself
345 *
346 * The "transport" option is required, as is "address" if server=n.
347 */
348static bool ParseJdwpOption(const std::string& name, const std::string& value) {
349 if (name == "transport") {
350 if (value == "dt_socket") {
Elliott Hughes376a7a02011-10-24 18:35:55 -0700351 gJdwpOptions.transport = JDWP::kJdwpTransportSocket;
Elliott Hughes3bb81562011-10-21 18:52:59 -0700352 } else if (value == "dt_android_adb") {
Elliott Hughes376a7a02011-10-24 18:35:55 -0700353 gJdwpOptions.transport = JDWP::kJdwpTransportAndroidAdb;
Elliott Hughes3bb81562011-10-21 18:52:59 -0700354 } else {
355 LOG(ERROR) << "JDWP transport not supported: " << value;
356 return false;
357 }
358 } else if (name == "server") {
359 if (value == "n") {
Elliott Hughes376a7a02011-10-24 18:35:55 -0700360 gJdwpOptions.server = false;
Elliott Hughes3bb81562011-10-21 18:52:59 -0700361 } else if (value == "y") {
Elliott Hughes376a7a02011-10-24 18:35:55 -0700362 gJdwpOptions.server = true;
Elliott Hughes3bb81562011-10-21 18:52:59 -0700363 } else {
364 LOG(ERROR) << "JDWP option 'server' must be 'y' or 'n'";
365 return false;
366 }
367 } else if (name == "suspend") {
368 if (value == "n") {
Elliott Hughes376a7a02011-10-24 18:35:55 -0700369 gJdwpOptions.suspend = false;
Elliott Hughes3bb81562011-10-21 18:52:59 -0700370 } else if (value == "y") {
Elliott Hughes376a7a02011-10-24 18:35:55 -0700371 gJdwpOptions.suspend = true;
Elliott Hughes3bb81562011-10-21 18:52:59 -0700372 } else {
373 LOG(ERROR) << "JDWP option 'suspend' must be 'y' or 'n'";
374 return false;
375 }
376 } else if (name == "address") {
377 /* this is either <port> or <host>:<port> */
378 std::string port_string;
Elliott Hughes376a7a02011-10-24 18:35:55 -0700379 gJdwpOptions.host.clear();
Elliott Hughes3bb81562011-10-21 18:52:59 -0700380 std::string::size_type colon = value.find(':');
381 if (colon != std::string::npos) {
Elliott Hughes376a7a02011-10-24 18:35:55 -0700382 gJdwpOptions.host = value.substr(0, colon);
Elliott Hughes3bb81562011-10-21 18:52:59 -0700383 port_string = value.substr(colon + 1);
384 } else {
385 port_string = value;
386 }
387 if (port_string.empty()) {
388 LOG(ERROR) << "JDWP address missing port: " << value;
389 return false;
390 }
391 char* end;
Elliott Hughesba8eee12012-01-24 20:25:24 -0800392 uint64_t port = strtoul(port_string.c_str(), &end, 10);
393 if (*end != '\0' || port > 0xffff) {
Elliott Hughes3bb81562011-10-21 18:52:59 -0700394 LOG(ERROR) << "JDWP address has junk in port field: " << value;
395 return false;
396 }
Elliott Hughes376a7a02011-10-24 18:35:55 -0700397 gJdwpOptions.port = port;
Elliott Hughes3bb81562011-10-21 18:52:59 -0700398 } else if (name == "launch" || name == "onthrow" || name == "oncaught" || name == "timeout") {
399 /* valid but unsupported */
400 LOG(INFO) << "Ignoring JDWP option '" << name << "'='" << value << "'";
401 } else {
402 LOG(INFO) << "Ignoring unrecognized JDWP option '" << name << "'='" << value << "'";
403 }
404
405 return true;
406}
407
408/*
409 * Parse the latter half of a -Xrunjdwp/-agentlib:jdwp= string, e.g.:
410 * "transport=dt_socket,address=8000,server=y,suspend=n"
411 */
412bool Dbg::ParseJdwpOptions(const std::string& options) {
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -0800413 VLOG(jdwp) << "ParseJdwpOptions: " << options;
Elliott Hughes47fce012011-10-25 18:37:19 -0700414
Elliott Hughes3bb81562011-10-21 18:52:59 -0700415 std::vector<std::string> pairs;
416 Split(options, ',', pairs);
417
418 for (size_t i = 0; i < pairs.size(); ++i) {
419 std::string::size_type equals = pairs[i].find('=');
420 if (equals == std::string::npos) {
421 LOG(ERROR) << "Can't parse JDWP option '" << pairs[i] << "' in '" << options << "'";
422 return false;
423 }
424 ParseJdwpOption(pairs[i].substr(0, equals), pairs[i].substr(equals + 1));
425 }
426
Elliott Hughes376a7a02011-10-24 18:35:55 -0700427 if (gJdwpOptions.transport == JDWP::kJdwpTransportUnknown) {
Elliott Hughes3bb81562011-10-21 18:52:59 -0700428 LOG(ERROR) << "Must specify JDWP transport: " << options;
429 }
Elliott Hughes376a7a02011-10-24 18:35:55 -0700430 if (!gJdwpOptions.server && (gJdwpOptions.host.empty() || gJdwpOptions.port == 0)) {
Elliott Hughes3bb81562011-10-21 18:52:59 -0700431 LOG(ERROR) << "Must specify JDWP host and port when server=n: " << options;
432 return false;
433 }
434
435 gJdwpConfigured = true;
436 return true;
437}
438
Elliott Hughesd1cc8362011-10-24 16:58:50 -0700439void Dbg::StartJdwp() {
Elliott Hughesc0f09332012-03-26 13:27:06 -0700440 if (!gJdwpAllowed || !IsJdwpConfigured()) {
Elliott Hughes376a7a02011-10-24 18:35:55 -0700441 // No JDWP for you!
442 return;
443 }
444
Elliott Hughes475fc232011-10-25 15:00:35 -0700445 CHECK(gRegistry == NULL);
446 gRegistry = new ObjectRegistry;
447
Elliott Hughesd1cc8362011-10-24 16:58:50 -0700448 // Init JDWP if the debugger is enabled. This may connect out to a
449 // debugger, passively listen for a debugger, or block waiting for a
450 // debugger.
Elliott Hughes376a7a02011-10-24 18:35:55 -0700451 gJdwpState = JDWP::JdwpState::Create(&gJdwpOptions);
452 if (gJdwpState == NULL) {
Elliott Hughesf8a2df72011-12-01 12:19:54 -0800453 // We probably failed because some other process has the port already, which means that
454 // if we don't abort the user is likely to think they're talking to us when they're actually
455 // talking to that other process.
Elliott Hughes3d30d9b2011-12-07 17:35:48 -0800456 LOG(FATAL) << "Debugger thread failed to initialize";
Elliott Hughesd1cc8362011-10-24 16:58:50 -0700457 }
458
459 // If a debugger has already attached, send the "welcome" message.
460 // This may cause us to suspend all threads.
Elliott Hughes376a7a02011-10-24 18:35:55 -0700461 if (gJdwpState->IsActive()) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700462 ScopedObjectAccess soa(Thread::Current());
Elliott Hughes376a7a02011-10-24 18:35:55 -0700463 if (!gJdwpState->PostVMStart()) {
Elliott Hughes3d30d9b2011-12-07 17:35:48 -0800464 LOG(WARNING) << "Failed to post 'start' message to debugger";
Elliott Hughesd1cc8362011-10-24 16:58:50 -0700465 }
466 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700467}
468
Elliott Hughesd1cc8362011-10-24 16:58:50 -0700469void Dbg::StopJdwp() {
Elliott Hughes376a7a02011-10-24 18:35:55 -0700470 delete gJdwpState;
Elliott Hughes475fc232011-10-25 15:00:35 -0700471 delete gRegistry;
472 gRegistry = NULL;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700473}
474
Elliott Hughes767a1472011-10-26 18:49:02 -0700475void Dbg::GcDidFinish() {
476 if (gDdmHpifWhen != HPIF_WHEN_NEVER) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700477 ScopedObjectAccess soa(Thread::Current());
Elliott Hughes81ff3182012-03-23 20:35:56 -0700478 LOG(DEBUG) << "Sending heap info to DDM";
Elliott Hughes7162ad92011-10-27 14:08:42 -0700479 DdmSendHeapInfo(gDdmHpifWhen);
Elliott Hughes767a1472011-10-26 18:49:02 -0700480 }
481 if (gDdmHpsgWhen != HPSG_WHEN_NEVER) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700482 ScopedObjectAccess soa(Thread::Current());
Elliott Hughes81ff3182012-03-23 20:35:56 -0700483 LOG(DEBUG) << "Dumping heap to DDM";
Elliott Hughes6a5bd492011-10-28 14:33:57 -0700484 DdmSendHeapSegments(false);
Elliott Hughes767a1472011-10-26 18:49:02 -0700485 }
486 if (gDdmNhsgWhen != HPSG_WHEN_NEVER) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700487 ScopedObjectAccess soa(Thread::Current());
Elliott Hughes767a1472011-10-26 18:49:02 -0700488 LOG(DEBUG) << "Dumping native heap to DDM";
Elliott Hughes6a5bd492011-10-28 14:33:57 -0700489 DdmSendHeapSegments(true);
Elliott Hughes767a1472011-10-26 18:49:02 -0700490 }
491}
492
Elliott Hughes4ffd3132011-10-24 12:06:42 -0700493void Dbg::SetJdwpAllowed(bool allowed) {
494 gJdwpAllowed = allowed;
495}
496
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700497DebugInvokeReq* Dbg::GetInvokeReq() {
Elliott Hughes475fc232011-10-25 15:00:35 -0700498 return Thread::Current()->GetInvokeReq();
499}
500
501Thread* Dbg::GetDebugThread() {
502 return (gJdwpState != NULL) ? gJdwpState->GetDebugThread() : NULL;
503}
504
505void Dbg::ClearWaitForEventThread() {
506 gJdwpState->ClearWaitForEventThread();
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700507}
508
509void Dbg::Connected() {
Elliott Hughes3bb81562011-10-21 18:52:59 -0700510 CHECK(!gDebuggerConnected);
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -0800511 VLOG(jdwp) << "JDWP has attached";
Elliott Hughes3bb81562011-10-21 18:52:59 -0700512 gDebuggerConnected = true;
Elliott Hughes86964332012-02-15 19:37:42 -0800513 gDisposed = false;
514}
515
516void Dbg::Disposed() {
517 gDisposed = true;
518}
519
520bool Dbg::IsDisposed() {
521 return gDisposed;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700522}
523
Elliott Hughesa2155262011-11-16 16:26:58 -0800524void Dbg::GoActive() {
525 // Enable all debugging features, including scans for breakpoints.
526 // This is a no-op if we're already active.
527 // Only called from the JDWP handler thread.
528 if (gDebuggerActive) {
529 return;
530 }
531
Elliott Hughesc0f09332012-03-26 13:27:06 -0700532 {
533 // TODO: dalvik only warned if there were breakpoints left over. clear in Dbg::Disconnected?
jeffhao09bfc6a2012-12-11 18:11:43 -0800534 MutexLock mu(Thread::Current(), *Locks::breakpoint_lock_);
Elliott Hughesc0f09332012-03-26 13:27:06 -0700535 CHECK_EQ(gBreakpoints.size(), 0U);
536 }
Elliott Hughesa2155262011-11-16 16:26:58 -0800537
Ian Rogers62d6c772013-02-27 08:32:07 -0800538 Runtime* runtime = Runtime::Current();
539 runtime->GetThreadList()->SuspendAll();
540 Thread* self = Thread::Current();
541 ThreadState old_state = self->SetStateUnsafe(kRunnable);
542 CHECK_NE(old_state, kRunnable);
543 runtime->GetInstrumentation()->AddListener(&gDebugInstrumentationListener,
544 instrumentation::Instrumentation::kMethodEntered |
545 instrumentation::Instrumentation::kMethodExited |
Jeff Hao14dd5a82013-04-11 10:23:36 -0700546 instrumentation::Instrumentation::kDexPcMoved |
547 instrumentation::Instrumentation::kExceptionCaught);
Elliott Hughesa2155262011-11-16 16:26:58 -0800548 gDebuggerActive = true;
Ian Rogers62d6c772013-02-27 08:32:07 -0800549 CHECK_EQ(self->SetStateUnsafe(old_state), kRunnable);
550 runtime->GetThreadList()->ResumeAll();
551
552 LOG(INFO) << "Debugger is active";
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700553}
554
555void Dbg::Disconnected() {
Elliott Hughes234ab152011-10-26 14:02:26 -0700556 CHECK(gDebuggerConnected);
557
Elliott Hughesc0f09332012-03-26 13:27:06 -0700558 LOG(INFO) << "Debugger is no longer active";
Elliott Hughes234ab152011-10-26 14:02:26 -0700559
Ian Rogers62d6c772013-02-27 08:32:07 -0800560 // Suspend all threads and exclusively acquire the mutator lock. Set the state of the thread
561 // to kRunnable to avoid scoped object access transitions. Remove the debugger as a listener
562 // and clear the object registry.
563 Runtime* runtime = Runtime::Current();
564 runtime->GetThreadList()->SuspendAll();
565 Thread* self = Thread::Current();
566 ThreadState old_state = self->SetStateUnsafe(kRunnable);
567 runtime->GetInstrumentation()->RemoveListener(&gDebugInstrumentationListener,
568 instrumentation::Instrumentation::kMethodEntered |
569 instrumentation::Instrumentation::kMethodExited |
Jeff Hao14dd5a82013-04-11 10:23:36 -0700570 instrumentation::Instrumentation::kDexPcMoved |
571 instrumentation::Instrumentation::kExceptionCaught);
Elliott Hughesc0f09332012-03-26 13:27:06 -0700572 gDebuggerActive = false;
Elliott Hughes234ab152011-10-26 14:02:26 -0700573 gRegistry->Clear();
574 gDebuggerConnected = false;
Ian Rogers62d6c772013-02-27 08:32:07 -0800575 CHECK_EQ(self->SetStateUnsafe(old_state), kRunnable);
576 runtime->GetThreadList()->ResumeAll();
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700577}
578
Elliott Hughesc0f09332012-03-26 13:27:06 -0700579bool Dbg::IsDebuggerActive() {
Elliott Hughes3bb81562011-10-21 18:52:59 -0700580 return gDebuggerActive;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700581}
582
Elliott Hughesc0f09332012-03-26 13:27:06 -0700583bool Dbg::IsJdwpConfigured() {
Elliott Hughes3bb81562011-10-21 18:52:59 -0700584 return gJdwpConfigured;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700585}
586
587int64_t Dbg::LastDebuggerActivity() {
Elliott Hughesca951522011-12-05 12:01:32 -0800588 return gJdwpState->LastDebuggerActivity();
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700589}
590
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700591void Dbg::UndoDebuggerSuspensions() {
Elliott Hughes234ab152011-10-26 14:02:26 -0700592 Runtime::Current()->GetThreadList()->UndoDebuggerSuspensions();
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700593}
594
Elliott Hughes88d63092013-01-09 09:55:54 -0800595std::string Dbg::GetClassName(JDWP::RefTypeId class_id) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800596 mirror::Object* o = gRegistry->Get<mirror::Object*>(class_id);
Elliott Hughes436e3722012-02-17 20:01:47 -0800597 if (o == NULL) {
598 return "NULL";
599 }
Elliott Hughes64f574f2013-02-20 14:57:12 -0800600 if (o == ObjectRegistry::kInvalidObject) {
Elliott Hughes88d63092013-01-09 09:55:54 -0800601 return StringPrintf("invalid object %p", reinterpret_cast<void*>(class_id));
Elliott Hughes436e3722012-02-17 20:01:47 -0800602 }
603 if (!o->IsClass()) {
Brian Carlstrom7934ac22013-07-26 10:54:15 -0700604 return StringPrintf("non-class %p", o); // This is only used for debugging output anyway.
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -0800605 }
Elliott Hughesc308a5d2012-02-16 17:12:06 -0800606 return DescriptorToName(ClassHelper(o->AsClass()).GetDescriptor());
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700607}
608
Elliott Hughes88d63092013-01-09 09:55:54 -0800609JDWP::JdwpError Dbg::GetClassObject(JDWP::RefTypeId id, JDWP::ObjectId& class_object_id) {
Elliott Hughes436e3722012-02-17 20:01:47 -0800610 JDWP::JdwpError status;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800611 mirror::Class* c = DecodeClass(id, status);
Elliott Hughes436e3722012-02-17 20:01:47 -0800612 if (c == NULL) {
613 return status;
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -0800614 }
Elliott Hughes88d63092013-01-09 09:55:54 -0800615 class_object_id = gRegistry->Add(c);
Elliott Hughes436e3722012-02-17 20:01:47 -0800616 return JDWP::ERR_NONE;
Elliott Hughes86964332012-02-15 19:37:42 -0800617}
618
Elliott Hughes88d63092013-01-09 09:55:54 -0800619JDWP::JdwpError Dbg::GetSuperclass(JDWP::RefTypeId id, JDWP::RefTypeId& superclass_id) {
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -0800620 JDWP::JdwpError status;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800621 mirror::Class* c = DecodeClass(id, status);
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -0800622 if (c == NULL) {
623 return status;
624 }
625 if (c->IsInterface()) {
626 // http://code.google.com/p/android/issues/detail?id=20856
Elliott Hughes88d63092013-01-09 09:55:54 -0800627 superclass_id = 0;
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -0800628 } else {
Elliott Hughes88d63092013-01-09 09:55:54 -0800629 superclass_id = gRegistry->Add(c->GetSuperClass());
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -0800630 }
631 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700632}
633
Elliott Hughes436e3722012-02-17 20:01:47 -0800634JDWP::JdwpError Dbg::GetClassLoader(JDWP::RefTypeId id, JDWP::ExpandBuf* pReply) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800635 mirror::Object* o = gRegistry->Get<mirror::Object*>(id);
Elliott Hughes64f574f2013-02-20 14:57:12 -0800636 if (o == NULL || o == ObjectRegistry::kInvalidObject) {
Elliott Hughes436e3722012-02-17 20:01:47 -0800637 return JDWP::ERR_INVALID_OBJECT;
638 }
639 expandBufAddObjectId(pReply, gRegistry->Add(o->GetClass()->GetClassLoader()));
640 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700641}
642
Elliott Hughes436e3722012-02-17 20:01:47 -0800643JDWP::JdwpError Dbg::GetModifiers(JDWP::RefTypeId id, JDWP::ExpandBuf* pReply) {
644 JDWP::JdwpError status;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800645 mirror::Class* c = DecodeClass(id, status);
Elliott Hughes436e3722012-02-17 20:01:47 -0800646 if (c == NULL) {
647 return status;
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -0800648 }
Elliott Hughes436e3722012-02-17 20:01:47 -0800649
650 uint32_t access_flags = c->GetAccessFlags() & kAccJavaFlagsMask;
651
652 // Set ACC_SUPER; dex files don't contain this flag, but all classes are supposed to have it set.
653 // Class.getModifiers doesn't return it, but JDWP does, so we set it here.
654 access_flags |= kAccSuper;
655
656 expandBufAdd4BE(pReply, access_flags);
657
658 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700659}
660
Elliott Hughesf327e072013-01-09 16:01:26 -0800661JDWP::JdwpError Dbg::GetMonitorInfo(JDWP::ObjectId object_id, JDWP::ExpandBuf* reply)
662 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800663 mirror::Object* o = gRegistry->Get<mirror::Object*>(object_id);
Elliott Hughes64f574f2013-02-20 14:57:12 -0800664 if (o == NULL || o == ObjectRegistry::kInvalidObject) {
Elliott Hughesf327e072013-01-09 16:01:26 -0800665 return JDWP::ERR_INVALID_OBJECT;
666 }
667
668 // Ensure all threads are suspended while we read objects' lock words.
669 Thread* self = Thread::Current();
670 Locks::mutator_lock_->SharedUnlock(self);
671 Locks::mutator_lock_->ExclusiveLock(self);
672
673 MonitorInfo monitor_info(o);
674
675 Locks::mutator_lock_->ExclusiveUnlock(self);
676 Locks::mutator_lock_->SharedLock(self);
677
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700678 if (monitor_info.owner_ != NULL) {
679 expandBufAddObjectId(reply, gRegistry->Add(monitor_info.owner_->GetPeer()));
Elliott Hughesf327e072013-01-09 16:01:26 -0800680 } else {
681 expandBufAddObjectId(reply, gRegistry->Add(NULL));
682 }
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700683 expandBufAdd4BE(reply, monitor_info.entry_count_);
684 expandBufAdd4BE(reply, monitor_info.waiters_.size());
685 for (size_t i = 0; i < monitor_info.waiters_.size(); ++i) {
686 expandBufAddObjectId(reply, gRegistry->Add(monitor_info.waiters_[i]->GetPeer()));
Elliott Hughesf327e072013-01-09 16:01:26 -0800687 }
688 return JDWP::ERR_NONE;
689}
690
Elliott Hughes734b8c62013-01-11 15:32:45 -0800691JDWP::JdwpError Dbg::GetOwnedMonitors(JDWP::ObjectId thread_id,
692 std::vector<JDWP::ObjectId>& monitors,
693 std::vector<uint32_t>& stack_depths)
Elliott Hughes4993bbc2013-01-10 15:41:25 -0800694 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
695 ScopedObjectAccessUnchecked soa(Thread::Current());
696 MutexLock mu(soa.Self(), *Locks::thread_list_lock_);
697 Thread* thread;
698 JDWP::JdwpError error = DecodeThread(soa, thread_id, thread);
699 if (error != JDWP::ERR_NONE) {
700 return error;
701 }
702 if (!IsSuspendedForDebugger(soa, thread)) {
703 return JDWP::ERR_THREAD_NOT_SUSPENDED;
704 }
705
706 struct OwnedMonitorVisitor : public StackVisitor {
Ian Rogers7a22fa62013-01-23 12:16:16 -0800707 OwnedMonitorVisitor(Thread* thread, Context* context)
Elliott Hughes4993bbc2013-01-10 15:41:25 -0800708 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_)
Ian Rogers7a22fa62013-01-23 12:16:16 -0800709 : StackVisitor(thread, context), current_stack_depth(0) {}
Elliott Hughes4993bbc2013-01-10 15:41:25 -0800710
711 // TODO: Enable annotalysis. We know lock is held in constructor, but abstraction confuses
712 // annotalysis.
713 bool VisitFrame() NO_THREAD_SAFETY_ANALYSIS {
714 if (!GetMethod()->IsRuntimeMethod()) {
715 Monitor::VisitLocks(this, AppendOwnedMonitors, this);
Elliott Hughes734b8c62013-01-11 15:32:45 -0800716 ++current_stack_depth;
Elliott Hughes4993bbc2013-01-10 15:41:25 -0800717 }
718 return true;
719 }
720
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800721 static void AppendOwnedMonitors(mirror::Object* owned_monitor, void* arg) {
Ian Rogers7a22fa62013-01-23 12:16:16 -0800722 OwnedMonitorVisitor* visitor = reinterpret_cast<OwnedMonitorVisitor*>(arg);
Elliott Hughes734b8c62013-01-11 15:32:45 -0800723 visitor->monitors.push_back(owned_monitor);
724 visitor->stack_depths.push_back(visitor->current_stack_depth);
Elliott Hughes4993bbc2013-01-10 15:41:25 -0800725 }
726
Elliott Hughes734b8c62013-01-11 15:32:45 -0800727 size_t current_stack_depth;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800728 std::vector<mirror::Object*> monitors;
Elliott Hughes734b8c62013-01-11 15:32:45 -0800729 std::vector<uint32_t> stack_depths;
Elliott Hughes4993bbc2013-01-10 15:41:25 -0800730 };
Ian Rogers7a22fa62013-01-23 12:16:16 -0800731 UniquePtr<Context> context(Context::Create());
732 OwnedMonitorVisitor visitor(thread, context.get());
Elliott Hughes4993bbc2013-01-10 15:41:25 -0800733 visitor.WalkStack();
734
735 for (size_t i = 0; i < visitor.monitors.size(); ++i) {
736 monitors.push_back(gRegistry->Add(visitor.monitors[i]));
Elliott Hughes734b8c62013-01-11 15:32:45 -0800737 stack_depths.push_back(visitor.stack_depths[i]);
Elliott Hughes4993bbc2013-01-10 15:41:25 -0800738 }
739
740 return JDWP::ERR_NONE;
741}
742
Elliott Hughesf9501702013-01-11 11:22:27 -0800743JDWP::JdwpError Dbg::GetContendedMonitor(JDWP::ObjectId thread_id, JDWP::ObjectId& contended_monitor)
744 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
745 ScopedObjectAccessUnchecked soa(Thread::Current());
746 MutexLock mu(soa.Self(), *Locks::thread_list_lock_);
747 Thread* thread;
748 JDWP::JdwpError error = DecodeThread(soa, thread_id, thread);
749 if (error != JDWP::ERR_NONE) {
750 return error;
751 }
752 if (!IsSuspendedForDebugger(soa, thread)) {
753 return JDWP::ERR_THREAD_NOT_SUSPENDED;
754 }
755
756 contended_monitor = gRegistry->Add(Monitor::GetContendedMonitor(thread));
757
758 return JDWP::ERR_NONE;
759}
760
Elliott Hughesec0f83d2013-01-15 16:54:08 -0800761JDWP::JdwpError Dbg::GetInstanceCounts(const std::vector<JDWP::RefTypeId>& class_ids,
762 std::vector<uint64_t>& counts)
763 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800764 std::vector<mirror::Class*> classes;
Elliott Hughesec0f83d2013-01-15 16:54:08 -0800765 counts.clear();
766 for (size_t i = 0; i < class_ids.size(); ++i) {
767 JDWP::JdwpError status;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800768 mirror::Class* c = DecodeClass(class_ids[i], status);
Elliott Hughesec0f83d2013-01-15 16:54:08 -0800769 if (c == NULL) {
770 return status;
771 }
772 classes.push_back(c);
773 counts.push_back(0);
774 }
775
776 Runtime::Current()->GetHeap()->CountInstances(classes, false, &counts[0]);
777 return JDWP::ERR_NONE;
778}
779
Elliott Hughes3b78c942013-01-15 17:35:41 -0800780JDWP::JdwpError Dbg::GetInstances(JDWP::RefTypeId class_id, int32_t max_count, std::vector<JDWP::ObjectId>& instances)
781 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
782 JDWP::JdwpError status;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800783 mirror::Class* c = DecodeClass(class_id, status);
Elliott Hughes3b78c942013-01-15 17:35:41 -0800784 if (c == NULL) {
785 return status;
786 }
787
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800788 std::vector<mirror::Object*> raw_instances;
Elliott Hughes3b78c942013-01-15 17:35:41 -0800789 Runtime::Current()->GetHeap()->GetInstances(c, max_count, raw_instances);
790 for (size_t i = 0; i < raw_instances.size(); ++i) {
791 instances.push_back(gRegistry->Add(raw_instances[i]));
792 }
793 return JDWP::ERR_NONE;
794}
795
Elliott Hughes0cbaff52013-01-16 15:28:01 -0800796JDWP::JdwpError Dbg::GetReferringObjects(JDWP::ObjectId object_id, int32_t max_count,
797 std::vector<JDWP::ObjectId>& referring_objects)
798 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800799 mirror::Object* o = gRegistry->Get<mirror::Object*>(object_id);
Elliott Hughes64f574f2013-02-20 14:57:12 -0800800 if (o == NULL || o == ObjectRegistry::kInvalidObject) {
Elliott Hughes0cbaff52013-01-16 15:28:01 -0800801 return JDWP::ERR_INVALID_OBJECT;
802 }
803
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800804 std::vector<mirror::Object*> raw_instances;
Elliott Hughes0cbaff52013-01-16 15:28:01 -0800805 Runtime::Current()->GetHeap()->GetReferringObjects(o, max_count, raw_instances);
806 for (size_t i = 0; i < raw_instances.size(); ++i) {
807 referring_objects.push_back(gRegistry->Add(raw_instances[i]));
808 }
809 return JDWP::ERR_NONE;
810}
811
Elliott Hughes64f574f2013-02-20 14:57:12 -0800812JDWP::JdwpError Dbg::DisableCollection(JDWP::ObjectId object_id)
813 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
814 gRegistry->DisableCollection(object_id);
815 return JDWP::ERR_NONE;
816}
817
818JDWP::JdwpError Dbg::EnableCollection(JDWP::ObjectId object_id)
819 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
820 gRegistry->EnableCollection(object_id);
821 return JDWP::ERR_NONE;
822}
823
824JDWP::JdwpError Dbg::IsCollected(JDWP::ObjectId object_id, bool& is_collected)
825 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
826 is_collected = gRegistry->IsCollected(object_id);
827 return JDWP::ERR_NONE;
828}
829
830void Dbg::DisposeObject(JDWP::ObjectId object_id, uint32_t reference_count)
831 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
832 gRegistry->DisposeObject(object_id, reference_count);
833}
834
Elliott Hughes88d63092013-01-09 09:55:54 -0800835JDWP::JdwpError Dbg::GetReflectedType(JDWP::RefTypeId class_id, JDWP::ExpandBuf* pReply) {
Elliott Hughes436e3722012-02-17 20:01:47 -0800836 JDWP::JdwpError status;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800837 mirror::Class* c = DecodeClass(class_id, status);
Elliott Hughes436e3722012-02-17 20:01:47 -0800838 if (c == NULL) {
839 return status;
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -0800840 }
Elliott Hughes436e3722012-02-17 20:01:47 -0800841
842 expandBufAdd1(pReply, c->IsInterface() ? JDWP::TT_INTERFACE : JDWP::TT_CLASS);
Elliott Hughes88d63092013-01-09 09:55:54 -0800843 expandBufAddRefTypeId(pReply, class_id);
Elliott Hughes436e3722012-02-17 20:01:47 -0800844 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700845}
846
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -0800847void Dbg::GetClassList(std::vector<JDWP::RefTypeId>& classes) {
Elliott Hughesa2155262011-11-16 16:26:58 -0800848 // Get the complete list of reference classes (i.e. all classes except
849 // the primitive types).
850 // Returns a newly-allocated buffer full of RefTypeId values.
851 struct ClassListCreator {
Elliott Hughesba8eee12012-01-24 20:25:24 -0800852 explicit ClassListCreator(std::vector<JDWP::RefTypeId>& classes) : classes(classes) {
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -0800853 }
854
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800855 static bool Visit(mirror::Class* c, void* arg) {
Elliott Hughesa2155262011-11-16 16:26:58 -0800856 return reinterpret_cast<ClassListCreator*>(arg)->Visit(c);
857 }
858
Elliott Hughes64f574f2013-02-20 14:57:12 -0800859 // TODO: Enable annotalysis. We know lock is held in constructor, but abstraction confuses
860 // annotalysis.
861 bool Visit(mirror::Class* c) NO_THREAD_SAFETY_ANALYSIS {
Elliott Hughesa2155262011-11-16 16:26:58 -0800862 if (!c->IsPrimitive()) {
Elliott Hughes64f574f2013-02-20 14:57:12 -0800863 classes.push_back(gRegistry->AddRefType(c));
Elliott Hughesa2155262011-11-16 16:26:58 -0800864 }
865 return true;
866 }
867
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -0800868 std::vector<JDWP::RefTypeId>& classes;
Elliott Hughesa2155262011-11-16 16:26:58 -0800869 };
870
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -0800871 ClassListCreator clc(classes);
Elliott Hughesa2155262011-11-16 16:26:58 -0800872 Runtime::Current()->GetClassLinker()->VisitClasses(ClassListCreator::Visit, &clc);
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700873}
874
Elliott Hughes88d63092013-01-09 09:55:54 -0800875JDWP::JdwpError Dbg::GetClassInfo(JDWP::RefTypeId class_id, JDWP::JdwpTypeTag* pTypeTag, uint32_t* pStatus, std::string* pDescriptor) {
Elliott Hughes436e3722012-02-17 20:01:47 -0800876 JDWP::JdwpError status;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800877 mirror::Class* c = DecodeClass(class_id, status);
Elliott Hughes436e3722012-02-17 20:01:47 -0800878 if (c == NULL) {
879 return status;
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -0800880 }
881
Elliott Hughesa2155262011-11-16 16:26:58 -0800882 if (c->IsArrayClass()) {
883 *pStatus = JDWP::CS_VERIFIED | JDWP::CS_PREPARED;
884 *pTypeTag = JDWP::TT_ARRAY;
885 } else {
886 if (c->IsErroneous()) {
887 *pStatus = JDWP::CS_ERROR;
888 } else {
889 *pStatus = JDWP::CS_VERIFIED | JDWP::CS_PREPARED | JDWP::CS_INITIALIZED;
890 }
891 *pTypeTag = c->IsInterface() ? JDWP::TT_INTERFACE : JDWP::TT_CLASS;
892 }
893
894 if (pDescriptor != NULL) {
Ian Rogersdfb325e2013-10-30 01:00:44 -0700895 *pDescriptor = ClassHelper(c).GetDescriptor();
Elliott Hughesa2155262011-11-16 16:26:58 -0800896 }
Elliott Hughes436e3722012-02-17 20:01:47 -0800897 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700898}
899
Elliott Hughesc3b77c72011-12-15 20:56:48 -0800900void Dbg::FindLoadedClassBySignature(const char* descriptor, std::vector<JDWP::RefTypeId>& ids) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800901 std::vector<mirror::Class*> classes;
Elliott Hughes6fa602d2011-12-02 17:54:25 -0800902 Runtime::Current()->GetClassLinker()->LookupClasses(descriptor, classes);
903 ids.clear();
904 for (size_t i = 0; i < classes.size(); ++i) {
905 ids.push_back(gRegistry->Add(classes[i]));
906 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700907}
908
Elliott Hughes64f574f2013-02-20 14:57:12 -0800909JDWP::JdwpError Dbg::GetReferenceType(JDWP::ObjectId object_id, JDWP::ExpandBuf* pReply)
910 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800911 mirror::Object* o = gRegistry->Get<mirror::Object*>(object_id);
Elliott Hughes64f574f2013-02-20 14:57:12 -0800912 if (o == NULL || o == ObjectRegistry::kInvalidObject) {
Elliott Hughes2435a572012-02-17 16:07:41 -0800913 return JDWP::ERR_INVALID_OBJECT;
Elliott Hughes499c5132011-11-17 14:55:11 -0800914 }
Elliott Hughes2435a572012-02-17 16:07:41 -0800915
916 JDWP::JdwpTypeTag type_tag;
917 if (o->GetClass()->IsArrayClass()) {
918 type_tag = JDWP::TT_ARRAY;
919 } else if (o->GetClass()->IsInterface()) {
920 type_tag = JDWP::TT_INTERFACE;
921 } else {
922 type_tag = JDWP::TT_CLASS;
923 }
Elliott Hughes64f574f2013-02-20 14:57:12 -0800924 JDWP::RefTypeId type_id = gRegistry->AddRefType(o->GetClass());
Elliott Hughes2435a572012-02-17 16:07:41 -0800925
926 expandBufAdd1(pReply, type_tag);
927 expandBufAddRefTypeId(pReply, type_id);
928
929 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700930}
931
Ian Rogersfc0e94b2013-09-23 23:51:32 -0700932JDWP::JdwpError Dbg::GetSignature(JDWP::RefTypeId class_id, std::string* signature) {
Elliott Hughes1fe7afb2012-02-13 17:23:03 -0800933 JDWP::JdwpError status;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800934 mirror::Class* c = DecodeClass(class_id, status);
Elliott Hughes1fe7afb2012-02-13 17:23:03 -0800935 if (c == NULL) {
936 return status;
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -0800937 }
Ian Rogersdfb325e2013-10-30 01:00:44 -0700938 *signature = ClassHelper(c).GetDescriptor();
Elliott Hughes1fe7afb2012-02-13 17:23:03 -0800939 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700940}
941
Elliott Hughes88d63092013-01-09 09:55:54 -0800942JDWP::JdwpError Dbg::GetSourceFile(JDWP::RefTypeId class_id, std::string& result) {
Elliott Hughes436e3722012-02-17 20:01:47 -0800943 JDWP::JdwpError status;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800944 mirror::Class* c = DecodeClass(class_id, status);
Elliott Hughes436e3722012-02-17 20:01:47 -0800945 if (c == NULL) {
946 return status;
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -0800947 }
Elliott Hughes436e3722012-02-17 20:01:47 -0800948 result = ClassHelper(c).GetSourceFile();
949 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700950}
951
Elliott Hughes88d63092013-01-09 09:55:54 -0800952JDWP::JdwpError Dbg::GetObjectTag(JDWP::ObjectId object_id, uint8_t& tag) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800953 mirror::Object* o = gRegistry->Get<mirror::Object*>(object_id);
Elliott Hughes64f574f2013-02-20 14:57:12 -0800954 if (o == ObjectRegistry::kInvalidObject) {
Elliott Hughes546b9862012-06-20 16:06:13 -0700955 return JDWP::ERR_INVALID_OBJECT;
956 }
957 tag = TagFromObject(o);
958 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700959}
960
Elliott Hughesaed4be92011-12-02 16:16:23 -0800961size_t Dbg::GetTagWidth(JDWP::JdwpTag tag) {
Elliott Hughesdbb40792011-11-18 17:05:22 -0800962 switch (tag) {
963 case JDWP::JT_VOID:
964 return 0;
965 case JDWP::JT_BYTE:
966 case JDWP::JT_BOOLEAN:
967 return 1;
968 case JDWP::JT_CHAR:
969 case JDWP::JT_SHORT:
970 return 2;
971 case JDWP::JT_FLOAT:
972 case JDWP::JT_INT:
973 return 4;
974 case JDWP::JT_ARRAY:
975 case JDWP::JT_OBJECT:
976 case JDWP::JT_STRING:
977 case JDWP::JT_THREAD:
978 case JDWP::JT_THREAD_GROUP:
979 case JDWP::JT_CLASS_LOADER:
980 case JDWP::JT_CLASS_OBJECT:
981 return sizeof(JDWP::ObjectId);
982 case JDWP::JT_DOUBLE:
983 case JDWP::JT_LONG:
984 return 8;
985 default:
Elliott Hughes3d30d9b2011-12-07 17:35:48 -0800986 LOG(FATAL) << "Unknown tag " << tag;
Elliott Hughesdbb40792011-11-18 17:05:22 -0800987 return -1;
988 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700989}
990
Elliott Hughes88d63092013-01-09 09:55:54 -0800991JDWP::JdwpError Dbg::GetArrayLength(JDWP::ObjectId array_id, int& length) {
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -0800992 JDWP::JdwpError status;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800993 mirror::Array* a = DecodeArray(array_id, status);
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -0800994 if (a == NULL) {
995 return status;
Elliott Hughes24437992011-11-30 14:49:33 -0800996 }
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -0800997 length = a->GetLength();
998 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700999}
1000
Elliott Hughes88d63092013-01-09 09:55:54 -08001001JDWP::JdwpError Dbg::OutputArray(JDWP::ObjectId array_id, int offset, int count, JDWP::ExpandBuf* pReply) {
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -08001002 JDWP::JdwpError status;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001003 mirror::Array* a = DecodeArray(array_id, status);
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -08001004 if (a == NULL) {
1005 return status;
1006 }
Elliott Hughes24437992011-11-30 14:49:33 -08001007
1008 if (offset < 0 || count < 0 || offset > a->GetLength() || a->GetLength() - offset < count) {
1009 LOG(WARNING) << __FUNCTION__ << " access out of bounds: offset=" << offset << "; count=" << count;
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -08001010 return JDWP::ERR_INVALID_LENGTH;
Elliott Hughes24437992011-11-30 14:49:33 -08001011 }
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001012 std::string descriptor(ClassHelper(a->GetClass()).GetDescriptor());
Elliott Hughes24437992011-11-30 14:49:33 -08001013 JDWP::JdwpTag tag = BasicTagFromDescriptor(descriptor.c_str() + 1);
1014
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -08001015 expandBufAdd1(pReply, tag);
1016 expandBufAdd4BE(pReply, count);
1017
Elliott Hughes24437992011-11-30 14:49:33 -08001018 if (IsPrimitiveTag(tag)) {
1019 size_t width = GetTagWidth(tag);
Elliott Hughes24437992011-11-30 14:49:33 -08001020 uint8_t* dst = expandBufAddSpace(pReply, count * width);
1021 if (width == 8) {
Ian Rogersa15e67d2012-02-28 13:51:55 -08001022 const uint64_t* src8 = reinterpret_cast<uint64_t*>(a->GetRawData(sizeof(uint64_t)));
Elliott Hughes24437992011-11-30 14:49:33 -08001023 for (int i = 0; i < count; ++i) JDWP::Write8BE(&dst, src8[offset + i]);
1024 } else if (width == 4) {
Ian Rogersa15e67d2012-02-28 13:51:55 -08001025 const uint32_t* src4 = reinterpret_cast<uint32_t*>(a->GetRawData(sizeof(uint32_t)));
Elliott Hughes24437992011-11-30 14:49:33 -08001026 for (int i = 0; i < count; ++i) JDWP::Write4BE(&dst, src4[offset + i]);
1027 } else if (width == 2) {
Ian Rogersa15e67d2012-02-28 13:51:55 -08001028 const uint16_t* src2 = reinterpret_cast<uint16_t*>(a->GetRawData(sizeof(uint16_t)));
Elliott Hughes24437992011-11-30 14:49:33 -08001029 for (int i = 0; i < count; ++i) JDWP::Write2BE(&dst, src2[offset + i]);
1030 } else {
Ian Rogersa15e67d2012-02-28 13:51:55 -08001031 const uint8_t* src = reinterpret_cast<uint8_t*>(a->GetRawData(sizeof(uint8_t)));
Elliott Hughes24437992011-11-30 14:49:33 -08001032 memcpy(dst, &src[offset * width], count * width);
1033 }
1034 } else {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001035 mirror::ObjectArray<mirror::Object>* oa = a->AsObjectArray<mirror::Object>();
Elliott Hughes24437992011-11-30 14:49:33 -08001036 for (int i = 0; i < count; ++i) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001037 mirror::Object* element = oa->Get(offset + i);
Elliott Hughes24437992011-11-30 14:49:33 -08001038 JDWP::JdwpTag specific_tag = (element != NULL) ? TagFromObject(element) : tag;
1039 expandBufAdd1(pReply, specific_tag);
1040 expandBufAddObjectId(pReply, gRegistry->Add(element));
1041 }
1042 }
1043
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -08001044 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001045}
1046
Elliott Hughes4b9702c2013-02-20 18:13:24 -08001047template <typename T> void CopyArrayData(mirror::Array* a, JDWP::Request& src, int offset, int count) {
1048 DCHECK(a->GetClass()->IsPrimitiveArray());
1049
1050 T* dst = &(reinterpret_cast<T*>(a->GetRawData(sizeof(T)))[offset * sizeof(T)]);
1051 for (int i = 0; i < count; ++i) {
1052 *dst++ = src.ReadValue(sizeof(T));
1053 }
1054}
1055
Elliott Hughes88d63092013-01-09 09:55:54 -08001056JDWP::JdwpError Dbg::SetArrayElements(JDWP::ObjectId array_id, int offset, int count,
Elliott Hughes4b9702c2013-02-20 18:13:24 -08001057 JDWP::Request& request)
Ian Rogersb726dcb2012-09-05 08:57:23 -07001058 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -08001059 JDWP::JdwpError status;
Elliott Hughes4b9702c2013-02-20 18:13:24 -08001060 mirror::Array* dst = DecodeArray(array_id, status);
1061 if (dst == NULL) {
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -08001062 return status;
1063 }
Elliott Hughesf03b8f62011-12-02 14:26:25 -08001064
Elliott Hughes4b9702c2013-02-20 18:13:24 -08001065 if (offset < 0 || count < 0 || offset > dst->GetLength() || dst->GetLength() - offset < count) {
Elliott Hughesf03b8f62011-12-02 14:26:25 -08001066 LOG(WARNING) << __FUNCTION__ << " access out of bounds: offset=" << offset << "; count=" << count;
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -08001067 return JDWP::ERR_INVALID_LENGTH;
Elliott Hughesf03b8f62011-12-02 14:26:25 -08001068 }
Ian Rogersfc0e94b2013-09-23 23:51:32 -07001069 const char* descriptor = ClassHelper(dst->GetClass()).GetDescriptor();
1070 JDWP::JdwpTag tag = BasicTagFromDescriptor(descriptor + 1);
Elliott Hughesf03b8f62011-12-02 14:26:25 -08001071
1072 if (IsPrimitiveTag(tag)) {
1073 size_t width = GetTagWidth(tag);
Elliott Hughesf03b8f62011-12-02 14:26:25 -08001074 if (width == 8) {
Elliott Hughes4b9702c2013-02-20 18:13:24 -08001075 CopyArrayData<uint64_t>(dst, request, offset, count);
Elliott Hughesf03b8f62011-12-02 14:26:25 -08001076 } else if (width == 4) {
Elliott Hughes4b9702c2013-02-20 18:13:24 -08001077 CopyArrayData<uint32_t>(dst, request, offset, count);
Elliott Hughesf03b8f62011-12-02 14:26:25 -08001078 } else if (width == 2) {
Elliott Hughes4b9702c2013-02-20 18:13:24 -08001079 CopyArrayData<uint16_t>(dst, request, offset, count);
Elliott Hughesf03b8f62011-12-02 14:26:25 -08001080 } else {
Elliott Hughes4b9702c2013-02-20 18:13:24 -08001081 CopyArrayData<uint8_t>(dst, request, offset, count);
Elliott Hughesf03b8f62011-12-02 14:26:25 -08001082 }
1083 } else {
Elliott Hughes4b9702c2013-02-20 18:13:24 -08001084 mirror::ObjectArray<mirror::Object>* oa = dst->AsObjectArray<mirror::Object>();
Elliott Hughesf03b8f62011-12-02 14:26:25 -08001085 for (int i = 0; i < count; ++i) {
Elliott Hughes4b9702c2013-02-20 18:13:24 -08001086 JDWP::ObjectId id = request.ReadObjectId();
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001087 mirror::Object* o = gRegistry->Get<mirror::Object*>(id);
Elliott Hughes64f574f2013-02-20 14:57:12 -08001088 if (o == ObjectRegistry::kInvalidObject) {
Elliott Hughes436e3722012-02-17 20:01:47 -08001089 return JDWP::ERR_INVALID_OBJECT;
1090 }
1091 oa->Set(offset + i, o);
Elliott Hughesf03b8f62011-12-02 14:26:25 -08001092 }
1093 }
1094
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -08001095 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001096}
1097
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -08001098JDWP::ObjectId Dbg::CreateString(const std::string& str) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001099 return gRegistry->Add(mirror::String::AllocFromModifiedUtf8(Thread::Current(), str.c_str()));
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001100}
1101
Elliott Hughes88d63092013-01-09 09:55:54 -08001102JDWP::JdwpError Dbg::CreateObject(JDWP::RefTypeId class_id, JDWP::ObjectId& new_object) {
Elliott Hughes436e3722012-02-17 20:01:47 -08001103 JDWP::JdwpError status;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001104 mirror::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 }
Ian Rogers50b35e22012-10-04 10:09:15 -07001108 new_object = gRegistry->Add(c->AllocObject(Thread::Current()));
Elliott Hughes436e3722012-02-17 20:01:47 -08001109 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001110}
1111
Elliott Hughesbf13d362011-12-08 15:51:37 -08001112/*
1113 * Used by Eclipse's "Display" view to evaluate "new byte[5]" to get "(byte[]) [0, 0, 0, 0, 0]".
1114 */
Elliott Hughes88d63092013-01-09 09:55:54 -08001115JDWP::JdwpError Dbg::CreateArrayObject(JDWP::RefTypeId array_class_id, uint32_t length,
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001116 JDWP::ObjectId& new_array) {
Elliott Hughes436e3722012-02-17 20:01:47 -08001117 JDWP::JdwpError status;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001118 mirror::Class* c = DecodeClass(array_class_id, status);
Elliott Hughes436e3722012-02-17 20:01:47 -08001119 if (c == NULL) {
1120 return status;
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -08001121 }
Mathieu Chartier590fee92013-09-13 13:46:47 -07001122 new_array = gRegistry->Add(
1123 mirror::Array::Alloc<kMovingCollector, true>(Thread::Current(), c, length));
Elliott Hughes436e3722012-02-17 20:01:47 -08001124 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001125}
1126
Elliott Hughes88d63092013-01-09 09:55:54 -08001127bool Dbg::MatchType(JDWP::RefTypeId instance_class_id, JDWP::RefTypeId class_id) {
Elliott Hughes436e3722012-02-17 20:01:47 -08001128 JDWP::JdwpError status;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001129 mirror::Class* c1 = DecodeClass(instance_class_id, status);
Elliott Hughesa656a0f2012-02-21 18:03:44 -08001130 CHECK(c1 != NULL);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001131 mirror::Class* c2 = DecodeClass(class_id, status);
Elliott Hughesa656a0f2012-02-21 18:03:44 -08001132 CHECK(c2 != NULL);
1133 return c1->IsAssignableFrom(c2);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001134}
1135
Brian Carlstromea46f952013-07-30 01:26:50 -07001136static JDWP::FieldId ToFieldId(const mirror::ArtField* f)
Ian Rogersb726dcb2012-09-05 08:57:23 -07001137 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Mathieu Chartier590fee92013-09-13 13:46:47 -07001138 CHECK(!kMovingFields);
Elliott Hughes03181a82011-11-17 17:22:21 -08001139 return static_cast<JDWP::FieldId>(reinterpret_cast<uintptr_t>(f));
Elliott Hughes03181a82011-11-17 17:22:21 -08001140}
1141
Brian Carlstromea46f952013-07-30 01:26:50 -07001142static JDWP::MethodId ToMethodId(const mirror::ArtMethod* m)
Ian Rogersb726dcb2012-09-05 08:57:23 -07001143 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Mathieu Chartier590fee92013-09-13 13:46:47 -07001144 CHECK(!kMovingMethods);
Elliott Hughes03181a82011-11-17 17:22:21 -08001145 return static_cast<JDWP::MethodId>(reinterpret_cast<uintptr_t>(m));
Elliott Hughes03181a82011-11-17 17:22:21 -08001146}
1147
Brian Carlstromea46f952013-07-30 01:26:50 -07001148static mirror::ArtField* FromFieldId(JDWP::FieldId fid)
Ian Rogersb726dcb2012-09-05 08:57:23 -07001149 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Mathieu Chartier590fee92013-09-13 13:46:47 -07001150 CHECK(!kMovingFields);
Brian Carlstromea46f952013-07-30 01:26:50 -07001151 return reinterpret_cast<mirror::ArtField*>(static_cast<uintptr_t>(fid));
Elliott Hughesaed4be92011-12-02 16:16:23 -08001152}
1153
Brian Carlstromea46f952013-07-30 01:26:50 -07001154static mirror::ArtMethod* FromMethodId(JDWP::MethodId mid)
Ian Rogersb726dcb2012-09-05 08:57:23 -07001155 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Mathieu Chartier590fee92013-09-13 13:46:47 -07001156 CHECK(!kMovingMethods);
Brian Carlstromea46f952013-07-30 01:26:50 -07001157 return reinterpret_cast<mirror::ArtMethod*>(static_cast<uintptr_t>(mid));
Elliott Hughes03181a82011-11-17 17:22:21 -08001158}
1159
Brian Carlstromea46f952013-07-30 01:26:50 -07001160static void SetLocation(JDWP::JdwpLocation& location, mirror::ArtMethod* m, uint32_t dex_pc)
Ian Rogersb726dcb2012-09-05 08:57:23 -07001161 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08001162 if (m == NULL) {
1163 memset(&location, 0, sizeof(location));
1164 } else {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001165 mirror::Class* c = m->GetDeclaringClass();
Elliott Hughes74847412012-06-20 18:10:21 -07001166 location.type_tag = c->IsInterface() ? JDWP::TT_INTERFACE : JDWP::TT_CLASS;
1167 location.class_id = gRegistry->Add(c);
1168 location.method_id = ToMethodId(m);
Ian Rogers0399dde2012-06-06 17:09:28 -07001169 location.dex_pc = dex_pc;
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08001170 }
Elliott Hughesd07986f2011-12-06 18:27:45 -08001171}
1172
Elliott Hughesa96836a2013-01-17 12:27:49 -08001173std::string Dbg::GetMethodName(JDWP::MethodId method_id)
Ian Rogersb726dcb2012-09-05 08:57:23 -07001174 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Brian Carlstromea46f952013-07-30 01:26:50 -07001175 mirror::ArtMethod* m = FromMethodId(method_id);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001176 return MethodHelper(m).GetName();
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001177}
1178
Elliott Hughesa96836a2013-01-17 12:27:49 -08001179std::string Dbg::GetFieldName(JDWP::FieldId field_id)
1180 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Brian Carlstromea46f952013-07-30 01:26:50 -07001181 mirror::ArtField* f = FromFieldId(field_id);
Elliott Hughesa96836a2013-01-17 12:27:49 -08001182 return FieldHelper(f).GetName();
1183}
1184
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001185/*
1186 * Augment the access flags for synthetic methods and fields by setting
1187 * the (as described by the spec) "0xf0000000 bit". Also, strip out any
1188 * flags not specified by the Java programming language.
1189 */
1190static uint32_t MangleAccessFlags(uint32_t accessFlags) {
1191 accessFlags &= kAccJavaFlagsMask;
1192 if ((accessFlags & kAccSynthetic) != 0) {
1193 accessFlags |= 0xf0000000;
1194 }
1195 return accessFlags;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001196}
1197
Elliott Hughesdbb40792011-11-18 17:05:22 -08001198static const uint16_t kEclipseWorkaroundSlot = 1000;
1199
1200/*
1201 * Eclipse appears to expect that the "this" reference is in slot zero.
1202 * If it's not, the "variables" display will show two copies of "this",
1203 * possibly because it gets "this" from SF.ThisObject and then displays
1204 * all locals with nonzero slot numbers.
1205 *
1206 * So, we remap the item in slot 0 to 1000, and remap "this" to zero. On
1207 * SF.GetValues / SF.SetValues we map them back.
Elliott Hughesc5b734a2011-12-01 17:20:58 -08001208 *
1209 * TODO: jdb uses the value to determine whether a variable is a local or an argument,
1210 * by checking whether it's less than the number of arguments. To make that work, we'd
1211 * have to "mangle" all the arguments to come first, not just the implicit argument 'this'.
Elliott Hughesdbb40792011-11-18 17:05:22 -08001212 */
1213static uint16_t MangleSlot(uint16_t slot, const char* name) {
1214 uint16_t newSlot = slot;
1215 if (strcmp(name, "this") == 0) {
1216 newSlot = 0;
1217 } else if (slot == 0) {
1218 newSlot = kEclipseWorkaroundSlot;
1219 }
1220 return newSlot;
1221}
1222
Brian Carlstromea46f952013-07-30 01:26:50 -07001223static uint16_t DemangleSlot(uint16_t slot, mirror::ArtMethod* m)
Ian Rogersb726dcb2012-09-05 08:57:23 -07001224 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Elliott Hughesdbb40792011-11-18 17:05:22 -08001225 if (slot == kEclipseWorkaroundSlot) {
Elliott Hughes68fdbd02011-11-29 19:22:47 -08001226 return 0;
Elliott Hughesdbb40792011-11-18 17:05:22 -08001227 } else if (slot == 0) {
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08001228 const DexFile::CodeItem* code_item = MethodHelper(m).GetCodeItem();
Elliott Hughescaf76542012-06-28 16:08:22 -07001229 CHECK(code_item != NULL) << PrettyMethod(m);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001230 return code_item->registers_size_ - code_item->ins_size_;
Elliott Hughesdbb40792011-11-18 17:05:22 -08001231 }
Elliott Hughes68fdbd02011-11-29 19:22:47 -08001232 return slot;
Elliott Hughesdbb40792011-11-18 17:05:22 -08001233}
1234
Elliott Hughes88d63092013-01-09 09:55:54 -08001235JDWP::JdwpError Dbg::OutputDeclaredFields(JDWP::RefTypeId class_id, bool with_generic, JDWP::ExpandBuf* pReply) {
Elliott Hughes436e3722012-02-17 20:01:47 -08001236 JDWP::JdwpError status;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001237 mirror::Class* c = DecodeClass(class_id, status);
Elliott Hughes436e3722012-02-17 20:01:47 -08001238 if (c == NULL) {
1239 return status;
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -08001240 }
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001241
1242 size_t instance_field_count = c->NumInstanceFields();
1243 size_t static_field_count = c->NumStaticFields();
1244
1245 expandBufAdd4BE(pReply, instance_field_count + static_field_count);
1246
1247 for (size_t i = 0; i < instance_field_count + static_field_count; ++i) {
Brian Carlstromea46f952013-07-30 01:26:50 -07001248 mirror::ArtField* f = (i < instance_field_count) ? c->GetInstanceField(i) : c->GetStaticField(i - instance_field_count);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001249 FieldHelper fh(f);
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001250 expandBufAddFieldId(pReply, ToFieldId(f));
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001251 expandBufAddUtf8String(pReply, fh.GetName());
1252 expandBufAddUtf8String(pReply, fh.GetTypeDescriptor());
Elliott Hughesc5b734a2011-12-01 17:20:58 -08001253 if (with_generic) {
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001254 static const char genericSignature[1] = "";
1255 expandBufAddUtf8String(pReply, genericSignature);
1256 }
1257 expandBufAdd4BE(pReply, MangleAccessFlags(f->GetAccessFlags()));
1258 }
Elliott Hughes436e3722012-02-17 20:01:47 -08001259 return JDWP::ERR_NONE;
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001260}
1261
Elliott Hughes88d63092013-01-09 09:55:54 -08001262JDWP::JdwpError Dbg::OutputDeclaredMethods(JDWP::RefTypeId class_id, bool with_generic,
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001263 JDWP::ExpandBuf* pReply) {
Elliott Hughes436e3722012-02-17 20:01:47 -08001264 JDWP::JdwpError status;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001265 mirror::Class* c = DecodeClass(class_id, status);
Elliott Hughes436e3722012-02-17 20:01:47 -08001266 if (c == NULL) {
1267 return status;
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -08001268 }
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001269
1270 size_t direct_method_count = c->NumDirectMethods();
1271 size_t virtual_method_count = c->NumVirtualMethods();
1272
1273 expandBufAdd4BE(pReply, direct_method_count + virtual_method_count);
1274
1275 for (size_t i = 0; i < direct_method_count + virtual_method_count; ++i) {
Brian Carlstromea46f952013-07-30 01:26:50 -07001276 mirror::ArtMethod* m = (i < direct_method_count) ? c->GetDirectMethod(i) : c->GetVirtualMethod(i - direct_method_count);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001277 MethodHelper mh(m);
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001278 expandBufAddMethodId(pReply, ToMethodId(m));
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001279 expandBufAddUtf8String(pReply, mh.GetName());
Ian Rogersd91d6d62013-09-25 20:26:14 -07001280 expandBufAddUtf8String(pReply, mh.GetSignature().ToString());
Elliott Hughesc5b734a2011-12-01 17:20:58 -08001281 if (with_generic) {
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001282 static const char genericSignature[1] = "";
1283 expandBufAddUtf8String(pReply, genericSignature);
1284 }
1285 expandBufAdd4BE(pReply, MangleAccessFlags(m->GetAccessFlags()));
1286 }
Elliott Hughes436e3722012-02-17 20:01:47 -08001287 return JDWP::ERR_NONE;
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001288}
1289
Elliott Hughes88d63092013-01-09 09:55:54 -08001290JDWP::JdwpError Dbg::OutputDeclaredInterfaces(JDWP::RefTypeId class_id, JDWP::ExpandBuf* pReply) {
Elliott Hughes436e3722012-02-17 20:01:47 -08001291 JDWP::JdwpError status;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001292 mirror::Class* c = DecodeClass(class_id, status);
Elliott Hughes436e3722012-02-17 20:01:47 -08001293 if (c == NULL) {
1294 return status;
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -08001295 }
Elliott Hughes436e3722012-02-17 20:01:47 -08001296
1297 ClassHelper kh(c);
Ian Rogersd24e2642012-06-06 21:21:43 -07001298 size_t interface_count = kh.NumDirectInterfaces();
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001299 expandBufAdd4BE(pReply, interface_count);
1300 for (size_t i = 0; i < interface_count; ++i) {
Elliott Hughes64f574f2013-02-20 14:57:12 -08001301 expandBufAddRefTypeId(pReply, gRegistry->AddRefType(kh.GetDirectInterface(i)));
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001302 }
Elliott Hughes436e3722012-02-17 20:01:47 -08001303 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001304}
1305
Elliott Hughes88d63092013-01-09 09:55:54 -08001306void Dbg::OutputLineTable(JDWP::RefTypeId, JDWP::MethodId method_id, JDWP::ExpandBuf* pReply)
Ian Rogersb726dcb2012-09-05 08:57:23 -07001307 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Elliott Hughes03181a82011-11-17 17:22:21 -08001308 struct DebugCallbackContext {
1309 int numItems;
1310 JDWP::ExpandBuf* pReply;
1311
Elliott Hughes2435a572012-02-17 16:07:41 -08001312 static bool Callback(void* context, uint32_t address, uint32_t line_number) {
Elliott Hughes03181a82011-11-17 17:22:21 -08001313 DebugCallbackContext* pContext = reinterpret_cast<DebugCallbackContext*>(context);
1314 expandBufAdd8BE(pContext->pReply, address);
Elliott Hughes2435a572012-02-17 16:07:41 -08001315 expandBufAdd4BE(pContext->pReply, line_number);
Elliott Hughes03181a82011-11-17 17:22:21 -08001316 pContext->numItems++;
Sebastien Hertzf2910ee2013-10-19 16:39:24 +02001317 return false;
Elliott Hughes03181a82011-11-17 17:22:21 -08001318 }
1319 };
Brian Carlstromea46f952013-07-30 01:26:50 -07001320 mirror::ArtMethod* m = FromMethodId(method_id);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001321 MethodHelper mh(m);
Elliott Hughes03181a82011-11-17 17:22:21 -08001322 uint64_t start, end;
1323 if (m->IsNative()) {
1324 start = -1;
1325 end = -1;
1326 } else {
1327 start = 0;
jeffhao14f0db92012-12-14 17:50:42 -08001328 // Return the index of the last instruction
1329 end = mh.GetCodeItem()->insns_size_in_code_units_ - 1;
Elliott Hughes03181a82011-11-17 17:22:21 -08001330 }
1331
1332 expandBufAdd8BE(pReply, start);
1333 expandBufAdd8BE(pReply, end);
1334
1335 // Add numLines later
1336 size_t numLinesOffset = expandBufGetLength(pReply);
1337 expandBufAdd4BE(pReply, 0);
1338
1339 DebugCallbackContext context;
1340 context.numItems = 0;
1341 context.pReply = pReply;
1342
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001343 mh.GetDexFile().DecodeDebugInfo(mh.GetCodeItem(), m->IsStatic(), m->GetDexMethodIndex(),
1344 DebugCallbackContext::Callback, NULL, &context);
Elliott Hughes03181a82011-11-17 17:22:21 -08001345
1346 JDWP::Set4BE(expandBufGetBuffer(pReply) + numLinesOffset, context.numItems);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001347}
1348
Elliott Hughes88d63092013-01-09 09:55:54 -08001349void Dbg::OutputVariableTable(JDWP::RefTypeId, JDWP::MethodId method_id, bool with_generic, JDWP::ExpandBuf* pReply) {
Elliott Hughesdbb40792011-11-18 17:05:22 -08001350 struct DebugCallbackContext {
Elliott Hughesdbb40792011-11-18 17:05:22 -08001351 JDWP::ExpandBuf* pReply;
Elliott Hughesc5b734a2011-12-01 17:20:58 -08001352 size_t variable_count;
1353 bool with_generic;
Elliott Hughesdbb40792011-11-18 17:05:22 -08001354
Elliott Hughesc5b734a2011-12-01 17:20:58 -08001355 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 -08001356 DebugCallbackContext* pContext = reinterpret_cast<DebugCallbackContext*>(context);
1357
Elliott Hughesad3da692012-02-24 16:51:35 -08001358 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 -08001359
Elliott Hughes68fdbd02011-11-29 19:22:47 -08001360 slot = MangleSlot(slot, name);
1361
Elliott Hughesdbb40792011-11-18 17:05:22 -08001362 expandBufAdd8BE(pContext->pReply, startAddress);
1363 expandBufAddUtf8String(pContext->pReply, name);
1364 expandBufAddUtf8String(pContext->pReply, descriptor);
Elliott Hughesc5b734a2011-12-01 17:20:58 -08001365 if (pContext->with_generic) {
Elliott Hughesdbb40792011-11-18 17:05:22 -08001366 expandBufAddUtf8String(pContext->pReply, signature);
1367 }
1368 expandBufAdd4BE(pContext->pReply, endAddress - startAddress);
1369 expandBufAdd4BE(pContext->pReply, slot);
1370
Elliott Hughesc5b734a2011-12-01 17:20:58 -08001371 ++pContext->variable_count;
Elliott Hughesdbb40792011-11-18 17:05:22 -08001372 }
1373 };
Brian Carlstromea46f952013-07-30 01:26:50 -07001374 mirror::ArtMethod* m = FromMethodId(method_id);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001375 MethodHelper mh(m);
1376 const DexFile::CodeItem* code_item = mh.GetCodeItem();
Elliott Hughesdbb40792011-11-18 17:05:22 -08001377
Elliott Hughesc5b734a2011-12-01 17:20:58 -08001378 // arg_count considers doubles and longs to take 2 units.
1379 // variable_count considers everything to take 1 unit.
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001380 std::string shorty(mh.GetShorty());
Brian Carlstromea46f952013-07-30 01:26:50 -07001381 expandBufAdd4BE(pReply, mirror::ArtMethod::NumArgRegisters(shorty));
Elliott Hughesdbb40792011-11-18 17:05:22 -08001382
Elliott Hughesc5b734a2011-12-01 17:20:58 -08001383 // We don't know the total number of variables yet, so leave a blank and update it later.
1384 size_t variable_count_offset = expandBufGetLength(pReply);
Elliott Hughesdbb40792011-11-18 17:05:22 -08001385 expandBufAdd4BE(pReply, 0);
1386
1387 DebugCallbackContext context;
Elliott Hughesdbb40792011-11-18 17:05:22 -08001388 context.pReply = pReply;
Elliott Hughesc5b734a2011-12-01 17:20:58 -08001389 context.variable_count = 0;
1390 context.with_generic = with_generic;
Elliott Hughesdbb40792011-11-18 17:05:22 -08001391
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001392 mh.GetDexFile().DecodeDebugInfo(code_item, m->IsStatic(), m->GetDexMethodIndex(), NULL,
1393 DebugCallbackContext::Callback, &context);
Elliott Hughesdbb40792011-11-18 17:05:22 -08001394
Elliott Hughesc5b734a2011-12-01 17:20:58 -08001395 JDWP::Set4BE(expandBufGetBuffer(pReply) + variable_count_offset, context.variable_count);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001396}
1397
Elliott Hughes9777ba22013-01-17 09:04:19 -08001398JDWP::JdwpError Dbg::GetBytecodes(JDWP::RefTypeId, JDWP::MethodId method_id,
1399 std::vector<uint8_t>& bytecodes)
1400 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Brian Carlstromea46f952013-07-30 01:26:50 -07001401 mirror::ArtMethod* m = FromMethodId(method_id);
Elliott Hughes9777ba22013-01-17 09:04:19 -08001402 if (m == NULL) {
1403 return JDWP::ERR_INVALID_METHODID;
1404 }
1405 MethodHelper mh(m);
1406 const DexFile::CodeItem* code_item = mh.GetCodeItem();
1407 size_t byte_count = code_item->insns_size_in_code_units_ * 2;
1408 const uint8_t* begin = reinterpret_cast<const uint8_t*>(code_item->insns_);
1409 const uint8_t* end = begin + byte_count;
1410 for (const uint8_t* p = begin; p != end; ++p) {
1411 bytecodes.push_back(*p);
1412 }
1413 return JDWP::ERR_NONE;
1414}
1415
Elliott Hughes88d63092013-01-09 09:55:54 -08001416JDWP::JdwpTag Dbg::GetFieldBasicTag(JDWP::FieldId field_id) {
1417 return BasicTagFromDescriptor(FieldHelper(FromFieldId(field_id)).GetTypeDescriptor());
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001418}
1419
Elliott Hughes88d63092013-01-09 09:55:54 -08001420JDWP::JdwpTag Dbg::GetStaticFieldBasicTag(JDWP::FieldId field_id) {
1421 return BasicTagFromDescriptor(FieldHelper(FromFieldId(field_id)).GetTypeDescriptor());
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001422}
1423
Elliott Hughes88d63092013-01-09 09:55:54 -08001424static JDWP::JdwpError GetFieldValueImpl(JDWP::RefTypeId ref_type_id, JDWP::ObjectId object_id,
1425 JDWP::FieldId field_id, JDWP::ExpandBuf* pReply,
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001426 bool is_static)
Ian Rogersb726dcb2012-09-05 08:57:23 -07001427 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Elliott Hughes0cf74332012-02-23 23:14:00 -08001428 JDWP::JdwpError status;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001429 mirror::Class* c = DecodeClass(ref_type_id, status);
Elliott Hughes88d63092013-01-09 09:55:54 -08001430 if (ref_type_id != 0 && c == NULL) {
Elliott Hughes0cf74332012-02-23 23:14:00 -08001431 return status;
1432 }
1433
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001434 mirror::Object* o = gRegistry->Get<mirror::Object*>(object_id);
Elliott Hughes64f574f2013-02-20 14:57:12 -08001435 if ((!is_static && o == NULL) || o == ObjectRegistry::kInvalidObject) {
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08001436 return JDWP::ERR_INVALID_OBJECT;
1437 }
Brian Carlstromea46f952013-07-30 01:26:50 -07001438 mirror::ArtField* f = FromFieldId(field_id);
Elliott Hughes0cf74332012-02-23 23:14:00 -08001439
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001440 mirror::Class* receiver_class = c;
Elliott Hughes0cf74332012-02-23 23:14:00 -08001441 if (receiver_class == NULL && o != NULL) {
1442 receiver_class = o->GetClass();
1443 }
1444 // TODO: should we give up now if receiver_class is NULL?
1445 if (receiver_class != NULL && !f->GetDeclaringClass()->IsAssignableFrom(receiver_class)) {
1446 LOG(INFO) << "ERR_INVALID_FIELDID: " << PrettyField(f) << " " << PrettyClass(receiver_class);
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08001447 return JDWP::ERR_INVALID_FIELDID;
1448 }
Elliott Hughesaed4be92011-12-02 16:16:23 -08001449
Elliott Hughes0cf74332012-02-23 23:14:00 -08001450 // The RI only enforces the static/non-static mismatch in one direction.
1451 // TODO: should we change the tests and check both?
1452 if (is_static) {
1453 if (!f->IsStatic()) {
1454 return JDWP::ERR_INVALID_FIELDID;
1455 }
1456 } else {
1457 if (f->IsStatic()) {
1458 LOG(WARNING) << "Ignoring non-NULL receiver for ObjectReference.SetValues on static field " << PrettyField(f);
Elliott Hughes0cf74332012-02-23 23:14:00 -08001459 }
1460 }
jeffhao0dfbb7e2012-11-28 15:26:03 -08001461 if (f->IsStatic()) {
1462 o = f->GetDeclaringClass();
1463 }
Elliott Hughes0cf74332012-02-23 23:14:00 -08001464
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001465 JDWP::JdwpTag tag = BasicTagFromDescriptor(FieldHelper(f).GetTypeDescriptor());
Elliott Hughesaed4be92011-12-02 16:16:23 -08001466
1467 if (IsPrimitiveTag(tag)) {
1468 expandBufAdd1(pReply, tag);
1469 if (tag == JDWP::JT_BOOLEAN || tag == JDWP::JT_BYTE) {
1470 expandBufAdd1(pReply, f->Get32(o));
1471 } else if (tag == JDWP::JT_CHAR || tag == JDWP::JT_SHORT) {
1472 expandBufAdd2BE(pReply, f->Get32(o));
1473 } else if (tag == JDWP::JT_FLOAT || tag == JDWP::JT_INT) {
1474 expandBufAdd4BE(pReply, f->Get32(o));
1475 } else if (tag == JDWP::JT_DOUBLE || tag == JDWP::JT_LONG) {
1476 expandBufAdd8BE(pReply, f->Get64(o));
1477 } else {
Elliott Hughes3d30d9b2011-12-07 17:35:48 -08001478 LOG(FATAL) << "Unknown tag: " << tag;
Elliott Hughesaed4be92011-12-02 16:16:23 -08001479 }
1480 } else {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001481 mirror::Object* value = f->GetObject(o);
Elliott Hughesaed4be92011-12-02 16:16:23 -08001482 expandBufAdd1(pReply, TagFromObject(value));
1483 expandBufAddObjectId(pReply, gRegistry->Add(value));
1484 }
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08001485 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001486}
1487
Elliott Hughes88d63092013-01-09 09:55:54 -08001488JDWP::JdwpError Dbg::GetFieldValue(JDWP::ObjectId object_id, JDWP::FieldId field_id,
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001489 JDWP::ExpandBuf* pReply) {
Elliott Hughes88d63092013-01-09 09:55:54 -08001490 return GetFieldValueImpl(0, object_id, field_id, pReply, false);
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08001491}
1492
Elliott Hughes88d63092013-01-09 09:55:54 -08001493JDWP::JdwpError Dbg::GetStaticFieldValue(JDWP::RefTypeId ref_type_id, JDWP::FieldId field_id, JDWP::ExpandBuf* pReply) {
1494 return GetFieldValueImpl(ref_type_id, 0, field_id, pReply, true);
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08001495}
1496
Elliott Hughes88d63092013-01-09 09:55:54 -08001497static JDWP::JdwpError SetFieldValueImpl(JDWP::ObjectId object_id, JDWP::FieldId field_id,
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001498 uint64_t value, int width, bool is_static)
Ian Rogersb726dcb2012-09-05 08:57:23 -07001499 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001500 mirror::Object* o = gRegistry->Get<mirror::Object*>(object_id);
Elliott Hughes64f574f2013-02-20 14:57:12 -08001501 if ((!is_static && o == NULL) || o == ObjectRegistry::kInvalidObject) {
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08001502 return JDWP::ERR_INVALID_OBJECT;
1503 }
Brian Carlstromea46f952013-07-30 01:26:50 -07001504 mirror::ArtField* f = FromFieldId(field_id);
Elliott Hughes0cf74332012-02-23 23:14:00 -08001505
1506 // The RI only enforces the static/non-static mismatch in one direction.
1507 // TODO: should we change the tests and check both?
1508 if (is_static) {
1509 if (!f->IsStatic()) {
1510 return JDWP::ERR_INVALID_FIELDID;
1511 }
1512 } else {
1513 if (f->IsStatic()) {
1514 LOG(WARNING) << "Ignoring non-NULL receiver for ObjectReference.SetValues on static field " << PrettyField(f);
Elliott Hughes0cf74332012-02-23 23:14:00 -08001515 }
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08001516 }
jeffhao0dfbb7e2012-11-28 15:26:03 -08001517 if (f->IsStatic()) {
1518 o = f->GetDeclaringClass();
1519 }
Elliott Hughesaed4be92011-12-02 16:16:23 -08001520
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001521 JDWP::JdwpTag tag = BasicTagFromDescriptor(FieldHelper(f).GetTypeDescriptor());
Elliott Hughesaed4be92011-12-02 16:16:23 -08001522
1523 if (IsPrimitiveTag(tag)) {
1524 if (tag == JDWP::JT_DOUBLE || tag == JDWP::JT_LONG) {
Elliott Hughes1bac54f2012-03-16 12:48:31 -07001525 CHECK_EQ(width, 8);
Elliott Hughesaed4be92011-12-02 16:16:23 -08001526 f->Set64(o, value);
1527 } else {
Elliott Hughes1bac54f2012-03-16 12:48:31 -07001528 CHECK_LE(width, 4);
Elliott Hughesaed4be92011-12-02 16:16:23 -08001529 f->Set32(o, value);
1530 }
1531 } else {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001532 mirror::Object* v = gRegistry->Get<mirror::Object*>(value);
Elliott Hughes64f574f2013-02-20 14:57:12 -08001533 if (v == ObjectRegistry::kInvalidObject) {
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -08001534 return JDWP::ERR_INVALID_OBJECT;
1535 }
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08001536 if (v != NULL) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001537 mirror::Class* field_type = FieldHelper(f).GetType();
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08001538 if (!field_type->IsAssignableFrom(v->GetClass())) {
1539 return JDWP::ERR_INVALID_OBJECT;
1540 }
1541 }
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -08001542 f->SetObject(o, v);
Elliott Hughesaed4be92011-12-02 16:16:23 -08001543 }
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -08001544
1545 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001546}
1547
Elliott Hughes88d63092013-01-09 09:55:54 -08001548JDWP::JdwpError Dbg::SetFieldValue(JDWP::ObjectId object_id, JDWP::FieldId field_id, uint64_t value,
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001549 int width) {
Elliott Hughes88d63092013-01-09 09:55:54 -08001550 return SetFieldValueImpl(object_id, field_id, value, width, false);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001551}
1552
Elliott Hughes88d63092013-01-09 09:55:54 -08001553JDWP::JdwpError Dbg::SetStaticFieldValue(JDWP::FieldId field_id, uint64_t value, int width) {
1554 return SetFieldValueImpl(0, field_id, value, width, true);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001555}
1556
Elliott Hughes88d63092013-01-09 09:55:54 -08001557std::string Dbg::StringToUtf8(JDWP::ObjectId string_id) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001558 mirror::String* s = gRegistry->Get<mirror::String*>(string_id);
Elliott Hughes68fdbd02011-11-29 19:22:47 -08001559 return s->ToModifiedUtf8();
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001560}
1561
Elliott Hughes221229c2013-01-08 18:17:50 -08001562JDWP::JdwpError Dbg::GetThreadName(JDWP::ObjectId thread_id, std::string& name) {
jeffhaoa77f0f62012-12-05 17:19:31 -08001563 ScopedObjectAccessUnchecked soa(Thread::Current());
1564 MutexLock mu(soa.Self(), *Locks::thread_list_lock_);
Elliott Hughes221229c2013-01-08 18:17:50 -08001565 Thread* thread;
1566 JDWP::JdwpError error = DecodeThread(soa, thread_id, thread);
1567 if (error != JDWP::ERR_NONE && error != JDWP::ERR_THREAD_NOT_ALIVE) {
1568 return error;
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001569 }
Elliott Hughes221229c2013-01-08 18:17:50 -08001570
1571 // We still need to report the zombie threads' names, so we can't just call Thread::GetThreadName.
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001572 mirror::Object* thread_object = gRegistry->Get<mirror::Object*>(thread_id);
Brian Carlstromea46f952013-07-30 01:26:50 -07001573 mirror::ArtField* java_lang_Thread_name_field =
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001574 soa.DecodeField(WellKnownClasses::java_lang_Thread_name);
1575 mirror::String* s =
1576 reinterpret_cast<mirror::String*>(java_lang_Thread_name_field->GetObject(thread_object));
Elliott Hughes221229c2013-01-08 18:17:50 -08001577 if (s != NULL) {
1578 name = s->ToModifiedUtf8();
1579 }
1580 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001581}
1582
Elliott Hughes221229c2013-01-08 18:17:50 -08001583JDWP::JdwpError Dbg::GetThreadGroup(JDWP::ObjectId thread_id, JDWP::ExpandBuf* pReply) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001584 ScopedObjectAccess soa(Thread::Current());
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001585 mirror::Object* thread_object = gRegistry->Get<mirror::Object*>(thread_id);
Elliott Hughes64f574f2013-02-20 14:57:12 -08001586 if (thread_object == ObjectRegistry::kInvalidObject) {
Elliott Hughes2435a572012-02-17 16:07:41 -08001587 return JDWP::ERR_INVALID_OBJECT;
1588 }
1589
1590 // Okay, so it's an object, but is it actually a thread?
Ian Rogers50b35e22012-10-04 10:09:15 -07001591 MutexLock mu(soa.Self(), *Locks::thread_list_lock_);
Elliott Hughes221229c2013-01-08 18:17:50 -08001592 Thread* thread;
1593 JDWP::JdwpError error = DecodeThread(soa, thread_id, thread);
1594 if (error == JDWP::ERR_THREAD_NOT_ALIVE) {
1595 // Zombie threads are in the null group.
1596 expandBufAddObjectId(pReply, JDWP::ObjectId(0));
1597 return JDWP::ERR_NONE;
1598 }
1599 if (error != JDWP::ERR_NONE) {
1600 return error;
Elliott Hughes2435a572012-02-17 16:07:41 -08001601 }
Elliott Hughes499c5132011-11-17 14:55:11 -08001602
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001603 mirror::Class* c = Runtime::Current()->GetClassLinker()->FindSystemClass("Ljava/lang/Thread;");
Elliott Hughes499c5132011-11-17 14:55:11 -08001604 CHECK(c != NULL);
Brian Carlstromea46f952013-07-30 01:26:50 -07001605 mirror::ArtField* f = c->FindInstanceField("group", "Ljava/lang/ThreadGroup;");
Elliott Hughes499c5132011-11-17 14:55:11 -08001606 CHECK(f != NULL);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001607 mirror::Object* group = f->GetObject(thread_object);
Elliott Hughes499c5132011-11-17 14:55:11 -08001608 CHECK(group != NULL);
Elliott Hughes2435a572012-02-17 16:07:41 -08001609 JDWP::ObjectId thread_group_id = gRegistry->Add(group);
1610
1611 expandBufAddObjectId(pReply, thread_group_id);
1612 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001613}
1614
Elliott Hughes88d63092013-01-09 09:55:54 -08001615std::string Dbg::GetThreadGroupName(JDWP::ObjectId thread_group_id) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001616 ScopedObjectAccess soa(Thread::Current());
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001617 mirror::Object* thread_group = gRegistry->Get<mirror::Object*>(thread_group_id);
Elliott Hughes499c5132011-11-17 14:55:11 -08001618 CHECK(thread_group != NULL);
1619
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001620 mirror::Class* c = Runtime::Current()->GetClassLinker()->FindSystemClass("Ljava/lang/ThreadGroup;");
Elliott Hughes499c5132011-11-17 14:55:11 -08001621 CHECK(c != NULL);
Brian Carlstromea46f952013-07-30 01:26:50 -07001622 mirror::ArtField* f = c->FindInstanceField("name", "Ljava/lang/String;");
Elliott Hughes499c5132011-11-17 14:55:11 -08001623 CHECK(f != NULL);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001624 mirror::String* s = reinterpret_cast<mirror::String*>(f->GetObject(thread_group));
Elliott Hughes499c5132011-11-17 14:55:11 -08001625 return s->ToModifiedUtf8();
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001626}
1627
Elliott Hughes88d63092013-01-09 09:55:54 -08001628JDWP::ObjectId Dbg::GetThreadGroupParent(JDWP::ObjectId thread_group_id) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001629 mirror::Object* thread_group = gRegistry->Get<mirror::Object*>(thread_group_id);
Elliott Hughes4e235312011-12-02 11:34:15 -08001630 CHECK(thread_group != NULL);
1631
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001632 mirror::Class* c = Runtime::Current()->GetClassLinker()->FindSystemClass("Ljava/lang/ThreadGroup;");
Elliott Hughes4e235312011-12-02 11:34:15 -08001633 CHECK(c != NULL);
Brian Carlstromea46f952013-07-30 01:26:50 -07001634 mirror::ArtField* f = c->FindInstanceField("parent", "Ljava/lang/ThreadGroup;");
Elliott Hughes4e235312011-12-02 11:34:15 -08001635 CHECK(f != NULL);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001636 mirror::Object* parent = f->GetObject(thread_group);
Elliott Hughes4e235312011-12-02 11:34:15 -08001637 return gRegistry->Add(parent);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001638}
1639
1640JDWP::ObjectId Dbg::GetSystemThreadGroupId() {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001641 ScopedObjectAccessUnchecked soa(Thread::Current());
Brian Carlstromea46f952013-07-30 01:26:50 -07001642 mirror::ArtField* f = soa.DecodeField(WellKnownClasses::java_lang_ThreadGroup_systemThreadGroup);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001643 mirror::Object* group = f->GetObject(f->GetDeclaringClass());
Ian Rogers365c1022012-06-22 15:05:28 -07001644 return gRegistry->Add(group);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001645}
1646
1647JDWP::ObjectId Dbg::GetMainThreadGroupId() {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001648 ScopedObjectAccess soa(Thread::Current());
Brian Carlstromea46f952013-07-30 01:26:50 -07001649 mirror::ArtField* f = soa.DecodeField(WellKnownClasses::java_lang_ThreadGroup_mainThreadGroup);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001650 mirror::Object* group = f->GetObject(f->GetDeclaringClass());
Ian Rogers365c1022012-06-22 15:05:28 -07001651 return gRegistry->Add(group);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001652}
1653
Jeff Hao920af3e2013-08-28 15:46:38 -07001654JDWP::JdwpThreadStatus Dbg::ToJdwpThreadStatus(ThreadState state) {
1655 switch (state) {
1656 case kBlocked:
1657 return JDWP::TS_MONITOR;
1658 case kNative:
1659 case kRunnable:
1660 case kSuspended:
1661 return JDWP::TS_RUNNING;
1662 case kSleeping:
1663 return JDWP::TS_SLEEPING;
1664 case kStarting:
1665 case kTerminated:
1666 return JDWP::TS_ZOMBIE;
1667 case kTimedWaiting:
1668 case kWaitingForDebuggerSend:
1669 case kWaitingForDebuggerSuspension:
1670 case kWaitingForDebuggerToAttach:
1671 case kWaitingForGcToComplete:
1672 case kWaitingForCheckPointsToRun:
1673 case kWaitingForJniOnLoad:
1674 case kWaitingForSignalCatcherOutput:
1675 case kWaitingInMainDebuggerLoop:
1676 case kWaitingInMainSignalCatcherLoop:
1677 case kWaitingPerformingGc:
1678 case kWaiting:
1679 return JDWP::TS_WAIT;
1680 // Don't add a 'default' here so the compiler can spot incompatible enum changes.
1681 }
1682 LOG(FATAL) << "Unknown thread state: " << state;
1683 return JDWP::TS_ZOMBIE;
1684}
1685
Elliott Hughes221229c2013-01-08 18:17:50 -08001686JDWP::JdwpError Dbg::GetThreadStatus(JDWP::ObjectId thread_id, JDWP::JdwpThreadStatus* pThreadStatus, JDWP::JdwpSuspendStatus* pSuspendStatus) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001687 ScopedObjectAccess soa(Thread::Current());
Elliott Hughes499c5132011-11-17 14:55:11 -08001688
Elliott Hughes9e0c1752013-01-09 14:02:58 -08001689 *pSuspendStatus = JDWP::SUSPEND_STATUS_NOT_SUSPENDED;
1690
Ian Rogers50b35e22012-10-04 10:09:15 -07001691 MutexLock mu(soa.Self(), *Locks::thread_list_lock_);
Elliott Hughes221229c2013-01-08 18:17:50 -08001692 Thread* thread;
1693 JDWP::JdwpError error = DecodeThread(soa, thread_id, thread);
1694 if (error != JDWP::ERR_NONE) {
1695 if (error == JDWP::ERR_THREAD_NOT_ALIVE) {
1696 *pThreadStatus = JDWP::TS_ZOMBIE;
Elliott Hughes221229c2013-01-08 18:17:50 -08001697 return JDWP::ERR_NONE;
1698 }
1699 return error;
Elliott Hughes499c5132011-11-17 14:55:11 -08001700 }
1701
Elliott Hughes9e0c1752013-01-09 14:02:58 -08001702 if (IsSuspendedForDebugger(soa, thread)) {
1703 *pSuspendStatus = JDWP::SUSPEND_STATUS_SUSPENDED;
Elliott Hughes499c5132011-11-17 14:55:11 -08001704 }
1705
Jeff Hao920af3e2013-08-28 15:46:38 -07001706 *pThreadStatus = ToJdwpThreadStatus(thread->GetState());
Elliott Hughes221229c2013-01-08 18:17:50 -08001707 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001708}
1709
Elliott Hughes221229c2013-01-08 18:17:50 -08001710JDWP::JdwpError Dbg::GetThreadDebugSuspendCount(JDWP::ObjectId thread_id, JDWP::ExpandBuf* pReply) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001711 ScopedObjectAccess soa(Thread::Current());
Ian Rogers50b35e22012-10-04 10:09:15 -07001712 MutexLock mu(soa.Self(), *Locks::thread_list_lock_);
Elliott Hughes221229c2013-01-08 18:17:50 -08001713 Thread* thread;
1714 JDWP::JdwpError error = DecodeThread(soa, thread_id, thread);
1715 if (error != JDWP::ERR_NONE) {
1716 return error;
Elliott Hughes2435a572012-02-17 16:07:41 -08001717 }
Ian Rogers50b35e22012-10-04 10:09:15 -07001718 MutexLock mu2(soa.Self(), *Locks::thread_suspend_count_lock_);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001719 expandBufAdd4BE(pReply, thread->GetDebugSuspendCount());
Elliott Hughes2435a572012-02-17 16:07:41 -08001720 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001721}
1722
Elliott Hughesf9501702013-01-11 11:22:27 -08001723JDWP::JdwpError Dbg::Interrupt(JDWP::ObjectId thread_id) {
1724 ScopedObjectAccess soa(Thread::Current());
1725 MutexLock mu(soa.Self(), *Locks::thread_list_lock_);
1726 Thread* thread;
1727 JDWP::JdwpError error = DecodeThread(soa, thread_id, thread);
1728 if (error != JDWP::ERR_NONE) {
1729 return error;
1730 }
1731 thread->Interrupt();
1732 return JDWP::ERR_NONE;
1733}
1734
Elliott Hughescaf76542012-06-28 16:08:22 -07001735void Dbg::GetThreads(JDWP::ObjectId thread_group_id, std::vector<JDWP::ObjectId>& thread_ids) {
Ian Rogers365c1022012-06-22 15:05:28 -07001736 class ThreadListVisitor {
1737 public:
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001738 ThreadListVisitor(const ScopedObjectAccessUnchecked& soa, mirror::Object* desired_thread_group,
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001739 std::vector<JDWP::ObjectId>& thread_ids)
Ian Rogersb726dcb2012-09-05 08:57:23 -07001740 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_)
jeffhao0dfbb7e2012-11-28 15:26:03 -08001741 : soa_(soa), desired_thread_group_(desired_thread_group), thread_ids_(thread_ids) {}
Ian Rogers365c1022012-06-22 15:05:28 -07001742
Elliott Hughesa2155262011-11-16 16:26:58 -08001743 static void Visit(Thread* t, void* arg) {
1744 reinterpret_cast<ThreadListVisitor*>(arg)->Visit(t);
1745 }
1746
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001747 // TODO: Enable annotalysis. We know lock is held in constructor, but abstraction confuses
1748 // annotalysis.
1749 void Visit(Thread* t) NO_THREAD_SAFETY_ANALYSIS {
Elliott Hughesa2155262011-11-16 16:26:58 -08001750 if (t == Dbg::GetDebugThread()) {
1751 // Skip the JDWP thread. Some debuggers get bent out of shape when they can't suspend and
1752 // query all threads, so it's easier if we just don't tell them about this thread.
1753 return;
1754 }
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001755 mirror::Object* peer = t->GetPeer();
jeffhao0dfbb7e2012-11-28 15:26:03 -08001756 if (IsInDesiredThreadGroup(peer)) {
Ian Rogers120f1c72012-09-28 17:17:10 -07001757 thread_ids_.push_back(gRegistry->Add(peer));
Elliott Hughesa2155262011-11-16 16:26:58 -08001758 }
1759 }
1760
Ian Rogers365c1022012-06-22 15:05:28 -07001761 private:
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001762 bool IsInDesiredThreadGroup(mirror::Object* peer)
jeffhao0dfbb7e2012-11-28 15:26:03 -08001763 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
jeffhao0dfbb7e2012-11-28 15:26:03 -08001764 // peer might be NULL if the thread is still starting up.
1765 if (peer == NULL) {
1766 // We can't tell the debugger about this thread yet.
1767 // TODO: if we identified threads to the debugger by their Thread*
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001768 // rather than their peer's mirror::Object*, we could fix this.
jeffhao0dfbb7e2012-11-28 15:26:03 -08001769 // Doing so might help us report ZOMBIE threads too.
1770 return false;
1771 }
jeffhaoc1e04902012-12-13 12:41:10 -08001772 // Do we want threads from all thread groups?
1773 if (desired_thread_group_ == NULL) {
1774 return true;
1775 }
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001776 mirror::Object* group = soa_.DecodeField(WellKnownClasses::java_lang_Thread_group)->GetObject(peer);
jeffhao0dfbb7e2012-11-28 15:26:03 -08001777 return (group == desired_thread_group_);
1778 }
1779
Mathieu Chartierdbe6f462012-09-25 16:54:50 -07001780 const ScopedObjectAccessUnchecked& soa_;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001781 mirror::Object* const desired_thread_group_;
Elliott Hughescaf76542012-06-28 16:08:22 -07001782 std::vector<JDWP::ObjectId>& thread_ids_;
Elliott Hughesa2155262011-11-16 16:26:58 -08001783 };
1784
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001785 ScopedObjectAccessUnchecked soa(Thread::Current());
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001786 mirror::Object* thread_group = gRegistry->Get<mirror::Object*>(thread_group_id);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001787 ThreadListVisitor tlv(soa, thread_group, thread_ids);
Ian Rogers50b35e22012-10-04 10:09:15 -07001788 MutexLock mu(soa.Self(), *Locks::thread_list_lock_);
Elliott Hughesf8349362012-06-18 15:00:06 -07001789 Runtime::Current()->GetThreadList()->ForEach(ThreadListVisitor::Visit, &tlv);
Elliott Hughescaf76542012-06-28 16:08:22 -07001790}
Elliott Hughesa2155262011-11-16 16:26:58 -08001791
Elliott Hughescaf76542012-06-28 16:08:22 -07001792void Dbg::GetChildThreadGroups(JDWP::ObjectId thread_group_id, std::vector<JDWP::ObjectId>& child_thread_group_ids) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001793 ScopedObjectAccess soa(Thread::Current());
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001794 mirror::Object* thread_group = gRegistry->Get<mirror::Object*>(thread_group_id);
Elliott Hughescaf76542012-06-28 16:08:22 -07001795
1796 // Get the ArrayList<ThreadGroup> "groups" out of this thread group...
Brian Carlstromea46f952013-07-30 01:26:50 -07001797 mirror::ArtField* groups_field = thread_group->GetClass()->FindInstanceField("groups", "Ljava/util/List;");
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001798 mirror::Object* groups_array_list = groups_field->GetObject(thread_group);
Elliott Hughescaf76542012-06-28 16:08:22 -07001799
1800 // Get the array and size out of the ArrayList<ThreadGroup>...
Brian Carlstromea46f952013-07-30 01:26:50 -07001801 mirror::ArtField* array_field = groups_array_list->GetClass()->FindInstanceField("array", "[Ljava/lang/Object;");
1802 mirror::ArtField* size_field = groups_array_list->GetClass()->FindInstanceField("size", "I");
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001803 mirror::ObjectArray<mirror::Object>* groups_array =
1804 array_field->GetObject(groups_array_list)->AsObjectArray<mirror::Object>();
Elliott Hughescaf76542012-06-28 16:08:22 -07001805 const int32_t size = size_field->GetInt(groups_array_list);
1806
1807 // Copy the first 'size' elements out of the array into the result.
1808 for (int32_t i = 0; i < size; ++i) {
1809 child_thread_group_ids.push_back(gRegistry->Add(groups_array->Get(i)));
Elliott Hughesa2155262011-11-16 16:26:58 -08001810 }
1811}
1812
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001813static int GetStackDepth(Thread* thread)
Ian Rogersb726dcb2012-09-05 08:57:23 -07001814 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Ian Rogers0399dde2012-06-06 17:09:28 -07001815 struct CountStackDepthVisitor : public StackVisitor {
Brian Carlstrom93ba8932013-07-17 21:31:49 -07001816 explicit CountStackDepthVisitor(Thread* thread)
Ian Rogers7a22fa62013-01-23 12:16:16 -08001817 : StackVisitor(thread, NULL), depth(0) {}
Ian Rogers0399dde2012-06-06 17:09:28 -07001818
Elliott Hughes64f574f2013-02-20 14:57:12 -08001819 // TODO: Enable annotalysis. We know lock is held in constructor, but abstraction confuses
1820 // annotalysis.
1821 bool VisitFrame() NO_THREAD_SAFETY_ANALYSIS {
Ian Rogers0399dde2012-06-06 17:09:28 -07001822 if (!GetMethod()->IsRuntimeMethod()) {
Elliott Hughesf8a2df72011-12-01 12:19:54 -08001823 ++depth;
1824 }
Elliott Hughes530fa002012-03-12 11:44:49 -07001825 return true;
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001826 }
1827 size_t depth;
1828 };
Elliott Hughes08fc03a2012-06-26 17:34:00 -07001829
Ian Rogers7a22fa62013-01-23 12:16:16 -08001830 CountStackDepthVisitor visitor(thread);
Ian Rogers0399dde2012-06-06 17:09:28 -07001831 visitor.WalkStack();
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001832 return visitor.depth;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001833}
1834
Elliott Hughes221229c2013-01-08 18:17:50 -08001835JDWP::JdwpError Dbg::GetThreadFrameCount(JDWP::ObjectId thread_id, size_t& result) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001836 ScopedObjectAccess soa(Thread::Current());
jeffhaoa77f0f62012-12-05 17:19:31 -08001837 MutexLock mu(soa.Self(), *Locks::thread_list_lock_);
Elliott Hughes221229c2013-01-08 18:17:50 -08001838 Thread* thread;
1839 JDWP::JdwpError error = DecodeThread(soa, thread_id, thread);
1840 if (error != JDWP::ERR_NONE) {
1841 return error;
1842 }
Elliott Hughesf15f4a02013-01-09 10:09:38 -08001843 if (!IsSuspendedForDebugger(soa, thread)) {
1844 return JDWP::ERR_THREAD_NOT_SUSPENDED;
1845 }
Elliott Hughes221229c2013-01-08 18:17:50 -08001846 result = GetStackDepth(thread);
1847 return JDWP::ERR_NONE;
Elliott Hughes86964332012-02-15 19:37:42 -08001848}
1849
Ian Rogers306057f2012-11-26 12:45:53 -08001850JDWP::JdwpError Dbg::GetThreadFrames(JDWP::ObjectId thread_id, size_t start_frame,
1851 size_t frame_count, JDWP::ExpandBuf* buf) {
Elliott Hughes6e9d22c2012-06-22 15:02:37 -07001852 class GetFrameVisitor : public StackVisitor {
1853 public:
Ian Rogers7a22fa62013-01-23 12:16:16 -08001854 GetFrameVisitor(Thread* thread, size_t start_frame, size_t frame_count, JDWP::ExpandBuf* buf)
Ian Rogersb726dcb2012-09-05 08:57:23 -07001855 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_)
Ian Rogers7a22fa62013-01-23 12:16:16 -08001856 : StackVisitor(thread, NULL), depth_(0),
Elliott Hughes6e9d22c2012-06-22 15:02:37 -07001857 start_frame_(start_frame), frame_count_(frame_count), buf_(buf) {
1858 expandBufAdd4BE(buf_, frame_count_);
Elliott Hughes03181a82011-11-17 17:22:21 -08001859 }
Ian Rogers0399dde2012-06-06 17:09:28 -07001860
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001861 // TODO: Enable annotalysis. We know lock is held in constructor, but abstraction confuses
1862 // annotalysis.
1863 virtual bool VisitFrame() NO_THREAD_SAFETY_ANALYSIS {
Ian Rogers0399dde2012-06-06 17:09:28 -07001864 if (GetMethod()->IsRuntimeMethod()) {
Brian Carlstrom7934ac22013-07-26 10:54:15 -07001865 return true; // The debugger can't do anything useful with a frame that has no Method*.
Elliott Hughes03181a82011-11-17 17:22:21 -08001866 }
Elliott Hughes6e9d22c2012-06-22 15:02:37 -07001867 if (depth_ >= start_frame_ + frame_count_) {
Elliott Hughes530fa002012-03-12 11:44:49 -07001868 return false;
Elliott Hughes03181a82011-11-17 17:22:21 -08001869 }
Elliott Hughes6e9d22c2012-06-22 15:02:37 -07001870 if (depth_ >= start_frame_) {
1871 JDWP::FrameId frame_id(GetFrameId());
1872 JDWP::JdwpLocation location;
1873 SetLocation(location, GetMethod(), GetDexPc());
Elliott Hughes7baf96f2012-06-22 16:33:50 -07001874 VLOG(jdwp) << StringPrintf(" Frame %3zd: id=%3lld ", depth_, frame_id) << location;
Elliott Hughes6e9d22c2012-06-22 15:02:37 -07001875 expandBufAdd8BE(buf_, frame_id);
1876 expandBufAddLocation(buf_, location);
1877 }
1878 ++depth_;
Elliott Hughes530fa002012-03-12 11:44:49 -07001879 return true;
Elliott Hughes03181a82011-11-17 17:22:21 -08001880 }
Elliott Hughes6e9d22c2012-06-22 15:02:37 -07001881
1882 private:
1883 size_t depth_;
1884 const size_t start_frame_;
1885 const size_t frame_count_;
1886 JDWP::ExpandBuf* buf_;
Elliott Hughes03181a82011-11-17 17:22:21 -08001887 };
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001888
1889 ScopedObjectAccessUnchecked soa(Thread::Current());
jeffhaoa77f0f62012-12-05 17:19:31 -08001890 MutexLock mu(soa.Self(), *Locks::thread_list_lock_);
Elliott Hughes221229c2013-01-08 18:17:50 -08001891 Thread* thread;
1892 JDWP::JdwpError error = DecodeThread(soa, thread_id, thread);
1893 if (error != JDWP::ERR_NONE) {
1894 return error;
1895 }
Elliott Hughesf15f4a02013-01-09 10:09:38 -08001896 if (!IsSuspendedForDebugger(soa, thread)) {
1897 return JDWP::ERR_THREAD_NOT_SUSPENDED;
1898 }
Ian Rogers7a22fa62013-01-23 12:16:16 -08001899 GetFrameVisitor visitor(thread, start_frame, frame_count, buf);
Ian Rogers0399dde2012-06-06 17:09:28 -07001900 visitor.WalkStack();
Elliott Hughes6e9d22c2012-06-22 15:02:37 -07001901 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001902}
1903
1904JDWP::ObjectId Dbg::GetThreadSelfId() {
Mathieu Chartierdbe6f462012-09-25 16:54:50 -07001905 ScopedObjectAccessUnchecked soa(Thread::Current());
Ian Rogerscfaa4552012-11-26 21:00:08 -08001906 return gRegistry->Add(soa.Self()->GetPeer());
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001907}
1908
Elliott Hughes475fc232011-10-25 15:00:35 -07001909void Dbg::SuspendVM() {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001910 Runtime::Current()->GetThreadList()->SuspendAllForDebugger();
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001911}
1912
1913void Dbg::ResumeVM() {
Elliott Hughesc61a2672012-06-21 14:52:29 -07001914 Runtime::Current()->GetThreadList()->UndoDebuggerSuspensions();
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001915}
1916
Elliott Hughes221229c2013-01-08 18:17:50 -08001917JDWP::JdwpError Dbg::SuspendThread(JDWP::ObjectId thread_id, bool request_suspension) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001918 ScopedLocalRef<jobject> peer(Thread::Current()->GetJniEnv(), NULL);
1919 {
1920 ScopedObjectAccess soa(Thread::Current());
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001921 peer.reset(soa.AddLocalReference<jobject>(gRegistry->Get<mirror::Object*>(thread_id)));
Elliott Hughes4e235312011-12-02 11:34:15 -08001922 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001923 if (peer.get() == NULL) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001924 return JDWP::ERR_THREAD_NOT_ALIVE;
1925 }
1926 // Suspend thread to build stack trace.
Elliott Hughesf327e072013-01-09 16:01:26 -08001927 bool timed_out;
Ian Rogersd9c4fc92013-10-01 19:45:43 -07001928 Thread* thread = ThreadList::SuspendThreadByPeer(peer.get(), request_suspension, true,
1929 &timed_out);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001930 if (thread != NULL) {
1931 return JDWP::ERR_NONE;
Elliott Hughesf327e072013-01-09 16:01:26 -08001932 } else if (timed_out) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001933 return JDWP::ERR_INTERNAL;
1934 } else {
1935 return JDWP::ERR_THREAD_NOT_ALIVE;
1936 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001937}
1938
Elliott Hughes221229c2013-01-08 18:17:50 -08001939void Dbg::ResumeThread(JDWP::ObjectId thread_id) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001940 ScopedObjectAccessUnchecked soa(Thread::Current());
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001941 mirror::Object* peer = gRegistry->Get<mirror::Object*>(thread_id);
jeffhaoa77f0f62012-12-05 17:19:31 -08001942 Thread* thread;
1943 {
1944 MutexLock mu(soa.Self(), *Locks::thread_list_lock_);
1945 thread = Thread::FromManagedThread(soa, peer);
1946 }
Elliott Hughes4e235312011-12-02 11:34:15 -08001947 if (thread == NULL) {
1948 LOG(WARNING) << "No such thread for resume: " << peer;
1949 return;
1950 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001951 bool needs_resume;
1952 {
Ian Rogers50b35e22012-10-04 10:09:15 -07001953 MutexLock mu2(soa.Self(), *Locks::thread_suspend_count_lock_);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001954 needs_resume = thread->GetSuspendCount() > 0;
1955 }
1956 if (needs_resume) {
Elliott Hughes546b9862012-06-20 16:06:13 -07001957 Runtime::Current()->GetThreadList()->Resume(thread, true);
1958 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001959}
1960
1961void Dbg::SuspendSelf() {
Elliott Hughes475fc232011-10-25 15:00:35 -07001962 Runtime::Current()->GetThreadList()->SuspendSelfForDebugger();
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001963}
1964
Ian Rogers0399dde2012-06-06 17:09:28 -07001965struct GetThisVisitor : public StackVisitor {
Ian Rogers7a22fa62013-01-23 12:16:16 -08001966 GetThisVisitor(Thread* thread, Context* context, JDWP::FrameId frame_id)
Ian Rogersb726dcb2012-09-05 08:57:23 -07001967 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_)
Ian Rogers7a22fa62013-01-23 12:16:16 -08001968 : StackVisitor(thread, context), this_object(NULL), frame_id(frame_id) {}
Ian Rogers0399dde2012-06-06 17:09:28 -07001969
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001970 // TODO: Enable annotalysis. We know lock is held in constructor, but abstraction confuses
1971 // annotalysis.
1972 virtual bool VisitFrame() NO_THREAD_SAFETY_ANALYSIS {
Elliott Hughes6e9d22c2012-06-22 15:02:37 -07001973 if (frame_id != GetFrameId()) {
Ian Rogers0399dde2012-06-06 17:09:28 -07001974 return true; // continue
Ian Rogers0399dde2012-06-06 17:09:28 -07001975 } else {
Ian Rogers62d6c772013-02-27 08:32:07 -08001976 this_object = GetThisObject();
1977 return false;
Ian Rogers0399dde2012-06-06 17:09:28 -07001978 }
Elliott Hughes86b00102011-12-05 17:54:26 -08001979 }
Ian Rogers0399dde2012-06-06 17:09:28 -07001980
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001981 mirror::Object* this_object;
Elliott Hughes6e9d22c2012-06-22 15:02:37 -07001982 JDWP::FrameId frame_id;
Ian Rogers0399dde2012-06-06 17:09:28 -07001983};
1984
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001985JDWP::JdwpError Dbg::GetThisObject(JDWP::ObjectId thread_id, JDWP::FrameId frame_id,
1986 JDWP::ObjectId* result) {
1987 ScopedObjectAccessUnchecked soa(Thread::Current());
1988 Thread* thread;
1989 {
Ian Rogers50b35e22012-10-04 10:09:15 -07001990 MutexLock mu(soa.Self(), *Locks::thread_list_lock_);
Elliott Hughes221229c2013-01-08 18:17:50 -08001991 JDWP::JdwpError error = DecodeThread(soa, thread_id, thread);
1992 if (error != JDWP::ERR_NONE) {
1993 return error;
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001994 }
Elliott Hughes9e0c1752013-01-09 14:02:58 -08001995 if (!IsSuspendedForDebugger(soa, thread)) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001996 return JDWP::ERR_THREAD_NOT_SUSPENDED;
1997 }
Elliott Hughes6e9d22c2012-06-22 15:02:37 -07001998 }
Elliott Hughescaf76542012-06-28 16:08:22 -07001999 UniquePtr<Context> context(Context::Create());
Ian Rogers7a22fa62013-01-23 12:16:16 -08002000 GetThisVisitor visitor(thread, context.get(), frame_id);
Ian Rogers0399dde2012-06-06 17:09:28 -07002001 visitor.WalkStack();
Elliott Hughes6e9d22c2012-06-22 15:02:37 -07002002 *result = gRegistry->Add(visitor.this_object);
2003 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002004}
2005
Elliott Hughes88d63092013-01-09 09:55:54 -08002006void Dbg::GetLocalValue(JDWP::ObjectId thread_id, JDWP::FrameId frame_id, int slot, JDWP::JdwpTag tag,
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002007 uint8_t* buf, size_t width) {
Ian Rogers0399dde2012-06-06 17:09:28 -07002008 struct GetLocalVisitor : public StackVisitor {
Ian Rogers7a22fa62013-01-23 12:16:16 -08002009 GetLocalVisitor(Thread* thread, Context* context, JDWP::FrameId frame_id, int slot,
2010 JDWP::JdwpTag tag, uint8_t* buf, size_t width)
Ian Rogersb726dcb2012-09-05 08:57:23 -07002011 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_)
Ian Rogers7a22fa62013-01-23 12:16:16 -08002012 : StackVisitor(thread, context), frame_id_(frame_id), slot_(slot), tag_(tag),
Ian Rogersca190662012-06-26 15:45:57 -07002013 buf_(buf), width_(width) {}
2014
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002015 // TODO: Enable annotalysis. We know lock is held in constructor, but abstraction confuses
2016 // annotalysis.
2017 bool VisitFrame() NO_THREAD_SAFETY_ANALYSIS {
Ian Rogers0399dde2012-06-06 17:09:28 -07002018 if (GetFrameId() != frame_id_) {
2019 return true; // Not our frame, carry on.
Elliott Hughesdbb40792011-11-18 17:05:22 -08002020 }
Ian Rogers0399dde2012-06-06 17:09:28 -07002021 // TODO: check that the tag is compatible with the actual type of the slot!
Brian Carlstromea46f952013-07-30 01:26:50 -07002022 mirror::ArtMethod* m = GetMethod();
Ian Rogers0399dde2012-06-06 17:09:28 -07002023 uint16_t reg = DemangleSlot(slot_, m);
Elliott Hughesdbb40792011-11-18 17:05:22 -08002024
Ian Rogers0399dde2012-06-06 17:09:28 -07002025 switch (tag_) {
2026 case JDWP::JT_BOOLEAN:
2027 {
2028 CHECK_EQ(width_, 1U);
Ian Rogers2bcb4a42012-11-08 10:39:18 -08002029 uint32_t intVal = GetVReg(m, reg, kIntVReg);
Ian Rogers0399dde2012-06-06 17:09:28 -07002030 VLOG(jdwp) << "get boolean local " << reg << " = " << intVal;
2031 JDWP::Set1(buf_+1, intVal != 0);
2032 }
2033 break;
2034 case JDWP::JT_BYTE:
2035 {
2036 CHECK_EQ(width_, 1U);
Ian Rogers2bcb4a42012-11-08 10:39:18 -08002037 uint32_t intVal = GetVReg(m, reg, kIntVReg);
Ian Rogers0399dde2012-06-06 17:09:28 -07002038 VLOG(jdwp) << "get byte local " << reg << " = " << intVal;
2039 JDWP::Set1(buf_+1, intVal);
2040 }
2041 break;
2042 case JDWP::JT_SHORT:
2043 case JDWP::JT_CHAR:
2044 {
2045 CHECK_EQ(width_, 2U);
Ian Rogers2bcb4a42012-11-08 10:39:18 -08002046 uint32_t intVal = GetVReg(m, reg, kIntVReg);
Ian Rogers0399dde2012-06-06 17:09:28 -07002047 VLOG(jdwp) << "get short/char local " << reg << " = " << intVal;
2048 JDWP::Set2BE(buf_+1, intVal);
2049 }
2050 break;
2051 case JDWP::JT_INT:
Ian Rogers2bcb4a42012-11-08 10:39:18 -08002052 {
2053 CHECK_EQ(width_, 4U);
2054 uint32_t intVal = GetVReg(m, reg, kIntVReg);
2055 VLOG(jdwp) << "get int local " << reg << " = " << intVal;
2056 JDWP::Set4BE(buf_+1, intVal);
2057 }
2058 break;
Ian Rogers0399dde2012-06-06 17:09:28 -07002059 case JDWP::JT_FLOAT:
2060 {
2061 CHECK_EQ(width_, 4U);
Ian Rogers2bcb4a42012-11-08 10:39:18 -08002062 uint32_t intVal = GetVReg(m, reg, kFloatVReg);
Ian Rogers0399dde2012-06-06 17:09:28 -07002063 VLOG(jdwp) << "get int/float local " << reg << " = " << intVal;
2064 JDWP::Set4BE(buf_+1, intVal);
2065 }
2066 break;
2067 case JDWP::JT_ARRAY:
2068 {
2069 CHECK_EQ(width_, sizeof(JDWP::ObjectId));
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002070 mirror::Object* o = reinterpret_cast<mirror::Object*>(GetVReg(m, reg, kReferenceVReg));
Ian Rogers0399dde2012-06-06 17:09:28 -07002071 VLOG(jdwp) << "get array local " << reg << " = " << o;
Mathieu Chartier590fee92013-09-13 13:46:47 -07002072 if (!Runtime::Current()->GetHeap()->IsValidObjectAddress(o)) {
Ian Rogers0399dde2012-06-06 17:09:28 -07002073 LOG(FATAL) << "Register " << reg << " expected to hold array: " << o;
2074 }
2075 JDWP::SetObjectId(buf_+1, gRegistry->Add(o));
2076 }
2077 break;
2078 case JDWP::JT_CLASS_LOADER:
2079 case JDWP::JT_CLASS_OBJECT:
2080 case JDWP::JT_OBJECT:
2081 case JDWP::JT_STRING:
2082 case JDWP::JT_THREAD:
2083 case JDWP::JT_THREAD_GROUP:
2084 {
2085 CHECK_EQ(width_, sizeof(JDWP::ObjectId));
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002086 mirror::Object* o = reinterpret_cast<mirror::Object*>(GetVReg(m, reg, kReferenceVReg));
Ian Rogers0399dde2012-06-06 17:09:28 -07002087 VLOG(jdwp) << "get object local " << reg << " = " << o;
Mathieu Chartier590fee92013-09-13 13:46:47 -07002088 if (!Runtime::Current()->GetHeap()->IsValidObjectAddress(o)) {
Ian Rogers0399dde2012-06-06 17:09:28 -07002089 LOG(FATAL) << "Register " << reg << " expected to hold object: " << o;
2090 }
2091 tag_ = TagFromObject(o);
2092 JDWP::SetObjectId(buf_+1, gRegistry->Add(o));
2093 }
2094 break;
2095 case JDWP::JT_DOUBLE:
Ian Rogers2bcb4a42012-11-08 10:39:18 -08002096 {
2097 CHECK_EQ(width_, 8U);
2098 uint32_t lo = GetVReg(m, reg, kDoubleLoVReg);
2099 uint64_t hi = GetVReg(m, reg + 1, kDoubleHiVReg);
2100 uint64_t longVal = (hi << 32) | lo;
2101 VLOG(jdwp) << "get double/long local " << hi << ":" << lo << " = " << longVal;
2102 JDWP::Set8BE(buf_+1, longVal);
2103 }
2104 break;
Ian Rogers0399dde2012-06-06 17:09:28 -07002105 case JDWP::JT_LONG:
2106 {
2107 CHECK_EQ(width_, 8U);
Ian Rogers2bcb4a42012-11-08 10:39:18 -08002108 uint32_t lo = GetVReg(m, reg, kLongLoVReg);
2109 uint64_t hi = GetVReg(m, reg + 1, kLongHiVReg);
Ian Rogers0399dde2012-06-06 17:09:28 -07002110 uint64_t longVal = (hi << 32) | lo;
2111 VLOG(jdwp) << "get double/long local " << hi << ":" << lo << " = " << longVal;
2112 JDWP::Set8BE(buf_+1, longVal);
2113 }
2114 break;
2115 default:
2116 LOG(FATAL) << "Unknown tag " << tag_;
2117 break;
2118 }
2119
2120 // Prepend tag, which may have been updated.
2121 JDWP::Set1(buf_, tag_);
2122 return false;
2123 }
2124
2125 const JDWP::FrameId frame_id_;
2126 const int slot_;
2127 JDWP::JdwpTag tag_;
2128 uint8_t* const buf_;
2129 const size_t width_;
2130 };
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002131
2132 ScopedObjectAccessUnchecked soa(Thread::Current());
jeffhaoa77f0f62012-12-05 17:19:31 -08002133 MutexLock mu(soa.Self(), *Locks::thread_list_lock_);
Elliott Hughes221229c2013-01-08 18:17:50 -08002134 Thread* thread;
2135 JDWP::JdwpError error = DecodeThread(soa, thread_id, thread);
2136 if (error != JDWP::ERR_NONE) {
2137 return;
2138 }
Ian Rogers0399dde2012-06-06 17:09:28 -07002139 UniquePtr<Context> context(Context::Create());
Ian Rogers7a22fa62013-01-23 12:16:16 -08002140 GetLocalVisitor visitor(thread, context.get(), frame_id, slot, tag, buf, width);
Ian Rogers0399dde2012-06-06 17:09:28 -07002141 visitor.WalkStack();
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002142}
2143
Elliott Hughes88d63092013-01-09 09:55:54 -08002144void Dbg::SetLocalValue(JDWP::ObjectId thread_id, JDWP::FrameId frame_id, int slot, JDWP::JdwpTag tag,
Ian Rogers0399dde2012-06-06 17:09:28 -07002145 uint64_t value, size_t width) {
2146 struct SetLocalVisitor : public StackVisitor {
Ian Rogers7a22fa62013-01-23 12:16:16 -08002147 SetLocalVisitor(Thread* thread, Context* context,
Ian Rogers0399dde2012-06-06 17:09:28 -07002148 JDWP::FrameId frame_id, int slot, JDWP::JdwpTag tag, uint64_t value,
Ian Rogersca190662012-06-26 15:45:57 -07002149 size_t width)
Ian Rogersb726dcb2012-09-05 08:57:23 -07002150 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_)
Ian Rogers7a22fa62013-01-23 12:16:16 -08002151 : StackVisitor(thread, context),
Elliott Hughes08fc03a2012-06-26 17:34:00 -07002152 frame_id_(frame_id), slot_(slot), tag_(tag), value_(value), width_(width) {}
Ian Rogersca190662012-06-26 15:45:57 -07002153
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002154 // TODO: Enable annotalysis. We know lock is held in constructor, but abstraction confuses
2155 // annotalysis.
2156 bool VisitFrame() NO_THREAD_SAFETY_ANALYSIS {
Ian Rogers0399dde2012-06-06 17:09:28 -07002157 if (GetFrameId() != frame_id_) {
2158 return true; // Not our frame, carry on.
2159 }
2160 // TODO: check that the tag is compatible with the actual type of the slot!
Brian Carlstromea46f952013-07-30 01:26:50 -07002161 mirror::ArtMethod* m = GetMethod();
Ian Rogers0399dde2012-06-06 17:09:28 -07002162 uint16_t reg = DemangleSlot(slot_, m);
2163
2164 switch (tag_) {
2165 case JDWP::JT_BOOLEAN:
2166 case JDWP::JT_BYTE:
2167 CHECK_EQ(width_, 1U);
Ian Rogers2bcb4a42012-11-08 10:39:18 -08002168 SetVReg(m, reg, static_cast<uint32_t>(value_), kIntVReg);
Ian Rogers0399dde2012-06-06 17:09:28 -07002169 break;
2170 case JDWP::JT_SHORT:
2171 case JDWP::JT_CHAR:
2172 CHECK_EQ(width_, 2U);
Ian Rogers2bcb4a42012-11-08 10:39:18 -08002173 SetVReg(m, reg, static_cast<uint32_t>(value_), kIntVReg);
Ian Rogers0399dde2012-06-06 17:09:28 -07002174 break;
2175 case JDWP::JT_INT:
Ian Rogers2bcb4a42012-11-08 10:39:18 -08002176 CHECK_EQ(width_, 4U);
2177 SetVReg(m, reg, static_cast<uint32_t>(value_), kIntVReg);
2178 break;
Ian Rogers0399dde2012-06-06 17:09:28 -07002179 case JDWP::JT_FLOAT:
2180 CHECK_EQ(width_, 4U);
Ian Rogers2bcb4a42012-11-08 10:39:18 -08002181 SetVReg(m, reg, static_cast<uint32_t>(value_), kFloatVReg);
Ian Rogers0399dde2012-06-06 17:09:28 -07002182 break;
2183 case JDWP::JT_ARRAY:
2184 case JDWP::JT_OBJECT:
2185 case JDWP::JT_STRING:
2186 {
2187 CHECK_EQ(width_, sizeof(JDWP::ObjectId));
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002188 mirror::Object* o = gRegistry->Get<mirror::Object*>(static_cast<JDWP::ObjectId>(value_));
Elliott Hughes64f574f2013-02-20 14:57:12 -08002189 if (o == ObjectRegistry::kInvalidObject) {
Ian Rogers0399dde2012-06-06 17:09:28 -07002190 UNIMPLEMENTED(FATAL) << "return an error code when given an invalid object to store";
2191 }
Ian Rogers2bcb4a42012-11-08 10:39:18 -08002192 SetVReg(m, reg, static_cast<uint32_t>(reinterpret_cast<uintptr_t>(o)), kReferenceVReg);
Ian Rogers0399dde2012-06-06 17:09:28 -07002193 }
2194 break;
2195 case JDWP::JT_DOUBLE:
Ian Rogers2bcb4a42012-11-08 10:39:18 -08002196 CHECK_EQ(width_, 8U);
2197 SetVReg(m, reg, static_cast<uint32_t>(value_), kDoubleLoVReg);
2198 SetVReg(m, reg + 1, static_cast<uint32_t>(value_ >> 32), kDoubleHiVReg);
2199 break;
Ian Rogers0399dde2012-06-06 17:09:28 -07002200 case JDWP::JT_LONG:
2201 CHECK_EQ(width_, 8U);
Ian Rogers2bcb4a42012-11-08 10:39:18 -08002202 SetVReg(m, reg, static_cast<uint32_t>(value_), kLongLoVReg);
2203 SetVReg(m, reg + 1, static_cast<uint32_t>(value_ >> 32), kLongHiVReg);
Ian Rogers0399dde2012-06-06 17:09:28 -07002204 break;
2205 default:
2206 LOG(FATAL) << "Unknown tag " << tag_;
2207 break;
2208 }
2209 return false;
2210 }
2211
2212 const JDWP::FrameId frame_id_;
2213 const int slot_;
2214 const JDWP::JdwpTag tag_;
2215 const uint64_t value_;
2216 const size_t width_;
2217 };
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002218
2219 ScopedObjectAccessUnchecked soa(Thread::Current());
jeffhaoa77f0f62012-12-05 17:19:31 -08002220 MutexLock mu(soa.Self(), *Locks::thread_list_lock_);
Elliott Hughes221229c2013-01-08 18:17:50 -08002221 Thread* thread;
2222 JDWP::JdwpError error = DecodeThread(soa, thread_id, thread);
2223 if (error != JDWP::ERR_NONE) {
2224 return;
2225 }
Elliott Hughes08fc03a2012-06-26 17:34:00 -07002226 UniquePtr<Context> context(Context::Create());
Ian Rogers7a22fa62013-01-23 12:16:16 -08002227 SetLocalVisitor visitor(thread, context.get(), frame_id, slot, tag, value, width);
Ian Rogers0399dde2012-06-06 17:09:28 -07002228 visitor.WalkStack();
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002229}
2230
Brian Carlstromea46f952013-07-30 01:26:50 -07002231void Dbg::PostLocationEvent(const mirror::ArtMethod* m, int dex_pc,
Ian Rogers62d6c772013-02-27 08:32:07 -08002232 mirror::Object* this_object, int event_flags) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002233 mirror::Class* c = m->GetDeclaringClass();
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08002234
2235 JDWP::JdwpLocation location;
Elliott Hughes74847412012-06-20 18:10:21 -07002236 location.type_tag = c->IsInterface() ? JDWP::TT_INTERFACE : JDWP::TT_CLASS;
Elliott Hughes64f574f2013-02-20 14:57:12 -08002237 location.class_id = gRegistry->AddRefType(c);
Elliott Hughes74847412012-06-20 18:10:21 -07002238 location.method_id = ToMethodId(m);
Elliott Hughes972a47b2012-02-21 18:16:06 -08002239 location.dex_pc = m->IsNative() ? -1 : dex_pc;
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08002240
Elliott Hughes64f574f2013-02-20 14:57:12 -08002241 // If 'this_object' isn't already in the registry, we know that we're not looking for it,
2242 // so there's no point adding it to the registry and burning through ids.
2243 JDWP::ObjectId this_id = 0;
2244 if (gRegistry->Contains(this_object)) {
2245 this_id = gRegistry->Add(this_object);
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08002246 }
Elliott Hughes64f574f2013-02-20 14:57:12 -08002247 gJdwpState->PostLocationEvent(&location, this_id, event_flags);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002248}
2249
Ian Rogers62d6c772013-02-27 08:32:07 -08002250void Dbg::PostException(Thread* thread, const ThrowLocation& throw_location,
Brian Carlstromea46f952013-07-30 01:26:50 -07002251 mirror::ArtMethod* catch_method,
Elliott Hughes64f574f2013-02-20 14:57:12 -08002252 uint32_t catch_dex_pc, mirror::Throwable* exception_object) {
Elliott Hughesc0f09332012-03-26 13:27:06 -07002253 if (!IsDebuggerActive()) {
Ian Rogers0ad5bb82011-12-07 10:16:32 -08002254 return;
2255 }
Elliott Hughes4740cdf2011-12-07 14:07:12 -08002256
Ian Rogers62d6c772013-02-27 08:32:07 -08002257 JDWP::JdwpLocation jdwp_throw_location;
2258 SetLocation(jdwp_throw_location, throw_location.GetMethod(), throw_location.GetDexPc());
Elliott Hughesd07986f2011-12-06 18:27:45 -08002259 JDWP::JdwpLocation catch_location;
Elliott Hughescaf76542012-06-28 16:08:22 -07002260 SetLocation(catch_location, catch_method, catch_dex_pc);
Elliott Hughesd07986f2011-12-06 18:27:45 -08002261
2262 // We need 'this' for InstanceOnly filters.
Ian Rogers62d6c772013-02-27 08:32:07 -08002263 JDWP::ObjectId this_id = gRegistry->Add(throw_location.GetThis());
Elliott Hughes64f574f2013-02-20 14:57:12 -08002264 JDWP::ObjectId exception_id = gRegistry->Add(exception_object);
2265 JDWP::RefTypeId exception_class_id = gRegistry->AddRefType(exception_object->GetClass());
Elliott Hughesd07986f2011-12-06 18:27:45 -08002266
Ian Rogers62d6c772013-02-27 08:32:07 -08002267 gJdwpState->PostException(&jdwp_throw_location, exception_id, exception_class_id, &catch_location,
2268 this_id);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002269}
2270
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002271void Dbg::PostClassPrepare(mirror::Class* c) {
Elliott Hughesc0f09332012-03-26 13:27:06 -07002272 if (!IsDebuggerActive()) {
Elliott Hughes4740cdf2011-12-07 14:07:12 -08002273 return;
2274 }
2275
Elliott Hughes3d30d9b2011-12-07 17:35:48 -08002276 // OLD-TODO - we currently always send both "verified" and "prepared" since
Elliott Hughes4740cdf2011-12-07 14:07:12 -08002277 // debuggers seem to like that. There might be some advantage to honesty,
2278 // since the class may not yet be verified.
2279 int state = JDWP::CS_VERIFIED | JDWP::CS_PREPARED;
2280 JDWP::JdwpTypeTag tag = c->IsInterface() ? JDWP::TT_INTERFACE : JDWP::TT_CLASS;
Ian Rogersfc0e94b2013-09-23 23:51:32 -07002281 gJdwpState->PostClassPrepare(tag, gRegistry->Add(c),
Ian Rogersdfb325e2013-10-30 01:00:44 -07002282 ClassHelper(c).GetDescriptor(), state);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002283}
2284
Ian Rogers62d6c772013-02-27 08:32:07 -08002285void Dbg::UpdateDebugger(Thread* thread, mirror::Object* this_object,
Brian Carlstromea46f952013-07-30 01:26:50 -07002286 const mirror::ArtMethod* m, uint32_t dex_pc) {
Ian Rogers62d6c772013-02-27 08:32:07 -08002287 if (!IsDebuggerActive() || dex_pc == static_cast<uint32_t>(-2) /* fake method exit */) {
Elliott Hughes2aa2e392012-02-17 17:15:43 -08002288 return;
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08002289 }
2290
Elliott Hughes2aa2e392012-02-17 17:15:43 -08002291 int event_flags = 0;
2292
Elliott Hughes86964332012-02-15 19:37:42 -08002293 if (IsBreakpoint(m, dex_pc)) {
2294 event_flags |= kBreakpoint;
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08002295 }
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08002296
jeffhao09bfc6a2012-12-11 18:11:43 -08002297 {
2298 // If the debugger is single-stepping one of our threads, check to
2299 // see if we're that thread and we've reached a step point.
2300 MutexLock mu(Thread::Current(), *Locks::breakpoint_lock_);
Ian Rogers62d6c772013-02-27 08:32:07 -08002301 if (gSingleStepControl.is_active && gSingleStepControl.thread == thread) {
jeffhao09bfc6a2012-12-11 18:11:43 -08002302 CHECK(!m->IsNative());
2303 if (gSingleStepControl.step_depth == JDWP::SD_INTO) {
2304 // Step into method calls. We break when the line number
2305 // or method pointer changes. If we're in SS_MIN mode, we
2306 // always stop.
2307 if (gSingleStepControl.method != m) {
2308 event_flags |= kSingleStep;
2309 VLOG(jdwp) << "SS new method";
2310 } else if (gSingleStepControl.step_size == JDWP::SS_MIN) {
Elliott Hughes86964332012-02-15 19:37:42 -08002311 event_flags |= kSingleStep;
2312 VLOG(jdwp) << "SS new instruction";
Elliott Hughes2435a572012-02-17 16:07:41 -08002313 } else if (gSingleStepControl.dex_pcs.find(dex_pc) == gSingleStepControl.dex_pcs.end()) {
2314 event_flags |= kSingleStep;
2315 VLOG(jdwp) << "SS new line";
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08002316 }
jeffhao09bfc6a2012-12-11 18:11:43 -08002317 } else if (gSingleStepControl.step_depth == JDWP::SD_OVER) {
2318 // Step over method calls. We break when the line number is
2319 // different and the frame depth is <= the original frame
2320 // depth. (We can't just compare on the method, because we
2321 // might get unrolled past it by an exception, and it's tricky
2322 // to identify recursion.)
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08002323
Ian Rogers62d6c772013-02-27 08:32:07 -08002324 int stack_depth = GetStackDepth(thread);
Elliott Hughes86964332012-02-15 19:37:42 -08002325
jeffhao09bfc6a2012-12-11 18:11:43 -08002326 if (stack_depth < gSingleStepControl.stack_depth) {
2327 // popped up one or more frames, always trigger
2328 event_flags |= kSingleStep;
2329 VLOG(jdwp) << "SS method pop";
2330 } else if (stack_depth == gSingleStepControl.stack_depth) {
2331 // same depth, see if we moved
2332 if (gSingleStepControl.step_size == JDWP::SS_MIN) {
2333 event_flags |= kSingleStep;
2334 VLOG(jdwp) << "SS new instruction";
2335 } else if (gSingleStepControl.dex_pcs.find(dex_pc) == gSingleStepControl.dex_pcs.end()) {
2336 event_flags |= kSingleStep;
2337 VLOG(jdwp) << "SS new line";
2338 }
2339 }
2340 } else {
2341 CHECK_EQ(gSingleStepControl.step_depth, JDWP::SD_OUT);
2342 // Return from the current method. We break when the frame
2343 // depth pops up.
2344
2345 // This differs from the "method exit" break in that it stops
2346 // with the PC at the next instruction in the returned-to
2347 // function, rather than the end of the returning function.
2348
Ian Rogers62d6c772013-02-27 08:32:07 -08002349 int stack_depth = GetStackDepth(thread);
jeffhao09bfc6a2012-12-11 18:11:43 -08002350 if (stack_depth < gSingleStepControl.stack_depth) {
2351 event_flags |= kSingleStep;
2352 VLOG(jdwp) << "SS method pop";
2353 }
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08002354 }
2355 }
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08002356 }
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08002357
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08002358 // If there's something interesting going on, see if it matches one
2359 // of the debugger filters.
2360 if (event_flags != 0) {
Ian Rogers62d6c772013-02-27 08:32:07 -08002361 Dbg::PostLocationEvent(m, dex_pc, this_object, event_flags);
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08002362 }
2363}
2364
Elliott Hughes86964332012-02-15 19:37:42 -08002365void Dbg::WatchLocation(const JDWP::JdwpLocation* location) {
jeffhao09bfc6a2012-12-11 18:11:43 -08002366 MutexLock mu(Thread::Current(), *Locks::breakpoint_lock_);
Brian Carlstromea46f952013-07-30 01:26:50 -07002367 mirror::ArtMethod* m = FromMethodId(location->method_id);
Elliott Hughes972a47b2012-02-21 18:16:06 -08002368 gBreakpoints.push_back(Breakpoint(m, location->dex_pc));
Elliott Hughes86964332012-02-15 19:37:42 -08002369 VLOG(jdwp) << "Set breakpoint #" << (gBreakpoints.size() - 1) << ": " << gBreakpoints[gBreakpoints.size() - 1];
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002370}
2371
Elliott Hughes86964332012-02-15 19:37:42 -08002372void Dbg::UnwatchLocation(const JDWP::JdwpLocation* location) {
jeffhao09bfc6a2012-12-11 18:11:43 -08002373 MutexLock mu(Thread::Current(), *Locks::breakpoint_lock_);
Brian Carlstromea46f952013-07-30 01:26:50 -07002374 mirror::ArtMethod* m = FromMethodId(location->method_id);
Elliott Hughes86964332012-02-15 19:37:42 -08002375 for (size_t i = 0; i < gBreakpoints.size(); ++i) {
Elliott Hughes972a47b2012-02-21 18:16:06 -08002376 if (gBreakpoints[i].method == m && gBreakpoints[i].dex_pc == location->dex_pc) {
Elliott Hughes86964332012-02-15 19:37:42 -08002377 VLOG(jdwp) << "Removed breakpoint #" << i << ": " << gBreakpoints[i];
2378 gBreakpoints.erase(gBreakpoints.begin() + i);
2379 return;
2380 }
2381 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002382}
2383
Jeff Hao449db332013-04-12 18:30:52 -07002384// Scoped utility class to suspend a thread so that we may do tasks such as walk its stack. Doesn't
2385// cause suspension if the thread is the current thread.
2386class ScopedThreadSuspension {
2387 public:
Ian Rogers33e95662013-05-20 20:29:14 -07002388 ScopedThreadSuspension(Thread* self, JDWP::ObjectId thread_id)
2389 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) :
Jeff Hao449db332013-04-12 18:30:52 -07002390 thread_(NULL),
2391 error_(JDWP::ERR_NONE),
2392 self_suspend_(false),
Ian Rogers33e95662013-05-20 20:29:14 -07002393 other_suspend_(false) {
Jeff Hao449db332013-04-12 18:30:52 -07002394 ScopedObjectAccessUnchecked soa(self);
2395 {
2396 MutexLock mu(soa.Self(), *Locks::thread_list_lock_);
2397 error_ = DecodeThread(soa, thread_id, thread_);
2398 }
2399 if (error_ == JDWP::ERR_NONE) {
2400 if (thread_ == soa.Self()) {
2401 self_suspend_ = true;
2402 } else {
2403 soa.Self()->TransitionFromRunnableToSuspended(kWaitingForDebuggerSuspension);
2404 jobject thread_peer = gRegistry->GetJObject(thread_id);
2405 bool timed_out;
Ian Rogersd9c4fc92013-10-01 19:45:43 -07002406 Thread* suspended_thread = ThreadList::SuspendThreadByPeer(thread_peer, true, true,
2407 &timed_out);
Jeff Hao449db332013-04-12 18:30:52 -07002408 CHECK_EQ(soa.Self()->TransitionFromSuspendedToRunnable(), kWaitingForDebuggerSuspension);
2409 if (suspended_thread == NULL) {
2410 // Thread terminated from under us while suspending.
2411 error_ = JDWP::ERR_INVALID_THREAD;
2412 } else {
2413 CHECK_EQ(suspended_thread, thread_);
2414 other_suspend_ = true;
2415 }
2416 }
2417 }
Elliott Hughes2435a572012-02-17 16:07:41 -08002418 }
Elliott Hughes86964332012-02-15 19:37:42 -08002419
Jeff Hao449db332013-04-12 18:30:52 -07002420 Thread* GetThread() const {
2421 return thread_;
2422 }
2423
2424 JDWP::JdwpError GetError() const {
2425 return error_;
2426 }
2427
2428 ~ScopedThreadSuspension() {
2429 if (other_suspend_) {
2430 Runtime::Current()->GetThreadList()->Resume(thread_, true);
2431 }
2432 }
2433
2434 private:
2435 Thread* thread_;
2436 JDWP::JdwpError error_;
2437 bool self_suspend_;
2438 bool other_suspend_;
2439};
2440
2441JDWP::JdwpError Dbg::ConfigureStep(JDWP::ObjectId thread_id, JDWP::JdwpStepSize step_size,
2442 JDWP::JdwpStepDepth step_depth) {
2443 Thread* self = Thread::Current();
2444 ScopedThreadSuspension sts(self, thread_id);
2445 if (sts.GetError() != JDWP::ERR_NONE) {
2446 return sts.GetError();
2447 }
2448
2449 MutexLock mu2(self, *Locks::breakpoint_lock_);
Elliott Hughes86964332012-02-15 19:37:42 -08002450 // TODO: there's no theoretical reason why we couldn't support single-stepping
2451 // of multiple threads at once, but we never did so historically.
Jeff Hao449db332013-04-12 18:30:52 -07002452 if (gSingleStepControl.thread != NULL && sts.GetThread() != gSingleStepControl.thread) {
Elliott Hughes86964332012-02-15 19:37:42 -08002453 LOG(WARNING) << "single-step already active for " << *gSingleStepControl.thread
Jeff Hao449db332013-04-12 18:30:52 -07002454 << "; switching to " << *sts.GetThread();
Elliott Hughes86964332012-02-15 19:37:42 -08002455 }
2456
Elliott Hughes2435a572012-02-17 16:07:41 -08002457 //
2458 // Work out what Method* we're in, the current line number, and how deep the stack currently
2459 // is for step-out.
2460 //
2461
Ian Rogers0399dde2012-06-06 17:09:28 -07002462 struct SingleStepStackVisitor : public StackVisitor {
Brian Carlstrom93ba8932013-07-17 21:31:49 -07002463 explicit SingleStepStackVisitor(Thread* thread)
jeffhao09bfc6a2012-12-11 18:11:43 -08002464 EXCLUSIVE_LOCKS_REQUIRED(Locks::breakpoint_lock_)
Ian Rogersb726dcb2012-09-05 08:57:23 -07002465 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_)
Ian Rogers7a22fa62013-01-23 12:16:16 -08002466 : StackVisitor(thread, NULL) {
Elliott Hughes86964332012-02-15 19:37:42 -08002467 gSingleStepControl.method = NULL;
2468 gSingleStepControl.stack_depth = 0;
2469 }
Ian Rogersca190662012-06-26 15:45:57 -07002470
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002471 // TODO: Enable annotalysis. We know lock is held in constructor, but abstraction confuses
2472 // annotalysis.
2473 bool VisitFrame() NO_THREAD_SAFETY_ANALYSIS {
jeffhao09bfc6a2012-12-11 18:11:43 -08002474 Locks::breakpoint_lock_->AssertHeld(Thread::Current());
Brian Carlstromea46f952013-07-30 01:26:50 -07002475 const mirror::ArtMethod* m = GetMethod();
Ian Rogers0399dde2012-06-06 17:09:28 -07002476 if (!m->IsRuntimeMethod()) {
Elliott Hughes86964332012-02-15 19:37:42 -08002477 ++gSingleStepControl.stack_depth;
2478 if (gSingleStepControl.method == NULL) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002479 const mirror::DexCache* dex_cache = m->GetDeclaringClass()->GetDexCache();
Elliott Hughes2435a572012-02-17 16:07:41 -08002480 gSingleStepControl.method = m;
2481 gSingleStepControl.line_number = -1;
2482 if (dex_cache != NULL) {
Ian Rogers4445a7e2012-10-05 17:19:13 -07002483 const DexFile& dex_file = *dex_cache->GetDexFile();
Ian Rogers0399dde2012-06-06 17:09:28 -07002484 gSingleStepControl.line_number = dex_file.GetLineNumFromPC(m, GetDexPc());
Elliott Hughes2435a572012-02-17 16:07:41 -08002485 }
Elliott Hughes86964332012-02-15 19:37:42 -08002486 }
2487 }
Elliott Hughes530fa002012-03-12 11:44:49 -07002488 return true;
Elliott Hughes86964332012-02-15 19:37:42 -08002489 }
2490 };
Jeff Hao449db332013-04-12 18:30:52 -07002491
2492 SingleStepStackVisitor visitor(sts.GetThread());
Ian Rogers0399dde2012-06-06 17:09:28 -07002493 visitor.WalkStack();
Elliott Hughes86964332012-02-15 19:37:42 -08002494
Elliott Hughes2435a572012-02-17 16:07:41 -08002495 //
2496 // Find the dex_pc values that correspond to the current line, for line-based single-stepping.
2497 //
2498
2499 struct DebugCallbackContext {
jeffhao09bfc6a2012-12-11 18:11:43 -08002500 DebugCallbackContext() EXCLUSIVE_LOCKS_REQUIRED(Locks::breakpoint_lock_) {
Elliott Hughes2435a572012-02-17 16:07:41 -08002501 last_pc_valid = false;
2502 last_pc = 0;
Elliott Hughes2435a572012-02-17 16:07:41 -08002503 }
2504
jeffhao09bfc6a2012-12-11 18:11:43 -08002505 // TODO: Enable annotalysis. We know lock is held in constructor, but abstraction confuses
2506 // annotalysis.
2507 static bool Callback(void* raw_context, uint32_t address, uint32_t line_number) NO_THREAD_SAFETY_ANALYSIS {
2508 Locks::breakpoint_lock_->AssertHeld(Thread::Current());
Elliott Hughes2435a572012-02-17 16:07:41 -08002509 DebugCallbackContext* context = reinterpret_cast<DebugCallbackContext*>(raw_context);
2510 if (static_cast<int32_t>(line_number) == gSingleStepControl.line_number) {
2511 if (!context->last_pc_valid) {
2512 // Everything from this address until the next line change is ours.
2513 context->last_pc = address;
2514 context->last_pc_valid = true;
2515 }
2516 // Otherwise, if we're already in a valid range for this line,
2517 // just keep going (shouldn't really happen)...
Brian Carlstrom7934ac22013-07-26 10:54:15 -07002518 } else if (context->last_pc_valid) { // and the line number is new
Elliott Hughes2435a572012-02-17 16:07:41 -08002519 // Add everything from the last entry up until here to the set
2520 for (uint32_t dex_pc = context->last_pc; dex_pc < address; ++dex_pc) {
2521 gSingleStepControl.dex_pcs.insert(dex_pc);
2522 }
2523 context->last_pc_valid = false;
2524 }
Brian Carlstrom7934ac22013-07-26 10:54:15 -07002525 return false; // There may be multiple entries for any given line.
Elliott Hughes2435a572012-02-17 16:07:41 -08002526 }
2527
jeffhao09bfc6a2012-12-11 18:11:43 -08002528 // TODO: Enable annotalysis. We know lock is held in constructor, but abstraction confuses
2529 // annotalysis.
2530 ~DebugCallbackContext() NO_THREAD_SAFETY_ANALYSIS {
2531 Locks::breakpoint_lock_->AssertHeld(Thread::Current());
Elliott Hughes2435a572012-02-17 16:07:41 -08002532 // If the line number was the last in the position table...
2533 if (last_pc_valid) {
2534 size_t end = MethodHelper(gSingleStepControl.method).GetCodeItem()->insns_size_in_code_units_;
2535 for (uint32_t dex_pc = last_pc; dex_pc < end; ++dex_pc) {
2536 gSingleStepControl.dex_pcs.insert(dex_pc);
2537 }
2538 }
2539 }
2540
2541 bool last_pc_valid;
2542 uint32_t last_pc;
2543 };
Elliott Hughes3e2e1a22012-02-21 11:33:41 -08002544 gSingleStepControl.dex_pcs.clear();
Brian Carlstromea46f952013-07-30 01:26:50 -07002545 const mirror::ArtMethod* m = gSingleStepControl.method;
Elliott Hughes3e2e1a22012-02-21 11:33:41 -08002546 if (m->IsNative()) {
2547 gSingleStepControl.line_number = -1;
2548 } else {
2549 DebugCallbackContext context;
2550 MethodHelper mh(m);
2551 mh.GetDexFile().DecodeDebugInfo(mh.GetCodeItem(), m->IsStatic(), m->GetDexMethodIndex(),
2552 DebugCallbackContext::Callback, NULL, &context);
2553 }
Elliott Hughes2435a572012-02-17 16:07:41 -08002554
2555 //
2556 // Everything else...
2557 //
2558
Jeff Hao449db332013-04-12 18:30:52 -07002559 gSingleStepControl.thread = sts.GetThread();
Elliott Hughes86964332012-02-15 19:37:42 -08002560 gSingleStepControl.step_size = step_size;
2561 gSingleStepControl.step_depth = step_depth;
2562 gSingleStepControl.is_active = true;
2563
Elliott Hughes2435a572012-02-17 16:07:41 -08002564 if (VLOG_IS_ON(jdwp)) {
2565 VLOG(jdwp) << "Single-step thread: " << *gSingleStepControl.thread;
2566 VLOG(jdwp) << "Single-step step size: " << gSingleStepControl.step_size;
2567 VLOG(jdwp) << "Single-step step depth: " << gSingleStepControl.step_depth;
2568 VLOG(jdwp) << "Single-step current method: " << PrettyMethod(gSingleStepControl.method);
2569 VLOG(jdwp) << "Single-step current line: " << gSingleStepControl.line_number;
2570 VLOG(jdwp) << "Single-step current stack depth: " << gSingleStepControl.stack_depth;
2571 VLOG(jdwp) << "Single-step dex_pc values:";
2572 for (std::set<uint32_t>::iterator it = gSingleStepControl.dex_pcs.begin() ; it != gSingleStepControl.dex_pcs.end(); ++it) {
Elliott Hughes229feb72012-02-23 13:33:29 -08002573 VLOG(jdwp) << StringPrintf(" %#x", *it);
Elliott Hughes2435a572012-02-17 16:07:41 -08002574 }
2575 }
2576
2577 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002578}
2579
Elliott Hughes221229c2013-01-08 18:17:50 -08002580void Dbg::UnconfigureStep(JDWP::ObjectId /*thread_id*/) {
jeffhao09bfc6a2012-12-11 18:11:43 -08002581 MutexLock mu(Thread::Current(), *Locks::breakpoint_lock_);
Elliott Hughesf8349362012-06-18 15:00:06 -07002582
Elliott Hughes86964332012-02-15 19:37:42 -08002583 gSingleStepControl.is_active = false;
2584 gSingleStepControl.thread = NULL;
Elliott Hughes2435a572012-02-17 16:07:41 -08002585 gSingleStepControl.dex_pcs.clear();
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002586}
2587
Elliott Hughes45651fd2012-02-21 15:48:20 -08002588static char JdwpTagToShortyChar(JDWP::JdwpTag tag) {
2589 switch (tag) {
2590 default:
2591 LOG(FATAL) << "unknown JDWP tag: " << PrintableChar(tag);
2592
2593 // Primitives.
2594 case JDWP::JT_BYTE: return 'B';
2595 case JDWP::JT_CHAR: return 'C';
2596 case JDWP::JT_FLOAT: return 'F';
2597 case JDWP::JT_DOUBLE: return 'D';
2598 case JDWP::JT_INT: return 'I';
2599 case JDWP::JT_LONG: return 'J';
2600 case JDWP::JT_SHORT: return 'S';
2601 case JDWP::JT_VOID: return 'V';
2602 case JDWP::JT_BOOLEAN: return 'Z';
2603
2604 // Reference types.
2605 case JDWP::JT_ARRAY:
2606 case JDWP::JT_OBJECT:
2607 case JDWP::JT_STRING:
2608 case JDWP::JT_THREAD:
2609 case JDWP::JT_THREAD_GROUP:
2610 case JDWP::JT_CLASS_LOADER:
2611 case JDWP::JT_CLASS_OBJECT:
2612 return 'L';
2613 }
2614}
2615
Elliott Hughes88d63092013-01-09 09:55:54 -08002616JDWP::JdwpError Dbg::InvokeMethod(JDWP::ObjectId thread_id, JDWP::ObjectId object_id,
2617 JDWP::RefTypeId class_id, JDWP::MethodId method_id,
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002618 uint32_t arg_count, uint64_t* arg_values,
2619 JDWP::JdwpTag* arg_types, uint32_t options,
2620 JDWP::JdwpTag* pResultTag, uint64_t* pResultValue,
2621 JDWP::ObjectId* pExceptionId) {
Elliott Hughesd07986f2011-12-06 18:27:45 -08002622 ThreadList* thread_list = Runtime::Current()->GetThreadList();
2623
2624 Thread* targetThread = NULL;
2625 DebugInvokeReq* req = NULL;
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002626 Thread* self = Thread::Current();
Elliott Hughesd07986f2011-12-06 18:27:45 -08002627 {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002628 ScopedObjectAccessUnchecked soa(self);
Ian Rogers50b35e22012-10-04 10:09:15 -07002629 MutexLock mu(soa.Self(), *Locks::thread_list_lock_);
Elliott Hughes221229c2013-01-08 18:17:50 -08002630 JDWP::JdwpError error = DecodeThread(soa, thread_id, targetThread);
2631 if (error != JDWP::ERR_NONE) {
2632 LOG(ERROR) << "InvokeMethod request for invalid thread id " << thread_id;
2633 return error;
Elliott Hughesd07986f2011-12-06 18:27:45 -08002634 }
2635 req = targetThread->GetInvokeReq();
2636 if (!req->ready) {
2637 LOG(ERROR) << "InvokeMethod request for thread not stopped by event: " << *targetThread;
2638 return JDWP::ERR_INVALID_THREAD;
2639 }
2640
2641 /*
2642 * We currently have a bug where we don't successfully resume the
2643 * target thread if the suspend count is too deep. We're expected to
2644 * require one "resume" for each "suspend", but when asked to execute
2645 * a method we have to resume fully and then re-suspend it back to the
2646 * same level. (The easiest way to cause this is to type "suspend"
2647 * multiple times in jdb.)
2648 *
2649 * It's unclear what this means when the event specifies "resume all"
2650 * and some threads are suspended more deeply than others. This is
2651 * a rare problem, so for now we just prevent it from hanging forever
2652 * by rejecting the method invocation request. Without this, we will
2653 * be stuck waiting on a suspended thread.
2654 */
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002655 int suspend_count;
2656 {
Ian Rogers50b35e22012-10-04 10:09:15 -07002657 MutexLock mu2(soa.Self(), *Locks::thread_suspend_count_lock_);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002658 suspend_count = targetThread->GetSuspendCount();
2659 }
Elliott Hughesd07986f2011-12-06 18:27:45 -08002660 if (suspend_count > 1) {
2661 LOG(ERROR) << *targetThread << " suspend count too deep for method invocation: " << suspend_count;
Brian Carlstrom7934ac22013-07-26 10:54:15 -07002662 return JDWP::ERR_THREAD_SUSPENDED; // Probably not expected here.
Elliott Hughesd07986f2011-12-06 18:27:45 -08002663 }
2664
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08002665 JDWP::JdwpError status;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002666 mirror::Object* receiver = gRegistry->Get<mirror::Object*>(object_id);
Elliott Hughes64f574f2013-02-20 14:57:12 -08002667 if (receiver == ObjectRegistry::kInvalidObject) {
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08002668 return JDWP::ERR_INVALID_OBJECT;
2669 }
Elliott Hughes45651fd2012-02-21 15:48:20 -08002670
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002671 mirror::Object* thread = gRegistry->Get<mirror::Object*>(thread_id);
Elliott Hughes64f574f2013-02-20 14:57:12 -08002672 if (thread == ObjectRegistry::kInvalidObject) {
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08002673 return JDWP::ERR_INVALID_OBJECT;
2674 }
Elliott Hughes45651fd2012-02-21 15:48:20 -08002675 // TODO: check that 'thread' is actually a java.lang.Thread!
2676
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002677 mirror::Class* c = DecodeClass(class_id, status);
Elliott Hughes45651fd2012-02-21 15:48:20 -08002678 if (c == NULL) {
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08002679 return status;
2680 }
Elliott Hughes45651fd2012-02-21 15:48:20 -08002681
Brian Carlstromea46f952013-07-30 01:26:50 -07002682 mirror::ArtMethod* m = FromMethodId(method_id);
Elliott Hughes45651fd2012-02-21 15:48:20 -08002683 if (m->IsStatic() != (receiver == NULL)) {
2684 return JDWP::ERR_INVALID_METHODID;
2685 }
2686 if (m->IsStatic()) {
2687 if (m->GetDeclaringClass() != c) {
2688 return JDWP::ERR_INVALID_METHODID;
2689 }
2690 } else {
2691 if (!m->GetDeclaringClass()->IsAssignableFrom(c)) {
2692 return JDWP::ERR_INVALID_METHODID;
2693 }
2694 }
2695
2696 // Check the argument list matches the method.
2697 MethodHelper mh(m);
2698 if (mh.GetShortyLength() - 1 != arg_count) {
2699 return JDWP::ERR_ILLEGAL_ARGUMENT;
2700 }
2701 const char* shorty = mh.GetShorty();
Elliott Hughes09201632013-04-15 15:50:07 -07002702 const DexFile::TypeList* types = mh.GetParameterTypeList();
Elliott Hughes45651fd2012-02-21 15:48:20 -08002703 for (size_t i = 0; i < arg_count; ++i) {
2704 if (shorty[i + 1] != JdwpTagToShortyChar(arg_types[i])) {
2705 return JDWP::ERR_ILLEGAL_ARGUMENT;
2706 }
Elliott Hughes09201632013-04-15 15:50:07 -07002707
2708 if (shorty[i + 1] == 'L') {
2709 // Did we really get an argument of an appropriate reference type?
2710 mirror::Class* parameter_type = mh.GetClassFromTypeIdx(types->GetTypeItem(i).type_idx_);
2711 mirror::Object* argument = gRegistry->Get<mirror::Object*>(arg_values[i]);
2712 if (argument == ObjectRegistry::kInvalidObject) {
2713 return JDWP::ERR_INVALID_OBJECT;
2714 }
2715 if (!argument->InstanceOf(parameter_type)) {
2716 return JDWP::ERR_ILLEGAL_ARGUMENT;
2717 }
2718
2719 // Turn the on-the-wire ObjectId into a jobject.
2720 jvalue& v = reinterpret_cast<jvalue&>(arg_values[i]);
2721 v.l = gRegistry->GetJObject(arg_values[i]);
2722 }
Elliott Hughes45651fd2012-02-21 15:48:20 -08002723 }
2724
2725 req->receiver_ = receiver;
2726 req->thread_ = thread;
2727 req->class_ = c;
2728 req->method_ = m;
2729 req->arg_count_ = arg_count;
2730 req->arg_values_ = arg_values;
Elliott Hughesd07986f2011-12-06 18:27:45 -08002731 req->options_ = options;
2732 req->invoke_needed_ = true;
2733 }
2734
2735 // The fact that we've released the thread list lock is a bit risky --- if the thread goes
2736 // away we're sitting high and dry -- but we must release this before the ResumeAllThreads
2737 // call, and it's unwise to hold it during WaitForSuspend.
2738
2739 {
2740 /*
2741 * We change our (JDWP thread) status, which should be THREAD_RUNNING,
Elliott Hughes81ff3182012-03-23 20:35:56 -07002742 * so we can suspend for a GC if the invoke request causes us to
Elliott Hughesd07986f2011-12-06 18:27:45 -08002743 * run out of memory. It's also a good idea to change it before locking
2744 * the invokeReq mutex, although that should never be held for long.
2745 */
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002746 self->TransitionFromRunnableToSuspended(kWaitingForDebuggerSend);
Elliott Hughesd07986f2011-12-06 18:27:45 -08002747
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08002748 VLOG(jdwp) << " Transferring control to event thread";
Elliott Hughesd07986f2011-12-06 18:27:45 -08002749 {
Ian Rogers50b35e22012-10-04 10:09:15 -07002750 MutexLock mu(self, req->lock_);
Elliott Hughesd07986f2011-12-06 18:27:45 -08002751
2752 if ((options & JDWP::INVOKE_SINGLE_THREADED) == 0) {
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08002753 VLOG(jdwp) << " Resuming all threads";
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002754 thread_list->UndoDebuggerSuspensions();
Elliott Hughesd07986f2011-12-06 18:27:45 -08002755 } else {
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08002756 VLOG(jdwp) << " Resuming event thread only";
Elliott Hughesd07986f2011-12-06 18:27:45 -08002757 thread_list->Resume(targetThread, true);
2758 }
2759
2760 // Wait for the request to finish executing.
2761 while (req->invoke_needed_) {
Ian Rogersc604d732012-10-14 16:09:54 -07002762 req->cond_.Wait(self);
Elliott Hughesd07986f2011-12-06 18:27:45 -08002763 }
2764 }
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08002765 VLOG(jdwp) << " Control has returned from event thread";
Elliott Hughesd07986f2011-12-06 18:27:45 -08002766
2767 /* wait for thread to re-suspend itself */
Brian Carlstromdf629502013-07-17 22:39:56 -07002768 SuspendThread(thread_id, false /* request_suspension */);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002769 self->TransitionFromSuspendedToRunnable();
Elliott Hughesd07986f2011-12-06 18:27:45 -08002770 }
2771
2772 /*
2773 * Suspend the threads. We waited for the target thread to suspend
2774 * itself, so all we need to do is suspend the others.
2775 *
2776 * The suspendAllThreads() call will double-suspend the event thread,
2777 * so we want to resume the target thread once to keep the books straight.
2778 */
2779 if ((options & JDWP::INVOKE_SINGLE_THREADED) == 0) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002780 self->TransitionFromRunnableToSuspended(kWaitingForDebuggerSuspension);
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08002781 VLOG(jdwp) << " Suspending all threads";
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002782 thread_list->SuspendAllForDebugger();
2783 self->TransitionFromSuspendedToRunnable();
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08002784 VLOG(jdwp) << " Resuming event thread to balance the count";
Elliott Hughesd07986f2011-12-06 18:27:45 -08002785 thread_list->Resume(targetThread, true);
2786 }
2787
2788 // Copy the result.
2789 *pResultTag = req->result_tag;
2790 if (IsPrimitiveTag(req->result_tag)) {
Elliott Hughesf24d3ce2012-04-11 17:43:37 -07002791 *pResultValue = req->result_value.GetJ();
Elliott Hughesd07986f2011-12-06 18:27:45 -08002792 } else {
Elliott Hughesf24d3ce2012-04-11 17:43:37 -07002793 *pResultValue = gRegistry->Add(req->result_value.GetL());
Elliott Hughesd07986f2011-12-06 18:27:45 -08002794 }
2795 *pExceptionId = req->exception;
2796 return req->error;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002797}
2798
2799void Dbg::ExecuteMethod(DebugInvokeReq* pReq) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002800 ScopedObjectAccess soa(Thread::Current());
Elliott Hughesd07986f2011-12-06 18:27:45 -08002801
Elliott Hughes81ff3182012-03-23 20:35:56 -07002802 // We can be called while an exception is pending. We need
Elliott Hughesd07986f2011-12-06 18:27:45 -08002803 // to preserve that across the method invocation.
Ian Rogers62d6c772013-02-27 08:32:07 -08002804 SirtRef<mirror::Object> old_throw_this_object(soa.Self(), NULL);
Brian Carlstromea46f952013-07-30 01:26:50 -07002805 SirtRef<mirror::ArtMethod> old_throw_method(soa.Self(), NULL);
Ian Rogers62d6c772013-02-27 08:32:07 -08002806 SirtRef<mirror::Throwable> old_exception(soa.Self(), NULL);
2807 uint32_t old_throw_dex_pc;
2808 {
2809 ThrowLocation old_throw_location;
2810 mirror::Throwable* old_exception_obj = soa.Self()->GetException(&old_throw_location);
2811 old_throw_this_object.reset(old_throw_location.GetThis());
2812 old_throw_method.reset(old_throw_location.GetMethod());
2813 old_exception.reset(old_exception_obj);
2814 old_throw_dex_pc = old_throw_location.GetDexPc();
2815 soa.Self()->ClearException();
2816 }
Elliott Hughesd07986f2011-12-06 18:27:45 -08002817
2818 // Translate the method through the vtable, unless the debugger wants to suppress it.
Brian Carlstromea46f952013-07-30 01:26:50 -07002819 mirror::ArtMethod* m = pReq->method_;
Elliott Hughesd07986f2011-12-06 18:27:45 -08002820 if ((pReq->options_ & JDWP::INVOKE_NONVIRTUAL) == 0 && pReq->receiver_ != NULL) {
Brian Carlstromea46f952013-07-30 01:26:50 -07002821 mirror::ArtMethod* actual_method = pReq->class_->FindVirtualMethodForVirtualOrInterface(pReq->method_);
Elliott Hughes45651fd2012-02-21 15:48:20 -08002822 if (actual_method != m) {
2823 VLOG(jdwp) << "ExecuteMethod translated " << PrettyMethod(m) << " to " << PrettyMethod(actual_method);
2824 m = actual_method;
2825 }
Elliott Hughesd07986f2011-12-06 18:27:45 -08002826 }
Elliott Hughescfa9cfa2013-04-16 16:52:01 -07002827 VLOG(jdwp) << "ExecuteMethod " << PrettyMethod(m)
2828 << " receiver=" << pReq->receiver_
2829 << " arg_count=" << pReq->arg_count_;
Elliott Hughesd07986f2011-12-06 18:27:45 -08002830 CHECK(m != NULL);
2831
2832 CHECK_EQ(sizeof(jvalue), sizeof(uint64_t));
2833
Jeff Hao5d917302013-02-27 17:57:33 -08002834 MethodHelper mh(m);
2835 ArgArray arg_array(mh.GetShorty(), mh.GetShortyLength());
2836 arg_array.BuildArgArray(soa, pReq->receiver_, reinterpret_cast<jvalue*>(pReq->arg_values_));
Jeff Hao6474d192013-03-26 14:08:09 -07002837 InvokeWithArgArray(soa, m, &arg_array, &pReq->result_value, mh.GetShorty()[0]);
Elliott Hughesd07986f2011-12-06 18:27:45 -08002838
Ian Rogers62d6c772013-02-27 08:32:07 -08002839 mirror::Throwable* exception = soa.Self()->GetException(NULL);
2840 soa.Self()->ClearException();
2841 pReq->exception = gRegistry->Add(exception);
Elliott Hughesd07986f2011-12-06 18:27:45 -08002842 pReq->result_tag = BasicTagFromDescriptor(MethodHelper(m).GetShorty());
2843 if (pReq->exception != 0) {
Ian Rogers62d6c772013-02-27 08:32:07 -08002844 VLOG(jdwp) << " JDWP invocation returning with exception=" << exception
2845 << " " << exception->Dump();
Elliott Hughesf24d3ce2012-04-11 17:43:37 -07002846 pReq->result_value.SetJ(0);
Elliott Hughesd07986f2011-12-06 18:27:45 -08002847 } else if (pReq->result_tag == JDWP::JT_OBJECT) {
2848 /* if no exception thrown, examine object result more closely */
Elliott Hughesf24d3ce2012-04-11 17:43:37 -07002849 JDWP::JdwpTag new_tag = TagFromObject(pReq->result_value.GetL());
Elliott Hughesd07986f2011-12-06 18:27:45 -08002850 if (new_tag != pReq->result_tag) {
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08002851 VLOG(jdwp) << " JDWP promoted result from " << pReq->result_tag << " to " << new_tag;
Elliott Hughesd07986f2011-12-06 18:27:45 -08002852 pReq->result_tag = new_tag;
2853 }
2854
2855 /*
2856 * Register the object. We don't actually need an ObjectId yet,
2857 * but we do need to be sure that the GC won't move or discard the
2858 * object when we switch out of RUNNING. The ObjectId conversion
2859 * will add the object to the "do not touch" list.
2860 *
2861 * We can't use the "tracked allocation" mechanism here because
2862 * the object is going to be handed off to a different thread.
2863 */
Elliott Hughesf24d3ce2012-04-11 17:43:37 -07002864 gRegistry->Add(pReq->result_value.GetL());
Elliott Hughesd07986f2011-12-06 18:27:45 -08002865 }
2866
2867 if (old_exception.get() != NULL) {
Ian Rogers62d6c772013-02-27 08:32:07 -08002868 ThrowLocation gc_safe_throw_location(old_throw_this_object.get(), old_throw_method.get(),
2869 old_throw_dex_pc);
2870 soa.Self()->SetException(gc_safe_throw_location, old_exception.get());
Elliott Hughesd07986f2011-12-06 18:27:45 -08002871 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002872}
2873
Elliott Hughesd07986f2011-12-06 18:27:45 -08002874/*
Elliott Hughes4b9702c2013-02-20 18:13:24 -08002875 * "request" contains a full JDWP packet, possibly with multiple chunks. We
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07002876 * need to process each, accumulate the replies, and ship the whole thing
2877 * back.
2878 *
2879 * Returns "true" if we have a reply. The reply buffer is newly allocated,
2880 * and includes the chunk type/length, followed by the data.
2881 *
Elliott Hughes3d30d9b2011-12-07 17:35:48 -08002882 * OLD-TODO: we currently assume that the request and reply include a single
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07002883 * chunk. If this becomes inconvenient we will need to adapt.
2884 */
Elliott Hughes4b9702c2013-02-20 18:13:24 -08002885bool Dbg::DdmHandlePacket(JDWP::Request& request, uint8_t** pReplyBuf, int* pReplyLen) {
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07002886 Thread* self = Thread::Current();
2887 JNIEnv* env = self->GetJniEnv();
2888
Elliott Hughes4b9702c2013-02-20 18:13:24 -08002889 uint32_t type = request.ReadUnsigned32("type");
2890 uint32_t length = request.ReadUnsigned32("length");
2891
2892 // Create a byte[] corresponding to 'request'.
2893 size_t request_length = request.size();
2894 ScopedLocalRef<jbyteArray> dataArray(env, env->NewByteArray(request_length));
Elliott Hughes6a5bd492011-10-28 14:33:57 -07002895 if (dataArray.get() == NULL) {
Elliott Hughes4b9702c2013-02-20 18:13:24 -08002896 LOG(WARNING) << "byte[] allocation failed: " << request_length;
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07002897 env->ExceptionClear();
2898 return false;
2899 }
Elliott Hughes4b9702c2013-02-20 18:13:24 -08002900 env->SetByteArrayRegion(dataArray.get(), 0, request_length, reinterpret_cast<const jbyte*>(request.data()));
2901 request.Skip(request_length);
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07002902
2903 // Run through and find all chunks. [Currently just find the first.]
Elliott Hughes6a5bd492011-10-28 14:33:57 -07002904 ScopedByteArrayRO contents(env, dataArray.get());
Elliott Hughes4b9702c2013-02-20 18:13:24 -08002905 if (length != request_length) {
2906 LOG(WARNING) << StringPrintf("bad chunk found (len=%u pktLen=%d)", length, request_length);
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07002907 return false;
2908 }
2909
2910 // Call "private static Chunk dispatch(int type, byte[] data, int offset, int length)".
Elliott Hugheseac76672012-05-24 21:56:51 -07002911 ScopedLocalRef<jobject> chunk(env, env->CallStaticObjectMethod(WellKnownClasses::org_apache_harmony_dalvik_ddmc_DdmServer,
2912 WellKnownClasses::org_apache_harmony_dalvik_ddmc_DdmServer_dispatch,
Elliott Hughes4b9702c2013-02-20 18:13:24 -08002913 type, dataArray.get(), 0, length));
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07002914 if (env->ExceptionCheck()) {
2915 LOG(INFO) << StringPrintf("Exception thrown by dispatcher for 0x%08x", type);
2916 env->ExceptionDescribe();
2917 env->ExceptionClear();
2918 return false;
2919 }
2920
Elliott Hughes6a5bd492011-10-28 14:33:57 -07002921 if (chunk.get() == NULL) {
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07002922 return false;
2923 }
2924
2925 /*
2926 * Pull the pieces out of the chunk. We copy the results into a
2927 * newly-allocated buffer that the caller can free. We don't want to
2928 * continue using the Chunk object because nothing has a reference to it.
2929 *
2930 * We could avoid this by returning type/data/offset/length and having
2931 * the caller be aware of the object lifetime issues, but that
Elliott Hughes81ff3182012-03-23 20:35:56 -07002932 * integrates the JDWP code more tightly into the rest of the runtime, and doesn't work
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07002933 * if we have responses for multiple chunks.
2934 *
2935 * So we're pretty much stuck with copying data around multiple times.
2936 */
Elliott Hugheseac76672012-05-24 21:56:51 -07002937 ScopedLocalRef<jbyteArray> replyData(env, reinterpret_cast<jbyteArray>(env->GetObjectField(chunk.get(), WellKnownClasses::org_apache_harmony_dalvik_ddmc_Chunk_data)));
Elliott Hughes4b9702c2013-02-20 18:13:24 -08002938 jint offset = env->GetIntField(chunk.get(), WellKnownClasses::org_apache_harmony_dalvik_ddmc_Chunk_offset);
Elliott Hugheseac76672012-05-24 21:56:51 -07002939 length = env->GetIntField(chunk.get(), WellKnownClasses::org_apache_harmony_dalvik_ddmc_Chunk_length);
Elliott Hugheseac76672012-05-24 21:56:51 -07002940 type = env->GetIntField(chunk.get(), WellKnownClasses::org_apache_harmony_dalvik_ddmc_Chunk_type);
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07002941
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08002942 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 -07002943 if (length == 0 || replyData.get() == NULL) {
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07002944 return false;
2945 }
2946
Elliott Hughes4b9702c2013-02-20 18:13:24 -08002947 const int kChunkHdrLen = 8;
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07002948 uint8_t* reply = new uint8_t[length + kChunkHdrLen];
2949 if (reply == NULL) {
2950 LOG(WARNING) << "malloc failed: " << (length + kChunkHdrLen);
2951 return false;
2952 }
Elliott Hughesf7c3b662011-10-27 12:04:56 -07002953 JDWP::Set4BE(reply + 0, type);
2954 JDWP::Set4BE(reply + 4, length);
Elliott Hughes6a5bd492011-10-28 14:33:57 -07002955 env->GetByteArrayRegion(replyData.get(), offset, length, reinterpret_cast<jbyte*>(reply + kChunkHdrLen));
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07002956
2957 *pReplyBuf = reply;
2958 *pReplyLen = length + kChunkHdrLen;
2959
Elliott Hughes4b9702c2013-02-20 18:13:24 -08002960 VLOG(jdwp) << StringPrintf("dvmHandleDdm returning type=%.4s %p len=%d", reinterpret_cast<char*>(reply), reply, length);
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07002961 return true;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002962}
2963
Elliott Hughesa2155262011-11-16 16:26:58 -08002964void Dbg::DdmBroadcast(bool connect) {
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08002965 VLOG(jdwp) << "Broadcasting DDM " << (connect ? "connect" : "disconnect") << "...";
Elliott Hughes47fce012011-10-25 18:37:19 -07002966
2967 Thread* self = Thread::Current();
Ian Rogers50b35e22012-10-04 10:09:15 -07002968 if (self->GetState() != kRunnable) {
2969 LOG(ERROR) << "DDM broadcast in thread state " << self->GetState();
2970 /* try anyway? */
Elliott Hughes47fce012011-10-25 18:37:19 -07002971 }
2972
2973 JNIEnv* env = self->GetJniEnv();
Elliott Hughes47fce012011-10-25 18:37:19 -07002974 jint event = connect ? 1 /*DdmServer.CONNECTED*/ : 2 /*DdmServer.DISCONNECTED*/;
Elliott Hugheseac76672012-05-24 21:56:51 -07002975 env->CallStaticVoidMethod(WellKnownClasses::org_apache_harmony_dalvik_ddmc_DdmServer,
2976 WellKnownClasses::org_apache_harmony_dalvik_ddmc_DdmServer_broadcast,
2977 event);
Elliott Hughes47fce012011-10-25 18:37:19 -07002978 if (env->ExceptionCheck()) {
2979 LOG(ERROR) << "DdmServer.broadcast " << event << " failed";
2980 env->ExceptionDescribe();
2981 env->ExceptionClear();
2982 }
2983}
2984
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002985void Dbg::DdmConnected() {
Elliott Hughesa2155262011-11-16 16:26:58 -08002986 Dbg::DdmBroadcast(true);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002987}
2988
2989void Dbg::DdmDisconnected() {
Elliott Hughesa2155262011-11-16 16:26:58 -08002990 Dbg::DdmBroadcast(false);
Elliott Hughes47fce012011-10-25 18:37:19 -07002991 gDdmThreadNotification = false;
2992}
2993
2994/*
Elliott Hughes82188472011-11-07 18:11:48 -08002995 * Send a notification when a thread starts, stops, or changes its name.
Elliott Hughes47fce012011-10-25 18:37:19 -07002996 *
2997 * Because we broadcast the full set of threads when the notifications are
2998 * first enabled, it's possible for "thread" to be actively executing.
2999 */
Elliott Hughes82188472011-11-07 18:11:48 -08003000void Dbg::DdmSendThreadNotification(Thread* t, uint32_t type) {
Elliott Hughes47fce012011-10-25 18:37:19 -07003001 if (!gDdmThreadNotification) {
3002 return;
3003 }
3004
Elliott Hughes82188472011-11-07 18:11:48 -08003005 if (type == CHUNK_TYPE("THDE")) {
Elliott Hughes47fce012011-10-25 18:37:19 -07003006 uint8_t buf[4];
Ian Rogersd9c4fc92013-10-01 19:45:43 -07003007 JDWP::Set4BE(&buf[0], t->GetThreadId());
Elliott Hughes47fce012011-10-25 18:37:19 -07003008 Dbg::DdmSendChunk(CHUNK_TYPE("THDE"), 4, buf);
Elliott Hughes82188472011-11-07 18:11:48 -08003009 } else {
3010 CHECK(type == CHUNK_TYPE("THCR") || type == CHUNK_TYPE("THNM")) << type;
Ian Rogers00f7d0e2012-07-19 15:28:27 -07003011 ScopedObjectAccessUnchecked soa(Thread::Current());
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003012 SirtRef<mirror::String> name(soa.Self(), t->GetThreadName(soa));
Elliott Hughes82188472011-11-07 18:11:48 -08003013 size_t char_count = (name.get() != NULL) ? name->GetLength() : 0;
jeffhao725a9572012-11-13 18:20:12 -08003014 const jchar* chars = (name.get() != NULL) ? name->GetCharArray()->GetData() : NULL;
Elliott Hughes82188472011-11-07 18:11:48 -08003015
Elliott Hughes21f32d72011-11-09 17:44:13 -08003016 std::vector<uint8_t> bytes;
Ian Rogersd9c4fc92013-10-01 19:45:43 -07003017 JDWP::Append4BE(bytes, t->GetThreadId());
Elliott Hughes545a0642011-11-08 19:10:03 -08003018 JDWP::AppendUtf16BE(bytes, chars, char_count);
Elliott Hughes21f32d72011-11-09 17:44:13 -08003019 CHECK_EQ(bytes.size(), char_count*2 + sizeof(uint32_t)*2);
3020 Dbg::DdmSendChunk(type, bytes);
Elliott Hughes47fce012011-10-25 18:37:19 -07003021 }
3022}
3023
Elliott Hughes47fce012011-10-25 18:37:19 -07003024void Dbg::DdmSetThreadNotification(bool enable) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07003025 // Enable/disable thread notifications.
Elliott Hughes47fce012011-10-25 18:37:19 -07003026 gDdmThreadNotification = enable;
3027 if (enable) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07003028 // Suspend the VM then post thread start notifications for all threads. Threads attaching will
3029 // see a suspension in progress and block until that ends. They then post their own start
3030 // notification.
3031 SuspendVM();
3032 std::list<Thread*> threads;
Ian Rogers50b35e22012-10-04 10:09:15 -07003033 Thread* self = Thread::Current();
Ian Rogers00f7d0e2012-07-19 15:28:27 -07003034 {
Ian Rogers50b35e22012-10-04 10:09:15 -07003035 MutexLock mu(self, *Locks::thread_list_lock_);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07003036 threads = Runtime::Current()->GetThreadList()->GetList();
3037 }
3038 {
Ian Rogers50b35e22012-10-04 10:09:15 -07003039 ScopedObjectAccess soa(self);
Mathieu Chartier02e25112013-08-14 16:14:24 -07003040 for (Thread* thread : threads) {
3041 Dbg::DdmSendThreadNotification(thread, CHUNK_TYPE("THCR"));
Ian Rogers00f7d0e2012-07-19 15:28:27 -07003042 }
3043 }
3044 ResumeVM();
Elliott Hughes47fce012011-10-25 18:37:19 -07003045 }
3046}
3047
Elliott Hughesa2155262011-11-16 16:26:58 -08003048void Dbg::PostThreadStartOrStop(Thread* t, uint32_t type) {
Elliott Hughesc0f09332012-03-26 13:27:06 -07003049 if (IsDebuggerActive()) {
Mathieu Chartierdbe6f462012-09-25 16:54:50 -07003050 ScopedObjectAccessUnchecked soa(Thread::Current());
Ian Rogerscfaa4552012-11-26 21:00:08 -08003051 JDWP::ObjectId id = gRegistry->Add(t->GetPeer());
Elliott Hughes82188472011-11-07 18:11:48 -08003052 gJdwpState->PostThreadChange(id, type == CHUNK_TYPE("THCR"));
Elliott Hughes47fce012011-10-25 18:37:19 -07003053 }
Elliott Hughes82188472011-11-07 18:11:48 -08003054 Dbg::DdmSendThreadNotification(t, type);
Elliott Hughes47fce012011-10-25 18:37:19 -07003055}
3056
3057void Dbg::PostThreadStart(Thread* t) {
Elliott Hughesa2155262011-11-16 16:26:58 -08003058 Dbg::PostThreadStartOrStop(t, CHUNK_TYPE("THCR"));
Elliott Hughes47fce012011-10-25 18:37:19 -07003059}
3060
3061void Dbg::PostThreadDeath(Thread* t) {
Elliott Hughesa2155262011-11-16 16:26:58 -08003062 Dbg::PostThreadStartOrStop(t, CHUNK_TYPE("THDE"));
Elliott Hughes872d4ec2011-10-21 17:07:15 -07003063}
3064
Elliott Hughes82188472011-11-07 18:11:48 -08003065void Dbg::DdmSendChunk(uint32_t type, size_t byte_count, const uint8_t* buf) {
Elliott Hughes3bb81562011-10-21 18:52:59 -07003066 CHECK(buf != NULL);
3067 iovec vec[1];
3068 vec[0].iov_base = reinterpret_cast<void*>(const_cast<uint8_t*>(buf));
3069 vec[0].iov_len = byte_count;
3070 Dbg::DdmSendChunkV(type, vec, 1);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07003071}
3072
Elliott Hughes21f32d72011-11-09 17:44:13 -08003073void Dbg::DdmSendChunk(uint32_t type, const std::vector<uint8_t>& bytes) {
3074 DdmSendChunk(type, bytes.size(), &bytes[0]);
3075}
3076
Brian Carlstromf5293522013-07-19 00:24:00 -07003077void Dbg::DdmSendChunkV(uint32_t type, const iovec* iov, int iov_count) {
Elliott Hughes3bb81562011-10-21 18:52:59 -07003078 if (gJdwpState == NULL) {
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08003079 VLOG(jdwp) << "Debugger thread not active, ignoring DDM send: " << type;
Elliott Hughes3bb81562011-10-21 18:52:59 -07003080 } else {
Elliott Hughescccd84f2011-12-05 16:51:54 -08003081 gJdwpState->DdmSendChunkV(type, iov, iov_count);
Elliott Hughes3bb81562011-10-21 18:52:59 -07003082 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -07003083}
3084
Elliott Hughes767a1472011-10-26 18:49:02 -07003085int Dbg::DdmHandleHpifChunk(HpifWhen when) {
3086 if (when == HPIF_WHEN_NOW) {
Elliott Hughes7162ad92011-10-27 14:08:42 -07003087 DdmSendHeapInfo(when);
Elliott Hughes767a1472011-10-26 18:49:02 -07003088 return true;
3089 }
3090
3091 if (when != HPIF_WHEN_NEVER && when != HPIF_WHEN_NEXT_GC && when != HPIF_WHEN_EVERY_GC) {
3092 LOG(ERROR) << "invalid HpifWhen value: " << static_cast<int>(when);
3093 return false;
3094 }
3095
3096 gDdmHpifWhen = when;
3097 return true;
3098}
3099
3100bool Dbg::DdmHandleHpsgNhsgChunk(Dbg::HpsgWhen when, Dbg::HpsgWhat what, bool native) {
3101 if (when != HPSG_WHEN_NEVER && when != HPSG_WHEN_EVERY_GC) {
3102 LOG(ERROR) << "invalid HpsgWhen value: " << static_cast<int>(when);
3103 return false;
3104 }
3105
3106 if (what != HPSG_WHAT_MERGED_OBJECTS && what != HPSG_WHAT_DISTINCT_OBJECTS) {
3107 LOG(ERROR) << "invalid HpsgWhat value: " << static_cast<int>(what);
3108 return false;
3109 }
3110
3111 if (native) {
3112 gDdmNhsgWhen = when;
3113 gDdmNhsgWhat = what;
3114 } else {
3115 gDdmHpsgWhen = when;
3116 gDdmHpsgWhat = what;
3117 }
3118 return true;
3119}
3120
Elliott Hughes7162ad92011-10-27 14:08:42 -07003121void Dbg::DdmSendHeapInfo(HpifWhen reason) {
3122 // If there's a one-shot 'when', reset it.
3123 if (reason == gDdmHpifWhen) {
3124 if (gDdmHpifWhen == HPIF_WHEN_NEXT_GC) {
3125 gDdmHpifWhen = HPIF_WHEN_NEVER;
3126 }
3127 }
3128
3129 /*
3130 * Chunk HPIF (client --> server)
3131 *
3132 * Heap Info. General information about the heap,
3133 * suitable for a summary display.
3134 *
3135 * [u4]: number of heaps
3136 *
3137 * For each heap:
3138 * [u4]: heap ID
3139 * [u8]: timestamp in ms since Unix epoch
3140 * [u1]: capture reason (same as 'when' value from server)
3141 * [u4]: max heap size in bytes (-Xmx)
3142 * [u4]: current heap size in bytes
3143 * [u4]: current number of bytes allocated
3144 * [u4]: current number of objects allocated
3145 */
3146 uint8_t heap_count = 1;
Ian Rogers1d54e732013-05-02 21:10:01 -07003147 gc::Heap* heap = Runtime::Current()->GetHeap();
Elliott Hughes21f32d72011-11-09 17:44:13 -08003148 std::vector<uint8_t> bytes;
Elliott Hughes545a0642011-11-08 19:10:03 -08003149 JDWP::Append4BE(bytes, heap_count);
Brian Carlstrom7934ac22013-07-26 10:54:15 -07003150 JDWP::Append4BE(bytes, 1); // Heap id (bogus; we only have one heap).
Elliott Hughes545a0642011-11-08 19:10:03 -08003151 JDWP::Append8BE(bytes, MilliTime());
3152 JDWP::Append1BE(bytes, reason);
Brian Carlstrom7934ac22013-07-26 10:54:15 -07003153 JDWP::Append4BE(bytes, heap->GetMaxMemory()); // Max allowed heap size in bytes.
3154 JDWP::Append4BE(bytes, heap->GetTotalMemory()); // Current heap size in bytes.
Elliott Hughesb3bd5f02012-03-08 21:05:27 -08003155 JDWP::Append4BE(bytes, heap->GetBytesAllocated());
3156 JDWP::Append4BE(bytes, heap->GetObjectsAllocated());
Elliott Hughes21f32d72011-11-09 17:44:13 -08003157 CHECK_EQ(bytes.size(), 4U + (heap_count * (4 + 8 + 1 + 4 + 4 + 4 + 4)));
3158 Dbg::DdmSendChunk(CHUNK_TYPE("HPIF"), bytes);
Elliott Hughes767a1472011-10-26 18:49:02 -07003159}
3160
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003161enum HpsgSolidity {
3162 SOLIDITY_FREE = 0,
3163 SOLIDITY_HARD = 1,
3164 SOLIDITY_SOFT = 2,
3165 SOLIDITY_WEAK = 3,
3166 SOLIDITY_PHANTOM = 4,
3167 SOLIDITY_FINALIZABLE = 5,
3168 SOLIDITY_SWEEP = 6,
3169};
3170
3171enum HpsgKind {
3172 KIND_OBJECT = 0,
3173 KIND_CLASS_OBJECT = 1,
3174 KIND_ARRAY_1 = 2,
3175 KIND_ARRAY_2 = 3,
3176 KIND_ARRAY_4 = 4,
3177 KIND_ARRAY_8 = 5,
3178 KIND_UNKNOWN = 6,
3179 KIND_NATIVE = 7,
3180};
3181
3182#define HPSG_PARTIAL (1<<7)
3183#define HPSG_STATE(solidity, kind) ((uint8_t)((((kind) & 0x7) << 3) | ((solidity) & 0x7)))
3184
Ian Rogers30fab402012-01-23 15:43:46 -08003185class HeapChunkContext {
3186 public:
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003187 // Maximum chunk size. Obtain this from the formula:
3188 // (((maximum_heap_size / ALLOCATION_UNIT_SIZE) + 255) / 256) * 2
3189 HeapChunkContext(bool merge, bool native)
Ian Rogers30fab402012-01-23 15:43:46 -08003190 : buf_(16384 - 16),
3191 type_(0),
3192 merge_(merge) {
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003193 Reset();
3194 if (native) {
Ian Rogers30fab402012-01-23 15:43:46 -08003195 type_ = CHUNK_TYPE("NHSG");
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003196 } else {
Ian Rogers30fab402012-01-23 15:43:46 -08003197 type_ = merge ? CHUNK_TYPE("HPSG") : CHUNK_TYPE("HPSO");
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003198 }
3199 }
3200
3201 ~HeapChunkContext() {
Ian Rogers30fab402012-01-23 15:43:46 -08003202 if (p_ > &buf_[0]) {
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003203 Flush();
3204 }
3205 }
3206
3207 void EnsureHeader(const void* chunk_ptr) {
Ian Rogers30fab402012-01-23 15:43:46 -08003208 if (!needHeader_) {
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003209 return;
3210 }
3211
3212 // Start a new HPSx chunk.
Brian Carlstrom7934ac22013-07-26 10:54:15 -07003213 JDWP::Write4BE(&p_, 1); // Heap id (bogus; we only have one heap).
3214 JDWP::Write1BE(&p_, 8); // Size of allocation unit, in bytes.
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003215
Brian Carlstrom7934ac22013-07-26 10:54:15 -07003216 JDWP::Write4BE(&p_, reinterpret_cast<uintptr_t>(chunk_ptr)); // virtual address of segment start.
3217 JDWP::Write4BE(&p_, 0); // offset of this piece (relative to the virtual address).
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003218 // [u4]: length of piece, in allocation units
3219 // 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 -08003220 pieceLenField_ = p_;
3221 JDWP::Write4BE(&p_, 0x55555555);
3222 needHeader_ = false;
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003223 }
3224
Ian Rogersb726dcb2012-09-05 08:57:23 -07003225 void Flush() SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Ian Rogersd636b062013-01-18 17:51:18 -08003226 if (pieceLenField_ == NULL) {
3227 // Flush immediately post Reset (maybe back-to-back Flush). Ignore.
3228 CHECK(needHeader_);
3229 return;
3230 }
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003231 // Patch the "length of piece" field.
Ian Rogers30fab402012-01-23 15:43:46 -08003232 CHECK_LE(&buf_[0], pieceLenField_);
3233 CHECK_LE(pieceLenField_, p_);
3234 JDWP::Set4BE(pieceLenField_, totalAllocationUnits_);
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003235
Ian Rogers30fab402012-01-23 15:43:46 -08003236 Dbg::DdmSendChunk(type_, p_ - &buf_[0], &buf_[0]);
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003237 Reset();
3238 }
3239
Ian Rogers00f7d0e2012-07-19 15:28:27 -07003240 static void HeapChunkCallback(void* start, void* end, size_t used_bytes, void* arg)
Ian Rogersb726dcb2012-09-05 08:57:23 -07003241 SHARED_LOCKS_REQUIRED(Locks::heap_bitmap_lock_,
3242 Locks::mutator_lock_) {
Ian Rogers30fab402012-01-23 15:43:46 -08003243 reinterpret_cast<HeapChunkContext*>(arg)->HeapChunkCallback(start, end, used_bytes);
Elliott Hughesa2155262011-11-16 16:26:58 -08003244 }
3245
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003246 private:
Elliott Hughesa2155262011-11-16 16:26:58 -08003247 enum { ALLOCATION_UNIT_SIZE = 8 };
3248
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003249 void Reset() {
Ian Rogers30fab402012-01-23 15:43:46 -08003250 p_ = &buf_[0];
Ian Rogers15bf2d32012-08-28 17:33:04 -07003251 startOfNextMemoryChunk_ = NULL;
Ian Rogers30fab402012-01-23 15:43:46 -08003252 totalAllocationUnits_ = 0;
3253 needHeader_ = true;
3254 pieceLenField_ = NULL;
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003255 }
3256
Ian Rogers00f7d0e2012-07-19 15:28:27 -07003257 void HeapChunkCallback(void* start, void* /*end*/, size_t used_bytes)
Ian Rogersb726dcb2012-09-05 08:57:23 -07003258 SHARED_LOCKS_REQUIRED(Locks::heap_bitmap_lock_,
3259 Locks::mutator_lock_) {
Ian Rogers30fab402012-01-23 15:43:46 -08003260 // Note: heap call backs cannot manipulate the heap upon which they are crawling, care is taken
3261 // in the following code not to allocate memory, by ensuring buf_ is of the correct size
Ian Rogers15bf2d32012-08-28 17:33:04 -07003262 if (used_bytes == 0) {
3263 if (start == NULL) {
3264 // Reset for start of new heap.
3265 startOfNextMemoryChunk_ = NULL;
3266 Flush();
3267 }
3268 // Only process in use memory so that free region information
3269 // also includes dlmalloc book keeping.
Elliott Hughesa2155262011-11-16 16:26:58 -08003270 return;
Elliott Hughesa2155262011-11-16 16:26:58 -08003271 }
3272
Ian Rogers15bf2d32012-08-28 17:33:04 -07003273 /* If we're looking at the native heap, we'll just return
3274 * (SOLIDITY_HARD, KIND_NATIVE) for all allocated chunks
3275 */
3276 bool native = type_ == CHUNK_TYPE("NHSG");
3277
3278 if (startOfNextMemoryChunk_ != NULL) {
3279 // Transmit any pending free memory. Native free memory of
3280 // over kMaxFreeLen could be because of the use of mmaps, so
3281 // don't report. If not free memory then start a new segment.
3282 bool flush = true;
3283 if (start > startOfNextMemoryChunk_) {
3284 const size_t kMaxFreeLen = 2 * kPageSize;
3285 void* freeStart = startOfNextMemoryChunk_;
3286 void* freeEnd = start;
Brian Carlstrom2d888622013-07-18 17:02:00 -07003287 size_t freeLen = reinterpret_cast<char*>(freeEnd) - reinterpret_cast<char*>(freeStart);
Ian Rogers15bf2d32012-08-28 17:33:04 -07003288 if (!native || freeLen < kMaxFreeLen) {
3289 AppendChunk(HPSG_STATE(SOLIDITY_FREE, 0), freeStart, freeLen);
3290 flush = false;
3291 }
3292 }
3293 if (flush) {
3294 startOfNextMemoryChunk_ = NULL;
3295 Flush();
3296 }
3297 }
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003298 const mirror::Object* obj = reinterpret_cast<const mirror::Object*>(start);
Elliott Hughesa2155262011-11-16 16:26:58 -08003299
3300 // Determine the type of this chunk.
3301 // OLD-TODO: if context.merge, see if this chunk is different from the last chunk.
3302 // If it's the same, we should combine them.
Ian Rogers15bf2d32012-08-28 17:33:04 -07003303 uint8_t state = ExamineObject(obj, native);
3304 // dlmalloc's chunk header is 2 * sizeof(size_t), but if the previous chunk is in use for an
3305 // allocation then the first sizeof(size_t) may belong to it.
3306 const size_t dlMallocOverhead = sizeof(size_t);
3307 AppendChunk(state, start, used_bytes + dlMallocOverhead);
Brian Carlstrom2d888622013-07-18 17:02:00 -07003308 startOfNextMemoryChunk_ = reinterpret_cast<char*>(start) + used_bytes + dlMallocOverhead;
Ian Rogers15bf2d32012-08-28 17:33:04 -07003309 }
Elliott Hughesa2155262011-11-16 16:26:58 -08003310
Ian Rogers15bf2d32012-08-28 17:33:04 -07003311 void AppendChunk(uint8_t state, void* ptr, size_t length)
Ian Rogersb726dcb2012-09-05 08:57:23 -07003312 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Ian Rogers15bf2d32012-08-28 17:33:04 -07003313 // Make sure there's enough room left in the buffer.
3314 // We need to use two bytes for every fractional 256 allocation units used by the chunk plus
3315 // 17 bytes for any header.
3316 size_t needed = (((length/ALLOCATION_UNIT_SIZE + 255) / 256) * 2) + 17;
3317 size_t bytesLeft = buf_.size() - (size_t)(p_ - &buf_[0]);
3318 if (bytesLeft < needed) {
3319 Flush();
3320 }
3321
3322 bytesLeft = buf_.size() - (size_t)(p_ - &buf_[0]);
3323 if (bytesLeft < needed) {
3324 LOG(WARNING) << "Chunk is too big to transmit (chunk_len=" << length << ", "
3325 << needed << " bytes)";
3326 return;
3327 }
3328 EnsureHeader(ptr);
Elliott Hughesa2155262011-11-16 16:26:58 -08003329 // Write out the chunk description.
Ian Rogers15bf2d32012-08-28 17:33:04 -07003330 length /= ALLOCATION_UNIT_SIZE; // Convert to allocation units.
3331 totalAllocationUnits_ += length;
3332 while (length > 256) {
Ian Rogers30fab402012-01-23 15:43:46 -08003333 *p_++ = state | HPSG_PARTIAL;
3334 *p_++ = 255; // length - 1
Ian Rogers15bf2d32012-08-28 17:33:04 -07003335 length -= 256;
Elliott Hughesa2155262011-11-16 16:26:58 -08003336 }
Ian Rogers30fab402012-01-23 15:43:46 -08003337 *p_++ = state;
Ian Rogers15bf2d32012-08-28 17:33:04 -07003338 *p_++ = length - 1;
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003339 }
3340
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003341 uint8_t ExamineObject(const mirror::Object* o, bool is_native_heap)
Ian Rogersb726dcb2012-09-05 08:57:23 -07003342 SHARED_LOCKS_REQUIRED(Locks::heap_bitmap_lock_) {
Elliott Hughesa2155262011-11-16 16:26:58 -08003343 if (o == NULL) {
3344 return HPSG_STATE(SOLIDITY_FREE, 0);
3345 }
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003346
Elliott Hughesa2155262011-11-16 16:26:58 -08003347 // It's an allocated chunk. Figure out what it is.
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003348
Elliott Hughesa2155262011-11-16 16:26:58 -08003349 // If we're looking at the native heap, we'll just return
3350 // (SOLIDITY_HARD, KIND_NATIVE) for all allocated chunks.
Ian Rogers00f7d0e2012-07-19 15:28:27 -07003351 if (is_native_heap) {
Elliott Hughesa2155262011-11-16 16:26:58 -08003352 return HPSG_STATE(SOLIDITY_HARD, KIND_NATIVE);
3353 }
3354
Ian Rogers5bfa60f2012-09-02 21:17:56 -07003355 if (!Runtime::Current()->GetHeap()->IsLiveObjectLocked(o)) {
Ian Rogers15bf2d32012-08-28 17:33:04 -07003356 return HPSG_STATE(SOLIDITY_HARD, KIND_NATIVE);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07003357 }
3358
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003359 mirror::Class* c = o->GetClass();
Elliott Hughesa2155262011-11-16 16:26:58 -08003360 if (c == NULL) {
3361 // The object was probably just created but hasn't been initialized yet.
3362 return HPSG_STATE(SOLIDITY_HARD, KIND_OBJECT);
3363 }
3364
Mathieu Chartier590fee92013-09-13 13:46:47 -07003365 if (!Runtime::Current()->GetHeap()->IsValidObjectAddress(c)) {
Ian Rogers15bf2d32012-08-28 17:33:04 -07003366 LOG(ERROR) << "Invalid class for managed heap object: " << o << " " << c;
Elliott Hughesa2155262011-11-16 16:26:58 -08003367 return HPSG_STATE(SOLIDITY_HARD, KIND_UNKNOWN);
3368 }
3369
3370 if (c->IsClassClass()) {
3371 return HPSG_STATE(SOLIDITY_HARD, KIND_CLASS_OBJECT);
3372 }
3373
3374 if (c->IsArrayClass()) {
3375 if (o->IsObjectArray()) {
3376 return HPSG_STATE(SOLIDITY_HARD, KIND_ARRAY_4);
3377 }
3378 switch (c->GetComponentSize()) {
3379 case 1: return HPSG_STATE(SOLIDITY_HARD, KIND_ARRAY_1);
3380 case 2: return HPSG_STATE(SOLIDITY_HARD, KIND_ARRAY_2);
3381 case 4: return HPSG_STATE(SOLIDITY_HARD, KIND_ARRAY_4);
3382 case 8: return HPSG_STATE(SOLIDITY_HARD, KIND_ARRAY_8);
3383 }
3384 }
3385
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003386 return HPSG_STATE(SOLIDITY_HARD, KIND_OBJECT);
3387 }
3388
Ian Rogers30fab402012-01-23 15:43:46 -08003389 std::vector<uint8_t> buf_;
3390 uint8_t* p_;
3391 uint8_t* pieceLenField_;
Ian Rogers15bf2d32012-08-28 17:33:04 -07003392 void* startOfNextMemoryChunk_;
Ian Rogers30fab402012-01-23 15:43:46 -08003393 size_t totalAllocationUnits_;
3394 uint32_t type_;
3395 bool merge_;
3396 bool needHeader_;
3397
Elliott Hughesa2155262011-11-16 16:26:58 -08003398 DISALLOW_COPY_AND_ASSIGN(HeapChunkContext);
3399};
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003400
3401void Dbg::DdmSendHeapSegments(bool native) {
3402 Dbg::HpsgWhen when;
3403 Dbg::HpsgWhat what;
3404 if (!native) {
3405 when = gDdmHpsgWhen;
3406 what = gDdmHpsgWhat;
3407 } else {
3408 when = gDdmNhsgWhen;
3409 what = gDdmNhsgWhat;
3410 }
3411 if (when == HPSG_WHEN_NEVER) {
3412 return;
3413 }
3414
3415 // Figure out what kind of chunks we'll be sending.
3416 CHECK(what == HPSG_WHAT_MERGED_OBJECTS || what == HPSG_WHAT_DISTINCT_OBJECTS) << static_cast<int>(what);
3417
3418 // First, send a heap start chunk.
3419 uint8_t heap_id[4];
Brian Carlstrom7934ac22013-07-26 10:54:15 -07003420 JDWP::Set4BE(&heap_id[0], 1); // Heap id (bogus; we only have one heap).
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003421 Dbg::DdmSendChunk(native ? CHUNK_TYPE("NHST") : CHUNK_TYPE("HPST"), sizeof(heap_id), heap_id);
3422
3423 // Send a series of heap segment chunks.
Elliott Hughesa2155262011-11-16 16:26:58 -08003424 HeapChunkContext context((what == HPSG_WHAT_MERGED_OBJECTS), native);
3425 if (native) {
Ian Rogers1d54e732013-05-02 21:10:01 -07003426 dlmalloc_inspect_all(HeapChunkContext::HeapChunkCallback, &context);
Elliott Hughesa2155262011-11-16 16:26:58 -08003427 } else {
Ian Rogers1d54e732013-05-02 21:10:01 -07003428 gc::Heap* heap = Runtime::Current()->GetHeap();
3429 const std::vector<gc::space::ContinuousSpace*>& spaces = heap->GetContinuousSpaces();
Ian Rogers50b35e22012-10-04 10:09:15 -07003430 Thread* self = Thread::Current();
Ian Rogers62d6c772013-02-27 08:32:07 -08003431 ReaderMutexLock mu(self, *Locks::heap_bitmap_lock_);
Ian Rogers1d54e732013-05-02 21:10:01 -07003432 typedef std::vector<gc::space::ContinuousSpace*>::const_iterator It;
3433 for (It cur = spaces.begin(), end = spaces.end(); cur != end; ++cur) {
3434 if ((*cur)->IsDlMallocSpace()) {
3435 (*cur)->AsDlMallocSpace()->Walk(HeapChunkContext::HeapChunkCallback, &context);
Mathieu Chartierb062fdd2012-07-03 09:51:48 -07003436 }
3437 }
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -07003438 // Walk the large objects, these are not in the AllocSpace.
3439 heap->GetLargeObjectsSpace()->Walk(HeapChunkContext::HeapChunkCallback, &context);
Elliott Hughesa2155262011-11-16 16:26:58 -08003440 }
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003441
3442 // Finally, send a heap end chunk.
3443 Dbg::DdmSendChunk(native ? CHUNK_TYPE("NHEN") : CHUNK_TYPE("HPEN"), sizeof(heap_id), heap_id);
Elliott Hughes767a1472011-10-26 18:49:02 -07003444}
3445
Elliott Hughesb1a58792013-07-11 18:10:58 -07003446static size_t GetAllocTrackerMax() {
3447#ifdef HAVE_ANDROID_OS
3448 // Check whether there's a system property overriding the number of records.
3449 const char* propertyName = "dalvik.vm.allocTrackerMax";
3450 char allocRecordMaxString[PROPERTY_VALUE_MAX];
3451 if (property_get(propertyName, allocRecordMaxString, "") > 0) {
3452 char* end;
3453 size_t value = strtoul(allocRecordMaxString, &end, 10);
3454 if (*end != '\0') {
Ruben Brunk3e47a742013-09-09 17:56:07 -07003455 LOG(ERROR) << "Ignoring " << propertyName << " '" << allocRecordMaxString
3456 << "' --- invalid";
Elliott Hughesb1a58792013-07-11 18:10:58 -07003457 return kDefaultNumAllocRecords;
3458 }
3459 if (!IsPowerOfTwo(value)) {
Ruben Brunk3e47a742013-09-09 17:56:07 -07003460 LOG(ERROR) << "Ignoring " << propertyName << " '" << allocRecordMaxString
3461 << "' --- not power of two";
Elliott Hughesb1a58792013-07-11 18:10:58 -07003462 return kDefaultNumAllocRecords;
3463 }
3464 return value;
3465 }
3466#endif
3467 return kDefaultNumAllocRecords;
3468}
3469
Elliott Hughes545a0642011-11-08 19:10:03 -08003470void Dbg::SetAllocTrackingEnabled(bool enabled) {
Ian Rogers50b35e22012-10-04 10:09:15 -07003471 MutexLock mu(Thread::Current(), gAllocTrackerLock);
Elliott Hughes545a0642011-11-08 19:10:03 -08003472 if (enabled) {
3473 if (recent_allocation_records_ == NULL) {
Elliott Hughesb1a58792013-07-11 18:10:58 -07003474 gAllocRecordMax = GetAllocTrackerMax();
3475 LOG(INFO) << "Enabling alloc tracker (" << gAllocRecordMax << " entries of "
3476 << kMaxAllocRecordStackDepth << " frames, taking "
3477 << PrettySize(sizeof(AllocRecord) * gAllocRecordMax) << ")";
Elliott Hughes545a0642011-11-08 19:10:03 -08003478 gAllocRecordHead = gAllocRecordCount = 0;
Elliott Hughesb1a58792013-07-11 18:10:58 -07003479 recent_allocation_records_ = new AllocRecord[gAllocRecordMax];
Elliott Hughes545a0642011-11-08 19:10:03 -08003480 CHECK(recent_allocation_records_ != NULL);
3481 }
Ian Rogersfa824272013-11-05 16:12:57 -08003482 Runtime::Current()->GetInstrumentation()->InstrumentQuickAllocEntryPoints();
Elliott Hughes545a0642011-11-08 19:10:03 -08003483 } else {
Ian Rogersfa824272013-11-05 16:12:57 -08003484 Runtime::Current()->GetInstrumentation()->UninstrumentQuickAllocEntryPoints();
Elliott Hughes545a0642011-11-08 19:10:03 -08003485 delete[] recent_allocation_records_;
3486 recent_allocation_records_ = NULL;
3487 }
3488}
3489
Ian Rogers0399dde2012-06-06 17:09:28 -07003490struct AllocRecordStackVisitor : public StackVisitor {
Ian Rogers7a22fa62013-01-23 12:16:16 -08003491 AllocRecordStackVisitor(Thread* thread, AllocRecord* record)
Ian Rogersb726dcb2012-09-05 08:57:23 -07003492 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_)
Ian Rogers7a22fa62013-01-23 12:16:16 -08003493 : StackVisitor(thread, NULL), record(record), depth(0) {}
Elliott Hughes545a0642011-11-08 19:10:03 -08003494
Ian Rogers00f7d0e2012-07-19 15:28:27 -07003495 // TODO: Enable annotalysis. We know lock is held in constructor, but abstraction confuses
3496 // annotalysis.
3497 bool VisitFrame() NO_THREAD_SAFETY_ANALYSIS {
Elliott Hughes545a0642011-11-08 19:10:03 -08003498 if (depth >= kMaxAllocRecordStackDepth) {
Elliott Hughes530fa002012-03-12 11:44:49 -07003499 return false;
Elliott Hughes545a0642011-11-08 19:10:03 -08003500 }
Brian Carlstromea46f952013-07-30 01:26:50 -07003501 mirror::ArtMethod* m = GetMethod();
Ian Rogers0399dde2012-06-06 17:09:28 -07003502 if (!m->IsRuntimeMethod()) {
3503 record->stack[depth].method = m;
3504 record->stack[depth].dex_pc = GetDexPc();
Elliott Hughes530fa002012-03-12 11:44:49 -07003505 ++depth;
Elliott Hughes545a0642011-11-08 19:10:03 -08003506 }
Elliott Hughes530fa002012-03-12 11:44:49 -07003507 return true;
Elliott Hughes545a0642011-11-08 19:10:03 -08003508 }
3509
3510 ~AllocRecordStackVisitor() {
3511 // Clear out any unused stack trace elements.
3512 for (; depth < kMaxAllocRecordStackDepth; ++depth) {
3513 record->stack[depth].method = NULL;
Ian Rogers0399dde2012-06-06 17:09:28 -07003514 record->stack[depth].dex_pc = 0;
Elliott Hughes545a0642011-11-08 19:10:03 -08003515 }
3516 }
3517
3518 AllocRecord* record;
3519 size_t depth;
3520};
3521
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003522void Dbg::RecordAllocation(mirror::Class* type, size_t byte_count) {
Elliott Hughes545a0642011-11-08 19:10:03 -08003523 Thread* self = Thread::Current();
3524 CHECK(self != NULL);
3525
Ian Rogers50b35e22012-10-04 10:09:15 -07003526 MutexLock mu(self, gAllocTrackerLock);
Elliott Hughes545a0642011-11-08 19:10:03 -08003527 if (recent_allocation_records_ == NULL) {
3528 return;
3529 }
3530
3531 // Advance and clip.
Elliott Hughesb1a58792013-07-11 18:10:58 -07003532 if (++gAllocRecordHead == gAllocRecordMax) {
Elliott Hughes545a0642011-11-08 19:10:03 -08003533 gAllocRecordHead = 0;
3534 }
3535
3536 // Fill in the basics.
3537 AllocRecord* record = &recent_allocation_records_[gAllocRecordHead];
3538 record->type = type;
3539 record->byte_count = byte_count;
Ian Rogersd9c4fc92013-10-01 19:45:43 -07003540 record->thin_lock_id = self->GetThreadId();
Elliott Hughes545a0642011-11-08 19:10:03 -08003541
3542 // Fill in the stack trace.
Ian Rogers7a22fa62013-01-23 12:16:16 -08003543 AllocRecordStackVisitor visitor(self, record);
Ian Rogers0399dde2012-06-06 17:09:28 -07003544 visitor.WalkStack();
Elliott Hughes545a0642011-11-08 19:10:03 -08003545
Elliott Hughesb1a58792013-07-11 18:10:58 -07003546 if (gAllocRecordCount < gAllocRecordMax) {
Elliott Hughes545a0642011-11-08 19:10:03 -08003547 ++gAllocRecordCount;
3548 }
3549}
3550
Elliott Hughesa8f93cb2012-06-08 17:08:48 -07003551// Returns the index of the head element.
3552//
3553// We point at the most-recently-written record, so if gAllocRecordCount is 1
3554// we want to use the current element. Take "head+1" and subtract count
3555// from it.
3556//
3557// We need to handle underflow in our circular buffer, so we add
Elliott Hughesb1a58792013-07-11 18:10:58 -07003558// gAllocRecordMax and then mask it back down.
Elliott Hughesf8349362012-06-18 15:00:06 -07003559static inline int HeadIndex() EXCLUSIVE_LOCKS_REQUIRED(gAllocTrackerLock) {
Elliott Hughesb1a58792013-07-11 18:10:58 -07003560 return (gAllocRecordHead+1 + gAllocRecordMax - gAllocRecordCount) & (gAllocRecordMax-1);
Elliott Hughes545a0642011-11-08 19:10:03 -08003561}
3562
3563void Dbg::DumpRecentAllocations() {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07003564 ScopedObjectAccess soa(Thread::Current());
Ian Rogers50b35e22012-10-04 10:09:15 -07003565 MutexLock mu(soa.Self(), gAllocTrackerLock);
Elliott Hughes545a0642011-11-08 19:10:03 -08003566 if (recent_allocation_records_ == NULL) {
3567 LOG(INFO) << "Not recording tracked allocations";
3568 return;
3569 }
3570
3571 // "i" is the head of the list. We want to start at the end of the
3572 // list and move forward to the tail.
Elliott Hughesa8f93cb2012-06-08 17:08:48 -07003573 size_t i = HeadIndex();
Elliott Hughes545a0642011-11-08 19:10:03 -08003574 size_t count = gAllocRecordCount;
3575
3576 LOG(INFO) << "Tracked allocations, (head=" << gAllocRecordHead << " count=" << count << ")";
3577 while (count--) {
3578 AllocRecord* record = &recent_allocation_records_[i];
3579
Elliott Hughesa8f93cb2012-06-08 17:08:48 -07003580 LOG(INFO) << StringPrintf(" Thread %-2d %6zd bytes ", record->thin_lock_id, record->byte_count)
Elliott Hughes545a0642011-11-08 19:10:03 -08003581 << PrettyClass(record->type);
3582
3583 for (size_t stack_frame = 0; stack_frame < kMaxAllocRecordStackDepth; ++stack_frame) {
Brian Carlstromea46f952013-07-30 01:26:50 -07003584 const mirror::ArtMethod* m = record->stack[stack_frame].method;
Elliott Hughes545a0642011-11-08 19:10:03 -08003585 if (m == NULL) {
3586 break;
3587 }
3588 LOG(INFO) << " " << PrettyMethod(m) << " line " << record->stack[stack_frame].LineNumber();
3589 }
3590
3591 // pause periodically to help logcat catch up
3592 if ((count % 5) == 0) {
3593 usleep(40000);
3594 }
3595
Elliott Hughesb1a58792013-07-11 18:10:58 -07003596 i = (i + 1) & (gAllocRecordMax-1);
Elliott Hughes545a0642011-11-08 19:10:03 -08003597 }
3598}
3599
3600class StringTable {
3601 public:
3602 StringTable() {
3603 }
3604
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08003605 void Add(const char* s) {
Elliott Hughes545a0642011-11-08 19:10:03 -08003606 table_.insert(s);
3607 }
3608
Elliott Hughesa8f93cb2012-06-08 17:08:48 -07003609 size_t IndexOf(const char* s) const {
Mathieu Chartier02e25112013-08-14 16:14:24 -07003610 auto it = table_.find(s);
Elliott Hughesa8f93cb2012-06-08 17:08:48 -07003611 if (it == table_.end()) {
3612 LOG(FATAL) << "IndexOf(\"" << s << "\") failed";
3613 }
3614 return std::distance(table_.begin(), it);
Elliott Hughes545a0642011-11-08 19:10:03 -08003615 }
3616
Elliott Hughesa8f93cb2012-06-08 17:08:48 -07003617 size_t Size() const {
Elliott Hughes545a0642011-11-08 19:10:03 -08003618 return table_.size();
3619 }
3620
Elliott Hughesa8f93cb2012-06-08 17:08:48 -07003621 void WriteTo(std::vector<uint8_t>& bytes) const {
Mathieu Chartier02e25112013-08-14 16:14:24 -07003622 for (const std::string& str : table_) {
3623 const char* s = str.c_str();
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08003624 size_t s_len = CountModifiedUtf8Chars(s);
3625 UniquePtr<uint16_t> s_utf16(new uint16_t[s_len]);
3626 ConvertModifiedUtf8ToUtf16(s_utf16.get(), s);
3627 JDWP::AppendUtf16BE(bytes, s_utf16.get(), s_len);
Elliott Hughes545a0642011-11-08 19:10:03 -08003628 }
3629 }
3630
3631 private:
Elliott Hughesa8f93cb2012-06-08 17:08:48 -07003632 std::set<std::string> table_;
Elliott Hughes545a0642011-11-08 19:10:03 -08003633 DISALLOW_COPY_AND_ASSIGN(StringTable);
3634};
3635
3636/*
3637 * The data we send to DDMS contains everything we have recorded.
3638 *
3639 * Message header (all values big-endian):
3640 * (1b) message header len (to allow future expansion); includes itself
3641 * (1b) entry header len
3642 * (1b) stack frame len
3643 * (2b) number of entries
3644 * (4b) offset to string table from start of message
3645 * (2b) number of class name strings
3646 * (2b) number of method name strings
3647 * (2b) number of source file name strings
3648 * For each entry:
3649 * (4b) total allocation size
Elliott Hughes221229c2013-01-08 18:17:50 -08003650 * (2b) thread id
Elliott Hughes545a0642011-11-08 19:10:03 -08003651 * (2b) allocated object's class name index
3652 * (1b) stack depth
3653 * For each stack frame:
3654 * (2b) method's class name
3655 * (2b) method name
3656 * (2b) method source file
3657 * (2b) line number, clipped to 32767; -2 if native; -1 if no source
3658 * (xb) class name strings
3659 * (xb) method name strings
3660 * (xb) source file strings
3661 *
3662 * As with other DDM traffic, strings are sent as a 4-byte length
3663 * followed by UTF-16 data.
3664 *
3665 * We send up 16-bit unsigned indexes into string tables. In theory there
Elliott Hughesb1a58792013-07-11 18:10:58 -07003666 * can be (kMaxAllocRecordStackDepth * gAllocRecordMax) unique strings in
Elliott Hughes545a0642011-11-08 19:10:03 -08003667 * each table, but in practice there should be far fewer.
3668 *
3669 * The chief reason for using a string table here is to keep the size of
3670 * the DDMS message to a minimum. This is partly to make the protocol
3671 * efficient, but also because we have to form the whole thing up all at
3672 * once in a memory buffer.
3673 *
3674 * We use separate string tables for class names, method names, and source
3675 * files to keep the indexes small. There will generally be no overlap
3676 * between the contents of these tables.
3677 */
3678jbyteArray Dbg::GetRecentAllocations() {
3679 if (false) {
3680 DumpRecentAllocations();
3681 }
3682
Ian Rogers50b35e22012-10-04 10:09:15 -07003683 Thread* self = Thread::Current();
Elliott Hughes545a0642011-11-08 19:10:03 -08003684 std::vector<uint8_t> bytes;
Mathieu Chartier46e811b2013-07-10 17:09:14 -07003685 {
3686 MutexLock mu(self, gAllocTrackerLock);
3687 //
3688 // Part 1: generate string tables.
3689 //
3690 StringTable class_names;
3691 StringTable method_names;
3692 StringTable filenames;
Elliott Hughes545a0642011-11-08 19:10:03 -08003693
Mathieu Chartier46e811b2013-07-10 17:09:14 -07003694 int count = gAllocRecordCount;
3695 int idx = HeadIndex();
3696 while (count--) {
3697 AllocRecord* record = &recent_allocation_records_[idx];
Elliott Hughes545a0642011-11-08 19:10:03 -08003698
Mathieu Chartier46e811b2013-07-10 17:09:14 -07003699 class_names.Add(ClassHelper(record->type).GetDescriptor());
Elliott Hughes545a0642011-11-08 19:10:03 -08003700
Mathieu Chartier46e811b2013-07-10 17:09:14 -07003701 MethodHelper mh;
3702 for (size_t i = 0; i < kMaxAllocRecordStackDepth; i++) {
Brian Carlstromea46f952013-07-30 01:26:50 -07003703 mirror::ArtMethod* m = record->stack[i].method;
Mathieu Chartier46e811b2013-07-10 17:09:14 -07003704 if (m != NULL) {
3705 mh.ChangeMethod(m);
3706 class_names.Add(mh.GetDeclaringClassDescriptor());
3707 method_names.Add(mh.GetName());
3708 filenames.Add(mh.GetDeclaringClassSourceFile());
3709 }
3710 }
Elliott Hughes545a0642011-11-08 19:10:03 -08003711
Elliott Hughesb1a58792013-07-11 18:10:58 -07003712 idx = (idx + 1) & (gAllocRecordMax-1);
Elliott Hughes545a0642011-11-08 19:10:03 -08003713 }
3714
Mathieu Chartier46e811b2013-07-10 17:09:14 -07003715 LOG(INFO) << "allocation records: " << gAllocRecordCount;
3716
3717 //
3718 // Part 2: Generate the output and store it in the buffer.
3719 //
3720
3721 // (1b) message header len (to allow future expansion); includes itself
3722 // (1b) entry header len
3723 // (1b) stack frame len
3724 const int kMessageHeaderLen = 15;
3725 const int kEntryHeaderLen = 9;
3726 const int kStackFrameLen = 8;
3727 JDWP::Append1BE(bytes, kMessageHeaderLen);
3728 JDWP::Append1BE(bytes, kEntryHeaderLen);
3729 JDWP::Append1BE(bytes, kStackFrameLen);
3730
3731 // (2b) number of entries
3732 // (4b) offset to string table from start of message
3733 // (2b) number of class name strings
3734 // (2b) number of method name strings
3735 // (2b) number of source file name strings
3736 JDWP::Append2BE(bytes, gAllocRecordCount);
3737 size_t string_table_offset = bytes.size();
Brian Carlstrom7934ac22013-07-26 10:54:15 -07003738 JDWP::Append4BE(bytes, 0); // We'll patch this later...
Mathieu Chartier46e811b2013-07-10 17:09:14 -07003739 JDWP::Append2BE(bytes, class_names.Size());
3740 JDWP::Append2BE(bytes, method_names.Size());
3741 JDWP::Append2BE(bytes, filenames.Size());
3742
3743 count = gAllocRecordCount;
3744 idx = HeadIndex();
Mathieu Chartier46e811b2013-07-10 17:09:14 -07003745 while (count--) {
3746 // For each entry:
3747 // (4b) total allocation size
3748 // (2b) thread id
3749 // (2b) allocated object's class name index
3750 // (1b) stack depth
3751 AllocRecord* record = &recent_allocation_records_[idx];
3752 size_t stack_depth = record->GetDepth();
Mathieu Chartier590fee92013-09-13 13:46:47 -07003753 ClassHelper kh(record->type);
Mathieu Chartier46e811b2013-07-10 17:09:14 -07003754 size_t allocated_object_class_name_index = class_names.IndexOf(kh.GetDescriptor());
3755 JDWP::Append4BE(bytes, record->byte_count);
3756 JDWP::Append2BE(bytes, record->thin_lock_id);
3757 JDWP::Append2BE(bytes, allocated_object_class_name_index);
3758 JDWP::Append1BE(bytes, stack_depth);
3759
3760 MethodHelper mh;
3761 for (size_t stack_frame = 0; stack_frame < stack_depth; ++stack_frame) {
3762 // For each stack frame:
3763 // (2b) method's class name
3764 // (2b) method name
3765 // (2b) method source file
3766 // (2b) line number, clipped to 32767; -2 if native; -1 if no source
3767 mh.ChangeMethod(record->stack[stack_frame].method);
3768 size_t class_name_index = class_names.IndexOf(mh.GetDeclaringClassDescriptor());
3769 size_t method_name_index = method_names.IndexOf(mh.GetName());
3770 size_t file_name_index = filenames.IndexOf(mh.GetDeclaringClassSourceFile());
3771 JDWP::Append2BE(bytes, class_name_index);
3772 JDWP::Append2BE(bytes, method_name_index);
3773 JDWP::Append2BE(bytes, file_name_index);
3774 JDWP::Append2BE(bytes, record->stack[stack_frame].LineNumber());
3775 }
3776
Elliott Hughesb1a58792013-07-11 18:10:58 -07003777 idx = (idx + 1) & (gAllocRecordMax-1);
Mathieu Chartier46e811b2013-07-10 17:09:14 -07003778 }
3779
3780 // (xb) class name strings
3781 // (xb) method name strings
3782 // (xb) source file strings
3783 JDWP::Set4BE(&bytes[string_table_offset], bytes.size());
3784 class_names.WriteTo(bytes);
3785 method_names.WriteTo(bytes);
3786 filenames.WriteTo(bytes);
Elliott Hughes545a0642011-11-08 19:10:03 -08003787 }
Ian Rogers50b35e22012-10-04 10:09:15 -07003788 JNIEnv* env = self->GetJniEnv();
Elliott Hughes545a0642011-11-08 19:10:03 -08003789 jbyteArray result = env->NewByteArray(bytes.size());
3790 if (result != NULL) {
3791 env->SetByteArrayRegion(result, 0, bytes.size(), reinterpret_cast<const jbyte*>(&bytes[0]));
3792 }
3793 return result;
3794}
3795
Elliott Hughes872d4ec2011-10-21 17:07:15 -07003796} // namespace art