blob: bcf72671dd6701c60fe843a6eac288be8853f767 [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,
Brian Carlstromea46f952013-07-30 01:26:50 -0700104 const 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,
Brian Carlstromea46f952013-07-30 01:26:50 -0700114 const 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,
125 const mirror::ArtMethod* method, uint32_t dex_pc)
126 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,
Brian Carlstromea46f952013-07-30 01:26:50 -0700133 const 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
Elliott Hughes86964332012-02-15 19:37:42 -0800179// Breakpoints and single-stepping.
jeffhao09bfc6a2012-12-11 18:11:43 -0800180static std::vector<Breakpoint> gBreakpoints GUARDED_BY(Locks::breakpoint_lock_);
Elliott Hughes86964332012-02-15 19:37:42 -0800181
Brian Carlstromea46f952013-07-30 01:26:50 -0700182static bool IsBreakpoint(const mirror::ArtMethod* m, uint32_t dex_pc)
jeffhao09bfc6a2012-12-11 18:11:43 -0800183 LOCKS_EXCLUDED(Locks::breakpoint_lock_)
Ian Rogersb726dcb2012-09-05 08:57:23 -0700184 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
jeffhao09bfc6a2012-12-11 18:11:43 -0800185 MutexLock mu(Thread::Current(), *Locks::breakpoint_lock_);
Elliott Hughes86964332012-02-15 19:37:42 -0800186 for (size_t i = 0; i < gBreakpoints.size(); ++i) {
Elliott Hughesa656a0f2012-02-21 18:03:44 -0800187 if (gBreakpoints[i].method == m && gBreakpoints[i].dex_pc == dex_pc) {
Elliott Hughes86964332012-02-15 19:37:42 -0800188 VLOG(jdwp) << "Hit breakpoint #" << i << ": " << gBreakpoints[i];
189 return true;
190 }
191 }
192 return false;
193}
194
Elliott Hughes9e0c1752013-01-09 14:02:58 -0800195static bool IsSuspendedForDebugger(ScopedObjectAccessUnchecked& soa, Thread* thread) {
196 MutexLock mu(soa.Self(), *Locks::thread_suspend_count_lock_);
197 // A thread may be suspended for GC; in this code, we really want to know whether
198 // there's a debugger suspension active.
199 return thread->IsSuspended() && thread->GetDebugSuspendCount() > 0;
200}
201
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800202static mirror::Array* DecodeArray(JDWP::RefTypeId id, JDWP::JdwpError& status)
Ian Rogersb726dcb2012-09-05 08:57:23 -0700203 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800204 mirror::Object* o = gRegistry->Get<mirror::Object*>(id);
Elliott Hughes64f574f2013-02-20 14:57:12 -0800205 if (o == NULL || o == ObjectRegistry::kInvalidObject) {
Elliott Hughes436e3722012-02-17 20:01:47 -0800206 status = JDWP::ERR_INVALID_OBJECT;
207 return NULL;
208 }
209 if (!o->IsArrayInstance()) {
210 status = JDWP::ERR_INVALID_ARRAY;
211 return NULL;
212 }
213 status = JDWP::ERR_NONE;
214 return o->AsArray();
215}
216
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800217static mirror::Class* DecodeClass(JDWP::RefTypeId id, JDWP::JdwpError& status)
Ian Rogersb726dcb2012-09-05 08:57:23 -0700218 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800219 mirror::Object* o = gRegistry->Get<mirror::Object*>(id);
Elliott Hughes64f574f2013-02-20 14:57:12 -0800220 if (o == NULL || o == ObjectRegistry::kInvalidObject) {
Elliott Hughes436e3722012-02-17 20:01:47 -0800221 status = JDWP::ERR_INVALID_OBJECT;
222 return NULL;
223 }
224 if (!o->IsClass()) {
225 status = JDWP::ERR_INVALID_CLASS;
226 return NULL;
227 }
228 status = JDWP::ERR_NONE;
229 return o->AsClass();
230}
231
Elliott Hughes221229c2013-01-08 18:17:50 -0800232static JDWP::JdwpError DecodeThread(ScopedObjectAccessUnchecked& soa, JDWP::ObjectId thread_id, Thread*& thread)
jeffhaoa77f0f62012-12-05 17:19:31 -0800233 EXCLUSIVE_LOCKS_REQUIRED(Locks::thread_list_lock_)
Ian Rogersb726dcb2012-09-05 08:57:23 -0700234 LOCKS_EXCLUDED(Locks::thread_suspend_count_lock_)
235 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800236 mirror::Object* thread_peer = gRegistry->Get<mirror::Object*>(thread_id);
Elliott Hughes64f574f2013-02-20 14:57:12 -0800237 if (thread_peer == NULL || thread_peer == ObjectRegistry::kInvalidObject) {
Elliott Hughes221229c2013-01-08 18:17:50 -0800238 // This isn't even an object.
239 return JDWP::ERR_INVALID_OBJECT;
Elliott Hughes436e3722012-02-17 20:01:47 -0800240 }
Elliott Hughes221229c2013-01-08 18:17:50 -0800241
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800242 mirror::Class* java_lang_Thread = soa.Decode<mirror::Class*>(WellKnownClasses::java_lang_Thread);
Elliott Hughes221229c2013-01-08 18:17:50 -0800243 if (!java_lang_Thread->IsAssignableFrom(thread_peer->GetClass())) {
244 // This isn't a thread.
245 return JDWP::ERR_INVALID_THREAD;
246 }
247
248 thread = Thread::FromManagedThread(soa, thread_peer);
249 if (thread == NULL) {
250 // This is a java.lang.Thread without a Thread*. Must be a zombie.
251 return JDWP::ERR_THREAD_NOT_ALIVE;
252 }
253 return JDWP::ERR_NONE;
Elliott Hughes436e3722012-02-17 20:01:47 -0800254}
255
Elliott Hughes24437992011-11-30 14:49:33 -0800256static JDWP::JdwpTag BasicTagFromDescriptor(const char* descriptor) {
257 // JDWP deliberately uses the descriptor characters' ASCII values for its enum.
258 // Note that by "basic" we mean that we don't get more specific than JT_OBJECT.
259 return static_cast<JDWP::JdwpTag>(descriptor[0]);
260}
261
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800262static JDWP::JdwpTag TagFromClass(mirror::Class* c)
Ian Rogersb726dcb2012-09-05 08:57:23 -0700263 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Elliott Hughes86b00102011-12-05 17:54:26 -0800264 CHECK(c != NULL);
Elliott Hughes24437992011-11-30 14:49:33 -0800265 if (c->IsArrayClass()) {
266 return JDWP::JT_ARRAY;
267 }
268
Elliott Hughes3d30d9b2011-12-07 17:35:48 -0800269 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
Elliott Hughes24437992011-11-30 14:49:33 -0800270 if (c->IsStringClass()) {
271 return JDWP::JT_STRING;
272 } else if (c->IsClassClass()) {
273 return JDWP::JT_CLASS_OBJECT;
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -0800274 } else if (class_linker->FindSystemClass("Ljava/lang/Thread;")->IsAssignableFrom(c)) {
Elliott Hughes24437992011-11-30 14:49:33 -0800275 return JDWP::JT_THREAD;
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -0800276 } else if (class_linker->FindSystemClass("Ljava/lang/ThreadGroup;")->IsAssignableFrom(c)) {
Elliott Hughes24437992011-11-30 14:49:33 -0800277 return JDWP::JT_THREAD_GROUP;
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -0800278 } else if (class_linker->FindSystemClass("Ljava/lang/ClassLoader;")->IsAssignableFrom(c)) {
Elliott Hughes24437992011-11-30 14:49:33 -0800279 return JDWP::JT_CLASS_LOADER;
Elliott Hughes24437992011-11-30 14:49:33 -0800280 } else {
281 return JDWP::JT_OBJECT;
282 }
283}
284
285/*
286 * Objects declared to hold Object might actually hold a more specific
287 * type. The debugger may take a special interest in these (e.g. it
288 * wants to display the contents of Strings), so we want to return an
289 * appropriate tag.
290 *
291 * Null objects are tagged JT_OBJECT.
292 */
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800293static JDWP::JdwpTag TagFromObject(const mirror::Object* o)
Ian Rogersb726dcb2012-09-05 08:57:23 -0700294 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Elliott Hughes24437992011-11-30 14:49:33 -0800295 return (o == NULL) ? JDWP::JT_OBJECT : TagFromClass(o->GetClass());
296}
297
298static bool IsPrimitiveTag(JDWP::JdwpTag tag) {
299 switch (tag) {
300 case JDWP::JT_BOOLEAN:
301 case JDWP::JT_BYTE:
302 case JDWP::JT_CHAR:
303 case JDWP::JT_FLOAT:
304 case JDWP::JT_DOUBLE:
305 case JDWP::JT_INT:
306 case JDWP::JT_LONG:
307 case JDWP::JT_SHORT:
308 case JDWP::JT_VOID:
309 return true;
310 default:
311 return false;
312 }
313}
314
Elliott Hughes3bb81562011-10-21 18:52:59 -0700315/*
316 * Handle one of the JDWP name/value pairs.
317 *
318 * JDWP options are:
319 * help: if specified, show help message and bail
320 * transport: may be dt_socket or dt_shmem
321 * address: for dt_socket, "host:port", or just "port" when listening
322 * server: if "y", wait for debugger to attach; if "n", attach to debugger
323 * timeout: how long to wait for debugger to connect / listen
324 *
325 * Useful with server=n (these aren't supported yet):
326 * onthrow=<exception-name>: connect to debugger when exception thrown
327 * onuncaught=y|n: connect to debugger when uncaught exception thrown
328 * launch=<command-line>: launch the debugger itself
329 *
330 * The "transport" option is required, as is "address" if server=n.
331 */
332static bool ParseJdwpOption(const std::string& name, const std::string& value) {
333 if (name == "transport") {
334 if (value == "dt_socket") {
Elliott Hughes376a7a02011-10-24 18:35:55 -0700335 gJdwpOptions.transport = JDWP::kJdwpTransportSocket;
Elliott Hughes3bb81562011-10-21 18:52:59 -0700336 } else if (value == "dt_android_adb") {
Elliott Hughes376a7a02011-10-24 18:35:55 -0700337 gJdwpOptions.transport = JDWP::kJdwpTransportAndroidAdb;
Elliott Hughes3bb81562011-10-21 18:52:59 -0700338 } else {
339 LOG(ERROR) << "JDWP transport not supported: " << value;
340 return false;
341 }
342 } else if (name == "server") {
343 if (value == "n") {
Elliott Hughes376a7a02011-10-24 18:35:55 -0700344 gJdwpOptions.server = false;
Elliott Hughes3bb81562011-10-21 18:52:59 -0700345 } else if (value == "y") {
Elliott Hughes376a7a02011-10-24 18:35:55 -0700346 gJdwpOptions.server = true;
Elliott Hughes3bb81562011-10-21 18:52:59 -0700347 } else {
348 LOG(ERROR) << "JDWP option 'server' must be 'y' or 'n'";
349 return false;
350 }
351 } else if (name == "suspend") {
352 if (value == "n") {
Elliott Hughes376a7a02011-10-24 18:35:55 -0700353 gJdwpOptions.suspend = false;
Elliott Hughes3bb81562011-10-21 18:52:59 -0700354 } else if (value == "y") {
Elliott Hughes376a7a02011-10-24 18:35:55 -0700355 gJdwpOptions.suspend = true;
Elliott Hughes3bb81562011-10-21 18:52:59 -0700356 } else {
357 LOG(ERROR) << "JDWP option 'suspend' must be 'y' or 'n'";
358 return false;
359 }
360 } else if (name == "address") {
361 /* this is either <port> or <host>:<port> */
362 std::string port_string;
Elliott Hughes376a7a02011-10-24 18:35:55 -0700363 gJdwpOptions.host.clear();
Elliott Hughes3bb81562011-10-21 18:52:59 -0700364 std::string::size_type colon = value.find(':');
365 if (colon != std::string::npos) {
Elliott Hughes376a7a02011-10-24 18:35:55 -0700366 gJdwpOptions.host = value.substr(0, colon);
Elliott Hughes3bb81562011-10-21 18:52:59 -0700367 port_string = value.substr(colon + 1);
368 } else {
369 port_string = value;
370 }
371 if (port_string.empty()) {
372 LOG(ERROR) << "JDWP address missing port: " << value;
373 return false;
374 }
375 char* end;
Elliott Hughesba8eee12012-01-24 20:25:24 -0800376 uint64_t port = strtoul(port_string.c_str(), &end, 10);
377 if (*end != '\0' || port > 0xffff) {
Elliott Hughes3bb81562011-10-21 18:52:59 -0700378 LOG(ERROR) << "JDWP address has junk in port field: " << value;
379 return false;
380 }
Elliott Hughes376a7a02011-10-24 18:35:55 -0700381 gJdwpOptions.port = port;
Elliott Hughes3bb81562011-10-21 18:52:59 -0700382 } else if (name == "launch" || name == "onthrow" || name == "oncaught" || name == "timeout") {
383 /* valid but unsupported */
384 LOG(INFO) << "Ignoring JDWP option '" << name << "'='" << value << "'";
385 } else {
386 LOG(INFO) << "Ignoring unrecognized JDWP option '" << name << "'='" << value << "'";
387 }
388
389 return true;
390}
391
392/*
393 * Parse the latter half of a -Xrunjdwp/-agentlib:jdwp= string, e.g.:
394 * "transport=dt_socket,address=8000,server=y,suspend=n"
395 */
396bool Dbg::ParseJdwpOptions(const std::string& options) {
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -0800397 VLOG(jdwp) << "ParseJdwpOptions: " << options;
Elliott Hughes47fce012011-10-25 18:37:19 -0700398
Elliott Hughes3bb81562011-10-21 18:52:59 -0700399 std::vector<std::string> pairs;
400 Split(options, ',', pairs);
401
402 for (size_t i = 0; i < pairs.size(); ++i) {
403 std::string::size_type equals = pairs[i].find('=');
404 if (equals == std::string::npos) {
405 LOG(ERROR) << "Can't parse JDWP option '" << pairs[i] << "' in '" << options << "'";
406 return false;
407 }
408 ParseJdwpOption(pairs[i].substr(0, equals), pairs[i].substr(equals + 1));
409 }
410
Elliott Hughes376a7a02011-10-24 18:35:55 -0700411 if (gJdwpOptions.transport == JDWP::kJdwpTransportUnknown) {
Elliott Hughes3bb81562011-10-21 18:52:59 -0700412 LOG(ERROR) << "Must specify JDWP transport: " << options;
413 }
Elliott Hughes376a7a02011-10-24 18:35:55 -0700414 if (!gJdwpOptions.server && (gJdwpOptions.host.empty() || gJdwpOptions.port == 0)) {
Elliott Hughes3bb81562011-10-21 18:52:59 -0700415 LOG(ERROR) << "Must specify JDWP host and port when server=n: " << options;
416 return false;
417 }
418
419 gJdwpConfigured = true;
420 return true;
421}
422
Elliott Hughesd1cc8362011-10-24 16:58:50 -0700423void Dbg::StartJdwp() {
Elliott Hughesc0f09332012-03-26 13:27:06 -0700424 if (!gJdwpAllowed || !IsJdwpConfigured()) {
Elliott Hughes376a7a02011-10-24 18:35:55 -0700425 // No JDWP for you!
426 return;
427 }
428
Elliott Hughes475fc232011-10-25 15:00:35 -0700429 CHECK(gRegistry == NULL);
430 gRegistry = new ObjectRegistry;
431
Elliott Hughesd1cc8362011-10-24 16:58:50 -0700432 // Init JDWP if the debugger is enabled. This may connect out to a
433 // debugger, passively listen for a debugger, or block waiting for a
434 // debugger.
Elliott Hughes376a7a02011-10-24 18:35:55 -0700435 gJdwpState = JDWP::JdwpState::Create(&gJdwpOptions);
436 if (gJdwpState == NULL) {
Elliott Hughesf8a2df72011-12-01 12:19:54 -0800437 // We probably failed because some other process has the port already, which means that
438 // if we don't abort the user is likely to think they're talking to us when they're actually
439 // talking to that other process.
Elliott Hughes3d30d9b2011-12-07 17:35:48 -0800440 LOG(FATAL) << "Debugger thread failed to initialize";
Elliott Hughesd1cc8362011-10-24 16:58:50 -0700441 }
442
443 // If a debugger has already attached, send the "welcome" message.
444 // This may cause us to suspend all threads.
Elliott Hughes376a7a02011-10-24 18:35:55 -0700445 if (gJdwpState->IsActive()) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700446 ScopedObjectAccess soa(Thread::Current());
Elliott Hughes376a7a02011-10-24 18:35:55 -0700447 if (!gJdwpState->PostVMStart()) {
Elliott Hughes3d30d9b2011-12-07 17:35:48 -0800448 LOG(WARNING) << "Failed to post 'start' message to debugger";
Elliott Hughesd1cc8362011-10-24 16:58:50 -0700449 }
450 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700451}
452
Elliott Hughesd1cc8362011-10-24 16:58:50 -0700453void Dbg::StopJdwp() {
Elliott Hughes376a7a02011-10-24 18:35:55 -0700454 delete gJdwpState;
Sebastien Hertz123756a2013-11-27 15:49:42 +0100455 gJdwpState = NULL;
Elliott Hughes475fc232011-10-25 15:00:35 -0700456 delete gRegistry;
457 gRegistry = NULL;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700458}
459
Elliott Hughes767a1472011-10-26 18:49:02 -0700460void Dbg::GcDidFinish() {
461 if (gDdmHpifWhen != HPIF_WHEN_NEVER) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700462 ScopedObjectAccess soa(Thread::Current());
Elliott Hughes81ff3182012-03-23 20:35:56 -0700463 LOG(DEBUG) << "Sending heap info to DDM";
Elliott Hughes7162ad92011-10-27 14:08:42 -0700464 DdmSendHeapInfo(gDdmHpifWhen);
Elliott Hughes767a1472011-10-26 18:49:02 -0700465 }
466 if (gDdmHpsgWhen != HPSG_WHEN_NEVER) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700467 ScopedObjectAccess soa(Thread::Current());
Elliott Hughes81ff3182012-03-23 20:35:56 -0700468 LOG(DEBUG) << "Dumping heap to DDM";
Elliott Hughes6a5bd492011-10-28 14:33:57 -0700469 DdmSendHeapSegments(false);
Elliott Hughes767a1472011-10-26 18:49:02 -0700470 }
471 if (gDdmNhsgWhen != HPSG_WHEN_NEVER) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700472 ScopedObjectAccess soa(Thread::Current());
Elliott Hughes767a1472011-10-26 18:49:02 -0700473 LOG(DEBUG) << "Dumping native heap to DDM";
Elliott Hughes6a5bd492011-10-28 14:33:57 -0700474 DdmSendHeapSegments(true);
Elliott Hughes767a1472011-10-26 18:49:02 -0700475 }
476}
477
Elliott Hughes4ffd3132011-10-24 12:06:42 -0700478void Dbg::SetJdwpAllowed(bool allowed) {
479 gJdwpAllowed = allowed;
480}
481
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700482DebugInvokeReq* Dbg::GetInvokeReq() {
Elliott Hughes475fc232011-10-25 15:00:35 -0700483 return Thread::Current()->GetInvokeReq();
484}
485
486Thread* Dbg::GetDebugThread() {
487 return (gJdwpState != NULL) ? gJdwpState->GetDebugThread() : NULL;
488}
489
490void Dbg::ClearWaitForEventThread() {
491 gJdwpState->ClearWaitForEventThread();
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700492}
493
494void Dbg::Connected() {
Elliott Hughes3bb81562011-10-21 18:52:59 -0700495 CHECK(!gDebuggerConnected);
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -0800496 VLOG(jdwp) << "JDWP has attached";
Elliott Hughes3bb81562011-10-21 18:52:59 -0700497 gDebuggerConnected = true;
Elliott Hughes86964332012-02-15 19:37:42 -0800498 gDisposed = false;
499}
500
501void Dbg::Disposed() {
502 gDisposed = true;
503}
504
505bool Dbg::IsDisposed() {
506 return gDisposed;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700507}
508
Elliott Hughesa2155262011-11-16 16:26:58 -0800509void Dbg::GoActive() {
510 // Enable all debugging features, including scans for breakpoints.
511 // This is a no-op if we're already active.
512 // Only called from the JDWP handler thread.
513 if (gDebuggerActive) {
514 return;
515 }
516
Elliott Hughesc0f09332012-03-26 13:27:06 -0700517 {
518 // TODO: dalvik only warned if there were breakpoints left over. clear in Dbg::Disconnected?
jeffhao09bfc6a2012-12-11 18:11:43 -0800519 MutexLock mu(Thread::Current(), *Locks::breakpoint_lock_);
Elliott Hughesc0f09332012-03-26 13:27:06 -0700520 CHECK_EQ(gBreakpoints.size(), 0U);
521 }
Elliott Hughesa2155262011-11-16 16:26:58 -0800522
Ian Rogers62d6c772013-02-27 08:32:07 -0800523 Runtime* runtime = Runtime::Current();
524 runtime->GetThreadList()->SuspendAll();
525 Thread* self = Thread::Current();
526 ThreadState old_state = self->SetStateUnsafe(kRunnable);
527 CHECK_NE(old_state, kRunnable);
528 runtime->GetInstrumentation()->AddListener(&gDebugInstrumentationListener,
529 instrumentation::Instrumentation::kMethodEntered |
530 instrumentation::Instrumentation::kMethodExited |
Jeff Hao14dd5a82013-04-11 10:23:36 -0700531 instrumentation::Instrumentation::kDexPcMoved |
532 instrumentation::Instrumentation::kExceptionCaught);
Elliott Hughesa2155262011-11-16 16:26:58 -0800533 gDebuggerActive = true;
Ian Rogers62d6c772013-02-27 08:32:07 -0800534 CHECK_EQ(self->SetStateUnsafe(old_state), kRunnable);
535 runtime->GetThreadList()->ResumeAll();
536
537 LOG(INFO) << "Debugger is active";
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700538}
539
540void Dbg::Disconnected() {
Elliott Hughes234ab152011-10-26 14:02:26 -0700541 CHECK(gDebuggerConnected);
542
Elliott Hughesc0f09332012-03-26 13:27:06 -0700543 LOG(INFO) << "Debugger is no longer active";
Elliott Hughes234ab152011-10-26 14:02:26 -0700544
Ian Rogers62d6c772013-02-27 08:32:07 -0800545 // Suspend all threads and exclusively acquire the mutator lock. Set the state of the thread
546 // to kRunnable to avoid scoped object access transitions. Remove the debugger as a listener
547 // and clear the object registry.
548 Runtime* runtime = Runtime::Current();
549 runtime->GetThreadList()->SuspendAll();
550 Thread* self = Thread::Current();
551 ThreadState old_state = self->SetStateUnsafe(kRunnable);
552 runtime->GetInstrumentation()->RemoveListener(&gDebugInstrumentationListener,
553 instrumentation::Instrumentation::kMethodEntered |
554 instrumentation::Instrumentation::kMethodExited |
Jeff Hao14dd5a82013-04-11 10:23:36 -0700555 instrumentation::Instrumentation::kDexPcMoved |
556 instrumentation::Instrumentation::kExceptionCaught);
Elliott Hughesc0f09332012-03-26 13:27:06 -0700557 gDebuggerActive = false;
Elliott Hughes234ab152011-10-26 14:02:26 -0700558 gRegistry->Clear();
559 gDebuggerConnected = false;
Ian Rogers62d6c772013-02-27 08:32:07 -0800560 CHECK_EQ(self->SetStateUnsafe(old_state), kRunnable);
561 runtime->GetThreadList()->ResumeAll();
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700562}
563
Elliott Hughesc0f09332012-03-26 13:27:06 -0700564bool Dbg::IsDebuggerActive() {
Elliott Hughes3bb81562011-10-21 18:52:59 -0700565 return gDebuggerActive;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700566}
567
Elliott Hughesc0f09332012-03-26 13:27:06 -0700568bool Dbg::IsJdwpConfigured() {
Elliott Hughes3bb81562011-10-21 18:52:59 -0700569 return gJdwpConfigured;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700570}
571
572int64_t Dbg::LastDebuggerActivity() {
Elliott Hughesca951522011-12-05 12:01:32 -0800573 return gJdwpState->LastDebuggerActivity();
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700574}
575
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700576void Dbg::UndoDebuggerSuspensions() {
Elliott Hughes234ab152011-10-26 14:02:26 -0700577 Runtime::Current()->GetThreadList()->UndoDebuggerSuspensions();
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700578}
579
Elliott Hughes88d63092013-01-09 09:55:54 -0800580std::string Dbg::GetClassName(JDWP::RefTypeId class_id) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800581 mirror::Object* o = gRegistry->Get<mirror::Object*>(class_id);
Elliott Hughes436e3722012-02-17 20:01:47 -0800582 if (o == NULL) {
583 return "NULL";
584 }
Elliott Hughes64f574f2013-02-20 14:57:12 -0800585 if (o == ObjectRegistry::kInvalidObject) {
Elliott Hughes88d63092013-01-09 09:55:54 -0800586 return StringPrintf("invalid object %p", reinterpret_cast<void*>(class_id));
Elliott Hughes436e3722012-02-17 20:01:47 -0800587 }
588 if (!o->IsClass()) {
Brian Carlstrom7934ac22013-07-26 10:54:15 -0700589 return StringPrintf("non-class %p", o); // This is only used for debugging output anyway.
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -0800590 }
Elliott Hughesc308a5d2012-02-16 17:12:06 -0800591 return DescriptorToName(ClassHelper(o->AsClass()).GetDescriptor());
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700592}
593
Elliott Hughes88d63092013-01-09 09:55:54 -0800594JDWP::JdwpError Dbg::GetClassObject(JDWP::RefTypeId id, JDWP::ObjectId& class_object_id) {
Elliott Hughes436e3722012-02-17 20:01:47 -0800595 JDWP::JdwpError status;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800596 mirror::Class* c = DecodeClass(id, status);
Elliott Hughes436e3722012-02-17 20:01:47 -0800597 if (c == NULL) {
598 return status;
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -0800599 }
Elliott Hughes88d63092013-01-09 09:55:54 -0800600 class_object_id = gRegistry->Add(c);
Elliott Hughes436e3722012-02-17 20:01:47 -0800601 return JDWP::ERR_NONE;
Elliott Hughes86964332012-02-15 19:37:42 -0800602}
603
Elliott Hughes88d63092013-01-09 09:55:54 -0800604JDWP::JdwpError Dbg::GetSuperclass(JDWP::RefTypeId id, JDWP::RefTypeId& superclass_id) {
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -0800605 JDWP::JdwpError status;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800606 mirror::Class* c = DecodeClass(id, status);
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -0800607 if (c == NULL) {
608 return status;
609 }
610 if (c->IsInterface()) {
611 // http://code.google.com/p/android/issues/detail?id=20856
Elliott Hughes88d63092013-01-09 09:55:54 -0800612 superclass_id = 0;
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -0800613 } else {
Elliott Hughes88d63092013-01-09 09:55:54 -0800614 superclass_id = gRegistry->Add(c->GetSuperClass());
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -0800615 }
616 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700617}
618
Elliott Hughes436e3722012-02-17 20:01:47 -0800619JDWP::JdwpError Dbg::GetClassLoader(JDWP::RefTypeId id, JDWP::ExpandBuf* pReply) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800620 mirror::Object* o = gRegistry->Get<mirror::Object*>(id);
Elliott Hughes64f574f2013-02-20 14:57:12 -0800621 if (o == NULL || o == ObjectRegistry::kInvalidObject) {
Elliott Hughes436e3722012-02-17 20:01:47 -0800622 return JDWP::ERR_INVALID_OBJECT;
623 }
624 expandBufAddObjectId(pReply, gRegistry->Add(o->GetClass()->GetClassLoader()));
625 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700626}
627
Elliott Hughes436e3722012-02-17 20:01:47 -0800628JDWP::JdwpError Dbg::GetModifiers(JDWP::RefTypeId id, JDWP::ExpandBuf* pReply) {
629 JDWP::JdwpError status;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800630 mirror::Class* c = DecodeClass(id, status);
Elliott Hughes436e3722012-02-17 20:01:47 -0800631 if (c == NULL) {
632 return status;
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -0800633 }
Elliott Hughes436e3722012-02-17 20:01:47 -0800634
635 uint32_t access_flags = c->GetAccessFlags() & kAccJavaFlagsMask;
636
637 // Set ACC_SUPER; dex files don't contain this flag, but all classes are supposed to have it set.
638 // Class.getModifiers doesn't return it, but JDWP does, so we set it here.
639 access_flags |= kAccSuper;
640
641 expandBufAdd4BE(pReply, access_flags);
642
643 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700644}
645
Elliott Hughesf327e072013-01-09 16:01:26 -0800646JDWP::JdwpError Dbg::GetMonitorInfo(JDWP::ObjectId object_id, JDWP::ExpandBuf* reply)
647 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800648 mirror::Object* o = gRegistry->Get<mirror::Object*>(object_id);
Elliott Hughes64f574f2013-02-20 14:57:12 -0800649 if (o == NULL || o == ObjectRegistry::kInvalidObject) {
Elliott Hughesf327e072013-01-09 16:01:26 -0800650 return JDWP::ERR_INVALID_OBJECT;
651 }
652
653 // Ensure all threads are suspended while we read objects' lock words.
654 Thread* self = Thread::Current();
655 Locks::mutator_lock_->SharedUnlock(self);
656 Locks::mutator_lock_->ExclusiveLock(self);
657
658 MonitorInfo monitor_info(o);
659
660 Locks::mutator_lock_->ExclusiveUnlock(self);
661 Locks::mutator_lock_->SharedLock(self);
662
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700663 if (monitor_info.owner_ != NULL) {
664 expandBufAddObjectId(reply, gRegistry->Add(monitor_info.owner_->GetPeer()));
Elliott Hughesf327e072013-01-09 16:01:26 -0800665 } else {
666 expandBufAddObjectId(reply, gRegistry->Add(NULL));
667 }
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700668 expandBufAdd4BE(reply, monitor_info.entry_count_);
669 expandBufAdd4BE(reply, monitor_info.waiters_.size());
670 for (size_t i = 0; i < monitor_info.waiters_.size(); ++i) {
671 expandBufAddObjectId(reply, gRegistry->Add(monitor_info.waiters_[i]->GetPeer()));
Elliott Hughesf327e072013-01-09 16:01:26 -0800672 }
673 return JDWP::ERR_NONE;
674}
675
Elliott Hughes734b8c62013-01-11 15:32:45 -0800676JDWP::JdwpError Dbg::GetOwnedMonitors(JDWP::ObjectId thread_id,
677 std::vector<JDWP::ObjectId>& monitors,
678 std::vector<uint32_t>& stack_depths)
Elliott Hughes4993bbc2013-01-10 15:41:25 -0800679 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
680 ScopedObjectAccessUnchecked soa(Thread::Current());
681 MutexLock mu(soa.Self(), *Locks::thread_list_lock_);
682 Thread* thread;
683 JDWP::JdwpError error = DecodeThread(soa, thread_id, thread);
684 if (error != JDWP::ERR_NONE) {
685 return error;
686 }
687 if (!IsSuspendedForDebugger(soa, thread)) {
688 return JDWP::ERR_THREAD_NOT_SUSPENDED;
689 }
690
691 struct OwnedMonitorVisitor : public StackVisitor {
Ian Rogers7a22fa62013-01-23 12:16:16 -0800692 OwnedMonitorVisitor(Thread* thread, Context* context)
Elliott Hughes4993bbc2013-01-10 15:41:25 -0800693 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_)
Ian Rogers7a22fa62013-01-23 12:16:16 -0800694 : StackVisitor(thread, context), current_stack_depth(0) {}
Elliott Hughes4993bbc2013-01-10 15:41:25 -0800695
696 // TODO: Enable annotalysis. We know lock is held in constructor, but abstraction confuses
697 // annotalysis.
698 bool VisitFrame() NO_THREAD_SAFETY_ANALYSIS {
699 if (!GetMethod()->IsRuntimeMethod()) {
700 Monitor::VisitLocks(this, AppendOwnedMonitors, this);
Elliott Hughes734b8c62013-01-11 15:32:45 -0800701 ++current_stack_depth;
Elliott Hughes4993bbc2013-01-10 15:41:25 -0800702 }
703 return true;
704 }
705
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800706 static void AppendOwnedMonitors(mirror::Object* owned_monitor, void* arg) {
Ian Rogers7a22fa62013-01-23 12:16:16 -0800707 OwnedMonitorVisitor* visitor = reinterpret_cast<OwnedMonitorVisitor*>(arg);
Elliott Hughes734b8c62013-01-11 15:32:45 -0800708 visitor->monitors.push_back(owned_monitor);
709 visitor->stack_depths.push_back(visitor->current_stack_depth);
Elliott Hughes4993bbc2013-01-10 15:41:25 -0800710 }
711
Elliott Hughes734b8c62013-01-11 15:32:45 -0800712 size_t current_stack_depth;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800713 std::vector<mirror::Object*> monitors;
Elliott Hughes734b8c62013-01-11 15:32:45 -0800714 std::vector<uint32_t> stack_depths;
Elliott Hughes4993bbc2013-01-10 15:41:25 -0800715 };
Ian Rogers7a22fa62013-01-23 12:16:16 -0800716 UniquePtr<Context> context(Context::Create());
717 OwnedMonitorVisitor visitor(thread, context.get());
Elliott Hughes4993bbc2013-01-10 15:41:25 -0800718 visitor.WalkStack();
719
720 for (size_t i = 0; i < visitor.monitors.size(); ++i) {
721 monitors.push_back(gRegistry->Add(visitor.monitors[i]));
Elliott Hughes734b8c62013-01-11 15:32:45 -0800722 stack_depths.push_back(visitor.stack_depths[i]);
Elliott Hughes4993bbc2013-01-10 15:41:25 -0800723 }
724
725 return JDWP::ERR_NONE;
726}
727
Elliott Hughesf9501702013-01-11 11:22:27 -0800728JDWP::JdwpError Dbg::GetContendedMonitor(JDWP::ObjectId thread_id, JDWP::ObjectId& contended_monitor)
729 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
730 ScopedObjectAccessUnchecked soa(Thread::Current());
731 MutexLock mu(soa.Self(), *Locks::thread_list_lock_);
732 Thread* thread;
733 JDWP::JdwpError error = DecodeThread(soa, thread_id, thread);
734 if (error != JDWP::ERR_NONE) {
735 return error;
736 }
737 if (!IsSuspendedForDebugger(soa, thread)) {
738 return JDWP::ERR_THREAD_NOT_SUSPENDED;
739 }
740
741 contended_monitor = gRegistry->Add(Monitor::GetContendedMonitor(thread));
742
743 return JDWP::ERR_NONE;
744}
745
Elliott Hughesec0f83d2013-01-15 16:54:08 -0800746JDWP::JdwpError Dbg::GetInstanceCounts(const std::vector<JDWP::RefTypeId>& class_ids,
747 std::vector<uint64_t>& counts)
748 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800749 std::vector<mirror::Class*> classes;
Elliott Hughesec0f83d2013-01-15 16:54:08 -0800750 counts.clear();
751 for (size_t i = 0; i < class_ids.size(); ++i) {
752 JDWP::JdwpError status;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800753 mirror::Class* c = DecodeClass(class_ids[i], status);
Elliott Hughesec0f83d2013-01-15 16:54:08 -0800754 if (c == NULL) {
755 return status;
756 }
757 classes.push_back(c);
758 counts.push_back(0);
759 }
760
761 Runtime::Current()->GetHeap()->CountInstances(classes, false, &counts[0]);
762 return JDWP::ERR_NONE;
763}
764
Elliott Hughes3b78c942013-01-15 17:35:41 -0800765JDWP::JdwpError Dbg::GetInstances(JDWP::RefTypeId class_id, int32_t max_count, std::vector<JDWP::ObjectId>& instances)
766 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
767 JDWP::JdwpError status;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800768 mirror::Class* c = DecodeClass(class_id, status);
Elliott Hughes3b78c942013-01-15 17:35:41 -0800769 if (c == NULL) {
770 return status;
771 }
772
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800773 std::vector<mirror::Object*> raw_instances;
Elliott Hughes3b78c942013-01-15 17:35:41 -0800774 Runtime::Current()->GetHeap()->GetInstances(c, max_count, raw_instances);
775 for (size_t i = 0; i < raw_instances.size(); ++i) {
776 instances.push_back(gRegistry->Add(raw_instances[i]));
777 }
778 return JDWP::ERR_NONE;
779}
780
Elliott Hughes0cbaff52013-01-16 15:28:01 -0800781JDWP::JdwpError Dbg::GetReferringObjects(JDWP::ObjectId object_id, int32_t max_count,
782 std::vector<JDWP::ObjectId>& referring_objects)
783 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800784 mirror::Object* o = gRegistry->Get<mirror::Object*>(object_id);
Elliott Hughes64f574f2013-02-20 14:57:12 -0800785 if (o == NULL || o == ObjectRegistry::kInvalidObject) {
Elliott Hughes0cbaff52013-01-16 15:28:01 -0800786 return JDWP::ERR_INVALID_OBJECT;
787 }
788
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800789 std::vector<mirror::Object*> raw_instances;
Elliott Hughes0cbaff52013-01-16 15:28:01 -0800790 Runtime::Current()->GetHeap()->GetReferringObjects(o, max_count, raw_instances);
791 for (size_t i = 0; i < raw_instances.size(); ++i) {
792 referring_objects.push_back(gRegistry->Add(raw_instances[i]));
793 }
794 return JDWP::ERR_NONE;
795}
796
Elliott Hughes64f574f2013-02-20 14:57:12 -0800797JDWP::JdwpError Dbg::DisableCollection(JDWP::ObjectId object_id)
798 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Sebastien Hertze96060a2013-12-11 12:06:28 +0100799 mirror::Object* o = gRegistry->Get<mirror::Object*>(object_id);
800 if (o == NULL || o == ObjectRegistry::kInvalidObject) {
801 return JDWP::ERR_INVALID_OBJECT;
802 }
Elliott Hughes64f574f2013-02-20 14:57:12 -0800803 gRegistry->DisableCollection(object_id);
804 return JDWP::ERR_NONE;
805}
806
807JDWP::JdwpError Dbg::EnableCollection(JDWP::ObjectId object_id)
808 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Sebastien Hertze96060a2013-12-11 12:06:28 +0100809 mirror::Object* o = gRegistry->Get<mirror::Object*>(object_id);
810 // Unlike DisableCollection, JDWP specs do not state an invalid object causes an error. The RI
811 // also ignores these cases and never return an error. However it's not obvious why this command
812 // should behave differently from DisableCollection and IsCollected commands. So let's be more
813 // strict and return an error if this happens.
814 if (o == NULL || o == ObjectRegistry::kInvalidObject) {
815 return JDWP::ERR_INVALID_OBJECT;
816 }
Elliott Hughes64f574f2013-02-20 14:57:12 -0800817 gRegistry->EnableCollection(object_id);
818 return JDWP::ERR_NONE;
819}
820
821JDWP::JdwpError Dbg::IsCollected(JDWP::ObjectId object_id, bool& is_collected)
822 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Sebastien Hertze96060a2013-12-11 12:06:28 +0100823 mirror::Object* o = gRegistry->Get<mirror::Object*>(object_id);
824 // JDWP specs state an INVALID_OBJECT error is returned if the object ID is not valid. However
825 // the RI seems to ignore this and does not return any error in this case. Let's comply with
826 // JDWP specs here.
827 if (o == NULL || o == ObjectRegistry::kInvalidObject) {
828 return JDWP::ERR_INVALID_OBJECT;
829 }
Elliott Hughes64f574f2013-02-20 14:57:12 -0800830 is_collected = gRegistry->IsCollected(object_id);
831 return JDWP::ERR_NONE;
832}
833
834void Dbg::DisposeObject(JDWP::ObjectId object_id, uint32_t reference_count)
835 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
836 gRegistry->DisposeObject(object_id, reference_count);
837}
838
Elliott Hughes88d63092013-01-09 09:55:54 -0800839JDWP::JdwpError Dbg::GetReflectedType(JDWP::RefTypeId class_id, JDWP::ExpandBuf* pReply) {
Elliott Hughes436e3722012-02-17 20:01:47 -0800840 JDWP::JdwpError status;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800841 mirror::Class* c = DecodeClass(class_id, status);
Elliott Hughes436e3722012-02-17 20:01:47 -0800842 if (c == NULL) {
843 return status;
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -0800844 }
Elliott Hughes436e3722012-02-17 20:01:47 -0800845
846 expandBufAdd1(pReply, c->IsInterface() ? JDWP::TT_INTERFACE : JDWP::TT_CLASS);
Elliott Hughes88d63092013-01-09 09:55:54 -0800847 expandBufAddRefTypeId(pReply, class_id);
Elliott Hughes436e3722012-02-17 20:01:47 -0800848 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700849}
850
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -0800851void Dbg::GetClassList(std::vector<JDWP::RefTypeId>& classes) {
Elliott Hughesa2155262011-11-16 16:26:58 -0800852 // Get the complete list of reference classes (i.e. all classes except
853 // the primitive types).
854 // Returns a newly-allocated buffer full of RefTypeId values.
855 struct ClassListCreator {
Elliott Hughesba8eee12012-01-24 20:25:24 -0800856 explicit ClassListCreator(std::vector<JDWP::RefTypeId>& classes) : classes(classes) {
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -0800857 }
858
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800859 static bool Visit(mirror::Class* c, void* arg) {
Elliott Hughesa2155262011-11-16 16:26:58 -0800860 return reinterpret_cast<ClassListCreator*>(arg)->Visit(c);
861 }
862
Elliott Hughes64f574f2013-02-20 14:57:12 -0800863 // TODO: Enable annotalysis. We know lock is held in constructor, but abstraction confuses
864 // annotalysis.
865 bool Visit(mirror::Class* c) NO_THREAD_SAFETY_ANALYSIS {
Elliott Hughesa2155262011-11-16 16:26:58 -0800866 if (!c->IsPrimitive()) {
Elliott Hughes64f574f2013-02-20 14:57:12 -0800867 classes.push_back(gRegistry->AddRefType(c));
Elliott Hughesa2155262011-11-16 16:26:58 -0800868 }
869 return true;
870 }
871
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -0800872 std::vector<JDWP::RefTypeId>& classes;
Elliott Hughesa2155262011-11-16 16:26:58 -0800873 };
874
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -0800875 ClassListCreator clc(classes);
Elliott Hughesa2155262011-11-16 16:26:58 -0800876 Runtime::Current()->GetClassLinker()->VisitClasses(ClassListCreator::Visit, &clc);
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700877}
878
Elliott Hughes88d63092013-01-09 09:55:54 -0800879JDWP::JdwpError Dbg::GetClassInfo(JDWP::RefTypeId class_id, JDWP::JdwpTypeTag* pTypeTag, uint32_t* pStatus, std::string* pDescriptor) {
Elliott Hughes436e3722012-02-17 20:01:47 -0800880 JDWP::JdwpError status;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800881 mirror::Class* c = DecodeClass(class_id, status);
Elliott Hughes436e3722012-02-17 20:01:47 -0800882 if (c == NULL) {
883 return status;
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -0800884 }
885
Elliott Hughesa2155262011-11-16 16:26:58 -0800886 if (c->IsArrayClass()) {
887 *pStatus = JDWP::CS_VERIFIED | JDWP::CS_PREPARED;
888 *pTypeTag = JDWP::TT_ARRAY;
889 } else {
890 if (c->IsErroneous()) {
891 *pStatus = JDWP::CS_ERROR;
892 } else {
893 *pStatus = JDWP::CS_VERIFIED | JDWP::CS_PREPARED | JDWP::CS_INITIALIZED;
894 }
895 *pTypeTag = c->IsInterface() ? JDWP::TT_INTERFACE : JDWP::TT_CLASS;
896 }
897
898 if (pDescriptor != NULL) {
Ian Rogersdfb325e2013-10-30 01:00:44 -0700899 *pDescriptor = ClassHelper(c).GetDescriptor();
Elliott Hughesa2155262011-11-16 16:26:58 -0800900 }
Elliott Hughes436e3722012-02-17 20:01:47 -0800901 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700902}
903
Elliott Hughesc3b77c72011-12-15 20:56:48 -0800904void Dbg::FindLoadedClassBySignature(const char* descriptor, std::vector<JDWP::RefTypeId>& ids) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800905 std::vector<mirror::Class*> classes;
Elliott Hughes6fa602d2011-12-02 17:54:25 -0800906 Runtime::Current()->GetClassLinker()->LookupClasses(descriptor, classes);
907 ids.clear();
908 for (size_t i = 0; i < classes.size(); ++i) {
909 ids.push_back(gRegistry->Add(classes[i]));
910 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700911}
912
Elliott Hughes64f574f2013-02-20 14:57:12 -0800913JDWP::JdwpError Dbg::GetReferenceType(JDWP::ObjectId object_id, JDWP::ExpandBuf* pReply)
914 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800915 mirror::Object* o = gRegistry->Get<mirror::Object*>(object_id);
Elliott Hughes64f574f2013-02-20 14:57:12 -0800916 if (o == NULL || o == ObjectRegistry::kInvalidObject) {
Elliott Hughes2435a572012-02-17 16:07:41 -0800917 return JDWP::ERR_INVALID_OBJECT;
Elliott Hughes499c5132011-11-17 14:55:11 -0800918 }
Elliott Hughes2435a572012-02-17 16:07:41 -0800919
920 JDWP::JdwpTypeTag type_tag;
921 if (o->GetClass()->IsArrayClass()) {
922 type_tag = JDWP::TT_ARRAY;
923 } else if (o->GetClass()->IsInterface()) {
924 type_tag = JDWP::TT_INTERFACE;
925 } else {
926 type_tag = JDWP::TT_CLASS;
927 }
Elliott Hughes64f574f2013-02-20 14:57:12 -0800928 JDWP::RefTypeId type_id = gRegistry->AddRefType(o->GetClass());
Elliott Hughes2435a572012-02-17 16:07:41 -0800929
930 expandBufAdd1(pReply, type_tag);
931 expandBufAddRefTypeId(pReply, type_id);
932
933 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700934}
935
Ian Rogersfc0e94b2013-09-23 23:51:32 -0700936JDWP::JdwpError Dbg::GetSignature(JDWP::RefTypeId class_id, std::string* signature) {
Elliott Hughes1fe7afb2012-02-13 17:23:03 -0800937 JDWP::JdwpError status;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800938 mirror::Class* c = DecodeClass(class_id, status);
Elliott Hughes1fe7afb2012-02-13 17:23:03 -0800939 if (c == NULL) {
940 return status;
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -0800941 }
Ian Rogersdfb325e2013-10-30 01:00:44 -0700942 *signature = ClassHelper(c).GetDescriptor();
Elliott Hughes1fe7afb2012-02-13 17:23:03 -0800943 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700944}
945
Elliott Hughes88d63092013-01-09 09:55:54 -0800946JDWP::JdwpError Dbg::GetSourceFile(JDWP::RefTypeId class_id, std::string& result) {
Elliott Hughes436e3722012-02-17 20:01:47 -0800947 JDWP::JdwpError status;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800948 mirror::Class* c = DecodeClass(class_id, status);
Elliott Hughes436e3722012-02-17 20:01:47 -0800949 if (c == NULL) {
950 return status;
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -0800951 }
Elliott Hughes436e3722012-02-17 20:01:47 -0800952 result = ClassHelper(c).GetSourceFile();
953 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700954}
955
Elliott Hughes88d63092013-01-09 09:55:54 -0800956JDWP::JdwpError Dbg::GetObjectTag(JDWP::ObjectId object_id, uint8_t& tag) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800957 mirror::Object* o = gRegistry->Get<mirror::Object*>(object_id);
Elliott Hughes64f574f2013-02-20 14:57:12 -0800958 if (o == ObjectRegistry::kInvalidObject) {
Elliott Hughes546b9862012-06-20 16:06:13 -0700959 return JDWP::ERR_INVALID_OBJECT;
960 }
961 tag = TagFromObject(o);
962 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700963}
964
Elliott Hughesaed4be92011-12-02 16:16:23 -0800965size_t Dbg::GetTagWidth(JDWP::JdwpTag tag) {
Elliott Hughesdbb40792011-11-18 17:05:22 -0800966 switch (tag) {
967 case JDWP::JT_VOID:
968 return 0;
969 case JDWP::JT_BYTE:
970 case JDWP::JT_BOOLEAN:
971 return 1;
972 case JDWP::JT_CHAR:
973 case JDWP::JT_SHORT:
974 return 2;
975 case JDWP::JT_FLOAT:
976 case JDWP::JT_INT:
977 return 4;
978 case JDWP::JT_ARRAY:
979 case JDWP::JT_OBJECT:
980 case JDWP::JT_STRING:
981 case JDWP::JT_THREAD:
982 case JDWP::JT_THREAD_GROUP:
983 case JDWP::JT_CLASS_LOADER:
984 case JDWP::JT_CLASS_OBJECT:
985 return sizeof(JDWP::ObjectId);
986 case JDWP::JT_DOUBLE:
987 case JDWP::JT_LONG:
988 return 8;
989 default:
Elliott Hughes3d30d9b2011-12-07 17:35:48 -0800990 LOG(FATAL) << "Unknown tag " << tag;
Elliott Hughesdbb40792011-11-18 17:05:22 -0800991 return -1;
992 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700993}
994
Elliott Hughes88d63092013-01-09 09:55:54 -0800995JDWP::JdwpError Dbg::GetArrayLength(JDWP::ObjectId array_id, int& length) {
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -0800996 JDWP::JdwpError status;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800997 mirror::Array* a = DecodeArray(array_id, status);
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -0800998 if (a == NULL) {
999 return status;
Elliott Hughes24437992011-11-30 14:49:33 -08001000 }
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -08001001 length = a->GetLength();
1002 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001003}
1004
Elliott Hughes88d63092013-01-09 09:55:54 -08001005JDWP::JdwpError Dbg::OutputArray(JDWP::ObjectId array_id, int offset, int count, JDWP::ExpandBuf* pReply) {
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -08001006 JDWP::JdwpError status;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001007 mirror::Array* a = DecodeArray(array_id, status);
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -08001008 if (a == NULL) {
1009 return status;
1010 }
Elliott Hughes24437992011-11-30 14:49:33 -08001011
1012 if (offset < 0 || count < 0 || offset > a->GetLength() || a->GetLength() - offset < count) {
1013 LOG(WARNING) << __FUNCTION__ << " access out of bounds: offset=" << offset << "; count=" << count;
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -08001014 return JDWP::ERR_INVALID_LENGTH;
Elliott Hughes24437992011-11-30 14:49:33 -08001015 }
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001016 std::string descriptor(ClassHelper(a->GetClass()).GetDescriptor());
Elliott Hughes24437992011-11-30 14:49:33 -08001017 JDWP::JdwpTag tag = BasicTagFromDescriptor(descriptor.c_str() + 1);
1018
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -08001019 expandBufAdd1(pReply, tag);
1020 expandBufAdd4BE(pReply, count);
1021
Elliott Hughes24437992011-11-30 14:49:33 -08001022 if (IsPrimitiveTag(tag)) {
1023 size_t width = GetTagWidth(tag);
Elliott Hughes24437992011-11-30 14:49:33 -08001024 uint8_t* dst = expandBufAddSpace(pReply, count * width);
1025 if (width == 8) {
Ian Rogersa15e67d2012-02-28 13:51:55 -08001026 const uint64_t* src8 = reinterpret_cast<uint64_t*>(a->GetRawData(sizeof(uint64_t)));
Elliott Hughes24437992011-11-30 14:49:33 -08001027 for (int i = 0; i < count; ++i) JDWP::Write8BE(&dst, src8[offset + i]);
1028 } else if (width == 4) {
Ian Rogersa15e67d2012-02-28 13:51:55 -08001029 const uint32_t* src4 = reinterpret_cast<uint32_t*>(a->GetRawData(sizeof(uint32_t)));
Elliott Hughes24437992011-11-30 14:49:33 -08001030 for (int i = 0; i < count; ++i) JDWP::Write4BE(&dst, src4[offset + i]);
1031 } else if (width == 2) {
Ian Rogersa15e67d2012-02-28 13:51:55 -08001032 const uint16_t* src2 = reinterpret_cast<uint16_t*>(a->GetRawData(sizeof(uint16_t)));
Elliott Hughes24437992011-11-30 14:49:33 -08001033 for (int i = 0; i < count; ++i) JDWP::Write2BE(&dst, src2[offset + i]);
1034 } else {
Ian Rogersa15e67d2012-02-28 13:51:55 -08001035 const uint8_t* src = reinterpret_cast<uint8_t*>(a->GetRawData(sizeof(uint8_t)));
Elliott Hughes24437992011-11-30 14:49:33 -08001036 memcpy(dst, &src[offset * width], count * width);
1037 }
1038 } else {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001039 mirror::ObjectArray<mirror::Object>* oa = a->AsObjectArray<mirror::Object>();
Elliott Hughes24437992011-11-30 14:49:33 -08001040 for (int i = 0; i < count; ++i) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001041 mirror::Object* element = oa->Get(offset + i);
Elliott Hughes24437992011-11-30 14:49:33 -08001042 JDWP::JdwpTag specific_tag = (element != NULL) ? TagFromObject(element) : tag;
1043 expandBufAdd1(pReply, specific_tag);
1044 expandBufAddObjectId(pReply, gRegistry->Add(element));
1045 }
1046 }
1047
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -08001048 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001049}
1050
Elliott Hughes4b9702c2013-02-20 18:13:24 -08001051template <typename T> void CopyArrayData(mirror::Array* a, JDWP::Request& src, int offset, int count) {
1052 DCHECK(a->GetClass()->IsPrimitiveArray());
1053
1054 T* dst = &(reinterpret_cast<T*>(a->GetRawData(sizeof(T)))[offset * sizeof(T)]);
1055 for (int i = 0; i < count; ++i) {
1056 *dst++ = src.ReadValue(sizeof(T));
1057 }
1058}
1059
Elliott Hughes88d63092013-01-09 09:55:54 -08001060JDWP::JdwpError Dbg::SetArrayElements(JDWP::ObjectId array_id, int offset, int count,
Elliott Hughes4b9702c2013-02-20 18:13:24 -08001061 JDWP::Request& request)
Ian Rogersb726dcb2012-09-05 08:57:23 -07001062 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -08001063 JDWP::JdwpError status;
Elliott Hughes4b9702c2013-02-20 18:13:24 -08001064 mirror::Array* dst = DecodeArray(array_id, status);
1065 if (dst == NULL) {
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -08001066 return status;
1067 }
Elliott Hughesf03b8f62011-12-02 14:26:25 -08001068
Elliott Hughes4b9702c2013-02-20 18:13:24 -08001069 if (offset < 0 || count < 0 || offset > dst->GetLength() || dst->GetLength() - offset < count) {
Elliott Hughesf03b8f62011-12-02 14:26:25 -08001070 LOG(WARNING) << __FUNCTION__ << " access out of bounds: offset=" << offset << "; count=" << count;
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -08001071 return JDWP::ERR_INVALID_LENGTH;
Elliott Hughesf03b8f62011-12-02 14:26:25 -08001072 }
Ian Rogersfc0e94b2013-09-23 23:51:32 -07001073 const char* descriptor = ClassHelper(dst->GetClass()).GetDescriptor();
1074 JDWP::JdwpTag tag = BasicTagFromDescriptor(descriptor + 1);
Elliott Hughesf03b8f62011-12-02 14:26:25 -08001075
1076 if (IsPrimitiveTag(tag)) {
1077 size_t width = GetTagWidth(tag);
Elliott Hughesf03b8f62011-12-02 14:26:25 -08001078 if (width == 8) {
Elliott Hughes4b9702c2013-02-20 18:13:24 -08001079 CopyArrayData<uint64_t>(dst, request, offset, count);
Elliott Hughesf03b8f62011-12-02 14:26:25 -08001080 } else if (width == 4) {
Elliott Hughes4b9702c2013-02-20 18:13:24 -08001081 CopyArrayData<uint32_t>(dst, request, offset, count);
Elliott Hughesf03b8f62011-12-02 14:26:25 -08001082 } else if (width == 2) {
Elliott Hughes4b9702c2013-02-20 18:13:24 -08001083 CopyArrayData<uint16_t>(dst, request, offset, count);
Elliott Hughesf03b8f62011-12-02 14:26:25 -08001084 } else {
Elliott Hughes4b9702c2013-02-20 18:13:24 -08001085 CopyArrayData<uint8_t>(dst, request, offset, count);
Elliott Hughesf03b8f62011-12-02 14:26:25 -08001086 }
1087 } else {
Elliott Hughes4b9702c2013-02-20 18:13:24 -08001088 mirror::ObjectArray<mirror::Object>* oa = dst->AsObjectArray<mirror::Object>();
Elliott Hughesf03b8f62011-12-02 14:26:25 -08001089 for (int i = 0; i < count; ++i) {
Elliott Hughes4b9702c2013-02-20 18:13:24 -08001090 JDWP::ObjectId id = request.ReadObjectId();
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001091 mirror::Object* o = gRegistry->Get<mirror::Object*>(id);
Elliott Hughes64f574f2013-02-20 14:57:12 -08001092 if (o == ObjectRegistry::kInvalidObject) {
Elliott Hughes436e3722012-02-17 20:01:47 -08001093 return JDWP::ERR_INVALID_OBJECT;
1094 }
1095 oa->Set(offset + i, o);
Elliott Hughesf03b8f62011-12-02 14:26:25 -08001096 }
1097 }
1098
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -08001099 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001100}
1101
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -08001102JDWP::ObjectId Dbg::CreateString(const std::string& str) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001103 return gRegistry->Add(mirror::String::AllocFromModifiedUtf8(Thread::Current(), str.c_str()));
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001104}
1105
Elliott Hughes88d63092013-01-09 09:55:54 -08001106JDWP::JdwpError Dbg::CreateObject(JDWP::RefTypeId class_id, JDWP::ObjectId& new_object) {
Elliott Hughes436e3722012-02-17 20:01:47 -08001107 JDWP::JdwpError status;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001108 mirror::Class* c = DecodeClass(class_id, status);
Elliott Hughes436e3722012-02-17 20:01:47 -08001109 if (c == NULL) {
1110 return status;
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -08001111 }
Ian Rogers50b35e22012-10-04 10:09:15 -07001112 new_object = gRegistry->Add(c->AllocObject(Thread::Current()));
Elliott Hughes436e3722012-02-17 20:01:47 -08001113 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001114}
1115
Elliott Hughesbf13d362011-12-08 15:51:37 -08001116/*
1117 * Used by Eclipse's "Display" view to evaluate "new byte[5]" to get "(byte[]) [0, 0, 0, 0, 0]".
1118 */
Elliott Hughes88d63092013-01-09 09:55:54 -08001119JDWP::JdwpError Dbg::CreateArrayObject(JDWP::RefTypeId array_class_id, uint32_t length,
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001120 JDWP::ObjectId& new_array) {
Elliott Hughes436e3722012-02-17 20:01:47 -08001121 JDWP::JdwpError status;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001122 mirror::Class* c = DecodeClass(array_class_id, status);
Elliott Hughes436e3722012-02-17 20:01:47 -08001123 if (c == NULL) {
1124 return status;
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -08001125 }
Mathieu Chartiercbb2d202013-11-14 17:45:16 -08001126 new_array = gRegistry->Add(mirror::Array::Alloc<true>(Thread::Current(), c, length));
Elliott Hughes436e3722012-02-17 20:01:47 -08001127 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001128}
1129
Elliott Hughes88d63092013-01-09 09:55:54 -08001130bool Dbg::MatchType(JDWP::RefTypeId instance_class_id, JDWP::RefTypeId class_id) {
Elliott Hughes436e3722012-02-17 20:01:47 -08001131 JDWP::JdwpError status;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001132 mirror::Class* c1 = DecodeClass(instance_class_id, status);
Elliott Hughesa656a0f2012-02-21 18:03:44 -08001133 CHECK(c1 != NULL);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001134 mirror::Class* c2 = DecodeClass(class_id, status);
Elliott Hughesa656a0f2012-02-21 18:03:44 -08001135 CHECK(c2 != NULL);
Sebastien Hertz123756a2013-11-27 15:49:42 +01001136 return c2->IsAssignableFrom(c1);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001137}
1138
Brian Carlstromea46f952013-07-30 01:26:50 -07001139static JDWP::FieldId ToFieldId(const mirror::ArtField* f)
Ian Rogersb726dcb2012-09-05 08:57:23 -07001140 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Mathieu Chartier590fee92013-09-13 13:46:47 -07001141 CHECK(!kMovingFields);
Elliott Hughes03181a82011-11-17 17:22:21 -08001142 return static_cast<JDWP::FieldId>(reinterpret_cast<uintptr_t>(f));
Elliott Hughes03181a82011-11-17 17:22:21 -08001143}
1144
Brian Carlstromea46f952013-07-30 01:26:50 -07001145static JDWP::MethodId ToMethodId(const mirror::ArtMethod* m)
Ian Rogersb726dcb2012-09-05 08:57:23 -07001146 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Mathieu Chartier590fee92013-09-13 13:46:47 -07001147 CHECK(!kMovingMethods);
Elliott Hughes03181a82011-11-17 17:22:21 -08001148 return static_cast<JDWP::MethodId>(reinterpret_cast<uintptr_t>(m));
Elliott Hughes03181a82011-11-17 17:22:21 -08001149}
1150
Brian Carlstromea46f952013-07-30 01:26:50 -07001151static mirror::ArtField* FromFieldId(JDWP::FieldId fid)
Ian Rogersb726dcb2012-09-05 08:57:23 -07001152 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Mathieu Chartier590fee92013-09-13 13:46:47 -07001153 CHECK(!kMovingFields);
Brian Carlstromea46f952013-07-30 01:26:50 -07001154 return reinterpret_cast<mirror::ArtField*>(static_cast<uintptr_t>(fid));
Elliott Hughesaed4be92011-12-02 16:16:23 -08001155}
1156
Brian Carlstromea46f952013-07-30 01:26:50 -07001157static mirror::ArtMethod* FromMethodId(JDWP::MethodId mid)
Ian Rogersb726dcb2012-09-05 08:57:23 -07001158 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Mathieu Chartier590fee92013-09-13 13:46:47 -07001159 CHECK(!kMovingMethods);
Brian Carlstromea46f952013-07-30 01:26:50 -07001160 return reinterpret_cast<mirror::ArtMethod*>(static_cast<uintptr_t>(mid));
Elliott Hughes03181a82011-11-17 17:22:21 -08001161}
1162
Brian Carlstromea46f952013-07-30 01:26:50 -07001163static void SetLocation(JDWP::JdwpLocation& location, mirror::ArtMethod* m, uint32_t dex_pc)
Ian Rogersb726dcb2012-09-05 08:57:23 -07001164 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08001165 if (m == NULL) {
1166 memset(&location, 0, sizeof(location));
1167 } else {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001168 mirror::Class* c = m->GetDeclaringClass();
Elliott Hughes74847412012-06-20 18:10:21 -07001169 location.type_tag = c->IsInterface() ? JDWP::TT_INTERFACE : JDWP::TT_CLASS;
1170 location.class_id = gRegistry->Add(c);
1171 location.method_id = ToMethodId(m);
Ian Rogers0399dde2012-06-06 17:09:28 -07001172 location.dex_pc = dex_pc;
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08001173 }
Elliott Hughesd07986f2011-12-06 18:27:45 -08001174}
1175
Elliott Hughesa96836a2013-01-17 12:27:49 -08001176std::string Dbg::GetMethodName(JDWP::MethodId method_id)
Ian Rogersb726dcb2012-09-05 08:57:23 -07001177 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Brian Carlstromea46f952013-07-30 01:26:50 -07001178 mirror::ArtMethod* m = FromMethodId(method_id);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001179 return MethodHelper(m).GetName();
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001180}
1181
Elliott Hughesa96836a2013-01-17 12:27:49 -08001182std::string Dbg::GetFieldName(JDWP::FieldId field_id)
1183 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Brian Carlstromea46f952013-07-30 01:26:50 -07001184 mirror::ArtField* f = FromFieldId(field_id);
Elliott Hughesa96836a2013-01-17 12:27:49 -08001185 return FieldHelper(f).GetName();
1186}
1187
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001188/*
1189 * Augment the access flags for synthetic methods and fields by setting
1190 * the (as described by the spec) "0xf0000000 bit". Also, strip out any
1191 * flags not specified by the Java programming language.
1192 */
1193static uint32_t MangleAccessFlags(uint32_t accessFlags) {
1194 accessFlags &= kAccJavaFlagsMask;
1195 if ((accessFlags & kAccSynthetic) != 0) {
1196 accessFlags |= 0xf0000000;
1197 }
1198 return accessFlags;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001199}
1200
Elliott Hughesdbb40792011-11-18 17:05:22 -08001201/*
Jeff Haob7cefc72013-11-14 14:51:09 -08001202 * Circularly shifts registers so that arguments come first. Debuggers
1203 * expect slots to begin with arguments, but dex code places them at
1204 * the end.
Elliott Hughesdbb40792011-11-18 17:05:22 -08001205 */
Jeff Haob7cefc72013-11-14 14:51:09 -08001206static uint16_t MangleSlot(uint16_t slot, mirror::ArtMethod* m)
1207 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
1208 const DexFile::CodeItem* code_item = MethodHelper(m).GetCodeItem();
1209 uint16_t ins_size = code_item->ins_size_;
1210 uint16_t locals_size = code_item->registers_size_ - ins_size;
1211 if (slot >= locals_size) {
1212 return slot - locals_size;
1213 } else {
1214 return slot + ins_size;
Elliott Hughesdbb40792011-11-18 17:05:22 -08001215 }
Elliott Hughesdbb40792011-11-18 17:05:22 -08001216}
1217
Jeff Haob7cefc72013-11-14 14:51:09 -08001218/*
1219 * Circularly shifts registers so that arguments come last. Reverts
1220 * slots to dex style argument placement.
1221 */
Brian Carlstromea46f952013-07-30 01:26:50 -07001222static uint16_t DemangleSlot(uint16_t slot, mirror::ArtMethod* m)
Ian Rogersb726dcb2012-09-05 08:57:23 -07001223 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Jeff Haob7cefc72013-11-14 14:51:09 -08001224 const DexFile::CodeItem* code_item = MethodHelper(m).GetCodeItem();
1225 uint16_t ins_size = code_item->ins_size_;
1226 uint16_t locals_size = code_item->registers_size_ - ins_size;
1227 if (slot < ins_size) {
1228 return slot + locals_size;
1229 } else {
1230 return slot - ins_size;
Elliott Hughesdbb40792011-11-18 17:05:22 -08001231 }
Elliott Hughesdbb40792011-11-18 17:05:22 -08001232}
1233
Elliott Hughes88d63092013-01-09 09:55:54 -08001234JDWP::JdwpError Dbg::OutputDeclaredFields(JDWP::RefTypeId class_id, bool with_generic, JDWP::ExpandBuf* pReply) {
Elliott Hughes436e3722012-02-17 20:01:47 -08001235 JDWP::JdwpError status;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001236 mirror::Class* c = DecodeClass(class_id, status);
Elliott Hughes436e3722012-02-17 20:01:47 -08001237 if (c == NULL) {
1238 return status;
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -08001239 }
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001240
1241 size_t instance_field_count = c->NumInstanceFields();
1242 size_t static_field_count = c->NumStaticFields();
1243
1244 expandBufAdd4BE(pReply, instance_field_count + static_field_count);
1245
1246 for (size_t i = 0; i < instance_field_count + static_field_count; ++i) {
Brian Carlstromea46f952013-07-30 01:26:50 -07001247 mirror::ArtField* f = (i < instance_field_count) ? c->GetInstanceField(i) : c->GetStaticField(i - instance_field_count);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001248 FieldHelper fh(f);
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001249 expandBufAddFieldId(pReply, ToFieldId(f));
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001250 expandBufAddUtf8String(pReply, fh.GetName());
1251 expandBufAddUtf8String(pReply, fh.GetTypeDescriptor());
Elliott Hughesc5b734a2011-12-01 17:20:58 -08001252 if (with_generic) {
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001253 static const char genericSignature[1] = "";
1254 expandBufAddUtf8String(pReply, genericSignature);
1255 }
1256 expandBufAdd4BE(pReply, MangleAccessFlags(f->GetAccessFlags()));
1257 }
Elliott Hughes436e3722012-02-17 20:01:47 -08001258 return JDWP::ERR_NONE;
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001259}
1260
Elliott Hughes88d63092013-01-09 09:55:54 -08001261JDWP::JdwpError Dbg::OutputDeclaredMethods(JDWP::RefTypeId class_id, bool with_generic,
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001262 JDWP::ExpandBuf* pReply) {
Elliott Hughes436e3722012-02-17 20:01:47 -08001263 JDWP::JdwpError status;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001264 mirror::Class* c = DecodeClass(class_id, status);
Elliott Hughes436e3722012-02-17 20:01:47 -08001265 if (c == NULL) {
1266 return status;
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -08001267 }
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001268
1269 size_t direct_method_count = c->NumDirectMethods();
1270 size_t virtual_method_count = c->NumVirtualMethods();
1271
1272 expandBufAdd4BE(pReply, direct_method_count + virtual_method_count);
1273
1274 for (size_t i = 0; i < direct_method_count + virtual_method_count; ++i) {
Brian Carlstromea46f952013-07-30 01:26:50 -07001275 mirror::ArtMethod* m = (i < direct_method_count) ? c->GetDirectMethod(i) : c->GetVirtualMethod(i - direct_method_count);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001276 MethodHelper mh(m);
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001277 expandBufAddMethodId(pReply, ToMethodId(m));
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001278 expandBufAddUtf8String(pReply, mh.GetName());
Ian Rogersd91d6d62013-09-25 20:26:14 -07001279 expandBufAddUtf8String(pReply, mh.GetSignature().ToString());
Elliott Hughesc5b734a2011-12-01 17:20:58 -08001280 if (with_generic) {
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001281 static const char genericSignature[1] = "";
1282 expandBufAddUtf8String(pReply, genericSignature);
1283 }
1284 expandBufAdd4BE(pReply, MangleAccessFlags(m->GetAccessFlags()));
1285 }
Elliott Hughes436e3722012-02-17 20:01:47 -08001286 return JDWP::ERR_NONE;
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001287}
1288
Elliott Hughes88d63092013-01-09 09:55:54 -08001289JDWP::JdwpError Dbg::OutputDeclaredInterfaces(JDWP::RefTypeId class_id, JDWP::ExpandBuf* pReply) {
Elliott Hughes436e3722012-02-17 20:01:47 -08001290 JDWP::JdwpError status;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001291 mirror::Class* c = DecodeClass(class_id, status);
Elliott Hughes436e3722012-02-17 20:01:47 -08001292 if (c == NULL) {
1293 return status;
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -08001294 }
Elliott Hughes436e3722012-02-17 20:01:47 -08001295
1296 ClassHelper kh(c);
Ian Rogersd24e2642012-06-06 21:21:43 -07001297 size_t interface_count = kh.NumDirectInterfaces();
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001298 expandBufAdd4BE(pReply, interface_count);
1299 for (size_t i = 0; i < interface_count; ++i) {
Elliott Hughes64f574f2013-02-20 14:57:12 -08001300 expandBufAddRefTypeId(pReply, gRegistry->AddRefType(kh.GetDirectInterface(i)));
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001301 }
Elliott Hughes436e3722012-02-17 20:01:47 -08001302 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001303}
1304
Elliott Hughes88d63092013-01-09 09:55:54 -08001305void Dbg::OutputLineTable(JDWP::RefTypeId, JDWP::MethodId method_id, JDWP::ExpandBuf* pReply)
Ian Rogersb726dcb2012-09-05 08:57:23 -07001306 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Elliott Hughes03181a82011-11-17 17:22:21 -08001307 struct DebugCallbackContext {
1308 int numItems;
1309 JDWP::ExpandBuf* pReply;
1310
Elliott Hughes2435a572012-02-17 16:07:41 -08001311 static bool Callback(void* context, uint32_t address, uint32_t line_number) {
Elliott Hughes03181a82011-11-17 17:22:21 -08001312 DebugCallbackContext* pContext = reinterpret_cast<DebugCallbackContext*>(context);
1313 expandBufAdd8BE(pContext->pReply, address);
Elliott Hughes2435a572012-02-17 16:07:41 -08001314 expandBufAdd4BE(pContext->pReply, line_number);
Elliott Hughes03181a82011-11-17 17:22:21 -08001315 pContext->numItems++;
Sebastien Hertzf2910ee2013-10-19 16:39:24 +02001316 return false;
Elliott Hughes03181a82011-11-17 17:22:21 -08001317 }
1318 };
Brian Carlstromea46f952013-07-30 01:26:50 -07001319 mirror::ArtMethod* m = FromMethodId(method_id);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001320 MethodHelper mh(m);
Elliott Hughes03181a82011-11-17 17:22:21 -08001321 uint64_t start, end;
1322 if (m->IsNative()) {
1323 start = -1;
1324 end = -1;
1325 } else {
1326 start = 0;
jeffhao14f0db92012-12-14 17:50:42 -08001327 // Return the index of the last instruction
1328 end = mh.GetCodeItem()->insns_size_in_code_units_ - 1;
Elliott Hughes03181a82011-11-17 17:22:21 -08001329 }
1330
1331 expandBufAdd8BE(pReply, start);
1332 expandBufAdd8BE(pReply, end);
1333
1334 // Add numLines later
1335 size_t numLinesOffset = expandBufGetLength(pReply);
1336 expandBufAdd4BE(pReply, 0);
1337
1338 DebugCallbackContext context;
1339 context.numItems = 0;
1340 context.pReply = pReply;
1341
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001342 mh.GetDexFile().DecodeDebugInfo(mh.GetCodeItem(), m->IsStatic(), m->GetDexMethodIndex(),
1343 DebugCallbackContext::Callback, NULL, &context);
Elliott Hughes03181a82011-11-17 17:22:21 -08001344
1345 JDWP::Set4BE(expandBufGetBuffer(pReply) + numLinesOffset, context.numItems);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001346}
1347
Elliott Hughes88d63092013-01-09 09:55:54 -08001348void Dbg::OutputVariableTable(JDWP::RefTypeId, JDWP::MethodId method_id, bool with_generic, JDWP::ExpandBuf* pReply) {
Elliott Hughesdbb40792011-11-18 17:05:22 -08001349 struct DebugCallbackContext {
Jeff Haob7cefc72013-11-14 14:51:09 -08001350 mirror::ArtMethod* method;
Elliott Hughesdbb40792011-11-18 17:05:22 -08001351 JDWP::ExpandBuf* pReply;
Elliott Hughesc5b734a2011-12-01 17:20:58 -08001352 size_t variable_count;
1353 bool with_generic;
Elliott Hughesdbb40792011-11-18 17:05:22 -08001354
Jeff Haob7cefc72013-11-14 14:51:09 -08001355 static void Callback(void* context, uint16_t slot, uint32_t startAddress, uint32_t endAddress, const char* name, const char* descriptor, const char* signature)
1356 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Elliott Hughesdbb40792011-11-18 17:05:22 -08001357 DebugCallbackContext* pContext = reinterpret_cast<DebugCallbackContext*>(context);
1358
Jeff Haob7cefc72013-11-14 14:51:09 -08001359 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 -08001360
Jeff Haob7cefc72013-11-14 14:51:09 -08001361 slot = MangleSlot(slot, pContext->method);
Elliott Hughes68fdbd02011-11-29 19:22:47 -08001362
Elliott Hughesdbb40792011-11-18 17:05:22 -08001363 expandBufAdd8BE(pContext->pReply, startAddress);
1364 expandBufAddUtf8String(pContext->pReply, name);
1365 expandBufAddUtf8String(pContext->pReply, descriptor);
Elliott Hughesc5b734a2011-12-01 17:20:58 -08001366 if (pContext->with_generic) {
Elliott Hughesdbb40792011-11-18 17:05:22 -08001367 expandBufAddUtf8String(pContext->pReply, signature);
1368 }
1369 expandBufAdd4BE(pContext->pReply, endAddress - startAddress);
1370 expandBufAdd4BE(pContext->pReply, slot);
1371
Elliott Hughesc5b734a2011-12-01 17:20:58 -08001372 ++pContext->variable_count;
Elliott Hughesdbb40792011-11-18 17:05:22 -08001373 }
1374 };
Brian Carlstromea46f952013-07-30 01:26:50 -07001375 mirror::ArtMethod* m = FromMethodId(method_id);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001376 MethodHelper mh(m);
1377 const DexFile::CodeItem* code_item = mh.GetCodeItem();
Elliott Hughesdbb40792011-11-18 17:05:22 -08001378
Elliott Hughesc5b734a2011-12-01 17:20:58 -08001379 // arg_count considers doubles and longs to take 2 units.
1380 // variable_count considers everything to take 1 unit.
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001381 std::string shorty(mh.GetShorty());
Brian Carlstromea46f952013-07-30 01:26:50 -07001382 expandBufAdd4BE(pReply, mirror::ArtMethod::NumArgRegisters(shorty));
Elliott Hughesdbb40792011-11-18 17:05:22 -08001383
Elliott Hughesc5b734a2011-12-01 17:20:58 -08001384 // We don't know the total number of variables yet, so leave a blank and update it later.
1385 size_t variable_count_offset = expandBufGetLength(pReply);
Elliott Hughesdbb40792011-11-18 17:05:22 -08001386 expandBufAdd4BE(pReply, 0);
1387
1388 DebugCallbackContext context;
Jeff Haob7cefc72013-11-14 14:51:09 -08001389 context.method = m;
Elliott Hughesdbb40792011-11-18 17:05:22 -08001390 context.pReply = pReply;
Elliott Hughesc5b734a2011-12-01 17:20:58 -08001391 context.variable_count = 0;
1392 context.with_generic = with_generic;
Elliott Hughesdbb40792011-11-18 17:05:22 -08001393
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001394 mh.GetDexFile().DecodeDebugInfo(code_item, m->IsStatic(), m->GetDexMethodIndex(), NULL,
1395 DebugCallbackContext::Callback, &context);
Elliott Hughesdbb40792011-11-18 17:05:22 -08001396
Elliott Hughesc5b734a2011-12-01 17:20:58 -08001397 JDWP::Set4BE(expandBufGetBuffer(pReply) + variable_count_offset, context.variable_count);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001398}
1399
Jeff Hao579b0242013-11-18 13:16:49 -08001400void Dbg::OutputMethodReturnValue(JDWP::MethodId method_id, const JValue* return_value,
1401 JDWP::ExpandBuf* pReply) {
1402 mirror::ArtMethod* m = FromMethodId(method_id);
1403 JDWP::JdwpTag tag = BasicTagFromDescriptor(MethodHelper(m).GetShorty());
1404 OutputJValue(tag, return_value, pReply);
1405}
1406
Elliott Hughes9777ba22013-01-17 09:04:19 -08001407JDWP::JdwpError Dbg::GetBytecodes(JDWP::RefTypeId, JDWP::MethodId method_id,
1408 std::vector<uint8_t>& bytecodes)
1409 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Brian Carlstromea46f952013-07-30 01:26:50 -07001410 mirror::ArtMethod* m = FromMethodId(method_id);
Elliott Hughes9777ba22013-01-17 09:04:19 -08001411 if (m == NULL) {
1412 return JDWP::ERR_INVALID_METHODID;
1413 }
1414 MethodHelper mh(m);
1415 const DexFile::CodeItem* code_item = mh.GetCodeItem();
1416 size_t byte_count = code_item->insns_size_in_code_units_ * 2;
1417 const uint8_t* begin = reinterpret_cast<const uint8_t*>(code_item->insns_);
1418 const uint8_t* end = begin + byte_count;
1419 for (const uint8_t* p = begin; p != end; ++p) {
1420 bytecodes.push_back(*p);
1421 }
1422 return JDWP::ERR_NONE;
1423}
1424
Elliott Hughes88d63092013-01-09 09:55:54 -08001425JDWP::JdwpTag Dbg::GetFieldBasicTag(JDWP::FieldId field_id) {
1426 return BasicTagFromDescriptor(FieldHelper(FromFieldId(field_id)).GetTypeDescriptor());
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001427}
1428
Elliott Hughes88d63092013-01-09 09:55:54 -08001429JDWP::JdwpTag Dbg::GetStaticFieldBasicTag(JDWP::FieldId field_id) {
1430 return BasicTagFromDescriptor(FieldHelper(FromFieldId(field_id)).GetTypeDescriptor());
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001431}
1432
Elliott Hughes88d63092013-01-09 09:55:54 -08001433static JDWP::JdwpError GetFieldValueImpl(JDWP::RefTypeId ref_type_id, JDWP::ObjectId object_id,
1434 JDWP::FieldId field_id, JDWP::ExpandBuf* pReply,
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001435 bool is_static)
Ian Rogersb726dcb2012-09-05 08:57:23 -07001436 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Elliott Hughes0cf74332012-02-23 23:14:00 -08001437 JDWP::JdwpError status;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001438 mirror::Class* c = DecodeClass(ref_type_id, status);
Elliott Hughes88d63092013-01-09 09:55:54 -08001439 if (ref_type_id != 0 && c == NULL) {
Elliott Hughes0cf74332012-02-23 23:14:00 -08001440 return status;
1441 }
1442
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001443 mirror::Object* o = gRegistry->Get<mirror::Object*>(object_id);
Elliott Hughes64f574f2013-02-20 14:57:12 -08001444 if ((!is_static && o == NULL) || o == ObjectRegistry::kInvalidObject) {
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08001445 return JDWP::ERR_INVALID_OBJECT;
1446 }
Brian Carlstromea46f952013-07-30 01:26:50 -07001447 mirror::ArtField* f = FromFieldId(field_id);
Elliott Hughes0cf74332012-02-23 23:14:00 -08001448
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001449 mirror::Class* receiver_class = c;
Elliott Hughes0cf74332012-02-23 23:14:00 -08001450 if (receiver_class == NULL && o != NULL) {
1451 receiver_class = o->GetClass();
1452 }
1453 // TODO: should we give up now if receiver_class is NULL?
1454 if (receiver_class != NULL && !f->GetDeclaringClass()->IsAssignableFrom(receiver_class)) {
1455 LOG(INFO) << "ERR_INVALID_FIELDID: " << PrettyField(f) << " " << PrettyClass(receiver_class);
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08001456 return JDWP::ERR_INVALID_FIELDID;
1457 }
Elliott Hughesaed4be92011-12-02 16:16:23 -08001458
Elliott Hughes0cf74332012-02-23 23:14:00 -08001459 // The RI only enforces the static/non-static mismatch in one direction.
1460 // TODO: should we change the tests and check both?
1461 if (is_static) {
1462 if (!f->IsStatic()) {
1463 return JDWP::ERR_INVALID_FIELDID;
1464 }
1465 } else {
1466 if (f->IsStatic()) {
1467 LOG(WARNING) << "Ignoring non-NULL receiver for ObjectReference.SetValues on static field " << PrettyField(f);
Elliott Hughes0cf74332012-02-23 23:14:00 -08001468 }
1469 }
jeffhao0dfbb7e2012-11-28 15:26:03 -08001470 if (f->IsStatic()) {
1471 o = f->GetDeclaringClass();
1472 }
Elliott Hughes0cf74332012-02-23 23:14:00 -08001473
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001474 JDWP::JdwpTag tag = BasicTagFromDescriptor(FieldHelper(f).GetTypeDescriptor());
Jeff Hao579b0242013-11-18 13:16:49 -08001475 JValue field_value;
1476 if (tag == JDWP::JT_VOID) {
1477 LOG(FATAL) << "Unknown tag: " << tag;
1478 } else if (!IsPrimitiveTag(tag)) {
1479 field_value.SetL(f->GetObject(o));
1480 } else if (tag == JDWP::JT_DOUBLE || tag == JDWP::JT_LONG) {
1481 field_value.SetJ(f->Get64(o));
Elliott Hughesaed4be92011-12-02 16:16:23 -08001482 } else {
Jeff Hao579b0242013-11-18 13:16:49 -08001483 field_value.SetI(f->Get32(o));
Elliott Hughesaed4be92011-12-02 16:16:23 -08001484 }
Jeff Hao579b0242013-11-18 13:16:49 -08001485 Dbg::OutputJValue(tag, &field_value, pReply);
1486
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08001487 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001488}
1489
Elliott Hughes88d63092013-01-09 09:55:54 -08001490JDWP::JdwpError Dbg::GetFieldValue(JDWP::ObjectId object_id, JDWP::FieldId field_id,
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001491 JDWP::ExpandBuf* pReply) {
Elliott Hughes88d63092013-01-09 09:55:54 -08001492 return GetFieldValueImpl(0, object_id, field_id, pReply, false);
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08001493}
1494
Elliott Hughes88d63092013-01-09 09:55:54 -08001495JDWP::JdwpError Dbg::GetStaticFieldValue(JDWP::RefTypeId ref_type_id, JDWP::FieldId field_id, JDWP::ExpandBuf* pReply) {
1496 return GetFieldValueImpl(ref_type_id, 0, field_id, pReply, true);
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08001497}
1498
Elliott Hughes88d63092013-01-09 09:55:54 -08001499static JDWP::JdwpError SetFieldValueImpl(JDWP::ObjectId object_id, JDWP::FieldId field_id,
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001500 uint64_t value, int width, bool is_static)
Ian Rogersb726dcb2012-09-05 08:57:23 -07001501 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001502 mirror::Object* o = gRegistry->Get<mirror::Object*>(object_id);
Elliott Hughes64f574f2013-02-20 14:57:12 -08001503 if ((!is_static && o == NULL) || o == ObjectRegistry::kInvalidObject) {
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08001504 return JDWP::ERR_INVALID_OBJECT;
1505 }
Brian Carlstromea46f952013-07-30 01:26:50 -07001506 mirror::ArtField* f = FromFieldId(field_id);
Elliott Hughes0cf74332012-02-23 23:14:00 -08001507
1508 // The RI only enforces the static/non-static mismatch in one direction.
1509 // TODO: should we change the tests and check both?
1510 if (is_static) {
1511 if (!f->IsStatic()) {
1512 return JDWP::ERR_INVALID_FIELDID;
1513 }
1514 } else {
1515 if (f->IsStatic()) {
1516 LOG(WARNING) << "Ignoring non-NULL receiver for ObjectReference.SetValues on static field " << PrettyField(f);
Elliott Hughes0cf74332012-02-23 23:14:00 -08001517 }
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08001518 }
jeffhao0dfbb7e2012-11-28 15:26:03 -08001519 if (f->IsStatic()) {
1520 o = f->GetDeclaringClass();
1521 }
Elliott Hughesaed4be92011-12-02 16:16:23 -08001522
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001523 JDWP::JdwpTag tag = BasicTagFromDescriptor(FieldHelper(f).GetTypeDescriptor());
Elliott Hughesaed4be92011-12-02 16:16:23 -08001524
1525 if (IsPrimitiveTag(tag)) {
1526 if (tag == JDWP::JT_DOUBLE || tag == JDWP::JT_LONG) {
Elliott Hughes1bac54f2012-03-16 12:48:31 -07001527 CHECK_EQ(width, 8);
Elliott Hughesaed4be92011-12-02 16:16:23 -08001528 f->Set64(o, value);
1529 } else {
Elliott Hughes1bac54f2012-03-16 12:48:31 -07001530 CHECK_LE(width, 4);
Elliott Hughesaed4be92011-12-02 16:16:23 -08001531 f->Set32(o, value);
1532 }
1533 } else {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001534 mirror::Object* v = gRegistry->Get<mirror::Object*>(value);
Elliott Hughes64f574f2013-02-20 14:57:12 -08001535 if (v == ObjectRegistry::kInvalidObject) {
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -08001536 return JDWP::ERR_INVALID_OBJECT;
1537 }
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08001538 if (v != NULL) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001539 mirror::Class* field_type = FieldHelper(f).GetType();
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08001540 if (!field_type->IsAssignableFrom(v->GetClass())) {
1541 return JDWP::ERR_INVALID_OBJECT;
1542 }
1543 }
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -08001544 f->SetObject(o, v);
Elliott Hughesaed4be92011-12-02 16:16:23 -08001545 }
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -08001546
1547 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001548}
1549
Elliott Hughes88d63092013-01-09 09:55:54 -08001550JDWP::JdwpError Dbg::SetFieldValue(JDWP::ObjectId object_id, JDWP::FieldId field_id, uint64_t value,
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001551 int width) {
Elliott Hughes88d63092013-01-09 09:55:54 -08001552 return SetFieldValueImpl(object_id, field_id, value, width, false);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001553}
1554
Elliott Hughes88d63092013-01-09 09:55:54 -08001555JDWP::JdwpError Dbg::SetStaticFieldValue(JDWP::FieldId field_id, uint64_t value, int width) {
1556 return SetFieldValueImpl(0, field_id, value, width, true);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001557}
1558
Elliott Hughes88d63092013-01-09 09:55:54 -08001559std::string Dbg::StringToUtf8(JDWP::ObjectId string_id) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001560 mirror::String* s = gRegistry->Get<mirror::String*>(string_id);
Elliott Hughes68fdbd02011-11-29 19:22:47 -08001561 return s->ToModifiedUtf8();
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001562}
1563
Jeff Hao579b0242013-11-18 13:16:49 -08001564void Dbg::OutputJValue(JDWP::JdwpTag tag, const JValue* return_value, JDWP::ExpandBuf* pReply) {
1565 if (IsPrimitiveTag(tag)) {
1566 expandBufAdd1(pReply, tag);
1567 if (tag == JDWP::JT_BOOLEAN || tag == JDWP::JT_BYTE) {
1568 expandBufAdd1(pReply, return_value->GetI());
1569 } else if (tag == JDWP::JT_CHAR || tag == JDWP::JT_SHORT) {
1570 expandBufAdd2BE(pReply, return_value->GetI());
1571 } else if (tag == JDWP::JT_FLOAT || tag == JDWP::JT_INT) {
1572 expandBufAdd4BE(pReply, return_value->GetI());
1573 } else if (tag == JDWP::JT_DOUBLE || tag == JDWP::JT_LONG) {
1574 expandBufAdd8BE(pReply, return_value->GetJ());
1575 } else {
1576 CHECK_EQ(tag, JDWP::JT_VOID);
1577 }
1578 } else {
1579 mirror::Object* value = return_value->GetL();
1580 expandBufAdd1(pReply, TagFromObject(value));
1581 expandBufAddObjectId(pReply, gRegistry->Add(value));
1582 }
1583}
1584
Elliott Hughes221229c2013-01-08 18:17:50 -08001585JDWP::JdwpError Dbg::GetThreadName(JDWP::ObjectId thread_id, std::string& name) {
jeffhaoa77f0f62012-12-05 17:19:31 -08001586 ScopedObjectAccessUnchecked soa(Thread::Current());
1587 MutexLock mu(soa.Self(), *Locks::thread_list_lock_);
Elliott Hughes221229c2013-01-08 18:17:50 -08001588 Thread* thread;
1589 JDWP::JdwpError error = DecodeThread(soa, thread_id, thread);
1590 if (error != JDWP::ERR_NONE && error != JDWP::ERR_THREAD_NOT_ALIVE) {
1591 return error;
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001592 }
Elliott Hughes221229c2013-01-08 18:17:50 -08001593
1594 // We still need to report the zombie threads' names, so we can't just call Thread::GetThreadName.
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001595 mirror::Object* thread_object = gRegistry->Get<mirror::Object*>(thread_id);
Brian Carlstromea46f952013-07-30 01:26:50 -07001596 mirror::ArtField* java_lang_Thread_name_field =
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001597 soa.DecodeField(WellKnownClasses::java_lang_Thread_name);
1598 mirror::String* s =
1599 reinterpret_cast<mirror::String*>(java_lang_Thread_name_field->GetObject(thread_object));
Elliott Hughes221229c2013-01-08 18:17:50 -08001600 if (s != NULL) {
1601 name = s->ToModifiedUtf8();
1602 }
1603 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001604}
1605
Elliott Hughes221229c2013-01-08 18:17:50 -08001606JDWP::JdwpError Dbg::GetThreadGroup(JDWP::ObjectId thread_id, JDWP::ExpandBuf* pReply) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001607 ScopedObjectAccess soa(Thread::Current());
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001608 mirror::Object* thread_object = gRegistry->Get<mirror::Object*>(thread_id);
Elliott Hughes64f574f2013-02-20 14:57:12 -08001609 if (thread_object == ObjectRegistry::kInvalidObject) {
Elliott Hughes2435a572012-02-17 16:07:41 -08001610 return JDWP::ERR_INVALID_OBJECT;
1611 }
1612
1613 // Okay, so it's an object, but is it actually a thread?
Ian Rogers50b35e22012-10-04 10:09:15 -07001614 MutexLock mu(soa.Self(), *Locks::thread_list_lock_);
Elliott Hughes221229c2013-01-08 18:17:50 -08001615 Thread* thread;
1616 JDWP::JdwpError error = DecodeThread(soa, thread_id, thread);
1617 if (error == JDWP::ERR_THREAD_NOT_ALIVE) {
1618 // Zombie threads are in the null group.
1619 expandBufAddObjectId(pReply, JDWP::ObjectId(0));
1620 return JDWP::ERR_NONE;
1621 }
1622 if (error != JDWP::ERR_NONE) {
1623 return error;
Elliott Hughes2435a572012-02-17 16:07:41 -08001624 }
Elliott Hughes499c5132011-11-17 14:55:11 -08001625
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001626 mirror::Class* c = Runtime::Current()->GetClassLinker()->FindSystemClass("Ljava/lang/Thread;");
Elliott Hughes499c5132011-11-17 14:55:11 -08001627 CHECK(c != NULL);
Brian Carlstromea46f952013-07-30 01:26:50 -07001628 mirror::ArtField* f = c->FindInstanceField("group", "Ljava/lang/ThreadGroup;");
Elliott Hughes499c5132011-11-17 14:55:11 -08001629 CHECK(f != NULL);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001630 mirror::Object* group = f->GetObject(thread_object);
Elliott Hughes499c5132011-11-17 14:55:11 -08001631 CHECK(group != NULL);
Elliott Hughes2435a572012-02-17 16:07:41 -08001632 JDWP::ObjectId thread_group_id = gRegistry->Add(group);
1633
1634 expandBufAddObjectId(pReply, thread_group_id);
1635 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001636}
1637
Elliott Hughes88d63092013-01-09 09:55:54 -08001638std::string Dbg::GetThreadGroupName(JDWP::ObjectId thread_group_id) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001639 ScopedObjectAccess soa(Thread::Current());
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001640 mirror::Object* thread_group = gRegistry->Get<mirror::Object*>(thread_group_id);
Elliott Hughes499c5132011-11-17 14:55:11 -08001641 CHECK(thread_group != NULL);
1642
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001643 mirror::Class* c = Runtime::Current()->GetClassLinker()->FindSystemClass("Ljava/lang/ThreadGroup;");
Elliott Hughes499c5132011-11-17 14:55:11 -08001644 CHECK(c != NULL);
Brian Carlstromea46f952013-07-30 01:26:50 -07001645 mirror::ArtField* f = c->FindInstanceField("name", "Ljava/lang/String;");
Elliott Hughes499c5132011-11-17 14:55:11 -08001646 CHECK(f != NULL);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001647 mirror::String* s = reinterpret_cast<mirror::String*>(f->GetObject(thread_group));
Elliott Hughes499c5132011-11-17 14:55:11 -08001648 return s->ToModifiedUtf8();
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001649}
1650
Elliott Hughes88d63092013-01-09 09:55:54 -08001651JDWP::ObjectId Dbg::GetThreadGroupParent(JDWP::ObjectId thread_group_id) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001652 mirror::Object* thread_group = gRegistry->Get<mirror::Object*>(thread_group_id);
Elliott Hughes4e235312011-12-02 11:34:15 -08001653 CHECK(thread_group != NULL);
1654
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001655 mirror::Class* c = Runtime::Current()->GetClassLinker()->FindSystemClass("Ljava/lang/ThreadGroup;");
Elliott Hughes4e235312011-12-02 11:34:15 -08001656 CHECK(c != NULL);
Brian Carlstromea46f952013-07-30 01:26:50 -07001657 mirror::ArtField* f = c->FindInstanceField("parent", "Ljava/lang/ThreadGroup;");
Elliott Hughes4e235312011-12-02 11:34:15 -08001658 CHECK(f != NULL);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001659 mirror::Object* parent = f->GetObject(thread_group);
Elliott Hughes4e235312011-12-02 11:34:15 -08001660 return gRegistry->Add(parent);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001661}
1662
1663JDWP::ObjectId Dbg::GetSystemThreadGroupId() {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001664 ScopedObjectAccessUnchecked soa(Thread::Current());
Brian Carlstromea46f952013-07-30 01:26:50 -07001665 mirror::ArtField* f = soa.DecodeField(WellKnownClasses::java_lang_ThreadGroup_systemThreadGroup);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001666 mirror::Object* group = f->GetObject(f->GetDeclaringClass());
Ian Rogers365c1022012-06-22 15:05:28 -07001667 return gRegistry->Add(group);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001668}
1669
1670JDWP::ObjectId Dbg::GetMainThreadGroupId() {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001671 ScopedObjectAccess soa(Thread::Current());
Brian Carlstromea46f952013-07-30 01:26:50 -07001672 mirror::ArtField* f = soa.DecodeField(WellKnownClasses::java_lang_ThreadGroup_mainThreadGroup);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001673 mirror::Object* group = f->GetObject(f->GetDeclaringClass());
Ian Rogers365c1022012-06-22 15:05:28 -07001674 return gRegistry->Add(group);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001675}
1676
Jeff Hao920af3e2013-08-28 15:46:38 -07001677JDWP::JdwpThreadStatus Dbg::ToJdwpThreadStatus(ThreadState state) {
1678 switch (state) {
1679 case kBlocked:
1680 return JDWP::TS_MONITOR;
1681 case kNative:
1682 case kRunnable:
1683 case kSuspended:
1684 return JDWP::TS_RUNNING;
1685 case kSleeping:
1686 return JDWP::TS_SLEEPING;
1687 case kStarting:
1688 case kTerminated:
1689 return JDWP::TS_ZOMBIE;
1690 case kTimedWaiting:
1691 case kWaitingForDebuggerSend:
1692 case kWaitingForDebuggerSuspension:
1693 case kWaitingForDebuggerToAttach:
1694 case kWaitingForGcToComplete:
1695 case kWaitingForCheckPointsToRun:
1696 case kWaitingForJniOnLoad:
1697 case kWaitingForSignalCatcherOutput:
1698 case kWaitingInMainDebuggerLoop:
1699 case kWaitingInMainSignalCatcherLoop:
1700 case kWaitingPerformingGc:
1701 case kWaiting:
1702 return JDWP::TS_WAIT;
1703 // Don't add a 'default' here so the compiler can spot incompatible enum changes.
1704 }
1705 LOG(FATAL) << "Unknown thread state: " << state;
1706 return JDWP::TS_ZOMBIE;
1707}
1708
Elliott Hughes221229c2013-01-08 18:17:50 -08001709JDWP::JdwpError Dbg::GetThreadStatus(JDWP::ObjectId thread_id, JDWP::JdwpThreadStatus* pThreadStatus, JDWP::JdwpSuspendStatus* pSuspendStatus) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001710 ScopedObjectAccess soa(Thread::Current());
Elliott Hughes499c5132011-11-17 14:55:11 -08001711
Elliott Hughes9e0c1752013-01-09 14:02:58 -08001712 *pSuspendStatus = JDWP::SUSPEND_STATUS_NOT_SUSPENDED;
1713
Ian Rogers50b35e22012-10-04 10:09:15 -07001714 MutexLock mu(soa.Self(), *Locks::thread_list_lock_);
Elliott Hughes221229c2013-01-08 18:17:50 -08001715 Thread* thread;
1716 JDWP::JdwpError error = DecodeThread(soa, thread_id, thread);
1717 if (error != JDWP::ERR_NONE) {
1718 if (error == JDWP::ERR_THREAD_NOT_ALIVE) {
1719 *pThreadStatus = JDWP::TS_ZOMBIE;
Elliott Hughes221229c2013-01-08 18:17:50 -08001720 return JDWP::ERR_NONE;
1721 }
1722 return error;
Elliott Hughes499c5132011-11-17 14:55:11 -08001723 }
1724
Elliott Hughes9e0c1752013-01-09 14:02:58 -08001725 if (IsSuspendedForDebugger(soa, thread)) {
1726 *pSuspendStatus = JDWP::SUSPEND_STATUS_SUSPENDED;
Elliott Hughes499c5132011-11-17 14:55:11 -08001727 }
1728
Jeff Hao920af3e2013-08-28 15:46:38 -07001729 *pThreadStatus = ToJdwpThreadStatus(thread->GetState());
Elliott Hughes221229c2013-01-08 18:17:50 -08001730 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001731}
1732
Elliott Hughes221229c2013-01-08 18:17:50 -08001733JDWP::JdwpError Dbg::GetThreadDebugSuspendCount(JDWP::ObjectId thread_id, JDWP::ExpandBuf* pReply) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001734 ScopedObjectAccess soa(Thread::Current());
Ian Rogers50b35e22012-10-04 10:09:15 -07001735 MutexLock mu(soa.Self(), *Locks::thread_list_lock_);
Elliott Hughes221229c2013-01-08 18:17:50 -08001736 Thread* thread;
1737 JDWP::JdwpError error = DecodeThread(soa, thread_id, thread);
1738 if (error != JDWP::ERR_NONE) {
1739 return error;
Elliott Hughes2435a572012-02-17 16:07:41 -08001740 }
Ian Rogers50b35e22012-10-04 10:09:15 -07001741 MutexLock mu2(soa.Self(), *Locks::thread_suspend_count_lock_);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001742 expandBufAdd4BE(pReply, thread->GetDebugSuspendCount());
Elliott Hughes2435a572012-02-17 16:07:41 -08001743 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001744}
1745
Elliott Hughesf9501702013-01-11 11:22:27 -08001746JDWP::JdwpError Dbg::Interrupt(JDWP::ObjectId thread_id) {
1747 ScopedObjectAccess soa(Thread::Current());
1748 MutexLock mu(soa.Self(), *Locks::thread_list_lock_);
1749 Thread* thread;
1750 JDWP::JdwpError error = DecodeThread(soa, thread_id, thread);
1751 if (error != JDWP::ERR_NONE) {
1752 return error;
1753 }
1754 thread->Interrupt();
1755 return JDWP::ERR_NONE;
1756}
1757
Elliott Hughescaf76542012-06-28 16:08:22 -07001758void Dbg::GetThreads(JDWP::ObjectId thread_group_id, std::vector<JDWP::ObjectId>& thread_ids) {
Ian Rogers365c1022012-06-22 15:05:28 -07001759 class ThreadListVisitor {
1760 public:
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001761 ThreadListVisitor(const ScopedObjectAccessUnchecked& soa, mirror::Object* desired_thread_group,
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001762 std::vector<JDWP::ObjectId>& thread_ids)
Ian Rogersb726dcb2012-09-05 08:57:23 -07001763 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_)
jeffhao0dfbb7e2012-11-28 15:26:03 -08001764 : soa_(soa), desired_thread_group_(desired_thread_group), thread_ids_(thread_ids) {}
Ian Rogers365c1022012-06-22 15:05:28 -07001765
Elliott Hughesa2155262011-11-16 16:26:58 -08001766 static void Visit(Thread* t, void* arg) {
1767 reinterpret_cast<ThreadListVisitor*>(arg)->Visit(t);
1768 }
1769
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001770 // TODO: Enable annotalysis. We know lock is held in constructor, but abstraction confuses
1771 // annotalysis.
1772 void Visit(Thread* t) NO_THREAD_SAFETY_ANALYSIS {
Elliott Hughesa2155262011-11-16 16:26:58 -08001773 if (t == Dbg::GetDebugThread()) {
1774 // Skip the JDWP thread. Some debuggers get bent out of shape when they can't suspend and
1775 // query all threads, so it's easier if we just don't tell them about this thread.
1776 return;
1777 }
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001778 mirror::Object* peer = t->GetPeer();
jeffhao0dfbb7e2012-11-28 15:26:03 -08001779 if (IsInDesiredThreadGroup(peer)) {
Ian Rogers120f1c72012-09-28 17:17:10 -07001780 thread_ids_.push_back(gRegistry->Add(peer));
Elliott Hughesa2155262011-11-16 16:26:58 -08001781 }
1782 }
1783
Ian Rogers365c1022012-06-22 15:05:28 -07001784 private:
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001785 bool IsInDesiredThreadGroup(mirror::Object* peer)
jeffhao0dfbb7e2012-11-28 15:26:03 -08001786 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
jeffhao0dfbb7e2012-11-28 15:26:03 -08001787 // peer might be NULL if the thread is still starting up.
1788 if (peer == NULL) {
1789 // We can't tell the debugger about this thread yet.
1790 // TODO: if we identified threads to the debugger by their Thread*
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001791 // rather than their peer's mirror::Object*, we could fix this.
jeffhao0dfbb7e2012-11-28 15:26:03 -08001792 // Doing so might help us report ZOMBIE threads too.
1793 return false;
1794 }
jeffhaoc1e04902012-12-13 12:41:10 -08001795 // Do we want threads from all thread groups?
1796 if (desired_thread_group_ == NULL) {
1797 return true;
1798 }
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001799 mirror::Object* group = soa_.DecodeField(WellKnownClasses::java_lang_Thread_group)->GetObject(peer);
jeffhao0dfbb7e2012-11-28 15:26:03 -08001800 return (group == desired_thread_group_);
1801 }
1802
Mathieu Chartierdbe6f462012-09-25 16:54:50 -07001803 const ScopedObjectAccessUnchecked& soa_;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001804 mirror::Object* const desired_thread_group_;
Elliott Hughescaf76542012-06-28 16:08:22 -07001805 std::vector<JDWP::ObjectId>& thread_ids_;
Elliott Hughesa2155262011-11-16 16:26:58 -08001806 };
1807
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001808 ScopedObjectAccessUnchecked soa(Thread::Current());
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001809 mirror::Object* thread_group = gRegistry->Get<mirror::Object*>(thread_group_id);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001810 ThreadListVisitor tlv(soa, thread_group, thread_ids);
Ian Rogers50b35e22012-10-04 10:09:15 -07001811 MutexLock mu(soa.Self(), *Locks::thread_list_lock_);
Elliott Hughesf8349362012-06-18 15:00:06 -07001812 Runtime::Current()->GetThreadList()->ForEach(ThreadListVisitor::Visit, &tlv);
Elliott Hughescaf76542012-06-28 16:08:22 -07001813}
Elliott Hughesa2155262011-11-16 16:26:58 -08001814
Elliott Hughescaf76542012-06-28 16:08:22 -07001815void Dbg::GetChildThreadGroups(JDWP::ObjectId thread_group_id, std::vector<JDWP::ObjectId>& child_thread_group_ids) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001816 ScopedObjectAccess soa(Thread::Current());
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001817 mirror::Object* thread_group = gRegistry->Get<mirror::Object*>(thread_group_id);
Elliott Hughescaf76542012-06-28 16:08:22 -07001818
1819 // Get the ArrayList<ThreadGroup> "groups" out of this thread group...
Brian Carlstromea46f952013-07-30 01:26:50 -07001820 mirror::ArtField* groups_field = thread_group->GetClass()->FindInstanceField("groups", "Ljava/util/List;");
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001821 mirror::Object* groups_array_list = groups_field->GetObject(thread_group);
Elliott Hughescaf76542012-06-28 16:08:22 -07001822
1823 // Get the array and size out of the ArrayList<ThreadGroup>...
Brian Carlstromea46f952013-07-30 01:26:50 -07001824 mirror::ArtField* array_field = groups_array_list->GetClass()->FindInstanceField("array", "[Ljava/lang/Object;");
1825 mirror::ArtField* size_field = groups_array_list->GetClass()->FindInstanceField("size", "I");
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001826 mirror::ObjectArray<mirror::Object>* groups_array =
1827 array_field->GetObject(groups_array_list)->AsObjectArray<mirror::Object>();
Elliott Hughescaf76542012-06-28 16:08:22 -07001828 const int32_t size = size_field->GetInt(groups_array_list);
1829
1830 // Copy the first 'size' elements out of the array into the result.
1831 for (int32_t i = 0; i < size; ++i) {
1832 child_thread_group_ids.push_back(gRegistry->Add(groups_array->Get(i)));
Elliott Hughesa2155262011-11-16 16:26:58 -08001833 }
1834}
1835
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001836static int GetStackDepth(Thread* thread)
Ian Rogersb726dcb2012-09-05 08:57:23 -07001837 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Ian Rogers0399dde2012-06-06 17:09:28 -07001838 struct CountStackDepthVisitor : public StackVisitor {
Brian Carlstrom93ba8932013-07-17 21:31:49 -07001839 explicit CountStackDepthVisitor(Thread* thread)
Ian Rogers7a22fa62013-01-23 12:16:16 -08001840 : StackVisitor(thread, NULL), depth(0) {}
Ian Rogers0399dde2012-06-06 17:09:28 -07001841
Elliott Hughes64f574f2013-02-20 14:57:12 -08001842 // TODO: Enable annotalysis. We know lock is held in constructor, but abstraction confuses
1843 // annotalysis.
1844 bool VisitFrame() NO_THREAD_SAFETY_ANALYSIS {
Ian Rogers0399dde2012-06-06 17:09:28 -07001845 if (!GetMethod()->IsRuntimeMethod()) {
Elliott Hughesf8a2df72011-12-01 12:19:54 -08001846 ++depth;
1847 }
Elliott Hughes530fa002012-03-12 11:44:49 -07001848 return true;
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001849 }
1850 size_t depth;
1851 };
Elliott Hughes08fc03a2012-06-26 17:34:00 -07001852
Ian Rogers7a22fa62013-01-23 12:16:16 -08001853 CountStackDepthVisitor visitor(thread);
Ian Rogers0399dde2012-06-06 17:09:28 -07001854 visitor.WalkStack();
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001855 return visitor.depth;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001856}
1857
Elliott Hughes221229c2013-01-08 18:17:50 -08001858JDWP::JdwpError Dbg::GetThreadFrameCount(JDWP::ObjectId thread_id, size_t& result) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001859 ScopedObjectAccess soa(Thread::Current());
jeffhaoa77f0f62012-12-05 17:19:31 -08001860 MutexLock mu(soa.Self(), *Locks::thread_list_lock_);
Elliott Hughes221229c2013-01-08 18:17:50 -08001861 Thread* thread;
1862 JDWP::JdwpError error = DecodeThread(soa, thread_id, thread);
1863 if (error != JDWP::ERR_NONE) {
1864 return error;
1865 }
Elliott Hughesf15f4a02013-01-09 10:09:38 -08001866 if (!IsSuspendedForDebugger(soa, thread)) {
1867 return JDWP::ERR_THREAD_NOT_SUSPENDED;
1868 }
Elliott Hughes221229c2013-01-08 18:17:50 -08001869 result = GetStackDepth(thread);
1870 return JDWP::ERR_NONE;
Elliott Hughes86964332012-02-15 19:37:42 -08001871}
1872
Ian Rogers306057f2012-11-26 12:45:53 -08001873JDWP::JdwpError Dbg::GetThreadFrames(JDWP::ObjectId thread_id, size_t start_frame,
1874 size_t frame_count, JDWP::ExpandBuf* buf) {
Elliott Hughes6e9d22c2012-06-22 15:02:37 -07001875 class GetFrameVisitor : public StackVisitor {
1876 public:
Ian Rogers7a22fa62013-01-23 12:16:16 -08001877 GetFrameVisitor(Thread* thread, size_t start_frame, size_t frame_count, JDWP::ExpandBuf* buf)
Ian Rogersb726dcb2012-09-05 08:57:23 -07001878 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_)
Ian Rogers7a22fa62013-01-23 12:16:16 -08001879 : StackVisitor(thread, NULL), depth_(0),
Elliott Hughes6e9d22c2012-06-22 15:02:37 -07001880 start_frame_(start_frame), frame_count_(frame_count), buf_(buf) {
1881 expandBufAdd4BE(buf_, frame_count_);
Elliott Hughes03181a82011-11-17 17:22:21 -08001882 }
Ian Rogers0399dde2012-06-06 17:09:28 -07001883
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001884 // TODO: Enable annotalysis. We know lock is held in constructor, but abstraction confuses
1885 // annotalysis.
1886 virtual bool VisitFrame() NO_THREAD_SAFETY_ANALYSIS {
Ian Rogers0399dde2012-06-06 17:09:28 -07001887 if (GetMethod()->IsRuntimeMethod()) {
Brian Carlstrom7934ac22013-07-26 10:54:15 -07001888 return true; // The debugger can't do anything useful with a frame that has no Method*.
Elliott Hughes03181a82011-11-17 17:22:21 -08001889 }
Elliott Hughes6e9d22c2012-06-22 15:02:37 -07001890 if (depth_ >= start_frame_ + frame_count_) {
Elliott Hughes530fa002012-03-12 11:44:49 -07001891 return false;
Elliott Hughes03181a82011-11-17 17:22:21 -08001892 }
Elliott Hughes6e9d22c2012-06-22 15:02:37 -07001893 if (depth_ >= start_frame_) {
1894 JDWP::FrameId frame_id(GetFrameId());
1895 JDWP::JdwpLocation location;
1896 SetLocation(location, GetMethod(), GetDexPc());
Elliott Hughes7baf96f2012-06-22 16:33:50 -07001897 VLOG(jdwp) << StringPrintf(" Frame %3zd: id=%3lld ", depth_, frame_id) << location;
Elliott Hughes6e9d22c2012-06-22 15:02:37 -07001898 expandBufAdd8BE(buf_, frame_id);
1899 expandBufAddLocation(buf_, location);
1900 }
1901 ++depth_;
Elliott Hughes530fa002012-03-12 11:44:49 -07001902 return true;
Elliott Hughes03181a82011-11-17 17:22:21 -08001903 }
Elliott Hughes6e9d22c2012-06-22 15:02:37 -07001904
1905 private:
1906 size_t depth_;
1907 const size_t start_frame_;
1908 const size_t frame_count_;
1909 JDWP::ExpandBuf* buf_;
Elliott Hughes03181a82011-11-17 17:22:21 -08001910 };
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001911
1912 ScopedObjectAccessUnchecked soa(Thread::Current());
jeffhaoa77f0f62012-12-05 17:19:31 -08001913 MutexLock mu(soa.Self(), *Locks::thread_list_lock_);
Elliott Hughes221229c2013-01-08 18:17:50 -08001914 Thread* thread;
1915 JDWP::JdwpError error = DecodeThread(soa, thread_id, thread);
1916 if (error != JDWP::ERR_NONE) {
1917 return error;
1918 }
Elliott Hughesf15f4a02013-01-09 10:09:38 -08001919 if (!IsSuspendedForDebugger(soa, thread)) {
1920 return JDWP::ERR_THREAD_NOT_SUSPENDED;
1921 }
Ian Rogers7a22fa62013-01-23 12:16:16 -08001922 GetFrameVisitor visitor(thread, start_frame, frame_count, buf);
Ian Rogers0399dde2012-06-06 17:09:28 -07001923 visitor.WalkStack();
Elliott Hughes6e9d22c2012-06-22 15:02:37 -07001924 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001925}
1926
1927JDWP::ObjectId Dbg::GetThreadSelfId() {
Mathieu Chartierdbe6f462012-09-25 16:54:50 -07001928 ScopedObjectAccessUnchecked soa(Thread::Current());
Ian Rogerscfaa4552012-11-26 21:00:08 -08001929 return gRegistry->Add(soa.Self()->GetPeer());
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001930}
1931
Elliott Hughes475fc232011-10-25 15:00:35 -07001932void Dbg::SuspendVM() {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001933 Runtime::Current()->GetThreadList()->SuspendAllForDebugger();
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001934}
1935
1936void Dbg::ResumeVM() {
Elliott Hughesc61a2672012-06-21 14:52:29 -07001937 Runtime::Current()->GetThreadList()->UndoDebuggerSuspensions();
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001938}
1939
Elliott Hughes221229c2013-01-08 18:17:50 -08001940JDWP::JdwpError Dbg::SuspendThread(JDWP::ObjectId thread_id, bool request_suspension) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001941 ScopedLocalRef<jobject> peer(Thread::Current()->GetJniEnv(), NULL);
1942 {
1943 ScopedObjectAccess soa(Thread::Current());
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001944 peer.reset(soa.AddLocalReference<jobject>(gRegistry->Get<mirror::Object*>(thread_id)));
Elliott Hughes4e235312011-12-02 11:34:15 -08001945 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001946 if (peer.get() == NULL) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001947 return JDWP::ERR_THREAD_NOT_ALIVE;
1948 }
1949 // Suspend thread to build stack trace.
Elliott Hughesf327e072013-01-09 16:01:26 -08001950 bool timed_out;
Ian Rogersd9c4fc92013-10-01 19:45:43 -07001951 Thread* thread = ThreadList::SuspendThreadByPeer(peer.get(), request_suspension, true,
1952 &timed_out);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001953 if (thread != NULL) {
1954 return JDWP::ERR_NONE;
Elliott Hughesf327e072013-01-09 16:01:26 -08001955 } else if (timed_out) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001956 return JDWP::ERR_INTERNAL;
1957 } else {
1958 return JDWP::ERR_THREAD_NOT_ALIVE;
1959 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001960}
1961
Elliott Hughes221229c2013-01-08 18:17:50 -08001962void Dbg::ResumeThread(JDWP::ObjectId thread_id) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001963 ScopedObjectAccessUnchecked soa(Thread::Current());
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001964 mirror::Object* peer = gRegistry->Get<mirror::Object*>(thread_id);
jeffhaoa77f0f62012-12-05 17:19:31 -08001965 Thread* thread;
1966 {
1967 MutexLock mu(soa.Self(), *Locks::thread_list_lock_);
1968 thread = Thread::FromManagedThread(soa, peer);
1969 }
Elliott Hughes4e235312011-12-02 11:34:15 -08001970 if (thread == NULL) {
1971 LOG(WARNING) << "No such thread for resume: " << peer;
1972 return;
1973 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001974 bool needs_resume;
1975 {
Ian Rogers50b35e22012-10-04 10:09:15 -07001976 MutexLock mu2(soa.Self(), *Locks::thread_suspend_count_lock_);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001977 needs_resume = thread->GetSuspendCount() > 0;
1978 }
1979 if (needs_resume) {
Elliott Hughes546b9862012-06-20 16:06:13 -07001980 Runtime::Current()->GetThreadList()->Resume(thread, true);
1981 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001982}
1983
1984void Dbg::SuspendSelf() {
Elliott Hughes475fc232011-10-25 15:00:35 -07001985 Runtime::Current()->GetThreadList()->SuspendSelfForDebugger();
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001986}
1987
Ian Rogers0399dde2012-06-06 17:09:28 -07001988struct GetThisVisitor : public StackVisitor {
Ian Rogers7a22fa62013-01-23 12:16:16 -08001989 GetThisVisitor(Thread* thread, Context* context, JDWP::FrameId frame_id)
Ian Rogersb726dcb2012-09-05 08:57:23 -07001990 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_)
Ian Rogers7a22fa62013-01-23 12:16:16 -08001991 : StackVisitor(thread, context), this_object(NULL), frame_id(frame_id) {}
Ian Rogers0399dde2012-06-06 17:09:28 -07001992
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001993 // TODO: Enable annotalysis. We know lock is held in constructor, but abstraction confuses
1994 // annotalysis.
1995 virtual bool VisitFrame() NO_THREAD_SAFETY_ANALYSIS {
Elliott Hughes6e9d22c2012-06-22 15:02:37 -07001996 if (frame_id != GetFrameId()) {
Ian Rogers0399dde2012-06-06 17:09:28 -07001997 return true; // continue
Ian Rogers0399dde2012-06-06 17:09:28 -07001998 } else {
Ian Rogers62d6c772013-02-27 08:32:07 -08001999 this_object = GetThisObject();
2000 return false;
Ian Rogers0399dde2012-06-06 17:09:28 -07002001 }
Elliott Hughes86b00102011-12-05 17:54:26 -08002002 }
Ian Rogers0399dde2012-06-06 17:09:28 -07002003
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002004 mirror::Object* this_object;
Elliott Hughes6e9d22c2012-06-22 15:02:37 -07002005 JDWP::FrameId frame_id;
Ian Rogers0399dde2012-06-06 17:09:28 -07002006};
2007
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002008JDWP::JdwpError Dbg::GetThisObject(JDWP::ObjectId thread_id, JDWP::FrameId frame_id,
2009 JDWP::ObjectId* result) {
2010 ScopedObjectAccessUnchecked soa(Thread::Current());
2011 Thread* thread;
2012 {
Ian Rogers50b35e22012-10-04 10:09:15 -07002013 MutexLock mu(soa.Self(), *Locks::thread_list_lock_);
Elliott Hughes221229c2013-01-08 18:17:50 -08002014 JDWP::JdwpError error = DecodeThread(soa, thread_id, thread);
2015 if (error != JDWP::ERR_NONE) {
2016 return error;
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002017 }
Elliott Hughes9e0c1752013-01-09 14:02:58 -08002018 if (!IsSuspendedForDebugger(soa, thread)) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002019 return JDWP::ERR_THREAD_NOT_SUSPENDED;
2020 }
Elliott Hughes6e9d22c2012-06-22 15:02:37 -07002021 }
Elliott Hughescaf76542012-06-28 16:08:22 -07002022 UniquePtr<Context> context(Context::Create());
Ian Rogers7a22fa62013-01-23 12:16:16 -08002023 GetThisVisitor visitor(thread, context.get(), frame_id);
Ian Rogers0399dde2012-06-06 17:09:28 -07002024 visitor.WalkStack();
Elliott Hughes6e9d22c2012-06-22 15:02:37 -07002025 *result = gRegistry->Add(visitor.this_object);
2026 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002027}
2028
Elliott Hughes88d63092013-01-09 09:55:54 -08002029void Dbg::GetLocalValue(JDWP::ObjectId thread_id, JDWP::FrameId frame_id, int slot, JDWP::JdwpTag tag,
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002030 uint8_t* buf, size_t width) {
Ian Rogers0399dde2012-06-06 17:09:28 -07002031 struct GetLocalVisitor : public StackVisitor {
Ian Rogers7a22fa62013-01-23 12:16:16 -08002032 GetLocalVisitor(Thread* thread, Context* context, JDWP::FrameId frame_id, int slot,
2033 JDWP::JdwpTag tag, uint8_t* buf, size_t width)
Ian Rogersb726dcb2012-09-05 08:57:23 -07002034 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_)
Ian Rogers7a22fa62013-01-23 12:16:16 -08002035 : StackVisitor(thread, context), frame_id_(frame_id), slot_(slot), tag_(tag),
Ian Rogersca190662012-06-26 15:45:57 -07002036 buf_(buf), width_(width) {}
2037
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002038 // TODO: Enable annotalysis. We know lock is held in constructor, but abstraction confuses
2039 // annotalysis.
2040 bool VisitFrame() NO_THREAD_SAFETY_ANALYSIS {
Ian Rogers0399dde2012-06-06 17:09:28 -07002041 if (GetFrameId() != frame_id_) {
2042 return true; // Not our frame, carry on.
Elliott Hughesdbb40792011-11-18 17:05:22 -08002043 }
Ian Rogers0399dde2012-06-06 17:09:28 -07002044 // TODO: check that the tag is compatible with the actual type of the slot!
Brian Carlstromea46f952013-07-30 01:26:50 -07002045 mirror::ArtMethod* m = GetMethod();
Ian Rogers0399dde2012-06-06 17:09:28 -07002046 uint16_t reg = DemangleSlot(slot_, m);
Elliott Hughesdbb40792011-11-18 17:05:22 -08002047
Ian Rogers0399dde2012-06-06 17:09:28 -07002048 switch (tag_) {
2049 case JDWP::JT_BOOLEAN:
2050 {
2051 CHECK_EQ(width_, 1U);
Ian Rogers2bcb4a42012-11-08 10:39:18 -08002052 uint32_t intVal = GetVReg(m, reg, kIntVReg);
Ian Rogers0399dde2012-06-06 17:09:28 -07002053 VLOG(jdwp) << "get boolean local " << reg << " = " << intVal;
2054 JDWP::Set1(buf_+1, intVal != 0);
2055 }
2056 break;
2057 case JDWP::JT_BYTE:
2058 {
2059 CHECK_EQ(width_, 1U);
Ian Rogers2bcb4a42012-11-08 10:39:18 -08002060 uint32_t intVal = GetVReg(m, reg, kIntVReg);
Ian Rogers0399dde2012-06-06 17:09:28 -07002061 VLOG(jdwp) << "get byte local " << reg << " = " << intVal;
2062 JDWP::Set1(buf_+1, intVal);
2063 }
2064 break;
2065 case JDWP::JT_SHORT:
2066 case JDWP::JT_CHAR:
2067 {
2068 CHECK_EQ(width_, 2U);
Ian Rogers2bcb4a42012-11-08 10:39:18 -08002069 uint32_t intVal = GetVReg(m, reg, kIntVReg);
Ian Rogers0399dde2012-06-06 17:09:28 -07002070 VLOG(jdwp) << "get short/char local " << reg << " = " << intVal;
2071 JDWP::Set2BE(buf_+1, intVal);
2072 }
2073 break;
2074 case JDWP::JT_INT:
Ian Rogers2bcb4a42012-11-08 10:39:18 -08002075 {
2076 CHECK_EQ(width_, 4U);
2077 uint32_t intVal = GetVReg(m, reg, kIntVReg);
2078 VLOG(jdwp) << "get int local " << reg << " = " << intVal;
2079 JDWP::Set4BE(buf_+1, intVal);
2080 }
2081 break;
Ian Rogers0399dde2012-06-06 17:09:28 -07002082 case JDWP::JT_FLOAT:
2083 {
2084 CHECK_EQ(width_, 4U);
Ian Rogers2bcb4a42012-11-08 10:39:18 -08002085 uint32_t intVal = GetVReg(m, reg, kFloatVReg);
Ian Rogers0399dde2012-06-06 17:09:28 -07002086 VLOG(jdwp) << "get int/float local " << reg << " = " << intVal;
2087 JDWP::Set4BE(buf_+1, intVal);
2088 }
2089 break;
2090 case JDWP::JT_ARRAY:
2091 {
2092 CHECK_EQ(width_, sizeof(JDWP::ObjectId));
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002093 mirror::Object* o = reinterpret_cast<mirror::Object*>(GetVReg(m, reg, kReferenceVReg));
Ian Rogers0399dde2012-06-06 17:09:28 -07002094 VLOG(jdwp) << "get array local " << reg << " = " << o;
Mathieu Chartier590fee92013-09-13 13:46:47 -07002095 if (!Runtime::Current()->GetHeap()->IsValidObjectAddress(o)) {
Ian Rogers0399dde2012-06-06 17:09:28 -07002096 LOG(FATAL) << "Register " << reg << " expected to hold array: " << o;
2097 }
2098 JDWP::SetObjectId(buf_+1, gRegistry->Add(o));
2099 }
2100 break;
2101 case JDWP::JT_CLASS_LOADER:
2102 case JDWP::JT_CLASS_OBJECT:
2103 case JDWP::JT_OBJECT:
2104 case JDWP::JT_STRING:
2105 case JDWP::JT_THREAD:
2106 case JDWP::JT_THREAD_GROUP:
2107 {
2108 CHECK_EQ(width_, sizeof(JDWP::ObjectId));
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002109 mirror::Object* o = reinterpret_cast<mirror::Object*>(GetVReg(m, reg, kReferenceVReg));
Ian Rogers0399dde2012-06-06 17:09:28 -07002110 VLOG(jdwp) << "get object local " << reg << " = " << o;
Mathieu Chartier590fee92013-09-13 13:46:47 -07002111 if (!Runtime::Current()->GetHeap()->IsValidObjectAddress(o)) {
Ian Rogers0399dde2012-06-06 17:09:28 -07002112 LOG(FATAL) << "Register " << reg << " expected to hold object: " << o;
2113 }
2114 tag_ = TagFromObject(o);
2115 JDWP::SetObjectId(buf_+1, gRegistry->Add(o));
2116 }
2117 break;
2118 case JDWP::JT_DOUBLE:
Ian Rogers2bcb4a42012-11-08 10:39:18 -08002119 {
2120 CHECK_EQ(width_, 8U);
2121 uint32_t lo = GetVReg(m, reg, kDoubleLoVReg);
2122 uint64_t hi = GetVReg(m, reg + 1, kDoubleHiVReg);
2123 uint64_t longVal = (hi << 32) | lo;
2124 VLOG(jdwp) << "get double/long local " << hi << ":" << lo << " = " << longVal;
2125 JDWP::Set8BE(buf_+1, longVal);
2126 }
2127 break;
Ian Rogers0399dde2012-06-06 17:09:28 -07002128 case JDWP::JT_LONG:
2129 {
2130 CHECK_EQ(width_, 8U);
Ian Rogers2bcb4a42012-11-08 10:39:18 -08002131 uint32_t lo = GetVReg(m, reg, kLongLoVReg);
2132 uint64_t hi = GetVReg(m, reg + 1, kLongHiVReg);
Ian Rogers0399dde2012-06-06 17:09:28 -07002133 uint64_t longVal = (hi << 32) | lo;
2134 VLOG(jdwp) << "get double/long local " << hi << ":" << lo << " = " << longVal;
2135 JDWP::Set8BE(buf_+1, longVal);
2136 }
2137 break;
2138 default:
2139 LOG(FATAL) << "Unknown tag " << tag_;
2140 break;
2141 }
2142
2143 // Prepend tag, which may have been updated.
2144 JDWP::Set1(buf_, tag_);
2145 return false;
2146 }
2147
2148 const JDWP::FrameId frame_id_;
2149 const int slot_;
2150 JDWP::JdwpTag tag_;
2151 uint8_t* const buf_;
2152 const size_t width_;
2153 };
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002154
2155 ScopedObjectAccessUnchecked soa(Thread::Current());
jeffhaoa77f0f62012-12-05 17:19:31 -08002156 MutexLock mu(soa.Self(), *Locks::thread_list_lock_);
Elliott Hughes221229c2013-01-08 18:17:50 -08002157 Thread* thread;
2158 JDWP::JdwpError error = DecodeThread(soa, thread_id, thread);
2159 if (error != JDWP::ERR_NONE) {
2160 return;
2161 }
Ian Rogers0399dde2012-06-06 17:09:28 -07002162 UniquePtr<Context> context(Context::Create());
Ian Rogers7a22fa62013-01-23 12:16:16 -08002163 GetLocalVisitor visitor(thread, context.get(), frame_id, slot, tag, buf, width);
Ian Rogers0399dde2012-06-06 17:09:28 -07002164 visitor.WalkStack();
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002165}
2166
Elliott Hughes88d63092013-01-09 09:55:54 -08002167void Dbg::SetLocalValue(JDWP::ObjectId thread_id, JDWP::FrameId frame_id, int slot, JDWP::JdwpTag tag,
Ian Rogers0399dde2012-06-06 17:09:28 -07002168 uint64_t value, size_t width) {
2169 struct SetLocalVisitor : public StackVisitor {
Ian Rogers7a22fa62013-01-23 12:16:16 -08002170 SetLocalVisitor(Thread* thread, Context* context,
Ian Rogers0399dde2012-06-06 17:09:28 -07002171 JDWP::FrameId frame_id, int slot, JDWP::JdwpTag tag, uint64_t value,
Ian Rogersca190662012-06-26 15:45:57 -07002172 size_t width)
Ian Rogersb726dcb2012-09-05 08:57:23 -07002173 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_)
Ian Rogers7a22fa62013-01-23 12:16:16 -08002174 : StackVisitor(thread, context),
Elliott Hughes08fc03a2012-06-26 17:34:00 -07002175 frame_id_(frame_id), slot_(slot), tag_(tag), value_(value), width_(width) {}
Ian Rogersca190662012-06-26 15:45:57 -07002176
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002177 // TODO: Enable annotalysis. We know lock is held in constructor, but abstraction confuses
2178 // annotalysis.
2179 bool VisitFrame() NO_THREAD_SAFETY_ANALYSIS {
Ian Rogers0399dde2012-06-06 17:09:28 -07002180 if (GetFrameId() != frame_id_) {
2181 return true; // Not our frame, carry on.
2182 }
2183 // TODO: check that the tag is compatible with the actual type of the slot!
Brian Carlstromea46f952013-07-30 01:26:50 -07002184 mirror::ArtMethod* m = GetMethod();
Ian Rogers0399dde2012-06-06 17:09:28 -07002185 uint16_t reg = DemangleSlot(slot_, m);
2186
2187 switch (tag_) {
2188 case JDWP::JT_BOOLEAN:
2189 case JDWP::JT_BYTE:
2190 CHECK_EQ(width_, 1U);
Ian Rogers2bcb4a42012-11-08 10:39:18 -08002191 SetVReg(m, reg, static_cast<uint32_t>(value_), kIntVReg);
Ian Rogers0399dde2012-06-06 17:09:28 -07002192 break;
2193 case JDWP::JT_SHORT:
2194 case JDWP::JT_CHAR:
2195 CHECK_EQ(width_, 2U);
Ian Rogers2bcb4a42012-11-08 10:39:18 -08002196 SetVReg(m, reg, static_cast<uint32_t>(value_), kIntVReg);
Ian Rogers0399dde2012-06-06 17:09:28 -07002197 break;
2198 case JDWP::JT_INT:
Ian Rogers2bcb4a42012-11-08 10:39:18 -08002199 CHECK_EQ(width_, 4U);
2200 SetVReg(m, reg, static_cast<uint32_t>(value_), kIntVReg);
2201 break;
Ian Rogers0399dde2012-06-06 17:09:28 -07002202 case JDWP::JT_FLOAT:
2203 CHECK_EQ(width_, 4U);
Ian Rogers2bcb4a42012-11-08 10:39:18 -08002204 SetVReg(m, reg, static_cast<uint32_t>(value_), kFloatVReg);
Ian Rogers0399dde2012-06-06 17:09:28 -07002205 break;
2206 case JDWP::JT_ARRAY:
2207 case JDWP::JT_OBJECT:
2208 case JDWP::JT_STRING:
2209 {
2210 CHECK_EQ(width_, sizeof(JDWP::ObjectId));
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002211 mirror::Object* o = gRegistry->Get<mirror::Object*>(static_cast<JDWP::ObjectId>(value_));
Elliott Hughes64f574f2013-02-20 14:57:12 -08002212 if (o == ObjectRegistry::kInvalidObject) {
Ian Rogers0399dde2012-06-06 17:09:28 -07002213 UNIMPLEMENTED(FATAL) << "return an error code when given an invalid object to store";
2214 }
Ian Rogers2bcb4a42012-11-08 10:39:18 -08002215 SetVReg(m, reg, static_cast<uint32_t>(reinterpret_cast<uintptr_t>(o)), kReferenceVReg);
Ian Rogers0399dde2012-06-06 17:09:28 -07002216 }
2217 break;
2218 case JDWP::JT_DOUBLE:
Ian Rogers2bcb4a42012-11-08 10:39:18 -08002219 CHECK_EQ(width_, 8U);
2220 SetVReg(m, reg, static_cast<uint32_t>(value_), kDoubleLoVReg);
2221 SetVReg(m, reg + 1, static_cast<uint32_t>(value_ >> 32), kDoubleHiVReg);
2222 break;
Ian Rogers0399dde2012-06-06 17:09:28 -07002223 case JDWP::JT_LONG:
2224 CHECK_EQ(width_, 8U);
Ian Rogers2bcb4a42012-11-08 10:39:18 -08002225 SetVReg(m, reg, static_cast<uint32_t>(value_), kLongLoVReg);
2226 SetVReg(m, reg + 1, static_cast<uint32_t>(value_ >> 32), kLongHiVReg);
Ian Rogers0399dde2012-06-06 17:09:28 -07002227 break;
2228 default:
2229 LOG(FATAL) << "Unknown tag " << tag_;
2230 break;
2231 }
2232 return false;
2233 }
2234
2235 const JDWP::FrameId frame_id_;
2236 const int slot_;
2237 const JDWP::JdwpTag tag_;
2238 const uint64_t value_;
2239 const size_t width_;
2240 };
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002241
2242 ScopedObjectAccessUnchecked soa(Thread::Current());
jeffhaoa77f0f62012-12-05 17:19:31 -08002243 MutexLock mu(soa.Self(), *Locks::thread_list_lock_);
Elliott Hughes221229c2013-01-08 18:17:50 -08002244 Thread* thread;
2245 JDWP::JdwpError error = DecodeThread(soa, thread_id, thread);
2246 if (error != JDWP::ERR_NONE) {
2247 return;
2248 }
Elliott Hughes08fc03a2012-06-26 17:34:00 -07002249 UniquePtr<Context> context(Context::Create());
Ian Rogers7a22fa62013-01-23 12:16:16 -08002250 SetLocalVisitor visitor(thread, context.get(), frame_id, slot, tag, value, width);
Ian Rogers0399dde2012-06-06 17:09:28 -07002251 visitor.WalkStack();
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002252}
2253
Jeff Hao579b0242013-11-18 13:16:49 -08002254void Dbg::PostLocationEvent(const mirror::ArtMethod* m, int dex_pc, mirror::Object* this_object,
2255 int event_flags, const JValue* return_value) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002256 mirror::Class* c = m->GetDeclaringClass();
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08002257
2258 JDWP::JdwpLocation location;
Elliott Hughes74847412012-06-20 18:10:21 -07002259 location.type_tag = c->IsInterface() ? JDWP::TT_INTERFACE : JDWP::TT_CLASS;
Elliott Hughes64f574f2013-02-20 14:57:12 -08002260 location.class_id = gRegistry->AddRefType(c);
Elliott Hughes74847412012-06-20 18:10:21 -07002261 location.method_id = ToMethodId(m);
Elliott Hughes972a47b2012-02-21 18:16:06 -08002262 location.dex_pc = m->IsNative() ? -1 : dex_pc;
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08002263
Elliott Hughes64f574f2013-02-20 14:57:12 -08002264 // If 'this_object' isn't already in the registry, we know that we're not looking for it,
2265 // so there's no point adding it to the registry and burning through ids.
2266 JDWP::ObjectId this_id = 0;
2267 if (gRegistry->Contains(this_object)) {
2268 this_id = gRegistry->Add(this_object);
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08002269 }
Jeff Hao579b0242013-11-18 13:16:49 -08002270 gJdwpState->PostLocationEvent(&location, this_id, event_flags, return_value);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002271}
2272
Ian Rogers62d6c772013-02-27 08:32:07 -08002273void Dbg::PostException(Thread* thread, const ThrowLocation& throw_location,
Brian Carlstromea46f952013-07-30 01:26:50 -07002274 mirror::ArtMethod* catch_method,
Elliott Hughes64f574f2013-02-20 14:57:12 -08002275 uint32_t catch_dex_pc, mirror::Throwable* exception_object) {
Elliott Hughesc0f09332012-03-26 13:27:06 -07002276 if (!IsDebuggerActive()) {
Ian Rogers0ad5bb82011-12-07 10:16:32 -08002277 return;
2278 }
Elliott Hughes4740cdf2011-12-07 14:07:12 -08002279
Ian Rogers62d6c772013-02-27 08:32:07 -08002280 JDWP::JdwpLocation jdwp_throw_location;
2281 SetLocation(jdwp_throw_location, throw_location.GetMethod(), throw_location.GetDexPc());
Elliott Hughesd07986f2011-12-06 18:27:45 -08002282 JDWP::JdwpLocation catch_location;
Elliott Hughescaf76542012-06-28 16:08:22 -07002283 SetLocation(catch_location, catch_method, catch_dex_pc);
Elliott Hughesd07986f2011-12-06 18:27:45 -08002284
2285 // We need 'this' for InstanceOnly filters.
Ian Rogers62d6c772013-02-27 08:32:07 -08002286 JDWP::ObjectId this_id = gRegistry->Add(throw_location.GetThis());
Elliott Hughes64f574f2013-02-20 14:57:12 -08002287 JDWP::ObjectId exception_id = gRegistry->Add(exception_object);
2288 JDWP::RefTypeId exception_class_id = gRegistry->AddRefType(exception_object->GetClass());
Elliott Hughesd07986f2011-12-06 18:27:45 -08002289
Ian Rogers62d6c772013-02-27 08:32:07 -08002290 gJdwpState->PostException(&jdwp_throw_location, exception_id, exception_class_id, &catch_location,
2291 this_id);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002292}
2293
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002294void Dbg::PostClassPrepare(mirror::Class* c) {
Elliott Hughesc0f09332012-03-26 13:27:06 -07002295 if (!IsDebuggerActive()) {
Elliott Hughes4740cdf2011-12-07 14:07:12 -08002296 return;
2297 }
2298
Elliott Hughes3d30d9b2011-12-07 17:35:48 -08002299 // OLD-TODO - we currently always send both "verified" and "prepared" since
Elliott Hughes4740cdf2011-12-07 14:07:12 -08002300 // debuggers seem to like that. There might be some advantage to honesty,
2301 // since the class may not yet be verified.
2302 int state = JDWP::CS_VERIFIED | JDWP::CS_PREPARED;
2303 JDWP::JdwpTypeTag tag = c->IsInterface() ? JDWP::TT_INTERFACE : JDWP::TT_CLASS;
Ian Rogersfc0e94b2013-09-23 23:51:32 -07002304 gJdwpState->PostClassPrepare(tag, gRegistry->Add(c),
Ian Rogersdfb325e2013-10-30 01:00:44 -07002305 ClassHelper(c).GetDescriptor(), state);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002306}
2307
Ian Rogers62d6c772013-02-27 08:32:07 -08002308void Dbg::UpdateDebugger(Thread* thread, mirror::Object* this_object,
Brian Carlstromea46f952013-07-30 01:26:50 -07002309 const mirror::ArtMethod* m, uint32_t dex_pc) {
Ian Rogers62d6c772013-02-27 08:32:07 -08002310 if (!IsDebuggerActive() || dex_pc == static_cast<uint32_t>(-2) /* fake method exit */) {
Elliott Hughes2aa2e392012-02-17 17:15:43 -08002311 return;
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08002312 }
2313
Elliott Hughes2aa2e392012-02-17 17:15:43 -08002314 int event_flags = 0;
2315
Elliott Hughes86964332012-02-15 19:37:42 -08002316 if (IsBreakpoint(m, dex_pc)) {
2317 event_flags |= kBreakpoint;
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08002318 }
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08002319
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01002320 // If the debugger is single-stepping one of our threads, check to
2321 // see if we're that thread and we've reached a step point.
2322 const SingleStepControl* single_step_control = thread->GetSingleStepControl();
2323 DCHECK(single_step_control != nullptr);
2324 if (single_step_control->is_active) {
2325 CHECK(!m->IsNative());
2326 if (single_step_control->step_depth == JDWP::SD_INTO) {
2327 // Step into method calls. We break when the line number
2328 // or method pointer changes. If we're in SS_MIN mode, we
2329 // always stop.
2330 if (single_step_control->method != m) {
2331 event_flags |= kSingleStep;
2332 VLOG(jdwp) << "SS new method";
2333 } else if (single_step_control->step_size == JDWP::SS_MIN) {
2334 event_flags |= kSingleStep;
2335 VLOG(jdwp) << "SS new instruction";
2336 } else if (single_step_control->dex_pcs.find(dex_pc) == single_step_control->dex_pcs.end()) {
2337 event_flags |= kSingleStep;
2338 VLOG(jdwp) << "SS new line";
2339 }
2340 } else if (single_step_control->step_depth == JDWP::SD_OVER) {
2341 // Step over method calls. We break when the line number is
2342 // different and the frame depth is <= the original frame
2343 // depth. (We can't just compare on the method, because we
2344 // might get unrolled past it by an exception, and it's tricky
2345 // to identify recursion.)
2346
2347 int stack_depth = GetStackDepth(thread);
2348
2349 if (stack_depth < single_step_control->stack_depth) {
2350 // Popped up one or more frames, always trigger.
2351 event_flags |= kSingleStep;
2352 VLOG(jdwp) << "SS method pop";
2353 } else if (stack_depth == single_step_control->stack_depth) {
2354 // Same depth, see if we moved.
2355 if (single_step_control->step_size == JDWP::SS_MIN) {
Elliott Hughes86964332012-02-15 19:37:42 -08002356 event_flags |= kSingleStep;
2357 VLOG(jdwp) << "SS new instruction";
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01002358 } else if (single_step_control->dex_pcs.find(dex_pc) == single_step_control->dex_pcs.end()) {
Elliott Hughes2435a572012-02-17 16:07:41 -08002359 event_flags |= kSingleStep;
2360 VLOG(jdwp) << "SS new line";
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08002361 }
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01002362 }
2363 } else {
2364 CHECK_EQ(single_step_control->step_depth, JDWP::SD_OUT);
2365 // Return from the current method. We break when the frame
2366 // depth pops up.
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08002367
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01002368 // This differs from the "method exit" break in that it stops
2369 // with the PC at the next instruction in the returned-to
2370 // function, rather than the end of the returning function.
Elliott Hughes86964332012-02-15 19:37:42 -08002371
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01002372 int stack_depth = GetStackDepth(thread);
2373 if (stack_depth < single_step_control->stack_depth) {
2374 event_flags |= kSingleStep;
2375 VLOG(jdwp) << "SS method pop";
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08002376 }
2377 }
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08002378 }
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08002379
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08002380 // If there's something interesting going on, see if it matches one
2381 // of the debugger filters.
2382 if (event_flags != 0) {
Jeff Hao579b0242013-11-18 13:16:49 -08002383 Dbg::PostLocationEvent(m, dex_pc, this_object, event_flags, nullptr);
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08002384 }
2385}
2386
Elliott Hughes86964332012-02-15 19:37:42 -08002387void Dbg::WatchLocation(const JDWP::JdwpLocation* location) {
jeffhao09bfc6a2012-12-11 18:11:43 -08002388 MutexLock mu(Thread::Current(), *Locks::breakpoint_lock_);
Brian Carlstromea46f952013-07-30 01:26:50 -07002389 mirror::ArtMethod* m = FromMethodId(location->method_id);
Elliott Hughes972a47b2012-02-21 18:16:06 -08002390 gBreakpoints.push_back(Breakpoint(m, location->dex_pc));
Elliott Hughes86964332012-02-15 19:37:42 -08002391 VLOG(jdwp) << "Set breakpoint #" << (gBreakpoints.size() - 1) << ": " << gBreakpoints[gBreakpoints.size() - 1];
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002392}
2393
Elliott Hughes86964332012-02-15 19:37:42 -08002394void Dbg::UnwatchLocation(const JDWP::JdwpLocation* location) {
jeffhao09bfc6a2012-12-11 18:11:43 -08002395 MutexLock mu(Thread::Current(), *Locks::breakpoint_lock_);
Brian Carlstromea46f952013-07-30 01:26:50 -07002396 mirror::ArtMethod* m = FromMethodId(location->method_id);
Elliott Hughes86964332012-02-15 19:37:42 -08002397 for (size_t i = 0; i < gBreakpoints.size(); ++i) {
Elliott Hughes972a47b2012-02-21 18:16:06 -08002398 if (gBreakpoints[i].method == m && gBreakpoints[i].dex_pc == location->dex_pc) {
Elliott Hughes86964332012-02-15 19:37:42 -08002399 VLOG(jdwp) << "Removed breakpoint #" << i << ": " << gBreakpoints[i];
2400 gBreakpoints.erase(gBreakpoints.begin() + i);
2401 return;
2402 }
2403 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002404}
2405
Jeff Hao449db332013-04-12 18:30:52 -07002406// Scoped utility class to suspend a thread so that we may do tasks such as walk its stack. Doesn't
2407// cause suspension if the thread is the current thread.
2408class ScopedThreadSuspension {
2409 public:
Ian Rogers33e95662013-05-20 20:29:14 -07002410 ScopedThreadSuspension(Thread* self, JDWP::ObjectId thread_id)
2411 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) :
Jeff Hao449db332013-04-12 18:30:52 -07002412 thread_(NULL),
2413 error_(JDWP::ERR_NONE),
2414 self_suspend_(false),
Ian Rogers33e95662013-05-20 20:29:14 -07002415 other_suspend_(false) {
Jeff Hao449db332013-04-12 18:30:52 -07002416 ScopedObjectAccessUnchecked soa(self);
2417 {
2418 MutexLock mu(soa.Self(), *Locks::thread_list_lock_);
2419 error_ = DecodeThread(soa, thread_id, thread_);
2420 }
2421 if (error_ == JDWP::ERR_NONE) {
2422 if (thread_ == soa.Self()) {
2423 self_suspend_ = true;
2424 } else {
2425 soa.Self()->TransitionFromRunnableToSuspended(kWaitingForDebuggerSuspension);
2426 jobject thread_peer = gRegistry->GetJObject(thread_id);
2427 bool timed_out;
Ian Rogersd9c4fc92013-10-01 19:45:43 -07002428 Thread* suspended_thread = ThreadList::SuspendThreadByPeer(thread_peer, true, true,
2429 &timed_out);
Jeff Hao449db332013-04-12 18:30:52 -07002430 CHECK_EQ(soa.Self()->TransitionFromSuspendedToRunnable(), kWaitingForDebuggerSuspension);
2431 if (suspended_thread == NULL) {
2432 // Thread terminated from under us while suspending.
2433 error_ = JDWP::ERR_INVALID_THREAD;
2434 } else {
2435 CHECK_EQ(suspended_thread, thread_);
2436 other_suspend_ = true;
2437 }
2438 }
2439 }
Elliott Hughes2435a572012-02-17 16:07:41 -08002440 }
Elliott Hughes86964332012-02-15 19:37:42 -08002441
Jeff Hao449db332013-04-12 18:30:52 -07002442 Thread* GetThread() const {
2443 return thread_;
2444 }
2445
2446 JDWP::JdwpError GetError() const {
2447 return error_;
2448 }
2449
2450 ~ScopedThreadSuspension() {
2451 if (other_suspend_) {
2452 Runtime::Current()->GetThreadList()->Resume(thread_, true);
2453 }
2454 }
2455
2456 private:
2457 Thread* thread_;
2458 JDWP::JdwpError error_;
2459 bool self_suspend_;
2460 bool other_suspend_;
2461};
2462
2463JDWP::JdwpError Dbg::ConfigureStep(JDWP::ObjectId thread_id, JDWP::JdwpStepSize step_size,
2464 JDWP::JdwpStepDepth step_depth) {
2465 Thread* self = Thread::Current();
2466 ScopedThreadSuspension sts(self, thread_id);
2467 if (sts.GetError() != JDWP::ERR_NONE) {
2468 return sts.GetError();
2469 }
2470
Elliott Hughes2435a572012-02-17 16:07:41 -08002471 //
2472 // Work out what Method* we're in, the current line number, and how deep the stack currently
2473 // is for step-out.
2474 //
2475
Ian Rogers0399dde2012-06-06 17:09:28 -07002476 struct SingleStepStackVisitor : public StackVisitor {
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01002477 explicit SingleStepStackVisitor(Thread* thread, SingleStepControl* single_step_control,
2478 int32_t* line_number)
Ian Rogersb726dcb2012-09-05 08:57:23 -07002479 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_)
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01002480 : StackVisitor(thread, NULL), single_step_control_(single_step_control),
2481 line_number_(line_number) {
2482 DCHECK_EQ(single_step_control_, thread->GetSingleStepControl());
2483 single_step_control_->method = NULL;
2484 single_step_control_->stack_depth = 0;
Elliott Hughes86964332012-02-15 19:37:42 -08002485 }
Ian Rogersca190662012-06-26 15:45:57 -07002486
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002487 // TODO: Enable annotalysis. We know lock is held in constructor, but abstraction confuses
2488 // annotalysis.
2489 bool VisitFrame() NO_THREAD_SAFETY_ANALYSIS {
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01002490 mirror::ArtMethod* m = GetMethod();
Ian Rogers0399dde2012-06-06 17:09:28 -07002491 if (!m->IsRuntimeMethod()) {
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01002492 ++single_step_control_->stack_depth;
2493 if (single_step_control_->method == NULL) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002494 const mirror::DexCache* dex_cache = m->GetDeclaringClass()->GetDexCache();
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01002495 single_step_control_->method = m;
2496 *line_number_ = -1;
Elliott Hughes2435a572012-02-17 16:07:41 -08002497 if (dex_cache != NULL) {
Ian Rogers4445a7e2012-10-05 17:19:13 -07002498 const DexFile& dex_file = *dex_cache->GetDexFile();
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01002499 *line_number_ = dex_file.GetLineNumFromPC(m, GetDexPc());
Elliott Hughes2435a572012-02-17 16:07:41 -08002500 }
Elliott Hughes86964332012-02-15 19:37:42 -08002501 }
2502 }
Elliott Hughes530fa002012-03-12 11:44:49 -07002503 return true;
Elliott Hughes86964332012-02-15 19:37:42 -08002504 }
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01002505
2506 SingleStepControl* const single_step_control_;
2507 int32_t* const line_number_;
Elliott Hughes86964332012-02-15 19:37:42 -08002508 };
Jeff Hao449db332013-04-12 18:30:52 -07002509
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01002510 Thread* const thread = sts.GetThread();
2511 SingleStepControl* const single_step_control = thread->GetSingleStepControl();
2512 DCHECK(single_step_control != nullptr);
2513 int32_t line_number = -1;
2514 SingleStepStackVisitor visitor(thread, single_step_control, &line_number);
Ian Rogers0399dde2012-06-06 17:09:28 -07002515 visitor.WalkStack();
Elliott Hughes86964332012-02-15 19:37:42 -08002516
Elliott Hughes2435a572012-02-17 16:07:41 -08002517 //
2518 // Find the dex_pc values that correspond to the current line, for line-based single-stepping.
2519 //
2520
2521 struct DebugCallbackContext {
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01002522 explicit DebugCallbackContext(SingleStepControl* single_step_control, int32_t line_number)
2523 : single_step_control_(single_step_control), line_number_(line_number),
2524 last_pc_valid(false), last_pc(0) {
Elliott Hughes2435a572012-02-17 16:07:41 -08002525 }
2526
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01002527 static bool Callback(void* raw_context, uint32_t address, uint32_t line_number) {
Elliott Hughes2435a572012-02-17 16:07:41 -08002528 DebugCallbackContext* context = reinterpret_cast<DebugCallbackContext*>(raw_context);
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01002529 if (static_cast<int32_t>(line_number) == context->line_number_) {
Elliott Hughes2435a572012-02-17 16:07:41 -08002530 if (!context->last_pc_valid) {
2531 // Everything from this address until the next line change is ours.
2532 context->last_pc = address;
2533 context->last_pc_valid = true;
2534 }
2535 // Otherwise, if we're already in a valid range for this line,
2536 // just keep going (shouldn't really happen)...
Brian Carlstrom7934ac22013-07-26 10:54:15 -07002537 } else if (context->last_pc_valid) { // and the line number is new
Elliott Hughes2435a572012-02-17 16:07:41 -08002538 // Add everything from the last entry up until here to the set
2539 for (uint32_t dex_pc = context->last_pc; dex_pc < address; ++dex_pc) {
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01002540 context->single_step_control_->dex_pcs.insert(dex_pc);
Elliott Hughes2435a572012-02-17 16:07:41 -08002541 }
2542 context->last_pc_valid = false;
2543 }
Brian Carlstrom7934ac22013-07-26 10:54:15 -07002544 return false; // There may be multiple entries for any given line.
Elliott Hughes2435a572012-02-17 16:07:41 -08002545 }
2546
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01002547 ~DebugCallbackContext() {
Elliott Hughes2435a572012-02-17 16:07:41 -08002548 // If the line number was the last in the position table...
2549 if (last_pc_valid) {
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01002550 size_t end = MethodHelper(single_step_control_->method).GetCodeItem()->insns_size_in_code_units_;
Elliott Hughes2435a572012-02-17 16:07:41 -08002551 for (uint32_t dex_pc = last_pc; dex_pc < end; ++dex_pc) {
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01002552 single_step_control_->dex_pcs.insert(dex_pc);
Elliott Hughes2435a572012-02-17 16:07:41 -08002553 }
2554 }
2555 }
2556
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01002557 SingleStepControl* const single_step_control_;
2558 const int32_t line_number_;
Elliott Hughes2435a572012-02-17 16:07:41 -08002559 bool last_pc_valid;
2560 uint32_t last_pc;
2561 };
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01002562 single_step_control->dex_pcs.clear();
2563 const mirror::ArtMethod* m = single_step_control->method;
2564 if (!m->IsNative()) {
2565 DebugCallbackContext context(single_step_control, line_number);
Elliott Hughes3e2e1a22012-02-21 11:33:41 -08002566 MethodHelper mh(m);
2567 mh.GetDexFile().DecodeDebugInfo(mh.GetCodeItem(), m->IsStatic(), m->GetDexMethodIndex(),
2568 DebugCallbackContext::Callback, NULL, &context);
2569 }
Elliott Hughes2435a572012-02-17 16:07:41 -08002570
2571 //
2572 // Everything else...
2573 //
2574
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01002575 single_step_control->step_size = step_size;
2576 single_step_control->step_depth = step_depth;
2577 single_step_control->is_active = true;
Elliott Hughes86964332012-02-15 19:37:42 -08002578
Elliott Hughes2435a572012-02-17 16:07:41 -08002579 if (VLOG_IS_ON(jdwp)) {
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01002580 VLOG(jdwp) << "Single-step thread: " << *thread;
2581 VLOG(jdwp) << "Single-step step size: " << single_step_control->step_size;
2582 VLOG(jdwp) << "Single-step step depth: " << single_step_control->step_depth;
2583 VLOG(jdwp) << "Single-step current method: " << PrettyMethod(single_step_control->method);
2584 VLOG(jdwp) << "Single-step current line: " << line_number;
2585 VLOG(jdwp) << "Single-step current stack depth: " << single_step_control->stack_depth;
Elliott Hughes2435a572012-02-17 16:07:41 -08002586 VLOG(jdwp) << "Single-step dex_pc values:";
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01002587 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 -08002588 VLOG(jdwp) << StringPrintf(" %#x", *it);
Elliott Hughes2435a572012-02-17 16:07:41 -08002589 }
2590 }
2591
2592 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002593}
2594
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01002595void Dbg::UnconfigureStep(JDWP::ObjectId thread_id) {
2596 ScopedObjectAccessUnchecked soa(Thread::Current());
2597 MutexLock mu(soa.Self(), *Locks::thread_list_lock_);
2598 Thread* thread;
2599 JDWP::JdwpError error = DecodeThread(soa, thread_id, thread);
Sebastien Hertz87118ed2013-11-26 17:57:18 +01002600 if (error == JDWP::ERR_NONE) {
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01002601 SingleStepControl* single_step_control = thread->GetSingleStepControl();
2602 DCHECK(single_step_control != nullptr);
2603 single_step_control->is_active = false;
2604 single_step_control->dex_pcs.clear();
2605 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002606}
2607
Elliott Hughes45651fd2012-02-21 15:48:20 -08002608static char JdwpTagToShortyChar(JDWP::JdwpTag tag) {
2609 switch (tag) {
2610 default:
2611 LOG(FATAL) << "unknown JDWP tag: " << PrintableChar(tag);
2612
2613 // Primitives.
2614 case JDWP::JT_BYTE: return 'B';
2615 case JDWP::JT_CHAR: return 'C';
2616 case JDWP::JT_FLOAT: return 'F';
2617 case JDWP::JT_DOUBLE: return 'D';
2618 case JDWP::JT_INT: return 'I';
2619 case JDWP::JT_LONG: return 'J';
2620 case JDWP::JT_SHORT: return 'S';
2621 case JDWP::JT_VOID: return 'V';
2622 case JDWP::JT_BOOLEAN: return 'Z';
2623
2624 // Reference types.
2625 case JDWP::JT_ARRAY:
2626 case JDWP::JT_OBJECT:
2627 case JDWP::JT_STRING:
2628 case JDWP::JT_THREAD:
2629 case JDWP::JT_THREAD_GROUP:
2630 case JDWP::JT_CLASS_LOADER:
2631 case JDWP::JT_CLASS_OBJECT:
2632 return 'L';
2633 }
2634}
2635
Elliott Hughes88d63092013-01-09 09:55:54 -08002636JDWP::JdwpError Dbg::InvokeMethod(JDWP::ObjectId thread_id, JDWP::ObjectId object_id,
2637 JDWP::RefTypeId class_id, JDWP::MethodId method_id,
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002638 uint32_t arg_count, uint64_t* arg_values,
2639 JDWP::JdwpTag* arg_types, uint32_t options,
2640 JDWP::JdwpTag* pResultTag, uint64_t* pResultValue,
2641 JDWP::ObjectId* pExceptionId) {
Elliott Hughesd07986f2011-12-06 18:27:45 -08002642 ThreadList* thread_list = Runtime::Current()->GetThreadList();
2643
2644 Thread* targetThread = NULL;
2645 DebugInvokeReq* req = NULL;
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002646 Thread* self = Thread::Current();
Elliott Hughesd07986f2011-12-06 18:27:45 -08002647 {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002648 ScopedObjectAccessUnchecked soa(self);
Ian Rogers50b35e22012-10-04 10:09:15 -07002649 MutexLock mu(soa.Self(), *Locks::thread_list_lock_);
Elliott Hughes221229c2013-01-08 18:17:50 -08002650 JDWP::JdwpError error = DecodeThread(soa, thread_id, targetThread);
2651 if (error != JDWP::ERR_NONE) {
2652 LOG(ERROR) << "InvokeMethod request for invalid thread id " << thread_id;
2653 return error;
Elliott Hughesd07986f2011-12-06 18:27:45 -08002654 }
2655 req = targetThread->GetInvokeReq();
2656 if (!req->ready) {
2657 LOG(ERROR) << "InvokeMethod request for thread not stopped by event: " << *targetThread;
2658 return JDWP::ERR_INVALID_THREAD;
2659 }
2660
2661 /*
2662 * We currently have a bug where we don't successfully resume the
2663 * target thread if the suspend count is too deep. We're expected to
2664 * require one "resume" for each "suspend", but when asked to execute
2665 * a method we have to resume fully and then re-suspend it back to the
2666 * same level. (The easiest way to cause this is to type "suspend"
2667 * multiple times in jdb.)
2668 *
2669 * It's unclear what this means when the event specifies "resume all"
2670 * and some threads are suspended more deeply than others. This is
2671 * a rare problem, so for now we just prevent it from hanging forever
2672 * by rejecting the method invocation request. Without this, we will
2673 * be stuck waiting on a suspended thread.
2674 */
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002675 int suspend_count;
2676 {
Ian Rogers50b35e22012-10-04 10:09:15 -07002677 MutexLock mu2(soa.Self(), *Locks::thread_suspend_count_lock_);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002678 suspend_count = targetThread->GetSuspendCount();
2679 }
Elliott Hughesd07986f2011-12-06 18:27:45 -08002680 if (suspend_count > 1) {
2681 LOG(ERROR) << *targetThread << " suspend count too deep for method invocation: " << suspend_count;
Brian Carlstrom7934ac22013-07-26 10:54:15 -07002682 return JDWP::ERR_THREAD_SUSPENDED; // Probably not expected here.
Elliott Hughesd07986f2011-12-06 18:27:45 -08002683 }
2684
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08002685 JDWP::JdwpError status;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002686 mirror::Object* receiver = gRegistry->Get<mirror::Object*>(object_id);
Elliott Hughes64f574f2013-02-20 14:57:12 -08002687 if (receiver == ObjectRegistry::kInvalidObject) {
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08002688 return JDWP::ERR_INVALID_OBJECT;
2689 }
Elliott Hughes45651fd2012-02-21 15:48:20 -08002690
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002691 mirror::Object* thread = gRegistry->Get<mirror::Object*>(thread_id);
Elliott Hughes64f574f2013-02-20 14:57:12 -08002692 if (thread == ObjectRegistry::kInvalidObject) {
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08002693 return JDWP::ERR_INVALID_OBJECT;
2694 }
Elliott Hughes45651fd2012-02-21 15:48:20 -08002695 // TODO: check that 'thread' is actually a java.lang.Thread!
2696
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002697 mirror::Class* c = DecodeClass(class_id, status);
Elliott Hughes45651fd2012-02-21 15:48:20 -08002698 if (c == NULL) {
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08002699 return status;
2700 }
Elliott Hughes45651fd2012-02-21 15:48:20 -08002701
Brian Carlstromea46f952013-07-30 01:26:50 -07002702 mirror::ArtMethod* m = FromMethodId(method_id);
Elliott Hughes45651fd2012-02-21 15:48:20 -08002703 if (m->IsStatic() != (receiver == NULL)) {
2704 return JDWP::ERR_INVALID_METHODID;
2705 }
2706 if (m->IsStatic()) {
2707 if (m->GetDeclaringClass() != c) {
2708 return JDWP::ERR_INVALID_METHODID;
2709 }
2710 } else {
2711 if (!m->GetDeclaringClass()->IsAssignableFrom(c)) {
2712 return JDWP::ERR_INVALID_METHODID;
2713 }
2714 }
2715
2716 // Check the argument list matches the method.
2717 MethodHelper mh(m);
2718 if (mh.GetShortyLength() - 1 != arg_count) {
2719 return JDWP::ERR_ILLEGAL_ARGUMENT;
2720 }
2721 const char* shorty = mh.GetShorty();
Elliott Hughes09201632013-04-15 15:50:07 -07002722 const DexFile::TypeList* types = mh.GetParameterTypeList();
Elliott Hughes45651fd2012-02-21 15:48:20 -08002723 for (size_t i = 0; i < arg_count; ++i) {
2724 if (shorty[i + 1] != JdwpTagToShortyChar(arg_types[i])) {
2725 return JDWP::ERR_ILLEGAL_ARGUMENT;
2726 }
Elliott Hughes09201632013-04-15 15:50:07 -07002727
2728 if (shorty[i + 1] == 'L') {
2729 // Did we really get an argument of an appropriate reference type?
2730 mirror::Class* parameter_type = mh.GetClassFromTypeIdx(types->GetTypeItem(i).type_idx_);
2731 mirror::Object* argument = gRegistry->Get<mirror::Object*>(arg_values[i]);
2732 if (argument == ObjectRegistry::kInvalidObject) {
2733 return JDWP::ERR_INVALID_OBJECT;
2734 }
Sebastien Hertz0630ab52013-11-28 18:53:35 +01002735 if (argument != NULL && !argument->InstanceOf(parameter_type)) {
Elliott Hughes09201632013-04-15 15:50:07 -07002736 return JDWP::ERR_ILLEGAL_ARGUMENT;
2737 }
2738
2739 // Turn the on-the-wire ObjectId into a jobject.
2740 jvalue& v = reinterpret_cast<jvalue&>(arg_values[i]);
2741 v.l = gRegistry->GetJObject(arg_values[i]);
2742 }
Elliott Hughes45651fd2012-02-21 15:48:20 -08002743 }
2744
Sebastien Hertzd38667a2013-11-25 15:43:54 +01002745 req->receiver = receiver;
2746 req->thread = thread;
2747 req->klass = c;
2748 req->method = m;
2749 req->arg_count = arg_count;
2750 req->arg_values = arg_values;
2751 req->options = options;
2752 req->invoke_needed = true;
Elliott Hughesd07986f2011-12-06 18:27:45 -08002753 }
2754
2755 // The fact that we've released the thread list lock is a bit risky --- if the thread goes
2756 // away we're sitting high and dry -- but we must release this before the ResumeAllThreads
2757 // call, and it's unwise to hold it during WaitForSuspend.
2758
2759 {
2760 /*
2761 * We change our (JDWP thread) status, which should be THREAD_RUNNING,
Elliott Hughes81ff3182012-03-23 20:35:56 -07002762 * so we can suspend for a GC if the invoke request causes us to
Elliott Hughesd07986f2011-12-06 18:27:45 -08002763 * run out of memory. It's also a good idea to change it before locking
2764 * the invokeReq mutex, although that should never be held for long.
2765 */
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002766 self->TransitionFromRunnableToSuspended(kWaitingForDebuggerSend);
Elliott Hughesd07986f2011-12-06 18:27:45 -08002767
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08002768 VLOG(jdwp) << " Transferring control to event thread";
Elliott Hughesd07986f2011-12-06 18:27:45 -08002769 {
Sebastien Hertzd38667a2013-11-25 15:43:54 +01002770 MutexLock mu(self, req->lock);
Elliott Hughesd07986f2011-12-06 18:27:45 -08002771
2772 if ((options & JDWP::INVOKE_SINGLE_THREADED) == 0) {
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08002773 VLOG(jdwp) << " Resuming all threads";
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002774 thread_list->UndoDebuggerSuspensions();
Elliott Hughesd07986f2011-12-06 18:27:45 -08002775 } else {
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08002776 VLOG(jdwp) << " Resuming event thread only";
Elliott Hughesd07986f2011-12-06 18:27:45 -08002777 thread_list->Resume(targetThread, true);
2778 }
2779
2780 // Wait for the request to finish executing.
Sebastien Hertzd38667a2013-11-25 15:43:54 +01002781 while (req->invoke_needed) {
2782 req->cond.Wait(self);
Elliott Hughesd07986f2011-12-06 18:27:45 -08002783 }
2784 }
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08002785 VLOG(jdwp) << " Control has returned from event thread";
Elliott Hughesd07986f2011-12-06 18:27:45 -08002786
2787 /* wait for thread to re-suspend itself */
Brian Carlstromdf629502013-07-17 22:39:56 -07002788 SuspendThread(thread_id, false /* request_suspension */);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002789 self->TransitionFromSuspendedToRunnable();
Elliott Hughesd07986f2011-12-06 18:27:45 -08002790 }
2791
2792 /*
2793 * Suspend the threads. We waited for the target thread to suspend
2794 * itself, so all we need to do is suspend the others.
2795 *
2796 * The suspendAllThreads() call will double-suspend the event thread,
2797 * so we want to resume the target thread once to keep the books straight.
2798 */
2799 if ((options & JDWP::INVOKE_SINGLE_THREADED) == 0) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002800 self->TransitionFromRunnableToSuspended(kWaitingForDebuggerSuspension);
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08002801 VLOG(jdwp) << " Suspending all threads";
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002802 thread_list->SuspendAllForDebugger();
2803 self->TransitionFromSuspendedToRunnable();
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08002804 VLOG(jdwp) << " Resuming event thread to balance the count";
Elliott Hughesd07986f2011-12-06 18:27:45 -08002805 thread_list->Resume(targetThread, true);
2806 }
2807
2808 // Copy the result.
2809 *pResultTag = req->result_tag;
2810 if (IsPrimitiveTag(req->result_tag)) {
Elliott Hughesf24d3ce2012-04-11 17:43:37 -07002811 *pResultValue = req->result_value.GetJ();
Elliott Hughesd07986f2011-12-06 18:27:45 -08002812 } else {
Elliott Hughesf24d3ce2012-04-11 17:43:37 -07002813 *pResultValue = gRegistry->Add(req->result_value.GetL());
Elliott Hughesd07986f2011-12-06 18:27:45 -08002814 }
2815 *pExceptionId = req->exception;
2816 return req->error;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002817}
2818
2819void Dbg::ExecuteMethod(DebugInvokeReq* pReq) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002820 ScopedObjectAccess soa(Thread::Current());
Elliott Hughesd07986f2011-12-06 18:27:45 -08002821
Elliott Hughes81ff3182012-03-23 20:35:56 -07002822 // We can be called while an exception is pending. We need
Elliott Hughesd07986f2011-12-06 18:27:45 -08002823 // to preserve that across the method invocation.
Ian Rogers62d6c772013-02-27 08:32:07 -08002824 SirtRef<mirror::Object> old_throw_this_object(soa.Self(), NULL);
Brian Carlstromea46f952013-07-30 01:26:50 -07002825 SirtRef<mirror::ArtMethod> old_throw_method(soa.Self(), NULL);
Ian Rogers62d6c772013-02-27 08:32:07 -08002826 SirtRef<mirror::Throwable> old_exception(soa.Self(), NULL);
2827 uint32_t old_throw_dex_pc;
2828 {
2829 ThrowLocation old_throw_location;
2830 mirror::Throwable* old_exception_obj = soa.Self()->GetException(&old_throw_location);
2831 old_throw_this_object.reset(old_throw_location.GetThis());
2832 old_throw_method.reset(old_throw_location.GetMethod());
2833 old_exception.reset(old_exception_obj);
2834 old_throw_dex_pc = old_throw_location.GetDexPc();
2835 soa.Self()->ClearException();
2836 }
Elliott Hughesd07986f2011-12-06 18:27:45 -08002837
2838 // Translate the method through the vtable, unless the debugger wants to suppress it.
Mathieu Chartierc528dba2013-11-26 12:00:11 -08002839 SirtRef<mirror::ArtMethod> m(soa.Self(), pReq->method);
Sebastien Hertzd38667a2013-11-25 15:43:54 +01002840 if ((pReq->options & JDWP::INVOKE_NONVIRTUAL) == 0 && pReq->receiver != NULL) {
2841 mirror::ArtMethod* actual_method = pReq->klass->FindVirtualMethodForVirtualOrInterface(pReq->method);
Mathieu Chartierc528dba2013-11-26 12:00:11 -08002842 if (actual_method != m.get()) {
2843 VLOG(jdwp) << "ExecuteMethod translated " << PrettyMethod(m.get()) << " to " << PrettyMethod(actual_method);
2844 m.reset(actual_method);
Elliott Hughes45651fd2012-02-21 15:48:20 -08002845 }
Elliott Hughesd07986f2011-12-06 18:27:45 -08002846 }
Mathieu Chartierc528dba2013-11-26 12:00:11 -08002847 VLOG(jdwp) << "ExecuteMethod " << PrettyMethod(m.get())
Sebastien Hertzd38667a2013-11-25 15:43:54 +01002848 << " receiver=" << pReq->receiver
2849 << " arg_count=" << pReq->arg_count;
Mathieu Chartierc528dba2013-11-26 12:00:11 -08002850 CHECK(m.get() != nullptr);
Elliott Hughesd07986f2011-12-06 18:27:45 -08002851
2852 CHECK_EQ(sizeof(jvalue), sizeof(uint64_t));
2853
Mathieu Chartierc528dba2013-11-26 12:00:11 -08002854 MethodHelper mh(m.get());
Jeff Hao5d917302013-02-27 17:57:33 -08002855 ArgArray arg_array(mh.GetShorty(), mh.GetShortyLength());
Sebastien Hertzd38667a2013-11-25 15:43:54 +01002856 arg_array.BuildArgArray(soa, pReq->receiver, reinterpret_cast<jvalue*>(pReq->arg_values));
Mathieu Chartierc528dba2013-11-26 12:00:11 -08002857 InvokeWithArgArray(soa, m.get(), &arg_array, &pReq->result_value, mh.GetShorty()[0]);
Elliott Hughesd07986f2011-12-06 18:27:45 -08002858
Ian Rogers62d6c772013-02-27 08:32:07 -08002859 mirror::Throwable* exception = soa.Self()->GetException(NULL);
2860 soa.Self()->ClearException();
2861 pReq->exception = gRegistry->Add(exception);
Mathieu Chartierc528dba2013-11-26 12:00:11 -08002862 pReq->result_tag = BasicTagFromDescriptor(MethodHelper(m.get()).GetShorty());
Elliott Hughesd07986f2011-12-06 18:27:45 -08002863 if (pReq->exception != 0) {
Ian Rogers62d6c772013-02-27 08:32:07 -08002864 VLOG(jdwp) << " JDWP invocation returning with exception=" << exception
2865 << " " << exception->Dump();
Elliott Hughesf24d3ce2012-04-11 17:43:37 -07002866 pReq->result_value.SetJ(0);
Elliott Hughesd07986f2011-12-06 18:27:45 -08002867 } else if (pReq->result_tag == JDWP::JT_OBJECT) {
2868 /* if no exception thrown, examine object result more closely */
Elliott Hughesf24d3ce2012-04-11 17:43:37 -07002869 JDWP::JdwpTag new_tag = TagFromObject(pReq->result_value.GetL());
Elliott Hughesd07986f2011-12-06 18:27:45 -08002870 if (new_tag != pReq->result_tag) {
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08002871 VLOG(jdwp) << " JDWP promoted result from " << pReq->result_tag << " to " << new_tag;
Elliott Hughesd07986f2011-12-06 18:27:45 -08002872 pReq->result_tag = new_tag;
2873 }
2874
2875 /*
2876 * Register the object. We don't actually need an ObjectId yet,
2877 * but we do need to be sure that the GC won't move or discard the
2878 * object when we switch out of RUNNING. The ObjectId conversion
2879 * will add the object to the "do not touch" list.
2880 *
2881 * We can't use the "tracked allocation" mechanism here because
2882 * the object is going to be handed off to a different thread.
2883 */
Elliott Hughesf24d3ce2012-04-11 17:43:37 -07002884 gRegistry->Add(pReq->result_value.GetL());
Elliott Hughesd07986f2011-12-06 18:27:45 -08002885 }
2886
2887 if (old_exception.get() != NULL) {
Ian Rogers62d6c772013-02-27 08:32:07 -08002888 ThrowLocation gc_safe_throw_location(old_throw_this_object.get(), old_throw_method.get(),
2889 old_throw_dex_pc);
2890 soa.Self()->SetException(gc_safe_throw_location, old_exception.get());
Elliott Hughesd07986f2011-12-06 18:27:45 -08002891 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002892}
2893
Elliott Hughesd07986f2011-12-06 18:27:45 -08002894/*
Elliott Hughes4b9702c2013-02-20 18:13:24 -08002895 * "request" contains a full JDWP packet, possibly with multiple chunks. We
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07002896 * need to process each, accumulate the replies, and ship the whole thing
2897 * back.
2898 *
2899 * Returns "true" if we have a reply. The reply buffer is newly allocated,
2900 * and includes the chunk type/length, followed by the data.
2901 *
Elliott Hughes3d30d9b2011-12-07 17:35:48 -08002902 * OLD-TODO: we currently assume that the request and reply include a single
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07002903 * chunk. If this becomes inconvenient we will need to adapt.
2904 */
Elliott Hughes4b9702c2013-02-20 18:13:24 -08002905bool Dbg::DdmHandlePacket(JDWP::Request& request, uint8_t** pReplyBuf, int* pReplyLen) {
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07002906 Thread* self = Thread::Current();
2907 JNIEnv* env = self->GetJniEnv();
2908
Elliott Hughes4b9702c2013-02-20 18:13:24 -08002909 uint32_t type = request.ReadUnsigned32("type");
2910 uint32_t length = request.ReadUnsigned32("length");
2911
2912 // Create a byte[] corresponding to 'request'.
2913 size_t request_length = request.size();
2914 ScopedLocalRef<jbyteArray> dataArray(env, env->NewByteArray(request_length));
Elliott Hughes6a5bd492011-10-28 14:33:57 -07002915 if (dataArray.get() == NULL) {
Elliott Hughes4b9702c2013-02-20 18:13:24 -08002916 LOG(WARNING) << "byte[] allocation failed: " << request_length;
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07002917 env->ExceptionClear();
2918 return false;
2919 }
Elliott Hughes4b9702c2013-02-20 18:13:24 -08002920 env->SetByteArrayRegion(dataArray.get(), 0, request_length, reinterpret_cast<const jbyte*>(request.data()));
2921 request.Skip(request_length);
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07002922
2923 // Run through and find all chunks. [Currently just find the first.]
Elliott Hughes6a5bd492011-10-28 14:33:57 -07002924 ScopedByteArrayRO contents(env, dataArray.get());
Elliott Hughes4b9702c2013-02-20 18:13:24 -08002925 if (length != request_length) {
2926 LOG(WARNING) << StringPrintf("bad chunk found (len=%u pktLen=%d)", length, request_length);
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07002927 return false;
2928 }
2929
2930 // Call "private static Chunk dispatch(int type, byte[] data, int offset, int length)".
Elliott Hugheseac76672012-05-24 21:56:51 -07002931 ScopedLocalRef<jobject> chunk(env, env->CallStaticObjectMethod(WellKnownClasses::org_apache_harmony_dalvik_ddmc_DdmServer,
2932 WellKnownClasses::org_apache_harmony_dalvik_ddmc_DdmServer_dispatch,
Elliott Hughes4b9702c2013-02-20 18:13:24 -08002933 type, dataArray.get(), 0, length));
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07002934 if (env->ExceptionCheck()) {
2935 LOG(INFO) << StringPrintf("Exception thrown by dispatcher for 0x%08x", type);
2936 env->ExceptionDescribe();
2937 env->ExceptionClear();
2938 return false;
2939 }
2940
Elliott Hughes6a5bd492011-10-28 14:33:57 -07002941 if (chunk.get() == NULL) {
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07002942 return false;
2943 }
2944
2945 /*
2946 * Pull the pieces out of the chunk. We copy the results into a
2947 * newly-allocated buffer that the caller can free. We don't want to
2948 * continue using the Chunk object because nothing has a reference to it.
2949 *
2950 * We could avoid this by returning type/data/offset/length and having
2951 * the caller be aware of the object lifetime issues, but that
Elliott Hughes81ff3182012-03-23 20:35:56 -07002952 * integrates the JDWP code more tightly into the rest of the runtime, and doesn't work
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07002953 * if we have responses for multiple chunks.
2954 *
2955 * So we're pretty much stuck with copying data around multiple times.
2956 */
Elliott Hugheseac76672012-05-24 21:56:51 -07002957 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 -08002958 jint offset = env->GetIntField(chunk.get(), WellKnownClasses::org_apache_harmony_dalvik_ddmc_Chunk_offset);
Elliott Hugheseac76672012-05-24 21:56:51 -07002959 length = env->GetIntField(chunk.get(), WellKnownClasses::org_apache_harmony_dalvik_ddmc_Chunk_length);
Elliott Hugheseac76672012-05-24 21:56:51 -07002960 type = env->GetIntField(chunk.get(), WellKnownClasses::org_apache_harmony_dalvik_ddmc_Chunk_type);
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07002961
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08002962 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 -07002963 if (length == 0 || replyData.get() == NULL) {
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07002964 return false;
2965 }
2966
Elliott Hughes4b9702c2013-02-20 18:13:24 -08002967 const int kChunkHdrLen = 8;
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07002968 uint8_t* reply = new uint8_t[length + kChunkHdrLen];
2969 if (reply == NULL) {
2970 LOG(WARNING) << "malloc failed: " << (length + kChunkHdrLen);
2971 return false;
2972 }
Elliott Hughesf7c3b662011-10-27 12:04:56 -07002973 JDWP::Set4BE(reply + 0, type);
2974 JDWP::Set4BE(reply + 4, length);
Elliott Hughes6a5bd492011-10-28 14:33:57 -07002975 env->GetByteArrayRegion(replyData.get(), offset, length, reinterpret_cast<jbyte*>(reply + kChunkHdrLen));
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07002976
2977 *pReplyBuf = reply;
2978 *pReplyLen = length + kChunkHdrLen;
2979
Elliott Hughes4b9702c2013-02-20 18:13:24 -08002980 VLOG(jdwp) << StringPrintf("dvmHandleDdm returning type=%.4s %p len=%d", reinterpret_cast<char*>(reply), reply, length);
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07002981 return true;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002982}
2983
Elliott Hughesa2155262011-11-16 16:26:58 -08002984void Dbg::DdmBroadcast(bool connect) {
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08002985 VLOG(jdwp) << "Broadcasting DDM " << (connect ? "connect" : "disconnect") << "...";
Elliott Hughes47fce012011-10-25 18:37:19 -07002986
2987 Thread* self = Thread::Current();
Ian Rogers50b35e22012-10-04 10:09:15 -07002988 if (self->GetState() != kRunnable) {
2989 LOG(ERROR) << "DDM broadcast in thread state " << self->GetState();
2990 /* try anyway? */
Elliott Hughes47fce012011-10-25 18:37:19 -07002991 }
2992
2993 JNIEnv* env = self->GetJniEnv();
Elliott Hughes47fce012011-10-25 18:37:19 -07002994 jint event = connect ? 1 /*DdmServer.CONNECTED*/ : 2 /*DdmServer.DISCONNECTED*/;
Elliott Hugheseac76672012-05-24 21:56:51 -07002995 env->CallStaticVoidMethod(WellKnownClasses::org_apache_harmony_dalvik_ddmc_DdmServer,
2996 WellKnownClasses::org_apache_harmony_dalvik_ddmc_DdmServer_broadcast,
2997 event);
Elliott Hughes47fce012011-10-25 18:37:19 -07002998 if (env->ExceptionCheck()) {
2999 LOG(ERROR) << "DdmServer.broadcast " << event << " failed";
3000 env->ExceptionDescribe();
3001 env->ExceptionClear();
3002 }
3003}
3004
Elliott Hughes872d4ec2011-10-21 17:07:15 -07003005void Dbg::DdmConnected() {
Elliott Hughesa2155262011-11-16 16:26:58 -08003006 Dbg::DdmBroadcast(true);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07003007}
3008
3009void Dbg::DdmDisconnected() {
Elliott Hughesa2155262011-11-16 16:26:58 -08003010 Dbg::DdmBroadcast(false);
Elliott Hughes47fce012011-10-25 18:37:19 -07003011 gDdmThreadNotification = false;
3012}
3013
3014/*
Elliott Hughes82188472011-11-07 18:11:48 -08003015 * Send a notification when a thread starts, stops, or changes its name.
Elliott Hughes47fce012011-10-25 18:37:19 -07003016 *
3017 * Because we broadcast the full set of threads when the notifications are
3018 * first enabled, it's possible for "thread" to be actively executing.
3019 */
Elliott Hughes82188472011-11-07 18:11:48 -08003020void Dbg::DdmSendThreadNotification(Thread* t, uint32_t type) {
Elliott Hughes47fce012011-10-25 18:37:19 -07003021 if (!gDdmThreadNotification) {
3022 return;
3023 }
3024
Elliott Hughes82188472011-11-07 18:11:48 -08003025 if (type == CHUNK_TYPE("THDE")) {
Elliott Hughes47fce012011-10-25 18:37:19 -07003026 uint8_t buf[4];
Ian Rogersd9c4fc92013-10-01 19:45:43 -07003027 JDWP::Set4BE(&buf[0], t->GetThreadId());
Elliott Hughes47fce012011-10-25 18:37:19 -07003028 Dbg::DdmSendChunk(CHUNK_TYPE("THDE"), 4, buf);
Elliott Hughes82188472011-11-07 18:11:48 -08003029 } else {
3030 CHECK(type == CHUNK_TYPE("THCR") || type == CHUNK_TYPE("THNM")) << type;
Ian Rogers00f7d0e2012-07-19 15:28:27 -07003031 ScopedObjectAccessUnchecked soa(Thread::Current());
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003032 SirtRef<mirror::String> name(soa.Self(), t->GetThreadName(soa));
Elliott Hughes82188472011-11-07 18:11:48 -08003033 size_t char_count = (name.get() != NULL) ? name->GetLength() : 0;
jeffhao725a9572012-11-13 18:20:12 -08003034 const jchar* chars = (name.get() != NULL) ? name->GetCharArray()->GetData() : NULL;
Elliott Hughes82188472011-11-07 18:11:48 -08003035
Elliott Hughes21f32d72011-11-09 17:44:13 -08003036 std::vector<uint8_t> bytes;
Ian Rogersd9c4fc92013-10-01 19:45:43 -07003037 JDWP::Append4BE(bytes, t->GetThreadId());
Elliott Hughes545a0642011-11-08 19:10:03 -08003038 JDWP::AppendUtf16BE(bytes, chars, char_count);
Elliott Hughes21f32d72011-11-09 17:44:13 -08003039 CHECK_EQ(bytes.size(), char_count*2 + sizeof(uint32_t)*2);
3040 Dbg::DdmSendChunk(type, bytes);
Elliott Hughes47fce012011-10-25 18:37:19 -07003041 }
3042}
3043
Elliott Hughes47fce012011-10-25 18:37:19 -07003044void Dbg::DdmSetThreadNotification(bool enable) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07003045 // Enable/disable thread notifications.
Elliott Hughes47fce012011-10-25 18:37:19 -07003046 gDdmThreadNotification = enable;
3047 if (enable) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07003048 // Suspend the VM then post thread start notifications for all threads. Threads attaching will
3049 // see a suspension in progress and block until that ends. They then post their own start
3050 // notification.
3051 SuspendVM();
3052 std::list<Thread*> threads;
Ian Rogers50b35e22012-10-04 10:09:15 -07003053 Thread* self = Thread::Current();
Ian Rogers00f7d0e2012-07-19 15:28:27 -07003054 {
Ian Rogers50b35e22012-10-04 10:09:15 -07003055 MutexLock mu(self, *Locks::thread_list_lock_);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07003056 threads = Runtime::Current()->GetThreadList()->GetList();
3057 }
3058 {
Ian Rogers50b35e22012-10-04 10:09:15 -07003059 ScopedObjectAccess soa(self);
Mathieu Chartier02e25112013-08-14 16:14:24 -07003060 for (Thread* thread : threads) {
3061 Dbg::DdmSendThreadNotification(thread, CHUNK_TYPE("THCR"));
Ian Rogers00f7d0e2012-07-19 15:28:27 -07003062 }
3063 }
3064 ResumeVM();
Elliott Hughes47fce012011-10-25 18:37:19 -07003065 }
3066}
3067
Elliott Hughesa2155262011-11-16 16:26:58 -08003068void Dbg::PostThreadStartOrStop(Thread* t, uint32_t type) {
Elliott Hughesc0f09332012-03-26 13:27:06 -07003069 if (IsDebuggerActive()) {
Mathieu Chartierdbe6f462012-09-25 16:54:50 -07003070 ScopedObjectAccessUnchecked soa(Thread::Current());
Ian Rogerscfaa4552012-11-26 21:00:08 -08003071 JDWP::ObjectId id = gRegistry->Add(t->GetPeer());
Elliott Hughes82188472011-11-07 18:11:48 -08003072 gJdwpState->PostThreadChange(id, type == CHUNK_TYPE("THCR"));
Elliott Hughes47fce012011-10-25 18:37:19 -07003073 }
Elliott Hughes82188472011-11-07 18:11:48 -08003074 Dbg::DdmSendThreadNotification(t, type);
Elliott Hughes47fce012011-10-25 18:37:19 -07003075}
3076
3077void Dbg::PostThreadStart(Thread* t) {
Elliott Hughesa2155262011-11-16 16:26:58 -08003078 Dbg::PostThreadStartOrStop(t, CHUNK_TYPE("THCR"));
Elliott Hughes47fce012011-10-25 18:37:19 -07003079}
3080
3081void Dbg::PostThreadDeath(Thread* t) {
Elliott Hughesa2155262011-11-16 16:26:58 -08003082 Dbg::PostThreadStartOrStop(t, CHUNK_TYPE("THDE"));
Elliott Hughes872d4ec2011-10-21 17:07:15 -07003083}
3084
Elliott Hughes82188472011-11-07 18:11:48 -08003085void Dbg::DdmSendChunk(uint32_t type, size_t byte_count, const uint8_t* buf) {
Elliott Hughes3bb81562011-10-21 18:52:59 -07003086 CHECK(buf != NULL);
3087 iovec vec[1];
3088 vec[0].iov_base = reinterpret_cast<void*>(const_cast<uint8_t*>(buf));
3089 vec[0].iov_len = byte_count;
3090 Dbg::DdmSendChunkV(type, vec, 1);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07003091}
3092
Elliott Hughes21f32d72011-11-09 17:44:13 -08003093void Dbg::DdmSendChunk(uint32_t type, const std::vector<uint8_t>& bytes) {
3094 DdmSendChunk(type, bytes.size(), &bytes[0]);
3095}
3096
Brian Carlstromf5293522013-07-19 00:24:00 -07003097void Dbg::DdmSendChunkV(uint32_t type, const iovec* iov, int iov_count) {
Elliott Hughes3bb81562011-10-21 18:52:59 -07003098 if (gJdwpState == NULL) {
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08003099 VLOG(jdwp) << "Debugger thread not active, ignoring DDM send: " << type;
Elliott Hughes3bb81562011-10-21 18:52:59 -07003100 } else {
Elliott Hughescccd84f2011-12-05 16:51:54 -08003101 gJdwpState->DdmSendChunkV(type, iov, iov_count);
Elliott Hughes3bb81562011-10-21 18:52:59 -07003102 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -07003103}
3104
Elliott Hughes767a1472011-10-26 18:49:02 -07003105int Dbg::DdmHandleHpifChunk(HpifWhen when) {
3106 if (when == HPIF_WHEN_NOW) {
Elliott Hughes7162ad92011-10-27 14:08:42 -07003107 DdmSendHeapInfo(when);
Elliott Hughes767a1472011-10-26 18:49:02 -07003108 return true;
3109 }
3110
3111 if (when != HPIF_WHEN_NEVER && when != HPIF_WHEN_NEXT_GC && when != HPIF_WHEN_EVERY_GC) {
3112 LOG(ERROR) << "invalid HpifWhen value: " << static_cast<int>(when);
3113 return false;
3114 }
3115
3116 gDdmHpifWhen = when;
3117 return true;
3118}
3119
3120bool Dbg::DdmHandleHpsgNhsgChunk(Dbg::HpsgWhen when, Dbg::HpsgWhat what, bool native) {
3121 if (when != HPSG_WHEN_NEVER && when != HPSG_WHEN_EVERY_GC) {
3122 LOG(ERROR) << "invalid HpsgWhen value: " << static_cast<int>(when);
3123 return false;
3124 }
3125
3126 if (what != HPSG_WHAT_MERGED_OBJECTS && what != HPSG_WHAT_DISTINCT_OBJECTS) {
3127 LOG(ERROR) << "invalid HpsgWhat value: " << static_cast<int>(what);
3128 return false;
3129 }
3130
3131 if (native) {
3132 gDdmNhsgWhen = when;
3133 gDdmNhsgWhat = what;
3134 } else {
3135 gDdmHpsgWhen = when;
3136 gDdmHpsgWhat = what;
3137 }
3138 return true;
3139}
3140
Elliott Hughes7162ad92011-10-27 14:08:42 -07003141void Dbg::DdmSendHeapInfo(HpifWhen reason) {
3142 // If there's a one-shot 'when', reset it.
3143 if (reason == gDdmHpifWhen) {
3144 if (gDdmHpifWhen == HPIF_WHEN_NEXT_GC) {
3145 gDdmHpifWhen = HPIF_WHEN_NEVER;
3146 }
3147 }
3148
3149 /*
3150 * Chunk HPIF (client --> server)
3151 *
3152 * Heap Info. General information about the heap,
3153 * suitable for a summary display.
3154 *
3155 * [u4]: number of heaps
3156 *
3157 * For each heap:
3158 * [u4]: heap ID
3159 * [u8]: timestamp in ms since Unix epoch
3160 * [u1]: capture reason (same as 'when' value from server)
3161 * [u4]: max heap size in bytes (-Xmx)
3162 * [u4]: current heap size in bytes
3163 * [u4]: current number of bytes allocated
3164 * [u4]: current number of objects allocated
3165 */
3166 uint8_t heap_count = 1;
Ian Rogers1d54e732013-05-02 21:10:01 -07003167 gc::Heap* heap = Runtime::Current()->GetHeap();
Elliott Hughes21f32d72011-11-09 17:44:13 -08003168 std::vector<uint8_t> bytes;
Elliott Hughes545a0642011-11-08 19:10:03 -08003169 JDWP::Append4BE(bytes, heap_count);
Brian Carlstrom7934ac22013-07-26 10:54:15 -07003170 JDWP::Append4BE(bytes, 1); // Heap id (bogus; we only have one heap).
Elliott Hughes545a0642011-11-08 19:10:03 -08003171 JDWP::Append8BE(bytes, MilliTime());
3172 JDWP::Append1BE(bytes, reason);
Brian Carlstrom7934ac22013-07-26 10:54:15 -07003173 JDWP::Append4BE(bytes, heap->GetMaxMemory()); // Max allowed heap size in bytes.
3174 JDWP::Append4BE(bytes, heap->GetTotalMemory()); // Current heap size in bytes.
Elliott Hughesb3bd5f02012-03-08 21:05:27 -08003175 JDWP::Append4BE(bytes, heap->GetBytesAllocated());
3176 JDWP::Append4BE(bytes, heap->GetObjectsAllocated());
Elliott Hughes21f32d72011-11-09 17:44:13 -08003177 CHECK_EQ(bytes.size(), 4U + (heap_count * (4 + 8 + 1 + 4 + 4 + 4 + 4)));
3178 Dbg::DdmSendChunk(CHUNK_TYPE("HPIF"), bytes);
Elliott Hughes767a1472011-10-26 18:49:02 -07003179}
3180
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003181enum HpsgSolidity {
3182 SOLIDITY_FREE = 0,
3183 SOLIDITY_HARD = 1,
3184 SOLIDITY_SOFT = 2,
3185 SOLIDITY_WEAK = 3,
3186 SOLIDITY_PHANTOM = 4,
3187 SOLIDITY_FINALIZABLE = 5,
3188 SOLIDITY_SWEEP = 6,
3189};
3190
3191enum HpsgKind {
3192 KIND_OBJECT = 0,
3193 KIND_CLASS_OBJECT = 1,
3194 KIND_ARRAY_1 = 2,
3195 KIND_ARRAY_2 = 3,
3196 KIND_ARRAY_4 = 4,
3197 KIND_ARRAY_8 = 5,
3198 KIND_UNKNOWN = 6,
3199 KIND_NATIVE = 7,
3200};
3201
3202#define HPSG_PARTIAL (1<<7)
3203#define HPSG_STATE(solidity, kind) ((uint8_t)((((kind) & 0x7) << 3) | ((solidity) & 0x7)))
3204
Ian Rogers30fab402012-01-23 15:43:46 -08003205class HeapChunkContext {
3206 public:
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003207 // Maximum chunk size. Obtain this from the formula:
3208 // (((maximum_heap_size / ALLOCATION_UNIT_SIZE) + 255) / 256) * 2
3209 HeapChunkContext(bool merge, bool native)
Ian Rogers30fab402012-01-23 15:43:46 -08003210 : buf_(16384 - 16),
3211 type_(0),
3212 merge_(merge) {
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003213 Reset();
3214 if (native) {
Ian Rogers30fab402012-01-23 15:43:46 -08003215 type_ = CHUNK_TYPE("NHSG");
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003216 } else {
Ian Rogers30fab402012-01-23 15:43:46 -08003217 type_ = merge ? CHUNK_TYPE("HPSG") : CHUNK_TYPE("HPSO");
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003218 }
3219 }
3220
3221 ~HeapChunkContext() {
Ian Rogers30fab402012-01-23 15:43:46 -08003222 if (p_ > &buf_[0]) {
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003223 Flush();
3224 }
3225 }
3226
3227 void EnsureHeader(const void* chunk_ptr) {
Ian Rogers30fab402012-01-23 15:43:46 -08003228 if (!needHeader_) {
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003229 return;
3230 }
3231
3232 // Start a new HPSx chunk.
Brian Carlstrom7934ac22013-07-26 10:54:15 -07003233 JDWP::Write4BE(&p_, 1); // Heap id (bogus; we only have one heap).
3234 JDWP::Write1BE(&p_, 8); // Size of allocation unit, in bytes.
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003235
Brian Carlstrom7934ac22013-07-26 10:54:15 -07003236 JDWP::Write4BE(&p_, reinterpret_cast<uintptr_t>(chunk_ptr)); // virtual address of segment start.
3237 JDWP::Write4BE(&p_, 0); // offset of this piece (relative to the virtual address).
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003238 // [u4]: length of piece, in allocation units
3239 // 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 -08003240 pieceLenField_ = p_;
3241 JDWP::Write4BE(&p_, 0x55555555);
3242 needHeader_ = false;
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003243 }
3244
Ian Rogersb726dcb2012-09-05 08:57:23 -07003245 void Flush() SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Ian Rogersd636b062013-01-18 17:51:18 -08003246 if (pieceLenField_ == NULL) {
3247 // Flush immediately post Reset (maybe back-to-back Flush). Ignore.
3248 CHECK(needHeader_);
3249 return;
3250 }
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003251 // Patch the "length of piece" field.
Ian Rogers30fab402012-01-23 15:43:46 -08003252 CHECK_LE(&buf_[0], pieceLenField_);
3253 CHECK_LE(pieceLenField_, p_);
3254 JDWP::Set4BE(pieceLenField_, totalAllocationUnits_);
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003255
Ian Rogers30fab402012-01-23 15:43:46 -08003256 Dbg::DdmSendChunk(type_, p_ - &buf_[0], &buf_[0]);
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003257 Reset();
3258 }
3259
Ian Rogers00f7d0e2012-07-19 15:28:27 -07003260 static void HeapChunkCallback(void* start, void* end, size_t used_bytes, void* arg)
Ian Rogersb726dcb2012-09-05 08:57:23 -07003261 SHARED_LOCKS_REQUIRED(Locks::heap_bitmap_lock_,
3262 Locks::mutator_lock_) {
Ian Rogers30fab402012-01-23 15:43:46 -08003263 reinterpret_cast<HeapChunkContext*>(arg)->HeapChunkCallback(start, end, used_bytes);
Elliott Hughesa2155262011-11-16 16:26:58 -08003264 }
3265
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003266 private:
Elliott Hughesa2155262011-11-16 16:26:58 -08003267 enum { ALLOCATION_UNIT_SIZE = 8 };
3268
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003269 void Reset() {
Ian Rogers30fab402012-01-23 15:43:46 -08003270 p_ = &buf_[0];
Ian Rogers15bf2d32012-08-28 17:33:04 -07003271 startOfNextMemoryChunk_ = NULL;
Ian Rogers30fab402012-01-23 15:43:46 -08003272 totalAllocationUnits_ = 0;
3273 needHeader_ = true;
3274 pieceLenField_ = NULL;
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003275 }
3276
Ian Rogers00f7d0e2012-07-19 15:28:27 -07003277 void HeapChunkCallback(void* start, void* /*end*/, size_t used_bytes)
Ian Rogersb726dcb2012-09-05 08:57:23 -07003278 SHARED_LOCKS_REQUIRED(Locks::heap_bitmap_lock_,
3279 Locks::mutator_lock_) {
Ian Rogers30fab402012-01-23 15:43:46 -08003280 // Note: heap call backs cannot manipulate the heap upon which they are crawling, care is taken
3281 // in the following code not to allocate memory, by ensuring buf_ is of the correct size
Ian Rogers15bf2d32012-08-28 17:33:04 -07003282 if (used_bytes == 0) {
3283 if (start == NULL) {
3284 // Reset for start of new heap.
3285 startOfNextMemoryChunk_ = NULL;
3286 Flush();
3287 }
3288 // Only process in use memory so that free region information
3289 // also includes dlmalloc book keeping.
Elliott Hughesa2155262011-11-16 16:26:58 -08003290 return;
Elliott Hughesa2155262011-11-16 16:26:58 -08003291 }
3292
Ian Rogers15bf2d32012-08-28 17:33:04 -07003293 /* If we're looking at the native heap, we'll just return
3294 * (SOLIDITY_HARD, KIND_NATIVE) for all allocated chunks
3295 */
3296 bool native = type_ == CHUNK_TYPE("NHSG");
3297
3298 if (startOfNextMemoryChunk_ != NULL) {
3299 // Transmit any pending free memory. Native free memory of
3300 // over kMaxFreeLen could be because of the use of mmaps, so
3301 // don't report. If not free memory then start a new segment.
3302 bool flush = true;
3303 if (start > startOfNextMemoryChunk_) {
3304 const size_t kMaxFreeLen = 2 * kPageSize;
3305 void* freeStart = startOfNextMemoryChunk_;
3306 void* freeEnd = start;
Brian Carlstrom2d888622013-07-18 17:02:00 -07003307 size_t freeLen = reinterpret_cast<char*>(freeEnd) - reinterpret_cast<char*>(freeStart);
Ian Rogers15bf2d32012-08-28 17:33:04 -07003308 if (!native || freeLen < kMaxFreeLen) {
3309 AppendChunk(HPSG_STATE(SOLIDITY_FREE, 0), freeStart, freeLen);
3310 flush = false;
3311 }
3312 }
3313 if (flush) {
3314 startOfNextMemoryChunk_ = NULL;
3315 Flush();
3316 }
3317 }
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003318 const mirror::Object* obj = reinterpret_cast<const mirror::Object*>(start);
Elliott Hughesa2155262011-11-16 16:26:58 -08003319
3320 // Determine the type of this chunk.
3321 // OLD-TODO: if context.merge, see if this chunk is different from the last chunk.
3322 // If it's the same, we should combine them.
Ian Rogers15bf2d32012-08-28 17:33:04 -07003323 uint8_t state = ExamineObject(obj, native);
3324 // dlmalloc's chunk header is 2 * sizeof(size_t), but if the previous chunk is in use for an
3325 // allocation then the first sizeof(size_t) may belong to it.
3326 const size_t dlMallocOverhead = sizeof(size_t);
3327 AppendChunk(state, start, used_bytes + dlMallocOverhead);
Brian Carlstrom2d888622013-07-18 17:02:00 -07003328 startOfNextMemoryChunk_ = reinterpret_cast<char*>(start) + used_bytes + dlMallocOverhead;
Ian Rogers15bf2d32012-08-28 17:33:04 -07003329 }
Elliott Hughesa2155262011-11-16 16:26:58 -08003330
Ian Rogers15bf2d32012-08-28 17:33:04 -07003331 void AppendChunk(uint8_t state, void* ptr, size_t length)
Ian Rogersb726dcb2012-09-05 08:57:23 -07003332 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Ian Rogers15bf2d32012-08-28 17:33:04 -07003333 // Make sure there's enough room left in the buffer.
3334 // We need to use two bytes for every fractional 256 allocation units used by the chunk plus
3335 // 17 bytes for any header.
3336 size_t needed = (((length/ALLOCATION_UNIT_SIZE + 255) / 256) * 2) + 17;
3337 size_t bytesLeft = buf_.size() - (size_t)(p_ - &buf_[0]);
3338 if (bytesLeft < needed) {
3339 Flush();
3340 }
3341
3342 bytesLeft = buf_.size() - (size_t)(p_ - &buf_[0]);
3343 if (bytesLeft < needed) {
3344 LOG(WARNING) << "Chunk is too big to transmit (chunk_len=" << length << ", "
3345 << needed << " bytes)";
3346 return;
3347 }
3348 EnsureHeader(ptr);
Elliott Hughesa2155262011-11-16 16:26:58 -08003349 // Write out the chunk description.
Ian Rogers15bf2d32012-08-28 17:33:04 -07003350 length /= ALLOCATION_UNIT_SIZE; // Convert to allocation units.
3351 totalAllocationUnits_ += length;
3352 while (length > 256) {
Ian Rogers30fab402012-01-23 15:43:46 -08003353 *p_++ = state | HPSG_PARTIAL;
3354 *p_++ = 255; // length - 1
Ian Rogers15bf2d32012-08-28 17:33:04 -07003355 length -= 256;
Elliott Hughesa2155262011-11-16 16:26:58 -08003356 }
Ian Rogers30fab402012-01-23 15:43:46 -08003357 *p_++ = state;
Ian Rogers15bf2d32012-08-28 17:33:04 -07003358 *p_++ = length - 1;
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003359 }
3360
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003361 uint8_t ExamineObject(const mirror::Object* o, bool is_native_heap)
Ian Rogersb726dcb2012-09-05 08:57:23 -07003362 SHARED_LOCKS_REQUIRED(Locks::heap_bitmap_lock_) {
Elliott Hughesa2155262011-11-16 16:26:58 -08003363 if (o == NULL) {
3364 return HPSG_STATE(SOLIDITY_FREE, 0);
3365 }
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003366
Elliott Hughesa2155262011-11-16 16:26:58 -08003367 // It's an allocated chunk. Figure out what it is.
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003368
Elliott Hughesa2155262011-11-16 16:26:58 -08003369 // If we're looking at the native heap, we'll just return
3370 // (SOLIDITY_HARD, KIND_NATIVE) for all allocated chunks.
Ian Rogers00f7d0e2012-07-19 15:28:27 -07003371 if (is_native_heap) {
Elliott Hughesa2155262011-11-16 16:26:58 -08003372 return HPSG_STATE(SOLIDITY_HARD, KIND_NATIVE);
3373 }
3374
Ian Rogers5bfa60f2012-09-02 21:17:56 -07003375 if (!Runtime::Current()->GetHeap()->IsLiveObjectLocked(o)) {
Ian Rogers15bf2d32012-08-28 17:33:04 -07003376 return HPSG_STATE(SOLIDITY_HARD, KIND_NATIVE);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07003377 }
3378
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003379 mirror::Class* c = o->GetClass();
Elliott Hughesa2155262011-11-16 16:26:58 -08003380 if (c == NULL) {
3381 // The object was probably just created but hasn't been initialized yet.
3382 return HPSG_STATE(SOLIDITY_HARD, KIND_OBJECT);
3383 }
3384
Mathieu Chartier590fee92013-09-13 13:46:47 -07003385 if (!Runtime::Current()->GetHeap()->IsValidObjectAddress(c)) {
Ian Rogers15bf2d32012-08-28 17:33:04 -07003386 LOG(ERROR) << "Invalid class for managed heap object: " << o << " " << c;
Elliott Hughesa2155262011-11-16 16:26:58 -08003387 return HPSG_STATE(SOLIDITY_HARD, KIND_UNKNOWN);
3388 }
3389
3390 if (c->IsClassClass()) {
3391 return HPSG_STATE(SOLIDITY_HARD, KIND_CLASS_OBJECT);
3392 }
3393
3394 if (c->IsArrayClass()) {
3395 if (o->IsObjectArray()) {
3396 return HPSG_STATE(SOLIDITY_HARD, KIND_ARRAY_4);
3397 }
3398 switch (c->GetComponentSize()) {
3399 case 1: return HPSG_STATE(SOLIDITY_HARD, KIND_ARRAY_1);
3400 case 2: return HPSG_STATE(SOLIDITY_HARD, KIND_ARRAY_2);
3401 case 4: return HPSG_STATE(SOLIDITY_HARD, KIND_ARRAY_4);
3402 case 8: return HPSG_STATE(SOLIDITY_HARD, KIND_ARRAY_8);
3403 }
3404 }
3405
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003406 return HPSG_STATE(SOLIDITY_HARD, KIND_OBJECT);
3407 }
3408
Ian Rogers30fab402012-01-23 15:43:46 -08003409 std::vector<uint8_t> buf_;
3410 uint8_t* p_;
3411 uint8_t* pieceLenField_;
Ian Rogers15bf2d32012-08-28 17:33:04 -07003412 void* startOfNextMemoryChunk_;
Ian Rogers30fab402012-01-23 15:43:46 -08003413 size_t totalAllocationUnits_;
3414 uint32_t type_;
3415 bool merge_;
3416 bool needHeader_;
3417
Elliott Hughesa2155262011-11-16 16:26:58 -08003418 DISALLOW_COPY_AND_ASSIGN(HeapChunkContext);
3419};
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003420
3421void Dbg::DdmSendHeapSegments(bool native) {
3422 Dbg::HpsgWhen when;
3423 Dbg::HpsgWhat what;
3424 if (!native) {
3425 when = gDdmHpsgWhen;
3426 what = gDdmHpsgWhat;
3427 } else {
3428 when = gDdmNhsgWhen;
3429 what = gDdmNhsgWhat;
3430 }
3431 if (when == HPSG_WHEN_NEVER) {
3432 return;
3433 }
3434
3435 // Figure out what kind of chunks we'll be sending.
3436 CHECK(what == HPSG_WHAT_MERGED_OBJECTS || what == HPSG_WHAT_DISTINCT_OBJECTS) << static_cast<int>(what);
3437
3438 // First, send a heap start chunk.
3439 uint8_t heap_id[4];
Brian Carlstrom7934ac22013-07-26 10:54:15 -07003440 JDWP::Set4BE(&heap_id[0], 1); // Heap id (bogus; we only have one heap).
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003441 Dbg::DdmSendChunk(native ? CHUNK_TYPE("NHST") : CHUNK_TYPE("HPST"), sizeof(heap_id), heap_id);
3442
Hiroshi Yamauchicf58d4a2013-09-26 14:21:22 -07003443 Thread* self = Thread::Current();
3444
3445 // To allow the Walk/InspectAll() below to exclusively-lock the
3446 // mutator lock, temporarily release the shared access to the
3447 // mutator lock here by transitioning to the suspended state.
3448 Locks::mutator_lock_->AssertSharedHeld(self);
3449 self->TransitionFromRunnableToSuspended(kSuspended);
3450
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003451 // Send a series of heap segment chunks.
Elliott Hughesa2155262011-11-16 16:26:58 -08003452 HeapChunkContext context((what == HPSG_WHAT_MERGED_OBJECTS), native);
3453 if (native) {
Ian Rogers1d54e732013-05-02 21:10:01 -07003454 dlmalloc_inspect_all(HeapChunkContext::HeapChunkCallback, &context);
Elliott Hughesa2155262011-11-16 16:26:58 -08003455 } else {
Ian Rogers1d54e732013-05-02 21:10:01 -07003456 gc::Heap* heap = Runtime::Current()->GetHeap();
3457 const std::vector<gc::space::ContinuousSpace*>& spaces = heap->GetContinuousSpaces();
Ian Rogers62d6c772013-02-27 08:32:07 -08003458 ReaderMutexLock mu(self, *Locks::heap_bitmap_lock_);
Ian Rogers1d54e732013-05-02 21:10:01 -07003459 typedef std::vector<gc::space::ContinuousSpace*>::const_iterator It;
3460 for (It cur = spaces.begin(), end = spaces.end(); cur != end; ++cur) {
Hiroshi Yamauchicf58d4a2013-09-26 14:21:22 -07003461 if ((*cur)->IsMallocSpace()) {
3462 (*cur)->AsMallocSpace()->Walk(HeapChunkContext::HeapChunkCallback, &context);
Mathieu Chartierb062fdd2012-07-03 09:51:48 -07003463 }
3464 }
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -07003465 // Walk the large objects, these are not in the AllocSpace.
3466 heap->GetLargeObjectsSpace()->Walk(HeapChunkContext::HeapChunkCallback, &context);
Elliott Hughesa2155262011-11-16 16:26:58 -08003467 }
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003468
Hiroshi Yamauchicf58d4a2013-09-26 14:21:22 -07003469 // Shared-lock the mutator lock back.
3470 self->TransitionFromSuspendedToRunnable();
3471 Locks::mutator_lock_->AssertSharedHeld(self);
3472
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003473 // Finally, send a heap end chunk.
3474 Dbg::DdmSendChunk(native ? CHUNK_TYPE("NHEN") : CHUNK_TYPE("HPEN"), sizeof(heap_id), heap_id);
Elliott Hughes767a1472011-10-26 18:49:02 -07003475}
3476
Elliott Hughesb1a58792013-07-11 18:10:58 -07003477static size_t GetAllocTrackerMax() {
3478#ifdef HAVE_ANDROID_OS
3479 // Check whether there's a system property overriding the number of records.
3480 const char* propertyName = "dalvik.vm.allocTrackerMax";
3481 char allocRecordMaxString[PROPERTY_VALUE_MAX];
3482 if (property_get(propertyName, allocRecordMaxString, "") > 0) {
3483 char* end;
3484 size_t value = strtoul(allocRecordMaxString, &end, 10);
3485 if (*end != '\0') {
Ruben Brunk3e47a742013-09-09 17:56:07 -07003486 LOG(ERROR) << "Ignoring " << propertyName << " '" << allocRecordMaxString
3487 << "' --- invalid";
Elliott Hughesb1a58792013-07-11 18:10:58 -07003488 return kDefaultNumAllocRecords;
3489 }
3490 if (!IsPowerOfTwo(value)) {
Ruben Brunk3e47a742013-09-09 17:56:07 -07003491 LOG(ERROR) << "Ignoring " << propertyName << " '" << allocRecordMaxString
3492 << "' --- not power of two";
Elliott Hughesb1a58792013-07-11 18:10:58 -07003493 return kDefaultNumAllocRecords;
3494 }
3495 return value;
3496 }
3497#endif
3498 return kDefaultNumAllocRecords;
3499}
3500
Elliott Hughes545a0642011-11-08 19:10:03 -08003501void Dbg::SetAllocTrackingEnabled(bool enabled) {
Ian Rogers50b35e22012-10-04 10:09:15 -07003502 MutexLock mu(Thread::Current(), gAllocTrackerLock);
Elliott Hughes545a0642011-11-08 19:10:03 -08003503 if (enabled) {
3504 if (recent_allocation_records_ == NULL) {
Elliott Hughesb1a58792013-07-11 18:10:58 -07003505 gAllocRecordMax = GetAllocTrackerMax();
3506 LOG(INFO) << "Enabling alloc tracker (" << gAllocRecordMax << " entries of "
3507 << kMaxAllocRecordStackDepth << " frames, taking "
3508 << PrettySize(sizeof(AllocRecord) * gAllocRecordMax) << ")";
Elliott Hughes545a0642011-11-08 19:10:03 -08003509 gAllocRecordHead = gAllocRecordCount = 0;
Elliott Hughesb1a58792013-07-11 18:10:58 -07003510 recent_allocation_records_ = new AllocRecord[gAllocRecordMax];
Elliott Hughes545a0642011-11-08 19:10:03 -08003511 CHECK(recent_allocation_records_ != NULL);
3512 }
Ian Rogersfa824272013-11-05 16:12:57 -08003513 Runtime::Current()->GetInstrumentation()->InstrumentQuickAllocEntryPoints();
Elliott Hughes545a0642011-11-08 19:10:03 -08003514 } else {
Ian Rogersfa824272013-11-05 16:12:57 -08003515 Runtime::Current()->GetInstrumentation()->UninstrumentQuickAllocEntryPoints();
Elliott Hughes545a0642011-11-08 19:10:03 -08003516 delete[] recent_allocation_records_;
3517 recent_allocation_records_ = NULL;
3518 }
3519}
3520
Ian Rogers0399dde2012-06-06 17:09:28 -07003521struct AllocRecordStackVisitor : public StackVisitor {
Ian Rogers7a22fa62013-01-23 12:16:16 -08003522 AllocRecordStackVisitor(Thread* thread, AllocRecord* record)
Ian Rogersb726dcb2012-09-05 08:57:23 -07003523 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_)
Ian Rogers7a22fa62013-01-23 12:16:16 -08003524 : StackVisitor(thread, NULL), record(record), depth(0) {}
Elliott Hughes545a0642011-11-08 19:10:03 -08003525
Ian Rogers00f7d0e2012-07-19 15:28:27 -07003526 // TODO: Enable annotalysis. We know lock is held in constructor, but abstraction confuses
3527 // annotalysis.
3528 bool VisitFrame() NO_THREAD_SAFETY_ANALYSIS {
Elliott Hughes545a0642011-11-08 19:10:03 -08003529 if (depth >= kMaxAllocRecordStackDepth) {
Elliott Hughes530fa002012-03-12 11:44:49 -07003530 return false;
Elliott Hughes545a0642011-11-08 19:10:03 -08003531 }
Brian Carlstromea46f952013-07-30 01:26:50 -07003532 mirror::ArtMethod* m = GetMethod();
Ian Rogers0399dde2012-06-06 17:09:28 -07003533 if (!m->IsRuntimeMethod()) {
3534 record->stack[depth].method = m;
3535 record->stack[depth].dex_pc = GetDexPc();
Elliott Hughes530fa002012-03-12 11:44:49 -07003536 ++depth;
Elliott Hughes545a0642011-11-08 19:10:03 -08003537 }
Elliott Hughes530fa002012-03-12 11:44:49 -07003538 return true;
Elliott Hughes545a0642011-11-08 19:10:03 -08003539 }
3540
3541 ~AllocRecordStackVisitor() {
3542 // Clear out any unused stack trace elements.
3543 for (; depth < kMaxAllocRecordStackDepth; ++depth) {
3544 record->stack[depth].method = NULL;
Ian Rogers0399dde2012-06-06 17:09:28 -07003545 record->stack[depth].dex_pc = 0;
Elliott Hughes545a0642011-11-08 19:10:03 -08003546 }
3547 }
3548
3549 AllocRecord* record;
3550 size_t depth;
3551};
3552
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003553void Dbg::RecordAllocation(mirror::Class* type, size_t byte_count) {
Elliott Hughes545a0642011-11-08 19:10:03 -08003554 Thread* self = Thread::Current();
3555 CHECK(self != NULL);
3556
Ian Rogers50b35e22012-10-04 10:09:15 -07003557 MutexLock mu(self, gAllocTrackerLock);
Elliott Hughes545a0642011-11-08 19:10:03 -08003558 if (recent_allocation_records_ == NULL) {
3559 return;
3560 }
3561
3562 // Advance and clip.
Elliott Hughesb1a58792013-07-11 18:10:58 -07003563 if (++gAllocRecordHead == gAllocRecordMax) {
Elliott Hughes545a0642011-11-08 19:10:03 -08003564 gAllocRecordHead = 0;
3565 }
3566
3567 // Fill in the basics.
3568 AllocRecord* record = &recent_allocation_records_[gAllocRecordHead];
3569 record->type = type;
3570 record->byte_count = byte_count;
Ian Rogersd9c4fc92013-10-01 19:45:43 -07003571 record->thin_lock_id = self->GetThreadId();
Elliott Hughes545a0642011-11-08 19:10:03 -08003572
3573 // Fill in the stack trace.
Ian Rogers7a22fa62013-01-23 12:16:16 -08003574 AllocRecordStackVisitor visitor(self, record);
Ian Rogers0399dde2012-06-06 17:09:28 -07003575 visitor.WalkStack();
Elliott Hughes545a0642011-11-08 19:10:03 -08003576
Elliott Hughesb1a58792013-07-11 18:10:58 -07003577 if (gAllocRecordCount < gAllocRecordMax) {
Elliott Hughes545a0642011-11-08 19:10:03 -08003578 ++gAllocRecordCount;
3579 }
3580}
3581
Elliott Hughesa8f93cb2012-06-08 17:08:48 -07003582// Returns the index of the head element.
3583//
3584// We point at the most-recently-written record, so if gAllocRecordCount is 1
3585// we want to use the current element. Take "head+1" and subtract count
3586// from it.
3587//
3588// We need to handle underflow in our circular buffer, so we add
Elliott Hughesb1a58792013-07-11 18:10:58 -07003589// gAllocRecordMax and then mask it back down.
Elliott Hughesf8349362012-06-18 15:00:06 -07003590static inline int HeadIndex() EXCLUSIVE_LOCKS_REQUIRED(gAllocTrackerLock) {
Elliott Hughesb1a58792013-07-11 18:10:58 -07003591 return (gAllocRecordHead+1 + gAllocRecordMax - gAllocRecordCount) & (gAllocRecordMax-1);
Elliott Hughes545a0642011-11-08 19:10:03 -08003592}
3593
3594void Dbg::DumpRecentAllocations() {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07003595 ScopedObjectAccess soa(Thread::Current());
Ian Rogers50b35e22012-10-04 10:09:15 -07003596 MutexLock mu(soa.Self(), gAllocTrackerLock);
Elliott Hughes545a0642011-11-08 19:10:03 -08003597 if (recent_allocation_records_ == NULL) {
3598 LOG(INFO) << "Not recording tracked allocations";
3599 return;
3600 }
3601
3602 // "i" is the head of the list. We want to start at the end of the
3603 // list and move forward to the tail.
Elliott Hughesa8f93cb2012-06-08 17:08:48 -07003604 size_t i = HeadIndex();
Elliott Hughes545a0642011-11-08 19:10:03 -08003605 size_t count = gAllocRecordCount;
3606
3607 LOG(INFO) << "Tracked allocations, (head=" << gAllocRecordHead << " count=" << count << ")";
3608 while (count--) {
3609 AllocRecord* record = &recent_allocation_records_[i];
3610
Elliott Hughesa8f93cb2012-06-08 17:08:48 -07003611 LOG(INFO) << StringPrintf(" Thread %-2d %6zd bytes ", record->thin_lock_id, record->byte_count)
Elliott Hughes545a0642011-11-08 19:10:03 -08003612 << PrettyClass(record->type);
3613
3614 for (size_t stack_frame = 0; stack_frame < kMaxAllocRecordStackDepth; ++stack_frame) {
Brian Carlstromea46f952013-07-30 01:26:50 -07003615 const mirror::ArtMethod* m = record->stack[stack_frame].method;
Elliott Hughes545a0642011-11-08 19:10:03 -08003616 if (m == NULL) {
3617 break;
3618 }
3619 LOG(INFO) << " " << PrettyMethod(m) << " line " << record->stack[stack_frame].LineNumber();
3620 }
3621
3622 // pause periodically to help logcat catch up
3623 if ((count % 5) == 0) {
3624 usleep(40000);
3625 }
3626
Elliott Hughesb1a58792013-07-11 18:10:58 -07003627 i = (i + 1) & (gAllocRecordMax-1);
Elliott Hughes545a0642011-11-08 19:10:03 -08003628 }
3629}
3630
3631class StringTable {
3632 public:
3633 StringTable() {
3634 }
3635
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08003636 void Add(const char* s) {
Elliott Hughes545a0642011-11-08 19:10:03 -08003637 table_.insert(s);
3638 }
3639
Elliott Hughesa8f93cb2012-06-08 17:08:48 -07003640 size_t IndexOf(const char* s) const {
Mathieu Chartier02e25112013-08-14 16:14:24 -07003641 auto it = table_.find(s);
Elliott Hughesa8f93cb2012-06-08 17:08:48 -07003642 if (it == table_.end()) {
3643 LOG(FATAL) << "IndexOf(\"" << s << "\") failed";
3644 }
3645 return std::distance(table_.begin(), it);
Elliott Hughes545a0642011-11-08 19:10:03 -08003646 }
3647
Elliott Hughesa8f93cb2012-06-08 17:08:48 -07003648 size_t Size() const {
Elliott Hughes545a0642011-11-08 19:10:03 -08003649 return table_.size();
3650 }
3651
Elliott Hughesa8f93cb2012-06-08 17:08:48 -07003652 void WriteTo(std::vector<uint8_t>& bytes) const {
Mathieu Chartier02e25112013-08-14 16:14:24 -07003653 for (const std::string& str : table_) {
3654 const char* s = str.c_str();
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08003655 size_t s_len = CountModifiedUtf8Chars(s);
3656 UniquePtr<uint16_t> s_utf16(new uint16_t[s_len]);
3657 ConvertModifiedUtf8ToUtf16(s_utf16.get(), s);
3658 JDWP::AppendUtf16BE(bytes, s_utf16.get(), s_len);
Elliott Hughes545a0642011-11-08 19:10:03 -08003659 }
3660 }
3661
3662 private:
Elliott Hughesa8f93cb2012-06-08 17:08:48 -07003663 std::set<std::string> table_;
Elliott Hughes545a0642011-11-08 19:10:03 -08003664 DISALLOW_COPY_AND_ASSIGN(StringTable);
3665};
3666
3667/*
3668 * The data we send to DDMS contains everything we have recorded.
3669 *
3670 * Message header (all values big-endian):
3671 * (1b) message header len (to allow future expansion); includes itself
3672 * (1b) entry header len
3673 * (1b) stack frame len
3674 * (2b) number of entries
3675 * (4b) offset to string table from start of message
3676 * (2b) number of class name strings
3677 * (2b) number of method name strings
3678 * (2b) number of source file name strings
3679 * For each entry:
3680 * (4b) total allocation size
Elliott Hughes221229c2013-01-08 18:17:50 -08003681 * (2b) thread id
Elliott Hughes545a0642011-11-08 19:10:03 -08003682 * (2b) allocated object's class name index
3683 * (1b) stack depth
3684 * For each stack frame:
3685 * (2b) method's class name
3686 * (2b) method name
3687 * (2b) method source file
3688 * (2b) line number, clipped to 32767; -2 if native; -1 if no source
3689 * (xb) class name strings
3690 * (xb) method name strings
3691 * (xb) source file strings
3692 *
3693 * As with other DDM traffic, strings are sent as a 4-byte length
3694 * followed by UTF-16 data.
3695 *
3696 * We send up 16-bit unsigned indexes into string tables. In theory there
Elliott Hughesb1a58792013-07-11 18:10:58 -07003697 * can be (kMaxAllocRecordStackDepth * gAllocRecordMax) unique strings in
Elliott Hughes545a0642011-11-08 19:10:03 -08003698 * each table, but in practice there should be far fewer.
3699 *
3700 * The chief reason for using a string table here is to keep the size of
3701 * the DDMS message to a minimum. This is partly to make the protocol
3702 * efficient, but also because we have to form the whole thing up all at
3703 * once in a memory buffer.
3704 *
3705 * We use separate string tables for class names, method names, and source
3706 * files to keep the indexes small. There will generally be no overlap
3707 * between the contents of these tables.
3708 */
3709jbyteArray Dbg::GetRecentAllocations() {
3710 if (false) {
3711 DumpRecentAllocations();
3712 }
3713
Ian Rogers50b35e22012-10-04 10:09:15 -07003714 Thread* self = Thread::Current();
Elliott Hughes545a0642011-11-08 19:10:03 -08003715 std::vector<uint8_t> bytes;
Mathieu Chartier46e811b2013-07-10 17:09:14 -07003716 {
3717 MutexLock mu(self, gAllocTrackerLock);
3718 //
3719 // Part 1: generate string tables.
3720 //
3721 StringTable class_names;
3722 StringTable method_names;
3723 StringTable filenames;
Elliott Hughes545a0642011-11-08 19:10:03 -08003724
Mathieu Chartier46e811b2013-07-10 17:09:14 -07003725 int count = gAllocRecordCount;
3726 int idx = HeadIndex();
3727 while (count--) {
3728 AllocRecord* record = &recent_allocation_records_[idx];
Elliott Hughes545a0642011-11-08 19:10:03 -08003729
Mathieu Chartier46e811b2013-07-10 17:09:14 -07003730 class_names.Add(ClassHelper(record->type).GetDescriptor());
Elliott Hughes545a0642011-11-08 19:10:03 -08003731
Mathieu Chartier46e811b2013-07-10 17:09:14 -07003732 MethodHelper mh;
3733 for (size_t i = 0; i < kMaxAllocRecordStackDepth; i++) {
Brian Carlstromea46f952013-07-30 01:26:50 -07003734 mirror::ArtMethod* m = record->stack[i].method;
Mathieu Chartier46e811b2013-07-10 17:09:14 -07003735 if (m != NULL) {
3736 mh.ChangeMethod(m);
3737 class_names.Add(mh.GetDeclaringClassDescriptor());
3738 method_names.Add(mh.GetName());
3739 filenames.Add(mh.GetDeclaringClassSourceFile());
3740 }
3741 }
Elliott Hughes545a0642011-11-08 19:10:03 -08003742
Elliott Hughesb1a58792013-07-11 18:10:58 -07003743 idx = (idx + 1) & (gAllocRecordMax-1);
Elliott Hughes545a0642011-11-08 19:10:03 -08003744 }
3745
Mathieu Chartier46e811b2013-07-10 17:09:14 -07003746 LOG(INFO) << "allocation records: " << gAllocRecordCount;
3747
3748 //
3749 // Part 2: Generate the output and store it in the buffer.
3750 //
3751
3752 // (1b) message header len (to allow future expansion); includes itself
3753 // (1b) entry header len
3754 // (1b) stack frame len
3755 const int kMessageHeaderLen = 15;
3756 const int kEntryHeaderLen = 9;
3757 const int kStackFrameLen = 8;
3758 JDWP::Append1BE(bytes, kMessageHeaderLen);
3759 JDWP::Append1BE(bytes, kEntryHeaderLen);
3760 JDWP::Append1BE(bytes, kStackFrameLen);
3761
3762 // (2b) number of entries
3763 // (4b) offset to string table from start of message
3764 // (2b) number of class name strings
3765 // (2b) number of method name strings
3766 // (2b) number of source file name strings
3767 JDWP::Append2BE(bytes, gAllocRecordCount);
3768 size_t string_table_offset = bytes.size();
Brian Carlstrom7934ac22013-07-26 10:54:15 -07003769 JDWP::Append4BE(bytes, 0); // We'll patch this later...
Mathieu Chartier46e811b2013-07-10 17:09:14 -07003770 JDWP::Append2BE(bytes, class_names.Size());
3771 JDWP::Append2BE(bytes, method_names.Size());
3772 JDWP::Append2BE(bytes, filenames.Size());
3773
3774 count = gAllocRecordCount;
3775 idx = HeadIndex();
Mathieu Chartier46e811b2013-07-10 17:09:14 -07003776 while (count--) {
3777 // For each entry:
3778 // (4b) total allocation size
3779 // (2b) thread id
3780 // (2b) allocated object's class name index
3781 // (1b) stack depth
3782 AllocRecord* record = &recent_allocation_records_[idx];
3783 size_t stack_depth = record->GetDepth();
Mathieu Chartier590fee92013-09-13 13:46:47 -07003784 ClassHelper kh(record->type);
Mathieu Chartier46e811b2013-07-10 17:09:14 -07003785 size_t allocated_object_class_name_index = class_names.IndexOf(kh.GetDescriptor());
3786 JDWP::Append4BE(bytes, record->byte_count);
3787 JDWP::Append2BE(bytes, record->thin_lock_id);
3788 JDWP::Append2BE(bytes, allocated_object_class_name_index);
3789 JDWP::Append1BE(bytes, stack_depth);
3790
3791 MethodHelper mh;
3792 for (size_t stack_frame = 0; stack_frame < stack_depth; ++stack_frame) {
3793 // For each stack frame:
3794 // (2b) method's class name
3795 // (2b) method name
3796 // (2b) method source file
3797 // (2b) line number, clipped to 32767; -2 if native; -1 if no source
3798 mh.ChangeMethod(record->stack[stack_frame].method);
3799 size_t class_name_index = class_names.IndexOf(mh.GetDeclaringClassDescriptor());
3800 size_t method_name_index = method_names.IndexOf(mh.GetName());
3801 size_t file_name_index = filenames.IndexOf(mh.GetDeclaringClassSourceFile());
3802 JDWP::Append2BE(bytes, class_name_index);
3803 JDWP::Append2BE(bytes, method_name_index);
3804 JDWP::Append2BE(bytes, file_name_index);
3805 JDWP::Append2BE(bytes, record->stack[stack_frame].LineNumber());
3806 }
3807
Elliott Hughesb1a58792013-07-11 18:10:58 -07003808 idx = (idx + 1) & (gAllocRecordMax-1);
Mathieu Chartier46e811b2013-07-10 17:09:14 -07003809 }
3810
3811 // (xb) class name strings
3812 // (xb) method name strings
3813 // (xb) source file strings
3814 JDWP::Set4BE(&bytes[string_table_offset], bytes.size());
3815 class_names.WriteTo(bytes);
3816 method_names.WriteTo(bytes);
3817 filenames.WriteTo(bytes);
Elliott Hughes545a0642011-11-08 19:10:03 -08003818 }
Ian Rogers50b35e22012-10-04 10:09:15 -07003819 JNIEnv* env = self->GetJniEnv();
Elliott Hughes545a0642011-11-08 19:10:03 -08003820 jbyteArray result = env->NewByteArray(bytes.size());
3821 if (result != NULL) {
3822 env->SetByteArrayRegion(result, 0, bytes.size(), reinterpret_cast<const jbyte*>(&bytes[0]));
3823 }
3824 return result;
3825}
3826
Elliott Hughes872d4ec2011-10-21 17:07:15 -07003827} // namespace art