blob: d3f684dc0c1835c42f8a9c7439e04b91ca4bbd58 [file] [log] [blame]
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001/*
2 * Copyright (C) 2008 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17#include "debugger.h"
18
Elliott Hughes3bb81562011-10-21 18:52:59 -070019#include <sys/uio.h>
20
Elliott Hughes545a0642011-11-08 19:10:03 -080021#include <set>
22
Ian Rogers166db042013-07-26 12:05:57 -070023#include "arch/context.h"
Elliott Hughes545a0642011-11-08 19:10:03 -080024#include "class_linker.h"
Ian Rogers2dd0e2c2013-01-24 12:42:14 -080025#include "class_linker-inl.h"
Ian Rogers4f6ad8a2013-03-18 15:27:28 -070026#include "dex_file-inl.h"
Ian Rogers776ac1f2012-04-13 23:36:36 -070027#include "dex_instruction.h"
Ian Rogers1d54e732013-05-02 21:10:01 -070028#include "gc/accounting/card_table-inl.h"
29#include "gc/space/large_object_space.h"
30#include "gc/space/space-inl.h"
Jeff Hao5d917302013-02-27 17:57:33 -080031#include "invoke_arg_array_builder.h"
Elliott Hughes64f574f2013-02-20 14:57:12 -080032#include "jdwp/object_registry.h"
Brian Carlstromea46f952013-07-30 01:26:50 -070033#include "mirror/art_field-inl.h"
34#include "mirror/art_method-inl.h"
Ian Rogers2dd0e2c2013-01-24 12:42:14 -080035#include "mirror/class.h"
36#include "mirror/class-inl.h"
37#include "mirror/class_loader.h"
Ian Rogers2dd0e2c2013-01-24 12:42:14 -080038#include "mirror/object-inl.h"
39#include "mirror/object_array-inl.h"
40#include "mirror/throwable.h"
Ian Rogers6d4d9fc2011-11-30 16:24:48 -080041#include "object_utils.h"
Elliott Hughesa0e18062012-04-13 15:59:59 -070042#include "safe_map.h"
Elliott Hughes64f574f2013-02-20 14:57:12 -080043#include "scoped_thread_state_change.h"
Elliott Hughes6a5bd492011-10-28 14:33:57 -070044#include "ScopedLocalRef.h"
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -070045#include "ScopedPrimitiveArray.h"
Ian Rogers1f539342012-10-03 21:09:42 -070046#include "sirt_ref.h"
Elliott Hughes47fce012011-10-25 18:37:19 -070047#include "stack_indirect_reference_table.h"
Elliott Hughes475fc232011-10-25 15:00:35 -070048#include "thread_list.h"
Ian Rogers62d6c772013-02-27 08:32:07 -080049#include "throw_location.h"
Ian Rogers2dd0e2c2013-01-24 12:42:14 -080050#include "utf.h"
Elliott Hugheseac76672012-05-24 21:56:51 -070051#include "well_known_classes.h"
Elliott Hughes475fc232011-10-25 15:00:35 -070052
Brian Carlstrom3d92d522013-07-12 09:03:08 -070053#ifdef HAVE_ANDROID_OS
54#include "cutils/properties.h"
55#endif
56
Elliott Hughes872d4ec2011-10-21 17:07:15 -070057namespace art {
58
Brian Carlstrom7934ac22013-07-26 10:54:15 -070059static const size_t kMaxAllocRecordStackDepth = 16; // Max 255.
60static const size_t kDefaultNumAllocRecords = 64*1024; // Must be a power of 2.
Elliott Hughes475fc232011-10-25 15:00:35 -070061
Elliott Hughes545a0642011-11-08 19:10:03 -080062struct AllocRecordStackTraceElement {
Brian Carlstromea46f952013-07-30 01:26:50 -070063 mirror::ArtMethod* method;
Ian Rogers0399dde2012-06-06 17:09:28 -070064 uint32_t dex_pc;
Elliott Hughes545a0642011-11-08 19:10:03 -080065
Mathieu Chartier412c7fc2014-02-07 12:18:39 -080066 AllocRecordStackTraceElement() : method(nullptr), dex_pc(0) {
67 }
68
Ian Rogersb726dcb2012-09-05 08:57:23 -070069 int32_t LineNumber() const SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Ian Rogers0399dde2012-06-06 17:09:28 -070070 return MethodHelper(method).GetLineNumFromDexPC(dex_pc);
Elliott Hughes545a0642011-11-08 19:10:03 -080071 }
72};
73
74struct AllocRecord {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -080075 mirror::Class* type;
Elliott Hughes545a0642011-11-08 19:10:03 -080076 size_t byte_count;
77 uint16_t thin_lock_id;
Brian Carlstrom7934ac22013-07-26 10:54:15 -070078 AllocRecordStackTraceElement stack[kMaxAllocRecordStackDepth]; // Unused entries have NULL method.
Elliott Hughes545a0642011-11-08 19:10:03 -080079
80 size_t GetDepth() {
81 size_t depth = 0;
82 while (depth < kMaxAllocRecordStackDepth && stack[depth].method != NULL) {
83 ++depth;
84 }
85 return depth;
86 }
Mathieu Chartier412c7fc2014-02-07 12:18:39 -080087
Mathieu Chartier83c8ee02014-01-28 14:50:23 -080088 void UpdateObjectPointers(IsMarkedCallback* callback, void* arg)
Mathieu Chartier412c7fc2014-02-07 12:18:39 -080089 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
90 if (type != nullptr) {
Mathieu Chartier83c8ee02014-01-28 14:50:23 -080091 type = down_cast<mirror::Class*>(callback(type, arg));
Mathieu Chartier412c7fc2014-02-07 12:18:39 -080092 }
93 for (size_t stack_frame = 0; stack_frame < kMaxAllocRecordStackDepth; ++stack_frame) {
94 mirror::ArtMethod*& m = stack[stack_frame].method;
95 if (m == nullptr) {
96 break;
97 }
Mathieu Chartier83c8ee02014-01-28 14:50:23 -080098 m = down_cast<mirror::ArtMethod*>(callback(m, arg));
Mathieu Chartier412c7fc2014-02-07 12:18:39 -080099 }
100 }
Elliott Hughes545a0642011-11-08 19:10:03 -0800101};
102
Elliott Hughes86964332012-02-15 19:37:42 -0800103struct Breakpoint {
Brian Carlstromea46f952013-07-30 01:26:50 -0700104 mirror::ArtMethod* method;
Elliott Hughesa656a0f2012-02-21 18:03:44 -0800105 uint32_t dex_pc;
Brian Carlstromea46f952013-07-30 01:26:50 -0700106 Breakpoint(mirror::ArtMethod* method, uint32_t dex_pc) : method(method), dex_pc(dex_pc) {}
Elliott Hughes86964332012-02-15 19:37:42 -0800107};
108
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700109static std::ostream& operator<<(std::ostream& os, const Breakpoint& rhs)
Ian Rogersb726dcb2012-09-05 08:57:23 -0700110 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Elliott Hughes229feb72012-02-23 13:33:29 -0800111 os << StringPrintf("Breakpoint[%s @%#x]", PrettyMethod(rhs.method).c_str(), rhs.dex_pc);
Elliott Hughes86964332012-02-15 19:37:42 -0800112 return os;
113}
114
Ian Rogers62d6c772013-02-27 08:32:07 -0800115class DebugInstrumentationListener : public instrumentation::InstrumentationListener {
116 public:
117 DebugInstrumentationListener() {}
118 virtual ~DebugInstrumentationListener() {}
119
120 virtual void MethodEntered(Thread* thread, mirror::Object* this_object,
Ian Rogersef7d42f2014-01-06 12:55:46 -0800121 mirror::ArtMethod* method, uint32_t dex_pc)
Ian Rogers62d6c772013-02-27 08:32:07 -0800122 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
123 if (method->IsNative()) {
124 // TODO: post location events is a suspension point and native method entry stubs aren't.
125 return;
126 }
Jeff Hao579b0242013-11-18 13:16:49 -0800127 Dbg::PostLocationEvent(method, 0, this_object, Dbg::kMethodEntry, nullptr);
Ian Rogers62d6c772013-02-27 08:32:07 -0800128 }
129
130 virtual void MethodExited(Thread* thread, mirror::Object* this_object,
Ian Rogersef7d42f2014-01-06 12:55:46 -0800131 mirror::ArtMethod* method,
Ian Rogers62d6c772013-02-27 08:32:07 -0800132 uint32_t dex_pc, const JValue& return_value)
133 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Ian Rogers62d6c772013-02-27 08:32:07 -0800134 if (method->IsNative()) {
135 // TODO: post location events is a suspension point and native method entry stubs aren't.
136 return;
137 }
Jeff Hao579b0242013-11-18 13:16:49 -0800138 Dbg::PostLocationEvent(method, dex_pc, this_object, Dbg::kMethodExit, &return_value);
Ian Rogers62d6c772013-02-27 08:32:07 -0800139 }
140
Sebastien Hertz51db44a2013-11-19 10:00:29 +0100141 virtual void MethodUnwind(Thread* thread, mirror::Object* this_object,
Ian Rogersef7d42f2014-01-06 12:55:46 -0800142 mirror::ArtMethod* method, uint32_t dex_pc)
Sebastien Hertz51db44a2013-11-19 10:00:29 +0100143 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Ian Rogers62d6c772013-02-27 08:32:07 -0800144 // We're not recorded to listen to this kind of event, so complain.
145 LOG(ERROR) << "Unexpected method unwind event in debugger " << PrettyMethod(method)
Sebastien Hertz51db44a2013-11-19 10:00:29 +0100146 << " " << dex_pc;
Ian Rogers62d6c772013-02-27 08:32:07 -0800147 }
148
149 virtual void DexPcMoved(Thread* thread, mirror::Object* this_object,
Ian Rogersef7d42f2014-01-06 12:55:46 -0800150 mirror::ArtMethod* method, uint32_t new_dex_pc)
Ian Rogers62d6c772013-02-27 08:32:07 -0800151 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
152 Dbg::UpdateDebugger(thread, this_object, method, new_dex_pc);
153 }
154
155 virtual void ExceptionCaught(Thread* thread, const ThrowLocation& throw_location,
Brian Carlstromea46f952013-07-30 01:26:50 -0700156 mirror::ArtMethod* catch_method, uint32_t catch_dex_pc,
Ian Rogers62d6c772013-02-27 08:32:07 -0800157 mirror::Throwable* exception_object)
158 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
159 Dbg::PostException(thread, throw_location, catch_method, catch_dex_pc, exception_object);
160 }
Ian Rogers62d6c772013-02-27 08:32:07 -0800161} gDebugInstrumentationListener;
162
Elliott Hughes4ffd3132011-10-24 12:06:42 -0700163// JDWP is allowed unless the Zygote forbids it.
164static bool gJdwpAllowed = true;
165
Elliott Hughesc0f09332012-03-26 13:27:06 -0700166// Was there a -Xrunjdwp or -agentlib:jdwp= argument on the command line?
Elliott Hughes3bb81562011-10-21 18:52:59 -0700167static bool gJdwpConfigured = false;
168
Elliott Hughesc0f09332012-03-26 13:27:06 -0700169// Broken-down JDWP options. (Only valid if IsJdwpConfigured() is true.)
Elliott Hughes376a7a02011-10-24 18:35:55 -0700170static JDWP::JdwpOptions gJdwpOptions;
Elliott Hughes3bb81562011-10-21 18:52:59 -0700171
172// Runtime JDWP state.
173static JDWP::JdwpState* gJdwpState = NULL;
174static bool gDebuggerConnected; // debugger or DDMS is connected.
175static bool gDebuggerActive; // debugger is making requests.
Elliott Hughes86964332012-02-15 19:37:42 -0800176static bool gDisposed; // debugger called VirtualMachine.Dispose, so we should drop the connection.
Elliott Hughes3bb81562011-10-21 18:52:59 -0700177
Elliott Hughes47fce012011-10-25 18:37:19 -0700178static bool gDdmThreadNotification = false;
179
Elliott Hughes767a1472011-10-26 18:49:02 -0700180// DDMS GC-related settings.
181static Dbg::HpifWhen gDdmHpifWhen = Dbg::HPIF_WHEN_NEVER;
182static Dbg::HpsgWhen gDdmHpsgWhen = Dbg::HPSG_WHEN_NEVER;
183static Dbg::HpsgWhat gDdmHpsgWhat;
184static Dbg::HpsgWhen gDdmNhsgWhen = Dbg::HPSG_WHEN_NEVER;
185static Dbg::HpsgWhat gDdmNhsgWhat;
186
Elliott Hughes475fc232011-10-25 15:00:35 -0700187static ObjectRegistry* gRegistry = NULL;
188
Elliott Hughes545a0642011-11-08 19:10:03 -0800189// Recent allocation tracking.
Brian Carlstromdf629502013-07-17 22:39:56 -0700190static Mutex gAllocTrackerLock DEFAULT_MUTEX_ACQUIRED_AFTER("AllocTracker lock");
Brian Carlstrom7934ac22013-07-26 10:54:15 -0700191AllocRecord* Dbg::recent_allocation_records_ PT_GUARDED_BY(gAllocTrackerLock) = NULL; // TODO: CircularBuffer<AllocRecord>
Elliott Hughesb1a58792013-07-11 18:10:58 -0700192static size_t gAllocRecordMax GUARDED_BY(gAllocTrackerLock) = 0;
Elliott Hughesf8349362012-06-18 15:00:06 -0700193static size_t gAllocRecordHead GUARDED_BY(gAllocTrackerLock) = 0;
194static size_t gAllocRecordCount GUARDED_BY(gAllocTrackerLock) = 0;
Elliott Hughes545a0642011-11-08 19:10:03 -0800195
Sebastien Hertz138dbfc2013-12-04 18:15:25 +0100196// Deoptimization support.
197struct MethodInstrumentationRequest {
198 bool deoptimize;
199
200 // Method for selective deoptimization. NULL means full deoptimization.
201 mirror::ArtMethod* method;
202
203 MethodInstrumentationRequest(bool deoptimize, mirror::ArtMethod* method)
204 : deoptimize(deoptimize), method(method) {}
205};
206// TODO we need to visit associated methods as roots.
207static std::vector<MethodInstrumentationRequest> gDeoptimizationRequests GUARDED_BY(Locks::deoptimization_lock_);
208
209// Breakpoints.
jeffhao09bfc6a2012-12-11 18:11:43 -0800210static std::vector<Breakpoint> gBreakpoints GUARDED_BY(Locks::breakpoint_lock_);
Elliott Hughes86964332012-02-15 19:37:42 -0800211
Brian Carlstromea46f952013-07-30 01:26:50 -0700212static bool IsBreakpoint(const mirror::ArtMethod* m, uint32_t dex_pc)
jeffhao09bfc6a2012-12-11 18:11:43 -0800213 LOCKS_EXCLUDED(Locks::breakpoint_lock_)
Ian Rogersb726dcb2012-09-05 08:57:23 -0700214 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
jeffhao09bfc6a2012-12-11 18:11:43 -0800215 MutexLock mu(Thread::Current(), *Locks::breakpoint_lock_);
Sebastien Hertz138dbfc2013-12-04 18:15:25 +0100216 for (size_t i = 0, e = gBreakpoints.size(); i < e; ++i) {
Elliott Hughesa656a0f2012-02-21 18:03:44 -0800217 if (gBreakpoints[i].method == m && gBreakpoints[i].dex_pc == dex_pc) {
Elliott Hughes86964332012-02-15 19:37:42 -0800218 VLOG(jdwp) << "Hit breakpoint #" << i << ": " << gBreakpoints[i];
219 return true;
220 }
221 }
222 return false;
223}
224
Elliott Hughes9e0c1752013-01-09 14:02:58 -0800225static bool IsSuspendedForDebugger(ScopedObjectAccessUnchecked& soa, Thread* thread) {
226 MutexLock mu(soa.Self(), *Locks::thread_suspend_count_lock_);
227 // A thread may be suspended for GC; in this code, we really want to know whether
228 // there's a debugger suspension active.
229 return thread->IsSuspended() && thread->GetDebugSuspendCount() > 0;
230}
231
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800232static mirror::Array* DecodeArray(JDWP::RefTypeId id, JDWP::JdwpError& status)
Ian Rogersb726dcb2012-09-05 08:57:23 -0700233 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800234 mirror::Object* o = gRegistry->Get<mirror::Object*>(id);
Elliott Hughes64f574f2013-02-20 14:57:12 -0800235 if (o == NULL || o == ObjectRegistry::kInvalidObject) {
Elliott Hughes436e3722012-02-17 20:01:47 -0800236 status = JDWP::ERR_INVALID_OBJECT;
237 return NULL;
238 }
239 if (!o->IsArrayInstance()) {
240 status = JDWP::ERR_INVALID_ARRAY;
241 return NULL;
242 }
243 status = JDWP::ERR_NONE;
244 return o->AsArray();
245}
246
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800247static mirror::Class* DecodeClass(JDWP::RefTypeId id, JDWP::JdwpError& status)
Ian Rogersb726dcb2012-09-05 08:57:23 -0700248 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800249 mirror::Object* o = gRegistry->Get<mirror::Object*>(id);
Elliott Hughes64f574f2013-02-20 14:57:12 -0800250 if (o == NULL || o == ObjectRegistry::kInvalidObject) {
Elliott Hughes436e3722012-02-17 20:01:47 -0800251 status = JDWP::ERR_INVALID_OBJECT;
252 return NULL;
253 }
254 if (!o->IsClass()) {
255 status = JDWP::ERR_INVALID_CLASS;
256 return NULL;
257 }
258 status = JDWP::ERR_NONE;
259 return o->AsClass();
260}
261
Elliott Hughes221229c2013-01-08 18:17:50 -0800262static JDWP::JdwpError DecodeThread(ScopedObjectAccessUnchecked& soa, JDWP::ObjectId thread_id, Thread*& thread)
jeffhaoa77f0f62012-12-05 17:19:31 -0800263 EXCLUSIVE_LOCKS_REQUIRED(Locks::thread_list_lock_)
Ian Rogersb726dcb2012-09-05 08:57:23 -0700264 LOCKS_EXCLUDED(Locks::thread_suspend_count_lock_)
265 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800266 mirror::Object* thread_peer = gRegistry->Get<mirror::Object*>(thread_id);
Elliott Hughes64f574f2013-02-20 14:57:12 -0800267 if (thread_peer == NULL || thread_peer == ObjectRegistry::kInvalidObject) {
Elliott Hughes221229c2013-01-08 18:17:50 -0800268 // This isn't even an object.
269 return JDWP::ERR_INVALID_OBJECT;
Elliott Hughes436e3722012-02-17 20:01:47 -0800270 }
Elliott Hughes221229c2013-01-08 18:17:50 -0800271
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800272 mirror::Class* java_lang_Thread = soa.Decode<mirror::Class*>(WellKnownClasses::java_lang_Thread);
Elliott Hughes221229c2013-01-08 18:17:50 -0800273 if (!java_lang_Thread->IsAssignableFrom(thread_peer->GetClass())) {
274 // This isn't a thread.
275 return JDWP::ERR_INVALID_THREAD;
276 }
277
278 thread = Thread::FromManagedThread(soa, thread_peer);
279 if (thread == NULL) {
280 // This is a java.lang.Thread without a Thread*. Must be a zombie.
281 return JDWP::ERR_THREAD_NOT_ALIVE;
282 }
283 return JDWP::ERR_NONE;
Elliott Hughes436e3722012-02-17 20:01:47 -0800284}
285
Elliott Hughes24437992011-11-30 14:49:33 -0800286static JDWP::JdwpTag BasicTagFromDescriptor(const char* descriptor) {
287 // JDWP deliberately uses the descriptor characters' ASCII values for its enum.
288 // Note that by "basic" we mean that we don't get more specific than JT_OBJECT.
289 return static_cast<JDWP::JdwpTag>(descriptor[0]);
290}
291
Ian Rogers98379392014-02-24 16:53:16 -0800292static JDWP::JdwpTag TagFromClass(const ScopedObjectAccessUnchecked& soa, mirror::Class* c)
Ian Rogersb726dcb2012-09-05 08:57:23 -0700293 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Elliott Hughes86b00102011-12-05 17:54:26 -0800294 CHECK(c != NULL);
Elliott Hughes24437992011-11-30 14:49:33 -0800295 if (c->IsArrayClass()) {
296 return JDWP::JT_ARRAY;
297 }
Elliott Hughes24437992011-11-30 14:49:33 -0800298 if (c->IsStringClass()) {
299 return JDWP::JT_STRING;
Elliott Hughes24437992011-11-30 14:49:33 -0800300 }
Ian Rogers98379392014-02-24 16:53:16 -0800301 if (c->IsClassClass()) {
302 return JDWP::JT_CLASS_OBJECT;
303 }
304 {
305 mirror::Class* thread_class = soa.Decode<mirror::Class*>(WellKnownClasses::java_lang_Thread);
306 if (thread_class->IsAssignableFrom(c)) {
307 return JDWP::JT_THREAD;
308 }
309 }
310 {
311 mirror::Class* thread_group_class =
312 soa.Decode<mirror::Class*>(WellKnownClasses::java_lang_ThreadGroup);
313 if (thread_group_class->IsAssignableFrom(c)) {
314 return JDWP::JT_THREAD_GROUP;
315 }
316 }
317 {
318 mirror::Class* class_loader_class =
319 soa.Decode<mirror::Class*>(WellKnownClasses::java_lang_ClassLoader);
320 if (class_loader_class->IsAssignableFrom(c)) {
321 return JDWP::JT_CLASS_LOADER;
322 }
323 }
324 return JDWP::JT_OBJECT;
Elliott Hughes24437992011-11-30 14:49:33 -0800325}
326
327/*
328 * Objects declared to hold Object might actually hold a more specific
329 * type. The debugger may take a special interest in these (e.g. it
330 * wants to display the contents of Strings), so we want to return an
331 * appropriate tag.
332 *
333 * Null objects are tagged JT_OBJECT.
334 */
Ian Rogers98379392014-02-24 16:53:16 -0800335static JDWP::JdwpTag TagFromObject(const ScopedObjectAccessUnchecked& soa, mirror::Object* o)
Ian Rogersb726dcb2012-09-05 08:57:23 -0700336 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Ian Rogers98379392014-02-24 16:53:16 -0800337 return (o == NULL) ? JDWP::JT_OBJECT : TagFromClass(soa, o->GetClass());
Elliott Hughes24437992011-11-30 14:49:33 -0800338}
339
340static bool IsPrimitiveTag(JDWP::JdwpTag tag) {
341 switch (tag) {
342 case JDWP::JT_BOOLEAN:
343 case JDWP::JT_BYTE:
344 case JDWP::JT_CHAR:
345 case JDWP::JT_FLOAT:
346 case JDWP::JT_DOUBLE:
347 case JDWP::JT_INT:
348 case JDWP::JT_LONG:
349 case JDWP::JT_SHORT:
350 case JDWP::JT_VOID:
351 return true;
352 default:
353 return false;
354 }
355}
356
Elliott Hughes3bb81562011-10-21 18:52:59 -0700357/*
358 * Handle one of the JDWP name/value pairs.
359 *
360 * JDWP options are:
361 * help: if specified, show help message and bail
362 * transport: may be dt_socket or dt_shmem
363 * address: for dt_socket, "host:port", or just "port" when listening
364 * server: if "y", wait for debugger to attach; if "n", attach to debugger
365 * timeout: how long to wait for debugger to connect / listen
366 *
367 * Useful with server=n (these aren't supported yet):
368 * onthrow=<exception-name>: connect to debugger when exception thrown
369 * onuncaught=y|n: connect to debugger when uncaught exception thrown
370 * launch=<command-line>: launch the debugger itself
371 *
372 * The "transport" option is required, as is "address" if server=n.
373 */
374static bool ParseJdwpOption(const std::string& name, const std::string& value) {
375 if (name == "transport") {
376 if (value == "dt_socket") {
Elliott Hughes376a7a02011-10-24 18:35:55 -0700377 gJdwpOptions.transport = JDWP::kJdwpTransportSocket;
Elliott Hughes3bb81562011-10-21 18:52:59 -0700378 } else if (value == "dt_android_adb") {
Elliott Hughes376a7a02011-10-24 18:35:55 -0700379 gJdwpOptions.transport = JDWP::kJdwpTransportAndroidAdb;
Elliott Hughes3bb81562011-10-21 18:52:59 -0700380 } else {
381 LOG(ERROR) << "JDWP transport not supported: " << value;
382 return false;
383 }
384 } else if (name == "server") {
385 if (value == "n") {
Elliott Hughes376a7a02011-10-24 18:35:55 -0700386 gJdwpOptions.server = false;
Elliott Hughes3bb81562011-10-21 18:52:59 -0700387 } else if (value == "y") {
Elliott Hughes376a7a02011-10-24 18:35:55 -0700388 gJdwpOptions.server = true;
Elliott Hughes3bb81562011-10-21 18:52:59 -0700389 } else {
390 LOG(ERROR) << "JDWP option 'server' must be 'y' or 'n'";
391 return false;
392 }
393 } else if (name == "suspend") {
394 if (value == "n") {
Elliott Hughes376a7a02011-10-24 18:35:55 -0700395 gJdwpOptions.suspend = false;
Elliott Hughes3bb81562011-10-21 18:52:59 -0700396 } else if (value == "y") {
Elliott Hughes376a7a02011-10-24 18:35:55 -0700397 gJdwpOptions.suspend = true;
Elliott Hughes3bb81562011-10-21 18:52:59 -0700398 } else {
399 LOG(ERROR) << "JDWP option 'suspend' must be 'y' or 'n'";
400 return false;
401 }
402 } else if (name == "address") {
403 /* this is either <port> or <host>:<port> */
404 std::string port_string;
Elliott Hughes376a7a02011-10-24 18:35:55 -0700405 gJdwpOptions.host.clear();
Elliott Hughes3bb81562011-10-21 18:52:59 -0700406 std::string::size_type colon = value.find(':');
407 if (colon != std::string::npos) {
Elliott Hughes376a7a02011-10-24 18:35:55 -0700408 gJdwpOptions.host = value.substr(0, colon);
Elliott Hughes3bb81562011-10-21 18:52:59 -0700409 port_string = value.substr(colon + 1);
410 } else {
411 port_string = value;
412 }
413 if (port_string.empty()) {
414 LOG(ERROR) << "JDWP address missing port: " << value;
415 return false;
416 }
417 char* end;
Elliott Hughesba8eee12012-01-24 20:25:24 -0800418 uint64_t port = strtoul(port_string.c_str(), &end, 10);
419 if (*end != '\0' || port > 0xffff) {
Elliott Hughes3bb81562011-10-21 18:52:59 -0700420 LOG(ERROR) << "JDWP address has junk in port field: " << value;
421 return false;
422 }
Elliott Hughes376a7a02011-10-24 18:35:55 -0700423 gJdwpOptions.port = port;
Elliott Hughes3bb81562011-10-21 18:52:59 -0700424 } else if (name == "launch" || name == "onthrow" || name == "oncaught" || name == "timeout") {
425 /* valid but unsupported */
426 LOG(INFO) << "Ignoring JDWP option '" << name << "'='" << value << "'";
427 } else {
428 LOG(INFO) << "Ignoring unrecognized JDWP option '" << name << "'='" << value << "'";
429 }
430
431 return true;
432}
433
434/*
435 * Parse the latter half of a -Xrunjdwp/-agentlib:jdwp= string, e.g.:
436 * "transport=dt_socket,address=8000,server=y,suspend=n"
437 */
438bool Dbg::ParseJdwpOptions(const std::string& options) {
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -0800439 VLOG(jdwp) << "ParseJdwpOptions: " << options;
Elliott Hughes47fce012011-10-25 18:37:19 -0700440
Elliott Hughes3bb81562011-10-21 18:52:59 -0700441 std::vector<std::string> pairs;
442 Split(options, ',', pairs);
443
444 for (size_t i = 0; i < pairs.size(); ++i) {
445 std::string::size_type equals = pairs[i].find('=');
446 if (equals == std::string::npos) {
447 LOG(ERROR) << "Can't parse JDWP option '" << pairs[i] << "' in '" << options << "'";
448 return false;
449 }
450 ParseJdwpOption(pairs[i].substr(0, equals), pairs[i].substr(equals + 1));
451 }
452
Elliott Hughes376a7a02011-10-24 18:35:55 -0700453 if (gJdwpOptions.transport == JDWP::kJdwpTransportUnknown) {
Elliott Hughes3bb81562011-10-21 18:52:59 -0700454 LOG(ERROR) << "Must specify JDWP transport: " << options;
455 }
Elliott Hughes376a7a02011-10-24 18:35:55 -0700456 if (!gJdwpOptions.server && (gJdwpOptions.host.empty() || gJdwpOptions.port == 0)) {
Elliott Hughes3bb81562011-10-21 18:52:59 -0700457 LOG(ERROR) << "Must specify JDWP host and port when server=n: " << options;
458 return false;
459 }
460
461 gJdwpConfigured = true;
462 return true;
463}
464
Elliott Hughesd1cc8362011-10-24 16:58:50 -0700465void Dbg::StartJdwp() {
Elliott Hughesc0f09332012-03-26 13:27:06 -0700466 if (!gJdwpAllowed || !IsJdwpConfigured()) {
Elliott Hughes376a7a02011-10-24 18:35:55 -0700467 // No JDWP for you!
468 return;
469 }
470
Elliott Hughes475fc232011-10-25 15:00:35 -0700471 CHECK(gRegistry == NULL);
472 gRegistry = new ObjectRegistry;
473
Elliott Hughesd1cc8362011-10-24 16:58:50 -0700474 // Init JDWP if the debugger is enabled. This may connect out to a
475 // debugger, passively listen for a debugger, or block waiting for a
476 // debugger.
Elliott Hughes376a7a02011-10-24 18:35:55 -0700477 gJdwpState = JDWP::JdwpState::Create(&gJdwpOptions);
478 if (gJdwpState == NULL) {
Elliott Hughesf8a2df72011-12-01 12:19:54 -0800479 // We probably failed because some other process has the port already, which means that
480 // if we don't abort the user is likely to think they're talking to us when they're actually
481 // talking to that other process.
Elliott Hughes3d30d9b2011-12-07 17:35:48 -0800482 LOG(FATAL) << "Debugger thread failed to initialize";
Elliott Hughesd1cc8362011-10-24 16:58:50 -0700483 }
484
485 // If a debugger has already attached, send the "welcome" message.
486 // This may cause us to suspend all threads.
Elliott Hughes376a7a02011-10-24 18:35:55 -0700487 if (gJdwpState->IsActive()) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700488 ScopedObjectAccess soa(Thread::Current());
Elliott Hughes376a7a02011-10-24 18:35:55 -0700489 if (!gJdwpState->PostVMStart()) {
Elliott Hughes3d30d9b2011-12-07 17:35:48 -0800490 LOG(WARNING) << "Failed to post 'start' message to debugger";
Elliott Hughesd1cc8362011-10-24 16:58:50 -0700491 }
492 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700493}
494
Elliott Hughesd1cc8362011-10-24 16:58:50 -0700495void Dbg::StopJdwp() {
Sebastien Hertz0376e6b2014-02-06 18:12:59 +0100496 // Prevent the JDWP thread from processing JDWP incoming packets after we close the connection.
497 Disposed();
Elliott Hughes376a7a02011-10-24 18:35:55 -0700498 delete gJdwpState;
Sebastien Hertz123756a2013-11-27 15:49:42 +0100499 gJdwpState = NULL;
Elliott Hughes475fc232011-10-25 15:00:35 -0700500 delete gRegistry;
501 gRegistry = NULL;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700502}
503
Elliott Hughes767a1472011-10-26 18:49:02 -0700504void Dbg::GcDidFinish() {
505 if (gDdmHpifWhen != HPIF_WHEN_NEVER) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700506 ScopedObjectAccess soa(Thread::Current());
Elliott Hughes81ff3182012-03-23 20:35:56 -0700507 LOG(DEBUG) << "Sending heap info to DDM";
Elliott Hughes7162ad92011-10-27 14:08:42 -0700508 DdmSendHeapInfo(gDdmHpifWhen);
Elliott Hughes767a1472011-10-26 18:49:02 -0700509 }
510 if (gDdmHpsgWhen != HPSG_WHEN_NEVER) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700511 ScopedObjectAccess soa(Thread::Current());
Elliott Hughes81ff3182012-03-23 20:35:56 -0700512 LOG(DEBUG) << "Dumping heap to DDM";
Elliott Hughes6a5bd492011-10-28 14:33:57 -0700513 DdmSendHeapSegments(false);
Elliott Hughes767a1472011-10-26 18:49:02 -0700514 }
515 if (gDdmNhsgWhen != HPSG_WHEN_NEVER) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700516 ScopedObjectAccess soa(Thread::Current());
Elliott Hughes767a1472011-10-26 18:49:02 -0700517 LOG(DEBUG) << "Dumping native heap to DDM";
Elliott Hughes6a5bd492011-10-28 14:33:57 -0700518 DdmSendHeapSegments(true);
Elliott Hughes767a1472011-10-26 18:49:02 -0700519 }
520}
521
Elliott Hughes4ffd3132011-10-24 12:06:42 -0700522void Dbg::SetJdwpAllowed(bool allowed) {
523 gJdwpAllowed = allowed;
524}
525
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700526DebugInvokeReq* Dbg::GetInvokeReq() {
Elliott Hughes475fc232011-10-25 15:00:35 -0700527 return Thread::Current()->GetInvokeReq();
528}
529
530Thread* Dbg::GetDebugThread() {
531 return (gJdwpState != NULL) ? gJdwpState->GetDebugThread() : NULL;
532}
533
534void Dbg::ClearWaitForEventThread() {
535 gJdwpState->ClearWaitForEventThread();
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700536}
537
538void Dbg::Connected() {
Elliott Hughes3bb81562011-10-21 18:52:59 -0700539 CHECK(!gDebuggerConnected);
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -0800540 VLOG(jdwp) << "JDWP has attached";
Elliott Hughes3bb81562011-10-21 18:52:59 -0700541 gDebuggerConnected = true;
Elliott Hughes86964332012-02-15 19:37:42 -0800542 gDisposed = false;
543}
544
545void Dbg::Disposed() {
546 gDisposed = true;
547}
548
549bool Dbg::IsDisposed() {
550 return gDisposed;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700551}
552
Elliott Hughesa2155262011-11-16 16:26:58 -0800553void Dbg::GoActive() {
554 // Enable all debugging features, including scans for breakpoints.
555 // This is a no-op if we're already active.
556 // Only called from the JDWP handler thread.
557 if (gDebuggerActive) {
558 return;
559 }
560
Elliott Hughesc0f09332012-03-26 13:27:06 -0700561 {
562 // TODO: dalvik only warned if there were breakpoints left over. clear in Dbg::Disconnected?
jeffhao09bfc6a2012-12-11 18:11:43 -0800563 MutexLock mu(Thread::Current(), *Locks::breakpoint_lock_);
Elliott Hughesc0f09332012-03-26 13:27:06 -0700564 CHECK_EQ(gBreakpoints.size(), 0U);
565 }
Elliott Hughesa2155262011-11-16 16:26:58 -0800566
Sebastien Hertz138dbfc2013-12-04 18:15:25 +0100567 {
568 MutexLock mu(Thread::Current(), *Locks::deoptimization_lock_);
569 CHECK_EQ(gDeoptimizationRequests.size(), 0U);
570 }
571
Ian Rogers62d6c772013-02-27 08:32:07 -0800572 Runtime* runtime = Runtime::Current();
573 runtime->GetThreadList()->SuspendAll();
574 Thread* self = Thread::Current();
575 ThreadState old_state = self->SetStateUnsafe(kRunnable);
576 CHECK_NE(old_state, kRunnable);
Sebastien Hertz138dbfc2013-12-04 18:15:25 +0100577 runtime->GetInstrumentation()->EnableDeoptimization();
Ian Rogers62d6c772013-02-27 08:32:07 -0800578 runtime->GetInstrumentation()->AddListener(&gDebugInstrumentationListener,
579 instrumentation::Instrumentation::kMethodEntered |
580 instrumentation::Instrumentation::kMethodExited |
Jeff Hao14dd5a82013-04-11 10:23:36 -0700581 instrumentation::Instrumentation::kDexPcMoved |
582 instrumentation::Instrumentation::kExceptionCaught);
Elliott Hughesa2155262011-11-16 16:26:58 -0800583 gDebuggerActive = true;
Ian Rogers62d6c772013-02-27 08:32:07 -0800584 CHECK_EQ(self->SetStateUnsafe(old_state), kRunnable);
585 runtime->GetThreadList()->ResumeAll();
586
587 LOG(INFO) << "Debugger is active";
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700588}
589
590void Dbg::Disconnected() {
Elliott Hughes234ab152011-10-26 14:02:26 -0700591 CHECK(gDebuggerConnected);
592
Elliott Hughesc0f09332012-03-26 13:27:06 -0700593 LOG(INFO) << "Debugger is no longer active";
Elliott Hughes234ab152011-10-26 14:02:26 -0700594
Ian Rogers62d6c772013-02-27 08:32:07 -0800595 // Suspend all threads and exclusively acquire the mutator lock. Set the state of the thread
596 // to kRunnable to avoid scoped object access transitions. Remove the debugger as a listener
597 // and clear the object registry.
598 Runtime* runtime = Runtime::Current();
599 runtime->GetThreadList()->SuspendAll();
600 Thread* self = Thread::Current();
601 ThreadState old_state = self->SetStateUnsafe(kRunnable);
Sebastien Hertz138dbfc2013-12-04 18:15:25 +0100602 {
603 // Since we're going to disable deoptimization, we clear the deoptimization requests queue.
604 // This prevent us from having any pending deoptimization request when the debugger attaches to
605 // us again while no event has been requested yet.
606 MutexLock mu(Thread::Current(), *Locks::deoptimization_lock_);
607 gDeoptimizationRequests.clear();
608 }
Ian Rogers62d6c772013-02-27 08:32:07 -0800609 runtime->GetInstrumentation()->RemoveListener(&gDebugInstrumentationListener,
610 instrumentation::Instrumentation::kMethodEntered |
611 instrumentation::Instrumentation::kMethodExited |
Jeff Hao14dd5a82013-04-11 10:23:36 -0700612 instrumentation::Instrumentation::kDexPcMoved |
613 instrumentation::Instrumentation::kExceptionCaught);
Sebastien Hertz11d40c22014-02-19 18:00:17 +0100614 runtime->GetInstrumentation()->DisableDeoptimization();
Elliott Hughesc0f09332012-03-26 13:27:06 -0700615 gDebuggerActive = false;
Elliott Hughes234ab152011-10-26 14:02:26 -0700616 gRegistry->Clear();
617 gDebuggerConnected = false;
Ian Rogers62d6c772013-02-27 08:32:07 -0800618 CHECK_EQ(self->SetStateUnsafe(old_state), kRunnable);
619 runtime->GetThreadList()->ResumeAll();
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700620}
621
Elliott Hughesc0f09332012-03-26 13:27:06 -0700622bool Dbg::IsDebuggerActive() {
Elliott Hughes3bb81562011-10-21 18:52:59 -0700623 return gDebuggerActive;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700624}
625
Elliott Hughesc0f09332012-03-26 13:27:06 -0700626bool Dbg::IsJdwpConfigured() {
Elliott Hughes3bb81562011-10-21 18:52:59 -0700627 return gJdwpConfigured;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700628}
629
630int64_t Dbg::LastDebuggerActivity() {
Elliott Hughesca951522011-12-05 12:01:32 -0800631 return gJdwpState->LastDebuggerActivity();
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700632}
633
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700634void Dbg::UndoDebuggerSuspensions() {
Elliott Hughes234ab152011-10-26 14:02:26 -0700635 Runtime::Current()->GetThreadList()->UndoDebuggerSuspensions();
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700636}
637
Elliott Hughes88d63092013-01-09 09:55:54 -0800638std::string Dbg::GetClassName(JDWP::RefTypeId class_id) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800639 mirror::Object* o = gRegistry->Get<mirror::Object*>(class_id);
Elliott Hughes436e3722012-02-17 20:01:47 -0800640 if (o == NULL) {
641 return "NULL";
642 }
Elliott Hughes64f574f2013-02-20 14:57:12 -0800643 if (o == ObjectRegistry::kInvalidObject) {
Elliott Hughes88d63092013-01-09 09:55:54 -0800644 return StringPrintf("invalid object %p", reinterpret_cast<void*>(class_id));
Elliott Hughes436e3722012-02-17 20:01:47 -0800645 }
646 if (!o->IsClass()) {
Brian Carlstrom7934ac22013-07-26 10:54:15 -0700647 return StringPrintf("non-class %p", o); // This is only used for debugging output anyway.
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -0800648 }
Elliott Hughesc308a5d2012-02-16 17:12:06 -0800649 return DescriptorToName(ClassHelper(o->AsClass()).GetDescriptor());
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700650}
651
Elliott Hughes88d63092013-01-09 09:55:54 -0800652JDWP::JdwpError Dbg::GetClassObject(JDWP::RefTypeId id, JDWP::ObjectId& class_object_id) {
Elliott Hughes436e3722012-02-17 20:01:47 -0800653 JDWP::JdwpError status;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800654 mirror::Class* c = DecodeClass(id, status);
Elliott Hughes436e3722012-02-17 20:01:47 -0800655 if (c == NULL) {
656 return status;
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -0800657 }
Elliott Hughes88d63092013-01-09 09:55:54 -0800658 class_object_id = gRegistry->Add(c);
Elliott Hughes436e3722012-02-17 20:01:47 -0800659 return JDWP::ERR_NONE;
Elliott Hughes86964332012-02-15 19:37:42 -0800660}
661
Elliott Hughes88d63092013-01-09 09:55:54 -0800662JDWP::JdwpError Dbg::GetSuperclass(JDWP::RefTypeId id, JDWP::RefTypeId& superclass_id) {
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -0800663 JDWP::JdwpError status;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800664 mirror::Class* c = DecodeClass(id, status);
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -0800665 if (c == NULL) {
666 return status;
667 }
668 if (c->IsInterface()) {
669 // http://code.google.com/p/android/issues/detail?id=20856
Elliott Hughes88d63092013-01-09 09:55:54 -0800670 superclass_id = 0;
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -0800671 } else {
Elliott Hughes88d63092013-01-09 09:55:54 -0800672 superclass_id = gRegistry->Add(c->GetSuperClass());
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -0800673 }
674 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700675}
676
Elliott Hughes436e3722012-02-17 20:01:47 -0800677JDWP::JdwpError Dbg::GetClassLoader(JDWP::RefTypeId id, JDWP::ExpandBuf* pReply) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800678 mirror::Object* o = gRegistry->Get<mirror::Object*>(id);
Elliott Hughes64f574f2013-02-20 14:57:12 -0800679 if (o == NULL || o == ObjectRegistry::kInvalidObject) {
Elliott Hughes436e3722012-02-17 20:01:47 -0800680 return JDWP::ERR_INVALID_OBJECT;
681 }
682 expandBufAddObjectId(pReply, gRegistry->Add(o->GetClass()->GetClassLoader()));
683 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700684}
685
Elliott Hughes436e3722012-02-17 20:01:47 -0800686JDWP::JdwpError Dbg::GetModifiers(JDWP::RefTypeId id, JDWP::ExpandBuf* pReply) {
687 JDWP::JdwpError status;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800688 mirror::Class* c = DecodeClass(id, status);
Elliott Hughes436e3722012-02-17 20:01:47 -0800689 if (c == NULL) {
690 return status;
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -0800691 }
Elliott Hughes436e3722012-02-17 20:01:47 -0800692
693 uint32_t access_flags = c->GetAccessFlags() & kAccJavaFlagsMask;
694
Yevgeny Roubande34eea2014-02-15 01:06:03 +0700695 // Set ACC_SUPER. Dex files don't contain this flag but only classes are supposed to have it set,
696 // not interfaces.
Elliott Hughes436e3722012-02-17 20:01:47 -0800697 // Class.getModifiers doesn't return it, but JDWP does, so we set it here.
Yevgeny Roubande34eea2014-02-15 01:06:03 +0700698 if ((access_flags & kAccInterface) == 0) {
699 access_flags |= kAccSuper;
700 }
Elliott Hughes436e3722012-02-17 20:01:47 -0800701
702 expandBufAdd4BE(pReply, access_flags);
703
704 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700705}
706
Elliott Hughesf327e072013-01-09 16:01:26 -0800707JDWP::JdwpError Dbg::GetMonitorInfo(JDWP::ObjectId object_id, JDWP::ExpandBuf* reply)
708 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800709 mirror::Object* o = gRegistry->Get<mirror::Object*>(object_id);
Elliott Hughes64f574f2013-02-20 14:57:12 -0800710 if (o == NULL || o == ObjectRegistry::kInvalidObject) {
Elliott Hughesf327e072013-01-09 16:01:26 -0800711 return JDWP::ERR_INVALID_OBJECT;
712 }
713
714 // Ensure all threads are suspended while we read objects' lock words.
715 Thread* self = Thread::Current();
716 Locks::mutator_lock_->SharedUnlock(self);
717 Locks::mutator_lock_->ExclusiveLock(self);
718
719 MonitorInfo monitor_info(o);
720
721 Locks::mutator_lock_->ExclusiveUnlock(self);
722 Locks::mutator_lock_->SharedLock(self);
723
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700724 if (monitor_info.owner_ != NULL) {
725 expandBufAddObjectId(reply, gRegistry->Add(monitor_info.owner_->GetPeer()));
Elliott Hughesf327e072013-01-09 16:01:26 -0800726 } else {
727 expandBufAddObjectId(reply, gRegistry->Add(NULL));
728 }
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700729 expandBufAdd4BE(reply, monitor_info.entry_count_);
730 expandBufAdd4BE(reply, monitor_info.waiters_.size());
731 for (size_t i = 0; i < monitor_info.waiters_.size(); ++i) {
732 expandBufAddObjectId(reply, gRegistry->Add(monitor_info.waiters_[i]->GetPeer()));
Elliott Hughesf327e072013-01-09 16:01:26 -0800733 }
734 return JDWP::ERR_NONE;
735}
736
Elliott Hughes734b8c62013-01-11 15:32:45 -0800737JDWP::JdwpError Dbg::GetOwnedMonitors(JDWP::ObjectId thread_id,
738 std::vector<JDWP::ObjectId>& monitors,
739 std::vector<uint32_t>& stack_depths)
Elliott Hughes4993bbc2013-01-10 15:41:25 -0800740 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
741 ScopedObjectAccessUnchecked soa(Thread::Current());
742 MutexLock mu(soa.Self(), *Locks::thread_list_lock_);
743 Thread* thread;
744 JDWP::JdwpError error = DecodeThread(soa, thread_id, thread);
745 if (error != JDWP::ERR_NONE) {
746 return error;
747 }
748 if (!IsSuspendedForDebugger(soa, thread)) {
749 return JDWP::ERR_THREAD_NOT_SUSPENDED;
750 }
751
752 struct OwnedMonitorVisitor : public StackVisitor {
Ian Rogers7a22fa62013-01-23 12:16:16 -0800753 OwnedMonitorVisitor(Thread* thread, Context* context)
Elliott Hughes4993bbc2013-01-10 15:41:25 -0800754 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_)
Ian Rogers7a22fa62013-01-23 12:16:16 -0800755 : StackVisitor(thread, context), current_stack_depth(0) {}
Elliott Hughes4993bbc2013-01-10 15:41:25 -0800756
757 // TODO: Enable annotalysis. We know lock is held in constructor, but abstraction confuses
758 // annotalysis.
759 bool VisitFrame() NO_THREAD_SAFETY_ANALYSIS {
760 if (!GetMethod()->IsRuntimeMethod()) {
761 Monitor::VisitLocks(this, AppendOwnedMonitors, this);
Elliott Hughes734b8c62013-01-11 15:32:45 -0800762 ++current_stack_depth;
Elliott Hughes4993bbc2013-01-10 15:41:25 -0800763 }
764 return true;
765 }
766
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800767 static void AppendOwnedMonitors(mirror::Object* owned_monitor, void* arg) {
Ian Rogers7a22fa62013-01-23 12:16:16 -0800768 OwnedMonitorVisitor* visitor = reinterpret_cast<OwnedMonitorVisitor*>(arg);
Elliott Hughes734b8c62013-01-11 15:32:45 -0800769 visitor->monitors.push_back(owned_monitor);
770 visitor->stack_depths.push_back(visitor->current_stack_depth);
Elliott Hughes4993bbc2013-01-10 15:41:25 -0800771 }
772
Elliott Hughes734b8c62013-01-11 15:32:45 -0800773 size_t current_stack_depth;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800774 std::vector<mirror::Object*> monitors;
Elliott Hughes734b8c62013-01-11 15:32:45 -0800775 std::vector<uint32_t> stack_depths;
Elliott Hughes4993bbc2013-01-10 15:41:25 -0800776 };
Ian Rogers7a22fa62013-01-23 12:16:16 -0800777 UniquePtr<Context> context(Context::Create());
778 OwnedMonitorVisitor visitor(thread, context.get());
Elliott Hughes4993bbc2013-01-10 15:41:25 -0800779 visitor.WalkStack();
780
781 for (size_t i = 0; i < visitor.monitors.size(); ++i) {
782 monitors.push_back(gRegistry->Add(visitor.monitors[i]));
Elliott Hughes734b8c62013-01-11 15:32:45 -0800783 stack_depths.push_back(visitor.stack_depths[i]);
Elliott Hughes4993bbc2013-01-10 15:41:25 -0800784 }
785
786 return JDWP::ERR_NONE;
787}
788
Elliott Hughesf9501702013-01-11 11:22:27 -0800789JDWP::JdwpError Dbg::GetContendedMonitor(JDWP::ObjectId thread_id, JDWP::ObjectId& contended_monitor)
790 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
791 ScopedObjectAccessUnchecked soa(Thread::Current());
792 MutexLock mu(soa.Self(), *Locks::thread_list_lock_);
793 Thread* thread;
794 JDWP::JdwpError error = DecodeThread(soa, thread_id, thread);
795 if (error != JDWP::ERR_NONE) {
796 return error;
797 }
798 if (!IsSuspendedForDebugger(soa, thread)) {
799 return JDWP::ERR_THREAD_NOT_SUSPENDED;
800 }
801
802 contended_monitor = gRegistry->Add(Monitor::GetContendedMonitor(thread));
803
804 return JDWP::ERR_NONE;
805}
806
Elliott Hughesec0f83d2013-01-15 16:54:08 -0800807JDWP::JdwpError Dbg::GetInstanceCounts(const std::vector<JDWP::RefTypeId>& class_ids,
808 std::vector<uint64_t>& counts)
809 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Mathieu Chartier412c7fc2014-02-07 12:18:39 -0800810 gc::Heap* heap = Runtime::Current()->GetHeap();
811 heap->CollectGarbage(false);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800812 std::vector<mirror::Class*> classes;
Elliott Hughesec0f83d2013-01-15 16:54:08 -0800813 counts.clear();
814 for (size_t i = 0; i < class_ids.size(); ++i) {
815 JDWP::JdwpError status;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800816 mirror::Class* c = DecodeClass(class_ids[i], status);
Elliott Hughesec0f83d2013-01-15 16:54:08 -0800817 if (c == NULL) {
818 return status;
819 }
820 classes.push_back(c);
821 counts.push_back(0);
822 }
Mathieu Chartier412c7fc2014-02-07 12:18:39 -0800823 heap->CountInstances(classes, false, &counts[0]);
Elliott Hughesec0f83d2013-01-15 16:54:08 -0800824 return JDWP::ERR_NONE;
825}
826
Elliott Hughes3b78c942013-01-15 17:35:41 -0800827JDWP::JdwpError Dbg::GetInstances(JDWP::RefTypeId class_id, int32_t max_count, std::vector<JDWP::ObjectId>& instances)
828 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Mathieu Chartier412c7fc2014-02-07 12:18:39 -0800829 gc::Heap* heap = Runtime::Current()->GetHeap();
830 // We only want reachable instances, so do a GC.
831 heap->CollectGarbage(false);
Elliott Hughes3b78c942013-01-15 17:35:41 -0800832 JDWP::JdwpError status;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800833 mirror::Class* c = DecodeClass(class_id, status);
Mathieu Chartier412c7fc2014-02-07 12:18:39 -0800834 if (c == nullptr) {
Elliott Hughes3b78c942013-01-15 17:35:41 -0800835 return status;
836 }
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800837 std::vector<mirror::Object*> raw_instances;
Elliott Hughes3b78c942013-01-15 17:35:41 -0800838 Runtime::Current()->GetHeap()->GetInstances(c, max_count, raw_instances);
839 for (size_t i = 0; i < raw_instances.size(); ++i) {
840 instances.push_back(gRegistry->Add(raw_instances[i]));
841 }
842 return JDWP::ERR_NONE;
843}
844
Elliott Hughes0cbaff52013-01-16 15:28:01 -0800845JDWP::JdwpError Dbg::GetReferringObjects(JDWP::ObjectId object_id, int32_t max_count,
846 std::vector<JDWP::ObjectId>& referring_objects)
847 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Mathieu Chartier412c7fc2014-02-07 12:18:39 -0800848 gc::Heap* heap = Runtime::Current()->GetHeap();
849 heap->CollectGarbage(false);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800850 mirror::Object* o = gRegistry->Get<mirror::Object*>(object_id);
Elliott Hughes64f574f2013-02-20 14:57:12 -0800851 if (o == NULL || o == ObjectRegistry::kInvalidObject) {
Elliott Hughes0cbaff52013-01-16 15:28:01 -0800852 return JDWP::ERR_INVALID_OBJECT;
853 }
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800854 std::vector<mirror::Object*> raw_instances;
Mathieu Chartier412c7fc2014-02-07 12:18:39 -0800855 heap->GetReferringObjects(o, max_count, raw_instances);
Elliott Hughes0cbaff52013-01-16 15:28:01 -0800856 for (size_t i = 0; i < raw_instances.size(); ++i) {
857 referring_objects.push_back(gRegistry->Add(raw_instances[i]));
858 }
859 return JDWP::ERR_NONE;
860}
861
Elliott Hughes64f574f2013-02-20 14:57:12 -0800862JDWP::JdwpError Dbg::DisableCollection(JDWP::ObjectId object_id)
863 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Sebastien Hertze96060a2013-12-11 12:06:28 +0100864 mirror::Object* o = gRegistry->Get<mirror::Object*>(object_id);
865 if (o == NULL || o == ObjectRegistry::kInvalidObject) {
866 return JDWP::ERR_INVALID_OBJECT;
867 }
Elliott Hughes64f574f2013-02-20 14:57:12 -0800868 gRegistry->DisableCollection(object_id);
869 return JDWP::ERR_NONE;
870}
871
872JDWP::JdwpError Dbg::EnableCollection(JDWP::ObjectId object_id)
873 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Sebastien Hertze96060a2013-12-11 12:06:28 +0100874 mirror::Object* o = gRegistry->Get<mirror::Object*>(object_id);
875 // Unlike DisableCollection, JDWP specs do not state an invalid object causes an error. The RI
876 // also ignores these cases and never return an error. However it's not obvious why this command
877 // should behave differently from DisableCollection and IsCollected commands. So let's be more
878 // strict and return an error if this happens.
879 if (o == NULL || o == ObjectRegistry::kInvalidObject) {
880 return JDWP::ERR_INVALID_OBJECT;
881 }
Elliott Hughes64f574f2013-02-20 14:57:12 -0800882 gRegistry->EnableCollection(object_id);
883 return JDWP::ERR_NONE;
884}
885
886JDWP::JdwpError Dbg::IsCollected(JDWP::ObjectId object_id, bool& is_collected)
887 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Sebastien Hertz65637eb2014-01-10 17:40:02 +0100888 if (object_id == 0) {
889 // Null object id is invalid.
Sebastien Hertze96060a2013-12-11 12:06:28 +0100890 return JDWP::ERR_INVALID_OBJECT;
891 }
Sebastien Hertz65637eb2014-01-10 17:40:02 +0100892 // JDWP specs state an INVALID_OBJECT error is returned if the object ID is not valid. However
893 // the RI seems to ignore this and assume object has been collected.
894 mirror::Object* o = gRegistry->Get<mirror::Object*>(object_id);
895 if (o == NULL || o == ObjectRegistry::kInvalidObject) {
896 is_collected = true;
897 } else {
898 is_collected = gRegistry->IsCollected(object_id);
899 }
Elliott Hughes64f574f2013-02-20 14:57:12 -0800900 return JDWP::ERR_NONE;
901}
902
903void Dbg::DisposeObject(JDWP::ObjectId object_id, uint32_t reference_count)
904 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
905 gRegistry->DisposeObject(object_id, reference_count);
906}
907
Elliott Hughes88d63092013-01-09 09:55:54 -0800908JDWP::JdwpError Dbg::GetReflectedType(JDWP::RefTypeId class_id, JDWP::ExpandBuf* pReply) {
Elliott Hughes436e3722012-02-17 20:01:47 -0800909 JDWP::JdwpError status;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800910 mirror::Class* c = DecodeClass(class_id, status);
Elliott Hughes436e3722012-02-17 20:01:47 -0800911 if (c == NULL) {
912 return status;
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -0800913 }
Elliott Hughes436e3722012-02-17 20:01:47 -0800914
915 expandBufAdd1(pReply, c->IsInterface() ? JDWP::TT_INTERFACE : JDWP::TT_CLASS);
Elliott Hughes88d63092013-01-09 09:55:54 -0800916 expandBufAddRefTypeId(pReply, class_id);
Elliott Hughes436e3722012-02-17 20:01:47 -0800917 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700918}
919
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -0800920void Dbg::GetClassList(std::vector<JDWP::RefTypeId>& classes) {
Elliott Hughesa2155262011-11-16 16:26:58 -0800921 // Get the complete list of reference classes (i.e. all classes except
922 // the primitive types).
923 // Returns a newly-allocated buffer full of RefTypeId values.
924 struct ClassListCreator {
Elliott Hughesba8eee12012-01-24 20:25:24 -0800925 explicit ClassListCreator(std::vector<JDWP::RefTypeId>& classes) : classes(classes) {
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -0800926 }
927
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800928 static bool Visit(mirror::Class* c, void* arg) {
Elliott Hughesa2155262011-11-16 16:26:58 -0800929 return reinterpret_cast<ClassListCreator*>(arg)->Visit(c);
930 }
931
Elliott Hughes64f574f2013-02-20 14:57:12 -0800932 // TODO: Enable annotalysis. We know lock is held in constructor, but abstraction confuses
933 // annotalysis.
934 bool Visit(mirror::Class* c) NO_THREAD_SAFETY_ANALYSIS {
Elliott Hughesa2155262011-11-16 16:26:58 -0800935 if (!c->IsPrimitive()) {
Elliott Hughes64f574f2013-02-20 14:57:12 -0800936 classes.push_back(gRegistry->AddRefType(c));
Elliott Hughesa2155262011-11-16 16:26:58 -0800937 }
938 return true;
939 }
940
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -0800941 std::vector<JDWP::RefTypeId>& classes;
Elliott Hughesa2155262011-11-16 16:26:58 -0800942 };
943
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -0800944 ClassListCreator clc(classes);
Elliott Hughesa2155262011-11-16 16:26:58 -0800945 Runtime::Current()->GetClassLinker()->VisitClasses(ClassListCreator::Visit, &clc);
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700946}
947
Elliott Hughes88d63092013-01-09 09:55:54 -0800948JDWP::JdwpError Dbg::GetClassInfo(JDWP::RefTypeId class_id, JDWP::JdwpTypeTag* pTypeTag, uint32_t* pStatus, std::string* pDescriptor) {
Elliott Hughes436e3722012-02-17 20:01:47 -0800949 JDWP::JdwpError status;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800950 mirror::Class* c = DecodeClass(class_id, status);
Elliott Hughes436e3722012-02-17 20:01:47 -0800951 if (c == NULL) {
952 return status;
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -0800953 }
954
Elliott Hughesa2155262011-11-16 16:26:58 -0800955 if (c->IsArrayClass()) {
956 *pStatus = JDWP::CS_VERIFIED | JDWP::CS_PREPARED;
957 *pTypeTag = JDWP::TT_ARRAY;
958 } else {
959 if (c->IsErroneous()) {
960 *pStatus = JDWP::CS_ERROR;
961 } else {
962 *pStatus = JDWP::CS_VERIFIED | JDWP::CS_PREPARED | JDWP::CS_INITIALIZED;
963 }
964 *pTypeTag = c->IsInterface() ? JDWP::TT_INTERFACE : JDWP::TT_CLASS;
965 }
966
967 if (pDescriptor != NULL) {
Ian Rogersdfb325e2013-10-30 01:00:44 -0700968 *pDescriptor = ClassHelper(c).GetDescriptor();
Elliott Hughesa2155262011-11-16 16:26:58 -0800969 }
Elliott Hughes436e3722012-02-17 20:01:47 -0800970 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700971}
972
Elliott Hughesc3b77c72011-12-15 20:56:48 -0800973void Dbg::FindLoadedClassBySignature(const char* descriptor, std::vector<JDWP::RefTypeId>& ids) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800974 std::vector<mirror::Class*> classes;
Elliott Hughes6fa602d2011-12-02 17:54:25 -0800975 Runtime::Current()->GetClassLinker()->LookupClasses(descriptor, classes);
976 ids.clear();
977 for (size_t i = 0; i < classes.size(); ++i) {
978 ids.push_back(gRegistry->Add(classes[i]));
979 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700980}
981
Elliott Hughes64f574f2013-02-20 14:57:12 -0800982JDWP::JdwpError Dbg::GetReferenceType(JDWP::ObjectId object_id, JDWP::ExpandBuf* pReply)
983 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800984 mirror::Object* o = gRegistry->Get<mirror::Object*>(object_id);
Elliott Hughes64f574f2013-02-20 14:57:12 -0800985 if (o == NULL || o == ObjectRegistry::kInvalidObject) {
Elliott Hughes2435a572012-02-17 16:07:41 -0800986 return JDWP::ERR_INVALID_OBJECT;
Elliott Hughes499c5132011-11-17 14:55:11 -0800987 }
Elliott Hughes2435a572012-02-17 16:07:41 -0800988
989 JDWP::JdwpTypeTag type_tag;
990 if (o->GetClass()->IsArrayClass()) {
991 type_tag = JDWP::TT_ARRAY;
992 } else if (o->GetClass()->IsInterface()) {
993 type_tag = JDWP::TT_INTERFACE;
994 } else {
995 type_tag = JDWP::TT_CLASS;
996 }
Elliott Hughes64f574f2013-02-20 14:57:12 -0800997 JDWP::RefTypeId type_id = gRegistry->AddRefType(o->GetClass());
Elliott Hughes2435a572012-02-17 16:07:41 -0800998
999 expandBufAdd1(pReply, type_tag);
1000 expandBufAddRefTypeId(pReply, type_id);
1001
1002 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001003}
1004
Ian Rogersfc0e94b2013-09-23 23:51:32 -07001005JDWP::JdwpError Dbg::GetSignature(JDWP::RefTypeId class_id, std::string* signature) {
Elliott Hughes1fe7afb2012-02-13 17:23:03 -08001006 JDWP::JdwpError status;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001007 mirror::Class* c = DecodeClass(class_id, status);
Elliott Hughes1fe7afb2012-02-13 17:23:03 -08001008 if (c == NULL) {
1009 return status;
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -08001010 }
Ian Rogersdfb325e2013-10-30 01:00:44 -07001011 *signature = ClassHelper(c).GetDescriptor();
Elliott Hughes1fe7afb2012-02-13 17:23:03 -08001012 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001013}
1014
Elliott Hughes88d63092013-01-09 09:55:54 -08001015JDWP::JdwpError Dbg::GetSourceFile(JDWP::RefTypeId class_id, std::string& result) {
Elliott Hughes436e3722012-02-17 20:01:47 -08001016 JDWP::JdwpError status;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001017 mirror::Class* c = DecodeClass(class_id, status);
Elliott Hughes436e3722012-02-17 20:01:47 -08001018 if (c == NULL) {
1019 return status;
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -08001020 }
Elliott Hughes436e3722012-02-17 20:01:47 -08001021 result = ClassHelper(c).GetSourceFile();
1022 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001023}
1024
Elliott Hughes88d63092013-01-09 09:55:54 -08001025JDWP::JdwpError Dbg::GetObjectTag(JDWP::ObjectId object_id, uint8_t& tag) {
Ian Rogers98379392014-02-24 16:53:16 -08001026 ScopedObjectAccessUnchecked soa(Thread::Current());
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001027 mirror::Object* o = gRegistry->Get<mirror::Object*>(object_id);
Elliott Hughes64f574f2013-02-20 14:57:12 -08001028 if (o == ObjectRegistry::kInvalidObject) {
Elliott Hughes546b9862012-06-20 16:06:13 -07001029 return JDWP::ERR_INVALID_OBJECT;
1030 }
Ian Rogers98379392014-02-24 16:53:16 -08001031 tag = TagFromObject(soa, o);
Elliott Hughes546b9862012-06-20 16:06:13 -07001032 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001033}
1034
Elliott Hughesaed4be92011-12-02 16:16:23 -08001035size_t Dbg::GetTagWidth(JDWP::JdwpTag tag) {
Elliott Hughesdbb40792011-11-18 17:05:22 -08001036 switch (tag) {
1037 case JDWP::JT_VOID:
1038 return 0;
1039 case JDWP::JT_BYTE:
1040 case JDWP::JT_BOOLEAN:
1041 return 1;
1042 case JDWP::JT_CHAR:
1043 case JDWP::JT_SHORT:
1044 return 2;
1045 case JDWP::JT_FLOAT:
1046 case JDWP::JT_INT:
1047 return 4;
1048 case JDWP::JT_ARRAY:
1049 case JDWP::JT_OBJECT:
1050 case JDWP::JT_STRING:
1051 case JDWP::JT_THREAD:
1052 case JDWP::JT_THREAD_GROUP:
1053 case JDWP::JT_CLASS_LOADER:
1054 case JDWP::JT_CLASS_OBJECT:
1055 return sizeof(JDWP::ObjectId);
1056 case JDWP::JT_DOUBLE:
1057 case JDWP::JT_LONG:
1058 return 8;
1059 default:
Elliott Hughes3d30d9b2011-12-07 17:35:48 -08001060 LOG(FATAL) << "Unknown tag " << tag;
Elliott Hughesdbb40792011-11-18 17:05:22 -08001061 return -1;
1062 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001063}
1064
Elliott Hughes88d63092013-01-09 09:55:54 -08001065JDWP::JdwpError Dbg::GetArrayLength(JDWP::ObjectId array_id, int& length) {
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -08001066 JDWP::JdwpError status;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001067 mirror::Array* a = DecodeArray(array_id, status);
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -08001068 if (a == NULL) {
1069 return status;
Elliott Hughes24437992011-11-30 14:49:33 -08001070 }
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -08001071 length = a->GetLength();
1072 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001073}
1074
Elliott Hughes88d63092013-01-09 09:55:54 -08001075JDWP::JdwpError Dbg::OutputArray(JDWP::ObjectId array_id, int offset, int count, JDWP::ExpandBuf* pReply) {
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -08001076 JDWP::JdwpError status;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001077 mirror::Array* a = DecodeArray(array_id, status);
Ian Rogers98379392014-02-24 16:53:16 -08001078 if (a == nullptr) {
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -08001079 return status;
1080 }
Elliott Hughes24437992011-11-30 14:49:33 -08001081
1082 if (offset < 0 || count < 0 || offset > a->GetLength() || a->GetLength() - offset < count) {
1083 LOG(WARNING) << __FUNCTION__ << " access out of bounds: offset=" << offset << "; count=" << count;
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -08001084 return JDWP::ERR_INVALID_LENGTH;
Elliott Hughes24437992011-11-30 14:49:33 -08001085 }
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001086 std::string descriptor(ClassHelper(a->GetClass()).GetDescriptor());
Elliott Hughes24437992011-11-30 14:49:33 -08001087 JDWP::JdwpTag tag = BasicTagFromDescriptor(descriptor.c_str() + 1);
1088
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -08001089 expandBufAdd1(pReply, tag);
1090 expandBufAdd4BE(pReply, count);
1091
Elliott Hughes24437992011-11-30 14:49:33 -08001092 if (IsPrimitiveTag(tag)) {
1093 size_t width = GetTagWidth(tag);
Elliott Hughes24437992011-11-30 14:49:33 -08001094 uint8_t* dst = expandBufAddSpace(pReply, count * width);
1095 if (width == 8) {
Ian Rogersef7d42f2014-01-06 12:55:46 -08001096 const uint64_t* src8 = reinterpret_cast<uint64_t*>(a->GetRawData(sizeof(uint64_t), 0));
Elliott Hughes24437992011-11-30 14:49:33 -08001097 for (int i = 0; i < count; ++i) JDWP::Write8BE(&dst, src8[offset + i]);
1098 } else if (width == 4) {
Ian Rogersef7d42f2014-01-06 12:55:46 -08001099 const uint32_t* src4 = reinterpret_cast<uint32_t*>(a->GetRawData(sizeof(uint32_t), 0));
Elliott Hughes24437992011-11-30 14:49:33 -08001100 for (int i = 0; i < count; ++i) JDWP::Write4BE(&dst, src4[offset + i]);
1101 } else if (width == 2) {
Ian Rogersef7d42f2014-01-06 12:55:46 -08001102 const uint16_t* src2 = reinterpret_cast<uint16_t*>(a->GetRawData(sizeof(uint16_t), 0));
Elliott Hughes24437992011-11-30 14:49:33 -08001103 for (int i = 0; i < count; ++i) JDWP::Write2BE(&dst, src2[offset + i]);
1104 } else {
Ian Rogersef7d42f2014-01-06 12:55:46 -08001105 const uint8_t* src = reinterpret_cast<uint8_t*>(a->GetRawData(sizeof(uint8_t), 0));
Elliott Hughes24437992011-11-30 14:49:33 -08001106 memcpy(dst, &src[offset * width], count * width);
1107 }
1108 } else {
Ian Rogers98379392014-02-24 16:53:16 -08001109 ScopedObjectAccessUnchecked soa(Thread::Current());
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001110 mirror::ObjectArray<mirror::Object>* oa = a->AsObjectArray<mirror::Object>();
Elliott Hughes24437992011-11-30 14:49:33 -08001111 for (int i = 0; i < count; ++i) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001112 mirror::Object* element = oa->Get(offset + i);
Ian Rogers98379392014-02-24 16:53:16 -08001113 JDWP::JdwpTag specific_tag = (element != nullptr) ? TagFromObject(soa, element)
1114 : tag;
Elliott Hughes24437992011-11-30 14:49:33 -08001115 expandBufAdd1(pReply, specific_tag);
1116 expandBufAddObjectId(pReply, gRegistry->Add(element));
1117 }
1118 }
1119
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -08001120 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001121}
1122
Ian Rogersef7d42f2014-01-06 12:55:46 -08001123template <typename T>
1124static void CopyArrayData(mirror::Array* a, JDWP::Request& src, int offset, int count)
1125 NO_THREAD_SAFETY_ANALYSIS {
1126 // TODO: fix when annotalysis correctly handles non-member functions.
Elliott Hughes4b9702c2013-02-20 18:13:24 -08001127 DCHECK(a->GetClass()->IsPrimitiveArray());
1128
Ian Rogersef7d42f2014-01-06 12:55:46 -08001129 T* dst = reinterpret_cast<T*>(a->GetRawData(sizeof(T), offset));
Elliott Hughes4b9702c2013-02-20 18:13:24 -08001130 for (int i = 0; i < count; ++i) {
1131 *dst++ = src.ReadValue(sizeof(T));
1132 }
1133}
1134
Elliott Hughes88d63092013-01-09 09:55:54 -08001135JDWP::JdwpError Dbg::SetArrayElements(JDWP::ObjectId array_id, int offset, int count,
Elliott Hughes4b9702c2013-02-20 18:13:24 -08001136 JDWP::Request& request)
Ian Rogersb726dcb2012-09-05 08:57:23 -07001137 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -08001138 JDWP::JdwpError status;
Elliott Hughes4b9702c2013-02-20 18:13:24 -08001139 mirror::Array* dst = DecodeArray(array_id, status);
1140 if (dst == NULL) {
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -08001141 return status;
1142 }
Elliott Hughesf03b8f62011-12-02 14:26:25 -08001143
Elliott Hughes4b9702c2013-02-20 18:13:24 -08001144 if (offset < 0 || count < 0 || offset > dst->GetLength() || dst->GetLength() - offset < count) {
Elliott Hughesf03b8f62011-12-02 14:26:25 -08001145 LOG(WARNING) << __FUNCTION__ << " access out of bounds: offset=" << offset << "; count=" << count;
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -08001146 return JDWP::ERR_INVALID_LENGTH;
Elliott Hughesf03b8f62011-12-02 14:26:25 -08001147 }
Ian Rogersfc0e94b2013-09-23 23:51:32 -07001148 const char* descriptor = ClassHelper(dst->GetClass()).GetDescriptor();
1149 JDWP::JdwpTag tag = BasicTagFromDescriptor(descriptor + 1);
Elliott Hughesf03b8f62011-12-02 14:26:25 -08001150
1151 if (IsPrimitiveTag(tag)) {
1152 size_t width = GetTagWidth(tag);
Elliott Hughesf03b8f62011-12-02 14:26:25 -08001153 if (width == 8) {
Elliott Hughes4b9702c2013-02-20 18:13:24 -08001154 CopyArrayData<uint64_t>(dst, request, offset, count);
Elliott Hughesf03b8f62011-12-02 14:26:25 -08001155 } else if (width == 4) {
Elliott Hughes4b9702c2013-02-20 18:13:24 -08001156 CopyArrayData<uint32_t>(dst, request, offset, count);
Elliott Hughesf03b8f62011-12-02 14:26:25 -08001157 } else if (width == 2) {
Elliott Hughes4b9702c2013-02-20 18:13:24 -08001158 CopyArrayData<uint16_t>(dst, request, offset, count);
Elliott Hughesf03b8f62011-12-02 14:26:25 -08001159 } else {
Elliott Hughes4b9702c2013-02-20 18:13:24 -08001160 CopyArrayData<uint8_t>(dst, request, offset, count);
Elliott Hughesf03b8f62011-12-02 14:26:25 -08001161 }
1162 } else {
Elliott Hughes4b9702c2013-02-20 18:13:24 -08001163 mirror::ObjectArray<mirror::Object>* oa = dst->AsObjectArray<mirror::Object>();
Elliott Hughesf03b8f62011-12-02 14:26:25 -08001164 for (int i = 0; i < count; ++i) {
Elliott Hughes4b9702c2013-02-20 18:13:24 -08001165 JDWP::ObjectId id = request.ReadObjectId();
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001166 mirror::Object* o = gRegistry->Get<mirror::Object*>(id);
Elliott Hughes64f574f2013-02-20 14:57:12 -08001167 if (o == ObjectRegistry::kInvalidObject) {
Elliott Hughes436e3722012-02-17 20:01:47 -08001168 return JDWP::ERR_INVALID_OBJECT;
1169 }
Sebastien Hertzd2fe10a2014-01-15 10:20:56 +01001170 oa->Set<false>(offset + i, o);
Elliott Hughesf03b8f62011-12-02 14:26:25 -08001171 }
1172 }
1173
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -08001174 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001175}
1176
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -08001177JDWP::ObjectId Dbg::CreateString(const std::string& str) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001178 return gRegistry->Add(mirror::String::AllocFromModifiedUtf8(Thread::Current(), str.c_str()));
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001179}
1180
Elliott Hughes88d63092013-01-09 09:55:54 -08001181JDWP::JdwpError Dbg::CreateObject(JDWP::RefTypeId class_id, JDWP::ObjectId& new_object) {
Elliott Hughes436e3722012-02-17 20:01:47 -08001182 JDWP::JdwpError status;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001183 mirror::Class* c = DecodeClass(class_id, status);
Elliott Hughes436e3722012-02-17 20:01:47 -08001184 if (c == NULL) {
1185 return status;
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -08001186 }
Ian Rogers50b35e22012-10-04 10:09:15 -07001187 new_object = gRegistry->Add(c->AllocObject(Thread::Current()));
Elliott Hughes436e3722012-02-17 20:01:47 -08001188 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001189}
1190
Elliott Hughesbf13d362011-12-08 15:51:37 -08001191/*
1192 * Used by Eclipse's "Display" view to evaluate "new byte[5]" to get "(byte[]) [0, 0, 0, 0, 0]".
1193 */
Elliott Hughes88d63092013-01-09 09:55:54 -08001194JDWP::JdwpError Dbg::CreateArrayObject(JDWP::RefTypeId array_class_id, uint32_t length,
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001195 JDWP::ObjectId& new_array) {
Elliott Hughes436e3722012-02-17 20:01:47 -08001196 JDWP::JdwpError status;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001197 mirror::Class* c = DecodeClass(array_class_id, status);
Elliott Hughes436e3722012-02-17 20:01:47 -08001198 if (c == NULL) {
1199 return status;
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -08001200 }
Mathieu Chartiercbb2d202013-11-14 17:45:16 -08001201 new_array = gRegistry->Add(mirror::Array::Alloc<true>(Thread::Current(), c, length));
Elliott Hughes436e3722012-02-17 20:01:47 -08001202 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001203}
1204
Elliott Hughes88d63092013-01-09 09:55:54 -08001205bool Dbg::MatchType(JDWP::RefTypeId instance_class_id, JDWP::RefTypeId class_id) {
Elliott Hughes436e3722012-02-17 20:01:47 -08001206 JDWP::JdwpError status;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001207 mirror::Class* c1 = DecodeClass(instance_class_id, status);
Elliott Hughesa656a0f2012-02-21 18:03:44 -08001208 CHECK(c1 != NULL);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001209 mirror::Class* c2 = DecodeClass(class_id, status);
Elliott Hughesa656a0f2012-02-21 18:03:44 -08001210 CHECK(c2 != NULL);
Sebastien Hertz123756a2013-11-27 15:49:42 +01001211 return c2->IsAssignableFrom(c1);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001212}
1213
Brian Carlstromea46f952013-07-30 01:26:50 -07001214static JDWP::FieldId ToFieldId(const mirror::ArtField* f)
Ian Rogersb726dcb2012-09-05 08:57:23 -07001215 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Mathieu Chartier590fee92013-09-13 13:46:47 -07001216 CHECK(!kMovingFields);
Elliott Hughes03181a82011-11-17 17:22:21 -08001217 return static_cast<JDWP::FieldId>(reinterpret_cast<uintptr_t>(f));
Elliott Hughes03181a82011-11-17 17:22:21 -08001218}
1219
Brian Carlstromea46f952013-07-30 01:26:50 -07001220static JDWP::MethodId ToMethodId(const mirror::ArtMethod* m)
Ian Rogersb726dcb2012-09-05 08:57:23 -07001221 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Mathieu Chartier590fee92013-09-13 13:46:47 -07001222 CHECK(!kMovingMethods);
Elliott Hughes03181a82011-11-17 17:22:21 -08001223 return static_cast<JDWP::MethodId>(reinterpret_cast<uintptr_t>(m));
Elliott Hughes03181a82011-11-17 17:22:21 -08001224}
1225
Brian Carlstromea46f952013-07-30 01:26:50 -07001226static mirror::ArtField* FromFieldId(JDWP::FieldId fid)
Ian Rogersb726dcb2012-09-05 08:57:23 -07001227 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Mathieu Chartier590fee92013-09-13 13:46:47 -07001228 CHECK(!kMovingFields);
Brian Carlstromea46f952013-07-30 01:26:50 -07001229 return reinterpret_cast<mirror::ArtField*>(static_cast<uintptr_t>(fid));
Elliott Hughesaed4be92011-12-02 16:16:23 -08001230}
1231
Brian Carlstromea46f952013-07-30 01:26:50 -07001232static mirror::ArtMethod* FromMethodId(JDWP::MethodId mid)
Ian Rogersb726dcb2012-09-05 08:57:23 -07001233 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Mathieu Chartier590fee92013-09-13 13:46:47 -07001234 CHECK(!kMovingMethods);
Brian Carlstromea46f952013-07-30 01:26:50 -07001235 return reinterpret_cast<mirror::ArtMethod*>(static_cast<uintptr_t>(mid));
Elliott Hughes03181a82011-11-17 17:22:21 -08001236}
1237
Brian Carlstromea46f952013-07-30 01:26:50 -07001238static void SetLocation(JDWP::JdwpLocation& location, mirror::ArtMethod* m, uint32_t dex_pc)
Ian Rogersb726dcb2012-09-05 08:57:23 -07001239 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08001240 if (m == NULL) {
1241 memset(&location, 0, sizeof(location));
1242 } else {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001243 mirror::Class* c = m->GetDeclaringClass();
Elliott Hughes74847412012-06-20 18:10:21 -07001244 location.type_tag = c->IsInterface() ? JDWP::TT_INTERFACE : JDWP::TT_CLASS;
1245 location.class_id = gRegistry->Add(c);
1246 location.method_id = ToMethodId(m);
Ian Rogers0399dde2012-06-06 17:09:28 -07001247 location.dex_pc = dex_pc;
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08001248 }
Elliott Hughesd07986f2011-12-06 18:27:45 -08001249}
1250
Elliott Hughesa96836a2013-01-17 12:27:49 -08001251std::string Dbg::GetMethodName(JDWP::MethodId method_id)
Ian Rogersb726dcb2012-09-05 08:57:23 -07001252 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Brian Carlstromea46f952013-07-30 01:26:50 -07001253 mirror::ArtMethod* m = FromMethodId(method_id);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001254 return MethodHelper(m).GetName();
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001255}
1256
Elliott Hughesa96836a2013-01-17 12:27:49 -08001257std::string Dbg::GetFieldName(JDWP::FieldId field_id)
1258 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Brian Carlstromea46f952013-07-30 01:26:50 -07001259 mirror::ArtField* f = FromFieldId(field_id);
Elliott Hughesa96836a2013-01-17 12:27:49 -08001260 return FieldHelper(f).GetName();
1261}
1262
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001263/*
1264 * Augment the access flags for synthetic methods and fields by setting
1265 * the (as described by the spec) "0xf0000000 bit". Also, strip out any
1266 * flags not specified by the Java programming language.
1267 */
1268static uint32_t MangleAccessFlags(uint32_t accessFlags) {
1269 accessFlags &= kAccJavaFlagsMask;
1270 if ((accessFlags & kAccSynthetic) != 0) {
1271 accessFlags |= 0xf0000000;
1272 }
1273 return accessFlags;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001274}
1275
Elliott Hughesdbb40792011-11-18 17:05:22 -08001276/*
Jeff Haob7cefc72013-11-14 14:51:09 -08001277 * Circularly shifts registers so that arguments come first. Debuggers
1278 * expect slots to begin with arguments, but dex code places them at
1279 * the end.
Elliott Hughesdbb40792011-11-18 17:05:22 -08001280 */
Jeff Haob7cefc72013-11-14 14:51:09 -08001281static uint16_t MangleSlot(uint16_t slot, mirror::ArtMethod* m)
1282 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
1283 const DexFile::CodeItem* code_item = MethodHelper(m).GetCodeItem();
1284 uint16_t ins_size = code_item->ins_size_;
1285 uint16_t locals_size = code_item->registers_size_ - ins_size;
1286 if (slot >= locals_size) {
1287 return slot - locals_size;
1288 } else {
1289 return slot + ins_size;
Elliott Hughesdbb40792011-11-18 17:05:22 -08001290 }
Elliott Hughesdbb40792011-11-18 17:05:22 -08001291}
1292
Jeff Haob7cefc72013-11-14 14:51:09 -08001293/*
1294 * Circularly shifts registers so that arguments come last. Reverts
1295 * slots to dex style argument placement.
1296 */
Brian Carlstromea46f952013-07-30 01:26:50 -07001297static uint16_t DemangleSlot(uint16_t slot, mirror::ArtMethod* m)
Ian Rogersb726dcb2012-09-05 08:57:23 -07001298 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Jeff Haob7cefc72013-11-14 14:51:09 -08001299 const DexFile::CodeItem* code_item = MethodHelper(m).GetCodeItem();
1300 uint16_t ins_size = code_item->ins_size_;
1301 uint16_t locals_size = code_item->registers_size_ - ins_size;
1302 if (slot < ins_size) {
1303 return slot + locals_size;
1304 } else {
1305 return slot - ins_size;
Elliott Hughesdbb40792011-11-18 17:05:22 -08001306 }
Elliott Hughesdbb40792011-11-18 17:05:22 -08001307}
1308
Elliott Hughes88d63092013-01-09 09:55:54 -08001309JDWP::JdwpError Dbg::OutputDeclaredFields(JDWP::RefTypeId class_id, bool with_generic, JDWP::ExpandBuf* pReply) {
Elliott Hughes436e3722012-02-17 20:01:47 -08001310 JDWP::JdwpError status;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001311 mirror::Class* c = DecodeClass(class_id, status);
Elliott Hughes436e3722012-02-17 20:01:47 -08001312 if (c == NULL) {
1313 return status;
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -08001314 }
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001315
1316 size_t instance_field_count = c->NumInstanceFields();
1317 size_t static_field_count = c->NumStaticFields();
1318
1319 expandBufAdd4BE(pReply, instance_field_count + static_field_count);
1320
1321 for (size_t i = 0; i < instance_field_count + static_field_count; ++i) {
Brian Carlstromea46f952013-07-30 01:26:50 -07001322 mirror::ArtField* f = (i < instance_field_count) ? c->GetInstanceField(i) : c->GetStaticField(i - instance_field_count);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001323 FieldHelper fh(f);
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001324 expandBufAddFieldId(pReply, ToFieldId(f));
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001325 expandBufAddUtf8String(pReply, fh.GetName());
1326 expandBufAddUtf8String(pReply, fh.GetTypeDescriptor());
Elliott Hughesc5b734a2011-12-01 17:20:58 -08001327 if (with_generic) {
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001328 static const char genericSignature[1] = "";
1329 expandBufAddUtf8String(pReply, genericSignature);
1330 }
1331 expandBufAdd4BE(pReply, MangleAccessFlags(f->GetAccessFlags()));
1332 }
Elliott Hughes436e3722012-02-17 20:01:47 -08001333 return JDWP::ERR_NONE;
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001334}
1335
Elliott Hughes88d63092013-01-09 09:55:54 -08001336JDWP::JdwpError Dbg::OutputDeclaredMethods(JDWP::RefTypeId class_id, bool with_generic,
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001337 JDWP::ExpandBuf* pReply) {
Elliott Hughes436e3722012-02-17 20:01:47 -08001338 JDWP::JdwpError status;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001339 mirror::Class* c = DecodeClass(class_id, status);
Elliott Hughes436e3722012-02-17 20:01:47 -08001340 if (c == NULL) {
1341 return status;
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -08001342 }
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001343
1344 size_t direct_method_count = c->NumDirectMethods();
1345 size_t virtual_method_count = c->NumVirtualMethods();
1346
1347 expandBufAdd4BE(pReply, direct_method_count + virtual_method_count);
1348
1349 for (size_t i = 0; i < direct_method_count + virtual_method_count; ++i) {
Brian Carlstromea46f952013-07-30 01:26:50 -07001350 mirror::ArtMethod* m = (i < direct_method_count) ? c->GetDirectMethod(i) : c->GetVirtualMethod(i - direct_method_count);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001351 MethodHelper mh(m);
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001352 expandBufAddMethodId(pReply, ToMethodId(m));
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001353 expandBufAddUtf8String(pReply, mh.GetName());
Ian Rogersd91d6d62013-09-25 20:26:14 -07001354 expandBufAddUtf8String(pReply, mh.GetSignature().ToString());
Elliott Hughesc5b734a2011-12-01 17:20:58 -08001355 if (with_generic) {
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001356 static const char genericSignature[1] = "";
1357 expandBufAddUtf8String(pReply, genericSignature);
1358 }
1359 expandBufAdd4BE(pReply, MangleAccessFlags(m->GetAccessFlags()));
1360 }
Elliott Hughes436e3722012-02-17 20:01:47 -08001361 return JDWP::ERR_NONE;
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001362}
1363
Elliott Hughes88d63092013-01-09 09:55:54 -08001364JDWP::JdwpError Dbg::OutputDeclaredInterfaces(JDWP::RefTypeId class_id, JDWP::ExpandBuf* pReply) {
Elliott Hughes436e3722012-02-17 20:01:47 -08001365 JDWP::JdwpError status;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001366 mirror::Class* c = DecodeClass(class_id, status);
Elliott Hughes436e3722012-02-17 20:01:47 -08001367 if (c == NULL) {
1368 return status;
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -08001369 }
Elliott Hughes436e3722012-02-17 20:01:47 -08001370
1371 ClassHelper kh(c);
Ian Rogersd24e2642012-06-06 21:21:43 -07001372 size_t interface_count = kh.NumDirectInterfaces();
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001373 expandBufAdd4BE(pReply, interface_count);
1374 for (size_t i = 0; i < interface_count; ++i) {
Elliott Hughes64f574f2013-02-20 14:57:12 -08001375 expandBufAddRefTypeId(pReply, gRegistry->AddRefType(kh.GetDirectInterface(i)));
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001376 }
Elliott Hughes436e3722012-02-17 20:01:47 -08001377 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001378}
1379
Elliott Hughes88d63092013-01-09 09:55:54 -08001380void Dbg::OutputLineTable(JDWP::RefTypeId, JDWP::MethodId method_id, JDWP::ExpandBuf* pReply)
Ian Rogersb726dcb2012-09-05 08:57:23 -07001381 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Elliott Hughes03181a82011-11-17 17:22:21 -08001382 struct DebugCallbackContext {
1383 int numItems;
1384 JDWP::ExpandBuf* pReply;
1385
Elliott Hughes2435a572012-02-17 16:07:41 -08001386 static bool Callback(void* context, uint32_t address, uint32_t line_number) {
Elliott Hughes03181a82011-11-17 17:22:21 -08001387 DebugCallbackContext* pContext = reinterpret_cast<DebugCallbackContext*>(context);
1388 expandBufAdd8BE(pContext->pReply, address);
Elliott Hughes2435a572012-02-17 16:07:41 -08001389 expandBufAdd4BE(pContext->pReply, line_number);
Elliott Hughes03181a82011-11-17 17:22:21 -08001390 pContext->numItems++;
Sebastien Hertzf2910ee2013-10-19 16:39:24 +02001391 return false;
Elliott Hughes03181a82011-11-17 17:22:21 -08001392 }
1393 };
Brian Carlstromea46f952013-07-30 01:26:50 -07001394 mirror::ArtMethod* m = FromMethodId(method_id);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001395 MethodHelper mh(m);
Elliott Hughes03181a82011-11-17 17:22:21 -08001396 uint64_t start, end;
1397 if (m->IsNative()) {
1398 start = -1;
1399 end = -1;
1400 } else {
1401 start = 0;
jeffhao14f0db92012-12-14 17:50:42 -08001402 // Return the index of the last instruction
1403 end = mh.GetCodeItem()->insns_size_in_code_units_ - 1;
Elliott Hughes03181a82011-11-17 17:22:21 -08001404 }
1405
1406 expandBufAdd8BE(pReply, start);
1407 expandBufAdd8BE(pReply, end);
1408
1409 // Add numLines later
1410 size_t numLinesOffset = expandBufGetLength(pReply);
1411 expandBufAdd4BE(pReply, 0);
1412
1413 DebugCallbackContext context;
1414 context.numItems = 0;
1415 context.pReply = pReply;
1416
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001417 mh.GetDexFile().DecodeDebugInfo(mh.GetCodeItem(), m->IsStatic(), m->GetDexMethodIndex(),
1418 DebugCallbackContext::Callback, NULL, &context);
Elliott Hughes03181a82011-11-17 17:22:21 -08001419
1420 JDWP::Set4BE(expandBufGetBuffer(pReply) + numLinesOffset, context.numItems);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001421}
1422
Elliott Hughes88d63092013-01-09 09:55:54 -08001423void Dbg::OutputVariableTable(JDWP::RefTypeId, JDWP::MethodId method_id, bool with_generic, JDWP::ExpandBuf* pReply) {
Elliott Hughesdbb40792011-11-18 17:05:22 -08001424 struct DebugCallbackContext {
Jeff Haob7cefc72013-11-14 14:51:09 -08001425 mirror::ArtMethod* method;
Elliott Hughesdbb40792011-11-18 17:05:22 -08001426 JDWP::ExpandBuf* pReply;
Elliott Hughesc5b734a2011-12-01 17:20:58 -08001427 size_t variable_count;
1428 bool with_generic;
Elliott Hughesdbb40792011-11-18 17:05:22 -08001429
Jeff Haob7cefc72013-11-14 14:51:09 -08001430 static void Callback(void* context, uint16_t slot, uint32_t startAddress, uint32_t endAddress, const char* name, const char* descriptor, const char* signature)
1431 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Elliott Hughesdbb40792011-11-18 17:05:22 -08001432 DebugCallbackContext* pContext = reinterpret_cast<DebugCallbackContext*>(context);
1433
Jeff Haob7cefc72013-11-14 14:51:09 -08001434 VLOG(jdwp) << StringPrintf(" %2zd: %d(%d) '%s' '%s' '%s' actual slot=%d mangled slot=%d", pContext->variable_count, startAddress, endAddress - startAddress, name, descriptor, signature, slot, MangleSlot(slot, pContext->method));
Elliott Hughesdbb40792011-11-18 17:05:22 -08001435
Jeff Haob7cefc72013-11-14 14:51:09 -08001436 slot = MangleSlot(slot, pContext->method);
Elliott Hughes68fdbd02011-11-29 19:22:47 -08001437
Elliott Hughesdbb40792011-11-18 17:05:22 -08001438 expandBufAdd8BE(pContext->pReply, startAddress);
1439 expandBufAddUtf8String(pContext->pReply, name);
1440 expandBufAddUtf8String(pContext->pReply, descriptor);
Elliott Hughesc5b734a2011-12-01 17:20:58 -08001441 if (pContext->with_generic) {
Elliott Hughesdbb40792011-11-18 17:05:22 -08001442 expandBufAddUtf8String(pContext->pReply, signature);
1443 }
1444 expandBufAdd4BE(pContext->pReply, endAddress - startAddress);
1445 expandBufAdd4BE(pContext->pReply, slot);
1446
Elliott Hughesc5b734a2011-12-01 17:20:58 -08001447 ++pContext->variable_count;
Elliott Hughesdbb40792011-11-18 17:05:22 -08001448 }
1449 };
Brian Carlstromea46f952013-07-30 01:26:50 -07001450 mirror::ArtMethod* m = FromMethodId(method_id);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001451 MethodHelper mh(m);
1452 const DexFile::CodeItem* code_item = mh.GetCodeItem();
Elliott Hughesdbb40792011-11-18 17:05:22 -08001453
Elliott Hughesc5b734a2011-12-01 17:20:58 -08001454 // arg_count considers doubles and longs to take 2 units.
1455 // variable_count considers everything to take 1 unit.
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001456 std::string shorty(mh.GetShorty());
Brian Carlstromea46f952013-07-30 01:26:50 -07001457 expandBufAdd4BE(pReply, mirror::ArtMethod::NumArgRegisters(shorty));
Elliott Hughesdbb40792011-11-18 17:05:22 -08001458
Elliott Hughesc5b734a2011-12-01 17:20:58 -08001459 // We don't know the total number of variables yet, so leave a blank and update it later.
1460 size_t variable_count_offset = expandBufGetLength(pReply);
Elliott Hughesdbb40792011-11-18 17:05:22 -08001461 expandBufAdd4BE(pReply, 0);
1462
1463 DebugCallbackContext context;
Jeff Haob7cefc72013-11-14 14:51:09 -08001464 context.method = m;
Elliott Hughesdbb40792011-11-18 17:05:22 -08001465 context.pReply = pReply;
Elliott Hughesc5b734a2011-12-01 17:20:58 -08001466 context.variable_count = 0;
1467 context.with_generic = with_generic;
Elliott Hughesdbb40792011-11-18 17:05:22 -08001468
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001469 mh.GetDexFile().DecodeDebugInfo(code_item, m->IsStatic(), m->GetDexMethodIndex(), NULL,
1470 DebugCallbackContext::Callback, &context);
Elliott Hughesdbb40792011-11-18 17:05:22 -08001471
Elliott Hughesc5b734a2011-12-01 17:20:58 -08001472 JDWP::Set4BE(expandBufGetBuffer(pReply) + variable_count_offset, context.variable_count);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001473}
1474
Jeff Hao579b0242013-11-18 13:16:49 -08001475void Dbg::OutputMethodReturnValue(JDWP::MethodId method_id, const JValue* return_value,
1476 JDWP::ExpandBuf* pReply) {
1477 mirror::ArtMethod* m = FromMethodId(method_id);
1478 JDWP::JdwpTag tag = BasicTagFromDescriptor(MethodHelper(m).GetShorty());
1479 OutputJValue(tag, return_value, pReply);
1480}
1481
Elliott Hughes9777ba22013-01-17 09:04:19 -08001482JDWP::JdwpError Dbg::GetBytecodes(JDWP::RefTypeId, JDWP::MethodId method_id,
1483 std::vector<uint8_t>& bytecodes)
1484 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Brian Carlstromea46f952013-07-30 01:26:50 -07001485 mirror::ArtMethod* m = FromMethodId(method_id);
Elliott Hughes9777ba22013-01-17 09:04:19 -08001486 if (m == NULL) {
1487 return JDWP::ERR_INVALID_METHODID;
1488 }
1489 MethodHelper mh(m);
1490 const DexFile::CodeItem* code_item = mh.GetCodeItem();
1491 size_t byte_count = code_item->insns_size_in_code_units_ * 2;
1492 const uint8_t* begin = reinterpret_cast<const uint8_t*>(code_item->insns_);
1493 const uint8_t* end = begin + byte_count;
1494 for (const uint8_t* p = begin; p != end; ++p) {
1495 bytecodes.push_back(*p);
1496 }
1497 return JDWP::ERR_NONE;
1498}
1499
Elliott Hughes88d63092013-01-09 09:55:54 -08001500JDWP::JdwpTag Dbg::GetFieldBasicTag(JDWP::FieldId field_id) {
1501 return BasicTagFromDescriptor(FieldHelper(FromFieldId(field_id)).GetTypeDescriptor());
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001502}
1503
Elliott Hughes88d63092013-01-09 09:55:54 -08001504JDWP::JdwpTag Dbg::GetStaticFieldBasicTag(JDWP::FieldId field_id) {
1505 return BasicTagFromDescriptor(FieldHelper(FromFieldId(field_id)).GetTypeDescriptor());
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001506}
1507
Elliott Hughes88d63092013-01-09 09:55:54 -08001508static JDWP::JdwpError GetFieldValueImpl(JDWP::RefTypeId ref_type_id, JDWP::ObjectId object_id,
1509 JDWP::FieldId field_id, JDWP::ExpandBuf* pReply,
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001510 bool is_static)
Ian Rogersb726dcb2012-09-05 08:57:23 -07001511 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Elliott Hughes0cf74332012-02-23 23:14:00 -08001512 JDWP::JdwpError status;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001513 mirror::Class* c = DecodeClass(ref_type_id, status);
Elliott Hughes88d63092013-01-09 09:55:54 -08001514 if (ref_type_id != 0 && c == NULL) {
Elliott Hughes0cf74332012-02-23 23:14:00 -08001515 return status;
1516 }
1517
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001518 mirror::Object* o = gRegistry->Get<mirror::Object*>(object_id);
Elliott Hughes64f574f2013-02-20 14:57:12 -08001519 if ((!is_static && o == NULL) || o == ObjectRegistry::kInvalidObject) {
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08001520 return JDWP::ERR_INVALID_OBJECT;
1521 }
Brian Carlstromea46f952013-07-30 01:26:50 -07001522 mirror::ArtField* f = FromFieldId(field_id);
Elliott Hughes0cf74332012-02-23 23:14:00 -08001523
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001524 mirror::Class* receiver_class = c;
Elliott Hughes0cf74332012-02-23 23:14:00 -08001525 if (receiver_class == NULL && o != NULL) {
1526 receiver_class = o->GetClass();
1527 }
1528 // TODO: should we give up now if receiver_class is NULL?
1529 if (receiver_class != NULL && !f->GetDeclaringClass()->IsAssignableFrom(receiver_class)) {
1530 LOG(INFO) << "ERR_INVALID_FIELDID: " << PrettyField(f) << " " << PrettyClass(receiver_class);
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08001531 return JDWP::ERR_INVALID_FIELDID;
1532 }
Elliott Hughesaed4be92011-12-02 16:16:23 -08001533
Elliott Hughes0cf74332012-02-23 23:14:00 -08001534 // The RI only enforces the static/non-static mismatch in one direction.
1535 // TODO: should we change the tests and check both?
1536 if (is_static) {
1537 if (!f->IsStatic()) {
1538 return JDWP::ERR_INVALID_FIELDID;
1539 }
1540 } else {
1541 if (f->IsStatic()) {
1542 LOG(WARNING) << "Ignoring non-NULL receiver for ObjectReference.SetValues on static field " << PrettyField(f);
Elliott Hughes0cf74332012-02-23 23:14:00 -08001543 }
1544 }
jeffhao0dfbb7e2012-11-28 15:26:03 -08001545 if (f->IsStatic()) {
1546 o = f->GetDeclaringClass();
1547 }
Elliott Hughes0cf74332012-02-23 23:14:00 -08001548
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001549 JDWP::JdwpTag tag = BasicTagFromDescriptor(FieldHelper(f).GetTypeDescriptor());
Jeff Hao579b0242013-11-18 13:16:49 -08001550 JValue field_value;
1551 if (tag == JDWP::JT_VOID) {
1552 LOG(FATAL) << "Unknown tag: " << tag;
1553 } else if (!IsPrimitiveTag(tag)) {
1554 field_value.SetL(f->GetObject(o));
1555 } else if (tag == JDWP::JT_DOUBLE || tag == JDWP::JT_LONG) {
1556 field_value.SetJ(f->Get64(o));
Elliott Hughesaed4be92011-12-02 16:16:23 -08001557 } else {
Jeff Hao579b0242013-11-18 13:16:49 -08001558 field_value.SetI(f->Get32(o));
Elliott Hughesaed4be92011-12-02 16:16:23 -08001559 }
Jeff Hao579b0242013-11-18 13:16:49 -08001560 Dbg::OutputJValue(tag, &field_value, pReply);
1561
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08001562 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001563}
1564
Elliott Hughes88d63092013-01-09 09:55:54 -08001565JDWP::JdwpError Dbg::GetFieldValue(JDWP::ObjectId object_id, JDWP::FieldId field_id,
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001566 JDWP::ExpandBuf* pReply) {
Elliott Hughes88d63092013-01-09 09:55:54 -08001567 return GetFieldValueImpl(0, object_id, field_id, pReply, false);
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08001568}
1569
Elliott Hughes88d63092013-01-09 09:55:54 -08001570JDWP::JdwpError Dbg::GetStaticFieldValue(JDWP::RefTypeId ref_type_id, JDWP::FieldId field_id, JDWP::ExpandBuf* pReply) {
1571 return GetFieldValueImpl(ref_type_id, 0, field_id, pReply, true);
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08001572}
1573
Elliott Hughes88d63092013-01-09 09:55:54 -08001574static JDWP::JdwpError SetFieldValueImpl(JDWP::ObjectId object_id, JDWP::FieldId field_id,
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001575 uint64_t value, int width, bool is_static)
Ian Rogersb726dcb2012-09-05 08:57:23 -07001576 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001577 mirror::Object* o = gRegistry->Get<mirror::Object*>(object_id);
Elliott Hughes64f574f2013-02-20 14:57:12 -08001578 if ((!is_static && o == NULL) || o == ObjectRegistry::kInvalidObject) {
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08001579 return JDWP::ERR_INVALID_OBJECT;
1580 }
Brian Carlstromea46f952013-07-30 01:26:50 -07001581 mirror::ArtField* f = FromFieldId(field_id);
Elliott Hughes0cf74332012-02-23 23:14:00 -08001582
1583 // The RI only enforces the static/non-static mismatch in one direction.
1584 // TODO: should we change the tests and check both?
1585 if (is_static) {
1586 if (!f->IsStatic()) {
1587 return JDWP::ERR_INVALID_FIELDID;
1588 }
1589 } else {
1590 if (f->IsStatic()) {
1591 LOG(WARNING) << "Ignoring non-NULL receiver for ObjectReference.SetValues on static field " << PrettyField(f);
Elliott Hughes0cf74332012-02-23 23:14:00 -08001592 }
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08001593 }
jeffhao0dfbb7e2012-11-28 15:26:03 -08001594 if (f->IsStatic()) {
1595 o = f->GetDeclaringClass();
1596 }
Elliott Hughesaed4be92011-12-02 16:16:23 -08001597
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001598 JDWP::JdwpTag tag = BasicTagFromDescriptor(FieldHelper(f).GetTypeDescriptor());
Elliott Hughesaed4be92011-12-02 16:16:23 -08001599
1600 if (IsPrimitiveTag(tag)) {
1601 if (tag == JDWP::JT_DOUBLE || tag == JDWP::JT_LONG) {
Elliott Hughes1bac54f2012-03-16 12:48:31 -07001602 CHECK_EQ(width, 8);
Sebastien Hertzd2fe10a2014-01-15 10:20:56 +01001603 // Debugging can't use transactional mode (runtime only).
1604 f->Set64<false>(o, value);
Elliott Hughesaed4be92011-12-02 16:16:23 -08001605 } else {
Elliott Hughes1bac54f2012-03-16 12:48:31 -07001606 CHECK_LE(width, 4);
Sebastien Hertzd2fe10a2014-01-15 10:20:56 +01001607 // Debugging can't use transactional mode (runtime only).
1608 f->Set32<false>(o, value);
Elliott Hughesaed4be92011-12-02 16:16:23 -08001609 }
1610 } else {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001611 mirror::Object* v = gRegistry->Get<mirror::Object*>(value);
Elliott Hughes64f574f2013-02-20 14:57:12 -08001612 if (v == ObjectRegistry::kInvalidObject) {
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -08001613 return JDWP::ERR_INVALID_OBJECT;
1614 }
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08001615 if (v != NULL) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001616 mirror::Class* field_type = FieldHelper(f).GetType();
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08001617 if (!field_type->IsAssignableFrom(v->GetClass())) {
1618 return JDWP::ERR_INVALID_OBJECT;
1619 }
1620 }
Sebastien Hertzd2fe10a2014-01-15 10:20:56 +01001621 // Debugging can't use transactional mode (runtime only).
1622 f->SetObject<false>(o, v);
Elliott Hughesaed4be92011-12-02 16:16:23 -08001623 }
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -08001624
1625 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001626}
1627
Elliott Hughes88d63092013-01-09 09:55:54 -08001628JDWP::JdwpError Dbg::SetFieldValue(JDWP::ObjectId object_id, JDWP::FieldId field_id, uint64_t value,
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001629 int width) {
Elliott Hughes88d63092013-01-09 09:55:54 -08001630 return SetFieldValueImpl(object_id, field_id, value, width, false);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001631}
1632
Elliott Hughes88d63092013-01-09 09:55:54 -08001633JDWP::JdwpError Dbg::SetStaticFieldValue(JDWP::FieldId field_id, uint64_t value, int width) {
1634 return SetFieldValueImpl(0, field_id, value, width, true);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001635}
1636
Elliott Hughes88d63092013-01-09 09:55:54 -08001637std::string Dbg::StringToUtf8(JDWP::ObjectId string_id) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001638 mirror::String* s = gRegistry->Get<mirror::String*>(string_id);
Elliott Hughes68fdbd02011-11-29 19:22:47 -08001639 return s->ToModifiedUtf8();
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001640}
1641
Jeff Hao579b0242013-11-18 13:16:49 -08001642void Dbg::OutputJValue(JDWP::JdwpTag tag, const JValue* return_value, JDWP::ExpandBuf* pReply) {
1643 if (IsPrimitiveTag(tag)) {
1644 expandBufAdd1(pReply, tag);
1645 if (tag == JDWP::JT_BOOLEAN || tag == JDWP::JT_BYTE) {
1646 expandBufAdd1(pReply, return_value->GetI());
1647 } else if (tag == JDWP::JT_CHAR || tag == JDWP::JT_SHORT) {
1648 expandBufAdd2BE(pReply, return_value->GetI());
1649 } else if (tag == JDWP::JT_FLOAT || tag == JDWP::JT_INT) {
1650 expandBufAdd4BE(pReply, return_value->GetI());
1651 } else if (tag == JDWP::JT_DOUBLE || tag == JDWP::JT_LONG) {
1652 expandBufAdd8BE(pReply, return_value->GetJ());
1653 } else {
1654 CHECK_EQ(tag, JDWP::JT_VOID);
1655 }
1656 } else {
Ian Rogers98379392014-02-24 16:53:16 -08001657 ScopedObjectAccessUnchecked soa(Thread::Current());
Jeff Hao579b0242013-11-18 13:16:49 -08001658 mirror::Object* value = return_value->GetL();
Ian Rogers98379392014-02-24 16:53:16 -08001659 expandBufAdd1(pReply, TagFromObject(soa, value));
Jeff Hao579b0242013-11-18 13:16:49 -08001660 expandBufAddObjectId(pReply, gRegistry->Add(value));
1661 }
1662}
1663
Elliott Hughes221229c2013-01-08 18:17:50 -08001664JDWP::JdwpError Dbg::GetThreadName(JDWP::ObjectId thread_id, std::string& name) {
jeffhaoa77f0f62012-12-05 17:19:31 -08001665 ScopedObjectAccessUnchecked soa(Thread::Current());
1666 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 && error != JDWP::ERR_THREAD_NOT_ALIVE) {
1670 return error;
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001671 }
Elliott Hughes221229c2013-01-08 18:17:50 -08001672
1673 // We still need to report the zombie threads' names, so we can't just call Thread::GetThreadName.
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001674 mirror::Object* thread_object = gRegistry->Get<mirror::Object*>(thread_id);
Brian Carlstromea46f952013-07-30 01:26:50 -07001675 mirror::ArtField* java_lang_Thread_name_field =
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001676 soa.DecodeField(WellKnownClasses::java_lang_Thread_name);
1677 mirror::String* s =
1678 reinterpret_cast<mirror::String*>(java_lang_Thread_name_field->GetObject(thread_object));
Elliott Hughes221229c2013-01-08 18:17:50 -08001679 if (s != NULL) {
1680 name = s->ToModifiedUtf8();
1681 }
1682 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001683}
1684
Elliott Hughes221229c2013-01-08 18:17:50 -08001685JDWP::JdwpError Dbg::GetThreadGroup(JDWP::ObjectId thread_id, JDWP::ExpandBuf* pReply) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001686 ScopedObjectAccess soa(Thread::Current());
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001687 mirror::Object* thread_object = gRegistry->Get<mirror::Object*>(thread_id);
Elliott Hughes64f574f2013-02-20 14:57:12 -08001688 if (thread_object == ObjectRegistry::kInvalidObject) {
Elliott Hughes2435a572012-02-17 16:07:41 -08001689 return JDWP::ERR_INVALID_OBJECT;
1690 }
Ian Rogers98379392014-02-24 16:53:16 -08001691 const char* old_cause = soa.Self()->StartAssertNoThreadSuspension("Debugger: GetThreadGroup");
Elliott Hughes2435a572012-02-17 16:07:41 -08001692 // Okay, so it's an object, but is it actually a thread?
Ian Rogers50b35e22012-10-04 10:09:15 -07001693 MutexLock mu(soa.Self(), *Locks::thread_list_lock_);
Elliott Hughes221229c2013-01-08 18:17:50 -08001694 Thread* thread;
1695 JDWP::JdwpError error = DecodeThread(soa, thread_id, thread);
1696 if (error == JDWP::ERR_THREAD_NOT_ALIVE) {
1697 // Zombie threads are in the null group.
1698 expandBufAddObjectId(pReply, JDWP::ObjectId(0));
1699 return JDWP::ERR_NONE;
1700 }
1701 if (error != JDWP::ERR_NONE) {
1702 return error;
Elliott Hughes2435a572012-02-17 16:07:41 -08001703 }
Ian Rogers98379392014-02-24 16:53:16 -08001704 mirror::Class* c = soa.Decode<mirror::Class*>(WellKnownClasses::java_lang_Thread);
1705 CHECK(c != nullptr);
Brian Carlstromea46f952013-07-30 01:26:50 -07001706 mirror::ArtField* f = c->FindInstanceField("group", "Ljava/lang/ThreadGroup;");
Elliott Hughes499c5132011-11-17 14:55:11 -08001707 CHECK(f != NULL);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001708 mirror::Object* group = f->GetObject(thread_object);
Elliott Hughes499c5132011-11-17 14:55:11 -08001709 CHECK(group != NULL);
Elliott Hughes2435a572012-02-17 16:07:41 -08001710 JDWP::ObjectId thread_group_id = gRegistry->Add(group);
Ian Rogers98379392014-02-24 16:53:16 -08001711 soa.Self()->EndAssertNoThreadSuspension(old_cause);
Elliott Hughes2435a572012-02-17 16:07:41 -08001712
1713 expandBufAddObjectId(pReply, thread_group_id);
1714 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001715}
1716
Elliott Hughes88d63092013-01-09 09:55:54 -08001717std::string Dbg::GetThreadGroupName(JDWP::ObjectId thread_group_id) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001718 ScopedObjectAccess soa(Thread::Current());
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001719 mirror::Object* thread_group = gRegistry->Get<mirror::Object*>(thread_group_id);
Ian Rogers98379392014-02-24 16:53:16 -08001720 CHECK(thread_group != nullptr);
1721 const char* old_cause = soa.Self()->StartAssertNoThreadSuspension("Debugger: GetThreadGroupName");
1722 mirror::Class* c = soa.Decode<mirror::Class*>(WellKnownClasses::java_lang_ThreadGroup);
1723 CHECK(c != nullptr);
Brian Carlstromea46f952013-07-30 01:26:50 -07001724 mirror::ArtField* f = c->FindInstanceField("name", "Ljava/lang/String;");
Elliott Hughes499c5132011-11-17 14:55:11 -08001725 CHECK(f != NULL);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001726 mirror::String* s = reinterpret_cast<mirror::String*>(f->GetObject(thread_group));
Ian Rogers98379392014-02-24 16:53:16 -08001727 soa.Self()->EndAssertNoThreadSuspension(old_cause);
Elliott Hughes499c5132011-11-17 14:55:11 -08001728 return s->ToModifiedUtf8();
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001729}
1730
Elliott Hughes88d63092013-01-09 09:55:54 -08001731JDWP::ObjectId Dbg::GetThreadGroupParent(JDWP::ObjectId thread_group_id) {
Ian Rogers98379392014-02-24 16:53:16 -08001732 ScopedObjectAccessUnchecked soa(Thread::Current());
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001733 mirror::Object* thread_group = gRegistry->Get<mirror::Object*>(thread_group_id);
Ian Rogers98379392014-02-24 16:53:16 -08001734 CHECK(thread_group != nullptr);
1735 const char* old_cause = soa.Self()->StartAssertNoThreadSuspension("Debugger: GetThreadGroupParent");
1736 mirror::Class* c = soa.Decode<mirror::Class*>(WellKnownClasses::java_lang_ThreadGroup);
1737 CHECK(c != nullptr);
Brian Carlstromea46f952013-07-30 01:26:50 -07001738 mirror::ArtField* f = c->FindInstanceField("parent", "Ljava/lang/ThreadGroup;");
Elliott Hughes4e235312011-12-02 11:34:15 -08001739 CHECK(f != NULL);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001740 mirror::Object* parent = f->GetObject(thread_group);
Ian Rogers98379392014-02-24 16:53:16 -08001741 soa.Self()->EndAssertNoThreadSuspension(old_cause);
Elliott Hughes4e235312011-12-02 11:34:15 -08001742 return gRegistry->Add(parent);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001743}
1744
1745JDWP::ObjectId Dbg::GetSystemThreadGroupId() {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001746 ScopedObjectAccessUnchecked soa(Thread::Current());
Brian Carlstromea46f952013-07-30 01:26:50 -07001747 mirror::ArtField* f = soa.DecodeField(WellKnownClasses::java_lang_ThreadGroup_systemThreadGroup);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001748 mirror::Object* group = f->GetObject(f->GetDeclaringClass());
Ian Rogers365c1022012-06-22 15:05:28 -07001749 return gRegistry->Add(group);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001750}
1751
1752JDWP::ObjectId Dbg::GetMainThreadGroupId() {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001753 ScopedObjectAccess soa(Thread::Current());
Brian Carlstromea46f952013-07-30 01:26:50 -07001754 mirror::ArtField* f = soa.DecodeField(WellKnownClasses::java_lang_ThreadGroup_mainThreadGroup);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001755 mirror::Object* group = f->GetObject(f->GetDeclaringClass());
Ian Rogers365c1022012-06-22 15:05:28 -07001756 return gRegistry->Add(group);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001757}
1758
Jeff Hao920af3e2013-08-28 15:46:38 -07001759JDWP::JdwpThreadStatus Dbg::ToJdwpThreadStatus(ThreadState state) {
1760 switch (state) {
1761 case kBlocked:
1762 return JDWP::TS_MONITOR;
1763 case kNative:
1764 case kRunnable:
1765 case kSuspended:
1766 return JDWP::TS_RUNNING;
1767 case kSleeping:
1768 return JDWP::TS_SLEEPING;
1769 case kStarting:
1770 case kTerminated:
1771 return JDWP::TS_ZOMBIE;
1772 case kTimedWaiting:
1773 case kWaitingForDebuggerSend:
1774 case kWaitingForDebuggerSuspension:
1775 case kWaitingForDebuggerToAttach:
Sebastien Hertz138dbfc2013-12-04 18:15:25 +01001776 case kWaitingForDeoptimization:
Jeff Hao920af3e2013-08-28 15:46:38 -07001777 case kWaitingForGcToComplete:
1778 case kWaitingForCheckPointsToRun:
1779 case kWaitingForJniOnLoad:
1780 case kWaitingForSignalCatcherOutput:
1781 case kWaitingInMainDebuggerLoop:
1782 case kWaitingInMainSignalCatcherLoop:
1783 case kWaitingPerformingGc:
1784 case kWaiting:
1785 return JDWP::TS_WAIT;
1786 // Don't add a 'default' here so the compiler can spot incompatible enum changes.
1787 }
1788 LOG(FATAL) << "Unknown thread state: " << state;
1789 return JDWP::TS_ZOMBIE;
1790}
1791
Elliott Hughes221229c2013-01-08 18:17:50 -08001792JDWP::JdwpError Dbg::GetThreadStatus(JDWP::ObjectId thread_id, JDWP::JdwpThreadStatus* pThreadStatus, JDWP::JdwpSuspendStatus* pSuspendStatus) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001793 ScopedObjectAccess soa(Thread::Current());
Elliott Hughes499c5132011-11-17 14:55:11 -08001794
Elliott Hughes9e0c1752013-01-09 14:02:58 -08001795 *pSuspendStatus = JDWP::SUSPEND_STATUS_NOT_SUSPENDED;
1796
Ian Rogers50b35e22012-10-04 10:09:15 -07001797 MutexLock mu(soa.Self(), *Locks::thread_list_lock_);
Elliott Hughes221229c2013-01-08 18:17:50 -08001798 Thread* thread;
1799 JDWP::JdwpError error = DecodeThread(soa, thread_id, thread);
1800 if (error != JDWP::ERR_NONE) {
1801 if (error == JDWP::ERR_THREAD_NOT_ALIVE) {
1802 *pThreadStatus = JDWP::TS_ZOMBIE;
Elliott Hughes221229c2013-01-08 18:17:50 -08001803 return JDWP::ERR_NONE;
1804 }
1805 return error;
Elliott Hughes499c5132011-11-17 14:55:11 -08001806 }
1807
Elliott Hughes9e0c1752013-01-09 14:02:58 -08001808 if (IsSuspendedForDebugger(soa, thread)) {
1809 *pSuspendStatus = JDWP::SUSPEND_STATUS_SUSPENDED;
Elliott Hughes499c5132011-11-17 14:55:11 -08001810 }
1811
Jeff Hao920af3e2013-08-28 15:46:38 -07001812 *pThreadStatus = ToJdwpThreadStatus(thread->GetState());
Elliott Hughes221229c2013-01-08 18:17:50 -08001813 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001814}
1815
Elliott Hughes221229c2013-01-08 18:17:50 -08001816JDWP::JdwpError Dbg::GetThreadDebugSuspendCount(JDWP::ObjectId thread_id, JDWP::ExpandBuf* pReply) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001817 ScopedObjectAccess soa(Thread::Current());
Ian Rogers50b35e22012-10-04 10:09:15 -07001818 MutexLock mu(soa.Self(), *Locks::thread_list_lock_);
Elliott Hughes221229c2013-01-08 18:17:50 -08001819 Thread* thread;
1820 JDWP::JdwpError error = DecodeThread(soa, thread_id, thread);
1821 if (error != JDWP::ERR_NONE) {
1822 return error;
Elliott Hughes2435a572012-02-17 16:07:41 -08001823 }
Ian Rogers50b35e22012-10-04 10:09:15 -07001824 MutexLock mu2(soa.Self(), *Locks::thread_suspend_count_lock_);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001825 expandBufAdd4BE(pReply, thread->GetDebugSuspendCount());
Elliott Hughes2435a572012-02-17 16:07:41 -08001826 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001827}
1828
Elliott Hughesf9501702013-01-11 11:22:27 -08001829JDWP::JdwpError Dbg::Interrupt(JDWP::ObjectId thread_id) {
1830 ScopedObjectAccess soa(Thread::Current());
1831 MutexLock mu(soa.Self(), *Locks::thread_list_lock_);
1832 Thread* thread;
1833 JDWP::JdwpError error = DecodeThread(soa, thread_id, thread);
1834 if (error != JDWP::ERR_NONE) {
1835 return error;
1836 }
1837 thread->Interrupt();
1838 return JDWP::ERR_NONE;
1839}
1840
Elliott Hughescaf76542012-06-28 16:08:22 -07001841void Dbg::GetThreads(JDWP::ObjectId thread_group_id, std::vector<JDWP::ObjectId>& thread_ids) {
Ian Rogers365c1022012-06-22 15:05:28 -07001842 class ThreadListVisitor {
1843 public:
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001844 ThreadListVisitor(const ScopedObjectAccessUnchecked& soa, mirror::Object* desired_thread_group,
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001845 std::vector<JDWP::ObjectId>& thread_ids)
Ian Rogersb726dcb2012-09-05 08:57:23 -07001846 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_)
jeffhao0dfbb7e2012-11-28 15:26:03 -08001847 : soa_(soa), desired_thread_group_(desired_thread_group), thread_ids_(thread_ids) {}
Ian Rogers365c1022012-06-22 15:05:28 -07001848
Elliott Hughesa2155262011-11-16 16:26:58 -08001849 static void Visit(Thread* t, void* arg) {
1850 reinterpret_cast<ThreadListVisitor*>(arg)->Visit(t);
1851 }
1852
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001853 // TODO: Enable annotalysis. We know lock is held in constructor, but abstraction confuses
1854 // annotalysis.
1855 void Visit(Thread* t) NO_THREAD_SAFETY_ANALYSIS {
Elliott Hughesa2155262011-11-16 16:26:58 -08001856 if (t == Dbg::GetDebugThread()) {
1857 // Skip the JDWP thread. Some debuggers get bent out of shape when they can't suspend and
1858 // query all threads, so it's easier if we just don't tell them about this thread.
1859 return;
1860 }
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001861 mirror::Object* peer = t->GetPeer();
jeffhao0dfbb7e2012-11-28 15:26:03 -08001862 if (IsInDesiredThreadGroup(peer)) {
Ian Rogers120f1c72012-09-28 17:17:10 -07001863 thread_ids_.push_back(gRegistry->Add(peer));
Elliott Hughesa2155262011-11-16 16:26:58 -08001864 }
1865 }
1866
Ian Rogers365c1022012-06-22 15:05:28 -07001867 private:
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001868 bool IsInDesiredThreadGroup(mirror::Object* peer)
jeffhao0dfbb7e2012-11-28 15:26:03 -08001869 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
jeffhao0dfbb7e2012-11-28 15:26:03 -08001870 // peer might be NULL if the thread is still starting up.
1871 if (peer == NULL) {
1872 // We can't tell the debugger about this thread yet.
1873 // TODO: if we identified threads to the debugger by their Thread*
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001874 // rather than their peer's mirror::Object*, we could fix this.
jeffhao0dfbb7e2012-11-28 15:26:03 -08001875 // Doing so might help us report ZOMBIE threads too.
1876 return false;
1877 }
jeffhaoc1e04902012-12-13 12:41:10 -08001878 // Do we want threads from all thread groups?
1879 if (desired_thread_group_ == NULL) {
1880 return true;
1881 }
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001882 mirror::Object* group = soa_.DecodeField(WellKnownClasses::java_lang_Thread_group)->GetObject(peer);
jeffhao0dfbb7e2012-11-28 15:26:03 -08001883 return (group == desired_thread_group_);
1884 }
1885
Mathieu Chartierdbe6f462012-09-25 16:54:50 -07001886 const ScopedObjectAccessUnchecked& soa_;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001887 mirror::Object* const desired_thread_group_;
Elliott Hughescaf76542012-06-28 16:08:22 -07001888 std::vector<JDWP::ObjectId>& thread_ids_;
Elliott Hughesa2155262011-11-16 16:26:58 -08001889 };
1890
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001891 ScopedObjectAccessUnchecked soa(Thread::Current());
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001892 mirror::Object* thread_group = gRegistry->Get<mirror::Object*>(thread_group_id);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001893 ThreadListVisitor tlv(soa, thread_group, thread_ids);
Ian Rogers50b35e22012-10-04 10:09:15 -07001894 MutexLock mu(soa.Self(), *Locks::thread_list_lock_);
Elliott Hughesf8349362012-06-18 15:00:06 -07001895 Runtime::Current()->GetThreadList()->ForEach(ThreadListVisitor::Visit, &tlv);
Elliott Hughescaf76542012-06-28 16:08:22 -07001896}
Elliott Hughesa2155262011-11-16 16:26:58 -08001897
Elliott Hughescaf76542012-06-28 16:08:22 -07001898void Dbg::GetChildThreadGroups(JDWP::ObjectId thread_group_id, std::vector<JDWP::ObjectId>& child_thread_group_ids) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001899 ScopedObjectAccess soa(Thread::Current());
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001900 mirror::Object* thread_group = gRegistry->Get<mirror::Object*>(thread_group_id);
Elliott Hughescaf76542012-06-28 16:08:22 -07001901
1902 // Get the ArrayList<ThreadGroup> "groups" out of this thread group...
Brian Carlstromea46f952013-07-30 01:26:50 -07001903 mirror::ArtField* groups_field = thread_group->GetClass()->FindInstanceField("groups", "Ljava/util/List;");
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001904 mirror::Object* groups_array_list = groups_field->GetObject(thread_group);
Elliott Hughescaf76542012-06-28 16:08:22 -07001905
1906 // Get the array and size out of the ArrayList<ThreadGroup>...
Brian Carlstromea46f952013-07-30 01:26:50 -07001907 mirror::ArtField* array_field = groups_array_list->GetClass()->FindInstanceField("array", "[Ljava/lang/Object;");
1908 mirror::ArtField* size_field = groups_array_list->GetClass()->FindInstanceField("size", "I");
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001909 mirror::ObjectArray<mirror::Object>* groups_array =
1910 array_field->GetObject(groups_array_list)->AsObjectArray<mirror::Object>();
Elliott Hughescaf76542012-06-28 16:08:22 -07001911 const int32_t size = size_field->GetInt(groups_array_list);
1912
1913 // Copy the first 'size' elements out of the array into the result.
1914 for (int32_t i = 0; i < size; ++i) {
1915 child_thread_group_ids.push_back(gRegistry->Add(groups_array->Get(i)));
Elliott Hughesa2155262011-11-16 16:26:58 -08001916 }
1917}
1918
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001919static int GetStackDepth(Thread* thread)
Ian Rogersb726dcb2012-09-05 08:57:23 -07001920 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Ian Rogers0399dde2012-06-06 17:09:28 -07001921 struct CountStackDepthVisitor : public StackVisitor {
Brian Carlstrom93ba8932013-07-17 21:31:49 -07001922 explicit CountStackDepthVisitor(Thread* thread)
Ian Rogers7a22fa62013-01-23 12:16:16 -08001923 : StackVisitor(thread, NULL), depth(0) {}
Ian Rogers0399dde2012-06-06 17:09:28 -07001924
Elliott Hughes64f574f2013-02-20 14:57:12 -08001925 // TODO: Enable annotalysis. We know lock is held in constructor, but abstraction confuses
1926 // annotalysis.
1927 bool VisitFrame() NO_THREAD_SAFETY_ANALYSIS {
Ian Rogers0399dde2012-06-06 17:09:28 -07001928 if (!GetMethod()->IsRuntimeMethod()) {
Elliott Hughesf8a2df72011-12-01 12:19:54 -08001929 ++depth;
1930 }
Elliott Hughes530fa002012-03-12 11:44:49 -07001931 return true;
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001932 }
1933 size_t depth;
1934 };
Elliott Hughes08fc03a2012-06-26 17:34:00 -07001935
Ian Rogers7a22fa62013-01-23 12:16:16 -08001936 CountStackDepthVisitor visitor(thread);
Ian Rogers0399dde2012-06-06 17:09:28 -07001937 visitor.WalkStack();
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001938 return visitor.depth;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001939}
1940
Elliott Hughes221229c2013-01-08 18:17:50 -08001941JDWP::JdwpError Dbg::GetThreadFrameCount(JDWP::ObjectId thread_id, size_t& result) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001942 ScopedObjectAccess soa(Thread::Current());
jeffhaoa77f0f62012-12-05 17:19:31 -08001943 MutexLock mu(soa.Self(), *Locks::thread_list_lock_);
Elliott Hughes221229c2013-01-08 18:17:50 -08001944 Thread* thread;
1945 JDWP::JdwpError error = DecodeThread(soa, thread_id, thread);
1946 if (error != JDWP::ERR_NONE) {
1947 return error;
1948 }
Elliott Hughesf15f4a02013-01-09 10:09:38 -08001949 if (!IsSuspendedForDebugger(soa, thread)) {
1950 return JDWP::ERR_THREAD_NOT_SUSPENDED;
1951 }
Elliott Hughes221229c2013-01-08 18:17:50 -08001952 result = GetStackDepth(thread);
1953 return JDWP::ERR_NONE;
Elliott Hughes86964332012-02-15 19:37:42 -08001954}
1955
Ian Rogers306057f2012-11-26 12:45:53 -08001956JDWP::JdwpError Dbg::GetThreadFrames(JDWP::ObjectId thread_id, size_t start_frame,
1957 size_t frame_count, JDWP::ExpandBuf* buf) {
Elliott Hughes6e9d22c2012-06-22 15:02:37 -07001958 class GetFrameVisitor : public StackVisitor {
1959 public:
Ian Rogers7a22fa62013-01-23 12:16:16 -08001960 GetFrameVisitor(Thread* thread, size_t start_frame, size_t frame_count, JDWP::ExpandBuf* buf)
Ian Rogersb726dcb2012-09-05 08:57:23 -07001961 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_)
Ian Rogers7a22fa62013-01-23 12:16:16 -08001962 : StackVisitor(thread, NULL), depth_(0),
Elliott Hughes6e9d22c2012-06-22 15:02:37 -07001963 start_frame_(start_frame), frame_count_(frame_count), buf_(buf) {
1964 expandBufAdd4BE(buf_, frame_count_);
Elliott Hughes03181a82011-11-17 17:22:21 -08001965 }
Ian Rogers0399dde2012-06-06 17:09:28 -07001966
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001967 // TODO: Enable annotalysis. We know lock is held in constructor, but abstraction confuses
1968 // annotalysis.
1969 virtual bool VisitFrame() NO_THREAD_SAFETY_ANALYSIS {
Ian Rogers0399dde2012-06-06 17:09:28 -07001970 if (GetMethod()->IsRuntimeMethod()) {
Brian Carlstrom7934ac22013-07-26 10:54:15 -07001971 return true; // The debugger can't do anything useful with a frame that has no Method*.
Elliott Hughes03181a82011-11-17 17:22:21 -08001972 }
Elliott Hughes6e9d22c2012-06-22 15:02:37 -07001973 if (depth_ >= start_frame_ + frame_count_) {
Elliott Hughes530fa002012-03-12 11:44:49 -07001974 return false;
Elliott Hughes03181a82011-11-17 17:22:21 -08001975 }
Elliott Hughes6e9d22c2012-06-22 15:02:37 -07001976 if (depth_ >= start_frame_) {
1977 JDWP::FrameId frame_id(GetFrameId());
1978 JDWP::JdwpLocation location;
1979 SetLocation(location, GetMethod(), GetDexPc());
Ian Rogersef7d42f2014-01-06 12:55:46 -08001980 VLOG(jdwp) << StringPrintf(" Frame %3zd: id=%3" PRIu64 " ", depth_, frame_id) << location;
Elliott Hughes6e9d22c2012-06-22 15:02:37 -07001981 expandBufAdd8BE(buf_, frame_id);
1982 expandBufAddLocation(buf_, location);
1983 }
1984 ++depth_;
Elliott Hughes530fa002012-03-12 11:44:49 -07001985 return true;
Elliott Hughes03181a82011-11-17 17:22:21 -08001986 }
Elliott Hughes6e9d22c2012-06-22 15:02:37 -07001987
1988 private:
1989 size_t depth_;
1990 const size_t start_frame_;
1991 const size_t frame_count_;
1992 JDWP::ExpandBuf* buf_;
Elliott Hughes03181a82011-11-17 17:22:21 -08001993 };
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001994
1995 ScopedObjectAccessUnchecked soa(Thread::Current());
jeffhaoa77f0f62012-12-05 17:19:31 -08001996 MutexLock mu(soa.Self(), *Locks::thread_list_lock_);
Elliott Hughes221229c2013-01-08 18:17:50 -08001997 Thread* thread;
1998 JDWP::JdwpError error = DecodeThread(soa, thread_id, thread);
1999 if (error != JDWP::ERR_NONE) {
2000 return error;
2001 }
Elliott Hughesf15f4a02013-01-09 10:09:38 -08002002 if (!IsSuspendedForDebugger(soa, thread)) {
2003 return JDWP::ERR_THREAD_NOT_SUSPENDED;
2004 }
Ian Rogers7a22fa62013-01-23 12:16:16 -08002005 GetFrameVisitor visitor(thread, start_frame, frame_count, buf);
Ian Rogers0399dde2012-06-06 17:09:28 -07002006 visitor.WalkStack();
Elliott Hughes6e9d22c2012-06-22 15:02:37 -07002007 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002008}
2009
2010JDWP::ObjectId Dbg::GetThreadSelfId() {
Mathieu Chartierdbe6f462012-09-25 16:54:50 -07002011 ScopedObjectAccessUnchecked soa(Thread::Current());
Ian Rogerscfaa4552012-11-26 21:00:08 -08002012 return gRegistry->Add(soa.Self()->GetPeer());
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002013}
2014
Elliott Hughes475fc232011-10-25 15:00:35 -07002015void Dbg::SuspendVM() {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002016 Runtime::Current()->GetThreadList()->SuspendAllForDebugger();
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002017}
2018
2019void Dbg::ResumeVM() {
Elliott Hughesc61a2672012-06-21 14:52:29 -07002020 Runtime::Current()->GetThreadList()->UndoDebuggerSuspensions();
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002021}
2022
Elliott Hughes221229c2013-01-08 18:17:50 -08002023JDWP::JdwpError Dbg::SuspendThread(JDWP::ObjectId thread_id, bool request_suspension) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002024 ScopedLocalRef<jobject> peer(Thread::Current()->GetJniEnv(), NULL);
2025 {
2026 ScopedObjectAccess soa(Thread::Current());
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002027 peer.reset(soa.AddLocalReference<jobject>(gRegistry->Get<mirror::Object*>(thread_id)));
Elliott Hughes4e235312011-12-02 11:34:15 -08002028 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002029 if (peer.get() == NULL) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002030 return JDWP::ERR_THREAD_NOT_ALIVE;
2031 }
2032 // Suspend thread to build stack trace.
Elliott Hughesf327e072013-01-09 16:01:26 -08002033 bool timed_out;
Ian Rogersd9c4fc92013-10-01 19:45:43 -07002034 Thread* thread = ThreadList::SuspendThreadByPeer(peer.get(), request_suspension, true,
2035 &timed_out);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002036 if (thread != NULL) {
2037 return JDWP::ERR_NONE;
Elliott Hughesf327e072013-01-09 16:01:26 -08002038 } else if (timed_out) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002039 return JDWP::ERR_INTERNAL;
2040 } else {
2041 return JDWP::ERR_THREAD_NOT_ALIVE;
2042 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002043}
2044
Elliott Hughes221229c2013-01-08 18:17:50 -08002045void Dbg::ResumeThread(JDWP::ObjectId thread_id) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002046 ScopedObjectAccessUnchecked soa(Thread::Current());
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002047 mirror::Object* peer = gRegistry->Get<mirror::Object*>(thread_id);
jeffhaoa77f0f62012-12-05 17:19:31 -08002048 Thread* thread;
2049 {
2050 MutexLock mu(soa.Self(), *Locks::thread_list_lock_);
2051 thread = Thread::FromManagedThread(soa, peer);
2052 }
Elliott Hughes4e235312011-12-02 11:34:15 -08002053 if (thread == NULL) {
2054 LOG(WARNING) << "No such thread for resume: " << peer;
2055 return;
2056 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002057 bool needs_resume;
2058 {
Ian Rogers50b35e22012-10-04 10:09:15 -07002059 MutexLock mu2(soa.Self(), *Locks::thread_suspend_count_lock_);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002060 needs_resume = thread->GetSuspendCount() > 0;
2061 }
2062 if (needs_resume) {
Elliott Hughes546b9862012-06-20 16:06:13 -07002063 Runtime::Current()->GetThreadList()->Resume(thread, true);
2064 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002065}
2066
2067void Dbg::SuspendSelf() {
Elliott Hughes475fc232011-10-25 15:00:35 -07002068 Runtime::Current()->GetThreadList()->SuspendSelfForDebugger();
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002069}
2070
Ian Rogers0399dde2012-06-06 17:09:28 -07002071struct GetThisVisitor : public StackVisitor {
Ian Rogers7a22fa62013-01-23 12:16:16 -08002072 GetThisVisitor(Thread* thread, Context* context, JDWP::FrameId frame_id)
Ian Rogersb726dcb2012-09-05 08:57:23 -07002073 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_)
Ian Rogers7a22fa62013-01-23 12:16:16 -08002074 : StackVisitor(thread, context), this_object(NULL), frame_id(frame_id) {}
Ian Rogers0399dde2012-06-06 17:09:28 -07002075
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002076 // TODO: Enable annotalysis. We know lock is held in constructor, but abstraction confuses
2077 // annotalysis.
2078 virtual bool VisitFrame() NO_THREAD_SAFETY_ANALYSIS {
Elliott Hughes6e9d22c2012-06-22 15:02:37 -07002079 if (frame_id != GetFrameId()) {
Ian Rogers0399dde2012-06-06 17:09:28 -07002080 return true; // continue
Ian Rogers0399dde2012-06-06 17:09:28 -07002081 } else {
Ian Rogers62d6c772013-02-27 08:32:07 -08002082 this_object = GetThisObject();
2083 return false;
Ian Rogers0399dde2012-06-06 17:09:28 -07002084 }
Elliott Hughes86b00102011-12-05 17:54:26 -08002085 }
Ian Rogers0399dde2012-06-06 17:09:28 -07002086
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002087 mirror::Object* this_object;
Elliott Hughes6e9d22c2012-06-22 15:02:37 -07002088 JDWP::FrameId frame_id;
Ian Rogers0399dde2012-06-06 17:09:28 -07002089};
2090
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002091JDWP::JdwpError Dbg::GetThisObject(JDWP::ObjectId thread_id, JDWP::FrameId frame_id,
2092 JDWP::ObjectId* result) {
2093 ScopedObjectAccessUnchecked soa(Thread::Current());
2094 Thread* thread;
2095 {
Ian Rogers50b35e22012-10-04 10:09:15 -07002096 MutexLock mu(soa.Self(), *Locks::thread_list_lock_);
Elliott Hughes221229c2013-01-08 18:17:50 -08002097 JDWP::JdwpError error = DecodeThread(soa, thread_id, thread);
2098 if (error != JDWP::ERR_NONE) {
2099 return error;
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002100 }
Elliott Hughes9e0c1752013-01-09 14:02:58 -08002101 if (!IsSuspendedForDebugger(soa, thread)) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002102 return JDWP::ERR_THREAD_NOT_SUSPENDED;
2103 }
Elliott Hughes6e9d22c2012-06-22 15:02:37 -07002104 }
Elliott Hughescaf76542012-06-28 16:08:22 -07002105 UniquePtr<Context> context(Context::Create());
Ian Rogers7a22fa62013-01-23 12:16:16 -08002106 GetThisVisitor visitor(thread, context.get(), frame_id);
Ian Rogers0399dde2012-06-06 17:09:28 -07002107 visitor.WalkStack();
Elliott Hughes6e9d22c2012-06-22 15:02:37 -07002108 *result = gRegistry->Add(visitor.this_object);
2109 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002110}
2111
Ian Rogers98379392014-02-24 16:53:16 -08002112void Dbg::GetLocalValue(JDWP::ObjectId thread_id, JDWP::FrameId frame_id, int slot,
2113 JDWP::JdwpTag tag, uint8_t* buf, size_t width) {
Ian Rogers0399dde2012-06-06 17:09:28 -07002114 struct GetLocalVisitor : public StackVisitor {
Ian Rogers98379392014-02-24 16:53:16 -08002115 GetLocalVisitor(const ScopedObjectAccessUnchecked& soa, Thread* thread, Context* context,
2116 JDWP::FrameId frame_id, int slot, JDWP::JdwpTag tag, uint8_t* buf, size_t width)
Ian Rogersb726dcb2012-09-05 08:57:23 -07002117 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_)
Ian Rogers98379392014-02-24 16:53:16 -08002118 : StackVisitor(thread, context), soa_(soa), frame_id_(frame_id), slot_(slot), tag_(tag),
Ian Rogersca190662012-06-26 15:45:57 -07002119 buf_(buf), width_(width) {}
2120
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002121 // TODO: Enable annotalysis. We know lock is held in constructor, but abstraction confuses
2122 // annotalysis.
2123 bool VisitFrame() NO_THREAD_SAFETY_ANALYSIS {
Ian Rogers0399dde2012-06-06 17:09:28 -07002124 if (GetFrameId() != frame_id_) {
2125 return true; // Not our frame, carry on.
Elliott Hughesdbb40792011-11-18 17:05:22 -08002126 }
Ian Rogers0399dde2012-06-06 17:09:28 -07002127 // TODO: check that the tag is compatible with the actual type of the slot!
Brian Carlstromea46f952013-07-30 01:26:50 -07002128 mirror::ArtMethod* m = GetMethod();
Ian Rogers0399dde2012-06-06 17:09:28 -07002129 uint16_t reg = DemangleSlot(slot_, m);
Elliott Hughesdbb40792011-11-18 17:05:22 -08002130
Ian Rogers0399dde2012-06-06 17:09:28 -07002131 switch (tag_) {
2132 case JDWP::JT_BOOLEAN:
2133 {
2134 CHECK_EQ(width_, 1U);
Ian Rogers2bcb4a42012-11-08 10:39:18 -08002135 uint32_t intVal = GetVReg(m, reg, kIntVReg);
Ian Rogers0399dde2012-06-06 17:09:28 -07002136 VLOG(jdwp) << "get boolean local " << reg << " = " << intVal;
2137 JDWP::Set1(buf_+1, intVal != 0);
2138 }
2139 break;
2140 case JDWP::JT_BYTE:
2141 {
2142 CHECK_EQ(width_, 1U);
Ian Rogers2bcb4a42012-11-08 10:39:18 -08002143 uint32_t intVal = GetVReg(m, reg, kIntVReg);
Ian Rogers0399dde2012-06-06 17:09:28 -07002144 VLOG(jdwp) << "get byte local " << reg << " = " << intVal;
2145 JDWP::Set1(buf_+1, intVal);
2146 }
2147 break;
2148 case JDWP::JT_SHORT:
2149 case JDWP::JT_CHAR:
2150 {
2151 CHECK_EQ(width_, 2U);
Ian Rogers2bcb4a42012-11-08 10:39:18 -08002152 uint32_t intVal = GetVReg(m, reg, kIntVReg);
Ian Rogers0399dde2012-06-06 17:09:28 -07002153 VLOG(jdwp) << "get short/char local " << reg << " = " << intVal;
2154 JDWP::Set2BE(buf_+1, intVal);
2155 }
2156 break;
2157 case JDWP::JT_INT:
Ian Rogers2bcb4a42012-11-08 10:39:18 -08002158 {
2159 CHECK_EQ(width_, 4U);
2160 uint32_t intVal = GetVReg(m, reg, kIntVReg);
2161 VLOG(jdwp) << "get int local " << reg << " = " << intVal;
2162 JDWP::Set4BE(buf_+1, intVal);
2163 }
2164 break;
Ian Rogers0399dde2012-06-06 17:09:28 -07002165 case JDWP::JT_FLOAT:
2166 {
2167 CHECK_EQ(width_, 4U);
Ian Rogers2bcb4a42012-11-08 10:39:18 -08002168 uint32_t intVal = GetVReg(m, reg, kFloatVReg);
Ian Rogers0399dde2012-06-06 17:09:28 -07002169 VLOG(jdwp) << "get int/float local " << reg << " = " << intVal;
2170 JDWP::Set4BE(buf_+1, intVal);
2171 }
2172 break;
2173 case JDWP::JT_ARRAY:
2174 {
2175 CHECK_EQ(width_, sizeof(JDWP::ObjectId));
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002176 mirror::Object* o = reinterpret_cast<mirror::Object*>(GetVReg(m, reg, kReferenceVReg));
Ian Rogers0399dde2012-06-06 17:09:28 -07002177 VLOG(jdwp) << "get array local " << reg << " = " << o;
Mathieu Chartier590fee92013-09-13 13:46:47 -07002178 if (!Runtime::Current()->GetHeap()->IsValidObjectAddress(o)) {
Ian Rogers0399dde2012-06-06 17:09:28 -07002179 LOG(FATAL) << "Register " << reg << " expected to hold array: " << o;
2180 }
2181 JDWP::SetObjectId(buf_+1, gRegistry->Add(o));
2182 }
2183 break;
2184 case JDWP::JT_CLASS_LOADER:
2185 case JDWP::JT_CLASS_OBJECT:
2186 case JDWP::JT_OBJECT:
2187 case JDWP::JT_STRING:
2188 case JDWP::JT_THREAD:
2189 case JDWP::JT_THREAD_GROUP:
2190 {
2191 CHECK_EQ(width_, sizeof(JDWP::ObjectId));
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002192 mirror::Object* o = reinterpret_cast<mirror::Object*>(GetVReg(m, reg, kReferenceVReg));
Ian Rogers0399dde2012-06-06 17:09:28 -07002193 VLOG(jdwp) << "get object local " << reg << " = " << o;
Mathieu Chartier590fee92013-09-13 13:46:47 -07002194 if (!Runtime::Current()->GetHeap()->IsValidObjectAddress(o)) {
Ian Rogers0399dde2012-06-06 17:09:28 -07002195 LOG(FATAL) << "Register " << reg << " expected to hold object: " << o;
2196 }
Ian Rogers98379392014-02-24 16:53:16 -08002197 tag_ = TagFromObject(soa_, o);
Ian Rogers0399dde2012-06-06 17:09:28 -07002198 JDWP::SetObjectId(buf_+1, gRegistry->Add(o));
2199 }
2200 break;
2201 case JDWP::JT_DOUBLE:
Ian Rogers2bcb4a42012-11-08 10:39:18 -08002202 {
2203 CHECK_EQ(width_, 8U);
2204 uint32_t lo = GetVReg(m, reg, kDoubleLoVReg);
2205 uint64_t hi = GetVReg(m, reg + 1, kDoubleHiVReg);
2206 uint64_t longVal = (hi << 32) | lo;
2207 VLOG(jdwp) << "get double/long local " << hi << ":" << lo << " = " << longVal;
2208 JDWP::Set8BE(buf_+1, longVal);
2209 }
2210 break;
Ian Rogers0399dde2012-06-06 17:09:28 -07002211 case JDWP::JT_LONG:
2212 {
2213 CHECK_EQ(width_, 8U);
Ian Rogers2bcb4a42012-11-08 10:39:18 -08002214 uint32_t lo = GetVReg(m, reg, kLongLoVReg);
2215 uint64_t hi = GetVReg(m, reg + 1, kLongHiVReg);
Ian Rogers0399dde2012-06-06 17:09:28 -07002216 uint64_t longVal = (hi << 32) | lo;
2217 VLOG(jdwp) << "get double/long local " << hi << ":" << lo << " = " << longVal;
2218 JDWP::Set8BE(buf_+1, longVal);
2219 }
2220 break;
2221 default:
2222 LOG(FATAL) << "Unknown tag " << tag_;
2223 break;
2224 }
2225
2226 // Prepend tag, which may have been updated.
2227 JDWP::Set1(buf_, tag_);
2228 return false;
2229 }
Ian Rogers98379392014-02-24 16:53:16 -08002230 const ScopedObjectAccessUnchecked& soa_;
Ian Rogers0399dde2012-06-06 17:09:28 -07002231 const JDWP::FrameId frame_id_;
2232 const int slot_;
2233 JDWP::JdwpTag tag_;
2234 uint8_t* const buf_;
2235 const size_t width_;
2236 };
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002237
2238 ScopedObjectAccessUnchecked soa(Thread::Current());
jeffhaoa77f0f62012-12-05 17:19:31 -08002239 MutexLock mu(soa.Self(), *Locks::thread_list_lock_);
Elliott Hughes221229c2013-01-08 18:17:50 -08002240 Thread* thread;
2241 JDWP::JdwpError error = DecodeThread(soa, thread_id, thread);
2242 if (error != JDWP::ERR_NONE) {
2243 return;
2244 }
Ian Rogers0399dde2012-06-06 17:09:28 -07002245 UniquePtr<Context> context(Context::Create());
Ian Rogers98379392014-02-24 16:53:16 -08002246 GetLocalVisitor visitor(soa, thread, context.get(), frame_id, slot, tag, buf, width);
Ian Rogers0399dde2012-06-06 17:09:28 -07002247 visitor.WalkStack();
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002248}
2249
Elliott Hughes88d63092013-01-09 09:55:54 -08002250void Dbg::SetLocalValue(JDWP::ObjectId thread_id, JDWP::FrameId frame_id, int slot, JDWP::JdwpTag tag,
Ian Rogers0399dde2012-06-06 17:09:28 -07002251 uint64_t value, size_t width) {
2252 struct SetLocalVisitor : public StackVisitor {
Ian Rogers7a22fa62013-01-23 12:16:16 -08002253 SetLocalVisitor(Thread* thread, Context* context,
Ian Rogers0399dde2012-06-06 17:09:28 -07002254 JDWP::FrameId frame_id, int slot, JDWP::JdwpTag tag, uint64_t value,
Ian Rogersca190662012-06-26 15:45:57 -07002255 size_t width)
Ian Rogersb726dcb2012-09-05 08:57:23 -07002256 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_)
Ian Rogers7a22fa62013-01-23 12:16:16 -08002257 : StackVisitor(thread, context),
Elliott Hughes08fc03a2012-06-26 17:34:00 -07002258 frame_id_(frame_id), slot_(slot), tag_(tag), value_(value), width_(width) {}
Ian Rogersca190662012-06-26 15:45:57 -07002259
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002260 // TODO: Enable annotalysis. We know lock is held in constructor, but abstraction confuses
2261 // annotalysis.
2262 bool VisitFrame() NO_THREAD_SAFETY_ANALYSIS {
Ian Rogers0399dde2012-06-06 17:09:28 -07002263 if (GetFrameId() != frame_id_) {
2264 return true; // Not our frame, carry on.
2265 }
2266 // TODO: check that the tag is compatible with the actual type of the slot!
Brian Carlstromea46f952013-07-30 01:26:50 -07002267 mirror::ArtMethod* m = GetMethod();
Ian Rogers0399dde2012-06-06 17:09:28 -07002268 uint16_t reg = DemangleSlot(slot_, m);
2269
2270 switch (tag_) {
2271 case JDWP::JT_BOOLEAN:
2272 case JDWP::JT_BYTE:
2273 CHECK_EQ(width_, 1U);
Ian Rogers2bcb4a42012-11-08 10:39:18 -08002274 SetVReg(m, reg, static_cast<uint32_t>(value_), kIntVReg);
Ian Rogers0399dde2012-06-06 17:09:28 -07002275 break;
2276 case JDWP::JT_SHORT:
2277 case JDWP::JT_CHAR:
2278 CHECK_EQ(width_, 2U);
Ian Rogers2bcb4a42012-11-08 10:39:18 -08002279 SetVReg(m, reg, static_cast<uint32_t>(value_), kIntVReg);
Ian Rogers0399dde2012-06-06 17:09:28 -07002280 break;
2281 case JDWP::JT_INT:
Ian Rogers2bcb4a42012-11-08 10:39:18 -08002282 CHECK_EQ(width_, 4U);
2283 SetVReg(m, reg, static_cast<uint32_t>(value_), kIntVReg);
2284 break;
Ian Rogers0399dde2012-06-06 17:09:28 -07002285 case JDWP::JT_FLOAT:
2286 CHECK_EQ(width_, 4U);
Ian Rogers2bcb4a42012-11-08 10:39:18 -08002287 SetVReg(m, reg, static_cast<uint32_t>(value_), kFloatVReg);
Ian Rogers0399dde2012-06-06 17:09:28 -07002288 break;
2289 case JDWP::JT_ARRAY:
2290 case JDWP::JT_OBJECT:
2291 case JDWP::JT_STRING:
2292 {
2293 CHECK_EQ(width_, sizeof(JDWP::ObjectId));
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002294 mirror::Object* o = gRegistry->Get<mirror::Object*>(static_cast<JDWP::ObjectId>(value_));
Elliott Hughes64f574f2013-02-20 14:57:12 -08002295 if (o == ObjectRegistry::kInvalidObject) {
Ian Rogers0399dde2012-06-06 17:09:28 -07002296 UNIMPLEMENTED(FATAL) << "return an error code when given an invalid object to store";
2297 }
Ian Rogers2bcb4a42012-11-08 10:39:18 -08002298 SetVReg(m, reg, static_cast<uint32_t>(reinterpret_cast<uintptr_t>(o)), kReferenceVReg);
Ian Rogers0399dde2012-06-06 17:09:28 -07002299 }
2300 break;
2301 case JDWP::JT_DOUBLE:
Ian Rogers2bcb4a42012-11-08 10:39:18 -08002302 CHECK_EQ(width_, 8U);
2303 SetVReg(m, reg, static_cast<uint32_t>(value_), kDoubleLoVReg);
2304 SetVReg(m, reg + 1, static_cast<uint32_t>(value_ >> 32), kDoubleHiVReg);
2305 break;
Ian Rogers0399dde2012-06-06 17:09:28 -07002306 case JDWP::JT_LONG:
2307 CHECK_EQ(width_, 8U);
Ian Rogers2bcb4a42012-11-08 10:39:18 -08002308 SetVReg(m, reg, static_cast<uint32_t>(value_), kLongLoVReg);
2309 SetVReg(m, reg + 1, static_cast<uint32_t>(value_ >> 32), kLongHiVReg);
Ian Rogers0399dde2012-06-06 17:09:28 -07002310 break;
2311 default:
2312 LOG(FATAL) << "Unknown tag " << tag_;
2313 break;
2314 }
2315 return false;
2316 }
2317
2318 const JDWP::FrameId frame_id_;
2319 const int slot_;
2320 const JDWP::JdwpTag tag_;
2321 const uint64_t value_;
2322 const size_t width_;
2323 };
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002324
2325 ScopedObjectAccessUnchecked soa(Thread::Current());
jeffhaoa77f0f62012-12-05 17:19:31 -08002326 MutexLock mu(soa.Self(), *Locks::thread_list_lock_);
Elliott Hughes221229c2013-01-08 18:17:50 -08002327 Thread* thread;
2328 JDWP::JdwpError error = DecodeThread(soa, thread_id, thread);
2329 if (error != JDWP::ERR_NONE) {
2330 return;
2331 }
Elliott Hughes08fc03a2012-06-26 17:34:00 -07002332 UniquePtr<Context> context(Context::Create());
Ian Rogers7a22fa62013-01-23 12:16:16 -08002333 SetLocalVisitor visitor(thread, context.get(), frame_id, slot, tag, value, width);
Ian Rogers0399dde2012-06-06 17:09:28 -07002334 visitor.WalkStack();
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002335}
2336
Ian Rogersef7d42f2014-01-06 12:55:46 -08002337void Dbg::PostLocationEvent(mirror::ArtMethod* m, int dex_pc, mirror::Object* this_object,
Jeff Hao579b0242013-11-18 13:16:49 -08002338 int event_flags, const JValue* return_value) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002339 mirror::Class* c = m->GetDeclaringClass();
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08002340
2341 JDWP::JdwpLocation location;
Elliott Hughes74847412012-06-20 18:10:21 -07002342 location.type_tag = c->IsInterface() ? JDWP::TT_INTERFACE : JDWP::TT_CLASS;
Elliott Hughes64f574f2013-02-20 14:57:12 -08002343 location.class_id = gRegistry->AddRefType(c);
Elliott Hughes74847412012-06-20 18:10:21 -07002344 location.method_id = ToMethodId(m);
Elliott Hughes972a47b2012-02-21 18:16:06 -08002345 location.dex_pc = m->IsNative() ? -1 : dex_pc;
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08002346
Elliott Hughes64f574f2013-02-20 14:57:12 -08002347 // If 'this_object' isn't already in the registry, we know that we're not looking for it,
2348 // so there's no point adding it to the registry and burning through ids.
2349 JDWP::ObjectId this_id = 0;
2350 if (gRegistry->Contains(this_object)) {
2351 this_id = gRegistry->Add(this_object);
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08002352 }
Jeff Hao579b0242013-11-18 13:16:49 -08002353 gJdwpState->PostLocationEvent(&location, this_id, event_flags, return_value);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002354}
2355
Ian Rogers62d6c772013-02-27 08:32:07 -08002356void Dbg::PostException(Thread* thread, const ThrowLocation& throw_location,
Brian Carlstromea46f952013-07-30 01:26:50 -07002357 mirror::ArtMethod* catch_method,
Elliott Hughes64f574f2013-02-20 14:57:12 -08002358 uint32_t catch_dex_pc, mirror::Throwable* exception_object) {
Elliott Hughesc0f09332012-03-26 13:27:06 -07002359 if (!IsDebuggerActive()) {
Ian Rogers0ad5bb82011-12-07 10:16:32 -08002360 return;
2361 }
Elliott Hughes4740cdf2011-12-07 14:07:12 -08002362
Ian Rogers62d6c772013-02-27 08:32:07 -08002363 JDWP::JdwpLocation jdwp_throw_location;
2364 SetLocation(jdwp_throw_location, throw_location.GetMethod(), throw_location.GetDexPc());
Elliott Hughesd07986f2011-12-06 18:27:45 -08002365 JDWP::JdwpLocation catch_location;
Elliott Hughescaf76542012-06-28 16:08:22 -07002366 SetLocation(catch_location, catch_method, catch_dex_pc);
Elliott Hughesd07986f2011-12-06 18:27:45 -08002367
2368 // We need 'this' for InstanceOnly filters.
Ian Rogers62d6c772013-02-27 08:32:07 -08002369 JDWP::ObjectId this_id = gRegistry->Add(throw_location.GetThis());
Elliott Hughes64f574f2013-02-20 14:57:12 -08002370 JDWP::ObjectId exception_id = gRegistry->Add(exception_object);
2371 JDWP::RefTypeId exception_class_id = gRegistry->AddRefType(exception_object->GetClass());
Elliott Hughesd07986f2011-12-06 18:27:45 -08002372
Ian Rogers62d6c772013-02-27 08:32:07 -08002373 gJdwpState->PostException(&jdwp_throw_location, exception_id, exception_class_id, &catch_location,
2374 this_id);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002375}
2376
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002377void Dbg::PostClassPrepare(mirror::Class* c) {
Elliott Hughesc0f09332012-03-26 13:27:06 -07002378 if (!IsDebuggerActive()) {
Elliott Hughes4740cdf2011-12-07 14:07:12 -08002379 return;
2380 }
2381
Elliott Hughes3d30d9b2011-12-07 17:35:48 -08002382 // OLD-TODO - we currently always send both "verified" and "prepared" since
Elliott Hughes4740cdf2011-12-07 14:07:12 -08002383 // debuggers seem to like that. There might be some advantage to honesty,
2384 // since the class may not yet be verified.
2385 int state = JDWP::CS_VERIFIED | JDWP::CS_PREPARED;
2386 JDWP::JdwpTypeTag tag = c->IsInterface() ? JDWP::TT_INTERFACE : JDWP::TT_CLASS;
Ian Rogersfc0e94b2013-09-23 23:51:32 -07002387 gJdwpState->PostClassPrepare(tag, gRegistry->Add(c),
Ian Rogersdfb325e2013-10-30 01:00:44 -07002388 ClassHelper(c).GetDescriptor(), state);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002389}
2390
Ian Rogers62d6c772013-02-27 08:32:07 -08002391void Dbg::UpdateDebugger(Thread* thread, mirror::Object* this_object,
Ian Rogersef7d42f2014-01-06 12:55:46 -08002392 mirror::ArtMethod* m, uint32_t dex_pc) {
Ian Rogers62d6c772013-02-27 08:32:07 -08002393 if (!IsDebuggerActive() || dex_pc == static_cast<uint32_t>(-2) /* fake method exit */) {
Elliott Hughes2aa2e392012-02-17 17:15:43 -08002394 return;
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08002395 }
2396
Elliott Hughes2aa2e392012-02-17 17:15:43 -08002397 int event_flags = 0;
2398
Elliott Hughes86964332012-02-15 19:37:42 -08002399 if (IsBreakpoint(m, dex_pc)) {
2400 event_flags |= kBreakpoint;
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08002401 }
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08002402
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01002403 // If the debugger is single-stepping one of our threads, check to
2404 // see if we're that thread and we've reached a step point.
2405 const SingleStepControl* single_step_control = thread->GetSingleStepControl();
2406 DCHECK(single_step_control != nullptr);
2407 if (single_step_control->is_active) {
2408 CHECK(!m->IsNative());
2409 if (single_step_control->step_depth == JDWP::SD_INTO) {
2410 // Step into method calls. We break when the line number
2411 // or method pointer changes. If we're in SS_MIN mode, we
2412 // always stop.
2413 if (single_step_control->method != m) {
2414 event_flags |= kSingleStep;
2415 VLOG(jdwp) << "SS new method";
2416 } else if (single_step_control->step_size == JDWP::SS_MIN) {
2417 event_flags |= kSingleStep;
2418 VLOG(jdwp) << "SS new instruction";
2419 } else if (single_step_control->dex_pcs.find(dex_pc) == single_step_control->dex_pcs.end()) {
2420 event_flags |= kSingleStep;
2421 VLOG(jdwp) << "SS new line";
2422 }
2423 } else if (single_step_control->step_depth == JDWP::SD_OVER) {
2424 // Step over method calls. We break when the line number is
2425 // different and the frame depth is <= the original frame
2426 // depth. (We can't just compare on the method, because we
2427 // might get unrolled past it by an exception, and it's tricky
2428 // to identify recursion.)
2429
2430 int stack_depth = GetStackDepth(thread);
2431
2432 if (stack_depth < single_step_control->stack_depth) {
2433 // Popped up one or more frames, always trigger.
2434 event_flags |= kSingleStep;
2435 VLOG(jdwp) << "SS method pop";
2436 } else if (stack_depth == single_step_control->stack_depth) {
2437 // Same depth, see if we moved.
2438 if (single_step_control->step_size == JDWP::SS_MIN) {
Elliott Hughes86964332012-02-15 19:37:42 -08002439 event_flags |= kSingleStep;
2440 VLOG(jdwp) << "SS new instruction";
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01002441 } else if (single_step_control->dex_pcs.find(dex_pc) == single_step_control->dex_pcs.end()) {
Elliott Hughes2435a572012-02-17 16:07:41 -08002442 event_flags |= kSingleStep;
2443 VLOG(jdwp) << "SS new line";
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08002444 }
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01002445 }
2446 } else {
2447 CHECK_EQ(single_step_control->step_depth, JDWP::SD_OUT);
2448 // Return from the current method. We break when the frame
2449 // depth pops up.
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08002450
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01002451 // This differs from the "method exit" break in that it stops
2452 // with the PC at the next instruction in the returned-to
2453 // function, rather than the end of the returning function.
Elliott Hughes86964332012-02-15 19:37:42 -08002454
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01002455 int stack_depth = GetStackDepth(thread);
2456 if (stack_depth < single_step_control->stack_depth) {
2457 event_flags |= kSingleStep;
2458 VLOG(jdwp) << "SS method pop";
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08002459 }
2460 }
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08002461 }
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08002462
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08002463 // If there's something interesting going on, see if it matches one
2464 // of the debugger filters.
2465 if (event_flags != 0) {
Jeff Hao579b0242013-11-18 13:16:49 -08002466 Dbg::PostLocationEvent(m, dex_pc, this_object, event_flags, nullptr);
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08002467 }
2468}
2469
Sebastien Hertz138dbfc2013-12-04 18:15:25 +01002470static void ProcessDeoptimizationRequests()
2471 LOCKS_EXCLUDED(Locks::deoptimization_lock_)
2472 EXCLUSIVE_LOCKS_REQUIRED(Locks::mutator_lock_) {
2473 Locks::mutator_lock_->AssertExclusiveHeld(Thread::Current());
2474 MutexLock mu(Thread::Current(), *Locks::deoptimization_lock_);
2475 instrumentation::Instrumentation* instrumentation = Runtime::Current()->GetInstrumentation();
2476 for (const MethodInstrumentationRequest& request : gDeoptimizationRequests) {
2477 mirror::ArtMethod* const method = request.method;
2478 if (method != nullptr) {
2479 // Selective deoptimization.
2480 if (request.deoptimize) {
2481 VLOG(jdwp) << "Deoptimize method " << PrettyMethod(method);
2482 instrumentation->Deoptimize(method);
2483 } else {
2484 VLOG(jdwp) << "Undeoptimize method " << PrettyMethod(method);
2485 instrumentation->Undeoptimize(method);
2486 }
2487 } else {
2488 // Full deoptimization.
2489 if (request.deoptimize) {
2490 VLOG(jdwp) << "Deoptimize the world";
2491 instrumentation->DeoptimizeEverything();
2492 } else {
2493 VLOG(jdwp) << "Undeoptimize the world";
2494 instrumentation->UndeoptimizeEverything();
2495 }
2496 }
2497 }
2498 gDeoptimizationRequests.clear();
2499}
2500
2501// Process deoptimization requests after suspending all mutator threads.
2502void Dbg::ManageDeoptimization() {
2503 Thread* const self = Thread::Current();
2504 {
2505 // Avoid suspend/resume if there is no pending request.
2506 MutexLock mu(self, *Locks::deoptimization_lock_);
2507 if (gDeoptimizationRequests.empty()) {
2508 return;
2509 }
2510 }
2511 CHECK_EQ(self->GetState(), kRunnable);
2512 self->TransitionFromRunnableToSuspended(kWaitingForDeoptimization);
2513 // We need to suspend mutator threads first.
2514 Runtime* const runtime = Runtime::Current();
2515 runtime->GetThreadList()->SuspendAll();
2516 const ThreadState old_state = self->SetStateUnsafe(kRunnable);
2517 ProcessDeoptimizationRequests();
2518 CHECK_EQ(self->SetStateUnsafe(old_state), kRunnable);
2519 runtime->GetThreadList()->ResumeAll();
2520 self->TransitionFromSuspendedToRunnable();
2521}
2522
2523// Enable full deoptimization.
2524void Dbg::EnableFullDeoptimization() {
2525 MutexLock mu(Thread::Current(), *Locks::deoptimization_lock_);
2526 VLOG(jdwp) << "Request full deoptimization";
2527 gDeoptimizationRequests.push_back(MethodInstrumentationRequest(true, nullptr));
2528}
2529
2530// Disable full deoptimization.
2531void Dbg::DisableFullDeoptimization() {
2532 MutexLock mu(Thread::Current(), *Locks::deoptimization_lock_);
2533 VLOG(jdwp) << "Request full undeoptimization";
2534 gDeoptimizationRequests.push_back(MethodInstrumentationRequest(false, nullptr));
2535}
2536
Elliott Hughes86964332012-02-15 19:37:42 -08002537void Dbg::WatchLocation(const JDWP::JdwpLocation* location) {
Sebastien Hertz138dbfc2013-12-04 18:15:25 +01002538 bool need_deoptimization = true;
Brian Carlstromea46f952013-07-30 01:26:50 -07002539 mirror::ArtMethod* m = FromMethodId(location->method_id);
Sebastien Hertz138dbfc2013-12-04 18:15:25 +01002540 {
2541 MutexLock mu(Thread::Current(), *Locks::breakpoint_lock_);
2542
2543 // If there is no breakpoint on this method yet, we need to deoptimize it.
2544 for (const Breakpoint& breakpoint : gBreakpoints) {
2545 if (breakpoint.method == m) {
2546 // We already set a breakpoint on this method, hence we deoptimized it.
2547 DCHECK(Runtime::Current()->GetInstrumentation()->IsDeoptimized(m));
2548 need_deoptimization = false;
2549 break;
2550 }
2551 }
2552
2553 gBreakpoints.push_back(Breakpoint(m, location->dex_pc));
2554 VLOG(jdwp) << "Set breakpoint #" << (gBreakpoints.size() - 1) << ": " << gBreakpoints[gBreakpoints.size() - 1];
2555 }
2556
2557 if (need_deoptimization) {
2558 // Request its deoptimization. This will be done after updating the JDWP event list.
2559 MutexLock mu(Thread::Current(), *Locks::deoptimization_lock_);
2560 gDeoptimizationRequests.push_back(MethodInstrumentationRequest(true, m));
2561 VLOG(jdwp) << "Request deoptimization of " << PrettyMethod(m);
2562 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002563}
2564
Elliott Hughes86964332012-02-15 19:37:42 -08002565void Dbg::UnwatchLocation(const JDWP::JdwpLocation* location) {
Sebastien Hertz138dbfc2013-12-04 18:15:25 +01002566 bool can_undeoptimize = true;
Brian Carlstromea46f952013-07-30 01:26:50 -07002567 mirror::ArtMethod* m = FromMethodId(location->method_id);
Sebastien Hertz138dbfc2013-12-04 18:15:25 +01002568 DCHECK(Runtime::Current()->GetInstrumentation()->IsDeoptimized(m));
2569 {
2570 MutexLock mu(Thread::Current(), *Locks::breakpoint_lock_);
2571 for (size_t i = 0, e = gBreakpoints.size(); i < e; ++i) {
2572 if (gBreakpoints[i].method == m && gBreakpoints[i].dex_pc == location->dex_pc) {
2573 VLOG(jdwp) << "Removed breakpoint #" << i << ": " << gBreakpoints[i];
2574 gBreakpoints.erase(gBreakpoints.begin() + i);
2575 break;
2576 }
Elliott Hughes86964332012-02-15 19:37:42 -08002577 }
Sebastien Hertz138dbfc2013-12-04 18:15:25 +01002578
2579 // If there is no breakpoint on this method, we can undeoptimize it.
2580 for (const Breakpoint& breakpoint : gBreakpoints) {
2581 if (breakpoint.method == m) {
2582 can_undeoptimize = false;
2583 break;
2584 }
2585 }
2586 }
2587
2588 if (can_undeoptimize) {
2589 // Request its undeoptimization. This will be done after updating the JDWP event list.
2590 MutexLock mu(Thread::Current(), *Locks::deoptimization_lock_);
2591 gDeoptimizationRequests.push_back(MethodInstrumentationRequest(false, m));
2592 VLOG(jdwp) << "Request undeoptimization of " << PrettyMethod(m);
Elliott Hughes86964332012-02-15 19:37:42 -08002593 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002594}
2595
Jeff Hao449db332013-04-12 18:30:52 -07002596// Scoped utility class to suspend a thread so that we may do tasks such as walk its stack. Doesn't
2597// cause suspension if the thread is the current thread.
2598class ScopedThreadSuspension {
2599 public:
Ian Rogers33e95662013-05-20 20:29:14 -07002600 ScopedThreadSuspension(Thread* self, JDWP::ObjectId thread_id)
2601 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) :
Jeff Hao449db332013-04-12 18:30:52 -07002602 thread_(NULL),
2603 error_(JDWP::ERR_NONE),
2604 self_suspend_(false),
Ian Rogers33e95662013-05-20 20:29:14 -07002605 other_suspend_(false) {
Jeff Hao449db332013-04-12 18:30:52 -07002606 ScopedObjectAccessUnchecked soa(self);
2607 {
2608 MutexLock mu(soa.Self(), *Locks::thread_list_lock_);
2609 error_ = DecodeThread(soa, thread_id, thread_);
2610 }
2611 if (error_ == JDWP::ERR_NONE) {
2612 if (thread_ == soa.Self()) {
2613 self_suspend_ = true;
2614 } else {
2615 soa.Self()->TransitionFromRunnableToSuspended(kWaitingForDebuggerSuspension);
2616 jobject thread_peer = gRegistry->GetJObject(thread_id);
2617 bool timed_out;
Ian Rogersd9c4fc92013-10-01 19:45:43 -07002618 Thread* suspended_thread = ThreadList::SuspendThreadByPeer(thread_peer, true, true,
2619 &timed_out);
Jeff Hao449db332013-04-12 18:30:52 -07002620 CHECK_EQ(soa.Self()->TransitionFromSuspendedToRunnable(), kWaitingForDebuggerSuspension);
2621 if (suspended_thread == NULL) {
2622 // Thread terminated from under us while suspending.
2623 error_ = JDWP::ERR_INVALID_THREAD;
2624 } else {
2625 CHECK_EQ(suspended_thread, thread_);
2626 other_suspend_ = true;
2627 }
2628 }
2629 }
Elliott Hughes2435a572012-02-17 16:07:41 -08002630 }
Elliott Hughes86964332012-02-15 19:37:42 -08002631
Jeff Hao449db332013-04-12 18:30:52 -07002632 Thread* GetThread() const {
2633 return thread_;
2634 }
2635
2636 JDWP::JdwpError GetError() const {
2637 return error_;
2638 }
2639
2640 ~ScopedThreadSuspension() {
2641 if (other_suspend_) {
2642 Runtime::Current()->GetThreadList()->Resume(thread_, true);
2643 }
2644 }
2645
2646 private:
2647 Thread* thread_;
2648 JDWP::JdwpError error_;
2649 bool self_suspend_;
2650 bool other_suspend_;
2651};
2652
2653JDWP::JdwpError Dbg::ConfigureStep(JDWP::ObjectId thread_id, JDWP::JdwpStepSize step_size,
2654 JDWP::JdwpStepDepth step_depth) {
2655 Thread* self = Thread::Current();
2656 ScopedThreadSuspension sts(self, thread_id);
2657 if (sts.GetError() != JDWP::ERR_NONE) {
2658 return sts.GetError();
2659 }
2660
Elliott Hughes2435a572012-02-17 16:07:41 -08002661 //
2662 // Work out what Method* we're in, the current line number, and how deep the stack currently
2663 // is for step-out.
2664 //
2665
Ian Rogers0399dde2012-06-06 17:09:28 -07002666 struct SingleStepStackVisitor : public StackVisitor {
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01002667 explicit SingleStepStackVisitor(Thread* thread, SingleStepControl* single_step_control,
2668 int32_t* line_number)
Ian Rogersb726dcb2012-09-05 08:57:23 -07002669 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_)
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01002670 : StackVisitor(thread, NULL), single_step_control_(single_step_control),
2671 line_number_(line_number) {
2672 DCHECK_EQ(single_step_control_, thread->GetSingleStepControl());
2673 single_step_control_->method = NULL;
2674 single_step_control_->stack_depth = 0;
Elliott Hughes86964332012-02-15 19:37:42 -08002675 }
Ian Rogersca190662012-06-26 15:45:57 -07002676
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002677 // TODO: Enable annotalysis. We know lock is held in constructor, but abstraction confuses
2678 // annotalysis.
2679 bool VisitFrame() NO_THREAD_SAFETY_ANALYSIS {
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01002680 mirror::ArtMethod* m = GetMethod();
Ian Rogers0399dde2012-06-06 17:09:28 -07002681 if (!m->IsRuntimeMethod()) {
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01002682 ++single_step_control_->stack_depth;
2683 if (single_step_control_->method == NULL) {
Ian Rogersef7d42f2014-01-06 12:55:46 -08002684 mirror::DexCache* dex_cache = m->GetDeclaringClass()->GetDexCache();
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01002685 single_step_control_->method = m;
2686 *line_number_ = -1;
Elliott Hughes2435a572012-02-17 16:07:41 -08002687 if (dex_cache != NULL) {
Ian Rogers4445a7e2012-10-05 17:19:13 -07002688 const DexFile& dex_file = *dex_cache->GetDexFile();
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01002689 *line_number_ = dex_file.GetLineNumFromPC(m, GetDexPc());
Elliott Hughes2435a572012-02-17 16:07:41 -08002690 }
Elliott Hughes86964332012-02-15 19:37:42 -08002691 }
2692 }
Elliott Hughes530fa002012-03-12 11:44:49 -07002693 return true;
Elliott Hughes86964332012-02-15 19:37:42 -08002694 }
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01002695
2696 SingleStepControl* const single_step_control_;
2697 int32_t* const line_number_;
Elliott Hughes86964332012-02-15 19:37:42 -08002698 };
Jeff Hao449db332013-04-12 18:30:52 -07002699
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01002700 Thread* const thread = sts.GetThread();
2701 SingleStepControl* const single_step_control = thread->GetSingleStepControl();
2702 DCHECK(single_step_control != nullptr);
2703 int32_t line_number = -1;
2704 SingleStepStackVisitor visitor(thread, single_step_control, &line_number);
Ian Rogers0399dde2012-06-06 17:09:28 -07002705 visitor.WalkStack();
Elliott Hughes86964332012-02-15 19:37:42 -08002706
Elliott Hughes2435a572012-02-17 16:07:41 -08002707 //
2708 // Find the dex_pc values that correspond to the current line, for line-based single-stepping.
2709 //
2710
2711 struct DebugCallbackContext {
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01002712 explicit DebugCallbackContext(SingleStepControl* single_step_control, int32_t line_number)
2713 : single_step_control_(single_step_control), line_number_(line_number),
2714 last_pc_valid(false), last_pc(0) {
Elliott Hughes2435a572012-02-17 16:07:41 -08002715 }
2716
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01002717 static bool Callback(void* raw_context, uint32_t address, uint32_t line_number) {
Elliott Hughes2435a572012-02-17 16:07:41 -08002718 DebugCallbackContext* context = reinterpret_cast<DebugCallbackContext*>(raw_context);
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01002719 if (static_cast<int32_t>(line_number) == context->line_number_) {
Elliott Hughes2435a572012-02-17 16:07:41 -08002720 if (!context->last_pc_valid) {
2721 // Everything from this address until the next line change is ours.
2722 context->last_pc = address;
2723 context->last_pc_valid = true;
2724 }
2725 // Otherwise, if we're already in a valid range for this line,
2726 // just keep going (shouldn't really happen)...
Brian Carlstrom7934ac22013-07-26 10:54:15 -07002727 } else if (context->last_pc_valid) { // and the line number is new
Elliott Hughes2435a572012-02-17 16:07:41 -08002728 // Add everything from the last entry up until here to the set
2729 for (uint32_t dex_pc = context->last_pc; dex_pc < address; ++dex_pc) {
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01002730 context->single_step_control_->dex_pcs.insert(dex_pc);
Elliott Hughes2435a572012-02-17 16:07:41 -08002731 }
2732 context->last_pc_valid = false;
2733 }
Brian Carlstrom7934ac22013-07-26 10:54:15 -07002734 return false; // There may be multiple entries for any given line.
Elliott Hughes2435a572012-02-17 16:07:41 -08002735 }
2736
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01002737 ~DebugCallbackContext() {
Elliott Hughes2435a572012-02-17 16:07:41 -08002738 // If the line number was the last in the position table...
2739 if (last_pc_valid) {
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01002740 size_t end = MethodHelper(single_step_control_->method).GetCodeItem()->insns_size_in_code_units_;
Elliott Hughes2435a572012-02-17 16:07:41 -08002741 for (uint32_t dex_pc = last_pc; dex_pc < end; ++dex_pc) {
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01002742 single_step_control_->dex_pcs.insert(dex_pc);
Elliott Hughes2435a572012-02-17 16:07:41 -08002743 }
2744 }
2745 }
2746
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01002747 SingleStepControl* const single_step_control_;
2748 const int32_t line_number_;
Elliott Hughes2435a572012-02-17 16:07:41 -08002749 bool last_pc_valid;
2750 uint32_t last_pc;
2751 };
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01002752 single_step_control->dex_pcs.clear();
Ian Rogersef7d42f2014-01-06 12:55:46 -08002753 mirror::ArtMethod* m = single_step_control->method;
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01002754 if (!m->IsNative()) {
2755 DebugCallbackContext context(single_step_control, line_number);
Elliott Hughes3e2e1a22012-02-21 11:33:41 -08002756 MethodHelper mh(m);
2757 mh.GetDexFile().DecodeDebugInfo(mh.GetCodeItem(), m->IsStatic(), m->GetDexMethodIndex(),
2758 DebugCallbackContext::Callback, NULL, &context);
2759 }
Elliott Hughes2435a572012-02-17 16:07:41 -08002760
2761 //
2762 // Everything else...
2763 //
2764
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01002765 single_step_control->step_size = step_size;
2766 single_step_control->step_depth = step_depth;
2767 single_step_control->is_active = true;
Elliott Hughes86964332012-02-15 19:37:42 -08002768
Elliott Hughes2435a572012-02-17 16:07:41 -08002769 if (VLOG_IS_ON(jdwp)) {
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01002770 VLOG(jdwp) << "Single-step thread: " << *thread;
2771 VLOG(jdwp) << "Single-step step size: " << single_step_control->step_size;
2772 VLOG(jdwp) << "Single-step step depth: " << single_step_control->step_depth;
2773 VLOG(jdwp) << "Single-step current method: " << PrettyMethod(single_step_control->method);
2774 VLOG(jdwp) << "Single-step current line: " << line_number;
2775 VLOG(jdwp) << "Single-step current stack depth: " << single_step_control->stack_depth;
Elliott Hughes2435a572012-02-17 16:07:41 -08002776 VLOG(jdwp) << "Single-step dex_pc values:";
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01002777 for (std::set<uint32_t>::iterator it = single_step_control->dex_pcs.begin(); it != single_step_control->dex_pcs.end(); ++it) {
Elliott Hughes229feb72012-02-23 13:33:29 -08002778 VLOG(jdwp) << StringPrintf(" %#x", *it);
Elliott Hughes2435a572012-02-17 16:07:41 -08002779 }
2780 }
2781
2782 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002783}
2784
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01002785void Dbg::UnconfigureStep(JDWP::ObjectId thread_id) {
2786 ScopedObjectAccessUnchecked soa(Thread::Current());
2787 MutexLock mu(soa.Self(), *Locks::thread_list_lock_);
2788 Thread* thread;
2789 JDWP::JdwpError error = DecodeThread(soa, thread_id, thread);
Sebastien Hertz87118ed2013-11-26 17:57:18 +01002790 if (error == JDWP::ERR_NONE) {
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01002791 SingleStepControl* single_step_control = thread->GetSingleStepControl();
2792 DCHECK(single_step_control != nullptr);
2793 single_step_control->is_active = false;
2794 single_step_control->dex_pcs.clear();
2795 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002796}
2797
Elliott Hughes45651fd2012-02-21 15:48:20 -08002798static char JdwpTagToShortyChar(JDWP::JdwpTag tag) {
2799 switch (tag) {
2800 default:
2801 LOG(FATAL) << "unknown JDWP tag: " << PrintableChar(tag);
2802
2803 // Primitives.
2804 case JDWP::JT_BYTE: return 'B';
2805 case JDWP::JT_CHAR: return 'C';
2806 case JDWP::JT_FLOAT: return 'F';
2807 case JDWP::JT_DOUBLE: return 'D';
2808 case JDWP::JT_INT: return 'I';
2809 case JDWP::JT_LONG: return 'J';
2810 case JDWP::JT_SHORT: return 'S';
2811 case JDWP::JT_VOID: return 'V';
2812 case JDWP::JT_BOOLEAN: return 'Z';
2813
2814 // Reference types.
2815 case JDWP::JT_ARRAY:
2816 case JDWP::JT_OBJECT:
2817 case JDWP::JT_STRING:
2818 case JDWP::JT_THREAD:
2819 case JDWP::JT_THREAD_GROUP:
2820 case JDWP::JT_CLASS_LOADER:
2821 case JDWP::JT_CLASS_OBJECT:
2822 return 'L';
2823 }
2824}
2825
Elliott Hughes88d63092013-01-09 09:55:54 -08002826JDWP::JdwpError Dbg::InvokeMethod(JDWP::ObjectId thread_id, JDWP::ObjectId object_id,
2827 JDWP::RefTypeId class_id, JDWP::MethodId method_id,
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002828 uint32_t arg_count, uint64_t* arg_values,
2829 JDWP::JdwpTag* arg_types, uint32_t options,
2830 JDWP::JdwpTag* pResultTag, uint64_t* pResultValue,
2831 JDWP::ObjectId* pExceptionId) {
Elliott Hughesd07986f2011-12-06 18:27:45 -08002832 ThreadList* thread_list = Runtime::Current()->GetThreadList();
2833
2834 Thread* targetThread = NULL;
2835 DebugInvokeReq* req = NULL;
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002836 Thread* self = Thread::Current();
Elliott Hughesd07986f2011-12-06 18:27:45 -08002837 {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002838 ScopedObjectAccessUnchecked soa(self);
Ian Rogers50b35e22012-10-04 10:09:15 -07002839 MutexLock mu(soa.Self(), *Locks::thread_list_lock_);
Elliott Hughes221229c2013-01-08 18:17:50 -08002840 JDWP::JdwpError error = DecodeThread(soa, thread_id, targetThread);
2841 if (error != JDWP::ERR_NONE) {
2842 LOG(ERROR) << "InvokeMethod request for invalid thread id " << thread_id;
2843 return error;
Elliott Hughesd07986f2011-12-06 18:27:45 -08002844 }
2845 req = targetThread->GetInvokeReq();
2846 if (!req->ready) {
2847 LOG(ERROR) << "InvokeMethod request for thread not stopped by event: " << *targetThread;
2848 return JDWP::ERR_INVALID_THREAD;
2849 }
2850
2851 /*
2852 * We currently have a bug where we don't successfully resume the
2853 * target thread if the suspend count is too deep. We're expected to
2854 * require one "resume" for each "suspend", but when asked to execute
2855 * a method we have to resume fully and then re-suspend it back to the
2856 * same level. (The easiest way to cause this is to type "suspend"
2857 * multiple times in jdb.)
2858 *
2859 * It's unclear what this means when the event specifies "resume all"
2860 * and some threads are suspended more deeply than others. This is
2861 * a rare problem, so for now we just prevent it from hanging forever
2862 * by rejecting the method invocation request. Without this, we will
2863 * be stuck waiting on a suspended thread.
2864 */
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002865 int suspend_count;
2866 {
Ian Rogers50b35e22012-10-04 10:09:15 -07002867 MutexLock mu2(soa.Self(), *Locks::thread_suspend_count_lock_);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002868 suspend_count = targetThread->GetSuspendCount();
2869 }
Elliott Hughesd07986f2011-12-06 18:27:45 -08002870 if (suspend_count > 1) {
2871 LOG(ERROR) << *targetThread << " suspend count too deep for method invocation: " << suspend_count;
Brian Carlstrom7934ac22013-07-26 10:54:15 -07002872 return JDWP::ERR_THREAD_SUSPENDED; // Probably not expected here.
Elliott Hughesd07986f2011-12-06 18:27:45 -08002873 }
2874
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08002875 JDWP::JdwpError status;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002876 mirror::Object* receiver = gRegistry->Get<mirror::Object*>(object_id);
Elliott Hughes64f574f2013-02-20 14:57:12 -08002877 if (receiver == ObjectRegistry::kInvalidObject) {
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08002878 return JDWP::ERR_INVALID_OBJECT;
2879 }
Elliott Hughes45651fd2012-02-21 15:48:20 -08002880
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002881 mirror::Object* thread = gRegistry->Get<mirror::Object*>(thread_id);
Elliott Hughes64f574f2013-02-20 14:57:12 -08002882 if (thread == ObjectRegistry::kInvalidObject) {
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08002883 return JDWP::ERR_INVALID_OBJECT;
2884 }
Elliott Hughes45651fd2012-02-21 15:48:20 -08002885 // TODO: check that 'thread' is actually a java.lang.Thread!
2886
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002887 mirror::Class* c = DecodeClass(class_id, status);
Elliott Hughes45651fd2012-02-21 15:48:20 -08002888 if (c == NULL) {
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08002889 return status;
2890 }
Elliott Hughes45651fd2012-02-21 15:48:20 -08002891
Brian Carlstromea46f952013-07-30 01:26:50 -07002892 mirror::ArtMethod* m = FromMethodId(method_id);
Elliott Hughes45651fd2012-02-21 15:48:20 -08002893 if (m->IsStatic() != (receiver == NULL)) {
2894 return JDWP::ERR_INVALID_METHODID;
2895 }
2896 if (m->IsStatic()) {
2897 if (m->GetDeclaringClass() != c) {
2898 return JDWP::ERR_INVALID_METHODID;
2899 }
2900 } else {
2901 if (!m->GetDeclaringClass()->IsAssignableFrom(c)) {
2902 return JDWP::ERR_INVALID_METHODID;
2903 }
2904 }
2905
2906 // Check the argument list matches the method.
2907 MethodHelper mh(m);
2908 if (mh.GetShortyLength() - 1 != arg_count) {
2909 return JDWP::ERR_ILLEGAL_ARGUMENT;
2910 }
2911 const char* shorty = mh.GetShorty();
Elliott Hughes09201632013-04-15 15:50:07 -07002912 const DexFile::TypeList* types = mh.GetParameterTypeList();
Elliott Hughes45651fd2012-02-21 15:48:20 -08002913 for (size_t i = 0; i < arg_count; ++i) {
2914 if (shorty[i + 1] != JdwpTagToShortyChar(arg_types[i])) {
2915 return JDWP::ERR_ILLEGAL_ARGUMENT;
2916 }
Elliott Hughes09201632013-04-15 15:50:07 -07002917
2918 if (shorty[i + 1] == 'L') {
2919 // Did we really get an argument of an appropriate reference type?
2920 mirror::Class* parameter_type = mh.GetClassFromTypeIdx(types->GetTypeItem(i).type_idx_);
2921 mirror::Object* argument = gRegistry->Get<mirror::Object*>(arg_values[i]);
2922 if (argument == ObjectRegistry::kInvalidObject) {
2923 return JDWP::ERR_INVALID_OBJECT;
2924 }
Sebastien Hertz0630ab52013-11-28 18:53:35 +01002925 if (argument != NULL && !argument->InstanceOf(parameter_type)) {
Elliott Hughes09201632013-04-15 15:50:07 -07002926 return JDWP::ERR_ILLEGAL_ARGUMENT;
2927 }
2928
2929 // Turn the on-the-wire ObjectId into a jobject.
2930 jvalue& v = reinterpret_cast<jvalue&>(arg_values[i]);
2931 v.l = gRegistry->GetJObject(arg_values[i]);
2932 }
Elliott Hughes45651fd2012-02-21 15:48:20 -08002933 }
2934
Sebastien Hertzd38667a2013-11-25 15:43:54 +01002935 req->receiver = receiver;
2936 req->thread = thread;
2937 req->klass = c;
2938 req->method = m;
2939 req->arg_count = arg_count;
2940 req->arg_values = arg_values;
2941 req->options = options;
2942 req->invoke_needed = true;
Elliott Hughesd07986f2011-12-06 18:27:45 -08002943 }
2944
2945 // The fact that we've released the thread list lock is a bit risky --- if the thread goes
2946 // away we're sitting high and dry -- but we must release this before the ResumeAllThreads
2947 // call, and it's unwise to hold it during WaitForSuspend.
2948
2949 {
2950 /*
2951 * We change our (JDWP thread) status, which should be THREAD_RUNNING,
Elliott Hughes81ff3182012-03-23 20:35:56 -07002952 * so we can suspend for a GC if the invoke request causes us to
Elliott Hughesd07986f2011-12-06 18:27:45 -08002953 * run out of memory. It's also a good idea to change it before locking
2954 * the invokeReq mutex, although that should never be held for long.
2955 */
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002956 self->TransitionFromRunnableToSuspended(kWaitingForDebuggerSend);
Elliott Hughesd07986f2011-12-06 18:27:45 -08002957
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08002958 VLOG(jdwp) << " Transferring control to event thread";
Elliott Hughesd07986f2011-12-06 18:27:45 -08002959 {
Sebastien Hertzd38667a2013-11-25 15:43:54 +01002960 MutexLock mu(self, req->lock);
Elliott Hughesd07986f2011-12-06 18:27:45 -08002961
2962 if ((options & JDWP::INVOKE_SINGLE_THREADED) == 0) {
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08002963 VLOG(jdwp) << " Resuming all threads";
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002964 thread_list->UndoDebuggerSuspensions();
Elliott Hughesd07986f2011-12-06 18:27:45 -08002965 } else {
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08002966 VLOG(jdwp) << " Resuming event thread only";
Elliott Hughesd07986f2011-12-06 18:27:45 -08002967 thread_list->Resume(targetThread, true);
2968 }
2969
2970 // Wait for the request to finish executing.
Sebastien Hertzd38667a2013-11-25 15:43:54 +01002971 while (req->invoke_needed) {
2972 req->cond.Wait(self);
Elliott Hughesd07986f2011-12-06 18:27:45 -08002973 }
2974 }
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08002975 VLOG(jdwp) << " Control has returned from event thread";
Elliott Hughesd07986f2011-12-06 18:27:45 -08002976
2977 /* wait for thread to re-suspend itself */
Brian Carlstromdf629502013-07-17 22:39:56 -07002978 SuspendThread(thread_id, false /* request_suspension */);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002979 self->TransitionFromSuspendedToRunnable();
Elliott Hughesd07986f2011-12-06 18:27:45 -08002980 }
2981
2982 /*
2983 * Suspend the threads. We waited for the target thread to suspend
2984 * itself, so all we need to do is suspend the others.
2985 *
2986 * The suspendAllThreads() call will double-suspend the event thread,
2987 * so we want to resume the target thread once to keep the books straight.
2988 */
2989 if ((options & JDWP::INVOKE_SINGLE_THREADED) == 0) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002990 self->TransitionFromRunnableToSuspended(kWaitingForDebuggerSuspension);
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08002991 VLOG(jdwp) << " Suspending all threads";
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002992 thread_list->SuspendAllForDebugger();
2993 self->TransitionFromSuspendedToRunnable();
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08002994 VLOG(jdwp) << " Resuming event thread to balance the count";
Elliott Hughesd07986f2011-12-06 18:27:45 -08002995 thread_list->Resume(targetThread, true);
2996 }
2997
2998 // Copy the result.
2999 *pResultTag = req->result_tag;
3000 if (IsPrimitiveTag(req->result_tag)) {
Elliott Hughesf24d3ce2012-04-11 17:43:37 -07003001 *pResultValue = req->result_value.GetJ();
Elliott Hughesd07986f2011-12-06 18:27:45 -08003002 } else {
Elliott Hughesf24d3ce2012-04-11 17:43:37 -07003003 *pResultValue = gRegistry->Add(req->result_value.GetL());
Elliott Hughesd07986f2011-12-06 18:27:45 -08003004 }
3005 *pExceptionId = req->exception;
3006 return req->error;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07003007}
3008
3009void Dbg::ExecuteMethod(DebugInvokeReq* pReq) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07003010 ScopedObjectAccess soa(Thread::Current());
Elliott Hughesd07986f2011-12-06 18:27:45 -08003011
Elliott Hughes81ff3182012-03-23 20:35:56 -07003012 // We can be called while an exception is pending. We need
Elliott Hughesd07986f2011-12-06 18:27:45 -08003013 // to preserve that across the method invocation.
Ian Rogers62d6c772013-02-27 08:32:07 -08003014 SirtRef<mirror::Object> old_throw_this_object(soa.Self(), NULL);
Brian Carlstromea46f952013-07-30 01:26:50 -07003015 SirtRef<mirror::ArtMethod> old_throw_method(soa.Self(), NULL);
Ian Rogers62d6c772013-02-27 08:32:07 -08003016 SirtRef<mirror::Throwable> old_exception(soa.Self(), NULL);
3017 uint32_t old_throw_dex_pc;
3018 {
3019 ThrowLocation old_throw_location;
3020 mirror::Throwable* old_exception_obj = soa.Self()->GetException(&old_throw_location);
3021 old_throw_this_object.reset(old_throw_location.GetThis());
3022 old_throw_method.reset(old_throw_location.GetMethod());
3023 old_exception.reset(old_exception_obj);
3024 old_throw_dex_pc = old_throw_location.GetDexPc();
3025 soa.Self()->ClearException();
3026 }
Elliott Hughesd07986f2011-12-06 18:27:45 -08003027
3028 // Translate the method through the vtable, unless the debugger wants to suppress it.
Mathieu Chartierc528dba2013-11-26 12:00:11 -08003029 SirtRef<mirror::ArtMethod> m(soa.Self(), pReq->method);
Sebastien Hertzd38667a2013-11-25 15:43:54 +01003030 if ((pReq->options & JDWP::INVOKE_NONVIRTUAL) == 0 && pReq->receiver != NULL) {
3031 mirror::ArtMethod* actual_method = pReq->klass->FindVirtualMethodForVirtualOrInterface(pReq->method);
Mathieu Chartierc528dba2013-11-26 12:00:11 -08003032 if (actual_method != m.get()) {
3033 VLOG(jdwp) << "ExecuteMethod translated " << PrettyMethod(m.get()) << " to " << PrettyMethod(actual_method);
3034 m.reset(actual_method);
Elliott Hughes45651fd2012-02-21 15:48:20 -08003035 }
Elliott Hughesd07986f2011-12-06 18:27:45 -08003036 }
Mathieu Chartierc528dba2013-11-26 12:00:11 -08003037 VLOG(jdwp) << "ExecuteMethod " << PrettyMethod(m.get())
Sebastien Hertzd38667a2013-11-25 15:43:54 +01003038 << " receiver=" << pReq->receiver
3039 << " arg_count=" << pReq->arg_count;
Mathieu Chartierc528dba2013-11-26 12:00:11 -08003040 CHECK(m.get() != nullptr);
Elliott Hughesd07986f2011-12-06 18:27:45 -08003041
3042 CHECK_EQ(sizeof(jvalue), sizeof(uint64_t));
3043
Mathieu Chartierc528dba2013-11-26 12:00:11 -08003044 MethodHelper mh(m.get());
Jeff Hao5d917302013-02-27 17:57:33 -08003045 ArgArray arg_array(mh.GetShorty(), mh.GetShortyLength());
Sebastien Hertzd38667a2013-11-25 15:43:54 +01003046 arg_array.BuildArgArray(soa, pReq->receiver, reinterpret_cast<jvalue*>(pReq->arg_values));
Ian Rogers0177e532014-02-11 16:30:46 -08003047 InvokeWithArgArray(soa, m.get(), &arg_array, &pReq->result_value, mh.GetShorty());
Elliott Hughesd07986f2011-12-06 18:27:45 -08003048
Ian Rogers62d6c772013-02-27 08:32:07 -08003049 mirror::Throwable* exception = soa.Self()->GetException(NULL);
3050 soa.Self()->ClearException();
3051 pReq->exception = gRegistry->Add(exception);
Mathieu Chartierc528dba2013-11-26 12:00:11 -08003052 pReq->result_tag = BasicTagFromDescriptor(MethodHelper(m.get()).GetShorty());
Elliott Hughesd07986f2011-12-06 18:27:45 -08003053 if (pReq->exception != 0) {
Ian Rogers62d6c772013-02-27 08:32:07 -08003054 VLOG(jdwp) << " JDWP invocation returning with exception=" << exception
3055 << " " << exception->Dump();
Elliott Hughesf24d3ce2012-04-11 17:43:37 -07003056 pReq->result_value.SetJ(0);
Elliott Hughesd07986f2011-12-06 18:27:45 -08003057 } else if (pReq->result_tag == JDWP::JT_OBJECT) {
3058 /* if no exception thrown, examine object result more closely */
Ian Rogers98379392014-02-24 16:53:16 -08003059 JDWP::JdwpTag new_tag = TagFromObject(soa, pReq->result_value.GetL());
Elliott Hughesd07986f2011-12-06 18:27:45 -08003060 if (new_tag != pReq->result_tag) {
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08003061 VLOG(jdwp) << " JDWP promoted result from " << pReq->result_tag << " to " << new_tag;
Elliott Hughesd07986f2011-12-06 18:27:45 -08003062 pReq->result_tag = new_tag;
3063 }
3064
3065 /*
3066 * Register the object. We don't actually need an ObjectId yet,
3067 * but we do need to be sure that the GC won't move or discard the
3068 * object when we switch out of RUNNING. The ObjectId conversion
3069 * will add the object to the "do not touch" list.
3070 *
3071 * We can't use the "tracked allocation" mechanism here because
3072 * the object is going to be handed off to a different thread.
3073 */
Elliott Hughesf24d3ce2012-04-11 17:43:37 -07003074 gRegistry->Add(pReq->result_value.GetL());
Elliott Hughesd07986f2011-12-06 18:27:45 -08003075 }
3076
3077 if (old_exception.get() != NULL) {
Ian Rogers62d6c772013-02-27 08:32:07 -08003078 ThrowLocation gc_safe_throw_location(old_throw_this_object.get(), old_throw_method.get(),
3079 old_throw_dex_pc);
3080 soa.Self()->SetException(gc_safe_throw_location, old_exception.get());
Elliott Hughesd07986f2011-12-06 18:27:45 -08003081 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -07003082}
3083
Elliott Hughesd07986f2011-12-06 18:27:45 -08003084/*
Elliott Hughes4b9702c2013-02-20 18:13:24 -08003085 * "request" contains a full JDWP packet, possibly with multiple chunks. We
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07003086 * need to process each, accumulate the replies, and ship the whole thing
3087 * back.
3088 *
3089 * Returns "true" if we have a reply. The reply buffer is newly allocated,
3090 * and includes the chunk type/length, followed by the data.
3091 *
Elliott Hughes3d30d9b2011-12-07 17:35:48 -08003092 * OLD-TODO: we currently assume that the request and reply include a single
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07003093 * chunk. If this becomes inconvenient we will need to adapt.
3094 */
Elliott Hughes4b9702c2013-02-20 18:13:24 -08003095bool Dbg::DdmHandlePacket(JDWP::Request& request, uint8_t** pReplyBuf, int* pReplyLen) {
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07003096 Thread* self = Thread::Current();
3097 JNIEnv* env = self->GetJniEnv();
3098
Elliott Hughes4b9702c2013-02-20 18:13:24 -08003099 uint32_t type = request.ReadUnsigned32("type");
3100 uint32_t length = request.ReadUnsigned32("length");
3101
3102 // Create a byte[] corresponding to 'request'.
3103 size_t request_length = request.size();
3104 ScopedLocalRef<jbyteArray> dataArray(env, env->NewByteArray(request_length));
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003105 if (dataArray.get() == NULL) {
Elliott Hughes4b9702c2013-02-20 18:13:24 -08003106 LOG(WARNING) << "byte[] allocation failed: " << request_length;
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07003107 env->ExceptionClear();
3108 return false;
3109 }
Elliott Hughes4b9702c2013-02-20 18:13:24 -08003110 env->SetByteArrayRegion(dataArray.get(), 0, request_length, reinterpret_cast<const jbyte*>(request.data()));
3111 request.Skip(request_length);
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07003112
3113 // Run through and find all chunks. [Currently just find the first.]
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003114 ScopedByteArrayRO contents(env, dataArray.get());
Elliott Hughes4b9702c2013-02-20 18:13:24 -08003115 if (length != request_length) {
Ian Rogersef7d42f2014-01-06 12:55:46 -08003116 LOG(WARNING) << StringPrintf("bad chunk found (len=%u pktLen=%zd)", length, request_length);
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07003117 return false;
3118 }
3119
3120 // Call "private static Chunk dispatch(int type, byte[] data, int offset, int length)".
Elliott Hugheseac76672012-05-24 21:56:51 -07003121 ScopedLocalRef<jobject> chunk(env, env->CallStaticObjectMethod(WellKnownClasses::org_apache_harmony_dalvik_ddmc_DdmServer,
3122 WellKnownClasses::org_apache_harmony_dalvik_ddmc_DdmServer_dispatch,
Elliott Hughes4b9702c2013-02-20 18:13:24 -08003123 type, dataArray.get(), 0, length));
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07003124 if (env->ExceptionCheck()) {
3125 LOG(INFO) << StringPrintf("Exception thrown by dispatcher for 0x%08x", type);
3126 env->ExceptionDescribe();
3127 env->ExceptionClear();
3128 return false;
3129 }
3130
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003131 if (chunk.get() == NULL) {
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07003132 return false;
3133 }
3134
3135 /*
3136 * Pull the pieces out of the chunk. We copy the results into a
3137 * newly-allocated buffer that the caller can free. We don't want to
3138 * continue using the Chunk object because nothing has a reference to it.
3139 *
3140 * We could avoid this by returning type/data/offset/length and having
3141 * the caller be aware of the object lifetime issues, but that
Elliott Hughes81ff3182012-03-23 20:35:56 -07003142 * integrates the JDWP code more tightly into the rest of the runtime, and doesn't work
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07003143 * if we have responses for multiple chunks.
3144 *
3145 * So we're pretty much stuck with copying data around multiple times.
3146 */
Elliott Hugheseac76672012-05-24 21:56:51 -07003147 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 -08003148 jint offset = env->GetIntField(chunk.get(), WellKnownClasses::org_apache_harmony_dalvik_ddmc_Chunk_offset);
Elliott Hugheseac76672012-05-24 21:56:51 -07003149 length = env->GetIntField(chunk.get(), WellKnownClasses::org_apache_harmony_dalvik_ddmc_Chunk_length);
Elliott Hugheseac76672012-05-24 21:56:51 -07003150 type = env->GetIntField(chunk.get(), WellKnownClasses::org_apache_harmony_dalvik_ddmc_Chunk_type);
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07003151
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08003152 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 -07003153 if (length == 0 || replyData.get() == NULL) {
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07003154 return false;
3155 }
3156
Elliott Hughes4b9702c2013-02-20 18:13:24 -08003157 const int kChunkHdrLen = 8;
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07003158 uint8_t* reply = new uint8_t[length + kChunkHdrLen];
3159 if (reply == NULL) {
3160 LOG(WARNING) << "malloc failed: " << (length + kChunkHdrLen);
3161 return false;
3162 }
Elliott Hughesf7c3b662011-10-27 12:04:56 -07003163 JDWP::Set4BE(reply + 0, type);
3164 JDWP::Set4BE(reply + 4, length);
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003165 env->GetByteArrayRegion(replyData.get(), offset, length, reinterpret_cast<jbyte*>(reply + kChunkHdrLen));
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07003166
3167 *pReplyBuf = reply;
3168 *pReplyLen = length + kChunkHdrLen;
3169
Elliott Hughes4b9702c2013-02-20 18:13:24 -08003170 VLOG(jdwp) << StringPrintf("dvmHandleDdm returning type=%.4s %p len=%d", reinterpret_cast<char*>(reply), reply, length);
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07003171 return true;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07003172}
3173
Elliott Hughesa2155262011-11-16 16:26:58 -08003174void Dbg::DdmBroadcast(bool connect) {
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08003175 VLOG(jdwp) << "Broadcasting DDM " << (connect ? "connect" : "disconnect") << "...";
Elliott Hughes47fce012011-10-25 18:37:19 -07003176
3177 Thread* self = Thread::Current();
Ian Rogers50b35e22012-10-04 10:09:15 -07003178 if (self->GetState() != kRunnable) {
3179 LOG(ERROR) << "DDM broadcast in thread state " << self->GetState();
3180 /* try anyway? */
Elliott Hughes47fce012011-10-25 18:37:19 -07003181 }
3182
3183 JNIEnv* env = self->GetJniEnv();
Elliott Hughes47fce012011-10-25 18:37:19 -07003184 jint event = connect ? 1 /*DdmServer.CONNECTED*/ : 2 /*DdmServer.DISCONNECTED*/;
Elliott Hugheseac76672012-05-24 21:56:51 -07003185 env->CallStaticVoidMethod(WellKnownClasses::org_apache_harmony_dalvik_ddmc_DdmServer,
3186 WellKnownClasses::org_apache_harmony_dalvik_ddmc_DdmServer_broadcast,
3187 event);
Elliott Hughes47fce012011-10-25 18:37:19 -07003188 if (env->ExceptionCheck()) {
3189 LOG(ERROR) << "DdmServer.broadcast " << event << " failed";
3190 env->ExceptionDescribe();
3191 env->ExceptionClear();
3192 }
3193}
3194
Elliott Hughes872d4ec2011-10-21 17:07:15 -07003195void Dbg::DdmConnected() {
Elliott Hughesa2155262011-11-16 16:26:58 -08003196 Dbg::DdmBroadcast(true);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07003197}
3198
3199void Dbg::DdmDisconnected() {
Elliott Hughesa2155262011-11-16 16:26:58 -08003200 Dbg::DdmBroadcast(false);
Elliott Hughes47fce012011-10-25 18:37:19 -07003201 gDdmThreadNotification = false;
3202}
3203
3204/*
Elliott Hughes82188472011-11-07 18:11:48 -08003205 * Send a notification when a thread starts, stops, or changes its name.
Elliott Hughes47fce012011-10-25 18:37:19 -07003206 *
3207 * Because we broadcast the full set of threads when the notifications are
3208 * first enabled, it's possible for "thread" to be actively executing.
3209 */
Elliott Hughes82188472011-11-07 18:11:48 -08003210void Dbg::DdmSendThreadNotification(Thread* t, uint32_t type) {
Elliott Hughes47fce012011-10-25 18:37:19 -07003211 if (!gDdmThreadNotification) {
3212 return;
3213 }
3214
Elliott Hughes82188472011-11-07 18:11:48 -08003215 if (type == CHUNK_TYPE("THDE")) {
Elliott Hughes47fce012011-10-25 18:37:19 -07003216 uint8_t buf[4];
Ian Rogersd9c4fc92013-10-01 19:45:43 -07003217 JDWP::Set4BE(&buf[0], t->GetThreadId());
Elliott Hughes47fce012011-10-25 18:37:19 -07003218 Dbg::DdmSendChunk(CHUNK_TYPE("THDE"), 4, buf);
Elliott Hughes82188472011-11-07 18:11:48 -08003219 } else {
3220 CHECK(type == CHUNK_TYPE("THCR") || type == CHUNK_TYPE("THNM")) << type;
Ian Rogers00f7d0e2012-07-19 15:28:27 -07003221 ScopedObjectAccessUnchecked soa(Thread::Current());
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003222 SirtRef<mirror::String> name(soa.Self(), t->GetThreadName(soa));
Elliott Hughes82188472011-11-07 18:11:48 -08003223 size_t char_count = (name.get() != NULL) ? name->GetLength() : 0;
jeffhao725a9572012-11-13 18:20:12 -08003224 const jchar* chars = (name.get() != NULL) ? name->GetCharArray()->GetData() : NULL;
Elliott Hughes82188472011-11-07 18:11:48 -08003225
Elliott Hughes21f32d72011-11-09 17:44:13 -08003226 std::vector<uint8_t> bytes;
Ian Rogersd9c4fc92013-10-01 19:45:43 -07003227 JDWP::Append4BE(bytes, t->GetThreadId());
Elliott Hughes545a0642011-11-08 19:10:03 -08003228 JDWP::AppendUtf16BE(bytes, chars, char_count);
Elliott Hughes21f32d72011-11-09 17:44:13 -08003229 CHECK_EQ(bytes.size(), char_count*2 + sizeof(uint32_t)*2);
3230 Dbg::DdmSendChunk(type, bytes);
Elliott Hughes47fce012011-10-25 18:37:19 -07003231 }
3232}
3233
Elliott Hughes47fce012011-10-25 18:37:19 -07003234void Dbg::DdmSetThreadNotification(bool enable) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07003235 // Enable/disable thread notifications.
Elliott Hughes47fce012011-10-25 18:37:19 -07003236 gDdmThreadNotification = enable;
3237 if (enable) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07003238 // Suspend the VM then post thread start notifications for all threads. Threads attaching will
3239 // see a suspension in progress and block until that ends. They then post their own start
3240 // notification.
3241 SuspendVM();
3242 std::list<Thread*> threads;
Ian Rogers50b35e22012-10-04 10:09:15 -07003243 Thread* self = Thread::Current();
Ian Rogers00f7d0e2012-07-19 15:28:27 -07003244 {
Ian Rogers50b35e22012-10-04 10:09:15 -07003245 MutexLock mu(self, *Locks::thread_list_lock_);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07003246 threads = Runtime::Current()->GetThreadList()->GetList();
3247 }
3248 {
Ian Rogers50b35e22012-10-04 10:09:15 -07003249 ScopedObjectAccess soa(self);
Mathieu Chartier02e25112013-08-14 16:14:24 -07003250 for (Thread* thread : threads) {
3251 Dbg::DdmSendThreadNotification(thread, CHUNK_TYPE("THCR"));
Ian Rogers00f7d0e2012-07-19 15:28:27 -07003252 }
3253 }
3254 ResumeVM();
Elliott Hughes47fce012011-10-25 18:37:19 -07003255 }
3256}
3257
Elliott Hughesa2155262011-11-16 16:26:58 -08003258void Dbg::PostThreadStartOrStop(Thread* t, uint32_t type) {
Elliott Hughesc0f09332012-03-26 13:27:06 -07003259 if (IsDebuggerActive()) {
Mathieu Chartierdbe6f462012-09-25 16:54:50 -07003260 ScopedObjectAccessUnchecked soa(Thread::Current());
Ian Rogerscfaa4552012-11-26 21:00:08 -08003261 JDWP::ObjectId id = gRegistry->Add(t->GetPeer());
Elliott Hughes82188472011-11-07 18:11:48 -08003262 gJdwpState->PostThreadChange(id, type == CHUNK_TYPE("THCR"));
Elliott Hughes47fce012011-10-25 18:37:19 -07003263 }
Elliott Hughes82188472011-11-07 18:11:48 -08003264 Dbg::DdmSendThreadNotification(t, type);
Elliott Hughes47fce012011-10-25 18:37:19 -07003265}
3266
3267void Dbg::PostThreadStart(Thread* t) {
Elliott Hughesa2155262011-11-16 16:26:58 -08003268 Dbg::PostThreadStartOrStop(t, CHUNK_TYPE("THCR"));
Elliott Hughes47fce012011-10-25 18:37:19 -07003269}
3270
3271void Dbg::PostThreadDeath(Thread* t) {
Elliott Hughesa2155262011-11-16 16:26:58 -08003272 Dbg::PostThreadStartOrStop(t, CHUNK_TYPE("THDE"));
Elliott Hughes872d4ec2011-10-21 17:07:15 -07003273}
3274
Elliott Hughes82188472011-11-07 18:11:48 -08003275void Dbg::DdmSendChunk(uint32_t type, size_t byte_count, const uint8_t* buf) {
Elliott Hughes3bb81562011-10-21 18:52:59 -07003276 CHECK(buf != NULL);
3277 iovec vec[1];
3278 vec[0].iov_base = reinterpret_cast<void*>(const_cast<uint8_t*>(buf));
3279 vec[0].iov_len = byte_count;
3280 Dbg::DdmSendChunkV(type, vec, 1);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07003281}
3282
Elliott Hughes21f32d72011-11-09 17:44:13 -08003283void Dbg::DdmSendChunk(uint32_t type, const std::vector<uint8_t>& bytes) {
3284 DdmSendChunk(type, bytes.size(), &bytes[0]);
3285}
3286
Brian Carlstromf5293522013-07-19 00:24:00 -07003287void Dbg::DdmSendChunkV(uint32_t type, const iovec* iov, int iov_count) {
Elliott Hughes3bb81562011-10-21 18:52:59 -07003288 if (gJdwpState == NULL) {
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08003289 VLOG(jdwp) << "Debugger thread not active, ignoring DDM send: " << type;
Elliott Hughes3bb81562011-10-21 18:52:59 -07003290 } else {
Elliott Hughescccd84f2011-12-05 16:51:54 -08003291 gJdwpState->DdmSendChunkV(type, iov, iov_count);
Elliott Hughes3bb81562011-10-21 18:52:59 -07003292 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -07003293}
3294
Elliott Hughes767a1472011-10-26 18:49:02 -07003295int Dbg::DdmHandleHpifChunk(HpifWhen when) {
3296 if (when == HPIF_WHEN_NOW) {
Elliott Hughes7162ad92011-10-27 14:08:42 -07003297 DdmSendHeapInfo(when);
Elliott Hughes767a1472011-10-26 18:49:02 -07003298 return true;
3299 }
3300
3301 if (when != HPIF_WHEN_NEVER && when != HPIF_WHEN_NEXT_GC && when != HPIF_WHEN_EVERY_GC) {
3302 LOG(ERROR) << "invalid HpifWhen value: " << static_cast<int>(when);
3303 return false;
3304 }
3305
3306 gDdmHpifWhen = when;
3307 return true;
3308}
3309
3310bool Dbg::DdmHandleHpsgNhsgChunk(Dbg::HpsgWhen when, Dbg::HpsgWhat what, bool native) {
3311 if (when != HPSG_WHEN_NEVER && when != HPSG_WHEN_EVERY_GC) {
3312 LOG(ERROR) << "invalid HpsgWhen value: " << static_cast<int>(when);
3313 return false;
3314 }
3315
3316 if (what != HPSG_WHAT_MERGED_OBJECTS && what != HPSG_WHAT_DISTINCT_OBJECTS) {
3317 LOG(ERROR) << "invalid HpsgWhat value: " << static_cast<int>(what);
3318 return false;
3319 }
3320
3321 if (native) {
3322 gDdmNhsgWhen = when;
3323 gDdmNhsgWhat = what;
3324 } else {
3325 gDdmHpsgWhen = when;
3326 gDdmHpsgWhat = what;
3327 }
3328 return true;
3329}
3330
Elliott Hughes7162ad92011-10-27 14:08:42 -07003331void Dbg::DdmSendHeapInfo(HpifWhen reason) {
3332 // If there's a one-shot 'when', reset it.
3333 if (reason == gDdmHpifWhen) {
3334 if (gDdmHpifWhen == HPIF_WHEN_NEXT_GC) {
3335 gDdmHpifWhen = HPIF_WHEN_NEVER;
3336 }
3337 }
3338
3339 /*
3340 * Chunk HPIF (client --> server)
3341 *
3342 * Heap Info. General information about the heap,
3343 * suitable for a summary display.
3344 *
3345 * [u4]: number of heaps
3346 *
3347 * For each heap:
3348 * [u4]: heap ID
3349 * [u8]: timestamp in ms since Unix epoch
3350 * [u1]: capture reason (same as 'when' value from server)
3351 * [u4]: max heap size in bytes (-Xmx)
3352 * [u4]: current heap size in bytes
3353 * [u4]: current number of bytes allocated
3354 * [u4]: current number of objects allocated
3355 */
3356 uint8_t heap_count = 1;
Ian Rogers1d54e732013-05-02 21:10:01 -07003357 gc::Heap* heap = Runtime::Current()->GetHeap();
Elliott Hughes21f32d72011-11-09 17:44:13 -08003358 std::vector<uint8_t> bytes;
Elliott Hughes545a0642011-11-08 19:10:03 -08003359 JDWP::Append4BE(bytes, heap_count);
Brian Carlstrom7934ac22013-07-26 10:54:15 -07003360 JDWP::Append4BE(bytes, 1); // Heap id (bogus; we only have one heap).
Elliott Hughes545a0642011-11-08 19:10:03 -08003361 JDWP::Append8BE(bytes, MilliTime());
3362 JDWP::Append1BE(bytes, reason);
Brian Carlstrom7934ac22013-07-26 10:54:15 -07003363 JDWP::Append4BE(bytes, heap->GetMaxMemory()); // Max allowed heap size in bytes.
3364 JDWP::Append4BE(bytes, heap->GetTotalMemory()); // Current heap size in bytes.
Elliott Hughesb3bd5f02012-03-08 21:05:27 -08003365 JDWP::Append4BE(bytes, heap->GetBytesAllocated());
3366 JDWP::Append4BE(bytes, heap->GetObjectsAllocated());
Elliott Hughes21f32d72011-11-09 17:44:13 -08003367 CHECK_EQ(bytes.size(), 4U + (heap_count * (4 + 8 + 1 + 4 + 4 + 4 + 4)));
3368 Dbg::DdmSendChunk(CHUNK_TYPE("HPIF"), bytes);
Elliott Hughes767a1472011-10-26 18:49:02 -07003369}
3370
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003371enum HpsgSolidity {
3372 SOLIDITY_FREE = 0,
3373 SOLIDITY_HARD = 1,
3374 SOLIDITY_SOFT = 2,
3375 SOLIDITY_WEAK = 3,
3376 SOLIDITY_PHANTOM = 4,
3377 SOLIDITY_FINALIZABLE = 5,
3378 SOLIDITY_SWEEP = 6,
3379};
3380
3381enum HpsgKind {
3382 KIND_OBJECT = 0,
3383 KIND_CLASS_OBJECT = 1,
3384 KIND_ARRAY_1 = 2,
3385 KIND_ARRAY_2 = 3,
3386 KIND_ARRAY_4 = 4,
3387 KIND_ARRAY_8 = 5,
3388 KIND_UNKNOWN = 6,
3389 KIND_NATIVE = 7,
3390};
3391
3392#define HPSG_PARTIAL (1<<7)
3393#define HPSG_STATE(solidity, kind) ((uint8_t)((((kind) & 0x7) << 3) | ((solidity) & 0x7)))
3394
Ian Rogers30fab402012-01-23 15:43:46 -08003395class HeapChunkContext {
3396 public:
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003397 // Maximum chunk size. Obtain this from the formula:
3398 // (((maximum_heap_size / ALLOCATION_UNIT_SIZE) + 255) / 256) * 2
3399 HeapChunkContext(bool merge, bool native)
Ian Rogers30fab402012-01-23 15:43:46 -08003400 : buf_(16384 - 16),
3401 type_(0),
3402 merge_(merge) {
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003403 Reset();
3404 if (native) {
Ian Rogers30fab402012-01-23 15:43:46 -08003405 type_ = CHUNK_TYPE("NHSG");
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003406 } else {
Ian Rogers30fab402012-01-23 15:43:46 -08003407 type_ = merge ? CHUNK_TYPE("HPSG") : CHUNK_TYPE("HPSO");
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003408 }
3409 }
3410
3411 ~HeapChunkContext() {
Ian Rogers30fab402012-01-23 15:43:46 -08003412 if (p_ > &buf_[0]) {
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003413 Flush();
3414 }
3415 }
3416
3417 void EnsureHeader(const void* chunk_ptr) {
Ian Rogers30fab402012-01-23 15:43:46 -08003418 if (!needHeader_) {
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003419 return;
3420 }
3421
3422 // Start a new HPSx chunk.
Brian Carlstrom7934ac22013-07-26 10:54:15 -07003423 JDWP::Write4BE(&p_, 1); // Heap id (bogus; we only have one heap).
3424 JDWP::Write1BE(&p_, 8); // Size of allocation unit, in bytes.
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003425
Brian Carlstrom7934ac22013-07-26 10:54:15 -07003426 JDWP::Write4BE(&p_, reinterpret_cast<uintptr_t>(chunk_ptr)); // virtual address of segment start.
3427 JDWP::Write4BE(&p_, 0); // offset of this piece (relative to the virtual address).
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003428 // [u4]: length of piece, in allocation units
3429 // 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 -08003430 pieceLenField_ = p_;
3431 JDWP::Write4BE(&p_, 0x55555555);
3432 needHeader_ = false;
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003433 }
3434
Ian Rogersb726dcb2012-09-05 08:57:23 -07003435 void Flush() SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Ian Rogersd636b062013-01-18 17:51:18 -08003436 if (pieceLenField_ == NULL) {
3437 // Flush immediately post Reset (maybe back-to-back Flush). Ignore.
3438 CHECK(needHeader_);
3439 return;
3440 }
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003441 // Patch the "length of piece" field.
Ian Rogers30fab402012-01-23 15:43:46 -08003442 CHECK_LE(&buf_[0], pieceLenField_);
3443 CHECK_LE(pieceLenField_, p_);
3444 JDWP::Set4BE(pieceLenField_, totalAllocationUnits_);
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003445
Ian Rogers30fab402012-01-23 15:43:46 -08003446 Dbg::DdmSendChunk(type_, p_ - &buf_[0], &buf_[0]);
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003447 Reset();
3448 }
3449
Ian Rogers00f7d0e2012-07-19 15:28:27 -07003450 static void HeapChunkCallback(void* start, void* end, size_t used_bytes, void* arg)
Ian Rogersb726dcb2012-09-05 08:57:23 -07003451 SHARED_LOCKS_REQUIRED(Locks::heap_bitmap_lock_,
3452 Locks::mutator_lock_) {
Ian Rogers30fab402012-01-23 15:43:46 -08003453 reinterpret_cast<HeapChunkContext*>(arg)->HeapChunkCallback(start, end, used_bytes);
Elliott Hughesa2155262011-11-16 16:26:58 -08003454 }
3455
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003456 private:
Elliott Hughesa2155262011-11-16 16:26:58 -08003457 enum { ALLOCATION_UNIT_SIZE = 8 };
3458
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003459 void Reset() {
Ian Rogers30fab402012-01-23 15:43:46 -08003460 p_ = &buf_[0];
Ian Rogers15bf2d32012-08-28 17:33:04 -07003461 startOfNextMemoryChunk_ = NULL;
Ian Rogers30fab402012-01-23 15:43:46 -08003462 totalAllocationUnits_ = 0;
3463 needHeader_ = true;
3464 pieceLenField_ = NULL;
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003465 }
3466
Ian Rogers00f7d0e2012-07-19 15:28:27 -07003467 void HeapChunkCallback(void* start, void* /*end*/, size_t used_bytes)
Ian Rogersb726dcb2012-09-05 08:57:23 -07003468 SHARED_LOCKS_REQUIRED(Locks::heap_bitmap_lock_,
3469 Locks::mutator_lock_) {
Ian Rogers30fab402012-01-23 15:43:46 -08003470 // Note: heap call backs cannot manipulate the heap upon which they are crawling, care is taken
3471 // in the following code not to allocate memory, by ensuring buf_ is of the correct size
Ian Rogers15bf2d32012-08-28 17:33:04 -07003472 if (used_bytes == 0) {
3473 if (start == NULL) {
3474 // Reset for start of new heap.
3475 startOfNextMemoryChunk_ = NULL;
3476 Flush();
3477 }
3478 // Only process in use memory so that free region information
3479 // also includes dlmalloc book keeping.
Elliott Hughesa2155262011-11-16 16:26:58 -08003480 return;
Elliott Hughesa2155262011-11-16 16:26:58 -08003481 }
3482
Ian Rogers15bf2d32012-08-28 17:33:04 -07003483 /* If we're looking at the native heap, we'll just return
3484 * (SOLIDITY_HARD, KIND_NATIVE) for all allocated chunks
3485 */
3486 bool native = type_ == CHUNK_TYPE("NHSG");
3487
3488 if (startOfNextMemoryChunk_ != NULL) {
3489 // Transmit any pending free memory. Native free memory of
3490 // over kMaxFreeLen could be because of the use of mmaps, so
3491 // don't report. If not free memory then start a new segment.
3492 bool flush = true;
3493 if (start > startOfNextMemoryChunk_) {
3494 const size_t kMaxFreeLen = 2 * kPageSize;
3495 void* freeStart = startOfNextMemoryChunk_;
3496 void* freeEnd = start;
Brian Carlstrom2d888622013-07-18 17:02:00 -07003497 size_t freeLen = reinterpret_cast<char*>(freeEnd) - reinterpret_cast<char*>(freeStart);
Ian Rogers15bf2d32012-08-28 17:33:04 -07003498 if (!native || freeLen < kMaxFreeLen) {
3499 AppendChunk(HPSG_STATE(SOLIDITY_FREE, 0), freeStart, freeLen);
3500 flush = false;
3501 }
3502 }
3503 if (flush) {
3504 startOfNextMemoryChunk_ = NULL;
3505 Flush();
3506 }
3507 }
Ian Rogersef7d42f2014-01-06 12:55:46 -08003508 mirror::Object* obj = reinterpret_cast<mirror::Object*>(start);
Elliott Hughesa2155262011-11-16 16:26:58 -08003509
3510 // Determine the type of this chunk.
3511 // OLD-TODO: if context.merge, see if this chunk is different from the last chunk.
3512 // If it's the same, we should combine them.
Ian Rogers15bf2d32012-08-28 17:33:04 -07003513 uint8_t state = ExamineObject(obj, native);
3514 // dlmalloc's chunk header is 2 * sizeof(size_t), but if the previous chunk is in use for an
3515 // allocation then the first sizeof(size_t) may belong to it.
3516 const size_t dlMallocOverhead = sizeof(size_t);
3517 AppendChunk(state, start, used_bytes + dlMallocOverhead);
Brian Carlstrom2d888622013-07-18 17:02:00 -07003518 startOfNextMemoryChunk_ = reinterpret_cast<char*>(start) + used_bytes + dlMallocOverhead;
Ian Rogers15bf2d32012-08-28 17:33:04 -07003519 }
Elliott Hughesa2155262011-11-16 16:26:58 -08003520
Ian Rogers15bf2d32012-08-28 17:33:04 -07003521 void AppendChunk(uint8_t state, void* ptr, size_t length)
Ian Rogersb726dcb2012-09-05 08:57:23 -07003522 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Ian Rogers15bf2d32012-08-28 17:33:04 -07003523 // Make sure there's enough room left in the buffer.
3524 // We need to use two bytes for every fractional 256 allocation units used by the chunk plus
3525 // 17 bytes for any header.
3526 size_t needed = (((length/ALLOCATION_UNIT_SIZE + 255) / 256) * 2) + 17;
3527 size_t bytesLeft = buf_.size() - (size_t)(p_ - &buf_[0]);
3528 if (bytesLeft < needed) {
3529 Flush();
3530 }
3531
3532 bytesLeft = buf_.size() - (size_t)(p_ - &buf_[0]);
3533 if (bytesLeft < needed) {
3534 LOG(WARNING) << "Chunk is too big to transmit (chunk_len=" << length << ", "
3535 << needed << " bytes)";
3536 return;
3537 }
3538 EnsureHeader(ptr);
Elliott Hughesa2155262011-11-16 16:26:58 -08003539 // Write out the chunk description.
Ian Rogers15bf2d32012-08-28 17:33:04 -07003540 length /= ALLOCATION_UNIT_SIZE; // Convert to allocation units.
3541 totalAllocationUnits_ += length;
3542 while (length > 256) {
Ian Rogers30fab402012-01-23 15:43:46 -08003543 *p_++ = state | HPSG_PARTIAL;
3544 *p_++ = 255; // length - 1
Ian Rogers15bf2d32012-08-28 17:33:04 -07003545 length -= 256;
Elliott Hughesa2155262011-11-16 16:26:58 -08003546 }
Ian Rogers30fab402012-01-23 15:43:46 -08003547 *p_++ = state;
Ian Rogers15bf2d32012-08-28 17:33:04 -07003548 *p_++ = length - 1;
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003549 }
3550
Ian Rogersef7d42f2014-01-06 12:55:46 -08003551 uint8_t ExamineObject(mirror::Object* o, bool is_native_heap)
3552 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_, Locks::heap_bitmap_lock_) {
Elliott Hughesa2155262011-11-16 16:26:58 -08003553 if (o == NULL) {
3554 return HPSG_STATE(SOLIDITY_FREE, 0);
3555 }
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003556
Elliott Hughesa2155262011-11-16 16:26:58 -08003557 // It's an allocated chunk. Figure out what it is.
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003558
Elliott Hughesa2155262011-11-16 16:26:58 -08003559 // If we're looking at the native heap, we'll just return
3560 // (SOLIDITY_HARD, KIND_NATIVE) for all allocated chunks.
Ian Rogers00f7d0e2012-07-19 15:28:27 -07003561 if (is_native_heap) {
Elliott Hughesa2155262011-11-16 16:26:58 -08003562 return HPSG_STATE(SOLIDITY_HARD, KIND_NATIVE);
3563 }
3564
Ian Rogers5bfa60f2012-09-02 21:17:56 -07003565 if (!Runtime::Current()->GetHeap()->IsLiveObjectLocked(o)) {
Ian Rogers15bf2d32012-08-28 17:33:04 -07003566 return HPSG_STATE(SOLIDITY_HARD, KIND_NATIVE);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07003567 }
3568
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003569 mirror::Class* c = o->GetClass();
Elliott Hughesa2155262011-11-16 16:26:58 -08003570 if (c == NULL) {
3571 // The object was probably just created but hasn't been initialized yet.
3572 return HPSG_STATE(SOLIDITY_HARD, KIND_OBJECT);
3573 }
3574
Mathieu Chartier590fee92013-09-13 13:46:47 -07003575 if (!Runtime::Current()->GetHeap()->IsValidObjectAddress(c)) {
Ian Rogers15bf2d32012-08-28 17:33:04 -07003576 LOG(ERROR) << "Invalid class for managed heap object: " << o << " " << c;
Elliott Hughesa2155262011-11-16 16:26:58 -08003577 return HPSG_STATE(SOLIDITY_HARD, KIND_UNKNOWN);
3578 }
3579
3580 if (c->IsClassClass()) {
3581 return HPSG_STATE(SOLIDITY_HARD, KIND_CLASS_OBJECT);
3582 }
3583
3584 if (c->IsArrayClass()) {
3585 if (o->IsObjectArray()) {
3586 return HPSG_STATE(SOLIDITY_HARD, KIND_ARRAY_4);
3587 }
3588 switch (c->GetComponentSize()) {
3589 case 1: return HPSG_STATE(SOLIDITY_HARD, KIND_ARRAY_1);
3590 case 2: return HPSG_STATE(SOLIDITY_HARD, KIND_ARRAY_2);
3591 case 4: return HPSG_STATE(SOLIDITY_HARD, KIND_ARRAY_4);
3592 case 8: return HPSG_STATE(SOLIDITY_HARD, KIND_ARRAY_8);
3593 }
3594 }
3595
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003596 return HPSG_STATE(SOLIDITY_HARD, KIND_OBJECT);
3597 }
3598
Ian Rogers30fab402012-01-23 15:43:46 -08003599 std::vector<uint8_t> buf_;
3600 uint8_t* p_;
3601 uint8_t* pieceLenField_;
Ian Rogers15bf2d32012-08-28 17:33:04 -07003602 void* startOfNextMemoryChunk_;
Ian Rogers30fab402012-01-23 15:43:46 -08003603 size_t totalAllocationUnits_;
3604 uint32_t type_;
3605 bool merge_;
3606 bool needHeader_;
3607
Elliott Hughesa2155262011-11-16 16:26:58 -08003608 DISALLOW_COPY_AND_ASSIGN(HeapChunkContext);
3609};
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003610
3611void Dbg::DdmSendHeapSegments(bool native) {
3612 Dbg::HpsgWhen when;
3613 Dbg::HpsgWhat what;
3614 if (!native) {
3615 when = gDdmHpsgWhen;
3616 what = gDdmHpsgWhat;
3617 } else {
3618 when = gDdmNhsgWhen;
3619 what = gDdmNhsgWhat;
3620 }
3621 if (when == HPSG_WHEN_NEVER) {
3622 return;
3623 }
3624
3625 // Figure out what kind of chunks we'll be sending.
3626 CHECK(what == HPSG_WHAT_MERGED_OBJECTS || what == HPSG_WHAT_DISTINCT_OBJECTS) << static_cast<int>(what);
3627
3628 // First, send a heap start chunk.
3629 uint8_t heap_id[4];
Brian Carlstrom7934ac22013-07-26 10:54:15 -07003630 JDWP::Set4BE(&heap_id[0], 1); // Heap id (bogus; we only have one heap).
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003631 Dbg::DdmSendChunk(native ? CHUNK_TYPE("NHST") : CHUNK_TYPE("HPST"), sizeof(heap_id), heap_id);
3632
Hiroshi Yamauchicf58d4a2013-09-26 14:21:22 -07003633 Thread* self = Thread::Current();
3634
3635 // To allow the Walk/InspectAll() below to exclusively-lock the
3636 // mutator lock, temporarily release the shared access to the
3637 // mutator lock here by transitioning to the suspended state.
3638 Locks::mutator_lock_->AssertSharedHeld(self);
3639 self->TransitionFromRunnableToSuspended(kSuspended);
3640
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003641 // Send a series of heap segment chunks.
Elliott Hughesa2155262011-11-16 16:26:58 -08003642 HeapChunkContext context((what == HPSG_WHAT_MERGED_OBJECTS), native);
3643 if (native) {
Ian Rogers1d54e732013-05-02 21:10:01 -07003644 dlmalloc_inspect_all(HeapChunkContext::HeapChunkCallback, &context);
Elliott Hughesa2155262011-11-16 16:26:58 -08003645 } else {
Ian Rogers1d54e732013-05-02 21:10:01 -07003646 gc::Heap* heap = Runtime::Current()->GetHeap();
3647 const std::vector<gc::space::ContinuousSpace*>& spaces = heap->GetContinuousSpaces();
Ian Rogers62d6c772013-02-27 08:32:07 -08003648 ReaderMutexLock mu(self, *Locks::heap_bitmap_lock_);
Ian Rogers1d54e732013-05-02 21:10:01 -07003649 typedef std::vector<gc::space::ContinuousSpace*>::const_iterator It;
3650 for (It cur = spaces.begin(), end = spaces.end(); cur != end; ++cur) {
Hiroshi Yamauchicf58d4a2013-09-26 14:21:22 -07003651 if ((*cur)->IsMallocSpace()) {
3652 (*cur)->AsMallocSpace()->Walk(HeapChunkContext::HeapChunkCallback, &context);
Mathieu Chartierb062fdd2012-07-03 09:51:48 -07003653 }
3654 }
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -07003655 // Walk the large objects, these are not in the AllocSpace.
3656 heap->GetLargeObjectsSpace()->Walk(HeapChunkContext::HeapChunkCallback, &context);
Elliott Hughesa2155262011-11-16 16:26:58 -08003657 }
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003658
Hiroshi Yamauchicf58d4a2013-09-26 14:21:22 -07003659 // Shared-lock the mutator lock back.
3660 self->TransitionFromSuspendedToRunnable();
3661 Locks::mutator_lock_->AssertSharedHeld(self);
3662
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003663 // Finally, send a heap end chunk.
3664 Dbg::DdmSendChunk(native ? CHUNK_TYPE("NHEN") : CHUNK_TYPE("HPEN"), sizeof(heap_id), heap_id);
Elliott Hughes767a1472011-10-26 18:49:02 -07003665}
3666
Elliott Hughesb1a58792013-07-11 18:10:58 -07003667static size_t GetAllocTrackerMax() {
3668#ifdef HAVE_ANDROID_OS
3669 // Check whether there's a system property overriding the number of records.
3670 const char* propertyName = "dalvik.vm.allocTrackerMax";
3671 char allocRecordMaxString[PROPERTY_VALUE_MAX];
3672 if (property_get(propertyName, allocRecordMaxString, "") > 0) {
3673 char* end;
3674 size_t value = strtoul(allocRecordMaxString, &end, 10);
3675 if (*end != '\0') {
Ruben Brunk3e47a742013-09-09 17:56:07 -07003676 LOG(ERROR) << "Ignoring " << propertyName << " '" << allocRecordMaxString
3677 << "' --- invalid";
Elliott Hughesb1a58792013-07-11 18:10:58 -07003678 return kDefaultNumAllocRecords;
3679 }
3680 if (!IsPowerOfTwo(value)) {
Ruben Brunk3e47a742013-09-09 17:56:07 -07003681 LOG(ERROR) << "Ignoring " << propertyName << " '" << allocRecordMaxString
3682 << "' --- not power of two";
Elliott Hughesb1a58792013-07-11 18:10:58 -07003683 return kDefaultNumAllocRecords;
3684 }
3685 return value;
3686 }
3687#endif
3688 return kDefaultNumAllocRecords;
3689}
3690
Elliott Hughes545a0642011-11-08 19:10:03 -08003691void Dbg::SetAllocTrackingEnabled(bool enabled) {
Ian Rogers50b35e22012-10-04 10:09:15 -07003692 MutexLock mu(Thread::Current(), gAllocTrackerLock);
Elliott Hughes545a0642011-11-08 19:10:03 -08003693 if (enabled) {
3694 if (recent_allocation_records_ == NULL) {
Elliott Hughesb1a58792013-07-11 18:10:58 -07003695 gAllocRecordMax = GetAllocTrackerMax();
3696 LOG(INFO) << "Enabling alloc tracker (" << gAllocRecordMax << " entries of "
3697 << kMaxAllocRecordStackDepth << " frames, taking "
3698 << PrettySize(sizeof(AllocRecord) * gAllocRecordMax) << ")";
Elliott Hughes545a0642011-11-08 19:10:03 -08003699 gAllocRecordHead = gAllocRecordCount = 0;
Elliott Hughesb1a58792013-07-11 18:10:58 -07003700 recent_allocation_records_ = new AllocRecord[gAllocRecordMax];
Elliott Hughes545a0642011-11-08 19:10:03 -08003701 CHECK(recent_allocation_records_ != NULL);
3702 }
Ian Rogersfa824272013-11-05 16:12:57 -08003703 Runtime::Current()->GetInstrumentation()->InstrumentQuickAllocEntryPoints();
Elliott Hughes545a0642011-11-08 19:10:03 -08003704 } else {
Ian Rogersfa824272013-11-05 16:12:57 -08003705 Runtime::Current()->GetInstrumentation()->UninstrumentQuickAllocEntryPoints();
Elliott Hughes545a0642011-11-08 19:10:03 -08003706 delete[] recent_allocation_records_;
3707 recent_allocation_records_ = NULL;
3708 }
3709}
3710
Ian Rogers0399dde2012-06-06 17:09:28 -07003711struct AllocRecordStackVisitor : public StackVisitor {
Ian Rogers7a22fa62013-01-23 12:16:16 -08003712 AllocRecordStackVisitor(Thread* thread, AllocRecord* record)
Ian Rogersb726dcb2012-09-05 08:57:23 -07003713 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_)
Ian Rogers7a22fa62013-01-23 12:16:16 -08003714 : StackVisitor(thread, NULL), record(record), depth(0) {}
Elliott Hughes545a0642011-11-08 19:10:03 -08003715
Ian Rogers00f7d0e2012-07-19 15:28:27 -07003716 // TODO: Enable annotalysis. We know lock is held in constructor, but abstraction confuses
3717 // annotalysis.
3718 bool VisitFrame() NO_THREAD_SAFETY_ANALYSIS {
Elliott Hughes545a0642011-11-08 19:10:03 -08003719 if (depth >= kMaxAllocRecordStackDepth) {
Elliott Hughes530fa002012-03-12 11:44:49 -07003720 return false;
Elliott Hughes545a0642011-11-08 19:10:03 -08003721 }
Brian Carlstromea46f952013-07-30 01:26:50 -07003722 mirror::ArtMethod* m = GetMethod();
Ian Rogers0399dde2012-06-06 17:09:28 -07003723 if (!m->IsRuntimeMethod()) {
3724 record->stack[depth].method = m;
3725 record->stack[depth].dex_pc = GetDexPc();
Elliott Hughes530fa002012-03-12 11:44:49 -07003726 ++depth;
Elliott Hughes545a0642011-11-08 19:10:03 -08003727 }
Elliott Hughes530fa002012-03-12 11:44:49 -07003728 return true;
Elliott Hughes545a0642011-11-08 19:10:03 -08003729 }
3730
3731 ~AllocRecordStackVisitor() {
3732 // Clear out any unused stack trace elements.
3733 for (; depth < kMaxAllocRecordStackDepth; ++depth) {
3734 record->stack[depth].method = NULL;
Ian Rogers0399dde2012-06-06 17:09:28 -07003735 record->stack[depth].dex_pc = 0;
Elliott Hughes545a0642011-11-08 19:10:03 -08003736 }
3737 }
3738
3739 AllocRecord* record;
3740 size_t depth;
3741};
3742
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003743void Dbg::RecordAllocation(mirror::Class* type, size_t byte_count) {
Elliott Hughes545a0642011-11-08 19:10:03 -08003744 Thread* self = Thread::Current();
3745 CHECK(self != NULL);
3746
Ian Rogers50b35e22012-10-04 10:09:15 -07003747 MutexLock mu(self, gAllocTrackerLock);
Elliott Hughes545a0642011-11-08 19:10:03 -08003748 if (recent_allocation_records_ == NULL) {
3749 return;
3750 }
3751
3752 // Advance and clip.
Elliott Hughesb1a58792013-07-11 18:10:58 -07003753 if (++gAllocRecordHead == gAllocRecordMax) {
Elliott Hughes545a0642011-11-08 19:10:03 -08003754 gAllocRecordHead = 0;
3755 }
3756
3757 // Fill in the basics.
3758 AllocRecord* record = &recent_allocation_records_[gAllocRecordHead];
3759 record->type = type;
3760 record->byte_count = byte_count;
Ian Rogersd9c4fc92013-10-01 19:45:43 -07003761 record->thin_lock_id = self->GetThreadId();
Elliott Hughes545a0642011-11-08 19:10:03 -08003762
3763 // Fill in the stack trace.
Ian Rogers7a22fa62013-01-23 12:16:16 -08003764 AllocRecordStackVisitor visitor(self, record);
Ian Rogers0399dde2012-06-06 17:09:28 -07003765 visitor.WalkStack();
Elliott Hughes545a0642011-11-08 19:10:03 -08003766
Elliott Hughesb1a58792013-07-11 18:10:58 -07003767 if (gAllocRecordCount < gAllocRecordMax) {
Elliott Hughes545a0642011-11-08 19:10:03 -08003768 ++gAllocRecordCount;
3769 }
3770}
3771
Elliott Hughesa8f93cb2012-06-08 17:08:48 -07003772// Returns the index of the head element.
3773//
3774// We point at the most-recently-written record, so if gAllocRecordCount is 1
3775// we want to use the current element. Take "head+1" and subtract count
3776// from it.
3777//
3778// We need to handle underflow in our circular buffer, so we add
Elliott Hughesb1a58792013-07-11 18:10:58 -07003779// gAllocRecordMax and then mask it back down.
Elliott Hughesf8349362012-06-18 15:00:06 -07003780static inline int HeadIndex() EXCLUSIVE_LOCKS_REQUIRED(gAllocTrackerLock) {
Elliott Hughesb1a58792013-07-11 18:10:58 -07003781 return (gAllocRecordHead+1 + gAllocRecordMax - gAllocRecordCount) & (gAllocRecordMax-1);
Elliott Hughes545a0642011-11-08 19:10:03 -08003782}
3783
3784void Dbg::DumpRecentAllocations() {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07003785 ScopedObjectAccess soa(Thread::Current());
Ian Rogers50b35e22012-10-04 10:09:15 -07003786 MutexLock mu(soa.Self(), gAllocTrackerLock);
Elliott Hughes545a0642011-11-08 19:10:03 -08003787 if (recent_allocation_records_ == NULL) {
3788 LOG(INFO) << "Not recording tracked allocations";
3789 return;
3790 }
3791
3792 // "i" is the head of the list. We want to start at the end of the
3793 // list and move forward to the tail.
Elliott Hughesa8f93cb2012-06-08 17:08:48 -07003794 size_t i = HeadIndex();
Elliott Hughes545a0642011-11-08 19:10:03 -08003795 size_t count = gAllocRecordCount;
3796
3797 LOG(INFO) << "Tracked allocations, (head=" << gAllocRecordHead << " count=" << count << ")";
3798 while (count--) {
3799 AllocRecord* record = &recent_allocation_records_[i];
3800
Elliott Hughesa8f93cb2012-06-08 17:08:48 -07003801 LOG(INFO) << StringPrintf(" Thread %-2d %6zd bytes ", record->thin_lock_id, record->byte_count)
Elliott Hughes545a0642011-11-08 19:10:03 -08003802 << PrettyClass(record->type);
3803
3804 for (size_t stack_frame = 0; stack_frame < kMaxAllocRecordStackDepth; ++stack_frame) {
Ian Rogersef7d42f2014-01-06 12:55:46 -08003805 mirror::ArtMethod* m = record->stack[stack_frame].method;
Elliott Hughes545a0642011-11-08 19:10:03 -08003806 if (m == NULL) {
3807 break;
3808 }
3809 LOG(INFO) << " " << PrettyMethod(m) << " line " << record->stack[stack_frame].LineNumber();
3810 }
3811
3812 // pause periodically to help logcat catch up
3813 if ((count % 5) == 0) {
3814 usleep(40000);
3815 }
3816
Elliott Hughesb1a58792013-07-11 18:10:58 -07003817 i = (i + 1) & (gAllocRecordMax-1);
Elliott Hughes545a0642011-11-08 19:10:03 -08003818 }
3819}
3820
Mathieu Chartier83c8ee02014-01-28 14:50:23 -08003821void Dbg::UpdateObjectPointers(IsMarkedCallback* visitor, void* arg) {
Mathieu Chartier412c7fc2014-02-07 12:18:39 -08003822 {
3823 MutexLock mu(Thread::Current(), gAllocTrackerLock);
3824 if (recent_allocation_records_ != nullptr) {
3825 size_t i = HeadIndex();
3826 size_t count = gAllocRecordCount;
3827 while (count--) {
3828 AllocRecord* record = &recent_allocation_records_[i];
3829 DCHECK(record != nullptr);
3830 record->UpdateObjectPointers(visitor, arg);
3831 i = (i + 1) & (gAllocRecordMax - 1);
3832 }
3833 }
3834 }
3835 if (gRegistry != nullptr) {
3836 gRegistry->UpdateObjectPointers(visitor, arg);
3837 }
3838}
3839
3840void Dbg::AllowNewObjectRegistryObjects() {
3841 if (gRegistry != nullptr) {
3842 gRegistry->AllowNewObjects();
3843 }
3844}
3845
3846void Dbg::DisallowNewObjectRegistryObjects() {
3847 if (gRegistry != nullptr) {
3848 gRegistry->DisallowNewObjects();
3849 }
3850}
3851
Elliott Hughes545a0642011-11-08 19:10:03 -08003852class StringTable {
3853 public:
3854 StringTable() {
3855 }
3856
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08003857 void Add(const char* s) {
Elliott Hughes545a0642011-11-08 19:10:03 -08003858 table_.insert(s);
3859 }
3860
Elliott Hughesa8f93cb2012-06-08 17:08:48 -07003861 size_t IndexOf(const char* s) const {
Mathieu Chartier02e25112013-08-14 16:14:24 -07003862 auto it = table_.find(s);
Elliott Hughesa8f93cb2012-06-08 17:08:48 -07003863 if (it == table_.end()) {
3864 LOG(FATAL) << "IndexOf(\"" << s << "\") failed";
3865 }
3866 return std::distance(table_.begin(), it);
Elliott Hughes545a0642011-11-08 19:10:03 -08003867 }
3868
Elliott Hughesa8f93cb2012-06-08 17:08:48 -07003869 size_t Size() const {
Elliott Hughes545a0642011-11-08 19:10:03 -08003870 return table_.size();
3871 }
3872
Elliott Hughesa8f93cb2012-06-08 17:08:48 -07003873 void WriteTo(std::vector<uint8_t>& bytes) const {
Mathieu Chartier02e25112013-08-14 16:14:24 -07003874 for (const std::string& str : table_) {
3875 const char* s = str.c_str();
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08003876 size_t s_len = CountModifiedUtf8Chars(s);
3877 UniquePtr<uint16_t> s_utf16(new uint16_t[s_len]);
3878 ConvertModifiedUtf8ToUtf16(s_utf16.get(), s);
3879 JDWP::AppendUtf16BE(bytes, s_utf16.get(), s_len);
Elliott Hughes545a0642011-11-08 19:10:03 -08003880 }
3881 }
3882
3883 private:
Elliott Hughesa8f93cb2012-06-08 17:08:48 -07003884 std::set<std::string> table_;
Elliott Hughes545a0642011-11-08 19:10:03 -08003885 DISALLOW_COPY_AND_ASSIGN(StringTable);
3886};
3887
3888/*
3889 * The data we send to DDMS contains everything we have recorded.
3890 *
3891 * Message header (all values big-endian):
3892 * (1b) message header len (to allow future expansion); includes itself
3893 * (1b) entry header len
3894 * (1b) stack frame len
3895 * (2b) number of entries
3896 * (4b) offset to string table from start of message
3897 * (2b) number of class name strings
3898 * (2b) number of method name strings
3899 * (2b) number of source file name strings
3900 * For each entry:
3901 * (4b) total allocation size
Elliott Hughes221229c2013-01-08 18:17:50 -08003902 * (2b) thread id
Elliott Hughes545a0642011-11-08 19:10:03 -08003903 * (2b) allocated object's class name index
3904 * (1b) stack depth
3905 * For each stack frame:
3906 * (2b) method's class name
3907 * (2b) method name
3908 * (2b) method source file
3909 * (2b) line number, clipped to 32767; -2 if native; -1 if no source
3910 * (xb) class name strings
3911 * (xb) method name strings
3912 * (xb) source file strings
3913 *
3914 * As with other DDM traffic, strings are sent as a 4-byte length
3915 * followed by UTF-16 data.
3916 *
3917 * We send up 16-bit unsigned indexes into string tables. In theory there
Elliott Hughesb1a58792013-07-11 18:10:58 -07003918 * can be (kMaxAllocRecordStackDepth * gAllocRecordMax) unique strings in
Elliott Hughes545a0642011-11-08 19:10:03 -08003919 * each table, but in practice there should be far fewer.
3920 *
3921 * The chief reason for using a string table here is to keep the size of
3922 * the DDMS message to a minimum. This is partly to make the protocol
3923 * efficient, but also because we have to form the whole thing up all at
3924 * once in a memory buffer.
3925 *
3926 * We use separate string tables for class names, method names, and source
3927 * files to keep the indexes small. There will generally be no overlap
3928 * between the contents of these tables.
3929 */
3930jbyteArray Dbg::GetRecentAllocations() {
3931 if (false) {
3932 DumpRecentAllocations();
3933 }
3934
Ian Rogers50b35e22012-10-04 10:09:15 -07003935 Thread* self = Thread::Current();
Elliott Hughes545a0642011-11-08 19:10:03 -08003936 std::vector<uint8_t> bytes;
Mathieu Chartier46e811b2013-07-10 17:09:14 -07003937 {
3938 MutexLock mu(self, gAllocTrackerLock);
3939 //
3940 // Part 1: generate string tables.
3941 //
3942 StringTable class_names;
3943 StringTable method_names;
3944 StringTable filenames;
Elliott Hughes545a0642011-11-08 19:10:03 -08003945
Mathieu Chartier46e811b2013-07-10 17:09:14 -07003946 int count = gAllocRecordCount;
3947 int idx = HeadIndex();
3948 while (count--) {
3949 AllocRecord* record = &recent_allocation_records_[idx];
Elliott Hughes545a0642011-11-08 19:10:03 -08003950
Mathieu Chartier46e811b2013-07-10 17:09:14 -07003951 class_names.Add(ClassHelper(record->type).GetDescriptor());
Elliott Hughes545a0642011-11-08 19:10:03 -08003952
Mathieu Chartier46e811b2013-07-10 17:09:14 -07003953 MethodHelper mh;
3954 for (size_t i = 0; i < kMaxAllocRecordStackDepth; i++) {
Brian Carlstromea46f952013-07-30 01:26:50 -07003955 mirror::ArtMethod* m = record->stack[i].method;
Mathieu Chartier46e811b2013-07-10 17:09:14 -07003956 if (m != NULL) {
3957 mh.ChangeMethod(m);
3958 class_names.Add(mh.GetDeclaringClassDescriptor());
3959 method_names.Add(mh.GetName());
3960 filenames.Add(mh.GetDeclaringClassSourceFile());
3961 }
3962 }
Elliott Hughes545a0642011-11-08 19:10:03 -08003963
Elliott Hughesb1a58792013-07-11 18:10:58 -07003964 idx = (idx + 1) & (gAllocRecordMax-1);
Elliott Hughes545a0642011-11-08 19:10:03 -08003965 }
3966
Mathieu Chartier46e811b2013-07-10 17:09:14 -07003967 LOG(INFO) << "allocation records: " << gAllocRecordCount;
3968
3969 //
3970 // Part 2: Generate the output and store it in the buffer.
3971 //
3972
3973 // (1b) message header len (to allow future expansion); includes itself
3974 // (1b) entry header len
3975 // (1b) stack frame len
3976 const int kMessageHeaderLen = 15;
3977 const int kEntryHeaderLen = 9;
3978 const int kStackFrameLen = 8;
3979 JDWP::Append1BE(bytes, kMessageHeaderLen);
3980 JDWP::Append1BE(bytes, kEntryHeaderLen);
3981 JDWP::Append1BE(bytes, kStackFrameLen);
3982
3983 // (2b) number of entries
3984 // (4b) offset to string table from start of message
3985 // (2b) number of class name strings
3986 // (2b) number of method name strings
3987 // (2b) number of source file name strings
3988 JDWP::Append2BE(bytes, gAllocRecordCount);
3989 size_t string_table_offset = bytes.size();
Brian Carlstrom7934ac22013-07-26 10:54:15 -07003990 JDWP::Append4BE(bytes, 0); // We'll patch this later...
Mathieu Chartier46e811b2013-07-10 17:09:14 -07003991 JDWP::Append2BE(bytes, class_names.Size());
3992 JDWP::Append2BE(bytes, method_names.Size());
3993 JDWP::Append2BE(bytes, filenames.Size());
3994
3995 count = gAllocRecordCount;
3996 idx = HeadIndex();
Mathieu Chartier46e811b2013-07-10 17:09:14 -07003997 while (count--) {
3998 // For each entry:
3999 // (4b) total allocation size
4000 // (2b) thread id
4001 // (2b) allocated object's class name index
4002 // (1b) stack depth
4003 AllocRecord* record = &recent_allocation_records_[idx];
4004 size_t stack_depth = record->GetDepth();
Mathieu Chartier590fee92013-09-13 13:46:47 -07004005 ClassHelper kh(record->type);
Mathieu Chartier46e811b2013-07-10 17:09:14 -07004006 size_t allocated_object_class_name_index = class_names.IndexOf(kh.GetDescriptor());
4007 JDWP::Append4BE(bytes, record->byte_count);
4008 JDWP::Append2BE(bytes, record->thin_lock_id);
4009 JDWP::Append2BE(bytes, allocated_object_class_name_index);
4010 JDWP::Append1BE(bytes, stack_depth);
4011
4012 MethodHelper mh;
4013 for (size_t stack_frame = 0; stack_frame < stack_depth; ++stack_frame) {
4014 // For each stack frame:
4015 // (2b) method's class name
4016 // (2b) method name
4017 // (2b) method source file
4018 // (2b) line number, clipped to 32767; -2 if native; -1 if no source
4019 mh.ChangeMethod(record->stack[stack_frame].method);
4020 size_t class_name_index = class_names.IndexOf(mh.GetDeclaringClassDescriptor());
4021 size_t method_name_index = method_names.IndexOf(mh.GetName());
4022 size_t file_name_index = filenames.IndexOf(mh.GetDeclaringClassSourceFile());
4023 JDWP::Append2BE(bytes, class_name_index);
4024 JDWP::Append2BE(bytes, method_name_index);
4025 JDWP::Append2BE(bytes, file_name_index);
4026 JDWP::Append2BE(bytes, record->stack[stack_frame].LineNumber());
4027 }
4028
Elliott Hughesb1a58792013-07-11 18:10:58 -07004029 idx = (idx + 1) & (gAllocRecordMax-1);
Mathieu Chartier46e811b2013-07-10 17:09:14 -07004030 }
4031
4032 // (xb) class name strings
4033 // (xb) method name strings
4034 // (xb) source file strings
4035 JDWP::Set4BE(&bytes[string_table_offset], bytes.size());
4036 class_names.WriteTo(bytes);
4037 method_names.WriteTo(bytes);
4038 filenames.WriteTo(bytes);
Elliott Hughes545a0642011-11-08 19:10:03 -08004039 }
Ian Rogers50b35e22012-10-04 10:09:15 -07004040 JNIEnv* env = self->GetJniEnv();
Elliott Hughes545a0642011-11-08 19:10:03 -08004041 jbyteArray result = env->NewByteArray(bytes.size());
4042 if (result != NULL) {
4043 env->SetByteArrayRegion(result, 0, bytes.size(), reinterpret_cast<const jbyte*>(&bytes[0]));
4044 }
4045 return result;
4046}
4047
Elliott Hughes872d4ec2011-10-21 17:07:15 -07004048} // namespace art