blob: f19c353f18d6828026e3112280c814ff7c835978 [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"
Mathieu Chartiereb8167a2014-05-07 15:43:14 -070031#include "handle_scope.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"
Ian Rogersb0fa5dc2014-04-28 16:47:08 -070040#include "mirror/string-inl.h"
Ian Rogers2dd0e2c2013-01-24 12:42:14 -080041#include "mirror/throwable.h"
Ian Rogers6d4d9fc2011-11-30 16:24:48 -080042#include "object_utils.h"
Sebastien Hertza76a6d42014-03-20 16:40:17 +010043#include "quick/inline_method_analyser.h"
Ian Rogers53b8b092014-03-13 23:45:53 -070044#include "reflection.h"
Elliott Hughesa0e18062012-04-13 15:59:59 -070045#include "safe_map.h"
Elliott Hughes64f574f2013-02-20 14:57:12 -080046#include "scoped_thread_state_change.h"
Elliott Hughes6a5bd492011-10-28 14:33:57 -070047#include "ScopedLocalRef.h"
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -070048#include "ScopedPrimitiveArray.h"
Mathieu Chartiereb8167a2014-05-07 15:43:14 -070049#include "handle_scope-inl.h"
Elliott Hughes475fc232011-10-25 15:00:35 -070050#include "thread_list.h"
Ian Rogers62d6c772013-02-27 08:32:07 -080051#include "throw_location.h"
Ian Rogers2dd0e2c2013-01-24 12:42:14 -080052#include "utf.h"
Sebastien Hertza76a6d42014-03-20 16:40:17 +010053#include "verifier/method_verifier-inl.h"
Elliott Hugheseac76672012-05-24 21:56:51 -070054#include "well_known_classes.h"
Elliott Hughes475fc232011-10-25 15:00:35 -070055
Brian Carlstrom3d92d522013-07-12 09:03:08 -070056#ifdef HAVE_ANDROID_OS
57#include "cutils/properties.h"
58#endif
59
Elliott Hughes872d4ec2011-10-21 17:07:15 -070060namespace art {
61
Brian Carlstrom7934ac22013-07-26 10:54:15 -070062static const size_t kMaxAllocRecordStackDepth = 16; // Max 255.
63static const size_t kDefaultNumAllocRecords = 64*1024; // Must be a power of 2.
Elliott Hughes475fc232011-10-25 15:00:35 -070064
Hiroshi Yamauchib5a9e3d2014-06-09 12:11:20 -070065class AllocRecordStackTraceElement {
66 public:
67 AllocRecordStackTraceElement() : method_(nullptr), dex_pc_(0) {
Mathieu Chartier412c7fc2014-02-07 12:18:39 -080068 }
69
Hiroshi Yamauchib5a9e3d2014-06-09 12:11:20 -070070 int32_t LineNumber() SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
71 mirror::ArtMethod* method = Method();
72 DCHECK(method != nullptr);
73 return method->GetLineNumFromDexPC(DexPc());
Elliott Hughes545a0642011-11-08 19:10:03 -080074 }
Hiroshi Yamauchib5a9e3d2014-06-09 12:11:20 -070075
76 mirror::ArtMethod* Method() SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
77 mirror::ArtMethod* method = reinterpret_cast<mirror::ArtMethod*>(
78 Thread::Current()->DecodeJObject(method_));
79 return method;
80 }
81
82 void SetMethod(mirror::ArtMethod* m) SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
83 ScopedObjectAccessUnchecked soa(Thread::Current());
84 JNIEnv* env = soa.Env();
85 if (method_ != nullptr) {
86 env->DeleteWeakGlobalRef(method_);
87 }
88 method_ = env->NewWeakGlobalRef(soa.AddLocalReference<jobject>(m));
89 }
90
91 uint32_t DexPc() const {
92 return dex_pc_;
93 }
94
95 void SetDexPc(uint32_t pc) {
96 dex_pc_ = pc;
97 }
98
99 private:
100 jobject method_; // This is a weak global.
101 uint32_t dex_pc_;
Elliott Hughes545a0642011-11-08 19:10:03 -0800102};
103
Hiroshi Yamauchib5a9e3d2014-06-09 12:11:20 -0700104class AllocRecord {
105 public:
106 AllocRecord() : type_(nullptr), byte_count_(0), thin_lock_id_(0) {}
Elliott Hughes545a0642011-11-08 19:10:03 -0800107
Hiroshi Yamauchib5a9e3d2014-06-09 12:11:20 -0700108 mirror::Class* Type() SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
109 mirror::Class* type = reinterpret_cast<mirror::Class*>(
110 Thread::Current()->DecodeJObject(type_));
111 return type;
112 }
113
114 void SetType(mirror::Class* t) SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
115 ScopedObjectAccessUnchecked soa(Thread::Current());
116 JNIEnv* env = soa.Env();
117 if (type_ != nullptr) {
118 env->DeleteWeakGlobalRef(type_);
119 }
120 type_ = env->NewWeakGlobalRef(soa.AddLocalReference<jobject>(t));
121 }
122
123 size_t GetDepth() SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Elliott Hughes545a0642011-11-08 19:10:03 -0800124 size_t depth = 0;
Hiroshi Yamauchib5a9e3d2014-06-09 12:11:20 -0700125 while (depth < kMaxAllocRecordStackDepth && stack_[depth].Method() != NULL) {
Elliott Hughes545a0642011-11-08 19:10:03 -0800126 ++depth;
127 }
128 return depth;
129 }
Mathieu Chartier412c7fc2014-02-07 12:18:39 -0800130
Hiroshi Yamauchib5a9e3d2014-06-09 12:11:20 -0700131 size_t ByteCount() const {
132 return byte_count_;
Mathieu Chartier412c7fc2014-02-07 12:18:39 -0800133 }
Hiroshi Yamauchib5a9e3d2014-06-09 12:11:20 -0700134
135 void SetByteCount(size_t count) {
136 byte_count_ = count;
137 }
138
139 uint16_t ThinLockId() const {
140 return thin_lock_id_;
141 }
142
143 void SetThinLockId(uint16_t id) {
144 thin_lock_id_ = id;
145 }
146
147 AllocRecordStackTraceElement* StackElement(size_t index) {
148 DCHECK_LT(index, kMaxAllocRecordStackDepth);
149 return &stack_[index];
150 }
151
152 private:
153 jobject type_; // This is a weak global.
154 size_t byte_count_;
155 uint16_t thin_lock_id_;
156 AllocRecordStackTraceElement stack_[kMaxAllocRecordStackDepth]; // Unused entries have NULL method.
Elliott Hughes545a0642011-11-08 19:10:03 -0800157};
158
Elliott Hughes86964332012-02-15 19:37:42 -0800159struct Breakpoint {
Sebastien Hertza76a6d42014-03-20 16:40:17 +0100160 // The location of this breakpoint.
Brian Carlstromea46f952013-07-30 01:26:50 -0700161 mirror::ArtMethod* method;
Elliott Hughesa656a0f2012-02-21 18:03:44 -0800162 uint32_t dex_pc;
Sebastien Hertza76a6d42014-03-20 16:40:17 +0100163
164 // Indicates whether breakpoint needs full deoptimization or selective deoptimization.
165 bool need_full_deoptimization;
166
167 Breakpoint(mirror::ArtMethod* method, uint32_t dex_pc, bool need_full_deoptimization)
168 : method(method), dex_pc(dex_pc), need_full_deoptimization(need_full_deoptimization) {}
Mathieu Chartier3b05e9b2014-03-25 09:29:43 -0700169
170 void VisitRoots(RootCallback* callback, void* arg) {
171 if (method != nullptr) {
172 callback(reinterpret_cast<mirror::Object**>(&method), arg, 0, kRootDebugger);
173 }
174 }
Elliott Hughes86964332012-02-15 19:37:42 -0800175};
176
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700177static std::ostream& operator<<(std::ostream& os, const Breakpoint& rhs)
Ian Rogersb726dcb2012-09-05 08:57:23 -0700178 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Elliott Hughes229feb72012-02-23 13:33:29 -0800179 os << StringPrintf("Breakpoint[%s @%#x]", PrettyMethod(rhs.method).c_str(), rhs.dex_pc);
Elliott Hughes86964332012-02-15 19:37:42 -0800180 return os;
181}
182
Sebastien Hertz3f52eaf2014-04-04 17:50:18 +0200183class DebugInstrumentationListener FINAL : public instrumentation::InstrumentationListener {
Ian Rogers62d6c772013-02-27 08:32:07 -0800184 public:
185 DebugInstrumentationListener() {}
186 virtual ~DebugInstrumentationListener() {}
187
Sebastien Hertz3f52eaf2014-04-04 17:50:18 +0200188 void MethodEntered(Thread* thread, mirror::Object* this_object, mirror::ArtMethod* method,
189 uint32_t dex_pc)
190 OVERRIDE SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Ian Rogers62d6c772013-02-27 08:32:07 -0800191 if (method->IsNative()) {
192 // TODO: post location events is a suspension point and native method entry stubs aren't.
193 return;
194 }
Sebastien Hertz8379b222014-02-24 17:38:15 +0100195 Dbg::UpdateDebugger(thread, this_object, method, 0, Dbg::kMethodEntry, nullptr);
Ian Rogers62d6c772013-02-27 08:32:07 -0800196 }
197
Sebastien Hertz3f52eaf2014-04-04 17:50:18 +0200198 void MethodExited(Thread* thread, mirror::Object* this_object, mirror::ArtMethod* method,
199 uint32_t dex_pc, const JValue& return_value)
200 OVERRIDE SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Ian Rogers62d6c772013-02-27 08:32:07 -0800201 if (method->IsNative()) {
202 // TODO: post location events is a suspension point and native method entry stubs aren't.
203 return;
204 }
Sebastien Hertz8379b222014-02-24 17:38:15 +0100205 Dbg::UpdateDebugger(thread, this_object, method, dex_pc, Dbg::kMethodExit, &return_value);
Ian Rogers62d6c772013-02-27 08:32:07 -0800206 }
207
Sebastien Hertz3f52eaf2014-04-04 17:50:18 +0200208 void MethodUnwind(Thread* thread, mirror::Object* this_object, mirror::ArtMethod* method,
209 uint32_t dex_pc)
210 OVERRIDE SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Ian Rogers62d6c772013-02-27 08:32:07 -0800211 // We're not recorded to listen to this kind of event, so complain.
212 LOG(ERROR) << "Unexpected method unwind event in debugger " << PrettyMethod(method)
Sebastien Hertz51db44a2013-11-19 10:00:29 +0100213 << " " << dex_pc;
Ian Rogers62d6c772013-02-27 08:32:07 -0800214 }
215
Sebastien Hertz3f52eaf2014-04-04 17:50:18 +0200216 void DexPcMoved(Thread* thread, mirror::Object* this_object, mirror::ArtMethod* method,
217 uint32_t new_dex_pc)
218 OVERRIDE SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Sebastien Hertz8379b222014-02-24 17:38:15 +0100219 Dbg::UpdateDebugger(thread, this_object, method, new_dex_pc, 0, nullptr);
Ian Rogers62d6c772013-02-27 08:32:07 -0800220 }
221
Sebastien Hertz3f52eaf2014-04-04 17:50:18 +0200222 void FieldRead(Thread* thread, mirror::Object* this_object, mirror::ArtMethod* method,
223 uint32_t dex_pc, mirror::ArtField* field)
224 OVERRIDE SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
225 Dbg::PostFieldAccessEvent(method, dex_pc, this_object, field);
Ian Rogers62d6c772013-02-27 08:32:07 -0800226 }
Sebastien Hertz3f52eaf2014-04-04 17:50:18 +0200227
228 void FieldWritten(Thread* thread, mirror::Object* this_object, mirror::ArtMethod* method,
229 uint32_t dex_pc, mirror::ArtField* field, const JValue& field_value)
230 OVERRIDE SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
231 Dbg::PostFieldModificationEvent(method, dex_pc, this_object, field, &field_value);
232 }
233
234 void ExceptionCaught(Thread* thread, const ThrowLocation& throw_location,
235 mirror::ArtMethod* catch_method, uint32_t catch_dex_pc,
236 mirror::Throwable* exception_object)
237 OVERRIDE SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
238 Dbg::PostException(throw_location, catch_method, catch_dex_pc, exception_object);
239 }
240
241 private:
242 DISALLOW_COPY_AND_ASSIGN(DebugInstrumentationListener);
Ian Rogers62d6c772013-02-27 08:32:07 -0800243} gDebugInstrumentationListener;
244
Elliott Hughes4ffd3132011-10-24 12:06:42 -0700245// JDWP is allowed unless the Zygote forbids it.
246static bool gJdwpAllowed = true;
247
Elliott Hughesc0f09332012-03-26 13:27:06 -0700248// Was there a -Xrunjdwp or -agentlib:jdwp= argument on the command line?
Elliott Hughes3bb81562011-10-21 18:52:59 -0700249static bool gJdwpConfigured = false;
250
Elliott Hughesc0f09332012-03-26 13:27:06 -0700251// Broken-down JDWP options. (Only valid if IsJdwpConfigured() is true.)
Elliott Hughes376a7a02011-10-24 18:35:55 -0700252static JDWP::JdwpOptions gJdwpOptions;
Elliott Hughes3bb81562011-10-21 18:52:59 -0700253
254// Runtime JDWP state.
255static JDWP::JdwpState* gJdwpState = NULL;
256static bool gDebuggerConnected; // debugger or DDMS is connected.
257static bool gDebuggerActive; // debugger is making requests.
Elliott Hughes86964332012-02-15 19:37:42 -0800258static bool gDisposed; // debugger called VirtualMachine.Dispose, so we should drop the connection.
Elliott Hughes3bb81562011-10-21 18:52:59 -0700259
Elliott Hughes47fce012011-10-25 18:37:19 -0700260static bool gDdmThreadNotification = false;
261
Elliott Hughes767a1472011-10-26 18:49:02 -0700262// DDMS GC-related settings.
263static Dbg::HpifWhen gDdmHpifWhen = Dbg::HPIF_WHEN_NEVER;
264static Dbg::HpsgWhen gDdmHpsgWhen = Dbg::HPSG_WHEN_NEVER;
265static Dbg::HpsgWhat gDdmHpsgWhat;
266static Dbg::HpsgWhen gDdmNhsgWhen = Dbg::HPSG_WHEN_NEVER;
267static Dbg::HpsgWhat gDdmNhsgWhat;
268
Ian Rogers719d1a32014-03-06 12:13:39 -0800269static ObjectRegistry* gRegistry = nullptr;
Elliott Hughes475fc232011-10-25 15:00:35 -0700270
Elliott Hughes545a0642011-11-08 19:10:03 -0800271// Recent allocation tracking.
Ian Rogers719d1a32014-03-06 12:13:39 -0800272Mutex* Dbg::alloc_tracker_lock_ = nullptr;
273AllocRecord* Dbg::recent_allocation_records_ = nullptr; // TODO: CircularBuffer<AllocRecord>
274size_t Dbg::alloc_record_max_ = 0;
275size_t Dbg::alloc_record_head_ = 0;
276size_t Dbg::alloc_record_count_ = 0;
Elliott Hughes545a0642011-11-08 19:10:03 -0800277
Sebastien Hertz138dbfc2013-12-04 18:15:25 +0100278// Deoptimization support.
Sebastien Hertz4d25df32014-03-21 17:44:46 +0100279Mutex* Dbg::deoptimization_lock_ = nullptr;
280std::vector<DeoptimizationRequest> Dbg::deoptimization_requests_;
281size_t Dbg::full_deoptimization_event_count_ = 0;
Sebastien Hertz7ec2f1c2014-03-27 20:06:47 +0100282size_t Dbg::delayed_full_undeoptimization_count_ = 0;
Sebastien Hertz138dbfc2013-12-04 18:15:25 +0100283
Sebastien Hertz42cd43f2014-05-13 14:15:41 +0200284// Instrumentation event reference counters.
285size_t Dbg::dex_pc_change_event_ref_count_ = 0;
286size_t Dbg::method_enter_event_ref_count_ = 0;
287size_t Dbg::method_exit_event_ref_count_ = 0;
288size_t Dbg::field_read_event_ref_count_ = 0;
289size_t Dbg::field_write_event_ref_count_ = 0;
290size_t Dbg::exception_catch_event_ref_count_ = 0;
291uint32_t Dbg::instrumentation_events_ = 0;
292
Sebastien Hertz138dbfc2013-12-04 18:15:25 +0100293// Breakpoints.
jeffhao09bfc6a2012-12-11 18:11:43 -0800294static std::vector<Breakpoint> gBreakpoints GUARDED_BY(Locks::breakpoint_lock_);
Elliott Hughes86964332012-02-15 19:37:42 -0800295
Mathieu Chartier3b05e9b2014-03-25 09:29:43 -0700296void DebugInvokeReq::VisitRoots(RootCallback* callback, void* arg, uint32_t tid,
297 RootType root_type) {
298 if (receiver != nullptr) {
299 callback(&receiver, arg, tid, root_type);
300 }
301 if (thread != nullptr) {
302 callback(&thread, arg, tid, root_type);
303 }
304 if (klass != nullptr) {
305 callback(reinterpret_cast<mirror::Object**>(&klass), arg, tid, root_type);
306 }
307 if (method != nullptr) {
308 callback(reinterpret_cast<mirror::Object**>(&method), arg, tid, root_type);
309 }
310}
311
Sebastien Hertzbb43b432014-04-14 11:59:08 +0200312void DebugInvokeReq::Clear() {
313 invoke_needed = false;
314 receiver = nullptr;
315 thread = nullptr;
316 klass = nullptr;
317 method = nullptr;
318}
319
Mathieu Chartier3b05e9b2014-03-25 09:29:43 -0700320void SingleStepControl::VisitRoots(RootCallback* callback, void* arg, uint32_t tid,
321 RootType root_type) {
322 if (method != nullptr) {
323 callback(reinterpret_cast<mirror::Object**>(&method), arg, tid, root_type);
324 }
325}
326
Sebastien Hertzbb43b432014-04-14 11:59:08 +0200327bool SingleStepControl::ContainsDexPc(uint32_t dex_pc) const {
328 return dex_pcs.find(dex_pc) == dex_pcs.end();
329}
330
331void SingleStepControl::Clear() {
332 is_active = false;
333 method = nullptr;
334 dex_pcs.clear();
335}
336
Sebastien Hertz4d25df32014-03-21 17:44:46 +0100337void DeoptimizationRequest::VisitRoots(RootCallback* callback, void* arg) {
338 if (method != nullptr) {
339 callback(reinterpret_cast<mirror::Object**>(&method), arg, 0, kRootDebugger);
340 }
341}
342
Brian Carlstromea46f952013-07-30 01:26:50 -0700343static bool IsBreakpoint(const mirror::ArtMethod* m, uint32_t dex_pc)
jeffhao09bfc6a2012-12-11 18:11:43 -0800344 LOCKS_EXCLUDED(Locks::breakpoint_lock_)
Ian Rogersb726dcb2012-09-05 08:57:23 -0700345 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
jeffhao09bfc6a2012-12-11 18:11:43 -0800346 MutexLock mu(Thread::Current(), *Locks::breakpoint_lock_);
Sebastien Hertz138dbfc2013-12-04 18:15:25 +0100347 for (size_t i = 0, e = gBreakpoints.size(); i < e; ++i) {
Elliott Hughesa656a0f2012-02-21 18:03:44 -0800348 if (gBreakpoints[i].method == m && gBreakpoints[i].dex_pc == dex_pc) {
Elliott Hughes86964332012-02-15 19:37:42 -0800349 VLOG(jdwp) << "Hit breakpoint #" << i << ": " << gBreakpoints[i];
350 return true;
351 }
352 }
353 return false;
354}
355
Sebastien Hertz52d131d2014-03-13 16:17:40 +0100356static bool IsSuspendedForDebugger(ScopedObjectAccessUnchecked& soa, Thread* thread)
357 LOCKS_EXCLUDED(Locks::thread_suspend_count_lock_) {
Elliott Hughes9e0c1752013-01-09 14:02:58 -0800358 MutexLock mu(soa.Self(), *Locks::thread_suspend_count_lock_);
359 // A thread may be suspended for GC; in this code, we really want to know whether
360 // there's a debugger suspension active.
361 return thread->IsSuspended() && thread->GetDebugSuspendCount() > 0;
362}
363
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800364static mirror::Array* DecodeArray(JDWP::RefTypeId id, JDWP::JdwpError& status)
Ian Rogersb726dcb2012-09-05 08:57:23 -0700365 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800366 mirror::Object* o = gRegistry->Get<mirror::Object*>(id);
Elliott Hughes64f574f2013-02-20 14:57:12 -0800367 if (o == NULL || o == ObjectRegistry::kInvalidObject) {
Elliott Hughes436e3722012-02-17 20:01:47 -0800368 status = JDWP::ERR_INVALID_OBJECT;
369 return NULL;
370 }
371 if (!o->IsArrayInstance()) {
372 status = JDWP::ERR_INVALID_ARRAY;
373 return NULL;
374 }
375 status = JDWP::ERR_NONE;
376 return o->AsArray();
377}
378
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800379static mirror::Class* DecodeClass(JDWP::RefTypeId id, JDWP::JdwpError& status)
Ian Rogersb726dcb2012-09-05 08:57:23 -0700380 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800381 mirror::Object* o = gRegistry->Get<mirror::Object*>(id);
Elliott Hughes64f574f2013-02-20 14:57:12 -0800382 if (o == NULL || o == ObjectRegistry::kInvalidObject) {
Elliott Hughes436e3722012-02-17 20:01:47 -0800383 status = JDWP::ERR_INVALID_OBJECT;
384 return NULL;
385 }
386 if (!o->IsClass()) {
387 status = JDWP::ERR_INVALID_CLASS;
388 return NULL;
389 }
390 status = JDWP::ERR_NONE;
391 return o->AsClass();
392}
393
Elliott Hughes221229c2013-01-08 18:17:50 -0800394static JDWP::JdwpError DecodeThread(ScopedObjectAccessUnchecked& soa, JDWP::ObjectId thread_id, Thread*& thread)
jeffhaoa77f0f62012-12-05 17:19:31 -0800395 EXCLUSIVE_LOCKS_REQUIRED(Locks::thread_list_lock_)
Ian Rogersb726dcb2012-09-05 08:57:23 -0700396 LOCKS_EXCLUDED(Locks::thread_suspend_count_lock_)
397 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800398 mirror::Object* thread_peer = gRegistry->Get<mirror::Object*>(thread_id);
Elliott Hughes64f574f2013-02-20 14:57:12 -0800399 if (thread_peer == NULL || thread_peer == ObjectRegistry::kInvalidObject) {
Elliott Hughes221229c2013-01-08 18:17:50 -0800400 // This isn't even an object.
401 return JDWP::ERR_INVALID_OBJECT;
Elliott Hughes436e3722012-02-17 20:01:47 -0800402 }
Elliott Hughes221229c2013-01-08 18:17:50 -0800403
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800404 mirror::Class* java_lang_Thread = soa.Decode<mirror::Class*>(WellKnownClasses::java_lang_Thread);
Elliott Hughes221229c2013-01-08 18:17:50 -0800405 if (!java_lang_Thread->IsAssignableFrom(thread_peer->GetClass())) {
406 // This isn't a thread.
407 return JDWP::ERR_INVALID_THREAD;
408 }
409
410 thread = Thread::FromManagedThread(soa, thread_peer);
411 if (thread == NULL) {
412 // This is a java.lang.Thread without a Thread*. Must be a zombie.
413 return JDWP::ERR_THREAD_NOT_ALIVE;
414 }
415 return JDWP::ERR_NONE;
Elliott Hughes436e3722012-02-17 20:01:47 -0800416}
417
Elliott Hughes24437992011-11-30 14:49:33 -0800418static JDWP::JdwpTag BasicTagFromDescriptor(const char* descriptor) {
419 // JDWP deliberately uses the descriptor characters' ASCII values for its enum.
420 // Note that by "basic" we mean that we don't get more specific than JT_OBJECT.
421 return static_cast<JDWP::JdwpTag>(descriptor[0]);
422}
423
Ian Rogers98379392014-02-24 16:53:16 -0800424static JDWP::JdwpTag TagFromClass(const ScopedObjectAccessUnchecked& soa, mirror::Class* c)
Ian Rogersb726dcb2012-09-05 08:57:23 -0700425 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Elliott Hughes86b00102011-12-05 17:54:26 -0800426 CHECK(c != NULL);
Elliott Hughes24437992011-11-30 14:49:33 -0800427 if (c->IsArrayClass()) {
428 return JDWP::JT_ARRAY;
429 }
Elliott Hughes24437992011-11-30 14:49:33 -0800430 if (c->IsStringClass()) {
431 return JDWP::JT_STRING;
Elliott Hughes24437992011-11-30 14:49:33 -0800432 }
Ian Rogers98379392014-02-24 16:53:16 -0800433 if (c->IsClassClass()) {
434 return JDWP::JT_CLASS_OBJECT;
435 }
436 {
437 mirror::Class* thread_class = soa.Decode<mirror::Class*>(WellKnownClasses::java_lang_Thread);
438 if (thread_class->IsAssignableFrom(c)) {
439 return JDWP::JT_THREAD;
440 }
441 }
442 {
443 mirror::Class* thread_group_class =
444 soa.Decode<mirror::Class*>(WellKnownClasses::java_lang_ThreadGroup);
445 if (thread_group_class->IsAssignableFrom(c)) {
446 return JDWP::JT_THREAD_GROUP;
447 }
448 }
449 {
450 mirror::Class* class_loader_class =
451 soa.Decode<mirror::Class*>(WellKnownClasses::java_lang_ClassLoader);
452 if (class_loader_class->IsAssignableFrom(c)) {
453 return JDWP::JT_CLASS_LOADER;
454 }
455 }
456 return JDWP::JT_OBJECT;
Elliott Hughes24437992011-11-30 14:49:33 -0800457}
458
459/*
460 * Objects declared to hold Object might actually hold a more specific
461 * type. The debugger may take a special interest in these (e.g. it
462 * wants to display the contents of Strings), so we want to return an
463 * appropriate tag.
464 *
465 * Null objects are tagged JT_OBJECT.
466 */
Ian Rogers98379392014-02-24 16:53:16 -0800467static JDWP::JdwpTag TagFromObject(const ScopedObjectAccessUnchecked& soa, mirror::Object* o)
Ian Rogersb726dcb2012-09-05 08:57:23 -0700468 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Ian Rogers98379392014-02-24 16:53:16 -0800469 return (o == NULL) ? JDWP::JT_OBJECT : TagFromClass(soa, o->GetClass());
Elliott Hughes24437992011-11-30 14:49:33 -0800470}
471
472static bool IsPrimitiveTag(JDWP::JdwpTag tag) {
473 switch (tag) {
474 case JDWP::JT_BOOLEAN:
475 case JDWP::JT_BYTE:
476 case JDWP::JT_CHAR:
477 case JDWP::JT_FLOAT:
478 case JDWP::JT_DOUBLE:
479 case JDWP::JT_INT:
480 case JDWP::JT_LONG:
481 case JDWP::JT_SHORT:
482 case JDWP::JT_VOID:
483 return true;
484 default:
485 return false;
486 }
487}
488
Elliott Hughes3bb81562011-10-21 18:52:59 -0700489/*
490 * Handle one of the JDWP name/value pairs.
491 *
492 * JDWP options are:
493 * help: if specified, show help message and bail
494 * transport: may be dt_socket or dt_shmem
495 * address: for dt_socket, "host:port", or just "port" when listening
496 * server: if "y", wait for debugger to attach; if "n", attach to debugger
497 * timeout: how long to wait for debugger to connect / listen
498 *
499 * Useful with server=n (these aren't supported yet):
500 * onthrow=<exception-name>: connect to debugger when exception thrown
501 * onuncaught=y|n: connect to debugger when uncaught exception thrown
502 * launch=<command-line>: launch the debugger itself
503 *
504 * The "transport" option is required, as is "address" if server=n.
505 */
506static bool ParseJdwpOption(const std::string& name, const std::string& value) {
507 if (name == "transport") {
508 if (value == "dt_socket") {
Elliott Hughes376a7a02011-10-24 18:35:55 -0700509 gJdwpOptions.transport = JDWP::kJdwpTransportSocket;
Elliott Hughes3bb81562011-10-21 18:52:59 -0700510 } else if (value == "dt_android_adb") {
Elliott Hughes376a7a02011-10-24 18:35:55 -0700511 gJdwpOptions.transport = JDWP::kJdwpTransportAndroidAdb;
Elliott Hughes3bb81562011-10-21 18:52:59 -0700512 } else {
513 LOG(ERROR) << "JDWP transport not supported: " << value;
514 return false;
515 }
516 } else if (name == "server") {
517 if (value == "n") {
Elliott Hughes376a7a02011-10-24 18:35:55 -0700518 gJdwpOptions.server = false;
Elliott Hughes3bb81562011-10-21 18:52:59 -0700519 } else if (value == "y") {
Elliott Hughes376a7a02011-10-24 18:35:55 -0700520 gJdwpOptions.server = true;
Elliott Hughes3bb81562011-10-21 18:52:59 -0700521 } else {
522 LOG(ERROR) << "JDWP option 'server' must be 'y' or 'n'";
523 return false;
524 }
525 } else if (name == "suspend") {
526 if (value == "n") {
Elliott Hughes376a7a02011-10-24 18:35:55 -0700527 gJdwpOptions.suspend = false;
Elliott Hughes3bb81562011-10-21 18:52:59 -0700528 } else if (value == "y") {
Elliott Hughes376a7a02011-10-24 18:35:55 -0700529 gJdwpOptions.suspend = true;
Elliott Hughes3bb81562011-10-21 18:52:59 -0700530 } else {
531 LOG(ERROR) << "JDWP option 'suspend' must be 'y' or 'n'";
532 return false;
533 }
534 } else if (name == "address") {
535 /* this is either <port> or <host>:<port> */
536 std::string port_string;
Elliott Hughes376a7a02011-10-24 18:35:55 -0700537 gJdwpOptions.host.clear();
Elliott Hughes3bb81562011-10-21 18:52:59 -0700538 std::string::size_type colon = value.find(':');
539 if (colon != std::string::npos) {
Elliott Hughes376a7a02011-10-24 18:35:55 -0700540 gJdwpOptions.host = value.substr(0, colon);
Elliott Hughes3bb81562011-10-21 18:52:59 -0700541 port_string = value.substr(colon + 1);
542 } else {
543 port_string = value;
544 }
545 if (port_string.empty()) {
546 LOG(ERROR) << "JDWP address missing port: " << value;
547 return false;
548 }
549 char* end;
Elliott Hughesba8eee12012-01-24 20:25:24 -0800550 uint64_t port = strtoul(port_string.c_str(), &end, 10);
551 if (*end != '\0' || port > 0xffff) {
Elliott Hughes3bb81562011-10-21 18:52:59 -0700552 LOG(ERROR) << "JDWP address has junk in port field: " << value;
553 return false;
554 }
Elliott Hughes376a7a02011-10-24 18:35:55 -0700555 gJdwpOptions.port = port;
Elliott Hughes3bb81562011-10-21 18:52:59 -0700556 } else if (name == "launch" || name == "onthrow" || name == "oncaught" || name == "timeout") {
557 /* valid but unsupported */
558 LOG(INFO) << "Ignoring JDWP option '" << name << "'='" << value << "'";
559 } else {
560 LOG(INFO) << "Ignoring unrecognized JDWP option '" << name << "'='" << value << "'";
561 }
562
563 return true;
564}
565
566/*
567 * Parse the latter half of a -Xrunjdwp/-agentlib:jdwp= string, e.g.:
568 * "transport=dt_socket,address=8000,server=y,suspend=n"
569 */
570bool Dbg::ParseJdwpOptions(const std::string& options) {
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -0800571 VLOG(jdwp) << "ParseJdwpOptions: " << options;
Elliott Hughes47fce012011-10-25 18:37:19 -0700572
Elliott Hughes3bb81562011-10-21 18:52:59 -0700573 std::vector<std::string> pairs;
574 Split(options, ',', pairs);
575
576 for (size_t i = 0; i < pairs.size(); ++i) {
577 std::string::size_type equals = pairs[i].find('=');
578 if (equals == std::string::npos) {
579 LOG(ERROR) << "Can't parse JDWP option '" << pairs[i] << "' in '" << options << "'";
580 return false;
581 }
582 ParseJdwpOption(pairs[i].substr(0, equals), pairs[i].substr(equals + 1));
583 }
584
Elliott Hughes376a7a02011-10-24 18:35:55 -0700585 if (gJdwpOptions.transport == JDWP::kJdwpTransportUnknown) {
Elliott Hughes3bb81562011-10-21 18:52:59 -0700586 LOG(ERROR) << "Must specify JDWP transport: " << options;
587 }
Elliott Hughes376a7a02011-10-24 18:35:55 -0700588 if (!gJdwpOptions.server && (gJdwpOptions.host.empty() || gJdwpOptions.port == 0)) {
Elliott Hughes3bb81562011-10-21 18:52:59 -0700589 LOG(ERROR) << "Must specify JDWP host and port when server=n: " << options;
590 return false;
591 }
592
593 gJdwpConfigured = true;
594 return true;
595}
596
Elliott Hughesd1cc8362011-10-24 16:58:50 -0700597void Dbg::StartJdwp() {
Elliott Hughesc0f09332012-03-26 13:27:06 -0700598 if (!gJdwpAllowed || !IsJdwpConfigured()) {
Elliott Hughes376a7a02011-10-24 18:35:55 -0700599 // No JDWP for you!
600 return;
601 }
602
Ian Rogers719d1a32014-03-06 12:13:39 -0800603 CHECK(gRegistry == nullptr);
Elliott Hughes475fc232011-10-25 15:00:35 -0700604 gRegistry = new ObjectRegistry;
605
Ian Rogers719d1a32014-03-06 12:13:39 -0800606 alloc_tracker_lock_ = new Mutex("AllocTracker lock");
Sebastien Hertz4d25df32014-03-21 17:44:46 +0100607 deoptimization_lock_ = new Mutex("deoptimization lock", kDeoptimizationLock);
Elliott Hughesd1cc8362011-10-24 16:58:50 -0700608 // Init JDWP if the debugger is enabled. This may connect out to a
609 // debugger, passively listen for a debugger, or block waiting for a
610 // debugger.
Elliott Hughes376a7a02011-10-24 18:35:55 -0700611 gJdwpState = JDWP::JdwpState::Create(&gJdwpOptions);
612 if (gJdwpState == NULL) {
Elliott Hughesf8a2df72011-12-01 12:19:54 -0800613 // We probably failed because some other process has the port already, which means that
614 // if we don't abort the user is likely to think they're talking to us when they're actually
615 // talking to that other process.
Elliott Hughes3d30d9b2011-12-07 17:35:48 -0800616 LOG(FATAL) << "Debugger thread failed to initialize";
Elliott Hughesd1cc8362011-10-24 16:58:50 -0700617 }
618
619 // If a debugger has already attached, send the "welcome" message.
620 // This may cause us to suspend all threads.
Elliott Hughes376a7a02011-10-24 18:35:55 -0700621 if (gJdwpState->IsActive()) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700622 ScopedObjectAccess soa(Thread::Current());
Elliott Hughes376a7a02011-10-24 18:35:55 -0700623 if (!gJdwpState->PostVMStart()) {
Elliott Hughes3d30d9b2011-12-07 17:35:48 -0800624 LOG(WARNING) << "Failed to post 'start' message to debugger";
Elliott Hughesd1cc8362011-10-24 16:58:50 -0700625 }
626 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700627}
628
Mathieu Chartier3b05e9b2014-03-25 09:29:43 -0700629void Dbg::VisitRoots(RootCallback* callback, void* arg) {
Sebastien Hertz4d25df32014-03-21 17:44:46 +0100630 {
631 MutexLock mu(Thread::Current(), *Locks::breakpoint_lock_);
632 for (Breakpoint& bp : gBreakpoints) {
633 bp.VisitRoots(callback, arg);
634 }
635 }
636 if (deoptimization_lock_ != nullptr) { // only true if the debugger is started.
637 MutexLock mu(Thread::Current(), *deoptimization_lock_);
638 for (DeoptimizationRequest& req : deoptimization_requests_) {
639 req.VisitRoots(callback, arg);
640 }
Mathieu Chartier3b05e9b2014-03-25 09:29:43 -0700641 }
642}
643
Elliott Hughesd1cc8362011-10-24 16:58:50 -0700644void Dbg::StopJdwp() {
Sebastien Hertz0376e6b2014-02-06 18:12:59 +0100645 // Prevent the JDWP thread from processing JDWP incoming packets after we close the connection.
646 Disposed();
Elliott Hughes376a7a02011-10-24 18:35:55 -0700647 delete gJdwpState;
Ian Rogers719d1a32014-03-06 12:13:39 -0800648 gJdwpState = nullptr;
Elliott Hughes475fc232011-10-25 15:00:35 -0700649 delete gRegistry;
Ian Rogers719d1a32014-03-06 12:13:39 -0800650 gRegistry = nullptr;
651 delete alloc_tracker_lock_;
652 alloc_tracker_lock_ = nullptr;
Sebastien Hertz4d25df32014-03-21 17:44:46 +0100653 delete deoptimization_lock_;
654 deoptimization_lock_ = nullptr;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700655}
656
Elliott Hughes767a1472011-10-26 18:49:02 -0700657void Dbg::GcDidFinish() {
658 if (gDdmHpifWhen != HPIF_WHEN_NEVER) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700659 ScopedObjectAccess soa(Thread::Current());
Brian Carlstrom4d466a82014-05-08 19:05:29 -0700660 VLOG(jdwp) << "Sending heap info to DDM";
Elliott Hughes7162ad92011-10-27 14:08:42 -0700661 DdmSendHeapInfo(gDdmHpifWhen);
Elliott Hughes767a1472011-10-26 18:49:02 -0700662 }
663 if (gDdmHpsgWhen != HPSG_WHEN_NEVER) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700664 ScopedObjectAccess soa(Thread::Current());
Brian Carlstrom4d466a82014-05-08 19:05:29 -0700665 VLOG(jdwp) << "Dumping heap to DDM";
Elliott Hughes6a5bd492011-10-28 14:33:57 -0700666 DdmSendHeapSegments(false);
Elliott Hughes767a1472011-10-26 18:49:02 -0700667 }
668 if (gDdmNhsgWhen != HPSG_WHEN_NEVER) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700669 ScopedObjectAccess soa(Thread::Current());
Brian Carlstrom4d466a82014-05-08 19:05:29 -0700670 VLOG(jdwp) << "Dumping native heap to DDM";
Elliott Hughes6a5bd492011-10-28 14:33:57 -0700671 DdmSendHeapSegments(true);
Elliott Hughes767a1472011-10-26 18:49:02 -0700672 }
673}
674
Elliott Hughes4ffd3132011-10-24 12:06:42 -0700675void Dbg::SetJdwpAllowed(bool allowed) {
676 gJdwpAllowed = allowed;
677}
678
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700679DebugInvokeReq* Dbg::GetInvokeReq() {
Elliott Hughes475fc232011-10-25 15:00:35 -0700680 return Thread::Current()->GetInvokeReq();
681}
682
683Thread* Dbg::GetDebugThread() {
684 return (gJdwpState != NULL) ? gJdwpState->GetDebugThread() : NULL;
685}
686
687void Dbg::ClearWaitForEventThread() {
688 gJdwpState->ClearWaitForEventThread();
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700689}
690
691void Dbg::Connected() {
Elliott Hughes3bb81562011-10-21 18:52:59 -0700692 CHECK(!gDebuggerConnected);
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -0800693 VLOG(jdwp) << "JDWP has attached";
Elliott Hughes3bb81562011-10-21 18:52:59 -0700694 gDebuggerConnected = true;
Elliott Hughes86964332012-02-15 19:37:42 -0800695 gDisposed = false;
696}
697
698void Dbg::Disposed() {
699 gDisposed = true;
700}
701
702bool Dbg::IsDisposed() {
703 return gDisposed;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700704}
705
Elliott Hughesa2155262011-11-16 16:26:58 -0800706void Dbg::GoActive() {
707 // Enable all debugging features, including scans for breakpoints.
708 // This is a no-op if we're already active.
709 // Only called from the JDWP handler thread.
710 if (gDebuggerActive) {
711 return;
712 }
713
Elliott Hughesc0f09332012-03-26 13:27:06 -0700714 {
715 // TODO: dalvik only warned if there were breakpoints left over. clear in Dbg::Disconnected?
jeffhao09bfc6a2012-12-11 18:11:43 -0800716 MutexLock mu(Thread::Current(), *Locks::breakpoint_lock_);
Elliott Hughesc0f09332012-03-26 13:27:06 -0700717 CHECK_EQ(gBreakpoints.size(), 0U);
718 }
Elliott Hughesa2155262011-11-16 16:26:58 -0800719
Sebastien Hertz138dbfc2013-12-04 18:15:25 +0100720 {
Sebastien Hertz4d25df32014-03-21 17:44:46 +0100721 MutexLock mu(Thread::Current(), *deoptimization_lock_);
722 CHECK_EQ(deoptimization_requests_.size(), 0U);
723 CHECK_EQ(full_deoptimization_event_count_, 0U);
Sebastien Hertz7ec2f1c2014-03-27 20:06:47 +0100724 CHECK_EQ(delayed_full_undeoptimization_count_, 0U);
Sebastien Hertz42cd43f2014-05-13 14:15:41 +0200725 CHECK_EQ(dex_pc_change_event_ref_count_, 0U);
726 CHECK_EQ(method_enter_event_ref_count_, 0U);
727 CHECK_EQ(method_exit_event_ref_count_, 0U);
728 CHECK_EQ(field_read_event_ref_count_, 0U);
729 CHECK_EQ(field_write_event_ref_count_, 0U);
730 CHECK_EQ(exception_catch_event_ref_count_, 0U);
Sebastien Hertz138dbfc2013-12-04 18:15:25 +0100731 }
732
Ian Rogers62d6c772013-02-27 08:32:07 -0800733 Runtime* runtime = Runtime::Current();
734 runtime->GetThreadList()->SuspendAll();
735 Thread* self = Thread::Current();
736 ThreadState old_state = self->SetStateUnsafe(kRunnable);
737 CHECK_NE(old_state, kRunnable);
Sebastien Hertz138dbfc2013-12-04 18:15:25 +0100738 runtime->GetInstrumentation()->EnableDeoptimization();
Sebastien Hertz42cd43f2014-05-13 14:15:41 +0200739 instrumentation_events_ = 0;
Elliott Hughesa2155262011-11-16 16:26:58 -0800740 gDebuggerActive = true;
Ian Rogers62d6c772013-02-27 08:32:07 -0800741 CHECK_EQ(self->SetStateUnsafe(old_state), kRunnable);
742 runtime->GetThreadList()->ResumeAll();
743
744 LOG(INFO) << "Debugger is active";
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700745}
746
747void Dbg::Disconnected() {
Elliott Hughes234ab152011-10-26 14:02:26 -0700748 CHECK(gDebuggerConnected);
749
Elliott Hughesc0f09332012-03-26 13:27:06 -0700750 LOG(INFO) << "Debugger is no longer active";
Elliott Hughes234ab152011-10-26 14:02:26 -0700751
Ian Rogers62d6c772013-02-27 08:32:07 -0800752 // Suspend all threads and exclusively acquire the mutator lock. Set the state of the thread
753 // to kRunnable to avoid scoped object access transitions. Remove the debugger as a listener
754 // and clear the object registry.
755 Runtime* runtime = Runtime::Current();
756 runtime->GetThreadList()->SuspendAll();
757 Thread* self = Thread::Current();
758 ThreadState old_state = self->SetStateUnsafe(kRunnable);
Sebastien Hertzaaea7342014-02-25 15:10:04 +0100759
760 // Debugger may not be active at this point.
761 if (gDebuggerActive) {
762 {
763 // Since we're going to disable deoptimization, we clear the deoptimization requests queue.
764 // This prevents us from having any pending deoptimization request when the debugger attaches
765 // to us again while no event has been requested yet.
Sebastien Hertz4d25df32014-03-21 17:44:46 +0100766 MutexLock mu(Thread::Current(), *deoptimization_lock_);
767 deoptimization_requests_.clear();
768 full_deoptimization_event_count_ = 0U;
Sebastien Hertz7ec2f1c2014-03-27 20:06:47 +0100769 delayed_full_undeoptimization_count_ = 0U;
Sebastien Hertzaaea7342014-02-25 15:10:04 +0100770 }
Sebastien Hertz42cd43f2014-05-13 14:15:41 +0200771 if (instrumentation_events_ != 0) {
772 runtime->GetInstrumentation()->RemoveListener(&gDebugInstrumentationListener,
773 instrumentation_events_);
774 instrumentation_events_ = 0;
775 }
Sebastien Hertzaaea7342014-02-25 15:10:04 +0100776 runtime->GetInstrumentation()->DisableDeoptimization();
777 gDebuggerActive = false;
Sebastien Hertz138dbfc2013-12-04 18:15:25 +0100778 }
Elliott Hughes234ab152011-10-26 14:02:26 -0700779 gRegistry->Clear();
780 gDebuggerConnected = false;
Ian Rogers62d6c772013-02-27 08:32:07 -0800781 CHECK_EQ(self->SetStateUnsafe(old_state), kRunnable);
782 runtime->GetThreadList()->ResumeAll();
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700783}
784
Elliott Hughesc0f09332012-03-26 13:27:06 -0700785bool Dbg::IsDebuggerActive() {
Elliott Hughes3bb81562011-10-21 18:52:59 -0700786 return gDebuggerActive;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700787}
788
Elliott Hughesc0f09332012-03-26 13:27:06 -0700789bool Dbg::IsJdwpConfigured() {
Elliott Hughes3bb81562011-10-21 18:52:59 -0700790 return gJdwpConfigured;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700791}
792
793int64_t Dbg::LastDebuggerActivity() {
Elliott Hughesca951522011-12-05 12:01:32 -0800794 return gJdwpState->LastDebuggerActivity();
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700795}
796
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700797void Dbg::UndoDebuggerSuspensions() {
Elliott Hughes234ab152011-10-26 14:02:26 -0700798 Runtime::Current()->GetThreadList()->UndoDebuggerSuspensions();
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700799}
800
Elliott Hughes88d63092013-01-09 09:55:54 -0800801std::string Dbg::GetClassName(JDWP::RefTypeId class_id) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800802 mirror::Object* o = gRegistry->Get<mirror::Object*>(class_id);
Elliott Hughes436e3722012-02-17 20:01:47 -0800803 if (o == NULL) {
804 return "NULL";
805 }
Elliott Hughes64f574f2013-02-20 14:57:12 -0800806 if (o == ObjectRegistry::kInvalidObject) {
Elliott Hughes88d63092013-01-09 09:55:54 -0800807 return StringPrintf("invalid object %p", reinterpret_cast<void*>(class_id));
Elliott Hughes436e3722012-02-17 20:01:47 -0800808 }
809 if (!o->IsClass()) {
Brian Carlstrom7934ac22013-07-26 10:54:15 -0700810 return StringPrintf("non-class %p", o); // This is only used for debugging output anyway.
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -0800811 }
Mathieu Chartierf8322842014-05-16 10:59:25 -0700812 return DescriptorToName(o->AsClass()->GetDescriptor().c_str());
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700813}
814
Elliott Hughes88d63092013-01-09 09:55:54 -0800815JDWP::JdwpError Dbg::GetClassObject(JDWP::RefTypeId id, JDWP::ObjectId& class_object_id) {
Elliott Hughes436e3722012-02-17 20:01:47 -0800816 JDWP::JdwpError status;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800817 mirror::Class* c = DecodeClass(id, status);
Elliott Hughes436e3722012-02-17 20:01:47 -0800818 if (c == NULL) {
819 return status;
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -0800820 }
Elliott Hughes88d63092013-01-09 09:55:54 -0800821 class_object_id = gRegistry->Add(c);
Elliott Hughes436e3722012-02-17 20:01:47 -0800822 return JDWP::ERR_NONE;
Elliott Hughes86964332012-02-15 19:37:42 -0800823}
824
Elliott Hughes88d63092013-01-09 09:55:54 -0800825JDWP::JdwpError Dbg::GetSuperclass(JDWP::RefTypeId id, JDWP::RefTypeId& superclass_id) {
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -0800826 JDWP::JdwpError status;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800827 mirror::Class* c = DecodeClass(id, status);
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -0800828 if (c == NULL) {
829 return status;
830 }
831 if (c->IsInterface()) {
832 // http://code.google.com/p/android/issues/detail?id=20856
Elliott Hughes88d63092013-01-09 09:55:54 -0800833 superclass_id = 0;
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -0800834 } else {
Elliott Hughes88d63092013-01-09 09:55:54 -0800835 superclass_id = gRegistry->Add(c->GetSuperClass());
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -0800836 }
837 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700838}
839
Elliott Hughes436e3722012-02-17 20:01:47 -0800840JDWP::JdwpError Dbg::GetClassLoader(JDWP::RefTypeId id, JDWP::ExpandBuf* pReply) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800841 mirror::Object* o = gRegistry->Get<mirror::Object*>(id);
Elliott Hughes64f574f2013-02-20 14:57:12 -0800842 if (o == NULL || o == ObjectRegistry::kInvalidObject) {
Elliott Hughes436e3722012-02-17 20:01:47 -0800843 return JDWP::ERR_INVALID_OBJECT;
844 }
845 expandBufAddObjectId(pReply, gRegistry->Add(o->GetClass()->GetClassLoader()));
846 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700847}
848
Elliott Hughes436e3722012-02-17 20:01:47 -0800849JDWP::JdwpError Dbg::GetModifiers(JDWP::RefTypeId id, JDWP::ExpandBuf* pReply) {
850 JDWP::JdwpError status;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800851 mirror::Class* c = DecodeClass(id, status);
Elliott Hughes436e3722012-02-17 20:01:47 -0800852 if (c == NULL) {
853 return status;
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -0800854 }
Elliott Hughes436e3722012-02-17 20:01:47 -0800855
856 uint32_t access_flags = c->GetAccessFlags() & kAccJavaFlagsMask;
857
Yevgeny Roubande34eea2014-02-15 01:06:03 +0700858 // Set ACC_SUPER. Dex files don't contain this flag but only classes are supposed to have it set,
859 // not interfaces.
Elliott Hughes436e3722012-02-17 20:01:47 -0800860 // Class.getModifiers doesn't return it, but JDWP does, so we set it here.
Yevgeny Roubande34eea2014-02-15 01:06:03 +0700861 if ((access_flags & kAccInterface) == 0) {
862 access_flags |= kAccSuper;
863 }
Elliott Hughes436e3722012-02-17 20:01:47 -0800864
865 expandBufAdd4BE(pReply, access_flags);
866
867 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700868}
869
Elliott Hughesf327e072013-01-09 16:01:26 -0800870JDWP::JdwpError Dbg::GetMonitorInfo(JDWP::ObjectId object_id, JDWP::ExpandBuf* reply)
871 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800872 mirror::Object* o = gRegistry->Get<mirror::Object*>(object_id);
Elliott Hughes64f574f2013-02-20 14:57:12 -0800873 if (o == NULL || o == ObjectRegistry::kInvalidObject) {
Elliott Hughesf327e072013-01-09 16:01:26 -0800874 return JDWP::ERR_INVALID_OBJECT;
875 }
876
877 // Ensure all threads are suspended while we read objects' lock words.
878 Thread* self = Thread::Current();
Sebastien Hertz54263242014-03-19 18:16:50 +0100879 CHECK_EQ(self->GetState(), kRunnable);
880 self->TransitionFromRunnableToSuspended(kSuspended);
881 Runtime::Current()->GetThreadList()->SuspendAll();
Elliott Hughesf327e072013-01-09 16:01:26 -0800882
883 MonitorInfo monitor_info(o);
884
Sebastien Hertz54263242014-03-19 18:16:50 +0100885 Runtime::Current()->GetThreadList()->ResumeAll();
886 self->TransitionFromSuspendedToRunnable();
Elliott Hughesf327e072013-01-09 16:01:26 -0800887
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700888 if (monitor_info.owner_ != NULL) {
889 expandBufAddObjectId(reply, gRegistry->Add(monitor_info.owner_->GetPeer()));
Elliott Hughesf327e072013-01-09 16:01:26 -0800890 } else {
891 expandBufAddObjectId(reply, gRegistry->Add(NULL));
892 }
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700893 expandBufAdd4BE(reply, monitor_info.entry_count_);
894 expandBufAdd4BE(reply, monitor_info.waiters_.size());
895 for (size_t i = 0; i < monitor_info.waiters_.size(); ++i) {
896 expandBufAddObjectId(reply, gRegistry->Add(monitor_info.waiters_[i]->GetPeer()));
Elliott Hughesf327e072013-01-09 16:01:26 -0800897 }
898 return JDWP::ERR_NONE;
899}
900
Elliott Hughes734b8c62013-01-11 15:32:45 -0800901JDWP::JdwpError Dbg::GetOwnedMonitors(JDWP::ObjectId thread_id,
902 std::vector<JDWP::ObjectId>& monitors,
Sebastien Hertz52d131d2014-03-13 16:17:40 +0100903 std::vector<uint32_t>& stack_depths) {
Elliott Hughes4993bbc2013-01-10 15:41:25 -0800904 struct OwnedMonitorVisitor : public StackVisitor {
Hiroshi Yamauchib5a9e3d2014-06-09 12:11:20 -0700905 OwnedMonitorVisitor(Thread* thread, Context* context,
Hiroshi Yamauchicc8c5c52014-06-13 15:08:05 -0700906 std::vector<JDWP::ObjectId>* monitor_vector,
Hiroshi Yamauchib5a9e3d2014-06-09 12:11:20 -0700907 std::vector<uint32_t>* stack_depth_vector)
Elliott Hughes4993bbc2013-01-10 15:41:25 -0800908 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_)
Hiroshi Yamauchib5a9e3d2014-06-09 12:11:20 -0700909 : StackVisitor(thread, context), current_stack_depth(0),
910 monitors(monitor_vector), stack_depths(stack_depth_vector) {}
Elliott Hughes4993bbc2013-01-10 15:41:25 -0800911
912 // TODO: Enable annotalysis. We know lock is held in constructor, but abstraction confuses
913 // annotalysis.
914 bool VisitFrame() NO_THREAD_SAFETY_ANALYSIS {
915 if (!GetMethod()->IsRuntimeMethod()) {
916 Monitor::VisitLocks(this, AppendOwnedMonitors, this);
Elliott Hughes734b8c62013-01-11 15:32:45 -0800917 ++current_stack_depth;
Elliott Hughes4993bbc2013-01-10 15:41:25 -0800918 }
919 return true;
920 }
921
Hiroshi Yamauchicc8c5c52014-06-13 15:08:05 -0700922 static void AppendOwnedMonitors(mirror::Object* owned_monitor, void* arg)
923 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Ian Rogers7a22fa62013-01-23 12:16:16 -0800924 OwnedMonitorVisitor* visitor = reinterpret_cast<OwnedMonitorVisitor*>(arg);
Hiroshi Yamauchicc8c5c52014-06-13 15:08:05 -0700925 visitor->monitors->push_back(gRegistry->Add(owned_monitor));
Hiroshi Yamauchib5a9e3d2014-06-09 12:11:20 -0700926 visitor->stack_depths->push_back(visitor->current_stack_depth);
Elliott Hughes4993bbc2013-01-10 15:41:25 -0800927 }
928
Elliott Hughes734b8c62013-01-11 15:32:45 -0800929 size_t current_stack_depth;
Hiroshi Yamauchicc8c5c52014-06-13 15:08:05 -0700930 std::vector<JDWP::ObjectId>* monitors;
Hiroshi Yamauchib5a9e3d2014-06-09 12:11:20 -0700931 std::vector<uint32_t>* stack_depths;
Elliott Hughes4993bbc2013-01-10 15:41:25 -0800932 };
Elliott Hughes4993bbc2013-01-10 15:41:25 -0800933
Hiroshi Yamauchib5a9e3d2014-06-09 12:11:20 -0700934 ScopedObjectAccessUnchecked soa(Thread::Current());
Hiroshi Yamauchicc8c5c52014-06-13 15:08:05 -0700935 Thread* thread;
Hiroshi Yamauchib5a9e3d2014-06-09 12:11:20 -0700936 {
937 MutexLock mu(soa.Self(), *Locks::thread_list_lock_);
Hiroshi Yamauchib5a9e3d2014-06-09 12:11:20 -0700938 JDWP::JdwpError error = DecodeThread(soa, thread_id, thread);
939 if (error != JDWP::ERR_NONE) {
940 return error;
941 }
942 if (!IsSuspendedForDebugger(soa, thread)) {
943 return JDWP::ERR_THREAD_NOT_SUSPENDED;
944 }
Hiroshi Yamauchib5a9e3d2014-06-09 12:11:20 -0700945 }
Hiroshi Yamauchicc8c5c52014-06-13 15:08:05 -0700946 std::unique_ptr<Context> context(Context::Create());
947 OwnedMonitorVisitor visitor(thread, context.get(), &monitors, &stack_depths);
948 visitor.WalkStack();
Elliott Hughes4993bbc2013-01-10 15:41:25 -0800949 return JDWP::ERR_NONE;
950}
951
Sebastien Hertz52d131d2014-03-13 16:17:40 +0100952JDWP::JdwpError Dbg::GetContendedMonitor(JDWP::ObjectId thread_id,
953 JDWP::ObjectId& contended_monitor) {
Hiroshi Yamauchib5a9e3d2014-06-09 12:11:20 -0700954 mirror::Object* contended_monitor_obj;
Elliott Hughesf9501702013-01-11 11:22:27 -0800955 ScopedObjectAccessUnchecked soa(Thread::Current());
Hiroshi Yamauchib5a9e3d2014-06-09 12:11:20 -0700956 {
957 MutexLock mu(soa.Self(), *Locks::thread_list_lock_);
958 Thread* thread;
959 JDWP::JdwpError error = DecodeThread(soa, thread_id, thread);
960 if (error != JDWP::ERR_NONE) {
961 return error;
962 }
963 if (!IsSuspendedForDebugger(soa, thread)) {
964 return JDWP::ERR_THREAD_NOT_SUSPENDED;
965 }
966 contended_monitor_obj = Monitor::GetContendedMonitor(thread);
Elliott Hughesf9501702013-01-11 11:22:27 -0800967 }
Hiroshi Yamauchib5a9e3d2014-06-09 12:11:20 -0700968 // Add() requires the thread_list_lock_ not held to avoid the lock
969 // level violation.
970 contended_monitor = gRegistry->Add(contended_monitor_obj);
Elliott Hughesf9501702013-01-11 11:22:27 -0800971 return JDWP::ERR_NONE;
972}
973
Elliott Hughesec0f83d2013-01-15 16:54:08 -0800974JDWP::JdwpError Dbg::GetInstanceCounts(const std::vector<JDWP::RefTypeId>& class_ids,
975 std::vector<uint64_t>& counts)
976 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Mathieu Chartier412c7fc2014-02-07 12:18:39 -0800977 gc::Heap* heap = Runtime::Current()->GetHeap();
978 heap->CollectGarbage(false);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800979 std::vector<mirror::Class*> classes;
Elliott Hughesec0f83d2013-01-15 16:54:08 -0800980 counts.clear();
981 for (size_t i = 0; i < class_ids.size(); ++i) {
982 JDWP::JdwpError status;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800983 mirror::Class* c = DecodeClass(class_ids[i], status);
Elliott Hughesec0f83d2013-01-15 16:54:08 -0800984 if (c == NULL) {
985 return status;
986 }
987 classes.push_back(c);
988 counts.push_back(0);
989 }
Mathieu Chartier412c7fc2014-02-07 12:18:39 -0800990 heap->CountInstances(classes, false, &counts[0]);
Elliott Hughesec0f83d2013-01-15 16:54:08 -0800991 return JDWP::ERR_NONE;
992}
993
Elliott Hughes3b78c942013-01-15 17:35:41 -0800994JDWP::JdwpError Dbg::GetInstances(JDWP::RefTypeId class_id, int32_t max_count, std::vector<JDWP::ObjectId>& instances)
995 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Mathieu Chartier412c7fc2014-02-07 12:18:39 -0800996 gc::Heap* heap = Runtime::Current()->GetHeap();
997 // We only want reachable instances, so do a GC.
998 heap->CollectGarbage(false);
Elliott Hughes3b78c942013-01-15 17:35:41 -0800999 JDWP::JdwpError status;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001000 mirror::Class* c = DecodeClass(class_id, status);
Mathieu Chartier412c7fc2014-02-07 12:18:39 -08001001 if (c == nullptr) {
Elliott Hughes3b78c942013-01-15 17:35:41 -08001002 return status;
1003 }
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001004 std::vector<mirror::Object*> raw_instances;
Elliott Hughes3b78c942013-01-15 17:35:41 -08001005 Runtime::Current()->GetHeap()->GetInstances(c, max_count, raw_instances);
1006 for (size_t i = 0; i < raw_instances.size(); ++i) {
1007 instances.push_back(gRegistry->Add(raw_instances[i]));
1008 }
1009 return JDWP::ERR_NONE;
1010}
1011
Elliott Hughes0cbaff52013-01-16 15:28:01 -08001012JDWP::JdwpError Dbg::GetReferringObjects(JDWP::ObjectId object_id, int32_t max_count,
1013 std::vector<JDWP::ObjectId>& referring_objects)
1014 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Mathieu Chartier412c7fc2014-02-07 12:18:39 -08001015 gc::Heap* heap = Runtime::Current()->GetHeap();
1016 heap->CollectGarbage(false);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001017 mirror::Object* o = gRegistry->Get<mirror::Object*>(object_id);
Elliott Hughes64f574f2013-02-20 14:57:12 -08001018 if (o == NULL || o == ObjectRegistry::kInvalidObject) {
Elliott Hughes0cbaff52013-01-16 15:28:01 -08001019 return JDWP::ERR_INVALID_OBJECT;
1020 }
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001021 std::vector<mirror::Object*> raw_instances;
Mathieu Chartier412c7fc2014-02-07 12:18:39 -08001022 heap->GetReferringObjects(o, max_count, raw_instances);
Elliott Hughes0cbaff52013-01-16 15:28:01 -08001023 for (size_t i = 0; i < raw_instances.size(); ++i) {
1024 referring_objects.push_back(gRegistry->Add(raw_instances[i]));
1025 }
1026 return JDWP::ERR_NONE;
1027}
1028
Elliott Hughes64f574f2013-02-20 14:57:12 -08001029JDWP::JdwpError Dbg::DisableCollection(JDWP::ObjectId object_id)
1030 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Sebastien Hertze96060a2013-12-11 12:06:28 +01001031 mirror::Object* o = gRegistry->Get<mirror::Object*>(object_id);
1032 if (o == NULL || o == ObjectRegistry::kInvalidObject) {
1033 return JDWP::ERR_INVALID_OBJECT;
1034 }
Elliott Hughes64f574f2013-02-20 14:57:12 -08001035 gRegistry->DisableCollection(object_id);
1036 return JDWP::ERR_NONE;
1037}
1038
1039JDWP::JdwpError Dbg::EnableCollection(JDWP::ObjectId object_id)
1040 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Sebastien Hertze96060a2013-12-11 12:06:28 +01001041 mirror::Object* o = gRegistry->Get<mirror::Object*>(object_id);
1042 // Unlike DisableCollection, JDWP specs do not state an invalid object causes an error. The RI
1043 // also ignores these cases and never return an error. However it's not obvious why this command
1044 // should behave differently from DisableCollection and IsCollected commands. So let's be more
1045 // strict and return an error if this happens.
1046 if (o == NULL || o == ObjectRegistry::kInvalidObject) {
1047 return JDWP::ERR_INVALID_OBJECT;
1048 }
Elliott Hughes64f574f2013-02-20 14:57:12 -08001049 gRegistry->EnableCollection(object_id);
1050 return JDWP::ERR_NONE;
1051}
1052
1053JDWP::JdwpError Dbg::IsCollected(JDWP::ObjectId object_id, bool& is_collected)
1054 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Sebastien Hertz65637eb2014-01-10 17:40:02 +01001055 if (object_id == 0) {
1056 // Null object id is invalid.
Sebastien Hertze96060a2013-12-11 12:06:28 +01001057 return JDWP::ERR_INVALID_OBJECT;
1058 }
Sebastien Hertz65637eb2014-01-10 17:40:02 +01001059 // JDWP specs state an INVALID_OBJECT error is returned if the object ID is not valid. However
1060 // the RI seems to ignore this and assume object has been collected.
1061 mirror::Object* o = gRegistry->Get<mirror::Object*>(object_id);
1062 if (o == NULL || o == ObjectRegistry::kInvalidObject) {
1063 is_collected = true;
1064 } else {
1065 is_collected = gRegistry->IsCollected(object_id);
1066 }
Elliott Hughes64f574f2013-02-20 14:57:12 -08001067 return JDWP::ERR_NONE;
1068}
1069
1070void Dbg::DisposeObject(JDWP::ObjectId object_id, uint32_t reference_count)
1071 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
1072 gRegistry->DisposeObject(object_id, reference_count);
1073}
1074
Sebastien Hertz4d8fd492014-03-28 16:29:41 +01001075static JDWP::JdwpTypeTag GetTypeTag(mirror::Class* klass)
1076 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
1077 DCHECK(klass != nullptr);
1078 if (klass->IsArrayClass()) {
1079 return JDWP::TT_ARRAY;
1080 } else if (klass->IsInterface()) {
1081 return JDWP::TT_INTERFACE;
1082 } else {
1083 return JDWP::TT_CLASS;
1084 }
1085}
1086
Elliott Hughes88d63092013-01-09 09:55:54 -08001087JDWP::JdwpError Dbg::GetReflectedType(JDWP::RefTypeId class_id, JDWP::ExpandBuf* pReply) {
Elliott Hughes436e3722012-02-17 20:01:47 -08001088 JDWP::JdwpError status;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001089 mirror::Class* c = DecodeClass(class_id, status);
Elliott Hughes436e3722012-02-17 20:01:47 -08001090 if (c == NULL) {
1091 return status;
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -08001092 }
Elliott Hughes436e3722012-02-17 20:01:47 -08001093
Sebastien Hertz4d8fd492014-03-28 16:29:41 +01001094 JDWP::JdwpTypeTag type_tag = GetTypeTag(c);
1095 expandBufAdd1(pReply, type_tag);
Elliott Hughes88d63092013-01-09 09:55:54 -08001096 expandBufAddRefTypeId(pReply, class_id);
Elliott Hughes436e3722012-02-17 20:01:47 -08001097 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001098}
1099
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -08001100void Dbg::GetClassList(std::vector<JDWP::RefTypeId>& classes) {
Elliott Hughesa2155262011-11-16 16:26:58 -08001101 // Get the complete list of reference classes (i.e. all classes except
1102 // the primitive types).
1103 // Returns a newly-allocated buffer full of RefTypeId values.
1104 struct ClassListCreator {
Elliott Hughesba8eee12012-01-24 20:25:24 -08001105 explicit ClassListCreator(std::vector<JDWP::RefTypeId>& classes) : classes(classes) {
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -08001106 }
1107
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001108 static bool Visit(mirror::Class* c, void* arg) {
Elliott Hughesa2155262011-11-16 16:26:58 -08001109 return reinterpret_cast<ClassListCreator*>(arg)->Visit(c);
1110 }
1111
Elliott Hughes64f574f2013-02-20 14:57:12 -08001112 // TODO: Enable annotalysis. We know lock is held in constructor, but abstraction confuses
1113 // annotalysis.
1114 bool Visit(mirror::Class* c) NO_THREAD_SAFETY_ANALYSIS {
Elliott Hughesa2155262011-11-16 16:26:58 -08001115 if (!c->IsPrimitive()) {
Elliott Hughes64f574f2013-02-20 14:57:12 -08001116 classes.push_back(gRegistry->AddRefType(c));
Elliott Hughesa2155262011-11-16 16:26:58 -08001117 }
1118 return true;
1119 }
1120
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -08001121 std::vector<JDWP::RefTypeId>& classes;
Elliott Hughesa2155262011-11-16 16:26:58 -08001122 };
1123
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -08001124 ClassListCreator clc(classes);
Elliott Hughesa2155262011-11-16 16:26:58 -08001125 Runtime::Current()->GetClassLinker()->VisitClasses(ClassListCreator::Visit, &clc);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001126}
1127
Elliott Hughes88d63092013-01-09 09:55:54 -08001128JDWP::JdwpError Dbg::GetClassInfo(JDWP::RefTypeId class_id, JDWP::JdwpTypeTag* pTypeTag, uint32_t* pStatus, std::string* pDescriptor) {
Elliott Hughes436e3722012-02-17 20:01:47 -08001129 JDWP::JdwpError status;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001130 mirror::Class* c = DecodeClass(class_id, status);
Elliott Hughes436e3722012-02-17 20:01:47 -08001131 if (c == NULL) {
1132 return status;
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -08001133 }
1134
Elliott Hughesa2155262011-11-16 16:26:58 -08001135 if (c->IsArrayClass()) {
1136 *pStatus = JDWP::CS_VERIFIED | JDWP::CS_PREPARED;
1137 *pTypeTag = JDWP::TT_ARRAY;
1138 } else {
1139 if (c->IsErroneous()) {
1140 *pStatus = JDWP::CS_ERROR;
1141 } else {
1142 *pStatus = JDWP::CS_VERIFIED | JDWP::CS_PREPARED | JDWP::CS_INITIALIZED;
1143 }
1144 *pTypeTag = c->IsInterface() ? JDWP::TT_INTERFACE : JDWP::TT_CLASS;
1145 }
1146
1147 if (pDescriptor != NULL) {
Mathieu Chartierf8322842014-05-16 10:59:25 -07001148 *pDescriptor = c->GetDescriptor();
Elliott Hughesa2155262011-11-16 16:26:58 -08001149 }
Elliott Hughes436e3722012-02-17 20:01:47 -08001150 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001151}
1152
Elliott Hughesc3b77c72011-12-15 20:56:48 -08001153void Dbg::FindLoadedClassBySignature(const char* descriptor, std::vector<JDWP::RefTypeId>& ids) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001154 std::vector<mirror::Class*> classes;
Elliott Hughes6fa602d2011-12-02 17:54:25 -08001155 Runtime::Current()->GetClassLinker()->LookupClasses(descriptor, classes);
1156 ids.clear();
1157 for (size_t i = 0; i < classes.size(); ++i) {
1158 ids.push_back(gRegistry->Add(classes[i]));
1159 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001160}
1161
Elliott Hughes64f574f2013-02-20 14:57:12 -08001162JDWP::JdwpError Dbg::GetReferenceType(JDWP::ObjectId object_id, JDWP::ExpandBuf* pReply)
1163 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001164 mirror::Object* o = gRegistry->Get<mirror::Object*>(object_id);
Elliott Hughes64f574f2013-02-20 14:57:12 -08001165 if (o == NULL || o == ObjectRegistry::kInvalidObject) {
Elliott Hughes2435a572012-02-17 16:07:41 -08001166 return JDWP::ERR_INVALID_OBJECT;
Elliott Hughes499c5132011-11-17 14:55:11 -08001167 }
Elliott Hughes2435a572012-02-17 16:07:41 -08001168
Sebastien Hertz4d8fd492014-03-28 16:29:41 +01001169 JDWP::JdwpTypeTag type_tag = GetTypeTag(o->GetClass());
Elliott Hughes64f574f2013-02-20 14:57:12 -08001170 JDWP::RefTypeId type_id = gRegistry->AddRefType(o->GetClass());
Elliott Hughes2435a572012-02-17 16:07:41 -08001171
1172 expandBufAdd1(pReply, type_tag);
1173 expandBufAddRefTypeId(pReply, type_id);
1174
1175 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001176}
1177
Ian Rogersfc0e94b2013-09-23 23:51:32 -07001178JDWP::JdwpError Dbg::GetSignature(JDWP::RefTypeId class_id, std::string* signature) {
Elliott Hughes1fe7afb2012-02-13 17:23:03 -08001179 JDWP::JdwpError status;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001180 mirror::Class* c = DecodeClass(class_id, status);
Elliott Hughes1fe7afb2012-02-13 17:23:03 -08001181 if (c == NULL) {
1182 return status;
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -08001183 }
Mathieu Chartierf8322842014-05-16 10:59:25 -07001184 *signature = c->GetDescriptor();
Elliott Hughes1fe7afb2012-02-13 17:23:03 -08001185 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001186}
1187
Elliott Hughes88d63092013-01-09 09:55:54 -08001188JDWP::JdwpError Dbg::GetSourceFile(JDWP::RefTypeId class_id, std::string& result) {
Elliott Hughes436e3722012-02-17 20:01:47 -08001189 JDWP::JdwpError status;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001190 mirror::Class* c = DecodeClass(class_id, status);
Sebastien Hertz4206eb52014-06-05 10:15:45 +02001191 if (c == nullptr) {
Elliott Hughes436e3722012-02-17 20:01:47 -08001192 return status;
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -08001193 }
Sebastien Hertz4206eb52014-06-05 10:15:45 +02001194 const char* source_file = c->GetSourceFile();
1195 if (source_file == nullptr) {
Sebastien Hertzb7054ba2014-03-13 11:52:31 +01001196 return JDWP::ERR_ABSENT_INFORMATION;
1197 }
Sebastien Hertz4206eb52014-06-05 10:15:45 +02001198 result = source_file;
Elliott Hughes436e3722012-02-17 20:01:47 -08001199 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001200}
1201
Elliott Hughes88d63092013-01-09 09:55:54 -08001202JDWP::JdwpError Dbg::GetObjectTag(JDWP::ObjectId object_id, uint8_t& tag) {
Ian Rogers98379392014-02-24 16:53:16 -08001203 ScopedObjectAccessUnchecked soa(Thread::Current());
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001204 mirror::Object* o = gRegistry->Get<mirror::Object*>(object_id);
Elliott Hughes64f574f2013-02-20 14:57:12 -08001205 if (o == ObjectRegistry::kInvalidObject) {
Elliott Hughes546b9862012-06-20 16:06:13 -07001206 return JDWP::ERR_INVALID_OBJECT;
1207 }
Ian Rogers98379392014-02-24 16:53:16 -08001208 tag = TagFromObject(soa, o);
Elliott Hughes546b9862012-06-20 16:06:13 -07001209 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001210}
1211
Elliott Hughesaed4be92011-12-02 16:16:23 -08001212size_t Dbg::GetTagWidth(JDWP::JdwpTag tag) {
Elliott Hughesdbb40792011-11-18 17:05:22 -08001213 switch (tag) {
1214 case JDWP::JT_VOID:
1215 return 0;
1216 case JDWP::JT_BYTE:
1217 case JDWP::JT_BOOLEAN:
1218 return 1;
1219 case JDWP::JT_CHAR:
1220 case JDWP::JT_SHORT:
1221 return 2;
1222 case JDWP::JT_FLOAT:
1223 case JDWP::JT_INT:
1224 return 4;
1225 case JDWP::JT_ARRAY:
1226 case JDWP::JT_OBJECT:
1227 case JDWP::JT_STRING:
1228 case JDWP::JT_THREAD:
1229 case JDWP::JT_THREAD_GROUP:
1230 case JDWP::JT_CLASS_LOADER:
1231 case JDWP::JT_CLASS_OBJECT:
1232 return sizeof(JDWP::ObjectId);
1233 case JDWP::JT_DOUBLE:
1234 case JDWP::JT_LONG:
1235 return 8;
1236 default:
Elliott Hughes3d30d9b2011-12-07 17:35:48 -08001237 LOG(FATAL) << "Unknown tag " << tag;
Elliott Hughesdbb40792011-11-18 17:05:22 -08001238 return -1;
1239 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001240}
1241
Elliott Hughes88d63092013-01-09 09:55:54 -08001242JDWP::JdwpError Dbg::GetArrayLength(JDWP::ObjectId array_id, int& length) {
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -08001243 JDWP::JdwpError status;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001244 mirror::Array* a = DecodeArray(array_id, status);
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -08001245 if (a == NULL) {
1246 return status;
Elliott Hughes24437992011-11-30 14:49:33 -08001247 }
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -08001248 length = a->GetLength();
1249 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001250}
1251
Elliott Hughes88d63092013-01-09 09:55:54 -08001252JDWP::JdwpError Dbg::OutputArray(JDWP::ObjectId array_id, int offset, int count, JDWP::ExpandBuf* pReply) {
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -08001253 JDWP::JdwpError status;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001254 mirror::Array* a = DecodeArray(array_id, status);
Ian Rogers98379392014-02-24 16:53:16 -08001255 if (a == nullptr) {
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -08001256 return status;
1257 }
Elliott Hughes24437992011-11-30 14:49:33 -08001258
1259 if (offset < 0 || count < 0 || offset > a->GetLength() || a->GetLength() - offset < count) {
1260 LOG(WARNING) << __FUNCTION__ << " access out of bounds: offset=" << offset << "; count=" << count;
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -08001261 return JDWP::ERR_INVALID_LENGTH;
Elliott Hughes24437992011-11-30 14:49:33 -08001262 }
Mathieu Chartierf8322842014-05-16 10:59:25 -07001263 std::string descriptor(a->GetClass()->GetDescriptor());
Elliott Hughes24437992011-11-30 14:49:33 -08001264 JDWP::JdwpTag tag = BasicTagFromDescriptor(descriptor.c_str() + 1);
1265
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -08001266 expandBufAdd1(pReply, tag);
1267 expandBufAdd4BE(pReply, count);
1268
Elliott Hughes24437992011-11-30 14:49:33 -08001269 if (IsPrimitiveTag(tag)) {
1270 size_t width = GetTagWidth(tag);
Elliott Hughes24437992011-11-30 14:49:33 -08001271 uint8_t* dst = expandBufAddSpace(pReply, count * width);
1272 if (width == 8) {
Ian Rogersef7d42f2014-01-06 12:55:46 -08001273 const uint64_t* src8 = reinterpret_cast<uint64_t*>(a->GetRawData(sizeof(uint64_t), 0));
Elliott Hughes24437992011-11-30 14:49:33 -08001274 for (int i = 0; i < count; ++i) JDWP::Write8BE(&dst, src8[offset + i]);
1275 } else if (width == 4) {
Ian Rogersef7d42f2014-01-06 12:55:46 -08001276 const uint32_t* src4 = reinterpret_cast<uint32_t*>(a->GetRawData(sizeof(uint32_t), 0));
Elliott Hughes24437992011-11-30 14:49:33 -08001277 for (int i = 0; i < count; ++i) JDWP::Write4BE(&dst, src4[offset + i]);
1278 } else if (width == 2) {
Ian Rogersef7d42f2014-01-06 12:55:46 -08001279 const uint16_t* src2 = reinterpret_cast<uint16_t*>(a->GetRawData(sizeof(uint16_t), 0));
Elliott Hughes24437992011-11-30 14:49:33 -08001280 for (int i = 0; i < count; ++i) JDWP::Write2BE(&dst, src2[offset + i]);
1281 } else {
Ian Rogersef7d42f2014-01-06 12:55:46 -08001282 const uint8_t* src = reinterpret_cast<uint8_t*>(a->GetRawData(sizeof(uint8_t), 0));
Elliott Hughes24437992011-11-30 14:49:33 -08001283 memcpy(dst, &src[offset * width], count * width);
1284 }
1285 } else {
Ian Rogers98379392014-02-24 16:53:16 -08001286 ScopedObjectAccessUnchecked soa(Thread::Current());
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001287 mirror::ObjectArray<mirror::Object>* oa = a->AsObjectArray<mirror::Object>();
Elliott Hughes24437992011-11-30 14:49:33 -08001288 for (int i = 0; i < count; ++i) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001289 mirror::Object* element = oa->Get(offset + i);
Ian Rogers98379392014-02-24 16:53:16 -08001290 JDWP::JdwpTag specific_tag = (element != nullptr) ? TagFromObject(soa, element)
1291 : tag;
Elliott Hughes24437992011-11-30 14:49:33 -08001292 expandBufAdd1(pReply, specific_tag);
1293 expandBufAddObjectId(pReply, gRegistry->Add(element));
1294 }
1295 }
1296
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -08001297 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001298}
1299
Ian Rogersef7d42f2014-01-06 12:55:46 -08001300template <typename T>
1301static void CopyArrayData(mirror::Array* a, JDWP::Request& src, int offset, int count)
1302 NO_THREAD_SAFETY_ANALYSIS {
1303 // TODO: fix when annotalysis correctly handles non-member functions.
Elliott Hughes4b9702c2013-02-20 18:13:24 -08001304 DCHECK(a->GetClass()->IsPrimitiveArray());
1305
Ian Rogersef7d42f2014-01-06 12:55:46 -08001306 T* dst = reinterpret_cast<T*>(a->GetRawData(sizeof(T), offset));
Elliott Hughes4b9702c2013-02-20 18:13:24 -08001307 for (int i = 0; i < count; ++i) {
1308 *dst++ = src.ReadValue(sizeof(T));
1309 }
1310}
1311
Elliott Hughes88d63092013-01-09 09:55:54 -08001312JDWP::JdwpError Dbg::SetArrayElements(JDWP::ObjectId array_id, int offset, int count,
Elliott Hughes4b9702c2013-02-20 18:13:24 -08001313 JDWP::Request& request)
Ian Rogersb726dcb2012-09-05 08:57:23 -07001314 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -08001315 JDWP::JdwpError status;
Elliott Hughes4b9702c2013-02-20 18:13:24 -08001316 mirror::Array* dst = DecodeArray(array_id, status);
1317 if (dst == NULL) {
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -08001318 return status;
1319 }
Elliott Hughesf03b8f62011-12-02 14:26:25 -08001320
Elliott Hughes4b9702c2013-02-20 18:13:24 -08001321 if (offset < 0 || count < 0 || offset > dst->GetLength() || dst->GetLength() - offset < count) {
Elliott Hughesf03b8f62011-12-02 14:26:25 -08001322 LOG(WARNING) << __FUNCTION__ << " access out of bounds: offset=" << offset << "; count=" << count;
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -08001323 return JDWP::ERR_INVALID_LENGTH;
Elliott Hughesf03b8f62011-12-02 14:26:25 -08001324 }
Mathieu Chartierf8322842014-05-16 10:59:25 -07001325 std::string descriptor = dst->GetClass()->GetDescriptor();
1326 JDWP::JdwpTag tag = BasicTagFromDescriptor(descriptor.c_str() + 1);
Elliott Hughesf03b8f62011-12-02 14:26:25 -08001327
1328 if (IsPrimitiveTag(tag)) {
1329 size_t width = GetTagWidth(tag);
Elliott Hughesf03b8f62011-12-02 14:26:25 -08001330 if (width == 8) {
Elliott Hughes4b9702c2013-02-20 18:13:24 -08001331 CopyArrayData<uint64_t>(dst, request, offset, count);
Elliott Hughesf03b8f62011-12-02 14:26:25 -08001332 } else if (width == 4) {
Elliott Hughes4b9702c2013-02-20 18:13:24 -08001333 CopyArrayData<uint32_t>(dst, request, offset, count);
Elliott Hughesf03b8f62011-12-02 14:26:25 -08001334 } else if (width == 2) {
Elliott Hughes4b9702c2013-02-20 18:13:24 -08001335 CopyArrayData<uint16_t>(dst, request, offset, count);
Elliott Hughesf03b8f62011-12-02 14:26:25 -08001336 } else {
Elliott Hughes4b9702c2013-02-20 18:13:24 -08001337 CopyArrayData<uint8_t>(dst, request, offset, count);
Elliott Hughesf03b8f62011-12-02 14:26:25 -08001338 }
1339 } else {
Elliott Hughes4b9702c2013-02-20 18:13:24 -08001340 mirror::ObjectArray<mirror::Object>* oa = dst->AsObjectArray<mirror::Object>();
Elliott Hughesf03b8f62011-12-02 14:26:25 -08001341 for (int i = 0; i < count; ++i) {
Elliott Hughes4b9702c2013-02-20 18:13:24 -08001342 JDWP::ObjectId id = request.ReadObjectId();
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001343 mirror::Object* o = gRegistry->Get<mirror::Object*>(id);
Elliott Hughes64f574f2013-02-20 14:57:12 -08001344 if (o == ObjectRegistry::kInvalidObject) {
Elliott Hughes436e3722012-02-17 20:01:47 -08001345 return JDWP::ERR_INVALID_OBJECT;
1346 }
Sebastien Hertzd2fe10a2014-01-15 10:20:56 +01001347 oa->Set<false>(offset + i, o);
Elliott Hughesf03b8f62011-12-02 14:26:25 -08001348 }
1349 }
1350
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -08001351 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001352}
1353
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -08001354JDWP::ObjectId Dbg::CreateString(const std::string& str) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001355 return gRegistry->Add(mirror::String::AllocFromModifiedUtf8(Thread::Current(), str.c_str()));
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001356}
1357
Elliott Hughes88d63092013-01-09 09:55:54 -08001358JDWP::JdwpError Dbg::CreateObject(JDWP::RefTypeId class_id, JDWP::ObjectId& new_object) {
Elliott Hughes436e3722012-02-17 20:01:47 -08001359 JDWP::JdwpError status;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001360 mirror::Class* c = DecodeClass(class_id, status);
Elliott Hughes436e3722012-02-17 20:01:47 -08001361 if (c == NULL) {
1362 return status;
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -08001363 }
Ian Rogers50b35e22012-10-04 10:09:15 -07001364 new_object = gRegistry->Add(c->AllocObject(Thread::Current()));
Elliott Hughes436e3722012-02-17 20:01:47 -08001365 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001366}
1367
Elliott Hughesbf13d362011-12-08 15:51:37 -08001368/*
1369 * Used by Eclipse's "Display" view to evaluate "new byte[5]" to get "(byte[]) [0, 0, 0, 0, 0]".
1370 */
Elliott Hughes88d63092013-01-09 09:55:54 -08001371JDWP::JdwpError Dbg::CreateArrayObject(JDWP::RefTypeId array_class_id, uint32_t length,
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001372 JDWP::ObjectId& new_array) {
Elliott Hughes436e3722012-02-17 20:01:47 -08001373 JDWP::JdwpError status;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001374 mirror::Class* c = DecodeClass(array_class_id, status);
Elliott Hughes436e3722012-02-17 20:01:47 -08001375 if (c == NULL) {
1376 return status;
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -08001377 }
Ian Rogers6fac4472014-02-25 17:01:10 -08001378 new_array = gRegistry->Add(mirror::Array::Alloc<true>(Thread::Current(), c, length,
1379 c->GetComponentSize(),
1380 Runtime::Current()->GetHeap()->GetCurrentAllocator()));
Elliott Hughes436e3722012-02-17 20:01:47 -08001381 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001382}
1383
Elliott Hughes88d63092013-01-09 09:55:54 -08001384bool Dbg::MatchType(JDWP::RefTypeId instance_class_id, JDWP::RefTypeId class_id) {
Elliott Hughes436e3722012-02-17 20:01:47 -08001385 JDWP::JdwpError status;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001386 mirror::Class* c1 = DecodeClass(instance_class_id, status);
Elliott Hughesa656a0f2012-02-21 18:03:44 -08001387 CHECK(c1 != NULL);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001388 mirror::Class* c2 = DecodeClass(class_id, status);
Elliott Hughesa656a0f2012-02-21 18:03:44 -08001389 CHECK(c2 != NULL);
Sebastien Hertz123756a2013-11-27 15:49:42 +01001390 return c2->IsAssignableFrom(c1);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001391}
1392
Brian Carlstromea46f952013-07-30 01:26:50 -07001393static JDWP::FieldId ToFieldId(const mirror::ArtField* f)
Ian Rogersb726dcb2012-09-05 08:57:23 -07001394 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Mathieu Chartier590fee92013-09-13 13:46:47 -07001395 CHECK(!kMovingFields);
Elliott Hughes03181a82011-11-17 17:22:21 -08001396 return static_cast<JDWP::FieldId>(reinterpret_cast<uintptr_t>(f));
Elliott Hughes03181a82011-11-17 17:22:21 -08001397}
1398
Brian Carlstromea46f952013-07-30 01:26:50 -07001399static JDWP::MethodId ToMethodId(const mirror::ArtMethod* m)
Ian Rogersb726dcb2012-09-05 08:57:23 -07001400 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Mathieu Chartier590fee92013-09-13 13:46:47 -07001401 CHECK(!kMovingMethods);
Elliott Hughes03181a82011-11-17 17:22:21 -08001402 return static_cast<JDWP::MethodId>(reinterpret_cast<uintptr_t>(m));
Elliott Hughes03181a82011-11-17 17:22:21 -08001403}
1404
Brian Carlstromea46f952013-07-30 01:26:50 -07001405static mirror::ArtField* FromFieldId(JDWP::FieldId fid)
Ian Rogersb726dcb2012-09-05 08:57:23 -07001406 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Mathieu Chartier590fee92013-09-13 13:46:47 -07001407 CHECK(!kMovingFields);
Brian Carlstromea46f952013-07-30 01:26:50 -07001408 return reinterpret_cast<mirror::ArtField*>(static_cast<uintptr_t>(fid));
Elliott Hughesaed4be92011-12-02 16:16:23 -08001409}
1410
Brian Carlstromea46f952013-07-30 01:26:50 -07001411static mirror::ArtMethod* FromMethodId(JDWP::MethodId mid)
Ian Rogersb726dcb2012-09-05 08:57:23 -07001412 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Mathieu Chartier590fee92013-09-13 13:46:47 -07001413 CHECK(!kMovingMethods);
Brian Carlstromea46f952013-07-30 01:26:50 -07001414 return reinterpret_cast<mirror::ArtMethod*>(static_cast<uintptr_t>(mid));
Elliott Hughes03181a82011-11-17 17:22:21 -08001415}
1416
Brian Carlstromea46f952013-07-30 01:26:50 -07001417static void SetLocation(JDWP::JdwpLocation& location, mirror::ArtMethod* m, uint32_t dex_pc)
Ian Rogersb726dcb2012-09-05 08:57:23 -07001418 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08001419 if (m == NULL) {
1420 memset(&location, 0, sizeof(location));
1421 } else {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001422 mirror::Class* c = m->GetDeclaringClass();
Sebastien Hertz4d8fd492014-03-28 16:29:41 +01001423 location.type_tag = GetTypeTag(c);
Sebastien Hertzcb19ebf2014-03-11 15:26:35 +01001424 location.class_id = gRegistry->AddRefType(c);
Elliott Hughes74847412012-06-20 18:10:21 -07001425 location.method_id = ToMethodId(m);
Sebastien Hertzcb19ebf2014-03-11 15:26:35 +01001426 location.dex_pc = (m->IsNative() || m->IsProxyMethod()) ? static_cast<uint64_t>(-1) : dex_pc;
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08001427 }
Elliott Hughesd07986f2011-12-06 18:27:45 -08001428}
1429
Elliott Hughesa96836a2013-01-17 12:27:49 -08001430std::string Dbg::GetMethodName(JDWP::MethodId method_id)
Ian Rogersb726dcb2012-09-05 08:57:23 -07001431 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Brian Carlstromea46f952013-07-30 01:26:50 -07001432 mirror::ArtMethod* m = FromMethodId(method_id);
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07001433 return m->GetName();
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001434}
1435
Elliott Hughesa96836a2013-01-17 12:27:49 -08001436std::string Dbg::GetFieldName(JDWP::FieldId field_id)
1437 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Mathieu Chartier61c5ebc2014-06-05 17:42:53 -07001438 return FromFieldId(field_id)->GetName();
Elliott Hughesa96836a2013-01-17 12:27:49 -08001439}
1440
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001441/*
1442 * Augment the access flags for synthetic methods and fields by setting
1443 * the (as described by the spec) "0xf0000000 bit". Also, strip out any
1444 * flags not specified by the Java programming language.
1445 */
1446static uint32_t MangleAccessFlags(uint32_t accessFlags) {
1447 accessFlags &= kAccJavaFlagsMask;
1448 if ((accessFlags & kAccSynthetic) != 0) {
1449 accessFlags |= 0xf0000000;
1450 }
1451 return accessFlags;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001452}
1453
Elliott Hughesdbb40792011-11-18 17:05:22 -08001454/*
Jeff Haob7cefc72013-11-14 14:51:09 -08001455 * Circularly shifts registers so that arguments come first. Debuggers
1456 * expect slots to begin with arguments, but dex code places them at
1457 * the end.
Elliott Hughesdbb40792011-11-18 17:05:22 -08001458 */
Jeff Haob7cefc72013-11-14 14:51:09 -08001459static uint16_t MangleSlot(uint16_t slot, mirror::ArtMethod* m)
1460 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07001461 const DexFile::CodeItem* code_item = m->GetCodeItem();
Sebastien Hertzcb19ebf2014-03-11 15:26:35 +01001462 if (code_item == nullptr) {
1463 // We should not get here for a method without code (native, proxy or abstract). Log it and
1464 // return the slot as is since all registers are arguments.
1465 LOG(WARNING) << "Trying to mangle slot for method without code " << PrettyMethod(m);
1466 return slot;
1467 }
Jeff Haob7cefc72013-11-14 14:51:09 -08001468 uint16_t ins_size = code_item->ins_size_;
1469 uint16_t locals_size = code_item->registers_size_ - ins_size;
1470 if (slot >= locals_size) {
1471 return slot - locals_size;
1472 } else {
1473 return slot + ins_size;
Elliott Hughesdbb40792011-11-18 17:05:22 -08001474 }
Elliott Hughesdbb40792011-11-18 17:05:22 -08001475}
1476
Jeff Haob7cefc72013-11-14 14:51:09 -08001477/*
1478 * Circularly shifts registers so that arguments come last. Reverts
1479 * slots to dex style argument placement.
1480 */
Brian Carlstromea46f952013-07-30 01:26:50 -07001481static uint16_t DemangleSlot(uint16_t slot, mirror::ArtMethod* m)
Ian Rogersb726dcb2012-09-05 08:57:23 -07001482 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07001483 const DexFile::CodeItem* code_item = m->GetCodeItem();
Sebastien Hertzcb19ebf2014-03-11 15:26:35 +01001484 if (code_item == nullptr) {
1485 // We should not get here for a method without code (native, proxy or abstract). Log it and
1486 // return the slot as is since all registers are arguments.
1487 LOG(WARNING) << "Trying to demangle slot for method without code " << PrettyMethod(m);
1488 return slot;
1489 }
Jeff Haob7cefc72013-11-14 14:51:09 -08001490 uint16_t ins_size = code_item->ins_size_;
1491 uint16_t locals_size = code_item->registers_size_ - ins_size;
1492 if (slot < ins_size) {
1493 return slot + locals_size;
1494 } else {
1495 return slot - ins_size;
Elliott Hughesdbb40792011-11-18 17:05:22 -08001496 }
Elliott Hughesdbb40792011-11-18 17:05:22 -08001497}
1498
Elliott Hughes88d63092013-01-09 09:55:54 -08001499JDWP::JdwpError Dbg::OutputDeclaredFields(JDWP::RefTypeId class_id, bool with_generic, JDWP::ExpandBuf* pReply) {
Elliott Hughes436e3722012-02-17 20:01:47 -08001500 JDWP::JdwpError status;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001501 mirror::Class* c = DecodeClass(class_id, status);
Elliott Hughes436e3722012-02-17 20:01:47 -08001502 if (c == NULL) {
1503 return status;
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -08001504 }
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001505
1506 size_t instance_field_count = c->NumInstanceFields();
1507 size_t static_field_count = c->NumStaticFields();
1508
1509 expandBufAdd4BE(pReply, instance_field_count + static_field_count);
1510
1511 for (size_t i = 0; i < instance_field_count + static_field_count; ++i) {
Brian Carlstromea46f952013-07-30 01:26:50 -07001512 mirror::ArtField* f = (i < instance_field_count) ? c->GetInstanceField(i) : c->GetStaticField(i - instance_field_count);
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001513 expandBufAddFieldId(pReply, ToFieldId(f));
Mathieu Chartier61c5ebc2014-06-05 17:42:53 -07001514 expandBufAddUtf8String(pReply, f->GetName());
1515 expandBufAddUtf8String(pReply, f->GetTypeDescriptor());
Elliott Hughesc5b734a2011-12-01 17:20:58 -08001516 if (with_generic) {
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001517 static const char genericSignature[1] = "";
1518 expandBufAddUtf8String(pReply, genericSignature);
1519 }
1520 expandBufAdd4BE(pReply, MangleAccessFlags(f->GetAccessFlags()));
1521 }
Elliott Hughes436e3722012-02-17 20:01:47 -08001522 return JDWP::ERR_NONE;
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001523}
1524
Elliott Hughes88d63092013-01-09 09:55:54 -08001525JDWP::JdwpError Dbg::OutputDeclaredMethods(JDWP::RefTypeId class_id, bool with_generic,
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001526 JDWP::ExpandBuf* pReply) {
Elliott Hughes436e3722012-02-17 20:01:47 -08001527 JDWP::JdwpError status;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001528 mirror::Class* c = DecodeClass(class_id, status);
Elliott Hughes436e3722012-02-17 20:01:47 -08001529 if (c == NULL) {
1530 return status;
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -08001531 }
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001532
1533 size_t direct_method_count = c->NumDirectMethods();
1534 size_t virtual_method_count = c->NumVirtualMethods();
1535
1536 expandBufAdd4BE(pReply, direct_method_count + virtual_method_count);
1537
1538 for (size_t i = 0; i < direct_method_count + virtual_method_count; ++i) {
Brian Carlstromea46f952013-07-30 01:26:50 -07001539 mirror::ArtMethod* m = (i < direct_method_count) ? c->GetDirectMethod(i) : c->GetVirtualMethod(i - direct_method_count);
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001540 expandBufAddMethodId(pReply, ToMethodId(m));
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07001541 expandBufAddUtf8String(pReply, m->GetName());
1542 expandBufAddUtf8String(pReply, m->GetSignature().ToString());
Elliott Hughesc5b734a2011-12-01 17:20:58 -08001543 if (with_generic) {
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001544 static const char genericSignature[1] = "";
1545 expandBufAddUtf8String(pReply, genericSignature);
1546 }
1547 expandBufAdd4BE(pReply, MangleAccessFlags(m->GetAccessFlags()));
1548 }
Elliott Hughes436e3722012-02-17 20:01:47 -08001549 return JDWP::ERR_NONE;
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001550}
1551
Elliott Hughes88d63092013-01-09 09:55:54 -08001552JDWP::JdwpError Dbg::OutputDeclaredInterfaces(JDWP::RefTypeId class_id, JDWP::ExpandBuf* pReply) {
Elliott Hughes436e3722012-02-17 20:01:47 -08001553 JDWP::JdwpError status;
Mathieu Chartierf8322842014-05-16 10:59:25 -07001554 Thread* self = Thread::Current();
1555 StackHandleScope<1> hs(self);
1556 Handle<mirror::Class> c(hs.NewHandle(DecodeClass(class_id, status)));
1557 if (c.Get() == nullptr) {
Elliott Hughes436e3722012-02-17 20:01:47 -08001558 return status;
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -08001559 }
Mathieu Chartierf8322842014-05-16 10:59:25 -07001560 size_t interface_count = c->NumDirectInterfaces();
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001561 expandBufAdd4BE(pReply, interface_count);
1562 for (size_t i = 0; i < interface_count; ++i) {
Mathieu Chartierf8322842014-05-16 10:59:25 -07001563 expandBufAddRefTypeId(pReply,
1564 gRegistry->AddRefType(mirror::Class::GetDirectInterface(self, c, i)));
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001565 }
Elliott Hughes436e3722012-02-17 20:01:47 -08001566 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001567}
1568
Elliott Hughes88d63092013-01-09 09:55:54 -08001569void Dbg::OutputLineTable(JDWP::RefTypeId, JDWP::MethodId method_id, JDWP::ExpandBuf* pReply)
Ian Rogersb726dcb2012-09-05 08:57:23 -07001570 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Elliott Hughes03181a82011-11-17 17:22:21 -08001571 struct DebugCallbackContext {
1572 int numItems;
1573 JDWP::ExpandBuf* pReply;
1574
Elliott Hughes2435a572012-02-17 16:07:41 -08001575 static bool Callback(void* context, uint32_t address, uint32_t line_number) {
Elliott Hughes03181a82011-11-17 17:22:21 -08001576 DebugCallbackContext* pContext = reinterpret_cast<DebugCallbackContext*>(context);
1577 expandBufAdd8BE(pContext->pReply, address);
Elliott Hughes2435a572012-02-17 16:07:41 -08001578 expandBufAdd4BE(pContext->pReply, line_number);
Elliott Hughes03181a82011-11-17 17:22:21 -08001579 pContext->numItems++;
Sebastien Hertzf2910ee2013-10-19 16:39:24 +02001580 return false;
Elliott Hughes03181a82011-11-17 17:22:21 -08001581 }
1582 };
Brian Carlstromea46f952013-07-30 01:26:50 -07001583 mirror::ArtMethod* m = FromMethodId(method_id);
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07001584 const DexFile::CodeItem* code_item = m->GetCodeItem();
Elliott Hughes03181a82011-11-17 17:22:21 -08001585 uint64_t start, end;
Sebastien Hertzcb19ebf2014-03-11 15:26:35 +01001586 if (code_item == nullptr) {
1587 DCHECK(m->IsNative() || m->IsProxyMethod());
Elliott Hughes03181a82011-11-17 17:22:21 -08001588 start = -1;
1589 end = -1;
1590 } else {
1591 start = 0;
jeffhao14f0db92012-12-14 17:50:42 -08001592 // Return the index of the last instruction
Sebastien Hertzcb19ebf2014-03-11 15:26:35 +01001593 end = code_item->insns_size_in_code_units_ - 1;
Elliott Hughes03181a82011-11-17 17:22:21 -08001594 }
1595
1596 expandBufAdd8BE(pReply, start);
1597 expandBufAdd8BE(pReply, end);
1598
1599 // Add numLines later
1600 size_t numLinesOffset = expandBufGetLength(pReply);
1601 expandBufAdd4BE(pReply, 0);
1602
1603 DebugCallbackContext context;
1604 context.numItems = 0;
1605 context.pReply = pReply;
1606
Sebastien Hertzcb19ebf2014-03-11 15:26:35 +01001607 if (code_item != nullptr) {
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07001608 m->GetDexFile()->DecodeDebugInfo(code_item, m->IsStatic(), m->GetDexMethodIndex(),
1609 DebugCallbackContext::Callback, NULL, &context);
Sebastien Hertzcb19ebf2014-03-11 15:26:35 +01001610 }
Elliott Hughes03181a82011-11-17 17:22:21 -08001611
1612 JDWP::Set4BE(expandBufGetBuffer(pReply) + numLinesOffset, context.numItems);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001613}
1614
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07001615void Dbg::OutputVariableTable(JDWP::RefTypeId, JDWP::MethodId method_id, bool with_generic,
1616 JDWP::ExpandBuf* pReply) {
Elliott Hughesdbb40792011-11-18 17:05:22 -08001617 struct DebugCallbackContext {
Jeff Haob7cefc72013-11-14 14:51:09 -08001618 mirror::ArtMethod* method;
Elliott Hughesdbb40792011-11-18 17:05:22 -08001619 JDWP::ExpandBuf* pReply;
Elliott Hughesc5b734a2011-12-01 17:20:58 -08001620 size_t variable_count;
1621 bool with_generic;
Elliott Hughesdbb40792011-11-18 17:05:22 -08001622
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07001623 static void Callback(void* context, uint16_t slot, uint32_t startAddress, uint32_t endAddress,
1624 const char* name, const char* descriptor, const char* signature)
Jeff Haob7cefc72013-11-14 14:51:09 -08001625 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Elliott Hughesdbb40792011-11-18 17:05:22 -08001626 DebugCallbackContext* pContext = reinterpret_cast<DebugCallbackContext*>(context);
1627
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07001628 VLOG(jdwp) << StringPrintf(" %2zd: %d(%d) '%s' '%s' '%s' actual slot=%d mangled slot=%d",
1629 pContext->variable_count, startAddress, endAddress - startAddress,
1630 name, descriptor, signature, slot,
1631 MangleSlot(slot, pContext->method));
Elliott Hughesdbb40792011-11-18 17:05:22 -08001632
Jeff Haob7cefc72013-11-14 14:51:09 -08001633 slot = MangleSlot(slot, pContext->method);
Elliott Hughes68fdbd02011-11-29 19:22:47 -08001634
Elliott Hughesdbb40792011-11-18 17:05:22 -08001635 expandBufAdd8BE(pContext->pReply, startAddress);
1636 expandBufAddUtf8String(pContext->pReply, name);
1637 expandBufAddUtf8String(pContext->pReply, descriptor);
Elliott Hughesc5b734a2011-12-01 17:20:58 -08001638 if (pContext->with_generic) {
Elliott Hughesdbb40792011-11-18 17:05:22 -08001639 expandBufAddUtf8String(pContext->pReply, signature);
1640 }
1641 expandBufAdd4BE(pContext->pReply, endAddress - startAddress);
1642 expandBufAdd4BE(pContext->pReply, slot);
1643
Elliott Hughesc5b734a2011-12-01 17:20:58 -08001644 ++pContext->variable_count;
Elliott Hughesdbb40792011-11-18 17:05:22 -08001645 }
1646 };
Brian Carlstromea46f952013-07-30 01:26:50 -07001647 mirror::ArtMethod* m = FromMethodId(method_id);
Elliott Hughesdbb40792011-11-18 17:05:22 -08001648
Elliott Hughesc5b734a2011-12-01 17:20:58 -08001649 // arg_count considers doubles and longs to take 2 units.
1650 // variable_count considers everything to take 1 unit.
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07001651 std::string shorty(m->GetShorty());
Brian Carlstromea46f952013-07-30 01:26:50 -07001652 expandBufAdd4BE(pReply, mirror::ArtMethod::NumArgRegisters(shorty));
Elliott Hughesdbb40792011-11-18 17:05:22 -08001653
Elliott Hughesc5b734a2011-12-01 17:20:58 -08001654 // We don't know the total number of variables yet, so leave a blank and update it later.
1655 size_t variable_count_offset = expandBufGetLength(pReply);
Elliott Hughesdbb40792011-11-18 17:05:22 -08001656 expandBufAdd4BE(pReply, 0);
1657
1658 DebugCallbackContext context;
Jeff Haob7cefc72013-11-14 14:51:09 -08001659 context.method = m;
Elliott Hughesdbb40792011-11-18 17:05:22 -08001660 context.pReply = pReply;
Elliott Hughesc5b734a2011-12-01 17:20:58 -08001661 context.variable_count = 0;
1662 context.with_generic = with_generic;
Elliott Hughesdbb40792011-11-18 17:05:22 -08001663
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07001664 const DexFile::CodeItem* code_item = m->GetCodeItem();
Sebastien Hertzcb19ebf2014-03-11 15:26:35 +01001665 if (code_item != nullptr) {
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07001666 m->GetDexFile()->DecodeDebugInfo(
1667 code_item, m->IsStatic(), m->GetDexMethodIndex(), NULL, DebugCallbackContext::Callback,
1668 &context);
Sebastien Hertzcb19ebf2014-03-11 15:26:35 +01001669 }
Elliott Hughesdbb40792011-11-18 17:05:22 -08001670
Elliott Hughesc5b734a2011-12-01 17:20:58 -08001671 JDWP::Set4BE(expandBufGetBuffer(pReply) + variable_count_offset, context.variable_count);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001672}
1673
Jeff Hao579b0242013-11-18 13:16:49 -08001674void Dbg::OutputMethodReturnValue(JDWP::MethodId method_id, const JValue* return_value,
1675 JDWP::ExpandBuf* pReply) {
1676 mirror::ArtMethod* m = FromMethodId(method_id);
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07001677 JDWP::JdwpTag tag = BasicTagFromDescriptor(m->GetShorty());
Jeff Hao579b0242013-11-18 13:16:49 -08001678 OutputJValue(tag, return_value, pReply);
1679}
1680
Sebastien Hertz3f52eaf2014-04-04 17:50:18 +02001681void Dbg::OutputFieldValue(JDWP::FieldId field_id, const JValue* field_value,
1682 JDWP::ExpandBuf* pReply) {
1683 mirror::ArtField* f = FromFieldId(field_id);
Mathieu Chartier61c5ebc2014-06-05 17:42:53 -07001684 JDWP::JdwpTag tag = BasicTagFromDescriptor(f->GetTypeDescriptor());
Sebastien Hertz3f52eaf2014-04-04 17:50:18 +02001685 OutputJValue(tag, field_value, pReply);
1686}
1687
Elliott Hughes9777ba22013-01-17 09:04:19 -08001688JDWP::JdwpError Dbg::GetBytecodes(JDWP::RefTypeId, JDWP::MethodId method_id,
1689 std::vector<uint8_t>& bytecodes)
1690 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Brian Carlstromea46f952013-07-30 01:26:50 -07001691 mirror::ArtMethod* m = FromMethodId(method_id);
Elliott Hughes9777ba22013-01-17 09:04:19 -08001692 if (m == NULL) {
1693 return JDWP::ERR_INVALID_METHODID;
1694 }
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07001695 const DexFile::CodeItem* code_item = m->GetCodeItem();
Elliott Hughes9777ba22013-01-17 09:04:19 -08001696 size_t byte_count = code_item->insns_size_in_code_units_ * 2;
1697 const uint8_t* begin = reinterpret_cast<const uint8_t*>(code_item->insns_);
1698 const uint8_t* end = begin + byte_count;
1699 for (const uint8_t* p = begin; p != end; ++p) {
1700 bytecodes.push_back(*p);
1701 }
1702 return JDWP::ERR_NONE;
1703}
1704
Elliott Hughes88d63092013-01-09 09:55:54 -08001705JDWP::JdwpTag Dbg::GetFieldBasicTag(JDWP::FieldId field_id) {
Mathieu Chartier61c5ebc2014-06-05 17:42:53 -07001706 return BasicTagFromDescriptor(FromFieldId(field_id)->GetTypeDescriptor());
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001707}
1708
Elliott Hughes88d63092013-01-09 09:55:54 -08001709JDWP::JdwpTag Dbg::GetStaticFieldBasicTag(JDWP::FieldId field_id) {
Mathieu Chartier61c5ebc2014-06-05 17:42:53 -07001710 return BasicTagFromDescriptor(FromFieldId(field_id)->GetTypeDescriptor());
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001711}
1712
Elliott Hughes88d63092013-01-09 09:55:54 -08001713static JDWP::JdwpError GetFieldValueImpl(JDWP::RefTypeId ref_type_id, JDWP::ObjectId object_id,
1714 JDWP::FieldId field_id, JDWP::ExpandBuf* pReply,
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001715 bool is_static)
Ian Rogersb726dcb2012-09-05 08:57:23 -07001716 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Elliott Hughes0cf74332012-02-23 23:14:00 -08001717 JDWP::JdwpError status;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001718 mirror::Class* c = DecodeClass(ref_type_id, status);
Elliott Hughes88d63092013-01-09 09:55:54 -08001719 if (ref_type_id != 0 && c == NULL) {
Elliott Hughes0cf74332012-02-23 23:14:00 -08001720 return status;
1721 }
1722
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001723 mirror::Object* o = gRegistry->Get<mirror::Object*>(object_id);
Elliott Hughes64f574f2013-02-20 14:57:12 -08001724 if ((!is_static && o == NULL) || o == ObjectRegistry::kInvalidObject) {
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08001725 return JDWP::ERR_INVALID_OBJECT;
1726 }
Brian Carlstromea46f952013-07-30 01:26:50 -07001727 mirror::ArtField* f = FromFieldId(field_id);
Elliott Hughes0cf74332012-02-23 23:14:00 -08001728
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001729 mirror::Class* receiver_class = c;
Elliott Hughes0cf74332012-02-23 23:14:00 -08001730 if (receiver_class == NULL && o != NULL) {
1731 receiver_class = o->GetClass();
1732 }
1733 // TODO: should we give up now if receiver_class is NULL?
1734 if (receiver_class != NULL && !f->GetDeclaringClass()->IsAssignableFrom(receiver_class)) {
1735 LOG(INFO) << "ERR_INVALID_FIELDID: " << PrettyField(f) << " " << PrettyClass(receiver_class);
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08001736 return JDWP::ERR_INVALID_FIELDID;
1737 }
Elliott Hughesaed4be92011-12-02 16:16:23 -08001738
Elliott Hughes0cf74332012-02-23 23:14:00 -08001739 // The RI only enforces the static/non-static mismatch in one direction.
1740 // TODO: should we change the tests and check both?
1741 if (is_static) {
1742 if (!f->IsStatic()) {
1743 return JDWP::ERR_INVALID_FIELDID;
1744 }
1745 } else {
1746 if (f->IsStatic()) {
1747 LOG(WARNING) << "Ignoring non-NULL receiver for ObjectReference.SetValues on static field " << PrettyField(f);
Elliott Hughes0cf74332012-02-23 23:14:00 -08001748 }
1749 }
jeffhao0dfbb7e2012-11-28 15:26:03 -08001750 if (f->IsStatic()) {
1751 o = f->GetDeclaringClass();
1752 }
Elliott Hughes0cf74332012-02-23 23:14:00 -08001753
Mathieu Chartier61c5ebc2014-06-05 17:42:53 -07001754 JDWP::JdwpTag tag = BasicTagFromDescriptor(f->GetTypeDescriptor());
Jeff Hao579b0242013-11-18 13:16:49 -08001755 JValue field_value;
1756 if (tag == JDWP::JT_VOID) {
1757 LOG(FATAL) << "Unknown tag: " << tag;
1758 } else if (!IsPrimitiveTag(tag)) {
1759 field_value.SetL(f->GetObject(o));
1760 } else if (tag == JDWP::JT_DOUBLE || tag == JDWP::JT_LONG) {
1761 field_value.SetJ(f->Get64(o));
Elliott Hughesaed4be92011-12-02 16:16:23 -08001762 } else {
Jeff Hao579b0242013-11-18 13:16:49 -08001763 field_value.SetI(f->Get32(o));
Elliott Hughesaed4be92011-12-02 16:16:23 -08001764 }
Jeff Hao579b0242013-11-18 13:16:49 -08001765 Dbg::OutputJValue(tag, &field_value, pReply);
1766
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08001767 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001768}
1769
Elliott Hughes88d63092013-01-09 09:55:54 -08001770JDWP::JdwpError Dbg::GetFieldValue(JDWP::ObjectId object_id, JDWP::FieldId field_id,
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001771 JDWP::ExpandBuf* pReply) {
Elliott Hughes88d63092013-01-09 09:55:54 -08001772 return GetFieldValueImpl(0, object_id, field_id, pReply, false);
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08001773}
1774
Elliott Hughes88d63092013-01-09 09:55:54 -08001775JDWP::JdwpError Dbg::GetStaticFieldValue(JDWP::RefTypeId ref_type_id, JDWP::FieldId field_id, JDWP::ExpandBuf* pReply) {
1776 return GetFieldValueImpl(ref_type_id, 0, field_id, pReply, true);
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08001777}
1778
Elliott Hughes88d63092013-01-09 09:55:54 -08001779static JDWP::JdwpError SetFieldValueImpl(JDWP::ObjectId object_id, JDWP::FieldId field_id,
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001780 uint64_t value, int width, bool is_static)
Ian Rogersb726dcb2012-09-05 08:57:23 -07001781 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001782 mirror::Object* o = gRegistry->Get<mirror::Object*>(object_id);
Elliott Hughes64f574f2013-02-20 14:57:12 -08001783 if ((!is_static && o == NULL) || o == ObjectRegistry::kInvalidObject) {
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08001784 return JDWP::ERR_INVALID_OBJECT;
1785 }
Brian Carlstromea46f952013-07-30 01:26:50 -07001786 mirror::ArtField* f = FromFieldId(field_id);
Elliott Hughes0cf74332012-02-23 23:14:00 -08001787
1788 // The RI only enforces the static/non-static mismatch in one direction.
1789 // TODO: should we change the tests and check both?
1790 if (is_static) {
1791 if (!f->IsStatic()) {
1792 return JDWP::ERR_INVALID_FIELDID;
1793 }
1794 } else {
1795 if (f->IsStatic()) {
1796 LOG(WARNING) << "Ignoring non-NULL receiver for ObjectReference.SetValues on static field " << PrettyField(f);
Elliott Hughes0cf74332012-02-23 23:14:00 -08001797 }
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08001798 }
jeffhao0dfbb7e2012-11-28 15:26:03 -08001799 if (f->IsStatic()) {
1800 o = f->GetDeclaringClass();
1801 }
Elliott Hughesaed4be92011-12-02 16:16:23 -08001802
Mathieu Chartier61c5ebc2014-06-05 17:42:53 -07001803 JDWP::JdwpTag tag = BasicTagFromDescriptor(f->GetTypeDescriptor());
Elliott Hughesaed4be92011-12-02 16:16:23 -08001804
1805 if (IsPrimitiveTag(tag)) {
1806 if (tag == JDWP::JT_DOUBLE || tag == JDWP::JT_LONG) {
Elliott Hughes1bac54f2012-03-16 12:48:31 -07001807 CHECK_EQ(width, 8);
Sebastien Hertzd2fe10a2014-01-15 10:20:56 +01001808 // Debugging can't use transactional mode (runtime only).
1809 f->Set64<false>(o, value);
Elliott Hughesaed4be92011-12-02 16:16:23 -08001810 } else {
Elliott Hughes1bac54f2012-03-16 12:48:31 -07001811 CHECK_LE(width, 4);
Sebastien Hertzd2fe10a2014-01-15 10:20:56 +01001812 // Debugging can't use transactional mode (runtime only).
1813 f->Set32<false>(o, value);
Elliott Hughesaed4be92011-12-02 16:16:23 -08001814 }
1815 } else {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001816 mirror::Object* v = gRegistry->Get<mirror::Object*>(value);
Elliott Hughes64f574f2013-02-20 14:57:12 -08001817 if (v == ObjectRegistry::kInvalidObject) {
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -08001818 return JDWP::ERR_INVALID_OBJECT;
1819 }
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08001820 if (v != NULL) {
Mathieu Chartier61c5ebc2014-06-05 17:42:53 -07001821 mirror::Class* field_type;
1822 {
1823 StackHandleScope<3> hs(Thread::Current());
1824 HandleWrapper<mirror::Object> h_v(hs.NewHandleWrapper(&v));
1825 HandleWrapper<mirror::ArtField> h_f(hs.NewHandleWrapper(&f));
1826 HandleWrapper<mirror::Object> h_o(hs.NewHandleWrapper(&o));
1827 field_type = FieldHelper(h_f).GetType();
1828 }
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08001829 if (!field_type->IsAssignableFrom(v->GetClass())) {
1830 return JDWP::ERR_INVALID_OBJECT;
1831 }
1832 }
Sebastien Hertzd2fe10a2014-01-15 10:20:56 +01001833 // Debugging can't use transactional mode (runtime only).
1834 f->SetObject<false>(o, v);
Elliott Hughesaed4be92011-12-02 16:16:23 -08001835 }
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -08001836
1837 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001838}
1839
Elliott Hughes88d63092013-01-09 09:55:54 -08001840JDWP::JdwpError Dbg::SetFieldValue(JDWP::ObjectId object_id, JDWP::FieldId field_id, uint64_t value,
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001841 int width) {
Elliott Hughes88d63092013-01-09 09:55:54 -08001842 return SetFieldValueImpl(object_id, field_id, value, width, false);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001843}
1844
Elliott Hughes88d63092013-01-09 09:55:54 -08001845JDWP::JdwpError Dbg::SetStaticFieldValue(JDWP::FieldId field_id, uint64_t value, int width) {
1846 return SetFieldValueImpl(0, field_id, value, width, true);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001847}
1848
Elliott Hughes88d63092013-01-09 09:55:54 -08001849std::string Dbg::StringToUtf8(JDWP::ObjectId string_id) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001850 mirror::String* s = gRegistry->Get<mirror::String*>(string_id);
Elliott Hughes68fdbd02011-11-29 19:22:47 -08001851 return s->ToModifiedUtf8();
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001852}
1853
Jeff Hao579b0242013-11-18 13:16:49 -08001854void Dbg::OutputJValue(JDWP::JdwpTag tag, const JValue* return_value, JDWP::ExpandBuf* pReply) {
1855 if (IsPrimitiveTag(tag)) {
1856 expandBufAdd1(pReply, tag);
1857 if (tag == JDWP::JT_BOOLEAN || tag == JDWP::JT_BYTE) {
1858 expandBufAdd1(pReply, return_value->GetI());
1859 } else if (tag == JDWP::JT_CHAR || tag == JDWP::JT_SHORT) {
1860 expandBufAdd2BE(pReply, return_value->GetI());
1861 } else if (tag == JDWP::JT_FLOAT || tag == JDWP::JT_INT) {
1862 expandBufAdd4BE(pReply, return_value->GetI());
1863 } else if (tag == JDWP::JT_DOUBLE || tag == JDWP::JT_LONG) {
1864 expandBufAdd8BE(pReply, return_value->GetJ());
1865 } else {
1866 CHECK_EQ(tag, JDWP::JT_VOID);
1867 }
1868 } else {
Ian Rogers98379392014-02-24 16:53:16 -08001869 ScopedObjectAccessUnchecked soa(Thread::Current());
Jeff Hao579b0242013-11-18 13:16:49 -08001870 mirror::Object* value = return_value->GetL();
Ian Rogers98379392014-02-24 16:53:16 -08001871 expandBufAdd1(pReply, TagFromObject(soa, value));
Jeff Hao579b0242013-11-18 13:16:49 -08001872 expandBufAddObjectId(pReply, gRegistry->Add(value));
1873 }
1874}
1875
Elliott Hughes221229c2013-01-08 18:17:50 -08001876JDWP::JdwpError Dbg::GetThreadName(JDWP::ObjectId thread_id, std::string& name) {
jeffhaoa77f0f62012-12-05 17:19:31 -08001877 ScopedObjectAccessUnchecked soa(Thread::Current());
1878 MutexLock mu(soa.Self(), *Locks::thread_list_lock_);
Elliott Hughes221229c2013-01-08 18:17:50 -08001879 Thread* thread;
1880 JDWP::JdwpError error = DecodeThread(soa, thread_id, thread);
1881 if (error != JDWP::ERR_NONE && error != JDWP::ERR_THREAD_NOT_ALIVE) {
1882 return error;
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001883 }
Elliott Hughes221229c2013-01-08 18:17:50 -08001884
1885 // We still need to report the zombie threads' names, so we can't just call Thread::GetThreadName.
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001886 mirror::Object* thread_object = gRegistry->Get<mirror::Object*>(thread_id);
Brian Carlstromea46f952013-07-30 01:26:50 -07001887 mirror::ArtField* java_lang_Thread_name_field =
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001888 soa.DecodeField(WellKnownClasses::java_lang_Thread_name);
1889 mirror::String* s =
1890 reinterpret_cast<mirror::String*>(java_lang_Thread_name_field->GetObject(thread_object));
Elliott Hughes221229c2013-01-08 18:17:50 -08001891 if (s != NULL) {
1892 name = s->ToModifiedUtf8();
1893 }
1894 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001895}
1896
Elliott Hughes221229c2013-01-08 18:17:50 -08001897JDWP::JdwpError Dbg::GetThreadGroup(JDWP::ObjectId thread_id, JDWP::ExpandBuf* pReply) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001898 ScopedObjectAccess soa(Thread::Current());
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001899 mirror::Object* thread_object = gRegistry->Get<mirror::Object*>(thread_id);
Elliott Hughes64f574f2013-02-20 14:57:12 -08001900 if (thread_object == ObjectRegistry::kInvalidObject) {
Elliott Hughes2435a572012-02-17 16:07:41 -08001901 return JDWP::ERR_INVALID_OBJECT;
1902 }
Ian Rogers98379392014-02-24 16:53:16 -08001903 const char* old_cause = soa.Self()->StartAssertNoThreadSuspension("Debugger: GetThreadGroup");
Elliott Hughes2435a572012-02-17 16:07:41 -08001904 // Okay, so it's an object, but is it actually a thread?
Hiroshi Yamauchib5a9e3d2014-06-09 12:11:20 -07001905 JDWP::JdwpError error;
1906 {
1907 MutexLock mu(soa.Self(), *Locks::thread_list_lock_);
1908 Thread* thread;
1909 error = DecodeThread(soa, thread_id, thread);
1910 }
Elliott Hughes221229c2013-01-08 18:17:50 -08001911 if (error == JDWP::ERR_THREAD_NOT_ALIVE) {
1912 // Zombie threads are in the null group.
1913 expandBufAddObjectId(pReply, JDWP::ObjectId(0));
Sebastien Hertz52d131d2014-03-13 16:17:40 +01001914 error = JDWP::ERR_NONE;
1915 } else if (error == JDWP::ERR_NONE) {
1916 mirror::Class* c = soa.Decode<mirror::Class*>(WellKnownClasses::java_lang_Thread);
1917 CHECK(c != nullptr);
1918 mirror::ArtField* f = c->FindInstanceField("group", "Ljava/lang/ThreadGroup;");
Hiroshi Yamauchib5a9e3d2014-06-09 12:11:20 -07001919 CHECK(f != nullptr);
Sebastien Hertz52d131d2014-03-13 16:17:40 +01001920 mirror::Object* group = f->GetObject(thread_object);
Hiroshi Yamauchib5a9e3d2014-06-09 12:11:20 -07001921 CHECK(group != nullptr);
Sebastien Hertz52d131d2014-03-13 16:17:40 +01001922 JDWP::ObjectId thread_group_id = gRegistry->Add(group);
1923 expandBufAddObjectId(pReply, thread_group_id);
Elliott Hughes221229c2013-01-08 18:17:50 -08001924 }
Ian Rogers98379392014-02-24 16:53:16 -08001925 soa.Self()->EndAssertNoThreadSuspension(old_cause);
Sebastien Hertz52d131d2014-03-13 16:17:40 +01001926 return error;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001927}
1928
Elliott Hughes88d63092013-01-09 09:55:54 -08001929std::string Dbg::GetThreadGroupName(JDWP::ObjectId thread_group_id) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001930 ScopedObjectAccess soa(Thread::Current());
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001931 mirror::Object* thread_group = gRegistry->Get<mirror::Object*>(thread_group_id);
Ian Rogers98379392014-02-24 16:53:16 -08001932 CHECK(thread_group != nullptr);
1933 const char* old_cause = soa.Self()->StartAssertNoThreadSuspension("Debugger: GetThreadGroupName");
1934 mirror::Class* c = soa.Decode<mirror::Class*>(WellKnownClasses::java_lang_ThreadGroup);
1935 CHECK(c != nullptr);
Brian Carlstromea46f952013-07-30 01:26:50 -07001936 mirror::ArtField* f = c->FindInstanceField("name", "Ljava/lang/String;");
Elliott Hughes499c5132011-11-17 14:55:11 -08001937 CHECK(f != NULL);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001938 mirror::String* s = reinterpret_cast<mirror::String*>(f->GetObject(thread_group));
Ian Rogers98379392014-02-24 16:53:16 -08001939 soa.Self()->EndAssertNoThreadSuspension(old_cause);
Elliott Hughes499c5132011-11-17 14:55:11 -08001940 return s->ToModifiedUtf8();
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001941}
1942
Elliott Hughes88d63092013-01-09 09:55:54 -08001943JDWP::ObjectId Dbg::GetThreadGroupParent(JDWP::ObjectId thread_group_id) {
Ian Rogers98379392014-02-24 16:53:16 -08001944 ScopedObjectAccessUnchecked soa(Thread::Current());
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001945 mirror::Object* thread_group = gRegistry->Get<mirror::Object*>(thread_group_id);
Ian Rogers98379392014-02-24 16:53:16 -08001946 CHECK(thread_group != nullptr);
1947 const char* old_cause = soa.Self()->StartAssertNoThreadSuspension("Debugger: GetThreadGroupParent");
1948 mirror::Class* c = soa.Decode<mirror::Class*>(WellKnownClasses::java_lang_ThreadGroup);
1949 CHECK(c != nullptr);
Brian Carlstromea46f952013-07-30 01:26:50 -07001950 mirror::ArtField* f = c->FindInstanceField("parent", "Ljava/lang/ThreadGroup;");
Elliott Hughes4e235312011-12-02 11:34:15 -08001951 CHECK(f != NULL);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001952 mirror::Object* parent = f->GetObject(thread_group);
Ian Rogers98379392014-02-24 16:53:16 -08001953 soa.Self()->EndAssertNoThreadSuspension(old_cause);
Elliott Hughes4e235312011-12-02 11:34:15 -08001954 return gRegistry->Add(parent);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001955}
1956
1957JDWP::ObjectId Dbg::GetSystemThreadGroupId() {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001958 ScopedObjectAccessUnchecked soa(Thread::Current());
Brian Carlstromea46f952013-07-30 01:26:50 -07001959 mirror::ArtField* f = soa.DecodeField(WellKnownClasses::java_lang_ThreadGroup_systemThreadGroup);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001960 mirror::Object* group = f->GetObject(f->GetDeclaringClass());
Ian Rogers365c1022012-06-22 15:05:28 -07001961 return gRegistry->Add(group);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001962}
1963
1964JDWP::ObjectId Dbg::GetMainThreadGroupId() {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001965 ScopedObjectAccess soa(Thread::Current());
Brian Carlstromea46f952013-07-30 01:26:50 -07001966 mirror::ArtField* f = soa.DecodeField(WellKnownClasses::java_lang_ThreadGroup_mainThreadGroup);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001967 mirror::Object* group = f->GetObject(f->GetDeclaringClass());
Ian Rogers365c1022012-06-22 15:05:28 -07001968 return gRegistry->Add(group);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001969}
1970
Jeff Hao920af3e2013-08-28 15:46:38 -07001971JDWP::JdwpThreadStatus Dbg::ToJdwpThreadStatus(ThreadState state) {
1972 switch (state) {
1973 case kBlocked:
1974 return JDWP::TS_MONITOR;
1975 case kNative:
1976 case kRunnable:
1977 case kSuspended:
1978 return JDWP::TS_RUNNING;
1979 case kSleeping:
1980 return JDWP::TS_SLEEPING;
1981 case kStarting:
1982 case kTerminated:
1983 return JDWP::TS_ZOMBIE;
1984 case kTimedWaiting:
1985 case kWaitingForDebuggerSend:
1986 case kWaitingForDebuggerSuspension:
1987 case kWaitingForDebuggerToAttach:
Sebastien Hertz138dbfc2013-12-04 18:15:25 +01001988 case kWaitingForDeoptimization:
Jeff Hao920af3e2013-08-28 15:46:38 -07001989 case kWaitingForGcToComplete:
1990 case kWaitingForCheckPointsToRun:
1991 case kWaitingForJniOnLoad:
1992 case kWaitingForSignalCatcherOutput:
1993 case kWaitingInMainDebuggerLoop:
1994 case kWaitingInMainSignalCatcherLoop:
1995 case kWaitingPerformingGc:
1996 case kWaiting:
1997 return JDWP::TS_WAIT;
1998 // Don't add a 'default' here so the compiler can spot incompatible enum changes.
1999 }
2000 LOG(FATAL) << "Unknown thread state: " << state;
2001 return JDWP::TS_ZOMBIE;
2002}
2003
Sebastien Hertz52d131d2014-03-13 16:17:40 +01002004JDWP::JdwpError Dbg::GetThreadStatus(JDWP::ObjectId thread_id, JDWP::JdwpThreadStatus* pThreadStatus,
2005 JDWP::JdwpSuspendStatus* pSuspendStatus) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002006 ScopedObjectAccess soa(Thread::Current());
Elliott Hughes499c5132011-11-17 14:55:11 -08002007
Elliott Hughes9e0c1752013-01-09 14:02:58 -08002008 *pSuspendStatus = JDWP::SUSPEND_STATUS_NOT_SUSPENDED;
2009
Ian Rogers50b35e22012-10-04 10:09:15 -07002010 MutexLock mu(soa.Self(), *Locks::thread_list_lock_);
Elliott Hughes221229c2013-01-08 18:17:50 -08002011 Thread* thread;
2012 JDWP::JdwpError error = DecodeThread(soa, thread_id, thread);
2013 if (error != JDWP::ERR_NONE) {
2014 if (error == JDWP::ERR_THREAD_NOT_ALIVE) {
2015 *pThreadStatus = JDWP::TS_ZOMBIE;
Elliott Hughes221229c2013-01-08 18:17:50 -08002016 return JDWP::ERR_NONE;
2017 }
2018 return error;
Elliott Hughes499c5132011-11-17 14:55:11 -08002019 }
2020
Elliott Hughes9e0c1752013-01-09 14:02:58 -08002021 if (IsSuspendedForDebugger(soa, thread)) {
2022 *pSuspendStatus = JDWP::SUSPEND_STATUS_SUSPENDED;
Elliott Hughes499c5132011-11-17 14:55:11 -08002023 }
2024
Jeff Hao920af3e2013-08-28 15:46:38 -07002025 *pThreadStatus = ToJdwpThreadStatus(thread->GetState());
Elliott Hughes221229c2013-01-08 18:17:50 -08002026 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002027}
2028
Elliott Hughes221229c2013-01-08 18:17:50 -08002029JDWP::JdwpError Dbg::GetThreadDebugSuspendCount(JDWP::ObjectId thread_id, JDWP::ExpandBuf* pReply) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002030 ScopedObjectAccess soa(Thread::Current());
Ian Rogers50b35e22012-10-04 10:09:15 -07002031 MutexLock mu(soa.Self(), *Locks::thread_list_lock_);
Elliott Hughes221229c2013-01-08 18:17:50 -08002032 Thread* thread;
2033 JDWP::JdwpError error = DecodeThread(soa, thread_id, thread);
2034 if (error != JDWP::ERR_NONE) {
2035 return error;
Elliott Hughes2435a572012-02-17 16:07:41 -08002036 }
Ian Rogers50b35e22012-10-04 10:09:15 -07002037 MutexLock mu2(soa.Self(), *Locks::thread_suspend_count_lock_);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002038 expandBufAdd4BE(pReply, thread->GetDebugSuspendCount());
Elliott Hughes2435a572012-02-17 16:07:41 -08002039 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002040}
2041
Elliott Hughesf9501702013-01-11 11:22:27 -08002042JDWP::JdwpError Dbg::Interrupt(JDWP::ObjectId thread_id) {
2043 ScopedObjectAccess soa(Thread::Current());
2044 MutexLock mu(soa.Self(), *Locks::thread_list_lock_);
2045 Thread* thread;
2046 JDWP::JdwpError error = DecodeThread(soa, thread_id, thread);
2047 if (error != JDWP::ERR_NONE) {
2048 return error;
2049 }
Ian Rogersdd7624d2014-03-14 17:43:00 -07002050 thread->Interrupt(soa.Self());
Elliott Hughesf9501702013-01-11 11:22:27 -08002051 return JDWP::ERR_NONE;
2052}
2053
Elliott Hughescaf76542012-06-28 16:08:22 -07002054void Dbg::GetThreads(JDWP::ObjectId thread_group_id, std::vector<JDWP::ObjectId>& thread_ids) {
Ian Rogers365c1022012-06-22 15:05:28 -07002055 class ThreadListVisitor {
2056 public:
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002057 ThreadListVisitor(const ScopedObjectAccessUnchecked& soa, mirror::Object* desired_thread_group,
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002058 std::vector<JDWP::ObjectId>& thread_ids)
Ian Rogersb726dcb2012-09-05 08:57:23 -07002059 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_)
jeffhao0dfbb7e2012-11-28 15:26:03 -08002060 : soa_(soa), desired_thread_group_(desired_thread_group), thread_ids_(thread_ids) {}
Ian Rogers365c1022012-06-22 15:05:28 -07002061
Elliott Hughesa2155262011-11-16 16:26:58 -08002062 static void Visit(Thread* t, void* arg) {
2063 reinterpret_cast<ThreadListVisitor*>(arg)->Visit(t);
2064 }
2065
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002066 // TODO: Enable annotalysis. We know lock is held in constructor, but abstraction confuses
2067 // annotalysis.
2068 void Visit(Thread* t) NO_THREAD_SAFETY_ANALYSIS {
Elliott Hughesa2155262011-11-16 16:26:58 -08002069 if (t == Dbg::GetDebugThread()) {
2070 // Skip the JDWP thread. Some debuggers get bent out of shape when they can't suspend and
2071 // query all threads, so it's easier if we just don't tell them about this thread.
2072 return;
2073 }
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002074 mirror::Object* peer = t->GetPeer();
jeffhao0dfbb7e2012-11-28 15:26:03 -08002075 if (IsInDesiredThreadGroup(peer)) {
Ian Rogers120f1c72012-09-28 17:17:10 -07002076 thread_ids_.push_back(gRegistry->Add(peer));
Elliott Hughesa2155262011-11-16 16:26:58 -08002077 }
2078 }
2079
Ian Rogers365c1022012-06-22 15:05:28 -07002080 private:
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002081 bool IsInDesiredThreadGroup(mirror::Object* peer)
jeffhao0dfbb7e2012-11-28 15:26:03 -08002082 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
jeffhao0dfbb7e2012-11-28 15:26:03 -08002083 // peer might be NULL if the thread is still starting up.
2084 if (peer == NULL) {
2085 // We can't tell the debugger about this thread yet.
2086 // TODO: if we identified threads to the debugger by their Thread*
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002087 // rather than their peer's mirror::Object*, we could fix this.
jeffhao0dfbb7e2012-11-28 15:26:03 -08002088 // Doing so might help us report ZOMBIE threads too.
2089 return false;
2090 }
jeffhaoc1e04902012-12-13 12:41:10 -08002091 // Do we want threads from all thread groups?
2092 if (desired_thread_group_ == NULL) {
2093 return true;
2094 }
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002095 mirror::Object* group = soa_.DecodeField(WellKnownClasses::java_lang_Thread_group)->GetObject(peer);
jeffhao0dfbb7e2012-11-28 15:26:03 -08002096 return (group == desired_thread_group_);
2097 }
2098
Mathieu Chartierdbe6f462012-09-25 16:54:50 -07002099 const ScopedObjectAccessUnchecked& soa_;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002100 mirror::Object* const desired_thread_group_;
Elliott Hughescaf76542012-06-28 16:08:22 -07002101 std::vector<JDWP::ObjectId>& thread_ids_;
Elliott Hughesa2155262011-11-16 16:26:58 -08002102 };
2103
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002104 ScopedObjectAccessUnchecked soa(Thread::Current());
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002105 mirror::Object* thread_group = gRegistry->Get<mirror::Object*>(thread_group_id);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002106 ThreadListVisitor tlv(soa, thread_group, thread_ids);
Ian Rogers50b35e22012-10-04 10:09:15 -07002107 MutexLock mu(soa.Self(), *Locks::thread_list_lock_);
Elliott Hughesf8349362012-06-18 15:00:06 -07002108 Runtime::Current()->GetThreadList()->ForEach(ThreadListVisitor::Visit, &tlv);
Elliott Hughescaf76542012-06-28 16:08:22 -07002109}
Elliott Hughesa2155262011-11-16 16:26:58 -08002110
Elliott Hughescaf76542012-06-28 16:08:22 -07002111void Dbg::GetChildThreadGroups(JDWP::ObjectId thread_group_id, std::vector<JDWP::ObjectId>& child_thread_group_ids) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002112 ScopedObjectAccess soa(Thread::Current());
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002113 mirror::Object* thread_group = gRegistry->Get<mirror::Object*>(thread_group_id);
Elliott Hughescaf76542012-06-28 16:08:22 -07002114
2115 // Get the ArrayList<ThreadGroup> "groups" out of this thread group...
Brian Carlstromea46f952013-07-30 01:26:50 -07002116 mirror::ArtField* groups_field = thread_group->GetClass()->FindInstanceField("groups", "Ljava/util/List;");
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002117 mirror::Object* groups_array_list = groups_field->GetObject(thread_group);
Elliott Hughescaf76542012-06-28 16:08:22 -07002118
2119 // Get the array and size out of the ArrayList<ThreadGroup>...
Brian Carlstromea46f952013-07-30 01:26:50 -07002120 mirror::ArtField* array_field = groups_array_list->GetClass()->FindInstanceField("array", "[Ljava/lang/Object;");
2121 mirror::ArtField* size_field = groups_array_list->GetClass()->FindInstanceField("size", "I");
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002122 mirror::ObjectArray<mirror::Object>* groups_array =
2123 array_field->GetObject(groups_array_list)->AsObjectArray<mirror::Object>();
Elliott Hughescaf76542012-06-28 16:08:22 -07002124 const int32_t size = size_field->GetInt(groups_array_list);
2125
2126 // Copy the first 'size' elements out of the array into the result.
2127 for (int32_t i = 0; i < size; ++i) {
2128 child_thread_group_ids.push_back(gRegistry->Add(groups_array->Get(i)));
Elliott Hughesa2155262011-11-16 16:26:58 -08002129 }
2130}
2131
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002132static int GetStackDepth(Thread* thread)
Ian Rogersb726dcb2012-09-05 08:57:23 -07002133 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Ian Rogers0399dde2012-06-06 17:09:28 -07002134 struct CountStackDepthVisitor : public StackVisitor {
Brian Carlstrom93ba8932013-07-17 21:31:49 -07002135 explicit CountStackDepthVisitor(Thread* thread)
Ian Rogers7a22fa62013-01-23 12:16:16 -08002136 : StackVisitor(thread, NULL), depth(0) {}
Ian Rogers0399dde2012-06-06 17:09:28 -07002137
Elliott Hughes64f574f2013-02-20 14:57:12 -08002138 // TODO: Enable annotalysis. We know lock is held in constructor, but abstraction confuses
2139 // annotalysis.
2140 bool VisitFrame() NO_THREAD_SAFETY_ANALYSIS {
Ian Rogers0399dde2012-06-06 17:09:28 -07002141 if (!GetMethod()->IsRuntimeMethod()) {
Elliott Hughesf8a2df72011-12-01 12:19:54 -08002142 ++depth;
2143 }
Elliott Hughes530fa002012-03-12 11:44:49 -07002144 return true;
Elliott Hughesa2e54f62011-11-17 13:01:30 -08002145 }
2146 size_t depth;
2147 };
Elliott Hughes08fc03a2012-06-26 17:34:00 -07002148
Ian Rogers7a22fa62013-01-23 12:16:16 -08002149 CountStackDepthVisitor visitor(thread);
Ian Rogers0399dde2012-06-06 17:09:28 -07002150 visitor.WalkStack();
Elliott Hughesa2e54f62011-11-17 13:01:30 -08002151 return visitor.depth;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002152}
2153
Elliott Hughes221229c2013-01-08 18:17:50 -08002154JDWP::JdwpError Dbg::GetThreadFrameCount(JDWP::ObjectId thread_id, size_t& result) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002155 ScopedObjectAccess soa(Thread::Current());
jeffhaoa77f0f62012-12-05 17:19:31 -08002156 MutexLock mu(soa.Self(), *Locks::thread_list_lock_);
Elliott Hughes221229c2013-01-08 18:17:50 -08002157 Thread* thread;
2158 JDWP::JdwpError error = DecodeThread(soa, thread_id, thread);
2159 if (error != JDWP::ERR_NONE) {
2160 return error;
2161 }
Elliott Hughesf15f4a02013-01-09 10:09:38 -08002162 if (!IsSuspendedForDebugger(soa, thread)) {
2163 return JDWP::ERR_THREAD_NOT_SUSPENDED;
2164 }
Elliott Hughes221229c2013-01-08 18:17:50 -08002165 result = GetStackDepth(thread);
2166 return JDWP::ERR_NONE;
Elliott Hughes86964332012-02-15 19:37:42 -08002167}
2168
Ian Rogers306057f2012-11-26 12:45:53 -08002169JDWP::JdwpError Dbg::GetThreadFrames(JDWP::ObjectId thread_id, size_t start_frame,
2170 size_t frame_count, JDWP::ExpandBuf* buf) {
Elliott Hughes6e9d22c2012-06-22 15:02:37 -07002171 class GetFrameVisitor : public StackVisitor {
2172 public:
Ian Rogers7a22fa62013-01-23 12:16:16 -08002173 GetFrameVisitor(Thread* thread, size_t start_frame, size_t frame_count, JDWP::ExpandBuf* buf)
Ian Rogersb726dcb2012-09-05 08:57:23 -07002174 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_)
Ian Rogers7a22fa62013-01-23 12:16:16 -08002175 : StackVisitor(thread, NULL), depth_(0),
Elliott Hughes6e9d22c2012-06-22 15:02:37 -07002176 start_frame_(start_frame), frame_count_(frame_count), buf_(buf) {
2177 expandBufAdd4BE(buf_, frame_count_);
Elliott Hughes03181a82011-11-17 17:22:21 -08002178 }
Ian Rogers0399dde2012-06-06 17:09:28 -07002179
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002180 // TODO: Enable annotalysis. We know lock is held in constructor, but abstraction confuses
2181 // annotalysis.
2182 virtual bool VisitFrame() NO_THREAD_SAFETY_ANALYSIS {
Ian Rogers0399dde2012-06-06 17:09:28 -07002183 if (GetMethod()->IsRuntimeMethod()) {
Brian Carlstrom7934ac22013-07-26 10:54:15 -07002184 return true; // The debugger can't do anything useful with a frame that has no Method*.
Elliott Hughes03181a82011-11-17 17:22:21 -08002185 }
Elliott Hughes6e9d22c2012-06-22 15:02:37 -07002186 if (depth_ >= start_frame_ + frame_count_) {
Elliott Hughes530fa002012-03-12 11:44:49 -07002187 return false;
Elliott Hughes03181a82011-11-17 17:22:21 -08002188 }
Elliott Hughes6e9d22c2012-06-22 15:02:37 -07002189 if (depth_ >= start_frame_) {
2190 JDWP::FrameId frame_id(GetFrameId());
2191 JDWP::JdwpLocation location;
2192 SetLocation(location, GetMethod(), GetDexPc());
Ian Rogersef7d42f2014-01-06 12:55:46 -08002193 VLOG(jdwp) << StringPrintf(" Frame %3zd: id=%3" PRIu64 " ", depth_, frame_id) << location;
Elliott Hughes6e9d22c2012-06-22 15:02:37 -07002194 expandBufAdd8BE(buf_, frame_id);
2195 expandBufAddLocation(buf_, location);
2196 }
2197 ++depth_;
Elliott Hughes530fa002012-03-12 11:44:49 -07002198 return true;
Elliott Hughes03181a82011-11-17 17:22:21 -08002199 }
Elliott Hughes6e9d22c2012-06-22 15:02:37 -07002200
2201 private:
2202 size_t depth_;
2203 const size_t start_frame_;
2204 const size_t frame_count_;
2205 JDWP::ExpandBuf* buf_;
Elliott Hughes03181a82011-11-17 17:22:21 -08002206 };
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002207
2208 ScopedObjectAccessUnchecked soa(Thread::Current());
jeffhaoa77f0f62012-12-05 17:19:31 -08002209 MutexLock mu(soa.Self(), *Locks::thread_list_lock_);
Elliott Hughes221229c2013-01-08 18:17:50 -08002210 Thread* thread;
2211 JDWP::JdwpError error = DecodeThread(soa, thread_id, thread);
2212 if (error != JDWP::ERR_NONE) {
2213 return error;
2214 }
Elliott Hughesf15f4a02013-01-09 10:09:38 -08002215 if (!IsSuspendedForDebugger(soa, thread)) {
2216 return JDWP::ERR_THREAD_NOT_SUSPENDED;
2217 }
Ian Rogers7a22fa62013-01-23 12:16:16 -08002218 GetFrameVisitor visitor(thread, start_frame, frame_count, buf);
Ian Rogers0399dde2012-06-06 17:09:28 -07002219 visitor.WalkStack();
Elliott Hughes6e9d22c2012-06-22 15:02:37 -07002220 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002221}
2222
2223JDWP::ObjectId Dbg::GetThreadSelfId() {
Mathieu Chartierdbe6f462012-09-25 16:54:50 -07002224 ScopedObjectAccessUnchecked soa(Thread::Current());
Ian Rogerscfaa4552012-11-26 21:00:08 -08002225 return gRegistry->Add(soa.Self()->GetPeer());
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002226}
2227
Elliott Hughes475fc232011-10-25 15:00:35 -07002228void Dbg::SuspendVM() {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002229 Runtime::Current()->GetThreadList()->SuspendAllForDebugger();
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002230}
2231
2232void Dbg::ResumeVM() {
Elliott Hughesc61a2672012-06-21 14:52:29 -07002233 Runtime::Current()->GetThreadList()->UndoDebuggerSuspensions();
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002234}
2235
Elliott Hughes221229c2013-01-08 18:17:50 -08002236JDWP::JdwpError Dbg::SuspendThread(JDWP::ObjectId thread_id, bool request_suspension) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002237 ScopedLocalRef<jobject> peer(Thread::Current()->GetJniEnv(), NULL);
2238 {
2239 ScopedObjectAccess soa(Thread::Current());
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002240 peer.reset(soa.AddLocalReference<jobject>(gRegistry->Get<mirror::Object*>(thread_id)));
Elliott Hughes4e235312011-12-02 11:34:15 -08002241 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002242 if (peer.get() == NULL) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002243 return JDWP::ERR_THREAD_NOT_ALIVE;
2244 }
2245 // Suspend thread to build stack trace.
Elliott Hughesf327e072013-01-09 16:01:26 -08002246 bool timed_out;
Ian Rogersd9c4fc92013-10-01 19:45:43 -07002247 Thread* thread = ThreadList::SuspendThreadByPeer(peer.get(), request_suspension, true,
2248 &timed_out);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002249 if (thread != NULL) {
2250 return JDWP::ERR_NONE;
Elliott Hughesf327e072013-01-09 16:01:26 -08002251 } else if (timed_out) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002252 return JDWP::ERR_INTERNAL;
2253 } else {
2254 return JDWP::ERR_THREAD_NOT_ALIVE;
2255 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002256}
2257
Elliott Hughes221229c2013-01-08 18:17:50 -08002258void Dbg::ResumeThread(JDWP::ObjectId thread_id) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002259 ScopedObjectAccessUnchecked soa(Thread::Current());
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002260 mirror::Object* peer = gRegistry->Get<mirror::Object*>(thread_id);
jeffhaoa77f0f62012-12-05 17:19:31 -08002261 Thread* thread;
2262 {
2263 MutexLock mu(soa.Self(), *Locks::thread_list_lock_);
2264 thread = Thread::FromManagedThread(soa, peer);
2265 }
Elliott Hughes4e235312011-12-02 11:34:15 -08002266 if (thread == NULL) {
2267 LOG(WARNING) << "No such thread for resume: " << peer;
2268 return;
2269 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002270 bool needs_resume;
2271 {
Ian Rogers50b35e22012-10-04 10:09:15 -07002272 MutexLock mu2(soa.Self(), *Locks::thread_suspend_count_lock_);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002273 needs_resume = thread->GetSuspendCount() > 0;
2274 }
2275 if (needs_resume) {
Elliott Hughes546b9862012-06-20 16:06:13 -07002276 Runtime::Current()->GetThreadList()->Resume(thread, true);
2277 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002278}
2279
2280void Dbg::SuspendSelf() {
Elliott Hughes475fc232011-10-25 15:00:35 -07002281 Runtime::Current()->GetThreadList()->SuspendSelfForDebugger();
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002282}
2283
Ian Rogers0399dde2012-06-06 17:09:28 -07002284struct GetThisVisitor : public StackVisitor {
Ian Rogers7a22fa62013-01-23 12:16:16 -08002285 GetThisVisitor(Thread* thread, Context* context, JDWP::FrameId frame_id)
Ian Rogersb726dcb2012-09-05 08:57:23 -07002286 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_)
Ian Rogers7a22fa62013-01-23 12:16:16 -08002287 : StackVisitor(thread, context), this_object(NULL), frame_id(frame_id) {}
Ian Rogers0399dde2012-06-06 17:09:28 -07002288
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002289 // TODO: Enable annotalysis. We know lock is held in constructor, but abstraction confuses
2290 // annotalysis.
2291 virtual bool VisitFrame() NO_THREAD_SAFETY_ANALYSIS {
Elliott Hughes6e9d22c2012-06-22 15:02:37 -07002292 if (frame_id != GetFrameId()) {
Ian Rogers0399dde2012-06-06 17:09:28 -07002293 return true; // continue
Ian Rogers0399dde2012-06-06 17:09:28 -07002294 } else {
Ian Rogers62d6c772013-02-27 08:32:07 -08002295 this_object = GetThisObject();
2296 return false;
Ian Rogers0399dde2012-06-06 17:09:28 -07002297 }
Elliott Hughes86b00102011-12-05 17:54:26 -08002298 }
Ian Rogers0399dde2012-06-06 17:09:28 -07002299
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002300 mirror::Object* this_object;
Elliott Hughes6e9d22c2012-06-22 15:02:37 -07002301 JDWP::FrameId frame_id;
Ian Rogers0399dde2012-06-06 17:09:28 -07002302};
2303
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002304JDWP::JdwpError Dbg::GetThisObject(JDWP::ObjectId thread_id, JDWP::FrameId frame_id,
2305 JDWP::ObjectId* result) {
2306 ScopedObjectAccessUnchecked soa(Thread::Current());
2307 Thread* thread;
2308 {
Ian Rogers50b35e22012-10-04 10:09:15 -07002309 MutexLock mu(soa.Self(), *Locks::thread_list_lock_);
Elliott Hughes221229c2013-01-08 18:17:50 -08002310 JDWP::JdwpError error = DecodeThread(soa, thread_id, thread);
2311 if (error != JDWP::ERR_NONE) {
2312 return error;
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002313 }
Elliott Hughes9e0c1752013-01-09 14:02:58 -08002314 if (!IsSuspendedForDebugger(soa, thread)) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002315 return JDWP::ERR_THREAD_NOT_SUSPENDED;
2316 }
Elliott Hughes6e9d22c2012-06-22 15:02:37 -07002317 }
Ian Rogers700a4022014-05-19 16:49:03 -07002318 std::unique_ptr<Context> context(Context::Create());
Ian Rogers7a22fa62013-01-23 12:16:16 -08002319 GetThisVisitor visitor(thread, context.get(), frame_id);
Ian Rogers0399dde2012-06-06 17:09:28 -07002320 visitor.WalkStack();
Elliott Hughes6e9d22c2012-06-22 15:02:37 -07002321 *result = gRegistry->Add(visitor.this_object);
2322 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002323}
2324
Sebastien Hertzcb19ebf2014-03-11 15:26:35 +01002325JDWP::JdwpError Dbg::GetLocalValue(JDWP::ObjectId thread_id, JDWP::FrameId frame_id, int slot,
2326 JDWP::JdwpTag tag, uint8_t* buf, size_t width) {
Ian Rogers0399dde2012-06-06 17:09:28 -07002327 struct GetLocalVisitor : public StackVisitor {
Ian Rogers98379392014-02-24 16:53:16 -08002328 GetLocalVisitor(const ScopedObjectAccessUnchecked& soa, Thread* thread, Context* context,
2329 JDWP::FrameId frame_id, int slot, JDWP::JdwpTag tag, uint8_t* buf, size_t width)
Ian Rogersb726dcb2012-09-05 08:57:23 -07002330 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_)
Ian Rogers98379392014-02-24 16:53:16 -08002331 : StackVisitor(thread, context), soa_(soa), frame_id_(frame_id), slot_(slot), tag_(tag),
Sebastien Hertzcb19ebf2014-03-11 15:26:35 +01002332 buf_(buf), width_(width), error_(JDWP::ERR_NONE) {}
Ian Rogersca190662012-06-26 15:45:57 -07002333
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002334 // TODO: Enable annotalysis. We know lock is held in constructor, but abstraction confuses
2335 // annotalysis.
2336 bool VisitFrame() NO_THREAD_SAFETY_ANALYSIS {
Ian Rogers0399dde2012-06-06 17:09:28 -07002337 if (GetFrameId() != frame_id_) {
2338 return true; // Not our frame, carry on.
Elliott Hughesdbb40792011-11-18 17:05:22 -08002339 }
Ian Rogers0399dde2012-06-06 17:09:28 -07002340 // TODO: check that the tag is compatible with the actual type of the slot!
Sebastien Hertzcb19ebf2014-03-11 15:26:35 +01002341 // TODO: check slot is valid for this method or return INVALID_SLOT error.
Brian Carlstromea46f952013-07-30 01:26:50 -07002342 mirror::ArtMethod* m = GetMethod();
Sebastien Hertzcb19ebf2014-03-11 15:26:35 +01002343 if (m->IsNative()) {
2344 // We can't read local value from native method.
2345 error_ = JDWP::ERR_OPAQUE_FRAME;
2346 return false;
2347 }
Ian Rogers0399dde2012-06-06 17:09:28 -07002348 uint16_t reg = DemangleSlot(slot_, m);
Sebastien Hertz0bcb2902014-06-17 15:52:45 +02002349 constexpr JDWP::JdwpError kFailureErrorCode = JDWP::ERR_ABSENT_INFORMATION;
Ian Rogers0399dde2012-06-06 17:09:28 -07002350 switch (tag_) {
Sebastien Hertz0bcb2902014-06-17 15:52:45 +02002351 case JDWP::JT_BOOLEAN: {
Ian Rogers0399dde2012-06-06 17:09:28 -07002352 CHECK_EQ(width_, 1U);
Sebastien Hertz0bcb2902014-06-17 15:52:45 +02002353 uint32_t intVal;
2354 if (GetVReg(m, reg, kIntVReg, &intVal)) {
2355 VLOG(jdwp) << "get boolean local " << reg << " = " << intVal;
2356 JDWP::Set1(buf_+1, intVal != 0);
2357 } else {
2358 VLOG(jdwp) << "failed to get boolean local " << reg;
2359 error_ = kFailureErrorCode;
2360 }
2361 break;
Ian Rogers0399dde2012-06-06 17:09:28 -07002362 }
Sebastien Hertz0bcb2902014-06-17 15:52:45 +02002363 case JDWP::JT_BYTE: {
Ian Rogers0399dde2012-06-06 17:09:28 -07002364 CHECK_EQ(width_, 1U);
Sebastien Hertz0bcb2902014-06-17 15:52:45 +02002365 uint32_t intVal;
2366 if (GetVReg(m, reg, kIntVReg, &intVal)) {
2367 VLOG(jdwp) << "get byte local " << reg << " = " << intVal;
2368 JDWP::Set1(buf_+1, intVal);
2369 } else {
2370 VLOG(jdwp) << "failed to get byte local " << reg;
2371 error_ = kFailureErrorCode;
2372 }
2373 break;
Ian Rogers0399dde2012-06-06 17:09:28 -07002374 }
Sebastien Hertz0bcb2902014-06-17 15:52:45 +02002375 case JDWP::JT_SHORT:
2376 case JDWP::JT_CHAR: {
Ian Rogers0399dde2012-06-06 17:09:28 -07002377 CHECK_EQ(width_, 2U);
Sebastien Hertz0bcb2902014-06-17 15:52:45 +02002378 uint32_t intVal;
2379 if (GetVReg(m, reg, kIntVReg, &intVal)) {
2380 VLOG(jdwp) << "get short/char local " << reg << " = " << intVal;
2381 JDWP::Set2BE(buf_+1, intVal);
2382 } else {
2383 VLOG(jdwp) << "failed to get short/char local " << reg;
2384 error_ = kFailureErrorCode;
Sebastien Hertzaa9b3ae2014-06-13 14:49:27 +02002385 }
Sebastien Hertz0bcb2902014-06-17 15:52:45 +02002386 break;
Sebastien Hertzaa9b3ae2014-06-13 14:49:27 +02002387 }
Sebastien Hertz0bcb2902014-06-17 15:52:45 +02002388 case JDWP::JT_INT: {
2389 CHECK_EQ(width_, 4U);
2390 uint32_t intVal;
2391 if (GetVReg(m, reg, kIntVReg, &intVal)) {
2392 VLOG(jdwp) << "get int local " << reg << " = " << intVal;
2393 JDWP::Set4BE(buf_+1, intVal);
2394 } else {
2395 VLOG(jdwp) << "failed to get int local " << reg;
2396 error_ = kFailureErrorCode;
Sebastien Hertz8ebd94a2014-06-17 09:49:21 +00002397 }
Sebastien Hertz0bcb2902014-06-17 15:52:45 +02002398 break;
Sebastien Hertz8ebd94a2014-06-17 09:49:21 +00002399 }
Sebastien Hertz0bcb2902014-06-17 15:52:45 +02002400 case JDWP::JT_FLOAT: {
2401 CHECK_EQ(width_, 4U);
2402 uint32_t intVal;
2403 if (GetVReg(m, reg, kFloatVReg, &intVal)) {
2404 VLOG(jdwp) << "get float local " << reg << " = " << intVal;
2405 JDWP::Set4BE(buf_+1, intVal);
2406 } else {
2407 VLOG(jdwp) << "failed to get float local " << reg;
2408 error_ = kFailureErrorCode;
2409 }
2410 break;
2411 }
2412 case JDWP::JT_ARRAY:
2413 case JDWP::JT_CLASS_LOADER:
2414 case JDWP::JT_CLASS_OBJECT:
2415 case JDWP::JT_OBJECT:
2416 case JDWP::JT_STRING:
2417 case JDWP::JT_THREAD:
2418 case JDWP::JT_THREAD_GROUP: {
2419 CHECK_EQ(width_, sizeof(JDWP::ObjectId));
2420 uint32_t intVal;
2421 if (GetVReg(m, reg, kReferenceVReg, &intVal)) {
2422 mirror::Object* o = reinterpret_cast<mirror::Object*>(intVal);
2423 VLOG(jdwp) << "get " << tag_ << " object local " << reg << " = " << o;
2424 if (!Runtime::Current()->GetHeap()->IsValidObjectAddress(o)) {
2425 LOG(FATAL) << "Register " << reg << " expected to hold " << tag_ << " object: " << o;
2426 }
2427 tag_ = TagFromObject(soa_, o);
2428 JDWP::SetObjectId(buf_+1, gRegistry->Add(o));
2429 } else {
2430 VLOG(jdwp) << "failed to get " << tag_ << " object local " << reg;
2431 error_ = kFailureErrorCode;
2432 }
2433 break;
2434 }
2435 case JDWP::JT_DOUBLE: {
Ian Rogers2bcb4a42012-11-08 10:39:18 -08002436 CHECK_EQ(width_, 8U);
Sebastien Hertz0bcb2902014-06-17 15:52:45 +02002437 uint32_t lo;
2438 uint32_t hi;
2439 if (GetVReg(m, reg, kDoubleLoVReg, &lo) && GetVReg(m, reg + 1, kDoubleHiVReg, &hi)) {
2440 uint64_t longVal = (static_cast<uint64_t>(hi) << 32) | lo;
2441 VLOG(jdwp) << "get double local " << reg << " = "
2442 << hi << ":" << lo << " = " << longVal;
2443 JDWP::Set8BE(buf_+1, longVal);
2444 } else {
2445 VLOG(jdwp) << "failed to get double local " << reg;
2446 error_ = kFailureErrorCode;
2447 }
2448 break;
Ian Rogers2bcb4a42012-11-08 10:39:18 -08002449 }
Sebastien Hertz0bcb2902014-06-17 15:52:45 +02002450 case JDWP::JT_LONG: {
Ian Rogers0399dde2012-06-06 17:09:28 -07002451 CHECK_EQ(width_, 8U);
Sebastien Hertz0bcb2902014-06-17 15:52:45 +02002452 uint32_t lo;
2453 uint32_t hi;
2454 if (GetVReg(m, reg, kLongLoVReg, &lo) && GetVReg(m, reg + 1, kLongHiVReg, &hi)) {
2455 uint64_t longVal = (static_cast<uint64_t>(hi) << 32) | lo;
2456 VLOG(jdwp) << "get long local " << reg << " = "
2457 << hi << ":" << lo << " = " << longVal;
2458 JDWP::Set8BE(buf_+1, longVal);
2459 } else {
2460 VLOG(jdwp) << "failed to get long local " << reg;
2461 error_ = kFailureErrorCode;
2462 }
2463 break;
Ian Rogers0399dde2012-06-06 17:09:28 -07002464 }
Sebastien Hertz0bcb2902014-06-17 15:52:45 +02002465 default:
2466 LOG(FATAL) << "Unknown tag " << tag_;
2467 break;
Ian Rogers0399dde2012-06-06 17:09:28 -07002468 }
2469
2470 // Prepend tag, which may have been updated.
2471 JDWP::Set1(buf_, tag_);
2472 return false;
2473 }
Ian Rogers98379392014-02-24 16:53:16 -08002474 const ScopedObjectAccessUnchecked& soa_;
Ian Rogers0399dde2012-06-06 17:09:28 -07002475 const JDWP::FrameId frame_id_;
2476 const int slot_;
2477 JDWP::JdwpTag tag_;
2478 uint8_t* const buf_;
2479 const size_t width_;
Sebastien Hertzcb19ebf2014-03-11 15:26:35 +01002480 JDWP::JdwpError error_;
Ian Rogers0399dde2012-06-06 17:09:28 -07002481 };
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002482
2483 ScopedObjectAccessUnchecked soa(Thread::Current());
jeffhaoa77f0f62012-12-05 17:19:31 -08002484 MutexLock mu(soa.Self(), *Locks::thread_list_lock_);
Elliott Hughes221229c2013-01-08 18:17:50 -08002485 Thread* thread;
2486 JDWP::JdwpError error = DecodeThread(soa, thread_id, thread);
2487 if (error != JDWP::ERR_NONE) {
Sebastien Hertzcb19ebf2014-03-11 15:26:35 +01002488 return error;
Elliott Hughes221229c2013-01-08 18:17:50 -08002489 }
Sebastien Hertzcb19ebf2014-03-11 15:26:35 +01002490 // TODO check thread is suspended by the debugger ?
Ian Rogers700a4022014-05-19 16:49:03 -07002491 std::unique_ptr<Context> context(Context::Create());
Ian Rogers98379392014-02-24 16:53:16 -08002492 GetLocalVisitor visitor(soa, thread, context.get(), frame_id, slot, tag, buf, width);
Ian Rogers0399dde2012-06-06 17:09:28 -07002493 visitor.WalkStack();
Sebastien Hertzcb19ebf2014-03-11 15:26:35 +01002494 return visitor.error_;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002495}
2496
Sebastien Hertzcb19ebf2014-03-11 15:26:35 +01002497JDWP::JdwpError Dbg::SetLocalValue(JDWP::ObjectId thread_id, JDWP::FrameId frame_id, int slot,
2498 JDWP::JdwpTag tag, uint64_t value, size_t width) {
Ian Rogers0399dde2012-06-06 17:09:28 -07002499 struct SetLocalVisitor : public StackVisitor {
Ian Rogers7a22fa62013-01-23 12:16:16 -08002500 SetLocalVisitor(Thread* thread, Context* context,
Ian Rogers0399dde2012-06-06 17:09:28 -07002501 JDWP::FrameId frame_id, int slot, JDWP::JdwpTag tag, uint64_t value,
Ian Rogersca190662012-06-26 15:45:57 -07002502 size_t width)
Ian Rogersb726dcb2012-09-05 08:57:23 -07002503 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_)
Ian Rogers7a22fa62013-01-23 12:16:16 -08002504 : StackVisitor(thread, context),
Sebastien Hertzcb19ebf2014-03-11 15:26:35 +01002505 frame_id_(frame_id), slot_(slot), tag_(tag), value_(value), width_(width),
2506 error_(JDWP::ERR_NONE) {}
Ian Rogersca190662012-06-26 15:45:57 -07002507
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002508 // TODO: Enable annotalysis. We know lock is held in constructor, but abstraction confuses
2509 // annotalysis.
2510 bool VisitFrame() NO_THREAD_SAFETY_ANALYSIS {
Ian Rogers0399dde2012-06-06 17:09:28 -07002511 if (GetFrameId() != frame_id_) {
2512 return true; // Not our frame, carry on.
2513 }
2514 // TODO: check that the tag is compatible with the actual type of the slot!
Sebastien Hertzcb19ebf2014-03-11 15:26:35 +01002515 // TODO: check slot is valid for this method or return INVALID_SLOT error.
Brian Carlstromea46f952013-07-30 01:26:50 -07002516 mirror::ArtMethod* m = GetMethod();
Sebastien Hertzcb19ebf2014-03-11 15:26:35 +01002517 if (m->IsNative()) {
2518 // We can't read local value from native method.
2519 error_ = JDWP::ERR_OPAQUE_FRAME;
2520 return false;
2521 }
Ian Rogers0399dde2012-06-06 17:09:28 -07002522 uint16_t reg = DemangleSlot(slot_, m);
Sebastien Hertz0bcb2902014-06-17 15:52:45 +02002523 constexpr JDWP::JdwpError kFailureErrorCode = JDWP::ERR_ABSENT_INFORMATION;
Ian Rogers0399dde2012-06-06 17:09:28 -07002524 switch (tag_) {
2525 case JDWP::JT_BOOLEAN:
2526 case JDWP::JT_BYTE:
2527 CHECK_EQ(width_, 1U);
Sebastien Hertz0bcb2902014-06-17 15:52:45 +02002528 if (!SetVReg(m, reg, static_cast<uint32_t>(value_), kIntVReg)) {
2529 VLOG(jdwp) << "failed to set boolean/byte local " << reg << " = "
2530 << static_cast<uint32_t>(value_);
2531 error_ = kFailureErrorCode;
2532 }
Ian Rogers0399dde2012-06-06 17:09:28 -07002533 break;
2534 case JDWP::JT_SHORT:
2535 case JDWP::JT_CHAR:
2536 CHECK_EQ(width_, 2U);
Sebastien Hertz0bcb2902014-06-17 15:52:45 +02002537 if (!SetVReg(m, reg, static_cast<uint32_t>(value_), kIntVReg)) {
2538 VLOG(jdwp) << "failed to set short/char local " << reg << " = "
2539 << static_cast<uint32_t>(value_);
2540 error_ = kFailureErrorCode;
2541 }
Ian Rogers0399dde2012-06-06 17:09:28 -07002542 break;
2543 case JDWP::JT_INT:
Ian Rogers2bcb4a42012-11-08 10:39:18 -08002544 CHECK_EQ(width_, 4U);
Sebastien Hertz0bcb2902014-06-17 15:52:45 +02002545 if (!SetVReg(m, reg, static_cast<uint32_t>(value_), kIntVReg)) {
2546 VLOG(jdwp) << "failed to set int local " << reg << " = "
2547 << static_cast<uint32_t>(value_);
2548 error_ = kFailureErrorCode;
2549 }
Ian Rogers2bcb4a42012-11-08 10:39:18 -08002550 break;
Ian Rogers0399dde2012-06-06 17:09:28 -07002551 case JDWP::JT_FLOAT:
2552 CHECK_EQ(width_, 4U);
Sebastien Hertz0bcb2902014-06-17 15:52:45 +02002553 if (!SetVReg(m, reg, static_cast<uint32_t>(value_), kFloatVReg)) {
2554 VLOG(jdwp) << "failed to set float local " << reg << " = "
2555 << static_cast<uint32_t>(value_);
2556 error_ = kFailureErrorCode;
2557 }
Ian Rogers0399dde2012-06-06 17:09:28 -07002558 break;
2559 case JDWP::JT_ARRAY:
Sebastien Hertz0bcb2902014-06-17 15:52:45 +02002560 case JDWP::JT_CLASS_LOADER:
2561 case JDWP::JT_CLASS_OBJECT:
Ian Rogers0399dde2012-06-06 17:09:28 -07002562 case JDWP::JT_OBJECT:
2563 case JDWP::JT_STRING:
Sebastien Hertz0bcb2902014-06-17 15:52:45 +02002564 case JDWP::JT_THREAD:
2565 case JDWP::JT_THREAD_GROUP: {
Ian Rogers0399dde2012-06-06 17:09:28 -07002566 CHECK_EQ(width_, sizeof(JDWP::ObjectId));
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002567 mirror::Object* o = gRegistry->Get<mirror::Object*>(static_cast<JDWP::ObjectId>(value_));
Elliott Hughes64f574f2013-02-20 14:57:12 -08002568 if (o == ObjectRegistry::kInvalidObject) {
Sebastien Hertz0bcb2902014-06-17 15:52:45 +02002569 VLOG(jdwp) << tag_ << " object " << o << " is an invalid object";
2570 error_ = JDWP::ERR_INVALID_OBJECT;
2571 } else if (!SetVReg(m, reg, static_cast<uint32_t>(reinterpret_cast<uintptr_t>(o)),
2572 kReferenceVReg)) {
2573 VLOG(jdwp) << "failed to set " << tag_ << " object local " << reg << " = " << o;
2574 error_ = kFailureErrorCode;
Ian Rogers0399dde2012-06-06 17:09:28 -07002575 }
Sebastien Hertz0bcb2902014-06-17 15:52:45 +02002576 break;
Ian Rogers0399dde2012-06-06 17:09:28 -07002577 }
Sebastien Hertz0bcb2902014-06-17 15:52:45 +02002578 case JDWP::JT_DOUBLE: {
Ian Rogers2bcb4a42012-11-08 10:39:18 -08002579 CHECK_EQ(width_, 8U);
Sebastien Hertz0bcb2902014-06-17 15:52:45 +02002580 const uint32_t lo = static_cast<uint32_t>(value_);
2581 const uint32_t hi = static_cast<uint32_t>(value_ >> 32);
2582 bool success = SetVReg(m, reg, lo, kDoubleLoVReg);
2583 success &= SetVReg(m, reg + 1, hi, kDoubleHiVReg);
2584 if (!success) {
2585 uint64_t longVal = (static_cast<uint64_t>(hi) << 32) | lo;
2586 VLOG(jdwp) << "failed to set double local " << reg << " = "
2587 << hi << ":" << lo << " = " << longVal;
2588 error_ = kFailureErrorCode;
2589 }
Ian Rogers2bcb4a42012-11-08 10:39:18 -08002590 break;
Sebastien Hertz0bcb2902014-06-17 15:52:45 +02002591 }
2592 case JDWP::JT_LONG: {
Ian Rogers0399dde2012-06-06 17:09:28 -07002593 CHECK_EQ(width_, 8U);
Sebastien Hertz0bcb2902014-06-17 15:52:45 +02002594 const uint32_t lo = static_cast<uint32_t>(value_);
2595 const uint32_t hi = static_cast<uint32_t>(value_ >> 32);
2596 bool success = SetVReg(m, reg, lo, kLongLoVReg);
2597 success &= SetVReg(m, reg + 1, hi, kLongHiVReg);
2598 if (!success) {
2599 uint64_t longVal = (static_cast<uint64_t>(hi) << 32) | lo;
2600 VLOG(jdwp) << "failed to set double local " << reg << " = "
2601 << hi << ":" << lo << " = " << longVal;
2602 error_ = kFailureErrorCode;
2603 }
Ian Rogers0399dde2012-06-06 17:09:28 -07002604 break;
Sebastien Hertz0bcb2902014-06-17 15:52:45 +02002605 }
Ian Rogers0399dde2012-06-06 17:09:28 -07002606 default:
2607 LOG(FATAL) << "Unknown tag " << tag_;
2608 break;
2609 }
2610 return false;
2611 }
2612
2613 const JDWP::FrameId frame_id_;
2614 const int slot_;
2615 const JDWP::JdwpTag tag_;
2616 const uint64_t value_;
2617 const size_t width_;
Sebastien Hertzcb19ebf2014-03-11 15:26:35 +01002618 JDWP::JdwpError error_;
Ian Rogers0399dde2012-06-06 17:09:28 -07002619 };
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002620
2621 ScopedObjectAccessUnchecked soa(Thread::Current());
jeffhaoa77f0f62012-12-05 17:19:31 -08002622 MutexLock mu(soa.Self(), *Locks::thread_list_lock_);
Elliott Hughes221229c2013-01-08 18:17:50 -08002623 Thread* thread;
2624 JDWP::JdwpError error = DecodeThread(soa, thread_id, thread);
2625 if (error != JDWP::ERR_NONE) {
Sebastien Hertzcb19ebf2014-03-11 15:26:35 +01002626 return error;
Elliott Hughes221229c2013-01-08 18:17:50 -08002627 }
Sebastien Hertzcb19ebf2014-03-11 15:26:35 +01002628 // TODO check thread is suspended by the debugger ?
Ian Rogers700a4022014-05-19 16:49:03 -07002629 std::unique_ptr<Context> context(Context::Create());
Ian Rogers7a22fa62013-01-23 12:16:16 -08002630 SetLocalVisitor visitor(thread, context.get(), frame_id, slot, tag, value, width);
Ian Rogers0399dde2012-06-06 17:09:28 -07002631 visitor.WalkStack();
Sebastien Hertzcb19ebf2014-03-11 15:26:35 +01002632 return visitor.error_;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002633}
2634
Sebastien Hertz3f52eaf2014-04-04 17:50:18 +02002635JDWP::ObjectId Dbg::GetThisObjectIdForEvent(mirror::Object* this_object) {
2636 // If 'this_object' isn't already in the registry, we know that we're not looking for it, so
2637 // there's no point adding it to the registry and burning through ids.
2638 // When registering an event request with an instance filter, we've been given an existing object
2639 // id so it must already be present in the registry when the event fires.
2640 JDWP::ObjectId this_id = 0;
2641 if (this_object != nullptr && gRegistry->Contains(this_object)) {
2642 this_id = gRegistry->Add(this_object);
2643 }
2644 return this_id;
2645}
2646
Ian Rogersef7d42f2014-01-06 12:55:46 -08002647void Dbg::PostLocationEvent(mirror::ArtMethod* m, int dex_pc, mirror::Object* this_object,
Jeff Hao579b0242013-11-18 13:16:49 -08002648 int event_flags, const JValue* return_value) {
Sebastien Hertz3f52eaf2014-04-04 17:50:18 +02002649 if (!IsDebuggerActive()) {
2650 return;
2651 }
2652 DCHECK(m != nullptr);
2653 DCHECK_EQ(m->IsStatic(), this_object == nullptr);
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08002654 JDWP::JdwpLocation location;
Sebastien Hertzcb19ebf2014-03-11 15:26:35 +01002655 SetLocation(location, m, dex_pc);
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08002656
Sebastien Hertz3f52eaf2014-04-04 17:50:18 +02002657 // We need 'this' for InstanceOnly filters only.
2658 JDWP::ObjectId this_id = GetThisObjectIdForEvent(this_object);
Jeff Hao579b0242013-11-18 13:16:49 -08002659 gJdwpState->PostLocationEvent(&location, this_id, event_flags, return_value);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002660}
2661
Sebastien Hertz3f52eaf2014-04-04 17:50:18 +02002662void Dbg::PostFieldAccessEvent(mirror::ArtMethod* m, int dex_pc,
2663 mirror::Object* this_object, mirror::ArtField* f) {
2664 if (!IsDebuggerActive()) {
2665 return;
2666 }
2667 DCHECK(m != nullptr);
2668 DCHECK(f != nullptr);
2669 JDWP::JdwpLocation location;
2670 SetLocation(location, m, dex_pc);
2671
2672 JDWP::RefTypeId type_id = gRegistry->AddRefType(f->GetDeclaringClass());
2673 JDWP::FieldId field_id = ToFieldId(f);
2674 JDWP::ObjectId this_id = gRegistry->Add(this_object);
2675
2676 gJdwpState->PostFieldEvent(&location, type_id, field_id, this_id, nullptr, false);
2677}
2678
2679void Dbg::PostFieldModificationEvent(mirror::ArtMethod* m, int dex_pc,
2680 mirror::Object* this_object, mirror::ArtField* f,
2681 const JValue* field_value) {
2682 if (!IsDebuggerActive()) {
2683 return;
2684 }
2685 DCHECK(m != nullptr);
2686 DCHECK(f != nullptr);
2687 DCHECK(field_value != nullptr);
2688 JDWP::JdwpLocation location;
2689 SetLocation(location, m, dex_pc);
2690
2691 JDWP::RefTypeId type_id = gRegistry->AddRefType(f->GetDeclaringClass());
2692 JDWP::FieldId field_id = ToFieldId(f);
2693 JDWP::ObjectId this_id = gRegistry->Add(this_object);
2694
2695 gJdwpState->PostFieldEvent(&location, type_id, field_id, this_id, field_value, true);
2696}
2697
2698void Dbg::PostException(const ThrowLocation& throw_location,
Brian Carlstromea46f952013-07-30 01:26:50 -07002699 mirror::ArtMethod* catch_method,
Elliott Hughes64f574f2013-02-20 14:57:12 -08002700 uint32_t catch_dex_pc, mirror::Throwable* exception_object) {
Elliott Hughesc0f09332012-03-26 13:27:06 -07002701 if (!IsDebuggerActive()) {
Ian Rogers0ad5bb82011-12-07 10:16:32 -08002702 return;
2703 }
Elliott Hughes4740cdf2011-12-07 14:07:12 -08002704
Ian Rogers62d6c772013-02-27 08:32:07 -08002705 JDWP::JdwpLocation jdwp_throw_location;
2706 SetLocation(jdwp_throw_location, throw_location.GetMethod(), throw_location.GetDexPc());
Elliott Hughesd07986f2011-12-06 18:27:45 -08002707 JDWP::JdwpLocation catch_location;
Elliott Hughescaf76542012-06-28 16:08:22 -07002708 SetLocation(catch_location, catch_method, catch_dex_pc);
Elliott Hughesd07986f2011-12-06 18:27:45 -08002709
Sebastien Hertz3f52eaf2014-04-04 17:50:18 +02002710 // We need 'this' for InstanceOnly filters only.
2711 JDWP::ObjectId this_id = GetThisObjectIdForEvent(throw_location.GetThis());
Elliott Hughes64f574f2013-02-20 14:57:12 -08002712 JDWP::ObjectId exception_id = gRegistry->Add(exception_object);
2713 JDWP::RefTypeId exception_class_id = gRegistry->AddRefType(exception_object->GetClass());
Elliott Hughesd07986f2011-12-06 18:27:45 -08002714
Ian Rogers62d6c772013-02-27 08:32:07 -08002715 gJdwpState->PostException(&jdwp_throw_location, exception_id, exception_class_id, &catch_location,
2716 this_id);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002717}
2718
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002719void Dbg::PostClassPrepare(mirror::Class* c) {
Elliott Hughesc0f09332012-03-26 13:27:06 -07002720 if (!IsDebuggerActive()) {
Elliott Hughes4740cdf2011-12-07 14:07:12 -08002721 return;
2722 }
2723
Elliott Hughes3d30d9b2011-12-07 17:35:48 -08002724 // OLD-TODO - we currently always send both "verified" and "prepared" since
Elliott Hughes4740cdf2011-12-07 14:07:12 -08002725 // debuggers seem to like that. There might be some advantage to honesty,
2726 // since the class may not yet be verified.
2727 int state = JDWP::CS_VERIFIED | JDWP::CS_PREPARED;
Sebastien Hertz4d8fd492014-03-28 16:29:41 +01002728 JDWP::JdwpTypeTag tag = GetTypeTag(c);
Mathieu Chartierf8322842014-05-16 10:59:25 -07002729 gJdwpState->PostClassPrepare(tag, gRegistry->Add(c), c->GetDescriptor(), state);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002730}
2731
Ian Rogers62d6c772013-02-27 08:32:07 -08002732void Dbg::UpdateDebugger(Thread* thread, mirror::Object* this_object,
Sebastien Hertz8379b222014-02-24 17:38:15 +01002733 mirror::ArtMethod* m, uint32_t dex_pc,
2734 int event_flags, const JValue* return_value) {
Ian Rogers62d6c772013-02-27 08:32:07 -08002735 if (!IsDebuggerActive() || dex_pc == static_cast<uint32_t>(-2) /* fake method exit */) {
Elliott Hughes2aa2e392012-02-17 17:15:43 -08002736 return;
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08002737 }
2738
Elliott Hughes86964332012-02-15 19:37:42 -08002739 if (IsBreakpoint(m, dex_pc)) {
2740 event_flags |= kBreakpoint;
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08002741 }
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08002742
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01002743 // If the debugger is single-stepping one of our threads, check to
2744 // see if we're that thread and we've reached a step point.
2745 const SingleStepControl* single_step_control = thread->GetSingleStepControl();
2746 DCHECK(single_step_control != nullptr);
2747 if (single_step_control->is_active) {
2748 CHECK(!m->IsNative());
2749 if (single_step_control->step_depth == JDWP::SD_INTO) {
2750 // Step into method calls. We break when the line number
2751 // or method pointer changes. If we're in SS_MIN mode, we
2752 // always stop.
2753 if (single_step_control->method != m) {
2754 event_flags |= kSingleStep;
2755 VLOG(jdwp) << "SS new method";
2756 } else if (single_step_control->step_size == JDWP::SS_MIN) {
2757 event_flags |= kSingleStep;
2758 VLOG(jdwp) << "SS new instruction";
Sebastien Hertzbb43b432014-04-14 11:59:08 +02002759 } else if (single_step_control->ContainsDexPc(dex_pc)) {
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01002760 event_flags |= kSingleStep;
2761 VLOG(jdwp) << "SS new line";
2762 }
2763 } else if (single_step_control->step_depth == JDWP::SD_OVER) {
2764 // Step over method calls. We break when the line number is
2765 // different and the frame depth is <= the original frame
2766 // depth. (We can't just compare on the method, because we
2767 // might get unrolled past it by an exception, and it's tricky
2768 // to identify recursion.)
2769
2770 int stack_depth = GetStackDepth(thread);
2771
2772 if (stack_depth < single_step_control->stack_depth) {
2773 // Popped up one or more frames, always trigger.
2774 event_flags |= kSingleStep;
2775 VLOG(jdwp) << "SS method pop";
2776 } else if (stack_depth == single_step_control->stack_depth) {
2777 // Same depth, see if we moved.
2778 if (single_step_control->step_size == JDWP::SS_MIN) {
Elliott Hughes86964332012-02-15 19:37:42 -08002779 event_flags |= kSingleStep;
2780 VLOG(jdwp) << "SS new instruction";
Sebastien Hertzbb43b432014-04-14 11:59:08 +02002781 } else if (single_step_control->ContainsDexPc(dex_pc)) {
Elliott Hughes2435a572012-02-17 16:07:41 -08002782 event_flags |= kSingleStep;
2783 VLOG(jdwp) << "SS new line";
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08002784 }
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01002785 }
2786 } else {
2787 CHECK_EQ(single_step_control->step_depth, JDWP::SD_OUT);
2788 // Return from the current method. We break when the frame
2789 // depth pops up.
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08002790
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01002791 // This differs from the "method exit" break in that it stops
2792 // with the PC at the next instruction in the returned-to
2793 // function, rather than the end of the returning function.
Elliott Hughes86964332012-02-15 19:37:42 -08002794
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01002795 int stack_depth = GetStackDepth(thread);
2796 if (stack_depth < single_step_control->stack_depth) {
2797 event_flags |= kSingleStep;
2798 VLOG(jdwp) << "SS method pop";
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08002799 }
2800 }
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08002801 }
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08002802
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08002803 // If there's something interesting going on, see if it matches one
2804 // of the debugger filters.
2805 if (event_flags != 0) {
Sebastien Hertz8379b222014-02-24 17:38:15 +01002806 Dbg::PostLocationEvent(m, dex_pc, this_object, event_flags, return_value);
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08002807 }
2808}
2809
Sebastien Hertz42cd43f2014-05-13 14:15:41 +02002810size_t* Dbg::GetReferenceCounterForEvent(uint32_t instrumentation_event) {
2811 switch (instrumentation_event) {
2812 case instrumentation::Instrumentation::kMethodEntered:
2813 return &method_enter_event_ref_count_;
2814 case instrumentation::Instrumentation::kMethodExited:
2815 return &method_exit_event_ref_count_;
2816 case instrumentation::Instrumentation::kDexPcMoved:
2817 return &dex_pc_change_event_ref_count_;
2818 case instrumentation::Instrumentation::kFieldRead:
2819 return &field_read_event_ref_count_;
2820 case instrumentation::Instrumentation::kFieldWritten:
2821 return &field_write_event_ref_count_;
2822 case instrumentation::Instrumentation::kExceptionCaught:
2823 return &exception_catch_event_ref_count_;
2824 default:
2825 return nullptr;
2826 }
2827}
2828
Sebastien Hertz4d25df32014-03-21 17:44:46 +01002829// Process request while all mutator threads are suspended.
2830void Dbg::ProcessDeoptimizationRequest(const DeoptimizationRequest& request) {
Sebastien Hertz138dbfc2013-12-04 18:15:25 +01002831 instrumentation::Instrumentation* instrumentation = Runtime::Current()->GetInstrumentation();
Sebastien Hertz4d25df32014-03-21 17:44:46 +01002832 switch (request.kind) {
2833 case DeoptimizationRequest::kNothing:
2834 LOG(WARNING) << "Ignoring empty deoptimization request.";
2835 break;
Sebastien Hertz42cd43f2014-05-13 14:15:41 +02002836 case DeoptimizationRequest::kRegisterForEvent:
2837 VLOG(jdwp) << StringPrintf("Add debugger as listener for instrumentation event 0x%x",
2838 request.instrumentation_event);
2839 instrumentation->AddListener(&gDebugInstrumentationListener, request.instrumentation_event);
2840 instrumentation_events_ |= request.instrumentation_event;
2841 break;
2842 case DeoptimizationRequest::kUnregisterForEvent:
2843 VLOG(jdwp) << StringPrintf("Remove debugger as listener for instrumentation event 0x%x",
2844 request.instrumentation_event);
2845 instrumentation->RemoveListener(&gDebugInstrumentationListener,
2846 request.instrumentation_event);
2847 instrumentation_events_ &= ~request.instrumentation_event;
2848 break;
Sebastien Hertz4d25df32014-03-21 17:44:46 +01002849 case DeoptimizationRequest::kFullDeoptimization:
Sebastien Hertz7ec2f1c2014-03-27 20:06:47 +01002850 VLOG(jdwp) << "Deoptimize the world ...";
Sebastien Hertz4d25df32014-03-21 17:44:46 +01002851 instrumentation->DeoptimizeEverything();
Sebastien Hertz7ec2f1c2014-03-27 20:06:47 +01002852 VLOG(jdwp) << "Deoptimize the world DONE";
Sebastien Hertz4d25df32014-03-21 17:44:46 +01002853 break;
2854 case DeoptimizationRequest::kFullUndeoptimization:
Sebastien Hertz7ec2f1c2014-03-27 20:06:47 +01002855 VLOG(jdwp) << "Undeoptimize the world ...";
Sebastien Hertz4d25df32014-03-21 17:44:46 +01002856 instrumentation->UndeoptimizeEverything();
Sebastien Hertz7ec2f1c2014-03-27 20:06:47 +01002857 VLOG(jdwp) << "Undeoptimize the world DONE";
Sebastien Hertz4d25df32014-03-21 17:44:46 +01002858 break;
2859 case DeoptimizationRequest::kSelectiveDeoptimization:
Sebastien Hertz7ec2f1c2014-03-27 20:06:47 +01002860 VLOG(jdwp) << "Deoptimize method " << PrettyMethod(request.method) << " ...";
Sebastien Hertz4d25df32014-03-21 17:44:46 +01002861 instrumentation->Deoptimize(request.method);
Sebastien Hertz7ec2f1c2014-03-27 20:06:47 +01002862 VLOG(jdwp) << "Deoptimize method " << PrettyMethod(request.method) << " DONE";
Sebastien Hertz4d25df32014-03-21 17:44:46 +01002863 break;
2864 case DeoptimizationRequest::kSelectiveUndeoptimization:
Sebastien Hertz7ec2f1c2014-03-27 20:06:47 +01002865 VLOG(jdwp) << "Undeoptimize method " << PrettyMethod(request.method) << " ...";
Sebastien Hertz4d25df32014-03-21 17:44:46 +01002866 instrumentation->Undeoptimize(request.method);
Sebastien Hertz7ec2f1c2014-03-27 20:06:47 +01002867 VLOG(jdwp) << "Undeoptimize method " << PrettyMethod(request.method) << " DONE";
Sebastien Hertz4d25df32014-03-21 17:44:46 +01002868 break;
2869 default:
2870 LOG(FATAL) << "Unsupported deoptimization request kind " << request.kind;
2871 break;
Sebastien Hertz138dbfc2013-12-04 18:15:25 +01002872 }
Sebastien Hertz138dbfc2013-12-04 18:15:25 +01002873}
2874
Sebastien Hertz7ec2f1c2014-03-27 20:06:47 +01002875void Dbg::DelayFullUndeoptimization() {
2876 MutexLock mu(Thread::Current(), *deoptimization_lock_);
2877 ++delayed_full_undeoptimization_count_;
2878 DCHECK_LE(delayed_full_undeoptimization_count_, full_deoptimization_event_count_);
2879}
2880
2881void Dbg::ProcessDelayedFullUndeoptimizations() {
2882 // TODO: avoid taking the lock twice (once here and once in ManageDeoptimization).
2883 {
2884 MutexLock mu(Thread::Current(), *deoptimization_lock_);
2885 while (delayed_full_undeoptimization_count_ > 0) {
2886 DeoptimizationRequest req;
2887 req.kind = DeoptimizationRequest::kFullUndeoptimization;
2888 req.method = nullptr;
2889 RequestDeoptimizationLocked(req);
2890 --delayed_full_undeoptimization_count_;
2891 }
2892 }
2893 ManageDeoptimization();
2894}
2895
Sebastien Hertz4d25df32014-03-21 17:44:46 +01002896void Dbg::RequestDeoptimization(const DeoptimizationRequest& req) {
2897 if (req.kind == DeoptimizationRequest::kNothing) {
2898 // Nothing to do.
2899 return;
2900 }
2901 MutexLock mu(Thread::Current(), *deoptimization_lock_);
Sebastien Hertz7ec2f1c2014-03-27 20:06:47 +01002902 RequestDeoptimizationLocked(req);
2903}
2904
2905void Dbg::RequestDeoptimizationLocked(const DeoptimizationRequest& req) {
Sebastien Hertz4d25df32014-03-21 17:44:46 +01002906 switch (req.kind) {
Sebastien Hertz42cd43f2014-05-13 14:15:41 +02002907 case DeoptimizationRequest::kRegisterForEvent: {
2908 DCHECK_NE(req.instrumentation_event, 0u);
2909 size_t* counter = GetReferenceCounterForEvent(req.instrumentation_event);
2910 CHECK(counter != nullptr) << StringPrintf("No counter for instrumentation event 0x%x",
2911 req.instrumentation_event);
2912 if (*counter == 0) {
Sebastien Hertz7d2ae432014-05-15 11:26:34 +02002913 VLOG(jdwp) << StringPrintf("Queue request #%zd to start listening to instrumentation event 0x%x",
Sebastien Hertz42cd43f2014-05-13 14:15:41 +02002914 deoptimization_requests_.size(), req.instrumentation_event);
2915 deoptimization_requests_.push_back(req);
2916 }
2917 *counter = *counter + 1;
2918 break;
2919 }
2920 case DeoptimizationRequest::kUnregisterForEvent: {
2921 DCHECK_NE(req.instrumentation_event, 0u);
2922 size_t* counter = GetReferenceCounterForEvent(req.instrumentation_event);
2923 CHECK(counter != nullptr) << StringPrintf("No counter for instrumentation event 0x%x",
2924 req.instrumentation_event);
2925 *counter = *counter - 1;
2926 if (*counter == 0) {
Sebastien Hertz7d2ae432014-05-15 11:26:34 +02002927 VLOG(jdwp) << StringPrintf("Queue request #%zd to stop listening to instrumentation event 0x%x",
Sebastien Hertz42cd43f2014-05-13 14:15:41 +02002928 deoptimization_requests_.size(), req.instrumentation_event);
2929 deoptimization_requests_.push_back(req);
2930 }
2931 break;
2932 }
Sebastien Hertz4d25df32014-03-21 17:44:46 +01002933 case DeoptimizationRequest::kFullDeoptimization: {
2934 DCHECK(req.method == nullptr);
2935 if (full_deoptimization_event_count_ == 0) {
Sebastien Hertz7ec2f1c2014-03-27 20:06:47 +01002936 VLOG(jdwp) << "Queue request #" << deoptimization_requests_.size()
2937 << " for full deoptimization";
Sebastien Hertz4d25df32014-03-21 17:44:46 +01002938 deoptimization_requests_.push_back(req);
2939 }
2940 ++full_deoptimization_event_count_;
2941 break;
2942 }
2943 case DeoptimizationRequest::kFullUndeoptimization: {
2944 DCHECK(req.method == nullptr);
Sebastien Hertze713d932014-05-15 10:48:53 +02002945 DCHECK_GT(full_deoptimization_event_count_, 0U);
Sebastien Hertz4d25df32014-03-21 17:44:46 +01002946 --full_deoptimization_event_count_;
2947 if (full_deoptimization_event_count_ == 0) {
Sebastien Hertz7ec2f1c2014-03-27 20:06:47 +01002948 VLOG(jdwp) << "Queue request #" << deoptimization_requests_.size()
2949 << " for full undeoptimization";
Sebastien Hertz4d25df32014-03-21 17:44:46 +01002950 deoptimization_requests_.push_back(req);
2951 }
2952 break;
2953 }
2954 case DeoptimizationRequest::kSelectiveDeoptimization: {
2955 DCHECK(req.method != nullptr);
Sebastien Hertz7ec2f1c2014-03-27 20:06:47 +01002956 VLOG(jdwp) << "Queue request #" << deoptimization_requests_.size()
2957 << " for deoptimization of " << PrettyMethod(req.method);
Sebastien Hertz4d25df32014-03-21 17:44:46 +01002958 deoptimization_requests_.push_back(req);
2959 break;
2960 }
2961 case DeoptimizationRequest::kSelectiveUndeoptimization: {
2962 DCHECK(req.method != nullptr);
Sebastien Hertz7ec2f1c2014-03-27 20:06:47 +01002963 VLOG(jdwp) << "Queue request #" << deoptimization_requests_.size()
2964 << " for undeoptimization of " << PrettyMethod(req.method);
Sebastien Hertz4d25df32014-03-21 17:44:46 +01002965 deoptimization_requests_.push_back(req);
2966 break;
2967 }
2968 default: {
2969 LOG(FATAL) << "Unknown deoptimization request kind " << req.kind;
2970 break;
2971 }
2972 }
2973}
2974
Sebastien Hertz138dbfc2013-12-04 18:15:25 +01002975void Dbg::ManageDeoptimization() {
2976 Thread* const self = Thread::Current();
2977 {
2978 // Avoid suspend/resume if there is no pending request.
Sebastien Hertz4d25df32014-03-21 17:44:46 +01002979 MutexLock mu(self, *deoptimization_lock_);
2980 if (deoptimization_requests_.empty()) {
Sebastien Hertz138dbfc2013-12-04 18:15:25 +01002981 return;
2982 }
2983 }
2984 CHECK_EQ(self->GetState(), kRunnable);
2985 self->TransitionFromRunnableToSuspended(kWaitingForDeoptimization);
2986 // We need to suspend mutator threads first.
2987 Runtime* const runtime = Runtime::Current();
2988 runtime->GetThreadList()->SuspendAll();
2989 const ThreadState old_state = self->SetStateUnsafe(kRunnable);
Sebastien Hertz4d25df32014-03-21 17:44:46 +01002990 {
2991 MutexLock mu(self, *deoptimization_lock_);
Sebastien Hertz7ec2f1c2014-03-27 20:06:47 +01002992 size_t req_index = 0;
Sebastien Hertz4d25df32014-03-21 17:44:46 +01002993 for (const DeoptimizationRequest& request : deoptimization_requests_) {
Sebastien Hertz7ec2f1c2014-03-27 20:06:47 +01002994 VLOG(jdwp) << "Process deoptimization request #" << req_index++;
Sebastien Hertz4d25df32014-03-21 17:44:46 +01002995 ProcessDeoptimizationRequest(request);
2996 }
2997 deoptimization_requests_.clear();
2998 }
Sebastien Hertz138dbfc2013-12-04 18:15:25 +01002999 CHECK_EQ(self->SetStateUnsafe(old_state), kRunnable);
3000 runtime->GetThreadList()->ResumeAll();
3001 self->TransitionFromSuspendedToRunnable();
3002}
3003
Sebastien Hertza76a6d42014-03-20 16:40:17 +01003004static bool IsMethodPossiblyInlined(Thread* self, mirror::ArtMethod* m)
3005 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07003006 const DexFile::CodeItem* code_item = m->GetCodeItem();
Sebastien Hertza76a6d42014-03-20 16:40:17 +01003007 if (code_item == nullptr) {
3008 // TODO We should not be asked to watch location in a native or abstract method so the code item
3009 // should never be null. We could just check we never encounter this case.
3010 return false;
Sebastien Hertz138dbfc2013-12-04 18:15:25 +01003011 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003012 StackHandleScope<2> hs(self);
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07003013 mirror::Class* declaring_class = m->GetDeclaringClass();
3014 Handle<mirror::DexCache> dex_cache(hs.NewHandle(declaring_class->GetDexCache()));
3015 Handle<mirror::ClassLoader> class_loader(hs.NewHandle(declaring_class->GetClassLoader()));
3016 verifier::MethodVerifier verifier(dex_cache->GetDexFile(), &dex_cache, &class_loader,
3017 &m->GetClassDef(), code_item, m->GetDexMethodIndex(), m,
Ian Rogers46960fe2014-05-23 10:43:43 -07003018 m->GetAccessFlags(), false, true, false);
Sebastien Hertza76a6d42014-03-20 16:40:17 +01003019 // Note: we don't need to verify the method.
3020 return InlineMethodAnalyser::AnalyseMethodCode(&verifier, nullptr);
3021}
Sebastien Hertz138dbfc2013-12-04 18:15:25 +01003022
Sebastien Hertza76a6d42014-03-20 16:40:17 +01003023static const Breakpoint* FindFirstBreakpointForMethod(mirror::ArtMethod* m)
3024 EXCLUSIVE_LOCKS_REQUIRED(Locks::breakpoint_lock_) {
3025 for (const Breakpoint& breakpoint : gBreakpoints) {
3026 if (breakpoint.method == m) {
3027 return &breakpoint;
3028 }
3029 }
3030 return nullptr;
3031}
3032
3033// Sanity checks all existing breakpoints on the same method.
3034static void SanityCheckExistingBreakpoints(mirror::ArtMethod* m, bool need_full_deoptimization)
3035 EXCLUSIVE_LOCKS_REQUIRED(Locks::breakpoint_lock_) {
3036 if (kIsDebugBuild) {
3037 for (const Breakpoint& breakpoint : gBreakpoints) {
3038 CHECK_EQ(need_full_deoptimization, breakpoint.need_full_deoptimization);
3039 }
3040 if (need_full_deoptimization) {
3041 // We should have deoptimized everything but not "selectively" deoptimized this method.
3042 CHECK(Runtime::Current()->GetInstrumentation()->AreAllMethodsDeoptimized());
3043 CHECK(!Runtime::Current()->GetInstrumentation()->IsDeoptimized(m));
3044 } else {
3045 // We should have "selectively" deoptimized this method.
3046 // Note: while we have not deoptimized everything for this method, we may have done it for
3047 // another event.
3048 CHECK(Runtime::Current()->GetInstrumentation()->IsDeoptimized(m));
3049 }
Sebastien Hertz138dbfc2013-12-04 18:15:25 +01003050 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -07003051}
3052
Sebastien Hertza76a6d42014-03-20 16:40:17 +01003053// Installs a breakpoint at the specified location. Also indicates through the deoptimization
3054// request if we need to deoptimize.
3055void Dbg::WatchLocation(const JDWP::JdwpLocation* location, DeoptimizationRequest* req) {
3056 Thread* const self = Thread::Current();
Brian Carlstromea46f952013-07-30 01:26:50 -07003057 mirror::ArtMethod* m = FromMethodId(location->method_id);
Sebastien Hertza76a6d42014-03-20 16:40:17 +01003058 DCHECK(m != nullptr) << "No method for method id " << location->method_id;
Sebastien Hertz138dbfc2013-12-04 18:15:25 +01003059
Sebastien Hertza76a6d42014-03-20 16:40:17 +01003060 MutexLock mu(self, *Locks::breakpoint_lock_);
3061 const Breakpoint* const existing_breakpoint = FindFirstBreakpointForMethod(m);
3062 bool need_full_deoptimization;
3063 if (existing_breakpoint == nullptr) {
3064 // There is no breakpoint on this method yet: we need to deoptimize. If this method may be
3065 // inlined, we deoptimize everything; otherwise we deoptimize only this method.
3066 need_full_deoptimization = IsMethodPossiblyInlined(self, m);
3067 if (need_full_deoptimization) {
3068 req->kind = DeoptimizationRequest::kFullDeoptimization;
3069 req->method = nullptr;
3070 } else {
3071 req->kind = DeoptimizationRequest::kSelectiveDeoptimization;
3072 req->method = m;
Sebastien Hertz138dbfc2013-12-04 18:15:25 +01003073 }
Sebastien Hertza76a6d42014-03-20 16:40:17 +01003074 } else {
3075 // There is at least one breakpoint for this method: we don't need to deoptimize.
3076 req->kind = DeoptimizationRequest::kNothing;
3077 req->method = nullptr;
3078
3079 need_full_deoptimization = existing_breakpoint->need_full_deoptimization;
3080 SanityCheckExistingBreakpoints(m, need_full_deoptimization);
Sebastien Hertz138dbfc2013-12-04 18:15:25 +01003081 }
3082
Sebastien Hertza76a6d42014-03-20 16:40:17 +01003083 gBreakpoints.push_back(Breakpoint(m, location->dex_pc, need_full_deoptimization));
3084 VLOG(jdwp) << "Set breakpoint #" << (gBreakpoints.size() - 1) << ": "
3085 << gBreakpoints[gBreakpoints.size() - 1];
3086}
3087
3088// Uninstalls a breakpoint at the specified location. Also indicates through the deoptimization
3089// request if we need to undeoptimize.
3090void Dbg::UnwatchLocation(const JDWP::JdwpLocation* location, DeoptimizationRequest* req) {
3091 mirror::ArtMethod* m = FromMethodId(location->method_id);
3092 DCHECK(m != nullptr) << "No method for method id " << location->method_id;
3093
3094 MutexLock mu(Thread::Current(), *Locks::breakpoint_lock_);
3095 bool need_full_deoptimization = false;
3096 for (size_t i = 0, e = gBreakpoints.size(); i < e; ++i) {
3097 if (gBreakpoints[i].method == m && gBreakpoints[i].dex_pc == location->dex_pc) {
3098 VLOG(jdwp) << "Removed breakpoint #" << i << ": " << gBreakpoints[i];
3099 need_full_deoptimization = gBreakpoints[i].need_full_deoptimization;
3100 DCHECK_NE(need_full_deoptimization, Runtime::Current()->GetInstrumentation()->IsDeoptimized(m));
3101 gBreakpoints.erase(gBreakpoints.begin() + i);
3102 break;
3103 }
3104 }
3105 const Breakpoint* const existing_breakpoint = FindFirstBreakpointForMethod(m);
3106 if (existing_breakpoint == nullptr) {
3107 // There is no more breakpoint on this method: we need to undeoptimize.
3108 if (need_full_deoptimization) {
3109 // This method required full deoptimization: we need to undeoptimize everything.
3110 req->kind = DeoptimizationRequest::kFullUndeoptimization;
3111 req->method = nullptr;
3112 } else {
3113 // This method required selective deoptimization: we need to undeoptimize only that method.
3114 req->kind = DeoptimizationRequest::kSelectiveUndeoptimization;
3115 req->method = m;
3116 }
3117 } else {
3118 // There is at least one breakpoint for this method: we don't need to undeoptimize.
3119 req->kind = DeoptimizationRequest::kNothing;
3120 req->method = nullptr;
3121 SanityCheckExistingBreakpoints(m, need_full_deoptimization);
Elliott Hughes86964332012-02-15 19:37:42 -08003122 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -07003123}
3124
Jeff Hao449db332013-04-12 18:30:52 -07003125// Scoped utility class to suspend a thread so that we may do tasks such as walk its stack. Doesn't
3126// cause suspension if the thread is the current thread.
3127class ScopedThreadSuspension {
3128 public:
Ian Rogers33e95662013-05-20 20:29:14 -07003129 ScopedThreadSuspension(Thread* self, JDWP::ObjectId thread_id)
Sebastien Hertz52d131d2014-03-13 16:17:40 +01003130 LOCKS_EXCLUDED(Locks::thread_list_lock_)
Ian Rogers33e95662013-05-20 20:29:14 -07003131 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) :
Jeff Hao449db332013-04-12 18:30:52 -07003132 thread_(NULL),
3133 error_(JDWP::ERR_NONE),
3134 self_suspend_(false),
Ian Rogers33e95662013-05-20 20:29:14 -07003135 other_suspend_(false) {
Jeff Hao449db332013-04-12 18:30:52 -07003136 ScopedObjectAccessUnchecked soa(self);
3137 {
3138 MutexLock mu(soa.Self(), *Locks::thread_list_lock_);
3139 error_ = DecodeThread(soa, thread_id, thread_);
3140 }
3141 if (error_ == JDWP::ERR_NONE) {
3142 if (thread_ == soa.Self()) {
3143 self_suspend_ = true;
3144 } else {
3145 soa.Self()->TransitionFromRunnableToSuspended(kWaitingForDebuggerSuspension);
3146 jobject thread_peer = gRegistry->GetJObject(thread_id);
3147 bool timed_out;
Ian Rogersd9c4fc92013-10-01 19:45:43 -07003148 Thread* suspended_thread = ThreadList::SuspendThreadByPeer(thread_peer, true, true,
3149 &timed_out);
Jeff Hao449db332013-04-12 18:30:52 -07003150 CHECK_EQ(soa.Self()->TransitionFromSuspendedToRunnable(), kWaitingForDebuggerSuspension);
3151 if (suspended_thread == NULL) {
3152 // Thread terminated from under us while suspending.
3153 error_ = JDWP::ERR_INVALID_THREAD;
3154 } else {
3155 CHECK_EQ(suspended_thread, thread_);
3156 other_suspend_ = true;
3157 }
3158 }
3159 }
Elliott Hughes2435a572012-02-17 16:07:41 -08003160 }
Elliott Hughes86964332012-02-15 19:37:42 -08003161
Jeff Hao449db332013-04-12 18:30:52 -07003162 Thread* GetThread() const {
3163 return thread_;
3164 }
3165
3166 JDWP::JdwpError GetError() const {
3167 return error_;
3168 }
3169
3170 ~ScopedThreadSuspension() {
3171 if (other_suspend_) {
3172 Runtime::Current()->GetThreadList()->Resume(thread_, true);
3173 }
3174 }
3175
3176 private:
3177 Thread* thread_;
3178 JDWP::JdwpError error_;
3179 bool self_suspend_;
3180 bool other_suspend_;
3181};
3182
3183JDWP::JdwpError Dbg::ConfigureStep(JDWP::ObjectId thread_id, JDWP::JdwpStepSize step_size,
3184 JDWP::JdwpStepDepth step_depth) {
3185 Thread* self = Thread::Current();
3186 ScopedThreadSuspension sts(self, thread_id);
3187 if (sts.GetError() != JDWP::ERR_NONE) {
3188 return sts.GetError();
3189 }
3190
Elliott Hughes2435a572012-02-17 16:07:41 -08003191 //
3192 // Work out what Method* we're in, the current line number, and how deep the stack currently
3193 // is for step-out.
3194 //
3195
Ian Rogers0399dde2012-06-06 17:09:28 -07003196 struct SingleStepStackVisitor : public StackVisitor {
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01003197 explicit SingleStepStackVisitor(Thread* thread, SingleStepControl* single_step_control,
3198 int32_t* line_number)
Ian Rogersb726dcb2012-09-05 08:57:23 -07003199 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_)
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01003200 : StackVisitor(thread, NULL), single_step_control_(single_step_control),
3201 line_number_(line_number) {
3202 DCHECK_EQ(single_step_control_, thread->GetSingleStepControl());
3203 single_step_control_->method = NULL;
3204 single_step_control_->stack_depth = 0;
Elliott Hughes86964332012-02-15 19:37:42 -08003205 }
Ian Rogersca190662012-06-26 15:45:57 -07003206
Ian Rogers00f7d0e2012-07-19 15:28:27 -07003207 // TODO: Enable annotalysis. We know lock is held in constructor, but abstraction confuses
3208 // annotalysis.
3209 bool VisitFrame() NO_THREAD_SAFETY_ANALYSIS {
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01003210 mirror::ArtMethod* m = GetMethod();
Ian Rogers0399dde2012-06-06 17:09:28 -07003211 if (!m->IsRuntimeMethod()) {
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01003212 ++single_step_control_->stack_depth;
3213 if (single_step_control_->method == NULL) {
Ian Rogersef7d42f2014-01-06 12:55:46 -08003214 mirror::DexCache* dex_cache = m->GetDeclaringClass()->GetDexCache();
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01003215 single_step_control_->method = m;
3216 *line_number_ = -1;
Elliott Hughes2435a572012-02-17 16:07:41 -08003217 if (dex_cache != NULL) {
Ian Rogers4445a7e2012-10-05 17:19:13 -07003218 const DexFile& dex_file = *dex_cache->GetDexFile();
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01003219 *line_number_ = dex_file.GetLineNumFromPC(m, GetDexPc());
Elliott Hughes2435a572012-02-17 16:07:41 -08003220 }
Elliott Hughes86964332012-02-15 19:37:42 -08003221 }
3222 }
Elliott Hughes530fa002012-03-12 11:44:49 -07003223 return true;
Elliott Hughes86964332012-02-15 19:37:42 -08003224 }
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01003225
3226 SingleStepControl* const single_step_control_;
3227 int32_t* const line_number_;
Elliott Hughes86964332012-02-15 19:37:42 -08003228 };
Jeff Hao449db332013-04-12 18:30:52 -07003229
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01003230 Thread* const thread = sts.GetThread();
3231 SingleStepControl* const single_step_control = thread->GetSingleStepControl();
3232 DCHECK(single_step_control != nullptr);
3233 int32_t line_number = -1;
3234 SingleStepStackVisitor visitor(thread, single_step_control, &line_number);
Ian Rogers0399dde2012-06-06 17:09:28 -07003235 visitor.WalkStack();
Elliott Hughes86964332012-02-15 19:37:42 -08003236
Elliott Hughes2435a572012-02-17 16:07:41 -08003237 //
3238 // Find the dex_pc values that correspond to the current line, for line-based single-stepping.
3239 //
3240
3241 struct DebugCallbackContext {
Sebastien Hertzbb43b432014-04-14 11:59:08 +02003242 explicit DebugCallbackContext(SingleStepControl* single_step_control, int32_t line_number,
3243 const DexFile::CodeItem* code_item)
3244 : single_step_control_(single_step_control), line_number_(line_number), code_item_(code_item),
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01003245 last_pc_valid(false), last_pc(0) {
Elliott Hughes2435a572012-02-17 16:07:41 -08003246 }
3247
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01003248 static bool Callback(void* raw_context, uint32_t address, uint32_t line_number) {
Elliott Hughes2435a572012-02-17 16:07:41 -08003249 DebugCallbackContext* context = reinterpret_cast<DebugCallbackContext*>(raw_context);
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01003250 if (static_cast<int32_t>(line_number) == context->line_number_) {
Elliott Hughes2435a572012-02-17 16:07:41 -08003251 if (!context->last_pc_valid) {
3252 // Everything from this address until the next line change is ours.
3253 context->last_pc = address;
3254 context->last_pc_valid = true;
3255 }
3256 // Otherwise, if we're already in a valid range for this line,
3257 // just keep going (shouldn't really happen)...
Brian Carlstrom7934ac22013-07-26 10:54:15 -07003258 } else if (context->last_pc_valid) { // and the line number is new
Elliott Hughes2435a572012-02-17 16:07:41 -08003259 // Add everything from the last entry up until here to the set
3260 for (uint32_t dex_pc = context->last_pc; dex_pc < address; ++dex_pc) {
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01003261 context->single_step_control_->dex_pcs.insert(dex_pc);
Elliott Hughes2435a572012-02-17 16:07:41 -08003262 }
3263 context->last_pc_valid = false;
3264 }
Brian Carlstrom7934ac22013-07-26 10:54:15 -07003265 return false; // There may be multiple entries for any given line.
Elliott Hughes2435a572012-02-17 16:07:41 -08003266 }
3267
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01003268 ~DebugCallbackContext() {
Elliott Hughes2435a572012-02-17 16:07:41 -08003269 // If the line number was the last in the position table...
3270 if (last_pc_valid) {
Sebastien Hertzbb43b432014-04-14 11:59:08 +02003271 size_t end = code_item_->insns_size_in_code_units_;
Elliott Hughes2435a572012-02-17 16:07:41 -08003272 for (uint32_t dex_pc = last_pc; dex_pc < end; ++dex_pc) {
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01003273 single_step_control_->dex_pcs.insert(dex_pc);
Elliott Hughes2435a572012-02-17 16:07:41 -08003274 }
3275 }
3276 }
3277
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01003278 SingleStepControl* const single_step_control_;
3279 const int32_t line_number_;
Sebastien Hertzbb43b432014-04-14 11:59:08 +02003280 const DexFile::CodeItem* const code_item_;
Elliott Hughes2435a572012-02-17 16:07:41 -08003281 bool last_pc_valid;
3282 uint32_t last_pc;
3283 };
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01003284 single_step_control->dex_pcs.clear();
Ian Rogersef7d42f2014-01-06 12:55:46 -08003285 mirror::ArtMethod* m = single_step_control->method;
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01003286 if (!m->IsNative()) {
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07003287 const DexFile::CodeItem* const code_item = m->GetCodeItem();
Sebastien Hertzbb43b432014-04-14 11:59:08 +02003288 DebugCallbackContext context(single_step_control, line_number, code_item);
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07003289 m->GetDexFile()->DecodeDebugInfo(code_item, m->IsStatic(), m->GetDexMethodIndex(),
3290 DebugCallbackContext::Callback, NULL, &context);
Elliott Hughes3e2e1a22012-02-21 11:33:41 -08003291 }
Elliott Hughes2435a572012-02-17 16:07:41 -08003292
3293 //
3294 // Everything else...
3295 //
3296
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01003297 single_step_control->step_size = step_size;
3298 single_step_control->step_depth = step_depth;
3299 single_step_control->is_active = true;
Elliott Hughes86964332012-02-15 19:37:42 -08003300
Elliott Hughes2435a572012-02-17 16:07:41 -08003301 if (VLOG_IS_ON(jdwp)) {
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01003302 VLOG(jdwp) << "Single-step thread: " << *thread;
3303 VLOG(jdwp) << "Single-step step size: " << single_step_control->step_size;
3304 VLOG(jdwp) << "Single-step step depth: " << single_step_control->step_depth;
3305 VLOG(jdwp) << "Single-step current method: " << PrettyMethod(single_step_control->method);
3306 VLOG(jdwp) << "Single-step current line: " << line_number;
3307 VLOG(jdwp) << "Single-step current stack depth: " << single_step_control->stack_depth;
Elliott Hughes2435a572012-02-17 16:07:41 -08003308 VLOG(jdwp) << "Single-step dex_pc values:";
Sebastien Hertzbb43b432014-04-14 11:59:08 +02003309 for (uint32_t dex_pc : single_step_control->dex_pcs) {
3310 VLOG(jdwp) << StringPrintf(" %#x", dex_pc);
Elliott Hughes2435a572012-02-17 16:07:41 -08003311 }
3312 }
3313
3314 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07003315}
3316
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01003317void Dbg::UnconfigureStep(JDWP::ObjectId thread_id) {
3318 ScopedObjectAccessUnchecked soa(Thread::Current());
3319 MutexLock mu(soa.Self(), *Locks::thread_list_lock_);
3320 Thread* thread;
3321 JDWP::JdwpError error = DecodeThread(soa, thread_id, thread);
Sebastien Hertz87118ed2013-11-26 17:57:18 +01003322 if (error == JDWP::ERR_NONE) {
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01003323 SingleStepControl* single_step_control = thread->GetSingleStepControl();
3324 DCHECK(single_step_control != nullptr);
Sebastien Hertzbb43b432014-04-14 11:59:08 +02003325 single_step_control->Clear();
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01003326 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -07003327}
3328
Elliott Hughes45651fd2012-02-21 15:48:20 -08003329static char JdwpTagToShortyChar(JDWP::JdwpTag tag) {
3330 switch (tag) {
3331 default:
3332 LOG(FATAL) << "unknown JDWP tag: " << PrintableChar(tag);
3333
3334 // Primitives.
3335 case JDWP::JT_BYTE: return 'B';
3336 case JDWP::JT_CHAR: return 'C';
3337 case JDWP::JT_FLOAT: return 'F';
3338 case JDWP::JT_DOUBLE: return 'D';
3339 case JDWP::JT_INT: return 'I';
3340 case JDWP::JT_LONG: return 'J';
3341 case JDWP::JT_SHORT: return 'S';
3342 case JDWP::JT_VOID: return 'V';
3343 case JDWP::JT_BOOLEAN: return 'Z';
3344
3345 // Reference types.
3346 case JDWP::JT_ARRAY:
3347 case JDWP::JT_OBJECT:
3348 case JDWP::JT_STRING:
3349 case JDWP::JT_THREAD:
3350 case JDWP::JT_THREAD_GROUP:
3351 case JDWP::JT_CLASS_LOADER:
3352 case JDWP::JT_CLASS_OBJECT:
3353 return 'L';
3354 }
3355}
3356
Elliott Hughes88d63092013-01-09 09:55:54 -08003357JDWP::JdwpError Dbg::InvokeMethod(JDWP::ObjectId thread_id, JDWP::ObjectId object_id,
3358 JDWP::RefTypeId class_id, JDWP::MethodId method_id,
Ian Rogers00f7d0e2012-07-19 15:28:27 -07003359 uint32_t arg_count, uint64_t* arg_values,
3360 JDWP::JdwpTag* arg_types, uint32_t options,
3361 JDWP::JdwpTag* pResultTag, uint64_t* pResultValue,
3362 JDWP::ObjectId* pExceptionId) {
Elliott Hughesd07986f2011-12-06 18:27:45 -08003363 ThreadList* thread_list = Runtime::Current()->GetThreadList();
3364
3365 Thread* targetThread = NULL;
3366 DebugInvokeReq* req = NULL;
Ian Rogers00f7d0e2012-07-19 15:28:27 -07003367 Thread* self = Thread::Current();
Elliott Hughesd07986f2011-12-06 18:27:45 -08003368 {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07003369 ScopedObjectAccessUnchecked soa(self);
Ian Rogers50b35e22012-10-04 10:09:15 -07003370 MutexLock mu(soa.Self(), *Locks::thread_list_lock_);
Elliott Hughes221229c2013-01-08 18:17:50 -08003371 JDWP::JdwpError error = DecodeThread(soa, thread_id, targetThread);
3372 if (error != JDWP::ERR_NONE) {
3373 LOG(ERROR) << "InvokeMethod request for invalid thread id " << thread_id;
3374 return error;
Elliott Hughesd07986f2011-12-06 18:27:45 -08003375 }
3376 req = targetThread->GetInvokeReq();
3377 if (!req->ready) {
3378 LOG(ERROR) << "InvokeMethod request for thread not stopped by event: " << *targetThread;
3379 return JDWP::ERR_INVALID_THREAD;
3380 }
3381
3382 /*
3383 * We currently have a bug where we don't successfully resume the
3384 * target thread if the suspend count is too deep. We're expected to
3385 * require one "resume" for each "suspend", but when asked to execute
3386 * a method we have to resume fully and then re-suspend it back to the
3387 * same level. (The easiest way to cause this is to type "suspend"
3388 * multiple times in jdb.)
3389 *
3390 * It's unclear what this means when the event specifies "resume all"
3391 * and some threads are suspended more deeply than others. This is
3392 * a rare problem, so for now we just prevent it from hanging forever
3393 * by rejecting the method invocation request. Without this, we will
3394 * be stuck waiting on a suspended thread.
3395 */
Ian Rogers00f7d0e2012-07-19 15:28:27 -07003396 int suspend_count;
3397 {
Ian Rogers50b35e22012-10-04 10:09:15 -07003398 MutexLock mu2(soa.Self(), *Locks::thread_suspend_count_lock_);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07003399 suspend_count = targetThread->GetSuspendCount();
3400 }
Elliott Hughesd07986f2011-12-06 18:27:45 -08003401 if (suspend_count > 1) {
3402 LOG(ERROR) << *targetThread << " suspend count too deep for method invocation: " << suspend_count;
Brian Carlstrom7934ac22013-07-26 10:54:15 -07003403 return JDWP::ERR_THREAD_SUSPENDED; // Probably not expected here.
Elliott Hughesd07986f2011-12-06 18:27:45 -08003404 }
3405
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08003406 JDWP::JdwpError status;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003407 mirror::Object* receiver = gRegistry->Get<mirror::Object*>(object_id);
Elliott Hughes64f574f2013-02-20 14:57:12 -08003408 if (receiver == ObjectRegistry::kInvalidObject) {
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08003409 return JDWP::ERR_INVALID_OBJECT;
3410 }
Elliott Hughes45651fd2012-02-21 15:48:20 -08003411
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003412 mirror::Object* thread = gRegistry->Get<mirror::Object*>(thread_id);
Elliott Hughes64f574f2013-02-20 14:57:12 -08003413 if (thread == ObjectRegistry::kInvalidObject) {
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08003414 return JDWP::ERR_INVALID_OBJECT;
3415 }
Elliott Hughes45651fd2012-02-21 15:48:20 -08003416 // TODO: check that 'thread' is actually a java.lang.Thread!
3417
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003418 mirror::Class* c = DecodeClass(class_id, status);
Elliott Hughes45651fd2012-02-21 15:48:20 -08003419 if (c == NULL) {
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08003420 return status;
3421 }
Elliott Hughes45651fd2012-02-21 15:48:20 -08003422
Brian Carlstromea46f952013-07-30 01:26:50 -07003423 mirror::ArtMethod* m = FromMethodId(method_id);
Elliott Hughes45651fd2012-02-21 15:48:20 -08003424 if (m->IsStatic() != (receiver == NULL)) {
3425 return JDWP::ERR_INVALID_METHODID;
3426 }
3427 if (m->IsStatic()) {
3428 if (m->GetDeclaringClass() != c) {
3429 return JDWP::ERR_INVALID_METHODID;
3430 }
3431 } else {
3432 if (!m->GetDeclaringClass()->IsAssignableFrom(c)) {
3433 return JDWP::ERR_INVALID_METHODID;
3434 }
3435 }
3436
3437 // Check the argument list matches the method.
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07003438 uint32_t shorty_len = 0;
3439 const char* shorty = m->GetShorty(&shorty_len);
3440 if (shorty_len - 1 != arg_count) {
Elliott Hughes45651fd2012-02-21 15:48:20 -08003441 return JDWP::ERR_ILLEGAL_ARGUMENT;
3442 }
Elliott Hughes09201632013-04-15 15:50:07 -07003443
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07003444 {
3445 StackHandleScope<3> hs(soa.Self());
3446 MethodHelper mh(hs.NewHandle(m));
3447 HandleWrapper<mirror::Object> h_obj(hs.NewHandleWrapper(&receiver));
3448 HandleWrapper<mirror::Class> h_klass(hs.NewHandleWrapper(&c));
3449 const DexFile::TypeList* types = m->GetParameterTypeList();
3450 for (size_t i = 0; i < arg_count; ++i) {
3451 if (shorty[i + 1] != JdwpTagToShortyChar(arg_types[i])) {
Elliott Hughes09201632013-04-15 15:50:07 -07003452 return JDWP::ERR_ILLEGAL_ARGUMENT;
3453 }
3454
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07003455 if (shorty[i + 1] == 'L') {
3456 // Did we really get an argument of an appropriate reference type?
3457 mirror::Class* parameter_type = mh.GetClassFromTypeIdx(types->GetTypeItem(i).type_idx_);
3458 mirror::Object* argument = gRegistry->Get<mirror::Object*>(arg_values[i]);
3459 if (argument == ObjectRegistry::kInvalidObject) {
3460 return JDWP::ERR_INVALID_OBJECT;
3461 }
3462 if (argument != NULL && !argument->InstanceOf(parameter_type)) {
3463 return JDWP::ERR_ILLEGAL_ARGUMENT;
3464 }
3465
3466 // Turn the on-the-wire ObjectId into a jobject.
3467 jvalue& v = reinterpret_cast<jvalue&>(arg_values[i]);
3468 v.l = gRegistry->GetJObject(arg_values[i]);
3469 }
Elliott Hughes09201632013-04-15 15:50:07 -07003470 }
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07003471 // Update in case it moved.
3472 m = mh.GetMethod();
Elliott Hughes45651fd2012-02-21 15:48:20 -08003473 }
3474
Sebastien Hertzd38667a2013-11-25 15:43:54 +01003475 req->receiver = receiver;
3476 req->thread = thread;
3477 req->klass = c;
3478 req->method = m;
3479 req->arg_count = arg_count;
3480 req->arg_values = arg_values;
3481 req->options = options;
3482 req->invoke_needed = true;
Elliott Hughesd07986f2011-12-06 18:27:45 -08003483 }
3484
3485 // The fact that we've released the thread list lock is a bit risky --- if the thread goes
3486 // away we're sitting high and dry -- but we must release this before the ResumeAllThreads
3487 // call, and it's unwise to hold it during WaitForSuspend.
3488
3489 {
3490 /*
3491 * We change our (JDWP thread) status, which should be THREAD_RUNNING,
Elliott Hughes81ff3182012-03-23 20:35:56 -07003492 * so we can suspend for a GC if the invoke request causes us to
Elliott Hughesd07986f2011-12-06 18:27:45 -08003493 * run out of memory. It's also a good idea to change it before locking
3494 * the invokeReq mutex, although that should never be held for long.
3495 */
Ian Rogers00f7d0e2012-07-19 15:28:27 -07003496 self->TransitionFromRunnableToSuspended(kWaitingForDebuggerSend);
Elliott Hughesd07986f2011-12-06 18:27:45 -08003497
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08003498 VLOG(jdwp) << " Transferring control to event thread";
Elliott Hughesd07986f2011-12-06 18:27:45 -08003499 {
Sebastien Hertzd38667a2013-11-25 15:43:54 +01003500 MutexLock mu(self, req->lock);
Elliott Hughesd07986f2011-12-06 18:27:45 -08003501
3502 if ((options & JDWP::INVOKE_SINGLE_THREADED) == 0) {
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08003503 VLOG(jdwp) << " Resuming all threads";
Ian Rogers00f7d0e2012-07-19 15:28:27 -07003504 thread_list->UndoDebuggerSuspensions();
Elliott Hughesd07986f2011-12-06 18:27:45 -08003505 } else {
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08003506 VLOG(jdwp) << " Resuming event thread only";
Elliott Hughesd07986f2011-12-06 18:27:45 -08003507 thread_list->Resume(targetThread, true);
3508 }
3509
3510 // Wait for the request to finish executing.
Sebastien Hertzd38667a2013-11-25 15:43:54 +01003511 while (req->invoke_needed) {
3512 req->cond.Wait(self);
Elliott Hughesd07986f2011-12-06 18:27:45 -08003513 }
3514 }
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08003515 VLOG(jdwp) << " Control has returned from event thread";
Elliott Hughesd07986f2011-12-06 18:27:45 -08003516
3517 /* wait for thread to re-suspend itself */
Brian Carlstromdf629502013-07-17 22:39:56 -07003518 SuspendThread(thread_id, false /* request_suspension */);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07003519 self->TransitionFromSuspendedToRunnable();
Elliott Hughesd07986f2011-12-06 18:27:45 -08003520 }
3521
3522 /*
3523 * Suspend the threads. We waited for the target thread to suspend
3524 * itself, so all we need to do is suspend the others.
3525 *
3526 * The suspendAllThreads() call will double-suspend the event thread,
3527 * so we want to resume the target thread once to keep the books straight.
3528 */
3529 if ((options & JDWP::INVOKE_SINGLE_THREADED) == 0) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07003530 self->TransitionFromRunnableToSuspended(kWaitingForDebuggerSuspension);
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08003531 VLOG(jdwp) << " Suspending all threads";
Ian Rogers00f7d0e2012-07-19 15:28:27 -07003532 thread_list->SuspendAllForDebugger();
3533 self->TransitionFromSuspendedToRunnable();
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08003534 VLOG(jdwp) << " Resuming event thread to balance the count";
Elliott Hughesd07986f2011-12-06 18:27:45 -08003535 thread_list->Resume(targetThread, true);
3536 }
3537
3538 // Copy the result.
3539 *pResultTag = req->result_tag;
3540 if (IsPrimitiveTag(req->result_tag)) {
Elliott Hughesf24d3ce2012-04-11 17:43:37 -07003541 *pResultValue = req->result_value.GetJ();
Elliott Hughesd07986f2011-12-06 18:27:45 -08003542 } else {
Elliott Hughesf24d3ce2012-04-11 17:43:37 -07003543 *pResultValue = gRegistry->Add(req->result_value.GetL());
Elliott Hughesd07986f2011-12-06 18:27:45 -08003544 }
3545 *pExceptionId = req->exception;
3546 return req->error;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07003547}
3548
3549void Dbg::ExecuteMethod(DebugInvokeReq* pReq) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07003550 ScopedObjectAccess soa(Thread::Current());
Elliott Hughesd07986f2011-12-06 18:27:45 -08003551
Elliott Hughes81ff3182012-03-23 20:35:56 -07003552 // We can be called while an exception is pending. We need
Elliott Hughesd07986f2011-12-06 18:27:45 -08003553 // to preserve that across the method invocation.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003554 StackHandleScope<4> hs(soa.Self());
3555 auto old_throw_this_object = hs.NewHandle<mirror::Object>(nullptr);
3556 auto old_throw_method = hs.NewHandle<mirror::ArtMethod>(nullptr);
3557 auto old_exception = hs.NewHandle<mirror::Throwable>(nullptr);
Ian Rogers62d6c772013-02-27 08:32:07 -08003558 uint32_t old_throw_dex_pc;
Sebastien Hertz9f102032014-05-23 08:59:42 +02003559 bool old_exception_report_flag;
Ian Rogers62d6c772013-02-27 08:32:07 -08003560 {
3561 ThrowLocation old_throw_location;
3562 mirror::Throwable* old_exception_obj = soa.Self()->GetException(&old_throw_location);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003563 old_throw_this_object.Assign(old_throw_location.GetThis());
3564 old_throw_method.Assign(old_throw_location.GetMethod());
3565 old_exception.Assign(old_exception_obj);
Ian Rogers62d6c772013-02-27 08:32:07 -08003566 old_throw_dex_pc = old_throw_location.GetDexPc();
Sebastien Hertz9f102032014-05-23 08:59:42 +02003567 old_exception_report_flag = soa.Self()->IsExceptionReportedToInstrumentation();
Ian Rogers62d6c772013-02-27 08:32:07 -08003568 soa.Self()->ClearException();
3569 }
Elliott Hughesd07986f2011-12-06 18:27:45 -08003570
3571 // Translate the method through the vtable, unless the debugger wants to suppress it.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003572 Handle<mirror::ArtMethod> m(hs.NewHandle(pReq->method));
Sebastien Hertzd38667a2013-11-25 15:43:54 +01003573 if ((pReq->options & JDWP::INVOKE_NONVIRTUAL) == 0 && pReq->receiver != NULL) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003574 mirror::ArtMethod* actual_method = pReq->klass->FindVirtualMethodForVirtualOrInterface(m.Get());
3575 if (actual_method != m.Get()) {
3576 VLOG(jdwp) << "ExecuteMethod translated " << PrettyMethod(m.Get()) << " to " << PrettyMethod(actual_method);
3577 m.Assign(actual_method);
Elliott Hughes45651fd2012-02-21 15:48:20 -08003578 }
Elliott Hughesd07986f2011-12-06 18:27:45 -08003579 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003580 VLOG(jdwp) << "ExecuteMethod " << PrettyMethod(m.Get())
Sebastien Hertzd38667a2013-11-25 15:43:54 +01003581 << " receiver=" << pReq->receiver
3582 << " arg_count=" << pReq->arg_count;
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003583 CHECK(m.Get() != nullptr);
Elliott Hughesd07986f2011-12-06 18:27:45 -08003584
3585 CHECK_EQ(sizeof(jvalue), sizeof(uint64_t));
3586
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003587 pReq->result_value = InvokeWithJValues(soa, pReq->receiver, soa.EncodeMethod(m.Get()),
Ian Rogers53b8b092014-03-13 23:45:53 -07003588 reinterpret_cast<jvalue*>(pReq->arg_values));
Elliott Hughesd07986f2011-12-06 18:27:45 -08003589
Ian Rogers62d6c772013-02-27 08:32:07 -08003590 mirror::Throwable* exception = soa.Self()->GetException(NULL);
3591 soa.Self()->ClearException();
3592 pReq->exception = gRegistry->Add(exception);
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07003593 pReq->result_tag = BasicTagFromDescriptor(m.Get()->GetShorty());
Elliott Hughesd07986f2011-12-06 18:27:45 -08003594 if (pReq->exception != 0) {
Ian Rogers62d6c772013-02-27 08:32:07 -08003595 VLOG(jdwp) << " JDWP invocation returning with exception=" << exception
3596 << " " << exception->Dump();
Elliott Hughesf24d3ce2012-04-11 17:43:37 -07003597 pReq->result_value.SetJ(0);
Elliott Hughesd07986f2011-12-06 18:27:45 -08003598 } else if (pReq->result_tag == JDWP::JT_OBJECT) {
3599 /* if no exception thrown, examine object result more closely */
Ian Rogers98379392014-02-24 16:53:16 -08003600 JDWP::JdwpTag new_tag = TagFromObject(soa, pReq->result_value.GetL());
Elliott Hughesd07986f2011-12-06 18:27:45 -08003601 if (new_tag != pReq->result_tag) {
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08003602 VLOG(jdwp) << " JDWP promoted result from " << pReq->result_tag << " to " << new_tag;
Elliott Hughesd07986f2011-12-06 18:27:45 -08003603 pReq->result_tag = new_tag;
3604 }
3605
3606 /*
3607 * Register the object. We don't actually need an ObjectId yet,
3608 * but we do need to be sure that the GC won't move or discard the
3609 * object when we switch out of RUNNING. The ObjectId conversion
3610 * will add the object to the "do not touch" list.
3611 *
3612 * We can't use the "tracked allocation" mechanism here because
3613 * the object is going to be handed off to a different thread.
3614 */
Elliott Hughesf24d3ce2012-04-11 17:43:37 -07003615 gRegistry->Add(pReq->result_value.GetL());
Elliott Hughesd07986f2011-12-06 18:27:45 -08003616 }
3617
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003618 if (old_exception.Get() != NULL) {
3619 ThrowLocation gc_safe_throw_location(old_throw_this_object.Get(), old_throw_method.Get(),
Ian Rogers62d6c772013-02-27 08:32:07 -08003620 old_throw_dex_pc);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003621 soa.Self()->SetException(gc_safe_throw_location, old_exception.Get());
Sebastien Hertz9f102032014-05-23 08:59:42 +02003622 soa.Self()->SetExceptionReportedToInstrumentation(old_exception_report_flag);
Elliott Hughesd07986f2011-12-06 18:27:45 -08003623 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -07003624}
3625
Elliott Hughesd07986f2011-12-06 18:27:45 -08003626/*
Elliott Hughes4b9702c2013-02-20 18:13:24 -08003627 * "request" contains a full JDWP packet, possibly with multiple chunks. We
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07003628 * need to process each, accumulate the replies, and ship the whole thing
3629 * back.
3630 *
3631 * Returns "true" if we have a reply. The reply buffer is newly allocated,
3632 * and includes the chunk type/length, followed by the data.
3633 *
Elliott Hughes3d30d9b2011-12-07 17:35:48 -08003634 * OLD-TODO: we currently assume that the request and reply include a single
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07003635 * chunk. If this becomes inconvenient we will need to adapt.
3636 */
Elliott Hughes4b9702c2013-02-20 18:13:24 -08003637bool Dbg::DdmHandlePacket(JDWP::Request& request, uint8_t** pReplyBuf, int* pReplyLen) {
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07003638 Thread* self = Thread::Current();
3639 JNIEnv* env = self->GetJniEnv();
3640
Elliott Hughes4b9702c2013-02-20 18:13:24 -08003641 uint32_t type = request.ReadUnsigned32("type");
3642 uint32_t length = request.ReadUnsigned32("length");
3643
3644 // Create a byte[] corresponding to 'request'.
3645 size_t request_length = request.size();
3646 ScopedLocalRef<jbyteArray> dataArray(env, env->NewByteArray(request_length));
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003647 if (dataArray.get() == NULL) {
Elliott Hughes4b9702c2013-02-20 18:13:24 -08003648 LOG(WARNING) << "byte[] allocation failed: " << request_length;
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07003649 env->ExceptionClear();
3650 return false;
3651 }
Elliott Hughes4b9702c2013-02-20 18:13:24 -08003652 env->SetByteArrayRegion(dataArray.get(), 0, request_length, reinterpret_cast<const jbyte*>(request.data()));
3653 request.Skip(request_length);
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07003654
3655 // Run through and find all chunks. [Currently just find the first.]
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003656 ScopedByteArrayRO contents(env, dataArray.get());
Elliott Hughes4b9702c2013-02-20 18:13:24 -08003657 if (length != request_length) {
Ian Rogersef7d42f2014-01-06 12:55:46 -08003658 LOG(WARNING) << StringPrintf("bad chunk found (len=%u pktLen=%zd)", length, request_length);
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07003659 return false;
3660 }
3661
3662 // Call "private static Chunk dispatch(int type, byte[] data, int offset, int length)".
Elliott Hugheseac76672012-05-24 21:56:51 -07003663 ScopedLocalRef<jobject> chunk(env, env->CallStaticObjectMethod(WellKnownClasses::org_apache_harmony_dalvik_ddmc_DdmServer,
3664 WellKnownClasses::org_apache_harmony_dalvik_ddmc_DdmServer_dispatch,
Elliott Hughes4b9702c2013-02-20 18:13:24 -08003665 type, dataArray.get(), 0, length));
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07003666 if (env->ExceptionCheck()) {
3667 LOG(INFO) << StringPrintf("Exception thrown by dispatcher for 0x%08x", type);
3668 env->ExceptionDescribe();
3669 env->ExceptionClear();
3670 return false;
3671 }
3672
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003673 if (chunk.get() == NULL) {
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07003674 return false;
3675 }
3676
3677 /*
3678 * Pull the pieces out of the chunk. We copy the results into a
3679 * newly-allocated buffer that the caller can free. We don't want to
3680 * continue using the Chunk object because nothing has a reference to it.
3681 *
3682 * We could avoid this by returning type/data/offset/length and having
3683 * the caller be aware of the object lifetime issues, but that
Elliott Hughes81ff3182012-03-23 20:35:56 -07003684 * integrates the JDWP code more tightly into the rest of the runtime, and doesn't work
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07003685 * if we have responses for multiple chunks.
3686 *
3687 * So we're pretty much stuck with copying data around multiple times.
3688 */
Elliott Hugheseac76672012-05-24 21:56:51 -07003689 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 -08003690 jint offset = env->GetIntField(chunk.get(), WellKnownClasses::org_apache_harmony_dalvik_ddmc_Chunk_offset);
Elliott Hugheseac76672012-05-24 21:56:51 -07003691 length = env->GetIntField(chunk.get(), WellKnownClasses::org_apache_harmony_dalvik_ddmc_Chunk_length);
Elliott Hugheseac76672012-05-24 21:56:51 -07003692 type = env->GetIntField(chunk.get(), WellKnownClasses::org_apache_harmony_dalvik_ddmc_Chunk_type);
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07003693
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08003694 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 -07003695 if (length == 0 || replyData.get() == NULL) {
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07003696 return false;
3697 }
3698
Elliott Hughes4b9702c2013-02-20 18:13:24 -08003699 const int kChunkHdrLen = 8;
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07003700 uint8_t* reply = new uint8_t[length + kChunkHdrLen];
3701 if (reply == NULL) {
3702 LOG(WARNING) << "malloc failed: " << (length + kChunkHdrLen);
3703 return false;
3704 }
Elliott Hughesf7c3b662011-10-27 12:04:56 -07003705 JDWP::Set4BE(reply + 0, type);
3706 JDWP::Set4BE(reply + 4, length);
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003707 env->GetByteArrayRegion(replyData.get(), offset, length, reinterpret_cast<jbyte*>(reply + kChunkHdrLen));
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07003708
3709 *pReplyBuf = reply;
3710 *pReplyLen = length + kChunkHdrLen;
3711
Elliott Hughes4b9702c2013-02-20 18:13:24 -08003712 VLOG(jdwp) << StringPrintf("dvmHandleDdm returning type=%.4s %p len=%d", reinterpret_cast<char*>(reply), reply, length);
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07003713 return true;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07003714}
3715
Elliott Hughesa2155262011-11-16 16:26:58 -08003716void Dbg::DdmBroadcast(bool connect) {
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08003717 VLOG(jdwp) << "Broadcasting DDM " << (connect ? "connect" : "disconnect") << "...";
Elliott Hughes47fce012011-10-25 18:37:19 -07003718
3719 Thread* self = Thread::Current();
Ian Rogers50b35e22012-10-04 10:09:15 -07003720 if (self->GetState() != kRunnable) {
3721 LOG(ERROR) << "DDM broadcast in thread state " << self->GetState();
3722 /* try anyway? */
Elliott Hughes47fce012011-10-25 18:37:19 -07003723 }
3724
3725 JNIEnv* env = self->GetJniEnv();
Elliott Hughes47fce012011-10-25 18:37:19 -07003726 jint event = connect ? 1 /*DdmServer.CONNECTED*/ : 2 /*DdmServer.DISCONNECTED*/;
Elliott Hugheseac76672012-05-24 21:56:51 -07003727 env->CallStaticVoidMethod(WellKnownClasses::org_apache_harmony_dalvik_ddmc_DdmServer,
3728 WellKnownClasses::org_apache_harmony_dalvik_ddmc_DdmServer_broadcast,
3729 event);
Elliott Hughes47fce012011-10-25 18:37:19 -07003730 if (env->ExceptionCheck()) {
3731 LOG(ERROR) << "DdmServer.broadcast " << event << " failed";
3732 env->ExceptionDescribe();
3733 env->ExceptionClear();
3734 }
3735}
3736
Elliott Hughes872d4ec2011-10-21 17:07:15 -07003737void Dbg::DdmConnected() {
Elliott Hughesa2155262011-11-16 16:26:58 -08003738 Dbg::DdmBroadcast(true);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07003739}
3740
3741void Dbg::DdmDisconnected() {
Elliott Hughesa2155262011-11-16 16:26:58 -08003742 Dbg::DdmBroadcast(false);
Elliott Hughes47fce012011-10-25 18:37:19 -07003743 gDdmThreadNotification = false;
3744}
3745
3746/*
Elliott Hughes82188472011-11-07 18:11:48 -08003747 * Send a notification when a thread starts, stops, or changes its name.
Elliott Hughes47fce012011-10-25 18:37:19 -07003748 *
3749 * Because we broadcast the full set of threads when the notifications are
3750 * first enabled, it's possible for "thread" to be actively executing.
3751 */
Elliott Hughes82188472011-11-07 18:11:48 -08003752void Dbg::DdmSendThreadNotification(Thread* t, uint32_t type) {
Elliott Hughes47fce012011-10-25 18:37:19 -07003753 if (!gDdmThreadNotification) {
3754 return;
3755 }
3756
Elliott Hughes82188472011-11-07 18:11:48 -08003757 if (type == CHUNK_TYPE("THDE")) {
Elliott Hughes47fce012011-10-25 18:37:19 -07003758 uint8_t buf[4];
Ian Rogersd9c4fc92013-10-01 19:45:43 -07003759 JDWP::Set4BE(&buf[0], t->GetThreadId());
Elliott Hughes47fce012011-10-25 18:37:19 -07003760 Dbg::DdmSendChunk(CHUNK_TYPE("THDE"), 4, buf);
Elliott Hughes82188472011-11-07 18:11:48 -08003761 } else {
3762 CHECK(type == CHUNK_TYPE("THCR") || type == CHUNK_TYPE("THNM")) << type;
Ian Rogers00f7d0e2012-07-19 15:28:27 -07003763 ScopedObjectAccessUnchecked soa(Thread::Current());
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003764 StackHandleScope<1> hs(soa.Self());
3765 Handle<mirror::String> name(hs.NewHandle(t->GetThreadName(soa)));
3766 size_t char_count = (name.Get() != NULL) ? name->GetLength() : 0;
3767 const jchar* chars = (name.Get() != NULL) ? name->GetCharArray()->GetData() : NULL;
Elliott Hughes82188472011-11-07 18:11:48 -08003768
Elliott Hughes21f32d72011-11-09 17:44:13 -08003769 std::vector<uint8_t> bytes;
Ian Rogersd9c4fc92013-10-01 19:45:43 -07003770 JDWP::Append4BE(bytes, t->GetThreadId());
Elliott Hughes545a0642011-11-08 19:10:03 -08003771 JDWP::AppendUtf16BE(bytes, chars, char_count);
Elliott Hughes21f32d72011-11-09 17:44:13 -08003772 CHECK_EQ(bytes.size(), char_count*2 + sizeof(uint32_t)*2);
3773 Dbg::DdmSendChunk(type, bytes);
Elliott Hughes47fce012011-10-25 18:37:19 -07003774 }
3775}
3776
Elliott Hughes47fce012011-10-25 18:37:19 -07003777void Dbg::DdmSetThreadNotification(bool enable) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07003778 // Enable/disable thread notifications.
Elliott Hughes47fce012011-10-25 18:37:19 -07003779 gDdmThreadNotification = enable;
3780 if (enable) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07003781 // Suspend the VM then post thread start notifications for all threads. Threads attaching will
3782 // see a suspension in progress and block until that ends. They then post their own start
3783 // notification.
3784 SuspendVM();
3785 std::list<Thread*> threads;
Ian Rogers50b35e22012-10-04 10:09:15 -07003786 Thread* self = Thread::Current();
Ian Rogers00f7d0e2012-07-19 15:28:27 -07003787 {
Ian Rogers50b35e22012-10-04 10:09:15 -07003788 MutexLock mu(self, *Locks::thread_list_lock_);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07003789 threads = Runtime::Current()->GetThreadList()->GetList();
3790 }
3791 {
Ian Rogers50b35e22012-10-04 10:09:15 -07003792 ScopedObjectAccess soa(self);
Mathieu Chartier02e25112013-08-14 16:14:24 -07003793 for (Thread* thread : threads) {
3794 Dbg::DdmSendThreadNotification(thread, CHUNK_TYPE("THCR"));
Ian Rogers00f7d0e2012-07-19 15:28:27 -07003795 }
3796 }
3797 ResumeVM();
Elliott Hughes47fce012011-10-25 18:37:19 -07003798 }
3799}
3800
Elliott Hughesa2155262011-11-16 16:26:58 -08003801void Dbg::PostThreadStartOrStop(Thread* t, uint32_t type) {
Elliott Hughesc0f09332012-03-26 13:27:06 -07003802 if (IsDebuggerActive()) {
Mathieu Chartierdbe6f462012-09-25 16:54:50 -07003803 ScopedObjectAccessUnchecked soa(Thread::Current());
Ian Rogerscfaa4552012-11-26 21:00:08 -08003804 JDWP::ObjectId id = gRegistry->Add(t->GetPeer());
Elliott Hughes82188472011-11-07 18:11:48 -08003805 gJdwpState->PostThreadChange(id, type == CHUNK_TYPE("THCR"));
Elliott Hughes47fce012011-10-25 18:37:19 -07003806 }
Elliott Hughes82188472011-11-07 18:11:48 -08003807 Dbg::DdmSendThreadNotification(t, type);
Elliott Hughes47fce012011-10-25 18:37:19 -07003808}
3809
3810void Dbg::PostThreadStart(Thread* t) {
Elliott Hughesa2155262011-11-16 16:26:58 -08003811 Dbg::PostThreadStartOrStop(t, CHUNK_TYPE("THCR"));
Elliott Hughes47fce012011-10-25 18:37:19 -07003812}
3813
3814void Dbg::PostThreadDeath(Thread* t) {
Elliott Hughesa2155262011-11-16 16:26:58 -08003815 Dbg::PostThreadStartOrStop(t, CHUNK_TYPE("THDE"));
Elliott Hughes872d4ec2011-10-21 17:07:15 -07003816}
3817
Elliott Hughes82188472011-11-07 18:11:48 -08003818void Dbg::DdmSendChunk(uint32_t type, size_t byte_count, const uint8_t* buf) {
Elliott Hughes3bb81562011-10-21 18:52:59 -07003819 CHECK(buf != NULL);
3820 iovec vec[1];
3821 vec[0].iov_base = reinterpret_cast<void*>(const_cast<uint8_t*>(buf));
3822 vec[0].iov_len = byte_count;
3823 Dbg::DdmSendChunkV(type, vec, 1);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07003824}
3825
Elliott Hughes21f32d72011-11-09 17:44:13 -08003826void Dbg::DdmSendChunk(uint32_t type, const std::vector<uint8_t>& bytes) {
3827 DdmSendChunk(type, bytes.size(), &bytes[0]);
3828}
3829
Brian Carlstromf5293522013-07-19 00:24:00 -07003830void Dbg::DdmSendChunkV(uint32_t type, const iovec* iov, int iov_count) {
Elliott Hughes3bb81562011-10-21 18:52:59 -07003831 if (gJdwpState == NULL) {
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08003832 VLOG(jdwp) << "Debugger thread not active, ignoring DDM send: " << type;
Elliott Hughes3bb81562011-10-21 18:52:59 -07003833 } else {
Elliott Hughescccd84f2011-12-05 16:51:54 -08003834 gJdwpState->DdmSendChunkV(type, iov, iov_count);
Elliott Hughes3bb81562011-10-21 18:52:59 -07003835 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -07003836}
3837
Elliott Hughes767a1472011-10-26 18:49:02 -07003838int Dbg::DdmHandleHpifChunk(HpifWhen when) {
3839 if (when == HPIF_WHEN_NOW) {
Elliott Hughes7162ad92011-10-27 14:08:42 -07003840 DdmSendHeapInfo(when);
Elliott Hughes767a1472011-10-26 18:49:02 -07003841 return true;
3842 }
3843
3844 if (when != HPIF_WHEN_NEVER && when != HPIF_WHEN_NEXT_GC && when != HPIF_WHEN_EVERY_GC) {
3845 LOG(ERROR) << "invalid HpifWhen value: " << static_cast<int>(when);
3846 return false;
3847 }
3848
3849 gDdmHpifWhen = when;
3850 return true;
3851}
3852
3853bool Dbg::DdmHandleHpsgNhsgChunk(Dbg::HpsgWhen when, Dbg::HpsgWhat what, bool native) {
3854 if (when != HPSG_WHEN_NEVER && when != HPSG_WHEN_EVERY_GC) {
3855 LOG(ERROR) << "invalid HpsgWhen value: " << static_cast<int>(when);
3856 return false;
3857 }
3858
3859 if (what != HPSG_WHAT_MERGED_OBJECTS && what != HPSG_WHAT_DISTINCT_OBJECTS) {
3860 LOG(ERROR) << "invalid HpsgWhat value: " << static_cast<int>(what);
3861 return false;
3862 }
3863
3864 if (native) {
3865 gDdmNhsgWhen = when;
3866 gDdmNhsgWhat = what;
3867 } else {
3868 gDdmHpsgWhen = when;
3869 gDdmHpsgWhat = what;
3870 }
3871 return true;
3872}
3873
Elliott Hughes7162ad92011-10-27 14:08:42 -07003874void Dbg::DdmSendHeapInfo(HpifWhen reason) {
3875 // If there's a one-shot 'when', reset it.
3876 if (reason == gDdmHpifWhen) {
3877 if (gDdmHpifWhen == HPIF_WHEN_NEXT_GC) {
3878 gDdmHpifWhen = HPIF_WHEN_NEVER;
3879 }
3880 }
3881
3882 /*
3883 * Chunk HPIF (client --> server)
3884 *
3885 * Heap Info. General information about the heap,
3886 * suitable for a summary display.
3887 *
3888 * [u4]: number of heaps
3889 *
3890 * For each heap:
3891 * [u4]: heap ID
3892 * [u8]: timestamp in ms since Unix epoch
3893 * [u1]: capture reason (same as 'when' value from server)
3894 * [u4]: max heap size in bytes (-Xmx)
3895 * [u4]: current heap size in bytes
3896 * [u4]: current number of bytes allocated
3897 * [u4]: current number of objects allocated
3898 */
3899 uint8_t heap_count = 1;
Ian Rogers1d54e732013-05-02 21:10:01 -07003900 gc::Heap* heap = Runtime::Current()->GetHeap();
Elliott Hughes21f32d72011-11-09 17:44:13 -08003901 std::vector<uint8_t> bytes;
Elliott Hughes545a0642011-11-08 19:10:03 -08003902 JDWP::Append4BE(bytes, heap_count);
Brian Carlstrom7934ac22013-07-26 10:54:15 -07003903 JDWP::Append4BE(bytes, 1); // Heap id (bogus; we only have one heap).
Elliott Hughes545a0642011-11-08 19:10:03 -08003904 JDWP::Append8BE(bytes, MilliTime());
3905 JDWP::Append1BE(bytes, reason);
Brian Carlstrom7934ac22013-07-26 10:54:15 -07003906 JDWP::Append4BE(bytes, heap->GetMaxMemory()); // Max allowed heap size in bytes.
3907 JDWP::Append4BE(bytes, heap->GetTotalMemory()); // Current heap size in bytes.
Elliott Hughesb3bd5f02012-03-08 21:05:27 -08003908 JDWP::Append4BE(bytes, heap->GetBytesAllocated());
3909 JDWP::Append4BE(bytes, heap->GetObjectsAllocated());
Elliott Hughes21f32d72011-11-09 17:44:13 -08003910 CHECK_EQ(bytes.size(), 4U + (heap_count * (4 + 8 + 1 + 4 + 4 + 4 + 4)));
3911 Dbg::DdmSendChunk(CHUNK_TYPE("HPIF"), bytes);
Elliott Hughes767a1472011-10-26 18:49:02 -07003912}
3913
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003914enum HpsgSolidity {
3915 SOLIDITY_FREE = 0,
3916 SOLIDITY_HARD = 1,
3917 SOLIDITY_SOFT = 2,
3918 SOLIDITY_WEAK = 3,
3919 SOLIDITY_PHANTOM = 4,
3920 SOLIDITY_FINALIZABLE = 5,
3921 SOLIDITY_SWEEP = 6,
3922};
3923
3924enum HpsgKind {
3925 KIND_OBJECT = 0,
3926 KIND_CLASS_OBJECT = 1,
3927 KIND_ARRAY_1 = 2,
3928 KIND_ARRAY_2 = 3,
3929 KIND_ARRAY_4 = 4,
3930 KIND_ARRAY_8 = 5,
3931 KIND_UNKNOWN = 6,
3932 KIND_NATIVE = 7,
3933};
3934
3935#define HPSG_PARTIAL (1<<7)
3936#define HPSG_STATE(solidity, kind) ((uint8_t)((((kind) & 0x7) << 3) | ((solidity) & 0x7)))
3937
Ian Rogers30fab402012-01-23 15:43:46 -08003938class HeapChunkContext {
3939 public:
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003940 // Maximum chunk size. Obtain this from the formula:
3941 // (((maximum_heap_size / ALLOCATION_UNIT_SIZE) + 255) / 256) * 2
3942 HeapChunkContext(bool merge, bool native)
Ian Rogers30fab402012-01-23 15:43:46 -08003943 : buf_(16384 - 16),
3944 type_(0),
3945 merge_(merge) {
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003946 Reset();
3947 if (native) {
Ian Rogers30fab402012-01-23 15:43:46 -08003948 type_ = CHUNK_TYPE("NHSG");
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003949 } else {
Ian Rogers30fab402012-01-23 15:43:46 -08003950 type_ = merge ? CHUNK_TYPE("HPSG") : CHUNK_TYPE("HPSO");
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003951 }
3952 }
3953
3954 ~HeapChunkContext() {
Ian Rogers30fab402012-01-23 15:43:46 -08003955 if (p_ > &buf_[0]) {
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003956 Flush();
3957 }
3958 }
3959
3960 void EnsureHeader(const void* chunk_ptr) {
Ian Rogers30fab402012-01-23 15:43:46 -08003961 if (!needHeader_) {
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003962 return;
3963 }
3964
3965 // Start a new HPSx chunk.
Brian Carlstrom7934ac22013-07-26 10:54:15 -07003966 JDWP::Write4BE(&p_, 1); // Heap id (bogus; we only have one heap).
3967 JDWP::Write1BE(&p_, 8); // Size of allocation unit, in bytes.
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003968
Brian Carlstrom7934ac22013-07-26 10:54:15 -07003969 JDWP::Write4BE(&p_, reinterpret_cast<uintptr_t>(chunk_ptr)); // virtual address of segment start.
3970 JDWP::Write4BE(&p_, 0); // offset of this piece (relative to the virtual address).
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003971 // [u4]: length of piece, in allocation units
3972 // 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 -08003973 pieceLenField_ = p_;
3974 JDWP::Write4BE(&p_, 0x55555555);
3975 needHeader_ = false;
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003976 }
3977
Ian Rogersb726dcb2012-09-05 08:57:23 -07003978 void Flush() SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Ian Rogersd636b062013-01-18 17:51:18 -08003979 if (pieceLenField_ == NULL) {
3980 // Flush immediately post Reset (maybe back-to-back Flush). Ignore.
3981 CHECK(needHeader_);
3982 return;
3983 }
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003984 // Patch the "length of piece" field.
Ian Rogers30fab402012-01-23 15:43:46 -08003985 CHECK_LE(&buf_[0], pieceLenField_);
3986 CHECK_LE(pieceLenField_, p_);
3987 JDWP::Set4BE(pieceLenField_, totalAllocationUnits_);
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003988
Ian Rogers30fab402012-01-23 15:43:46 -08003989 Dbg::DdmSendChunk(type_, p_ - &buf_[0], &buf_[0]);
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003990 Reset();
3991 }
3992
Ian Rogers00f7d0e2012-07-19 15:28:27 -07003993 static void HeapChunkCallback(void* start, void* end, size_t used_bytes, void* arg)
Ian Rogersb726dcb2012-09-05 08:57:23 -07003994 SHARED_LOCKS_REQUIRED(Locks::heap_bitmap_lock_,
3995 Locks::mutator_lock_) {
Ian Rogers30fab402012-01-23 15:43:46 -08003996 reinterpret_cast<HeapChunkContext*>(arg)->HeapChunkCallback(start, end, used_bytes);
Elliott Hughesa2155262011-11-16 16:26:58 -08003997 }
3998
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003999 private:
Elliott Hughesa2155262011-11-16 16:26:58 -08004000 enum { ALLOCATION_UNIT_SIZE = 8 };
4001
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004002 void Reset() {
Ian Rogers30fab402012-01-23 15:43:46 -08004003 p_ = &buf_[0];
Ian Rogers15bf2d32012-08-28 17:33:04 -07004004 startOfNextMemoryChunk_ = NULL;
Ian Rogers30fab402012-01-23 15:43:46 -08004005 totalAllocationUnits_ = 0;
4006 needHeader_ = true;
4007 pieceLenField_ = NULL;
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004008 }
4009
Ian Rogers00f7d0e2012-07-19 15:28:27 -07004010 void HeapChunkCallback(void* start, void* /*end*/, size_t used_bytes)
Ian Rogersb726dcb2012-09-05 08:57:23 -07004011 SHARED_LOCKS_REQUIRED(Locks::heap_bitmap_lock_,
4012 Locks::mutator_lock_) {
Ian Rogers30fab402012-01-23 15:43:46 -08004013 // Note: heap call backs cannot manipulate the heap upon which they are crawling, care is taken
4014 // in the following code not to allocate memory, by ensuring buf_ is of the correct size
Ian Rogers15bf2d32012-08-28 17:33:04 -07004015 if (used_bytes == 0) {
4016 if (start == NULL) {
4017 // Reset for start of new heap.
4018 startOfNextMemoryChunk_ = NULL;
4019 Flush();
4020 }
4021 // Only process in use memory so that free region information
4022 // also includes dlmalloc book keeping.
Elliott Hughesa2155262011-11-16 16:26:58 -08004023 return;
Elliott Hughesa2155262011-11-16 16:26:58 -08004024 }
4025
Ian Rogers15bf2d32012-08-28 17:33:04 -07004026 /* If we're looking at the native heap, we'll just return
4027 * (SOLIDITY_HARD, KIND_NATIVE) for all allocated chunks
4028 */
4029 bool native = type_ == CHUNK_TYPE("NHSG");
4030
4031 if (startOfNextMemoryChunk_ != NULL) {
4032 // Transmit any pending free memory. Native free memory of
4033 // over kMaxFreeLen could be because of the use of mmaps, so
4034 // don't report. If not free memory then start a new segment.
4035 bool flush = true;
4036 if (start > startOfNextMemoryChunk_) {
4037 const size_t kMaxFreeLen = 2 * kPageSize;
4038 void* freeStart = startOfNextMemoryChunk_;
4039 void* freeEnd = start;
Brian Carlstrom2d888622013-07-18 17:02:00 -07004040 size_t freeLen = reinterpret_cast<char*>(freeEnd) - reinterpret_cast<char*>(freeStart);
Ian Rogers15bf2d32012-08-28 17:33:04 -07004041 if (!native || freeLen < kMaxFreeLen) {
4042 AppendChunk(HPSG_STATE(SOLIDITY_FREE, 0), freeStart, freeLen);
4043 flush = false;
4044 }
4045 }
4046 if (flush) {
4047 startOfNextMemoryChunk_ = NULL;
4048 Flush();
4049 }
4050 }
Ian Rogersef7d42f2014-01-06 12:55:46 -08004051 mirror::Object* obj = reinterpret_cast<mirror::Object*>(start);
Elliott Hughesa2155262011-11-16 16:26:58 -08004052
4053 // Determine the type of this chunk.
4054 // OLD-TODO: if context.merge, see if this chunk is different from the last chunk.
4055 // If it's the same, we should combine them.
Ian Rogers15bf2d32012-08-28 17:33:04 -07004056 uint8_t state = ExamineObject(obj, native);
4057 // dlmalloc's chunk header is 2 * sizeof(size_t), but if the previous chunk is in use for an
4058 // allocation then the first sizeof(size_t) may belong to it.
4059 const size_t dlMallocOverhead = sizeof(size_t);
4060 AppendChunk(state, start, used_bytes + dlMallocOverhead);
Brian Carlstrom2d888622013-07-18 17:02:00 -07004061 startOfNextMemoryChunk_ = reinterpret_cast<char*>(start) + used_bytes + dlMallocOverhead;
Ian Rogers15bf2d32012-08-28 17:33:04 -07004062 }
Elliott Hughesa2155262011-11-16 16:26:58 -08004063
Ian Rogers15bf2d32012-08-28 17:33:04 -07004064 void AppendChunk(uint8_t state, void* ptr, size_t length)
Ian Rogersb726dcb2012-09-05 08:57:23 -07004065 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Ian Rogers15bf2d32012-08-28 17:33:04 -07004066 // Make sure there's enough room left in the buffer.
4067 // We need to use two bytes for every fractional 256 allocation units used by the chunk plus
4068 // 17 bytes for any header.
4069 size_t needed = (((length/ALLOCATION_UNIT_SIZE + 255) / 256) * 2) + 17;
4070 size_t bytesLeft = buf_.size() - (size_t)(p_ - &buf_[0]);
4071 if (bytesLeft < needed) {
4072 Flush();
4073 }
4074
4075 bytesLeft = buf_.size() - (size_t)(p_ - &buf_[0]);
4076 if (bytesLeft < needed) {
4077 LOG(WARNING) << "Chunk is too big to transmit (chunk_len=" << length << ", "
4078 << needed << " bytes)";
4079 return;
4080 }
4081 EnsureHeader(ptr);
Elliott Hughesa2155262011-11-16 16:26:58 -08004082 // Write out the chunk description.
Ian Rogers15bf2d32012-08-28 17:33:04 -07004083 length /= ALLOCATION_UNIT_SIZE; // Convert to allocation units.
4084 totalAllocationUnits_ += length;
4085 while (length > 256) {
Ian Rogers30fab402012-01-23 15:43:46 -08004086 *p_++ = state | HPSG_PARTIAL;
4087 *p_++ = 255; // length - 1
Ian Rogers15bf2d32012-08-28 17:33:04 -07004088 length -= 256;
Elliott Hughesa2155262011-11-16 16:26:58 -08004089 }
Ian Rogers30fab402012-01-23 15:43:46 -08004090 *p_++ = state;
Ian Rogers15bf2d32012-08-28 17:33:04 -07004091 *p_++ = length - 1;
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004092 }
4093
Ian Rogersef7d42f2014-01-06 12:55:46 -08004094 uint8_t ExamineObject(mirror::Object* o, bool is_native_heap)
4095 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_, Locks::heap_bitmap_lock_) {
Elliott Hughesa2155262011-11-16 16:26:58 -08004096 if (o == NULL) {
4097 return HPSG_STATE(SOLIDITY_FREE, 0);
4098 }
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004099
Elliott Hughesa2155262011-11-16 16:26:58 -08004100 // It's an allocated chunk. Figure out what it is.
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004101
Elliott Hughesa2155262011-11-16 16:26:58 -08004102 // If we're looking at the native heap, we'll just return
4103 // (SOLIDITY_HARD, KIND_NATIVE) for all allocated chunks.
Ian Rogers00f7d0e2012-07-19 15:28:27 -07004104 if (is_native_heap) {
Elliott Hughesa2155262011-11-16 16:26:58 -08004105 return HPSG_STATE(SOLIDITY_HARD, KIND_NATIVE);
4106 }
4107
Ian Rogers5bfa60f2012-09-02 21:17:56 -07004108 if (!Runtime::Current()->GetHeap()->IsLiveObjectLocked(o)) {
Ian Rogers15bf2d32012-08-28 17:33:04 -07004109 return HPSG_STATE(SOLIDITY_HARD, KIND_NATIVE);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07004110 }
4111
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08004112 mirror::Class* c = o->GetClass();
Elliott Hughesa2155262011-11-16 16:26:58 -08004113 if (c == NULL) {
4114 // The object was probably just created but hasn't been initialized yet.
4115 return HPSG_STATE(SOLIDITY_HARD, KIND_OBJECT);
4116 }
4117
Mathieu Chartier590fee92013-09-13 13:46:47 -07004118 if (!Runtime::Current()->GetHeap()->IsValidObjectAddress(c)) {
Ian Rogers15bf2d32012-08-28 17:33:04 -07004119 LOG(ERROR) << "Invalid class for managed heap object: " << o << " " << c;
Elliott Hughesa2155262011-11-16 16:26:58 -08004120 return HPSG_STATE(SOLIDITY_HARD, KIND_UNKNOWN);
4121 }
4122
4123 if (c->IsClassClass()) {
4124 return HPSG_STATE(SOLIDITY_HARD, KIND_CLASS_OBJECT);
4125 }
4126
4127 if (c->IsArrayClass()) {
4128 if (o->IsObjectArray()) {
4129 return HPSG_STATE(SOLIDITY_HARD, KIND_ARRAY_4);
4130 }
4131 switch (c->GetComponentSize()) {
4132 case 1: return HPSG_STATE(SOLIDITY_HARD, KIND_ARRAY_1);
4133 case 2: return HPSG_STATE(SOLIDITY_HARD, KIND_ARRAY_2);
4134 case 4: return HPSG_STATE(SOLIDITY_HARD, KIND_ARRAY_4);
4135 case 8: return HPSG_STATE(SOLIDITY_HARD, KIND_ARRAY_8);
4136 }
4137 }
4138
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004139 return HPSG_STATE(SOLIDITY_HARD, KIND_OBJECT);
4140 }
4141
Ian Rogers30fab402012-01-23 15:43:46 -08004142 std::vector<uint8_t> buf_;
4143 uint8_t* p_;
4144 uint8_t* pieceLenField_;
Ian Rogers15bf2d32012-08-28 17:33:04 -07004145 void* startOfNextMemoryChunk_;
Ian Rogers30fab402012-01-23 15:43:46 -08004146 size_t totalAllocationUnits_;
4147 uint32_t type_;
4148 bool merge_;
4149 bool needHeader_;
4150
Elliott Hughesa2155262011-11-16 16:26:58 -08004151 DISALLOW_COPY_AND_ASSIGN(HeapChunkContext);
4152};
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004153
4154void Dbg::DdmSendHeapSegments(bool native) {
4155 Dbg::HpsgWhen when;
4156 Dbg::HpsgWhat what;
4157 if (!native) {
4158 when = gDdmHpsgWhen;
4159 what = gDdmHpsgWhat;
4160 } else {
4161 when = gDdmNhsgWhen;
4162 what = gDdmNhsgWhat;
4163 }
4164 if (when == HPSG_WHEN_NEVER) {
4165 return;
4166 }
4167
4168 // Figure out what kind of chunks we'll be sending.
4169 CHECK(what == HPSG_WHAT_MERGED_OBJECTS || what == HPSG_WHAT_DISTINCT_OBJECTS) << static_cast<int>(what);
4170
4171 // First, send a heap start chunk.
4172 uint8_t heap_id[4];
Brian Carlstrom7934ac22013-07-26 10:54:15 -07004173 JDWP::Set4BE(&heap_id[0], 1); // Heap id (bogus; we only have one heap).
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004174 Dbg::DdmSendChunk(native ? CHUNK_TYPE("NHST") : CHUNK_TYPE("HPST"), sizeof(heap_id), heap_id);
4175
Hiroshi Yamauchicf58d4a2013-09-26 14:21:22 -07004176 Thread* self = Thread::Current();
4177
4178 // To allow the Walk/InspectAll() below to exclusively-lock the
4179 // mutator lock, temporarily release the shared access to the
4180 // mutator lock here by transitioning to the suspended state.
4181 Locks::mutator_lock_->AssertSharedHeld(self);
4182 self->TransitionFromRunnableToSuspended(kSuspended);
4183
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004184 // Send a series of heap segment chunks.
Elliott Hughesa2155262011-11-16 16:26:58 -08004185 HeapChunkContext context((what == HPSG_WHAT_MERGED_OBJECTS), native);
4186 if (native) {
Christopher Ferrisc4ddc042014-05-13 14:47:50 -07004187#ifdef USE_DLMALLOC
Ian Rogers1d54e732013-05-02 21:10:01 -07004188 dlmalloc_inspect_all(HeapChunkContext::HeapChunkCallback, &context);
Christopher Ferrisc4ddc042014-05-13 14:47:50 -07004189#else
4190 UNIMPLEMENTED(WARNING) << "Native heap inspection is only supported with dlmalloc";
4191#endif
Elliott Hughesa2155262011-11-16 16:26:58 -08004192 } else {
Ian Rogers1d54e732013-05-02 21:10:01 -07004193 gc::Heap* heap = Runtime::Current()->GetHeap();
4194 const std::vector<gc::space::ContinuousSpace*>& spaces = heap->GetContinuousSpaces();
Ian Rogers1d54e732013-05-02 21:10:01 -07004195 typedef std::vector<gc::space::ContinuousSpace*>::const_iterator It;
4196 for (It cur = spaces.begin(), end = spaces.end(); cur != end; ++cur) {
Hiroshi Yamauchicf58d4a2013-09-26 14:21:22 -07004197 if ((*cur)->IsMallocSpace()) {
4198 (*cur)->AsMallocSpace()->Walk(HeapChunkContext::HeapChunkCallback, &context);
Mathieu Chartierb062fdd2012-07-03 09:51:48 -07004199 }
4200 }
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -07004201 // Walk the large objects, these are not in the AllocSpace.
4202 heap->GetLargeObjectsSpace()->Walk(HeapChunkContext::HeapChunkCallback, &context);
Elliott Hughesa2155262011-11-16 16:26:58 -08004203 }
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004204
Hiroshi Yamauchicf58d4a2013-09-26 14:21:22 -07004205 // Shared-lock the mutator lock back.
4206 self->TransitionFromSuspendedToRunnable();
4207 Locks::mutator_lock_->AssertSharedHeld(self);
4208
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004209 // Finally, send a heap end chunk.
4210 Dbg::DdmSendChunk(native ? CHUNK_TYPE("NHEN") : CHUNK_TYPE("HPEN"), sizeof(heap_id), heap_id);
Elliott Hughes767a1472011-10-26 18:49:02 -07004211}
4212
Elliott Hughesb1a58792013-07-11 18:10:58 -07004213static size_t GetAllocTrackerMax() {
4214#ifdef HAVE_ANDROID_OS
4215 // Check whether there's a system property overriding the number of records.
4216 const char* propertyName = "dalvik.vm.allocTrackerMax";
4217 char allocRecordMaxString[PROPERTY_VALUE_MAX];
4218 if (property_get(propertyName, allocRecordMaxString, "") > 0) {
4219 char* end;
4220 size_t value = strtoul(allocRecordMaxString, &end, 10);
4221 if (*end != '\0') {
Ruben Brunk3e47a742013-09-09 17:56:07 -07004222 LOG(ERROR) << "Ignoring " << propertyName << " '" << allocRecordMaxString
4223 << "' --- invalid";
Elliott Hughesb1a58792013-07-11 18:10:58 -07004224 return kDefaultNumAllocRecords;
4225 }
4226 if (!IsPowerOfTwo(value)) {
Ruben Brunk3e47a742013-09-09 17:56:07 -07004227 LOG(ERROR) << "Ignoring " << propertyName << " '" << allocRecordMaxString
4228 << "' --- not power of two";
Elliott Hughesb1a58792013-07-11 18:10:58 -07004229 return kDefaultNumAllocRecords;
4230 }
4231 return value;
4232 }
4233#endif
4234 return kDefaultNumAllocRecords;
4235}
4236
Elliott Hughes545a0642011-11-08 19:10:03 -08004237void Dbg::SetAllocTrackingEnabled(bool enabled) {
Elliott Hughes545a0642011-11-08 19:10:03 -08004238 if (enabled) {
Sebastien Hertzb98063a2014-03-26 10:57:20 +01004239 {
4240 MutexLock mu(Thread::Current(), *alloc_tracker_lock_);
4241 if (recent_allocation_records_ == NULL) {
4242 alloc_record_max_ = GetAllocTrackerMax();
4243 LOG(INFO) << "Enabling alloc tracker (" << alloc_record_max_ << " entries of "
4244 << kMaxAllocRecordStackDepth << " frames, taking "
4245 << PrettySize(sizeof(AllocRecord) * alloc_record_max_) << ")";
4246 alloc_record_head_ = alloc_record_count_ = 0;
4247 recent_allocation_records_ = new AllocRecord[alloc_record_max_];
4248 CHECK(recent_allocation_records_ != NULL);
4249 }
Elliott Hughes545a0642011-11-08 19:10:03 -08004250 }
Ian Rogersfa824272013-11-05 16:12:57 -08004251 Runtime::Current()->GetInstrumentation()->InstrumentQuickAllocEntryPoints();
Elliott Hughes545a0642011-11-08 19:10:03 -08004252 } else {
Ian Rogersfa824272013-11-05 16:12:57 -08004253 Runtime::Current()->GetInstrumentation()->UninstrumentQuickAllocEntryPoints();
Sebastien Hertzb98063a2014-03-26 10:57:20 +01004254 {
4255 MutexLock mu(Thread::Current(), *alloc_tracker_lock_);
4256 delete[] recent_allocation_records_;
4257 recent_allocation_records_ = NULL;
4258 }
Elliott Hughes545a0642011-11-08 19:10:03 -08004259 }
4260}
4261
Ian Rogers0399dde2012-06-06 17:09:28 -07004262struct AllocRecordStackVisitor : public StackVisitor {
Ian Rogers7a22fa62013-01-23 12:16:16 -08004263 AllocRecordStackVisitor(Thread* thread, AllocRecord* record)
Ian Rogersb726dcb2012-09-05 08:57:23 -07004264 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_)
Ian Rogers7a22fa62013-01-23 12:16:16 -08004265 : StackVisitor(thread, NULL), record(record), depth(0) {}
Elliott Hughes545a0642011-11-08 19:10:03 -08004266
Ian Rogers00f7d0e2012-07-19 15:28:27 -07004267 // TODO: Enable annotalysis. We know lock is held in constructor, but abstraction confuses
4268 // annotalysis.
4269 bool VisitFrame() NO_THREAD_SAFETY_ANALYSIS {
Elliott Hughes545a0642011-11-08 19:10:03 -08004270 if (depth >= kMaxAllocRecordStackDepth) {
Elliott Hughes530fa002012-03-12 11:44:49 -07004271 return false;
Elliott Hughes545a0642011-11-08 19:10:03 -08004272 }
Brian Carlstromea46f952013-07-30 01:26:50 -07004273 mirror::ArtMethod* m = GetMethod();
Ian Rogers0399dde2012-06-06 17:09:28 -07004274 if (!m->IsRuntimeMethod()) {
Hiroshi Yamauchib5a9e3d2014-06-09 12:11:20 -07004275 record->StackElement(depth)->SetMethod(m);
4276 record->StackElement(depth)->SetDexPc(GetDexPc());
Elliott Hughes530fa002012-03-12 11:44:49 -07004277 ++depth;
Elliott Hughes545a0642011-11-08 19:10:03 -08004278 }
Elliott Hughes530fa002012-03-12 11:44:49 -07004279 return true;
Elliott Hughes545a0642011-11-08 19:10:03 -08004280 }
4281
4282 ~AllocRecordStackVisitor() {
4283 // Clear out any unused stack trace elements.
4284 for (; depth < kMaxAllocRecordStackDepth; ++depth) {
Hiroshi Yamauchib5a9e3d2014-06-09 12:11:20 -07004285 record->StackElement(depth)->SetMethod(nullptr);
4286 record->StackElement(depth)->SetDexPc(0);
Elliott Hughes545a0642011-11-08 19:10:03 -08004287 }
4288 }
4289
4290 AllocRecord* record;
4291 size_t depth;
4292};
4293
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08004294void Dbg::RecordAllocation(mirror::Class* type, size_t byte_count) {
Elliott Hughes545a0642011-11-08 19:10:03 -08004295 Thread* self = Thread::Current();
4296 CHECK(self != NULL);
4297
Ian Rogers719d1a32014-03-06 12:13:39 -08004298 MutexLock mu(self, *alloc_tracker_lock_);
Elliott Hughes545a0642011-11-08 19:10:03 -08004299 if (recent_allocation_records_ == NULL) {
4300 return;
4301 }
4302
4303 // Advance and clip.
Ian Rogers719d1a32014-03-06 12:13:39 -08004304 if (++alloc_record_head_ == alloc_record_max_) {
4305 alloc_record_head_ = 0;
Elliott Hughes545a0642011-11-08 19:10:03 -08004306 }
4307
4308 // Fill in the basics.
Ian Rogers719d1a32014-03-06 12:13:39 -08004309 AllocRecord* record = &recent_allocation_records_[alloc_record_head_];
Hiroshi Yamauchib5a9e3d2014-06-09 12:11:20 -07004310 record->SetType(type);
4311 record->SetByteCount(byte_count);
4312 record->SetThinLockId(self->GetThreadId());
Elliott Hughes545a0642011-11-08 19:10:03 -08004313
4314 // Fill in the stack trace.
Ian Rogers7a22fa62013-01-23 12:16:16 -08004315 AllocRecordStackVisitor visitor(self, record);
Ian Rogers0399dde2012-06-06 17:09:28 -07004316 visitor.WalkStack();
Elliott Hughes545a0642011-11-08 19:10:03 -08004317
Ian Rogers719d1a32014-03-06 12:13:39 -08004318 if (alloc_record_count_ < alloc_record_max_) {
4319 ++alloc_record_count_;
Elliott Hughes545a0642011-11-08 19:10:03 -08004320 }
4321}
4322
Elliott Hughesa8f93cb2012-06-08 17:08:48 -07004323// Returns the index of the head element.
4324//
4325// We point at the most-recently-written record, so if gAllocRecordCount is 1
4326// we want to use the current element. Take "head+1" and subtract count
4327// from it.
4328//
4329// We need to handle underflow in our circular buffer, so we add
Elliott Hughesb1a58792013-07-11 18:10:58 -07004330// gAllocRecordMax and then mask it back down.
Ian Rogers719d1a32014-03-06 12:13:39 -08004331size_t Dbg::HeadIndex() {
4332 return (Dbg::alloc_record_head_ + 1 + Dbg::alloc_record_max_ - Dbg::alloc_record_count_) &
4333 (Dbg::alloc_record_max_ - 1);
Elliott Hughes545a0642011-11-08 19:10:03 -08004334}
4335
4336void Dbg::DumpRecentAllocations() {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07004337 ScopedObjectAccess soa(Thread::Current());
Ian Rogers719d1a32014-03-06 12:13:39 -08004338 MutexLock mu(soa.Self(), *alloc_tracker_lock_);
Elliott Hughes545a0642011-11-08 19:10:03 -08004339 if (recent_allocation_records_ == NULL) {
4340 LOG(INFO) << "Not recording tracked allocations";
4341 return;
4342 }
4343
4344 // "i" is the head of the list. We want to start at the end of the
4345 // list and move forward to the tail.
Elliott Hughesa8f93cb2012-06-08 17:08:48 -07004346 size_t i = HeadIndex();
Ian Rogers719d1a32014-03-06 12:13:39 -08004347 size_t count = alloc_record_count_;
Elliott Hughes545a0642011-11-08 19:10:03 -08004348
Ian Rogers719d1a32014-03-06 12:13:39 -08004349 LOG(INFO) << "Tracked allocations, (head=" << alloc_record_head_ << " count=" << count << ")";
Elliott Hughes545a0642011-11-08 19:10:03 -08004350 while (count--) {
4351 AllocRecord* record = &recent_allocation_records_[i];
4352
Hiroshi Yamauchib5a9e3d2014-06-09 12:11:20 -07004353 LOG(INFO) << StringPrintf(" Thread %-2d %6zd bytes ", record->ThinLockId(), record->ByteCount())
4354 << PrettyClass(record->Type());
Elliott Hughes545a0642011-11-08 19:10:03 -08004355
4356 for (size_t stack_frame = 0; stack_frame < kMaxAllocRecordStackDepth; ++stack_frame) {
Hiroshi Yamauchib5a9e3d2014-06-09 12:11:20 -07004357 AllocRecordStackTraceElement* stack_element = record->StackElement(stack_frame);
4358 mirror::ArtMethod* m = stack_element->Method();
Elliott Hughes545a0642011-11-08 19:10:03 -08004359 if (m == NULL) {
4360 break;
4361 }
Hiroshi Yamauchib5a9e3d2014-06-09 12:11:20 -07004362 LOG(INFO) << " " << PrettyMethod(m) << " line " << stack_element->LineNumber();
Elliott Hughes545a0642011-11-08 19:10:03 -08004363 }
4364
4365 // pause periodically to help logcat catch up
4366 if ((count % 5) == 0) {
4367 usleep(40000);
4368 }
4369
Ian Rogers719d1a32014-03-06 12:13:39 -08004370 i = (i + 1) & (alloc_record_max_ - 1);
Elliott Hughes545a0642011-11-08 19:10:03 -08004371 }
4372}
4373
4374class StringTable {
4375 public:
4376 StringTable() {
4377 }
4378
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08004379 void Add(const char* s) {
Elliott Hughes545a0642011-11-08 19:10:03 -08004380 table_.insert(s);
4381 }
4382
Elliott Hughesa8f93cb2012-06-08 17:08:48 -07004383 size_t IndexOf(const char* s) const {
Mathieu Chartier02e25112013-08-14 16:14:24 -07004384 auto it = table_.find(s);
Elliott Hughesa8f93cb2012-06-08 17:08:48 -07004385 if (it == table_.end()) {
4386 LOG(FATAL) << "IndexOf(\"" << s << "\") failed";
4387 }
4388 return std::distance(table_.begin(), it);
Elliott Hughes545a0642011-11-08 19:10:03 -08004389 }
4390
Elliott Hughesa8f93cb2012-06-08 17:08:48 -07004391 size_t Size() const {
Elliott Hughes545a0642011-11-08 19:10:03 -08004392 return table_.size();
4393 }
4394
Elliott Hughesa8f93cb2012-06-08 17:08:48 -07004395 void WriteTo(std::vector<uint8_t>& bytes) const {
Mathieu Chartier02e25112013-08-14 16:14:24 -07004396 for (const std::string& str : table_) {
4397 const char* s = str.c_str();
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08004398 size_t s_len = CountModifiedUtf8Chars(s);
Ian Rogers700a4022014-05-19 16:49:03 -07004399 std::unique_ptr<uint16_t> s_utf16(new uint16_t[s_len]);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08004400 ConvertModifiedUtf8ToUtf16(s_utf16.get(), s);
4401 JDWP::AppendUtf16BE(bytes, s_utf16.get(), s_len);
Elliott Hughes545a0642011-11-08 19:10:03 -08004402 }
4403 }
4404
4405 private:
Elliott Hughesa8f93cb2012-06-08 17:08:48 -07004406 std::set<std::string> table_;
Elliott Hughes545a0642011-11-08 19:10:03 -08004407 DISALLOW_COPY_AND_ASSIGN(StringTable);
4408};
4409
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07004410static const char* GetMethodSourceFile(mirror::ArtMethod* method)
Sebastien Hertz280286a2014-04-28 09:26:50 +02004411 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07004412 DCHECK(method != nullptr);
4413 const char* source_file = method->GetDeclaringClassSourceFile();
Sebastien Hertz280286a2014-04-28 09:26:50 +02004414 return (source_file != nullptr) ? source_file : "";
4415}
4416
Elliott Hughes545a0642011-11-08 19:10:03 -08004417/*
4418 * The data we send to DDMS contains everything we have recorded.
4419 *
4420 * Message header (all values big-endian):
4421 * (1b) message header len (to allow future expansion); includes itself
4422 * (1b) entry header len
4423 * (1b) stack frame len
4424 * (2b) number of entries
4425 * (4b) offset to string table from start of message
4426 * (2b) number of class name strings
4427 * (2b) number of method name strings
4428 * (2b) number of source file name strings
4429 * For each entry:
4430 * (4b) total allocation size
Elliott Hughes221229c2013-01-08 18:17:50 -08004431 * (2b) thread id
Elliott Hughes545a0642011-11-08 19:10:03 -08004432 * (2b) allocated object's class name index
4433 * (1b) stack depth
4434 * For each stack frame:
4435 * (2b) method's class name
4436 * (2b) method name
4437 * (2b) method source file
4438 * (2b) line number, clipped to 32767; -2 if native; -1 if no source
4439 * (xb) class name strings
4440 * (xb) method name strings
4441 * (xb) source file strings
4442 *
4443 * As with other DDM traffic, strings are sent as a 4-byte length
4444 * followed by UTF-16 data.
4445 *
4446 * We send up 16-bit unsigned indexes into string tables. In theory there
Elliott Hughesb1a58792013-07-11 18:10:58 -07004447 * can be (kMaxAllocRecordStackDepth * gAllocRecordMax) unique strings in
Elliott Hughes545a0642011-11-08 19:10:03 -08004448 * each table, but in practice there should be far fewer.
4449 *
4450 * The chief reason for using a string table here is to keep the size of
4451 * the DDMS message to a minimum. This is partly to make the protocol
4452 * efficient, but also because we have to form the whole thing up all at
4453 * once in a memory buffer.
4454 *
4455 * We use separate string tables for class names, method names, and source
4456 * files to keep the indexes small. There will generally be no overlap
4457 * between the contents of these tables.
4458 */
4459jbyteArray Dbg::GetRecentAllocations() {
4460 if (false) {
4461 DumpRecentAllocations();
4462 }
4463
Ian Rogers50b35e22012-10-04 10:09:15 -07004464 Thread* self = Thread::Current();
Elliott Hughes545a0642011-11-08 19:10:03 -08004465 std::vector<uint8_t> bytes;
Mathieu Chartier46e811b2013-07-10 17:09:14 -07004466 {
Ian Rogers719d1a32014-03-06 12:13:39 -08004467 MutexLock mu(self, *alloc_tracker_lock_);
Mathieu Chartier46e811b2013-07-10 17:09:14 -07004468 //
4469 // Part 1: generate string tables.
4470 //
4471 StringTable class_names;
4472 StringTable method_names;
4473 StringTable filenames;
Elliott Hughes545a0642011-11-08 19:10:03 -08004474
Ian Rogers719d1a32014-03-06 12:13:39 -08004475 int count = alloc_record_count_;
Mathieu Chartier46e811b2013-07-10 17:09:14 -07004476 int idx = HeadIndex();
4477 while (count--) {
4478 AllocRecord* record = &recent_allocation_records_[idx];
Elliott Hughes545a0642011-11-08 19:10:03 -08004479
Hiroshi Yamauchib5a9e3d2014-06-09 12:11:20 -07004480 class_names.Add(record->Type()->GetDescriptor().c_str());
Elliott Hughes545a0642011-11-08 19:10:03 -08004481
Mathieu Chartier46e811b2013-07-10 17:09:14 -07004482 for (size_t i = 0; i < kMaxAllocRecordStackDepth; i++) {
Hiroshi Yamauchib5a9e3d2014-06-09 12:11:20 -07004483 mirror::ArtMethod* m = record->StackElement(i)->Method();
Mathieu Chartier46e811b2013-07-10 17:09:14 -07004484 if (m != NULL) {
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07004485 class_names.Add(m->GetDeclaringClassDescriptor());
4486 method_names.Add(m->GetName());
4487 filenames.Add(GetMethodSourceFile(m));
Mathieu Chartier46e811b2013-07-10 17:09:14 -07004488 }
4489 }
Elliott Hughes545a0642011-11-08 19:10:03 -08004490
Ian Rogers719d1a32014-03-06 12:13:39 -08004491 idx = (idx + 1) & (alloc_record_max_ - 1);
Elliott Hughes545a0642011-11-08 19:10:03 -08004492 }
4493
Ian Rogers719d1a32014-03-06 12:13:39 -08004494 LOG(INFO) << "allocation records: " << alloc_record_count_;
Mathieu Chartier46e811b2013-07-10 17:09:14 -07004495
4496 //
4497 // Part 2: Generate the output and store it in the buffer.
4498 //
4499
4500 // (1b) message header len (to allow future expansion); includes itself
4501 // (1b) entry header len
4502 // (1b) stack frame len
4503 const int kMessageHeaderLen = 15;
4504 const int kEntryHeaderLen = 9;
4505 const int kStackFrameLen = 8;
4506 JDWP::Append1BE(bytes, kMessageHeaderLen);
4507 JDWP::Append1BE(bytes, kEntryHeaderLen);
4508 JDWP::Append1BE(bytes, kStackFrameLen);
4509
4510 // (2b) number of entries
4511 // (4b) offset to string table from start of message
4512 // (2b) number of class name strings
4513 // (2b) number of method name strings
4514 // (2b) number of source file name strings
Ian Rogers719d1a32014-03-06 12:13:39 -08004515 JDWP::Append2BE(bytes, alloc_record_count_);
Mathieu Chartier46e811b2013-07-10 17:09:14 -07004516 size_t string_table_offset = bytes.size();
Brian Carlstrom7934ac22013-07-26 10:54:15 -07004517 JDWP::Append4BE(bytes, 0); // We'll patch this later...
Mathieu Chartier46e811b2013-07-10 17:09:14 -07004518 JDWP::Append2BE(bytes, class_names.Size());
4519 JDWP::Append2BE(bytes, method_names.Size());
4520 JDWP::Append2BE(bytes, filenames.Size());
4521
Ian Rogers719d1a32014-03-06 12:13:39 -08004522 count = alloc_record_count_;
Mathieu Chartier46e811b2013-07-10 17:09:14 -07004523 idx = HeadIndex();
Mathieu Chartier46e811b2013-07-10 17:09:14 -07004524 while (count--) {
4525 // For each entry:
4526 // (4b) total allocation size
4527 // (2b) thread id
4528 // (2b) allocated object's class name index
4529 // (1b) stack depth
4530 AllocRecord* record = &recent_allocation_records_[idx];
4531 size_t stack_depth = record->GetDepth();
Mathieu Chartierf8322842014-05-16 10:59:25 -07004532 size_t allocated_object_class_name_index =
Hiroshi Yamauchib5a9e3d2014-06-09 12:11:20 -07004533 class_names.IndexOf(record->Type()->GetDescriptor().c_str());
4534 JDWP::Append4BE(bytes, record->ByteCount());
4535 JDWP::Append2BE(bytes, record->ThinLockId());
Mathieu Chartier46e811b2013-07-10 17:09:14 -07004536 JDWP::Append2BE(bytes, allocated_object_class_name_index);
4537 JDWP::Append1BE(bytes, stack_depth);
4538
Mathieu Chartier46e811b2013-07-10 17:09:14 -07004539 for (size_t stack_frame = 0; stack_frame < stack_depth; ++stack_frame) {
4540 // For each stack frame:
4541 // (2b) method's class name
4542 // (2b) method name
4543 // (2b) method source file
4544 // (2b) line number, clipped to 32767; -2 if native; -1 if no source
Hiroshi Yamauchib5a9e3d2014-06-09 12:11:20 -07004545 mirror::ArtMethod* m = record->StackElement(stack_frame)->Method();
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07004546 size_t class_name_index = class_names.IndexOf(m->GetDeclaringClassDescriptor());
4547 size_t method_name_index = method_names.IndexOf(m->GetName());
4548 size_t file_name_index = filenames.IndexOf(GetMethodSourceFile(m));
Mathieu Chartier46e811b2013-07-10 17:09:14 -07004549 JDWP::Append2BE(bytes, class_name_index);
4550 JDWP::Append2BE(bytes, method_name_index);
4551 JDWP::Append2BE(bytes, file_name_index);
Hiroshi Yamauchib5a9e3d2014-06-09 12:11:20 -07004552 JDWP::Append2BE(bytes, record->StackElement(stack_frame)->LineNumber());
Mathieu Chartier46e811b2013-07-10 17:09:14 -07004553 }
4554
Ian Rogers719d1a32014-03-06 12:13:39 -08004555 idx = (idx + 1) & (alloc_record_max_ - 1);
Mathieu Chartier46e811b2013-07-10 17:09:14 -07004556 }
4557
4558 // (xb) class name strings
4559 // (xb) method name strings
4560 // (xb) source file strings
4561 JDWP::Set4BE(&bytes[string_table_offset], bytes.size());
4562 class_names.WriteTo(bytes);
4563 method_names.WriteTo(bytes);
4564 filenames.WriteTo(bytes);
Elliott Hughes545a0642011-11-08 19:10:03 -08004565 }
Ian Rogers50b35e22012-10-04 10:09:15 -07004566 JNIEnv* env = self->GetJniEnv();
Elliott Hughes545a0642011-11-08 19:10:03 -08004567 jbyteArray result = env->NewByteArray(bytes.size());
4568 if (result != NULL) {
4569 env->SetByteArrayRegion(result, 0, bytes.size(), reinterpret_cast<const jbyte*>(&bytes[0]));
4570 }
4571 return result;
4572}
4573
Elliott Hughes872d4ec2011-10-21 17:07:15 -07004574} // namespace art