blob: 89f841eb3d1432b02da4d908bc55b3001acbc4ed [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 Rogers2dd0e2c2013-01-24 12:42:14 -0800292static JDWP::JdwpTag TagFromClass(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 }
298
Elliott Hughes3d30d9b2011-12-07 17:35:48 -0800299 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
Elliott Hughes24437992011-11-30 14:49:33 -0800300 if (c->IsStringClass()) {
301 return JDWP::JT_STRING;
302 } else if (c->IsClassClass()) {
303 return JDWP::JT_CLASS_OBJECT;
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -0800304 } else if (class_linker->FindSystemClass("Ljava/lang/Thread;")->IsAssignableFrom(c)) {
Elliott Hughes24437992011-11-30 14:49:33 -0800305 return JDWP::JT_THREAD;
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -0800306 } else if (class_linker->FindSystemClass("Ljava/lang/ThreadGroup;")->IsAssignableFrom(c)) {
Elliott Hughes24437992011-11-30 14:49:33 -0800307 return JDWP::JT_THREAD_GROUP;
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -0800308 } else if (class_linker->FindSystemClass("Ljava/lang/ClassLoader;")->IsAssignableFrom(c)) {
Elliott Hughes24437992011-11-30 14:49:33 -0800309 return JDWP::JT_CLASS_LOADER;
Elliott Hughes24437992011-11-30 14:49:33 -0800310 } else {
311 return JDWP::JT_OBJECT;
312 }
313}
314
315/*
316 * Objects declared to hold Object might actually hold a more specific
317 * type. The debugger may take a special interest in these (e.g. it
318 * wants to display the contents of Strings), so we want to return an
319 * appropriate tag.
320 *
321 * Null objects are tagged JT_OBJECT.
322 */
Ian Rogersef7d42f2014-01-06 12:55:46 -0800323static JDWP::JdwpTag TagFromObject(mirror::Object* o)
Ian Rogersb726dcb2012-09-05 08:57:23 -0700324 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Elliott Hughes24437992011-11-30 14:49:33 -0800325 return (o == NULL) ? JDWP::JT_OBJECT : TagFromClass(o->GetClass());
326}
327
328static bool IsPrimitiveTag(JDWP::JdwpTag tag) {
329 switch (tag) {
330 case JDWP::JT_BOOLEAN:
331 case JDWP::JT_BYTE:
332 case JDWP::JT_CHAR:
333 case JDWP::JT_FLOAT:
334 case JDWP::JT_DOUBLE:
335 case JDWP::JT_INT:
336 case JDWP::JT_LONG:
337 case JDWP::JT_SHORT:
338 case JDWP::JT_VOID:
339 return true;
340 default:
341 return false;
342 }
343}
344
Elliott Hughes3bb81562011-10-21 18:52:59 -0700345/*
346 * Handle one of the JDWP name/value pairs.
347 *
348 * JDWP options are:
349 * help: if specified, show help message and bail
350 * transport: may be dt_socket or dt_shmem
351 * address: for dt_socket, "host:port", or just "port" when listening
352 * server: if "y", wait for debugger to attach; if "n", attach to debugger
353 * timeout: how long to wait for debugger to connect / listen
354 *
355 * Useful with server=n (these aren't supported yet):
356 * onthrow=<exception-name>: connect to debugger when exception thrown
357 * onuncaught=y|n: connect to debugger when uncaught exception thrown
358 * launch=<command-line>: launch the debugger itself
359 *
360 * The "transport" option is required, as is "address" if server=n.
361 */
362static bool ParseJdwpOption(const std::string& name, const std::string& value) {
363 if (name == "transport") {
364 if (value == "dt_socket") {
Elliott Hughes376a7a02011-10-24 18:35:55 -0700365 gJdwpOptions.transport = JDWP::kJdwpTransportSocket;
Elliott Hughes3bb81562011-10-21 18:52:59 -0700366 } else if (value == "dt_android_adb") {
Elliott Hughes376a7a02011-10-24 18:35:55 -0700367 gJdwpOptions.transport = JDWP::kJdwpTransportAndroidAdb;
Elliott Hughes3bb81562011-10-21 18:52:59 -0700368 } else {
369 LOG(ERROR) << "JDWP transport not supported: " << value;
370 return false;
371 }
372 } else if (name == "server") {
373 if (value == "n") {
Elliott Hughes376a7a02011-10-24 18:35:55 -0700374 gJdwpOptions.server = false;
Elliott Hughes3bb81562011-10-21 18:52:59 -0700375 } else if (value == "y") {
Elliott Hughes376a7a02011-10-24 18:35:55 -0700376 gJdwpOptions.server = true;
Elliott Hughes3bb81562011-10-21 18:52:59 -0700377 } else {
378 LOG(ERROR) << "JDWP option 'server' must be 'y' or 'n'";
379 return false;
380 }
381 } else if (name == "suspend") {
382 if (value == "n") {
Elliott Hughes376a7a02011-10-24 18:35:55 -0700383 gJdwpOptions.suspend = false;
Elliott Hughes3bb81562011-10-21 18:52:59 -0700384 } else if (value == "y") {
Elliott Hughes376a7a02011-10-24 18:35:55 -0700385 gJdwpOptions.suspend = true;
Elliott Hughes3bb81562011-10-21 18:52:59 -0700386 } else {
387 LOG(ERROR) << "JDWP option 'suspend' must be 'y' or 'n'";
388 return false;
389 }
390 } else if (name == "address") {
391 /* this is either <port> or <host>:<port> */
392 std::string port_string;
Elliott Hughes376a7a02011-10-24 18:35:55 -0700393 gJdwpOptions.host.clear();
Elliott Hughes3bb81562011-10-21 18:52:59 -0700394 std::string::size_type colon = value.find(':');
395 if (colon != std::string::npos) {
Elliott Hughes376a7a02011-10-24 18:35:55 -0700396 gJdwpOptions.host = value.substr(0, colon);
Elliott Hughes3bb81562011-10-21 18:52:59 -0700397 port_string = value.substr(colon + 1);
398 } else {
399 port_string = value;
400 }
401 if (port_string.empty()) {
402 LOG(ERROR) << "JDWP address missing port: " << value;
403 return false;
404 }
405 char* end;
Elliott Hughesba8eee12012-01-24 20:25:24 -0800406 uint64_t port = strtoul(port_string.c_str(), &end, 10);
407 if (*end != '\0' || port > 0xffff) {
Elliott Hughes3bb81562011-10-21 18:52:59 -0700408 LOG(ERROR) << "JDWP address has junk in port field: " << value;
409 return false;
410 }
Elliott Hughes376a7a02011-10-24 18:35:55 -0700411 gJdwpOptions.port = port;
Elliott Hughes3bb81562011-10-21 18:52:59 -0700412 } else if (name == "launch" || name == "onthrow" || name == "oncaught" || name == "timeout") {
413 /* valid but unsupported */
414 LOG(INFO) << "Ignoring JDWP option '" << name << "'='" << value << "'";
415 } else {
416 LOG(INFO) << "Ignoring unrecognized JDWP option '" << name << "'='" << value << "'";
417 }
418
419 return true;
420}
421
422/*
423 * Parse the latter half of a -Xrunjdwp/-agentlib:jdwp= string, e.g.:
424 * "transport=dt_socket,address=8000,server=y,suspend=n"
425 */
426bool Dbg::ParseJdwpOptions(const std::string& options) {
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -0800427 VLOG(jdwp) << "ParseJdwpOptions: " << options;
Elliott Hughes47fce012011-10-25 18:37:19 -0700428
Elliott Hughes3bb81562011-10-21 18:52:59 -0700429 std::vector<std::string> pairs;
430 Split(options, ',', pairs);
431
432 for (size_t i = 0; i < pairs.size(); ++i) {
433 std::string::size_type equals = pairs[i].find('=');
434 if (equals == std::string::npos) {
435 LOG(ERROR) << "Can't parse JDWP option '" << pairs[i] << "' in '" << options << "'";
436 return false;
437 }
438 ParseJdwpOption(pairs[i].substr(0, equals), pairs[i].substr(equals + 1));
439 }
440
Elliott Hughes376a7a02011-10-24 18:35:55 -0700441 if (gJdwpOptions.transport == JDWP::kJdwpTransportUnknown) {
Elliott Hughes3bb81562011-10-21 18:52:59 -0700442 LOG(ERROR) << "Must specify JDWP transport: " << options;
443 }
Elliott Hughes376a7a02011-10-24 18:35:55 -0700444 if (!gJdwpOptions.server && (gJdwpOptions.host.empty() || gJdwpOptions.port == 0)) {
Elliott Hughes3bb81562011-10-21 18:52:59 -0700445 LOG(ERROR) << "Must specify JDWP host and port when server=n: " << options;
446 return false;
447 }
448
449 gJdwpConfigured = true;
450 return true;
451}
452
Elliott Hughesd1cc8362011-10-24 16:58:50 -0700453void Dbg::StartJdwp() {
Elliott Hughesc0f09332012-03-26 13:27:06 -0700454 if (!gJdwpAllowed || !IsJdwpConfigured()) {
Elliott Hughes376a7a02011-10-24 18:35:55 -0700455 // No JDWP for you!
456 return;
457 }
458
Elliott Hughes475fc232011-10-25 15:00:35 -0700459 CHECK(gRegistry == NULL);
460 gRegistry = new ObjectRegistry;
461
Elliott Hughesd1cc8362011-10-24 16:58:50 -0700462 // Init JDWP if the debugger is enabled. This may connect out to a
463 // debugger, passively listen for a debugger, or block waiting for a
464 // debugger.
Elliott Hughes376a7a02011-10-24 18:35:55 -0700465 gJdwpState = JDWP::JdwpState::Create(&gJdwpOptions);
466 if (gJdwpState == NULL) {
Elliott Hughesf8a2df72011-12-01 12:19:54 -0800467 // We probably failed because some other process has the port already, which means that
468 // if we don't abort the user is likely to think they're talking to us when they're actually
469 // talking to that other process.
Elliott Hughes3d30d9b2011-12-07 17:35:48 -0800470 LOG(FATAL) << "Debugger thread failed to initialize";
Elliott Hughesd1cc8362011-10-24 16:58:50 -0700471 }
472
473 // If a debugger has already attached, send the "welcome" message.
474 // This may cause us to suspend all threads.
Elliott Hughes376a7a02011-10-24 18:35:55 -0700475 if (gJdwpState->IsActive()) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700476 ScopedObjectAccess soa(Thread::Current());
Elliott Hughes376a7a02011-10-24 18:35:55 -0700477 if (!gJdwpState->PostVMStart()) {
Elliott Hughes3d30d9b2011-12-07 17:35:48 -0800478 LOG(WARNING) << "Failed to post 'start' message to debugger";
Elliott Hughesd1cc8362011-10-24 16:58:50 -0700479 }
480 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700481}
482
Elliott Hughesd1cc8362011-10-24 16:58:50 -0700483void Dbg::StopJdwp() {
Sebastien Hertz0376e6b2014-02-06 18:12:59 +0100484 // Prevent the JDWP thread from processing JDWP incoming packets after we close the connection.
485 Disposed();
Elliott Hughes376a7a02011-10-24 18:35:55 -0700486 delete gJdwpState;
Sebastien Hertz123756a2013-11-27 15:49:42 +0100487 gJdwpState = NULL;
Elliott Hughes475fc232011-10-25 15:00:35 -0700488 delete gRegistry;
489 gRegistry = NULL;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700490}
491
Elliott Hughes767a1472011-10-26 18:49:02 -0700492void Dbg::GcDidFinish() {
493 if (gDdmHpifWhen != HPIF_WHEN_NEVER) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700494 ScopedObjectAccess soa(Thread::Current());
Elliott Hughes81ff3182012-03-23 20:35:56 -0700495 LOG(DEBUG) << "Sending heap info to DDM";
Elliott Hughes7162ad92011-10-27 14:08:42 -0700496 DdmSendHeapInfo(gDdmHpifWhen);
Elliott Hughes767a1472011-10-26 18:49:02 -0700497 }
498 if (gDdmHpsgWhen != HPSG_WHEN_NEVER) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700499 ScopedObjectAccess soa(Thread::Current());
Elliott Hughes81ff3182012-03-23 20:35:56 -0700500 LOG(DEBUG) << "Dumping heap to DDM";
Elliott Hughes6a5bd492011-10-28 14:33:57 -0700501 DdmSendHeapSegments(false);
Elliott Hughes767a1472011-10-26 18:49:02 -0700502 }
503 if (gDdmNhsgWhen != HPSG_WHEN_NEVER) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700504 ScopedObjectAccess soa(Thread::Current());
Elliott Hughes767a1472011-10-26 18:49:02 -0700505 LOG(DEBUG) << "Dumping native heap to DDM";
Elliott Hughes6a5bd492011-10-28 14:33:57 -0700506 DdmSendHeapSegments(true);
Elliott Hughes767a1472011-10-26 18:49:02 -0700507 }
508}
509
Elliott Hughes4ffd3132011-10-24 12:06:42 -0700510void Dbg::SetJdwpAllowed(bool allowed) {
511 gJdwpAllowed = allowed;
512}
513
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700514DebugInvokeReq* Dbg::GetInvokeReq() {
Elliott Hughes475fc232011-10-25 15:00:35 -0700515 return Thread::Current()->GetInvokeReq();
516}
517
518Thread* Dbg::GetDebugThread() {
519 return (gJdwpState != NULL) ? gJdwpState->GetDebugThread() : NULL;
520}
521
522void Dbg::ClearWaitForEventThread() {
523 gJdwpState->ClearWaitForEventThread();
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700524}
525
526void Dbg::Connected() {
Elliott Hughes3bb81562011-10-21 18:52:59 -0700527 CHECK(!gDebuggerConnected);
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -0800528 VLOG(jdwp) << "JDWP has attached";
Elliott Hughes3bb81562011-10-21 18:52:59 -0700529 gDebuggerConnected = true;
Elliott Hughes86964332012-02-15 19:37:42 -0800530 gDisposed = false;
531}
532
533void Dbg::Disposed() {
534 gDisposed = true;
535}
536
537bool Dbg::IsDisposed() {
538 return gDisposed;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700539}
540
Elliott Hughesa2155262011-11-16 16:26:58 -0800541void Dbg::GoActive() {
542 // Enable all debugging features, including scans for breakpoints.
543 // This is a no-op if we're already active.
544 // Only called from the JDWP handler thread.
545 if (gDebuggerActive) {
546 return;
547 }
548
Elliott Hughesc0f09332012-03-26 13:27:06 -0700549 {
550 // TODO: dalvik only warned if there were breakpoints left over. clear in Dbg::Disconnected?
jeffhao09bfc6a2012-12-11 18:11:43 -0800551 MutexLock mu(Thread::Current(), *Locks::breakpoint_lock_);
Elliott Hughesc0f09332012-03-26 13:27:06 -0700552 CHECK_EQ(gBreakpoints.size(), 0U);
553 }
Elliott Hughesa2155262011-11-16 16:26:58 -0800554
Sebastien Hertz138dbfc2013-12-04 18:15:25 +0100555 {
556 MutexLock mu(Thread::Current(), *Locks::deoptimization_lock_);
557 CHECK_EQ(gDeoptimizationRequests.size(), 0U);
558 }
559
Ian Rogers62d6c772013-02-27 08:32:07 -0800560 Runtime* runtime = Runtime::Current();
561 runtime->GetThreadList()->SuspendAll();
562 Thread* self = Thread::Current();
563 ThreadState old_state = self->SetStateUnsafe(kRunnable);
564 CHECK_NE(old_state, kRunnable);
Sebastien Hertz138dbfc2013-12-04 18:15:25 +0100565 runtime->GetInstrumentation()->EnableDeoptimization();
Ian Rogers62d6c772013-02-27 08:32:07 -0800566 runtime->GetInstrumentation()->AddListener(&gDebugInstrumentationListener,
567 instrumentation::Instrumentation::kMethodEntered |
568 instrumentation::Instrumentation::kMethodExited |
Jeff Hao14dd5a82013-04-11 10:23:36 -0700569 instrumentation::Instrumentation::kDexPcMoved |
570 instrumentation::Instrumentation::kExceptionCaught);
Elliott Hughesa2155262011-11-16 16:26:58 -0800571 gDebuggerActive = true;
Ian Rogers62d6c772013-02-27 08:32:07 -0800572 CHECK_EQ(self->SetStateUnsafe(old_state), kRunnable);
573 runtime->GetThreadList()->ResumeAll();
574
575 LOG(INFO) << "Debugger is active";
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700576}
577
578void Dbg::Disconnected() {
Elliott Hughes234ab152011-10-26 14:02:26 -0700579 CHECK(gDebuggerConnected);
580
Elliott Hughesc0f09332012-03-26 13:27:06 -0700581 LOG(INFO) << "Debugger is no longer active";
Elliott Hughes234ab152011-10-26 14:02:26 -0700582
Ian Rogers62d6c772013-02-27 08:32:07 -0800583 // Suspend all threads and exclusively acquire the mutator lock. Set the state of the thread
584 // to kRunnable to avoid scoped object access transitions. Remove the debugger as a listener
585 // and clear the object registry.
586 Runtime* runtime = Runtime::Current();
587 runtime->GetThreadList()->SuspendAll();
588 Thread* self = Thread::Current();
589 ThreadState old_state = self->SetStateUnsafe(kRunnable);
Sebastien Hertz138dbfc2013-12-04 18:15:25 +0100590 {
591 // Since we're going to disable deoptimization, we clear the deoptimization requests queue.
592 // This prevent us from having any pending deoptimization request when the debugger attaches to
593 // us again while no event has been requested yet.
594 MutexLock mu(Thread::Current(), *Locks::deoptimization_lock_);
595 gDeoptimizationRequests.clear();
596 }
Ian Rogers62d6c772013-02-27 08:32:07 -0800597 runtime->GetInstrumentation()->RemoveListener(&gDebugInstrumentationListener,
598 instrumentation::Instrumentation::kMethodEntered |
599 instrumentation::Instrumentation::kMethodExited |
Jeff Hao14dd5a82013-04-11 10:23:36 -0700600 instrumentation::Instrumentation::kDexPcMoved |
601 instrumentation::Instrumentation::kExceptionCaught);
Sebastien Hertz11d40c22014-02-19 18:00:17 +0100602 runtime->GetInstrumentation()->DisableDeoptimization();
Elliott Hughesc0f09332012-03-26 13:27:06 -0700603 gDebuggerActive = false;
Elliott Hughes234ab152011-10-26 14:02:26 -0700604 gRegistry->Clear();
605 gDebuggerConnected = false;
Ian Rogers62d6c772013-02-27 08:32:07 -0800606 CHECK_EQ(self->SetStateUnsafe(old_state), kRunnable);
607 runtime->GetThreadList()->ResumeAll();
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700608}
609
Elliott Hughesc0f09332012-03-26 13:27:06 -0700610bool Dbg::IsDebuggerActive() {
Elliott Hughes3bb81562011-10-21 18:52:59 -0700611 return gDebuggerActive;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700612}
613
Elliott Hughesc0f09332012-03-26 13:27:06 -0700614bool Dbg::IsJdwpConfigured() {
Elliott Hughes3bb81562011-10-21 18:52:59 -0700615 return gJdwpConfigured;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700616}
617
618int64_t Dbg::LastDebuggerActivity() {
Elliott Hughesca951522011-12-05 12:01:32 -0800619 return gJdwpState->LastDebuggerActivity();
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700620}
621
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700622void Dbg::UndoDebuggerSuspensions() {
Elliott Hughes234ab152011-10-26 14:02:26 -0700623 Runtime::Current()->GetThreadList()->UndoDebuggerSuspensions();
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700624}
625
Elliott Hughes88d63092013-01-09 09:55:54 -0800626std::string Dbg::GetClassName(JDWP::RefTypeId class_id) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800627 mirror::Object* o = gRegistry->Get<mirror::Object*>(class_id);
Elliott Hughes436e3722012-02-17 20:01:47 -0800628 if (o == NULL) {
629 return "NULL";
630 }
Elliott Hughes64f574f2013-02-20 14:57:12 -0800631 if (o == ObjectRegistry::kInvalidObject) {
Elliott Hughes88d63092013-01-09 09:55:54 -0800632 return StringPrintf("invalid object %p", reinterpret_cast<void*>(class_id));
Elliott Hughes436e3722012-02-17 20:01:47 -0800633 }
634 if (!o->IsClass()) {
Brian Carlstrom7934ac22013-07-26 10:54:15 -0700635 return StringPrintf("non-class %p", o); // This is only used for debugging output anyway.
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -0800636 }
Elliott Hughesc308a5d2012-02-16 17:12:06 -0800637 return DescriptorToName(ClassHelper(o->AsClass()).GetDescriptor());
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700638}
639
Elliott Hughes88d63092013-01-09 09:55:54 -0800640JDWP::JdwpError Dbg::GetClassObject(JDWP::RefTypeId id, JDWP::ObjectId& class_object_id) {
Elliott Hughes436e3722012-02-17 20:01:47 -0800641 JDWP::JdwpError status;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800642 mirror::Class* c = DecodeClass(id, status);
Elliott Hughes436e3722012-02-17 20:01:47 -0800643 if (c == NULL) {
644 return status;
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -0800645 }
Elliott Hughes88d63092013-01-09 09:55:54 -0800646 class_object_id = gRegistry->Add(c);
Elliott Hughes436e3722012-02-17 20:01:47 -0800647 return JDWP::ERR_NONE;
Elliott Hughes86964332012-02-15 19:37:42 -0800648}
649
Elliott Hughes88d63092013-01-09 09:55:54 -0800650JDWP::JdwpError Dbg::GetSuperclass(JDWP::RefTypeId id, JDWP::RefTypeId& superclass_id) {
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -0800651 JDWP::JdwpError status;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800652 mirror::Class* c = DecodeClass(id, status);
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -0800653 if (c == NULL) {
654 return status;
655 }
656 if (c->IsInterface()) {
657 // http://code.google.com/p/android/issues/detail?id=20856
Elliott Hughes88d63092013-01-09 09:55:54 -0800658 superclass_id = 0;
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -0800659 } else {
Elliott Hughes88d63092013-01-09 09:55:54 -0800660 superclass_id = gRegistry->Add(c->GetSuperClass());
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -0800661 }
662 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700663}
664
Elliott Hughes436e3722012-02-17 20:01:47 -0800665JDWP::JdwpError Dbg::GetClassLoader(JDWP::RefTypeId id, JDWP::ExpandBuf* pReply) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800666 mirror::Object* o = gRegistry->Get<mirror::Object*>(id);
Elliott Hughes64f574f2013-02-20 14:57:12 -0800667 if (o == NULL || o == ObjectRegistry::kInvalidObject) {
Elliott Hughes436e3722012-02-17 20:01:47 -0800668 return JDWP::ERR_INVALID_OBJECT;
669 }
670 expandBufAddObjectId(pReply, gRegistry->Add(o->GetClass()->GetClassLoader()));
671 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700672}
673
Elliott Hughes436e3722012-02-17 20:01:47 -0800674JDWP::JdwpError Dbg::GetModifiers(JDWP::RefTypeId id, JDWP::ExpandBuf* pReply) {
675 JDWP::JdwpError status;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800676 mirror::Class* c = DecodeClass(id, status);
Elliott Hughes436e3722012-02-17 20:01:47 -0800677 if (c == NULL) {
678 return status;
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -0800679 }
Elliott Hughes436e3722012-02-17 20:01:47 -0800680
681 uint32_t access_flags = c->GetAccessFlags() & kAccJavaFlagsMask;
682
Yevgeny Roubande34eea2014-02-15 01:06:03 +0700683 // Set ACC_SUPER. Dex files don't contain this flag but only classes are supposed to have it set,
684 // not interfaces.
Elliott Hughes436e3722012-02-17 20:01:47 -0800685 // Class.getModifiers doesn't return it, but JDWP does, so we set it here.
Yevgeny Roubande34eea2014-02-15 01:06:03 +0700686 if ((access_flags & kAccInterface) == 0) {
687 access_flags |= kAccSuper;
688 }
Elliott Hughes436e3722012-02-17 20:01:47 -0800689
690 expandBufAdd4BE(pReply, access_flags);
691
692 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700693}
694
Elliott Hughesf327e072013-01-09 16:01:26 -0800695JDWP::JdwpError Dbg::GetMonitorInfo(JDWP::ObjectId object_id, JDWP::ExpandBuf* reply)
696 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800697 mirror::Object* o = gRegistry->Get<mirror::Object*>(object_id);
Elliott Hughes64f574f2013-02-20 14:57:12 -0800698 if (o == NULL || o == ObjectRegistry::kInvalidObject) {
Elliott Hughesf327e072013-01-09 16:01:26 -0800699 return JDWP::ERR_INVALID_OBJECT;
700 }
701
702 // Ensure all threads are suspended while we read objects' lock words.
703 Thread* self = Thread::Current();
704 Locks::mutator_lock_->SharedUnlock(self);
705 Locks::mutator_lock_->ExclusiveLock(self);
706
707 MonitorInfo monitor_info(o);
708
709 Locks::mutator_lock_->ExclusiveUnlock(self);
710 Locks::mutator_lock_->SharedLock(self);
711
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700712 if (monitor_info.owner_ != NULL) {
713 expandBufAddObjectId(reply, gRegistry->Add(monitor_info.owner_->GetPeer()));
Elliott Hughesf327e072013-01-09 16:01:26 -0800714 } else {
715 expandBufAddObjectId(reply, gRegistry->Add(NULL));
716 }
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700717 expandBufAdd4BE(reply, monitor_info.entry_count_);
718 expandBufAdd4BE(reply, monitor_info.waiters_.size());
719 for (size_t i = 0; i < monitor_info.waiters_.size(); ++i) {
720 expandBufAddObjectId(reply, gRegistry->Add(monitor_info.waiters_[i]->GetPeer()));
Elliott Hughesf327e072013-01-09 16:01:26 -0800721 }
722 return JDWP::ERR_NONE;
723}
724
Elliott Hughes734b8c62013-01-11 15:32:45 -0800725JDWP::JdwpError Dbg::GetOwnedMonitors(JDWP::ObjectId thread_id,
726 std::vector<JDWP::ObjectId>& monitors,
727 std::vector<uint32_t>& stack_depths)
Elliott Hughes4993bbc2013-01-10 15:41:25 -0800728 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
729 ScopedObjectAccessUnchecked soa(Thread::Current());
730 MutexLock mu(soa.Self(), *Locks::thread_list_lock_);
731 Thread* thread;
732 JDWP::JdwpError error = DecodeThread(soa, thread_id, thread);
733 if (error != JDWP::ERR_NONE) {
734 return error;
735 }
736 if (!IsSuspendedForDebugger(soa, thread)) {
737 return JDWP::ERR_THREAD_NOT_SUSPENDED;
738 }
739
740 struct OwnedMonitorVisitor : public StackVisitor {
Ian Rogers7a22fa62013-01-23 12:16:16 -0800741 OwnedMonitorVisitor(Thread* thread, Context* context)
Elliott Hughes4993bbc2013-01-10 15:41:25 -0800742 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_)
Ian Rogers7a22fa62013-01-23 12:16:16 -0800743 : StackVisitor(thread, context), current_stack_depth(0) {}
Elliott Hughes4993bbc2013-01-10 15:41:25 -0800744
745 // TODO: Enable annotalysis. We know lock is held in constructor, but abstraction confuses
746 // annotalysis.
747 bool VisitFrame() NO_THREAD_SAFETY_ANALYSIS {
748 if (!GetMethod()->IsRuntimeMethod()) {
749 Monitor::VisitLocks(this, AppendOwnedMonitors, this);
Elliott Hughes734b8c62013-01-11 15:32:45 -0800750 ++current_stack_depth;
Elliott Hughes4993bbc2013-01-10 15:41:25 -0800751 }
752 return true;
753 }
754
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800755 static void AppendOwnedMonitors(mirror::Object* owned_monitor, void* arg) {
Ian Rogers7a22fa62013-01-23 12:16:16 -0800756 OwnedMonitorVisitor* visitor = reinterpret_cast<OwnedMonitorVisitor*>(arg);
Elliott Hughes734b8c62013-01-11 15:32:45 -0800757 visitor->monitors.push_back(owned_monitor);
758 visitor->stack_depths.push_back(visitor->current_stack_depth);
Elliott Hughes4993bbc2013-01-10 15:41:25 -0800759 }
760
Elliott Hughes734b8c62013-01-11 15:32:45 -0800761 size_t current_stack_depth;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800762 std::vector<mirror::Object*> monitors;
Elliott Hughes734b8c62013-01-11 15:32:45 -0800763 std::vector<uint32_t> stack_depths;
Elliott Hughes4993bbc2013-01-10 15:41:25 -0800764 };
Ian Rogers7a22fa62013-01-23 12:16:16 -0800765 UniquePtr<Context> context(Context::Create());
766 OwnedMonitorVisitor visitor(thread, context.get());
Elliott Hughes4993bbc2013-01-10 15:41:25 -0800767 visitor.WalkStack();
768
769 for (size_t i = 0; i < visitor.monitors.size(); ++i) {
770 monitors.push_back(gRegistry->Add(visitor.monitors[i]));
Elliott Hughes734b8c62013-01-11 15:32:45 -0800771 stack_depths.push_back(visitor.stack_depths[i]);
Elliott Hughes4993bbc2013-01-10 15:41:25 -0800772 }
773
774 return JDWP::ERR_NONE;
775}
776
Elliott Hughesf9501702013-01-11 11:22:27 -0800777JDWP::JdwpError Dbg::GetContendedMonitor(JDWP::ObjectId thread_id, JDWP::ObjectId& contended_monitor)
778 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
779 ScopedObjectAccessUnchecked soa(Thread::Current());
780 MutexLock mu(soa.Self(), *Locks::thread_list_lock_);
781 Thread* thread;
782 JDWP::JdwpError error = DecodeThread(soa, thread_id, thread);
783 if (error != JDWP::ERR_NONE) {
784 return error;
785 }
786 if (!IsSuspendedForDebugger(soa, thread)) {
787 return JDWP::ERR_THREAD_NOT_SUSPENDED;
788 }
789
790 contended_monitor = gRegistry->Add(Monitor::GetContendedMonitor(thread));
791
792 return JDWP::ERR_NONE;
793}
794
Elliott Hughesec0f83d2013-01-15 16:54:08 -0800795JDWP::JdwpError Dbg::GetInstanceCounts(const std::vector<JDWP::RefTypeId>& class_ids,
796 std::vector<uint64_t>& counts)
797 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Mathieu Chartier412c7fc2014-02-07 12:18:39 -0800798 gc::Heap* heap = Runtime::Current()->GetHeap();
799 heap->CollectGarbage(false);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800800 std::vector<mirror::Class*> classes;
Elliott Hughesec0f83d2013-01-15 16:54:08 -0800801 counts.clear();
802 for (size_t i = 0; i < class_ids.size(); ++i) {
803 JDWP::JdwpError status;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800804 mirror::Class* c = DecodeClass(class_ids[i], status);
Elliott Hughesec0f83d2013-01-15 16:54:08 -0800805 if (c == NULL) {
806 return status;
807 }
808 classes.push_back(c);
809 counts.push_back(0);
810 }
Mathieu Chartier412c7fc2014-02-07 12:18:39 -0800811 heap->CountInstances(classes, false, &counts[0]);
Elliott Hughesec0f83d2013-01-15 16:54:08 -0800812 return JDWP::ERR_NONE;
813}
814
Elliott Hughes3b78c942013-01-15 17:35:41 -0800815JDWP::JdwpError Dbg::GetInstances(JDWP::RefTypeId class_id, int32_t max_count, std::vector<JDWP::ObjectId>& instances)
816 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Mathieu Chartier412c7fc2014-02-07 12:18:39 -0800817 gc::Heap* heap = Runtime::Current()->GetHeap();
818 // We only want reachable instances, so do a GC.
819 heap->CollectGarbage(false);
Elliott Hughes3b78c942013-01-15 17:35:41 -0800820 JDWP::JdwpError status;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800821 mirror::Class* c = DecodeClass(class_id, status);
Mathieu Chartier412c7fc2014-02-07 12:18:39 -0800822 if (c == nullptr) {
Elliott Hughes3b78c942013-01-15 17:35:41 -0800823 return status;
824 }
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800825 std::vector<mirror::Object*> raw_instances;
Elliott Hughes3b78c942013-01-15 17:35:41 -0800826 Runtime::Current()->GetHeap()->GetInstances(c, max_count, raw_instances);
827 for (size_t i = 0; i < raw_instances.size(); ++i) {
828 instances.push_back(gRegistry->Add(raw_instances[i]));
829 }
830 return JDWP::ERR_NONE;
831}
832
Elliott Hughes0cbaff52013-01-16 15:28:01 -0800833JDWP::JdwpError Dbg::GetReferringObjects(JDWP::ObjectId object_id, int32_t max_count,
834 std::vector<JDWP::ObjectId>& referring_objects)
835 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Mathieu Chartier412c7fc2014-02-07 12:18:39 -0800836 gc::Heap* heap = Runtime::Current()->GetHeap();
837 heap->CollectGarbage(false);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800838 mirror::Object* o = gRegistry->Get<mirror::Object*>(object_id);
Elliott Hughes64f574f2013-02-20 14:57:12 -0800839 if (o == NULL || o == ObjectRegistry::kInvalidObject) {
Elliott Hughes0cbaff52013-01-16 15:28:01 -0800840 return JDWP::ERR_INVALID_OBJECT;
841 }
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800842 std::vector<mirror::Object*> raw_instances;
Mathieu Chartier412c7fc2014-02-07 12:18:39 -0800843 heap->GetReferringObjects(o, max_count, raw_instances);
Elliott Hughes0cbaff52013-01-16 15:28:01 -0800844 for (size_t i = 0; i < raw_instances.size(); ++i) {
845 referring_objects.push_back(gRegistry->Add(raw_instances[i]));
846 }
847 return JDWP::ERR_NONE;
848}
849
Elliott Hughes64f574f2013-02-20 14:57:12 -0800850JDWP::JdwpError Dbg::DisableCollection(JDWP::ObjectId object_id)
851 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Sebastien Hertze96060a2013-12-11 12:06:28 +0100852 mirror::Object* o = gRegistry->Get<mirror::Object*>(object_id);
853 if (o == NULL || o == ObjectRegistry::kInvalidObject) {
854 return JDWP::ERR_INVALID_OBJECT;
855 }
Elliott Hughes64f574f2013-02-20 14:57:12 -0800856 gRegistry->DisableCollection(object_id);
857 return JDWP::ERR_NONE;
858}
859
860JDWP::JdwpError Dbg::EnableCollection(JDWP::ObjectId object_id)
861 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Sebastien Hertze96060a2013-12-11 12:06:28 +0100862 mirror::Object* o = gRegistry->Get<mirror::Object*>(object_id);
863 // Unlike DisableCollection, JDWP specs do not state an invalid object causes an error. The RI
864 // also ignores these cases and never return an error. However it's not obvious why this command
865 // should behave differently from DisableCollection and IsCollected commands. So let's be more
866 // strict and return an error if this happens.
867 if (o == NULL || o == ObjectRegistry::kInvalidObject) {
868 return JDWP::ERR_INVALID_OBJECT;
869 }
Elliott Hughes64f574f2013-02-20 14:57:12 -0800870 gRegistry->EnableCollection(object_id);
871 return JDWP::ERR_NONE;
872}
873
874JDWP::JdwpError Dbg::IsCollected(JDWP::ObjectId object_id, bool& is_collected)
875 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Sebastien Hertz65637eb2014-01-10 17:40:02 +0100876 if (object_id == 0) {
877 // Null object id is invalid.
Sebastien Hertze96060a2013-12-11 12:06:28 +0100878 return JDWP::ERR_INVALID_OBJECT;
879 }
Sebastien Hertz65637eb2014-01-10 17:40:02 +0100880 // JDWP specs state an INVALID_OBJECT error is returned if the object ID is not valid. However
881 // the RI seems to ignore this and assume object has been collected.
882 mirror::Object* o = gRegistry->Get<mirror::Object*>(object_id);
883 if (o == NULL || o == ObjectRegistry::kInvalidObject) {
884 is_collected = true;
885 } else {
886 is_collected = gRegistry->IsCollected(object_id);
887 }
Elliott Hughes64f574f2013-02-20 14:57:12 -0800888 return JDWP::ERR_NONE;
889}
890
891void Dbg::DisposeObject(JDWP::ObjectId object_id, uint32_t reference_count)
892 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
893 gRegistry->DisposeObject(object_id, reference_count);
894}
895
Elliott Hughes88d63092013-01-09 09:55:54 -0800896JDWP::JdwpError Dbg::GetReflectedType(JDWP::RefTypeId class_id, JDWP::ExpandBuf* pReply) {
Elliott Hughes436e3722012-02-17 20:01:47 -0800897 JDWP::JdwpError status;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800898 mirror::Class* c = DecodeClass(class_id, status);
Elliott Hughes436e3722012-02-17 20:01:47 -0800899 if (c == NULL) {
900 return status;
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -0800901 }
Elliott Hughes436e3722012-02-17 20:01:47 -0800902
903 expandBufAdd1(pReply, c->IsInterface() ? JDWP::TT_INTERFACE : JDWP::TT_CLASS);
Elliott Hughes88d63092013-01-09 09:55:54 -0800904 expandBufAddRefTypeId(pReply, class_id);
Elliott Hughes436e3722012-02-17 20:01:47 -0800905 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700906}
907
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -0800908void Dbg::GetClassList(std::vector<JDWP::RefTypeId>& classes) {
Elliott Hughesa2155262011-11-16 16:26:58 -0800909 // Get the complete list of reference classes (i.e. all classes except
910 // the primitive types).
911 // Returns a newly-allocated buffer full of RefTypeId values.
912 struct ClassListCreator {
Elliott Hughesba8eee12012-01-24 20:25:24 -0800913 explicit ClassListCreator(std::vector<JDWP::RefTypeId>& classes) : classes(classes) {
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -0800914 }
915
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800916 static bool Visit(mirror::Class* c, void* arg) {
Elliott Hughesa2155262011-11-16 16:26:58 -0800917 return reinterpret_cast<ClassListCreator*>(arg)->Visit(c);
918 }
919
Elliott Hughes64f574f2013-02-20 14:57:12 -0800920 // TODO: Enable annotalysis. We know lock is held in constructor, but abstraction confuses
921 // annotalysis.
922 bool Visit(mirror::Class* c) NO_THREAD_SAFETY_ANALYSIS {
Elliott Hughesa2155262011-11-16 16:26:58 -0800923 if (!c->IsPrimitive()) {
Elliott Hughes64f574f2013-02-20 14:57:12 -0800924 classes.push_back(gRegistry->AddRefType(c));
Elliott Hughesa2155262011-11-16 16:26:58 -0800925 }
926 return true;
927 }
928
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -0800929 std::vector<JDWP::RefTypeId>& classes;
Elliott Hughesa2155262011-11-16 16:26:58 -0800930 };
931
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -0800932 ClassListCreator clc(classes);
Elliott Hughesa2155262011-11-16 16:26:58 -0800933 Runtime::Current()->GetClassLinker()->VisitClasses(ClassListCreator::Visit, &clc);
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700934}
935
Elliott Hughes88d63092013-01-09 09:55:54 -0800936JDWP::JdwpError Dbg::GetClassInfo(JDWP::RefTypeId class_id, JDWP::JdwpTypeTag* pTypeTag, uint32_t* pStatus, std::string* pDescriptor) {
Elliott Hughes436e3722012-02-17 20:01:47 -0800937 JDWP::JdwpError status;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800938 mirror::Class* c = DecodeClass(class_id, status);
Elliott Hughes436e3722012-02-17 20:01:47 -0800939 if (c == NULL) {
940 return status;
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -0800941 }
942
Elliott Hughesa2155262011-11-16 16:26:58 -0800943 if (c->IsArrayClass()) {
944 *pStatus = JDWP::CS_VERIFIED | JDWP::CS_PREPARED;
945 *pTypeTag = JDWP::TT_ARRAY;
946 } else {
947 if (c->IsErroneous()) {
948 *pStatus = JDWP::CS_ERROR;
949 } else {
950 *pStatus = JDWP::CS_VERIFIED | JDWP::CS_PREPARED | JDWP::CS_INITIALIZED;
951 }
952 *pTypeTag = c->IsInterface() ? JDWP::TT_INTERFACE : JDWP::TT_CLASS;
953 }
954
955 if (pDescriptor != NULL) {
Ian Rogersdfb325e2013-10-30 01:00:44 -0700956 *pDescriptor = ClassHelper(c).GetDescriptor();
Elliott Hughesa2155262011-11-16 16:26:58 -0800957 }
Elliott Hughes436e3722012-02-17 20:01:47 -0800958 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700959}
960
Elliott Hughesc3b77c72011-12-15 20:56:48 -0800961void Dbg::FindLoadedClassBySignature(const char* descriptor, std::vector<JDWP::RefTypeId>& ids) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800962 std::vector<mirror::Class*> classes;
Elliott Hughes6fa602d2011-12-02 17:54:25 -0800963 Runtime::Current()->GetClassLinker()->LookupClasses(descriptor, classes);
964 ids.clear();
965 for (size_t i = 0; i < classes.size(); ++i) {
966 ids.push_back(gRegistry->Add(classes[i]));
967 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700968}
969
Elliott Hughes64f574f2013-02-20 14:57:12 -0800970JDWP::JdwpError Dbg::GetReferenceType(JDWP::ObjectId object_id, JDWP::ExpandBuf* pReply)
971 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800972 mirror::Object* o = gRegistry->Get<mirror::Object*>(object_id);
Elliott Hughes64f574f2013-02-20 14:57:12 -0800973 if (o == NULL || o == ObjectRegistry::kInvalidObject) {
Elliott Hughes2435a572012-02-17 16:07:41 -0800974 return JDWP::ERR_INVALID_OBJECT;
Elliott Hughes499c5132011-11-17 14:55:11 -0800975 }
Elliott Hughes2435a572012-02-17 16:07:41 -0800976
977 JDWP::JdwpTypeTag type_tag;
978 if (o->GetClass()->IsArrayClass()) {
979 type_tag = JDWP::TT_ARRAY;
980 } else if (o->GetClass()->IsInterface()) {
981 type_tag = JDWP::TT_INTERFACE;
982 } else {
983 type_tag = JDWP::TT_CLASS;
984 }
Elliott Hughes64f574f2013-02-20 14:57:12 -0800985 JDWP::RefTypeId type_id = gRegistry->AddRefType(o->GetClass());
Elliott Hughes2435a572012-02-17 16:07:41 -0800986
987 expandBufAdd1(pReply, type_tag);
988 expandBufAddRefTypeId(pReply, type_id);
989
990 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700991}
992
Ian Rogersfc0e94b2013-09-23 23:51:32 -0700993JDWP::JdwpError Dbg::GetSignature(JDWP::RefTypeId class_id, std::string* signature) {
Elliott Hughes1fe7afb2012-02-13 17:23:03 -0800994 JDWP::JdwpError status;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800995 mirror::Class* c = DecodeClass(class_id, status);
Elliott Hughes1fe7afb2012-02-13 17:23:03 -0800996 if (c == NULL) {
997 return status;
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -0800998 }
Ian Rogersdfb325e2013-10-30 01:00:44 -0700999 *signature = ClassHelper(c).GetDescriptor();
Elliott Hughes1fe7afb2012-02-13 17:23:03 -08001000 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001001}
1002
Elliott Hughes88d63092013-01-09 09:55:54 -08001003JDWP::JdwpError Dbg::GetSourceFile(JDWP::RefTypeId class_id, std::string& result) {
Elliott Hughes436e3722012-02-17 20:01:47 -08001004 JDWP::JdwpError status;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001005 mirror::Class* c = DecodeClass(class_id, status);
Elliott Hughes436e3722012-02-17 20:01:47 -08001006 if (c == NULL) {
1007 return status;
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -08001008 }
Elliott Hughes436e3722012-02-17 20:01:47 -08001009 result = ClassHelper(c).GetSourceFile();
1010 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001011}
1012
Elliott Hughes88d63092013-01-09 09:55:54 -08001013JDWP::JdwpError Dbg::GetObjectTag(JDWP::ObjectId object_id, uint8_t& tag) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001014 mirror::Object* o = gRegistry->Get<mirror::Object*>(object_id);
Elliott Hughes64f574f2013-02-20 14:57:12 -08001015 if (o == ObjectRegistry::kInvalidObject) {
Elliott Hughes546b9862012-06-20 16:06:13 -07001016 return JDWP::ERR_INVALID_OBJECT;
1017 }
1018 tag = TagFromObject(o);
1019 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001020}
1021
Elliott Hughesaed4be92011-12-02 16:16:23 -08001022size_t Dbg::GetTagWidth(JDWP::JdwpTag tag) {
Elliott Hughesdbb40792011-11-18 17:05:22 -08001023 switch (tag) {
1024 case JDWP::JT_VOID:
1025 return 0;
1026 case JDWP::JT_BYTE:
1027 case JDWP::JT_BOOLEAN:
1028 return 1;
1029 case JDWP::JT_CHAR:
1030 case JDWP::JT_SHORT:
1031 return 2;
1032 case JDWP::JT_FLOAT:
1033 case JDWP::JT_INT:
1034 return 4;
1035 case JDWP::JT_ARRAY:
1036 case JDWP::JT_OBJECT:
1037 case JDWP::JT_STRING:
1038 case JDWP::JT_THREAD:
1039 case JDWP::JT_THREAD_GROUP:
1040 case JDWP::JT_CLASS_LOADER:
1041 case JDWP::JT_CLASS_OBJECT:
1042 return sizeof(JDWP::ObjectId);
1043 case JDWP::JT_DOUBLE:
1044 case JDWP::JT_LONG:
1045 return 8;
1046 default:
Elliott Hughes3d30d9b2011-12-07 17:35:48 -08001047 LOG(FATAL) << "Unknown tag " << tag;
Elliott Hughesdbb40792011-11-18 17:05:22 -08001048 return -1;
1049 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001050}
1051
Elliott Hughes88d63092013-01-09 09:55:54 -08001052JDWP::JdwpError Dbg::GetArrayLength(JDWP::ObjectId array_id, int& length) {
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -08001053 JDWP::JdwpError status;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001054 mirror::Array* a = DecodeArray(array_id, status);
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -08001055 if (a == NULL) {
1056 return status;
Elliott Hughes24437992011-11-30 14:49:33 -08001057 }
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -08001058 length = a->GetLength();
1059 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001060}
1061
Elliott Hughes88d63092013-01-09 09:55:54 -08001062JDWP::JdwpError Dbg::OutputArray(JDWP::ObjectId array_id, int offset, int count, JDWP::ExpandBuf* pReply) {
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -08001063 JDWP::JdwpError status;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001064 mirror::Array* a = DecodeArray(array_id, status);
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -08001065 if (a == NULL) {
1066 return status;
1067 }
Elliott Hughes24437992011-11-30 14:49:33 -08001068
1069 if (offset < 0 || count < 0 || offset > a->GetLength() || a->GetLength() - offset < count) {
1070 LOG(WARNING) << __FUNCTION__ << " access out of bounds: offset=" << offset << "; count=" << count;
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -08001071 return JDWP::ERR_INVALID_LENGTH;
Elliott Hughes24437992011-11-30 14:49:33 -08001072 }
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001073 std::string descriptor(ClassHelper(a->GetClass()).GetDescriptor());
Elliott Hughes24437992011-11-30 14:49:33 -08001074 JDWP::JdwpTag tag = BasicTagFromDescriptor(descriptor.c_str() + 1);
1075
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -08001076 expandBufAdd1(pReply, tag);
1077 expandBufAdd4BE(pReply, count);
1078
Elliott Hughes24437992011-11-30 14:49:33 -08001079 if (IsPrimitiveTag(tag)) {
1080 size_t width = GetTagWidth(tag);
Elliott Hughes24437992011-11-30 14:49:33 -08001081 uint8_t* dst = expandBufAddSpace(pReply, count * width);
1082 if (width == 8) {
Ian Rogersef7d42f2014-01-06 12:55:46 -08001083 const uint64_t* src8 = reinterpret_cast<uint64_t*>(a->GetRawData(sizeof(uint64_t), 0));
Elliott Hughes24437992011-11-30 14:49:33 -08001084 for (int i = 0; i < count; ++i) JDWP::Write8BE(&dst, src8[offset + i]);
1085 } else if (width == 4) {
Ian Rogersef7d42f2014-01-06 12:55:46 -08001086 const uint32_t* src4 = reinterpret_cast<uint32_t*>(a->GetRawData(sizeof(uint32_t), 0));
Elliott Hughes24437992011-11-30 14:49:33 -08001087 for (int i = 0; i < count; ++i) JDWP::Write4BE(&dst, src4[offset + i]);
1088 } else if (width == 2) {
Ian Rogersef7d42f2014-01-06 12:55:46 -08001089 const uint16_t* src2 = reinterpret_cast<uint16_t*>(a->GetRawData(sizeof(uint16_t), 0));
Elliott Hughes24437992011-11-30 14:49:33 -08001090 for (int i = 0; i < count; ++i) JDWP::Write2BE(&dst, src2[offset + i]);
1091 } else {
Ian Rogersef7d42f2014-01-06 12:55:46 -08001092 const uint8_t* src = reinterpret_cast<uint8_t*>(a->GetRawData(sizeof(uint8_t), 0));
Elliott Hughes24437992011-11-30 14:49:33 -08001093 memcpy(dst, &src[offset * width], count * width);
1094 }
1095 } else {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001096 mirror::ObjectArray<mirror::Object>* oa = a->AsObjectArray<mirror::Object>();
Elliott Hughes24437992011-11-30 14:49:33 -08001097 for (int i = 0; i < count; ++i) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001098 mirror::Object* element = oa->Get(offset + i);
Elliott Hughes24437992011-11-30 14:49:33 -08001099 JDWP::JdwpTag specific_tag = (element != NULL) ? TagFromObject(element) : tag;
1100 expandBufAdd1(pReply, specific_tag);
1101 expandBufAddObjectId(pReply, gRegistry->Add(element));
1102 }
1103 }
1104
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -08001105 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001106}
1107
Ian Rogersef7d42f2014-01-06 12:55:46 -08001108template <typename T>
1109static void CopyArrayData(mirror::Array* a, JDWP::Request& src, int offset, int count)
1110 NO_THREAD_SAFETY_ANALYSIS {
1111 // TODO: fix when annotalysis correctly handles non-member functions.
Elliott Hughes4b9702c2013-02-20 18:13:24 -08001112 DCHECK(a->GetClass()->IsPrimitiveArray());
1113
Ian Rogersef7d42f2014-01-06 12:55:46 -08001114 T* dst = reinterpret_cast<T*>(a->GetRawData(sizeof(T), offset));
Elliott Hughes4b9702c2013-02-20 18:13:24 -08001115 for (int i = 0; i < count; ++i) {
1116 *dst++ = src.ReadValue(sizeof(T));
1117 }
1118}
1119
Elliott Hughes88d63092013-01-09 09:55:54 -08001120JDWP::JdwpError Dbg::SetArrayElements(JDWP::ObjectId array_id, int offset, int count,
Elliott Hughes4b9702c2013-02-20 18:13:24 -08001121 JDWP::Request& request)
Ian Rogersb726dcb2012-09-05 08:57:23 -07001122 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -08001123 JDWP::JdwpError status;
Elliott Hughes4b9702c2013-02-20 18:13:24 -08001124 mirror::Array* dst = DecodeArray(array_id, status);
1125 if (dst == NULL) {
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -08001126 return status;
1127 }
Elliott Hughesf03b8f62011-12-02 14:26:25 -08001128
Elliott Hughes4b9702c2013-02-20 18:13:24 -08001129 if (offset < 0 || count < 0 || offset > dst->GetLength() || dst->GetLength() - offset < count) {
Elliott Hughesf03b8f62011-12-02 14:26:25 -08001130 LOG(WARNING) << __FUNCTION__ << " access out of bounds: offset=" << offset << "; count=" << count;
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -08001131 return JDWP::ERR_INVALID_LENGTH;
Elliott Hughesf03b8f62011-12-02 14:26:25 -08001132 }
Ian Rogersfc0e94b2013-09-23 23:51:32 -07001133 const char* descriptor = ClassHelper(dst->GetClass()).GetDescriptor();
1134 JDWP::JdwpTag tag = BasicTagFromDescriptor(descriptor + 1);
Elliott Hughesf03b8f62011-12-02 14:26:25 -08001135
1136 if (IsPrimitiveTag(tag)) {
1137 size_t width = GetTagWidth(tag);
Elliott Hughesf03b8f62011-12-02 14:26:25 -08001138 if (width == 8) {
Elliott Hughes4b9702c2013-02-20 18:13:24 -08001139 CopyArrayData<uint64_t>(dst, request, offset, count);
Elliott Hughesf03b8f62011-12-02 14:26:25 -08001140 } else if (width == 4) {
Elliott Hughes4b9702c2013-02-20 18:13:24 -08001141 CopyArrayData<uint32_t>(dst, request, offset, count);
Elliott Hughesf03b8f62011-12-02 14:26:25 -08001142 } else if (width == 2) {
Elliott Hughes4b9702c2013-02-20 18:13:24 -08001143 CopyArrayData<uint16_t>(dst, request, offset, count);
Elliott Hughesf03b8f62011-12-02 14:26:25 -08001144 } else {
Elliott Hughes4b9702c2013-02-20 18:13:24 -08001145 CopyArrayData<uint8_t>(dst, request, offset, count);
Elliott Hughesf03b8f62011-12-02 14:26:25 -08001146 }
1147 } else {
Elliott Hughes4b9702c2013-02-20 18:13:24 -08001148 mirror::ObjectArray<mirror::Object>* oa = dst->AsObjectArray<mirror::Object>();
Elliott Hughesf03b8f62011-12-02 14:26:25 -08001149 for (int i = 0; i < count; ++i) {
Elliott Hughes4b9702c2013-02-20 18:13:24 -08001150 JDWP::ObjectId id = request.ReadObjectId();
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001151 mirror::Object* o = gRegistry->Get<mirror::Object*>(id);
Elliott Hughes64f574f2013-02-20 14:57:12 -08001152 if (o == ObjectRegistry::kInvalidObject) {
Elliott Hughes436e3722012-02-17 20:01:47 -08001153 return JDWP::ERR_INVALID_OBJECT;
1154 }
Sebastien Hertzd2fe10a2014-01-15 10:20:56 +01001155 oa->Set<false>(offset + i, o);
Elliott Hughesf03b8f62011-12-02 14:26:25 -08001156 }
1157 }
1158
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -08001159 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001160}
1161
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -08001162JDWP::ObjectId Dbg::CreateString(const std::string& str) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001163 return gRegistry->Add(mirror::String::AllocFromModifiedUtf8(Thread::Current(), str.c_str()));
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001164}
1165
Elliott Hughes88d63092013-01-09 09:55:54 -08001166JDWP::JdwpError Dbg::CreateObject(JDWP::RefTypeId class_id, JDWP::ObjectId& new_object) {
Elliott Hughes436e3722012-02-17 20:01:47 -08001167 JDWP::JdwpError status;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001168 mirror::Class* c = DecodeClass(class_id, status);
Elliott Hughes436e3722012-02-17 20:01:47 -08001169 if (c == NULL) {
1170 return status;
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -08001171 }
Ian Rogers50b35e22012-10-04 10:09:15 -07001172 new_object = gRegistry->Add(c->AllocObject(Thread::Current()));
Elliott Hughes436e3722012-02-17 20:01:47 -08001173 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001174}
1175
Elliott Hughesbf13d362011-12-08 15:51:37 -08001176/*
1177 * Used by Eclipse's "Display" view to evaluate "new byte[5]" to get "(byte[]) [0, 0, 0, 0, 0]".
1178 */
Elliott Hughes88d63092013-01-09 09:55:54 -08001179JDWP::JdwpError Dbg::CreateArrayObject(JDWP::RefTypeId array_class_id, uint32_t length,
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001180 JDWP::ObjectId& new_array) {
Elliott Hughes436e3722012-02-17 20:01:47 -08001181 JDWP::JdwpError status;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001182 mirror::Class* c = DecodeClass(array_class_id, status);
Elliott Hughes436e3722012-02-17 20:01:47 -08001183 if (c == NULL) {
1184 return status;
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -08001185 }
Mathieu Chartiercbb2d202013-11-14 17:45:16 -08001186 new_array = gRegistry->Add(mirror::Array::Alloc<true>(Thread::Current(), c, length));
Elliott Hughes436e3722012-02-17 20:01:47 -08001187 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001188}
1189
Elliott Hughes88d63092013-01-09 09:55:54 -08001190bool Dbg::MatchType(JDWP::RefTypeId instance_class_id, JDWP::RefTypeId class_id) {
Elliott Hughes436e3722012-02-17 20:01:47 -08001191 JDWP::JdwpError status;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001192 mirror::Class* c1 = DecodeClass(instance_class_id, status);
Elliott Hughesa656a0f2012-02-21 18:03:44 -08001193 CHECK(c1 != NULL);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001194 mirror::Class* c2 = DecodeClass(class_id, status);
Elliott Hughesa656a0f2012-02-21 18:03:44 -08001195 CHECK(c2 != NULL);
Sebastien Hertz123756a2013-11-27 15:49:42 +01001196 return c2->IsAssignableFrom(c1);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001197}
1198
Brian Carlstromea46f952013-07-30 01:26:50 -07001199static JDWP::FieldId ToFieldId(const mirror::ArtField* f)
Ian Rogersb726dcb2012-09-05 08:57:23 -07001200 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Mathieu Chartier590fee92013-09-13 13:46:47 -07001201 CHECK(!kMovingFields);
Elliott Hughes03181a82011-11-17 17:22:21 -08001202 return static_cast<JDWP::FieldId>(reinterpret_cast<uintptr_t>(f));
Elliott Hughes03181a82011-11-17 17:22:21 -08001203}
1204
Brian Carlstromea46f952013-07-30 01:26:50 -07001205static JDWP::MethodId ToMethodId(const mirror::ArtMethod* m)
Ian Rogersb726dcb2012-09-05 08:57:23 -07001206 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Mathieu Chartier590fee92013-09-13 13:46:47 -07001207 CHECK(!kMovingMethods);
Elliott Hughes03181a82011-11-17 17:22:21 -08001208 return static_cast<JDWP::MethodId>(reinterpret_cast<uintptr_t>(m));
Elliott Hughes03181a82011-11-17 17:22:21 -08001209}
1210
Brian Carlstromea46f952013-07-30 01:26:50 -07001211static mirror::ArtField* FromFieldId(JDWP::FieldId fid)
Ian Rogersb726dcb2012-09-05 08:57:23 -07001212 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Mathieu Chartier590fee92013-09-13 13:46:47 -07001213 CHECK(!kMovingFields);
Brian Carlstromea46f952013-07-30 01:26:50 -07001214 return reinterpret_cast<mirror::ArtField*>(static_cast<uintptr_t>(fid));
Elliott Hughesaed4be92011-12-02 16:16:23 -08001215}
1216
Brian Carlstromea46f952013-07-30 01:26:50 -07001217static mirror::ArtMethod* FromMethodId(JDWP::MethodId mid)
Ian Rogersb726dcb2012-09-05 08:57:23 -07001218 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Mathieu Chartier590fee92013-09-13 13:46:47 -07001219 CHECK(!kMovingMethods);
Brian Carlstromea46f952013-07-30 01:26:50 -07001220 return reinterpret_cast<mirror::ArtMethod*>(static_cast<uintptr_t>(mid));
Elliott Hughes03181a82011-11-17 17:22:21 -08001221}
1222
Brian Carlstromea46f952013-07-30 01:26:50 -07001223static void SetLocation(JDWP::JdwpLocation& location, mirror::ArtMethod* m, uint32_t dex_pc)
Ian Rogersb726dcb2012-09-05 08:57:23 -07001224 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08001225 if (m == NULL) {
1226 memset(&location, 0, sizeof(location));
1227 } else {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001228 mirror::Class* c = m->GetDeclaringClass();
Elliott Hughes74847412012-06-20 18:10:21 -07001229 location.type_tag = c->IsInterface() ? JDWP::TT_INTERFACE : JDWP::TT_CLASS;
1230 location.class_id = gRegistry->Add(c);
1231 location.method_id = ToMethodId(m);
Ian Rogers0399dde2012-06-06 17:09:28 -07001232 location.dex_pc = dex_pc;
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08001233 }
Elliott Hughesd07986f2011-12-06 18:27:45 -08001234}
1235
Elliott Hughesa96836a2013-01-17 12:27:49 -08001236std::string Dbg::GetMethodName(JDWP::MethodId method_id)
Ian Rogersb726dcb2012-09-05 08:57:23 -07001237 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Brian Carlstromea46f952013-07-30 01:26:50 -07001238 mirror::ArtMethod* m = FromMethodId(method_id);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001239 return MethodHelper(m).GetName();
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001240}
1241
Elliott Hughesa96836a2013-01-17 12:27:49 -08001242std::string Dbg::GetFieldName(JDWP::FieldId field_id)
1243 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Brian Carlstromea46f952013-07-30 01:26:50 -07001244 mirror::ArtField* f = FromFieldId(field_id);
Elliott Hughesa96836a2013-01-17 12:27:49 -08001245 return FieldHelper(f).GetName();
1246}
1247
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001248/*
1249 * Augment the access flags for synthetic methods and fields by setting
1250 * the (as described by the spec) "0xf0000000 bit". Also, strip out any
1251 * flags not specified by the Java programming language.
1252 */
1253static uint32_t MangleAccessFlags(uint32_t accessFlags) {
1254 accessFlags &= kAccJavaFlagsMask;
1255 if ((accessFlags & kAccSynthetic) != 0) {
1256 accessFlags |= 0xf0000000;
1257 }
1258 return accessFlags;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001259}
1260
Elliott Hughesdbb40792011-11-18 17:05:22 -08001261/*
Jeff Haob7cefc72013-11-14 14:51:09 -08001262 * Circularly shifts registers so that arguments come first. Debuggers
1263 * expect slots to begin with arguments, but dex code places them at
1264 * the end.
Elliott Hughesdbb40792011-11-18 17:05:22 -08001265 */
Jeff Haob7cefc72013-11-14 14:51:09 -08001266static uint16_t MangleSlot(uint16_t slot, mirror::ArtMethod* m)
1267 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
1268 const DexFile::CodeItem* code_item = MethodHelper(m).GetCodeItem();
1269 uint16_t ins_size = code_item->ins_size_;
1270 uint16_t locals_size = code_item->registers_size_ - ins_size;
1271 if (slot >= locals_size) {
1272 return slot - locals_size;
1273 } else {
1274 return slot + ins_size;
Elliott Hughesdbb40792011-11-18 17:05:22 -08001275 }
Elliott Hughesdbb40792011-11-18 17:05:22 -08001276}
1277
Jeff Haob7cefc72013-11-14 14:51:09 -08001278/*
1279 * Circularly shifts registers so that arguments come last. Reverts
1280 * slots to dex style argument placement.
1281 */
Brian Carlstromea46f952013-07-30 01:26:50 -07001282static uint16_t DemangleSlot(uint16_t slot, mirror::ArtMethod* m)
Ian Rogersb726dcb2012-09-05 08:57:23 -07001283 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Jeff Haob7cefc72013-11-14 14:51:09 -08001284 const DexFile::CodeItem* code_item = MethodHelper(m).GetCodeItem();
1285 uint16_t ins_size = code_item->ins_size_;
1286 uint16_t locals_size = code_item->registers_size_ - ins_size;
1287 if (slot < ins_size) {
1288 return slot + locals_size;
1289 } else {
1290 return slot - ins_size;
Elliott Hughesdbb40792011-11-18 17:05:22 -08001291 }
Elliott Hughesdbb40792011-11-18 17:05:22 -08001292}
1293
Elliott Hughes88d63092013-01-09 09:55:54 -08001294JDWP::JdwpError Dbg::OutputDeclaredFields(JDWP::RefTypeId class_id, bool with_generic, JDWP::ExpandBuf* pReply) {
Elliott Hughes436e3722012-02-17 20:01:47 -08001295 JDWP::JdwpError status;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001296 mirror::Class* c = DecodeClass(class_id, status);
Elliott Hughes436e3722012-02-17 20:01:47 -08001297 if (c == NULL) {
1298 return status;
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -08001299 }
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001300
1301 size_t instance_field_count = c->NumInstanceFields();
1302 size_t static_field_count = c->NumStaticFields();
1303
1304 expandBufAdd4BE(pReply, instance_field_count + static_field_count);
1305
1306 for (size_t i = 0; i < instance_field_count + static_field_count; ++i) {
Brian Carlstromea46f952013-07-30 01:26:50 -07001307 mirror::ArtField* f = (i < instance_field_count) ? c->GetInstanceField(i) : c->GetStaticField(i - instance_field_count);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001308 FieldHelper fh(f);
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001309 expandBufAddFieldId(pReply, ToFieldId(f));
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001310 expandBufAddUtf8String(pReply, fh.GetName());
1311 expandBufAddUtf8String(pReply, fh.GetTypeDescriptor());
Elliott Hughesc5b734a2011-12-01 17:20:58 -08001312 if (with_generic) {
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001313 static const char genericSignature[1] = "";
1314 expandBufAddUtf8String(pReply, genericSignature);
1315 }
1316 expandBufAdd4BE(pReply, MangleAccessFlags(f->GetAccessFlags()));
1317 }
Elliott Hughes436e3722012-02-17 20:01:47 -08001318 return JDWP::ERR_NONE;
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001319}
1320
Elliott Hughes88d63092013-01-09 09:55:54 -08001321JDWP::JdwpError Dbg::OutputDeclaredMethods(JDWP::RefTypeId class_id, bool with_generic,
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001322 JDWP::ExpandBuf* pReply) {
Elliott Hughes436e3722012-02-17 20:01:47 -08001323 JDWP::JdwpError status;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001324 mirror::Class* c = DecodeClass(class_id, status);
Elliott Hughes436e3722012-02-17 20:01:47 -08001325 if (c == NULL) {
1326 return status;
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -08001327 }
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001328
1329 size_t direct_method_count = c->NumDirectMethods();
1330 size_t virtual_method_count = c->NumVirtualMethods();
1331
1332 expandBufAdd4BE(pReply, direct_method_count + virtual_method_count);
1333
1334 for (size_t i = 0; i < direct_method_count + virtual_method_count; ++i) {
Brian Carlstromea46f952013-07-30 01:26:50 -07001335 mirror::ArtMethod* m = (i < direct_method_count) ? c->GetDirectMethod(i) : c->GetVirtualMethod(i - direct_method_count);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001336 MethodHelper mh(m);
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001337 expandBufAddMethodId(pReply, ToMethodId(m));
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001338 expandBufAddUtf8String(pReply, mh.GetName());
Ian Rogersd91d6d62013-09-25 20:26:14 -07001339 expandBufAddUtf8String(pReply, mh.GetSignature().ToString());
Elliott Hughesc5b734a2011-12-01 17:20:58 -08001340 if (with_generic) {
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001341 static const char genericSignature[1] = "";
1342 expandBufAddUtf8String(pReply, genericSignature);
1343 }
1344 expandBufAdd4BE(pReply, MangleAccessFlags(m->GetAccessFlags()));
1345 }
Elliott Hughes436e3722012-02-17 20:01:47 -08001346 return JDWP::ERR_NONE;
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001347}
1348
Elliott Hughes88d63092013-01-09 09:55:54 -08001349JDWP::JdwpError Dbg::OutputDeclaredInterfaces(JDWP::RefTypeId class_id, JDWP::ExpandBuf* pReply) {
Elliott Hughes436e3722012-02-17 20:01:47 -08001350 JDWP::JdwpError status;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001351 mirror::Class* c = DecodeClass(class_id, status);
Elliott Hughes436e3722012-02-17 20:01:47 -08001352 if (c == NULL) {
1353 return status;
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -08001354 }
Elliott Hughes436e3722012-02-17 20:01:47 -08001355
1356 ClassHelper kh(c);
Ian Rogersd24e2642012-06-06 21:21:43 -07001357 size_t interface_count = kh.NumDirectInterfaces();
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001358 expandBufAdd4BE(pReply, interface_count);
1359 for (size_t i = 0; i < interface_count; ++i) {
Elliott Hughes64f574f2013-02-20 14:57:12 -08001360 expandBufAddRefTypeId(pReply, gRegistry->AddRefType(kh.GetDirectInterface(i)));
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001361 }
Elliott Hughes436e3722012-02-17 20:01:47 -08001362 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001363}
1364
Elliott Hughes88d63092013-01-09 09:55:54 -08001365void Dbg::OutputLineTable(JDWP::RefTypeId, JDWP::MethodId method_id, JDWP::ExpandBuf* pReply)
Ian Rogersb726dcb2012-09-05 08:57:23 -07001366 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Elliott Hughes03181a82011-11-17 17:22:21 -08001367 struct DebugCallbackContext {
1368 int numItems;
1369 JDWP::ExpandBuf* pReply;
1370
Elliott Hughes2435a572012-02-17 16:07:41 -08001371 static bool Callback(void* context, uint32_t address, uint32_t line_number) {
Elliott Hughes03181a82011-11-17 17:22:21 -08001372 DebugCallbackContext* pContext = reinterpret_cast<DebugCallbackContext*>(context);
1373 expandBufAdd8BE(pContext->pReply, address);
Elliott Hughes2435a572012-02-17 16:07:41 -08001374 expandBufAdd4BE(pContext->pReply, line_number);
Elliott Hughes03181a82011-11-17 17:22:21 -08001375 pContext->numItems++;
Sebastien Hertzf2910ee2013-10-19 16:39:24 +02001376 return false;
Elliott Hughes03181a82011-11-17 17:22:21 -08001377 }
1378 };
Brian Carlstromea46f952013-07-30 01:26:50 -07001379 mirror::ArtMethod* m = FromMethodId(method_id);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001380 MethodHelper mh(m);
Elliott Hughes03181a82011-11-17 17:22:21 -08001381 uint64_t start, end;
1382 if (m->IsNative()) {
1383 start = -1;
1384 end = -1;
1385 } else {
1386 start = 0;
jeffhao14f0db92012-12-14 17:50:42 -08001387 // Return the index of the last instruction
1388 end = mh.GetCodeItem()->insns_size_in_code_units_ - 1;
Elliott Hughes03181a82011-11-17 17:22:21 -08001389 }
1390
1391 expandBufAdd8BE(pReply, start);
1392 expandBufAdd8BE(pReply, end);
1393
1394 // Add numLines later
1395 size_t numLinesOffset = expandBufGetLength(pReply);
1396 expandBufAdd4BE(pReply, 0);
1397
1398 DebugCallbackContext context;
1399 context.numItems = 0;
1400 context.pReply = pReply;
1401
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001402 mh.GetDexFile().DecodeDebugInfo(mh.GetCodeItem(), m->IsStatic(), m->GetDexMethodIndex(),
1403 DebugCallbackContext::Callback, NULL, &context);
Elliott Hughes03181a82011-11-17 17:22:21 -08001404
1405 JDWP::Set4BE(expandBufGetBuffer(pReply) + numLinesOffset, context.numItems);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001406}
1407
Elliott Hughes88d63092013-01-09 09:55:54 -08001408void Dbg::OutputVariableTable(JDWP::RefTypeId, JDWP::MethodId method_id, bool with_generic, JDWP::ExpandBuf* pReply) {
Elliott Hughesdbb40792011-11-18 17:05:22 -08001409 struct DebugCallbackContext {
Jeff Haob7cefc72013-11-14 14:51:09 -08001410 mirror::ArtMethod* method;
Elliott Hughesdbb40792011-11-18 17:05:22 -08001411 JDWP::ExpandBuf* pReply;
Elliott Hughesc5b734a2011-12-01 17:20:58 -08001412 size_t variable_count;
1413 bool with_generic;
Elliott Hughesdbb40792011-11-18 17:05:22 -08001414
Jeff Haob7cefc72013-11-14 14:51:09 -08001415 static void Callback(void* context, uint16_t slot, uint32_t startAddress, uint32_t endAddress, const char* name, const char* descriptor, const char* signature)
1416 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Elliott Hughesdbb40792011-11-18 17:05:22 -08001417 DebugCallbackContext* pContext = reinterpret_cast<DebugCallbackContext*>(context);
1418
Jeff Haob7cefc72013-11-14 14:51:09 -08001419 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 -08001420
Jeff Haob7cefc72013-11-14 14:51:09 -08001421 slot = MangleSlot(slot, pContext->method);
Elliott Hughes68fdbd02011-11-29 19:22:47 -08001422
Elliott Hughesdbb40792011-11-18 17:05:22 -08001423 expandBufAdd8BE(pContext->pReply, startAddress);
1424 expandBufAddUtf8String(pContext->pReply, name);
1425 expandBufAddUtf8String(pContext->pReply, descriptor);
Elliott Hughesc5b734a2011-12-01 17:20:58 -08001426 if (pContext->with_generic) {
Elliott Hughesdbb40792011-11-18 17:05:22 -08001427 expandBufAddUtf8String(pContext->pReply, signature);
1428 }
1429 expandBufAdd4BE(pContext->pReply, endAddress - startAddress);
1430 expandBufAdd4BE(pContext->pReply, slot);
1431
Elliott Hughesc5b734a2011-12-01 17:20:58 -08001432 ++pContext->variable_count;
Elliott Hughesdbb40792011-11-18 17:05:22 -08001433 }
1434 };
Brian Carlstromea46f952013-07-30 01:26:50 -07001435 mirror::ArtMethod* m = FromMethodId(method_id);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001436 MethodHelper mh(m);
1437 const DexFile::CodeItem* code_item = mh.GetCodeItem();
Elliott Hughesdbb40792011-11-18 17:05:22 -08001438
Elliott Hughesc5b734a2011-12-01 17:20:58 -08001439 // arg_count considers doubles and longs to take 2 units.
1440 // variable_count considers everything to take 1 unit.
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001441 std::string shorty(mh.GetShorty());
Brian Carlstromea46f952013-07-30 01:26:50 -07001442 expandBufAdd4BE(pReply, mirror::ArtMethod::NumArgRegisters(shorty));
Elliott Hughesdbb40792011-11-18 17:05:22 -08001443
Elliott Hughesc5b734a2011-12-01 17:20:58 -08001444 // We don't know the total number of variables yet, so leave a blank and update it later.
1445 size_t variable_count_offset = expandBufGetLength(pReply);
Elliott Hughesdbb40792011-11-18 17:05:22 -08001446 expandBufAdd4BE(pReply, 0);
1447
1448 DebugCallbackContext context;
Jeff Haob7cefc72013-11-14 14:51:09 -08001449 context.method = m;
Elliott Hughesdbb40792011-11-18 17:05:22 -08001450 context.pReply = pReply;
Elliott Hughesc5b734a2011-12-01 17:20:58 -08001451 context.variable_count = 0;
1452 context.with_generic = with_generic;
Elliott Hughesdbb40792011-11-18 17:05:22 -08001453
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001454 mh.GetDexFile().DecodeDebugInfo(code_item, m->IsStatic(), m->GetDexMethodIndex(), NULL,
1455 DebugCallbackContext::Callback, &context);
Elliott Hughesdbb40792011-11-18 17:05:22 -08001456
Elliott Hughesc5b734a2011-12-01 17:20:58 -08001457 JDWP::Set4BE(expandBufGetBuffer(pReply) + variable_count_offset, context.variable_count);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001458}
1459
Jeff Hao579b0242013-11-18 13:16:49 -08001460void Dbg::OutputMethodReturnValue(JDWP::MethodId method_id, const JValue* return_value,
1461 JDWP::ExpandBuf* pReply) {
1462 mirror::ArtMethod* m = FromMethodId(method_id);
1463 JDWP::JdwpTag tag = BasicTagFromDescriptor(MethodHelper(m).GetShorty());
1464 OutputJValue(tag, return_value, pReply);
1465}
1466
Elliott Hughes9777ba22013-01-17 09:04:19 -08001467JDWP::JdwpError Dbg::GetBytecodes(JDWP::RefTypeId, JDWP::MethodId method_id,
1468 std::vector<uint8_t>& bytecodes)
1469 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Brian Carlstromea46f952013-07-30 01:26:50 -07001470 mirror::ArtMethod* m = FromMethodId(method_id);
Elliott Hughes9777ba22013-01-17 09:04:19 -08001471 if (m == NULL) {
1472 return JDWP::ERR_INVALID_METHODID;
1473 }
1474 MethodHelper mh(m);
1475 const DexFile::CodeItem* code_item = mh.GetCodeItem();
1476 size_t byte_count = code_item->insns_size_in_code_units_ * 2;
1477 const uint8_t* begin = reinterpret_cast<const uint8_t*>(code_item->insns_);
1478 const uint8_t* end = begin + byte_count;
1479 for (const uint8_t* p = begin; p != end; ++p) {
1480 bytecodes.push_back(*p);
1481 }
1482 return JDWP::ERR_NONE;
1483}
1484
Elliott Hughes88d63092013-01-09 09:55:54 -08001485JDWP::JdwpTag Dbg::GetFieldBasicTag(JDWP::FieldId field_id) {
1486 return BasicTagFromDescriptor(FieldHelper(FromFieldId(field_id)).GetTypeDescriptor());
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001487}
1488
Elliott Hughes88d63092013-01-09 09:55:54 -08001489JDWP::JdwpTag Dbg::GetStaticFieldBasicTag(JDWP::FieldId field_id) {
1490 return BasicTagFromDescriptor(FieldHelper(FromFieldId(field_id)).GetTypeDescriptor());
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001491}
1492
Elliott Hughes88d63092013-01-09 09:55:54 -08001493static JDWP::JdwpError GetFieldValueImpl(JDWP::RefTypeId ref_type_id, JDWP::ObjectId object_id,
1494 JDWP::FieldId field_id, JDWP::ExpandBuf* pReply,
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001495 bool is_static)
Ian Rogersb726dcb2012-09-05 08:57:23 -07001496 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Elliott Hughes0cf74332012-02-23 23:14:00 -08001497 JDWP::JdwpError status;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001498 mirror::Class* c = DecodeClass(ref_type_id, status);
Elliott Hughes88d63092013-01-09 09:55:54 -08001499 if (ref_type_id != 0 && c == NULL) {
Elliott Hughes0cf74332012-02-23 23:14:00 -08001500 return status;
1501 }
1502
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001503 mirror::Object* o = gRegistry->Get<mirror::Object*>(object_id);
Elliott Hughes64f574f2013-02-20 14:57:12 -08001504 if ((!is_static && o == NULL) || o == ObjectRegistry::kInvalidObject) {
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08001505 return JDWP::ERR_INVALID_OBJECT;
1506 }
Brian Carlstromea46f952013-07-30 01:26:50 -07001507 mirror::ArtField* f = FromFieldId(field_id);
Elliott Hughes0cf74332012-02-23 23:14:00 -08001508
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001509 mirror::Class* receiver_class = c;
Elliott Hughes0cf74332012-02-23 23:14:00 -08001510 if (receiver_class == NULL && o != NULL) {
1511 receiver_class = o->GetClass();
1512 }
1513 // TODO: should we give up now if receiver_class is NULL?
1514 if (receiver_class != NULL && !f->GetDeclaringClass()->IsAssignableFrom(receiver_class)) {
1515 LOG(INFO) << "ERR_INVALID_FIELDID: " << PrettyField(f) << " " << PrettyClass(receiver_class);
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08001516 return JDWP::ERR_INVALID_FIELDID;
1517 }
Elliott Hughesaed4be92011-12-02 16:16:23 -08001518
Elliott Hughes0cf74332012-02-23 23:14:00 -08001519 // The RI only enforces the static/non-static mismatch in one direction.
1520 // TODO: should we change the tests and check both?
1521 if (is_static) {
1522 if (!f->IsStatic()) {
1523 return JDWP::ERR_INVALID_FIELDID;
1524 }
1525 } else {
1526 if (f->IsStatic()) {
1527 LOG(WARNING) << "Ignoring non-NULL receiver for ObjectReference.SetValues on static field " << PrettyField(f);
Elliott Hughes0cf74332012-02-23 23:14:00 -08001528 }
1529 }
jeffhao0dfbb7e2012-11-28 15:26:03 -08001530 if (f->IsStatic()) {
1531 o = f->GetDeclaringClass();
1532 }
Elliott Hughes0cf74332012-02-23 23:14:00 -08001533
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001534 JDWP::JdwpTag tag = BasicTagFromDescriptor(FieldHelper(f).GetTypeDescriptor());
Jeff Hao579b0242013-11-18 13:16:49 -08001535 JValue field_value;
1536 if (tag == JDWP::JT_VOID) {
1537 LOG(FATAL) << "Unknown tag: " << tag;
1538 } else if (!IsPrimitiveTag(tag)) {
1539 field_value.SetL(f->GetObject(o));
1540 } else if (tag == JDWP::JT_DOUBLE || tag == JDWP::JT_LONG) {
1541 field_value.SetJ(f->Get64(o));
Elliott Hughesaed4be92011-12-02 16:16:23 -08001542 } else {
Jeff Hao579b0242013-11-18 13:16:49 -08001543 field_value.SetI(f->Get32(o));
Elliott Hughesaed4be92011-12-02 16:16:23 -08001544 }
Jeff Hao579b0242013-11-18 13:16:49 -08001545 Dbg::OutputJValue(tag, &field_value, pReply);
1546
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08001547 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001548}
1549
Elliott Hughes88d63092013-01-09 09:55:54 -08001550JDWP::JdwpError Dbg::GetFieldValue(JDWP::ObjectId object_id, JDWP::FieldId field_id,
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001551 JDWP::ExpandBuf* pReply) {
Elliott Hughes88d63092013-01-09 09:55:54 -08001552 return GetFieldValueImpl(0, object_id, field_id, pReply, false);
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08001553}
1554
Elliott Hughes88d63092013-01-09 09:55:54 -08001555JDWP::JdwpError Dbg::GetStaticFieldValue(JDWP::RefTypeId ref_type_id, JDWP::FieldId field_id, JDWP::ExpandBuf* pReply) {
1556 return GetFieldValueImpl(ref_type_id, 0, field_id, pReply, true);
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08001557}
1558
Elliott Hughes88d63092013-01-09 09:55:54 -08001559static JDWP::JdwpError SetFieldValueImpl(JDWP::ObjectId object_id, JDWP::FieldId field_id,
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001560 uint64_t value, int width, bool is_static)
Ian Rogersb726dcb2012-09-05 08:57:23 -07001561 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001562 mirror::Object* o = gRegistry->Get<mirror::Object*>(object_id);
Elliott Hughes64f574f2013-02-20 14:57:12 -08001563 if ((!is_static && o == NULL) || o == ObjectRegistry::kInvalidObject) {
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08001564 return JDWP::ERR_INVALID_OBJECT;
1565 }
Brian Carlstromea46f952013-07-30 01:26:50 -07001566 mirror::ArtField* f = FromFieldId(field_id);
Elliott Hughes0cf74332012-02-23 23:14:00 -08001567
1568 // The RI only enforces the static/non-static mismatch in one direction.
1569 // TODO: should we change the tests and check both?
1570 if (is_static) {
1571 if (!f->IsStatic()) {
1572 return JDWP::ERR_INVALID_FIELDID;
1573 }
1574 } else {
1575 if (f->IsStatic()) {
1576 LOG(WARNING) << "Ignoring non-NULL receiver for ObjectReference.SetValues on static field " << PrettyField(f);
Elliott Hughes0cf74332012-02-23 23:14:00 -08001577 }
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08001578 }
jeffhao0dfbb7e2012-11-28 15:26:03 -08001579 if (f->IsStatic()) {
1580 o = f->GetDeclaringClass();
1581 }
Elliott Hughesaed4be92011-12-02 16:16:23 -08001582
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001583 JDWP::JdwpTag tag = BasicTagFromDescriptor(FieldHelper(f).GetTypeDescriptor());
Elliott Hughesaed4be92011-12-02 16:16:23 -08001584
1585 if (IsPrimitiveTag(tag)) {
1586 if (tag == JDWP::JT_DOUBLE || tag == JDWP::JT_LONG) {
Elliott Hughes1bac54f2012-03-16 12:48:31 -07001587 CHECK_EQ(width, 8);
Sebastien Hertzd2fe10a2014-01-15 10:20:56 +01001588 // Debugging can't use transactional mode (runtime only).
1589 f->Set64<false>(o, value);
Elliott Hughesaed4be92011-12-02 16:16:23 -08001590 } else {
Elliott Hughes1bac54f2012-03-16 12:48:31 -07001591 CHECK_LE(width, 4);
Sebastien Hertzd2fe10a2014-01-15 10:20:56 +01001592 // Debugging can't use transactional mode (runtime only).
1593 f->Set32<false>(o, value);
Elliott Hughesaed4be92011-12-02 16:16:23 -08001594 }
1595 } else {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001596 mirror::Object* v = gRegistry->Get<mirror::Object*>(value);
Elliott Hughes64f574f2013-02-20 14:57:12 -08001597 if (v == ObjectRegistry::kInvalidObject) {
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -08001598 return JDWP::ERR_INVALID_OBJECT;
1599 }
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08001600 if (v != NULL) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001601 mirror::Class* field_type = FieldHelper(f).GetType();
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08001602 if (!field_type->IsAssignableFrom(v->GetClass())) {
1603 return JDWP::ERR_INVALID_OBJECT;
1604 }
1605 }
Sebastien Hertzd2fe10a2014-01-15 10:20:56 +01001606 // Debugging can't use transactional mode (runtime only).
1607 f->SetObject<false>(o, v);
Elliott Hughesaed4be92011-12-02 16:16:23 -08001608 }
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -08001609
1610 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001611}
1612
Elliott Hughes88d63092013-01-09 09:55:54 -08001613JDWP::JdwpError Dbg::SetFieldValue(JDWP::ObjectId object_id, JDWP::FieldId field_id, uint64_t value,
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001614 int width) {
Elliott Hughes88d63092013-01-09 09:55:54 -08001615 return SetFieldValueImpl(object_id, field_id, value, width, false);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001616}
1617
Elliott Hughes88d63092013-01-09 09:55:54 -08001618JDWP::JdwpError Dbg::SetStaticFieldValue(JDWP::FieldId field_id, uint64_t value, int width) {
1619 return SetFieldValueImpl(0, field_id, value, width, true);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001620}
1621
Elliott Hughes88d63092013-01-09 09:55:54 -08001622std::string Dbg::StringToUtf8(JDWP::ObjectId string_id) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001623 mirror::String* s = gRegistry->Get<mirror::String*>(string_id);
Elliott Hughes68fdbd02011-11-29 19:22:47 -08001624 return s->ToModifiedUtf8();
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001625}
1626
Jeff Hao579b0242013-11-18 13:16:49 -08001627void Dbg::OutputJValue(JDWP::JdwpTag tag, const JValue* return_value, JDWP::ExpandBuf* pReply) {
1628 if (IsPrimitiveTag(tag)) {
1629 expandBufAdd1(pReply, tag);
1630 if (tag == JDWP::JT_BOOLEAN || tag == JDWP::JT_BYTE) {
1631 expandBufAdd1(pReply, return_value->GetI());
1632 } else if (tag == JDWP::JT_CHAR || tag == JDWP::JT_SHORT) {
1633 expandBufAdd2BE(pReply, return_value->GetI());
1634 } else if (tag == JDWP::JT_FLOAT || tag == JDWP::JT_INT) {
1635 expandBufAdd4BE(pReply, return_value->GetI());
1636 } else if (tag == JDWP::JT_DOUBLE || tag == JDWP::JT_LONG) {
1637 expandBufAdd8BE(pReply, return_value->GetJ());
1638 } else {
1639 CHECK_EQ(tag, JDWP::JT_VOID);
1640 }
1641 } else {
1642 mirror::Object* value = return_value->GetL();
1643 expandBufAdd1(pReply, TagFromObject(value));
1644 expandBufAddObjectId(pReply, gRegistry->Add(value));
1645 }
1646}
1647
Elliott Hughes221229c2013-01-08 18:17:50 -08001648JDWP::JdwpError Dbg::GetThreadName(JDWP::ObjectId thread_id, std::string& name) {
jeffhaoa77f0f62012-12-05 17:19:31 -08001649 ScopedObjectAccessUnchecked soa(Thread::Current());
1650 MutexLock mu(soa.Self(), *Locks::thread_list_lock_);
Elliott Hughes221229c2013-01-08 18:17:50 -08001651 Thread* thread;
1652 JDWP::JdwpError error = DecodeThread(soa, thread_id, thread);
1653 if (error != JDWP::ERR_NONE && error != JDWP::ERR_THREAD_NOT_ALIVE) {
1654 return error;
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001655 }
Elliott Hughes221229c2013-01-08 18:17:50 -08001656
1657 // We still need to report the zombie threads' names, so we can't just call Thread::GetThreadName.
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001658 mirror::Object* thread_object = gRegistry->Get<mirror::Object*>(thread_id);
Brian Carlstromea46f952013-07-30 01:26:50 -07001659 mirror::ArtField* java_lang_Thread_name_field =
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001660 soa.DecodeField(WellKnownClasses::java_lang_Thread_name);
1661 mirror::String* s =
1662 reinterpret_cast<mirror::String*>(java_lang_Thread_name_field->GetObject(thread_object));
Elliott Hughes221229c2013-01-08 18:17:50 -08001663 if (s != NULL) {
1664 name = s->ToModifiedUtf8();
1665 }
1666 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001667}
1668
Elliott Hughes221229c2013-01-08 18:17:50 -08001669JDWP::JdwpError Dbg::GetThreadGroup(JDWP::ObjectId thread_id, JDWP::ExpandBuf* pReply) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001670 ScopedObjectAccess soa(Thread::Current());
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001671 mirror::Object* thread_object = gRegistry->Get<mirror::Object*>(thread_id);
Elliott Hughes64f574f2013-02-20 14:57:12 -08001672 if (thread_object == ObjectRegistry::kInvalidObject) {
Elliott Hughes2435a572012-02-17 16:07:41 -08001673 return JDWP::ERR_INVALID_OBJECT;
1674 }
1675
1676 // Okay, so it's an object, but is it actually a thread?
Ian Rogers50b35e22012-10-04 10:09:15 -07001677 MutexLock mu(soa.Self(), *Locks::thread_list_lock_);
Elliott Hughes221229c2013-01-08 18:17:50 -08001678 Thread* thread;
1679 JDWP::JdwpError error = DecodeThread(soa, thread_id, thread);
1680 if (error == JDWP::ERR_THREAD_NOT_ALIVE) {
1681 // Zombie threads are in the null group.
1682 expandBufAddObjectId(pReply, JDWP::ObjectId(0));
1683 return JDWP::ERR_NONE;
1684 }
1685 if (error != JDWP::ERR_NONE) {
1686 return error;
Elliott Hughes2435a572012-02-17 16:07:41 -08001687 }
Elliott Hughes499c5132011-11-17 14:55:11 -08001688
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001689 mirror::Class* c = Runtime::Current()->GetClassLinker()->FindSystemClass("Ljava/lang/Thread;");
Elliott Hughes499c5132011-11-17 14:55:11 -08001690 CHECK(c != NULL);
Brian Carlstromea46f952013-07-30 01:26:50 -07001691 mirror::ArtField* f = c->FindInstanceField("group", "Ljava/lang/ThreadGroup;");
Elliott Hughes499c5132011-11-17 14:55:11 -08001692 CHECK(f != NULL);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001693 mirror::Object* group = f->GetObject(thread_object);
Elliott Hughes499c5132011-11-17 14:55:11 -08001694 CHECK(group != NULL);
Elliott Hughes2435a572012-02-17 16:07:41 -08001695 JDWP::ObjectId thread_group_id = gRegistry->Add(group);
1696
1697 expandBufAddObjectId(pReply, thread_group_id);
1698 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001699}
1700
Elliott Hughes88d63092013-01-09 09:55:54 -08001701std::string Dbg::GetThreadGroupName(JDWP::ObjectId thread_group_id) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001702 ScopedObjectAccess soa(Thread::Current());
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001703 mirror::Object* thread_group = gRegistry->Get<mirror::Object*>(thread_group_id);
Elliott Hughes499c5132011-11-17 14:55:11 -08001704 CHECK(thread_group != NULL);
1705
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001706 mirror::Class* c = Runtime::Current()->GetClassLinker()->FindSystemClass("Ljava/lang/ThreadGroup;");
Elliott Hughes499c5132011-11-17 14:55:11 -08001707 CHECK(c != NULL);
Brian Carlstromea46f952013-07-30 01:26:50 -07001708 mirror::ArtField* f = c->FindInstanceField("name", "Ljava/lang/String;");
Elliott Hughes499c5132011-11-17 14:55:11 -08001709 CHECK(f != NULL);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001710 mirror::String* s = reinterpret_cast<mirror::String*>(f->GetObject(thread_group));
Elliott Hughes499c5132011-11-17 14:55:11 -08001711 return s->ToModifiedUtf8();
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001712}
1713
Elliott Hughes88d63092013-01-09 09:55:54 -08001714JDWP::ObjectId Dbg::GetThreadGroupParent(JDWP::ObjectId thread_group_id) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001715 mirror::Object* thread_group = gRegistry->Get<mirror::Object*>(thread_group_id);
Elliott Hughes4e235312011-12-02 11:34:15 -08001716 CHECK(thread_group != NULL);
1717
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001718 mirror::Class* c = Runtime::Current()->GetClassLinker()->FindSystemClass("Ljava/lang/ThreadGroup;");
Elliott Hughes4e235312011-12-02 11:34:15 -08001719 CHECK(c != NULL);
Brian Carlstromea46f952013-07-30 01:26:50 -07001720 mirror::ArtField* f = c->FindInstanceField("parent", "Ljava/lang/ThreadGroup;");
Elliott Hughes4e235312011-12-02 11:34:15 -08001721 CHECK(f != NULL);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001722 mirror::Object* parent = f->GetObject(thread_group);
Elliott Hughes4e235312011-12-02 11:34:15 -08001723 return gRegistry->Add(parent);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001724}
1725
1726JDWP::ObjectId Dbg::GetSystemThreadGroupId() {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001727 ScopedObjectAccessUnchecked soa(Thread::Current());
Brian Carlstromea46f952013-07-30 01:26:50 -07001728 mirror::ArtField* f = soa.DecodeField(WellKnownClasses::java_lang_ThreadGroup_systemThreadGroup);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001729 mirror::Object* group = f->GetObject(f->GetDeclaringClass());
Ian Rogers365c1022012-06-22 15:05:28 -07001730 return gRegistry->Add(group);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001731}
1732
1733JDWP::ObjectId Dbg::GetMainThreadGroupId() {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001734 ScopedObjectAccess soa(Thread::Current());
Brian Carlstromea46f952013-07-30 01:26:50 -07001735 mirror::ArtField* f = soa.DecodeField(WellKnownClasses::java_lang_ThreadGroup_mainThreadGroup);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001736 mirror::Object* group = f->GetObject(f->GetDeclaringClass());
Ian Rogers365c1022012-06-22 15:05:28 -07001737 return gRegistry->Add(group);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001738}
1739
Jeff Hao920af3e2013-08-28 15:46:38 -07001740JDWP::JdwpThreadStatus Dbg::ToJdwpThreadStatus(ThreadState state) {
1741 switch (state) {
1742 case kBlocked:
1743 return JDWP::TS_MONITOR;
1744 case kNative:
1745 case kRunnable:
1746 case kSuspended:
1747 return JDWP::TS_RUNNING;
1748 case kSleeping:
1749 return JDWP::TS_SLEEPING;
1750 case kStarting:
1751 case kTerminated:
1752 return JDWP::TS_ZOMBIE;
1753 case kTimedWaiting:
1754 case kWaitingForDebuggerSend:
1755 case kWaitingForDebuggerSuspension:
1756 case kWaitingForDebuggerToAttach:
Sebastien Hertz138dbfc2013-12-04 18:15:25 +01001757 case kWaitingForDeoptimization:
Jeff Hao920af3e2013-08-28 15:46:38 -07001758 case kWaitingForGcToComplete:
1759 case kWaitingForCheckPointsToRun:
1760 case kWaitingForJniOnLoad:
1761 case kWaitingForSignalCatcherOutput:
1762 case kWaitingInMainDebuggerLoop:
1763 case kWaitingInMainSignalCatcherLoop:
1764 case kWaitingPerformingGc:
1765 case kWaiting:
1766 return JDWP::TS_WAIT;
1767 // Don't add a 'default' here so the compiler can spot incompatible enum changes.
1768 }
1769 LOG(FATAL) << "Unknown thread state: " << state;
1770 return JDWP::TS_ZOMBIE;
1771}
1772
Elliott Hughes221229c2013-01-08 18:17:50 -08001773JDWP::JdwpError Dbg::GetThreadStatus(JDWP::ObjectId thread_id, JDWP::JdwpThreadStatus* pThreadStatus, JDWP::JdwpSuspendStatus* pSuspendStatus) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001774 ScopedObjectAccess soa(Thread::Current());
Elliott Hughes499c5132011-11-17 14:55:11 -08001775
Elliott Hughes9e0c1752013-01-09 14:02:58 -08001776 *pSuspendStatus = JDWP::SUSPEND_STATUS_NOT_SUSPENDED;
1777
Ian Rogers50b35e22012-10-04 10:09:15 -07001778 MutexLock mu(soa.Self(), *Locks::thread_list_lock_);
Elliott Hughes221229c2013-01-08 18:17:50 -08001779 Thread* thread;
1780 JDWP::JdwpError error = DecodeThread(soa, thread_id, thread);
1781 if (error != JDWP::ERR_NONE) {
1782 if (error == JDWP::ERR_THREAD_NOT_ALIVE) {
1783 *pThreadStatus = JDWP::TS_ZOMBIE;
Elliott Hughes221229c2013-01-08 18:17:50 -08001784 return JDWP::ERR_NONE;
1785 }
1786 return error;
Elliott Hughes499c5132011-11-17 14:55:11 -08001787 }
1788
Elliott Hughes9e0c1752013-01-09 14:02:58 -08001789 if (IsSuspendedForDebugger(soa, thread)) {
1790 *pSuspendStatus = JDWP::SUSPEND_STATUS_SUSPENDED;
Elliott Hughes499c5132011-11-17 14:55:11 -08001791 }
1792
Jeff Hao920af3e2013-08-28 15:46:38 -07001793 *pThreadStatus = ToJdwpThreadStatus(thread->GetState());
Elliott Hughes221229c2013-01-08 18:17:50 -08001794 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001795}
1796
Elliott Hughes221229c2013-01-08 18:17:50 -08001797JDWP::JdwpError Dbg::GetThreadDebugSuspendCount(JDWP::ObjectId thread_id, JDWP::ExpandBuf* pReply) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001798 ScopedObjectAccess soa(Thread::Current());
Ian Rogers50b35e22012-10-04 10:09:15 -07001799 MutexLock mu(soa.Self(), *Locks::thread_list_lock_);
Elliott Hughes221229c2013-01-08 18:17:50 -08001800 Thread* thread;
1801 JDWP::JdwpError error = DecodeThread(soa, thread_id, thread);
1802 if (error != JDWP::ERR_NONE) {
1803 return error;
Elliott Hughes2435a572012-02-17 16:07:41 -08001804 }
Ian Rogers50b35e22012-10-04 10:09:15 -07001805 MutexLock mu2(soa.Self(), *Locks::thread_suspend_count_lock_);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001806 expandBufAdd4BE(pReply, thread->GetDebugSuspendCount());
Elliott Hughes2435a572012-02-17 16:07:41 -08001807 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001808}
1809
Elliott Hughesf9501702013-01-11 11:22:27 -08001810JDWP::JdwpError Dbg::Interrupt(JDWP::ObjectId thread_id) {
1811 ScopedObjectAccess soa(Thread::Current());
1812 MutexLock mu(soa.Self(), *Locks::thread_list_lock_);
1813 Thread* thread;
1814 JDWP::JdwpError error = DecodeThread(soa, thread_id, thread);
1815 if (error != JDWP::ERR_NONE) {
1816 return error;
1817 }
1818 thread->Interrupt();
1819 return JDWP::ERR_NONE;
1820}
1821
Elliott Hughescaf76542012-06-28 16:08:22 -07001822void Dbg::GetThreads(JDWP::ObjectId thread_group_id, std::vector<JDWP::ObjectId>& thread_ids) {
Ian Rogers365c1022012-06-22 15:05:28 -07001823 class ThreadListVisitor {
1824 public:
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001825 ThreadListVisitor(const ScopedObjectAccessUnchecked& soa, mirror::Object* desired_thread_group,
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001826 std::vector<JDWP::ObjectId>& thread_ids)
Ian Rogersb726dcb2012-09-05 08:57:23 -07001827 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_)
jeffhao0dfbb7e2012-11-28 15:26:03 -08001828 : soa_(soa), desired_thread_group_(desired_thread_group), thread_ids_(thread_ids) {}
Ian Rogers365c1022012-06-22 15:05:28 -07001829
Elliott Hughesa2155262011-11-16 16:26:58 -08001830 static void Visit(Thread* t, void* arg) {
1831 reinterpret_cast<ThreadListVisitor*>(arg)->Visit(t);
1832 }
1833
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001834 // TODO: Enable annotalysis. We know lock is held in constructor, but abstraction confuses
1835 // annotalysis.
1836 void Visit(Thread* t) NO_THREAD_SAFETY_ANALYSIS {
Elliott Hughesa2155262011-11-16 16:26:58 -08001837 if (t == Dbg::GetDebugThread()) {
1838 // Skip the JDWP thread. Some debuggers get bent out of shape when they can't suspend and
1839 // query all threads, so it's easier if we just don't tell them about this thread.
1840 return;
1841 }
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001842 mirror::Object* peer = t->GetPeer();
jeffhao0dfbb7e2012-11-28 15:26:03 -08001843 if (IsInDesiredThreadGroup(peer)) {
Ian Rogers120f1c72012-09-28 17:17:10 -07001844 thread_ids_.push_back(gRegistry->Add(peer));
Elliott Hughesa2155262011-11-16 16:26:58 -08001845 }
1846 }
1847
Ian Rogers365c1022012-06-22 15:05:28 -07001848 private:
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001849 bool IsInDesiredThreadGroup(mirror::Object* peer)
jeffhao0dfbb7e2012-11-28 15:26:03 -08001850 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
jeffhao0dfbb7e2012-11-28 15:26:03 -08001851 // peer might be NULL if the thread is still starting up.
1852 if (peer == NULL) {
1853 // We can't tell the debugger about this thread yet.
1854 // TODO: if we identified threads to the debugger by their Thread*
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001855 // rather than their peer's mirror::Object*, we could fix this.
jeffhao0dfbb7e2012-11-28 15:26:03 -08001856 // Doing so might help us report ZOMBIE threads too.
1857 return false;
1858 }
jeffhaoc1e04902012-12-13 12:41:10 -08001859 // Do we want threads from all thread groups?
1860 if (desired_thread_group_ == NULL) {
1861 return true;
1862 }
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001863 mirror::Object* group = soa_.DecodeField(WellKnownClasses::java_lang_Thread_group)->GetObject(peer);
jeffhao0dfbb7e2012-11-28 15:26:03 -08001864 return (group == desired_thread_group_);
1865 }
1866
Mathieu Chartierdbe6f462012-09-25 16:54:50 -07001867 const ScopedObjectAccessUnchecked& soa_;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001868 mirror::Object* const desired_thread_group_;
Elliott Hughescaf76542012-06-28 16:08:22 -07001869 std::vector<JDWP::ObjectId>& thread_ids_;
Elliott Hughesa2155262011-11-16 16:26:58 -08001870 };
1871
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001872 ScopedObjectAccessUnchecked soa(Thread::Current());
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001873 mirror::Object* thread_group = gRegistry->Get<mirror::Object*>(thread_group_id);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001874 ThreadListVisitor tlv(soa, thread_group, thread_ids);
Ian Rogers50b35e22012-10-04 10:09:15 -07001875 MutexLock mu(soa.Self(), *Locks::thread_list_lock_);
Elliott Hughesf8349362012-06-18 15:00:06 -07001876 Runtime::Current()->GetThreadList()->ForEach(ThreadListVisitor::Visit, &tlv);
Elliott Hughescaf76542012-06-28 16:08:22 -07001877}
Elliott Hughesa2155262011-11-16 16:26:58 -08001878
Elliott Hughescaf76542012-06-28 16:08:22 -07001879void Dbg::GetChildThreadGroups(JDWP::ObjectId thread_group_id, std::vector<JDWP::ObjectId>& child_thread_group_ids) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001880 ScopedObjectAccess soa(Thread::Current());
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001881 mirror::Object* thread_group = gRegistry->Get<mirror::Object*>(thread_group_id);
Elliott Hughescaf76542012-06-28 16:08:22 -07001882
1883 // Get the ArrayList<ThreadGroup> "groups" out of this thread group...
Brian Carlstromea46f952013-07-30 01:26:50 -07001884 mirror::ArtField* groups_field = thread_group->GetClass()->FindInstanceField("groups", "Ljava/util/List;");
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001885 mirror::Object* groups_array_list = groups_field->GetObject(thread_group);
Elliott Hughescaf76542012-06-28 16:08:22 -07001886
1887 // Get the array and size out of the ArrayList<ThreadGroup>...
Brian Carlstromea46f952013-07-30 01:26:50 -07001888 mirror::ArtField* array_field = groups_array_list->GetClass()->FindInstanceField("array", "[Ljava/lang/Object;");
1889 mirror::ArtField* size_field = groups_array_list->GetClass()->FindInstanceField("size", "I");
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001890 mirror::ObjectArray<mirror::Object>* groups_array =
1891 array_field->GetObject(groups_array_list)->AsObjectArray<mirror::Object>();
Elliott Hughescaf76542012-06-28 16:08:22 -07001892 const int32_t size = size_field->GetInt(groups_array_list);
1893
1894 // Copy the first 'size' elements out of the array into the result.
1895 for (int32_t i = 0; i < size; ++i) {
1896 child_thread_group_ids.push_back(gRegistry->Add(groups_array->Get(i)));
Elliott Hughesa2155262011-11-16 16:26:58 -08001897 }
1898}
1899
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001900static int GetStackDepth(Thread* thread)
Ian Rogersb726dcb2012-09-05 08:57:23 -07001901 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Ian Rogers0399dde2012-06-06 17:09:28 -07001902 struct CountStackDepthVisitor : public StackVisitor {
Brian Carlstrom93ba8932013-07-17 21:31:49 -07001903 explicit CountStackDepthVisitor(Thread* thread)
Ian Rogers7a22fa62013-01-23 12:16:16 -08001904 : StackVisitor(thread, NULL), depth(0) {}
Ian Rogers0399dde2012-06-06 17:09:28 -07001905
Elliott Hughes64f574f2013-02-20 14:57:12 -08001906 // TODO: Enable annotalysis. We know lock is held in constructor, but abstraction confuses
1907 // annotalysis.
1908 bool VisitFrame() NO_THREAD_SAFETY_ANALYSIS {
Ian Rogers0399dde2012-06-06 17:09:28 -07001909 if (!GetMethod()->IsRuntimeMethod()) {
Elliott Hughesf8a2df72011-12-01 12:19:54 -08001910 ++depth;
1911 }
Elliott Hughes530fa002012-03-12 11:44:49 -07001912 return true;
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001913 }
1914 size_t depth;
1915 };
Elliott Hughes08fc03a2012-06-26 17:34:00 -07001916
Ian Rogers7a22fa62013-01-23 12:16:16 -08001917 CountStackDepthVisitor visitor(thread);
Ian Rogers0399dde2012-06-06 17:09:28 -07001918 visitor.WalkStack();
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001919 return visitor.depth;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001920}
1921
Elliott Hughes221229c2013-01-08 18:17:50 -08001922JDWP::JdwpError Dbg::GetThreadFrameCount(JDWP::ObjectId thread_id, size_t& result) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001923 ScopedObjectAccess soa(Thread::Current());
jeffhaoa77f0f62012-12-05 17:19:31 -08001924 MutexLock mu(soa.Self(), *Locks::thread_list_lock_);
Elliott Hughes221229c2013-01-08 18:17:50 -08001925 Thread* thread;
1926 JDWP::JdwpError error = DecodeThread(soa, thread_id, thread);
1927 if (error != JDWP::ERR_NONE) {
1928 return error;
1929 }
Elliott Hughesf15f4a02013-01-09 10:09:38 -08001930 if (!IsSuspendedForDebugger(soa, thread)) {
1931 return JDWP::ERR_THREAD_NOT_SUSPENDED;
1932 }
Elliott Hughes221229c2013-01-08 18:17:50 -08001933 result = GetStackDepth(thread);
1934 return JDWP::ERR_NONE;
Elliott Hughes86964332012-02-15 19:37:42 -08001935}
1936
Ian Rogers306057f2012-11-26 12:45:53 -08001937JDWP::JdwpError Dbg::GetThreadFrames(JDWP::ObjectId thread_id, size_t start_frame,
1938 size_t frame_count, JDWP::ExpandBuf* buf) {
Elliott Hughes6e9d22c2012-06-22 15:02:37 -07001939 class GetFrameVisitor : public StackVisitor {
1940 public:
Ian Rogers7a22fa62013-01-23 12:16:16 -08001941 GetFrameVisitor(Thread* thread, size_t start_frame, size_t frame_count, JDWP::ExpandBuf* buf)
Ian Rogersb726dcb2012-09-05 08:57:23 -07001942 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_)
Ian Rogers7a22fa62013-01-23 12:16:16 -08001943 : StackVisitor(thread, NULL), depth_(0),
Elliott Hughes6e9d22c2012-06-22 15:02:37 -07001944 start_frame_(start_frame), frame_count_(frame_count), buf_(buf) {
1945 expandBufAdd4BE(buf_, frame_count_);
Elliott Hughes03181a82011-11-17 17:22:21 -08001946 }
Ian Rogers0399dde2012-06-06 17:09:28 -07001947
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001948 // TODO: Enable annotalysis. We know lock is held in constructor, but abstraction confuses
1949 // annotalysis.
1950 virtual bool VisitFrame() NO_THREAD_SAFETY_ANALYSIS {
Ian Rogers0399dde2012-06-06 17:09:28 -07001951 if (GetMethod()->IsRuntimeMethod()) {
Brian Carlstrom7934ac22013-07-26 10:54:15 -07001952 return true; // The debugger can't do anything useful with a frame that has no Method*.
Elliott Hughes03181a82011-11-17 17:22:21 -08001953 }
Elliott Hughes6e9d22c2012-06-22 15:02:37 -07001954 if (depth_ >= start_frame_ + frame_count_) {
Elliott Hughes530fa002012-03-12 11:44:49 -07001955 return false;
Elliott Hughes03181a82011-11-17 17:22:21 -08001956 }
Elliott Hughes6e9d22c2012-06-22 15:02:37 -07001957 if (depth_ >= start_frame_) {
1958 JDWP::FrameId frame_id(GetFrameId());
1959 JDWP::JdwpLocation location;
1960 SetLocation(location, GetMethod(), GetDexPc());
Ian Rogersef7d42f2014-01-06 12:55:46 -08001961 VLOG(jdwp) << StringPrintf(" Frame %3zd: id=%3" PRIu64 " ", depth_, frame_id) << location;
Elliott Hughes6e9d22c2012-06-22 15:02:37 -07001962 expandBufAdd8BE(buf_, frame_id);
1963 expandBufAddLocation(buf_, location);
1964 }
1965 ++depth_;
Elliott Hughes530fa002012-03-12 11:44:49 -07001966 return true;
Elliott Hughes03181a82011-11-17 17:22:21 -08001967 }
Elliott Hughes6e9d22c2012-06-22 15:02:37 -07001968
1969 private:
1970 size_t depth_;
1971 const size_t start_frame_;
1972 const size_t frame_count_;
1973 JDWP::ExpandBuf* buf_;
Elliott Hughes03181a82011-11-17 17:22:21 -08001974 };
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001975
1976 ScopedObjectAccessUnchecked soa(Thread::Current());
jeffhaoa77f0f62012-12-05 17:19:31 -08001977 MutexLock mu(soa.Self(), *Locks::thread_list_lock_);
Elliott Hughes221229c2013-01-08 18:17:50 -08001978 Thread* thread;
1979 JDWP::JdwpError error = DecodeThread(soa, thread_id, thread);
1980 if (error != JDWP::ERR_NONE) {
1981 return error;
1982 }
Elliott Hughesf15f4a02013-01-09 10:09:38 -08001983 if (!IsSuspendedForDebugger(soa, thread)) {
1984 return JDWP::ERR_THREAD_NOT_SUSPENDED;
1985 }
Ian Rogers7a22fa62013-01-23 12:16:16 -08001986 GetFrameVisitor visitor(thread, start_frame, frame_count, buf);
Ian Rogers0399dde2012-06-06 17:09:28 -07001987 visitor.WalkStack();
Elliott Hughes6e9d22c2012-06-22 15:02:37 -07001988 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001989}
1990
1991JDWP::ObjectId Dbg::GetThreadSelfId() {
Mathieu Chartierdbe6f462012-09-25 16:54:50 -07001992 ScopedObjectAccessUnchecked soa(Thread::Current());
Ian Rogerscfaa4552012-11-26 21:00:08 -08001993 return gRegistry->Add(soa.Self()->GetPeer());
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001994}
1995
Elliott Hughes475fc232011-10-25 15:00:35 -07001996void Dbg::SuspendVM() {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001997 Runtime::Current()->GetThreadList()->SuspendAllForDebugger();
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001998}
1999
2000void Dbg::ResumeVM() {
Elliott Hughesc61a2672012-06-21 14:52:29 -07002001 Runtime::Current()->GetThreadList()->UndoDebuggerSuspensions();
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002002}
2003
Elliott Hughes221229c2013-01-08 18:17:50 -08002004JDWP::JdwpError Dbg::SuspendThread(JDWP::ObjectId thread_id, bool request_suspension) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002005 ScopedLocalRef<jobject> peer(Thread::Current()->GetJniEnv(), NULL);
2006 {
2007 ScopedObjectAccess soa(Thread::Current());
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002008 peer.reset(soa.AddLocalReference<jobject>(gRegistry->Get<mirror::Object*>(thread_id)));
Elliott Hughes4e235312011-12-02 11:34:15 -08002009 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002010 if (peer.get() == NULL) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002011 return JDWP::ERR_THREAD_NOT_ALIVE;
2012 }
2013 // Suspend thread to build stack trace.
Elliott Hughesf327e072013-01-09 16:01:26 -08002014 bool timed_out;
Ian Rogersd9c4fc92013-10-01 19:45:43 -07002015 Thread* thread = ThreadList::SuspendThreadByPeer(peer.get(), request_suspension, true,
2016 &timed_out);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002017 if (thread != NULL) {
2018 return JDWP::ERR_NONE;
Elliott Hughesf327e072013-01-09 16:01:26 -08002019 } else if (timed_out) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002020 return JDWP::ERR_INTERNAL;
2021 } else {
2022 return JDWP::ERR_THREAD_NOT_ALIVE;
2023 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002024}
2025
Elliott Hughes221229c2013-01-08 18:17:50 -08002026void Dbg::ResumeThread(JDWP::ObjectId thread_id) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002027 ScopedObjectAccessUnchecked soa(Thread::Current());
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002028 mirror::Object* peer = gRegistry->Get<mirror::Object*>(thread_id);
jeffhaoa77f0f62012-12-05 17:19:31 -08002029 Thread* thread;
2030 {
2031 MutexLock mu(soa.Self(), *Locks::thread_list_lock_);
2032 thread = Thread::FromManagedThread(soa, peer);
2033 }
Elliott Hughes4e235312011-12-02 11:34:15 -08002034 if (thread == NULL) {
2035 LOG(WARNING) << "No such thread for resume: " << peer;
2036 return;
2037 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002038 bool needs_resume;
2039 {
Ian Rogers50b35e22012-10-04 10:09:15 -07002040 MutexLock mu2(soa.Self(), *Locks::thread_suspend_count_lock_);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002041 needs_resume = thread->GetSuspendCount() > 0;
2042 }
2043 if (needs_resume) {
Elliott Hughes546b9862012-06-20 16:06:13 -07002044 Runtime::Current()->GetThreadList()->Resume(thread, true);
2045 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002046}
2047
2048void Dbg::SuspendSelf() {
Elliott Hughes475fc232011-10-25 15:00:35 -07002049 Runtime::Current()->GetThreadList()->SuspendSelfForDebugger();
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002050}
2051
Ian Rogers0399dde2012-06-06 17:09:28 -07002052struct GetThisVisitor : public StackVisitor {
Ian Rogers7a22fa62013-01-23 12:16:16 -08002053 GetThisVisitor(Thread* thread, Context* context, JDWP::FrameId frame_id)
Ian Rogersb726dcb2012-09-05 08:57:23 -07002054 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_)
Ian Rogers7a22fa62013-01-23 12:16:16 -08002055 : StackVisitor(thread, context), this_object(NULL), frame_id(frame_id) {}
Ian Rogers0399dde2012-06-06 17:09:28 -07002056
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002057 // TODO: Enable annotalysis. We know lock is held in constructor, but abstraction confuses
2058 // annotalysis.
2059 virtual bool VisitFrame() NO_THREAD_SAFETY_ANALYSIS {
Elliott Hughes6e9d22c2012-06-22 15:02:37 -07002060 if (frame_id != GetFrameId()) {
Ian Rogers0399dde2012-06-06 17:09:28 -07002061 return true; // continue
Ian Rogers0399dde2012-06-06 17:09:28 -07002062 } else {
Ian Rogers62d6c772013-02-27 08:32:07 -08002063 this_object = GetThisObject();
2064 return false;
Ian Rogers0399dde2012-06-06 17:09:28 -07002065 }
Elliott Hughes86b00102011-12-05 17:54:26 -08002066 }
Ian Rogers0399dde2012-06-06 17:09:28 -07002067
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002068 mirror::Object* this_object;
Elliott Hughes6e9d22c2012-06-22 15:02:37 -07002069 JDWP::FrameId frame_id;
Ian Rogers0399dde2012-06-06 17:09:28 -07002070};
2071
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002072JDWP::JdwpError Dbg::GetThisObject(JDWP::ObjectId thread_id, JDWP::FrameId frame_id,
2073 JDWP::ObjectId* result) {
2074 ScopedObjectAccessUnchecked soa(Thread::Current());
2075 Thread* thread;
2076 {
Ian Rogers50b35e22012-10-04 10:09:15 -07002077 MutexLock mu(soa.Self(), *Locks::thread_list_lock_);
Elliott Hughes221229c2013-01-08 18:17:50 -08002078 JDWP::JdwpError error = DecodeThread(soa, thread_id, thread);
2079 if (error != JDWP::ERR_NONE) {
2080 return error;
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002081 }
Elliott Hughes9e0c1752013-01-09 14:02:58 -08002082 if (!IsSuspendedForDebugger(soa, thread)) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002083 return JDWP::ERR_THREAD_NOT_SUSPENDED;
2084 }
Elliott Hughes6e9d22c2012-06-22 15:02:37 -07002085 }
Elliott Hughescaf76542012-06-28 16:08:22 -07002086 UniquePtr<Context> context(Context::Create());
Ian Rogers7a22fa62013-01-23 12:16:16 -08002087 GetThisVisitor visitor(thread, context.get(), frame_id);
Ian Rogers0399dde2012-06-06 17:09:28 -07002088 visitor.WalkStack();
Elliott Hughes6e9d22c2012-06-22 15:02:37 -07002089 *result = gRegistry->Add(visitor.this_object);
2090 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002091}
2092
Elliott Hughes88d63092013-01-09 09:55:54 -08002093void Dbg::GetLocalValue(JDWP::ObjectId thread_id, JDWP::FrameId frame_id, int slot, JDWP::JdwpTag tag,
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002094 uint8_t* buf, size_t width) {
Ian Rogers0399dde2012-06-06 17:09:28 -07002095 struct GetLocalVisitor : public StackVisitor {
Ian Rogers7a22fa62013-01-23 12:16:16 -08002096 GetLocalVisitor(Thread* thread, Context* context, JDWP::FrameId frame_id, int slot,
2097 JDWP::JdwpTag tag, uint8_t* buf, size_t width)
Ian Rogersb726dcb2012-09-05 08:57:23 -07002098 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_)
Ian Rogers7a22fa62013-01-23 12:16:16 -08002099 : StackVisitor(thread, context), frame_id_(frame_id), slot_(slot), tag_(tag),
Ian Rogersca190662012-06-26 15:45:57 -07002100 buf_(buf), width_(width) {}
2101
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002102 // TODO: Enable annotalysis. We know lock is held in constructor, but abstraction confuses
2103 // annotalysis.
2104 bool VisitFrame() NO_THREAD_SAFETY_ANALYSIS {
Ian Rogers0399dde2012-06-06 17:09:28 -07002105 if (GetFrameId() != frame_id_) {
2106 return true; // Not our frame, carry on.
Elliott Hughesdbb40792011-11-18 17:05:22 -08002107 }
Ian Rogers0399dde2012-06-06 17:09:28 -07002108 // TODO: check that the tag is compatible with the actual type of the slot!
Brian Carlstromea46f952013-07-30 01:26:50 -07002109 mirror::ArtMethod* m = GetMethod();
Ian Rogers0399dde2012-06-06 17:09:28 -07002110 uint16_t reg = DemangleSlot(slot_, m);
Elliott Hughesdbb40792011-11-18 17:05:22 -08002111
Ian Rogers0399dde2012-06-06 17:09:28 -07002112 switch (tag_) {
2113 case JDWP::JT_BOOLEAN:
2114 {
2115 CHECK_EQ(width_, 1U);
Ian Rogers2bcb4a42012-11-08 10:39:18 -08002116 uint32_t intVal = GetVReg(m, reg, kIntVReg);
Ian Rogers0399dde2012-06-06 17:09:28 -07002117 VLOG(jdwp) << "get boolean local " << reg << " = " << intVal;
2118 JDWP::Set1(buf_+1, intVal != 0);
2119 }
2120 break;
2121 case JDWP::JT_BYTE:
2122 {
2123 CHECK_EQ(width_, 1U);
Ian Rogers2bcb4a42012-11-08 10:39:18 -08002124 uint32_t intVal = GetVReg(m, reg, kIntVReg);
Ian Rogers0399dde2012-06-06 17:09:28 -07002125 VLOG(jdwp) << "get byte local " << reg << " = " << intVal;
2126 JDWP::Set1(buf_+1, intVal);
2127 }
2128 break;
2129 case JDWP::JT_SHORT:
2130 case JDWP::JT_CHAR:
2131 {
2132 CHECK_EQ(width_, 2U);
Ian Rogers2bcb4a42012-11-08 10:39:18 -08002133 uint32_t intVal = GetVReg(m, reg, kIntVReg);
Ian Rogers0399dde2012-06-06 17:09:28 -07002134 VLOG(jdwp) << "get short/char local " << reg << " = " << intVal;
2135 JDWP::Set2BE(buf_+1, intVal);
2136 }
2137 break;
2138 case JDWP::JT_INT:
Ian Rogers2bcb4a42012-11-08 10:39:18 -08002139 {
2140 CHECK_EQ(width_, 4U);
2141 uint32_t intVal = GetVReg(m, reg, kIntVReg);
2142 VLOG(jdwp) << "get int local " << reg << " = " << intVal;
2143 JDWP::Set4BE(buf_+1, intVal);
2144 }
2145 break;
Ian Rogers0399dde2012-06-06 17:09:28 -07002146 case JDWP::JT_FLOAT:
2147 {
2148 CHECK_EQ(width_, 4U);
Ian Rogers2bcb4a42012-11-08 10:39:18 -08002149 uint32_t intVal = GetVReg(m, reg, kFloatVReg);
Ian Rogers0399dde2012-06-06 17:09:28 -07002150 VLOG(jdwp) << "get int/float local " << reg << " = " << intVal;
2151 JDWP::Set4BE(buf_+1, intVal);
2152 }
2153 break;
2154 case JDWP::JT_ARRAY:
2155 {
2156 CHECK_EQ(width_, sizeof(JDWP::ObjectId));
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002157 mirror::Object* o = reinterpret_cast<mirror::Object*>(GetVReg(m, reg, kReferenceVReg));
Ian Rogers0399dde2012-06-06 17:09:28 -07002158 VLOG(jdwp) << "get array local " << reg << " = " << o;
Mathieu Chartier590fee92013-09-13 13:46:47 -07002159 if (!Runtime::Current()->GetHeap()->IsValidObjectAddress(o)) {
Ian Rogers0399dde2012-06-06 17:09:28 -07002160 LOG(FATAL) << "Register " << reg << " expected to hold array: " << o;
2161 }
2162 JDWP::SetObjectId(buf_+1, gRegistry->Add(o));
2163 }
2164 break;
2165 case JDWP::JT_CLASS_LOADER:
2166 case JDWP::JT_CLASS_OBJECT:
2167 case JDWP::JT_OBJECT:
2168 case JDWP::JT_STRING:
2169 case JDWP::JT_THREAD:
2170 case JDWP::JT_THREAD_GROUP:
2171 {
2172 CHECK_EQ(width_, sizeof(JDWP::ObjectId));
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002173 mirror::Object* o = reinterpret_cast<mirror::Object*>(GetVReg(m, reg, kReferenceVReg));
Ian Rogers0399dde2012-06-06 17:09:28 -07002174 VLOG(jdwp) << "get object local " << reg << " = " << o;
Mathieu Chartier590fee92013-09-13 13:46:47 -07002175 if (!Runtime::Current()->GetHeap()->IsValidObjectAddress(o)) {
Ian Rogers0399dde2012-06-06 17:09:28 -07002176 LOG(FATAL) << "Register " << reg << " expected to hold object: " << o;
2177 }
2178 tag_ = TagFromObject(o);
2179 JDWP::SetObjectId(buf_+1, gRegistry->Add(o));
2180 }
2181 break;
2182 case JDWP::JT_DOUBLE:
Ian Rogers2bcb4a42012-11-08 10:39:18 -08002183 {
2184 CHECK_EQ(width_, 8U);
2185 uint32_t lo = GetVReg(m, reg, kDoubleLoVReg);
2186 uint64_t hi = GetVReg(m, reg + 1, kDoubleHiVReg);
2187 uint64_t longVal = (hi << 32) | lo;
2188 VLOG(jdwp) << "get double/long local " << hi << ":" << lo << " = " << longVal;
2189 JDWP::Set8BE(buf_+1, longVal);
2190 }
2191 break;
Ian Rogers0399dde2012-06-06 17:09:28 -07002192 case JDWP::JT_LONG:
2193 {
2194 CHECK_EQ(width_, 8U);
Ian Rogers2bcb4a42012-11-08 10:39:18 -08002195 uint32_t lo = GetVReg(m, reg, kLongLoVReg);
2196 uint64_t hi = GetVReg(m, reg + 1, kLongHiVReg);
Ian Rogers0399dde2012-06-06 17:09:28 -07002197 uint64_t longVal = (hi << 32) | lo;
2198 VLOG(jdwp) << "get double/long local " << hi << ":" << lo << " = " << longVal;
2199 JDWP::Set8BE(buf_+1, longVal);
2200 }
2201 break;
2202 default:
2203 LOG(FATAL) << "Unknown tag " << tag_;
2204 break;
2205 }
2206
2207 // Prepend tag, which may have been updated.
2208 JDWP::Set1(buf_, tag_);
2209 return false;
2210 }
2211
2212 const JDWP::FrameId frame_id_;
2213 const int slot_;
2214 JDWP::JdwpTag tag_;
2215 uint8_t* const buf_;
2216 const size_t width_;
2217 };
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002218
2219 ScopedObjectAccessUnchecked soa(Thread::Current());
jeffhaoa77f0f62012-12-05 17:19:31 -08002220 MutexLock mu(soa.Self(), *Locks::thread_list_lock_);
Elliott Hughes221229c2013-01-08 18:17:50 -08002221 Thread* thread;
2222 JDWP::JdwpError error = DecodeThread(soa, thread_id, thread);
2223 if (error != JDWP::ERR_NONE) {
2224 return;
2225 }
Ian Rogers0399dde2012-06-06 17:09:28 -07002226 UniquePtr<Context> context(Context::Create());
Ian Rogers7a22fa62013-01-23 12:16:16 -08002227 GetLocalVisitor visitor(thread, context.get(), frame_id, slot, tag, buf, width);
Ian Rogers0399dde2012-06-06 17:09:28 -07002228 visitor.WalkStack();
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002229}
2230
Elliott Hughes88d63092013-01-09 09:55:54 -08002231void Dbg::SetLocalValue(JDWP::ObjectId thread_id, JDWP::FrameId frame_id, int slot, JDWP::JdwpTag tag,
Ian Rogers0399dde2012-06-06 17:09:28 -07002232 uint64_t value, size_t width) {
2233 struct SetLocalVisitor : public StackVisitor {
Ian Rogers7a22fa62013-01-23 12:16:16 -08002234 SetLocalVisitor(Thread* thread, Context* context,
Ian Rogers0399dde2012-06-06 17:09:28 -07002235 JDWP::FrameId frame_id, int slot, JDWP::JdwpTag tag, uint64_t value,
Ian Rogersca190662012-06-26 15:45:57 -07002236 size_t width)
Ian Rogersb726dcb2012-09-05 08:57:23 -07002237 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_)
Ian Rogers7a22fa62013-01-23 12:16:16 -08002238 : StackVisitor(thread, context),
Elliott Hughes08fc03a2012-06-26 17:34:00 -07002239 frame_id_(frame_id), slot_(slot), tag_(tag), value_(value), width_(width) {}
Ian Rogersca190662012-06-26 15:45:57 -07002240
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002241 // TODO: Enable annotalysis. We know lock is held in constructor, but abstraction confuses
2242 // annotalysis.
2243 bool VisitFrame() NO_THREAD_SAFETY_ANALYSIS {
Ian Rogers0399dde2012-06-06 17:09:28 -07002244 if (GetFrameId() != frame_id_) {
2245 return true; // Not our frame, carry on.
2246 }
2247 // TODO: check that the tag is compatible with the actual type of the slot!
Brian Carlstromea46f952013-07-30 01:26:50 -07002248 mirror::ArtMethod* m = GetMethod();
Ian Rogers0399dde2012-06-06 17:09:28 -07002249 uint16_t reg = DemangleSlot(slot_, m);
2250
2251 switch (tag_) {
2252 case JDWP::JT_BOOLEAN:
2253 case JDWP::JT_BYTE:
2254 CHECK_EQ(width_, 1U);
Ian Rogers2bcb4a42012-11-08 10:39:18 -08002255 SetVReg(m, reg, static_cast<uint32_t>(value_), kIntVReg);
Ian Rogers0399dde2012-06-06 17:09:28 -07002256 break;
2257 case JDWP::JT_SHORT:
2258 case JDWP::JT_CHAR:
2259 CHECK_EQ(width_, 2U);
Ian Rogers2bcb4a42012-11-08 10:39:18 -08002260 SetVReg(m, reg, static_cast<uint32_t>(value_), kIntVReg);
Ian Rogers0399dde2012-06-06 17:09:28 -07002261 break;
2262 case JDWP::JT_INT:
Ian Rogers2bcb4a42012-11-08 10:39:18 -08002263 CHECK_EQ(width_, 4U);
2264 SetVReg(m, reg, static_cast<uint32_t>(value_), kIntVReg);
2265 break;
Ian Rogers0399dde2012-06-06 17:09:28 -07002266 case JDWP::JT_FLOAT:
2267 CHECK_EQ(width_, 4U);
Ian Rogers2bcb4a42012-11-08 10:39:18 -08002268 SetVReg(m, reg, static_cast<uint32_t>(value_), kFloatVReg);
Ian Rogers0399dde2012-06-06 17:09:28 -07002269 break;
2270 case JDWP::JT_ARRAY:
2271 case JDWP::JT_OBJECT:
2272 case JDWP::JT_STRING:
2273 {
2274 CHECK_EQ(width_, sizeof(JDWP::ObjectId));
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002275 mirror::Object* o = gRegistry->Get<mirror::Object*>(static_cast<JDWP::ObjectId>(value_));
Elliott Hughes64f574f2013-02-20 14:57:12 -08002276 if (o == ObjectRegistry::kInvalidObject) {
Ian Rogers0399dde2012-06-06 17:09:28 -07002277 UNIMPLEMENTED(FATAL) << "return an error code when given an invalid object to store";
2278 }
Ian Rogers2bcb4a42012-11-08 10:39:18 -08002279 SetVReg(m, reg, static_cast<uint32_t>(reinterpret_cast<uintptr_t>(o)), kReferenceVReg);
Ian Rogers0399dde2012-06-06 17:09:28 -07002280 }
2281 break;
2282 case JDWP::JT_DOUBLE:
Ian Rogers2bcb4a42012-11-08 10:39:18 -08002283 CHECK_EQ(width_, 8U);
2284 SetVReg(m, reg, static_cast<uint32_t>(value_), kDoubleLoVReg);
2285 SetVReg(m, reg + 1, static_cast<uint32_t>(value_ >> 32), kDoubleHiVReg);
2286 break;
Ian Rogers0399dde2012-06-06 17:09:28 -07002287 case JDWP::JT_LONG:
2288 CHECK_EQ(width_, 8U);
Ian Rogers2bcb4a42012-11-08 10:39:18 -08002289 SetVReg(m, reg, static_cast<uint32_t>(value_), kLongLoVReg);
2290 SetVReg(m, reg + 1, static_cast<uint32_t>(value_ >> 32), kLongHiVReg);
Ian Rogers0399dde2012-06-06 17:09:28 -07002291 break;
2292 default:
2293 LOG(FATAL) << "Unknown tag " << tag_;
2294 break;
2295 }
2296 return false;
2297 }
2298
2299 const JDWP::FrameId frame_id_;
2300 const int slot_;
2301 const JDWP::JdwpTag tag_;
2302 const uint64_t value_;
2303 const size_t width_;
2304 };
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002305
2306 ScopedObjectAccessUnchecked soa(Thread::Current());
jeffhaoa77f0f62012-12-05 17:19:31 -08002307 MutexLock mu(soa.Self(), *Locks::thread_list_lock_);
Elliott Hughes221229c2013-01-08 18:17:50 -08002308 Thread* thread;
2309 JDWP::JdwpError error = DecodeThread(soa, thread_id, thread);
2310 if (error != JDWP::ERR_NONE) {
2311 return;
2312 }
Elliott Hughes08fc03a2012-06-26 17:34:00 -07002313 UniquePtr<Context> context(Context::Create());
Ian Rogers7a22fa62013-01-23 12:16:16 -08002314 SetLocalVisitor visitor(thread, context.get(), frame_id, slot, tag, value, width);
Ian Rogers0399dde2012-06-06 17:09:28 -07002315 visitor.WalkStack();
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002316}
2317
Ian Rogersef7d42f2014-01-06 12:55:46 -08002318void Dbg::PostLocationEvent(mirror::ArtMethod* m, int dex_pc, mirror::Object* this_object,
Jeff Hao579b0242013-11-18 13:16:49 -08002319 int event_flags, const JValue* return_value) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002320 mirror::Class* c = m->GetDeclaringClass();
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08002321
2322 JDWP::JdwpLocation location;
Elliott Hughes74847412012-06-20 18:10:21 -07002323 location.type_tag = c->IsInterface() ? JDWP::TT_INTERFACE : JDWP::TT_CLASS;
Elliott Hughes64f574f2013-02-20 14:57:12 -08002324 location.class_id = gRegistry->AddRefType(c);
Elliott Hughes74847412012-06-20 18:10:21 -07002325 location.method_id = ToMethodId(m);
Elliott Hughes972a47b2012-02-21 18:16:06 -08002326 location.dex_pc = m->IsNative() ? -1 : dex_pc;
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08002327
Elliott Hughes64f574f2013-02-20 14:57:12 -08002328 // If 'this_object' isn't already in the registry, we know that we're not looking for it,
2329 // so there's no point adding it to the registry and burning through ids.
2330 JDWP::ObjectId this_id = 0;
2331 if (gRegistry->Contains(this_object)) {
2332 this_id = gRegistry->Add(this_object);
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08002333 }
Jeff Hao579b0242013-11-18 13:16:49 -08002334 gJdwpState->PostLocationEvent(&location, this_id, event_flags, return_value);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002335}
2336
Ian Rogers62d6c772013-02-27 08:32:07 -08002337void Dbg::PostException(Thread* thread, const ThrowLocation& throw_location,
Brian Carlstromea46f952013-07-30 01:26:50 -07002338 mirror::ArtMethod* catch_method,
Elliott Hughes64f574f2013-02-20 14:57:12 -08002339 uint32_t catch_dex_pc, mirror::Throwable* exception_object) {
Elliott Hughesc0f09332012-03-26 13:27:06 -07002340 if (!IsDebuggerActive()) {
Ian Rogers0ad5bb82011-12-07 10:16:32 -08002341 return;
2342 }
Elliott Hughes4740cdf2011-12-07 14:07:12 -08002343
Ian Rogers62d6c772013-02-27 08:32:07 -08002344 JDWP::JdwpLocation jdwp_throw_location;
2345 SetLocation(jdwp_throw_location, throw_location.GetMethod(), throw_location.GetDexPc());
Elliott Hughesd07986f2011-12-06 18:27:45 -08002346 JDWP::JdwpLocation catch_location;
Elliott Hughescaf76542012-06-28 16:08:22 -07002347 SetLocation(catch_location, catch_method, catch_dex_pc);
Elliott Hughesd07986f2011-12-06 18:27:45 -08002348
2349 // We need 'this' for InstanceOnly filters.
Ian Rogers62d6c772013-02-27 08:32:07 -08002350 JDWP::ObjectId this_id = gRegistry->Add(throw_location.GetThis());
Elliott Hughes64f574f2013-02-20 14:57:12 -08002351 JDWP::ObjectId exception_id = gRegistry->Add(exception_object);
2352 JDWP::RefTypeId exception_class_id = gRegistry->AddRefType(exception_object->GetClass());
Elliott Hughesd07986f2011-12-06 18:27:45 -08002353
Ian Rogers62d6c772013-02-27 08:32:07 -08002354 gJdwpState->PostException(&jdwp_throw_location, exception_id, exception_class_id, &catch_location,
2355 this_id);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002356}
2357
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002358void Dbg::PostClassPrepare(mirror::Class* c) {
Elliott Hughesc0f09332012-03-26 13:27:06 -07002359 if (!IsDebuggerActive()) {
Elliott Hughes4740cdf2011-12-07 14:07:12 -08002360 return;
2361 }
2362
Elliott Hughes3d30d9b2011-12-07 17:35:48 -08002363 // OLD-TODO - we currently always send both "verified" and "prepared" since
Elliott Hughes4740cdf2011-12-07 14:07:12 -08002364 // debuggers seem to like that. There might be some advantage to honesty,
2365 // since the class may not yet be verified.
2366 int state = JDWP::CS_VERIFIED | JDWP::CS_PREPARED;
2367 JDWP::JdwpTypeTag tag = c->IsInterface() ? JDWP::TT_INTERFACE : JDWP::TT_CLASS;
Ian Rogersfc0e94b2013-09-23 23:51:32 -07002368 gJdwpState->PostClassPrepare(tag, gRegistry->Add(c),
Ian Rogersdfb325e2013-10-30 01:00:44 -07002369 ClassHelper(c).GetDescriptor(), state);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002370}
2371
Ian Rogers62d6c772013-02-27 08:32:07 -08002372void Dbg::UpdateDebugger(Thread* thread, mirror::Object* this_object,
Ian Rogersef7d42f2014-01-06 12:55:46 -08002373 mirror::ArtMethod* m, uint32_t dex_pc) {
Ian Rogers62d6c772013-02-27 08:32:07 -08002374 if (!IsDebuggerActive() || dex_pc == static_cast<uint32_t>(-2) /* fake method exit */) {
Elliott Hughes2aa2e392012-02-17 17:15:43 -08002375 return;
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08002376 }
2377
Elliott Hughes2aa2e392012-02-17 17:15:43 -08002378 int event_flags = 0;
2379
Elliott Hughes86964332012-02-15 19:37:42 -08002380 if (IsBreakpoint(m, dex_pc)) {
2381 event_flags |= kBreakpoint;
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08002382 }
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08002383
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01002384 // If the debugger is single-stepping one of our threads, check to
2385 // see if we're that thread and we've reached a step point.
2386 const SingleStepControl* single_step_control = thread->GetSingleStepControl();
2387 DCHECK(single_step_control != nullptr);
2388 if (single_step_control->is_active) {
2389 CHECK(!m->IsNative());
2390 if (single_step_control->step_depth == JDWP::SD_INTO) {
2391 // Step into method calls. We break when the line number
2392 // or method pointer changes. If we're in SS_MIN mode, we
2393 // always stop.
2394 if (single_step_control->method != m) {
2395 event_flags |= kSingleStep;
2396 VLOG(jdwp) << "SS new method";
2397 } else if (single_step_control->step_size == JDWP::SS_MIN) {
2398 event_flags |= kSingleStep;
2399 VLOG(jdwp) << "SS new instruction";
2400 } else if (single_step_control->dex_pcs.find(dex_pc) == single_step_control->dex_pcs.end()) {
2401 event_flags |= kSingleStep;
2402 VLOG(jdwp) << "SS new line";
2403 }
2404 } else if (single_step_control->step_depth == JDWP::SD_OVER) {
2405 // Step over method calls. We break when the line number is
2406 // different and the frame depth is <= the original frame
2407 // depth. (We can't just compare on the method, because we
2408 // might get unrolled past it by an exception, and it's tricky
2409 // to identify recursion.)
2410
2411 int stack_depth = GetStackDepth(thread);
2412
2413 if (stack_depth < single_step_control->stack_depth) {
2414 // Popped up one or more frames, always trigger.
2415 event_flags |= kSingleStep;
2416 VLOG(jdwp) << "SS method pop";
2417 } else if (stack_depth == single_step_control->stack_depth) {
2418 // Same depth, see if we moved.
2419 if (single_step_control->step_size == JDWP::SS_MIN) {
Elliott Hughes86964332012-02-15 19:37:42 -08002420 event_flags |= kSingleStep;
2421 VLOG(jdwp) << "SS new instruction";
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01002422 } else if (single_step_control->dex_pcs.find(dex_pc) == single_step_control->dex_pcs.end()) {
Elliott Hughes2435a572012-02-17 16:07:41 -08002423 event_flags |= kSingleStep;
2424 VLOG(jdwp) << "SS new line";
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08002425 }
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01002426 }
2427 } else {
2428 CHECK_EQ(single_step_control->step_depth, JDWP::SD_OUT);
2429 // Return from the current method. We break when the frame
2430 // depth pops up.
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08002431
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01002432 // This differs from the "method exit" break in that it stops
2433 // with the PC at the next instruction in the returned-to
2434 // function, rather than the end of the returning function.
Elliott Hughes86964332012-02-15 19:37:42 -08002435
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01002436 int stack_depth = GetStackDepth(thread);
2437 if (stack_depth < single_step_control->stack_depth) {
2438 event_flags |= kSingleStep;
2439 VLOG(jdwp) << "SS method pop";
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08002440 }
2441 }
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08002442 }
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08002443
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08002444 // If there's something interesting going on, see if it matches one
2445 // of the debugger filters.
2446 if (event_flags != 0) {
Jeff Hao579b0242013-11-18 13:16:49 -08002447 Dbg::PostLocationEvent(m, dex_pc, this_object, event_flags, nullptr);
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08002448 }
2449}
2450
Sebastien Hertz138dbfc2013-12-04 18:15:25 +01002451static void ProcessDeoptimizationRequests()
2452 LOCKS_EXCLUDED(Locks::deoptimization_lock_)
2453 EXCLUSIVE_LOCKS_REQUIRED(Locks::mutator_lock_) {
2454 Locks::mutator_lock_->AssertExclusiveHeld(Thread::Current());
2455 MutexLock mu(Thread::Current(), *Locks::deoptimization_lock_);
2456 instrumentation::Instrumentation* instrumentation = Runtime::Current()->GetInstrumentation();
2457 for (const MethodInstrumentationRequest& request : gDeoptimizationRequests) {
2458 mirror::ArtMethod* const method = request.method;
2459 if (method != nullptr) {
2460 // Selective deoptimization.
2461 if (request.deoptimize) {
2462 VLOG(jdwp) << "Deoptimize method " << PrettyMethod(method);
2463 instrumentation->Deoptimize(method);
2464 } else {
2465 VLOG(jdwp) << "Undeoptimize method " << PrettyMethod(method);
2466 instrumentation->Undeoptimize(method);
2467 }
2468 } else {
2469 // Full deoptimization.
2470 if (request.deoptimize) {
2471 VLOG(jdwp) << "Deoptimize the world";
2472 instrumentation->DeoptimizeEverything();
2473 } else {
2474 VLOG(jdwp) << "Undeoptimize the world";
2475 instrumentation->UndeoptimizeEverything();
2476 }
2477 }
2478 }
2479 gDeoptimizationRequests.clear();
2480}
2481
2482// Process deoptimization requests after suspending all mutator threads.
2483void Dbg::ManageDeoptimization() {
2484 Thread* const self = Thread::Current();
2485 {
2486 // Avoid suspend/resume if there is no pending request.
2487 MutexLock mu(self, *Locks::deoptimization_lock_);
2488 if (gDeoptimizationRequests.empty()) {
2489 return;
2490 }
2491 }
2492 CHECK_EQ(self->GetState(), kRunnable);
2493 self->TransitionFromRunnableToSuspended(kWaitingForDeoptimization);
2494 // We need to suspend mutator threads first.
2495 Runtime* const runtime = Runtime::Current();
2496 runtime->GetThreadList()->SuspendAll();
2497 const ThreadState old_state = self->SetStateUnsafe(kRunnable);
2498 ProcessDeoptimizationRequests();
2499 CHECK_EQ(self->SetStateUnsafe(old_state), kRunnable);
2500 runtime->GetThreadList()->ResumeAll();
2501 self->TransitionFromSuspendedToRunnable();
2502}
2503
2504// Enable full deoptimization.
2505void Dbg::EnableFullDeoptimization() {
2506 MutexLock mu(Thread::Current(), *Locks::deoptimization_lock_);
2507 VLOG(jdwp) << "Request full deoptimization";
2508 gDeoptimizationRequests.push_back(MethodInstrumentationRequest(true, nullptr));
2509}
2510
2511// Disable full deoptimization.
2512void Dbg::DisableFullDeoptimization() {
2513 MutexLock mu(Thread::Current(), *Locks::deoptimization_lock_);
2514 VLOG(jdwp) << "Request full undeoptimization";
2515 gDeoptimizationRequests.push_back(MethodInstrumentationRequest(false, nullptr));
2516}
2517
Elliott Hughes86964332012-02-15 19:37:42 -08002518void Dbg::WatchLocation(const JDWP::JdwpLocation* location) {
Sebastien Hertz138dbfc2013-12-04 18:15:25 +01002519 bool need_deoptimization = true;
Brian Carlstromea46f952013-07-30 01:26:50 -07002520 mirror::ArtMethod* m = FromMethodId(location->method_id);
Sebastien Hertz138dbfc2013-12-04 18:15:25 +01002521 {
2522 MutexLock mu(Thread::Current(), *Locks::breakpoint_lock_);
2523
2524 // If there is no breakpoint on this method yet, we need to deoptimize it.
2525 for (const Breakpoint& breakpoint : gBreakpoints) {
2526 if (breakpoint.method == m) {
2527 // We already set a breakpoint on this method, hence we deoptimized it.
2528 DCHECK(Runtime::Current()->GetInstrumentation()->IsDeoptimized(m));
2529 need_deoptimization = false;
2530 break;
2531 }
2532 }
2533
2534 gBreakpoints.push_back(Breakpoint(m, location->dex_pc));
2535 VLOG(jdwp) << "Set breakpoint #" << (gBreakpoints.size() - 1) << ": " << gBreakpoints[gBreakpoints.size() - 1];
2536 }
2537
2538 if (need_deoptimization) {
2539 // Request its deoptimization. This will be done after updating the JDWP event list.
2540 MutexLock mu(Thread::Current(), *Locks::deoptimization_lock_);
2541 gDeoptimizationRequests.push_back(MethodInstrumentationRequest(true, m));
2542 VLOG(jdwp) << "Request deoptimization of " << PrettyMethod(m);
2543 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002544}
2545
Elliott Hughes86964332012-02-15 19:37:42 -08002546void Dbg::UnwatchLocation(const JDWP::JdwpLocation* location) {
Sebastien Hertz138dbfc2013-12-04 18:15:25 +01002547 bool can_undeoptimize = true;
Brian Carlstromea46f952013-07-30 01:26:50 -07002548 mirror::ArtMethod* m = FromMethodId(location->method_id);
Sebastien Hertz138dbfc2013-12-04 18:15:25 +01002549 DCHECK(Runtime::Current()->GetInstrumentation()->IsDeoptimized(m));
2550 {
2551 MutexLock mu(Thread::Current(), *Locks::breakpoint_lock_);
2552 for (size_t i = 0, e = gBreakpoints.size(); i < e; ++i) {
2553 if (gBreakpoints[i].method == m && gBreakpoints[i].dex_pc == location->dex_pc) {
2554 VLOG(jdwp) << "Removed breakpoint #" << i << ": " << gBreakpoints[i];
2555 gBreakpoints.erase(gBreakpoints.begin() + i);
2556 break;
2557 }
Elliott Hughes86964332012-02-15 19:37:42 -08002558 }
Sebastien Hertz138dbfc2013-12-04 18:15:25 +01002559
2560 // If there is no breakpoint on this method, we can undeoptimize it.
2561 for (const Breakpoint& breakpoint : gBreakpoints) {
2562 if (breakpoint.method == m) {
2563 can_undeoptimize = false;
2564 break;
2565 }
2566 }
2567 }
2568
2569 if (can_undeoptimize) {
2570 // Request its undeoptimization. This will be done after updating the JDWP event list.
2571 MutexLock mu(Thread::Current(), *Locks::deoptimization_lock_);
2572 gDeoptimizationRequests.push_back(MethodInstrumentationRequest(false, m));
2573 VLOG(jdwp) << "Request undeoptimization of " << PrettyMethod(m);
Elliott Hughes86964332012-02-15 19:37:42 -08002574 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002575}
2576
Jeff Hao449db332013-04-12 18:30:52 -07002577// Scoped utility class to suspend a thread so that we may do tasks such as walk its stack. Doesn't
2578// cause suspension if the thread is the current thread.
2579class ScopedThreadSuspension {
2580 public:
Ian Rogers33e95662013-05-20 20:29:14 -07002581 ScopedThreadSuspension(Thread* self, JDWP::ObjectId thread_id)
2582 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) :
Jeff Hao449db332013-04-12 18:30:52 -07002583 thread_(NULL),
2584 error_(JDWP::ERR_NONE),
2585 self_suspend_(false),
Ian Rogers33e95662013-05-20 20:29:14 -07002586 other_suspend_(false) {
Jeff Hao449db332013-04-12 18:30:52 -07002587 ScopedObjectAccessUnchecked soa(self);
2588 {
2589 MutexLock mu(soa.Self(), *Locks::thread_list_lock_);
2590 error_ = DecodeThread(soa, thread_id, thread_);
2591 }
2592 if (error_ == JDWP::ERR_NONE) {
2593 if (thread_ == soa.Self()) {
2594 self_suspend_ = true;
2595 } else {
2596 soa.Self()->TransitionFromRunnableToSuspended(kWaitingForDebuggerSuspension);
2597 jobject thread_peer = gRegistry->GetJObject(thread_id);
2598 bool timed_out;
Ian Rogersd9c4fc92013-10-01 19:45:43 -07002599 Thread* suspended_thread = ThreadList::SuspendThreadByPeer(thread_peer, true, true,
2600 &timed_out);
Jeff Hao449db332013-04-12 18:30:52 -07002601 CHECK_EQ(soa.Self()->TransitionFromSuspendedToRunnable(), kWaitingForDebuggerSuspension);
2602 if (suspended_thread == NULL) {
2603 // Thread terminated from under us while suspending.
2604 error_ = JDWP::ERR_INVALID_THREAD;
2605 } else {
2606 CHECK_EQ(suspended_thread, thread_);
2607 other_suspend_ = true;
2608 }
2609 }
2610 }
Elliott Hughes2435a572012-02-17 16:07:41 -08002611 }
Elliott Hughes86964332012-02-15 19:37:42 -08002612
Jeff Hao449db332013-04-12 18:30:52 -07002613 Thread* GetThread() const {
2614 return thread_;
2615 }
2616
2617 JDWP::JdwpError GetError() const {
2618 return error_;
2619 }
2620
2621 ~ScopedThreadSuspension() {
2622 if (other_suspend_) {
2623 Runtime::Current()->GetThreadList()->Resume(thread_, true);
2624 }
2625 }
2626
2627 private:
2628 Thread* thread_;
2629 JDWP::JdwpError error_;
2630 bool self_suspend_;
2631 bool other_suspend_;
2632};
2633
2634JDWP::JdwpError Dbg::ConfigureStep(JDWP::ObjectId thread_id, JDWP::JdwpStepSize step_size,
2635 JDWP::JdwpStepDepth step_depth) {
2636 Thread* self = Thread::Current();
2637 ScopedThreadSuspension sts(self, thread_id);
2638 if (sts.GetError() != JDWP::ERR_NONE) {
2639 return sts.GetError();
2640 }
2641
Elliott Hughes2435a572012-02-17 16:07:41 -08002642 //
2643 // Work out what Method* we're in, the current line number, and how deep the stack currently
2644 // is for step-out.
2645 //
2646
Ian Rogers0399dde2012-06-06 17:09:28 -07002647 struct SingleStepStackVisitor : public StackVisitor {
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01002648 explicit SingleStepStackVisitor(Thread* thread, SingleStepControl* single_step_control,
2649 int32_t* line_number)
Ian Rogersb726dcb2012-09-05 08:57:23 -07002650 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_)
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01002651 : StackVisitor(thread, NULL), single_step_control_(single_step_control),
2652 line_number_(line_number) {
2653 DCHECK_EQ(single_step_control_, thread->GetSingleStepControl());
2654 single_step_control_->method = NULL;
2655 single_step_control_->stack_depth = 0;
Elliott Hughes86964332012-02-15 19:37:42 -08002656 }
Ian Rogersca190662012-06-26 15:45:57 -07002657
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002658 // TODO: Enable annotalysis. We know lock is held in constructor, but abstraction confuses
2659 // annotalysis.
2660 bool VisitFrame() NO_THREAD_SAFETY_ANALYSIS {
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01002661 mirror::ArtMethod* m = GetMethod();
Ian Rogers0399dde2012-06-06 17:09:28 -07002662 if (!m->IsRuntimeMethod()) {
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01002663 ++single_step_control_->stack_depth;
2664 if (single_step_control_->method == NULL) {
Ian Rogersef7d42f2014-01-06 12:55:46 -08002665 mirror::DexCache* dex_cache = m->GetDeclaringClass()->GetDexCache();
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01002666 single_step_control_->method = m;
2667 *line_number_ = -1;
Elliott Hughes2435a572012-02-17 16:07:41 -08002668 if (dex_cache != NULL) {
Ian Rogers4445a7e2012-10-05 17:19:13 -07002669 const DexFile& dex_file = *dex_cache->GetDexFile();
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01002670 *line_number_ = dex_file.GetLineNumFromPC(m, GetDexPc());
Elliott Hughes2435a572012-02-17 16:07:41 -08002671 }
Elliott Hughes86964332012-02-15 19:37:42 -08002672 }
2673 }
Elliott Hughes530fa002012-03-12 11:44:49 -07002674 return true;
Elliott Hughes86964332012-02-15 19:37:42 -08002675 }
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01002676
2677 SingleStepControl* const single_step_control_;
2678 int32_t* const line_number_;
Elliott Hughes86964332012-02-15 19:37:42 -08002679 };
Jeff Hao449db332013-04-12 18:30:52 -07002680
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01002681 Thread* const thread = sts.GetThread();
2682 SingleStepControl* const single_step_control = thread->GetSingleStepControl();
2683 DCHECK(single_step_control != nullptr);
2684 int32_t line_number = -1;
2685 SingleStepStackVisitor visitor(thread, single_step_control, &line_number);
Ian Rogers0399dde2012-06-06 17:09:28 -07002686 visitor.WalkStack();
Elliott Hughes86964332012-02-15 19:37:42 -08002687
Elliott Hughes2435a572012-02-17 16:07:41 -08002688 //
2689 // Find the dex_pc values that correspond to the current line, for line-based single-stepping.
2690 //
2691
2692 struct DebugCallbackContext {
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01002693 explicit DebugCallbackContext(SingleStepControl* single_step_control, int32_t line_number)
2694 : single_step_control_(single_step_control), line_number_(line_number),
2695 last_pc_valid(false), last_pc(0) {
Elliott Hughes2435a572012-02-17 16:07:41 -08002696 }
2697
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01002698 static bool Callback(void* raw_context, uint32_t address, uint32_t line_number) {
Elliott Hughes2435a572012-02-17 16:07:41 -08002699 DebugCallbackContext* context = reinterpret_cast<DebugCallbackContext*>(raw_context);
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01002700 if (static_cast<int32_t>(line_number) == context->line_number_) {
Elliott Hughes2435a572012-02-17 16:07:41 -08002701 if (!context->last_pc_valid) {
2702 // Everything from this address until the next line change is ours.
2703 context->last_pc = address;
2704 context->last_pc_valid = true;
2705 }
2706 // Otherwise, if we're already in a valid range for this line,
2707 // just keep going (shouldn't really happen)...
Brian Carlstrom7934ac22013-07-26 10:54:15 -07002708 } else if (context->last_pc_valid) { // and the line number is new
Elliott Hughes2435a572012-02-17 16:07:41 -08002709 // Add everything from the last entry up until here to the set
2710 for (uint32_t dex_pc = context->last_pc; dex_pc < address; ++dex_pc) {
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01002711 context->single_step_control_->dex_pcs.insert(dex_pc);
Elliott Hughes2435a572012-02-17 16:07:41 -08002712 }
2713 context->last_pc_valid = false;
2714 }
Brian Carlstrom7934ac22013-07-26 10:54:15 -07002715 return false; // There may be multiple entries for any given line.
Elliott Hughes2435a572012-02-17 16:07:41 -08002716 }
2717
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01002718 ~DebugCallbackContext() {
Elliott Hughes2435a572012-02-17 16:07:41 -08002719 // If the line number was the last in the position table...
2720 if (last_pc_valid) {
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01002721 size_t end = MethodHelper(single_step_control_->method).GetCodeItem()->insns_size_in_code_units_;
Elliott Hughes2435a572012-02-17 16:07:41 -08002722 for (uint32_t dex_pc = last_pc; dex_pc < end; ++dex_pc) {
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01002723 single_step_control_->dex_pcs.insert(dex_pc);
Elliott Hughes2435a572012-02-17 16:07:41 -08002724 }
2725 }
2726 }
2727
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01002728 SingleStepControl* const single_step_control_;
2729 const int32_t line_number_;
Elliott Hughes2435a572012-02-17 16:07:41 -08002730 bool last_pc_valid;
2731 uint32_t last_pc;
2732 };
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01002733 single_step_control->dex_pcs.clear();
Ian Rogersef7d42f2014-01-06 12:55:46 -08002734 mirror::ArtMethod* m = single_step_control->method;
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01002735 if (!m->IsNative()) {
2736 DebugCallbackContext context(single_step_control, line_number);
Elliott Hughes3e2e1a22012-02-21 11:33:41 -08002737 MethodHelper mh(m);
2738 mh.GetDexFile().DecodeDebugInfo(mh.GetCodeItem(), m->IsStatic(), m->GetDexMethodIndex(),
2739 DebugCallbackContext::Callback, NULL, &context);
2740 }
Elliott Hughes2435a572012-02-17 16:07:41 -08002741
2742 //
2743 // Everything else...
2744 //
2745
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01002746 single_step_control->step_size = step_size;
2747 single_step_control->step_depth = step_depth;
2748 single_step_control->is_active = true;
Elliott Hughes86964332012-02-15 19:37:42 -08002749
Elliott Hughes2435a572012-02-17 16:07:41 -08002750 if (VLOG_IS_ON(jdwp)) {
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01002751 VLOG(jdwp) << "Single-step thread: " << *thread;
2752 VLOG(jdwp) << "Single-step step size: " << single_step_control->step_size;
2753 VLOG(jdwp) << "Single-step step depth: " << single_step_control->step_depth;
2754 VLOG(jdwp) << "Single-step current method: " << PrettyMethod(single_step_control->method);
2755 VLOG(jdwp) << "Single-step current line: " << line_number;
2756 VLOG(jdwp) << "Single-step current stack depth: " << single_step_control->stack_depth;
Elliott Hughes2435a572012-02-17 16:07:41 -08002757 VLOG(jdwp) << "Single-step dex_pc values:";
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01002758 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 -08002759 VLOG(jdwp) << StringPrintf(" %#x", *it);
Elliott Hughes2435a572012-02-17 16:07:41 -08002760 }
2761 }
2762
2763 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002764}
2765
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01002766void Dbg::UnconfigureStep(JDWP::ObjectId thread_id) {
2767 ScopedObjectAccessUnchecked soa(Thread::Current());
2768 MutexLock mu(soa.Self(), *Locks::thread_list_lock_);
2769 Thread* thread;
2770 JDWP::JdwpError error = DecodeThread(soa, thread_id, thread);
Sebastien Hertz87118ed2013-11-26 17:57:18 +01002771 if (error == JDWP::ERR_NONE) {
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01002772 SingleStepControl* single_step_control = thread->GetSingleStepControl();
2773 DCHECK(single_step_control != nullptr);
2774 single_step_control->is_active = false;
2775 single_step_control->dex_pcs.clear();
2776 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002777}
2778
Elliott Hughes45651fd2012-02-21 15:48:20 -08002779static char JdwpTagToShortyChar(JDWP::JdwpTag tag) {
2780 switch (tag) {
2781 default:
2782 LOG(FATAL) << "unknown JDWP tag: " << PrintableChar(tag);
2783
2784 // Primitives.
2785 case JDWP::JT_BYTE: return 'B';
2786 case JDWP::JT_CHAR: return 'C';
2787 case JDWP::JT_FLOAT: return 'F';
2788 case JDWP::JT_DOUBLE: return 'D';
2789 case JDWP::JT_INT: return 'I';
2790 case JDWP::JT_LONG: return 'J';
2791 case JDWP::JT_SHORT: return 'S';
2792 case JDWP::JT_VOID: return 'V';
2793 case JDWP::JT_BOOLEAN: return 'Z';
2794
2795 // Reference types.
2796 case JDWP::JT_ARRAY:
2797 case JDWP::JT_OBJECT:
2798 case JDWP::JT_STRING:
2799 case JDWP::JT_THREAD:
2800 case JDWP::JT_THREAD_GROUP:
2801 case JDWP::JT_CLASS_LOADER:
2802 case JDWP::JT_CLASS_OBJECT:
2803 return 'L';
2804 }
2805}
2806
Elliott Hughes88d63092013-01-09 09:55:54 -08002807JDWP::JdwpError Dbg::InvokeMethod(JDWP::ObjectId thread_id, JDWP::ObjectId object_id,
2808 JDWP::RefTypeId class_id, JDWP::MethodId method_id,
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002809 uint32_t arg_count, uint64_t* arg_values,
2810 JDWP::JdwpTag* arg_types, uint32_t options,
2811 JDWP::JdwpTag* pResultTag, uint64_t* pResultValue,
2812 JDWP::ObjectId* pExceptionId) {
Elliott Hughesd07986f2011-12-06 18:27:45 -08002813 ThreadList* thread_list = Runtime::Current()->GetThreadList();
2814
2815 Thread* targetThread = NULL;
2816 DebugInvokeReq* req = NULL;
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002817 Thread* self = Thread::Current();
Elliott Hughesd07986f2011-12-06 18:27:45 -08002818 {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002819 ScopedObjectAccessUnchecked soa(self);
Ian Rogers50b35e22012-10-04 10:09:15 -07002820 MutexLock mu(soa.Self(), *Locks::thread_list_lock_);
Elliott Hughes221229c2013-01-08 18:17:50 -08002821 JDWP::JdwpError error = DecodeThread(soa, thread_id, targetThread);
2822 if (error != JDWP::ERR_NONE) {
2823 LOG(ERROR) << "InvokeMethod request for invalid thread id " << thread_id;
2824 return error;
Elliott Hughesd07986f2011-12-06 18:27:45 -08002825 }
2826 req = targetThread->GetInvokeReq();
2827 if (!req->ready) {
2828 LOG(ERROR) << "InvokeMethod request for thread not stopped by event: " << *targetThread;
2829 return JDWP::ERR_INVALID_THREAD;
2830 }
2831
2832 /*
2833 * We currently have a bug where we don't successfully resume the
2834 * target thread if the suspend count is too deep. We're expected to
2835 * require one "resume" for each "suspend", but when asked to execute
2836 * a method we have to resume fully and then re-suspend it back to the
2837 * same level. (The easiest way to cause this is to type "suspend"
2838 * multiple times in jdb.)
2839 *
2840 * It's unclear what this means when the event specifies "resume all"
2841 * and some threads are suspended more deeply than others. This is
2842 * a rare problem, so for now we just prevent it from hanging forever
2843 * by rejecting the method invocation request. Without this, we will
2844 * be stuck waiting on a suspended thread.
2845 */
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002846 int suspend_count;
2847 {
Ian Rogers50b35e22012-10-04 10:09:15 -07002848 MutexLock mu2(soa.Self(), *Locks::thread_suspend_count_lock_);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002849 suspend_count = targetThread->GetSuspendCount();
2850 }
Elliott Hughesd07986f2011-12-06 18:27:45 -08002851 if (suspend_count > 1) {
2852 LOG(ERROR) << *targetThread << " suspend count too deep for method invocation: " << suspend_count;
Brian Carlstrom7934ac22013-07-26 10:54:15 -07002853 return JDWP::ERR_THREAD_SUSPENDED; // Probably not expected here.
Elliott Hughesd07986f2011-12-06 18:27:45 -08002854 }
2855
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08002856 JDWP::JdwpError status;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002857 mirror::Object* receiver = gRegistry->Get<mirror::Object*>(object_id);
Elliott Hughes64f574f2013-02-20 14:57:12 -08002858 if (receiver == ObjectRegistry::kInvalidObject) {
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08002859 return JDWP::ERR_INVALID_OBJECT;
2860 }
Elliott Hughes45651fd2012-02-21 15:48:20 -08002861
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002862 mirror::Object* thread = gRegistry->Get<mirror::Object*>(thread_id);
Elliott Hughes64f574f2013-02-20 14:57:12 -08002863 if (thread == ObjectRegistry::kInvalidObject) {
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08002864 return JDWP::ERR_INVALID_OBJECT;
2865 }
Elliott Hughes45651fd2012-02-21 15:48:20 -08002866 // TODO: check that 'thread' is actually a java.lang.Thread!
2867
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002868 mirror::Class* c = DecodeClass(class_id, status);
Elliott Hughes45651fd2012-02-21 15:48:20 -08002869 if (c == NULL) {
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08002870 return status;
2871 }
Elliott Hughes45651fd2012-02-21 15:48:20 -08002872
Brian Carlstromea46f952013-07-30 01:26:50 -07002873 mirror::ArtMethod* m = FromMethodId(method_id);
Elliott Hughes45651fd2012-02-21 15:48:20 -08002874 if (m->IsStatic() != (receiver == NULL)) {
2875 return JDWP::ERR_INVALID_METHODID;
2876 }
2877 if (m->IsStatic()) {
2878 if (m->GetDeclaringClass() != c) {
2879 return JDWP::ERR_INVALID_METHODID;
2880 }
2881 } else {
2882 if (!m->GetDeclaringClass()->IsAssignableFrom(c)) {
2883 return JDWP::ERR_INVALID_METHODID;
2884 }
2885 }
2886
2887 // Check the argument list matches the method.
2888 MethodHelper mh(m);
2889 if (mh.GetShortyLength() - 1 != arg_count) {
2890 return JDWP::ERR_ILLEGAL_ARGUMENT;
2891 }
2892 const char* shorty = mh.GetShorty();
Elliott Hughes09201632013-04-15 15:50:07 -07002893 const DexFile::TypeList* types = mh.GetParameterTypeList();
Elliott Hughes45651fd2012-02-21 15:48:20 -08002894 for (size_t i = 0; i < arg_count; ++i) {
2895 if (shorty[i + 1] != JdwpTagToShortyChar(arg_types[i])) {
2896 return JDWP::ERR_ILLEGAL_ARGUMENT;
2897 }
Elliott Hughes09201632013-04-15 15:50:07 -07002898
2899 if (shorty[i + 1] == 'L') {
2900 // Did we really get an argument of an appropriate reference type?
2901 mirror::Class* parameter_type = mh.GetClassFromTypeIdx(types->GetTypeItem(i).type_idx_);
2902 mirror::Object* argument = gRegistry->Get<mirror::Object*>(arg_values[i]);
2903 if (argument == ObjectRegistry::kInvalidObject) {
2904 return JDWP::ERR_INVALID_OBJECT;
2905 }
Sebastien Hertz0630ab52013-11-28 18:53:35 +01002906 if (argument != NULL && !argument->InstanceOf(parameter_type)) {
Elliott Hughes09201632013-04-15 15:50:07 -07002907 return JDWP::ERR_ILLEGAL_ARGUMENT;
2908 }
2909
2910 // Turn the on-the-wire ObjectId into a jobject.
2911 jvalue& v = reinterpret_cast<jvalue&>(arg_values[i]);
2912 v.l = gRegistry->GetJObject(arg_values[i]);
2913 }
Elliott Hughes45651fd2012-02-21 15:48:20 -08002914 }
2915
Sebastien Hertzd38667a2013-11-25 15:43:54 +01002916 req->receiver = receiver;
2917 req->thread = thread;
2918 req->klass = c;
2919 req->method = m;
2920 req->arg_count = arg_count;
2921 req->arg_values = arg_values;
2922 req->options = options;
2923 req->invoke_needed = true;
Elliott Hughesd07986f2011-12-06 18:27:45 -08002924 }
2925
2926 // The fact that we've released the thread list lock is a bit risky --- if the thread goes
2927 // away we're sitting high and dry -- but we must release this before the ResumeAllThreads
2928 // call, and it's unwise to hold it during WaitForSuspend.
2929
2930 {
2931 /*
2932 * We change our (JDWP thread) status, which should be THREAD_RUNNING,
Elliott Hughes81ff3182012-03-23 20:35:56 -07002933 * so we can suspend for a GC if the invoke request causes us to
Elliott Hughesd07986f2011-12-06 18:27:45 -08002934 * run out of memory. It's also a good idea to change it before locking
2935 * the invokeReq mutex, although that should never be held for long.
2936 */
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002937 self->TransitionFromRunnableToSuspended(kWaitingForDebuggerSend);
Elliott Hughesd07986f2011-12-06 18:27:45 -08002938
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08002939 VLOG(jdwp) << " Transferring control to event thread";
Elliott Hughesd07986f2011-12-06 18:27:45 -08002940 {
Sebastien Hertzd38667a2013-11-25 15:43:54 +01002941 MutexLock mu(self, req->lock);
Elliott Hughesd07986f2011-12-06 18:27:45 -08002942
2943 if ((options & JDWP::INVOKE_SINGLE_THREADED) == 0) {
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08002944 VLOG(jdwp) << " Resuming all threads";
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002945 thread_list->UndoDebuggerSuspensions();
Elliott Hughesd07986f2011-12-06 18:27:45 -08002946 } else {
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08002947 VLOG(jdwp) << " Resuming event thread only";
Elliott Hughesd07986f2011-12-06 18:27:45 -08002948 thread_list->Resume(targetThread, true);
2949 }
2950
2951 // Wait for the request to finish executing.
Sebastien Hertzd38667a2013-11-25 15:43:54 +01002952 while (req->invoke_needed) {
2953 req->cond.Wait(self);
Elliott Hughesd07986f2011-12-06 18:27:45 -08002954 }
2955 }
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08002956 VLOG(jdwp) << " Control has returned from event thread";
Elliott Hughesd07986f2011-12-06 18:27:45 -08002957
2958 /* wait for thread to re-suspend itself */
Brian Carlstromdf629502013-07-17 22:39:56 -07002959 SuspendThread(thread_id, false /* request_suspension */);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002960 self->TransitionFromSuspendedToRunnable();
Elliott Hughesd07986f2011-12-06 18:27:45 -08002961 }
2962
2963 /*
2964 * Suspend the threads. We waited for the target thread to suspend
2965 * itself, so all we need to do is suspend the others.
2966 *
2967 * The suspendAllThreads() call will double-suspend the event thread,
2968 * so we want to resume the target thread once to keep the books straight.
2969 */
2970 if ((options & JDWP::INVOKE_SINGLE_THREADED) == 0) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002971 self->TransitionFromRunnableToSuspended(kWaitingForDebuggerSuspension);
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08002972 VLOG(jdwp) << " Suspending all threads";
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002973 thread_list->SuspendAllForDebugger();
2974 self->TransitionFromSuspendedToRunnable();
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08002975 VLOG(jdwp) << " Resuming event thread to balance the count";
Elliott Hughesd07986f2011-12-06 18:27:45 -08002976 thread_list->Resume(targetThread, true);
2977 }
2978
2979 // Copy the result.
2980 *pResultTag = req->result_tag;
2981 if (IsPrimitiveTag(req->result_tag)) {
Elliott Hughesf24d3ce2012-04-11 17:43:37 -07002982 *pResultValue = req->result_value.GetJ();
Elliott Hughesd07986f2011-12-06 18:27:45 -08002983 } else {
Elliott Hughesf24d3ce2012-04-11 17:43:37 -07002984 *pResultValue = gRegistry->Add(req->result_value.GetL());
Elliott Hughesd07986f2011-12-06 18:27:45 -08002985 }
2986 *pExceptionId = req->exception;
2987 return req->error;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002988}
2989
2990void Dbg::ExecuteMethod(DebugInvokeReq* pReq) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002991 ScopedObjectAccess soa(Thread::Current());
Elliott Hughesd07986f2011-12-06 18:27:45 -08002992
Elliott Hughes81ff3182012-03-23 20:35:56 -07002993 // We can be called while an exception is pending. We need
Elliott Hughesd07986f2011-12-06 18:27:45 -08002994 // to preserve that across the method invocation.
Ian Rogers62d6c772013-02-27 08:32:07 -08002995 SirtRef<mirror::Object> old_throw_this_object(soa.Self(), NULL);
Brian Carlstromea46f952013-07-30 01:26:50 -07002996 SirtRef<mirror::ArtMethod> old_throw_method(soa.Self(), NULL);
Ian Rogers62d6c772013-02-27 08:32:07 -08002997 SirtRef<mirror::Throwable> old_exception(soa.Self(), NULL);
2998 uint32_t old_throw_dex_pc;
2999 {
3000 ThrowLocation old_throw_location;
3001 mirror::Throwable* old_exception_obj = soa.Self()->GetException(&old_throw_location);
3002 old_throw_this_object.reset(old_throw_location.GetThis());
3003 old_throw_method.reset(old_throw_location.GetMethod());
3004 old_exception.reset(old_exception_obj);
3005 old_throw_dex_pc = old_throw_location.GetDexPc();
3006 soa.Self()->ClearException();
3007 }
Elliott Hughesd07986f2011-12-06 18:27:45 -08003008
3009 // Translate the method through the vtable, unless the debugger wants to suppress it.
Mathieu Chartierc528dba2013-11-26 12:00:11 -08003010 SirtRef<mirror::ArtMethod> m(soa.Self(), pReq->method);
Sebastien Hertzd38667a2013-11-25 15:43:54 +01003011 if ((pReq->options & JDWP::INVOKE_NONVIRTUAL) == 0 && pReq->receiver != NULL) {
3012 mirror::ArtMethod* actual_method = pReq->klass->FindVirtualMethodForVirtualOrInterface(pReq->method);
Mathieu Chartierc528dba2013-11-26 12:00:11 -08003013 if (actual_method != m.get()) {
3014 VLOG(jdwp) << "ExecuteMethod translated " << PrettyMethod(m.get()) << " to " << PrettyMethod(actual_method);
3015 m.reset(actual_method);
Elliott Hughes45651fd2012-02-21 15:48:20 -08003016 }
Elliott Hughesd07986f2011-12-06 18:27:45 -08003017 }
Mathieu Chartierc528dba2013-11-26 12:00:11 -08003018 VLOG(jdwp) << "ExecuteMethod " << PrettyMethod(m.get())
Sebastien Hertzd38667a2013-11-25 15:43:54 +01003019 << " receiver=" << pReq->receiver
3020 << " arg_count=" << pReq->arg_count;
Mathieu Chartierc528dba2013-11-26 12:00:11 -08003021 CHECK(m.get() != nullptr);
Elliott Hughesd07986f2011-12-06 18:27:45 -08003022
3023 CHECK_EQ(sizeof(jvalue), sizeof(uint64_t));
3024
Mathieu Chartierc528dba2013-11-26 12:00:11 -08003025 MethodHelper mh(m.get());
Jeff Hao5d917302013-02-27 17:57:33 -08003026 ArgArray arg_array(mh.GetShorty(), mh.GetShortyLength());
Sebastien Hertzd38667a2013-11-25 15:43:54 +01003027 arg_array.BuildArgArray(soa, pReq->receiver, reinterpret_cast<jvalue*>(pReq->arg_values));
Ian Rogers0177e532014-02-11 16:30:46 -08003028 InvokeWithArgArray(soa, m.get(), &arg_array, &pReq->result_value, mh.GetShorty());
Elliott Hughesd07986f2011-12-06 18:27:45 -08003029
Ian Rogers62d6c772013-02-27 08:32:07 -08003030 mirror::Throwable* exception = soa.Self()->GetException(NULL);
3031 soa.Self()->ClearException();
3032 pReq->exception = gRegistry->Add(exception);
Mathieu Chartierc528dba2013-11-26 12:00:11 -08003033 pReq->result_tag = BasicTagFromDescriptor(MethodHelper(m.get()).GetShorty());
Elliott Hughesd07986f2011-12-06 18:27:45 -08003034 if (pReq->exception != 0) {
Ian Rogers62d6c772013-02-27 08:32:07 -08003035 VLOG(jdwp) << " JDWP invocation returning with exception=" << exception
3036 << " " << exception->Dump();
Elliott Hughesf24d3ce2012-04-11 17:43:37 -07003037 pReq->result_value.SetJ(0);
Elliott Hughesd07986f2011-12-06 18:27:45 -08003038 } else if (pReq->result_tag == JDWP::JT_OBJECT) {
3039 /* if no exception thrown, examine object result more closely */
Elliott Hughesf24d3ce2012-04-11 17:43:37 -07003040 JDWP::JdwpTag new_tag = TagFromObject(pReq->result_value.GetL());
Elliott Hughesd07986f2011-12-06 18:27:45 -08003041 if (new_tag != pReq->result_tag) {
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08003042 VLOG(jdwp) << " JDWP promoted result from " << pReq->result_tag << " to " << new_tag;
Elliott Hughesd07986f2011-12-06 18:27:45 -08003043 pReq->result_tag = new_tag;
3044 }
3045
3046 /*
3047 * Register the object. We don't actually need an ObjectId yet,
3048 * but we do need to be sure that the GC won't move or discard the
3049 * object when we switch out of RUNNING. The ObjectId conversion
3050 * will add the object to the "do not touch" list.
3051 *
3052 * We can't use the "tracked allocation" mechanism here because
3053 * the object is going to be handed off to a different thread.
3054 */
Elliott Hughesf24d3ce2012-04-11 17:43:37 -07003055 gRegistry->Add(pReq->result_value.GetL());
Elliott Hughesd07986f2011-12-06 18:27:45 -08003056 }
3057
3058 if (old_exception.get() != NULL) {
Ian Rogers62d6c772013-02-27 08:32:07 -08003059 ThrowLocation gc_safe_throw_location(old_throw_this_object.get(), old_throw_method.get(),
3060 old_throw_dex_pc);
3061 soa.Self()->SetException(gc_safe_throw_location, old_exception.get());
Elliott Hughesd07986f2011-12-06 18:27:45 -08003062 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -07003063}
3064
Elliott Hughesd07986f2011-12-06 18:27:45 -08003065/*
Elliott Hughes4b9702c2013-02-20 18:13:24 -08003066 * "request" contains a full JDWP packet, possibly with multiple chunks. We
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07003067 * need to process each, accumulate the replies, and ship the whole thing
3068 * back.
3069 *
3070 * Returns "true" if we have a reply. The reply buffer is newly allocated,
3071 * and includes the chunk type/length, followed by the data.
3072 *
Elliott Hughes3d30d9b2011-12-07 17:35:48 -08003073 * OLD-TODO: we currently assume that the request and reply include a single
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07003074 * chunk. If this becomes inconvenient we will need to adapt.
3075 */
Elliott Hughes4b9702c2013-02-20 18:13:24 -08003076bool Dbg::DdmHandlePacket(JDWP::Request& request, uint8_t** pReplyBuf, int* pReplyLen) {
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07003077 Thread* self = Thread::Current();
3078 JNIEnv* env = self->GetJniEnv();
3079
Elliott Hughes4b9702c2013-02-20 18:13:24 -08003080 uint32_t type = request.ReadUnsigned32("type");
3081 uint32_t length = request.ReadUnsigned32("length");
3082
3083 // Create a byte[] corresponding to 'request'.
3084 size_t request_length = request.size();
3085 ScopedLocalRef<jbyteArray> dataArray(env, env->NewByteArray(request_length));
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003086 if (dataArray.get() == NULL) {
Elliott Hughes4b9702c2013-02-20 18:13:24 -08003087 LOG(WARNING) << "byte[] allocation failed: " << request_length;
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07003088 env->ExceptionClear();
3089 return false;
3090 }
Elliott Hughes4b9702c2013-02-20 18:13:24 -08003091 env->SetByteArrayRegion(dataArray.get(), 0, request_length, reinterpret_cast<const jbyte*>(request.data()));
3092 request.Skip(request_length);
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07003093
3094 // Run through and find all chunks. [Currently just find the first.]
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003095 ScopedByteArrayRO contents(env, dataArray.get());
Elliott Hughes4b9702c2013-02-20 18:13:24 -08003096 if (length != request_length) {
Ian Rogersef7d42f2014-01-06 12:55:46 -08003097 LOG(WARNING) << StringPrintf("bad chunk found (len=%u pktLen=%zd)", length, request_length);
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07003098 return false;
3099 }
3100
3101 // Call "private static Chunk dispatch(int type, byte[] data, int offset, int length)".
Elliott Hugheseac76672012-05-24 21:56:51 -07003102 ScopedLocalRef<jobject> chunk(env, env->CallStaticObjectMethod(WellKnownClasses::org_apache_harmony_dalvik_ddmc_DdmServer,
3103 WellKnownClasses::org_apache_harmony_dalvik_ddmc_DdmServer_dispatch,
Elliott Hughes4b9702c2013-02-20 18:13:24 -08003104 type, dataArray.get(), 0, length));
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07003105 if (env->ExceptionCheck()) {
3106 LOG(INFO) << StringPrintf("Exception thrown by dispatcher for 0x%08x", type);
3107 env->ExceptionDescribe();
3108 env->ExceptionClear();
3109 return false;
3110 }
3111
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003112 if (chunk.get() == NULL) {
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07003113 return false;
3114 }
3115
3116 /*
3117 * Pull the pieces out of the chunk. We copy the results into a
3118 * newly-allocated buffer that the caller can free. We don't want to
3119 * continue using the Chunk object because nothing has a reference to it.
3120 *
3121 * We could avoid this by returning type/data/offset/length and having
3122 * the caller be aware of the object lifetime issues, but that
Elliott Hughes81ff3182012-03-23 20:35:56 -07003123 * integrates the JDWP code more tightly into the rest of the runtime, and doesn't work
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07003124 * if we have responses for multiple chunks.
3125 *
3126 * So we're pretty much stuck with copying data around multiple times.
3127 */
Elliott Hugheseac76672012-05-24 21:56:51 -07003128 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 -08003129 jint offset = env->GetIntField(chunk.get(), WellKnownClasses::org_apache_harmony_dalvik_ddmc_Chunk_offset);
Elliott Hugheseac76672012-05-24 21:56:51 -07003130 length = env->GetIntField(chunk.get(), WellKnownClasses::org_apache_harmony_dalvik_ddmc_Chunk_length);
Elliott Hugheseac76672012-05-24 21:56:51 -07003131 type = env->GetIntField(chunk.get(), WellKnownClasses::org_apache_harmony_dalvik_ddmc_Chunk_type);
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07003132
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08003133 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 -07003134 if (length == 0 || replyData.get() == NULL) {
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07003135 return false;
3136 }
3137
Elliott Hughes4b9702c2013-02-20 18:13:24 -08003138 const int kChunkHdrLen = 8;
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07003139 uint8_t* reply = new uint8_t[length + kChunkHdrLen];
3140 if (reply == NULL) {
3141 LOG(WARNING) << "malloc failed: " << (length + kChunkHdrLen);
3142 return false;
3143 }
Elliott Hughesf7c3b662011-10-27 12:04:56 -07003144 JDWP::Set4BE(reply + 0, type);
3145 JDWP::Set4BE(reply + 4, length);
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003146 env->GetByteArrayRegion(replyData.get(), offset, length, reinterpret_cast<jbyte*>(reply + kChunkHdrLen));
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07003147
3148 *pReplyBuf = reply;
3149 *pReplyLen = length + kChunkHdrLen;
3150
Elliott Hughes4b9702c2013-02-20 18:13:24 -08003151 VLOG(jdwp) << StringPrintf("dvmHandleDdm returning type=%.4s %p len=%d", reinterpret_cast<char*>(reply), reply, length);
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07003152 return true;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07003153}
3154
Elliott Hughesa2155262011-11-16 16:26:58 -08003155void Dbg::DdmBroadcast(bool connect) {
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08003156 VLOG(jdwp) << "Broadcasting DDM " << (connect ? "connect" : "disconnect") << "...";
Elliott Hughes47fce012011-10-25 18:37:19 -07003157
3158 Thread* self = Thread::Current();
Ian Rogers50b35e22012-10-04 10:09:15 -07003159 if (self->GetState() != kRunnable) {
3160 LOG(ERROR) << "DDM broadcast in thread state " << self->GetState();
3161 /* try anyway? */
Elliott Hughes47fce012011-10-25 18:37:19 -07003162 }
3163
3164 JNIEnv* env = self->GetJniEnv();
Elliott Hughes47fce012011-10-25 18:37:19 -07003165 jint event = connect ? 1 /*DdmServer.CONNECTED*/ : 2 /*DdmServer.DISCONNECTED*/;
Elliott Hugheseac76672012-05-24 21:56:51 -07003166 env->CallStaticVoidMethod(WellKnownClasses::org_apache_harmony_dalvik_ddmc_DdmServer,
3167 WellKnownClasses::org_apache_harmony_dalvik_ddmc_DdmServer_broadcast,
3168 event);
Elliott Hughes47fce012011-10-25 18:37:19 -07003169 if (env->ExceptionCheck()) {
3170 LOG(ERROR) << "DdmServer.broadcast " << event << " failed";
3171 env->ExceptionDescribe();
3172 env->ExceptionClear();
3173 }
3174}
3175
Elliott Hughes872d4ec2011-10-21 17:07:15 -07003176void Dbg::DdmConnected() {
Elliott Hughesa2155262011-11-16 16:26:58 -08003177 Dbg::DdmBroadcast(true);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07003178}
3179
3180void Dbg::DdmDisconnected() {
Elliott Hughesa2155262011-11-16 16:26:58 -08003181 Dbg::DdmBroadcast(false);
Elliott Hughes47fce012011-10-25 18:37:19 -07003182 gDdmThreadNotification = false;
3183}
3184
3185/*
Elliott Hughes82188472011-11-07 18:11:48 -08003186 * Send a notification when a thread starts, stops, or changes its name.
Elliott Hughes47fce012011-10-25 18:37:19 -07003187 *
3188 * Because we broadcast the full set of threads when the notifications are
3189 * first enabled, it's possible for "thread" to be actively executing.
3190 */
Elliott Hughes82188472011-11-07 18:11:48 -08003191void Dbg::DdmSendThreadNotification(Thread* t, uint32_t type) {
Elliott Hughes47fce012011-10-25 18:37:19 -07003192 if (!gDdmThreadNotification) {
3193 return;
3194 }
3195
Elliott Hughes82188472011-11-07 18:11:48 -08003196 if (type == CHUNK_TYPE("THDE")) {
Elliott Hughes47fce012011-10-25 18:37:19 -07003197 uint8_t buf[4];
Ian Rogersd9c4fc92013-10-01 19:45:43 -07003198 JDWP::Set4BE(&buf[0], t->GetThreadId());
Elliott Hughes47fce012011-10-25 18:37:19 -07003199 Dbg::DdmSendChunk(CHUNK_TYPE("THDE"), 4, buf);
Elliott Hughes82188472011-11-07 18:11:48 -08003200 } else {
3201 CHECK(type == CHUNK_TYPE("THCR") || type == CHUNK_TYPE("THNM")) << type;
Ian Rogers00f7d0e2012-07-19 15:28:27 -07003202 ScopedObjectAccessUnchecked soa(Thread::Current());
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003203 SirtRef<mirror::String> name(soa.Self(), t->GetThreadName(soa));
Elliott Hughes82188472011-11-07 18:11:48 -08003204 size_t char_count = (name.get() != NULL) ? name->GetLength() : 0;
jeffhao725a9572012-11-13 18:20:12 -08003205 const jchar* chars = (name.get() != NULL) ? name->GetCharArray()->GetData() : NULL;
Elliott Hughes82188472011-11-07 18:11:48 -08003206
Elliott Hughes21f32d72011-11-09 17:44:13 -08003207 std::vector<uint8_t> bytes;
Ian Rogersd9c4fc92013-10-01 19:45:43 -07003208 JDWP::Append4BE(bytes, t->GetThreadId());
Elliott Hughes545a0642011-11-08 19:10:03 -08003209 JDWP::AppendUtf16BE(bytes, chars, char_count);
Elliott Hughes21f32d72011-11-09 17:44:13 -08003210 CHECK_EQ(bytes.size(), char_count*2 + sizeof(uint32_t)*2);
3211 Dbg::DdmSendChunk(type, bytes);
Elliott Hughes47fce012011-10-25 18:37:19 -07003212 }
3213}
3214
Elliott Hughes47fce012011-10-25 18:37:19 -07003215void Dbg::DdmSetThreadNotification(bool enable) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07003216 // Enable/disable thread notifications.
Elliott Hughes47fce012011-10-25 18:37:19 -07003217 gDdmThreadNotification = enable;
3218 if (enable) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07003219 // Suspend the VM then post thread start notifications for all threads. Threads attaching will
3220 // see a suspension in progress and block until that ends. They then post their own start
3221 // notification.
3222 SuspendVM();
3223 std::list<Thread*> threads;
Ian Rogers50b35e22012-10-04 10:09:15 -07003224 Thread* self = Thread::Current();
Ian Rogers00f7d0e2012-07-19 15:28:27 -07003225 {
Ian Rogers50b35e22012-10-04 10:09:15 -07003226 MutexLock mu(self, *Locks::thread_list_lock_);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07003227 threads = Runtime::Current()->GetThreadList()->GetList();
3228 }
3229 {
Ian Rogers50b35e22012-10-04 10:09:15 -07003230 ScopedObjectAccess soa(self);
Mathieu Chartier02e25112013-08-14 16:14:24 -07003231 for (Thread* thread : threads) {
3232 Dbg::DdmSendThreadNotification(thread, CHUNK_TYPE("THCR"));
Ian Rogers00f7d0e2012-07-19 15:28:27 -07003233 }
3234 }
3235 ResumeVM();
Elliott Hughes47fce012011-10-25 18:37:19 -07003236 }
3237}
3238
Elliott Hughesa2155262011-11-16 16:26:58 -08003239void Dbg::PostThreadStartOrStop(Thread* t, uint32_t type) {
Elliott Hughesc0f09332012-03-26 13:27:06 -07003240 if (IsDebuggerActive()) {
Mathieu Chartierdbe6f462012-09-25 16:54:50 -07003241 ScopedObjectAccessUnchecked soa(Thread::Current());
Ian Rogerscfaa4552012-11-26 21:00:08 -08003242 JDWP::ObjectId id = gRegistry->Add(t->GetPeer());
Elliott Hughes82188472011-11-07 18:11:48 -08003243 gJdwpState->PostThreadChange(id, type == CHUNK_TYPE("THCR"));
Elliott Hughes47fce012011-10-25 18:37:19 -07003244 }
Elliott Hughes82188472011-11-07 18:11:48 -08003245 Dbg::DdmSendThreadNotification(t, type);
Elliott Hughes47fce012011-10-25 18:37:19 -07003246}
3247
3248void Dbg::PostThreadStart(Thread* t) {
Elliott Hughesa2155262011-11-16 16:26:58 -08003249 Dbg::PostThreadStartOrStop(t, CHUNK_TYPE("THCR"));
Elliott Hughes47fce012011-10-25 18:37:19 -07003250}
3251
3252void Dbg::PostThreadDeath(Thread* t) {
Elliott Hughesa2155262011-11-16 16:26:58 -08003253 Dbg::PostThreadStartOrStop(t, CHUNK_TYPE("THDE"));
Elliott Hughes872d4ec2011-10-21 17:07:15 -07003254}
3255
Elliott Hughes82188472011-11-07 18:11:48 -08003256void Dbg::DdmSendChunk(uint32_t type, size_t byte_count, const uint8_t* buf) {
Elliott Hughes3bb81562011-10-21 18:52:59 -07003257 CHECK(buf != NULL);
3258 iovec vec[1];
3259 vec[0].iov_base = reinterpret_cast<void*>(const_cast<uint8_t*>(buf));
3260 vec[0].iov_len = byte_count;
3261 Dbg::DdmSendChunkV(type, vec, 1);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07003262}
3263
Elliott Hughes21f32d72011-11-09 17:44:13 -08003264void Dbg::DdmSendChunk(uint32_t type, const std::vector<uint8_t>& bytes) {
3265 DdmSendChunk(type, bytes.size(), &bytes[0]);
3266}
3267
Brian Carlstromf5293522013-07-19 00:24:00 -07003268void Dbg::DdmSendChunkV(uint32_t type, const iovec* iov, int iov_count) {
Elliott Hughes3bb81562011-10-21 18:52:59 -07003269 if (gJdwpState == NULL) {
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08003270 VLOG(jdwp) << "Debugger thread not active, ignoring DDM send: " << type;
Elliott Hughes3bb81562011-10-21 18:52:59 -07003271 } else {
Elliott Hughescccd84f2011-12-05 16:51:54 -08003272 gJdwpState->DdmSendChunkV(type, iov, iov_count);
Elliott Hughes3bb81562011-10-21 18:52:59 -07003273 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -07003274}
3275
Elliott Hughes767a1472011-10-26 18:49:02 -07003276int Dbg::DdmHandleHpifChunk(HpifWhen when) {
3277 if (when == HPIF_WHEN_NOW) {
Elliott Hughes7162ad92011-10-27 14:08:42 -07003278 DdmSendHeapInfo(when);
Elliott Hughes767a1472011-10-26 18:49:02 -07003279 return true;
3280 }
3281
3282 if (when != HPIF_WHEN_NEVER && when != HPIF_WHEN_NEXT_GC && when != HPIF_WHEN_EVERY_GC) {
3283 LOG(ERROR) << "invalid HpifWhen value: " << static_cast<int>(when);
3284 return false;
3285 }
3286
3287 gDdmHpifWhen = when;
3288 return true;
3289}
3290
3291bool Dbg::DdmHandleHpsgNhsgChunk(Dbg::HpsgWhen when, Dbg::HpsgWhat what, bool native) {
3292 if (when != HPSG_WHEN_NEVER && when != HPSG_WHEN_EVERY_GC) {
3293 LOG(ERROR) << "invalid HpsgWhen value: " << static_cast<int>(when);
3294 return false;
3295 }
3296
3297 if (what != HPSG_WHAT_MERGED_OBJECTS && what != HPSG_WHAT_DISTINCT_OBJECTS) {
3298 LOG(ERROR) << "invalid HpsgWhat value: " << static_cast<int>(what);
3299 return false;
3300 }
3301
3302 if (native) {
3303 gDdmNhsgWhen = when;
3304 gDdmNhsgWhat = what;
3305 } else {
3306 gDdmHpsgWhen = when;
3307 gDdmHpsgWhat = what;
3308 }
3309 return true;
3310}
3311
Elliott Hughes7162ad92011-10-27 14:08:42 -07003312void Dbg::DdmSendHeapInfo(HpifWhen reason) {
3313 // If there's a one-shot 'when', reset it.
3314 if (reason == gDdmHpifWhen) {
3315 if (gDdmHpifWhen == HPIF_WHEN_NEXT_GC) {
3316 gDdmHpifWhen = HPIF_WHEN_NEVER;
3317 }
3318 }
3319
3320 /*
3321 * Chunk HPIF (client --> server)
3322 *
3323 * Heap Info. General information about the heap,
3324 * suitable for a summary display.
3325 *
3326 * [u4]: number of heaps
3327 *
3328 * For each heap:
3329 * [u4]: heap ID
3330 * [u8]: timestamp in ms since Unix epoch
3331 * [u1]: capture reason (same as 'when' value from server)
3332 * [u4]: max heap size in bytes (-Xmx)
3333 * [u4]: current heap size in bytes
3334 * [u4]: current number of bytes allocated
3335 * [u4]: current number of objects allocated
3336 */
3337 uint8_t heap_count = 1;
Ian Rogers1d54e732013-05-02 21:10:01 -07003338 gc::Heap* heap = Runtime::Current()->GetHeap();
Elliott Hughes21f32d72011-11-09 17:44:13 -08003339 std::vector<uint8_t> bytes;
Elliott Hughes545a0642011-11-08 19:10:03 -08003340 JDWP::Append4BE(bytes, heap_count);
Brian Carlstrom7934ac22013-07-26 10:54:15 -07003341 JDWP::Append4BE(bytes, 1); // Heap id (bogus; we only have one heap).
Elliott Hughes545a0642011-11-08 19:10:03 -08003342 JDWP::Append8BE(bytes, MilliTime());
3343 JDWP::Append1BE(bytes, reason);
Brian Carlstrom7934ac22013-07-26 10:54:15 -07003344 JDWP::Append4BE(bytes, heap->GetMaxMemory()); // Max allowed heap size in bytes.
3345 JDWP::Append4BE(bytes, heap->GetTotalMemory()); // Current heap size in bytes.
Elliott Hughesb3bd5f02012-03-08 21:05:27 -08003346 JDWP::Append4BE(bytes, heap->GetBytesAllocated());
3347 JDWP::Append4BE(bytes, heap->GetObjectsAllocated());
Elliott Hughes21f32d72011-11-09 17:44:13 -08003348 CHECK_EQ(bytes.size(), 4U + (heap_count * (4 + 8 + 1 + 4 + 4 + 4 + 4)));
3349 Dbg::DdmSendChunk(CHUNK_TYPE("HPIF"), bytes);
Elliott Hughes767a1472011-10-26 18:49:02 -07003350}
3351
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003352enum HpsgSolidity {
3353 SOLIDITY_FREE = 0,
3354 SOLIDITY_HARD = 1,
3355 SOLIDITY_SOFT = 2,
3356 SOLIDITY_WEAK = 3,
3357 SOLIDITY_PHANTOM = 4,
3358 SOLIDITY_FINALIZABLE = 5,
3359 SOLIDITY_SWEEP = 6,
3360};
3361
3362enum HpsgKind {
3363 KIND_OBJECT = 0,
3364 KIND_CLASS_OBJECT = 1,
3365 KIND_ARRAY_1 = 2,
3366 KIND_ARRAY_2 = 3,
3367 KIND_ARRAY_4 = 4,
3368 KIND_ARRAY_8 = 5,
3369 KIND_UNKNOWN = 6,
3370 KIND_NATIVE = 7,
3371};
3372
3373#define HPSG_PARTIAL (1<<7)
3374#define HPSG_STATE(solidity, kind) ((uint8_t)((((kind) & 0x7) << 3) | ((solidity) & 0x7)))
3375
Ian Rogers30fab402012-01-23 15:43:46 -08003376class HeapChunkContext {
3377 public:
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003378 // Maximum chunk size. Obtain this from the formula:
3379 // (((maximum_heap_size / ALLOCATION_UNIT_SIZE) + 255) / 256) * 2
3380 HeapChunkContext(bool merge, bool native)
Ian Rogers30fab402012-01-23 15:43:46 -08003381 : buf_(16384 - 16),
3382 type_(0),
3383 merge_(merge) {
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003384 Reset();
3385 if (native) {
Ian Rogers30fab402012-01-23 15:43:46 -08003386 type_ = CHUNK_TYPE("NHSG");
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003387 } else {
Ian Rogers30fab402012-01-23 15:43:46 -08003388 type_ = merge ? CHUNK_TYPE("HPSG") : CHUNK_TYPE("HPSO");
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003389 }
3390 }
3391
3392 ~HeapChunkContext() {
Ian Rogers30fab402012-01-23 15:43:46 -08003393 if (p_ > &buf_[0]) {
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003394 Flush();
3395 }
3396 }
3397
3398 void EnsureHeader(const void* chunk_ptr) {
Ian Rogers30fab402012-01-23 15:43:46 -08003399 if (!needHeader_) {
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003400 return;
3401 }
3402
3403 // Start a new HPSx chunk.
Brian Carlstrom7934ac22013-07-26 10:54:15 -07003404 JDWP::Write4BE(&p_, 1); // Heap id (bogus; we only have one heap).
3405 JDWP::Write1BE(&p_, 8); // Size of allocation unit, in bytes.
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003406
Brian Carlstrom7934ac22013-07-26 10:54:15 -07003407 JDWP::Write4BE(&p_, reinterpret_cast<uintptr_t>(chunk_ptr)); // virtual address of segment start.
3408 JDWP::Write4BE(&p_, 0); // offset of this piece (relative to the virtual address).
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003409 // [u4]: length of piece, in allocation units
3410 // 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 -08003411 pieceLenField_ = p_;
3412 JDWP::Write4BE(&p_, 0x55555555);
3413 needHeader_ = false;
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003414 }
3415
Ian Rogersb726dcb2012-09-05 08:57:23 -07003416 void Flush() SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Ian Rogersd636b062013-01-18 17:51:18 -08003417 if (pieceLenField_ == NULL) {
3418 // Flush immediately post Reset (maybe back-to-back Flush). Ignore.
3419 CHECK(needHeader_);
3420 return;
3421 }
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003422 // Patch the "length of piece" field.
Ian Rogers30fab402012-01-23 15:43:46 -08003423 CHECK_LE(&buf_[0], pieceLenField_);
3424 CHECK_LE(pieceLenField_, p_);
3425 JDWP::Set4BE(pieceLenField_, totalAllocationUnits_);
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003426
Ian Rogers30fab402012-01-23 15:43:46 -08003427 Dbg::DdmSendChunk(type_, p_ - &buf_[0], &buf_[0]);
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003428 Reset();
3429 }
3430
Ian Rogers00f7d0e2012-07-19 15:28:27 -07003431 static void HeapChunkCallback(void* start, void* end, size_t used_bytes, void* arg)
Ian Rogersb726dcb2012-09-05 08:57:23 -07003432 SHARED_LOCKS_REQUIRED(Locks::heap_bitmap_lock_,
3433 Locks::mutator_lock_) {
Ian Rogers30fab402012-01-23 15:43:46 -08003434 reinterpret_cast<HeapChunkContext*>(arg)->HeapChunkCallback(start, end, used_bytes);
Elliott Hughesa2155262011-11-16 16:26:58 -08003435 }
3436
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003437 private:
Elliott Hughesa2155262011-11-16 16:26:58 -08003438 enum { ALLOCATION_UNIT_SIZE = 8 };
3439
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003440 void Reset() {
Ian Rogers30fab402012-01-23 15:43:46 -08003441 p_ = &buf_[0];
Ian Rogers15bf2d32012-08-28 17:33:04 -07003442 startOfNextMemoryChunk_ = NULL;
Ian Rogers30fab402012-01-23 15:43:46 -08003443 totalAllocationUnits_ = 0;
3444 needHeader_ = true;
3445 pieceLenField_ = NULL;
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003446 }
3447
Ian Rogers00f7d0e2012-07-19 15:28:27 -07003448 void HeapChunkCallback(void* start, void* /*end*/, size_t used_bytes)
Ian Rogersb726dcb2012-09-05 08:57:23 -07003449 SHARED_LOCKS_REQUIRED(Locks::heap_bitmap_lock_,
3450 Locks::mutator_lock_) {
Ian Rogers30fab402012-01-23 15:43:46 -08003451 // Note: heap call backs cannot manipulate the heap upon which they are crawling, care is taken
3452 // in the following code not to allocate memory, by ensuring buf_ is of the correct size
Ian Rogers15bf2d32012-08-28 17:33:04 -07003453 if (used_bytes == 0) {
3454 if (start == NULL) {
3455 // Reset for start of new heap.
3456 startOfNextMemoryChunk_ = NULL;
3457 Flush();
3458 }
3459 // Only process in use memory so that free region information
3460 // also includes dlmalloc book keeping.
Elliott Hughesa2155262011-11-16 16:26:58 -08003461 return;
Elliott Hughesa2155262011-11-16 16:26:58 -08003462 }
3463
Ian Rogers15bf2d32012-08-28 17:33:04 -07003464 /* If we're looking at the native heap, we'll just return
3465 * (SOLIDITY_HARD, KIND_NATIVE) for all allocated chunks
3466 */
3467 bool native = type_ == CHUNK_TYPE("NHSG");
3468
3469 if (startOfNextMemoryChunk_ != NULL) {
3470 // Transmit any pending free memory. Native free memory of
3471 // over kMaxFreeLen could be because of the use of mmaps, so
3472 // don't report. If not free memory then start a new segment.
3473 bool flush = true;
3474 if (start > startOfNextMemoryChunk_) {
3475 const size_t kMaxFreeLen = 2 * kPageSize;
3476 void* freeStart = startOfNextMemoryChunk_;
3477 void* freeEnd = start;
Brian Carlstrom2d888622013-07-18 17:02:00 -07003478 size_t freeLen = reinterpret_cast<char*>(freeEnd) - reinterpret_cast<char*>(freeStart);
Ian Rogers15bf2d32012-08-28 17:33:04 -07003479 if (!native || freeLen < kMaxFreeLen) {
3480 AppendChunk(HPSG_STATE(SOLIDITY_FREE, 0), freeStart, freeLen);
3481 flush = false;
3482 }
3483 }
3484 if (flush) {
3485 startOfNextMemoryChunk_ = NULL;
3486 Flush();
3487 }
3488 }
Ian Rogersef7d42f2014-01-06 12:55:46 -08003489 mirror::Object* obj = reinterpret_cast<mirror::Object*>(start);
Elliott Hughesa2155262011-11-16 16:26:58 -08003490
3491 // Determine the type of this chunk.
3492 // OLD-TODO: if context.merge, see if this chunk is different from the last chunk.
3493 // If it's the same, we should combine them.
Ian Rogers15bf2d32012-08-28 17:33:04 -07003494 uint8_t state = ExamineObject(obj, native);
3495 // dlmalloc's chunk header is 2 * sizeof(size_t), but if the previous chunk is in use for an
3496 // allocation then the first sizeof(size_t) may belong to it.
3497 const size_t dlMallocOverhead = sizeof(size_t);
3498 AppendChunk(state, start, used_bytes + dlMallocOverhead);
Brian Carlstrom2d888622013-07-18 17:02:00 -07003499 startOfNextMemoryChunk_ = reinterpret_cast<char*>(start) + used_bytes + dlMallocOverhead;
Ian Rogers15bf2d32012-08-28 17:33:04 -07003500 }
Elliott Hughesa2155262011-11-16 16:26:58 -08003501
Ian Rogers15bf2d32012-08-28 17:33:04 -07003502 void AppendChunk(uint8_t state, void* ptr, size_t length)
Ian Rogersb726dcb2012-09-05 08:57:23 -07003503 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Ian Rogers15bf2d32012-08-28 17:33:04 -07003504 // Make sure there's enough room left in the buffer.
3505 // We need to use two bytes for every fractional 256 allocation units used by the chunk plus
3506 // 17 bytes for any header.
3507 size_t needed = (((length/ALLOCATION_UNIT_SIZE + 255) / 256) * 2) + 17;
3508 size_t bytesLeft = buf_.size() - (size_t)(p_ - &buf_[0]);
3509 if (bytesLeft < needed) {
3510 Flush();
3511 }
3512
3513 bytesLeft = buf_.size() - (size_t)(p_ - &buf_[0]);
3514 if (bytesLeft < needed) {
3515 LOG(WARNING) << "Chunk is too big to transmit (chunk_len=" << length << ", "
3516 << needed << " bytes)";
3517 return;
3518 }
3519 EnsureHeader(ptr);
Elliott Hughesa2155262011-11-16 16:26:58 -08003520 // Write out the chunk description.
Ian Rogers15bf2d32012-08-28 17:33:04 -07003521 length /= ALLOCATION_UNIT_SIZE; // Convert to allocation units.
3522 totalAllocationUnits_ += length;
3523 while (length > 256) {
Ian Rogers30fab402012-01-23 15:43:46 -08003524 *p_++ = state | HPSG_PARTIAL;
3525 *p_++ = 255; // length - 1
Ian Rogers15bf2d32012-08-28 17:33:04 -07003526 length -= 256;
Elliott Hughesa2155262011-11-16 16:26:58 -08003527 }
Ian Rogers30fab402012-01-23 15:43:46 -08003528 *p_++ = state;
Ian Rogers15bf2d32012-08-28 17:33:04 -07003529 *p_++ = length - 1;
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003530 }
3531
Ian Rogersef7d42f2014-01-06 12:55:46 -08003532 uint8_t ExamineObject(mirror::Object* o, bool is_native_heap)
3533 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_, Locks::heap_bitmap_lock_) {
Elliott Hughesa2155262011-11-16 16:26:58 -08003534 if (o == NULL) {
3535 return HPSG_STATE(SOLIDITY_FREE, 0);
3536 }
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003537
Elliott Hughesa2155262011-11-16 16:26:58 -08003538 // It's an allocated chunk. Figure out what it is.
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003539
Elliott Hughesa2155262011-11-16 16:26:58 -08003540 // If we're looking at the native heap, we'll just return
3541 // (SOLIDITY_HARD, KIND_NATIVE) for all allocated chunks.
Ian Rogers00f7d0e2012-07-19 15:28:27 -07003542 if (is_native_heap) {
Elliott Hughesa2155262011-11-16 16:26:58 -08003543 return HPSG_STATE(SOLIDITY_HARD, KIND_NATIVE);
3544 }
3545
Ian Rogers5bfa60f2012-09-02 21:17:56 -07003546 if (!Runtime::Current()->GetHeap()->IsLiveObjectLocked(o)) {
Ian Rogers15bf2d32012-08-28 17:33:04 -07003547 return HPSG_STATE(SOLIDITY_HARD, KIND_NATIVE);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07003548 }
3549
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003550 mirror::Class* c = o->GetClass();
Elliott Hughesa2155262011-11-16 16:26:58 -08003551 if (c == NULL) {
3552 // The object was probably just created but hasn't been initialized yet.
3553 return HPSG_STATE(SOLIDITY_HARD, KIND_OBJECT);
3554 }
3555
Mathieu Chartier590fee92013-09-13 13:46:47 -07003556 if (!Runtime::Current()->GetHeap()->IsValidObjectAddress(c)) {
Ian Rogers15bf2d32012-08-28 17:33:04 -07003557 LOG(ERROR) << "Invalid class for managed heap object: " << o << " " << c;
Elliott Hughesa2155262011-11-16 16:26:58 -08003558 return HPSG_STATE(SOLIDITY_HARD, KIND_UNKNOWN);
3559 }
3560
3561 if (c->IsClassClass()) {
3562 return HPSG_STATE(SOLIDITY_HARD, KIND_CLASS_OBJECT);
3563 }
3564
3565 if (c->IsArrayClass()) {
3566 if (o->IsObjectArray()) {
3567 return HPSG_STATE(SOLIDITY_HARD, KIND_ARRAY_4);
3568 }
3569 switch (c->GetComponentSize()) {
3570 case 1: return HPSG_STATE(SOLIDITY_HARD, KIND_ARRAY_1);
3571 case 2: return HPSG_STATE(SOLIDITY_HARD, KIND_ARRAY_2);
3572 case 4: return HPSG_STATE(SOLIDITY_HARD, KIND_ARRAY_4);
3573 case 8: return HPSG_STATE(SOLIDITY_HARD, KIND_ARRAY_8);
3574 }
3575 }
3576
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003577 return HPSG_STATE(SOLIDITY_HARD, KIND_OBJECT);
3578 }
3579
Ian Rogers30fab402012-01-23 15:43:46 -08003580 std::vector<uint8_t> buf_;
3581 uint8_t* p_;
3582 uint8_t* pieceLenField_;
Ian Rogers15bf2d32012-08-28 17:33:04 -07003583 void* startOfNextMemoryChunk_;
Ian Rogers30fab402012-01-23 15:43:46 -08003584 size_t totalAllocationUnits_;
3585 uint32_t type_;
3586 bool merge_;
3587 bool needHeader_;
3588
Elliott Hughesa2155262011-11-16 16:26:58 -08003589 DISALLOW_COPY_AND_ASSIGN(HeapChunkContext);
3590};
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003591
3592void Dbg::DdmSendHeapSegments(bool native) {
3593 Dbg::HpsgWhen when;
3594 Dbg::HpsgWhat what;
3595 if (!native) {
3596 when = gDdmHpsgWhen;
3597 what = gDdmHpsgWhat;
3598 } else {
3599 when = gDdmNhsgWhen;
3600 what = gDdmNhsgWhat;
3601 }
3602 if (when == HPSG_WHEN_NEVER) {
3603 return;
3604 }
3605
3606 // Figure out what kind of chunks we'll be sending.
3607 CHECK(what == HPSG_WHAT_MERGED_OBJECTS || what == HPSG_WHAT_DISTINCT_OBJECTS) << static_cast<int>(what);
3608
3609 // First, send a heap start chunk.
3610 uint8_t heap_id[4];
Brian Carlstrom7934ac22013-07-26 10:54:15 -07003611 JDWP::Set4BE(&heap_id[0], 1); // Heap id (bogus; we only have one heap).
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003612 Dbg::DdmSendChunk(native ? CHUNK_TYPE("NHST") : CHUNK_TYPE("HPST"), sizeof(heap_id), heap_id);
3613
Hiroshi Yamauchicf58d4a2013-09-26 14:21:22 -07003614 Thread* self = Thread::Current();
3615
3616 // To allow the Walk/InspectAll() below to exclusively-lock the
3617 // mutator lock, temporarily release the shared access to the
3618 // mutator lock here by transitioning to the suspended state.
3619 Locks::mutator_lock_->AssertSharedHeld(self);
3620 self->TransitionFromRunnableToSuspended(kSuspended);
3621
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003622 // Send a series of heap segment chunks.
Elliott Hughesa2155262011-11-16 16:26:58 -08003623 HeapChunkContext context((what == HPSG_WHAT_MERGED_OBJECTS), native);
3624 if (native) {
Ian Rogers1d54e732013-05-02 21:10:01 -07003625 dlmalloc_inspect_all(HeapChunkContext::HeapChunkCallback, &context);
Elliott Hughesa2155262011-11-16 16:26:58 -08003626 } else {
Ian Rogers1d54e732013-05-02 21:10:01 -07003627 gc::Heap* heap = Runtime::Current()->GetHeap();
3628 const std::vector<gc::space::ContinuousSpace*>& spaces = heap->GetContinuousSpaces();
Ian Rogers62d6c772013-02-27 08:32:07 -08003629 ReaderMutexLock mu(self, *Locks::heap_bitmap_lock_);
Ian Rogers1d54e732013-05-02 21:10:01 -07003630 typedef std::vector<gc::space::ContinuousSpace*>::const_iterator It;
3631 for (It cur = spaces.begin(), end = spaces.end(); cur != end; ++cur) {
Hiroshi Yamauchicf58d4a2013-09-26 14:21:22 -07003632 if ((*cur)->IsMallocSpace()) {
3633 (*cur)->AsMallocSpace()->Walk(HeapChunkContext::HeapChunkCallback, &context);
Mathieu Chartierb062fdd2012-07-03 09:51:48 -07003634 }
3635 }
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -07003636 // Walk the large objects, these are not in the AllocSpace.
3637 heap->GetLargeObjectsSpace()->Walk(HeapChunkContext::HeapChunkCallback, &context);
Elliott Hughesa2155262011-11-16 16:26:58 -08003638 }
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003639
Hiroshi Yamauchicf58d4a2013-09-26 14:21:22 -07003640 // Shared-lock the mutator lock back.
3641 self->TransitionFromSuspendedToRunnable();
3642 Locks::mutator_lock_->AssertSharedHeld(self);
3643
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003644 // Finally, send a heap end chunk.
3645 Dbg::DdmSendChunk(native ? CHUNK_TYPE("NHEN") : CHUNK_TYPE("HPEN"), sizeof(heap_id), heap_id);
Elliott Hughes767a1472011-10-26 18:49:02 -07003646}
3647
Elliott Hughesb1a58792013-07-11 18:10:58 -07003648static size_t GetAllocTrackerMax() {
3649#ifdef HAVE_ANDROID_OS
3650 // Check whether there's a system property overriding the number of records.
3651 const char* propertyName = "dalvik.vm.allocTrackerMax";
3652 char allocRecordMaxString[PROPERTY_VALUE_MAX];
3653 if (property_get(propertyName, allocRecordMaxString, "") > 0) {
3654 char* end;
3655 size_t value = strtoul(allocRecordMaxString, &end, 10);
3656 if (*end != '\0') {
Ruben Brunk3e47a742013-09-09 17:56:07 -07003657 LOG(ERROR) << "Ignoring " << propertyName << " '" << allocRecordMaxString
3658 << "' --- invalid";
Elliott Hughesb1a58792013-07-11 18:10:58 -07003659 return kDefaultNumAllocRecords;
3660 }
3661 if (!IsPowerOfTwo(value)) {
Ruben Brunk3e47a742013-09-09 17:56:07 -07003662 LOG(ERROR) << "Ignoring " << propertyName << " '" << allocRecordMaxString
3663 << "' --- not power of two";
Elliott Hughesb1a58792013-07-11 18:10:58 -07003664 return kDefaultNumAllocRecords;
3665 }
3666 return value;
3667 }
3668#endif
3669 return kDefaultNumAllocRecords;
3670}
3671
Elliott Hughes545a0642011-11-08 19:10:03 -08003672void Dbg::SetAllocTrackingEnabled(bool enabled) {
Ian Rogers50b35e22012-10-04 10:09:15 -07003673 MutexLock mu(Thread::Current(), gAllocTrackerLock);
Elliott Hughes545a0642011-11-08 19:10:03 -08003674 if (enabled) {
3675 if (recent_allocation_records_ == NULL) {
Elliott Hughesb1a58792013-07-11 18:10:58 -07003676 gAllocRecordMax = GetAllocTrackerMax();
3677 LOG(INFO) << "Enabling alloc tracker (" << gAllocRecordMax << " entries of "
3678 << kMaxAllocRecordStackDepth << " frames, taking "
3679 << PrettySize(sizeof(AllocRecord) * gAllocRecordMax) << ")";
Elliott Hughes545a0642011-11-08 19:10:03 -08003680 gAllocRecordHead = gAllocRecordCount = 0;
Elliott Hughesb1a58792013-07-11 18:10:58 -07003681 recent_allocation_records_ = new AllocRecord[gAllocRecordMax];
Elliott Hughes545a0642011-11-08 19:10:03 -08003682 CHECK(recent_allocation_records_ != NULL);
3683 }
Ian Rogersfa824272013-11-05 16:12:57 -08003684 Runtime::Current()->GetInstrumentation()->InstrumentQuickAllocEntryPoints();
Elliott Hughes545a0642011-11-08 19:10:03 -08003685 } else {
Ian Rogersfa824272013-11-05 16:12:57 -08003686 Runtime::Current()->GetInstrumentation()->UninstrumentQuickAllocEntryPoints();
Elliott Hughes545a0642011-11-08 19:10:03 -08003687 delete[] recent_allocation_records_;
3688 recent_allocation_records_ = NULL;
3689 }
3690}
3691
Ian Rogers0399dde2012-06-06 17:09:28 -07003692struct AllocRecordStackVisitor : public StackVisitor {
Ian Rogers7a22fa62013-01-23 12:16:16 -08003693 AllocRecordStackVisitor(Thread* thread, AllocRecord* record)
Ian Rogersb726dcb2012-09-05 08:57:23 -07003694 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_)
Ian Rogers7a22fa62013-01-23 12:16:16 -08003695 : StackVisitor(thread, NULL), record(record), depth(0) {}
Elliott Hughes545a0642011-11-08 19:10:03 -08003696
Ian Rogers00f7d0e2012-07-19 15:28:27 -07003697 // TODO: Enable annotalysis. We know lock is held in constructor, but abstraction confuses
3698 // annotalysis.
3699 bool VisitFrame() NO_THREAD_SAFETY_ANALYSIS {
Elliott Hughes545a0642011-11-08 19:10:03 -08003700 if (depth >= kMaxAllocRecordStackDepth) {
Elliott Hughes530fa002012-03-12 11:44:49 -07003701 return false;
Elliott Hughes545a0642011-11-08 19:10:03 -08003702 }
Brian Carlstromea46f952013-07-30 01:26:50 -07003703 mirror::ArtMethod* m = GetMethod();
Ian Rogers0399dde2012-06-06 17:09:28 -07003704 if (!m->IsRuntimeMethod()) {
3705 record->stack[depth].method = m;
3706 record->stack[depth].dex_pc = GetDexPc();
Elliott Hughes530fa002012-03-12 11:44:49 -07003707 ++depth;
Elliott Hughes545a0642011-11-08 19:10:03 -08003708 }
Elliott Hughes530fa002012-03-12 11:44:49 -07003709 return true;
Elliott Hughes545a0642011-11-08 19:10:03 -08003710 }
3711
3712 ~AllocRecordStackVisitor() {
3713 // Clear out any unused stack trace elements.
3714 for (; depth < kMaxAllocRecordStackDepth; ++depth) {
3715 record->stack[depth].method = NULL;
Ian Rogers0399dde2012-06-06 17:09:28 -07003716 record->stack[depth].dex_pc = 0;
Elliott Hughes545a0642011-11-08 19:10:03 -08003717 }
3718 }
3719
3720 AllocRecord* record;
3721 size_t depth;
3722};
3723
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003724void Dbg::RecordAllocation(mirror::Class* type, size_t byte_count) {
Elliott Hughes545a0642011-11-08 19:10:03 -08003725 Thread* self = Thread::Current();
3726 CHECK(self != NULL);
3727
Ian Rogers50b35e22012-10-04 10:09:15 -07003728 MutexLock mu(self, gAllocTrackerLock);
Elliott Hughes545a0642011-11-08 19:10:03 -08003729 if (recent_allocation_records_ == NULL) {
3730 return;
3731 }
3732
3733 // Advance and clip.
Elliott Hughesb1a58792013-07-11 18:10:58 -07003734 if (++gAllocRecordHead == gAllocRecordMax) {
Elliott Hughes545a0642011-11-08 19:10:03 -08003735 gAllocRecordHead = 0;
3736 }
3737
3738 // Fill in the basics.
3739 AllocRecord* record = &recent_allocation_records_[gAllocRecordHead];
3740 record->type = type;
3741 record->byte_count = byte_count;
Ian Rogersd9c4fc92013-10-01 19:45:43 -07003742 record->thin_lock_id = self->GetThreadId();
Elliott Hughes545a0642011-11-08 19:10:03 -08003743
3744 // Fill in the stack trace.
Ian Rogers7a22fa62013-01-23 12:16:16 -08003745 AllocRecordStackVisitor visitor(self, record);
Ian Rogers0399dde2012-06-06 17:09:28 -07003746 visitor.WalkStack();
Elliott Hughes545a0642011-11-08 19:10:03 -08003747
Elliott Hughesb1a58792013-07-11 18:10:58 -07003748 if (gAllocRecordCount < gAllocRecordMax) {
Elliott Hughes545a0642011-11-08 19:10:03 -08003749 ++gAllocRecordCount;
3750 }
3751}
3752
Elliott Hughesa8f93cb2012-06-08 17:08:48 -07003753// Returns the index of the head element.
3754//
3755// We point at the most-recently-written record, so if gAllocRecordCount is 1
3756// we want to use the current element. Take "head+1" and subtract count
3757// from it.
3758//
3759// We need to handle underflow in our circular buffer, so we add
Elliott Hughesb1a58792013-07-11 18:10:58 -07003760// gAllocRecordMax and then mask it back down.
Elliott Hughesf8349362012-06-18 15:00:06 -07003761static inline int HeadIndex() EXCLUSIVE_LOCKS_REQUIRED(gAllocTrackerLock) {
Elliott Hughesb1a58792013-07-11 18:10:58 -07003762 return (gAllocRecordHead+1 + gAllocRecordMax - gAllocRecordCount) & (gAllocRecordMax-1);
Elliott Hughes545a0642011-11-08 19:10:03 -08003763}
3764
3765void Dbg::DumpRecentAllocations() {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07003766 ScopedObjectAccess soa(Thread::Current());
Ian Rogers50b35e22012-10-04 10:09:15 -07003767 MutexLock mu(soa.Self(), gAllocTrackerLock);
Elliott Hughes545a0642011-11-08 19:10:03 -08003768 if (recent_allocation_records_ == NULL) {
3769 LOG(INFO) << "Not recording tracked allocations";
3770 return;
3771 }
3772
3773 // "i" is the head of the list. We want to start at the end of the
3774 // list and move forward to the tail.
Elliott Hughesa8f93cb2012-06-08 17:08:48 -07003775 size_t i = HeadIndex();
Elliott Hughes545a0642011-11-08 19:10:03 -08003776 size_t count = gAllocRecordCount;
3777
3778 LOG(INFO) << "Tracked allocations, (head=" << gAllocRecordHead << " count=" << count << ")";
3779 while (count--) {
3780 AllocRecord* record = &recent_allocation_records_[i];
3781
Elliott Hughesa8f93cb2012-06-08 17:08:48 -07003782 LOG(INFO) << StringPrintf(" Thread %-2d %6zd bytes ", record->thin_lock_id, record->byte_count)
Elliott Hughes545a0642011-11-08 19:10:03 -08003783 << PrettyClass(record->type);
3784
3785 for (size_t stack_frame = 0; stack_frame < kMaxAllocRecordStackDepth; ++stack_frame) {
Ian Rogersef7d42f2014-01-06 12:55:46 -08003786 mirror::ArtMethod* m = record->stack[stack_frame].method;
Elliott Hughes545a0642011-11-08 19:10:03 -08003787 if (m == NULL) {
3788 break;
3789 }
3790 LOG(INFO) << " " << PrettyMethod(m) << " line " << record->stack[stack_frame].LineNumber();
3791 }
3792
3793 // pause periodically to help logcat catch up
3794 if ((count % 5) == 0) {
3795 usleep(40000);
3796 }
3797
Elliott Hughesb1a58792013-07-11 18:10:58 -07003798 i = (i + 1) & (gAllocRecordMax-1);
Elliott Hughes545a0642011-11-08 19:10:03 -08003799 }
3800}
3801
Mathieu Chartier83c8ee02014-01-28 14:50:23 -08003802void Dbg::UpdateObjectPointers(IsMarkedCallback* visitor, void* arg) {
Mathieu Chartier412c7fc2014-02-07 12:18:39 -08003803 {
3804 MutexLock mu(Thread::Current(), gAllocTrackerLock);
3805 if (recent_allocation_records_ != nullptr) {
3806 size_t i = HeadIndex();
3807 size_t count = gAllocRecordCount;
3808 while (count--) {
3809 AllocRecord* record = &recent_allocation_records_[i];
3810 DCHECK(record != nullptr);
3811 record->UpdateObjectPointers(visitor, arg);
3812 i = (i + 1) & (gAllocRecordMax - 1);
3813 }
3814 }
3815 }
3816 if (gRegistry != nullptr) {
3817 gRegistry->UpdateObjectPointers(visitor, arg);
3818 }
3819}
3820
3821void Dbg::AllowNewObjectRegistryObjects() {
3822 if (gRegistry != nullptr) {
3823 gRegistry->AllowNewObjects();
3824 }
3825}
3826
3827void Dbg::DisallowNewObjectRegistryObjects() {
3828 if (gRegistry != nullptr) {
3829 gRegistry->DisallowNewObjects();
3830 }
3831}
3832
Elliott Hughes545a0642011-11-08 19:10:03 -08003833class StringTable {
3834 public:
3835 StringTable() {
3836 }
3837
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08003838 void Add(const char* s) {
Elliott Hughes545a0642011-11-08 19:10:03 -08003839 table_.insert(s);
3840 }
3841
Elliott Hughesa8f93cb2012-06-08 17:08:48 -07003842 size_t IndexOf(const char* s) const {
Mathieu Chartier02e25112013-08-14 16:14:24 -07003843 auto it = table_.find(s);
Elliott Hughesa8f93cb2012-06-08 17:08:48 -07003844 if (it == table_.end()) {
3845 LOG(FATAL) << "IndexOf(\"" << s << "\") failed";
3846 }
3847 return std::distance(table_.begin(), it);
Elliott Hughes545a0642011-11-08 19:10:03 -08003848 }
3849
Elliott Hughesa8f93cb2012-06-08 17:08:48 -07003850 size_t Size() const {
Elliott Hughes545a0642011-11-08 19:10:03 -08003851 return table_.size();
3852 }
3853
Elliott Hughesa8f93cb2012-06-08 17:08:48 -07003854 void WriteTo(std::vector<uint8_t>& bytes) const {
Mathieu Chartier02e25112013-08-14 16:14:24 -07003855 for (const std::string& str : table_) {
3856 const char* s = str.c_str();
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08003857 size_t s_len = CountModifiedUtf8Chars(s);
3858 UniquePtr<uint16_t> s_utf16(new uint16_t[s_len]);
3859 ConvertModifiedUtf8ToUtf16(s_utf16.get(), s);
3860 JDWP::AppendUtf16BE(bytes, s_utf16.get(), s_len);
Elliott Hughes545a0642011-11-08 19:10:03 -08003861 }
3862 }
3863
3864 private:
Elliott Hughesa8f93cb2012-06-08 17:08:48 -07003865 std::set<std::string> table_;
Elliott Hughes545a0642011-11-08 19:10:03 -08003866 DISALLOW_COPY_AND_ASSIGN(StringTable);
3867};
3868
3869/*
3870 * The data we send to DDMS contains everything we have recorded.
3871 *
3872 * Message header (all values big-endian):
3873 * (1b) message header len (to allow future expansion); includes itself
3874 * (1b) entry header len
3875 * (1b) stack frame len
3876 * (2b) number of entries
3877 * (4b) offset to string table from start of message
3878 * (2b) number of class name strings
3879 * (2b) number of method name strings
3880 * (2b) number of source file name strings
3881 * For each entry:
3882 * (4b) total allocation size
Elliott Hughes221229c2013-01-08 18:17:50 -08003883 * (2b) thread id
Elliott Hughes545a0642011-11-08 19:10:03 -08003884 * (2b) allocated object's class name index
3885 * (1b) stack depth
3886 * For each stack frame:
3887 * (2b) method's class name
3888 * (2b) method name
3889 * (2b) method source file
3890 * (2b) line number, clipped to 32767; -2 if native; -1 if no source
3891 * (xb) class name strings
3892 * (xb) method name strings
3893 * (xb) source file strings
3894 *
3895 * As with other DDM traffic, strings are sent as a 4-byte length
3896 * followed by UTF-16 data.
3897 *
3898 * We send up 16-bit unsigned indexes into string tables. In theory there
Elliott Hughesb1a58792013-07-11 18:10:58 -07003899 * can be (kMaxAllocRecordStackDepth * gAllocRecordMax) unique strings in
Elliott Hughes545a0642011-11-08 19:10:03 -08003900 * each table, but in practice there should be far fewer.
3901 *
3902 * The chief reason for using a string table here is to keep the size of
3903 * the DDMS message to a minimum. This is partly to make the protocol
3904 * efficient, but also because we have to form the whole thing up all at
3905 * once in a memory buffer.
3906 *
3907 * We use separate string tables for class names, method names, and source
3908 * files to keep the indexes small. There will generally be no overlap
3909 * between the contents of these tables.
3910 */
3911jbyteArray Dbg::GetRecentAllocations() {
3912 if (false) {
3913 DumpRecentAllocations();
3914 }
3915
Ian Rogers50b35e22012-10-04 10:09:15 -07003916 Thread* self = Thread::Current();
Elliott Hughes545a0642011-11-08 19:10:03 -08003917 std::vector<uint8_t> bytes;
Mathieu Chartier46e811b2013-07-10 17:09:14 -07003918 {
3919 MutexLock mu(self, gAllocTrackerLock);
3920 //
3921 // Part 1: generate string tables.
3922 //
3923 StringTable class_names;
3924 StringTable method_names;
3925 StringTable filenames;
Elliott Hughes545a0642011-11-08 19:10:03 -08003926
Mathieu Chartier46e811b2013-07-10 17:09:14 -07003927 int count = gAllocRecordCount;
3928 int idx = HeadIndex();
3929 while (count--) {
3930 AllocRecord* record = &recent_allocation_records_[idx];
Elliott Hughes545a0642011-11-08 19:10:03 -08003931
Mathieu Chartier46e811b2013-07-10 17:09:14 -07003932 class_names.Add(ClassHelper(record->type).GetDescriptor());
Elliott Hughes545a0642011-11-08 19:10:03 -08003933
Mathieu Chartier46e811b2013-07-10 17:09:14 -07003934 MethodHelper mh;
3935 for (size_t i = 0; i < kMaxAllocRecordStackDepth; i++) {
Brian Carlstromea46f952013-07-30 01:26:50 -07003936 mirror::ArtMethod* m = record->stack[i].method;
Mathieu Chartier46e811b2013-07-10 17:09:14 -07003937 if (m != NULL) {
3938 mh.ChangeMethod(m);
3939 class_names.Add(mh.GetDeclaringClassDescriptor());
3940 method_names.Add(mh.GetName());
3941 filenames.Add(mh.GetDeclaringClassSourceFile());
3942 }
3943 }
Elliott Hughes545a0642011-11-08 19:10:03 -08003944
Elliott Hughesb1a58792013-07-11 18:10:58 -07003945 idx = (idx + 1) & (gAllocRecordMax-1);
Elliott Hughes545a0642011-11-08 19:10:03 -08003946 }
3947
Mathieu Chartier46e811b2013-07-10 17:09:14 -07003948 LOG(INFO) << "allocation records: " << gAllocRecordCount;
3949
3950 //
3951 // Part 2: Generate the output and store it in the buffer.
3952 //
3953
3954 // (1b) message header len (to allow future expansion); includes itself
3955 // (1b) entry header len
3956 // (1b) stack frame len
3957 const int kMessageHeaderLen = 15;
3958 const int kEntryHeaderLen = 9;
3959 const int kStackFrameLen = 8;
3960 JDWP::Append1BE(bytes, kMessageHeaderLen);
3961 JDWP::Append1BE(bytes, kEntryHeaderLen);
3962 JDWP::Append1BE(bytes, kStackFrameLen);
3963
3964 // (2b) number of entries
3965 // (4b) offset to string table from start of message
3966 // (2b) number of class name strings
3967 // (2b) number of method name strings
3968 // (2b) number of source file name strings
3969 JDWP::Append2BE(bytes, gAllocRecordCount);
3970 size_t string_table_offset = bytes.size();
Brian Carlstrom7934ac22013-07-26 10:54:15 -07003971 JDWP::Append4BE(bytes, 0); // We'll patch this later...
Mathieu Chartier46e811b2013-07-10 17:09:14 -07003972 JDWP::Append2BE(bytes, class_names.Size());
3973 JDWP::Append2BE(bytes, method_names.Size());
3974 JDWP::Append2BE(bytes, filenames.Size());
3975
3976 count = gAllocRecordCount;
3977 idx = HeadIndex();
Mathieu Chartier46e811b2013-07-10 17:09:14 -07003978 while (count--) {
3979 // For each entry:
3980 // (4b) total allocation size
3981 // (2b) thread id
3982 // (2b) allocated object's class name index
3983 // (1b) stack depth
3984 AllocRecord* record = &recent_allocation_records_[idx];
3985 size_t stack_depth = record->GetDepth();
Mathieu Chartier590fee92013-09-13 13:46:47 -07003986 ClassHelper kh(record->type);
Mathieu Chartier46e811b2013-07-10 17:09:14 -07003987 size_t allocated_object_class_name_index = class_names.IndexOf(kh.GetDescriptor());
3988 JDWP::Append4BE(bytes, record->byte_count);
3989 JDWP::Append2BE(bytes, record->thin_lock_id);
3990 JDWP::Append2BE(bytes, allocated_object_class_name_index);
3991 JDWP::Append1BE(bytes, stack_depth);
3992
3993 MethodHelper mh;
3994 for (size_t stack_frame = 0; stack_frame < stack_depth; ++stack_frame) {
3995 // For each stack frame:
3996 // (2b) method's class name
3997 // (2b) method name
3998 // (2b) method source file
3999 // (2b) line number, clipped to 32767; -2 if native; -1 if no source
4000 mh.ChangeMethod(record->stack[stack_frame].method);
4001 size_t class_name_index = class_names.IndexOf(mh.GetDeclaringClassDescriptor());
4002 size_t method_name_index = method_names.IndexOf(mh.GetName());
4003 size_t file_name_index = filenames.IndexOf(mh.GetDeclaringClassSourceFile());
4004 JDWP::Append2BE(bytes, class_name_index);
4005 JDWP::Append2BE(bytes, method_name_index);
4006 JDWP::Append2BE(bytes, file_name_index);
4007 JDWP::Append2BE(bytes, record->stack[stack_frame].LineNumber());
4008 }
4009
Elliott Hughesb1a58792013-07-11 18:10:58 -07004010 idx = (idx + 1) & (gAllocRecordMax-1);
Mathieu Chartier46e811b2013-07-10 17:09:14 -07004011 }
4012
4013 // (xb) class name strings
4014 // (xb) method name strings
4015 // (xb) source file strings
4016 JDWP::Set4BE(&bytes[string_table_offset], bytes.size());
4017 class_names.WriteTo(bytes);
4018 method_names.WriteTo(bytes);
4019 filenames.WriteTo(bytes);
Elliott Hughes545a0642011-11-08 19:10:03 -08004020 }
Ian Rogers50b35e22012-10-04 10:09:15 -07004021 JNIEnv* env = self->GetJniEnv();
Elliott Hughes545a0642011-11-08 19:10:03 -08004022 jbyteArray result = env->NewByteArray(bytes.size());
4023 if (result != NULL) {
4024 env->SetByteArrayRegion(result, 0, bytes.size(), reinterpret_cast<const jbyte*>(&bytes[0]));
4025 }
4026 return result;
4027}
4028
Elliott Hughes872d4ec2011-10-21 17:07:15 -07004029} // namespace art