blob: 64be25c3e4f95c201756faba16dcf97958b206e4 [file] [log] [blame]
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001/*
2 * Copyright (C) 2008 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17#include "debugger.h"
18
Elliott Hughes3bb81562011-10-21 18:52:59 -070019#include <sys/uio.h>
20
Elliott Hughes545a0642011-11-08 19:10:03 -080021#include <set>
22
23#include "class_linker.h"
Ian Rogers2dd0e2c2013-01-24 12:42:14 -080024#include "class_linker-inl.h"
Ian Rogers4f6ad8a2013-03-18 15:27:28 -070025#include "dex_file-inl.h"
Ian Rogers776ac1f2012-04-13 23:36:36 -070026#include "dex_instruction.h"
Ian Rogers2dd0e2c2013-01-24 12:42:14 -080027#include "gc/card_table-inl.h"
Mathieu Chartier1c23e1e2012-10-12 14:14:11 -070028#include "gc/large_object_space.h"
29#include "gc/space.h"
Jeff Hao5d917302013-02-27 17:57:33 -080030#include "invoke_arg_array_builder.h"
Elliott Hughes64f574f2013-02-20 14:57:12 -080031#include "jdwp/object_registry.h"
Ian Rogers2dd0e2c2013-01-24 12:42:14 -080032#include "mirror/abstract_method-inl.h"
33#include "mirror/class.h"
34#include "mirror/class-inl.h"
35#include "mirror/class_loader.h"
36#include "mirror/field-inl.h"
37#include "mirror/object-inl.h"
38#include "mirror/object_array-inl.h"
39#include "mirror/throwable.h"
Ian Rogers2bcb4a42012-11-08 10:39:18 -080040#include "oat/runtime/context.h"
Ian Rogers6d4d9fc2011-11-30 16:24:48 -080041#include "object_utils.h"
Elliott Hughesa0e18062012-04-13 15:59:59 -070042#include "safe_map.h"
Elliott Hughes64f574f2013-02-20 14:57:12 -080043#include "scoped_thread_state_change.h"
Elliott Hughes6a5bd492011-10-28 14:33:57 -070044#include "ScopedLocalRef.h"
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -070045#include "ScopedPrimitiveArray.h"
Ian Rogers1f539342012-10-03 21:09:42 -070046#include "sirt_ref.h"
Elliott Hughes47fce012011-10-25 18:37:19 -070047#include "stack_indirect_reference_table.h"
Elliott Hughes475fc232011-10-25 15:00:35 -070048#include "thread_list.h"
Ian Rogers62d6c772013-02-27 08:32:07 -080049#include "throw_location.h"
Ian Rogers2dd0e2c2013-01-24 12:42:14 -080050#include "utf.h"
Elliott Hugheseac76672012-05-24 21:56:51 -070051#include "well_known_classes.h"
Elliott Hughes475fc232011-10-25 15:00:35 -070052
Elliott Hughes872d4ec2011-10-21 17:07:15 -070053namespace art {
54
Elliott Hughes545a0642011-11-08 19:10:03 -080055static const size_t kMaxAllocRecordStackDepth = 16; // Max 255.
Elliott Hughes64f574f2013-02-20 14:57:12 -080056static const size_t kNumAllocRecords = 512; // Must be a power of 2.
Elliott Hughes475fc232011-10-25 15:00:35 -070057
Elliott Hughes545a0642011-11-08 19:10:03 -080058struct AllocRecordStackTraceElement {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -080059 mirror::AbstractMethod* method;
Ian Rogers0399dde2012-06-06 17:09:28 -070060 uint32_t dex_pc;
Elliott Hughes545a0642011-11-08 19:10:03 -080061
Ian Rogersb726dcb2012-09-05 08:57:23 -070062 int32_t LineNumber() const SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Ian Rogers0399dde2012-06-06 17:09:28 -070063 return MethodHelper(method).GetLineNumFromDexPC(dex_pc);
Elliott Hughes545a0642011-11-08 19:10:03 -080064 }
65};
66
67struct AllocRecord {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -080068 mirror::Class* type;
Elliott Hughes545a0642011-11-08 19:10:03 -080069 size_t byte_count;
70 uint16_t thin_lock_id;
71 AllocRecordStackTraceElement stack[kMaxAllocRecordStackDepth]; // Unused entries have NULL method.
72
73 size_t GetDepth() {
74 size_t depth = 0;
75 while (depth < kMaxAllocRecordStackDepth && stack[depth].method != NULL) {
76 ++depth;
77 }
78 return depth;
79 }
80};
81
Elliott Hughes86964332012-02-15 19:37:42 -080082struct Breakpoint {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -080083 mirror::AbstractMethod* method;
Elliott Hughesa656a0f2012-02-21 18:03:44 -080084 uint32_t dex_pc;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -080085 Breakpoint(mirror::AbstractMethod* method, uint32_t dex_pc) : method(method), dex_pc(dex_pc) {}
Elliott Hughes86964332012-02-15 19:37:42 -080086};
87
Ian Rogers00f7d0e2012-07-19 15:28:27 -070088static std::ostream& operator<<(std::ostream& os, const Breakpoint& rhs)
Ian Rogersb726dcb2012-09-05 08:57:23 -070089 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Elliott Hughes229feb72012-02-23 13:33:29 -080090 os << StringPrintf("Breakpoint[%s @%#x]", PrettyMethod(rhs.method).c_str(), rhs.dex_pc);
Elliott Hughes86964332012-02-15 19:37:42 -080091 return os;
92}
93
94struct SingleStepControl {
95 // Are we single-stepping right now?
96 bool is_active;
97 Thread* thread;
98
99 JDWP::JdwpStepSize step_size;
100 JDWP::JdwpStepDepth step_depth;
101
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800102 const mirror::AbstractMethod* method;
Elliott Hughes2435a572012-02-17 16:07:41 -0800103 int32_t line_number; // Or -1 for native methods.
104 std::set<uint32_t> dex_pcs;
Elliott Hughes86964332012-02-15 19:37:42 -0800105 int stack_depth;
106};
107
Ian Rogers62d6c772013-02-27 08:32:07 -0800108class DebugInstrumentationListener : public instrumentation::InstrumentationListener {
109 public:
110 DebugInstrumentationListener() {}
111 virtual ~DebugInstrumentationListener() {}
112
113 virtual void MethodEntered(Thread* thread, mirror::Object* this_object,
114 const mirror::AbstractMethod* method, uint32_t dex_pc)
115 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
116 if (method->IsNative()) {
117 // TODO: post location events is a suspension point and native method entry stubs aren't.
118 return;
119 }
120 Dbg::PostLocationEvent(method, 0, this_object, Dbg::kMethodEntry);
121 }
122
123 virtual void MethodExited(Thread* thread, mirror::Object* this_object,
124 const mirror::AbstractMethod* method,
125 uint32_t dex_pc, const JValue& return_value)
126 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
127 UNUSED(return_value);
128 if (method->IsNative()) {
129 // TODO: post location events is a suspension point and native method entry stubs aren't.
130 return;
131 }
132 Dbg::PostLocationEvent(method, dex_pc, this_object, Dbg::kMethodExit);
133 }
134
135 virtual void MethodUnwind(Thread* thread, const mirror::AbstractMethod* method,
136 uint32_t dex_pc) SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
137 // We're not recorded to listen to this kind of event, so complain.
138 LOG(ERROR) << "Unexpected method unwind event in debugger " << PrettyMethod(method)
139 << " " << dex_pc;
140 }
141
142 virtual void DexPcMoved(Thread* thread, mirror::Object* this_object,
143 const mirror::AbstractMethod* method, uint32_t new_dex_pc)
144 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
145 Dbg::UpdateDebugger(thread, this_object, method, new_dex_pc);
146 }
147
148 virtual void ExceptionCaught(Thread* thread, const ThrowLocation& throw_location,
149 mirror::AbstractMethod* catch_method, uint32_t catch_dex_pc,
150 mirror::Throwable* exception_object)
151 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
152 Dbg::PostException(thread, throw_location, catch_method, catch_dex_pc, exception_object);
153 }
154
155} gDebugInstrumentationListener;
156
Elliott Hughes4ffd3132011-10-24 12:06:42 -0700157// JDWP is allowed unless the Zygote forbids it.
158static bool gJdwpAllowed = true;
159
Elliott Hughesc0f09332012-03-26 13:27:06 -0700160// Was there a -Xrunjdwp or -agentlib:jdwp= argument on the command line?
Elliott Hughes3bb81562011-10-21 18:52:59 -0700161static bool gJdwpConfigured = false;
162
Elliott Hughesc0f09332012-03-26 13:27:06 -0700163// Broken-down JDWP options. (Only valid if IsJdwpConfigured() is true.)
Elliott Hughes376a7a02011-10-24 18:35:55 -0700164static JDWP::JdwpOptions gJdwpOptions;
Elliott Hughes3bb81562011-10-21 18:52:59 -0700165
166// Runtime JDWP state.
167static JDWP::JdwpState* gJdwpState = NULL;
168static bool gDebuggerConnected; // debugger or DDMS is connected.
169static bool gDebuggerActive; // debugger is making requests.
Elliott Hughes86964332012-02-15 19:37:42 -0800170static bool gDisposed; // debugger called VirtualMachine.Dispose, so we should drop the connection.
Elliott Hughes3bb81562011-10-21 18:52:59 -0700171
Elliott Hughes47fce012011-10-25 18:37:19 -0700172static bool gDdmThreadNotification = false;
173
Elliott Hughes767a1472011-10-26 18:49:02 -0700174// DDMS GC-related settings.
175static Dbg::HpifWhen gDdmHpifWhen = Dbg::HPIF_WHEN_NEVER;
176static Dbg::HpsgWhen gDdmHpsgWhen = Dbg::HPSG_WHEN_NEVER;
177static Dbg::HpsgWhat gDdmHpsgWhat;
178static Dbg::HpsgWhen gDdmNhsgWhen = Dbg::HPSG_WHEN_NEVER;
179static Dbg::HpsgWhat gDdmNhsgWhat;
180
Elliott Hughes475fc232011-10-25 15:00:35 -0700181static ObjectRegistry* gRegistry = NULL;
182
Elliott Hughes545a0642011-11-08 19:10:03 -0800183// Recent allocation tracking.
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700184static Mutex gAllocTrackerLock DEFAULT_MUTEX_ACQUIRED_AFTER ("AllocTracker lock");
Elliott Hughesf8349362012-06-18 15:00:06 -0700185AllocRecord* Dbg::recent_allocation_records_ PT_GUARDED_BY(gAllocTrackerLock) = NULL; // TODO: CircularBuffer<AllocRecord>
186static size_t gAllocRecordHead GUARDED_BY(gAllocTrackerLock) = 0;
187static size_t gAllocRecordCount GUARDED_BY(gAllocTrackerLock) = 0;
Elliott Hughes545a0642011-11-08 19:10:03 -0800188
Elliott Hughes86964332012-02-15 19:37:42 -0800189// Breakpoints and single-stepping.
jeffhao09bfc6a2012-12-11 18:11:43 -0800190static std::vector<Breakpoint> gBreakpoints GUARDED_BY(Locks::breakpoint_lock_);
191static SingleStepControl gSingleStepControl GUARDED_BY(Locks::breakpoint_lock_);
Elliott Hughes86964332012-02-15 19:37:42 -0800192
Ian Rogers62d6c772013-02-27 08:32:07 -0800193static bool IsBreakpoint(const mirror::AbstractMethod* m, uint32_t dex_pc)
jeffhao09bfc6a2012-12-11 18:11:43 -0800194 LOCKS_EXCLUDED(Locks::breakpoint_lock_)
Ian Rogersb726dcb2012-09-05 08:57:23 -0700195 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
jeffhao09bfc6a2012-12-11 18:11:43 -0800196 MutexLock mu(Thread::Current(), *Locks::breakpoint_lock_);
Elliott Hughes86964332012-02-15 19:37:42 -0800197 for (size_t i = 0; i < gBreakpoints.size(); ++i) {
Elliott Hughesa656a0f2012-02-21 18:03:44 -0800198 if (gBreakpoints[i].method == m && gBreakpoints[i].dex_pc == dex_pc) {
Elliott Hughes86964332012-02-15 19:37:42 -0800199 VLOG(jdwp) << "Hit breakpoint #" << i << ": " << gBreakpoints[i];
200 return true;
201 }
202 }
203 return false;
204}
205
Elliott Hughes9e0c1752013-01-09 14:02:58 -0800206static bool IsSuspendedForDebugger(ScopedObjectAccessUnchecked& soa, Thread* thread) {
207 MutexLock mu(soa.Self(), *Locks::thread_suspend_count_lock_);
208 // A thread may be suspended for GC; in this code, we really want to know whether
209 // there's a debugger suspension active.
210 return thread->IsSuspended() && thread->GetDebugSuspendCount() > 0;
211}
212
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800213static mirror::Array* DecodeArray(JDWP::RefTypeId id, JDWP::JdwpError& status)
Ian Rogersb726dcb2012-09-05 08:57:23 -0700214 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800215 mirror::Object* o = gRegistry->Get<mirror::Object*>(id);
Elliott Hughes64f574f2013-02-20 14:57:12 -0800216 if (o == NULL || o == ObjectRegistry::kInvalidObject) {
Elliott Hughes436e3722012-02-17 20:01:47 -0800217 status = JDWP::ERR_INVALID_OBJECT;
218 return NULL;
219 }
220 if (!o->IsArrayInstance()) {
221 status = JDWP::ERR_INVALID_ARRAY;
222 return NULL;
223 }
224 status = JDWP::ERR_NONE;
225 return o->AsArray();
226}
227
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800228static mirror::Class* DecodeClass(JDWP::RefTypeId id, JDWP::JdwpError& status)
Ian Rogersb726dcb2012-09-05 08:57:23 -0700229 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800230 mirror::Object* o = gRegistry->Get<mirror::Object*>(id);
Elliott Hughes64f574f2013-02-20 14:57:12 -0800231 if (o == NULL || o == ObjectRegistry::kInvalidObject) {
Elliott Hughes436e3722012-02-17 20:01:47 -0800232 status = JDWP::ERR_INVALID_OBJECT;
233 return NULL;
234 }
235 if (!o->IsClass()) {
236 status = JDWP::ERR_INVALID_CLASS;
237 return NULL;
238 }
239 status = JDWP::ERR_NONE;
240 return o->AsClass();
241}
242
Elliott Hughes221229c2013-01-08 18:17:50 -0800243static JDWP::JdwpError DecodeThread(ScopedObjectAccessUnchecked& soa, JDWP::ObjectId thread_id, Thread*& thread)
jeffhaoa77f0f62012-12-05 17:19:31 -0800244 EXCLUSIVE_LOCKS_REQUIRED(Locks::thread_list_lock_)
Ian Rogersb726dcb2012-09-05 08:57:23 -0700245 LOCKS_EXCLUDED(Locks::thread_suspend_count_lock_)
246 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800247 mirror::Object* thread_peer = gRegistry->Get<mirror::Object*>(thread_id);
Elliott Hughes64f574f2013-02-20 14:57:12 -0800248 if (thread_peer == NULL || thread_peer == ObjectRegistry::kInvalidObject) {
Elliott Hughes221229c2013-01-08 18:17:50 -0800249 // This isn't even an object.
250 return JDWP::ERR_INVALID_OBJECT;
Elliott Hughes436e3722012-02-17 20:01:47 -0800251 }
Elliott Hughes221229c2013-01-08 18:17:50 -0800252
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800253 mirror::Class* java_lang_Thread = soa.Decode<mirror::Class*>(WellKnownClasses::java_lang_Thread);
Elliott Hughes221229c2013-01-08 18:17:50 -0800254 if (!java_lang_Thread->IsAssignableFrom(thread_peer->GetClass())) {
255 // This isn't a thread.
256 return JDWP::ERR_INVALID_THREAD;
257 }
258
259 thread = Thread::FromManagedThread(soa, thread_peer);
260 if (thread == NULL) {
261 // This is a java.lang.Thread without a Thread*. Must be a zombie.
262 return JDWP::ERR_THREAD_NOT_ALIVE;
263 }
264 return JDWP::ERR_NONE;
Elliott Hughes436e3722012-02-17 20:01:47 -0800265}
266
Elliott Hughes24437992011-11-30 14:49:33 -0800267static JDWP::JdwpTag BasicTagFromDescriptor(const char* descriptor) {
268 // JDWP deliberately uses the descriptor characters' ASCII values for its enum.
269 // Note that by "basic" we mean that we don't get more specific than JT_OBJECT.
270 return static_cast<JDWP::JdwpTag>(descriptor[0]);
271}
272
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800273static JDWP::JdwpTag TagFromClass(mirror::Class* c)
Ian Rogersb726dcb2012-09-05 08:57:23 -0700274 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Elliott Hughes86b00102011-12-05 17:54:26 -0800275 CHECK(c != NULL);
Elliott Hughes24437992011-11-30 14:49:33 -0800276 if (c->IsArrayClass()) {
277 return JDWP::JT_ARRAY;
278 }
279
Elliott Hughes3d30d9b2011-12-07 17:35:48 -0800280 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
Elliott Hughes24437992011-11-30 14:49:33 -0800281 if (c->IsStringClass()) {
282 return JDWP::JT_STRING;
283 } else if (c->IsClassClass()) {
284 return JDWP::JT_CLASS_OBJECT;
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -0800285 } else if (class_linker->FindSystemClass("Ljava/lang/Thread;")->IsAssignableFrom(c)) {
Elliott Hughes24437992011-11-30 14:49:33 -0800286 return JDWP::JT_THREAD;
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -0800287 } else if (class_linker->FindSystemClass("Ljava/lang/ThreadGroup;")->IsAssignableFrom(c)) {
Elliott Hughes24437992011-11-30 14:49:33 -0800288 return JDWP::JT_THREAD_GROUP;
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -0800289 } else if (class_linker->FindSystemClass("Ljava/lang/ClassLoader;")->IsAssignableFrom(c)) {
Elliott Hughes24437992011-11-30 14:49:33 -0800290 return JDWP::JT_CLASS_LOADER;
Elliott Hughes24437992011-11-30 14:49:33 -0800291 } else {
292 return JDWP::JT_OBJECT;
293 }
294}
295
296/*
297 * Objects declared to hold Object might actually hold a more specific
298 * type. The debugger may take a special interest in these (e.g. it
299 * wants to display the contents of Strings), so we want to return an
300 * appropriate tag.
301 *
302 * Null objects are tagged JT_OBJECT.
303 */
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800304static JDWP::JdwpTag TagFromObject(const mirror::Object* o)
Ian Rogersb726dcb2012-09-05 08:57:23 -0700305 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Elliott Hughes24437992011-11-30 14:49:33 -0800306 return (o == NULL) ? JDWP::JT_OBJECT : TagFromClass(o->GetClass());
307}
308
309static bool IsPrimitiveTag(JDWP::JdwpTag tag) {
310 switch (tag) {
311 case JDWP::JT_BOOLEAN:
312 case JDWP::JT_BYTE:
313 case JDWP::JT_CHAR:
314 case JDWP::JT_FLOAT:
315 case JDWP::JT_DOUBLE:
316 case JDWP::JT_INT:
317 case JDWP::JT_LONG:
318 case JDWP::JT_SHORT:
319 case JDWP::JT_VOID:
320 return true;
321 default:
322 return false;
323 }
324}
325
Elliott Hughes3bb81562011-10-21 18:52:59 -0700326/*
327 * Handle one of the JDWP name/value pairs.
328 *
329 * JDWP options are:
330 * help: if specified, show help message and bail
331 * transport: may be dt_socket or dt_shmem
332 * address: for dt_socket, "host:port", or just "port" when listening
333 * server: if "y", wait for debugger to attach; if "n", attach to debugger
334 * timeout: how long to wait for debugger to connect / listen
335 *
336 * Useful with server=n (these aren't supported yet):
337 * onthrow=<exception-name>: connect to debugger when exception thrown
338 * onuncaught=y|n: connect to debugger when uncaught exception thrown
339 * launch=<command-line>: launch the debugger itself
340 *
341 * The "transport" option is required, as is "address" if server=n.
342 */
343static bool ParseJdwpOption(const std::string& name, const std::string& value) {
344 if (name == "transport") {
345 if (value == "dt_socket") {
Elliott Hughes376a7a02011-10-24 18:35:55 -0700346 gJdwpOptions.transport = JDWP::kJdwpTransportSocket;
Elliott Hughes3bb81562011-10-21 18:52:59 -0700347 } else if (value == "dt_android_adb") {
Elliott Hughes376a7a02011-10-24 18:35:55 -0700348 gJdwpOptions.transport = JDWP::kJdwpTransportAndroidAdb;
Elliott Hughes3bb81562011-10-21 18:52:59 -0700349 } else {
350 LOG(ERROR) << "JDWP transport not supported: " << value;
351 return false;
352 }
353 } else if (name == "server") {
354 if (value == "n") {
Elliott Hughes376a7a02011-10-24 18:35:55 -0700355 gJdwpOptions.server = false;
Elliott Hughes3bb81562011-10-21 18:52:59 -0700356 } else if (value == "y") {
Elliott Hughes376a7a02011-10-24 18:35:55 -0700357 gJdwpOptions.server = true;
Elliott Hughes3bb81562011-10-21 18:52:59 -0700358 } else {
359 LOG(ERROR) << "JDWP option 'server' must be 'y' or 'n'";
360 return false;
361 }
362 } else if (name == "suspend") {
363 if (value == "n") {
Elliott Hughes376a7a02011-10-24 18:35:55 -0700364 gJdwpOptions.suspend = false;
Elliott Hughes3bb81562011-10-21 18:52:59 -0700365 } else if (value == "y") {
Elliott Hughes376a7a02011-10-24 18:35:55 -0700366 gJdwpOptions.suspend = true;
Elliott Hughes3bb81562011-10-21 18:52:59 -0700367 } else {
368 LOG(ERROR) << "JDWP option 'suspend' must be 'y' or 'n'";
369 return false;
370 }
371 } else if (name == "address") {
372 /* this is either <port> or <host>:<port> */
373 std::string port_string;
Elliott Hughes376a7a02011-10-24 18:35:55 -0700374 gJdwpOptions.host.clear();
Elliott Hughes3bb81562011-10-21 18:52:59 -0700375 std::string::size_type colon = value.find(':');
376 if (colon != std::string::npos) {
Elliott Hughes376a7a02011-10-24 18:35:55 -0700377 gJdwpOptions.host = value.substr(0, colon);
Elliott Hughes3bb81562011-10-21 18:52:59 -0700378 port_string = value.substr(colon + 1);
379 } else {
380 port_string = value;
381 }
382 if (port_string.empty()) {
383 LOG(ERROR) << "JDWP address missing port: " << value;
384 return false;
385 }
386 char* end;
Elliott Hughesba8eee12012-01-24 20:25:24 -0800387 uint64_t port = strtoul(port_string.c_str(), &end, 10);
388 if (*end != '\0' || port > 0xffff) {
Elliott Hughes3bb81562011-10-21 18:52:59 -0700389 LOG(ERROR) << "JDWP address has junk in port field: " << value;
390 return false;
391 }
Elliott Hughes376a7a02011-10-24 18:35:55 -0700392 gJdwpOptions.port = port;
Elliott Hughes3bb81562011-10-21 18:52:59 -0700393 } else if (name == "launch" || name == "onthrow" || name == "oncaught" || name == "timeout") {
394 /* valid but unsupported */
395 LOG(INFO) << "Ignoring JDWP option '" << name << "'='" << value << "'";
396 } else {
397 LOG(INFO) << "Ignoring unrecognized JDWP option '" << name << "'='" << value << "'";
398 }
399
400 return true;
401}
402
403/*
404 * Parse the latter half of a -Xrunjdwp/-agentlib:jdwp= string, e.g.:
405 * "transport=dt_socket,address=8000,server=y,suspend=n"
406 */
407bool Dbg::ParseJdwpOptions(const std::string& options) {
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -0800408 VLOG(jdwp) << "ParseJdwpOptions: " << options;
Elliott Hughes47fce012011-10-25 18:37:19 -0700409
Elliott Hughes3bb81562011-10-21 18:52:59 -0700410 std::vector<std::string> pairs;
411 Split(options, ',', pairs);
412
413 for (size_t i = 0; i < pairs.size(); ++i) {
414 std::string::size_type equals = pairs[i].find('=');
415 if (equals == std::string::npos) {
416 LOG(ERROR) << "Can't parse JDWP option '" << pairs[i] << "' in '" << options << "'";
417 return false;
418 }
419 ParseJdwpOption(pairs[i].substr(0, equals), pairs[i].substr(equals + 1));
420 }
421
Elliott Hughes376a7a02011-10-24 18:35:55 -0700422 if (gJdwpOptions.transport == JDWP::kJdwpTransportUnknown) {
Elliott Hughes3bb81562011-10-21 18:52:59 -0700423 LOG(ERROR) << "Must specify JDWP transport: " << options;
424 }
Elliott Hughes376a7a02011-10-24 18:35:55 -0700425 if (!gJdwpOptions.server && (gJdwpOptions.host.empty() || gJdwpOptions.port == 0)) {
Elliott Hughes3bb81562011-10-21 18:52:59 -0700426 LOG(ERROR) << "Must specify JDWP host and port when server=n: " << options;
427 return false;
428 }
429
430 gJdwpConfigured = true;
431 return true;
432}
433
Elliott Hughesd1cc8362011-10-24 16:58:50 -0700434void Dbg::StartJdwp() {
Elliott Hughesc0f09332012-03-26 13:27:06 -0700435 if (!gJdwpAllowed || !IsJdwpConfigured()) {
Elliott Hughes376a7a02011-10-24 18:35:55 -0700436 // No JDWP for you!
437 return;
438 }
439
Elliott Hughes475fc232011-10-25 15:00:35 -0700440 CHECK(gRegistry == NULL);
441 gRegistry = new ObjectRegistry;
442
Elliott Hughesd1cc8362011-10-24 16:58:50 -0700443 // Init JDWP if the debugger is enabled. This may connect out to a
444 // debugger, passively listen for a debugger, or block waiting for a
445 // debugger.
Elliott Hughes376a7a02011-10-24 18:35:55 -0700446 gJdwpState = JDWP::JdwpState::Create(&gJdwpOptions);
447 if (gJdwpState == NULL) {
Elliott Hughesf8a2df72011-12-01 12:19:54 -0800448 // We probably failed because some other process has the port already, which means that
449 // if we don't abort the user is likely to think they're talking to us when they're actually
450 // talking to that other process.
Elliott Hughes3d30d9b2011-12-07 17:35:48 -0800451 LOG(FATAL) << "Debugger thread failed to initialize";
Elliott Hughesd1cc8362011-10-24 16:58:50 -0700452 }
453
454 // If a debugger has already attached, send the "welcome" message.
455 // This may cause us to suspend all threads.
Elliott Hughes376a7a02011-10-24 18:35:55 -0700456 if (gJdwpState->IsActive()) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700457 ScopedObjectAccess soa(Thread::Current());
Elliott Hughes376a7a02011-10-24 18:35:55 -0700458 if (!gJdwpState->PostVMStart()) {
Elliott Hughes3d30d9b2011-12-07 17:35:48 -0800459 LOG(WARNING) << "Failed to post 'start' message to debugger";
Elliott Hughesd1cc8362011-10-24 16:58:50 -0700460 }
461 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700462}
463
Elliott Hughesd1cc8362011-10-24 16:58:50 -0700464void Dbg::StopJdwp() {
Elliott Hughes376a7a02011-10-24 18:35:55 -0700465 delete gJdwpState;
Elliott Hughes475fc232011-10-25 15:00:35 -0700466 delete gRegistry;
467 gRegistry = NULL;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700468}
469
Elliott Hughes767a1472011-10-26 18:49:02 -0700470void Dbg::GcDidFinish() {
471 if (gDdmHpifWhen != HPIF_WHEN_NEVER) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700472 ScopedObjectAccess soa(Thread::Current());
Elliott Hughes81ff3182012-03-23 20:35:56 -0700473 LOG(DEBUG) << "Sending heap info to DDM";
Elliott Hughes7162ad92011-10-27 14:08:42 -0700474 DdmSendHeapInfo(gDdmHpifWhen);
Elliott Hughes767a1472011-10-26 18:49:02 -0700475 }
476 if (gDdmHpsgWhen != HPSG_WHEN_NEVER) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700477 ScopedObjectAccess soa(Thread::Current());
Elliott Hughes81ff3182012-03-23 20:35:56 -0700478 LOG(DEBUG) << "Dumping heap to DDM";
Elliott Hughes6a5bd492011-10-28 14:33:57 -0700479 DdmSendHeapSegments(false);
Elliott Hughes767a1472011-10-26 18:49:02 -0700480 }
481 if (gDdmNhsgWhen != HPSG_WHEN_NEVER) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700482 ScopedObjectAccess soa(Thread::Current());
Elliott Hughes767a1472011-10-26 18:49:02 -0700483 LOG(DEBUG) << "Dumping native heap to DDM";
Elliott Hughes6a5bd492011-10-28 14:33:57 -0700484 DdmSendHeapSegments(true);
Elliott Hughes767a1472011-10-26 18:49:02 -0700485 }
486}
487
Elliott Hughes4ffd3132011-10-24 12:06:42 -0700488void Dbg::SetJdwpAllowed(bool allowed) {
489 gJdwpAllowed = allowed;
490}
491
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700492DebugInvokeReq* Dbg::GetInvokeReq() {
Elliott Hughes475fc232011-10-25 15:00:35 -0700493 return Thread::Current()->GetInvokeReq();
494}
495
496Thread* Dbg::GetDebugThread() {
497 return (gJdwpState != NULL) ? gJdwpState->GetDebugThread() : NULL;
498}
499
500void Dbg::ClearWaitForEventThread() {
501 gJdwpState->ClearWaitForEventThread();
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700502}
503
504void Dbg::Connected() {
Elliott Hughes3bb81562011-10-21 18:52:59 -0700505 CHECK(!gDebuggerConnected);
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -0800506 VLOG(jdwp) << "JDWP has attached";
Elliott Hughes3bb81562011-10-21 18:52:59 -0700507 gDebuggerConnected = true;
Elliott Hughes86964332012-02-15 19:37:42 -0800508 gDisposed = false;
509}
510
511void Dbg::Disposed() {
512 gDisposed = true;
513}
514
515bool Dbg::IsDisposed() {
516 return gDisposed;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700517}
518
Elliott Hughesa2155262011-11-16 16:26:58 -0800519void Dbg::GoActive() {
520 // Enable all debugging features, including scans for breakpoints.
521 // This is a no-op if we're already active.
522 // Only called from the JDWP handler thread.
523 if (gDebuggerActive) {
524 return;
525 }
526
Elliott Hughesc0f09332012-03-26 13:27:06 -0700527 {
528 // TODO: dalvik only warned if there were breakpoints left over. clear in Dbg::Disconnected?
jeffhao09bfc6a2012-12-11 18:11:43 -0800529 MutexLock mu(Thread::Current(), *Locks::breakpoint_lock_);
Elliott Hughesc0f09332012-03-26 13:27:06 -0700530 CHECK_EQ(gBreakpoints.size(), 0U);
531 }
Elliott Hughesa2155262011-11-16 16:26:58 -0800532
Ian Rogers62d6c772013-02-27 08:32:07 -0800533 Runtime* runtime = Runtime::Current();
534 runtime->GetThreadList()->SuspendAll();
535 Thread* self = Thread::Current();
536 ThreadState old_state = self->SetStateUnsafe(kRunnable);
537 CHECK_NE(old_state, kRunnable);
538 runtime->GetInstrumentation()->AddListener(&gDebugInstrumentationListener,
539 instrumentation::Instrumentation::kMethodEntered |
540 instrumentation::Instrumentation::kMethodExited |
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;
1694 case kWaitingForJniOnLoad: *pThreadStatus = JDWP::TS_WAIT; break;
1695 case kWaitingForSignalCatcherOutput: *pThreadStatus = JDWP::TS_WAIT; break;
1696 case kWaitingInMainDebuggerLoop: *pThreadStatus = JDWP::TS_WAIT; break;
1697 case kWaitingInMainSignalCatcherLoop: *pThreadStatus = JDWP::TS_WAIT; break;
1698 case kWaitingPerformingGc: *pThreadStatus = JDWP::TS_WAIT; break;
1699 case kWaiting: *pThreadStatus = JDWP::TS_WAIT; break;
1700 // Don't add a 'default' here so the compiler can spot incompatible enum changes.
1701 }
Elliott Hughes221229c2013-01-08 18:17:50 -08001702 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001703}
1704
Elliott Hughes221229c2013-01-08 18:17:50 -08001705JDWP::JdwpError Dbg::GetThreadDebugSuspendCount(JDWP::ObjectId thread_id, JDWP::ExpandBuf* pReply) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001706 ScopedObjectAccess soa(Thread::Current());
Ian Rogers50b35e22012-10-04 10:09:15 -07001707 MutexLock mu(soa.Self(), *Locks::thread_list_lock_);
Elliott Hughes221229c2013-01-08 18:17:50 -08001708 Thread* thread;
1709 JDWP::JdwpError error = DecodeThread(soa, thread_id, thread);
1710 if (error != JDWP::ERR_NONE) {
1711 return error;
Elliott Hughes2435a572012-02-17 16:07:41 -08001712 }
Ian Rogers50b35e22012-10-04 10:09:15 -07001713 MutexLock mu2(soa.Self(), *Locks::thread_suspend_count_lock_);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001714 expandBufAdd4BE(pReply, thread->GetDebugSuspendCount());
Elliott Hughes2435a572012-02-17 16:07:41 -08001715 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001716}
1717
Elliott Hughesf9501702013-01-11 11:22:27 -08001718JDWP::JdwpError Dbg::Interrupt(JDWP::ObjectId thread_id) {
1719 ScopedObjectAccess soa(Thread::Current());
1720 MutexLock mu(soa.Self(), *Locks::thread_list_lock_);
1721 Thread* thread;
1722 JDWP::JdwpError error = DecodeThread(soa, thread_id, thread);
1723 if (error != JDWP::ERR_NONE) {
1724 return error;
1725 }
1726 thread->Interrupt();
1727 return JDWP::ERR_NONE;
1728}
1729
Elliott Hughescaf76542012-06-28 16:08:22 -07001730void Dbg::GetThreads(JDWP::ObjectId thread_group_id, std::vector<JDWP::ObjectId>& thread_ids) {
Ian Rogers365c1022012-06-22 15:05:28 -07001731 class ThreadListVisitor {
1732 public:
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001733 ThreadListVisitor(const ScopedObjectAccessUnchecked& soa, mirror::Object* desired_thread_group,
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001734 std::vector<JDWP::ObjectId>& thread_ids)
Ian Rogersb726dcb2012-09-05 08:57:23 -07001735 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_)
jeffhao0dfbb7e2012-11-28 15:26:03 -08001736 : soa_(soa), desired_thread_group_(desired_thread_group), thread_ids_(thread_ids) {}
Ian Rogers365c1022012-06-22 15:05:28 -07001737
Elliott Hughesa2155262011-11-16 16:26:58 -08001738 static void Visit(Thread* t, void* arg) {
1739 reinterpret_cast<ThreadListVisitor*>(arg)->Visit(t);
1740 }
1741
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001742 // TODO: Enable annotalysis. We know lock is held in constructor, but abstraction confuses
1743 // annotalysis.
1744 void Visit(Thread* t) NO_THREAD_SAFETY_ANALYSIS {
Elliott Hughesa2155262011-11-16 16:26:58 -08001745 if (t == Dbg::GetDebugThread()) {
1746 // Skip the JDWP thread. Some debuggers get bent out of shape when they can't suspend and
1747 // query all threads, so it's easier if we just don't tell them about this thread.
1748 return;
1749 }
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001750 mirror::Object* peer = t->GetPeer();
jeffhao0dfbb7e2012-11-28 15:26:03 -08001751 if (IsInDesiredThreadGroup(peer)) {
Ian Rogers120f1c72012-09-28 17:17:10 -07001752 thread_ids_.push_back(gRegistry->Add(peer));
Elliott Hughesa2155262011-11-16 16:26:58 -08001753 }
1754 }
1755
Ian Rogers365c1022012-06-22 15:05:28 -07001756 private:
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001757 bool IsInDesiredThreadGroup(mirror::Object* peer)
jeffhao0dfbb7e2012-11-28 15:26:03 -08001758 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
jeffhao0dfbb7e2012-11-28 15:26:03 -08001759 // peer might be NULL if the thread is still starting up.
1760 if (peer == NULL) {
1761 // We can't tell the debugger about this thread yet.
1762 // TODO: if we identified threads to the debugger by their Thread*
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001763 // rather than their peer's mirror::Object*, we could fix this.
jeffhao0dfbb7e2012-11-28 15:26:03 -08001764 // Doing so might help us report ZOMBIE threads too.
1765 return false;
1766 }
jeffhaoc1e04902012-12-13 12:41:10 -08001767 // Do we want threads from all thread groups?
1768 if (desired_thread_group_ == NULL) {
1769 return true;
1770 }
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001771 mirror::Object* group = soa_.DecodeField(WellKnownClasses::java_lang_Thread_group)->GetObject(peer);
jeffhao0dfbb7e2012-11-28 15:26:03 -08001772 return (group == desired_thread_group_);
1773 }
1774
Mathieu Chartierdbe6f462012-09-25 16:54:50 -07001775 const ScopedObjectAccessUnchecked& soa_;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001776 mirror::Object* const desired_thread_group_;
Elliott Hughescaf76542012-06-28 16:08:22 -07001777 std::vector<JDWP::ObjectId>& thread_ids_;
Elliott Hughesa2155262011-11-16 16:26:58 -08001778 };
1779
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001780 ScopedObjectAccessUnchecked soa(Thread::Current());
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001781 mirror::Object* thread_group = gRegistry->Get<mirror::Object*>(thread_group_id);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001782 ThreadListVisitor tlv(soa, thread_group, thread_ids);
Ian Rogers50b35e22012-10-04 10:09:15 -07001783 MutexLock mu(soa.Self(), *Locks::thread_list_lock_);
Elliott Hughesf8349362012-06-18 15:00:06 -07001784 Runtime::Current()->GetThreadList()->ForEach(ThreadListVisitor::Visit, &tlv);
Elliott Hughescaf76542012-06-28 16:08:22 -07001785}
Elliott Hughesa2155262011-11-16 16:26:58 -08001786
Elliott Hughescaf76542012-06-28 16:08:22 -07001787void Dbg::GetChildThreadGroups(JDWP::ObjectId thread_group_id, std::vector<JDWP::ObjectId>& child_thread_group_ids) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001788 ScopedObjectAccess soa(Thread::Current());
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001789 mirror::Object* thread_group = gRegistry->Get<mirror::Object*>(thread_group_id);
Elliott Hughescaf76542012-06-28 16:08:22 -07001790
1791 // Get the ArrayList<ThreadGroup> "groups" out of this thread group...
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001792 mirror::Field* groups_field = thread_group->GetClass()->FindInstanceField("groups", "Ljava/util/List;");
1793 mirror::Object* groups_array_list = groups_field->GetObject(thread_group);
Elliott Hughescaf76542012-06-28 16:08:22 -07001794
1795 // Get the array and size out of the ArrayList<ThreadGroup>...
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001796 mirror::Field* array_field = groups_array_list->GetClass()->FindInstanceField("array", "[Ljava/lang/Object;");
1797 mirror::Field* size_field = groups_array_list->GetClass()->FindInstanceField("size", "I");
1798 mirror::ObjectArray<mirror::Object>* groups_array =
1799 array_field->GetObject(groups_array_list)->AsObjectArray<mirror::Object>();
Elliott Hughescaf76542012-06-28 16:08:22 -07001800 const int32_t size = size_field->GetInt(groups_array_list);
1801
1802 // Copy the first 'size' elements out of the array into the result.
1803 for (int32_t i = 0; i < size; ++i) {
1804 child_thread_group_ids.push_back(gRegistry->Add(groups_array->Get(i)));
Elliott Hughesa2155262011-11-16 16:26:58 -08001805 }
1806}
1807
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001808static int GetStackDepth(Thread* thread)
Ian Rogersb726dcb2012-09-05 08:57:23 -07001809 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Ian Rogers0399dde2012-06-06 17:09:28 -07001810 struct CountStackDepthVisitor : public StackVisitor {
Ian Rogers7a22fa62013-01-23 12:16:16 -08001811 CountStackDepthVisitor(Thread* thread)
1812 : StackVisitor(thread, NULL), depth(0) {}
Ian Rogers0399dde2012-06-06 17:09:28 -07001813
Elliott Hughes64f574f2013-02-20 14:57:12 -08001814 // TODO: Enable annotalysis. We know lock is held in constructor, but abstraction confuses
1815 // annotalysis.
1816 bool VisitFrame() NO_THREAD_SAFETY_ANALYSIS {
Ian Rogers0399dde2012-06-06 17:09:28 -07001817 if (!GetMethod()->IsRuntimeMethod()) {
Elliott Hughesf8a2df72011-12-01 12:19:54 -08001818 ++depth;
1819 }
Elliott Hughes530fa002012-03-12 11:44:49 -07001820 return true;
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001821 }
1822 size_t depth;
1823 };
Elliott Hughes08fc03a2012-06-26 17:34:00 -07001824
Ian Rogers7a22fa62013-01-23 12:16:16 -08001825 CountStackDepthVisitor visitor(thread);
Ian Rogers0399dde2012-06-06 17:09:28 -07001826 visitor.WalkStack();
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001827 return visitor.depth;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001828}
1829
Elliott Hughes221229c2013-01-08 18:17:50 -08001830JDWP::JdwpError Dbg::GetThreadFrameCount(JDWP::ObjectId thread_id, size_t& result) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001831 ScopedObjectAccess soa(Thread::Current());
jeffhaoa77f0f62012-12-05 17:19:31 -08001832 MutexLock mu(soa.Self(), *Locks::thread_list_lock_);
Elliott Hughes221229c2013-01-08 18:17:50 -08001833 Thread* thread;
1834 JDWP::JdwpError error = DecodeThread(soa, thread_id, thread);
1835 if (error != JDWP::ERR_NONE) {
1836 return error;
1837 }
Elliott Hughesf15f4a02013-01-09 10:09:38 -08001838 if (!IsSuspendedForDebugger(soa, thread)) {
1839 return JDWP::ERR_THREAD_NOT_SUSPENDED;
1840 }
Elliott Hughes221229c2013-01-08 18:17:50 -08001841 result = GetStackDepth(thread);
1842 return JDWP::ERR_NONE;
Elliott Hughes86964332012-02-15 19:37:42 -08001843}
1844
Ian Rogers306057f2012-11-26 12:45:53 -08001845JDWP::JdwpError Dbg::GetThreadFrames(JDWP::ObjectId thread_id, size_t start_frame,
1846 size_t frame_count, JDWP::ExpandBuf* buf) {
Elliott Hughes6e9d22c2012-06-22 15:02:37 -07001847 class GetFrameVisitor : public StackVisitor {
1848 public:
Ian Rogers7a22fa62013-01-23 12:16:16 -08001849 GetFrameVisitor(Thread* thread, size_t start_frame, size_t frame_count, JDWP::ExpandBuf* buf)
Ian Rogersb726dcb2012-09-05 08:57:23 -07001850 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_)
Ian Rogers7a22fa62013-01-23 12:16:16 -08001851 : StackVisitor(thread, NULL), depth_(0),
Elliott Hughes6e9d22c2012-06-22 15:02:37 -07001852 start_frame_(start_frame), frame_count_(frame_count), buf_(buf) {
1853 expandBufAdd4BE(buf_, frame_count_);
Elliott Hughes03181a82011-11-17 17:22:21 -08001854 }
Ian Rogers0399dde2012-06-06 17:09:28 -07001855
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001856 // TODO: Enable annotalysis. We know lock is held in constructor, but abstraction confuses
1857 // annotalysis.
1858 virtual bool VisitFrame() NO_THREAD_SAFETY_ANALYSIS {
Ian Rogers0399dde2012-06-06 17:09:28 -07001859 if (GetMethod()->IsRuntimeMethod()) {
Elliott Hughes530fa002012-03-12 11:44:49 -07001860 return true; // The debugger can't do anything useful with a frame that has no Method*.
Elliott Hughes03181a82011-11-17 17:22:21 -08001861 }
Elliott Hughes6e9d22c2012-06-22 15:02:37 -07001862 if (depth_ >= start_frame_ + frame_count_) {
Elliott Hughes530fa002012-03-12 11:44:49 -07001863 return false;
Elliott Hughes03181a82011-11-17 17:22:21 -08001864 }
Elliott Hughes6e9d22c2012-06-22 15:02:37 -07001865 if (depth_ >= start_frame_) {
1866 JDWP::FrameId frame_id(GetFrameId());
1867 JDWP::JdwpLocation location;
1868 SetLocation(location, GetMethod(), GetDexPc());
Elliott Hughes7baf96f2012-06-22 16:33:50 -07001869 VLOG(jdwp) << StringPrintf(" Frame %3zd: id=%3lld ", depth_, frame_id) << location;
Elliott Hughes6e9d22c2012-06-22 15:02:37 -07001870 expandBufAdd8BE(buf_, frame_id);
1871 expandBufAddLocation(buf_, location);
1872 }
1873 ++depth_;
Elliott Hughes530fa002012-03-12 11:44:49 -07001874 return true;
Elliott Hughes03181a82011-11-17 17:22:21 -08001875 }
Elliott Hughes6e9d22c2012-06-22 15:02:37 -07001876
1877 private:
1878 size_t depth_;
1879 const size_t start_frame_;
1880 const size_t frame_count_;
1881 JDWP::ExpandBuf* buf_;
Elliott Hughes03181a82011-11-17 17:22:21 -08001882 };
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001883
1884 ScopedObjectAccessUnchecked soa(Thread::Current());
jeffhaoa77f0f62012-12-05 17:19:31 -08001885 MutexLock mu(soa.Self(), *Locks::thread_list_lock_);
Elliott Hughes221229c2013-01-08 18:17:50 -08001886 Thread* thread;
1887 JDWP::JdwpError error = DecodeThread(soa, thread_id, thread);
1888 if (error != JDWP::ERR_NONE) {
1889 return error;
1890 }
Elliott Hughesf15f4a02013-01-09 10:09:38 -08001891 if (!IsSuspendedForDebugger(soa, thread)) {
1892 return JDWP::ERR_THREAD_NOT_SUSPENDED;
1893 }
Ian Rogers7a22fa62013-01-23 12:16:16 -08001894 GetFrameVisitor visitor(thread, start_frame, frame_count, buf);
Ian Rogers0399dde2012-06-06 17:09:28 -07001895 visitor.WalkStack();
Elliott Hughes6e9d22c2012-06-22 15:02:37 -07001896 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001897}
1898
1899JDWP::ObjectId Dbg::GetThreadSelfId() {
Mathieu Chartierdbe6f462012-09-25 16:54:50 -07001900 ScopedObjectAccessUnchecked soa(Thread::Current());
Ian Rogerscfaa4552012-11-26 21:00:08 -08001901 return gRegistry->Add(soa.Self()->GetPeer());
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001902}
1903
Elliott Hughes475fc232011-10-25 15:00:35 -07001904void Dbg::SuspendVM() {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001905 Runtime::Current()->GetThreadList()->SuspendAllForDebugger();
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001906}
1907
1908void Dbg::ResumeVM() {
Elliott Hughesc61a2672012-06-21 14:52:29 -07001909 Runtime::Current()->GetThreadList()->UndoDebuggerSuspensions();
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001910}
1911
Elliott Hughes221229c2013-01-08 18:17:50 -08001912JDWP::JdwpError Dbg::SuspendThread(JDWP::ObjectId thread_id, bool request_suspension) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001913 ScopedLocalRef<jobject> peer(Thread::Current()->GetJniEnv(), NULL);
1914 {
1915 ScopedObjectAccess soa(Thread::Current());
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001916 peer.reset(soa.AddLocalReference<jobject>(gRegistry->Get<mirror::Object*>(thread_id)));
Elliott Hughes4e235312011-12-02 11:34:15 -08001917 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001918 if (peer.get() == NULL) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001919 return JDWP::ERR_THREAD_NOT_ALIVE;
1920 }
1921 // Suspend thread to build stack trace.
Elliott Hughesf327e072013-01-09 16:01:26 -08001922 bool timed_out;
1923 Thread* thread = Thread::SuspendForDebugger(peer.get(), request_suspension, &timed_out);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001924 if (thread != NULL) {
1925 return JDWP::ERR_NONE;
Elliott Hughesf327e072013-01-09 16:01:26 -08001926 } else if (timed_out) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001927 return JDWP::ERR_INTERNAL;
1928 } else {
1929 return JDWP::ERR_THREAD_NOT_ALIVE;
1930 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001931}
1932
Elliott Hughes221229c2013-01-08 18:17:50 -08001933void Dbg::ResumeThread(JDWP::ObjectId thread_id) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001934 ScopedObjectAccessUnchecked soa(Thread::Current());
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001935 mirror::Object* peer = gRegistry->Get<mirror::Object*>(thread_id);
jeffhaoa77f0f62012-12-05 17:19:31 -08001936 Thread* thread;
1937 {
1938 MutexLock mu(soa.Self(), *Locks::thread_list_lock_);
1939 thread = Thread::FromManagedThread(soa, peer);
1940 }
Elliott Hughes4e235312011-12-02 11:34:15 -08001941 if (thread == NULL) {
1942 LOG(WARNING) << "No such thread for resume: " << peer;
1943 return;
1944 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001945 bool needs_resume;
1946 {
Ian Rogers50b35e22012-10-04 10:09:15 -07001947 MutexLock mu2(soa.Self(), *Locks::thread_suspend_count_lock_);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001948 needs_resume = thread->GetSuspendCount() > 0;
1949 }
1950 if (needs_resume) {
Elliott Hughes546b9862012-06-20 16:06:13 -07001951 Runtime::Current()->GetThreadList()->Resume(thread, true);
1952 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001953}
1954
1955void Dbg::SuspendSelf() {
Elliott Hughes475fc232011-10-25 15:00:35 -07001956 Runtime::Current()->GetThreadList()->SuspendSelfForDebugger();
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001957}
1958
Ian Rogers0399dde2012-06-06 17:09:28 -07001959struct GetThisVisitor : public StackVisitor {
Ian Rogers7a22fa62013-01-23 12:16:16 -08001960 GetThisVisitor(Thread* thread, Context* context, JDWP::FrameId frame_id)
Ian Rogersb726dcb2012-09-05 08:57:23 -07001961 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_)
Ian Rogers7a22fa62013-01-23 12:16:16 -08001962 : StackVisitor(thread, context), this_object(NULL), frame_id(frame_id) {}
Ian Rogers0399dde2012-06-06 17:09:28 -07001963
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001964 // TODO: Enable annotalysis. We know lock is held in constructor, but abstraction confuses
1965 // annotalysis.
1966 virtual bool VisitFrame() NO_THREAD_SAFETY_ANALYSIS {
Elliott Hughes6e9d22c2012-06-22 15:02:37 -07001967 if (frame_id != GetFrameId()) {
Ian Rogers0399dde2012-06-06 17:09:28 -07001968 return true; // continue
Ian Rogers0399dde2012-06-06 17:09:28 -07001969 } else {
Ian Rogers62d6c772013-02-27 08:32:07 -08001970 this_object = GetThisObject();
1971 return false;
Ian Rogers0399dde2012-06-06 17:09:28 -07001972 }
Elliott Hughes86b00102011-12-05 17:54:26 -08001973 }
Ian Rogers0399dde2012-06-06 17:09:28 -07001974
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001975 mirror::Object* this_object;
Elliott Hughes6e9d22c2012-06-22 15:02:37 -07001976 JDWP::FrameId frame_id;
Ian Rogers0399dde2012-06-06 17:09:28 -07001977};
1978
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001979JDWP::JdwpError Dbg::GetThisObject(JDWP::ObjectId thread_id, JDWP::FrameId frame_id,
1980 JDWP::ObjectId* result) {
1981 ScopedObjectAccessUnchecked soa(Thread::Current());
1982 Thread* thread;
1983 {
Ian Rogers50b35e22012-10-04 10:09:15 -07001984 MutexLock mu(soa.Self(), *Locks::thread_list_lock_);
Elliott Hughes221229c2013-01-08 18:17:50 -08001985 JDWP::JdwpError error = DecodeThread(soa, thread_id, thread);
1986 if (error != JDWP::ERR_NONE) {
1987 return error;
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001988 }
Elliott Hughes9e0c1752013-01-09 14:02:58 -08001989 if (!IsSuspendedForDebugger(soa, thread)) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001990 return JDWP::ERR_THREAD_NOT_SUSPENDED;
1991 }
Elliott Hughes6e9d22c2012-06-22 15:02:37 -07001992 }
Elliott Hughescaf76542012-06-28 16:08:22 -07001993 UniquePtr<Context> context(Context::Create());
Ian Rogers7a22fa62013-01-23 12:16:16 -08001994 GetThisVisitor visitor(thread, context.get(), frame_id);
Ian Rogers0399dde2012-06-06 17:09:28 -07001995 visitor.WalkStack();
Elliott Hughes6e9d22c2012-06-22 15:02:37 -07001996 *result = gRegistry->Add(visitor.this_object);
1997 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001998}
1999
Elliott Hughes88d63092013-01-09 09:55:54 -08002000void Dbg::GetLocalValue(JDWP::ObjectId thread_id, JDWP::FrameId frame_id, int slot, JDWP::JdwpTag tag,
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002001 uint8_t* buf, size_t width) {
Ian Rogers0399dde2012-06-06 17:09:28 -07002002 struct GetLocalVisitor : public StackVisitor {
Ian Rogers7a22fa62013-01-23 12:16:16 -08002003 GetLocalVisitor(Thread* thread, Context* context, JDWP::FrameId frame_id, int slot,
2004 JDWP::JdwpTag tag, uint8_t* buf, size_t width)
Ian Rogersb726dcb2012-09-05 08:57:23 -07002005 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_)
Ian Rogers7a22fa62013-01-23 12:16:16 -08002006 : StackVisitor(thread, context), frame_id_(frame_id), slot_(slot), tag_(tag),
Ian Rogersca190662012-06-26 15:45:57 -07002007 buf_(buf), width_(width) {}
2008
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002009 // TODO: Enable annotalysis. We know lock is held in constructor, but abstraction confuses
2010 // annotalysis.
2011 bool VisitFrame() NO_THREAD_SAFETY_ANALYSIS {
Ian Rogers0399dde2012-06-06 17:09:28 -07002012 if (GetFrameId() != frame_id_) {
2013 return true; // Not our frame, carry on.
Elliott Hughesdbb40792011-11-18 17:05:22 -08002014 }
Ian Rogers0399dde2012-06-06 17:09:28 -07002015 // TODO: check that the tag is compatible with the actual type of the slot!
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002016 mirror::AbstractMethod* m = GetMethod();
Ian Rogers0399dde2012-06-06 17:09:28 -07002017 uint16_t reg = DemangleSlot(slot_, m);
Elliott Hughesdbb40792011-11-18 17:05:22 -08002018
Ian Rogers0399dde2012-06-06 17:09:28 -07002019 switch (tag_) {
2020 case JDWP::JT_BOOLEAN:
2021 {
2022 CHECK_EQ(width_, 1U);
Ian Rogers2bcb4a42012-11-08 10:39:18 -08002023 uint32_t intVal = GetVReg(m, reg, kIntVReg);
Ian Rogers0399dde2012-06-06 17:09:28 -07002024 VLOG(jdwp) << "get boolean local " << reg << " = " << intVal;
2025 JDWP::Set1(buf_+1, intVal != 0);
2026 }
2027 break;
2028 case JDWP::JT_BYTE:
2029 {
2030 CHECK_EQ(width_, 1U);
Ian Rogers2bcb4a42012-11-08 10:39:18 -08002031 uint32_t intVal = GetVReg(m, reg, kIntVReg);
Ian Rogers0399dde2012-06-06 17:09:28 -07002032 VLOG(jdwp) << "get byte local " << reg << " = " << intVal;
2033 JDWP::Set1(buf_+1, intVal);
2034 }
2035 break;
2036 case JDWP::JT_SHORT:
2037 case JDWP::JT_CHAR:
2038 {
2039 CHECK_EQ(width_, 2U);
Ian Rogers2bcb4a42012-11-08 10:39:18 -08002040 uint32_t intVal = GetVReg(m, reg, kIntVReg);
Ian Rogers0399dde2012-06-06 17:09:28 -07002041 VLOG(jdwp) << "get short/char local " << reg << " = " << intVal;
2042 JDWP::Set2BE(buf_+1, intVal);
2043 }
2044 break;
2045 case JDWP::JT_INT:
Ian Rogers2bcb4a42012-11-08 10:39:18 -08002046 {
2047 CHECK_EQ(width_, 4U);
2048 uint32_t intVal = GetVReg(m, reg, kIntVReg);
2049 VLOG(jdwp) << "get int local " << reg << " = " << intVal;
2050 JDWP::Set4BE(buf_+1, intVal);
2051 }
2052 break;
Ian Rogers0399dde2012-06-06 17:09:28 -07002053 case JDWP::JT_FLOAT:
2054 {
2055 CHECK_EQ(width_, 4U);
Ian Rogers2bcb4a42012-11-08 10:39:18 -08002056 uint32_t intVal = GetVReg(m, reg, kFloatVReg);
Ian Rogers0399dde2012-06-06 17:09:28 -07002057 VLOG(jdwp) << "get int/float local " << reg << " = " << intVal;
2058 JDWP::Set4BE(buf_+1, intVal);
2059 }
2060 break;
2061 case JDWP::JT_ARRAY:
2062 {
2063 CHECK_EQ(width_, sizeof(JDWP::ObjectId));
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002064 mirror::Object* o = reinterpret_cast<mirror::Object*>(GetVReg(m, reg, kReferenceVReg));
Ian Rogers0399dde2012-06-06 17:09:28 -07002065 VLOG(jdwp) << "get array local " << reg << " = " << o;
2066 if (!Runtime::Current()->GetHeap()->IsHeapAddress(o)) {
2067 LOG(FATAL) << "Register " << reg << " expected to hold array: " << o;
2068 }
2069 JDWP::SetObjectId(buf_+1, gRegistry->Add(o));
2070 }
2071 break;
2072 case JDWP::JT_CLASS_LOADER:
2073 case JDWP::JT_CLASS_OBJECT:
2074 case JDWP::JT_OBJECT:
2075 case JDWP::JT_STRING:
2076 case JDWP::JT_THREAD:
2077 case JDWP::JT_THREAD_GROUP:
2078 {
2079 CHECK_EQ(width_, sizeof(JDWP::ObjectId));
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002080 mirror::Object* o = reinterpret_cast<mirror::Object*>(GetVReg(m, reg, kReferenceVReg));
Ian Rogers0399dde2012-06-06 17:09:28 -07002081 VLOG(jdwp) << "get object local " << reg << " = " << o;
2082 if (!Runtime::Current()->GetHeap()->IsHeapAddress(o)) {
2083 LOG(FATAL) << "Register " << reg << " expected to hold object: " << o;
2084 }
2085 tag_ = TagFromObject(o);
2086 JDWP::SetObjectId(buf_+1, gRegistry->Add(o));
2087 }
2088 break;
2089 case JDWP::JT_DOUBLE:
Ian Rogers2bcb4a42012-11-08 10:39:18 -08002090 {
2091 CHECK_EQ(width_, 8U);
2092 uint32_t lo = GetVReg(m, reg, kDoubleLoVReg);
2093 uint64_t hi = GetVReg(m, reg + 1, kDoubleHiVReg);
2094 uint64_t longVal = (hi << 32) | lo;
2095 VLOG(jdwp) << "get double/long local " << hi << ":" << lo << " = " << longVal;
2096 JDWP::Set8BE(buf_+1, longVal);
2097 }
2098 break;
Ian Rogers0399dde2012-06-06 17:09:28 -07002099 case JDWP::JT_LONG:
2100 {
2101 CHECK_EQ(width_, 8U);
Ian Rogers2bcb4a42012-11-08 10:39:18 -08002102 uint32_t lo = GetVReg(m, reg, kLongLoVReg);
2103 uint64_t hi = GetVReg(m, reg + 1, kLongHiVReg);
Ian Rogers0399dde2012-06-06 17:09:28 -07002104 uint64_t longVal = (hi << 32) | lo;
2105 VLOG(jdwp) << "get double/long local " << hi << ":" << lo << " = " << longVal;
2106 JDWP::Set8BE(buf_+1, longVal);
2107 }
2108 break;
2109 default:
2110 LOG(FATAL) << "Unknown tag " << tag_;
2111 break;
2112 }
2113
2114 // Prepend tag, which may have been updated.
2115 JDWP::Set1(buf_, tag_);
2116 return false;
2117 }
2118
2119 const JDWP::FrameId frame_id_;
2120 const int slot_;
2121 JDWP::JdwpTag tag_;
2122 uint8_t* const buf_;
2123 const size_t width_;
2124 };
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002125
2126 ScopedObjectAccessUnchecked soa(Thread::Current());
jeffhaoa77f0f62012-12-05 17:19:31 -08002127 MutexLock mu(soa.Self(), *Locks::thread_list_lock_);
Elliott Hughes221229c2013-01-08 18:17:50 -08002128 Thread* thread;
2129 JDWP::JdwpError error = DecodeThread(soa, thread_id, thread);
2130 if (error != JDWP::ERR_NONE) {
2131 return;
2132 }
Ian Rogers0399dde2012-06-06 17:09:28 -07002133 UniquePtr<Context> context(Context::Create());
Ian Rogers7a22fa62013-01-23 12:16:16 -08002134 GetLocalVisitor visitor(thread, context.get(), frame_id, slot, tag, buf, width);
Ian Rogers0399dde2012-06-06 17:09:28 -07002135 visitor.WalkStack();
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002136}
2137
Elliott Hughes88d63092013-01-09 09:55:54 -08002138void Dbg::SetLocalValue(JDWP::ObjectId thread_id, JDWP::FrameId frame_id, int slot, JDWP::JdwpTag tag,
Ian Rogers0399dde2012-06-06 17:09:28 -07002139 uint64_t value, size_t width) {
2140 struct SetLocalVisitor : public StackVisitor {
Ian Rogers7a22fa62013-01-23 12:16:16 -08002141 SetLocalVisitor(Thread* thread, Context* context,
Ian Rogers0399dde2012-06-06 17:09:28 -07002142 JDWP::FrameId frame_id, int slot, JDWP::JdwpTag tag, uint64_t value,
Ian Rogersca190662012-06-26 15:45:57 -07002143 size_t width)
Ian Rogersb726dcb2012-09-05 08:57:23 -07002144 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_)
Ian Rogers7a22fa62013-01-23 12:16:16 -08002145 : StackVisitor(thread, context),
Elliott Hughes08fc03a2012-06-26 17:34:00 -07002146 frame_id_(frame_id), slot_(slot), tag_(tag), value_(value), width_(width) {}
Ian Rogersca190662012-06-26 15:45:57 -07002147
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002148 // TODO: Enable annotalysis. We know lock is held in constructor, but abstraction confuses
2149 // annotalysis.
2150 bool VisitFrame() NO_THREAD_SAFETY_ANALYSIS {
Ian Rogers0399dde2012-06-06 17:09:28 -07002151 if (GetFrameId() != frame_id_) {
2152 return true; // Not our frame, carry on.
2153 }
2154 // TODO: check that the tag is compatible with the actual type of the slot!
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002155 mirror::AbstractMethod* m = GetMethod();
Ian Rogers0399dde2012-06-06 17:09:28 -07002156 uint16_t reg = DemangleSlot(slot_, m);
2157
2158 switch (tag_) {
2159 case JDWP::JT_BOOLEAN:
2160 case JDWP::JT_BYTE:
2161 CHECK_EQ(width_, 1U);
Ian Rogers2bcb4a42012-11-08 10:39:18 -08002162 SetVReg(m, reg, static_cast<uint32_t>(value_), kIntVReg);
Ian Rogers0399dde2012-06-06 17:09:28 -07002163 break;
2164 case JDWP::JT_SHORT:
2165 case JDWP::JT_CHAR:
2166 CHECK_EQ(width_, 2U);
Ian Rogers2bcb4a42012-11-08 10:39:18 -08002167 SetVReg(m, reg, static_cast<uint32_t>(value_), kIntVReg);
Ian Rogers0399dde2012-06-06 17:09:28 -07002168 break;
2169 case JDWP::JT_INT:
Ian Rogers2bcb4a42012-11-08 10:39:18 -08002170 CHECK_EQ(width_, 4U);
2171 SetVReg(m, reg, static_cast<uint32_t>(value_), kIntVReg);
2172 break;
Ian Rogers0399dde2012-06-06 17:09:28 -07002173 case JDWP::JT_FLOAT:
2174 CHECK_EQ(width_, 4U);
Ian Rogers2bcb4a42012-11-08 10:39:18 -08002175 SetVReg(m, reg, static_cast<uint32_t>(value_), kFloatVReg);
Ian Rogers0399dde2012-06-06 17:09:28 -07002176 break;
2177 case JDWP::JT_ARRAY:
2178 case JDWP::JT_OBJECT:
2179 case JDWP::JT_STRING:
2180 {
2181 CHECK_EQ(width_, sizeof(JDWP::ObjectId));
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002182 mirror::Object* o = gRegistry->Get<mirror::Object*>(static_cast<JDWP::ObjectId>(value_));
Elliott Hughes64f574f2013-02-20 14:57:12 -08002183 if (o == ObjectRegistry::kInvalidObject) {
Ian Rogers0399dde2012-06-06 17:09:28 -07002184 UNIMPLEMENTED(FATAL) << "return an error code when given an invalid object to store";
2185 }
Ian Rogers2bcb4a42012-11-08 10:39:18 -08002186 SetVReg(m, reg, static_cast<uint32_t>(reinterpret_cast<uintptr_t>(o)), kReferenceVReg);
Ian Rogers0399dde2012-06-06 17:09:28 -07002187 }
2188 break;
2189 case JDWP::JT_DOUBLE:
Ian Rogers2bcb4a42012-11-08 10:39:18 -08002190 CHECK_EQ(width_, 8U);
2191 SetVReg(m, reg, static_cast<uint32_t>(value_), kDoubleLoVReg);
2192 SetVReg(m, reg + 1, static_cast<uint32_t>(value_ >> 32), kDoubleHiVReg);
2193 break;
Ian Rogers0399dde2012-06-06 17:09:28 -07002194 case JDWP::JT_LONG:
2195 CHECK_EQ(width_, 8U);
Ian Rogers2bcb4a42012-11-08 10:39:18 -08002196 SetVReg(m, reg, static_cast<uint32_t>(value_), kLongLoVReg);
2197 SetVReg(m, reg + 1, static_cast<uint32_t>(value_ >> 32), kLongHiVReg);
Ian Rogers0399dde2012-06-06 17:09:28 -07002198 break;
2199 default:
2200 LOG(FATAL) << "Unknown tag " << tag_;
2201 break;
2202 }
2203 return false;
2204 }
2205
2206 const JDWP::FrameId frame_id_;
2207 const int slot_;
2208 const JDWP::JdwpTag tag_;
2209 const uint64_t value_;
2210 const size_t width_;
2211 };
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002212
2213 ScopedObjectAccessUnchecked soa(Thread::Current());
jeffhaoa77f0f62012-12-05 17:19:31 -08002214 MutexLock mu(soa.Self(), *Locks::thread_list_lock_);
Elliott Hughes221229c2013-01-08 18:17:50 -08002215 Thread* thread;
2216 JDWP::JdwpError error = DecodeThread(soa, thread_id, thread);
2217 if (error != JDWP::ERR_NONE) {
2218 return;
2219 }
Elliott Hughes08fc03a2012-06-26 17:34:00 -07002220 UniquePtr<Context> context(Context::Create());
Ian Rogers7a22fa62013-01-23 12:16:16 -08002221 SetLocalVisitor visitor(thread, context.get(), frame_id, slot, tag, value, width);
Ian Rogers0399dde2012-06-06 17:09:28 -07002222 visitor.WalkStack();
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002223}
2224
Ian Rogers62d6c772013-02-27 08:32:07 -08002225void Dbg::PostLocationEvent(const mirror::AbstractMethod* m, int dex_pc,
2226 mirror::Object* this_object, int event_flags) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002227 mirror::Class* c = m->GetDeclaringClass();
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08002228
2229 JDWP::JdwpLocation location;
Elliott Hughes74847412012-06-20 18:10:21 -07002230 location.type_tag = c->IsInterface() ? JDWP::TT_INTERFACE : JDWP::TT_CLASS;
Elliott Hughes64f574f2013-02-20 14:57:12 -08002231 location.class_id = gRegistry->AddRefType(c);
Elliott Hughes74847412012-06-20 18:10:21 -07002232 location.method_id = ToMethodId(m);
Elliott Hughes972a47b2012-02-21 18:16:06 -08002233 location.dex_pc = m->IsNative() ? -1 : dex_pc;
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08002234
Elliott Hughes64f574f2013-02-20 14:57:12 -08002235 // If 'this_object' isn't already in the registry, we know that we're not looking for it,
2236 // so there's no point adding it to the registry and burning through ids.
2237 JDWP::ObjectId this_id = 0;
2238 if (gRegistry->Contains(this_object)) {
2239 this_id = gRegistry->Add(this_object);
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08002240 }
Elliott Hughes64f574f2013-02-20 14:57:12 -08002241 gJdwpState->PostLocationEvent(&location, this_id, event_flags);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002242}
2243
Ian Rogers62d6c772013-02-27 08:32:07 -08002244void Dbg::PostException(Thread* thread, const ThrowLocation& throw_location,
2245 mirror::AbstractMethod* catch_method,
Elliott Hughes64f574f2013-02-20 14:57:12 -08002246 uint32_t catch_dex_pc, mirror::Throwable* exception_object) {
Elliott Hughesc0f09332012-03-26 13:27:06 -07002247 if (!IsDebuggerActive()) {
Ian Rogers0ad5bb82011-12-07 10:16:32 -08002248 return;
2249 }
Elliott Hughes4740cdf2011-12-07 14:07:12 -08002250
Ian Rogers62d6c772013-02-27 08:32:07 -08002251 JDWP::JdwpLocation jdwp_throw_location;
2252 SetLocation(jdwp_throw_location, throw_location.GetMethod(), throw_location.GetDexPc());
Elliott Hughesd07986f2011-12-06 18:27:45 -08002253 JDWP::JdwpLocation catch_location;
Elliott Hughescaf76542012-06-28 16:08:22 -07002254 SetLocation(catch_location, catch_method, catch_dex_pc);
Elliott Hughesd07986f2011-12-06 18:27:45 -08002255
2256 // We need 'this' for InstanceOnly filters.
Ian Rogers62d6c772013-02-27 08:32:07 -08002257 JDWP::ObjectId this_id = gRegistry->Add(throw_location.GetThis());
Elliott Hughes64f574f2013-02-20 14:57:12 -08002258 JDWP::ObjectId exception_id = gRegistry->Add(exception_object);
2259 JDWP::RefTypeId exception_class_id = gRegistry->AddRefType(exception_object->GetClass());
Elliott Hughesd07986f2011-12-06 18:27:45 -08002260
Ian Rogers62d6c772013-02-27 08:32:07 -08002261 gJdwpState->PostException(&jdwp_throw_location, exception_id, exception_class_id, &catch_location,
2262 this_id);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002263}
2264
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002265void Dbg::PostClassPrepare(mirror::Class* c) {
Elliott Hughesc0f09332012-03-26 13:27:06 -07002266 if (!IsDebuggerActive()) {
Elliott Hughes4740cdf2011-12-07 14:07:12 -08002267 return;
2268 }
2269
Elliott Hughes3d30d9b2011-12-07 17:35:48 -08002270 // OLD-TODO - we currently always send both "verified" and "prepared" since
Elliott Hughes4740cdf2011-12-07 14:07:12 -08002271 // debuggers seem to like that. There might be some advantage to honesty,
2272 // since the class may not yet be verified.
2273 int state = JDWP::CS_VERIFIED | JDWP::CS_PREPARED;
2274 JDWP::JdwpTypeTag tag = c->IsInterface() ? JDWP::TT_INTERFACE : JDWP::TT_CLASS;
2275 gJdwpState->PostClassPrepare(tag, gRegistry->Add(c), ClassHelper(c).GetDescriptor(), state);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002276}
2277
Ian Rogers62d6c772013-02-27 08:32:07 -08002278void Dbg::UpdateDebugger(Thread* thread, mirror::Object* this_object,
2279 const mirror::AbstractMethod* m, uint32_t dex_pc) {
2280 if (!IsDebuggerActive() || dex_pc == static_cast<uint32_t>(-2) /* fake method exit */) {
Elliott Hughes2aa2e392012-02-17 17:15:43 -08002281 return;
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08002282 }
2283
Elliott Hughes2aa2e392012-02-17 17:15:43 -08002284 int event_flags = 0;
2285
Elliott Hughes86964332012-02-15 19:37:42 -08002286 if (IsBreakpoint(m, dex_pc)) {
2287 event_flags |= kBreakpoint;
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08002288 }
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08002289
jeffhao09bfc6a2012-12-11 18:11:43 -08002290 {
2291 // If the debugger is single-stepping one of our threads, check to
2292 // see if we're that thread and we've reached a step point.
2293 MutexLock mu(Thread::Current(), *Locks::breakpoint_lock_);
Ian Rogers62d6c772013-02-27 08:32:07 -08002294 if (gSingleStepControl.is_active && gSingleStepControl.thread == thread) {
jeffhao09bfc6a2012-12-11 18:11:43 -08002295 CHECK(!m->IsNative());
2296 if (gSingleStepControl.step_depth == JDWP::SD_INTO) {
2297 // Step into method calls. We break when the line number
2298 // or method pointer changes. If we're in SS_MIN mode, we
2299 // always stop.
2300 if (gSingleStepControl.method != m) {
2301 event_flags |= kSingleStep;
2302 VLOG(jdwp) << "SS new method";
2303 } else if (gSingleStepControl.step_size == JDWP::SS_MIN) {
Elliott Hughes86964332012-02-15 19:37:42 -08002304 event_flags |= kSingleStep;
2305 VLOG(jdwp) << "SS new instruction";
Elliott Hughes2435a572012-02-17 16:07:41 -08002306 } else if (gSingleStepControl.dex_pcs.find(dex_pc) == gSingleStepControl.dex_pcs.end()) {
2307 event_flags |= kSingleStep;
2308 VLOG(jdwp) << "SS new line";
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08002309 }
jeffhao09bfc6a2012-12-11 18:11:43 -08002310 } else if (gSingleStepControl.step_depth == JDWP::SD_OVER) {
2311 // Step over method calls. We break when the line number is
2312 // different and the frame depth is <= the original frame
2313 // depth. (We can't just compare on the method, because we
2314 // might get unrolled past it by an exception, and it's tricky
2315 // to identify recursion.)
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08002316
Ian Rogers62d6c772013-02-27 08:32:07 -08002317 int stack_depth = GetStackDepth(thread);
Elliott Hughes86964332012-02-15 19:37:42 -08002318
jeffhao09bfc6a2012-12-11 18:11:43 -08002319 if (stack_depth < gSingleStepControl.stack_depth) {
2320 // popped up one or more frames, always trigger
2321 event_flags |= kSingleStep;
2322 VLOG(jdwp) << "SS method pop";
2323 } else if (stack_depth == gSingleStepControl.stack_depth) {
2324 // same depth, see if we moved
2325 if (gSingleStepControl.step_size == JDWP::SS_MIN) {
2326 event_flags |= kSingleStep;
2327 VLOG(jdwp) << "SS new instruction";
2328 } else if (gSingleStepControl.dex_pcs.find(dex_pc) == gSingleStepControl.dex_pcs.end()) {
2329 event_flags |= kSingleStep;
2330 VLOG(jdwp) << "SS new line";
2331 }
2332 }
2333 } else {
2334 CHECK_EQ(gSingleStepControl.step_depth, JDWP::SD_OUT);
2335 // Return from the current method. We break when the frame
2336 // depth pops up.
2337
2338 // This differs from the "method exit" break in that it stops
2339 // with the PC at the next instruction in the returned-to
2340 // function, rather than the end of the returning function.
2341
Ian Rogers62d6c772013-02-27 08:32:07 -08002342 int stack_depth = GetStackDepth(thread);
jeffhao09bfc6a2012-12-11 18:11:43 -08002343 if (stack_depth < gSingleStepControl.stack_depth) {
2344 event_flags |= kSingleStep;
2345 VLOG(jdwp) << "SS method pop";
2346 }
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08002347 }
2348 }
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08002349 }
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08002350
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08002351 // If there's something interesting going on, see if it matches one
2352 // of the debugger filters.
2353 if (event_flags != 0) {
Ian Rogers62d6c772013-02-27 08:32:07 -08002354 Dbg::PostLocationEvent(m, dex_pc, this_object, event_flags);
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08002355 }
2356}
2357
Elliott Hughes86964332012-02-15 19:37:42 -08002358void Dbg::WatchLocation(const JDWP::JdwpLocation* location) {
jeffhao09bfc6a2012-12-11 18:11:43 -08002359 MutexLock mu(Thread::Current(), *Locks::breakpoint_lock_);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002360 mirror::AbstractMethod* m = FromMethodId(location->method_id);
Elliott Hughes972a47b2012-02-21 18:16:06 -08002361 gBreakpoints.push_back(Breakpoint(m, location->dex_pc));
Elliott Hughes86964332012-02-15 19:37:42 -08002362 VLOG(jdwp) << "Set breakpoint #" << (gBreakpoints.size() - 1) << ": " << gBreakpoints[gBreakpoints.size() - 1];
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002363}
2364
Elliott Hughes86964332012-02-15 19:37:42 -08002365void Dbg::UnwatchLocation(const JDWP::JdwpLocation* location) {
jeffhao09bfc6a2012-12-11 18:11:43 -08002366 MutexLock mu(Thread::Current(), *Locks::breakpoint_lock_);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002367 mirror::AbstractMethod* m = FromMethodId(location->method_id);
Elliott Hughes86964332012-02-15 19:37:42 -08002368 for (size_t i = 0; i < gBreakpoints.size(); ++i) {
Elliott Hughes972a47b2012-02-21 18:16:06 -08002369 if (gBreakpoints[i].method == m && gBreakpoints[i].dex_pc == location->dex_pc) {
Elliott Hughes86964332012-02-15 19:37:42 -08002370 VLOG(jdwp) << "Removed breakpoint #" << i << ": " << gBreakpoints[i];
2371 gBreakpoints.erase(gBreakpoints.begin() + i);
2372 return;
2373 }
2374 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002375}
2376
Jeff Hao449db332013-04-12 18:30:52 -07002377// Scoped utility class to suspend a thread so that we may do tasks such as walk its stack. Doesn't
2378// cause suspension if the thread is the current thread.
2379class ScopedThreadSuspension {
2380 public:
2381 ScopedThreadSuspension(Thread* self, JDWP::ObjectId thread_id) :
2382 thread_(NULL),
2383 error_(JDWP::ERR_NONE),
2384 self_suspend_(false),
2385 other_suspend_(false) SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
2386 ScopedObjectAccessUnchecked soa(self);
2387 {
2388 MutexLock mu(soa.Self(), *Locks::thread_list_lock_);
2389 error_ = DecodeThread(soa, thread_id, thread_);
2390 }
2391 if (error_ == JDWP::ERR_NONE) {
2392 if (thread_ == soa.Self()) {
2393 self_suspend_ = true;
2394 } else {
2395 soa.Self()->TransitionFromRunnableToSuspended(kWaitingForDebuggerSuspension);
2396 jobject thread_peer = gRegistry->GetJObject(thread_id);
2397 bool timed_out;
2398 Thread* suspended_thread = Thread::SuspendForDebugger(thread_peer, true, &timed_out);
2399 CHECK_EQ(soa.Self()->TransitionFromSuspendedToRunnable(), kWaitingForDebuggerSuspension);
2400 if (suspended_thread == NULL) {
2401 // Thread terminated from under us while suspending.
2402 error_ = JDWP::ERR_INVALID_THREAD;
2403 } else {
2404 CHECK_EQ(suspended_thread, thread_);
2405 other_suspend_ = true;
2406 }
2407 }
2408 }
Elliott Hughes2435a572012-02-17 16:07:41 -08002409 }
Elliott Hughes86964332012-02-15 19:37:42 -08002410
Jeff Hao449db332013-04-12 18:30:52 -07002411 Thread* GetThread() const {
2412 return thread_;
2413 }
2414
2415 JDWP::JdwpError GetError() const {
2416 return error_;
2417 }
2418
2419 ~ScopedThreadSuspension() {
2420 if (other_suspend_) {
2421 Runtime::Current()->GetThreadList()->Resume(thread_, true);
2422 }
2423 }
2424
2425 private:
2426 Thread* thread_;
2427 JDWP::JdwpError error_;
2428 bool self_suspend_;
2429 bool other_suspend_;
2430};
2431
2432JDWP::JdwpError Dbg::ConfigureStep(JDWP::ObjectId thread_id, JDWP::JdwpStepSize step_size,
2433 JDWP::JdwpStepDepth step_depth) {
2434 Thread* self = Thread::Current();
2435 ScopedThreadSuspension sts(self, thread_id);
2436 if (sts.GetError() != JDWP::ERR_NONE) {
2437 return sts.GetError();
2438 }
2439
2440 MutexLock mu2(self, *Locks::breakpoint_lock_);
Elliott Hughes86964332012-02-15 19:37:42 -08002441 // TODO: there's no theoretical reason why we couldn't support single-stepping
2442 // of multiple threads at once, but we never did so historically.
Jeff Hao449db332013-04-12 18:30:52 -07002443 if (gSingleStepControl.thread != NULL && sts.GetThread() != gSingleStepControl.thread) {
Elliott Hughes86964332012-02-15 19:37:42 -08002444 LOG(WARNING) << "single-step already active for " << *gSingleStepControl.thread
Jeff Hao449db332013-04-12 18:30:52 -07002445 << "; switching to " << *sts.GetThread();
Elliott Hughes86964332012-02-15 19:37:42 -08002446 }
2447
Elliott Hughes2435a572012-02-17 16:07:41 -08002448 //
2449 // Work out what Method* we're in, the current line number, and how deep the stack currently
2450 // is for step-out.
2451 //
2452
Ian Rogers0399dde2012-06-06 17:09:28 -07002453 struct SingleStepStackVisitor : public StackVisitor {
Ian Rogers7a22fa62013-01-23 12:16:16 -08002454 SingleStepStackVisitor(Thread* thread)
jeffhao09bfc6a2012-12-11 18:11:43 -08002455 EXCLUSIVE_LOCKS_REQUIRED(Locks::breakpoint_lock_)
Ian Rogersb726dcb2012-09-05 08:57:23 -07002456 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_)
Ian Rogers7a22fa62013-01-23 12:16:16 -08002457 : StackVisitor(thread, NULL) {
Elliott Hughes86964332012-02-15 19:37:42 -08002458 gSingleStepControl.method = NULL;
2459 gSingleStepControl.stack_depth = 0;
2460 }
Ian Rogersca190662012-06-26 15:45:57 -07002461
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002462 // TODO: Enable annotalysis. We know lock is held in constructor, but abstraction confuses
2463 // annotalysis.
2464 bool VisitFrame() NO_THREAD_SAFETY_ANALYSIS {
jeffhao09bfc6a2012-12-11 18:11:43 -08002465 Locks::breakpoint_lock_->AssertHeld(Thread::Current());
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002466 const mirror::AbstractMethod* m = GetMethod();
Ian Rogers0399dde2012-06-06 17:09:28 -07002467 if (!m->IsRuntimeMethod()) {
Elliott Hughes86964332012-02-15 19:37:42 -08002468 ++gSingleStepControl.stack_depth;
2469 if (gSingleStepControl.method == NULL) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002470 const mirror::DexCache* dex_cache = m->GetDeclaringClass()->GetDexCache();
Elliott Hughes2435a572012-02-17 16:07:41 -08002471 gSingleStepControl.method = m;
2472 gSingleStepControl.line_number = -1;
2473 if (dex_cache != NULL) {
Ian Rogers4445a7e2012-10-05 17:19:13 -07002474 const DexFile& dex_file = *dex_cache->GetDexFile();
Ian Rogers0399dde2012-06-06 17:09:28 -07002475 gSingleStepControl.line_number = dex_file.GetLineNumFromPC(m, GetDexPc());
Elliott Hughes2435a572012-02-17 16:07:41 -08002476 }
Elliott Hughes86964332012-02-15 19:37:42 -08002477 }
2478 }
Elliott Hughes530fa002012-03-12 11:44:49 -07002479 return true;
Elliott Hughes86964332012-02-15 19:37:42 -08002480 }
2481 };
Jeff Hao449db332013-04-12 18:30:52 -07002482
2483 SingleStepStackVisitor visitor(sts.GetThread());
Ian Rogers0399dde2012-06-06 17:09:28 -07002484 visitor.WalkStack();
Elliott Hughes86964332012-02-15 19:37:42 -08002485
Elliott Hughes2435a572012-02-17 16:07:41 -08002486 //
2487 // Find the dex_pc values that correspond to the current line, for line-based single-stepping.
2488 //
2489
2490 struct DebugCallbackContext {
jeffhao09bfc6a2012-12-11 18:11:43 -08002491 DebugCallbackContext() EXCLUSIVE_LOCKS_REQUIRED(Locks::breakpoint_lock_) {
Elliott Hughes2435a572012-02-17 16:07:41 -08002492 last_pc_valid = false;
2493 last_pc = 0;
Elliott Hughes2435a572012-02-17 16:07:41 -08002494 }
2495
jeffhao09bfc6a2012-12-11 18:11:43 -08002496 // TODO: Enable annotalysis. We know lock is held in constructor, but abstraction confuses
2497 // annotalysis.
2498 static bool Callback(void* raw_context, uint32_t address, uint32_t line_number) NO_THREAD_SAFETY_ANALYSIS {
2499 Locks::breakpoint_lock_->AssertHeld(Thread::Current());
Elliott Hughes2435a572012-02-17 16:07:41 -08002500 DebugCallbackContext* context = reinterpret_cast<DebugCallbackContext*>(raw_context);
2501 if (static_cast<int32_t>(line_number) == gSingleStepControl.line_number) {
2502 if (!context->last_pc_valid) {
2503 // Everything from this address until the next line change is ours.
2504 context->last_pc = address;
2505 context->last_pc_valid = true;
2506 }
2507 // Otherwise, if we're already in a valid range for this line,
2508 // just keep going (shouldn't really happen)...
2509 } else if (context->last_pc_valid) { // and the line number is new
2510 // Add everything from the last entry up until here to the set
2511 for (uint32_t dex_pc = context->last_pc; dex_pc < address; ++dex_pc) {
2512 gSingleStepControl.dex_pcs.insert(dex_pc);
2513 }
2514 context->last_pc_valid = false;
2515 }
2516 return false; // There may be multiple entries for any given line.
2517 }
2518
jeffhao09bfc6a2012-12-11 18:11:43 -08002519 // TODO: Enable annotalysis. We know lock is held in constructor, but abstraction confuses
2520 // annotalysis.
2521 ~DebugCallbackContext() NO_THREAD_SAFETY_ANALYSIS {
2522 Locks::breakpoint_lock_->AssertHeld(Thread::Current());
Elliott Hughes2435a572012-02-17 16:07:41 -08002523 // If the line number was the last in the position table...
2524 if (last_pc_valid) {
2525 size_t end = MethodHelper(gSingleStepControl.method).GetCodeItem()->insns_size_in_code_units_;
2526 for (uint32_t dex_pc = last_pc; dex_pc < end; ++dex_pc) {
2527 gSingleStepControl.dex_pcs.insert(dex_pc);
2528 }
2529 }
2530 }
2531
2532 bool last_pc_valid;
2533 uint32_t last_pc;
2534 };
Elliott Hughes3e2e1a22012-02-21 11:33:41 -08002535 gSingleStepControl.dex_pcs.clear();
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002536 const mirror::AbstractMethod* m = gSingleStepControl.method;
Elliott Hughes3e2e1a22012-02-21 11:33:41 -08002537 if (m->IsNative()) {
2538 gSingleStepControl.line_number = -1;
2539 } else {
2540 DebugCallbackContext context;
2541 MethodHelper mh(m);
2542 mh.GetDexFile().DecodeDebugInfo(mh.GetCodeItem(), m->IsStatic(), m->GetDexMethodIndex(),
2543 DebugCallbackContext::Callback, NULL, &context);
2544 }
Elliott Hughes2435a572012-02-17 16:07:41 -08002545
2546 //
2547 // Everything else...
2548 //
2549
Jeff Hao449db332013-04-12 18:30:52 -07002550 gSingleStepControl.thread = sts.GetThread();
Elliott Hughes86964332012-02-15 19:37:42 -08002551 gSingleStepControl.step_size = step_size;
2552 gSingleStepControl.step_depth = step_depth;
2553 gSingleStepControl.is_active = true;
2554
Elliott Hughes2435a572012-02-17 16:07:41 -08002555 if (VLOG_IS_ON(jdwp)) {
2556 VLOG(jdwp) << "Single-step thread: " << *gSingleStepControl.thread;
2557 VLOG(jdwp) << "Single-step step size: " << gSingleStepControl.step_size;
2558 VLOG(jdwp) << "Single-step step depth: " << gSingleStepControl.step_depth;
2559 VLOG(jdwp) << "Single-step current method: " << PrettyMethod(gSingleStepControl.method);
2560 VLOG(jdwp) << "Single-step current line: " << gSingleStepControl.line_number;
2561 VLOG(jdwp) << "Single-step current stack depth: " << gSingleStepControl.stack_depth;
2562 VLOG(jdwp) << "Single-step dex_pc values:";
2563 for (std::set<uint32_t>::iterator it = gSingleStepControl.dex_pcs.begin() ; it != gSingleStepControl.dex_pcs.end(); ++it) {
Elliott Hughes229feb72012-02-23 13:33:29 -08002564 VLOG(jdwp) << StringPrintf(" %#x", *it);
Elliott Hughes2435a572012-02-17 16:07:41 -08002565 }
2566 }
2567
2568 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002569}
2570
Elliott Hughes221229c2013-01-08 18:17:50 -08002571void Dbg::UnconfigureStep(JDWP::ObjectId /*thread_id*/) {
jeffhao09bfc6a2012-12-11 18:11:43 -08002572 MutexLock mu(Thread::Current(), *Locks::breakpoint_lock_);
Elliott Hughesf8349362012-06-18 15:00:06 -07002573
Elliott Hughes86964332012-02-15 19:37:42 -08002574 gSingleStepControl.is_active = false;
2575 gSingleStepControl.thread = NULL;
Elliott Hughes2435a572012-02-17 16:07:41 -08002576 gSingleStepControl.dex_pcs.clear();
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002577}
2578
Elliott Hughes45651fd2012-02-21 15:48:20 -08002579static char JdwpTagToShortyChar(JDWP::JdwpTag tag) {
2580 switch (tag) {
2581 default:
2582 LOG(FATAL) << "unknown JDWP tag: " << PrintableChar(tag);
2583
2584 // Primitives.
2585 case JDWP::JT_BYTE: return 'B';
2586 case JDWP::JT_CHAR: return 'C';
2587 case JDWP::JT_FLOAT: return 'F';
2588 case JDWP::JT_DOUBLE: return 'D';
2589 case JDWP::JT_INT: return 'I';
2590 case JDWP::JT_LONG: return 'J';
2591 case JDWP::JT_SHORT: return 'S';
2592 case JDWP::JT_VOID: return 'V';
2593 case JDWP::JT_BOOLEAN: return 'Z';
2594
2595 // Reference types.
2596 case JDWP::JT_ARRAY:
2597 case JDWP::JT_OBJECT:
2598 case JDWP::JT_STRING:
2599 case JDWP::JT_THREAD:
2600 case JDWP::JT_THREAD_GROUP:
2601 case JDWP::JT_CLASS_LOADER:
2602 case JDWP::JT_CLASS_OBJECT:
2603 return 'L';
2604 }
2605}
2606
Elliott Hughes88d63092013-01-09 09:55:54 -08002607JDWP::JdwpError Dbg::InvokeMethod(JDWP::ObjectId thread_id, JDWP::ObjectId object_id,
2608 JDWP::RefTypeId class_id, JDWP::MethodId method_id,
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002609 uint32_t arg_count, uint64_t* arg_values,
2610 JDWP::JdwpTag* arg_types, uint32_t options,
2611 JDWP::JdwpTag* pResultTag, uint64_t* pResultValue,
2612 JDWP::ObjectId* pExceptionId) {
Elliott Hughesd07986f2011-12-06 18:27:45 -08002613 ThreadList* thread_list = Runtime::Current()->GetThreadList();
2614
2615 Thread* targetThread = NULL;
2616 DebugInvokeReq* req = NULL;
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002617 Thread* self = Thread::Current();
Elliott Hughesd07986f2011-12-06 18:27:45 -08002618 {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002619 ScopedObjectAccessUnchecked soa(self);
Ian Rogers50b35e22012-10-04 10:09:15 -07002620 MutexLock mu(soa.Self(), *Locks::thread_list_lock_);
Elliott Hughes221229c2013-01-08 18:17:50 -08002621 JDWP::JdwpError error = DecodeThread(soa, thread_id, targetThread);
2622 if (error != JDWP::ERR_NONE) {
2623 LOG(ERROR) << "InvokeMethod request for invalid thread id " << thread_id;
2624 return error;
Elliott Hughesd07986f2011-12-06 18:27:45 -08002625 }
2626 req = targetThread->GetInvokeReq();
2627 if (!req->ready) {
2628 LOG(ERROR) << "InvokeMethod request for thread not stopped by event: " << *targetThread;
2629 return JDWP::ERR_INVALID_THREAD;
2630 }
2631
2632 /*
2633 * We currently have a bug where we don't successfully resume the
2634 * target thread if the suspend count is too deep. We're expected to
2635 * require one "resume" for each "suspend", but when asked to execute
2636 * a method we have to resume fully and then re-suspend it back to the
2637 * same level. (The easiest way to cause this is to type "suspend"
2638 * multiple times in jdb.)
2639 *
2640 * It's unclear what this means when the event specifies "resume all"
2641 * and some threads are suspended more deeply than others. This is
2642 * a rare problem, so for now we just prevent it from hanging forever
2643 * by rejecting the method invocation request. Without this, we will
2644 * be stuck waiting on a suspended thread.
2645 */
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002646 int suspend_count;
2647 {
Ian Rogers50b35e22012-10-04 10:09:15 -07002648 MutexLock mu2(soa.Self(), *Locks::thread_suspend_count_lock_);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002649 suspend_count = targetThread->GetSuspendCount();
2650 }
Elliott Hughesd07986f2011-12-06 18:27:45 -08002651 if (suspend_count > 1) {
2652 LOG(ERROR) << *targetThread << " suspend count too deep for method invocation: " << suspend_count;
2653 return JDWP::ERR_THREAD_SUSPENDED; // Probably not expected here.
2654 }
2655
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08002656 JDWP::JdwpError status;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002657 mirror::Object* receiver = gRegistry->Get<mirror::Object*>(object_id);
Elliott Hughes64f574f2013-02-20 14:57:12 -08002658 if (receiver == ObjectRegistry::kInvalidObject) {
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08002659 return JDWP::ERR_INVALID_OBJECT;
2660 }
Elliott Hughes45651fd2012-02-21 15:48:20 -08002661
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002662 mirror::Object* thread = gRegistry->Get<mirror::Object*>(thread_id);
Elliott Hughes64f574f2013-02-20 14:57:12 -08002663 if (thread == ObjectRegistry::kInvalidObject) {
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08002664 return JDWP::ERR_INVALID_OBJECT;
2665 }
Elliott Hughes45651fd2012-02-21 15:48:20 -08002666 // TODO: check that 'thread' is actually a java.lang.Thread!
2667
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002668 mirror::Class* c = DecodeClass(class_id, status);
Elliott Hughes45651fd2012-02-21 15:48:20 -08002669 if (c == NULL) {
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08002670 return status;
2671 }
Elliott Hughes45651fd2012-02-21 15:48:20 -08002672
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002673 mirror::AbstractMethod* m = FromMethodId(method_id);
Elliott Hughes45651fd2012-02-21 15:48:20 -08002674 if (m->IsStatic() != (receiver == NULL)) {
2675 return JDWP::ERR_INVALID_METHODID;
2676 }
2677 if (m->IsStatic()) {
2678 if (m->GetDeclaringClass() != c) {
2679 return JDWP::ERR_INVALID_METHODID;
2680 }
2681 } else {
2682 if (!m->GetDeclaringClass()->IsAssignableFrom(c)) {
2683 return JDWP::ERR_INVALID_METHODID;
2684 }
2685 }
2686
2687 // Check the argument list matches the method.
2688 MethodHelper mh(m);
2689 if (mh.GetShortyLength() - 1 != arg_count) {
2690 return JDWP::ERR_ILLEGAL_ARGUMENT;
2691 }
2692 const char* shorty = mh.GetShorty();
2693 for (size_t i = 0; i < arg_count; ++i) {
2694 if (shorty[i + 1] != JdwpTagToShortyChar(arg_types[i])) {
2695 return JDWP::ERR_ILLEGAL_ARGUMENT;
2696 }
2697 }
2698
2699 req->receiver_ = receiver;
2700 req->thread_ = thread;
2701 req->class_ = c;
2702 req->method_ = m;
2703 req->arg_count_ = arg_count;
2704 req->arg_values_ = arg_values;
Elliott Hughesd07986f2011-12-06 18:27:45 -08002705 req->options_ = options;
2706 req->invoke_needed_ = true;
2707 }
2708
2709 // The fact that we've released the thread list lock is a bit risky --- if the thread goes
2710 // away we're sitting high and dry -- but we must release this before the ResumeAllThreads
2711 // call, and it's unwise to hold it during WaitForSuspend.
2712
2713 {
2714 /*
2715 * We change our (JDWP thread) status, which should be THREAD_RUNNING,
Elliott Hughes81ff3182012-03-23 20:35:56 -07002716 * so we can suspend for a GC if the invoke request causes us to
Elliott Hughesd07986f2011-12-06 18:27:45 -08002717 * run out of memory. It's also a good idea to change it before locking
2718 * the invokeReq mutex, although that should never be held for long.
2719 */
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002720 self->TransitionFromRunnableToSuspended(kWaitingForDebuggerSend);
Elliott Hughesd07986f2011-12-06 18:27:45 -08002721
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08002722 VLOG(jdwp) << " Transferring control to event thread";
Elliott Hughesd07986f2011-12-06 18:27:45 -08002723 {
Ian Rogers50b35e22012-10-04 10:09:15 -07002724 MutexLock mu(self, req->lock_);
Elliott Hughesd07986f2011-12-06 18:27:45 -08002725
2726 if ((options & JDWP::INVOKE_SINGLE_THREADED) == 0) {
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08002727 VLOG(jdwp) << " Resuming all threads";
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002728 thread_list->UndoDebuggerSuspensions();
Elliott Hughesd07986f2011-12-06 18:27:45 -08002729 } else {
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08002730 VLOG(jdwp) << " Resuming event thread only";
Elliott Hughesd07986f2011-12-06 18:27:45 -08002731 thread_list->Resume(targetThread, true);
2732 }
2733
2734 // Wait for the request to finish executing.
2735 while (req->invoke_needed_) {
Ian Rogersc604d732012-10-14 16:09:54 -07002736 req->cond_.Wait(self);
Elliott Hughesd07986f2011-12-06 18:27:45 -08002737 }
2738 }
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08002739 VLOG(jdwp) << " Control has returned from event thread";
Elliott Hughesd07986f2011-12-06 18:27:45 -08002740
2741 /* wait for thread to re-suspend itself */
Elliott Hughes221229c2013-01-08 18:17:50 -08002742 SuspendThread(thread_id, false /* request_suspension */ );
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002743 self->TransitionFromSuspendedToRunnable();
Elliott Hughesd07986f2011-12-06 18:27:45 -08002744 }
2745
2746 /*
2747 * Suspend the threads. We waited for the target thread to suspend
2748 * itself, so all we need to do is suspend the others.
2749 *
2750 * The suspendAllThreads() call will double-suspend the event thread,
2751 * so we want to resume the target thread once to keep the books straight.
2752 */
2753 if ((options & JDWP::INVOKE_SINGLE_THREADED) == 0) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002754 self->TransitionFromRunnableToSuspended(kWaitingForDebuggerSuspension);
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08002755 VLOG(jdwp) << " Suspending all threads";
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002756 thread_list->SuspendAllForDebugger();
2757 self->TransitionFromSuspendedToRunnable();
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08002758 VLOG(jdwp) << " Resuming event thread to balance the count";
Elliott Hughesd07986f2011-12-06 18:27:45 -08002759 thread_list->Resume(targetThread, true);
2760 }
2761
2762 // Copy the result.
2763 *pResultTag = req->result_tag;
2764 if (IsPrimitiveTag(req->result_tag)) {
Elliott Hughesf24d3ce2012-04-11 17:43:37 -07002765 *pResultValue = req->result_value.GetJ();
Elliott Hughesd07986f2011-12-06 18:27:45 -08002766 } else {
Elliott Hughesf24d3ce2012-04-11 17:43:37 -07002767 *pResultValue = gRegistry->Add(req->result_value.GetL());
Elliott Hughesd07986f2011-12-06 18:27:45 -08002768 }
2769 *pExceptionId = req->exception;
2770 return req->error;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002771}
2772
2773void Dbg::ExecuteMethod(DebugInvokeReq* pReq) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002774 ScopedObjectAccess soa(Thread::Current());
Elliott Hughesd07986f2011-12-06 18:27:45 -08002775
Elliott Hughes81ff3182012-03-23 20:35:56 -07002776 // We can be called while an exception is pending. We need
Elliott Hughesd07986f2011-12-06 18:27:45 -08002777 // to preserve that across the method invocation.
Ian Rogers62d6c772013-02-27 08:32:07 -08002778 SirtRef<mirror::Object> old_throw_this_object(soa.Self(), NULL);
2779 SirtRef<mirror::AbstractMethod> old_throw_method(soa.Self(), NULL);
2780 SirtRef<mirror::Throwable> old_exception(soa.Self(), NULL);
2781 uint32_t old_throw_dex_pc;
2782 {
2783 ThrowLocation old_throw_location;
2784 mirror::Throwable* old_exception_obj = soa.Self()->GetException(&old_throw_location);
2785 old_throw_this_object.reset(old_throw_location.GetThis());
2786 old_throw_method.reset(old_throw_location.GetMethod());
2787 old_exception.reset(old_exception_obj);
2788 old_throw_dex_pc = old_throw_location.GetDexPc();
2789 soa.Self()->ClearException();
2790 }
Elliott Hughesd07986f2011-12-06 18:27:45 -08002791
2792 // Translate the method through the vtable, unless the debugger wants to suppress it.
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002793 mirror::AbstractMethod* m = pReq->method_;
Elliott Hughesd07986f2011-12-06 18:27:45 -08002794 if ((pReq->options_ & JDWP::INVOKE_NONVIRTUAL) == 0 && pReq->receiver_ != NULL) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002795 mirror::AbstractMethod* actual_method = pReq->class_->FindVirtualMethodForVirtualOrInterface(pReq->method_);
Elliott Hughes45651fd2012-02-21 15:48:20 -08002796 if (actual_method != m) {
2797 VLOG(jdwp) << "ExecuteMethod translated " << PrettyMethod(m) << " to " << PrettyMethod(actual_method);
2798 m = actual_method;
2799 }
Elliott Hughesd07986f2011-12-06 18:27:45 -08002800 }
Elliott Hughes45651fd2012-02-21 15:48:20 -08002801 VLOG(jdwp) << "ExecuteMethod " << PrettyMethod(m);
Elliott Hughesd07986f2011-12-06 18:27:45 -08002802 CHECK(m != NULL);
2803
2804 CHECK_EQ(sizeof(jvalue), sizeof(uint64_t));
2805
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002806 LOG(INFO) << "self=" << soa.Self() << " pReq->receiver_=" << pReq->receiver_ << " m=" << m
2807 << " #" << pReq->arg_count_ << " " << pReq->arg_values_;
Jeff Hao5d917302013-02-27 17:57:33 -08002808
2809 MethodHelper mh(m);
2810 ArgArray arg_array(mh.GetShorty(), mh.GetShortyLength());
2811 arg_array.BuildArgArray(soa, pReq->receiver_, reinterpret_cast<jvalue*>(pReq->arg_values_));
Jeff Hao6474d192013-03-26 14:08:09 -07002812 InvokeWithArgArray(soa, m, &arg_array, &pReq->result_value, mh.GetShorty()[0]);
Elliott Hughesd07986f2011-12-06 18:27:45 -08002813
Ian Rogers62d6c772013-02-27 08:32:07 -08002814 mirror::Throwable* exception = soa.Self()->GetException(NULL);
2815 soa.Self()->ClearException();
2816 pReq->exception = gRegistry->Add(exception);
Elliott Hughesd07986f2011-12-06 18:27:45 -08002817 pReq->result_tag = BasicTagFromDescriptor(MethodHelper(m).GetShorty());
2818 if (pReq->exception != 0) {
Ian Rogers62d6c772013-02-27 08:32:07 -08002819 VLOG(jdwp) << " JDWP invocation returning with exception=" << exception
2820 << " " << exception->Dump();
Elliott Hughesf24d3ce2012-04-11 17:43:37 -07002821 pReq->result_value.SetJ(0);
Elliott Hughesd07986f2011-12-06 18:27:45 -08002822 } else if (pReq->result_tag == JDWP::JT_OBJECT) {
2823 /* if no exception thrown, examine object result more closely */
Elliott Hughesf24d3ce2012-04-11 17:43:37 -07002824 JDWP::JdwpTag new_tag = TagFromObject(pReq->result_value.GetL());
Elliott Hughesd07986f2011-12-06 18:27:45 -08002825 if (new_tag != pReq->result_tag) {
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08002826 VLOG(jdwp) << " JDWP promoted result from " << pReq->result_tag << " to " << new_tag;
Elliott Hughesd07986f2011-12-06 18:27:45 -08002827 pReq->result_tag = new_tag;
2828 }
2829
2830 /*
2831 * Register the object. We don't actually need an ObjectId yet,
2832 * but we do need to be sure that the GC won't move or discard the
2833 * object when we switch out of RUNNING. The ObjectId conversion
2834 * will add the object to the "do not touch" list.
2835 *
2836 * We can't use the "tracked allocation" mechanism here because
2837 * the object is going to be handed off to a different thread.
2838 */
Elliott Hughesf24d3ce2012-04-11 17:43:37 -07002839 gRegistry->Add(pReq->result_value.GetL());
Elliott Hughesd07986f2011-12-06 18:27:45 -08002840 }
2841
2842 if (old_exception.get() != NULL) {
Ian Rogers62d6c772013-02-27 08:32:07 -08002843 ThrowLocation gc_safe_throw_location(old_throw_this_object.get(), old_throw_method.get(),
2844 old_throw_dex_pc);
2845 soa.Self()->SetException(gc_safe_throw_location, old_exception.get());
Elliott Hughesd07986f2011-12-06 18:27:45 -08002846 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002847}
2848
Elliott Hughesd07986f2011-12-06 18:27:45 -08002849/*
Elliott Hughes4b9702c2013-02-20 18:13:24 -08002850 * "request" contains a full JDWP packet, possibly with multiple chunks. We
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07002851 * need to process each, accumulate the replies, and ship the whole thing
2852 * back.
2853 *
2854 * Returns "true" if we have a reply. The reply buffer is newly allocated,
2855 * and includes the chunk type/length, followed by the data.
2856 *
Elliott Hughes3d30d9b2011-12-07 17:35:48 -08002857 * OLD-TODO: we currently assume that the request and reply include a single
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07002858 * chunk. If this becomes inconvenient we will need to adapt.
2859 */
Elliott Hughes4b9702c2013-02-20 18:13:24 -08002860bool Dbg::DdmHandlePacket(JDWP::Request& request, uint8_t** pReplyBuf, int* pReplyLen) {
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07002861 Thread* self = Thread::Current();
2862 JNIEnv* env = self->GetJniEnv();
2863
Elliott Hughes4b9702c2013-02-20 18:13:24 -08002864 uint32_t type = request.ReadUnsigned32("type");
2865 uint32_t length = request.ReadUnsigned32("length");
2866
2867 // Create a byte[] corresponding to 'request'.
2868 size_t request_length = request.size();
2869 ScopedLocalRef<jbyteArray> dataArray(env, env->NewByteArray(request_length));
Elliott Hughes6a5bd492011-10-28 14:33:57 -07002870 if (dataArray.get() == NULL) {
Elliott Hughes4b9702c2013-02-20 18:13:24 -08002871 LOG(WARNING) << "byte[] allocation failed: " << request_length;
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07002872 env->ExceptionClear();
2873 return false;
2874 }
Elliott Hughes4b9702c2013-02-20 18:13:24 -08002875 env->SetByteArrayRegion(dataArray.get(), 0, request_length, reinterpret_cast<const jbyte*>(request.data()));
2876 request.Skip(request_length);
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07002877
2878 // Run through and find all chunks. [Currently just find the first.]
Elliott Hughes6a5bd492011-10-28 14:33:57 -07002879 ScopedByteArrayRO contents(env, dataArray.get());
Elliott Hughes4b9702c2013-02-20 18:13:24 -08002880 if (length != request_length) {
2881 LOG(WARNING) << StringPrintf("bad chunk found (len=%u pktLen=%d)", length, request_length);
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07002882 return false;
2883 }
2884
2885 // Call "private static Chunk dispatch(int type, byte[] data, int offset, int length)".
Elliott Hugheseac76672012-05-24 21:56:51 -07002886 ScopedLocalRef<jobject> chunk(env, env->CallStaticObjectMethod(WellKnownClasses::org_apache_harmony_dalvik_ddmc_DdmServer,
2887 WellKnownClasses::org_apache_harmony_dalvik_ddmc_DdmServer_dispatch,
Elliott Hughes4b9702c2013-02-20 18:13:24 -08002888 type, dataArray.get(), 0, length));
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07002889 if (env->ExceptionCheck()) {
2890 LOG(INFO) << StringPrintf("Exception thrown by dispatcher for 0x%08x", type);
2891 env->ExceptionDescribe();
2892 env->ExceptionClear();
2893 return false;
2894 }
2895
Elliott Hughes6a5bd492011-10-28 14:33:57 -07002896 if (chunk.get() == NULL) {
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07002897 return false;
2898 }
2899
2900 /*
2901 * Pull the pieces out of the chunk. We copy the results into a
2902 * newly-allocated buffer that the caller can free. We don't want to
2903 * continue using the Chunk object because nothing has a reference to it.
2904 *
2905 * We could avoid this by returning type/data/offset/length and having
2906 * the caller be aware of the object lifetime issues, but that
Elliott Hughes81ff3182012-03-23 20:35:56 -07002907 * integrates the JDWP code more tightly into the rest of the runtime, and doesn't work
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07002908 * if we have responses for multiple chunks.
2909 *
2910 * So we're pretty much stuck with copying data around multiple times.
2911 */
Elliott Hugheseac76672012-05-24 21:56:51 -07002912 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 -08002913 jint offset = env->GetIntField(chunk.get(), WellKnownClasses::org_apache_harmony_dalvik_ddmc_Chunk_offset);
Elliott Hugheseac76672012-05-24 21:56:51 -07002914 length = env->GetIntField(chunk.get(), WellKnownClasses::org_apache_harmony_dalvik_ddmc_Chunk_length);
Elliott Hugheseac76672012-05-24 21:56:51 -07002915 type = env->GetIntField(chunk.get(), WellKnownClasses::org_apache_harmony_dalvik_ddmc_Chunk_type);
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07002916
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08002917 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 -07002918 if (length == 0 || replyData.get() == NULL) {
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07002919 return false;
2920 }
2921
Elliott Hughes4b9702c2013-02-20 18:13:24 -08002922 const int kChunkHdrLen = 8;
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07002923 uint8_t* reply = new uint8_t[length + kChunkHdrLen];
2924 if (reply == NULL) {
2925 LOG(WARNING) << "malloc failed: " << (length + kChunkHdrLen);
2926 return false;
2927 }
Elliott Hughesf7c3b662011-10-27 12:04:56 -07002928 JDWP::Set4BE(reply + 0, type);
2929 JDWP::Set4BE(reply + 4, length);
Elliott Hughes6a5bd492011-10-28 14:33:57 -07002930 env->GetByteArrayRegion(replyData.get(), offset, length, reinterpret_cast<jbyte*>(reply + kChunkHdrLen));
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07002931
2932 *pReplyBuf = reply;
2933 *pReplyLen = length + kChunkHdrLen;
2934
Elliott Hughes4b9702c2013-02-20 18:13:24 -08002935 VLOG(jdwp) << StringPrintf("dvmHandleDdm returning type=%.4s %p len=%d", reinterpret_cast<char*>(reply), reply, length);
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07002936 return true;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002937}
2938
Elliott Hughesa2155262011-11-16 16:26:58 -08002939void Dbg::DdmBroadcast(bool connect) {
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08002940 VLOG(jdwp) << "Broadcasting DDM " << (connect ? "connect" : "disconnect") << "...";
Elliott Hughes47fce012011-10-25 18:37:19 -07002941
2942 Thread* self = Thread::Current();
Ian Rogers50b35e22012-10-04 10:09:15 -07002943 if (self->GetState() != kRunnable) {
2944 LOG(ERROR) << "DDM broadcast in thread state " << self->GetState();
2945 /* try anyway? */
Elliott Hughes47fce012011-10-25 18:37:19 -07002946 }
2947
2948 JNIEnv* env = self->GetJniEnv();
Elliott Hughes47fce012011-10-25 18:37:19 -07002949 jint event = connect ? 1 /*DdmServer.CONNECTED*/ : 2 /*DdmServer.DISCONNECTED*/;
Elliott Hugheseac76672012-05-24 21:56:51 -07002950 env->CallStaticVoidMethod(WellKnownClasses::org_apache_harmony_dalvik_ddmc_DdmServer,
2951 WellKnownClasses::org_apache_harmony_dalvik_ddmc_DdmServer_broadcast,
2952 event);
Elliott Hughes47fce012011-10-25 18:37:19 -07002953 if (env->ExceptionCheck()) {
2954 LOG(ERROR) << "DdmServer.broadcast " << event << " failed";
2955 env->ExceptionDescribe();
2956 env->ExceptionClear();
2957 }
2958}
2959
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002960void Dbg::DdmConnected() {
Elliott Hughesa2155262011-11-16 16:26:58 -08002961 Dbg::DdmBroadcast(true);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002962}
2963
2964void Dbg::DdmDisconnected() {
Elliott Hughesa2155262011-11-16 16:26:58 -08002965 Dbg::DdmBroadcast(false);
Elliott Hughes47fce012011-10-25 18:37:19 -07002966 gDdmThreadNotification = false;
2967}
2968
2969/*
Elliott Hughes82188472011-11-07 18:11:48 -08002970 * Send a notification when a thread starts, stops, or changes its name.
Elliott Hughes47fce012011-10-25 18:37:19 -07002971 *
2972 * Because we broadcast the full set of threads when the notifications are
2973 * first enabled, it's possible for "thread" to be actively executing.
2974 */
Elliott Hughes82188472011-11-07 18:11:48 -08002975void Dbg::DdmSendThreadNotification(Thread* t, uint32_t type) {
Elliott Hughes47fce012011-10-25 18:37:19 -07002976 if (!gDdmThreadNotification) {
2977 return;
2978 }
2979
Elliott Hughes82188472011-11-07 18:11:48 -08002980 if (type == CHUNK_TYPE("THDE")) {
Elliott Hughes47fce012011-10-25 18:37:19 -07002981 uint8_t buf[4];
Elliott Hughesf7c3b662011-10-27 12:04:56 -07002982 JDWP::Set4BE(&buf[0], t->GetThinLockId());
Elliott Hughes47fce012011-10-25 18:37:19 -07002983 Dbg::DdmSendChunk(CHUNK_TYPE("THDE"), 4, buf);
Elliott Hughes82188472011-11-07 18:11:48 -08002984 } else {
2985 CHECK(type == CHUNK_TYPE("THCR") || type == CHUNK_TYPE("THNM")) << type;
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002986 ScopedObjectAccessUnchecked soa(Thread::Current());
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002987 SirtRef<mirror::String> name(soa.Self(), t->GetThreadName(soa));
Elliott Hughes82188472011-11-07 18:11:48 -08002988 size_t char_count = (name.get() != NULL) ? name->GetLength() : 0;
jeffhao725a9572012-11-13 18:20:12 -08002989 const jchar* chars = (name.get() != NULL) ? name->GetCharArray()->GetData() : NULL;
Elliott Hughes82188472011-11-07 18:11:48 -08002990
Elliott Hughes21f32d72011-11-09 17:44:13 -08002991 std::vector<uint8_t> bytes;
Elliott Hughes545a0642011-11-08 19:10:03 -08002992 JDWP::Append4BE(bytes, t->GetThinLockId());
2993 JDWP::AppendUtf16BE(bytes, chars, char_count);
Elliott Hughes21f32d72011-11-09 17:44:13 -08002994 CHECK_EQ(bytes.size(), char_count*2 + sizeof(uint32_t)*2);
2995 Dbg::DdmSendChunk(type, bytes);
Elliott Hughes47fce012011-10-25 18:37:19 -07002996 }
2997}
2998
Elliott Hughes47fce012011-10-25 18:37:19 -07002999void Dbg::DdmSetThreadNotification(bool enable) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07003000 // Enable/disable thread notifications.
Elliott Hughes47fce012011-10-25 18:37:19 -07003001 gDdmThreadNotification = enable;
3002 if (enable) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07003003 // Suspend the VM then post thread start notifications for all threads. Threads attaching will
3004 // see a suspension in progress and block until that ends. They then post their own start
3005 // notification.
3006 SuspendVM();
3007 std::list<Thread*> threads;
Ian Rogers50b35e22012-10-04 10:09:15 -07003008 Thread* self = Thread::Current();
Ian Rogers00f7d0e2012-07-19 15:28:27 -07003009 {
Ian Rogers50b35e22012-10-04 10:09:15 -07003010 MutexLock mu(self, *Locks::thread_list_lock_);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07003011 threads = Runtime::Current()->GetThreadList()->GetList();
3012 }
3013 {
Ian Rogers50b35e22012-10-04 10:09:15 -07003014 ScopedObjectAccess soa(self);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07003015 typedef std::list<Thread*>::const_iterator It; // TODO: C++0x auto
3016 for (It it = threads.begin(), end = threads.end(); it != end; ++it) {
3017 Dbg::DdmSendThreadNotification(*it, CHUNK_TYPE("THCR"));
3018 }
3019 }
3020 ResumeVM();
Elliott Hughes47fce012011-10-25 18:37:19 -07003021 }
3022}
3023
Elliott Hughesa2155262011-11-16 16:26:58 -08003024void Dbg::PostThreadStartOrStop(Thread* t, uint32_t type) {
Elliott Hughesc0f09332012-03-26 13:27:06 -07003025 if (IsDebuggerActive()) {
Mathieu Chartierdbe6f462012-09-25 16:54:50 -07003026 ScopedObjectAccessUnchecked soa(Thread::Current());
Ian Rogerscfaa4552012-11-26 21:00:08 -08003027 JDWP::ObjectId id = gRegistry->Add(t->GetPeer());
Elliott Hughes82188472011-11-07 18:11:48 -08003028 gJdwpState->PostThreadChange(id, type == CHUNK_TYPE("THCR"));
Elliott Hughes47fce012011-10-25 18:37:19 -07003029 }
Elliott Hughes82188472011-11-07 18:11:48 -08003030 Dbg::DdmSendThreadNotification(t, type);
Elliott Hughes47fce012011-10-25 18:37:19 -07003031}
3032
3033void Dbg::PostThreadStart(Thread* t) {
Elliott Hughesa2155262011-11-16 16:26:58 -08003034 Dbg::PostThreadStartOrStop(t, CHUNK_TYPE("THCR"));
Elliott Hughes47fce012011-10-25 18:37:19 -07003035}
3036
3037void Dbg::PostThreadDeath(Thread* t) {
Elliott Hughesa2155262011-11-16 16:26:58 -08003038 Dbg::PostThreadStartOrStop(t, CHUNK_TYPE("THDE"));
Elliott Hughes872d4ec2011-10-21 17:07:15 -07003039}
3040
Elliott Hughes82188472011-11-07 18:11:48 -08003041void Dbg::DdmSendChunk(uint32_t type, size_t byte_count, const uint8_t* buf) {
Elliott Hughes3bb81562011-10-21 18:52:59 -07003042 CHECK(buf != NULL);
3043 iovec vec[1];
3044 vec[0].iov_base = reinterpret_cast<void*>(const_cast<uint8_t*>(buf));
3045 vec[0].iov_len = byte_count;
3046 Dbg::DdmSendChunkV(type, vec, 1);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07003047}
3048
Elliott Hughes21f32d72011-11-09 17:44:13 -08003049void Dbg::DdmSendChunk(uint32_t type, const std::vector<uint8_t>& bytes) {
3050 DdmSendChunk(type, bytes.size(), &bytes[0]);
3051}
3052
Elliott Hughescccd84f2011-12-05 16:51:54 -08003053void Dbg::DdmSendChunkV(uint32_t type, const struct iovec* iov, int iov_count) {
Elliott Hughes3bb81562011-10-21 18:52:59 -07003054 if (gJdwpState == NULL) {
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08003055 VLOG(jdwp) << "Debugger thread not active, ignoring DDM send: " << type;
Elliott Hughes3bb81562011-10-21 18:52:59 -07003056 } else {
Elliott Hughescccd84f2011-12-05 16:51:54 -08003057 gJdwpState->DdmSendChunkV(type, iov, iov_count);
Elliott Hughes3bb81562011-10-21 18:52:59 -07003058 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -07003059}
3060
Elliott Hughes767a1472011-10-26 18:49:02 -07003061int Dbg::DdmHandleHpifChunk(HpifWhen when) {
3062 if (when == HPIF_WHEN_NOW) {
Elliott Hughes7162ad92011-10-27 14:08:42 -07003063 DdmSendHeapInfo(when);
Elliott Hughes767a1472011-10-26 18:49:02 -07003064 return true;
3065 }
3066
3067 if (when != HPIF_WHEN_NEVER && when != HPIF_WHEN_NEXT_GC && when != HPIF_WHEN_EVERY_GC) {
3068 LOG(ERROR) << "invalid HpifWhen value: " << static_cast<int>(when);
3069 return false;
3070 }
3071
3072 gDdmHpifWhen = when;
3073 return true;
3074}
3075
3076bool Dbg::DdmHandleHpsgNhsgChunk(Dbg::HpsgWhen when, Dbg::HpsgWhat what, bool native) {
3077 if (when != HPSG_WHEN_NEVER && when != HPSG_WHEN_EVERY_GC) {
3078 LOG(ERROR) << "invalid HpsgWhen value: " << static_cast<int>(when);
3079 return false;
3080 }
3081
3082 if (what != HPSG_WHAT_MERGED_OBJECTS && what != HPSG_WHAT_DISTINCT_OBJECTS) {
3083 LOG(ERROR) << "invalid HpsgWhat value: " << static_cast<int>(what);
3084 return false;
3085 }
3086
3087 if (native) {
3088 gDdmNhsgWhen = when;
3089 gDdmNhsgWhat = what;
3090 } else {
3091 gDdmHpsgWhen = when;
3092 gDdmHpsgWhat = what;
3093 }
3094 return true;
3095}
3096
Elliott Hughes7162ad92011-10-27 14:08:42 -07003097void Dbg::DdmSendHeapInfo(HpifWhen reason) {
3098 // If there's a one-shot 'when', reset it.
3099 if (reason == gDdmHpifWhen) {
3100 if (gDdmHpifWhen == HPIF_WHEN_NEXT_GC) {
3101 gDdmHpifWhen = HPIF_WHEN_NEVER;
3102 }
3103 }
3104
3105 /*
3106 * Chunk HPIF (client --> server)
3107 *
3108 * Heap Info. General information about the heap,
3109 * suitable for a summary display.
3110 *
3111 * [u4]: number of heaps
3112 *
3113 * For each heap:
3114 * [u4]: heap ID
3115 * [u8]: timestamp in ms since Unix epoch
3116 * [u1]: capture reason (same as 'when' value from server)
3117 * [u4]: max heap size in bytes (-Xmx)
3118 * [u4]: current heap size in bytes
3119 * [u4]: current number of bytes allocated
3120 * [u4]: current number of objects allocated
3121 */
3122 uint8_t heap_count = 1;
Elliott Hughesb3bd5f02012-03-08 21:05:27 -08003123 Heap* heap = Runtime::Current()->GetHeap();
Elliott Hughes21f32d72011-11-09 17:44:13 -08003124 std::vector<uint8_t> bytes;
Elliott Hughes545a0642011-11-08 19:10:03 -08003125 JDWP::Append4BE(bytes, heap_count);
3126 JDWP::Append4BE(bytes, 1); // Heap id (bogus; we only have one heap).
3127 JDWP::Append8BE(bytes, MilliTime());
3128 JDWP::Append1BE(bytes, reason);
Elliott Hughesb3bd5f02012-03-08 21:05:27 -08003129 JDWP::Append4BE(bytes, heap->GetMaxMemory()); // Max allowed heap size in bytes.
3130 JDWP::Append4BE(bytes, heap->GetTotalMemory()); // Current heap size in bytes.
3131 JDWP::Append4BE(bytes, heap->GetBytesAllocated());
3132 JDWP::Append4BE(bytes, heap->GetObjectsAllocated());
Elliott Hughes21f32d72011-11-09 17:44:13 -08003133 CHECK_EQ(bytes.size(), 4U + (heap_count * (4 + 8 + 1 + 4 + 4 + 4 + 4)));
3134 Dbg::DdmSendChunk(CHUNK_TYPE("HPIF"), bytes);
Elliott Hughes767a1472011-10-26 18:49:02 -07003135}
3136
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003137enum HpsgSolidity {
3138 SOLIDITY_FREE = 0,
3139 SOLIDITY_HARD = 1,
3140 SOLIDITY_SOFT = 2,
3141 SOLIDITY_WEAK = 3,
3142 SOLIDITY_PHANTOM = 4,
3143 SOLIDITY_FINALIZABLE = 5,
3144 SOLIDITY_SWEEP = 6,
3145};
3146
3147enum HpsgKind {
3148 KIND_OBJECT = 0,
3149 KIND_CLASS_OBJECT = 1,
3150 KIND_ARRAY_1 = 2,
3151 KIND_ARRAY_2 = 3,
3152 KIND_ARRAY_4 = 4,
3153 KIND_ARRAY_8 = 5,
3154 KIND_UNKNOWN = 6,
3155 KIND_NATIVE = 7,
3156};
3157
3158#define HPSG_PARTIAL (1<<7)
3159#define HPSG_STATE(solidity, kind) ((uint8_t)((((kind) & 0x7) << 3) | ((solidity) & 0x7)))
3160
Ian Rogers30fab402012-01-23 15:43:46 -08003161class HeapChunkContext {
3162 public:
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003163 // Maximum chunk size. Obtain this from the formula:
3164 // (((maximum_heap_size / ALLOCATION_UNIT_SIZE) + 255) / 256) * 2
3165 HeapChunkContext(bool merge, bool native)
Ian Rogers30fab402012-01-23 15:43:46 -08003166 : buf_(16384 - 16),
3167 type_(0),
3168 merge_(merge) {
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003169 Reset();
3170 if (native) {
Ian Rogers30fab402012-01-23 15:43:46 -08003171 type_ = CHUNK_TYPE("NHSG");
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003172 } else {
Ian Rogers30fab402012-01-23 15:43:46 -08003173 type_ = merge ? CHUNK_TYPE("HPSG") : CHUNK_TYPE("HPSO");
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003174 }
3175 }
3176
3177 ~HeapChunkContext() {
Ian Rogers30fab402012-01-23 15:43:46 -08003178 if (p_ > &buf_[0]) {
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003179 Flush();
3180 }
3181 }
3182
3183 void EnsureHeader(const void* chunk_ptr) {
Ian Rogers30fab402012-01-23 15:43:46 -08003184 if (!needHeader_) {
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003185 return;
3186 }
3187
3188 // Start a new HPSx chunk.
Ian Rogers30fab402012-01-23 15:43:46 -08003189 JDWP::Write4BE(&p_, 1); // Heap id (bogus; we only have one heap).
3190 JDWP::Write1BE(&p_, 8); // Size of allocation unit, in bytes.
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003191
Ian Rogers30fab402012-01-23 15:43:46 -08003192 JDWP::Write4BE(&p_, reinterpret_cast<uintptr_t>(chunk_ptr)); // virtual address of segment start.
3193 JDWP::Write4BE(&p_, 0); // offset of this piece (relative to the virtual address).
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003194 // [u4]: length of piece, in allocation units
3195 // 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 -08003196 pieceLenField_ = p_;
3197 JDWP::Write4BE(&p_, 0x55555555);
3198 needHeader_ = false;
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003199 }
3200
Ian Rogersb726dcb2012-09-05 08:57:23 -07003201 void Flush() SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Ian Rogersd636b062013-01-18 17:51:18 -08003202 if (pieceLenField_ == NULL) {
3203 // Flush immediately post Reset (maybe back-to-back Flush). Ignore.
3204 CHECK(needHeader_);
3205 return;
3206 }
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003207 // Patch the "length of piece" field.
Ian Rogers30fab402012-01-23 15:43:46 -08003208 CHECK_LE(&buf_[0], pieceLenField_);
3209 CHECK_LE(pieceLenField_, p_);
3210 JDWP::Set4BE(pieceLenField_, totalAllocationUnits_);
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003211
Ian Rogers30fab402012-01-23 15:43:46 -08003212 Dbg::DdmSendChunk(type_, p_ - &buf_[0], &buf_[0]);
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003213 Reset();
3214 }
3215
Ian Rogers00f7d0e2012-07-19 15:28:27 -07003216 static void HeapChunkCallback(void* start, void* end, size_t used_bytes, void* arg)
Ian Rogersb726dcb2012-09-05 08:57:23 -07003217 SHARED_LOCKS_REQUIRED(Locks::heap_bitmap_lock_,
3218 Locks::mutator_lock_) {
Ian Rogers30fab402012-01-23 15:43:46 -08003219 reinterpret_cast<HeapChunkContext*>(arg)->HeapChunkCallback(start, end, used_bytes);
Elliott Hughesa2155262011-11-16 16:26:58 -08003220 }
3221
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003222 private:
Elliott Hughesa2155262011-11-16 16:26:58 -08003223 enum { ALLOCATION_UNIT_SIZE = 8 };
3224
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003225 void Reset() {
Ian Rogers30fab402012-01-23 15:43:46 -08003226 p_ = &buf_[0];
Ian Rogers15bf2d32012-08-28 17:33:04 -07003227 startOfNextMemoryChunk_ = NULL;
Ian Rogers30fab402012-01-23 15:43:46 -08003228 totalAllocationUnits_ = 0;
3229 needHeader_ = true;
3230 pieceLenField_ = NULL;
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003231 }
3232
Ian Rogers00f7d0e2012-07-19 15:28:27 -07003233 void HeapChunkCallback(void* start, void* /*end*/, size_t used_bytes)
Ian Rogersb726dcb2012-09-05 08:57:23 -07003234 SHARED_LOCKS_REQUIRED(Locks::heap_bitmap_lock_,
3235 Locks::mutator_lock_) {
Ian Rogers30fab402012-01-23 15:43:46 -08003236 // Note: heap call backs cannot manipulate the heap upon which they are crawling, care is taken
3237 // in the following code not to allocate memory, by ensuring buf_ is of the correct size
Ian Rogers15bf2d32012-08-28 17:33:04 -07003238 if (used_bytes == 0) {
3239 if (start == NULL) {
3240 // Reset for start of new heap.
3241 startOfNextMemoryChunk_ = NULL;
3242 Flush();
3243 }
3244 // Only process in use memory so that free region information
3245 // also includes dlmalloc book keeping.
Elliott Hughesa2155262011-11-16 16:26:58 -08003246 return;
Elliott Hughesa2155262011-11-16 16:26:58 -08003247 }
3248
Ian Rogers15bf2d32012-08-28 17:33:04 -07003249 /* If we're looking at the native heap, we'll just return
3250 * (SOLIDITY_HARD, KIND_NATIVE) for all allocated chunks
3251 */
3252 bool native = type_ == CHUNK_TYPE("NHSG");
3253
3254 if (startOfNextMemoryChunk_ != NULL) {
3255 // Transmit any pending free memory. Native free memory of
3256 // over kMaxFreeLen could be because of the use of mmaps, so
3257 // don't report. If not free memory then start a new segment.
3258 bool flush = true;
3259 if (start > startOfNextMemoryChunk_) {
3260 const size_t kMaxFreeLen = 2 * kPageSize;
3261 void* freeStart = startOfNextMemoryChunk_;
3262 void* freeEnd = start;
3263 size_t freeLen = (char*)freeEnd - (char*)freeStart;
3264 if (!native || freeLen < kMaxFreeLen) {
3265 AppendChunk(HPSG_STATE(SOLIDITY_FREE, 0), freeStart, freeLen);
3266 flush = false;
3267 }
3268 }
3269 if (flush) {
3270 startOfNextMemoryChunk_ = NULL;
3271 Flush();
3272 }
3273 }
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003274 const mirror::Object* obj = reinterpret_cast<const mirror::Object*>(start);
Elliott Hughesa2155262011-11-16 16:26:58 -08003275
3276 // Determine the type of this chunk.
3277 // OLD-TODO: if context.merge, see if this chunk is different from the last chunk.
3278 // If it's the same, we should combine them.
Ian Rogers15bf2d32012-08-28 17:33:04 -07003279 uint8_t state = ExamineObject(obj, native);
3280 // dlmalloc's chunk header is 2 * sizeof(size_t), but if the previous chunk is in use for an
3281 // allocation then the first sizeof(size_t) may belong to it.
3282 const size_t dlMallocOverhead = sizeof(size_t);
3283 AppendChunk(state, start, used_bytes + dlMallocOverhead);
3284 startOfNextMemoryChunk_ = (char*)start + used_bytes + dlMallocOverhead;
3285 }
Elliott Hughesa2155262011-11-16 16:26:58 -08003286
Ian Rogers15bf2d32012-08-28 17:33:04 -07003287 void AppendChunk(uint8_t state, void* ptr, size_t length)
Ian Rogersb726dcb2012-09-05 08:57:23 -07003288 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Ian Rogers15bf2d32012-08-28 17:33:04 -07003289 // Make sure there's enough room left in the buffer.
3290 // We need to use two bytes for every fractional 256 allocation units used by the chunk plus
3291 // 17 bytes for any header.
3292 size_t needed = (((length/ALLOCATION_UNIT_SIZE + 255) / 256) * 2) + 17;
3293 size_t bytesLeft = buf_.size() - (size_t)(p_ - &buf_[0]);
3294 if (bytesLeft < needed) {
3295 Flush();
3296 }
3297
3298 bytesLeft = buf_.size() - (size_t)(p_ - &buf_[0]);
3299 if (bytesLeft < needed) {
3300 LOG(WARNING) << "Chunk is too big to transmit (chunk_len=" << length << ", "
3301 << needed << " bytes)";
3302 return;
3303 }
3304 EnsureHeader(ptr);
Elliott Hughesa2155262011-11-16 16:26:58 -08003305 // Write out the chunk description.
Ian Rogers15bf2d32012-08-28 17:33:04 -07003306 length /= ALLOCATION_UNIT_SIZE; // Convert to allocation units.
3307 totalAllocationUnits_ += length;
3308 while (length > 256) {
Ian Rogers30fab402012-01-23 15:43:46 -08003309 *p_++ = state | HPSG_PARTIAL;
3310 *p_++ = 255; // length - 1
Ian Rogers15bf2d32012-08-28 17:33:04 -07003311 length -= 256;
Elliott Hughesa2155262011-11-16 16:26:58 -08003312 }
Ian Rogers30fab402012-01-23 15:43:46 -08003313 *p_++ = state;
Ian Rogers15bf2d32012-08-28 17:33:04 -07003314 *p_++ = length - 1;
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003315 }
3316
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003317 uint8_t ExamineObject(const mirror::Object* o, bool is_native_heap)
Ian Rogersb726dcb2012-09-05 08:57:23 -07003318 SHARED_LOCKS_REQUIRED(Locks::heap_bitmap_lock_) {
Elliott Hughesa2155262011-11-16 16:26:58 -08003319 if (o == NULL) {
3320 return HPSG_STATE(SOLIDITY_FREE, 0);
3321 }
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003322
Elliott Hughesa2155262011-11-16 16:26:58 -08003323 // It's an allocated chunk. Figure out what it is.
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003324
Elliott Hughesa2155262011-11-16 16:26:58 -08003325 // If we're looking at the native heap, we'll just return
3326 // (SOLIDITY_HARD, KIND_NATIVE) for all allocated chunks.
Ian Rogers00f7d0e2012-07-19 15:28:27 -07003327 if (is_native_heap) {
Elliott Hughesa2155262011-11-16 16:26:58 -08003328 return HPSG_STATE(SOLIDITY_HARD, KIND_NATIVE);
3329 }
3330
Ian Rogers5bfa60f2012-09-02 21:17:56 -07003331 if (!Runtime::Current()->GetHeap()->IsLiveObjectLocked(o)) {
Ian Rogers15bf2d32012-08-28 17:33:04 -07003332 return HPSG_STATE(SOLIDITY_HARD, KIND_NATIVE);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07003333 }
3334
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003335 mirror::Class* c = o->GetClass();
Elliott Hughesa2155262011-11-16 16:26:58 -08003336 if (c == NULL) {
3337 // The object was probably just created but hasn't been initialized yet.
3338 return HPSG_STATE(SOLIDITY_HARD, KIND_OBJECT);
3339 }
3340
Elliott Hughesb3bd5f02012-03-08 21:05:27 -08003341 if (!Runtime::Current()->GetHeap()->IsHeapAddress(c)) {
Ian Rogers15bf2d32012-08-28 17:33:04 -07003342 LOG(ERROR) << "Invalid class for managed heap object: " << o << " " << c;
Elliott Hughesa2155262011-11-16 16:26:58 -08003343 return HPSG_STATE(SOLIDITY_HARD, KIND_UNKNOWN);
3344 }
3345
3346 if (c->IsClassClass()) {
3347 return HPSG_STATE(SOLIDITY_HARD, KIND_CLASS_OBJECT);
3348 }
3349
3350 if (c->IsArrayClass()) {
3351 if (o->IsObjectArray()) {
3352 return HPSG_STATE(SOLIDITY_HARD, KIND_ARRAY_4);
3353 }
3354 switch (c->GetComponentSize()) {
3355 case 1: return HPSG_STATE(SOLIDITY_HARD, KIND_ARRAY_1);
3356 case 2: return HPSG_STATE(SOLIDITY_HARD, KIND_ARRAY_2);
3357 case 4: return HPSG_STATE(SOLIDITY_HARD, KIND_ARRAY_4);
3358 case 8: return HPSG_STATE(SOLIDITY_HARD, KIND_ARRAY_8);
3359 }
3360 }
3361
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003362 return HPSG_STATE(SOLIDITY_HARD, KIND_OBJECT);
3363 }
3364
Ian Rogers30fab402012-01-23 15:43:46 -08003365 std::vector<uint8_t> buf_;
3366 uint8_t* p_;
3367 uint8_t* pieceLenField_;
Ian Rogers15bf2d32012-08-28 17:33:04 -07003368 void* startOfNextMemoryChunk_;
Ian Rogers30fab402012-01-23 15:43:46 -08003369 size_t totalAllocationUnits_;
3370 uint32_t type_;
3371 bool merge_;
3372 bool needHeader_;
3373
Elliott Hughesa2155262011-11-16 16:26:58 -08003374 DISALLOW_COPY_AND_ASSIGN(HeapChunkContext);
3375};
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003376
3377void Dbg::DdmSendHeapSegments(bool native) {
3378 Dbg::HpsgWhen when;
3379 Dbg::HpsgWhat what;
3380 if (!native) {
3381 when = gDdmHpsgWhen;
3382 what = gDdmHpsgWhat;
3383 } else {
3384 when = gDdmNhsgWhen;
3385 what = gDdmNhsgWhat;
3386 }
3387 if (when == HPSG_WHEN_NEVER) {
3388 return;
3389 }
3390
3391 // Figure out what kind of chunks we'll be sending.
3392 CHECK(what == HPSG_WHAT_MERGED_OBJECTS || what == HPSG_WHAT_DISTINCT_OBJECTS) << static_cast<int>(what);
3393
3394 // First, send a heap start chunk.
3395 uint8_t heap_id[4];
3396 JDWP::Set4BE(&heap_id[0], 1); // Heap id (bogus; we only have one heap).
3397 Dbg::DdmSendChunk(native ? CHUNK_TYPE("NHST") : CHUNK_TYPE("HPST"), sizeof(heap_id), heap_id);
3398
3399 // Send a series of heap segment chunks.
Elliott Hughesa2155262011-11-16 16:26:58 -08003400 HeapChunkContext context((what == HPSG_WHAT_MERGED_OBJECTS), native);
3401 if (native) {
Ian Rogers30fab402012-01-23 15:43:46 -08003402 // TODO: enable when bionic has moved to dlmalloc 2.8.5
3403 // dlmalloc_inspect_all(HeapChunkContext::HeapChunkCallback, &context);
3404 UNIMPLEMENTED(WARNING) << "Native heap send heap segments";
Elliott Hughesa2155262011-11-16 16:26:58 -08003405 } else {
Elliott Hughesb3bd5f02012-03-08 21:05:27 -08003406 Heap* heap = Runtime::Current()->GetHeap();
Mathieu Chartierfd678be2012-08-30 14:50:54 -07003407 const Spaces& spaces = heap->GetSpaces();
Ian Rogers50b35e22012-10-04 10:09:15 -07003408 Thread* self = Thread::Current();
Ian Rogers62d6c772013-02-27 08:32:07 -08003409 ReaderMutexLock mu(self, *Locks::heap_bitmap_lock_);
Mathieu Chartierfd678be2012-08-30 14:50:54 -07003410 for (Spaces::const_iterator cur = spaces.begin(); cur != spaces.end(); ++cur) {
Mathieu Chartierb062fdd2012-07-03 09:51:48 -07003411 if ((*cur)->IsAllocSpace()) {
3412 (*cur)->AsAllocSpace()->Walk(HeapChunkContext::HeapChunkCallback, &context);
3413 }
3414 }
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -07003415 // Walk the large objects, these are not in the AllocSpace.
3416 heap->GetLargeObjectsSpace()->Walk(HeapChunkContext::HeapChunkCallback, &context);
Elliott Hughesa2155262011-11-16 16:26:58 -08003417 }
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003418
3419 // Finally, send a heap end chunk.
3420 Dbg::DdmSendChunk(native ? CHUNK_TYPE("NHEN") : CHUNK_TYPE("HPEN"), sizeof(heap_id), heap_id);
Elliott Hughes767a1472011-10-26 18:49:02 -07003421}
3422
Elliott Hughes545a0642011-11-08 19:10:03 -08003423void Dbg::SetAllocTrackingEnabled(bool enabled) {
Ian Rogers50b35e22012-10-04 10:09:15 -07003424 MutexLock mu(Thread::Current(), gAllocTrackerLock);
Elliott Hughes545a0642011-11-08 19:10:03 -08003425 if (enabled) {
3426 if (recent_allocation_records_ == NULL) {
3427 LOG(INFO) << "Enabling alloc tracker (" << kNumAllocRecords << " entries, "
3428 << kMaxAllocRecordStackDepth << " frames --> "
3429 << (sizeof(AllocRecord) * kNumAllocRecords) << " bytes)";
3430 gAllocRecordHead = gAllocRecordCount = 0;
3431 recent_allocation_records_ = new AllocRecord[kNumAllocRecords];
3432 CHECK(recent_allocation_records_ != NULL);
3433 }
3434 } else {
3435 delete[] recent_allocation_records_;
3436 recent_allocation_records_ = NULL;
3437 }
3438}
3439
Ian Rogers0399dde2012-06-06 17:09:28 -07003440struct AllocRecordStackVisitor : public StackVisitor {
Ian Rogers7a22fa62013-01-23 12:16:16 -08003441 AllocRecordStackVisitor(Thread* thread, AllocRecord* record)
Ian Rogersb726dcb2012-09-05 08:57:23 -07003442 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_)
Ian Rogers7a22fa62013-01-23 12:16:16 -08003443 : StackVisitor(thread, NULL), record(record), depth(0) {}
Elliott Hughes545a0642011-11-08 19:10:03 -08003444
Ian Rogers00f7d0e2012-07-19 15:28:27 -07003445 // TODO: Enable annotalysis. We know lock is held in constructor, but abstraction confuses
3446 // annotalysis.
3447 bool VisitFrame() NO_THREAD_SAFETY_ANALYSIS {
Elliott Hughes545a0642011-11-08 19:10:03 -08003448 if (depth >= kMaxAllocRecordStackDepth) {
Elliott Hughes530fa002012-03-12 11:44:49 -07003449 return false;
Elliott Hughes545a0642011-11-08 19:10:03 -08003450 }
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003451 mirror::AbstractMethod* m = GetMethod();
Ian Rogers0399dde2012-06-06 17:09:28 -07003452 if (!m->IsRuntimeMethod()) {
3453 record->stack[depth].method = m;
3454 record->stack[depth].dex_pc = GetDexPc();
Elliott Hughes530fa002012-03-12 11:44:49 -07003455 ++depth;
Elliott Hughes545a0642011-11-08 19:10:03 -08003456 }
Elliott Hughes530fa002012-03-12 11:44:49 -07003457 return true;
Elliott Hughes545a0642011-11-08 19:10:03 -08003458 }
3459
3460 ~AllocRecordStackVisitor() {
3461 // Clear out any unused stack trace elements.
3462 for (; depth < kMaxAllocRecordStackDepth; ++depth) {
3463 record->stack[depth].method = NULL;
Ian Rogers0399dde2012-06-06 17:09:28 -07003464 record->stack[depth].dex_pc = 0;
Elliott Hughes545a0642011-11-08 19:10:03 -08003465 }
3466 }
3467
3468 AllocRecord* record;
3469 size_t depth;
3470};
3471
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003472void Dbg::RecordAllocation(mirror::Class* type, size_t byte_count) {
Elliott Hughes545a0642011-11-08 19:10:03 -08003473 Thread* self = Thread::Current();
3474 CHECK(self != NULL);
3475
Ian Rogers50b35e22012-10-04 10:09:15 -07003476 MutexLock mu(self, gAllocTrackerLock);
Elliott Hughes545a0642011-11-08 19:10:03 -08003477 if (recent_allocation_records_ == NULL) {
3478 return;
3479 }
3480
3481 // Advance and clip.
3482 if (++gAllocRecordHead == kNumAllocRecords) {
3483 gAllocRecordHead = 0;
3484 }
3485
3486 // Fill in the basics.
3487 AllocRecord* record = &recent_allocation_records_[gAllocRecordHead];
3488 record->type = type;
3489 record->byte_count = byte_count;
3490 record->thin_lock_id = self->GetThinLockId();
3491
3492 // Fill in the stack trace.
Ian Rogers7a22fa62013-01-23 12:16:16 -08003493 AllocRecordStackVisitor visitor(self, record);
Ian Rogers0399dde2012-06-06 17:09:28 -07003494 visitor.WalkStack();
Elliott Hughes545a0642011-11-08 19:10:03 -08003495
3496 if (gAllocRecordCount < kNumAllocRecords) {
3497 ++gAllocRecordCount;
3498 }
3499}
3500
Elliott Hughesa8f93cb2012-06-08 17:08:48 -07003501// Returns the index of the head element.
3502//
3503// We point at the most-recently-written record, so if gAllocRecordCount is 1
3504// we want to use the current element. Take "head+1" and subtract count
3505// from it.
3506//
3507// We need to handle underflow in our circular buffer, so we add
3508// kNumAllocRecords and then mask it back down.
Elliott Hughesf8349362012-06-18 15:00:06 -07003509static inline int HeadIndex() EXCLUSIVE_LOCKS_REQUIRED(gAllocTrackerLock) {
Elliott Hughes545a0642011-11-08 19:10:03 -08003510 return (gAllocRecordHead+1 + kNumAllocRecords - gAllocRecordCount) & (kNumAllocRecords-1);
3511}
3512
3513void Dbg::DumpRecentAllocations() {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07003514 ScopedObjectAccess soa(Thread::Current());
Ian Rogers50b35e22012-10-04 10:09:15 -07003515 MutexLock mu(soa.Self(), gAllocTrackerLock);
Elliott Hughes545a0642011-11-08 19:10:03 -08003516 if (recent_allocation_records_ == NULL) {
3517 LOG(INFO) << "Not recording tracked allocations";
3518 return;
3519 }
3520
3521 // "i" is the head of the list. We want to start at the end of the
3522 // list and move forward to the tail.
Elliott Hughesa8f93cb2012-06-08 17:08:48 -07003523 size_t i = HeadIndex();
Elliott Hughes545a0642011-11-08 19:10:03 -08003524 size_t count = gAllocRecordCount;
3525
3526 LOG(INFO) << "Tracked allocations, (head=" << gAllocRecordHead << " count=" << count << ")";
3527 while (count--) {
3528 AllocRecord* record = &recent_allocation_records_[i];
3529
Elliott Hughesa8f93cb2012-06-08 17:08:48 -07003530 LOG(INFO) << StringPrintf(" Thread %-2d %6zd bytes ", record->thin_lock_id, record->byte_count)
Elliott Hughes545a0642011-11-08 19:10:03 -08003531 << PrettyClass(record->type);
3532
3533 for (size_t stack_frame = 0; stack_frame < kMaxAllocRecordStackDepth; ++stack_frame) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003534 const mirror::AbstractMethod* m = record->stack[stack_frame].method;
Elliott Hughes545a0642011-11-08 19:10:03 -08003535 if (m == NULL) {
3536 break;
3537 }
3538 LOG(INFO) << " " << PrettyMethod(m) << " line " << record->stack[stack_frame].LineNumber();
3539 }
3540
3541 // pause periodically to help logcat catch up
3542 if ((count % 5) == 0) {
3543 usleep(40000);
3544 }
3545
3546 i = (i + 1) & (kNumAllocRecords-1);
3547 }
3548}
3549
3550class StringTable {
3551 public:
3552 StringTable() {
3553 }
3554
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08003555 void Add(const char* s) {
Elliott Hughes545a0642011-11-08 19:10:03 -08003556 table_.insert(s);
3557 }
3558
Elliott Hughesa8f93cb2012-06-08 17:08:48 -07003559 size_t IndexOf(const char* s) const {
3560 typedef std::set<std::string>::const_iterator It; // TODO: C++0x auto
3561 It it = table_.find(s);
3562 if (it == table_.end()) {
3563 LOG(FATAL) << "IndexOf(\"" << s << "\") failed";
3564 }
3565 return std::distance(table_.begin(), it);
Elliott Hughes545a0642011-11-08 19:10:03 -08003566 }
3567
Elliott Hughesa8f93cb2012-06-08 17:08:48 -07003568 size_t Size() const {
Elliott Hughes545a0642011-11-08 19:10:03 -08003569 return table_.size();
3570 }
3571
Elliott Hughesa8f93cb2012-06-08 17:08:48 -07003572 void WriteTo(std::vector<uint8_t>& bytes) const {
3573 typedef std::set<std::string>::const_iterator It; // TODO: C++0x auto
Elliott Hughes545a0642011-11-08 19:10:03 -08003574 for (It it = table_.begin(); it != table_.end(); ++it) {
Elliott Hughesa8f93cb2012-06-08 17:08:48 -07003575 const char* s = (*it).c_str();
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08003576 size_t s_len = CountModifiedUtf8Chars(s);
3577 UniquePtr<uint16_t> s_utf16(new uint16_t[s_len]);
3578 ConvertModifiedUtf8ToUtf16(s_utf16.get(), s);
3579 JDWP::AppendUtf16BE(bytes, s_utf16.get(), s_len);
Elliott Hughes545a0642011-11-08 19:10:03 -08003580 }
3581 }
3582
3583 private:
Elliott Hughesa8f93cb2012-06-08 17:08:48 -07003584 std::set<std::string> table_;
Elliott Hughes545a0642011-11-08 19:10:03 -08003585 DISALLOW_COPY_AND_ASSIGN(StringTable);
3586};
3587
3588/*
3589 * The data we send to DDMS contains everything we have recorded.
3590 *
3591 * Message header (all values big-endian):
3592 * (1b) message header len (to allow future expansion); includes itself
3593 * (1b) entry header len
3594 * (1b) stack frame len
3595 * (2b) number of entries
3596 * (4b) offset to string table from start of message
3597 * (2b) number of class name strings
3598 * (2b) number of method name strings
3599 * (2b) number of source file name strings
3600 * For each entry:
3601 * (4b) total allocation size
Elliott Hughes221229c2013-01-08 18:17:50 -08003602 * (2b) thread id
Elliott Hughes545a0642011-11-08 19:10:03 -08003603 * (2b) allocated object's class name index
3604 * (1b) stack depth
3605 * For each stack frame:
3606 * (2b) method's class name
3607 * (2b) method name
3608 * (2b) method source file
3609 * (2b) line number, clipped to 32767; -2 if native; -1 if no source
3610 * (xb) class name strings
3611 * (xb) method name strings
3612 * (xb) source file strings
3613 *
3614 * As with other DDM traffic, strings are sent as a 4-byte length
3615 * followed by UTF-16 data.
3616 *
3617 * We send up 16-bit unsigned indexes into string tables. In theory there
3618 * can be (kMaxAllocRecordStackDepth * kNumAllocRecords) unique strings in
3619 * each table, but in practice there should be far fewer.
3620 *
3621 * The chief reason for using a string table here is to keep the size of
3622 * the DDMS message to a minimum. This is partly to make the protocol
3623 * efficient, but also because we have to form the whole thing up all at
3624 * once in a memory buffer.
3625 *
3626 * We use separate string tables for class names, method names, and source
3627 * files to keep the indexes small. There will generally be no overlap
3628 * between the contents of these tables.
3629 */
3630jbyteArray Dbg::GetRecentAllocations() {
3631 if (false) {
3632 DumpRecentAllocations();
3633 }
3634
Ian Rogers50b35e22012-10-04 10:09:15 -07003635 Thread* self = Thread::Current();
3636 MutexLock mu(self, gAllocTrackerLock);
Elliott Hughes545a0642011-11-08 19:10:03 -08003637
Elliott Hughesa8f93cb2012-06-08 17:08:48 -07003638 //
3639 // Part 1: generate string tables.
3640 //
Elliott Hughes545a0642011-11-08 19:10:03 -08003641 StringTable class_names;
3642 StringTable method_names;
3643 StringTable filenames;
3644
3645 int count = gAllocRecordCount;
Elliott Hughesa8f93cb2012-06-08 17:08:48 -07003646 int idx = HeadIndex();
Elliott Hughes545a0642011-11-08 19:10:03 -08003647 while (count--) {
3648 AllocRecord* record = &recent_allocation_records_[idx];
3649
Elliott Hughes91250e02011-12-13 22:30:35 -08003650 class_names.Add(ClassHelper(record->type).GetDescriptor());
Elliott Hughes545a0642011-11-08 19:10:03 -08003651
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08003652 MethodHelper mh;
Elliott Hughes545a0642011-11-08 19:10:03 -08003653 for (size_t i = 0; i < kMaxAllocRecordStackDepth; i++) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003654 mirror::AbstractMethod* m = record->stack[i].method;
Elliott Hughes545a0642011-11-08 19:10:03 -08003655 if (m != NULL) {
Ian Rogersba377812012-05-28 21:16:29 -07003656 mh.ChangeMethod(m);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08003657 class_names.Add(mh.GetDeclaringClassDescriptor());
3658 method_names.Add(mh.GetName());
3659 filenames.Add(mh.GetDeclaringClassSourceFile());
Elliott Hughes545a0642011-11-08 19:10:03 -08003660 }
3661 }
3662
3663 idx = (idx + 1) & (kNumAllocRecords-1);
3664 }
3665
3666 LOG(INFO) << "allocation records: " << gAllocRecordCount;
3667
Elliott Hughesa8f93cb2012-06-08 17:08:48 -07003668 //
3669 // Part 2: allocate a buffer and generate the output.
3670 //
Elliott Hughes545a0642011-11-08 19:10:03 -08003671 std::vector<uint8_t> bytes;
3672
3673 // (1b) message header len (to allow future expansion); includes itself
3674 // (1b) entry header len
3675 // (1b) stack frame len
3676 const int kMessageHeaderLen = 15;
3677 const int kEntryHeaderLen = 9;
3678 const int kStackFrameLen = 8;
3679 JDWP::Append1BE(bytes, kMessageHeaderLen);
3680 JDWP::Append1BE(bytes, kEntryHeaderLen);
3681 JDWP::Append1BE(bytes, kStackFrameLen);
3682
3683 // (2b) number of entries
3684 // (4b) offset to string table from start of message
3685 // (2b) number of class name strings
3686 // (2b) number of method name strings
3687 // (2b) number of source file name strings
3688 JDWP::Append2BE(bytes, gAllocRecordCount);
3689 size_t string_table_offset = bytes.size();
3690 JDWP::Append4BE(bytes, 0); // We'll patch this later...
3691 JDWP::Append2BE(bytes, class_names.Size());
3692 JDWP::Append2BE(bytes, method_names.Size());
3693 JDWP::Append2BE(bytes, filenames.Size());
3694
3695 count = gAllocRecordCount;
Elliott Hughesa8f93cb2012-06-08 17:08:48 -07003696 idx = HeadIndex();
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08003697 ClassHelper kh;
Elliott Hughes545a0642011-11-08 19:10:03 -08003698 while (count--) {
3699 // For each entry:
3700 // (4b) total allocation size
3701 // (2b) thread id
3702 // (2b) allocated object's class name index
3703 // (1b) stack depth
3704 AllocRecord* record = &recent_allocation_records_[idx];
3705 size_t stack_depth = record->GetDepth();
Elliott Hughesa8f93cb2012-06-08 17:08:48 -07003706 kh.ChangeClass(record->type);
3707 size_t allocated_object_class_name_index = class_names.IndexOf(kh.GetDescriptor());
Elliott Hughes545a0642011-11-08 19:10:03 -08003708 JDWP::Append4BE(bytes, record->byte_count);
3709 JDWP::Append2BE(bytes, record->thin_lock_id);
Elliott Hughesa8f93cb2012-06-08 17:08:48 -07003710 JDWP::Append2BE(bytes, allocated_object_class_name_index);
Elliott Hughes545a0642011-11-08 19:10:03 -08003711 JDWP::Append1BE(bytes, stack_depth);
3712
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08003713 MethodHelper mh;
Elliott Hughes545a0642011-11-08 19:10:03 -08003714 for (size_t stack_frame = 0; stack_frame < stack_depth; ++stack_frame) {
3715 // For each stack frame:
3716 // (2b) method's class name
3717 // (2b) method name
3718 // (2b) method source file
3719 // (2b) line number, clipped to 32767; -2 if native; -1 if no source
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08003720 mh.ChangeMethod(record->stack[stack_frame].method);
Elliott Hughesa8f93cb2012-06-08 17:08:48 -07003721 size_t class_name_index = class_names.IndexOf(mh.GetDeclaringClassDescriptor());
3722 size_t method_name_index = method_names.IndexOf(mh.GetName());
3723 size_t file_name_index = filenames.IndexOf(mh.GetDeclaringClassSourceFile());
3724 JDWP::Append2BE(bytes, class_name_index);
3725 JDWP::Append2BE(bytes, method_name_index);
3726 JDWP::Append2BE(bytes, file_name_index);
Elliott Hughes545a0642011-11-08 19:10:03 -08003727 JDWP::Append2BE(bytes, record->stack[stack_frame].LineNumber());
3728 }
3729
3730 idx = (idx + 1) & (kNumAllocRecords-1);
3731 }
3732
3733 // (xb) class name strings
3734 // (xb) method name strings
3735 // (xb) source file strings
3736 JDWP::Set4BE(&bytes[string_table_offset], bytes.size());
3737 class_names.WriteTo(bytes);
3738 method_names.WriteTo(bytes);
3739 filenames.WriteTo(bytes);
3740
Ian Rogers50b35e22012-10-04 10:09:15 -07003741 JNIEnv* env = self->GetJniEnv();
Elliott Hughes545a0642011-11-08 19:10:03 -08003742 jbyteArray result = env->NewByteArray(bytes.size());
3743 if (result != NULL) {
3744 env->SetByteArrayRegion(result, 0, bytes.size(), reinterpret_cast<const jbyte*>(&bytes[0]));
3745 }
3746 return result;
3747}
3748
Elliott Hughes872d4ec2011-10-21 17:07:15 -07003749} // namespace art