blob: d63cb1c83525fe6e54cad2f27802463702b35547 [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 }
110 Dbg::PostLocationEvent(method, 0, this_object, Dbg::kMethodEntry);
111 }
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_) {
117 UNUSED(return_value);
118 if (method->IsNative()) {
119 // TODO: post location events is a suspension point and native method entry stubs aren't.
120 return;
121 }
122 Dbg::PostLocationEvent(method, dex_pc, this_object, Dbg::kMethodExit);
123 }
124
Brian Carlstromea46f952013-07-30 01:26:50 -0700125 virtual void MethodUnwind(Thread* thread, const mirror::ArtMethod* method,
Ian Rogers62d6c772013-02-27 08:32:07 -0800126 uint32_t dex_pc) SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
127 // We're not recorded to listen to this kind of event, so complain.
128 LOG(ERROR) << "Unexpected method unwind event in debugger " << PrettyMethod(method)
129 << " " << dex_pc;
130 }
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;
Elliott Hughes475fc232011-10-25 15:00:35 -0700455 delete gRegistry;
456 gRegistry = NULL;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700457}
458
Elliott Hughes767a1472011-10-26 18:49:02 -0700459void Dbg::GcDidFinish() {
460 if (gDdmHpifWhen != HPIF_WHEN_NEVER) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700461 ScopedObjectAccess soa(Thread::Current());
Elliott Hughes81ff3182012-03-23 20:35:56 -0700462 LOG(DEBUG) << "Sending heap info to DDM";
Elliott Hughes7162ad92011-10-27 14:08:42 -0700463 DdmSendHeapInfo(gDdmHpifWhen);
Elliott Hughes767a1472011-10-26 18:49:02 -0700464 }
465 if (gDdmHpsgWhen != HPSG_WHEN_NEVER) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700466 ScopedObjectAccess soa(Thread::Current());
Elliott Hughes81ff3182012-03-23 20:35:56 -0700467 LOG(DEBUG) << "Dumping heap to DDM";
Elliott Hughes6a5bd492011-10-28 14:33:57 -0700468 DdmSendHeapSegments(false);
Elliott Hughes767a1472011-10-26 18:49:02 -0700469 }
470 if (gDdmNhsgWhen != HPSG_WHEN_NEVER) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700471 ScopedObjectAccess soa(Thread::Current());
Elliott Hughes767a1472011-10-26 18:49:02 -0700472 LOG(DEBUG) << "Dumping native heap to DDM";
Elliott Hughes6a5bd492011-10-28 14:33:57 -0700473 DdmSendHeapSegments(true);
Elliott Hughes767a1472011-10-26 18:49:02 -0700474 }
475}
476
Elliott Hughes4ffd3132011-10-24 12:06:42 -0700477void Dbg::SetJdwpAllowed(bool allowed) {
478 gJdwpAllowed = allowed;
479}
480
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700481DebugInvokeReq* Dbg::GetInvokeReq() {
Elliott Hughes475fc232011-10-25 15:00:35 -0700482 return Thread::Current()->GetInvokeReq();
483}
484
485Thread* Dbg::GetDebugThread() {
486 return (gJdwpState != NULL) ? gJdwpState->GetDebugThread() : NULL;
487}
488
489void Dbg::ClearWaitForEventThread() {
490 gJdwpState->ClearWaitForEventThread();
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700491}
492
493void Dbg::Connected() {
Elliott Hughes3bb81562011-10-21 18:52:59 -0700494 CHECK(!gDebuggerConnected);
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -0800495 VLOG(jdwp) << "JDWP has attached";
Elliott Hughes3bb81562011-10-21 18:52:59 -0700496 gDebuggerConnected = true;
Elliott Hughes86964332012-02-15 19:37:42 -0800497 gDisposed = false;
498}
499
500void Dbg::Disposed() {
501 gDisposed = true;
502}
503
504bool Dbg::IsDisposed() {
505 return gDisposed;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700506}
507
Elliott Hughesa2155262011-11-16 16:26:58 -0800508void Dbg::GoActive() {
509 // Enable all debugging features, including scans for breakpoints.
510 // This is a no-op if we're already active.
511 // Only called from the JDWP handler thread.
512 if (gDebuggerActive) {
513 return;
514 }
515
Elliott Hughesc0f09332012-03-26 13:27:06 -0700516 {
517 // TODO: dalvik only warned if there were breakpoints left over. clear in Dbg::Disconnected?
jeffhao09bfc6a2012-12-11 18:11:43 -0800518 MutexLock mu(Thread::Current(), *Locks::breakpoint_lock_);
Elliott Hughesc0f09332012-03-26 13:27:06 -0700519 CHECK_EQ(gBreakpoints.size(), 0U);
520 }
Elliott Hughesa2155262011-11-16 16:26:58 -0800521
Ian Rogers62d6c772013-02-27 08:32:07 -0800522 Runtime* runtime = Runtime::Current();
523 runtime->GetThreadList()->SuspendAll();
524 Thread* self = Thread::Current();
525 ThreadState old_state = self->SetStateUnsafe(kRunnable);
526 CHECK_NE(old_state, kRunnable);
527 runtime->GetInstrumentation()->AddListener(&gDebugInstrumentationListener,
528 instrumentation::Instrumentation::kMethodEntered |
529 instrumentation::Instrumentation::kMethodExited |
Jeff Hao14dd5a82013-04-11 10:23:36 -0700530 instrumentation::Instrumentation::kDexPcMoved |
531 instrumentation::Instrumentation::kExceptionCaught);
Elliott Hughesa2155262011-11-16 16:26:58 -0800532 gDebuggerActive = true;
Ian Rogers62d6c772013-02-27 08:32:07 -0800533 CHECK_EQ(self->SetStateUnsafe(old_state), kRunnable);
534 runtime->GetThreadList()->ResumeAll();
535
536 LOG(INFO) << "Debugger is active";
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700537}
538
539void Dbg::Disconnected() {
Elliott Hughes234ab152011-10-26 14:02:26 -0700540 CHECK(gDebuggerConnected);
541
Elliott Hughesc0f09332012-03-26 13:27:06 -0700542 LOG(INFO) << "Debugger is no longer active";
Elliott Hughes234ab152011-10-26 14:02:26 -0700543
Ian Rogers62d6c772013-02-27 08:32:07 -0800544 // Suspend all threads and exclusively acquire the mutator lock. Set the state of the thread
545 // to kRunnable to avoid scoped object access transitions. Remove the debugger as a listener
546 // and clear the object registry.
547 Runtime* runtime = Runtime::Current();
548 runtime->GetThreadList()->SuspendAll();
549 Thread* self = Thread::Current();
550 ThreadState old_state = self->SetStateUnsafe(kRunnable);
551 runtime->GetInstrumentation()->RemoveListener(&gDebugInstrumentationListener,
552 instrumentation::Instrumentation::kMethodEntered |
553 instrumentation::Instrumentation::kMethodExited |
Jeff Hao14dd5a82013-04-11 10:23:36 -0700554 instrumentation::Instrumentation::kDexPcMoved |
555 instrumentation::Instrumentation::kExceptionCaught);
Elliott Hughesc0f09332012-03-26 13:27:06 -0700556 gDebuggerActive = false;
Elliott Hughes234ab152011-10-26 14:02:26 -0700557 gRegistry->Clear();
558 gDebuggerConnected = false;
Ian Rogers62d6c772013-02-27 08:32:07 -0800559 CHECK_EQ(self->SetStateUnsafe(old_state), kRunnable);
560 runtime->GetThreadList()->ResumeAll();
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700561}
562
Elliott Hughesc0f09332012-03-26 13:27:06 -0700563bool Dbg::IsDebuggerActive() {
Elliott Hughes3bb81562011-10-21 18:52:59 -0700564 return gDebuggerActive;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700565}
566
Elliott Hughesc0f09332012-03-26 13:27:06 -0700567bool Dbg::IsJdwpConfigured() {
Elliott Hughes3bb81562011-10-21 18:52:59 -0700568 return gJdwpConfigured;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700569}
570
571int64_t Dbg::LastDebuggerActivity() {
Elliott Hughesca951522011-12-05 12:01:32 -0800572 return gJdwpState->LastDebuggerActivity();
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700573}
574
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700575void Dbg::UndoDebuggerSuspensions() {
Elliott Hughes234ab152011-10-26 14:02:26 -0700576 Runtime::Current()->GetThreadList()->UndoDebuggerSuspensions();
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700577}
578
Elliott Hughes88d63092013-01-09 09:55:54 -0800579std::string Dbg::GetClassName(JDWP::RefTypeId class_id) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800580 mirror::Object* o = gRegistry->Get<mirror::Object*>(class_id);
Elliott Hughes436e3722012-02-17 20:01:47 -0800581 if (o == NULL) {
582 return "NULL";
583 }
Elliott Hughes64f574f2013-02-20 14:57:12 -0800584 if (o == ObjectRegistry::kInvalidObject) {
Elliott Hughes88d63092013-01-09 09:55:54 -0800585 return StringPrintf("invalid object %p", reinterpret_cast<void*>(class_id));
Elliott Hughes436e3722012-02-17 20:01:47 -0800586 }
587 if (!o->IsClass()) {
Brian Carlstrom7934ac22013-07-26 10:54:15 -0700588 return StringPrintf("non-class %p", o); // This is only used for debugging output anyway.
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -0800589 }
Elliott Hughesc308a5d2012-02-16 17:12:06 -0800590 return DescriptorToName(ClassHelper(o->AsClass()).GetDescriptor());
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700591}
592
Elliott Hughes88d63092013-01-09 09:55:54 -0800593JDWP::JdwpError Dbg::GetClassObject(JDWP::RefTypeId id, JDWP::ObjectId& class_object_id) {
Elliott Hughes436e3722012-02-17 20:01:47 -0800594 JDWP::JdwpError status;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800595 mirror::Class* c = DecodeClass(id, status);
Elliott Hughes436e3722012-02-17 20:01:47 -0800596 if (c == NULL) {
597 return status;
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -0800598 }
Elliott Hughes88d63092013-01-09 09:55:54 -0800599 class_object_id = gRegistry->Add(c);
Elliott Hughes436e3722012-02-17 20:01:47 -0800600 return JDWP::ERR_NONE;
Elliott Hughes86964332012-02-15 19:37:42 -0800601}
602
Elliott Hughes88d63092013-01-09 09:55:54 -0800603JDWP::JdwpError Dbg::GetSuperclass(JDWP::RefTypeId id, JDWP::RefTypeId& superclass_id) {
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -0800604 JDWP::JdwpError status;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800605 mirror::Class* c = DecodeClass(id, status);
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -0800606 if (c == NULL) {
607 return status;
608 }
609 if (c->IsInterface()) {
610 // http://code.google.com/p/android/issues/detail?id=20856
Elliott Hughes88d63092013-01-09 09:55:54 -0800611 superclass_id = 0;
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -0800612 } else {
Elliott Hughes88d63092013-01-09 09:55:54 -0800613 superclass_id = gRegistry->Add(c->GetSuperClass());
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -0800614 }
615 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700616}
617
Elliott Hughes436e3722012-02-17 20:01:47 -0800618JDWP::JdwpError Dbg::GetClassLoader(JDWP::RefTypeId id, JDWP::ExpandBuf* pReply) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800619 mirror::Object* o = gRegistry->Get<mirror::Object*>(id);
Elliott Hughes64f574f2013-02-20 14:57:12 -0800620 if (o == NULL || o == ObjectRegistry::kInvalidObject) {
Elliott Hughes436e3722012-02-17 20:01:47 -0800621 return JDWP::ERR_INVALID_OBJECT;
622 }
623 expandBufAddObjectId(pReply, gRegistry->Add(o->GetClass()->GetClassLoader()));
624 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700625}
626
Elliott Hughes436e3722012-02-17 20:01:47 -0800627JDWP::JdwpError Dbg::GetModifiers(JDWP::RefTypeId id, JDWP::ExpandBuf* pReply) {
628 JDWP::JdwpError status;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800629 mirror::Class* c = DecodeClass(id, status);
Elliott Hughes436e3722012-02-17 20:01:47 -0800630 if (c == NULL) {
631 return status;
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -0800632 }
Elliott Hughes436e3722012-02-17 20:01:47 -0800633
634 uint32_t access_flags = c->GetAccessFlags() & kAccJavaFlagsMask;
635
636 // Set ACC_SUPER; dex files don't contain this flag, but all classes are supposed to have it set.
637 // Class.getModifiers doesn't return it, but JDWP does, so we set it here.
638 access_flags |= kAccSuper;
639
640 expandBufAdd4BE(pReply, access_flags);
641
642 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700643}
644
Elliott Hughesf327e072013-01-09 16:01:26 -0800645JDWP::JdwpError Dbg::GetMonitorInfo(JDWP::ObjectId object_id, JDWP::ExpandBuf* reply)
646 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800647 mirror::Object* o = gRegistry->Get<mirror::Object*>(object_id);
Elliott Hughes64f574f2013-02-20 14:57:12 -0800648 if (o == NULL || o == ObjectRegistry::kInvalidObject) {
Elliott Hughesf327e072013-01-09 16:01:26 -0800649 return JDWP::ERR_INVALID_OBJECT;
650 }
651
652 // Ensure all threads are suspended while we read objects' lock words.
653 Thread* self = Thread::Current();
654 Locks::mutator_lock_->SharedUnlock(self);
655 Locks::mutator_lock_->ExclusiveLock(self);
656
657 MonitorInfo monitor_info(o);
658
659 Locks::mutator_lock_->ExclusiveUnlock(self);
660 Locks::mutator_lock_->SharedLock(self);
661
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700662 if (monitor_info.owner_ != NULL) {
663 expandBufAddObjectId(reply, gRegistry->Add(monitor_info.owner_->GetPeer()));
Elliott Hughesf327e072013-01-09 16:01:26 -0800664 } else {
665 expandBufAddObjectId(reply, gRegistry->Add(NULL));
666 }
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700667 expandBufAdd4BE(reply, monitor_info.entry_count_);
668 expandBufAdd4BE(reply, monitor_info.waiters_.size());
669 for (size_t i = 0; i < monitor_info.waiters_.size(); ++i) {
670 expandBufAddObjectId(reply, gRegistry->Add(monitor_info.waiters_[i]->GetPeer()));
Elliott Hughesf327e072013-01-09 16:01:26 -0800671 }
672 return JDWP::ERR_NONE;
673}
674
Elliott Hughes734b8c62013-01-11 15:32:45 -0800675JDWP::JdwpError Dbg::GetOwnedMonitors(JDWP::ObjectId thread_id,
676 std::vector<JDWP::ObjectId>& monitors,
677 std::vector<uint32_t>& stack_depths)
Elliott Hughes4993bbc2013-01-10 15:41:25 -0800678 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
679 ScopedObjectAccessUnchecked soa(Thread::Current());
680 MutexLock mu(soa.Self(), *Locks::thread_list_lock_);
681 Thread* thread;
682 JDWP::JdwpError error = DecodeThread(soa, thread_id, thread);
683 if (error != JDWP::ERR_NONE) {
684 return error;
685 }
686 if (!IsSuspendedForDebugger(soa, thread)) {
687 return JDWP::ERR_THREAD_NOT_SUSPENDED;
688 }
689
690 struct OwnedMonitorVisitor : public StackVisitor {
Ian Rogers7a22fa62013-01-23 12:16:16 -0800691 OwnedMonitorVisitor(Thread* thread, Context* context)
Elliott Hughes4993bbc2013-01-10 15:41:25 -0800692 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_)
Ian Rogers7a22fa62013-01-23 12:16:16 -0800693 : StackVisitor(thread, context), current_stack_depth(0) {}
Elliott Hughes4993bbc2013-01-10 15:41:25 -0800694
695 // TODO: Enable annotalysis. We know lock is held in constructor, but abstraction confuses
696 // annotalysis.
697 bool VisitFrame() NO_THREAD_SAFETY_ANALYSIS {
698 if (!GetMethod()->IsRuntimeMethod()) {
699 Monitor::VisitLocks(this, AppendOwnedMonitors, this);
Elliott Hughes734b8c62013-01-11 15:32:45 -0800700 ++current_stack_depth;
Elliott Hughes4993bbc2013-01-10 15:41:25 -0800701 }
702 return true;
703 }
704
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800705 static void AppendOwnedMonitors(mirror::Object* owned_monitor, void* arg) {
Ian Rogers7a22fa62013-01-23 12:16:16 -0800706 OwnedMonitorVisitor* visitor = reinterpret_cast<OwnedMonitorVisitor*>(arg);
Elliott Hughes734b8c62013-01-11 15:32:45 -0800707 visitor->monitors.push_back(owned_monitor);
708 visitor->stack_depths.push_back(visitor->current_stack_depth);
Elliott Hughes4993bbc2013-01-10 15:41:25 -0800709 }
710
Elliott Hughes734b8c62013-01-11 15:32:45 -0800711 size_t current_stack_depth;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800712 std::vector<mirror::Object*> monitors;
Elliott Hughes734b8c62013-01-11 15:32:45 -0800713 std::vector<uint32_t> stack_depths;
Elliott Hughes4993bbc2013-01-10 15:41:25 -0800714 };
Ian Rogers7a22fa62013-01-23 12:16:16 -0800715 UniquePtr<Context> context(Context::Create());
716 OwnedMonitorVisitor visitor(thread, context.get());
Elliott Hughes4993bbc2013-01-10 15:41:25 -0800717 visitor.WalkStack();
718
719 for (size_t i = 0; i < visitor.monitors.size(); ++i) {
720 monitors.push_back(gRegistry->Add(visitor.monitors[i]));
Elliott Hughes734b8c62013-01-11 15:32:45 -0800721 stack_depths.push_back(visitor.stack_depths[i]);
Elliott Hughes4993bbc2013-01-10 15:41:25 -0800722 }
723
724 return JDWP::ERR_NONE;
725}
726
Elliott Hughesf9501702013-01-11 11:22:27 -0800727JDWP::JdwpError Dbg::GetContendedMonitor(JDWP::ObjectId thread_id, JDWP::ObjectId& contended_monitor)
728 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
729 ScopedObjectAccessUnchecked soa(Thread::Current());
730 MutexLock mu(soa.Self(), *Locks::thread_list_lock_);
731 Thread* thread;
732 JDWP::JdwpError error = DecodeThread(soa, thread_id, thread);
733 if (error != JDWP::ERR_NONE) {
734 return error;
735 }
736 if (!IsSuspendedForDebugger(soa, thread)) {
737 return JDWP::ERR_THREAD_NOT_SUSPENDED;
738 }
739
740 contended_monitor = gRegistry->Add(Monitor::GetContendedMonitor(thread));
741
742 return JDWP::ERR_NONE;
743}
744
Elliott Hughesec0f83d2013-01-15 16:54:08 -0800745JDWP::JdwpError Dbg::GetInstanceCounts(const std::vector<JDWP::RefTypeId>& class_ids,
746 std::vector<uint64_t>& counts)
747 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800748 std::vector<mirror::Class*> classes;
Elliott Hughesec0f83d2013-01-15 16:54:08 -0800749 counts.clear();
750 for (size_t i = 0; i < class_ids.size(); ++i) {
751 JDWP::JdwpError status;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800752 mirror::Class* c = DecodeClass(class_ids[i], status);
Elliott Hughesec0f83d2013-01-15 16:54:08 -0800753 if (c == NULL) {
754 return status;
755 }
756 classes.push_back(c);
757 counts.push_back(0);
758 }
759
760 Runtime::Current()->GetHeap()->CountInstances(classes, false, &counts[0]);
761 return JDWP::ERR_NONE;
762}
763
Elliott Hughes3b78c942013-01-15 17:35:41 -0800764JDWP::JdwpError Dbg::GetInstances(JDWP::RefTypeId class_id, int32_t max_count, std::vector<JDWP::ObjectId>& instances)
765 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
766 JDWP::JdwpError status;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800767 mirror::Class* c = DecodeClass(class_id, status);
Elliott Hughes3b78c942013-01-15 17:35:41 -0800768 if (c == NULL) {
769 return status;
770 }
771
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800772 std::vector<mirror::Object*> raw_instances;
Elliott Hughes3b78c942013-01-15 17:35:41 -0800773 Runtime::Current()->GetHeap()->GetInstances(c, max_count, raw_instances);
774 for (size_t i = 0; i < raw_instances.size(); ++i) {
775 instances.push_back(gRegistry->Add(raw_instances[i]));
776 }
777 return JDWP::ERR_NONE;
778}
779
Elliott Hughes0cbaff52013-01-16 15:28:01 -0800780JDWP::JdwpError Dbg::GetReferringObjects(JDWP::ObjectId object_id, int32_t max_count,
781 std::vector<JDWP::ObjectId>& referring_objects)
782 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800783 mirror::Object* o = gRegistry->Get<mirror::Object*>(object_id);
Elliott Hughes64f574f2013-02-20 14:57:12 -0800784 if (o == NULL || o == ObjectRegistry::kInvalidObject) {
Elliott Hughes0cbaff52013-01-16 15:28:01 -0800785 return JDWP::ERR_INVALID_OBJECT;
786 }
787
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800788 std::vector<mirror::Object*> raw_instances;
Elliott Hughes0cbaff52013-01-16 15:28:01 -0800789 Runtime::Current()->GetHeap()->GetReferringObjects(o, max_count, raw_instances);
790 for (size_t i = 0; i < raw_instances.size(); ++i) {
791 referring_objects.push_back(gRegistry->Add(raw_instances[i]));
792 }
793 return JDWP::ERR_NONE;
794}
795
Elliott Hughes64f574f2013-02-20 14:57:12 -0800796JDWP::JdwpError Dbg::DisableCollection(JDWP::ObjectId object_id)
797 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
798 gRegistry->DisableCollection(object_id);
799 return JDWP::ERR_NONE;
800}
801
802JDWP::JdwpError Dbg::EnableCollection(JDWP::ObjectId object_id)
803 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
804 gRegistry->EnableCollection(object_id);
805 return JDWP::ERR_NONE;
806}
807
808JDWP::JdwpError Dbg::IsCollected(JDWP::ObjectId object_id, bool& is_collected)
809 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
810 is_collected = gRegistry->IsCollected(object_id);
811 return JDWP::ERR_NONE;
812}
813
814void Dbg::DisposeObject(JDWP::ObjectId object_id, uint32_t reference_count)
815 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
816 gRegistry->DisposeObject(object_id, reference_count);
817}
818
Elliott Hughes88d63092013-01-09 09:55:54 -0800819JDWP::JdwpError Dbg::GetReflectedType(JDWP::RefTypeId class_id, JDWP::ExpandBuf* pReply) {
Elliott Hughes436e3722012-02-17 20:01:47 -0800820 JDWP::JdwpError status;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800821 mirror::Class* c = DecodeClass(class_id, status);
Elliott Hughes436e3722012-02-17 20:01:47 -0800822 if (c == NULL) {
823 return status;
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -0800824 }
Elliott Hughes436e3722012-02-17 20:01:47 -0800825
826 expandBufAdd1(pReply, c->IsInterface() ? JDWP::TT_INTERFACE : JDWP::TT_CLASS);
Elliott Hughes88d63092013-01-09 09:55:54 -0800827 expandBufAddRefTypeId(pReply, class_id);
Elliott Hughes436e3722012-02-17 20:01:47 -0800828 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700829}
830
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -0800831void Dbg::GetClassList(std::vector<JDWP::RefTypeId>& classes) {
Elliott Hughesa2155262011-11-16 16:26:58 -0800832 // Get the complete list of reference classes (i.e. all classes except
833 // the primitive types).
834 // Returns a newly-allocated buffer full of RefTypeId values.
835 struct ClassListCreator {
Elliott Hughesba8eee12012-01-24 20:25:24 -0800836 explicit ClassListCreator(std::vector<JDWP::RefTypeId>& classes) : classes(classes) {
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -0800837 }
838
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800839 static bool Visit(mirror::Class* c, void* arg) {
Elliott Hughesa2155262011-11-16 16:26:58 -0800840 return reinterpret_cast<ClassListCreator*>(arg)->Visit(c);
841 }
842
Elliott Hughes64f574f2013-02-20 14:57:12 -0800843 // TODO: Enable annotalysis. We know lock is held in constructor, but abstraction confuses
844 // annotalysis.
845 bool Visit(mirror::Class* c) NO_THREAD_SAFETY_ANALYSIS {
Elliott Hughesa2155262011-11-16 16:26:58 -0800846 if (!c->IsPrimitive()) {
Elliott Hughes64f574f2013-02-20 14:57:12 -0800847 classes.push_back(gRegistry->AddRefType(c));
Elliott Hughesa2155262011-11-16 16:26:58 -0800848 }
849 return true;
850 }
851
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -0800852 std::vector<JDWP::RefTypeId>& classes;
Elliott Hughesa2155262011-11-16 16:26:58 -0800853 };
854
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -0800855 ClassListCreator clc(classes);
Elliott Hughesa2155262011-11-16 16:26:58 -0800856 Runtime::Current()->GetClassLinker()->VisitClasses(ClassListCreator::Visit, &clc);
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700857}
858
Elliott Hughes88d63092013-01-09 09:55:54 -0800859JDWP::JdwpError Dbg::GetClassInfo(JDWP::RefTypeId class_id, JDWP::JdwpTypeTag* pTypeTag, uint32_t* pStatus, std::string* pDescriptor) {
Elliott Hughes436e3722012-02-17 20:01:47 -0800860 JDWP::JdwpError status;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800861 mirror::Class* c = DecodeClass(class_id, status);
Elliott Hughes436e3722012-02-17 20:01:47 -0800862 if (c == NULL) {
863 return status;
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -0800864 }
865
Elliott Hughesa2155262011-11-16 16:26:58 -0800866 if (c->IsArrayClass()) {
867 *pStatus = JDWP::CS_VERIFIED | JDWP::CS_PREPARED;
868 *pTypeTag = JDWP::TT_ARRAY;
869 } else {
870 if (c->IsErroneous()) {
871 *pStatus = JDWP::CS_ERROR;
872 } else {
873 *pStatus = JDWP::CS_VERIFIED | JDWP::CS_PREPARED | JDWP::CS_INITIALIZED;
874 }
875 *pTypeTag = c->IsInterface() ? JDWP::TT_INTERFACE : JDWP::TT_CLASS;
876 }
877
878 if (pDescriptor != NULL) {
Ian Rogersdfb325e2013-10-30 01:00:44 -0700879 *pDescriptor = ClassHelper(c).GetDescriptor();
Elliott Hughesa2155262011-11-16 16:26:58 -0800880 }
Elliott Hughes436e3722012-02-17 20:01:47 -0800881 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700882}
883
Elliott Hughesc3b77c72011-12-15 20:56:48 -0800884void Dbg::FindLoadedClassBySignature(const char* descriptor, std::vector<JDWP::RefTypeId>& ids) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800885 std::vector<mirror::Class*> classes;
Elliott Hughes6fa602d2011-12-02 17:54:25 -0800886 Runtime::Current()->GetClassLinker()->LookupClasses(descriptor, classes);
887 ids.clear();
888 for (size_t i = 0; i < classes.size(); ++i) {
889 ids.push_back(gRegistry->Add(classes[i]));
890 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700891}
892
Elliott Hughes64f574f2013-02-20 14:57:12 -0800893JDWP::JdwpError Dbg::GetReferenceType(JDWP::ObjectId object_id, JDWP::ExpandBuf* pReply)
894 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800895 mirror::Object* o = gRegistry->Get<mirror::Object*>(object_id);
Elliott Hughes64f574f2013-02-20 14:57:12 -0800896 if (o == NULL || o == ObjectRegistry::kInvalidObject) {
Elliott Hughes2435a572012-02-17 16:07:41 -0800897 return JDWP::ERR_INVALID_OBJECT;
Elliott Hughes499c5132011-11-17 14:55:11 -0800898 }
Elliott Hughes2435a572012-02-17 16:07:41 -0800899
900 JDWP::JdwpTypeTag type_tag;
901 if (o->GetClass()->IsArrayClass()) {
902 type_tag = JDWP::TT_ARRAY;
903 } else if (o->GetClass()->IsInterface()) {
904 type_tag = JDWP::TT_INTERFACE;
905 } else {
906 type_tag = JDWP::TT_CLASS;
907 }
Elliott Hughes64f574f2013-02-20 14:57:12 -0800908 JDWP::RefTypeId type_id = gRegistry->AddRefType(o->GetClass());
Elliott Hughes2435a572012-02-17 16:07:41 -0800909
910 expandBufAdd1(pReply, type_tag);
911 expandBufAddRefTypeId(pReply, type_id);
912
913 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700914}
915
Ian Rogersfc0e94b2013-09-23 23:51:32 -0700916JDWP::JdwpError Dbg::GetSignature(JDWP::RefTypeId class_id, std::string* signature) {
Elliott Hughes1fe7afb2012-02-13 17:23:03 -0800917 JDWP::JdwpError status;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800918 mirror::Class* c = DecodeClass(class_id, status);
Elliott Hughes1fe7afb2012-02-13 17:23:03 -0800919 if (c == NULL) {
920 return status;
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -0800921 }
Ian Rogersdfb325e2013-10-30 01:00:44 -0700922 *signature = ClassHelper(c).GetDescriptor();
Elliott Hughes1fe7afb2012-02-13 17:23:03 -0800923 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700924}
925
Elliott Hughes88d63092013-01-09 09:55:54 -0800926JDWP::JdwpError Dbg::GetSourceFile(JDWP::RefTypeId class_id, std::string& result) {
Elliott Hughes436e3722012-02-17 20:01:47 -0800927 JDWP::JdwpError status;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800928 mirror::Class* c = DecodeClass(class_id, status);
Elliott Hughes436e3722012-02-17 20:01:47 -0800929 if (c == NULL) {
930 return status;
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -0800931 }
Elliott Hughes436e3722012-02-17 20:01:47 -0800932 result = ClassHelper(c).GetSourceFile();
933 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700934}
935
Elliott Hughes88d63092013-01-09 09:55:54 -0800936JDWP::JdwpError Dbg::GetObjectTag(JDWP::ObjectId object_id, uint8_t& tag) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800937 mirror::Object* o = gRegistry->Get<mirror::Object*>(object_id);
Elliott Hughes64f574f2013-02-20 14:57:12 -0800938 if (o == ObjectRegistry::kInvalidObject) {
Elliott Hughes546b9862012-06-20 16:06:13 -0700939 return JDWP::ERR_INVALID_OBJECT;
940 }
941 tag = TagFromObject(o);
942 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700943}
944
Elliott Hughesaed4be92011-12-02 16:16:23 -0800945size_t Dbg::GetTagWidth(JDWP::JdwpTag tag) {
Elliott Hughesdbb40792011-11-18 17:05:22 -0800946 switch (tag) {
947 case JDWP::JT_VOID:
948 return 0;
949 case JDWP::JT_BYTE:
950 case JDWP::JT_BOOLEAN:
951 return 1;
952 case JDWP::JT_CHAR:
953 case JDWP::JT_SHORT:
954 return 2;
955 case JDWP::JT_FLOAT:
956 case JDWP::JT_INT:
957 return 4;
958 case JDWP::JT_ARRAY:
959 case JDWP::JT_OBJECT:
960 case JDWP::JT_STRING:
961 case JDWP::JT_THREAD:
962 case JDWP::JT_THREAD_GROUP:
963 case JDWP::JT_CLASS_LOADER:
964 case JDWP::JT_CLASS_OBJECT:
965 return sizeof(JDWP::ObjectId);
966 case JDWP::JT_DOUBLE:
967 case JDWP::JT_LONG:
968 return 8;
969 default:
Elliott Hughes3d30d9b2011-12-07 17:35:48 -0800970 LOG(FATAL) << "Unknown tag " << tag;
Elliott Hughesdbb40792011-11-18 17:05:22 -0800971 return -1;
972 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700973}
974
Elliott Hughes88d63092013-01-09 09:55:54 -0800975JDWP::JdwpError Dbg::GetArrayLength(JDWP::ObjectId array_id, int& length) {
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -0800976 JDWP::JdwpError status;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800977 mirror::Array* a = DecodeArray(array_id, status);
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -0800978 if (a == NULL) {
979 return status;
Elliott Hughes24437992011-11-30 14:49:33 -0800980 }
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -0800981 length = a->GetLength();
982 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700983}
984
Elliott Hughes88d63092013-01-09 09:55:54 -0800985JDWP::JdwpError Dbg::OutputArray(JDWP::ObjectId array_id, int offset, int count, JDWP::ExpandBuf* pReply) {
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -0800986 JDWP::JdwpError status;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800987 mirror::Array* a = DecodeArray(array_id, status);
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -0800988 if (a == NULL) {
989 return status;
990 }
Elliott Hughes24437992011-11-30 14:49:33 -0800991
992 if (offset < 0 || count < 0 || offset > a->GetLength() || a->GetLength() - offset < count) {
993 LOG(WARNING) << __FUNCTION__ << " access out of bounds: offset=" << offset << "; count=" << count;
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -0800994 return JDWP::ERR_INVALID_LENGTH;
Elliott Hughes24437992011-11-30 14:49:33 -0800995 }
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800996 std::string descriptor(ClassHelper(a->GetClass()).GetDescriptor());
Elliott Hughes24437992011-11-30 14:49:33 -0800997 JDWP::JdwpTag tag = BasicTagFromDescriptor(descriptor.c_str() + 1);
998
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -0800999 expandBufAdd1(pReply, tag);
1000 expandBufAdd4BE(pReply, count);
1001
Elliott Hughes24437992011-11-30 14:49:33 -08001002 if (IsPrimitiveTag(tag)) {
1003 size_t width = GetTagWidth(tag);
Elliott Hughes24437992011-11-30 14:49:33 -08001004 uint8_t* dst = expandBufAddSpace(pReply, count * width);
1005 if (width == 8) {
Ian Rogersa15e67d2012-02-28 13:51:55 -08001006 const uint64_t* src8 = reinterpret_cast<uint64_t*>(a->GetRawData(sizeof(uint64_t)));
Elliott Hughes24437992011-11-30 14:49:33 -08001007 for (int i = 0; i < count; ++i) JDWP::Write8BE(&dst, src8[offset + i]);
1008 } else if (width == 4) {
Ian Rogersa15e67d2012-02-28 13:51:55 -08001009 const uint32_t* src4 = reinterpret_cast<uint32_t*>(a->GetRawData(sizeof(uint32_t)));
Elliott Hughes24437992011-11-30 14:49:33 -08001010 for (int i = 0; i < count; ++i) JDWP::Write4BE(&dst, src4[offset + i]);
1011 } else if (width == 2) {
Ian Rogersa15e67d2012-02-28 13:51:55 -08001012 const uint16_t* src2 = reinterpret_cast<uint16_t*>(a->GetRawData(sizeof(uint16_t)));
Elliott Hughes24437992011-11-30 14:49:33 -08001013 for (int i = 0; i < count; ++i) JDWP::Write2BE(&dst, src2[offset + i]);
1014 } else {
Ian Rogersa15e67d2012-02-28 13:51:55 -08001015 const uint8_t* src = reinterpret_cast<uint8_t*>(a->GetRawData(sizeof(uint8_t)));
Elliott Hughes24437992011-11-30 14:49:33 -08001016 memcpy(dst, &src[offset * width], count * width);
1017 }
1018 } else {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001019 mirror::ObjectArray<mirror::Object>* oa = a->AsObjectArray<mirror::Object>();
Elliott Hughes24437992011-11-30 14:49:33 -08001020 for (int i = 0; i < count; ++i) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001021 mirror::Object* element = oa->Get(offset + i);
Elliott Hughes24437992011-11-30 14:49:33 -08001022 JDWP::JdwpTag specific_tag = (element != NULL) ? TagFromObject(element) : tag;
1023 expandBufAdd1(pReply, specific_tag);
1024 expandBufAddObjectId(pReply, gRegistry->Add(element));
1025 }
1026 }
1027
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -08001028 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001029}
1030
Elliott Hughes4b9702c2013-02-20 18:13:24 -08001031template <typename T> void CopyArrayData(mirror::Array* a, JDWP::Request& src, int offset, int count) {
1032 DCHECK(a->GetClass()->IsPrimitiveArray());
1033
1034 T* dst = &(reinterpret_cast<T*>(a->GetRawData(sizeof(T)))[offset * sizeof(T)]);
1035 for (int i = 0; i < count; ++i) {
1036 *dst++ = src.ReadValue(sizeof(T));
1037 }
1038}
1039
Elliott Hughes88d63092013-01-09 09:55:54 -08001040JDWP::JdwpError Dbg::SetArrayElements(JDWP::ObjectId array_id, int offset, int count,
Elliott Hughes4b9702c2013-02-20 18:13:24 -08001041 JDWP::Request& request)
Ian Rogersb726dcb2012-09-05 08:57:23 -07001042 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -08001043 JDWP::JdwpError status;
Elliott Hughes4b9702c2013-02-20 18:13:24 -08001044 mirror::Array* dst = DecodeArray(array_id, status);
1045 if (dst == NULL) {
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -08001046 return status;
1047 }
Elliott Hughesf03b8f62011-12-02 14:26:25 -08001048
Elliott Hughes4b9702c2013-02-20 18:13:24 -08001049 if (offset < 0 || count < 0 || offset > dst->GetLength() || dst->GetLength() - offset < count) {
Elliott Hughesf03b8f62011-12-02 14:26:25 -08001050 LOG(WARNING) << __FUNCTION__ << " access out of bounds: offset=" << offset << "; count=" << count;
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -08001051 return JDWP::ERR_INVALID_LENGTH;
Elliott Hughesf03b8f62011-12-02 14:26:25 -08001052 }
Ian Rogersfc0e94b2013-09-23 23:51:32 -07001053 const char* descriptor = ClassHelper(dst->GetClass()).GetDescriptor();
1054 JDWP::JdwpTag tag = BasicTagFromDescriptor(descriptor + 1);
Elliott Hughesf03b8f62011-12-02 14:26:25 -08001055
1056 if (IsPrimitiveTag(tag)) {
1057 size_t width = GetTagWidth(tag);
Elliott Hughesf03b8f62011-12-02 14:26:25 -08001058 if (width == 8) {
Elliott Hughes4b9702c2013-02-20 18:13:24 -08001059 CopyArrayData<uint64_t>(dst, request, offset, count);
Elliott Hughesf03b8f62011-12-02 14:26:25 -08001060 } else if (width == 4) {
Elliott Hughes4b9702c2013-02-20 18:13:24 -08001061 CopyArrayData<uint32_t>(dst, request, offset, count);
Elliott Hughesf03b8f62011-12-02 14:26:25 -08001062 } else if (width == 2) {
Elliott Hughes4b9702c2013-02-20 18:13:24 -08001063 CopyArrayData<uint16_t>(dst, request, offset, count);
Elliott Hughesf03b8f62011-12-02 14:26:25 -08001064 } else {
Elliott Hughes4b9702c2013-02-20 18:13:24 -08001065 CopyArrayData<uint8_t>(dst, request, offset, count);
Elliott Hughesf03b8f62011-12-02 14:26:25 -08001066 }
1067 } else {
Elliott Hughes4b9702c2013-02-20 18:13:24 -08001068 mirror::ObjectArray<mirror::Object>* oa = dst->AsObjectArray<mirror::Object>();
Elliott Hughesf03b8f62011-12-02 14:26:25 -08001069 for (int i = 0; i < count; ++i) {
Elliott Hughes4b9702c2013-02-20 18:13:24 -08001070 JDWP::ObjectId id = request.ReadObjectId();
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001071 mirror::Object* o = gRegistry->Get<mirror::Object*>(id);
Elliott Hughes64f574f2013-02-20 14:57:12 -08001072 if (o == ObjectRegistry::kInvalidObject) {
Elliott Hughes436e3722012-02-17 20:01:47 -08001073 return JDWP::ERR_INVALID_OBJECT;
1074 }
1075 oa->Set(offset + i, o);
Elliott Hughesf03b8f62011-12-02 14:26:25 -08001076 }
1077 }
1078
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -08001079 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001080}
1081
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -08001082JDWP::ObjectId Dbg::CreateString(const std::string& str) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001083 return gRegistry->Add(mirror::String::AllocFromModifiedUtf8(Thread::Current(), str.c_str()));
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001084}
1085
Elliott Hughes88d63092013-01-09 09:55:54 -08001086JDWP::JdwpError Dbg::CreateObject(JDWP::RefTypeId class_id, JDWP::ObjectId& new_object) {
Elliott Hughes436e3722012-02-17 20:01:47 -08001087 JDWP::JdwpError status;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001088 mirror::Class* c = DecodeClass(class_id, status);
Elliott Hughes436e3722012-02-17 20:01:47 -08001089 if (c == NULL) {
1090 return status;
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -08001091 }
Ian Rogers50b35e22012-10-04 10:09:15 -07001092 new_object = gRegistry->Add(c->AllocObject(Thread::Current()));
Elliott Hughes436e3722012-02-17 20:01:47 -08001093 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001094}
1095
Elliott Hughesbf13d362011-12-08 15:51:37 -08001096/*
1097 * Used by Eclipse's "Display" view to evaluate "new byte[5]" to get "(byte[]) [0, 0, 0, 0, 0]".
1098 */
Elliott Hughes88d63092013-01-09 09:55:54 -08001099JDWP::JdwpError Dbg::CreateArrayObject(JDWP::RefTypeId array_class_id, uint32_t length,
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001100 JDWP::ObjectId& new_array) {
Elliott Hughes436e3722012-02-17 20:01:47 -08001101 JDWP::JdwpError status;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001102 mirror::Class* c = DecodeClass(array_class_id, status);
Elliott Hughes436e3722012-02-17 20:01:47 -08001103 if (c == NULL) {
1104 return status;
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -08001105 }
Mathieu Chartier590fee92013-09-13 13:46:47 -07001106 new_array = gRegistry->Add(
1107 mirror::Array::Alloc<kMovingCollector, true>(Thread::Current(), c, length));
Elliott Hughes436e3722012-02-17 20:01:47 -08001108 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001109}
1110
Elliott Hughes88d63092013-01-09 09:55:54 -08001111bool Dbg::MatchType(JDWP::RefTypeId instance_class_id, JDWP::RefTypeId class_id) {
Elliott Hughes436e3722012-02-17 20:01:47 -08001112 JDWP::JdwpError status;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001113 mirror::Class* c1 = DecodeClass(instance_class_id, status);
Elliott Hughesa656a0f2012-02-21 18:03:44 -08001114 CHECK(c1 != NULL);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001115 mirror::Class* c2 = DecodeClass(class_id, status);
Elliott Hughesa656a0f2012-02-21 18:03:44 -08001116 CHECK(c2 != NULL);
1117 return c1->IsAssignableFrom(c2);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001118}
1119
Brian Carlstromea46f952013-07-30 01:26:50 -07001120static JDWP::FieldId ToFieldId(const mirror::ArtField* f)
Ian Rogersb726dcb2012-09-05 08:57:23 -07001121 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Mathieu Chartier590fee92013-09-13 13:46:47 -07001122 CHECK(!kMovingFields);
Elliott Hughes03181a82011-11-17 17:22:21 -08001123 return static_cast<JDWP::FieldId>(reinterpret_cast<uintptr_t>(f));
Elliott Hughes03181a82011-11-17 17:22:21 -08001124}
1125
Brian Carlstromea46f952013-07-30 01:26:50 -07001126static JDWP::MethodId ToMethodId(const mirror::ArtMethod* m)
Ian Rogersb726dcb2012-09-05 08:57:23 -07001127 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Mathieu Chartier590fee92013-09-13 13:46:47 -07001128 CHECK(!kMovingMethods);
Elliott Hughes03181a82011-11-17 17:22:21 -08001129 return static_cast<JDWP::MethodId>(reinterpret_cast<uintptr_t>(m));
Elliott Hughes03181a82011-11-17 17:22:21 -08001130}
1131
Brian Carlstromea46f952013-07-30 01:26:50 -07001132static mirror::ArtField* FromFieldId(JDWP::FieldId fid)
Ian Rogersb726dcb2012-09-05 08:57:23 -07001133 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Mathieu Chartier590fee92013-09-13 13:46:47 -07001134 CHECK(!kMovingFields);
Brian Carlstromea46f952013-07-30 01:26:50 -07001135 return reinterpret_cast<mirror::ArtField*>(static_cast<uintptr_t>(fid));
Elliott Hughesaed4be92011-12-02 16:16:23 -08001136}
1137
Brian Carlstromea46f952013-07-30 01:26:50 -07001138static mirror::ArtMethod* FromMethodId(JDWP::MethodId mid)
Ian Rogersb726dcb2012-09-05 08:57:23 -07001139 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Mathieu Chartier590fee92013-09-13 13:46:47 -07001140 CHECK(!kMovingMethods);
Brian Carlstromea46f952013-07-30 01:26:50 -07001141 return reinterpret_cast<mirror::ArtMethod*>(static_cast<uintptr_t>(mid));
Elliott Hughes03181a82011-11-17 17:22:21 -08001142}
1143
Brian Carlstromea46f952013-07-30 01:26:50 -07001144static void SetLocation(JDWP::JdwpLocation& location, mirror::ArtMethod* m, uint32_t dex_pc)
Ian Rogersb726dcb2012-09-05 08:57:23 -07001145 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08001146 if (m == NULL) {
1147 memset(&location, 0, sizeof(location));
1148 } else {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001149 mirror::Class* c = m->GetDeclaringClass();
Elliott Hughes74847412012-06-20 18:10:21 -07001150 location.type_tag = c->IsInterface() ? JDWP::TT_INTERFACE : JDWP::TT_CLASS;
1151 location.class_id = gRegistry->Add(c);
1152 location.method_id = ToMethodId(m);
Ian Rogers0399dde2012-06-06 17:09:28 -07001153 location.dex_pc = dex_pc;
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08001154 }
Elliott Hughesd07986f2011-12-06 18:27:45 -08001155}
1156
Elliott Hughesa96836a2013-01-17 12:27:49 -08001157std::string Dbg::GetMethodName(JDWP::MethodId method_id)
Ian Rogersb726dcb2012-09-05 08:57:23 -07001158 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Brian Carlstromea46f952013-07-30 01:26:50 -07001159 mirror::ArtMethod* m = FromMethodId(method_id);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001160 return MethodHelper(m).GetName();
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001161}
1162
Elliott Hughesa96836a2013-01-17 12:27:49 -08001163std::string Dbg::GetFieldName(JDWP::FieldId field_id)
1164 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Brian Carlstromea46f952013-07-30 01:26:50 -07001165 mirror::ArtField* f = FromFieldId(field_id);
Elliott Hughesa96836a2013-01-17 12:27:49 -08001166 return FieldHelper(f).GetName();
1167}
1168
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001169/*
1170 * Augment the access flags for synthetic methods and fields by setting
1171 * the (as described by the spec) "0xf0000000 bit". Also, strip out any
1172 * flags not specified by the Java programming language.
1173 */
1174static uint32_t MangleAccessFlags(uint32_t accessFlags) {
1175 accessFlags &= kAccJavaFlagsMask;
1176 if ((accessFlags & kAccSynthetic) != 0) {
1177 accessFlags |= 0xf0000000;
1178 }
1179 return accessFlags;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001180}
1181
Elliott Hughesdbb40792011-11-18 17:05:22 -08001182static const uint16_t kEclipseWorkaroundSlot = 1000;
1183
1184/*
1185 * Eclipse appears to expect that the "this" reference is in slot zero.
1186 * If it's not, the "variables" display will show two copies of "this",
1187 * possibly because it gets "this" from SF.ThisObject and then displays
1188 * all locals with nonzero slot numbers.
1189 *
1190 * So, we remap the item in slot 0 to 1000, and remap "this" to zero. On
1191 * SF.GetValues / SF.SetValues we map them back.
Elliott Hughesc5b734a2011-12-01 17:20:58 -08001192 *
1193 * TODO: jdb uses the value to determine whether a variable is a local or an argument,
1194 * by checking whether it's less than the number of arguments. To make that work, we'd
1195 * have to "mangle" all the arguments to come first, not just the implicit argument 'this'.
Elliott Hughesdbb40792011-11-18 17:05:22 -08001196 */
1197static uint16_t MangleSlot(uint16_t slot, const char* name) {
1198 uint16_t newSlot = slot;
1199 if (strcmp(name, "this") == 0) {
1200 newSlot = 0;
1201 } else if (slot == 0) {
1202 newSlot = kEclipseWorkaroundSlot;
1203 }
1204 return newSlot;
1205}
1206
Brian Carlstromea46f952013-07-30 01:26:50 -07001207static uint16_t DemangleSlot(uint16_t slot, mirror::ArtMethod* m)
Ian Rogersb726dcb2012-09-05 08:57:23 -07001208 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Elliott Hughesdbb40792011-11-18 17:05:22 -08001209 if (slot == kEclipseWorkaroundSlot) {
Elliott Hughes68fdbd02011-11-29 19:22:47 -08001210 return 0;
Elliott Hughesdbb40792011-11-18 17:05:22 -08001211 } else if (slot == 0) {
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08001212 const DexFile::CodeItem* code_item = MethodHelper(m).GetCodeItem();
Elliott Hughescaf76542012-06-28 16:08:22 -07001213 CHECK(code_item != NULL) << PrettyMethod(m);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001214 return code_item->registers_size_ - code_item->ins_size_;
Elliott Hughesdbb40792011-11-18 17:05:22 -08001215 }
Elliott Hughes68fdbd02011-11-29 19:22:47 -08001216 return slot;
Elliott Hughesdbb40792011-11-18 17:05:22 -08001217}
1218
Elliott Hughes88d63092013-01-09 09:55:54 -08001219JDWP::JdwpError Dbg::OutputDeclaredFields(JDWP::RefTypeId class_id, bool with_generic, JDWP::ExpandBuf* pReply) {
Elliott Hughes436e3722012-02-17 20:01:47 -08001220 JDWP::JdwpError status;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001221 mirror::Class* c = DecodeClass(class_id, status);
Elliott Hughes436e3722012-02-17 20:01:47 -08001222 if (c == NULL) {
1223 return status;
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -08001224 }
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001225
1226 size_t instance_field_count = c->NumInstanceFields();
1227 size_t static_field_count = c->NumStaticFields();
1228
1229 expandBufAdd4BE(pReply, instance_field_count + static_field_count);
1230
1231 for (size_t i = 0; i < instance_field_count + static_field_count; ++i) {
Brian Carlstromea46f952013-07-30 01:26:50 -07001232 mirror::ArtField* f = (i < instance_field_count) ? c->GetInstanceField(i) : c->GetStaticField(i - instance_field_count);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001233 FieldHelper fh(f);
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001234 expandBufAddFieldId(pReply, ToFieldId(f));
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001235 expandBufAddUtf8String(pReply, fh.GetName());
1236 expandBufAddUtf8String(pReply, fh.GetTypeDescriptor());
Elliott Hughesc5b734a2011-12-01 17:20:58 -08001237 if (with_generic) {
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001238 static const char genericSignature[1] = "";
1239 expandBufAddUtf8String(pReply, genericSignature);
1240 }
1241 expandBufAdd4BE(pReply, MangleAccessFlags(f->GetAccessFlags()));
1242 }
Elliott Hughes436e3722012-02-17 20:01:47 -08001243 return JDWP::ERR_NONE;
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001244}
1245
Elliott Hughes88d63092013-01-09 09:55:54 -08001246JDWP::JdwpError Dbg::OutputDeclaredMethods(JDWP::RefTypeId class_id, bool with_generic,
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001247 JDWP::ExpandBuf* pReply) {
Elliott Hughes436e3722012-02-17 20:01:47 -08001248 JDWP::JdwpError status;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001249 mirror::Class* c = DecodeClass(class_id, status);
Elliott Hughes436e3722012-02-17 20:01:47 -08001250 if (c == NULL) {
1251 return status;
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -08001252 }
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001253
1254 size_t direct_method_count = c->NumDirectMethods();
1255 size_t virtual_method_count = c->NumVirtualMethods();
1256
1257 expandBufAdd4BE(pReply, direct_method_count + virtual_method_count);
1258
1259 for (size_t i = 0; i < direct_method_count + virtual_method_count; ++i) {
Brian Carlstromea46f952013-07-30 01:26:50 -07001260 mirror::ArtMethod* m = (i < direct_method_count) ? c->GetDirectMethod(i) : c->GetVirtualMethod(i - direct_method_count);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001261 MethodHelper mh(m);
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001262 expandBufAddMethodId(pReply, ToMethodId(m));
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001263 expandBufAddUtf8String(pReply, mh.GetName());
Ian Rogersd91d6d62013-09-25 20:26:14 -07001264 expandBufAddUtf8String(pReply, mh.GetSignature().ToString());
Elliott Hughesc5b734a2011-12-01 17:20:58 -08001265 if (with_generic) {
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001266 static const char genericSignature[1] = "";
1267 expandBufAddUtf8String(pReply, genericSignature);
1268 }
1269 expandBufAdd4BE(pReply, MangleAccessFlags(m->GetAccessFlags()));
1270 }
Elliott Hughes436e3722012-02-17 20:01:47 -08001271 return JDWP::ERR_NONE;
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001272}
1273
Elliott Hughes88d63092013-01-09 09:55:54 -08001274JDWP::JdwpError Dbg::OutputDeclaredInterfaces(JDWP::RefTypeId class_id, JDWP::ExpandBuf* pReply) {
Elliott Hughes436e3722012-02-17 20:01:47 -08001275 JDWP::JdwpError status;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001276 mirror::Class* c = DecodeClass(class_id, status);
Elliott Hughes436e3722012-02-17 20:01:47 -08001277 if (c == NULL) {
1278 return status;
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -08001279 }
Elliott Hughes436e3722012-02-17 20:01:47 -08001280
1281 ClassHelper kh(c);
Ian Rogersd24e2642012-06-06 21:21:43 -07001282 size_t interface_count = kh.NumDirectInterfaces();
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001283 expandBufAdd4BE(pReply, interface_count);
1284 for (size_t i = 0; i < interface_count; ++i) {
Elliott Hughes64f574f2013-02-20 14:57:12 -08001285 expandBufAddRefTypeId(pReply, gRegistry->AddRefType(kh.GetDirectInterface(i)));
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001286 }
Elliott Hughes436e3722012-02-17 20:01:47 -08001287 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001288}
1289
Elliott Hughes88d63092013-01-09 09:55:54 -08001290void Dbg::OutputLineTable(JDWP::RefTypeId, JDWP::MethodId method_id, JDWP::ExpandBuf* pReply)
Ian Rogersb726dcb2012-09-05 08:57:23 -07001291 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Elliott Hughes03181a82011-11-17 17:22:21 -08001292 struct DebugCallbackContext {
1293 int numItems;
1294 JDWP::ExpandBuf* pReply;
1295
Elliott Hughes2435a572012-02-17 16:07:41 -08001296 static bool Callback(void* context, uint32_t address, uint32_t line_number) {
Elliott Hughes03181a82011-11-17 17:22:21 -08001297 DebugCallbackContext* pContext = reinterpret_cast<DebugCallbackContext*>(context);
1298 expandBufAdd8BE(pContext->pReply, address);
Elliott Hughes2435a572012-02-17 16:07:41 -08001299 expandBufAdd4BE(pContext->pReply, line_number);
Elliott Hughes03181a82011-11-17 17:22:21 -08001300 pContext->numItems++;
Sebastien Hertzf2910ee2013-10-19 16:39:24 +02001301 return false;
Elliott Hughes03181a82011-11-17 17:22:21 -08001302 }
1303 };
Brian Carlstromea46f952013-07-30 01:26:50 -07001304 mirror::ArtMethod* m = FromMethodId(method_id);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001305 MethodHelper mh(m);
Elliott Hughes03181a82011-11-17 17:22:21 -08001306 uint64_t start, end;
1307 if (m->IsNative()) {
1308 start = -1;
1309 end = -1;
1310 } else {
1311 start = 0;
jeffhao14f0db92012-12-14 17:50:42 -08001312 // Return the index of the last instruction
1313 end = mh.GetCodeItem()->insns_size_in_code_units_ - 1;
Elliott Hughes03181a82011-11-17 17:22:21 -08001314 }
1315
1316 expandBufAdd8BE(pReply, start);
1317 expandBufAdd8BE(pReply, end);
1318
1319 // Add numLines later
1320 size_t numLinesOffset = expandBufGetLength(pReply);
1321 expandBufAdd4BE(pReply, 0);
1322
1323 DebugCallbackContext context;
1324 context.numItems = 0;
1325 context.pReply = pReply;
1326
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001327 mh.GetDexFile().DecodeDebugInfo(mh.GetCodeItem(), m->IsStatic(), m->GetDexMethodIndex(),
1328 DebugCallbackContext::Callback, NULL, &context);
Elliott Hughes03181a82011-11-17 17:22:21 -08001329
1330 JDWP::Set4BE(expandBufGetBuffer(pReply) + numLinesOffset, context.numItems);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001331}
1332
Elliott Hughes88d63092013-01-09 09:55:54 -08001333void Dbg::OutputVariableTable(JDWP::RefTypeId, JDWP::MethodId method_id, bool with_generic, JDWP::ExpandBuf* pReply) {
Elliott Hughesdbb40792011-11-18 17:05:22 -08001334 struct DebugCallbackContext {
Elliott Hughesdbb40792011-11-18 17:05:22 -08001335 JDWP::ExpandBuf* pReply;
Elliott Hughesc5b734a2011-12-01 17:20:58 -08001336 size_t variable_count;
1337 bool with_generic;
Elliott Hughesdbb40792011-11-18 17:05:22 -08001338
Elliott Hughesc5b734a2011-12-01 17:20:58 -08001339 static void Callback(void* context, uint16_t slot, uint32_t startAddress, uint32_t endAddress, const char* name, const char* descriptor, const char* signature) {
Elliott Hughesdbb40792011-11-18 17:05:22 -08001340 DebugCallbackContext* pContext = reinterpret_cast<DebugCallbackContext*>(context);
1341
Elliott Hughesad3da692012-02-24 16:51:35 -08001342 VLOG(jdwp) << StringPrintf(" %2zd: %d(%d) '%s' '%s' '%s' actual slot=%d mangled slot=%d", pContext->variable_count, startAddress, endAddress - startAddress, name, descriptor, signature, slot, MangleSlot(slot, name));
Elliott Hughesdbb40792011-11-18 17:05:22 -08001343
Elliott Hughes68fdbd02011-11-29 19:22:47 -08001344 slot = MangleSlot(slot, name);
1345
Elliott Hughesdbb40792011-11-18 17:05:22 -08001346 expandBufAdd8BE(pContext->pReply, startAddress);
1347 expandBufAddUtf8String(pContext->pReply, name);
1348 expandBufAddUtf8String(pContext->pReply, descriptor);
Elliott Hughesc5b734a2011-12-01 17:20:58 -08001349 if (pContext->with_generic) {
Elliott Hughesdbb40792011-11-18 17:05:22 -08001350 expandBufAddUtf8String(pContext->pReply, signature);
1351 }
1352 expandBufAdd4BE(pContext->pReply, endAddress - startAddress);
1353 expandBufAdd4BE(pContext->pReply, slot);
1354
Elliott Hughesc5b734a2011-12-01 17:20:58 -08001355 ++pContext->variable_count;
Elliott Hughesdbb40792011-11-18 17:05:22 -08001356 }
1357 };
Brian Carlstromea46f952013-07-30 01:26:50 -07001358 mirror::ArtMethod* m = FromMethodId(method_id);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001359 MethodHelper mh(m);
1360 const DexFile::CodeItem* code_item = mh.GetCodeItem();
Elliott Hughesdbb40792011-11-18 17:05:22 -08001361
Elliott Hughesc5b734a2011-12-01 17:20:58 -08001362 // arg_count considers doubles and longs to take 2 units.
1363 // variable_count considers everything to take 1 unit.
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001364 std::string shorty(mh.GetShorty());
Brian Carlstromea46f952013-07-30 01:26:50 -07001365 expandBufAdd4BE(pReply, mirror::ArtMethod::NumArgRegisters(shorty));
Elliott Hughesdbb40792011-11-18 17:05:22 -08001366
Elliott Hughesc5b734a2011-12-01 17:20:58 -08001367 // We don't know the total number of variables yet, so leave a blank and update it later.
1368 size_t variable_count_offset = expandBufGetLength(pReply);
Elliott Hughesdbb40792011-11-18 17:05:22 -08001369 expandBufAdd4BE(pReply, 0);
1370
1371 DebugCallbackContext context;
Elliott Hughesdbb40792011-11-18 17:05:22 -08001372 context.pReply = pReply;
Elliott Hughesc5b734a2011-12-01 17:20:58 -08001373 context.variable_count = 0;
1374 context.with_generic = with_generic;
Elliott Hughesdbb40792011-11-18 17:05:22 -08001375
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001376 mh.GetDexFile().DecodeDebugInfo(code_item, m->IsStatic(), m->GetDexMethodIndex(), NULL,
1377 DebugCallbackContext::Callback, &context);
Elliott Hughesdbb40792011-11-18 17:05:22 -08001378
Elliott Hughesc5b734a2011-12-01 17:20:58 -08001379 JDWP::Set4BE(expandBufGetBuffer(pReply) + variable_count_offset, context.variable_count);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001380}
1381
Elliott Hughes9777ba22013-01-17 09:04:19 -08001382JDWP::JdwpError Dbg::GetBytecodes(JDWP::RefTypeId, JDWP::MethodId method_id,
1383 std::vector<uint8_t>& bytecodes)
1384 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Brian Carlstromea46f952013-07-30 01:26:50 -07001385 mirror::ArtMethod* m = FromMethodId(method_id);
Elliott Hughes9777ba22013-01-17 09:04:19 -08001386 if (m == NULL) {
1387 return JDWP::ERR_INVALID_METHODID;
1388 }
1389 MethodHelper mh(m);
1390 const DexFile::CodeItem* code_item = mh.GetCodeItem();
1391 size_t byte_count = code_item->insns_size_in_code_units_ * 2;
1392 const uint8_t* begin = reinterpret_cast<const uint8_t*>(code_item->insns_);
1393 const uint8_t* end = begin + byte_count;
1394 for (const uint8_t* p = begin; p != end; ++p) {
1395 bytecodes.push_back(*p);
1396 }
1397 return JDWP::ERR_NONE;
1398}
1399
Elliott Hughes88d63092013-01-09 09:55:54 -08001400JDWP::JdwpTag Dbg::GetFieldBasicTag(JDWP::FieldId field_id) {
1401 return BasicTagFromDescriptor(FieldHelper(FromFieldId(field_id)).GetTypeDescriptor());
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001402}
1403
Elliott Hughes88d63092013-01-09 09:55:54 -08001404JDWP::JdwpTag Dbg::GetStaticFieldBasicTag(JDWP::FieldId field_id) {
1405 return BasicTagFromDescriptor(FieldHelper(FromFieldId(field_id)).GetTypeDescriptor());
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001406}
1407
Elliott Hughes88d63092013-01-09 09:55:54 -08001408static JDWP::JdwpError GetFieldValueImpl(JDWP::RefTypeId ref_type_id, JDWP::ObjectId object_id,
1409 JDWP::FieldId field_id, JDWP::ExpandBuf* pReply,
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001410 bool is_static)
Ian Rogersb726dcb2012-09-05 08:57:23 -07001411 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Elliott Hughes0cf74332012-02-23 23:14:00 -08001412 JDWP::JdwpError status;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001413 mirror::Class* c = DecodeClass(ref_type_id, status);
Elliott Hughes88d63092013-01-09 09:55:54 -08001414 if (ref_type_id != 0 && c == NULL) {
Elliott Hughes0cf74332012-02-23 23:14:00 -08001415 return status;
1416 }
1417
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001418 mirror::Object* o = gRegistry->Get<mirror::Object*>(object_id);
Elliott Hughes64f574f2013-02-20 14:57:12 -08001419 if ((!is_static && o == NULL) || o == ObjectRegistry::kInvalidObject) {
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08001420 return JDWP::ERR_INVALID_OBJECT;
1421 }
Brian Carlstromea46f952013-07-30 01:26:50 -07001422 mirror::ArtField* f = FromFieldId(field_id);
Elliott Hughes0cf74332012-02-23 23:14:00 -08001423
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001424 mirror::Class* receiver_class = c;
Elliott Hughes0cf74332012-02-23 23:14:00 -08001425 if (receiver_class == NULL && o != NULL) {
1426 receiver_class = o->GetClass();
1427 }
1428 // TODO: should we give up now if receiver_class is NULL?
1429 if (receiver_class != NULL && !f->GetDeclaringClass()->IsAssignableFrom(receiver_class)) {
1430 LOG(INFO) << "ERR_INVALID_FIELDID: " << PrettyField(f) << " " << PrettyClass(receiver_class);
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08001431 return JDWP::ERR_INVALID_FIELDID;
1432 }
Elliott Hughesaed4be92011-12-02 16:16:23 -08001433
Elliott Hughes0cf74332012-02-23 23:14:00 -08001434 // The RI only enforces the static/non-static mismatch in one direction.
1435 // TODO: should we change the tests and check both?
1436 if (is_static) {
1437 if (!f->IsStatic()) {
1438 return JDWP::ERR_INVALID_FIELDID;
1439 }
1440 } else {
1441 if (f->IsStatic()) {
1442 LOG(WARNING) << "Ignoring non-NULL receiver for ObjectReference.SetValues on static field " << PrettyField(f);
Elliott Hughes0cf74332012-02-23 23:14:00 -08001443 }
1444 }
jeffhao0dfbb7e2012-11-28 15:26:03 -08001445 if (f->IsStatic()) {
1446 o = f->GetDeclaringClass();
1447 }
Elliott Hughes0cf74332012-02-23 23:14:00 -08001448
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001449 JDWP::JdwpTag tag = BasicTagFromDescriptor(FieldHelper(f).GetTypeDescriptor());
Elliott Hughesaed4be92011-12-02 16:16:23 -08001450
1451 if (IsPrimitiveTag(tag)) {
1452 expandBufAdd1(pReply, tag);
1453 if (tag == JDWP::JT_BOOLEAN || tag == JDWP::JT_BYTE) {
1454 expandBufAdd1(pReply, f->Get32(o));
1455 } else if (tag == JDWP::JT_CHAR || tag == JDWP::JT_SHORT) {
1456 expandBufAdd2BE(pReply, f->Get32(o));
1457 } else if (tag == JDWP::JT_FLOAT || tag == JDWP::JT_INT) {
1458 expandBufAdd4BE(pReply, f->Get32(o));
1459 } else if (tag == JDWP::JT_DOUBLE || tag == JDWP::JT_LONG) {
1460 expandBufAdd8BE(pReply, f->Get64(o));
1461 } else {
Elliott Hughes3d30d9b2011-12-07 17:35:48 -08001462 LOG(FATAL) << "Unknown tag: " << tag;
Elliott Hughesaed4be92011-12-02 16:16:23 -08001463 }
1464 } else {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001465 mirror::Object* value = f->GetObject(o);
Elliott Hughesaed4be92011-12-02 16:16:23 -08001466 expandBufAdd1(pReply, TagFromObject(value));
1467 expandBufAddObjectId(pReply, gRegistry->Add(value));
1468 }
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08001469 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001470}
1471
Elliott Hughes88d63092013-01-09 09:55:54 -08001472JDWP::JdwpError Dbg::GetFieldValue(JDWP::ObjectId object_id, JDWP::FieldId field_id,
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001473 JDWP::ExpandBuf* pReply) {
Elliott Hughes88d63092013-01-09 09:55:54 -08001474 return GetFieldValueImpl(0, object_id, field_id, pReply, false);
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08001475}
1476
Elliott Hughes88d63092013-01-09 09:55:54 -08001477JDWP::JdwpError Dbg::GetStaticFieldValue(JDWP::RefTypeId ref_type_id, JDWP::FieldId field_id, JDWP::ExpandBuf* pReply) {
1478 return GetFieldValueImpl(ref_type_id, 0, field_id, pReply, true);
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08001479}
1480
Elliott Hughes88d63092013-01-09 09:55:54 -08001481static JDWP::JdwpError SetFieldValueImpl(JDWP::ObjectId object_id, JDWP::FieldId field_id,
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001482 uint64_t value, int width, bool is_static)
Ian Rogersb726dcb2012-09-05 08:57:23 -07001483 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001484 mirror::Object* o = gRegistry->Get<mirror::Object*>(object_id);
Elliott Hughes64f574f2013-02-20 14:57:12 -08001485 if ((!is_static && o == NULL) || o == ObjectRegistry::kInvalidObject) {
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08001486 return JDWP::ERR_INVALID_OBJECT;
1487 }
Brian Carlstromea46f952013-07-30 01:26:50 -07001488 mirror::ArtField* f = FromFieldId(field_id);
Elliott Hughes0cf74332012-02-23 23:14:00 -08001489
1490 // The RI only enforces the static/non-static mismatch in one direction.
1491 // TODO: should we change the tests and check both?
1492 if (is_static) {
1493 if (!f->IsStatic()) {
1494 return JDWP::ERR_INVALID_FIELDID;
1495 }
1496 } else {
1497 if (f->IsStatic()) {
1498 LOG(WARNING) << "Ignoring non-NULL receiver for ObjectReference.SetValues on static field " << PrettyField(f);
Elliott Hughes0cf74332012-02-23 23:14:00 -08001499 }
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08001500 }
jeffhao0dfbb7e2012-11-28 15:26:03 -08001501 if (f->IsStatic()) {
1502 o = f->GetDeclaringClass();
1503 }
Elliott Hughesaed4be92011-12-02 16:16:23 -08001504
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001505 JDWP::JdwpTag tag = BasicTagFromDescriptor(FieldHelper(f).GetTypeDescriptor());
Elliott Hughesaed4be92011-12-02 16:16:23 -08001506
1507 if (IsPrimitiveTag(tag)) {
1508 if (tag == JDWP::JT_DOUBLE || tag == JDWP::JT_LONG) {
Elliott Hughes1bac54f2012-03-16 12:48:31 -07001509 CHECK_EQ(width, 8);
Elliott Hughesaed4be92011-12-02 16:16:23 -08001510 f->Set64(o, value);
1511 } else {
Elliott Hughes1bac54f2012-03-16 12:48:31 -07001512 CHECK_LE(width, 4);
Elliott Hughesaed4be92011-12-02 16:16:23 -08001513 f->Set32(o, value);
1514 }
1515 } else {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001516 mirror::Object* v = gRegistry->Get<mirror::Object*>(value);
Elliott Hughes64f574f2013-02-20 14:57:12 -08001517 if (v == ObjectRegistry::kInvalidObject) {
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -08001518 return JDWP::ERR_INVALID_OBJECT;
1519 }
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08001520 if (v != NULL) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001521 mirror::Class* field_type = FieldHelper(f).GetType();
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08001522 if (!field_type->IsAssignableFrom(v->GetClass())) {
1523 return JDWP::ERR_INVALID_OBJECT;
1524 }
1525 }
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -08001526 f->SetObject(o, v);
Elliott Hughesaed4be92011-12-02 16:16:23 -08001527 }
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -08001528
1529 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001530}
1531
Elliott Hughes88d63092013-01-09 09:55:54 -08001532JDWP::JdwpError Dbg::SetFieldValue(JDWP::ObjectId object_id, JDWP::FieldId field_id, uint64_t value,
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001533 int width) {
Elliott Hughes88d63092013-01-09 09:55:54 -08001534 return SetFieldValueImpl(object_id, field_id, value, width, false);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001535}
1536
Elliott Hughes88d63092013-01-09 09:55:54 -08001537JDWP::JdwpError Dbg::SetStaticFieldValue(JDWP::FieldId field_id, uint64_t value, int width) {
1538 return SetFieldValueImpl(0, field_id, value, width, true);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001539}
1540
Elliott Hughes88d63092013-01-09 09:55:54 -08001541std::string Dbg::StringToUtf8(JDWP::ObjectId string_id) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001542 mirror::String* s = gRegistry->Get<mirror::String*>(string_id);
Elliott Hughes68fdbd02011-11-29 19:22:47 -08001543 return s->ToModifiedUtf8();
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001544}
1545
Elliott Hughes221229c2013-01-08 18:17:50 -08001546JDWP::JdwpError Dbg::GetThreadName(JDWP::ObjectId thread_id, std::string& name) {
jeffhaoa77f0f62012-12-05 17:19:31 -08001547 ScopedObjectAccessUnchecked soa(Thread::Current());
1548 MutexLock mu(soa.Self(), *Locks::thread_list_lock_);
Elliott Hughes221229c2013-01-08 18:17:50 -08001549 Thread* thread;
1550 JDWP::JdwpError error = DecodeThread(soa, thread_id, thread);
1551 if (error != JDWP::ERR_NONE && error != JDWP::ERR_THREAD_NOT_ALIVE) {
1552 return error;
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001553 }
Elliott Hughes221229c2013-01-08 18:17:50 -08001554
1555 // We still need to report the zombie threads' names, so we can't just call Thread::GetThreadName.
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001556 mirror::Object* thread_object = gRegistry->Get<mirror::Object*>(thread_id);
Brian Carlstromea46f952013-07-30 01:26:50 -07001557 mirror::ArtField* java_lang_Thread_name_field =
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001558 soa.DecodeField(WellKnownClasses::java_lang_Thread_name);
1559 mirror::String* s =
1560 reinterpret_cast<mirror::String*>(java_lang_Thread_name_field->GetObject(thread_object));
Elliott Hughes221229c2013-01-08 18:17:50 -08001561 if (s != NULL) {
1562 name = s->ToModifiedUtf8();
1563 }
1564 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001565}
1566
Elliott Hughes221229c2013-01-08 18:17:50 -08001567JDWP::JdwpError Dbg::GetThreadGroup(JDWP::ObjectId thread_id, JDWP::ExpandBuf* pReply) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001568 ScopedObjectAccess soa(Thread::Current());
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001569 mirror::Object* thread_object = gRegistry->Get<mirror::Object*>(thread_id);
Elliott Hughes64f574f2013-02-20 14:57:12 -08001570 if (thread_object == ObjectRegistry::kInvalidObject) {
Elliott Hughes2435a572012-02-17 16:07:41 -08001571 return JDWP::ERR_INVALID_OBJECT;
1572 }
1573
1574 // Okay, so it's an object, but is it actually a thread?
Ian Rogers50b35e22012-10-04 10:09:15 -07001575 MutexLock mu(soa.Self(), *Locks::thread_list_lock_);
Elliott Hughes221229c2013-01-08 18:17:50 -08001576 Thread* thread;
1577 JDWP::JdwpError error = DecodeThread(soa, thread_id, thread);
1578 if (error == JDWP::ERR_THREAD_NOT_ALIVE) {
1579 // Zombie threads are in the null group.
1580 expandBufAddObjectId(pReply, JDWP::ObjectId(0));
1581 return JDWP::ERR_NONE;
1582 }
1583 if (error != JDWP::ERR_NONE) {
1584 return error;
Elliott Hughes2435a572012-02-17 16:07:41 -08001585 }
Elliott Hughes499c5132011-11-17 14:55:11 -08001586
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001587 mirror::Class* c = Runtime::Current()->GetClassLinker()->FindSystemClass("Ljava/lang/Thread;");
Elliott Hughes499c5132011-11-17 14:55:11 -08001588 CHECK(c != NULL);
Brian Carlstromea46f952013-07-30 01:26:50 -07001589 mirror::ArtField* f = c->FindInstanceField("group", "Ljava/lang/ThreadGroup;");
Elliott Hughes499c5132011-11-17 14:55:11 -08001590 CHECK(f != NULL);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001591 mirror::Object* group = f->GetObject(thread_object);
Elliott Hughes499c5132011-11-17 14:55:11 -08001592 CHECK(group != NULL);
Elliott Hughes2435a572012-02-17 16:07:41 -08001593 JDWP::ObjectId thread_group_id = gRegistry->Add(group);
1594
1595 expandBufAddObjectId(pReply, thread_group_id);
1596 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001597}
1598
Elliott Hughes88d63092013-01-09 09:55:54 -08001599std::string Dbg::GetThreadGroupName(JDWP::ObjectId thread_group_id) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001600 ScopedObjectAccess soa(Thread::Current());
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001601 mirror::Object* thread_group = gRegistry->Get<mirror::Object*>(thread_group_id);
Elliott Hughes499c5132011-11-17 14:55:11 -08001602 CHECK(thread_group != NULL);
1603
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001604 mirror::Class* c = Runtime::Current()->GetClassLinker()->FindSystemClass("Ljava/lang/ThreadGroup;");
Elliott Hughes499c5132011-11-17 14:55:11 -08001605 CHECK(c != NULL);
Brian Carlstromea46f952013-07-30 01:26:50 -07001606 mirror::ArtField* f = c->FindInstanceField("name", "Ljava/lang/String;");
Elliott Hughes499c5132011-11-17 14:55:11 -08001607 CHECK(f != NULL);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001608 mirror::String* s = reinterpret_cast<mirror::String*>(f->GetObject(thread_group));
Elliott Hughes499c5132011-11-17 14:55:11 -08001609 return s->ToModifiedUtf8();
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001610}
1611
Elliott Hughes88d63092013-01-09 09:55:54 -08001612JDWP::ObjectId Dbg::GetThreadGroupParent(JDWP::ObjectId thread_group_id) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001613 mirror::Object* thread_group = gRegistry->Get<mirror::Object*>(thread_group_id);
Elliott Hughes4e235312011-12-02 11:34:15 -08001614 CHECK(thread_group != NULL);
1615
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001616 mirror::Class* c = Runtime::Current()->GetClassLinker()->FindSystemClass("Ljava/lang/ThreadGroup;");
Elliott Hughes4e235312011-12-02 11:34:15 -08001617 CHECK(c != NULL);
Brian Carlstromea46f952013-07-30 01:26:50 -07001618 mirror::ArtField* f = c->FindInstanceField("parent", "Ljava/lang/ThreadGroup;");
Elliott Hughes4e235312011-12-02 11:34:15 -08001619 CHECK(f != NULL);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001620 mirror::Object* parent = f->GetObject(thread_group);
Elliott Hughes4e235312011-12-02 11:34:15 -08001621 return gRegistry->Add(parent);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001622}
1623
1624JDWP::ObjectId Dbg::GetSystemThreadGroupId() {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001625 ScopedObjectAccessUnchecked soa(Thread::Current());
Brian Carlstromea46f952013-07-30 01:26:50 -07001626 mirror::ArtField* f = soa.DecodeField(WellKnownClasses::java_lang_ThreadGroup_systemThreadGroup);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001627 mirror::Object* group = f->GetObject(f->GetDeclaringClass());
Ian Rogers365c1022012-06-22 15:05:28 -07001628 return gRegistry->Add(group);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001629}
1630
1631JDWP::ObjectId Dbg::GetMainThreadGroupId() {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001632 ScopedObjectAccess soa(Thread::Current());
Brian Carlstromea46f952013-07-30 01:26:50 -07001633 mirror::ArtField* f = soa.DecodeField(WellKnownClasses::java_lang_ThreadGroup_mainThreadGroup);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001634 mirror::Object* group = f->GetObject(f->GetDeclaringClass());
Ian Rogers365c1022012-06-22 15:05:28 -07001635 return gRegistry->Add(group);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001636}
1637
Jeff Hao920af3e2013-08-28 15:46:38 -07001638JDWP::JdwpThreadStatus Dbg::ToJdwpThreadStatus(ThreadState state) {
1639 switch (state) {
1640 case kBlocked:
1641 return JDWP::TS_MONITOR;
1642 case kNative:
1643 case kRunnable:
1644 case kSuspended:
1645 return JDWP::TS_RUNNING;
1646 case kSleeping:
1647 return JDWP::TS_SLEEPING;
1648 case kStarting:
1649 case kTerminated:
1650 return JDWP::TS_ZOMBIE;
1651 case kTimedWaiting:
1652 case kWaitingForDebuggerSend:
1653 case kWaitingForDebuggerSuspension:
1654 case kWaitingForDebuggerToAttach:
1655 case kWaitingForGcToComplete:
1656 case kWaitingForCheckPointsToRun:
1657 case kWaitingForJniOnLoad:
1658 case kWaitingForSignalCatcherOutput:
1659 case kWaitingInMainDebuggerLoop:
1660 case kWaitingInMainSignalCatcherLoop:
1661 case kWaitingPerformingGc:
1662 case kWaiting:
1663 return JDWP::TS_WAIT;
1664 // Don't add a 'default' here so the compiler can spot incompatible enum changes.
1665 }
1666 LOG(FATAL) << "Unknown thread state: " << state;
1667 return JDWP::TS_ZOMBIE;
1668}
1669
Elliott Hughes221229c2013-01-08 18:17:50 -08001670JDWP::JdwpError Dbg::GetThreadStatus(JDWP::ObjectId thread_id, JDWP::JdwpThreadStatus* pThreadStatus, JDWP::JdwpSuspendStatus* pSuspendStatus) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001671 ScopedObjectAccess soa(Thread::Current());
Elliott Hughes499c5132011-11-17 14:55:11 -08001672
Elliott Hughes9e0c1752013-01-09 14:02:58 -08001673 *pSuspendStatus = JDWP::SUSPEND_STATUS_NOT_SUSPENDED;
1674
Ian Rogers50b35e22012-10-04 10:09:15 -07001675 MutexLock mu(soa.Self(), *Locks::thread_list_lock_);
Elliott Hughes221229c2013-01-08 18:17:50 -08001676 Thread* thread;
1677 JDWP::JdwpError error = DecodeThread(soa, thread_id, thread);
1678 if (error != JDWP::ERR_NONE) {
1679 if (error == JDWP::ERR_THREAD_NOT_ALIVE) {
1680 *pThreadStatus = JDWP::TS_ZOMBIE;
Elliott Hughes221229c2013-01-08 18:17:50 -08001681 return JDWP::ERR_NONE;
1682 }
1683 return error;
Elliott Hughes499c5132011-11-17 14:55:11 -08001684 }
1685
Elliott Hughes9e0c1752013-01-09 14:02:58 -08001686 if (IsSuspendedForDebugger(soa, thread)) {
1687 *pSuspendStatus = JDWP::SUSPEND_STATUS_SUSPENDED;
Elliott Hughes499c5132011-11-17 14:55:11 -08001688 }
1689
Jeff Hao920af3e2013-08-28 15:46:38 -07001690 *pThreadStatus = ToJdwpThreadStatus(thread->GetState());
Elliott Hughes221229c2013-01-08 18:17:50 -08001691 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001692}
1693
Elliott Hughes221229c2013-01-08 18:17:50 -08001694JDWP::JdwpError Dbg::GetThreadDebugSuspendCount(JDWP::ObjectId thread_id, JDWP::ExpandBuf* pReply) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001695 ScopedObjectAccess soa(Thread::Current());
Ian Rogers50b35e22012-10-04 10:09:15 -07001696 MutexLock mu(soa.Self(), *Locks::thread_list_lock_);
Elliott Hughes221229c2013-01-08 18:17:50 -08001697 Thread* thread;
1698 JDWP::JdwpError error = DecodeThread(soa, thread_id, thread);
1699 if (error != JDWP::ERR_NONE) {
1700 return error;
Elliott Hughes2435a572012-02-17 16:07:41 -08001701 }
Ian Rogers50b35e22012-10-04 10:09:15 -07001702 MutexLock mu2(soa.Self(), *Locks::thread_suspend_count_lock_);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001703 expandBufAdd4BE(pReply, thread->GetDebugSuspendCount());
Elliott Hughes2435a572012-02-17 16:07:41 -08001704 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001705}
1706
Elliott Hughesf9501702013-01-11 11:22:27 -08001707JDWP::JdwpError Dbg::Interrupt(JDWP::ObjectId thread_id) {
1708 ScopedObjectAccess soa(Thread::Current());
1709 MutexLock mu(soa.Self(), *Locks::thread_list_lock_);
1710 Thread* thread;
1711 JDWP::JdwpError error = DecodeThread(soa, thread_id, thread);
1712 if (error != JDWP::ERR_NONE) {
1713 return error;
1714 }
1715 thread->Interrupt();
1716 return JDWP::ERR_NONE;
1717}
1718
Elliott Hughescaf76542012-06-28 16:08:22 -07001719void Dbg::GetThreads(JDWP::ObjectId thread_group_id, std::vector<JDWP::ObjectId>& thread_ids) {
Ian Rogers365c1022012-06-22 15:05:28 -07001720 class ThreadListVisitor {
1721 public:
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001722 ThreadListVisitor(const ScopedObjectAccessUnchecked& soa, mirror::Object* desired_thread_group,
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001723 std::vector<JDWP::ObjectId>& thread_ids)
Ian Rogersb726dcb2012-09-05 08:57:23 -07001724 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_)
jeffhao0dfbb7e2012-11-28 15:26:03 -08001725 : soa_(soa), desired_thread_group_(desired_thread_group), thread_ids_(thread_ids) {}
Ian Rogers365c1022012-06-22 15:05:28 -07001726
Elliott Hughesa2155262011-11-16 16:26:58 -08001727 static void Visit(Thread* t, void* arg) {
1728 reinterpret_cast<ThreadListVisitor*>(arg)->Visit(t);
1729 }
1730
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001731 // TODO: Enable annotalysis. We know lock is held in constructor, but abstraction confuses
1732 // annotalysis.
1733 void Visit(Thread* t) NO_THREAD_SAFETY_ANALYSIS {
Elliott Hughesa2155262011-11-16 16:26:58 -08001734 if (t == Dbg::GetDebugThread()) {
1735 // Skip the JDWP thread. Some debuggers get bent out of shape when they can't suspend and
1736 // query all threads, so it's easier if we just don't tell them about this thread.
1737 return;
1738 }
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001739 mirror::Object* peer = t->GetPeer();
jeffhao0dfbb7e2012-11-28 15:26:03 -08001740 if (IsInDesiredThreadGroup(peer)) {
Ian Rogers120f1c72012-09-28 17:17:10 -07001741 thread_ids_.push_back(gRegistry->Add(peer));
Elliott Hughesa2155262011-11-16 16:26:58 -08001742 }
1743 }
1744
Ian Rogers365c1022012-06-22 15:05:28 -07001745 private:
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001746 bool IsInDesiredThreadGroup(mirror::Object* peer)
jeffhao0dfbb7e2012-11-28 15:26:03 -08001747 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
jeffhao0dfbb7e2012-11-28 15:26:03 -08001748 // peer might be NULL if the thread is still starting up.
1749 if (peer == NULL) {
1750 // We can't tell the debugger about this thread yet.
1751 // TODO: if we identified threads to the debugger by their Thread*
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001752 // rather than their peer's mirror::Object*, we could fix this.
jeffhao0dfbb7e2012-11-28 15:26:03 -08001753 // Doing so might help us report ZOMBIE threads too.
1754 return false;
1755 }
jeffhaoc1e04902012-12-13 12:41:10 -08001756 // Do we want threads from all thread groups?
1757 if (desired_thread_group_ == NULL) {
1758 return true;
1759 }
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001760 mirror::Object* group = soa_.DecodeField(WellKnownClasses::java_lang_Thread_group)->GetObject(peer);
jeffhao0dfbb7e2012-11-28 15:26:03 -08001761 return (group == desired_thread_group_);
1762 }
1763
Mathieu Chartierdbe6f462012-09-25 16:54:50 -07001764 const ScopedObjectAccessUnchecked& soa_;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001765 mirror::Object* const desired_thread_group_;
Elliott Hughescaf76542012-06-28 16:08:22 -07001766 std::vector<JDWP::ObjectId>& thread_ids_;
Elliott Hughesa2155262011-11-16 16:26:58 -08001767 };
1768
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001769 ScopedObjectAccessUnchecked soa(Thread::Current());
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001770 mirror::Object* thread_group = gRegistry->Get<mirror::Object*>(thread_group_id);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001771 ThreadListVisitor tlv(soa, thread_group, thread_ids);
Ian Rogers50b35e22012-10-04 10:09:15 -07001772 MutexLock mu(soa.Self(), *Locks::thread_list_lock_);
Elliott Hughesf8349362012-06-18 15:00:06 -07001773 Runtime::Current()->GetThreadList()->ForEach(ThreadListVisitor::Visit, &tlv);
Elliott Hughescaf76542012-06-28 16:08:22 -07001774}
Elliott Hughesa2155262011-11-16 16:26:58 -08001775
Elliott Hughescaf76542012-06-28 16:08:22 -07001776void Dbg::GetChildThreadGroups(JDWP::ObjectId thread_group_id, std::vector<JDWP::ObjectId>& child_thread_group_ids) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001777 ScopedObjectAccess soa(Thread::Current());
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001778 mirror::Object* thread_group = gRegistry->Get<mirror::Object*>(thread_group_id);
Elliott Hughescaf76542012-06-28 16:08:22 -07001779
1780 // Get the ArrayList<ThreadGroup> "groups" out of this thread group...
Brian Carlstromea46f952013-07-30 01:26:50 -07001781 mirror::ArtField* groups_field = thread_group->GetClass()->FindInstanceField("groups", "Ljava/util/List;");
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001782 mirror::Object* groups_array_list = groups_field->GetObject(thread_group);
Elliott Hughescaf76542012-06-28 16:08:22 -07001783
1784 // Get the array and size out of the ArrayList<ThreadGroup>...
Brian Carlstromea46f952013-07-30 01:26:50 -07001785 mirror::ArtField* array_field = groups_array_list->GetClass()->FindInstanceField("array", "[Ljava/lang/Object;");
1786 mirror::ArtField* size_field = groups_array_list->GetClass()->FindInstanceField("size", "I");
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001787 mirror::ObjectArray<mirror::Object>* groups_array =
1788 array_field->GetObject(groups_array_list)->AsObjectArray<mirror::Object>();
Elliott Hughescaf76542012-06-28 16:08:22 -07001789 const int32_t size = size_field->GetInt(groups_array_list);
1790
1791 // Copy the first 'size' elements out of the array into the result.
1792 for (int32_t i = 0; i < size; ++i) {
1793 child_thread_group_ids.push_back(gRegistry->Add(groups_array->Get(i)));
Elliott Hughesa2155262011-11-16 16:26:58 -08001794 }
1795}
1796
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001797static int GetStackDepth(Thread* thread)
Ian Rogersb726dcb2012-09-05 08:57:23 -07001798 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Ian Rogers0399dde2012-06-06 17:09:28 -07001799 struct CountStackDepthVisitor : public StackVisitor {
Brian Carlstrom93ba8932013-07-17 21:31:49 -07001800 explicit CountStackDepthVisitor(Thread* thread)
Ian Rogers7a22fa62013-01-23 12:16:16 -08001801 : StackVisitor(thread, NULL), depth(0) {}
Ian Rogers0399dde2012-06-06 17:09:28 -07001802
Elliott Hughes64f574f2013-02-20 14:57:12 -08001803 // TODO: Enable annotalysis. We know lock is held in constructor, but abstraction confuses
1804 // annotalysis.
1805 bool VisitFrame() NO_THREAD_SAFETY_ANALYSIS {
Ian Rogers0399dde2012-06-06 17:09:28 -07001806 if (!GetMethod()->IsRuntimeMethod()) {
Elliott Hughesf8a2df72011-12-01 12:19:54 -08001807 ++depth;
1808 }
Elliott Hughes530fa002012-03-12 11:44:49 -07001809 return true;
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001810 }
1811 size_t depth;
1812 };
Elliott Hughes08fc03a2012-06-26 17:34:00 -07001813
Ian Rogers7a22fa62013-01-23 12:16:16 -08001814 CountStackDepthVisitor visitor(thread);
Ian Rogers0399dde2012-06-06 17:09:28 -07001815 visitor.WalkStack();
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001816 return visitor.depth;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001817}
1818
Elliott Hughes221229c2013-01-08 18:17:50 -08001819JDWP::JdwpError Dbg::GetThreadFrameCount(JDWP::ObjectId thread_id, size_t& result) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001820 ScopedObjectAccess soa(Thread::Current());
jeffhaoa77f0f62012-12-05 17:19:31 -08001821 MutexLock mu(soa.Self(), *Locks::thread_list_lock_);
Elliott Hughes221229c2013-01-08 18:17:50 -08001822 Thread* thread;
1823 JDWP::JdwpError error = DecodeThread(soa, thread_id, thread);
1824 if (error != JDWP::ERR_NONE) {
1825 return error;
1826 }
Elliott Hughesf15f4a02013-01-09 10:09:38 -08001827 if (!IsSuspendedForDebugger(soa, thread)) {
1828 return JDWP::ERR_THREAD_NOT_SUSPENDED;
1829 }
Elliott Hughes221229c2013-01-08 18:17:50 -08001830 result = GetStackDepth(thread);
1831 return JDWP::ERR_NONE;
Elliott Hughes86964332012-02-15 19:37:42 -08001832}
1833
Ian Rogers306057f2012-11-26 12:45:53 -08001834JDWP::JdwpError Dbg::GetThreadFrames(JDWP::ObjectId thread_id, size_t start_frame,
1835 size_t frame_count, JDWP::ExpandBuf* buf) {
Elliott Hughes6e9d22c2012-06-22 15:02:37 -07001836 class GetFrameVisitor : public StackVisitor {
1837 public:
Ian Rogers7a22fa62013-01-23 12:16:16 -08001838 GetFrameVisitor(Thread* thread, size_t start_frame, size_t frame_count, JDWP::ExpandBuf* buf)
Ian Rogersb726dcb2012-09-05 08:57:23 -07001839 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_)
Ian Rogers7a22fa62013-01-23 12:16:16 -08001840 : StackVisitor(thread, NULL), depth_(0),
Elliott Hughes6e9d22c2012-06-22 15:02:37 -07001841 start_frame_(start_frame), frame_count_(frame_count), buf_(buf) {
1842 expandBufAdd4BE(buf_, frame_count_);
Elliott Hughes03181a82011-11-17 17:22:21 -08001843 }
Ian Rogers0399dde2012-06-06 17:09:28 -07001844
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001845 // TODO: Enable annotalysis. We know lock is held in constructor, but abstraction confuses
1846 // annotalysis.
1847 virtual bool VisitFrame() NO_THREAD_SAFETY_ANALYSIS {
Ian Rogers0399dde2012-06-06 17:09:28 -07001848 if (GetMethod()->IsRuntimeMethod()) {
Brian Carlstrom7934ac22013-07-26 10:54:15 -07001849 return true; // The debugger can't do anything useful with a frame that has no Method*.
Elliott Hughes03181a82011-11-17 17:22:21 -08001850 }
Elliott Hughes6e9d22c2012-06-22 15:02:37 -07001851 if (depth_ >= start_frame_ + frame_count_) {
Elliott Hughes530fa002012-03-12 11:44:49 -07001852 return false;
Elliott Hughes03181a82011-11-17 17:22:21 -08001853 }
Elliott Hughes6e9d22c2012-06-22 15:02:37 -07001854 if (depth_ >= start_frame_) {
1855 JDWP::FrameId frame_id(GetFrameId());
1856 JDWP::JdwpLocation location;
1857 SetLocation(location, GetMethod(), GetDexPc());
Elliott Hughes7baf96f2012-06-22 16:33:50 -07001858 VLOG(jdwp) << StringPrintf(" Frame %3zd: id=%3lld ", depth_, frame_id) << location;
Elliott Hughes6e9d22c2012-06-22 15:02:37 -07001859 expandBufAdd8BE(buf_, frame_id);
1860 expandBufAddLocation(buf_, location);
1861 }
1862 ++depth_;
Elliott Hughes530fa002012-03-12 11:44:49 -07001863 return true;
Elliott Hughes03181a82011-11-17 17:22:21 -08001864 }
Elliott Hughes6e9d22c2012-06-22 15:02:37 -07001865
1866 private:
1867 size_t depth_;
1868 const size_t start_frame_;
1869 const size_t frame_count_;
1870 JDWP::ExpandBuf* buf_;
Elliott Hughes03181a82011-11-17 17:22:21 -08001871 };
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001872
1873 ScopedObjectAccessUnchecked soa(Thread::Current());
jeffhaoa77f0f62012-12-05 17:19:31 -08001874 MutexLock mu(soa.Self(), *Locks::thread_list_lock_);
Elliott Hughes221229c2013-01-08 18:17:50 -08001875 Thread* thread;
1876 JDWP::JdwpError error = DecodeThread(soa, thread_id, thread);
1877 if (error != JDWP::ERR_NONE) {
1878 return error;
1879 }
Elliott Hughesf15f4a02013-01-09 10:09:38 -08001880 if (!IsSuspendedForDebugger(soa, thread)) {
1881 return JDWP::ERR_THREAD_NOT_SUSPENDED;
1882 }
Ian Rogers7a22fa62013-01-23 12:16:16 -08001883 GetFrameVisitor visitor(thread, start_frame, frame_count, buf);
Ian Rogers0399dde2012-06-06 17:09:28 -07001884 visitor.WalkStack();
Elliott Hughes6e9d22c2012-06-22 15:02:37 -07001885 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001886}
1887
1888JDWP::ObjectId Dbg::GetThreadSelfId() {
Mathieu Chartierdbe6f462012-09-25 16:54:50 -07001889 ScopedObjectAccessUnchecked soa(Thread::Current());
Ian Rogerscfaa4552012-11-26 21:00:08 -08001890 return gRegistry->Add(soa.Self()->GetPeer());
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001891}
1892
Elliott Hughes475fc232011-10-25 15:00:35 -07001893void Dbg::SuspendVM() {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001894 Runtime::Current()->GetThreadList()->SuspendAllForDebugger();
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001895}
1896
1897void Dbg::ResumeVM() {
Elliott Hughesc61a2672012-06-21 14:52:29 -07001898 Runtime::Current()->GetThreadList()->UndoDebuggerSuspensions();
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001899}
1900
Elliott Hughes221229c2013-01-08 18:17:50 -08001901JDWP::JdwpError Dbg::SuspendThread(JDWP::ObjectId thread_id, bool request_suspension) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001902 ScopedLocalRef<jobject> peer(Thread::Current()->GetJniEnv(), NULL);
1903 {
1904 ScopedObjectAccess soa(Thread::Current());
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001905 peer.reset(soa.AddLocalReference<jobject>(gRegistry->Get<mirror::Object*>(thread_id)));
Elliott Hughes4e235312011-12-02 11:34:15 -08001906 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001907 if (peer.get() == NULL) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001908 return JDWP::ERR_THREAD_NOT_ALIVE;
1909 }
1910 // Suspend thread to build stack trace.
Elliott Hughesf327e072013-01-09 16:01:26 -08001911 bool timed_out;
Ian Rogersd9c4fc92013-10-01 19:45:43 -07001912 Thread* thread = ThreadList::SuspendThreadByPeer(peer.get(), request_suspension, true,
1913 &timed_out);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001914 if (thread != NULL) {
1915 return JDWP::ERR_NONE;
Elliott Hughesf327e072013-01-09 16:01:26 -08001916 } else if (timed_out) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001917 return JDWP::ERR_INTERNAL;
1918 } else {
1919 return JDWP::ERR_THREAD_NOT_ALIVE;
1920 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001921}
1922
Elliott Hughes221229c2013-01-08 18:17:50 -08001923void Dbg::ResumeThread(JDWP::ObjectId thread_id) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001924 ScopedObjectAccessUnchecked soa(Thread::Current());
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001925 mirror::Object* peer = gRegistry->Get<mirror::Object*>(thread_id);
jeffhaoa77f0f62012-12-05 17:19:31 -08001926 Thread* thread;
1927 {
1928 MutexLock mu(soa.Self(), *Locks::thread_list_lock_);
1929 thread = Thread::FromManagedThread(soa, peer);
1930 }
Elliott Hughes4e235312011-12-02 11:34:15 -08001931 if (thread == NULL) {
1932 LOG(WARNING) << "No such thread for resume: " << peer;
1933 return;
1934 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001935 bool needs_resume;
1936 {
Ian Rogers50b35e22012-10-04 10:09:15 -07001937 MutexLock mu2(soa.Self(), *Locks::thread_suspend_count_lock_);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001938 needs_resume = thread->GetSuspendCount() > 0;
1939 }
1940 if (needs_resume) {
Elliott Hughes546b9862012-06-20 16:06:13 -07001941 Runtime::Current()->GetThreadList()->Resume(thread, true);
1942 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001943}
1944
1945void Dbg::SuspendSelf() {
Elliott Hughes475fc232011-10-25 15:00:35 -07001946 Runtime::Current()->GetThreadList()->SuspendSelfForDebugger();
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001947}
1948
Ian Rogers0399dde2012-06-06 17:09:28 -07001949struct GetThisVisitor : public StackVisitor {
Ian Rogers7a22fa62013-01-23 12:16:16 -08001950 GetThisVisitor(Thread* thread, Context* context, JDWP::FrameId frame_id)
Ian Rogersb726dcb2012-09-05 08:57:23 -07001951 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_)
Ian Rogers7a22fa62013-01-23 12:16:16 -08001952 : StackVisitor(thread, context), this_object(NULL), frame_id(frame_id) {}
Ian Rogers0399dde2012-06-06 17:09:28 -07001953
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001954 // TODO: Enable annotalysis. We know lock is held in constructor, but abstraction confuses
1955 // annotalysis.
1956 virtual bool VisitFrame() NO_THREAD_SAFETY_ANALYSIS {
Elliott Hughes6e9d22c2012-06-22 15:02:37 -07001957 if (frame_id != GetFrameId()) {
Ian Rogers0399dde2012-06-06 17:09:28 -07001958 return true; // continue
Ian Rogers0399dde2012-06-06 17:09:28 -07001959 } else {
Ian Rogers62d6c772013-02-27 08:32:07 -08001960 this_object = GetThisObject();
1961 return false;
Ian Rogers0399dde2012-06-06 17:09:28 -07001962 }
Elliott Hughes86b00102011-12-05 17:54:26 -08001963 }
Ian Rogers0399dde2012-06-06 17:09:28 -07001964
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001965 mirror::Object* this_object;
Elliott Hughes6e9d22c2012-06-22 15:02:37 -07001966 JDWP::FrameId frame_id;
Ian Rogers0399dde2012-06-06 17:09:28 -07001967};
1968
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001969JDWP::JdwpError Dbg::GetThisObject(JDWP::ObjectId thread_id, JDWP::FrameId frame_id,
1970 JDWP::ObjectId* result) {
1971 ScopedObjectAccessUnchecked soa(Thread::Current());
1972 Thread* thread;
1973 {
Ian Rogers50b35e22012-10-04 10:09:15 -07001974 MutexLock mu(soa.Self(), *Locks::thread_list_lock_);
Elliott Hughes221229c2013-01-08 18:17:50 -08001975 JDWP::JdwpError error = DecodeThread(soa, thread_id, thread);
1976 if (error != JDWP::ERR_NONE) {
1977 return error;
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001978 }
Elliott Hughes9e0c1752013-01-09 14:02:58 -08001979 if (!IsSuspendedForDebugger(soa, thread)) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001980 return JDWP::ERR_THREAD_NOT_SUSPENDED;
1981 }
Elliott Hughes6e9d22c2012-06-22 15:02:37 -07001982 }
Elliott Hughescaf76542012-06-28 16:08:22 -07001983 UniquePtr<Context> context(Context::Create());
Ian Rogers7a22fa62013-01-23 12:16:16 -08001984 GetThisVisitor visitor(thread, context.get(), frame_id);
Ian Rogers0399dde2012-06-06 17:09:28 -07001985 visitor.WalkStack();
Elliott Hughes6e9d22c2012-06-22 15:02:37 -07001986 *result = gRegistry->Add(visitor.this_object);
1987 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001988}
1989
Elliott Hughes88d63092013-01-09 09:55:54 -08001990void Dbg::GetLocalValue(JDWP::ObjectId thread_id, JDWP::FrameId frame_id, int slot, JDWP::JdwpTag tag,
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001991 uint8_t* buf, size_t width) {
Ian Rogers0399dde2012-06-06 17:09:28 -07001992 struct GetLocalVisitor : public StackVisitor {
Ian Rogers7a22fa62013-01-23 12:16:16 -08001993 GetLocalVisitor(Thread* thread, Context* context, JDWP::FrameId frame_id, int slot,
1994 JDWP::JdwpTag tag, uint8_t* buf, size_t width)
Ian Rogersb726dcb2012-09-05 08:57:23 -07001995 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_)
Ian Rogers7a22fa62013-01-23 12:16:16 -08001996 : StackVisitor(thread, context), frame_id_(frame_id), slot_(slot), tag_(tag),
Ian Rogersca190662012-06-26 15:45:57 -07001997 buf_(buf), width_(width) {}
1998
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001999 // TODO: Enable annotalysis. We know lock is held in constructor, but abstraction confuses
2000 // annotalysis.
2001 bool VisitFrame() NO_THREAD_SAFETY_ANALYSIS {
Ian Rogers0399dde2012-06-06 17:09:28 -07002002 if (GetFrameId() != frame_id_) {
2003 return true; // Not our frame, carry on.
Elliott Hughesdbb40792011-11-18 17:05:22 -08002004 }
Ian Rogers0399dde2012-06-06 17:09:28 -07002005 // TODO: check that the tag is compatible with the actual type of the slot!
Brian Carlstromea46f952013-07-30 01:26:50 -07002006 mirror::ArtMethod* m = GetMethod();
Ian Rogers0399dde2012-06-06 17:09:28 -07002007 uint16_t reg = DemangleSlot(slot_, m);
Elliott Hughesdbb40792011-11-18 17:05:22 -08002008
Ian Rogers0399dde2012-06-06 17:09:28 -07002009 switch (tag_) {
2010 case JDWP::JT_BOOLEAN:
2011 {
2012 CHECK_EQ(width_, 1U);
Ian Rogers2bcb4a42012-11-08 10:39:18 -08002013 uint32_t intVal = GetVReg(m, reg, kIntVReg);
Ian Rogers0399dde2012-06-06 17:09:28 -07002014 VLOG(jdwp) << "get boolean local " << reg << " = " << intVal;
2015 JDWP::Set1(buf_+1, intVal != 0);
2016 }
2017 break;
2018 case JDWP::JT_BYTE:
2019 {
2020 CHECK_EQ(width_, 1U);
Ian Rogers2bcb4a42012-11-08 10:39:18 -08002021 uint32_t intVal = GetVReg(m, reg, kIntVReg);
Ian Rogers0399dde2012-06-06 17:09:28 -07002022 VLOG(jdwp) << "get byte local " << reg << " = " << intVal;
2023 JDWP::Set1(buf_+1, intVal);
2024 }
2025 break;
2026 case JDWP::JT_SHORT:
2027 case JDWP::JT_CHAR:
2028 {
2029 CHECK_EQ(width_, 2U);
Ian Rogers2bcb4a42012-11-08 10:39:18 -08002030 uint32_t intVal = GetVReg(m, reg, kIntVReg);
Ian Rogers0399dde2012-06-06 17:09:28 -07002031 VLOG(jdwp) << "get short/char local " << reg << " = " << intVal;
2032 JDWP::Set2BE(buf_+1, intVal);
2033 }
2034 break;
2035 case JDWP::JT_INT:
Ian Rogers2bcb4a42012-11-08 10:39:18 -08002036 {
2037 CHECK_EQ(width_, 4U);
2038 uint32_t intVal = GetVReg(m, reg, kIntVReg);
2039 VLOG(jdwp) << "get int local " << reg << " = " << intVal;
2040 JDWP::Set4BE(buf_+1, intVal);
2041 }
2042 break;
Ian Rogers0399dde2012-06-06 17:09:28 -07002043 case JDWP::JT_FLOAT:
2044 {
2045 CHECK_EQ(width_, 4U);
Ian Rogers2bcb4a42012-11-08 10:39:18 -08002046 uint32_t intVal = GetVReg(m, reg, kFloatVReg);
Ian Rogers0399dde2012-06-06 17:09:28 -07002047 VLOG(jdwp) << "get int/float local " << reg << " = " << intVal;
2048 JDWP::Set4BE(buf_+1, intVal);
2049 }
2050 break;
2051 case JDWP::JT_ARRAY:
2052 {
2053 CHECK_EQ(width_, sizeof(JDWP::ObjectId));
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002054 mirror::Object* o = reinterpret_cast<mirror::Object*>(GetVReg(m, reg, kReferenceVReg));
Ian Rogers0399dde2012-06-06 17:09:28 -07002055 VLOG(jdwp) << "get array local " << reg << " = " << o;
Mathieu Chartier590fee92013-09-13 13:46:47 -07002056 if (!Runtime::Current()->GetHeap()->IsValidObjectAddress(o)) {
Ian Rogers0399dde2012-06-06 17:09:28 -07002057 LOG(FATAL) << "Register " << reg << " expected to hold array: " << o;
2058 }
2059 JDWP::SetObjectId(buf_+1, gRegistry->Add(o));
2060 }
2061 break;
2062 case JDWP::JT_CLASS_LOADER:
2063 case JDWP::JT_CLASS_OBJECT:
2064 case JDWP::JT_OBJECT:
2065 case JDWP::JT_STRING:
2066 case JDWP::JT_THREAD:
2067 case JDWP::JT_THREAD_GROUP:
2068 {
2069 CHECK_EQ(width_, sizeof(JDWP::ObjectId));
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002070 mirror::Object* o = reinterpret_cast<mirror::Object*>(GetVReg(m, reg, kReferenceVReg));
Ian Rogers0399dde2012-06-06 17:09:28 -07002071 VLOG(jdwp) << "get object local " << reg << " = " << o;
Mathieu Chartier590fee92013-09-13 13:46:47 -07002072 if (!Runtime::Current()->GetHeap()->IsValidObjectAddress(o)) {
Ian Rogers0399dde2012-06-06 17:09:28 -07002073 LOG(FATAL) << "Register " << reg << " expected to hold object: " << o;
2074 }
2075 tag_ = TagFromObject(o);
2076 JDWP::SetObjectId(buf_+1, gRegistry->Add(o));
2077 }
2078 break;
2079 case JDWP::JT_DOUBLE:
Ian Rogers2bcb4a42012-11-08 10:39:18 -08002080 {
2081 CHECK_EQ(width_, 8U);
2082 uint32_t lo = GetVReg(m, reg, kDoubleLoVReg);
2083 uint64_t hi = GetVReg(m, reg + 1, kDoubleHiVReg);
2084 uint64_t longVal = (hi << 32) | lo;
2085 VLOG(jdwp) << "get double/long local " << hi << ":" << lo << " = " << longVal;
2086 JDWP::Set8BE(buf_+1, longVal);
2087 }
2088 break;
Ian Rogers0399dde2012-06-06 17:09:28 -07002089 case JDWP::JT_LONG:
2090 {
2091 CHECK_EQ(width_, 8U);
Ian Rogers2bcb4a42012-11-08 10:39:18 -08002092 uint32_t lo = GetVReg(m, reg, kLongLoVReg);
2093 uint64_t hi = GetVReg(m, reg + 1, kLongHiVReg);
Ian Rogers0399dde2012-06-06 17:09:28 -07002094 uint64_t longVal = (hi << 32) | lo;
2095 VLOG(jdwp) << "get double/long local " << hi << ":" << lo << " = " << longVal;
2096 JDWP::Set8BE(buf_+1, longVal);
2097 }
2098 break;
2099 default:
2100 LOG(FATAL) << "Unknown tag " << tag_;
2101 break;
2102 }
2103
2104 // Prepend tag, which may have been updated.
2105 JDWP::Set1(buf_, tag_);
2106 return false;
2107 }
2108
2109 const JDWP::FrameId frame_id_;
2110 const int slot_;
2111 JDWP::JdwpTag tag_;
2112 uint8_t* const buf_;
2113 const size_t width_;
2114 };
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002115
2116 ScopedObjectAccessUnchecked soa(Thread::Current());
jeffhaoa77f0f62012-12-05 17:19:31 -08002117 MutexLock mu(soa.Self(), *Locks::thread_list_lock_);
Elliott Hughes221229c2013-01-08 18:17:50 -08002118 Thread* thread;
2119 JDWP::JdwpError error = DecodeThread(soa, thread_id, thread);
2120 if (error != JDWP::ERR_NONE) {
2121 return;
2122 }
Ian Rogers0399dde2012-06-06 17:09:28 -07002123 UniquePtr<Context> context(Context::Create());
Ian Rogers7a22fa62013-01-23 12:16:16 -08002124 GetLocalVisitor visitor(thread, context.get(), frame_id, slot, tag, buf, width);
Ian Rogers0399dde2012-06-06 17:09:28 -07002125 visitor.WalkStack();
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002126}
2127
Elliott Hughes88d63092013-01-09 09:55:54 -08002128void Dbg::SetLocalValue(JDWP::ObjectId thread_id, JDWP::FrameId frame_id, int slot, JDWP::JdwpTag tag,
Ian Rogers0399dde2012-06-06 17:09:28 -07002129 uint64_t value, size_t width) {
2130 struct SetLocalVisitor : public StackVisitor {
Ian Rogers7a22fa62013-01-23 12:16:16 -08002131 SetLocalVisitor(Thread* thread, Context* context,
Ian Rogers0399dde2012-06-06 17:09:28 -07002132 JDWP::FrameId frame_id, int slot, JDWP::JdwpTag tag, uint64_t value,
Ian Rogersca190662012-06-26 15:45:57 -07002133 size_t width)
Ian Rogersb726dcb2012-09-05 08:57:23 -07002134 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_)
Ian Rogers7a22fa62013-01-23 12:16:16 -08002135 : StackVisitor(thread, context),
Elliott Hughes08fc03a2012-06-26 17:34:00 -07002136 frame_id_(frame_id), slot_(slot), tag_(tag), value_(value), width_(width) {}
Ian Rogersca190662012-06-26 15:45:57 -07002137
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002138 // TODO: Enable annotalysis. We know lock is held in constructor, but abstraction confuses
2139 // annotalysis.
2140 bool VisitFrame() NO_THREAD_SAFETY_ANALYSIS {
Ian Rogers0399dde2012-06-06 17:09:28 -07002141 if (GetFrameId() != frame_id_) {
2142 return true; // Not our frame, carry on.
2143 }
2144 // TODO: check that the tag is compatible with the actual type of the slot!
Brian Carlstromea46f952013-07-30 01:26:50 -07002145 mirror::ArtMethod* m = GetMethod();
Ian Rogers0399dde2012-06-06 17:09:28 -07002146 uint16_t reg = DemangleSlot(slot_, m);
2147
2148 switch (tag_) {
2149 case JDWP::JT_BOOLEAN:
2150 case JDWP::JT_BYTE:
2151 CHECK_EQ(width_, 1U);
Ian Rogers2bcb4a42012-11-08 10:39:18 -08002152 SetVReg(m, reg, static_cast<uint32_t>(value_), kIntVReg);
Ian Rogers0399dde2012-06-06 17:09:28 -07002153 break;
2154 case JDWP::JT_SHORT:
2155 case JDWP::JT_CHAR:
2156 CHECK_EQ(width_, 2U);
Ian Rogers2bcb4a42012-11-08 10:39:18 -08002157 SetVReg(m, reg, static_cast<uint32_t>(value_), kIntVReg);
Ian Rogers0399dde2012-06-06 17:09:28 -07002158 break;
2159 case JDWP::JT_INT:
Ian Rogers2bcb4a42012-11-08 10:39:18 -08002160 CHECK_EQ(width_, 4U);
2161 SetVReg(m, reg, static_cast<uint32_t>(value_), kIntVReg);
2162 break;
Ian Rogers0399dde2012-06-06 17:09:28 -07002163 case JDWP::JT_FLOAT:
2164 CHECK_EQ(width_, 4U);
Ian Rogers2bcb4a42012-11-08 10:39:18 -08002165 SetVReg(m, reg, static_cast<uint32_t>(value_), kFloatVReg);
Ian Rogers0399dde2012-06-06 17:09:28 -07002166 break;
2167 case JDWP::JT_ARRAY:
2168 case JDWP::JT_OBJECT:
2169 case JDWP::JT_STRING:
2170 {
2171 CHECK_EQ(width_, sizeof(JDWP::ObjectId));
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002172 mirror::Object* o = gRegistry->Get<mirror::Object*>(static_cast<JDWP::ObjectId>(value_));
Elliott Hughes64f574f2013-02-20 14:57:12 -08002173 if (o == ObjectRegistry::kInvalidObject) {
Ian Rogers0399dde2012-06-06 17:09:28 -07002174 UNIMPLEMENTED(FATAL) << "return an error code when given an invalid object to store";
2175 }
Ian Rogers2bcb4a42012-11-08 10:39:18 -08002176 SetVReg(m, reg, static_cast<uint32_t>(reinterpret_cast<uintptr_t>(o)), kReferenceVReg);
Ian Rogers0399dde2012-06-06 17:09:28 -07002177 }
2178 break;
2179 case JDWP::JT_DOUBLE:
Ian Rogers2bcb4a42012-11-08 10:39:18 -08002180 CHECK_EQ(width_, 8U);
2181 SetVReg(m, reg, static_cast<uint32_t>(value_), kDoubleLoVReg);
2182 SetVReg(m, reg + 1, static_cast<uint32_t>(value_ >> 32), kDoubleHiVReg);
2183 break;
Ian Rogers0399dde2012-06-06 17:09:28 -07002184 case JDWP::JT_LONG:
2185 CHECK_EQ(width_, 8U);
Ian Rogers2bcb4a42012-11-08 10:39:18 -08002186 SetVReg(m, reg, static_cast<uint32_t>(value_), kLongLoVReg);
2187 SetVReg(m, reg + 1, static_cast<uint32_t>(value_ >> 32), kLongHiVReg);
Ian Rogers0399dde2012-06-06 17:09:28 -07002188 break;
2189 default:
2190 LOG(FATAL) << "Unknown tag " << tag_;
2191 break;
2192 }
2193 return false;
2194 }
2195
2196 const JDWP::FrameId frame_id_;
2197 const int slot_;
2198 const JDWP::JdwpTag tag_;
2199 const uint64_t value_;
2200 const size_t width_;
2201 };
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002202
2203 ScopedObjectAccessUnchecked soa(Thread::Current());
jeffhaoa77f0f62012-12-05 17:19:31 -08002204 MutexLock mu(soa.Self(), *Locks::thread_list_lock_);
Elliott Hughes221229c2013-01-08 18:17:50 -08002205 Thread* thread;
2206 JDWP::JdwpError error = DecodeThread(soa, thread_id, thread);
2207 if (error != JDWP::ERR_NONE) {
2208 return;
2209 }
Elliott Hughes08fc03a2012-06-26 17:34:00 -07002210 UniquePtr<Context> context(Context::Create());
Ian Rogers7a22fa62013-01-23 12:16:16 -08002211 SetLocalVisitor visitor(thread, context.get(), frame_id, slot, tag, value, width);
Ian Rogers0399dde2012-06-06 17:09:28 -07002212 visitor.WalkStack();
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002213}
2214
Brian Carlstromea46f952013-07-30 01:26:50 -07002215void Dbg::PostLocationEvent(const mirror::ArtMethod* m, int dex_pc,
Ian Rogers62d6c772013-02-27 08:32:07 -08002216 mirror::Object* this_object, int event_flags) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002217 mirror::Class* c = m->GetDeclaringClass();
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08002218
2219 JDWP::JdwpLocation location;
Elliott Hughes74847412012-06-20 18:10:21 -07002220 location.type_tag = c->IsInterface() ? JDWP::TT_INTERFACE : JDWP::TT_CLASS;
Elliott Hughes64f574f2013-02-20 14:57:12 -08002221 location.class_id = gRegistry->AddRefType(c);
Elliott Hughes74847412012-06-20 18:10:21 -07002222 location.method_id = ToMethodId(m);
Elliott Hughes972a47b2012-02-21 18:16:06 -08002223 location.dex_pc = m->IsNative() ? -1 : dex_pc;
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08002224
Elliott Hughes64f574f2013-02-20 14:57:12 -08002225 // If 'this_object' isn't already in the registry, we know that we're not looking for it,
2226 // so there's no point adding it to the registry and burning through ids.
2227 JDWP::ObjectId this_id = 0;
2228 if (gRegistry->Contains(this_object)) {
2229 this_id = gRegistry->Add(this_object);
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08002230 }
Elliott Hughes64f574f2013-02-20 14:57:12 -08002231 gJdwpState->PostLocationEvent(&location, this_id, event_flags);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002232}
2233
Ian Rogers62d6c772013-02-27 08:32:07 -08002234void Dbg::PostException(Thread* thread, const ThrowLocation& throw_location,
Brian Carlstromea46f952013-07-30 01:26:50 -07002235 mirror::ArtMethod* catch_method,
Elliott Hughes64f574f2013-02-20 14:57:12 -08002236 uint32_t catch_dex_pc, mirror::Throwable* exception_object) {
Elliott Hughesc0f09332012-03-26 13:27:06 -07002237 if (!IsDebuggerActive()) {
Ian Rogers0ad5bb82011-12-07 10:16:32 -08002238 return;
2239 }
Elliott Hughes4740cdf2011-12-07 14:07:12 -08002240
Ian Rogers62d6c772013-02-27 08:32:07 -08002241 JDWP::JdwpLocation jdwp_throw_location;
2242 SetLocation(jdwp_throw_location, throw_location.GetMethod(), throw_location.GetDexPc());
Elliott Hughesd07986f2011-12-06 18:27:45 -08002243 JDWP::JdwpLocation catch_location;
Elliott Hughescaf76542012-06-28 16:08:22 -07002244 SetLocation(catch_location, catch_method, catch_dex_pc);
Elliott Hughesd07986f2011-12-06 18:27:45 -08002245
2246 // We need 'this' for InstanceOnly filters.
Ian Rogers62d6c772013-02-27 08:32:07 -08002247 JDWP::ObjectId this_id = gRegistry->Add(throw_location.GetThis());
Elliott Hughes64f574f2013-02-20 14:57:12 -08002248 JDWP::ObjectId exception_id = gRegistry->Add(exception_object);
2249 JDWP::RefTypeId exception_class_id = gRegistry->AddRefType(exception_object->GetClass());
Elliott Hughesd07986f2011-12-06 18:27:45 -08002250
Ian Rogers62d6c772013-02-27 08:32:07 -08002251 gJdwpState->PostException(&jdwp_throw_location, exception_id, exception_class_id, &catch_location,
2252 this_id);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002253}
2254
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002255void Dbg::PostClassPrepare(mirror::Class* c) {
Elliott Hughesc0f09332012-03-26 13:27:06 -07002256 if (!IsDebuggerActive()) {
Elliott Hughes4740cdf2011-12-07 14:07:12 -08002257 return;
2258 }
2259
Elliott Hughes3d30d9b2011-12-07 17:35:48 -08002260 // OLD-TODO - we currently always send both "verified" and "prepared" since
Elliott Hughes4740cdf2011-12-07 14:07:12 -08002261 // debuggers seem to like that. There might be some advantage to honesty,
2262 // since the class may not yet be verified.
2263 int state = JDWP::CS_VERIFIED | JDWP::CS_PREPARED;
2264 JDWP::JdwpTypeTag tag = c->IsInterface() ? JDWP::TT_INTERFACE : JDWP::TT_CLASS;
Ian Rogersfc0e94b2013-09-23 23:51:32 -07002265 gJdwpState->PostClassPrepare(tag, gRegistry->Add(c),
Ian Rogersdfb325e2013-10-30 01:00:44 -07002266 ClassHelper(c).GetDescriptor(), state);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002267}
2268
Ian Rogers62d6c772013-02-27 08:32:07 -08002269void Dbg::UpdateDebugger(Thread* thread, mirror::Object* this_object,
Brian Carlstromea46f952013-07-30 01:26:50 -07002270 const mirror::ArtMethod* m, uint32_t dex_pc) {
Ian Rogers62d6c772013-02-27 08:32:07 -08002271 if (!IsDebuggerActive() || dex_pc == static_cast<uint32_t>(-2) /* fake method exit */) {
Elliott Hughes2aa2e392012-02-17 17:15:43 -08002272 return;
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08002273 }
2274
Elliott Hughes2aa2e392012-02-17 17:15:43 -08002275 int event_flags = 0;
2276
Elliott Hughes86964332012-02-15 19:37:42 -08002277 if (IsBreakpoint(m, dex_pc)) {
2278 event_flags |= kBreakpoint;
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08002279 }
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08002280
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01002281 // If the debugger is single-stepping one of our threads, check to
2282 // see if we're that thread and we've reached a step point.
2283 const SingleStepControl* single_step_control = thread->GetSingleStepControl();
2284 DCHECK(single_step_control != nullptr);
2285 if (single_step_control->is_active) {
2286 CHECK(!m->IsNative());
2287 if (single_step_control->step_depth == JDWP::SD_INTO) {
2288 // Step into method calls. We break when the line number
2289 // or method pointer changes. If we're in SS_MIN mode, we
2290 // always stop.
2291 if (single_step_control->method != m) {
2292 event_flags |= kSingleStep;
2293 VLOG(jdwp) << "SS new method";
2294 } else if (single_step_control->step_size == JDWP::SS_MIN) {
2295 event_flags |= kSingleStep;
2296 VLOG(jdwp) << "SS new instruction";
2297 } else if (single_step_control->dex_pcs.find(dex_pc) == single_step_control->dex_pcs.end()) {
2298 event_flags |= kSingleStep;
2299 VLOG(jdwp) << "SS new line";
2300 }
2301 } else if (single_step_control->step_depth == JDWP::SD_OVER) {
2302 // Step over method calls. We break when the line number is
2303 // different and the frame depth is <= the original frame
2304 // depth. (We can't just compare on the method, because we
2305 // might get unrolled past it by an exception, and it's tricky
2306 // to identify recursion.)
2307
2308 int stack_depth = GetStackDepth(thread);
2309
2310 if (stack_depth < single_step_control->stack_depth) {
2311 // Popped up one or more frames, always trigger.
2312 event_flags |= kSingleStep;
2313 VLOG(jdwp) << "SS method pop";
2314 } else if (stack_depth == single_step_control->stack_depth) {
2315 // Same depth, see if we moved.
2316 if (single_step_control->step_size == JDWP::SS_MIN) {
Elliott Hughes86964332012-02-15 19:37:42 -08002317 event_flags |= kSingleStep;
2318 VLOG(jdwp) << "SS new instruction";
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01002319 } else if (single_step_control->dex_pcs.find(dex_pc) == single_step_control->dex_pcs.end()) {
Elliott Hughes2435a572012-02-17 16:07:41 -08002320 event_flags |= kSingleStep;
2321 VLOG(jdwp) << "SS new line";
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08002322 }
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01002323 }
2324 } else {
2325 CHECK_EQ(single_step_control->step_depth, JDWP::SD_OUT);
2326 // Return from the current method. We break when the frame
2327 // depth pops up.
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08002328
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01002329 // This differs from the "method exit" break in that it stops
2330 // with the PC at the next instruction in the returned-to
2331 // function, rather than the end of the returning function.
Elliott Hughes86964332012-02-15 19:37:42 -08002332
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01002333 int stack_depth = GetStackDepth(thread);
2334 if (stack_depth < single_step_control->stack_depth) {
2335 event_flags |= kSingleStep;
2336 VLOG(jdwp) << "SS method pop";
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08002337 }
2338 }
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08002339 }
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08002340
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08002341 // If there's something interesting going on, see if it matches one
2342 // of the debugger filters.
2343 if (event_flags != 0) {
Ian Rogers62d6c772013-02-27 08:32:07 -08002344 Dbg::PostLocationEvent(m, dex_pc, this_object, event_flags);
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08002345 }
2346}
2347
Elliott Hughes86964332012-02-15 19:37:42 -08002348void Dbg::WatchLocation(const JDWP::JdwpLocation* location) {
jeffhao09bfc6a2012-12-11 18:11:43 -08002349 MutexLock mu(Thread::Current(), *Locks::breakpoint_lock_);
Brian Carlstromea46f952013-07-30 01:26:50 -07002350 mirror::ArtMethod* m = FromMethodId(location->method_id);
Elliott Hughes972a47b2012-02-21 18:16:06 -08002351 gBreakpoints.push_back(Breakpoint(m, location->dex_pc));
Elliott Hughes86964332012-02-15 19:37:42 -08002352 VLOG(jdwp) << "Set breakpoint #" << (gBreakpoints.size() - 1) << ": " << gBreakpoints[gBreakpoints.size() - 1];
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002353}
2354
Elliott Hughes86964332012-02-15 19:37:42 -08002355void Dbg::UnwatchLocation(const JDWP::JdwpLocation* location) {
jeffhao09bfc6a2012-12-11 18:11:43 -08002356 MutexLock mu(Thread::Current(), *Locks::breakpoint_lock_);
Brian Carlstromea46f952013-07-30 01:26:50 -07002357 mirror::ArtMethod* m = FromMethodId(location->method_id);
Elliott Hughes86964332012-02-15 19:37:42 -08002358 for (size_t i = 0; i < gBreakpoints.size(); ++i) {
Elliott Hughes972a47b2012-02-21 18:16:06 -08002359 if (gBreakpoints[i].method == m && gBreakpoints[i].dex_pc == location->dex_pc) {
Elliott Hughes86964332012-02-15 19:37:42 -08002360 VLOG(jdwp) << "Removed breakpoint #" << i << ": " << gBreakpoints[i];
2361 gBreakpoints.erase(gBreakpoints.begin() + i);
2362 return;
2363 }
2364 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002365}
2366
Jeff Hao449db332013-04-12 18:30:52 -07002367// Scoped utility class to suspend a thread so that we may do tasks such as walk its stack. Doesn't
2368// cause suspension if the thread is the current thread.
2369class ScopedThreadSuspension {
2370 public:
Ian Rogers33e95662013-05-20 20:29:14 -07002371 ScopedThreadSuspension(Thread* self, JDWP::ObjectId thread_id)
2372 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) :
Jeff Hao449db332013-04-12 18:30:52 -07002373 thread_(NULL),
2374 error_(JDWP::ERR_NONE),
2375 self_suspend_(false),
Ian Rogers33e95662013-05-20 20:29:14 -07002376 other_suspend_(false) {
Jeff Hao449db332013-04-12 18:30:52 -07002377 ScopedObjectAccessUnchecked soa(self);
2378 {
2379 MutexLock mu(soa.Self(), *Locks::thread_list_lock_);
2380 error_ = DecodeThread(soa, thread_id, thread_);
2381 }
2382 if (error_ == JDWP::ERR_NONE) {
2383 if (thread_ == soa.Self()) {
2384 self_suspend_ = true;
2385 } else {
2386 soa.Self()->TransitionFromRunnableToSuspended(kWaitingForDebuggerSuspension);
2387 jobject thread_peer = gRegistry->GetJObject(thread_id);
2388 bool timed_out;
Ian Rogersd9c4fc92013-10-01 19:45:43 -07002389 Thread* suspended_thread = ThreadList::SuspendThreadByPeer(thread_peer, true, true,
2390 &timed_out);
Jeff Hao449db332013-04-12 18:30:52 -07002391 CHECK_EQ(soa.Self()->TransitionFromSuspendedToRunnable(), kWaitingForDebuggerSuspension);
2392 if (suspended_thread == NULL) {
2393 // Thread terminated from under us while suspending.
2394 error_ = JDWP::ERR_INVALID_THREAD;
2395 } else {
2396 CHECK_EQ(suspended_thread, thread_);
2397 other_suspend_ = true;
2398 }
2399 }
2400 }
Elliott Hughes2435a572012-02-17 16:07:41 -08002401 }
Elliott Hughes86964332012-02-15 19:37:42 -08002402
Jeff Hao449db332013-04-12 18:30:52 -07002403 Thread* GetThread() const {
2404 return thread_;
2405 }
2406
2407 JDWP::JdwpError GetError() const {
2408 return error_;
2409 }
2410
2411 ~ScopedThreadSuspension() {
2412 if (other_suspend_) {
2413 Runtime::Current()->GetThreadList()->Resume(thread_, true);
2414 }
2415 }
2416
2417 private:
2418 Thread* thread_;
2419 JDWP::JdwpError error_;
2420 bool self_suspend_;
2421 bool other_suspend_;
2422};
2423
2424JDWP::JdwpError Dbg::ConfigureStep(JDWP::ObjectId thread_id, JDWP::JdwpStepSize step_size,
2425 JDWP::JdwpStepDepth step_depth) {
2426 Thread* self = Thread::Current();
2427 ScopedThreadSuspension sts(self, thread_id);
2428 if (sts.GetError() != JDWP::ERR_NONE) {
2429 return sts.GetError();
2430 }
2431
Elliott Hughes2435a572012-02-17 16:07:41 -08002432 //
2433 // Work out what Method* we're in, the current line number, and how deep the stack currently
2434 // is for step-out.
2435 //
2436
Ian Rogers0399dde2012-06-06 17:09:28 -07002437 struct SingleStepStackVisitor : public StackVisitor {
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01002438 explicit SingleStepStackVisitor(Thread* thread, SingleStepControl* single_step_control,
2439 int32_t* line_number)
Ian Rogersb726dcb2012-09-05 08:57:23 -07002440 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_)
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01002441 : StackVisitor(thread, NULL), single_step_control_(single_step_control),
2442 line_number_(line_number) {
2443 DCHECK_EQ(single_step_control_, thread->GetSingleStepControl());
2444 single_step_control_->method = NULL;
2445 single_step_control_->stack_depth = 0;
Elliott Hughes86964332012-02-15 19:37:42 -08002446 }
Ian Rogersca190662012-06-26 15:45:57 -07002447
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002448 // TODO: Enable annotalysis. We know lock is held in constructor, but abstraction confuses
2449 // annotalysis.
2450 bool VisitFrame() NO_THREAD_SAFETY_ANALYSIS {
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01002451 mirror::ArtMethod* m = GetMethod();
Ian Rogers0399dde2012-06-06 17:09:28 -07002452 if (!m->IsRuntimeMethod()) {
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01002453 ++single_step_control_->stack_depth;
2454 if (single_step_control_->method == NULL) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002455 const mirror::DexCache* dex_cache = m->GetDeclaringClass()->GetDexCache();
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01002456 single_step_control_->method = m;
2457 *line_number_ = -1;
Elliott Hughes2435a572012-02-17 16:07:41 -08002458 if (dex_cache != NULL) {
Ian Rogers4445a7e2012-10-05 17:19:13 -07002459 const DexFile& dex_file = *dex_cache->GetDexFile();
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01002460 *line_number_ = dex_file.GetLineNumFromPC(m, GetDexPc());
Elliott Hughes2435a572012-02-17 16:07:41 -08002461 }
Elliott Hughes86964332012-02-15 19:37:42 -08002462 }
2463 }
Elliott Hughes530fa002012-03-12 11:44:49 -07002464 return true;
Elliott Hughes86964332012-02-15 19:37:42 -08002465 }
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01002466
2467 SingleStepControl* const single_step_control_;
2468 int32_t* const line_number_;
Elliott Hughes86964332012-02-15 19:37:42 -08002469 };
Jeff Hao449db332013-04-12 18:30:52 -07002470
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01002471 Thread* const thread = sts.GetThread();
2472 SingleStepControl* const single_step_control = thread->GetSingleStepControl();
2473 DCHECK(single_step_control != nullptr);
2474 int32_t line_number = -1;
2475 SingleStepStackVisitor visitor(thread, single_step_control, &line_number);
Ian Rogers0399dde2012-06-06 17:09:28 -07002476 visitor.WalkStack();
Elliott Hughes86964332012-02-15 19:37:42 -08002477
Elliott Hughes2435a572012-02-17 16:07:41 -08002478 //
2479 // Find the dex_pc values that correspond to the current line, for line-based single-stepping.
2480 //
2481
2482 struct DebugCallbackContext {
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01002483 explicit DebugCallbackContext(SingleStepControl* single_step_control, int32_t line_number)
2484 : single_step_control_(single_step_control), line_number_(line_number),
2485 last_pc_valid(false), last_pc(0) {
Elliott Hughes2435a572012-02-17 16:07:41 -08002486 }
2487
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01002488 static bool Callback(void* raw_context, uint32_t address, uint32_t line_number) {
Elliott Hughes2435a572012-02-17 16:07:41 -08002489 DebugCallbackContext* context = reinterpret_cast<DebugCallbackContext*>(raw_context);
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01002490 if (static_cast<int32_t>(line_number) == context->line_number_) {
Elliott Hughes2435a572012-02-17 16:07:41 -08002491 if (!context->last_pc_valid) {
2492 // Everything from this address until the next line change is ours.
2493 context->last_pc = address;
2494 context->last_pc_valid = true;
2495 }
2496 // Otherwise, if we're already in a valid range for this line,
2497 // just keep going (shouldn't really happen)...
Brian Carlstrom7934ac22013-07-26 10:54:15 -07002498 } else if (context->last_pc_valid) { // and the line number is new
Elliott Hughes2435a572012-02-17 16:07:41 -08002499 // Add everything from the last entry up until here to the set
2500 for (uint32_t dex_pc = context->last_pc; dex_pc < address; ++dex_pc) {
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01002501 context->single_step_control_->dex_pcs.insert(dex_pc);
Elliott Hughes2435a572012-02-17 16:07:41 -08002502 }
2503 context->last_pc_valid = false;
2504 }
Brian Carlstrom7934ac22013-07-26 10:54:15 -07002505 return false; // There may be multiple entries for any given line.
Elliott Hughes2435a572012-02-17 16:07:41 -08002506 }
2507
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01002508 ~DebugCallbackContext() {
Elliott Hughes2435a572012-02-17 16:07:41 -08002509 // If the line number was the last in the position table...
2510 if (last_pc_valid) {
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01002511 size_t end = MethodHelper(single_step_control_->method).GetCodeItem()->insns_size_in_code_units_;
Elliott Hughes2435a572012-02-17 16:07:41 -08002512 for (uint32_t dex_pc = last_pc; dex_pc < end; ++dex_pc) {
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01002513 single_step_control_->dex_pcs.insert(dex_pc);
Elliott Hughes2435a572012-02-17 16:07:41 -08002514 }
2515 }
2516 }
2517
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01002518 SingleStepControl* const single_step_control_;
2519 const int32_t line_number_;
Elliott Hughes2435a572012-02-17 16:07:41 -08002520 bool last_pc_valid;
2521 uint32_t last_pc;
2522 };
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01002523 single_step_control->dex_pcs.clear();
2524 const mirror::ArtMethod* m = single_step_control->method;
2525 if (!m->IsNative()) {
2526 DebugCallbackContext context(single_step_control, line_number);
Elliott Hughes3e2e1a22012-02-21 11:33:41 -08002527 MethodHelper mh(m);
2528 mh.GetDexFile().DecodeDebugInfo(mh.GetCodeItem(), m->IsStatic(), m->GetDexMethodIndex(),
2529 DebugCallbackContext::Callback, NULL, &context);
2530 }
Elliott Hughes2435a572012-02-17 16:07:41 -08002531
2532 //
2533 // Everything else...
2534 //
2535
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01002536 single_step_control->step_size = step_size;
2537 single_step_control->step_depth = step_depth;
2538 single_step_control->is_active = true;
Elliott Hughes86964332012-02-15 19:37:42 -08002539
Elliott Hughes2435a572012-02-17 16:07:41 -08002540 if (VLOG_IS_ON(jdwp)) {
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01002541 VLOG(jdwp) << "Single-step thread: " << *thread;
2542 VLOG(jdwp) << "Single-step step size: " << single_step_control->step_size;
2543 VLOG(jdwp) << "Single-step step depth: " << single_step_control->step_depth;
2544 VLOG(jdwp) << "Single-step current method: " << PrettyMethod(single_step_control->method);
2545 VLOG(jdwp) << "Single-step current line: " << line_number;
2546 VLOG(jdwp) << "Single-step current stack depth: " << single_step_control->stack_depth;
Elliott Hughes2435a572012-02-17 16:07:41 -08002547 VLOG(jdwp) << "Single-step dex_pc values:";
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01002548 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 -08002549 VLOG(jdwp) << StringPrintf(" %#x", *it);
Elliott Hughes2435a572012-02-17 16:07:41 -08002550 }
2551 }
2552
2553 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002554}
2555
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01002556void Dbg::UnconfigureStep(JDWP::ObjectId thread_id) {
2557 ScopedObjectAccessUnchecked soa(Thread::Current());
2558 MutexLock mu(soa.Self(), *Locks::thread_list_lock_);
2559 Thread* thread;
2560 JDWP::JdwpError error = DecodeThread(soa, thread_id, thread);
2561 if (error != JDWP::ERR_NONE) {
2562 SingleStepControl* single_step_control = thread->GetSingleStepControl();
2563 DCHECK(single_step_control != nullptr);
2564 single_step_control->is_active = false;
2565 single_step_control->dex_pcs.clear();
2566 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002567}
2568
Elliott Hughes45651fd2012-02-21 15:48:20 -08002569static char JdwpTagToShortyChar(JDWP::JdwpTag tag) {
2570 switch (tag) {
2571 default:
2572 LOG(FATAL) << "unknown JDWP tag: " << PrintableChar(tag);
2573
2574 // Primitives.
2575 case JDWP::JT_BYTE: return 'B';
2576 case JDWP::JT_CHAR: return 'C';
2577 case JDWP::JT_FLOAT: return 'F';
2578 case JDWP::JT_DOUBLE: return 'D';
2579 case JDWP::JT_INT: return 'I';
2580 case JDWP::JT_LONG: return 'J';
2581 case JDWP::JT_SHORT: return 'S';
2582 case JDWP::JT_VOID: return 'V';
2583 case JDWP::JT_BOOLEAN: return 'Z';
2584
2585 // Reference types.
2586 case JDWP::JT_ARRAY:
2587 case JDWP::JT_OBJECT:
2588 case JDWP::JT_STRING:
2589 case JDWP::JT_THREAD:
2590 case JDWP::JT_THREAD_GROUP:
2591 case JDWP::JT_CLASS_LOADER:
2592 case JDWP::JT_CLASS_OBJECT:
2593 return 'L';
2594 }
2595}
2596
Elliott Hughes88d63092013-01-09 09:55:54 -08002597JDWP::JdwpError Dbg::InvokeMethod(JDWP::ObjectId thread_id, JDWP::ObjectId object_id,
2598 JDWP::RefTypeId class_id, JDWP::MethodId method_id,
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002599 uint32_t arg_count, uint64_t* arg_values,
2600 JDWP::JdwpTag* arg_types, uint32_t options,
2601 JDWP::JdwpTag* pResultTag, uint64_t* pResultValue,
2602 JDWP::ObjectId* pExceptionId) {
Elliott Hughesd07986f2011-12-06 18:27:45 -08002603 ThreadList* thread_list = Runtime::Current()->GetThreadList();
2604
2605 Thread* targetThread = NULL;
2606 DebugInvokeReq* req = NULL;
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002607 Thread* self = Thread::Current();
Elliott Hughesd07986f2011-12-06 18:27:45 -08002608 {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002609 ScopedObjectAccessUnchecked soa(self);
Ian Rogers50b35e22012-10-04 10:09:15 -07002610 MutexLock mu(soa.Self(), *Locks::thread_list_lock_);
Elliott Hughes221229c2013-01-08 18:17:50 -08002611 JDWP::JdwpError error = DecodeThread(soa, thread_id, targetThread);
2612 if (error != JDWP::ERR_NONE) {
2613 LOG(ERROR) << "InvokeMethod request for invalid thread id " << thread_id;
2614 return error;
Elliott Hughesd07986f2011-12-06 18:27:45 -08002615 }
2616 req = targetThread->GetInvokeReq();
2617 if (!req->ready) {
2618 LOG(ERROR) << "InvokeMethod request for thread not stopped by event: " << *targetThread;
2619 return JDWP::ERR_INVALID_THREAD;
2620 }
2621
2622 /*
2623 * We currently have a bug where we don't successfully resume the
2624 * target thread if the suspend count is too deep. We're expected to
2625 * require one "resume" for each "suspend", but when asked to execute
2626 * a method we have to resume fully and then re-suspend it back to the
2627 * same level. (The easiest way to cause this is to type "suspend"
2628 * multiple times in jdb.)
2629 *
2630 * It's unclear what this means when the event specifies "resume all"
2631 * and some threads are suspended more deeply than others. This is
2632 * a rare problem, so for now we just prevent it from hanging forever
2633 * by rejecting the method invocation request. Without this, we will
2634 * be stuck waiting on a suspended thread.
2635 */
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002636 int suspend_count;
2637 {
Ian Rogers50b35e22012-10-04 10:09:15 -07002638 MutexLock mu2(soa.Self(), *Locks::thread_suspend_count_lock_);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002639 suspend_count = targetThread->GetSuspendCount();
2640 }
Elliott Hughesd07986f2011-12-06 18:27:45 -08002641 if (suspend_count > 1) {
2642 LOG(ERROR) << *targetThread << " suspend count too deep for method invocation: " << suspend_count;
Brian Carlstrom7934ac22013-07-26 10:54:15 -07002643 return JDWP::ERR_THREAD_SUSPENDED; // Probably not expected here.
Elliott Hughesd07986f2011-12-06 18:27:45 -08002644 }
2645
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08002646 JDWP::JdwpError status;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002647 mirror::Object* receiver = gRegistry->Get<mirror::Object*>(object_id);
Elliott Hughes64f574f2013-02-20 14:57:12 -08002648 if (receiver == ObjectRegistry::kInvalidObject) {
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08002649 return JDWP::ERR_INVALID_OBJECT;
2650 }
Elliott Hughes45651fd2012-02-21 15:48:20 -08002651
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002652 mirror::Object* thread = gRegistry->Get<mirror::Object*>(thread_id);
Elliott Hughes64f574f2013-02-20 14:57:12 -08002653 if (thread == ObjectRegistry::kInvalidObject) {
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08002654 return JDWP::ERR_INVALID_OBJECT;
2655 }
Elliott Hughes45651fd2012-02-21 15:48:20 -08002656 // TODO: check that 'thread' is actually a java.lang.Thread!
2657
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002658 mirror::Class* c = DecodeClass(class_id, status);
Elliott Hughes45651fd2012-02-21 15:48:20 -08002659 if (c == NULL) {
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08002660 return status;
2661 }
Elliott Hughes45651fd2012-02-21 15:48:20 -08002662
Brian Carlstromea46f952013-07-30 01:26:50 -07002663 mirror::ArtMethod* m = FromMethodId(method_id);
Elliott Hughes45651fd2012-02-21 15:48:20 -08002664 if (m->IsStatic() != (receiver == NULL)) {
2665 return JDWP::ERR_INVALID_METHODID;
2666 }
2667 if (m->IsStatic()) {
2668 if (m->GetDeclaringClass() != c) {
2669 return JDWP::ERR_INVALID_METHODID;
2670 }
2671 } else {
2672 if (!m->GetDeclaringClass()->IsAssignableFrom(c)) {
2673 return JDWP::ERR_INVALID_METHODID;
2674 }
2675 }
2676
2677 // Check the argument list matches the method.
2678 MethodHelper mh(m);
2679 if (mh.GetShortyLength() - 1 != arg_count) {
2680 return JDWP::ERR_ILLEGAL_ARGUMENT;
2681 }
2682 const char* shorty = mh.GetShorty();
Elliott Hughes09201632013-04-15 15:50:07 -07002683 const DexFile::TypeList* types = mh.GetParameterTypeList();
Elliott Hughes45651fd2012-02-21 15:48:20 -08002684 for (size_t i = 0; i < arg_count; ++i) {
2685 if (shorty[i + 1] != JdwpTagToShortyChar(arg_types[i])) {
2686 return JDWP::ERR_ILLEGAL_ARGUMENT;
2687 }
Elliott Hughes09201632013-04-15 15:50:07 -07002688
2689 if (shorty[i + 1] == 'L') {
2690 // Did we really get an argument of an appropriate reference type?
2691 mirror::Class* parameter_type = mh.GetClassFromTypeIdx(types->GetTypeItem(i).type_idx_);
2692 mirror::Object* argument = gRegistry->Get<mirror::Object*>(arg_values[i]);
2693 if (argument == ObjectRegistry::kInvalidObject) {
2694 return JDWP::ERR_INVALID_OBJECT;
2695 }
2696 if (!argument->InstanceOf(parameter_type)) {
2697 return JDWP::ERR_ILLEGAL_ARGUMENT;
2698 }
2699
2700 // Turn the on-the-wire ObjectId into a jobject.
2701 jvalue& v = reinterpret_cast<jvalue&>(arg_values[i]);
2702 v.l = gRegistry->GetJObject(arg_values[i]);
2703 }
Elliott Hughes45651fd2012-02-21 15:48:20 -08002704 }
2705
2706 req->receiver_ = receiver;
2707 req->thread_ = thread;
2708 req->class_ = c;
2709 req->method_ = m;
2710 req->arg_count_ = arg_count;
2711 req->arg_values_ = arg_values;
Elliott Hughesd07986f2011-12-06 18:27:45 -08002712 req->options_ = options;
2713 req->invoke_needed_ = true;
2714 }
2715
2716 // The fact that we've released the thread list lock is a bit risky --- if the thread goes
2717 // away we're sitting high and dry -- but we must release this before the ResumeAllThreads
2718 // call, and it's unwise to hold it during WaitForSuspend.
2719
2720 {
2721 /*
2722 * We change our (JDWP thread) status, which should be THREAD_RUNNING,
Elliott Hughes81ff3182012-03-23 20:35:56 -07002723 * so we can suspend for a GC if the invoke request causes us to
Elliott Hughesd07986f2011-12-06 18:27:45 -08002724 * run out of memory. It's also a good idea to change it before locking
2725 * the invokeReq mutex, although that should never be held for long.
2726 */
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002727 self->TransitionFromRunnableToSuspended(kWaitingForDebuggerSend);
Elliott Hughesd07986f2011-12-06 18:27:45 -08002728
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08002729 VLOG(jdwp) << " Transferring control to event thread";
Elliott Hughesd07986f2011-12-06 18:27:45 -08002730 {
Ian Rogers50b35e22012-10-04 10:09:15 -07002731 MutexLock mu(self, req->lock_);
Elliott Hughesd07986f2011-12-06 18:27:45 -08002732
2733 if ((options & JDWP::INVOKE_SINGLE_THREADED) == 0) {
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08002734 VLOG(jdwp) << " Resuming all threads";
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002735 thread_list->UndoDebuggerSuspensions();
Elliott Hughesd07986f2011-12-06 18:27:45 -08002736 } else {
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08002737 VLOG(jdwp) << " Resuming event thread only";
Elliott Hughesd07986f2011-12-06 18:27:45 -08002738 thread_list->Resume(targetThread, true);
2739 }
2740
2741 // Wait for the request to finish executing.
2742 while (req->invoke_needed_) {
Ian Rogersc604d732012-10-14 16:09:54 -07002743 req->cond_.Wait(self);
Elliott Hughesd07986f2011-12-06 18:27:45 -08002744 }
2745 }
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08002746 VLOG(jdwp) << " Control has returned from event thread";
Elliott Hughesd07986f2011-12-06 18:27:45 -08002747
2748 /* wait for thread to re-suspend itself */
Brian Carlstromdf629502013-07-17 22:39:56 -07002749 SuspendThread(thread_id, false /* request_suspension */);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002750 self->TransitionFromSuspendedToRunnable();
Elliott Hughesd07986f2011-12-06 18:27:45 -08002751 }
2752
2753 /*
2754 * Suspend the threads. We waited for the target thread to suspend
2755 * itself, so all we need to do is suspend the others.
2756 *
2757 * The suspendAllThreads() call will double-suspend the event thread,
2758 * so we want to resume the target thread once to keep the books straight.
2759 */
2760 if ((options & JDWP::INVOKE_SINGLE_THREADED) == 0) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002761 self->TransitionFromRunnableToSuspended(kWaitingForDebuggerSuspension);
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08002762 VLOG(jdwp) << " Suspending all threads";
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002763 thread_list->SuspendAllForDebugger();
2764 self->TransitionFromSuspendedToRunnable();
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08002765 VLOG(jdwp) << " Resuming event thread to balance the count";
Elliott Hughesd07986f2011-12-06 18:27:45 -08002766 thread_list->Resume(targetThread, true);
2767 }
2768
2769 // Copy the result.
2770 *pResultTag = req->result_tag;
2771 if (IsPrimitiveTag(req->result_tag)) {
Elliott Hughesf24d3ce2012-04-11 17:43:37 -07002772 *pResultValue = req->result_value.GetJ();
Elliott Hughesd07986f2011-12-06 18:27:45 -08002773 } else {
Elliott Hughesf24d3ce2012-04-11 17:43:37 -07002774 *pResultValue = gRegistry->Add(req->result_value.GetL());
Elliott Hughesd07986f2011-12-06 18:27:45 -08002775 }
2776 *pExceptionId = req->exception;
2777 return req->error;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002778}
2779
2780void Dbg::ExecuteMethod(DebugInvokeReq* pReq) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002781 ScopedObjectAccess soa(Thread::Current());
Elliott Hughesd07986f2011-12-06 18:27:45 -08002782
Elliott Hughes81ff3182012-03-23 20:35:56 -07002783 // We can be called while an exception is pending. We need
Elliott Hughesd07986f2011-12-06 18:27:45 -08002784 // to preserve that across the method invocation.
Ian Rogers62d6c772013-02-27 08:32:07 -08002785 SirtRef<mirror::Object> old_throw_this_object(soa.Self(), NULL);
Brian Carlstromea46f952013-07-30 01:26:50 -07002786 SirtRef<mirror::ArtMethod> old_throw_method(soa.Self(), NULL);
Ian Rogers62d6c772013-02-27 08:32:07 -08002787 SirtRef<mirror::Throwable> old_exception(soa.Self(), NULL);
2788 uint32_t old_throw_dex_pc;
2789 {
2790 ThrowLocation old_throw_location;
2791 mirror::Throwable* old_exception_obj = soa.Self()->GetException(&old_throw_location);
2792 old_throw_this_object.reset(old_throw_location.GetThis());
2793 old_throw_method.reset(old_throw_location.GetMethod());
2794 old_exception.reset(old_exception_obj);
2795 old_throw_dex_pc = old_throw_location.GetDexPc();
2796 soa.Self()->ClearException();
2797 }
Elliott Hughesd07986f2011-12-06 18:27:45 -08002798
2799 // Translate the method through the vtable, unless the debugger wants to suppress it.
Brian Carlstromea46f952013-07-30 01:26:50 -07002800 mirror::ArtMethod* m = pReq->method_;
Elliott Hughesd07986f2011-12-06 18:27:45 -08002801 if ((pReq->options_ & JDWP::INVOKE_NONVIRTUAL) == 0 && pReq->receiver_ != NULL) {
Brian Carlstromea46f952013-07-30 01:26:50 -07002802 mirror::ArtMethod* actual_method = pReq->class_->FindVirtualMethodForVirtualOrInterface(pReq->method_);
Elliott Hughes45651fd2012-02-21 15:48:20 -08002803 if (actual_method != m) {
2804 VLOG(jdwp) << "ExecuteMethod translated " << PrettyMethod(m) << " to " << PrettyMethod(actual_method);
2805 m = actual_method;
2806 }
Elliott Hughesd07986f2011-12-06 18:27:45 -08002807 }
Elliott Hughescfa9cfa2013-04-16 16:52:01 -07002808 VLOG(jdwp) << "ExecuteMethod " << PrettyMethod(m)
2809 << " receiver=" << pReq->receiver_
2810 << " arg_count=" << pReq->arg_count_;
Elliott Hughesd07986f2011-12-06 18:27:45 -08002811 CHECK(m != NULL);
2812
2813 CHECK_EQ(sizeof(jvalue), sizeof(uint64_t));
2814
Jeff Hao5d917302013-02-27 17:57:33 -08002815 MethodHelper mh(m);
2816 ArgArray arg_array(mh.GetShorty(), mh.GetShortyLength());
2817 arg_array.BuildArgArray(soa, pReq->receiver_, reinterpret_cast<jvalue*>(pReq->arg_values_));
Jeff Hao6474d192013-03-26 14:08:09 -07002818 InvokeWithArgArray(soa, m, &arg_array, &pReq->result_value, mh.GetShorty()[0]);
Elliott Hughesd07986f2011-12-06 18:27:45 -08002819
Ian Rogers62d6c772013-02-27 08:32:07 -08002820 mirror::Throwable* exception = soa.Self()->GetException(NULL);
2821 soa.Self()->ClearException();
2822 pReq->exception = gRegistry->Add(exception);
Elliott Hughesd07986f2011-12-06 18:27:45 -08002823 pReq->result_tag = BasicTagFromDescriptor(MethodHelper(m).GetShorty());
2824 if (pReq->exception != 0) {
Ian Rogers62d6c772013-02-27 08:32:07 -08002825 VLOG(jdwp) << " JDWP invocation returning with exception=" << exception
2826 << " " << exception->Dump();
Elliott Hughesf24d3ce2012-04-11 17:43:37 -07002827 pReq->result_value.SetJ(0);
Elliott Hughesd07986f2011-12-06 18:27:45 -08002828 } else if (pReq->result_tag == JDWP::JT_OBJECT) {
2829 /* if no exception thrown, examine object result more closely */
Elliott Hughesf24d3ce2012-04-11 17:43:37 -07002830 JDWP::JdwpTag new_tag = TagFromObject(pReq->result_value.GetL());
Elliott Hughesd07986f2011-12-06 18:27:45 -08002831 if (new_tag != pReq->result_tag) {
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08002832 VLOG(jdwp) << " JDWP promoted result from " << pReq->result_tag << " to " << new_tag;
Elliott Hughesd07986f2011-12-06 18:27:45 -08002833 pReq->result_tag = new_tag;
2834 }
2835
2836 /*
2837 * Register the object. We don't actually need an ObjectId yet,
2838 * but we do need to be sure that the GC won't move or discard the
2839 * object when we switch out of RUNNING. The ObjectId conversion
2840 * will add the object to the "do not touch" list.
2841 *
2842 * We can't use the "tracked allocation" mechanism here because
2843 * the object is going to be handed off to a different thread.
2844 */
Elliott Hughesf24d3ce2012-04-11 17:43:37 -07002845 gRegistry->Add(pReq->result_value.GetL());
Elliott Hughesd07986f2011-12-06 18:27:45 -08002846 }
2847
2848 if (old_exception.get() != NULL) {
Ian Rogers62d6c772013-02-27 08:32:07 -08002849 ThrowLocation gc_safe_throw_location(old_throw_this_object.get(), old_throw_method.get(),
2850 old_throw_dex_pc);
2851 soa.Self()->SetException(gc_safe_throw_location, old_exception.get());
Elliott Hughesd07986f2011-12-06 18:27:45 -08002852 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002853}
2854
Elliott Hughesd07986f2011-12-06 18:27:45 -08002855/*
Elliott Hughes4b9702c2013-02-20 18:13:24 -08002856 * "request" contains a full JDWP packet, possibly with multiple chunks. We
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07002857 * need to process each, accumulate the replies, and ship the whole thing
2858 * back.
2859 *
2860 * Returns "true" if we have a reply. The reply buffer is newly allocated,
2861 * and includes the chunk type/length, followed by the data.
2862 *
Elliott Hughes3d30d9b2011-12-07 17:35:48 -08002863 * OLD-TODO: we currently assume that the request and reply include a single
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07002864 * chunk. If this becomes inconvenient we will need to adapt.
2865 */
Elliott Hughes4b9702c2013-02-20 18:13:24 -08002866bool Dbg::DdmHandlePacket(JDWP::Request& request, uint8_t** pReplyBuf, int* pReplyLen) {
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07002867 Thread* self = Thread::Current();
2868 JNIEnv* env = self->GetJniEnv();
2869
Elliott Hughes4b9702c2013-02-20 18:13:24 -08002870 uint32_t type = request.ReadUnsigned32("type");
2871 uint32_t length = request.ReadUnsigned32("length");
2872
2873 // Create a byte[] corresponding to 'request'.
2874 size_t request_length = request.size();
2875 ScopedLocalRef<jbyteArray> dataArray(env, env->NewByteArray(request_length));
Elliott Hughes6a5bd492011-10-28 14:33:57 -07002876 if (dataArray.get() == NULL) {
Elliott Hughes4b9702c2013-02-20 18:13:24 -08002877 LOG(WARNING) << "byte[] allocation failed: " << request_length;
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07002878 env->ExceptionClear();
2879 return false;
2880 }
Elliott Hughes4b9702c2013-02-20 18:13:24 -08002881 env->SetByteArrayRegion(dataArray.get(), 0, request_length, reinterpret_cast<const jbyte*>(request.data()));
2882 request.Skip(request_length);
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07002883
2884 // Run through and find all chunks. [Currently just find the first.]
Elliott Hughes6a5bd492011-10-28 14:33:57 -07002885 ScopedByteArrayRO contents(env, dataArray.get());
Elliott Hughes4b9702c2013-02-20 18:13:24 -08002886 if (length != request_length) {
2887 LOG(WARNING) << StringPrintf("bad chunk found (len=%u pktLen=%d)", length, request_length);
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07002888 return false;
2889 }
2890
2891 // Call "private static Chunk dispatch(int type, byte[] data, int offset, int length)".
Elliott Hugheseac76672012-05-24 21:56:51 -07002892 ScopedLocalRef<jobject> chunk(env, env->CallStaticObjectMethod(WellKnownClasses::org_apache_harmony_dalvik_ddmc_DdmServer,
2893 WellKnownClasses::org_apache_harmony_dalvik_ddmc_DdmServer_dispatch,
Elliott Hughes4b9702c2013-02-20 18:13:24 -08002894 type, dataArray.get(), 0, length));
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07002895 if (env->ExceptionCheck()) {
2896 LOG(INFO) << StringPrintf("Exception thrown by dispatcher for 0x%08x", type);
2897 env->ExceptionDescribe();
2898 env->ExceptionClear();
2899 return false;
2900 }
2901
Elliott Hughes6a5bd492011-10-28 14:33:57 -07002902 if (chunk.get() == NULL) {
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07002903 return false;
2904 }
2905
2906 /*
2907 * Pull the pieces out of the chunk. We copy the results into a
2908 * newly-allocated buffer that the caller can free. We don't want to
2909 * continue using the Chunk object because nothing has a reference to it.
2910 *
2911 * We could avoid this by returning type/data/offset/length and having
2912 * the caller be aware of the object lifetime issues, but that
Elliott Hughes81ff3182012-03-23 20:35:56 -07002913 * integrates the JDWP code more tightly into the rest of the runtime, and doesn't work
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07002914 * if we have responses for multiple chunks.
2915 *
2916 * So we're pretty much stuck with copying data around multiple times.
2917 */
Elliott Hugheseac76672012-05-24 21:56:51 -07002918 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 -08002919 jint offset = env->GetIntField(chunk.get(), WellKnownClasses::org_apache_harmony_dalvik_ddmc_Chunk_offset);
Elliott Hugheseac76672012-05-24 21:56:51 -07002920 length = env->GetIntField(chunk.get(), WellKnownClasses::org_apache_harmony_dalvik_ddmc_Chunk_length);
Elliott Hugheseac76672012-05-24 21:56:51 -07002921 type = env->GetIntField(chunk.get(), WellKnownClasses::org_apache_harmony_dalvik_ddmc_Chunk_type);
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07002922
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08002923 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 -07002924 if (length == 0 || replyData.get() == NULL) {
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07002925 return false;
2926 }
2927
Elliott Hughes4b9702c2013-02-20 18:13:24 -08002928 const int kChunkHdrLen = 8;
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07002929 uint8_t* reply = new uint8_t[length + kChunkHdrLen];
2930 if (reply == NULL) {
2931 LOG(WARNING) << "malloc failed: " << (length + kChunkHdrLen);
2932 return false;
2933 }
Elliott Hughesf7c3b662011-10-27 12:04:56 -07002934 JDWP::Set4BE(reply + 0, type);
2935 JDWP::Set4BE(reply + 4, length);
Elliott Hughes6a5bd492011-10-28 14:33:57 -07002936 env->GetByteArrayRegion(replyData.get(), offset, length, reinterpret_cast<jbyte*>(reply + kChunkHdrLen));
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07002937
2938 *pReplyBuf = reply;
2939 *pReplyLen = length + kChunkHdrLen;
2940
Elliott Hughes4b9702c2013-02-20 18:13:24 -08002941 VLOG(jdwp) << StringPrintf("dvmHandleDdm returning type=%.4s %p len=%d", reinterpret_cast<char*>(reply), reply, length);
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07002942 return true;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002943}
2944
Elliott Hughesa2155262011-11-16 16:26:58 -08002945void Dbg::DdmBroadcast(bool connect) {
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08002946 VLOG(jdwp) << "Broadcasting DDM " << (connect ? "connect" : "disconnect") << "...";
Elliott Hughes47fce012011-10-25 18:37:19 -07002947
2948 Thread* self = Thread::Current();
Ian Rogers50b35e22012-10-04 10:09:15 -07002949 if (self->GetState() != kRunnable) {
2950 LOG(ERROR) << "DDM broadcast in thread state " << self->GetState();
2951 /* try anyway? */
Elliott Hughes47fce012011-10-25 18:37:19 -07002952 }
2953
2954 JNIEnv* env = self->GetJniEnv();
Elliott Hughes47fce012011-10-25 18:37:19 -07002955 jint event = connect ? 1 /*DdmServer.CONNECTED*/ : 2 /*DdmServer.DISCONNECTED*/;
Elliott Hugheseac76672012-05-24 21:56:51 -07002956 env->CallStaticVoidMethod(WellKnownClasses::org_apache_harmony_dalvik_ddmc_DdmServer,
2957 WellKnownClasses::org_apache_harmony_dalvik_ddmc_DdmServer_broadcast,
2958 event);
Elliott Hughes47fce012011-10-25 18:37:19 -07002959 if (env->ExceptionCheck()) {
2960 LOG(ERROR) << "DdmServer.broadcast " << event << " failed";
2961 env->ExceptionDescribe();
2962 env->ExceptionClear();
2963 }
2964}
2965
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002966void Dbg::DdmConnected() {
Elliott Hughesa2155262011-11-16 16:26:58 -08002967 Dbg::DdmBroadcast(true);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002968}
2969
2970void Dbg::DdmDisconnected() {
Elliott Hughesa2155262011-11-16 16:26:58 -08002971 Dbg::DdmBroadcast(false);
Elliott Hughes47fce012011-10-25 18:37:19 -07002972 gDdmThreadNotification = false;
2973}
2974
2975/*
Elliott Hughes82188472011-11-07 18:11:48 -08002976 * Send a notification when a thread starts, stops, or changes its name.
Elliott Hughes47fce012011-10-25 18:37:19 -07002977 *
2978 * Because we broadcast the full set of threads when the notifications are
2979 * first enabled, it's possible for "thread" to be actively executing.
2980 */
Elliott Hughes82188472011-11-07 18:11:48 -08002981void Dbg::DdmSendThreadNotification(Thread* t, uint32_t type) {
Elliott Hughes47fce012011-10-25 18:37:19 -07002982 if (!gDdmThreadNotification) {
2983 return;
2984 }
2985
Elliott Hughes82188472011-11-07 18:11:48 -08002986 if (type == CHUNK_TYPE("THDE")) {
Elliott Hughes47fce012011-10-25 18:37:19 -07002987 uint8_t buf[4];
Ian Rogersd9c4fc92013-10-01 19:45:43 -07002988 JDWP::Set4BE(&buf[0], t->GetThreadId());
Elliott Hughes47fce012011-10-25 18:37:19 -07002989 Dbg::DdmSendChunk(CHUNK_TYPE("THDE"), 4, buf);
Elliott Hughes82188472011-11-07 18:11:48 -08002990 } else {
2991 CHECK(type == CHUNK_TYPE("THCR") || type == CHUNK_TYPE("THNM")) << type;
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002992 ScopedObjectAccessUnchecked soa(Thread::Current());
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002993 SirtRef<mirror::String> name(soa.Self(), t->GetThreadName(soa));
Elliott Hughes82188472011-11-07 18:11:48 -08002994 size_t char_count = (name.get() != NULL) ? name->GetLength() : 0;
jeffhao725a9572012-11-13 18:20:12 -08002995 const jchar* chars = (name.get() != NULL) ? name->GetCharArray()->GetData() : NULL;
Elliott Hughes82188472011-11-07 18:11:48 -08002996
Elliott Hughes21f32d72011-11-09 17:44:13 -08002997 std::vector<uint8_t> bytes;
Ian Rogersd9c4fc92013-10-01 19:45:43 -07002998 JDWP::Append4BE(bytes, t->GetThreadId());
Elliott Hughes545a0642011-11-08 19:10:03 -08002999 JDWP::AppendUtf16BE(bytes, chars, char_count);
Elliott Hughes21f32d72011-11-09 17:44:13 -08003000 CHECK_EQ(bytes.size(), char_count*2 + sizeof(uint32_t)*2);
3001 Dbg::DdmSendChunk(type, bytes);
Elliott Hughes47fce012011-10-25 18:37:19 -07003002 }
3003}
3004
Elliott Hughes47fce012011-10-25 18:37:19 -07003005void Dbg::DdmSetThreadNotification(bool enable) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07003006 // Enable/disable thread notifications.
Elliott Hughes47fce012011-10-25 18:37:19 -07003007 gDdmThreadNotification = enable;
3008 if (enable) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07003009 // Suspend the VM then post thread start notifications for all threads. Threads attaching will
3010 // see a suspension in progress and block until that ends. They then post their own start
3011 // notification.
3012 SuspendVM();
3013 std::list<Thread*> threads;
Ian Rogers50b35e22012-10-04 10:09:15 -07003014 Thread* self = Thread::Current();
Ian Rogers00f7d0e2012-07-19 15:28:27 -07003015 {
Ian Rogers50b35e22012-10-04 10:09:15 -07003016 MutexLock mu(self, *Locks::thread_list_lock_);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07003017 threads = Runtime::Current()->GetThreadList()->GetList();
3018 }
3019 {
Ian Rogers50b35e22012-10-04 10:09:15 -07003020 ScopedObjectAccess soa(self);
Mathieu Chartier02e25112013-08-14 16:14:24 -07003021 for (Thread* thread : threads) {
3022 Dbg::DdmSendThreadNotification(thread, CHUNK_TYPE("THCR"));
Ian Rogers00f7d0e2012-07-19 15:28:27 -07003023 }
3024 }
3025 ResumeVM();
Elliott Hughes47fce012011-10-25 18:37:19 -07003026 }
3027}
3028
Elliott Hughesa2155262011-11-16 16:26:58 -08003029void Dbg::PostThreadStartOrStop(Thread* t, uint32_t type) {
Elliott Hughesc0f09332012-03-26 13:27:06 -07003030 if (IsDebuggerActive()) {
Mathieu Chartierdbe6f462012-09-25 16:54:50 -07003031 ScopedObjectAccessUnchecked soa(Thread::Current());
Ian Rogerscfaa4552012-11-26 21:00:08 -08003032 JDWP::ObjectId id = gRegistry->Add(t->GetPeer());
Elliott Hughes82188472011-11-07 18:11:48 -08003033 gJdwpState->PostThreadChange(id, type == CHUNK_TYPE("THCR"));
Elliott Hughes47fce012011-10-25 18:37:19 -07003034 }
Elliott Hughes82188472011-11-07 18:11:48 -08003035 Dbg::DdmSendThreadNotification(t, type);
Elliott Hughes47fce012011-10-25 18:37:19 -07003036}
3037
3038void Dbg::PostThreadStart(Thread* t) {
Elliott Hughesa2155262011-11-16 16:26:58 -08003039 Dbg::PostThreadStartOrStop(t, CHUNK_TYPE("THCR"));
Elliott Hughes47fce012011-10-25 18:37:19 -07003040}
3041
3042void Dbg::PostThreadDeath(Thread* t) {
Elliott Hughesa2155262011-11-16 16:26:58 -08003043 Dbg::PostThreadStartOrStop(t, CHUNK_TYPE("THDE"));
Elliott Hughes872d4ec2011-10-21 17:07:15 -07003044}
3045
Elliott Hughes82188472011-11-07 18:11:48 -08003046void Dbg::DdmSendChunk(uint32_t type, size_t byte_count, const uint8_t* buf) {
Elliott Hughes3bb81562011-10-21 18:52:59 -07003047 CHECK(buf != NULL);
3048 iovec vec[1];
3049 vec[0].iov_base = reinterpret_cast<void*>(const_cast<uint8_t*>(buf));
3050 vec[0].iov_len = byte_count;
3051 Dbg::DdmSendChunkV(type, vec, 1);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07003052}
3053
Elliott Hughes21f32d72011-11-09 17:44:13 -08003054void Dbg::DdmSendChunk(uint32_t type, const std::vector<uint8_t>& bytes) {
3055 DdmSendChunk(type, bytes.size(), &bytes[0]);
3056}
3057
Brian Carlstromf5293522013-07-19 00:24:00 -07003058void Dbg::DdmSendChunkV(uint32_t type, const iovec* iov, int iov_count) {
Elliott Hughes3bb81562011-10-21 18:52:59 -07003059 if (gJdwpState == NULL) {
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08003060 VLOG(jdwp) << "Debugger thread not active, ignoring DDM send: " << type;
Elliott Hughes3bb81562011-10-21 18:52:59 -07003061 } else {
Elliott Hughescccd84f2011-12-05 16:51:54 -08003062 gJdwpState->DdmSendChunkV(type, iov, iov_count);
Elliott Hughes3bb81562011-10-21 18:52:59 -07003063 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -07003064}
3065
Elliott Hughes767a1472011-10-26 18:49:02 -07003066int Dbg::DdmHandleHpifChunk(HpifWhen when) {
3067 if (when == HPIF_WHEN_NOW) {
Elliott Hughes7162ad92011-10-27 14:08:42 -07003068 DdmSendHeapInfo(when);
Elliott Hughes767a1472011-10-26 18:49:02 -07003069 return true;
3070 }
3071
3072 if (when != HPIF_WHEN_NEVER && when != HPIF_WHEN_NEXT_GC && when != HPIF_WHEN_EVERY_GC) {
3073 LOG(ERROR) << "invalid HpifWhen value: " << static_cast<int>(when);
3074 return false;
3075 }
3076
3077 gDdmHpifWhen = when;
3078 return true;
3079}
3080
3081bool Dbg::DdmHandleHpsgNhsgChunk(Dbg::HpsgWhen when, Dbg::HpsgWhat what, bool native) {
3082 if (when != HPSG_WHEN_NEVER && when != HPSG_WHEN_EVERY_GC) {
3083 LOG(ERROR) << "invalid HpsgWhen value: " << static_cast<int>(when);
3084 return false;
3085 }
3086
3087 if (what != HPSG_WHAT_MERGED_OBJECTS && what != HPSG_WHAT_DISTINCT_OBJECTS) {
3088 LOG(ERROR) << "invalid HpsgWhat value: " << static_cast<int>(what);
3089 return false;
3090 }
3091
3092 if (native) {
3093 gDdmNhsgWhen = when;
3094 gDdmNhsgWhat = what;
3095 } else {
3096 gDdmHpsgWhen = when;
3097 gDdmHpsgWhat = what;
3098 }
3099 return true;
3100}
3101
Elliott Hughes7162ad92011-10-27 14:08:42 -07003102void Dbg::DdmSendHeapInfo(HpifWhen reason) {
3103 // If there's a one-shot 'when', reset it.
3104 if (reason == gDdmHpifWhen) {
3105 if (gDdmHpifWhen == HPIF_WHEN_NEXT_GC) {
3106 gDdmHpifWhen = HPIF_WHEN_NEVER;
3107 }
3108 }
3109
3110 /*
3111 * Chunk HPIF (client --> server)
3112 *
3113 * Heap Info. General information about the heap,
3114 * suitable for a summary display.
3115 *
3116 * [u4]: number of heaps
3117 *
3118 * For each heap:
3119 * [u4]: heap ID
3120 * [u8]: timestamp in ms since Unix epoch
3121 * [u1]: capture reason (same as 'when' value from server)
3122 * [u4]: max heap size in bytes (-Xmx)
3123 * [u4]: current heap size in bytes
3124 * [u4]: current number of bytes allocated
3125 * [u4]: current number of objects allocated
3126 */
3127 uint8_t heap_count = 1;
Ian Rogers1d54e732013-05-02 21:10:01 -07003128 gc::Heap* heap = Runtime::Current()->GetHeap();
Elliott Hughes21f32d72011-11-09 17:44:13 -08003129 std::vector<uint8_t> bytes;
Elliott Hughes545a0642011-11-08 19:10:03 -08003130 JDWP::Append4BE(bytes, heap_count);
Brian Carlstrom7934ac22013-07-26 10:54:15 -07003131 JDWP::Append4BE(bytes, 1); // Heap id (bogus; we only have one heap).
Elliott Hughes545a0642011-11-08 19:10:03 -08003132 JDWP::Append8BE(bytes, MilliTime());
3133 JDWP::Append1BE(bytes, reason);
Brian Carlstrom7934ac22013-07-26 10:54:15 -07003134 JDWP::Append4BE(bytes, heap->GetMaxMemory()); // Max allowed heap size in bytes.
3135 JDWP::Append4BE(bytes, heap->GetTotalMemory()); // Current heap size in bytes.
Elliott Hughesb3bd5f02012-03-08 21:05:27 -08003136 JDWP::Append4BE(bytes, heap->GetBytesAllocated());
3137 JDWP::Append4BE(bytes, heap->GetObjectsAllocated());
Elliott Hughes21f32d72011-11-09 17:44:13 -08003138 CHECK_EQ(bytes.size(), 4U + (heap_count * (4 + 8 + 1 + 4 + 4 + 4 + 4)));
3139 Dbg::DdmSendChunk(CHUNK_TYPE("HPIF"), bytes);
Elliott Hughes767a1472011-10-26 18:49:02 -07003140}
3141
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003142enum HpsgSolidity {
3143 SOLIDITY_FREE = 0,
3144 SOLIDITY_HARD = 1,
3145 SOLIDITY_SOFT = 2,
3146 SOLIDITY_WEAK = 3,
3147 SOLIDITY_PHANTOM = 4,
3148 SOLIDITY_FINALIZABLE = 5,
3149 SOLIDITY_SWEEP = 6,
3150};
3151
3152enum HpsgKind {
3153 KIND_OBJECT = 0,
3154 KIND_CLASS_OBJECT = 1,
3155 KIND_ARRAY_1 = 2,
3156 KIND_ARRAY_2 = 3,
3157 KIND_ARRAY_4 = 4,
3158 KIND_ARRAY_8 = 5,
3159 KIND_UNKNOWN = 6,
3160 KIND_NATIVE = 7,
3161};
3162
3163#define HPSG_PARTIAL (1<<7)
3164#define HPSG_STATE(solidity, kind) ((uint8_t)((((kind) & 0x7) << 3) | ((solidity) & 0x7)))
3165
Ian Rogers30fab402012-01-23 15:43:46 -08003166class HeapChunkContext {
3167 public:
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003168 // Maximum chunk size. Obtain this from the formula:
3169 // (((maximum_heap_size / ALLOCATION_UNIT_SIZE) + 255) / 256) * 2
3170 HeapChunkContext(bool merge, bool native)
Ian Rogers30fab402012-01-23 15:43:46 -08003171 : buf_(16384 - 16),
3172 type_(0),
3173 merge_(merge) {
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003174 Reset();
3175 if (native) {
Ian Rogers30fab402012-01-23 15:43:46 -08003176 type_ = CHUNK_TYPE("NHSG");
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003177 } else {
Ian Rogers30fab402012-01-23 15:43:46 -08003178 type_ = merge ? CHUNK_TYPE("HPSG") : CHUNK_TYPE("HPSO");
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003179 }
3180 }
3181
3182 ~HeapChunkContext() {
Ian Rogers30fab402012-01-23 15:43:46 -08003183 if (p_ > &buf_[0]) {
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003184 Flush();
3185 }
3186 }
3187
3188 void EnsureHeader(const void* chunk_ptr) {
Ian Rogers30fab402012-01-23 15:43:46 -08003189 if (!needHeader_) {
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003190 return;
3191 }
3192
3193 // Start a new HPSx chunk.
Brian Carlstrom7934ac22013-07-26 10:54:15 -07003194 JDWP::Write4BE(&p_, 1); // Heap id (bogus; we only have one heap).
3195 JDWP::Write1BE(&p_, 8); // Size of allocation unit, in bytes.
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003196
Brian Carlstrom7934ac22013-07-26 10:54:15 -07003197 JDWP::Write4BE(&p_, reinterpret_cast<uintptr_t>(chunk_ptr)); // virtual address of segment start.
3198 JDWP::Write4BE(&p_, 0); // offset of this piece (relative to the virtual address).
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003199 // [u4]: length of piece, in allocation units
3200 // 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 -08003201 pieceLenField_ = p_;
3202 JDWP::Write4BE(&p_, 0x55555555);
3203 needHeader_ = false;
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003204 }
3205
Ian Rogersb726dcb2012-09-05 08:57:23 -07003206 void Flush() SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Ian Rogersd636b062013-01-18 17:51:18 -08003207 if (pieceLenField_ == NULL) {
3208 // Flush immediately post Reset (maybe back-to-back Flush). Ignore.
3209 CHECK(needHeader_);
3210 return;
3211 }
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003212 // Patch the "length of piece" field.
Ian Rogers30fab402012-01-23 15:43:46 -08003213 CHECK_LE(&buf_[0], pieceLenField_);
3214 CHECK_LE(pieceLenField_, p_);
3215 JDWP::Set4BE(pieceLenField_, totalAllocationUnits_);
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003216
Ian Rogers30fab402012-01-23 15:43:46 -08003217 Dbg::DdmSendChunk(type_, p_ - &buf_[0], &buf_[0]);
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003218 Reset();
3219 }
3220
Ian Rogers00f7d0e2012-07-19 15:28:27 -07003221 static void HeapChunkCallback(void* start, void* end, size_t used_bytes, void* arg)
Ian Rogersb726dcb2012-09-05 08:57:23 -07003222 SHARED_LOCKS_REQUIRED(Locks::heap_bitmap_lock_,
3223 Locks::mutator_lock_) {
Ian Rogers30fab402012-01-23 15:43:46 -08003224 reinterpret_cast<HeapChunkContext*>(arg)->HeapChunkCallback(start, end, used_bytes);
Elliott Hughesa2155262011-11-16 16:26:58 -08003225 }
3226
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003227 private:
Elliott Hughesa2155262011-11-16 16:26:58 -08003228 enum { ALLOCATION_UNIT_SIZE = 8 };
3229
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003230 void Reset() {
Ian Rogers30fab402012-01-23 15:43:46 -08003231 p_ = &buf_[0];
Ian Rogers15bf2d32012-08-28 17:33:04 -07003232 startOfNextMemoryChunk_ = NULL;
Ian Rogers30fab402012-01-23 15:43:46 -08003233 totalAllocationUnits_ = 0;
3234 needHeader_ = true;
3235 pieceLenField_ = NULL;
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003236 }
3237
Ian Rogers00f7d0e2012-07-19 15:28:27 -07003238 void HeapChunkCallback(void* start, void* /*end*/, size_t used_bytes)
Ian Rogersb726dcb2012-09-05 08:57:23 -07003239 SHARED_LOCKS_REQUIRED(Locks::heap_bitmap_lock_,
3240 Locks::mutator_lock_) {
Ian Rogers30fab402012-01-23 15:43:46 -08003241 // Note: heap call backs cannot manipulate the heap upon which they are crawling, care is taken
3242 // in the following code not to allocate memory, by ensuring buf_ is of the correct size
Ian Rogers15bf2d32012-08-28 17:33:04 -07003243 if (used_bytes == 0) {
3244 if (start == NULL) {
3245 // Reset for start of new heap.
3246 startOfNextMemoryChunk_ = NULL;
3247 Flush();
3248 }
3249 // Only process in use memory so that free region information
3250 // also includes dlmalloc book keeping.
Elliott Hughesa2155262011-11-16 16:26:58 -08003251 return;
Elliott Hughesa2155262011-11-16 16:26:58 -08003252 }
3253
Ian Rogers15bf2d32012-08-28 17:33:04 -07003254 /* If we're looking at the native heap, we'll just return
3255 * (SOLIDITY_HARD, KIND_NATIVE) for all allocated chunks
3256 */
3257 bool native = type_ == CHUNK_TYPE("NHSG");
3258
3259 if (startOfNextMemoryChunk_ != NULL) {
3260 // Transmit any pending free memory. Native free memory of
3261 // over kMaxFreeLen could be because of the use of mmaps, so
3262 // don't report. If not free memory then start a new segment.
3263 bool flush = true;
3264 if (start > startOfNextMemoryChunk_) {
3265 const size_t kMaxFreeLen = 2 * kPageSize;
3266 void* freeStart = startOfNextMemoryChunk_;
3267 void* freeEnd = start;
Brian Carlstrom2d888622013-07-18 17:02:00 -07003268 size_t freeLen = reinterpret_cast<char*>(freeEnd) - reinterpret_cast<char*>(freeStart);
Ian Rogers15bf2d32012-08-28 17:33:04 -07003269 if (!native || freeLen < kMaxFreeLen) {
3270 AppendChunk(HPSG_STATE(SOLIDITY_FREE, 0), freeStart, freeLen);
3271 flush = false;
3272 }
3273 }
3274 if (flush) {
3275 startOfNextMemoryChunk_ = NULL;
3276 Flush();
3277 }
3278 }
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003279 const mirror::Object* obj = reinterpret_cast<const mirror::Object*>(start);
Elliott Hughesa2155262011-11-16 16:26:58 -08003280
3281 // Determine the type of this chunk.
3282 // OLD-TODO: if context.merge, see if this chunk is different from the last chunk.
3283 // If it's the same, we should combine them.
Ian Rogers15bf2d32012-08-28 17:33:04 -07003284 uint8_t state = ExamineObject(obj, native);
3285 // dlmalloc's chunk header is 2 * sizeof(size_t), but if the previous chunk is in use for an
3286 // allocation then the first sizeof(size_t) may belong to it.
3287 const size_t dlMallocOverhead = sizeof(size_t);
3288 AppendChunk(state, start, used_bytes + dlMallocOverhead);
Brian Carlstrom2d888622013-07-18 17:02:00 -07003289 startOfNextMemoryChunk_ = reinterpret_cast<char*>(start) + used_bytes + dlMallocOverhead;
Ian Rogers15bf2d32012-08-28 17:33:04 -07003290 }
Elliott Hughesa2155262011-11-16 16:26:58 -08003291
Ian Rogers15bf2d32012-08-28 17:33:04 -07003292 void AppendChunk(uint8_t state, void* ptr, size_t length)
Ian Rogersb726dcb2012-09-05 08:57:23 -07003293 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Ian Rogers15bf2d32012-08-28 17:33:04 -07003294 // Make sure there's enough room left in the buffer.
3295 // We need to use two bytes for every fractional 256 allocation units used by the chunk plus
3296 // 17 bytes for any header.
3297 size_t needed = (((length/ALLOCATION_UNIT_SIZE + 255) / 256) * 2) + 17;
3298 size_t bytesLeft = buf_.size() - (size_t)(p_ - &buf_[0]);
3299 if (bytesLeft < needed) {
3300 Flush();
3301 }
3302
3303 bytesLeft = buf_.size() - (size_t)(p_ - &buf_[0]);
3304 if (bytesLeft < needed) {
3305 LOG(WARNING) << "Chunk is too big to transmit (chunk_len=" << length << ", "
3306 << needed << " bytes)";
3307 return;
3308 }
3309 EnsureHeader(ptr);
Elliott Hughesa2155262011-11-16 16:26:58 -08003310 // Write out the chunk description.
Ian Rogers15bf2d32012-08-28 17:33:04 -07003311 length /= ALLOCATION_UNIT_SIZE; // Convert to allocation units.
3312 totalAllocationUnits_ += length;
3313 while (length > 256) {
Ian Rogers30fab402012-01-23 15:43:46 -08003314 *p_++ = state | HPSG_PARTIAL;
3315 *p_++ = 255; // length - 1
Ian Rogers15bf2d32012-08-28 17:33:04 -07003316 length -= 256;
Elliott Hughesa2155262011-11-16 16:26:58 -08003317 }
Ian Rogers30fab402012-01-23 15:43:46 -08003318 *p_++ = state;
Ian Rogers15bf2d32012-08-28 17:33:04 -07003319 *p_++ = length - 1;
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003320 }
3321
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003322 uint8_t ExamineObject(const mirror::Object* o, bool is_native_heap)
Ian Rogersb726dcb2012-09-05 08:57:23 -07003323 SHARED_LOCKS_REQUIRED(Locks::heap_bitmap_lock_) {
Elliott Hughesa2155262011-11-16 16:26:58 -08003324 if (o == NULL) {
3325 return HPSG_STATE(SOLIDITY_FREE, 0);
3326 }
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003327
Elliott Hughesa2155262011-11-16 16:26:58 -08003328 // It's an allocated chunk. Figure out what it is.
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003329
Elliott Hughesa2155262011-11-16 16:26:58 -08003330 // If we're looking at the native heap, we'll just return
3331 // (SOLIDITY_HARD, KIND_NATIVE) for all allocated chunks.
Ian Rogers00f7d0e2012-07-19 15:28:27 -07003332 if (is_native_heap) {
Elliott Hughesa2155262011-11-16 16:26:58 -08003333 return HPSG_STATE(SOLIDITY_HARD, KIND_NATIVE);
3334 }
3335
Ian Rogers5bfa60f2012-09-02 21:17:56 -07003336 if (!Runtime::Current()->GetHeap()->IsLiveObjectLocked(o)) {
Ian Rogers15bf2d32012-08-28 17:33:04 -07003337 return HPSG_STATE(SOLIDITY_HARD, KIND_NATIVE);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07003338 }
3339
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003340 mirror::Class* c = o->GetClass();
Elliott Hughesa2155262011-11-16 16:26:58 -08003341 if (c == NULL) {
3342 // The object was probably just created but hasn't been initialized yet.
3343 return HPSG_STATE(SOLIDITY_HARD, KIND_OBJECT);
3344 }
3345
Mathieu Chartier590fee92013-09-13 13:46:47 -07003346 if (!Runtime::Current()->GetHeap()->IsValidObjectAddress(c)) {
Ian Rogers15bf2d32012-08-28 17:33:04 -07003347 LOG(ERROR) << "Invalid class for managed heap object: " << o << " " << c;
Elliott Hughesa2155262011-11-16 16:26:58 -08003348 return HPSG_STATE(SOLIDITY_HARD, KIND_UNKNOWN);
3349 }
3350
3351 if (c->IsClassClass()) {
3352 return HPSG_STATE(SOLIDITY_HARD, KIND_CLASS_OBJECT);
3353 }
3354
3355 if (c->IsArrayClass()) {
3356 if (o->IsObjectArray()) {
3357 return HPSG_STATE(SOLIDITY_HARD, KIND_ARRAY_4);
3358 }
3359 switch (c->GetComponentSize()) {
3360 case 1: return HPSG_STATE(SOLIDITY_HARD, KIND_ARRAY_1);
3361 case 2: return HPSG_STATE(SOLIDITY_HARD, KIND_ARRAY_2);
3362 case 4: return HPSG_STATE(SOLIDITY_HARD, KIND_ARRAY_4);
3363 case 8: return HPSG_STATE(SOLIDITY_HARD, KIND_ARRAY_8);
3364 }
3365 }
3366
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003367 return HPSG_STATE(SOLIDITY_HARD, KIND_OBJECT);
3368 }
3369
Ian Rogers30fab402012-01-23 15:43:46 -08003370 std::vector<uint8_t> buf_;
3371 uint8_t* p_;
3372 uint8_t* pieceLenField_;
Ian Rogers15bf2d32012-08-28 17:33:04 -07003373 void* startOfNextMemoryChunk_;
Ian Rogers30fab402012-01-23 15:43:46 -08003374 size_t totalAllocationUnits_;
3375 uint32_t type_;
3376 bool merge_;
3377 bool needHeader_;
3378
Elliott Hughesa2155262011-11-16 16:26:58 -08003379 DISALLOW_COPY_AND_ASSIGN(HeapChunkContext);
3380};
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003381
3382void Dbg::DdmSendHeapSegments(bool native) {
3383 Dbg::HpsgWhen when;
3384 Dbg::HpsgWhat what;
3385 if (!native) {
3386 when = gDdmHpsgWhen;
3387 what = gDdmHpsgWhat;
3388 } else {
3389 when = gDdmNhsgWhen;
3390 what = gDdmNhsgWhat;
3391 }
3392 if (when == HPSG_WHEN_NEVER) {
3393 return;
3394 }
3395
3396 // Figure out what kind of chunks we'll be sending.
3397 CHECK(what == HPSG_WHAT_MERGED_OBJECTS || what == HPSG_WHAT_DISTINCT_OBJECTS) << static_cast<int>(what);
3398
3399 // First, send a heap start chunk.
3400 uint8_t heap_id[4];
Brian Carlstrom7934ac22013-07-26 10:54:15 -07003401 JDWP::Set4BE(&heap_id[0], 1); // Heap id (bogus; we only have one heap).
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003402 Dbg::DdmSendChunk(native ? CHUNK_TYPE("NHST") : CHUNK_TYPE("HPST"), sizeof(heap_id), heap_id);
3403
3404 // Send a series of heap segment chunks.
Elliott Hughesa2155262011-11-16 16:26:58 -08003405 HeapChunkContext context((what == HPSG_WHAT_MERGED_OBJECTS), native);
3406 if (native) {
Ian Rogers1d54e732013-05-02 21:10:01 -07003407 dlmalloc_inspect_all(HeapChunkContext::HeapChunkCallback, &context);
Elliott Hughesa2155262011-11-16 16:26:58 -08003408 } else {
Ian Rogers1d54e732013-05-02 21:10:01 -07003409 gc::Heap* heap = Runtime::Current()->GetHeap();
3410 const std::vector<gc::space::ContinuousSpace*>& spaces = heap->GetContinuousSpaces();
Ian Rogers50b35e22012-10-04 10:09:15 -07003411 Thread* self = Thread::Current();
Ian Rogers62d6c772013-02-27 08:32:07 -08003412 ReaderMutexLock mu(self, *Locks::heap_bitmap_lock_);
Ian Rogers1d54e732013-05-02 21:10:01 -07003413 typedef std::vector<gc::space::ContinuousSpace*>::const_iterator It;
3414 for (It cur = spaces.begin(), end = spaces.end(); cur != end; ++cur) {
3415 if ((*cur)->IsDlMallocSpace()) {
3416 (*cur)->AsDlMallocSpace()->Walk(HeapChunkContext::HeapChunkCallback, &context);
Mathieu Chartierb062fdd2012-07-03 09:51:48 -07003417 }
3418 }
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -07003419 // Walk the large objects, these are not in the AllocSpace.
3420 heap->GetLargeObjectsSpace()->Walk(HeapChunkContext::HeapChunkCallback, &context);
Elliott Hughesa2155262011-11-16 16:26:58 -08003421 }
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003422
3423 // Finally, send a heap end chunk.
3424 Dbg::DdmSendChunk(native ? CHUNK_TYPE("NHEN") : CHUNK_TYPE("HPEN"), sizeof(heap_id), heap_id);
Elliott Hughes767a1472011-10-26 18:49:02 -07003425}
3426
Elliott Hughesb1a58792013-07-11 18:10:58 -07003427static size_t GetAllocTrackerMax() {
3428#ifdef HAVE_ANDROID_OS
3429 // Check whether there's a system property overriding the number of records.
3430 const char* propertyName = "dalvik.vm.allocTrackerMax";
3431 char allocRecordMaxString[PROPERTY_VALUE_MAX];
3432 if (property_get(propertyName, allocRecordMaxString, "") > 0) {
3433 char* end;
3434 size_t value = strtoul(allocRecordMaxString, &end, 10);
3435 if (*end != '\0') {
Ruben Brunk3e47a742013-09-09 17:56:07 -07003436 LOG(ERROR) << "Ignoring " << propertyName << " '" << allocRecordMaxString
3437 << "' --- invalid";
Elliott Hughesb1a58792013-07-11 18:10:58 -07003438 return kDefaultNumAllocRecords;
3439 }
3440 if (!IsPowerOfTwo(value)) {
Ruben Brunk3e47a742013-09-09 17:56:07 -07003441 LOG(ERROR) << "Ignoring " << propertyName << " '" << allocRecordMaxString
3442 << "' --- not power of two";
Elliott Hughesb1a58792013-07-11 18:10:58 -07003443 return kDefaultNumAllocRecords;
3444 }
3445 return value;
3446 }
3447#endif
3448 return kDefaultNumAllocRecords;
3449}
3450
Elliott Hughes545a0642011-11-08 19:10:03 -08003451void Dbg::SetAllocTrackingEnabled(bool enabled) {
Ian Rogers50b35e22012-10-04 10:09:15 -07003452 MutexLock mu(Thread::Current(), gAllocTrackerLock);
Elliott Hughes545a0642011-11-08 19:10:03 -08003453 if (enabled) {
3454 if (recent_allocation_records_ == NULL) {
Elliott Hughesb1a58792013-07-11 18:10:58 -07003455 gAllocRecordMax = GetAllocTrackerMax();
3456 LOG(INFO) << "Enabling alloc tracker (" << gAllocRecordMax << " entries of "
3457 << kMaxAllocRecordStackDepth << " frames, taking "
3458 << PrettySize(sizeof(AllocRecord) * gAllocRecordMax) << ")";
Elliott Hughes545a0642011-11-08 19:10:03 -08003459 gAllocRecordHead = gAllocRecordCount = 0;
Elliott Hughesb1a58792013-07-11 18:10:58 -07003460 recent_allocation_records_ = new AllocRecord[gAllocRecordMax];
Elliott Hughes545a0642011-11-08 19:10:03 -08003461 CHECK(recent_allocation_records_ != NULL);
3462 }
Ian Rogersfa824272013-11-05 16:12:57 -08003463 Runtime::Current()->GetInstrumentation()->InstrumentQuickAllocEntryPoints();
Elliott Hughes545a0642011-11-08 19:10:03 -08003464 } else {
Ian Rogersfa824272013-11-05 16:12:57 -08003465 Runtime::Current()->GetInstrumentation()->UninstrumentQuickAllocEntryPoints();
Elliott Hughes545a0642011-11-08 19:10:03 -08003466 delete[] recent_allocation_records_;
3467 recent_allocation_records_ = NULL;
3468 }
3469}
3470
Ian Rogers0399dde2012-06-06 17:09:28 -07003471struct AllocRecordStackVisitor : public StackVisitor {
Ian Rogers7a22fa62013-01-23 12:16:16 -08003472 AllocRecordStackVisitor(Thread* thread, AllocRecord* record)
Ian Rogersb726dcb2012-09-05 08:57:23 -07003473 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_)
Ian Rogers7a22fa62013-01-23 12:16:16 -08003474 : StackVisitor(thread, NULL), record(record), depth(0) {}
Elliott Hughes545a0642011-11-08 19:10:03 -08003475
Ian Rogers00f7d0e2012-07-19 15:28:27 -07003476 // TODO: Enable annotalysis. We know lock is held in constructor, but abstraction confuses
3477 // annotalysis.
3478 bool VisitFrame() NO_THREAD_SAFETY_ANALYSIS {
Elliott Hughes545a0642011-11-08 19:10:03 -08003479 if (depth >= kMaxAllocRecordStackDepth) {
Elliott Hughes530fa002012-03-12 11:44:49 -07003480 return false;
Elliott Hughes545a0642011-11-08 19:10:03 -08003481 }
Brian Carlstromea46f952013-07-30 01:26:50 -07003482 mirror::ArtMethod* m = GetMethod();
Ian Rogers0399dde2012-06-06 17:09:28 -07003483 if (!m->IsRuntimeMethod()) {
3484 record->stack[depth].method = m;
3485 record->stack[depth].dex_pc = GetDexPc();
Elliott Hughes530fa002012-03-12 11:44:49 -07003486 ++depth;
Elliott Hughes545a0642011-11-08 19:10:03 -08003487 }
Elliott Hughes530fa002012-03-12 11:44:49 -07003488 return true;
Elliott Hughes545a0642011-11-08 19:10:03 -08003489 }
3490
3491 ~AllocRecordStackVisitor() {
3492 // Clear out any unused stack trace elements.
3493 for (; depth < kMaxAllocRecordStackDepth; ++depth) {
3494 record->stack[depth].method = NULL;
Ian Rogers0399dde2012-06-06 17:09:28 -07003495 record->stack[depth].dex_pc = 0;
Elliott Hughes545a0642011-11-08 19:10:03 -08003496 }
3497 }
3498
3499 AllocRecord* record;
3500 size_t depth;
3501};
3502
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003503void Dbg::RecordAllocation(mirror::Class* type, size_t byte_count) {
Elliott Hughes545a0642011-11-08 19:10:03 -08003504 Thread* self = Thread::Current();
3505 CHECK(self != NULL);
3506
Ian Rogers50b35e22012-10-04 10:09:15 -07003507 MutexLock mu(self, gAllocTrackerLock);
Elliott Hughes545a0642011-11-08 19:10:03 -08003508 if (recent_allocation_records_ == NULL) {
3509 return;
3510 }
3511
3512 // Advance and clip.
Elliott Hughesb1a58792013-07-11 18:10:58 -07003513 if (++gAllocRecordHead == gAllocRecordMax) {
Elliott Hughes545a0642011-11-08 19:10:03 -08003514 gAllocRecordHead = 0;
3515 }
3516
3517 // Fill in the basics.
3518 AllocRecord* record = &recent_allocation_records_[gAllocRecordHead];
3519 record->type = type;
3520 record->byte_count = byte_count;
Ian Rogersd9c4fc92013-10-01 19:45:43 -07003521 record->thin_lock_id = self->GetThreadId();
Elliott Hughes545a0642011-11-08 19:10:03 -08003522
3523 // Fill in the stack trace.
Ian Rogers7a22fa62013-01-23 12:16:16 -08003524 AllocRecordStackVisitor visitor(self, record);
Ian Rogers0399dde2012-06-06 17:09:28 -07003525 visitor.WalkStack();
Elliott Hughes545a0642011-11-08 19:10:03 -08003526
Elliott Hughesb1a58792013-07-11 18:10:58 -07003527 if (gAllocRecordCount < gAllocRecordMax) {
Elliott Hughes545a0642011-11-08 19:10:03 -08003528 ++gAllocRecordCount;
3529 }
3530}
3531
Elliott Hughesa8f93cb2012-06-08 17:08:48 -07003532// Returns the index of the head element.
3533//
3534// We point at the most-recently-written record, so if gAllocRecordCount is 1
3535// we want to use the current element. Take "head+1" and subtract count
3536// from it.
3537//
3538// We need to handle underflow in our circular buffer, so we add
Elliott Hughesb1a58792013-07-11 18:10:58 -07003539// gAllocRecordMax and then mask it back down.
Elliott Hughesf8349362012-06-18 15:00:06 -07003540static inline int HeadIndex() EXCLUSIVE_LOCKS_REQUIRED(gAllocTrackerLock) {
Elliott Hughesb1a58792013-07-11 18:10:58 -07003541 return (gAllocRecordHead+1 + gAllocRecordMax - gAllocRecordCount) & (gAllocRecordMax-1);
Elliott Hughes545a0642011-11-08 19:10:03 -08003542}
3543
3544void Dbg::DumpRecentAllocations() {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07003545 ScopedObjectAccess soa(Thread::Current());
Ian Rogers50b35e22012-10-04 10:09:15 -07003546 MutexLock mu(soa.Self(), gAllocTrackerLock);
Elliott Hughes545a0642011-11-08 19:10:03 -08003547 if (recent_allocation_records_ == NULL) {
3548 LOG(INFO) << "Not recording tracked allocations";
3549 return;
3550 }
3551
3552 // "i" is the head of the list. We want to start at the end of the
3553 // list and move forward to the tail.
Elliott Hughesa8f93cb2012-06-08 17:08:48 -07003554 size_t i = HeadIndex();
Elliott Hughes545a0642011-11-08 19:10:03 -08003555 size_t count = gAllocRecordCount;
3556
3557 LOG(INFO) << "Tracked allocations, (head=" << gAllocRecordHead << " count=" << count << ")";
3558 while (count--) {
3559 AllocRecord* record = &recent_allocation_records_[i];
3560
Elliott Hughesa8f93cb2012-06-08 17:08:48 -07003561 LOG(INFO) << StringPrintf(" Thread %-2d %6zd bytes ", record->thin_lock_id, record->byte_count)
Elliott Hughes545a0642011-11-08 19:10:03 -08003562 << PrettyClass(record->type);
3563
3564 for (size_t stack_frame = 0; stack_frame < kMaxAllocRecordStackDepth; ++stack_frame) {
Brian Carlstromea46f952013-07-30 01:26:50 -07003565 const mirror::ArtMethod* m = record->stack[stack_frame].method;
Elliott Hughes545a0642011-11-08 19:10:03 -08003566 if (m == NULL) {
3567 break;
3568 }
3569 LOG(INFO) << " " << PrettyMethod(m) << " line " << record->stack[stack_frame].LineNumber();
3570 }
3571
3572 // pause periodically to help logcat catch up
3573 if ((count % 5) == 0) {
3574 usleep(40000);
3575 }
3576
Elliott Hughesb1a58792013-07-11 18:10:58 -07003577 i = (i + 1) & (gAllocRecordMax-1);
Elliott Hughes545a0642011-11-08 19:10:03 -08003578 }
3579}
3580
3581class StringTable {
3582 public:
3583 StringTable() {
3584 }
3585
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08003586 void Add(const char* s) {
Elliott Hughes545a0642011-11-08 19:10:03 -08003587 table_.insert(s);
3588 }
3589
Elliott Hughesa8f93cb2012-06-08 17:08:48 -07003590 size_t IndexOf(const char* s) const {
Mathieu Chartier02e25112013-08-14 16:14:24 -07003591 auto it = table_.find(s);
Elliott Hughesa8f93cb2012-06-08 17:08:48 -07003592 if (it == table_.end()) {
3593 LOG(FATAL) << "IndexOf(\"" << s << "\") failed";
3594 }
3595 return std::distance(table_.begin(), it);
Elliott Hughes545a0642011-11-08 19:10:03 -08003596 }
3597
Elliott Hughesa8f93cb2012-06-08 17:08:48 -07003598 size_t Size() const {
Elliott Hughes545a0642011-11-08 19:10:03 -08003599 return table_.size();
3600 }
3601
Elliott Hughesa8f93cb2012-06-08 17:08:48 -07003602 void WriteTo(std::vector<uint8_t>& bytes) const {
Mathieu Chartier02e25112013-08-14 16:14:24 -07003603 for (const std::string& str : table_) {
3604 const char* s = str.c_str();
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08003605 size_t s_len = CountModifiedUtf8Chars(s);
3606 UniquePtr<uint16_t> s_utf16(new uint16_t[s_len]);
3607 ConvertModifiedUtf8ToUtf16(s_utf16.get(), s);
3608 JDWP::AppendUtf16BE(bytes, s_utf16.get(), s_len);
Elliott Hughes545a0642011-11-08 19:10:03 -08003609 }
3610 }
3611
3612 private:
Elliott Hughesa8f93cb2012-06-08 17:08:48 -07003613 std::set<std::string> table_;
Elliott Hughes545a0642011-11-08 19:10:03 -08003614 DISALLOW_COPY_AND_ASSIGN(StringTable);
3615};
3616
3617/*
3618 * The data we send to DDMS contains everything we have recorded.
3619 *
3620 * Message header (all values big-endian):
3621 * (1b) message header len (to allow future expansion); includes itself
3622 * (1b) entry header len
3623 * (1b) stack frame len
3624 * (2b) number of entries
3625 * (4b) offset to string table from start of message
3626 * (2b) number of class name strings
3627 * (2b) number of method name strings
3628 * (2b) number of source file name strings
3629 * For each entry:
3630 * (4b) total allocation size
Elliott Hughes221229c2013-01-08 18:17:50 -08003631 * (2b) thread id
Elliott Hughes545a0642011-11-08 19:10:03 -08003632 * (2b) allocated object's class name index
3633 * (1b) stack depth
3634 * For each stack frame:
3635 * (2b) method's class name
3636 * (2b) method name
3637 * (2b) method source file
3638 * (2b) line number, clipped to 32767; -2 if native; -1 if no source
3639 * (xb) class name strings
3640 * (xb) method name strings
3641 * (xb) source file strings
3642 *
3643 * As with other DDM traffic, strings are sent as a 4-byte length
3644 * followed by UTF-16 data.
3645 *
3646 * We send up 16-bit unsigned indexes into string tables. In theory there
Elliott Hughesb1a58792013-07-11 18:10:58 -07003647 * can be (kMaxAllocRecordStackDepth * gAllocRecordMax) unique strings in
Elliott Hughes545a0642011-11-08 19:10:03 -08003648 * each table, but in practice there should be far fewer.
3649 *
3650 * The chief reason for using a string table here is to keep the size of
3651 * the DDMS message to a minimum. This is partly to make the protocol
3652 * efficient, but also because we have to form the whole thing up all at
3653 * once in a memory buffer.
3654 *
3655 * We use separate string tables for class names, method names, and source
3656 * files to keep the indexes small. There will generally be no overlap
3657 * between the contents of these tables.
3658 */
3659jbyteArray Dbg::GetRecentAllocations() {
3660 if (false) {
3661 DumpRecentAllocations();
3662 }
3663
Ian Rogers50b35e22012-10-04 10:09:15 -07003664 Thread* self = Thread::Current();
Elliott Hughes545a0642011-11-08 19:10:03 -08003665 std::vector<uint8_t> bytes;
Mathieu Chartier46e811b2013-07-10 17:09:14 -07003666 {
3667 MutexLock mu(self, gAllocTrackerLock);
3668 //
3669 // Part 1: generate string tables.
3670 //
3671 StringTable class_names;
3672 StringTable method_names;
3673 StringTable filenames;
Elliott Hughes545a0642011-11-08 19:10:03 -08003674
Mathieu Chartier46e811b2013-07-10 17:09:14 -07003675 int count = gAllocRecordCount;
3676 int idx = HeadIndex();
3677 while (count--) {
3678 AllocRecord* record = &recent_allocation_records_[idx];
Elliott Hughes545a0642011-11-08 19:10:03 -08003679
Mathieu Chartier46e811b2013-07-10 17:09:14 -07003680 class_names.Add(ClassHelper(record->type).GetDescriptor());
Elliott Hughes545a0642011-11-08 19:10:03 -08003681
Mathieu Chartier46e811b2013-07-10 17:09:14 -07003682 MethodHelper mh;
3683 for (size_t i = 0; i < kMaxAllocRecordStackDepth; i++) {
Brian Carlstromea46f952013-07-30 01:26:50 -07003684 mirror::ArtMethod* m = record->stack[i].method;
Mathieu Chartier46e811b2013-07-10 17:09:14 -07003685 if (m != NULL) {
3686 mh.ChangeMethod(m);
3687 class_names.Add(mh.GetDeclaringClassDescriptor());
3688 method_names.Add(mh.GetName());
3689 filenames.Add(mh.GetDeclaringClassSourceFile());
3690 }
3691 }
Elliott Hughes545a0642011-11-08 19:10:03 -08003692
Elliott Hughesb1a58792013-07-11 18:10:58 -07003693 idx = (idx + 1) & (gAllocRecordMax-1);
Elliott Hughes545a0642011-11-08 19:10:03 -08003694 }
3695
Mathieu Chartier46e811b2013-07-10 17:09:14 -07003696 LOG(INFO) << "allocation records: " << gAllocRecordCount;
3697
3698 //
3699 // Part 2: Generate the output and store it in the buffer.
3700 //
3701
3702 // (1b) message header len (to allow future expansion); includes itself
3703 // (1b) entry header len
3704 // (1b) stack frame len
3705 const int kMessageHeaderLen = 15;
3706 const int kEntryHeaderLen = 9;
3707 const int kStackFrameLen = 8;
3708 JDWP::Append1BE(bytes, kMessageHeaderLen);
3709 JDWP::Append1BE(bytes, kEntryHeaderLen);
3710 JDWP::Append1BE(bytes, kStackFrameLen);
3711
3712 // (2b) number of entries
3713 // (4b) offset to string table from start of message
3714 // (2b) number of class name strings
3715 // (2b) number of method name strings
3716 // (2b) number of source file name strings
3717 JDWP::Append2BE(bytes, gAllocRecordCount);
3718 size_t string_table_offset = bytes.size();
Brian Carlstrom7934ac22013-07-26 10:54:15 -07003719 JDWP::Append4BE(bytes, 0); // We'll patch this later...
Mathieu Chartier46e811b2013-07-10 17:09:14 -07003720 JDWP::Append2BE(bytes, class_names.Size());
3721 JDWP::Append2BE(bytes, method_names.Size());
3722 JDWP::Append2BE(bytes, filenames.Size());
3723
3724 count = gAllocRecordCount;
3725 idx = HeadIndex();
Mathieu Chartier46e811b2013-07-10 17:09:14 -07003726 while (count--) {
3727 // For each entry:
3728 // (4b) total allocation size
3729 // (2b) thread id
3730 // (2b) allocated object's class name index
3731 // (1b) stack depth
3732 AllocRecord* record = &recent_allocation_records_[idx];
3733 size_t stack_depth = record->GetDepth();
Mathieu Chartier590fee92013-09-13 13:46:47 -07003734 ClassHelper kh(record->type);
Mathieu Chartier46e811b2013-07-10 17:09:14 -07003735 size_t allocated_object_class_name_index = class_names.IndexOf(kh.GetDescriptor());
3736 JDWP::Append4BE(bytes, record->byte_count);
3737 JDWP::Append2BE(bytes, record->thin_lock_id);
3738 JDWP::Append2BE(bytes, allocated_object_class_name_index);
3739 JDWP::Append1BE(bytes, stack_depth);
3740
3741 MethodHelper mh;
3742 for (size_t stack_frame = 0; stack_frame < stack_depth; ++stack_frame) {
3743 // For each stack frame:
3744 // (2b) method's class name
3745 // (2b) method name
3746 // (2b) method source file
3747 // (2b) line number, clipped to 32767; -2 if native; -1 if no source
3748 mh.ChangeMethod(record->stack[stack_frame].method);
3749 size_t class_name_index = class_names.IndexOf(mh.GetDeclaringClassDescriptor());
3750 size_t method_name_index = method_names.IndexOf(mh.GetName());
3751 size_t file_name_index = filenames.IndexOf(mh.GetDeclaringClassSourceFile());
3752 JDWP::Append2BE(bytes, class_name_index);
3753 JDWP::Append2BE(bytes, method_name_index);
3754 JDWP::Append2BE(bytes, file_name_index);
3755 JDWP::Append2BE(bytes, record->stack[stack_frame].LineNumber());
3756 }
3757
Elliott Hughesb1a58792013-07-11 18:10:58 -07003758 idx = (idx + 1) & (gAllocRecordMax-1);
Mathieu Chartier46e811b2013-07-10 17:09:14 -07003759 }
3760
3761 // (xb) class name strings
3762 // (xb) method name strings
3763 // (xb) source file strings
3764 JDWP::Set4BE(&bytes[string_table_offset], bytes.size());
3765 class_names.WriteTo(bytes);
3766 method_names.WriteTo(bytes);
3767 filenames.WriteTo(bytes);
Elliott Hughes545a0642011-11-08 19:10:03 -08003768 }
Ian Rogers50b35e22012-10-04 10:09:15 -07003769 JNIEnv* env = self->GetJniEnv();
Elliott Hughes545a0642011-11-08 19:10:03 -08003770 jbyteArray result = env->NewByteArray(bytes.size());
3771 if (result != NULL) {
3772 env->SetByteArrayRegion(result, 0, bytes.size(), reinterpret_cast<const jbyte*>(&bytes[0]));
3773 }
3774 return result;
3775}
3776
Elliott Hughes872d4ec2011-10-21 17:07:15 -07003777} // namespace art