blob: 9bd1eb57d576a0a7e06b42c1aad650c55c90a83a [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
23#include "class_linker.h"
Ian Rogers2dd0e2c2013-01-24 12:42:14 -080024#include "class_linker-inl.h"
Ian Rogers4f6ad8a2013-03-18 15:27:28 -070025#include "dex_file-inl.h"
Ian Rogers776ac1f2012-04-13 23:36:36 -070026#include "dex_instruction.h"
Ian Rogers2dd0e2c2013-01-24 12:42:14 -080027#include "gc/card_table-inl.h"
Mathieu Chartier1c23e1e2012-10-12 14:14:11 -070028#include "gc/large_object_space.h"
29#include "gc/space.h"
Jeff Hao5d917302013-02-27 17:57:33 -080030#include "invoke_arg_array_builder.h"
Elliott Hughes64f574f2013-02-20 14:57:12 -080031#include "jdwp/object_registry.h"
Ian Rogers2dd0e2c2013-01-24 12:42:14 -080032#include "mirror/abstract_method-inl.h"
33#include "mirror/class.h"
34#include "mirror/class-inl.h"
35#include "mirror/class_loader.h"
36#include "mirror/field-inl.h"
37#include "mirror/object-inl.h"
38#include "mirror/object_array-inl.h"
39#include "mirror/throwable.h"
Ian Rogers2bcb4a42012-11-08 10:39:18 -080040#include "oat/runtime/context.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
Elliott Hughes872d4ec2011-10-21 17:07:15 -070053namespace art {
54
Elliott Hughes545a0642011-11-08 19:10:03 -080055static const size_t kMaxAllocRecordStackDepth = 16; // Max 255.
Elliott Hughes64f574f2013-02-20 14:57:12 -080056static const size_t kNumAllocRecords = 512; // Must be a power of 2.
Elliott Hughes475fc232011-10-25 15:00:35 -070057
Elliott Hughes545a0642011-11-08 19:10:03 -080058struct AllocRecordStackTraceElement {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -080059 mirror::AbstractMethod* method;
Ian Rogers0399dde2012-06-06 17:09:28 -070060 uint32_t dex_pc;
Elliott Hughes545a0642011-11-08 19:10:03 -080061
Ian Rogersb726dcb2012-09-05 08:57:23 -070062 int32_t LineNumber() const SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Ian Rogers0399dde2012-06-06 17:09:28 -070063 return MethodHelper(method).GetLineNumFromDexPC(dex_pc);
Elliott Hughes545a0642011-11-08 19:10:03 -080064 }
65};
66
67struct AllocRecord {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -080068 mirror::Class* type;
Elliott Hughes545a0642011-11-08 19:10:03 -080069 size_t byte_count;
70 uint16_t thin_lock_id;
71 AllocRecordStackTraceElement stack[kMaxAllocRecordStackDepth]; // Unused entries have NULL method.
72
73 size_t GetDepth() {
74 size_t depth = 0;
75 while (depth < kMaxAllocRecordStackDepth && stack[depth].method != NULL) {
76 ++depth;
77 }
78 return depth;
79 }
80};
81
Elliott Hughes86964332012-02-15 19:37:42 -080082struct Breakpoint {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -080083 mirror::AbstractMethod* method;
Elliott Hughesa656a0f2012-02-21 18:03:44 -080084 uint32_t dex_pc;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -080085 Breakpoint(mirror::AbstractMethod* method, uint32_t dex_pc) : method(method), dex_pc(dex_pc) {}
Elliott Hughes86964332012-02-15 19:37:42 -080086};
87
Ian Rogers00f7d0e2012-07-19 15:28:27 -070088static std::ostream& operator<<(std::ostream& os, const Breakpoint& rhs)
Ian Rogersb726dcb2012-09-05 08:57:23 -070089 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Elliott Hughes229feb72012-02-23 13:33:29 -080090 os << StringPrintf("Breakpoint[%s @%#x]", PrettyMethod(rhs.method).c_str(), rhs.dex_pc);
Elliott Hughes86964332012-02-15 19:37:42 -080091 return os;
92}
93
94struct SingleStepControl {
95 // Are we single-stepping right now?
96 bool is_active;
97 Thread* thread;
98
99 JDWP::JdwpStepSize step_size;
100 JDWP::JdwpStepDepth step_depth;
101
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800102 const mirror::AbstractMethod* method;
Elliott Hughes2435a572012-02-17 16:07:41 -0800103 int32_t line_number; // Or -1 for native methods.
104 std::set<uint32_t> dex_pcs;
Elliott Hughes86964332012-02-15 19:37:42 -0800105 int stack_depth;
106};
107
Ian Rogers62d6c772013-02-27 08:32:07 -0800108class DebugInstrumentationListener : public instrumentation::InstrumentationListener {
109 public:
110 DebugInstrumentationListener() {}
111 virtual ~DebugInstrumentationListener() {}
112
113 virtual void MethodEntered(Thread* thread, mirror::Object* this_object,
114 const mirror::AbstractMethod* method, uint32_t dex_pc)
115 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
116 if (method->IsNative()) {
117 // TODO: post location events is a suspension point and native method entry stubs aren't.
118 return;
119 }
120 Dbg::PostLocationEvent(method, 0, this_object, Dbg::kMethodEntry);
121 }
122
123 virtual void MethodExited(Thread* thread, mirror::Object* this_object,
124 const mirror::AbstractMethod* method,
125 uint32_t dex_pc, const JValue& return_value)
126 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
127 UNUSED(return_value);
128 if (method->IsNative()) {
129 // TODO: post location events is a suspension point and native method entry stubs aren't.
130 return;
131 }
132 Dbg::PostLocationEvent(method, dex_pc, this_object, Dbg::kMethodExit);
133 }
134
135 virtual void MethodUnwind(Thread* thread, const mirror::AbstractMethod* method,
136 uint32_t dex_pc) SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
137 // We're not recorded to listen to this kind of event, so complain.
138 LOG(ERROR) << "Unexpected method unwind event in debugger " << PrettyMethod(method)
139 << " " << dex_pc;
140 }
141
142 virtual void DexPcMoved(Thread* thread, mirror::Object* this_object,
143 const mirror::AbstractMethod* method, uint32_t new_dex_pc)
144 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
145 Dbg::UpdateDebugger(thread, this_object, method, new_dex_pc);
146 }
147
148 virtual void ExceptionCaught(Thread* thread, const ThrowLocation& throw_location,
149 mirror::AbstractMethod* catch_method, uint32_t catch_dex_pc,
150 mirror::Throwable* exception_object)
151 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
152 Dbg::PostException(thread, throw_location, catch_method, catch_dex_pc, exception_object);
153 }
154
155} gDebugInstrumentationListener;
156
Elliott Hughes4ffd3132011-10-24 12:06:42 -0700157// JDWP is allowed unless the Zygote forbids it.
158static bool gJdwpAllowed = true;
159
Elliott Hughesc0f09332012-03-26 13:27:06 -0700160// Was there a -Xrunjdwp or -agentlib:jdwp= argument on the command line?
Elliott Hughes3bb81562011-10-21 18:52:59 -0700161static bool gJdwpConfigured = false;
162
Elliott Hughesc0f09332012-03-26 13:27:06 -0700163// Broken-down JDWP options. (Only valid if IsJdwpConfigured() is true.)
Elliott Hughes376a7a02011-10-24 18:35:55 -0700164static JDWP::JdwpOptions gJdwpOptions;
Elliott Hughes3bb81562011-10-21 18:52:59 -0700165
166// Runtime JDWP state.
167static JDWP::JdwpState* gJdwpState = NULL;
168static bool gDebuggerConnected; // debugger or DDMS is connected.
169static bool gDebuggerActive; // debugger is making requests.
Elliott Hughes86964332012-02-15 19:37:42 -0800170static bool gDisposed; // debugger called VirtualMachine.Dispose, so we should drop the connection.
Elliott Hughes3bb81562011-10-21 18:52:59 -0700171
Elliott Hughes47fce012011-10-25 18:37:19 -0700172static bool gDdmThreadNotification = false;
173
Elliott Hughes767a1472011-10-26 18:49:02 -0700174// DDMS GC-related settings.
175static Dbg::HpifWhen gDdmHpifWhen = Dbg::HPIF_WHEN_NEVER;
176static Dbg::HpsgWhen gDdmHpsgWhen = Dbg::HPSG_WHEN_NEVER;
177static Dbg::HpsgWhat gDdmHpsgWhat;
178static Dbg::HpsgWhen gDdmNhsgWhen = Dbg::HPSG_WHEN_NEVER;
179static Dbg::HpsgWhat gDdmNhsgWhat;
180
Elliott Hughes475fc232011-10-25 15:00:35 -0700181static ObjectRegistry* gRegistry = NULL;
182
Elliott Hughes545a0642011-11-08 19:10:03 -0800183// Recent allocation tracking.
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700184static Mutex gAllocTrackerLock DEFAULT_MUTEX_ACQUIRED_AFTER ("AllocTracker lock");
Elliott Hughesf8349362012-06-18 15:00:06 -0700185AllocRecord* Dbg::recent_allocation_records_ PT_GUARDED_BY(gAllocTrackerLock) = NULL; // TODO: CircularBuffer<AllocRecord>
186static size_t gAllocRecordHead GUARDED_BY(gAllocTrackerLock) = 0;
187static size_t gAllocRecordCount GUARDED_BY(gAllocTrackerLock) = 0;
Elliott Hughes545a0642011-11-08 19:10:03 -0800188
Elliott Hughes86964332012-02-15 19:37:42 -0800189// Breakpoints and single-stepping.
jeffhao09bfc6a2012-12-11 18:11:43 -0800190static std::vector<Breakpoint> gBreakpoints GUARDED_BY(Locks::breakpoint_lock_);
191static SingleStepControl gSingleStepControl GUARDED_BY(Locks::breakpoint_lock_);
Elliott Hughes86964332012-02-15 19:37:42 -0800192
Ian Rogers62d6c772013-02-27 08:32:07 -0800193static bool IsBreakpoint(const mirror::AbstractMethod* m, uint32_t dex_pc)
jeffhao09bfc6a2012-12-11 18:11:43 -0800194 LOCKS_EXCLUDED(Locks::breakpoint_lock_)
Ian Rogersb726dcb2012-09-05 08:57:23 -0700195 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
jeffhao09bfc6a2012-12-11 18:11:43 -0800196 MutexLock mu(Thread::Current(), *Locks::breakpoint_lock_);
Elliott Hughes86964332012-02-15 19:37:42 -0800197 for (size_t i = 0; i < gBreakpoints.size(); ++i) {
Elliott Hughesa656a0f2012-02-21 18:03:44 -0800198 if (gBreakpoints[i].method == m && gBreakpoints[i].dex_pc == dex_pc) {
Elliott Hughes86964332012-02-15 19:37:42 -0800199 VLOG(jdwp) << "Hit breakpoint #" << i << ": " << gBreakpoints[i];
200 return true;
201 }
202 }
203 return false;
204}
205
Elliott Hughes9e0c1752013-01-09 14:02:58 -0800206static bool IsSuspendedForDebugger(ScopedObjectAccessUnchecked& soa, Thread* thread) {
207 MutexLock mu(soa.Self(), *Locks::thread_suspend_count_lock_);
208 // A thread may be suspended for GC; in this code, we really want to know whether
209 // there's a debugger suspension active.
210 return thread->IsSuspended() && thread->GetDebugSuspendCount() > 0;
211}
212
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800213static mirror::Array* DecodeArray(JDWP::RefTypeId id, JDWP::JdwpError& status)
Ian Rogersb726dcb2012-09-05 08:57:23 -0700214 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800215 mirror::Object* o = gRegistry->Get<mirror::Object*>(id);
Elliott Hughes64f574f2013-02-20 14:57:12 -0800216 if (o == NULL || o == ObjectRegistry::kInvalidObject) {
Elliott Hughes436e3722012-02-17 20:01:47 -0800217 status = JDWP::ERR_INVALID_OBJECT;
218 return NULL;
219 }
220 if (!o->IsArrayInstance()) {
221 status = JDWP::ERR_INVALID_ARRAY;
222 return NULL;
223 }
224 status = JDWP::ERR_NONE;
225 return o->AsArray();
226}
227
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800228static mirror::Class* DecodeClass(JDWP::RefTypeId id, JDWP::JdwpError& status)
Ian Rogersb726dcb2012-09-05 08:57:23 -0700229 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800230 mirror::Object* o = gRegistry->Get<mirror::Object*>(id);
Elliott Hughes64f574f2013-02-20 14:57:12 -0800231 if (o == NULL || o == ObjectRegistry::kInvalidObject) {
Elliott Hughes436e3722012-02-17 20:01:47 -0800232 status = JDWP::ERR_INVALID_OBJECT;
233 return NULL;
234 }
235 if (!o->IsClass()) {
236 status = JDWP::ERR_INVALID_CLASS;
237 return NULL;
238 }
239 status = JDWP::ERR_NONE;
240 return o->AsClass();
241}
242
Elliott Hughes221229c2013-01-08 18:17:50 -0800243static JDWP::JdwpError DecodeThread(ScopedObjectAccessUnchecked& soa, JDWP::ObjectId thread_id, Thread*& thread)
jeffhaoa77f0f62012-12-05 17:19:31 -0800244 EXCLUSIVE_LOCKS_REQUIRED(Locks::thread_list_lock_)
Ian Rogersb726dcb2012-09-05 08:57:23 -0700245 LOCKS_EXCLUDED(Locks::thread_suspend_count_lock_)
246 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800247 mirror::Object* thread_peer = gRegistry->Get<mirror::Object*>(thread_id);
Elliott Hughes64f574f2013-02-20 14:57:12 -0800248 if (thread_peer == NULL || thread_peer == ObjectRegistry::kInvalidObject) {
Elliott Hughes221229c2013-01-08 18:17:50 -0800249 // This isn't even an object.
250 return JDWP::ERR_INVALID_OBJECT;
Elliott Hughes436e3722012-02-17 20:01:47 -0800251 }
Elliott Hughes221229c2013-01-08 18:17:50 -0800252
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800253 mirror::Class* java_lang_Thread = soa.Decode<mirror::Class*>(WellKnownClasses::java_lang_Thread);
Elliott Hughes221229c2013-01-08 18:17:50 -0800254 if (!java_lang_Thread->IsAssignableFrom(thread_peer->GetClass())) {
255 // This isn't a thread.
256 return JDWP::ERR_INVALID_THREAD;
257 }
258
259 thread = Thread::FromManagedThread(soa, thread_peer);
260 if (thread == NULL) {
261 // This is a java.lang.Thread without a Thread*. Must be a zombie.
262 return JDWP::ERR_THREAD_NOT_ALIVE;
263 }
264 return JDWP::ERR_NONE;
Elliott Hughes436e3722012-02-17 20:01:47 -0800265}
266
Elliott Hughes24437992011-11-30 14:49:33 -0800267static JDWP::JdwpTag BasicTagFromDescriptor(const char* descriptor) {
268 // JDWP deliberately uses the descriptor characters' ASCII values for its enum.
269 // Note that by "basic" we mean that we don't get more specific than JT_OBJECT.
270 return static_cast<JDWP::JdwpTag>(descriptor[0]);
271}
272
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800273static JDWP::JdwpTag TagFromClass(mirror::Class* c)
Ian Rogersb726dcb2012-09-05 08:57:23 -0700274 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Elliott Hughes86b00102011-12-05 17:54:26 -0800275 CHECK(c != NULL);
Elliott Hughes24437992011-11-30 14:49:33 -0800276 if (c->IsArrayClass()) {
277 return JDWP::JT_ARRAY;
278 }
279
Elliott Hughes3d30d9b2011-12-07 17:35:48 -0800280 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
Elliott Hughes24437992011-11-30 14:49:33 -0800281 if (c->IsStringClass()) {
282 return JDWP::JT_STRING;
283 } else if (c->IsClassClass()) {
284 return JDWP::JT_CLASS_OBJECT;
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -0800285 } else if (class_linker->FindSystemClass("Ljava/lang/Thread;")->IsAssignableFrom(c)) {
Elliott Hughes24437992011-11-30 14:49:33 -0800286 return JDWP::JT_THREAD;
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -0800287 } else if (class_linker->FindSystemClass("Ljava/lang/ThreadGroup;")->IsAssignableFrom(c)) {
Elliott Hughes24437992011-11-30 14:49:33 -0800288 return JDWP::JT_THREAD_GROUP;
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -0800289 } else if (class_linker->FindSystemClass("Ljava/lang/ClassLoader;")->IsAssignableFrom(c)) {
Elliott Hughes24437992011-11-30 14:49:33 -0800290 return JDWP::JT_CLASS_LOADER;
Elliott Hughes24437992011-11-30 14:49:33 -0800291 } else {
292 return JDWP::JT_OBJECT;
293 }
294}
295
296/*
297 * Objects declared to hold Object might actually hold a more specific
298 * type. The debugger may take a special interest in these (e.g. it
299 * wants to display the contents of Strings), so we want to return an
300 * appropriate tag.
301 *
302 * Null objects are tagged JT_OBJECT.
303 */
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800304static JDWP::JdwpTag TagFromObject(const mirror::Object* o)
Ian Rogersb726dcb2012-09-05 08:57:23 -0700305 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Elliott Hughes24437992011-11-30 14:49:33 -0800306 return (o == NULL) ? JDWP::JT_OBJECT : TagFromClass(o->GetClass());
307}
308
309static bool IsPrimitiveTag(JDWP::JdwpTag tag) {
310 switch (tag) {
311 case JDWP::JT_BOOLEAN:
312 case JDWP::JT_BYTE:
313 case JDWP::JT_CHAR:
314 case JDWP::JT_FLOAT:
315 case JDWP::JT_DOUBLE:
316 case JDWP::JT_INT:
317 case JDWP::JT_LONG:
318 case JDWP::JT_SHORT:
319 case JDWP::JT_VOID:
320 return true;
321 default:
322 return false;
323 }
324}
325
Elliott Hughes3bb81562011-10-21 18:52:59 -0700326/*
327 * Handle one of the JDWP name/value pairs.
328 *
329 * JDWP options are:
330 * help: if specified, show help message and bail
331 * transport: may be dt_socket or dt_shmem
332 * address: for dt_socket, "host:port", or just "port" when listening
333 * server: if "y", wait for debugger to attach; if "n", attach to debugger
334 * timeout: how long to wait for debugger to connect / listen
335 *
336 * Useful with server=n (these aren't supported yet):
337 * onthrow=<exception-name>: connect to debugger when exception thrown
338 * onuncaught=y|n: connect to debugger when uncaught exception thrown
339 * launch=<command-line>: launch the debugger itself
340 *
341 * The "transport" option is required, as is "address" if server=n.
342 */
343static bool ParseJdwpOption(const std::string& name, const std::string& value) {
344 if (name == "transport") {
345 if (value == "dt_socket") {
Elliott Hughes376a7a02011-10-24 18:35:55 -0700346 gJdwpOptions.transport = JDWP::kJdwpTransportSocket;
Elliott Hughes3bb81562011-10-21 18:52:59 -0700347 } else if (value == "dt_android_adb") {
Elliott Hughes376a7a02011-10-24 18:35:55 -0700348 gJdwpOptions.transport = JDWP::kJdwpTransportAndroidAdb;
Elliott Hughes3bb81562011-10-21 18:52:59 -0700349 } else {
350 LOG(ERROR) << "JDWP transport not supported: " << value;
351 return false;
352 }
353 } else if (name == "server") {
354 if (value == "n") {
Elliott Hughes376a7a02011-10-24 18:35:55 -0700355 gJdwpOptions.server = false;
Elliott Hughes3bb81562011-10-21 18:52:59 -0700356 } else if (value == "y") {
Elliott Hughes376a7a02011-10-24 18:35:55 -0700357 gJdwpOptions.server = true;
Elliott Hughes3bb81562011-10-21 18:52:59 -0700358 } else {
359 LOG(ERROR) << "JDWP option 'server' must be 'y' or 'n'";
360 return false;
361 }
362 } else if (name == "suspend") {
363 if (value == "n") {
Elliott Hughes376a7a02011-10-24 18:35:55 -0700364 gJdwpOptions.suspend = false;
Elliott Hughes3bb81562011-10-21 18:52:59 -0700365 } else if (value == "y") {
Elliott Hughes376a7a02011-10-24 18:35:55 -0700366 gJdwpOptions.suspend = true;
Elliott Hughes3bb81562011-10-21 18:52:59 -0700367 } else {
368 LOG(ERROR) << "JDWP option 'suspend' must be 'y' or 'n'";
369 return false;
370 }
371 } else if (name == "address") {
372 /* this is either <port> or <host>:<port> */
373 std::string port_string;
Elliott Hughes376a7a02011-10-24 18:35:55 -0700374 gJdwpOptions.host.clear();
Elliott Hughes3bb81562011-10-21 18:52:59 -0700375 std::string::size_type colon = value.find(':');
376 if (colon != std::string::npos) {
Elliott Hughes376a7a02011-10-24 18:35:55 -0700377 gJdwpOptions.host = value.substr(0, colon);
Elliott Hughes3bb81562011-10-21 18:52:59 -0700378 port_string = value.substr(colon + 1);
379 } else {
380 port_string = value;
381 }
382 if (port_string.empty()) {
383 LOG(ERROR) << "JDWP address missing port: " << value;
384 return false;
385 }
386 char* end;
Elliott Hughesba8eee12012-01-24 20:25:24 -0800387 uint64_t port = strtoul(port_string.c_str(), &end, 10);
388 if (*end != '\0' || port > 0xffff) {
Elliott Hughes3bb81562011-10-21 18:52:59 -0700389 LOG(ERROR) << "JDWP address has junk in port field: " << value;
390 return false;
391 }
Elliott Hughes376a7a02011-10-24 18:35:55 -0700392 gJdwpOptions.port = port;
Elliott Hughes3bb81562011-10-21 18:52:59 -0700393 } else if (name == "launch" || name == "onthrow" || name == "oncaught" || name == "timeout") {
394 /* valid but unsupported */
395 LOG(INFO) << "Ignoring JDWP option '" << name << "'='" << value << "'";
396 } else {
397 LOG(INFO) << "Ignoring unrecognized JDWP option '" << name << "'='" << value << "'";
398 }
399
400 return true;
401}
402
403/*
404 * Parse the latter half of a -Xrunjdwp/-agentlib:jdwp= string, e.g.:
405 * "transport=dt_socket,address=8000,server=y,suspend=n"
406 */
407bool Dbg::ParseJdwpOptions(const std::string& options) {
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -0800408 VLOG(jdwp) << "ParseJdwpOptions: " << options;
Elliott Hughes47fce012011-10-25 18:37:19 -0700409
Elliott Hughes3bb81562011-10-21 18:52:59 -0700410 std::vector<std::string> pairs;
411 Split(options, ',', pairs);
412
413 for (size_t i = 0; i < pairs.size(); ++i) {
414 std::string::size_type equals = pairs[i].find('=');
415 if (equals == std::string::npos) {
416 LOG(ERROR) << "Can't parse JDWP option '" << pairs[i] << "' in '" << options << "'";
417 return false;
418 }
419 ParseJdwpOption(pairs[i].substr(0, equals), pairs[i].substr(equals + 1));
420 }
421
Elliott Hughes376a7a02011-10-24 18:35:55 -0700422 if (gJdwpOptions.transport == JDWP::kJdwpTransportUnknown) {
Elliott Hughes3bb81562011-10-21 18:52:59 -0700423 LOG(ERROR) << "Must specify JDWP transport: " << options;
424 }
Elliott Hughes376a7a02011-10-24 18:35:55 -0700425 if (!gJdwpOptions.server && (gJdwpOptions.host.empty() || gJdwpOptions.port == 0)) {
Elliott Hughes3bb81562011-10-21 18:52:59 -0700426 LOG(ERROR) << "Must specify JDWP host and port when server=n: " << options;
427 return false;
428 }
429
430 gJdwpConfigured = true;
431 return true;
432}
433
Elliott Hughesd1cc8362011-10-24 16:58:50 -0700434void Dbg::StartJdwp() {
Elliott Hughesc0f09332012-03-26 13:27:06 -0700435 if (!gJdwpAllowed || !IsJdwpConfigured()) {
Elliott Hughes376a7a02011-10-24 18:35:55 -0700436 // No JDWP for you!
437 return;
438 }
439
Elliott Hughes475fc232011-10-25 15:00:35 -0700440 CHECK(gRegistry == NULL);
441 gRegistry = new ObjectRegistry;
442
Elliott Hughesd1cc8362011-10-24 16:58:50 -0700443 // Init JDWP if the debugger is enabled. This may connect out to a
444 // debugger, passively listen for a debugger, or block waiting for a
445 // debugger.
Elliott Hughes376a7a02011-10-24 18:35:55 -0700446 gJdwpState = JDWP::JdwpState::Create(&gJdwpOptions);
447 if (gJdwpState == NULL) {
Elliott Hughesf8a2df72011-12-01 12:19:54 -0800448 // We probably failed because some other process has the port already, which means that
449 // if we don't abort the user is likely to think they're talking to us when they're actually
450 // talking to that other process.
Elliott Hughes3d30d9b2011-12-07 17:35:48 -0800451 LOG(FATAL) << "Debugger thread failed to initialize";
Elliott Hughesd1cc8362011-10-24 16:58:50 -0700452 }
453
454 // If a debugger has already attached, send the "welcome" message.
455 // This may cause us to suspend all threads.
Elliott Hughes376a7a02011-10-24 18:35:55 -0700456 if (gJdwpState->IsActive()) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700457 ScopedObjectAccess soa(Thread::Current());
Elliott Hughes376a7a02011-10-24 18:35:55 -0700458 if (!gJdwpState->PostVMStart()) {
Elliott Hughes3d30d9b2011-12-07 17:35:48 -0800459 LOG(WARNING) << "Failed to post 'start' message to debugger";
Elliott Hughesd1cc8362011-10-24 16:58:50 -0700460 }
461 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700462}
463
Elliott Hughesd1cc8362011-10-24 16:58:50 -0700464void Dbg::StopJdwp() {
Elliott Hughes376a7a02011-10-24 18:35:55 -0700465 delete gJdwpState;
Elliott Hughes475fc232011-10-25 15:00:35 -0700466 delete gRegistry;
467 gRegistry = NULL;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700468}
469
Elliott Hughes767a1472011-10-26 18:49:02 -0700470void Dbg::GcDidFinish() {
471 if (gDdmHpifWhen != HPIF_WHEN_NEVER) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700472 ScopedObjectAccess soa(Thread::Current());
Elliott Hughes81ff3182012-03-23 20:35:56 -0700473 LOG(DEBUG) << "Sending heap info to DDM";
Elliott Hughes7162ad92011-10-27 14:08:42 -0700474 DdmSendHeapInfo(gDdmHpifWhen);
Elliott Hughes767a1472011-10-26 18:49:02 -0700475 }
476 if (gDdmHpsgWhen != HPSG_WHEN_NEVER) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700477 ScopedObjectAccess soa(Thread::Current());
Elliott Hughes81ff3182012-03-23 20:35:56 -0700478 LOG(DEBUG) << "Dumping heap to DDM";
Elliott Hughes6a5bd492011-10-28 14:33:57 -0700479 DdmSendHeapSegments(false);
Elliott Hughes767a1472011-10-26 18:49:02 -0700480 }
481 if (gDdmNhsgWhen != HPSG_WHEN_NEVER) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700482 ScopedObjectAccess soa(Thread::Current());
Elliott Hughes767a1472011-10-26 18:49:02 -0700483 LOG(DEBUG) << "Dumping native heap to DDM";
Elliott Hughes6a5bd492011-10-28 14:33:57 -0700484 DdmSendHeapSegments(true);
Elliott Hughes767a1472011-10-26 18:49:02 -0700485 }
486}
487
Elliott Hughes4ffd3132011-10-24 12:06:42 -0700488void Dbg::SetJdwpAllowed(bool allowed) {
489 gJdwpAllowed = allowed;
490}
491
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700492DebugInvokeReq* Dbg::GetInvokeReq() {
Elliott Hughes475fc232011-10-25 15:00:35 -0700493 return Thread::Current()->GetInvokeReq();
494}
495
496Thread* Dbg::GetDebugThread() {
497 return (gJdwpState != NULL) ? gJdwpState->GetDebugThread() : NULL;
498}
499
500void Dbg::ClearWaitForEventThread() {
501 gJdwpState->ClearWaitForEventThread();
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700502}
503
504void Dbg::Connected() {
Elliott Hughes3bb81562011-10-21 18:52:59 -0700505 CHECK(!gDebuggerConnected);
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -0800506 VLOG(jdwp) << "JDWP has attached";
Elliott Hughes3bb81562011-10-21 18:52:59 -0700507 gDebuggerConnected = true;
Elliott Hughes86964332012-02-15 19:37:42 -0800508 gDisposed = false;
509}
510
511void Dbg::Disposed() {
512 gDisposed = true;
513}
514
515bool Dbg::IsDisposed() {
516 return gDisposed;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700517}
518
Elliott Hughesa2155262011-11-16 16:26:58 -0800519void Dbg::GoActive() {
520 // Enable all debugging features, including scans for breakpoints.
521 // This is a no-op if we're already active.
522 // Only called from the JDWP handler thread.
523 if (gDebuggerActive) {
524 return;
525 }
526
Elliott Hughesc0f09332012-03-26 13:27:06 -0700527 {
528 // TODO: dalvik only warned if there were breakpoints left over. clear in Dbg::Disconnected?
jeffhao09bfc6a2012-12-11 18:11:43 -0800529 MutexLock mu(Thread::Current(), *Locks::breakpoint_lock_);
Elliott Hughesc0f09332012-03-26 13:27:06 -0700530 CHECK_EQ(gBreakpoints.size(), 0U);
531 }
Elliott Hughesa2155262011-11-16 16:26:58 -0800532
Ian Rogers62d6c772013-02-27 08:32:07 -0800533 Runtime* runtime = Runtime::Current();
534 runtime->GetThreadList()->SuspendAll();
535 Thread* self = Thread::Current();
536 ThreadState old_state = self->SetStateUnsafe(kRunnable);
537 CHECK_NE(old_state, kRunnable);
538 runtime->GetInstrumentation()->AddListener(&gDebugInstrumentationListener,
539 instrumentation::Instrumentation::kMethodEntered |
540 instrumentation::Instrumentation::kMethodExited |
541 instrumentation::Instrumentation::kDexPcMoved);
Elliott Hughesa2155262011-11-16 16:26:58 -0800542 gDebuggerActive = true;
Ian Rogers62d6c772013-02-27 08:32:07 -0800543 CHECK_EQ(self->SetStateUnsafe(old_state), kRunnable);
544 runtime->GetThreadList()->ResumeAll();
545
546 LOG(INFO) << "Debugger is active";
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700547}
548
549void Dbg::Disconnected() {
Elliott Hughes234ab152011-10-26 14:02:26 -0700550 CHECK(gDebuggerConnected);
551
Elliott Hughesc0f09332012-03-26 13:27:06 -0700552 LOG(INFO) << "Debugger is no longer active";
Elliott Hughes234ab152011-10-26 14:02:26 -0700553
Ian Rogers62d6c772013-02-27 08:32:07 -0800554 // Suspend all threads and exclusively acquire the mutator lock. Set the state of the thread
555 // to kRunnable to avoid scoped object access transitions. Remove the debugger as a listener
556 // and clear the object registry.
557 Runtime* runtime = Runtime::Current();
558 runtime->GetThreadList()->SuspendAll();
559 Thread* self = Thread::Current();
560 ThreadState old_state = self->SetStateUnsafe(kRunnable);
561 runtime->GetInstrumentation()->RemoveListener(&gDebugInstrumentationListener,
562 instrumentation::Instrumentation::kMethodEntered |
563 instrumentation::Instrumentation::kMethodExited |
564 instrumentation::Instrumentation::kDexPcMoved);
Elliott Hughesc0f09332012-03-26 13:27:06 -0700565 gDebuggerActive = false;
Elliott Hughes234ab152011-10-26 14:02:26 -0700566 gRegistry->Clear();
567 gDebuggerConnected = false;
Ian Rogers62d6c772013-02-27 08:32:07 -0800568 CHECK_EQ(self->SetStateUnsafe(old_state), kRunnable);
569 runtime->GetThreadList()->ResumeAll();
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700570}
571
Elliott Hughesc0f09332012-03-26 13:27:06 -0700572bool Dbg::IsDebuggerActive() {
Elliott Hughes3bb81562011-10-21 18:52:59 -0700573 return gDebuggerActive;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700574}
575
Elliott Hughesc0f09332012-03-26 13:27:06 -0700576bool Dbg::IsJdwpConfigured() {
Elliott Hughes3bb81562011-10-21 18:52:59 -0700577 return gJdwpConfigured;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700578}
579
580int64_t Dbg::LastDebuggerActivity() {
Elliott Hughesca951522011-12-05 12:01:32 -0800581 return gJdwpState->LastDebuggerActivity();
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700582}
583
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700584void Dbg::UndoDebuggerSuspensions() {
Elliott Hughes234ab152011-10-26 14:02:26 -0700585 Runtime::Current()->GetThreadList()->UndoDebuggerSuspensions();
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700586}
587
Elliott Hughes88d63092013-01-09 09:55:54 -0800588std::string Dbg::GetClassName(JDWP::RefTypeId class_id) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800589 mirror::Object* o = gRegistry->Get<mirror::Object*>(class_id);
Elliott Hughes436e3722012-02-17 20:01:47 -0800590 if (o == NULL) {
591 return "NULL";
592 }
Elliott Hughes64f574f2013-02-20 14:57:12 -0800593 if (o == ObjectRegistry::kInvalidObject) {
Elliott Hughes88d63092013-01-09 09:55:54 -0800594 return StringPrintf("invalid object %p", reinterpret_cast<void*>(class_id));
Elliott Hughes436e3722012-02-17 20:01:47 -0800595 }
596 if (!o->IsClass()) {
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -0800597 return StringPrintf("non-class %p", o); // This is only used for debugging output anyway.
598 }
Elliott Hughesc308a5d2012-02-16 17:12:06 -0800599 return DescriptorToName(ClassHelper(o->AsClass()).GetDescriptor());
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700600}
601
Elliott Hughes88d63092013-01-09 09:55:54 -0800602JDWP::JdwpError Dbg::GetClassObject(JDWP::RefTypeId id, JDWP::ObjectId& class_object_id) {
Elliott Hughes436e3722012-02-17 20:01:47 -0800603 JDWP::JdwpError status;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800604 mirror::Class* c = DecodeClass(id, status);
Elliott Hughes436e3722012-02-17 20:01:47 -0800605 if (c == NULL) {
606 return status;
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -0800607 }
Elliott Hughes88d63092013-01-09 09:55:54 -0800608 class_object_id = gRegistry->Add(c);
Elliott Hughes436e3722012-02-17 20:01:47 -0800609 return JDWP::ERR_NONE;
Elliott Hughes86964332012-02-15 19:37:42 -0800610}
611
Elliott Hughes88d63092013-01-09 09:55:54 -0800612JDWP::JdwpError Dbg::GetSuperclass(JDWP::RefTypeId id, JDWP::RefTypeId& superclass_id) {
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -0800613 JDWP::JdwpError status;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800614 mirror::Class* c = DecodeClass(id, status);
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -0800615 if (c == NULL) {
616 return status;
617 }
618 if (c->IsInterface()) {
619 // http://code.google.com/p/android/issues/detail?id=20856
Elliott Hughes88d63092013-01-09 09:55:54 -0800620 superclass_id = 0;
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -0800621 } else {
Elliott Hughes88d63092013-01-09 09:55:54 -0800622 superclass_id = gRegistry->Add(c->GetSuperClass());
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -0800623 }
624 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700625}
626
Elliott Hughes436e3722012-02-17 20:01:47 -0800627JDWP::JdwpError Dbg::GetClassLoader(JDWP::RefTypeId id, JDWP::ExpandBuf* pReply) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800628 mirror::Object* o = gRegistry->Get<mirror::Object*>(id);
Elliott Hughes64f574f2013-02-20 14:57:12 -0800629 if (o == NULL || o == ObjectRegistry::kInvalidObject) {
Elliott Hughes436e3722012-02-17 20:01:47 -0800630 return JDWP::ERR_INVALID_OBJECT;
631 }
632 expandBufAddObjectId(pReply, gRegistry->Add(o->GetClass()->GetClassLoader()));
633 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700634}
635
Elliott Hughes436e3722012-02-17 20:01:47 -0800636JDWP::JdwpError Dbg::GetModifiers(JDWP::RefTypeId id, JDWP::ExpandBuf* pReply) {
637 JDWP::JdwpError status;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800638 mirror::Class* c = DecodeClass(id, status);
Elliott Hughes436e3722012-02-17 20:01:47 -0800639 if (c == NULL) {
640 return status;
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -0800641 }
Elliott Hughes436e3722012-02-17 20:01:47 -0800642
643 uint32_t access_flags = c->GetAccessFlags() & kAccJavaFlagsMask;
644
645 // Set ACC_SUPER; dex files don't contain this flag, but all classes are supposed to have it set.
646 // Class.getModifiers doesn't return it, but JDWP does, so we set it here.
647 access_flags |= kAccSuper;
648
649 expandBufAdd4BE(pReply, access_flags);
650
651 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700652}
653
Elliott Hughesf327e072013-01-09 16:01:26 -0800654JDWP::JdwpError Dbg::GetMonitorInfo(JDWP::ObjectId object_id, JDWP::ExpandBuf* reply)
655 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800656 mirror::Object* o = gRegistry->Get<mirror::Object*>(object_id);
Elliott Hughes64f574f2013-02-20 14:57:12 -0800657 if (o == NULL || o == ObjectRegistry::kInvalidObject) {
Elliott Hughesf327e072013-01-09 16:01:26 -0800658 return JDWP::ERR_INVALID_OBJECT;
659 }
660
661 // Ensure all threads are suspended while we read objects' lock words.
662 Thread* self = Thread::Current();
663 Locks::mutator_lock_->SharedUnlock(self);
664 Locks::mutator_lock_->ExclusiveLock(self);
665
666 MonitorInfo monitor_info(o);
667
668 Locks::mutator_lock_->ExclusiveUnlock(self);
669 Locks::mutator_lock_->SharedLock(self);
670
671 if (monitor_info.owner != NULL) {
672 expandBufAddObjectId(reply, gRegistry->Add(monitor_info.owner->GetPeer()));
673 } else {
674 expandBufAddObjectId(reply, gRegistry->Add(NULL));
675 }
676 expandBufAdd4BE(reply, monitor_info.entry_count);
677 expandBufAdd4BE(reply, monitor_info.waiters.size());
678 for (size_t i = 0; i < monitor_info.waiters.size(); ++i) {
679 expandBufAddObjectId(reply, gRegistry->Add(monitor_info.waiters[i]->GetPeer()));
680 }
681 return JDWP::ERR_NONE;
682}
683
Elliott Hughes734b8c62013-01-11 15:32:45 -0800684JDWP::JdwpError Dbg::GetOwnedMonitors(JDWP::ObjectId thread_id,
685 std::vector<JDWP::ObjectId>& monitors,
686 std::vector<uint32_t>& stack_depths)
Elliott Hughes4993bbc2013-01-10 15:41:25 -0800687 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
688 ScopedObjectAccessUnchecked soa(Thread::Current());
689 MutexLock mu(soa.Self(), *Locks::thread_list_lock_);
690 Thread* thread;
691 JDWP::JdwpError error = DecodeThread(soa, thread_id, thread);
692 if (error != JDWP::ERR_NONE) {
693 return error;
694 }
695 if (!IsSuspendedForDebugger(soa, thread)) {
696 return JDWP::ERR_THREAD_NOT_SUSPENDED;
697 }
698
699 struct OwnedMonitorVisitor : public StackVisitor {
Ian Rogers7a22fa62013-01-23 12:16:16 -0800700 OwnedMonitorVisitor(Thread* thread, Context* context)
Elliott Hughes4993bbc2013-01-10 15:41:25 -0800701 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_)
Ian Rogers7a22fa62013-01-23 12:16:16 -0800702 : StackVisitor(thread, context), current_stack_depth(0) {}
Elliott Hughes4993bbc2013-01-10 15:41:25 -0800703
704 // TODO: Enable annotalysis. We know lock is held in constructor, but abstraction confuses
705 // annotalysis.
706 bool VisitFrame() NO_THREAD_SAFETY_ANALYSIS {
707 if (!GetMethod()->IsRuntimeMethod()) {
708 Monitor::VisitLocks(this, AppendOwnedMonitors, this);
Elliott Hughes734b8c62013-01-11 15:32:45 -0800709 ++current_stack_depth;
Elliott Hughes4993bbc2013-01-10 15:41:25 -0800710 }
711 return true;
712 }
713
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800714 static void AppendOwnedMonitors(mirror::Object* owned_monitor, void* arg) {
Ian Rogers7a22fa62013-01-23 12:16:16 -0800715 OwnedMonitorVisitor* visitor = reinterpret_cast<OwnedMonitorVisitor*>(arg);
Elliott Hughes734b8c62013-01-11 15:32:45 -0800716 visitor->monitors.push_back(owned_monitor);
717 visitor->stack_depths.push_back(visitor->current_stack_depth);
Elliott Hughes4993bbc2013-01-10 15:41:25 -0800718 }
719
Elliott Hughes734b8c62013-01-11 15:32:45 -0800720 size_t current_stack_depth;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800721 std::vector<mirror::Object*> monitors;
Elliott Hughes734b8c62013-01-11 15:32:45 -0800722 std::vector<uint32_t> stack_depths;
Elliott Hughes4993bbc2013-01-10 15:41:25 -0800723 };
Ian Rogers7a22fa62013-01-23 12:16:16 -0800724 UniquePtr<Context> context(Context::Create());
725 OwnedMonitorVisitor visitor(thread, context.get());
Elliott Hughes4993bbc2013-01-10 15:41:25 -0800726 visitor.WalkStack();
727
728 for (size_t i = 0; i < visitor.monitors.size(); ++i) {
729 monitors.push_back(gRegistry->Add(visitor.monitors[i]));
Elliott Hughes734b8c62013-01-11 15:32:45 -0800730 stack_depths.push_back(visitor.stack_depths[i]);
Elliott Hughes4993bbc2013-01-10 15:41:25 -0800731 }
732
733 return JDWP::ERR_NONE;
734}
735
Elliott Hughesf9501702013-01-11 11:22:27 -0800736JDWP::JdwpError Dbg::GetContendedMonitor(JDWP::ObjectId thread_id, JDWP::ObjectId& contended_monitor)
737 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
738 ScopedObjectAccessUnchecked soa(Thread::Current());
739 MutexLock mu(soa.Self(), *Locks::thread_list_lock_);
740 Thread* thread;
741 JDWP::JdwpError error = DecodeThread(soa, thread_id, thread);
742 if (error != JDWP::ERR_NONE) {
743 return error;
744 }
745 if (!IsSuspendedForDebugger(soa, thread)) {
746 return JDWP::ERR_THREAD_NOT_SUSPENDED;
747 }
748
749 contended_monitor = gRegistry->Add(Monitor::GetContendedMonitor(thread));
750
751 return JDWP::ERR_NONE;
752}
753
Elliott Hughesec0f83d2013-01-15 16:54:08 -0800754JDWP::JdwpError Dbg::GetInstanceCounts(const std::vector<JDWP::RefTypeId>& class_ids,
755 std::vector<uint64_t>& counts)
756 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
757
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800758 std::vector<mirror::Class*> classes;
Elliott Hughesec0f83d2013-01-15 16:54:08 -0800759 counts.clear();
760 for (size_t i = 0; i < class_ids.size(); ++i) {
761 JDWP::JdwpError status;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800762 mirror::Class* c = DecodeClass(class_ids[i], status);
Elliott Hughesec0f83d2013-01-15 16:54:08 -0800763 if (c == NULL) {
764 return status;
765 }
766 classes.push_back(c);
767 counts.push_back(0);
768 }
769
770 Runtime::Current()->GetHeap()->CountInstances(classes, false, &counts[0]);
771 return JDWP::ERR_NONE;
772}
773
Elliott Hughes3b78c942013-01-15 17:35:41 -0800774JDWP::JdwpError Dbg::GetInstances(JDWP::RefTypeId class_id, int32_t max_count, std::vector<JDWP::ObjectId>& instances)
775 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
776 JDWP::JdwpError status;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800777 mirror::Class* c = DecodeClass(class_id, status);
Elliott Hughes3b78c942013-01-15 17:35:41 -0800778 if (c == NULL) {
779 return status;
780 }
781
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800782 std::vector<mirror::Object*> raw_instances;
Elliott Hughes3b78c942013-01-15 17:35:41 -0800783 Runtime::Current()->GetHeap()->GetInstances(c, max_count, raw_instances);
784 for (size_t i = 0; i < raw_instances.size(); ++i) {
785 instances.push_back(gRegistry->Add(raw_instances[i]));
786 }
787 return JDWP::ERR_NONE;
788}
789
Elliott Hughes0cbaff52013-01-16 15:28:01 -0800790JDWP::JdwpError Dbg::GetReferringObjects(JDWP::ObjectId object_id, int32_t max_count,
791 std::vector<JDWP::ObjectId>& referring_objects)
792 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800793 mirror::Object* o = gRegistry->Get<mirror::Object*>(object_id);
Elliott Hughes64f574f2013-02-20 14:57:12 -0800794 if (o == NULL || o == ObjectRegistry::kInvalidObject) {
Elliott Hughes0cbaff52013-01-16 15:28:01 -0800795 return JDWP::ERR_INVALID_OBJECT;
796 }
797
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800798 std::vector<mirror::Object*> raw_instances;
Elliott Hughes0cbaff52013-01-16 15:28:01 -0800799 Runtime::Current()->GetHeap()->GetReferringObjects(o, max_count, raw_instances);
800 for (size_t i = 0; i < raw_instances.size(); ++i) {
801 referring_objects.push_back(gRegistry->Add(raw_instances[i]));
802 }
803 return JDWP::ERR_NONE;
804}
805
Elliott Hughes64f574f2013-02-20 14:57:12 -0800806JDWP::JdwpError Dbg::DisableCollection(JDWP::ObjectId object_id)
807 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
808 gRegistry->DisableCollection(object_id);
809 return JDWP::ERR_NONE;
810}
811
812JDWP::JdwpError Dbg::EnableCollection(JDWP::ObjectId object_id)
813 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
814 gRegistry->EnableCollection(object_id);
815 return JDWP::ERR_NONE;
816}
817
818JDWP::JdwpError Dbg::IsCollected(JDWP::ObjectId object_id, bool& is_collected)
819 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
820 is_collected = gRegistry->IsCollected(object_id);
821 return JDWP::ERR_NONE;
822}
823
824void Dbg::DisposeObject(JDWP::ObjectId object_id, uint32_t reference_count)
825 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
826 gRegistry->DisposeObject(object_id, reference_count);
827}
828
Elliott Hughes88d63092013-01-09 09:55:54 -0800829JDWP::JdwpError Dbg::GetReflectedType(JDWP::RefTypeId class_id, JDWP::ExpandBuf* pReply) {
Elliott Hughes436e3722012-02-17 20:01:47 -0800830 JDWP::JdwpError status;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800831 mirror::Class* c = DecodeClass(class_id, status);
Elliott Hughes436e3722012-02-17 20:01:47 -0800832 if (c == NULL) {
833 return status;
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -0800834 }
Elliott Hughes436e3722012-02-17 20:01:47 -0800835
836 expandBufAdd1(pReply, c->IsInterface() ? JDWP::TT_INTERFACE : JDWP::TT_CLASS);
Elliott Hughes88d63092013-01-09 09:55:54 -0800837 expandBufAddRefTypeId(pReply, class_id);
Elliott Hughes436e3722012-02-17 20:01:47 -0800838 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700839}
840
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -0800841void Dbg::GetClassList(std::vector<JDWP::RefTypeId>& classes) {
Elliott Hughesa2155262011-11-16 16:26:58 -0800842 // Get the complete list of reference classes (i.e. all classes except
843 // the primitive types).
844 // Returns a newly-allocated buffer full of RefTypeId values.
845 struct ClassListCreator {
Elliott Hughesba8eee12012-01-24 20:25:24 -0800846 explicit ClassListCreator(std::vector<JDWP::RefTypeId>& classes) : classes(classes) {
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -0800847 }
848
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800849 static bool Visit(mirror::Class* c, void* arg) {
Elliott Hughesa2155262011-11-16 16:26:58 -0800850 return reinterpret_cast<ClassListCreator*>(arg)->Visit(c);
851 }
852
Elliott Hughes64f574f2013-02-20 14:57:12 -0800853 // TODO: Enable annotalysis. We know lock is held in constructor, but abstraction confuses
854 // annotalysis.
855 bool Visit(mirror::Class* c) NO_THREAD_SAFETY_ANALYSIS {
Elliott Hughesa2155262011-11-16 16:26:58 -0800856 if (!c->IsPrimitive()) {
Elliott Hughes64f574f2013-02-20 14:57:12 -0800857 classes.push_back(gRegistry->AddRefType(c));
Elliott Hughesa2155262011-11-16 16:26:58 -0800858 }
859 return true;
860 }
861
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -0800862 std::vector<JDWP::RefTypeId>& classes;
Elliott Hughesa2155262011-11-16 16:26:58 -0800863 };
864
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -0800865 ClassListCreator clc(classes);
Elliott Hughesa2155262011-11-16 16:26:58 -0800866 Runtime::Current()->GetClassLinker()->VisitClasses(ClassListCreator::Visit, &clc);
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700867}
868
Elliott Hughes88d63092013-01-09 09:55:54 -0800869JDWP::JdwpError Dbg::GetClassInfo(JDWP::RefTypeId class_id, JDWP::JdwpTypeTag* pTypeTag, uint32_t* pStatus, std::string* pDescriptor) {
Elliott Hughes436e3722012-02-17 20:01:47 -0800870 JDWP::JdwpError status;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800871 mirror::Class* c = DecodeClass(class_id, status);
Elliott Hughes436e3722012-02-17 20:01:47 -0800872 if (c == NULL) {
873 return status;
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -0800874 }
875
Elliott Hughesa2155262011-11-16 16:26:58 -0800876 if (c->IsArrayClass()) {
877 *pStatus = JDWP::CS_VERIFIED | JDWP::CS_PREPARED;
878 *pTypeTag = JDWP::TT_ARRAY;
879 } else {
880 if (c->IsErroneous()) {
881 *pStatus = JDWP::CS_ERROR;
882 } else {
883 *pStatus = JDWP::CS_VERIFIED | JDWP::CS_PREPARED | JDWP::CS_INITIALIZED;
884 }
885 *pTypeTag = c->IsInterface() ? JDWP::TT_INTERFACE : JDWP::TT_CLASS;
886 }
887
888 if (pDescriptor != NULL) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800889 *pDescriptor = ClassHelper(c).GetDescriptor();
Elliott Hughesa2155262011-11-16 16:26:58 -0800890 }
Elliott Hughes436e3722012-02-17 20:01:47 -0800891 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700892}
893
Elliott Hughesc3b77c72011-12-15 20:56:48 -0800894void Dbg::FindLoadedClassBySignature(const char* descriptor, std::vector<JDWP::RefTypeId>& ids) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800895 std::vector<mirror::Class*> classes;
Elliott Hughes6fa602d2011-12-02 17:54:25 -0800896 Runtime::Current()->GetClassLinker()->LookupClasses(descriptor, classes);
897 ids.clear();
898 for (size_t i = 0; i < classes.size(); ++i) {
899 ids.push_back(gRegistry->Add(classes[i]));
900 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700901}
902
Elliott Hughes64f574f2013-02-20 14:57:12 -0800903JDWP::JdwpError Dbg::GetReferenceType(JDWP::ObjectId object_id, JDWP::ExpandBuf* pReply)
904 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800905 mirror::Object* o = gRegistry->Get<mirror::Object*>(object_id);
Elliott Hughes64f574f2013-02-20 14:57:12 -0800906 if (o == NULL || o == ObjectRegistry::kInvalidObject) {
Elliott Hughes2435a572012-02-17 16:07:41 -0800907 return JDWP::ERR_INVALID_OBJECT;
Elliott Hughes499c5132011-11-17 14:55:11 -0800908 }
Elliott Hughes2435a572012-02-17 16:07:41 -0800909
910 JDWP::JdwpTypeTag type_tag;
911 if (o->GetClass()->IsArrayClass()) {
912 type_tag = JDWP::TT_ARRAY;
913 } else if (o->GetClass()->IsInterface()) {
914 type_tag = JDWP::TT_INTERFACE;
915 } else {
916 type_tag = JDWP::TT_CLASS;
917 }
Elliott Hughes64f574f2013-02-20 14:57:12 -0800918 JDWP::RefTypeId type_id = gRegistry->AddRefType(o->GetClass());
Elliott Hughes2435a572012-02-17 16:07:41 -0800919
920 expandBufAdd1(pReply, type_tag);
921 expandBufAddRefTypeId(pReply, type_id);
922
923 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700924}
925
Elliott Hughes88d63092013-01-09 09:55:54 -0800926JDWP::JdwpError Dbg::GetSignature(JDWP::RefTypeId class_id, std::string& signature) {
Elliott Hughes1fe7afb2012-02-13 17:23:03 -0800927 JDWP::JdwpError status;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800928 mirror::Class* c = DecodeClass(class_id, status);
Elliott Hughes1fe7afb2012-02-13 17:23:03 -0800929 if (c == NULL) {
930 return status;
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -0800931 }
Elliott Hughes1fe7afb2012-02-13 17:23:03 -0800932 signature = ClassHelper(c).GetDescriptor();
933 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700934}
935
Elliott Hughes88d63092013-01-09 09:55:54 -0800936JDWP::JdwpError Dbg::GetSourceFile(JDWP::RefTypeId class_id, std::string& result) {
Elliott Hughes436e3722012-02-17 20:01:47 -0800937 JDWP::JdwpError status;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800938 mirror::Class* c = DecodeClass(class_id, status);
Elliott Hughes436e3722012-02-17 20:01:47 -0800939 if (c == NULL) {
940 return status;
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -0800941 }
Elliott Hughes436e3722012-02-17 20:01:47 -0800942 result = ClassHelper(c).GetSourceFile();
943 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700944}
945
Elliott Hughes88d63092013-01-09 09:55:54 -0800946JDWP::JdwpError Dbg::GetObjectTag(JDWP::ObjectId object_id, uint8_t& tag) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800947 mirror::Object* o = gRegistry->Get<mirror::Object*>(object_id);
Elliott Hughes64f574f2013-02-20 14:57:12 -0800948 if (o == ObjectRegistry::kInvalidObject) {
Elliott Hughes546b9862012-06-20 16:06:13 -0700949 return JDWP::ERR_INVALID_OBJECT;
950 }
951 tag = TagFromObject(o);
952 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700953}
954
Elliott Hughesaed4be92011-12-02 16:16:23 -0800955size_t Dbg::GetTagWidth(JDWP::JdwpTag tag) {
Elliott Hughesdbb40792011-11-18 17:05:22 -0800956 switch (tag) {
957 case JDWP::JT_VOID:
958 return 0;
959 case JDWP::JT_BYTE:
960 case JDWP::JT_BOOLEAN:
961 return 1;
962 case JDWP::JT_CHAR:
963 case JDWP::JT_SHORT:
964 return 2;
965 case JDWP::JT_FLOAT:
966 case JDWP::JT_INT:
967 return 4;
968 case JDWP::JT_ARRAY:
969 case JDWP::JT_OBJECT:
970 case JDWP::JT_STRING:
971 case JDWP::JT_THREAD:
972 case JDWP::JT_THREAD_GROUP:
973 case JDWP::JT_CLASS_LOADER:
974 case JDWP::JT_CLASS_OBJECT:
975 return sizeof(JDWP::ObjectId);
976 case JDWP::JT_DOUBLE:
977 case JDWP::JT_LONG:
978 return 8;
979 default:
Elliott Hughes3d30d9b2011-12-07 17:35:48 -0800980 LOG(FATAL) << "Unknown tag " << tag;
Elliott Hughesdbb40792011-11-18 17:05:22 -0800981 return -1;
982 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700983}
984
Elliott Hughes88d63092013-01-09 09:55:54 -0800985JDWP::JdwpError Dbg::GetArrayLength(JDWP::ObjectId array_id, int& length) {
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;
Elliott Hughes24437992011-11-30 14:49:33 -0800990 }
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -0800991 length = a->GetLength();
992 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700993}
994
Elliott Hughes88d63092013-01-09 09:55:54 -0800995JDWP::JdwpError Dbg::OutputArray(JDWP::ObjectId array_id, int offset, int count, JDWP::ExpandBuf* pReply) {
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -0800996 JDWP::JdwpError status;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800997 mirror::Array* a = DecodeArray(array_id, status);
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -0800998 if (a == NULL) {
999 return status;
1000 }
Elliott Hughes24437992011-11-30 14:49:33 -08001001
1002 if (offset < 0 || count < 0 || offset > a->GetLength() || a->GetLength() - offset < count) {
1003 LOG(WARNING) << __FUNCTION__ << " access out of bounds: offset=" << offset << "; count=" << count;
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -08001004 return JDWP::ERR_INVALID_LENGTH;
Elliott Hughes24437992011-11-30 14:49:33 -08001005 }
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001006 std::string descriptor(ClassHelper(a->GetClass()).GetDescriptor());
Elliott Hughes24437992011-11-30 14:49:33 -08001007 JDWP::JdwpTag tag = BasicTagFromDescriptor(descriptor.c_str() + 1);
1008
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -08001009 expandBufAdd1(pReply, tag);
1010 expandBufAdd4BE(pReply, count);
1011
Elliott Hughes24437992011-11-30 14:49:33 -08001012 if (IsPrimitiveTag(tag)) {
1013 size_t width = GetTagWidth(tag);
Elliott Hughes24437992011-11-30 14:49:33 -08001014 uint8_t* dst = expandBufAddSpace(pReply, count * width);
1015 if (width == 8) {
Ian Rogersa15e67d2012-02-28 13:51:55 -08001016 const uint64_t* src8 = reinterpret_cast<uint64_t*>(a->GetRawData(sizeof(uint64_t)));
Elliott Hughes24437992011-11-30 14:49:33 -08001017 for (int i = 0; i < count; ++i) JDWP::Write8BE(&dst, src8[offset + i]);
1018 } else if (width == 4) {
Ian Rogersa15e67d2012-02-28 13:51:55 -08001019 const uint32_t* src4 = reinterpret_cast<uint32_t*>(a->GetRawData(sizeof(uint32_t)));
Elliott Hughes24437992011-11-30 14:49:33 -08001020 for (int i = 0; i < count; ++i) JDWP::Write4BE(&dst, src4[offset + i]);
1021 } else if (width == 2) {
Ian Rogersa15e67d2012-02-28 13:51:55 -08001022 const uint16_t* src2 = reinterpret_cast<uint16_t*>(a->GetRawData(sizeof(uint16_t)));
Elliott Hughes24437992011-11-30 14:49:33 -08001023 for (int i = 0; i < count; ++i) JDWP::Write2BE(&dst, src2[offset + i]);
1024 } else {
Ian Rogersa15e67d2012-02-28 13:51:55 -08001025 const uint8_t* src = reinterpret_cast<uint8_t*>(a->GetRawData(sizeof(uint8_t)));
Elliott Hughes24437992011-11-30 14:49:33 -08001026 memcpy(dst, &src[offset * width], count * width);
1027 }
1028 } else {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001029 mirror::ObjectArray<mirror::Object>* oa = a->AsObjectArray<mirror::Object>();
Elliott Hughes24437992011-11-30 14:49:33 -08001030 for (int i = 0; i < count; ++i) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001031 mirror::Object* element = oa->Get(offset + i);
Elliott Hughes24437992011-11-30 14:49:33 -08001032 JDWP::JdwpTag specific_tag = (element != NULL) ? TagFromObject(element) : tag;
1033 expandBufAdd1(pReply, specific_tag);
1034 expandBufAddObjectId(pReply, gRegistry->Add(element));
1035 }
1036 }
1037
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -08001038 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001039}
1040
Elliott Hughes4b9702c2013-02-20 18:13:24 -08001041template <typename T> void CopyArrayData(mirror::Array* a, JDWP::Request& src, int offset, int count) {
1042 DCHECK(a->GetClass()->IsPrimitiveArray());
1043
1044 T* dst = &(reinterpret_cast<T*>(a->GetRawData(sizeof(T)))[offset * sizeof(T)]);
1045 for (int i = 0; i < count; ++i) {
1046 *dst++ = src.ReadValue(sizeof(T));
1047 }
1048}
1049
Elliott Hughes88d63092013-01-09 09:55:54 -08001050JDWP::JdwpError Dbg::SetArrayElements(JDWP::ObjectId array_id, int offset, int count,
Elliott Hughes4b9702c2013-02-20 18:13:24 -08001051 JDWP::Request& request)
Ian Rogersb726dcb2012-09-05 08:57:23 -07001052 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -08001053 JDWP::JdwpError status;
Elliott Hughes4b9702c2013-02-20 18:13:24 -08001054 mirror::Array* dst = DecodeArray(array_id, status);
1055 if (dst == NULL) {
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -08001056 return status;
1057 }
Elliott Hughesf03b8f62011-12-02 14:26:25 -08001058
Elliott Hughes4b9702c2013-02-20 18:13:24 -08001059 if (offset < 0 || count < 0 || offset > dst->GetLength() || dst->GetLength() - offset < count) {
Elliott Hughesf03b8f62011-12-02 14:26:25 -08001060 LOG(WARNING) << __FUNCTION__ << " access out of bounds: offset=" << offset << "; count=" << count;
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -08001061 return JDWP::ERR_INVALID_LENGTH;
Elliott Hughesf03b8f62011-12-02 14:26:25 -08001062 }
Elliott Hughes4b9702c2013-02-20 18:13:24 -08001063 std::string descriptor(ClassHelper(dst->GetClass()).GetDescriptor());
Elliott Hughesf03b8f62011-12-02 14:26:25 -08001064 JDWP::JdwpTag tag = BasicTagFromDescriptor(descriptor.c_str() + 1);
1065
1066 if (IsPrimitiveTag(tag)) {
1067 size_t width = GetTagWidth(tag);
Elliott Hughesf03b8f62011-12-02 14:26:25 -08001068 if (width == 8) {
Elliott Hughes4b9702c2013-02-20 18:13:24 -08001069 CopyArrayData<uint64_t>(dst, request, offset, count);
Elliott Hughesf03b8f62011-12-02 14:26:25 -08001070 } else if (width == 4) {
Elliott Hughes4b9702c2013-02-20 18:13:24 -08001071 CopyArrayData<uint32_t>(dst, request, offset, count);
Elliott Hughesf03b8f62011-12-02 14:26:25 -08001072 } else if (width == 2) {
Elliott Hughes4b9702c2013-02-20 18:13:24 -08001073 CopyArrayData<uint16_t>(dst, request, offset, count);
Elliott Hughesf03b8f62011-12-02 14:26:25 -08001074 } else {
Elliott Hughes4b9702c2013-02-20 18:13:24 -08001075 CopyArrayData<uint8_t>(dst, request, offset, count);
Elliott Hughesf03b8f62011-12-02 14:26:25 -08001076 }
1077 } else {
Elliott Hughes4b9702c2013-02-20 18:13:24 -08001078 mirror::ObjectArray<mirror::Object>* oa = dst->AsObjectArray<mirror::Object>();
Elliott Hughesf03b8f62011-12-02 14:26:25 -08001079 for (int i = 0; i < count; ++i) {
Elliott Hughes4b9702c2013-02-20 18:13:24 -08001080 JDWP::ObjectId id = request.ReadObjectId();
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001081 mirror::Object* o = gRegistry->Get<mirror::Object*>(id);
Elliott Hughes64f574f2013-02-20 14:57:12 -08001082 if (o == ObjectRegistry::kInvalidObject) {
Elliott Hughes436e3722012-02-17 20:01:47 -08001083 return JDWP::ERR_INVALID_OBJECT;
1084 }
1085 oa->Set(offset + i, o);
Elliott Hughesf03b8f62011-12-02 14:26:25 -08001086 }
1087 }
1088
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -08001089 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001090}
1091
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -08001092JDWP::ObjectId Dbg::CreateString(const std::string& str) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001093 return gRegistry->Add(mirror::String::AllocFromModifiedUtf8(Thread::Current(), str.c_str()));
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001094}
1095
Elliott Hughes88d63092013-01-09 09:55:54 -08001096JDWP::JdwpError Dbg::CreateObject(JDWP::RefTypeId class_id, JDWP::ObjectId& new_object) {
Elliott Hughes436e3722012-02-17 20:01:47 -08001097 JDWP::JdwpError status;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001098 mirror::Class* c = DecodeClass(class_id, status);
Elliott Hughes436e3722012-02-17 20:01:47 -08001099 if (c == NULL) {
1100 return status;
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -08001101 }
Ian Rogers50b35e22012-10-04 10:09:15 -07001102 new_object = gRegistry->Add(c->AllocObject(Thread::Current()));
Elliott Hughes436e3722012-02-17 20:01:47 -08001103 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001104}
1105
Elliott Hughesbf13d362011-12-08 15:51:37 -08001106/*
1107 * Used by Eclipse's "Display" view to evaluate "new byte[5]" to get "(byte[]) [0, 0, 0, 0, 0]".
1108 */
Elliott Hughes88d63092013-01-09 09:55:54 -08001109JDWP::JdwpError Dbg::CreateArrayObject(JDWP::RefTypeId array_class_id, uint32_t length,
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001110 JDWP::ObjectId& new_array) {
Elliott Hughes436e3722012-02-17 20:01:47 -08001111 JDWP::JdwpError status;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001112 mirror::Class* c = DecodeClass(array_class_id, status);
Elliott Hughes436e3722012-02-17 20:01:47 -08001113 if (c == NULL) {
1114 return status;
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -08001115 }
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001116 new_array = gRegistry->Add(mirror::Array::Alloc(Thread::Current(), c, length));
Elliott Hughes436e3722012-02-17 20:01:47 -08001117 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001118}
1119
Elliott Hughes88d63092013-01-09 09:55:54 -08001120bool Dbg::MatchType(JDWP::RefTypeId instance_class_id, JDWP::RefTypeId class_id) {
Elliott Hughes436e3722012-02-17 20:01:47 -08001121 JDWP::JdwpError status;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001122 mirror::Class* c1 = DecodeClass(instance_class_id, status);
Elliott Hughesa656a0f2012-02-21 18:03:44 -08001123 CHECK(c1 != NULL);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001124 mirror::Class* c2 = DecodeClass(class_id, status);
Elliott Hughesa656a0f2012-02-21 18:03:44 -08001125 CHECK(c2 != NULL);
1126 return c1->IsAssignableFrom(c2);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001127}
1128
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001129static JDWP::FieldId ToFieldId(const mirror::Field* f)
Ian Rogersb726dcb2012-09-05 08:57:23 -07001130 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Elliott Hughes03181a82011-11-17 17:22:21 -08001131#ifdef MOVING_GARBAGE_COLLECTOR
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001132 UNIMPLEMENTED(FATAL);
Elliott Hughes03181a82011-11-17 17:22:21 -08001133#else
1134 return static_cast<JDWP::FieldId>(reinterpret_cast<uintptr_t>(f));
1135#endif
1136}
1137
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001138static JDWP::MethodId ToMethodId(const mirror::AbstractMethod* m)
Ian Rogersb726dcb2012-09-05 08:57:23 -07001139 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Elliott Hughes03181a82011-11-17 17:22:21 -08001140#ifdef MOVING_GARBAGE_COLLECTOR
1141 UNIMPLEMENTED(FATAL);
1142#else
1143 return static_cast<JDWP::MethodId>(reinterpret_cast<uintptr_t>(m));
1144#endif
1145}
1146
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001147static mirror::Field* FromFieldId(JDWP::FieldId fid)
Ian Rogersb726dcb2012-09-05 08:57:23 -07001148 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Elliott Hughesaed4be92011-12-02 16:16:23 -08001149#ifdef MOVING_GARBAGE_COLLECTOR
1150 UNIMPLEMENTED(FATAL);
1151#else
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001152 return reinterpret_cast<mirror::Field*>(static_cast<uintptr_t>(fid));
Elliott Hughesaed4be92011-12-02 16:16:23 -08001153#endif
1154}
1155
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001156static mirror::AbstractMethod* FromMethodId(JDWP::MethodId mid)
Ian Rogersb726dcb2012-09-05 08:57:23 -07001157 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Elliott Hughes03181a82011-11-17 17:22:21 -08001158#ifdef MOVING_GARBAGE_COLLECTOR
1159 UNIMPLEMENTED(FATAL);
1160#else
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001161 return reinterpret_cast<mirror::AbstractMethod*>(static_cast<uintptr_t>(mid));
Elliott Hughes03181a82011-11-17 17:22:21 -08001162#endif
1163}
1164
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001165static void SetLocation(JDWP::JdwpLocation& location, mirror::AbstractMethod* m, uint32_t dex_pc)
Ian Rogersb726dcb2012-09-05 08:57:23 -07001166 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08001167 if (m == NULL) {
1168 memset(&location, 0, sizeof(location));
1169 } else {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001170 mirror::Class* c = m->GetDeclaringClass();
Elliott Hughes74847412012-06-20 18:10:21 -07001171 location.type_tag = c->IsInterface() ? JDWP::TT_INTERFACE : JDWP::TT_CLASS;
1172 location.class_id = gRegistry->Add(c);
1173 location.method_id = ToMethodId(m);
Ian Rogers0399dde2012-06-06 17:09:28 -07001174 location.dex_pc = dex_pc;
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08001175 }
Elliott Hughesd07986f2011-12-06 18:27:45 -08001176}
1177
Elliott Hughesa96836a2013-01-17 12:27:49 -08001178std::string Dbg::GetMethodName(JDWP::MethodId method_id)
Ian Rogersb726dcb2012-09-05 08:57:23 -07001179 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001180 mirror::AbstractMethod* m = FromMethodId(method_id);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001181 return MethodHelper(m).GetName();
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001182}
1183
Elliott Hughesa96836a2013-01-17 12:27:49 -08001184std::string Dbg::GetFieldName(JDWP::FieldId field_id)
1185 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001186 mirror::Field* f = FromFieldId(field_id);
Elliott Hughesa96836a2013-01-17 12:27:49 -08001187 return FieldHelper(f).GetName();
1188}
1189
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001190/*
1191 * Augment the access flags for synthetic methods and fields by setting
1192 * the (as described by the spec) "0xf0000000 bit". Also, strip out any
1193 * flags not specified by the Java programming language.
1194 */
1195static uint32_t MangleAccessFlags(uint32_t accessFlags) {
1196 accessFlags &= kAccJavaFlagsMask;
1197 if ((accessFlags & kAccSynthetic) != 0) {
1198 accessFlags |= 0xf0000000;
1199 }
1200 return accessFlags;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001201}
1202
Elliott Hughesdbb40792011-11-18 17:05:22 -08001203static const uint16_t kEclipseWorkaroundSlot = 1000;
1204
1205/*
1206 * Eclipse appears to expect that the "this" reference is in slot zero.
1207 * If it's not, the "variables" display will show two copies of "this",
1208 * possibly because it gets "this" from SF.ThisObject and then displays
1209 * all locals with nonzero slot numbers.
1210 *
1211 * So, we remap the item in slot 0 to 1000, and remap "this" to zero. On
1212 * SF.GetValues / SF.SetValues we map them back.
Elliott Hughesc5b734a2011-12-01 17:20:58 -08001213 *
1214 * TODO: jdb uses the value to determine whether a variable is a local or an argument,
1215 * by checking whether it's less than the number of arguments. To make that work, we'd
1216 * have to "mangle" all the arguments to come first, not just the implicit argument 'this'.
Elliott Hughesdbb40792011-11-18 17:05:22 -08001217 */
1218static uint16_t MangleSlot(uint16_t slot, const char* name) {
1219 uint16_t newSlot = slot;
1220 if (strcmp(name, "this") == 0) {
1221 newSlot = 0;
1222 } else if (slot == 0) {
1223 newSlot = kEclipseWorkaroundSlot;
1224 }
1225 return newSlot;
1226}
1227
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001228static uint16_t DemangleSlot(uint16_t slot, mirror::AbstractMethod* m)
Ian Rogersb726dcb2012-09-05 08:57:23 -07001229 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Elliott Hughesdbb40792011-11-18 17:05:22 -08001230 if (slot == kEclipseWorkaroundSlot) {
Elliott Hughes68fdbd02011-11-29 19:22:47 -08001231 return 0;
Elliott Hughesdbb40792011-11-18 17:05:22 -08001232 } else if (slot == 0) {
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08001233 const DexFile::CodeItem* code_item = MethodHelper(m).GetCodeItem();
Elliott Hughescaf76542012-06-28 16:08:22 -07001234 CHECK(code_item != NULL) << PrettyMethod(m);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001235 return code_item->registers_size_ - code_item->ins_size_;
Elliott Hughesdbb40792011-11-18 17:05:22 -08001236 }
Elliott Hughes68fdbd02011-11-29 19:22:47 -08001237 return slot;
Elliott Hughesdbb40792011-11-18 17:05:22 -08001238}
1239
Elliott Hughes88d63092013-01-09 09:55:54 -08001240JDWP::JdwpError Dbg::OutputDeclaredFields(JDWP::RefTypeId class_id, bool with_generic, JDWP::ExpandBuf* pReply) {
Elliott Hughes436e3722012-02-17 20:01:47 -08001241 JDWP::JdwpError status;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001242 mirror::Class* c = DecodeClass(class_id, status);
Elliott Hughes436e3722012-02-17 20:01:47 -08001243 if (c == NULL) {
1244 return status;
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -08001245 }
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001246
1247 size_t instance_field_count = c->NumInstanceFields();
1248 size_t static_field_count = c->NumStaticFields();
1249
1250 expandBufAdd4BE(pReply, instance_field_count + static_field_count);
1251
1252 for (size_t i = 0; i < instance_field_count + static_field_count; ++i) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001253 mirror::Field* f = (i < instance_field_count) ? c->GetInstanceField(i) : c->GetStaticField(i - instance_field_count);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001254 FieldHelper fh(f);
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001255 expandBufAddFieldId(pReply, ToFieldId(f));
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001256 expandBufAddUtf8String(pReply, fh.GetName());
1257 expandBufAddUtf8String(pReply, fh.GetTypeDescriptor());
Elliott Hughesc5b734a2011-12-01 17:20:58 -08001258 if (with_generic) {
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001259 static const char genericSignature[1] = "";
1260 expandBufAddUtf8String(pReply, genericSignature);
1261 }
1262 expandBufAdd4BE(pReply, MangleAccessFlags(f->GetAccessFlags()));
1263 }
Elliott Hughes436e3722012-02-17 20:01:47 -08001264 return JDWP::ERR_NONE;
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001265}
1266
Elliott Hughes88d63092013-01-09 09:55:54 -08001267JDWP::JdwpError Dbg::OutputDeclaredMethods(JDWP::RefTypeId class_id, bool with_generic,
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001268 JDWP::ExpandBuf* pReply) {
Elliott Hughes436e3722012-02-17 20:01:47 -08001269 JDWP::JdwpError status;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001270 mirror::Class* c = DecodeClass(class_id, status);
Elliott Hughes436e3722012-02-17 20:01:47 -08001271 if (c == NULL) {
1272 return status;
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -08001273 }
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001274
1275 size_t direct_method_count = c->NumDirectMethods();
1276 size_t virtual_method_count = c->NumVirtualMethods();
1277
1278 expandBufAdd4BE(pReply, direct_method_count + virtual_method_count);
1279
1280 for (size_t i = 0; i < direct_method_count + virtual_method_count; ++i) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001281 mirror::AbstractMethod* m = (i < direct_method_count) ? c->GetDirectMethod(i) : c->GetVirtualMethod(i - direct_method_count);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001282 MethodHelper mh(m);
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001283 expandBufAddMethodId(pReply, ToMethodId(m));
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001284 expandBufAddUtf8String(pReply, mh.GetName());
Elliott Hughes4740cdf2011-12-07 14:07:12 -08001285 expandBufAddUtf8String(pReply, mh.GetSignature());
Elliott Hughesc5b734a2011-12-01 17:20:58 -08001286 if (with_generic) {
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001287 static const char genericSignature[1] = "";
1288 expandBufAddUtf8String(pReply, genericSignature);
1289 }
1290 expandBufAdd4BE(pReply, MangleAccessFlags(m->GetAccessFlags()));
1291 }
Elliott Hughes436e3722012-02-17 20:01:47 -08001292 return JDWP::ERR_NONE;
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001293}
1294
Elliott Hughes88d63092013-01-09 09:55:54 -08001295JDWP::JdwpError Dbg::OutputDeclaredInterfaces(JDWP::RefTypeId class_id, JDWP::ExpandBuf* pReply) {
Elliott Hughes436e3722012-02-17 20:01:47 -08001296 JDWP::JdwpError status;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001297 mirror::Class* c = DecodeClass(class_id, status);
Elliott Hughes436e3722012-02-17 20:01:47 -08001298 if (c == NULL) {
1299 return status;
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -08001300 }
Elliott Hughes436e3722012-02-17 20:01:47 -08001301
1302 ClassHelper kh(c);
Ian Rogersd24e2642012-06-06 21:21:43 -07001303 size_t interface_count = kh.NumDirectInterfaces();
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001304 expandBufAdd4BE(pReply, interface_count);
1305 for (size_t i = 0; i < interface_count; ++i) {
Elliott Hughes64f574f2013-02-20 14:57:12 -08001306 expandBufAddRefTypeId(pReply, gRegistry->AddRefType(kh.GetDirectInterface(i)));
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001307 }
Elliott Hughes436e3722012-02-17 20:01:47 -08001308 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001309}
1310
Elliott Hughes88d63092013-01-09 09:55:54 -08001311void Dbg::OutputLineTable(JDWP::RefTypeId, JDWP::MethodId method_id, JDWP::ExpandBuf* pReply)
Ian Rogersb726dcb2012-09-05 08:57:23 -07001312 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Elliott Hughes03181a82011-11-17 17:22:21 -08001313 struct DebugCallbackContext {
1314 int numItems;
1315 JDWP::ExpandBuf* pReply;
1316
Elliott Hughes2435a572012-02-17 16:07:41 -08001317 static bool Callback(void* context, uint32_t address, uint32_t line_number) {
Elliott Hughes03181a82011-11-17 17:22:21 -08001318 DebugCallbackContext* pContext = reinterpret_cast<DebugCallbackContext*>(context);
1319 expandBufAdd8BE(pContext->pReply, address);
Elliott Hughes2435a572012-02-17 16:07:41 -08001320 expandBufAdd4BE(pContext->pReply, line_number);
Elliott Hughes03181a82011-11-17 17:22:21 -08001321 pContext->numItems++;
1322 return true;
1323 }
1324 };
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001325 mirror::AbstractMethod* m = FromMethodId(method_id);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001326 MethodHelper mh(m);
Elliott Hughes03181a82011-11-17 17:22:21 -08001327 uint64_t start, end;
1328 if (m->IsNative()) {
1329 start = -1;
1330 end = -1;
1331 } else {
1332 start = 0;
jeffhao14f0db92012-12-14 17:50:42 -08001333 // Return the index of the last instruction
1334 end = mh.GetCodeItem()->insns_size_in_code_units_ - 1;
Elliott Hughes03181a82011-11-17 17:22:21 -08001335 }
1336
1337 expandBufAdd8BE(pReply, start);
1338 expandBufAdd8BE(pReply, end);
1339
1340 // Add numLines later
1341 size_t numLinesOffset = expandBufGetLength(pReply);
1342 expandBufAdd4BE(pReply, 0);
1343
1344 DebugCallbackContext context;
1345 context.numItems = 0;
1346 context.pReply = pReply;
1347
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001348 mh.GetDexFile().DecodeDebugInfo(mh.GetCodeItem(), m->IsStatic(), m->GetDexMethodIndex(),
1349 DebugCallbackContext::Callback, NULL, &context);
Elliott Hughes03181a82011-11-17 17:22:21 -08001350
1351 JDWP::Set4BE(expandBufGetBuffer(pReply) + numLinesOffset, context.numItems);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001352}
1353
Elliott Hughes88d63092013-01-09 09:55:54 -08001354void Dbg::OutputVariableTable(JDWP::RefTypeId, JDWP::MethodId method_id, bool with_generic, JDWP::ExpandBuf* pReply) {
Elliott Hughesdbb40792011-11-18 17:05:22 -08001355 struct DebugCallbackContext {
Elliott Hughesdbb40792011-11-18 17:05:22 -08001356 JDWP::ExpandBuf* pReply;
Elliott Hughesc5b734a2011-12-01 17:20:58 -08001357 size_t variable_count;
1358 bool with_generic;
Elliott Hughesdbb40792011-11-18 17:05:22 -08001359
Elliott Hughesc5b734a2011-12-01 17:20:58 -08001360 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 -08001361 DebugCallbackContext* pContext = reinterpret_cast<DebugCallbackContext*>(context);
1362
Elliott Hughesad3da692012-02-24 16:51:35 -08001363 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 -08001364
Elliott Hughes68fdbd02011-11-29 19:22:47 -08001365 slot = MangleSlot(slot, name);
1366
Elliott Hughesdbb40792011-11-18 17:05:22 -08001367 expandBufAdd8BE(pContext->pReply, startAddress);
1368 expandBufAddUtf8String(pContext->pReply, name);
1369 expandBufAddUtf8String(pContext->pReply, descriptor);
Elliott Hughesc5b734a2011-12-01 17:20:58 -08001370 if (pContext->with_generic) {
Elliott Hughesdbb40792011-11-18 17:05:22 -08001371 expandBufAddUtf8String(pContext->pReply, signature);
1372 }
1373 expandBufAdd4BE(pContext->pReply, endAddress - startAddress);
1374 expandBufAdd4BE(pContext->pReply, slot);
1375
Elliott Hughesc5b734a2011-12-01 17:20:58 -08001376 ++pContext->variable_count;
Elliott Hughesdbb40792011-11-18 17:05:22 -08001377 }
1378 };
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001379 mirror::AbstractMethod* m = FromMethodId(method_id);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001380 MethodHelper mh(m);
1381 const DexFile::CodeItem* code_item = mh.GetCodeItem();
Elliott Hughesdbb40792011-11-18 17:05:22 -08001382
Elliott Hughesc5b734a2011-12-01 17:20:58 -08001383 // arg_count considers doubles and longs to take 2 units.
1384 // variable_count considers everything to take 1 unit.
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001385 std::string shorty(mh.GetShorty());
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001386 expandBufAdd4BE(pReply, mirror::AbstractMethod::NumArgRegisters(shorty));
Elliott Hughesdbb40792011-11-18 17:05:22 -08001387
Elliott Hughesc5b734a2011-12-01 17:20:58 -08001388 // We don't know the total number of variables yet, so leave a blank and update it later.
1389 size_t variable_count_offset = expandBufGetLength(pReply);
Elliott Hughesdbb40792011-11-18 17:05:22 -08001390 expandBufAdd4BE(pReply, 0);
1391
1392 DebugCallbackContext context;
Elliott Hughesdbb40792011-11-18 17:05:22 -08001393 context.pReply = pReply;
Elliott Hughesc5b734a2011-12-01 17:20:58 -08001394 context.variable_count = 0;
1395 context.with_generic = with_generic;
Elliott Hughesdbb40792011-11-18 17:05:22 -08001396
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001397 mh.GetDexFile().DecodeDebugInfo(code_item, m->IsStatic(), m->GetDexMethodIndex(), NULL,
1398 DebugCallbackContext::Callback, &context);
Elliott Hughesdbb40792011-11-18 17:05:22 -08001399
Elliott Hughesc5b734a2011-12-01 17:20:58 -08001400 JDWP::Set4BE(expandBufGetBuffer(pReply) + variable_count_offset, context.variable_count);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001401}
1402
Elliott Hughes9777ba22013-01-17 09:04:19 -08001403JDWP::JdwpError Dbg::GetBytecodes(JDWP::RefTypeId, JDWP::MethodId method_id,
1404 std::vector<uint8_t>& bytecodes)
1405 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001406 mirror::AbstractMethod* m = FromMethodId(method_id);
Elliott Hughes9777ba22013-01-17 09:04:19 -08001407 if (m == NULL) {
1408 return JDWP::ERR_INVALID_METHODID;
1409 }
1410 MethodHelper mh(m);
1411 const DexFile::CodeItem* code_item = mh.GetCodeItem();
1412 size_t byte_count = code_item->insns_size_in_code_units_ * 2;
1413 const uint8_t* begin = reinterpret_cast<const uint8_t*>(code_item->insns_);
1414 const uint8_t* end = begin + byte_count;
1415 for (const uint8_t* p = begin; p != end; ++p) {
1416 bytecodes.push_back(*p);
1417 }
1418 return JDWP::ERR_NONE;
1419}
1420
Elliott Hughes88d63092013-01-09 09:55:54 -08001421JDWP::JdwpTag Dbg::GetFieldBasicTag(JDWP::FieldId field_id) {
1422 return BasicTagFromDescriptor(FieldHelper(FromFieldId(field_id)).GetTypeDescriptor());
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001423}
1424
Elliott Hughes88d63092013-01-09 09:55:54 -08001425JDWP::JdwpTag Dbg::GetStaticFieldBasicTag(JDWP::FieldId field_id) {
1426 return BasicTagFromDescriptor(FieldHelper(FromFieldId(field_id)).GetTypeDescriptor());
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001427}
1428
Elliott Hughes88d63092013-01-09 09:55:54 -08001429static JDWP::JdwpError GetFieldValueImpl(JDWP::RefTypeId ref_type_id, JDWP::ObjectId object_id,
1430 JDWP::FieldId field_id, JDWP::ExpandBuf* pReply,
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001431 bool is_static)
Ian Rogersb726dcb2012-09-05 08:57:23 -07001432 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Elliott Hughes0cf74332012-02-23 23:14:00 -08001433 JDWP::JdwpError status;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001434 mirror::Class* c = DecodeClass(ref_type_id, status);
Elliott Hughes88d63092013-01-09 09:55:54 -08001435 if (ref_type_id != 0 && c == NULL) {
Elliott Hughes0cf74332012-02-23 23:14:00 -08001436 return status;
1437 }
1438
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001439 mirror::Object* o = gRegistry->Get<mirror::Object*>(object_id);
Elliott Hughes64f574f2013-02-20 14:57:12 -08001440 if ((!is_static && o == NULL) || o == ObjectRegistry::kInvalidObject) {
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08001441 return JDWP::ERR_INVALID_OBJECT;
1442 }
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001443 mirror::Field* f = FromFieldId(field_id);
Elliott Hughes0cf74332012-02-23 23:14:00 -08001444
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001445 mirror::Class* receiver_class = c;
Elliott Hughes0cf74332012-02-23 23:14:00 -08001446 if (receiver_class == NULL && o != NULL) {
1447 receiver_class = o->GetClass();
1448 }
1449 // TODO: should we give up now if receiver_class is NULL?
1450 if (receiver_class != NULL && !f->GetDeclaringClass()->IsAssignableFrom(receiver_class)) {
1451 LOG(INFO) << "ERR_INVALID_FIELDID: " << PrettyField(f) << " " << PrettyClass(receiver_class);
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08001452 return JDWP::ERR_INVALID_FIELDID;
1453 }
Elliott Hughesaed4be92011-12-02 16:16:23 -08001454
Elliott Hughes0cf74332012-02-23 23:14:00 -08001455 // The RI only enforces the static/non-static mismatch in one direction.
1456 // TODO: should we change the tests and check both?
1457 if (is_static) {
1458 if (!f->IsStatic()) {
1459 return JDWP::ERR_INVALID_FIELDID;
1460 }
1461 } else {
1462 if (f->IsStatic()) {
1463 LOG(WARNING) << "Ignoring non-NULL receiver for ObjectReference.SetValues on static field " << PrettyField(f);
Elliott Hughes0cf74332012-02-23 23:14:00 -08001464 }
1465 }
jeffhao0dfbb7e2012-11-28 15:26:03 -08001466 if (f->IsStatic()) {
1467 o = f->GetDeclaringClass();
1468 }
Elliott Hughes0cf74332012-02-23 23:14:00 -08001469
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001470 JDWP::JdwpTag tag = BasicTagFromDescriptor(FieldHelper(f).GetTypeDescriptor());
Elliott Hughesaed4be92011-12-02 16:16:23 -08001471
1472 if (IsPrimitiveTag(tag)) {
1473 expandBufAdd1(pReply, tag);
1474 if (tag == JDWP::JT_BOOLEAN || tag == JDWP::JT_BYTE) {
1475 expandBufAdd1(pReply, f->Get32(o));
1476 } else if (tag == JDWP::JT_CHAR || tag == JDWP::JT_SHORT) {
1477 expandBufAdd2BE(pReply, f->Get32(o));
1478 } else if (tag == JDWP::JT_FLOAT || tag == JDWP::JT_INT) {
1479 expandBufAdd4BE(pReply, f->Get32(o));
1480 } else if (tag == JDWP::JT_DOUBLE || tag == JDWP::JT_LONG) {
1481 expandBufAdd8BE(pReply, f->Get64(o));
1482 } else {
Elliott Hughes3d30d9b2011-12-07 17:35:48 -08001483 LOG(FATAL) << "Unknown tag: " << tag;
Elliott Hughesaed4be92011-12-02 16:16:23 -08001484 }
1485 } else {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001486 mirror::Object* value = f->GetObject(o);
Elliott Hughesaed4be92011-12-02 16:16:23 -08001487 expandBufAdd1(pReply, TagFromObject(value));
1488 expandBufAddObjectId(pReply, gRegistry->Add(value));
1489 }
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08001490 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001491}
1492
Elliott Hughes88d63092013-01-09 09:55:54 -08001493JDWP::JdwpError Dbg::GetFieldValue(JDWP::ObjectId object_id, JDWP::FieldId field_id,
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001494 JDWP::ExpandBuf* pReply) {
Elliott Hughes88d63092013-01-09 09:55:54 -08001495 return GetFieldValueImpl(0, object_id, field_id, pReply, false);
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08001496}
1497
Elliott Hughes88d63092013-01-09 09:55:54 -08001498JDWP::JdwpError Dbg::GetStaticFieldValue(JDWP::RefTypeId ref_type_id, JDWP::FieldId field_id, JDWP::ExpandBuf* pReply) {
1499 return GetFieldValueImpl(ref_type_id, 0, field_id, pReply, true);
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08001500}
1501
Elliott Hughes88d63092013-01-09 09:55:54 -08001502static JDWP::JdwpError SetFieldValueImpl(JDWP::ObjectId object_id, JDWP::FieldId field_id,
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001503 uint64_t value, int width, bool is_static)
Ian Rogersb726dcb2012-09-05 08:57:23 -07001504 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001505 mirror::Object* o = gRegistry->Get<mirror::Object*>(object_id);
Elliott Hughes64f574f2013-02-20 14:57:12 -08001506 if ((!is_static && o == NULL) || o == ObjectRegistry::kInvalidObject) {
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08001507 return JDWP::ERR_INVALID_OBJECT;
1508 }
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001509 mirror::Field* f = FromFieldId(field_id);
Elliott Hughes0cf74332012-02-23 23:14:00 -08001510
1511 // The RI only enforces the static/non-static mismatch in one direction.
1512 // TODO: should we change the tests and check both?
1513 if (is_static) {
1514 if (!f->IsStatic()) {
1515 return JDWP::ERR_INVALID_FIELDID;
1516 }
1517 } else {
1518 if (f->IsStatic()) {
1519 LOG(WARNING) << "Ignoring non-NULL receiver for ObjectReference.SetValues on static field " << PrettyField(f);
Elliott Hughes0cf74332012-02-23 23:14:00 -08001520 }
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08001521 }
jeffhao0dfbb7e2012-11-28 15:26:03 -08001522 if (f->IsStatic()) {
1523 o = f->GetDeclaringClass();
1524 }
Elliott Hughesaed4be92011-12-02 16:16:23 -08001525
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001526 JDWP::JdwpTag tag = BasicTagFromDescriptor(FieldHelper(f).GetTypeDescriptor());
Elliott Hughesaed4be92011-12-02 16:16:23 -08001527
1528 if (IsPrimitiveTag(tag)) {
1529 if (tag == JDWP::JT_DOUBLE || tag == JDWP::JT_LONG) {
Elliott Hughes1bac54f2012-03-16 12:48:31 -07001530 CHECK_EQ(width, 8);
Elliott Hughesaed4be92011-12-02 16:16:23 -08001531 f->Set64(o, value);
1532 } else {
Elliott Hughes1bac54f2012-03-16 12:48:31 -07001533 CHECK_LE(width, 4);
Elliott Hughesaed4be92011-12-02 16:16:23 -08001534 f->Set32(o, value);
1535 }
1536 } else {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001537 mirror::Object* v = gRegistry->Get<mirror::Object*>(value);
Elliott Hughes64f574f2013-02-20 14:57:12 -08001538 if (v == ObjectRegistry::kInvalidObject) {
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -08001539 return JDWP::ERR_INVALID_OBJECT;
1540 }
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08001541 if (v != NULL) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001542 mirror::Class* field_type = FieldHelper(f).GetType();
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08001543 if (!field_type->IsAssignableFrom(v->GetClass())) {
1544 return JDWP::ERR_INVALID_OBJECT;
1545 }
1546 }
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -08001547 f->SetObject(o, v);
Elliott Hughesaed4be92011-12-02 16:16:23 -08001548 }
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -08001549
1550 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001551}
1552
Elliott Hughes88d63092013-01-09 09:55:54 -08001553JDWP::JdwpError Dbg::SetFieldValue(JDWP::ObjectId object_id, JDWP::FieldId field_id, uint64_t value,
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001554 int width) {
Elliott Hughes88d63092013-01-09 09:55:54 -08001555 return SetFieldValueImpl(object_id, field_id, value, width, false);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001556}
1557
Elliott Hughes88d63092013-01-09 09:55:54 -08001558JDWP::JdwpError Dbg::SetStaticFieldValue(JDWP::FieldId field_id, uint64_t value, int width) {
1559 return SetFieldValueImpl(0, field_id, value, width, true);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001560}
1561
Elliott Hughes88d63092013-01-09 09:55:54 -08001562std::string Dbg::StringToUtf8(JDWP::ObjectId string_id) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001563 mirror::String* s = gRegistry->Get<mirror::String*>(string_id);
Elliott Hughes68fdbd02011-11-29 19:22:47 -08001564 return s->ToModifiedUtf8();
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001565}
1566
Elliott Hughes221229c2013-01-08 18:17:50 -08001567JDWP::JdwpError Dbg::GetThreadName(JDWP::ObjectId thread_id, std::string& name) {
jeffhaoa77f0f62012-12-05 17:19:31 -08001568 ScopedObjectAccessUnchecked soa(Thread::Current());
1569 MutexLock mu(soa.Self(), *Locks::thread_list_lock_);
Elliott Hughes221229c2013-01-08 18:17:50 -08001570 Thread* thread;
1571 JDWP::JdwpError error = DecodeThread(soa, thread_id, thread);
1572 if (error != JDWP::ERR_NONE && error != JDWP::ERR_THREAD_NOT_ALIVE) {
1573 return error;
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001574 }
Elliott Hughes221229c2013-01-08 18:17:50 -08001575
1576 // We still need to report the zombie threads' names, so we can't just call Thread::GetThreadName.
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001577 mirror::Object* thread_object = gRegistry->Get<mirror::Object*>(thread_id);
1578 mirror::Field* java_lang_Thread_name_field =
1579 soa.DecodeField(WellKnownClasses::java_lang_Thread_name);
1580 mirror::String* s =
1581 reinterpret_cast<mirror::String*>(java_lang_Thread_name_field->GetObject(thread_object));
Elliott Hughes221229c2013-01-08 18:17:50 -08001582 if (s != NULL) {
1583 name = s->ToModifiedUtf8();
1584 }
1585 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001586}
1587
Elliott Hughes221229c2013-01-08 18:17:50 -08001588JDWP::JdwpError Dbg::GetThreadGroup(JDWP::ObjectId thread_id, JDWP::ExpandBuf* pReply) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001589 ScopedObjectAccess soa(Thread::Current());
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001590 mirror::Object* thread_object = gRegistry->Get<mirror::Object*>(thread_id);
Elliott Hughes64f574f2013-02-20 14:57:12 -08001591 if (thread_object == ObjectRegistry::kInvalidObject) {
Elliott Hughes2435a572012-02-17 16:07:41 -08001592 return JDWP::ERR_INVALID_OBJECT;
1593 }
1594
1595 // Okay, so it's an object, but is it actually a thread?
Ian Rogers50b35e22012-10-04 10:09:15 -07001596 MutexLock mu(soa.Self(), *Locks::thread_list_lock_);
Elliott Hughes221229c2013-01-08 18:17:50 -08001597 Thread* thread;
1598 JDWP::JdwpError error = DecodeThread(soa, thread_id, thread);
1599 if (error == JDWP::ERR_THREAD_NOT_ALIVE) {
1600 // Zombie threads are in the null group.
1601 expandBufAddObjectId(pReply, JDWP::ObjectId(0));
1602 return JDWP::ERR_NONE;
1603 }
1604 if (error != JDWP::ERR_NONE) {
1605 return error;
Elliott Hughes2435a572012-02-17 16:07:41 -08001606 }
Elliott Hughes499c5132011-11-17 14:55:11 -08001607
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001608 mirror::Class* c = Runtime::Current()->GetClassLinker()->FindSystemClass("Ljava/lang/Thread;");
Elliott Hughes499c5132011-11-17 14:55:11 -08001609 CHECK(c != NULL);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001610 mirror::Field* f = c->FindInstanceField("group", "Ljava/lang/ThreadGroup;");
Elliott Hughes499c5132011-11-17 14:55:11 -08001611 CHECK(f != NULL);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001612 mirror::Object* group = f->GetObject(thread_object);
Elliott Hughes499c5132011-11-17 14:55:11 -08001613 CHECK(group != NULL);
Elliott Hughes2435a572012-02-17 16:07:41 -08001614 JDWP::ObjectId thread_group_id = gRegistry->Add(group);
1615
1616 expandBufAddObjectId(pReply, thread_group_id);
1617 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001618}
1619
Elliott Hughes88d63092013-01-09 09:55:54 -08001620std::string Dbg::GetThreadGroupName(JDWP::ObjectId thread_group_id) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001621 ScopedObjectAccess soa(Thread::Current());
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001622 mirror::Object* thread_group = gRegistry->Get<mirror::Object*>(thread_group_id);
Elliott Hughes499c5132011-11-17 14:55:11 -08001623 CHECK(thread_group != NULL);
1624
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001625 mirror::Class* c = Runtime::Current()->GetClassLinker()->FindSystemClass("Ljava/lang/ThreadGroup;");
Elliott Hughes499c5132011-11-17 14:55:11 -08001626 CHECK(c != NULL);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001627 mirror::Field* f = c->FindInstanceField("name", "Ljava/lang/String;");
Elliott Hughes499c5132011-11-17 14:55:11 -08001628 CHECK(f != NULL);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001629 mirror::String* s = reinterpret_cast<mirror::String*>(f->GetObject(thread_group));
Elliott Hughes499c5132011-11-17 14:55:11 -08001630 return s->ToModifiedUtf8();
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001631}
1632
Elliott Hughes88d63092013-01-09 09:55:54 -08001633JDWP::ObjectId Dbg::GetThreadGroupParent(JDWP::ObjectId thread_group_id) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001634 mirror::Object* thread_group = gRegistry->Get<mirror::Object*>(thread_group_id);
Elliott Hughes4e235312011-12-02 11:34:15 -08001635 CHECK(thread_group != NULL);
1636
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001637 mirror::Class* c = Runtime::Current()->GetClassLinker()->FindSystemClass("Ljava/lang/ThreadGroup;");
Elliott Hughes4e235312011-12-02 11:34:15 -08001638 CHECK(c != NULL);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001639 mirror::Field* f = c->FindInstanceField("parent", "Ljava/lang/ThreadGroup;");
Elliott Hughes4e235312011-12-02 11:34:15 -08001640 CHECK(f != NULL);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001641 mirror::Object* parent = f->GetObject(thread_group);
Elliott Hughes4e235312011-12-02 11:34:15 -08001642 return gRegistry->Add(parent);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001643}
1644
1645JDWP::ObjectId Dbg::GetSystemThreadGroupId() {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001646 ScopedObjectAccessUnchecked soa(Thread::Current());
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001647 mirror::Field* f = soa.DecodeField(WellKnownClasses::java_lang_ThreadGroup_systemThreadGroup);
1648 mirror::Object* group = f->GetObject(f->GetDeclaringClass());
Ian Rogers365c1022012-06-22 15:05:28 -07001649 return gRegistry->Add(group);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001650}
1651
1652JDWP::ObjectId Dbg::GetMainThreadGroupId() {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001653 ScopedObjectAccess soa(Thread::Current());
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001654 mirror::Field* f = soa.DecodeField(WellKnownClasses::java_lang_ThreadGroup_mainThreadGroup);
1655 mirror::Object* group = f->GetObject(f->GetDeclaringClass());
Ian Rogers365c1022012-06-22 15:05:28 -07001656 return gRegistry->Add(group);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001657}
1658
Elliott Hughes221229c2013-01-08 18:17:50 -08001659JDWP::JdwpError Dbg::GetThreadStatus(JDWP::ObjectId thread_id, JDWP::JdwpThreadStatus* pThreadStatus, JDWP::JdwpSuspendStatus* pSuspendStatus) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001660 ScopedObjectAccess soa(Thread::Current());
Elliott Hughes499c5132011-11-17 14:55:11 -08001661
Elliott Hughes9e0c1752013-01-09 14:02:58 -08001662 *pSuspendStatus = JDWP::SUSPEND_STATUS_NOT_SUSPENDED;
1663
Ian Rogers50b35e22012-10-04 10:09:15 -07001664 MutexLock mu(soa.Self(), *Locks::thread_list_lock_);
Elliott Hughes221229c2013-01-08 18:17:50 -08001665 Thread* thread;
1666 JDWP::JdwpError error = DecodeThread(soa, thread_id, thread);
1667 if (error != JDWP::ERR_NONE) {
1668 if (error == JDWP::ERR_THREAD_NOT_ALIVE) {
1669 *pThreadStatus = JDWP::TS_ZOMBIE;
Elliott Hughes221229c2013-01-08 18:17:50 -08001670 return JDWP::ERR_NONE;
1671 }
1672 return error;
Elliott Hughes499c5132011-11-17 14:55:11 -08001673 }
1674
Elliott Hughes9e0c1752013-01-09 14:02:58 -08001675 if (IsSuspendedForDebugger(soa, thread)) {
1676 *pSuspendStatus = JDWP::SUSPEND_STATUS_SUSPENDED;
Elliott Hughes499c5132011-11-17 14:55:11 -08001677 }
1678
Elliott Hughes9e0c1752013-01-09 14:02:58 -08001679 switch (thread->GetState()) {
1680 case kBlocked: *pThreadStatus = JDWP::TS_MONITOR; break;
1681 case kNative: *pThreadStatus = JDWP::TS_RUNNING; break;
1682 case kRunnable: *pThreadStatus = JDWP::TS_RUNNING; break;
1683 case kSleeping: *pThreadStatus = JDWP::TS_SLEEPING; break;
1684 case kStarting: *pThreadStatus = JDWP::TS_ZOMBIE; break;
1685 case kSuspended: *pThreadStatus = JDWP::TS_RUNNING; break;
1686 case kTerminated: *pThreadStatus = JDWP::TS_ZOMBIE; break;
1687 case kTimedWaiting: *pThreadStatus = JDWP::TS_WAIT; break;
1688 case kWaitingForDebuggerSend: *pThreadStatus = JDWP::TS_WAIT; break;
1689 case kWaitingForDebuggerSuspension: *pThreadStatus = JDWP::TS_WAIT; break;
1690 case kWaitingForDebuggerToAttach: *pThreadStatus = JDWP::TS_WAIT; break;
1691 case kWaitingForGcToComplete: *pThreadStatus = JDWP::TS_WAIT; break;
1692 case kWaitingForJniOnLoad: *pThreadStatus = JDWP::TS_WAIT; break;
1693 case kWaitingForSignalCatcherOutput: *pThreadStatus = JDWP::TS_WAIT; break;
1694 case kWaitingInMainDebuggerLoop: *pThreadStatus = JDWP::TS_WAIT; break;
1695 case kWaitingInMainSignalCatcherLoop: *pThreadStatus = JDWP::TS_WAIT; break;
1696 case kWaitingPerformingGc: *pThreadStatus = JDWP::TS_WAIT; break;
1697 case kWaiting: *pThreadStatus = JDWP::TS_WAIT; break;
1698 // Don't add a 'default' here so the compiler can spot incompatible enum changes.
1699 }
Elliott Hughes221229c2013-01-08 18:17:50 -08001700 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001701}
1702
Elliott Hughes221229c2013-01-08 18:17:50 -08001703JDWP::JdwpError Dbg::GetThreadDebugSuspendCount(JDWP::ObjectId thread_id, JDWP::ExpandBuf* pReply) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001704 ScopedObjectAccess soa(Thread::Current());
Ian Rogers50b35e22012-10-04 10:09:15 -07001705 MutexLock mu(soa.Self(), *Locks::thread_list_lock_);
Elliott Hughes221229c2013-01-08 18:17:50 -08001706 Thread* thread;
1707 JDWP::JdwpError error = DecodeThread(soa, thread_id, thread);
1708 if (error != JDWP::ERR_NONE) {
1709 return error;
Elliott Hughes2435a572012-02-17 16:07:41 -08001710 }
Ian Rogers50b35e22012-10-04 10:09:15 -07001711 MutexLock mu2(soa.Self(), *Locks::thread_suspend_count_lock_);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001712 expandBufAdd4BE(pReply, thread->GetDebugSuspendCount());
Elliott Hughes2435a572012-02-17 16:07:41 -08001713 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001714}
1715
Elliott Hughesf9501702013-01-11 11:22:27 -08001716JDWP::JdwpError Dbg::Interrupt(JDWP::ObjectId thread_id) {
1717 ScopedObjectAccess soa(Thread::Current());
1718 MutexLock mu(soa.Self(), *Locks::thread_list_lock_);
1719 Thread* thread;
1720 JDWP::JdwpError error = DecodeThread(soa, thread_id, thread);
1721 if (error != JDWP::ERR_NONE) {
1722 return error;
1723 }
1724 thread->Interrupt();
1725 return JDWP::ERR_NONE;
1726}
1727
Elliott Hughescaf76542012-06-28 16:08:22 -07001728void Dbg::GetThreads(JDWP::ObjectId thread_group_id, std::vector<JDWP::ObjectId>& thread_ids) {
Ian Rogers365c1022012-06-22 15:05:28 -07001729 class ThreadListVisitor {
1730 public:
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001731 ThreadListVisitor(const ScopedObjectAccessUnchecked& soa, mirror::Object* desired_thread_group,
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001732 std::vector<JDWP::ObjectId>& thread_ids)
Ian Rogersb726dcb2012-09-05 08:57:23 -07001733 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_)
jeffhao0dfbb7e2012-11-28 15:26:03 -08001734 : soa_(soa), desired_thread_group_(desired_thread_group), thread_ids_(thread_ids) {}
Ian Rogers365c1022012-06-22 15:05:28 -07001735
Elliott Hughesa2155262011-11-16 16:26:58 -08001736 static void Visit(Thread* t, void* arg) {
1737 reinterpret_cast<ThreadListVisitor*>(arg)->Visit(t);
1738 }
1739
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001740 // TODO: Enable annotalysis. We know lock is held in constructor, but abstraction confuses
1741 // annotalysis.
1742 void Visit(Thread* t) NO_THREAD_SAFETY_ANALYSIS {
Elliott Hughesa2155262011-11-16 16:26:58 -08001743 if (t == Dbg::GetDebugThread()) {
1744 // Skip the JDWP thread. Some debuggers get bent out of shape when they can't suspend and
1745 // query all threads, so it's easier if we just don't tell them about this thread.
1746 return;
1747 }
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001748 mirror::Object* peer = t->GetPeer();
jeffhao0dfbb7e2012-11-28 15:26:03 -08001749 if (IsInDesiredThreadGroup(peer)) {
Ian Rogers120f1c72012-09-28 17:17:10 -07001750 thread_ids_.push_back(gRegistry->Add(peer));
Elliott Hughesa2155262011-11-16 16:26:58 -08001751 }
1752 }
1753
Ian Rogers365c1022012-06-22 15:05:28 -07001754 private:
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001755 bool IsInDesiredThreadGroup(mirror::Object* peer)
jeffhao0dfbb7e2012-11-28 15:26:03 -08001756 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
jeffhao0dfbb7e2012-11-28 15:26:03 -08001757 // peer might be NULL if the thread is still starting up.
1758 if (peer == NULL) {
1759 // We can't tell the debugger about this thread yet.
1760 // TODO: if we identified threads to the debugger by their Thread*
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001761 // rather than their peer's mirror::Object*, we could fix this.
jeffhao0dfbb7e2012-11-28 15:26:03 -08001762 // Doing so might help us report ZOMBIE threads too.
1763 return false;
1764 }
jeffhaoc1e04902012-12-13 12:41:10 -08001765 // Do we want threads from all thread groups?
1766 if (desired_thread_group_ == NULL) {
1767 return true;
1768 }
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001769 mirror::Object* group = soa_.DecodeField(WellKnownClasses::java_lang_Thread_group)->GetObject(peer);
jeffhao0dfbb7e2012-11-28 15:26:03 -08001770 return (group == desired_thread_group_);
1771 }
1772
Mathieu Chartierdbe6f462012-09-25 16:54:50 -07001773 const ScopedObjectAccessUnchecked& soa_;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001774 mirror::Object* const desired_thread_group_;
Elliott Hughescaf76542012-06-28 16:08:22 -07001775 std::vector<JDWP::ObjectId>& thread_ids_;
Elliott Hughesa2155262011-11-16 16:26:58 -08001776 };
1777
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001778 ScopedObjectAccessUnchecked soa(Thread::Current());
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001779 mirror::Object* thread_group = gRegistry->Get<mirror::Object*>(thread_group_id);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001780 ThreadListVisitor tlv(soa, thread_group, thread_ids);
Ian Rogers50b35e22012-10-04 10:09:15 -07001781 MutexLock mu(soa.Self(), *Locks::thread_list_lock_);
Elliott Hughesf8349362012-06-18 15:00:06 -07001782 Runtime::Current()->GetThreadList()->ForEach(ThreadListVisitor::Visit, &tlv);
Elliott Hughescaf76542012-06-28 16:08:22 -07001783}
Elliott Hughesa2155262011-11-16 16:26:58 -08001784
Elliott Hughescaf76542012-06-28 16:08:22 -07001785void Dbg::GetChildThreadGroups(JDWP::ObjectId thread_group_id, std::vector<JDWP::ObjectId>& child_thread_group_ids) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001786 ScopedObjectAccess soa(Thread::Current());
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001787 mirror::Object* thread_group = gRegistry->Get<mirror::Object*>(thread_group_id);
Elliott Hughescaf76542012-06-28 16:08:22 -07001788
1789 // Get the ArrayList<ThreadGroup> "groups" out of this thread group...
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001790 mirror::Field* groups_field = thread_group->GetClass()->FindInstanceField("groups", "Ljava/util/List;");
1791 mirror::Object* groups_array_list = groups_field->GetObject(thread_group);
Elliott Hughescaf76542012-06-28 16:08:22 -07001792
1793 // Get the array and size out of the ArrayList<ThreadGroup>...
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001794 mirror::Field* array_field = groups_array_list->GetClass()->FindInstanceField("array", "[Ljava/lang/Object;");
1795 mirror::Field* size_field = groups_array_list->GetClass()->FindInstanceField("size", "I");
1796 mirror::ObjectArray<mirror::Object>* groups_array =
1797 array_field->GetObject(groups_array_list)->AsObjectArray<mirror::Object>();
Elliott Hughescaf76542012-06-28 16:08:22 -07001798 const int32_t size = size_field->GetInt(groups_array_list);
1799
1800 // Copy the first 'size' elements out of the array into the result.
1801 for (int32_t i = 0; i < size; ++i) {
1802 child_thread_group_ids.push_back(gRegistry->Add(groups_array->Get(i)));
Elliott Hughesa2155262011-11-16 16:26:58 -08001803 }
1804}
1805
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001806static int GetStackDepth(Thread* thread)
Ian Rogersb726dcb2012-09-05 08:57:23 -07001807 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Ian Rogers0399dde2012-06-06 17:09:28 -07001808 struct CountStackDepthVisitor : public StackVisitor {
Ian Rogers7a22fa62013-01-23 12:16:16 -08001809 CountStackDepthVisitor(Thread* thread)
1810 : StackVisitor(thread, NULL), depth(0) {}
Ian Rogers0399dde2012-06-06 17:09:28 -07001811
Elliott Hughes64f574f2013-02-20 14:57:12 -08001812 // TODO: Enable annotalysis. We know lock is held in constructor, but abstraction confuses
1813 // annotalysis.
1814 bool VisitFrame() NO_THREAD_SAFETY_ANALYSIS {
Ian Rogers0399dde2012-06-06 17:09:28 -07001815 if (!GetMethod()->IsRuntimeMethod()) {
Elliott Hughesf8a2df72011-12-01 12:19:54 -08001816 ++depth;
1817 }
Elliott Hughes530fa002012-03-12 11:44:49 -07001818 return true;
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001819 }
1820 size_t depth;
1821 };
Elliott Hughes08fc03a2012-06-26 17:34:00 -07001822
Ian Rogers7a22fa62013-01-23 12:16:16 -08001823 CountStackDepthVisitor visitor(thread);
Ian Rogers0399dde2012-06-06 17:09:28 -07001824 visitor.WalkStack();
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001825 return visitor.depth;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001826}
1827
Elliott Hughes221229c2013-01-08 18:17:50 -08001828JDWP::JdwpError Dbg::GetThreadFrameCount(JDWP::ObjectId thread_id, size_t& result) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001829 ScopedObjectAccess soa(Thread::Current());
jeffhaoa77f0f62012-12-05 17:19:31 -08001830 MutexLock mu(soa.Self(), *Locks::thread_list_lock_);
Elliott Hughes221229c2013-01-08 18:17:50 -08001831 Thread* thread;
1832 JDWP::JdwpError error = DecodeThread(soa, thread_id, thread);
1833 if (error != JDWP::ERR_NONE) {
1834 return error;
1835 }
Elliott Hughesf15f4a02013-01-09 10:09:38 -08001836 if (!IsSuspendedForDebugger(soa, thread)) {
1837 return JDWP::ERR_THREAD_NOT_SUSPENDED;
1838 }
Elliott Hughes221229c2013-01-08 18:17:50 -08001839 result = GetStackDepth(thread);
1840 return JDWP::ERR_NONE;
Elliott Hughes86964332012-02-15 19:37:42 -08001841}
1842
Ian Rogers306057f2012-11-26 12:45:53 -08001843JDWP::JdwpError Dbg::GetThreadFrames(JDWP::ObjectId thread_id, size_t start_frame,
1844 size_t frame_count, JDWP::ExpandBuf* buf) {
Elliott Hughes6e9d22c2012-06-22 15:02:37 -07001845 class GetFrameVisitor : public StackVisitor {
1846 public:
Ian Rogers7a22fa62013-01-23 12:16:16 -08001847 GetFrameVisitor(Thread* thread, size_t start_frame, size_t frame_count, JDWP::ExpandBuf* buf)
Ian Rogersb726dcb2012-09-05 08:57:23 -07001848 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_)
Ian Rogers7a22fa62013-01-23 12:16:16 -08001849 : StackVisitor(thread, NULL), depth_(0),
Elliott Hughes6e9d22c2012-06-22 15:02:37 -07001850 start_frame_(start_frame), frame_count_(frame_count), buf_(buf) {
1851 expandBufAdd4BE(buf_, frame_count_);
Elliott Hughes03181a82011-11-17 17:22:21 -08001852 }
Ian Rogers0399dde2012-06-06 17:09:28 -07001853
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001854 // TODO: Enable annotalysis. We know lock is held in constructor, but abstraction confuses
1855 // annotalysis.
1856 virtual bool VisitFrame() NO_THREAD_SAFETY_ANALYSIS {
Ian Rogers0399dde2012-06-06 17:09:28 -07001857 if (GetMethod()->IsRuntimeMethod()) {
Elliott Hughes530fa002012-03-12 11:44:49 -07001858 return true; // The debugger can't do anything useful with a frame that has no Method*.
Elliott Hughes03181a82011-11-17 17:22:21 -08001859 }
Elliott Hughes6e9d22c2012-06-22 15:02:37 -07001860 if (depth_ >= start_frame_ + frame_count_) {
Elliott Hughes530fa002012-03-12 11:44:49 -07001861 return false;
Elliott Hughes03181a82011-11-17 17:22:21 -08001862 }
Elliott Hughes6e9d22c2012-06-22 15:02:37 -07001863 if (depth_ >= start_frame_) {
1864 JDWP::FrameId frame_id(GetFrameId());
1865 JDWP::JdwpLocation location;
1866 SetLocation(location, GetMethod(), GetDexPc());
Elliott Hughes7baf96f2012-06-22 16:33:50 -07001867 VLOG(jdwp) << StringPrintf(" Frame %3zd: id=%3lld ", depth_, frame_id) << location;
Elliott Hughes6e9d22c2012-06-22 15:02:37 -07001868 expandBufAdd8BE(buf_, frame_id);
1869 expandBufAddLocation(buf_, location);
1870 }
1871 ++depth_;
Elliott Hughes530fa002012-03-12 11:44:49 -07001872 return true;
Elliott Hughes03181a82011-11-17 17:22:21 -08001873 }
Elliott Hughes6e9d22c2012-06-22 15:02:37 -07001874
1875 private:
1876 size_t depth_;
1877 const size_t start_frame_;
1878 const size_t frame_count_;
1879 JDWP::ExpandBuf* buf_;
Elliott Hughes03181a82011-11-17 17:22:21 -08001880 };
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001881
1882 ScopedObjectAccessUnchecked soa(Thread::Current());
jeffhaoa77f0f62012-12-05 17:19:31 -08001883 MutexLock mu(soa.Self(), *Locks::thread_list_lock_);
Elliott Hughes221229c2013-01-08 18:17:50 -08001884 Thread* thread;
1885 JDWP::JdwpError error = DecodeThread(soa, thread_id, thread);
1886 if (error != JDWP::ERR_NONE) {
1887 return error;
1888 }
Elliott Hughesf15f4a02013-01-09 10:09:38 -08001889 if (!IsSuspendedForDebugger(soa, thread)) {
1890 return JDWP::ERR_THREAD_NOT_SUSPENDED;
1891 }
Ian Rogers7a22fa62013-01-23 12:16:16 -08001892 GetFrameVisitor visitor(thread, start_frame, frame_count, buf);
Ian Rogers0399dde2012-06-06 17:09:28 -07001893 visitor.WalkStack();
Elliott Hughes6e9d22c2012-06-22 15:02:37 -07001894 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001895}
1896
1897JDWP::ObjectId Dbg::GetThreadSelfId() {
Mathieu Chartierdbe6f462012-09-25 16:54:50 -07001898 ScopedObjectAccessUnchecked soa(Thread::Current());
Ian Rogerscfaa4552012-11-26 21:00:08 -08001899 return gRegistry->Add(soa.Self()->GetPeer());
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001900}
1901
Elliott Hughes475fc232011-10-25 15:00:35 -07001902void Dbg::SuspendVM() {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001903 Runtime::Current()->GetThreadList()->SuspendAllForDebugger();
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001904}
1905
1906void Dbg::ResumeVM() {
Elliott Hughesc61a2672012-06-21 14:52:29 -07001907 Runtime::Current()->GetThreadList()->UndoDebuggerSuspensions();
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001908}
1909
Elliott Hughes221229c2013-01-08 18:17:50 -08001910JDWP::JdwpError Dbg::SuspendThread(JDWP::ObjectId thread_id, bool request_suspension) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001911 ScopedLocalRef<jobject> peer(Thread::Current()->GetJniEnv(), NULL);
1912 {
1913 ScopedObjectAccess soa(Thread::Current());
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001914 peer.reset(soa.AddLocalReference<jobject>(gRegistry->Get<mirror::Object*>(thread_id)));
Elliott Hughes4e235312011-12-02 11:34:15 -08001915 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001916 if (peer.get() == NULL) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001917 return JDWP::ERR_THREAD_NOT_ALIVE;
1918 }
1919 // Suspend thread to build stack trace.
Elliott Hughesf327e072013-01-09 16:01:26 -08001920 bool timed_out;
1921 Thread* thread = Thread::SuspendForDebugger(peer.get(), request_suspension, &timed_out);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001922 if (thread != NULL) {
1923 return JDWP::ERR_NONE;
Elliott Hughesf327e072013-01-09 16:01:26 -08001924 } else if (timed_out) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001925 return JDWP::ERR_INTERNAL;
1926 } else {
1927 return JDWP::ERR_THREAD_NOT_ALIVE;
1928 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001929}
1930
Elliott Hughes221229c2013-01-08 18:17:50 -08001931void Dbg::ResumeThread(JDWP::ObjectId thread_id) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001932 ScopedObjectAccessUnchecked soa(Thread::Current());
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001933 mirror::Object* peer = gRegistry->Get<mirror::Object*>(thread_id);
jeffhaoa77f0f62012-12-05 17:19:31 -08001934 Thread* thread;
1935 {
1936 MutexLock mu(soa.Self(), *Locks::thread_list_lock_);
1937 thread = Thread::FromManagedThread(soa, peer);
1938 }
Elliott Hughes4e235312011-12-02 11:34:15 -08001939 if (thread == NULL) {
1940 LOG(WARNING) << "No such thread for resume: " << peer;
1941 return;
1942 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001943 bool needs_resume;
1944 {
Ian Rogers50b35e22012-10-04 10:09:15 -07001945 MutexLock mu2(soa.Self(), *Locks::thread_suspend_count_lock_);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001946 needs_resume = thread->GetSuspendCount() > 0;
1947 }
1948 if (needs_resume) {
Elliott Hughes546b9862012-06-20 16:06:13 -07001949 Runtime::Current()->GetThreadList()->Resume(thread, true);
1950 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001951}
1952
1953void Dbg::SuspendSelf() {
Elliott Hughes475fc232011-10-25 15:00:35 -07001954 Runtime::Current()->GetThreadList()->SuspendSelfForDebugger();
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001955}
1956
Ian Rogers0399dde2012-06-06 17:09:28 -07001957struct GetThisVisitor : public StackVisitor {
Ian Rogers7a22fa62013-01-23 12:16:16 -08001958 GetThisVisitor(Thread* thread, Context* context, JDWP::FrameId frame_id)
Ian Rogersb726dcb2012-09-05 08:57:23 -07001959 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_)
Ian Rogers7a22fa62013-01-23 12:16:16 -08001960 : StackVisitor(thread, context), this_object(NULL), frame_id(frame_id) {}
Ian Rogers0399dde2012-06-06 17:09:28 -07001961
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001962 // TODO: Enable annotalysis. We know lock is held in constructor, but abstraction confuses
1963 // annotalysis.
1964 virtual bool VisitFrame() NO_THREAD_SAFETY_ANALYSIS {
Elliott Hughes6e9d22c2012-06-22 15:02:37 -07001965 if (frame_id != GetFrameId()) {
Ian Rogers0399dde2012-06-06 17:09:28 -07001966 return true; // continue
Ian Rogers0399dde2012-06-06 17:09:28 -07001967 } else {
Ian Rogers62d6c772013-02-27 08:32:07 -08001968 this_object = GetThisObject();
1969 return false;
Ian Rogers0399dde2012-06-06 17:09:28 -07001970 }
Elliott Hughes86b00102011-12-05 17:54:26 -08001971 }
Ian Rogers0399dde2012-06-06 17:09:28 -07001972
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001973 mirror::Object* this_object;
Elliott Hughes6e9d22c2012-06-22 15:02:37 -07001974 JDWP::FrameId frame_id;
Ian Rogers0399dde2012-06-06 17:09:28 -07001975};
1976
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001977JDWP::JdwpError Dbg::GetThisObject(JDWP::ObjectId thread_id, JDWP::FrameId frame_id,
1978 JDWP::ObjectId* result) {
1979 ScopedObjectAccessUnchecked soa(Thread::Current());
1980 Thread* thread;
1981 {
Ian Rogers50b35e22012-10-04 10:09:15 -07001982 MutexLock mu(soa.Self(), *Locks::thread_list_lock_);
Elliott Hughes221229c2013-01-08 18:17:50 -08001983 JDWP::JdwpError error = DecodeThread(soa, thread_id, thread);
1984 if (error != JDWP::ERR_NONE) {
1985 return error;
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001986 }
Elliott Hughes9e0c1752013-01-09 14:02:58 -08001987 if (!IsSuspendedForDebugger(soa, thread)) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001988 return JDWP::ERR_THREAD_NOT_SUSPENDED;
1989 }
Elliott Hughes6e9d22c2012-06-22 15:02:37 -07001990 }
Elliott Hughescaf76542012-06-28 16:08:22 -07001991 UniquePtr<Context> context(Context::Create());
Ian Rogers7a22fa62013-01-23 12:16:16 -08001992 GetThisVisitor visitor(thread, context.get(), frame_id);
Ian Rogers0399dde2012-06-06 17:09:28 -07001993 visitor.WalkStack();
Elliott Hughes6e9d22c2012-06-22 15:02:37 -07001994 *result = gRegistry->Add(visitor.this_object);
1995 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001996}
1997
Elliott Hughes88d63092013-01-09 09:55:54 -08001998void Dbg::GetLocalValue(JDWP::ObjectId thread_id, JDWP::FrameId frame_id, int slot, JDWP::JdwpTag tag,
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001999 uint8_t* buf, size_t width) {
Ian Rogers0399dde2012-06-06 17:09:28 -07002000 struct GetLocalVisitor : public StackVisitor {
Ian Rogers7a22fa62013-01-23 12:16:16 -08002001 GetLocalVisitor(Thread* thread, Context* context, JDWP::FrameId frame_id, int slot,
2002 JDWP::JdwpTag tag, uint8_t* buf, size_t width)
Ian Rogersb726dcb2012-09-05 08:57:23 -07002003 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_)
Ian Rogers7a22fa62013-01-23 12:16:16 -08002004 : StackVisitor(thread, context), frame_id_(frame_id), slot_(slot), tag_(tag),
Ian Rogersca190662012-06-26 15:45:57 -07002005 buf_(buf), width_(width) {}
2006
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002007 // TODO: Enable annotalysis. We know lock is held in constructor, but abstraction confuses
2008 // annotalysis.
2009 bool VisitFrame() NO_THREAD_SAFETY_ANALYSIS {
Ian Rogers0399dde2012-06-06 17:09:28 -07002010 if (GetFrameId() != frame_id_) {
2011 return true; // Not our frame, carry on.
Elliott Hughesdbb40792011-11-18 17:05:22 -08002012 }
Ian Rogers0399dde2012-06-06 17:09:28 -07002013 // TODO: check that the tag is compatible with the actual type of the slot!
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002014 mirror::AbstractMethod* m = GetMethod();
Ian Rogers0399dde2012-06-06 17:09:28 -07002015 uint16_t reg = DemangleSlot(slot_, m);
Elliott Hughesdbb40792011-11-18 17:05:22 -08002016
Ian Rogers0399dde2012-06-06 17:09:28 -07002017 switch (tag_) {
2018 case JDWP::JT_BOOLEAN:
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 boolean local " << reg << " = " << intVal;
2023 JDWP::Set1(buf_+1, intVal != 0);
2024 }
2025 break;
2026 case JDWP::JT_BYTE:
2027 {
2028 CHECK_EQ(width_, 1U);
Ian Rogers2bcb4a42012-11-08 10:39:18 -08002029 uint32_t intVal = GetVReg(m, reg, kIntVReg);
Ian Rogers0399dde2012-06-06 17:09:28 -07002030 VLOG(jdwp) << "get byte local " << reg << " = " << intVal;
2031 JDWP::Set1(buf_+1, intVal);
2032 }
2033 break;
2034 case JDWP::JT_SHORT:
2035 case JDWP::JT_CHAR:
2036 {
2037 CHECK_EQ(width_, 2U);
Ian Rogers2bcb4a42012-11-08 10:39:18 -08002038 uint32_t intVal = GetVReg(m, reg, kIntVReg);
Ian Rogers0399dde2012-06-06 17:09:28 -07002039 VLOG(jdwp) << "get short/char local " << reg << " = " << intVal;
2040 JDWP::Set2BE(buf_+1, intVal);
2041 }
2042 break;
2043 case JDWP::JT_INT:
Ian Rogers2bcb4a42012-11-08 10:39:18 -08002044 {
2045 CHECK_EQ(width_, 4U);
2046 uint32_t intVal = GetVReg(m, reg, kIntVReg);
2047 VLOG(jdwp) << "get int local " << reg << " = " << intVal;
2048 JDWP::Set4BE(buf_+1, intVal);
2049 }
2050 break;
Ian Rogers0399dde2012-06-06 17:09:28 -07002051 case JDWP::JT_FLOAT:
2052 {
2053 CHECK_EQ(width_, 4U);
Ian Rogers2bcb4a42012-11-08 10:39:18 -08002054 uint32_t intVal = GetVReg(m, reg, kFloatVReg);
Ian Rogers0399dde2012-06-06 17:09:28 -07002055 VLOG(jdwp) << "get int/float local " << reg << " = " << intVal;
2056 JDWP::Set4BE(buf_+1, intVal);
2057 }
2058 break;
2059 case JDWP::JT_ARRAY:
2060 {
2061 CHECK_EQ(width_, sizeof(JDWP::ObjectId));
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002062 mirror::Object* o = reinterpret_cast<mirror::Object*>(GetVReg(m, reg, kReferenceVReg));
Ian Rogers0399dde2012-06-06 17:09:28 -07002063 VLOG(jdwp) << "get array local " << reg << " = " << o;
2064 if (!Runtime::Current()->GetHeap()->IsHeapAddress(o)) {
2065 LOG(FATAL) << "Register " << reg << " expected to hold array: " << o;
2066 }
2067 JDWP::SetObjectId(buf_+1, gRegistry->Add(o));
2068 }
2069 break;
2070 case JDWP::JT_CLASS_LOADER:
2071 case JDWP::JT_CLASS_OBJECT:
2072 case JDWP::JT_OBJECT:
2073 case JDWP::JT_STRING:
2074 case JDWP::JT_THREAD:
2075 case JDWP::JT_THREAD_GROUP:
2076 {
2077 CHECK_EQ(width_, sizeof(JDWP::ObjectId));
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002078 mirror::Object* o = reinterpret_cast<mirror::Object*>(GetVReg(m, reg, kReferenceVReg));
Ian Rogers0399dde2012-06-06 17:09:28 -07002079 VLOG(jdwp) << "get object local " << reg << " = " << o;
2080 if (!Runtime::Current()->GetHeap()->IsHeapAddress(o)) {
2081 LOG(FATAL) << "Register " << reg << " expected to hold object: " << o;
2082 }
2083 tag_ = TagFromObject(o);
2084 JDWP::SetObjectId(buf_+1, gRegistry->Add(o));
2085 }
2086 break;
2087 case JDWP::JT_DOUBLE:
Ian Rogers2bcb4a42012-11-08 10:39:18 -08002088 {
2089 CHECK_EQ(width_, 8U);
2090 uint32_t lo = GetVReg(m, reg, kDoubleLoVReg);
2091 uint64_t hi = GetVReg(m, reg + 1, kDoubleHiVReg);
2092 uint64_t longVal = (hi << 32) | lo;
2093 VLOG(jdwp) << "get double/long local " << hi << ":" << lo << " = " << longVal;
2094 JDWP::Set8BE(buf_+1, longVal);
2095 }
2096 break;
Ian Rogers0399dde2012-06-06 17:09:28 -07002097 case JDWP::JT_LONG:
2098 {
2099 CHECK_EQ(width_, 8U);
Ian Rogers2bcb4a42012-11-08 10:39:18 -08002100 uint32_t lo = GetVReg(m, reg, kLongLoVReg);
2101 uint64_t hi = GetVReg(m, reg + 1, kLongHiVReg);
Ian Rogers0399dde2012-06-06 17:09:28 -07002102 uint64_t longVal = (hi << 32) | lo;
2103 VLOG(jdwp) << "get double/long local " << hi << ":" << lo << " = " << longVal;
2104 JDWP::Set8BE(buf_+1, longVal);
2105 }
2106 break;
2107 default:
2108 LOG(FATAL) << "Unknown tag " << tag_;
2109 break;
2110 }
2111
2112 // Prepend tag, which may have been updated.
2113 JDWP::Set1(buf_, tag_);
2114 return false;
2115 }
2116
2117 const JDWP::FrameId frame_id_;
2118 const int slot_;
2119 JDWP::JdwpTag tag_;
2120 uint8_t* const buf_;
2121 const size_t width_;
2122 };
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002123
2124 ScopedObjectAccessUnchecked soa(Thread::Current());
jeffhaoa77f0f62012-12-05 17:19:31 -08002125 MutexLock mu(soa.Self(), *Locks::thread_list_lock_);
Elliott Hughes221229c2013-01-08 18:17:50 -08002126 Thread* thread;
2127 JDWP::JdwpError error = DecodeThread(soa, thread_id, thread);
2128 if (error != JDWP::ERR_NONE) {
2129 return;
2130 }
Ian Rogers0399dde2012-06-06 17:09:28 -07002131 UniquePtr<Context> context(Context::Create());
Ian Rogers7a22fa62013-01-23 12:16:16 -08002132 GetLocalVisitor visitor(thread, context.get(), frame_id, slot, tag, buf, width);
Ian Rogers0399dde2012-06-06 17:09:28 -07002133 visitor.WalkStack();
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002134}
2135
Elliott Hughes88d63092013-01-09 09:55:54 -08002136void Dbg::SetLocalValue(JDWP::ObjectId thread_id, JDWP::FrameId frame_id, int slot, JDWP::JdwpTag tag,
Ian Rogers0399dde2012-06-06 17:09:28 -07002137 uint64_t value, size_t width) {
2138 struct SetLocalVisitor : public StackVisitor {
Ian Rogers7a22fa62013-01-23 12:16:16 -08002139 SetLocalVisitor(Thread* thread, Context* context,
Ian Rogers0399dde2012-06-06 17:09:28 -07002140 JDWP::FrameId frame_id, int slot, JDWP::JdwpTag tag, uint64_t value,
Ian Rogersca190662012-06-26 15:45:57 -07002141 size_t width)
Ian Rogersb726dcb2012-09-05 08:57:23 -07002142 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_)
Ian Rogers7a22fa62013-01-23 12:16:16 -08002143 : StackVisitor(thread, context),
Elliott Hughes08fc03a2012-06-26 17:34:00 -07002144 frame_id_(frame_id), slot_(slot), tag_(tag), value_(value), width_(width) {}
Ian Rogersca190662012-06-26 15:45:57 -07002145
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002146 // TODO: Enable annotalysis. We know lock is held in constructor, but abstraction confuses
2147 // annotalysis.
2148 bool VisitFrame() NO_THREAD_SAFETY_ANALYSIS {
Ian Rogers0399dde2012-06-06 17:09:28 -07002149 if (GetFrameId() != frame_id_) {
2150 return true; // Not our frame, carry on.
2151 }
2152 // TODO: check that the tag is compatible with the actual type of the slot!
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002153 mirror::AbstractMethod* m = GetMethod();
Ian Rogers0399dde2012-06-06 17:09:28 -07002154 uint16_t reg = DemangleSlot(slot_, m);
2155
2156 switch (tag_) {
2157 case JDWP::JT_BOOLEAN:
2158 case JDWP::JT_BYTE:
2159 CHECK_EQ(width_, 1U);
Ian Rogers2bcb4a42012-11-08 10:39:18 -08002160 SetVReg(m, reg, static_cast<uint32_t>(value_), kIntVReg);
Ian Rogers0399dde2012-06-06 17:09:28 -07002161 break;
2162 case JDWP::JT_SHORT:
2163 case JDWP::JT_CHAR:
2164 CHECK_EQ(width_, 2U);
Ian Rogers2bcb4a42012-11-08 10:39:18 -08002165 SetVReg(m, reg, static_cast<uint32_t>(value_), kIntVReg);
Ian Rogers0399dde2012-06-06 17:09:28 -07002166 break;
2167 case JDWP::JT_INT:
Ian Rogers2bcb4a42012-11-08 10:39:18 -08002168 CHECK_EQ(width_, 4U);
2169 SetVReg(m, reg, static_cast<uint32_t>(value_), kIntVReg);
2170 break;
Ian Rogers0399dde2012-06-06 17:09:28 -07002171 case JDWP::JT_FLOAT:
2172 CHECK_EQ(width_, 4U);
Ian Rogers2bcb4a42012-11-08 10:39:18 -08002173 SetVReg(m, reg, static_cast<uint32_t>(value_), kFloatVReg);
Ian Rogers0399dde2012-06-06 17:09:28 -07002174 break;
2175 case JDWP::JT_ARRAY:
2176 case JDWP::JT_OBJECT:
2177 case JDWP::JT_STRING:
2178 {
2179 CHECK_EQ(width_, sizeof(JDWP::ObjectId));
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002180 mirror::Object* o = gRegistry->Get<mirror::Object*>(static_cast<JDWP::ObjectId>(value_));
Elliott Hughes64f574f2013-02-20 14:57:12 -08002181 if (o == ObjectRegistry::kInvalidObject) {
Ian Rogers0399dde2012-06-06 17:09:28 -07002182 UNIMPLEMENTED(FATAL) << "return an error code when given an invalid object to store";
2183 }
Ian Rogers2bcb4a42012-11-08 10:39:18 -08002184 SetVReg(m, reg, static_cast<uint32_t>(reinterpret_cast<uintptr_t>(o)), kReferenceVReg);
Ian Rogers0399dde2012-06-06 17:09:28 -07002185 }
2186 break;
2187 case JDWP::JT_DOUBLE:
Ian Rogers2bcb4a42012-11-08 10:39:18 -08002188 CHECK_EQ(width_, 8U);
2189 SetVReg(m, reg, static_cast<uint32_t>(value_), kDoubleLoVReg);
2190 SetVReg(m, reg + 1, static_cast<uint32_t>(value_ >> 32), kDoubleHiVReg);
2191 break;
Ian Rogers0399dde2012-06-06 17:09:28 -07002192 case JDWP::JT_LONG:
2193 CHECK_EQ(width_, 8U);
Ian Rogers2bcb4a42012-11-08 10:39:18 -08002194 SetVReg(m, reg, static_cast<uint32_t>(value_), kLongLoVReg);
2195 SetVReg(m, reg + 1, static_cast<uint32_t>(value_ >> 32), kLongHiVReg);
Ian Rogers0399dde2012-06-06 17:09:28 -07002196 break;
2197 default:
2198 LOG(FATAL) << "Unknown tag " << tag_;
2199 break;
2200 }
2201 return false;
2202 }
2203
2204 const JDWP::FrameId frame_id_;
2205 const int slot_;
2206 const JDWP::JdwpTag tag_;
2207 const uint64_t value_;
2208 const size_t width_;
2209 };
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002210
2211 ScopedObjectAccessUnchecked soa(Thread::Current());
jeffhaoa77f0f62012-12-05 17:19:31 -08002212 MutexLock mu(soa.Self(), *Locks::thread_list_lock_);
Elliott Hughes221229c2013-01-08 18:17:50 -08002213 Thread* thread;
2214 JDWP::JdwpError error = DecodeThread(soa, thread_id, thread);
2215 if (error != JDWP::ERR_NONE) {
2216 return;
2217 }
Elliott Hughes08fc03a2012-06-26 17:34:00 -07002218 UniquePtr<Context> context(Context::Create());
Ian Rogers7a22fa62013-01-23 12:16:16 -08002219 SetLocalVisitor visitor(thread, context.get(), frame_id, slot, tag, value, width);
Ian Rogers0399dde2012-06-06 17:09:28 -07002220 visitor.WalkStack();
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002221}
2222
Ian Rogers62d6c772013-02-27 08:32:07 -08002223void Dbg::PostLocationEvent(const mirror::AbstractMethod* m, int dex_pc,
2224 mirror::Object* this_object, int event_flags) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002225 mirror::Class* c = m->GetDeclaringClass();
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08002226
2227 JDWP::JdwpLocation location;
Elliott Hughes74847412012-06-20 18:10:21 -07002228 location.type_tag = c->IsInterface() ? JDWP::TT_INTERFACE : JDWP::TT_CLASS;
Elliott Hughes64f574f2013-02-20 14:57:12 -08002229 location.class_id = gRegistry->AddRefType(c);
Elliott Hughes74847412012-06-20 18:10:21 -07002230 location.method_id = ToMethodId(m);
Elliott Hughes972a47b2012-02-21 18:16:06 -08002231 location.dex_pc = m->IsNative() ? -1 : dex_pc;
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08002232
Elliott Hughes64f574f2013-02-20 14:57:12 -08002233 // If 'this_object' isn't already in the registry, we know that we're not looking for it,
2234 // so there's no point adding it to the registry and burning through ids.
2235 JDWP::ObjectId this_id = 0;
2236 if (gRegistry->Contains(this_object)) {
2237 this_id = gRegistry->Add(this_object);
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08002238 }
Elliott Hughes64f574f2013-02-20 14:57:12 -08002239 gJdwpState->PostLocationEvent(&location, this_id, event_flags);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002240}
2241
Ian Rogers62d6c772013-02-27 08:32:07 -08002242void Dbg::PostException(Thread* thread, const ThrowLocation& throw_location,
2243 mirror::AbstractMethod* catch_method,
Elliott Hughes64f574f2013-02-20 14:57:12 -08002244 uint32_t catch_dex_pc, mirror::Throwable* exception_object) {
Elliott Hughesc0f09332012-03-26 13:27:06 -07002245 if (!IsDebuggerActive()) {
Ian Rogers0ad5bb82011-12-07 10:16:32 -08002246 return;
2247 }
Elliott Hughes4740cdf2011-12-07 14:07:12 -08002248
Ian Rogers62d6c772013-02-27 08:32:07 -08002249 JDWP::JdwpLocation jdwp_throw_location;
2250 SetLocation(jdwp_throw_location, throw_location.GetMethod(), throw_location.GetDexPc());
Elliott Hughesd07986f2011-12-06 18:27:45 -08002251 JDWP::JdwpLocation catch_location;
Elliott Hughescaf76542012-06-28 16:08:22 -07002252 SetLocation(catch_location, catch_method, catch_dex_pc);
Elliott Hughesd07986f2011-12-06 18:27:45 -08002253
2254 // We need 'this' for InstanceOnly filters.
Ian Rogers62d6c772013-02-27 08:32:07 -08002255 JDWP::ObjectId this_id = gRegistry->Add(throw_location.GetThis());
Elliott Hughes64f574f2013-02-20 14:57:12 -08002256 JDWP::ObjectId exception_id = gRegistry->Add(exception_object);
2257 JDWP::RefTypeId exception_class_id = gRegistry->AddRefType(exception_object->GetClass());
Elliott Hughesd07986f2011-12-06 18:27:45 -08002258
Ian Rogers62d6c772013-02-27 08:32:07 -08002259 gJdwpState->PostException(&jdwp_throw_location, exception_id, exception_class_id, &catch_location,
2260 this_id);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002261}
2262
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002263void Dbg::PostClassPrepare(mirror::Class* c) {
Elliott Hughesc0f09332012-03-26 13:27:06 -07002264 if (!IsDebuggerActive()) {
Elliott Hughes4740cdf2011-12-07 14:07:12 -08002265 return;
2266 }
2267
Elliott Hughes3d30d9b2011-12-07 17:35:48 -08002268 // OLD-TODO - we currently always send both "verified" and "prepared" since
Elliott Hughes4740cdf2011-12-07 14:07:12 -08002269 // debuggers seem to like that. There might be some advantage to honesty,
2270 // since the class may not yet be verified.
2271 int state = JDWP::CS_VERIFIED | JDWP::CS_PREPARED;
2272 JDWP::JdwpTypeTag tag = c->IsInterface() ? JDWP::TT_INTERFACE : JDWP::TT_CLASS;
2273 gJdwpState->PostClassPrepare(tag, gRegistry->Add(c), ClassHelper(c).GetDescriptor(), state);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002274}
2275
Ian Rogers62d6c772013-02-27 08:32:07 -08002276void Dbg::UpdateDebugger(Thread* thread, mirror::Object* this_object,
2277 const mirror::AbstractMethod* m, uint32_t dex_pc) {
2278 if (!IsDebuggerActive() || dex_pc == static_cast<uint32_t>(-2) /* fake method exit */) {
Elliott Hughes2aa2e392012-02-17 17:15:43 -08002279 return;
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08002280 }
2281
Elliott Hughes2aa2e392012-02-17 17:15:43 -08002282 int event_flags = 0;
2283
Elliott Hughes86964332012-02-15 19:37:42 -08002284 if (IsBreakpoint(m, dex_pc)) {
2285 event_flags |= kBreakpoint;
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08002286 }
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08002287
jeffhao09bfc6a2012-12-11 18:11:43 -08002288 {
2289 // If the debugger is single-stepping one of our threads, check to
2290 // see if we're that thread and we've reached a step point.
2291 MutexLock mu(Thread::Current(), *Locks::breakpoint_lock_);
Ian Rogers62d6c772013-02-27 08:32:07 -08002292 if (gSingleStepControl.is_active && gSingleStepControl.thread == thread) {
jeffhao09bfc6a2012-12-11 18:11:43 -08002293 CHECK(!m->IsNative());
2294 if (gSingleStepControl.step_depth == JDWP::SD_INTO) {
2295 // Step into method calls. We break when the line number
2296 // or method pointer changes. If we're in SS_MIN mode, we
2297 // always stop.
2298 if (gSingleStepControl.method != m) {
2299 event_flags |= kSingleStep;
2300 VLOG(jdwp) << "SS new method";
2301 } else if (gSingleStepControl.step_size == JDWP::SS_MIN) {
Elliott Hughes86964332012-02-15 19:37:42 -08002302 event_flags |= kSingleStep;
2303 VLOG(jdwp) << "SS new instruction";
Elliott Hughes2435a572012-02-17 16:07:41 -08002304 } else if (gSingleStepControl.dex_pcs.find(dex_pc) == gSingleStepControl.dex_pcs.end()) {
2305 event_flags |= kSingleStep;
2306 VLOG(jdwp) << "SS new line";
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08002307 }
jeffhao09bfc6a2012-12-11 18:11:43 -08002308 } else if (gSingleStepControl.step_depth == JDWP::SD_OVER) {
2309 // Step over method calls. We break when the line number is
2310 // different and the frame depth is <= the original frame
2311 // depth. (We can't just compare on the method, because we
2312 // might get unrolled past it by an exception, and it's tricky
2313 // to identify recursion.)
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08002314
Ian Rogers62d6c772013-02-27 08:32:07 -08002315 int stack_depth = GetStackDepth(thread);
Elliott Hughes86964332012-02-15 19:37:42 -08002316
jeffhao09bfc6a2012-12-11 18:11:43 -08002317 if (stack_depth < gSingleStepControl.stack_depth) {
2318 // popped up one or more frames, always trigger
2319 event_flags |= kSingleStep;
2320 VLOG(jdwp) << "SS method pop";
2321 } else if (stack_depth == gSingleStepControl.stack_depth) {
2322 // same depth, see if we moved
2323 if (gSingleStepControl.step_size == JDWP::SS_MIN) {
2324 event_flags |= kSingleStep;
2325 VLOG(jdwp) << "SS new instruction";
2326 } else if (gSingleStepControl.dex_pcs.find(dex_pc) == gSingleStepControl.dex_pcs.end()) {
2327 event_flags |= kSingleStep;
2328 VLOG(jdwp) << "SS new line";
2329 }
2330 }
2331 } else {
2332 CHECK_EQ(gSingleStepControl.step_depth, JDWP::SD_OUT);
2333 // Return from the current method. We break when the frame
2334 // depth pops up.
2335
2336 // This differs from the "method exit" break in that it stops
2337 // with the PC at the next instruction in the returned-to
2338 // function, rather than the end of the returning function.
2339
Ian Rogers62d6c772013-02-27 08:32:07 -08002340 int stack_depth = GetStackDepth(thread);
jeffhao09bfc6a2012-12-11 18:11:43 -08002341 if (stack_depth < gSingleStepControl.stack_depth) {
2342 event_flags |= kSingleStep;
2343 VLOG(jdwp) << "SS method pop";
2344 }
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08002345 }
2346 }
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08002347 }
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08002348
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08002349 // If there's something interesting going on, see if it matches one
2350 // of the debugger filters.
2351 if (event_flags != 0) {
Ian Rogers62d6c772013-02-27 08:32:07 -08002352 Dbg::PostLocationEvent(m, dex_pc, this_object, event_flags);
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08002353 }
2354}
2355
Elliott Hughes86964332012-02-15 19:37:42 -08002356void Dbg::WatchLocation(const JDWP::JdwpLocation* location) {
jeffhao09bfc6a2012-12-11 18:11:43 -08002357 MutexLock mu(Thread::Current(), *Locks::breakpoint_lock_);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002358 mirror::AbstractMethod* m = FromMethodId(location->method_id);
Elliott Hughes972a47b2012-02-21 18:16:06 -08002359 gBreakpoints.push_back(Breakpoint(m, location->dex_pc));
Elliott Hughes86964332012-02-15 19:37:42 -08002360 VLOG(jdwp) << "Set breakpoint #" << (gBreakpoints.size() - 1) << ": " << gBreakpoints[gBreakpoints.size() - 1];
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002361}
2362
Elliott Hughes86964332012-02-15 19:37:42 -08002363void Dbg::UnwatchLocation(const JDWP::JdwpLocation* location) {
jeffhao09bfc6a2012-12-11 18:11:43 -08002364 MutexLock mu(Thread::Current(), *Locks::breakpoint_lock_);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002365 mirror::AbstractMethod* m = FromMethodId(location->method_id);
Elliott Hughes86964332012-02-15 19:37:42 -08002366 for (size_t i = 0; i < gBreakpoints.size(); ++i) {
Elliott Hughes972a47b2012-02-21 18:16:06 -08002367 if (gBreakpoints[i].method == m && gBreakpoints[i].dex_pc == location->dex_pc) {
Elliott Hughes86964332012-02-15 19:37:42 -08002368 VLOG(jdwp) << "Removed breakpoint #" << i << ": " << gBreakpoints[i];
2369 gBreakpoints.erase(gBreakpoints.begin() + i);
2370 return;
2371 }
2372 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002373}
2374
Elliott Hughes221229c2013-01-08 18:17:50 -08002375JDWP::JdwpError Dbg::ConfigureStep(JDWP::ObjectId thread_id, JDWP::JdwpStepSize step_size,
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002376 JDWP::JdwpStepDepth step_depth) {
2377 ScopedObjectAccessUnchecked soa(Thread::Current());
jeffhaoa77f0f62012-12-05 17:19:31 -08002378 MutexLock mu(soa.Self(), *Locks::thread_list_lock_);
Elliott Hughes221229c2013-01-08 18:17:50 -08002379 Thread* thread;
2380 JDWP::JdwpError error = DecodeThread(soa, thread_id, thread);
2381 if (error != JDWP::ERR_NONE) {
2382 return error;
Elliott Hughes2435a572012-02-17 16:07:41 -08002383 }
Elliott Hughes86964332012-02-15 19:37:42 -08002384
jeffhao09bfc6a2012-12-11 18:11:43 -08002385 MutexLock mu2(soa.Self(), *Locks::breakpoint_lock_);
Elliott Hughes86964332012-02-15 19:37:42 -08002386 // TODO: there's no theoretical reason why we couldn't support single-stepping
2387 // of multiple threads at once, but we never did so historically.
2388 if (gSingleStepControl.thread != NULL && thread != gSingleStepControl.thread) {
2389 LOG(WARNING) << "single-step already active for " << *gSingleStepControl.thread
2390 << "; switching to " << *thread;
2391 }
2392
Elliott Hughes2435a572012-02-17 16:07:41 -08002393 //
2394 // Work out what Method* we're in, the current line number, and how deep the stack currently
2395 // is for step-out.
2396 //
2397
Ian Rogers0399dde2012-06-06 17:09:28 -07002398 struct SingleStepStackVisitor : public StackVisitor {
Ian Rogers7a22fa62013-01-23 12:16:16 -08002399 SingleStepStackVisitor(Thread* thread)
jeffhao09bfc6a2012-12-11 18:11:43 -08002400 EXCLUSIVE_LOCKS_REQUIRED(Locks::breakpoint_lock_)
Ian Rogersb726dcb2012-09-05 08:57:23 -07002401 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_)
Ian Rogers7a22fa62013-01-23 12:16:16 -08002402 : StackVisitor(thread, NULL) {
Elliott Hughes86964332012-02-15 19:37:42 -08002403 gSingleStepControl.method = NULL;
2404 gSingleStepControl.stack_depth = 0;
2405 }
Ian Rogersca190662012-06-26 15:45:57 -07002406
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002407 // TODO: Enable annotalysis. We know lock is held in constructor, but abstraction confuses
2408 // annotalysis.
2409 bool VisitFrame() NO_THREAD_SAFETY_ANALYSIS {
jeffhao09bfc6a2012-12-11 18:11:43 -08002410 Locks::breakpoint_lock_->AssertHeld(Thread::Current());
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002411 const mirror::AbstractMethod* m = GetMethod();
Ian Rogers0399dde2012-06-06 17:09:28 -07002412 if (!m->IsRuntimeMethod()) {
Elliott Hughes86964332012-02-15 19:37:42 -08002413 ++gSingleStepControl.stack_depth;
2414 if (gSingleStepControl.method == NULL) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002415 const mirror::DexCache* dex_cache = m->GetDeclaringClass()->GetDexCache();
Elliott Hughes2435a572012-02-17 16:07:41 -08002416 gSingleStepControl.method = m;
2417 gSingleStepControl.line_number = -1;
2418 if (dex_cache != NULL) {
Ian Rogers4445a7e2012-10-05 17:19:13 -07002419 const DexFile& dex_file = *dex_cache->GetDexFile();
Ian Rogers0399dde2012-06-06 17:09:28 -07002420 gSingleStepControl.line_number = dex_file.GetLineNumFromPC(m, GetDexPc());
Elliott Hughes2435a572012-02-17 16:07:41 -08002421 }
Elliott Hughes86964332012-02-15 19:37:42 -08002422 }
2423 }
Elliott Hughes530fa002012-03-12 11:44:49 -07002424 return true;
Elliott Hughes86964332012-02-15 19:37:42 -08002425 }
2426 };
Ian Rogers7a22fa62013-01-23 12:16:16 -08002427 SingleStepStackVisitor visitor(thread);
Ian Rogers0399dde2012-06-06 17:09:28 -07002428 visitor.WalkStack();
Elliott Hughes86964332012-02-15 19:37:42 -08002429
Elliott Hughes2435a572012-02-17 16:07:41 -08002430 //
2431 // Find the dex_pc values that correspond to the current line, for line-based single-stepping.
2432 //
2433
2434 struct DebugCallbackContext {
jeffhao09bfc6a2012-12-11 18:11:43 -08002435 DebugCallbackContext() EXCLUSIVE_LOCKS_REQUIRED(Locks::breakpoint_lock_) {
Elliott Hughes2435a572012-02-17 16:07:41 -08002436 last_pc_valid = false;
2437 last_pc = 0;
Elliott Hughes2435a572012-02-17 16:07:41 -08002438 }
2439
jeffhao09bfc6a2012-12-11 18:11:43 -08002440 // TODO: Enable annotalysis. We know lock is held in constructor, but abstraction confuses
2441 // annotalysis.
2442 static bool Callback(void* raw_context, uint32_t address, uint32_t line_number) NO_THREAD_SAFETY_ANALYSIS {
2443 Locks::breakpoint_lock_->AssertHeld(Thread::Current());
Elliott Hughes2435a572012-02-17 16:07:41 -08002444 DebugCallbackContext* context = reinterpret_cast<DebugCallbackContext*>(raw_context);
2445 if (static_cast<int32_t>(line_number) == gSingleStepControl.line_number) {
2446 if (!context->last_pc_valid) {
2447 // Everything from this address until the next line change is ours.
2448 context->last_pc = address;
2449 context->last_pc_valid = true;
2450 }
2451 // Otherwise, if we're already in a valid range for this line,
2452 // just keep going (shouldn't really happen)...
2453 } else if (context->last_pc_valid) { // and the line number is new
2454 // Add everything from the last entry up until here to the set
2455 for (uint32_t dex_pc = context->last_pc; dex_pc < address; ++dex_pc) {
2456 gSingleStepControl.dex_pcs.insert(dex_pc);
2457 }
2458 context->last_pc_valid = false;
2459 }
2460 return false; // There may be multiple entries for any given line.
2461 }
2462
jeffhao09bfc6a2012-12-11 18:11:43 -08002463 // TODO: Enable annotalysis. We know lock is held in constructor, but abstraction confuses
2464 // annotalysis.
2465 ~DebugCallbackContext() NO_THREAD_SAFETY_ANALYSIS {
2466 Locks::breakpoint_lock_->AssertHeld(Thread::Current());
Elliott Hughes2435a572012-02-17 16:07:41 -08002467 // If the line number was the last in the position table...
2468 if (last_pc_valid) {
2469 size_t end = MethodHelper(gSingleStepControl.method).GetCodeItem()->insns_size_in_code_units_;
2470 for (uint32_t dex_pc = last_pc; dex_pc < end; ++dex_pc) {
2471 gSingleStepControl.dex_pcs.insert(dex_pc);
2472 }
2473 }
2474 }
2475
2476 bool last_pc_valid;
2477 uint32_t last_pc;
2478 };
Elliott Hughes3e2e1a22012-02-21 11:33:41 -08002479 gSingleStepControl.dex_pcs.clear();
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002480 const mirror::AbstractMethod* m = gSingleStepControl.method;
Elliott Hughes3e2e1a22012-02-21 11:33:41 -08002481 if (m->IsNative()) {
2482 gSingleStepControl.line_number = -1;
2483 } else {
2484 DebugCallbackContext context;
2485 MethodHelper mh(m);
2486 mh.GetDexFile().DecodeDebugInfo(mh.GetCodeItem(), m->IsStatic(), m->GetDexMethodIndex(),
2487 DebugCallbackContext::Callback, NULL, &context);
2488 }
Elliott Hughes2435a572012-02-17 16:07:41 -08002489
2490 //
2491 // Everything else...
2492 //
2493
Elliott Hughes86964332012-02-15 19:37:42 -08002494 gSingleStepControl.thread = thread;
2495 gSingleStepControl.step_size = step_size;
2496 gSingleStepControl.step_depth = step_depth;
2497 gSingleStepControl.is_active = true;
2498
Elliott Hughes2435a572012-02-17 16:07:41 -08002499 if (VLOG_IS_ON(jdwp)) {
2500 VLOG(jdwp) << "Single-step thread: " << *gSingleStepControl.thread;
2501 VLOG(jdwp) << "Single-step step size: " << gSingleStepControl.step_size;
2502 VLOG(jdwp) << "Single-step step depth: " << gSingleStepControl.step_depth;
2503 VLOG(jdwp) << "Single-step current method: " << PrettyMethod(gSingleStepControl.method);
2504 VLOG(jdwp) << "Single-step current line: " << gSingleStepControl.line_number;
2505 VLOG(jdwp) << "Single-step current stack depth: " << gSingleStepControl.stack_depth;
2506 VLOG(jdwp) << "Single-step dex_pc values:";
2507 for (std::set<uint32_t>::iterator it = gSingleStepControl.dex_pcs.begin() ; it != gSingleStepControl.dex_pcs.end(); ++it) {
Elliott Hughes229feb72012-02-23 13:33:29 -08002508 VLOG(jdwp) << StringPrintf(" %#x", *it);
Elliott Hughes2435a572012-02-17 16:07:41 -08002509 }
2510 }
2511
2512 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002513}
2514
Elliott Hughes221229c2013-01-08 18:17:50 -08002515void Dbg::UnconfigureStep(JDWP::ObjectId /*thread_id*/) {
jeffhao09bfc6a2012-12-11 18:11:43 -08002516 MutexLock mu(Thread::Current(), *Locks::breakpoint_lock_);
Elliott Hughesf8349362012-06-18 15:00:06 -07002517
Elliott Hughes86964332012-02-15 19:37:42 -08002518 gSingleStepControl.is_active = false;
2519 gSingleStepControl.thread = NULL;
Elliott Hughes2435a572012-02-17 16:07:41 -08002520 gSingleStepControl.dex_pcs.clear();
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002521}
2522
Elliott Hughes45651fd2012-02-21 15:48:20 -08002523static char JdwpTagToShortyChar(JDWP::JdwpTag tag) {
2524 switch (tag) {
2525 default:
2526 LOG(FATAL) << "unknown JDWP tag: " << PrintableChar(tag);
2527
2528 // Primitives.
2529 case JDWP::JT_BYTE: return 'B';
2530 case JDWP::JT_CHAR: return 'C';
2531 case JDWP::JT_FLOAT: return 'F';
2532 case JDWP::JT_DOUBLE: return 'D';
2533 case JDWP::JT_INT: return 'I';
2534 case JDWP::JT_LONG: return 'J';
2535 case JDWP::JT_SHORT: return 'S';
2536 case JDWP::JT_VOID: return 'V';
2537 case JDWP::JT_BOOLEAN: return 'Z';
2538
2539 // Reference types.
2540 case JDWP::JT_ARRAY:
2541 case JDWP::JT_OBJECT:
2542 case JDWP::JT_STRING:
2543 case JDWP::JT_THREAD:
2544 case JDWP::JT_THREAD_GROUP:
2545 case JDWP::JT_CLASS_LOADER:
2546 case JDWP::JT_CLASS_OBJECT:
2547 return 'L';
2548 }
2549}
2550
Elliott Hughes88d63092013-01-09 09:55:54 -08002551JDWP::JdwpError Dbg::InvokeMethod(JDWP::ObjectId thread_id, JDWP::ObjectId object_id,
2552 JDWP::RefTypeId class_id, JDWP::MethodId method_id,
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002553 uint32_t arg_count, uint64_t* arg_values,
2554 JDWP::JdwpTag* arg_types, uint32_t options,
2555 JDWP::JdwpTag* pResultTag, uint64_t* pResultValue,
2556 JDWP::ObjectId* pExceptionId) {
Elliott Hughesd07986f2011-12-06 18:27:45 -08002557 ThreadList* thread_list = Runtime::Current()->GetThreadList();
2558
2559 Thread* targetThread = NULL;
2560 DebugInvokeReq* req = NULL;
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002561 Thread* self = Thread::Current();
Elliott Hughesd07986f2011-12-06 18:27:45 -08002562 {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002563 ScopedObjectAccessUnchecked soa(self);
Ian Rogers50b35e22012-10-04 10:09:15 -07002564 MutexLock mu(soa.Self(), *Locks::thread_list_lock_);
Elliott Hughes221229c2013-01-08 18:17:50 -08002565 JDWP::JdwpError error = DecodeThread(soa, thread_id, targetThread);
2566 if (error != JDWP::ERR_NONE) {
2567 LOG(ERROR) << "InvokeMethod request for invalid thread id " << thread_id;
2568 return error;
Elliott Hughesd07986f2011-12-06 18:27:45 -08002569 }
2570 req = targetThread->GetInvokeReq();
2571 if (!req->ready) {
2572 LOG(ERROR) << "InvokeMethod request for thread not stopped by event: " << *targetThread;
2573 return JDWP::ERR_INVALID_THREAD;
2574 }
2575
2576 /*
2577 * We currently have a bug where we don't successfully resume the
2578 * target thread if the suspend count is too deep. We're expected to
2579 * require one "resume" for each "suspend", but when asked to execute
2580 * a method we have to resume fully and then re-suspend it back to the
2581 * same level. (The easiest way to cause this is to type "suspend"
2582 * multiple times in jdb.)
2583 *
2584 * It's unclear what this means when the event specifies "resume all"
2585 * and some threads are suspended more deeply than others. This is
2586 * a rare problem, so for now we just prevent it from hanging forever
2587 * by rejecting the method invocation request. Without this, we will
2588 * be stuck waiting on a suspended thread.
2589 */
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002590 int suspend_count;
2591 {
Ian Rogers50b35e22012-10-04 10:09:15 -07002592 MutexLock mu2(soa.Self(), *Locks::thread_suspend_count_lock_);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002593 suspend_count = targetThread->GetSuspendCount();
2594 }
Elliott Hughesd07986f2011-12-06 18:27:45 -08002595 if (suspend_count > 1) {
2596 LOG(ERROR) << *targetThread << " suspend count too deep for method invocation: " << suspend_count;
2597 return JDWP::ERR_THREAD_SUSPENDED; // Probably not expected here.
2598 }
2599
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08002600 JDWP::JdwpError status;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002601 mirror::Object* receiver = gRegistry->Get<mirror::Object*>(object_id);
Elliott Hughes64f574f2013-02-20 14:57:12 -08002602 if (receiver == ObjectRegistry::kInvalidObject) {
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08002603 return JDWP::ERR_INVALID_OBJECT;
2604 }
Elliott Hughes45651fd2012-02-21 15:48:20 -08002605
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002606 mirror::Object* thread = gRegistry->Get<mirror::Object*>(thread_id);
Elliott Hughes64f574f2013-02-20 14:57:12 -08002607 if (thread == ObjectRegistry::kInvalidObject) {
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08002608 return JDWP::ERR_INVALID_OBJECT;
2609 }
Elliott Hughes45651fd2012-02-21 15:48:20 -08002610 // TODO: check that 'thread' is actually a java.lang.Thread!
2611
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002612 mirror::Class* c = DecodeClass(class_id, status);
Elliott Hughes45651fd2012-02-21 15:48:20 -08002613 if (c == NULL) {
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08002614 return status;
2615 }
Elliott Hughes45651fd2012-02-21 15:48:20 -08002616
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002617 mirror::AbstractMethod* m = FromMethodId(method_id);
Elliott Hughes45651fd2012-02-21 15:48:20 -08002618 if (m->IsStatic() != (receiver == NULL)) {
2619 return JDWP::ERR_INVALID_METHODID;
2620 }
2621 if (m->IsStatic()) {
2622 if (m->GetDeclaringClass() != c) {
2623 return JDWP::ERR_INVALID_METHODID;
2624 }
2625 } else {
2626 if (!m->GetDeclaringClass()->IsAssignableFrom(c)) {
2627 return JDWP::ERR_INVALID_METHODID;
2628 }
2629 }
2630
2631 // Check the argument list matches the method.
2632 MethodHelper mh(m);
2633 if (mh.GetShortyLength() - 1 != arg_count) {
2634 return JDWP::ERR_ILLEGAL_ARGUMENT;
2635 }
2636 const char* shorty = mh.GetShorty();
2637 for (size_t i = 0; i < arg_count; ++i) {
2638 if (shorty[i + 1] != JdwpTagToShortyChar(arg_types[i])) {
2639 return JDWP::ERR_ILLEGAL_ARGUMENT;
2640 }
2641 }
2642
2643 req->receiver_ = receiver;
2644 req->thread_ = thread;
2645 req->class_ = c;
2646 req->method_ = m;
2647 req->arg_count_ = arg_count;
2648 req->arg_values_ = arg_values;
Elliott Hughesd07986f2011-12-06 18:27:45 -08002649 req->options_ = options;
2650 req->invoke_needed_ = true;
2651 }
2652
2653 // The fact that we've released the thread list lock is a bit risky --- if the thread goes
2654 // away we're sitting high and dry -- but we must release this before the ResumeAllThreads
2655 // call, and it's unwise to hold it during WaitForSuspend.
2656
2657 {
2658 /*
2659 * We change our (JDWP thread) status, which should be THREAD_RUNNING,
Elliott Hughes81ff3182012-03-23 20:35:56 -07002660 * so we can suspend for a GC if the invoke request causes us to
Elliott Hughesd07986f2011-12-06 18:27:45 -08002661 * run out of memory. It's also a good idea to change it before locking
2662 * the invokeReq mutex, although that should never be held for long.
2663 */
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002664 self->TransitionFromRunnableToSuspended(kWaitingForDebuggerSend);
Elliott Hughesd07986f2011-12-06 18:27:45 -08002665
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08002666 VLOG(jdwp) << " Transferring control to event thread";
Elliott Hughesd07986f2011-12-06 18:27:45 -08002667 {
Ian Rogers50b35e22012-10-04 10:09:15 -07002668 MutexLock mu(self, req->lock_);
Elliott Hughesd07986f2011-12-06 18:27:45 -08002669
2670 if ((options & JDWP::INVOKE_SINGLE_THREADED) == 0) {
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08002671 VLOG(jdwp) << " Resuming all threads";
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002672 thread_list->UndoDebuggerSuspensions();
Elliott Hughesd07986f2011-12-06 18:27:45 -08002673 } else {
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08002674 VLOG(jdwp) << " Resuming event thread only";
Elliott Hughesd07986f2011-12-06 18:27:45 -08002675 thread_list->Resume(targetThread, true);
2676 }
2677
2678 // Wait for the request to finish executing.
2679 while (req->invoke_needed_) {
Ian Rogersc604d732012-10-14 16:09:54 -07002680 req->cond_.Wait(self);
Elliott Hughesd07986f2011-12-06 18:27:45 -08002681 }
2682 }
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08002683 VLOG(jdwp) << " Control has returned from event thread";
Elliott Hughesd07986f2011-12-06 18:27:45 -08002684
2685 /* wait for thread to re-suspend itself */
Elliott Hughes221229c2013-01-08 18:17:50 -08002686 SuspendThread(thread_id, false /* request_suspension */ );
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002687 self->TransitionFromSuspendedToRunnable();
Elliott Hughesd07986f2011-12-06 18:27:45 -08002688 }
2689
2690 /*
2691 * Suspend the threads. We waited for the target thread to suspend
2692 * itself, so all we need to do is suspend the others.
2693 *
2694 * The suspendAllThreads() call will double-suspend the event thread,
2695 * so we want to resume the target thread once to keep the books straight.
2696 */
2697 if ((options & JDWP::INVOKE_SINGLE_THREADED) == 0) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002698 self->TransitionFromRunnableToSuspended(kWaitingForDebuggerSuspension);
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08002699 VLOG(jdwp) << " Suspending all threads";
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002700 thread_list->SuspendAllForDebugger();
2701 self->TransitionFromSuspendedToRunnable();
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08002702 VLOG(jdwp) << " Resuming event thread to balance the count";
Elliott Hughesd07986f2011-12-06 18:27:45 -08002703 thread_list->Resume(targetThread, true);
2704 }
2705
2706 // Copy the result.
2707 *pResultTag = req->result_tag;
2708 if (IsPrimitiveTag(req->result_tag)) {
Elliott Hughesf24d3ce2012-04-11 17:43:37 -07002709 *pResultValue = req->result_value.GetJ();
Elliott Hughesd07986f2011-12-06 18:27:45 -08002710 } else {
Elliott Hughesf24d3ce2012-04-11 17:43:37 -07002711 *pResultValue = gRegistry->Add(req->result_value.GetL());
Elliott Hughesd07986f2011-12-06 18:27:45 -08002712 }
2713 *pExceptionId = req->exception;
2714 return req->error;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002715}
2716
2717void Dbg::ExecuteMethod(DebugInvokeReq* pReq) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002718 ScopedObjectAccess soa(Thread::Current());
Elliott Hughesd07986f2011-12-06 18:27:45 -08002719
Elliott Hughes81ff3182012-03-23 20:35:56 -07002720 // We can be called while an exception is pending. We need
Elliott Hughesd07986f2011-12-06 18:27:45 -08002721 // to preserve that across the method invocation.
Ian Rogers62d6c772013-02-27 08:32:07 -08002722 SirtRef<mirror::Object> old_throw_this_object(soa.Self(), NULL);
2723 SirtRef<mirror::AbstractMethod> old_throw_method(soa.Self(), NULL);
2724 SirtRef<mirror::Throwable> old_exception(soa.Self(), NULL);
2725 uint32_t old_throw_dex_pc;
2726 {
2727 ThrowLocation old_throw_location;
2728 mirror::Throwable* old_exception_obj = soa.Self()->GetException(&old_throw_location);
2729 old_throw_this_object.reset(old_throw_location.GetThis());
2730 old_throw_method.reset(old_throw_location.GetMethod());
2731 old_exception.reset(old_exception_obj);
2732 old_throw_dex_pc = old_throw_location.GetDexPc();
2733 soa.Self()->ClearException();
2734 }
Elliott Hughesd07986f2011-12-06 18:27:45 -08002735
2736 // Translate the method through the vtable, unless the debugger wants to suppress it.
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002737 mirror::AbstractMethod* m = pReq->method_;
Elliott Hughesd07986f2011-12-06 18:27:45 -08002738 if ((pReq->options_ & JDWP::INVOKE_NONVIRTUAL) == 0 && pReq->receiver_ != NULL) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002739 mirror::AbstractMethod* actual_method = pReq->class_->FindVirtualMethodForVirtualOrInterface(pReq->method_);
Elliott Hughes45651fd2012-02-21 15:48:20 -08002740 if (actual_method != m) {
2741 VLOG(jdwp) << "ExecuteMethod translated " << PrettyMethod(m) << " to " << PrettyMethod(actual_method);
2742 m = actual_method;
2743 }
Elliott Hughesd07986f2011-12-06 18:27:45 -08002744 }
Elliott Hughes45651fd2012-02-21 15:48:20 -08002745 VLOG(jdwp) << "ExecuteMethod " << PrettyMethod(m);
Elliott Hughesd07986f2011-12-06 18:27:45 -08002746 CHECK(m != NULL);
2747
2748 CHECK_EQ(sizeof(jvalue), sizeof(uint64_t));
2749
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002750 LOG(INFO) << "self=" << soa.Self() << " pReq->receiver_=" << pReq->receiver_ << " m=" << m
2751 << " #" << pReq->arg_count_ << " " << pReq->arg_values_;
Jeff Hao5d917302013-02-27 17:57:33 -08002752
2753 MethodHelper mh(m);
2754 ArgArray arg_array(mh.GetShorty(), mh.GetShortyLength());
2755 arg_array.BuildArgArray(soa, pReq->receiver_, reinterpret_cast<jvalue*>(pReq->arg_values_));
Jeff Hao6474d192013-03-26 14:08:09 -07002756 InvokeWithArgArray(soa, m, &arg_array, &pReq->result_value, mh.GetShorty()[0]);
Elliott Hughesd07986f2011-12-06 18:27:45 -08002757
Ian Rogers62d6c772013-02-27 08:32:07 -08002758 mirror::Throwable* exception = soa.Self()->GetException(NULL);
2759 soa.Self()->ClearException();
2760 pReq->exception = gRegistry->Add(exception);
Elliott Hughesd07986f2011-12-06 18:27:45 -08002761 pReq->result_tag = BasicTagFromDescriptor(MethodHelper(m).GetShorty());
2762 if (pReq->exception != 0) {
Ian Rogers62d6c772013-02-27 08:32:07 -08002763 VLOG(jdwp) << " JDWP invocation returning with exception=" << exception
2764 << " " << exception->Dump();
Elliott Hughesf24d3ce2012-04-11 17:43:37 -07002765 pReq->result_value.SetJ(0);
Elliott Hughesd07986f2011-12-06 18:27:45 -08002766 } else if (pReq->result_tag == JDWP::JT_OBJECT) {
2767 /* if no exception thrown, examine object result more closely */
Elliott Hughesf24d3ce2012-04-11 17:43:37 -07002768 JDWP::JdwpTag new_tag = TagFromObject(pReq->result_value.GetL());
Elliott Hughesd07986f2011-12-06 18:27:45 -08002769 if (new_tag != pReq->result_tag) {
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08002770 VLOG(jdwp) << " JDWP promoted result from " << pReq->result_tag << " to " << new_tag;
Elliott Hughesd07986f2011-12-06 18:27:45 -08002771 pReq->result_tag = new_tag;
2772 }
2773
2774 /*
2775 * Register the object. We don't actually need an ObjectId yet,
2776 * but we do need to be sure that the GC won't move or discard the
2777 * object when we switch out of RUNNING. The ObjectId conversion
2778 * will add the object to the "do not touch" list.
2779 *
2780 * We can't use the "tracked allocation" mechanism here because
2781 * the object is going to be handed off to a different thread.
2782 */
Elliott Hughesf24d3ce2012-04-11 17:43:37 -07002783 gRegistry->Add(pReq->result_value.GetL());
Elliott Hughesd07986f2011-12-06 18:27:45 -08002784 }
2785
2786 if (old_exception.get() != NULL) {
Ian Rogers62d6c772013-02-27 08:32:07 -08002787 ThrowLocation gc_safe_throw_location(old_throw_this_object.get(), old_throw_method.get(),
2788 old_throw_dex_pc);
2789 soa.Self()->SetException(gc_safe_throw_location, old_exception.get());
Elliott Hughesd07986f2011-12-06 18:27:45 -08002790 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002791}
2792
Elliott Hughesd07986f2011-12-06 18:27:45 -08002793/*
Elliott Hughes4b9702c2013-02-20 18:13:24 -08002794 * "request" contains a full JDWP packet, possibly with multiple chunks. We
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07002795 * need to process each, accumulate the replies, and ship the whole thing
2796 * back.
2797 *
2798 * Returns "true" if we have a reply. The reply buffer is newly allocated,
2799 * and includes the chunk type/length, followed by the data.
2800 *
Elliott Hughes3d30d9b2011-12-07 17:35:48 -08002801 * OLD-TODO: we currently assume that the request and reply include a single
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07002802 * chunk. If this becomes inconvenient we will need to adapt.
2803 */
Elliott Hughes4b9702c2013-02-20 18:13:24 -08002804bool Dbg::DdmHandlePacket(JDWP::Request& request, uint8_t** pReplyBuf, int* pReplyLen) {
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07002805 Thread* self = Thread::Current();
2806 JNIEnv* env = self->GetJniEnv();
2807
Elliott Hughes4b9702c2013-02-20 18:13:24 -08002808 uint32_t type = request.ReadUnsigned32("type");
2809 uint32_t length = request.ReadUnsigned32("length");
2810
2811 // Create a byte[] corresponding to 'request'.
2812 size_t request_length = request.size();
2813 ScopedLocalRef<jbyteArray> dataArray(env, env->NewByteArray(request_length));
Elliott Hughes6a5bd492011-10-28 14:33:57 -07002814 if (dataArray.get() == NULL) {
Elliott Hughes4b9702c2013-02-20 18:13:24 -08002815 LOG(WARNING) << "byte[] allocation failed: " << request_length;
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07002816 env->ExceptionClear();
2817 return false;
2818 }
Elliott Hughes4b9702c2013-02-20 18:13:24 -08002819 env->SetByteArrayRegion(dataArray.get(), 0, request_length, reinterpret_cast<const jbyte*>(request.data()));
2820 request.Skip(request_length);
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07002821
2822 // Run through and find all chunks. [Currently just find the first.]
Elliott Hughes6a5bd492011-10-28 14:33:57 -07002823 ScopedByteArrayRO contents(env, dataArray.get());
Elliott Hughes4b9702c2013-02-20 18:13:24 -08002824 if (length != request_length) {
2825 LOG(WARNING) << StringPrintf("bad chunk found (len=%u pktLen=%d)", length, request_length);
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07002826 return false;
2827 }
2828
2829 // Call "private static Chunk dispatch(int type, byte[] data, int offset, int length)".
Elliott Hugheseac76672012-05-24 21:56:51 -07002830 ScopedLocalRef<jobject> chunk(env, env->CallStaticObjectMethod(WellKnownClasses::org_apache_harmony_dalvik_ddmc_DdmServer,
2831 WellKnownClasses::org_apache_harmony_dalvik_ddmc_DdmServer_dispatch,
Elliott Hughes4b9702c2013-02-20 18:13:24 -08002832 type, dataArray.get(), 0, length));
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07002833 if (env->ExceptionCheck()) {
2834 LOG(INFO) << StringPrintf("Exception thrown by dispatcher for 0x%08x", type);
2835 env->ExceptionDescribe();
2836 env->ExceptionClear();
2837 return false;
2838 }
2839
Elliott Hughes6a5bd492011-10-28 14:33:57 -07002840 if (chunk.get() == NULL) {
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07002841 return false;
2842 }
2843
2844 /*
2845 * Pull the pieces out of the chunk. We copy the results into a
2846 * newly-allocated buffer that the caller can free. We don't want to
2847 * continue using the Chunk object because nothing has a reference to it.
2848 *
2849 * We could avoid this by returning type/data/offset/length and having
2850 * the caller be aware of the object lifetime issues, but that
Elliott Hughes81ff3182012-03-23 20:35:56 -07002851 * integrates the JDWP code more tightly into the rest of the runtime, and doesn't work
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07002852 * if we have responses for multiple chunks.
2853 *
2854 * So we're pretty much stuck with copying data around multiple times.
2855 */
Elliott Hugheseac76672012-05-24 21:56:51 -07002856 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 -08002857 jint offset = env->GetIntField(chunk.get(), WellKnownClasses::org_apache_harmony_dalvik_ddmc_Chunk_offset);
Elliott Hugheseac76672012-05-24 21:56:51 -07002858 length = env->GetIntField(chunk.get(), WellKnownClasses::org_apache_harmony_dalvik_ddmc_Chunk_length);
Elliott Hugheseac76672012-05-24 21:56:51 -07002859 type = env->GetIntField(chunk.get(), WellKnownClasses::org_apache_harmony_dalvik_ddmc_Chunk_type);
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07002860
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08002861 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 -07002862 if (length == 0 || replyData.get() == NULL) {
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07002863 return false;
2864 }
2865
Elliott Hughes4b9702c2013-02-20 18:13:24 -08002866 const int kChunkHdrLen = 8;
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07002867 uint8_t* reply = new uint8_t[length + kChunkHdrLen];
2868 if (reply == NULL) {
2869 LOG(WARNING) << "malloc failed: " << (length + kChunkHdrLen);
2870 return false;
2871 }
Elliott Hughesf7c3b662011-10-27 12:04:56 -07002872 JDWP::Set4BE(reply + 0, type);
2873 JDWP::Set4BE(reply + 4, length);
Elliott Hughes6a5bd492011-10-28 14:33:57 -07002874 env->GetByteArrayRegion(replyData.get(), offset, length, reinterpret_cast<jbyte*>(reply + kChunkHdrLen));
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07002875
2876 *pReplyBuf = reply;
2877 *pReplyLen = length + kChunkHdrLen;
2878
Elliott Hughes4b9702c2013-02-20 18:13:24 -08002879 VLOG(jdwp) << StringPrintf("dvmHandleDdm returning type=%.4s %p len=%d", reinterpret_cast<char*>(reply), reply, length);
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07002880 return true;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002881}
2882
Elliott Hughesa2155262011-11-16 16:26:58 -08002883void Dbg::DdmBroadcast(bool connect) {
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08002884 VLOG(jdwp) << "Broadcasting DDM " << (connect ? "connect" : "disconnect") << "...";
Elliott Hughes47fce012011-10-25 18:37:19 -07002885
2886 Thread* self = Thread::Current();
Ian Rogers50b35e22012-10-04 10:09:15 -07002887 if (self->GetState() != kRunnable) {
2888 LOG(ERROR) << "DDM broadcast in thread state " << self->GetState();
2889 /* try anyway? */
Elliott Hughes47fce012011-10-25 18:37:19 -07002890 }
2891
2892 JNIEnv* env = self->GetJniEnv();
Elliott Hughes47fce012011-10-25 18:37:19 -07002893 jint event = connect ? 1 /*DdmServer.CONNECTED*/ : 2 /*DdmServer.DISCONNECTED*/;
Elliott Hugheseac76672012-05-24 21:56:51 -07002894 env->CallStaticVoidMethod(WellKnownClasses::org_apache_harmony_dalvik_ddmc_DdmServer,
2895 WellKnownClasses::org_apache_harmony_dalvik_ddmc_DdmServer_broadcast,
2896 event);
Elliott Hughes47fce012011-10-25 18:37:19 -07002897 if (env->ExceptionCheck()) {
2898 LOG(ERROR) << "DdmServer.broadcast " << event << " failed";
2899 env->ExceptionDescribe();
2900 env->ExceptionClear();
2901 }
2902}
2903
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002904void Dbg::DdmConnected() {
Elliott Hughesa2155262011-11-16 16:26:58 -08002905 Dbg::DdmBroadcast(true);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002906}
2907
2908void Dbg::DdmDisconnected() {
Elliott Hughesa2155262011-11-16 16:26:58 -08002909 Dbg::DdmBroadcast(false);
Elliott Hughes47fce012011-10-25 18:37:19 -07002910 gDdmThreadNotification = false;
2911}
2912
2913/*
Elliott Hughes82188472011-11-07 18:11:48 -08002914 * Send a notification when a thread starts, stops, or changes its name.
Elliott Hughes47fce012011-10-25 18:37:19 -07002915 *
2916 * Because we broadcast the full set of threads when the notifications are
2917 * first enabled, it's possible for "thread" to be actively executing.
2918 */
Elliott Hughes82188472011-11-07 18:11:48 -08002919void Dbg::DdmSendThreadNotification(Thread* t, uint32_t type) {
Elliott Hughes47fce012011-10-25 18:37:19 -07002920 if (!gDdmThreadNotification) {
2921 return;
2922 }
2923
Elliott Hughes82188472011-11-07 18:11:48 -08002924 if (type == CHUNK_TYPE("THDE")) {
Elliott Hughes47fce012011-10-25 18:37:19 -07002925 uint8_t buf[4];
Elliott Hughesf7c3b662011-10-27 12:04:56 -07002926 JDWP::Set4BE(&buf[0], t->GetThinLockId());
Elliott Hughes47fce012011-10-25 18:37:19 -07002927 Dbg::DdmSendChunk(CHUNK_TYPE("THDE"), 4, buf);
Elliott Hughes82188472011-11-07 18:11:48 -08002928 } else {
2929 CHECK(type == CHUNK_TYPE("THCR") || type == CHUNK_TYPE("THNM")) << type;
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002930 ScopedObjectAccessUnchecked soa(Thread::Current());
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002931 SirtRef<mirror::String> name(soa.Self(), t->GetThreadName(soa));
Elliott Hughes82188472011-11-07 18:11:48 -08002932 size_t char_count = (name.get() != NULL) ? name->GetLength() : 0;
jeffhao725a9572012-11-13 18:20:12 -08002933 const jchar* chars = (name.get() != NULL) ? name->GetCharArray()->GetData() : NULL;
Elliott Hughes82188472011-11-07 18:11:48 -08002934
Elliott Hughes21f32d72011-11-09 17:44:13 -08002935 std::vector<uint8_t> bytes;
Elliott Hughes545a0642011-11-08 19:10:03 -08002936 JDWP::Append4BE(bytes, t->GetThinLockId());
2937 JDWP::AppendUtf16BE(bytes, chars, char_count);
Elliott Hughes21f32d72011-11-09 17:44:13 -08002938 CHECK_EQ(bytes.size(), char_count*2 + sizeof(uint32_t)*2);
2939 Dbg::DdmSendChunk(type, bytes);
Elliott Hughes47fce012011-10-25 18:37:19 -07002940 }
2941}
2942
Elliott Hughes47fce012011-10-25 18:37:19 -07002943void Dbg::DdmSetThreadNotification(bool enable) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002944 // Enable/disable thread notifications.
Elliott Hughes47fce012011-10-25 18:37:19 -07002945 gDdmThreadNotification = enable;
2946 if (enable) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002947 // Suspend the VM then post thread start notifications for all threads. Threads attaching will
2948 // see a suspension in progress and block until that ends. They then post their own start
2949 // notification.
2950 SuspendVM();
2951 std::list<Thread*> threads;
Ian Rogers50b35e22012-10-04 10:09:15 -07002952 Thread* self = Thread::Current();
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002953 {
Ian Rogers50b35e22012-10-04 10:09:15 -07002954 MutexLock mu(self, *Locks::thread_list_lock_);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002955 threads = Runtime::Current()->GetThreadList()->GetList();
2956 }
2957 {
Ian Rogers50b35e22012-10-04 10:09:15 -07002958 ScopedObjectAccess soa(self);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002959 typedef std::list<Thread*>::const_iterator It; // TODO: C++0x auto
2960 for (It it = threads.begin(), end = threads.end(); it != end; ++it) {
2961 Dbg::DdmSendThreadNotification(*it, CHUNK_TYPE("THCR"));
2962 }
2963 }
2964 ResumeVM();
Elliott Hughes47fce012011-10-25 18:37:19 -07002965 }
2966}
2967
Elliott Hughesa2155262011-11-16 16:26:58 -08002968void Dbg::PostThreadStartOrStop(Thread* t, uint32_t type) {
Elliott Hughesc0f09332012-03-26 13:27:06 -07002969 if (IsDebuggerActive()) {
Mathieu Chartierdbe6f462012-09-25 16:54:50 -07002970 ScopedObjectAccessUnchecked soa(Thread::Current());
Ian Rogerscfaa4552012-11-26 21:00:08 -08002971 JDWP::ObjectId id = gRegistry->Add(t->GetPeer());
Elliott Hughes82188472011-11-07 18:11:48 -08002972 gJdwpState->PostThreadChange(id, type == CHUNK_TYPE("THCR"));
Elliott Hughes47fce012011-10-25 18:37:19 -07002973 }
Elliott Hughes82188472011-11-07 18:11:48 -08002974 Dbg::DdmSendThreadNotification(t, type);
Elliott Hughes47fce012011-10-25 18:37:19 -07002975}
2976
2977void Dbg::PostThreadStart(Thread* t) {
Elliott Hughesa2155262011-11-16 16:26:58 -08002978 Dbg::PostThreadStartOrStop(t, CHUNK_TYPE("THCR"));
Elliott Hughes47fce012011-10-25 18:37:19 -07002979}
2980
2981void Dbg::PostThreadDeath(Thread* t) {
Elliott Hughesa2155262011-11-16 16:26:58 -08002982 Dbg::PostThreadStartOrStop(t, CHUNK_TYPE("THDE"));
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002983}
2984
Elliott Hughes82188472011-11-07 18:11:48 -08002985void Dbg::DdmSendChunk(uint32_t type, size_t byte_count, const uint8_t* buf) {
Elliott Hughes3bb81562011-10-21 18:52:59 -07002986 CHECK(buf != NULL);
2987 iovec vec[1];
2988 vec[0].iov_base = reinterpret_cast<void*>(const_cast<uint8_t*>(buf));
2989 vec[0].iov_len = byte_count;
2990 Dbg::DdmSendChunkV(type, vec, 1);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002991}
2992
Elliott Hughes21f32d72011-11-09 17:44:13 -08002993void Dbg::DdmSendChunk(uint32_t type, const std::vector<uint8_t>& bytes) {
2994 DdmSendChunk(type, bytes.size(), &bytes[0]);
2995}
2996
Elliott Hughescccd84f2011-12-05 16:51:54 -08002997void Dbg::DdmSendChunkV(uint32_t type, const struct iovec* iov, int iov_count) {
Elliott Hughes3bb81562011-10-21 18:52:59 -07002998 if (gJdwpState == NULL) {
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08002999 VLOG(jdwp) << "Debugger thread not active, ignoring DDM send: " << type;
Elliott Hughes3bb81562011-10-21 18:52:59 -07003000 } else {
Elliott Hughescccd84f2011-12-05 16:51:54 -08003001 gJdwpState->DdmSendChunkV(type, iov, iov_count);
Elliott Hughes3bb81562011-10-21 18:52:59 -07003002 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -07003003}
3004
Elliott Hughes767a1472011-10-26 18:49:02 -07003005int Dbg::DdmHandleHpifChunk(HpifWhen when) {
3006 if (when == HPIF_WHEN_NOW) {
Elliott Hughes7162ad92011-10-27 14:08:42 -07003007 DdmSendHeapInfo(when);
Elliott Hughes767a1472011-10-26 18:49:02 -07003008 return true;
3009 }
3010
3011 if (when != HPIF_WHEN_NEVER && when != HPIF_WHEN_NEXT_GC && when != HPIF_WHEN_EVERY_GC) {
3012 LOG(ERROR) << "invalid HpifWhen value: " << static_cast<int>(when);
3013 return false;
3014 }
3015
3016 gDdmHpifWhen = when;
3017 return true;
3018}
3019
3020bool Dbg::DdmHandleHpsgNhsgChunk(Dbg::HpsgWhen when, Dbg::HpsgWhat what, bool native) {
3021 if (when != HPSG_WHEN_NEVER && when != HPSG_WHEN_EVERY_GC) {
3022 LOG(ERROR) << "invalid HpsgWhen value: " << static_cast<int>(when);
3023 return false;
3024 }
3025
3026 if (what != HPSG_WHAT_MERGED_OBJECTS && what != HPSG_WHAT_DISTINCT_OBJECTS) {
3027 LOG(ERROR) << "invalid HpsgWhat value: " << static_cast<int>(what);
3028 return false;
3029 }
3030
3031 if (native) {
3032 gDdmNhsgWhen = when;
3033 gDdmNhsgWhat = what;
3034 } else {
3035 gDdmHpsgWhen = when;
3036 gDdmHpsgWhat = what;
3037 }
3038 return true;
3039}
3040
Elliott Hughes7162ad92011-10-27 14:08:42 -07003041void Dbg::DdmSendHeapInfo(HpifWhen reason) {
3042 // If there's a one-shot 'when', reset it.
3043 if (reason == gDdmHpifWhen) {
3044 if (gDdmHpifWhen == HPIF_WHEN_NEXT_GC) {
3045 gDdmHpifWhen = HPIF_WHEN_NEVER;
3046 }
3047 }
3048
3049 /*
3050 * Chunk HPIF (client --> server)
3051 *
3052 * Heap Info. General information about the heap,
3053 * suitable for a summary display.
3054 *
3055 * [u4]: number of heaps
3056 *
3057 * For each heap:
3058 * [u4]: heap ID
3059 * [u8]: timestamp in ms since Unix epoch
3060 * [u1]: capture reason (same as 'when' value from server)
3061 * [u4]: max heap size in bytes (-Xmx)
3062 * [u4]: current heap size in bytes
3063 * [u4]: current number of bytes allocated
3064 * [u4]: current number of objects allocated
3065 */
3066 uint8_t heap_count = 1;
Elliott Hughesb3bd5f02012-03-08 21:05:27 -08003067 Heap* heap = Runtime::Current()->GetHeap();
Elliott Hughes21f32d72011-11-09 17:44:13 -08003068 std::vector<uint8_t> bytes;
Elliott Hughes545a0642011-11-08 19:10:03 -08003069 JDWP::Append4BE(bytes, heap_count);
3070 JDWP::Append4BE(bytes, 1); // Heap id (bogus; we only have one heap).
3071 JDWP::Append8BE(bytes, MilliTime());
3072 JDWP::Append1BE(bytes, reason);
Elliott Hughesb3bd5f02012-03-08 21:05:27 -08003073 JDWP::Append4BE(bytes, heap->GetMaxMemory()); // Max allowed heap size in bytes.
3074 JDWP::Append4BE(bytes, heap->GetTotalMemory()); // Current heap size in bytes.
3075 JDWP::Append4BE(bytes, heap->GetBytesAllocated());
3076 JDWP::Append4BE(bytes, heap->GetObjectsAllocated());
Elliott Hughes21f32d72011-11-09 17:44:13 -08003077 CHECK_EQ(bytes.size(), 4U + (heap_count * (4 + 8 + 1 + 4 + 4 + 4 + 4)));
3078 Dbg::DdmSendChunk(CHUNK_TYPE("HPIF"), bytes);
Elliott Hughes767a1472011-10-26 18:49:02 -07003079}
3080
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003081enum HpsgSolidity {
3082 SOLIDITY_FREE = 0,
3083 SOLIDITY_HARD = 1,
3084 SOLIDITY_SOFT = 2,
3085 SOLIDITY_WEAK = 3,
3086 SOLIDITY_PHANTOM = 4,
3087 SOLIDITY_FINALIZABLE = 5,
3088 SOLIDITY_SWEEP = 6,
3089};
3090
3091enum HpsgKind {
3092 KIND_OBJECT = 0,
3093 KIND_CLASS_OBJECT = 1,
3094 KIND_ARRAY_1 = 2,
3095 KIND_ARRAY_2 = 3,
3096 KIND_ARRAY_4 = 4,
3097 KIND_ARRAY_8 = 5,
3098 KIND_UNKNOWN = 6,
3099 KIND_NATIVE = 7,
3100};
3101
3102#define HPSG_PARTIAL (1<<7)
3103#define HPSG_STATE(solidity, kind) ((uint8_t)((((kind) & 0x7) << 3) | ((solidity) & 0x7)))
3104
Ian Rogers30fab402012-01-23 15:43:46 -08003105class HeapChunkContext {
3106 public:
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003107 // Maximum chunk size. Obtain this from the formula:
3108 // (((maximum_heap_size / ALLOCATION_UNIT_SIZE) + 255) / 256) * 2
3109 HeapChunkContext(bool merge, bool native)
Ian Rogers30fab402012-01-23 15:43:46 -08003110 : buf_(16384 - 16),
3111 type_(0),
3112 merge_(merge) {
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003113 Reset();
3114 if (native) {
Ian Rogers30fab402012-01-23 15:43:46 -08003115 type_ = CHUNK_TYPE("NHSG");
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003116 } else {
Ian Rogers30fab402012-01-23 15:43:46 -08003117 type_ = merge ? CHUNK_TYPE("HPSG") : CHUNK_TYPE("HPSO");
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003118 }
3119 }
3120
3121 ~HeapChunkContext() {
Ian Rogers30fab402012-01-23 15:43:46 -08003122 if (p_ > &buf_[0]) {
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003123 Flush();
3124 }
3125 }
3126
3127 void EnsureHeader(const void* chunk_ptr) {
Ian Rogers30fab402012-01-23 15:43:46 -08003128 if (!needHeader_) {
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003129 return;
3130 }
3131
3132 // Start a new HPSx chunk.
Ian Rogers30fab402012-01-23 15:43:46 -08003133 JDWP::Write4BE(&p_, 1); // Heap id (bogus; we only have one heap).
3134 JDWP::Write1BE(&p_, 8); // Size of allocation unit, in bytes.
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003135
Ian Rogers30fab402012-01-23 15:43:46 -08003136 JDWP::Write4BE(&p_, reinterpret_cast<uintptr_t>(chunk_ptr)); // virtual address of segment start.
3137 JDWP::Write4BE(&p_, 0); // offset of this piece (relative to the virtual address).
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003138 // [u4]: length of piece, in allocation units
3139 // 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 -08003140 pieceLenField_ = p_;
3141 JDWP::Write4BE(&p_, 0x55555555);
3142 needHeader_ = false;
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003143 }
3144
Ian Rogersb726dcb2012-09-05 08:57:23 -07003145 void Flush() SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Ian Rogersd636b062013-01-18 17:51:18 -08003146 if (pieceLenField_ == NULL) {
3147 // Flush immediately post Reset (maybe back-to-back Flush). Ignore.
3148 CHECK(needHeader_);
3149 return;
3150 }
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003151 // Patch the "length of piece" field.
Ian Rogers30fab402012-01-23 15:43:46 -08003152 CHECK_LE(&buf_[0], pieceLenField_);
3153 CHECK_LE(pieceLenField_, p_);
3154 JDWP::Set4BE(pieceLenField_, totalAllocationUnits_);
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003155
Ian Rogers30fab402012-01-23 15:43:46 -08003156 Dbg::DdmSendChunk(type_, p_ - &buf_[0], &buf_[0]);
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003157 Reset();
3158 }
3159
Ian Rogers00f7d0e2012-07-19 15:28:27 -07003160 static void HeapChunkCallback(void* start, void* end, size_t used_bytes, void* arg)
Ian Rogersb726dcb2012-09-05 08:57:23 -07003161 SHARED_LOCKS_REQUIRED(Locks::heap_bitmap_lock_,
3162 Locks::mutator_lock_) {
Ian Rogers30fab402012-01-23 15:43:46 -08003163 reinterpret_cast<HeapChunkContext*>(arg)->HeapChunkCallback(start, end, used_bytes);
Elliott Hughesa2155262011-11-16 16:26:58 -08003164 }
3165
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003166 private:
Elliott Hughesa2155262011-11-16 16:26:58 -08003167 enum { ALLOCATION_UNIT_SIZE = 8 };
3168
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003169 void Reset() {
Ian Rogers30fab402012-01-23 15:43:46 -08003170 p_ = &buf_[0];
Ian Rogers15bf2d32012-08-28 17:33:04 -07003171 startOfNextMemoryChunk_ = NULL;
Ian Rogers30fab402012-01-23 15:43:46 -08003172 totalAllocationUnits_ = 0;
3173 needHeader_ = true;
3174 pieceLenField_ = NULL;
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003175 }
3176
Ian Rogers00f7d0e2012-07-19 15:28:27 -07003177 void HeapChunkCallback(void* start, void* /*end*/, size_t used_bytes)
Ian Rogersb726dcb2012-09-05 08:57:23 -07003178 SHARED_LOCKS_REQUIRED(Locks::heap_bitmap_lock_,
3179 Locks::mutator_lock_) {
Ian Rogers30fab402012-01-23 15:43:46 -08003180 // Note: heap call backs cannot manipulate the heap upon which they are crawling, care is taken
3181 // in the following code not to allocate memory, by ensuring buf_ is of the correct size
Ian Rogers15bf2d32012-08-28 17:33:04 -07003182 if (used_bytes == 0) {
3183 if (start == NULL) {
3184 // Reset for start of new heap.
3185 startOfNextMemoryChunk_ = NULL;
3186 Flush();
3187 }
3188 // Only process in use memory so that free region information
3189 // also includes dlmalloc book keeping.
Elliott Hughesa2155262011-11-16 16:26:58 -08003190 return;
Elliott Hughesa2155262011-11-16 16:26:58 -08003191 }
3192
Ian Rogers15bf2d32012-08-28 17:33:04 -07003193 /* If we're looking at the native heap, we'll just return
3194 * (SOLIDITY_HARD, KIND_NATIVE) for all allocated chunks
3195 */
3196 bool native = type_ == CHUNK_TYPE("NHSG");
3197
3198 if (startOfNextMemoryChunk_ != NULL) {
3199 // Transmit any pending free memory. Native free memory of
3200 // over kMaxFreeLen could be because of the use of mmaps, so
3201 // don't report. If not free memory then start a new segment.
3202 bool flush = true;
3203 if (start > startOfNextMemoryChunk_) {
3204 const size_t kMaxFreeLen = 2 * kPageSize;
3205 void* freeStart = startOfNextMemoryChunk_;
3206 void* freeEnd = start;
3207 size_t freeLen = (char*)freeEnd - (char*)freeStart;
3208 if (!native || freeLen < kMaxFreeLen) {
3209 AppendChunk(HPSG_STATE(SOLIDITY_FREE, 0), freeStart, freeLen);
3210 flush = false;
3211 }
3212 }
3213 if (flush) {
3214 startOfNextMemoryChunk_ = NULL;
3215 Flush();
3216 }
3217 }
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003218 const mirror::Object* obj = reinterpret_cast<const mirror::Object*>(start);
Elliott Hughesa2155262011-11-16 16:26:58 -08003219
3220 // Determine the type of this chunk.
3221 // OLD-TODO: if context.merge, see if this chunk is different from the last chunk.
3222 // If it's the same, we should combine them.
Ian Rogers15bf2d32012-08-28 17:33:04 -07003223 uint8_t state = ExamineObject(obj, native);
3224 // dlmalloc's chunk header is 2 * sizeof(size_t), but if the previous chunk is in use for an
3225 // allocation then the first sizeof(size_t) may belong to it.
3226 const size_t dlMallocOverhead = sizeof(size_t);
3227 AppendChunk(state, start, used_bytes + dlMallocOverhead);
3228 startOfNextMemoryChunk_ = (char*)start + used_bytes + dlMallocOverhead;
3229 }
Elliott Hughesa2155262011-11-16 16:26:58 -08003230
Ian Rogers15bf2d32012-08-28 17:33:04 -07003231 void AppendChunk(uint8_t state, void* ptr, size_t length)
Ian Rogersb726dcb2012-09-05 08:57:23 -07003232 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Ian Rogers15bf2d32012-08-28 17:33:04 -07003233 // Make sure there's enough room left in the buffer.
3234 // We need to use two bytes for every fractional 256 allocation units used by the chunk plus
3235 // 17 bytes for any header.
3236 size_t needed = (((length/ALLOCATION_UNIT_SIZE + 255) / 256) * 2) + 17;
3237 size_t bytesLeft = buf_.size() - (size_t)(p_ - &buf_[0]);
3238 if (bytesLeft < needed) {
3239 Flush();
3240 }
3241
3242 bytesLeft = buf_.size() - (size_t)(p_ - &buf_[0]);
3243 if (bytesLeft < needed) {
3244 LOG(WARNING) << "Chunk is too big to transmit (chunk_len=" << length << ", "
3245 << needed << " bytes)";
3246 return;
3247 }
3248 EnsureHeader(ptr);
Elliott Hughesa2155262011-11-16 16:26:58 -08003249 // Write out the chunk description.
Ian Rogers15bf2d32012-08-28 17:33:04 -07003250 length /= ALLOCATION_UNIT_SIZE; // Convert to allocation units.
3251 totalAllocationUnits_ += length;
3252 while (length > 256) {
Ian Rogers30fab402012-01-23 15:43:46 -08003253 *p_++ = state | HPSG_PARTIAL;
3254 *p_++ = 255; // length - 1
Ian Rogers15bf2d32012-08-28 17:33:04 -07003255 length -= 256;
Elliott Hughesa2155262011-11-16 16:26:58 -08003256 }
Ian Rogers30fab402012-01-23 15:43:46 -08003257 *p_++ = state;
Ian Rogers15bf2d32012-08-28 17:33:04 -07003258 *p_++ = length - 1;
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003259 }
3260
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003261 uint8_t ExamineObject(const mirror::Object* o, bool is_native_heap)
Ian Rogersb726dcb2012-09-05 08:57:23 -07003262 SHARED_LOCKS_REQUIRED(Locks::heap_bitmap_lock_) {
Elliott Hughesa2155262011-11-16 16:26:58 -08003263 if (o == NULL) {
3264 return HPSG_STATE(SOLIDITY_FREE, 0);
3265 }
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003266
Elliott Hughesa2155262011-11-16 16:26:58 -08003267 // It's an allocated chunk. Figure out what it is.
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003268
Elliott Hughesa2155262011-11-16 16:26:58 -08003269 // If we're looking at the native heap, we'll just return
3270 // (SOLIDITY_HARD, KIND_NATIVE) for all allocated chunks.
Ian Rogers00f7d0e2012-07-19 15:28:27 -07003271 if (is_native_heap) {
Elliott Hughesa2155262011-11-16 16:26:58 -08003272 return HPSG_STATE(SOLIDITY_HARD, KIND_NATIVE);
3273 }
3274
Ian Rogers5bfa60f2012-09-02 21:17:56 -07003275 if (!Runtime::Current()->GetHeap()->IsLiveObjectLocked(o)) {
Ian Rogers15bf2d32012-08-28 17:33:04 -07003276 return HPSG_STATE(SOLIDITY_HARD, KIND_NATIVE);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07003277 }
3278
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003279 mirror::Class* c = o->GetClass();
Elliott Hughesa2155262011-11-16 16:26:58 -08003280 if (c == NULL) {
3281 // The object was probably just created but hasn't been initialized yet.
3282 return HPSG_STATE(SOLIDITY_HARD, KIND_OBJECT);
3283 }
3284
Elliott Hughesb3bd5f02012-03-08 21:05:27 -08003285 if (!Runtime::Current()->GetHeap()->IsHeapAddress(c)) {
Ian Rogers15bf2d32012-08-28 17:33:04 -07003286 LOG(ERROR) << "Invalid class for managed heap object: " << o << " " << c;
Elliott Hughesa2155262011-11-16 16:26:58 -08003287 return HPSG_STATE(SOLIDITY_HARD, KIND_UNKNOWN);
3288 }
3289
3290 if (c->IsClassClass()) {
3291 return HPSG_STATE(SOLIDITY_HARD, KIND_CLASS_OBJECT);
3292 }
3293
3294 if (c->IsArrayClass()) {
3295 if (o->IsObjectArray()) {
3296 return HPSG_STATE(SOLIDITY_HARD, KIND_ARRAY_4);
3297 }
3298 switch (c->GetComponentSize()) {
3299 case 1: return HPSG_STATE(SOLIDITY_HARD, KIND_ARRAY_1);
3300 case 2: return HPSG_STATE(SOLIDITY_HARD, KIND_ARRAY_2);
3301 case 4: return HPSG_STATE(SOLIDITY_HARD, KIND_ARRAY_4);
3302 case 8: return HPSG_STATE(SOLIDITY_HARD, KIND_ARRAY_8);
3303 }
3304 }
3305
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003306 return HPSG_STATE(SOLIDITY_HARD, KIND_OBJECT);
3307 }
3308
Ian Rogers30fab402012-01-23 15:43:46 -08003309 std::vector<uint8_t> buf_;
3310 uint8_t* p_;
3311 uint8_t* pieceLenField_;
Ian Rogers15bf2d32012-08-28 17:33:04 -07003312 void* startOfNextMemoryChunk_;
Ian Rogers30fab402012-01-23 15:43:46 -08003313 size_t totalAllocationUnits_;
3314 uint32_t type_;
3315 bool merge_;
3316 bool needHeader_;
3317
Elliott Hughesa2155262011-11-16 16:26:58 -08003318 DISALLOW_COPY_AND_ASSIGN(HeapChunkContext);
3319};
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003320
3321void Dbg::DdmSendHeapSegments(bool native) {
3322 Dbg::HpsgWhen when;
3323 Dbg::HpsgWhat what;
3324 if (!native) {
3325 when = gDdmHpsgWhen;
3326 what = gDdmHpsgWhat;
3327 } else {
3328 when = gDdmNhsgWhen;
3329 what = gDdmNhsgWhat;
3330 }
3331 if (when == HPSG_WHEN_NEVER) {
3332 return;
3333 }
3334
3335 // Figure out what kind of chunks we'll be sending.
3336 CHECK(what == HPSG_WHAT_MERGED_OBJECTS || what == HPSG_WHAT_DISTINCT_OBJECTS) << static_cast<int>(what);
3337
3338 // First, send a heap start chunk.
3339 uint8_t heap_id[4];
3340 JDWP::Set4BE(&heap_id[0], 1); // Heap id (bogus; we only have one heap).
3341 Dbg::DdmSendChunk(native ? CHUNK_TYPE("NHST") : CHUNK_TYPE("HPST"), sizeof(heap_id), heap_id);
3342
3343 // Send a series of heap segment chunks.
Elliott Hughesa2155262011-11-16 16:26:58 -08003344 HeapChunkContext context((what == HPSG_WHAT_MERGED_OBJECTS), native);
3345 if (native) {
Ian Rogers30fab402012-01-23 15:43:46 -08003346 // TODO: enable when bionic has moved to dlmalloc 2.8.5
3347 // dlmalloc_inspect_all(HeapChunkContext::HeapChunkCallback, &context);
3348 UNIMPLEMENTED(WARNING) << "Native heap send heap segments";
Elliott Hughesa2155262011-11-16 16:26:58 -08003349 } else {
Elliott Hughesb3bd5f02012-03-08 21:05:27 -08003350 Heap* heap = Runtime::Current()->GetHeap();
Mathieu Chartierfd678be2012-08-30 14:50:54 -07003351 const Spaces& spaces = heap->GetSpaces();
Ian Rogers50b35e22012-10-04 10:09:15 -07003352 Thread* self = Thread::Current();
Ian Rogers62d6c772013-02-27 08:32:07 -08003353 ReaderMutexLock mu(self, *Locks::heap_bitmap_lock_);
Mathieu Chartierfd678be2012-08-30 14:50:54 -07003354 for (Spaces::const_iterator cur = spaces.begin(); cur != spaces.end(); ++cur) {
Mathieu Chartierb062fdd2012-07-03 09:51:48 -07003355 if ((*cur)->IsAllocSpace()) {
3356 (*cur)->AsAllocSpace()->Walk(HeapChunkContext::HeapChunkCallback, &context);
3357 }
3358 }
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -07003359 // Walk the large objects, these are not in the AllocSpace.
3360 heap->GetLargeObjectsSpace()->Walk(HeapChunkContext::HeapChunkCallback, &context);
Elliott Hughesa2155262011-11-16 16:26:58 -08003361 }
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003362
3363 // Finally, send a heap end chunk.
3364 Dbg::DdmSendChunk(native ? CHUNK_TYPE("NHEN") : CHUNK_TYPE("HPEN"), sizeof(heap_id), heap_id);
Elliott Hughes767a1472011-10-26 18:49:02 -07003365}
3366
Elliott Hughes545a0642011-11-08 19:10:03 -08003367void Dbg::SetAllocTrackingEnabled(bool enabled) {
Ian Rogers50b35e22012-10-04 10:09:15 -07003368 MutexLock mu(Thread::Current(), gAllocTrackerLock);
Elliott Hughes545a0642011-11-08 19:10:03 -08003369 if (enabled) {
3370 if (recent_allocation_records_ == NULL) {
3371 LOG(INFO) << "Enabling alloc tracker (" << kNumAllocRecords << " entries, "
3372 << kMaxAllocRecordStackDepth << " frames --> "
3373 << (sizeof(AllocRecord) * kNumAllocRecords) << " bytes)";
3374 gAllocRecordHead = gAllocRecordCount = 0;
3375 recent_allocation_records_ = new AllocRecord[kNumAllocRecords];
3376 CHECK(recent_allocation_records_ != NULL);
3377 }
3378 } else {
3379 delete[] recent_allocation_records_;
3380 recent_allocation_records_ = NULL;
3381 }
3382}
3383
Ian Rogers0399dde2012-06-06 17:09:28 -07003384struct AllocRecordStackVisitor : public StackVisitor {
Ian Rogers7a22fa62013-01-23 12:16:16 -08003385 AllocRecordStackVisitor(Thread* thread, AllocRecord* record)
Ian Rogersb726dcb2012-09-05 08:57:23 -07003386 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_)
Ian Rogers7a22fa62013-01-23 12:16:16 -08003387 : StackVisitor(thread, NULL), record(record), depth(0) {}
Elliott Hughes545a0642011-11-08 19:10:03 -08003388
Ian Rogers00f7d0e2012-07-19 15:28:27 -07003389 // TODO: Enable annotalysis. We know lock is held in constructor, but abstraction confuses
3390 // annotalysis.
3391 bool VisitFrame() NO_THREAD_SAFETY_ANALYSIS {
Elliott Hughes545a0642011-11-08 19:10:03 -08003392 if (depth >= kMaxAllocRecordStackDepth) {
Elliott Hughes530fa002012-03-12 11:44:49 -07003393 return false;
Elliott Hughes545a0642011-11-08 19:10:03 -08003394 }
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003395 mirror::AbstractMethod* m = GetMethod();
Ian Rogers0399dde2012-06-06 17:09:28 -07003396 if (!m->IsRuntimeMethod()) {
3397 record->stack[depth].method = m;
3398 record->stack[depth].dex_pc = GetDexPc();
Elliott Hughes530fa002012-03-12 11:44:49 -07003399 ++depth;
Elliott Hughes545a0642011-11-08 19:10:03 -08003400 }
Elliott Hughes530fa002012-03-12 11:44:49 -07003401 return true;
Elliott Hughes545a0642011-11-08 19:10:03 -08003402 }
3403
3404 ~AllocRecordStackVisitor() {
3405 // Clear out any unused stack trace elements.
3406 for (; depth < kMaxAllocRecordStackDepth; ++depth) {
3407 record->stack[depth].method = NULL;
Ian Rogers0399dde2012-06-06 17:09:28 -07003408 record->stack[depth].dex_pc = 0;
Elliott Hughes545a0642011-11-08 19:10:03 -08003409 }
3410 }
3411
3412 AllocRecord* record;
3413 size_t depth;
3414};
3415
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003416void Dbg::RecordAllocation(mirror::Class* type, size_t byte_count) {
Elliott Hughes545a0642011-11-08 19:10:03 -08003417 Thread* self = Thread::Current();
3418 CHECK(self != NULL);
3419
Ian Rogers50b35e22012-10-04 10:09:15 -07003420 MutexLock mu(self, gAllocTrackerLock);
Elliott Hughes545a0642011-11-08 19:10:03 -08003421 if (recent_allocation_records_ == NULL) {
3422 return;
3423 }
3424
3425 // Advance and clip.
3426 if (++gAllocRecordHead == kNumAllocRecords) {
3427 gAllocRecordHead = 0;
3428 }
3429
3430 // Fill in the basics.
3431 AllocRecord* record = &recent_allocation_records_[gAllocRecordHead];
3432 record->type = type;
3433 record->byte_count = byte_count;
3434 record->thin_lock_id = self->GetThinLockId();
3435
3436 // Fill in the stack trace.
Ian Rogers7a22fa62013-01-23 12:16:16 -08003437 AllocRecordStackVisitor visitor(self, record);
Ian Rogers0399dde2012-06-06 17:09:28 -07003438 visitor.WalkStack();
Elliott Hughes545a0642011-11-08 19:10:03 -08003439
3440 if (gAllocRecordCount < kNumAllocRecords) {
3441 ++gAllocRecordCount;
3442 }
3443}
3444
Elliott Hughesa8f93cb2012-06-08 17:08:48 -07003445// Returns the index of the head element.
3446//
3447// We point at the most-recently-written record, so if gAllocRecordCount is 1
3448// we want to use the current element. Take "head+1" and subtract count
3449// from it.
3450//
3451// We need to handle underflow in our circular buffer, so we add
3452// kNumAllocRecords and then mask it back down.
Elliott Hughesf8349362012-06-18 15:00:06 -07003453static inline int HeadIndex() EXCLUSIVE_LOCKS_REQUIRED(gAllocTrackerLock) {
Elliott Hughes545a0642011-11-08 19:10:03 -08003454 return (gAllocRecordHead+1 + kNumAllocRecords - gAllocRecordCount) & (kNumAllocRecords-1);
3455}
3456
3457void Dbg::DumpRecentAllocations() {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07003458 ScopedObjectAccess soa(Thread::Current());
Ian Rogers50b35e22012-10-04 10:09:15 -07003459 MutexLock mu(soa.Self(), gAllocTrackerLock);
Elliott Hughes545a0642011-11-08 19:10:03 -08003460 if (recent_allocation_records_ == NULL) {
3461 LOG(INFO) << "Not recording tracked allocations";
3462 return;
3463 }
3464
3465 // "i" is the head of the list. We want to start at the end of the
3466 // list and move forward to the tail.
Elliott Hughesa8f93cb2012-06-08 17:08:48 -07003467 size_t i = HeadIndex();
Elliott Hughes545a0642011-11-08 19:10:03 -08003468 size_t count = gAllocRecordCount;
3469
3470 LOG(INFO) << "Tracked allocations, (head=" << gAllocRecordHead << " count=" << count << ")";
3471 while (count--) {
3472 AllocRecord* record = &recent_allocation_records_[i];
3473
Elliott Hughesa8f93cb2012-06-08 17:08:48 -07003474 LOG(INFO) << StringPrintf(" Thread %-2d %6zd bytes ", record->thin_lock_id, record->byte_count)
Elliott Hughes545a0642011-11-08 19:10:03 -08003475 << PrettyClass(record->type);
3476
3477 for (size_t stack_frame = 0; stack_frame < kMaxAllocRecordStackDepth; ++stack_frame) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003478 const mirror::AbstractMethod* m = record->stack[stack_frame].method;
Elliott Hughes545a0642011-11-08 19:10:03 -08003479 if (m == NULL) {
3480 break;
3481 }
3482 LOG(INFO) << " " << PrettyMethod(m) << " line " << record->stack[stack_frame].LineNumber();
3483 }
3484
3485 // pause periodically to help logcat catch up
3486 if ((count % 5) == 0) {
3487 usleep(40000);
3488 }
3489
3490 i = (i + 1) & (kNumAllocRecords-1);
3491 }
3492}
3493
3494class StringTable {
3495 public:
3496 StringTable() {
3497 }
3498
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08003499 void Add(const char* s) {
Elliott Hughes545a0642011-11-08 19:10:03 -08003500 table_.insert(s);
3501 }
3502
Elliott Hughesa8f93cb2012-06-08 17:08:48 -07003503 size_t IndexOf(const char* s) const {
3504 typedef std::set<std::string>::const_iterator It; // TODO: C++0x auto
3505 It it = table_.find(s);
3506 if (it == table_.end()) {
3507 LOG(FATAL) << "IndexOf(\"" << s << "\") failed";
3508 }
3509 return std::distance(table_.begin(), it);
Elliott Hughes545a0642011-11-08 19:10:03 -08003510 }
3511
Elliott Hughesa8f93cb2012-06-08 17:08:48 -07003512 size_t Size() const {
Elliott Hughes545a0642011-11-08 19:10:03 -08003513 return table_.size();
3514 }
3515
Elliott Hughesa8f93cb2012-06-08 17:08:48 -07003516 void WriteTo(std::vector<uint8_t>& bytes) const {
3517 typedef std::set<std::string>::const_iterator It; // TODO: C++0x auto
Elliott Hughes545a0642011-11-08 19:10:03 -08003518 for (It it = table_.begin(); it != table_.end(); ++it) {
Elliott Hughesa8f93cb2012-06-08 17:08:48 -07003519 const char* s = (*it).c_str();
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08003520 size_t s_len = CountModifiedUtf8Chars(s);
3521 UniquePtr<uint16_t> s_utf16(new uint16_t[s_len]);
3522 ConvertModifiedUtf8ToUtf16(s_utf16.get(), s);
3523 JDWP::AppendUtf16BE(bytes, s_utf16.get(), s_len);
Elliott Hughes545a0642011-11-08 19:10:03 -08003524 }
3525 }
3526
3527 private:
Elliott Hughesa8f93cb2012-06-08 17:08:48 -07003528 std::set<std::string> table_;
Elliott Hughes545a0642011-11-08 19:10:03 -08003529 DISALLOW_COPY_AND_ASSIGN(StringTable);
3530};
3531
3532/*
3533 * The data we send to DDMS contains everything we have recorded.
3534 *
3535 * Message header (all values big-endian):
3536 * (1b) message header len (to allow future expansion); includes itself
3537 * (1b) entry header len
3538 * (1b) stack frame len
3539 * (2b) number of entries
3540 * (4b) offset to string table from start of message
3541 * (2b) number of class name strings
3542 * (2b) number of method name strings
3543 * (2b) number of source file name strings
3544 * For each entry:
3545 * (4b) total allocation size
Elliott Hughes221229c2013-01-08 18:17:50 -08003546 * (2b) thread id
Elliott Hughes545a0642011-11-08 19:10:03 -08003547 * (2b) allocated object's class name index
3548 * (1b) stack depth
3549 * For each stack frame:
3550 * (2b) method's class name
3551 * (2b) method name
3552 * (2b) method source file
3553 * (2b) line number, clipped to 32767; -2 if native; -1 if no source
3554 * (xb) class name strings
3555 * (xb) method name strings
3556 * (xb) source file strings
3557 *
3558 * As with other DDM traffic, strings are sent as a 4-byte length
3559 * followed by UTF-16 data.
3560 *
3561 * We send up 16-bit unsigned indexes into string tables. In theory there
3562 * can be (kMaxAllocRecordStackDepth * kNumAllocRecords) unique strings in
3563 * each table, but in practice there should be far fewer.
3564 *
3565 * The chief reason for using a string table here is to keep the size of
3566 * the DDMS message to a minimum. This is partly to make the protocol
3567 * efficient, but also because we have to form the whole thing up all at
3568 * once in a memory buffer.
3569 *
3570 * We use separate string tables for class names, method names, and source
3571 * files to keep the indexes small. There will generally be no overlap
3572 * between the contents of these tables.
3573 */
3574jbyteArray Dbg::GetRecentAllocations() {
3575 if (false) {
3576 DumpRecentAllocations();
3577 }
3578
Ian Rogers50b35e22012-10-04 10:09:15 -07003579 Thread* self = Thread::Current();
3580 MutexLock mu(self, gAllocTrackerLock);
Elliott Hughes545a0642011-11-08 19:10:03 -08003581
Elliott Hughesa8f93cb2012-06-08 17:08:48 -07003582 //
3583 // Part 1: generate string tables.
3584 //
Elliott Hughes545a0642011-11-08 19:10:03 -08003585 StringTable class_names;
3586 StringTable method_names;
3587 StringTable filenames;
3588
3589 int count = gAllocRecordCount;
Elliott Hughesa8f93cb2012-06-08 17:08:48 -07003590 int idx = HeadIndex();
Elliott Hughes545a0642011-11-08 19:10:03 -08003591 while (count--) {
3592 AllocRecord* record = &recent_allocation_records_[idx];
3593
Elliott Hughes91250e02011-12-13 22:30:35 -08003594 class_names.Add(ClassHelper(record->type).GetDescriptor());
Elliott Hughes545a0642011-11-08 19:10:03 -08003595
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08003596 MethodHelper mh;
Elliott Hughes545a0642011-11-08 19:10:03 -08003597 for (size_t i = 0; i < kMaxAllocRecordStackDepth; i++) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003598 mirror::AbstractMethod* m = record->stack[i].method;
Elliott Hughes545a0642011-11-08 19:10:03 -08003599 if (m != NULL) {
Ian Rogersba377812012-05-28 21:16:29 -07003600 mh.ChangeMethod(m);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08003601 class_names.Add(mh.GetDeclaringClassDescriptor());
3602 method_names.Add(mh.GetName());
3603 filenames.Add(mh.GetDeclaringClassSourceFile());
Elliott Hughes545a0642011-11-08 19:10:03 -08003604 }
3605 }
3606
3607 idx = (idx + 1) & (kNumAllocRecords-1);
3608 }
3609
3610 LOG(INFO) << "allocation records: " << gAllocRecordCount;
3611
Elliott Hughesa8f93cb2012-06-08 17:08:48 -07003612 //
3613 // Part 2: allocate a buffer and generate the output.
3614 //
Elliott Hughes545a0642011-11-08 19:10:03 -08003615 std::vector<uint8_t> bytes;
3616
3617 // (1b) message header len (to allow future expansion); includes itself
3618 // (1b) entry header len
3619 // (1b) stack frame len
3620 const int kMessageHeaderLen = 15;
3621 const int kEntryHeaderLen = 9;
3622 const int kStackFrameLen = 8;
3623 JDWP::Append1BE(bytes, kMessageHeaderLen);
3624 JDWP::Append1BE(bytes, kEntryHeaderLen);
3625 JDWP::Append1BE(bytes, kStackFrameLen);
3626
3627 // (2b) number of entries
3628 // (4b) offset to string table from start of message
3629 // (2b) number of class name strings
3630 // (2b) number of method name strings
3631 // (2b) number of source file name strings
3632 JDWP::Append2BE(bytes, gAllocRecordCount);
3633 size_t string_table_offset = bytes.size();
3634 JDWP::Append4BE(bytes, 0); // We'll patch this later...
3635 JDWP::Append2BE(bytes, class_names.Size());
3636 JDWP::Append2BE(bytes, method_names.Size());
3637 JDWP::Append2BE(bytes, filenames.Size());
3638
3639 count = gAllocRecordCount;
Elliott Hughesa8f93cb2012-06-08 17:08:48 -07003640 idx = HeadIndex();
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08003641 ClassHelper kh;
Elliott Hughes545a0642011-11-08 19:10:03 -08003642 while (count--) {
3643 // For each entry:
3644 // (4b) total allocation size
3645 // (2b) thread id
3646 // (2b) allocated object's class name index
3647 // (1b) stack depth
3648 AllocRecord* record = &recent_allocation_records_[idx];
3649 size_t stack_depth = record->GetDepth();
Elliott Hughesa8f93cb2012-06-08 17:08:48 -07003650 kh.ChangeClass(record->type);
3651 size_t allocated_object_class_name_index = class_names.IndexOf(kh.GetDescriptor());
Elliott Hughes545a0642011-11-08 19:10:03 -08003652 JDWP::Append4BE(bytes, record->byte_count);
3653 JDWP::Append2BE(bytes, record->thin_lock_id);
Elliott Hughesa8f93cb2012-06-08 17:08:48 -07003654 JDWP::Append2BE(bytes, allocated_object_class_name_index);
Elliott Hughes545a0642011-11-08 19:10:03 -08003655 JDWP::Append1BE(bytes, stack_depth);
3656
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08003657 MethodHelper mh;
Elliott Hughes545a0642011-11-08 19:10:03 -08003658 for (size_t stack_frame = 0; stack_frame < stack_depth; ++stack_frame) {
3659 // For each stack frame:
3660 // (2b) method's class name
3661 // (2b) method name
3662 // (2b) method source file
3663 // (2b) line number, clipped to 32767; -2 if native; -1 if no source
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08003664 mh.ChangeMethod(record->stack[stack_frame].method);
Elliott Hughesa8f93cb2012-06-08 17:08:48 -07003665 size_t class_name_index = class_names.IndexOf(mh.GetDeclaringClassDescriptor());
3666 size_t method_name_index = method_names.IndexOf(mh.GetName());
3667 size_t file_name_index = filenames.IndexOf(mh.GetDeclaringClassSourceFile());
3668 JDWP::Append2BE(bytes, class_name_index);
3669 JDWP::Append2BE(bytes, method_name_index);
3670 JDWP::Append2BE(bytes, file_name_index);
Elliott Hughes545a0642011-11-08 19:10:03 -08003671 JDWP::Append2BE(bytes, record->stack[stack_frame].LineNumber());
3672 }
3673
3674 idx = (idx + 1) & (kNumAllocRecords-1);
3675 }
3676
3677 // (xb) class name strings
3678 // (xb) method name strings
3679 // (xb) source file strings
3680 JDWP::Set4BE(&bytes[string_table_offset], bytes.size());
3681 class_names.WriteTo(bytes);
3682 method_names.WriteTo(bytes);
3683 filenames.WriteTo(bytes);
3684
Ian Rogers50b35e22012-10-04 10:09:15 -07003685 JNIEnv* env = self->GetJniEnv();
Elliott Hughes545a0642011-11-08 19:10:03 -08003686 jbyteArray result = env->NewByteArray(bytes.size());
3687 if (result != NULL) {
3688 env->SetByteArrayRegion(result, 0, bytes.size(), reinterpret_cast<const jbyte*>(&bytes[0]));
3689 }
3690 return result;
3691}
3692
Elliott Hughes872d4ec2011-10-21 17:07:15 -07003693} // namespace art