blob: 1276cd909430c987722feb0c5c13d326403fc28b [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
Ian Rogers719d1a32014-03-06 12:13:39 -0800187static ObjectRegistry* gRegistry = nullptr;
Elliott Hughes475fc232011-10-25 15:00:35 -0700188
Elliott Hughes545a0642011-11-08 19:10:03 -0800189// Recent allocation tracking.
Ian Rogers719d1a32014-03-06 12:13:39 -0800190Mutex* Dbg::alloc_tracker_lock_ = nullptr;
191AllocRecord* Dbg::recent_allocation_records_ = nullptr; // TODO: CircularBuffer<AllocRecord>
192size_t Dbg::alloc_record_max_ = 0;
193size_t Dbg::alloc_record_head_ = 0;
194size_t Dbg::alloc_record_count_ = 0;
Elliott Hughes545a0642011-11-08 19:10:03 -0800195
Sebastien Hertz138dbfc2013-12-04 18:15:25 +0100196// Deoptimization support.
197struct MethodInstrumentationRequest {
198 bool deoptimize;
199
200 // Method for selective deoptimization. NULL means full deoptimization.
201 mirror::ArtMethod* method;
202
203 MethodInstrumentationRequest(bool deoptimize, mirror::ArtMethod* method)
204 : deoptimize(deoptimize), method(method) {}
205};
206// TODO we need to visit associated methods as roots.
207static std::vector<MethodInstrumentationRequest> gDeoptimizationRequests GUARDED_BY(Locks::deoptimization_lock_);
208
209// Breakpoints.
jeffhao09bfc6a2012-12-11 18:11:43 -0800210static std::vector<Breakpoint> gBreakpoints GUARDED_BY(Locks::breakpoint_lock_);
Elliott Hughes86964332012-02-15 19:37:42 -0800211
Brian Carlstromea46f952013-07-30 01:26:50 -0700212static bool IsBreakpoint(const mirror::ArtMethod* m, uint32_t dex_pc)
jeffhao09bfc6a2012-12-11 18:11:43 -0800213 LOCKS_EXCLUDED(Locks::breakpoint_lock_)
Ian Rogersb726dcb2012-09-05 08:57:23 -0700214 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
jeffhao09bfc6a2012-12-11 18:11:43 -0800215 MutexLock mu(Thread::Current(), *Locks::breakpoint_lock_);
Sebastien Hertz138dbfc2013-12-04 18:15:25 +0100216 for (size_t i = 0, e = gBreakpoints.size(); i < e; ++i) {
Elliott Hughesa656a0f2012-02-21 18:03:44 -0800217 if (gBreakpoints[i].method == m && gBreakpoints[i].dex_pc == dex_pc) {
Elliott Hughes86964332012-02-15 19:37:42 -0800218 VLOG(jdwp) << "Hit breakpoint #" << i << ": " << gBreakpoints[i];
219 return true;
220 }
221 }
222 return false;
223}
224
Elliott Hughes9e0c1752013-01-09 14:02:58 -0800225static bool IsSuspendedForDebugger(ScopedObjectAccessUnchecked& soa, Thread* thread) {
226 MutexLock mu(soa.Self(), *Locks::thread_suspend_count_lock_);
227 // A thread may be suspended for GC; in this code, we really want to know whether
228 // there's a debugger suspension active.
229 return thread->IsSuspended() && thread->GetDebugSuspendCount() > 0;
230}
231
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800232static mirror::Array* DecodeArray(JDWP::RefTypeId id, JDWP::JdwpError& status)
Ian Rogersb726dcb2012-09-05 08:57:23 -0700233 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800234 mirror::Object* o = gRegistry->Get<mirror::Object*>(id);
Elliott Hughes64f574f2013-02-20 14:57:12 -0800235 if (o == NULL || o == ObjectRegistry::kInvalidObject) {
Elliott Hughes436e3722012-02-17 20:01:47 -0800236 status = JDWP::ERR_INVALID_OBJECT;
237 return NULL;
238 }
239 if (!o->IsArrayInstance()) {
240 status = JDWP::ERR_INVALID_ARRAY;
241 return NULL;
242 }
243 status = JDWP::ERR_NONE;
244 return o->AsArray();
245}
246
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800247static mirror::Class* DecodeClass(JDWP::RefTypeId id, JDWP::JdwpError& status)
Ian Rogersb726dcb2012-09-05 08:57:23 -0700248 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800249 mirror::Object* o = gRegistry->Get<mirror::Object*>(id);
Elliott Hughes64f574f2013-02-20 14:57:12 -0800250 if (o == NULL || o == ObjectRegistry::kInvalidObject) {
Elliott Hughes436e3722012-02-17 20:01:47 -0800251 status = JDWP::ERR_INVALID_OBJECT;
252 return NULL;
253 }
254 if (!o->IsClass()) {
255 status = JDWP::ERR_INVALID_CLASS;
256 return NULL;
257 }
258 status = JDWP::ERR_NONE;
259 return o->AsClass();
260}
261
Elliott Hughes221229c2013-01-08 18:17:50 -0800262static JDWP::JdwpError DecodeThread(ScopedObjectAccessUnchecked& soa, JDWP::ObjectId thread_id, Thread*& thread)
jeffhaoa77f0f62012-12-05 17:19:31 -0800263 EXCLUSIVE_LOCKS_REQUIRED(Locks::thread_list_lock_)
Ian Rogersb726dcb2012-09-05 08:57:23 -0700264 LOCKS_EXCLUDED(Locks::thread_suspend_count_lock_)
265 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800266 mirror::Object* thread_peer = gRegistry->Get<mirror::Object*>(thread_id);
Elliott Hughes64f574f2013-02-20 14:57:12 -0800267 if (thread_peer == NULL || thread_peer == ObjectRegistry::kInvalidObject) {
Elliott Hughes221229c2013-01-08 18:17:50 -0800268 // This isn't even an object.
269 return JDWP::ERR_INVALID_OBJECT;
Elliott Hughes436e3722012-02-17 20:01:47 -0800270 }
Elliott Hughes221229c2013-01-08 18:17:50 -0800271
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800272 mirror::Class* java_lang_Thread = soa.Decode<mirror::Class*>(WellKnownClasses::java_lang_Thread);
Elliott Hughes221229c2013-01-08 18:17:50 -0800273 if (!java_lang_Thread->IsAssignableFrom(thread_peer->GetClass())) {
274 // This isn't a thread.
275 return JDWP::ERR_INVALID_THREAD;
276 }
277
278 thread = Thread::FromManagedThread(soa, thread_peer);
279 if (thread == NULL) {
280 // This is a java.lang.Thread without a Thread*. Must be a zombie.
281 return JDWP::ERR_THREAD_NOT_ALIVE;
282 }
283 return JDWP::ERR_NONE;
Elliott Hughes436e3722012-02-17 20:01:47 -0800284}
285
Elliott Hughes24437992011-11-30 14:49:33 -0800286static JDWP::JdwpTag BasicTagFromDescriptor(const char* descriptor) {
287 // JDWP deliberately uses the descriptor characters' ASCII values for its enum.
288 // Note that by "basic" we mean that we don't get more specific than JT_OBJECT.
289 return static_cast<JDWP::JdwpTag>(descriptor[0]);
290}
291
Ian Rogers98379392014-02-24 16:53:16 -0800292static JDWP::JdwpTag TagFromClass(const ScopedObjectAccessUnchecked& soa, mirror::Class* c)
Ian Rogersb726dcb2012-09-05 08:57:23 -0700293 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Elliott Hughes86b00102011-12-05 17:54:26 -0800294 CHECK(c != NULL);
Elliott Hughes24437992011-11-30 14:49:33 -0800295 if (c->IsArrayClass()) {
296 return JDWP::JT_ARRAY;
297 }
Elliott Hughes24437992011-11-30 14:49:33 -0800298 if (c->IsStringClass()) {
299 return JDWP::JT_STRING;
Elliott Hughes24437992011-11-30 14:49:33 -0800300 }
Ian Rogers98379392014-02-24 16:53:16 -0800301 if (c->IsClassClass()) {
302 return JDWP::JT_CLASS_OBJECT;
303 }
304 {
305 mirror::Class* thread_class = soa.Decode<mirror::Class*>(WellKnownClasses::java_lang_Thread);
306 if (thread_class->IsAssignableFrom(c)) {
307 return JDWP::JT_THREAD;
308 }
309 }
310 {
311 mirror::Class* thread_group_class =
312 soa.Decode<mirror::Class*>(WellKnownClasses::java_lang_ThreadGroup);
313 if (thread_group_class->IsAssignableFrom(c)) {
314 return JDWP::JT_THREAD_GROUP;
315 }
316 }
317 {
318 mirror::Class* class_loader_class =
319 soa.Decode<mirror::Class*>(WellKnownClasses::java_lang_ClassLoader);
320 if (class_loader_class->IsAssignableFrom(c)) {
321 return JDWP::JT_CLASS_LOADER;
322 }
323 }
324 return JDWP::JT_OBJECT;
Elliott Hughes24437992011-11-30 14:49:33 -0800325}
326
327/*
328 * Objects declared to hold Object might actually hold a more specific
329 * type. The debugger may take a special interest in these (e.g. it
330 * wants to display the contents of Strings), so we want to return an
331 * appropriate tag.
332 *
333 * Null objects are tagged JT_OBJECT.
334 */
Ian Rogers98379392014-02-24 16:53:16 -0800335static JDWP::JdwpTag TagFromObject(const ScopedObjectAccessUnchecked& soa, mirror::Object* o)
Ian Rogersb726dcb2012-09-05 08:57:23 -0700336 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Ian Rogers98379392014-02-24 16:53:16 -0800337 return (o == NULL) ? JDWP::JT_OBJECT : TagFromClass(soa, o->GetClass());
Elliott Hughes24437992011-11-30 14:49:33 -0800338}
339
340static bool IsPrimitiveTag(JDWP::JdwpTag tag) {
341 switch (tag) {
342 case JDWP::JT_BOOLEAN:
343 case JDWP::JT_BYTE:
344 case JDWP::JT_CHAR:
345 case JDWP::JT_FLOAT:
346 case JDWP::JT_DOUBLE:
347 case JDWP::JT_INT:
348 case JDWP::JT_LONG:
349 case JDWP::JT_SHORT:
350 case JDWP::JT_VOID:
351 return true;
352 default:
353 return false;
354 }
355}
356
Elliott Hughes3bb81562011-10-21 18:52:59 -0700357/*
358 * Handle one of the JDWP name/value pairs.
359 *
360 * JDWP options are:
361 * help: if specified, show help message and bail
362 * transport: may be dt_socket or dt_shmem
363 * address: for dt_socket, "host:port", or just "port" when listening
364 * server: if "y", wait for debugger to attach; if "n", attach to debugger
365 * timeout: how long to wait for debugger to connect / listen
366 *
367 * Useful with server=n (these aren't supported yet):
368 * onthrow=<exception-name>: connect to debugger when exception thrown
369 * onuncaught=y|n: connect to debugger when uncaught exception thrown
370 * launch=<command-line>: launch the debugger itself
371 *
372 * The "transport" option is required, as is "address" if server=n.
373 */
374static bool ParseJdwpOption(const std::string& name, const std::string& value) {
375 if (name == "transport") {
376 if (value == "dt_socket") {
Elliott Hughes376a7a02011-10-24 18:35:55 -0700377 gJdwpOptions.transport = JDWP::kJdwpTransportSocket;
Elliott Hughes3bb81562011-10-21 18:52:59 -0700378 } else if (value == "dt_android_adb") {
Elliott Hughes376a7a02011-10-24 18:35:55 -0700379 gJdwpOptions.transport = JDWP::kJdwpTransportAndroidAdb;
Elliott Hughes3bb81562011-10-21 18:52:59 -0700380 } else {
381 LOG(ERROR) << "JDWP transport not supported: " << value;
382 return false;
383 }
384 } else if (name == "server") {
385 if (value == "n") {
Elliott Hughes376a7a02011-10-24 18:35:55 -0700386 gJdwpOptions.server = false;
Elliott Hughes3bb81562011-10-21 18:52:59 -0700387 } else if (value == "y") {
Elliott Hughes376a7a02011-10-24 18:35:55 -0700388 gJdwpOptions.server = true;
Elliott Hughes3bb81562011-10-21 18:52:59 -0700389 } else {
390 LOG(ERROR) << "JDWP option 'server' must be 'y' or 'n'";
391 return false;
392 }
393 } else if (name == "suspend") {
394 if (value == "n") {
Elliott Hughes376a7a02011-10-24 18:35:55 -0700395 gJdwpOptions.suspend = false;
Elliott Hughes3bb81562011-10-21 18:52:59 -0700396 } else if (value == "y") {
Elliott Hughes376a7a02011-10-24 18:35:55 -0700397 gJdwpOptions.suspend = true;
Elliott Hughes3bb81562011-10-21 18:52:59 -0700398 } else {
399 LOG(ERROR) << "JDWP option 'suspend' must be 'y' or 'n'";
400 return false;
401 }
402 } else if (name == "address") {
403 /* this is either <port> or <host>:<port> */
404 std::string port_string;
Elliott Hughes376a7a02011-10-24 18:35:55 -0700405 gJdwpOptions.host.clear();
Elliott Hughes3bb81562011-10-21 18:52:59 -0700406 std::string::size_type colon = value.find(':');
407 if (colon != std::string::npos) {
Elliott Hughes376a7a02011-10-24 18:35:55 -0700408 gJdwpOptions.host = value.substr(0, colon);
Elliott Hughes3bb81562011-10-21 18:52:59 -0700409 port_string = value.substr(colon + 1);
410 } else {
411 port_string = value;
412 }
413 if (port_string.empty()) {
414 LOG(ERROR) << "JDWP address missing port: " << value;
415 return false;
416 }
417 char* end;
Elliott Hughesba8eee12012-01-24 20:25:24 -0800418 uint64_t port = strtoul(port_string.c_str(), &end, 10);
419 if (*end != '\0' || port > 0xffff) {
Elliott Hughes3bb81562011-10-21 18:52:59 -0700420 LOG(ERROR) << "JDWP address has junk in port field: " << value;
421 return false;
422 }
Elliott Hughes376a7a02011-10-24 18:35:55 -0700423 gJdwpOptions.port = port;
Elliott Hughes3bb81562011-10-21 18:52:59 -0700424 } else if (name == "launch" || name == "onthrow" || name == "oncaught" || name == "timeout") {
425 /* valid but unsupported */
426 LOG(INFO) << "Ignoring JDWP option '" << name << "'='" << value << "'";
427 } else {
428 LOG(INFO) << "Ignoring unrecognized JDWP option '" << name << "'='" << value << "'";
429 }
430
431 return true;
432}
433
434/*
435 * Parse the latter half of a -Xrunjdwp/-agentlib:jdwp= string, e.g.:
436 * "transport=dt_socket,address=8000,server=y,suspend=n"
437 */
438bool Dbg::ParseJdwpOptions(const std::string& options) {
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -0800439 VLOG(jdwp) << "ParseJdwpOptions: " << options;
Elliott Hughes47fce012011-10-25 18:37:19 -0700440
Elliott Hughes3bb81562011-10-21 18:52:59 -0700441 std::vector<std::string> pairs;
442 Split(options, ',', pairs);
443
444 for (size_t i = 0; i < pairs.size(); ++i) {
445 std::string::size_type equals = pairs[i].find('=');
446 if (equals == std::string::npos) {
447 LOG(ERROR) << "Can't parse JDWP option '" << pairs[i] << "' in '" << options << "'";
448 return false;
449 }
450 ParseJdwpOption(pairs[i].substr(0, equals), pairs[i].substr(equals + 1));
451 }
452
Elliott Hughes376a7a02011-10-24 18:35:55 -0700453 if (gJdwpOptions.transport == JDWP::kJdwpTransportUnknown) {
Elliott Hughes3bb81562011-10-21 18:52:59 -0700454 LOG(ERROR) << "Must specify JDWP transport: " << options;
455 }
Elliott Hughes376a7a02011-10-24 18:35:55 -0700456 if (!gJdwpOptions.server && (gJdwpOptions.host.empty() || gJdwpOptions.port == 0)) {
Elliott Hughes3bb81562011-10-21 18:52:59 -0700457 LOG(ERROR) << "Must specify JDWP host and port when server=n: " << options;
458 return false;
459 }
460
461 gJdwpConfigured = true;
462 return true;
463}
464
Elliott Hughesd1cc8362011-10-24 16:58:50 -0700465void Dbg::StartJdwp() {
Elliott Hughesc0f09332012-03-26 13:27:06 -0700466 if (!gJdwpAllowed || !IsJdwpConfigured()) {
Elliott Hughes376a7a02011-10-24 18:35:55 -0700467 // No JDWP for you!
468 return;
469 }
470
Ian Rogers719d1a32014-03-06 12:13:39 -0800471 CHECK(gRegistry == nullptr);
Elliott Hughes475fc232011-10-25 15:00:35 -0700472 gRegistry = new ObjectRegistry;
473
Ian Rogers719d1a32014-03-06 12:13:39 -0800474 alloc_tracker_lock_ = new Mutex("AllocTracker lock");
Elliott Hughesd1cc8362011-10-24 16:58:50 -0700475 // Init JDWP if the debugger is enabled. This may connect out to a
476 // debugger, passively listen for a debugger, or block waiting for a
477 // debugger.
Elliott Hughes376a7a02011-10-24 18:35:55 -0700478 gJdwpState = JDWP::JdwpState::Create(&gJdwpOptions);
479 if (gJdwpState == NULL) {
Elliott Hughesf8a2df72011-12-01 12:19:54 -0800480 // We probably failed because some other process has the port already, which means that
481 // if we don't abort the user is likely to think they're talking to us when they're actually
482 // talking to that other process.
Elliott Hughes3d30d9b2011-12-07 17:35:48 -0800483 LOG(FATAL) << "Debugger thread failed to initialize";
Elliott Hughesd1cc8362011-10-24 16:58:50 -0700484 }
485
486 // If a debugger has already attached, send the "welcome" message.
487 // This may cause us to suspend all threads.
Elliott Hughes376a7a02011-10-24 18:35:55 -0700488 if (gJdwpState->IsActive()) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700489 ScopedObjectAccess soa(Thread::Current());
Elliott Hughes376a7a02011-10-24 18:35:55 -0700490 if (!gJdwpState->PostVMStart()) {
Elliott Hughes3d30d9b2011-12-07 17:35:48 -0800491 LOG(WARNING) << "Failed to post 'start' message to debugger";
Elliott Hughesd1cc8362011-10-24 16:58:50 -0700492 }
493 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700494}
495
Elliott Hughesd1cc8362011-10-24 16:58:50 -0700496void Dbg::StopJdwp() {
Sebastien Hertz0376e6b2014-02-06 18:12:59 +0100497 // Prevent the JDWP thread from processing JDWP incoming packets after we close the connection.
498 Disposed();
Elliott Hughes376a7a02011-10-24 18:35:55 -0700499 delete gJdwpState;
Ian Rogers719d1a32014-03-06 12:13:39 -0800500 gJdwpState = nullptr;
Elliott Hughes475fc232011-10-25 15:00:35 -0700501 delete gRegistry;
Ian Rogers719d1a32014-03-06 12:13:39 -0800502 gRegistry = nullptr;
503 delete alloc_tracker_lock_;
504 alloc_tracker_lock_ = nullptr;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700505}
506
Elliott Hughes767a1472011-10-26 18:49:02 -0700507void Dbg::GcDidFinish() {
508 if (gDdmHpifWhen != HPIF_WHEN_NEVER) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700509 ScopedObjectAccess soa(Thread::Current());
Elliott Hughes81ff3182012-03-23 20:35:56 -0700510 LOG(DEBUG) << "Sending heap info to DDM";
Elliott Hughes7162ad92011-10-27 14:08:42 -0700511 DdmSendHeapInfo(gDdmHpifWhen);
Elliott Hughes767a1472011-10-26 18:49:02 -0700512 }
513 if (gDdmHpsgWhen != HPSG_WHEN_NEVER) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700514 ScopedObjectAccess soa(Thread::Current());
Elliott Hughes81ff3182012-03-23 20:35:56 -0700515 LOG(DEBUG) << "Dumping heap to DDM";
Elliott Hughes6a5bd492011-10-28 14:33:57 -0700516 DdmSendHeapSegments(false);
Elliott Hughes767a1472011-10-26 18:49:02 -0700517 }
518 if (gDdmNhsgWhen != HPSG_WHEN_NEVER) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700519 ScopedObjectAccess soa(Thread::Current());
Elliott Hughes767a1472011-10-26 18:49:02 -0700520 LOG(DEBUG) << "Dumping native heap to DDM";
Elliott Hughes6a5bd492011-10-28 14:33:57 -0700521 DdmSendHeapSegments(true);
Elliott Hughes767a1472011-10-26 18:49:02 -0700522 }
523}
524
Elliott Hughes4ffd3132011-10-24 12:06:42 -0700525void Dbg::SetJdwpAllowed(bool allowed) {
526 gJdwpAllowed = allowed;
527}
528
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700529DebugInvokeReq* Dbg::GetInvokeReq() {
Elliott Hughes475fc232011-10-25 15:00:35 -0700530 return Thread::Current()->GetInvokeReq();
531}
532
533Thread* Dbg::GetDebugThread() {
534 return (gJdwpState != NULL) ? gJdwpState->GetDebugThread() : NULL;
535}
536
537void Dbg::ClearWaitForEventThread() {
538 gJdwpState->ClearWaitForEventThread();
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700539}
540
541void Dbg::Connected() {
Elliott Hughes3bb81562011-10-21 18:52:59 -0700542 CHECK(!gDebuggerConnected);
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -0800543 VLOG(jdwp) << "JDWP has attached";
Elliott Hughes3bb81562011-10-21 18:52:59 -0700544 gDebuggerConnected = true;
Elliott Hughes86964332012-02-15 19:37:42 -0800545 gDisposed = false;
546}
547
548void Dbg::Disposed() {
549 gDisposed = true;
550}
551
552bool Dbg::IsDisposed() {
553 return gDisposed;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700554}
555
Elliott Hughesa2155262011-11-16 16:26:58 -0800556void Dbg::GoActive() {
557 // Enable all debugging features, including scans for breakpoints.
558 // This is a no-op if we're already active.
559 // Only called from the JDWP handler thread.
560 if (gDebuggerActive) {
561 return;
562 }
563
Elliott Hughesc0f09332012-03-26 13:27:06 -0700564 {
565 // TODO: dalvik only warned if there were breakpoints left over. clear in Dbg::Disconnected?
jeffhao09bfc6a2012-12-11 18:11:43 -0800566 MutexLock mu(Thread::Current(), *Locks::breakpoint_lock_);
Elliott Hughesc0f09332012-03-26 13:27:06 -0700567 CHECK_EQ(gBreakpoints.size(), 0U);
568 }
Elliott Hughesa2155262011-11-16 16:26:58 -0800569
Sebastien Hertz138dbfc2013-12-04 18:15:25 +0100570 {
571 MutexLock mu(Thread::Current(), *Locks::deoptimization_lock_);
572 CHECK_EQ(gDeoptimizationRequests.size(), 0U);
573 }
574
Ian Rogers62d6c772013-02-27 08:32:07 -0800575 Runtime* runtime = Runtime::Current();
576 runtime->GetThreadList()->SuspendAll();
577 Thread* self = Thread::Current();
578 ThreadState old_state = self->SetStateUnsafe(kRunnable);
579 CHECK_NE(old_state, kRunnable);
Sebastien Hertz138dbfc2013-12-04 18:15:25 +0100580 runtime->GetInstrumentation()->EnableDeoptimization();
Ian Rogers62d6c772013-02-27 08:32:07 -0800581 runtime->GetInstrumentation()->AddListener(&gDebugInstrumentationListener,
582 instrumentation::Instrumentation::kMethodEntered |
583 instrumentation::Instrumentation::kMethodExited |
Jeff Hao14dd5a82013-04-11 10:23:36 -0700584 instrumentation::Instrumentation::kDexPcMoved |
585 instrumentation::Instrumentation::kExceptionCaught);
Elliott Hughesa2155262011-11-16 16:26:58 -0800586 gDebuggerActive = true;
Ian Rogers62d6c772013-02-27 08:32:07 -0800587 CHECK_EQ(self->SetStateUnsafe(old_state), kRunnable);
588 runtime->GetThreadList()->ResumeAll();
589
590 LOG(INFO) << "Debugger is active";
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700591}
592
593void Dbg::Disconnected() {
Elliott Hughes234ab152011-10-26 14:02:26 -0700594 CHECK(gDebuggerConnected);
595
Elliott Hughesc0f09332012-03-26 13:27:06 -0700596 LOG(INFO) << "Debugger is no longer active";
Elliott Hughes234ab152011-10-26 14:02:26 -0700597
Ian Rogers62d6c772013-02-27 08:32:07 -0800598 // Suspend all threads and exclusively acquire the mutator lock. Set the state of the thread
599 // to kRunnable to avoid scoped object access transitions. Remove the debugger as a listener
600 // and clear the object registry.
601 Runtime* runtime = Runtime::Current();
602 runtime->GetThreadList()->SuspendAll();
603 Thread* self = Thread::Current();
604 ThreadState old_state = self->SetStateUnsafe(kRunnable);
Sebastien Hertzaaea7342014-02-25 15:10:04 +0100605
606 // Debugger may not be active at this point.
607 if (gDebuggerActive) {
608 {
609 // Since we're going to disable deoptimization, we clear the deoptimization requests queue.
610 // This prevents us from having any pending deoptimization request when the debugger attaches
611 // to us again while no event has been requested yet.
612 MutexLock mu(Thread::Current(), *Locks::deoptimization_lock_);
613 gDeoptimizationRequests.clear();
614 }
615 runtime->GetInstrumentation()->RemoveListener(&gDebugInstrumentationListener,
616 instrumentation::Instrumentation::kMethodEntered |
617 instrumentation::Instrumentation::kMethodExited |
618 instrumentation::Instrumentation::kDexPcMoved |
619 instrumentation::Instrumentation::kExceptionCaught);
620 runtime->GetInstrumentation()->DisableDeoptimization();
621 gDebuggerActive = false;
Sebastien Hertz138dbfc2013-12-04 18:15:25 +0100622 }
Elliott Hughes234ab152011-10-26 14:02:26 -0700623 gRegistry->Clear();
624 gDebuggerConnected = false;
Ian Rogers62d6c772013-02-27 08:32:07 -0800625 CHECK_EQ(self->SetStateUnsafe(old_state), kRunnable);
626 runtime->GetThreadList()->ResumeAll();
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700627}
628
Elliott Hughesc0f09332012-03-26 13:27:06 -0700629bool Dbg::IsDebuggerActive() {
Elliott Hughes3bb81562011-10-21 18:52:59 -0700630 return gDebuggerActive;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700631}
632
Elliott Hughesc0f09332012-03-26 13:27:06 -0700633bool Dbg::IsJdwpConfigured() {
Elliott Hughes3bb81562011-10-21 18:52:59 -0700634 return gJdwpConfigured;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700635}
636
637int64_t Dbg::LastDebuggerActivity() {
Elliott Hughesca951522011-12-05 12:01:32 -0800638 return gJdwpState->LastDebuggerActivity();
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700639}
640
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700641void Dbg::UndoDebuggerSuspensions() {
Elliott Hughes234ab152011-10-26 14:02:26 -0700642 Runtime::Current()->GetThreadList()->UndoDebuggerSuspensions();
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700643}
644
Elliott Hughes88d63092013-01-09 09:55:54 -0800645std::string Dbg::GetClassName(JDWP::RefTypeId class_id) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800646 mirror::Object* o = gRegistry->Get<mirror::Object*>(class_id);
Elliott Hughes436e3722012-02-17 20:01:47 -0800647 if (o == NULL) {
648 return "NULL";
649 }
Elliott Hughes64f574f2013-02-20 14:57:12 -0800650 if (o == ObjectRegistry::kInvalidObject) {
Elliott Hughes88d63092013-01-09 09:55:54 -0800651 return StringPrintf("invalid object %p", reinterpret_cast<void*>(class_id));
Elliott Hughes436e3722012-02-17 20:01:47 -0800652 }
653 if (!o->IsClass()) {
Brian Carlstrom7934ac22013-07-26 10:54:15 -0700654 return StringPrintf("non-class %p", o); // This is only used for debugging output anyway.
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -0800655 }
Elliott Hughesc308a5d2012-02-16 17:12:06 -0800656 return DescriptorToName(ClassHelper(o->AsClass()).GetDescriptor());
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700657}
658
Elliott Hughes88d63092013-01-09 09:55:54 -0800659JDWP::JdwpError Dbg::GetClassObject(JDWP::RefTypeId id, JDWP::ObjectId& class_object_id) {
Elliott Hughes436e3722012-02-17 20:01:47 -0800660 JDWP::JdwpError status;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800661 mirror::Class* c = DecodeClass(id, status);
Elliott Hughes436e3722012-02-17 20:01:47 -0800662 if (c == NULL) {
663 return status;
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -0800664 }
Elliott Hughes88d63092013-01-09 09:55:54 -0800665 class_object_id = gRegistry->Add(c);
Elliott Hughes436e3722012-02-17 20:01:47 -0800666 return JDWP::ERR_NONE;
Elliott Hughes86964332012-02-15 19:37:42 -0800667}
668
Elliott Hughes88d63092013-01-09 09:55:54 -0800669JDWP::JdwpError Dbg::GetSuperclass(JDWP::RefTypeId id, JDWP::RefTypeId& superclass_id) {
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -0800670 JDWP::JdwpError status;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800671 mirror::Class* c = DecodeClass(id, status);
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -0800672 if (c == NULL) {
673 return status;
674 }
675 if (c->IsInterface()) {
676 // http://code.google.com/p/android/issues/detail?id=20856
Elliott Hughes88d63092013-01-09 09:55:54 -0800677 superclass_id = 0;
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -0800678 } else {
Elliott Hughes88d63092013-01-09 09:55:54 -0800679 superclass_id = gRegistry->Add(c->GetSuperClass());
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -0800680 }
681 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700682}
683
Elliott Hughes436e3722012-02-17 20:01:47 -0800684JDWP::JdwpError Dbg::GetClassLoader(JDWP::RefTypeId id, JDWP::ExpandBuf* pReply) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800685 mirror::Object* o = gRegistry->Get<mirror::Object*>(id);
Elliott Hughes64f574f2013-02-20 14:57:12 -0800686 if (o == NULL || o == ObjectRegistry::kInvalidObject) {
Elliott Hughes436e3722012-02-17 20:01:47 -0800687 return JDWP::ERR_INVALID_OBJECT;
688 }
689 expandBufAddObjectId(pReply, gRegistry->Add(o->GetClass()->GetClassLoader()));
690 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700691}
692
Elliott Hughes436e3722012-02-17 20:01:47 -0800693JDWP::JdwpError Dbg::GetModifiers(JDWP::RefTypeId id, JDWP::ExpandBuf* pReply) {
694 JDWP::JdwpError status;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800695 mirror::Class* c = DecodeClass(id, status);
Elliott Hughes436e3722012-02-17 20:01:47 -0800696 if (c == NULL) {
697 return status;
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -0800698 }
Elliott Hughes436e3722012-02-17 20:01:47 -0800699
700 uint32_t access_flags = c->GetAccessFlags() & kAccJavaFlagsMask;
701
Yevgeny Roubande34eea2014-02-15 01:06:03 +0700702 // Set ACC_SUPER. Dex files don't contain this flag but only classes are supposed to have it set,
703 // not interfaces.
Elliott Hughes436e3722012-02-17 20:01:47 -0800704 // Class.getModifiers doesn't return it, but JDWP does, so we set it here.
Yevgeny Roubande34eea2014-02-15 01:06:03 +0700705 if ((access_flags & kAccInterface) == 0) {
706 access_flags |= kAccSuper;
707 }
Elliott Hughes436e3722012-02-17 20:01:47 -0800708
709 expandBufAdd4BE(pReply, access_flags);
710
711 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700712}
713
Elliott Hughesf327e072013-01-09 16:01:26 -0800714JDWP::JdwpError Dbg::GetMonitorInfo(JDWP::ObjectId object_id, JDWP::ExpandBuf* reply)
715 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800716 mirror::Object* o = gRegistry->Get<mirror::Object*>(object_id);
Elliott Hughes64f574f2013-02-20 14:57:12 -0800717 if (o == NULL || o == ObjectRegistry::kInvalidObject) {
Elliott Hughesf327e072013-01-09 16:01:26 -0800718 return JDWP::ERR_INVALID_OBJECT;
719 }
720
721 // Ensure all threads are suspended while we read objects' lock words.
722 Thread* self = Thread::Current();
723 Locks::mutator_lock_->SharedUnlock(self);
724 Locks::mutator_lock_->ExclusiveLock(self);
725
726 MonitorInfo monitor_info(o);
727
728 Locks::mutator_lock_->ExclusiveUnlock(self);
729 Locks::mutator_lock_->SharedLock(self);
730
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700731 if (monitor_info.owner_ != NULL) {
732 expandBufAddObjectId(reply, gRegistry->Add(monitor_info.owner_->GetPeer()));
Elliott Hughesf327e072013-01-09 16:01:26 -0800733 } else {
734 expandBufAddObjectId(reply, gRegistry->Add(NULL));
735 }
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700736 expandBufAdd4BE(reply, monitor_info.entry_count_);
737 expandBufAdd4BE(reply, monitor_info.waiters_.size());
738 for (size_t i = 0; i < monitor_info.waiters_.size(); ++i) {
739 expandBufAddObjectId(reply, gRegistry->Add(monitor_info.waiters_[i]->GetPeer()));
Elliott Hughesf327e072013-01-09 16:01:26 -0800740 }
741 return JDWP::ERR_NONE;
742}
743
Elliott Hughes734b8c62013-01-11 15:32:45 -0800744JDWP::JdwpError Dbg::GetOwnedMonitors(JDWP::ObjectId thread_id,
745 std::vector<JDWP::ObjectId>& monitors,
746 std::vector<uint32_t>& stack_depths)
Elliott Hughes4993bbc2013-01-10 15:41:25 -0800747 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
748 ScopedObjectAccessUnchecked soa(Thread::Current());
749 MutexLock mu(soa.Self(), *Locks::thread_list_lock_);
750 Thread* thread;
751 JDWP::JdwpError error = DecodeThread(soa, thread_id, thread);
752 if (error != JDWP::ERR_NONE) {
753 return error;
754 }
755 if (!IsSuspendedForDebugger(soa, thread)) {
756 return JDWP::ERR_THREAD_NOT_SUSPENDED;
757 }
758
759 struct OwnedMonitorVisitor : public StackVisitor {
Ian Rogers7a22fa62013-01-23 12:16:16 -0800760 OwnedMonitorVisitor(Thread* thread, Context* context)
Elliott Hughes4993bbc2013-01-10 15:41:25 -0800761 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_)
Ian Rogers7a22fa62013-01-23 12:16:16 -0800762 : StackVisitor(thread, context), current_stack_depth(0) {}
Elliott Hughes4993bbc2013-01-10 15:41:25 -0800763
764 // TODO: Enable annotalysis. We know lock is held in constructor, but abstraction confuses
765 // annotalysis.
766 bool VisitFrame() NO_THREAD_SAFETY_ANALYSIS {
767 if (!GetMethod()->IsRuntimeMethod()) {
768 Monitor::VisitLocks(this, AppendOwnedMonitors, this);
Elliott Hughes734b8c62013-01-11 15:32:45 -0800769 ++current_stack_depth;
Elliott Hughes4993bbc2013-01-10 15:41:25 -0800770 }
771 return true;
772 }
773
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800774 static void AppendOwnedMonitors(mirror::Object* owned_monitor, void* arg) {
Ian Rogers7a22fa62013-01-23 12:16:16 -0800775 OwnedMonitorVisitor* visitor = reinterpret_cast<OwnedMonitorVisitor*>(arg);
Elliott Hughes734b8c62013-01-11 15:32:45 -0800776 visitor->monitors.push_back(owned_monitor);
777 visitor->stack_depths.push_back(visitor->current_stack_depth);
Elliott Hughes4993bbc2013-01-10 15:41:25 -0800778 }
779
Elliott Hughes734b8c62013-01-11 15:32:45 -0800780 size_t current_stack_depth;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800781 std::vector<mirror::Object*> monitors;
Elliott Hughes734b8c62013-01-11 15:32:45 -0800782 std::vector<uint32_t> stack_depths;
Elliott Hughes4993bbc2013-01-10 15:41:25 -0800783 };
Ian Rogers7a22fa62013-01-23 12:16:16 -0800784 UniquePtr<Context> context(Context::Create());
785 OwnedMonitorVisitor visitor(thread, context.get());
Elliott Hughes4993bbc2013-01-10 15:41:25 -0800786 visitor.WalkStack();
787
788 for (size_t i = 0; i < visitor.monitors.size(); ++i) {
789 monitors.push_back(gRegistry->Add(visitor.monitors[i]));
Elliott Hughes734b8c62013-01-11 15:32:45 -0800790 stack_depths.push_back(visitor.stack_depths[i]);
Elliott Hughes4993bbc2013-01-10 15:41:25 -0800791 }
792
793 return JDWP::ERR_NONE;
794}
795
Elliott Hughesf9501702013-01-11 11:22:27 -0800796JDWP::JdwpError Dbg::GetContendedMonitor(JDWP::ObjectId thread_id, JDWP::ObjectId& contended_monitor)
797 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
798 ScopedObjectAccessUnchecked soa(Thread::Current());
799 MutexLock mu(soa.Self(), *Locks::thread_list_lock_);
800 Thread* thread;
801 JDWP::JdwpError error = DecodeThread(soa, thread_id, thread);
802 if (error != JDWP::ERR_NONE) {
803 return error;
804 }
805 if (!IsSuspendedForDebugger(soa, thread)) {
806 return JDWP::ERR_THREAD_NOT_SUSPENDED;
807 }
808
809 contended_monitor = gRegistry->Add(Monitor::GetContendedMonitor(thread));
810
811 return JDWP::ERR_NONE;
812}
813
Elliott Hughesec0f83d2013-01-15 16:54:08 -0800814JDWP::JdwpError Dbg::GetInstanceCounts(const std::vector<JDWP::RefTypeId>& class_ids,
815 std::vector<uint64_t>& counts)
816 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Mathieu Chartier412c7fc2014-02-07 12:18:39 -0800817 gc::Heap* heap = Runtime::Current()->GetHeap();
818 heap->CollectGarbage(false);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800819 std::vector<mirror::Class*> classes;
Elliott Hughesec0f83d2013-01-15 16:54:08 -0800820 counts.clear();
821 for (size_t i = 0; i < class_ids.size(); ++i) {
822 JDWP::JdwpError status;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800823 mirror::Class* c = DecodeClass(class_ids[i], status);
Elliott Hughesec0f83d2013-01-15 16:54:08 -0800824 if (c == NULL) {
825 return status;
826 }
827 classes.push_back(c);
828 counts.push_back(0);
829 }
Mathieu Chartier412c7fc2014-02-07 12:18:39 -0800830 heap->CountInstances(classes, false, &counts[0]);
Elliott Hughesec0f83d2013-01-15 16:54:08 -0800831 return JDWP::ERR_NONE;
832}
833
Elliott Hughes3b78c942013-01-15 17:35:41 -0800834JDWP::JdwpError Dbg::GetInstances(JDWP::RefTypeId class_id, int32_t max_count, std::vector<JDWP::ObjectId>& instances)
835 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Mathieu Chartier412c7fc2014-02-07 12:18:39 -0800836 gc::Heap* heap = Runtime::Current()->GetHeap();
837 // We only want reachable instances, so do a GC.
838 heap->CollectGarbage(false);
Elliott Hughes3b78c942013-01-15 17:35:41 -0800839 JDWP::JdwpError status;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800840 mirror::Class* c = DecodeClass(class_id, status);
Mathieu Chartier412c7fc2014-02-07 12:18:39 -0800841 if (c == nullptr) {
Elliott Hughes3b78c942013-01-15 17:35:41 -0800842 return status;
843 }
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800844 std::vector<mirror::Object*> raw_instances;
Elliott Hughes3b78c942013-01-15 17:35:41 -0800845 Runtime::Current()->GetHeap()->GetInstances(c, max_count, raw_instances);
846 for (size_t i = 0; i < raw_instances.size(); ++i) {
847 instances.push_back(gRegistry->Add(raw_instances[i]));
848 }
849 return JDWP::ERR_NONE;
850}
851
Elliott Hughes0cbaff52013-01-16 15:28:01 -0800852JDWP::JdwpError Dbg::GetReferringObjects(JDWP::ObjectId object_id, int32_t max_count,
853 std::vector<JDWP::ObjectId>& referring_objects)
854 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Mathieu Chartier412c7fc2014-02-07 12:18:39 -0800855 gc::Heap* heap = Runtime::Current()->GetHeap();
856 heap->CollectGarbage(false);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800857 mirror::Object* o = gRegistry->Get<mirror::Object*>(object_id);
Elliott Hughes64f574f2013-02-20 14:57:12 -0800858 if (o == NULL || o == ObjectRegistry::kInvalidObject) {
Elliott Hughes0cbaff52013-01-16 15:28:01 -0800859 return JDWP::ERR_INVALID_OBJECT;
860 }
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800861 std::vector<mirror::Object*> raw_instances;
Mathieu Chartier412c7fc2014-02-07 12:18:39 -0800862 heap->GetReferringObjects(o, max_count, raw_instances);
Elliott Hughes0cbaff52013-01-16 15:28:01 -0800863 for (size_t i = 0; i < raw_instances.size(); ++i) {
864 referring_objects.push_back(gRegistry->Add(raw_instances[i]));
865 }
866 return JDWP::ERR_NONE;
867}
868
Elliott Hughes64f574f2013-02-20 14:57:12 -0800869JDWP::JdwpError Dbg::DisableCollection(JDWP::ObjectId object_id)
870 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Sebastien Hertze96060a2013-12-11 12:06:28 +0100871 mirror::Object* o = gRegistry->Get<mirror::Object*>(object_id);
872 if (o == NULL || o == ObjectRegistry::kInvalidObject) {
873 return JDWP::ERR_INVALID_OBJECT;
874 }
Elliott Hughes64f574f2013-02-20 14:57:12 -0800875 gRegistry->DisableCollection(object_id);
876 return JDWP::ERR_NONE;
877}
878
879JDWP::JdwpError Dbg::EnableCollection(JDWP::ObjectId object_id)
880 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Sebastien Hertze96060a2013-12-11 12:06:28 +0100881 mirror::Object* o = gRegistry->Get<mirror::Object*>(object_id);
882 // Unlike DisableCollection, JDWP specs do not state an invalid object causes an error. The RI
883 // also ignores these cases and never return an error. However it's not obvious why this command
884 // should behave differently from DisableCollection and IsCollected commands. So let's be more
885 // strict and return an error if this happens.
886 if (o == NULL || o == ObjectRegistry::kInvalidObject) {
887 return JDWP::ERR_INVALID_OBJECT;
888 }
Elliott Hughes64f574f2013-02-20 14:57:12 -0800889 gRegistry->EnableCollection(object_id);
890 return JDWP::ERR_NONE;
891}
892
893JDWP::JdwpError Dbg::IsCollected(JDWP::ObjectId object_id, bool& is_collected)
894 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Sebastien Hertz65637eb2014-01-10 17:40:02 +0100895 if (object_id == 0) {
896 // Null object id is invalid.
Sebastien Hertze96060a2013-12-11 12:06:28 +0100897 return JDWP::ERR_INVALID_OBJECT;
898 }
Sebastien Hertz65637eb2014-01-10 17:40:02 +0100899 // JDWP specs state an INVALID_OBJECT error is returned if the object ID is not valid. However
900 // the RI seems to ignore this and assume object has been collected.
901 mirror::Object* o = gRegistry->Get<mirror::Object*>(object_id);
902 if (o == NULL || o == ObjectRegistry::kInvalidObject) {
903 is_collected = true;
904 } else {
905 is_collected = gRegistry->IsCollected(object_id);
906 }
Elliott Hughes64f574f2013-02-20 14:57:12 -0800907 return JDWP::ERR_NONE;
908}
909
910void Dbg::DisposeObject(JDWP::ObjectId object_id, uint32_t reference_count)
911 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
912 gRegistry->DisposeObject(object_id, reference_count);
913}
914
Elliott Hughes88d63092013-01-09 09:55:54 -0800915JDWP::JdwpError Dbg::GetReflectedType(JDWP::RefTypeId class_id, JDWP::ExpandBuf* pReply) {
Elliott Hughes436e3722012-02-17 20:01:47 -0800916 JDWP::JdwpError status;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800917 mirror::Class* c = DecodeClass(class_id, status);
Elliott Hughes436e3722012-02-17 20:01:47 -0800918 if (c == NULL) {
919 return status;
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -0800920 }
Elliott Hughes436e3722012-02-17 20:01:47 -0800921
922 expandBufAdd1(pReply, c->IsInterface() ? JDWP::TT_INTERFACE : JDWP::TT_CLASS);
Elliott Hughes88d63092013-01-09 09:55:54 -0800923 expandBufAddRefTypeId(pReply, class_id);
Elliott Hughes436e3722012-02-17 20:01:47 -0800924 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700925}
926
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -0800927void Dbg::GetClassList(std::vector<JDWP::RefTypeId>& classes) {
Elliott Hughesa2155262011-11-16 16:26:58 -0800928 // Get the complete list of reference classes (i.e. all classes except
929 // the primitive types).
930 // Returns a newly-allocated buffer full of RefTypeId values.
931 struct ClassListCreator {
Elliott Hughesba8eee12012-01-24 20:25:24 -0800932 explicit ClassListCreator(std::vector<JDWP::RefTypeId>& classes) : classes(classes) {
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -0800933 }
934
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800935 static bool Visit(mirror::Class* c, void* arg) {
Elliott Hughesa2155262011-11-16 16:26:58 -0800936 return reinterpret_cast<ClassListCreator*>(arg)->Visit(c);
937 }
938
Elliott Hughes64f574f2013-02-20 14:57:12 -0800939 // TODO: Enable annotalysis. We know lock is held in constructor, but abstraction confuses
940 // annotalysis.
941 bool Visit(mirror::Class* c) NO_THREAD_SAFETY_ANALYSIS {
Elliott Hughesa2155262011-11-16 16:26:58 -0800942 if (!c->IsPrimitive()) {
Elliott Hughes64f574f2013-02-20 14:57:12 -0800943 classes.push_back(gRegistry->AddRefType(c));
Elliott Hughesa2155262011-11-16 16:26:58 -0800944 }
945 return true;
946 }
947
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -0800948 std::vector<JDWP::RefTypeId>& classes;
Elliott Hughesa2155262011-11-16 16:26:58 -0800949 };
950
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -0800951 ClassListCreator clc(classes);
Elliott Hughesa2155262011-11-16 16:26:58 -0800952 Runtime::Current()->GetClassLinker()->VisitClasses(ClassListCreator::Visit, &clc);
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700953}
954
Elliott Hughes88d63092013-01-09 09:55:54 -0800955JDWP::JdwpError Dbg::GetClassInfo(JDWP::RefTypeId class_id, JDWP::JdwpTypeTag* pTypeTag, uint32_t* pStatus, std::string* pDescriptor) {
Elliott Hughes436e3722012-02-17 20:01:47 -0800956 JDWP::JdwpError status;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800957 mirror::Class* c = DecodeClass(class_id, status);
Elliott Hughes436e3722012-02-17 20:01:47 -0800958 if (c == NULL) {
959 return status;
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -0800960 }
961
Elliott Hughesa2155262011-11-16 16:26:58 -0800962 if (c->IsArrayClass()) {
963 *pStatus = JDWP::CS_VERIFIED | JDWP::CS_PREPARED;
964 *pTypeTag = JDWP::TT_ARRAY;
965 } else {
966 if (c->IsErroneous()) {
967 *pStatus = JDWP::CS_ERROR;
968 } else {
969 *pStatus = JDWP::CS_VERIFIED | JDWP::CS_PREPARED | JDWP::CS_INITIALIZED;
970 }
971 *pTypeTag = c->IsInterface() ? JDWP::TT_INTERFACE : JDWP::TT_CLASS;
972 }
973
974 if (pDescriptor != NULL) {
Ian Rogersdfb325e2013-10-30 01:00:44 -0700975 *pDescriptor = ClassHelper(c).GetDescriptor();
Elliott Hughesa2155262011-11-16 16:26:58 -0800976 }
Elliott Hughes436e3722012-02-17 20:01:47 -0800977 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700978}
979
Elliott Hughesc3b77c72011-12-15 20:56:48 -0800980void Dbg::FindLoadedClassBySignature(const char* descriptor, std::vector<JDWP::RefTypeId>& ids) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800981 std::vector<mirror::Class*> classes;
Elliott Hughes6fa602d2011-12-02 17:54:25 -0800982 Runtime::Current()->GetClassLinker()->LookupClasses(descriptor, classes);
983 ids.clear();
984 for (size_t i = 0; i < classes.size(); ++i) {
985 ids.push_back(gRegistry->Add(classes[i]));
986 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700987}
988
Elliott Hughes64f574f2013-02-20 14:57:12 -0800989JDWP::JdwpError Dbg::GetReferenceType(JDWP::ObjectId object_id, JDWP::ExpandBuf* pReply)
990 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800991 mirror::Object* o = gRegistry->Get<mirror::Object*>(object_id);
Elliott Hughes64f574f2013-02-20 14:57:12 -0800992 if (o == NULL || o == ObjectRegistry::kInvalidObject) {
Elliott Hughes2435a572012-02-17 16:07:41 -0800993 return JDWP::ERR_INVALID_OBJECT;
Elliott Hughes499c5132011-11-17 14:55:11 -0800994 }
Elliott Hughes2435a572012-02-17 16:07:41 -0800995
996 JDWP::JdwpTypeTag type_tag;
997 if (o->GetClass()->IsArrayClass()) {
998 type_tag = JDWP::TT_ARRAY;
999 } else if (o->GetClass()->IsInterface()) {
1000 type_tag = JDWP::TT_INTERFACE;
1001 } else {
1002 type_tag = JDWP::TT_CLASS;
1003 }
Elliott Hughes64f574f2013-02-20 14:57:12 -08001004 JDWP::RefTypeId type_id = gRegistry->AddRefType(o->GetClass());
Elliott Hughes2435a572012-02-17 16:07:41 -08001005
1006 expandBufAdd1(pReply, type_tag);
1007 expandBufAddRefTypeId(pReply, type_id);
1008
1009 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001010}
1011
Ian Rogersfc0e94b2013-09-23 23:51:32 -07001012JDWP::JdwpError Dbg::GetSignature(JDWP::RefTypeId class_id, std::string* signature) {
Elliott Hughes1fe7afb2012-02-13 17:23:03 -08001013 JDWP::JdwpError status;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001014 mirror::Class* c = DecodeClass(class_id, status);
Elliott Hughes1fe7afb2012-02-13 17:23:03 -08001015 if (c == NULL) {
1016 return status;
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -08001017 }
Ian Rogersdfb325e2013-10-30 01:00:44 -07001018 *signature = ClassHelper(c).GetDescriptor();
Elliott Hughes1fe7afb2012-02-13 17:23:03 -08001019 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001020}
1021
Elliott Hughes88d63092013-01-09 09:55:54 -08001022JDWP::JdwpError Dbg::GetSourceFile(JDWP::RefTypeId class_id, std::string& result) {
Elliott Hughes436e3722012-02-17 20:01:47 -08001023 JDWP::JdwpError status;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001024 mirror::Class* c = DecodeClass(class_id, status);
Elliott Hughes436e3722012-02-17 20:01:47 -08001025 if (c == NULL) {
1026 return status;
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -08001027 }
Sebastien Hertzb7054ba2014-03-13 11:52:31 +01001028 if (c->IsProxyClass()) {
1029 return JDWP::ERR_ABSENT_INFORMATION;
1030 }
Elliott Hughes436e3722012-02-17 20:01:47 -08001031 result = ClassHelper(c).GetSourceFile();
1032 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001033}
1034
Elliott Hughes88d63092013-01-09 09:55:54 -08001035JDWP::JdwpError Dbg::GetObjectTag(JDWP::ObjectId object_id, uint8_t& tag) {
Ian Rogers98379392014-02-24 16:53:16 -08001036 ScopedObjectAccessUnchecked soa(Thread::Current());
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001037 mirror::Object* o = gRegistry->Get<mirror::Object*>(object_id);
Elliott Hughes64f574f2013-02-20 14:57:12 -08001038 if (o == ObjectRegistry::kInvalidObject) {
Elliott Hughes546b9862012-06-20 16:06:13 -07001039 return JDWP::ERR_INVALID_OBJECT;
1040 }
Ian Rogers98379392014-02-24 16:53:16 -08001041 tag = TagFromObject(soa, o);
Elliott Hughes546b9862012-06-20 16:06:13 -07001042 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001043}
1044
Elliott Hughesaed4be92011-12-02 16:16:23 -08001045size_t Dbg::GetTagWidth(JDWP::JdwpTag tag) {
Elliott Hughesdbb40792011-11-18 17:05:22 -08001046 switch (tag) {
1047 case JDWP::JT_VOID:
1048 return 0;
1049 case JDWP::JT_BYTE:
1050 case JDWP::JT_BOOLEAN:
1051 return 1;
1052 case JDWP::JT_CHAR:
1053 case JDWP::JT_SHORT:
1054 return 2;
1055 case JDWP::JT_FLOAT:
1056 case JDWP::JT_INT:
1057 return 4;
1058 case JDWP::JT_ARRAY:
1059 case JDWP::JT_OBJECT:
1060 case JDWP::JT_STRING:
1061 case JDWP::JT_THREAD:
1062 case JDWP::JT_THREAD_GROUP:
1063 case JDWP::JT_CLASS_LOADER:
1064 case JDWP::JT_CLASS_OBJECT:
1065 return sizeof(JDWP::ObjectId);
1066 case JDWP::JT_DOUBLE:
1067 case JDWP::JT_LONG:
1068 return 8;
1069 default:
Elliott Hughes3d30d9b2011-12-07 17:35:48 -08001070 LOG(FATAL) << "Unknown tag " << tag;
Elliott Hughesdbb40792011-11-18 17:05:22 -08001071 return -1;
1072 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001073}
1074
Elliott Hughes88d63092013-01-09 09:55:54 -08001075JDWP::JdwpError Dbg::GetArrayLength(JDWP::ObjectId array_id, int& length) {
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -08001076 JDWP::JdwpError status;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001077 mirror::Array* a = DecodeArray(array_id, status);
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -08001078 if (a == NULL) {
1079 return status;
Elliott Hughes24437992011-11-30 14:49:33 -08001080 }
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -08001081 length = a->GetLength();
1082 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001083}
1084
Elliott Hughes88d63092013-01-09 09:55:54 -08001085JDWP::JdwpError Dbg::OutputArray(JDWP::ObjectId array_id, int offset, int count, JDWP::ExpandBuf* pReply) {
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -08001086 JDWP::JdwpError status;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001087 mirror::Array* a = DecodeArray(array_id, status);
Ian Rogers98379392014-02-24 16:53:16 -08001088 if (a == nullptr) {
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -08001089 return status;
1090 }
Elliott Hughes24437992011-11-30 14:49:33 -08001091
1092 if (offset < 0 || count < 0 || offset > a->GetLength() || a->GetLength() - offset < count) {
1093 LOG(WARNING) << __FUNCTION__ << " access out of bounds: offset=" << offset << "; count=" << count;
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -08001094 return JDWP::ERR_INVALID_LENGTH;
Elliott Hughes24437992011-11-30 14:49:33 -08001095 }
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001096 std::string descriptor(ClassHelper(a->GetClass()).GetDescriptor());
Elliott Hughes24437992011-11-30 14:49:33 -08001097 JDWP::JdwpTag tag = BasicTagFromDescriptor(descriptor.c_str() + 1);
1098
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -08001099 expandBufAdd1(pReply, tag);
1100 expandBufAdd4BE(pReply, count);
1101
Elliott Hughes24437992011-11-30 14:49:33 -08001102 if (IsPrimitiveTag(tag)) {
1103 size_t width = GetTagWidth(tag);
Elliott Hughes24437992011-11-30 14:49:33 -08001104 uint8_t* dst = expandBufAddSpace(pReply, count * width);
1105 if (width == 8) {
Ian Rogersef7d42f2014-01-06 12:55:46 -08001106 const uint64_t* src8 = reinterpret_cast<uint64_t*>(a->GetRawData(sizeof(uint64_t), 0));
Elliott Hughes24437992011-11-30 14:49:33 -08001107 for (int i = 0; i < count; ++i) JDWP::Write8BE(&dst, src8[offset + i]);
1108 } else if (width == 4) {
Ian Rogersef7d42f2014-01-06 12:55:46 -08001109 const uint32_t* src4 = reinterpret_cast<uint32_t*>(a->GetRawData(sizeof(uint32_t), 0));
Elliott Hughes24437992011-11-30 14:49:33 -08001110 for (int i = 0; i < count; ++i) JDWP::Write4BE(&dst, src4[offset + i]);
1111 } else if (width == 2) {
Ian Rogersef7d42f2014-01-06 12:55:46 -08001112 const uint16_t* src2 = reinterpret_cast<uint16_t*>(a->GetRawData(sizeof(uint16_t), 0));
Elliott Hughes24437992011-11-30 14:49:33 -08001113 for (int i = 0; i < count; ++i) JDWP::Write2BE(&dst, src2[offset + i]);
1114 } else {
Ian Rogersef7d42f2014-01-06 12:55:46 -08001115 const uint8_t* src = reinterpret_cast<uint8_t*>(a->GetRawData(sizeof(uint8_t), 0));
Elliott Hughes24437992011-11-30 14:49:33 -08001116 memcpy(dst, &src[offset * width], count * width);
1117 }
1118 } else {
Ian Rogers98379392014-02-24 16:53:16 -08001119 ScopedObjectAccessUnchecked soa(Thread::Current());
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001120 mirror::ObjectArray<mirror::Object>* oa = a->AsObjectArray<mirror::Object>();
Elliott Hughes24437992011-11-30 14:49:33 -08001121 for (int i = 0; i < count; ++i) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001122 mirror::Object* element = oa->Get(offset + i);
Ian Rogers98379392014-02-24 16:53:16 -08001123 JDWP::JdwpTag specific_tag = (element != nullptr) ? TagFromObject(soa, element)
1124 : tag;
Elliott Hughes24437992011-11-30 14:49:33 -08001125 expandBufAdd1(pReply, specific_tag);
1126 expandBufAddObjectId(pReply, gRegistry->Add(element));
1127 }
1128 }
1129
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -08001130 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001131}
1132
Ian Rogersef7d42f2014-01-06 12:55:46 -08001133template <typename T>
1134static void CopyArrayData(mirror::Array* a, JDWP::Request& src, int offset, int count)
1135 NO_THREAD_SAFETY_ANALYSIS {
1136 // TODO: fix when annotalysis correctly handles non-member functions.
Elliott Hughes4b9702c2013-02-20 18:13:24 -08001137 DCHECK(a->GetClass()->IsPrimitiveArray());
1138
Ian Rogersef7d42f2014-01-06 12:55:46 -08001139 T* dst = reinterpret_cast<T*>(a->GetRawData(sizeof(T), offset));
Elliott Hughes4b9702c2013-02-20 18:13:24 -08001140 for (int i = 0; i < count; ++i) {
1141 *dst++ = src.ReadValue(sizeof(T));
1142 }
1143}
1144
Elliott Hughes88d63092013-01-09 09:55:54 -08001145JDWP::JdwpError Dbg::SetArrayElements(JDWP::ObjectId array_id, int offset, int count,
Elliott Hughes4b9702c2013-02-20 18:13:24 -08001146 JDWP::Request& request)
Ian Rogersb726dcb2012-09-05 08:57:23 -07001147 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -08001148 JDWP::JdwpError status;
Elliott Hughes4b9702c2013-02-20 18:13:24 -08001149 mirror::Array* dst = DecodeArray(array_id, status);
1150 if (dst == NULL) {
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -08001151 return status;
1152 }
Elliott Hughesf03b8f62011-12-02 14:26:25 -08001153
Elliott Hughes4b9702c2013-02-20 18:13:24 -08001154 if (offset < 0 || count < 0 || offset > dst->GetLength() || dst->GetLength() - offset < count) {
Elliott Hughesf03b8f62011-12-02 14:26:25 -08001155 LOG(WARNING) << __FUNCTION__ << " access out of bounds: offset=" << offset << "; count=" << count;
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -08001156 return JDWP::ERR_INVALID_LENGTH;
Elliott Hughesf03b8f62011-12-02 14:26:25 -08001157 }
Ian Rogersfc0e94b2013-09-23 23:51:32 -07001158 const char* descriptor = ClassHelper(dst->GetClass()).GetDescriptor();
1159 JDWP::JdwpTag tag = BasicTagFromDescriptor(descriptor + 1);
Elliott Hughesf03b8f62011-12-02 14:26:25 -08001160
1161 if (IsPrimitiveTag(tag)) {
1162 size_t width = GetTagWidth(tag);
Elliott Hughesf03b8f62011-12-02 14:26:25 -08001163 if (width == 8) {
Elliott Hughes4b9702c2013-02-20 18:13:24 -08001164 CopyArrayData<uint64_t>(dst, request, offset, count);
Elliott Hughesf03b8f62011-12-02 14:26:25 -08001165 } else if (width == 4) {
Elliott Hughes4b9702c2013-02-20 18:13:24 -08001166 CopyArrayData<uint32_t>(dst, request, offset, count);
Elliott Hughesf03b8f62011-12-02 14:26:25 -08001167 } else if (width == 2) {
Elliott Hughes4b9702c2013-02-20 18:13:24 -08001168 CopyArrayData<uint16_t>(dst, request, offset, count);
Elliott Hughesf03b8f62011-12-02 14:26:25 -08001169 } else {
Elliott Hughes4b9702c2013-02-20 18:13:24 -08001170 CopyArrayData<uint8_t>(dst, request, offset, count);
Elliott Hughesf03b8f62011-12-02 14:26:25 -08001171 }
1172 } else {
Elliott Hughes4b9702c2013-02-20 18:13:24 -08001173 mirror::ObjectArray<mirror::Object>* oa = dst->AsObjectArray<mirror::Object>();
Elliott Hughesf03b8f62011-12-02 14:26:25 -08001174 for (int i = 0; i < count; ++i) {
Elliott Hughes4b9702c2013-02-20 18:13:24 -08001175 JDWP::ObjectId id = request.ReadObjectId();
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001176 mirror::Object* o = gRegistry->Get<mirror::Object*>(id);
Elliott Hughes64f574f2013-02-20 14:57:12 -08001177 if (o == ObjectRegistry::kInvalidObject) {
Elliott Hughes436e3722012-02-17 20:01:47 -08001178 return JDWP::ERR_INVALID_OBJECT;
1179 }
Sebastien Hertzd2fe10a2014-01-15 10:20:56 +01001180 oa->Set<false>(offset + i, o);
Elliott Hughesf03b8f62011-12-02 14:26:25 -08001181 }
1182 }
1183
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -08001184 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001185}
1186
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -08001187JDWP::ObjectId Dbg::CreateString(const std::string& str) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001188 return gRegistry->Add(mirror::String::AllocFromModifiedUtf8(Thread::Current(), str.c_str()));
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001189}
1190
Elliott Hughes88d63092013-01-09 09:55:54 -08001191JDWP::JdwpError Dbg::CreateObject(JDWP::RefTypeId class_id, JDWP::ObjectId& new_object) {
Elliott Hughes436e3722012-02-17 20:01:47 -08001192 JDWP::JdwpError status;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001193 mirror::Class* c = DecodeClass(class_id, status);
Elliott Hughes436e3722012-02-17 20:01:47 -08001194 if (c == NULL) {
1195 return status;
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -08001196 }
Ian Rogers50b35e22012-10-04 10:09:15 -07001197 new_object = gRegistry->Add(c->AllocObject(Thread::Current()));
Elliott Hughes436e3722012-02-17 20:01:47 -08001198 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001199}
1200
Elliott Hughesbf13d362011-12-08 15:51:37 -08001201/*
1202 * Used by Eclipse's "Display" view to evaluate "new byte[5]" to get "(byte[]) [0, 0, 0, 0, 0]".
1203 */
Elliott Hughes88d63092013-01-09 09:55:54 -08001204JDWP::JdwpError Dbg::CreateArrayObject(JDWP::RefTypeId array_class_id, uint32_t length,
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001205 JDWP::ObjectId& new_array) {
Elliott Hughes436e3722012-02-17 20:01:47 -08001206 JDWP::JdwpError status;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001207 mirror::Class* c = DecodeClass(array_class_id, status);
Elliott Hughes436e3722012-02-17 20:01:47 -08001208 if (c == NULL) {
1209 return status;
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -08001210 }
Ian Rogers6fac4472014-02-25 17:01:10 -08001211 new_array = gRegistry->Add(mirror::Array::Alloc<true>(Thread::Current(), c, length,
1212 c->GetComponentSize(),
1213 Runtime::Current()->GetHeap()->GetCurrentAllocator()));
Elliott Hughes436e3722012-02-17 20:01:47 -08001214 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001215}
1216
Elliott Hughes88d63092013-01-09 09:55:54 -08001217bool Dbg::MatchType(JDWP::RefTypeId instance_class_id, JDWP::RefTypeId class_id) {
Elliott Hughes436e3722012-02-17 20:01:47 -08001218 JDWP::JdwpError status;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001219 mirror::Class* c1 = DecodeClass(instance_class_id, status);
Elliott Hughesa656a0f2012-02-21 18:03:44 -08001220 CHECK(c1 != NULL);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001221 mirror::Class* c2 = DecodeClass(class_id, status);
Elliott Hughesa656a0f2012-02-21 18:03:44 -08001222 CHECK(c2 != NULL);
Sebastien Hertz123756a2013-11-27 15:49:42 +01001223 return c2->IsAssignableFrom(c1);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001224}
1225
Brian Carlstromea46f952013-07-30 01:26:50 -07001226static JDWP::FieldId ToFieldId(const mirror::ArtField* f)
Ian Rogersb726dcb2012-09-05 08:57:23 -07001227 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Mathieu Chartier590fee92013-09-13 13:46:47 -07001228 CHECK(!kMovingFields);
Elliott Hughes03181a82011-11-17 17:22:21 -08001229 return static_cast<JDWP::FieldId>(reinterpret_cast<uintptr_t>(f));
Elliott Hughes03181a82011-11-17 17:22:21 -08001230}
1231
Brian Carlstromea46f952013-07-30 01:26:50 -07001232static JDWP::MethodId ToMethodId(const mirror::ArtMethod* m)
Ian Rogersb726dcb2012-09-05 08:57:23 -07001233 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Mathieu Chartier590fee92013-09-13 13:46:47 -07001234 CHECK(!kMovingMethods);
Elliott Hughes03181a82011-11-17 17:22:21 -08001235 return static_cast<JDWP::MethodId>(reinterpret_cast<uintptr_t>(m));
Elliott Hughes03181a82011-11-17 17:22:21 -08001236}
1237
Brian Carlstromea46f952013-07-30 01:26:50 -07001238static mirror::ArtField* FromFieldId(JDWP::FieldId fid)
Ian Rogersb726dcb2012-09-05 08:57:23 -07001239 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Mathieu Chartier590fee92013-09-13 13:46:47 -07001240 CHECK(!kMovingFields);
Brian Carlstromea46f952013-07-30 01:26:50 -07001241 return reinterpret_cast<mirror::ArtField*>(static_cast<uintptr_t>(fid));
Elliott Hughesaed4be92011-12-02 16:16:23 -08001242}
1243
Brian Carlstromea46f952013-07-30 01:26:50 -07001244static mirror::ArtMethod* FromMethodId(JDWP::MethodId mid)
Ian Rogersb726dcb2012-09-05 08:57:23 -07001245 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Mathieu Chartier590fee92013-09-13 13:46:47 -07001246 CHECK(!kMovingMethods);
Brian Carlstromea46f952013-07-30 01:26:50 -07001247 return reinterpret_cast<mirror::ArtMethod*>(static_cast<uintptr_t>(mid));
Elliott Hughes03181a82011-11-17 17:22:21 -08001248}
1249
Brian Carlstromea46f952013-07-30 01:26:50 -07001250static void SetLocation(JDWP::JdwpLocation& location, mirror::ArtMethod* m, uint32_t dex_pc)
Ian Rogersb726dcb2012-09-05 08:57:23 -07001251 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08001252 if (m == NULL) {
1253 memset(&location, 0, sizeof(location));
1254 } else {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001255 mirror::Class* c = m->GetDeclaringClass();
Elliott Hughes74847412012-06-20 18:10:21 -07001256 location.type_tag = c->IsInterface() ? JDWP::TT_INTERFACE : JDWP::TT_CLASS;
1257 location.class_id = gRegistry->Add(c);
1258 location.method_id = ToMethodId(m);
Ian Rogers0399dde2012-06-06 17:09:28 -07001259 location.dex_pc = dex_pc;
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08001260 }
Elliott Hughesd07986f2011-12-06 18:27:45 -08001261}
1262
Elliott Hughesa96836a2013-01-17 12:27:49 -08001263std::string Dbg::GetMethodName(JDWP::MethodId method_id)
Ian Rogersb726dcb2012-09-05 08:57:23 -07001264 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Brian Carlstromea46f952013-07-30 01:26:50 -07001265 mirror::ArtMethod* m = FromMethodId(method_id);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001266 return MethodHelper(m).GetName();
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001267}
1268
Elliott Hughesa96836a2013-01-17 12:27:49 -08001269std::string Dbg::GetFieldName(JDWP::FieldId field_id)
1270 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Brian Carlstromea46f952013-07-30 01:26:50 -07001271 mirror::ArtField* f = FromFieldId(field_id);
Elliott Hughesa96836a2013-01-17 12:27:49 -08001272 return FieldHelper(f).GetName();
1273}
1274
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001275/*
1276 * Augment the access flags for synthetic methods and fields by setting
1277 * the (as described by the spec) "0xf0000000 bit". Also, strip out any
1278 * flags not specified by the Java programming language.
1279 */
1280static uint32_t MangleAccessFlags(uint32_t accessFlags) {
1281 accessFlags &= kAccJavaFlagsMask;
1282 if ((accessFlags & kAccSynthetic) != 0) {
1283 accessFlags |= 0xf0000000;
1284 }
1285 return accessFlags;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001286}
1287
Elliott Hughesdbb40792011-11-18 17:05:22 -08001288/*
Jeff Haob7cefc72013-11-14 14:51:09 -08001289 * Circularly shifts registers so that arguments come first. Debuggers
1290 * expect slots to begin with arguments, but dex code places them at
1291 * the end.
Elliott Hughesdbb40792011-11-18 17:05:22 -08001292 */
Jeff Haob7cefc72013-11-14 14:51:09 -08001293static uint16_t MangleSlot(uint16_t slot, mirror::ArtMethod* m)
1294 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
1295 const DexFile::CodeItem* code_item = MethodHelper(m).GetCodeItem();
1296 uint16_t ins_size = code_item->ins_size_;
1297 uint16_t locals_size = code_item->registers_size_ - ins_size;
1298 if (slot >= locals_size) {
1299 return slot - locals_size;
1300 } else {
1301 return slot + ins_size;
Elliott Hughesdbb40792011-11-18 17:05:22 -08001302 }
Elliott Hughesdbb40792011-11-18 17:05:22 -08001303}
1304
Jeff Haob7cefc72013-11-14 14:51:09 -08001305/*
1306 * Circularly shifts registers so that arguments come last. Reverts
1307 * slots to dex style argument placement.
1308 */
Brian Carlstromea46f952013-07-30 01:26:50 -07001309static uint16_t DemangleSlot(uint16_t slot, mirror::ArtMethod* m)
Ian Rogersb726dcb2012-09-05 08:57:23 -07001310 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Jeff Haob7cefc72013-11-14 14:51:09 -08001311 const DexFile::CodeItem* code_item = MethodHelper(m).GetCodeItem();
1312 uint16_t ins_size = code_item->ins_size_;
1313 uint16_t locals_size = code_item->registers_size_ - ins_size;
1314 if (slot < ins_size) {
1315 return slot + locals_size;
1316 } else {
1317 return slot - ins_size;
Elliott Hughesdbb40792011-11-18 17:05:22 -08001318 }
Elliott Hughesdbb40792011-11-18 17:05:22 -08001319}
1320
Elliott Hughes88d63092013-01-09 09:55:54 -08001321JDWP::JdwpError Dbg::OutputDeclaredFields(JDWP::RefTypeId class_id, bool with_generic, JDWP::ExpandBuf* pReply) {
Elliott Hughes436e3722012-02-17 20:01:47 -08001322 JDWP::JdwpError status;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001323 mirror::Class* c = DecodeClass(class_id, status);
Elliott Hughes436e3722012-02-17 20:01:47 -08001324 if (c == NULL) {
1325 return status;
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -08001326 }
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001327
1328 size_t instance_field_count = c->NumInstanceFields();
1329 size_t static_field_count = c->NumStaticFields();
1330
1331 expandBufAdd4BE(pReply, instance_field_count + static_field_count);
1332
1333 for (size_t i = 0; i < instance_field_count + static_field_count; ++i) {
Brian Carlstromea46f952013-07-30 01:26:50 -07001334 mirror::ArtField* f = (i < instance_field_count) ? c->GetInstanceField(i) : c->GetStaticField(i - instance_field_count);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001335 FieldHelper fh(f);
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001336 expandBufAddFieldId(pReply, ToFieldId(f));
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001337 expandBufAddUtf8String(pReply, fh.GetName());
1338 expandBufAddUtf8String(pReply, fh.GetTypeDescriptor());
Elliott Hughesc5b734a2011-12-01 17:20:58 -08001339 if (with_generic) {
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001340 static const char genericSignature[1] = "";
1341 expandBufAddUtf8String(pReply, genericSignature);
1342 }
1343 expandBufAdd4BE(pReply, MangleAccessFlags(f->GetAccessFlags()));
1344 }
Elliott Hughes436e3722012-02-17 20:01:47 -08001345 return JDWP::ERR_NONE;
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001346}
1347
Elliott Hughes88d63092013-01-09 09:55:54 -08001348JDWP::JdwpError Dbg::OutputDeclaredMethods(JDWP::RefTypeId class_id, bool with_generic,
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001349 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 Hughesa2e54f62011-11-17 13:01:30 -08001355
1356 size_t direct_method_count = c->NumDirectMethods();
1357 size_t virtual_method_count = c->NumVirtualMethods();
1358
1359 expandBufAdd4BE(pReply, direct_method_count + virtual_method_count);
1360
1361 for (size_t i = 0; i < direct_method_count + virtual_method_count; ++i) {
Brian Carlstromea46f952013-07-30 01:26:50 -07001362 mirror::ArtMethod* m = (i < direct_method_count) ? c->GetDirectMethod(i) : c->GetVirtualMethod(i - direct_method_count);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001363 MethodHelper mh(m);
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001364 expandBufAddMethodId(pReply, ToMethodId(m));
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001365 expandBufAddUtf8String(pReply, mh.GetName());
Ian Rogersd91d6d62013-09-25 20:26:14 -07001366 expandBufAddUtf8String(pReply, mh.GetSignature().ToString());
Elliott Hughesc5b734a2011-12-01 17:20:58 -08001367 if (with_generic) {
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001368 static const char genericSignature[1] = "";
1369 expandBufAddUtf8String(pReply, genericSignature);
1370 }
1371 expandBufAdd4BE(pReply, MangleAccessFlags(m->GetAccessFlags()));
1372 }
Elliott Hughes436e3722012-02-17 20:01:47 -08001373 return JDWP::ERR_NONE;
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001374}
1375
Elliott Hughes88d63092013-01-09 09:55:54 -08001376JDWP::JdwpError Dbg::OutputDeclaredInterfaces(JDWP::RefTypeId class_id, JDWP::ExpandBuf* pReply) {
Elliott Hughes436e3722012-02-17 20:01:47 -08001377 JDWP::JdwpError status;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001378 mirror::Class* c = DecodeClass(class_id, status);
Elliott Hughes436e3722012-02-17 20:01:47 -08001379 if (c == NULL) {
1380 return status;
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -08001381 }
Elliott Hughes436e3722012-02-17 20:01:47 -08001382
1383 ClassHelper kh(c);
Ian Rogersd24e2642012-06-06 21:21:43 -07001384 size_t interface_count = kh.NumDirectInterfaces();
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001385 expandBufAdd4BE(pReply, interface_count);
1386 for (size_t i = 0; i < interface_count; ++i) {
Elliott Hughes64f574f2013-02-20 14:57:12 -08001387 expandBufAddRefTypeId(pReply, gRegistry->AddRefType(kh.GetDirectInterface(i)));
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001388 }
Elliott Hughes436e3722012-02-17 20:01:47 -08001389 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001390}
1391
Elliott Hughes88d63092013-01-09 09:55:54 -08001392void Dbg::OutputLineTable(JDWP::RefTypeId, JDWP::MethodId method_id, JDWP::ExpandBuf* pReply)
Ian Rogersb726dcb2012-09-05 08:57:23 -07001393 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Elliott Hughes03181a82011-11-17 17:22:21 -08001394 struct DebugCallbackContext {
1395 int numItems;
1396 JDWP::ExpandBuf* pReply;
1397
Elliott Hughes2435a572012-02-17 16:07:41 -08001398 static bool Callback(void* context, uint32_t address, uint32_t line_number) {
Elliott Hughes03181a82011-11-17 17:22:21 -08001399 DebugCallbackContext* pContext = reinterpret_cast<DebugCallbackContext*>(context);
1400 expandBufAdd8BE(pContext->pReply, address);
Elliott Hughes2435a572012-02-17 16:07:41 -08001401 expandBufAdd4BE(pContext->pReply, line_number);
Elliott Hughes03181a82011-11-17 17:22:21 -08001402 pContext->numItems++;
Sebastien Hertzf2910ee2013-10-19 16:39:24 +02001403 return false;
Elliott Hughes03181a82011-11-17 17:22:21 -08001404 }
1405 };
Brian Carlstromea46f952013-07-30 01:26:50 -07001406 mirror::ArtMethod* m = FromMethodId(method_id);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001407 MethodHelper mh(m);
Elliott Hughes03181a82011-11-17 17:22:21 -08001408 uint64_t start, end;
1409 if (m->IsNative()) {
1410 start = -1;
1411 end = -1;
1412 } else {
1413 start = 0;
jeffhao14f0db92012-12-14 17:50:42 -08001414 // Return the index of the last instruction
1415 end = mh.GetCodeItem()->insns_size_in_code_units_ - 1;
Elliott Hughes03181a82011-11-17 17:22:21 -08001416 }
1417
1418 expandBufAdd8BE(pReply, start);
1419 expandBufAdd8BE(pReply, end);
1420
1421 // Add numLines later
1422 size_t numLinesOffset = expandBufGetLength(pReply);
1423 expandBufAdd4BE(pReply, 0);
1424
1425 DebugCallbackContext context;
1426 context.numItems = 0;
1427 context.pReply = pReply;
1428
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001429 mh.GetDexFile().DecodeDebugInfo(mh.GetCodeItem(), m->IsStatic(), m->GetDexMethodIndex(),
1430 DebugCallbackContext::Callback, NULL, &context);
Elliott Hughes03181a82011-11-17 17:22:21 -08001431
1432 JDWP::Set4BE(expandBufGetBuffer(pReply) + numLinesOffset, context.numItems);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001433}
1434
Elliott Hughes88d63092013-01-09 09:55:54 -08001435void Dbg::OutputVariableTable(JDWP::RefTypeId, JDWP::MethodId method_id, bool with_generic, JDWP::ExpandBuf* pReply) {
Elliott Hughesdbb40792011-11-18 17:05:22 -08001436 struct DebugCallbackContext {
Jeff Haob7cefc72013-11-14 14:51:09 -08001437 mirror::ArtMethod* method;
Elliott Hughesdbb40792011-11-18 17:05:22 -08001438 JDWP::ExpandBuf* pReply;
Elliott Hughesc5b734a2011-12-01 17:20:58 -08001439 size_t variable_count;
1440 bool with_generic;
Elliott Hughesdbb40792011-11-18 17:05:22 -08001441
Jeff Haob7cefc72013-11-14 14:51:09 -08001442 static void Callback(void* context, uint16_t slot, uint32_t startAddress, uint32_t endAddress, const char* name, const char* descriptor, const char* signature)
1443 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Elliott Hughesdbb40792011-11-18 17:05:22 -08001444 DebugCallbackContext* pContext = reinterpret_cast<DebugCallbackContext*>(context);
1445
Jeff Haob7cefc72013-11-14 14:51:09 -08001446 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 -08001447
Jeff Haob7cefc72013-11-14 14:51:09 -08001448 slot = MangleSlot(slot, pContext->method);
Elliott Hughes68fdbd02011-11-29 19:22:47 -08001449
Elliott Hughesdbb40792011-11-18 17:05:22 -08001450 expandBufAdd8BE(pContext->pReply, startAddress);
1451 expandBufAddUtf8String(pContext->pReply, name);
1452 expandBufAddUtf8String(pContext->pReply, descriptor);
Elliott Hughesc5b734a2011-12-01 17:20:58 -08001453 if (pContext->with_generic) {
Elliott Hughesdbb40792011-11-18 17:05:22 -08001454 expandBufAddUtf8String(pContext->pReply, signature);
1455 }
1456 expandBufAdd4BE(pContext->pReply, endAddress - startAddress);
1457 expandBufAdd4BE(pContext->pReply, slot);
1458
Elliott Hughesc5b734a2011-12-01 17:20:58 -08001459 ++pContext->variable_count;
Elliott Hughesdbb40792011-11-18 17:05:22 -08001460 }
1461 };
Brian Carlstromea46f952013-07-30 01:26:50 -07001462 mirror::ArtMethod* m = FromMethodId(method_id);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001463 MethodHelper mh(m);
1464 const DexFile::CodeItem* code_item = mh.GetCodeItem();
Elliott Hughesdbb40792011-11-18 17:05:22 -08001465
Elliott Hughesc5b734a2011-12-01 17:20:58 -08001466 // arg_count considers doubles and longs to take 2 units.
1467 // variable_count considers everything to take 1 unit.
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001468 std::string shorty(mh.GetShorty());
Brian Carlstromea46f952013-07-30 01:26:50 -07001469 expandBufAdd4BE(pReply, mirror::ArtMethod::NumArgRegisters(shorty));
Elliott Hughesdbb40792011-11-18 17:05:22 -08001470
Elliott Hughesc5b734a2011-12-01 17:20:58 -08001471 // We don't know the total number of variables yet, so leave a blank and update it later.
1472 size_t variable_count_offset = expandBufGetLength(pReply);
Elliott Hughesdbb40792011-11-18 17:05:22 -08001473 expandBufAdd4BE(pReply, 0);
1474
1475 DebugCallbackContext context;
Jeff Haob7cefc72013-11-14 14:51:09 -08001476 context.method = m;
Elliott Hughesdbb40792011-11-18 17:05:22 -08001477 context.pReply = pReply;
Elliott Hughesc5b734a2011-12-01 17:20:58 -08001478 context.variable_count = 0;
1479 context.with_generic = with_generic;
Elliott Hughesdbb40792011-11-18 17:05:22 -08001480
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001481 mh.GetDexFile().DecodeDebugInfo(code_item, m->IsStatic(), m->GetDexMethodIndex(), NULL,
1482 DebugCallbackContext::Callback, &context);
Elliott Hughesdbb40792011-11-18 17:05:22 -08001483
Elliott Hughesc5b734a2011-12-01 17:20:58 -08001484 JDWP::Set4BE(expandBufGetBuffer(pReply) + variable_count_offset, context.variable_count);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001485}
1486
Jeff Hao579b0242013-11-18 13:16:49 -08001487void Dbg::OutputMethodReturnValue(JDWP::MethodId method_id, const JValue* return_value,
1488 JDWP::ExpandBuf* pReply) {
1489 mirror::ArtMethod* m = FromMethodId(method_id);
1490 JDWP::JdwpTag tag = BasicTagFromDescriptor(MethodHelper(m).GetShorty());
1491 OutputJValue(tag, return_value, pReply);
1492}
1493
Elliott Hughes9777ba22013-01-17 09:04:19 -08001494JDWP::JdwpError Dbg::GetBytecodes(JDWP::RefTypeId, JDWP::MethodId method_id,
1495 std::vector<uint8_t>& bytecodes)
1496 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Brian Carlstromea46f952013-07-30 01:26:50 -07001497 mirror::ArtMethod* m = FromMethodId(method_id);
Elliott Hughes9777ba22013-01-17 09:04:19 -08001498 if (m == NULL) {
1499 return JDWP::ERR_INVALID_METHODID;
1500 }
1501 MethodHelper mh(m);
1502 const DexFile::CodeItem* code_item = mh.GetCodeItem();
1503 size_t byte_count = code_item->insns_size_in_code_units_ * 2;
1504 const uint8_t* begin = reinterpret_cast<const uint8_t*>(code_item->insns_);
1505 const uint8_t* end = begin + byte_count;
1506 for (const uint8_t* p = begin; p != end; ++p) {
1507 bytecodes.push_back(*p);
1508 }
1509 return JDWP::ERR_NONE;
1510}
1511
Elliott Hughes88d63092013-01-09 09:55:54 -08001512JDWP::JdwpTag Dbg::GetFieldBasicTag(JDWP::FieldId field_id) {
1513 return BasicTagFromDescriptor(FieldHelper(FromFieldId(field_id)).GetTypeDescriptor());
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001514}
1515
Elliott Hughes88d63092013-01-09 09:55:54 -08001516JDWP::JdwpTag Dbg::GetStaticFieldBasicTag(JDWP::FieldId field_id) {
1517 return BasicTagFromDescriptor(FieldHelper(FromFieldId(field_id)).GetTypeDescriptor());
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001518}
1519
Elliott Hughes88d63092013-01-09 09:55:54 -08001520static JDWP::JdwpError GetFieldValueImpl(JDWP::RefTypeId ref_type_id, JDWP::ObjectId object_id,
1521 JDWP::FieldId field_id, JDWP::ExpandBuf* pReply,
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001522 bool is_static)
Ian Rogersb726dcb2012-09-05 08:57:23 -07001523 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Elliott Hughes0cf74332012-02-23 23:14:00 -08001524 JDWP::JdwpError status;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001525 mirror::Class* c = DecodeClass(ref_type_id, status);
Elliott Hughes88d63092013-01-09 09:55:54 -08001526 if (ref_type_id != 0 && c == NULL) {
Elliott Hughes0cf74332012-02-23 23:14:00 -08001527 return status;
1528 }
1529
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001530 mirror::Object* o = gRegistry->Get<mirror::Object*>(object_id);
Elliott Hughes64f574f2013-02-20 14:57:12 -08001531 if ((!is_static && o == NULL) || o == ObjectRegistry::kInvalidObject) {
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08001532 return JDWP::ERR_INVALID_OBJECT;
1533 }
Brian Carlstromea46f952013-07-30 01:26:50 -07001534 mirror::ArtField* f = FromFieldId(field_id);
Elliott Hughes0cf74332012-02-23 23:14:00 -08001535
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001536 mirror::Class* receiver_class = c;
Elliott Hughes0cf74332012-02-23 23:14:00 -08001537 if (receiver_class == NULL && o != NULL) {
1538 receiver_class = o->GetClass();
1539 }
1540 // TODO: should we give up now if receiver_class is NULL?
1541 if (receiver_class != NULL && !f->GetDeclaringClass()->IsAssignableFrom(receiver_class)) {
1542 LOG(INFO) << "ERR_INVALID_FIELDID: " << PrettyField(f) << " " << PrettyClass(receiver_class);
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08001543 return JDWP::ERR_INVALID_FIELDID;
1544 }
Elliott Hughesaed4be92011-12-02 16:16:23 -08001545
Elliott Hughes0cf74332012-02-23 23:14:00 -08001546 // The RI only enforces the static/non-static mismatch in one direction.
1547 // TODO: should we change the tests and check both?
1548 if (is_static) {
1549 if (!f->IsStatic()) {
1550 return JDWP::ERR_INVALID_FIELDID;
1551 }
1552 } else {
1553 if (f->IsStatic()) {
1554 LOG(WARNING) << "Ignoring non-NULL receiver for ObjectReference.SetValues on static field " << PrettyField(f);
Elliott Hughes0cf74332012-02-23 23:14:00 -08001555 }
1556 }
jeffhao0dfbb7e2012-11-28 15:26:03 -08001557 if (f->IsStatic()) {
1558 o = f->GetDeclaringClass();
1559 }
Elliott Hughes0cf74332012-02-23 23:14:00 -08001560
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001561 JDWP::JdwpTag tag = BasicTagFromDescriptor(FieldHelper(f).GetTypeDescriptor());
Jeff Hao579b0242013-11-18 13:16:49 -08001562 JValue field_value;
1563 if (tag == JDWP::JT_VOID) {
1564 LOG(FATAL) << "Unknown tag: " << tag;
1565 } else if (!IsPrimitiveTag(tag)) {
1566 field_value.SetL(f->GetObject(o));
1567 } else if (tag == JDWP::JT_DOUBLE || tag == JDWP::JT_LONG) {
1568 field_value.SetJ(f->Get64(o));
Elliott Hughesaed4be92011-12-02 16:16:23 -08001569 } else {
Jeff Hao579b0242013-11-18 13:16:49 -08001570 field_value.SetI(f->Get32(o));
Elliott Hughesaed4be92011-12-02 16:16:23 -08001571 }
Jeff Hao579b0242013-11-18 13:16:49 -08001572 Dbg::OutputJValue(tag, &field_value, pReply);
1573
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08001574 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001575}
1576
Elliott Hughes88d63092013-01-09 09:55:54 -08001577JDWP::JdwpError Dbg::GetFieldValue(JDWP::ObjectId object_id, JDWP::FieldId field_id,
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001578 JDWP::ExpandBuf* pReply) {
Elliott Hughes88d63092013-01-09 09:55:54 -08001579 return GetFieldValueImpl(0, object_id, field_id, pReply, false);
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08001580}
1581
Elliott Hughes88d63092013-01-09 09:55:54 -08001582JDWP::JdwpError Dbg::GetStaticFieldValue(JDWP::RefTypeId ref_type_id, JDWP::FieldId field_id, JDWP::ExpandBuf* pReply) {
1583 return GetFieldValueImpl(ref_type_id, 0, field_id, pReply, true);
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08001584}
1585
Elliott Hughes88d63092013-01-09 09:55:54 -08001586static JDWP::JdwpError SetFieldValueImpl(JDWP::ObjectId object_id, JDWP::FieldId field_id,
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001587 uint64_t value, int width, bool is_static)
Ian Rogersb726dcb2012-09-05 08:57:23 -07001588 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001589 mirror::Object* o = gRegistry->Get<mirror::Object*>(object_id);
Elliott Hughes64f574f2013-02-20 14:57:12 -08001590 if ((!is_static && o == NULL) || o == ObjectRegistry::kInvalidObject) {
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08001591 return JDWP::ERR_INVALID_OBJECT;
1592 }
Brian Carlstromea46f952013-07-30 01:26:50 -07001593 mirror::ArtField* f = FromFieldId(field_id);
Elliott Hughes0cf74332012-02-23 23:14:00 -08001594
1595 // The RI only enforces the static/non-static mismatch in one direction.
1596 // TODO: should we change the tests and check both?
1597 if (is_static) {
1598 if (!f->IsStatic()) {
1599 return JDWP::ERR_INVALID_FIELDID;
1600 }
1601 } else {
1602 if (f->IsStatic()) {
1603 LOG(WARNING) << "Ignoring non-NULL receiver for ObjectReference.SetValues on static field " << PrettyField(f);
Elliott Hughes0cf74332012-02-23 23:14:00 -08001604 }
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08001605 }
jeffhao0dfbb7e2012-11-28 15:26:03 -08001606 if (f->IsStatic()) {
1607 o = f->GetDeclaringClass();
1608 }
Elliott Hughesaed4be92011-12-02 16:16:23 -08001609
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001610 JDWP::JdwpTag tag = BasicTagFromDescriptor(FieldHelper(f).GetTypeDescriptor());
Elliott Hughesaed4be92011-12-02 16:16:23 -08001611
1612 if (IsPrimitiveTag(tag)) {
1613 if (tag == JDWP::JT_DOUBLE || tag == JDWP::JT_LONG) {
Elliott Hughes1bac54f2012-03-16 12:48:31 -07001614 CHECK_EQ(width, 8);
Sebastien Hertzd2fe10a2014-01-15 10:20:56 +01001615 // Debugging can't use transactional mode (runtime only).
1616 f->Set64<false>(o, value);
Elliott Hughesaed4be92011-12-02 16:16:23 -08001617 } else {
Elliott Hughes1bac54f2012-03-16 12:48:31 -07001618 CHECK_LE(width, 4);
Sebastien Hertzd2fe10a2014-01-15 10:20:56 +01001619 // Debugging can't use transactional mode (runtime only).
1620 f->Set32<false>(o, value);
Elliott Hughesaed4be92011-12-02 16:16:23 -08001621 }
1622 } else {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001623 mirror::Object* v = gRegistry->Get<mirror::Object*>(value);
Elliott Hughes64f574f2013-02-20 14:57:12 -08001624 if (v == ObjectRegistry::kInvalidObject) {
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -08001625 return JDWP::ERR_INVALID_OBJECT;
1626 }
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08001627 if (v != NULL) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001628 mirror::Class* field_type = FieldHelper(f).GetType();
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08001629 if (!field_type->IsAssignableFrom(v->GetClass())) {
1630 return JDWP::ERR_INVALID_OBJECT;
1631 }
1632 }
Sebastien Hertzd2fe10a2014-01-15 10:20:56 +01001633 // Debugging can't use transactional mode (runtime only).
1634 f->SetObject<false>(o, v);
Elliott Hughesaed4be92011-12-02 16:16:23 -08001635 }
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -08001636
1637 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001638}
1639
Elliott Hughes88d63092013-01-09 09:55:54 -08001640JDWP::JdwpError Dbg::SetFieldValue(JDWP::ObjectId object_id, JDWP::FieldId field_id, uint64_t value,
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001641 int width) {
Elliott Hughes88d63092013-01-09 09:55:54 -08001642 return SetFieldValueImpl(object_id, field_id, value, width, false);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001643}
1644
Elliott Hughes88d63092013-01-09 09:55:54 -08001645JDWP::JdwpError Dbg::SetStaticFieldValue(JDWP::FieldId field_id, uint64_t value, int width) {
1646 return SetFieldValueImpl(0, field_id, value, width, true);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001647}
1648
Elliott Hughes88d63092013-01-09 09:55:54 -08001649std::string Dbg::StringToUtf8(JDWP::ObjectId string_id) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001650 mirror::String* s = gRegistry->Get<mirror::String*>(string_id);
Elliott Hughes68fdbd02011-11-29 19:22:47 -08001651 return s->ToModifiedUtf8();
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001652}
1653
Jeff Hao579b0242013-11-18 13:16:49 -08001654void Dbg::OutputJValue(JDWP::JdwpTag tag, const JValue* return_value, JDWP::ExpandBuf* pReply) {
1655 if (IsPrimitiveTag(tag)) {
1656 expandBufAdd1(pReply, tag);
1657 if (tag == JDWP::JT_BOOLEAN || tag == JDWP::JT_BYTE) {
1658 expandBufAdd1(pReply, return_value->GetI());
1659 } else if (tag == JDWP::JT_CHAR || tag == JDWP::JT_SHORT) {
1660 expandBufAdd2BE(pReply, return_value->GetI());
1661 } else if (tag == JDWP::JT_FLOAT || tag == JDWP::JT_INT) {
1662 expandBufAdd4BE(pReply, return_value->GetI());
1663 } else if (tag == JDWP::JT_DOUBLE || tag == JDWP::JT_LONG) {
1664 expandBufAdd8BE(pReply, return_value->GetJ());
1665 } else {
1666 CHECK_EQ(tag, JDWP::JT_VOID);
1667 }
1668 } else {
Ian Rogers98379392014-02-24 16:53:16 -08001669 ScopedObjectAccessUnchecked soa(Thread::Current());
Jeff Hao579b0242013-11-18 13:16:49 -08001670 mirror::Object* value = return_value->GetL();
Ian Rogers98379392014-02-24 16:53:16 -08001671 expandBufAdd1(pReply, TagFromObject(soa, value));
Jeff Hao579b0242013-11-18 13:16:49 -08001672 expandBufAddObjectId(pReply, gRegistry->Add(value));
1673 }
1674}
1675
Elliott Hughes221229c2013-01-08 18:17:50 -08001676JDWP::JdwpError Dbg::GetThreadName(JDWP::ObjectId thread_id, std::string& name) {
jeffhaoa77f0f62012-12-05 17:19:31 -08001677 ScopedObjectAccessUnchecked soa(Thread::Current());
1678 MutexLock mu(soa.Self(), *Locks::thread_list_lock_);
Elliott Hughes221229c2013-01-08 18:17:50 -08001679 Thread* thread;
1680 JDWP::JdwpError error = DecodeThread(soa, thread_id, thread);
1681 if (error != JDWP::ERR_NONE && error != JDWP::ERR_THREAD_NOT_ALIVE) {
1682 return error;
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001683 }
Elliott Hughes221229c2013-01-08 18:17:50 -08001684
1685 // We still need to report the zombie threads' names, so we can't just call Thread::GetThreadName.
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001686 mirror::Object* thread_object = gRegistry->Get<mirror::Object*>(thread_id);
Brian Carlstromea46f952013-07-30 01:26:50 -07001687 mirror::ArtField* java_lang_Thread_name_field =
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001688 soa.DecodeField(WellKnownClasses::java_lang_Thread_name);
1689 mirror::String* s =
1690 reinterpret_cast<mirror::String*>(java_lang_Thread_name_field->GetObject(thread_object));
Elliott Hughes221229c2013-01-08 18:17:50 -08001691 if (s != NULL) {
1692 name = s->ToModifiedUtf8();
1693 }
1694 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001695}
1696
Elliott Hughes221229c2013-01-08 18:17:50 -08001697JDWP::JdwpError Dbg::GetThreadGroup(JDWP::ObjectId thread_id, JDWP::ExpandBuf* pReply) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001698 ScopedObjectAccess soa(Thread::Current());
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001699 mirror::Object* thread_object = gRegistry->Get<mirror::Object*>(thread_id);
Elliott Hughes64f574f2013-02-20 14:57:12 -08001700 if (thread_object == ObjectRegistry::kInvalidObject) {
Elliott Hughes2435a572012-02-17 16:07:41 -08001701 return JDWP::ERR_INVALID_OBJECT;
1702 }
Ian Rogers98379392014-02-24 16:53:16 -08001703 const char* old_cause = soa.Self()->StartAssertNoThreadSuspension("Debugger: GetThreadGroup");
Elliott Hughes2435a572012-02-17 16:07:41 -08001704 // Okay, so it's an object, but is it actually a thread?
Ian Rogers50b35e22012-10-04 10:09:15 -07001705 MutexLock mu(soa.Self(), *Locks::thread_list_lock_);
Elliott Hughes221229c2013-01-08 18:17:50 -08001706 Thread* thread;
1707 JDWP::JdwpError error = DecodeThread(soa, thread_id, thread);
1708 if (error == JDWP::ERR_THREAD_NOT_ALIVE) {
1709 // Zombie threads are in the null group.
1710 expandBufAddObjectId(pReply, JDWP::ObjectId(0));
1711 return JDWP::ERR_NONE;
1712 }
1713 if (error != JDWP::ERR_NONE) {
1714 return error;
Elliott Hughes2435a572012-02-17 16:07:41 -08001715 }
Ian Rogers98379392014-02-24 16:53:16 -08001716 mirror::Class* c = soa.Decode<mirror::Class*>(WellKnownClasses::java_lang_Thread);
1717 CHECK(c != nullptr);
Brian Carlstromea46f952013-07-30 01:26:50 -07001718 mirror::ArtField* f = c->FindInstanceField("group", "Ljava/lang/ThreadGroup;");
Elliott Hughes499c5132011-11-17 14:55:11 -08001719 CHECK(f != NULL);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001720 mirror::Object* group = f->GetObject(thread_object);
Elliott Hughes499c5132011-11-17 14:55:11 -08001721 CHECK(group != NULL);
Elliott Hughes2435a572012-02-17 16:07:41 -08001722 JDWP::ObjectId thread_group_id = gRegistry->Add(group);
Ian Rogers98379392014-02-24 16:53:16 -08001723 soa.Self()->EndAssertNoThreadSuspension(old_cause);
Elliott Hughes2435a572012-02-17 16:07:41 -08001724
1725 expandBufAddObjectId(pReply, thread_group_id);
1726 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001727}
1728
Elliott Hughes88d63092013-01-09 09:55:54 -08001729std::string Dbg::GetThreadGroupName(JDWP::ObjectId thread_group_id) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001730 ScopedObjectAccess soa(Thread::Current());
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001731 mirror::Object* thread_group = gRegistry->Get<mirror::Object*>(thread_group_id);
Ian Rogers98379392014-02-24 16:53:16 -08001732 CHECK(thread_group != nullptr);
1733 const char* old_cause = soa.Self()->StartAssertNoThreadSuspension("Debugger: GetThreadGroupName");
1734 mirror::Class* c = soa.Decode<mirror::Class*>(WellKnownClasses::java_lang_ThreadGroup);
1735 CHECK(c != nullptr);
Brian Carlstromea46f952013-07-30 01:26:50 -07001736 mirror::ArtField* f = c->FindInstanceField("name", "Ljava/lang/String;");
Elliott Hughes499c5132011-11-17 14:55:11 -08001737 CHECK(f != NULL);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001738 mirror::String* s = reinterpret_cast<mirror::String*>(f->GetObject(thread_group));
Ian Rogers98379392014-02-24 16:53:16 -08001739 soa.Self()->EndAssertNoThreadSuspension(old_cause);
Elliott Hughes499c5132011-11-17 14:55:11 -08001740 return s->ToModifiedUtf8();
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001741}
1742
Elliott Hughes88d63092013-01-09 09:55:54 -08001743JDWP::ObjectId Dbg::GetThreadGroupParent(JDWP::ObjectId thread_group_id) {
Ian Rogers98379392014-02-24 16:53:16 -08001744 ScopedObjectAccessUnchecked soa(Thread::Current());
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001745 mirror::Object* thread_group = gRegistry->Get<mirror::Object*>(thread_group_id);
Ian Rogers98379392014-02-24 16:53:16 -08001746 CHECK(thread_group != nullptr);
1747 const char* old_cause = soa.Self()->StartAssertNoThreadSuspension("Debugger: GetThreadGroupParent");
1748 mirror::Class* c = soa.Decode<mirror::Class*>(WellKnownClasses::java_lang_ThreadGroup);
1749 CHECK(c != nullptr);
Brian Carlstromea46f952013-07-30 01:26:50 -07001750 mirror::ArtField* f = c->FindInstanceField("parent", "Ljava/lang/ThreadGroup;");
Elliott Hughes4e235312011-12-02 11:34:15 -08001751 CHECK(f != NULL);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001752 mirror::Object* parent = f->GetObject(thread_group);
Ian Rogers98379392014-02-24 16:53:16 -08001753 soa.Self()->EndAssertNoThreadSuspension(old_cause);
Elliott Hughes4e235312011-12-02 11:34:15 -08001754 return gRegistry->Add(parent);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001755}
1756
1757JDWP::ObjectId Dbg::GetSystemThreadGroupId() {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001758 ScopedObjectAccessUnchecked soa(Thread::Current());
Brian Carlstromea46f952013-07-30 01:26:50 -07001759 mirror::ArtField* f = soa.DecodeField(WellKnownClasses::java_lang_ThreadGroup_systemThreadGroup);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001760 mirror::Object* group = f->GetObject(f->GetDeclaringClass());
Ian Rogers365c1022012-06-22 15:05:28 -07001761 return gRegistry->Add(group);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001762}
1763
1764JDWP::ObjectId Dbg::GetMainThreadGroupId() {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001765 ScopedObjectAccess soa(Thread::Current());
Brian Carlstromea46f952013-07-30 01:26:50 -07001766 mirror::ArtField* f = soa.DecodeField(WellKnownClasses::java_lang_ThreadGroup_mainThreadGroup);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001767 mirror::Object* group = f->GetObject(f->GetDeclaringClass());
Ian Rogers365c1022012-06-22 15:05:28 -07001768 return gRegistry->Add(group);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001769}
1770
Jeff Hao920af3e2013-08-28 15:46:38 -07001771JDWP::JdwpThreadStatus Dbg::ToJdwpThreadStatus(ThreadState state) {
1772 switch (state) {
1773 case kBlocked:
1774 return JDWP::TS_MONITOR;
1775 case kNative:
1776 case kRunnable:
1777 case kSuspended:
1778 return JDWP::TS_RUNNING;
1779 case kSleeping:
1780 return JDWP::TS_SLEEPING;
1781 case kStarting:
1782 case kTerminated:
1783 return JDWP::TS_ZOMBIE;
1784 case kTimedWaiting:
1785 case kWaitingForDebuggerSend:
1786 case kWaitingForDebuggerSuspension:
1787 case kWaitingForDebuggerToAttach:
Sebastien Hertz138dbfc2013-12-04 18:15:25 +01001788 case kWaitingForDeoptimization:
Jeff Hao920af3e2013-08-28 15:46:38 -07001789 case kWaitingForGcToComplete:
1790 case kWaitingForCheckPointsToRun:
1791 case kWaitingForJniOnLoad:
1792 case kWaitingForSignalCatcherOutput:
1793 case kWaitingInMainDebuggerLoop:
1794 case kWaitingInMainSignalCatcherLoop:
1795 case kWaitingPerformingGc:
1796 case kWaiting:
1797 return JDWP::TS_WAIT;
1798 // Don't add a 'default' here so the compiler can spot incompatible enum changes.
1799 }
1800 LOG(FATAL) << "Unknown thread state: " << state;
1801 return JDWP::TS_ZOMBIE;
1802}
1803
Elliott Hughes221229c2013-01-08 18:17:50 -08001804JDWP::JdwpError Dbg::GetThreadStatus(JDWP::ObjectId thread_id, JDWP::JdwpThreadStatus* pThreadStatus, JDWP::JdwpSuspendStatus* pSuspendStatus) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001805 ScopedObjectAccess soa(Thread::Current());
Elliott Hughes499c5132011-11-17 14:55:11 -08001806
Elliott Hughes9e0c1752013-01-09 14:02:58 -08001807 *pSuspendStatus = JDWP::SUSPEND_STATUS_NOT_SUSPENDED;
1808
Ian Rogers50b35e22012-10-04 10:09:15 -07001809 MutexLock mu(soa.Self(), *Locks::thread_list_lock_);
Elliott Hughes221229c2013-01-08 18:17:50 -08001810 Thread* thread;
1811 JDWP::JdwpError error = DecodeThread(soa, thread_id, thread);
1812 if (error != JDWP::ERR_NONE) {
1813 if (error == JDWP::ERR_THREAD_NOT_ALIVE) {
1814 *pThreadStatus = JDWP::TS_ZOMBIE;
Elliott Hughes221229c2013-01-08 18:17:50 -08001815 return JDWP::ERR_NONE;
1816 }
1817 return error;
Elliott Hughes499c5132011-11-17 14:55:11 -08001818 }
1819
Elliott Hughes9e0c1752013-01-09 14:02:58 -08001820 if (IsSuspendedForDebugger(soa, thread)) {
1821 *pSuspendStatus = JDWP::SUSPEND_STATUS_SUSPENDED;
Elliott Hughes499c5132011-11-17 14:55:11 -08001822 }
1823
Jeff Hao920af3e2013-08-28 15:46:38 -07001824 *pThreadStatus = ToJdwpThreadStatus(thread->GetState());
Elliott Hughes221229c2013-01-08 18:17:50 -08001825 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001826}
1827
Elliott Hughes221229c2013-01-08 18:17:50 -08001828JDWP::JdwpError Dbg::GetThreadDebugSuspendCount(JDWP::ObjectId thread_id, JDWP::ExpandBuf* pReply) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001829 ScopedObjectAccess soa(Thread::Current());
Ian Rogers50b35e22012-10-04 10:09:15 -07001830 MutexLock mu(soa.Self(), *Locks::thread_list_lock_);
Elliott Hughes221229c2013-01-08 18:17:50 -08001831 Thread* thread;
1832 JDWP::JdwpError error = DecodeThread(soa, thread_id, thread);
1833 if (error != JDWP::ERR_NONE) {
1834 return error;
Elliott Hughes2435a572012-02-17 16:07:41 -08001835 }
Ian Rogers50b35e22012-10-04 10:09:15 -07001836 MutexLock mu2(soa.Self(), *Locks::thread_suspend_count_lock_);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001837 expandBufAdd4BE(pReply, thread->GetDebugSuspendCount());
Elliott Hughes2435a572012-02-17 16:07:41 -08001838 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001839}
1840
Elliott Hughesf9501702013-01-11 11:22:27 -08001841JDWP::JdwpError Dbg::Interrupt(JDWP::ObjectId thread_id) {
1842 ScopedObjectAccess soa(Thread::Current());
1843 MutexLock mu(soa.Self(), *Locks::thread_list_lock_);
1844 Thread* thread;
1845 JDWP::JdwpError error = DecodeThread(soa, thread_id, thread);
1846 if (error != JDWP::ERR_NONE) {
1847 return error;
1848 }
1849 thread->Interrupt();
1850 return JDWP::ERR_NONE;
1851}
1852
Elliott Hughescaf76542012-06-28 16:08:22 -07001853void Dbg::GetThreads(JDWP::ObjectId thread_group_id, std::vector<JDWP::ObjectId>& thread_ids) {
Ian Rogers365c1022012-06-22 15:05:28 -07001854 class ThreadListVisitor {
1855 public:
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001856 ThreadListVisitor(const ScopedObjectAccessUnchecked& soa, mirror::Object* desired_thread_group,
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001857 std::vector<JDWP::ObjectId>& thread_ids)
Ian Rogersb726dcb2012-09-05 08:57:23 -07001858 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_)
jeffhao0dfbb7e2012-11-28 15:26:03 -08001859 : soa_(soa), desired_thread_group_(desired_thread_group), thread_ids_(thread_ids) {}
Ian Rogers365c1022012-06-22 15:05:28 -07001860
Elliott Hughesa2155262011-11-16 16:26:58 -08001861 static void Visit(Thread* t, void* arg) {
1862 reinterpret_cast<ThreadListVisitor*>(arg)->Visit(t);
1863 }
1864
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001865 // TODO: Enable annotalysis. We know lock is held in constructor, but abstraction confuses
1866 // annotalysis.
1867 void Visit(Thread* t) NO_THREAD_SAFETY_ANALYSIS {
Elliott Hughesa2155262011-11-16 16:26:58 -08001868 if (t == Dbg::GetDebugThread()) {
1869 // Skip the JDWP thread. Some debuggers get bent out of shape when they can't suspend and
1870 // query all threads, so it's easier if we just don't tell them about this thread.
1871 return;
1872 }
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001873 mirror::Object* peer = t->GetPeer();
jeffhao0dfbb7e2012-11-28 15:26:03 -08001874 if (IsInDesiredThreadGroup(peer)) {
Ian Rogers120f1c72012-09-28 17:17:10 -07001875 thread_ids_.push_back(gRegistry->Add(peer));
Elliott Hughesa2155262011-11-16 16:26:58 -08001876 }
1877 }
1878
Ian Rogers365c1022012-06-22 15:05:28 -07001879 private:
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001880 bool IsInDesiredThreadGroup(mirror::Object* peer)
jeffhao0dfbb7e2012-11-28 15:26:03 -08001881 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
jeffhao0dfbb7e2012-11-28 15:26:03 -08001882 // peer might be NULL if the thread is still starting up.
1883 if (peer == NULL) {
1884 // We can't tell the debugger about this thread yet.
1885 // TODO: if we identified threads to the debugger by their Thread*
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001886 // rather than their peer's mirror::Object*, we could fix this.
jeffhao0dfbb7e2012-11-28 15:26:03 -08001887 // Doing so might help us report ZOMBIE threads too.
1888 return false;
1889 }
jeffhaoc1e04902012-12-13 12:41:10 -08001890 // Do we want threads from all thread groups?
1891 if (desired_thread_group_ == NULL) {
1892 return true;
1893 }
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001894 mirror::Object* group = soa_.DecodeField(WellKnownClasses::java_lang_Thread_group)->GetObject(peer);
jeffhao0dfbb7e2012-11-28 15:26:03 -08001895 return (group == desired_thread_group_);
1896 }
1897
Mathieu Chartierdbe6f462012-09-25 16:54:50 -07001898 const ScopedObjectAccessUnchecked& soa_;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001899 mirror::Object* const desired_thread_group_;
Elliott Hughescaf76542012-06-28 16:08:22 -07001900 std::vector<JDWP::ObjectId>& thread_ids_;
Elliott Hughesa2155262011-11-16 16:26:58 -08001901 };
1902
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001903 ScopedObjectAccessUnchecked soa(Thread::Current());
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001904 mirror::Object* thread_group = gRegistry->Get<mirror::Object*>(thread_group_id);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001905 ThreadListVisitor tlv(soa, thread_group, thread_ids);
Ian Rogers50b35e22012-10-04 10:09:15 -07001906 MutexLock mu(soa.Self(), *Locks::thread_list_lock_);
Elliott Hughesf8349362012-06-18 15:00:06 -07001907 Runtime::Current()->GetThreadList()->ForEach(ThreadListVisitor::Visit, &tlv);
Elliott Hughescaf76542012-06-28 16:08:22 -07001908}
Elliott Hughesa2155262011-11-16 16:26:58 -08001909
Elliott Hughescaf76542012-06-28 16:08:22 -07001910void Dbg::GetChildThreadGroups(JDWP::ObjectId thread_group_id, std::vector<JDWP::ObjectId>& child_thread_group_ids) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001911 ScopedObjectAccess soa(Thread::Current());
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001912 mirror::Object* thread_group = gRegistry->Get<mirror::Object*>(thread_group_id);
Elliott Hughescaf76542012-06-28 16:08:22 -07001913
1914 // Get the ArrayList<ThreadGroup> "groups" out of this thread group...
Brian Carlstromea46f952013-07-30 01:26:50 -07001915 mirror::ArtField* groups_field = thread_group->GetClass()->FindInstanceField("groups", "Ljava/util/List;");
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001916 mirror::Object* groups_array_list = groups_field->GetObject(thread_group);
Elliott Hughescaf76542012-06-28 16:08:22 -07001917
1918 // Get the array and size out of the ArrayList<ThreadGroup>...
Brian Carlstromea46f952013-07-30 01:26:50 -07001919 mirror::ArtField* array_field = groups_array_list->GetClass()->FindInstanceField("array", "[Ljava/lang/Object;");
1920 mirror::ArtField* size_field = groups_array_list->GetClass()->FindInstanceField("size", "I");
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001921 mirror::ObjectArray<mirror::Object>* groups_array =
1922 array_field->GetObject(groups_array_list)->AsObjectArray<mirror::Object>();
Elliott Hughescaf76542012-06-28 16:08:22 -07001923 const int32_t size = size_field->GetInt(groups_array_list);
1924
1925 // Copy the first 'size' elements out of the array into the result.
1926 for (int32_t i = 0; i < size; ++i) {
1927 child_thread_group_ids.push_back(gRegistry->Add(groups_array->Get(i)));
Elliott Hughesa2155262011-11-16 16:26:58 -08001928 }
1929}
1930
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001931static int GetStackDepth(Thread* thread)
Ian Rogersb726dcb2012-09-05 08:57:23 -07001932 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Ian Rogers0399dde2012-06-06 17:09:28 -07001933 struct CountStackDepthVisitor : public StackVisitor {
Brian Carlstrom93ba8932013-07-17 21:31:49 -07001934 explicit CountStackDepthVisitor(Thread* thread)
Ian Rogers7a22fa62013-01-23 12:16:16 -08001935 : StackVisitor(thread, NULL), depth(0) {}
Ian Rogers0399dde2012-06-06 17:09:28 -07001936
Elliott Hughes64f574f2013-02-20 14:57:12 -08001937 // TODO: Enable annotalysis. We know lock is held in constructor, but abstraction confuses
1938 // annotalysis.
1939 bool VisitFrame() NO_THREAD_SAFETY_ANALYSIS {
Ian Rogers0399dde2012-06-06 17:09:28 -07001940 if (!GetMethod()->IsRuntimeMethod()) {
Elliott Hughesf8a2df72011-12-01 12:19:54 -08001941 ++depth;
1942 }
Elliott Hughes530fa002012-03-12 11:44:49 -07001943 return true;
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001944 }
1945 size_t depth;
1946 };
Elliott Hughes08fc03a2012-06-26 17:34:00 -07001947
Ian Rogers7a22fa62013-01-23 12:16:16 -08001948 CountStackDepthVisitor visitor(thread);
Ian Rogers0399dde2012-06-06 17:09:28 -07001949 visitor.WalkStack();
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001950 return visitor.depth;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001951}
1952
Elliott Hughes221229c2013-01-08 18:17:50 -08001953JDWP::JdwpError Dbg::GetThreadFrameCount(JDWP::ObjectId thread_id, size_t& result) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001954 ScopedObjectAccess soa(Thread::Current());
jeffhaoa77f0f62012-12-05 17:19:31 -08001955 MutexLock mu(soa.Self(), *Locks::thread_list_lock_);
Elliott Hughes221229c2013-01-08 18:17:50 -08001956 Thread* thread;
1957 JDWP::JdwpError error = DecodeThread(soa, thread_id, thread);
1958 if (error != JDWP::ERR_NONE) {
1959 return error;
1960 }
Elliott Hughesf15f4a02013-01-09 10:09:38 -08001961 if (!IsSuspendedForDebugger(soa, thread)) {
1962 return JDWP::ERR_THREAD_NOT_SUSPENDED;
1963 }
Elliott Hughes221229c2013-01-08 18:17:50 -08001964 result = GetStackDepth(thread);
1965 return JDWP::ERR_NONE;
Elliott Hughes86964332012-02-15 19:37:42 -08001966}
1967
Ian Rogers306057f2012-11-26 12:45:53 -08001968JDWP::JdwpError Dbg::GetThreadFrames(JDWP::ObjectId thread_id, size_t start_frame,
1969 size_t frame_count, JDWP::ExpandBuf* buf) {
Elliott Hughes6e9d22c2012-06-22 15:02:37 -07001970 class GetFrameVisitor : public StackVisitor {
1971 public:
Ian Rogers7a22fa62013-01-23 12:16:16 -08001972 GetFrameVisitor(Thread* thread, size_t start_frame, size_t frame_count, JDWP::ExpandBuf* buf)
Ian Rogersb726dcb2012-09-05 08:57:23 -07001973 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_)
Ian Rogers7a22fa62013-01-23 12:16:16 -08001974 : StackVisitor(thread, NULL), depth_(0),
Elliott Hughes6e9d22c2012-06-22 15:02:37 -07001975 start_frame_(start_frame), frame_count_(frame_count), buf_(buf) {
1976 expandBufAdd4BE(buf_, frame_count_);
Elliott Hughes03181a82011-11-17 17:22:21 -08001977 }
Ian Rogers0399dde2012-06-06 17:09:28 -07001978
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001979 // TODO: Enable annotalysis. We know lock is held in constructor, but abstraction confuses
1980 // annotalysis.
1981 virtual bool VisitFrame() NO_THREAD_SAFETY_ANALYSIS {
Ian Rogers0399dde2012-06-06 17:09:28 -07001982 if (GetMethod()->IsRuntimeMethod()) {
Brian Carlstrom7934ac22013-07-26 10:54:15 -07001983 return true; // The debugger can't do anything useful with a frame that has no Method*.
Elliott Hughes03181a82011-11-17 17:22:21 -08001984 }
Elliott Hughes6e9d22c2012-06-22 15:02:37 -07001985 if (depth_ >= start_frame_ + frame_count_) {
Elliott Hughes530fa002012-03-12 11:44:49 -07001986 return false;
Elliott Hughes03181a82011-11-17 17:22:21 -08001987 }
Elliott Hughes6e9d22c2012-06-22 15:02:37 -07001988 if (depth_ >= start_frame_) {
1989 JDWP::FrameId frame_id(GetFrameId());
1990 JDWP::JdwpLocation location;
1991 SetLocation(location, GetMethod(), GetDexPc());
Ian Rogersef7d42f2014-01-06 12:55:46 -08001992 VLOG(jdwp) << StringPrintf(" Frame %3zd: id=%3" PRIu64 " ", depth_, frame_id) << location;
Elliott Hughes6e9d22c2012-06-22 15:02:37 -07001993 expandBufAdd8BE(buf_, frame_id);
1994 expandBufAddLocation(buf_, location);
1995 }
1996 ++depth_;
Elliott Hughes530fa002012-03-12 11:44:49 -07001997 return true;
Elliott Hughes03181a82011-11-17 17:22:21 -08001998 }
Elliott Hughes6e9d22c2012-06-22 15:02:37 -07001999
2000 private:
2001 size_t depth_;
2002 const size_t start_frame_;
2003 const size_t frame_count_;
2004 JDWP::ExpandBuf* buf_;
Elliott Hughes03181a82011-11-17 17:22:21 -08002005 };
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002006
2007 ScopedObjectAccessUnchecked soa(Thread::Current());
jeffhaoa77f0f62012-12-05 17:19:31 -08002008 MutexLock mu(soa.Self(), *Locks::thread_list_lock_);
Elliott Hughes221229c2013-01-08 18:17:50 -08002009 Thread* thread;
2010 JDWP::JdwpError error = DecodeThread(soa, thread_id, thread);
2011 if (error != JDWP::ERR_NONE) {
2012 return error;
2013 }
Elliott Hughesf15f4a02013-01-09 10:09:38 -08002014 if (!IsSuspendedForDebugger(soa, thread)) {
2015 return JDWP::ERR_THREAD_NOT_SUSPENDED;
2016 }
Ian Rogers7a22fa62013-01-23 12:16:16 -08002017 GetFrameVisitor visitor(thread, start_frame, frame_count, buf);
Ian Rogers0399dde2012-06-06 17:09:28 -07002018 visitor.WalkStack();
Elliott Hughes6e9d22c2012-06-22 15:02:37 -07002019 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002020}
2021
2022JDWP::ObjectId Dbg::GetThreadSelfId() {
Mathieu Chartierdbe6f462012-09-25 16:54:50 -07002023 ScopedObjectAccessUnchecked soa(Thread::Current());
Ian Rogerscfaa4552012-11-26 21:00:08 -08002024 return gRegistry->Add(soa.Self()->GetPeer());
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002025}
2026
Elliott Hughes475fc232011-10-25 15:00:35 -07002027void Dbg::SuspendVM() {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002028 Runtime::Current()->GetThreadList()->SuspendAllForDebugger();
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002029}
2030
2031void Dbg::ResumeVM() {
Elliott Hughesc61a2672012-06-21 14:52:29 -07002032 Runtime::Current()->GetThreadList()->UndoDebuggerSuspensions();
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002033}
2034
Elliott Hughes221229c2013-01-08 18:17:50 -08002035JDWP::JdwpError Dbg::SuspendThread(JDWP::ObjectId thread_id, bool request_suspension) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002036 ScopedLocalRef<jobject> peer(Thread::Current()->GetJniEnv(), NULL);
2037 {
2038 ScopedObjectAccess soa(Thread::Current());
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002039 peer.reset(soa.AddLocalReference<jobject>(gRegistry->Get<mirror::Object*>(thread_id)));
Elliott Hughes4e235312011-12-02 11:34:15 -08002040 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002041 if (peer.get() == NULL) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002042 return JDWP::ERR_THREAD_NOT_ALIVE;
2043 }
2044 // Suspend thread to build stack trace.
Elliott Hughesf327e072013-01-09 16:01:26 -08002045 bool timed_out;
Ian Rogersd9c4fc92013-10-01 19:45:43 -07002046 Thread* thread = ThreadList::SuspendThreadByPeer(peer.get(), request_suspension, true,
2047 &timed_out);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002048 if (thread != NULL) {
2049 return JDWP::ERR_NONE;
Elliott Hughesf327e072013-01-09 16:01:26 -08002050 } else if (timed_out) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002051 return JDWP::ERR_INTERNAL;
2052 } else {
2053 return JDWP::ERR_THREAD_NOT_ALIVE;
2054 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002055}
2056
Elliott Hughes221229c2013-01-08 18:17:50 -08002057void Dbg::ResumeThread(JDWP::ObjectId thread_id) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002058 ScopedObjectAccessUnchecked soa(Thread::Current());
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002059 mirror::Object* peer = gRegistry->Get<mirror::Object*>(thread_id);
jeffhaoa77f0f62012-12-05 17:19:31 -08002060 Thread* thread;
2061 {
2062 MutexLock mu(soa.Self(), *Locks::thread_list_lock_);
2063 thread = Thread::FromManagedThread(soa, peer);
2064 }
Elliott Hughes4e235312011-12-02 11:34:15 -08002065 if (thread == NULL) {
2066 LOG(WARNING) << "No such thread for resume: " << peer;
2067 return;
2068 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002069 bool needs_resume;
2070 {
Ian Rogers50b35e22012-10-04 10:09:15 -07002071 MutexLock mu2(soa.Self(), *Locks::thread_suspend_count_lock_);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002072 needs_resume = thread->GetSuspendCount() > 0;
2073 }
2074 if (needs_resume) {
Elliott Hughes546b9862012-06-20 16:06:13 -07002075 Runtime::Current()->GetThreadList()->Resume(thread, true);
2076 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002077}
2078
2079void Dbg::SuspendSelf() {
Elliott Hughes475fc232011-10-25 15:00:35 -07002080 Runtime::Current()->GetThreadList()->SuspendSelfForDebugger();
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002081}
2082
Ian Rogers0399dde2012-06-06 17:09:28 -07002083struct GetThisVisitor : public StackVisitor {
Ian Rogers7a22fa62013-01-23 12:16:16 -08002084 GetThisVisitor(Thread* thread, Context* context, JDWP::FrameId frame_id)
Ian Rogersb726dcb2012-09-05 08:57:23 -07002085 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_)
Ian Rogers7a22fa62013-01-23 12:16:16 -08002086 : StackVisitor(thread, context), this_object(NULL), frame_id(frame_id) {}
Ian Rogers0399dde2012-06-06 17:09:28 -07002087
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002088 // TODO: Enable annotalysis. We know lock is held in constructor, but abstraction confuses
2089 // annotalysis.
2090 virtual bool VisitFrame() NO_THREAD_SAFETY_ANALYSIS {
Elliott Hughes6e9d22c2012-06-22 15:02:37 -07002091 if (frame_id != GetFrameId()) {
Ian Rogers0399dde2012-06-06 17:09:28 -07002092 return true; // continue
Ian Rogers0399dde2012-06-06 17:09:28 -07002093 } else {
Ian Rogers62d6c772013-02-27 08:32:07 -08002094 this_object = GetThisObject();
2095 return false;
Ian Rogers0399dde2012-06-06 17:09:28 -07002096 }
Elliott Hughes86b00102011-12-05 17:54:26 -08002097 }
Ian Rogers0399dde2012-06-06 17:09:28 -07002098
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002099 mirror::Object* this_object;
Elliott Hughes6e9d22c2012-06-22 15:02:37 -07002100 JDWP::FrameId frame_id;
Ian Rogers0399dde2012-06-06 17:09:28 -07002101};
2102
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002103JDWP::JdwpError Dbg::GetThisObject(JDWP::ObjectId thread_id, JDWP::FrameId frame_id,
2104 JDWP::ObjectId* result) {
2105 ScopedObjectAccessUnchecked soa(Thread::Current());
2106 Thread* thread;
2107 {
Ian Rogers50b35e22012-10-04 10:09:15 -07002108 MutexLock mu(soa.Self(), *Locks::thread_list_lock_);
Elliott Hughes221229c2013-01-08 18:17:50 -08002109 JDWP::JdwpError error = DecodeThread(soa, thread_id, thread);
2110 if (error != JDWP::ERR_NONE) {
2111 return error;
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002112 }
Elliott Hughes9e0c1752013-01-09 14:02:58 -08002113 if (!IsSuspendedForDebugger(soa, thread)) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002114 return JDWP::ERR_THREAD_NOT_SUSPENDED;
2115 }
Elliott Hughes6e9d22c2012-06-22 15:02:37 -07002116 }
Elliott Hughescaf76542012-06-28 16:08:22 -07002117 UniquePtr<Context> context(Context::Create());
Ian Rogers7a22fa62013-01-23 12:16:16 -08002118 GetThisVisitor visitor(thread, context.get(), frame_id);
Ian Rogers0399dde2012-06-06 17:09:28 -07002119 visitor.WalkStack();
Elliott Hughes6e9d22c2012-06-22 15:02:37 -07002120 *result = gRegistry->Add(visitor.this_object);
2121 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002122}
2123
Ian Rogers98379392014-02-24 16:53:16 -08002124void Dbg::GetLocalValue(JDWP::ObjectId thread_id, JDWP::FrameId frame_id, int slot,
2125 JDWP::JdwpTag tag, uint8_t* buf, size_t width) {
Ian Rogers0399dde2012-06-06 17:09:28 -07002126 struct GetLocalVisitor : public StackVisitor {
Ian Rogers98379392014-02-24 16:53:16 -08002127 GetLocalVisitor(const ScopedObjectAccessUnchecked& soa, Thread* thread, Context* context,
2128 JDWP::FrameId frame_id, int slot, JDWP::JdwpTag tag, uint8_t* buf, size_t width)
Ian Rogersb726dcb2012-09-05 08:57:23 -07002129 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_)
Ian Rogers98379392014-02-24 16:53:16 -08002130 : StackVisitor(thread, context), soa_(soa), frame_id_(frame_id), slot_(slot), tag_(tag),
Ian Rogersca190662012-06-26 15:45:57 -07002131 buf_(buf), width_(width) {}
2132
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002133 // TODO: Enable annotalysis. We know lock is held in constructor, but abstraction confuses
2134 // annotalysis.
2135 bool VisitFrame() NO_THREAD_SAFETY_ANALYSIS {
Ian Rogers0399dde2012-06-06 17:09:28 -07002136 if (GetFrameId() != frame_id_) {
2137 return true; // Not our frame, carry on.
Elliott Hughesdbb40792011-11-18 17:05:22 -08002138 }
Ian Rogers0399dde2012-06-06 17:09:28 -07002139 // TODO: check that the tag is compatible with the actual type of the slot!
Brian Carlstromea46f952013-07-30 01:26:50 -07002140 mirror::ArtMethod* m = GetMethod();
Ian Rogers0399dde2012-06-06 17:09:28 -07002141 uint16_t reg = DemangleSlot(slot_, m);
Elliott Hughesdbb40792011-11-18 17:05:22 -08002142
Ian Rogers0399dde2012-06-06 17:09:28 -07002143 switch (tag_) {
2144 case JDWP::JT_BOOLEAN:
2145 {
2146 CHECK_EQ(width_, 1U);
Ian Rogers2bcb4a42012-11-08 10:39:18 -08002147 uint32_t intVal = GetVReg(m, reg, kIntVReg);
Ian Rogers0399dde2012-06-06 17:09:28 -07002148 VLOG(jdwp) << "get boolean local " << reg << " = " << intVal;
2149 JDWP::Set1(buf_+1, intVal != 0);
2150 }
2151 break;
2152 case JDWP::JT_BYTE:
2153 {
2154 CHECK_EQ(width_, 1U);
Ian Rogers2bcb4a42012-11-08 10:39:18 -08002155 uint32_t intVal = GetVReg(m, reg, kIntVReg);
Ian Rogers0399dde2012-06-06 17:09:28 -07002156 VLOG(jdwp) << "get byte local " << reg << " = " << intVal;
2157 JDWP::Set1(buf_+1, intVal);
2158 }
2159 break;
2160 case JDWP::JT_SHORT:
2161 case JDWP::JT_CHAR:
2162 {
2163 CHECK_EQ(width_, 2U);
Ian Rogers2bcb4a42012-11-08 10:39:18 -08002164 uint32_t intVal = GetVReg(m, reg, kIntVReg);
Ian Rogers0399dde2012-06-06 17:09:28 -07002165 VLOG(jdwp) << "get short/char local " << reg << " = " << intVal;
2166 JDWP::Set2BE(buf_+1, intVal);
2167 }
2168 break;
2169 case JDWP::JT_INT:
Ian Rogers2bcb4a42012-11-08 10:39:18 -08002170 {
2171 CHECK_EQ(width_, 4U);
2172 uint32_t intVal = GetVReg(m, reg, kIntVReg);
2173 VLOG(jdwp) << "get int local " << reg << " = " << intVal;
2174 JDWP::Set4BE(buf_+1, intVal);
2175 }
2176 break;
Ian Rogers0399dde2012-06-06 17:09:28 -07002177 case JDWP::JT_FLOAT:
2178 {
2179 CHECK_EQ(width_, 4U);
Ian Rogers2bcb4a42012-11-08 10:39:18 -08002180 uint32_t intVal = GetVReg(m, reg, kFloatVReg);
Ian Rogers0399dde2012-06-06 17:09:28 -07002181 VLOG(jdwp) << "get int/float local " << reg << " = " << intVal;
2182 JDWP::Set4BE(buf_+1, intVal);
2183 }
2184 break;
2185 case JDWP::JT_ARRAY:
2186 {
2187 CHECK_EQ(width_, sizeof(JDWP::ObjectId));
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002188 mirror::Object* o = reinterpret_cast<mirror::Object*>(GetVReg(m, reg, kReferenceVReg));
Ian Rogers0399dde2012-06-06 17:09:28 -07002189 VLOG(jdwp) << "get array local " << reg << " = " << o;
Mathieu Chartier590fee92013-09-13 13:46:47 -07002190 if (!Runtime::Current()->GetHeap()->IsValidObjectAddress(o)) {
Ian Rogers0399dde2012-06-06 17:09:28 -07002191 LOG(FATAL) << "Register " << reg << " expected to hold array: " << o;
2192 }
2193 JDWP::SetObjectId(buf_+1, gRegistry->Add(o));
2194 }
2195 break;
2196 case JDWP::JT_CLASS_LOADER:
2197 case JDWP::JT_CLASS_OBJECT:
2198 case JDWP::JT_OBJECT:
2199 case JDWP::JT_STRING:
2200 case JDWP::JT_THREAD:
2201 case JDWP::JT_THREAD_GROUP:
2202 {
2203 CHECK_EQ(width_, sizeof(JDWP::ObjectId));
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002204 mirror::Object* o = reinterpret_cast<mirror::Object*>(GetVReg(m, reg, kReferenceVReg));
Ian Rogers0399dde2012-06-06 17:09:28 -07002205 VLOG(jdwp) << "get object local " << reg << " = " << o;
Mathieu Chartier590fee92013-09-13 13:46:47 -07002206 if (!Runtime::Current()->GetHeap()->IsValidObjectAddress(o)) {
Ian Rogers0399dde2012-06-06 17:09:28 -07002207 LOG(FATAL) << "Register " << reg << " expected to hold object: " << o;
2208 }
Ian Rogers98379392014-02-24 16:53:16 -08002209 tag_ = TagFromObject(soa_, o);
Ian Rogers0399dde2012-06-06 17:09:28 -07002210 JDWP::SetObjectId(buf_+1, gRegistry->Add(o));
2211 }
2212 break;
2213 case JDWP::JT_DOUBLE:
Ian Rogers2bcb4a42012-11-08 10:39:18 -08002214 {
2215 CHECK_EQ(width_, 8U);
2216 uint32_t lo = GetVReg(m, reg, kDoubleLoVReg);
2217 uint64_t hi = GetVReg(m, reg + 1, kDoubleHiVReg);
2218 uint64_t longVal = (hi << 32) | lo;
2219 VLOG(jdwp) << "get double/long local " << hi << ":" << lo << " = " << longVal;
2220 JDWP::Set8BE(buf_+1, longVal);
2221 }
2222 break;
Ian Rogers0399dde2012-06-06 17:09:28 -07002223 case JDWP::JT_LONG:
2224 {
2225 CHECK_EQ(width_, 8U);
Ian Rogers2bcb4a42012-11-08 10:39:18 -08002226 uint32_t lo = GetVReg(m, reg, kLongLoVReg);
2227 uint64_t hi = GetVReg(m, reg + 1, kLongHiVReg);
Ian Rogers0399dde2012-06-06 17:09:28 -07002228 uint64_t longVal = (hi << 32) | lo;
2229 VLOG(jdwp) << "get double/long local " << hi << ":" << lo << " = " << longVal;
2230 JDWP::Set8BE(buf_+1, longVal);
2231 }
2232 break;
2233 default:
2234 LOG(FATAL) << "Unknown tag " << tag_;
2235 break;
2236 }
2237
2238 // Prepend tag, which may have been updated.
2239 JDWP::Set1(buf_, tag_);
2240 return false;
2241 }
Ian Rogers98379392014-02-24 16:53:16 -08002242 const ScopedObjectAccessUnchecked& soa_;
Ian Rogers0399dde2012-06-06 17:09:28 -07002243 const JDWP::FrameId frame_id_;
2244 const int slot_;
2245 JDWP::JdwpTag tag_;
2246 uint8_t* const buf_;
2247 const size_t width_;
2248 };
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002249
2250 ScopedObjectAccessUnchecked soa(Thread::Current());
jeffhaoa77f0f62012-12-05 17:19:31 -08002251 MutexLock mu(soa.Self(), *Locks::thread_list_lock_);
Elliott Hughes221229c2013-01-08 18:17:50 -08002252 Thread* thread;
2253 JDWP::JdwpError error = DecodeThread(soa, thread_id, thread);
2254 if (error != JDWP::ERR_NONE) {
2255 return;
2256 }
Ian Rogers0399dde2012-06-06 17:09:28 -07002257 UniquePtr<Context> context(Context::Create());
Ian Rogers98379392014-02-24 16:53:16 -08002258 GetLocalVisitor visitor(soa, thread, context.get(), frame_id, slot, tag, buf, width);
Ian Rogers0399dde2012-06-06 17:09:28 -07002259 visitor.WalkStack();
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002260}
2261
Elliott Hughes88d63092013-01-09 09:55:54 -08002262void Dbg::SetLocalValue(JDWP::ObjectId thread_id, JDWP::FrameId frame_id, int slot, JDWP::JdwpTag tag,
Ian Rogers0399dde2012-06-06 17:09:28 -07002263 uint64_t value, size_t width) {
2264 struct SetLocalVisitor : public StackVisitor {
Ian Rogers7a22fa62013-01-23 12:16:16 -08002265 SetLocalVisitor(Thread* thread, Context* context,
Ian Rogers0399dde2012-06-06 17:09:28 -07002266 JDWP::FrameId frame_id, int slot, JDWP::JdwpTag tag, uint64_t value,
Ian Rogersca190662012-06-26 15:45:57 -07002267 size_t width)
Ian Rogersb726dcb2012-09-05 08:57:23 -07002268 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_)
Ian Rogers7a22fa62013-01-23 12:16:16 -08002269 : StackVisitor(thread, context),
Elliott Hughes08fc03a2012-06-26 17:34:00 -07002270 frame_id_(frame_id), slot_(slot), tag_(tag), value_(value), width_(width) {}
Ian Rogersca190662012-06-26 15:45:57 -07002271
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002272 // TODO: Enable annotalysis. We know lock is held in constructor, but abstraction confuses
2273 // annotalysis.
2274 bool VisitFrame() NO_THREAD_SAFETY_ANALYSIS {
Ian Rogers0399dde2012-06-06 17:09:28 -07002275 if (GetFrameId() != frame_id_) {
2276 return true; // Not our frame, carry on.
2277 }
2278 // TODO: check that the tag is compatible with the actual type of the slot!
Brian Carlstromea46f952013-07-30 01:26:50 -07002279 mirror::ArtMethod* m = GetMethod();
Ian Rogers0399dde2012-06-06 17:09:28 -07002280 uint16_t reg = DemangleSlot(slot_, m);
2281
2282 switch (tag_) {
2283 case JDWP::JT_BOOLEAN:
2284 case JDWP::JT_BYTE:
2285 CHECK_EQ(width_, 1U);
Ian Rogers2bcb4a42012-11-08 10:39:18 -08002286 SetVReg(m, reg, static_cast<uint32_t>(value_), kIntVReg);
Ian Rogers0399dde2012-06-06 17:09:28 -07002287 break;
2288 case JDWP::JT_SHORT:
2289 case JDWP::JT_CHAR:
2290 CHECK_EQ(width_, 2U);
Ian Rogers2bcb4a42012-11-08 10:39:18 -08002291 SetVReg(m, reg, static_cast<uint32_t>(value_), kIntVReg);
Ian Rogers0399dde2012-06-06 17:09:28 -07002292 break;
2293 case JDWP::JT_INT:
Ian Rogers2bcb4a42012-11-08 10:39:18 -08002294 CHECK_EQ(width_, 4U);
2295 SetVReg(m, reg, static_cast<uint32_t>(value_), kIntVReg);
2296 break;
Ian Rogers0399dde2012-06-06 17:09:28 -07002297 case JDWP::JT_FLOAT:
2298 CHECK_EQ(width_, 4U);
Ian Rogers2bcb4a42012-11-08 10:39:18 -08002299 SetVReg(m, reg, static_cast<uint32_t>(value_), kFloatVReg);
Ian Rogers0399dde2012-06-06 17:09:28 -07002300 break;
2301 case JDWP::JT_ARRAY:
2302 case JDWP::JT_OBJECT:
2303 case JDWP::JT_STRING:
2304 {
2305 CHECK_EQ(width_, sizeof(JDWP::ObjectId));
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002306 mirror::Object* o = gRegistry->Get<mirror::Object*>(static_cast<JDWP::ObjectId>(value_));
Elliott Hughes64f574f2013-02-20 14:57:12 -08002307 if (o == ObjectRegistry::kInvalidObject) {
Ian Rogers0399dde2012-06-06 17:09:28 -07002308 UNIMPLEMENTED(FATAL) << "return an error code when given an invalid object to store";
2309 }
Ian Rogers2bcb4a42012-11-08 10:39:18 -08002310 SetVReg(m, reg, static_cast<uint32_t>(reinterpret_cast<uintptr_t>(o)), kReferenceVReg);
Ian Rogers0399dde2012-06-06 17:09:28 -07002311 }
2312 break;
2313 case JDWP::JT_DOUBLE:
Ian Rogers2bcb4a42012-11-08 10:39:18 -08002314 CHECK_EQ(width_, 8U);
2315 SetVReg(m, reg, static_cast<uint32_t>(value_), kDoubleLoVReg);
2316 SetVReg(m, reg + 1, static_cast<uint32_t>(value_ >> 32), kDoubleHiVReg);
2317 break;
Ian Rogers0399dde2012-06-06 17:09:28 -07002318 case JDWP::JT_LONG:
2319 CHECK_EQ(width_, 8U);
Ian Rogers2bcb4a42012-11-08 10:39:18 -08002320 SetVReg(m, reg, static_cast<uint32_t>(value_), kLongLoVReg);
2321 SetVReg(m, reg + 1, static_cast<uint32_t>(value_ >> 32), kLongHiVReg);
Ian Rogers0399dde2012-06-06 17:09:28 -07002322 break;
2323 default:
2324 LOG(FATAL) << "Unknown tag " << tag_;
2325 break;
2326 }
2327 return false;
2328 }
2329
2330 const JDWP::FrameId frame_id_;
2331 const int slot_;
2332 const JDWP::JdwpTag tag_;
2333 const uint64_t value_;
2334 const size_t width_;
2335 };
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002336
2337 ScopedObjectAccessUnchecked soa(Thread::Current());
jeffhaoa77f0f62012-12-05 17:19:31 -08002338 MutexLock mu(soa.Self(), *Locks::thread_list_lock_);
Elliott Hughes221229c2013-01-08 18:17:50 -08002339 Thread* thread;
2340 JDWP::JdwpError error = DecodeThread(soa, thread_id, thread);
2341 if (error != JDWP::ERR_NONE) {
2342 return;
2343 }
Elliott Hughes08fc03a2012-06-26 17:34:00 -07002344 UniquePtr<Context> context(Context::Create());
Ian Rogers7a22fa62013-01-23 12:16:16 -08002345 SetLocalVisitor visitor(thread, context.get(), frame_id, slot, tag, value, width);
Ian Rogers0399dde2012-06-06 17:09:28 -07002346 visitor.WalkStack();
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002347}
2348
Ian Rogersef7d42f2014-01-06 12:55:46 -08002349void Dbg::PostLocationEvent(mirror::ArtMethod* m, int dex_pc, mirror::Object* this_object,
Jeff Hao579b0242013-11-18 13:16:49 -08002350 int event_flags, const JValue* return_value) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002351 mirror::Class* c = m->GetDeclaringClass();
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08002352
2353 JDWP::JdwpLocation location;
Elliott Hughes74847412012-06-20 18:10:21 -07002354 location.type_tag = c->IsInterface() ? JDWP::TT_INTERFACE : JDWP::TT_CLASS;
Elliott Hughes64f574f2013-02-20 14:57:12 -08002355 location.class_id = gRegistry->AddRefType(c);
Elliott Hughes74847412012-06-20 18:10:21 -07002356 location.method_id = ToMethodId(m);
Elliott Hughes972a47b2012-02-21 18:16:06 -08002357 location.dex_pc = m->IsNative() ? -1 : dex_pc;
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08002358
Elliott Hughes64f574f2013-02-20 14:57:12 -08002359 // If 'this_object' isn't already in the registry, we know that we're not looking for it,
2360 // so there's no point adding it to the registry and burning through ids.
2361 JDWP::ObjectId this_id = 0;
2362 if (gRegistry->Contains(this_object)) {
2363 this_id = gRegistry->Add(this_object);
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08002364 }
Jeff Hao579b0242013-11-18 13:16:49 -08002365 gJdwpState->PostLocationEvent(&location, this_id, event_flags, return_value);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002366}
2367
Ian Rogers62d6c772013-02-27 08:32:07 -08002368void Dbg::PostException(Thread* thread, const ThrowLocation& throw_location,
Brian Carlstromea46f952013-07-30 01:26:50 -07002369 mirror::ArtMethod* catch_method,
Elliott Hughes64f574f2013-02-20 14:57:12 -08002370 uint32_t catch_dex_pc, mirror::Throwable* exception_object) {
Elliott Hughesc0f09332012-03-26 13:27:06 -07002371 if (!IsDebuggerActive()) {
Ian Rogers0ad5bb82011-12-07 10:16:32 -08002372 return;
2373 }
Elliott Hughes4740cdf2011-12-07 14:07:12 -08002374
Ian Rogers62d6c772013-02-27 08:32:07 -08002375 JDWP::JdwpLocation jdwp_throw_location;
2376 SetLocation(jdwp_throw_location, throw_location.GetMethod(), throw_location.GetDexPc());
Elliott Hughesd07986f2011-12-06 18:27:45 -08002377 JDWP::JdwpLocation catch_location;
Elliott Hughescaf76542012-06-28 16:08:22 -07002378 SetLocation(catch_location, catch_method, catch_dex_pc);
Elliott Hughesd07986f2011-12-06 18:27:45 -08002379
2380 // We need 'this' for InstanceOnly filters.
Ian Rogers62d6c772013-02-27 08:32:07 -08002381 JDWP::ObjectId this_id = gRegistry->Add(throw_location.GetThis());
Elliott Hughes64f574f2013-02-20 14:57:12 -08002382 JDWP::ObjectId exception_id = gRegistry->Add(exception_object);
2383 JDWP::RefTypeId exception_class_id = gRegistry->AddRefType(exception_object->GetClass());
Elliott Hughesd07986f2011-12-06 18:27:45 -08002384
Ian Rogers62d6c772013-02-27 08:32:07 -08002385 gJdwpState->PostException(&jdwp_throw_location, exception_id, exception_class_id, &catch_location,
2386 this_id);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002387}
2388
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002389void Dbg::PostClassPrepare(mirror::Class* c) {
Elliott Hughesc0f09332012-03-26 13:27:06 -07002390 if (!IsDebuggerActive()) {
Elliott Hughes4740cdf2011-12-07 14:07:12 -08002391 return;
2392 }
2393
Elliott Hughes3d30d9b2011-12-07 17:35:48 -08002394 // OLD-TODO - we currently always send both "verified" and "prepared" since
Elliott Hughes4740cdf2011-12-07 14:07:12 -08002395 // debuggers seem to like that. There might be some advantage to honesty,
2396 // since the class may not yet be verified.
2397 int state = JDWP::CS_VERIFIED | JDWP::CS_PREPARED;
2398 JDWP::JdwpTypeTag tag = c->IsInterface() ? JDWP::TT_INTERFACE : JDWP::TT_CLASS;
Ian Rogersfc0e94b2013-09-23 23:51:32 -07002399 gJdwpState->PostClassPrepare(tag, gRegistry->Add(c),
Ian Rogersdfb325e2013-10-30 01:00:44 -07002400 ClassHelper(c).GetDescriptor(), state);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002401}
2402
Ian Rogers62d6c772013-02-27 08:32:07 -08002403void Dbg::UpdateDebugger(Thread* thread, mirror::Object* this_object,
Ian Rogersef7d42f2014-01-06 12:55:46 -08002404 mirror::ArtMethod* m, uint32_t dex_pc) {
Ian Rogers62d6c772013-02-27 08:32:07 -08002405 if (!IsDebuggerActive() || dex_pc == static_cast<uint32_t>(-2) /* fake method exit */) {
Elliott Hughes2aa2e392012-02-17 17:15:43 -08002406 return;
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08002407 }
2408
Elliott Hughes2aa2e392012-02-17 17:15:43 -08002409 int event_flags = 0;
2410
Elliott Hughes86964332012-02-15 19:37:42 -08002411 if (IsBreakpoint(m, dex_pc)) {
2412 event_flags |= kBreakpoint;
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08002413 }
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08002414
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01002415 // If the debugger is single-stepping one of our threads, check to
2416 // see if we're that thread and we've reached a step point.
2417 const SingleStepControl* single_step_control = thread->GetSingleStepControl();
2418 DCHECK(single_step_control != nullptr);
2419 if (single_step_control->is_active) {
2420 CHECK(!m->IsNative());
2421 if (single_step_control->step_depth == JDWP::SD_INTO) {
2422 // Step into method calls. We break when the line number
2423 // or method pointer changes. If we're in SS_MIN mode, we
2424 // always stop.
2425 if (single_step_control->method != m) {
2426 event_flags |= kSingleStep;
2427 VLOG(jdwp) << "SS new method";
2428 } else if (single_step_control->step_size == JDWP::SS_MIN) {
2429 event_flags |= kSingleStep;
2430 VLOG(jdwp) << "SS new instruction";
2431 } else if (single_step_control->dex_pcs.find(dex_pc) == single_step_control->dex_pcs.end()) {
2432 event_flags |= kSingleStep;
2433 VLOG(jdwp) << "SS new line";
2434 }
2435 } else if (single_step_control->step_depth == JDWP::SD_OVER) {
2436 // Step over method calls. We break when the line number is
2437 // different and the frame depth is <= the original frame
2438 // depth. (We can't just compare on the method, because we
2439 // might get unrolled past it by an exception, and it's tricky
2440 // to identify recursion.)
2441
2442 int stack_depth = GetStackDepth(thread);
2443
2444 if (stack_depth < single_step_control->stack_depth) {
2445 // Popped up one or more frames, always trigger.
2446 event_flags |= kSingleStep;
2447 VLOG(jdwp) << "SS method pop";
2448 } else if (stack_depth == single_step_control->stack_depth) {
2449 // Same depth, see if we moved.
2450 if (single_step_control->step_size == JDWP::SS_MIN) {
Elliott Hughes86964332012-02-15 19:37:42 -08002451 event_flags |= kSingleStep;
2452 VLOG(jdwp) << "SS new instruction";
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01002453 } else if (single_step_control->dex_pcs.find(dex_pc) == single_step_control->dex_pcs.end()) {
Elliott Hughes2435a572012-02-17 16:07:41 -08002454 event_flags |= kSingleStep;
2455 VLOG(jdwp) << "SS new line";
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08002456 }
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01002457 }
2458 } else {
2459 CHECK_EQ(single_step_control->step_depth, JDWP::SD_OUT);
2460 // Return from the current method. We break when the frame
2461 // depth pops up.
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08002462
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01002463 // This differs from the "method exit" break in that it stops
2464 // with the PC at the next instruction in the returned-to
2465 // function, rather than the end of the returning function.
Elliott Hughes86964332012-02-15 19:37:42 -08002466
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01002467 int stack_depth = GetStackDepth(thread);
2468 if (stack_depth < single_step_control->stack_depth) {
2469 event_flags |= kSingleStep;
2470 VLOG(jdwp) << "SS method pop";
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08002471 }
2472 }
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08002473 }
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08002474
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08002475 // If there's something interesting going on, see if it matches one
2476 // of the debugger filters.
2477 if (event_flags != 0) {
Jeff Hao579b0242013-11-18 13:16:49 -08002478 Dbg::PostLocationEvent(m, dex_pc, this_object, event_flags, nullptr);
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08002479 }
2480}
2481
Sebastien Hertz138dbfc2013-12-04 18:15:25 +01002482static void ProcessDeoptimizationRequests()
2483 LOCKS_EXCLUDED(Locks::deoptimization_lock_)
2484 EXCLUSIVE_LOCKS_REQUIRED(Locks::mutator_lock_) {
2485 Locks::mutator_lock_->AssertExclusiveHeld(Thread::Current());
2486 MutexLock mu(Thread::Current(), *Locks::deoptimization_lock_);
2487 instrumentation::Instrumentation* instrumentation = Runtime::Current()->GetInstrumentation();
2488 for (const MethodInstrumentationRequest& request : gDeoptimizationRequests) {
2489 mirror::ArtMethod* const method = request.method;
2490 if (method != nullptr) {
2491 // Selective deoptimization.
2492 if (request.deoptimize) {
2493 VLOG(jdwp) << "Deoptimize method " << PrettyMethod(method);
2494 instrumentation->Deoptimize(method);
2495 } else {
2496 VLOG(jdwp) << "Undeoptimize method " << PrettyMethod(method);
2497 instrumentation->Undeoptimize(method);
2498 }
2499 } else {
2500 // Full deoptimization.
2501 if (request.deoptimize) {
2502 VLOG(jdwp) << "Deoptimize the world";
2503 instrumentation->DeoptimizeEverything();
2504 } else {
2505 VLOG(jdwp) << "Undeoptimize the world";
2506 instrumentation->UndeoptimizeEverything();
2507 }
2508 }
2509 }
2510 gDeoptimizationRequests.clear();
2511}
2512
2513// Process deoptimization requests after suspending all mutator threads.
2514void Dbg::ManageDeoptimization() {
2515 Thread* const self = Thread::Current();
2516 {
2517 // Avoid suspend/resume if there is no pending request.
2518 MutexLock mu(self, *Locks::deoptimization_lock_);
2519 if (gDeoptimizationRequests.empty()) {
2520 return;
2521 }
2522 }
2523 CHECK_EQ(self->GetState(), kRunnable);
2524 self->TransitionFromRunnableToSuspended(kWaitingForDeoptimization);
2525 // We need to suspend mutator threads first.
2526 Runtime* const runtime = Runtime::Current();
2527 runtime->GetThreadList()->SuspendAll();
2528 const ThreadState old_state = self->SetStateUnsafe(kRunnable);
2529 ProcessDeoptimizationRequests();
2530 CHECK_EQ(self->SetStateUnsafe(old_state), kRunnable);
2531 runtime->GetThreadList()->ResumeAll();
2532 self->TransitionFromSuspendedToRunnable();
2533}
2534
2535// Enable full deoptimization.
2536void Dbg::EnableFullDeoptimization() {
2537 MutexLock mu(Thread::Current(), *Locks::deoptimization_lock_);
2538 VLOG(jdwp) << "Request full deoptimization";
2539 gDeoptimizationRequests.push_back(MethodInstrumentationRequest(true, nullptr));
2540}
2541
2542// Disable full deoptimization.
2543void Dbg::DisableFullDeoptimization() {
2544 MutexLock mu(Thread::Current(), *Locks::deoptimization_lock_);
2545 VLOG(jdwp) << "Request full undeoptimization";
2546 gDeoptimizationRequests.push_back(MethodInstrumentationRequest(false, nullptr));
2547}
2548
Elliott Hughes86964332012-02-15 19:37:42 -08002549void Dbg::WatchLocation(const JDWP::JdwpLocation* location) {
Sebastien Hertz138dbfc2013-12-04 18:15:25 +01002550 bool need_deoptimization = true;
Brian Carlstromea46f952013-07-30 01:26:50 -07002551 mirror::ArtMethod* m = FromMethodId(location->method_id);
Sebastien Hertz138dbfc2013-12-04 18:15:25 +01002552 {
2553 MutexLock mu(Thread::Current(), *Locks::breakpoint_lock_);
2554
2555 // If there is no breakpoint on this method yet, we need to deoptimize it.
2556 for (const Breakpoint& breakpoint : gBreakpoints) {
2557 if (breakpoint.method == m) {
2558 // We already set a breakpoint on this method, hence we deoptimized it.
2559 DCHECK(Runtime::Current()->GetInstrumentation()->IsDeoptimized(m));
2560 need_deoptimization = false;
2561 break;
2562 }
2563 }
2564
2565 gBreakpoints.push_back(Breakpoint(m, location->dex_pc));
2566 VLOG(jdwp) << "Set breakpoint #" << (gBreakpoints.size() - 1) << ": " << gBreakpoints[gBreakpoints.size() - 1];
2567 }
2568
2569 if (need_deoptimization) {
2570 // Request its deoptimization. This will be done after updating the JDWP event list.
2571 MutexLock mu(Thread::Current(), *Locks::deoptimization_lock_);
2572 gDeoptimizationRequests.push_back(MethodInstrumentationRequest(true, m));
2573 VLOG(jdwp) << "Request deoptimization of " << PrettyMethod(m);
2574 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002575}
2576
Elliott Hughes86964332012-02-15 19:37:42 -08002577void Dbg::UnwatchLocation(const JDWP::JdwpLocation* location) {
Sebastien Hertz138dbfc2013-12-04 18:15:25 +01002578 bool can_undeoptimize = true;
Brian Carlstromea46f952013-07-30 01:26:50 -07002579 mirror::ArtMethod* m = FromMethodId(location->method_id);
Sebastien Hertz138dbfc2013-12-04 18:15:25 +01002580 DCHECK(Runtime::Current()->GetInstrumentation()->IsDeoptimized(m));
2581 {
2582 MutexLock mu(Thread::Current(), *Locks::breakpoint_lock_);
2583 for (size_t i = 0, e = gBreakpoints.size(); i < e; ++i) {
2584 if (gBreakpoints[i].method == m && gBreakpoints[i].dex_pc == location->dex_pc) {
2585 VLOG(jdwp) << "Removed breakpoint #" << i << ": " << gBreakpoints[i];
2586 gBreakpoints.erase(gBreakpoints.begin() + i);
2587 break;
2588 }
Elliott Hughes86964332012-02-15 19:37:42 -08002589 }
Sebastien Hertz138dbfc2013-12-04 18:15:25 +01002590
2591 // If there is no breakpoint on this method, we can undeoptimize it.
2592 for (const Breakpoint& breakpoint : gBreakpoints) {
2593 if (breakpoint.method == m) {
2594 can_undeoptimize = false;
2595 break;
2596 }
2597 }
2598 }
2599
2600 if (can_undeoptimize) {
2601 // Request its undeoptimization. This will be done after updating the JDWP event list.
2602 MutexLock mu(Thread::Current(), *Locks::deoptimization_lock_);
2603 gDeoptimizationRequests.push_back(MethodInstrumentationRequest(false, m));
2604 VLOG(jdwp) << "Request undeoptimization of " << PrettyMethod(m);
Elliott Hughes86964332012-02-15 19:37:42 -08002605 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002606}
2607
Jeff Hao449db332013-04-12 18:30:52 -07002608// Scoped utility class to suspend a thread so that we may do tasks such as walk its stack. Doesn't
2609// cause suspension if the thread is the current thread.
2610class ScopedThreadSuspension {
2611 public:
Ian Rogers33e95662013-05-20 20:29:14 -07002612 ScopedThreadSuspension(Thread* self, JDWP::ObjectId thread_id)
2613 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) :
Jeff Hao449db332013-04-12 18:30:52 -07002614 thread_(NULL),
2615 error_(JDWP::ERR_NONE),
2616 self_suspend_(false),
Ian Rogers33e95662013-05-20 20:29:14 -07002617 other_suspend_(false) {
Jeff Hao449db332013-04-12 18:30:52 -07002618 ScopedObjectAccessUnchecked soa(self);
2619 {
2620 MutexLock mu(soa.Self(), *Locks::thread_list_lock_);
2621 error_ = DecodeThread(soa, thread_id, thread_);
2622 }
2623 if (error_ == JDWP::ERR_NONE) {
2624 if (thread_ == soa.Self()) {
2625 self_suspend_ = true;
2626 } else {
2627 soa.Self()->TransitionFromRunnableToSuspended(kWaitingForDebuggerSuspension);
2628 jobject thread_peer = gRegistry->GetJObject(thread_id);
2629 bool timed_out;
Ian Rogersd9c4fc92013-10-01 19:45:43 -07002630 Thread* suspended_thread = ThreadList::SuspendThreadByPeer(thread_peer, true, true,
2631 &timed_out);
Jeff Hao449db332013-04-12 18:30:52 -07002632 CHECK_EQ(soa.Self()->TransitionFromSuspendedToRunnable(), kWaitingForDebuggerSuspension);
2633 if (suspended_thread == NULL) {
2634 // Thread terminated from under us while suspending.
2635 error_ = JDWP::ERR_INVALID_THREAD;
2636 } else {
2637 CHECK_EQ(suspended_thread, thread_);
2638 other_suspend_ = true;
2639 }
2640 }
2641 }
Elliott Hughes2435a572012-02-17 16:07:41 -08002642 }
Elliott Hughes86964332012-02-15 19:37:42 -08002643
Jeff Hao449db332013-04-12 18:30:52 -07002644 Thread* GetThread() const {
2645 return thread_;
2646 }
2647
2648 JDWP::JdwpError GetError() const {
2649 return error_;
2650 }
2651
2652 ~ScopedThreadSuspension() {
2653 if (other_suspend_) {
2654 Runtime::Current()->GetThreadList()->Resume(thread_, true);
2655 }
2656 }
2657
2658 private:
2659 Thread* thread_;
2660 JDWP::JdwpError error_;
2661 bool self_suspend_;
2662 bool other_suspend_;
2663};
2664
2665JDWP::JdwpError Dbg::ConfigureStep(JDWP::ObjectId thread_id, JDWP::JdwpStepSize step_size,
2666 JDWP::JdwpStepDepth step_depth) {
2667 Thread* self = Thread::Current();
2668 ScopedThreadSuspension sts(self, thread_id);
2669 if (sts.GetError() != JDWP::ERR_NONE) {
2670 return sts.GetError();
2671 }
2672
Elliott Hughes2435a572012-02-17 16:07:41 -08002673 //
2674 // Work out what Method* we're in, the current line number, and how deep the stack currently
2675 // is for step-out.
2676 //
2677
Ian Rogers0399dde2012-06-06 17:09:28 -07002678 struct SingleStepStackVisitor : public StackVisitor {
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01002679 explicit SingleStepStackVisitor(Thread* thread, SingleStepControl* single_step_control,
2680 int32_t* line_number)
Ian Rogersb726dcb2012-09-05 08:57:23 -07002681 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_)
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01002682 : StackVisitor(thread, NULL), single_step_control_(single_step_control),
2683 line_number_(line_number) {
2684 DCHECK_EQ(single_step_control_, thread->GetSingleStepControl());
2685 single_step_control_->method = NULL;
2686 single_step_control_->stack_depth = 0;
Elliott Hughes86964332012-02-15 19:37:42 -08002687 }
Ian Rogersca190662012-06-26 15:45:57 -07002688
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002689 // TODO: Enable annotalysis. We know lock is held in constructor, but abstraction confuses
2690 // annotalysis.
2691 bool VisitFrame() NO_THREAD_SAFETY_ANALYSIS {
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01002692 mirror::ArtMethod* m = GetMethod();
Ian Rogers0399dde2012-06-06 17:09:28 -07002693 if (!m->IsRuntimeMethod()) {
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01002694 ++single_step_control_->stack_depth;
2695 if (single_step_control_->method == NULL) {
Ian Rogersef7d42f2014-01-06 12:55:46 -08002696 mirror::DexCache* dex_cache = m->GetDeclaringClass()->GetDexCache();
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01002697 single_step_control_->method = m;
2698 *line_number_ = -1;
Elliott Hughes2435a572012-02-17 16:07:41 -08002699 if (dex_cache != NULL) {
Ian Rogers4445a7e2012-10-05 17:19:13 -07002700 const DexFile& dex_file = *dex_cache->GetDexFile();
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01002701 *line_number_ = dex_file.GetLineNumFromPC(m, GetDexPc());
Elliott Hughes2435a572012-02-17 16:07:41 -08002702 }
Elliott Hughes86964332012-02-15 19:37:42 -08002703 }
2704 }
Elliott Hughes530fa002012-03-12 11:44:49 -07002705 return true;
Elliott Hughes86964332012-02-15 19:37:42 -08002706 }
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01002707
2708 SingleStepControl* const single_step_control_;
2709 int32_t* const line_number_;
Elliott Hughes86964332012-02-15 19:37:42 -08002710 };
Jeff Hao449db332013-04-12 18:30:52 -07002711
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01002712 Thread* const thread = sts.GetThread();
2713 SingleStepControl* const single_step_control = thread->GetSingleStepControl();
2714 DCHECK(single_step_control != nullptr);
2715 int32_t line_number = -1;
2716 SingleStepStackVisitor visitor(thread, single_step_control, &line_number);
Ian Rogers0399dde2012-06-06 17:09:28 -07002717 visitor.WalkStack();
Elliott Hughes86964332012-02-15 19:37:42 -08002718
Elliott Hughes2435a572012-02-17 16:07:41 -08002719 //
2720 // Find the dex_pc values that correspond to the current line, for line-based single-stepping.
2721 //
2722
2723 struct DebugCallbackContext {
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01002724 explicit DebugCallbackContext(SingleStepControl* single_step_control, int32_t line_number)
2725 : single_step_control_(single_step_control), line_number_(line_number),
2726 last_pc_valid(false), last_pc(0) {
Elliott Hughes2435a572012-02-17 16:07:41 -08002727 }
2728
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01002729 static bool Callback(void* raw_context, uint32_t address, uint32_t line_number) {
Elliott Hughes2435a572012-02-17 16:07:41 -08002730 DebugCallbackContext* context = reinterpret_cast<DebugCallbackContext*>(raw_context);
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01002731 if (static_cast<int32_t>(line_number) == context->line_number_) {
Elliott Hughes2435a572012-02-17 16:07:41 -08002732 if (!context->last_pc_valid) {
2733 // Everything from this address until the next line change is ours.
2734 context->last_pc = address;
2735 context->last_pc_valid = true;
2736 }
2737 // Otherwise, if we're already in a valid range for this line,
2738 // just keep going (shouldn't really happen)...
Brian Carlstrom7934ac22013-07-26 10:54:15 -07002739 } else if (context->last_pc_valid) { // and the line number is new
Elliott Hughes2435a572012-02-17 16:07:41 -08002740 // Add everything from the last entry up until here to the set
2741 for (uint32_t dex_pc = context->last_pc; dex_pc < address; ++dex_pc) {
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01002742 context->single_step_control_->dex_pcs.insert(dex_pc);
Elliott Hughes2435a572012-02-17 16:07:41 -08002743 }
2744 context->last_pc_valid = false;
2745 }
Brian Carlstrom7934ac22013-07-26 10:54:15 -07002746 return false; // There may be multiple entries for any given line.
Elliott Hughes2435a572012-02-17 16:07:41 -08002747 }
2748
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01002749 ~DebugCallbackContext() {
Elliott Hughes2435a572012-02-17 16:07:41 -08002750 // If the line number was the last in the position table...
2751 if (last_pc_valid) {
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01002752 size_t end = MethodHelper(single_step_control_->method).GetCodeItem()->insns_size_in_code_units_;
Elliott Hughes2435a572012-02-17 16:07:41 -08002753 for (uint32_t dex_pc = last_pc; dex_pc < end; ++dex_pc) {
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01002754 single_step_control_->dex_pcs.insert(dex_pc);
Elliott Hughes2435a572012-02-17 16:07:41 -08002755 }
2756 }
2757 }
2758
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01002759 SingleStepControl* const single_step_control_;
2760 const int32_t line_number_;
Elliott Hughes2435a572012-02-17 16:07:41 -08002761 bool last_pc_valid;
2762 uint32_t last_pc;
2763 };
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01002764 single_step_control->dex_pcs.clear();
Ian Rogersef7d42f2014-01-06 12:55:46 -08002765 mirror::ArtMethod* m = single_step_control->method;
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01002766 if (!m->IsNative()) {
2767 DebugCallbackContext context(single_step_control, line_number);
Elliott Hughes3e2e1a22012-02-21 11:33:41 -08002768 MethodHelper mh(m);
2769 mh.GetDexFile().DecodeDebugInfo(mh.GetCodeItem(), m->IsStatic(), m->GetDexMethodIndex(),
2770 DebugCallbackContext::Callback, NULL, &context);
2771 }
Elliott Hughes2435a572012-02-17 16:07:41 -08002772
2773 //
2774 // Everything else...
2775 //
2776
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01002777 single_step_control->step_size = step_size;
2778 single_step_control->step_depth = step_depth;
2779 single_step_control->is_active = true;
Elliott Hughes86964332012-02-15 19:37:42 -08002780
Elliott Hughes2435a572012-02-17 16:07:41 -08002781 if (VLOG_IS_ON(jdwp)) {
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01002782 VLOG(jdwp) << "Single-step thread: " << *thread;
2783 VLOG(jdwp) << "Single-step step size: " << single_step_control->step_size;
2784 VLOG(jdwp) << "Single-step step depth: " << single_step_control->step_depth;
2785 VLOG(jdwp) << "Single-step current method: " << PrettyMethod(single_step_control->method);
2786 VLOG(jdwp) << "Single-step current line: " << line_number;
2787 VLOG(jdwp) << "Single-step current stack depth: " << single_step_control->stack_depth;
Elliott Hughes2435a572012-02-17 16:07:41 -08002788 VLOG(jdwp) << "Single-step dex_pc values:";
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01002789 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 -08002790 VLOG(jdwp) << StringPrintf(" %#x", *it);
Elliott Hughes2435a572012-02-17 16:07:41 -08002791 }
2792 }
2793
2794 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002795}
2796
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01002797void Dbg::UnconfigureStep(JDWP::ObjectId thread_id) {
2798 ScopedObjectAccessUnchecked soa(Thread::Current());
2799 MutexLock mu(soa.Self(), *Locks::thread_list_lock_);
2800 Thread* thread;
2801 JDWP::JdwpError error = DecodeThread(soa, thread_id, thread);
Sebastien Hertz87118ed2013-11-26 17:57:18 +01002802 if (error == JDWP::ERR_NONE) {
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01002803 SingleStepControl* single_step_control = thread->GetSingleStepControl();
2804 DCHECK(single_step_control != nullptr);
2805 single_step_control->is_active = false;
2806 single_step_control->dex_pcs.clear();
2807 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002808}
2809
Elliott Hughes45651fd2012-02-21 15:48:20 -08002810static char JdwpTagToShortyChar(JDWP::JdwpTag tag) {
2811 switch (tag) {
2812 default:
2813 LOG(FATAL) << "unknown JDWP tag: " << PrintableChar(tag);
2814
2815 // Primitives.
2816 case JDWP::JT_BYTE: return 'B';
2817 case JDWP::JT_CHAR: return 'C';
2818 case JDWP::JT_FLOAT: return 'F';
2819 case JDWP::JT_DOUBLE: return 'D';
2820 case JDWP::JT_INT: return 'I';
2821 case JDWP::JT_LONG: return 'J';
2822 case JDWP::JT_SHORT: return 'S';
2823 case JDWP::JT_VOID: return 'V';
2824 case JDWP::JT_BOOLEAN: return 'Z';
2825
2826 // Reference types.
2827 case JDWP::JT_ARRAY:
2828 case JDWP::JT_OBJECT:
2829 case JDWP::JT_STRING:
2830 case JDWP::JT_THREAD:
2831 case JDWP::JT_THREAD_GROUP:
2832 case JDWP::JT_CLASS_LOADER:
2833 case JDWP::JT_CLASS_OBJECT:
2834 return 'L';
2835 }
2836}
2837
Elliott Hughes88d63092013-01-09 09:55:54 -08002838JDWP::JdwpError Dbg::InvokeMethod(JDWP::ObjectId thread_id, JDWP::ObjectId object_id,
2839 JDWP::RefTypeId class_id, JDWP::MethodId method_id,
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002840 uint32_t arg_count, uint64_t* arg_values,
2841 JDWP::JdwpTag* arg_types, uint32_t options,
2842 JDWP::JdwpTag* pResultTag, uint64_t* pResultValue,
2843 JDWP::ObjectId* pExceptionId) {
Elliott Hughesd07986f2011-12-06 18:27:45 -08002844 ThreadList* thread_list = Runtime::Current()->GetThreadList();
2845
2846 Thread* targetThread = NULL;
2847 DebugInvokeReq* req = NULL;
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002848 Thread* self = Thread::Current();
Elliott Hughesd07986f2011-12-06 18:27:45 -08002849 {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002850 ScopedObjectAccessUnchecked soa(self);
Ian Rogers50b35e22012-10-04 10:09:15 -07002851 MutexLock mu(soa.Self(), *Locks::thread_list_lock_);
Elliott Hughes221229c2013-01-08 18:17:50 -08002852 JDWP::JdwpError error = DecodeThread(soa, thread_id, targetThread);
2853 if (error != JDWP::ERR_NONE) {
2854 LOG(ERROR) << "InvokeMethod request for invalid thread id " << thread_id;
2855 return error;
Elliott Hughesd07986f2011-12-06 18:27:45 -08002856 }
2857 req = targetThread->GetInvokeReq();
2858 if (!req->ready) {
2859 LOG(ERROR) << "InvokeMethod request for thread not stopped by event: " << *targetThread;
2860 return JDWP::ERR_INVALID_THREAD;
2861 }
2862
2863 /*
2864 * We currently have a bug where we don't successfully resume the
2865 * target thread if the suspend count is too deep. We're expected to
2866 * require one "resume" for each "suspend", but when asked to execute
2867 * a method we have to resume fully and then re-suspend it back to the
2868 * same level. (The easiest way to cause this is to type "suspend"
2869 * multiple times in jdb.)
2870 *
2871 * It's unclear what this means when the event specifies "resume all"
2872 * and some threads are suspended more deeply than others. This is
2873 * a rare problem, so for now we just prevent it from hanging forever
2874 * by rejecting the method invocation request. Without this, we will
2875 * be stuck waiting on a suspended thread.
2876 */
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002877 int suspend_count;
2878 {
Ian Rogers50b35e22012-10-04 10:09:15 -07002879 MutexLock mu2(soa.Self(), *Locks::thread_suspend_count_lock_);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002880 suspend_count = targetThread->GetSuspendCount();
2881 }
Elliott Hughesd07986f2011-12-06 18:27:45 -08002882 if (suspend_count > 1) {
2883 LOG(ERROR) << *targetThread << " suspend count too deep for method invocation: " << suspend_count;
Brian Carlstrom7934ac22013-07-26 10:54:15 -07002884 return JDWP::ERR_THREAD_SUSPENDED; // Probably not expected here.
Elliott Hughesd07986f2011-12-06 18:27:45 -08002885 }
2886
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08002887 JDWP::JdwpError status;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002888 mirror::Object* receiver = gRegistry->Get<mirror::Object*>(object_id);
Elliott Hughes64f574f2013-02-20 14:57:12 -08002889 if (receiver == ObjectRegistry::kInvalidObject) {
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08002890 return JDWP::ERR_INVALID_OBJECT;
2891 }
Elliott Hughes45651fd2012-02-21 15:48:20 -08002892
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002893 mirror::Object* thread = gRegistry->Get<mirror::Object*>(thread_id);
Elliott Hughes64f574f2013-02-20 14:57:12 -08002894 if (thread == ObjectRegistry::kInvalidObject) {
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08002895 return JDWP::ERR_INVALID_OBJECT;
2896 }
Elliott Hughes45651fd2012-02-21 15:48:20 -08002897 // TODO: check that 'thread' is actually a java.lang.Thread!
2898
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002899 mirror::Class* c = DecodeClass(class_id, status);
Elliott Hughes45651fd2012-02-21 15:48:20 -08002900 if (c == NULL) {
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08002901 return status;
2902 }
Elliott Hughes45651fd2012-02-21 15:48:20 -08002903
Brian Carlstromea46f952013-07-30 01:26:50 -07002904 mirror::ArtMethod* m = FromMethodId(method_id);
Elliott Hughes45651fd2012-02-21 15:48:20 -08002905 if (m->IsStatic() != (receiver == NULL)) {
2906 return JDWP::ERR_INVALID_METHODID;
2907 }
2908 if (m->IsStatic()) {
2909 if (m->GetDeclaringClass() != c) {
2910 return JDWP::ERR_INVALID_METHODID;
2911 }
2912 } else {
2913 if (!m->GetDeclaringClass()->IsAssignableFrom(c)) {
2914 return JDWP::ERR_INVALID_METHODID;
2915 }
2916 }
2917
2918 // Check the argument list matches the method.
2919 MethodHelper mh(m);
2920 if (mh.GetShortyLength() - 1 != arg_count) {
2921 return JDWP::ERR_ILLEGAL_ARGUMENT;
2922 }
2923 const char* shorty = mh.GetShorty();
Elliott Hughes09201632013-04-15 15:50:07 -07002924 const DexFile::TypeList* types = mh.GetParameterTypeList();
Elliott Hughes45651fd2012-02-21 15:48:20 -08002925 for (size_t i = 0; i < arg_count; ++i) {
2926 if (shorty[i + 1] != JdwpTagToShortyChar(arg_types[i])) {
2927 return JDWP::ERR_ILLEGAL_ARGUMENT;
2928 }
Elliott Hughes09201632013-04-15 15:50:07 -07002929
2930 if (shorty[i + 1] == 'L') {
2931 // Did we really get an argument of an appropriate reference type?
2932 mirror::Class* parameter_type = mh.GetClassFromTypeIdx(types->GetTypeItem(i).type_idx_);
2933 mirror::Object* argument = gRegistry->Get<mirror::Object*>(arg_values[i]);
2934 if (argument == ObjectRegistry::kInvalidObject) {
2935 return JDWP::ERR_INVALID_OBJECT;
2936 }
Sebastien Hertz0630ab52013-11-28 18:53:35 +01002937 if (argument != NULL && !argument->InstanceOf(parameter_type)) {
Elliott Hughes09201632013-04-15 15:50:07 -07002938 return JDWP::ERR_ILLEGAL_ARGUMENT;
2939 }
2940
2941 // Turn the on-the-wire ObjectId into a jobject.
2942 jvalue& v = reinterpret_cast<jvalue&>(arg_values[i]);
2943 v.l = gRegistry->GetJObject(arg_values[i]);
2944 }
Elliott Hughes45651fd2012-02-21 15:48:20 -08002945 }
2946
Sebastien Hertzd38667a2013-11-25 15:43:54 +01002947 req->receiver = receiver;
2948 req->thread = thread;
2949 req->klass = c;
2950 req->method = m;
2951 req->arg_count = arg_count;
2952 req->arg_values = arg_values;
2953 req->options = options;
2954 req->invoke_needed = true;
Elliott Hughesd07986f2011-12-06 18:27:45 -08002955 }
2956
2957 // The fact that we've released the thread list lock is a bit risky --- if the thread goes
2958 // away we're sitting high and dry -- but we must release this before the ResumeAllThreads
2959 // call, and it's unwise to hold it during WaitForSuspend.
2960
2961 {
2962 /*
2963 * We change our (JDWP thread) status, which should be THREAD_RUNNING,
Elliott Hughes81ff3182012-03-23 20:35:56 -07002964 * so we can suspend for a GC if the invoke request causes us to
Elliott Hughesd07986f2011-12-06 18:27:45 -08002965 * run out of memory. It's also a good idea to change it before locking
2966 * the invokeReq mutex, although that should never be held for long.
2967 */
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002968 self->TransitionFromRunnableToSuspended(kWaitingForDebuggerSend);
Elliott Hughesd07986f2011-12-06 18:27:45 -08002969
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08002970 VLOG(jdwp) << " Transferring control to event thread";
Elliott Hughesd07986f2011-12-06 18:27:45 -08002971 {
Sebastien Hertzd38667a2013-11-25 15:43:54 +01002972 MutexLock mu(self, req->lock);
Elliott Hughesd07986f2011-12-06 18:27:45 -08002973
2974 if ((options & JDWP::INVOKE_SINGLE_THREADED) == 0) {
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08002975 VLOG(jdwp) << " Resuming all threads";
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002976 thread_list->UndoDebuggerSuspensions();
Elliott Hughesd07986f2011-12-06 18:27:45 -08002977 } else {
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08002978 VLOG(jdwp) << " Resuming event thread only";
Elliott Hughesd07986f2011-12-06 18:27:45 -08002979 thread_list->Resume(targetThread, true);
2980 }
2981
2982 // Wait for the request to finish executing.
Sebastien Hertzd38667a2013-11-25 15:43:54 +01002983 while (req->invoke_needed) {
2984 req->cond.Wait(self);
Elliott Hughesd07986f2011-12-06 18:27:45 -08002985 }
2986 }
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08002987 VLOG(jdwp) << " Control has returned from event thread";
Elliott Hughesd07986f2011-12-06 18:27:45 -08002988
2989 /* wait for thread to re-suspend itself */
Brian Carlstromdf629502013-07-17 22:39:56 -07002990 SuspendThread(thread_id, false /* request_suspension */);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002991 self->TransitionFromSuspendedToRunnable();
Elliott Hughesd07986f2011-12-06 18:27:45 -08002992 }
2993
2994 /*
2995 * Suspend the threads. We waited for the target thread to suspend
2996 * itself, so all we need to do is suspend the others.
2997 *
2998 * The suspendAllThreads() call will double-suspend the event thread,
2999 * so we want to resume the target thread once to keep the books straight.
3000 */
3001 if ((options & JDWP::INVOKE_SINGLE_THREADED) == 0) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07003002 self->TransitionFromRunnableToSuspended(kWaitingForDebuggerSuspension);
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08003003 VLOG(jdwp) << " Suspending all threads";
Ian Rogers00f7d0e2012-07-19 15:28:27 -07003004 thread_list->SuspendAllForDebugger();
3005 self->TransitionFromSuspendedToRunnable();
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08003006 VLOG(jdwp) << " Resuming event thread to balance the count";
Elliott Hughesd07986f2011-12-06 18:27:45 -08003007 thread_list->Resume(targetThread, true);
3008 }
3009
3010 // Copy the result.
3011 *pResultTag = req->result_tag;
3012 if (IsPrimitiveTag(req->result_tag)) {
Elliott Hughesf24d3ce2012-04-11 17:43:37 -07003013 *pResultValue = req->result_value.GetJ();
Elliott Hughesd07986f2011-12-06 18:27:45 -08003014 } else {
Elliott Hughesf24d3ce2012-04-11 17:43:37 -07003015 *pResultValue = gRegistry->Add(req->result_value.GetL());
Elliott Hughesd07986f2011-12-06 18:27:45 -08003016 }
3017 *pExceptionId = req->exception;
3018 return req->error;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07003019}
3020
3021void Dbg::ExecuteMethod(DebugInvokeReq* pReq) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07003022 ScopedObjectAccess soa(Thread::Current());
Elliott Hughesd07986f2011-12-06 18:27:45 -08003023
Elliott Hughes81ff3182012-03-23 20:35:56 -07003024 // We can be called while an exception is pending. We need
Elliott Hughesd07986f2011-12-06 18:27:45 -08003025 // to preserve that across the method invocation.
Ian Rogers62d6c772013-02-27 08:32:07 -08003026 SirtRef<mirror::Object> old_throw_this_object(soa.Self(), NULL);
Brian Carlstromea46f952013-07-30 01:26:50 -07003027 SirtRef<mirror::ArtMethod> old_throw_method(soa.Self(), NULL);
Ian Rogers62d6c772013-02-27 08:32:07 -08003028 SirtRef<mirror::Throwable> old_exception(soa.Self(), NULL);
3029 uint32_t old_throw_dex_pc;
3030 {
3031 ThrowLocation old_throw_location;
3032 mirror::Throwable* old_exception_obj = soa.Self()->GetException(&old_throw_location);
3033 old_throw_this_object.reset(old_throw_location.GetThis());
3034 old_throw_method.reset(old_throw_location.GetMethod());
3035 old_exception.reset(old_exception_obj);
3036 old_throw_dex_pc = old_throw_location.GetDexPc();
3037 soa.Self()->ClearException();
3038 }
Elliott Hughesd07986f2011-12-06 18:27:45 -08003039
3040 // Translate the method through the vtable, unless the debugger wants to suppress it.
Mathieu Chartierc528dba2013-11-26 12:00:11 -08003041 SirtRef<mirror::ArtMethod> m(soa.Self(), pReq->method);
Sebastien Hertzd38667a2013-11-25 15:43:54 +01003042 if ((pReq->options & JDWP::INVOKE_NONVIRTUAL) == 0 && pReq->receiver != NULL) {
3043 mirror::ArtMethod* actual_method = pReq->klass->FindVirtualMethodForVirtualOrInterface(pReq->method);
Mathieu Chartierc528dba2013-11-26 12:00:11 -08003044 if (actual_method != m.get()) {
3045 VLOG(jdwp) << "ExecuteMethod translated " << PrettyMethod(m.get()) << " to " << PrettyMethod(actual_method);
3046 m.reset(actual_method);
Elliott Hughes45651fd2012-02-21 15:48:20 -08003047 }
Elliott Hughesd07986f2011-12-06 18:27:45 -08003048 }
Mathieu Chartierc528dba2013-11-26 12:00:11 -08003049 VLOG(jdwp) << "ExecuteMethod " << PrettyMethod(m.get())
Sebastien Hertzd38667a2013-11-25 15:43:54 +01003050 << " receiver=" << pReq->receiver
3051 << " arg_count=" << pReq->arg_count;
Mathieu Chartierc528dba2013-11-26 12:00:11 -08003052 CHECK(m.get() != nullptr);
Elliott Hughesd07986f2011-12-06 18:27:45 -08003053
3054 CHECK_EQ(sizeof(jvalue), sizeof(uint64_t));
3055
Mathieu Chartierc528dba2013-11-26 12:00:11 -08003056 MethodHelper mh(m.get());
Jeff Hao5d917302013-02-27 17:57:33 -08003057 ArgArray arg_array(mh.GetShorty(), mh.GetShortyLength());
Sebastien Hertzd38667a2013-11-25 15:43:54 +01003058 arg_array.BuildArgArray(soa, pReq->receiver, reinterpret_cast<jvalue*>(pReq->arg_values));
Ian Rogers0177e532014-02-11 16:30:46 -08003059 InvokeWithArgArray(soa, m.get(), &arg_array, &pReq->result_value, mh.GetShorty());
Elliott Hughesd07986f2011-12-06 18:27:45 -08003060
Ian Rogers62d6c772013-02-27 08:32:07 -08003061 mirror::Throwable* exception = soa.Self()->GetException(NULL);
3062 soa.Self()->ClearException();
3063 pReq->exception = gRegistry->Add(exception);
Mathieu Chartierc528dba2013-11-26 12:00:11 -08003064 pReq->result_tag = BasicTagFromDescriptor(MethodHelper(m.get()).GetShorty());
Elliott Hughesd07986f2011-12-06 18:27:45 -08003065 if (pReq->exception != 0) {
Ian Rogers62d6c772013-02-27 08:32:07 -08003066 VLOG(jdwp) << " JDWP invocation returning with exception=" << exception
3067 << " " << exception->Dump();
Elliott Hughesf24d3ce2012-04-11 17:43:37 -07003068 pReq->result_value.SetJ(0);
Elliott Hughesd07986f2011-12-06 18:27:45 -08003069 } else if (pReq->result_tag == JDWP::JT_OBJECT) {
3070 /* if no exception thrown, examine object result more closely */
Ian Rogers98379392014-02-24 16:53:16 -08003071 JDWP::JdwpTag new_tag = TagFromObject(soa, pReq->result_value.GetL());
Elliott Hughesd07986f2011-12-06 18:27:45 -08003072 if (new_tag != pReq->result_tag) {
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08003073 VLOG(jdwp) << " JDWP promoted result from " << pReq->result_tag << " to " << new_tag;
Elliott Hughesd07986f2011-12-06 18:27:45 -08003074 pReq->result_tag = new_tag;
3075 }
3076
3077 /*
3078 * Register the object. We don't actually need an ObjectId yet,
3079 * but we do need to be sure that the GC won't move or discard the
3080 * object when we switch out of RUNNING. The ObjectId conversion
3081 * will add the object to the "do not touch" list.
3082 *
3083 * We can't use the "tracked allocation" mechanism here because
3084 * the object is going to be handed off to a different thread.
3085 */
Elliott Hughesf24d3ce2012-04-11 17:43:37 -07003086 gRegistry->Add(pReq->result_value.GetL());
Elliott Hughesd07986f2011-12-06 18:27:45 -08003087 }
3088
3089 if (old_exception.get() != NULL) {
Ian Rogers62d6c772013-02-27 08:32:07 -08003090 ThrowLocation gc_safe_throw_location(old_throw_this_object.get(), old_throw_method.get(),
3091 old_throw_dex_pc);
3092 soa.Self()->SetException(gc_safe_throw_location, old_exception.get());
Elliott Hughesd07986f2011-12-06 18:27:45 -08003093 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -07003094}
3095
Elliott Hughesd07986f2011-12-06 18:27:45 -08003096/*
Elliott Hughes4b9702c2013-02-20 18:13:24 -08003097 * "request" contains a full JDWP packet, possibly with multiple chunks. We
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07003098 * need to process each, accumulate the replies, and ship the whole thing
3099 * back.
3100 *
3101 * Returns "true" if we have a reply. The reply buffer is newly allocated,
3102 * and includes the chunk type/length, followed by the data.
3103 *
Elliott Hughes3d30d9b2011-12-07 17:35:48 -08003104 * OLD-TODO: we currently assume that the request and reply include a single
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07003105 * chunk. If this becomes inconvenient we will need to adapt.
3106 */
Elliott Hughes4b9702c2013-02-20 18:13:24 -08003107bool Dbg::DdmHandlePacket(JDWP::Request& request, uint8_t** pReplyBuf, int* pReplyLen) {
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07003108 Thread* self = Thread::Current();
3109 JNIEnv* env = self->GetJniEnv();
3110
Elliott Hughes4b9702c2013-02-20 18:13:24 -08003111 uint32_t type = request.ReadUnsigned32("type");
3112 uint32_t length = request.ReadUnsigned32("length");
3113
3114 // Create a byte[] corresponding to 'request'.
3115 size_t request_length = request.size();
3116 ScopedLocalRef<jbyteArray> dataArray(env, env->NewByteArray(request_length));
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003117 if (dataArray.get() == NULL) {
Elliott Hughes4b9702c2013-02-20 18:13:24 -08003118 LOG(WARNING) << "byte[] allocation failed: " << request_length;
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07003119 env->ExceptionClear();
3120 return false;
3121 }
Elliott Hughes4b9702c2013-02-20 18:13:24 -08003122 env->SetByteArrayRegion(dataArray.get(), 0, request_length, reinterpret_cast<const jbyte*>(request.data()));
3123 request.Skip(request_length);
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07003124
3125 // Run through and find all chunks. [Currently just find the first.]
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003126 ScopedByteArrayRO contents(env, dataArray.get());
Elliott Hughes4b9702c2013-02-20 18:13:24 -08003127 if (length != request_length) {
Ian Rogersef7d42f2014-01-06 12:55:46 -08003128 LOG(WARNING) << StringPrintf("bad chunk found (len=%u pktLen=%zd)", length, request_length);
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07003129 return false;
3130 }
3131
3132 // Call "private static Chunk dispatch(int type, byte[] data, int offset, int length)".
Elliott Hugheseac76672012-05-24 21:56:51 -07003133 ScopedLocalRef<jobject> chunk(env, env->CallStaticObjectMethod(WellKnownClasses::org_apache_harmony_dalvik_ddmc_DdmServer,
3134 WellKnownClasses::org_apache_harmony_dalvik_ddmc_DdmServer_dispatch,
Elliott Hughes4b9702c2013-02-20 18:13:24 -08003135 type, dataArray.get(), 0, length));
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07003136 if (env->ExceptionCheck()) {
3137 LOG(INFO) << StringPrintf("Exception thrown by dispatcher for 0x%08x", type);
3138 env->ExceptionDescribe();
3139 env->ExceptionClear();
3140 return false;
3141 }
3142
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003143 if (chunk.get() == NULL) {
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07003144 return false;
3145 }
3146
3147 /*
3148 * Pull the pieces out of the chunk. We copy the results into a
3149 * newly-allocated buffer that the caller can free. We don't want to
3150 * continue using the Chunk object because nothing has a reference to it.
3151 *
3152 * We could avoid this by returning type/data/offset/length and having
3153 * the caller be aware of the object lifetime issues, but that
Elliott Hughes81ff3182012-03-23 20:35:56 -07003154 * integrates the JDWP code more tightly into the rest of the runtime, and doesn't work
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07003155 * if we have responses for multiple chunks.
3156 *
3157 * So we're pretty much stuck with copying data around multiple times.
3158 */
Elliott Hugheseac76672012-05-24 21:56:51 -07003159 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 -08003160 jint offset = env->GetIntField(chunk.get(), WellKnownClasses::org_apache_harmony_dalvik_ddmc_Chunk_offset);
Elliott Hugheseac76672012-05-24 21:56:51 -07003161 length = env->GetIntField(chunk.get(), WellKnownClasses::org_apache_harmony_dalvik_ddmc_Chunk_length);
Elliott Hugheseac76672012-05-24 21:56:51 -07003162 type = env->GetIntField(chunk.get(), WellKnownClasses::org_apache_harmony_dalvik_ddmc_Chunk_type);
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07003163
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08003164 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 -07003165 if (length == 0 || replyData.get() == NULL) {
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07003166 return false;
3167 }
3168
Elliott Hughes4b9702c2013-02-20 18:13:24 -08003169 const int kChunkHdrLen = 8;
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07003170 uint8_t* reply = new uint8_t[length + kChunkHdrLen];
3171 if (reply == NULL) {
3172 LOG(WARNING) << "malloc failed: " << (length + kChunkHdrLen);
3173 return false;
3174 }
Elliott Hughesf7c3b662011-10-27 12:04:56 -07003175 JDWP::Set4BE(reply + 0, type);
3176 JDWP::Set4BE(reply + 4, length);
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003177 env->GetByteArrayRegion(replyData.get(), offset, length, reinterpret_cast<jbyte*>(reply + kChunkHdrLen));
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07003178
3179 *pReplyBuf = reply;
3180 *pReplyLen = length + kChunkHdrLen;
3181
Elliott Hughes4b9702c2013-02-20 18:13:24 -08003182 VLOG(jdwp) << StringPrintf("dvmHandleDdm returning type=%.4s %p len=%d", reinterpret_cast<char*>(reply), reply, length);
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07003183 return true;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07003184}
3185
Elliott Hughesa2155262011-11-16 16:26:58 -08003186void Dbg::DdmBroadcast(bool connect) {
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08003187 VLOG(jdwp) << "Broadcasting DDM " << (connect ? "connect" : "disconnect") << "...";
Elliott Hughes47fce012011-10-25 18:37:19 -07003188
3189 Thread* self = Thread::Current();
Ian Rogers50b35e22012-10-04 10:09:15 -07003190 if (self->GetState() != kRunnable) {
3191 LOG(ERROR) << "DDM broadcast in thread state " << self->GetState();
3192 /* try anyway? */
Elliott Hughes47fce012011-10-25 18:37:19 -07003193 }
3194
3195 JNIEnv* env = self->GetJniEnv();
Elliott Hughes47fce012011-10-25 18:37:19 -07003196 jint event = connect ? 1 /*DdmServer.CONNECTED*/ : 2 /*DdmServer.DISCONNECTED*/;
Elliott Hugheseac76672012-05-24 21:56:51 -07003197 env->CallStaticVoidMethod(WellKnownClasses::org_apache_harmony_dalvik_ddmc_DdmServer,
3198 WellKnownClasses::org_apache_harmony_dalvik_ddmc_DdmServer_broadcast,
3199 event);
Elliott Hughes47fce012011-10-25 18:37:19 -07003200 if (env->ExceptionCheck()) {
3201 LOG(ERROR) << "DdmServer.broadcast " << event << " failed";
3202 env->ExceptionDescribe();
3203 env->ExceptionClear();
3204 }
3205}
3206
Elliott Hughes872d4ec2011-10-21 17:07:15 -07003207void Dbg::DdmConnected() {
Elliott Hughesa2155262011-11-16 16:26:58 -08003208 Dbg::DdmBroadcast(true);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07003209}
3210
3211void Dbg::DdmDisconnected() {
Elliott Hughesa2155262011-11-16 16:26:58 -08003212 Dbg::DdmBroadcast(false);
Elliott Hughes47fce012011-10-25 18:37:19 -07003213 gDdmThreadNotification = false;
3214}
3215
3216/*
Elliott Hughes82188472011-11-07 18:11:48 -08003217 * Send a notification when a thread starts, stops, or changes its name.
Elliott Hughes47fce012011-10-25 18:37:19 -07003218 *
3219 * Because we broadcast the full set of threads when the notifications are
3220 * first enabled, it's possible for "thread" to be actively executing.
3221 */
Elliott Hughes82188472011-11-07 18:11:48 -08003222void Dbg::DdmSendThreadNotification(Thread* t, uint32_t type) {
Elliott Hughes47fce012011-10-25 18:37:19 -07003223 if (!gDdmThreadNotification) {
3224 return;
3225 }
3226
Elliott Hughes82188472011-11-07 18:11:48 -08003227 if (type == CHUNK_TYPE("THDE")) {
Elliott Hughes47fce012011-10-25 18:37:19 -07003228 uint8_t buf[4];
Ian Rogersd9c4fc92013-10-01 19:45:43 -07003229 JDWP::Set4BE(&buf[0], t->GetThreadId());
Elliott Hughes47fce012011-10-25 18:37:19 -07003230 Dbg::DdmSendChunk(CHUNK_TYPE("THDE"), 4, buf);
Elliott Hughes82188472011-11-07 18:11:48 -08003231 } else {
3232 CHECK(type == CHUNK_TYPE("THCR") || type == CHUNK_TYPE("THNM")) << type;
Ian Rogers00f7d0e2012-07-19 15:28:27 -07003233 ScopedObjectAccessUnchecked soa(Thread::Current());
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003234 SirtRef<mirror::String> name(soa.Self(), t->GetThreadName(soa));
Elliott Hughes82188472011-11-07 18:11:48 -08003235 size_t char_count = (name.get() != NULL) ? name->GetLength() : 0;
jeffhao725a9572012-11-13 18:20:12 -08003236 const jchar* chars = (name.get() != NULL) ? name->GetCharArray()->GetData() : NULL;
Elliott Hughes82188472011-11-07 18:11:48 -08003237
Elliott Hughes21f32d72011-11-09 17:44:13 -08003238 std::vector<uint8_t> bytes;
Ian Rogersd9c4fc92013-10-01 19:45:43 -07003239 JDWP::Append4BE(bytes, t->GetThreadId());
Elliott Hughes545a0642011-11-08 19:10:03 -08003240 JDWP::AppendUtf16BE(bytes, chars, char_count);
Elliott Hughes21f32d72011-11-09 17:44:13 -08003241 CHECK_EQ(bytes.size(), char_count*2 + sizeof(uint32_t)*2);
3242 Dbg::DdmSendChunk(type, bytes);
Elliott Hughes47fce012011-10-25 18:37:19 -07003243 }
3244}
3245
Elliott Hughes47fce012011-10-25 18:37:19 -07003246void Dbg::DdmSetThreadNotification(bool enable) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07003247 // Enable/disable thread notifications.
Elliott Hughes47fce012011-10-25 18:37:19 -07003248 gDdmThreadNotification = enable;
3249 if (enable) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07003250 // Suspend the VM then post thread start notifications for all threads. Threads attaching will
3251 // see a suspension in progress and block until that ends. They then post their own start
3252 // notification.
3253 SuspendVM();
3254 std::list<Thread*> threads;
Ian Rogers50b35e22012-10-04 10:09:15 -07003255 Thread* self = Thread::Current();
Ian Rogers00f7d0e2012-07-19 15:28:27 -07003256 {
Ian Rogers50b35e22012-10-04 10:09:15 -07003257 MutexLock mu(self, *Locks::thread_list_lock_);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07003258 threads = Runtime::Current()->GetThreadList()->GetList();
3259 }
3260 {
Ian Rogers50b35e22012-10-04 10:09:15 -07003261 ScopedObjectAccess soa(self);
Mathieu Chartier02e25112013-08-14 16:14:24 -07003262 for (Thread* thread : threads) {
3263 Dbg::DdmSendThreadNotification(thread, CHUNK_TYPE("THCR"));
Ian Rogers00f7d0e2012-07-19 15:28:27 -07003264 }
3265 }
3266 ResumeVM();
Elliott Hughes47fce012011-10-25 18:37:19 -07003267 }
3268}
3269
Elliott Hughesa2155262011-11-16 16:26:58 -08003270void Dbg::PostThreadStartOrStop(Thread* t, uint32_t type) {
Elliott Hughesc0f09332012-03-26 13:27:06 -07003271 if (IsDebuggerActive()) {
Mathieu Chartierdbe6f462012-09-25 16:54:50 -07003272 ScopedObjectAccessUnchecked soa(Thread::Current());
Ian Rogerscfaa4552012-11-26 21:00:08 -08003273 JDWP::ObjectId id = gRegistry->Add(t->GetPeer());
Elliott Hughes82188472011-11-07 18:11:48 -08003274 gJdwpState->PostThreadChange(id, type == CHUNK_TYPE("THCR"));
Elliott Hughes47fce012011-10-25 18:37:19 -07003275 }
Elliott Hughes82188472011-11-07 18:11:48 -08003276 Dbg::DdmSendThreadNotification(t, type);
Elliott Hughes47fce012011-10-25 18:37:19 -07003277}
3278
3279void Dbg::PostThreadStart(Thread* t) {
Elliott Hughesa2155262011-11-16 16:26:58 -08003280 Dbg::PostThreadStartOrStop(t, CHUNK_TYPE("THCR"));
Elliott Hughes47fce012011-10-25 18:37:19 -07003281}
3282
3283void Dbg::PostThreadDeath(Thread* t) {
Elliott Hughesa2155262011-11-16 16:26:58 -08003284 Dbg::PostThreadStartOrStop(t, CHUNK_TYPE("THDE"));
Elliott Hughes872d4ec2011-10-21 17:07:15 -07003285}
3286
Elliott Hughes82188472011-11-07 18:11:48 -08003287void Dbg::DdmSendChunk(uint32_t type, size_t byte_count, const uint8_t* buf) {
Elliott Hughes3bb81562011-10-21 18:52:59 -07003288 CHECK(buf != NULL);
3289 iovec vec[1];
3290 vec[0].iov_base = reinterpret_cast<void*>(const_cast<uint8_t*>(buf));
3291 vec[0].iov_len = byte_count;
3292 Dbg::DdmSendChunkV(type, vec, 1);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07003293}
3294
Elliott Hughes21f32d72011-11-09 17:44:13 -08003295void Dbg::DdmSendChunk(uint32_t type, const std::vector<uint8_t>& bytes) {
3296 DdmSendChunk(type, bytes.size(), &bytes[0]);
3297}
3298
Brian Carlstromf5293522013-07-19 00:24:00 -07003299void Dbg::DdmSendChunkV(uint32_t type, const iovec* iov, int iov_count) {
Elliott Hughes3bb81562011-10-21 18:52:59 -07003300 if (gJdwpState == NULL) {
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08003301 VLOG(jdwp) << "Debugger thread not active, ignoring DDM send: " << type;
Elliott Hughes3bb81562011-10-21 18:52:59 -07003302 } else {
Elliott Hughescccd84f2011-12-05 16:51:54 -08003303 gJdwpState->DdmSendChunkV(type, iov, iov_count);
Elliott Hughes3bb81562011-10-21 18:52:59 -07003304 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -07003305}
3306
Elliott Hughes767a1472011-10-26 18:49:02 -07003307int Dbg::DdmHandleHpifChunk(HpifWhen when) {
3308 if (when == HPIF_WHEN_NOW) {
Elliott Hughes7162ad92011-10-27 14:08:42 -07003309 DdmSendHeapInfo(when);
Elliott Hughes767a1472011-10-26 18:49:02 -07003310 return true;
3311 }
3312
3313 if (when != HPIF_WHEN_NEVER && when != HPIF_WHEN_NEXT_GC && when != HPIF_WHEN_EVERY_GC) {
3314 LOG(ERROR) << "invalid HpifWhen value: " << static_cast<int>(when);
3315 return false;
3316 }
3317
3318 gDdmHpifWhen = when;
3319 return true;
3320}
3321
3322bool Dbg::DdmHandleHpsgNhsgChunk(Dbg::HpsgWhen when, Dbg::HpsgWhat what, bool native) {
3323 if (when != HPSG_WHEN_NEVER && when != HPSG_WHEN_EVERY_GC) {
3324 LOG(ERROR) << "invalid HpsgWhen value: " << static_cast<int>(when);
3325 return false;
3326 }
3327
3328 if (what != HPSG_WHAT_MERGED_OBJECTS && what != HPSG_WHAT_DISTINCT_OBJECTS) {
3329 LOG(ERROR) << "invalid HpsgWhat value: " << static_cast<int>(what);
3330 return false;
3331 }
3332
3333 if (native) {
3334 gDdmNhsgWhen = when;
3335 gDdmNhsgWhat = what;
3336 } else {
3337 gDdmHpsgWhen = when;
3338 gDdmHpsgWhat = what;
3339 }
3340 return true;
3341}
3342
Elliott Hughes7162ad92011-10-27 14:08:42 -07003343void Dbg::DdmSendHeapInfo(HpifWhen reason) {
3344 // If there's a one-shot 'when', reset it.
3345 if (reason == gDdmHpifWhen) {
3346 if (gDdmHpifWhen == HPIF_WHEN_NEXT_GC) {
3347 gDdmHpifWhen = HPIF_WHEN_NEVER;
3348 }
3349 }
3350
3351 /*
3352 * Chunk HPIF (client --> server)
3353 *
3354 * Heap Info. General information about the heap,
3355 * suitable for a summary display.
3356 *
3357 * [u4]: number of heaps
3358 *
3359 * For each heap:
3360 * [u4]: heap ID
3361 * [u8]: timestamp in ms since Unix epoch
3362 * [u1]: capture reason (same as 'when' value from server)
3363 * [u4]: max heap size in bytes (-Xmx)
3364 * [u4]: current heap size in bytes
3365 * [u4]: current number of bytes allocated
3366 * [u4]: current number of objects allocated
3367 */
3368 uint8_t heap_count = 1;
Ian Rogers1d54e732013-05-02 21:10:01 -07003369 gc::Heap* heap = Runtime::Current()->GetHeap();
Elliott Hughes21f32d72011-11-09 17:44:13 -08003370 std::vector<uint8_t> bytes;
Elliott Hughes545a0642011-11-08 19:10:03 -08003371 JDWP::Append4BE(bytes, heap_count);
Brian Carlstrom7934ac22013-07-26 10:54:15 -07003372 JDWP::Append4BE(bytes, 1); // Heap id (bogus; we only have one heap).
Elliott Hughes545a0642011-11-08 19:10:03 -08003373 JDWP::Append8BE(bytes, MilliTime());
3374 JDWP::Append1BE(bytes, reason);
Brian Carlstrom7934ac22013-07-26 10:54:15 -07003375 JDWP::Append4BE(bytes, heap->GetMaxMemory()); // Max allowed heap size in bytes.
3376 JDWP::Append4BE(bytes, heap->GetTotalMemory()); // Current heap size in bytes.
Elliott Hughesb3bd5f02012-03-08 21:05:27 -08003377 JDWP::Append4BE(bytes, heap->GetBytesAllocated());
3378 JDWP::Append4BE(bytes, heap->GetObjectsAllocated());
Elliott Hughes21f32d72011-11-09 17:44:13 -08003379 CHECK_EQ(bytes.size(), 4U + (heap_count * (4 + 8 + 1 + 4 + 4 + 4 + 4)));
3380 Dbg::DdmSendChunk(CHUNK_TYPE("HPIF"), bytes);
Elliott Hughes767a1472011-10-26 18:49:02 -07003381}
3382
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003383enum HpsgSolidity {
3384 SOLIDITY_FREE = 0,
3385 SOLIDITY_HARD = 1,
3386 SOLIDITY_SOFT = 2,
3387 SOLIDITY_WEAK = 3,
3388 SOLIDITY_PHANTOM = 4,
3389 SOLIDITY_FINALIZABLE = 5,
3390 SOLIDITY_SWEEP = 6,
3391};
3392
3393enum HpsgKind {
3394 KIND_OBJECT = 0,
3395 KIND_CLASS_OBJECT = 1,
3396 KIND_ARRAY_1 = 2,
3397 KIND_ARRAY_2 = 3,
3398 KIND_ARRAY_4 = 4,
3399 KIND_ARRAY_8 = 5,
3400 KIND_UNKNOWN = 6,
3401 KIND_NATIVE = 7,
3402};
3403
3404#define HPSG_PARTIAL (1<<7)
3405#define HPSG_STATE(solidity, kind) ((uint8_t)((((kind) & 0x7) << 3) | ((solidity) & 0x7)))
3406
Ian Rogers30fab402012-01-23 15:43:46 -08003407class HeapChunkContext {
3408 public:
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003409 // Maximum chunk size. Obtain this from the formula:
3410 // (((maximum_heap_size / ALLOCATION_UNIT_SIZE) + 255) / 256) * 2
3411 HeapChunkContext(bool merge, bool native)
Ian Rogers30fab402012-01-23 15:43:46 -08003412 : buf_(16384 - 16),
3413 type_(0),
3414 merge_(merge) {
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003415 Reset();
3416 if (native) {
Ian Rogers30fab402012-01-23 15:43:46 -08003417 type_ = CHUNK_TYPE("NHSG");
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003418 } else {
Ian Rogers30fab402012-01-23 15:43:46 -08003419 type_ = merge ? CHUNK_TYPE("HPSG") : CHUNK_TYPE("HPSO");
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003420 }
3421 }
3422
3423 ~HeapChunkContext() {
Ian Rogers30fab402012-01-23 15:43:46 -08003424 if (p_ > &buf_[0]) {
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003425 Flush();
3426 }
3427 }
3428
3429 void EnsureHeader(const void* chunk_ptr) {
Ian Rogers30fab402012-01-23 15:43:46 -08003430 if (!needHeader_) {
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003431 return;
3432 }
3433
3434 // Start a new HPSx chunk.
Brian Carlstrom7934ac22013-07-26 10:54:15 -07003435 JDWP::Write4BE(&p_, 1); // Heap id (bogus; we only have one heap).
3436 JDWP::Write1BE(&p_, 8); // Size of allocation unit, in bytes.
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003437
Brian Carlstrom7934ac22013-07-26 10:54:15 -07003438 JDWP::Write4BE(&p_, reinterpret_cast<uintptr_t>(chunk_ptr)); // virtual address of segment start.
3439 JDWP::Write4BE(&p_, 0); // offset of this piece (relative to the virtual address).
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003440 // [u4]: length of piece, in allocation units
3441 // 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 -08003442 pieceLenField_ = p_;
3443 JDWP::Write4BE(&p_, 0x55555555);
3444 needHeader_ = false;
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003445 }
3446
Ian Rogersb726dcb2012-09-05 08:57:23 -07003447 void Flush() SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Ian Rogersd636b062013-01-18 17:51:18 -08003448 if (pieceLenField_ == NULL) {
3449 // Flush immediately post Reset (maybe back-to-back Flush). Ignore.
3450 CHECK(needHeader_);
3451 return;
3452 }
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003453 // Patch the "length of piece" field.
Ian Rogers30fab402012-01-23 15:43:46 -08003454 CHECK_LE(&buf_[0], pieceLenField_);
3455 CHECK_LE(pieceLenField_, p_);
3456 JDWP::Set4BE(pieceLenField_, totalAllocationUnits_);
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003457
Ian Rogers30fab402012-01-23 15:43:46 -08003458 Dbg::DdmSendChunk(type_, p_ - &buf_[0], &buf_[0]);
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003459 Reset();
3460 }
3461
Ian Rogers00f7d0e2012-07-19 15:28:27 -07003462 static void HeapChunkCallback(void* start, void* end, size_t used_bytes, void* arg)
Ian Rogersb726dcb2012-09-05 08:57:23 -07003463 SHARED_LOCKS_REQUIRED(Locks::heap_bitmap_lock_,
3464 Locks::mutator_lock_) {
Ian Rogers30fab402012-01-23 15:43:46 -08003465 reinterpret_cast<HeapChunkContext*>(arg)->HeapChunkCallback(start, end, used_bytes);
Elliott Hughesa2155262011-11-16 16:26:58 -08003466 }
3467
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003468 private:
Elliott Hughesa2155262011-11-16 16:26:58 -08003469 enum { ALLOCATION_UNIT_SIZE = 8 };
3470
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003471 void Reset() {
Ian Rogers30fab402012-01-23 15:43:46 -08003472 p_ = &buf_[0];
Ian Rogers15bf2d32012-08-28 17:33:04 -07003473 startOfNextMemoryChunk_ = NULL;
Ian Rogers30fab402012-01-23 15:43:46 -08003474 totalAllocationUnits_ = 0;
3475 needHeader_ = true;
3476 pieceLenField_ = NULL;
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003477 }
3478
Ian Rogers00f7d0e2012-07-19 15:28:27 -07003479 void HeapChunkCallback(void* start, void* /*end*/, size_t used_bytes)
Ian Rogersb726dcb2012-09-05 08:57:23 -07003480 SHARED_LOCKS_REQUIRED(Locks::heap_bitmap_lock_,
3481 Locks::mutator_lock_) {
Ian Rogers30fab402012-01-23 15:43:46 -08003482 // Note: heap call backs cannot manipulate the heap upon which they are crawling, care is taken
3483 // in the following code not to allocate memory, by ensuring buf_ is of the correct size
Ian Rogers15bf2d32012-08-28 17:33:04 -07003484 if (used_bytes == 0) {
3485 if (start == NULL) {
3486 // Reset for start of new heap.
3487 startOfNextMemoryChunk_ = NULL;
3488 Flush();
3489 }
3490 // Only process in use memory so that free region information
3491 // also includes dlmalloc book keeping.
Elliott Hughesa2155262011-11-16 16:26:58 -08003492 return;
Elliott Hughesa2155262011-11-16 16:26:58 -08003493 }
3494
Ian Rogers15bf2d32012-08-28 17:33:04 -07003495 /* If we're looking at the native heap, we'll just return
3496 * (SOLIDITY_HARD, KIND_NATIVE) for all allocated chunks
3497 */
3498 bool native = type_ == CHUNK_TYPE("NHSG");
3499
3500 if (startOfNextMemoryChunk_ != NULL) {
3501 // Transmit any pending free memory. Native free memory of
3502 // over kMaxFreeLen could be because of the use of mmaps, so
3503 // don't report. If not free memory then start a new segment.
3504 bool flush = true;
3505 if (start > startOfNextMemoryChunk_) {
3506 const size_t kMaxFreeLen = 2 * kPageSize;
3507 void* freeStart = startOfNextMemoryChunk_;
3508 void* freeEnd = start;
Brian Carlstrom2d888622013-07-18 17:02:00 -07003509 size_t freeLen = reinterpret_cast<char*>(freeEnd) - reinterpret_cast<char*>(freeStart);
Ian Rogers15bf2d32012-08-28 17:33:04 -07003510 if (!native || freeLen < kMaxFreeLen) {
3511 AppendChunk(HPSG_STATE(SOLIDITY_FREE, 0), freeStart, freeLen);
3512 flush = false;
3513 }
3514 }
3515 if (flush) {
3516 startOfNextMemoryChunk_ = NULL;
3517 Flush();
3518 }
3519 }
Ian Rogersef7d42f2014-01-06 12:55:46 -08003520 mirror::Object* obj = reinterpret_cast<mirror::Object*>(start);
Elliott Hughesa2155262011-11-16 16:26:58 -08003521
3522 // Determine the type of this chunk.
3523 // OLD-TODO: if context.merge, see if this chunk is different from the last chunk.
3524 // If it's the same, we should combine them.
Ian Rogers15bf2d32012-08-28 17:33:04 -07003525 uint8_t state = ExamineObject(obj, native);
3526 // dlmalloc's chunk header is 2 * sizeof(size_t), but if the previous chunk is in use for an
3527 // allocation then the first sizeof(size_t) may belong to it.
3528 const size_t dlMallocOverhead = sizeof(size_t);
3529 AppendChunk(state, start, used_bytes + dlMallocOverhead);
Brian Carlstrom2d888622013-07-18 17:02:00 -07003530 startOfNextMemoryChunk_ = reinterpret_cast<char*>(start) + used_bytes + dlMallocOverhead;
Ian Rogers15bf2d32012-08-28 17:33:04 -07003531 }
Elliott Hughesa2155262011-11-16 16:26:58 -08003532
Ian Rogers15bf2d32012-08-28 17:33:04 -07003533 void AppendChunk(uint8_t state, void* ptr, size_t length)
Ian Rogersb726dcb2012-09-05 08:57:23 -07003534 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Ian Rogers15bf2d32012-08-28 17:33:04 -07003535 // Make sure there's enough room left in the buffer.
3536 // We need to use two bytes for every fractional 256 allocation units used by the chunk plus
3537 // 17 bytes for any header.
3538 size_t needed = (((length/ALLOCATION_UNIT_SIZE + 255) / 256) * 2) + 17;
3539 size_t bytesLeft = buf_.size() - (size_t)(p_ - &buf_[0]);
3540 if (bytesLeft < needed) {
3541 Flush();
3542 }
3543
3544 bytesLeft = buf_.size() - (size_t)(p_ - &buf_[0]);
3545 if (bytesLeft < needed) {
3546 LOG(WARNING) << "Chunk is too big to transmit (chunk_len=" << length << ", "
3547 << needed << " bytes)";
3548 return;
3549 }
3550 EnsureHeader(ptr);
Elliott Hughesa2155262011-11-16 16:26:58 -08003551 // Write out the chunk description.
Ian Rogers15bf2d32012-08-28 17:33:04 -07003552 length /= ALLOCATION_UNIT_SIZE; // Convert to allocation units.
3553 totalAllocationUnits_ += length;
3554 while (length > 256) {
Ian Rogers30fab402012-01-23 15:43:46 -08003555 *p_++ = state | HPSG_PARTIAL;
3556 *p_++ = 255; // length - 1
Ian Rogers15bf2d32012-08-28 17:33:04 -07003557 length -= 256;
Elliott Hughesa2155262011-11-16 16:26:58 -08003558 }
Ian Rogers30fab402012-01-23 15:43:46 -08003559 *p_++ = state;
Ian Rogers15bf2d32012-08-28 17:33:04 -07003560 *p_++ = length - 1;
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003561 }
3562
Ian Rogersef7d42f2014-01-06 12:55:46 -08003563 uint8_t ExamineObject(mirror::Object* o, bool is_native_heap)
3564 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_, Locks::heap_bitmap_lock_) {
Elliott Hughesa2155262011-11-16 16:26:58 -08003565 if (o == NULL) {
3566 return HPSG_STATE(SOLIDITY_FREE, 0);
3567 }
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003568
Elliott Hughesa2155262011-11-16 16:26:58 -08003569 // It's an allocated chunk. Figure out what it is.
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003570
Elliott Hughesa2155262011-11-16 16:26:58 -08003571 // If we're looking at the native heap, we'll just return
3572 // (SOLIDITY_HARD, KIND_NATIVE) for all allocated chunks.
Ian Rogers00f7d0e2012-07-19 15:28:27 -07003573 if (is_native_heap) {
Elliott Hughesa2155262011-11-16 16:26:58 -08003574 return HPSG_STATE(SOLIDITY_HARD, KIND_NATIVE);
3575 }
3576
Ian Rogers5bfa60f2012-09-02 21:17:56 -07003577 if (!Runtime::Current()->GetHeap()->IsLiveObjectLocked(o)) {
Ian Rogers15bf2d32012-08-28 17:33:04 -07003578 return HPSG_STATE(SOLIDITY_HARD, KIND_NATIVE);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07003579 }
3580
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003581 mirror::Class* c = o->GetClass();
Elliott Hughesa2155262011-11-16 16:26:58 -08003582 if (c == NULL) {
3583 // The object was probably just created but hasn't been initialized yet.
3584 return HPSG_STATE(SOLIDITY_HARD, KIND_OBJECT);
3585 }
3586
Mathieu Chartier590fee92013-09-13 13:46:47 -07003587 if (!Runtime::Current()->GetHeap()->IsValidObjectAddress(c)) {
Ian Rogers15bf2d32012-08-28 17:33:04 -07003588 LOG(ERROR) << "Invalid class for managed heap object: " << o << " " << c;
Elliott Hughesa2155262011-11-16 16:26:58 -08003589 return HPSG_STATE(SOLIDITY_HARD, KIND_UNKNOWN);
3590 }
3591
3592 if (c->IsClassClass()) {
3593 return HPSG_STATE(SOLIDITY_HARD, KIND_CLASS_OBJECT);
3594 }
3595
3596 if (c->IsArrayClass()) {
3597 if (o->IsObjectArray()) {
3598 return HPSG_STATE(SOLIDITY_HARD, KIND_ARRAY_4);
3599 }
3600 switch (c->GetComponentSize()) {
3601 case 1: return HPSG_STATE(SOLIDITY_HARD, KIND_ARRAY_1);
3602 case 2: return HPSG_STATE(SOLIDITY_HARD, KIND_ARRAY_2);
3603 case 4: return HPSG_STATE(SOLIDITY_HARD, KIND_ARRAY_4);
3604 case 8: return HPSG_STATE(SOLIDITY_HARD, KIND_ARRAY_8);
3605 }
3606 }
3607
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003608 return HPSG_STATE(SOLIDITY_HARD, KIND_OBJECT);
3609 }
3610
Ian Rogers30fab402012-01-23 15:43:46 -08003611 std::vector<uint8_t> buf_;
3612 uint8_t* p_;
3613 uint8_t* pieceLenField_;
Ian Rogers15bf2d32012-08-28 17:33:04 -07003614 void* startOfNextMemoryChunk_;
Ian Rogers30fab402012-01-23 15:43:46 -08003615 size_t totalAllocationUnits_;
3616 uint32_t type_;
3617 bool merge_;
3618 bool needHeader_;
3619
Elliott Hughesa2155262011-11-16 16:26:58 -08003620 DISALLOW_COPY_AND_ASSIGN(HeapChunkContext);
3621};
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003622
3623void Dbg::DdmSendHeapSegments(bool native) {
3624 Dbg::HpsgWhen when;
3625 Dbg::HpsgWhat what;
3626 if (!native) {
3627 when = gDdmHpsgWhen;
3628 what = gDdmHpsgWhat;
3629 } else {
3630 when = gDdmNhsgWhen;
3631 what = gDdmNhsgWhat;
3632 }
3633 if (when == HPSG_WHEN_NEVER) {
3634 return;
3635 }
3636
3637 // Figure out what kind of chunks we'll be sending.
3638 CHECK(what == HPSG_WHAT_MERGED_OBJECTS || what == HPSG_WHAT_DISTINCT_OBJECTS) << static_cast<int>(what);
3639
3640 // First, send a heap start chunk.
3641 uint8_t heap_id[4];
Brian Carlstrom7934ac22013-07-26 10:54:15 -07003642 JDWP::Set4BE(&heap_id[0], 1); // Heap id (bogus; we only have one heap).
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003643 Dbg::DdmSendChunk(native ? CHUNK_TYPE("NHST") : CHUNK_TYPE("HPST"), sizeof(heap_id), heap_id);
3644
Hiroshi Yamauchicf58d4a2013-09-26 14:21:22 -07003645 Thread* self = Thread::Current();
3646
3647 // To allow the Walk/InspectAll() below to exclusively-lock the
3648 // mutator lock, temporarily release the shared access to the
3649 // mutator lock here by transitioning to the suspended state.
3650 Locks::mutator_lock_->AssertSharedHeld(self);
3651 self->TransitionFromRunnableToSuspended(kSuspended);
3652
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003653 // Send a series of heap segment chunks.
Elliott Hughesa2155262011-11-16 16:26:58 -08003654 HeapChunkContext context((what == HPSG_WHAT_MERGED_OBJECTS), native);
3655 if (native) {
Ian Rogers1d54e732013-05-02 21:10:01 -07003656 dlmalloc_inspect_all(HeapChunkContext::HeapChunkCallback, &context);
Elliott Hughesa2155262011-11-16 16:26:58 -08003657 } else {
Ian Rogers1d54e732013-05-02 21:10:01 -07003658 gc::Heap* heap = Runtime::Current()->GetHeap();
3659 const std::vector<gc::space::ContinuousSpace*>& spaces = heap->GetContinuousSpaces();
Ian Rogers62d6c772013-02-27 08:32:07 -08003660 ReaderMutexLock mu(self, *Locks::heap_bitmap_lock_);
Ian Rogers1d54e732013-05-02 21:10:01 -07003661 typedef std::vector<gc::space::ContinuousSpace*>::const_iterator It;
3662 for (It cur = spaces.begin(), end = spaces.end(); cur != end; ++cur) {
Hiroshi Yamauchicf58d4a2013-09-26 14:21:22 -07003663 if ((*cur)->IsMallocSpace()) {
3664 (*cur)->AsMallocSpace()->Walk(HeapChunkContext::HeapChunkCallback, &context);
Mathieu Chartierb062fdd2012-07-03 09:51:48 -07003665 }
3666 }
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -07003667 // Walk the large objects, these are not in the AllocSpace.
3668 heap->GetLargeObjectsSpace()->Walk(HeapChunkContext::HeapChunkCallback, &context);
Elliott Hughesa2155262011-11-16 16:26:58 -08003669 }
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003670
Hiroshi Yamauchicf58d4a2013-09-26 14:21:22 -07003671 // Shared-lock the mutator lock back.
3672 self->TransitionFromSuspendedToRunnable();
3673 Locks::mutator_lock_->AssertSharedHeld(self);
3674
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003675 // Finally, send a heap end chunk.
3676 Dbg::DdmSendChunk(native ? CHUNK_TYPE("NHEN") : CHUNK_TYPE("HPEN"), sizeof(heap_id), heap_id);
Elliott Hughes767a1472011-10-26 18:49:02 -07003677}
3678
Elliott Hughesb1a58792013-07-11 18:10:58 -07003679static size_t GetAllocTrackerMax() {
3680#ifdef HAVE_ANDROID_OS
3681 // Check whether there's a system property overriding the number of records.
3682 const char* propertyName = "dalvik.vm.allocTrackerMax";
3683 char allocRecordMaxString[PROPERTY_VALUE_MAX];
3684 if (property_get(propertyName, allocRecordMaxString, "") > 0) {
3685 char* end;
3686 size_t value = strtoul(allocRecordMaxString, &end, 10);
3687 if (*end != '\0') {
Ruben Brunk3e47a742013-09-09 17:56:07 -07003688 LOG(ERROR) << "Ignoring " << propertyName << " '" << allocRecordMaxString
3689 << "' --- invalid";
Elliott Hughesb1a58792013-07-11 18:10:58 -07003690 return kDefaultNumAllocRecords;
3691 }
3692 if (!IsPowerOfTwo(value)) {
Ruben Brunk3e47a742013-09-09 17:56:07 -07003693 LOG(ERROR) << "Ignoring " << propertyName << " '" << allocRecordMaxString
3694 << "' --- not power of two";
Elliott Hughesb1a58792013-07-11 18:10:58 -07003695 return kDefaultNumAllocRecords;
3696 }
3697 return value;
3698 }
3699#endif
3700 return kDefaultNumAllocRecords;
3701}
3702
Elliott Hughes545a0642011-11-08 19:10:03 -08003703void Dbg::SetAllocTrackingEnabled(bool enabled) {
Ian Rogers719d1a32014-03-06 12:13:39 -08003704 MutexLock mu(Thread::Current(), *alloc_tracker_lock_);
Elliott Hughes545a0642011-11-08 19:10:03 -08003705 if (enabled) {
3706 if (recent_allocation_records_ == NULL) {
Ian Rogers719d1a32014-03-06 12:13:39 -08003707 alloc_record_max_ = GetAllocTrackerMax();
3708 LOG(INFO) << "Enabling alloc tracker (" << alloc_record_max_ << " entries of "
Elliott Hughesb1a58792013-07-11 18:10:58 -07003709 << kMaxAllocRecordStackDepth << " frames, taking "
Ian Rogers719d1a32014-03-06 12:13:39 -08003710 << PrettySize(sizeof(AllocRecord) * alloc_record_max_) << ")";
3711 alloc_record_head_ = alloc_record_count_ = 0;
3712 recent_allocation_records_ = new AllocRecord[alloc_record_max_];
Elliott Hughes545a0642011-11-08 19:10:03 -08003713 CHECK(recent_allocation_records_ != NULL);
3714 }
Ian Rogersfa824272013-11-05 16:12:57 -08003715 Runtime::Current()->GetInstrumentation()->InstrumentQuickAllocEntryPoints();
Elliott Hughes545a0642011-11-08 19:10:03 -08003716 } else {
Ian Rogersfa824272013-11-05 16:12:57 -08003717 Runtime::Current()->GetInstrumentation()->UninstrumentQuickAllocEntryPoints();
Elliott Hughes545a0642011-11-08 19:10:03 -08003718 delete[] recent_allocation_records_;
3719 recent_allocation_records_ = NULL;
3720 }
3721}
3722
Ian Rogers0399dde2012-06-06 17:09:28 -07003723struct AllocRecordStackVisitor : public StackVisitor {
Ian Rogers7a22fa62013-01-23 12:16:16 -08003724 AllocRecordStackVisitor(Thread* thread, AllocRecord* record)
Ian Rogersb726dcb2012-09-05 08:57:23 -07003725 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_)
Ian Rogers7a22fa62013-01-23 12:16:16 -08003726 : StackVisitor(thread, NULL), record(record), depth(0) {}
Elliott Hughes545a0642011-11-08 19:10:03 -08003727
Ian Rogers00f7d0e2012-07-19 15:28:27 -07003728 // TODO: Enable annotalysis. We know lock is held in constructor, but abstraction confuses
3729 // annotalysis.
3730 bool VisitFrame() NO_THREAD_SAFETY_ANALYSIS {
Elliott Hughes545a0642011-11-08 19:10:03 -08003731 if (depth >= kMaxAllocRecordStackDepth) {
Elliott Hughes530fa002012-03-12 11:44:49 -07003732 return false;
Elliott Hughes545a0642011-11-08 19:10:03 -08003733 }
Brian Carlstromea46f952013-07-30 01:26:50 -07003734 mirror::ArtMethod* m = GetMethod();
Ian Rogers0399dde2012-06-06 17:09:28 -07003735 if (!m->IsRuntimeMethod()) {
3736 record->stack[depth].method = m;
3737 record->stack[depth].dex_pc = GetDexPc();
Elliott Hughes530fa002012-03-12 11:44:49 -07003738 ++depth;
Elliott Hughes545a0642011-11-08 19:10:03 -08003739 }
Elliott Hughes530fa002012-03-12 11:44:49 -07003740 return true;
Elliott Hughes545a0642011-11-08 19:10:03 -08003741 }
3742
3743 ~AllocRecordStackVisitor() {
3744 // Clear out any unused stack trace elements.
3745 for (; depth < kMaxAllocRecordStackDepth; ++depth) {
3746 record->stack[depth].method = NULL;
Ian Rogers0399dde2012-06-06 17:09:28 -07003747 record->stack[depth].dex_pc = 0;
Elliott Hughes545a0642011-11-08 19:10:03 -08003748 }
3749 }
3750
3751 AllocRecord* record;
3752 size_t depth;
3753};
3754
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003755void Dbg::RecordAllocation(mirror::Class* type, size_t byte_count) {
Elliott Hughes545a0642011-11-08 19:10:03 -08003756 Thread* self = Thread::Current();
3757 CHECK(self != NULL);
3758
Ian Rogers719d1a32014-03-06 12:13:39 -08003759 MutexLock mu(self, *alloc_tracker_lock_);
Elliott Hughes545a0642011-11-08 19:10:03 -08003760 if (recent_allocation_records_ == NULL) {
3761 return;
3762 }
3763
3764 // Advance and clip.
Ian Rogers719d1a32014-03-06 12:13:39 -08003765 if (++alloc_record_head_ == alloc_record_max_) {
3766 alloc_record_head_ = 0;
Elliott Hughes545a0642011-11-08 19:10:03 -08003767 }
3768
3769 // Fill in the basics.
Ian Rogers719d1a32014-03-06 12:13:39 -08003770 AllocRecord* record = &recent_allocation_records_[alloc_record_head_];
Elliott Hughes545a0642011-11-08 19:10:03 -08003771 record->type = type;
3772 record->byte_count = byte_count;
Ian Rogersd9c4fc92013-10-01 19:45:43 -07003773 record->thin_lock_id = self->GetThreadId();
Elliott Hughes545a0642011-11-08 19:10:03 -08003774
3775 // Fill in the stack trace.
Ian Rogers7a22fa62013-01-23 12:16:16 -08003776 AllocRecordStackVisitor visitor(self, record);
Ian Rogers0399dde2012-06-06 17:09:28 -07003777 visitor.WalkStack();
Elliott Hughes545a0642011-11-08 19:10:03 -08003778
Ian Rogers719d1a32014-03-06 12:13:39 -08003779 if (alloc_record_count_ < alloc_record_max_) {
3780 ++alloc_record_count_;
Elliott Hughes545a0642011-11-08 19:10:03 -08003781 }
3782}
3783
Elliott Hughesa8f93cb2012-06-08 17:08:48 -07003784// Returns the index of the head element.
3785//
3786// We point at the most-recently-written record, so if gAllocRecordCount is 1
3787// we want to use the current element. Take "head+1" and subtract count
3788// from it.
3789//
3790// We need to handle underflow in our circular buffer, so we add
Elliott Hughesb1a58792013-07-11 18:10:58 -07003791// gAllocRecordMax and then mask it back down.
Ian Rogers719d1a32014-03-06 12:13:39 -08003792size_t Dbg::HeadIndex() {
3793 return (Dbg::alloc_record_head_ + 1 + Dbg::alloc_record_max_ - Dbg::alloc_record_count_) &
3794 (Dbg::alloc_record_max_ - 1);
Elliott Hughes545a0642011-11-08 19:10:03 -08003795}
3796
3797void Dbg::DumpRecentAllocations() {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07003798 ScopedObjectAccess soa(Thread::Current());
Ian Rogers719d1a32014-03-06 12:13:39 -08003799 MutexLock mu(soa.Self(), *alloc_tracker_lock_);
Elliott Hughes545a0642011-11-08 19:10:03 -08003800 if (recent_allocation_records_ == NULL) {
3801 LOG(INFO) << "Not recording tracked allocations";
3802 return;
3803 }
3804
3805 // "i" is the head of the list. We want to start at the end of the
3806 // list and move forward to the tail.
Elliott Hughesa8f93cb2012-06-08 17:08:48 -07003807 size_t i = HeadIndex();
Ian Rogers719d1a32014-03-06 12:13:39 -08003808 size_t count = alloc_record_count_;
Elliott Hughes545a0642011-11-08 19:10:03 -08003809
Ian Rogers719d1a32014-03-06 12:13:39 -08003810 LOG(INFO) << "Tracked allocations, (head=" << alloc_record_head_ << " count=" << count << ")";
Elliott Hughes545a0642011-11-08 19:10:03 -08003811 while (count--) {
3812 AllocRecord* record = &recent_allocation_records_[i];
3813
Elliott Hughesa8f93cb2012-06-08 17:08:48 -07003814 LOG(INFO) << StringPrintf(" Thread %-2d %6zd bytes ", record->thin_lock_id, record->byte_count)
Elliott Hughes545a0642011-11-08 19:10:03 -08003815 << PrettyClass(record->type);
3816
3817 for (size_t stack_frame = 0; stack_frame < kMaxAllocRecordStackDepth; ++stack_frame) {
Ian Rogersef7d42f2014-01-06 12:55:46 -08003818 mirror::ArtMethod* m = record->stack[stack_frame].method;
Elliott Hughes545a0642011-11-08 19:10:03 -08003819 if (m == NULL) {
3820 break;
3821 }
3822 LOG(INFO) << " " << PrettyMethod(m) << " line " << record->stack[stack_frame].LineNumber();
3823 }
3824
3825 // pause periodically to help logcat catch up
3826 if ((count % 5) == 0) {
3827 usleep(40000);
3828 }
3829
Ian Rogers719d1a32014-03-06 12:13:39 -08003830 i = (i + 1) & (alloc_record_max_ - 1);
Elliott Hughes545a0642011-11-08 19:10:03 -08003831 }
3832}
3833
Mathieu Chartier83c8ee02014-01-28 14:50:23 -08003834void Dbg::UpdateObjectPointers(IsMarkedCallback* visitor, void* arg) {
Ian Rogers719d1a32014-03-06 12:13:39 -08003835 if (recent_allocation_records_ != nullptr) {
3836 MutexLock mu(Thread::Current(), *alloc_tracker_lock_);
3837 size_t i = HeadIndex();
3838 size_t count = alloc_record_count_;
3839 while (count--) {
3840 AllocRecord* record = &recent_allocation_records_[i];
3841 DCHECK(record != nullptr);
3842 record->UpdateObjectPointers(visitor, arg);
3843 i = (i + 1) & (alloc_record_max_ - 1);
Mathieu Chartier412c7fc2014-02-07 12:18:39 -08003844 }
3845 }
3846 if (gRegistry != nullptr) {
3847 gRegistry->UpdateObjectPointers(visitor, arg);
3848 }
3849}
3850
3851void Dbg::AllowNewObjectRegistryObjects() {
3852 if (gRegistry != nullptr) {
3853 gRegistry->AllowNewObjects();
3854 }
3855}
3856
3857void Dbg::DisallowNewObjectRegistryObjects() {
3858 if (gRegistry != nullptr) {
3859 gRegistry->DisallowNewObjects();
3860 }
3861}
3862
Elliott Hughes545a0642011-11-08 19:10:03 -08003863class StringTable {
3864 public:
3865 StringTable() {
3866 }
3867
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08003868 void Add(const char* s) {
Elliott Hughes545a0642011-11-08 19:10:03 -08003869 table_.insert(s);
3870 }
3871
Elliott Hughesa8f93cb2012-06-08 17:08:48 -07003872 size_t IndexOf(const char* s) const {
Mathieu Chartier02e25112013-08-14 16:14:24 -07003873 auto it = table_.find(s);
Elliott Hughesa8f93cb2012-06-08 17:08:48 -07003874 if (it == table_.end()) {
3875 LOG(FATAL) << "IndexOf(\"" << s << "\") failed";
3876 }
3877 return std::distance(table_.begin(), it);
Elliott Hughes545a0642011-11-08 19:10:03 -08003878 }
3879
Elliott Hughesa8f93cb2012-06-08 17:08:48 -07003880 size_t Size() const {
Elliott Hughes545a0642011-11-08 19:10:03 -08003881 return table_.size();
3882 }
3883
Elliott Hughesa8f93cb2012-06-08 17:08:48 -07003884 void WriteTo(std::vector<uint8_t>& bytes) const {
Mathieu Chartier02e25112013-08-14 16:14:24 -07003885 for (const std::string& str : table_) {
3886 const char* s = str.c_str();
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08003887 size_t s_len = CountModifiedUtf8Chars(s);
3888 UniquePtr<uint16_t> s_utf16(new uint16_t[s_len]);
3889 ConvertModifiedUtf8ToUtf16(s_utf16.get(), s);
3890 JDWP::AppendUtf16BE(bytes, s_utf16.get(), s_len);
Elliott Hughes545a0642011-11-08 19:10:03 -08003891 }
3892 }
3893
3894 private:
Elliott Hughesa8f93cb2012-06-08 17:08:48 -07003895 std::set<std::string> table_;
Elliott Hughes545a0642011-11-08 19:10:03 -08003896 DISALLOW_COPY_AND_ASSIGN(StringTable);
3897};
3898
3899/*
3900 * The data we send to DDMS contains everything we have recorded.
3901 *
3902 * Message header (all values big-endian):
3903 * (1b) message header len (to allow future expansion); includes itself
3904 * (1b) entry header len
3905 * (1b) stack frame len
3906 * (2b) number of entries
3907 * (4b) offset to string table from start of message
3908 * (2b) number of class name strings
3909 * (2b) number of method name strings
3910 * (2b) number of source file name strings
3911 * For each entry:
3912 * (4b) total allocation size
Elliott Hughes221229c2013-01-08 18:17:50 -08003913 * (2b) thread id
Elliott Hughes545a0642011-11-08 19:10:03 -08003914 * (2b) allocated object's class name index
3915 * (1b) stack depth
3916 * For each stack frame:
3917 * (2b) method's class name
3918 * (2b) method name
3919 * (2b) method source file
3920 * (2b) line number, clipped to 32767; -2 if native; -1 if no source
3921 * (xb) class name strings
3922 * (xb) method name strings
3923 * (xb) source file strings
3924 *
3925 * As with other DDM traffic, strings are sent as a 4-byte length
3926 * followed by UTF-16 data.
3927 *
3928 * We send up 16-bit unsigned indexes into string tables. In theory there
Elliott Hughesb1a58792013-07-11 18:10:58 -07003929 * can be (kMaxAllocRecordStackDepth * gAllocRecordMax) unique strings in
Elliott Hughes545a0642011-11-08 19:10:03 -08003930 * each table, but in practice there should be far fewer.
3931 *
3932 * The chief reason for using a string table here is to keep the size of
3933 * the DDMS message to a minimum. This is partly to make the protocol
3934 * efficient, but also because we have to form the whole thing up all at
3935 * once in a memory buffer.
3936 *
3937 * We use separate string tables for class names, method names, and source
3938 * files to keep the indexes small. There will generally be no overlap
3939 * between the contents of these tables.
3940 */
3941jbyteArray Dbg::GetRecentAllocations() {
3942 if (false) {
3943 DumpRecentAllocations();
3944 }
3945
Ian Rogers50b35e22012-10-04 10:09:15 -07003946 Thread* self = Thread::Current();
Elliott Hughes545a0642011-11-08 19:10:03 -08003947 std::vector<uint8_t> bytes;
Mathieu Chartier46e811b2013-07-10 17:09:14 -07003948 {
Ian Rogers719d1a32014-03-06 12:13:39 -08003949 MutexLock mu(self, *alloc_tracker_lock_);
Mathieu Chartier46e811b2013-07-10 17:09:14 -07003950 //
3951 // Part 1: generate string tables.
3952 //
3953 StringTable class_names;
3954 StringTable method_names;
3955 StringTable filenames;
Elliott Hughes545a0642011-11-08 19:10:03 -08003956
Ian Rogers719d1a32014-03-06 12:13:39 -08003957 int count = alloc_record_count_;
Mathieu Chartier46e811b2013-07-10 17:09:14 -07003958 int idx = HeadIndex();
3959 while (count--) {
3960 AllocRecord* record = &recent_allocation_records_[idx];
Elliott Hughes545a0642011-11-08 19:10:03 -08003961
Mathieu Chartier46e811b2013-07-10 17:09:14 -07003962 class_names.Add(ClassHelper(record->type).GetDescriptor());
Elliott Hughes545a0642011-11-08 19:10:03 -08003963
Mathieu Chartier46e811b2013-07-10 17:09:14 -07003964 MethodHelper mh;
3965 for (size_t i = 0; i < kMaxAllocRecordStackDepth; i++) {
Brian Carlstromea46f952013-07-30 01:26:50 -07003966 mirror::ArtMethod* m = record->stack[i].method;
Mathieu Chartier46e811b2013-07-10 17:09:14 -07003967 if (m != NULL) {
3968 mh.ChangeMethod(m);
3969 class_names.Add(mh.GetDeclaringClassDescriptor());
3970 method_names.Add(mh.GetName());
3971 filenames.Add(mh.GetDeclaringClassSourceFile());
3972 }
3973 }
Elliott Hughes545a0642011-11-08 19:10:03 -08003974
Ian Rogers719d1a32014-03-06 12:13:39 -08003975 idx = (idx + 1) & (alloc_record_max_ - 1);
Elliott Hughes545a0642011-11-08 19:10:03 -08003976 }
3977
Ian Rogers719d1a32014-03-06 12:13:39 -08003978 LOG(INFO) << "allocation records: " << alloc_record_count_;
Mathieu Chartier46e811b2013-07-10 17:09:14 -07003979
3980 //
3981 // Part 2: Generate the output and store it in the buffer.
3982 //
3983
3984 // (1b) message header len (to allow future expansion); includes itself
3985 // (1b) entry header len
3986 // (1b) stack frame len
3987 const int kMessageHeaderLen = 15;
3988 const int kEntryHeaderLen = 9;
3989 const int kStackFrameLen = 8;
3990 JDWP::Append1BE(bytes, kMessageHeaderLen);
3991 JDWP::Append1BE(bytes, kEntryHeaderLen);
3992 JDWP::Append1BE(bytes, kStackFrameLen);
3993
3994 // (2b) number of entries
3995 // (4b) offset to string table from start of message
3996 // (2b) number of class name strings
3997 // (2b) number of method name strings
3998 // (2b) number of source file name strings
Ian Rogers719d1a32014-03-06 12:13:39 -08003999 JDWP::Append2BE(bytes, alloc_record_count_);
Mathieu Chartier46e811b2013-07-10 17:09:14 -07004000 size_t string_table_offset = bytes.size();
Brian Carlstrom7934ac22013-07-26 10:54:15 -07004001 JDWP::Append4BE(bytes, 0); // We'll patch this later...
Mathieu Chartier46e811b2013-07-10 17:09:14 -07004002 JDWP::Append2BE(bytes, class_names.Size());
4003 JDWP::Append2BE(bytes, method_names.Size());
4004 JDWP::Append2BE(bytes, filenames.Size());
4005
Ian Rogers719d1a32014-03-06 12:13:39 -08004006 count = alloc_record_count_;
Mathieu Chartier46e811b2013-07-10 17:09:14 -07004007 idx = HeadIndex();
Mathieu Chartier46e811b2013-07-10 17:09:14 -07004008 while (count--) {
4009 // For each entry:
4010 // (4b) total allocation size
4011 // (2b) thread id
4012 // (2b) allocated object's class name index
4013 // (1b) stack depth
4014 AllocRecord* record = &recent_allocation_records_[idx];
4015 size_t stack_depth = record->GetDepth();
Mathieu Chartier590fee92013-09-13 13:46:47 -07004016 ClassHelper kh(record->type);
Mathieu Chartier46e811b2013-07-10 17:09:14 -07004017 size_t allocated_object_class_name_index = class_names.IndexOf(kh.GetDescriptor());
4018 JDWP::Append4BE(bytes, record->byte_count);
4019 JDWP::Append2BE(bytes, record->thin_lock_id);
4020 JDWP::Append2BE(bytes, allocated_object_class_name_index);
4021 JDWP::Append1BE(bytes, stack_depth);
4022
4023 MethodHelper mh;
4024 for (size_t stack_frame = 0; stack_frame < stack_depth; ++stack_frame) {
4025 // For each stack frame:
4026 // (2b) method's class name
4027 // (2b) method name
4028 // (2b) method source file
4029 // (2b) line number, clipped to 32767; -2 if native; -1 if no source
4030 mh.ChangeMethod(record->stack[stack_frame].method);
4031 size_t class_name_index = class_names.IndexOf(mh.GetDeclaringClassDescriptor());
4032 size_t method_name_index = method_names.IndexOf(mh.GetName());
4033 size_t file_name_index = filenames.IndexOf(mh.GetDeclaringClassSourceFile());
4034 JDWP::Append2BE(bytes, class_name_index);
4035 JDWP::Append2BE(bytes, method_name_index);
4036 JDWP::Append2BE(bytes, file_name_index);
4037 JDWP::Append2BE(bytes, record->stack[stack_frame].LineNumber());
4038 }
4039
Ian Rogers719d1a32014-03-06 12:13:39 -08004040 idx = (idx + 1) & (alloc_record_max_ - 1);
Mathieu Chartier46e811b2013-07-10 17:09:14 -07004041 }
4042
4043 // (xb) class name strings
4044 // (xb) method name strings
4045 // (xb) source file strings
4046 JDWP::Set4BE(&bytes[string_table_offset], bytes.size());
4047 class_names.WriteTo(bytes);
4048 method_names.WriteTo(bytes);
4049 filenames.WriteTo(bytes);
Elliott Hughes545a0642011-11-08 19:10:03 -08004050 }
Ian Rogers50b35e22012-10-04 10:09:15 -07004051 JNIEnv* env = self->GetJniEnv();
Elliott Hughes545a0642011-11-08 19:10:03 -08004052 jbyteArray result = env->NewByteArray(bytes.size());
4053 if (result != NULL) {
4054 env->SetByteArrayRegion(result, 0, bytes.size(), reinterpret_cast<const jbyte*>(&bytes[0]));
4055 }
4056 return result;
4057}
4058
Elliott Hughes872d4ec2011-10-21 17:07:15 -07004059} // namespace art