blob: d50b55bf1bcab7749b58113f042f062bedbf57e2 [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 Rogers1d54e732013-05-02 21:10:01 -070027#include "gc/accounting/card_table-inl.h"
28#include "gc/space/large_object_space.h"
29#include "gc/space/space-inl.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 |
Jeff Hao14dd5a82013-04-11 10:23:36 -0700541 instrumentation::Instrumentation::kDexPcMoved |
542 instrumentation::Instrumentation::kExceptionCaught);
Elliott Hughesa2155262011-11-16 16:26:58 -0800543 gDebuggerActive = true;
Ian Rogers62d6c772013-02-27 08:32:07 -0800544 CHECK_EQ(self->SetStateUnsafe(old_state), kRunnable);
545 runtime->GetThreadList()->ResumeAll();
546
547 LOG(INFO) << "Debugger is active";
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700548}
549
550void Dbg::Disconnected() {
Elliott Hughes234ab152011-10-26 14:02:26 -0700551 CHECK(gDebuggerConnected);
552
Elliott Hughesc0f09332012-03-26 13:27:06 -0700553 LOG(INFO) << "Debugger is no longer active";
Elliott Hughes234ab152011-10-26 14:02:26 -0700554
Ian Rogers62d6c772013-02-27 08:32:07 -0800555 // Suspend all threads and exclusively acquire the mutator lock. Set the state of the thread
556 // to kRunnable to avoid scoped object access transitions. Remove the debugger as a listener
557 // and clear the object registry.
558 Runtime* runtime = Runtime::Current();
559 runtime->GetThreadList()->SuspendAll();
560 Thread* self = Thread::Current();
561 ThreadState old_state = self->SetStateUnsafe(kRunnable);
562 runtime->GetInstrumentation()->RemoveListener(&gDebugInstrumentationListener,
563 instrumentation::Instrumentation::kMethodEntered |
564 instrumentation::Instrumentation::kMethodExited |
Jeff Hao14dd5a82013-04-11 10:23:36 -0700565 instrumentation::Instrumentation::kDexPcMoved |
566 instrumentation::Instrumentation::kExceptionCaught);
Elliott Hughesc0f09332012-03-26 13:27:06 -0700567 gDebuggerActive = false;
Elliott Hughes234ab152011-10-26 14:02:26 -0700568 gRegistry->Clear();
569 gDebuggerConnected = false;
Ian Rogers62d6c772013-02-27 08:32:07 -0800570 CHECK_EQ(self->SetStateUnsafe(old_state), kRunnable);
571 runtime->GetThreadList()->ResumeAll();
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700572}
573
Elliott Hughesc0f09332012-03-26 13:27:06 -0700574bool Dbg::IsDebuggerActive() {
Elliott Hughes3bb81562011-10-21 18:52:59 -0700575 return gDebuggerActive;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700576}
577
Elliott Hughesc0f09332012-03-26 13:27:06 -0700578bool Dbg::IsJdwpConfigured() {
Elliott Hughes3bb81562011-10-21 18:52:59 -0700579 return gJdwpConfigured;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700580}
581
582int64_t Dbg::LastDebuggerActivity() {
Elliott Hughesca951522011-12-05 12:01:32 -0800583 return gJdwpState->LastDebuggerActivity();
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700584}
585
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700586void Dbg::UndoDebuggerSuspensions() {
Elliott Hughes234ab152011-10-26 14:02:26 -0700587 Runtime::Current()->GetThreadList()->UndoDebuggerSuspensions();
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700588}
589
Elliott Hughes88d63092013-01-09 09:55:54 -0800590std::string Dbg::GetClassName(JDWP::RefTypeId class_id) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800591 mirror::Object* o = gRegistry->Get<mirror::Object*>(class_id);
Elliott Hughes436e3722012-02-17 20:01:47 -0800592 if (o == NULL) {
593 return "NULL";
594 }
Elliott Hughes64f574f2013-02-20 14:57:12 -0800595 if (o == ObjectRegistry::kInvalidObject) {
Elliott Hughes88d63092013-01-09 09:55:54 -0800596 return StringPrintf("invalid object %p", reinterpret_cast<void*>(class_id));
Elliott Hughes436e3722012-02-17 20:01:47 -0800597 }
598 if (!o->IsClass()) {
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -0800599 return StringPrintf("non-class %p", o); // This is only used for debugging output anyway.
600 }
Elliott Hughesc308a5d2012-02-16 17:12:06 -0800601 return DescriptorToName(ClassHelper(o->AsClass()).GetDescriptor());
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700602}
603
Elliott Hughes88d63092013-01-09 09:55:54 -0800604JDWP::JdwpError Dbg::GetClassObject(JDWP::RefTypeId id, JDWP::ObjectId& class_object_id) {
Elliott Hughes436e3722012-02-17 20:01:47 -0800605 JDWP::JdwpError status;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800606 mirror::Class* c = DecodeClass(id, status);
Elliott Hughes436e3722012-02-17 20:01:47 -0800607 if (c == NULL) {
608 return status;
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -0800609 }
Elliott Hughes88d63092013-01-09 09:55:54 -0800610 class_object_id = gRegistry->Add(c);
Elliott Hughes436e3722012-02-17 20:01:47 -0800611 return JDWP::ERR_NONE;
Elliott Hughes86964332012-02-15 19:37:42 -0800612}
613
Elliott Hughes88d63092013-01-09 09:55:54 -0800614JDWP::JdwpError Dbg::GetSuperclass(JDWP::RefTypeId id, JDWP::RefTypeId& superclass_id) {
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -0800615 JDWP::JdwpError status;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800616 mirror::Class* c = DecodeClass(id, status);
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -0800617 if (c == NULL) {
618 return status;
619 }
620 if (c->IsInterface()) {
621 // http://code.google.com/p/android/issues/detail?id=20856
Elliott Hughes88d63092013-01-09 09:55:54 -0800622 superclass_id = 0;
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -0800623 } else {
Elliott Hughes88d63092013-01-09 09:55:54 -0800624 superclass_id = gRegistry->Add(c->GetSuperClass());
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -0800625 }
626 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700627}
628
Elliott Hughes436e3722012-02-17 20:01:47 -0800629JDWP::JdwpError Dbg::GetClassLoader(JDWP::RefTypeId id, JDWP::ExpandBuf* pReply) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800630 mirror::Object* o = gRegistry->Get<mirror::Object*>(id);
Elliott Hughes64f574f2013-02-20 14:57:12 -0800631 if (o == NULL || o == ObjectRegistry::kInvalidObject) {
Elliott Hughes436e3722012-02-17 20:01:47 -0800632 return JDWP::ERR_INVALID_OBJECT;
633 }
634 expandBufAddObjectId(pReply, gRegistry->Add(o->GetClass()->GetClassLoader()));
635 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700636}
637
Elliott Hughes436e3722012-02-17 20:01:47 -0800638JDWP::JdwpError Dbg::GetModifiers(JDWP::RefTypeId id, JDWP::ExpandBuf* pReply) {
639 JDWP::JdwpError status;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800640 mirror::Class* c = DecodeClass(id, status);
Elliott Hughes436e3722012-02-17 20:01:47 -0800641 if (c == NULL) {
642 return status;
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -0800643 }
Elliott Hughes436e3722012-02-17 20:01:47 -0800644
645 uint32_t access_flags = c->GetAccessFlags() & kAccJavaFlagsMask;
646
647 // Set ACC_SUPER; dex files don't contain this flag, but all classes are supposed to have it set.
648 // Class.getModifiers doesn't return it, but JDWP does, so we set it here.
649 access_flags |= kAccSuper;
650
651 expandBufAdd4BE(pReply, access_flags);
652
653 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700654}
655
Elliott Hughesf327e072013-01-09 16:01:26 -0800656JDWP::JdwpError Dbg::GetMonitorInfo(JDWP::ObjectId object_id, JDWP::ExpandBuf* reply)
657 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800658 mirror::Object* o = gRegistry->Get<mirror::Object*>(object_id);
Elliott Hughes64f574f2013-02-20 14:57:12 -0800659 if (o == NULL || o == ObjectRegistry::kInvalidObject) {
Elliott Hughesf327e072013-01-09 16:01:26 -0800660 return JDWP::ERR_INVALID_OBJECT;
661 }
662
663 // Ensure all threads are suspended while we read objects' lock words.
664 Thread* self = Thread::Current();
665 Locks::mutator_lock_->SharedUnlock(self);
666 Locks::mutator_lock_->ExclusiveLock(self);
667
668 MonitorInfo monitor_info(o);
669
670 Locks::mutator_lock_->ExclusiveUnlock(self);
671 Locks::mutator_lock_->SharedLock(self);
672
673 if (monitor_info.owner != NULL) {
674 expandBufAddObjectId(reply, gRegistry->Add(monitor_info.owner->GetPeer()));
675 } else {
676 expandBufAddObjectId(reply, gRegistry->Add(NULL));
677 }
678 expandBufAdd4BE(reply, monitor_info.entry_count);
679 expandBufAdd4BE(reply, monitor_info.waiters.size());
680 for (size_t i = 0; i < monitor_info.waiters.size(); ++i) {
681 expandBufAddObjectId(reply, gRegistry->Add(monitor_info.waiters[i]->GetPeer()));
682 }
683 return JDWP::ERR_NONE;
684}
685
Elliott Hughes734b8c62013-01-11 15:32:45 -0800686JDWP::JdwpError Dbg::GetOwnedMonitors(JDWP::ObjectId thread_id,
687 std::vector<JDWP::ObjectId>& monitors,
688 std::vector<uint32_t>& stack_depths)
Elliott Hughes4993bbc2013-01-10 15:41:25 -0800689 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
690 ScopedObjectAccessUnchecked soa(Thread::Current());
691 MutexLock mu(soa.Self(), *Locks::thread_list_lock_);
692 Thread* thread;
693 JDWP::JdwpError error = DecodeThread(soa, thread_id, thread);
694 if (error != JDWP::ERR_NONE) {
695 return error;
696 }
697 if (!IsSuspendedForDebugger(soa, thread)) {
698 return JDWP::ERR_THREAD_NOT_SUSPENDED;
699 }
700
701 struct OwnedMonitorVisitor : public StackVisitor {
Ian Rogers7a22fa62013-01-23 12:16:16 -0800702 OwnedMonitorVisitor(Thread* thread, Context* context)
Elliott Hughes4993bbc2013-01-10 15:41:25 -0800703 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_)
Ian Rogers7a22fa62013-01-23 12:16:16 -0800704 : StackVisitor(thread, context), current_stack_depth(0) {}
Elliott Hughes4993bbc2013-01-10 15:41:25 -0800705
706 // TODO: Enable annotalysis. We know lock is held in constructor, but abstraction confuses
707 // annotalysis.
708 bool VisitFrame() NO_THREAD_SAFETY_ANALYSIS {
709 if (!GetMethod()->IsRuntimeMethod()) {
710 Monitor::VisitLocks(this, AppendOwnedMonitors, this);
Elliott Hughes734b8c62013-01-11 15:32:45 -0800711 ++current_stack_depth;
Elliott Hughes4993bbc2013-01-10 15:41:25 -0800712 }
713 return true;
714 }
715
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800716 static void AppendOwnedMonitors(mirror::Object* owned_monitor, void* arg) {
Ian Rogers7a22fa62013-01-23 12:16:16 -0800717 OwnedMonitorVisitor* visitor = reinterpret_cast<OwnedMonitorVisitor*>(arg);
Elliott Hughes734b8c62013-01-11 15:32:45 -0800718 visitor->monitors.push_back(owned_monitor);
719 visitor->stack_depths.push_back(visitor->current_stack_depth);
Elliott Hughes4993bbc2013-01-10 15:41:25 -0800720 }
721
Elliott Hughes734b8c62013-01-11 15:32:45 -0800722 size_t current_stack_depth;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800723 std::vector<mirror::Object*> monitors;
Elliott Hughes734b8c62013-01-11 15:32:45 -0800724 std::vector<uint32_t> stack_depths;
Elliott Hughes4993bbc2013-01-10 15:41:25 -0800725 };
Ian Rogers7a22fa62013-01-23 12:16:16 -0800726 UniquePtr<Context> context(Context::Create());
727 OwnedMonitorVisitor visitor(thread, context.get());
Elliott Hughes4993bbc2013-01-10 15:41:25 -0800728 visitor.WalkStack();
729
730 for (size_t i = 0; i < visitor.monitors.size(); ++i) {
731 monitors.push_back(gRegistry->Add(visitor.monitors[i]));
Elliott Hughes734b8c62013-01-11 15:32:45 -0800732 stack_depths.push_back(visitor.stack_depths[i]);
Elliott Hughes4993bbc2013-01-10 15:41:25 -0800733 }
734
735 return JDWP::ERR_NONE;
736}
737
Elliott Hughesf9501702013-01-11 11:22:27 -0800738JDWP::JdwpError Dbg::GetContendedMonitor(JDWP::ObjectId thread_id, JDWP::ObjectId& contended_monitor)
739 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
740 ScopedObjectAccessUnchecked soa(Thread::Current());
741 MutexLock mu(soa.Self(), *Locks::thread_list_lock_);
742 Thread* thread;
743 JDWP::JdwpError error = DecodeThread(soa, thread_id, thread);
744 if (error != JDWP::ERR_NONE) {
745 return error;
746 }
747 if (!IsSuspendedForDebugger(soa, thread)) {
748 return JDWP::ERR_THREAD_NOT_SUSPENDED;
749 }
750
751 contended_monitor = gRegistry->Add(Monitor::GetContendedMonitor(thread));
752
753 return JDWP::ERR_NONE;
754}
755
Elliott Hughesec0f83d2013-01-15 16:54:08 -0800756JDWP::JdwpError Dbg::GetInstanceCounts(const std::vector<JDWP::RefTypeId>& class_ids,
757 std::vector<uint64_t>& counts)
758 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
759
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800760 std::vector<mirror::Class*> classes;
Elliott Hughesec0f83d2013-01-15 16:54:08 -0800761 counts.clear();
762 for (size_t i = 0; i < class_ids.size(); ++i) {
763 JDWP::JdwpError status;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800764 mirror::Class* c = DecodeClass(class_ids[i], status);
Elliott Hughesec0f83d2013-01-15 16:54:08 -0800765 if (c == NULL) {
766 return status;
767 }
768 classes.push_back(c);
769 counts.push_back(0);
770 }
771
772 Runtime::Current()->GetHeap()->CountInstances(classes, false, &counts[0]);
773 return JDWP::ERR_NONE;
774}
775
Elliott Hughes3b78c942013-01-15 17:35:41 -0800776JDWP::JdwpError Dbg::GetInstances(JDWP::RefTypeId class_id, int32_t max_count, std::vector<JDWP::ObjectId>& instances)
777 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
778 JDWP::JdwpError status;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800779 mirror::Class* c = DecodeClass(class_id, status);
Elliott Hughes3b78c942013-01-15 17:35:41 -0800780 if (c == NULL) {
781 return status;
782 }
783
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800784 std::vector<mirror::Object*> raw_instances;
Elliott Hughes3b78c942013-01-15 17:35:41 -0800785 Runtime::Current()->GetHeap()->GetInstances(c, max_count, raw_instances);
786 for (size_t i = 0; i < raw_instances.size(); ++i) {
787 instances.push_back(gRegistry->Add(raw_instances[i]));
788 }
789 return JDWP::ERR_NONE;
790}
791
Elliott Hughes0cbaff52013-01-16 15:28:01 -0800792JDWP::JdwpError Dbg::GetReferringObjects(JDWP::ObjectId object_id, int32_t max_count,
793 std::vector<JDWP::ObjectId>& referring_objects)
794 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800795 mirror::Object* o = gRegistry->Get<mirror::Object*>(object_id);
Elliott Hughes64f574f2013-02-20 14:57:12 -0800796 if (o == NULL || o == ObjectRegistry::kInvalidObject) {
Elliott Hughes0cbaff52013-01-16 15:28:01 -0800797 return JDWP::ERR_INVALID_OBJECT;
798 }
799
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800800 std::vector<mirror::Object*> raw_instances;
Elliott Hughes0cbaff52013-01-16 15:28:01 -0800801 Runtime::Current()->GetHeap()->GetReferringObjects(o, max_count, raw_instances);
802 for (size_t i = 0; i < raw_instances.size(); ++i) {
803 referring_objects.push_back(gRegistry->Add(raw_instances[i]));
804 }
805 return JDWP::ERR_NONE;
806}
807
Elliott Hughes64f574f2013-02-20 14:57:12 -0800808JDWP::JdwpError Dbg::DisableCollection(JDWP::ObjectId object_id)
809 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
810 gRegistry->DisableCollection(object_id);
811 return JDWP::ERR_NONE;
812}
813
814JDWP::JdwpError Dbg::EnableCollection(JDWP::ObjectId object_id)
815 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
816 gRegistry->EnableCollection(object_id);
817 return JDWP::ERR_NONE;
818}
819
820JDWP::JdwpError Dbg::IsCollected(JDWP::ObjectId object_id, bool& is_collected)
821 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
822 is_collected = gRegistry->IsCollected(object_id);
823 return JDWP::ERR_NONE;
824}
825
826void Dbg::DisposeObject(JDWP::ObjectId object_id, uint32_t reference_count)
827 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
828 gRegistry->DisposeObject(object_id, reference_count);
829}
830
Elliott Hughes88d63092013-01-09 09:55:54 -0800831JDWP::JdwpError Dbg::GetReflectedType(JDWP::RefTypeId class_id, JDWP::ExpandBuf* pReply) {
Elliott Hughes436e3722012-02-17 20:01:47 -0800832 JDWP::JdwpError status;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800833 mirror::Class* c = DecodeClass(class_id, status);
Elliott Hughes436e3722012-02-17 20:01:47 -0800834 if (c == NULL) {
835 return status;
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -0800836 }
Elliott Hughes436e3722012-02-17 20:01:47 -0800837
838 expandBufAdd1(pReply, c->IsInterface() ? JDWP::TT_INTERFACE : JDWP::TT_CLASS);
Elliott Hughes88d63092013-01-09 09:55:54 -0800839 expandBufAddRefTypeId(pReply, class_id);
Elliott Hughes436e3722012-02-17 20:01:47 -0800840 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700841}
842
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -0800843void Dbg::GetClassList(std::vector<JDWP::RefTypeId>& classes) {
Elliott Hughesa2155262011-11-16 16:26:58 -0800844 // Get the complete list of reference classes (i.e. all classes except
845 // the primitive types).
846 // Returns a newly-allocated buffer full of RefTypeId values.
847 struct ClassListCreator {
Elliott Hughesba8eee12012-01-24 20:25:24 -0800848 explicit ClassListCreator(std::vector<JDWP::RefTypeId>& classes) : classes(classes) {
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -0800849 }
850
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800851 static bool Visit(mirror::Class* c, void* arg) {
Elliott Hughesa2155262011-11-16 16:26:58 -0800852 return reinterpret_cast<ClassListCreator*>(arg)->Visit(c);
853 }
854
Elliott Hughes64f574f2013-02-20 14:57:12 -0800855 // TODO: Enable annotalysis. We know lock is held in constructor, but abstraction confuses
856 // annotalysis.
857 bool Visit(mirror::Class* c) NO_THREAD_SAFETY_ANALYSIS {
Elliott Hughesa2155262011-11-16 16:26:58 -0800858 if (!c->IsPrimitive()) {
Elliott Hughes64f574f2013-02-20 14:57:12 -0800859 classes.push_back(gRegistry->AddRefType(c));
Elliott Hughesa2155262011-11-16 16:26:58 -0800860 }
861 return true;
862 }
863
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -0800864 std::vector<JDWP::RefTypeId>& classes;
Elliott Hughesa2155262011-11-16 16:26:58 -0800865 };
866
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -0800867 ClassListCreator clc(classes);
Elliott Hughesa2155262011-11-16 16:26:58 -0800868 Runtime::Current()->GetClassLinker()->VisitClasses(ClassListCreator::Visit, &clc);
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700869}
870
Elliott Hughes88d63092013-01-09 09:55:54 -0800871JDWP::JdwpError Dbg::GetClassInfo(JDWP::RefTypeId class_id, JDWP::JdwpTypeTag* pTypeTag, uint32_t* pStatus, std::string* pDescriptor) {
Elliott Hughes436e3722012-02-17 20:01:47 -0800872 JDWP::JdwpError status;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800873 mirror::Class* c = DecodeClass(class_id, status);
Elliott Hughes436e3722012-02-17 20:01:47 -0800874 if (c == NULL) {
875 return status;
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -0800876 }
877
Elliott Hughesa2155262011-11-16 16:26:58 -0800878 if (c->IsArrayClass()) {
879 *pStatus = JDWP::CS_VERIFIED | JDWP::CS_PREPARED;
880 *pTypeTag = JDWP::TT_ARRAY;
881 } else {
882 if (c->IsErroneous()) {
883 *pStatus = JDWP::CS_ERROR;
884 } else {
885 *pStatus = JDWP::CS_VERIFIED | JDWP::CS_PREPARED | JDWP::CS_INITIALIZED;
886 }
887 *pTypeTag = c->IsInterface() ? JDWP::TT_INTERFACE : JDWP::TT_CLASS;
888 }
889
890 if (pDescriptor != NULL) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800891 *pDescriptor = ClassHelper(c).GetDescriptor();
Elliott Hughesa2155262011-11-16 16:26:58 -0800892 }
Elliott Hughes436e3722012-02-17 20:01:47 -0800893 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700894}
895
Elliott Hughesc3b77c72011-12-15 20:56:48 -0800896void Dbg::FindLoadedClassBySignature(const char* descriptor, std::vector<JDWP::RefTypeId>& ids) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800897 std::vector<mirror::Class*> classes;
Elliott Hughes6fa602d2011-12-02 17:54:25 -0800898 Runtime::Current()->GetClassLinker()->LookupClasses(descriptor, classes);
899 ids.clear();
900 for (size_t i = 0; i < classes.size(); ++i) {
901 ids.push_back(gRegistry->Add(classes[i]));
902 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700903}
904
Elliott Hughes64f574f2013-02-20 14:57:12 -0800905JDWP::JdwpError Dbg::GetReferenceType(JDWP::ObjectId object_id, JDWP::ExpandBuf* pReply)
906 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800907 mirror::Object* o = gRegistry->Get<mirror::Object*>(object_id);
Elliott Hughes64f574f2013-02-20 14:57:12 -0800908 if (o == NULL || o == ObjectRegistry::kInvalidObject) {
Elliott Hughes2435a572012-02-17 16:07:41 -0800909 return JDWP::ERR_INVALID_OBJECT;
Elliott Hughes499c5132011-11-17 14:55:11 -0800910 }
Elliott Hughes2435a572012-02-17 16:07:41 -0800911
912 JDWP::JdwpTypeTag type_tag;
913 if (o->GetClass()->IsArrayClass()) {
914 type_tag = JDWP::TT_ARRAY;
915 } else if (o->GetClass()->IsInterface()) {
916 type_tag = JDWP::TT_INTERFACE;
917 } else {
918 type_tag = JDWP::TT_CLASS;
919 }
Elliott Hughes64f574f2013-02-20 14:57:12 -0800920 JDWP::RefTypeId type_id = gRegistry->AddRefType(o->GetClass());
Elliott Hughes2435a572012-02-17 16:07:41 -0800921
922 expandBufAdd1(pReply, type_tag);
923 expandBufAddRefTypeId(pReply, type_id);
924
925 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700926}
927
Elliott Hughes88d63092013-01-09 09:55:54 -0800928JDWP::JdwpError Dbg::GetSignature(JDWP::RefTypeId class_id, std::string& signature) {
Elliott Hughes1fe7afb2012-02-13 17:23:03 -0800929 JDWP::JdwpError status;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800930 mirror::Class* c = DecodeClass(class_id, status);
Elliott Hughes1fe7afb2012-02-13 17:23:03 -0800931 if (c == NULL) {
932 return status;
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -0800933 }
Elliott Hughes1fe7afb2012-02-13 17:23:03 -0800934 signature = ClassHelper(c).GetDescriptor();
935 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700936}
937
Elliott Hughes88d63092013-01-09 09:55:54 -0800938JDWP::JdwpError Dbg::GetSourceFile(JDWP::RefTypeId class_id, std::string& result) {
Elliott Hughes436e3722012-02-17 20:01:47 -0800939 JDWP::JdwpError status;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800940 mirror::Class* c = DecodeClass(class_id, status);
Elliott Hughes436e3722012-02-17 20:01:47 -0800941 if (c == NULL) {
942 return status;
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -0800943 }
Elliott Hughes436e3722012-02-17 20:01:47 -0800944 result = ClassHelper(c).GetSourceFile();
945 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700946}
947
Elliott Hughes88d63092013-01-09 09:55:54 -0800948JDWP::JdwpError Dbg::GetObjectTag(JDWP::ObjectId object_id, uint8_t& tag) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800949 mirror::Object* o = gRegistry->Get<mirror::Object*>(object_id);
Elliott Hughes64f574f2013-02-20 14:57:12 -0800950 if (o == ObjectRegistry::kInvalidObject) {
Elliott Hughes546b9862012-06-20 16:06:13 -0700951 return JDWP::ERR_INVALID_OBJECT;
952 }
953 tag = TagFromObject(o);
954 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700955}
956
Elliott Hughesaed4be92011-12-02 16:16:23 -0800957size_t Dbg::GetTagWidth(JDWP::JdwpTag tag) {
Elliott Hughesdbb40792011-11-18 17:05:22 -0800958 switch (tag) {
959 case JDWP::JT_VOID:
960 return 0;
961 case JDWP::JT_BYTE:
962 case JDWP::JT_BOOLEAN:
963 return 1;
964 case JDWP::JT_CHAR:
965 case JDWP::JT_SHORT:
966 return 2;
967 case JDWP::JT_FLOAT:
968 case JDWP::JT_INT:
969 return 4;
970 case JDWP::JT_ARRAY:
971 case JDWP::JT_OBJECT:
972 case JDWP::JT_STRING:
973 case JDWP::JT_THREAD:
974 case JDWP::JT_THREAD_GROUP:
975 case JDWP::JT_CLASS_LOADER:
976 case JDWP::JT_CLASS_OBJECT:
977 return sizeof(JDWP::ObjectId);
978 case JDWP::JT_DOUBLE:
979 case JDWP::JT_LONG:
980 return 8;
981 default:
Elliott Hughes3d30d9b2011-12-07 17:35:48 -0800982 LOG(FATAL) << "Unknown tag " << tag;
Elliott Hughesdbb40792011-11-18 17:05:22 -0800983 return -1;
984 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700985}
986
Elliott Hughes88d63092013-01-09 09:55:54 -0800987JDWP::JdwpError Dbg::GetArrayLength(JDWP::ObjectId array_id, int& length) {
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -0800988 JDWP::JdwpError status;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800989 mirror::Array* a = DecodeArray(array_id, status);
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -0800990 if (a == NULL) {
991 return status;
Elliott Hughes24437992011-11-30 14:49:33 -0800992 }
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -0800993 length = a->GetLength();
994 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700995}
996
Elliott Hughes88d63092013-01-09 09:55:54 -0800997JDWP::JdwpError Dbg::OutputArray(JDWP::ObjectId array_id, int offset, int count, JDWP::ExpandBuf* pReply) {
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -0800998 JDWP::JdwpError status;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800999 mirror::Array* a = DecodeArray(array_id, status);
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -08001000 if (a == NULL) {
1001 return status;
1002 }
Elliott Hughes24437992011-11-30 14:49:33 -08001003
1004 if (offset < 0 || count < 0 || offset > a->GetLength() || a->GetLength() - offset < count) {
1005 LOG(WARNING) << __FUNCTION__ << " access out of bounds: offset=" << offset << "; count=" << count;
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -08001006 return JDWP::ERR_INVALID_LENGTH;
Elliott Hughes24437992011-11-30 14:49:33 -08001007 }
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001008 std::string descriptor(ClassHelper(a->GetClass()).GetDescriptor());
Elliott Hughes24437992011-11-30 14:49:33 -08001009 JDWP::JdwpTag tag = BasicTagFromDescriptor(descriptor.c_str() + 1);
1010
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -08001011 expandBufAdd1(pReply, tag);
1012 expandBufAdd4BE(pReply, count);
1013
Elliott Hughes24437992011-11-30 14:49:33 -08001014 if (IsPrimitiveTag(tag)) {
1015 size_t width = GetTagWidth(tag);
Elliott Hughes24437992011-11-30 14:49:33 -08001016 uint8_t* dst = expandBufAddSpace(pReply, count * width);
1017 if (width == 8) {
Ian Rogersa15e67d2012-02-28 13:51:55 -08001018 const uint64_t* src8 = reinterpret_cast<uint64_t*>(a->GetRawData(sizeof(uint64_t)));
Elliott Hughes24437992011-11-30 14:49:33 -08001019 for (int i = 0; i < count; ++i) JDWP::Write8BE(&dst, src8[offset + i]);
1020 } else if (width == 4) {
Ian Rogersa15e67d2012-02-28 13:51:55 -08001021 const uint32_t* src4 = reinterpret_cast<uint32_t*>(a->GetRawData(sizeof(uint32_t)));
Elliott Hughes24437992011-11-30 14:49:33 -08001022 for (int i = 0; i < count; ++i) JDWP::Write4BE(&dst, src4[offset + i]);
1023 } else if (width == 2) {
Ian Rogersa15e67d2012-02-28 13:51:55 -08001024 const uint16_t* src2 = reinterpret_cast<uint16_t*>(a->GetRawData(sizeof(uint16_t)));
Elliott Hughes24437992011-11-30 14:49:33 -08001025 for (int i = 0; i < count; ++i) JDWP::Write2BE(&dst, src2[offset + i]);
1026 } else {
Ian Rogersa15e67d2012-02-28 13:51:55 -08001027 const uint8_t* src = reinterpret_cast<uint8_t*>(a->GetRawData(sizeof(uint8_t)));
Elliott Hughes24437992011-11-30 14:49:33 -08001028 memcpy(dst, &src[offset * width], count * width);
1029 }
1030 } else {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001031 mirror::ObjectArray<mirror::Object>* oa = a->AsObjectArray<mirror::Object>();
Elliott Hughes24437992011-11-30 14:49:33 -08001032 for (int i = 0; i < count; ++i) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001033 mirror::Object* element = oa->Get(offset + i);
Elliott Hughes24437992011-11-30 14:49:33 -08001034 JDWP::JdwpTag specific_tag = (element != NULL) ? TagFromObject(element) : tag;
1035 expandBufAdd1(pReply, specific_tag);
1036 expandBufAddObjectId(pReply, gRegistry->Add(element));
1037 }
1038 }
1039
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -08001040 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001041}
1042
Elliott Hughes4b9702c2013-02-20 18:13:24 -08001043template <typename T> void CopyArrayData(mirror::Array* a, JDWP::Request& src, int offset, int count) {
1044 DCHECK(a->GetClass()->IsPrimitiveArray());
1045
1046 T* dst = &(reinterpret_cast<T*>(a->GetRawData(sizeof(T)))[offset * sizeof(T)]);
1047 for (int i = 0; i < count; ++i) {
1048 *dst++ = src.ReadValue(sizeof(T));
1049 }
1050}
1051
Elliott Hughes88d63092013-01-09 09:55:54 -08001052JDWP::JdwpError Dbg::SetArrayElements(JDWP::ObjectId array_id, int offset, int count,
Elliott Hughes4b9702c2013-02-20 18:13:24 -08001053 JDWP::Request& request)
Ian Rogersb726dcb2012-09-05 08:57:23 -07001054 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -08001055 JDWP::JdwpError status;
Elliott Hughes4b9702c2013-02-20 18:13:24 -08001056 mirror::Array* dst = DecodeArray(array_id, status);
1057 if (dst == NULL) {
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -08001058 return status;
1059 }
Elliott Hughesf03b8f62011-12-02 14:26:25 -08001060
Elliott Hughes4b9702c2013-02-20 18:13:24 -08001061 if (offset < 0 || count < 0 || offset > dst->GetLength() || dst->GetLength() - offset < count) {
Elliott Hughesf03b8f62011-12-02 14:26:25 -08001062 LOG(WARNING) << __FUNCTION__ << " access out of bounds: offset=" << offset << "; count=" << count;
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -08001063 return JDWP::ERR_INVALID_LENGTH;
Elliott Hughesf03b8f62011-12-02 14:26:25 -08001064 }
Elliott Hughes4b9702c2013-02-20 18:13:24 -08001065 std::string descriptor(ClassHelper(dst->GetClass()).GetDescriptor());
Elliott Hughesf03b8f62011-12-02 14:26:25 -08001066 JDWP::JdwpTag tag = BasicTagFromDescriptor(descriptor.c_str() + 1);
1067
1068 if (IsPrimitiveTag(tag)) {
1069 size_t width = GetTagWidth(tag);
Elliott Hughesf03b8f62011-12-02 14:26:25 -08001070 if (width == 8) {
Elliott Hughes4b9702c2013-02-20 18:13:24 -08001071 CopyArrayData<uint64_t>(dst, request, offset, count);
Elliott Hughesf03b8f62011-12-02 14:26:25 -08001072 } else if (width == 4) {
Elliott Hughes4b9702c2013-02-20 18:13:24 -08001073 CopyArrayData<uint32_t>(dst, request, offset, count);
Elliott Hughesf03b8f62011-12-02 14:26:25 -08001074 } else if (width == 2) {
Elliott Hughes4b9702c2013-02-20 18:13:24 -08001075 CopyArrayData<uint16_t>(dst, request, offset, count);
Elliott Hughesf03b8f62011-12-02 14:26:25 -08001076 } else {
Elliott Hughes4b9702c2013-02-20 18:13:24 -08001077 CopyArrayData<uint8_t>(dst, request, offset, count);
Elliott Hughesf03b8f62011-12-02 14:26:25 -08001078 }
1079 } else {
Elliott Hughes4b9702c2013-02-20 18:13:24 -08001080 mirror::ObjectArray<mirror::Object>* oa = dst->AsObjectArray<mirror::Object>();
Elliott Hughesf03b8f62011-12-02 14:26:25 -08001081 for (int i = 0; i < count; ++i) {
Elliott Hughes4b9702c2013-02-20 18:13:24 -08001082 JDWP::ObjectId id = request.ReadObjectId();
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001083 mirror::Object* o = gRegistry->Get<mirror::Object*>(id);
Elliott Hughes64f574f2013-02-20 14:57:12 -08001084 if (o == ObjectRegistry::kInvalidObject) {
Elliott Hughes436e3722012-02-17 20:01:47 -08001085 return JDWP::ERR_INVALID_OBJECT;
1086 }
1087 oa->Set(offset + i, o);
Elliott Hughesf03b8f62011-12-02 14:26:25 -08001088 }
1089 }
1090
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -08001091 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001092}
1093
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -08001094JDWP::ObjectId Dbg::CreateString(const std::string& str) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001095 return gRegistry->Add(mirror::String::AllocFromModifiedUtf8(Thread::Current(), str.c_str()));
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001096}
1097
Elliott Hughes88d63092013-01-09 09:55:54 -08001098JDWP::JdwpError Dbg::CreateObject(JDWP::RefTypeId class_id, JDWP::ObjectId& new_object) {
Elliott Hughes436e3722012-02-17 20:01:47 -08001099 JDWP::JdwpError status;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001100 mirror::Class* c = DecodeClass(class_id, status);
Elliott Hughes436e3722012-02-17 20:01:47 -08001101 if (c == NULL) {
1102 return status;
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -08001103 }
Ian Rogers50b35e22012-10-04 10:09:15 -07001104 new_object = gRegistry->Add(c->AllocObject(Thread::Current()));
Elliott Hughes436e3722012-02-17 20:01:47 -08001105 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001106}
1107
Elliott Hughesbf13d362011-12-08 15:51:37 -08001108/*
1109 * Used by Eclipse's "Display" view to evaluate "new byte[5]" to get "(byte[]) [0, 0, 0, 0, 0]".
1110 */
Elliott Hughes88d63092013-01-09 09:55:54 -08001111JDWP::JdwpError Dbg::CreateArrayObject(JDWP::RefTypeId array_class_id, uint32_t length,
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001112 JDWP::ObjectId& new_array) {
Elliott Hughes436e3722012-02-17 20:01:47 -08001113 JDWP::JdwpError status;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001114 mirror::Class* c = DecodeClass(array_class_id, status);
Elliott Hughes436e3722012-02-17 20:01:47 -08001115 if (c == NULL) {
1116 return status;
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -08001117 }
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001118 new_array = gRegistry->Add(mirror::Array::Alloc(Thread::Current(), c, length));
Elliott Hughes436e3722012-02-17 20:01:47 -08001119 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001120}
1121
Elliott Hughes88d63092013-01-09 09:55:54 -08001122bool Dbg::MatchType(JDWP::RefTypeId instance_class_id, JDWP::RefTypeId class_id) {
Elliott Hughes436e3722012-02-17 20:01:47 -08001123 JDWP::JdwpError status;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001124 mirror::Class* c1 = DecodeClass(instance_class_id, status);
Elliott Hughesa656a0f2012-02-21 18:03:44 -08001125 CHECK(c1 != NULL);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001126 mirror::Class* c2 = DecodeClass(class_id, status);
Elliott Hughesa656a0f2012-02-21 18:03:44 -08001127 CHECK(c2 != NULL);
1128 return c1->IsAssignableFrom(c2);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001129}
1130
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001131static JDWP::FieldId ToFieldId(const mirror::Field* f)
Ian Rogersb726dcb2012-09-05 08:57:23 -07001132 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Elliott Hughes03181a82011-11-17 17:22:21 -08001133#ifdef MOVING_GARBAGE_COLLECTOR
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001134 UNIMPLEMENTED(FATAL);
Elliott Hughes03181a82011-11-17 17:22:21 -08001135#else
1136 return static_cast<JDWP::FieldId>(reinterpret_cast<uintptr_t>(f));
1137#endif
1138}
1139
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001140static JDWP::MethodId ToMethodId(const mirror::AbstractMethod* m)
Ian Rogersb726dcb2012-09-05 08:57:23 -07001141 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Elliott Hughes03181a82011-11-17 17:22:21 -08001142#ifdef MOVING_GARBAGE_COLLECTOR
1143 UNIMPLEMENTED(FATAL);
1144#else
1145 return static_cast<JDWP::MethodId>(reinterpret_cast<uintptr_t>(m));
1146#endif
1147}
1148
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001149static mirror::Field* FromFieldId(JDWP::FieldId fid)
Ian Rogersb726dcb2012-09-05 08:57:23 -07001150 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Elliott Hughesaed4be92011-12-02 16:16:23 -08001151#ifdef MOVING_GARBAGE_COLLECTOR
1152 UNIMPLEMENTED(FATAL);
1153#else
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001154 return reinterpret_cast<mirror::Field*>(static_cast<uintptr_t>(fid));
Elliott Hughesaed4be92011-12-02 16:16:23 -08001155#endif
1156}
1157
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001158static mirror::AbstractMethod* FromMethodId(JDWP::MethodId mid)
Ian Rogersb726dcb2012-09-05 08:57:23 -07001159 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Elliott Hughes03181a82011-11-17 17:22:21 -08001160#ifdef MOVING_GARBAGE_COLLECTOR
1161 UNIMPLEMENTED(FATAL);
1162#else
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001163 return reinterpret_cast<mirror::AbstractMethod*>(static_cast<uintptr_t>(mid));
Elliott Hughes03181a82011-11-17 17:22:21 -08001164#endif
1165}
1166
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001167static void SetLocation(JDWP::JdwpLocation& location, mirror::AbstractMethod* m, uint32_t dex_pc)
Ian Rogersb726dcb2012-09-05 08:57:23 -07001168 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08001169 if (m == NULL) {
1170 memset(&location, 0, sizeof(location));
1171 } else {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001172 mirror::Class* c = m->GetDeclaringClass();
Elliott Hughes74847412012-06-20 18:10:21 -07001173 location.type_tag = c->IsInterface() ? JDWP::TT_INTERFACE : JDWP::TT_CLASS;
1174 location.class_id = gRegistry->Add(c);
1175 location.method_id = ToMethodId(m);
Ian Rogers0399dde2012-06-06 17:09:28 -07001176 location.dex_pc = dex_pc;
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08001177 }
Elliott Hughesd07986f2011-12-06 18:27:45 -08001178}
1179
Elliott Hughesa96836a2013-01-17 12:27:49 -08001180std::string Dbg::GetMethodName(JDWP::MethodId method_id)
Ian Rogersb726dcb2012-09-05 08:57:23 -07001181 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001182 mirror::AbstractMethod* m = FromMethodId(method_id);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001183 return MethodHelper(m).GetName();
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001184}
1185
Elliott Hughesa96836a2013-01-17 12:27:49 -08001186std::string Dbg::GetFieldName(JDWP::FieldId field_id)
1187 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001188 mirror::Field* f = FromFieldId(field_id);
Elliott Hughesa96836a2013-01-17 12:27:49 -08001189 return FieldHelper(f).GetName();
1190}
1191
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001192/*
1193 * Augment the access flags for synthetic methods and fields by setting
1194 * the (as described by the spec) "0xf0000000 bit". Also, strip out any
1195 * flags not specified by the Java programming language.
1196 */
1197static uint32_t MangleAccessFlags(uint32_t accessFlags) {
1198 accessFlags &= kAccJavaFlagsMask;
1199 if ((accessFlags & kAccSynthetic) != 0) {
1200 accessFlags |= 0xf0000000;
1201 }
1202 return accessFlags;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001203}
1204
Elliott Hughesdbb40792011-11-18 17:05:22 -08001205static const uint16_t kEclipseWorkaroundSlot = 1000;
1206
1207/*
1208 * Eclipse appears to expect that the "this" reference is in slot zero.
1209 * If it's not, the "variables" display will show two copies of "this",
1210 * possibly because it gets "this" from SF.ThisObject and then displays
1211 * all locals with nonzero slot numbers.
1212 *
1213 * So, we remap the item in slot 0 to 1000, and remap "this" to zero. On
1214 * SF.GetValues / SF.SetValues we map them back.
Elliott Hughesc5b734a2011-12-01 17:20:58 -08001215 *
1216 * TODO: jdb uses the value to determine whether a variable is a local or an argument,
1217 * by checking whether it's less than the number of arguments. To make that work, we'd
1218 * have to "mangle" all the arguments to come first, not just the implicit argument 'this'.
Elliott Hughesdbb40792011-11-18 17:05:22 -08001219 */
1220static uint16_t MangleSlot(uint16_t slot, const char* name) {
1221 uint16_t newSlot = slot;
1222 if (strcmp(name, "this") == 0) {
1223 newSlot = 0;
1224 } else if (slot == 0) {
1225 newSlot = kEclipseWorkaroundSlot;
1226 }
1227 return newSlot;
1228}
1229
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001230static uint16_t DemangleSlot(uint16_t slot, mirror::AbstractMethod* m)
Ian Rogersb726dcb2012-09-05 08:57:23 -07001231 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Elliott Hughesdbb40792011-11-18 17:05:22 -08001232 if (slot == kEclipseWorkaroundSlot) {
Elliott Hughes68fdbd02011-11-29 19:22:47 -08001233 return 0;
Elliott Hughesdbb40792011-11-18 17:05:22 -08001234 } else if (slot == 0) {
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08001235 const DexFile::CodeItem* code_item = MethodHelper(m).GetCodeItem();
Elliott Hughescaf76542012-06-28 16:08:22 -07001236 CHECK(code_item != NULL) << PrettyMethod(m);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001237 return code_item->registers_size_ - code_item->ins_size_;
Elliott Hughesdbb40792011-11-18 17:05:22 -08001238 }
Elliott Hughes68fdbd02011-11-29 19:22:47 -08001239 return slot;
Elliott Hughesdbb40792011-11-18 17:05:22 -08001240}
1241
Elliott Hughes88d63092013-01-09 09:55:54 -08001242JDWP::JdwpError Dbg::OutputDeclaredFields(JDWP::RefTypeId class_id, bool with_generic, JDWP::ExpandBuf* pReply) {
Elliott Hughes436e3722012-02-17 20:01:47 -08001243 JDWP::JdwpError status;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001244 mirror::Class* c = DecodeClass(class_id, status);
Elliott Hughes436e3722012-02-17 20:01:47 -08001245 if (c == NULL) {
1246 return status;
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -08001247 }
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001248
1249 size_t instance_field_count = c->NumInstanceFields();
1250 size_t static_field_count = c->NumStaticFields();
1251
1252 expandBufAdd4BE(pReply, instance_field_count + static_field_count);
1253
1254 for (size_t i = 0; i < instance_field_count + static_field_count; ++i) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001255 mirror::Field* f = (i < instance_field_count) ? c->GetInstanceField(i) : c->GetStaticField(i - instance_field_count);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001256 FieldHelper fh(f);
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001257 expandBufAddFieldId(pReply, ToFieldId(f));
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001258 expandBufAddUtf8String(pReply, fh.GetName());
1259 expandBufAddUtf8String(pReply, fh.GetTypeDescriptor());
Elliott Hughesc5b734a2011-12-01 17:20:58 -08001260 if (with_generic) {
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001261 static const char genericSignature[1] = "";
1262 expandBufAddUtf8String(pReply, genericSignature);
1263 }
1264 expandBufAdd4BE(pReply, MangleAccessFlags(f->GetAccessFlags()));
1265 }
Elliott Hughes436e3722012-02-17 20:01:47 -08001266 return JDWP::ERR_NONE;
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001267}
1268
Elliott Hughes88d63092013-01-09 09:55:54 -08001269JDWP::JdwpError Dbg::OutputDeclaredMethods(JDWP::RefTypeId class_id, bool with_generic,
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001270 JDWP::ExpandBuf* pReply) {
Elliott Hughes436e3722012-02-17 20:01:47 -08001271 JDWP::JdwpError status;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001272 mirror::Class* c = DecodeClass(class_id, status);
Elliott Hughes436e3722012-02-17 20:01:47 -08001273 if (c == NULL) {
1274 return status;
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -08001275 }
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001276
1277 size_t direct_method_count = c->NumDirectMethods();
1278 size_t virtual_method_count = c->NumVirtualMethods();
1279
1280 expandBufAdd4BE(pReply, direct_method_count + virtual_method_count);
1281
1282 for (size_t i = 0; i < direct_method_count + virtual_method_count; ++i) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001283 mirror::AbstractMethod* m = (i < direct_method_count) ? c->GetDirectMethod(i) : c->GetVirtualMethod(i - direct_method_count);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001284 MethodHelper mh(m);
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001285 expandBufAddMethodId(pReply, ToMethodId(m));
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001286 expandBufAddUtf8String(pReply, mh.GetName());
Elliott Hughes4740cdf2011-12-07 14:07:12 -08001287 expandBufAddUtf8String(pReply, mh.GetSignature());
Elliott Hughesc5b734a2011-12-01 17:20:58 -08001288 if (with_generic) {
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001289 static const char genericSignature[1] = "";
1290 expandBufAddUtf8String(pReply, genericSignature);
1291 }
1292 expandBufAdd4BE(pReply, MangleAccessFlags(m->GetAccessFlags()));
1293 }
Elliott Hughes436e3722012-02-17 20:01:47 -08001294 return JDWP::ERR_NONE;
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001295}
1296
Elliott Hughes88d63092013-01-09 09:55:54 -08001297JDWP::JdwpError Dbg::OutputDeclaredInterfaces(JDWP::RefTypeId class_id, JDWP::ExpandBuf* pReply) {
Elliott Hughes436e3722012-02-17 20:01:47 -08001298 JDWP::JdwpError status;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001299 mirror::Class* c = DecodeClass(class_id, status);
Elliott Hughes436e3722012-02-17 20:01:47 -08001300 if (c == NULL) {
1301 return status;
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -08001302 }
Elliott Hughes436e3722012-02-17 20:01:47 -08001303
1304 ClassHelper kh(c);
Ian Rogersd24e2642012-06-06 21:21:43 -07001305 size_t interface_count = kh.NumDirectInterfaces();
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001306 expandBufAdd4BE(pReply, interface_count);
1307 for (size_t i = 0; i < interface_count; ++i) {
Elliott Hughes64f574f2013-02-20 14:57:12 -08001308 expandBufAddRefTypeId(pReply, gRegistry->AddRefType(kh.GetDirectInterface(i)));
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001309 }
Elliott Hughes436e3722012-02-17 20:01:47 -08001310 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001311}
1312
Elliott Hughes88d63092013-01-09 09:55:54 -08001313void Dbg::OutputLineTable(JDWP::RefTypeId, JDWP::MethodId method_id, JDWP::ExpandBuf* pReply)
Ian Rogersb726dcb2012-09-05 08:57:23 -07001314 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Elliott Hughes03181a82011-11-17 17:22:21 -08001315 struct DebugCallbackContext {
1316 int numItems;
1317 JDWP::ExpandBuf* pReply;
1318
Elliott Hughes2435a572012-02-17 16:07:41 -08001319 static bool Callback(void* context, uint32_t address, uint32_t line_number) {
Elliott Hughes03181a82011-11-17 17:22:21 -08001320 DebugCallbackContext* pContext = reinterpret_cast<DebugCallbackContext*>(context);
1321 expandBufAdd8BE(pContext->pReply, address);
Elliott Hughes2435a572012-02-17 16:07:41 -08001322 expandBufAdd4BE(pContext->pReply, line_number);
Elliott Hughes03181a82011-11-17 17:22:21 -08001323 pContext->numItems++;
1324 return true;
1325 }
1326 };
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001327 mirror::AbstractMethod* m = FromMethodId(method_id);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001328 MethodHelper mh(m);
Elliott Hughes03181a82011-11-17 17:22:21 -08001329 uint64_t start, end;
1330 if (m->IsNative()) {
1331 start = -1;
1332 end = -1;
1333 } else {
1334 start = 0;
jeffhao14f0db92012-12-14 17:50:42 -08001335 // Return the index of the last instruction
1336 end = mh.GetCodeItem()->insns_size_in_code_units_ - 1;
Elliott Hughes03181a82011-11-17 17:22:21 -08001337 }
1338
1339 expandBufAdd8BE(pReply, start);
1340 expandBufAdd8BE(pReply, end);
1341
1342 // Add numLines later
1343 size_t numLinesOffset = expandBufGetLength(pReply);
1344 expandBufAdd4BE(pReply, 0);
1345
1346 DebugCallbackContext context;
1347 context.numItems = 0;
1348 context.pReply = pReply;
1349
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001350 mh.GetDexFile().DecodeDebugInfo(mh.GetCodeItem(), m->IsStatic(), m->GetDexMethodIndex(),
1351 DebugCallbackContext::Callback, NULL, &context);
Elliott Hughes03181a82011-11-17 17:22:21 -08001352
1353 JDWP::Set4BE(expandBufGetBuffer(pReply) + numLinesOffset, context.numItems);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001354}
1355
Elliott Hughes88d63092013-01-09 09:55:54 -08001356void Dbg::OutputVariableTable(JDWP::RefTypeId, JDWP::MethodId method_id, bool with_generic, JDWP::ExpandBuf* pReply) {
Elliott Hughesdbb40792011-11-18 17:05:22 -08001357 struct DebugCallbackContext {
Elliott Hughesdbb40792011-11-18 17:05:22 -08001358 JDWP::ExpandBuf* pReply;
Elliott Hughesc5b734a2011-12-01 17:20:58 -08001359 size_t variable_count;
1360 bool with_generic;
Elliott Hughesdbb40792011-11-18 17:05:22 -08001361
Elliott Hughesc5b734a2011-12-01 17:20:58 -08001362 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 -08001363 DebugCallbackContext* pContext = reinterpret_cast<DebugCallbackContext*>(context);
1364
Elliott Hughesad3da692012-02-24 16:51:35 -08001365 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 -08001366
Elliott Hughes68fdbd02011-11-29 19:22:47 -08001367 slot = MangleSlot(slot, name);
1368
Elliott Hughesdbb40792011-11-18 17:05:22 -08001369 expandBufAdd8BE(pContext->pReply, startAddress);
1370 expandBufAddUtf8String(pContext->pReply, name);
1371 expandBufAddUtf8String(pContext->pReply, descriptor);
Elliott Hughesc5b734a2011-12-01 17:20:58 -08001372 if (pContext->with_generic) {
Elliott Hughesdbb40792011-11-18 17:05:22 -08001373 expandBufAddUtf8String(pContext->pReply, signature);
1374 }
1375 expandBufAdd4BE(pContext->pReply, endAddress - startAddress);
1376 expandBufAdd4BE(pContext->pReply, slot);
1377
Elliott Hughesc5b734a2011-12-01 17:20:58 -08001378 ++pContext->variable_count;
Elliott Hughesdbb40792011-11-18 17:05:22 -08001379 }
1380 };
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001381 mirror::AbstractMethod* m = FromMethodId(method_id);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001382 MethodHelper mh(m);
1383 const DexFile::CodeItem* code_item = mh.GetCodeItem();
Elliott Hughesdbb40792011-11-18 17:05:22 -08001384
Elliott Hughesc5b734a2011-12-01 17:20:58 -08001385 // arg_count considers doubles and longs to take 2 units.
1386 // variable_count considers everything to take 1 unit.
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001387 std::string shorty(mh.GetShorty());
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001388 expandBufAdd4BE(pReply, mirror::AbstractMethod::NumArgRegisters(shorty));
Elliott Hughesdbb40792011-11-18 17:05:22 -08001389
Elliott Hughesc5b734a2011-12-01 17:20:58 -08001390 // We don't know the total number of variables yet, so leave a blank and update it later.
1391 size_t variable_count_offset = expandBufGetLength(pReply);
Elliott Hughesdbb40792011-11-18 17:05:22 -08001392 expandBufAdd4BE(pReply, 0);
1393
1394 DebugCallbackContext context;
Elliott Hughesdbb40792011-11-18 17:05:22 -08001395 context.pReply = pReply;
Elliott Hughesc5b734a2011-12-01 17:20:58 -08001396 context.variable_count = 0;
1397 context.with_generic = with_generic;
Elliott Hughesdbb40792011-11-18 17:05:22 -08001398
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001399 mh.GetDexFile().DecodeDebugInfo(code_item, m->IsStatic(), m->GetDexMethodIndex(), NULL,
1400 DebugCallbackContext::Callback, &context);
Elliott Hughesdbb40792011-11-18 17:05:22 -08001401
Elliott Hughesc5b734a2011-12-01 17:20:58 -08001402 JDWP::Set4BE(expandBufGetBuffer(pReply) + variable_count_offset, context.variable_count);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001403}
1404
Elliott Hughes9777ba22013-01-17 09:04:19 -08001405JDWP::JdwpError Dbg::GetBytecodes(JDWP::RefTypeId, JDWP::MethodId method_id,
1406 std::vector<uint8_t>& bytecodes)
1407 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001408 mirror::AbstractMethod* m = FromMethodId(method_id);
Elliott Hughes9777ba22013-01-17 09:04:19 -08001409 if (m == NULL) {
1410 return JDWP::ERR_INVALID_METHODID;
1411 }
1412 MethodHelper mh(m);
1413 const DexFile::CodeItem* code_item = mh.GetCodeItem();
1414 size_t byte_count = code_item->insns_size_in_code_units_ * 2;
1415 const uint8_t* begin = reinterpret_cast<const uint8_t*>(code_item->insns_);
1416 const uint8_t* end = begin + byte_count;
1417 for (const uint8_t* p = begin; p != end; ++p) {
1418 bytecodes.push_back(*p);
1419 }
1420 return JDWP::ERR_NONE;
1421}
1422
Elliott Hughes88d63092013-01-09 09:55:54 -08001423JDWP::JdwpTag Dbg::GetFieldBasicTag(JDWP::FieldId field_id) {
1424 return BasicTagFromDescriptor(FieldHelper(FromFieldId(field_id)).GetTypeDescriptor());
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001425}
1426
Elliott Hughes88d63092013-01-09 09:55:54 -08001427JDWP::JdwpTag Dbg::GetStaticFieldBasicTag(JDWP::FieldId field_id) {
1428 return BasicTagFromDescriptor(FieldHelper(FromFieldId(field_id)).GetTypeDescriptor());
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001429}
1430
Elliott Hughes88d63092013-01-09 09:55:54 -08001431static JDWP::JdwpError GetFieldValueImpl(JDWP::RefTypeId ref_type_id, JDWP::ObjectId object_id,
1432 JDWP::FieldId field_id, JDWP::ExpandBuf* pReply,
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001433 bool is_static)
Ian Rogersb726dcb2012-09-05 08:57:23 -07001434 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Elliott Hughes0cf74332012-02-23 23:14:00 -08001435 JDWP::JdwpError status;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001436 mirror::Class* c = DecodeClass(ref_type_id, status);
Elliott Hughes88d63092013-01-09 09:55:54 -08001437 if (ref_type_id != 0 && c == NULL) {
Elliott Hughes0cf74332012-02-23 23:14:00 -08001438 return status;
1439 }
1440
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001441 mirror::Object* o = gRegistry->Get<mirror::Object*>(object_id);
Elliott Hughes64f574f2013-02-20 14:57:12 -08001442 if ((!is_static && o == NULL) || o == ObjectRegistry::kInvalidObject) {
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08001443 return JDWP::ERR_INVALID_OBJECT;
1444 }
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001445 mirror::Field* f = FromFieldId(field_id);
Elliott Hughes0cf74332012-02-23 23:14:00 -08001446
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001447 mirror::Class* receiver_class = c;
Elliott Hughes0cf74332012-02-23 23:14:00 -08001448 if (receiver_class == NULL && o != NULL) {
1449 receiver_class = o->GetClass();
1450 }
1451 // TODO: should we give up now if receiver_class is NULL?
1452 if (receiver_class != NULL && !f->GetDeclaringClass()->IsAssignableFrom(receiver_class)) {
1453 LOG(INFO) << "ERR_INVALID_FIELDID: " << PrettyField(f) << " " << PrettyClass(receiver_class);
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08001454 return JDWP::ERR_INVALID_FIELDID;
1455 }
Elliott Hughesaed4be92011-12-02 16:16:23 -08001456
Elliott Hughes0cf74332012-02-23 23:14:00 -08001457 // The RI only enforces the static/non-static mismatch in one direction.
1458 // TODO: should we change the tests and check both?
1459 if (is_static) {
1460 if (!f->IsStatic()) {
1461 return JDWP::ERR_INVALID_FIELDID;
1462 }
1463 } else {
1464 if (f->IsStatic()) {
1465 LOG(WARNING) << "Ignoring non-NULL receiver for ObjectReference.SetValues on static field " << PrettyField(f);
Elliott Hughes0cf74332012-02-23 23:14:00 -08001466 }
1467 }
jeffhao0dfbb7e2012-11-28 15:26:03 -08001468 if (f->IsStatic()) {
1469 o = f->GetDeclaringClass();
1470 }
Elliott Hughes0cf74332012-02-23 23:14:00 -08001471
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001472 JDWP::JdwpTag tag = BasicTagFromDescriptor(FieldHelper(f).GetTypeDescriptor());
Elliott Hughesaed4be92011-12-02 16:16:23 -08001473
1474 if (IsPrimitiveTag(tag)) {
1475 expandBufAdd1(pReply, tag);
1476 if (tag == JDWP::JT_BOOLEAN || tag == JDWP::JT_BYTE) {
1477 expandBufAdd1(pReply, f->Get32(o));
1478 } else if (tag == JDWP::JT_CHAR || tag == JDWP::JT_SHORT) {
1479 expandBufAdd2BE(pReply, f->Get32(o));
1480 } else if (tag == JDWP::JT_FLOAT || tag == JDWP::JT_INT) {
1481 expandBufAdd4BE(pReply, f->Get32(o));
1482 } else if (tag == JDWP::JT_DOUBLE || tag == JDWP::JT_LONG) {
1483 expandBufAdd8BE(pReply, f->Get64(o));
1484 } else {
Elliott Hughes3d30d9b2011-12-07 17:35:48 -08001485 LOG(FATAL) << "Unknown tag: " << tag;
Elliott Hughesaed4be92011-12-02 16:16:23 -08001486 }
1487 } else {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001488 mirror::Object* value = f->GetObject(o);
Elliott Hughesaed4be92011-12-02 16:16:23 -08001489 expandBufAdd1(pReply, TagFromObject(value));
1490 expandBufAddObjectId(pReply, gRegistry->Add(value));
1491 }
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08001492 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001493}
1494
Elliott Hughes88d63092013-01-09 09:55:54 -08001495JDWP::JdwpError Dbg::GetFieldValue(JDWP::ObjectId object_id, JDWP::FieldId field_id,
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001496 JDWP::ExpandBuf* pReply) {
Elliott Hughes88d63092013-01-09 09:55:54 -08001497 return GetFieldValueImpl(0, object_id, field_id, pReply, false);
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08001498}
1499
Elliott Hughes88d63092013-01-09 09:55:54 -08001500JDWP::JdwpError Dbg::GetStaticFieldValue(JDWP::RefTypeId ref_type_id, JDWP::FieldId field_id, JDWP::ExpandBuf* pReply) {
1501 return GetFieldValueImpl(ref_type_id, 0, field_id, pReply, true);
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08001502}
1503
Elliott Hughes88d63092013-01-09 09:55:54 -08001504static JDWP::JdwpError SetFieldValueImpl(JDWP::ObjectId object_id, JDWP::FieldId field_id,
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001505 uint64_t value, int width, bool is_static)
Ian Rogersb726dcb2012-09-05 08:57:23 -07001506 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001507 mirror::Object* o = gRegistry->Get<mirror::Object*>(object_id);
Elliott Hughes64f574f2013-02-20 14:57:12 -08001508 if ((!is_static && o == NULL) || o == ObjectRegistry::kInvalidObject) {
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08001509 return JDWP::ERR_INVALID_OBJECT;
1510 }
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001511 mirror::Field* f = FromFieldId(field_id);
Elliott Hughes0cf74332012-02-23 23:14:00 -08001512
1513 // The RI only enforces the static/non-static mismatch in one direction.
1514 // TODO: should we change the tests and check both?
1515 if (is_static) {
1516 if (!f->IsStatic()) {
1517 return JDWP::ERR_INVALID_FIELDID;
1518 }
1519 } else {
1520 if (f->IsStatic()) {
1521 LOG(WARNING) << "Ignoring non-NULL receiver for ObjectReference.SetValues on static field " << PrettyField(f);
Elliott Hughes0cf74332012-02-23 23:14:00 -08001522 }
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08001523 }
jeffhao0dfbb7e2012-11-28 15:26:03 -08001524 if (f->IsStatic()) {
1525 o = f->GetDeclaringClass();
1526 }
Elliott Hughesaed4be92011-12-02 16:16:23 -08001527
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001528 JDWP::JdwpTag tag = BasicTagFromDescriptor(FieldHelper(f).GetTypeDescriptor());
Elliott Hughesaed4be92011-12-02 16:16:23 -08001529
1530 if (IsPrimitiveTag(tag)) {
1531 if (tag == JDWP::JT_DOUBLE || tag == JDWP::JT_LONG) {
Elliott Hughes1bac54f2012-03-16 12:48:31 -07001532 CHECK_EQ(width, 8);
Elliott Hughesaed4be92011-12-02 16:16:23 -08001533 f->Set64(o, value);
1534 } else {
Elliott Hughes1bac54f2012-03-16 12:48:31 -07001535 CHECK_LE(width, 4);
Elliott Hughesaed4be92011-12-02 16:16:23 -08001536 f->Set32(o, value);
1537 }
1538 } else {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001539 mirror::Object* v = gRegistry->Get<mirror::Object*>(value);
Elliott Hughes64f574f2013-02-20 14:57:12 -08001540 if (v == ObjectRegistry::kInvalidObject) {
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -08001541 return JDWP::ERR_INVALID_OBJECT;
1542 }
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08001543 if (v != NULL) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001544 mirror::Class* field_type = FieldHelper(f).GetType();
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08001545 if (!field_type->IsAssignableFrom(v->GetClass())) {
1546 return JDWP::ERR_INVALID_OBJECT;
1547 }
1548 }
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -08001549 f->SetObject(o, v);
Elliott Hughesaed4be92011-12-02 16:16:23 -08001550 }
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -08001551
1552 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001553}
1554
Elliott Hughes88d63092013-01-09 09:55:54 -08001555JDWP::JdwpError Dbg::SetFieldValue(JDWP::ObjectId object_id, JDWP::FieldId field_id, uint64_t value,
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001556 int width) {
Elliott Hughes88d63092013-01-09 09:55:54 -08001557 return SetFieldValueImpl(object_id, field_id, value, width, false);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001558}
1559
Elliott Hughes88d63092013-01-09 09:55:54 -08001560JDWP::JdwpError Dbg::SetStaticFieldValue(JDWP::FieldId field_id, uint64_t value, int width) {
1561 return SetFieldValueImpl(0, field_id, value, width, true);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001562}
1563
Elliott Hughes88d63092013-01-09 09:55:54 -08001564std::string Dbg::StringToUtf8(JDWP::ObjectId string_id) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001565 mirror::String* s = gRegistry->Get<mirror::String*>(string_id);
Elliott Hughes68fdbd02011-11-29 19:22:47 -08001566 return s->ToModifiedUtf8();
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001567}
1568
Elliott Hughes221229c2013-01-08 18:17:50 -08001569JDWP::JdwpError Dbg::GetThreadName(JDWP::ObjectId thread_id, std::string& name) {
jeffhaoa77f0f62012-12-05 17:19:31 -08001570 ScopedObjectAccessUnchecked soa(Thread::Current());
1571 MutexLock mu(soa.Self(), *Locks::thread_list_lock_);
Elliott Hughes221229c2013-01-08 18:17:50 -08001572 Thread* thread;
1573 JDWP::JdwpError error = DecodeThread(soa, thread_id, thread);
1574 if (error != JDWP::ERR_NONE && error != JDWP::ERR_THREAD_NOT_ALIVE) {
1575 return error;
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001576 }
Elliott Hughes221229c2013-01-08 18:17:50 -08001577
1578 // We still need to report the zombie threads' names, so we can't just call Thread::GetThreadName.
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001579 mirror::Object* thread_object = gRegistry->Get<mirror::Object*>(thread_id);
1580 mirror::Field* java_lang_Thread_name_field =
1581 soa.DecodeField(WellKnownClasses::java_lang_Thread_name);
1582 mirror::String* s =
1583 reinterpret_cast<mirror::String*>(java_lang_Thread_name_field->GetObject(thread_object));
Elliott Hughes221229c2013-01-08 18:17:50 -08001584 if (s != NULL) {
1585 name = s->ToModifiedUtf8();
1586 }
1587 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001588}
1589
Elliott Hughes221229c2013-01-08 18:17:50 -08001590JDWP::JdwpError Dbg::GetThreadGroup(JDWP::ObjectId thread_id, JDWP::ExpandBuf* pReply) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001591 ScopedObjectAccess soa(Thread::Current());
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001592 mirror::Object* thread_object = gRegistry->Get<mirror::Object*>(thread_id);
Elliott Hughes64f574f2013-02-20 14:57:12 -08001593 if (thread_object == ObjectRegistry::kInvalidObject) {
Elliott Hughes2435a572012-02-17 16:07:41 -08001594 return JDWP::ERR_INVALID_OBJECT;
1595 }
1596
1597 // Okay, so it's an object, but is it actually a thread?
Ian Rogers50b35e22012-10-04 10:09:15 -07001598 MutexLock mu(soa.Self(), *Locks::thread_list_lock_);
Elliott Hughes221229c2013-01-08 18:17:50 -08001599 Thread* thread;
1600 JDWP::JdwpError error = DecodeThread(soa, thread_id, thread);
1601 if (error == JDWP::ERR_THREAD_NOT_ALIVE) {
1602 // Zombie threads are in the null group.
1603 expandBufAddObjectId(pReply, JDWP::ObjectId(0));
1604 return JDWP::ERR_NONE;
1605 }
1606 if (error != JDWP::ERR_NONE) {
1607 return error;
Elliott Hughes2435a572012-02-17 16:07:41 -08001608 }
Elliott Hughes499c5132011-11-17 14:55:11 -08001609
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001610 mirror::Class* c = Runtime::Current()->GetClassLinker()->FindSystemClass("Ljava/lang/Thread;");
Elliott Hughes499c5132011-11-17 14:55:11 -08001611 CHECK(c != NULL);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001612 mirror::Field* f = c->FindInstanceField("group", "Ljava/lang/ThreadGroup;");
Elliott Hughes499c5132011-11-17 14:55:11 -08001613 CHECK(f != NULL);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001614 mirror::Object* group = f->GetObject(thread_object);
Elliott Hughes499c5132011-11-17 14:55:11 -08001615 CHECK(group != NULL);
Elliott Hughes2435a572012-02-17 16:07:41 -08001616 JDWP::ObjectId thread_group_id = gRegistry->Add(group);
1617
1618 expandBufAddObjectId(pReply, thread_group_id);
1619 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001620}
1621
Elliott Hughes88d63092013-01-09 09:55:54 -08001622std::string Dbg::GetThreadGroupName(JDWP::ObjectId thread_group_id) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001623 ScopedObjectAccess soa(Thread::Current());
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001624 mirror::Object* thread_group = gRegistry->Get<mirror::Object*>(thread_group_id);
Elliott Hughes499c5132011-11-17 14:55:11 -08001625 CHECK(thread_group != NULL);
1626
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001627 mirror::Class* c = Runtime::Current()->GetClassLinker()->FindSystemClass("Ljava/lang/ThreadGroup;");
Elliott Hughes499c5132011-11-17 14:55:11 -08001628 CHECK(c != NULL);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001629 mirror::Field* f = c->FindInstanceField("name", "Ljava/lang/String;");
Elliott Hughes499c5132011-11-17 14:55:11 -08001630 CHECK(f != NULL);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001631 mirror::String* s = reinterpret_cast<mirror::String*>(f->GetObject(thread_group));
Elliott Hughes499c5132011-11-17 14:55:11 -08001632 return s->ToModifiedUtf8();
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001633}
1634
Elliott Hughes88d63092013-01-09 09:55:54 -08001635JDWP::ObjectId Dbg::GetThreadGroupParent(JDWP::ObjectId thread_group_id) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001636 mirror::Object* thread_group = gRegistry->Get<mirror::Object*>(thread_group_id);
Elliott Hughes4e235312011-12-02 11:34:15 -08001637 CHECK(thread_group != NULL);
1638
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001639 mirror::Class* c = Runtime::Current()->GetClassLinker()->FindSystemClass("Ljava/lang/ThreadGroup;");
Elliott Hughes4e235312011-12-02 11:34:15 -08001640 CHECK(c != NULL);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001641 mirror::Field* f = c->FindInstanceField("parent", "Ljava/lang/ThreadGroup;");
Elliott Hughes4e235312011-12-02 11:34:15 -08001642 CHECK(f != NULL);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001643 mirror::Object* parent = f->GetObject(thread_group);
Elliott Hughes4e235312011-12-02 11:34:15 -08001644 return gRegistry->Add(parent);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001645}
1646
1647JDWP::ObjectId Dbg::GetSystemThreadGroupId() {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001648 ScopedObjectAccessUnchecked soa(Thread::Current());
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001649 mirror::Field* f = soa.DecodeField(WellKnownClasses::java_lang_ThreadGroup_systemThreadGroup);
1650 mirror::Object* group = f->GetObject(f->GetDeclaringClass());
Ian Rogers365c1022012-06-22 15:05:28 -07001651 return gRegistry->Add(group);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001652}
1653
1654JDWP::ObjectId Dbg::GetMainThreadGroupId() {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001655 ScopedObjectAccess soa(Thread::Current());
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001656 mirror::Field* f = soa.DecodeField(WellKnownClasses::java_lang_ThreadGroup_mainThreadGroup);
1657 mirror::Object* group = f->GetObject(f->GetDeclaringClass());
Ian Rogers365c1022012-06-22 15:05:28 -07001658 return gRegistry->Add(group);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001659}
1660
Elliott Hughes221229c2013-01-08 18:17:50 -08001661JDWP::JdwpError Dbg::GetThreadStatus(JDWP::ObjectId thread_id, JDWP::JdwpThreadStatus* pThreadStatus, JDWP::JdwpSuspendStatus* pSuspendStatus) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001662 ScopedObjectAccess soa(Thread::Current());
Elliott Hughes499c5132011-11-17 14:55:11 -08001663
Elliott Hughes9e0c1752013-01-09 14:02:58 -08001664 *pSuspendStatus = JDWP::SUSPEND_STATUS_NOT_SUSPENDED;
1665
Ian Rogers50b35e22012-10-04 10:09:15 -07001666 MutexLock mu(soa.Self(), *Locks::thread_list_lock_);
Elliott Hughes221229c2013-01-08 18:17:50 -08001667 Thread* thread;
1668 JDWP::JdwpError error = DecodeThread(soa, thread_id, thread);
1669 if (error != JDWP::ERR_NONE) {
1670 if (error == JDWP::ERR_THREAD_NOT_ALIVE) {
1671 *pThreadStatus = JDWP::TS_ZOMBIE;
Elliott Hughes221229c2013-01-08 18:17:50 -08001672 return JDWP::ERR_NONE;
1673 }
1674 return error;
Elliott Hughes499c5132011-11-17 14:55:11 -08001675 }
1676
Elliott Hughes9e0c1752013-01-09 14:02:58 -08001677 if (IsSuspendedForDebugger(soa, thread)) {
1678 *pSuspendStatus = JDWP::SUSPEND_STATUS_SUSPENDED;
Elliott Hughes499c5132011-11-17 14:55:11 -08001679 }
1680
Elliott Hughes9e0c1752013-01-09 14:02:58 -08001681 switch (thread->GetState()) {
1682 case kBlocked: *pThreadStatus = JDWP::TS_MONITOR; break;
1683 case kNative: *pThreadStatus = JDWP::TS_RUNNING; break;
1684 case kRunnable: *pThreadStatus = JDWP::TS_RUNNING; break;
1685 case kSleeping: *pThreadStatus = JDWP::TS_SLEEPING; break;
1686 case kStarting: *pThreadStatus = JDWP::TS_ZOMBIE; break;
1687 case kSuspended: *pThreadStatus = JDWP::TS_RUNNING; break;
1688 case kTerminated: *pThreadStatus = JDWP::TS_ZOMBIE; break;
1689 case kTimedWaiting: *pThreadStatus = JDWP::TS_WAIT; break;
1690 case kWaitingForDebuggerSend: *pThreadStatus = JDWP::TS_WAIT; break;
1691 case kWaitingForDebuggerSuspension: *pThreadStatus = JDWP::TS_WAIT; break;
1692 case kWaitingForDebuggerToAttach: *pThreadStatus = JDWP::TS_WAIT; break;
1693 case kWaitingForGcToComplete: *pThreadStatus = JDWP::TS_WAIT; break;
Ian Rogers1d54e732013-05-02 21:10:01 -07001694 case kWaitingForCheckPointsToRun: *pThreadStatus = JDWP::TS_WAIT; break;
Elliott Hughes9e0c1752013-01-09 14:02:58 -08001695 case kWaitingForJniOnLoad: *pThreadStatus = JDWP::TS_WAIT; break;
1696 case kWaitingForSignalCatcherOutput: *pThreadStatus = JDWP::TS_WAIT; break;
1697 case kWaitingInMainDebuggerLoop: *pThreadStatus = JDWP::TS_WAIT; break;
1698 case kWaitingInMainSignalCatcherLoop: *pThreadStatus = JDWP::TS_WAIT; break;
1699 case kWaitingPerformingGc: *pThreadStatus = JDWP::TS_WAIT; break;
1700 case kWaiting: *pThreadStatus = JDWP::TS_WAIT; break;
1701 // Don't add a 'default' here so the compiler can spot incompatible enum changes.
1702 }
Elliott Hughes221229c2013-01-08 18:17:50 -08001703 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001704}
1705
Elliott Hughes221229c2013-01-08 18:17:50 -08001706JDWP::JdwpError Dbg::GetThreadDebugSuspendCount(JDWP::ObjectId thread_id, JDWP::ExpandBuf* pReply) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001707 ScopedObjectAccess soa(Thread::Current());
Ian Rogers50b35e22012-10-04 10:09:15 -07001708 MutexLock mu(soa.Self(), *Locks::thread_list_lock_);
Elliott Hughes221229c2013-01-08 18:17:50 -08001709 Thread* thread;
1710 JDWP::JdwpError error = DecodeThread(soa, thread_id, thread);
1711 if (error != JDWP::ERR_NONE) {
1712 return error;
Elliott Hughes2435a572012-02-17 16:07:41 -08001713 }
Ian Rogers50b35e22012-10-04 10:09:15 -07001714 MutexLock mu2(soa.Self(), *Locks::thread_suspend_count_lock_);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001715 expandBufAdd4BE(pReply, thread->GetDebugSuspendCount());
Elliott Hughes2435a572012-02-17 16:07:41 -08001716 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001717}
1718
Elliott Hughesf9501702013-01-11 11:22:27 -08001719JDWP::JdwpError Dbg::Interrupt(JDWP::ObjectId thread_id) {
1720 ScopedObjectAccess soa(Thread::Current());
1721 MutexLock mu(soa.Self(), *Locks::thread_list_lock_);
1722 Thread* thread;
1723 JDWP::JdwpError error = DecodeThread(soa, thread_id, thread);
1724 if (error != JDWP::ERR_NONE) {
1725 return error;
1726 }
1727 thread->Interrupt();
1728 return JDWP::ERR_NONE;
1729}
1730
Elliott Hughescaf76542012-06-28 16:08:22 -07001731void Dbg::GetThreads(JDWP::ObjectId thread_group_id, std::vector<JDWP::ObjectId>& thread_ids) {
Ian Rogers365c1022012-06-22 15:05:28 -07001732 class ThreadListVisitor {
1733 public:
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001734 ThreadListVisitor(const ScopedObjectAccessUnchecked& soa, mirror::Object* desired_thread_group,
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001735 std::vector<JDWP::ObjectId>& thread_ids)
Ian Rogersb726dcb2012-09-05 08:57:23 -07001736 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_)
jeffhao0dfbb7e2012-11-28 15:26:03 -08001737 : soa_(soa), desired_thread_group_(desired_thread_group), thread_ids_(thread_ids) {}
Ian Rogers365c1022012-06-22 15:05:28 -07001738
Elliott Hughesa2155262011-11-16 16:26:58 -08001739 static void Visit(Thread* t, void* arg) {
1740 reinterpret_cast<ThreadListVisitor*>(arg)->Visit(t);
1741 }
1742
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001743 // TODO: Enable annotalysis. We know lock is held in constructor, but abstraction confuses
1744 // annotalysis.
1745 void Visit(Thread* t) NO_THREAD_SAFETY_ANALYSIS {
Elliott Hughesa2155262011-11-16 16:26:58 -08001746 if (t == Dbg::GetDebugThread()) {
1747 // Skip the JDWP thread. Some debuggers get bent out of shape when they can't suspend and
1748 // query all threads, so it's easier if we just don't tell them about this thread.
1749 return;
1750 }
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001751 mirror::Object* peer = t->GetPeer();
jeffhao0dfbb7e2012-11-28 15:26:03 -08001752 if (IsInDesiredThreadGroup(peer)) {
Ian Rogers120f1c72012-09-28 17:17:10 -07001753 thread_ids_.push_back(gRegistry->Add(peer));
Elliott Hughesa2155262011-11-16 16:26:58 -08001754 }
1755 }
1756
Ian Rogers365c1022012-06-22 15:05:28 -07001757 private:
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001758 bool IsInDesiredThreadGroup(mirror::Object* peer)
jeffhao0dfbb7e2012-11-28 15:26:03 -08001759 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
jeffhao0dfbb7e2012-11-28 15:26:03 -08001760 // peer might be NULL if the thread is still starting up.
1761 if (peer == NULL) {
1762 // We can't tell the debugger about this thread yet.
1763 // TODO: if we identified threads to the debugger by their Thread*
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001764 // rather than their peer's mirror::Object*, we could fix this.
jeffhao0dfbb7e2012-11-28 15:26:03 -08001765 // Doing so might help us report ZOMBIE threads too.
1766 return false;
1767 }
jeffhaoc1e04902012-12-13 12:41:10 -08001768 // Do we want threads from all thread groups?
1769 if (desired_thread_group_ == NULL) {
1770 return true;
1771 }
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001772 mirror::Object* group = soa_.DecodeField(WellKnownClasses::java_lang_Thread_group)->GetObject(peer);
jeffhao0dfbb7e2012-11-28 15:26:03 -08001773 return (group == desired_thread_group_);
1774 }
1775
Mathieu Chartierdbe6f462012-09-25 16:54:50 -07001776 const ScopedObjectAccessUnchecked& soa_;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001777 mirror::Object* const desired_thread_group_;
Elliott Hughescaf76542012-06-28 16:08:22 -07001778 std::vector<JDWP::ObjectId>& thread_ids_;
Elliott Hughesa2155262011-11-16 16:26:58 -08001779 };
1780
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001781 ScopedObjectAccessUnchecked soa(Thread::Current());
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001782 mirror::Object* thread_group = gRegistry->Get<mirror::Object*>(thread_group_id);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001783 ThreadListVisitor tlv(soa, thread_group, thread_ids);
Ian Rogers50b35e22012-10-04 10:09:15 -07001784 MutexLock mu(soa.Self(), *Locks::thread_list_lock_);
Elliott Hughesf8349362012-06-18 15:00:06 -07001785 Runtime::Current()->GetThreadList()->ForEach(ThreadListVisitor::Visit, &tlv);
Elliott Hughescaf76542012-06-28 16:08:22 -07001786}
Elliott Hughesa2155262011-11-16 16:26:58 -08001787
Elliott Hughescaf76542012-06-28 16:08:22 -07001788void Dbg::GetChildThreadGroups(JDWP::ObjectId thread_group_id, std::vector<JDWP::ObjectId>& child_thread_group_ids) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001789 ScopedObjectAccess soa(Thread::Current());
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001790 mirror::Object* thread_group = gRegistry->Get<mirror::Object*>(thread_group_id);
Elliott Hughescaf76542012-06-28 16:08:22 -07001791
1792 // Get the ArrayList<ThreadGroup> "groups" out of this thread group...
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001793 mirror::Field* groups_field = thread_group->GetClass()->FindInstanceField("groups", "Ljava/util/List;");
1794 mirror::Object* groups_array_list = groups_field->GetObject(thread_group);
Elliott Hughescaf76542012-06-28 16:08:22 -07001795
1796 // Get the array and size out of the ArrayList<ThreadGroup>...
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001797 mirror::Field* array_field = groups_array_list->GetClass()->FindInstanceField("array", "[Ljava/lang/Object;");
1798 mirror::Field* size_field = groups_array_list->GetClass()->FindInstanceField("size", "I");
1799 mirror::ObjectArray<mirror::Object>* groups_array =
1800 array_field->GetObject(groups_array_list)->AsObjectArray<mirror::Object>();
Elliott Hughescaf76542012-06-28 16:08:22 -07001801 const int32_t size = size_field->GetInt(groups_array_list);
1802
1803 // Copy the first 'size' elements out of the array into the result.
1804 for (int32_t i = 0; i < size; ++i) {
1805 child_thread_group_ids.push_back(gRegistry->Add(groups_array->Get(i)));
Elliott Hughesa2155262011-11-16 16:26:58 -08001806 }
1807}
1808
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001809static int GetStackDepth(Thread* thread)
Ian Rogersb726dcb2012-09-05 08:57:23 -07001810 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Ian Rogers0399dde2012-06-06 17:09:28 -07001811 struct CountStackDepthVisitor : public StackVisitor {
Ian Rogers7a22fa62013-01-23 12:16:16 -08001812 CountStackDepthVisitor(Thread* thread)
1813 : StackVisitor(thread, NULL), depth(0) {}
Ian Rogers0399dde2012-06-06 17:09:28 -07001814
Elliott Hughes64f574f2013-02-20 14:57:12 -08001815 // TODO: Enable annotalysis. We know lock is held in constructor, but abstraction confuses
1816 // annotalysis.
1817 bool VisitFrame() NO_THREAD_SAFETY_ANALYSIS {
Ian Rogers0399dde2012-06-06 17:09:28 -07001818 if (!GetMethod()->IsRuntimeMethod()) {
Elliott Hughesf8a2df72011-12-01 12:19:54 -08001819 ++depth;
1820 }
Elliott Hughes530fa002012-03-12 11:44:49 -07001821 return true;
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001822 }
1823 size_t depth;
1824 };
Elliott Hughes08fc03a2012-06-26 17:34:00 -07001825
Ian Rogers7a22fa62013-01-23 12:16:16 -08001826 CountStackDepthVisitor visitor(thread);
Ian Rogers0399dde2012-06-06 17:09:28 -07001827 visitor.WalkStack();
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001828 return visitor.depth;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001829}
1830
Elliott Hughes221229c2013-01-08 18:17:50 -08001831JDWP::JdwpError Dbg::GetThreadFrameCount(JDWP::ObjectId thread_id, size_t& result) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001832 ScopedObjectAccess soa(Thread::Current());
jeffhaoa77f0f62012-12-05 17:19:31 -08001833 MutexLock mu(soa.Self(), *Locks::thread_list_lock_);
Elliott Hughes221229c2013-01-08 18:17:50 -08001834 Thread* thread;
1835 JDWP::JdwpError error = DecodeThread(soa, thread_id, thread);
1836 if (error != JDWP::ERR_NONE) {
1837 return error;
1838 }
Elliott Hughesf15f4a02013-01-09 10:09:38 -08001839 if (!IsSuspendedForDebugger(soa, thread)) {
1840 return JDWP::ERR_THREAD_NOT_SUSPENDED;
1841 }
Elliott Hughes221229c2013-01-08 18:17:50 -08001842 result = GetStackDepth(thread);
1843 return JDWP::ERR_NONE;
Elliott Hughes86964332012-02-15 19:37:42 -08001844}
1845
Ian Rogers306057f2012-11-26 12:45:53 -08001846JDWP::JdwpError Dbg::GetThreadFrames(JDWP::ObjectId thread_id, size_t start_frame,
1847 size_t frame_count, JDWP::ExpandBuf* buf) {
Elliott Hughes6e9d22c2012-06-22 15:02:37 -07001848 class GetFrameVisitor : public StackVisitor {
1849 public:
Ian Rogers7a22fa62013-01-23 12:16:16 -08001850 GetFrameVisitor(Thread* thread, size_t start_frame, size_t frame_count, JDWP::ExpandBuf* buf)
Ian Rogersb726dcb2012-09-05 08:57:23 -07001851 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_)
Ian Rogers7a22fa62013-01-23 12:16:16 -08001852 : StackVisitor(thread, NULL), depth_(0),
Elliott Hughes6e9d22c2012-06-22 15:02:37 -07001853 start_frame_(start_frame), frame_count_(frame_count), buf_(buf) {
1854 expandBufAdd4BE(buf_, frame_count_);
Elliott Hughes03181a82011-11-17 17:22:21 -08001855 }
Ian Rogers0399dde2012-06-06 17:09:28 -07001856
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001857 // TODO: Enable annotalysis. We know lock is held in constructor, but abstraction confuses
1858 // annotalysis.
1859 virtual bool VisitFrame() NO_THREAD_SAFETY_ANALYSIS {
Ian Rogers0399dde2012-06-06 17:09:28 -07001860 if (GetMethod()->IsRuntimeMethod()) {
Elliott Hughes530fa002012-03-12 11:44:49 -07001861 return true; // The debugger can't do anything useful with a frame that has no Method*.
Elliott Hughes03181a82011-11-17 17:22:21 -08001862 }
Elliott Hughes6e9d22c2012-06-22 15:02:37 -07001863 if (depth_ >= start_frame_ + frame_count_) {
Elliott Hughes530fa002012-03-12 11:44:49 -07001864 return false;
Elliott Hughes03181a82011-11-17 17:22:21 -08001865 }
Elliott Hughes6e9d22c2012-06-22 15:02:37 -07001866 if (depth_ >= start_frame_) {
1867 JDWP::FrameId frame_id(GetFrameId());
1868 JDWP::JdwpLocation location;
1869 SetLocation(location, GetMethod(), GetDexPc());
Elliott Hughes7baf96f2012-06-22 16:33:50 -07001870 VLOG(jdwp) << StringPrintf(" Frame %3zd: id=%3lld ", depth_, frame_id) << location;
Elliott Hughes6e9d22c2012-06-22 15:02:37 -07001871 expandBufAdd8BE(buf_, frame_id);
1872 expandBufAddLocation(buf_, location);
1873 }
1874 ++depth_;
Elliott Hughes530fa002012-03-12 11:44:49 -07001875 return true;
Elliott Hughes03181a82011-11-17 17:22:21 -08001876 }
Elliott Hughes6e9d22c2012-06-22 15:02:37 -07001877
1878 private:
1879 size_t depth_;
1880 const size_t start_frame_;
1881 const size_t frame_count_;
1882 JDWP::ExpandBuf* buf_;
Elliott Hughes03181a82011-11-17 17:22:21 -08001883 };
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001884
1885 ScopedObjectAccessUnchecked soa(Thread::Current());
jeffhaoa77f0f62012-12-05 17:19:31 -08001886 MutexLock mu(soa.Self(), *Locks::thread_list_lock_);
Elliott Hughes221229c2013-01-08 18:17:50 -08001887 Thread* thread;
1888 JDWP::JdwpError error = DecodeThread(soa, thread_id, thread);
1889 if (error != JDWP::ERR_NONE) {
1890 return error;
1891 }
Elliott Hughesf15f4a02013-01-09 10:09:38 -08001892 if (!IsSuspendedForDebugger(soa, thread)) {
1893 return JDWP::ERR_THREAD_NOT_SUSPENDED;
1894 }
Ian Rogers7a22fa62013-01-23 12:16:16 -08001895 GetFrameVisitor visitor(thread, start_frame, frame_count, buf);
Ian Rogers0399dde2012-06-06 17:09:28 -07001896 visitor.WalkStack();
Elliott Hughes6e9d22c2012-06-22 15:02:37 -07001897 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001898}
1899
1900JDWP::ObjectId Dbg::GetThreadSelfId() {
Mathieu Chartierdbe6f462012-09-25 16:54:50 -07001901 ScopedObjectAccessUnchecked soa(Thread::Current());
Ian Rogerscfaa4552012-11-26 21:00:08 -08001902 return gRegistry->Add(soa.Self()->GetPeer());
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001903}
1904
Elliott Hughes475fc232011-10-25 15:00:35 -07001905void Dbg::SuspendVM() {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001906 Runtime::Current()->GetThreadList()->SuspendAllForDebugger();
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001907}
1908
1909void Dbg::ResumeVM() {
Elliott Hughesc61a2672012-06-21 14:52:29 -07001910 Runtime::Current()->GetThreadList()->UndoDebuggerSuspensions();
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001911}
1912
Elliott Hughes221229c2013-01-08 18:17:50 -08001913JDWP::JdwpError Dbg::SuspendThread(JDWP::ObjectId thread_id, bool request_suspension) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001914 ScopedLocalRef<jobject> peer(Thread::Current()->GetJniEnv(), NULL);
1915 {
1916 ScopedObjectAccess soa(Thread::Current());
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001917 peer.reset(soa.AddLocalReference<jobject>(gRegistry->Get<mirror::Object*>(thread_id)));
Elliott Hughes4e235312011-12-02 11:34:15 -08001918 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001919 if (peer.get() == NULL) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001920 return JDWP::ERR_THREAD_NOT_ALIVE;
1921 }
1922 // Suspend thread to build stack trace.
Elliott Hughesf327e072013-01-09 16:01:26 -08001923 bool timed_out;
1924 Thread* thread = Thread::SuspendForDebugger(peer.get(), request_suspension, &timed_out);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001925 if (thread != NULL) {
1926 return JDWP::ERR_NONE;
Elliott Hughesf327e072013-01-09 16:01:26 -08001927 } else if (timed_out) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001928 return JDWP::ERR_INTERNAL;
1929 } else {
1930 return JDWP::ERR_THREAD_NOT_ALIVE;
1931 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001932}
1933
Elliott Hughes221229c2013-01-08 18:17:50 -08001934void Dbg::ResumeThread(JDWP::ObjectId thread_id) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001935 ScopedObjectAccessUnchecked soa(Thread::Current());
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001936 mirror::Object* peer = gRegistry->Get<mirror::Object*>(thread_id);
jeffhaoa77f0f62012-12-05 17:19:31 -08001937 Thread* thread;
1938 {
1939 MutexLock mu(soa.Self(), *Locks::thread_list_lock_);
1940 thread = Thread::FromManagedThread(soa, peer);
1941 }
Elliott Hughes4e235312011-12-02 11:34:15 -08001942 if (thread == NULL) {
1943 LOG(WARNING) << "No such thread for resume: " << peer;
1944 return;
1945 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001946 bool needs_resume;
1947 {
Ian Rogers50b35e22012-10-04 10:09:15 -07001948 MutexLock mu2(soa.Self(), *Locks::thread_suspend_count_lock_);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001949 needs_resume = thread->GetSuspendCount() > 0;
1950 }
1951 if (needs_resume) {
Elliott Hughes546b9862012-06-20 16:06:13 -07001952 Runtime::Current()->GetThreadList()->Resume(thread, true);
1953 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001954}
1955
1956void Dbg::SuspendSelf() {
Elliott Hughes475fc232011-10-25 15:00:35 -07001957 Runtime::Current()->GetThreadList()->SuspendSelfForDebugger();
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001958}
1959
Ian Rogers0399dde2012-06-06 17:09:28 -07001960struct GetThisVisitor : public StackVisitor {
Ian Rogers7a22fa62013-01-23 12:16:16 -08001961 GetThisVisitor(Thread* thread, Context* context, JDWP::FrameId frame_id)
Ian Rogersb726dcb2012-09-05 08:57:23 -07001962 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_)
Ian Rogers7a22fa62013-01-23 12:16:16 -08001963 : StackVisitor(thread, context), this_object(NULL), frame_id(frame_id) {}
Ian Rogers0399dde2012-06-06 17:09:28 -07001964
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001965 // TODO: Enable annotalysis. We know lock is held in constructor, but abstraction confuses
1966 // annotalysis.
1967 virtual bool VisitFrame() NO_THREAD_SAFETY_ANALYSIS {
Elliott Hughes6e9d22c2012-06-22 15:02:37 -07001968 if (frame_id != GetFrameId()) {
Ian Rogers0399dde2012-06-06 17:09:28 -07001969 return true; // continue
Ian Rogers0399dde2012-06-06 17:09:28 -07001970 } else {
Ian Rogers62d6c772013-02-27 08:32:07 -08001971 this_object = GetThisObject();
1972 return false;
Ian Rogers0399dde2012-06-06 17:09:28 -07001973 }
Elliott Hughes86b00102011-12-05 17:54:26 -08001974 }
Ian Rogers0399dde2012-06-06 17:09:28 -07001975
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001976 mirror::Object* this_object;
Elliott Hughes6e9d22c2012-06-22 15:02:37 -07001977 JDWP::FrameId frame_id;
Ian Rogers0399dde2012-06-06 17:09:28 -07001978};
1979
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001980JDWP::JdwpError Dbg::GetThisObject(JDWP::ObjectId thread_id, JDWP::FrameId frame_id,
1981 JDWP::ObjectId* result) {
1982 ScopedObjectAccessUnchecked soa(Thread::Current());
1983 Thread* thread;
1984 {
Ian Rogers50b35e22012-10-04 10:09:15 -07001985 MutexLock mu(soa.Self(), *Locks::thread_list_lock_);
Elliott Hughes221229c2013-01-08 18:17:50 -08001986 JDWP::JdwpError error = DecodeThread(soa, thread_id, thread);
1987 if (error != JDWP::ERR_NONE) {
1988 return error;
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001989 }
Elliott Hughes9e0c1752013-01-09 14:02:58 -08001990 if (!IsSuspendedForDebugger(soa, thread)) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001991 return JDWP::ERR_THREAD_NOT_SUSPENDED;
1992 }
Elliott Hughes6e9d22c2012-06-22 15:02:37 -07001993 }
Elliott Hughescaf76542012-06-28 16:08:22 -07001994 UniquePtr<Context> context(Context::Create());
Ian Rogers7a22fa62013-01-23 12:16:16 -08001995 GetThisVisitor visitor(thread, context.get(), frame_id);
Ian Rogers0399dde2012-06-06 17:09:28 -07001996 visitor.WalkStack();
Elliott Hughes6e9d22c2012-06-22 15:02:37 -07001997 *result = gRegistry->Add(visitor.this_object);
1998 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001999}
2000
Elliott Hughes88d63092013-01-09 09:55:54 -08002001void Dbg::GetLocalValue(JDWP::ObjectId thread_id, JDWP::FrameId frame_id, int slot, JDWP::JdwpTag tag,
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002002 uint8_t* buf, size_t width) {
Ian Rogers0399dde2012-06-06 17:09:28 -07002003 struct GetLocalVisitor : public StackVisitor {
Ian Rogers7a22fa62013-01-23 12:16:16 -08002004 GetLocalVisitor(Thread* thread, Context* context, JDWP::FrameId frame_id, int slot,
2005 JDWP::JdwpTag tag, uint8_t* buf, size_t width)
Ian Rogersb726dcb2012-09-05 08:57:23 -07002006 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_)
Ian Rogers7a22fa62013-01-23 12:16:16 -08002007 : StackVisitor(thread, context), frame_id_(frame_id), slot_(slot), tag_(tag),
Ian Rogersca190662012-06-26 15:45:57 -07002008 buf_(buf), width_(width) {}
2009
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002010 // TODO: Enable annotalysis. We know lock is held in constructor, but abstraction confuses
2011 // annotalysis.
2012 bool VisitFrame() NO_THREAD_SAFETY_ANALYSIS {
Ian Rogers0399dde2012-06-06 17:09:28 -07002013 if (GetFrameId() != frame_id_) {
2014 return true; // Not our frame, carry on.
Elliott Hughesdbb40792011-11-18 17:05:22 -08002015 }
Ian Rogers0399dde2012-06-06 17:09:28 -07002016 // TODO: check that the tag is compatible with the actual type of the slot!
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002017 mirror::AbstractMethod* m = GetMethod();
Ian Rogers0399dde2012-06-06 17:09:28 -07002018 uint16_t reg = DemangleSlot(slot_, m);
Elliott Hughesdbb40792011-11-18 17:05:22 -08002019
Ian Rogers0399dde2012-06-06 17:09:28 -07002020 switch (tag_) {
2021 case JDWP::JT_BOOLEAN:
2022 {
2023 CHECK_EQ(width_, 1U);
Ian Rogers2bcb4a42012-11-08 10:39:18 -08002024 uint32_t intVal = GetVReg(m, reg, kIntVReg);
Ian Rogers0399dde2012-06-06 17:09:28 -07002025 VLOG(jdwp) << "get boolean local " << reg << " = " << intVal;
2026 JDWP::Set1(buf_+1, intVal != 0);
2027 }
2028 break;
2029 case JDWP::JT_BYTE:
2030 {
2031 CHECK_EQ(width_, 1U);
Ian Rogers2bcb4a42012-11-08 10:39:18 -08002032 uint32_t intVal = GetVReg(m, reg, kIntVReg);
Ian Rogers0399dde2012-06-06 17:09:28 -07002033 VLOG(jdwp) << "get byte local " << reg << " = " << intVal;
2034 JDWP::Set1(buf_+1, intVal);
2035 }
2036 break;
2037 case JDWP::JT_SHORT:
2038 case JDWP::JT_CHAR:
2039 {
2040 CHECK_EQ(width_, 2U);
Ian Rogers2bcb4a42012-11-08 10:39:18 -08002041 uint32_t intVal = GetVReg(m, reg, kIntVReg);
Ian Rogers0399dde2012-06-06 17:09:28 -07002042 VLOG(jdwp) << "get short/char local " << reg << " = " << intVal;
2043 JDWP::Set2BE(buf_+1, intVal);
2044 }
2045 break;
2046 case JDWP::JT_INT:
Ian Rogers2bcb4a42012-11-08 10:39:18 -08002047 {
2048 CHECK_EQ(width_, 4U);
2049 uint32_t intVal = GetVReg(m, reg, kIntVReg);
2050 VLOG(jdwp) << "get int local " << reg << " = " << intVal;
2051 JDWP::Set4BE(buf_+1, intVal);
2052 }
2053 break;
Ian Rogers0399dde2012-06-06 17:09:28 -07002054 case JDWP::JT_FLOAT:
2055 {
2056 CHECK_EQ(width_, 4U);
Ian Rogers2bcb4a42012-11-08 10:39:18 -08002057 uint32_t intVal = GetVReg(m, reg, kFloatVReg);
Ian Rogers0399dde2012-06-06 17:09:28 -07002058 VLOG(jdwp) << "get int/float local " << reg << " = " << intVal;
2059 JDWP::Set4BE(buf_+1, intVal);
2060 }
2061 break;
2062 case JDWP::JT_ARRAY:
2063 {
2064 CHECK_EQ(width_, sizeof(JDWP::ObjectId));
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002065 mirror::Object* o = reinterpret_cast<mirror::Object*>(GetVReg(m, reg, kReferenceVReg));
Ian Rogers0399dde2012-06-06 17:09:28 -07002066 VLOG(jdwp) << "get array local " << reg << " = " << o;
2067 if (!Runtime::Current()->GetHeap()->IsHeapAddress(o)) {
2068 LOG(FATAL) << "Register " << reg << " expected to hold array: " << o;
2069 }
2070 JDWP::SetObjectId(buf_+1, gRegistry->Add(o));
2071 }
2072 break;
2073 case JDWP::JT_CLASS_LOADER:
2074 case JDWP::JT_CLASS_OBJECT:
2075 case JDWP::JT_OBJECT:
2076 case JDWP::JT_STRING:
2077 case JDWP::JT_THREAD:
2078 case JDWP::JT_THREAD_GROUP:
2079 {
2080 CHECK_EQ(width_, sizeof(JDWP::ObjectId));
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002081 mirror::Object* o = reinterpret_cast<mirror::Object*>(GetVReg(m, reg, kReferenceVReg));
Ian Rogers0399dde2012-06-06 17:09:28 -07002082 VLOG(jdwp) << "get object local " << reg << " = " << o;
2083 if (!Runtime::Current()->GetHeap()->IsHeapAddress(o)) {
2084 LOG(FATAL) << "Register " << reg << " expected to hold object: " << o;
2085 }
2086 tag_ = TagFromObject(o);
2087 JDWP::SetObjectId(buf_+1, gRegistry->Add(o));
2088 }
2089 break;
2090 case JDWP::JT_DOUBLE:
Ian Rogers2bcb4a42012-11-08 10:39:18 -08002091 {
2092 CHECK_EQ(width_, 8U);
2093 uint32_t lo = GetVReg(m, reg, kDoubleLoVReg);
2094 uint64_t hi = GetVReg(m, reg + 1, kDoubleHiVReg);
2095 uint64_t longVal = (hi << 32) | lo;
2096 VLOG(jdwp) << "get double/long local " << hi << ":" << lo << " = " << longVal;
2097 JDWP::Set8BE(buf_+1, longVal);
2098 }
2099 break;
Ian Rogers0399dde2012-06-06 17:09:28 -07002100 case JDWP::JT_LONG:
2101 {
2102 CHECK_EQ(width_, 8U);
Ian Rogers2bcb4a42012-11-08 10:39:18 -08002103 uint32_t lo = GetVReg(m, reg, kLongLoVReg);
2104 uint64_t hi = GetVReg(m, reg + 1, kLongHiVReg);
Ian Rogers0399dde2012-06-06 17:09:28 -07002105 uint64_t longVal = (hi << 32) | lo;
2106 VLOG(jdwp) << "get double/long local " << hi << ":" << lo << " = " << longVal;
2107 JDWP::Set8BE(buf_+1, longVal);
2108 }
2109 break;
2110 default:
2111 LOG(FATAL) << "Unknown tag " << tag_;
2112 break;
2113 }
2114
2115 // Prepend tag, which may have been updated.
2116 JDWP::Set1(buf_, tag_);
2117 return false;
2118 }
2119
2120 const JDWP::FrameId frame_id_;
2121 const int slot_;
2122 JDWP::JdwpTag tag_;
2123 uint8_t* const buf_;
2124 const size_t width_;
2125 };
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002126
2127 ScopedObjectAccessUnchecked soa(Thread::Current());
jeffhaoa77f0f62012-12-05 17:19:31 -08002128 MutexLock mu(soa.Self(), *Locks::thread_list_lock_);
Elliott Hughes221229c2013-01-08 18:17:50 -08002129 Thread* thread;
2130 JDWP::JdwpError error = DecodeThread(soa, thread_id, thread);
2131 if (error != JDWP::ERR_NONE) {
2132 return;
2133 }
Ian Rogers0399dde2012-06-06 17:09:28 -07002134 UniquePtr<Context> context(Context::Create());
Ian Rogers7a22fa62013-01-23 12:16:16 -08002135 GetLocalVisitor visitor(thread, context.get(), frame_id, slot, tag, buf, width);
Ian Rogers0399dde2012-06-06 17:09:28 -07002136 visitor.WalkStack();
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002137}
2138
Elliott Hughes88d63092013-01-09 09:55:54 -08002139void Dbg::SetLocalValue(JDWP::ObjectId thread_id, JDWP::FrameId frame_id, int slot, JDWP::JdwpTag tag,
Ian Rogers0399dde2012-06-06 17:09:28 -07002140 uint64_t value, size_t width) {
2141 struct SetLocalVisitor : public StackVisitor {
Ian Rogers7a22fa62013-01-23 12:16:16 -08002142 SetLocalVisitor(Thread* thread, Context* context,
Ian Rogers0399dde2012-06-06 17:09:28 -07002143 JDWP::FrameId frame_id, int slot, JDWP::JdwpTag tag, uint64_t value,
Ian Rogersca190662012-06-26 15:45:57 -07002144 size_t width)
Ian Rogersb726dcb2012-09-05 08:57:23 -07002145 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_)
Ian Rogers7a22fa62013-01-23 12:16:16 -08002146 : StackVisitor(thread, context),
Elliott Hughes08fc03a2012-06-26 17:34:00 -07002147 frame_id_(frame_id), slot_(slot), tag_(tag), value_(value), width_(width) {}
Ian Rogersca190662012-06-26 15:45:57 -07002148
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002149 // TODO: Enable annotalysis. We know lock is held in constructor, but abstraction confuses
2150 // annotalysis.
2151 bool VisitFrame() NO_THREAD_SAFETY_ANALYSIS {
Ian Rogers0399dde2012-06-06 17:09:28 -07002152 if (GetFrameId() != frame_id_) {
2153 return true; // Not our frame, carry on.
2154 }
2155 // TODO: check that the tag is compatible with the actual type of the slot!
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002156 mirror::AbstractMethod* m = GetMethod();
Ian Rogers0399dde2012-06-06 17:09:28 -07002157 uint16_t reg = DemangleSlot(slot_, m);
2158
2159 switch (tag_) {
2160 case JDWP::JT_BOOLEAN:
2161 case JDWP::JT_BYTE:
2162 CHECK_EQ(width_, 1U);
Ian Rogers2bcb4a42012-11-08 10:39:18 -08002163 SetVReg(m, reg, static_cast<uint32_t>(value_), kIntVReg);
Ian Rogers0399dde2012-06-06 17:09:28 -07002164 break;
2165 case JDWP::JT_SHORT:
2166 case JDWP::JT_CHAR:
2167 CHECK_EQ(width_, 2U);
Ian Rogers2bcb4a42012-11-08 10:39:18 -08002168 SetVReg(m, reg, static_cast<uint32_t>(value_), kIntVReg);
Ian Rogers0399dde2012-06-06 17:09:28 -07002169 break;
2170 case JDWP::JT_INT:
Ian Rogers2bcb4a42012-11-08 10:39:18 -08002171 CHECK_EQ(width_, 4U);
2172 SetVReg(m, reg, static_cast<uint32_t>(value_), kIntVReg);
2173 break;
Ian Rogers0399dde2012-06-06 17:09:28 -07002174 case JDWP::JT_FLOAT:
2175 CHECK_EQ(width_, 4U);
Ian Rogers2bcb4a42012-11-08 10:39:18 -08002176 SetVReg(m, reg, static_cast<uint32_t>(value_), kFloatVReg);
Ian Rogers0399dde2012-06-06 17:09:28 -07002177 break;
2178 case JDWP::JT_ARRAY:
2179 case JDWP::JT_OBJECT:
2180 case JDWP::JT_STRING:
2181 {
2182 CHECK_EQ(width_, sizeof(JDWP::ObjectId));
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002183 mirror::Object* o = gRegistry->Get<mirror::Object*>(static_cast<JDWP::ObjectId>(value_));
Elliott Hughes64f574f2013-02-20 14:57:12 -08002184 if (o == ObjectRegistry::kInvalidObject) {
Ian Rogers0399dde2012-06-06 17:09:28 -07002185 UNIMPLEMENTED(FATAL) << "return an error code when given an invalid object to store";
2186 }
Ian Rogers2bcb4a42012-11-08 10:39:18 -08002187 SetVReg(m, reg, static_cast<uint32_t>(reinterpret_cast<uintptr_t>(o)), kReferenceVReg);
Ian Rogers0399dde2012-06-06 17:09:28 -07002188 }
2189 break;
2190 case JDWP::JT_DOUBLE:
Ian Rogers2bcb4a42012-11-08 10:39:18 -08002191 CHECK_EQ(width_, 8U);
2192 SetVReg(m, reg, static_cast<uint32_t>(value_), kDoubleLoVReg);
2193 SetVReg(m, reg + 1, static_cast<uint32_t>(value_ >> 32), kDoubleHiVReg);
2194 break;
Ian Rogers0399dde2012-06-06 17:09:28 -07002195 case JDWP::JT_LONG:
2196 CHECK_EQ(width_, 8U);
Ian Rogers2bcb4a42012-11-08 10:39:18 -08002197 SetVReg(m, reg, static_cast<uint32_t>(value_), kLongLoVReg);
2198 SetVReg(m, reg + 1, static_cast<uint32_t>(value_ >> 32), kLongHiVReg);
Ian Rogers0399dde2012-06-06 17:09:28 -07002199 break;
2200 default:
2201 LOG(FATAL) << "Unknown tag " << tag_;
2202 break;
2203 }
2204 return false;
2205 }
2206
2207 const JDWP::FrameId frame_id_;
2208 const int slot_;
2209 const JDWP::JdwpTag tag_;
2210 const uint64_t value_;
2211 const size_t width_;
2212 };
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002213
2214 ScopedObjectAccessUnchecked soa(Thread::Current());
jeffhaoa77f0f62012-12-05 17:19:31 -08002215 MutexLock mu(soa.Self(), *Locks::thread_list_lock_);
Elliott Hughes221229c2013-01-08 18:17:50 -08002216 Thread* thread;
2217 JDWP::JdwpError error = DecodeThread(soa, thread_id, thread);
2218 if (error != JDWP::ERR_NONE) {
2219 return;
2220 }
Elliott Hughes08fc03a2012-06-26 17:34:00 -07002221 UniquePtr<Context> context(Context::Create());
Ian Rogers7a22fa62013-01-23 12:16:16 -08002222 SetLocalVisitor visitor(thread, context.get(), frame_id, slot, tag, value, width);
Ian Rogers0399dde2012-06-06 17:09:28 -07002223 visitor.WalkStack();
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002224}
2225
Ian Rogers62d6c772013-02-27 08:32:07 -08002226void Dbg::PostLocationEvent(const mirror::AbstractMethod* m, int dex_pc,
2227 mirror::Object* this_object, int event_flags) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002228 mirror::Class* c = m->GetDeclaringClass();
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08002229
2230 JDWP::JdwpLocation location;
Elliott Hughes74847412012-06-20 18:10:21 -07002231 location.type_tag = c->IsInterface() ? JDWP::TT_INTERFACE : JDWP::TT_CLASS;
Elliott Hughes64f574f2013-02-20 14:57:12 -08002232 location.class_id = gRegistry->AddRefType(c);
Elliott Hughes74847412012-06-20 18:10:21 -07002233 location.method_id = ToMethodId(m);
Elliott Hughes972a47b2012-02-21 18:16:06 -08002234 location.dex_pc = m->IsNative() ? -1 : dex_pc;
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08002235
Elliott Hughes64f574f2013-02-20 14:57:12 -08002236 // If 'this_object' isn't already in the registry, we know that we're not looking for it,
2237 // so there's no point adding it to the registry and burning through ids.
2238 JDWP::ObjectId this_id = 0;
2239 if (gRegistry->Contains(this_object)) {
2240 this_id = gRegistry->Add(this_object);
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08002241 }
Elliott Hughes64f574f2013-02-20 14:57:12 -08002242 gJdwpState->PostLocationEvent(&location, this_id, event_flags);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002243}
2244
Ian Rogers62d6c772013-02-27 08:32:07 -08002245void Dbg::PostException(Thread* thread, const ThrowLocation& throw_location,
2246 mirror::AbstractMethod* catch_method,
Elliott Hughes64f574f2013-02-20 14:57:12 -08002247 uint32_t catch_dex_pc, mirror::Throwable* exception_object) {
Elliott Hughesc0f09332012-03-26 13:27:06 -07002248 if (!IsDebuggerActive()) {
Ian Rogers0ad5bb82011-12-07 10:16:32 -08002249 return;
2250 }
Elliott Hughes4740cdf2011-12-07 14:07:12 -08002251
Ian Rogers62d6c772013-02-27 08:32:07 -08002252 JDWP::JdwpLocation jdwp_throw_location;
2253 SetLocation(jdwp_throw_location, throw_location.GetMethod(), throw_location.GetDexPc());
Elliott Hughesd07986f2011-12-06 18:27:45 -08002254 JDWP::JdwpLocation catch_location;
Elliott Hughescaf76542012-06-28 16:08:22 -07002255 SetLocation(catch_location, catch_method, catch_dex_pc);
Elliott Hughesd07986f2011-12-06 18:27:45 -08002256
2257 // We need 'this' for InstanceOnly filters.
Ian Rogers62d6c772013-02-27 08:32:07 -08002258 JDWP::ObjectId this_id = gRegistry->Add(throw_location.GetThis());
Elliott Hughes64f574f2013-02-20 14:57:12 -08002259 JDWP::ObjectId exception_id = gRegistry->Add(exception_object);
2260 JDWP::RefTypeId exception_class_id = gRegistry->AddRefType(exception_object->GetClass());
Elliott Hughesd07986f2011-12-06 18:27:45 -08002261
Ian Rogers62d6c772013-02-27 08:32:07 -08002262 gJdwpState->PostException(&jdwp_throw_location, exception_id, exception_class_id, &catch_location,
2263 this_id);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002264}
2265
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002266void Dbg::PostClassPrepare(mirror::Class* c) {
Elliott Hughesc0f09332012-03-26 13:27:06 -07002267 if (!IsDebuggerActive()) {
Elliott Hughes4740cdf2011-12-07 14:07:12 -08002268 return;
2269 }
2270
Elliott Hughes3d30d9b2011-12-07 17:35:48 -08002271 // OLD-TODO - we currently always send both "verified" and "prepared" since
Elliott Hughes4740cdf2011-12-07 14:07:12 -08002272 // debuggers seem to like that. There might be some advantage to honesty,
2273 // since the class may not yet be verified.
2274 int state = JDWP::CS_VERIFIED | JDWP::CS_PREPARED;
2275 JDWP::JdwpTypeTag tag = c->IsInterface() ? JDWP::TT_INTERFACE : JDWP::TT_CLASS;
2276 gJdwpState->PostClassPrepare(tag, gRegistry->Add(c), ClassHelper(c).GetDescriptor(), state);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002277}
2278
Ian Rogers62d6c772013-02-27 08:32:07 -08002279void Dbg::UpdateDebugger(Thread* thread, mirror::Object* this_object,
2280 const mirror::AbstractMethod* m, uint32_t dex_pc) {
2281 if (!IsDebuggerActive() || dex_pc == static_cast<uint32_t>(-2) /* fake method exit */) {
Elliott Hughes2aa2e392012-02-17 17:15:43 -08002282 return;
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08002283 }
2284
Elliott Hughes2aa2e392012-02-17 17:15:43 -08002285 int event_flags = 0;
2286
Elliott Hughes86964332012-02-15 19:37:42 -08002287 if (IsBreakpoint(m, dex_pc)) {
2288 event_flags |= kBreakpoint;
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08002289 }
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08002290
jeffhao09bfc6a2012-12-11 18:11:43 -08002291 {
2292 // If the debugger is single-stepping one of our threads, check to
2293 // see if we're that thread and we've reached a step point.
2294 MutexLock mu(Thread::Current(), *Locks::breakpoint_lock_);
Ian Rogers62d6c772013-02-27 08:32:07 -08002295 if (gSingleStepControl.is_active && gSingleStepControl.thread == thread) {
jeffhao09bfc6a2012-12-11 18:11:43 -08002296 CHECK(!m->IsNative());
2297 if (gSingleStepControl.step_depth == JDWP::SD_INTO) {
2298 // Step into method calls. We break when the line number
2299 // or method pointer changes. If we're in SS_MIN mode, we
2300 // always stop.
2301 if (gSingleStepControl.method != m) {
2302 event_flags |= kSingleStep;
2303 VLOG(jdwp) << "SS new method";
2304 } else if (gSingleStepControl.step_size == JDWP::SS_MIN) {
Elliott Hughes86964332012-02-15 19:37:42 -08002305 event_flags |= kSingleStep;
2306 VLOG(jdwp) << "SS new instruction";
Elliott Hughes2435a572012-02-17 16:07:41 -08002307 } else if (gSingleStepControl.dex_pcs.find(dex_pc) == gSingleStepControl.dex_pcs.end()) {
2308 event_flags |= kSingleStep;
2309 VLOG(jdwp) << "SS new line";
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08002310 }
jeffhao09bfc6a2012-12-11 18:11:43 -08002311 } else if (gSingleStepControl.step_depth == JDWP::SD_OVER) {
2312 // Step over method calls. We break when the line number is
2313 // different and the frame depth is <= the original frame
2314 // depth. (We can't just compare on the method, because we
2315 // might get unrolled past it by an exception, and it's tricky
2316 // to identify recursion.)
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08002317
Ian Rogers62d6c772013-02-27 08:32:07 -08002318 int stack_depth = GetStackDepth(thread);
Elliott Hughes86964332012-02-15 19:37:42 -08002319
jeffhao09bfc6a2012-12-11 18:11:43 -08002320 if (stack_depth < gSingleStepControl.stack_depth) {
2321 // popped up one or more frames, always trigger
2322 event_flags |= kSingleStep;
2323 VLOG(jdwp) << "SS method pop";
2324 } else if (stack_depth == gSingleStepControl.stack_depth) {
2325 // same depth, see if we moved
2326 if (gSingleStepControl.step_size == JDWP::SS_MIN) {
2327 event_flags |= kSingleStep;
2328 VLOG(jdwp) << "SS new instruction";
2329 } else if (gSingleStepControl.dex_pcs.find(dex_pc) == gSingleStepControl.dex_pcs.end()) {
2330 event_flags |= kSingleStep;
2331 VLOG(jdwp) << "SS new line";
2332 }
2333 }
2334 } else {
2335 CHECK_EQ(gSingleStepControl.step_depth, JDWP::SD_OUT);
2336 // Return from the current method. We break when the frame
2337 // depth pops up.
2338
2339 // This differs from the "method exit" break in that it stops
2340 // with the PC at the next instruction in the returned-to
2341 // function, rather than the end of the returning function.
2342
Ian Rogers62d6c772013-02-27 08:32:07 -08002343 int stack_depth = GetStackDepth(thread);
jeffhao09bfc6a2012-12-11 18:11:43 -08002344 if (stack_depth < gSingleStepControl.stack_depth) {
2345 event_flags |= kSingleStep;
2346 VLOG(jdwp) << "SS method pop";
2347 }
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08002348 }
2349 }
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08002350 }
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08002351
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08002352 // If there's something interesting going on, see if it matches one
2353 // of the debugger filters.
2354 if (event_flags != 0) {
Ian Rogers62d6c772013-02-27 08:32:07 -08002355 Dbg::PostLocationEvent(m, dex_pc, this_object, event_flags);
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08002356 }
2357}
2358
Elliott Hughes86964332012-02-15 19:37:42 -08002359void Dbg::WatchLocation(const JDWP::JdwpLocation* location) {
jeffhao09bfc6a2012-12-11 18:11:43 -08002360 MutexLock mu(Thread::Current(), *Locks::breakpoint_lock_);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002361 mirror::AbstractMethod* m = FromMethodId(location->method_id);
Elliott Hughes972a47b2012-02-21 18:16:06 -08002362 gBreakpoints.push_back(Breakpoint(m, location->dex_pc));
Elliott Hughes86964332012-02-15 19:37:42 -08002363 VLOG(jdwp) << "Set breakpoint #" << (gBreakpoints.size() - 1) << ": " << gBreakpoints[gBreakpoints.size() - 1];
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002364}
2365
Elliott Hughes86964332012-02-15 19:37:42 -08002366void Dbg::UnwatchLocation(const JDWP::JdwpLocation* location) {
jeffhao09bfc6a2012-12-11 18:11:43 -08002367 MutexLock mu(Thread::Current(), *Locks::breakpoint_lock_);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002368 mirror::AbstractMethod* m = FromMethodId(location->method_id);
Elliott Hughes86964332012-02-15 19:37:42 -08002369 for (size_t i = 0; i < gBreakpoints.size(); ++i) {
Elliott Hughes972a47b2012-02-21 18:16:06 -08002370 if (gBreakpoints[i].method == m && gBreakpoints[i].dex_pc == location->dex_pc) {
Elliott Hughes86964332012-02-15 19:37:42 -08002371 VLOG(jdwp) << "Removed breakpoint #" << i << ": " << gBreakpoints[i];
2372 gBreakpoints.erase(gBreakpoints.begin() + i);
2373 return;
2374 }
2375 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002376}
2377
Jeff Hao449db332013-04-12 18:30:52 -07002378// Scoped utility class to suspend a thread so that we may do tasks such as walk its stack. Doesn't
2379// cause suspension if the thread is the current thread.
2380class ScopedThreadSuspension {
2381 public:
Ian Rogers33e95662013-05-20 20:29:14 -07002382 ScopedThreadSuspension(Thread* self, JDWP::ObjectId thread_id)
2383 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) :
Jeff Hao449db332013-04-12 18:30:52 -07002384 thread_(NULL),
2385 error_(JDWP::ERR_NONE),
2386 self_suspend_(false),
Ian Rogers33e95662013-05-20 20:29:14 -07002387 other_suspend_(false) {
Jeff Hao449db332013-04-12 18:30:52 -07002388 ScopedObjectAccessUnchecked soa(self);
2389 {
2390 MutexLock mu(soa.Self(), *Locks::thread_list_lock_);
2391 error_ = DecodeThread(soa, thread_id, thread_);
2392 }
2393 if (error_ == JDWP::ERR_NONE) {
2394 if (thread_ == soa.Self()) {
2395 self_suspend_ = true;
2396 } else {
2397 soa.Self()->TransitionFromRunnableToSuspended(kWaitingForDebuggerSuspension);
2398 jobject thread_peer = gRegistry->GetJObject(thread_id);
2399 bool timed_out;
2400 Thread* suspended_thread = Thread::SuspendForDebugger(thread_peer, true, &timed_out);
2401 CHECK_EQ(soa.Self()->TransitionFromSuspendedToRunnable(), kWaitingForDebuggerSuspension);
2402 if (suspended_thread == NULL) {
2403 // Thread terminated from under us while suspending.
2404 error_ = JDWP::ERR_INVALID_THREAD;
2405 } else {
2406 CHECK_EQ(suspended_thread, thread_);
2407 other_suspend_ = true;
2408 }
2409 }
2410 }
Elliott Hughes2435a572012-02-17 16:07:41 -08002411 }
Elliott Hughes86964332012-02-15 19:37:42 -08002412
Jeff Hao449db332013-04-12 18:30:52 -07002413 Thread* GetThread() const {
2414 return thread_;
2415 }
2416
2417 JDWP::JdwpError GetError() const {
2418 return error_;
2419 }
2420
2421 ~ScopedThreadSuspension() {
2422 if (other_suspend_) {
2423 Runtime::Current()->GetThreadList()->Resume(thread_, true);
2424 }
2425 }
2426
2427 private:
2428 Thread* thread_;
2429 JDWP::JdwpError error_;
2430 bool self_suspend_;
2431 bool other_suspend_;
2432};
2433
2434JDWP::JdwpError Dbg::ConfigureStep(JDWP::ObjectId thread_id, JDWP::JdwpStepSize step_size,
2435 JDWP::JdwpStepDepth step_depth) {
2436 Thread* self = Thread::Current();
2437 ScopedThreadSuspension sts(self, thread_id);
2438 if (sts.GetError() != JDWP::ERR_NONE) {
2439 return sts.GetError();
2440 }
2441
2442 MutexLock mu2(self, *Locks::breakpoint_lock_);
Elliott Hughes86964332012-02-15 19:37:42 -08002443 // TODO: there's no theoretical reason why we couldn't support single-stepping
2444 // of multiple threads at once, but we never did so historically.
Jeff Hao449db332013-04-12 18:30:52 -07002445 if (gSingleStepControl.thread != NULL && sts.GetThread() != gSingleStepControl.thread) {
Elliott Hughes86964332012-02-15 19:37:42 -08002446 LOG(WARNING) << "single-step already active for " << *gSingleStepControl.thread
Jeff Hao449db332013-04-12 18:30:52 -07002447 << "; switching to " << *sts.GetThread();
Elliott Hughes86964332012-02-15 19:37:42 -08002448 }
2449
Elliott Hughes2435a572012-02-17 16:07:41 -08002450 //
2451 // Work out what Method* we're in, the current line number, and how deep the stack currently
2452 // is for step-out.
2453 //
2454
Ian Rogers0399dde2012-06-06 17:09:28 -07002455 struct SingleStepStackVisitor : public StackVisitor {
Ian Rogers7a22fa62013-01-23 12:16:16 -08002456 SingleStepStackVisitor(Thread* thread)
jeffhao09bfc6a2012-12-11 18:11:43 -08002457 EXCLUSIVE_LOCKS_REQUIRED(Locks::breakpoint_lock_)
Ian Rogersb726dcb2012-09-05 08:57:23 -07002458 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_)
Ian Rogers7a22fa62013-01-23 12:16:16 -08002459 : StackVisitor(thread, NULL) {
Elliott Hughes86964332012-02-15 19:37:42 -08002460 gSingleStepControl.method = NULL;
2461 gSingleStepControl.stack_depth = 0;
2462 }
Ian Rogersca190662012-06-26 15:45:57 -07002463
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002464 // TODO: Enable annotalysis. We know lock is held in constructor, but abstraction confuses
2465 // annotalysis.
2466 bool VisitFrame() NO_THREAD_SAFETY_ANALYSIS {
jeffhao09bfc6a2012-12-11 18:11:43 -08002467 Locks::breakpoint_lock_->AssertHeld(Thread::Current());
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002468 const mirror::AbstractMethod* m = GetMethod();
Ian Rogers0399dde2012-06-06 17:09:28 -07002469 if (!m->IsRuntimeMethod()) {
Elliott Hughes86964332012-02-15 19:37:42 -08002470 ++gSingleStepControl.stack_depth;
2471 if (gSingleStepControl.method == NULL) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002472 const mirror::DexCache* dex_cache = m->GetDeclaringClass()->GetDexCache();
Elliott Hughes2435a572012-02-17 16:07:41 -08002473 gSingleStepControl.method = m;
2474 gSingleStepControl.line_number = -1;
2475 if (dex_cache != NULL) {
Ian Rogers4445a7e2012-10-05 17:19:13 -07002476 const DexFile& dex_file = *dex_cache->GetDexFile();
Ian Rogers0399dde2012-06-06 17:09:28 -07002477 gSingleStepControl.line_number = dex_file.GetLineNumFromPC(m, GetDexPc());
Elliott Hughes2435a572012-02-17 16:07:41 -08002478 }
Elliott Hughes86964332012-02-15 19:37:42 -08002479 }
2480 }
Elliott Hughes530fa002012-03-12 11:44:49 -07002481 return true;
Elliott Hughes86964332012-02-15 19:37:42 -08002482 }
2483 };
Jeff Hao449db332013-04-12 18:30:52 -07002484
2485 SingleStepStackVisitor visitor(sts.GetThread());
Ian Rogers0399dde2012-06-06 17:09:28 -07002486 visitor.WalkStack();
Elliott Hughes86964332012-02-15 19:37:42 -08002487
Elliott Hughes2435a572012-02-17 16:07:41 -08002488 //
2489 // Find the dex_pc values that correspond to the current line, for line-based single-stepping.
2490 //
2491
2492 struct DebugCallbackContext {
jeffhao09bfc6a2012-12-11 18:11:43 -08002493 DebugCallbackContext() EXCLUSIVE_LOCKS_REQUIRED(Locks::breakpoint_lock_) {
Elliott Hughes2435a572012-02-17 16:07:41 -08002494 last_pc_valid = false;
2495 last_pc = 0;
Elliott Hughes2435a572012-02-17 16:07:41 -08002496 }
2497
jeffhao09bfc6a2012-12-11 18:11:43 -08002498 // TODO: Enable annotalysis. We know lock is held in constructor, but abstraction confuses
2499 // annotalysis.
2500 static bool Callback(void* raw_context, uint32_t address, uint32_t line_number) NO_THREAD_SAFETY_ANALYSIS {
2501 Locks::breakpoint_lock_->AssertHeld(Thread::Current());
Elliott Hughes2435a572012-02-17 16:07:41 -08002502 DebugCallbackContext* context = reinterpret_cast<DebugCallbackContext*>(raw_context);
2503 if (static_cast<int32_t>(line_number) == gSingleStepControl.line_number) {
2504 if (!context->last_pc_valid) {
2505 // Everything from this address until the next line change is ours.
2506 context->last_pc = address;
2507 context->last_pc_valid = true;
2508 }
2509 // Otherwise, if we're already in a valid range for this line,
2510 // just keep going (shouldn't really happen)...
2511 } else if (context->last_pc_valid) { // and the line number is new
2512 // Add everything from the last entry up until here to the set
2513 for (uint32_t dex_pc = context->last_pc; dex_pc < address; ++dex_pc) {
2514 gSingleStepControl.dex_pcs.insert(dex_pc);
2515 }
2516 context->last_pc_valid = false;
2517 }
2518 return false; // There may be multiple entries for any given line.
2519 }
2520
jeffhao09bfc6a2012-12-11 18:11:43 -08002521 // TODO: Enable annotalysis. We know lock is held in constructor, but abstraction confuses
2522 // annotalysis.
2523 ~DebugCallbackContext() NO_THREAD_SAFETY_ANALYSIS {
2524 Locks::breakpoint_lock_->AssertHeld(Thread::Current());
Elliott Hughes2435a572012-02-17 16:07:41 -08002525 // If the line number was the last in the position table...
2526 if (last_pc_valid) {
2527 size_t end = MethodHelper(gSingleStepControl.method).GetCodeItem()->insns_size_in_code_units_;
2528 for (uint32_t dex_pc = last_pc; dex_pc < end; ++dex_pc) {
2529 gSingleStepControl.dex_pcs.insert(dex_pc);
2530 }
2531 }
2532 }
2533
2534 bool last_pc_valid;
2535 uint32_t last_pc;
2536 };
Elliott Hughes3e2e1a22012-02-21 11:33:41 -08002537 gSingleStepControl.dex_pcs.clear();
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002538 const mirror::AbstractMethod* m = gSingleStepControl.method;
Elliott Hughes3e2e1a22012-02-21 11:33:41 -08002539 if (m->IsNative()) {
2540 gSingleStepControl.line_number = -1;
2541 } else {
2542 DebugCallbackContext context;
2543 MethodHelper mh(m);
2544 mh.GetDexFile().DecodeDebugInfo(mh.GetCodeItem(), m->IsStatic(), m->GetDexMethodIndex(),
2545 DebugCallbackContext::Callback, NULL, &context);
2546 }
Elliott Hughes2435a572012-02-17 16:07:41 -08002547
2548 //
2549 // Everything else...
2550 //
2551
Jeff Hao449db332013-04-12 18:30:52 -07002552 gSingleStepControl.thread = sts.GetThread();
Elliott Hughes86964332012-02-15 19:37:42 -08002553 gSingleStepControl.step_size = step_size;
2554 gSingleStepControl.step_depth = step_depth;
2555 gSingleStepControl.is_active = true;
2556
Elliott Hughes2435a572012-02-17 16:07:41 -08002557 if (VLOG_IS_ON(jdwp)) {
2558 VLOG(jdwp) << "Single-step thread: " << *gSingleStepControl.thread;
2559 VLOG(jdwp) << "Single-step step size: " << gSingleStepControl.step_size;
2560 VLOG(jdwp) << "Single-step step depth: " << gSingleStepControl.step_depth;
2561 VLOG(jdwp) << "Single-step current method: " << PrettyMethod(gSingleStepControl.method);
2562 VLOG(jdwp) << "Single-step current line: " << gSingleStepControl.line_number;
2563 VLOG(jdwp) << "Single-step current stack depth: " << gSingleStepControl.stack_depth;
2564 VLOG(jdwp) << "Single-step dex_pc values:";
2565 for (std::set<uint32_t>::iterator it = gSingleStepControl.dex_pcs.begin() ; it != gSingleStepControl.dex_pcs.end(); ++it) {
Elliott Hughes229feb72012-02-23 13:33:29 -08002566 VLOG(jdwp) << StringPrintf(" %#x", *it);
Elliott Hughes2435a572012-02-17 16:07:41 -08002567 }
2568 }
2569
2570 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002571}
2572
Elliott Hughes221229c2013-01-08 18:17:50 -08002573void Dbg::UnconfigureStep(JDWP::ObjectId /*thread_id*/) {
jeffhao09bfc6a2012-12-11 18:11:43 -08002574 MutexLock mu(Thread::Current(), *Locks::breakpoint_lock_);
Elliott Hughesf8349362012-06-18 15:00:06 -07002575
Elliott Hughes86964332012-02-15 19:37:42 -08002576 gSingleStepControl.is_active = false;
2577 gSingleStepControl.thread = NULL;
Elliott Hughes2435a572012-02-17 16:07:41 -08002578 gSingleStepControl.dex_pcs.clear();
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002579}
2580
Elliott Hughes45651fd2012-02-21 15:48:20 -08002581static char JdwpTagToShortyChar(JDWP::JdwpTag tag) {
2582 switch (tag) {
2583 default:
2584 LOG(FATAL) << "unknown JDWP tag: " << PrintableChar(tag);
2585
2586 // Primitives.
2587 case JDWP::JT_BYTE: return 'B';
2588 case JDWP::JT_CHAR: return 'C';
2589 case JDWP::JT_FLOAT: return 'F';
2590 case JDWP::JT_DOUBLE: return 'D';
2591 case JDWP::JT_INT: return 'I';
2592 case JDWP::JT_LONG: return 'J';
2593 case JDWP::JT_SHORT: return 'S';
2594 case JDWP::JT_VOID: return 'V';
2595 case JDWP::JT_BOOLEAN: return 'Z';
2596
2597 // Reference types.
2598 case JDWP::JT_ARRAY:
2599 case JDWP::JT_OBJECT:
2600 case JDWP::JT_STRING:
2601 case JDWP::JT_THREAD:
2602 case JDWP::JT_THREAD_GROUP:
2603 case JDWP::JT_CLASS_LOADER:
2604 case JDWP::JT_CLASS_OBJECT:
2605 return 'L';
2606 }
2607}
2608
Elliott Hughes88d63092013-01-09 09:55:54 -08002609JDWP::JdwpError Dbg::InvokeMethod(JDWP::ObjectId thread_id, JDWP::ObjectId object_id,
2610 JDWP::RefTypeId class_id, JDWP::MethodId method_id,
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002611 uint32_t arg_count, uint64_t* arg_values,
2612 JDWP::JdwpTag* arg_types, uint32_t options,
2613 JDWP::JdwpTag* pResultTag, uint64_t* pResultValue,
2614 JDWP::ObjectId* pExceptionId) {
Elliott Hughesd07986f2011-12-06 18:27:45 -08002615 ThreadList* thread_list = Runtime::Current()->GetThreadList();
2616
2617 Thread* targetThread = NULL;
2618 DebugInvokeReq* req = NULL;
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002619 Thread* self = Thread::Current();
Elliott Hughesd07986f2011-12-06 18:27:45 -08002620 {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002621 ScopedObjectAccessUnchecked soa(self);
Ian Rogers50b35e22012-10-04 10:09:15 -07002622 MutexLock mu(soa.Self(), *Locks::thread_list_lock_);
Elliott Hughes221229c2013-01-08 18:17:50 -08002623 JDWP::JdwpError error = DecodeThread(soa, thread_id, targetThread);
2624 if (error != JDWP::ERR_NONE) {
2625 LOG(ERROR) << "InvokeMethod request for invalid thread id " << thread_id;
2626 return error;
Elliott Hughesd07986f2011-12-06 18:27:45 -08002627 }
2628 req = targetThread->GetInvokeReq();
2629 if (!req->ready) {
2630 LOG(ERROR) << "InvokeMethod request for thread not stopped by event: " << *targetThread;
2631 return JDWP::ERR_INVALID_THREAD;
2632 }
2633
2634 /*
2635 * We currently have a bug where we don't successfully resume the
2636 * target thread if the suspend count is too deep. We're expected to
2637 * require one "resume" for each "suspend", but when asked to execute
2638 * a method we have to resume fully and then re-suspend it back to the
2639 * same level. (The easiest way to cause this is to type "suspend"
2640 * multiple times in jdb.)
2641 *
2642 * It's unclear what this means when the event specifies "resume all"
2643 * and some threads are suspended more deeply than others. This is
2644 * a rare problem, so for now we just prevent it from hanging forever
2645 * by rejecting the method invocation request. Without this, we will
2646 * be stuck waiting on a suspended thread.
2647 */
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002648 int suspend_count;
2649 {
Ian Rogers50b35e22012-10-04 10:09:15 -07002650 MutexLock mu2(soa.Self(), *Locks::thread_suspend_count_lock_);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002651 suspend_count = targetThread->GetSuspendCount();
2652 }
Elliott Hughesd07986f2011-12-06 18:27:45 -08002653 if (suspend_count > 1) {
2654 LOG(ERROR) << *targetThread << " suspend count too deep for method invocation: " << suspend_count;
2655 return JDWP::ERR_THREAD_SUSPENDED; // Probably not expected here.
2656 }
2657
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08002658 JDWP::JdwpError status;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002659 mirror::Object* receiver = gRegistry->Get<mirror::Object*>(object_id);
Elliott Hughes64f574f2013-02-20 14:57:12 -08002660 if (receiver == ObjectRegistry::kInvalidObject) {
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08002661 return JDWP::ERR_INVALID_OBJECT;
2662 }
Elliott Hughes45651fd2012-02-21 15:48:20 -08002663
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002664 mirror::Object* thread = gRegistry->Get<mirror::Object*>(thread_id);
Elliott Hughes64f574f2013-02-20 14:57:12 -08002665 if (thread == ObjectRegistry::kInvalidObject) {
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08002666 return JDWP::ERR_INVALID_OBJECT;
2667 }
Elliott Hughes45651fd2012-02-21 15:48:20 -08002668 // TODO: check that 'thread' is actually a java.lang.Thread!
2669
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002670 mirror::Class* c = DecodeClass(class_id, status);
Elliott Hughes45651fd2012-02-21 15:48:20 -08002671 if (c == NULL) {
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08002672 return status;
2673 }
Elliott Hughes45651fd2012-02-21 15:48:20 -08002674
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002675 mirror::AbstractMethod* m = FromMethodId(method_id);
Elliott Hughes45651fd2012-02-21 15:48:20 -08002676 if (m->IsStatic() != (receiver == NULL)) {
2677 return JDWP::ERR_INVALID_METHODID;
2678 }
2679 if (m->IsStatic()) {
2680 if (m->GetDeclaringClass() != c) {
2681 return JDWP::ERR_INVALID_METHODID;
2682 }
2683 } else {
2684 if (!m->GetDeclaringClass()->IsAssignableFrom(c)) {
2685 return JDWP::ERR_INVALID_METHODID;
2686 }
2687 }
2688
2689 // Check the argument list matches the method.
2690 MethodHelper mh(m);
2691 if (mh.GetShortyLength() - 1 != arg_count) {
2692 return JDWP::ERR_ILLEGAL_ARGUMENT;
2693 }
2694 const char* shorty = mh.GetShorty();
Elliott Hughes09201632013-04-15 15:50:07 -07002695 const DexFile::TypeList* types = mh.GetParameterTypeList();
Elliott Hughes45651fd2012-02-21 15:48:20 -08002696 for (size_t i = 0; i < arg_count; ++i) {
2697 if (shorty[i + 1] != JdwpTagToShortyChar(arg_types[i])) {
2698 return JDWP::ERR_ILLEGAL_ARGUMENT;
2699 }
Elliott Hughes09201632013-04-15 15:50:07 -07002700
2701 if (shorty[i + 1] == 'L') {
2702 // Did we really get an argument of an appropriate reference type?
2703 mirror::Class* parameter_type = mh.GetClassFromTypeIdx(types->GetTypeItem(i).type_idx_);
2704 mirror::Object* argument = gRegistry->Get<mirror::Object*>(arg_values[i]);
2705 if (argument == ObjectRegistry::kInvalidObject) {
2706 return JDWP::ERR_INVALID_OBJECT;
2707 }
2708 if (!argument->InstanceOf(parameter_type)) {
2709 return JDWP::ERR_ILLEGAL_ARGUMENT;
2710 }
2711
2712 // Turn the on-the-wire ObjectId into a jobject.
2713 jvalue& v = reinterpret_cast<jvalue&>(arg_values[i]);
2714 v.l = gRegistry->GetJObject(arg_values[i]);
2715 }
Elliott Hughes45651fd2012-02-21 15:48:20 -08002716 }
2717
2718 req->receiver_ = receiver;
2719 req->thread_ = thread;
2720 req->class_ = c;
2721 req->method_ = m;
2722 req->arg_count_ = arg_count;
2723 req->arg_values_ = arg_values;
Elliott Hughesd07986f2011-12-06 18:27:45 -08002724 req->options_ = options;
2725 req->invoke_needed_ = true;
2726 }
2727
2728 // The fact that we've released the thread list lock is a bit risky --- if the thread goes
2729 // away we're sitting high and dry -- but we must release this before the ResumeAllThreads
2730 // call, and it's unwise to hold it during WaitForSuspend.
2731
2732 {
2733 /*
2734 * We change our (JDWP thread) status, which should be THREAD_RUNNING,
Elliott Hughes81ff3182012-03-23 20:35:56 -07002735 * so we can suspend for a GC if the invoke request causes us to
Elliott Hughesd07986f2011-12-06 18:27:45 -08002736 * run out of memory. It's also a good idea to change it before locking
2737 * the invokeReq mutex, although that should never be held for long.
2738 */
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002739 self->TransitionFromRunnableToSuspended(kWaitingForDebuggerSend);
Elliott Hughesd07986f2011-12-06 18:27:45 -08002740
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08002741 VLOG(jdwp) << " Transferring control to event thread";
Elliott Hughesd07986f2011-12-06 18:27:45 -08002742 {
Ian Rogers50b35e22012-10-04 10:09:15 -07002743 MutexLock mu(self, req->lock_);
Elliott Hughesd07986f2011-12-06 18:27:45 -08002744
2745 if ((options & JDWP::INVOKE_SINGLE_THREADED) == 0) {
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08002746 VLOG(jdwp) << " Resuming all threads";
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002747 thread_list->UndoDebuggerSuspensions();
Elliott Hughesd07986f2011-12-06 18:27:45 -08002748 } else {
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08002749 VLOG(jdwp) << " Resuming event thread only";
Elliott Hughesd07986f2011-12-06 18:27:45 -08002750 thread_list->Resume(targetThread, true);
2751 }
2752
2753 // Wait for the request to finish executing.
2754 while (req->invoke_needed_) {
Ian Rogersc604d732012-10-14 16:09:54 -07002755 req->cond_.Wait(self);
Elliott Hughesd07986f2011-12-06 18:27:45 -08002756 }
2757 }
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08002758 VLOG(jdwp) << " Control has returned from event thread";
Elliott Hughesd07986f2011-12-06 18:27:45 -08002759
2760 /* wait for thread to re-suspend itself */
Elliott Hughes221229c2013-01-08 18:17:50 -08002761 SuspendThread(thread_id, false /* request_suspension */ );
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002762 self->TransitionFromSuspendedToRunnable();
Elliott Hughesd07986f2011-12-06 18:27:45 -08002763 }
2764
2765 /*
2766 * Suspend the threads. We waited for the target thread to suspend
2767 * itself, so all we need to do is suspend the others.
2768 *
2769 * The suspendAllThreads() call will double-suspend the event thread,
2770 * so we want to resume the target thread once to keep the books straight.
2771 */
2772 if ((options & JDWP::INVOKE_SINGLE_THREADED) == 0) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002773 self->TransitionFromRunnableToSuspended(kWaitingForDebuggerSuspension);
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08002774 VLOG(jdwp) << " Suspending all threads";
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002775 thread_list->SuspendAllForDebugger();
2776 self->TransitionFromSuspendedToRunnable();
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08002777 VLOG(jdwp) << " Resuming event thread to balance the count";
Elliott Hughesd07986f2011-12-06 18:27:45 -08002778 thread_list->Resume(targetThread, true);
2779 }
2780
2781 // Copy the result.
2782 *pResultTag = req->result_tag;
2783 if (IsPrimitiveTag(req->result_tag)) {
Elliott Hughesf24d3ce2012-04-11 17:43:37 -07002784 *pResultValue = req->result_value.GetJ();
Elliott Hughesd07986f2011-12-06 18:27:45 -08002785 } else {
Elliott Hughesf24d3ce2012-04-11 17:43:37 -07002786 *pResultValue = gRegistry->Add(req->result_value.GetL());
Elliott Hughesd07986f2011-12-06 18:27:45 -08002787 }
2788 *pExceptionId = req->exception;
2789 return req->error;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002790}
2791
2792void Dbg::ExecuteMethod(DebugInvokeReq* pReq) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002793 ScopedObjectAccess soa(Thread::Current());
Elliott Hughesd07986f2011-12-06 18:27:45 -08002794
Elliott Hughes81ff3182012-03-23 20:35:56 -07002795 // We can be called while an exception is pending. We need
Elliott Hughesd07986f2011-12-06 18:27:45 -08002796 // to preserve that across the method invocation.
Ian Rogers62d6c772013-02-27 08:32:07 -08002797 SirtRef<mirror::Object> old_throw_this_object(soa.Self(), NULL);
2798 SirtRef<mirror::AbstractMethod> old_throw_method(soa.Self(), NULL);
2799 SirtRef<mirror::Throwable> old_exception(soa.Self(), NULL);
2800 uint32_t old_throw_dex_pc;
2801 {
2802 ThrowLocation old_throw_location;
2803 mirror::Throwable* old_exception_obj = soa.Self()->GetException(&old_throw_location);
2804 old_throw_this_object.reset(old_throw_location.GetThis());
2805 old_throw_method.reset(old_throw_location.GetMethod());
2806 old_exception.reset(old_exception_obj);
2807 old_throw_dex_pc = old_throw_location.GetDexPc();
2808 soa.Self()->ClearException();
2809 }
Elliott Hughesd07986f2011-12-06 18:27:45 -08002810
2811 // Translate the method through the vtable, unless the debugger wants to suppress it.
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002812 mirror::AbstractMethod* m = pReq->method_;
Elliott Hughesd07986f2011-12-06 18:27:45 -08002813 if ((pReq->options_ & JDWP::INVOKE_NONVIRTUAL) == 0 && pReq->receiver_ != NULL) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002814 mirror::AbstractMethod* actual_method = pReq->class_->FindVirtualMethodForVirtualOrInterface(pReq->method_);
Elliott Hughes45651fd2012-02-21 15:48:20 -08002815 if (actual_method != m) {
2816 VLOG(jdwp) << "ExecuteMethod translated " << PrettyMethod(m) << " to " << PrettyMethod(actual_method);
2817 m = actual_method;
2818 }
Elliott Hughesd07986f2011-12-06 18:27:45 -08002819 }
Elliott Hughescfa9cfa2013-04-16 16:52:01 -07002820 VLOG(jdwp) << "ExecuteMethod " << PrettyMethod(m)
2821 << " receiver=" << pReq->receiver_
2822 << " arg_count=" << pReq->arg_count_;
Elliott Hughesd07986f2011-12-06 18:27:45 -08002823 CHECK(m != NULL);
2824
2825 CHECK_EQ(sizeof(jvalue), sizeof(uint64_t));
2826
Jeff Hao5d917302013-02-27 17:57:33 -08002827 MethodHelper mh(m);
2828 ArgArray arg_array(mh.GetShorty(), mh.GetShortyLength());
2829 arg_array.BuildArgArray(soa, pReq->receiver_, reinterpret_cast<jvalue*>(pReq->arg_values_));
Jeff Hao6474d192013-03-26 14:08:09 -07002830 InvokeWithArgArray(soa, m, &arg_array, &pReq->result_value, mh.GetShorty()[0]);
Elliott Hughesd07986f2011-12-06 18:27:45 -08002831
Ian Rogers62d6c772013-02-27 08:32:07 -08002832 mirror::Throwable* exception = soa.Self()->GetException(NULL);
2833 soa.Self()->ClearException();
2834 pReq->exception = gRegistry->Add(exception);
Elliott Hughesd07986f2011-12-06 18:27:45 -08002835 pReq->result_tag = BasicTagFromDescriptor(MethodHelper(m).GetShorty());
2836 if (pReq->exception != 0) {
Ian Rogers62d6c772013-02-27 08:32:07 -08002837 VLOG(jdwp) << " JDWP invocation returning with exception=" << exception
2838 << " " << exception->Dump();
Elliott Hughesf24d3ce2012-04-11 17:43:37 -07002839 pReq->result_value.SetJ(0);
Elliott Hughesd07986f2011-12-06 18:27:45 -08002840 } else if (pReq->result_tag == JDWP::JT_OBJECT) {
2841 /* if no exception thrown, examine object result more closely */
Elliott Hughesf24d3ce2012-04-11 17:43:37 -07002842 JDWP::JdwpTag new_tag = TagFromObject(pReq->result_value.GetL());
Elliott Hughesd07986f2011-12-06 18:27:45 -08002843 if (new_tag != pReq->result_tag) {
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08002844 VLOG(jdwp) << " JDWP promoted result from " << pReq->result_tag << " to " << new_tag;
Elliott Hughesd07986f2011-12-06 18:27:45 -08002845 pReq->result_tag = new_tag;
2846 }
2847
2848 /*
2849 * Register the object. We don't actually need an ObjectId yet,
2850 * but we do need to be sure that the GC won't move or discard the
2851 * object when we switch out of RUNNING. The ObjectId conversion
2852 * will add the object to the "do not touch" list.
2853 *
2854 * We can't use the "tracked allocation" mechanism here because
2855 * the object is going to be handed off to a different thread.
2856 */
Elliott Hughesf24d3ce2012-04-11 17:43:37 -07002857 gRegistry->Add(pReq->result_value.GetL());
Elliott Hughesd07986f2011-12-06 18:27:45 -08002858 }
2859
2860 if (old_exception.get() != NULL) {
Ian Rogers62d6c772013-02-27 08:32:07 -08002861 ThrowLocation gc_safe_throw_location(old_throw_this_object.get(), old_throw_method.get(),
2862 old_throw_dex_pc);
2863 soa.Self()->SetException(gc_safe_throw_location, old_exception.get());
Elliott Hughesd07986f2011-12-06 18:27:45 -08002864 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002865}
2866
Elliott Hughesd07986f2011-12-06 18:27:45 -08002867/*
Elliott Hughes4b9702c2013-02-20 18:13:24 -08002868 * "request" contains a full JDWP packet, possibly with multiple chunks. We
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07002869 * need to process each, accumulate the replies, and ship the whole thing
2870 * back.
2871 *
2872 * Returns "true" if we have a reply. The reply buffer is newly allocated,
2873 * and includes the chunk type/length, followed by the data.
2874 *
Elliott Hughes3d30d9b2011-12-07 17:35:48 -08002875 * OLD-TODO: we currently assume that the request and reply include a single
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07002876 * chunk. If this becomes inconvenient we will need to adapt.
2877 */
Elliott Hughes4b9702c2013-02-20 18:13:24 -08002878bool Dbg::DdmHandlePacket(JDWP::Request& request, uint8_t** pReplyBuf, int* pReplyLen) {
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07002879 Thread* self = Thread::Current();
2880 JNIEnv* env = self->GetJniEnv();
2881
Elliott Hughes4b9702c2013-02-20 18:13:24 -08002882 uint32_t type = request.ReadUnsigned32("type");
2883 uint32_t length = request.ReadUnsigned32("length");
2884
2885 // Create a byte[] corresponding to 'request'.
2886 size_t request_length = request.size();
2887 ScopedLocalRef<jbyteArray> dataArray(env, env->NewByteArray(request_length));
Elliott Hughes6a5bd492011-10-28 14:33:57 -07002888 if (dataArray.get() == NULL) {
Elliott Hughes4b9702c2013-02-20 18:13:24 -08002889 LOG(WARNING) << "byte[] allocation failed: " << request_length;
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07002890 env->ExceptionClear();
2891 return false;
2892 }
Elliott Hughes4b9702c2013-02-20 18:13:24 -08002893 env->SetByteArrayRegion(dataArray.get(), 0, request_length, reinterpret_cast<const jbyte*>(request.data()));
2894 request.Skip(request_length);
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07002895
2896 // Run through and find all chunks. [Currently just find the first.]
Elliott Hughes6a5bd492011-10-28 14:33:57 -07002897 ScopedByteArrayRO contents(env, dataArray.get());
Elliott Hughes4b9702c2013-02-20 18:13:24 -08002898 if (length != request_length) {
2899 LOG(WARNING) << StringPrintf("bad chunk found (len=%u pktLen=%d)", length, request_length);
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07002900 return false;
2901 }
2902
2903 // Call "private static Chunk dispatch(int type, byte[] data, int offset, int length)".
Elliott Hugheseac76672012-05-24 21:56:51 -07002904 ScopedLocalRef<jobject> chunk(env, env->CallStaticObjectMethod(WellKnownClasses::org_apache_harmony_dalvik_ddmc_DdmServer,
2905 WellKnownClasses::org_apache_harmony_dalvik_ddmc_DdmServer_dispatch,
Elliott Hughes4b9702c2013-02-20 18:13:24 -08002906 type, dataArray.get(), 0, length));
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07002907 if (env->ExceptionCheck()) {
2908 LOG(INFO) << StringPrintf("Exception thrown by dispatcher for 0x%08x", type);
2909 env->ExceptionDescribe();
2910 env->ExceptionClear();
2911 return false;
2912 }
2913
Elliott Hughes6a5bd492011-10-28 14:33:57 -07002914 if (chunk.get() == NULL) {
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07002915 return false;
2916 }
2917
2918 /*
2919 * Pull the pieces out of the chunk. We copy the results into a
2920 * newly-allocated buffer that the caller can free. We don't want to
2921 * continue using the Chunk object because nothing has a reference to it.
2922 *
2923 * We could avoid this by returning type/data/offset/length and having
2924 * the caller be aware of the object lifetime issues, but that
Elliott Hughes81ff3182012-03-23 20:35:56 -07002925 * integrates the JDWP code more tightly into the rest of the runtime, and doesn't work
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07002926 * if we have responses for multiple chunks.
2927 *
2928 * So we're pretty much stuck with copying data around multiple times.
2929 */
Elliott Hugheseac76672012-05-24 21:56:51 -07002930 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 -08002931 jint offset = env->GetIntField(chunk.get(), WellKnownClasses::org_apache_harmony_dalvik_ddmc_Chunk_offset);
Elliott Hugheseac76672012-05-24 21:56:51 -07002932 length = env->GetIntField(chunk.get(), WellKnownClasses::org_apache_harmony_dalvik_ddmc_Chunk_length);
Elliott Hugheseac76672012-05-24 21:56:51 -07002933 type = env->GetIntField(chunk.get(), WellKnownClasses::org_apache_harmony_dalvik_ddmc_Chunk_type);
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07002934
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08002935 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 -07002936 if (length == 0 || replyData.get() == NULL) {
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07002937 return false;
2938 }
2939
Elliott Hughes4b9702c2013-02-20 18:13:24 -08002940 const int kChunkHdrLen = 8;
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07002941 uint8_t* reply = new uint8_t[length + kChunkHdrLen];
2942 if (reply == NULL) {
2943 LOG(WARNING) << "malloc failed: " << (length + kChunkHdrLen);
2944 return false;
2945 }
Elliott Hughesf7c3b662011-10-27 12:04:56 -07002946 JDWP::Set4BE(reply + 0, type);
2947 JDWP::Set4BE(reply + 4, length);
Elliott Hughes6a5bd492011-10-28 14:33:57 -07002948 env->GetByteArrayRegion(replyData.get(), offset, length, reinterpret_cast<jbyte*>(reply + kChunkHdrLen));
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07002949
2950 *pReplyBuf = reply;
2951 *pReplyLen = length + kChunkHdrLen;
2952
Elliott Hughes4b9702c2013-02-20 18:13:24 -08002953 VLOG(jdwp) << StringPrintf("dvmHandleDdm returning type=%.4s %p len=%d", reinterpret_cast<char*>(reply), reply, length);
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07002954 return true;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002955}
2956
Elliott Hughesa2155262011-11-16 16:26:58 -08002957void Dbg::DdmBroadcast(bool connect) {
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08002958 VLOG(jdwp) << "Broadcasting DDM " << (connect ? "connect" : "disconnect") << "...";
Elliott Hughes47fce012011-10-25 18:37:19 -07002959
2960 Thread* self = Thread::Current();
Ian Rogers50b35e22012-10-04 10:09:15 -07002961 if (self->GetState() != kRunnable) {
2962 LOG(ERROR) << "DDM broadcast in thread state " << self->GetState();
2963 /* try anyway? */
Elliott Hughes47fce012011-10-25 18:37:19 -07002964 }
2965
2966 JNIEnv* env = self->GetJniEnv();
Elliott Hughes47fce012011-10-25 18:37:19 -07002967 jint event = connect ? 1 /*DdmServer.CONNECTED*/ : 2 /*DdmServer.DISCONNECTED*/;
Elliott Hugheseac76672012-05-24 21:56:51 -07002968 env->CallStaticVoidMethod(WellKnownClasses::org_apache_harmony_dalvik_ddmc_DdmServer,
2969 WellKnownClasses::org_apache_harmony_dalvik_ddmc_DdmServer_broadcast,
2970 event);
Elliott Hughes47fce012011-10-25 18:37:19 -07002971 if (env->ExceptionCheck()) {
2972 LOG(ERROR) << "DdmServer.broadcast " << event << " failed";
2973 env->ExceptionDescribe();
2974 env->ExceptionClear();
2975 }
2976}
2977
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002978void Dbg::DdmConnected() {
Elliott Hughesa2155262011-11-16 16:26:58 -08002979 Dbg::DdmBroadcast(true);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002980}
2981
2982void Dbg::DdmDisconnected() {
Elliott Hughesa2155262011-11-16 16:26:58 -08002983 Dbg::DdmBroadcast(false);
Elliott Hughes47fce012011-10-25 18:37:19 -07002984 gDdmThreadNotification = false;
2985}
2986
2987/*
Elliott Hughes82188472011-11-07 18:11:48 -08002988 * Send a notification when a thread starts, stops, or changes its name.
Elliott Hughes47fce012011-10-25 18:37:19 -07002989 *
2990 * Because we broadcast the full set of threads when the notifications are
2991 * first enabled, it's possible for "thread" to be actively executing.
2992 */
Elliott Hughes82188472011-11-07 18:11:48 -08002993void Dbg::DdmSendThreadNotification(Thread* t, uint32_t type) {
Elliott Hughes47fce012011-10-25 18:37:19 -07002994 if (!gDdmThreadNotification) {
2995 return;
2996 }
2997
Elliott Hughes82188472011-11-07 18:11:48 -08002998 if (type == CHUNK_TYPE("THDE")) {
Elliott Hughes47fce012011-10-25 18:37:19 -07002999 uint8_t buf[4];
Elliott Hughesf7c3b662011-10-27 12:04:56 -07003000 JDWP::Set4BE(&buf[0], t->GetThinLockId());
Elliott Hughes47fce012011-10-25 18:37:19 -07003001 Dbg::DdmSendChunk(CHUNK_TYPE("THDE"), 4, buf);
Elliott Hughes82188472011-11-07 18:11:48 -08003002 } else {
3003 CHECK(type == CHUNK_TYPE("THCR") || type == CHUNK_TYPE("THNM")) << type;
Ian Rogers00f7d0e2012-07-19 15:28:27 -07003004 ScopedObjectAccessUnchecked soa(Thread::Current());
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003005 SirtRef<mirror::String> name(soa.Self(), t->GetThreadName(soa));
Elliott Hughes82188472011-11-07 18:11:48 -08003006 size_t char_count = (name.get() != NULL) ? name->GetLength() : 0;
jeffhao725a9572012-11-13 18:20:12 -08003007 const jchar* chars = (name.get() != NULL) ? name->GetCharArray()->GetData() : NULL;
Elliott Hughes82188472011-11-07 18:11:48 -08003008
Elliott Hughes21f32d72011-11-09 17:44:13 -08003009 std::vector<uint8_t> bytes;
Elliott Hughes545a0642011-11-08 19:10:03 -08003010 JDWP::Append4BE(bytes, t->GetThinLockId());
3011 JDWP::AppendUtf16BE(bytes, chars, char_count);
Elliott Hughes21f32d72011-11-09 17:44:13 -08003012 CHECK_EQ(bytes.size(), char_count*2 + sizeof(uint32_t)*2);
3013 Dbg::DdmSendChunk(type, bytes);
Elliott Hughes47fce012011-10-25 18:37:19 -07003014 }
3015}
3016
Elliott Hughes47fce012011-10-25 18:37:19 -07003017void Dbg::DdmSetThreadNotification(bool enable) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07003018 // Enable/disable thread notifications.
Elliott Hughes47fce012011-10-25 18:37:19 -07003019 gDdmThreadNotification = enable;
3020 if (enable) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07003021 // Suspend the VM then post thread start notifications for all threads. Threads attaching will
3022 // see a suspension in progress and block until that ends. They then post their own start
3023 // notification.
3024 SuspendVM();
3025 std::list<Thread*> threads;
Ian Rogers50b35e22012-10-04 10:09:15 -07003026 Thread* self = Thread::Current();
Ian Rogers00f7d0e2012-07-19 15:28:27 -07003027 {
Ian Rogers50b35e22012-10-04 10:09:15 -07003028 MutexLock mu(self, *Locks::thread_list_lock_);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07003029 threads = Runtime::Current()->GetThreadList()->GetList();
3030 }
3031 {
Ian Rogers50b35e22012-10-04 10:09:15 -07003032 ScopedObjectAccess soa(self);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07003033 typedef std::list<Thread*>::const_iterator It; // TODO: C++0x auto
3034 for (It it = threads.begin(), end = threads.end(); it != end; ++it) {
3035 Dbg::DdmSendThreadNotification(*it, CHUNK_TYPE("THCR"));
3036 }
3037 }
3038 ResumeVM();
Elliott Hughes47fce012011-10-25 18:37:19 -07003039 }
3040}
3041
Elliott Hughesa2155262011-11-16 16:26:58 -08003042void Dbg::PostThreadStartOrStop(Thread* t, uint32_t type) {
Elliott Hughesc0f09332012-03-26 13:27:06 -07003043 if (IsDebuggerActive()) {
Mathieu Chartierdbe6f462012-09-25 16:54:50 -07003044 ScopedObjectAccessUnchecked soa(Thread::Current());
Ian Rogerscfaa4552012-11-26 21:00:08 -08003045 JDWP::ObjectId id = gRegistry->Add(t->GetPeer());
Elliott Hughes82188472011-11-07 18:11:48 -08003046 gJdwpState->PostThreadChange(id, type == CHUNK_TYPE("THCR"));
Elliott Hughes47fce012011-10-25 18:37:19 -07003047 }
Elliott Hughes82188472011-11-07 18:11:48 -08003048 Dbg::DdmSendThreadNotification(t, type);
Elliott Hughes47fce012011-10-25 18:37:19 -07003049}
3050
3051void Dbg::PostThreadStart(Thread* t) {
Elliott Hughesa2155262011-11-16 16:26:58 -08003052 Dbg::PostThreadStartOrStop(t, CHUNK_TYPE("THCR"));
Elliott Hughes47fce012011-10-25 18:37:19 -07003053}
3054
3055void Dbg::PostThreadDeath(Thread* t) {
Elliott Hughesa2155262011-11-16 16:26:58 -08003056 Dbg::PostThreadStartOrStop(t, CHUNK_TYPE("THDE"));
Elliott Hughes872d4ec2011-10-21 17:07:15 -07003057}
3058
Elliott Hughes82188472011-11-07 18:11:48 -08003059void Dbg::DdmSendChunk(uint32_t type, size_t byte_count, const uint8_t* buf) {
Elliott Hughes3bb81562011-10-21 18:52:59 -07003060 CHECK(buf != NULL);
3061 iovec vec[1];
3062 vec[0].iov_base = reinterpret_cast<void*>(const_cast<uint8_t*>(buf));
3063 vec[0].iov_len = byte_count;
3064 Dbg::DdmSendChunkV(type, vec, 1);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07003065}
3066
Elliott Hughes21f32d72011-11-09 17:44:13 -08003067void Dbg::DdmSendChunk(uint32_t type, const std::vector<uint8_t>& bytes) {
3068 DdmSendChunk(type, bytes.size(), &bytes[0]);
3069}
3070
Elliott Hughescccd84f2011-12-05 16:51:54 -08003071void Dbg::DdmSendChunkV(uint32_t type, const struct iovec* iov, int iov_count) {
Elliott Hughes3bb81562011-10-21 18:52:59 -07003072 if (gJdwpState == NULL) {
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08003073 VLOG(jdwp) << "Debugger thread not active, ignoring DDM send: " << type;
Elliott Hughes3bb81562011-10-21 18:52:59 -07003074 } else {
Elliott Hughescccd84f2011-12-05 16:51:54 -08003075 gJdwpState->DdmSendChunkV(type, iov, iov_count);
Elliott Hughes3bb81562011-10-21 18:52:59 -07003076 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -07003077}
3078
Elliott Hughes767a1472011-10-26 18:49:02 -07003079int Dbg::DdmHandleHpifChunk(HpifWhen when) {
3080 if (when == HPIF_WHEN_NOW) {
Elliott Hughes7162ad92011-10-27 14:08:42 -07003081 DdmSendHeapInfo(when);
Elliott Hughes767a1472011-10-26 18:49:02 -07003082 return true;
3083 }
3084
3085 if (when != HPIF_WHEN_NEVER && when != HPIF_WHEN_NEXT_GC && when != HPIF_WHEN_EVERY_GC) {
3086 LOG(ERROR) << "invalid HpifWhen value: " << static_cast<int>(when);
3087 return false;
3088 }
3089
3090 gDdmHpifWhen = when;
3091 return true;
3092}
3093
3094bool Dbg::DdmHandleHpsgNhsgChunk(Dbg::HpsgWhen when, Dbg::HpsgWhat what, bool native) {
3095 if (when != HPSG_WHEN_NEVER && when != HPSG_WHEN_EVERY_GC) {
3096 LOG(ERROR) << "invalid HpsgWhen value: " << static_cast<int>(when);
3097 return false;
3098 }
3099
3100 if (what != HPSG_WHAT_MERGED_OBJECTS && what != HPSG_WHAT_DISTINCT_OBJECTS) {
3101 LOG(ERROR) << "invalid HpsgWhat value: " << static_cast<int>(what);
3102 return false;
3103 }
3104
3105 if (native) {
3106 gDdmNhsgWhen = when;
3107 gDdmNhsgWhat = what;
3108 } else {
3109 gDdmHpsgWhen = when;
3110 gDdmHpsgWhat = what;
3111 }
3112 return true;
3113}
3114
Elliott Hughes7162ad92011-10-27 14:08:42 -07003115void Dbg::DdmSendHeapInfo(HpifWhen reason) {
3116 // If there's a one-shot 'when', reset it.
3117 if (reason == gDdmHpifWhen) {
3118 if (gDdmHpifWhen == HPIF_WHEN_NEXT_GC) {
3119 gDdmHpifWhen = HPIF_WHEN_NEVER;
3120 }
3121 }
3122
3123 /*
3124 * Chunk HPIF (client --> server)
3125 *
3126 * Heap Info. General information about the heap,
3127 * suitable for a summary display.
3128 *
3129 * [u4]: number of heaps
3130 *
3131 * For each heap:
3132 * [u4]: heap ID
3133 * [u8]: timestamp in ms since Unix epoch
3134 * [u1]: capture reason (same as 'when' value from server)
3135 * [u4]: max heap size in bytes (-Xmx)
3136 * [u4]: current heap size in bytes
3137 * [u4]: current number of bytes allocated
3138 * [u4]: current number of objects allocated
3139 */
3140 uint8_t heap_count = 1;
Ian Rogers1d54e732013-05-02 21:10:01 -07003141 gc::Heap* heap = Runtime::Current()->GetHeap();
Elliott Hughes21f32d72011-11-09 17:44:13 -08003142 std::vector<uint8_t> bytes;
Elliott Hughes545a0642011-11-08 19:10:03 -08003143 JDWP::Append4BE(bytes, heap_count);
3144 JDWP::Append4BE(bytes, 1); // Heap id (bogus; we only have one heap).
3145 JDWP::Append8BE(bytes, MilliTime());
3146 JDWP::Append1BE(bytes, reason);
Elliott Hughesb3bd5f02012-03-08 21:05:27 -08003147 JDWP::Append4BE(bytes, heap->GetMaxMemory()); // Max allowed heap size in bytes.
3148 JDWP::Append4BE(bytes, heap->GetTotalMemory()); // Current heap size in bytes.
3149 JDWP::Append4BE(bytes, heap->GetBytesAllocated());
3150 JDWP::Append4BE(bytes, heap->GetObjectsAllocated());
Elliott Hughes21f32d72011-11-09 17:44:13 -08003151 CHECK_EQ(bytes.size(), 4U + (heap_count * (4 + 8 + 1 + 4 + 4 + 4 + 4)));
3152 Dbg::DdmSendChunk(CHUNK_TYPE("HPIF"), bytes);
Elliott Hughes767a1472011-10-26 18:49:02 -07003153}
3154
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003155enum HpsgSolidity {
3156 SOLIDITY_FREE = 0,
3157 SOLIDITY_HARD = 1,
3158 SOLIDITY_SOFT = 2,
3159 SOLIDITY_WEAK = 3,
3160 SOLIDITY_PHANTOM = 4,
3161 SOLIDITY_FINALIZABLE = 5,
3162 SOLIDITY_SWEEP = 6,
3163};
3164
3165enum HpsgKind {
3166 KIND_OBJECT = 0,
3167 KIND_CLASS_OBJECT = 1,
3168 KIND_ARRAY_1 = 2,
3169 KIND_ARRAY_2 = 3,
3170 KIND_ARRAY_4 = 4,
3171 KIND_ARRAY_8 = 5,
3172 KIND_UNKNOWN = 6,
3173 KIND_NATIVE = 7,
3174};
3175
3176#define HPSG_PARTIAL (1<<7)
3177#define HPSG_STATE(solidity, kind) ((uint8_t)((((kind) & 0x7) << 3) | ((solidity) & 0x7)))
3178
Ian Rogers30fab402012-01-23 15:43:46 -08003179class HeapChunkContext {
3180 public:
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003181 // Maximum chunk size. Obtain this from the formula:
3182 // (((maximum_heap_size / ALLOCATION_UNIT_SIZE) + 255) / 256) * 2
3183 HeapChunkContext(bool merge, bool native)
Ian Rogers30fab402012-01-23 15:43:46 -08003184 : buf_(16384 - 16),
3185 type_(0),
3186 merge_(merge) {
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003187 Reset();
3188 if (native) {
Ian Rogers30fab402012-01-23 15:43:46 -08003189 type_ = CHUNK_TYPE("NHSG");
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003190 } else {
Ian Rogers30fab402012-01-23 15:43:46 -08003191 type_ = merge ? CHUNK_TYPE("HPSG") : CHUNK_TYPE("HPSO");
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003192 }
3193 }
3194
3195 ~HeapChunkContext() {
Ian Rogers30fab402012-01-23 15:43:46 -08003196 if (p_ > &buf_[0]) {
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003197 Flush();
3198 }
3199 }
3200
3201 void EnsureHeader(const void* chunk_ptr) {
Ian Rogers30fab402012-01-23 15:43:46 -08003202 if (!needHeader_) {
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003203 return;
3204 }
3205
3206 // Start a new HPSx chunk.
Ian Rogers30fab402012-01-23 15:43:46 -08003207 JDWP::Write4BE(&p_, 1); // Heap id (bogus; we only have one heap).
3208 JDWP::Write1BE(&p_, 8); // Size of allocation unit, in bytes.
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003209
Ian Rogers30fab402012-01-23 15:43:46 -08003210 JDWP::Write4BE(&p_, reinterpret_cast<uintptr_t>(chunk_ptr)); // virtual address of segment start.
3211 JDWP::Write4BE(&p_, 0); // offset of this piece (relative to the virtual address).
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003212 // [u4]: length of piece, in allocation units
3213 // 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 -08003214 pieceLenField_ = p_;
3215 JDWP::Write4BE(&p_, 0x55555555);
3216 needHeader_ = false;
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003217 }
3218
Ian Rogersb726dcb2012-09-05 08:57:23 -07003219 void Flush() SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Ian Rogersd636b062013-01-18 17:51:18 -08003220 if (pieceLenField_ == NULL) {
3221 // Flush immediately post Reset (maybe back-to-back Flush). Ignore.
3222 CHECK(needHeader_);
3223 return;
3224 }
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003225 // Patch the "length of piece" field.
Ian Rogers30fab402012-01-23 15:43:46 -08003226 CHECK_LE(&buf_[0], pieceLenField_);
3227 CHECK_LE(pieceLenField_, p_);
3228 JDWP::Set4BE(pieceLenField_, totalAllocationUnits_);
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003229
Ian Rogers30fab402012-01-23 15:43:46 -08003230 Dbg::DdmSendChunk(type_, p_ - &buf_[0], &buf_[0]);
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003231 Reset();
3232 }
3233
Ian Rogers00f7d0e2012-07-19 15:28:27 -07003234 static void HeapChunkCallback(void* start, void* end, size_t used_bytes, void* arg)
Ian Rogersb726dcb2012-09-05 08:57:23 -07003235 SHARED_LOCKS_REQUIRED(Locks::heap_bitmap_lock_,
3236 Locks::mutator_lock_) {
Ian Rogers30fab402012-01-23 15:43:46 -08003237 reinterpret_cast<HeapChunkContext*>(arg)->HeapChunkCallback(start, end, used_bytes);
Elliott Hughesa2155262011-11-16 16:26:58 -08003238 }
3239
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003240 private:
Elliott Hughesa2155262011-11-16 16:26:58 -08003241 enum { ALLOCATION_UNIT_SIZE = 8 };
3242
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003243 void Reset() {
Ian Rogers30fab402012-01-23 15:43:46 -08003244 p_ = &buf_[0];
Ian Rogers15bf2d32012-08-28 17:33:04 -07003245 startOfNextMemoryChunk_ = NULL;
Ian Rogers30fab402012-01-23 15:43:46 -08003246 totalAllocationUnits_ = 0;
3247 needHeader_ = true;
3248 pieceLenField_ = NULL;
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003249 }
3250
Ian Rogers00f7d0e2012-07-19 15:28:27 -07003251 void HeapChunkCallback(void* start, void* /*end*/, size_t used_bytes)
Ian Rogersb726dcb2012-09-05 08:57:23 -07003252 SHARED_LOCKS_REQUIRED(Locks::heap_bitmap_lock_,
3253 Locks::mutator_lock_) {
Ian Rogers30fab402012-01-23 15:43:46 -08003254 // Note: heap call backs cannot manipulate the heap upon which they are crawling, care is taken
3255 // in the following code not to allocate memory, by ensuring buf_ is of the correct size
Ian Rogers15bf2d32012-08-28 17:33:04 -07003256 if (used_bytes == 0) {
3257 if (start == NULL) {
3258 // Reset for start of new heap.
3259 startOfNextMemoryChunk_ = NULL;
3260 Flush();
3261 }
3262 // Only process in use memory so that free region information
3263 // also includes dlmalloc book keeping.
Elliott Hughesa2155262011-11-16 16:26:58 -08003264 return;
Elliott Hughesa2155262011-11-16 16:26:58 -08003265 }
3266
Ian Rogers15bf2d32012-08-28 17:33:04 -07003267 /* If we're looking at the native heap, we'll just return
3268 * (SOLIDITY_HARD, KIND_NATIVE) for all allocated chunks
3269 */
3270 bool native = type_ == CHUNK_TYPE("NHSG");
3271
3272 if (startOfNextMemoryChunk_ != NULL) {
3273 // Transmit any pending free memory. Native free memory of
3274 // over kMaxFreeLen could be because of the use of mmaps, so
3275 // don't report. If not free memory then start a new segment.
3276 bool flush = true;
3277 if (start > startOfNextMemoryChunk_) {
3278 const size_t kMaxFreeLen = 2 * kPageSize;
3279 void* freeStart = startOfNextMemoryChunk_;
3280 void* freeEnd = start;
3281 size_t freeLen = (char*)freeEnd - (char*)freeStart;
3282 if (!native || freeLen < kMaxFreeLen) {
3283 AppendChunk(HPSG_STATE(SOLIDITY_FREE, 0), freeStart, freeLen);
3284 flush = false;
3285 }
3286 }
3287 if (flush) {
3288 startOfNextMemoryChunk_ = NULL;
3289 Flush();
3290 }
3291 }
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003292 const mirror::Object* obj = reinterpret_cast<const mirror::Object*>(start);
Elliott Hughesa2155262011-11-16 16:26:58 -08003293
3294 // Determine the type of this chunk.
3295 // OLD-TODO: if context.merge, see if this chunk is different from the last chunk.
3296 // If it's the same, we should combine them.
Ian Rogers15bf2d32012-08-28 17:33:04 -07003297 uint8_t state = ExamineObject(obj, native);
3298 // dlmalloc's chunk header is 2 * sizeof(size_t), but if the previous chunk is in use for an
3299 // allocation then the first sizeof(size_t) may belong to it.
3300 const size_t dlMallocOverhead = sizeof(size_t);
3301 AppendChunk(state, start, used_bytes + dlMallocOverhead);
3302 startOfNextMemoryChunk_ = (char*)start + used_bytes + dlMallocOverhead;
3303 }
Elliott Hughesa2155262011-11-16 16:26:58 -08003304
Ian Rogers15bf2d32012-08-28 17:33:04 -07003305 void AppendChunk(uint8_t state, void* ptr, size_t length)
Ian Rogersb726dcb2012-09-05 08:57:23 -07003306 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Ian Rogers15bf2d32012-08-28 17:33:04 -07003307 // Make sure there's enough room left in the buffer.
3308 // We need to use two bytes for every fractional 256 allocation units used by the chunk plus
3309 // 17 bytes for any header.
3310 size_t needed = (((length/ALLOCATION_UNIT_SIZE + 255) / 256) * 2) + 17;
3311 size_t bytesLeft = buf_.size() - (size_t)(p_ - &buf_[0]);
3312 if (bytesLeft < needed) {
3313 Flush();
3314 }
3315
3316 bytesLeft = buf_.size() - (size_t)(p_ - &buf_[0]);
3317 if (bytesLeft < needed) {
3318 LOG(WARNING) << "Chunk is too big to transmit (chunk_len=" << length << ", "
3319 << needed << " bytes)";
3320 return;
3321 }
3322 EnsureHeader(ptr);
Elliott Hughesa2155262011-11-16 16:26:58 -08003323 // Write out the chunk description.
Ian Rogers15bf2d32012-08-28 17:33:04 -07003324 length /= ALLOCATION_UNIT_SIZE; // Convert to allocation units.
3325 totalAllocationUnits_ += length;
3326 while (length > 256) {
Ian Rogers30fab402012-01-23 15:43:46 -08003327 *p_++ = state | HPSG_PARTIAL;
3328 *p_++ = 255; // length - 1
Ian Rogers15bf2d32012-08-28 17:33:04 -07003329 length -= 256;
Elliott Hughesa2155262011-11-16 16:26:58 -08003330 }
Ian Rogers30fab402012-01-23 15:43:46 -08003331 *p_++ = state;
Ian Rogers15bf2d32012-08-28 17:33:04 -07003332 *p_++ = length - 1;
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003333 }
3334
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003335 uint8_t ExamineObject(const mirror::Object* o, bool is_native_heap)
Ian Rogersb726dcb2012-09-05 08:57:23 -07003336 SHARED_LOCKS_REQUIRED(Locks::heap_bitmap_lock_) {
Elliott Hughesa2155262011-11-16 16:26:58 -08003337 if (o == NULL) {
3338 return HPSG_STATE(SOLIDITY_FREE, 0);
3339 }
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003340
Elliott Hughesa2155262011-11-16 16:26:58 -08003341 // It's an allocated chunk. Figure out what it is.
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003342
Elliott Hughesa2155262011-11-16 16:26:58 -08003343 // If we're looking at the native heap, we'll just return
3344 // (SOLIDITY_HARD, KIND_NATIVE) for all allocated chunks.
Ian Rogers00f7d0e2012-07-19 15:28:27 -07003345 if (is_native_heap) {
Elliott Hughesa2155262011-11-16 16:26:58 -08003346 return HPSG_STATE(SOLIDITY_HARD, KIND_NATIVE);
3347 }
3348
Ian Rogers5bfa60f2012-09-02 21:17:56 -07003349 if (!Runtime::Current()->GetHeap()->IsLiveObjectLocked(o)) {
Ian Rogers15bf2d32012-08-28 17:33:04 -07003350 return HPSG_STATE(SOLIDITY_HARD, KIND_NATIVE);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07003351 }
3352
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003353 mirror::Class* c = o->GetClass();
Elliott Hughesa2155262011-11-16 16:26:58 -08003354 if (c == NULL) {
3355 // The object was probably just created but hasn't been initialized yet.
3356 return HPSG_STATE(SOLIDITY_HARD, KIND_OBJECT);
3357 }
3358
Elliott Hughesb3bd5f02012-03-08 21:05:27 -08003359 if (!Runtime::Current()->GetHeap()->IsHeapAddress(c)) {
Ian Rogers15bf2d32012-08-28 17:33:04 -07003360 LOG(ERROR) << "Invalid class for managed heap object: " << o << " " << c;
Elliott Hughesa2155262011-11-16 16:26:58 -08003361 return HPSG_STATE(SOLIDITY_HARD, KIND_UNKNOWN);
3362 }
3363
3364 if (c->IsClassClass()) {
3365 return HPSG_STATE(SOLIDITY_HARD, KIND_CLASS_OBJECT);
3366 }
3367
3368 if (c->IsArrayClass()) {
3369 if (o->IsObjectArray()) {
3370 return HPSG_STATE(SOLIDITY_HARD, KIND_ARRAY_4);
3371 }
3372 switch (c->GetComponentSize()) {
3373 case 1: return HPSG_STATE(SOLIDITY_HARD, KIND_ARRAY_1);
3374 case 2: return HPSG_STATE(SOLIDITY_HARD, KIND_ARRAY_2);
3375 case 4: return HPSG_STATE(SOLIDITY_HARD, KIND_ARRAY_4);
3376 case 8: return HPSG_STATE(SOLIDITY_HARD, KIND_ARRAY_8);
3377 }
3378 }
3379
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003380 return HPSG_STATE(SOLIDITY_HARD, KIND_OBJECT);
3381 }
3382
Ian Rogers30fab402012-01-23 15:43:46 -08003383 std::vector<uint8_t> buf_;
3384 uint8_t* p_;
3385 uint8_t* pieceLenField_;
Ian Rogers15bf2d32012-08-28 17:33:04 -07003386 void* startOfNextMemoryChunk_;
Ian Rogers30fab402012-01-23 15:43:46 -08003387 size_t totalAllocationUnits_;
3388 uint32_t type_;
3389 bool merge_;
3390 bool needHeader_;
3391
Elliott Hughesa2155262011-11-16 16:26:58 -08003392 DISALLOW_COPY_AND_ASSIGN(HeapChunkContext);
3393};
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003394
3395void Dbg::DdmSendHeapSegments(bool native) {
3396 Dbg::HpsgWhen when;
3397 Dbg::HpsgWhat what;
3398 if (!native) {
3399 when = gDdmHpsgWhen;
3400 what = gDdmHpsgWhat;
3401 } else {
3402 when = gDdmNhsgWhen;
3403 what = gDdmNhsgWhat;
3404 }
3405 if (when == HPSG_WHEN_NEVER) {
3406 return;
3407 }
3408
3409 // Figure out what kind of chunks we'll be sending.
3410 CHECK(what == HPSG_WHAT_MERGED_OBJECTS || what == HPSG_WHAT_DISTINCT_OBJECTS) << static_cast<int>(what);
3411
3412 // First, send a heap start chunk.
3413 uint8_t heap_id[4];
3414 JDWP::Set4BE(&heap_id[0], 1); // Heap id (bogus; we only have one heap).
3415 Dbg::DdmSendChunk(native ? CHUNK_TYPE("NHST") : CHUNK_TYPE("HPST"), sizeof(heap_id), heap_id);
3416
3417 // Send a series of heap segment chunks.
Elliott Hughesa2155262011-11-16 16:26:58 -08003418 HeapChunkContext context((what == HPSG_WHAT_MERGED_OBJECTS), native);
3419 if (native) {
Ian Rogers1d54e732013-05-02 21:10:01 -07003420 dlmalloc_inspect_all(HeapChunkContext::HeapChunkCallback, &context);
Elliott Hughesa2155262011-11-16 16:26:58 -08003421 } else {
Ian Rogers1d54e732013-05-02 21:10:01 -07003422 gc::Heap* heap = Runtime::Current()->GetHeap();
3423 const std::vector<gc::space::ContinuousSpace*>& spaces = heap->GetContinuousSpaces();
Ian Rogers50b35e22012-10-04 10:09:15 -07003424 Thread* self = Thread::Current();
Ian Rogers62d6c772013-02-27 08:32:07 -08003425 ReaderMutexLock mu(self, *Locks::heap_bitmap_lock_);
Ian Rogers1d54e732013-05-02 21:10:01 -07003426 typedef std::vector<gc::space::ContinuousSpace*>::const_iterator It;
3427 for (It cur = spaces.begin(), end = spaces.end(); cur != end; ++cur) {
3428 if ((*cur)->IsDlMallocSpace()) {
3429 (*cur)->AsDlMallocSpace()->Walk(HeapChunkContext::HeapChunkCallback, &context);
Mathieu Chartierb062fdd2012-07-03 09:51:48 -07003430 }
3431 }
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -07003432 // Walk the large objects, these are not in the AllocSpace.
3433 heap->GetLargeObjectsSpace()->Walk(HeapChunkContext::HeapChunkCallback, &context);
Elliott Hughesa2155262011-11-16 16:26:58 -08003434 }
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003435
3436 // Finally, send a heap end chunk.
3437 Dbg::DdmSendChunk(native ? CHUNK_TYPE("NHEN") : CHUNK_TYPE("HPEN"), sizeof(heap_id), heap_id);
Elliott Hughes767a1472011-10-26 18:49:02 -07003438}
3439
Elliott Hughes545a0642011-11-08 19:10:03 -08003440void Dbg::SetAllocTrackingEnabled(bool enabled) {
Ian Rogers50b35e22012-10-04 10:09:15 -07003441 MutexLock mu(Thread::Current(), gAllocTrackerLock);
Elliott Hughes545a0642011-11-08 19:10:03 -08003442 if (enabled) {
3443 if (recent_allocation_records_ == NULL) {
3444 LOG(INFO) << "Enabling alloc tracker (" << kNumAllocRecords << " entries, "
3445 << kMaxAllocRecordStackDepth << " frames --> "
3446 << (sizeof(AllocRecord) * kNumAllocRecords) << " bytes)";
3447 gAllocRecordHead = gAllocRecordCount = 0;
3448 recent_allocation_records_ = new AllocRecord[kNumAllocRecords];
3449 CHECK(recent_allocation_records_ != NULL);
3450 }
3451 } else {
3452 delete[] recent_allocation_records_;
3453 recent_allocation_records_ = NULL;
3454 }
3455}
3456
Ian Rogers0399dde2012-06-06 17:09:28 -07003457struct AllocRecordStackVisitor : public StackVisitor {
Ian Rogers7a22fa62013-01-23 12:16:16 -08003458 AllocRecordStackVisitor(Thread* thread, AllocRecord* record)
Ian Rogersb726dcb2012-09-05 08:57:23 -07003459 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_)
Ian Rogers7a22fa62013-01-23 12:16:16 -08003460 : StackVisitor(thread, NULL), record(record), depth(0) {}
Elliott Hughes545a0642011-11-08 19:10:03 -08003461
Ian Rogers00f7d0e2012-07-19 15:28:27 -07003462 // TODO: Enable annotalysis. We know lock is held in constructor, but abstraction confuses
3463 // annotalysis.
3464 bool VisitFrame() NO_THREAD_SAFETY_ANALYSIS {
Elliott Hughes545a0642011-11-08 19:10:03 -08003465 if (depth >= kMaxAllocRecordStackDepth) {
Elliott Hughes530fa002012-03-12 11:44:49 -07003466 return false;
Elliott Hughes545a0642011-11-08 19:10:03 -08003467 }
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003468 mirror::AbstractMethod* m = GetMethod();
Ian Rogers0399dde2012-06-06 17:09:28 -07003469 if (!m->IsRuntimeMethod()) {
3470 record->stack[depth].method = m;
3471 record->stack[depth].dex_pc = GetDexPc();
Elliott Hughes530fa002012-03-12 11:44:49 -07003472 ++depth;
Elliott Hughes545a0642011-11-08 19:10:03 -08003473 }
Elliott Hughes530fa002012-03-12 11:44:49 -07003474 return true;
Elliott Hughes545a0642011-11-08 19:10:03 -08003475 }
3476
3477 ~AllocRecordStackVisitor() {
3478 // Clear out any unused stack trace elements.
3479 for (; depth < kMaxAllocRecordStackDepth; ++depth) {
3480 record->stack[depth].method = NULL;
Ian Rogers0399dde2012-06-06 17:09:28 -07003481 record->stack[depth].dex_pc = 0;
Elliott Hughes545a0642011-11-08 19:10:03 -08003482 }
3483 }
3484
3485 AllocRecord* record;
3486 size_t depth;
3487};
3488
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003489void Dbg::RecordAllocation(mirror::Class* type, size_t byte_count) {
Elliott Hughes545a0642011-11-08 19:10:03 -08003490 Thread* self = Thread::Current();
3491 CHECK(self != NULL);
3492
Ian Rogers50b35e22012-10-04 10:09:15 -07003493 MutexLock mu(self, gAllocTrackerLock);
Elliott Hughes545a0642011-11-08 19:10:03 -08003494 if (recent_allocation_records_ == NULL) {
3495 return;
3496 }
3497
3498 // Advance and clip.
3499 if (++gAllocRecordHead == kNumAllocRecords) {
3500 gAllocRecordHead = 0;
3501 }
3502
3503 // Fill in the basics.
3504 AllocRecord* record = &recent_allocation_records_[gAllocRecordHead];
3505 record->type = type;
3506 record->byte_count = byte_count;
3507 record->thin_lock_id = self->GetThinLockId();
3508
3509 // Fill in the stack trace.
Ian Rogers7a22fa62013-01-23 12:16:16 -08003510 AllocRecordStackVisitor visitor(self, record);
Ian Rogers0399dde2012-06-06 17:09:28 -07003511 visitor.WalkStack();
Elliott Hughes545a0642011-11-08 19:10:03 -08003512
3513 if (gAllocRecordCount < kNumAllocRecords) {
3514 ++gAllocRecordCount;
3515 }
3516}
3517
Elliott Hughesa8f93cb2012-06-08 17:08:48 -07003518// Returns the index of the head element.
3519//
3520// We point at the most-recently-written record, so if gAllocRecordCount is 1
3521// we want to use the current element. Take "head+1" and subtract count
3522// from it.
3523//
3524// We need to handle underflow in our circular buffer, so we add
3525// kNumAllocRecords and then mask it back down.
Elliott Hughesf8349362012-06-18 15:00:06 -07003526static inline int HeadIndex() EXCLUSIVE_LOCKS_REQUIRED(gAllocTrackerLock) {
Elliott Hughes545a0642011-11-08 19:10:03 -08003527 return (gAllocRecordHead+1 + kNumAllocRecords - gAllocRecordCount) & (kNumAllocRecords-1);
3528}
3529
3530void Dbg::DumpRecentAllocations() {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07003531 ScopedObjectAccess soa(Thread::Current());
Ian Rogers50b35e22012-10-04 10:09:15 -07003532 MutexLock mu(soa.Self(), gAllocTrackerLock);
Elliott Hughes545a0642011-11-08 19:10:03 -08003533 if (recent_allocation_records_ == NULL) {
3534 LOG(INFO) << "Not recording tracked allocations";
3535 return;
3536 }
3537
3538 // "i" is the head of the list. We want to start at the end of the
3539 // list and move forward to the tail.
Elliott Hughesa8f93cb2012-06-08 17:08:48 -07003540 size_t i = HeadIndex();
Elliott Hughes545a0642011-11-08 19:10:03 -08003541 size_t count = gAllocRecordCount;
3542
3543 LOG(INFO) << "Tracked allocations, (head=" << gAllocRecordHead << " count=" << count << ")";
3544 while (count--) {
3545 AllocRecord* record = &recent_allocation_records_[i];
3546
Elliott Hughesa8f93cb2012-06-08 17:08:48 -07003547 LOG(INFO) << StringPrintf(" Thread %-2d %6zd bytes ", record->thin_lock_id, record->byte_count)
Elliott Hughes545a0642011-11-08 19:10:03 -08003548 << PrettyClass(record->type);
3549
3550 for (size_t stack_frame = 0; stack_frame < kMaxAllocRecordStackDepth; ++stack_frame) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003551 const mirror::AbstractMethod* m = record->stack[stack_frame].method;
Elliott Hughes545a0642011-11-08 19:10:03 -08003552 if (m == NULL) {
3553 break;
3554 }
3555 LOG(INFO) << " " << PrettyMethod(m) << " line " << record->stack[stack_frame].LineNumber();
3556 }
3557
3558 // pause periodically to help logcat catch up
3559 if ((count % 5) == 0) {
3560 usleep(40000);
3561 }
3562
3563 i = (i + 1) & (kNumAllocRecords-1);
3564 }
3565}
3566
3567class StringTable {
3568 public:
3569 StringTable() {
3570 }
3571
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08003572 void Add(const char* s) {
Elliott Hughes545a0642011-11-08 19:10:03 -08003573 table_.insert(s);
3574 }
3575
Elliott Hughesa8f93cb2012-06-08 17:08:48 -07003576 size_t IndexOf(const char* s) const {
3577 typedef std::set<std::string>::const_iterator It; // TODO: C++0x auto
3578 It it = table_.find(s);
3579 if (it == table_.end()) {
3580 LOG(FATAL) << "IndexOf(\"" << s << "\") failed";
3581 }
3582 return std::distance(table_.begin(), it);
Elliott Hughes545a0642011-11-08 19:10:03 -08003583 }
3584
Elliott Hughesa8f93cb2012-06-08 17:08:48 -07003585 size_t Size() const {
Elliott Hughes545a0642011-11-08 19:10:03 -08003586 return table_.size();
3587 }
3588
Elliott Hughesa8f93cb2012-06-08 17:08:48 -07003589 void WriteTo(std::vector<uint8_t>& bytes) const {
3590 typedef std::set<std::string>::const_iterator It; // TODO: C++0x auto
Elliott Hughes545a0642011-11-08 19:10:03 -08003591 for (It it = table_.begin(); it != table_.end(); ++it) {
Elliott Hughesa8f93cb2012-06-08 17:08:48 -07003592 const char* s = (*it).c_str();
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08003593 size_t s_len = CountModifiedUtf8Chars(s);
3594 UniquePtr<uint16_t> s_utf16(new uint16_t[s_len]);
3595 ConvertModifiedUtf8ToUtf16(s_utf16.get(), s);
3596 JDWP::AppendUtf16BE(bytes, s_utf16.get(), s_len);
Elliott Hughes545a0642011-11-08 19:10:03 -08003597 }
3598 }
3599
3600 private:
Elliott Hughesa8f93cb2012-06-08 17:08:48 -07003601 std::set<std::string> table_;
Elliott Hughes545a0642011-11-08 19:10:03 -08003602 DISALLOW_COPY_AND_ASSIGN(StringTable);
3603};
3604
3605/*
3606 * The data we send to DDMS contains everything we have recorded.
3607 *
3608 * Message header (all values big-endian):
3609 * (1b) message header len (to allow future expansion); includes itself
3610 * (1b) entry header len
3611 * (1b) stack frame len
3612 * (2b) number of entries
3613 * (4b) offset to string table from start of message
3614 * (2b) number of class name strings
3615 * (2b) number of method name strings
3616 * (2b) number of source file name strings
3617 * For each entry:
3618 * (4b) total allocation size
Elliott Hughes221229c2013-01-08 18:17:50 -08003619 * (2b) thread id
Elliott Hughes545a0642011-11-08 19:10:03 -08003620 * (2b) allocated object's class name index
3621 * (1b) stack depth
3622 * For each stack frame:
3623 * (2b) method's class name
3624 * (2b) method name
3625 * (2b) method source file
3626 * (2b) line number, clipped to 32767; -2 if native; -1 if no source
3627 * (xb) class name strings
3628 * (xb) method name strings
3629 * (xb) source file strings
3630 *
3631 * As with other DDM traffic, strings are sent as a 4-byte length
3632 * followed by UTF-16 data.
3633 *
3634 * We send up 16-bit unsigned indexes into string tables. In theory there
3635 * can be (kMaxAllocRecordStackDepth * kNumAllocRecords) unique strings in
3636 * each table, but in practice there should be far fewer.
3637 *
3638 * The chief reason for using a string table here is to keep the size of
3639 * the DDMS message to a minimum. This is partly to make the protocol
3640 * efficient, but also because we have to form the whole thing up all at
3641 * once in a memory buffer.
3642 *
3643 * We use separate string tables for class names, method names, and source
3644 * files to keep the indexes small. There will generally be no overlap
3645 * between the contents of these tables.
3646 */
3647jbyteArray Dbg::GetRecentAllocations() {
3648 if (false) {
3649 DumpRecentAllocations();
3650 }
3651
Ian Rogers50b35e22012-10-04 10:09:15 -07003652 Thread* self = Thread::Current();
Elliott Hughes545a0642011-11-08 19:10:03 -08003653 std::vector<uint8_t> bytes;
Mathieu Chartier46e811b2013-07-10 17:09:14 -07003654 {
3655 MutexLock mu(self, gAllocTrackerLock);
3656 //
3657 // Part 1: generate string tables.
3658 //
3659 StringTable class_names;
3660 StringTable method_names;
3661 StringTable filenames;
Elliott Hughes545a0642011-11-08 19:10:03 -08003662
Mathieu Chartier46e811b2013-07-10 17:09:14 -07003663 int count = gAllocRecordCount;
3664 int idx = HeadIndex();
3665 while (count--) {
3666 AllocRecord* record = &recent_allocation_records_[idx];
Elliott Hughes545a0642011-11-08 19:10:03 -08003667
Mathieu Chartier46e811b2013-07-10 17:09:14 -07003668 class_names.Add(ClassHelper(record->type).GetDescriptor());
Elliott Hughes545a0642011-11-08 19:10:03 -08003669
Mathieu Chartier46e811b2013-07-10 17:09:14 -07003670 MethodHelper mh;
3671 for (size_t i = 0; i < kMaxAllocRecordStackDepth; i++) {
3672 mirror::AbstractMethod* m = record->stack[i].method;
3673 if (m != NULL) {
3674 mh.ChangeMethod(m);
3675 class_names.Add(mh.GetDeclaringClassDescriptor());
3676 method_names.Add(mh.GetName());
3677 filenames.Add(mh.GetDeclaringClassSourceFile());
3678 }
3679 }
Elliott Hughes545a0642011-11-08 19:10:03 -08003680
Mathieu Chartier46e811b2013-07-10 17:09:14 -07003681 idx = (idx + 1) & (kNumAllocRecords-1);
Elliott Hughes545a0642011-11-08 19:10:03 -08003682 }
3683
Mathieu Chartier46e811b2013-07-10 17:09:14 -07003684 LOG(INFO) << "allocation records: " << gAllocRecordCount;
3685
3686 //
3687 // Part 2: Generate the output and store it in the buffer.
3688 //
3689
3690 // (1b) message header len (to allow future expansion); includes itself
3691 // (1b) entry header len
3692 // (1b) stack frame len
3693 const int kMessageHeaderLen = 15;
3694 const int kEntryHeaderLen = 9;
3695 const int kStackFrameLen = 8;
3696 JDWP::Append1BE(bytes, kMessageHeaderLen);
3697 JDWP::Append1BE(bytes, kEntryHeaderLen);
3698 JDWP::Append1BE(bytes, kStackFrameLen);
3699
3700 // (2b) number of entries
3701 // (4b) offset to string table from start of message
3702 // (2b) number of class name strings
3703 // (2b) number of method name strings
3704 // (2b) number of source file name strings
3705 JDWP::Append2BE(bytes, gAllocRecordCount);
3706 size_t string_table_offset = bytes.size();
3707 JDWP::Append4BE(bytes, 0); // We'll patch this later...
3708 JDWP::Append2BE(bytes, class_names.Size());
3709 JDWP::Append2BE(bytes, method_names.Size());
3710 JDWP::Append2BE(bytes, filenames.Size());
3711
3712 count = gAllocRecordCount;
3713 idx = HeadIndex();
3714 ClassHelper kh;
3715 while (count--) {
3716 // For each entry:
3717 // (4b) total allocation size
3718 // (2b) thread id
3719 // (2b) allocated object's class name index
3720 // (1b) stack depth
3721 AllocRecord* record = &recent_allocation_records_[idx];
3722 size_t stack_depth = record->GetDepth();
3723 kh.ChangeClass(record->type);
3724 size_t allocated_object_class_name_index = class_names.IndexOf(kh.GetDescriptor());
3725 JDWP::Append4BE(bytes, record->byte_count);
3726 JDWP::Append2BE(bytes, record->thin_lock_id);
3727 JDWP::Append2BE(bytes, allocated_object_class_name_index);
3728 JDWP::Append1BE(bytes, stack_depth);
3729
3730 MethodHelper mh;
3731 for (size_t stack_frame = 0; stack_frame < stack_depth; ++stack_frame) {
3732 // For each stack frame:
3733 // (2b) method's class name
3734 // (2b) method name
3735 // (2b) method source file
3736 // (2b) line number, clipped to 32767; -2 if native; -1 if no source
3737 mh.ChangeMethod(record->stack[stack_frame].method);
3738 size_t class_name_index = class_names.IndexOf(mh.GetDeclaringClassDescriptor());
3739 size_t method_name_index = method_names.IndexOf(mh.GetName());
3740 size_t file_name_index = filenames.IndexOf(mh.GetDeclaringClassSourceFile());
3741 JDWP::Append2BE(bytes, class_name_index);
3742 JDWP::Append2BE(bytes, method_name_index);
3743 JDWP::Append2BE(bytes, file_name_index);
3744 JDWP::Append2BE(bytes, record->stack[stack_frame].LineNumber());
3745 }
3746
3747 idx = (idx + 1) & (kNumAllocRecords-1);
3748 }
3749
3750 // (xb) class name strings
3751 // (xb) method name strings
3752 // (xb) source file strings
3753 JDWP::Set4BE(&bytes[string_table_offset], bytes.size());
3754 class_names.WriteTo(bytes);
3755 method_names.WriteTo(bytes);
3756 filenames.WriteTo(bytes);
Elliott Hughes545a0642011-11-08 19:10:03 -08003757 }
Ian Rogers50b35e22012-10-04 10:09:15 -07003758 JNIEnv* env = self->GetJniEnv();
Elliott Hughes545a0642011-11-08 19:10:03 -08003759 jbyteArray result = env->NewByteArray(bytes.size());
3760 if (result != NULL) {
3761 env->SetByteArrayRegion(result, 0, bytes.size(), reinterpret_cast<const jbyte*>(&bytes[0]));
3762 }
3763 return result;
3764}
3765
Elliott Hughes872d4ec2011-10-21 17:07:15 -07003766} // namespace art