blob: 99e7867ffb4ae40ffe87d4cf08e428c81e11b5cc [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
Ian Rogers62d6c772013-02-27 08:32:07 -080098class DebugInstrumentationListener : public instrumentation::InstrumentationListener {
99 public:
100 DebugInstrumentationListener() {}
101 virtual ~DebugInstrumentationListener() {}
102
103 virtual void MethodEntered(Thread* thread, mirror::Object* this_object,
Ian Rogersef7d42f2014-01-06 12:55:46 -0800104 mirror::ArtMethod* method, uint32_t dex_pc)
Ian Rogers62d6c772013-02-27 08:32:07 -0800105 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
106 if (method->IsNative()) {
107 // TODO: post location events is a suspension point and native method entry stubs aren't.
108 return;
109 }
Jeff Hao579b0242013-11-18 13:16:49 -0800110 Dbg::PostLocationEvent(method, 0, this_object, Dbg::kMethodEntry, nullptr);
Ian Rogers62d6c772013-02-27 08:32:07 -0800111 }
112
113 virtual void MethodExited(Thread* thread, mirror::Object* this_object,
Ian Rogersef7d42f2014-01-06 12:55:46 -0800114 mirror::ArtMethod* method,
Ian Rogers62d6c772013-02-27 08:32:07 -0800115 uint32_t dex_pc, const JValue& return_value)
116 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Ian Rogers62d6c772013-02-27 08:32:07 -0800117 if (method->IsNative()) {
118 // TODO: post location events is a suspension point and native method entry stubs aren't.
119 return;
120 }
Jeff Hao579b0242013-11-18 13:16:49 -0800121 Dbg::PostLocationEvent(method, dex_pc, this_object, Dbg::kMethodExit, &return_value);
Ian Rogers62d6c772013-02-27 08:32:07 -0800122 }
123
Sebastien Hertz51db44a2013-11-19 10:00:29 +0100124 virtual void MethodUnwind(Thread* thread, mirror::Object* this_object,
Ian Rogersef7d42f2014-01-06 12:55:46 -0800125 mirror::ArtMethod* method, uint32_t dex_pc)
Sebastien Hertz51db44a2013-11-19 10:00:29 +0100126 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Ian Rogers62d6c772013-02-27 08:32:07 -0800127 // We're not recorded to listen to this kind of event, so complain.
128 LOG(ERROR) << "Unexpected method unwind event in debugger " << PrettyMethod(method)
Sebastien Hertz51db44a2013-11-19 10:00:29 +0100129 << " " << dex_pc;
Ian Rogers62d6c772013-02-27 08:32:07 -0800130 }
131
132 virtual void DexPcMoved(Thread* thread, mirror::Object* this_object,
Ian Rogersef7d42f2014-01-06 12:55:46 -0800133 mirror::ArtMethod* method, uint32_t new_dex_pc)
Ian Rogers62d6c772013-02-27 08:32:07 -0800134 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
135 Dbg::UpdateDebugger(thread, this_object, method, new_dex_pc);
136 }
137
138 virtual void ExceptionCaught(Thread* thread, const ThrowLocation& throw_location,
Brian Carlstromea46f952013-07-30 01:26:50 -0700139 mirror::ArtMethod* catch_method, uint32_t catch_dex_pc,
Ian Rogers62d6c772013-02-27 08:32:07 -0800140 mirror::Throwable* exception_object)
141 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
142 Dbg::PostException(thread, throw_location, catch_method, catch_dex_pc, exception_object);
143 }
Ian Rogers62d6c772013-02-27 08:32:07 -0800144} gDebugInstrumentationListener;
145
Elliott Hughes4ffd3132011-10-24 12:06:42 -0700146// JDWP is allowed unless the Zygote forbids it.
147static bool gJdwpAllowed = true;
148
Elliott Hughesc0f09332012-03-26 13:27:06 -0700149// Was there a -Xrunjdwp or -agentlib:jdwp= argument on the command line?
Elliott Hughes3bb81562011-10-21 18:52:59 -0700150static bool gJdwpConfigured = false;
151
Elliott Hughesc0f09332012-03-26 13:27:06 -0700152// Broken-down JDWP options. (Only valid if IsJdwpConfigured() is true.)
Elliott Hughes376a7a02011-10-24 18:35:55 -0700153static JDWP::JdwpOptions gJdwpOptions;
Elliott Hughes3bb81562011-10-21 18:52:59 -0700154
155// Runtime JDWP state.
156static JDWP::JdwpState* gJdwpState = NULL;
157static bool gDebuggerConnected; // debugger or DDMS is connected.
158static bool gDebuggerActive; // debugger is making requests.
Elliott Hughes86964332012-02-15 19:37:42 -0800159static bool gDisposed; // debugger called VirtualMachine.Dispose, so we should drop the connection.
Elliott Hughes3bb81562011-10-21 18:52:59 -0700160
Elliott Hughes47fce012011-10-25 18:37:19 -0700161static bool gDdmThreadNotification = false;
162
Elliott Hughes767a1472011-10-26 18:49:02 -0700163// DDMS GC-related settings.
164static Dbg::HpifWhen gDdmHpifWhen = Dbg::HPIF_WHEN_NEVER;
165static Dbg::HpsgWhen gDdmHpsgWhen = Dbg::HPSG_WHEN_NEVER;
166static Dbg::HpsgWhat gDdmHpsgWhat;
167static Dbg::HpsgWhen gDdmNhsgWhen = Dbg::HPSG_WHEN_NEVER;
168static Dbg::HpsgWhat gDdmNhsgWhat;
169
Elliott Hughes475fc232011-10-25 15:00:35 -0700170static ObjectRegistry* gRegistry = NULL;
171
Elliott Hughes545a0642011-11-08 19:10:03 -0800172// Recent allocation tracking.
Brian Carlstromdf629502013-07-17 22:39:56 -0700173static Mutex gAllocTrackerLock DEFAULT_MUTEX_ACQUIRED_AFTER("AllocTracker lock");
Brian Carlstrom7934ac22013-07-26 10:54:15 -0700174AllocRecord* Dbg::recent_allocation_records_ PT_GUARDED_BY(gAllocTrackerLock) = NULL; // TODO: CircularBuffer<AllocRecord>
Elliott Hughesb1a58792013-07-11 18:10:58 -0700175static size_t gAllocRecordMax GUARDED_BY(gAllocTrackerLock) = 0;
Elliott Hughesf8349362012-06-18 15:00:06 -0700176static size_t gAllocRecordHead GUARDED_BY(gAllocTrackerLock) = 0;
177static size_t gAllocRecordCount GUARDED_BY(gAllocTrackerLock) = 0;
Elliott Hughes545a0642011-11-08 19:10:03 -0800178
Sebastien Hertz138dbfc2013-12-04 18:15:25 +0100179// Deoptimization support.
180struct MethodInstrumentationRequest {
181 bool deoptimize;
182
183 // Method for selective deoptimization. NULL means full deoptimization.
184 mirror::ArtMethod* method;
185
186 MethodInstrumentationRequest(bool deoptimize, mirror::ArtMethod* method)
187 : deoptimize(deoptimize), method(method) {}
188};
189// TODO we need to visit associated methods as roots.
190static std::vector<MethodInstrumentationRequest> gDeoptimizationRequests GUARDED_BY(Locks::deoptimization_lock_);
191
192// Breakpoints.
jeffhao09bfc6a2012-12-11 18:11:43 -0800193static std::vector<Breakpoint> gBreakpoints GUARDED_BY(Locks::breakpoint_lock_);
Elliott Hughes86964332012-02-15 19:37:42 -0800194
Brian Carlstromea46f952013-07-30 01:26:50 -0700195static bool IsBreakpoint(const mirror::ArtMethod* m, uint32_t dex_pc)
jeffhao09bfc6a2012-12-11 18:11:43 -0800196 LOCKS_EXCLUDED(Locks::breakpoint_lock_)
Ian Rogersb726dcb2012-09-05 08:57:23 -0700197 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
jeffhao09bfc6a2012-12-11 18:11:43 -0800198 MutexLock mu(Thread::Current(), *Locks::breakpoint_lock_);
Sebastien Hertz138dbfc2013-12-04 18:15:25 +0100199 for (size_t i = 0, e = gBreakpoints.size(); i < e; ++i) {
Elliott Hughesa656a0f2012-02-21 18:03:44 -0800200 if (gBreakpoints[i].method == m && gBreakpoints[i].dex_pc == dex_pc) {
Elliott Hughes86964332012-02-15 19:37:42 -0800201 VLOG(jdwp) << "Hit breakpoint #" << i << ": " << gBreakpoints[i];
202 return true;
203 }
204 }
205 return false;
206}
207
Elliott Hughes9e0c1752013-01-09 14:02:58 -0800208static bool IsSuspendedForDebugger(ScopedObjectAccessUnchecked& soa, Thread* thread) {
209 MutexLock mu(soa.Self(), *Locks::thread_suspend_count_lock_);
210 // A thread may be suspended for GC; in this code, we really want to know whether
211 // there's a debugger suspension active.
212 return thread->IsSuspended() && thread->GetDebugSuspendCount() > 0;
213}
214
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800215static mirror::Array* DecodeArray(JDWP::RefTypeId id, JDWP::JdwpError& status)
Ian Rogersb726dcb2012-09-05 08:57:23 -0700216 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800217 mirror::Object* o = gRegistry->Get<mirror::Object*>(id);
Elliott Hughes64f574f2013-02-20 14:57:12 -0800218 if (o == NULL || o == ObjectRegistry::kInvalidObject) {
Elliott Hughes436e3722012-02-17 20:01:47 -0800219 status = JDWP::ERR_INVALID_OBJECT;
220 return NULL;
221 }
222 if (!o->IsArrayInstance()) {
223 status = JDWP::ERR_INVALID_ARRAY;
224 return NULL;
225 }
226 status = JDWP::ERR_NONE;
227 return o->AsArray();
228}
229
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800230static mirror::Class* DecodeClass(JDWP::RefTypeId id, JDWP::JdwpError& status)
Ian Rogersb726dcb2012-09-05 08:57:23 -0700231 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800232 mirror::Object* o = gRegistry->Get<mirror::Object*>(id);
Elliott Hughes64f574f2013-02-20 14:57:12 -0800233 if (o == NULL || o == ObjectRegistry::kInvalidObject) {
Elliott Hughes436e3722012-02-17 20:01:47 -0800234 status = JDWP::ERR_INVALID_OBJECT;
235 return NULL;
236 }
237 if (!o->IsClass()) {
238 status = JDWP::ERR_INVALID_CLASS;
239 return NULL;
240 }
241 status = JDWP::ERR_NONE;
242 return o->AsClass();
243}
244
Elliott Hughes221229c2013-01-08 18:17:50 -0800245static JDWP::JdwpError DecodeThread(ScopedObjectAccessUnchecked& soa, JDWP::ObjectId thread_id, Thread*& thread)
jeffhaoa77f0f62012-12-05 17:19:31 -0800246 EXCLUSIVE_LOCKS_REQUIRED(Locks::thread_list_lock_)
Ian Rogersb726dcb2012-09-05 08:57:23 -0700247 LOCKS_EXCLUDED(Locks::thread_suspend_count_lock_)
248 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800249 mirror::Object* thread_peer = gRegistry->Get<mirror::Object*>(thread_id);
Elliott Hughes64f574f2013-02-20 14:57:12 -0800250 if (thread_peer == NULL || thread_peer == ObjectRegistry::kInvalidObject) {
Elliott Hughes221229c2013-01-08 18:17:50 -0800251 // This isn't even an object.
252 return JDWP::ERR_INVALID_OBJECT;
Elliott Hughes436e3722012-02-17 20:01:47 -0800253 }
Elliott Hughes221229c2013-01-08 18:17:50 -0800254
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800255 mirror::Class* java_lang_Thread = soa.Decode<mirror::Class*>(WellKnownClasses::java_lang_Thread);
Elliott Hughes221229c2013-01-08 18:17:50 -0800256 if (!java_lang_Thread->IsAssignableFrom(thread_peer->GetClass())) {
257 // This isn't a thread.
258 return JDWP::ERR_INVALID_THREAD;
259 }
260
261 thread = Thread::FromManagedThread(soa, thread_peer);
262 if (thread == NULL) {
263 // This is a java.lang.Thread without a Thread*. Must be a zombie.
264 return JDWP::ERR_THREAD_NOT_ALIVE;
265 }
266 return JDWP::ERR_NONE;
Elliott Hughes436e3722012-02-17 20:01:47 -0800267}
268
Elliott Hughes24437992011-11-30 14:49:33 -0800269static JDWP::JdwpTag BasicTagFromDescriptor(const char* descriptor) {
270 // JDWP deliberately uses the descriptor characters' ASCII values for its enum.
271 // Note that by "basic" we mean that we don't get more specific than JT_OBJECT.
272 return static_cast<JDWP::JdwpTag>(descriptor[0]);
273}
274
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800275static JDWP::JdwpTag TagFromClass(mirror::Class* c)
Ian Rogersb726dcb2012-09-05 08:57:23 -0700276 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Elliott Hughes86b00102011-12-05 17:54:26 -0800277 CHECK(c != NULL);
Elliott Hughes24437992011-11-30 14:49:33 -0800278 if (c->IsArrayClass()) {
279 return JDWP::JT_ARRAY;
280 }
281
Elliott Hughes3d30d9b2011-12-07 17:35:48 -0800282 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
Elliott Hughes24437992011-11-30 14:49:33 -0800283 if (c->IsStringClass()) {
284 return JDWP::JT_STRING;
285 } else if (c->IsClassClass()) {
286 return JDWP::JT_CLASS_OBJECT;
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -0800287 } else if (class_linker->FindSystemClass("Ljava/lang/Thread;")->IsAssignableFrom(c)) {
Elliott Hughes24437992011-11-30 14:49:33 -0800288 return JDWP::JT_THREAD;
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -0800289 } else if (class_linker->FindSystemClass("Ljava/lang/ThreadGroup;")->IsAssignableFrom(c)) {
Elliott Hughes24437992011-11-30 14:49:33 -0800290 return JDWP::JT_THREAD_GROUP;
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -0800291 } else if (class_linker->FindSystemClass("Ljava/lang/ClassLoader;")->IsAssignableFrom(c)) {
Elliott Hughes24437992011-11-30 14:49:33 -0800292 return JDWP::JT_CLASS_LOADER;
Elliott Hughes24437992011-11-30 14:49:33 -0800293 } else {
294 return JDWP::JT_OBJECT;
295 }
296}
297
298/*
299 * Objects declared to hold Object might actually hold a more specific
300 * type. The debugger may take a special interest in these (e.g. it
301 * wants to display the contents of Strings), so we want to return an
302 * appropriate tag.
303 *
304 * Null objects are tagged JT_OBJECT.
305 */
Ian Rogersef7d42f2014-01-06 12:55:46 -0800306static JDWP::JdwpTag TagFromObject(mirror::Object* o)
Ian Rogersb726dcb2012-09-05 08:57:23 -0700307 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Elliott Hughes24437992011-11-30 14:49:33 -0800308 return (o == NULL) ? JDWP::JT_OBJECT : TagFromClass(o->GetClass());
309}
310
311static bool IsPrimitiveTag(JDWP::JdwpTag tag) {
312 switch (tag) {
313 case JDWP::JT_BOOLEAN:
314 case JDWP::JT_BYTE:
315 case JDWP::JT_CHAR:
316 case JDWP::JT_FLOAT:
317 case JDWP::JT_DOUBLE:
318 case JDWP::JT_INT:
319 case JDWP::JT_LONG:
320 case JDWP::JT_SHORT:
321 case JDWP::JT_VOID:
322 return true;
323 default:
324 return false;
325 }
326}
327
Elliott Hughes3bb81562011-10-21 18:52:59 -0700328/*
329 * Handle one of the JDWP name/value pairs.
330 *
331 * JDWP options are:
332 * help: if specified, show help message and bail
333 * transport: may be dt_socket or dt_shmem
334 * address: for dt_socket, "host:port", or just "port" when listening
335 * server: if "y", wait for debugger to attach; if "n", attach to debugger
336 * timeout: how long to wait for debugger to connect / listen
337 *
338 * Useful with server=n (these aren't supported yet):
339 * onthrow=<exception-name>: connect to debugger when exception thrown
340 * onuncaught=y|n: connect to debugger when uncaught exception thrown
341 * launch=<command-line>: launch the debugger itself
342 *
343 * The "transport" option is required, as is "address" if server=n.
344 */
345static bool ParseJdwpOption(const std::string& name, const std::string& value) {
346 if (name == "transport") {
347 if (value == "dt_socket") {
Elliott Hughes376a7a02011-10-24 18:35:55 -0700348 gJdwpOptions.transport = JDWP::kJdwpTransportSocket;
Elliott Hughes3bb81562011-10-21 18:52:59 -0700349 } else if (value == "dt_android_adb") {
Elliott Hughes376a7a02011-10-24 18:35:55 -0700350 gJdwpOptions.transport = JDWP::kJdwpTransportAndroidAdb;
Elliott Hughes3bb81562011-10-21 18:52:59 -0700351 } else {
352 LOG(ERROR) << "JDWP transport not supported: " << value;
353 return false;
354 }
355 } else if (name == "server") {
356 if (value == "n") {
Elliott Hughes376a7a02011-10-24 18:35:55 -0700357 gJdwpOptions.server = false;
Elliott Hughes3bb81562011-10-21 18:52:59 -0700358 } else if (value == "y") {
Elliott Hughes376a7a02011-10-24 18:35:55 -0700359 gJdwpOptions.server = true;
Elliott Hughes3bb81562011-10-21 18:52:59 -0700360 } else {
361 LOG(ERROR) << "JDWP option 'server' must be 'y' or 'n'";
362 return false;
363 }
364 } else if (name == "suspend") {
365 if (value == "n") {
Elliott Hughes376a7a02011-10-24 18:35:55 -0700366 gJdwpOptions.suspend = false;
Elliott Hughes3bb81562011-10-21 18:52:59 -0700367 } else if (value == "y") {
Elliott Hughes376a7a02011-10-24 18:35:55 -0700368 gJdwpOptions.suspend = true;
Elliott Hughes3bb81562011-10-21 18:52:59 -0700369 } else {
370 LOG(ERROR) << "JDWP option 'suspend' must be 'y' or 'n'";
371 return false;
372 }
373 } else if (name == "address") {
374 /* this is either <port> or <host>:<port> */
375 std::string port_string;
Elliott Hughes376a7a02011-10-24 18:35:55 -0700376 gJdwpOptions.host.clear();
Elliott Hughes3bb81562011-10-21 18:52:59 -0700377 std::string::size_type colon = value.find(':');
378 if (colon != std::string::npos) {
Elliott Hughes376a7a02011-10-24 18:35:55 -0700379 gJdwpOptions.host = value.substr(0, colon);
Elliott Hughes3bb81562011-10-21 18:52:59 -0700380 port_string = value.substr(colon + 1);
381 } else {
382 port_string = value;
383 }
384 if (port_string.empty()) {
385 LOG(ERROR) << "JDWP address missing port: " << value;
386 return false;
387 }
388 char* end;
Elliott Hughesba8eee12012-01-24 20:25:24 -0800389 uint64_t port = strtoul(port_string.c_str(), &end, 10);
390 if (*end != '\0' || port > 0xffff) {
Elliott Hughes3bb81562011-10-21 18:52:59 -0700391 LOG(ERROR) << "JDWP address has junk in port field: " << value;
392 return false;
393 }
Elliott Hughes376a7a02011-10-24 18:35:55 -0700394 gJdwpOptions.port = port;
Elliott Hughes3bb81562011-10-21 18:52:59 -0700395 } else if (name == "launch" || name == "onthrow" || name == "oncaught" || name == "timeout") {
396 /* valid but unsupported */
397 LOG(INFO) << "Ignoring JDWP option '" << name << "'='" << value << "'";
398 } else {
399 LOG(INFO) << "Ignoring unrecognized JDWP option '" << name << "'='" << value << "'";
400 }
401
402 return true;
403}
404
405/*
406 * Parse the latter half of a -Xrunjdwp/-agentlib:jdwp= string, e.g.:
407 * "transport=dt_socket,address=8000,server=y,suspend=n"
408 */
409bool Dbg::ParseJdwpOptions(const std::string& options) {
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -0800410 VLOG(jdwp) << "ParseJdwpOptions: " << options;
Elliott Hughes47fce012011-10-25 18:37:19 -0700411
Elliott Hughes3bb81562011-10-21 18:52:59 -0700412 std::vector<std::string> pairs;
413 Split(options, ',', pairs);
414
415 for (size_t i = 0; i < pairs.size(); ++i) {
416 std::string::size_type equals = pairs[i].find('=');
417 if (equals == std::string::npos) {
418 LOG(ERROR) << "Can't parse JDWP option '" << pairs[i] << "' in '" << options << "'";
419 return false;
420 }
421 ParseJdwpOption(pairs[i].substr(0, equals), pairs[i].substr(equals + 1));
422 }
423
Elliott Hughes376a7a02011-10-24 18:35:55 -0700424 if (gJdwpOptions.transport == JDWP::kJdwpTransportUnknown) {
Elliott Hughes3bb81562011-10-21 18:52:59 -0700425 LOG(ERROR) << "Must specify JDWP transport: " << options;
426 }
Elliott Hughes376a7a02011-10-24 18:35:55 -0700427 if (!gJdwpOptions.server && (gJdwpOptions.host.empty() || gJdwpOptions.port == 0)) {
Elliott Hughes3bb81562011-10-21 18:52:59 -0700428 LOG(ERROR) << "Must specify JDWP host and port when server=n: " << options;
429 return false;
430 }
431
432 gJdwpConfigured = true;
433 return true;
434}
435
Elliott Hughesd1cc8362011-10-24 16:58:50 -0700436void Dbg::StartJdwp() {
Elliott Hughesc0f09332012-03-26 13:27:06 -0700437 if (!gJdwpAllowed || !IsJdwpConfigured()) {
Elliott Hughes376a7a02011-10-24 18:35:55 -0700438 // No JDWP for you!
439 return;
440 }
441
Elliott Hughes475fc232011-10-25 15:00:35 -0700442 CHECK(gRegistry == NULL);
443 gRegistry = new ObjectRegistry;
444
Elliott Hughesd1cc8362011-10-24 16:58:50 -0700445 // Init JDWP if the debugger is enabled. This may connect out to a
446 // debugger, passively listen for a debugger, or block waiting for a
447 // debugger.
Elliott Hughes376a7a02011-10-24 18:35:55 -0700448 gJdwpState = JDWP::JdwpState::Create(&gJdwpOptions);
449 if (gJdwpState == NULL) {
Elliott Hughesf8a2df72011-12-01 12:19:54 -0800450 // We probably failed because some other process has the port already, which means that
451 // if we don't abort the user is likely to think they're talking to us when they're actually
452 // talking to that other process.
Elliott Hughes3d30d9b2011-12-07 17:35:48 -0800453 LOG(FATAL) << "Debugger thread failed to initialize";
Elliott Hughesd1cc8362011-10-24 16:58:50 -0700454 }
455
456 // If a debugger has already attached, send the "welcome" message.
457 // This may cause us to suspend all threads.
Elliott Hughes376a7a02011-10-24 18:35:55 -0700458 if (gJdwpState->IsActive()) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700459 ScopedObjectAccess soa(Thread::Current());
Elliott Hughes376a7a02011-10-24 18:35:55 -0700460 if (!gJdwpState->PostVMStart()) {
Elliott Hughes3d30d9b2011-12-07 17:35:48 -0800461 LOG(WARNING) << "Failed to post 'start' message to debugger";
Elliott Hughesd1cc8362011-10-24 16:58:50 -0700462 }
463 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700464}
465
Elliott Hughesd1cc8362011-10-24 16:58:50 -0700466void Dbg::StopJdwp() {
Sebastien Hertz0376e6b2014-02-06 18:12:59 +0100467 // Prevent the JDWP thread from processing JDWP incoming packets after we close the connection.
468 Disposed();
Elliott Hughes376a7a02011-10-24 18:35:55 -0700469 delete gJdwpState;
Sebastien Hertz123756a2013-11-27 15:49:42 +0100470 gJdwpState = NULL;
Elliott Hughes475fc232011-10-25 15:00:35 -0700471 delete gRegistry;
472 gRegistry = NULL;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700473}
474
Elliott Hughes767a1472011-10-26 18:49:02 -0700475void Dbg::GcDidFinish() {
476 if (gDdmHpifWhen != HPIF_WHEN_NEVER) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700477 ScopedObjectAccess soa(Thread::Current());
Elliott Hughes81ff3182012-03-23 20:35:56 -0700478 LOG(DEBUG) << "Sending heap info to DDM";
Elliott Hughes7162ad92011-10-27 14:08:42 -0700479 DdmSendHeapInfo(gDdmHpifWhen);
Elliott Hughes767a1472011-10-26 18:49:02 -0700480 }
481 if (gDdmHpsgWhen != HPSG_WHEN_NEVER) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700482 ScopedObjectAccess soa(Thread::Current());
Elliott Hughes81ff3182012-03-23 20:35:56 -0700483 LOG(DEBUG) << "Dumping heap to DDM";
Elliott Hughes6a5bd492011-10-28 14:33:57 -0700484 DdmSendHeapSegments(false);
Elliott Hughes767a1472011-10-26 18:49:02 -0700485 }
486 if (gDdmNhsgWhen != HPSG_WHEN_NEVER) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700487 ScopedObjectAccess soa(Thread::Current());
Elliott Hughes767a1472011-10-26 18:49:02 -0700488 LOG(DEBUG) << "Dumping native heap to DDM";
Elliott Hughes6a5bd492011-10-28 14:33:57 -0700489 DdmSendHeapSegments(true);
Elliott Hughes767a1472011-10-26 18:49:02 -0700490 }
491}
492
Elliott Hughes4ffd3132011-10-24 12:06:42 -0700493void Dbg::SetJdwpAllowed(bool allowed) {
494 gJdwpAllowed = allowed;
495}
496
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700497DebugInvokeReq* Dbg::GetInvokeReq() {
Elliott Hughes475fc232011-10-25 15:00:35 -0700498 return Thread::Current()->GetInvokeReq();
499}
500
501Thread* Dbg::GetDebugThread() {
502 return (gJdwpState != NULL) ? gJdwpState->GetDebugThread() : NULL;
503}
504
505void Dbg::ClearWaitForEventThread() {
506 gJdwpState->ClearWaitForEventThread();
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700507}
508
509void Dbg::Connected() {
Elliott Hughes3bb81562011-10-21 18:52:59 -0700510 CHECK(!gDebuggerConnected);
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -0800511 VLOG(jdwp) << "JDWP has attached";
Elliott Hughes3bb81562011-10-21 18:52:59 -0700512 gDebuggerConnected = true;
Elliott Hughes86964332012-02-15 19:37:42 -0800513 gDisposed = false;
514}
515
516void Dbg::Disposed() {
517 gDisposed = true;
518}
519
520bool Dbg::IsDisposed() {
521 return gDisposed;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700522}
523
Elliott Hughesa2155262011-11-16 16:26:58 -0800524void Dbg::GoActive() {
525 // Enable all debugging features, including scans for breakpoints.
526 // This is a no-op if we're already active.
527 // Only called from the JDWP handler thread.
528 if (gDebuggerActive) {
529 return;
530 }
531
Elliott Hughesc0f09332012-03-26 13:27:06 -0700532 {
533 // TODO: dalvik only warned if there were breakpoints left over. clear in Dbg::Disconnected?
jeffhao09bfc6a2012-12-11 18:11:43 -0800534 MutexLock mu(Thread::Current(), *Locks::breakpoint_lock_);
Elliott Hughesc0f09332012-03-26 13:27:06 -0700535 CHECK_EQ(gBreakpoints.size(), 0U);
536 }
Elliott Hughesa2155262011-11-16 16:26:58 -0800537
Sebastien Hertz138dbfc2013-12-04 18:15:25 +0100538 {
539 MutexLock mu(Thread::Current(), *Locks::deoptimization_lock_);
540 CHECK_EQ(gDeoptimizationRequests.size(), 0U);
541 }
542
Ian Rogers62d6c772013-02-27 08:32:07 -0800543 Runtime* runtime = Runtime::Current();
544 runtime->GetThreadList()->SuspendAll();
545 Thread* self = Thread::Current();
546 ThreadState old_state = self->SetStateUnsafe(kRunnable);
547 CHECK_NE(old_state, kRunnable);
Sebastien Hertz138dbfc2013-12-04 18:15:25 +0100548 runtime->GetInstrumentation()->EnableDeoptimization();
Ian Rogers62d6c772013-02-27 08:32:07 -0800549 runtime->GetInstrumentation()->AddListener(&gDebugInstrumentationListener,
550 instrumentation::Instrumentation::kMethodEntered |
551 instrumentation::Instrumentation::kMethodExited |
Jeff Hao14dd5a82013-04-11 10:23:36 -0700552 instrumentation::Instrumentation::kDexPcMoved |
553 instrumentation::Instrumentation::kExceptionCaught);
Elliott Hughesa2155262011-11-16 16:26:58 -0800554 gDebuggerActive = true;
Ian Rogers62d6c772013-02-27 08:32:07 -0800555 CHECK_EQ(self->SetStateUnsafe(old_state), kRunnable);
556 runtime->GetThreadList()->ResumeAll();
557
558 LOG(INFO) << "Debugger is active";
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700559}
560
561void Dbg::Disconnected() {
Elliott Hughes234ab152011-10-26 14:02:26 -0700562 CHECK(gDebuggerConnected);
563
Elliott Hughesc0f09332012-03-26 13:27:06 -0700564 LOG(INFO) << "Debugger is no longer active";
Elliott Hughes234ab152011-10-26 14:02:26 -0700565
Ian Rogers62d6c772013-02-27 08:32:07 -0800566 // Suspend all threads and exclusively acquire the mutator lock. Set the state of the thread
567 // to kRunnable to avoid scoped object access transitions. Remove the debugger as a listener
568 // and clear the object registry.
569 Runtime* runtime = Runtime::Current();
570 runtime->GetThreadList()->SuspendAll();
571 Thread* self = Thread::Current();
572 ThreadState old_state = self->SetStateUnsafe(kRunnable);
Sebastien Hertz138dbfc2013-12-04 18:15:25 +0100573 {
574 // Since we're going to disable deoptimization, we clear the deoptimization requests queue.
575 // This prevent us from having any pending deoptimization request when the debugger attaches to
576 // us again while no event has been requested yet.
577 MutexLock mu(Thread::Current(), *Locks::deoptimization_lock_);
578 gDeoptimizationRequests.clear();
579 }
580 runtime->GetInstrumentation()->DisableDeoptimization();
Ian Rogers62d6c772013-02-27 08:32:07 -0800581 runtime->GetInstrumentation()->RemoveListener(&gDebugInstrumentationListener,
582 instrumentation::Instrumentation::kMethodEntered |
583 instrumentation::Instrumentation::kMethodExited |
Jeff Hao14dd5a82013-04-11 10:23:36 -0700584 instrumentation::Instrumentation::kDexPcMoved |
585 instrumentation::Instrumentation::kExceptionCaught);
Elliott Hughesc0f09332012-03-26 13:27:06 -0700586 gDebuggerActive = false;
Elliott Hughes234ab152011-10-26 14:02:26 -0700587 gRegistry->Clear();
588 gDebuggerConnected = false;
Ian Rogers62d6c772013-02-27 08:32:07 -0800589 CHECK_EQ(self->SetStateUnsafe(old_state), kRunnable);
590 runtime->GetThreadList()->ResumeAll();
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700591}
592
Elliott Hughesc0f09332012-03-26 13:27:06 -0700593bool Dbg::IsDebuggerActive() {
Elliott Hughes3bb81562011-10-21 18:52:59 -0700594 return gDebuggerActive;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700595}
596
Elliott Hughesc0f09332012-03-26 13:27:06 -0700597bool Dbg::IsJdwpConfigured() {
Elliott Hughes3bb81562011-10-21 18:52:59 -0700598 return gJdwpConfigured;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700599}
600
601int64_t Dbg::LastDebuggerActivity() {
Elliott Hughesca951522011-12-05 12:01:32 -0800602 return gJdwpState->LastDebuggerActivity();
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700603}
604
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700605void Dbg::UndoDebuggerSuspensions() {
Elliott Hughes234ab152011-10-26 14:02:26 -0700606 Runtime::Current()->GetThreadList()->UndoDebuggerSuspensions();
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700607}
608
Elliott Hughes88d63092013-01-09 09:55:54 -0800609std::string Dbg::GetClassName(JDWP::RefTypeId class_id) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800610 mirror::Object* o = gRegistry->Get<mirror::Object*>(class_id);
Elliott Hughes436e3722012-02-17 20:01:47 -0800611 if (o == NULL) {
612 return "NULL";
613 }
Elliott Hughes64f574f2013-02-20 14:57:12 -0800614 if (o == ObjectRegistry::kInvalidObject) {
Elliott Hughes88d63092013-01-09 09:55:54 -0800615 return StringPrintf("invalid object %p", reinterpret_cast<void*>(class_id));
Elliott Hughes436e3722012-02-17 20:01:47 -0800616 }
617 if (!o->IsClass()) {
Brian Carlstrom7934ac22013-07-26 10:54:15 -0700618 return StringPrintf("non-class %p", o); // This is only used for debugging output anyway.
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -0800619 }
Elliott Hughesc308a5d2012-02-16 17:12:06 -0800620 return DescriptorToName(ClassHelper(o->AsClass()).GetDescriptor());
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700621}
622
Elliott Hughes88d63092013-01-09 09:55:54 -0800623JDWP::JdwpError Dbg::GetClassObject(JDWP::RefTypeId id, JDWP::ObjectId& class_object_id) {
Elliott Hughes436e3722012-02-17 20:01:47 -0800624 JDWP::JdwpError status;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800625 mirror::Class* c = DecodeClass(id, status);
Elliott Hughes436e3722012-02-17 20:01:47 -0800626 if (c == NULL) {
627 return status;
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -0800628 }
Elliott Hughes88d63092013-01-09 09:55:54 -0800629 class_object_id = gRegistry->Add(c);
Elliott Hughes436e3722012-02-17 20:01:47 -0800630 return JDWP::ERR_NONE;
Elliott Hughes86964332012-02-15 19:37:42 -0800631}
632
Elliott Hughes88d63092013-01-09 09:55:54 -0800633JDWP::JdwpError Dbg::GetSuperclass(JDWP::RefTypeId id, JDWP::RefTypeId& superclass_id) {
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -0800634 JDWP::JdwpError status;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800635 mirror::Class* c = DecodeClass(id, status);
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -0800636 if (c == NULL) {
637 return status;
638 }
639 if (c->IsInterface()) {
640 // http://code.google.com/p/android/issues/detail?id=20856
Elliott Hughes88d63092013-01-09 09:55:54 -0800641 superclass_id = 0;
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -0800642 } else {
Elliott Hughes88d63092013-01-09 09:55:54 -0800643 superclass_id = gRegistry->Add(c->GetSuperClass());
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -0800644 }
645 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700646}
647
Elliott Hughes436e3722012-02-17 20:01:47 -0800648JDWP::JdwpError Dbg::GetClassLoader(JDWP::RefTypeId id, JDWP::ExpandBuf* pReply) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800649 mirror::Object* o = gRegistry->Get<mirror::Object*>(id);
Elliott Hughes64f574f2013-02-20 14:57:12 -0800650 if (o == NULL || o == ObjectRegistry::kInvalidObject) {
Elliott Hughes436e3722012-02-17 20:01:47 -0800651 return JDWP::ERR_INVALID_OBJECT;
652 }
653 expandBufAddObjectId(pReply, gRegistry->Add(o->GetClass()->GetClassLoader()));
654 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700655}
656
Elliott Hughes436e3722012-02-17 20:01:47 -0800657JDWP::JdwpError Dbg::GetModifiers(JDWP::RefTypeId id, JDWP::ExpandBuf* pReply) {
658 JDWP::JdwpError status;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800659 mirror::Class* c = DecodeClass(id, status);
Elliott Hughes436e3722012-02-17 20:01:47 -0800660 if (c == NULL) {
661 return status;
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -0800662 }
Elliott Hughes436e3722012-02-17 20:01:47 -0800663
664 uint32_t access_flags = c->GetAccessFlags() & kAccJavaFlagsMask;
665
666 // Set ACC_SUPER; dex files don't contain this flag, but all classes are supposed to have it set.
667 // Class.getModifiers doesn't return it, but JDWP does, so we set it here.
668 access_flags |= kAccSuper;
669
670 expandBufAdd4BE(pReply, access_flags);
671
672 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700673}
674
Elliott Hughesf327e072013-01-09 16:01:26 -0800675JDWP::JdwpError Dbg::GetMonitorInfo(JDWP::ObjectId object_id, JDWP::ExpandBuf* reply)
676 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800677 mirror::Object* o = gRegistry->Get<mirror::Object*>(object_id);
Elliott Hughes64f574f2013-02-20 14:57:12 -0800678 if (o == NULL || o == ObjectRegistry::kInvalidObject) {
Elliott Hughesf327e072013-01-09 16:01:26 -0800679 return JDWP::ERR_INVALID_OBJECT;
680 }
681
682 // Ensure all threads are suspended while we read objects' lock words.
683 Thread* self = Thread::Current();
684 Locks::mutator_lock_->SharedUnlock(self);
685 Locks::mutator_lock_->ExclusiveLock(self);
686
687 MonitorInfo monitor_info(o);
688
689 Locks::mutator_lock_->ExclusiveUnlock(self);
690 Locks::mutator_lock_->SharedLock(self);
691
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700692 if (monitor_info.owner_ != NULL) {
693 expandBufAddObjectId(reply, gRegistry->Add(monitor_info.owner_->GetPeer()));
Elliott Hughesf327e072013-01-09 16:01:26 -0800694 } else {
695 expandBufAddObjectId(reply, gRegistry->Add(NULL));
696 }
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700697 expandBufAdd4BE(reply, monitor_info.entry_count_);
698 expandBufAdd4BE(reply, monitor_info.waiters_.size());
699 for (size_t i = 0; i < monitor_info.waiters_.size(); ++i) {
700 expandBufAddObjectId(reply, gRegistry->Add(monitor_info.waiters_[i]->GetPeer()));
Elliott Hughesf327e072013-01-09 16:01:26 -0800701 }
702 return JDWP::ERR_NONE;
703}
704
Elliott Hughes734b8c62013-01-11 15:32:45 -0800705JDWP::JdwpError Dbg::GetOwnedMonitors(JDWP::ObjectId thread_id,
706 std::vector<JDWP::ObjectId>& monitors,
707 std::vector<uint32_t>& stack_depths)
Elliott Hughes4993bbc2013-01-10 15:41:25 -0800708 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
709 ScopedObjectAccessUnchecked soa(Thread::Current());
710 MutexLock mu(soa.Self(), *Locks::thread_list_lock_);
711 Thread* thread;
712 JDWP::JdwpError error = DecodeThread(soa, thread_id, thread);
713 if (error != JDWP::ERR_NONE) {
714 return error;
715 }
716 if (!IsSuspendedForDebugger(soa, thread)) {
717 return JDWP::ERR_THREAD_NOT_SUSPENDED;
718 }
719
720 struct OwnedMonitorVisitor : public StackVisitor {
Ian Rogers7a22fa62013-01-23 12:16:16 -0800721 OwnedMonitorVisitor(Thread* thread, Context* context)
Elliott Hughes4993bbc2013-01-10 15:41:25 -0800722 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_)
Ian Rogers7a22fa62013-01-23 12:16:16 -0800723 : StackVisitor(thread, context), current_stack_depth(0) {}
Elliott Hughes4993bbc2013-01-10 15:41:25 -0800724
725 // TODO: Enable annotalysis. We know lock is held in constructor, but abstraction confuses
726 // annotalysis.
727 bool VisitFrame() NO_THREAD_SAFETY_ANALYSIS {
728 if (!GetMethod()->IsRuntimeMethod()) {
729 Monitor::VisitLocks(this, AppendOwnedMonitors, this);
Elliott Hughes734b8c62013-01-11 15:32:45 -0800730 ++current_stack_depth;
Elliott Hughes4993bbc2013-01-10 15:41:25 -0800731 }
732 return true;
733 }
734
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800735 static void AppendOwnedMonitors(mirror::Object* owned_monitor, void* arg) {
Ian Rogers7a22fa62013-01-23 12:16:16 -0800736 OwnedMonitorVisitor* visitor = reinterpret_cast<OwnedMonitorVisitor*>(arg);
Elliott Hughes734b8c62013-01-11 15:32:45 -0800737 visitor->monitors.push_back(owned_monitor);
738 visitor->stack_depths.push_back(visitor->current_stack_depth);
Elliott Hughes4993bbc2013-01-10 15:41:25 -0800739 }
740
Elliott Hughes734b8c62013-01-11 15:32:45 -0800741 size_t current_stack_depth;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800742 std::vector<mirror::Object*> monitors;
Elliott Hughes734b8c62013-01-11 15:32:45 -0800743 std::vector<uint32_t> stack_depths;
Elliott Hughes4993bbc2013-01-10 15:41:25 -0800744 };
Ian Rogers7a22fa62013-01-23 12:16:16 -0800745 UniquePtr<Context> context(Context::Create());
746 OwnedMonitorVisitor visitor(thread, context.get());
Elliott Hughes4993bbc2013-01-10 15:41:25 -0800747 visitor.WalkStack();
748
749 for (size_t i = 0; i < visitor.monitors.size(); ++i) {
750 monitors.push_back(gRegistry->Add(visitor.monitors[i]));
Elliott Hughes734b8c62013-01-11 15:32:45 -0800751 stack_depths.push_back(visitor.stack_depths[i]);
Elliott Hughes4993bbc2013-01-10 15:41:25 -0800752 }
753
754 return JDWP::ERR_NONE;
755}
756
Elliott Hughesf9501702013-01-11 11:22:27 -0800757JDWP::JdwpError Dbg::GetContendedMonitor(JDWP::ObjectId thread_id, JDWP::ObjectId& contended_monitor)
758 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
759 ScopedObjectAccessUnchecked soa(Thread::Current());
760 MutexLock mu(soa.Self(), *Locks::thread_list_lock_);
761 Thread* thread;
762 JDWP::JdwpError error = DecodeThread(soa, thread_id, thread);
763 if (error != JDWP::ERR_NONE) {
764 return error;
765 }
766 if (!IsSuspendedForDebugger(soa, thread)) {
767 return JDWP::ERR_THREAD_NOT_SUSPENDED;
768 }
769
770 contended_monitor = gRegistry->Add(Monitor::GetContendedMonitor(thread));
771
772 return JDWP::ERR_NONE;
773}
774
Elliott Hughesec0f83d2013-01-15 16:54:08 -0800775JDWP::JdwpError Dbg::GetInstanceCounts(const std::vector<JDWP::RefTypeId>& class_ids,
776 std::vector<uint64_t>& counts)
777 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800778 std::vector<mirror::Class*> classes;
Elliott Hughesec0f83d2013-01-15 16:54:08 -0800779 counts.clear();
780 for (size_t i = 0; i < class_ids.size(); ++i) {
781 JDWP::JdwpError status;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800782 mirror::Class* c = DecodeClass(class_ids[i], status);
Elliott Hughesec0f83d2013-01-15 16:54:08 -0800783 if (c == NULL) {
784 return status;
785 }
786 classes.push_back(c);
787 counts.push_back(0);
788 }
789
790 Runtime::Current()->GetHeap()->CountInstances(classes, false, &counts[0]);
791 return JDWP::ERR_NONE;
792}
793
Elliott Hughes3b78c942013-01-15 17:35:41 -0800794JDWP::JdwpError Dbg::GetInstances(JDWP::RefTypeId class_id, int32_t max_count, std::vector<JDWP::ObjectId>& instances)
795 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
796 JDWP::JdwpError status;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800797 mirror::Class* c = DecodeClass(class_id, status);
Elliott Hughes3b78c942013-01-15 17:35:41 -0800798 if (c == NULL) {
799 return status;
800 }
801
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800802 std::vector<mirror::Object*> raw_instances;
Elliott Hughes3b78c942013-01-15 17:35:41 -0800803 Runtime::Current()->GetHeap()->GetInstances(c, max_count, raw_instances);
804 for (size_t i = 0; i < raw_instances.size(); ++i) {
805 instances.push_back(gRegistry->Add(raw_instances[i]));
806 }
807 return JDWP::ERR_NONE;
808}
809
Elliott Hughes0cbaff52013-01-16 15:28:01 -0800810JDWP::JdwpError Dbg::GetReferringObjects(JDWP::ObjectId object_id, int32_t max_count,
811 std::vector<JDWP::ObjectId>& referring_objects)
812 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800813 mirror::Object* o = gRegistry->Get<mirror::Object*>(object_id);
Elliott Hughes64f574f2013-02-20 14:57:12 -0800814 if (o == NULL || o == ObjectRegistry::kInvalidObject) {
Elliott Hughes0cbaff52013-01-16 15:28:01 -0800815 return JDWP::ERR_INVALID_OBJECT;
816 }
817
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800818 std::vector<mirror::Object*> raw_instances;
Elliott Hughes0cbaff52013-01-16 15:28:01 -0800819 Runtime::Current()->GetHeap()->GetReferringObjects(o, max_count, raw_instances);
820 for (size_t i = 0; i < raw_instances.size(); ++i) {
821 referring_objects.push_back(gRegistry->Add(raw_instances[i]));
822 }
823 return JDWP::ERR_NONE;
824}
825
Elliott Hughes64f574f2013-02-20 14:57:12 -0800826JDWP::JdwpError Dbg::DisableCollection(JDWP::ObjectId object_id)
827 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Sebastien Hertze96060a2013-12-11 12:06:28 +0100828 mirror::Object* o = gRegistry->Get<mirror::Object*>(object_id);
829 if (o == NULL || o == ObjectRegistry::kInvalidObject) {
830 return JDWP::ERR_INVALID_OBJECT;
831 }
Elliott Hughes64f574f2013-02-20 14:57:12 -0800832 gRegistry->DisableCollection(object_id);
833 return JDWP::ERR_NONE;
834}
835
836JDWP::JdwpError Dbg::EnableCollection(JDWP::ObjectId object_id)
837 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Sebastien Hertze96060a2013-12-11 12:06:28 +0100838 mirror::Object* o = gRegistry->Get<mirror::Object*>(object_id);
839 // Unlike DisableCollection, JDWP specs do not state an invalid object causes an error. The RI
840 // also ignores these cases and never return an error. However it's not obvious why this command
841 // should behave differently from DisableCollection and IsCollected commands. So let's be more
842 // strict and return an error if this happens.
843 if (o == NULL || o == ObjectRegistry::kInvalidObject) {
844 return JDWP::ERR_INVALID_OBJECT;
845 }
Elliott Hughes64f574f2013-02-20 14:57:12 -0800846 gRegistry->EnableCollection(object_id);
847 return JDWP::ERR_NONE;
848}
849
850JDWP::JdwpError Dbg::IsCollected(JDWP::ObjectId object_id, bool& is_collected)
851 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Sebastien Hertz65637eb2014-01-10 17:40:02 +0100852 if (object_id == 0) {
853 // Null object id is invalid.
Sebastien Hertze96060a2013-12-11 12:06:28 +0100854 return JDWP::ERR_INVALID_OBJECT;
855 }
Sebastien Hertz65637eb2014-01-10 17:40:02 +0100856 // JDWP specs state an INVALID_OBJECT error is returned if the object ID is not valid. However
857 // the RI seems to ignore this and assume object has been collected.
858 mirror::Object* o = gRegistry->Get<mirror::Object*>(object_id);
859 if (o == NULL || o == ObjectRegistry::kInvalidObject) {
860 is_collected = true;
861 } else {
862 is_collected = gRegistry->IsCollected(object_id);
863 }
Elliott Hughes64f574f2013-02-20 14:57:12 -0800864 return JDWP::ERR_NONE;
865}
866
867void Dbg::DisposeObject(JDWP::ObjectId object_id, uint32_t reference_count)
868 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
869 gRegistry->DisposeObject(object_id, reference_count);
870}
871
Elliott Hughes88d63092013-01-09 09:55:54 -0800872JDWP::JdwpError Dbg::GetReflectedType(JDWP::RefTypeId class_id, JDWP::ExpandBuf* pReply) {
Elliott Hughes436e3722012-02-17 20:01:47 -0800873 JDWP::JdwpError status;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800874 mirror::Class* c = DecodeClass(class_id, status);
Elliott Hughes436e3722012-02-17 20:01:47 -0800875 if (c == NULL) {
876 return status;
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -0800877 }
Elliott Hughes436e3722012-02-17 20:01:47 -0800878
879 expandBufAdd1(pReply, c->IsInterface() ? JDWP::TT_INTERFACE : JDWP::TT_CLASS);
Elliott Hughes88d63092013-01-09 09:55:54 -0800880 expandBufAddRefTypeId(pReply, class_id);
Elliott Hughes436e3722012-02-17 20:01:47 -0800881 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700882}
883
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -0800884void Dbg::GetClassList(std::vector<JDWP::RefTypeId>& classes) {
Elliott Hughesa2155262011-11-16 16:26:58 -0800885 // Get the complete list of reference classes (i.e. all classes except
886 // the primitive types).
887 // Returns a newly-allocated buffer full of RefTypeId values.
888 struct ClassListCreator {
Elliott Hughesba8eee12012-01-24 20:25:24 -0800889 explicit ClassListCreator(std::vector<JDWP::RefTypeId>& classes) : classes(classes) {
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -0800890 }
891
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800892 static bool Visit(mirror::Class* c, void* arg) {
Elliott Hughesa2155262011-11-16 16:26:58 -0800893 return reinterpret_cast<ClassListCreator*>(arg)->Visit(c);
894 }
895
Elliott Hughes64f574f2013-02-20 14:57:12 -0800896 // TODO: Enable annotalysis. We know lock is held in constructor, but abstraction confuses
897 // annotalysis.
898 bool Visit(mirror::Class* c) NO_THREAD_SAFETY_ANALYSIS {
Elliott Hughesa2155262011-11-16 16:26:58 -0800899 if (!c->IsPrimitive()) {
Elliott Hughes64f574f2013-02-20 14:57:12 -0800900 classes.push_back(gRegistry->AddRefType(c));
Elliott Hughesa2155262011-11-16 16:26:58 -0800901 }
902 return true;
903 }
904
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -0800905 std::vector<JDWP::RefTypeId>& classes;
Elliott Hughesa2155262011-11-16 16:26:58 -0800906 };
907
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -0800908 ClassListCreator clc(classes);
Elliott Hughesa2155262011-11-16 16:26:58 -0800909 Runtime::Current()->GetClassLinker()->VisitClasses(ClassListCreator::Visit, &clc);
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700910}
911
Elliott Hughes88d63092013-01-09 09:55:54 -0800912JDWP::JdwpError Dbg::GetClassInfo(JDWP::RefTypeId class_id, JDWP::JdwpTypeTag* pTypeTag, uint32_t* pStatus, std::string* pDescriptor) {
Elliott Hughes436e3722012-02-17 20:01:47 -0800913 JDWP::JdwpError status;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800914 mirror::Class* c = DecodeClass(class_id, status);
Elliott Hughes436e3722012-02-17 20:01:47 -0800915 if (c == NULL) {
916 return status;
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -0800917 }
918
Elliott Hughesa2155262011-11-16 16:26:58 -0800919 if (c->IsArrayClass()) {
920 *pStatus = JDWP::CS_VERIFIED | JDWP::CS_PREPARED;
921 *pTypeTag = JDWP::TT_ARRAY;
922 } else {
923 if (c->IsErroneous()) {
924 *pStatus = JDWP::CS_ERROR;
925 } else {
926 *pStatus = JDWP::CS_VERIFIED | JDWP::CS_PREPARED | JDWP::CS_INITIALIZED;
927 }
928 *pTypeTag = c->IsInterface() ? JDWP::TT_INTERFACE : JDWP::TT_CLASS;
929 }
930
931 if (pDescriptor != NULL) {
Ian Rogersdfb325e2013-10-30 01:00:44 -0700932 *pDescriptor = ClassHelper(c).GetDescriptor();
Elliott Hughesa2155262011-11-16 16:26:58 -0800933 }
Elliott Hughes436e3722012-02-17 20:01:47 -0800934 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700935}
936
Elliott Hughesc3b77c72011-12-15 20:56:48 -0800937void Dbg::FindLoadedClassBySignature(const char* descriptor, std::vector<JDWP::RefTypeId>& ids) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800938 std::vector<mirror::Class*> classes;
Elliott Hughes6fa602d2011-12-02 17:54:25 -0800939 Runtime::Current()->GetClassLinker()->LookupClasses(descriptor, classes);
940 ids.clear();
941 for (size_t i = 0; i < classes.size(); ++i) {
942 ids.push_back(gRegistry->Add(classes[i]));
943 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700944}
945
Elliott Hughes64f574f2013-02-20 14:57:12 -0800946JDWP::JdwpError Dbg::GetReferenceType(JDWP::ObjectId object_id, JDWP::ExpandBuf* pReply)
947 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800948 mirror::Object* o = gRegistry->Get<mirror::Object*>(object_id);
Elliott Hughes64f574f2013-02-20 14:57:12 -0800949 if (o == NULL || o == ObjectRegistry::kInvalidObject) {
Elliott Hughes2435a572012-02-17 16:07:41 -0800950 return JDWP::ERR_INVALID_OBJECT;
Elliott Hughes499c5132011-11-17 14:55:11 -0800951 }
Elliott Hughes2435a572012-02-17 16:07:41 -0800952
953 JDWP::JdwpTypeTag type_tag;
954 if (o->GetClass()->IsArrayClass()) {
955 type_tag = JDWP::TT_ARRAY;
956 } else if (o->GetClass()->IsInterface()) {
957 type_tag = JDWP::TT_INTERFACE;
958 } else {
959 type_tag = JDWP::TT_CLASS;
960 }
Elliott Hughes64f574f2013-02-20 14:57:12 -0800961 JDWP::RefTypeId type_id = gRegistry->AddRefType(o->GetClass());
Elliott Hughes2435a572012-02-17 16:07:41 -0800962
963 expandBufAdd1(pReply, type_tag);
964 expandBufAddRefTypeId(pReply, type_id);
965
966 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700967}
968
Ian Rogersfc0e94b2013-09-23 23:51:32 -0700969JDWP::JdwpError Dbg::GetSignature(JDWP::RefTypeId class_id, std::string* signature) {
Elliott Hughes1fe7afb2012-02-13 17:23:03 -0800970 JDWP::JdwpError status;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800971 mirror::Class* c = DecodeClass(class_id, status);
Elliott Hughes1fe7afb2012-02-13 17:23:03 -0800972 if (c == NULL) {
973 return status;
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -0800974 }
Ian Rogersdfb325e2013-10-30 01:00:44 -0700975 *signature = ClassHelper(c).GetDescriptor();
Elliott Hughes1fe7afb2012-02-13 17:23:03 -0800976 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700977}
978
Elliott Hughes88d63092013-01-09 09:55:54 -0800979JDWP::JdwpError Dbg::GetSourceFile(JDWP::RefTypeId class_id, std::string& result) {
Elliott Hughes436e3722012-02-17 20:01:47 -0800980 JDWP::JdwpError status;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800981 mirror::Class* c = DecodeClass(class_id, status);
Elliott Hughes436e3722012-02-17 20:01:47 -0800982 if (c == NULL) {
983 return status;
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -0800984 }
Elliott Hughes436e3722012-02-17 20:01:47 -0800985 result = ClassHelper(c).GetSourceFile();
986 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700987}
988
Elliott Hughes88d63092013-01-09 09:55:54 -0800989JDWP::JdwpError Dbg::GetObjectTag(JDWP::ObjectId object_id, uint8_t& tag) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800990 mirror::Object* o = gRegistry->Get<mirror::Object*>(object_id);
Elliott Hughes64f574f2013-02-20 14:57:12 -0800991 if (o == ObjectRegistry::kInvalidObject) {
Elliott Hughes546b9862012-06-20 16:06:13 -0700992 return JDWP::ERR_INVALID_OBJECT;
993 }
994 tag = TagFromObject(o);
995 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700996}
997
Elliott Hughesaed4be92011-12-02 16:16:23 -0800998size_t Dbg::GetTagWidth(JDWP::JdwpTag tag) {
Elliott Hughesdbb40792011-11-18 17:05:22 -0800999 switch (tag) {
1000 case JDWP::JT_VOID:
1001 return 0;
1002 case JDWP::JT_BYTE:
1003 case JDWP::JT_BOOLEAN:
1004 return 1;
1005 case JDWP::JT_CHAR:
1006 case JDWP::JT_SHORT:
1007 return 2;
1008 case JDWP::JT_FLOAT:
1009 case JDWP::JT_INT:
1010 return 4;
1011 case JDWP::JT_ARRAY:
1012 case JDWP::JT_OBJECT:
1013 case JDWP::JT_STRING:
1014 case JDWP::JT_THREAD:
1015 case JDWP::JT_THREAD_GROUP:
1016 case JDWP::JT_CLASS_LOADER:
1017 case JDWP::JT_CLASS_OBJECT:
1018 return sizeof(JDWP::ObjectId);
1019 case JDWP::JT_DOUBLE:
1020 case JDWP::JT_LONG:
1021 return 8;
1022 default:
Elliott Hughes3d30d9b2011-12-07 17:35:48 -08001023 LOG(FATAL) << "Unknown tag " << tag;
Elliott Hughesdbb40792011-11-18 17:05:22 -08001024 return -1;
1025 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001026}
1027
Elliott Hughes88d63092013-01-09 09:55:54 -08001028JDWP::JdwpError Dbg::GetArrayLength(JDWP::ObjectId array_id, int& length) {
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -08001029 JDWP::JdwpError status;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001030 mirror::Array* a = DecodeArray(array_id, status);
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -08001031 if (a == NULL) {
1032 return status;
Elliott Hughes24437992011-11-30 14:49:33 -08001033 }
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -08001034 length = a->GetLength();
1035 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001036}
1037
Elliott Hughes88d63092013-01-09 09:55:54 -08001038JDWP::JdwpError Dbg::OutputArray(JDWP::ObjectId array_id, int offset, int count, JDWP::ExpandBuf* pReply) {
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -08001039 JDWP::JdwpError status;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001040 mirror::Array* a = DecodeArray(array_id, status);
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -08001041 if (a == NULL) {
1042 return status;
1043 }
Elliott Hughes24437992011-11-30 14:49:33 -08001044
1045 if (offset < 0 || count < 0 || offset > a->GetLength() || a->GetLength() - offset < count) {
1046 LOG(WARNING) << __FUNCTION__ << " access out of bounds: offset=" << offset << "; count=" << count;
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -08001047 return JDWP::ERR_INVALID_LENGTH;
Elliott Hughes24437992011-11-30 14:49:33 -08001048 }
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001049 std::string descriptor(ClassHelper(a->GetClass()).GetDescriptor());
Elliott Hughes24437992011-11-30 14:49:33 -08001050 JDWP::JdwpTag tag = BasicTagFromDescriptor(descriptor.c_str() + 1);
1051
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -08001052 expandBufAdd1(pReply, tag);
1053 expandBufAdd4BE(pReply, count);
1054
Elliott Hughes24437992011-11-30 14:49:33 -08001055 if (IsPrimitiveTag(tag)) {
1056 size_t width = GetTagWidth(tag);
Elliott Hughes24437992011-11-30 14:49:33 -08001057 uint8_t* dst = expandBufAddSpace(pReply, count * width);
1058 if (width == 8) {
Ian Rogersef7d42f2014-01-06 12:55:46 -08001059 const uint64_t* src8 = reinterpret_cast<uint64_t*>(a->GetRawData(sizeof(uint64_t), 0));
Elliott Hughes24437992011-11-30 14:49:33 -08001060 for (int i = 0; i < count; ++i) JDWP::Write8BE(&dst, src8[offset + i]);
1061 } else if (width == 4) {
Ian Rogersef7d42f2014-01-06 12:55:46 -08001062 const uint32_t* src4 = reinterpret_cast<uint32_t*>(a->GetRawData(sizeof(uint32_t), 0));
Elliott Hughes24437992011-11-30 14:49:33 -08001063 for (int i = 0; i < count; ++i) JDWP::Write4BE(&dst, src4[offset + i]);
1064 } else if (width == 2) {
Ian Rogersef7d42f2014-01-06 12:55:46 -08001065 const uint16_t* src2 = reinterpret_cast<uint16_t*>(a->GetRawData(sizeof(uint16_t), 0));
Elliott Hughes24437992011-11-30 14:49:33 -08001066 for (int i = 0; i < count; ++i) JDWP::Write2BE(&dst, src2[offset + i]);
1067 } else {
Ian Rogersef7d42f2014-01-06 12:55:46 -08001068 const uint8_t* src = reinterpret_cast<uint8_t*>(a->GetRawData(sizeof(uint8_t), 0));
Elliott Hughes24437992011-11-30 14:49:33 -08001069 memcpy(dst, &src[offset * width], count * width);
1070 }
1071 } else {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001072 mirror::ObjectArray<mirror::Object>* oa = a->AsObjectArray<mirror::Object>();
Elliott Hughes24437992011-11-30 14:49:33 -08001073 for (int i = 0; i < count; ++i) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001074 mirror::Object* element = oa->Get(offset + i);
Elliott Hughes24437992011-11-30 14:49:33 -08001075 JDWP::JdwpTag specific_tag = (element != NULL) ? TagFromObject(element) : tag;
1076 expandBufAdd1(pReply, specific_tag);
1077 expandBufAddObjectId(pReply, gRegistry->Add(element));
1078 }
1079 }
1080
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -08001081 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001082}
1083
Ian Rogersef7d42f2014-01-06 12:55:46 -08001084template <typename T>
1085static void CopyArrayData(mirror::Array* a, JDWP::Request& src, int offset, int count)
1086 NO_THREAD_SAFETY_ANALYSIS {
1087 // TODO: fix when annotalysis correctly handles non-member functions.
Elliott Hughes4b9702c2013-02-20 18:13:24 -08001088 DCHECK(a->GetClass()->IsPrimitiveArray());
1089
Ian Rogersef7d42f2014-01-06 12:55:46 -08001090 T* dst = reinterpret_cast<T*>(a->GetRawData(sizeof(T), offset));
Elliott Hughes4b9702c2013-02-20 18:13:24 -08001091 for (int i = 0; i < count; ++i) {
1092 *dst++ = src.ReadValue(sizeof(T));
1093 }
1094}
1095
Elliott Hughes88d63092013-01-09 09:55:54 -08001096JDWP::JdwpError Dbg::SetArrayElements(JDWP::ObjectId array_id, int offset, int count,
Elliott Hughes4b9702c2013-02-20 18:13:24 -08001097 JDWP::Request& request)
Ian Rogersb726dcb2012-09-05 08:57:23 -07001098 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -08001099 JDWP::JdwpError status;
Elliott Hughes4b9702c2013-02-20 18:13:24 -08001100 mirror::Array* dst = DecodeArray(array_id, status);
1101 if (dst == NULL) {
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -08001102 return status;
1103 }
Elliott Hughesf03b8f62011-12-02 14:26:25 -08001104
Elliott Hughes4b9702c2013-02-20 18:13:24 -08001105 if (offset < 0 || count < 0 || offset > dst->GetLength() || dst->GetLength() - offset < count) {
Elliott Hughesf03b8f62011-12-02 14:26:25 -08001106 LOG(WARNING) << __FUNCTION__ << " access out of bounds: offset=" << offset << "; count=" << count;
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -08001107 return JDWP::ERR_INVALID_LENGTH;
Elliott Hughesf03b8f62011-12-02 14:26:25 -08001108 }
Ian Rogersfc0e94b2013-09-23 23:51:32 -07001109 const char* descriptor = ClassHelper(dst->GetClass()).GetDescriptor();
1110 JDWP::JdwpTag tag = BasicTagFromDescriptor(descriptor + 1);
Elliott Hughesf03b8f62011-12-02 14:26:25 -08001111
1112 if (IsPrimitiveTag(tag)) {
1113 size_t width = GetTagWidth(tag);
Elliott Hughesf03b8f62011-12-02 14:26:25 -08001114 if (width == 8) {
Elliott Hughes4b9702c2013-02-20 18:13:24 -08001115 CopyArrayData<uint64_t>(dst, request, offset, count);
Elliott Hughesf03b8f62011-12-02 14:26:25 -08001116 } else if (width == 4) {
Elliott Hughes4b9702c2013-02-20 18:13:24 -08001117 CopyArrayData<uint32_t>(dst, request, offset, count);
Elliott Hughesf03b8f62011-12-02 14:26:25 -08001118 } else if (width == 2) {
Elliott Hughes4b9702c2013-02-20 18:13:24 -08001119 CopyArrayData<uint16_t>(dst, request, offset, count);
Elliott Hughesf03b8f62011-12-02 14:26:25 -08001120 } else {
Elliott Hughes4b9702c2013-02-20 18:13:24 -08001121 CopyArrayData<uint8_t>(dst, request, offset, count);
Elliott Hughesf03b8f62011-12-02 14:26:25 -08001122 }
1123 } else {
Elliott Hughes4b9702c2013-02-20 18:13:24 -08001124 mirror::ObjectArray<mirror::Object>* oa = dst->AsObjectArray<mirror::Object>();
Elliott Hughesf03b8f62011-12-02 14:26:25 -08001125 for (int i = 0; i < count; ++i) {
Elliott Hughes4b9702c2013-02-20 18:13:24 -08001126 JDWP::ObjectId id = request.ReadObjectId();
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001127 mirror::Object* o = gRegistry->Get<mirror::Object*>(id);
Elliott Hughes64f574f2013-02-20 14:57:12 -08001128 if (o == ObjectRegistry::kInvalidObject) {
Elliott Hughes436e3722012-02-17 20:01:47 -08001129 return JDWP::ERR_INVALID_OBJECT;
1130 }
1131 oa->Set(offset + i, o);
Elliott Hughesf03b8f62011-12-02 14:26:25 -08001132 }
1133 }
1134
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -08001135 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001136}
1137
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -08001138JDWP::ObjectId Dbg::CreateString(const std::string& str) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001139 return gRegistry->Add(mirror::String::AllocFromModifiedUtf8(Thread::Current(), str.c_str()));
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001140}
1141
Elliott Hughes88d63092013-01-09 09:55:54 -08001142JDWP::JdwpError Dbg::CreateObject(JDWP::RefTypeId class_id, JDWP::ObjectId& new_object) {
Elliott Hughes436e3722012-02-17 20:01:47 -08001143 JDWP::JdwpError status;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001144 mirror::Class* c = DecodeClass(class_id, status);
Elliott Hughes436e3722012-02-17 20:01:47 -08001145 if (c == NULL) {
1146 return status;
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -08001147 }
Ian Rogers50b35e22012-10-04 10:09:15 -07001148 new_object = gRegistry->Add(c->AllocObject(Thread::Current()));
Elliott Hughes436e3722012-02-17 20:01:47 -08001149 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001150}
1151
Elliott Hughesbf13d362011-12-08 15:51:37 -08001152/*
1153 * Used by Eclipse's "Display" view to evaluate "new byte[5]" to get "(byte[]) [0, 0, 0, 0, 0]".
1154 */
Elliott Hughes88d63092013-01-09 09:55:54 -08001155JDWP::JdwpError Dbg::CreateArrayObject(JDWP::RefTypeId array_class_id, uint32_t length,
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001156 JDWP::ObjectId& new_array) {
Elliott Hughes436e3722012-02-17 20:01:47 -08001157 JDWP::JdwpError status;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001158 mirror::Class* c = DecodeClass(array_class_id, status);
Elliott Hughes436e3722012-02-17 20:01:47 -08001159 if (c == NULL) {
1160 return status;
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -08001161 }
Mathieu Chartiercbb2d202013-11-14 17:45:16 -08001162 new_array = gRegistry->Add(mirror::Array::Alloc<true>(Thread::Current(), c, length));
Elliott Hughes436e3722012-02-17 20:01:47 -08001163 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001164}
1165
Elliott Hughes88d63092013-01-09 09:55:54 -08001166bool Dbg::MatchType(JDWP::RefTypeId instance_class_id, JDWP::RefTypeId class_id) {
Elliott Hughes436e3722012-02-17 20:01:47 -08001167 JDWP::JdwpError status;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001168 mirror::Class* c1 = DecodeClass(instance_class_id, status);
Elliott Hughesa656a0f2012-02-21 18:03:44 -08001169 CHECK(c1 != NULL);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001170 mirror::Class* c2 = DecodeClass(class_id, status);
Elliott Hughesa656a0f2012-02-21 18:03:44 -08001171 CHECK(c2 != NULL);
Sebastien Hertz123756a2013-11-27 15:49:42 +01001172 return c2->IsAssignableFrom(c1);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001173}
1174
Brian Carlstromea46f952013-07-30 01:26:50 -07001175static JDWP::FieldId ToFieldId(const mirror::ArtField* f)
Ian Rogersb726dcb2012-09-05 08:57:23 -07001176 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Mathieu Chartier590fee92013-09-13 13:46:47 -07001177 CHECK(!kMovingFields);
Elliott Hughes03181a82011-11-17 17:22:21 -08001178 return static_cast<JDWP::FieldId>(reinterpret_cast<uintptr_t>(f));
Elliott Hughes03181a82011-11-17 17:22:21 -08001179}
1180
Brian Carlstromea46f952013-07-30 01:26:50 -07001181static JDWP::MethodId ToMethodId(const mirror::ArtMethod* m)
Ian Rogersb726dcb2012-09-05 08:57:23 -07001182 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Mathieu Chartier590fee92013-09-13 13:46:47 -07001183 CHECK(!kMovingMethods);
Elliott Hughes03181a82011-11-17 17:22:21 -08001184 return static_cast<JDWP::MethodId>(reinterpret_cast<uintptr_t>(m));
Elliott Hughes03181a82011-11-17 17:22:21 -08001185}
1186
Brian Carlstromea46f952013-07-30 01:26:50 -07001187static mirror::ArtField* FromFieldId(JDWP::FieldId fid)
Ian Rogersb726dcb2012-09-05 08:57:23 -07001188 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Mathieu Chartier590fee92013-09-13 13:46:47 -07001189 CHECK(!kMovingFields);
Brian Carlstromea46f952013-07-30 01:26:50 -07001190 return reinterpret_cast<mirror::ArtField*>(static_cast<uintptr_t>(fid));
Elliott Hughesaed4be92011-12-02 16:16:23 -08001191}
1192
Brian Carlstromea46f952013-07-30 01:26:50 -07001193static mirror::ArtMethod* FromMethodId(JDWP::MethodId mid)
Ian Rogersb726dcb2012-09-05 08:57:23 -07001194 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Mathieu Chartier590fee92013-09-13 13:46:47 -07001195 CHECK(!kMovingMethods);
Brian Carlstromea46f952013-07-30 01:26:50 -07001196 return reinterpret_cast<mirror::ArtMethod*>(static_cast<uintptr_t>(mid));
Elliott Hughes03181a82011-11-17 17:22:21 -08001197}
1198
Brian Carlstromea46f952013-07-30 01:26:50 -07001199static void SetLocation(JDWP::JdwpLocation& location, mirror::ArtMethod* m, uint32_t dex_pc)
Ian Rogersb726dcb2012-09-05 08:57:23 -07001200 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08001201 if (m == NULL) {
1202 memset(&location, 0, sizeof(location));
1203 } else {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001204 mirror::Class* c = m->GetDeclaringClass();
Elliott Hughes74847412012-06-20 18:10:21 -07001205 location.type_tag = c->IsInterface() ? JDWP::TT_INTERFACE : JDWP::TT_CLASS;
1206 location.class_id = gRegistry->Add(c);
1207 location.method_id = ToMethodId(m);
Ian Rogers0399dde2012-06-06 17:09:28 -07001208 location.dex_pc = dex_pc;
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08001209 }
Elliott Hughesd07986f2011-12-06 18:27:45 -08001210}
1211
Elliott Hughesa96836a2013-01-17 12:27:49 -08001212std::string Dbg::GetMethodName(JDWP::MethodId method_id)
Ian Rogersb726dcb2012-09-05 08:57:23 -07001213 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Brian Carlstromea46f952013-07-30 01:26:50 -07001214 mirror::ArtMethod* m = FromMethodId(method_id);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001215 return MethodHelper(m).GetName();
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001216}
1217
Elliott Hughesa96836a2013-01-17 12:27:49 -08001218std::string Dbg::GetFieldName(JDWP::FieldId field_id)
1219 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Brian Carlstromea46f952013-07-30 01:26:50 -07001220 mirror::ArtField* f = FromFieldId(field_id);
Elliott Hughesa96836a2013-01-17 12:27:49 -08001221 return FieldHelper(f).GetName();
1222}
1223
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001224/*
1225 * Augment the access flags for synthetic methods and fields by setting
1226 * the (as described by the spec) "0xf0000000 bit". Also, strip out any
1227 * flags not specified by the Java programming language.
1228 */
1229static uint32_t MangleAccessFlags(uint32_t accessFlags) {
1230 accessFlags &= kAccJavaFlagsMask;
1231 if ((accessFlags & kAccSynthetic) != 0) {
1232 accessFlags |= 0xf0000000;
1233 }
1234 return accessFlags;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001235}
1236
Elliott Hughesdbb40792011-11-18 17:05:22 -08001237/*
Jeff Haob7cefc72013-11-14 14:51:09 -08001238 * Circularly shifts registers so that arguments come first. Debuggers
1239 * expect slots to begin with arguments, but dex code places them at
1240 * the end.
Elliott Hughesdbb40792011-11-18 17:05:22 -08001241 */
Jeff Haob7cefc72013-11-14 14:51:09 -08001242static uint16_t MangleSlot(uint16_t slot, mirror::ArtMethod* m)
1243 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
1244 const DexFile::CodeItem* code_item = MethodHelper(m).GetCodeItem();
1245 uint16_t ins_size = code_item->ins_size_;
1246 uint16_t locals_size = code_item->registers_size_ - ins_size;
1247 if (slot >= locals_size) {
1248 return slot - locals_size;
1249 } else {
1250 return slot + ins_size;
Elliott Hughesdbb40792011-11-18 17:05:22 -08001251 }
Elliott Hughesdbb40792011-11-18 17:05:22 -08001252}
1253
Jeff Haob7cefc72013-11-14 14:51:09 -08001254/*
1255 * Circularly shifts registers so that arguments come last. Reverts
1256 * slots to dex style argument placement.
1257 */
Brian Carlstromea46f952013-07-30 01:26:50 -07001258static uint16_t DemangleSlot(uint16_t slot, mirror::ArtMethod* m)
Ian Rogersb726dcb2012-09-05 08:57:23 -07001259 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Jeff Haob7cefc72013-11-14 14:51:09 -08001260 const DexFile::CodeItem* code_item = MethodHelper(m).GetCodeItem();
1261 uint16_t ins_size = code_item->ins_size_;
1262 uint16_t locals_size = code_item->registers_size_ - ins_size;
1263 if (slot < ins_size) {
1264 return slot + locals_size;
1265 } else {
1266 return slot - ins_size;
Elliott Hughesdbb40792011-11-18 17:05:22 -08001267 }
Elliott Hughesdbb40792011-11-18 17:05:22 -08001268}
1269
Elliott Hughes88d63092013-01-09 09:55:54 -08001270JDWP::JdwpError Dbg::OutputDeclaredFields(JDWP::RefTypeId class_id, bool with_generic, JDWP::ExpandBuf* pReply) {
Elliott Hughes436e3722012-02-17 20:01:47 -08001271 JDWP::JdwpError status;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001272 mirror::Class* c = DecodeClass(class_id, status);
Elliott Hughes436e3722012-02-17 20:01:47 -08001273 if (c == NULL) {
1274 return status;
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -08001275 }
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001276
1277 size_t instance_field_count = c->NumInstanceFields();
1278 size_t static_field_count = c->NumStaticFields();
1279
1280 expandBufAdd4BE(pReply, instance_field_count + static_field_count);
1281
1282 for (size_t i = 0; i < instance_field_count + static_field_count; ++i) {
Brian Carlstromea46f952013-07-30 01:26:50 -07001283 mirror::ArtField* f = (i < instance_field_count) ? c->GetInstanceField(i) : c->GetStaticField(i - instance_field_count);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001284 FieldHelper fh(f);
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001285 expandBufAddFieldId(pReply, ToFieldId(f));
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001286 expandBufAddUtf8String(pReply, fh.GetName());
1287 expandBufAddUtf8String(pReply, fh.GetTypeDescriptor());
Elliott Hughesc5b734a2011-12-01 17:20:58 -08001288 if (with_generic) {
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001289 static const char genericSignature[1] = "";
1290 expandBufAddUtf8String(pReply, genericSignature);
1291 }
1292 expandBufAdd4BE(pReply, MangleAccessFlags(f->GetAccessFlags()));
1293 }
Elliott Hughes436e3722012-02-17 20:01:47 -08001294 return JDWP::ERR_NONE;
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001295}
1296
Elliott Hughes88d63092013-01-09 09:55:54 -08001297JDWP::JdwpError Dbg::OutputDeclaredMethods(JDWP::RefTypeId class_id, bool with_generic,
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001298 JDWP::ExpandBuf* pReply) {
Elliott Hughes436e3722012-02-17 20:01:47 -08001299 JDWP::JdwpError status;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001300 mirror::Class* c = DecodeClass(class_id, status);
Elliott Hughes436e3722012-02-17 20:01:47 -08001301 if (c == NULL) {
1302 return status;
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -08001303 }
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001304
1305 size_t direct_method_count = c->NumDirectMethods();
1306 size_t virtual_method_count = c->NumVirtualMethods();
1307
1308 expandBufAdd4BE(pReply, direct_method_count + virtual_method_count);
1309
1310 for (size_t i = 0; i < direct_method_count + virtual_method_count; ++i) {
Brian Carlstromea46f952013-07-30 01:26:50 -07001311 mirror::ArtMethod* m = (i < direct_method_count) ? c->GetDirectMethod(i) : c->GetVirtualMethod(i - direct_method_count);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001312 MethodHelper mh(m);
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001313 expandBufAddMethodId(pReply, ToMethodId(m));
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001314 expandBufAddUtf8String(pReply, mh.GetName());
Ian Rogersd91d6d62013-09-25 20:26:14 -07001315 expandBufAddUtf8String(pReply, mh.GetSignature().ToString());
Elliott Hughesc5b734a2011-12-01 17:20:58 -08001316 if (with_generic) {
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001317 static const char genericSignature[1] = "";
1318 expandBufAddUtf8String(pReply, genericSignature);
1319 }
1320 expandBufAdd4BE(pReply, MangleAccessFlags(m->GetAccessFlags()));
1321 }
Elliott Hughes436e3722012-02-17 20:01:47 -08001322 return JDWP::ERR_NONE;
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001323}
1324
Elliott Hughes88d63092013-01-09 09:55:54 -08001325JDWP::JdwpError Dbg::OutputDeclaredInterfaces(JDWP::RefTypeId class_id, JDWP::ExpandBuf* pReply) {
Elliott Hughes436e3722012-02-17 20:01:47 -08001326 JDWP::JdwpError status;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001327 mirror::Class* c = DecodeClass(class_id, status);
Elliott Hughes436e3722012-02-17 20:01:47 -08001328 if (c == NULL) {
1329 return status;
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -08001330 }
Elliott Hughes436e3722012-02-17 20:01:47 -08001331
1332 ClassHelper kh(c);
Ian Rogersd24e2642012-06-06 21:21:43 -07001333 size_t interface_count = kh.NumDirectInterfaces();
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001334 expandBufAdd4BE(pReply, interface_count);
1335 for (size_t i = 0; i < interface_count; ++i) {
Elliott Hughes64f574f2013-02-20 14:57:12 -08001336 expandBufAddRefTypeId(pReply, gRegistry->AddRefType(kh.GetDirectInterface(i)));
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001337 }
Elliott Hughes436e3722012-02-17 20:01:47 -08001338 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001339}
1340
Elliott Hughes88d63092013-01-09 09:55:54 -08001341void Dbg::OutputLineTable(JDWP::RefTypeId, JDWP::MethodId method_id, JDWP::ExpandBuf* pReply)
Ian Rogersb726dcb2012-09-05 08:57:23 -07001342 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Elliott Hughes03181a82011-11-17 17:22:21 -08001343 struct DebugCallbackContext {
1344 int numItems;
1345 JDWP::ExpandBuf* pReply;
1346
Elliott Hughes2435a572012-02-17 16:07:41 -08001347 static bool Callback(void* context, uint32_t address, uint32_t line_number) {
Elliott Hughes03181a82011-11-17 17:22:21 -08001348 DebugCallbackContext* pContext = reinterpret_cast<DebugCallbackContext*>(context);
1349 expandBufAdd8BE(pContext->pReply, address);
Elliott Hughes2435a572012-02-17 16:07:41 -08001350 expandBufAdd4BE(pContext->pReply, line_number);
Elliott Hughes03181a82011-11-17 17:22:21 -08001351 pContext->numItems++;
Sebastien Hertzf2910ee2013-10-19 16:39:24 +02001352 return false;
Elliott Hughes03181a82011-11-17 17:22:21 -08001353 }
1354 };
Brian Carlstromea46f952013-07-30 01:26:50 -07001355 mirror::ArtMethod* m = FromMethodId(method_id);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001356 MethodHelper mh(m);
Elliott Hughes03181a82011-11-17 17:22:21 -08001357 uint64_t start, end;
1358 if (m->IsNative()) {
1359 start = -1;
1360 end = -1;
1361 } else {
1362 start = 0;
jeffhao14f0db92012-12-14 17:50:42 -08001363 // Return the index of the last instruction
1364 end = mh.GetCodeItem()->insns_size_in_code_units_ - 1;
Elliott Hughes03181a82011-11-17 17:22:21 -08001365 }
1366
1367 expandBufAdd8BE(pReply, start);
1368 expandBufAdd8BE(pReply, end);
1369
1370 // Add numLines later
1371 size_t numLinesOffset = expandBufGetLength(pReply);
1372 expandBufAdd4BE(pReply, 0);
1373
1374 DebugCallbackContext context;
1375 context.numItems = 0;
1376 context.pReply = pReply;
1377
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001378 mh.GetDexFile().DecodeDebugInfo(mh.GetCodeItem(), m->IsStatic(), m->GetDexMethodIndex(),
1379 DebugCallbackContext::Callback, NULL, &context);
Elliott Hughes03181a82011-11-17 17:22:21 -08001380
1381 JDWP::Set4BE(expandBufGetBuffer(pReply) + numLinesOffset, context.numItems);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001382}
1383
Elliott Hughes88d63092013-01-09 09:55:54 -08001384void Dbg::OutputVariableTable(JDWP::RefTypeId, JDWP::MethodId method_id, bool with_generic, JDWP::ExpandBuf* pReply) {
Elliott Hughesdbb40792011-11-18 17:05:22 -08001385 struct DebugCallbackContext {
Jeff Haob7cefc72013-11-14 14:51:09 -08001386 mirror::ArtMethod* method;
Elliott Hughesdbb40792011-11-18 17:05:22 -08001387 JDWP::ExpandBuf* pReply;
Elliott Hughesc5b734a2011-12-01 17:20:58 -08001388 size_t variable_count;
1389 bool with_generic;
Elliott Hughesdbb40792011-11-18 17:05:22 -08001390
Jeff Haob7cefc72013-11-14 14:51:09 -08001391 static void Callback(void* context, uint16_t slot, uint32_t startAddress, uint32_t endAddress, const char* name, const char* descriptor, const char* signature)
1392 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Elliott Hughesdbb40792011-11-18 17:05:22 -08001393 DebugCallbackContext* pContext = reinterpret_cast<DebugCallbackContext*>(context);
1394
Jeff Haob7cefc72013-11-14 14:51:09 -08001395 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 -08001396
Jeff Haob7cefc72013-11-14 14:51:09 -08001397 slot = MangleSlot(slot, pContext->method);
Elliott Hughes68fdbd02011-11-29 19:22:47 -08001398
Elliott Hughesdbb40792011-11-18 17:05:22 -08001399 expandBufAdd8BE(pContext->pReply, startAddress);
1400 expandBufAddUtf8String(pContext->pReply, name);
1401 expandBufAddUtf8String(pContext->pReply, descriptor);
Elliott Hughesc5b734a2011-12-01 17:20:58 -08001402 if (pContext->with_generic) {
Elliott Hughesdbb40792011-11-18 17:05:22 -08001403 expandBufAddUtf8String(pContext->pReply, signature);
1404 }
1405 expandBufAdd4BE(pContext->pReply, endAddress - startAddress);
1406 expandBufAdd4BE(pContext->pReply, slot);
1407
Elliott Hughesc5b734a2011-12-01 17:20:58 -08001408 ++pContext->variable_count;
Elliott Hughesdbb40792011-11-18 17:05:22 -08001409 }
1410 };
Brian Carlstromea46f952013-07-30 01:26:50 -07001411 mirror::ArtMethod* m = FromMethodId(method_id);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001412 MethodHelper mh(m);
1413 const DexFile::CodeItem* code_item = mh.GetCodeItem();
Elliott Hughesdbb40792011-11-18 17:05:22 -08001414
Elliott Hughesc5b734a2011-12-01 17:20:58 -08001415 // arg_count considers doubles and longs to take 2 units.
1416 // variable_count considers everything to take 1 unit.
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001417 std::string shorty(mh.GetShorty());
Brian Carlstromea46f952013-07-30 01:26:50 -07001418 expandBufAdd4BE(pReply, mirror::ArtMethod::NumArgRegisters(shorty));
Elliott Hughesdbb40792011-11-18 17:05:22 -08001419
Elliott Hughesc5b734a2011-12-01 17:20:58 -08001420 // We don't know the total number of variables yet, so leave a blank and update it later.
1421 size_t variable_count_offset = expandBufGetLength(pReply);
Elliott Hughesdbb40792011-11-18 17:05:22 -08001422 expandBufAdd4BE(pReply, 0);
1423
1424 DebugCallbackContext context;
Jeff Haob7cefc72013-11-14 14:51:09 -08001425 context.method = m;
Elliott Hughesdbb40792011-11-18 17:05:22 -08001426 context.pReply = pReply;
Elliott Hughesc5b734a2011-12-01 17:20:58 -08001427 context.variable_count = 0;
1428 context.with_generic = with_generic;
Elliott Hughesdbb40792011-11-18 17:05:22 -08001429
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001430 mh.GetDexFile().DecodeDebugInfo(code_item, m->IsStatic(), m->GetDexMethodIndex(), NULL,
1431 DebugCallbackContext::Callback, &context);
Elliott Hughesdbb40792011-11-18 17:05:22 -08001432
Elliott Hughesc5b734a2011-12-01 17:20:58 -08001433 JDWP::Set4BE(expandBufGetBuffer(pReply) + variable_count_offset, context.variable_count);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001434}
1435
Jeff Hao579b0242013-11-18 13:16:49 -08001436void Dbg::OutputMethodReturnValue(JDWP::MethodId method_id, const JValue* return_value,
1437 JDWP::ExpandBuf* pReply) {
1438 mirror::ArtMethod* m = FromMethodId(method_id);
1439 JDWP::JdwpTag tag = BasicTagFromDescriptor(MethodHelper(m).GetShorty());
1440 OutputJValue(tag, return_value, pReply);
1441}
1442
Elliott Hughes9777ba22013-01-17 09:04:19 -08001443JDWP::JdwpError Dbg::GetBytecodes(JDWP::RefTypeId, JDWP::MethodId method_id,
1444 std::vector<uint8_t>& bytecodes)
1445 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Brian Carlstromea46f952013-07-30 01:26:50 -07001446 mirror::ArtMethod* m = FromMethodId(method_id);
Elliott Hughes9777ba22013-01-17 09:04:19 -08001447 if (m == NULL) {
1448 return JDWP::ERR_INVALID_METHODID;
1449 }
1450 MethodHelper mh(m);
1451 const DexFile::CodeItem* code_item = mh.GetCodeItem();
1452 size_t byte_count = code_item->insns_size_in_code_units_ * 2;
1453 const uint8_t* begin = reinterpret_cast<const uint8_t*>(code_item->insns_);
1454 const uint8_t* end = begin + byte_count;
1455 for (const uint8_t* p = begin; p != end; ++p) {
1456 bytecodes.push_back(*p);
1457 }
1458 return JDWP::ERR_NONE;
1459}
1460
Elliott Hughes88d63092013-01-09 09:55:54 -08001461JDWP::JdwpTag Dbg::GetFieldBasicTag(JDWP::FieldId field_id) {
1462 return BasicTagFromDescriptor(FieldHelper(FromFieldId(field_id)).GetTypeDescriptor());
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001463}
1464
Elliott Hughes88d63092013-01-09 09:55:54 -08001465JDWP::JdwpTag Dbg::GetStaticFieldBasicTag(JDWP::FieldId field_id) {
1466 return BasicTagFromDescriptor(FieldHelper(FromFieldId(field_id)).GetTypeDescriptor());
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001467}
1468
Elliott Hughes88d63092013-01-09 09:55:54 -08001469static JDWP::JdwpError GetFieldValueImpl(JDWP::RefTypeId ref_type_id, JDWP::ObjectId object_id,
1470 JDWP::FieldId field_id, JDWP::ExpandBuf* pReply,
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001471 bool is_static)
Ian Rogersb726dcb2012-09-05 08:57:23 -07001472 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Elliott Hughes0cf74332012-02-23 23:14:00 -08001473 JDWP::JdwpError status;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001474 mirror::Class* c = DecodeClass(ref_type_id, status);
Elliott Hughes88d63092013-01-09 09:55:54 -08001475 if (ref_type_id != 0 && c == NULL) {
Elliott Hughes0cf74332012-02-23 23:14:00 -08001476 return status;
1477 }
1478
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001479 mirror::Object* o = gRegistry->Get<mirror::Object*>(object_id);
Elliott Hughes64f574f2013-02-20 14:57:12 -08001480 if ((!is_static && o == NULL) || o == ObjectRegistry::kInvalidObject) {
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08001481 return JDWP::ERR_INVALID_OBJECT;
1482 }
Brian Carlstromea46f952013-07-30 01:26:50 -07001483 mirror::ArtField* f = FromFieldId(field_id);
Elliott Hughes0cf74332012-02-23 23:14:00 -08001484
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001485 mirror::Class* receiver_class = c;
Elliott Hughes0cf74332012-02-23 23:14:00 -08001486 if (receiver_class == NULL && o != NULL) {
1487 receiver_class = o->GetClass();
1488 }
1489 // TODO: should we give up now if receiver_class is NULL?
1490 if (receiver_class != NULL && !f->GetDeclaringClass()->IsAssignableFrom(receiver_class)) {
1491 LOG(INFO) << "ERR_INVALID_FIELDID: " << PrettyField(f) << " " << PrettyClass(receiver_class);
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08001492 return JDWP::ERR_INVALID_FIELDID;
1493 }
Elliott Hughesaed4be92011-12-02 16:16:23 -08001494
Elliott Hughes0cf74332012-02-23 23:14:00 -08001495 // The RI only enforces the static/non-static mismatch in one direction.
1496 // TODO: should we change the tests and check both?
1497 if (is_static) {
1498 if (!f->IsStatic()) {
1499 return JDWP::ERR_INVALID_FIELDID;
1500 }
1501 } else {
1502 if (f->IsStatic()) {
1503 LOG(WARNING) << "Ignoring non-NULL receiver for ObjectReference.SetValues on static field " << PrettyField(f);
Elliott Hughes0cf74332012-02-23 23:14:00 -08001504 }
1505 }
jeffhao0dfbb7e2012-11-28 15:26:03 -08001506 if (f->IsStatic()) {
1507 o = f->GetDeclaringClass();
1508 }
Elliott Hughes0cf74332012-02-23 23:14:00 -08001509
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001510 JDWP::JdwpTag tag = BasicTagFromDescriptor(FieldHelper(f).GetTypeDescriptor());
Jeff Hao579b0242013-11-18 13:16:49 -08001511 JValue field_value;
1512 if (tag == JDWP::JT_VOID) {
1513 LOG(FATAL) << "Unknown tag: " << tag;
1514 } else if (!IsPrimitiveTag(tag)) {
1515 field_value.SetL(f->GetObject(o));
1516 } else if (tag == JDWP::JT_DOUBLE || tag == JDWP::JT_LONG) {
1517 field_value.SetJ(f->Get64(o));
Elliott Hughesaed4be92011-12-02 16:16:23 -08001518 } else {
Jeff Hao579b0242013-11-18 13:16:49 -08001519 field_value.SetI(f->Get32(o));
Elliott Hughesaed4be92011-12-02 16:16:23 -08001520 }
Jeff Hao579b0242013-11-18 13:16:49 -08001521 Dbg::OutputJValue(tag, &field_value, pReply);
1522
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08001523 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001524}
1525
Elliott Hughes88d63092013-01-09 09:55:54 -08001526JDWP::JdwpError Dbg::GetFieldValue(JDWP::ObjectId object_id, JDWP::FieldId field_id,
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001527 JDWP::ExpandBuf* pReply) {
Elliott Hughes88d63092013-01-09 09:55:54 -08001528 return GetFieldValueImpl(0, object_id, field_id, pReply, false);
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08001529}
1530
Elliott Hughes88d63092013-01-09 09:55:54 -08001531JDWP::JdwpError Dbg::GetStaticFieldValue(JDWP::RefTypeId ref_type_id, JDWP::FieldId field_id, JDWP::ExpandBuf* pReply) {
1532 return GetFieldValueImpl(ref_type_id, 0, field_id, pReply, true);
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08001533}
1534
Elliott Hughes88d63092013-01-09 09:55:54 -08001535static JDWP::JdwpError SetFieldValueImpl(JDWP::ObjectId object_id, JDWP::FieldId field_id,
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001536 uint64_t value, int width, bool is_static)
Ian Rogersb726dcb2012-09-05 08:57:23 -07001537 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001538 mirror::Object* o = gRegistry->Get<mirror::Object*>(object_id);
Elliott Hughes64f574f2013-02-20 14:57:12 -08001539 if ((!is_static && o == NULL) || o == ObjectRegistry::kInvalidObject) {
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08001540 return JDWP::ERR_INVALID_OBJECT;
1541 }
Brian Carlstromea46f952013-07-30 01:26:50 -07001542 mirror::ArtField* f = FromFieldId(field_id);
Elliott Hughes0cf74332012-02-23 23:14:00 -08001543
1544 // The RI only enforces the static/non-static mismatch in one direction.
1545 // TODO: should we change the tests and check both?
1546 if (is_static) {
1547 if (!f->IsStatic()) {
1548 return JDWP::ERR_INVALID_FIELDID;
1549 }
1550 } else {
1551 if (f->IsStatic()) {
1552 LOG(WARNING) << "Ignoring non-NULL receiver for ObjectReference.SetValues on static field " << PrettyField(f);
Elliott Hughes0cf74332012-02-23 23:14:00 -08001553 }
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08001554 }
jeffhao0dfbb7e2012-11-28 15:26:03 -08001555 if (f->IsStatic()) {
1556 o = f->GetDeclaringClass();
1557 }
Elliott Hughesaed4be92011-12-02 16:16:23 -08001558
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001559 JDWP::JdwpTag tag = BasicTagFromDescriptor(FieldHelper(f).GetTypeDescriptor());
Elliott Hughesaed4be92011-12-02 16:16:23 -08001560
1561 if (IsPrimitiveTag(tag)) {
1562 if (tag == JDWP::JT_DOUBLE || tag == JDWP::JT_LONG) {
Elliott Hughes1bac54f2012-03-16 12:48:31 -07001563 CHECK_EQ(width, 8);
Elliott Hughesaed4be92011-12-02 16:16:23 -08001564 f->Set64(o, value);
1565 } else {
Elliott Hughes1bac54f2012-03-16 12:48:31 -07001566 CHECK_LE(width, 4);
Elliott Hughesaed4be92011-12-02 16:16:23 -08001567 f->Set32(o, value);
1568 }
1569 } else {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001570 mirror::Object* v = gRegistry->Get<mirror::Object*>(value);
Elliott Hughes64f574f2013-02-20 14:57:12 -08001571 if (v == ObjectRegistry::kInvalidObject) {
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -08001572 return JDWP::ERR_INVALID_OBJECT;
1573 }
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08001574 if (v != NULL) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001575 mirror::Class* field_type = FieldHelper(f).GetType();
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08001576 if (!field_type->IsAssignableFrom(v->GetClass())) {
1577 return JDWP::ERR_INVALID_OBJECT;
1578 }
1579 }
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -08001580 f->SetObject(o, v);
Elliott Hughesaed4be92011-12-02 16:16:23 -08001581 }
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -08001582
1583 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001584}
1585
Elliott Hughes88d63092013-01-09 09:55:54 -08001586JDWP::JdwpError Dbg::SetFieldValue(JDWP::ObjectId object_id, JDWP::FieldId field_id, uint64_t value,
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001587 int width) {
Elliott Hughes88d63092013-01-09 09:55:54 -08001588 return SetFieldValueImpl(object_id, field_id, value, width, false);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001589}
1590
Elliott Hughes88d63092013-01-09 09:55:54 -08001591JDWP::JdwpError Dbg::SetStaticFieldValue(JDWP::FieldId field_id, uint64_t value, int width) {
1592 return SetFieldValueImpl(0, field_id, value, width, true);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001593}
1594
Elliott Hughes88d63092013-01-09 09:55:54 -08001595std::string Dbg::StringToUtf8(JDWP::ObjectId string_id) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001596 mirror::String* s = gRegistry->Get<mirror::String*>(string_id);
Elliott Hughes68fdbd02011-11-29 19:22:47 -08001597 return s->ToModifiedUtf8();
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001598}
1599
Jeff Hao579b0242013-11-18 13:16:49 -08001600void Dbg::OutputJValue(JDWP::JdwpTag tag, const JValue* return_value, JDWP::ExpandBuf* pReply) {
1601 if (IsPrimitiveTag(tag)) {
1602 expandBufAdd1(pReply, tag);
1603 if (tag == JDWP::JT_BOOLEAN || tag == JDWP::JT_BYTE) {
1604 expandBufAdd1(pReply, return_value->GetI());
1605 } else if (tag == JDWP::JT_CHAR || tag == JDWP::JT_SHORT) {
1606 expandBufAdd2BE(pReply, return_value->GetI());
1607 } else if (tag == JDWP::JT_FLOAT || tag == JDWP::JT_INT) {
1608 expandBufAdd4BE(pReply, return_value->GetI());
1609 } else if (tag == JDWP::JT_DOUBLE || tag == JDWP::JT_LONG) {
1610 expandBufAdd8BE(pReply, return_value->GetJ());
1611 } else {
1612 CHECK_EQ(tag, JDWP::JT_VOID);
1613 }
1614 } else {
1615 mirror::Object* value = return_value->GetL();
1616 expandBufAdd1(pReply, TagFromObject(value));
1617 expandBufAddObjectId(pReply, gRegistry->Add(value));
1618 }
1619}
1620
Elliott Hughes221229c2013-01-08 18:17:50 -08001621JDWP::JdwpError Dbg::GetThreadName(JDWP::ObjectId thread_id, std::string& name) {
jeffhaoa77f0f62012-12-05 17:19:31 -08001622 ScopedObjectAccessUnchecked soa(Thread::Current());
1623 MutexLock mu(soa.Self(), *Locks::thread_list_lock_);
Elliott Hughes221229c2013-01-08 18:17:50 -08001624 Thread* thread;
1625 JDWP::JdwpError error = DecodeThread(soa, thread_id, thread);
1626 if (error != JDWP::ERR_NONE && error != JDWP::ERR_THREAD_NOT_ALIVE) {
1627 return error;
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001628 }
Elliott Hughes221229c2013-01-08 18:17:50 -08001629
1630 // We still need to report the zombie threads' names, so we can't just call Thread::GetThreadName.
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001631 mirror::Object* thread_object = gRegistry->Get<mirror::Object*>(thread_id);
Brian Carlstromea46f952013-07-30 01:26:50 -07001632 mirror::ArtField* java_lang_Thread_name_field =
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001633 soa.DecodeField(WellKnownClasses::java_lang_Thread_name);
1634 mirror::String* s =
1635 reinterpret_cast<mirror::String*>(java_lang_Thread_name_field->GetObject(thread_object));
Elliott Hughes221229c2013-01-08 18:17:50 -08001636 if (s != NULL) {
1637 name = s->ToModifiedUtf8();
1638 }
1639 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001640}
1641
Elliott Hughes221229c2013-01-08 18:17:50 -08001642JDWP::JdwpError Dbg::GetThreadGroup(JDWP::ObjectId thread_id, JDWP::ExpandBuf* pReply) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001643 ScopedObjectAccess soa(Thread::Current());
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001644 mirror::Object* thread_object = gRegistry->Get<mirror::Object*>(thread_id);
Elliott Hughes64f574f2013-02-20 14:57:12 -08001645 if (thread_object == ObjectRegistry::kInvalidObject) {
Elliott Hughes2435a572012-02-17 16:07:41 -08001646 return JDWP::ERR_INVALID_OBJECT;
1647 }
1648
1649 // Okay, so it's an object, but is it actually a thread?
Ian Rogers50b35e22012-10-04 10:09:15 -07001650 MutexLock mu(soa.Self(), *Locks::thread_list_lock_);
Elliott Hughes221229c2013-01-08 18:17:50 -08001651 Thread* thread;
1652 JDWP::JdwpError error = DecodeThread(soa, thread_id, thread);
1653 if (error == JDWP::ERR_THREAD_NOT_ALIVE) {
1654 // Zombie threads are in the null group.
1655 expandBufAddObjectId(pReply, JDWP::ObjectId(0));
1656 return JDWP::ERR_NONE;
1657 }
1658 if (error != JDWP::ERR_NONE) {
1659 return error;
Elliott Hughes2435a572012-02-17 16:07:41 -08001660 }
Elliott Hughes499c5132011-11-17 14:55:11 -08001661
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001662 mirror::Class* c = Runtime::Current()->GetClassLinker()->FindSystemClass("Ljava/lang/Thread;");
Elliott Hughes499c5132011-11-17 14:55:11 -08001663 CHECK(c != NULL);
Brian Carlstromea46f952013-07-30 01:26:50 -07001664 mirror::ArtField* f = c->FindInstanceField("group", "Ljava/lang/ThreadGroup;");
Elliott Hughes499c5132011-11-17 14:55:11 -08001665 CHECK(f != NULL);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001666 mirror::Object* group = f->GetObject(thread_object);
Elliott Hughes499c5132011-11-17 14:55:11 -08001667 CHECK(group != NULL);
Elliott Hughes2435a572012-02-17 16:07:41 -08001668 JDWP::ObjectId thread_group_id = gRegistry->Add(group);
1669
1670 expandBufAddObjectId(pReply, thread_group_id);
1671 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001672}
1673
Elliott Hughes88d63092013-01-09 09:55:54 -08001674std::string Dbg::GetThreadGroupName(JDWP::ObjectId thread_group_id) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001675 ScopedObjectAccess soa(Thread::Current());
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001676 mirror::Object* thread_group = gRegistry->Get<mirror::Object*>(thread_group_id);
Elliott Hughes499c5132011-11-17 14:55:11 -08001677 CHECK(thread_group != NULL);
1678
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001679 mirror::Class* c = Runtime::Current()->GetClassLinker()->FindSystemClass("Ljava/lang/ThreadGroup;");
Elliott Hughes499c5132011-11-17 14:55:11 -08001680 CHECK(c != NULL);
Brian Carlstromea46f952013-07-30 01:26:50 -07001681 mirror::ArtField* f = c->FindInstanceField("name", "Ljava/lang/String;");
Elliott Hughes499c5132011-11-17 14:55:11 -08001682 CHECK(f != NULL);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001683 mirror::String* s = reinterpret_cast<mirror::String*>(f->GetObject(thread_group));
Elliott Hughes499c5132011-11-17 14:55:11 -08001684 return s->ToModifiedUtf8();
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001685}
1686
Elliott Hughes88d63092013-01-09 09:55:54 -08001687JDWP::ObjectId Dbg::GetThreadGroupParent(JDWP::ObjectId thread_group_id) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001688 mirror::Object* thread_group = gRegistry->Get<mirror::Object*>(thread_group_id);
Elliott Hughes4e235312011-12-02 11:34:15 -08001689 CHECK(thread_group != NULL);
1690
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001691 mirror::Class* c = Runtime::Current()->GetClassLinker()->FindSystemClass("Ljava/lang/ThreadGroup;");
Elliott Hughes4e235312011-12-02 11:34:15 -08001692 CHECK(c != NULL);
Brian Carlstromea46f952013-07-30 01:26:50 -07001693 mirror::ArtField* f = c->FindInstanceField("parent", "Ljava/lang/ThreadGroup;");
Elliott Hughes4e235312011-12-02 11:34:15 -08001694 CHECK(f != NULL);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001695 mirror::Object* parent = f->GetObject(thread_group);
Elliott Hughes4e235312011-12-02 11:34:15 -08001696 return gRegistry->Add(parent);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001697}
1698
1699JDWP::ObjectId Dbg::GetSystemThreadGroupId() {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001700 ScopedObjectAccessUnchecked soa(Thread::Current());
Brian Carlstromea46f952013-07-30 01:26:50 -07001701 mirror::ArtField* f = soa.DecodeField(WellKnownClasses::java_lang_ThreadGroup_systemThreadGroup);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001702 mirror::Object* group = f->GetObject(f->GetDeclaringClass());
Ian Rogers365c1022012-06-22 15:05:28 -07001703 return gRegistry->Add(group);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001704}
1705
1706JDWP::ObjectId Dbg::GetMainThreadGroupId() {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001707 ScopedObjectAccess soa(Thread::Current());
Brian Carlstromea46f952013-07-30 01:26:50 -07001708 mirror::ArtField* f = soa.DecodeField(WellKnownClasses::java_lang_ThreadGroup_mainThreadGroup);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001709 mirror::Object* group = f->GetObject(f->GetDeclaringClass());
Ian Rogers365c1022012-06-22 15:05:28 -07001710 return gRegistry->Add(group);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001711}
1712
Jeff Hao920af3e2013-08-28 15:46:38 -07001713JDWP::JdwpThreadStatus Dbg::ToJdwpThreadStatus(ThreadState state) {
1714 switch (state) {
1715 case kBlocked:
1716 return JDWP::TS_MONITOR;
1717 case kNative:
1718 case kRunnable:
1719 case kSuspended:
1720 return JDWP::TS_RUNNING;
1721 case kSleeping:
1722 return JDWP::TS_SLEEPING;
1723 case kStarting:
1724 case kTerminated:
1725 return JDWP::TS_ZOMBIE;
1726 case kTimedWaiting:
1727 case kWaitingForDebuggerSend:
1728 case kWaitingForDebuggerSuspension:
1729 case kWaitingForDebuggerToAttach:
Sebastien Hertz138dbfc2013-12-04 18:15:25 +01001730 case kWaitingForDeoptimization:
Jeff Hao920af3e2013-08-28 15:46:38 -07001731 case kWaitingForGcToComplete:
1732 case kWaitingForCheckPointsToRun:
1733 case kWaitingForJniOnLoad:
1734 case kWaitingForSignalCatcherOutput:
1735 case kWaitingInMainDebuggerLoop:
1736 case kWaitingInMainSignalCatcherLoop:
1737 case kWaitingPerformingGc:
1738 case kWaiting:
1739 return JDWP::TS_WAIT;
1740 // Don't add a 'default' here so the compiler can spot incompatible enum changes.
1741 }
1742 LOG(FATAL) << "Unknown thread state: " << state;
1743 return JDWP::TS_ZOMBIE;
1744}
1745
Elliott Hughes221229c2013-01-08 18:17:50 -08001746JDWP::JdwpError Dbg::GetThreadStatus(JDWP::ObjectId thread_id, JDWP::JdwpThreadStatus* pThreadStatus, JDWP::JdwpSuspendStatus* pSuspendStatus) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001747 ScopedObjectAccess soa(Thread::Current());
Elliott Hughes499c5132011-11-17 14:55:11 -08001748
Elliott Hughes9e0c1752013-01-09 14:02:58 -08001749 *pSuspendStatus = JDWP::SUSPEND_STATUS_NOT_SUSPENDED;
1750
Ian Rogers50b35e22012-10-04 10:09:15 -07001751 MutexLock mu(soa.Self(), *Locks::thread_list_lock_);
Elliott Hughes221229c2013-01-08 18:17:50 -08001752 Thread* thread;
1753 JDWP::JdwpError error = DecodeThread(soa, thread_id, thread);
1754 if (error != JDWP::ERR_NONE) {
1755 if (error == JDWP::ERR_THREAD_NOT_ALIVE) {
1756 *pThreadStatus = JDWP::TS_ZOMBIE;
Elliott Hughes221229c2013-01-08 18:17:50 -08001757 return JDWP::ERR_NONE;
1758 }
1759 return error;
Elliott Hughes499c5132011-11-17 14:55:11 -08001760 }
1761
Elliott Hughes9e0c1752013-01-09 14:02:58 -08001762 if (IsSuspendedForDebugger(soa, thread)) {
1763 *pSuspendStatus = JDWP::SUSPEND_STATUS_SUSPENDED;
Elliott Hughes499c5132011-11-17 14:55:11 -08001764 }
1765
Jeff Hao920af3e2013-08-28 15:46:38 -07001766 *pThreadStatus = ToJdwpThreadStatus(thread->GetState());
Elliott Hughes221229c2013-01-08 18:17:50 -08001767 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001768}
1769
Elliott Hughes221229c2013-01-08 18:17:50 -08001770JDWP::JdwpError Dbg::GetThreadDebugSuspendCount(JDWP::ObjectId thread_id, JDWP::ExpandBuf* pReply) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001771 ScopedObjectAccess soa(Thread::Current());
Ian Rogers50b35e22012-10-04 10:09:15 -07001772 MutexLock mu(soa.Self(), *Locks::thread_list_lock_);
Elliott Hughes221229c2013-01-08 18:17:50 -08001773 Thread* thread;
1774 JDWP::JdwpError error = DecodeThread(soa, thread_id, thread);
1775 if (error != JDWP::ERR_NONE) {
1776 return error;
Elliott Hughes2435a572012-02-17 16:07:41 -08001777 }
Ian Rogers50b35e22012-10-04 10:09:15 -07001778 MutexLock mu2(soa.Self(), *Locks::thread_suspend_count_lock_);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001779 expandBufAdd4BE(pReply, thread->GetDebugSuspendCount());
Elliott Hughes2435a572012-02-17 16:07:41 -08001780 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001781}
1782
Elliott Hughesf9501702013-01-11 11:22:27 -08001783JDWP::JdwpError Dbg::Interrupt(JDWP::ObjectId thread_id) {
1784 ScopedObjectAccess soa(Thread::Current());
1785 MutexLock mu(soa.Self(), *Locks::thread_list_lock_);
1786 Thread* thread;
1787 JDWP::JdwpError error = DecodeThread(soa, thread_id, thread);
1788 if (error != JDWP::ERR_NONE) {
1789 return error;
1790 }
1791 thread->Interrupt();
1792 return JDWP::ERR_NONE;
1793}
1794
Elliott Hughescaf76542012-06-28 16:08:22 -07001795void Dbg::GetThreads(JDWP::ObjectId thread_group_id, std::vector<JDWP::ObjectId>& thread_ids) {
Ian Rogers365c1022012-06-22 15:05:28 -07001796 class ThreadListVisitor {
1797 public:
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001798 ThreadListVisitor(const ScopedObjectAccessUnchecked& soa, mirror::Object* desired_thread_group,
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001799 std::vector<JDWP::ObjectId>& thread_ids)
Ian Rogersb726dcb2012-09-05 08:57:23 -07001800 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_)
jeffhao0dfbb7e2012-11-28 15:26:03 -08001801 : soa_(soa), desired_thread_group_(desired_thread_group), thread_ids_(thread_ids) {}
Ian Rogers365c1022012-06-22 15:05:28 -07001802
Elliott Hughesa2155262011-11-16 16:26:58 -08001803 static void Visit(Thread* t, void* arg) {
1804 reinterpret_cast<ThreadListVisitor*>(arg)->Visit(t);
1805 }
1806
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001807 // TODO: Enable annotalysis. We know lock is held in constructor, but abstraction confuses
1808 // annotalysis.
1809 void Visit(Thread* t) NO_THREAD_SAFETY_ANALYSIS {
Elliott Hughesa2155262011-11-16 16:26:58 -08001810 if (t == Dbg::GetDebugThread()) {
1811 // Skip the JDWP thread. Some debuggers get bent out of shape when they can't suspend and
1812 // query all threads, so it's easier if we just don't tell them about this thread.
1813 return;
1814 }
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001815 mirror::Object* peer = t->GetPeer();
jeffhao0dfbb7e2012-11-28 15:26:03 -08001816 if (IsInDesiredThreadGroup(peer)) {
Ian Rogers120f1c72012-09-28 17:17:10 -07001817 thread_ids_.push_back(gRegistry->Add(peer));
Elliott Hughesa2155262011-11-16 16:26:58 -08001818 }
1819 }
1820
Ian Rogers365c1022012-06-22 15:05:28 -07001821 private:
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001822 bool IsInDesiredThreadGroup(mirror::Object* peer)
jeffhao0dfbb7e2012-11-28 15:26:03 -08001823 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
jeffhao0dfbb7e2012-11-28 15:26:03 -08001824 // peer might be NULL if the thread is still starting up.
1825 if (peer == NULL) {
1826 // We can't tell the debugger about this thread yet.
1827 // TODO: if we identified threads to the debugger by their Thread*
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001828 // rather than their peer's mirror::Object*, we could fix this.
jeffhao0dfbb7e2012-11-28 15:26:03 -08001829 // Doing so might help us report ZOMBIE threads too.
1830 return false;
1831 }
jeffhaoc1e04902012-12-13 12:41:10 -08001832 // Do we want threads from all thread groups?
1833 if (desired_thread_group_ == NULL) {
1834 return true;
1835 }
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001836 mirror::Object* group = soa_.DecodeField(WellKnownClasses::java_lang_Thread_group)->GetObject(peer);
jeffhao0dfbb7e2012-11-28 15:26:03 -08001837 return (group == desired_thread_group_);
1838 }
1839
Mathieu Chartierdbe6f462012-09-25 16:54:50 -07001840 const ScopedObjectAccessUnchecked& soa_;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001841 mirror::Object* const desired_thread_group_;
Elliott Hughescaf76542012-06-28 16:08:22 -07001842 std::vector<JDWP::ObjectId>& thread_ids_;
Elliott Hughesa2155262011-11-16 16:26:58 -08001843 };
1844
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001845 ScopedObjectAccessUnchecked soa(Thread::Current());
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001846 mirror::Object* thread_group = gRegistry->Get<mirror::Object*>(thread_group_id);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001847 ThreadListVisitor tlv(soa, thread_group, thread_ids);
Ian Rogers50b35e22012-10-04 10:09:15 -07001848 MutexLock mu(soa.Self(), *Locks::thread_list_lock_);
Elliott Hughesf8349362012-06-18 15:00:06 -07001849 Runtime::Current()->GetThreadList()->ForEach(ThreadListVisitor::Visit, &tlv);
Elliott Hughescaf76542012-06-28 16:08:22 -07001850}
Elliott Hughesa2155262011-11-16 16:26:58 -08001851
Elliott Hughescaf76542012-06-28 16:08:22 -07001852void Dbg::GetChildThreadGroups(JDWP::ObjectId thread_group_id, std::vector<JDWP::ObjectId>& child_thread_group_ids) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001853 ScopedObjectAccess soa(Thread::Current());
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001854 mirror::Object* thread_group = gRegistry->Get<mirror::Object*>(thread_group_id);
Elliott Hughescaf76542012-06-28 16:08:22 -07001855
1856 // Get the ArrayList<ThreadGroup> "groups" out of this thread group...
Brian Carlstromea46f952013-07-30 01:26:50 -07001857 mirror::ArtField* groups_field = thread_group->GetClass()->FindInstanceField("groups", "Ljava/util/List;");
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001858 mirror::Object* groups_array_list = groups_field->GetObject(thread_group);
Elliott Hughescaf76542012-06-28 16:08:22 -07001859
1860 // Get the array and size out of the ArrayList<ThreadGroup>...
Brian Carlstromea46f952013-07-30 01:26:50 -07001861 mirror::ArtField* array_field = groups_array_list->GetClass()->FindInstanceField("array", "[Ljava/lang/Object;");
1862 mirror::ArtField* size_field = groups_array_list->GetClass()->FindInstanceField("size", "I");
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001863 mirror::ObjectArray<mirror::Object>* groups_array =
1864 array_field->GetObject(groups_array_list)->AsObjectArray<mirror::Object>();
Elliott Hughescaf76542012-06-28 16:08:22 -07001865 const int32_t size = size_field->GetInt(groups_array_list);
1866
1867 // Copy the first 'size' elements out of the array into the result.
1868 for (int32_t i = 0; i < size; ++i) {
1869 child_thread_group_ids.push_back(gRegistry->Add(groups_array->Get(i)));
Elliott Hughesa2155262011-11-16 16:26:58 -08001870 }
1871}
1872
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001873static int GetStackDepth(Thread* thread)
Ian Rogersb726dcb2012-09-05 08:57:23 -07001874 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Ian Rogers0399dde2012-06-06 17:09:28 -07001875 struct CountStackDepthVisitor : public StackVisitor {
Brian Carlstrom93ba8932013-07-17 21:31:49 -07001876 explicit CountStackDepthVisitor(Thread* thread)
Ian Rogers7a22fa62013-01-23 12:16:16 -08001877 : StackVisitor(thread, NULL), depth(0) {}
Ian Rogers0399dde2012-06-06 17:09:28 -07001878
Elliott Hughes64f574f2013-02-20 14:57:12 -08001879 // TODO: Enable annotalysis. We know lock is held in constructor, but abstraction confuses
1880 // annotalysis.
1881 bool VisitFrame() NO_THREAD_SAFETY_ANALYSIS {
Ian Rogers0399dde2012-06-06 17:09:28 -07001882 if (!GetMethod()->IsRuntimeMethod()) {
Elliott Hughesf8a2df72011-12-01 12:19:54 -08001883 ++depth;
1884 }
Elliott Hughes530fa002012-03-12 11:44:49 -07001885 return true;
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001886 }
1887 size_t depth;
1888 };
Elliott Hughes08fc03a2012-06-26 17:34:00 -07001889
Ian Rogers7a22fa62013-01-23 12:16:16 -08001890 CountStackDepthVisitor visitor(thread);
Ian Rogers0399dde2012-06-06 17:09:28 -07001891 visitor.WalkStack();
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001892 return visitor.depth;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001893}
1894
Elliott Hughes221229c2013-01-08 18:17:50 -08001895JDWP::JdwpError Dbg::GetThreadFrameCount(JDWP::ObjectId thread_id, size_t& result) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001896 ScopedObjectAccess soa(Thread::Current());
jeffhaoa77f0f62012-12-05 17:19:31 -08001897 MutexLock mu(soa.Self(), *Locks::thread_list_lock_);
Elliott Hughes221229c2013-01-08 18:17:50 -08001898 Thread* thread;
1899 JDWP::JdwpError error = DecodeThread(soa, thread_id, thread);
1900 if (error != JDWP::ERR_NONE) {
1901 return error;
1902 }
Elliott Hughesf15f4a02013-01-09 10:09:38 -08001903 if (!IsSuspendedForDebugger(soa, thread)) {
1904 return JDWP::ERR_THREAD_NOT_SUSPENDED;
1905 }
Elliott Hughes221229c2013-01-08 18:17:50 -08001906 result = GetStackDepth(thread);
1907 return JDWP::ERR_NONE;
Elliott Hughes86964332012-02-15 19:37:42 -08001908}
1909
Ian Rogers306057f2012-11-26 12:45:53 -08001910JDWP::JdwpError Dbg::GetThreadFrames(JDWP::ObjectId thread_id, size_t start_frame,
1911 size_t frame_count, JDWP::ExpandBuf* buf) {
Elliott Hughes6e9d22c2012-06-22 15:02:37 -07001912 class GetFrameVisitor : public StackVisitor {
1913 public:
Ian Rogers7a22fa62013-01-23 12:16:16 -08001914 GetFrameVisitor(Thread* thread, size_t start_frame, size_t frame_count, JDWP::ExpandBuf* buf)
Ian Rogersb726dcb2012-09-05 08:57:23 -07001915 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_)
Ian Rogers7a22fa62013-01-23 12:16:16 -08001916 : StackVisitor(thread, NULL), depth_(0),
Elliott Hughes6e9d22c2012-06-22 15:02:37 -07001917 start_frame_(start_frame), frame_count_(frame_count), buf_(buf) {
1918 expandBufAdd4BE(buf_, frame_count_);
Elliott Hughes03181a82011-11-17 17:22:21 -08001919 }
Ian Rogers0399dde2012-06-06 17:09:28 -07001920
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001921 // TODO: Enable annotalysis. We know lock is held in constructor, but abstraction confuses
1922 // annotalysis.
1923 virtual bool VisitFrame() NO_THREAD_SAFETY_ANALYSIS {
Ian Rogers0399dde2012-06-06 17:09:28 -07001924 if (GetMethod()->IsRuntimeMethod()) {
Brian Carlstrom7934ac22013-07-26 10:54:15 -07001925 return true; // The debugger can't do anything useful with a frame that has no Method*.
Elliott Hughes03181a82011-11-17 17:22:21 -08001926 }
Elliott Hughes6e9d22c2012-06-22 15:02:37 -07001927 if (depth_ >= start_frame_ + frame_count_) {
Elliott Hughes530fa002012-03-12 11:44:49 -07001928 return false;
Elliott Hughes03181a82011-11-17 17:22:21 -08001929 }
Elliott Hughes6e9d22c2012-06-22 15:02:37 -07001930 if (depth_ >= start_frame_) {
1931 JDWP::FrameId frame_id(GetFrameId());
1932 JDWP::JdwpLocation location;
1933 SetLocation(location, GetMethod(), GetDexPc());
Ian Rogersef7d42f2014-01-06 12:55:46 -08001934 VLOG(jdwp) << StringPrintf(" Frame %3zd: id=%3" PRIu64 " ", depth_, frame_id) << location;
Elliott Hughes6e9d22c2012-06-22 15:02:37 -07001935 expandBufAdd8BE(buf_, frame_id);
1936 expandBufAddLocation(buf_, location);
1937 }
1938 ++depth_;
Elliott Hughes530fa002012-03-12 11:44:49 -07001939 return true;
Elliott Hughes03181a82011-11-17 17:22:21 -08001940 }
Elliott Hughes6e9d22c2012-06-22 15:02:37 -07001941
1942 private:
1943 size_t depth_;
1944 const size_t start_frame_;
1945 const size_t frame_count_;
1946 JDWP::ExpandBuf* buf_;
Elliott Hughes03181a82011-11-17 17:22:21 -08001947 };
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001948
1949 ScopedObjectAccessUnchecked soa(Thread::Current());
jeffhaoa77f0f62012-12-05 17:19:31 -08001950 MutexLock mu(soa.Self(), *Locks::thread_list_lock_);
Elliott Hughes221229c2013-01-08 18:17:50 -08001951 Thread* thread;
1952 JDWP::JdwpError error = DecodeThread(soa, thread_id, thread);
1953 if (error != JDWP::ERR_NONE) {
1954 return error;
1955 }
Elliott Hughesf15f4a02013-01-09 10:09:38 -08001956 if (!IsSuspendedForDebugger(soa, thread)) {
1957 return JDWP::ERR_THREAD_NOT_SUSPENDED;
1958 }
Ian Rogers7a22fa62013-01-23 12:16:16 -08001959 GetFrameVisitor visitor(thread, start_frame, frame_count, buf);
Ian Rogers0399dde2012-06-06 17:09:28 -07001960 visitor.WalkStack();
Elliott Hughes6e9d22c2012-06-22 15:02:37 -07001961 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001962}
1963
1964JDWP::ObjectId Dbg::GetThreadSelfId() {
Mathieu Chartierdbe6f462012-09-25 16:54:50 -07001965 ScopedObjectAccessUnchecked soa(Thread::Current());
Ian Rogerscfaa4552012-11-26 21:00:08 -08001966 return gRegistry->Add(soa.Self()->GetPeer());
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001967}
1968
Elliott Hughes475fc232011-10-25 15:00:35 -07001969void Dbg::SuspendVM() {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001970 Runtime::Current()->GetThreadList()->SuspendAllForDebugger();
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001971}
1972
1973void Dbg::ResumeVM() {
Elliott Hughesc61a2672012-06-21 14:52:29 -07001974 Runtime::Current()->GetThreadList()->UndoDebuggerSuspensions();
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001975}
1976
Elliott Hughes221229c2013-01-08 18:17:50 -08001977JDWP::JdwpError Dbg::SuspendThread(JDWP::ObjectId thread_id, bool request_suspension) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001978 ScopedLocalRef<jobject> peer(Thread::Current()->GetJniEnv(), NULL);
1979 {
1980 ScopedObjectAccess soa(Thread::Current());
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001981 peer.reset(soa.AddLocalReference<jobject>(gRegistry->Get<mirror::Object*>(thread_id)));
Elliott Hughes4e235312011-12-02 11:34:15 -08001982 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001983 if (peer.get() == NULL) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001984 return JDWP::ERR_THREAD_NOT_ALIVE;
1985 }
1986 // Suspend thread to build stack trace.
Elliott Hughesf327e072013-01-09 16:01:26 -08001987 bool timed_out;
Ian Rogersd9c4fc92013-10-01 19:45:43 -07001988 Thread* thread = ThreadList::SuspendThreadByPeer(peer.get(), request_suspension, true,
1989 &timed_out);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001990 if (thread != NULL) {
1991 return JDWP::ERR_NONE;
Elliott Hughesf327e072013-01-09 16:01:26 -08001992 } else if (timed_out) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001993 return JDWP::ERR_INTERNAL;
1994 } else {
1995 return JDWP::ERR_THREAD_NOT_ALIVE;
1996 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001997}
1998
Elliott Hughes221229c2013-01-08 18:17:50 -08001999void Dbg::ResumeThread(JDWP::ObjectId thread_id) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002000 ScopedObjectAccessUnchecked soa(Thread::Current());
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002001 mirror::Object* peer = gRegistry->Get<mirror::Object*>(thread_id);
jeffhaoa77f0f62012-12-05 17:19:31 -08002002 Thread* thread;
2003 {
2004 MutexLock mu(soa.Self(), *Locks::thread_list_lock_);
2005 thread = Thread::FromManagedThread(soa, peer);
2006 }
Elliott Hughes4e235312011-12-02 11:34:15 -08002007 if (thread == NULL) {
2008 LOG(WARNING) << "No such thread for resume: " << peer;
2009 return;
2010 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002011 bool needs_resume;
2012 {
Ian Rogers50b35e22012-10-04 10:09:15 -07002013 MutexLock mu2(soa.Self(), *Locks::thread_suspend_count_lock_);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002014 needs_resume = thread->GetSuspendCount() > 0;
2015 }
2016 if (needs_resume) {
Elliott Hughes546b9862012-06-20 16:06:13 -07002017 Runtime::Current()->GetThreadList()->Resume(thread, true);
2018 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002019}
2020
2021void Dbg::SuspendSelf() {
Elliott Hughes475fc232011-10-25 15:00:35 -07002022 Runtime::Current()->GetThreadList()->SuspendSelfForDebugger();
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002023}
2024
Ian Rogers0399dde2012-06-06 17:09:28 -07002025struct GetThisVisitor : public StackVisitor {
Ian Rogers7a22fa62013-01-23 12:16:16 -08002026 GetThisVisitor(Thread* thread, Context* context, JDWP::FrameId frame_id)
Ian Rogersb726dcb2012-09-05 08:57:23 -07002027 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_)
Ian Rogers7a22fa62013-01-23 12:16:16 -08002028 : StackVisitor(thread, context), this_object(NULL), frame_id(frame_id) {}
Ian Rogers0399dde2012-06-06 17:09:28 -07002029
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002030 // TODO: Enable annotalysis. We know lock is held in constructor, but abstraction confuses
2031 // annotalysis.
2032 virtual bool VisitFrame() NO_THREAD_SAFETY_ANALYSIS {
Elliott Hughes6e9d22c2012-06-22 15:02:37 -07002033 if (frame_id != GetFrameId()) {
Ian Rogers0399dde2012-06-06 17:09:28 -07002034 return true; // continue
Ian Rogers0399dde2012-06-06 17:09:28 -07002035 } else {
Ian Rogers62d6c772013-02-27 08:32:07 -08002036 this_object = GetThisObject();
2037 return false;
Ian Rogers0399dde2012-06-06 17:09:28 -07002038 }
Elliott Hughes86b00102011-12-05 17:54:26 -08002039 }
Ian Rogers0399dde2012-06-06 17:09:28 -07002040
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002041 mirror::Object* this_object;
Elliott Hughes6e9d22c2012-06-22 15:02:37 -07002042 JDWP::FrameId frame_id;
Ian Rogers0399dde2012-06-06 17:09:28 -07002043};
2044
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002045JDWP::JdwpError Dbg::GetThisObject(JDWP::ObjectId thread_id, JDWP::FrameId frame_id,
2046 JDWP::ObjectId* result) {
2047 ScopedObjectAccessUnchecked soa(Thread::Current());
2048 Thread* thread;
2049 {
Ian Rogers50b35e22012-10-04 10:09:15 -07002050 MutexLock mu(soa.Self(), *Locks::thread_list_lock_);
Elliott Hughes221229c2013-01-08 18:17:50 -08002051 JDWP::JdwpError error = DecodeThread(soa, thread_id, thread);
2052 if (error != JDWP::ERR_NONE) {
2053 return error;
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002054 }
Elliott Hughes9e0c1752013-01-09 14:02:58 -08002055 if (!IsSuspendedForDebugger(soa, thread)) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002056 return JDWP::ERR_THREAD_NOT_SUSPENDED;
2057 }
Elliott Hughes6e9d22c2012-06-22 15:02:37 -07002058 }
Elliott Hughescaf76542012-06-28 16:08:22 -07002059 UniquePtr<Context> context(Context::Create());
Ian Rogers7a22fa62013-01-23 12:16:16 -08002060 GetThisVisitor visitor(thread, context.get(), frame_id);
Ian Rogers0399dde2012-06-06 17:09:28 -07002061 visitor.WalkStack();
Elliott Hughes6e9d22c2012-06-22 15:02:37 -07002062 *result = gRegistry->Add(visitor.this_object);
2063 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002064}
2065
Elliott Hughes88d63092013-01-09 09:55:54 -08002066void Dbg::GetLocalValue(JDWP::ObjectId thread_id, JDWP::FrameId frame_id, int slot, JDWP::JdwpTag tag,
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002067 uint8_t* buf, size_t width) {
Ian Rogers0399dde2012-06-06 17:09:28 -07002068 struct GetLocalVisitor : public StackVisitor {
Ian Rogers7a22fa62013-01-23 12:16:16 -08002069 GetLocalVisitor(Thread* thread, Context* context, JDWP::FrameId frame_id, int slot,
2070 JDWP::JdwpTag tag, uint8_t* buf, size_t width)
Ian Rogersb726dcb2012-09-05 08:57:23 -07002071 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_)
Ian Rogers7a22fa62013-01-23 12:16:16 -08002072 : StackVisitor(thread, context), frame_id_(frame_id), slot_(slot), tag_(tag),
Ian Rogersca190662012-06-26 15:45:57 -07002073 buf_(buf), width_(width) {}
2074
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002075 // TODO: Enable annotalysis. We know lock is held in constructor, but abstraction confuses
2076 // annotalysis.
2077 bool VisitFrame() NO_THREAD_SAFETY_ANALYSIS {
Ian Rogers0399dde2012-06-06 17:09:28 -07002078 if (GetFrameId() != frame_id_) {
2079 return true; // Not our frame, carry on.
Elliott Hughesdbb40792011-11-18 17:05:22 -08002080 }
Ian Rogers0399dde2012-06-06 17:09:28 -07002081 // TODO: check that the tag is compatible with the actual type of the slot!
Brian Carlstromea46f952013-07-30 01:26:50 -07002082 mirror::ArtMethod* m = GetMethod();
Ian Rogers0399dde2012-06-06 17:09:28 -07002083 uint16_t reg = DemangleSlot(slot_, m);
Elliott Hughesdbb40792011-11-18 17:05:22 -08002084
Ian Rogers0399dde2012-06-06 17:09:28 -07002085 switch (tag_) {
2086 case JDWP::JT_BOOLEAN:
2087 {
2088 CHECK_EQ(width_, 1U);
Ian Rogers2bcb4a42012-11-08 10:39:18 -08002089 uint32_t intVal = GetVReg(m, reg, kIntVReg);
Ian Rogers0399dde2012-06-06 17:09:28 -07002090 VLOG(jdwp) << "get boolean local " << reg << " = " << intVal;
2091 JDWP::Set1(buf_+1, intVal != 0);
2092 }
2093 break;
2094 case JDWP::JT_BYTE:
2095 {
2096 CHECK_EQ(width_, 1U);
Ian Rogers2bcb4a42012-11-08 10:39:18 -08002097 uint32_t intVal = GetVReg(m, reg, kIntVReg);
Ian Rogers0399dde2012-06-06 17:09:28 -07002098 VLOG(jdwp) << "get byte local " << reg << " = " << intVal;
2099 JDWP::Set1(buf_+1, intVal);
2100 }
2101 break;
2102 case JDWP::JT_SHORT:
2103 case JDWP::JT_CHAR:
2104 {
2105 CHECK_EQ(width_, 2U);
Ian Rogers2bcb4a42012-11-08 10:39:18 -08002106 uint32_t intVal = GetVReg(m, reg, kIntVReg);
Ian Rogers0399dde2012-06-06 17:09:28 -07002107 VLOG(jdwp) << "get short/char local " << reg << " = " << intVal;
2108 JDWP::Set2BE(buf_+1, intVal);
2109 }
2110 break;
2111 case JDWP::JT_INT:
Ian Rogers2bcb4a42012-11-08 10:39:18 -08002112 {
2113 CHECK_EQ(width_, 4U);
2114 uint32_t intVal = GetVReg(m, reg, kIntVReg);
2115 VLOG(jdwp) << "get int local " << reg << " = " << intVal;
2116 JDWP::Set4BE(buf_+1, intVal);
2117 }
2118 break;
Ian Rogers0399dde2012-06-06 17:09:28 -07002119 case JDWP::JT_FLOAT:
2120 {
2121 CHECK_EQ(width_, 4U);
Ian Rogers2bcb4a42012-11-08 10:39:18 -08002122 uint32_t intVal = GetVReg(m, reg, kFloatVReg);
Ian Rogers0399dde2012-06-06 17:09:28 -07002123 VLOG(jdwp) << "get int/float local " << reg << " = " << intVal;
2124 JDWP::Set4BE(buf_+1, intVal);
2125 }
2126 break;
2127 case JDWP::JT_ARRAY:
2128 {
2129 CHECK_EQ(width_, sizeof(JDWP::ObjectId));
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002130 mirror::Object* o = reinterpret_cast<mirror::Object*>(GetVReg(m, reg, kReferenceVReg));
Ian Rogers0399dde2012-06-06 17:09:28 -07002131 VLOG(jdwp) << "get array local " << reg << " = " << o;
Mathieu Chartier590fee92013-09-13 13:46:47 -07002132 if (!Runtime::Current()->GetHeap()->IsValidObjectAddress(o)) {
Ian Rogers0399dde2012-06-06 17:09:28 -07002133 LOG(FATAL) << "Register " << reg << " expected to hold array: " << o;
2134 }
2135 JDWP::SetObjectId(buf_+1, gRegistry->Add(o));
2136 }
2137 break;
2138 case JDWP::JT_CLASS_LOADER:
2139 case JDWP::JT_CLASS_OBJECT:
2140 case JDWP::JT_OBJECT:
2141 case JDWP::JT_STRING:
2142 case JDWP::JT_THREAD:
2143 case JDWP::JT_THREAD_GROUP:
2144 {
2145 CHECK_EQ(width_, sizeof(JDWP::ObjectId));
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002146 mirror::Object* o = reinterpret_cast<mirror::Object*>(GetVReg(m, reg, kReferenceVReg));
Ian Rogers0399dde2012-06-06 17:09:28 -07002147 VLOG(jdwp) << "get object local " << reg << " = " << o;
Mathieu Chartier590fee92013-09-13 13:46:47 -07002148 if (!Runtime::Current()->GetHeap()->IsValidObjectAddress(o)) {
Ian Rogers0399dde2012-06-06 17:09:28 -07002149 LOG(FATAL) << "Register " << reg << " expected to hold object: " << o;
2150 }
2151 tag_ = TagFromObject(o);
2152 JDWP::SetObjectId(buf_+1, gRegistry->Add(o));
2153 }
2154 break;
2155 case JDWP::JT_DOUBLE:
Ian Rogers2bcb4a42012-11-08 10:39:18 -08002156 {
2157 CHECK_EQ(width_, 8U);
2158 uint32_t lo = GetVReg(m, reg, kDoubleLoVReg);
2159 uint64_t hi = GetVReg(m, reg + 1, kDoubleHiVReg);
2160 uint64_t longVal = (hi << 32) | lo;
2161 VLOG(jdwp) << "get double/long local " << hi << ":" << lo << " = " << longVal;
2162 JDWP::Set8BE(buf_+1, longVal);
2163 }
2164 break;
Ian Rogers0399dde2012-06-06 17:09:28 -07002165 case JDWP::JT_LONG:
2166 {
2167 CHECK_EQ(width_, 8U);
Ian Rogers2bcb4a42012-11-08 10:39:18 -08002168 uint32_t lo = GetVReg(m, reg, kLongLoVReg);
2169 uint64_t hi = GetVReg(m, reg + 1, kLongHiVReg);
Ian Rogers0399dde2012-06-06 17:09:28 -07002170 uint64_t longVal = (hi << 32) | lo;
2171 VLOG(jdwp) << "get double/long local " << hi << ":" << lo << " = " << longVal;
2172 JDWP::Set8BE(buf_+1, longVal);
2173 }
2174 break;
2175 default:
2176 LOG(FATAL) << "Unknown tag " << tag_;
2177 break;
2178 }
2179
2180 // Prepend tag, which may have been updated.
2181 JDWP::Set1(buf_, tag_);
2182 return false;
2183 }
2184
2185 const JDWP::FrameId frame_id_;
2186 const int slot_;
2187 JDWP::JdwpTag tag_;
2188 uint8_t* const buf_;
2189 const size_t width_;
2190 };
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002191
2192 ScopedObjectAccessUnchecked soa(Thread::Current());
jeffhaoa77f0f62012-12-05 17:19:31 -08002193 MutexLock mu(soa.Self(), *Locks::thread_list_lock_);
Elliott Hughes221229c2013-01-08 18:17:50 -08002194 Thread* thread;
2195 JDWP::JdwpError error = DecodeThread(soa, thread_id, thread);
2196 if (error != JDWP::ERR_NONE) {
2197 return;
2198 }
Ian Rogers0399dde2012-06-06 17:09:28 -07002199 UniquePtr<Context> context(Context::Create());
Ian Rogers7a22fa62013-01-23 12:16:16 -08002200 GetLocalVisitor visitor(thread, context.get(), frame_id, slot, tag, buf, width);
Ian Rogers0399dde2012-06-06 17:09:28 -07002201 visitor.WalkStack();
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002202}
2203
Elliott Hughes88d63092013-01-09 09:55:54 -08002204void Dbg::SetLocalValue(JDWP::ObjectId thread_id, JDWP::FrameId frame_id, int slot, JDWP::JdwpTag tag,
Ian Rogers0399dde2012-06-06 17:09:28 -07002205 uint64_t value, size_t width) {
2206 struct SetLocalVisitor : public StackVisitor {
Ian Rogers7a22fa62013-01-23 12:16:16 -08002207 SetLocalVisitor(Thread* thread, Context* context,
Ian Rogers0399dde2012-06-06 17:09:28 -07002208 JDWP::FrameId frame_id, int slot, JDWP::JdwpTag tag, uint64_t value,
Ian Rogersca190662012-06-26 15:45:57 -07002209 size_t width)
Ian Rogersb726dcb2012-09-05 08:57:23 -07002210 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_)
Ian Rogers7a22fa62013-01-23 12:16:16 -08002211 : StackVisitor(thread, context),
Elliott Hughes08fc03a2012-06-26 17:34:00 -07002212 frame_id_(frame_id), slot_(slot), tag_(tag), value_(value), width_(width) {}
Ian Rogersca190662012-06-26 15:45:57 -07002213
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002214 // TODO: Enable annotalysis. We know lock is held in constructor, but abstraction confuses
2215 // annotalysis.
2216 bool VisitFrame() NO_THREAD_SAFETY_ANALYSIS {
Ian Rogers0399dde2012-06-06 17:09:28 -07002217 if (GetFrameId() != frame_id_) {
2218 return true; // Not our frame, carry on.
2219 }
2220 // TODO: check that the tag is compatible with the actual type of the slot!
Brian Carlstromea46f952013-07-30 01:26:50 -07002221 mirror::ArtMethod* m = GetMethod();
Ian Rogers0399dde2012-06-06 17:09:28 -07002222 uint16_t reg = DemangleSlot(slot_, m);
2223
2224 switch (tag_) {
2225 case JDWP::JT_BOOLEAN:
2226 case JDWP::JT_BYTE:
2227 CHECK_EQ(width_, 1U);
Ian Rogers2bcb4a42012-11-08 10:39:18 -08002228 SetVReg(m, reg, static_cast<uint32_t>(value_), kIntVReg);
Ian Rogers0399dde2012-06-06 17:09:28 -07002229 break;
2230 case JDWP::JT_SHORT:
2231 case JDWP::JT_CHAR:
2232 CHECK_EQ(width_, 2U);
Ian Rogers2bcb4a42012-11-08 10:39:18 -08002233 SetVReg(m, reg, static_cast<uint32_t>(value_), kIntVReg);
Ian Rogers0399dde2012-06-06 17:09:28 -07002234 break;
2235 case JDWP::JT_INT:
Ian Rogers2bcb4a42012-11-08 10:39:18 -08002236 CHECK_EQ(width_, 4U);
2237 SetVReg(m, reg, static_cast<uint32_t>(value_), kIntVReg);
2238 break;
Ian Rogers0399dde2012-06-06 17:09:28 -07002239 case JDWP::JT_FLOAT:
2240 CHECK_EQ(width_, 4U);
Ian Rogers2bcb4a42012-11-08 10:39:18 -08002241 SetVReg(m, reg, static_cast<uint32_t>(value_), kFloatVReg);
Ian Rogers0399dde2012-06-06 17:09:28 -07002242 break;
2243 case JDWP::JT_ARRAY:
2244 case JDWP::JT_OBJECT:
2245 case JDWP::JT_STRING:
2246 {
2247 CHECK_EQ(width_, sizeof(JDWP::ObjectId));
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002248 mirror::Object* o = gRegistry->Get<mirror::Object*>(static_cast<JDWP::ObjectId>(value_));
Elliott Hughes64f574f2013-02-20 14:57:12 -08002249 if (o == ObjectRegistry::kInvalidObject) {
Ian Rogers0399dde2012-06-06 17:09:28 -07002250 UNIMPLEMENTED(FATAL) << "return an error code when given an invalid object to store";
2251 }
Ian Rogers2bcb4a42012-11-08 10:39:18 -08002252 SetVReg(m, reg, static_cast<uint32_t>(reinterpret_cast<uintptr_t>(o)), kReferenceVReg);
Ian Rogers0399dde2012-06-06 17:09:28 -07002253 }
2254 break;
2255 case JDWP::JT_DOUBLE:
Ian Rogers2bcb4a42012-11-08 10:39:18 -08002256 CHECK_EQ(width_, 8U);
2257 SetVReg(m, reg, static_cast<uint32_t>(value_), kDoubleLoVReg);
2258 SetVReg(m, reg + 1, static_cast<uint32_t>(value_ >> 32), kDoubleHiVReg);
2259 break;
Ian Rogers0399dde2012-06-06 17:09:28 -07002260 case JDWP::JT_LONG:
2261 CHECK_EQ(width_, 8U);
Ian Rogers2bcb4a42012-11-08 10:39:18 -08002262 SetVReg(m, reg, static_cast<uint32_t>(value_), kLongLoVReg);
2263 SetVReg(m, reg + 1, static_cast<uint32_t>(value_ >> 32), kLongHiVReg);
Ian Rogers0399dde2012-06-06 17:09:28 -07002264 break;
2265 default:
2266 LOG(FATAL) << "Unknown tag " << tag_;
2267 break;
2268 }
2269 return false;
2270 }
2271
2272 const JDWP::FrameId frame_id_;
2273 const int slot_;
2274 const JDWP::JdwpTag tag_;
2275 const uint64_t value_;
2276 const size_t width_;
2277 };
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002278
2279 ScopedObjectAccessUnchecked soa(Thread::Current());
jeffhaoa77f0f62012-12-05 17:19:31 -08002280 MutexLock mu(soa.Self(), *Locks::thread_list_lock_);
Elliott Hughes221229c2013-01-08 18:17:50 -08002281 Thread* thread;
2282 JDWP::JdwpError error = DecodeThread(soa, thread_id, thread);
2283 if (error != JDWP::ERR_NONE) {
2284 return;
2285 }
Elliott Hughes08fc03a2012-06-26 17:34:00 -07002286 UniquePtr<Context> context(Context::Create());
Ian Rogers7a22fa62013-01-23 12:16:16 -08002287 SetLocalVisitor visitor(thread, context.get(), frame_id, slot, tag, value, width);
Ian Rogers0399dde2012-06-06 17:09:28 -07002288 visitor.WalkStack();
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002289}
2290
Ian Rogersef7d42f2014-01-06 12:55:46 -08002291void Dbg::PostLocationEvent(mirror::ArtMethod* m, int dex_pc, mirror::Object* this_object,
Jeff Hao579b0242013-11-18 13:16:49 -08002292 int event_flags, const JValue* return_value) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002293 mirror::Class* c = m->GetDeclaringClass();
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08002294
2295 JDWP::JdwpLocation location;
Elliott Hughes74847412012-06-20 18:10:21 -07002296 location.type_tag = c->IsInterface() ? JDWP::TT_INTERFACE : JDWP::TT_CLASS;
Elliott Hughes64f574f2013-02-20 14:57:12 -08002297 location.class_id = gRegistry->AddRefType(c);
Elliott Hughes74847412012-06-20 18:10:21 -07002298 location.method_id = ToMethodId(m);
Elliott Hughes972a47b2012-02-21 18:16:06 -08002299 location.dex_pc = m->IsNative() ? -1 : dex_pc;
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08002300
Elliott Hughes64f574f2013-02-20 14:57:12 -08002301 // If 'this_object' isn't already in the registry, we know that we're not looking for it,
2302 // so there's no point adding it to the registry and burning through ids.
2303 JDWP::ObjectId this_id = 0;
2304 if (gRegistry->Contains(this_object)) {
2305 this_id = gRegistry->Add(this_object);
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08002306 }
Jeff Hao579b0242013-11-18 13:16:49 -08002307 gJdwpState->PostLocationEvent(&location, this_id, event_flags, return_value);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002308}
2309
Ian Rogers62d6c772013-02-27 08:32:07 -08002310void Dbg::PostException(Thread* thread, const ThrowLocation& throw_location,
Brian Carlstromea46f952013-07-30 01:26:50 -07002311 mirror::ArtMethod* catch_method,
Elliott Hughes64f574f2013-02-20 14:57:12 -08002312 uint32_t catch_dex_pc, mirror::Throwable* exception_object) {
Elliott Hughesc0f09332012-03-26 13:27:06 -07002313 if (!IsDebuggerActive()) {
Ian Rogers0ad5bb82011-12-07 10:16:32 -08002314 return;
2315 }
Elliott Hughes4740cdf2011-12-07 14:07:12 -08002316
Ian Rogers62d6c772013-02-27 08:32:07 -08002317 JDWP::JdwpLocation jdwp_throw_location;
2318 SetLocation(jdwp_throw_location, throw_location.GetMethod(), throw_location.GetDexPc());
Elliott Hughesd07986f2011-12-06 18:27:45 -08002319 JDWP::JdwpLocation catch_location;
Elliott Hughescaf76542012-06-28 16:08:22 -07002320 SetLocation(catch_location, catch_method, catch_dex_pc);
Elliott Hughesd07986f2011-12-06 18:27:45 -08002321
2322 // We need 'this' for InstanceOnly filters.
Ian Rogers62d6c772013-02-27 08:32:07 -08002323 JDWP::ObjectId this_id = gRegistry->Add(throw_location.GetThis());
Elliott Hughes64f574f2013-02-20 14:57:12 -08002324 JDWP::ObjectId exception_id = gRegistry->Add(exception_object);
2325 JDWP::RefTypeId exception_class_id = gRegistry->AddRefType(exception_object->GetClass());
Elliott Hughesd07986f2011-12-06 18:27:45 -08002326
Ian Rogers62d6c772013-02-27 08:32:07 -08002327 gJdwpState->PostException(&jdwp_throw_location, exception_id, exception_class_id, &catch_location,
2328 this_id);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002329}
2330
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002331void Dbg::PostClassPrepare(mirror::Class* c) {
Elliott Hughesc0f09332012-03-26 13:27:06 -07002332 if (!IsDebuggerActive()) {
Elliott Hughes4740cdf2011-12-07 14:07:12 -08002333 return;
2334 }
2335
Elliott Hughes3d30d9b2011-12-07 17:35:48 -08002336 // OLD-TODO - we currently always send both "verified" and "prepared" since
Elliott Hughes4740cdf2011-12-07 14:07:12 -08002337 // debuggers seem to like that. There might be some advantage to honesty,
2338 // since the class may not yet be verified.
2339 int state = JDWP::CS_VERIFIED | JDWP::CS_PREPARED;
2340 JDWP::JdwpTypeTag tag = c->IsInterface() ? JDWP::TT_INTERFACE : JDWP::TT_CLASS;
Ian Rogersfc0e94b2013-09-23 23:51:32 -07002341 gJdwpState->PostClassPrepare(tag, gRegistry->Add(c),
Ian Rogersdfb325e2013-10-30 01:00:44 -07002342 ClassHelper(c).GetDescriptor(), state);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002343}
2344
Ian Rogers62d6c772013-02-27 08:32:07 -08002345void Dbg::UpdateDebugger(Thread* thread, mirror::Object* this_object,
Ian Rogersef7d42f2014-01-06 12:55:46 -08002346 mirror::ArtMethod* m, uint32_t dex_pc) {
Ian Rogers62d6c772013-02-27 08:32:07 -08002347 if (!IsDebuggerActive() || dex_pc == static_cast<uint32_t>(-2) /* fake method exit */) {
Elliott Hughes2aa2e392012-02-17 17:15:43 -08002348 return;
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08002349 }
2350
Elliott Hughes2aa2e392012-02-17 17:15:43 -08002351 int event_flags = 0;
2352
Elliott Hughes86964332012-02-15 19:37:42 -08002353 if (IsBreakpoint(m, dex_pc)) {
2354 event_flags |= kBreakpoint;
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08002355 }
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08002356
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01002357 // If the debugger is single-stepping one of our threads, check to
2358 // see if we're that thread and we've reached a step point.
2359 const SingleStepControl* single_step_control = thread->GetSingleStepControl();
2360 DCHECK(single_step_control != nullptr);
2361 if (single_step_control->is_active) {
2362 CHECK(!m->IsNative());
2363 if (single_step_control->step_depth == JDWP::SD_INTO) {
2364 // Step into method calls. We break when the line number
2365 // or method pointer changes. If we're in SS_MIN mode, we
2366 // always stop.
2367 if (single_step_control->method != m) {
2368 event_flags |= kSingleStep;
2369 VLOG(jdwp) << "SS new method";
2370 } else if (single_step_control->step_size == JDWP::SS_MIN) {
2371 event_flags |= kSingleStep;
2372 VLOG(jdwp) << "SS new instruction";
2373 } else if (single_step_control->dex_pcs.find(dex_pc) == single_step_control->dex_pcs.end()) {
2374 event_flags |= kSingleStep;
2375 VLOG(jdwp) << "SS new line";
2376 }
2377 } else if (single_step_control->step_depth == JDWP::SD_OVER) {
2378 // Step over method calls. We break when the line number is
2379 // different and the frame depth is <= the original frame
2380 // depth. (We can't just compare on the method, because we
2381 // might get unrolled past it by an exception, and it's tricky
2382 // to identify recursion.)
2383
2384 int stack_depth = GetStackDepth(thread);
2385
2386 if (stack_depth < single_step_control->stack_depth) {
2387 // Popped up one or more frames, always trigger.
2388 event_flags |= kSingleStep;
2389 VLOG(jdwp) << "SS method pop";
2390 } else if (stack_depth == single_step_control->stack_depth) {
2391 // Same depth, see if we moved.
2392 if (single_step_control->step_size == JDWP::SS_MIN) {
Elliott Hughes86964332012-02-15 19:37:42 -08002393 event_flags |= kSingleStep;
2394 VLOG(jdwp) << "SS new instruction";
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01002395 } else if (single_step_control->dex_pcs.find(dex_pc) == single_step_control->dex_pcs.end()) {
Elliott Hughes2435a572012-02-17 16:07:41 -08002396 event_flags |= kSingleStep;
2397 VLOG(jdwp) << "SS new line";
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08002398 }
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01002399 }
2400 } else {
2401 CHECK_EQ(single_step_control->step_depth, JDWP::SD_OUT);
2402 // Return from the current method. We break when the frame
2403 // depth pops up.
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08002404
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01002405 // This differs from the "method exit" break in that it stops
2406 // with the PC at the next instruction in the returned-to
2407 // function, rather than the end of the returning function.
Elliott Hughes86964332012-02-15 19:37:42 -08002408
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01002409 int stack_depth = GetStackDepth(thread);
2410 if (stack_depth < single_step_control->stack_depth) {
2411 event_flags |= kSingleStep;
2412 VLOG(jdwp) << "SS method pop";
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08002413 }
2414 }
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08002415 }
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08002416
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08002417 // If there's something interesting going on, see if it matches one
2418 // of the debugger filters.
2419 if (event_flags != 0) {
Jeff Hao579b0242013-11-18 13:16:49 -08002420 Dbg::PostLocationEvent(m, dex_pc, this_object, event_flags, nullptr);
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08002421 }
2422}
2423
Sebastien Hertz138dbfc2013-12-04 18:15:25 +01002424static void ProcessDeoptimizationRequests()
2425 LOCKS_EXCLUDED(Locks::deoptimization_lock_)
2426 EXCLUSIVE_LOCKS_REQUIRED(Locks::mutator_lock_) {
2427 Locks::mutator_lock_->AssertExclusiveHeld(Thread::Current());
2428 MutexLock mu(Thread::Current(), *Locks::deoptimization_lock_);
2429 instrumentation::Instrumentation* instrumentation = Runtime::Current()->GetInstrumentation();
2430 for (const MethodInstrumentationRequest& request : gDeoptimizationRequests) {
2431 mirror::ArtMethod* const method = request.method;
2432 if (method != nullptr) {
2433 // Selective deoptimization.
2434 if (request.deoptimize) {
2435 VLOG(jdwp) << "Deoptimize method " << PrettyMethod(method);
2436 instrumentation->Deoptimize(method);
2437 } else {
2438 VLOG(jdwp) << "Undeoptimize method " << PrettyMethod(method);
2439 instrumentation->Undeoptimize(method);
2440 }
2441 } else {
2442 // Full deoptimization.
2443 if (request.deoptimize) {
2444 VLOG(jdwp) << "Deoptimize the world";
2445 instrumentation->DeoptimizeEverything();
2446 } else {
2447 VLOG(jdwp) << "Undeoptimize the world";
2448 instrumentation->UndeoptimizeEverything();
2449 }
2450 }
2451 }
2452 gDeoptimizationRequests.clear();
2453}
2454
2455// Process deoptimization requests after suspending all mutator threads.
2456void Dbg::ManageDeoptimization() {
2457 Thread* const self = Thread::Current();
2458 {
2459 // Avoid suspend/resume if there is no pending request.
2460 MutexLock mu(self, *Locks::deoptimization_lock_);
2461 if (gDeoptimizationRequests.empty()) {
2462 return;
2463 }
2464 }
2465 CHECK_EQ(self->GetState(), kRunnable);
2466 self->TransitionFromRunnableToSuspended(kWaitingForDeoptimization);
2467 // We need to suspend mutator threads first.
2468 Runtime* const runtime = Runtime::Current();
2469 runtime->GetThreadList()->SuspendAll();
2470 const ThreadState old_state = self->SetStateUnsafe(kRunnable);
2471 ProcessDeoptimizationRequests();
2472 CHECK_EQ(self->SetStateUnsafe(old_state), kRunnable);
2473 runtime->GetThreadList()->ResumeAll();
2474 self->TransitionFromSuspendedToRunnable();
2475}
2476
2477// Enable full deoptimization.
2478void Dbg::EnableFullDeoptimization() {
2479 MutexLock mu(Thread::Current(), *Locks::deoptimization_lock_);
2480 VLOG(jdwp) << "Request full deoptimization";
2481 gDeoptimizationRequests.push_back(MethodInstrumentationRequest(true, nullptr));
2482}
2483
2484// Disable full deoptimization.
2485void Dbg::DisableFullDeoptimization() {
2486 MutexLock mu(Thread::Current(), *Locks::deoptimization_lock_);
2487 VLOG(jdwp) << "Request full undeoptimization";
2488 gDeoptimizationRequests.push_back(MethodInstrumentationRequest(false, nullptr));
2489}
2490
Elliott Hughes86964332012-02-15 19:37:42 -08002491void Dbg::WatchLocation(const JDWP::JdwpLocation* location) {
Sebastien Hertz138dbfc2013-12-04 18:15:25 +01002492 bool need_deoptimization = true;
Brian Carlstromea46f952013-07-30 01:26:50 -07002493 mirror::ArtMethod* m = FromMethodId(location->method_id);
Sebastien Hertz138dbfc2013-12-04 18:15:25 +01002494 {
2495 MutexLock mu(Thread::Current(), *Locks::breakpoint_lock_);
2496
2497 // If there is no breakpoint on this method yet, we need to deoptimize it.
2498 for (const Breakpoint& breakpoint : gBreakpoints) {
2499 if (breakpoint.method == m) {
2500 // We already set a breakpoint on this method, hence we deoptimized it.
2501 DCHECK(Runtime::Current()->GetInstrumentation()->IsDeoptimized(m));
2502 need_deoptimization = false;
2503 break;
2504 }
2505 }
2506
2507 gBreakpoints.push_back(Breakpoint(m, location->dex_pc));
2508 VLOG(jdwp) << "Set breakpoint #" << (gBreakpoints.size() - 1) << ": " << gBreakpoints[gBreakpoints.size() - 1];
2509 }
2510
2511 if (need_deoptimization) {
2512 // Request its deoptimization. This will be done after updating the JDWP event list.
2513 MutexLock mu(Thread::Current(), *Locks::deoptimization_lock_);
2514 gDeoptimizationRequests.push_back(MethodInstrumentationRequest(true, m));
2515 VLOG(jdwp) << "Request deoptimization of " << PrettyMethod(m);
2516 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002517}
2518
Elliott Hughes86964332012-02-15 19:37:42 -08002519void Dbg::UnwatchLocation(const JDWP::JdwpLocation* location) {
Sebastien Hertz138dbfc2013-12-04 18:15:25 +01002520 bool can_undeoptimize = true;
Brian Carlstromea46f952013-07-30 01:26:50 -07002521 mirror::ArtMethod* m = FromMethodId(location->method_id);
Sebastien Hertz138dbfc2013-12-04 18:15:25 +01002522 DCHECK(Runtime::Current()->GetInstrumentation()->IsDeoptimized(m));
2523 {
2524 MutexLock mu(Thread::Current(), *Locks::breakpoint_lock_);
2525 for (size_t i = 0, e = gBreakpoints.size(); i < e; ++i) {
2526 if (gBreakpoints[i].method == m && gBreakpoints[i].dex_pc == location->dex_pc) {
2527 VLOG(jdwp) << "Removed breakpoint #" << i << ": " << gBreakpoints[i];
2528 gBreakpoints.erase(gBreakpoints.begin() + i);
2529 break;
2530 }
Elliott Hughes86964332012-02-15 19:37:42 -08002531 }
Sebastien Hertz138dbfc2013-12-04 18:15:25 +01002532
2533 // If there is no breakpoint on this method, we can undeoptimize it.
2534 for (const Breakpoint& breakpoint : gBreakpoints) {
2535 if (breakpoint.method == m) {
2536 can_undeoptimize = false;
2537 break;
2538 }
2539 }
2540 }
2541
2542 if (can_undeoptimize) {
2543 // Request its undeoptimization. This will be done after updating the JDWP event list.
2544 MutexLock mu(Thread::Current(), *Locks::deoptimization_lock_);
2545 gDeoptimizationRequests.push_back(MethodInstrumentationRequest(false, m));
2546 VLOG(jdwp) << "Request undeoptimization of " << PrettyMethod(m);
Elliott Hughes86964332012-02-15 19:37:42 -08002547 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002548}
2549
Jeff Hao449db332013-04-12 18:30:52 -07002550// Scoped utility class to suspend a thread so that we may do tasks such as walk its stack. Doesn't
2551// cause suspension if the thread is the current thread.
2552class ScopedThreadSuspension {
2553 public:
Ian Rogers33e95662013-05-20 20:29:14 -07002554 ScopedThreadSuspension(Thread* self, JDWP::ObjectId thread_id)
2555 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) :
Jeff Hao449db332013-04-12 18:30:52 -07002556 thread_(NULL),
2557 error_(JDWP::ERR_NONE),
2558 self_suspend_(false),
Ian Rogers33e95662013-05-20 20:29:14 -07002559 other_suspend_(false) {
Jeff Hao449db332013-04-12 18:30:52 -07002560 ScopedObjectAccessUnchecked soa(self);
2561 {
2562 MutexLock mu(soa.Self(), *Locks::thread_list_lock_);
2563 error_ = DecodeThread(soa, thread_id, thread_);
2564 }
2565 if (error_ == JDWP::ERR_NONE) {
2566 if (thread_ == soa.Self()) {
2567 self_suspend_ = true;
2568 } else {
2569 soa.Self()->TransitionFromRunnableToSuspended(kWaitingForDebuggerSuspension);
2570 jobject thread_peer = gRegistry->GetJObject(thread_id);
2571 bool timed_out;
Ian Rogersd9c4fc92013-10-01 19:45:43 -07002572 Thread* suspended_thread = ThreadList::SuspendThreadByPeer(thread_peer, true, true,
2573 &timed_out);
Jeff Hao449db332013-04-12 18:30:52 -07002574 CHECK_EQ(soa.Self()->TransitionFromSuspendedToRunnable(), kWaitingForDebuggerSuspension);
2575 if (suspended_thread == NULL) {
2576 // Thread terminated from under us while suspending.
2577 error_ = JDWP::ERR_INVALID_THREAD;
2578 } else {
2579 CHECK_EQ(suspended_thread, thread_);
2580 other_suspend_ = true;
2581 }
2582 }
2583 }
Elliott Hughes2435a572012-02-17 16:07:41 -08002584 }
Elliott Hughes86964332012-02-15 19:37:42 -08002585
Jeff Hao449db332013-04-12 18:30:52 -07002586 Thread* GetThread() const {
2587 return thread_;
2588 }
2589
2590 JDWP::JdwpError GetError() const {
2591 return error_;
2592 }
2593
2594 ~ScopedThreadSuspension() {
2595 if (other_suspend_) {
2596 Runtime::Current()->GetThreadList()->Resume(thread_, true);
2597 }
2598 }
2599
2600 private:
2601 Thread* thread_;
2602 JDWP::JdwpError error_;
2603 bool self_suspend_;
2604 bool other_suspend_;
2605};
2606
2607JDWP::JdwpError Dbg::ConfigureStep(JDWP::ObjectId thread_id, JDWP::JdwpStepSize step_size,
2608 JDWP::JdwpStepDepth step_depth) {
2609 Thread* self = Thread::Current();
2610 ScopedThreadSuspension sts(self, thread_id);
2611 if (sts.GetError() != JDWP::ERR_NONE) {
2612 return sts.GetError();
2613 }
2614
Elliott Hughes2435a572012-02-17 16:07:41 -08002615 //
2616 // Work out what Method* we're in, the current line number, and how deep the stack currently
2617 // is for step-out.
2618 //
2619
Ian Rogers0399dde2012-06-06 17:09:28 -07002620 struct SingleStepStackVisitor : public StackVisitor {
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01002621 explicit SingleStepStackVisitor(Thread* thread, SingleStepControl* single_step_control,
2622 int32_t* line_number)
Ian Rogersb726dcb2012-09-05 08:57:23 -07002623 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_)
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01002624 : StackVisitor(thread, NULL), single_step_control_(single_step_control),
2625 line_number_(line_number) {
2626 DCHECK_EQ(single_step_control_, thread->GetSingleStepControl());
2627 single_step_control_->method = NULL;
2628 single_step_control_->stack_depth = 0;
Elliott Hughes86964332012-02-15 19:37:42 -08002629 }
Ian Rogersca190662012-06-26 15:45:57 -07002630
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002631 // TODO: Enable annotalysis. We know lock is held in constructor, but abstraction confuses
2632 // annotalysis.
2633 bool VisitFrame() NO_THREAD_SAFETY_ANALYSIS {
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01002634 mirror::ArtMethod* m = GetMethod();
Ian Rogers0399dde2012-06-06 17:09:28 -07002635 if (!m->IsRuntimeMethod()) {
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01002636 ++single_step_control_->stack_depth;
2637 if (single_step_control_->method == NULL) {
Ian Rogersef7d42f2014-01-06 12:55:46 -08002638 mirror::DexCache* dex_cache = m->GetDeclaringClass()->GetDexCache();
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01002639 single_step_control_->method = m;
2640 *line_number_ = -1;
Elliott Hughes2435a572012-02-17 16:07:41 -08002641 if (dex_cache != NULL) {
Ian Rogers4445a7e2012-10-05 17:19:13 -07002642 const DexFile& dex_file = *dex_cache->GetDexFile();
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01002643 *line_number_ = dex_file.GetLineNumFromPC(m, GetDexPc());
Elliott Hughes2435a572012-02-17 16:07:41 -08002644 }
Elliott Hughes86964332012-02-15 19:37:42 -08002645 }
2646 }
Elliott Hughes530fa002012-03-12 11:44:49 -07002647 return true;
Elliott Hughes86964332012-02-15 19:37:42 -08002648 }
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01002649
2650 SingleStepControl* const single_step_control_;
2651 int32_t* const line_number_;
Elliott Hughes86964332012-02-15 19:37:42 -08002652 };
Jeff Hao449db332013-04-12 18:30:52 -07002653
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01002654 Thread* const thread = sts.GetThread();
2655 SingleStepControl* const single_step_control = thread->GetSingleStepControl();
2656 DCHECK(single_step_control != nullptr);
2657 int32_t line_number = -1;
2658 SingleStepStackVisitor visitor(thread, single_step_control, &line_number);
Ian Rogers0399dde2012-06-06 17:09:28 -07002659 visitor.WalkStack();
Elliott Hughes86964332012-02-15 19:37:42 -08002660
Elliott Hughes2435a572012-02-17 16:07:41 -08002661 //
2662 // Find the dex_pc values that correspond to the current line, for line-based single-stepping.
2663 //
2664
2665 struct DebugCallbackContext {
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01002666 explicit DebugCallbackContext(SingleStepControl* single_step_control, int32_t line_number)
2667 : single_step_control_(single_step_control), line_number_(line_number),
2668 last_pc_valid(false), last_pc(0) {
Elliott Hughes2435a572012-02-17 16:07:41 -08002669 }
2670
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01002671 static bool Callback(void* raw_context, uint32_t address, uint32_t line_number) {
Elliott Hughes2435a572012-02-17 16:07:41 -08002672 DebugCallbackContext* context = reinterpret_cast<DebugCallbackContext*>(raw_context);
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01002673 if (static_cast<int32_t>(line_number) == context->line_number_) {
Elliott Hughes2435a572012-02-17 16:07:41 -08002674 if (!context->last_pc_valid) {
2675 // Everything from this address until the next line change is ours.
2676 context->last_pc = address;
2677 context->last_pc_valid = true;
2678 }
2679 // Otherwise, if we're already in a valid range for this line,
2680 // just keep going (shouldn't really happen)...
Brian Carlstrom7934ac22013-07-26 10:54:15 -07002681 } else if (context->last_pc_valid) { // and the line number is new
Elliott Hughes2435a572012-02-17 16:07:41 -08002682 // Add everything from the last entry up until here to the set
2683 for (uint32_t dex_pc = context->last_pc; dex_pc < address; ++dex_pc) {
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01002684 context->single_step_control_->dex_pcs.insert(dex_pc);
Elliott Hughes2435a572012-02-17 16:07:41 -08002685 }
2686 context->last_pc_valid = false;
2687 }
Brian Carlstrom7934ac22013-07-26 10:54:15 -07002688 return false; // There may be multiple entries for any given line.
Elliott Hughes2435a572012-02-17 16:07:41 -08002689 }
2690
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01002691 ~DebugCallbackContext() {
Elliott Hughes2435a572012-02-17 16:07:41 -08002692 // If the line number was the last in the position table...
2693 if (last_pc_valid) {
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01002694 size_t end = MethodHelper(single_step_control_->method).GetCodeItem()->insns_size_in_code_units_;
Elliott Hughes2435a572012-02-17 16:07:41 -08002695 for (uint32_t dex_pc = last_pc; dex_pc < end; ++dex_pc) {
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01002696 single_step_control_->dex_pcs.insert(dex_pc);
Elliott Hughes2435a572012-02-17 16:07:41 -08002697 }
2698 }
2699 }
2700
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01002701 SingleStepControl* const single_step_control_;
2702 const int32_t line_number_;
Elliott Hughes2435a572012-02-17 16:07:41 -08002703 bool last_pc_valid;
2704 uint32_t last_pc;
2705 };
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01002706 single_step_control->dex_pcs.clear();
Ian Rogersef7d42f2014-01-06 12:55:46 -08002707 mirror::ArtMethod* m = single_step_control->method;
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01002708 if (!m->IsNative()) {
2709 DebugCallbackContext context(single_step_control, line_number);
Elliott Hughes3e2e1a22012-02-21 11:33:41 -08002710 MethodHelper mh(m);
2711 mh.GetDexFile().DecodeDebugInfo(mh.GetCodeItem(), m->IsStatic(), m->GetDexMethodIndex(),
2712 DebugCallbackContext::Callback, NULL, &context);
2713 }
Elliott Hughes2435a572012-02-17 16:07:41 -08002714
2715 //
2716 // Everything else...
2717 //
2718
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01002719 single_step_control->step_size = step_size;
2720 single_step_control->step_depth = step_depth;
2721 single_step_control->is_active = true;
Elliott Hughes86964332012-02-15 19:37:42 -08002722
Elliott Hughes2435a572012-02-17 16:07:41 -08002723 if (VLOG_IS_ON(jdwp)) {
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01002724 VLOG(jdwp) << "Single-step thread: " << *thread;
2725 VLOG(jdwp) << "Single-step step size: " << single_step_control->step_size;
2726 VLOG(jdwp) << "Single-step step depth: " << single_step_control->step_depth;
2727 VLOG(jdwp) << "Single-step current method: " << PrettyMethod(single_step_control->method);
2728 VLOG(jdwp) << "Single-step current line: " << line_number;
2729 VLOG(jdwp) << "Single-step current stack depth: " << single_step_control->stack_depth;
Elliott Hughes2435a572012-02-17 16:07:41 -08002730 VLOG(jdwp) << "Single-step dex_pc values:";
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01002731 for (std::set<uint32_t>::iterator it = single_step_control->dex_pcs.begin(); it != single_step_control->dex_pcs.end(); ++it) {
Elliott Hughes229feb72012-02-23 13:33:29 -08002732 VLOG(jdwp) << StringPrintf(" %#x", *it);
Elliott Hughes2435a572012-02-17 16:07:41 -08002733 }
2734 }
2735
2736 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002737}
2738
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01002739void Dbg::UnconfigureStep(JDWP::ObjectId thread_id) {
2740 ScopedObjectAccessUnchecked soa(Thread::Current());
2741 MutexLock mu(soa.Self(), *Locks::thread_list_lock_);
2742 Thread* thread;
2743 JDWP::JdwpError error = DecodeThread(soa, thread_id, thread);
Sebastien Hertz87118ed2013-11-26 17:57:18 +01002744 if (error == JDWP::ERR_NONE) {
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01002745 SingleStepControl* single_step_control = thread->GetSingleStepControl();
2746 DCHECK(single_step_control != nullptr);
2747 single_step_control->is_active = false;
2748 single_step_control->dex_pcs.clear();
2749 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002750}
2751
Elliott Hughes45651fd2012-02-21 15:48:20 -08002752static char JdwpTagToShortyChar(JDWP::JdwpTag tag) {
2753 switch (tag) {
2754 default:
2755 LOG(FATAL) << "unknown JDWP tag: " << PrintableChar(tag);
2756
2757 // Primitives.
2758 case JDWP::JT_BYTE: return 'B';
2759 case JDWP::JT_CHAR: return 'C';
2760 case JDWP::JT_FLOAT: return 'F';
2761 case JDWP::JT_DOUBLE: return 'D';
2762 case JDWP::JT_INT: return 'I';
2763 case JDWP::JT_LONG: return 'J';
2764 case JDWP::JT_SHORT: return 'S';
2765 case JDWP::JT_VOID: return 'V';
2766 case JDWP::JT_BOOLEAN: return 'Z';
2767
2768 // Reference types.
2769 case JDWP::JT_ARRAY:
2770 case JDWP::JT_OBJECT:
2771 case JDWP::JT_STRING:
2772 case JDWP::JT_THREAD:
2773 case JDWP::JT_THREAD_GROUP:
2774 case JDWP::JT_CLASS_LOADER:
2775 case JDWP::JT_CLASS_OBJECT:
2776 return 'L';
2777 }
2778}
2779
Elliott Hughes88d63092013-01-09 09:55:54 -08002780JDWP::JdwpError Dbg::InvokeMethod(JDWP::ObjectId thread_id, JDWP::ObjectId object_id,
2781 JDWP::RefTypeId class_id, JDWP::MethodId method_id,
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002782 uint32_t arg_count, uint64_t* arg_values,
2783 JDWP::JdwpTag* arg_types, uint32_t options,
2784 JDWP::JdwpTag* pResultTag, uint64_t* pResultValue,
2785 JDWP::ObjectId* pExceptionId) {
Elliott Hughesd07986f2011-12-06 18:27:45 -08002786 ThreadList* thread_list = Runtime::Current()->GetThreadList();
2787
2788 Thread* targetThread = NULL;
2789 DebugInvokeReq* req = NULL;
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002790 Thread* self = Thread::Current();
Elliott Hughesd07986f2011-12-06 18:27:45 -08002791 {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002792 ScopedObjectAccessUnchecked soa(self);
Ian Rogers50b35e22012-10-04 10:09:15 -07002793 MutexLock mu(soa.Self(), *Locks::thread_list_lock_);
Elliott Hughes221229c2013-01-08 18:17:50 -08002794 JDWP::JdwpError error = DecodeThread(soa, thread_id, targetThread);
2795 if (error != JDWP::ERR_NONE) {
2796 LOG(ERROR) << "InvokeMethod request for invalid thread id " << thread_id;
2797 return error;
Elliott Hughesd07986f2011-12-06 18:27:45 -08002798 }
2799 req = targetThread->GetInvokeReq();
2800 if (!req->ready) {
2801 LOG(ERROR) << "InvokeMethod request for thread not stopped by event: " << *targetThread;
2802 return JDWP::ERR_INVALID_THREAD;
2803 }
2804
2805 /*
2806 * We currently have a bug where we don't successfully resume the
2807 * target thread if the suspend count is too deep. We're expected to
2808 * require one "resume" for each "suspend", but when asked to execute
2809 * a method we have to resume fully and then re-suspend it back to the
2810 * same level. (The easiest way to cause this is to type "suspend"
2811 * multiple times in jdb.)
2812 *
2813 * It's unclear what this means when the event specifies "resume all"
2814 * and some threads are suspended more deeply than others. This is
2815 * a rare problem, so for now we just prevent it from hanging forever
2816 * by rejecting the method invocation request. Without this, we will
2817 * be stuck waiting on a suspended thread.
2818 */
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002819 int suspend_count;
2820 {
Ian Rogers50b35e22012-10-04 10:09:15 -07002821 MutexLock mu2(soa.Self(), *Locks::thread_suspend_count_lock_);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002822 suspend_count = targetThread->GetSuspendCount();
2823 }
Elliott Hughesd07986f2011-12-06 18:27:45 -08002824 if (suspend_count > 1) {
2825 LOG(ERROR) << *targetThread << " suspend count too deep for method invocation: " << suspend_count;
Brian Carlstrom7934ac22013-07-26 10:54:15 -07002826 return JDWP::ERR_THREAD_SUSPENDED; // Probably not expected here.
Elliott Hughesd07986f2011-12-06 18:27:45 -08002827 }
2828
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08002829 JDWP::JdwpError status;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002830 mirror::Object* receiver = gRegistry->Get<mirror::Object*>(object_id);
Elliott Hughes64f574f2013-02-20 14:57:12 -08002831 if (receiver == ObjectRegistry::kInvalidObject) {
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08002832 return JDWP::ERR_INVALID_OBJECT;
2833 }
Elliott Hughes45651fd2012-02-21 15:48:20 -08002834
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002835 mirror::Object* thread = gRegistry->Get<mirror::Object*>(thread_id);
Elliott Hughes64f574f2013-02-20 14:57:12 -08002836 if (thread == ObjectRegistry::kInvalidObject) {
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08002837 return JDWP::ERR_INVALID_OBJECT;
2838 }
Elliott Hughes45651fd2012-02-21 15:48:20 -08002839 // TODO: check that 'thread' is actually a java.lang.Thread!
2840
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002841 mirror::Class* c = DecodeClass(class_id, status);
Elliott Hughes45651fd2012-02-21 15:48:20 -08002842 if (c == NULL) {
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08002843 return status;
2844 }
Elliott Hughes45651fd2012-02-21 15:48:20 -08002845
Brian Carlstromea46f952013-07-30 01:26:50 -07002846 mirror::ArtMethod* m = FromMethodId(method_id);
Elliott Hughes45651fd2012-02-21 15:48:20 -08002847 if (m->IsStatic() != (receiver == NULL)) {
2848 return JDWP::ERR_INVALID_METHODID;
2849 }
2850 if (m->IsStatic()) {
2851 if (m->GetDeclaringClass() != c) {
2852 return JDWP::ERR_INVALID_METHODID;
2853 }
2854 } else {
2855 if (!m->GetDeclaringClass()->IsAssignableFrom(c)) {
2856 return JDWP::ERR_INVALID_METHODID;
2857 }
2858 }
2859
2860 // Check the argument list matches the method.
2861 MethodHelper mh(m);
2862 if (mh.GetShortyLength() - 1 != arg_count) {
2863 return JDWP::ERR_ILLEGAL_ARGUMENT;
2864 }
2865 const char* shorty = mh.GetShorty();
Elliott Hughes09201632013-04-15 15:50:07 -07002866 const DexFile::TypeList* types = mh.GetParameterTypeList();
Elliott Hughes45651fd2012-02-21 15:48:20 -08002867 for (size_t i = 0; i < arg_count; ++i) {
2868 if (shorty[i + 1] != JdwpTagToShortyChar(arg_types[i])) {
2869 return JDWP::ERR_ILLEGAL_ARGUMENT;
2870 }
Elliott Hughes09201632013-04-15 15:50:07 -07002871
2872 if (shorty[i + 1] == 'L') {
2873 // Did we really get an argument of an appropriate reference type?
2874 mirror::Class* parameter_type = mh.GetClassFromTypeIdx(types->GetTypeItem(i).type_idx_);
2875 mirror::Object* argument = gRegistry->Get<mirror::Object*>(arg_values[i]);
2876 if (argument == ObjectRegistry::kInvalidObject) {
2877 return JDWP::ERR_INVALID_OBJECT;
2878 }
Sebastien Hertz0630ab52013-11-28 18:53:35 +01002879 if (argument != NULL && !argument->InstanceOf(parameter_type)) {
Elliott Hughes09201632013-04-15 15:50:07 -07002880 return JDWP::ERR_ILLEGAL_ARGUMENT;
2881 }
2882
2883 // Turn the on-the-wire ObjectId into a jobject.
2884 jvalue& v = reinterpret_cast<jvalue&>(arg_values[i]);
2885 v.l = gRegistry->GetJObject(arg_values[i]);
2886 }
Elliott Hughes45651fd2012-02-21 15:48:20 -08002887 }
2888
Sebastien Hertzd38667a2013-11-25 15:43:54 +01002889 req->receiver = receiver;
2890 req->thread = thread;
2891 req->klass = c;
2892 req->method = m;
2893 req->arg_count = arg_count;
2894 req->arg_values = arg_values;
2895 req->options = options;
2896 req->invoke_needed = true;
Elliott Hughesd07986f2011-12-06 18:27:45 -08002897 }
2898
2899 // The fact that we've released the thread list lock is a bit risky --- if the thread goes
2900 // away we're sitting high and dry -- but we must release this before the ResumeAllThreads
2901 // call, and it's unwise to hold it during WaitForSuspend.
2902
2903 {
2904 /*
2905 * We change our (JDWP thread) status, which should be THREAD_RUNNING,
Elliott Hughes81ff3182012-03-23 20:35:56 -07002906 * so we can suspend for a GC if the invoke request causes us to
Elliott Hughesd07986f2011-12-06 18:27:45 -08002907 * run out of memory. It's also a good idea to change it before locking
2908 * the invokeReq mutex, although that should never be held for long.
2909 */
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002910 self->TransitionFromRunnableToSuspended(kWaitingForDebuggerSend);
Elliott Hughesd07986f2011-12-06 18:27:45 -08002911
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08002912 VLOG(jdwp) << " Transferring control to event thread";
Elliott Hughesd07986f2011-12-06 18:27:45 -08002913 {
Sebastien Hertzd38667a2013-11-25 15:43:54 +01002914 MutexLock mu(self, req->lock);
Elliott Hughesd07986f2011-12-06 18:27:45 -08002915
2916 if ((options & JDWP::INVOKE_SINGLE_THREADED) == 0) {
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08002917 VLOG(jdwp) << " Resuming all threads";
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002918 thread_list->UndoDebuggerSuspensions();
Elliott Hughesd07986f2011-12-06 18:27:45 -08002919 } else {
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08002920 VLOG(jdwp) << " Resuming event thread only";
Elliott Hughesd07986f2011-12-06 18:27:45 -08002921 thread_list->Resume(targetThread, true);
2922 }
2923
2924 // Wait for the request to finish executing.
Sebastien Hertzd38667a2013-11-25 15:43:54 +01002925 while (req->invoke_needed) {
2926 req->cond.Wait(self);
Elliott Hughesd07986f2011-12-06 18:27:45 -08002927 }
2928 }
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08002929 VLOG(jdwp) << " Control has returned from event thread";
Elliott Hughesd07986f2011-12-06 18:27:45 -08002930
2931 /* wait for thread to re-suspend itself */
Brian Carlstromdf629502013-07-17 22:39:56 -07002932 SuspendThread(thread_id, false /* request_suspension */);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002933 self->TransitionFromSuspendedToRunnable();
Elliott Hughesd07986f2011-12-06 18:27:45 -08002934 }
2935
2936 /*
2937 * Suspend the threads. We waited for the target thread to suspend
2938 * itself, so all we need to do is suspend the others.
2939 *
2940 * The suspendAllThreads() call will double-suspend the event thread,
2941 * so we want to resume the target thread once to keep the books straight.
2942 */
2943 if ((options & JDWP::INVOKE_SINGLE_THREADED) == 0) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002944 self->TransitionFromRunnableToSuspended(kWaitingForDebuggerSuspension);
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08002945 VLOG(jdwp) << " Suspending all threads";
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002946 thread_list->SuspendAllForDebugger();
2947 self->TransitionFromSuspendedToRunnable();
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08002948 VLOG(jdwp) << " Resuming event thread to balance the count";
Elliott Hughesd07986f2011-12-06 18:27:45 -08002949 thread_list->Resume(targetThread, true);
2950 }
2951
2952 // Copy the result.
2953 *pResultTag = req->result_tag;
2954 if (IsPrimitiveTag(req->result_tag)) {
Elliott Hughesf24d3ce2012-04-11 17:43:37 -07002955 *pResultValue = req->result_value.GetJ();
Elliott Hughesd07986f2011-12-06 18:27:45 -08002956 } else {
Elliott Hughesf24d3ce2012-04-11 17:43:37 -07002957 *pResultValue = gRegistry->Add(req->result_value.GetL());
Elliott Hughesd07986f2011-12-06 18:27:45 -08002958 }
2959 *pExceptionId = req->exception;
2960 return req->error;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002961}
2962
2963void Dbg::ExecuteMethod(DebugInvokeReq* pReq) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002964 ScopedObjectAccess soa(Thread::Current());
Elliott Hughesd07986f2011-12-06 18:27:45 -08002965
Elliott Hughes81ff3182012-03-23 20:35:56 -07002966 // We can be called while an exception is pending. We need
Elliott Hughesd07986f2011-12-06 18:27:45 -08002967 // to preserve that across the method invocation.
Ian Rogers62d6c772013-02-27 08:32:07 -08002968 SirtRef<mirror::Object> old_throw_this_object(soa.Self(), NULL);
Brian Carlstromea46f952013-07-30 01:26:50 -07002969 SirtRef<mirror::ArtMethod> old_throw_method(soa.Self(), NULL);
Ian Rogers62d6c772013-02-27 08:32:07 -08002970 SirtRef<mirror::Throwable> old_exception(soa.Self(), NULL);
2971 uint32_t old_throw_dex_pc;
2972 {
2973 ThrowLocation old_throw_location;
2974 mirror::Throwable* old_exception_obj = soa.Self()->GetException(&old_throw_location);
2975 old_throw_this_object.reset(old_throw_location.GetThis());
2976 old_throw_method.reset(old_throw_location.GetMethod());
2977 old_exception.reset(old_exception_obj);
2978 old_throw_dex_pc = old_throw_location.GetDexPc();
2979 soa.Self()->ClearException();
2980 }
Elliott Hughesd07986f2011-12-06 18:27:45 -08002981
2982 // Translate the method through the vtable, unless the debugger wants to suppress it.
Mathieu Chartierc528dba2013-11-26 12:00:11 -08002983 SirtRef<mirror::ArtMethod> m(soa.Self(), pReq->method);
Sebastien Hertzd38667a2013-11-25 15:43:54 +01002984 if ((pReq->options & JDWP::INVOKE_NONVIRTUAL) == 0 && pReq->receiver != NULL) {
2985 mirror::ArtMethod* actual_method = pReq->klass->FindVirtualMethodForVirtualOrInterface(pReq->method);
Mathieu Chartierc528dba2013-11-26 12:00:11 -08002986 if (actual_method != m.get()) {
2987 VLOG(jdwp) << "ExecuteMethod translated " << PrettyMethod(m.get()) << " to " << PrettyMethod(actual_method);
2988 m.reset(actual_method);
Elliott Hughes45651fd2012-02-21 15:48:20 -08002989 }
Elliott Hughesd07986f2011-12-06 18:27:45 -08002990 }
Mathieu Chartierc528dba2013-11-26 12:00:11 -08002991 VLOG(jdwp) << "ExecuteMethod " << PrettyMethod(m.get())
Sebastien Hertzd38667a2013-11-25 15:43:54 +01002992 << " receiver=" << pReq->receiver
2993 << " arg_count=" << pReq->arg_count;
Mathieu Chartierc528dba2013-11-26 12:00:11 -08002994 CHECK(m.get() != nullptr);
Elliott Hughesd07986f2011-12-06 18:27:45 -08002995
2996 CHECK_EQ(sizeof(jvalue), sizeof(uint64_t));
2997
Mathieu Chartierc528dba2013-11-26 12:00:11 -08002998 MethodHelper mh(m.get());
Jeff Hao5d917302013-02-27 17:57:33 -08002999 ArgArray arg_array(mh.GetShorty(), mh.GetShortyLength());
Sebastien Hertzd38667a2013-11-25 15:43:54 +01003000 arg_array.BuildArgArray(soa, pReq->receiver, reinterpret_cast<jvalue*>(pReq->arg_values));
Mathieu Chartierc528dba2013-11-26 12:00:11 -08003001 InvokeWithArgArray(soa, m.get(), &arg_array, &pReq->result_value, mh.GetShorty()[0]);
Elliott Hughesd07986f2011-12-06 18:27:45 -08003002
Ian Rogers62d6c772013-02-27 08:32:07 -08003003 mirror::Throwable* exception = soa.Self()->GetException(NULL);
3004 soa.Self()->ClearException();
3005 pReq->exception = gRegistry->Add(exception);
Mathieu Chartierc528dba2013-11-26 12:00:11 -08003006 pReq->result_tag = BasicTagFromDescriptor(MethodHelper(m.get()).GetShorty());
Elliott Hughesd07986f2011-12-06 18:27:45 -08003007 if (pReq->exception != 0) {
Ian Rogers62d6c772013-02-27 08:32:07 -08003008 VLOG(jdwp) << " JDWP invocation returning with exception=" << exception
3009 << " " << exception->Dump();
Elliott Hughesf24d3ce2012-04-11 17:43:37 -07003010 pReq->result_value.SetJ(0);
Elliott Hughesd07986f2011-12-06 18:27:45 -08003011 } else if (pReq->result_tag == JDWP::JT_OBJECT) {
3012 /* if no exception thrown, examine object result more closely */
Elliott Hughesf24d3ce2012-04-11 17:43:37 -07003013 JDWP::JdwpTag new_tag = TagFromObject(pReq->result_value.GetL());
Elliott Hughesd07986f2011-12-06 18:27:45 -08003014 if (new_tag != pReq->result_tag) {
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08003015 VLOG(jdwp) << " JDWP promoted result from " << pReq->result_tag << " to " << new_tag;
Elliott Hughesd07986f2011-12-06 18:27:45 -08003016 pReq->result_tag = new_tag;
3017 }
3018
3019 /*
3020 * Register the object. We don't actually need an ObjectId yet,
3021 * but we do need to be sure that the GC won't move or discard the
3022 * object when we switch out of RUNNING. The ObjectId conversion
3023 * will add the object to the "do not touch" list.
3024 *
3025 * We can't use the "tracked allocation" mechanism here because
3026 * the object is going to be handed off to a different thread.
3027 */
Elliott Hughesf24d3ce2012-04-11 17:43:37 -07003028 gRegistry->Add(pReq->result_value.GetL());
Elliott Hughesd07986f2011-12-06 18:27:45 -08003029 }
3030
3031 if (old_exception.get() != NULL) {
Ian Rogers62d6c772013-02-27 08:32:07 -08003032 ThrowLocation gc_safe_throw_location(old_throw_this_object.get(), old_throw_method.get(),
3033 old_throw_dex_pc);
3034 soa.Self()->SetException(gc_safe_throw_location, old_exception.get());
Elliott Hughesd07986f2011-12-06 18:27:45 -08003035 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -07003036}
3037
Elliott Hughesd07986f2011-12-06 18:27:45 -08003038/*
Elliott Hughes4b9702c2013-02-20 18:13:24 -08003039 * "request" contains a full JDWP packet, possibly with multiple chunks. We
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07003040 * need to process each, accumulate the replies, and ship the whole thing
3041 * back.
3042 *
3043 * Returns "true" if we have a reply. The reply buffer is newly allocated,
3044 * and includes the chunk type/length, followed by the data.
3045 *
Elliott Hughes3d30d9b2011-12-07 17:35:48 -08003046 * OLD-TODO: we currently assume that the request and reply include a single
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07003047 * chunk. If this becomes inconvenient we will need to adapt.
3048 */
Elliott Hughes4b9702c2013-02-20 18:13:24 -08003049bool Dbg::DdmHandlePacket(JDWP::Request& request, uint8_t** pReplyBuf, int* pReplyLen) {
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07003050 Thread* self = Thread::Current();
3051 JNIEnv* env = self->GetJniEnv();
3052
Elliott Hughes4b9702c2013-02-20 18:13:24 -08003053 uint32_t type = request.ReadUnsigned32("type");
3054 uint32_t length = request.ReadUnsigned32("length");
3055
3056 // Create a byte[] corresponding to 'request'.
3057 size_t request_length = request.size();
3058 ScopedLocalRef<jbyteArray> dataArray(env, env->NewByteArray(request_length));
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003059 if (dataArray.get() == NULL) {
Elliott Hughes4b9702c2013-02-20 18:13:24 -08003060 LOG(WARNING) << "byte[] allocation failed: " << request_length;
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07003061 env->ExceptionClear();
3062 return false;
3063 }
Elliott Hughes4b9702c2013-02-20 18:13:24 -08003064 env->SetByteArrayRegion(dataArray.get(), 0, request_length, reinterpret_cast<const jbyte*>(request.data()));
3065 request.Skip(request_length);
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07003066
3067 // Run through and find all chunks. [Currently just find the first.]
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003068 ScopedByteArrayRO contents(env, dataArray.get());
Elliott Hughes4b9702c2013-02-20 18:13:24 -08003069 if (length != request_length) {
Ian Rogersef7d42f2014-01-06 12:55:46 -08003070 LOG(WARNING) << StringPrintf("bad chunk found (len=%u pktLen=%zd)", length, request_length);
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07003071 return false;
3072 }
3073
3074 // Call "private static Chunk dispatch(int type, byte[] data, int offset, int length)".
Elliott Hugheseac76672012-05-24 21:56:51 -07003075 ScopedLocalRef<jobject> chunk(env, env->CallStaticObjectMethod(WellKnownClasses::org_apache_harmony_dalvik_ddmc_DdmServer,
3076 WellKnownClasses::org_apache_harmony_dalvik_ddmc_DdmServer_dispatch,
Elliott Hughes4b9702c2013-02-20 18:13:24 -08003077 type, dataArray.get(), 0, length));
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07003078 if (env->ExceptionCheck()) {
3079 LOG(INFO) << StringPrintf("Exception thrown by dispatcher for 0x%08x", type);
3080 env->ExceptionDescribe();
3081 env->ExceptionClear();
3082 return false;
3083 }
3084
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003085 if (chunk.get() == NULL) {
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07003086 return false;
3087 }
3088
3089 /*
3090 * Pull the pieces out of the chunk. We copy the results into a
3091 * newly-allocated buffer that the caller can free. We don't want to
3092 * continue using the Chunk object because nothing has a reference to it.
3093 *
3094 * We could avoid this by returning type/data/offset/length and having
3095 * the caller be aware of the object lifetime issues, but that
Elliott Hughes81ff3182012-03-23 20:35:56 -07003096 * integrates the JDWP code more tightly into the rest of the runtime, and doesn't work
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07003097 * if we have responses for multiple chunks.
3098 *
3099 * So we're pretty much stuck with copying data around multiple times.
3100 */
Elliott Hugheseac76672012-05-24 21:56:51 -07003101 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 -08003102 jint offset = env->GetIntField(chunk.get(), WellKnownClasses::org_apache_harmony_dalvik_ddmc_Chunk_offset);
Elliott Hugheseac76672012-05-24 21:56:51 -07003103 length = env->GetIntField(chunk.get(), WellKnownClasses::org_apache_harmony_dalvik_ddmc_Chunk_length);
Elliott Hugheseac76672012-05-24 21:56:51 -07003104 type = env->GetIntField(chunk.get(), WellKnownClasses::org_apache_harmony_dalvik_ddmc_Chunk_type);
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07003105
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08003106 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 -07003107 if (length == 0 || replyData.get() == NULL) {
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07003108 return false;
3109 }
3110
Elliott Hughes4b9702c2013-02-20 18:13:24 -08003111 const int kChunkHdrLen = 8;
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07003112 uint8_t* reply = new uint8_t[length + kChunkHdrLen];
3113 if (reply == NULL) {
3114 LOG(WARNING) << "malloc failed: " << (length + kChunkHdrLen);
3115 return false;
3116 }
Elliott Hughesf7c3b662011-10-27 12:04:56 -07003117 JDWP::Set4BE(reply + 0, type);
3118 JDWP::Set4BE(reply + 4, length);
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003119 env->GetByteArrayRegion(replyData.get(), offset, length, reinterpret_cast<jbyte*>(reply + kChunkHdrLen));
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07003120
3121 *pReplyBuf = reply;
3122 *pReplyLen = length + kChunkHdrLen;
3123
Elliott Hughes4b9702c2013-02-20 18:13:24 -08003124 VLOG(jdwp) << StringPrintf("dvmHandleDdm returning type=%.4s %p len=%d", reinterpret_cast<char*>(reply), reply, length);
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07003125 return true;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07003126}
3127
Elliott Hughesa2155262011-11-16 16:26:58 -08003128void Dbg::DdmBroadcast(bool connect) {
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08003129 VLOG(jdwp) << "Broadcasting DDM " << (connect ? "connect" : "disconnect") << "...";
Elliott Hughes47fce012011-10-25 18:37:19 -07003130
3131 Thread* self = Thread::Current();
Ian Rogers50b35e22012-10-04 10:09:15 -07003132 if (self->GetState() != kRunnable) {
3133 LOG(ERROR) << "DDM broadcast in thread state " << self->GetState();
3134 /* try anyway? */
Elliott Hughes47fce012011-10-25 18:37:19 -07003135 }
3136
3137 JNIEnv* env = self->GetJniEnv();
Elliott Hughes47fce012011-10-25 18:37:19 -07003138 jint event = connect ? 1 /*DdmServer.CONNECTED*/ : 2 /*DdmServer.DISCONNECTED*/;
Elliott Hugheseac76672012-05-24 21:56:51 -07003139 env->CallStaticVoidMethod(WellKnownClasses::org_apache_harmony_dalvik_ddmc_DdmServer,
3140 WellKnownClasses::org_apache_harmony_dalvik_ddmc_DdmServer_broadcast,
3141 event);
Elliott Hughes47fce012011-10-25 18:37:19 -07003142 if (env->ExceptionCheck()) {
3143 LOG(ERROR) << "DdmServer.broadcast " << event << " failed";
3144 env->ExceptionDescribe();
3145 env->ExceptionClear();
3146 }
3147}
3148
Elliott Hughes872d4ec2011-10-21 17:07:15 -07003149void Dbg::DdmConnected() {
Elliott Hughesa2155262011-11-16 16:26:58 -08003150 Dbg::DdmBroadcast(true);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07003151}
3152
3153void Dbg::DdmDisconnected() {
Elliott Hughesa2155262011-11-16 16:26:58 -08003154 Dbg::DdmBroadcast(false);
Elliott Hughes47fce012011-10-25 18:37:19 -07003155 gDdmThreadNotification = false;
3156}
3157
3158/*
Elliott Hughes82188472011-11-07 18:11:48 -08003159 * Send a notification when a thread starts, stops, or changes its name.
Elliott Hughes47fce012011-10-25 18:37:19 -07003160 *
3161 * Because we broadcast the full set of threads when the notifications are
3162 * first enabled, it's possible for "thread" to be actively executing.
3163 */
Elliott Hughes82188472011-11-07 18:11:48 -08003164void Dbg::DdmSendThreadNotification(Thread* t, uint32_t type) {
Elliott Hughes47fce012011-10-25 18:37:19 -07003165 if (!gDdmThreadNotification) {
3166 return;
3167 }
3168
Elliott Hughes82188472011-11-07 18:11:48 -08003169 if (type == CHUNK_TYPE("THDE")) {
Elliott Hughes47fce012011-10-25 18:37:19 -07003170 uint8_t buf[4];
Ian Rogersd9c4fc92013-10-01 19:45:43 -07003171 JDWP::Set4BE(&buf[0], t->GetThreadId());
Elliott Hughes47fce012011-10-25 18:37:19 -07003172 Dbg::DdmSendChunk(CHUNK_TYPE("THDE"), 4, buf);
Elliott Hughes82188472011-11-07 18:11:48 -08003173 } else {
3174 CHECK(type == CHUNK_TYPE("THCR") || type == CHUNK_TYPE("THNM")) << type;
Ian Rogers00f7d0e2012-07-19 15:28:27 -07003175 ScopedObjectAccessUnchecked soa(Thread::Current());
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003176 SirtRef<mirror::String> name(soa.Self(), t->GetThreadName(soa));
Elliott Hughes82188472011-11-07 18:11:48 -08003177 size_t char_count = (name.get() != NULL) ? name->GetLength() : 0;
jeffhao725a9572012-11-13 18:20:12 -08003178 const jchar* chars = (name.get() != NULL) ? name->GetCharArray()->GetData() : NULL;
Elliott Hughes82188472011-11-07 18:11:48 -08003179
Elliott Hughes21f32d72011-11-09 17:44:13 -08003180 std::vector<uint8_t> bytes;
Ian Rogersd9c4fc92013-10-01 19:45:43 -07003181 JDWP::Append4BE(bytes, t->GetThreadId());
Elliott Hughes545a0642011-11-08 19:10:03 -08003182 JDWP::AppendUtf16BE(bytes, chars, char_count);
Elliott Hughes21f32d72011-11-09 17:44:13 -08003183 CHECK_EQ(bytes.size(), char_count*2 + sizeof(uint32_t)*2);
3184 Dbg::DdmSendChunk(type, bytes);
Elliott Hughes47fce012011-10-25 18:37:19 -07003185 }
3186}
3187
Elliott Hughes47fce012011-10-25 18:37:19 -07003188void Dbg::DdmSetThreadNotification(bool enable) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07003189 // Enable/disable thread notifications.
Elliott Hughes47fce012011-10-25 18:37:19 -07003190 gDdmThreadNotification = enable;
3191 if (enable) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07003192 // Suspend the VM then post thread start notifications for all threads. Threads attaching will
3193 // see a suspension in progress and block until that ends. They then post their own start
3194 // notification.
3195 SuspendVM();
3196 std::list<Thread*> threads;
Ian Rogers50b35e22012-10-04 10:09:15 -07003197 Thread* self = Thread::Current();
Ian Rogers00f7d0e2012-07-19 15:28:27 -07003198 {
Ian Rogers50b35e22012-10-04 10:09:15 -07003199 MutexLock mu(self, *Locks::thread_list_lock_);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07003200 threads = Runtime::Current()->GetThreadList()->GetList();
3201 }
3202 {
Ian Rogers50b35e22012-10-04 10:09:15 -07003203 ScopedObjectAccess soa(self);
Mathieu Chartier02e25112013-08-14 16:14:24 -07003204 for (Thread* thread : threads) {
3205 Dbg::DdmSendThreadNotification(thread, CHUNK_TYPE("THCR"));
Ian Rogers00f7d0e2012-07-19 15:28:27 -07003206 }
3207 }
3208 ResumeVM();
Elliott Hughes47fce012011-10-25 18:37:19 -07003209 }
3210}
3211
Elliott Hughesa2155262011-11-16 16:26:58 -08003212void Dbg::PostThreadStartOrStop(Thread* t, uint32_t type) {
Elliott Hughesc0f09332012-03-26 13:27:06 -07003213 if (IsDebuggerActive()) {
Mathieu Chartierdbe6f462012-09-25 16:54:50 -07003214 ScopedObjectAccessUnchecked soa(Thread::Current());
Ian Rogerscfaa4552012-11-26 21:00:08 -08003215 JDWP::ObjectId id = gRegistry->Add(t->GetPeer());
Elliott Hughes82188472011-11-07 18:11:48 -08003216 gJdwpState->PostThreadChange(id, type == CHUNK_TYPE("THCR"));
Elliott Hughes47fce012011-10-25 18:37:19 -07003217 }
Elliott Hughes82188472011-11-07 18:11:48 -08003218 Dbg::DdmSendThreadNotification(t, type);
Elliott Hughes47fce012011-10-25 18:37:19 -07003219}
3220
3221void Dbg::PostThreadStart(Thread* t) {
Elliott Hughesa2155262011-11-16 16:26:58 -08003222 Dbg::PostThreadStartOrStop(t, CHUNK_TYPE("THCR"));
Elliott Hughes47fce012011-10-25 18:37:19 -07003223}
3224
3225void Dbg::PostThreadDeath(Thread* t) {
Elliott Hughesa2155262011-11-16 16:26:58 -08003226 Dbg::PostThreadStartOrStop(t, CHUNK_TYPE("THDE"));
Elliott Hughes872d4ec2011-10-21 17:07:15 -07003227}
3228
Elliott Hughes82188472011-11-07 18:11:48 -08003229void Dbg::DdmSendChunk(uint32_t type, size_t byte_count, const uint8_t* buf) {
Elliott Hughes3bb81562011-10-21 18:52:59 -07003230 CHECK(buf != NULL);
3231 iovec vec[1];
3232 vec[0].iov_base = reinterpret_cast<void*>(const_cast<uint8_t*>(buf));
3233 vec[0].iov_len = byte_count;
3234 Dbg::DdmSendChunkV(type, vec, 1);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07003235}
3236
Elliott Hughes21f32d72011-11-09 17:44:13 -08003237void Dbg::DdmSendChunk(uint32_t type, const std::vector<uint8_t>& bytes) {
3238 DdmSendChunk(type, bytes.size(), &bytes[0]);
3239}
3240
Brian Carlstromf5293522013-07-19 00:24:00 -07003241void Dbg::DdmSendChunkV(uint32_t type, const iovec* iov, int iov_count) {
Elliott Hughes3bb81562011-10-21 18:52:59 -07003242 if (gJdwpState == NULL) {
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08003243 VLOG(jdwp) << "Debugger thread not active, ignoring DDM send: " << type;
Elliott Hughes3bb81562011-10-21 18:52:59 -07003244 } else {
Elliott Hughescccd84f2011-12-05 16:51:54 -08003245 gJdwpState->DdmSendChunkV(type, iov, iov_count);
Elliott Hughes3bb81562011-10-21 18:52:59 -07003246 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -07003247}
3248
Elliott Hughes767a1472011-10-26 18:49:02 -07003249int Dbg::DdmHandleHpifChunk(HpifWhen when) {
3250 if (when == HPIF_WHEN_NOW) {
Elliott Hughes7162ad92011-10-27 14:08:42 -07003251 DdmSendHeapInfo(when);
Elliott Hughes767a1472011-10-26 18:49:02 -07003252 return true;
3253 }
3254
3255 if (when != HPIF_WHEN_NEVER && when != HPIF_WHEN_NEXT_GC && when != HPIF_WHEN_EVERY_GC) {
3256 LOG(ERROR) << "invalid HpifWhen value: " << static_cast<int>(when);
3257 return false;
3258 }
3259
3260 gDdmHpifWhen = when;
3261 return true;
3262}
3263
3264bool Dbg::DdmHandleHpsgNhsgChunk(Dbg::HpsgWhen when, Dbg::HpsgWhat what, bool native) {
3265 if (when != HPSG_WHEN_NEVER && when != HPSG_WHEN_EVERY_GC) {
3266 LOG(ERROR) << "invalid HpsgWhen value: " << static_cast<int>(when);
3267 return false;
3268 }
3269
3270 if (what != HPSG_WHAT_MERGED_OBJECTS && what != HPSG_WHAT_DISTINCT_OBJECTS) {
3271 LOG(ERROR) << "invalid HpsgWhat value: " << static_cast<int>(what);
3272 return false;
3273 }
3274
3275 if (native) {
3276 gDdmNhsgWhen = when;
3277 gDdmNhsgWhat = what;
3278 } else {
3279 gDdmHpsgWhen = when;
3280 gDdmHpsgWhat = what;
3281 }
3282 return true;
3283}
3284
Elliott Hughes7162ad92011-10-27 14:08:42 -07003285void Dbg::DdmSendHeapInfo(HpifWhen reason) {
3286 // If there's a one-shot 'when', reset it.
3287 if (reason == gDdmHpifWhen) {
3288 if (gDdmHpifWhen == HPIF_WHEN_NEXT_GC) {
3289 gDdmHpifWhen = HPIF_WHEN_NEVER;
3290 }
3291 }
3292
3293 /*
3294 * Chunk HPIF (client --> server)
3295 *
3296 * Heap Info. General information about the heap,
3297 * suitable for a summary display.
3298 *
3299 * [u4]: number of heaps
3300 *
3301 * For each heap:
3302 * [u4]: heap ID
3303 * [u8]: timestamp in ms since Unix epoch
3304 * [u1]: capture reason (same as 'when' value from server)
3305 * [u4]: max heap size in bytes (-Xmx)
3306 * [u4]: current heap size in bytes
3307 * [u4]: current number of bytes allocated
3308 * [u4]: current number of objects allocated
3309 */
3310 uint8_t heap_count = 1;
Ian Rogers1d54e732013-05-02 21:10:01 -07003311 gc::Heap* heap = Runtime::Current()->GetHeap();
Elliott Hughes21f32d72011-11-09 17:44:13 -08003312 std::vector<uint8_t> bytes;
Elliott Hughes545a0642011-11-08 19:10:03 -08003313 JDWP::Append4BE(bytes, heap_count);
Brian Carlstrom7934ac22013-07-26 10:54:15 -07003314 JDWP::Append4BE(bytes, 1); // Heap id (bogus; we only have one heap).
Elliott Hughes545a0642011-11-08 19:10:03 -08003315 JDWP::Append8BE(bytes, MilliTime());
3316 JDWP::Append1BE(bytes, reason);
Brian Carlstrom7934ac22013-07-26 10:54:15 -07003317 JDWP::Append4BE(bytes, heap->GetMaxMemory()); // Max allowed heap size in bytes.
3318 JDWP::Append4BE(bytes, heap->GetTotalMemory()); // Current heap size in bytes.
Elliott Hughesb3bd5f02012-03-08 21:05:27 -08003319 JDWP::Append4BE(bytes, heap->GetBytesAllocated());
3320 JDWP::Append4BE(bytes, heap->GetObjectsAllocated());
Elliott Hughes21f32d72011-11-09 17:44:13 -08003321 CHECK_EQ(bytes.size(), 4U + (heap_count * (4 + 8 + 1 + 4 + 4 + 4 + 4)));
3322 Dbg::DdmSendChunk(CHUNK_TYPE("HPIF"), bytes);
Elliott Hughes767a1472011-10-26 18:49:02 -07003323}
3324
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003325enum HpsgSolidity {
3326 SOLIDITY_FREE = 0,
3327 SOLIDITY_HARD = 1,
3328 SOLIDITY_SOFT = 2,
3329 SOLIDITY_WEAK = 3,
3330 SOLIDITY_PHANTOM = 4,
3331 SOLIDITY_FINALIZABLE = 5,
3332 SOLIDITY_SWEEP = 6,
3333};
3334
3335enum HpsgKind {
3336 KIND_OBJECT = 0,
3337 KIND_CLASS_OBJECT = 1,
3338 KIND_ARRAY_1 = 2,
3339 KIND_ARRAY_2 = 3,
3340 KIND_ARRAY_4 = 4,
3341 KIND_ARRAY_8 = 5,
3342 KIND_UNKNOWN = 6,
3343 KIND_NATIVE = 7,
3344};
3345
3346#define HPSG_PARTIAL (1<<7)
3347#define HPSG_STATE(solidity, kind) ((uint8_t)((((kind) & 0x7) << 3) | ((solidity) & 0x7)))
3348
Ian Rogers30fab402012-01-23 15:43:46 -08003349class HeapChunkContext {
3350 public:
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003351 // Maximum chunk size. Obtain this from the formula:
3352 // (((maximum_heap_size / ALLOCATION_UNIT_SIZE) + 255) / 256) * 2
3353 HeapChunkContext(bool merge, bool native)
Ian Rogers30fab402012-01-23 15:43:46 -08003354 : buf_(16384 - 16),
3355 type_(0),
3356 merge_(merge) {
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003357 Reset();
3358 if (native) {
Ian Rogers30fab402012-01-23 15:43:46 -08003359 type_ = CHUNK_TYPE("NHSG");
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003360 } else {
Ian Rogers30fab402012-01-23 15:43:46 -08003361 type_ = merge ? CHUNK_TYPE("HPSG") : CHUNK_TYPE("HPSO");
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003362 }
3363 }
3364
3365 ~HeapChunkContext() {
Ian Rogers30fab402012-01-23 15:43:46 -08003366 if (p_ > &buf_[0]) {
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003367 Flush();
3368 }
3369 }
3370
3371 void EnsureHeader(const void* chunk_ptr) {
Ian Rogers30fab402012-01-23 15:43:46 -08003372 if (!needHeader_) {
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003373 return;
3374 }
3375
3376 // Start a new HPSx chunk.
Brian Carlstrom7934ac22013-07-26 10:54:15 -07003377 JDWP::Write4BE(&p_, 1); // Heap id (bogus; we only have one heap).
3378 JDWP::Write1BE(&p_, 8); // Size of allocation unit, in bytes.
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003379
Brian Carlstrom7934ac22013-07-26 10:54:15 -07003380 JDWP::Write4BE(&p_, reinterpret_cast<uintptr_t>(chunk_ptr)); // virtual address of segment start.
3381 JDWP::Write4BE(&p_, 0); // offset of this piece (relative to the virtual address).
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003382 // [u4]: length of piece, in allocation units
3383 // 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 -08003384 pieceLenField_ = p_;
3385 JDWP::Write4BE(&p_, 0x55555555);
3386 needHeader_ = false;
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003387 }
3388
Ian Rogersb726dcb2012-09-05 08:57:23 -07003389 void Flush() SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Ian Rogersd636b062013-01-18 17:51:18 -08003390 if (pieceLenField_ == NULL) {
3391 // Flush immediately post Reset (maybe back-to-back Flush). Ignore.
3392 CHECK(needHeader_);
3393 return;
3394 }
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003395 // Patch the "length of piece" field.
Ian Rogers30fab402012-01-23 15:43:46 -08003396 CHECK_LE(&buf_[0], pieceLenField_);
3397 CHECK_LE(pieceLenField_, p_);
3398 JDWP::Set4BE(pieceLenField_, totalAllocationUnits_);
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003399
Ian Rogers30fab402012-01-23 15:43:46 -08003400 Dbg::DdmSendChunk(type_, p_ - &buf_[0], &buf_[0]);
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003401 Reset();
3402 }
3403
Ian Rogers00f7d0e2012-07-19 15:28:27 -07003404 static void HeapChunkCallback(void* start, void* end, size_t used_bytes, void* arg)
Ian Rogersb726dcb2012-09-05 08:57:23 -07003405 SHARED_LOCKS_REQUIRED(Locks::heap_bitmap_lock_,
3406 Locks::mutator_lock_) {
Ian Rogers30fab402012-01-23 15:43:46 -08003407 reinterpret_cast<HeapChunkContext*>(arg)->HeapChunkCallback(start, end, used_bytes);
Elliott Hughesa2155262011-11-16 16:26:58 -08003408 }
3409
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003410 private:
Elliott Hughesa2155262011-11-16 16:26:58 -08003411 enum { ALLOCATION_UNIT_SIZE = 8 };
3412
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003413 void Reset() {
Ian Rogers30fab402012-01-23 15:43:46 -08003414 p_ = &buf_[0];
Ian Rogers15bf2d32012-08-28 17:33:04 -07003415 startOfNextMemoryChunk_ = NULL;
Ian Rogers30fab402012-01-23 15:43:46 -08003416 totalAllocationUnits_ = 0;
3417 needHeader_ = true;
3418 pieceLenField_ = NULL;
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003419 }
3420
Ian Rogers00f7d0e2012-07-19 15:28:27 -07003421 void HeapChunkCallback(void* start, void* /*end*/, size_t used_bytes)
Ian Rogersb726dcb2012-09-05 08:57:23 -07003422 SHARED_LOCKS_REQUIRED(Locks::heap_bitmap_lock_,
3423 Locks::mutator_lock_) {
Ian Rogers30fab402012-01-23 15:43:46 -08003424 // Note: heap call backs cannot manipulate the heap upon which they are crawling, care is taken
3425 // in the following code not to allocate memory, by ensuring buf_ is of the correct size
Ian Rogers15bf2d32012-08-28 17:33:04 -07003426 if (used_bytes == 0) {
3427 if (start == NULL) {
3428 // Reset for start of new heap.
3429 startOfNextMemoryChunk_ = NULL;
3430 Flush();
3431 }
3432 // Only process in use memory so that free region information
3433 // also includes dlmalloc book keeping.
Elliott Hughesa2155262011-11-16 16:26:58 -08003434 return;
Elliott Hughesa2155262011-11-16 16:26:58 -08003435 }
3436
Ian Rogers15bf2d32012-08-28 17:33:04 -07003437 /* If we're looking at the native heap, we'll just return
3438 * (SOLIDITY_HARD, KIND_NATIVE) for all allocated chunks
3439 */
3440 bool native = type_ == CHUNK_TYPE("NHSG");
3441
3442 if (startOfNextMemoryChunk_ != NULL) {
3443 // Transmit any pending free memory. Native free memory of
3444 // over kMaxFreeLen could be because of the use of mmaps, so
3445 // don't report. If not free memory then start a new segment.
3446 bool flush = true;
3447 if (start > startOfNextMemoryChunk_) {
3448 const size_t kMaxFreeLen = 2 * kPageSize;
3449 void* freeStart = startOfNextMemoryChunk_;
3450 void* freeEnd = start;
Brian Carlstrom2d888622013-07-18 17:02:00 -07003451 size_t freeLen = reinterpret_cast<char*>(freeEnd) - reinterpret_cast<char*>(freeStart);
Ian Rogers15bf2d32012-08-28 17:33:04 -07003452 if (!native || freeLen < kMaxFreeLen) {
3453 AppendChunk(HPSG_STATE(SOLIDITY_FREE, 0), freeStart, freeLen);
3454 flush = false;
3455 }
3456 }
3457 if (flush) {
3458 startOfNextMemoryChunk_ = NULL;
3459 Flush();
3460 }
3461 }
Ian Rogersef7d42f2014-01-06 12:55:46 -08003462 mirror::Object* obj = reinterpret_cast<mirror::Object*>(start);
Elliott Hughesa2155262011-11-16 16:26:58 -08003463
3464 // Determine the type of this chunk.
3465 // OLD-TODO: if context.merge, see if this chunk is different from the last chunk.
3466 // If it's the same, we should combine them.
Ian Rogers15bf2d32012-08-28 17:33:04 -07003467 uint8_t state = ExamineObject(obj, native);
3468 // dlmalloc's chunk header is 2 * sizeof(size_t), but if the previous chunk is in use for an
3469 // allocation then the first sizeof(size_t) may belong to it.
3470 const size_t dlMallocOverhead = sizeof(size_t);
3471 AppendChunk(state, start, used_bytes + dlMallocOverhead);
Brian Carlstrom2d888622013-07-18 17:02:00 -07003472 startOfNextMemoryChunk_ = reinterpret_cast<char*>(start) + used_bytes + dlMallocOverhead;
Ian Rogers15bf2d32012-08-28 17:33:04 -07003473 }
Elliott Hughesa2155262011-11-16 16:26:58 -08003474
Ian Rogers15bf2d32012-08-28 17:33:04 -07003475 void AppendChunk(uint8_t state, void* ptr, size_t length)
Ian Rogersb726dcb2012-09-05 08:57:23 -07003476 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Ian Rogers15bf2d32012-08-28 17:33:04 -07003477 // Make sure there's enough room left in the buffer.
3478 // We need to use two bytes for every fractional 256 allocation units used by the chunk plus
3479 // 17 bytes for any header.
3480 size_t needed = (((length/ALLOCATION_UNIT_SIZE + 255) / 256) * 2) + 17;
3481 size_t bytesLeft = buf_.size() - (size_t)(p_ - &buf_[0]);
3482 if (bytesLeft < needed) {
3483 Flush();
3484 }
3485
3486 bytesLeft = buf_.size() - (size_t)(p_ - &buf_[0]);
3487 if (bytesLeft < needed) {
3488 LOG(WARNING) << "Chunk is too big to transmit (chunk_len=" << length << ", "
3489 << needed << " bytes)";
3490 return;
3491 }
3492 EnsureHeader(ptr);
Elliott Hughesa2155262011-11-16 16:26:58 -08003493 // Write out the chunk description.
Ian Rogers15bf2d32012-08-28 17:33:04 -07003494 length /= ALLOCATION_UNIT_SIZE; // Convert to allocation units.
3495 totalAllocationUnits_ += length;
3496 while (length > 256) {
Ian Rogers30fab402012-01-23 15:43:46 -08003497 *p_++ = state | HPSG_PARTIAL;
3498 *p_++ = 255; // length - 1
Ian Rogers15bf2d32012-08-28 17:33:04 -07003499 length -= 256;
Elliott Hughesa2155262011-11-16 16:26:58 -08003500 }
Ian Rogers30fab402012-01-23 15:43:46 -08003501 *p_++ = state;
Ian Rogers15bf2d32012-08-28 17:33:04 -07003502 *p_++ = length - 1;
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003503 }
3504
Ian Rogersef7d42f2014-01-06 12:55:46 -08003505 uint8_t ExamineObject(mirror::Object* o, bool is_native_heap)
3506 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_, Locks::heap_bitmap_lock_) {
Elliott Hughesa2155262011-11-16 16:26:58 -08003507 if (o == NULL) {
3508 return HPSG_STATE(SOLIDITY_FREE, 0);
3509 }
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003510
Elliott Hughesa2155262011-11-16 16:26:58 -08003511 // It's an allocated chunk. Figure out what it is.
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003512
Elliott Hughesa2155262011-11-16 16:26:58 -08003513 // If we're looking at the native heap, we'll just return
3514 // (SOLIDITY_HARD, KIND_NATIVE) for all allocated chunks.
Ian Rogers00f7d0e2012-07-19 15:28:27 -07003515 if (is_native_heap) {
Elliott Hughesa2155262011-11-16 16:26:58 -08003516 return HPSG_STATE(SOLIDITY_HARD, KIND_NATIVE);
3517 }
3518
Ian Rogers5bfa60f2012-09-02 21:17:56 -07003519 if (!Runtime::Current()->GetHeap()->IsLiveObjectLocked(o)) {
Ian Rogers15bf2d32012-08-28 17:33:04 -07003520 return HPSG_STATE(SOLIDITY_HARD, KIND_NATIVE);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07003521 }
3522
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003523 mirror::Class* c = o->GetClass();
Elliott Hughesa2155262011-11-16 16:26:58 -08003524 if (c == NULL) {
3525 // The object was probably just created but hasn't been initialized yet.
3526 return HPSG_STATE(SOLIDITY_HARD, KIND_OBJECT);
3527 }
3528
Mathieu Chartier590fee92013-09-13 13:46:47 -07003529 if (!Runtime::Current()->GetHeap()->IsValidObjectAddress(c)) {
Ian Rogers15bf2d32012-08-28 17:33:04 -07003530 LOG(ERROR) << "Invalid class for managed heap object: " << o << " " << c;
Elliott Hughesa2155262011-11-16 16:26:58 -08003531 return HPSG_STATE(SOLIDITY_HARD, KIND_UNKNOWN);
3532 }
3533
3534 if (c->IsClassClass()) {
3535 return HPSG_STATE(SOLIDITY_HARD, KIND_CLASS_OBJECT);
3536 }
3537
3538 if (c->IsArrayClass()) {
3539 if (o->IsObjectArray()) {
3540 return HPSG_STATE(SOLIDITY_HARD, KIND_ARRAY_4);
3541 }
3542 switch (c->GetComponentSize()) {
3543 case 1: return HPSG_STATE(SOLIDITY_HARD, KIND_ARRAY_1);
3544 case 2: return HPSG_STATE(SOLIDITY_HARD, KIND_ARRAY_2);
3545 case 4: return HPSG_STATE(SOLIDITY_HARD, KIND_ARRAY_4);
3546 case 8: return HPSG_STATE(SOLIDITY_HARD, KIND_ARRAY_8);
3547 }
3548 }
3549
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003550 return HPSG_STATE(SOLIDITY_HARD, KIND_OBJECT);
3551 }
3552
Ian Rogers30fab402012-01-23 15:43:46 -08003553 std::vector<uint8_t> buf_;
3554 uint8_t* p_;
3555 uint8_t* pieceLenField_;
Ian Rogers15bf2d32012-08-28 17:33:04 -07003556 void* startOfNextMemoryChunk_;
Ian Rogers30fab402012-01-23 15:43:46 -08003557 size_t totalAllocationUnits_;
3558 uint32_t type_;
3559 bool merge_;
3560 bool needHeader_;
3561
Elliott Hughesa2155262011-11-16 16:26:58 -08003562 DISALLOW_COPY_AND_ASSIGN(HeapChunkContext);
3563};
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003564
3565void Dbg::DdmSendHeapSegments(bool native) {
3566 Dbg::HpsgWhen when;
3567 Dbg::HpsgWhat what;
3568 if (!native) {
3569 when = gDdmHpsgWhen;
3570 what = gDdmHpsgWhat;
3571 } else {
3572 when = gDdmNhsgWhen;
3573 what = gDdmNhsgWhat;
3574 }
3575 if (when == HPSG_WHEN_NEVER) {
3576 return;
3577 }
3578
3579 // Figure out what kind of chunks we'll be sending.
3580 CHECK(what == HPSG_WHAT_MERGED_OBJECTS || what == HPSG_WHAT_DISTINCT_OBJECTS) << static_cast<int>(what);
3581
3582 // First, send a heap start chunk.
3583 uint8_t heap_id[4];
Brian Carlstrom7934ac22013-07-26 10:54:15 -07003584 JDWP::Set4BE(&heap_id[0], 1); // Heap id (bogus; we only have one heap).
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003585 Dbg::DdmSendChunk(native ? CHUNK_TYPE("NHST") : CHUNK_TYPE("HPST"), sizeof(heap_id), heap_id);
3586
Hiroshi Yamauchicf58d4a2013-09-26 14:21:22 -07003587 Thread* self = Thread::Current();
3588
3589 // To allow the Walk/InspectAll() below to exclusively-lock the
3590 // mutator lock, temporarily release the shared access to the
3591 // mutator lock here by transitioning to the suspended state.
3592 Locks::mutator_lock_->AssertSharedHeld(self);
3593 self->TransitionFromRunnableToSuspended(kSuspended);
3594
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003595 // Send a series of heap segment chunks.
Elliott Hughesa2155262011-11-16 16:26:58 -08003596 HeapChunkContext context((what == HPSG_WHAT_MERGED_OBJECTS), native);
3597 if (native) {
Ian Rogers1d54e732013-05-02 21:10:01 -07003598 dlmalloc_inspect_all(HeapChunkContext::HeapChunkCallback, &context);
Elliott Hughesa2155262011-11-16 16:26:58 -08003599 } else {
Ian Rogers1d54e732013-05-02 21:10:01 -07003600 gc::Heap* heap = Runtime::Current()->GetHeap();
3601 const std::vector<gc::space::ContinuousSpace*>& spaces = heap->GetContinuousSpaces();
Ian Rogers62d6c772013-02-27 08:32:07 -08003602 ReaderMutexLock mu(self, *Locks::heap_bitmap_lock_);
Ian Rogers1d54e732013-05-02 21:10:01 -07003603 typedef std::vector<gc::space::ContinuousSpace*>::const_iterator It;
3604 for (It cur = spaces.begin(), end = spaces.end(); cur != end; ++cur) {
Hiroshi Yamauchicf58d4a2013-09-26 14:21:22 -07003605 if ((*cur)->IsMallocSpace()) {
3606 (*cur)->AsMallocSpace()->Walk(HeapChunkContext::HeapChunkCallback, &context);
Mathieu Chartierb062fdd2012-07-03 09:51:48 -07003607 }
3608 }
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -07003609 // Walk the large objects, these are not in the AllocSpace.
3610 heap->GetLargeObjectsSpace()->Walk(HeapChunkContext::HeapChunkCallback, &context);
Elliott Hughesa2155262011-11-16 16:26:58 -08003611 }
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003612
Hiroshi Yamauchicf58d4a2013-09-26 14:21:22 -07003613 // Shared-lock the mutator lock back.
3614 self->TransitionFromSuspendedToRunnable();
3615 Locks::mutator_lock_->AssertSharedHeld(self);
3616
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003617 // Finally, send a heap end chunk.
3618 Dbg::DdmSendChunk(native ? CHUNK_TYPE("NHEN") : CHUNK_TYPE("HPEN"), sizeof(heap_id), heap_id);
Elliott Hughes767a1472011-10-26 18:49:02 -07003619}
3620
Elliott Hughesb1a58792013-07-11 18:10:58 -07003621static size_t GetAllocTrackerMax() {
3622#ifdef HAVE_ANDROID_OS
3623 // Check whether there's a system property overriding the number of records.
3624 const char* propertyName = "dalvik.vm.allocTrackerMax";
3625 char allocRecordMaxString[PROPERTY_VALUE_MAX];
3626 if (property_get(propertyName, allocRecordMaxString, "") > 0) {
3627 char* end;
3628 size_t value = strtoul(allocRecordMaxString, &end, 10);
3629 if (*end != '\0') {
Ruben Brunk3e47a742013-09-09 17:56:07 -07003630 LOG(ERROR) << "Ignoring " << propertyName << " '" << allocRecordMaxString
3631 << "' --- invalid";
Elliott Hughesb1a58792013-07-11 18:10:58 -07003632 return kDefaultNumAllocRecords;
3633 }
3634 if (!IsPowerOfTwo(value)) {
Ruben Brunk3e47a742013-09-09 17:56:07 -07003635 LOG(ERROR) << "Ignoring " << propertyName << " '" << allocRecordMaxString
3636 << "' --- not power of two";
Elliott Hughesb1a58792013-07-11 18:10:58 -07003637 return kDefaultNumAllocRecords;
3638 }
3639 return value;
3640 }
3641#endif
3642 return kDefaultNumAllocRecords;
3643}
3644
Elliott Hughes545a0642011-11-08 19:10:03 -08003645void Dbg::SetAllocTrackingEnabled(bool enabled) {
Ian Rogers50b35e22012-10-04 10:09:15 -07003646 MutexLock mu(Thread::Current(), gAllocTrackerLock);
Elliott Hughes545a0642011-11-08 19:10:03 -08003647 if (enabled) {
3648 if (recent_allocation_records_ == NULL) {
Elliott Hughesb1a58792013-07-11 18:10:58 -07003649 gAllocRecordMax = GetAllocTrackerMax();
3650 LOG(INFO) << "Enabling alloc tracker (" << gAllocRecordMax << " entries of "
3651 << kMaxAllocRecordStackDepth << " frames, taking "
3652 << PrettySize(sizeof(AllocRecord) * gAllocRecordMax) << ")";
Elliott Hughes545a0642011-11-08 19:10:03 -08003653 gAllocRecordHead = gAllocRecordCount = 0;
Elliott Hughesb1a58792013-07-11 18:10:58 -07003654 recent_allocation_records_ = new AllocRecord[gAllocRecordMax];
Elliott Hughes545a0642011-11-08 19:10:03 -08003655 CHECK(recent_allocation_records_ != NULL);
3656 }
Ian Rogersfa824272013-11-05 16:12:57 -08003657 Runtime::Current()->GetInstrumentation()->InstrumentQuickAllocEntryPoints();
Elliott Hughes545a0642011-11-08 19:10:03 -08003658 } else {
Ian Rogersfa824272013-11-05 16:12:57 -08003659 Runtime::Current()->GetInstrumentation()->UninstrumentQuickAllocEntryPoints();
Elliott Hughes545a0642011-11-08 19:10:03 -08003660 delete[] recent_allocation_records_;
3661 recent_allocation_records_ = NULL;
3662 }
3663}
3664
Ian Rogers0399dde2012-06-06 17:09:28 -07003665struct AllocRecordStackVisitor : public StackVisitor {
Ian Rogers7a22fa62013-01-23 12:16:16 -08003666 AllocRecordStackVisitor(Thread* thread, AllocRecord* record)
Ian Rogersb726dcb2012-09-05 08:57:23 -07003667 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_)
Ian Rogers7a22fa62013-01-23 12:16:16 -08003668 : StackVisitor(thread, NULL), record(record), depth(0) {}
Elliott Hughes545a0642011-11-08 19:10:03 -08003669
Ian Rogers00f7d0e2012-07-19 15:28:27 -07003670 // TODO: Enable annotalysis. We know lock is held in constructor, but abstraction confuses
3671 // annotalysis.
3672 bool VisitFrame() NO_THREAD_SAFETY_ANALYSIS {
Elliott Hughes545a0642011-11-08 19:10:03 -08003673 if (depth >= kMaxAllocRecordStackDepth) {
Elliott Hughes530fa002012-03-12 11:44:49 -07003674 return false;
Elliott Hughes545a0642011-11-08 19:10:03 -08003675 }
Brian Carlstromea46f952013-07-30 01:26:50 -07003676 mirror::ArtMethod* m = GetMethod();
Ian Rogers0399dde2012-06-06 17:09:28 -07003677 if (!m->IsRuntimeMethod()) {
3678 record->stack[depth].method = m;
3679 record->stack[depth].dex_pc = GetDexPc();
Elliott Hughes530fa002012-03-12 11:44:49 -07003680 ++depth;
Elliott Hughes545a0642011-11-08 19:10:03 -08003681 }
Elliott Hughes530fa002012-03-12 11:44:49 -07003682 return true;
Elliott Hughes545a0642011-11-08 19:10:03 -08003683 }
3684
3685 ~AllocRecordStackVisitor() {
3686 // Clear out any unused stack trace elements.
3687 for (; depth < kMaxAllocRecordStackDepth; ++depth) {
3688 record->stack[depth].method = NULL;
Ian Rogers0399dde2012-06-06 17:09:28 -07003689 record->stack[depth].dex_pc = 0;
Elliott Hughes545a0642011-11-08 19:10:03 -08003690 }
3691 }
3692
3693 AllocRecord* record;
3694 size_t depth;
3695};
3696
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003697void Dbg::RecordAllocation(mirror::Class* type, size_t byte_count) {
Elliott Hughes545a0642011-11-08 19:10:03 -08003698 Thread* self = Thread::Current();
3699 CHECK(self != NULL);
3700
Ian Rogers50b35e22012-10-04 10:09:15 -07003701 MutexLock mu(self, gAllocTrackerLock);
Elliott Hughes545a0642011-11-08 19:10:03 -08003702 if (recent_allocation_records_ == NULL) {
3703 return;
3704 }
3705
3706 // Advance and clip.
Elliott Hughesb1a58792013-07-11 18:10:58 -07003707 if (++gAllocRecordHead == gAllocRecordMax) {
Elliott Hughes545a0642011-11-08 19:10:03 -08003708 gAllocRecordHead = 0;
3709 }
3710
3711 // Fill in the basics.
3712 AllocRecord* record = &recent_allocation_records_[gAllocRecordHead];
3713 record->type = type;
3714 record->byte_count = byte_count;
Ian Rogersd9c4fc92013-10-01 19:45:43 -07003715 record->thin_lock_id = self->GetThreadId();
Elliott Hughes545a0642011-11-08 19:10:03 -08003716
3717 // Fill in the stack trace.
Ian Rogers7a22fa62013-01-23 12:16:16 -08003718 AllocRecordStackVisitor visitor(self, record);
Ian Rogers0399dde2012-06-06 17:09:28 -07003719 visitor.WalkStack();
Elliott Hughes545a0642011-11-08 19:10:03 -08003720
Elliott Hughesb1a58792013-07-11 18:10:58 -07003721 if (gAllocRecordCount < gAllocRecordMax) {
Elliott Hughes545a0642011-11-08 19:10:03 -08003722 ++gAllocRecordCount;
3723 }
3724}
3725
Elliott Hughesa8f93cb2012-06-08 17:08:48 -07003726// Returns the index of the head element.
3727//
3728// We point at the most-recently-written record, so if gAllocRecordCount is 1
3729// we want to use the current element. Take "head+1" and subtract count
3730// from it.
3731//
3732// We need to handle underflow in our circular buffer, so we add
Elliott Hughesb1a58792013-07-11 18:10:58 -07003733// gAllocRecordMax and then mask it back down.
Elliott Hughesf8349362012-06-18 15:00:06 -07003734static inline int HeadIndex() EXCLUSIVE_LOCKS_REQUIRED(gAllocTrackerLock) {
Elliott Hughesb1a58792013-07-11 18:10:58 -07003735 return (gAllocRecordHead+1 + gAllocRecordMax - gAllocRecordCount) & (gAllocRecordMax-1);
Elliott Hughes545a0642011-11-08 19:10:03 -08003736}
3737
3738void Dbg::DumpRecentAllocations() {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07003739 ScopedObjectAccess soa(Thread::Current());
Ian Rogers50b35e22012-10-04 10:09:15 -07003740 MutexLock mu(soa.Self(), gAllocTrackerLock);
Elliott Hughes545a0642011-11-08 19:10:03 -08003741 if (recent_allocation_records_ == NULL) {
3742 LOG(INFO) << "Not recording tracked allocations";
3743 return;
3744 }
3745
3746 // "i" is the head of the list. We want to start at the end of the
3747 // list and move forward to the tail.
Elliott Hughesa8f93cb2012-06-08 17:08:48 -07003748 size_t i = HeadIndex();
Elliott Hughes545a0642011-11-08 19:10:03 -08003749 size_t count = gAllocRecordCount;
3750
3751 LOG(INFO) << "Tracked allocations, (head=" << gAllocRecordHead << " count=" << count << ")";
3752 while (count--) {
3753 AllocRecord* record = &recent_allocation_records_[i];
3754
Elliott Hughesa8f93cb2012-06-08 17:08:48 -07003755 LOG(INFO) << StringPrintf(" Thread %-2d %6zd bytes ", record->thin_lock_id, record->byte_count)
Elliott Hughes545a0642011-11-08 19:10:03 -08003756 << PrettyClass(record->type);
3757
3758 for (size_t stack_frame = 0; stack_frame < kMaxAllocRecordStackDepth; ++stack_frame) {
Ian Rogersef7d42f2014-01-06 12:55:46 -08003759 mirror::ArtMethod* m = record->stack[stack_frame].method;
Elliott Hughes545a0642011-11-08 19:10:03 -08003760 if (m == NULL) {
3761 break;
3762 }
3763 LOG(INFO) << " " << PrettyMethod(m) << " line " << record->stack[stack_frame].LineNumber();
3764 }
3765
3766 // pause periodically to help logcat catch up
3767 if ((count % 5) == 0) {
3768 usleep(40000);
3769 }
3770
Elliott Hughesb1a58792013-07-11 18:10:58 -07003771 i = (i + 1) & (gAllocRecordMax-1);
Elliott Hughes545a0642011-11-08 19:10:03 -08003772 }
3773}
3774
3775class StringTable {
3776 public:
3777 StringTable() {
3778 }
3779
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08003780 void Add(const char* s) {
Elliott Hughes545a0642011-11-08 19:10:03 -08003781 table_.insert(s);
3782 }
3783
Elliott Hughesa8f93cb2012-06-08 17:08:48 -07003784 size_t IndexOf(const char* s) const {
Mathieu Chartier02e25112013-08-14 16:14:24 -07003785 auto it = table_.find(s);
Elliott Hughesa8f93cb2012-06-08 17:08:48 -07003786 if (it == table_.end()) {
3787 LOG(FATAL) << "IndexOf(\"" << s << "\") failed";
3788 }
3789 return std::distance(table_.begin(), it);
Elliott Hughes545a0642011-11-08 19:10:03 -08003790 }
3791
Elliott Hughesa8f93cb2012-06-08 17:08:48 -07003792 size_t Size() const {
Elliott Hughes545a0642011-11-08 19:10:03 -08003793 return table_.size();
3794 }
3795
Elliott Hughesa8f93cb2012-06-08 17:08:48 -07003796 void WriteTo(std::vector<uint8_t>& bytes) const {
Mathieu Chartier02e25112013-08-14 16:14:24 -07003797 for (const std::string& str : table_) {
3798 const char* s = str.c_str();
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08003799 size_t s_len = CountModifiedUtf8Chars(s);
3800 UniquePtr<uint16_t> s_utf16(new uint16_t[s_len]);
3801 ConvertModifiedUtf8ToUtf16(s_utf16.get(), s);
3802 JDWP::AppendUtf16BE(bytes, s_utf16.get(), s_len);
Elliott Hughes545a0642011-11-08 19:10:03 -08003803 }
3804 }
3805
3806 private:
Elliott Hughesa8f93cb2012-06-08 17:08:48 -07003807 std::set<std::string> table_;
Elliott Hughes545a0642011-11-08 19:10:03 -08003808 DISALLOW_COPY_AND_ASSIGN(StringTable);
3809};
3810
3811/*
3812 * The data we send to DDMS contains everything we have recorded.
3813 *
3814 * Message header (all values big-endian):
3815 * (1b) message header len (to allow future expansion); includes itself
3816 * (1b) entry header len
3817 * (1b) stack frame len
3818 * (2b) number of entries
3819 * (4b) offset to string table from start of message
3820 * (2b) number of class name strings
3821 * (2b) number of method name strings
3822 * (2b) number of source file name strings
3823 * For each entry:
3824 * (4b) total allocation size
Elliott Hughes221229c2013-01-08 18:17:50 -08003825 * (2b) thread id
Elliott Hughes545a0642011-11-08 19:10:03 -08003826 * (2b) allocated object's class name index
3827 * (1b) stack depth
3828 * For each stack frame:
3829 * (2b) method's class name
3830 * (2b) method name
3831 * (2b) method source file
3832 * (2b) line number, clipped to 32767; -2 if native; -1 if no source
3833 * (xb) class name strings
3834 * (xb) method name strings
3835 * (xb) source file strings
3836 *
3837 * As with other DDM traffic, strings are sent as a 4-byte length
3838 * followed by UTF-16 data.
3839 *
3840 * We send up 16-bit unsigned indexes into string tables. In theory there
Elliott Hughesb1a58792013-07-11 18:10:58 -07003841 * can be (kMaxAllocRecordStackDepth * gAllocRecordMax) unique strings in
Elliott Hughes545a0642011-11-08 19:10:03 -08003842 * each table, but in practice there should be far fewer.
3843 *
3844 * The chief reason for using a string table here is to keep the size of
3845 * the DDMS message to a minimum. This is partly to make the protocol
3846 * efficient, but also because we have to form the whole thing up all at
3847 * once in a memory buffer.
3848 *
3849 * We use separate string tables for class names, method names, and source
3850 * files to keep the indexes small. There will generally be no overlap
3851 * between the contents of these tables.
3852 */
3853jbyteArray Dbg::GetRecentAllocations() {
3854 if (false) {
3855 DumpRecentAllocations();
3856 }
3857
Ian Rogers50b35e22012-10-04 10:09:15 -07003858 Thread* self = Thread::Current();
Elliott Hughes545a0642011-11-08 19:10:03 -08003859 std::vector<uint8_t> bytes;
Mathieu Chartier46e811b2013-07-10 17:09:14 -07003860 {
3861 MutexLock mu(self, gAllocTrackerLock);
3862 //
3863 // Part 1: generate string tables.
3864 //
3865 StringTable class_names;
3866 StringTable method_names;
3867 StringTable filenames;
Elliott Hughes545a0642011-11-08 19:10:03 -08003868
Mathieu Chartier46e811b2013-07-10 17:09:14 -07003869 int count = gAllocRecordCount;
3870 int idx = HeadIndex();
3871 while (count--) {
3872 AllocRecord* record = &recent_allocation_records_[idx];
Elliott Hughes545a0642011-11-08 19:10:03 -08003873
Mathieu Chartier46e811b2013-07-10 17:09:14 -07003874 class_names.Add(ClassHelper(record->type).GetDescriptor());
Elliott Hughes545a0642011-11-08 19:10:03 -08003875
Mathieu Chartier46e811b2013-07-10 17:09:14 -07003876 MethodHelper mh;
3877 for (size_t i = 0; i < kMaxAllocRecordStackDepth; i++) {
Brian Carlstromea46f952013-07-30 01:26:50 -07003878 mirror::ArtMethod* m = record->stack[i].method;
Mathieu Chartier46e811b2013-07-10 17:09:14 -07003879 if (m != NULL) {
3880 mh.ChangeMethod(m);
3881 class_names.Add(mh.GetDeclaringClassDescriptor());
3882 method_names.Add(mh.GetName());
3883 filenames.Add(mh.GetDeclaringClassSourceFile());
3884 }
3885 }
Elliott Hughes545a0642011-11-08 19:10:03 -08003886
Elliott Hughesb1a58792013-07-11 18:10:58 -07003887 idx = (idx + 1) & (gAllocRecordMax-1);
Elliott Hughes545a0642011-11-08 19:10:03 -08003888 }
3889
Mathieu Chartier46e811b2013-07-10 17:09:14 -07003890 LOG(INFO) << "allocation records: " << gAllocRecordCount;
3891
3892 //
3893 // Part 2: Generate the output and store it in the buffer.
3894 //
3895
3896 // (1b) message header len (to allow future expansion); includes itself
3897 // (1b) entry header len
3898 // (1b) stack frame len
3899 const int kMessageHeaderLen = 15;
3900 const int kEntryHeaderLen = 9;
3901 const int kStackFrameLen = 8;
3902 JDWP::Append1BE(bytes, kMessageHeaderLen);
3903 JDWP::Append1BE(bytes, kEntryHeaderLen);
3904 JDWP::Append1BE(bytes, kStackFrameLen);
3905
3906 // (2b) number of entries
3907 // (4b) offset to string table from start of message
3908 // (2b) number of class name strings
3909 // (2b) number of method name strings
3910 // (2b) number of source file name strings
3911 JDWP::Append2BE(bytes, gAllocRecordCount);
3912 size_t string_table_offset = bytes.size();
Brian Carlstrom7934ac22013-07-26 10:54:15 -07003913 JDWP::Append4BE(bytes, 0); // We'll patch this later...
Mathieu Chartier46e811b2013-07-10 17:09:14 -07003914 JDWP::Append2BE(bytes, class_names.Size());
3915 JDWP::Append2BE(bytes, method_names.Size());
3916 JDWP::Append2BE(bytes, filenames.Size());
3917
3918 count = gAllocRecordCount;
3919 idx = HeadIndex();
Mathieu Chartier46e811b2013-07-10 17:09:14 -07003920 while (count--) {
3921 // For each entry:
3922 // (4b) total allocation size
3923 // (2b) thread id
3924 // (2b) allocated object's class name index
3925 // (1b) stack depth
3926 AllocRecord* record = &recent_allocation_records_[idx];
3927 size_t stack_depth = record->GetDepth();
Mathieu Chartier590fee92013-09-13 13:46:47 -07003928 ClassHelper kh(record->type);
Mathieu Chartier46e811b2013-07-10 17:09:14 -07003929 size_t allocated_object_class_name_index = class_names.IndexOf(kh.GetDescriptor());
3930 JDWP::Append4BE(bytes, record->byte_count);
3931 JDWP::Append2BE(bytes, record->thin_lock_id);
3932 JDWP::Append2BE(bytes, allocated_object_class_name_index);
3933 JDWP::Append1BE(bytes, stack_depth);
3934
3935 MethodHelper mh;
3936 for (size_t stack_frame = 0; stack_frame < stack_depth; ++stack_frame) {
3937 // For each stack frame:
3938 // (2b) method's class name
3939 // (2b) method name
3940 // (2b) method source file
3941 // (2b) line number, clipped to 32767; -2 if native; -1 if no source
3942 mh.ChangeMethod(record->stack[stack_frame].method);
3943 size_t class_name_index = class_names.IndexOf(mh.GetDeclaringClassDescriptor());
3944 size_t method_name_index = method_names.IndexOf(mh.GetName());
3945 size_t file_name_index = filenames.IndexOf(mh.GetDeclaringClassSourceFile());
3946 JDWP::Append2BE(bytes, class_name_index);
3947 JDWP::Append2BE(bytes, method_name_index);
3948 JDWP::Append2BE(bytes, file_name_index);
3949 JDWP::Append2BE(bytes, record->stack[stack_frame].LineNumber());
3950 }
3951
Elliott Hughesb1a58792013-07-11 18:10:58 -07003952 idx = (idx + 1) & (gAllocRecordMax-1);
Mathieu Chartier46e811b2013-07-10 17:09:14 -07003953 }
3954
3955 // (xb) class name strings
3956 // (xb) method name strings
3957 // (xb) source file strings
3958 JDWP::Set4BE(&bytes[string_table_offset], bytes.size());
3959 class_names.WriteTo(bytes);
3960 method_names.WriteTo(bytes);
3961 filenames.WriteTo(bytes);
Elliott Hughes545a0642011-11-08 19:10:03 -08003962 }
Ian Rogers50b35e22012-10-04 10:09:15 -07003963 JNIEnv* env = self->GetJniEnv();
Elliott Hughes545a0642011-11-08 19:10:03 -08003964 jbyteArray result = env->NewByteArray(bytes.size());
3965 if (result != NULL) {
3966 env->SetByteArrayRegion(result, 0, bytes.size(), reinterpret_cast<const jbyte*>(&bytes[0]));
3967 }
3968 return result;
3969}
3970
Elliott Hughes872d4ec2011-10-21 17:07:15 -07003971} // namespace art