blob: 4bc16fbf2c631414371944769bc2d87c605f25a9 [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
Brian Carlstromea46f952013-07-30 01:26:50 -0700139 virtual void MethodUnwind(Thread* thread, const mirror::ArtMethod* method,
Ian Rogers62d6c772013-02-27 08:32:07 -0800140 uint32_t dex_pc) SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
141 // We're not recorded to listen to this kind of event, so complain.
142 LOG(ERROR) << "Unexpected method unwind event in debugger " << PrettyMethod(method)
143 << " " << dex_pc;
144 }
145
146 virtual void DexPcMoved(Thread* thread, mirror::Object* this_object,
Brian Carlstromea46f952013-07-30 01:26:50 -0700147 const mirror::ArtMethod* method, uint32_t new_dex_pc)
Ian Rogers62d6c772013-02-27 08:32:07 -0800148 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
149 Dbg::UpdateDebugger(thread, this_object, method, new_dex_pc);
150 }
151
152 virtual void ExceptionCaught(Thread* thread, const ThrowLocation& throw_location,
Brian Carlstromea46f952013-07-30 01:26:50 -0700153 mirror::ArtMethod* catch_method, uint32_t catch_dex_pc,
Ian Rogers62d6c772013-02-27 08:32:07 -0800154 mirror::Throwable* exception_object)
155 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
156 Dbg::PostException(thread, throw_location, catch_method, catch_dex_pc, exception_object);
157 }
Ian Rogers62d6c772013-02-27 08:32:07 -0800158} gDebugInstrumentationListener;
159
Elliott Hughes4ffd3132011-10-24 12:06:42 -0700160// JDWP is allowed unless the Zygote forbids it.
161static bool gJdwpAllowed = true;
162
Elliott Hughesc0f09332012-03-26 13:27:06 -0700163// Was there a -Xrunjdwp or -agentlib:jdwp= argument on the command line?
Elliott Hughes3bb81562011-10-21 18:52:59 -0700164static bool gJdwpConfigured = false;
165
Elliott Hughesc0f09332012-03-26 13:27:06 -0700166// Broken-down JDWP options. (Only valid if IsJdwpConfigured() is true.)
Elliott Hughes376a7a02011-10-24 18:35:55 -0700167static JDWP::JdwpOptions gJdwpOptions;
Elliott Hughes3bb81562011-10-21 18:52:59 -0700168
169// Runtime JDWP state.
170static JDWP::JdwpState* gJdwpState = NULL;
171static bool gDebuggerConnected; // debugger or DDMS is connected.
172static bool gDebuggerActive; // debugger is making requests.
Elliott Hughes86964332012-02-15 19:37:42 -0800173static bool gDisposed; // debugger called VirtualMachine.Dispose, so we should drop the connection.
Elliott Hughes3bb81562011-10-21 18:52:59 -0700174
Elliott Hughes47fce012011-10-25 18:37:19 -0700175static bool gDdmThreadNotification = false;
176
Elliott Hughes767a1472011-10-26 18:49:02 -0700177// DDMS GC-related settings.
178static Dbg::HpifWhen gDdmHpifWhen = Dbg::HPIF_WHEN_NEVER;
179static Dbg::HpsgWhen gDdmHpsgWhen = Dbg::HPSG_WHEN_NEVER;
180static Dbg::HpsgWhat gDdmHpsgWhat;
181static Dbg::HpsgWhen gDdmNhsgWhen = Dbg::HPSG_WHEN_NEVER;
182static Dbg::HpsgWhat gDdmNhsgWhat;
183
Elliott Hughes475fc232011-10-25 15:00:35 -0700184static ObjectRegistry* gRegistry = NULL;
185
Elliott Hughes545a0642011-11-08 19:10:03 -0800186// Recent allocation tracking.
Brian Carlstromdf629502013-07-17 22:39:56 -0700187static Mutex gAllocTrackerLock DEFAULT_MUTEX_ACQUIRED_AFTER("AllocTracker lock");
Brian Carlstrom7934ac22013-07-26 10:54:15 -0700188AllocRecord* Dbg::recent_allocation_records_ PT_GUARDED_BY(gAllocTrackerLock) = NULL; // TODO: CircularBuffer<AllocRecord>
Elliott Hughesb1a58792013-07-11 18:10:58 -0700189static size_t gAllocRecordMax GUARDED_BY(gAllocTrackerLock) = 0;
Elliott Hughesf8349362012-06-18 15:00:06 -0700190static size_t gAllocRecordHead GUARDED_BY(gAllocTrackerLock) = 0;
191static size_t gAllocRecordCount GUARDED_BY(gAllocTrackerLock) = 0;
Elliott Hughes545a0642011-11-08 19:10:03 -0800192
Elliott Hughes86964332012-02-15 19:37:42 -0800193// Breakpoints and single-stepping.
jeffhao09bfc6a2012-12-11 18:11:43 -0800194static std::vector<Breakpoint> gBreakpoints GUARDED_BY(Locks::breakpoint_lock_);
195static SingleStepControl gSingleStepControl GUARDED_BY(Locks::breakpoint_lock_);
Elliott Hughes86964332012-02-15 19:37:42 -0800196
Brian Carlstromea46f952013-07-30 01:26:50 -0700197static bool IsBreakpoint(const mirror::ArtMethod* m, uint32_t dex_pc)
jeffhao09bfc6a2012-12-11 18:11:43 -0800198 LOCKS_EXCLUDED(Locks::breakpoint_lock_)
Ian Rogersb726dcb2012-09-05 08:57:23 -0700199 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
jeffhao09bfc6a2012-12-11 18:11:43 -0800200 MutexLock mu(Thread::Current(), *Locks::breakpoint_lock_);
Elliott Hughes86964332012-02-15 19:37:42 -0800201 for (size_t i = 0; i < gBreakpoints.size(); ++i) {
Elliott Hughesa656a0f2012-02-21 18:03:44 -0800202 if (gBreakpoints[i].method == m && gBreakpoints[i].dex_pc == dex_pc) {
Elliott Hughes86964332012-02-15 19:37:42 -0800203 VLOG(jdwp) << "Hit breakpoint #" << i << ": " << gBreakpoints[i];
204 return true;
205 }
206 }
207 return false;
208}
209
Elliott Hughes9e0c1752013-01-09 14:02:58 -0800210static bool IsSuspendedForDebugger(ScopedObjectAccessUnchecked& soa, Thread* thread) {
211 MutexLock mu(soa.Self(), *Locks::thread_suspend_count_lock_);
212 // A thread may be suspended for GC; in this code, we really want to know whether
213 // there's a debugger suspension active.
214 return thread->IsSuspended() && thread->GetDebugSuspendCount() > 0;
215}
216
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800217static mirror::Array* DecodeArray(JDWP::RefTypeId id, JDWP::JdwpError& status)
Ian Rogersb726dcb2012-09-05 08:57:23 -0700218 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800219 mirror::Object* o = gRegistry->Get<mirror::Object*>(id);
Elliott Hughes64f574f2013-02-20 14:57:12 -0800220 if (o == NULL || o == ObjectRegistry::kInvalidObject) {
Elliott Hughes436e3722012-02-17 20:01:47 -0800221 status = JDWP::ERR_INVALID_OBJECT;
222 return NULL;
223 }
224 if (!o->IsArrayInstance()) {
225 status = JDWP::ERR_INVALID_ARRAY;
226 return NULL;
227 }
228 status = JDWP::ERR_NONE;
229 return o->AsArray();
230}
231
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800232static mirror::Class* DecodeClass(JDWP::RefTypeId id, JDWP::JdwpError& status)
Ian Rogersb726dcb2012-09-05 08:57:23 -0700233 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800234 mirror::Object* o = gRegistry->Get<mirror::Object*>(id);
Elliott Hughes64f574f2013-02-20 14:57:12 -0800235 if (o == NULL || o == ObjectRegistry::kInvalidObject) {
Elliott Hughes436e3722012-02-17 20:01:47 -0800236 status = JDWP::ERR_INVALID_OBJECT;
237 return NULL;
238 }
239 if (!o->IsClass()) {
240 status = JDWP::ERR_INVALID_CLASS;
241 return NULL;
242 }
243 status = JDWP::ERR_NONE;
244 return o->AsClass();
245}
246
Elliott Hughes221229c2013-01-08 18:17:50 -0800247static JDWP::JdwpError DecodeThread(ScopedObjectAccessUnchecked& soa, JDWP::ObjectId thread_id, Thread*& thread)
jeffhaoa77f0f62012-12-05 17:19:31 -0800248 EXCLUSIVE_LOCKS_REQUIRED(Locks::thread_list_lock_)
Ian Rogersb726dcb2012-09-05 08:57:23 -0700249 LOCKS_EXCLUDED(Locks::thread_suspend_count_lock_)
250 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800251 mirror::Object* thread_peer = gRegistry->Get<mirror::Object*>(thread_id);
Elliott Hughes64f574f2013-02-20 14:57:12 -0800252 if (thread_peer == NULL || thread_peer == ObjectRegistry::kInvalidObject) {
Elliott Hughes221229c2013-01-08 18:17:50 -0800253 // This isn't even an object.
254 return JDWP::ERR_INVALID_OBJECT;
Elliott Hughes436e3722012-02-17 20:01:47 -0800255 }
Elliott Hughes221229c2013-01-08 18:17:50 -0800256
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800257 mirror::Class* java_lang_Thread = soa.Decode<mirror::Class*>(WellKnownClasses::java_lang_Thread);
Elliott Hughes221229c2013-01-08 18:17:50 -0800258 if (!java_lang_Thread->IsAssignableFrom(thread_peer->GetClass())) {
259 // This isn't a thread.
260 return JDWP::ERR_INVALID_THREAD;
261 }
262
263 thread = Thread::FromManagedThread(soa, thread_peer);
264 if (thread == NULL) {
265 // This is a java.lang.Thread without a Thread*. Must be a zombie.
266 return JDWP::ERR_THREAD_NOT_ALIVE;
267 }
268 return JDWP::ERR_NONE;
Elliott Hughes436e3722012-02-17 20:01:47 -0800269}
270
Elliott Hughes24437992011-11-30 14:49:33 -0800271static JDWP::JdwpTag BasicTagFromDescriptor(const char* descriptor) {
272 // JDWP deliberately uses the descriptor characters' ASCII values for its enum.
273 // Note that by "basic" we mean that we don't get more specific than JT_OBJECT.
274 return static_cast<JDWP::JdwpTag>(descriptor[0]);
275}
276
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800277static JDWP::JdwpTag TagFromClass(mirror::Class* c)
Ian Rogersb726dcb2012-09-05 08:57:23 -0700278 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Elliott Hughes86b00102011-12-05 17:54:26 -0800279 CHECK(c != NULL);
Elliott Hughes24437992011-11-30 14:49:33 -0800280 if (c->IsArrayClass()) {
281 return JDWP::JT_ARRAY;
282 }
283
Elliott Hughes3d30d9b2011-12-07 17:35:48 -0800284 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
Elliott Hughes24437992011-11-30 14:49:33 -0800285 if (c->IsStringClass()) {
286 return JDWP::JT_STRING;
287 } else if (c->IsClassClass()) {
288 return JDWP::JT_CLASS_OBJECT;
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -0800289 } else if (class_linker->FindSystemClass("Ljava/lang/Thread;")->IsAssignableFrom(c)) {
Elliott Hughes24437992011-11-30 14:49:33 -0800290 return JDWP::JT_THREAD;
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -0800291 } else if (class_linker->FindSystemClass("Ljava/lang/ThreadGroup;")->IsAssignableFrom(c)) {
Elliott Hughes24437992011-11-30 14:49:33 -0800292 return JDWP::JT_THREAD_GROUP;
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -0800293 } else if (class_linker->FindSystemClass("Ljava/lang/ClassLoader;")->IsAssignableFrom(c)) {
Elliott Hughes24437992011-11-30 14:49:33 -0800294 return JDWP::JT_CLASS_LOADER;
Elliott Hughes24437992011-11-30 14:49:33 -0800295 } else {
296 return JDWP::JT_OBJECT;
297 }
298}
299
300/*
301 * Objects declared to hold Object might actually hold a more specific
302 * type. The debugger may take a special interest in these (e.g. it
303 * wants to display the contents of Strings), so we want to return an
304 * appropriate tag.
305 *
306 * Null objects are tagged JT_OBJECT.
307 */
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800308static JDWP::JdwpTag TagFromObject(const mirror::Object* o)
Ian Rogersb726dcb2012-09-05 08:57:23 -0700309 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Elliott Hughes24437992011-11-30 14:49:33 -0800310 return (o == NULL) ? JDWP::JT_OBJECT : TagFromClass(o->GetClass());
311}
312
313static bool IsPrimitiveTag(JDWP::JdwpTag tag) {
314 switch (tag) {
315 case JDWP::JT_BOOLEAN:
316 case JDWP::JT_BYTE:
317 case JDWP::JT_CHAR:
318 case JDWP::JT_FLOAT:
319 case JDWP::JT_DOUBLE:
320 case JDWP::JT_INT:
321 case JDWP::JT_LONG:
322 case JDWP::JT_SHORT:
323 case JDWP::JT_VOID:
324 return true;
325 default:
326 return false;
327 }
328}
329
Elliott Hughes3bb81562011-10-21 18:52:59 -0700330/*
331 * Handle one of the JDWP name/value pairs.
332 *
333 * JDWP options are:
334 * help: if specified, show help message and bail
335 * transport: may be dt_socket or dt_shmem
336 * address: for dt_socket, "host:port", or just "port" when listening
337 * server: if "y", wait for debugger to attach; if "n", attach to debugger
338 * timeout: how long to wait for debugger to connect / listen
339 *
340 * Useful with server=n (these aren't supported yet):
341 * onthrow=<exception-name>: connect to debugger when exception thrown
342 * onuncaught=y|n: connect to debugger when uncaught exception thrown
343 * launch=<command-line>: launch the debugger itself
344 *
345 * The "transport" option is required, as is "address" if server=n.
346 */
347static bool ParseJdwpOption(const std::string& name, const std::string& value) {
348 if (name == "transport") {
349 if (value == "dt_socket") {
Elliott Hughes376a7a02011-10-24 18:35:55 -0700350 gJdwpOptions.transport = JDWP::kJdwpTransportSocket;
Elliott Hughes3bb81562011-10-21 18:52:59 -0700351 } else if (value == "dt_android_adb") {
Elliott Hughes376a7a02011-10-24 18:35:55 -0700352 gJdwpOptions.transport = JDWP::kJdwpTransportAndroidAdb;
Elliott Hughes3bb81562011-10-21 18:52:59 -0700353 } else {
354 LOG(ERROR) << "JDWP transport not supported: " << value;
355 return false;
356 }
357 } else if (name == "server") {
358 if (value == "n") {
Elliott Hughes376a7a02011-10-24 18:35:55 -0700359 gJdwpOptions.server = false;
Elliott Hughes3bb81562011-10-21 18:52:59 -0700360 } else if (value == "y") {
Elliott Hughes376a7a02011-10-24 18:35:55 -0700361 gJdwpOptions.server = true;
Elliott Hughes3bb81562011-10-21 18:52:59 -0700362 } else {
363 LOG(ERROR) << "JDWP option 'server' must be 'y' or 'n'";
364 return false;
365 }
366 } else if (name == "suspend") {
367 if (value == "n") {
Elliott Hughes376a7a02011-10-24 18:35:55 -0700368 gJdwpOptions.suspend = false;
Elliott Hughes3bb81562011-10-21 18:52:59 -0700369 } else if (value == "y") {
Elliott Hughes376a7a02011-10-24 18:35:55 -0700370 gJdwpOptions.suspend = true;
Elliott Hughes3bb81562011-10-21 18:52:59 -0700371 } else {
372 LOG(ERROR) << "JDWP option 'suspend' must be 'y' or 'n'";
373 return false;
374 }
375 } else if (name == "address") {
376 /* this is either <port> or <host>:<port> */
377 std::string port_string;
Elliott Hughes376a7a02011-10-24 18:35:55 -0700378 gJdwpOptions.host.clear();
Elliott Hughes3bb81562011-10-21 18:52:59 -0700379 std::string::size_type colon = value.find(':');
380 if (colon != std::string::npos) {
Elliott Hughes376a7a02011-10-24 18:35:55 -0700381 gJdwpOptions.host = value.substr(0, colon);
Elliott Hughes3bb81562011-10-21 18:52:59 -0700382 port_string = value.substr(colon + 1);
383 } else {
384 port_string = value;
385 }
386 if (port_string.empty()) {
387 LOG(ERROR) << "JDWP address missing port: " << value;
388 return false;
389 }
390 char* end;
Elliott Hughesba8eee12012-01-24 20:25:24 -0800391 uint64_t port = strtoul(port_string.c_str(), &end, 10);
392 if (*end != '\0' || port > 0xffff) {
Elliott Hughes3bb81562011-10-21 18:52:59 -0700393 LOG(ERROR) << "JDWP address has junk in port field: " << value;
394 return false;
395 }
Elliott Hughes376a7a02011-10-24 18:35:55 -0700396 gJdwpOptions.port = port;
Elliott Hughes3bb81562011-10-21 18:52:59 -0700397 } else if (name == "launch" || name == "onthrow" || name == "oncaught" || name == "timeout") {
398 /* valid but unsupported */
399 LOG(INFO) << "Ignoring JDWP option '" << name << "'='" << value << "'";
400 } else {
401 LOG(INFO) << "Ignoring unrecognized JDWP option '" << name << "'='" << value << "'";
402 }
403
404 return true;
405}
406
407/*
408 * Parse the latter half of a -Xrunjdwp/-agentlib:jdwp= string, e.g.:
409 * "transport=dt_socket,address=8000,server=y,suspend=n"
410 */
411bool Dbg::ParseJdwpOptions(const std::string& options) {
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -0800412 VLOG(jdwp) << "ParseJdwpOptions: " << options;
Elliott Hughes47fce012011-10-25 18:37:19 -0700413
Elliott Hughes3bb81562011-10-21 18:52:59 -0700414 std::vector<std::string> pairs;
415 Split(options, ',', pairs);
416
417 for (size_t i = 0; i < pairs.size(); ++i) {
418 std::string::size_type equals = pairs[i].find('=');
419 if (equals == std::string::npos) {
420 LOG(ERROR) << "Can't parse JDWP option '" << pairs[i] << "' in '" << options << "'";
421 return false;
422 }
423 ParseJdwpOption(pairs[i].substr(0, equals), pairs[i].substr(equals + 1));
424 }
425
Elliott Hughes376a7a02011-10-24 18:35:55 -0700426 if (gJdwpOptions.transport == JDWP::kJdwpTransportUnknown) {
Elliott Hughes3bb81562011-10-21 18:52:59 -0700427 LOG(ERROR) << "Must specify JDWP transport: " << options;
428 }
Elliott Hughes376a7a02011-10-24 18:35:55 -0700429 if (!gJdwpOptions.server && (gJdwpOptions.host.empty() || gJdwpOptions.port == 0)) {
Elliott Hughes3bb81562011-10-21 18:52:59 -0700430 LOG(ERROR) << "Must specify JDWP host and port when server=n: " << options;
431 return false;
432 }
433
434 gJdwpConfigured = true;
435 return true;
436}
437
Elliott Hughesd1cc8362011-10-24 16:58:50 -0700438void Dbg::StartJdwp() {
Elliott Hughesc0f09332012-03-26 13:27:06 -0700439 if (!gJdwpAllowed || !IsJdwpConfigured()) {
Elliott Hughes376a7a02011-10-24 18:35:55 -0700440 // No JDWP for you!
441 return;
442 }
443
Elliott Hughes475fc232011-10-25 15:00:35 -0700444 CHECK(gRegistry == NULL);
445 gRegistry = new ObjectRegistry;
446
Elliott Hughesd1cc8362011-10-24 16:58:50 -0700447 // Init JDWP if the debugger is enabled. This may connect out to a
448 // debugger, passively listen for a debugger, or block waiting for a
449 // debugger.
Elliott Hughes376a7a02011-10-24 18:35:55 -0700450 gJdwpState = JDWP::JdwpState::Create(&gJdwpOptions);
451 if (gJdwpState == NULL) {
Elliott Hughesf8a2df72011-12-01 12:19:54 -0800452 // We probably failed because some other process has the port already, which means that
453 // if we don't abort the user is likely to think they're talking to us when they're actually
454 // talking to that other process.
Elliott Hughes3d30d9b2011-12-07 17:35:48 -0800455 LOG(FATAL) << "Debugger thread failed to initialize";
Elliott Hughesd1cc8362011-10-24 16:58:50 -0700456 }
457
458 // If a debugger has already attached, send the "welcome" message.
459 // This may cause us to suspend all threads.
Elliott Hughes376a7a02011-10-24 18:35:55 -0700460 if (gJdwpState->IsActive()) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700461 ScopedObjectAccess soa(Thread::Current());
Elliott Hughes376a7a02011-10-24 18:35:55 -0700462 if (!gJdwpState->PostVMStart()) {
Elliott Hughes3d30d9b2011-12-07 17:35:48 -0800463 LOG(WARNING) << "Failed to post 'start' message to debugger";
Elliott Hughesd1cc8362011-10-24 16:58:50 -0700464 }
465 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700466}
467
Elliott Hughesd1cc8362011-10-24 16:58:50 -0700468void Dbg::StopJdwp() {
Elliott Hughes376a7a02011-10-24 18:35:55 -0700469 delete gJdwpState;
Elliott Hughes475fc232011-10-25 15:00:35 -0700470 delete gRegistry;
471 gRegistry = NULL;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700472}
473
Elliott Hughes767a1472011-10-26 18:49:02 -0700474void Dbg::GcDidFinish() {
475 if (gDdmHpifWhen != HPIF_WHEN_NEVER) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700476 ScopedObjectAccess soa(Thread::Current());
Elliott Hughes81ff3182012-03-23 20:35:56 -0700477 LOG(DEBUG) << "Sending heap info to DDM";
Elliott Hughes7162ad92011-10-27 14:08:42 -0700478 DdmSendHeapInfo(gDdmHpifWhen);
Elliott Hughes767a1472011-10-26 18:49:02 -0700479 }
480 if (gDdmHpsgWhen != HPSG_WHEN_NEVER) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700481 ScopedObjectAccess soa(Thread::Current());
Elliott Hughes81ff3182012-03-23 20:35:56 -0700482 LOG(DEBUG) << "Dumping heap to DDM";
Elliott Hughes6a5bd492011-10-28 14:33:57 -0700483 DdmSendHeapSegments(false);
Elliott Hughes767a1472011-10-26 18:49:02 -0700484 }
485 if (gDdmNhsgWhen != HPSG_WHEN_NEVER) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700486 ScopedObjectAccess soa(Thread::Current());
Elliott Hughes767a1472011-10-26 18:49:02 -0700487 LOG(DEBUG) << "Dumping native heap to DDM";
Elliott Hughes6a5bd492011-10-28 14:33:57 -0700488 DdmSendHeapSegments(true);
Elliott Hughes767a1472011-10-26 18:49:02 -0700489 }
490}
491
Elliott Hughes4ffd3132011-10-24 12:06:42 -0700492void Dbg::SetJdwpAllowed(bool allowed) {
493 gJdwpAllowed = allowed;
494}
495
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700496DebugInvokeReq* Dbg::GetInvokeReq() {
Elliott Hughes475fc232011-10-25 15:00:35 -0700497 return Thread::Current()->GetInvokeReq();
498}
499
500Thread* Dbg::GetDebugThread() {
501 return (gJdwpState != NULL) ? gJdwpState->GetDebugThread() : NULL;
502}
503
504void Dbg::ClearWaitForEventThread() {
505 gJdwpState->ClearWaitForEventThread();
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700506}
507
508void Dbg::Connected() {
Elliott Hughes3bb81562011-10-21 18:52:59 -0700509 CHECK(!gDebuggerConnected);
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -0800510 VLOG(jdwp) << "JDWP has attached";
Elliott Hughes3bb81562011-10-21 18:52:59 -0700511 gDebuggerConnected = true;
Elliott Hughes86964332012-02-15 19:37:42 -0800512 gDisposed = false;
513}
514
515void Dbg::Disposed() {
516 gDisposed = true;
517}
518
519bool Dbg::IsDisposed() {
520 return gDisposed;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700521}
522
Elliott Hughesa2155262011-11-16 16:26:58 -0800523void Dbg::GoActive() {
524 // Enable all debugging features, including scans for breakpoints.
525 // This is a no-op if we're already active.
526 // Only called from the JDWP handler thread.
527 if (gDebuggerActive) {
528 return;
529 }
530
Elliott Hughesc0f09332012-03-26 13:27:06 -0700531 {
532 // TODO: dalvik only warned if there were breakpoints left over. clear in Dbg::Disconnected?
jeffhao09bfc6a2012-12-11 18:11:43 -0800533 MutexLock mu(Thread::Current(), *Locks::breakpoint_lock_);
Elliott Hughesc0f09332012-03-26 13:27:06 -0700534 CHECK_EQ(gBreakpoints.size(), 0U);
535 }
Elliott Hughesa2155262011-11-16 16:26:58 -0800536
Ian Rogers62d6c772013-02-27 08:32:07 -0800537 Runtime* runtime = Runtime::Current();
538 runtime->GetThreadList()->SuspendAll();
539 Thread* self = Thread::Current();
540 ThreadState old_state = self->SetStateUnsafe(kRunnable);
541 CHECK_NE(old_state, kRunnable);
542 runtime->GetInstrumentation()->AddListener(&gDebugInstrumentationListener,
543 instrumentation::Instrumentation::kMethodEntered |
544 instrumentation::Instrumentation::kMethodExited |
Jeff Hao14dd5a82013-04-11 10:23:36 -0700545 instrumentation::Instrumentation::kDexPcMoved |
546 instrumentation::Instrumentation::kExceptionCaught);
Elliott Hughesa2155262011-11-16 16:26:58 -0800547 gDebuggerActive = true;
Ian Rogers62d6c772013-02-27 08:32:07 -0800548 CHECK_EQ(self->SetStateUnsafe(old_state), kRunnable);
549 runtime->GetThreadList()->ResumeAll();
550
551 LOG(INFO) << "Debugger is active";
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700552}
553
554void Dbg::Disconnected() {
Elliott Hughes234ab152011-10-26 14:02:26 -0700555 CHECK(gDebuggerConnected);
556
Elliott Hughesc0f09332012-03-26 13:27:06 -0700557 LOG(INFO) << "Debugger is no longer active";
Elliott Hughes234ab152011-10-26 14:02:26 -0700558
Ian Rogers62d6c772013-02-27 08:32:07 -0800559 // Suspend all threads and exclusively acquire the mutator lock. Set the state of the thread
560 // to kRunnable to avoid scoped object access transitions. Remove the debugger as a listener
561 // and clear the object registry.
562 Runtime* runtime = Runtime::Current();
563 runtime->GetThreadList()->SuspendAll();
564 Thread* self = Thread::Current();
565 ThreadState old_state = self->SetStateUnsafe(kRunnable);
566 runtime->GetInstrumentation()->RemoveListener(&gDebugInstrumentationListener,
567 instrumentation::Instrumentation::kMethodEntered |
568 instrumentation::Instrumentation::kMethodExited |
Jeff Hao14dd5a82013-04-11 10:23:36 -0700569 instrumentation::Instrumentation::kDexPcMoved |
570 instrumentation::Instrumentation::kExceptionCaught);
Elliott Hughesc0f09332012-03-26 13:27:06 -0700571 gDebuggerActive = false;
Elliott Hughes234ab152011-10-26 14:02:26 -0700572 gRegistry->Clear();
573 gDebuggerConnected = false;
Ian Rogers62d6c772013-02-27 08:32:07 -0800574 CHECK_EQ(self->SetStateUnsafe(old_state), kRunnable);
575 runtime->GetThreadList()->ResumeAll();
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700576}
577
Elliott Hughesc0f09332012-03-26 13:27:06 -0700578bool Dbg::IsDebuggerActive() {
Elliott Hughes3bb81562011-10-21 18:52:59 -0700579 return gDebuggerActive;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700580}
581
Elliott Hughesc0f09332012-03-26 13:27:06 -0700582bool Dbg::IsJdwpConfigured() {
Elliott Hughes3bb81562011-10-21 18:52:59 -0700583 return gJdwpConfigured;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700584}
585
586int64_t Dbg::LastDebuggerActivity() {
Elliott Hughesca951522011-12-05 12:01:32 -0800587 return gJdwpState->LastDebuggerActivity();
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700588}
589
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700590void Dbg::UndoDebuggerSuspensions() {
Elliott Hughes234ab152011-10-26 14:02:26 -0700591 Runtime::Current()->GetThreadList()->UndoDebuggerSuspensions();
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700592}
593
Elliott Hughes88d63092013-01-09 09:55:54 -0800594std::string Dbg::GetClassName(JDWP::RefTypeId class_id) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800595 mirror::Object* o = gRegistry->Get<mirror::Object*>(class_id);
Elliott Hughes436e3722012-02-17 20:01:47 -0800596 if (o == NULL) {
597 return "NULL";
598 }
Elliott Hughes64f574f2013-02-20 14:57:12 -0800599 if (o == ObjectRegistry::kInvalidObject) {
Elliott Hughes88d63092013-01-09 09:55:54 -0800600 return StringPrintf("invalid object %p", reinterpret_cast<void*>(class_id));
Elliott Hughes436e3722012-02-17 20:01:47 -0800601 }
602 if (!o->IsClass()) {
Brian Carlstrom7934ac22013-07-26 10:54:15 -0700603 return StringPrintf("non-class %p", o); // This is only used for debugging output anyway.
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -0800604 }
Elliott Hughesc308a5d2012-02-16 17:12:06 -0800605 return DescriptorToName(ClassHelper(o->AsClass()).GetDescriptor());
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700606}
607
Elliott Hughes88d63092013-01-09 09:55:54 -0800608JDWP::JdwpError Dbg::GetClassObject(JDWP::RefTypeId id, JDWP::ObjectId& class_object_id) {
Elliott Hughes436e3722012-02-17 20:01:47 -0800609 JDWP::JdwpError status;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800610 mirror::Class* c = DecodeClass(id, status);
Elliott Hughes436e3722012-02-17 20:01:47 -0800611 if (c == NULL) {
612 return status;
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -0800613 }
Elliott Hughes88d63092013-01-09 09:55:54 -0800614 class_object_id = gRegistry->Add(c);
Elliott Hughes436e3722012-02-17 20:01:47 -0800615 return JDWP::ERR_NONE;
Elliott Hughes86964332012-02-15 19:37:42 -0800616}
617
Elliott Hughes88d63092013-01-09 09:55:54 -0800618JDWP::JdwpError Dbg::GetSuperclass(JDWP::RefTypeId id, JDWP::RefTypeId& superclass_id) {
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -0800619 JDWP::JdwpError status;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800620 mirror::Class* c = DecodeClass(id, status);
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -0800621 if (c == NULL) {
622 return status;
623 }
624 if (c->IsInterface()) {
625 // http://code.google.com/p/android/issues/detail?id=20856
Elliott Hughes88d63092013-01-09 09:55:54 -0800626 superclass_id = 0;
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -0800627 } else {
Elliott Hughes88d63092013-01-09 09:55:54 -0800628 superclass_id = gRegistry->Add(c->GetSuperClass());
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -0800629 }
630 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700631}
632
Elliott Hughes436e3722012-02-17 20:01:47 -0800633JDWP::JdwpError Dbg::GetClassLoader(JDWP::RefTypeId id, JDWP::ExpandBuf* pReply) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800634 mirror::Object* o = gRegistry->Get<mirror::Object*>(id);
Elliott Hughes64f574f2013-02-20 14:57:12 -0800635 if (o == NULL || o == ObjectRegistry::kInvalidObject) {
Elliott Hughes436e3722012-02-17 20:01:47 -0800636 return JDWP::ERR_INVALID_OBJECT;
637 }
638 expandBufAddObjectId(pReply, gRegistry->Add(o->GetClass()->GetClassLoader()));
639 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700640}
641
Elliott Hughes436e3722012-02-17 20:01:47 -0800642JDWP::JdwpError Dbg::GetModifiers(JDWP::RefTypeId id, JDWP::ExpandBuf* pReply) {
643 JDWP::JdwpError status;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800644 mirror::Class* c = DecodeClass(id, status);
Elliott Hughes436e3722012-02-17 20:01:47 -0800645 if (c == NULL) {
646 return status;
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -0800647 }
Elliott Hughes436e3722012-02-17 20:01:47 -0800648
649 uint32_t access_flags = c->GetAccessFlags() & kAccJavaFlagsMask;
650
651 // Set ACC_SUPER; dex files don't contain this flag, but all classes are supposed to have it set.
652 // Class.getModifiers doesn't return it, but JDWP does, so we set it here.
653 access_flags |= kAccSuper;
654
655 expandBufAdd4BE(pReply, access_flags);
656
657 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700658}
659
Elliott Hughesf327e072013-01-09 16:01:26 -0800660JDWP::JdwpError Dbg::GetMonitorInfo(JDWP::ObjectId object_id, JDWP::ExpandBuf* reply)
661 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800662 mirror::Object* o = gRegistry->Get<mirror::Object*>(object_id);
Elliott Hughes64f574f2013-02-20 14:57:12 -0800663 if (o == NULL || o == ObjectRegistry::kInvalidObject) {
Elliott Hughesf327e072013-01-09 16:01:26 -0800664 return JDWP::ERR_INVALID_OBJECT;
665 }
666
667 // Ensure all threads are suspended while we read objects' lock words.
668 Thread* self = Thread::Current();
669 Locks::mutator_lock_->SharedUnlock(self);
670 Locks::mutator_lock_->ExclusiveLock(self);
671
672 MonitorInfo monitor_info(o);
673
674 Locks::mutator_lock_->ExclusiveUnlock(self);
675 Locks::mutator_lock_->SharedLock(self);
676
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700677 if (monitor_info.owner_ != NULL) {
678 expandBufAddObjectId(reply, gRegistry->Add(monitor_info.owner_->GetPeer()));
Elliott Hughesf327e072013-01-09 16:01:26 -0800679 } else {
680 expandBufAddObjectId(reply, gRegistry->Add(NULL));
681 }
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700682 expandBufAdd4BE(reply, monitor_info.entry_count_);
683 expandBufAdd4BE(reply, monitor_info.waiters_.size());
684 for (size_t i = 0; i < monitor_info.waiters_.size(); ++i) {
685 expandBufAddObjectId(reply, gRegistry->Add(monitor_info.waiters_[i]->GetPeer()));
Elliott Hughesf327e072013-01-09 16:01:26 -0800686 }
687 return JDWP::ERR_NONE;
688}
689
Elliott Hughes734b8c62013-01-11 15:32:45 -0800690JDWP::JdwpError Dbg::GetOwnedMonitors(JDWP::ObjectId thread_id,
691 std::vector<JDWP::ObjectId>& monitors,
692 std::vector<uint32_t>& stack_depths)
Elliott Hughes4993bbc2013-01-10 15:41:25 -0800693 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
694 ScopedObjectAccessUnchecked soa(Thread::Current());
695 MutexLock mu(soa.Self(), *Locks::thread_list_lock_);
696 Thread* thread;
697 JDWP::JdwpError error = DecodeThread(soa, thread_id, thread);
698 if (error != JDWP::ERR_NONE) {
699 return error;
700 }
701 if (!IsSuspendedForDebugger(soa, thread)) {
702 return JDWP::ERR_THREAD_NOT_SUSPENDED;
703 }
704
705 struct OwnedMonitorVisitor : public StackVisitor {
Ian Rogers7a22fa62013-01-23 12:16:16 -0800706 OwnedMonitorVisitor(Thread* thread, Context* context)
Elliott Hughes4993bbc2013-01-10 15:41:25 -0800707 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_)
Ian Rogers7a22fa62013-01-23 12:16:16 -0800708 : StackVisitor(thread, context), current_stack_depth(0) {}
Elliott Hughes4993bbc2013-01-10 15:41:25 -0800709
710 // TODO: Enable annotalysis. We know lock is held in constructor, but abstraction confuses
711 // annotalysis.
712 bool VisitFrame() NO_THREAD_SAFETY_ANALYSIS {
713 if (!GetMethod()->IsRuntimeMethod()) {
714 Monitor::VisitLocks(this, AppendOwnedMonitors, this);
Elliott Hughes734b8c62013-01-11 15:32:45 -0800715 ++current_stack_depth;
Elliott Hughes4993bbc2013-01-10 15:41:25 -0800716 }
717 return true;
718 }
719
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800720 static void AppendOwnedMonitors(mirror::Object* owned_monitor, void* arg) {
Ian Rogers7a22fa62013-01-23 12:16:16 -0800721 OwnedMonitorVisitor* visitor = reinterpret_cast<OwnedMonitorVisitor*>(arg);
Elliott Hughes734b8c62013-01-11 15:32:45 -0800722 visitor->monitors.push_back(owned_monitor);
723 visitor->stack_depths.push_back(visitor->current_stack_depth);
Elliott Hughes4993bbc2013-01-10 15:41:25 -0800724 }
725
Elliott Hughes734b8c62013-01-11 15:32:45 -0800726 size_t current_stack_depth;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800727 std::vector<mirror::Object*> monitors;
Elliott Hughes734b8c62013-01-11 15:32:45 -0800728 std::vector<uint32_t> stack_depths;
Elliott Hughes4993bbc2013-01-10 15:41:25 -0800729 };
Ian Rogers7a22fa62013-01-23 12:16:16 -0800730 UniquePtr<Context> context(Context::Create());
731 OwnedMonitorVisitor visitor(thread, context.get());
Elliott Hughes4993bbc2013-01-10 15:41:25 -0800732 visitor.WalkStack();
733
734 for (size_t i = 0; i < visitor.monitors.size(); ++i) {
735 monitors.push_back(gRegistry->Add(visitor.monitors[i]));
Elliott Hughes734b8c62013-01-11 15:32:45 -0800736 stack_depths.push_back(visitor.stack_depths[i]);
Elliott Hughes4993bbc2013-01-10 15:41:25 -0800737 }
738
739 return JDWP::ERR_NONE;
740}
741
Elliott Hughesf9501702013-01-11 11:22:27 -0800742JDWP::JdwpError Dbg::GetContendedMonitor(JDWP::ObjectId thread_id, JDWP::ObjectId& contended_monitor)
743 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
744 ScopedObjectAccessUnchecked soa(Thread::Current());
745 MutexLock mu(soa.Self(), *Locks::thread_list_lock_);
746 Thread* thread;
747 JDWP::JdwpError error = DecodeThread(soa, thread_id, thread);
748 if (error != JDWP::ERR_NONE) {
749 return error;
750 }
751 if (!IsSuspendedForDebugger(soa, thread)) {
752 return JDWP::ERR_THREAD_NOT_SUSPENDED;
753 }
754
755 contended_monitor = gRegistry->Add(Monitor::GetContendedMonitor(thread));
756
757 return JDWP::ERR_NONE;
758}
759
Elliott Hughesec0f83d2013-01-15 16:54:08 -0800760JDWP::JdwpError Dbg::GetInstanceCounts(const std::vector<JDWP::RefTypeId>& class_ids,
761 std::vector<uint64_t>& counts)
762 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800763 std::vector<mirror::Class*> classes;
Elliott Hughesec0f83d2013-01-15 16:54:08 -0800764 counts.clear();
765 for (size_t i = 0; i < class_ids.size(); ++i) {
766 JDWP::JdwpError status;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800767 mirror::Class* c = DecodeClass(class_ids[i], status);
Elliott Hughesec0f83d2013-01-15 16:54:08 -0800768 if (c == NULL) {
769 return status;
770 }
771 classes.push_back(c);
772 counts.push_back(0);
773 }
774
775 Runtime::Current()->GetHeap()->CountInstances(classes, false, &counts[0]);
776 return JDWP::ERR_NONE;
777}
778
Elliott Hughes3b78c942013-01-15 17:35:41 -0800779JDWP::JdwpError Dbg::GetInstances(JDWP::RefTypeId class_id, int32_t max_count, std::vector<JDWP::ObjectId>& instances)
780 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
781 JDWP::JdwpError status;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800782 mirror::Class* c = DecodeClass(class_id, status);
Elliott Hughes3b78c942013-01-15 17:35:41 -0800783 if (c == NULL) {
784 return status;
785 }
786
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800787 std::vector<mirror::Object*> raw_instances;
Elliott Hughes3b78c942013-01-15 17:35:41 -0800788 Runtime::Current()->GetHeap()->GetInstances(c, max_count, raw_instances);
789 for (size_t i = 0; i < raw_instances.size(); ++i) {
790 instances.push_back(gRegistry->Add(raw_instances[i]));
791 }
792 return JDWP::ERR_NONE;
793}
794
Elliott Hughes0cbaff52013-01-16 15:28:01 -0800795JDWP::JdwpError Dbg::GetReferringObjects(JDWP::ObjectId object_id, int32_t max_count,
796 std::vector<JDWP::ObjectId>& referring_objects)
797 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800798 mirror::Object* o = gRegistry->Get<mirror::Object*>(object_id);
Elliott Hughes64f574f2013-02-20 14:57:12 -0800799 if (o == NULL || o == ObjectRegistry::kInvalidObject) {
Elliott Hughes0cbaff52013-01-16 15:28:01 -0800800 return JDWP::ERR_INVALID_OBJECT;
801 }
802
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800803 std::vector<mirror::Object*> raw_instances;
Elliott Hughes0cbaff52013-01-16 15:28:01 -0800804 Runtime::Current()->GetHeap()->GetReferringObjects(o, max_count, raw_instances);
805 for (size_t i = 0; i < raw_instances.size(); ++i) {
806 referring_objects.push_back(gRegistry->Add(raw_instances[i]));
807 }
808 return JDWP::ERR_NONE;
809}
810
Elliott Hughes64f574f2013-02-20 14:57:12 -0800811JDWP::JdwpError Dbg::DisableCollection(JDWP::ObjectId object_id)
812 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
813 gRegistry->DisableCollection(object_id);
814 return JDWP::ERR_NONE;
815}
816
817JDWP::JdwpError Dbg::EnableCollection(JDWP::ObjectId object_id)
818 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
819 gRegistry->EnableCollection(object_id);
820 return JDWP::ERR_NONE;
821}
822
823JDWP::JdwpError Dbg::IsCollected(JDWP::ObjectId object_id, bool& is_collected)
824 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
825 is_collected = gRegistry->IsCollected(object_id);
826 return JDWP::ERR_NONE;
827}
828
829void Dbg::DisposeObject(JDWP::ObjectId object_id, uint32_t reference_count)
830 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
831 gRegistry->DisposeObject(object_id, reference_count);
832}
833
Elliott Hughes88d63092013-01-09 09:55:54 -0800834JDWP::JdwpError Dbg::GetReflectedType(JDWP::RefTypeId class_id, JDWP::ExpandBuf* pReply) {
Elliott Hughes436e3722012-02-17 20:01:47 -0800835 JDWP::JdwpError status;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800836 mirror::Class* c = DecodeClass(class_id, status);
Elliott Hughes436e3722012-02-17 20:01:47 -0800837 if (c == NULL) {
838 return status;
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -0800839 }
Elliott Hughes436e3722012-02-17 20:01:47 -0800840
841 expandBufAdd1(pReply, c->IsInterface() ? JDWP::TT_INTERFACE : JDWP::TT_CLASS);
Elliott Hughes88d63092013-01-09 09:55:54 -0800842 expandBufAddRefTypeId(pReply, class_id);
Elliott Hughes436e3722012-02-17 20:01:47 -0800843 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700844}
845
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -0800846void Dbg::GetClassList(std::vector<JDWP::RefTypeId>& classes) {
Elliott Hughesa2155262011-11-16 16:26:58 -0800847 // Get the complete list of reference classes (i.e. all classes except
848 // the primitive types).
849 // Returns a newly-allocated buffer full of RefTypeId values.
850 struct ClassListCreator {
Elliott Hughesba8eee12012-01-24 20:25:24 -0800851 explicit ClassListCreator(std::vector<JDWP::RefTypeId>& classes) : classes(classes) {
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -0800852 }
853
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800854 static bool Visit(mirror::Class* c, void* arg) {
Elliott Hughesa2155262011-11-16 16:26:58 -0800855 return reinterpret_cast<ClassListCreator*>(arg)->Visit(c);
856 }
857
Elliott Hughes64f574f2013-02-20 14:57:12 -0800858 // TODO: Enable annotalysis. We know lock is held in constructor, but abstraction confuses
859 // annotalysis.
860 bool Visit(mirror::Class* c) NO_THREAD_SAFETY_ANALYSIS {
Elliott Hughesa2155262011-11-16 16:26:58 -0800861 if (!c->IsPrimitive()) {
Elliott Hughes64f574f2013-02-20 14:57:12 -0800862 classes.push_back(gRegistry->AddRefType(c));
Elliott Hughesa2155262011-11-16 16:26:58 -0800863 }
864 return true;
865 }
866
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -0800867 std::vector<JDWP::RefTypeId>& classes;
Elliott Hughesa2155262011-11-16 16:26:58 -0800868 };
869
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -0800870 ClassListCreator clc(classes);
Elliott Hughesa2155262011-11-16 16:26:58 -0800871 Runtime::Current()->GetClassLinker()->VisitClasses(ClassListCreator::Visit, &clc);
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700872}
873
Elliott Hughes88d63092013-01-09 09:55:54 -0800874JDWP::JdwpError Dbg::GetClassInfo(JDWP::RefTypeId class_id, JDWP::JdwpTypeTag* pTypeTag, uint32_t* pStatus, std::string* pDescriptor) {
Elliott Hughes436e3722012-02-17 20:01:47 -0800875 JDWP::JdwpError status;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800876 mirror::Class* c = DecodeClass(class_id, status);
Elliott Hughes436e3722012-02-17 20:01:47 -0800877 if (c == NULL) {
878 return status;
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -0800879 }
880
Elliott Hughesa2155262011-11-16 16:26:58 -0800881 if (c->IsArrayClass()) {
882 *pStatus = JDWP::CS_VERIFIED | JDWP::CS_PREPARED;
883 *pTypeTag = JDWP::TT_ARRAY;
884 } else {
885 if (c->IsErroneous()) {
886 *pStatus = JDWP::CS_ERROR;
887 } else {
888 *pStatus = JDWP::CS_VERIFIED | JDWP::CS_PREPARED | JDWP::CS_INITIALIZED;
889 }
890 *pTypeTag = c->IsInterface() ? JDWP::TT_INTERFACE : JDWP::TT_CLASS;
891 }
892
893 if (pDescriptor != NULL) {
Ian Rogersdfb325e2013-10-30 01:00:44 -0700894 *pDescriptor = ClassHelper(c).GetDescriptor();
Elliott Hughesa2155262011-11-16 16:26:58 -0800895 }
Elliott Hughes436e3722012-02-17 20:01:47 -0800896 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700897}
898
Elliott Hughesc3b77c72011-12-15 20:56:48 -0800899void Dbg::FindLoadedClassBySignature(const char* descriptor, std::vector<JDWP::RefTypeId>& ids) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800900 std::vector<mirror::Class*> classes;
Elliott Hughes6fa602d2011-12-02 17:54:25 -0800901 Runtime::Current()->GetClassLinker()->LookupClasses(descriptor, classes);
902 ids.clear();
903 for (size_t i = 0; i < classes.size(); ++i) {
904 ids.push_back(gRegistry->Add(classes[i]));
905 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700906}
907
Elliott Hughes64f574f2013-02-20 14:57:12 -0800908JDWP::JdwpError Dbg::GetReferenceType(JDWP::ObjectId object_id, JDWP::ExpandBuf* pReply)
909 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800910 mirror::Object* o = gRegistry->Get<mirror::Object*>(object_id);
Elliott Hughes64f574f2013-02-20 14:57:12 -0800911 if (o == NULL || o == ObjectRegistry::kInvalidObject) {
Elliott Hughes2435a572012-02-17 16:07:41 -0800912 return JDWP::ERR_INVALID_OBJECT;
Elliott Hughes499c5132011-11-17 14:55:11 -0800913 }
Elliott Hughes2435a572012-02-17 16:07:41 -0800914
915 JDWP::JdwpTypeTag type_tag;
916 if (o->GetClass()->IsArrayClass()) {
917 type_tag = JDWP::TT_ARRAY;
918 } else if (o->GetClass()->IsInterface()) {
919 type_tag = JDWP::TT_INTERFACE;
920 } else {
921 type_tag = JDWP::TT_CLASS;
922 }
Elliott Hughes64f574f2013-02-20 14:57:12 -0800923 JDWP::RefTypeId type_id = gRegistry->AddRefType(o->GetClass());
Elliott Hughes2435a572012-02-17 16:07:41 -0800924
925 expandBufAdd1(pReply, type_tag);
926 expandBufAddRefTypeId(pReply, type_id);
927
928 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700929}
930
Ian Rogersfc0e94b2013-09-23 23:51:32 -0700931JDWP::JdwpError Dbg::GetSignature(JDWP::RefTypeId class_id, std::string* signature) {
Elliott Hughes1fe7afb2012-02-13 17:23:03 -0800932 JDWP::JdwpError status;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800933 mirror::Class* c = DecodeClass(class_id, status);
Elliott Hughes1fe7afb2012-02-13 17:23:03 -0800934 if (c == NULL) {
935 return status;
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -0800936 }
Ian Rogersdfb325e2013-10-30 01:00:44 -0700937 *signature = ClassHelper(c).GetDescriptor();
Elliott Hughes1fe7afb2012-02-13 17:23:03 -0800938 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700939}
940
Elliott Hughes88d63092013-01-09 09:55:54 -0800941JDWP::JdwpError Dbg::GetSourceFile(JDWP::RefTypeId class_id, std::string& result) {
Elliott Hughes436e3722012-02-17 20:01:47 -0800942 JDWP::JdwpError status;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800943 mirror::Class* c = DecodeClass(class_id, status);
Elliott Hughes436e3722012-02-17 20:01:47 -0800944 if (c == NULL) {
945 return status;
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -0800946 }
Elliott Hughes436e3722012-02-17 20:01:47 -0800947 result = ClassHelper(c).GetSourceFile();
948 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700949}
950
Elliott Hughes88d63092013-01-09 09:55:54 -0800951JDWP::JdwpError Dbg::GetObjectTag(JDWP::ObjectId object_id, uint8_t& tag) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800952 mirror::Object* o = gRegistry->Get<mirror::Object*>(object_id);
Elliott Hughes64f574f2013-02-20 14:57:12 -0800953 if (o == ObjectRegistry::kInvalidObject) {
Elliott Hughes546b9862012-06-20 16:06:13 -0700954 return JDWP::ERR_INVALID_OBJECT;
955 }
956 tag = TagFromObject(o);
957 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700958}
959
Elliott Hughesaed4be92011-12-02 16:16:23 -0800960size_t Dbg::GetTagWidth(JDWP::JdwpTag tag) {
Elliott Hughesdbb40792011-11-18 17:05:22 -0800961 switch (tag) {
962 case JDWP::JT_VOID:
963 return 0;
964 case JDWP::JT_BYTE:
965 case JDWP::JT_BOOLEAN:
966 return 1;
967 case JDWP::JT_CHAR:
968 case JDWP::JT_SHORT:
969 return 2;
970 case JDWP::JT_FLOAT:
971 case JDWP::JT_INT:
972 return 4;
973 case JDWP::JT_ARRAY:
974 case JDWP::JT_OBJECT:
975 case JDWP::JT_STRING:
976 case JDWP::JT_THREAD:
977 case JDWP::JT_THREAD_GROUP:
978 case JDWP::JT_CLASS_LOADER:
979 case JDWP::JT_CLASS_OBJECT:
980 return sizeof(JDWP::ObjectId);
981 case JDWP::JT_DOUBLE:
982 case JDWP::JT_LONG:
983 return 8;
984 default:
Elliott Hughes3d30d9b2011-12-07 17:35:48 -0800985 LOG(FATAL) << "Unknown tag " << tag;
Elliott Hughesdbb40792011-11-18 17:05:22 -0800986 return -1;
987 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700988}
989
Elliott Hughes88d63092013-01-09 09:55:54 -0800990JDWP::JdwpError Dbg::GetArrayLength(JDWP::ObjectId array_id, int& length) {
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -0800991 JDWP::JdwpError status;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800992 mirror::Array* a = DecodeArray(array_id, status);
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -0800993 if (a == NULL) {
994 return status;
Elliott Hughes24437992011-11-30 14:49:33 -0800995 }
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -0800996 length = a->GetLength();
997 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700998}
999
Elliott Hughes88d63092013-01-09 09:55:54 -08001000JDWP::JdwpError Dbg::OutputArray(JDWP::ObjectId array_id, int offset, int count, JDWP::ExpandBuf* pReply) {
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -08001001 JDWP::JdwpError status;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001002 mirror::Array* a = DecodeArray(array_id, status);
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -08001003 if (a == NULL) {
1004 return status;
1005 }
Elliott Hughes24437992011-11-30 14:49:33 -08001006
1007 if (offset < 0 || count < 0 || offset > a->GetLength() || a->GetLength() - offset < count) {
1008 LOG(WARNING) << __FUNCTION__ << " access out of bounds: offset=" << offset << "; count=" << count;
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -08001009 return JDWP::ERR_INVALID_LENGTH;
Elliott Hughes24437992011-11-30 14:49:33 -08001010 }
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001011 std::string descriptor(ClassHelper(a->GetClass()).GetDescriptor());
Elliott Hughes24437992011-11-30 14:49:33 -08001012 JDWP::JdwpTag tag = BasicTagFromDescriptor(descriptor.c_str() + 1);
1013
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -08001014 expandBufAdd1(pReply, tag);
1015 expandBufAdd4BE(pReply, count);
1016
Elliott Hughes24437992011-11-30 14:49:33 -08001017 if (IsPrimitiveTag(tag)) {
1018 size_t width = GetTagWidth(tag);
Elliott Hughes24437992011-11-30 14:49:33 -08001019 uint8_t* dst = expandBufAddSpace(pReply, count * width);
1020 if (width == 8) {
Ian Rogersa15e67d2012-02-28 13:51:55 -08001021 const uint64_t* src8 = reinterpret_cast<uint64_t*>(a->GetRawData(sizeof(uint64_t)));
Elliott Hughes24437992011-11-30 14:49:33 -08001022 for (int i = 0; i < count; ++i) JDWP::Write8BE(&dst, src8[offset + i]);
1023 } else if (width == 4) {
Ian Rogersa15e67d2012-02-28 13:51:55 -08001024 const uint32_t* src4 = reinterpret_cast<uint32_t*>(a->GetRawData(sizeof(uint32_t)));
Elliott Hughes24437992011-11-30 14:49:33 -08001025 for (int i = 0; i < count; ++i) JDWP::Write4BE(&dst, src4[offset + i]);
1026 } else if (width == 2) {
Ian Rogersa15e67d2012-02-28 13:51:55 -08001027 const uint16_t* src2 = reinterpret_cast<uint16_t*>(a->GetRawData(sizeof(uint16_t)));
Elliott Hughes24437992011-11-30 14:49:33 -08001028 for (int i = 0; i < count; ++i) JDWP::Write2BE(&dst, src2[offset + i]);
1029 } else {
Ian Rogersa15e67d2012-02-28 13:51:55 -08001030 const uint8_t* src = reinterpret_cast<uint8_t*>(a->GetRawData(sizeof(uint8_t)));
Elliott Hughes24437992011-11-30 14:49:33 -08001031 memcpy(dst, &src[offset * width], count * width);
1032 }
1033 } else {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001034 mirror::ObjectArray<mirror::Object>* oa = a->AsObjectArray<mirror::Object>();
Elliott Hughes24437992011-11-30 14:49:33 -08001035 for (int i = 0; i < count; ++i) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001036 mirror::Object* element = oa->Get(offset + i);
Elliott Hughes24437992011-11-30 14:49:33 -08001037 JDWP::JdwpTag specific_tag = (element != NULL) ? TagFromObject(element) : tag;
1038 expandBufAdd1(pReply, specific_tag);
1039 expandBufAddObjectId(pReply, gRegistry->Add(element));
1040 }
1041 }
1042
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -08001043 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001044}
1045
Elliott Hughes4b9702c2013-02-20 18:13:24 -08001046template <typename T> void CopyArrayData(mirror::Array* a, JDWP::Request& src, int offset, int count) {
1047 DCHECK(a->GetClass()->IsPrimitiveArray());
1048
1049 T* dst = &(reinterpret_cast<T*>(a->GetRawData(sizeof(T)))[offset * sizeof(T)]);
1050 for (int i = 0; i < count; ++i) {
1051 *dst++ = src.ReadValue(sizeof(T));
1052 }
1053}
1054
Elliott Hughes88d63092013-01-09 09:55:54 -08001055JDWP::JdwpError Dbg::SetArrayElements(JDWP::ObjectId array_id, int offset, int count,
Elliott Hughes4b9702c2013-02-20 18:13:24 -08001056 JDWP::Request& request)
Ian Rogersb726dcb2012-09-05 08:57:23 -07001057 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -08001058 JDWP::JdwpError status;
Elliott Hughes4b9702c2013-02-20 18:13:24 -08001059 mirror::Array* dst = DecodeArray(array_id, status);
1060 if (dst == NULL) {
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -08001061 return status;
1062 }
Elliott Hughesf03b8f62011-12-02 14:26:25 -08001063
Elliott Hughes4b9702c2013-02-20 18:13:24 -08001064 if (offset < 0 || count < 0 || offset > dst->GetLength() || dst->GetLength() - offset < count) {
Elliott Hughesf03b8f62011-12-02 14:26:25 -08001065 LOG(WARNING) << __FUNCTION__ << " access out of bounds: offset=" << offset << "; count=" << count;
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -08001066 return JDWP::ERR_INVALID_LENGTH;
Elliott Hughesf03b8f62011-12-02 14:26:25 -08001067 }
Ian Rogersfc0e94b2013-09-23 23:51:32 -07001068 const char* descriptor = ClassHelper(dst->GetClass()).GetDescriptor();
1069 JDWP::JdwpTag tag = BasicTagFromDescriptor(descriptor + 1);
Elliott Hughesf03b8f62011-12-02 14:26:25 -08001070
1071 if (IsPrimitiveTag(tag)) {
1072 size_t width = GetTagWidth(tag);
Elliott Hughesf03b8f62011-12-02 14:26:25 -08001073 if (width == 8) {
Elliott Hughes4b9702c2013-02-20 18:13:24 -08001074 CopyArrayData<uint64_t>(dst, request, offset, count);
Elliott Hughesf03b8f62011-12-02 14:26:25 -08001075 } else if (width == 4) {
Elliott Hughes4b9702c2013-02-20 18:13:24 -08001076 CopyArrayData<uint32_t>(dst, request, offset, count);
Elliott Hughesf03b8f62011-12-02 14:26:25 -08001077 } else if (width == 2) {
Elliott Hughes4b9702c2013-02-20 18:13:24 -08001078 CopyArrayData<uint16_t>(dst, request, offset, count);
Elliott Hughesf03b8f62011-12-02 14:26:25 -08001079 } else {
Elliott Hughes4b9702c2013-02-20 18:13:24 -08001080 CopyArrayData<uint8_t>(dst, request, offset, count);
Elliott Hughesf03b8f62011-12-02 14:26:25 -08001081 }
1082 } else {
Elliott Hughes4b9702c2013-02-20 18:13:24 -08001083 mirror::ObjectArray<mirror::Object>* oa = dst->AsObjectArray<mirror::Object>();
Elliott Hughesf03b8f62011-12-02 14:26:25 -08001084 for (int i = 0; i < count; ++i) {
Elliott Hughes4b9702c2013-02-20 18:13:24 -08001085 JDWP::ObjectId id = request.ReadObjectId();
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001086 mirror::Object* o = gRegistry->Get<mirror::Object*>(id);
Elliott Hughes64f574f2013-02-20 14:57:12 -08001087 if (o == ObjectRegistry::kInvalidObject) {
Elliott Hughes436e3722012-02-17 20:01:47 -08001088 return JDWP::ERR_INVALID_OBJECT;
1089 }
1090 oa->Set(offset + i, o);
Elliott Hughesf03b8f62011-12-02 14:26:25 -08001091 }
1092 }
1093
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -08001094 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001095}
1096
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -08001097JDWP::ObjectId Dbg::CreateString(const std::string& str) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001098 return gRegistry->Add(mirror::String::AllocFromModifiedUtf8(Thread::Current(), str.c_str()));
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001099}
1100
Elliott Hughes88d63092013-01-09 09:55:54 -08001101JDWP::JdwpError Dbg::CreateObject(JDWP::RefTypeId class_id, JDWP::ObjectId& new_object) {
Elliott Hughes436e3722012-02-17 20:01:47 -08001102 JDWP::JdwpError status;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001103 mirror::Class* c = DecodeClass(class_id, status);
Elliott Hughes436e3722012-02-17 20:01:47 -08001104 if (c == NULL) {
1105 return status;
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -08001106 }
Ian Rogers50b35e22012-10-04 10:09:15 -07001107 new_object = gRegistry->Add(c->AllocObject(Thread::Current()));
Elliott Hughes436e3722012-02-17 20:01:47 -08001108 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001109}
1110
Elliott Hughesbf13d362011-12-08 15:51:37 -08001111/*
1112 * Used by Eclipse's "Display" view to evaluate "new byte[5]" to get "(byte[]) [0, 0, 0, 0, 0]".
1113 */
Elliott Hughes88d63092013-01-09 09:55:54 -08001114JDWP::JdwpError Dbg::CreateArrayObject(JDWP::RefTypeId array_class_id, uint32_t length,
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001115 JDWP::ObjectId& new_array) {
Elliott Hughes436e3722012-02-17 20:01:47 -08001116 JDWP::JdwpError status;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001117 mirror::Class* c = DecodeClass(array_class_id, status);
Elliott Hughes436e3722012-02-17 20:01:47 -08001118 if (c == NULL) {
1119 return status;
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -08001120 }
Mathieu Chartier590fee92013-09-13 13:46:47 -07001121 new_array = gRegistry->Add(
1122 mirror::Array::Alloc<kMovingCollector, true>(Thread::Current(), c, length));
Elliott Hughes436e3722012-02-17 20:01:47 -08001123 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001124}
1125
Elliott Hughes88d63092013-01-09 09:55:54 -08001126bool Dbg::MatchType(JDWP::RefTypeId instance_class_id, JDWP::RefTypeId class_id) {
Elliott Hughes436e3722012-02-17 20:01:47 -08001127 JDWP::JdwpError status;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001128 mirror::Class* c1 = DecodeClass(instance_class_id, status);
Elliott Hughesa656a0f2012-02-21 18:03:44 -08001129 CHECK(c1 != NULL);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001130 mirror::Class* c2 = DecodeClass(class_id, status);
Elliott Hughesa656a0f2012-02-21 18:03:44 -08001131 CHECK(c2 != NULL);
1132 return c1->IsAssignableFrom(c2);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001133}
1134
Brian Carlstromea46f952013-07-30 01:26:50 -07001135static JDWP::FieldId ToFieldId(const mirror::ArtField* f)
Ian Rogersb726dcb2012-09-05 08:57:23 -07001136 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Mathieu Chartier590fee92013-09-13 13:46:47 -07001137 CHECK(!kMovingFields);
Elliott Hughes03181a82011-11-17 17:22:21 -08001138 return static_cast<JDWP::FieldId>(reinterpret_cast<uintptr_t>(f));
Elliott Hughes03181a82011-11-17 17:22:21 -08001139}
1140
Brian Carlstromea46f952013-07-30 01:26:50 -07001141static JDWP::MethodId ToMethodId(const mirror::ArtMethod* m)
Ian Rogersb726dcb2012-09-05 08:57:23 -07001142 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Mathieu Chartier590fee92013-09-13 13:46:47 -07001143 CHECK(!kMovingMethods);
Elliott Hughes03181a82011-11-17 17:22:21 -08001144 return static_cast<JDWP::MethodId>(reinterpret_cast<uintptr_t>(m));
Elliott Hughes03181a82011-11-17 17:22:21 -08001145}
1146
Brian Carlstromea46f952013-07-30 01:26:50 -07001147static mirror::ArtField* FromFieldId(JDWP::FieldId fid)
Ian Rogersb726dcb2012-09-05 08:57:23 -07001148 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Mathieu Chartier590fee92013-09-13 13:46:47 -07001149 CHECK(!kMovingFields);
Brian Carlstromea46f952013-07-30 01:26:50 -07001150 return reinterpret_cast<mirror::ArtField*>(static_cast<uintptr_t>(fid));
Elliott Hughesaed4be92011-12-02 16:16:23 -08001151}
1152
Brian Carlstromea46f952013-07-30 01:26:50 -07001153static mirror::ArtMethod* FromMethodId(JDWP::MethodId mid)
Ian Rogersb726dcb2012-09-05 08:57:23 -07001154 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Mathieu Chartier590fee92013-09-13 13:46:47 -07001155 CHECK(!kMovingMethods);
Brian Carlstromea46f952013-07-30 01:26:50 -07001156 return reinterpret_cast<mirror::ArtMethod*>(static_cast<uintptr_t>(mid));
Elliott Hughes03181a82011-11-17 17:22:21 -08001157}
1158
Brian Carlstromea46f952013-07-30 01:26:50 -07001159static void SetLocation(JDWP::JdwpLocation& location, mirror::ArtMethod* m, uint32_t dex_pc)
Ian Rogersb726dcb2012-09-05 08:57:23 -07001160 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08001161 if (m == NULL) {
1162 memset(&location, 0, sizeof(location));
1163 } else {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001164 mirror::Class* c = m->GetDeclaringClass();
Elliott Hughes74847412012-06-20 18:10:21 -07001165 location.type_tag = c->IsInterface() ? JDWP::TT_INTERFACE : JDWP::TT_CLASS;
1166 location.class_id = gRegistry->Add(c);
1167 location.method_id = ToMethodId(m);
Ian Rogers0399dde2012-06-06 17:09:28 -07001168 location.dex_pc = dex_pc;
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08001169 }
Elliott Hughesd07986f2011-12-06 18:27:45 -08001170}
1171
Elliott Hughesa96836a2013-01-17 12:27:49 -08001172std::string Dbg::GetMethodName(JDWP::MethodId method_id)
Ian Rogersb726dcb2012-09-05 08:57:23 -07001173 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Brian Carlstromea46f952013-07-30 01:26:50 -07001174 mirror::ArtMethod* m = FromMethodId(method_id);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001175 return MethodHelper(m).GetName();
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001176}
1177
Elliott Hughesa96836a2013-01-17 12:27:49 -08001178std::string Dbg::GetFieldName(JDWP::FieldId field_id)
1179 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Brian Carlstromea46f952013-07-30 01:26:50 -07001180 mirror::ArtField* f = FromFieldId(field_id);
Elliott Hughesa96836a2013-01-17 12:27:49 -08001181 return FieldHelper(f).GetName();
1182}
1183
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001184/*
1185 * Augment the access flags for synthetic methods and fields by setting
1186 * the (as described by the spec) "0xf0000000 bit". Also, strip out any
1187 * flags not specified by the Java programming language.
1188 */
1189static uint32_t MangleAccessFlags(uint32_t accessFlags) {
1190 accessFlags &= kAccJavaFlagsMask;
1191 if ((accessFlags & kAccSynthetic) != 0) {
1192 accessFlags |= 0xf0000000;
1193 }
1194 return accessFlags;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001195}
1196
Elliott Hughesdbb40792011-11-18 17:05:22 -08001197/*
Jeff Haob7cefc72013-11-14 14:51:09 -08001198 * Circularly shifts registers so that arguments come first. Debuggers
1199 * expect slots to begin with arguments, but dex code places them at
1200 * the end.
Elliott Hughesdbb40792011-11-18 17:05:22 -08001201 */
Jeff Haob7cefc72013-11-14 14:51:09 -08001202static uint16_t MangleSlot(uint16_t slot, mirror::ArtMethod* m)
1203 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
1204 const DexFile::CodeItem* code_item = MethodHelper(m).GetCodeItem();
1205 uint16_t ins_size = code_item->ins_size_;
1206 uint16_t locals_size = code_item->registers_size_ - ins_size;
1207 if (slot >= locals_size) {
1208 return slot - locals_size;
1209 } else {
1210 return slot + ins_size;
Elliott Hughesdbb40792011-11-18 17:05:22 -08001211 }
Elliott Hughesdbb40792011-11-18 17:05:22 -08001212}
1213
Jeff Haob7cefc72013-11-14 14:51:09 -08001214/*
1215 * Circularly shifts registers so that arguments come last. Reverts
1216 * slots to dex style argument placement.
1217 */
Brian Carlstromea46f952013-07-30 01:26:50 -07001218static uint16_t DemangleSlot(uint16_t slot, mirror::ArtMethod* m)
Ian Rogersb726dcb2012-09-05 08:57:23 -07001219 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Jeff Haob7cefc72013-11-14 14:51:09 -08001220 const DexFile::CodeItem* code_item = MethodHelper(m).GetCodeItem();
1221 uint16_t ins_size = code_item->ins_size_;
1222 uint16_t locals_size = code_item->registers_size_ - ins_size;
1223 if (slot < ins_size) {
1224 return slot + locals_size;
1225 } else {
1226 return slot - ins_size;
Elliott Hughesdbb40792011-11-18 17:05:22 -08001227 }
Elliott Hughesdbb40792011-11-18 17:05:22 -08001228}
1229
Elliott Hughes88d63092013-01-09 09:55:54 -08001230JDWP::JdwpError Dbg::OutputDeclaredFields(JDWP::RefTypeId class_id, bool with_generic, JDWP::ExpandBuf* pReply) {
Elliott Hughes436e3722012-02-17 20:01:47 -08001231 JDWP::JdwpError status;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001232 mirror::Class* c = DecodeClass(class_id, status);
Elliott Hughes436e3722012-02-17 20:01:47 -08001233 if (c == NULL) {
1234 return status;
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -08001235 }
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001236
1237 size_t instance_field_count = c->NumInstanceFields();
1238 size_t static_field_count = c->NumStaticFields();
1239
1240 expandBufAdd4BE(pReply, instance_field_count + static_field_count);
1241
1242 for (size_t i = 0; i < instance_field_count + static_field_count; ++i) {
Brian Carlstromea46f952013-07-30 01:26:50 -07001243 mirror::ArtField* f = (i < instance_field_count) ? c->GetInstanceField(i) : c->GetStaticField(i - instance_field_count);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001244 FieldHelper fh(f);
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001245 expandBufAddFieldId(pReply, ToFieldId(f));
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001246 expandBufAddUtf8String(pReply, fh.GetName());
1247 expandBufAddUtf8String(pReply, fh.GetTypeDescriptor());
Elliott Hughesc5b734a2011-12-01 17:20:58 -08001248 if (with_generic) {
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001249 static const char genericSignature[1] = "";
1250 expandBufAddUtf8String(pReply, genericSignature);
1251 }
1252 expandBufAdd4BE(pReply, MangleAccessFlags(f->GetAccessFlags()));
1253 }
Elliott Hughes436e3722012-02-17 20:01:47 -08001254 return JDWP::ERR_NONE;
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001255}
1256
Elliott Hughes88d63092013-01-09 09:55:54 -08001257JDWP::JdwpError Dbg::OutputDeclaredMethods(JDWP::RefTypeId class_id, bool with_generic,
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001258 JDWP::ExpandBuf* pReply) {
Elliott Hughes436e3722012-02-17 20:01:47 -08001259 JDWP::JdwpError status;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001260 mirror::Class* c = DecodeClass(class_id, status);
Elliott Hughes436e3722012-02-17 20:01:47 -08001261 if (c == NULL) {
1262 return status;
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -08001263 }
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001264
1265 size_t direct_method_count = c->NumDirectMethods();
1266 size_t virtual_method_count = c->NumVirtualMethods();
1267
1268 expandBufAdd4BE(pReply, direct_method_count + virtual_method_count);
1269
1270 for (size_t i = 0; i < direct_method_count + virtual_method_count; ++i) {
Brian Carlstromea46f952013-07-30 01:26:50 -07001271 mirror::ArtMethod* m = (i < direct_method_count) ? c->GetDirectMethod(i) : c->GetVirtualMethod(i - direct_method_count);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001272 MethodHelper mh(m);
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001273 expandBufAddMethodId(pReply, ToMethodId(m));
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001274 expandBufAddUtf8String(pReply, mh.GetName());
Ian Rogersd91d6d62013-09-25 20:26:14 -07001275 expandBufAddUtf8String(pReply, mh.GetSignature().ToString());
Elliott Hughesc5b734a2011-12-01 17:20:58 -08001276 if (with_generic) {
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001277 static const char genericSignature[1] = "";
1278 expandBufAddUtf8String(pReply, genericSignature);
1279 }
1280 expandBufAdd4BE(pReply, MangleAccessFlags(m->GetAccessFlags()));
1281 }
Elliott Hughes436e3722012-02-17 20:01:47 -08001282 return JDWP::ERR_NONE;
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001283}
1284
Elliott Hughes88d63092013-01-09 09:55:54 -08001285JDWP::JdwpError Dbg::OutputDeclaredInterfaces(JDWP::RefTypeId class_id, JDWP::ExpandBuf* pReply) {
Elliott Hughes436e3722012-02-17 20:01:47 -08001286 JDWP::JdwpError status;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001287 mirror::Class* c = DecodeClass(class_id, status);
Elliott Hughes436e3722012-02-17 20:01:47 -08001288 if (c == NULL) {
1289 return status;
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -08001290 }
Elliott Hughes436e3722012-02-17 20:01:47 -08001291
1292 ClassHelper kh(c);
Ian Rogersd24e2642012-06-06 21:21:43 -07001293 size_t interface_count = kh.NumDirectInterfaces();
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001294 expandBufAdd4BE(pReply, interface_count);
1295 for (size_t i = 0; i < interface_count; ++i) {
Elliott Hughes64f574f2013-02-20 14:57:12 -08001296 expandBufAddRefTypeId(pReply, gRegistry->AddRefType(kh.GetDirectInterface(i)));
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001297 }
Elliott Hughes436e3722012-02-17 20:01:47 -08001298 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001299}
1300
Elliott Hughes88d63092013-01-09 09:55:54 -08001301void Dbg::OutputLineTable(JDWP::RefTypeId, JDWP::MethodId method_id, JDWP::ExpandBuf* pReply)
Ian Rogersb726dcb2012-09-05 08:57:23 -07001302 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Elliott Hughes03181a82011-11-17 17:22:21 -08001303 struct DebugCallbackContext {
1304 int numItems;
1305 JDWP::ExpandBuf* pReply;
1306
Elliott Hughes2435a572012-02-17 16:07:41 -08001307 static bool Callback(void* context, uint32_t address, uint32_t line_number) {
Elliott Hughes03181a82011-11-17 17:22:21 -08001308 DebugCallbackContext* pContext = reinterpret_cast<DebugCallbackContext*>(context);
1309 expandBufAdd8BE(pContext->pReply, address);
Elliott Hughes2435a572012-02-17 16:07:41 -08001310 expandBufAdd4BE(pContext->pReply, line_number);
Elliott Hughes03181a82011-11-17 17:22:21 -08001311 pContext->numItems++;
Sebastien Hertzf2910ee2013-10-19 16:39:24 +02001312 return false;
Elliott Hughes03181a82011-11-17 17:22:21 -08001313 }
1314 };
Brian Carlstromea46f952013-07-30 01:26:50 -07001315 mirror::ArtMethod* m = FromMethodId(method_id);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001316 MethodHelper mh(m);
Elliott Hughes03181a82011-11-17 17:22:21 -08001317 uint64_t start, end;
1318 if (m->IsNative()) {
1319 start = -1;
1320 end = -1;
1321 } else {
1322 start = 0;
jeffhao14f0db92012-12-14 17:50:42 -08001323 // Return the index of the last instruction
1324 end = mh.GetCodeItem()->insns_size_in_code_units_ - 1;
Elliott Hughes03181a82011-11-17 17:22:21 -08001325 }
1326
1327 expandBufAdd8BE(pReply, start);
1328 expandBufAdd8BE(pReply, end);
1329
1330 // Add numLines later
1331 size_t numLinesOffset = expandBufGetLength(pReply);
1332 expandBufAdd4BE(pReply, 0);
1333
1334 DebugCallbackContext context;
1335 context.numItems = 0;
1336 context.pReply = pReply;
1337
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001338 mh.GetDexFile().DecodeDebugInfo(mh.GetCodeItem(), m->IsStatic(), m->GetDexMethodIndex(),
1339 DebugCallbackContext::Callback, NULL, &context);
Elliott Hughes03181a82011-11-17 17:22:21 -08001340
1341 JDWP::Set4BE(expandBufGetBuffer(pReply) + numLinesOffset, context.numItems);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001342}
1343
Elliott Hughes88d63092013-01-09 09:55:54 -08001344void Dbg::OutputVariableTable(JDWP::RefTypeId, JDWP::MethodId method_id, bool with_generic, JDWP::ExpandBuf* pReply) {
Elliott Hughesdbb40792011-11-18 17:05:22 -08001345 struct DebugCallbackContext {
Jeff Haob7cefc72013-11-14 14:51:09 -08001346 mirror::ArtMethod* method;
Elliott Hughesdbb40792011-11-18 17:05:22 -08001347 JDWP::ExpandBuf* pReply;
Elliott Hughesc5b734a2011-12-01 17:20:58 -08001348 size_t variable_count;
1349 bool with_generic;
Elliott Hughesdbb40792011-11-18 17:05:22 -08001350
Jeff Haob7cefc72013-11-14 14:51:09 -08001351 static void Callback(void* context, uint16_t slot, uint32_t startAddress, uint32_t endAddress, const char* name, const char* descriptor, const char* signature)
1352 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Elliott Hughesdbb40792011-11-18 17:05:22 -08001353 DebugCallbackContext* pContext = reinterpret_cast<DebugCallbackContext*>(context);
1354
Jeff Haob7cefc72013-11-14 14:51:09 -08001355 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, pContext->method));
Elliott Hughesdbb40792011-11-18 17:05:22 -08001356
Jeff Haob7cefc72013-11-14 14:51:09 -08001357 slot = MangleSlot(slot, pContext->method);
Elliott Hughes68fdbd02011-11-29 19:22:47 -08001358
Elliott Hughesdbb40792011-11-18 17:05:22 -08001359 expandBufAdd8BE(pContext->pReply, startAddress);
1360 expandBufAddUtf8String(pContext->pReply, name);
1361 expandBufAddUtf8String(pContext->pReply, descriptor);
Elliott Hughesc5b734a2011-12-01 17:20:58 -08001362 if (pContext->with_generic) {
Elliott Hughesdbb40792011-11-18 17:05:22 -08001363 expandBufAddUtf8String(pContext->pReply, signature);
1364 }
1365 expandBufAdd4BE(pContext->pReply, endAddress - startAddress);
1366 expandBufAdd4BE(pContext->pReply, slot);
1367
Elliott Hughesc5b734a2011-12-01 17:20:58 -08001368 ++pContext->variable_count;
Elliott Hughesdbb40792011-11-18 17:05:22 -08001369 }
1370 };
Brian Carlstromea46f952013-07-30 01:26:50 -07001371 mirror::ArtMethod* m = FromMethodId(method_id);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001372 MethodHelper mh(m);
1373 const DexFile::CodeItem* code_item = mh.GetCodeItem();
Elliott Hughesdbb40792011-11-18 17:05:22 -08001374
Elliott Hughesc5b734a2011-12-01 17:20:58 -08001375 // arg_count considers doubles and longs to take 2 units.
1376 // variable_count considers everything to take 1 unit.
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001377 std::string shorty(mh.GetShorty());
Brian Carlstromea46f952013-07-30 01:26:50 -07001378 expandBufAdd4BE(pReply, mirror::ArtMethod::NumArgRegisters(shorty));
Elliott Hughesdbb40792011-11-18 17:05:22 -08001379
Elliott Hughesc5b734a2011-12-01 17:20:58 -08001380 // We don't know the total number of variables yet, so leave a blank and update it later.
1381 size_t variable_count_offset = expandBufGetLength(pReply);
Elliott Hughesdbb40792011-11-18 17:05:22 -08001382 expandBufAdd4BE(pReply, 0);
1383
1384 DebugCallbackContext context;
Jeff Haob7cefc72013-11-14 14:51:09 -08001385 context.method = m;
Elliott Hughesdbb40792011-11-18 17:05:22 -08001386 context.pReply = pReply;
Elliott Hughesc5b734a2011-12-01 17:20:58 -08001387 context.variable_count = 0;
1388 context.with_generic = with_generic;
Elliott Hughesdbb40792011-11-18 17:05:22 -08001389
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001390 mh.GetDexFile().DecodeDebugInfo(code_item, m->IsStatic(), m->GetDexMethodIndex(), NULL,
1391 DebugCallbackContext::Callback, &context);
Elliott Hughesdbb40792011-11-18 17:05:22 -08001392
Elliott Hughesc5b734a2011-12-01 17:20:58 -08001393 JDWP::Set4BE(expandBufGetBuffer(pReply) + variable_count_offset, context.variable_count);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001394}
1395
Elliott Hughes9777ba22013-01-17 09:04:19 -08001396JDWP::JdwpError Dbg::GetBytecodes(JDWP::RefTypeId, JDWP::MethodId method_id,
1397 std::vector<uint8_t>& bytecodes)
1398 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Brian Carlstromea46f952013-07-30 01:26:50 -07001399 mirror::ArtMethod* m = FromMethodId(method_id);
Elliott Hughes9777ba22013-01-17 09:04:19 -08001400 if (m == NULL) {
1401 return JDWP::ERR_INVALID_METHODID;
1402 }
1403 MethodHelper mh(m);
1404 const DexFile::CodeItem* code_item = mh.GetCodeItem();
1405 size_t byte_count = code_item->insns_size_in_code_units_ * 2;
1406 const uint8_t* begin = reinterpret_cast<const uint8_t*>(code_item->insns_);
1407 const uint8_t* end = begin + byte_count;
1408 for (const uint8_t* p = begin; p != end; ++p) {
1409 bytecodes.push_back(*p);
1410 }
1411 return JDWP::ERR_NONE;
1412}
1413
Elliott Hughes88d63092013-01-09 09:55:54 -08001414JDWP::JdwpTag Dbg::GetFieldBasicTag(JDWP::FieldId field_id) {
1415 return BasicTagFromDescriptor(FieldHelper(FromFieldId(field_id)).GetTypeDescriptor());
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001416}
1417
Elliott Hughes88d63092013-01-09 09:55:54 -08001418JDWP::JdwpTag Dbg::GetStaticFieldBasicTag(JDWP::FieldId field_id) {
1419 return BasicTagFromDescriptor(FieldHelper(FromFieldId(field_id)).GetTypeDescriptor());
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001420}
1421
Elliott Hughes88d63092013-01-09 09:55:54 -08001422static JDWP::JdwpError GetFieldValueImpl(JDWP::RefTypeId ref_type_id, JDWP::ObjectId object_id,
1423 JDWP::FieldId field_id, JDWP::ExpandBuf* pReply,
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001424 bool is_static)
Ian Rogersb726dcb2012-09-05 08:57:23 -07001425 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Elliott Hughes0cf74332012-02-23 23:14:00 -08001426 JDWP::JdwpError status;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001427 mirror::Class* c = DecodeClass(ref_type_id, status);
Elliott Hughes88d63092013-01-09 09:55:54 -08001428 if (ref_type_id != 0 && c == NULL) {
Elliott Hughes0cf74332012-02-23 23:14:00 -08001429 return status;
1430 }
1431
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001432 mirror::Object* o = gRegistry->Get<mirror::Object*>(object_id);
Elliott Hughes64f574f2013-02-20 14:57:12 -08001433 if ((!is_static && o == NULL) || o == ObjectRegistry::kInvalidObject) {
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08001434 return JDWP::ERR_INVALID_OBJECT;
1435 }
Brian Carlstromea46f952013-07-30 01:26:50 -07001436 mirror::ArtField* f = FromFieldId(field_id);
Elliott Hughes0cf74332012-02-23 23:14:00 -08001437
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001438 mirror::Class* receiver_class = c;
Elliott Hughes0cf74332012-02-23 23:14:00 -08001439 if (receiver_class == NULL && o != NULL) {
1440 receiver_class = o->GetClass();
1441 }
1442 // TODO: should we give up now if receiver_class is NULL?
1443 if (receiver_class != NULL && !f->GetDeclaringClass()->IsAssignableFrom(receiver_class)) {
1444 LOG(INFO) << "ERR_INVALID_FIELDID: " << PrettyField(f) << " " << PrettyClass(receiver_class);
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08001445 return JDWP::ERR_INVALID_FIELDID;
1446 }
Elliott Hughesaed4be92011-12-02 16:16:23 -08001447
Elliott Hughes0cf74332012-02-23 23:14:00 -08001448 // The RI only enforces the static/non-static mismatch in one direction.
1449 // TODO: should we change the tests and check both?
1450 if (is_static) {
1451 if (!f->IsStatic()) {
1452 return JDWP::ERR_INVALID_FIELDID;
1453 }
1454 } else {
1455 if (f->IsStatic()) {
1456 LOG(WARNING) << "Ignoring non-NULL receiver for ObjectReference.SetValues on static field " << PrettyField(f);
Elliott Hughes0cf74332012-02-23 23:14:00 -08001457 }
1458 }
jeffhao0dfbb7e2012-11-28 15:26:03 -08001459 if (f->IsStatic()) {
1460 o = f->GetDeclaringClass();
1461 }
Elliott Hughes0cf74332012-02-23 23:14:00 -08001462
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001463 JDWP::JdwpTag tag = BasicTagFromDescriptor(FieldHelper(f).GetTypeDescriptor());
Elliott Hughesaed4be92011-12-02 16:16:23 -08001464
1465 if (IsPrimitiveTag(tag)) {
1466 expandBufAdd1(pReply, tag);
1467 if (tag == JDWP::JT_BOOLEAN || tag == JDWP::JT_BYTE) {
1468 expandBufAdd1(pReply, f->Get32(o));
1469 } else if (tag == JDWP::JT_CHAR || tag == JDWP::JT_SHORT) {
1470 expandBufAdd2BE(pReply, f->Get32(o));
1471 } else if (tag == JDWP::JT_FLOAT || tag == JDWP::JT_INT) {
1472 expandBufAdd4BE(pReply, f->Get32(o));
1473 } else if (tag == JDWP::JT_DOUBLE || tag == JDWP::JT_LONG) {
1474 expandBufAdd8BE(pReply, f->Get64(o));
1475 } else {
Elliott Hughes3d30d9b2011-12-07 17:35:48 -08001476 LOG(FATAL) << "Unknown tag: " << tag;
Elliott Hughesaed4be92011-12-02 16:16:23 -08001477 }
1478 } else {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001479 mirror::Object* value = f->GetObject(o);
Elliott Hughesaed4be92011-12-02 16:16:23 -08001480 expandBufAdd1(pReply, TagFromObject(value));
1481 expandBufAddObjectId(pReply, gRegistry->Add(value));
1482 }
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08001483 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001484}
1485
Elliott Hughes88d63092013-01-09 09:55:54 -08001486JDWP::JdwpError Dbg::GetFieldValue(JDWP::ObjectId object_id, JDWP::FieldId field_id,
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001487 JDWP::ExpandBuf* pReply) {
Elliott Hughes88d63092013-01-09 09:55:54 -08001488 return GetFieldValueImpl(0, object_id, field_id, pReply, false);
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08001489}
1490
Elliott Hughes88d63092013-01-09 09:55:54 -08001491JDWP::JdwpError Dbg::GetStaticFieldValue(JDWP::RefTypeId ref_type_id, JDWP::FieldId field_id, JDWP::ExpandBuf* pReply) {
1492 return GetFieldValueImpl(ref_type_id, 0, field_id, pReply, true);
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08001493}
1494
Elliott Hughes88d63092013-01-09 09:55:54 -08001495static JDWP::JdwpError SetFieldValueImpl(JDWP::ObjectId object_id, JDWP::FieldId field_id,
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001496 uint64_t value, int width, bool is_static)
Ian Rogersb726dcb2012-09-05 08:57:23 -07001497 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001498 mirror::Object* o = gRegistry->Get<mirror::Object*>(object_id);
Elliott Hughes64f574f2013-02-20 14:57:12 -08001499 if ((!is_static && o == NULL) || o == ObjectRegistry::kInvalidObject) {
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08001500 return JDWP::ERR_INVALID_OBJECT;
1501 }
Brian Carlstromea46f952013-07-30 01:26:50 -07001502 mirror::ArtField* f = FromFieldId(field_id);
Elliott Hughes0cf74332012-02-23 23:14:00 -08001503
1504 // The RI only enforces the static/non-static mismatch in one direction.
1505 // TODO: should we change the tests and check both?
1506 if (is_static) {
1507 if (!f->IsStatic()) {
1508 return JDWP::ERR_INVALID_FIELDID;
1509 }
1510 } else {
1511 if (f->IsStatic()) {
1512 LOG(WARNING) << "Ignoring non-NULL receiver for ObjectReference.SetValues on static field " << PrettyField(f);
Elliott Hughes0cf74332012-02-23 23:14:00 -08001513 }
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08001514 }
jeffhao0dfbb7e2012-11-28 15:26:03 -08001515 if (f->IsStatic()) {
1516 o = f->GetDeclaringClass();
1517 }
Elliott Hughesaed4be92011-12-02 16:16:23 -08001518
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001519 JDWP::JdwpTag tag = BasicTagFromDescriptor(FieldHelper(f).GetTypeDescriptor());
Elliott Hughesaed4be92011-12-02 16:16:23 -08001520
1521 if (IsPrimitiveTag(tag)) {
1522 if (tag == JDWP::JT_DOUBLE || tag == JDWP::JT_LONG) {
Elliott Hughes1bac54f2012-03-16 12:48:31 -07001523 CHECK_EQ(width, 8);
Elliott Hughesaed4be92011-12-02 16:16:23 -08001524 f->Set64(o, value);
1525 } else {
Elliott Hughes1bac54f2012-03-16 12:48:31 -07001526 CHECK_LE(width, 4);
Elliott Hughesaed4be92011-12-02 16:16:23 -08001527 f->Set32(o, value);
1528 }
1529 } else {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001530 mirror::Object* v = gRegistry->Get<mirror::Object*>(value);
Elliott Hughes64f574f2013-02-20 14:57:12 -08001531 if (v == ObjectRegistry::kInvalidObject) {
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -08001532 return JDWP::ERR_INVALID_OBJECT;
1533 }
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08001534 if (v != NULL) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001535 mirror::Class* field_type = FieldHelper(f).GetType();
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08001536 if (!field_type->IsAssignableFrom(v->GetClass())) {
1537 return JDWP::ERR_INVALID_OBJECT;
1538 }
1539 }
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -08001540 f->SetObject(o, v);
Elliott Hughesaed4be92011-12-02 16:16:23 -08001541 }
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -08001542
1543 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001544}
1545
Elliott Hughes88d63092013-01-09 09:55:54 -08001546JDWP::JdwpError Dbg::SetFieldValue(JDWP::ObjectId object_id, JDWP::FieldId field_id, uint64_t value,
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001547 int width) {
Elliott Hughes88d63092013-01-09 09:55:54 -08001548 return SetFieldValueImpl(object_id, field_id, value, width, false);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001549}
1550
Elliott Hughes88d63092013-01-09 09:55:54 -08001551JDWP::JdwpError Dbg::SetStaticFieldValue(JDWP::FieldId field_id, uint64_t value, int width) {
1552 return SetFieldValueImpl(0, field_id, value, width, true);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001553}
1554
Elliott Hughes88d63092013-01-09 09:55:54 -08001555std::string Dbg::StringToUtf8(JDWP::ObjectId string_id) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001556 mirror::String* s = gRegistry->Get<mirror::String*>(string_id);
Elliott Hughes68fdbd02011-11-29 19:22:47 -08001557 return s->ToModifiedUtf8();
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001558}
1559
Elliott Hughes221229c2013-01-08 18:17:50 -08001560JDWP::JdwpError Dbg::GetThreadName(JDWP::ObjectId thread_id, std::string& name) {
jeffhaoa77f0f62012-12-05 17:19:31 -08001561 ScopedObjectAccessUnchecked soa(Thread::Current());
1562 MutexLock mu(soa.Self(), *Locks::thread_list_lock_);
Elliott Hughes221229c2013-01-08 18:17:50 -08001563 Thread* thread;
1564 JDWP::JdwpError error = DecodeThread(soa, thread_id, thread);
1565 if (error != JDWP::ERR_NONE && error != JDWP::ERR_THREAD_NOT_ALIVE) {
1566 return error;
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001567 }
Elliott Hughes221229c2013-01-08 18:17:50 -08001568
1569 // We still need to report the zombie threads' names, so we can't just call Thread::GetThreadName.
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001570 mirror::Object* thread_object = gRegistry->Get<mirror::Object*>(thread_id);
Brian Carlstromea46f952013-07-30 01:26:50 -07001571 mirror::ArtField* java_lang_Thread_name_field =
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001572 soa.DecodeField(WellKnownClasses::java_lang_Thread_name);
1573 mirror::String* s =
1574 reinterpret_cast<mirror::String*>(java_lang_Thread_name_field->GetObject(thread_object));
Elliott Hughes221229c2013-01-08 18:17:50 -08001575 if (s != NULL) {
1576 name = s->ToModifiedUtf8();
1577 }
1578 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001579}
1580
Elliott Hughes221229c2013-01-08 18:17:50 -08001581JDWP::JdwpError Dbg::GetThreadGroup(JDWP::ObjectId thread_id, JDWP::ExpandBuf* pReply) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001582 ScopedObjectAccess soa(Thread::Current());
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001583 mirror::Object* thread_object = gRegistry->Get<mirror::Object*>(thread_id);
Elliott Hughes64f574f2013-02-20 14:57:12 -08001584 if (thread_object == ObjectRegistry::kInvalidObject) {
Elliott Hughes2435a572012-02-17 16:07:41 -08001585 return JDWP::ERR_INVALID_OBJECT;
1586 }
1587
1588 // Okay, so it's an object, but is it actually a thread?
Ian Rogers50b35e22012-10-04 10:09:15 -07001589 MutexLock mu(soa.Self(), *Locks::thread_list_lock_);
Elliott Hughes221229c2013-01-08 18:17:50 -08001590 Thread* thread;
1591 JDWP::JdwpError error = DecodeThread(soa, thread_id, thread);
1592 if (error == JDWP::ERR_THREAD_NOT_ALIVE) {
1593 // Zombie threads are in the null group.
1594 expandBufAddObjectId(pReply, JDWP::ObjectId(0));
1595 return JDWP::ERR_NONE;
1596 }
1597 if (error != JDWP::ERR_NONE) {
1598 return error;
Elliott Hughes2435a572012-02-17 16:07:41 -08001599 }
Elliott Hughes499c5132011-11-17 14:55:11 -08001600
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001601 mirror::Class* c = Runtime::Current()->GetClassLinker()->FindSystemClass("Ljava/lang/Thread;");
Elliott Hughes499c5132011-11-17 14:55:11 -08001602 CHECK(c != NULL);
Brian Carlstromea46f952013-07-30 01:26:50 -07001603 mirror::ArtField* f = c->FindInstanceField("group", "Ljava/lang/ThreadGroup;");
Elliott Hughes499c5132011-11-17 14:55:11 -08001604 CHECK(f != NULL);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001605 mirror::Object* group = f->GetObject(thread_object);
Elliott Hughes499c5132011-11-17 14:55:11 -08001606 CHECK(group != NULL);
Elliott Hughes2435a572012-02-17 16:07:41 -08001607 JDWP::ObjectId thread_group_id = gRegistry->Add(group);
1608
1609 expandBufAddObjectId(pReply, thread_group_id);
1610 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001611}
1612
Elliott Hughes88d63092013-01-09 09:55:54 -08001613std::string Dbg::GetThreadGroupName(JDWP::ObjectId thread_group_id) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001614 ScopedObjectAccess soa(Thread::Current());
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001615 mirror::Object* thread_group = gRegistry->Get<mirror::Object*>(thread_group_id);
Elliott Hughes499c5132011-11-17 14:55:11 -08001616 CHECK(thread_group != NULL);
1617
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001618 mirror::Class* c = Runtime::Current()->GetClassLinker()->FindSystemClass("Ljava/lang/ThreadGroup;");
Elliott Hughes499c5132011-11-17 14:55:11 -08001619 CHECK(c != NULL);
Brian Carlstromea46f952013-07-30 01:26:50 -07001620 mirror::ArtField* f = c->FindInstanceField("name", "Ljava/lang/String;");
Elliott Hughes499c5132011-11-17 14:55:11 -08001621 CHECK(f != NULL);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001622 mirror::String* s = reinterpret_cast<mirror::String*>(f->GetObject(thread_group));
Elliott Hughes499c5132011-11-17 14:55:11 -08001623 return s->ToModifiedUtf8();
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001624}
1625
Elliott Hughes88d63092013-01-09 09:55:54 -08001626JDWP::ObjectId Dbg::GetThreadGroupParent(JDWP::ObjectId thread_group_id) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001627 mirror::Object* thread_group = gRegistry->Get<mirror::Object*>(thread_group_id);
Elliott Hughes4e235312011-12-02 11:34:15 -08001628 CHECK(thread_group != NULL);
1629
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001630 mirror::Class* c = Runtime::Current()->GetClassLinker()->FindSystemClass("Ljava/lang/ThreadGroup;");
Elliott Hughes4e235312011-12-02 11:34:15 -08001631 CHECK(c != NULL);
Brian Carlstromea46f952013-07-30 01:26:50 -07001632 mirror::ArtField* f = c->FindInstanceField("parent", "Ljava/lang/ThreadGroup;");
Elliott Hughes4e235312011-12-02 11:34:15 -08001633 CHECK(f != NULL);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001634 mirror::Object* parent = f->GetObject(thread_group);
Elliott Hughes4e235312011-12-02 11:34:15 -08001635 return gRegistry->Add(parent);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001636}
1637
1638JDWP::ObjectId Dbg::GetSystemThreadGroupId() {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001639 ScopedObjectAccessUnchecked soa(Thread::Current());
Brian Carlstromea46f952013-07-30 01:26:50 -07001640 mirror::ArtField* f = soa.DecodeField(WellKnownClasses::java_lang_ThreadGroup_systemThreadGroup);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001641 mirror::Object* group = f->GetObject(f->GetDeclaringClass());
Ian Rogers365c1022012-06-22 15:05:28 -07001642 return gRegistry->Add(group);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001643}
1644
1645JDWP::ObjectId Dbg::GetMainThreadGroupId() {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001646 ScopedObjectAccess soa(Thread::Current());
Brian Carlstromea46f952013-07-30 01:26:50 -07001647 mirror::ArtField* f = soa.DecodeField(WellKnownClasses::java_lang_ThreadGroup_mainThreadGroup);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001648 mirror::Object* group = f->GetObject(f->GetDeclaringClass());
Ian Rogers365c1022012-06-22 15:05:28 -07001649 return gRegistry->Add(group);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001650}
1651
Jeff Hao920af3e2013-08-28 15:46:38 -07001652JDWP::JdwpThreadStatus Dbg::ToJdwpThreadStatus(ThreadState state) {
1653 switch (state) {
1654 case kBlocked:
1655 return JDWP::TS_MONITOR;
1656 case kNative:
1657 case kRunnable:
1658 case kSuspended:
1659 return JDWP::TS_RUNNING;
1660 case kSleeping:
1661 return JDWP::TS_SLEEPING;
1662 case kStarting:
1663 case kTerminated:
1664 return JDWP::TS_ZOMBIE;
1665 case kTimedWaiting:
1666 case kWaitingForDebuggerSend:
1667 case kWaitingForDebuggerSuspension:
1668 case kWaitingForDebuggerToAttach:
1669 case kWaitingForGcToComplete:
1670 case kWaitingForCheckPointsToRun:
1671 case kWaitingForJniOnLoad:
1672 case kWaitingForSignalCatcherOutput:
1673 case kWaitingInMainDebuggerLoop:
1674 case kWaitingInMainSignalCatcherLoop:
1675 case kWaitingPerformingGc:
1676 case kWaiting:
1677 return JDWP::TS_WAIT;
1678 // Don't add a 'default' here so the compiler can spot incompatible enum changes.
1679 }
1680 LOG(FATAL) << "Unknown thread state: " << state;
1681 return JDWP::TS_ZOMBIE;
1682}
1683
Elliott Hughes221229c2013-01-08 18:17:50 -08001684JDWP::JdwpError Dbg::GetThreadStatus(JDWP::ObjectId thread_id, JDWP::JdwpThreadStatus* pThreadStatus, JDWP::JdwpSuspendStatus* pSuspendStatus) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001685 ScopedObjectAccess soa(Thread::Current());
Elliott Hughes499c5132011-11-17 14:55:11 -08001686
Elliott Hughes9e0c1752013-01-09 14:02:58 -08001687 *pSuspendStatus = JDWP::SUSPEND_STATUS_NOT_SUSPENDED;
1688
Ian Rogers50b35e22012-10-04 10:09:15 -07001689 MutexLock mu(soa.Self(), *Locks::thread_list_lock_);
Elliott Hughes221229c2013-01-08 18:17:50 -08001690 Thread* thread;
1691 JDWP::JdwpError error = DecodeThread(soa, thread_id, thread);
1692 if (error != JDWP::ERR_NONE) {
1693 if (error == JDWP::ERR_THREAD_NOT_ALIVE) {
1694 *pThreadStatus = JDWP::TS_ZOMBIE;
Elliott Hughes221229c2013-01-08 18:17:50 -08001695 return JDWP::ERR_NONE;
1696 }
1697 return error;
Elliott Hughes499c5132011-11-17 14:55:11 -08001698 }
1699
Elliott Hughes9e0c1752013-01-09 14:02:58 -08001700 if (IsSuspendedForDebugger(soa, thread)) {
1701 *pSuspendStatus = JDWP::SUSPEND_STATUS_SUSPENDED;
Elliott Hughes499c5132011-11-17 14:55:11 -08001702 }
1703
Jeff Hao920af3e2013-08-28 15:46:38 -07001704 *pThreadStatus = ToJdwpThreadStatus(thread->GetState());
Elliott Hughes221229c2013-01-08 18:17:50 -08001705 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001706}
1707
Elliott Hughes221229c2013-01-08 18:17:50 -08001708JDWP::JdwpError Dbg::GetThreadDebugSuspendCount(JDWP::ObjectId thread_id, JDWP::ExpandBuf* pReply) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001709 ScopedObjectAccess soa(Thread::Current());
Ian Rogers50b35e22012-10-04 10:09:15 -07001710 MutexLock mu(soa.Self(), *Locks::thread_list_lock_);
Elliott Hughes221229c2013-01-08 18:17:50 -08001711 Thread* thread;
1712 JDWP::JdwpError error = DecodeThread(soa, thread_id, thread);
1713 if (error != JDWP::ERR_NONE) {
1714 return error;
Elliott Hughes2435a572012-02-17 16:07:41 -08001715 }
Ian Rogers50b35e22012-10-04 10:09:15 -07001716 MutexLock mu2(soa.Self(), *Locks::thread_suspend_count_lock_);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001717 expandBufAdd4BE(pReply, thread->GetDebugSuspendCount());
Elliott Hughes2435a572012-02-17 16:07:41 -08001718 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001719}
1720
Elliott Hughesf9501702013-01-11 11:22:27 -08001721JDWP::JdwpError Dbg::Interrupt(JDWP::ObjectId thread_id) {
1722 ScopedObjectAccess soa(Thread::Current());
1723 MutexLock mu(soa.Self(), *Locks::thread_list_lock_);
1724 Thread* thread;
1725 JDWP::JdwpError error = DecodeThread(soa, thread_id, thread);
1726 if (error != JDWP::ERR_NONE) {
1727 return error;
1728 }
1729 thread->Interrupt();
1730 return JDWP::ERR_NONE;
1731}
1732
Elliott Hughescaf76542012-06-28 16:08:22 -07001733void Dbg::GetThreads(JDWP::ObjectId thread_group_id, std::vector<JDWP::ObjectId>& thread_ids) {
Ian Rogers365c1022012-06-22 15:05:28 -07001734 class ThreadListVisitor {
1735 public:
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001736 ThreadListVisitor(const ScopedObjectAccessUnchecked& soa, mirror::Object* desired_thread_group,
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001737 std::vector<JDWP::ObjectId>& thread_ids)
Ian Rogersb726dcb2012-09-05 08:57:23 -07001738 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_)
jeffhao0dfbb7e2012-11-28 15:26:03 -08001739 : soa_(soa), desired_thread_group_(desired_thread_group), thread_ids_(thread_ids) {}
Ian Rogers365c1022012-06-22 15:05:28 -07001740
Elliott Hughesa2155262011-11-16 16:26:58 -08001741 static void Visit(Thread* t, void* arg) {
1742 reinterpret_cast<ThreadListVisitor*>(arg)->Visit(t);
1743 }
1744
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001745 // TODO: Enable annotalysis. We know lock is held in constructor, but abstraction confuses
1746 // annotalysis.
1747 void Visit(Thread* t) NO_THREAD_SAFETY_ANALYSIS {
Elliott Hughesa2155262011-11-16 16:26:58 -08001748 if (t == Dbg::GetDebugThread()) {
1749 // Skip the JDWP thread. Some debuggers get bent out of shape when they can't suspend and
1750 // query all threads, so it's easier if we just don't tell them about this thread.
1751 return;
1752 }
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001753 mirror::Object* peer = t->GetPeer();
jeffhao0dfbb7e2012-11-28 15:26:03 -08001754 if (IsInDesiredThreadGroup(peer)) {
Ian Rogers120f1c72012-09-28 17:17:10 -07001755 thread_ids_.push_back(gRegistry->Add(peer));
Elliott Hughesa2155262011-11-16 16:26:58 -08001756 }
1757 }
1758
Ian Rogers365c1022012-06-22 15:05:28 -07001759 private:
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001760 bool IsInDesiredThreadGroup(mirror::Object* peer)
jeffhao0dfbb7e2012-11-28 15:26:03 -08001761 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
jeffhao0dfbb7e2012-11-28 15:26:03 -08001762 // peer might be NULL if the thread is still starting up.
1763 if (peer == NULL) {
1764 // We can't tell the debugger about this thread yet.
1765 // TODO: if we identified threads to the debugger by their Thread*
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001766 // rather than their peer's mirror::Object*, we could fix this.
jeffhao0dfbb7e2012-11-28 15:26:03 -08001767 // Doing so might help us report ZOMBIE threads too.
1768 return false;
1769 }
jeffhaoc1e04902012-12-13 12:41:10 -08001770 // Do we want threads from all thread groups?
1771 if (desired_thread_group_ == NULL) {
1772 return true;
1773 }
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001774 mirror::Object* group = soa_.DecodeField(WellKnownClasses::java_lang_Thread_group)->GetObject(peer);
jeffhao0dfbb7e2012-11-28 15:26:03 -08001775 return (group == desired_thread_group_);
1776 }
1777
Mathieu Chartierdbe6f462012-09-25 16:54:50 -07001778 const ScopedObjectAccessUnchecked& soa_;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001779 mirror::Object* const desired_thread_group_;
Elliott Hughescaf76542012-06-28 16:08:22 -07001780 std::vector<JDWP::ObjectId>& thread_ids_;
Elliott Hughesa2155262011-11-16 16:26:58 -08001781 };
1782
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001783 ScopedObjectAccessUnchecked soa(Thread::Current());
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001784 mirror::Object* thread_group = gRegistry->Get<mirror::Object*>(thread_group_id);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001785 ThreadListVisitor tlv(soa, thread_group, thread_ids);
Ian Rogers50b35e22012-10-04 10:09:15 -07001786 MutexLock mu(soa.Self(), *Locks::thread_list_lock_);
Elliott Hughesf8349362012-06-18 15:00:06 -07001787 Runtime::Current()->GetThreadList()->ForEach(ThreadListVisitor::Visit, &tlv);
Elliott Hughescaf76542012-06-28 16:08:22 -07001788}
Elliott Hughesa2155262011-11-16 16:26:58 -08001789
Elliott Hughescaf76542012-06-28 16:08:22 -07001790void Dbg::GetChildThreadGroups(JDWP::ObjectId thread_group_id, std::vector<JDWP::ObjectId>& child_thread_group_ids) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001791 ScopedObjectAccess soa(Thread::Current());
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001792 mirror::Object* thread_group = gRegistry->Get<mirror::Object*>(thread_group_id);
Elliott Hughescaf76542012-06-28 16:08:22 -07001793
1794 // Get the ArrayList<ThreadGroup> "groups" out of this thread group...
Brian Carlstromea46f952013-07-30 01:26:50 -07001795 mirror::ArtField* groups_field = thread_group->GetClass()->FindInstanceField("groups", "Ljava/util/List;");
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001796 mirror::Object* groups_array_list = groups_field->GetObject(thread_group);
Elliott Hughescaf76542012-06-28 16:08:22 -07001797
1798 // Get the array and size out of the ArrayList<ThreadGroup>...
Brian Carlstromea46f952013-07-30 01:26:50 -07001799 mirror::ArtField* array_field = groups_array_list->GetClass()->FindInstanceField("array", "[Ljava/lang/Object;");
1800 mirror::ArtField* size_field = groups_array_list->GetClass()->FindInstanceField("size", "I");
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001801 mirror::ObjectArray<mirror::Object>* groups_array =
1802 array_field->GetObject(groups_array_list)->AsObjectArray<mirror::Object>();
Elliott Hughescaf76542012-06-28 16:08:22 -07001803 const int32_t size = size_field->GetInt(groups_array_list);
1804
1805 // Copy the first 'size' elements out of the array into the result.
1806 for (int32_t i = 0; i < size; ++i) {
1807 child_thread_group_ids.push_back(gRegistry->Add(groups_array->Get(i)));
Elliott Hughesa2155262011-11-16 16:26:58 -08001808 }
1809}
1810
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001811static int GetStackDepth(Thread* thread)
Ian Rogersb726dcb2012-09-05 08:57:23 -07001812 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Ian Rogers0399dde2012-06-06 17:09:28 -07001813 struct CountStackDepthVisitor : public StackVisitor {
Brian Carlstrom93ba8932013-07-17 21:31:49 -07001814 explicit CountStackDepthVisitor(Thread* thread)
Ian Rogers7a22fa62013-01-23 12:16:16 -08001815 : StackVisitor(thread, NULL), depth(0) {}
Ian Rogers0399dde2012-06-06 17:09:28 -07001816
Elliott Hughes64f574f2013-02-20 14:57:12 -08001817 // TODO: Enable annotalysis. We know lock is held in constructor, but abstraction confuses
1818 // annotalysis.
1819 bool VisitFrame() NO_THREAD_SAFETY_ANALYSIS {
Ian Rogers0399dde2012-06-06 17:09:28 -07001820 if (!GetMethod()->IsRuntimeMethod()) {
Elliott Hughesf8a2df72011-12-01 12:19:54 -08001821 ++depth;
1822 }
Elliott Hughes530fa002012-03-12 11:44:49 -07001823 return true;
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001824 }
1825 size_t depth;
1826 };
Elliott Hughes08fc03a2012-06-26 17:34:00 -07001827
Ian Rogers7a22fa62013-01-23 12:16:16 -08001828 CountStackDepthVisitor visitor(thread);
Ian Rogers0399dde2012-06-06 17:09:28 -07001829 visitor.WalkStack();
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001830 return visitor.depth;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001831}
1832
Elliott Hughes221229c2013-01-08 18:17:50 -08001833JDWP::JdwpError Dbg::GetThreadFrameCount(JDWP::ObjectId thread_id, size_t& result) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001834 ScopedObjectAccess soa(Thread::Current());
jeffhaoa77f0f62012-12-05 17:19:31 -08001835 MutexLock mu(soa.Self(), *Locks::thread_list_lock_);
Elliott Hughes221229c2013-01-08 18:17:50 -08001836 Thread* thread;
1837 JDWP::JdwpError error = DecodeThread(soa, thread_id, thread);
1838 if (error != JDWP::ERR_NONE) {
1839 return error;
1840 }
Elliott Hughesf15f4a02013-01-09 10:09:38 -08001841 if (!IsSuspendedForDebugger(soa, thread)) {
1842 return JDWP::ERR_THREAD_NOT_SUSPENDED;
1843 }
Elliott Hughes221229c2013-01-08 18:17:50 -08001844 result = GetStackDepth(thread);
1845 return JDWP::ERR_NONE;
Elliott Hughes86964332012-02-15 19:37:42 -08001846}
1847
Ian Rogers306057f2012-11-26 12:45:53 -08001848JDWP::JdwpError Dbg::GetThreadFrames(JDWP::ObjectId thread_id, size_t start_frame,
1849 size_t frame_count, JDWP::ExpandBuf* buf) {
Elliott Hughes6e9d22c2012-06-22 15:02:37 -07001850 class GetFrameVisitor : public StackVisitor {
1851 public:
Ian Rogers7a22fa62013-01-23 12:16:16 -08001852 GetFrameVisitor(Thread* thread, size_t start_frame, size_t frame_count, JDWP::ExpandBuf* buf)
Ian Rogersb726dcb2012-09-05 08:57:23 -07001853 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_)
Ian Rogers7a22fa62013-01-23 12:16:16 -08001854 : StackVisitor(thread, NULL), depth_(0),
Elliott Hughes6e9d22c2012-06-22 15:02:37 -07001855 start_frame_(start_frame), frame_count_(frame_count), buf_(buf) {
1856 expandBufAdd4BE(buf_, frame_count_);
Elliott Hughes03181a82011-11-17 17:22:21 -08001857 }
Ian Rogers0399dde2012-06-06 17:09:28 -07001858
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001859 // TODO: Enable annotalysis. We know lock is held in constructor, but abstraction confuses
1860 // annotalysis.
1861 virtual bool VisitFrame() NO_THREAD_SAFETY_ANALYSIS {
Ian Rogers0399dde2012-06-06 17:09:28 -07001862 if (GetMethod()->IsRuntimeMethod()) {
Brian Carlstrom7934ac22013-07-26 10:54:15 -07001863 return true; // The debugger can't do anything useful with a frame that has no Method*.
Elliott Hughes03181a82011-11-17 17:22:21 -08001864 }
Elliott Hughes6e9d22c2012-06-22 15:02:37 -07001865 if (depth_ >= start_frame_ + frame_count_) {
Elliott Hughes530fa002012-03-12 11:44:49 -07001866 return false;
Elliott Hughes03181a82011-11-17 17:22:21 -08001867 }
Elliott Hughes6e9d22c2012-06-22 15:02:37 -07001868 if (depth_ >= start_frame_) {
1869 JDWP::FrameId frame_id(GetFrameId());
1870 JDWP::JdwpLocation location;
1871 SetLocation(location, GetMethod(), GetDexPc());
Elliott Hughes7baf96f2012-06-22 16:33:50 -07001872 VLOG(jdwp) << StringPrintf(" Frame %3zd: id=%3lld ", depth_, frame_id) << location;
Elliott Hughes6e9d22c2012-06-22 15:02:37 -07001873 expandBufAdd8BE(buf_, frame_id);
1874 expandBufAddLocation(buf_, location);
1875 }
1876 ++depth_;
Elliott Hughes530fa002012-03-12 11:44:49 -07001877 return true;
Elliott Hughes03181a82011-11-17 17:22:21 -08001878 }
Elliott Hughes6e9d22c2012-06-22 15:02:37 -07001879
1880 private:
1881 size_t depth_;
1882 const size_t start_frame_;
1883 const size_t frame_count_;
1884 JDWP::ExpandBuf* buf_;
Elliott Hughes03181a82011-11-17 17:22:21 -08001885 };
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001886
1887 ScopedObjectAccessUnchecked soa(Thread::Current());
jeffhaoa77f0f62012-12-05 17:19:31 -08001888 MutexLock mu(soa.Self(), *Locks::thread_list_lock_);
Elliott Hughes221229c2013-01-08 18:17:50 -08001889 Thread* thread;
1890 JDWP::JdwpError error = DecodeThread(soa, thread_id, thread);
1891 if (error != JDWP::ERR_NONE) {
1892 return error;
1893 }
Elliott Hughesf15f4a02013-01-09 10:09:38 -08001894 if (!IsSuspendedForDebugger(soa, thread)) {
1895 return JDWP::ERR_THREAD_NOT_SUSPENDED;
1896 }
Ian Rogers7a22fa62013-01-23 12:16:16 -08001897 GetFrameVisitor visitor(thread, start_frame, frame_count, buf);
Ian Rogers0399dde2012-06-06 17:09:28 -07001898 visitor.WalkStack();
Elliott Hughes6e9d22c2012-06-22 15:02:37 -07001899 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001900}
1901
1902JDWP::ObjectId Dbg::GetThreadSelfId() {
Mathieu Chartierdbe6f462012-09-25 16:54:50 -07001903 ScopedObjectAccessUnchecked soa(Thread::Current());
Ian Rogerscfaa4552012-11-26 21:00:08 -08001904 return gRegistry->Add(soa.Self()->GetPeer());
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001905}
1906
Elliott Hughes475fc232011-10-25 15:00:35 -07001907void Dbg::SuspendVM() {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001908 Runtime::Current()->GetThreadList()->SuspendAllForDebugger();
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001909}
1910
1911void Dbg::ResumeVM() {
Elliott Hughesc61a2672012-06-21 14:52:29 -07001912 Runtime::Current()->GetThreadList()->UndoDebuggerSuspensions();
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001913}
1914
Elliott Hughes221229c2013-01-08 18:17:50 -08001915JDWP::JdwpError Dbg::SuspendThread(JDWP::ObjectId thread_id, bool request_suspension) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001916 ScopedLocalRef<jobject> peer(Thread::Current()->GetJniEnv(), NULL);
1917 {
1918 ScopedObjectAccess soa(Thread::Current());
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001919 peer.reset(soa.AddLocalReference<jobject>(gRegistry->Get<mirror::Object*>(thread_id)));
Elliott Hughes4e235312011-12-02 11:34:15 -08001920 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001921 if (peer.get() == NULL) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001922 return JDWP::ERR_THREAD_NOT_ALIVE;
1923 }
1924 // Suspend thread to build stack trace.
Elliott Hughesf327e072013-01-09 16:01:26 -08001925 bool timed_out;
Ian Rogersd9c4fc92013-10-01 19:45:43 -07001926 Thread* thread = ThreadList::SuspendThreadByPeer(peer.get(), request_suspension, true,
1927 &timed_out);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001928 if (thread != NULL) {
1929 return JDWP::ERR_NONE;
Elliott Hughesf327e072013-01-09 16:01:26 -08001930 } else if (timed_out) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001931 return JDWP::ERR_INTERNAL;
1932 } else {
1933 return JDWP::ERR_THREAD_NOT_ALIVE;
1934 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001935}
1936
Elliott Hughes221229c2013-01-08 18:17:50 -08001937void Dbg::ResumeThread(JDWP::ObjectId thread_id) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001938 ScopedObjectAccessUnchecked soa(Thread::Current());
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001939 mirror::Object* peer = gRegistry->Get<mirror::Object*>(thread_id);
jeffhaoa77f0f62012-12-05 17:19:31 -08001940 Thread* thread;
1941 {
1942 MutexLock mu(soa.Self(), *Locks::thread_list_lock_);
1943 thread = Thread::FromManagedThread(soa, peer);
1944 }
Elliott Hughes4e235312011-12-02 11:34:15 -08001945 if (thread == NULL) {
1946 LOG(WARNING) << "No such thread for resume: " << peer;
1947 return;
1948 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001949 bool needs_resume;
1950 {
Ian Rogers50b35e22012-10-04 10:09:15 -07001951 MutexLock mu2(soa.Self(), *Locks::thread_suspend_count_lock_);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001952 needs_resume = thread->GetSuspendCount() > 0;
1953 }
1954 if (needs_resume) {
Elliott Hughes546b9862012-06-20 16:06:13 -07001955 Runtime::Current()->GetThreadList()->Resume(thread, true);
1956 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001957}
1958
1959void Dbg::SuspendSelf() {
Elliott Hughes475fc232011-10-25 15:00:35 -07001960 Runtime::Current()->GetThreadList()->SuspendSelfForDebugger();
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001961}
1962
Ian Rogers0399dde2012-06-06 17:09:28 -07001963struct GetThisVisitor : public StackVisitor {
Ian Rogers7a22fa62013-01-23 12:16:16 -08001964 GetThisVisitor(Thread* thread, Context* context, JDWP::FrameId frame_id)
Ian Rogersb726dcb2012-09-05 08:57:23 -07001965 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_)
Ian Rogers7a22fa62013-01-23 12:16:16 -08001966 : StackVisitor(thread, context), this_object(NULL), frame_id(frame_id) {}
Ian Rogers0399dde2012-06-06 17:09:28 -07001967
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001968 // TODO: Enable annotalysis. We know lock is held in constructor, but abstraction confuses
1969 // annotalysis.
1970 virtual bool VisitFrame() NO_THREAD_SAFETY_ANALYSIS {
Elliott Hughes6e9d22c2012-06-22 15:02:37 -07001971 if (frame_id != GetFrameId()) {
Ian Rogers0399dde2012-06-06 17:09:28 -07001972 return true; // continue
Ian Rogers0399dde2012-06-06 17:09:28 -07001973 } else {
Ian Rogers62d6c772013-02-27 08:32:07 -08001974 this_object = GetThisObject();
1975 return false;
Ian Rogers0399dde2012-06-06 17:09:28 -07001976 }
Elliott Hughes86b00102011-12-05 17:54:26 -08001977 }
Ian Rogers0399dde2012-06-06 17:09:28 -07001978
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001979 mirror::Object* this_object;
Elliott Hughes6e9d22c2012-06-22 15:02:37 -07001980 JDWP::FrameId frame_id;
Ian Rogers0399dde2012-06-06 17:09:28 -07001981};
1982
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001983JDWP::JdwpError Dbg::GetThisObject(JDWP::ObjectId thread_id, JDWP::FrameId frame_id,
1984 JDWP::ObjectId* result) {
1985 ScopedObjectAccessUnchecked soa(Thread::Current());
1986 Thread* thread;
1987 {
Ian Rogers50b35e22012-10-04 10:09:15 -07001988 MutexLock mu(soa.Self(), *Locks::thread_list_lock_);
Elliott Hughes221229c2013-01-08 18:17:50 -08001989 JDWP::JdwpError error = DecodeThread(soa, thread_id, thread);
1990 if (error != JDWP::ERR_NONE) {
1991 return error;
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001992 }
Elliott Hughes9e0c1752013-01-09 14:02:58 -08001993 if (!IsSuspendedForDebugger(soa, thread)) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001994 return JDWP::ERR_THREAD_NOT_SUSPENDED;
1995 }
Elliott Hughes6e9d22c2012-06-22 15:02:37 -07001996 }
Elliott Hughescaf76542012-06-28 16:08:22 -07001997 UniquePtr<Context> context(Context::Create());
Ian Rogers7a22fa62013-01-23 12:16:16 -08001998 GetThisVisitor visitor(thread, context.get(), frame_id);
Ian Rogers0399dde2012-06-06 17:09:28 -07001999 visitor.WalkStack();
Elliott Hughes6e9d22c2012-06-22 15:02:37 -07002000 *result = gRegistry->Add(visitor.this_object);
2001 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002002}
2003
Elliott Hughes88d63092013-01-09 09:55:54 -08002004void Dbg::GetLocalValue(JDWP::ObjectId thread_id, JDWP::FrameId frame_id, int slot, JDWP::JdwpTag tag,
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002005 uint8_t* buf, size_t width) {
Ian Rogers0399dde2012-06-06 17:09:28 -07002006 struct GetLocalVisitor : public StackVisitor {
Ian Rogers7a22fa62013-01-23 12:16:16 -08002007 GetLocalVisitor(Thread* thread, Context* context, JDWP::FrameId frame_id, int slot,
2008 JDWP::JdwpTag tag, uint8_t* buf, size_t width)
Ian Rogersb726dcb2012-09-05 08:57:23 -07002009 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_)
Ian Rogers7a22fa62013-01-23 12:16:16 -08002010 : StackVisitor(thread, context), frame_id_(frame_id), slot_(slot), tag_(tag),
Ian Rogersca190662012-06-26 15:45:57 -07002011 buf_(buf), width_(width) {}
2012
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002013 // TODO: Enable annotalysis. We know lock is held in constructor, but abstraction confuses
2014 // annotalysis.
2015 bool VisitFrame() NO_THREAD_SAFETY_ANALYSIS {
Ian Rogers0399dde2012-06-06 17:09:28 -07002016 if (GetFrameId() != frame_id_) {
2017 return true; // Not our frame, carry on.
Elliott Hughesdbb40792011-11-18 17:05:22 -08002018 }
Ian Rogers0399dde2012-06-06 17:09:28 -07002019 // TODO: check that the tag is compatible with the actual type of the slot!
Brian Carlstromea46f952013-07-30 01:26:50 -07002020 mirror::ArtMethod* m = GetMethod();
Ian Rogers0399dde2012-06-06 17:09:28 -07002021 uint16_t reg = DemangleSlot(slot_, m);
Elliott Hughesdbb40792011-11-18 17:05:22 -08002022
Ian Rogers0399dde2012-06-06 17:09:28 -07002023 switch (tag_) {
2024 case JDWP::JT_BOOLEAN:
2025 {
2026 CHECK_EQ(width_, 1U);
Ian Rogers2bcb4a42012-11-08 10:39:18 -08002027 uint32_t intVal = GetVReg(m, reg, kIntVReg);
Ian Rogers0399dde2012-06-06 17:09:28 -07002028 VLOG(jdwp) << "get boolean local " << reg << " = " << intVal;
2029 JDWP::Set1(buf_+1, intVal != 0);
2030 }
2031 break;
2032 case JDWP::JT_BYTE:
2033 {
2034 CHECK_EQ(width_, 1U);
Ian Rogers2bcb4a42012-11-08 10:39:18 -08002035 uint32_t intVal = GetVReg(m, reg, kIntVReg);
Ian Rogers0399dde2012-06-06 17:09:28 -07002036 VLOG(jdwp) << "get byte local " << reg << " = " << intVal;
2037 JDWP::Set1(buf_+1, intVal);
2038 }
2039 break;
2040 case JDWP::JT_SHORT:
2041 case JDWP::JT_CHAR:
2042 {
2043 CHECK_EQ(width_, 2U);
Ian Rogers2bcb4a42012-11-08 10:39:18 -08002044 uint32_t intVal = GetVReg(m, reg, kIntVReg);
Ian Rogers0399dde2012-06-06 17:09:28 -07002045 VLOG(jdwp) << "get short/char local " << reg << " = " << intVal;
2046 JDWP::Set2BE(buf_+1, intVal);
2047 }
2048 break;
2049 case JDWP::JT_INT:
Ian Rogers2bcb4a42012-11-08 10:39:18 -08002050 {
2051 CHECK_EQ(width_, 4U);
2052 uint32_t intVal = GetVReg(m, reg, kIntVReg);
2053 VLOG(jdwp) << "get int local " << reg << " = " << intVal;
2054 JDWP::Set4BE(buf_+1, intVal);
2055 }
2056 break;
Ian Rogers0399dde2012-06-06 17:09:28 -07002057 case JDWP::JT_FLOAT:
2058 {
2059 CHECK_EQ(width_, 4U);
Ian Rogers2bcb4a42012-11-08 10:39:18 -08002060 uint32_t intVal = GetVReg(m, reg, kFloatVReg);
Ian Rogers0399dde2012-06-06 17:09:28 -07002061 VLOG(jdwp) << "get int/float local " << reg << " = " << intVal;
2062 JDWP::Set4BE(buf_+1, intVal);
2063 }
2064 break;
2065 case JDWP::JT_ARRAY:
2066 {
2067 CHECK_EQ(width_, sizeof(JDWP::ObjectId));
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002068 mirror::Object* o = reinterpret_cast<mirror::Object*>(GetVReg(m, reg, kReferenceVReg));
Ian Rogers0399dde2012-06-06 17:09:28 -07002069 VLOG(jdwp) << "get array local " << reg << " = " << o;
Mathieu Chartier590fee92013-09-13 13:46:47 -07002070 if (!Runtime::Current()->GetHeap()->IsValidObjectAddress(o)) {
Ian Rogers0399dde2012-06-06 17:09:28 -07002071 LOG(FATAL) << "Register " << reg << " expected to hold array: " << o;
2072 }
2073 JDWP::SetObjectId(buf_+1, gRegistry->Add(o));
2074 }
2075 break;
2076 case JDWP::JT_CLASS_LOADER:
2077 case JDWP::JT_CLASS_OBJECT:
2078 case JDWP::JT_OBJECT:
2079 case JDWP::JT_STRING:
2080 case JDWP::JT_THREAD:
2081 case JDWP::JT_THREAD_GROUP:
2082 {
2083 CHECK_EQ(width_, sizeof(JDWP::ObjectId));
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002084 mirror::Object* o = reinterpret_cast<mirror::Object*>(GetVReg(m, reg, kReferenceVReg));
Ian Rogers0399dde2012-06-06 17:09:28 -07002085 VLOG(jdwp) << "get object local " << reg << " = " << o;
Mathieu Chartier590fee92013-09-13 13:46:47 -07002086 if (!Runtime::Current()->GetHeap()->IsValidObjectAddress(o)) {
Ian Rogers0399dde2012-06-06 17:09:28 -07002087 LOG(FATAL) << "Register " << reg << " expected to hold object: " << o;
2088 }
2089 tag_ = TagFromObject(o);
2090 JDWP::SetObjectId(buf_+1, gRegistry->Add(o));
2091 }
2092 break;
2093 case JDWP::JT_DOUBLE:
Ian Rogers2bcb4a42012-11-08 10:39:18 -08002094 {
2095 CHECK_EQ(width_, 8U);
2096 uint32_t lo = GetVReg(m, reg, kDoubleLoVReg);
2097 uint64_t hi = GetVReg(m, reg + 1, kDoubleHiVReg);
2098 uint64_t longVal = (hi << 32) | lo;
2099 VLOG(jdwp) << "get double/long local " << hi << ":" << lo << " = " << longVal;
2100 JDWP::Set8BE(buf_+1, longVal);
2101 }
2102 break;
Ian Rogers0399dde2012-06-06 17:09:28 -07002103 case JDWP::JT_LONG:
2104 {
2105 CHECK_EQ(width_, 8U);
Ian Rogers2bcb4a42012-11-08 10:39:18 -08002106 uint32_t lo = GetVReg(m, reg, kLongLoVReg);
2107 uint64_t hi = GetVReg(m, reg + 1, kLongHiVReg);
Ian Rogers0399dde2012-06-06 17:09:28 -07002108 uint64_t longVal = (hi << 32) | lo;
2109 VLOG(jdwp) << "get double/long local " << hi << ":" << lo << " = " << longVal;
2110 JDWP::Set8BE(buf_+1, longVal);
2111 }
2112 break;
2113 default:
2114 LOG(FATAL) << "Unknown tag " << tag_;
2115 break;
2116 }
2117
2118 // Prepend tag, which may have been updated.
2119 JDWP::Set1(buf_, tag_);
2120 return false;
2121 }
2122
2123 const JDWP::FrameId frame_id_;
2124 const int slot_;
2125 JDWP::JdwpTag tag_;
2126 uint8_t* const buf_;
2127 const size_t width_;
2128 };
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002129
2130 ScopedObjectAccessUnchecked soa(Thread::Current());
jeffhaoa77f0f62012-12-05 17:19:31 -08002131 MutexLock mu(soa.Self(), *Locks::thread_list_lock_);
Elliott Hughes221229c2013-01-08 18:17:50 -08002132 Thread* thread;
2133 JDWP::JdwpError error = DecodeThread(soa, thread_id, thread);
2134 if (error != JDWP::ERR_NONE) {
2135 return;
2136 }
Ian Rogers0399dde2012-06-06 17:09:28 -07002137 UniquePtr<Context> context(Context::Create());
Ian Rogers7a22fa62013-01-23 12:16:16 -08002138 GetLocalVisitor visitor(thread, context.get(), frame_id, slot, tag, buf, width);
Ian Rogers0399dde2012-06-06 17:09:28 -07002139 visitor.WalkStack();
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002140}
2141
Elliott Hughes88d63092013-01-09 09:55:54 -08002142void Dbg::SetLocalValue(JDWP::ObjectId thread_id, JDWP::FrameId frame_id, int slot, JDWP::JdwpTag tag,
Ian Rogers0399dde2012-06-06 17:09:28 -07002143 uint64_t value, size_t width) {
2144 struct SetLocalVisitor : public StackVisitor {
Ian Rogers7a22fa62013-01-23 12:16:16 -08002145 SetLocalVisitor(Thread* thread, Context* context,
Ian Rogers0399dde2012-06-06 17:09:28 -07002146 JDWP::FrameId frame_id, int slot, JDWP::JdwpTag tag, uint64_t value,
Ian Rogersca190662012-06-26 15:45:57 -07002147 size_t width)
Ian Rogersb726dcb2012-09-05 08:57:23 -07002148 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_)
Ian Rogers7a22fa62013-01-23 12:16:16 -08002149 : StackVisitor(thread, context),
Elliott Hughes08fc03a2012-06-26 17:34:00 -07002150 frame_id_(frame_id), slot_(slot), tag_(tag), value_(value), width_(width) {}
Ian Rogersca190662012-06-26 15:45:57 -07002151
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002152 // TODO: Enable annotalysis. We know lock is held in constructor, but abstraction confuses
2153 // annotalysis.
2154 bool VisitFrame() NO_THREAD_SAFETY_ANALYSIS {
Ian Rogers0399dde2012-06-06 17:09:28 -07002155 if (GetFrameId() != frame_id_) {
2156 return true; // Not our frame, carry on.
2157 }
2158 // TODO: check that the tag is compatible with the actual type of the slot!
Brian Carlstromea46f952013-07-30 01:26:50 -07002159 mirror::ArtMethod* m = GetMethod();
Ian Rogers0399dde2012-06-06 17:09:28 -07002160 uint16_t reg = DemangleSlot(slot_, m);
2161
2162 switch (tag_) {
2163 case JDWP::JT_BOOLEAN:
2164 case JDWP::JT_BYTE:
2165 CHECK_EQ(width_, 1U);
Ian Rogers2bcb4a42012-11-08 10:39:18 -08002166 SetVReg(m, reg, static_cast<uint32_t>(value_), kIntVReg);
Ian Rogers0399dde2012-06-06 17:09:28 -07002167 break;
2168 case JDWP::JT_SHORT:
2169 case JDWP::JT_CHAR:
2170 CHECK_EQ(width_, 2U);
Ian Rogers2bcb4a42012-11-08 10:39:18 -08002171 SetVReg(m, reg, static_cast<uint32_t>(value_), kIntVReg);
Ian Rogers0399dde2012-06-06 17:09:28 -07002172 break;
2173 case JDWP::JT_INT:
Ian Rogers2bcb4a42012-11-08 10:39:18 -08002174 CHECK_EQ(width_, 4U);
2175 SetVReg(m, reg, static_cast<uint32_t>(value_), kIntVReg);
2176 break;
Ian Rogers0399dde2012-06-06 17:09:28 -07002177 case JDWP::JT_FLOAT:
2178 CHECK_EQ(width_, 4U);
Ian Rogers2bcb4a42012-11-08 10:39:18 -08002179 SetVReg(m, reg, static_cast<uint32_t>(value_), kFloatVReg);
Ian Rogers0399dde2012-06-06 17:09:28 -07002180 break;
2181 case JDWP::JT_ARRAY:
2182 case JDWP::JT_OBJECT:
2183 case JDWP::JT_STRING:
2184 {
2185 CHECK_EQ(width_, sizeof(JDWP::ObjectId));
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002186 mirror::Object* o = gRegistry->Get<mirror::Object*>(static_cast<JDWP::ObjectId>(value_));
Elliott Hughes64f574f2013-02-20 14:57:12 -08002187 if (o == ObjectRegistry::kInvalidObject) {
Ian Rogers0399dde2012-06-06 17:09:28 -07002188 UNIMPLEMENTED(FATAL) << "return an error code when given an invalid object to store";
2189 }
Ian Rogers2bcb4a42012-11-08 10:39:18 -08002190 SetVReg(m, reg, static_cast<uint32_t>(reinterpret_cast<uintptr_t>(o)), kReferenceVReg);
Ian Rogers0399dde2012-06-06 17:09:28 -07002191 }
2192 break;
2193 case JDWP::JT_DOUBLE:
Ian Rogers2bcb4a42012-11-08 10:39:18 -08002194 CHECK_EQ(width_, 8U);
2195 SetVReg(m, reg, static_cast<uint32_t>(value_), kDoubleLoVReg);
2196 SetVReg(m, reg + 1, static_cast<uint32_t>(value_ >> 32), kDoubleHiVReg);
2197 break;
Ian Rogers0399dde2012-06-06 17:09:28 -07002198 case JDWP::JT_LONG:
2199 CHECK_EQ(width_, 8U);
Ian Rogers2bcb4a42012-11-08 10:39:18 -08002200 SetVReg(m, reg, static_cast<uint32_t>(value_), kLongLoVReg);
2201 SetVReg(m, reg + 1, static_cast<uint32_t>(value_ >> 32), kLongHiVReg);
Ian Rogers0399dde2012-06-06 17:09:28 -07002202 break;
2203 default:
2204 LOG(FATAL) << "Unknown tag " << tag_;
2205 break;
2206 }
2207 return false;
2208 }
2209
2210 const JDWP::FrameId frame_id_;
2211 const int slot_;
2212 const JDWP::JdwpTag tag_;
2213 const uint64_t value_;
2214 const size_t width_;
2215 };
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002216
2217 ScopedObjectAccessUnchecked soa(Thread::Current());
jeffhaoa77f0f62012-12-05 17:19:31 -08002218 MutexLock mu(soa.Self(), *Locks::thread_list_lock_);
Elliott Hughes221229c2013-01-08 18:17:50 -08002219 Thread* thread;
2220 JDWP::JdwpError error = DecodeThread(soa, thread_id, thread);
2221 if (error != JDWP::ERR_NONE) {
2222 return;
2223 }
Elliott Hughes08fc03a2012-06-26 17:34:00 -07002224 UniquePtr<Context> context(Context::Create());
Ian Rogers7a22fa62013-01-23 12:16:16 -08002225 SetLocalVisitor visitor(thread, context.get(), frame_id, slot, tag, value, width);
Ian Rogers0399dde2012-06-06 17:09:28 -07002226 visitor.WalkStack();
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002227}
2228
Brian Carlstromea46f952013-07-30 01:26:50 -07002229void Dbg::PostLocationEvent(const mirror::ArtMethod* m, int dex_pc,
Ian Rogers62d6c772013-02-27 08:32:07 -08002230 mirror::Object* this_object, int event_flags) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002231 mirror::Class* c = m->GetDeclaringClass();
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08002232
2233 JDWP::JdwpLocation location;
Elliott Hughes74847412012-06-20 18:10:21 -07002234 location.type_tag = c->IsInterface() ? JDWP::TT_INTERFACE : JDWP::TT_CLASS;
Elliott Hughes64f574f2013-02-20 14:57:12 -08002235 location.class_id = gRegistry->AddRefType(c);
Elliott Hughes74847412012-06-20 18:10:21 -07002236 location.method_id = ToMethodId(m);
Elliott Hughes972a47b2012-02-21 18:16:06 -08002237 location.dex_pc = m->IsNative() ? -1 : dex_pc;
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08002238
Elliott Hughes64f574f2013-02-20 14:57:12 -08002239 // If 'this_object' isn't already in the registry, we know that we're not looking for it,
2240 // so there's no point adding it to the registry and burning through ids.
2241 JDWP::ObjectId this_id = 0;
2242 if (gRegistry->Contains(this_object)) {
2243 this_id = gRegistry->Add(this_object);
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08002244 }
Elliott Hughes64f574f2013-02-20 14:57:12 -08002245 gJdwpState->PostLocationEvent(&location, this_id, event_flags);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002246}
2247
Ian Rogers62d6c772013-02-27 08:32:07 -08002248void Dbg::PostException(Thread* thread, const ThrowLocation& throw_location,
Brian Carlstromea46f952013-07-30 01:26:50 -07002249 mirror::ArtMethod* catch_method,
Elliott Hughes64f574f2013-02-20 14:57:12 -08002250 uint32_t catch_dex_pc, mirror::Throwable* exception_object) {
Elliott Hughesc0f09332012-03-26 13:27:06 -07002251 if (!IsDebuggerActive()) {
Ian Rogers0ad5bb82011-12-07 10:16:32 -08002252 return;
2253 }
Elliott Hughes4740cdf2011-12-07 14:07:12 -08002254
Ian Rogers62d6c772013-02-27 08:32:07 -08002255 JDWP::JdwpLocation jdwp_throw_location;
2256 SetLocation(jdwp_throw_location, throw_location.GetMethod(), throw_location.GetDexPc());
Elliott Hughesd07986f2011-12-06 18:27:45 -08002257 JDWP::JdwpLocation catch_location;
Elliott Hughescaf76542012-06-28 16:08:22 -07002258 SetLocation(catch_location, catch_method, catch_dex_pc);
Elliott Hughesd07986f2011-12-06 18:27:45 -08002259
2260 // We need 'this' for InstanceOnly filters.
Ian Rogers62d6c772013-02-27 08:32:07 -08002261 JDWP::ObjectId this_id = gRegistry->Add(throw_location.GetThis());
Elliott Hughes64f574f2013-02-20 14:57:12 -08002262 JDWP::ObjectId exception_id = gRegistry->Add(exception_object);
2263 JDWP::RefTypeId exception_class_id = gRegistry->AddRefType(exception_object->GetClass());
Elliott Hughesd07986f2011-12-06 18:27:45 -08002264
Ian Rogers62d6c772013-02-27 08:32:07 -08002265 gJdwpState->PostException(&jdwp_throw_location, exception_id, exception_class_id, &catch_location,
2266 this_id);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002267}
2268
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002269void Dbg::PostClassPrepare(mirror::Class* c) {
Elliott Hughesc0f09332012-03-26 13:27:06 -07002270 if (!IsDebuggerActive()) {
Elliott Hughes4740cdf2011-12-07 14:07:12 -08002271 return;
2272 }
2273
Elliott Hughes3d30d9b2011-12-07 17:35:48 -08002274 // OLD-TODO - we currently always send both "verified" and "prepared" since
Elliott Hughes4740cdf2011-12-07 14:07:12 -08002275 // debuggers seem to like that. There might be some advantage to honesty,
2276 // since the class may not yet be verified.
2277 int state = JDWP::CS_VERIFIED | JDWP::CS_PREPARED;
2278 JDWP::JdwpTypeTag tag = c->IsInterface() ? JDWP::TT_INTERFACE : JDWP::TT_CLASS;
Ian Rogersfc0e94b2013-09-23 23:51:32 -07002279 gJdwpState->PostClassPrepare(tag, gRegistry->Add(c),
Ian Rogersdfb325e2013-10-30 01:00:44 -07002280 ClassHelper(c).GetDescriptor(), state);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002281}
2282
Ian Rogers62d6c772013-02-27 08:32:07 -08002283void Dbg::UpdateDebugger(Thread* thread, mirror::Object* this_object,
Brian Carlstromea46f952013-07-30 01:26:50 -07002284 const mirror::ArtMethod* m, uint32_t dex_pc) {
Ian Rogers62d6c772013-02-27 08:32:07 -08002285 if (!IsDebuggerActive() || dex_pc == static_cast<uint32_t>(-2) /* fake method exit */) {
Elliott Hughes2aa2e392012-02-17 17:15:43 -08002286 return;
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08002287 }
2288
Elliott Hughes2aa2e392012-02-17 17:15:43 -08002289 int event_flags = 0;
2290
Elliott Hughes86964332012-02-15 19:37:42 -08002291 if (IsBreakpoint(m, dex_pc)) {
2292 event_flags |= kBreakpoint;
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08002293 }
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08002294
jeffhao09bfc6a2012-12-11 18:11:43 -08002295 {
2296 // If the debugger is single-stepping one of our threads, check to
2297 // see if we're that thread and we've reached a step point.
2298 MutexLock mu(Thread::Current(), *Locks::breakpoint_lock_);
Ian Rogers62d6c772013-02-27 08:32:07 -08002299 if (gSingleStepControl.is_active && gSingleStepControl.thread == thread) {
jeffhao09bfc6a2012-12-11 18:11:43 -08002300 CHECK(!m->IsNative());
2301 if (gSingleStepControl.step_depth == JDWP::SD_INTO) {
2302 // Step into method calls. We break when the line number
2303 // or method pointer changes. If we're in SS_MIN mode, we
2304 // always stop.
2305 if (gSingleStepControl.method != m) {
2306 event_flags |= kSingleStep;
2307 VLOG(jdwp) << "SS new method";
2308 } else if (gSingleStepControl.step_size == JDWP::SS_MIN) {
Elliott Hughes86964332012-02-15 19:37:42 -08002309 event_flags |= kSingleStep;
2310 VLOG(jdwp) << "SS new instruction";
Elliott Hughes2435a572012-02-17 16:07:41 -08002311 } else if (gSingleStepControl.dex_pcs.find(dex_pc) == gSingleStepControl.dex_pcs.end()) {
2312 event_flags |= kSingleStep;
2313 VLOG(jdwp) << "SS new line";
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08002314 }
jeffhao09bfc6a2012-12-11 18:11:43 -08002315 } else if (gSingleStepControl.step_depth == JDWP::SD_OVER) {
2316 // Step over method calls. We break when the line number is
2317 // different and the frame depth is <= the original frame
2318 // depth. (We can't just compare on the method, because we
2319 // might get unrolled past it by an exception, and it's tricky
2320 // to identify recursion.)
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08002321
Ian Rogers62d6c772013-02-27 08:32:07 -08002322 int stack_depth = GetStackDepth(thread);
Elliott Hughes86964332012-02-15 19:37:42 -08002323
jeffhao09bfc6a2012-12-11 18:11:43 -08002324 if (stack_depth < gSingleStepControl.stack_depth) {
2325 // popped up one or more frames, always trigger
2326 event_flags |= kSingleStep;
2327 VLOG(jdwp) << "SS method pop";
2328 } else if (stack_depth == gSingleStepControl.stack_depth) {
2329 // same depth, see if we moved
2330 if (gSingleStepControl.step_size == JDWP::SS_MIN) {
2331 event_flags |= kSingleStep;
2332 VLOG(jdwp) << "SS new instruction";
2333 } else if (gSingleStepControl.dex_pcs.find(dex_pc) == gSingleStepControl.dex_pcs.end()) {
2334 event_flags |= kSingleStep;
2335 VLOG(jdwp) << "SS new line";
2336 }
2337 }
2338 } else {
2339 CHECK_EQ(gSingleStepControl.step_depth, JDWP::SD_OUT);
2340 // Return from the current method. We break when the frame
2341 // depth pops up.
2342
2343 // This differs from the "method exit" break in that it stops
2344 // with the PC at the next instruction in the returned-to
2345 // function, rather than the end of the returning function.
2346
Ian Rogers62d6c772013-02-27 08:32:07 -08002347 int stack_depth = GetStackDepth(thread);
jeffhao09bfc6a2012-12-11 18:11:43 -08002348 if (stack_depth < gSingleStepControl.stack_depth) {
2349 event_flags |= kSingleStep;
2350 VLOG(jdwp) << "SS method pop";
2351 }
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08002352 }
2353 }
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08002354 }
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08002355
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08002356 // If there's something interesting going on, see if it matches one
2357 // of the debugger filters.
2358 if (event_flags != 0) {
Ian Rogers62d6c772013-02-27 08:32:07 -08002359 Dbg::PostLocationEvent(m, dex_pc, this_object, event_flags);
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08002360 }
2361}
2362
Elliott Hughes86964332012-02-15 19:37:42 -08002363void Dbg::WatchLocation(const JDWP::JdwpLocation* location) {
jeffhao09bfc6a2012-12-11 18:11:43 -08002364 MutexLock mu(Thread::Current(), *Locks::breakpoint_lock_);
Brian Carlstromea46f952013-07-30 01:26:50 -07002365 mirror::ArtMethod* m = FromMethodId(location->method_id);
Elliott Hughes972a47b2012-02-21 18:16:06 -08002366 gBreakpoints.push_back(Breakpoint(m, location->dex_pc));
Elliott Hughes86964332012-02-15 19:37:42 -08002367 VLOG(jdwp) << "Set breakpoint #" << (gBreakpoints.size() - 1) << ": " << gBreakpoints[gBreakpoints.size() - 1];
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002368}
2369
Elliott Hughes86964332012-02-15 19:37:42 -08002370void Dbg::UnwatchLocation(const JDWP::JdwpLocation* location) {
jeffhao09bfc6a2012-12-11 18:11:43 -08002371 MutexLock mu(Thread::Current(), *Locks::breakpoint_lock_);
Brian Carlstromea46f952013-07-30 01:26:50 -07002372 mirror::ArtMethod* m = FromMethodId(location->method_id);
Elliott Hughes86964332012-02-15 19:37:42 -08002373 for (size_t i = 0; i < gBreakpoints.size(); ++i) {
Elliott Hughes972a47b2012-02-21 18:16:06 -08002374 if (gBreakpoints[i].method == m && gBreakpoints[i].dex_pc == location->dex_pc) {
Elliott Hughes86964332012-02-15 19:37:42 -08002375 VLOG(jdwp) << "Removed breakpoint #" << i << ": " << gBreakpoints[i];
2376 gBreakpoints.erase(gBreakpoints.begin() + i);
2377 return;
2378 }
2379 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002380}
2381
Jeff Hao449db332013-04-12 18:30:52 -07002382// Scoped utility class to suspend a thread so that we may do tasks such as walk its stack. Doesn't
2383// cause suspension if the thread is the current thread.
2384class ScopedThreadSuspension {
2385 public:
Ian Rogers33e95662013-05-20 20:29:14 -07002386 ScopedThreadSuspension(Thread* self, JDWP::ObjectId thread_id)
2387 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) :
Jeff Hao449db332013-04-12 18:30:52 -07002388 thread_(NULL),
2389 error_(JDWP::ERR_NONE),
2390 self_suspend_(false),
Ian Rogers33e95662013-05-20 20:29:14 -07002391 other_suspend_(false) {
Jeff Hao449db332013-04-12 18:30:52 -07002392 ScopedObjectAccessUnchecked soa(self);
2393 {
2394 MutexLock mu(soa.Self(), *Locks::thread_list_lock_);
2395 error_ = DecodeThread(soa, thread_id, thread_);
2396 }
2397 if (error_ == JDWP::ERR_NONE) {
2398 if (thread_ == soa.Self()) {
2399 self_suspend_ = true;
2400 } else {
2401 soa.Self()->TransitionFromRunnableToSuspended(kWaitingForDebuggerSuspension);
2402 jobject thread_peer = gRegistry->GetJObject(thread_id);
2403 bool timed_out;
Ian Rogersd9c4fc92013-10-01 19:45:43 -07002404 Thread* suspended_thread = ThreadList::SuspendThreadByPeer(thread_peer, true, true,
2405 &timed_out);
Jeff Hao449db332013-04-12 18:30:52 -07002406 CHECK_EQ(soa.Self()->TransitionFromSuspendedToRunnable(), kWaitingForDebuggerSuspension);
2407 if (suspended_thread == NULL) {
2408 // Thread terminated from under us while suspending.
2409 error_ = JDWP::ERR_INVALID_THREAD;
2410 } else {
2411 CHECK_EQ(suspended_thread, thread_);
2412 other_suspend_ = true;
2413 }
2414 }
2415 }
Elliott Hughes2435a572012-02-17 16:07:41 -08002416 }
Elliott Hughes86964332012-02-15 19:37:42 -08002417
Jeff Hao449db332013-04-12 18:30:52 -07002418 Thread* GetThread() const {
2419 return thread_;
2420 }
2421
2422 JDWP::JdwpError GetError() const {
2423 return error_;
2424 }
2425
2426 ~ScopedThreadSuspension() {
2427 if (other_suspend_) {
2428 Runtime::Current()->GetThreadList()->Resume(thread_, true);
2429 }
2430 }
2431
2432 private:
2433 Thread* thread_;
2434 JDWP::JdwpError error_;
2435 bool self_suspend_;
2436 bool other_suspend_;
2437};
2438
2439JDWP::JdwpError Dbg::ConfigureStep(JDWP::ObjectId thread_id, JDWP::JdwpStepSize step_size,
2440 JDWP::JdwpStepDepth step_depth) {
2441 Thread* self = Thread::Current();
2442 ScopedThreadSuspension sts(self, thread_id);
2443 if (sts.GetError() != JDWP::ERR_NONE) {
2444 return sts.GetError();
2445 }
2446
2447 MutexLock mu2(self, *Locks::breakpoint_lock_);
Elliott Hughes86964332012-02-15 19:37:42 -08002448 // TODO: there's no theoretical reason why we couldn't support single-stepping
2449 // of multiple threads at once, but we never did so historically.
Jeff Hao449db332013-04-12 18:30:52 -07002450 if (gSingleStepControl.thread != NULL && sts.GetThread() != gSingleStepControl.thread) {
Elliott Hughes86964332012-02-15 19:37:42 -08002451 LOG(WARNING) << "single-step already active for " << *gSingleStepControl.thread
Jeff Hao449db332013-04-12 18:30:52 -07002452 << "; switching to " << *sts.GetThread();
Elliott Hughes86964332012-02-15 19:37:42 -08002453 }
2454
Elliott Hughes2435a572012-02-17 16:07:41 -08002455 //
2456 // Work out what Method* we're in, the current line number, and how deep the stack currently
2457 // is for step-out.
2458 //
2459
Ian Rogers0399dde2012-06-06 17:09:28 -07002460 struct SingleStepStackVisitor : public StackVisitor {
Brian Carlstrom93ba8932013-07-17 21:31:49 -07002461 explicit SingleStepStackVisitor(Thread* thread)
jeffhao09bfc6a2012-12-11 18:11:43 -08002462 EXCLUSIVE_LOCKS_REQUIRED(Locks::breakpoint_lock_)
Ian Rogersb726dcb2012-09-05 08:57:23 -07002463 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_)
Ian Rogers7a22fa62013-01-23 12:16:16 -08002464 : StackVisitor(thread, NULL) {
Elliott Hughes86964332012-02-15 19:37:42 -08002465 gSingleStepControl.method = NULL;
2466 gSingleStepControl.stack_depth = 0;
2467 }
Ian Rogersca190662012-06-26 15:45:57 -07002468
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002469 // TODO: Enable annotalysis. We know lock is held in constructor, but abstraction confuses
2470 // annotalysis.
2471 bool VisitFrame() NO_THREAD_SAFETY_ANALYSIS {
jeffhao09bfc6a2012-12-11 18:11:43 -08002472 Locks::breakpoint_lock_->AssertHeld(Thread::Current());
Brian Carlstromea46f952013-07-30 01:26:50 -07002473 const mirror::ArtMethod* m = GetMethod();
Ian Rogers0399dde2012-06-06 17:09:28 -07002474 if (!m->IsRuntimeMethod()) {
Elliott Hughes86964332012-02-15 19:37:42 -08002475 ++gSingleStepControl.stack_depth;
2476 if (gSingleStepControl.method == NULL) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002477 const mirror::DexCache* dex_cache = m->GetDeclaringClass()->GetDexCache();
Elliott Hughes2435a572012-02-17 16:07:41 -08002478 gSingleStepControl.method = m;
2479 gSingleStepControl.line_number = -1;
2480 if (dex_cache != NULL) {
Ian Rogers4445a7e2012-10-05 17:19:13 -07002481 const DexFile& dex_file = *dex_cache->GetDexFile();
Ian Rogers0399dde2012-06-06 17:09:28 -07002482 gSingleStepControl.line_number = dex_file.GetLineNumFromPC(m, GetDexPc());
Elliott Hughes2435a572012-02-17 16:07:41 -08002483 }
Elliott Hughes86964332012-02-15 19:37:42 -08002484 }
2485 }
Elliott Hughes530fa002012-03-12 11:44:49 -07002486 return true;
Elliott Hughes86964332012-02-15 19:37:42 -08002487 }
2488 };
Jeff Hao449db332013-04-12 18:30:52 -07002489
2490 SingleStepStackVisitor visitor(sts.GetThread());
Ian Rogers0399dde2012-06-06 17:09:28 -07002491 visitor.WalkStack();
Elliott Hughes86964332012-02-15 19:37:42 -08002492
Elliott Hughes2435a572012-02-17 16:07:41 -08002493 //
2494 // Find the dex_pc values that correspond to the current line, for line-based single-stepping.
2495 //
2496
2497 struct DebugCallbackContext {
jeffhao09bfc6a2012-12-11 18:11:43 -08002498 DebugCallbackContext() EXCLUSIVE_LOCKS_REQUIRED(Locks::breakpoint_lock_) {
Elliott Hughes2435a572012-02-17 16:07:41 -08002499 last_pc_valid = false;
2500 last_pc = 0;
Elliott Hughes2435a572012-02-17 16:07:41 -08002501 }
2502
jeffhao09bfc6a2012-12-11 18:11:43 -08002503 // TODO: Enable annotalysis. We know lock is held in constructor, but abstraction confuses
2504 // annotalysis.
2505 static bool Callback(void* raw_context, uint32_t address, uint32_t line_number) NO_THREAD_SAFETY_ANALYSIS {
2506 Locks::breakpoint_lock_->AssertHeld(Thread::Current());
Elliott Hughes2435a572012-02-17 16:07:41 -08002507 DebugCallbackContext* context = reinterpret_cast<DebugCallbackContext*>(raw_context);
2508 if (static_cast<int32_t>(line_number) == gSingleStepControl.line_number) {
2509 if (!context->last_pc_valid) {
2510 // Everything from this address until the next line change is ours.
2511 context->last_pc = address;
2512 context->last_pc_valid = true;
2513 }
2514 // Otherwise, if we're already in a valid range for this line,
2515 // just keep going (shouldn't really happen)...
Brian Carlstrom7934ac22013-07-26 10:54:15 -07002516 } else if (context->last_pc_valid) { // and the line number is new
Elliott Hughes2435a572012-02-17 16:07:41 -08002517 // Add everything from the last entry up until here to the set
2518 for (uint32_t dex_pc = context->last_pc; dex_pc < address; ++dex_pc) {
2519 gSingleStepControl.dex_pcs.insert(dex_pc);
2520 }
2521 context->last_pc_valid = false;
2522 }
Brian Carlstrom7934ac22013-07-26 10:54:15 -07002523 return false; // There may be multiple entries for any given line.
Elliott Hughes2435a572012-02-17 16:07:41 -08002524 }
2525
jeffhao09bfc6a2012-12-11 18:11:43 -08002526 // TODO: Enable annotalysis. We know lock is held in constructor, but abstraction confuses
2527 // annotalysis.
2528 ~DebugCallbackContext() NO_THREAD_SAFETY_ANALYSIS {
2529 Locks::breakpoint_lock_->AssertHeld(Thread::Current());
Elliott Hughes2435a572012-02-17 16:07:41 -08002530 // If the line number was the last in the position table...
2531 if (last_pc_valid) {
2532 size_t end = MethodHelper(gSingleStepControl.method).GetCodeItem()->insns_size_in_code_units_;
2533 for (uint32_t dex_pc = last_pc; dex_pc < end; ++dex_pc) {
2534 gSingleStepControl.dex_pcs.insert(dex_pc);
2535 }
2536 }
2537 }
2538
2539 bool last_pc_valid;
2540 uint32_t last_pc;
2541 };
Elliott Hughes3e2e1a22012-02-21 11:33:41 -08002542 gSingleStepControl.dex_pcs.clear();
Brian Carlstromea46f952013-07-30 01:26:50 -07002543 const mirror::ArtMethod* m = gSingleStepControl.method;
Elliott Hughes3e2e1a22012-02-21 11:33:41 -08002544 if (m->IsNative()) {
2545 gSingleStepControl.line_number = -1;
2546 } else {
2547 DebugCallbackContext context;
2548 MethodHelper mh(m);
2549 mh.GetDexFile().DecodeDebugInfo(mh.GetCodeItem(), m->IsStatic(), m->GetDexMethodIndex(),
2550 DebugCallbackContext::Callback, NULL, &context);
2551 }
Elliott Hughes2435a572012-02-17 16:07:41 -08002552
2553 //
2554 // Everything else...
2555 //
2556
Jeff Hao449db332013-04-12 18:30:52 -07002557 gSingleStepControl.thread = sts.GetThread();
Elliott Hughes86964332012-02-15 19:37:42 -08002558 gSingleStepControl.step_size = step_size;
2559 gSingleStepControl.step_depth = step_depth;
2560 gSingleStepControl.is_active = true;
2561
Elliott Hughes2435a572012-02-17 16:07:41 -08002562 if (VLOG_IS_ON(jdwp)) {
2563 VLOG(jdwp) << "Single-step thread: " << *gSingleStepControl.thread;
2564 VLOG(jdwp) << "Single-step step size: " << gSingleStepControl.step_size;
2565 VLOG(jdwp) << "Single-step step depth: " << gSingleStepControl.step_depth;
2566 VLOG(jdwp) << "Single-step current method: " << PrettyMethod(gSingleStepControl.method);
2567 VLOG(jdwp) << "Single-step current line: " << gSingleStepControl.line_number;
2568 VLOG(jdwp) << "Single-step current stack depth: " << gSingleStepControl.stack_depth;
2569 VLOG(jdwp) << "Single-step dex_pc values:";
2570 for (std::set<uint32_t>::iterator it = gSingleStepControl.dex_pcs.begin() ; it != gSingleStepControl.dex_pcs.end(); ++it) {
Elliott Hughes229feb72012-02-23 13:33:29 -08002571 VLOG(jdwp) << StringPrintf(" %#x", *it);
Elliott Hughes2435a572012-02-17 16:07:41 -08002572 }
2573 }
2574
2575 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002576}
2577
Elliott Hughes221229c2013-01-08 18:17:50 -08002578void Dbg::UnconfigureStep(JDWP::ObjectId /*thread_id*/) {
jeffhao09bfc6a2012-12-11 18:11:43 -08002579 MutexLock mu(Thread::Current(), *Locks::breakpoint_lock_);
Elliott Hughesf8349362012-06-18 15:00:06 -07002580
Elliott Hughes86964332012-02-15 19:37:42 -08002581 gSingleStepControl.is_active = false;
2582 gSingleStepControl.thread = NULL;
Elliott Hughes2435a572012-02-17 16:07:41 -08002583 gSingleStepControl.dex_pcs.clear();
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002584}
2585
Elliott Hughes45651fd2012-02-21 15:48:20 -08002586static char JdwpTagToShortyChar(JDWP::JdwpTag tag) {
2587 switch (tag) {
2588 default:
2589 LOG(FATAL) << "unknown JDWP tag: " << PrintableChar(tag);
2590
2591 // Primitives.
2592 case JDWP::JT_BYTE: return 'B';
2593 case JDWP::JT_CHAR: return 'C';
2594 case JDWP::JT_FLOAT: return 'F';
2595 case JDWP::JT_DOUBLE: return 'D';
2596 case JDWP::JT_INT: return 'I';
2597 case JDWP::JT_LONG: return 'J';
2598 case JDWP::JT_SHORT: return 'S';
2599 case JDWP::JT_VOID: return 'V';
2600 case JDWP::JT_BOOLEAN: return 'Z';
2601
2602 // Reference types.
2603 case JDWP::JT_ARRAY:
2604 case JDWP::JT_OBJECT:
2605 case JDWP::JT_STRING:
2606 case JDWP::JT_THREAD:
2607 case JDWP::JT_THREAD_GROUP:
2608 case JDWP::JT_CLASS_LOADER:
2609 case JDWP::JT_CLASS_OBJECT:
2610 return 'L';
2611 }
2612}
2613
Elliott Hughes88d63092013-01-09 09:55:54 -08002614JDWP::JdwpError Dbg::InvokeMethod(JDWP::ObjectId thread_id, JDWP::ObjectId object_id,
2615 JDWP::RefTypeId class_id, JDWP::MethodId method_id,
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002616 uint32_t arg_count, uint64_t* arg_values,
2617 JDWP::JdwpTag* arg_types, uint32_t options,
2618 JDWP::JdwpTag* pResultTag, uint64_t* pResultValue,
2619 JDWP::ObjectId* pExceptionId) {
Elliott Hughesd07986f2011-12-06 18:27:45 -08002620 ThreadList* thread_list = Runtime::Current()->GetThreadList();
2621
2622 Thread* targetThread = NULL;
2623 DebugInvokeReq* req = NULL;
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002624 Thread* self = Thread::Current();
Elliott Hughesd07986f2011-12-06 18:27:45 -08002625 {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002626 ScopedObjectAccessUnchecked soa(self);
Ian Rogers50b35e22012-10-04 10:09:15 -07002627 MutexLock mu(soa.Self(), *Locks::thread_list_lock_);
Elliott Hughes221229c2013-01-08 18:17:50 -08002628 JDWP::JdwpError error = DecodeThread(soa, thread_id, targetThread);
2629 if (error != JDWP::ERR_NONE) {
2630 LOG(ERROR) << "InvokeMethod request for invalid thread id " << thread_id;
2631 return error;
Elliott Hughesd07986f2011-12-06 18:27:45 -08002632 }
2633 req = targetThread->GetInvokeReq();
2634 if (!req->ready) {
2635 LOG(ERROR) << "InvokeMethod request for thread not stopped by event: " << *targetThread;
2636 return JDWP::ERR_INVALID_THREAD;
2637 }
2638
2639 /*
2640 * We currently have a bug where we don't successfully resume the
2641 * target thread if the suspend count is too deep. We're expected to
2642 * require one "resume" for each "suspend", but when asked to execute
2643 * a method we have to resume fully and then re-suspend it back to the
2644 * same level. (The easiest way to cause this is to type "suspend"
2645 * multiple times in jdb.)
2646 *
2647 * It's unclear what this means when the event specifies "resume all"
2648 * and some threads are suspended more deeply than others. This is
2649 * a rare problem, so for now we just prevent it from hanging forever
2650 * by rejecting the method invocation request. Without this, we will
2651 * be stuck waiting on a suspended thread.
2652 */
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002653 int suspend_count;
2654 {
Ian Rogers50b35e22012-10-04 10:09:15 -07002655 MutexLock mu2(soa.Self(), *Locks::thread_suspend_count_lock_);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002656 suspend_count = targetThread->GetSuspendCount();
2657 }
Elliott Hughesd07986f2011-12-06 18:27:45 -08002658 if (suspend_count > 1) {
2659 LOG(ERROR) << *targetThread << " suspend count too deep for method invocation: " << suspend_count;
Brian Carlstrom7934ac22013-07-26 10:54:15 -07002660 return JDWP::ERR_THREAD_SUSPENDED; // Probably not expected here.
Elliott Hughesd07986f2011-12-06 18:27:45 -08002661 }
2662
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08002663 JDWP::JdwpError status;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002664 mirror::Object* receiver = gRegistry->Get<mirror::Object*>(object_id);
Elliott Hughes64f574f2013-02-20 14:57:12 -08002665 if (receiver == ObjectRegistry::kInvalidObject) {
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08002666 return JDWP::ERR_INVALID_OBJECT;
2667 }
Elliott Hughes45651fd2012-02-21 15:48:20 -08002668
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002669 mirror::Object* thread = gRegistry->Get<mirror::Object*>(thread_id);
Elliott Hughes64f574f2013-02-20 14:57:12 -08002670 if (thread == ObjectRegistry::kInvalidObject) {
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08002671 return JDWP::ERR_INVALID_OBJECT;
2672 }
Elliott Hughes45651fd2012-02-21 15:48:20 -08002673 // TODO: check that 'thread' is actually a java.lang.Thread!
2674
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002675 mirror::Class* c = DecodeClass(class_id, status);
Elliott Hughes45651fd2012-02-21 15:48:20 -08002676 if (c == NULL) {
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08002677 return status;
2678 }
Elliott Hughes45651fd2012-02-21 15:48:20 -08002679
Brian Carlstromea46f952013-07-30 01:26:50 -07002680 mirror::ArtMethod* m = FromMethodId(method_id);
Elliott Hughes45651fd2012-02-21 15:48:20 -08002681 if (m->IsStatic() != (receiver == NULL)) {
2682 return JDWP::ERR_INVALID_METHODID;
2683 }
2684 if (m->IsStatic()) {
2685 if (m->GetDeclaringClass() != c) {
2686 return JDWP::ERR_INVALID_METHODID;
2687 }
2688 } else {
2689 if (!m->GetDeclaringClass()->IsAssignableFrom(c)) {
2690 return JDWP::ERR_INVALID_METHODID;
2691 }
2692 }
2693
2694 // Check the argument list matches the method.
2695 MethodHelper mh(m);
2696 if (mh.GetShortyLength() - 1 != arg_count) {
2697 return JDWP::ERR_ILLEGAL_ARGUMENT;
2698 }
2699 const char* shorty = mh.GetShorty();
Elliott Hughes09201632013-04-15 15:50:07 -07002700 const DexFile::TypeList* types = mh.GetParameterTypeList();
Elliott Hughes45651fd2012-02-21 15:48:20 -08002701 for (size_t i = 0; i < arg_count; ++i) {
2702 if (shorty[i + 1] != JdwpTagToShortyChar(arg_types[i])) {
2703 return JDWP::ERR_ILLEGAL_ARGUMENT;
2704 }
Elliott Hughes09201632013-04-15 15:50:07 -07002705
2706 if (shorty[i + 1] == 'L') {
2707 // Did we really get an argument of an appropriate reference type?
2708 mirror::Class* parameter_type = mh.GetClassFromTypeIdx(types->GetTypeItem(i).type_idx_);
2709 mirror::Object* argument = gRegistry->Get<mirror::Object*>(arg_values[i]);
2710 if (argument == ObjectRegistry::kInvalidObject) {
2711 return JDWP::ERR_INVALID_OBJECT;
2712 }
2713 if (!argument->InstanceOf(parameter_type)) {
2714 return JDWP::ERR_ILLEGAL_ARGUMENT;
2715 }
2716
2717 // Turn the on-the-wire ObjectId into a jobject.
2718 jvalue& v = reinterpret_cast<jvalue&>(arg_values[i]);
2719 v.l = gRegistry->GetJObject(arg_values[i]);
2720 }
Elliott Hughes45651fd2012-02-21 15:48:20 -08002721 }
2722
2723 req->receiver_ = receiver;
2724 req->thread_ = thread;
2725 req->class_ = c;
2726 req->method_ = m;
2727 req->arg_count_ = arg_count;
2728 req->arg_values_ = arg_values;
Elliott Hughesd07986f2011-12-06 18:27:45 -08002729 req->options_ = options;
2730 req->invoke_needed_ = true;
2731 }
2732
2733 // The fact that we've released the thread list lock is a bit risky --- if the thread goes
2734 // away we're sitting high and dry -- but we must release this before the ResumeAllThreads
2735 // call, and it's unwise to hold it during WaitForSuspend.
2736
2737 {
2738 /*
2739 * We change our (JDWP thread) status, which should be THREAD_RUNNING,
Elliott Hughes81ff3182012-03-23 20:35:56 -07002740 * so we can suspend for a GC if the invoke request causes us to
Elliott Hughesd07986f2011-12-06 18:27:45 -08002741 * run out of memory. It's also a good idea to change it before locking
2742 * the invokeReq mutex, although that should never be held for long.
2743 */
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002744 self->TransitionFromRunnableToSuspended(kWaitingForDebuggerSend);
Elliott Hughesd07986f2011-12-06 18:27:45 -08002745
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08002746 VLOG(jdwp) << " Transferring control to event thread";
Elliott Hughesd07986f2011-12-06 18:27:45 -08002747 {
Ian Rogers50b35e22012-10-04 10:09:15 -07002748 MutexLock mu(self, req->lock_);
Elliott Hughesd07986f2011-12-06 18:27:45 -08002749
2750 if ((options & JDWP::INVOKE_SINGLE_THREADED) == 0) {
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08002751 VLOG(jdwp) << " Resuming all threads";
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002752 thread_list->UndoDebuggerSuspensions();
Elliott Hughesd07986f2011-12-06 18:27:45 -08002753 } else {
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08002754 VLOG(jdwp) << " Resuming event thread only";
Elliott Hughesd07986f2011-12-06 18:27:45 -08002755 thread_list->Resume(targetThread, true);
2756 }
2757
2758 // Wait for the request to finish executing.
2759 while (req->invoke_needed_) {
Ian Rogersc604d732012-10-14 16:09:54 -07002760 req->cond_.Wait(self);
Elliott Hughesd07986f2011-12-06 18:27:45 -08002761 }
2762 }
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08002763 VLOG(jdwp) << " Control has returned from event thread";
Elliott Hughesd07986f2011-12-06 18:27:45 -08002764
2765 /* wait for thread to re-suspend itself */
Brian Carlstromdf629502013-07-17 22:39:56 -07002766 SuspendThread(thread_id, false /* request_suspension */);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002767 self->TransitionFromSuspendedToRunnable();
Elliott Hughesd07986f2011-12-06 18:27:45 -08002768 }
2769
2770 /*
2771 * Suspend the threads. We waited for the target thread to suspend
2772 * itself, so all we need to do is suspend the others.
2773 *
2774 * The suspendAllThreads() call will double-suspend the event thread,
2775 * so we want to resume the target thread once to keep the books straight.
2776 */
2777 if ((options & JDWP::INVOKE_SINGLE_THREADED) == 0) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002778 self->TransitionFromRunnableToSuspended(kWaitingForDebuggerSuspension);
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08002779 VLOG(jdwp) << " Suspending all threads";
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002780 thread_list->SuspendAllForDebugger();
2781 self->TransitionFromSuspendedToRunnable();
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08002782 VLOG(jdwp) << " Resuming event thread to balance the count";
Elliott Hughesd07986f2011-12-06 18:27:45 -08002783 thread_list->Resume(targetThread, true);
2784 }
2785
2786 // Copy the result.
2787 *pResultTag = req->result_tag;
2788 if (IsPrimitiveTag(req->result_tag)) {
Elliott Hughesf24d3ce2012-04-11 17:43:37 -07002789 *pResultValue = req->result_value.GetJ();
Elliott Hughesd07986f2011-12-06 18:27:45 -08002790 } else {
Elliott Hughesf24d3ce2012-04-11 17:43:37 -07002791 *pResultValue = gRegistry->Add(req->result_value.GetL());
Elliott Hughesd07986f2011-12-06 18:27:45 -08002792 }
2793 *pExceptionId = req->exception;
2794 return req->error;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002795}
2796
2797void Dbg::ExecuteMethod(DebugInvokeReq* pReq) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002798 ScopedObjectAccess soa(Thread::Current());
Elliott Hughesd07986f2011-12-06 18:27:45 -08002799
Elliott Hughes81ff3182012-03-23 20:35:56 -07002800 // We can be called while an exception is pending. We need
Elliott Hughesd07986f2011-12-06 18:27:45 -08002801 // to preserve that across the method invocation.
Ian Rogers62d6c772013-02-27 08:32:07 -08002802 SirtRef<mirror::Object> old_throw_this_object(soa.Self(), NULL);
Brian Carlstromea46f952013-07-30 01:26:50 -07002803 SirtRef<mirror::ArtMethod> old_throw_method(soa.Self(), NULL);
Ian Rogers62d6c772013-02-27 08:32:07 -08002804 SirtRef<mirror::Throwable> old_exception(soa.Self(), NULL);
2805 uint32_t old_throw_dex_pc;
2806 {
2807 ThrowLocation old_throw_location;
2808 mirror::Throwable* old_exception_obj = soa.Self()->GetException(&old_throw_location);
2809 old_throw_this_object.reset(old_throw_location.GetThis());
2810 old_throw_method.reset(old_throw_location.GetMethod());
2811 old_exception.reset(old_exception_obj);
2812 old_throw_dex_pc = old_throw_location.GetDexPc();
2813 soa.Self()->ClearException();
2814 }
Elliott Hughesd07986f2011-12-06 18:27:45 -08002815
2816 // Translate the method through the vtable, unless the debugger wants to suppress it.
Brian Carlstromea46f952013-07-30 01:26:50 -07002817 mirror::ArtMethod* m = pReq->method_;
Elliott Hughesd07986f2011-12-06 18:27:45 -08002818 if ((pReq->options_ & JDWP::INVOKE_NONVIRTUAL) == 0 && pReq->receiver_ != NULL) {
Brian Carlstromea46f952013-07-30 01:26:50 -07002819 mirror::ArtMethod* actual_method = pReq->class_->FindVirtualMethodForVirtualOrInterface(pReq->method_);
Elliott Hughes45651fd2012-02-21 15:48:20 -08002820 if (actual_method != m) {
2821 VLOG(jdwp) << "ExecuteMethod translated " << PrettyMethod(m) << " to " << PrettyMethod(actual_method);
2822 m = actual_method;
2823 }
Elliott Hughesd07986f2011-12-06 18:27:45 -08002824 }
Elliott Hughescfa9cfa2013-04-16 16:52:01 -07002825 VLOG(jdwp) << "ExecuteMethod " << PrettyMethod(m)
2826 << " receiver=" << pReq->receiver_
2827 << " arg_count=" << pReq->arg_count_;
Elliott Hughesd07986f2011-12-06 18:27:45 -08002828 CHECK(m != NULL);
2829
2830 CHECK_EQ(sizeof(jvalue), sizeof(uint64_t));
2831
Jeff Hao5d917302013-02-27 17:57:33 -08002832 MethodHelper mh(m);
2833 ArgArray arg_array(mh.GetShorty(), mh.GetShortyLength());
2834 arg_array.BuildArgArray(soa, pReq->receiver_, reinterpret_cast<jvalue*>(pReq->arg_values_));
Jeff Hao6474d192013-03-26 14:08:09 -07002835 InvokeWithArgArray(soa, m, &arg_array, &pReq->result_value, mh.GetShorty()[0]);
Elliott Hughesd07986f2011-12-06 18:27:45 -08002836
Ian Rogers62d6c772013-02-27 08:32:07 -08002837 mirror::Throwable* exception = soa.Self()->GetException(NULL);
2838 soa.Self()->ClearException();
2839 pReq->exception = gRegistry->Add(exception);
Elliott Hughesd07986f2011-12-06 18:27:45 -08002840 pReq->result_tag = BasicTagFromDescriptor(MethodHelper(m).GetShorty());
2841 if (pReq->exception != 0) {
Ian Rogers62d6c772013-02-27 08:32:07 -08002842 VLOG(jdwp) << " JDWP invocation returning with exception=" << exception
2843 << " " << exception->Dump();
Elliott Hughesf24d3ce2012-04-11 17:43:37 -07002844 pReq->result_value.SetJ(0);
Elliott Hughesd07986f2011-12-06 18:27:45 -08002845 } else if (pReq->result_tag == JDWP::JT_OBJECT) {
2846 /* if no exception thrown, examine object result more closely */
Elliott Hughesf24d3ce2012-04-11 17:43:37 -07002847 JDWP::JdwpTag new_tag = TagFromObject(pReq->result_value.GetL());
Elliott Hughesd07986f2011-12-06 18:27:45 -08002848 if (new_tag != pReq->result_tag) {
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08002849 VLOG(jdwp) << " JDWP promoted result from " << pReq->result_tag << " to " << new_tag;
Elliott Hughesd07986f2011-12-06 18:27:45 -08002850 pReq->result_tag = new_tag;
2851 }
2852
2853 /*
2854 * Register the object. We don't actually need an ObjectId yet,
2855 * but we do need to be sure that the GC won't move or discard the
2856 * object when we switch out of RUNNING. The ObjectId conversion
2857 * will add the object to the "do not touch" list.
2858 *
2859 * We can't use the "tracked allocation" mechanism here because
2860 * the object is going to be handed off to a different thread.
2861 */
Elliott Hughesf24d3ce2012-04-11 17:43:37 -07002862 gRegistry->Add(pReq->result_value.GetL());
Elliott Hughesd07986f2011-12-06 18:27:45 -08002863 }
2864
2865 if (old_exception.get() != NULL) {
Ian Rogers62d6c772013-02-27 08:32:07 -08002866 ThrowLocation gc_safe_throw_location(old_throw_this_object.get(), old_throw_method.get(),
2867 old_throw_dex_pc);
2868 soa.Self()->SetException(gc_safe_throw_location, old_exception.get());
Elliott Hughesd07986f2011-12-06 18:27:45 -08002869 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002870}
2871
Elliott Hughesd07986f2011-12-06 18:27:45 -08002872/*
Elliott Hughes4b9702c2013-02-20 18:13:24 -08002873 * "request" contains a full JDWP packet, possibly with multiple chunks. We
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07002874 * need to process each, accumulate the replies, and ship the whole thing
2875 * back.
2876 *
2877 * Returns "true" if we have a reply. The reply buffer is newly allocated,
2878 * and includes the chunk type/length, followed by the data.
2879 *
Elliott Hughes3d30d9b2011-12-07 17:35:48 -08002880 * OLD-TODO: we currently assume that the request and reply include a single
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07002881 * chunk. If this becomes inconvenient we will need to adapt.
2882 */
Elliott Hughes4b9702c2013-02-20 18:13:24 -08002883bool Dbg::DdmHandlePacket(JDWP::Request& request, uint8_t** pReplyBuf, int* pReplyLen) {
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07002884 Thread* self = Thread::Current();
2885 JNIEnv* env = self->GetJniEnv();
2886
Elliott Hughes4b9702c2013-02-20 18:13:24 -08002887 uint32_t type = request.ReadUnsigned32("type");
2888 uint32_t length = request.ReadUnsigned32("length");
2889
2890 // Create a byte[] corresponding to 'request'.
2891 size_t request_length = request.size();
2892 ScopedLocalRef<jbyteArray> dataArray(env, env->NewByteArray(request_length));
Elliott Hughes6a5bd492011-10-28 14:33:57 -07002893 if (dataArray.get() == NULL) {
Elliott Hughes4b9702c2013-02-20 18:13:24 -08002894 LOG(WARNING) << "byte[] allocation failed: " << request_length;
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07002895 env->ExceptionClear();
2896 return false;
2897 }
Elliott Hughes4b9702c2013-02-20 18:13:24 -08002898 env->SetByteArrayRegion(dataArray.get(), 0, request_length, reinterpret_cast<const jbyte*>(request.data()));
2899 request.Skip(request_length);
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07002900
2901 // Run through and find all chunks. [Currently just find the first.]
Elliott Hughes6a5bd492011-10-28 14:33:57 -07002902 ScopedByteArrayRO contents(env, dataArray.get());
Elliott Hughes4b9702c2013-02-20 18:13:24 -08002903 if (length != request_length) {
2904 LOG(WARNING) << StringPrintf("bad chunk found (len=%u pktLen=%d)", length, request_length);
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07002905 return false;
2906 }
2907
2908 // Call "private static Chunk dispatch(int type, byte[] data, int offset, int length)".
Elliott Hugheseac76672012-05-24 21:56:51 -07002909 ScopedLocalRef<jobject> chunk(env, env->CallStaticObjectMethod(WellKnownClasses::org_apache_harmony_dalvik_ddmc_DdmServer,
2910 WellKnownClasses::org_apache_harmony_dalvik_ddmc_DdmServer_dispatch,
Elliott Hughes4b9702c2013-02-20 18:13:24 -08002911 type, dataArray.get(), 0, length));
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07002912 if (env->ExceptionCheck()) {
2913 LOG(INFO) << StringPrintf("Exception thrown by dispatcher for 0x%08x", type);
2914 env->ExceptionDescribe();
2915 env->ExceptionClear();
2916 return false;
2917 }
2918
Elliott Hughes6a5bd492011-10-28 14:33:57 -07002919 if (chunk.get() == NULL) {
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07002920 return false;
2921 }
2922
2923 /*
2924 * Pull the pieces out of the chunk. We copy the results into a
2925 * newly-allocated buffer that the caller can free. We don't want to
2926 * continue using the Chunk object because nothing has a reference to it.
2927 *
2928 * We could avoid this by returning type/data/offset/length and having
2929 * the caller be aware of the object lifetime issues, but that
Elliott Hughes81ff3182012-03-23 20:35:56 -07002930 * integrates the JDWP code more tightly into the rest of the runtime, and doesn't work
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07002931 * if we have responses for multiple chunks.
2932 *
2933 * So we're pretty much stuck with copying data around multiple times.
2934 */
Elliott Hugheseac76672012-05-24 21:56:51 -07002935 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 -08002936 jint offset = env->GetIntField(chunk.get(), WellKnownClasses::org_apache_harmony_dalvik_ddmc_Chunk_offset);
Elliott Hugheseac76672012-05-24 21:56:51 -07002937 length = env->GetIntField(chunk.get(), WellKnownClasses::org_apache_harmony_dalvik_ddmc_Chunk_length);
Elliott Hugheseac76672012-05-24 21:56:51 -07002938 type = env->GetIntField(chunk.get(), WellKnownClasses::org_apache_harmony_dalvik_ddmc_Chunk_type);
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07002939
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08002940 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 -07002941 if (length == 0 || replyData.get() == NULL) {
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07002942 return false;
2943 }
2944
Elliott Hughes4b9702c2013-02-20 18:13:24 -08002945 const int kChunkHdrLen = 8;
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07002946 uint8_t* reply = new uint8_t[length + kChunkHdrLen];
2947 if (reply == NULL) {
2948 LOG(WARNING) << "malloc failed: " << (length + kChunkHdrLen);
2949 return false;
2950 }
Elliott Hughesf7c3b662011-10-27 12:04:56 -07002951 JDWP::Set4BE(reply + 0, type);
2952 JDWP::Set4BE(reply + 4, length);
Elliott Hughes6a5bd492011-10-28 14:33:57 -07002953 env->GetByteArrayRegion(replyData.get(), offset, length, reinterpret_cast<jbyte*>(reply + kChunkHdrLen));
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07002954
2955 *pReplyBuf = reply;
2956 *pReplyLen = length + kChunkHdrLen;
2957
Elliott Hughes4b9702c2013-02-20 18:13:24 -08002958 VLOG(jdwp) << StringPrintf("dvmHandleDdm returning type=%.4s %p len=%d", reinterpret_cast<char*>(reply), reply, length);
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07002959 return true;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002960}
2961
Elliott Hughesa2155262011-11-16 16:26:58 -08002962void Dbg::DdmBroadcast(bool connect) {
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08002963 VLOG(jdwp) << "Broadcasting DDM " << (connect ? "connect" : "disconnect") << "...";
Elliott Hughes47fce012011-10-25 18:37:19 -07002964
2965 Thread* self = Thread::Current();
Ian Rogers50b35e22012-10-04 10:09:15 -07002966 if (self->GetState() != kRunnable) {
2967 LOG(ERROR) << "DDM broadcast in thread state " << self->GetState();
2968 /* try anyway? */
Elliott Hughes47fce012011-10-25 18:37:19 -07002969 }
2970
2971 JNIEnv* env = self->GetJniEnv();
Elliott Hughes47fce012011-10-25 18:37:19 -07002972 jint event = connect ? 1 /*DdmServer.CONNECTED*/ : 2 /*DdmServer.DISCONNECTED*/;
Elliott Hugheseac76672012-05-24 21:56:51 -07002973 env->CallStaticVoidMethod(WellKnownClasses::org_apache_harmony_dalvik_ddmc_DdmServer,
2974 WellKnownClasses::org_apache_harmony_dalvik_ddmc_DdmServer_broadcast,
2975 event);
Elliott Hughes47fce012011-10-25 18:37:19 -07002976 if (env->ExceptionCheck()) {
2977 LOG(ERROR) << "DdmServer.broadcast " << event << " failed";
2978 env->ExceptionDescribe();
2979 env->ExceptionClear();
2980 }
2981}
2982
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002983void Dbg::DdmConnected() {
Elliott Hughesa2155262011-11-16 16:26:58 -08002984 Dbg::DdmBroadcast(true);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002985}
2986
2987void Dbg::DdmDisconnected() {
Elliott Hughesa2155262011-11-16 16:26:58 -08002988 Dbg::DdmBroadcast(false);
Elliott Hughes47fce012011-10-25 18:37:19 -07002989 gDdmThreadNotification = false;
2990}
2991
2992/*
Elliott Hughes82188472011-11-07 18:11:48 -08002993 * Send a notification when a thread starts, stops, or changes its name.
Elliott Hughes47fce012011-10-25 18:37:19 -07002994 *
2995 * Because we broadcast the full set of threads when the notifications are
2996 * first enabled, it's possible for "thread" to be actively executing.
2997 */
Elliott Hughes82188472011-11-07 18:11:48 -08002998void Dbg::DdmSendThreadNotification(Thread* t, uint32_t type) {
Elliott Hughes47fce012011-10-25 18:37:19 -07002999 if (!gDdmThreadNotification) {
3000 return;
3001 }
3002
Elliott Hughes82188472011-11-07 18:11:48 -08003003 if (type == CHUNK_TYPE("THDE")) {
Elliott Hughes47fce012011-10-25 18:37:19 -07003004 uint8_t buf[4];
Ian Rogersd9c4fc92013-10-01 19:45:43 -07003005 JDWP::Set4BE(&buf[0], t->GetThreadId());
Elliott Hughes47fce012011-10-25 18:37:19 -07003006 Dbg::DdmSendChunk(CHUNK_TYPE("THDE"), 4, buf);
Elliott Hughes82188472011-11-07 18:11:48 -08003007 } else {
3008 CHECK(type == CHUNK_TYPE("THCR") || type == CHUNK_TYPE("THNM")) << type;
Ian Rogers00f7d0e2012-07-19 15:28:27 -07003009 ScopedObjectAccessUnchecked soa(Thread::Current());
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003010 SirtRef<mirror::String> name(soa.Self(), t->GetThreadName(soa));
Elliott Hughes82188472011-11-07 18:11:48 -08003011 size_t char_count = (name.get() != NULL) ? name->GetLength() : 0;
jeffhao725a9572012-11-13 18:20:12 -08003012 const jchar* chars = (name.get() != NULL) ? name->GetCharArray()->GetData() : NULL;
Elliott Hughes82188472011-11-07 18:11:48 -08003013
Elliott Hughes21f32d72011-11-09 17:44:13 -08003014 std::vector<uint8_t> bytes;
Ian Rogersd9c4fc92013-10-01 19:45:43 -07003015 JDWP::Append4BE(bytes, t->GetThreadId());
Elliott Hughes545a0642011-11-08 19:10:03 -08003016 JDWP::AppendUtf16BE(bytes, chars, char_count);
Elliott Hughes21f32d72011-11-09 17:44:13 -08003017 CHECK_EQ(bytes.size(), char_count*2 + sizeof(uint32_t)*2);
3018 Dbg::DdmSendChunk(type, bytes);
Elliott Hughes47fce012011-10-25 18:37:19 -07003019 }
3020}
3021
Elliott Hughes47fce012011-10-25 18:37:19 -07003022void Dbg::DdmSetThreadNotification(bool enable) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07003023 // Enable/disable thread notifications.
Elliott Hughes47fce012011-10-25 18:37:19 -07003024 gDdmThreadNotification = enable;
3025 if (enable) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07003026 // Suspend the VM then post thread start notifications for all threads. Threads attaching will
3027 // see a suspension in progress and block until that ends. They then post their own start
3028 // notification.
3029 SuspendVM();
3030 std::list<Thread*> threads;
Ian Rogers50b35e22012-10-04 10:09:15 -07003031 Thread* self = Thread::Current();
Ian Rogers00f7d0e2012-07-19 15:28:27 -07003032 {
Ian Rogers50b35e22012-10-04 10:09:15 -07003033 MutexLock mu(self, *Locks::thread_list_lock_);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07003034 threads = Runtime::Current()->GetThreadList()->GetList();
3035 }
3036 {
Ian Rogers50b35e22012-10-04 10:09:15 -07003037 ScopedObjectAccess soa(self);
Mathieu Chartier02e25112013-08-14 16:14:24 -07003038 for (Thread* thread : threads) {
3039 Dbg::DdmSendThreadNotification(thread, CHUNK_TYPE("THCR"));
Ian Rogers00f7d0e2012-07-19 15:28:27 -07003040 }
3041 }
3042 ResumeVM();
Elliott Hughes47fce012011-10-25 18:37:19 -07003043 }
3044}
3045
Elliott Hughesa2155262011-11-16 16:26:58 -08003046void Dbg::PostThreadStartOrStop(Thread* t, uint32_t type) {
Elliott Hughesc0f09332012-03-26 13:27:06 -07003047 if (IsDebuggerActive()) {
Mathieu Chartierdbe6f462012-09-25 16:54:50 -07003048 ScopedObjectAccessUnchecked soa(Thread::Current());
Ian Rogerscfaa4552012-11-26 21:00:08 -08003049 JDWP::ObjectId id = gRegistry->Add(t->GetPeer());
Elliott Hughes82188472011-11-07 18:11:48 -08003050 gJdwpState->PostThreadChange(id, type == CHUNK_TYPE("THCR"));
Elliott Hughes47fce012011-10-25 18:37:19 -07003051 }
Elliott Hughes82188472011-11-07 18:11:48 -08003052 Dbg::DdmSendThreadNotification(t, type);
Elliott Hughes47fce012011-10-25 18:37:19 -07003053}
3054
3055void Dbg::PostThreadStart(Thread* t) {
Elliott Hughesa2155262011-11-16 16:26:58 -08003056 Dbg::PostThreadStartOrStop(t, CHUNK_TYPE("THCR"));
Elliott Hughes47fce012011-10-25 18:37:19 -07003057}
3058
3059void Dbg::PostThreadDeath(Thread* t) {
Elliott Hughesa2155262011-11-16 16:26:58 -08003060 Dbg::PostThreadStartOrStop(t, CHUNK_TYPE("THDE"));
Elliott Hughes872d4ec2011-10-21 17:07:15 -07003061}
3062
Elliott Hughes82188472011-11-07 18:11:48 -08003063void Dbg::DdmSendChunk(uint32_t type, size_t byte_count, const uint8_t* buf) {
Elliott Hughes3bb81562011-10-21 18:52:59 -07003064 CHECK(buf != NULL);
3065 iovec vec[1];
3066 vec[0].iov_base = reinterpret_cast<void*>(const_cast<uint8_t*>(buf));
3067 vec[0].iov_len = byte_count;
3068 Dbg::DdmSendChunkV(type, vec, 1);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07003069}
3070
Elliott Hughes21f32d72011-11-09 17:44:13 -08003071void Dbg::DdmSendChunk(uint32_t type, const std::vector<uint8_t>& bytes) {
3072 DdmSendChunk(type, bytes.size(), &bytes[0]);
3073}
3074
Brian Carlstromf5293522013-07-19 00:24:00 -07003075void Dbg::DdmSendChunkV(uint32_t type, const iovec* iov, int iov_count) {
Elliott Hughes3bb81562011-10-21 18:52:59 -07003076 if (gJdwpState == NULL) {
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08003077 VLOG(jdwp) << "Debugger thread not active, ignoring DDM send: " << type;
Elliott Hughes3bb81562011-10-21 18:52:59 -07003078 } else {
Elliott Hughescccd84f2011-12-05 16:51:54 -08003079 gJdwpState->DdmSendChunkV(type, iov, iov_count);
Elliott Hughes3bb81562011-10-21 18:52:59 -07003080 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -07003081}
3082
Elliott Hughes767a1472011-10-26 18:49:02 -07003083int Dbg::DdmHandleHpifChunk(HpifWhen when) {
3084 if (when == HPIF_WHEN_NOW) {
Elliott Hughes7162ad92011-10-27 14:08:42 -07003085 DdmSendHeapInfo(when);
Elliott Hughes767a1472011-10-26 18:49:02 -07003086 return true;
3087 }
3088
3089 if (when != HPIF_WHEN_NEVER && when != HPIF_WHEN_NEXT_GC && when != HPIF_WHEN_EVERY_GC) {
3090 LOG(ERROR) << "invalid HpifWhen value: " << static_cast<int>(when);
3091 return false;
3092 }
3093
3094 gDdmHpifWhen = when;
3095 return true;
3096}
3097
3098bool Dbg::DdmHandleHpsgNhsgChunk(Dbg::HpsgWhen when, Dbg::HpsgWhat what, bool native) {
3099 if (when != HPSG_WHEN_NEVER && when != HPSG_WHEN_EVERY_GC) {
3100 LOG(ERROR) << "invalid HpsgWhen value: " << static_cast<int>(when);
3101 return false;
3102 }
3103
3104 if (what != HPSG_WHAT_MERGED_OBJECTS && what != HPSG_WHAT_DISTINCT_OBJECTS) {
3105 LOG(ERROR) << "invalid HpsgWhat value: " << static_cast<int>(what);
3106 return false;
3107 }
3108
3109 if (native) {
3110 gDdmNhsgWhen = when;
3111 gDdmNhsgWhat = what;
3112 } else {
3113 gDdmHpsgWhen = when;
3114 gDdmHpsgWhat = what;
3115 }
3116 return true;
3117}
3118
Elliott Hughes7162ad92011-10-27 14:08:42 -07003119void Dbg::DdmSendHeapInfo(HpifWhen reason) {
3120 // If there's a one-shot 'when', reset it.
3121 if (reason == gDdmHpifWhen) {
3122 if (gDdmHpifWhen == HPIF_WHEN_NEXT_GC) {
3123 gDdmHpifWhen = HPIF_WHEN_NEVER;
3124 }
3125 }
3126
3127 /*
3128 * Chunk HPIF (client --> server)
3129 *
3130 * Heap Info. General information about the heap,
3131 * suitable for a summary display.
3132 *
3133 * [u4]: number of heaps
3134 *
3135 * For each heap:
3136 * [u4]: heap ID
3137 * [u8]: timestamp in ms since Unix epoch
3138 * [u1]: capture reason (same as 'when' value from server)
3139 * [u4]: max heap size in bytes (-Xmx)
3140 * [u4]: current heap size in bytes
3141 * [u4]: current number of bytes allocated
3142 * [u4]: current number of objects allocated
3143 */
3144 uint8_t heap_count = 1;
Ian Rogers1d54e732013-05-02 21:10:01 -07003145 gc::Heap* heap = Runtime::Current()->GetHeap();
Elliott Hughes21f32d72011-11-09 17:44:13 -08003146 std::vector<uint8_t> bytes;
Elliott Hughes545a0642011-11-08 19:10:03 -08003147 JDWP::Append4BE(bytes, heap_count);
Brian Carlstrom7934ac22013-07-26 10:54:15 -07003148 JDWP::Append4BE(bytes, 1); // Heap id (bogus; we only have one heap).
Elliott Hughes545a0642011-11-08 19:10:03 -08003149 JDWP::Append8BE(bytes, MilliTime());
3150 JDWP::Append1BE(bytes, reason);
Brian Carlstrom7934ac22013-07-26 10:54:15 -07003151 JDWP::Append4BE(bytes, heap->GetMaxMemory()); // Max allowed heap size in bytes.
3152 JDWP::Append4BE(bytes, heap->GetTotalMemory()); // Current heap size in bytes.
Elliott Hughesb3bd5f02012-03-08 21:05:27 -08003153 JDWP::Append4BE(bytes, heap->GetBytesAllocated());
3154 JDWP::Append4BE(bytes, heap->GetObjectsAllocated());
Elliott Hughes21f32d72011-11-09 17:44:13 -08003155 CHECK_EQ(bytes.size(), 4U + (heap_count * (4 + 8 + 1 + 4 + 4 + 4 + 4)));
3156 Dbg::DdmSendChunk(CHUNK_TYPE("HPIF"), bytes);
Elliott Hughes767a1472011-10-26 18:49:02 -07003157}
3158
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003159enum HpsgSolidity {
3160 SOLIDITY_FREE = 0,
3161 SOLIDITY_HARD = 1,
3162 SOLIDITY_SOFT = 2,
3163 SOLIDITY_WEAK = 3,
3164 SOLIDITY_PHANTOM = 4,
3165 SOLIDITY_FINALIZABLE = 5,
3166 SOLIDITY_SWEEP = 6,
3167};
3168
3169enum HpsgKind {
3170 KIND_OBJECT = 0,
3171 KIND_CLASS_OBJECT = 1,
3172 KIND_ARRAY_1 = 2,
3173 KIND_ARRAY_2 = 3,
3174 KIND_ARRAY_4 = 4,
3175 KIND_ARRAY_8 = 5,
3176 KIND_UNKNOWN = 6,
3177 KIND_NATIVE = 7,
3178};
3179
3180#define HPSG_PARTIAL (1<<7)
3181#define HPSG_STATE(solidity, kind) ((uint8_t)((((kind) & 0x7) << 3) | ((solidity) & 0x7)))
3182
Ian Rogers30fab402012-01-23 15:43:46 -08003183class HeapChunkContext {
3184 public:
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003185 // Maximum chunk size. Obtain this from the formula:
3186 // (((maximum_heap_size / ALLOCATION_UNIT_SIZE) + 255) / 256) * 2
3187 HeapChunkContext(bool merge, bool native)
Ian Rogers30fab402012-01-23 15:43:46 -08003188 : buf_(16384 - 16),
3189 type_(0),
3190 merge_(merge) {
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003191 Reset();
3192 if (native) {
Ian Rogers30fab402012-01-23 15:43:46 -08003193 type_ = CHUNK_TYPE("NHSG");
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003194 } else {
Ian Rogers30fab402012-01-23 15:43:46 -08003195 type_ = merge ? CHUNK_TYPE("HPSG") : CHUNK_TYPE("HPSO");
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003196 }
3197 }
3198
3199 ~HeapChunkContext() {
Ian Rogers30fab402012-01-23 15:43:46 -08003200 if (p_ > &buf_[0]) {
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003201 Flush();
3202 }
3203 }
3204
3205 void EnsureHeader(const void* chunk_ptr) {
Ian Rogers30fab402012-01-23 15:43:46 -08003206 if (!needHeader_) {
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003207 return;
3208 }
3209
3210 // Start a new HPSx chunk.
Brian Carlstrom7934ac22013-07-26 10:54:15 -07003211 JDWP::Write4BE(&p_, 1); // Heap id (bogus; we only have one heap).
3212 JDWP::Write1BE(&p_, 8); // Size of allocation unit, in bytes.
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003213
Brian Carlstrom7934ac22013-07-26 10:54:15 -07003214 JDWP::Write4BE(&p_, reinterpret_cast<uintptr_t>(chunk_ptr)); // virtual address of segment start.
3215 JDWP::Write4BE(&p_, 0); // offset of this piece (relative to the virtual address).
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003216 // [u4]: length of piece, in allocation units
3217 // 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 -08003218 pieceLenField_ = p_;
3219 JDWP::Write4BE(&p_, 0x55555555);
3220 needHeader_ = false;
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003221 }
3222
Ian Rogersb726dcb2012-09-05 08:57:23 -07003223 void Flush() SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Ian Rogersd636b062013-01-18 17:51:18 -08003224 if (pieceLenField_ == NULL) {
3225 // Flush immediately post Reset (maybe back-to-back Flush). Ignore.
3226 CHECK(needHeader_);
3227 return;
3228 }
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003229 // Patch the "length of piece" field.
Ian Rogers30fab402012-01-23 15:43:46 -08003230 CHECK_LE(&buf_[0], pieceLenField_);
3231 CHECK_LE(pieceLenField_, p_);
3232 JDWP::Set4BE(pieceLenField_, totalAllocationUnits_);
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003233
Ian Rogers30fab402012-01-23 15:43:46 -08003234 Dbg::DdmSendChunk(type_, p_ - &buf_[0], &buf_[0]);
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003235 Reset();
3236 }
3237
Ian Rogers00f7d0e2012-07-19 15:28:27 -07003238 static void HeapChunkCallback(void* start, void* end, size_t used_bytes, void* arg)
Ian Rogersb726dcb2012-09-05 08:57:23 -07003239 SHARED_LOCKS_REQUIRED(Locks::heap_bitmap_lock_,
3240 Locks::mutator_lock_) {
Ian Rogers30fab402012-01-23 15:43:46 -08003241 reinterpret_cast<HeapChunkContext*>(arg)->HeapChunkCallback(start, end, used_bytes);
Elliott Hughesa2155262011-11-16 16:26:58 -08003242 }
3243
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003244 private:
Elliott Hughesa2155262011-11-16 16:26:58 -08003245 enum { ALLOCATION_UNIT_SIZE = 8 };
3246
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003247 void Reset() {
Ian Rogers30fab402012-01-23 15:43:46 -08003248 p_ = &buf_[0];
Ian Rogers15bf2d32012-08-28 17:33:04 -07003249 startOfNextMemoryChunk_ = NULL;
Ian Rogers30fab402012-01-23 15:43:46 -08003250 totalAllocationUnits_ = 0;
3251 needHeader_ = true;
3252 pieceLenField_ = NULL;
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003253 }
3254
Ian Rogers00f7d0e2012-07-19 15:28:27 -07003255 void HeapChunkCallback(void* start, void* /*end*/, size_t used_bytes)
Ian Rogersb726dcb2012-09-05 08:57:23 -07003256 SHARED_LOCKS_REQUIRED(Locks::heap_bitmap_lock_,
3257 Locks::mutator_lock_) {
Ian Rogers30fab402012-01-23 15:43:46 -08003258 // Note: heap call backs cannot manipulate the heap upon which they are crawling, care is taken
3259 // in the following code not to allocate memory, by ensuring buf_ is of the correct size
Ian Rogers15bf2d32012-08-28 17:33:04 -07003260 if (used_bytes == 0) {
3261 if (start == NULL) {
3262 // Reset for start of new heap.
3263 startOfNextMemoryChunk_ = NULL;
3264 Flush();
3265 }
3266 // Only process in use memory so that free region information
3267 // also includes dlmalloc book keeping.
Elliott Hughesa2155262011-11-16 16:26:58 -08003268 return;
Elliott Hughesa2155262011-11-16 16:26:58 -08003269 }
3270
Ian Rogers15bf2d32012-08-28 17:33:04 -07003271 /* If we're looking at the native heap, we'll just return
3272 * (SOLIDITY_HARD, KIND_NATIVE) for all allocated chunks
3273 */
3274 bool native = type_ == CHUNK_TYPE("NHSG");
3275
3276 if (startOfNextMemoryChunk_ != NULL) {
3277 // Transmit any pending free memory. Native free memory of
3278 // over kMaxFreeLen could be because of the use of mmaps, so
3279 // don't report. If not free memory then start a new segment.
3280 bool flush = true;
3281 if (start > startOfNextMemoryChunk_) {
3282 const size_t kMaxFreeLen = 2 * kPageSize;
3283 void* freeStart = startOfNextMemoryChunk_;
3284 void* freeEnd = start;
Brian Carlstrom2d888622013-07-18 17:02:00 -07003285 size_t freeLen = reinterpret_cast<char*>(freeEnd) - reinterpret_cast<char*>(freeStart);
Ian Rogers15bf2d32012-08-28 17:33:04 -07003286 if (!native || freeLen < kMaxFreeLen) {
3287 AppendChunk(HPSG_STATE(SOLIDITY_FREE, 0), freeStart, freeLen);
3288 flush = false;
3289 }
3290 }
3291 if (flush) {
3292 startOfNextMemoryChunk_ = NULL;
3293 Flush();
3294 }
3295 }
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003296 const mirror::Object* obj = reinterpret_cast<const mirror::Object*>(start);
Elliott Hughesa2155262011-11-16 16:26:58 -08003297
3298 // Determine the type of this chunk.
3299 // OLD-TODO: if context.merge, see if this chunk is different from the last chunk.
3300 // If it's the same, we should combine them.
Ian Rogers15bf2d32012-08-28 17:33:04 -07003301 uint8_t state = ExamineObject(obj, native);
3302 // dlmalloc's chunk header is 2 * sizeof(size_t), but if the previous chunk is in use for an
3303 // allocation then the first sizeof(size_t) may belong to it.
3304 const size_t dlMallocOverhead = sizeof(size_t);
3305 AppendChunk(state, start, used_bytes + dlMallocOverhead);
Brian Carlstrom2d888622013-07-18 17:02:00 -07003306 startOfNextMemoryChunk_ = reinterpret_cast<char*>(start) + used_bytes + dlMallocOverhead;
Ian Rogers15bf2d32012-08-28 17:33:04 -07003307 }
Elliott Hughesa2155262011-11-16 16:26:58 -08003308
Ian Rogers15bf2d32012-08-28 17:33:04 -07003309 void AppendChunk(uint8_t state, void* ptr, size_t length)
Ian Rogersb726dcb2012-09-05 08:57:23 -07003310 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Ian Rogers15bf2d32012-08-28 17:33:04 -07003311 // Make sure there's enough room left in the buffer.
3312 // We need to use two bytes for every fractional 256 allocation units used by the chunk plus
3313 // 17 bytes for any header.
3314 size_t needed = (((length/ALLOCATION_UNIT_SIZE + 255) / 256) * 2) + 17;
3315 size_t bytesLeft = buf_.size() - (size_t)(p_ - &buf_[0]);
3316 if (bytesLeft < needed) {
3317 Flush();
3318 }
3319
3320 bytesLeft = buf_.size() - (size_t)(p_ - &buf_[0]);
3321 if (bytesLeft < needed) {
3322 LOG(WARNING) << "Chunk is too big to transmit (chunk_len=" << length << ", "
3323 << needed << " bytes)";
3324 return;
3325 }
3326 EnsureHeader(ptr);
Elliott Hughesa2155262011-11-16 16:26:58 -08003327 // Write out the chunk description.
Ian Rogers15bf2d32012-08-28 17:33:04 -07003328 length /= ALLOCATION_UNIT_SIZE; // Convert to allocation units.
3329 totalAllocationUnits_ += length;
3330 while (length > 256) {
Ian Rogers30fab402012-01-23 15:43:46 -08003331 *p_++ = state | HPSG_PARTIAL;
3332 *p_++ = 255; // length - 1
Ian Rogers15bf2d32012-08-28 17:33:04 -07003333 length -= 256;
Elliott Hughesa2155262011-11-16 16:26:58 -08003334 }
Ian Rogers30fab402012-01-23 15:43:46 -08003335 *p_++ = state;
Ian Rogers15bf2d32012-08-28 17:33:04 -07003336 *p_++ = length - 1;
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003337 }
3338
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003339 uint8_t ExamineObject(const mirror::Object* o, bool is_native_heap)
Ian Rogersb726dcb2012-09-05 08:57:23 -07003340 SHARED_LOCKS_REQUIRED(Locks::heap_bitmap_lock_) {
Elliott Hughesa2155262011-11-16 16:26:58 -08003341 if (o == NULL) {
3342 return HPSG_STATE(SOLIDITY_FREE, 0);
3343 }
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003344
Elliott Hughesa2155262011-11-16 16:26:58 -08003345 // It's an allocated chunk. Figure out what it is.
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003346
Elliott Hughesa2155262011-11-16 16:26:58 -08003347 // If we're looking at the native heap, we'll just return
3348 // (SOLIDITY_HARD, KIND_NATIVE) for all allocated chunks.
Ian Rogers00f7d0e2012-07-19 15:28:27 -07003349 if (is_native_heap) {
Elliott Hughesa2155262011-11-16 16:26:58 -08003350 return HPSG_STATE(SOLIDITY_HARD, KIND_NATIVE);
3351 }
3352
Ian Rogers5bfa60f2012-09-02 21:17:56 -07003353 if (!Runtime::Current()->GetHeap()->IsLiveObjectLocked(o)) {
Ian Rogers15bf2d32012-08-28 17:33:04 -07003354 return HPSG_STATE(SOLIDITY_HARD, KIND_NATIVE);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07003355 }
3356
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003357 mirror::Class* c = o->GetClass();
Elliott Hughesa2155262011-11-16 16:26:58 -08003358 if (c == NULL) {
3359 // The object was probably just created but hasn't been initialized yet.
3360 return HPSG_STATE(SOLIDITY_HARD, KIND_OBJECT);
3361 }
3362
Mathieu Chartier590fee92013-09-13 13:46:47 -07003363 if (!Runtime::Current()->GetHeap()->IsValidObjectAddress(c)) {
Ian Rogers15bf2d32012-08-28 17:33:04 -07003364 LOG(ERROR) << "Invalid class for managed heap object: " << o << " " << c;
Elliott Hughesa2155262011-11-16 16:26:58 -08003365 return HPSG_STATE(SOLIDITY_HARD, KIND_UNKNOWN);
3366 }
3367
3368 if (c->IsClassClass()) {
3369 return HPSG_STATE(SOLIDITY_HARD, KIND_CLASS_OBJECT);
3370 }
3371
3372 if (c->IsArrayClass()) {
3373 if (o->IsObjectArray()) {
3374 return HPSG_STATE(SOLIDITY_HARD, KIND_ARRAY_4);
3375 }
3376 switch (c->GetComponentSize()) {
3377 case 1: return HPSG_STATE(SOLIDITY_HARD, KIND_ARRAY_1);
3378 case 2: return HPSG_STATE(SOLIDITY_HARD, KIND_ARRAY_2);
3379 case 4: return HPSG_STATE(SOLIDITY_HARD, KIND_ARRAY_4);
3380 case 8: return HPSG_STATE(SOLIDITY_HARD, KIND_ARRAY_8);
3381 }
3382 }
3383
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003384 return HPSG_STATE(SOLIDITY_HARD, KIND_OBJECT);
3385 }
3386
Ian Rogers30fab402012-01-23 15:43:46 -08003387 std::vector<uint8_t> buf_;
3388 uint8_t* p_;
3389 uint8_t* pieceLenField_;
Ian Rogers15bf2d32012-08-28 17:33:04 -07003390 void* startOfNextMemoryChunk_;
Ian Rogers30fab402012-01-23 15:43:46 -08003391 size_t totalAllocationUnits_;
3392 uint32_t type_;
3393 bool merge_;
3394 bool needHeader_;
3395
Elliott Hughesa2155262011-11-16 16:26:58 -08003396 DISALLOW_COPY_AND_ASSIGN(HeapChunkContext);
3397};
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003398
3399void Dbg::DdmSendHeapSegments(bool native) {
3400 Dbg::HpsgWhen when;
3401 Dbg::HpsgWhat what;
3402 if (!native) {
3403 when = gDdmHpsgWhen;
3404 what = gDdmHpsgWhat;
3405 } else {
3406 when = gDdmNhsgWhen;
3407 what = gDdmNhsgWhat;
3408 }
3409 if (when == HPSG_WHEN_NEVER) {
3410 return;
3411 }
3412
3413 // Figure out what kind of chunks we'll be sending.
3414 CHECK(what == HPSG_WHAT_MERGED_OBJECTS || what == HPSG_WHAT_DISTINCT_OBJECTS) << static_cast<int>(what);
3415
3416 // First, send a heap start chunk.
3417 uint8_t heap_id[4];
Brian Carlstrom7934ac22013-07-26 10:54:15 -07003418 JDWP::Set4BE(&heap_id[0], 1); // Heap id (bogus; we only have one heap).
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003419 Dbg::DdmSendChunk(native ? CHUNK_TYPE("NHST") : CHUNK_TYPE("HPST"), sizeof(heap_id), heap_id);
3420
Hiroshi Yamauchicf58d4a2013-09-26 14:21:22 -07003421 Thread* self = Thread::Current();
3422
3423 // To allow the Walk/InspectAll() below to exclusively-lock the
3424 // mutator lock, temporarily release the shared access to the
3425 // mutator lock here by transitioning to the suspended state.
3426 Locks::mutator_lock_->AssertSharedHeld(self);
3427 self->TransitionFromRunnableToSuspended(kSuspended);
3428
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003429 // Send a series of heap segment chunks.
Elliott Hughesa2155262011-11-16 16:26:58 -08003430 HeapChunkContext context((what == HPSG_WHAT_MERGED_OBJECTS), native);
3431 if (native) {
Ian Rogers1d54e732013-05-02 21:10:01 -07003432 dlmalloc_inspect_all(HeapChunkContext::HeapChunkCallback, &context);
Elliott Hughesa2155262011-11-16 16:26:58 -08003433 } else {
Ian Rogers1d54e732013-05-02 21:10:01 -07003434 gc::Heap* heap = Runtime::Current()->GetHeap();
3435 const std::vector<gc::space::ContinuousSpace*>& spaces = heap->GetContinuousSpaces();
Ian Rogers62d6c772013-02-27 08:32:07 -08003436 ReaderMutexLock mu(self, *Locks::heap_bitmap_lock_);
Ian Rogers1d54e732013-05-02 21:10:01 -07003437 typedef std::vector<gc::space::ContinuousSpace*>::const_iterator It;
3438 for (It cur = spaces.begin(), end = spaces.end(); cur != end; ++cur) {
Hiroshi Yamauchicf58d4a2013-09-26 14:21:22 -07003439 if ((*cur)->IsMallocSpace()) {
3440 (*cur)->AsMallocSpace()->Walk(HeapChunkContext::HeapChunkCallback, &context);
Mathieu Chartierb062fdd2012-07-03 09:51:48 -07003441 }
3442 }
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -07003443 // Walk the large objects, these are not in the AllocSpace.
3444 heap->GetLargeObjectsSpace()->Walk(HeapChunkContext::HeapChunkCallback, &context);
Elliott Hughesa2155262011-11-16 16:26:58 -08003445 }
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003446
Hiroshi Yamauchicf58d4a2013-09-26 14:21:22 -07003447 // Shared-lock the mutator lock back.
3448 self->TransitionFromSuspendedToRunnable();
3449 Locks::mutator_lock_->AssertSharedHeld(self);
3450
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003451 // Finally, send a heap end chunk.
3452 Dbg::DdmSendChunk(native ? CHUNK_TYPE("NHEN") : CHUNK_TYPE("HPEN"), sizeof(heap_id), heap_id);
Elliott Hughes767a1472011-10-26 18:49:02 -07003453}
3454
Elliott Hughesb1a58792013-07-11 18:10:58 -07003455static size_t GetAllocTrackerMax() {
3456#ifdef HAVE_ANDROID_OS
3457 // Check whether there's a system property overriding the number of records.
3458 const char* propertyName = "dalvik.vm.allocTrackerMax";
3459 char allocRecordMaxString[PROPERTY_VALUE_MAX];
3460 if (property_get(propertyName, allocRecordMaxString, "") > 0) {
3461 char* end;
3462 size_t value = strtoul(allocRecordMaxString, &end, 10);
3463 if (*end != '\0') {
Ruben Brunk3e47a742013-09-09 17:56:07 -07003464 LOG(ERROR) << "Ignoring " << propertyName << " '" << allocRecordMaxString
3465 << "' --- invalid";
Elliott Hughesb1a58792013-07-11 18:10:58 -07003466 return kDefaultNumAllocRecords;
3467 }
3468 if (!IsPowerOfTwo(value)) {
Ruben Brunk3e47a742013-09-09 17:56:07 -07003469 LOG(ERROR) << "Ignoring " << propertyName << " '" << allocRecordMaxString
3470 << "' --- not power of two";
Elliott Hughesb1a58792013-07-11 18:10:58 -07003471 return kDefaultNumAllocRecords;
3472 }
3473 return value;
3474 }
3475#endif
3476 return kDefaultNumAllocRecords;
3477}
3478
Elliott Hughes545a0642011-11-08 19:10:03 -08003479void Dbg::SetAllocTrackingEnabled(bool enabled) {
Ian Rogers50b35e22012-10-04 10:09:15 -07003480 MutexLock mu(Thread::Current(), gAllocTrackerLock);
Elliott Hughes545a0642011-11-08 19:10:03 -08003481 if (enabled) {
3482 if (recent_allocation_records_ == NULL) {
Elliott Hughesb1a58792013-07-11 18:10:58 -07003483 gAllocRecordMax = GetAllocTrackerMax();
3484 LOG(INFO) << "Enabling alloc tracker (" << gAllocRecordMax << " entries of "
3485 << kMaxAllocRecordStackDepth << " frames, taking "
3486 << PrettySize(sizeof(AllocRecord) * gAllocRecordMax) << ")";
Elliott Hughes545a0642011-11-08 19:10:03 -08003487 gAllocRecordHead = gAllocRecordCount = 0;
Elliott Hughesb1a58792013-07-11 18:10:58 -07003488 recent_allocation_records_ = new AllocRecord[gAllocRecordMax];
Elliott Hughes545a0642011-11-08 19:10:03 -08003489 CHECK(recent_allocation_records_ != NULL);
3490 }
Ian Rogersfa824272013-11-05 16:12:57 -08003491 Runtime::Current()->GetInstrumentation()->InstrumentQuickAllocEntryPoints();
Elliott Hughes545a0642011-11-08 19:10:03 -08003492 } else {
Ian Rogersfa824272013-11-05 16:12:57 -08003493 Runtime::Current()->GetInstrumentation()->UninstrumentQuickAllocEntryPoints();
Elliott Hughes545a0642011-11-08 19:10:03 -08003494 delete[] recent_allocation_records_;
3495 recent_allocation_records_ = NULL;
3496 }
3497}
3498
Ian Rogers0399dde2012-06-06 17:09:28 -07003499struct AllocRecordStackVisitor : public StackVisitor {
Ian Rogers7a22fa62013-01-23 12:16:16 -08003500 AllocRecordStackVisitor(Thread* thread, AllocRecord* record)
Ian Rogersb726dcb2012-09-05 08:57:23 -07003501 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_)
Ian Rogers7a22fa62013-01-23 12:16:16 -08003502 : StackVisitor(thread, NULL), record(record), depth(0) {}
Elliott Hughes545a0642011-11-08 19:10:03 -08003503
Ian Rogers00f7d0e2012-07-19 15:28:27 -07003504 // TODO: Enable annotalysis. We know lock is held in constructor, but abstraction confuses
3505 // annotalysis.
3506 bool VisitFrame() NO_THREAD_SAFETY_ANALYSIS {
Elliott Hughes545a0642011-11-08 19:10:03 -08003507 if (depth >= kMaxAllocRecordStackDepth) {
Elliott Hughes530fa002012-03-12 11:44:49 -07003508 return false;
Elliott Hughes545a0642011-11-08 19:10:03 -08003509 }
Brian Carlstromea46f952013-07-30 01:26:50 -07003510 mirror::ArtMethod* m = GetMethod();
Ian Rogers0399dde2012-06-06 17:09:28 -07003511 if (!m->IsRuntimeMethod()) {
3512 record->stack[depth].method = m;
3513 record->stack[depth].dex_pc = GetDexPc();
Elliott Hughes530fa002012-03-12 11:44:49 -07003514 ++depth;
Elliott Hughes545a0642011-11-08 19:10:03 -08003515 }
Elliott Hughes530fa002012-03-12 11:44:49 -07003516 return true;
Elliott Hughes545a0642011-11-08 19:10:03 -08003517 }
3518
3519 ~AllocRecordStackVisitor() {
3520 // Clear out any unused stack trace elements.
3521 for (; depth < kMaxAllocRecordStackDepth; ++depth) {
3522 record->stack[depth].method = NULL;
Ian Rogers0399dde2012-06-06 17:09:28 -07003523 record->stack[depth].dex_pc = 0;
Elliott Hughes545a0642011-11-08 19:10:03 -08003524 }
3525 }
3526
3527 AllocRecord* record;
3528 size_t depth;
3529};
3530
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003531void Dbg::RecordAllocation(mirror::Class* type, size_t byte_count) {
Elliott Hughes545a0642011-11-08 19:10:03 -08003532 Thread* self = Thread::Current();
3533 CHECK(self != NULL);
3534
Ian Rogers50b35e22012-10-04 10:09:15 -07003535 MutexLock mu(self, gAllocTrackerLock);
Elliott Hughes545a0642011-11-08 19:10:03 -08003536 if (recent_allocation_records_ == NULL) {
3537 return;
3538 }
3539
3540 // Advance and clip.
Elliott Hughesb1a58792013-07-11 18:10:58 -07003541 if (++gAllocRecordHead == gAllocRecordMax) {
Elliott Hughes545a0642011-11-08 19:10:03 -08003542 gAllocRecordHead = 0;
3543 }
3544
3545 // Fill in the basics.
3546 AllocRecord* record = &recent_allocation_records_[gAllocRecordHead];
3547 record->type = type;
3548 record->byte_count = byte_count;
Ian Rogersd9c4fc92013-10-01 19:45:43 -07003549 record->thin_lock_id = self->GetThreadId();
Elliott Hughes545a0642011-11-08 19:10:03 -08003550
3551 // Fill in the stack trace.
Ian Rogers7a22fa62013-01-23 12:16:16 -08003552 AllocRecordStackVisitor visitor(self, record);
Ian Rogers0399dde2012-06-06 17:09:28 -07003553 visitor.WalkStack();
Elliott Hughes545a0642011-11-08 19:10:03 -08003554
Elliott Hughesb1a58792013-07-11 18:10:58 -07003555 if (gAllocRecordCount < gAllocRecordMax) {
Elliott Hughes545a0642011-11-08 19:10:03 -08003556 ++gAllocRecordCount;
3557 }
3558}
3559
Elliott Hughesa8f93cb2012-06-08 17:08:48 -07003560// Returns the index of the head element.
3561//
3562// We point at the most-recently-written record, so if gAllocRecordCount is 1
3563// we want to use the current element. Take "head+1" and subtract count
3564// from it.
3565//
3566// We need to handle underflow in our circular buffer, so we add
Elliott Hughesb1a58792013-07-11 18:10:58 -07003567// gAllocRecordMax and then mask it back down.
Elliott Hughesf8349362012-06-18 15:00:06 -07003568static inline int HeadIndex() EXCLUSIVE_LOCKS_REQUIRED(gAllocTrackerLock) {
Elliott Hughesb1a58792013-07-11 18:10:58 -07003569 return (gAllocRecordHead+1 + gAllocRecordMax - gAllocRecordCount) & (gAllocRecordMax-1);
Elliott Hughes545a0642011-11-08 19:10:03 -08003570}
3571
3572void Dbg::DumpRecentAllocations() {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07003573 ScopedObjectAccess soa(Thread::Current());
Ian Rogers50b35e22012-10-04 10:09:15 -07003574 MutexLock mu(soa.Self(), gAllocTrackerLock);
Elliott Hughes545a0642011-11-08 19:10:03 -08003575 if (recent_allocation_records_ == NULL) {
3576 LOG(INFO) << "Not recording tracked allocations";
3577 return;
3578 }
3579
3580 // "i" is the head of the list. We want to start at the end of the
3581 // list and move forward to the tail.
Elliott Hughesa8f93cb2012-06-08 17:08:48 -07003582 size_t i = HeadIndex();
Elliott Hughes545a0642011-11-08 19:10:03 -08003583 size_t count = gAllocRecordCount;
3584
3585 LOG(INFO) << "Tracked allocations, (head=" << gAllocRecordHead << " count=" << count << ")";
3586 while (count--) {
3587 AllocRecord* record = &recent_allocation_records_[i];
3588
Elliott Hughesa8f93cb2012-06-08 17:08:48 -07003589 LOG(INFO) << StringPrintf(" Thread %-2d %6zd bytes ", record->thin_lock_id, record->byte_count)
Elliott Hughes545a0642011-11-08 19:10:03 -08003590 << PrettyClass(record->type);
3591
3592 for (size_t stack_frame = 0; stack_frame < kMaxAllocRecordStackDepth; ++stack_frame) {
Brian Carlstromea46f952013-07-30 01:26:50 -07003593 const mirror::ArtMethod* m = record->stack[stack_frame].method;
Elliott Hughes545a0642011-11-08 19:10:03 -08003594 if (m == NULL) {
3595 break;
3596 }
3597 LOG(INFO) << " " << PrettyMethod(m) << " line " << record->stack[stack_frame].LineNumber();
3598 }
3599
3600 // pause periodically to help logcat catch up
3601 if ((count % 5) == 0) {
3602 usleep(40000);
3603 }
3604
Elliott Hughesb1a58792013-07-11 18:10:58 -07003605 i = (i + 1) & (gAllocRecordMax-1);
Elliott Hughes545a0642011-11-08 19:10:03 -08003606 }
3607}
3608
3609class StringTable {
3610 public:
3611 StringTable() {
3612 }
3613
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08003614 void Add(const char* s) {
Elliott Hughes545a0642011-11-08 19:10:03 -08003615 table_.insert(s);
3616 }
3617
Elliott Hughesa8f93cb2012-06-08 17:08:48 -07003618 size_t IndexOf(const char* s) const {
Mathieu Chartier02e25112013-08-14 16:14:24 -07003619 auto it = table_.find(s);
Elliott Hughesa8f93cb2012-06-08 17:08:48 -07003620 if (it == table_.end()) {
3621 LOG(FATAL) << "IndexOf(\"" << s << "\") failed";
3622 }
3623 return std::distance(table_.begin(), it);
Elliott Hughes545a0642011-11-08 19:10:03 -08003624 }
3625
Elliott Hughesa8f93cb2012-06-08 17:08:48 -07003626 size_t Size() const {
Elliott Hughes545a0642011-11-08 19:10:03 -08003627 return table_.size();
3628 }
3629
Elliott Hughesa8f93cb2012-06-08 17:08:48 -07003630 void WriteTo(std::vector<uint8_t>& bytes) const {
Mathieu Chartier02e25112013-08-14 16:14:24 -07003631 for (const std::string& str : table_) {
3632 const char* s = str.c_str();
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08003633 size_t s_len = CountModifiedUtf8Chars(s);
3634 UniquePtr<uint16_t> s_utf16(new uint16_t[s_len]);
3635 ConvertModifiedUtf8ToUtf16(s_utf16.get(), s);
3636 JDWP::AppendUtf16BE(bytes, s_utf16.get(), s_len);
Elliott Hughes545a0642011-11-08 19:10:03 -08003637 }
3638 }
3639
3640 private:
Elliott Hughesa8f93cb2012-06-08 17:08:48 -07003641 std::set<std::string> table_;
Elliott Hughes545a0642011-11-08 19:10:03 -08003642 DISALLOW_COPY_AND_ASSIGN(StringTable);
3643};
3644
3645/*
3646 * The data we send to DDMS contains everything we have recorded.
3647 *
3648 * Message header (all values big-endian):
3649 * (1b) message header len (to allow future expansion); includes itself
3650 * (1b) entry header len
3651 * (1b) stack frame len
3652 * (2b) number of entries
3653 * (4b) offset to string table from start of message
3654 * (2b) number of class name strings
3655 * (2b) number of method name strings
3656 * (2b) number of source file name strings
3657 * For each entry:
3658 * (4b) total allocation size
Elliott Hughes221229c2013-01-08 18:17:50 -08003659 * (2b) thread id
Elliott Hughes545a0642011-11-08 19:10:03 -08003660 * (2b) allocated object's class name index
3661 * (1b) stack depth
3662 * For each stack frame:
3663 * (2b) method's class name
3664 * (2b) method name
3665 * (2b) method source file
3666 * (2b) line number, clipped to 32767; -2 if native; -1 if no source
3667 * (xb) class name strings
3668 * (xb) method name strings
3669 * (xb) source file strings
3670 *
3671 * As with other DDM traffic, strings are sent as a 4-byte length
3672 * followed by UTF-16 data.
3673 *
3674 * We send up 16-bit unsigned indexes into string tables. In theory there
Elliott Hughesb1a58792013-07-11 18:10:58 -07003675 * can be (kMaxAllocRecordStackDepth * gAllocRecordMax) unique strings in
Elliott Hughes545a0642011-11-08 19:10:03 -08003676 * each table, but in practice there should be far fewer.
3677 *
3678 * The chief reason for using a string table here is to keep the size of
3679 * the DDMS message to a minimum. This is partly to make the protocol
3680 * efficient, but also because we have to form the whole thing up all at
3681 * once in a memory buffer.
3682 *
3683 * We use separate string tables for class names, method names, and source
3684 * files to keep the indexes small. There will generally be no overlap
3685 * between the contents of these tables.
3686 */
3687jbyteArray Dbg::GetRecentAllocations() {
3688 if (false) {
3689 DumpRecentAllocations();
3690 }
3691
Ian Rogers50b35e22012-10-04 10:09:15 -07003692 Thread* self = Thread::Current();
Elliott Hughes545a0642011-11-08 19:10:03 -08003693 std::vector<uint8_t> bytes;
Mathieu Chartier46e811b2013-07-10 17:09:14 -07003694 {
3695 MutexLock mu(self, gAllocTrackerLock);
3696 //
3697 // Part 1: generate string tables.
3698 //
3699 StringTable class_names;
3700 StringTable method_names;
3701 StringTable filenames;
Elliott Hughes545a0642011-11-08 19:10:03 -08003702
Mathieu Chartier46e811b2013-07-10 17:09:14 -07003703 int count = gAllocRecordCount;
3704 int idx = HeadIndex();
3705 while (count--) {
3706 AllocRecord* record = &recent_allocation_records_[idx];
Elliott Hughes545a0642011-11-08 19:10:03 -08003707
Mathieu Chartier46e811b2013-07-10 17:09:14 -07003708 class_names.Add(ClassHelper(record->type).GetDescriptor());
Elliott Hughes545a0642011-11-08 19:10:03 -08003709
Mathieu Chartier46e811b2013-07-10 17:09:14 -07003710 MethodHelper mh;
3711 for (size_t i = 0; i < kMaxAllocRecordStackDepth; i++) {
Brian Carlstromea46f952013-07-30 01:26:50 -07003712 mirror::ArtMethod* m = record->stack[i].method;
Mathieu Chartier46e811b2013-07-10 17:09:14 -07003713 if (m != NULL) {
3714 mh.ChangeMethod(m);
3715 class_names.Add(mh.GetDeclaringClassDescriptor());
3716 method_names.Add(mh.GetName());
3717 filenames.Add(mh.GetDeclaringClassSourceFile());
3718 }
3719 }
Elliott Hughes545a0642011-11-08 19:10:03 -08003720
Elliott Hughesb1a58792013-07-11 18:10:58 -07003721 idx = (idx + 1) & (gAllocRecordMax-1);
Elliott Hughes545a0642011-11-08 19:10:03 -08003722 }
3723
Mathieu Chartier46e811b2013-07-10 17:09:14 -07003724 LOG(INFO) << "allocation records: " << gAllocRecordCount;
3725
3726 //
3727 // Part 2: Generate the output and store it in the buffer.
3728 //
3729
3730 // (1b) message header len (to allow future expansion); includes itself
3731 // (1b) entry header len
3732 // (1b) stack frame len
3733 const int kMessageHeaderLen = 15;
3734 const int kEntryHeaderLen = 9;
3735 const int kStackFrameLen = 8;
3736 JDWP::Append1BE(bytes, kMessageHeaderLen);
3737 JDWP::Append1BE(bytes, kEntryHeaderLen);
3738 JDWP::Append1BE(bytes, kStackFrameLen);
3739
3740 // (2b) number of entries
3741 // (4b) offset to string table from start of message
3742 // (2b) number of class name strings
3743 // (2b) number of method name strings
3744 // (2b) number of source file name strings
3745 JDWP::Append2BE(bytes, gAllocRecordCount);
3746 size_t string_table_offset = bytes.size();
Brian Carlstrom7934ac22013-07-26 10:54:15 -07003747 JDWP::Append4BE(bytes, 0); // We'll patch this later...
Mathieu Chartier46e811b2013-07-10 17:09:14 -07003748 JDWP::Append2BE(bytes, class_names.Size());
3749 JDWP::Append2BE(bytes, method_names.Size());
3750 JDWP::Append2BE(bytes, filenames.Size());
3751
3752 count = gAllocRecordCount;
3753 idx = HeadIndex();
Mathieu Chartier46e811b2013-07-10 17:09:14 -07003754 while (count--) {
3755 // For each entry:
3756 // (4b) total allocation size
3757 // (2b) thread id
3758 // (2b) allocated object's class name index
3759 // (1b) stack depth
3760 AllocRecord* record = &recent_allocation_records_[idx];
3761 size_t stack_depth = record->GetDepth();
Mathieu Chartier590fee92013-09-13 13:46:47 -07003762 ClassHelper kh(record->type);
Mathieu Chartier46e811b2013-07-10 17:09:14 -07003763 size_t allocated_object_class_name_index = class_names.IndexOf(kh.GetDescriptor());
3764 JDWP::Append4BE(bytes, record->byte_count);
3765 JDWP::Append2BE(bytes, record->thin_lock_id);
3766 JDWP::Append2BE(bytes, allocated_object_class_name_index);
3767 JDWP::Append1BE(bytes, stack_depth);
3768
3769 MethodHelper mh;
3770 for (size_t stack_frame = 0; stack_frame < stack_depth; ++stack_frame) {
3771 // For each stack frame:
3772 // (2b) method's class name
3773 // (2b) method name
3774 // (2b) method source file
3775 // (2b) line number, clipped to 32767; -2 if native; -1 if no source
3776 mh.ChangeMethod(record->stack[stack_frame].method);
3777 size_t class_name_index = class_names.IndexOf(mh.GetDeclaringClassDescriptor());
3778 size_t method_name_index = method_names.IndexOf(mh.GetName());
3779 size_t file_name_index = filenames.IndexOf(mh.GetDeclaringClassSourceFile());
3780 JDWP::Append2BE(bytes, class_name_index);
3781 JDWP::Append2BE(bytes, method_name_index);
3782 JDWP::Append2BE(bytes, file_name_index);
3783 JDWP::Append2BE(bytes, record->stack[stack_frame].LineNumber());
3784 }
3785
Elliott Hughesb1a58792013-07-11 18:10:58 -07003786 idx = (idx + 1) & (gAllocRecordMax-1);
Mathieu Chartier46e811b2013-07-10 17:09:14 -07003787 }
3788
3789 // (xb) class name strings
3790 // (xb) method name strings
3791 // (xb) source file strings
3792 JDWP::Set4BE(&bytes[string_table_offset], bytes.size());
3793 class_names.WriteTo(bytes);
3794 method_names.WriteTo(bytes);
3795 filenames.WriteTo(bytes);
Elliott Hughes545a0642011-11-08 19:10:03 -08003796 }
Ian Rogers50b35e22012-10-04 10:09:15 -07003797 JNIEnv* env = self->GetJniEnv();
Elliott Hughes545a0642011-11-08 19:10:03 -08003798 jbyteArray result = env->NewByteArray(bytes.size());
3799 if (result != NULL) {
3800 env->SetByteArrayRegion(result, 0, bytes.size(), reinterpret_cast<const jbyte*>(&bytes[0]));
3801 }
3802 return result;
3803}
3804
Elliott Hughes872d4ec2011-10-21 17:07:15 -07003805} // namespace art