blob: 964e84c367a721c09226692e73563b5ff2862125 [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"
Sebastien Hertza76a6d42014-03-20 16:40:17 +010042#include "quick/inline_method_analyser.h"
Ian Rogers53b8b092014-03-13 23:45:53 -070043#include "reflection.h"
Elliott Hughesa0e18062012-04-13 15:59:59 -070044#include "safe_map.h"
Elliott Hughes64f574f2013-02-20 14:57:12 -080045#include "scoped_thread_state_change.h"
Elliott Hughes6a5bd492011-10-28 14:33:57 -070046#include "ScopedLocalRef.h"
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -070047#include "ScopedPrimitiveArray.h"
Mathieu Chartiereb8167a2014-05-07 15:43:14 -070048#include "handle_scope-inl.h"
Elliott Hughes475fc232011-10-25 15:00:35 -070049#include "thread_list.h"
Ian Rogers62d6c772013-02-27 08:32:07 -080050#include "throw_location.h"
Ian Rogers2dd0e2c2013-01-24 12:42:14 -080051#include "utf.h"
Sebastien Hertza76a6d42014-03-20 16:40:17 +010052#include "verifier/method_verifier-inl.h"
Elliott Hugheseac76672012-05-24 21:56:51 -070053#include "well_known_classes.h"
Elliott Hughes475fc232011-10-25 15:00:35 -070054
Brian Carlstrom3d92d522013-07-12 09:03:08 -070055#ifdef HAVE_ANDROID_OS
56#include "cutils/properties.h"
57#endif
58
Elliott Hughes872d4ec2011-10-21 17:07:15 -070059namespace art {
60
Brian Carlstrom7934ac22013-07-26 10:54:15 -070061static const size_t kMaxAllocRecordStackDepth = 16; // Max 255.
Brian Carlstrom306db812014-09-05 13:01:41 -070062static const size_t kDefaultNumAllocRecords = 64*1024; // Must be a power of 2. 2BE can hold 64k-1.
63
64// Limit alloc_record_count to the 2BE value that is the limit of the current protocol.
65static uint16_t CappedAllocRecordCount(size_t alloc_record_count) {
66 if (alloc_record_count > 0xffff) {
67 return 0xffff;
68 }
69 return alloc_record_count;
70}
Elliott Hughes475fc232011-10-25 15:00:35 -070071
Hiroshi Yamauchib5a9e3d2014-06-09 12:11:20 -070072class AllocRecordStackTraceElement {
73 public:
74 AllocRecordStackTraceElement() : method_(nullptr), dex_pc_(0) {
Mathieu Chartier412c7fc2014-02-07 12:18:39 -080075 }
76
Hiroshi Yamauchib5a9e3d2014-06-09 12:11:20 -070077 int32_t LineNumber() SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
78 mirror::ArtMethod* method = Method();
79 DCHECK(method != nullptr);
80 return method->GetLineNumFromDexPC(DexPc());
Elliott Hughes545a0642011-11-08 19:10:03 -080081 }
Hiroshi Yamauchib5a9e3d2014-06-09 12:11:20 -070082
83 mirror::ArtMethod* Method() SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Mathieu Chartier4345c462014-06-27 10:20:14 -070084 ScopedObjectAccessUnchecked soa(Thread::Current());
85 return soa.DecodeMethod(method_);
Hiroshi Yamauchib5a9e3d2014-06-09 12:11:20 -070086 }
87
88 void SetMethod(mirror::ArtMethod* m) SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
89 ScopedObjectAccessUnchecked soa(Thread::Current());
Mathieu Chartier4345c462014-06-27 10:20:14 -070090 method_ = soa.EncodeMethod(m);
Hiroshi Yamauchib5a9e3d2014-06-09 12:11:20 -070091 }
92
93 uint32_t DexPc() const {
94 return dex_pc_;
95 }
96
97 void SetDexPc(uint32_t pc) {
98 dex_pc_ = pc;
99 }
100
101 private:
Mathieu Chartier4345c462014-06-27 10:20:14 -0700102 jmethodID method_;
Hiroshi Yamauchib5a9e3d2014-06-09 12:11:20 -0700103 uint32_t dex_pc_;
Elliott Hughes545a0642011-11-08 19:10:03 -0800104};
105
Mathieu Chartier4345c462014-06-27 10:20:14 -0700106jobject Dbg::TypeCache::Add(mirror::Class* t) {
107 ScopedObjectAccessUnchecked soa(Thread::Current());
Mathieu Chartier4c4d6092015-01-22 17:02:27 -0800108 JNIEnv* const env = soa.Env();
109 ScopedLocalRef<jobject> local_ref(soa.Env(), soa.AddLocalReference<jobject>(t));
110 const int32_t hash_code = soa.Decode<mirror::Class*>(local_ref.get())->IdentityHashCode();
Mathieu Chartier4345c462014-06-27 10:20:14 -0700111 auto range = objects_.equal_range(hash_code);
112 for (auto it = range.first; it != range.second; ++it) {
Mathieu Chartier4c4d6092015-01-22 17:02:27 -0800113 if (soa.Decode<mirror::Class*>(it->second) == soa.Decode<mirror::Class*>(local_ref.get())) {
Mathieu Chartier4345c462014-06-27 10:20:14 -0700114 // Found a matching weak global, return it.
115 return it->second;
116 }
117 }
Mathieu Chartier4c4d6092015-01-22 17:02:27 -0800118 const jobject weak_global = env->NewWeakGlobalRef(local_ref.get());
Mathieu Chartier4345c462014-06-27 10:20:14 -0700119 objects_.insert(std::make_pair(hash_code, weak_global));
120 return weak_global;
121}
122
123void Dbg::TypeCache::Clear() {
Brian Carlstrom306db812014-09-05 13:01:41 -0700124 JavaVMExt* vm = Runtime::Current()->GetJavaVM();
125 Thread* self = Thread::Current();
Mathieu Chartier4345c462014-06-27 10:20:14 -0700126 for (const auto& p : objects_) {
Brian Carlstrom306db812014-09-05 13:01:41 -0700127 vm->DeleteWeakGlobalRef(self, p.second);
Mathieu Chartier4345c462014-06-27 10:20:14 -0700128 }
129 objects_.clear();
130}
131
Hiroshi Yamauchib5a9e3d2014-06-09 12:11:20 -0700132class AllocRecord {
133 public:
134 AllocRecord() : type_(nullptr), byte_count_(0), thin_lock_id_(0) {}
Elliott Hughes545a0642011-11-08 19:10:03 -0800135
Hiroshi Yamauchib5a9e3d2014-06-09 12:11:20 -0700136 mirror::Class* Type() SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Mathieu Chartier4345c462014-06-27 10:20:14 -0700137 return down_cast<mirror::Class*>(Thread::Current()->DecodeJObject(type_));
Hiroshi Yamauchib5a9e3d2014-06-09 12:11:20 -0700138 }
139
Brian Carlstrom306db812014-09-05 13:01:41 -0700140 void SetType(mirror::Class* t) SHARED_LOCKS_REQUIRED(Locks::mutator_lock_,
141 Locks::alloc_tracker_lock_) {
142 type_ = Dbg::type_cache_.Add(t);
Hiroshi Yamauchib5a9e3d2014-06-09 12:11:20 -0700143 }
144
145 size_t GetDepth() SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Elliott Hughes545a0642011-11-08 19:10:03 -0800146 size_t depth = 0;
Ian Rogersc0542af2014-09-03 16:16:56 -0700147 while (depth < kMaxAllocRecordStackDepth && stack_[depth].Method() != nullptr) {
Elliott Hughes545a0642011-11-08 19:10:03 -0800148 ++depth;
149 }
150 return depth;
151 }
Mathieu Chartier412c7fc2014-02-07 12:18:39 -0800152
Hiroshi Yamauchib5a9e3d2014-06-09 12:11:20 -0700153 size_t ByteCount() const {
154 return byte_count_;
Mathieu Chartier412c7fc2014-02-07 12:18:39 -0800155 }
Hiroshi Yamauchib5a9e3d2014-06-09 12:11:20 -0700156
157 void SetByteCount(size_t count) {
158 byte_count_ = count;
159 }
160
161 uint16_t ThinLockId() const {
162 return thin_lock_id_;
163 }
164
165 void SetThinLockId(uint16_t id) {
166 thin_lock_id_ = id;
167 }
168
169 AllocRecordStackTraceElement* StackElement(size_t index) {
170 DCHECK_LT(index, kMaxAllocRecordStackDepth);
171 return &stack_[index];
172 }
173
174 private:
175 jobject type_; // This is a weak global.
176 size_t byte_count_;
177 uint16_t thin_lock_id_;
Ian Rogersc0542af2014-09-03 16:16:56 -0700178 AllocRecordStackTraceElement stack_[kMaxAllocRecordStackDepth]; // Unused entries have nullptr method.
Elliott Hughes545a0642011-11-08 19:10:03 -0800179};
180
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -0700181class Breakpoint {
182 public:
Sebastien Hertzf3928792014-11-17 19:00:37 +0100183 Breakpoint(mirror::ArtMethod* method, uint32_t dex_pc,
184 DeoptimizationRequest::Kind deoptimization_kind)
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -0700185 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_)
Sebastien Hertzf3928792014-11-17 19:00:37 +0100186 : method_(nullptr), dex_pc_(dex_pc), deoptimization_kind_(deoptimization_kind) {
187 CHECK(deoptimization_kind_ == DeoptimizationRequest::kNothing ||
188 deoptimization_kind_ == DeoptimizationRequest::kSelectiveDeoptimization ||
189 deoptimization_kind_ == DeoptimizationRequest::kFullDeoptimization);
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -0700190 ScopedObjectAccessUnchecked soa(Thread::Current());
191 method_ = soa.EncodeMethod(method);
192 }
193
194 Breakpoint(const Breakpoint& other) SHARED_LOCKS_REQUIRED(Locks::mutator_lock_)
195 : method_(nullptr), dex_pc_(other.dex_pc_),
Sebastien Hertzf3928792014-11-17 19:00:37 +0100196 deoptimization_kind_(other.deoptimization_kind_) {
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -0700197 ScopedObjectAccessUnchecked soa(Thread::Current());
198 method_ = soa.EncodeMethod(other.Method());
199 }
200
201 mirror::ArtMethod* Method() const SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
202 ScopedObjectAccessUnchecked soa(Thread::Current());
203 return soa.DecodeMethod(method_);
204 }
205
206 uint32_t DexPc() const {
207 return dex_pc_;
208 }
209
Sebastien Hertzf3928792014-11-17 19:00:37 +0100210 DeoptimizationRequest::Kind GetDeoptimizationKind() const {
211 return deoptimization_kind_;
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -0700212 }
213
214 private:
Sebastien Hertza76a6d42014-03-20 16:40:17 +0100215 // The location of this breakpoint.
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -0700216 jmethodID method_;
217 uint32_t dex_pc_;
Sebastien Hertza76a6d42014-03-20 16:40:17 +0100218
219 // Indicates whether breakpoint needs full deoptimization or selective deoptimization.
Sebastien Hertzf3928792014-11-17 19:00:37 +0100220 DeoptimizationRequest::Kind deoptimization_kind_;
Elliott Hughes86964332012-02-15 19:37:42 -0800221};
222
Sebastien Hertzed2be172014-08-19 15:33:43 +0200223static std::ostream& operator<<(std::ostream& os, const Breakpoint& rhs)
Ian Rogersb726dcb2012-09-05 08:57:23 -0700224 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -0700225 os << StringPrintf("Breakpoint[%s @%#x]", PrettyMethod(rhs.Method()).c_str(), rhs.DexPc());
Elliott Hughes86964332012-02-15 19:37:42 -0800226 return os;
227}
228
Sebastien Hertz3f52eaf2014-04-04 17:50:18 +0200229class DebugInstrumentationListener FINAL : public instrumentation::InstrumentationListener {
Ian Rogers62d6c772013-02-27 08:32:07 -0800230 public:
231 DebugInstrumentationListener() {}
232 virtual ~DebugInstrumentationListener() {}
233
Sebastien Hertz3f52eaf2014-04-04 17:50:18 +0200234 void MethodEntered(Thread* thread, mirror::Object* this_object, mirror::ArtMethod* method,
Ian Rogers6a3c1fc2014-10-31 00:33:20 -0700235 uint32_t dex_pc ATTRIBUTE_UNUSED)
Sebastien Hertz3f52eaf2014-04-04 17:50:18 +0200236 OVERRIDE SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Ian Rogers62d6c772013-02-27 08:32:07 -0800237 if (method->IsNative()) {
238 // TODO: post location events is a suspension point and native method entry stubs aren't.
239 return;
240 }
Sebastien Hertz8379b222014-02-24 17:38:15 +0100241 Dbg::UpdateDebugger(thread, this_object, method, 0, Dbg::kMethodEntry, nullptr);
Ian Rogers62d6c772013-02-27 08:32:07 -0800242 }
243
Sebastien Hertz3f52eaf2014-04-04 17:50:18 +0200244 void MethodExited(Thread* thread, mirror::Object* this_object, mirror::ArtMethod* method,
245 uint32_t dex_pc, const JValue& return_value)
246 OVERRIDE SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Ian Rogers62d6c772013-02-27 08:32:07 -0800247 if (method->IsNative()) {
248 // TODO: post location events is a suspension point and native method entry stubs aren't.
249 return;
250 }
Sebastien Hertz8379b222014-02-24 17:38:15 +0100251 Dbg::UpdateDebugger(thread, this_object, method, dex_pc, Dbg::kMethodExit, &return_value);
Ian Rogers62d6c772013-02-27 08:32:07 -0800252 }
253
Sebastien Hertz3f52eaf2014-04-04 17:50:18 +0200254 void MethodUnwind(Thread* thread, mirror::Object* this_object, mirror::ArtMethod* method,
255 uint32_t dex_pc)
256 OVERRIDE SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Ian Rogers62d6c772013-02-27 08:32:07 -0800257 // We're not recorded to listen to this kind of event, so complain.
Ian Rogers6a3c1fc2014-10-31 00:33:20 -0700258 UNUSED(thread, this_object, method, dex_pc);
Ian Rogers62d6c772013-02-27 08:32:07 -0800259 LOG(ERROR) << "Unexpected method unwind event in debugger " << PrettyMethod(method)
Sebastien Hertz51db44a2013-11-19 10:00:29 +0100260 << " " << dex_pc;
Ian Rogers62d6c772013-02-27 08:32:07 -0800261 }
262
Sebastien Hertz3f52eaf2014-04-04 17:50:18 +0200263 void DexPcMoved(Thread* thread, mirror::Object* this_object, mirror::ArtMethod* method,
264 uint32_t new_dex_pc)
265 OVERRIDE SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Sebastien Hertz8379b222014-02-24 17:38:15 +0100266 Dbg::UpdateDebugger(thread, this_object, method, new_dex_pc, 0, nullptr);
Ian Rogers62d6c772013-02-27 08:32:07 -0800267 }
268
Sebastien Hertz3f52eaf2014-04-04 17:50:18 +0200269 void FieldRead(Thread* thread, mirror::Object* this_object, mirror::ArtMethod* method,
270 uint32_t dex_pc, mirror::ArtField* field)
271 OVERRIDE SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Ian Rogers6a3c1fc2014-10-31 00:33:20 -0700272 UNUSED(thread);
Sebastien Hertz3f52eaf2014-04-04 17:50:18 +0200273 Dbg::PostFieldAccessEvent(method, dex_pc, this_object, field);
Ian Rogers62d6c772013-02-27 08:32:07 -0800274 }
Sebastien Hertz3f52eaf2014-04-04 17:50:18 +0200275
Ian Rogers6a3c1fc2014-10-31 00:33:20 -0700276 void FieldWritten(Thread* thread ATTRIBUTE_UNUSED, mirror::Object* this_object,
277 mirror::ArtMethod* method, uint32_t dex_pc, mirror::ArtField* field,
278 const JValue& field_value)
Sebastien Hertz3f52eaf2014-04-04 17:50:18 +0200279 OVERRIDE SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
280 Dbg::PostFieldModificationEvent(method, dex_pc, this_object, field, &field_value);
281 }
282
Nicolas Geoffray14691c52015-03-05 10:40:17 +0000283 void ExceptionCaught(Thread* thread ATTRIBUTE_UNUSED, mirror::Throwable* exception_object)
Sebastien Hertz3f52eaf2014-04-04 17:50:18 +0200284 OVERRIDE SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Nicolas Geoffray14691c52015-03-05 10:40:17 +0000285 Dbg::PostException(exception_object);
Sebastien Hertz3f52eaf2014-04-04 17:50:18 +0200286 }
287
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800288 // We only care about how many backward branches were executed in the Jit.
289 void BackwardBranch(Thread* /*thread*/, mirror::ArtMethod* method, int32_t dex_pc_offset)
290 OVERRIDE SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
291 LOG(ERROR) << "Unexpected backward branch event in debugger " << PrettyMethod(method)
292 << " " << dex_pc_offset;
293 }
294
Sebastien Hertz3f52eaf2014-04-04 17:50:18 +0200295 private:
296 DISALLOW_COPY_AND_ASSIGN(DebugInstrumentationListener);
Ian Rogers62d6c772013-02-27 08:32:07 -0800297} gDebugInstrumentationListener;
298
Elliott Hughes4ffd3132011-10-24 12:06:42 -0700299// JDWP is allowed unless the Zygote forbids it.
300static bool gJdwpAllowed = true;
301
Elliott Hughesc0f09332012-03-26 13:27:06 -0700302// Was there a -Xrunjdwp or -agentlib:jdwp= argument on the command line?
Elliott Hughes3bb81562011-10-21 18:52:59 -0700303static bool gJdwpConfigured = false;
304
Sebastien Hertzb3b173b2015-02-06 09:16:32 +0100305// JDWP options for debugging. Only valid if IsJdwpConfigured() is true.
306static JDWP::JdwpOptions gJdwpOptions;
307
Elliott Hughes3bb81562011-10-21 18:52:59 -0700308// Runtime JDWP state.
Ian Rogersc0542af2014-09-03 16:16:56 -0700309static JDWP::JdwpState* gJdwpState = nullptr;
Elliott Hughes3bb81562011-10-21 18:52:59 -0700310static bool gDebuggerConnected; // debugger or DDMS is connected.
311static bool gDebuggerActive; // debugger is making requests.
Elliott Hughes86964332012-02-15 19:37:42 -0800312static bool gDisposed; // debugger called VirtualMachine.Dispose, so we should drop the connection.
Elliott Hughes3bb81562011-10-21 18:52:59 -0700313
Elliott Hughes47fce012011-10-25 18:37:19 -0700314static bool gDdmThreadNotification = false;
315
Elliott Hughes767a1472011-10-26 18:49:02 -0700316// DDMS GC-related settings.
317static Dbg::HpifWhen gDdmHpifWhen = Dbg::HPIF_WHEN_NEVER;
318static Dbg::HpsgWhen gDdmHpsgWhen = Dbg::HPSG_WHEN_NEVER;
319static Dbg::HpsgWhat gDdmHpsgWhat;
320static Dbg::HpsgWhen gDdmNhsgWhen = Dbg::HPSG_WHEN_NEVER;
321static Dbg::HpsgWhat gDdmNhsgWhat;
322
Sebastien Hertz6995c602014-09-09 12:10:13 +0200323ObjectRegistry* Dbg::gRegistry = nullptr;
Elliott Hughes475fc232011-10-25 15:00:35 -0700324
Elliott Hughes545a0642011-11-08 19:10:03 -0800325// Recent allocation tracking.
Ian Rogers719d1a32014-03-06 12:13:39 -0800326AllocRecord* Dbg::recent_allocation_records_ = nullptr; // TODO: CircularBuffer<AllocRecord>
327size_t Dbg::alloc_record_max_ = 0;
328size_t Dbg::alloc_record_head_ = 0;
329size_t Dbg::alloc_record_count_ = 0;
Mathieu Chartier4345c462014-06-27 10:20:14 -0700330Dbg::TypeCache Dbg::type_cache_;
Elliott Hughes545a0642011-11-08 19:10:03 -0800331
Sebastien Hertz138dbfc2013-12-04 18:15:25 +0100332// Deoptimization support.
Sebastien Hertz4d25df32014-03-21 17:44:46 +0100333std::vector<DeoptimizationRequest> Dbg::deoptimization_requests_;
334size_t Dbg::full_deoptimization_event_count_ = 0;
Sebastien Hertz7ec2f1c2014-03-27 20:06:47 +0100335size_t Dbg::delayed_full_undeoptimization_count_ = 0;
Sebastien Hertz138dbfc2013-12-04 18:15:25 +0100336
Sebastien Hertz42cd43f2014-05-13 14:15:41 +0200337// Instrumentation event reference counters.
338size_t Dbg::dex_pc_change_event_ref_count_ = 0;
339size_t Dbg::method_enter_event_ref_count_ = 0;
340size_t Dbg::method_exit_event_ref_count_ = 0;
341size_t Dbg::field_read_event_ref_count_ = 0;
342size_t Dbg::field_write_event_ref_count_ = 0;
343size_t Dbg::exception_catch_event_ref_count_ = 0;
344uint32_t Dbg::instrumentation_events_ = 0;
345
Sebastien Hertz138dbfc2013-12-04 18:15:25 +0100346// Breakpoints.
jeffhao09bfc6a2012-12-11 18:11:43 -0800347static std::vector<Breakpoint> gBreakpoints GUARDED_BY(Locks::breakpoint_lock_);
Elliott Hughes86964332012-02-15 19:37:42 -0800348
Mathieu Chartiere34fa1d2015-01-14 14:55:47 -0800349void DebugInvokeReq::VisitRoots(RootCallback* callback, void* arg, const RootInfo& root_info) {
Mathieu Chartier3b05e9b2014-03-25 09:29:43 -0700350 if (receiver != nullptr) {
Mathieu Chartiere34fa1d2015-01-14 14:55:47 -0800351 callback(&receiver, arg, root_info);
Mathieu Chartier3b05e9b2014-03-25 09:29:43 -0700352 }
353 if (thread != nullptr) {
Mathieu Chartiere34fa1d2015-01-14 14:55:47 -0800354 callback(&thread, arg, root_info);
Mathieu Chartier3b05e9b2014-03-25 09:29:43 -0700355 }
356 if (klass != nullptr) {
Mathieu Chartiere34fa1d2015-01-14 14:55:47 -0800357 callback(reinterpret_cast<mirror::Object**>(&klass), arg, root_info);
Mathieu Chartier3b05e9b2014-03-25 09:29:43 -0700358 }
359 if (method != nullptr) {
Mathieu Chartiere34fa1d2015-01-14 14:55:47 -0800360 callback(reinterpret_cast<mirror::Object**>(&method), arg, root_info);
Mathieu Chartier3b05e9b2014-03-25 09:29:43 -0700361 }
362}
363
Sebastien Hertzbb43b432014-04-14 11:59:08 +0200364void DebugInvokeReq::Clear() {
365 invoke_needed = false;
366 receiver = nullptr;
367 thread = nullptr;
368 klass = nullptr;
369 method = nullptr;
370}
371
Mathieu Chartiere34fa1d2015-01-14 14:55:47 -0800372void SingleStepControl::VisitRoots(RootCallback* callback, void* arg, const RootInfo& root_info) {
Sebastien Hertz597c4f02015-01-26 17:37:14 +0100373 if (method_ != nullptr) {
374 callback(reinterpret_cast<mirror::Object**>(&method_), arg, root_info);
Mathieu Chartier3b05e9b2014-03-25 09:29:43 -0700375 }
376}
377
Sebastien Hertz597c4f02015-01-26 17:37:14 +0100378void SingleStepControl::AddDexPc(uint32_t dex_pc) {
379 dex_pcs_.insert(dex_pc);
Sebastien Hertzbb43b432014-04-14 11:59:08 +0200380}
381
Sebastien Hertz597c4f02015-01-26 17:37:14 +0100382bool SingleStepControl::ContainsDexPc(uint32_t dex_pc) const {
383 return dex_pcs_.find(dex_pc) == dex_pcs_.end();
Sebastien Hertzbb43b432014-04-14 11:59:08 +0200384}
385
Brian Carlstromea46f952013-07-30 01:26:50 -0700386static bool IsBreakpoint(const mirror::ArtMethod* m, uint32_t dex_pc)
jeffhao09bfc6a2012-12-11 18:11:43 -0800387 LOCKS_EXCLUDED(Locks::breakpoint_lock_)
Ian Rogersb726dcb2012-09-05 08:57:23 -0700388 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Sebastien Hertzed2be172014-08-19 15:33:43 +0200389 ReaderMutexLock mu(Thread::Current(), *Locks::breakpoint_lock_);
Sebastien Hertz138dbfc2013-12-04 18:15:25 +0100390 for (size_t i = 0, e = gBreakpoints.size(); i < e; ++i) {
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -0700391 if (gBreakpoints[i].DexPc() == dex_pc && gBreakpoints[i].Method() == m) {
Elliott Hughes86964332012-02-15 19:37:42 -0800392 VLOG(jdwp) << "Hit breakpoint #" << i << ": " << gBreakpoints[i];
393 return true;
394 }
395 }
396 return false;
397}
398
Sebastien Hertz52d131d2014-03-13 16:17:40 +0100399static bool IsSuspendedForDebugger(ScopedObjectAccessUnchecked& soa, Thread* thread)
400 LOCKS_EXCLUDED(Locks::thread_suspend_count_lock_) {
Elliott Hughes9e0c1752013-01-09 14:02:58 -0800401 MutexLock mu(soa.Self(), *Locks::thread_suspend_count_lock_);
402 // A thread may be suspended for GC; in this code, we really want to know whether
403 // there's a debugger suspension active.
404 return thread->IsSuspended() && thread->GetDebugSuspendCount() > 0;
405}
406
Ian Rogersc0542af2014-09-03 16:16:56 -0700407static mirror::Array* DecodeNonNullArray(JDWP::RefTypeId id, JDWP::JdwpError* error)
Ian Rogersb726dcb2012-09-05 08:57:23 -0700408 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Sebastien Hertz6995c602014-09-09 12:10:13 +0200409 mirror::Object* o = Dbg::GetObjectRegistry()->Get<mirror::Object*>(id, error);
Ian Rogersc0542af2014-09-03 16:16:56 -0700410 if (o == nullptr) {
411 *error = JDWP::ERR_INVALID_OBJECT;
412 return nullptr;
Elliott Hughes436e3722012-02-17 20:01:47 -0800413 }
414 if (!o->IsArrayInstance()) {
Ian Rogersc0542af2014-09-03 16:16:56 -0700415 *error = JDWP::ERR_INVALID_ARRAY;
416 return nullptr;
Elliott Hughes436e3722012-02-17 20:01:47 -0800417 }
Ian Rogersc0542af2014-09-03 16:16:56 -0700418 *error = JDWP::ERR_NONE;
Elliott Hughes436e3722012-02-17 20:01:47 -0800419 return o->AsArray();
420}
421
Ian Rogersc0542af2014-09-03 16:16:56 -0700422static mirror::Class* DecodeClass(JDWP::RefTypeId id, JDWP::JdwpError* error)
Ian Rogersb726dcb2012-09-05 08:57:23 -0700423 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Sebastien Hertz6995c602014-09-09 12:10:13 +0200424 mirror::Object* o = Dbg::GetObjectRegistry()->Get<mirror::Object*>(id, error);
Ian Rogersc0542af2014-09-03 16:16:56 -0700425 if (o == nullptr) {
426 *error = JDWP::ERR_INVALID_OBJECT;
427 return nullptr;
Elliott Hughes436e3722012-02-17 20:01:47 -0800428 }
429 if (!o->IsClass()) {
Ian Rogersc0542af2014-09-03 16:16:56 -0700430 *error = JDWP::ERR_INVALID_CLASS;
431 return nullptr;
Elliott Hughes436e3722012-02-17 20:01:47 -0800432 }
Ian Rogersc0542af2014-09-03 16:16:56 -0700433 *error = JDWP::ERR_NONE;
Elliott Hughes436e3722012-02-17 20:01:47 -0800434 return o->AsClass();
435}
436
Ian Rogersc0542af2014-09-03 16:16:56 -0700437static Thread* DecodeThread(ScopedObjectAccessUnchecked& soa, JDWP::ObjectId thread_id,
438 JDWP::JdwpError* error)
jeffhaoa77f0f62012-12-05 17:19:31 -0800439 EXCLUSIVE_LOCKS_REQUIRED(Locks::thread_list_lock_)
Ian Rogersb726dcb2012-09-05 08:57:23 -0700440 LOCKS_EXCLUDED(Locks::thread_suspend_count_lock_)
441 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Sebastien Hertz6995c602014-09-09 12:10:13 +0200442 mirror::Object* thread_peer = Dbg::GetObjectRegistry()->Get<mirror::Object*>(thread_id, error);
Ian Rogersc0542af2014-09-03 16:16:56 -0700443 if (thread_peer == nullptr) {
Elliott Hughes221229c2013-01-08 18:17:50 -0800444 // This isn't even an object.
Ian Rogersc0542af2014-09-03 16:16:56 -0700445 *error = JDWP::ERR_INVALID_OBJECT;
446 return nullptr;
Elliott Hughes436e3722012-02-17 20:01:47 -0800447 }
Elliott Hughes221229c2013-01-08 18:17:50 -0800448
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800449 mirror::Class* java_lang_Thread = soa.Decode<mirror::Class*>(WellKnownClasses::java_lang_Thread);
Elliott Hughes221229c2013-01-08 18:17:50 -0800450 if (!java_lang_Thread->IsAssignableFrom(thread_peer->GetClass())) {
451 // This isn't a thread.
Ian Rogersc0542af2014-09-03 16:16:56 -0700452 *error = JDWP::ERR_INVALID_THREAD;
453 return nullptr;
Elliott Hughes221229c2013-01-08 18:17:50 -0800454 }
455
Ian Rogersc0542af2014-09-03 16:16:56 -0700456 Thread* thread = Thread::FromManagedThread(soa, thread_peer);
457 // If thread is null then this a java.lang.Thread without a Thread*. Must be a un-started or a
458 // zombie.
459 *error = (thread == nullptr) ? JDWP::ERR_THREAD_NOT_ALIVE : JDWP::ERR_NONE;
460 return thread;
Elliott Hughes436e3722012-02-17 20:01:47 -0800461}
462
Elliott Hughes24437992011-11-30 14:49:33 -0800463static JDWP::JdwpTag BasicTagFromDescriptor(const char* descriptor) {
464 // JDWP deliberately uses the descriptor characters' ASCII values for its enum.
465 // Note that by "basic" we mean that we don't get more specific than JT_OBJECT.
466 return static_cast<JDWP::JdwpTag>(descriptor[0]);
467}
468
Ian Rogers1ff3c982014-08-12 02:30:58 -0700469static JDWP::JdwpTag BasicTagFromClass(mirror::Class* klass)
470 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
471 std::string temp;
472 const char* descriptor = klass->GetDescriptor(&temp);
473 return BasicTagFromDescriptor(descriptor);
474}
475
Ian Rogers98379392014-02-24 16:53:16 -0800476static JDWP::JdwpTag TagFromClass(const ScopedObjectAccessUnchecked& soa, mirror::Class* c)
Ian Rogersb726dcb2012-09-05 08:57:23 -0700477 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Ian Rogersc0542af2014-09-03 16:16:56 -0700478 CHECK(c != nullptr);
Elliott Hughes24437992011-11-30 14:49:33 -0800479 if (c->IsArrayClass()) {
480 return JDWP::JT_ARRAY;
481 }
Elliott Hughes24437992011-11-30 14:49:33 -0800482 if (c->IsStringClass()) {
483 return JDWP::JT_STRING;
Elliott Hughes24437992011-11-30 14:49:33 -0800484 }
Ian Rogers98379392014-02-24 16:53:16 -0800485 if (c->IsClassClass()) {
486 return JDWP::JT_CLASS_OBJECT;
487 }
488 {
489 mirror::Class* thread_class = soa.Decode<mirror::Class*>(WellKnownClasses::java_lang_Thread);
490 if (thread_class->IsAssignableFrom(c)) {
491 return JDWP::JT_THREAD;
492 }
493 }
494 {
495 mirror::Class* thread_group_class =
496 soa.Decode<mirror::Class*>(WellKnownClasses::java_lang_ThreadGroup);
497 if (thread_group_class->IsAssignableFrom(c)) {
498 return JDWP::JT_THREAD_GROUP;
499 }
500 }
501 {
502 mirror::Class* class_loader_class =
503 soa.Decode<mirror::Class*>(WellKnownClasses::java_lang_ClassLoader);
504 if (class_loader_class->IsAssignableFrom(c)) {
505 return JDWP::JT_CLASS_LOADER;
506 }
507 }
508 return JDWP::JT_OBJECT;
Elliott Hughes24437992011-11-30 14:49:33 -0800509}
510
511/*
512 * Objects declared to hold Object might actually hold a more specific
513 * type. The debugger may take a special interest in these (e.g. it
514 * wants to display the contents of Strings), so we want to return an
515 * appropriate tag.
516 *
517 * Null objects are tagged JT_OBJECT.
518 */
Sebastien Hertz6995c602014-09-09 12:10:13 +0200519JDWP::JdwpTag Dbg::TagFromObject(const ScopedObjectAccessUnchecked& soa, mirror::Object* o) {
Ian Rogersc0542af2014-09-03 16:16:56 -0700520 return (o == nullptr) ? JDWP::JT_OBJECT : TagFromClass(soa, o->GetClass());
Elliott Hughes24437992011-11-30 14:49:33 -0800521}
522
523static bool IsPrimitiveTag(JDWP::JdwpTag tag) {
524 switch (tag) {
525 case JDWP::JT_BOOLEAN:
526 case JDWP::JT_BYTE:
527 case JDWP::JT_CHAR:
528 case JDWP::JT_FLOAT:
529 case JDWP::JT_DOUBLE:
530 case JDWP::JT_INT:
531 case JDWP::JT_LONG:
532 case JDWP::JT_SHORT:
533 case JDWP::JT_VOID:
534 return true;
535 default:
536 return false;
537 }
538}
539
Sebastien Hertzb3b173b2015-02-06 09:16:32 +0100540void Dbg::StartJdwp() {
Elliott Hughesc0f09332012-03-26 13:27:06 -0700541 if (!gJdwpAllowed || !IsJdwpConfigured()) {
Elliott Hughes376a7a02011-10-24 18:35:55 -0700542 // No JDWP for you!
543 return;
544 }
545
Ian Rogers719d1a32014-03-06 12:13:39 -0800546 CHECK(gRegistry == nullptr);
Elliott Hughes475fc232011-10-25 15:00:35 -0700547 gRegistry = new ObjectRegistry;
548
Elliott Hughesd1cc8362011-10-24 16:58:50 -0700549 // Init JDWP if the debugger is enabled. This may connect out to a
550 // debugger, passively listen for a debugger, or block waiting for a
551 // debugger.
Sebastien Hertzb3b173b2015-02-06 09:16:32 +0100552 gJdwpState = JDWP::JdwpState::Create(&gJdwpOptions);
Ian Rogersc0542af2014-09-03 16:16:56 -0700553 if (gJdwpState == nullptr) {
Elliott Hughesf8a2df72011-12-01 12:19:54 -0800554 // We probably failed because some other process has the port already, which means that
555 // if we don't abort the user is likely to think they're talking to us when they're actually
556 // talking to that other process.
Elliott Hughes3d30d9b2011-12-07 17:35:48 -0800557 LOG(FATAL) << "Debugger thread failed to initialize";
Elliott Hughesd1cc8362011-10-24 16:58:50 -0700558 }
559
560 // If a debugger has already attached, send the "welcome" message.
561 // This may cause us to suspend all threads.
Elliott Hughes376a7a02011-10-24 18:35:55 -0700562 if (gJdwpState->IsActive()) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700563 ScopedObjectAccess soa(Thread::Current());
Sebastien Hertz7d955652014-10-22 10:57:10 +0200564 gJdwpState->PostVMStart();
Elliott Hughesd1cc8362011-10-24 16:58:50 -0700565 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700566}
567
Elliott Hughesd1cc8362011-10-24 16:58:50 -0700568void Dbg::StopJdwp() {
Sebastien Hertzc6345ef2014-08-18 19:26:39 +0200569 // Post VM_DEATH event before the JDWP connection is closed (either by the JDWP thread or the
570 // destruction of gJdwpState).
571 if (gJdwpState != nullptr && gJdwpState->IsActive()) {
572 gJdwpState->PostVMDeath();
573 }
Sebastien Hertz0376e6b2014-02-06 18:12:59 +0100574 // Prevent the JDWP thread from processing JDWP incoming packets after we close the connection.
575 Disposed();
Elliott Hughes376a7a02011-10-24 18:35:55 -0700576 delete gJdwpState;
Ian Rogers719d1a32014-03-06 12:13:39 -0800577 gJdwpState = nullptr;
Elliott Hughes475fc232011-10-25 15:00:35 -0700578 delete gRegistry;
Ian Rogers719d1a32014-03-06 12:13:39 -0800579 gRegistry = nullptr;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700580}
581
Elliott Hughes767a1472011-10-26 18:49:02 -0700582void Dbg::GcDidFinish() {
583 if (gDdmHpifWhen != HPIF_WHEN_NEVER) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700584 ScopedObjectAccess soa(Thread::Current());
Brian Carlstrom4d466a82014-05-08 19:05:29 -0700585 VLOG(jdwp) << "Sending heap info to DDM";
Elliott Hughes7162ad92011-10-27 14:08:42 -0700586 DdmSendHeapInfo(gDdmHpifWhen);
Elliott Hughes767a1472011-10-26 18:49:02 -0700587 }
588 if (gDdmHpsgWhen != HPSG_WHEN_NEVER) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700589 ScopedObjectAccess soa(Thread::Current());
Brian Carlstrom4d466a82014-05-08 19:05:29 -0700590 VLOG(jdwp) << "Dumping heap to DDM";
Elliott Hughes6a5bd492011-10-28 14:33:57 -0700591 DdmSendHeapSegments(false);
Elliott Hughes767a1472011-10-26 18:49:02 -0700592 }
593 if (gDdmNhsgWhen != HPSG_WHEN_NEVER) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700594 ScopedObjectAccess soa(Thread::Current());
Brian Carlstrom4d466a82014-05-08 19:05:29 -0700595 VLOG(jdwp) << "Dumping native heap to DDM";
Elliott Hughes6a5bd492011-10-28 14:33:57 -0700596 DdmSendHeapSegments(true);
Elliott Hughes767a1472011-10-26 18:49:02 -0700597 }
598}
599
Elliott Hughes4ffd3132011-10-24 12:06:42 -0700600void Dbg::SetJdwpAllowed(bool allowed) {
601 gJdwpAllowed = allowed;
602}
603
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700604DebugInvokeReq* Dbg::GetInvokeReq() {
Elliott Hughes475fc232011-10-25 15:00:35 -0700605 return Thread::Current()->GetInvokeReq();
606}
607
608Thread* Dbg::GetDebugThread() {
Ian Rogersc0542af2014-09-03 16:16:56 -0700609 return (gJdwpState != nullptr) ? gJdwpState->GetDebugThread() : nullptr;
Elliott Hughes475fc232011-10-25 15:00:35 -0700610}
611
612void Dbg::ClearWaitForEventThread() {
Sebastien Hertz2bf93f42015-01-09 18:44:05 +0100613 gJdwpState->ReleaseJdwpTokenForEvent();
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700614}
615
616void Dbg::Connected() {
Elliott Hughes3bb81562011-10-21 18:52:59 -0700617 CHECK(!gDebuggerConnected);
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -0800618 VLOG(jdwp) << "JDWP has attached";
Elliott Hughes3bb81562011-10-21 18:52:59 -0700619 gDebuggerConnected = true;
Elliott Hughes86964332012-02-15 19:37:42 -0800620 gDisposed = false;
621}
622
623void Dbg::Disposed() {
624 gDisposed = true;
625}
626
627bool Dbg::IsDisposed() {
628 return gDisposed;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700629}
630
Sebastien Hertzf3928792014-11-17 19:00:37 +0100631bool Dbg::RequiresDeoptimization() {
632 // We don't need deoptimization if everything runs with interpreter after
633 // enabling -Xint mode.
634 return !Runtime::Current()->GetInstrumentation()->IsForcedInterpretOnly();
635}
636
Elliott Hughesa2155262011-11-16 16:26:58 -0800637void Dbg::GoActive() {
638 // Enable all debugging features, including scans for breakpoints.
639 // This is a no-op if we're already active.
640 // Only called from the JDWP handler thread.
641 if (gDebuggerActive) {
642 return;
643 }
644
Elliott Hughesc0f09332012-03-26 13:27:06 -0700645 {
646 // TODO: dalvik only warned if there were breakpoints left over. clear in Dbg::Disconnected?
Sebastien Hertzed2be172014-08-19 15:33:43 +0200647 ReaderMutexLock mu(Thread::Current(), *Locks::breakpoint_lock_);
Elliott Hughesc0f09332012-03-26 13:27:06 -0700648 CHECK_EQ(gBreakpoints.size(), 0U);
649 }
Elliott Hughesa2155262011-11-16 16:26:58 -0800650
Sebastien Hertz138dbfc2013-12-04 18:15:25 +0100651 {
Brian Carlstrom306db812014-09-05 13:01:41 -0700652 MutexLock mu(Thread::Current(), *Locks::deoptimization_lock_);
Sebastien Hertz4d25df32014-03-21 17:44:46 +0100653 CHECK_EQ(deoptimization_requests_.size(), 0U);
654 CHECK_EQ(full_deoptimization_event_count_, 0U);
Sebastien Hertz7ec2f1c2014-03-27 20:06:47 +0100655 CHECK_EQ(delayed_full_undeoptimization_count_, 0U);
Sebastien Hertz42cd43f2014-05-13 14:15:41 +0200656 CHECK_EQ(dex_pc_change_event_ref_count_, 0U);
657 CHECK_EQ(method_enter_event_ref_count_, 0U);
658 CHECK_EQ(method_exit_event_ref_count_, 0U);
659 CHECK_EQ(field_read_event_ref_count_, 0U);
660 CHECK_EQ(field_write_event_ref_count_, 0U);
661 CHECK_EQ(exception_catch_event_ref_count_, 0U);
Sebastien Hertz138dbfc2013-12-04 18:15:25 +0100662 }
663
Ian Rogers62d6c772013-02-27 08:32:07 -0800664 Runtime* runtime = Runtime::Current();
665 runtime->GetThreadList()->SuspendAll();
666 Thread* self = Thread::Current();
667 ThreadState old_state = self->SetStateUnsafe(kRunnable);
668 CHECK_NE(old_state, kRunnable);
Sebastien Hertzf3928792014-11-17 19:00:37 +0100669 if (RequiresDeoptimization()) {
670 runtime->GetInstrumentation()->EnableDeoptimization();
671 }
Sebastien Hertz42cd43f2014-05-13 14:15:41 +0200672 instrumentation_events_ = 0;
Elliott Hughesa2155262011-11-16 16:26:58 -0800673 gDebuggerActive = true;
Ian Rogers62d6c772013-02-27 08:32:07 -0800674 CHECK_EQ(self->SetStateUnsafe(old_state), kRunnable);
675 runtime->GetThreadList()->ResumeAll();
676
677 LOG(INFO) << "Debugger is active";
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700678}
679
680void Dbg::Disconnected() {
Elliott Hughes234ab152011-10-26 14:02:26 -0700681 CHECK(gDebuggerConnected);
682
Elliott Hughesc0f09332012-03-26 13:27:06 -0700683 LOG(INFO) << "Debugger is no longer active";
Elliott Hughes234ab152011-10-26 14:02:26 -0700684
Ian Rogers62d6c772013-02-27 08:32:07 -0800685 // Suspend all threads and exclusively acquire the mutator lock. Set the state of the thread
686 // to kRunnable to avoid scoped object access transitions. Remove the debugger as a listener
687 // and clear the object registry.
688 Runtime* runtime = Runtime::Current();
689 runtime->GetThreadList()->SuspendAll();
690 Thread* self = Thread::Current();
691 ThreadState old_state = self->SetStateUnsafe(kRunnable);
Sebastien Hertzaaea7342014-02-25 15:10:04 +0100692
693 // Debugger may not be active at this point.
694 if (gDebuggerActive) {
695 {
696 // Since we're going to disable deoptimization, we clear the deoptimization requests queue.
697 // This prevents us from having any pending deoptimization request when the debugger attaches
698 // to us again while no event has been requested yet.
Brian Carlstrom306db812014-09-05 13:01:41 -0700699 MutexLock mu(Thread::Current(), *Locks::deoptimization_lock_);
Sebastien Hertz4d25df32014-03-21 17:44:46 +0100700 deoptimization_requests_.clear();
701 full_deoptimization_event_count_ = 0U;
Sebastien Hertz7ec2f1c2014-03-27 20:06:47 +0100702 delayed_full_undeoptimization_count_ = 0U;
Sebastien Hertzaaea7342014-02-25 15:10:04 +0100703 }
Sebastien Hertz42cd43f2014-05-13 14:15:41 +0200704 if (instrumentation_events_ != 0) {
705 runtime->GetInstrumentation()->RemoveListener(&gDebugInstrumentationListener,
706 instrumentation_events_);
707 instrumentation_events_ = 0;
708 }
Sebastien Hertzf3928792014-11-17 19:00:37 +0100709 if (RequiresDeoptimization()) {
710 runtime->GetInstrumentation()->DisableDeoptimization();
711 }
Sebastien Hertzaaea7342014-02-25 15:10:04 +0100712 gDebuggerActive = false;
Sebastien Hertz138dbfc2013-12-04 18:15:25 +0100713 }
Ian Rogers62d6c772013-02-27 08:32:07 -0800714 CHECK_EQ(self->SetStateUnsafe(old_state), kRunnable);
715 runtime->GetThreadList()->ResumeAll();
Sebastien Hertz55f65342015-01-13 22:48:34 +0100716
717 {
718 ScopedObjectAccess soa(self);
719 gRegistry->Clear();
720 }
721
722 gDebuggerConnected = false;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700723}
724
Elliott Hughesc0f09332012-03-26 13:27:06 -0700725bool Dbg::IsDebuggerActive() {
Elliott Hughes3bb81562011-10-21 18:52:59 -0700726 return gDebuggerActive;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700727}
728
Sebastien Hertzb3b173b2015-02-06 09:16:32 +0100729void Dbg::ConfigureJdwp(const JDWP::JdwpOptions& jdwp_options) {
730 CHECK_NE(jdwp_options.transport, JDWP::kJdwpTransportUnknown);
731 gJdwpOptions = jdwp_options;
732 gJdwpConfigured = true;
733}
734
Elliott Hughesc0f09332012-03-26 13:27:06 -0700735bool Dbg::IsJdwpConfigured() {
Elliott Hughes3bb81562011-10-21 18:52:59 -0700736 return gJdwpConfigured;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700737}
738
739int64_t Dbg::LastDebuggerActivity() {
Elliott Hughesca951522011-12-05 12:01:32 -0800740 return gJdwpState->LastDebuggerActivity();
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700741}
742
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700743void Dbg::UndoDebuggerSuspensions() {
Elliott Hughes234ab152011-10-26 14:02:26 -0700744 Runtime::Current()->GetThreadList()->UndoDebuggerSuspensions();
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700745}
746
Elliott Hughes88d63092013-01-09 09:55:54 -0800747std::string Dbg::GetClassName(JDWP::RefTypeId class_id) {
Ian Rogersc0542af2014-09-03 16:16:56 -0700748 JDWP::JdwpError error;
749 mirror::Object* o = gRegistry->Get<mirror::Object*>(class_id, &error);
750 if (o == nullptr) {
751 if (error == JDWP::ERR_NONE) {
752 return "NULL";
753 } else {
754 return StringPrintf("invalid object %p", reinterpret_cast<void*>(class_id));
755 }
Elliott Hughes436e3722012-02-17 20:01:47 -0800756 }
757 if (!o->IsClass()) {
Brian Carlstrom7934ac22013-07-26 10:54:15 -0700758 return StringPrintf("non-class %p", o); // This is only used for debugging output anyway.
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -0800759 }
Sebastien Hertz6995c602014-09-09 12:10:13 +0200760 return GetClassName(o->AsClass());
761}
762
763std::string Dbg::GetClassName(mirror::Class* klass) {
Sebastien Hertza9aa0ff2014-09-19 12:07:51 +0200764 if (klass == nullptr) {
765 return "NULL";
766 }
Ian Rogers1ff3c982014-08-12 02:30:58 -0700767 std::string temp;
Sebastien Hertz6995c602014-09-09 12:10:13 +0200768 return DescriptorToName(klass->GetDescriptor(&temp));
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700769}
770
Ian Rogersc0542af2014-09-03 16:16:56 -0700771JDWP::JdwpError Dbg::GetClassObject(JDWP::RefTypeId id, JDWP::ObjectId* class_object_id) {
Elliott Hughes436e3722012-02-17 20:01:47 -0800772 JDWP::JdwpError status;
Ian Rogersc0542af2014-09-03 16:16:56 -0700773 mirror::Class* c = DecodeClass(id, &status);
774 if (c == nullptr) {
775 *class_object_id = 0;
Elliott Hughes436e3722012-02-17 20:01:47 -0800776 return status;
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -0800777 }
Ian Rogersc0542af2014-09-03 16:16:56 -0700778 *class_object_id = gRegistry->Add(c);
Elliott Hughes436e3722012-02-17 20:01:47 -0800779 return JDWP::ERR_NONE;
Elliott Hughes86964332012-02-15 19:37:42 -0800780}
781
Ian Rogersc0542af2014-09-03 16:16:56 -0700782JDWP::JdwpError Dbg::GetSuperclass(JDWP::RefTypeId id, JDWP::RefTypeId* superclass_id) {
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -0800783 JDWP::JdwpError status;
Ian Rogersc0542af2014-09-03 16:16:56 -0700784 mirror::Class* c = DecodeClass(id, &status);
785 if (c == nullptr) {
786 *superclass_id = 0;
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -0800787 return status;
788 }
789 if (c->IsInterface()) {
790 // http://code.google.com/p/android/issues/detail?id=20856
Ian Rogersc0542af2014-09-03 16:16:56 -0700791 *superclass_id = 0;
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -0800792 } else {
Ian Rogersc0542af2014-09-03 16:16:56 -0700793 *superclass_id = gRegistry->Add(c->GetSuperClass());
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -0800794 }
795 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700796}
797
Elliott Hughes436e3722012-02-17 20:01:47 -0800798JDWP::JdwpError Dbg::GetClassLoader(JDWP::RefTypeId id, JDWP::ExpandBuf* pReply) {
Ian Rogersc0542af2014-09-03 16:16:56 -0700799 JDWP::JdwpError error;
800 mirror::Object* o = gRegistry->Get<mirror::Object*>(id, &error);
801 if (o == nullptr) {
Elliott Hughes436e3722012-02-17 20:01:47 -0800802 return JDWP::ERR_INVALID_OBJECT;
803 }
804 expandBufAddObjectId(pReply, gRegistry->Add(o->GetClass()->GetClassLoader()));
805 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700806}
807
Elliott Hughes436e3722012-02-17 20:01:47 -0800808JDWP::JdwpError Dbg::GetModifiers(JDWP::RefTypeId id, JDWP::ExpandBuf* pReply) {
Ian Rogersc0542af2014-09-03 16:16:56 -0700809 JDWP::JdwpError error;
810 mirror::Class* c = DecodeClass(id, &error);
811 if (c == nullptr) {
812 return error;
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -0800813 }
Elliott Hughes436e3722012-02-17 20:01:47 -0800814
815 uint32_t access_flags = c->GetAccessFlags() & kAccJavaFlagsMask;
816
Yevgeny Roubande34eea2014-02-15 01:06:03 +0700817 // Set ACC_SUPER. Dex files don't contain this flag but only classes are supposed to have it set,
818 // not interfaces.
Elliott Hughes436e3722012-02-17 20:01:47 -0800819 // Class.getModifiers doesn't return it, but JDWP does, so we set it here.
Yevgeny Roubande34eea2014-02-15 01:06:03 +0700820 if ((access_flags & kAccInterface) == 0) {
821 access_flags |= kAccSuper;
822 }
Elliott Hughes436e3722012-02-17 20:01:47 -0800823
824 expandBufAdd4BE(pReply, access_flags);
825
826 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700827}
828
Ian Rogersc0542af2014-09-03 16:16:56 -0700829JDWP::JdwpError Dbg::GetMonitorInfo(JDWP::ObjectId object_id, JDWP::ExpandBuf* reply) {
830 JDWP::JdwpError error;
831 mirror::Object* o = gRegistry->Get<mirror::Object*>(object_id, &error);
832 if (o == nullptr) {
Elliott Hughesf327e072013-01-09 16:01:26 -0800833 return JDWP::ERR_INVALID_OBJECT;
834 }
835
836 // Ensure all threads are suspended while we read objects' lock words.
837 Thread* self = Thread::Current();
Sebastien Hertz54263242014-03-19 18:16:50 +0100838 CHECK_EQ(self->GetState(), kRunnable);
839 self->TransitionFromRunnableToSuspended(kSuspended);
840 Runtime::Current()->GetThreadList()->SuspendAll();
Elliott Hughesf327e072013-01-09 16:01:26 -0800841
842 MonitorInfo monitor_info(o);
843
Sebastien Hertz54263242014-03-19 18:16:50 +0100844 Runtime::Current()->GetThreadList()->ResumeAll();
845 self->TransitionFromSuspendedToRunnable();
Elliott Hughesf327e072013-01-09 16:01:26 -0800846
Ian Rogersc0542af2014-09-03 16:16:56 -0700847 if (monitor_info.owner_ != nullptr) {
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700848 expandBufAddObjectId(reply, gRegistry->Add(monitor_info.owner_->GetPeer()));
Elliott Hughesf327e072013-01-09 16:01:26 -0800849 } else {
Ian Rogersc0542af2014-09-03 16:16:56 -0700850 expandBufAddObjectId(reply, gRegistry->Add(nullptr));
Elliott Hughesf327e072013-01-09 16:01:26 -0800851 }
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700852 expandBufAdd4BE(reply, monitor_info.entry_count_);
853 expandBufAdd4BE(reply, monitor_info.waiters_.size());
854 for (size_t i = 0; i < monitor_info.waiters_.size(); ++i) {
855 expandBufAddObjectId(reply, gRegistry->Add(monitor_info.waiters_[i]->GetPeer()));
Elliott Hughesf327e072013-01-09 16:01:26 -0800856 }
857 return JDWP::ERR_NONE;
858}
859
Elliott Hughes734b8c62013-01-11 15:32:45 -0800860JDWP::JdwpError Dbg::GetOwnedMonitors(JDWP::ObjectId thread_id,
Ian Rogersc0542af2014-09-03 16:16:56 -0700861 std::vector<JDWP::ObjectId>* monitors,
862 std::vector<uint32_t>* stack_depths) {
Elliott Hughes4993bbc2013-01-10 15:41:25 -0800863 struct OwnedMonitorVisitor : public StackVisitor {
Hiroshi Yamauchib5a9e3d2014-06-09 12:11:20 -0700864 OwnedMonitorVisitor(Thread* thread, Context* context,
Hiroshi Yamauchicc8c5c52014-06-13 15:08:05 -0700865 std::vector<JDWP::ObjectId>* monitor_vector,
Hiroshi Yamauchib5a9e3d2014-06-09 12:11:20 -0700866 std::vector<uint32_t>* stack_depth_vector)
Elliott Hughes4993bbc2013-01-10 15:41:25 -0800867 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_)
Hiroshi Yamauchib5a9e3d2014-06-09 12:11:20 -0700868 : StackVisitor(thread, context), current_stack_depth(0),
869 monitors(monitor_vector), stack_depths(stack_depth_vector) {}
Elliott Hughes4993bbc2013-01-10 15:41:25 -0800870
871 // TODO: Enable annotalysis. We know lock is held in constructor, but abstraction confuses
872 // annotalysis.
873 bool VisitFrame() NO_THREAD_SAFETY_ANALYSIS {
874 if (!GetMethod()->IsRuntimeMethod()) {
875 Monitor::VisitLocks(this, AppendOwnedMonitors, this);
Elliott Hughes734b8c62013-01-11 15:32:45 -0800876 ++current_stack_depth;
Elliott Hughes4993bbc2013-01-10 15:41:25 -0800877 }
878 return true;
879 }
880
Hiroshi Yamauchicc8c5c52014-06-13 15:08:05 -0700881 static void AppendOwnedMonitors(mirror::Object* owned_monitor, void* arg)
882 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Ian Rogers7a22fa62013-01-23 12:16:16 -0800883 OwnedMonitorVisitor* visitor = reinterpret_cast<OwnedMonitorVisitor*>(arg);
Hiroshi Yamauchicc8c5c52014-06-13 15:08:05 -0700884 visitor->monitors->push_back(gRegistry->Add(owned_monitor));
Hiroshi Yamauchib5a9e3d2014-06-09 12:11:20 -0700885 visitor->stack_depths->push_back(visitor->current_stack_depth);
Elliott Hughes4993bbc2013-01-10 15:41:25 -0800886 }
887
Elliott Hughes734b8c62013-01-11 15:32:45 -0800888 size_t current_stack_depth;
Ian Rogersc0542af2014-09-03 16:16:56 -0700889 std::vector<JDWP::ObjectId>* const monitors;
890 std::vector<uint32_t>* const stack_depths;
Elliott Hughes4993bbc2013-01-10 15:41:25 -0800891 };
Elliott Hughes4993bbc2013-01-10 15:41:25 -0800892
Hiroshi Yamauchib5a9e3d2014-06-09 12:11:20 -0700893 ScopedObjectAccessUnchecked soa(Thread::Current());
Hiroshi Yamauchicc8c5c52014-06-13 15:08:05 -0700894 Thread* thread;
Hiroshi Yamauchib5a9e3d2014-06-09 12:11:20 -0700895 {
896 MutexLock mu(soa.Self(), *Locks::thread_list_lock_);
Ian Rogersc0542af2014-09-03 16:16:56 -0700897 JDWP::JdwpError error;
898 thread = DecodeThread(soa, thread_id, &error);
899 if (thread == nullptr) {
Hiroshi Yamauchib5a9e3d2014-06-09 12:11:20 -0700900 return error;
901 }
902 if (!IsSuspendedForDebugger(soa, thread)) {
903 return JDWP::ERR_THREAD_NOT_SUSPENDED;
904 }
Hiroshi Yamauchib5a9e3d2014-06-09 12:11:20 -0700905 }
Hiroshi Yamauchicc8c5c52014-06-13 15:08:05 -0700906 std::unique_ptr<Context> context(Context::Create());
Ian Rogersc0542af2014-09-03 16:16:56 -0700907 OwnedMonitorVisitor visitor(thread, context.get(), monitors, stack_depths);
Hiroshi Yamauchicc8c5c52014-06-13 15:08:05 -0700908 visitor.WalkStack();
Elliott Hughes4993bbc2013-01-10 15:41:25 -0800909 return JDWP::ERR_NONE;
910}
911
Sebastien Hertz52d131d2014-03-13 16:17:40 +0100912JDWP::JdwpError Dbg::GetContendedMonitor(JDWP::ObjectId thread_id,
Ian Rogersc0542af2014-09-03 16:16:56 -0700913 JDWP::ObjectId* contended_monitor) {
Hiroshi Yamauchib5a9e3d2014-06-09 12:11:20 -0700914 mirror::Object* contended_monitor_obj;
Elliott Hughesf9501702013-01-11 11:22:27 -0800915 ScopedObjectAccessUnchecked soa(Thread::Current());
Ian Rogersc0542af2014-09-03 16:16:56 -0700916 *contended_monitor = 0;
Hiroshi Yamauchib5a9e3d2014-06-09 12:11:20 -0700917 {
918 MutexLock mu(soa.Self(), *Locks::thread_list_lock_);
Ian Rogersc0542af2014-09-03 16:16:56 -0700919 JDWP::JdwpError error;
920 Thread* thread = DecodeThread(soa, thread_id, &error);
921 if (thread == nullptr) {
Hiroshi Yamauchib5a9e3d2014-06-09 12:11:20 -0700922 return error;
923 }
924 if (!IsSuspendedForDebugger(soa, thread)) {
925 return JDWP::ERR_THREAD_NOT_SUSPENDED;
926 }
927 contended_monitor_obj = Monitor::GetContendedMonitor(thread);
Elliott Hughesf9501702013-01-11 11:22:27 -0800928 }
Hiroshi Yamauchib5a9e3d2014-06-09 12:11:20 -0700929 // Add() requires the thread_list_lock_ not held to avoid the lock
930 // level violation.
Ian Rogersc0542af2014-09-03 16:16:56 -0700931 *contended_monitor = gRegistry->Add(contended_monitor_obj);
Elliott Hughesf9501702013-01-11 11:22:27 -0800932 return JDWP::ERR_NONE;
933}
934
Elliott Hughesec0f83d2013-01-15 16:54:08 -0800935JDWP::JdwpError Dbg::GetInstanceCounts(const std::vector<JDWP::RefTypeId>& class_ids,
Ian Rogersc0542af2014-09-03 16:16:56 -0700936 std::vector<uint64_t>* counts) {
Mathieu Chartier412c7fc2014-02-07 12:18:39 -0800937 gc::Heap* heap = Runtime::Current()->GetHeap();
938 heap->CollectGarbage(false);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800939 std::vector<mirror::Class*> classes;
Ian Rogersc0542af2014-09-03 16:16:56 -0700940 counts->clear();
Elliott Hughesec0f83d2013-01-15 16:54:08 -0800941 for (size_t i = 0; i < class_ids.size(); ++i) {
Ian Rogersc0542af2014-09-03 16:16:56 -0700942 JDWP::JdwpError error;
943 mirror::Class* c = DecodeClass(class_ids[i], &error);
944 if (c == nullptr) {
945 return error;
Elliott Hughesec0f83d2013-01-15 16:54:08 -0800946 }
947 classes.push_back(c);
Ian Rogersc0542af2014-09-03 16:16:56 -0700948 counts->push_back(0);
Elliott Hughesec0f83d2013-01-15 16:54:08 -0800949 }
Ian Rogersc0542af2014-09-03 16:16:56 -0700950 heap->CountInstances(classes, false, &(*counts)[0]);
Elliott Hughesec0f83d2013-01-15 16:54:08 -0800951 return JDWP::ERR_NONE;
952}
953
Ian Rogersc0542af2014-09-03 16:16:56 -0700954JDWP::JdwpError Dbg::GetInstances(JDWP::RefTypeId class_id, int32_t max_count,
955 std::vector<JDWP::ObjectId>* instances) {
Mathieu Chartier412c7fc2014-02-07 12:18:39 -0800956 gc::Heap* heap = Runtime::Current()->GetHeap();
957 // We only want reachable instances, so do a GC.
958 heap->CollectGarbage(false);
Ian Rogersc0542af2014-09-03 16:16:56 -0700959 JDWP::JdwpError error;
960 mirror::Class* c = DecodeClass(class_id, &error);
Mathieu Chartier412c7fc2014-02-07 12:18:39 -0800961 if (c == nullptr) {
Ian Rogersc0542af2014-09-03 16:16:56 -0700962 return error;
Elliott Hughes3b78c942013-01-15 17:35:41 -0800963 }
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800964 std::vector<mirror::Object*> raw_instances;
Elliott Hughes3b78c942013-01-15 17:35:41 -0800965 Runtime::Current()->GetHeap()->GetInstances(c, max_count, raw_instances);
966 for (size_t i = 0; i < raw_instances.size(); ++i) {
Ian Rogersc0542af2014-09-03 16:16:56 -0700967 instances->push_back(gRegistry->Add(raw_instances[i]));
Elliott Hughes3b78c942013-01-15 17:35:41 -0800968 }
969 return JDWP::ERR_NONE;
970}
971
Elliott Hughes0cbaff52013-01-16 15:28:01 -0800972JDWP::JdwpError Dbg::GetReferringObjects(JDWP::ObjectId object_id, int32_t max_count,
Ian Rogersc0542af2014-09-03 16:16:56 -0700973 std::vector<JDWP::ObjectId>* referring_objects) {
Mathieu Chartier412c7fc2014-02-07 12:18:39 -0800974 gc::Heap* heap = Runtime::Current()->GetHeap();
975 heap->CollectGarbage(false);
Ian Rogersc0542af2014-09-03 16:16:56 -0700976 JDWP::JdwpError error;
977 mirror::Object* o = gRegistry->Get<mirror::Object*>(object_id, &error);
978 if (o == nullptr) {
Elliott Hughes0cbaff52013-01-16 15:28:01 -0800979 return JDWP::ERR_INVALID_OBJECT;
980 }
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800981 std::vector<mirror::Object*> raw_instances;
Mathieu Chartier412c7fc2014-02-07 12:18:39 -0800982 heap->GetReferringObjects(o, max_count, raw_instances);
Elliott Hughes0cbaff52013-01-16 15:28:01 -0800983 for (size_t i = 0; i < raw_instances.size(); ++i) {
Ian Rogersc0542af2014-09-03 16:16:56 -0700984 referring_objects->push_back(gRegistry->Add(raw_instances[i]));
Elliott Hughes0cbaff52013-01-16 15:28:01 -0800985 }
986 return JDWP::ERR_NONE;
987}
988
Ian Rogersc0542af2014-09-03 16:16:56 -0700989JDWP::JdwpError Dbg::DisableCollection(JDWP::ObjectId object_id) {
990 JDWP::JdwpError error;
991 mirror::Object* o = gRegistry->Get<mirror::Object*>(object_id, &error);
992 if (o == nullptr) {
Sebastien Hertze96060a2013-12-11 12:06:28 +0100993 return JDWP::ERR_INVALID_OBJECT;
994 }
Elliott Hughes64f574f2013-02-20 14:57:12 -0800995 gRegistry->DisableCollection(object_id);
996 return JDWP::ERR_NONE;
997}
998
Ian Rogersc0542af2014-09-03 16:16:56 -0700999JDWP::JdwpError Dbg::EnableCollection(JDWP::ObjectId object_id) {
1000 JDWP::JdwpError error;
1001 mirror::Object* o = gRegistry->Get<mirror::Object*>(object_id, &error);
Sebastien Hertze96060a2013-12-11 12:06:28 +01001002 // Unlike DisableCollection, JDWP specs do not state an invalid object causes an error. The RI
1003 // also ignores these cases and never return an error. However it's not obvious why this command
1004 // should behave differently from DisableCollection and IsCollected commands. So let's be more
1005 // strict and return an error if this happens.
Ian Rogersc0542af2014-09-03 16:16:56 -07001006 if (o == nullptr) {
Sebastien Hertze96060a2013-12-11 12:06:28 +01001007 return JDWP::ERR_INVALID_OBJECT;
1008 }
Elliott Hughes64f574f2013-02-20 14:57:12 -08001009 gRegistry->EnableCollection(object_id);
1010 return JDWP::ERR_NONE;
1011}
1012
Ian Rogersc0542af2014-09-03 16:16:56 -07001013JDWP::JdwpError Dbg::IsCollected(JDWP::ObjectId object_id, bool* is_collected) {
1014 *is_collected = true;
Sebastien Hertz65637eb2014-01-10 17:40:02 +01001015 if (object_id == 0) {
1016 // Null object id is invalid.
Sebastien Hertze96060a2013-12-11 12:06:28 +01001017 return JDWP::ERR_INVALID_OBJECT;
1018 }
Sebastien Hertz65637eb2014-01-10 17:40:02 +01001019 // JDWP specs state an INVALID_OBJECT error is returned if the object ID is not valid. However
1020 // the RI seems to ignore this and assume object has been collected.
Ian Rogersc0542af2014-09-03 16:16:56 -07001021 JDWP::JdwpError error;
1022 mirror::Object* o = gRegistry->Get<mirror::Object*>(object_id, &error);
1023 if (o != nullptr) {
1024 *is_collected = gRegistry->IsCollected(object_id);
Sebastien Hertz65637eb2014-01-10 17:40:02 +01001025 }
Elliott Hughes64f574f2013-02-20 14:57:12 -08001026 return JDWP::ERR_NONE;
1027}
1028
Ian Rogersc0542af2014-09-03 16:16:56 -07001029void Dbg::DisposeObject(JDWP::ObjectId object_id, uint32_t reference_count) {
Elliott Hughes64f574f2013-02-20 14:57:12 -08001030 gRegistry->DisposeObject(object_id, reference_count);
1031}
1032
Sebastien Hertz6995c602014-09-09 12:10:13 +02001033JDWP::JdwpTypeTag Dbg::GetTypeTag(mirror::Class* klass) {
Sebastien Hertz4d8fd492014-03-28 16:29:41 +01001034 DCHECK(klass != nullptr);
1035 if (klass->IsArrayClass()) {
1036 return JDWP::TT_ARRAY;
1037 } else if (klass->IsInterface()) {
1038 return JDWP::TT_INTERFACE;
1039 } else {
1040 return JDWP::TT_CLASS;
1041 }
1042}
1043
Elliott Hughes88d63092013-01-09 09:55:54 -08001044JDWP::JdwpError Dbg::GetReflectedType(JDWP::RefTypeId class_id, JDWP::ExpandBuf* pReply) {
Ian Rogersc0542af2014-09-03 16:16:56 -07001045 JDWP::JdwpError error;
1046 mirror::Class* c = DecodeClass(class_id, &error);
1047 if (c == nullptr) {
1048 return error;
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -08001049 }
Elliott Hughes436e3722012-02-17 20:01:47 -08001050
Sebastien Hertz4d8fd492014-03-28 16:29:41 +01001051 JDWP::JdwpTypeTag type_tag = GetTypeTag(c);
1052 expandBufAdd1(pReply, type_tag);
Elliott Hughes88d63092013-01-09 09:55:54 -08001053 expandBufAddRefTypeId(pReply, class_id);
Elliott Hughes436e3722012-02-17 20:01:47 -08001054 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001055}
1056
Ian Rogersc0542af2014-09-03 16:16:56 -07001057void Dbg::GetClassList(std::vector<JDWP::RefTypeId>* classes) {
Elliott Hughesa2155262011-11-16 16:26:58 -08001058 // Get the complete list of reference classes (i.e. all classes except
1059 // the primitive types).
1060 // Returns a newly-allocated buffer full of RefTypeId values.
1061 struct ClassListCreator {
Andreas Gampe277ccbd2014-11-03 21:36:10 -08001062 explicit ClassListCreator(std::vector<JDWP::RefTypeId>* classes_in) : classes(classes_in) {
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -08001063 }
1064
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001065 static bool Visit(mirror::Class* c, void* arg) {
Elliott Hughesa2155262011-11-16 16:26:58 -08001066 return reinterpret_cast<ClassListCreator*>(arg)->Visit(c);
1067 }
1068
Elliott Hughes64f574f2013-02-20 14:57:12 -08001069 // TODO: Enable annotalysis. We know lock is held in constructor, but abstraction confuses
1070 // annotalysis.
1071 bool Visit(mirror::Class* c) NO_THREAD_SAFETY_ANALYSIS {
Elliott Hughesa2155262011-11-16 16:26:58 -08001072 if (!c->IsPrimitive()) {
Ian Rogersc0542af2014-09-03 16:16:56 -07001073 classes->push_back(gRegistry->AddRefType(c));
Elliott Hughesa2155262011-11-16 16:26:58 -08001074 }
1075 return true;
1076 }
1077
Ian Rogersc0542af2014-09-03 16:16:56 -07001078 std::vector<JDWP::RefTypeId>* const classes;
Elliott Hughesa2155262011-11-16 16:26:58 -08001079 };
1080
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -08001081 ClassListCreator clc(classes);
Sebastien Hertz4537c412014-08-28 14:41:50 +02001082 Runtime::Current()->GetClassLinker()->VisitClassesWithoutClassesLock(ClassListCreator::Visit,
1083 &clc);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001084}
1085
Ian Rogers1ff3c982014-08-12 02:30:58 -07001086JDWP::JdwpError Dbg::GetClassInfo(JDWP::RefTypeId class_id, JDWP::JdwpTypeTag* pTypeTag,
1087 uint32_t* pStatus, std::string* pDescriptor) {
Ian Rogersc0542af2014-09-03 16:16:56 -07001088 JDWP::JdwpError error;
1089 mirror::Class* c = DecodeClass(class_id, &error);
1090 if (c == nullptr) {
1091 return error;
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -08001092 }
1093
Elliott Hughesa2155262011-11-16 16:26:58 -08001094 if (c->IsArrayClass()) {
1095 *pStatus = JDWP::CS_VERIFIED | JDWP::CS_PREPARED;
1096 *pTypeTag = JDWP::TT_ARRAY;
1097 } else {
1098 if (c->IsErroneous()) {
1099 *pStatus = JDWP::CS_ERROR;
1100 } else {
1101 *pStatus = JDWP::CS_VERIFIED | JDWP::CS_PREPARED | JDWP::CS_INITIALIZED;
1102 }
1103 *pTypeTag = c->IsInterface() ? JDWP::TT_INTERFACE : JDWP::TT_CLASS;
1104 }
1105
Ian Rogersc0542af2014-09-03 16:16:56 -07001106 if (pDescriptor != nullptr) {
Ian Rogers1ff3c982014-08-12 02:30:58 -07001107 std::string temp;
1108 *pDescriptor = c->GetDescriptor(&temp);
Elliott Hughesa2155262011-11-16 16:26:58 -08001109 }
Elliott Hughes436e3722012-02-17 20:01:47 -08001110 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001111}
1112
Ian Rogersc0542af2014-09-03 16:16:56 -07001113void Dbg::FindLoadedClassBySignature(const char* descriptor, std::vector<JDWP::RefTypeId>* ids) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001114 std::vector<mirror::Class*> classes;
Elliott Hughes6fa602d2011-12-02 17:54:25 -08001115 Runtime::Current()->GetClassLinker()->LookupClasses(descriptor, classes);
Ian Rogersc0542af2014-09-03 16:16:56 -07001116 ids->clear();
Elliott Hughes6fa602d2011-12-02 17:54:25 -08001117 for (size_t i = 0; i < classes.size(); ++i) {
Ian Rogersc0542af2014-09-03 16:16:56 -07001118 ids->push_back(gRegistry->Add(classes[i]));
Elliott Hughes6fa602d2011-12-02 17:54:25 -08001119 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001120}
1121
Ian Rogersc0542af2014-09-03 16:16:56 -07001122JDWP::JdwpError Dbg::GetReferenceType(JDWP::ObjectId object_id, JDWP::ExpandBuf* pReply) {
1123 JDWP::JdwpError error;
1124 mirror::Object* o = gRegistry->Get<mirror::Object*>(object_id, &error);
1125 if (o == nullptr) {
Elliott Hughes2435a572012-02-17 16:07:41 -08001126 return JDWP::ERR_INVALID_OBJECT;
Elliott Hughes499c5132011-11-17 14:55:11 -08001127 }
Elliott Hughes2435a572012-02-17 16:07:41 -08001128
Sebastien Hertz4d8fd492014-03-28 16:29:41 +01001129 JDWP::JdwpTypeTag type_tag = GetTypeTag(o->GetClass());
Elliott Hughes64f574f2013-02-20 14:57:12 -08001130 JDWP::RefTypeId type_id = gRegistry->AddRefType(o->GetClass());
Elliott Hughes2435a572012-02-17 16:07:41 -08001131
1132 expandBufAdd1(pReply, type_tag);
1133 expandBufAddRefTypeId(pReply, type_id);
1134
1135 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001136}
1137
Ian Rogersfc0e94b2013-09-23 23:51:32 -07001138JDWP::JdwpError Dbg::GetSignature(JDWP::RefTypeId class_id, std::string* signature) {
Ian Rogersc0542af2014-09-03 16:16:56 -07001139 JDWP::JdwpError error;
1140 mirror::Class* c = DecodeClass(class_id, &error);
1141 if (c == nullptr) {
1142 return error;
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -08001143 }
Ian Rogers1ff3c982014-08-12 02:30:58 -07001144 std::string temp;
1145 *signature = c->GetDescriptor(&temp);
Elliott Hughes1fe7afb2012-02-13 17:23:03 -08001146 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001147}
1148
Ian Rogersc0542af2014-09-03 16:16:56 -07001149JDWP::JdwpError Dbg::GetSourceFile(JDWP::RefTypeId class_id, std::string* result) {
1150 JDWP::JdwpError error;
1151 mirror::Class* c = DecodeClass(class_id, &error);
Sebastien Hertz4206eb52014-06-05 10:15:45 +02001152 if (c == nullptr) {
Ian Rogersc0542af2014-09-03 16:16:56 -07001153 return error;
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -08001154 }
Sebastien Hertz4206eb52014-06-05 10:15:45 +02001155 const char* source_file = c->GetSourceFile();
1156 if (source_file == nullptr) {
Sebastien Hertzb7054ba2014-03-13 11:52:31 +01001157 return JDWP::ERR_ABSENT_INFORMATION;
1158 }
Ian Rogersc0542af2014-09-03 16:16:56 -07001159 *result = source_file;
Elliott Hughes436e3722012-02-17 20:01:47 -08001160 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001161}
1162
Ian Rogersc0542af2014-09-03 16:16:56 -07001163JDWP::JdwpError Dbg::GetObjectTag(JDWP::ObjectId object_id, uint8_t* tag) {
Ian Rogers98379392014-02-24 16:53:16 -08001164 ScopedObjectAccessUnchecked soa(Thread::Current());
Ian Rogersc0542af2014-09-03 16:16:56 -07001165 JDWP::JdwpError error;
1166 mirror::Object* o = gRegistry->Get<mirror::Object*>(object_id, &error);
1167 if (error != JDWP::ERR_NONE) {
1168 *tag = JDWP::JT_VOID;
1169 return error;
Elliott Hughes546b9862012-06-20 16:06:13 -07001170 }
Ian Rogersc0542af2014-09-03 16:16:56 -07001171 *tag = TagFromObject(soa, o);
Elliott Hughes546b9862012-06-20 16:06:13 -07001172 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001173}
1174
Elliott Hughesaed4be92011-12-02 16:16:23 -08001175size_t Dbg::GetTagWidth(JDWP::JdwpTag tag) {
Elliott Hughesdbb40792011-11-18 17:05:22 -08001176 switch (tag) {
1177 case JDWP::JT_VOID:
1178 return 0;
1179 case JDWP::JT_BYTE:
1180 case JDWP::JT_BOOLEAN:
1181 return 1;
1182 case JDWP::JT_CHAR:
1183 case JDWP::JT_SHORT:
1184 return 2;
1185 case JDWP::JT_FLOAT:
1186 case JDWP::JT_INT:
1187 return 4;
1188 case JDWP::JT_ARRAY:
1189 case JDWP::JT_OBJECT:
1190 case JDWP::JT_STRING:
1191 case JDWP::JT_THREAD:
1192 case JDWP::JT_THREAD_GROUP:
1193 case JDWP::JT_CLASS_LOADER:
1194 case JDWP::JT_CLASS_OBJECT:
1195 return sizeof(JDWP::ObjectId);
1196 case JDWP::JT_DOUBLE:
1197 case JDWP::JT_LONG:
1198 return 8;
1199 default:
Elliott Hughes3d30d9b2011-12-07 17:35:48 -08001200 LOG(FATAL) << "Unknown tag " << tag;
Elliott Hughesdbb40792011-11-18 17:05:22 -08001201 return -1;
1202 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001203}
1204
Ian Rogersc0542af2014-09-03 16:16:56 -07001205JDWP::JdwpError Dbg::GetArrayLength(JDWP::ObjectId array_id, int32_t* length) {
1206 JDWP::JdwpError error;
1207 mirror::Array* a = DecodeNonNullArray(array_id, &error);
1208 if (a == nullptr) {
1209 return error;
Elliott Hughes24437992011-11-30 14:49:33 -08001210 }
Ian Rogersc0542af2014-09-03 16:16:56 -07001211 *length = a->GetLength();
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -08001212 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001213}
1214
Elliott Hughes88d63092013-01-09 09:55:54 -08001215JDWP::JdwpError Dbg::OutputArray(JDWP::ObjectId array_id, int offset, int count, JDWP::ExpandBuf* pReply) {
Ian Rogersc0542af2014-09-03 16:16:56 -07001216 JDWP::JdwpError error;
1217 mirror::Array* a = DecodeNonNullArray(array_id, &error);
Ian Rogers98379392014-02-24 16:53:16 -08001218 if (a == nullptr) {
Ian Rogersc0542af2014-09-03 16:16:56 -07001219 return error;
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -08001220 }
Elliott Hughes24437992011-11-30 14:49:33 -08001221
1222 if (offset < 0 || count < 0 || offset > a->GetLength() || a->GetLength() - offset < count) {
1223 LOG(WARNING) << __FUNCTION__ << " access out of bounds: offset=" << offset << "; count=" << count;
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -08001224 return JDWP::ERR_INVALID_LENGTH;
Elliott Hughes24437992011-11-30 14:49:33 -08001225 }
Ian Rogers1ff3c982014-08-12 02:30:58 -07001226 JDWP::JdwpTag element_tag = BasicTagFromClass(a->GetClass()->GetComponentType());
1227 expandBufAdd1(pReply, element_tag);
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -08001228 expandBufAdd4BE(pReply, count);
1229
Ian Rogers1ff3c982014-08-12 02:30:58 -07001230 if (IsPrimitiveTag(element_tag)) {
1231 size_t width = GetTagWidth(element_tag);
Elliott Hughes24437992011-11-30 14:49:33 -08001232 uint8_t* dst = expandBufAddSpace(pReply, count * width);
1233 if (width == 8) {
Ian Rogersef7d42f2014-01-06 12:55:46 -08001234 const uint64_t* src8 = reinterpret_cast<uint64_t*>(a->GetRawData(sizeof(uint64_t), 0));
Elliott Hughes24437992011-11-30 14:49:33 -08001235 for (int i = 0; i < count; ++i) JDWP::Write8BE(&dst, src8[offset + i]);
1236 } else if (width == 4) {
Ian Rogersef7d42f2014-01-06 12:55:46 -08001237 const uint32_t* src4 = reinterpret_cast<uint32_t*>(a->GetRawData(sizeof(uint32_t), 0));
Elliott Hughes24437992011-11-30 14:49:33 -08001238 for (int i = 0; i < count; ++i) JDWP::Write4BE(&dst, src4[offset + i]);
1239 } else if (width == 2) {
Ian Rogersef7d42f2014-01-06 12:55:46 -08001240 const uint16_t* src2 = reinterpret_cast<uint16_t*>(a->GetRawData(sizeof(uint16_t), 0));
Elliott Hughes24437992011-11-30 14:49:33 -08001241 for (int i = 0; i < count; ++i) JDWP::Write2BE(&dst, src2[offset + i]);
1242 } else {
Ian Rogersef7d42f2014-01-06 12:55:46 -08001243 const uint8_t* src = reinterpret_cast<uint8_t*>(a->GetRawData(sizeof(uint8_t), 0));
Elliott Hughes24437992011-11-30 14:49:33 -08001244 memcpy(dst, &src[offset * width], count * width);
1245 }
1246 } else {
Ian Rogers98379392014-02-24 16:53:16 -08001247 ScopedObjectAccessUnchecked soa(Thread::Current());
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001248 mirror::ObjectArray<mirror::Object>* oa = a->AsObjectArray<mirror::Object>();
Elliott Hughes24437992011-11-30 14:49:33 -08001249 for (int i = 0; i < count; ++i) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001250 mirror::Object* element = oa->Get(offset + i);
Ian Rogers98379392014-02-24 16:53:16 -08001251 JDWP::JdwpTag specific_tag = (element != nullptr) ? TagFromObject(soa, element)
Ian Rogers1ff3c982014-08-12 02:30:58 -07001252 : element_tag;
Elliott Hughes24437992011-11-30 14:49:33 -08001253 expandBufAdd1(pReply, specific_tag);
1254 expandBufAddObjectId(pReply, gRegistry->Add(element));
1255 }
1256 }
1257
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -08001258 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001259}
1260
Ian Rogersef7d42f2014-01-06 12:55:46 -08001261template <typename T>
Ian Rogersc0542af2014-09-03 16:16:56 -07001262static void CopyArrayData(mirror::Array* a, JDWP::Request* src, int offset, int count)
Ian Rogersef7d42f2014-01-06 12:55:46 -08001263 NO_THREAD_SAFETY_ANALYSIS {
1264 // TODO: fix when annotalysis correctly handles non-member functions.
Elliott Hughes4b9702c2013-02-20 18:13:24 -08001265 DCHECK(a->GetClass()->IsPrimitiveArray());
1266
Ian Rogersef7d42f2014-01-06 12:55:46 -08001267 T* dst = reinterpret_cast<T*>(a->GetRawData(sizeof(T), offset));
Elliott Hughes4b9702c2013-02-20 18:13:24 -08001268 for (int i = 0; i < count; ++i) {
Ian Rogersc0542af2014-09-03 16:16:56 -07001269 *dst++ = src->ReadValue(sizeof(T));
Elliott Hughes4b9702c2013-02-20 18:13:24 -08001270 }
1271}
1272
Elliott Hughes88d63092013-01-09 09:55:54 -08001273JDWP::JdwpError Dbg::SetArrayElements(JDWP::ObjectId array_id, int offset, int count,
Ian Rogersc0542af2014-09-03 16:16:56 -07001274 JDWP::Request* request) {
1275 JDWP::JdwpError error;
1276 mirror::Array* dst = DecodeNonNullArray(array_id, &error);
1277 if (dst == nullptr) {
1278 return error;
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -08001279 }
Elliott Hughesf03b8f62011-12-02 14:26:25 -08001280
Elliott Hughes4b9702c2013-02-20 18:13:24 -08001281 if (offset < 0 || count < 0 || offset > dst->GetLength() || dst->GetLength() - offset < count) {
Elliott Hughesf03b8f62011-12-02 14:26:25 -08001282 LOG(WARNING) << __FUNCTION__ << " access out of bounds: offset=" << offset << "; count=" << count;
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -08001283 return JDWP::ERR_INVALID_LENGTH;
Elliott Hughesf03b8f62011-12-02 14:26:25 -08001284 }
Ian Rogers1ff3c982014-08-12 02:30:58 -07001285 JDWP::JdwpTag element_tag = BasicTagFromClass(dst->GetClass()->GetComponentType());
Elliott Hughesf03b8f62011-12-02 14:26:25 -08001286
Ian Rogers1ff3c982014-08-12 02:30:58 -07001287 if (IsPrimitiveTag(element_tag)) {
1288 size_t width = GetTagWidth(element_tag);
Elliott Hughesf03b8f62011-12-02 14:26:25 -08001289 if (width == 8) {
Elliott Hughes4b9702c2013-02-20 18:13:24 -08001290 CopyArrayData<uint64_t>(dst, request, offset, count);
Elliott Hughesf03b8f62011-12-02 14:26:25 -08001291 } else if (width == 4) {
Elliott Hughes4b9702c2013-02-20 18:13:24 -08001292 CopyArrayData<uint32_t>(dst, request, offset, count);
Elliott Hughesf03b8f62011-12-02 14:26:25 -08001293 } else if (width == 2) {
Elliott Hughes4b9702c2013-02-20 18:13:24 -08001294 CopyArrayData<uint16_t>(dst, request, offset, count);
Elliott Hughesf03b8f62011-12-02 14:26:25 -08001295 } else {
Elliott Hughes4b9702c2013-02-20 18:13:24 -08001296 CopyArrayData<uint8_t>(dst, request, offset, count);
Elliott Hughesf03b8f62011-12-02 14:26:25 -08001297 }
1298 } else {
Elliott Hughes4b9702c2013-02-20 18:13:24 -08001299 mirror::ObjectArray<mirror::Object>* oa = dst->AsObjectArray<mirror::Object>();
Elliott Hughesf03b8f62011-12-02 14:26:25 -08001300 for (int i = 0; i < count; ++i) {
Ian Rogersc0542af2014-09-03 16:16:56 -07001301 JDWP::ObjectId id = request->ReadObjectId();
Ian Rogersc0542af2014-09-03 16:16:56 -07001302 mirror::Object* o = gRegistry->Get<mirror::Object*>(id, &error);
1303 if (error != JDWP::ERR_NONE) {
1304 return error;
Elliott Hughes436e3722012-02-17 20:01:47 -08001305 }
Sebastien Hertzd2fe10a2014-01-15 10:20:56 +01001306 oa->Set<false>(offset + i, o);
Elliott Hughesf03b8f62011-12-02 14:26:25 -08001307 }
1308 }
1309
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -08001310 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001311}
1312
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -08001313JDWP::ObjectId Dbg::CreateString(const std::string& str) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001314 return gRegistry->Add(mirror::String::AllocFromModifiedUtf8(Thread::Current(), str.c_str()));
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001315}
1316
Ian Rogersc0542af2014-09-03 16:16:56 -07001317JDWP::JdwpError Dbg::CreateObject(JDWP::RefTypeId class_id, JDWP::ObjectId* new_object) {
1318 JDWP::JdwpError error;
1319 mirror::Class* c = DecodeClass(class_id, &error);
1320 if (c == nullptr) {
1321 *new_object = 0;
1322 return error;
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -08001323 }
Ian Rogersc0542af2014-09-03 16:16:56 -07001324 *new_object = gRegistry->Add(c->AllocObject(Thread::Current()));
Elliott Hughes436e3722012-02-17 20:01:47 -08001325 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001326}
1327
Elliott Hughesbf13d362011-12-08 15:51:37 -08001328/*
1329 * Used by Eclipse's "Display" view to evaluate "new byte[5]" to get "(byte[]) [0, 0, 0, 0, 0]".
1330 */
Elliott Hughes88d63092013-01-09 09:55:54 -08001331JDWP::JdwpError Dbg::CreateArrayObject(JDWP::RefTypeId array_class_id, uint32_t length,
Ian Rogersc0542af2014-09-03 16:16:56 -07001332 JDWP::ObjectId* new_array) {
1333 JDWP::JdwpError error;
1334 mirror::Class* c = DecodeClass(array_class_id, &error);
1335 if (c == nullptr) {
1336 *new_array = 0;
1337 return error;
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -08001338 }
Ian Rogersc0542af2014-09-03 16:16:56 -07001339 *new_array = gRegistry->Add(mirror::Array::Alloc<true>(Thread::Current(), c, length,
Hiroshi Yamauchif0edfc32014-09-25 11:46:46 -07001340 c->GetComponentSizeShift(),
Ian Rogersc0542af2014-09-03 16:16:56 -07001341 Runtime::Current()->GetHeap()->GetCurrentAllocator()));
Elliott Hughes436e3722012-02-17 20:01:47 -08001342 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001343}
1344
Sebastien Hertz6995c602014-09-09 12:10:13 +02001345JDWP::FieldId Dbg::ToFieldId(const mirror::ArtField* f) {
Mathieu Chartier590fee92013-09-13 13:46:47 -07001346 CHECK(!kMovingFields);
Elliott Hughes03181a82011-11-17 17:22:21 -08001347 return static_cast<JDWP::FieldId>(reinterpret_cast<uintptr_t>(f));
Elliott Hughes03181a82011-11-17 17:22:21 -08001348}
1349
Brian Carlstromea46f952013-07-30 01:26:50 -07001350static JDWP::MethodId ToMethodId(const mirror::ArtMethod* m)
Ian Rogersb726dcb2012-09-05 08:57:23 -07001351 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Mathieu Chartier590fee92013-09-13 13:46:47 -07001352 CHECK(!kMovingMethods);
Elliott Hughes03181a82011-11-17 17:22:21 -08001353 return static_cast<JDWP::MethodId>(reinterpret_cast<uintptr_t>(m));
Elliott Hughes03181a82011-11-17 17:22:21 -08001354}
1355
Brian Carlstromea46f952013-07-30 01:26:50 -07001356static mirror::ArtField* FromFieldId(JDWP::FieldId fid)
Ian Rogersb726dcb2012-09-05 08:57:23 -07001357 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Mathieu Chartier590fee92013-09-13 13:46:47 -07001358 CHECK(!kMovingFields);
Brian Carlstromea46f952013-07-30 01:26:50 -07001359 return reinterpret_cast<mirror::ArtField*>(static_cast<uintptr_t>(fid));
Elliott Hughesaed4be92011-12-02 16:16:23 -08001360}
1361
Brian Carlstromea46f952013-07-30 01:26:50 -07001362static mirror::ArtMethod* FromMethodId(JDWP::MethodId mid)
Ian Rogersb726dcb2012-09-05 08:57:23 -07001363 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Mathieu Chartier590fee92013-09-13 13:46:47 -07001364 CHECK(!kMovingMethods);
Brian Carlstromea46f952013-07-30 01:26:50 -07001365 return reinterpret_cast<mirror::ArtMethod*>(static_cast<uintptr_t>(mid));
Elliott Hughes03181a82011-11-17 17:22:21 -08001366}
1367
Sebastien Hertz6995c602014-09-09 12:10:13 +02001368bool Dbg::MatchThread(JDWP::ObjectId expected_thread_id, Thread* event_thread) {
1369 CHECK(event_thread != nullptr);
1370 JDWP::JdwpError error;
1371 mirror::Object* expected_thread_peer = gRegistry->Get<mirror::Object*>(expected_thread_id,
1372 &error);
1373 return expected_thread_peer == event_thread->GetPeer();
1374}
1375
1376bool Dbg::MatchLocation(const JDWP::JdwpLocation& expected_location,
1377 const JDWP::EventLocation& event_location) {
1378 if (expected_location.dex_pc != event_location.dex_pc) {
1379 return false;
1380 }
1381 mirror::ArtMethod* m = FromMethodId(expected_location.method_id);
1382 return m == event_location.method;
1383}
1384
1385bool Dbg::MatchType(mirror::Class* event_class, JDWP::RefTypeId class_id) {
Sebastien Hertza9aa0ff2014-09-19 12:07:51 +02001386 if (event_class == nullptr) {
1387 return false;
1388 }
Sebastien Hertz6995c602014-09-09 12:10:13 +02001389 JDWP::JdwpError error;
1390 mirror::Class* expected_class = DecodeClass(class_id, &error);
1391 CHECK(expected_class != nullptr);
1392 return expected_class->IsAssignableFrom(event_class);
1393}
1394
1395bool Dbg::MatchField(JDWP::RefTypeId expected_type_id, JDWP::FieldId expected_field_id,
1396 mirror::ArtField* event_field) {
1397 mirror::ArtField* expected_field = FromFieldId(expected_field_id);
1398 if (expected_field != event_field) {
1399 return false;
1400 }
1401 return Dbg::MatchType(event_field->GetDeclaringClass(), expected_type_id);
1402}
1403
1404bool Dbg::MatchInstance(JDWP::ObjectId expected_instance_id, mirror::Object* event_instance) {
1405 JDWP::JdwpError error;
1406 mirror::Object* modifier_instance = gRegistry->Get<mirror::Object*>(expected_instance_id, &error);
1407 return modifier_instance == event_instance;
1408}
1409
1410void Dbg::SetJdwpLocation(JDWP::JdwpLocation* location, mirror::ArtMethod* m, uint32_t dex_pc)
Ian Rogersb726dcb2012-09-05 08:57:23 -07001411 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Ian Rogersc0542af2014-09-03 16:16:56 -07001412 if (m == nullptr) {
Sebastien Hertza9aa0ff2014-09-19 12:07:51 +02001413 memset(location, 0, sizeof(*location));
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08001414 } else {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001415 mirror::Class* c = m->GetDeclaringClass();
Ian Rogersc0542af2014-09-03 16:16:56 -07001416 location->type_tag = GetTypeTag(c);
1417 location->class_id = gRegistry->AddRefType(c);
1418 location->method_id = ToMethodId(m);
1419 location->dex_pc = (m->IsNative() || m->IsProxyMethod()) ? static_cast<uint64_t>(-1) : dex_pc;
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08001420 }
Elliott Hughesd07986f2011-12-06 18:27:45 -08001421}
1422
Ian Rogersc0542af2014-09-03 16:16:56 -07001423std::string Dbg::GetMethodName(JDWP::MethodId method_id) {
Brian Carlstromea46f952013-07-30 01:26:50 -07001424 mirror::ArtMethod* m = FromMethodId(method_id);
Sebastien Hertza9aa0ff2014-09-19 12:07:51 +02001425 if (m == nullptr) {
1426 return "NULL";
1427 }
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07001428 return m->GetName();
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001429}
1430
Ian Rogersc0542af2014-09-03 16:16:56 -07001431std::string Dbg::GetFieldName(JDWP::FieldId field_id) {
Sebastien Hertza9aa0ff2014-09-19 12:07:51 +02001432 mirror::ArtField* f = FromFieldId(field_id);
1433 if (f == nullptr) {
1434 return "NULL";
1435 }
1436 return f->GetName();
Elliott Hughesa96836a2013-01-17 12:27:49 -08001437}
1438
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001439/*
1440 * Augment the access flags for synthetic methods and fields by setting
1441 * the (as described by the spec) "0xf0000000 bit". Also, strip out any
1442 * flags not specified by the Java programming language.
1443 */
1444static uint32_t MangleAccessFlags(uint32_t accessFlags) {
1445 accessFlags &= kAccJavaFlagsMask;
1446 if ((accessFlags & kAccSynthetic) != 0) {
1447 accessFlags |= 0xf0000000;
1448 }
1449 return accessFlags;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001450}
1451
Elliott Hughesdbb40792011-11-18 17:05:22 -08001452/*
Jeff Haob7cefc72013-11-14 14:51:09 -08001453 * Circularly shifts registers so that arguments come first. Debuggers
1454 * expect slots to begin with arguments, but dex code places them at
1455 * the end.
Elliott Hughesdbb40792011-11-18 17:05:22 -08001456 */
Jeff Haob7cefc72013-11-14 14:51:09 -08001457static uint16_t MangleSlot(uint16_t slot, mirror::ArtMethod* m)
1458 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07001459 const DexFile::CodeItem* code_item = m->GetCodeItem();
Sebastien Hertzcb19ebf2014-03-11 15:26:35 +01001460 if (code_item == nullptr) {
1461 // We should not get here for a method without code (native, proxy or abstract). Log it and
1462 // return the slot as is since all registers are arguments.
1463 LOG(WARNING) << "Trying to mangle slot for method without code " << PrettyMethod(m);
1464 return slot;
1465 }
Jeff Haob7cefc72013-11-14 14:51:09 -08001466 uint16_t ins_size = code_item->ins_size_;
1467 uint16_t locals_size = code_item->registers_size_ - ins_size;
1468 if (slot >= locals_size) {
1469 return slot - locals_size;
1470 } else {
1471 return slot + ins_size;
Elliott Hughesdbb40792011-11-18 17:05:22 -08001472 }
Elliott Hughesdbb40792011-11-18 17:05:22 -08001473}
1474
Jeff Haob7cefc72013-11-14 14:51:09 -08001475/*
1476 * Circularly shifts registers so that arguments come last. Reverts
1477 * slots to dex style argument placement.
1478 */
Brian Carlstromea46f952013-07-30 01:26:50 -07001479static uint16_t DemangleSlot(uint16_t slot, mirror::ArtMethod* m)
Ian Rogersb726dcb2012-09-05 08:57:23 -07001480 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07001481 const DexFile::CodeItem* code_item = m->GetCodeItem();
Sebastien Hertzcb19ebf2014-03-11 15:26:35 +01001482 if (code_item == nullptr) {
1483 // We should not get here for a method without code (native, proxy or abstract). Log it and
1484 // return the slot as is since all registers are arguments.
1485 LOG(WARNING) << "Trying to demangle slot for method without code " << PrettyMethod(m);
1486 return slot;
1487 }
Jeff Haob7cefc72013-11-14 14:51:09 -08001488 uint16_t ins_size = code_item->ins_size_;
1489 uint16_t locals_size = code_item->registers_size_ - ins_size;
1490 if (slot < ins_size) {
1491 return slot + locals_size;
1492 } else {
1493 return slot - ins_size;
Elliott Hughesdbb40792011-11-18 17:05:22 -08001494 }
Elliott Hughesdbb40792011-11-18 17:05:22 -08001495}
1496
Elliott Hughes88d63092013-01-09 09:55:54 -08001497JDWP::JdwpError Dbg::OutputDeclaredFields(JDWP::RefTypeId class_id, bool with_generic, JDWP::ExpandBuf* pReply) {
Ian Rogersc0542af2014-09-03 16:16:56 -07001498 JDWP::JdwpError error;
1499 mirror::Class* c = DecodeClass(class_id, &error);
1500 if (c == nullptr) {
1501 return error;
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -08001502 }
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001503
1504 size_t instance_field_count = c->NumInstanceFields();
1505 size_t static_field_count = c->NumStaticFields();
1506
1507 expandBufAdd4BE(pReply, instance_field_count + static_field_count);
1508
1509 for (size_t i = 0; i < instance_field_count + static_field_count; ++i) {
Brian Carlstromea46f952013-07-30 01:26:50 -07001510 mirror::ArtField* f = (i < instance_field_count) ? c->GetInstanceField(i) : c->GetStaticField(i - instance_field_count);
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001511 expandBufAddFieldId(pReply, ToFieldId(f));
Mathieu Chartier61c5ebc2014-06-05 17:42:53 -07001512 expandBufAddUtf8String(pReply, f->GetName());
1513 expandBufAddUtf8String(pReply, f->GetTypeDescriptor());
Elliott Hughesc5b734a2011-12-01 17:20:58 -08001514 if (with_generic) {
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001515 static const char genericSignature[1] = "";
1516 expandBufAddUtf8String(pReply, genericSignature);
1517 }
1518 expandBufAdd4BE(pReply, MangleAccessFlags(f->GetAccessFlags()));
1519 }
Elliott Hughes436e3722012-02-17 20:01:47 -08001520 return JDWP::ERR_NONE;
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001521}
1522
Elliott Hughes88d63092013-01-09 09:55:54 -08001523JDWP::JdwpError Dbg::OutputDeclaredMethods(JDWP::RefTypeId class_id, bool with_generic,
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001524 JDWP::ExpandBuf* pReply) {
Ian Rogersc0542af2014-09-03 16:16:56 -07001525 JDWP::JdwpError error;
1526 mirror::Class* c = DecodeClass(class_id, &error);
1527 if (c == nullptr) {
1528 return error;
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -08001529 }
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001530
1531 size_t direct_method_count = c->NumDirectMethods();
1532 size_t virtual_method_count = c->NumVirtualMethods();
1533
1534 expandBufAdd4BE(pReply, direct_method_count + virtual_method_count);
1535
1536 for (size_t i = 0; i < direct_method_count + virtual_method_count; ++i) {
Brian Carlstromea46f952013-07-30 01:26:50 -07001537 mirror::ArtMethod* m = (i < direct_method_count) ? c->GetDirectMethod(i) : c->GetVirtualMethod(i - direct_method_count);
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001538 expandBufAddMethodId(pReply, ToMethodId(m));
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07001539 expandBufAddUtf8String(pReply, m->GetName());
1540 expandBufAddUtf8String(pReply, m->GetSignature().ToString());
Elliott Hughesc5b734a2011-12-01 17:20:58 -08001541 if (with_generic) {
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001542 static const char genericSignature[1] = "";
1543 expandBufAddUtf8String(pReply, genericSignature);
1544 }
1545 expandBufAdd4BE(pReply, MangleAccessFlags(m->GetAccessFlags()));
1546 }
Elliott Hughes436e3722012-02-17 20:01:47 -08001547 return JDWP::ERR_NONE;
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001548}
1549
Elliott Hughes88d63092013-01-09 09:55:54 -08001550JDWP::JdwpError Dbg::OutputDeclaredInterfaces(JDWP::RefTypeId class_id, JDWP::ExpandBuf* pReply) {
Ian Rogersc0542af2014-09-03 16:16:56 -07001551 JDWP::JdwpError error;
Mathieu Chartierf8322842014-05-16 10:59:25 -07001552 Thread* self = Thread::Current();
1553 StackHandleScope<1> hs(self);
Ian Rogersc0542af2014-09-03 16:16:56 -07001554 Handle<mirror::Class> c(hs.NewHandle(DecodeClass(class_id, &error)));
Mathieu Chartierf8322842014-05-16 10:59:25 -07001555 if (c.Get() == nullptr) {
Ian Rogersc0542af2014-09-03 16:16:56 -07001556 return error;
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -08001557 }
Mathieu Chartierf8322842014-05-16 10:59:25 -07001558 size_t interface_count = c->NumDirectInterfaces();
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001559 expandBufAdd4BE(pReply, interface_count);
1560 for (size_t i = 0; i < interface_count; ++i) {
Mathieu Chartierf8322842014-05-16 10:59:25 -07001561 expandBufAddRefTypeId(pReply,
1562 gRegistry->AddRefType(mirror::Class::GetDirectInterface(self, c, i)));
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001563 }
Elliott Hughes436e3722012-02-17 20:01:47 -08001564 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001565}
1566
Ian Rogersc0542af2014-09-03 16:16:56 -07001567void Dbg::OutputLineTable(JDWP::RefTypeId, JDWP::MethodId method_id, JDWP::ExpandBuf* pReply) {
Elliott Hughes03181a82011-11-17 17:22:21 -08001568 struct DebugCallbackContext {
1569 int numItems;
1570 JDWP::ExpandBuf* pReply;
1571
Elliott Hughes2435a572012-02-17 16:07:41 -08001572 static bool Callback(void* context, uint32_t address, uint32_t line_number) {
Elliott Hughes03181a82011-11-17 17:22:21 -08001573 DebugCallbackContext* pContext = reinterpret_cast<DebugCallbackContext*>(context);
1574 expandBufAdd8BE(pContext->pReply, address);
Elliott Hughes2435a572012-02-17 16:07:41 -08001575 expandBufAdd4BE(pContext->pReply, line_number);
Elliott Hughes03181a82011-11-17 17:22:21 -08001576 pContext->numItems++;
Sebastien Hertzf2910ee2013-10-19 16:39:24 +02001577 return false;
Elliott Hughes03181a82011-11-17 17:22:21 -08001578 }
1579 };
Brian Carlstromea46f952013-07-30 01:26:50 -07001580 mirror::ArtMethod* m = FromMethodId(method_id);
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07001581 const DexFile::CodeItem* code_item = m->GetCodeItem();
Elliott Hughes03181a82011-11-17 17:22:21 -08001582 uint64_t start, end;
Sebastien Hertzcb19ebf2014-03-11 15:26:35 +01001583 if (code_item == nullptr) {
1584 DCHECK(m->IsNative() || m->IsProxyMethod());
Elliott Hughes03181a82011-11-17 17:22:21 -08001585 start = -1;
1586 end = -1;
1587 } else {
1588 start = 0;
jeffhao14f0db92012-12-14 17:50:42 -08001589 // Return the index of the last instruction
Sebastien Hertzcb19ebf2014-03-11 15:26:35 +01001590 end = code_item->insns_size_in_code_units_ - 1;
Elliott Hughes03181a82011-11-17 17:22:21 -08001591 }
1592
1593 expandBufAdd8BE(pReply, start);
1594 expandBufAdd8BE(pReply, end);
1595
1596 // Add numLines later
1597 size_t numLinesOffset = expandBufGetLength(pReply);
1598 expandBufAdd4BE(pReply, 0);
1599
1600 DebugCallbackContext context;
1601 context.numItems = 0;
1602 context.pReply = pReply;
1603
Sebastien Hertzcb19ebf2014-03-11 15:26:35 +01001604 if (code_item != nullptr) {
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07001605 m->GetDexFile()->DecodeDebugInfo(code_item, m->IsStatic(), m->GetDexMethodIndex(),
Ian Rogersc0542af2014-09-03 16:16:56 -07001606 DebugCallbackContext::Callback, nullptr, &context);
Sebastien Hertzcb19ebf2014-03-11 15:26:35 +01001607 }
Elliott Hughes03181a82011-11-17 17:22:21 -08001608
1609 JDWP::Set4BE(expandBufGetBuffer(pReply) + numLinesOffset, context.numItems);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001610}
1611
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07001612void Dbg::OutputVariableTable(JDWP::RefTypeId, JDWP::MethodId method_id, bool with_generic,
1613 JDWP::ExpandBuf* pReply) {
Elliott Hughesdbb40792011-11-18 17:05:22 -08001614 struct DebugCallbackContext {
Jeff Haob7cefc72013-11-14 14:51:09 -08001615 mirror::ArtMethod* method;
Elliott Hughesdbb40792011-11-18 17:05:22 -08001616 JDWP::ExpandBuf* pReply;
Elliott Hughesc5b734a2011-12-01 17:20:58 -08001617 size_t variable_count;
1618 bool with_generic;
Elliott Hughesdbb40792011-11-18 17:05:22 -08001619
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07001620 static void Callback(void* context, uint16_t slot, uint32_t startAddress, uint32_t endAddress,
1621 const char* name, const char* descriptor, const char* signature)
Jeff Haob7cefc72013-11-14 14:51:09 -08001622 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Elliott Hughesdbb40792011-11-18 17:05:22 -08001623 DebugCallbackContext* pContext = reinterpret_cast<DebugCallbackContext*>(context);
1624
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07001625 VLOG(jdwp) << StringPrintf(" %2zd: %d(%d) '%s' '%s' '%s' actual slot=%d mangled slot=%d",
1626 pContext->variable_count, startAddress, endAddress - startAddress,
1627 name, descriptor, signature, slot,
1628 MangleSlot(slot, pContext->method));
Elliott Hughesdbb40792011-11-18 17:05:22 -08001629
Jeff Haob7cefc72013-11-14 14:51:09 -08001630 slot = MangleSlot(slot, pContext->method);
Elliott Hughes68fdbd02011-11-29 19:22:47 -08001631
Elliott Hughesdbb40792011-11-18 17:05:22 -08001632 expandBufAdd8BE(pContext->pReply, startAddress);
1633 expandBufAddUtf8String(pContext->pReply, name);
1634 expandBufAddUtf8String(pContext->pReply, descriptor);
Elliott Hughesc5b734a2011-12-01 17:20:58 -08001635 if (pContext->with_generic) {
Elliott Hughesdbb40792011-11-18 17:05:22 -08001636 expandBufAddUtf8String(pContext->pReply, signature);
1637 }
1638 expandBufAdd4BE(pContext->pReply, endAddress - startAddress);
1639 expandBufAdd4BE(pContext->pReply, slot);
1640
Elliott Hughesc5b734a2011-12-01 17:20:58 -08001641 ++pContext->variable_count;
Elliott Hughesdbb40792011-11-18 17:05:22 -08001642 }
1643 };
Brian Carlstromea46f952013-07-30 01:26:50 -07001644 mirror::ArtMethod* m = FromMethodId(method_id);
Elliott Hughesdbb40792011-11-18 17:05:22 -08001645
Elliott Hughesc5b734a2011-12-01 17:20:58 -08001646 // arg_count considers doubles and longs to take 2 units.
1647 // variable_count considers everything to take 1 unit.
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07001648 std::string shorty(m->GetShorty());
Brian Carlstromea46f952013-07-30 01:26:50 -07001649 expandBufAdd4BE(pReply, mirror::ArtMethod::NumArgRegisters(shorty));
Elliott Hughesdbb40792011-11-18 17:05:22 -08001650
Elliott Hughesc5b734a2011-12-01 17:20:58 -08001651 // We don't know the total number of variables yet, so leave a blank and update it later.
1652 size_t variable_count_offset = expandBufGetLength(pReply);
Elliott Hughesdbb40792011-11-18 17:05:22 -08001653 expandBufAdd4BE(pReply, 0);
1654
1655 DebugCallbackContext context;
Jeff Haob7cefc72013-11-14 14:51:09 -08001656 context.method = m;
Elliott Hughesdbb40792011-11-18 17:05:22 -08001657 context.pReply = pReply;
Elliott Hughesc5b734a2011-12-01 17:20:58 -08001658 context.variable_count = 0;
1659 context.with_generic = with_generic;
Elliott Hughesdbb40792011-11-18 17:05:22 -08001660
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07001661 const DexFile::CodeItem* code_item = m->GetCodeItem();
Sebastien Hertzcb19ebf2014-03-11 15:26:35 +01001662 if (code_item != nullptr) {
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07001663 m->GetDexFile()->DecodeDebugInfo(
Ian Rogersc0542af2014-09-03 16:16:56 -07001664 code_item, m->IsStatic(), m->GetDexMethodIndex(), nullptr, DebugCallbackContext::Callback,
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07001665 &context);
Sebastien Hertzcb19ebf2014-03-11 15:26:35 +01001666 }
Elliott Hughesdbb40792011-11-18 17:05:22 -08001667
Elliott Hughesc5b734a2011-12-01 17:20:58 -08001668 JDWP::Set4BE(expandBufGetBuffer(pReply) + variable_count_offset, context.variable_count);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001669}
1670
Jeff Hao579b0242013-11-18 13:16:49 -08001671void Dbg::OutputMethodReturnValue(JDWP::MethodId method_id, const JValue* return_value,
1672 JDWP::ExpandBuf* pReply) {
1673 mirror::ArtMethod* m = FromMethodId(method_id);
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07001674 JDWP::JdwpTag tag = BasicTagFromDescriptor(m->GetShorty());
Jeff Hao579b0242013-11-18 13:16:49 -08001675 OutputJValue(tag, return_value, pReply);
1676}
1677
Sebastien Hertz3f52eaf2014-04-04 17:50:18 +02001678void Dbg::OutputFieldValue(JDWP::FieldId field_id, const JValue* field_value,
1679 JDWP::ExpandBuf* pReply) {
1680 mirror::ArtField* f = FromFieldId(field_id);
Mathieu Chartier61c5ebc2014-06-05 17:42:53 -07001681 JDWP::JdwpTag tag = BasicTagFromDescriptor(f->GetTypeDescriptor());
Sebastien Hertz3f52eaf2014-04-04 17:50:18 +02001682 OutputJValue(tag, field_value, pReply);
1683}
1684
Elliott Hughes9777ba22013-01-17 09:04:19 -08001685JDWP::JdwpError Dbg::GetBytecodes(JDWP::RefTypeId, JDWP::MethodId method_id,
Ian Rogersc0542af2014-09-03 16:16:56 -07001686 std::vector<uint8_t>* bytecodes) {
Brian Carlstromea46f952013-07-30 01:26:50 -07001687 mirror::ArtMethod* m = FromMethodId(method_id);
Ian Rogersc0542af2014-09-03 16:16:56 -07001688 if (m == nullptr) {
Elliott Hughes9777ba22013-01-17 09:04:19 -08001689 return JDWP::ERR_INVALID_METHODID;
1690 }
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07001691 const DexFile::CodeItem* code_item = m->GetCodeItem();
Elliott Hughes9777ba22013-01-17 09:04:19 -08001692 size_t byte_count = code_item->insns_size_in_code_units_ * 2;
1693 const uint8_t* begin = reinterpret_cast<const uint8_t*>(code_item->insns_);
1694 const uint8_t* end = begin + byte_count;
1695 for (const uint8_t* p = begin; p != end; ++p) {
Ian Rogersc0542af2014-09-03 16:16:56 -07001696 bytecodes->push_back(*p);
Elliott Hughes9777ba22013-01-17 09:04:19 -08001697 }
1698 return JDWP::ERR_NONE;
1699}
1700
Elliott Hughes88d63092013-01-09 09:55:54 -08001701JDWP::JdwpTag Dbg::GetFieldBasicTag(JDWP::FieldId field_id) {
Mathieu Chartier61c5ebc2014-06-05 17:42:53 -07001702 return BasicTagFromDescriptor(FromFieldId(field_id)->GetTypeDescriptor());
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001703}
1704
Elliott Hughes88d63092013-01-09 09:55:54 -08001705JDWP::JdwpTag Dbg::GetStaticFieldBasicTag(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 -08001709static JDWP::JdwpError GetFieldValueImpl(JDWP::RefTypeId ref_type_id, JDWP::ObjectId object_id,
1710 JDWP::FieldId field_id, JDWP::ExpandBuf* pReply,
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001711 bool is_static)
Ian Rogersb726dcb2012-09-05 08:57:23 -07001712 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Ian Rogersc0542af2014-09-03 16:16:56 -07001713 JDWP::JdwpError error;
1714 mirror::Class* c = DecodeClass(ref_type_id, &error);
1715 if (ref_type_id != 0 && c == nullptr) {
1716 return error;
Elliott Hughes0cf74332012-02-23 23:14:00 -08001717 }
1718
Sebastien Hertz6995c602014-09-09 12:10:13 +02001719 mirror::Object* o = Dbg::GetObjectRegistry()->Get<mirror::Object*>(object_id, &error);
Ian Rogersc0542af2014-09-03 16:16:56 -07001720 if ((!is_static && o == nullptr) || error != JDWP::ERR_NONE) {
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08001721 return JDWP::ERR_INVALID_OBJECT;
1722 }
Brian Carlstromea46f952013-07-30 01:26:50 -07001723 mirror::ArtField* f = FromFieldId(field_id);
Elliott Hughes0cf74332012-02-23 23:14:00 -08001724
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001725 mirror::Class* receiver_class = c;
Ian Rogersc0542af2014-09-03 16:16:56 -07001726 if (receiver_class == nullptr && o != nullptr) {
Elliott Hughes0cf74332012-02-23 23:14:00 -08001727 receiver_class = o->GetClass();
1728 }
Ian Rogersc0542af2014-09-03 16:16:56 -07001729 // TODO: should we give up now if receiver_class is nullptr?
1730 if (receiver_class != nullptr && !f->GetDeclaringClass()->IsAssignableFrom(receiver_class)) {
Elliott Hughes0cf74332012-02-23 23:14:00 -08001731 LOG(INFO) << "ERR_INVALID_FIELDID: " << PrettyField(f) << " " << PrettyClass(receiver_class);
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08001732 return JDWP::ERR_INVALID_FIELDID;
1733 }
Elliott Hughesaed4be92011-12-02 16:16:23 -08001734
Elliott Hughes0cf74332012-02-23 23:14:00 -08001735 // The RI only enforces the static/non-static mismatch in one direction.
1736 // TODO: should we change the tests and check both?
1737 if (is_static) {
1738 if (!f->IsStatic()) {
1739 return JDWP::ERR_INVALID_FIELDID;
1740 }
1741 } else {
1742 if (f->IsStatic()) {
Ian Rogersc0542af2014-09-03 16:16:56 -07001743 LOG(WARNING) << "Ignoring non-nullptr receiver for ObjectReference.SetValues on static field "
1744 << PrettyField(f);
Elliott Hughes0cf74332012-02-23 23:14:00 -08001745 }
1746 }
jeffhao0dfbb7e2012-11-28 15:26:03 -08001747 if (f->IsStatic()) {
1748 o = f->GetDeclaringClass();
1749 }
Elliott Hughes0cf74332012-02-23 23:14:00 -08001750
Mathieu Chartier61c5ebc2014-06-05 17:42:53 -07001751 JDWP::JdwpTag tag = BasicTagFromDescriptor(f->GetTypeDescriptor());
Jeff Hao579b0242013-11-18 13:16:49 -08001752 JValue field_value;
1753 if (tag == JDWP::JT_VOID) {
1754 LOG(FATAL) << "Unknown tag: " << tag;
1755 } else if (!IsPrimitiveTag(tag)) {
1756 field_value.SetL(f->GetObject(o));
1757 } else if (tag == JDWP::JT_DOUBLE || tag == JDWP::JT_LONG) {
1758 field_value.SetJ(f->Get64(o));
Elliott Hughesaed4be92011-12-02 16:16:23 -08001759 } else {
Jeff Hao579b0242013-11-18 13:16:49 -08001760 field_value.SetI(f->Get32(o));
Elliott Hughesaed4be92011-12-02 16:16:23 -08001761 }
Jeff Hao579b0242013-11-18 13:16:49 -08001762 Dbg::OutputJValue(tag, &field_value, pReply);
1763
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08001764 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001765}
1766
Elliott Hughes88d63092013-01-09 09:55:54 -08001767JDWP::JdwpError Dbg::GetFieldValue(JDWP::ObjectId object_id, JDWP::FieldId field_id,
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001768 JDWP::ExpandBuf* pReply) {
Elliott Hughes88d63092013-01-09 09:55:54 -08001769 return GetFieldValueImpl(0, object_id, field_id, pReply, false);
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08001770}
1771
Ian Rogersc0542af2014-09-03 16:16:56 -07001772JDWP::JdwpError Dbg::GetStaticFieldValue(JDWP::RefTypeId ref_type_id, JDWP::FieldId field_id,
1773 JDWP::ExpandBuf* pReply) {
Elliott Hughes88d63092013-01-09 09:55:54 -08001774 return GetFieldValueImpl(ref_type_id, 0, field_id, pReply, true);
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08001775}
1776
Elliott Hughes88d63092013-01-09 09:55:54 -08001777static JDWP::JdwpError SetFieldValueImpl(JDWP::ObjectId object_id, JDWP::FieldId field_id,
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001778 uint64_t value, int width, bool is_static)
Ian Rogersb726dcb2012-09-05 08:57:23 -07001779 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Ian Rogersc0542af2014-09-03 16:16:56 -07001780 JDWP::JdwpError error;
Sebastien Hertz6995c602014-09-09 12:10:13 +02001781 mirror::Object* o = Dbg::GetObjectRegistry()->Get<mirror::Object*>(object_id, &error);
Ian Rogersc0542af2014-09-03 16:16:56 -07001782 if ((!is_static && o == nullptr) || error != JDWP::ERR_NONE) {
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08001783 return JDWP::ERR_INVALID_OBJECT;
1784 }
Brian Carlstromea46f952013-07-30 01:26:50 -07001785 mirror::ArtField* f = FromFieldId(field_id);
Elliott Hughes0cf74332012-02-23 23:14:00 -08001786
1787 // The RI only enforces the static/non-static mismatch in one direction.
1788 // TODO: should we change the tests and check both?
1789 if (is_static) {
1790 if (!f->IsStatic()) {
1791 return JDWP::ERR_INVALID_FIELDID;
1792 }
1793 } else {
1794 if (f->IsStatic()) {
Ian Rogersc0542af2014-09-03 16:16:56 -07001795 LOG(WARNING) << "Ignoring non-nullptr receiver for ObjectReference.SetValues on static field " << PrettyField(f);
Elliott Hughes0cf74332012-02-23 23:14:00 -08001796 }
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08001797 }
jeffhao0dfbb7e2012-11-28 15:26:03 -08001798 if (f->IsStatic()) {
1799 o = f->GetDeclaringClass();
1800 }
Elliott Hughesaed4be92011-12-02 16:16:23 -08001801
Mathieu Chartier61c5ebc2014-06-05 17:42:53 -07001802 JDWP::JdwpTag tag = BasicTagFromDescriptor(f->GetTypeDescriptor());
Elliott Hughesaed4be92011-12-02 16:16:23 -08001803
1804 if (IsPrimitiveTag(tag)) {
1805 if (tag == JDWP::JT_DOUBLE || tag == JDWP::JT_LONG) {
Elliott Hughes1bac54f2012-03-16 12:48:31 -07001806 CHECK_EQ(width, 8);
Sebastien Hertzd2fe10a2014-01-15 10:20:56 +01001807 // Debugging can't use transactional mode (runtime only).
1808 f->Set64<false>(o, value);
Elliott Hughesaed4be92011-12-02 16:16:23 -08001809 } else {
Elliott Hughes1bac54f2012-03-16 12:48:31 -07001810 CHECK_LE(width, 4);
Sebastien Hertzd2fe10a2014-01-15 10:20:56 +01001811 // Debugging can't use transactional mode (runtime only).
1812 f->Set32<false>(o, value);
Elliott Hughesaed4be92011-12-02 16:16:23 -08001813 }
1814 } else {
Sebastien Hertz6995c602014-09-09 12:10:13 +02001815 mirror::Object* v = Dbg::GetObjectRegistry()->Get<mirror::Object*>(value, &error);
Ian Rogersc0542af2014-09-03 16:16:56 -07001816 if (error != JDWP::ERR_NONE) {
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -08001817 return JDWP::ERR_INVALID_OBJECT;
1818 }
Ian Rogersc0542af2014-09-03 16:16:56 -07001819 if (v != nullptr) {
Mathieu Chartier61c5ebc2014-06-05 17:42:53 -07001820 mirror::Class* field_type;
1821 {
1822 StackHandleScope<3> hs(Thread::Current());
1823 HandleWrapper<mirror::Object> h_v(hs.NewHandleWrapper(&v));
1824 HandleWrapper<mirror::ArtField> h_f(hs.NewHandleWrapper(&f));
1825 HandleWrapper<mirror::Object> h_o(hs.NewHandleWrapper(&o));
Ian Rogers08f1f502014-12-02 15:04:37 -08001826 field_type = h_f->GetType(true);
Mathieu Chartier61c5ebc2014-06-05 17:42:53 -07001827 }
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08001828 if (!field_type->IsAssignableFrom(v->GetClass())) {
1829 return JDWP::ERR_INVALID_OBJECT;
1830 }
1831 }
Sebastien Hertzd2fe10a2014-01-15 10:20:56 +01001832 // Debugging can't use transactional mode (runtime only).
1833 f->SetObject<false>(o, v);
Elliott Hughesaed4be92011-12-02 16:16:23 -08001834 }
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -08001835
1836 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001837}
1838
Elliott Hughes88d63092013-01-09 09:55:54 -08001839JDWP::JdwpError Dbg::SetFieldValue(JDWP::ObjectId object_id, JDWP::FieldId field_id, uint64_t value,
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001840 int width) {
Elliott Hughes88d63092013-01-09 09:55:54 -08001841 return SetFieldValueImpl(object_id, field_id, value, width, false);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001842}
1843
Elliott Hughes88d63092013-01-09 09:55:54 -08001844JDWP::JdwpError Dbg::SetStaticFieldValue(JDWP::FieldId field_id, uint64_t value, int width) {
1845 return SetFieldValueImpl(0, field_id, value, width, true);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001846}
1847
Sebastien Hertzb0b0b492014-09-15 11:27:27 +02001848JDWP::JdwpError Dbg::StringToUtf8(JDWP::ObjectId string_id, std::string* str) {
Ian Rogersc0542af2014-09-03 16:16:56 -07001849 JDWP::JdwpError error;
Sebastien Hertzb0b0b492014-09-15 11:27:27 +02001850 mirror::Object* obj = gRegistry->Get<mirror::Object*>(string_id, &error);
1851 if (error != JDWP::ERR_NONE) {
1852 return error;
1853 }
1854 if (obj == nullptr) {
1855 return JDWP::ERR_INVALID_OBJECT;
1856 }
1857 {
1858 ScopedObjectAccessUnchecked soa(Thread::Current());
1859 mirror::Class* java_lang_String = soa.Decode<mirror::Class*>(WellKnownClasses::java_lang_String);
1860 if (!java_lang_String->IsAssignableFrom(obj->GetClass())) {
1861 // This isn't a string.
1862 return JDWP::ERR_INVALID_STRING;
1863 }
1864 }
1865 *str = obj->AsString()->ToModifiedUtf8();
1866 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001867}
1868
Jeff Hao579b0242013-11-18 13:16:49 -08001869void Dbg::OutputJValue(JDWP::JdwpTag tag, const JValue* return_value, JDWP::ExpandBuf* pReply) {
1870 if (IsPrimitiveTag(tag)) {
1871 expandBufAdd1(pReply, tag);
1872 if (tag == JDWP::JT_BOOLEAN || tag == JDWP::JT_BYTE) {
1873 expandBufAdd1(pReply, return_value->GetI());
1874 } else if (tag == JDWP::JT_CHAR || tag == JDWP::JT_SHORT) {
1875 expandBufAdd2BE(pReply, return_value->GetI());
1876 } else if (tag == JDWP::JT_FLOAT || tag == JDWP::JT_INT) {
1877 expandBufAdd4BE(pReply, return_value->GetI());
1878 } else if (tag == JDWP::JT_DOUBLE || tag == JDWP::JT_LONG) {
1879 expandBufAdd8BE(pReply, return_value->GetJ());
1880 } else {
1881 CHECK_EQ(tag, JDWP::JT_VOID);
1882 }
1883 } else {
Ian Rogers98379392014-02-24 16:53:16 -08001884 ScopedObjectAccessUnchecked soa(Thread::Current());
Jeff Hao579b0242013-11-18 13:16:49 -08001885 mirror::Object* value = return_value->GetL();
Ian Rogers98379392014-02-24 16:53:16 -08001886 expandBufAdd1(pReply, TagFromObject(soa, value));
Jeff Hao579b0242013-11-18 13:16:49 -08001887 expandBufAddObjectId(pReply, gRegistry->Add(value));
1888 }
1889}
1890
Ian Rogersc0542af2014-09-03 16:16:56 -07001891JDWP::JdwpError Dbg::GetThreadName(JDWP::ObjectId thread_id, std::string* name) {
jeffhaoa77f0f62012-12-05 17:19:31 -08001892 ScopedObjectAccessUnchecked soa(Thread::Current());
1893 MutexLock mu(soa.Self(), *Locks::thread_list_lock_);
Ian Rogersc0542af2014-09-03 16:16:56 -07001894 JDWP::JdwpError error;
1895 Thread* thread = DecodeThread(soa, thread_id, &error);
1896 UNUSED(thread);
Elliott Hughes221229c2013-01-08 18:17:50 -08001897 if (error != JDWP::ERR_NONE && error != JDWP::ERR_THREAD_NOT_ALIVE) {
1898 return error;
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001899 }
Elliott Hughes221229c2013-01-08 18:17:50 -08001900
1901 // We still need to report the zombie threads' names, so we can't just call Thread::GetThreadName.
Ian Rogersc0542af2014-09-03 16:16:56 -07001902 mirror::Object* thread_object = gRegistry->Get<mirror::Object*>(thread_id, &error);
1903 CHECK(thread_object != nullptr) << error;
Brian Carlstromea46f952013-07-30 01:26:50 -07001904 mirror::ArtField* java_lang_Thread_name_field =
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001905 soa.DecodeField(WellKnownClasses::java_lang_Thread_name);
1906 mirror::String* s =
1907 reinterpret_cast<mirror::String*>(java_lang_Thread_name_field->GetObject(thread_object));
Ian Rogersc0542af2014-09-03 16:16:56 -07001908 if (s != nullptr) {
1909 *name = s->ToModifiedUtf8();
Elliott Hughes221229c2013-01-08 18:17:50 -08001910 }
1911 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001912}
1913
Elliott Hughes221229c2013-01-08 18:17:50 -08001914JDWP::JdwpError Dbg::GetThreadGroup(JDWP::ObjectId thread_id, JDWP::ExpandBuf* pReply) {
Sebastien Hertza06430c2014-09-15 19:21:30 +02001915 ScopedObjectAccessUnchecked soa(Thread::Current());
Ian Rogersc0542af2014-09-03 16:16:56 -07001916 JDWP::JdwpError error;
1917 mirror::Object* thread_object = gRegistry->Get<mirror::Object*>(thread_id, &error);
1918 if (error != JDWP::ERR_NONE) {
Elliott Hughes2435a572012-02-17 16:07:41 -08001919 return JDWP::ERR_INVALID_OBJECT;
1920 }
Mathieu Chartier2d5f39e2014-09-19 17:52:37 -07001921 ScopedAssertNoThreadSuspension ants(soa.Self(), "Debugger: GetThreadGroup");
Elliott Hughes2435a572012-02-17 16:07:41 -08001922 // Okay, so it's an object, but is it actually a thread?
Hiroshi Yamauchib5a9e3d2014-06-09 12:11:20 -07001923 {
1924 MutexLock mu(soa.Self(), *Locks::thread_list_lock_);
Ian Rogersc0542af2014-09-03 16:16:56 -07001925 Thread* thread = DecodeThread(soa, thread_id, &error);
1926 UNUSED(thread);
Hiroshi Yamauchib5a9e3d2014-06-09 12:11:20 -07001927 }
Elliott Hughes221229c2013-01-08 18:17:50 -08001928 if (error == JDWP::ERR_THREAD_NOT_ALIVE) {
1929 // Zombie threads are in the null group.
1930 expandBufAddObjectId(pReply, JDWP::ObjectId(0));
Sebastien Hertz52d131d2014-03-13 16:17:40 +01001931 error = JDWP::ERR_NONE;
1932 } else if (error == JDWP::ERR_NONE) {
1933 mirror::Class* c = soa.Decode<mirror::Class*>(WellKnownClasses::java_lang_Thread);
1934 CHECK(c != nullptr);
Sebastien Hertze49e1952014-10-13 11:27:13 +02001935 mirror::ArtField* f = soa.DecodeField(WellKnownClasses::java_lang_Thread_group);
Hiroshi Yamauchib5a9e3d2014-06-09 12:11:20 -07001936 CHECK(f != nullptr);
Sebastien Hertz52d131d2014-03-13 16:17:40 +01001937 mirror::Object* group = f->GetObject(thread_object);
Hiroshi Yamauchib5a9e3d2014-06-09 12:11:20 -07001938 CHECK(group != nullptr);
Sebastien Hertz52d131d2014-03-13 16:17:40 +01001939 JDWP::ObjectId thread_group_id = gRegistry->Add(group);
1940 expandBufAddObjectId(pReply, thread_group_id);
Elliott Hughes221229c2013-01-08 18:17:50 -08001941 }
Sebastien Hertz52d131d2014-03-13 16:17:40 +01001942 return error;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001943}
1944
Sebastien Hertza06430c2014-09-15 19:21:30 +02001945static mirror::Object* DecodeThreadGroup(ScopedObjectAccessUnchecked& soa,
1946 JDWP::ObjectId thread_group_id, JDWP::JdwpError* error)
1947 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Sebastien Hertz6995c602014-09-09 12:10:13 +02001948 mirror::Object* thread_group = Dbg::GetObjectRegistry()->Get<mirror::Object*>(thread_group_id,
1949 error);
Sebastien Hertza06430c2014-09-15 19:21:30 +02001950 if (*error != JDWP::ERR_NONE) {
1951 return nullptr;
1952 }
1953 if (thread_group == nullptr) {
1954 *error = JDWP::ERR_INVALID_OBJECT;
1955 return nullptr;
1956 }
Ian Rogers98379392014-02-24 16:53:16 -08001957 mirror::Class* c = soa.Decode<mirror::Class*>(WellKnownClasses::java_lang_ThreadGroup);
1958 CHECK(c != nullptr);
Sebastien Hertza06430c2014-09-15 19:21:30 +02001959 if (!c->IsAssignableFrom(thread_group->GetClass())) {
1960 // This is not a java.lang.ThreadGroup.
1961 *error = JDWP::ERR_INVALID_THREAD_GROUP;
1962 return nullptr;
1963 }
1964 *error = JDWP::ERR_NONE;
1965 return thread_group;
1966}
1967
1968JDWP::JdwpError Dbg::GetThreadGroupName(JDWP::ObjectId thread_group_id, JDWP::ExpandBuf* pReply) {
1969 ScopedObjectAccessUnchecked soa(Thread::Current());
1970 JDWP::JdwpError error;
1971 mirror::Object* thread_group = DecodeThreadGroup(soa, thread_group_id, &error);
1972 if (error != JDWP::ERR_NONE) {
1973 return error;
1974 }
Mathieu Chartier2d5f39e2014-09-19 17:52:37 -07001975 ScopedAssertNoThreadSuspension ants(soa.Self(), "Debugger: GetThreadGroupName");
Sebastien Hertze49e1952014-10-13 11:27:13 +02001976 mirror::ArtField* f = soa.DecodeField(WellKnownClasses::java_lang_ThreadGroup_name);
Ian Rogersc0542af2014-09-03 16:16:56 -07001977 CHECK(f != nullptr);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001978 mirror::String* s = reinterpret_cast<mirror::String*>(f->GetObject(thread_group));
Sebastien Hertza06430c2014-09-15 19:21:30 +02001979
1980 std::string thread_group_name(s->ToModifiedUtf8());
1981 expandBufAddUtf8String(pReply, thread_group_name);
1982 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001983}
1984
Sebastien Hertza06430c2014-09-15 19:21:30 +02001985JDWP::JdwpError Dbg::GetThreadGroupParent(JDWP::ObjectId thread_group_id, JDWP::ExpandBuf* pReply) {
Ian Rogers98379392014-02-24 16:53:16 -08001986 ScopedObjectAccessUnchecked soa(Thread::Current());
Ian Rogersc0542af2014-09-03 16:16:56 -07001987 JDWP::JdwpError error;
Sebastien Hertza06430c2014-09-15 19:21:30 +02001988 mirror::Object* thread_group = DecodeThreadGroup(soa, thread_group_id, &error);
1989 if (error != JDWP::ERR_NONE) {
1990 return error;
1991 }
Mathieu Chartier2d5f39e2014-09-19 17:52:37 -07001992 mirror::Object* parent;
1993 {
1994 ScopedAssertNoThreadSuspension ants(soa.Self(), "Debugger: GetThreadGroupParent");
Sebastien Hertze49e1952014-10-13 11:27:13 +02001995 mirror::ArtField* f = soa.DecodeField(WellKnownClasses::java_lang_ThreadGroup_parent);
Mathieu Chartier2d5f39e2014-09-19 17:52:37 -07001996 CHECK(f != nullptr);
1997 parent = f->GetObject(thread_group);
1998 }
Sebastien Hertza06430c2014-09-15 19:21:30 +02001999 JDWP::ObjectId parent_group_id = gRegistry->Add(parent);
2000 expandBufAddObjectId(pReply, parent_group_id);
2001 return JDWP::ERR_NONE;
2002}
2003
2004static void GetChildThreadGroups(ScopedObjectAccessUnchecked& soa, mirror::Object* thread_group,
2005 std::vector<JDWP::ObjectId>* child_thread_group_ids)
2006 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
2007 CHECK(thread_group != nullptr);
2008
2009 // Get the ArrayList<ThreadGroup> "groups" out of this thread group...
Sebastien Hertze49e1952014-10-13 11:27:13 +02002010 mirror::ArtField* groups_field = soa.DecodeField(WellKnownClasses::java_lang_ThreadGroup_groups);
Sebastien Hertza06430c2014-09-15 19:21:30 +02002011 mirror::Object* groups_array_list = groups_field->GetObject(thread_group);
Sebastien Hertze49e1952014-10-13 11:27:13 +02002012 {
2013 // The "groups" field is declared as a java.util.List: check it really is
2014 // an instance of java.util.ArrayList.
2015 CHECK(groups_array_list != nullptr);
2016 mirror::Class* java_util_ArrayList_class =
2017 soa.Decode<mirror::Class*>(WellKnownClasses::java_util_ArrayList);
2018 CHECK(groups_array_list->InstanceOf(java_util_ArrayList_class));
2019 }
Sebastien Hertza06430c2014-09-15 19:21:30 +02002020
2021 // Get the array and size out of the ArrayList<ThreadGroup>...
Sebastien Hertze49e1952014-10-13 11:27:13 +02002022 mirror::ArtField* array_field = soa.DecodeField(WellKnownClasses::java_util_ArrayList_array);
2023 mirror::ArtField* size_field = soa.DecodeField(WellKnownClasses::java_util_ArrayList_size);
Sebastien Hertza06430c2014-09-15 19:21:30 +02002024 mirror::ObjectArray<mirror::Object>* groups_array =
2025 array_field->GetObject(groups_array_list)->AsObjectArray<mirror::Object>();
2026 const int32_t size = size_field->GetInt(groups_array_list);
2027
2028 // Copy the first 'size' elements out of the array into the result.
Sebastien Hertz6995c602014-09-09 12:10:13 +02002029 ObjectRegistry* registry = Dbg::GetObjectRegistry();
Sebastien Hertza06430c2014-09-15 19:21:30 +02002030 for (int32_t i = 0; i < size; ++i) {
Sebastien Hertz6995c602014-09-09 12:10:13 +02002031 child_thread_group_ids->push_back(registry->Add(groups_array->Get(i)));
Sebastien Hertza06430c2014-09-15 19:21:30 +02002032 }
2033}
2034
2035JDWP::JdwpError Dbg::GetThreadGroupChildren(JDWP::ObjectId thread_group_id,
2036 JDWP::ExpandBuf* pReply) {
2037 ScopedObjectAccessUnchecked soa(Thread::Current());
2038 JDWP::JdwpError error;
2039 mirror::Object* thread_group = DecodeThreadGroup(soa, thread_group_id, &error);
2040 if (error != JDWP::ERR_NONE) {
2041 return error;
2042 }
2043
2044 // Add child threads.
2045 {
2046 std::vector<JDWP::ObjectId> child_thread_ids;
2047 GetThreads(thread_group, &child_thread_ids);
2048 expandBufAdd4BE(pReply, child_thread_ids.size());
2049 for (JDWP::ObjectId child_thread_id : child_thread_ids) {
2050 expandBufAddObjectId(pReply, child_thread_id);
2051 }
2052 }
2053
2054 // Add child thread groups.
2055 {
2056 std::vector<JDWP::ObjectId> child_thread_groups_ids;
2057 GetChildThreadGroups(soa, thread_group, &child_thread_groups_ids);
2058 expandBufAdd4BE(pReply, child_thread_groups_ids.size());
2059 for (JDWP::ObjectId child_thread_group_id : child_thread_groups_ids) {
2060 expandBufAddObjectId(pReply, child_thread_group_id);
2061 }
2062 }
2063
2064 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002065}
2066
2067JDWP::ObjectId Dbg::GetSystemThreadGroupId() {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002068 ScopedObjectAccessUnchecked soa(Thread::Current());
Brian Carlstromea46f952013-07-30 01:26:50 -07002069 mirror::ArtField* f = soa.DecodeField(WellKnownClasses::java_lang_ThreadGroup_systemThreadGroup);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002070 mirror::Object* group = f->GetObject(f->GetDeclaringClass());
Ian Rogers365c1022012-06-22 15:05:28 -07002071 return gRegistry->Add(group);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002072}
2073
Jeff Hao920af3e2013-08-28 15:46:38 -07002074JDWP::JdwpThreadStatus Dbg::ToJdwpThreadStatus(ThreadState state) {
2075 switch (state) {
2076 case kBlocked:
2077 return JDWP::TS_MONITOR;
2078 case kNative:
2079 case kRunnable:
2080 case kSuspended:
2081 return JDWP::TS_RUNNING;
2082 case kSleeping:
2083 return JDWP::TS_SLEEPING;
2084 case kStarting:
2085 case kTerminated:
2086 return JDWP::TS_ZOMBIE;
2087 case kTimedWaiting:
Sebastien Hertzbae182c2013-12-17 10:42:03 +01002088 case kWaitingForCheckPointsToRun:
Jeff Hao920af3e2013-08-28 15:46:38 -07002089 case kWaitingForDebuggerSend:
2090 case kWaitingForDebuggerSuspension:
2091 case kWaitingForDebuggerToAttach:
Sebastien Hertz138dbfc2013-12-04 18:15:25 +01002092 case kWaitingForDeoptimization:
Jeff Hao920af3e2013-08-28 15:46:38 -07002093 case kWaitingForGcToComplete:
Jeff Hao920af3e2013-08-28 15:46:38 -07002094 case kWaitingForJniOnLoad:
Sebastien Hertzbae182c2013-12-17 10:42:03 +01002095 case kWaitingForMethodTracingStart:
Jeff Hao920af3e2013-08-28 15:46:38 -07002096 case kWaitingForSignalCatcherOutput:
Hiroshi Yamauchi0c8c3032015-01-16 16:54:35 -08002097 case kWaitingForVisitObjects:
Jeff Hao920af3e2013-08-28 15:46:38 -07002098 case kWaitingInMainDebuggerLoop:
2099 case kWaitingInMainSignalCatcherLoop:
2100 case kWaitingPerformingGc:
2101 case kWaiting:
2102 return JDWP::TS_WAIT;
2103 // Don't add a 'default' here so the compiler can spot incompatible enum changes.
2104 }
2105 LOG(FATAL) << "Unknown thread state: " << state;
2106 return JDWP::TS_ZOMBIE;
2107}
2108
Sebastien Hertz52d131d2014-03-13 16:17:40 +01002109JDWP::JdwpError Dbg::GetThreadStatus(JDWP::ObjectId thread_id, JDWP::JdwpThreadStatus* pThreadStatus,
2110 JDWP::JdwpSuspendStatus* pSuspendStatus) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002111 ScopedObjectAccess soa(Thread::Current());
Elliott Hughes499c5132011-11-17 14:55:11 -08002112
Elliott Hughes9e0c1752013-01-09 14:02:58 -08002113 *pSuspendStatus = JDWP::SUSPEND_STATUS_NOT_SUSPENDED;
2114
Ian Rogers50b35e22012-10-04 10:09:15 -07002115 MutexLock mu(soa.Self(), *Locks::thread_list_lock_);
Ian Rogersc0542af2014-09-03 16:16:56 -07002116 JDWP::JdwpError error;
2117 Thread* thread = DecodeThread(soa, thread_id, &error);
Elliott Hughes221229c2013-01-08 18:17:50 -08002118 if (error != JDWP::ERR_NONE) {
2119 if (error == JDWP::ERR_THREAD_NOT_ALIVE) {
2120 *pThreadStatus = JDWP::TS_ZOMBIE;
Elliott Hughes221229c2013-01-08 18:17:50 -08002121 return JDWP::ERR_NONE;
2122 }
2123 return error;
Elliott Hughes499c5132011-11-17 14:55:11 -08002124 }
2125
Elliott Hughes9e0c1752013-01-09 14:02:58 -08002126 if (IsSuspendedForDebugger(soa, thread)) {
2127 *pSuspendStatus = JDWP::SUSPEND_STATUS_SUSPENDED;
Elliott Hughes499c5132011-11-17 14:55:11 -08002128 }
2129
Jeff Hao920af3e2013-08-28 15:46:38 -07002130 *pThreadStatus = ToJdwpThreadStatus(thread->GetState());
Elliott Hughes221229c2013-01-08 18:17:50 -08002131 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002132}
2133
Elliott Hughes221229c2013-01-08 18:17:50 -08002134JDWP::JdwpError Dbg::GetThreadDebugSuspendCount(JDWP::ObjectId thread_id, JDWP::ExpandBuf* pReply) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002135 ScopedObjectAccess soa(Thread::Current());
Ian Rogers50b35e22012-10-04 10:09:15 -07002136 MutexLock mu(soa.Self(), *Locks::thread_list_lock_);
Ian Rogersc0542af2014-09-03 16:16:56 -07002137 JDWP::JdwpError error;
2138 Thread* thread = DecodeThread(soa, thread_id, &error);
Elliott Hughes221229c2013-01-08 18:17:50 -08002139 if (error != JDWP::ERR_NONE) {
2140 return error;
Elliott Hughes2435a572012-02-17 16:07:41 -08002141 }
Ian Rogers50b35e22012-10-04 10:09:15 -07002142 MutexLock mu2(soa.Self(), *Locks::thread_suspend_count_lock_);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002143 expandBufAdd4BE(pReply, thread->GetDebugSuspendCount());
Elliott Hughes2435a572012-02-17 16:07:41 -08002144 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002145}
2146
Elliott Hughesf9501702013-01-11 11:22:27 -08002147JDWP::JdwpError Dbg::Interrupt(JDWP::ObjectId thread_id) {
2148 ScopedObjectAccess soa(Thread::Current());
2149 MutexLock mu(soa.Self(), *Locks::thread_list_lock_);
Ian Rogersc0542af2014-09-03 16:16:56 -07002150 JDWP::JdwpError error;
2151 Thread* thread = DecodeThread(soa, thread_id, &error);
Elliott Hughesf9501702013-01-11 11:22:27 -08002152 if (error != JDWP::ERR_NONE) {
2153 return error;
2154 }
Ian Rogersdd7624d2014-03-14 17:43:00 -07002155 thread->Interrupt(soa.Self());
Elliott Hughesf9501702013-01-11 11:22:27 -08002156 return JDWP::ERR_NONE;
2157}
2158
Sebastien Hertz070f7322014-09-09 12:08:49 +02002159static bool IsInDesiredThreadGroup(ScopedObjectAccessUnchecked& soa,
2160 mirror::Object* desired_thread_group, mirror::Object* peer)
2161 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
2162 // Do we want threads from all thread groups?
2163 if (desired_thread_group == nullptr) {
2164 return true;
2165 }
2166 mirror::ArtField* thread_group_field = soa.DecodeField(WellKnownClasses::java_lang_Thread_group);
2167 DCHECK(thread_group_field != nullptr);
2168 mirror::Object* group = thread_group_field->GetObject(peer);
2169 return (group == desired_thread_group);
2170}
2171
Sebastien Hertza06430c2014-09-15 19:21:30 +02002172void Dbg::GetThreads(mirror::Object* thread_group, std::vector<JDWP::ObjectId>* thread_ids) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002173 ScopedObjectAccessUnchecked soa(Thread::Current());
Sebastien Hertz070f7322014-09-09 12:08:49 +02002174 std::list<Thread*> all_threads_list;
2175 {
2176 MutexLock mu(Thread::Current(), *Locks::thread_list_lock_);
2177 all_threads_list = Runtime::Current()->GetThreadList()->GetList();
2178 }
2179 for (Thread* t : all_threads_list) {
2180 if (t == Dbg::GetDebugThread()) {
2181 // Skip the JDWP thread. Some debuggers get bent out of shape when they can't suspend and
2182 // query all threads, so it's easier if we just don't tell them about this thread.
2183 continue;
2184 }
2185 if (t->IsStillStarting()) {
2186 // This thread is being started (and has been registered in the thread list). However, it is
2187 // not completely started yet so we must ignore it.
2188 continue;
2189 }
2190 mirror::Object* peer = t->GetPeer();
2191 if (peer == nullptr) {
2192 // peer might be NULL if the thread is still starting up. We can't tell the debugger about
2193 // this thread yet.
2194 // TODO: if we identified threads to the debugger by their Thread*
2195 // rather than their peer's mirror::Object*, we could fix this.
2196 // Doing so might help us report ZOMBIE threads too.
2197 continue;
2198 }
2199 if (IsInDesiredThreadGroup(soa, thread_group, peer)) {
2200 thread_ids->push_back(gRegistry->Add(peer));
2201 }
2202 }
Elliott Hughescaf76542012-06-28 16:08:22 -07002203}
Elliott Hughesa2155262011-11-16 16:26:58 -08002204
Ian Rogersc0542af2014-09-03 16:16:56 -07002205static int GetStackDepth(Thread* thread) SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Ian Rogers0399dde2012-06-06 17:09:28 -07002206 struct CountStackDepthVisitor : public StackVisitor {
Andreas Gampe277ccbd2014-11-03 21:36:10 -08002207 explicit CountStackDepthVisitor(Thread* thread_in)
2208 : StackVisitor(thread_in, nullptr), depth(0) {}
Ian Rogers0399dde2012-06-06 17:09:28 -07002209
Elliott Hughes64f574f2013-02-20 14:57:12 -08002210 // TODO: Enable annotalysis. We know lock is held in constructor, but abstraction confuses
2211 // annotalysis.
2212 bool VisitFrame() NO_THREAD_SAFETY_ANALYSIS {
Ian Rogers0399dde2012-06-06 17:09:28 -07002213 if (!GetMethod()->IsRuntimeMethod()) {
Elliott Hughesf8a2df72011-12-01 12:19:54 -08002214 ++depth;
2215 }
Elliott Hughes530fa002012-03-12 11:44:49 -07002216 return true;
Elliott Hughesa2e54f62011-11-17 13:01:30 -08002217 }
2218 size_t depth;
2219 };
Elliott Hughes08fc03a2012-06-26 17:34:00 -07002220
Ian Rogers7a22fa62013-01-23 12:16:16 -08002221 CountStackDepthVisitor visitor(thread);
Ian Rogers0399dde2012-06-06 17:09:28 -07002222 visitor.WalkStack();
Elliott Hughesa2e54f62011-11-17 13:01:30 -08002223 return visitor.depth;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002224}
2225
Ian Rogersc0542af2014-09-03 16:16:56 -07002226JDWP::JdwpError Dbg::GetThreadFrameCount(JDWP::ObjectId thread_id, size_t* result) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002227 ScopedObjectAccess soa(Thread::Current());
jeffhaoa77f0f62012-12-05 17:19:31 -08002228 MutexLock mu(soa.Self(), *Locks::thread_list_lock_);
Ian Rogersc0542af2014-09-03 16:16:56 -07002229 JDWP::JdwpError error;
2230 *result = 0;
2231 Thread* thread = DecodeThread(soa, thread_id, &error);
Elliott Hughes221229c2013-01-08 18:17:50 -08002232 if (error != JDWP::ERR_NONE) {
2233 return error;
2234 }
Elliott Hughesf15f4a02013-01-09 10:09:38 -08002235 if (!IsSuspendedForDebugger(soa, thread)) {
2236 return JDWP::ERR_THREAD_NOT_SUSPENDED;
2237 }
Ian Rogersc0542af2014-09-03 16:16:56 -07002238 *result = GetStackDepth(thread);
Elliott Hughes221229c2013-01-08 18:17:50 -08002239 return JDWP::ERR_NONE;
Elliott Hughes86964332012-02-15 19:37:42 -08002240}
2241
Ian Rogers306057f2012-11-26 12:45:53 -08002242JDWP::JdwpError Dbg::GetThreadFrames(JDWP::ObjectId thread_id, size_t start_frame,
2243 size_t frame_count, JDWP::ExpandBuf* buf) {
Elliott Hughes6e9d22c2012-06-22 15:02:37 -07002244 class GetFrameVisitor : public StackVisitor {
2245 public:
Andreas Gampe277ccbd2014-11-03 21:36:10 -08002246 GetFrameVisitor(Thread* thread, size_t start_frame_in, size_t frame_count_in,
2247 JDWP::ExpandBuf* buf_in)
Ian Rogersb726dcb2012-09-05 08:57:23 -07002248 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_)
Ian Rogersc0542af2014-09-03 16:16:56 -07002249 : StackVisitor(thread, nullptr), depth_(0),
Andreas Gampe277ccbd2014-11-03 21:36:10 -08002250 start_frame_(start_frame_in), frame_count_(frame_count_in), buf_(buf_in) {
Elliott Hughes6e9d22c2012-06-22 15:02:37 -07002251 expandBufAdd4BE(buf_, frame_count_);
Elliott Hughes03181a82011-11-17 17:22:21 -08002252 }
Ian Rogers0399dde2012-06-06 17:09:28 -07002253
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002254 // TODO: Enable annotalysis. We know lock is held in constructor, but abstraction confuses
2255 // annotalysis.
2256 virtual bool VisitFrame() NO_THREAD_SAFETY_ANALYSIS {
Ian Rogers0399dde2012-06-06 17:09:28 -07002257 if (GetMethod()->IsRuntimeMethod()) {
Brian Carlstrom7934ac22013-07-26 10:54:15 -07002258 return true; // The debugger can't do anything useful with a frame that has no Method*.
Elliott Hughes03181a82011-11-17 17:22:21 -08002259 }
Elliott Hughes6e9d22c2012-06-22 15:02:37 -07002260 if (depth_ >= start_frame_ + frame_count_) {
Elliott Hughes530fa002012-03-12 11:44:49 -07002261 return false;
Elliott Hughes03181a82011-11-17 17:22:21 -08002262 }
Elliott Hughes6e9d22c2012-06-22 15:02:37 -07002263 if (depth_ >= start_frame_) {
2264 JDWP::FrameId frame_id(GetFrameId());
2265 JDWP::JdwpLocation location;
Sebastien Hertz6995c602014-09-09 12:10:13 +02002266 SetJdwpLocation(&location, GetMethod(), GetDexPc());
Ian Rogersef7d42f2014-01-06 12:55:46 -08002267 VLOG(jdwp) << StringPrintf(" Frame %3zd: id=%3" PRIu64 " ", depth_, frame_id) << location;
Elliott Hughes6e9d22c2012-06-22 15:02:37 -07002268 expandBufAdd8BE(buf_, frame_id);
2269 expandBufAddLocation(buf_, location);
2270 }
2271 ++depth_;
Elliott Hughes530fa002012-03-12 11:44:49 -07002272 return true;
Elliott Hughes03181a82011-11-17 17:22:21 -08002273 }
Elliott Hughes6e9d22c2012-06-22 15:02:37 -07002274
2275 private:
2276 size_t depth_;
2277 const size_t start_frame_;
2278 const size_t frame_count_;
2279 JDWP::ExpandBuf* buf_;
Elliott Hughes03181a82011-11-17 17:22:21 -08002280 };
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002281
2282 ScopedObjectAccessUnchecked soa(Thread::Current());
jeffhaoa77f0f62012-12-05 17:19:31 -08002283 MutexLock mu(soa.Self(), *Locks::thread_list_lock_);
Ian Rogersc0542af2014-09-03 16:16:56 -07002284 JDWP::JdwpError error;
2285 Thread* thread = DecodeThread(soa, thread_id, &error);
Elliott Hughes221229c2013-01-08 18:17:50 -08002286 if (error != JDWP::ERR_NONE) {
2287 return error;
2288 }
Elliott Hughesf15f4a02013-01-09 10:09:38 -08002289 if (!IsSuspendedForDebugger(soa, thread)) {
2290 return JDWP::ERR_THREAD_NOT_SUSPENDED;
2291 }
Ian Rogers7a22fa62013-01-23 12:16:16 -08002292 GetFrameVisitor visitor(thread, start_frame, frame_count, buf);
Ian Rogers0399dde2012-06-06 17:09:28 -07002293 visitor.WalkStack();
Elliott Hughes6e9d22c2012-06-22 15:02:37 -07002294 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002295}
2296
2297JDWP::ObjectId Dbg::GetThreadSelfId() {
Sebastien Hertz6995c602014-09-09 12:10:13 +02002298 return GetThreadId(Thread::Current());
2299}
2300
2301JDWP::ObjectId Dbg::GetThreadId(Thread* thread) {
Mathieu Chartierdbe6f462012-09-25 16:54:50 -07002302 ScopedObjectAccessUnchecked soa(Thread::Current());
Sebastien Hertz6995c602014-09-09 12:10:13 +02002303 return gRegistry->Add(thread->GetPeer());
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002304}
2305
Elliott Hughes475fc232011-10-25 15:00:35 -07002306void Dbg::SuspendVM() {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002307 Runtime::Current()->GetThreadList()->SuspendAllForDebugger();
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002308}
2309
2310void Dbg::ResumeVM() {
Sebastien Hertz253fa552014-10-14 17:27:15 +02002311 Runtime::Current()->GetThreadList()->ResumeAllForDebugger();
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002312}
2313
Elliott Hughes221229c2013-01-08 18:17:50 -08002314JDWP::JdwpError Dbg::SuspendThread(JDWP::ObjectId thread_id, bool request_suspension) {
Ian Rogersf3d874c2014-07-17 18:52:42 -07002315 Thread* self = Thread::Current();
Ian Rogersc0542af2014-09-03 16:16:56 -07002316 ScopedLocalRef<jobject> peer(self->GetJniEnv(), nullptr);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002317 {
Ian Rogersf3d874c2014-07-17 18:52:42 -07002318 ScopedObjectAccess soa(self);
Ian Rogersc0542af2014-09-03 16:16:56 -07002319 JDWP::JdwpError error;
2320 peer.reset(soa.AddLocalReference<jobject>(gRegistry->Get<mirror::Object*>(thread_id, &error)));
Elliott Hughes4e235312011-12-02 11:34:15 -08002321 }
Ian Rogersc0542af2014-09-03 16:16:56 -07002322 if (peer.get() == nullptr) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002323 return JDWP::ERR_THREAD_NOT_ALIVE;
2324 }
Ian Rogers4ad5cd32014-11-11 23:08:07 -08002325 // Suspend thread to build stack trace.
Elliott Hughesf327e072013-01-09 16:01:26 -08002326 bool timed_out;
Brian Carlstromba32de42014-08-27 23:43:46 -07002327 ThreadList* thread_list = Runtime::Current()->GetThreadList();
2328 Thread* thread = thread_list->SuspendThreadByPeer(peer.get(), request_suspension, true,
2329 &timed_out);
Ian Rogersc0542af2014-09-03 16:16:56 -07002330 if (thread != nullptr) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002331 return JDWP::ERR_NONE;
Elliott Hughesf327e072013-01-09 16:01:26 -08002332 } else if (timed_out) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002333 return JDWP::ERR_INTERNAL;
2334 } else {
2335 return JDWP::ERR_THREAD_NOT_ALIVE;
2336 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002337}
2338
Elliott Hughes221229c2013-01-08 18:17:50 -08002339void Dbg::ResumeThread(JDWP::ObjectId thread_id) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002340 ScopedObjectAccessUnchecked soa(Thread::Current());
Ian Rogersc0542af2014-09-03 16:16:56 -07002341 JDWP::JdwpError error;
2342 mirror::Object* peer = gRegistry->Get<mirror::Object*>(thread_id, &error);
2343 CHECK(peer != nullptr) << error;
jeffhaoa77f0f62012-12-05 17:19:31 -08002344 Thread* thread;
2345 {
2346 MutexLock mu(soa.Self(), *Locks::thread_list_lock_);
2347 thread = Thread::FromManagedThread(soa, peer);
2348 }
Ian Rogersc0542af2014-09-03 16:16:56 -07002349 if (thread == nullptr) {
Elliott Hughes4e235312011-12-02 11:34:15 -08002350 LOG(WARNING) << "No such thread for resume: " << peer;
2351 return;
2352 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002353 bool needs_resume;
2354 {
Ian Rogers50b35e22012-10-04 10:09:15 -07002355 MutexLock mu2(soa.Self(), *Locks::thread_suspend_count_lock_);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002356 needs_resume = thread->GetSuspendCount() > 0;
2357 }
2358 if (needs_resume) {
Elliott Hughes546b9862012-06-20 16:06:13 -07002359 Runtime::Current()->GetThreadList()->Resume(thread, true);
2360 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002361}
2362
2363void Dbg::SuspendSelf() {
Elliott Hughes475fc232011-10-25 15:00:35 -07002364 Runtime::Current()->GetThreadList()->SuspendSelfForDebugger();
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002365}
2366
Ian Rogers0399dde2012-06-06 17:09:28 -07002367struct GetThisVisitor : public StackVisitor {
Andreas Gampe277ccbd2014-11-03 21:36:10 -08002368 GetThisVisitor(Thread* thread, Context* context, JDWP::FrameId frame_id_in)
Ian Rogersb726dcb2012-09-05 08:57:23 -07002369 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_)
Andreas Gampe277ccbd2014-11-03 21:36:10 -08002370 : StackVisitor(thread, context), this_object(nullptr), frame_id(frame_id_in) {}
Ian Rogers0399dde2012-06-06 17:09:28 -07002371
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002372 // TODO: Enable annotalysis. We know lock is held in constructor, but abstraction confuses
2373 // annotalysis.
2374 virtual bool VisitFrame() NO_THREAD_SAFETY_ANALYSIS {
Elliott Hughes6e9d22c2012-06-22 15:02:37 -07002375 if (frame_id != GetFrameId()) {
Ian Rogers0399dde2012-06-06 17:09:28 -07002376 return true; // continue
Ian Rogers0399dde2012-06-06 17:09:28 -07002377 } else {
Ian Rogers62d6c772013-02-27 08:32:07 -08002378 this_object = GetThisObject();
2379 return false;
Ian Rogers0399dde2012-06-06 17:09:28 -07002380 }
Elliott Hughes86b00102011-12-05 17:54:26 -08002381 }
Ian Rogers0399dde2012-06-06 17:09:28 -07002382
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002383 mirror::Object* this_object;
Elliott Hughes6e9d22c2012-06-22 15:02:37 -07002384 JDWP::FrameId frame_id;
Ian Rogers0399dde2012-06-06 17:09:28 -07002385};
2386
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002387JDWP::JdwpError Dbg::GetThisObject(JDWP::ObjectId thread_id, JDWP::FrameId frame_id,
2388 JDWP::ObjectId* result) {
2389 ScopedObjectAccessUnchecked soa(Thread::Current());
2390 Thread* thread;
2391 {
Ian Rogers50b35e22012-10-04 10:09:15 -07002392 MutexLock mu(soa.Self(), *Locks::thread_list_lock_);
Ian Rogersc0542af2014-09-03 16:16:56 -07002393 JDWP::JdwpError error;
2394 thread = DecodeThread(soa, thread_id, &error);
Elliott Hughes221229c2013-01-08 18:17:50 -08002395 if (error != JDWP::ERR_NONE) {
2396 return error;
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002397 }
Elliott Hughes9e0c1752013-01-09 14:02:58 -08002398 if (!IsSuspendedForDebugger(soa, thread)) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002399 return JDWP::ERR_THREAD_NOT_SUSPENDED;
2400 }
Elliott Hughes6e9d22c2012-06-22 15:02:37 -07002401 }
Ian Rogers700a4022014-05-19 16:49:03 -07002402 std::unique_ptr<Context> context(Context::Create());
Ian Rogers7a22fa62013-01-23 12:16:16 -08002403 GetThisVisitor visitor(thread, context.get(), frame_id);
Ian Rogers0399dde2012-06-06 17:09:28 -07002404 visitor.WalkStack();
Elliott Hughes6e9d22c2012-06-22 15:02:37 -07002405 *result = gRegistry->Add(visitor.this_object);
2406 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002407}
2408
Sebastien Hertz8009f392014-09-01 17:07:11 +02002409// Walks the stack until we find the frame with the given FrameId.
2410class FindFrameVisitor FINAL : public StackVisitor {
2411 public:
2412 FindFrameVisitor(Thread* thread, Context* context, JDWP::FrameId frame_id)
2413 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_)
2414 : StackVisitor(thread, context), frame_id_(frame_id), error_(JDWP::ERR_INVALID_FRAMEID) {}
Ian Rogersca190662012-06-26 15:45:57 -07002415
Sebastien Hertz8009f392014-09-01 17:07:11 +02002416 // TODO: Enable annotalysis. We know lock is held in constructor, but abstraction confuses
2417 // annotalysis.
2418 bool VisitFrame() NO_THREAD_SAFETY_ANALYSIS {
2419 if (GetFrameId() != frame_id_) {
2420 return true; // Not our frame, carry on.
Ian Rogers0399dde2012-06-06 17:09:28 -07002421 }
Sebastien Hertz8009f392014-09-01 17:07:11 +02002422 mirror::ArtMethod* m = GetMethod();
2423 if (m->IsNative()) {
2424 // We can't read/write local value from/into native method.
2425 error_ = JDWP::ERR_OPAQUE_FRAME;
2426 } else {
2427 // We found our frame.
2428 error_ = JDWP::ERR_NONE;
2429 }
2430 return false;
2431 }
2432
2433 JDWP::JdwpError GetError() const {
2434 return error_;
2435 }
2436
2437 private:
2438 const JDWP::FrameId frame_id_;
2439 JDWP::JdwpError error_;
2440};
2441
2442JDWP::JdwpError Dbg::GetLocalValues(JDWP::Request* request, JDWP::ExpandBuf* pReply) {
2443 JDWP::ObjectId thread_id = request->ReadThreadId();
2444 JDWP::FrameId frame_id = request->ReadFrameId();
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002445
2446 ScopedObjectAccessUnchecked soa(Thread::Current());
Sebastien Hertz8009f392014-09-01 17:07:11 +02002447 Thread* thread;
2448 {
2449 MutexLock mu(soa.Self(), *Locks::thread_list_lock_);
2450 JDWP::JdwpError error;
2451 thread = DecodeThread(soa, thread_id, &error);
2452 if (error != JDWP::ERR_NONE) {
2453 return error;
2454 }
Elliott Hughes221229c2013-01-08 18:17:50 -08002455 }
Sebastien Hertz8009f392014-09-01 17:07:11 +02002456 // Find the frame with the given frame_id.
Ian Rogers700a4022014-05-19 16:49:03 -07002457 std::unique_ptr<Context> context(Context::Create());
Sebastien Hertz8009f392014-09-01 17:07:11 +02002458 FindFrameVisitor visitor(thread, context.get(), frame_id);
Ian Rogers0399dde2012-06-06 17:09:28 -07002459 visitor.WalkStack();
Sebastien Hertz8009f392014-09-01 17:07:11 +02002460 if (visitor.GetError() != JDWP::ERR_NONE) {
2461 return visitor.GetError();
2462 }
2463
2464 // Read the values from visitor's context.
2465 int32_t slot_count = request->ReadSigned32("slot count");
2466 expandBufAdd4BE(pReply, slot_count); /* "int values" */
2467 for (int32_t i = 0; i < slot_count; ++i) {
2468 uint32_t slot = request->ReadUnsigned32("slot");
2469 JDWP::JdwpTag reqSigByte = request->ReadTag();
2470
2471 VLOG(jdwp) << " --> slot " << slot << " " << reqSigByte;
2472
2473 size_t width = Dbg::GetTagWidth(reqSigByte);
Sebastien Hertz7d955652014-10-22 10:57:10 +02002474 uint8_t* ptr = expandBufAddSpace(pReply, width + 1);
Sebastien Hertz8009f392014-09-01 17:07:11 +02002475 JDWP::JdwpError error = Dbg::GetLocalValue(visitor, soa, slot, reqSigByte, ptr, width);
2476 if (error != JDWP::ERR_NONE) {
2477 return error;
2478 }
2479 }
2480 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002481}
2482
Sebastien Hertz8009f392014-09-01 17:07:11 +02002483JDWP::JdwpError Dbg::GetLocalValue(const StackVisitor& visitor, ScopedObjectAccessUnchecked& soa,
2484 int slot, JDWP::JdwpTag tag, uint8_t* buf, size_t width) {
2485 mirror::ArtMethod* m = visitor.GetMethod();
2486 uint16_t reg = DemangleSlot(slot, m);
2487 // TODO: check that the tag is compatible with the actual type of the slot!
2488 // TODO: check slot is valid for this method or return INVALID_SLOT error.
2489 constexpr JDWP::JdwpError kFailureErrorCode = JDWP::ERR_ABSENT_INFORMATION;
2490 switch (tag) {
2491 case JDWP::JT_BOOLEAN: {
2492 CHECK_EQ(width, 1U);
2493 uint32_t intVal;
2494 if (visitor.GetVReg(m, reg, kIntVReg, &intVal)) {
2495 VLOG(jdwp) << "get boolean local " << reg << " = " << intVal;
2496 JDWP::Set1(buf + 1, intVal != 0);
2497 } else {
2498 VLOG(jdwp) << "failed to get boolean local " << reg;
2499 return kFailureErrorCode;
Ian Rogers0399dde2012-06-06 17:09:28 -07002500 }
Sebastien Hertz8009f392014-09-01 17:07:11 +02002501 break;
Ian Rogers0399dde2012-06-06 17:09:28 -07002502 }
Sebastien Hertz8009f392014-09-01 17:07:11 +02002503 case JDWP::JT_BYTE: {
2504 CHECK_EQ(width, 1U);
2505 uint32_t intVal;
2506 if (visitor.GetVReg(m, reg, kIntVReg, &intVal)) {
2507 VLOG(jdwp) << "get byte local " << reg << " = " << intVal;
2508 JDWP::Set1(buf + 1, intVal);
2509 } else {
2510 VLOG(jdwp) << "failed to get byte local " << reg;
2511 return kFailureErrorCode;
2512 }
2513 break;
2514 }
2515 case JDWP::JT_SHORT:
2516 case JDWP::JT_CHAR: {
2517 CHECK_EQ(width, 2U);
2518 uint32_t intVal;
2519 if (visitor.GetVReg(m, reg, kIntVReg, &intVal)) {
2520 VLOG(jdwp) << "get short/char local " << reg << " = " << intVal;
2521 JDWP::Set2BE(buf + 1, intVal);
2522 } else {
2523 VLOG(jdwp) << "failed to get short/char local " << reg;
2524 return kFailureErrorCode;
2525 }
2526 break;
2527 }
2528 case JDWP::JT_INT: {
2529 CHECK_EQ(width, 4U);
2530 uint32_t intVal;
2531 if (visitor.GetVReg(m, reg, kIntVReg, &intVal)) {
2532 VLOG(jdwp) << "get int local " << reg << " = " << intVal;
2533 JDWP::Set4BE(buf + 1, intVal);
2534 } else {
2535 VLOG(jdwp) << "failed to get int local " << reg;
2536 return kFailureErrorCode;
2537 }
2538 break;
2539 }
2540 case JDWP::JT_FLOAT: {
2541 CHECK_EQ(width, 4U);
2542 uint32_t intVal;
2543 if (visitor.GetVReg(m, reg, kFloatVReg, &intVal)) {
2544 VLOG(jdwp) << "get float local " << reg << " = " << intVal;
2545 JDWP::Set4BE(buf + 1, intVal);
2546 } else {
2547 VLOG(jdwp) << "failed to get float local " << reg;
2548 return kFailureErrorCode;
2549 }
2550 break;
2551 }
2552 case JDWP::JT_ARRAY:
2553 case JDWP::JT_CLASS_LOADER:
2554 case JDWP::JT_CLASS_OBJECT:
2555 case JDWP::JT_OBJECT:
2556 case JDWP::JT_STRING:
2557 case JDWP::JT_THREAD:
2558 case JDWP::JT_THREAD_GROUP: {
2559 CHECK_EQ(width, sizeof(JDWP::ObjectId));
2560 uint32_t intVal;
2561 if (visitor.GetVReg(m, reg, kReferenceVReg, &intVal)) {
2562 mirror::Object* o = reinterpret_cast<mirror::Object*>(intVal);
2563 VLOG(jdwp) << "get " << tag << " object local " << reg << " = " << o;
2564 if (!Runtime::Current()->GetHeap()->IsValidObjectAddress(o)) {
2565 LOG(FATAL) << "Register " << reg << " expected to hold " << tag << " object: " << o;
2566 }
2567 tag = TagFromObject(soa, o);
2568 JDWP::SetObjectId(buf + 1, gRegistry->Add(o));
2569 } else {
2570 VLOG(jdwp) << "failed to get " << tag << " object local " << reg;
2571 return kFailureErrorCode;
2572 }
2573 break;
2574 }
2575 case JDWP::JT_DOUBLE: {
2576 CHECK_EQ(width, 8U);
2577 uint64_t longVal;
2578 if (visitor.GetVRegPair(m, reg, kDoubleLoVReg, kDoubleHiVReg, &longVal)) {
2579 VLOG(jdwp) << "get double local " << reg << " = " << longVal;
2580 JDWP::Set8BE(buf + 1, longVal);
2581 } else {
2582 VLOG(jdwp) << "failed to get double local " << reg;
2583 return kFailureErrorCode;
2584 }
2585 break;
2586 }
2587 case JDWP::JT_LONG: {
2588 CHECK_EQ(width, 8U);
2589 uint64_t longVal;
2590 if (visitor.GetVRegPair(m, reg, kLongLoVReg, kLongHiVReg, &longVal)) {
2591 VLOG(jdwp) << "get long local " << reg << " = " << longVal;
2592 JDWP::Set8BE(buf + 1, longVal);
2593 } else {
2594 VLOG(jdwp) << "failed to get long local " << reg;
2595 return kFailureErrorCode;
2596 }
2597 break;
2598 }
2599 default:
2600 LOG(FATAL) << "Unknown tag " << tag;
2601 break;
2602 }
Ian Rogers0399dde2012-06-06 17:09:28 -07002603
Sebastien Hertz8009f392014-09-01 17:07:11 +02002604 // Prepend tag, which may have been updated.
2605 JDWP::Set1(buf, tag);
2606 return JDWP::ERR_NONE;
2607}
2608
2609JDWP::JdwpError Dbg::SetLocalValues(JDWP::Request* request) {
2610 JDWP::ObjectId thread_id = request->ReadThreadId();
2611 JDWP::FrameId frame_id = request->ReadFrameId();
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002612
2613 ScopedObjectAccessUnchecked soa(Thread::Current());
Sebastien Hertz8009f392014-09-01 17:07:11 +02002614 Thread* thread;
2615 {
2616 MutexLock mu(soa.Self(), *Locks::thread_list_lock_);
2617 JDWP::JdwpError error;
2618 thread = DecodeThread(soa, thread_id, &error);
2619 if (error != JDWP::ERR_NONE) {
2620 return error;
2621 }
Elliott Hughes221229c2013-01-08 18:17:50 -08002622 }
Sebastien Hertz8009f392014-09-01 17:07:11 +02002623 // Find the frame with the given frame_id.
Ian Rogers700a4022014-05-19 16:49:03 -07002624 std::unique_ptr<Context> context(Context::Create());
Sebastien Hertz8009f392014-09-01 17:07:11 +02002625 FindFrameVisitor visitor(thread, context.get(), frame_id);
Ian Rogers0399dde2012-06-06 17:09:28 -07002626 visitor.WalkStack();
Sebastien Hertz8009f392014-09-01 17:07:11 +02002627 if (visitor.GetError() != JDWP::ERR_NONE) {
2628 return visitor.GetError();
2629 }
2630
2631 // Writes the values into visitor's context.
2632 int32_t slot_count = request->ReadSigned32("slot count");
2633 for (int32_t i = 0; i < slot_count; ++i) {
2634 uint32_t slot = request->ReadUnsigned32("slot");
2635 JDWP::JdwpTag sigByte = request->ReadTag();
2636 size_t width = Dbg::GetTagWidth(sigByte);
2637 uint64_t value = request->ReadValue(width);
2638
2639 VLOG(jdwp) << " --> slot " << slot << " " << sigByte << " " << value;
2640 JDWP::JdwpError error = Dbg::SetLocalValue(visitor, slot, sigByte, value, width);
2641 if (error != JDWP::ERR_NONE) {
2642 return error;
2643 }
2644 }
2645 return JDWP::ERR_NONE;
2646}
2647
2648JDWP::JdwpError Dbg::SetLocalValue(StackVisitor& visitor, int slot, JDWP::JdwpTag tag,
2649 uint64_t value, size_t width) {
2650 mirror::ArtMethod* m = visitor.GetMethod();
2651 uint16_t reg = DemangleSlot(slot, m);
2652 // TODO: check that the tag is compatible with the actual type of the slot!
2653 // TODO: check slot is valid for this method or return INVALID_SLOT error.
2654 constexpr JDWP::JdwpError kFailureErrorCode = JDWP::ERR_ABSENT_INFORMATION;
2655 switch (tag) {
2656 case JDWP::JT_BOOLEAN:
2657 case JDWP::JT_BYTE:
2658 CHECK_EQ(width, 1U);
2659 if (!visitor.SetVReg(m, reg, static_cast<uint32_t>(value), kIntVReg)) {
2660 VLOG(jdwp) << "failed to set boolean/byte local " << reg << " = "
2661 << static_cast<uint32_t>(value);
2662 return kFailureErrorCode;
2663 }
2664 break;
2665 case JDWP::JT_SHORT:
2666 case JDWP::JT_CHAR:
2667 CHECK_EQ(width, 2U);
2668 if (!visitor.SetVReg(m, reg, static_cast<uint32_t>(value), kIntVReg)) {
2669 VLOG(jdwp) << "failed to set short/char local " << reg << " = "
2670 << static_cast<uint32_t>(value);
2671 return kFailureErrorCode;
2672 }
2673 break;
2674 case JDWP::JT_INT:
2675 CHECK_EQ(width, 4U);
2676 if (!visitor.SetVReg(m, reg, static_cast<uint32_t>(value), kIntVReg)) {
2677 VLOG(jdwp) << "failed to set int local " << reg << " = "
2678 << static_cast<uint32_t>(value);
2679 return kFailureErrorCode;
2680 }
2681 break;
2682 case JDWP::JT_FLOAT:
2683 CHECK_EQ(width, 4U);
2684 if (!visitor.SetVReg(m, reg, static_cast<uint32_t>(value), kFloatVReg)) {
2685 VLOG(jdwp) << "failed to set float local " << reg << " = "
2686 << static_cast<uint32_t>(value);
2687 return kFailureErrorCode;
2688 }
2689 break;
2690 case JDWP::JT_ARRAY:
2691 case JDWP::JT_CLASS_LOADER:
2692 case JDWP::JT_CLASS_OBJECT:
2693 case JDWP::JT_OBJECT:
2694 case JDWP::JT_STRING:
2695 case JDWP::JT_THREAD:
2696 case JDWP::JT_THREAD_GROUP: {
2697 CHECK_EQ(width, sizeof(JDWP::ObjectId));
2698 JDWP::JdwpError error;
2699 mirror::Object* o = gRegistry->Get<mirror::Object*>(static_cast<JDWP::ObjectId>(value),
2700 &error);
2701 if (error != JDWP::ERR_NONE) {
2702 VLOG(jdwp) << tag << " object " << o << " is an invalid object";
2703 return JDWP::ERR_INVALID_OBJECT;
2704 } else if (!visitor.SetVReg(m, reg, static_cast<uint32_t>(reinterpret_cast<uintptr_t>(o)),
2705 kReferenceVReg)) {
2706 VLOG(jdwp) << "failed to set " << tag << " object local " << reg << " = " << o;
2707 return kFailureErrorCode;
2708 }
2709 break;
2710 }
2711 case JDWP::JT_DOUBLE: {
2712 CHECK_EQ(width, 8U);
2713 if (!visitor.SetVRegPair(m, reg, value, kDoubleLoVReg, kDoubleHiVReg)) {
2714 VLOG(jdwp) << "failed to set double local " << reg << " = " << value;
2715 return kFailureErrorCode;
2716 }
2717 break;
2718 }
2719 case JDWP::JT_LONG: {
2720 CHECK_EQ(width, 8U);
2721 if (!visitor.SetVRegPair(m, reg, value, kLongLoVReg, kLongHiVReg)) {
2722 VLOG(jdwp) << "failed to set double local " << reg << " = " << value;
2723 return kFailureErrorCode;
2724 }
2725 break;
2726 }
2727 default:
2728 LOG(FATAL) << "Unknown tag " << tag;
2729 break;
2730 }
2731 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002732}
2733
Sebastien Hertz6995c602014-09-09 12:10:13 +02002734static void SetEventLocation(JDWP::EventLocation* location, mirror::ArtMethod* m, uint32_t dex_pc)
2735 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
2736 DCHECK(location != nullptr);
2737 if (m == nullptr) {
2738 memset(location, 0, sizeof(*location));
2739 } else {
2740 location->method = m;
2741 location->dex_pc = (m->IsNative() || m->IsProxyMethod()) ? static_cast<uint32_t>(-1) : dex_pc;
Sebastien Hertz3f52eaf2014-04-04 17:50:18 +02002742 }
Sebastien Hertz3f52eaf2014-04-04 17:50:18 +02002743}
2744
Ian Rogersef7d42f2014-01-06 12:55:46 -08002745void Dbg::PostLocationEvent(mirror::ArtMethod* m, int dex_pc, mirror::Object* this_object,
Jeff Hao579b0242013-11-18 13:16:49 -08002746 int event_flags, const JValue* return_value) {
Sebastien Hertz3f52eaf2014-04-04 17:50:18 +02002747 if (!IsDebuggerActive()) {
2748 return;
2749 }
2750 DCHECK(m != nullptr);
2751 DCHECK_EQ(m->IsStatic(), this_object == nullptr);
Sebastien Hertz6995c602014-09-09 12:10:13 +02002752 JDWP::EventLocation location;
2753 SetEventLocation(&location, m, dex_pc);
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08002754
Sebastien Hertz6995c602014-09-09 12:10:13 +02002755 gJdwpState->PostLocationEvent(&location, this_object, event_flags, return_value);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002756}
2757
Sebastien Hertz3f52eaf2014-04-04 17:50:18 +02002758void Dbg::PostFieldAccessEvent(mirror::ArtMethod* m, int dex_pc,
2759 mirror::Object* this_object, mirror::ArtField* f) {
2760 if (!IsDebuggerActive()) {
2761 return;
2762 }
2763 DCHECK(m != nullptr);
2764 DCHECK(f != nullptr);
Sebastien Hertz6995c602014-09-09 12:10:13 +02002765 JDWP::EventLocation location;
2766 SetEventLocation(&location, m, dex_pc);
Sebastien Hertz3f52eaf2014-04-04 17:50:18 +02002767
Sebastien Hertz6995c602014-09-09 12:10:13 +02002768 gJdwpState->PostFieldEvent(&location, f, this_object, nullptr, false);
Sebastien Hertz3f52eaf2014-04-04 17:50:18 +02002769}
2770
2771void Dbg::PostFieldModificationEvent(mirror::ArtMethod* m, int dex_pc,
2772 mirror::Object* this_object, mirror::ArtField* f,
2773 const JValue* field_value) {
2774 if (!IsDebuggerActive()) {
2775 return;
2776 }
2777 DCHECK(m != nullptr);
2778 DCHECK(f != nullptr);
2779 DCHECK(field_value != nullptr);
Sebastien Hertz6995c602014-09-09 12:10:13 +02002780 JDWP::EventLocation location;
2781 SetEventLocation(&location, m, dex_pc);
Sebastien Hertz3f52eaf2014-04-04 17:50:18 +02002782
Sebastien Hertz6995c602014-09-09 12:10:13 +02002783 gJdwpState->PostFieldEvent(&location, f, this_object, field_value, true);
Sebastien Hertz3f52eaf2014-04-04 17:50:18 +02002784}
2785
Nicolas Geoffray14691c52015-03-05 10:40:17 +00002786/**
2787 * Finds the location where this exception will be caught. We search until we reach the top
2788 * frame, in which case this exception is considered uncaught.
2789 */
2790class CatchLocationFinder : public StackVisitor {
2791 public:
2792 CatchLocationFinder(Thread* self, const Handle<mirror::Throwable>& exception, Context* context)
2793 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_)
2794 : StackVisitor(self, context),
2795 self_(self),
2796 exception_(exception),
2797 handle_scope_(self),
2798 this_at_throw_(handle_scope_.NewHandle<mirror::Object>(nullptr)),
2799 catch_method_(handle_scope_.NewHandle<mirror::ArtMethod>(nullptr)),
2800 throw_method_(handle_scope_.NewHandle<mirror::ArtMethod>(nullptr)),
2801 catch_dex_pc_(DexFile::kDexNoIndex),
2802 throw_dex_pc_(DexFile::kDexNoIndex) {
2803 }
2804
2805 bool VisitFrame() OVERRIDE SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
2806 mirror::ArtMethod* method = GetMethod();
2807 DCHECK(method != nullptr);
2808 if (method->IsRuntimeMethod()) {
2809 // Ignore callee save method.
2810 DCHECK(method->IsCalleeSaveMethod());
2811 return true;
2812 }
2813
2814 uint32_t dex_pc = GetDexPc();
2815 if (throw_method_.Get() == nullptr) {
2816 // First Java method found. It is either the method that threw the exception,
2817 // or the Java native method that is reporting an exception thrown by
2818 // native code.
2819 this_at_throw_.Assign(GetThisObject());
2820 throw_method_.Assign(method);
2821 throw_dex_pc_ = dex_pc;
2822 }
2823
2824 if (dex_pc != DexFile::kDexNoIndex) {
2825 StackHandleScope<2> hs(self_);
2826 uint32_t found_dex_pc;
2827 Handle<mirror::Class> exception_class(hs.NewHandle(exception_->GetClass()));
2828 Handle<mirror::ArtMethod> h_method(hs.NewHandle(method));
2829 bool unused_clear_exception;
2830 found_dex_pc = mirror::ArtMethod::FindCatchBlock(
2831 h_method, exception_class, dex_pc, &unused_clear_exception);
2832 if (found_dex_pc != DexFile::kDexNoIndex) {
2833 catch_method_.Assign(method);
2834 catch_dex_pc_ = found_dex_pc;
2835 return false; // End stack walk.
2836 }
2837 }
2838 return true; // Continue stack walk.
2839 }
2840
2841 mirror::ArtMethod* GetCatchMethod() SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
2842 return catch_method_.Get();
2843 }
2844
2845 mirror::ArtMethod* GetThrowMethod() SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
2846 return throw_method_.Get();
2847 }
2848
2849 mirror::Object* GetThisAtThrow() SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
2850 return this_at_throw_.Get();
2851 }
2852
2853 uint32_t GetCatchDexPc() const {
2854 return catch_dex_pc_;
2855 }
2856
2857 uint32_t GetThrowDexPc() const {
2858 return throw_dex_pc_;
2859 }
2860
2861 private:
2862 Thread* const self_;
2863 const Handle<mirror::Throwable>& exception_;
2864 StackHandleScope<3> handle_scope_;
2865 MutableHandle<mirror::Object> this_at_throw_;
2866 MutableHandle<mirror::ArtMethod> catch_method_;
2867 MutableHandle<mirror::ArtMethod> throw_method_;
2868 uint32_t catch_dex_pc_;
2869 uint32_t throw_dex_pc_;
2870
2871 DISALLOW_COPY_AND_ASSIGN(CatchLocationFinder);
2872};
2873
2874void Dbg::PostException(mirror::Throwable* exception_object) {
Elliott Hughesc0f09332012-03-26 13:27:06 -07002875 if (!IsDebuggerActive()) {
Ian Rogers0ad5bb82011-12-07 10:16:32 -08002876 return;
2877 }
Nicolas Geoffray14691c52015-03-05 10:40:17 +00002878 StackHandleScope<1> handle_scope(Thread::Current());
2879 Handle<mirror::Throwable> h_exception(handle_scope.NewHandle(exception_object));
2880 std::unique_ptr<Context> context(Context::Create());
2881 CatchLocationFinder clf(Thread::Current(), h_exception, context.get());
2882 clf.WalkStack(/* include_transitions */ false);
Sebastien Hertz6995c602014-09-09 12:10:13 +02002883 JDWP::EventLocation exception_throw_location;
Nicolas Geoffray14691c52015-03-05 10:40:17 +00002884 SetEventLocation(&exception_throw_location, clf.GetThrowMethod(), clf.GetThrowDexPc());
Sebastien Hertz6995c602014-09-09 12:10:13 +02002885 JDWP::EventLocation exception_catch_location;
Nicolas Geoffray14691c52015-03-05 10:40:17 +00002886 SetEventLocation(&exception_catch_location, clf.GetCatchMethod(), clf.GetCatchDexPc());
Elliott Hughes4740cdf2011-12-07 14:07:12 -08002887
Nicolas Geoffray14691c52015-03-05 10:40:17 +00002888 gJdwpState->PostException(&exception_throw_location, h_exception.Get(), &exception_catch_location,
2889 clf.GetThisAtThrow());
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002890}
2891
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002892void Dbg::PostClassPrepare(mirror::Class* c) {
Elliott Hughesc0f09332012-03-26 13:27:06 -07002893 if (!IsDebuggerActive()) {
Elliott Hughes4740cdf2011-12-07 14:07:12 -08002894 return;
2895 }
Sebastien Hertz6995c602014-09-09 12:10:13 +02002896 gJdwpState->PostClassPrepare(c);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002897}
2898
Ian Rogers62d6c772013-02-27 08:32:07 -08002899void Dbg::UpdateDebugger(Thread* thread, mirror::Object* this_object,
Sebastien Hertz8379b222014-02-24 17:38:15 +01002900 mirror::ArtMethod* m, uint32_t dex_pc,
2901 int event_flags, const JValue* return_value) {
Ian Rogers62d6c772013-02-27 08:32:07 -08002902 if (!IsDebuggerActive() || dex_pc == static_cast<uint32_t>(-2) /* fake method exit */) {
Elliott Hughes2aa2e392012-02-17 17:15:43 -08002903 return;
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08002904 }
2905
Elliott Hughes86964332012-02-15 19:37:42 -08002906 if (IsBreakpoint(m, dex_pc)) {
2907 event_flags |= kBreakpoint;
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08002908 }
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08002909
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01002910 // If the debugger is single-stepping one of our threads, check to
2911 // see if we're that thread and we've reached a step point.
2912 const SingleStepControl* single_step_control = thread->GetSingleStepControl();
Sebastien Hertz597c4f02015-01-26 17:37:14 +01002913 if (single_step_control != nullptr) {
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01002914 CHECK(!m->IsNative());
Sebastien Hertz597c4f02015-01-26 17:37:14 +01002915 if (single_step_control->GetStepDepth() == JDWP::SD_INTO) {
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01002916 // Step into method calls. We break when the line number
2917 // or method pointer changes. If we're in SS_MIN mode, we
2918 // always stop.
Sebastien Hertz597c4f02015-01-26 17:37:14 +01002919 if (single_step_control->GetMethod() != m) {
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01002920 event_flags |= kSingleStep;
2921 VLOG(jdwp) << "SS new method";
Sebastien Hertz597c4f02015-01-26 17:37:14 +01002922 } else if (single_step_control->GetStepSize() == JDWP::SS_MIN) {
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01002923 event_flags |= kSingleStep;
2924 VLOG(jdwp) << "SS new instruction";
Sebastien Hertzbb43b432014-04-14 11:59:08 +02002925 } else if (single_step_control->ContainsDexPc(dex_pc)) {
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01002926 event_flags |= kSingleStep;
2927 VLOG(jdwp) << "SS new line";
2928 }
Sebastien Hertz597c4f02015-01-26 17:37:14 +01002929 } else if (single_step_control->GetStepDepth() == JDWP::SD_OVER) {
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01002930 // Step over method calls. We break when the line number is
2931 // different and the frame depth is <= the original frame
2932 // depth. (We can't just compare on the method, because we
2933 // might get unrolled past it by an exception, and it's tricky
2934 // to identify recursion.)
2935
2936 int stack_depth = GetStackDepth(thread);
2937
Sebastien Hertz597c4f02015-01-26 17:37:14 +01002938 if (stack_depth < single_step_control->GetStackDepth()) {
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01002939 // Popped up one or more frames, always trigger.
2940 event_flags |= kSingleStep;
2941 VLOG(jdwp) << "SS method pop";
Sebastien Hertz597c4f02015-01-26 17:37:14 +01002942 } else if (stack_depth == single_step_control->GetStackDepth()) {
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01002943 // Same depth, see if we moved.
Sebastien Hertz597c4f02015-01-26 17:37:14 +01002944 if (single_step_control->GetStepSize() == JDWP::SS_MIN) {
Elliott Hughes86964332012-02-15 19:37:42 -08002945 event_flags |= kSingleStep;
2946 VLOG(jdwp) << "SS new instruction";
Sebastien Hertzbb43b432014-04-14 11:59:08 +02002947 } else if (single_step_control->ContainsDexPc(dex_pc)) {
Elliott Hughes2435a572012-02-17 16:07:41 -08002948 event_flags |= kSingleStep;
2949 VLOG(jdwp) << "SS new line";
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08002950 }
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01002951 }
2952 } else {
Sebastien Hertz597c4f02015-01-26 17:37:14 +01002953 CHECK_EQ(single_step_control->GetStepDepth(), JDWP::SD_OUT);
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01002954 // Return from the current method. We break when the frame
2955 // depth pops up.
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08002956
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01002957 // This differs from the "method exit" break in that it stops
2958 // with the PC at the next instruction in the returned-to
2959 // function, rather than the end of the returning function.
Elliott Hughes86964332012-02-15 19:37:42 -08002960
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01002961 int stack_depth = GetStackDepth(thread);
Sebastien Hertz597c4f02015-01-26 17:37:14 +01002962 if (stack_depth < single_step_control->GetStackDepth()) {
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01002963 event_flags |= kSingleStep;
2964 VLOG(jdwp) << "SS method pop";
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08002965 }
2966 }
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08002967 }
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08002968
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08002969 // If there's something interesting going on, see if it matches one
2970 // of the debugger filters.
2971 if (event_flags != 0) {
Sebastien Hertz8379b222014-02-24 17:38:15 +01002972 Dbg::PostLocationEvent(m, dex_pc, this_object, event_flags, return_value);
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08002973 }
2974}
2975
Sebastien Hertz42cd43f2014-05-13 14:15:41 +02002976size_t* Dbg::GetReferenceCounterForEvent(uint32_t instrumentation_event) {
2977 switch (instrumentation_event) {
2978 case instrumentation::Instrumentation::kMethodEntered:
2979 return &method_enter_event_ref_count_;
2980 case instrumentation::Instrumentation::kMethodExited:
2981 return &method_exit_event_ref_count_;
2982 case instrumentation::Instrumentation::kDexPcMoved:
2983 return &dex_pc_change_event_ref_count_;
2984 case instrumentation::Instrumentation::kFieldRead:
2985 return &field_read_event_ref_count_;
2986 case instrumentation::Instrumentation::kFieldWritten:
2987 return &field_write_event_ref_count_;
2988 case instrumentation::Instrumentation::kExceptionCaught:
2989 return &exception_catch_event_ref_count_;
2990 default:
2991 return nullptr;
2992 }
2993}
2994
Sebastien Hertz4d25df32014-03-21 17:44:46 +01002995// Process request while all mutator threads are suspended.
2996void Dbg::ProcessDeoptimizationRequest(const DeoptimizationRequest& request) {
Sebastien Hertz138dbfc2013-12-04 18:15:25 +01002997 instrumentation::Instrumentation* instrumentation = Runtime::Current()->GetInstrumentation();
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07002998 switch (request.GetKind()) {
Sebastien Hertz4d25df32014-03-21 17:44:46 +01002999 case DeoptimizationRequest::kNothing:
3000 LOG(WARNING) << "Ignoring empty deoptimization request.";
3001 break;
Sebastien Hertz42cd43f2014-05-13 14:15:41 +02003002 case DeoptimizationRequest::kRegisterForEvent:
3003 VLOG(jdwp) << StringPrintf("Add debugger as listener for instrumentation event 0x%x",
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003004 request.InstrumentationEvent());
3005 instrumentation->AddListener(&gDebugInstrumentationListener, request.InstrumentationEvent());
3006 instrumentation_events_ |= request.InstrumentationEvent();
Sebastien Hertz42cd43f2014-05-13 14:15:41 +02003007 break;
3008 case DeoptimizationRequest::kUnregisterForEvent:
3009 VLOG(jdwp) << StringPrintf("Remove debugger as listener for instrumentation event 0x%x",
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003010 request.InstrumentationEvent());
Sebastien Hertz42cd43f2014-05-13 14:15:41 +02003011 instrumentation->RemoveListener(&gDebugInstrumentationListener,
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003012 request.InstrumentationEvent());
3013 instrumentation_events_ &= ~request.InstrumentationEvent();
Sebastien Hertz42cd43f2014-05-13 14:15:41 +02003014 break;
Sebastien Hertz4d25df32014-03-21 17:44:46 +01003015 case DeoptimizationRequest::kFullDeoptimization:
Sebastien Hertz7ec2f1c2014-03-27 20:06:47 +01003016 VLOG(jdwp) << "Deoptimize the world ...";
Sebastien Hertz4d25df32014-03-21 17:44:46 +01003017 instrumentation->DeoptimizeEverything();
Sebastien Hertz7ec2f1c2014-03-27 20:06:47 +01003018 VLOG(jdwp) << "Deoptimize the world DONE";
Sebastien Hertz4d25df32014-03-21 17:44:46 +01003019 break;
3020 case DeoptimizationRequest::kFullUndeoptimization:
Sebastien Hertz7ec2f1c2014-03-27 20:06:47 +01003021 VLOG(jdwp) << "Undeoptimize the world ...";
Sebastien Hertz4d25df32014-03-21 17:44:46 +01003022 instrumentation->UndeoptimizeEverything();
Sebastien Hertz7ec2f1c2014-03-27 20:06:47 +01003023 VLOG(jdwp) << "Undeoptimize the world DONE";
Sebastien Hertz4d25df32014-03-21 17:44:46 +01003024 break;
3025 case DeoptimizationRequest::kSelectiveDeoptimization:
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003026 VLOG(jdwp) << "Deoptimize method " << PrettyMethod(request.Method()) << " ...";
3027 instrumentation->Deoptimize(request.Method());
3028 VLOG(jdwp) << "Deoptimize method " << PrettyMethod(request.Method()) << " DONE";
Sebastien Hertz4d25df32014-03-21 17:44:46 +01003029 break;
3030 case DeoptimizationRequest::kSelectiveUndeoptimization:
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003031 VLOG(jdwp) << "Undeoptimize method " << PrettyMethod(request.Method()) << " ...";
3032 instrumentation->Undeoptimize(request.Method());
3033 VLOG(jdwp) << "Undeoptimize method " << PrettyMethod(request.Method()) << " DONE";
Sebastien Hertz4d25df32014-03-21 17:44:46 +01003034 break;
3035 default:
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003036 LOG(FATAL) << "Unsupported deoptimization request kind " << request.GetKind();
Sebastien Hertz4d25df32014-03-21 17:44:46 +01003037 break;
Sebastien Hertz138dbfc2013-12-04 18:15:25 +01003038 }
Sebastien Hertz138dbfc2013-12-04 18:15:25 +01003039}
3040
Sebastien Hertz7ec2f1c2014-03-27 20:06:47 +01003041void Dbg::DelayFullUndeoptimization() {
Sebastien Hertzf3928792014-11-17 19:00:37 +01003042 if (RequiresDeoptimization()) {
3043 MutexLock mu(Thread::Current(), *Locks::deoptimization_lock_);
3044 ++delayed_full_undeoptimization_count_;
3045 DCHECK_LE(delayed_full_undeoptimization_count_, full_deoptimization_event_count_);
3046 }
Sebastien Hertz7ec2f1c2014-03-27 20:06:47 +01003047}
3048
3049void Dbg::ProcessDelayedFullUndeoptimizations() {
3050 // TODO: avoid taking the lock twice (once here and once in ManageDeoptimization).
3051 {
Brian Carlstrom306db812014-09-05 13:01:41 -07003052 MutexLock mu(Thread::Current(), *Locks::deoptimization_lock_);
Sebastien Hertz7ec2f1c2014-03-27 20:06:47 +01003053 while (delayed_full_undeoptimization_count_ > 0) {
3054 DeoptimizationRequest req;
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003055 req.SetKind(DeoptimizationRequest::kFullUndeoptimization);
3056 req.SetMethod(nullptr);
Sebastien Hertz7ec2f1c2014-03-27 20:06:47 +01003057 RequestDeoptimizationLocked(req);
3058 --delayed_full_undeoptimization_count_;
3059 }
3060 }
3061 ManageDeoptimization();
3062}
3063
Sebastien Hertz4d25df32014-03-21 17:44:46 +01003064void Dbg::RequestDeoptimization(const DeoptimizationRequest& req) {
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003065 if (req.GetKind() == DeoptimizationRequest::kNothing) {
Sebastien Hertz4d25df32014-03-21 17:44:46 +01003066 // Nothing to do.
3067 return;
3068 }
Brian Carlstrom306db812014-09-05 13:01:41 -07003069 MutexLock mu(Thread::Current(), *Locks::deoptimization_lock_);
Sebastien Hertz7ec2f1c2014-03-27 20:06:47 +01003070 RequestDeoptimizationLocked(req);
3071}
3072
3073void Dbg::RequestDeoptimizationLocked(const DeoptimizationRequest& req) {
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003074 switch (req.GetKind()) {
Sebastien Hertz42cd43f2014-05-13 14:15:41 +02003075 case DeoptimizationRequest::kRegisterForEvent: {
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003076 DCHECK_NE(req.InstrumentationEvent(), 0u);
3077 size_t* counter = GetReferenceCounterForEvent(req.InstrumentationEvent());
Sebastien Hertz42cd43f2014-05-13 14:15:41 +02003078 CHECK(counter != nullptr) << StringPrintf("No counter for instrumentation event 0x%x",
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003079 req.InstrumentationEvent());
Sebastien Hertz42cd43f2014-05-13 14:15:41 +02003080 if (*counter == 0) {
Sebastien Hertz7d2ae432014-05-15 11:26:34 +02003081 VLOG(jdwp) << StringPrintf("Queue request #%zd to start listening to instrumentation event 0x%x",
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003082 deoptimization_requests_.size(), req.InstrumentationEvent());
Sebastien Hertz42cd43f2014-05-13 14:15:41 +02003083 deoptimization_requests_.push_back(req);
3084 }
3085 *counter = *counter + 1;
3086 break;
3087 }
3088 case DeoptimizationRequest::kUnregisterForEvent: {
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003089 DCHECK_NE(req.InstrumentationEvent(), 0u);
3090 size_t* counter = GetReferenceCounterForEvent(req.InstrumentationEvent());
Sebastien Hertz42cd43f2014-05-13 14:15:41 +02003091 CHECK(counter != nullptr) << StringPrintf("No counter for instrumentation event 0x%x",
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003092 req.InstrumentationEvent());
Sebastien Hertz42cd43f2014-05-13 14:15:41 +02003093 *counter = *counter - 1;
3094 if (*counter == 0) {
Sebastien Hertz7d2ae432014-05-15 11:26:34 +02003095 VLOG(jdwp) << StringPrintf("Queue request #%zd to stop listening to instrumentation event 0x%x",
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003096 deoptimization_requests_.size(), req.InstrumentationEvent());
Sebastien Hertz42cd43f2014-05-13 14:15:41 +02003097 deoptimization_requests_.push_back(req);
3098 }
3099 break;
3100 }
Sebastien Hertz4d25df32014-03-21 17:44:46 +01003101 case DeoptimizationRequest::kFullDeoptimization: {
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003102 DCHECK(req.Method() == nullptr);
Sebastien Hertz4d25df32014-03-21 17:44:46 +01003103 if (full_deoptimization_event_count_ == 0) {
Sebastien Hertz7ec2f1c2014-03-27 20:06:47 +01003104 VLOG(jdwp) << "Queue request #" << deoptimization_requests_.size()
3105 << " for full deoptimization";
Sebastien Hertz4d25df32014-03-21 17:44:46 +01003106 deoptimization_requests_.push_back(req);
3107 }
3108 ++full_deoptimization_event_count_;
3109 break;
3110 }
3111 case DeoptimizationRequest::kFullUndeoptimization: {
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003112 DCHECK(req.Method() == nullptr);
Sebastien Hertze713d932014-05-15 10:48:53 +02003113 DCHECK_GT(full_deoptimization_event_count_, 0U);
Sebastien Hertz4d25df32014-03-21 17:44:46 +01003114 --full_deoptimization_event_count_;
3115 if (full_deoptimization_event_count_ == 0) {
Sebastien Hertz7ec2f1c2014-03-27 20:06:47 +01003116 VLOG(jdwp) << "Queue request #" << deoptimization_requests_.size()
3117 << " for full undeoptimization";
Sebastien Hertz4d25df32014-03-21 17:44:46 +01003118 deoptimization_requests_.push_back(req);
3119 }
3120 break;
3121 }
3122 case DeoptimizationRequest::kSelectiveDeoptimization: {
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003123 DCHECK(req.Method() != nullptr);
Sebastien Hertz7ec2f1c2014-03-27 20:06:47 +01003124 VLOG(jdwp) << "Queue request #" << deoptimization_requests_.size()
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003125 << " for deoptimization of " << PrettyMethod(req.Method());
Sebastien Hertz4d25df32014-03-21 17:44:46 +01003126 deoptimization_requests_.push_back(req);
3127 break;
3128 }
3129 case DeoptimizationRequest::kSelectiveUndeoptimization: {
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003130 DCHECK(req.Method() != nullptr);
Sebastien Hertz7ec2f1c2014-03-27 20:06:47 +01003131 VLOG(jdwp) << "Queue request #" << deoptimization_requests_.size()
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003132 << " for undeoptimization of " << PrettyMethod(req.Method());
Sebastien Hertz4d25df32014-03-21 17:44:46 +01003133 deoptimization_requests_.push_back(req);
3134 break;
3135 }
3136 default: {
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003137 LOG(FATAL) << "Unknown deoptimization request kind " << req.GetKind();
Sebastien Hertz4d25df32014-03-21 17:44:46 +01003138 break;
3139 }
3140 }
3141}
3142
Sebastien Hertz138dbfc2013-12-04 18:15:25 +01003143void Dbg::ManageDeoptimization() {
3144 Thread* const self = Thread::Current();
3145 {
3146 // Avoid suspend/resume if there is no pending request.
Brian Carlstrom306db812014-09-05 13:01:41 -07003147 MutexLock mu(self, *Locks::deoptimization_lock_);
Sebastien Hertz4d25df32014-03-21 17:44:46 +01003148 if (deoptimization_requests_.empty()) {
Sebastien Hertz138dbfc2013-12-04 18:15:25 +01003149 return;
3150 }
3151 }
3152 CHECK_EQ(self->GetState(), kRunnable);
3153 self->TransitionFromRunnableToSuspended(kWaitingForDeoptimization);
3154 // We need to suspend mutator threads first.
3155 Runtime* const runtime = Runtime::Current();
3156 runtime->GetThreadList()->SuspendAll();
3157 const ThreadState old_state = self->SetStateUnsafe(kRunnable);
Sebastien Hertz4d25df32014-03-21 17:44:46 +01003158 {
Brian Carlstrom306db812014-09-05 13:01:41 -07003159 MutexLock mu(self, *Locks::deoptimization_lock_);
Sebastien Hertz7ec2f1c2014-03-27 20:06:47 +01003160 size_t req_index = 0;
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003161 for (DeoptimizationRequest& request : deoptimization_requests_) {
Sebastien Hertz7ec2f1c2014-03-27 20:06:47 +01003162 VLOG(jdwp) << "Process deoptimization request #" << req_index++;
Sebastien Hertz4d25df32014-03-21 17:44:46 +01003163 ProcessDeoptimizationRequest(request);
3164 }
3165 deoptimization_requests_.clear();
3166 }
Sebastien Hertz138dbfc2013-12-04 18:15:25 +01003167 CHECK_EQ(self->SetStateUnsafe(old_state), kRunnable);
3168 runtime->GetThreadList()->ResumeAll();
3169 self->TransitionFromSuspendedToRunnable();
3170}
3171
Sebastien Hertza76a6d42014-03-20 16:40:17 +01003172static bool IsMethodPossiblyInlined(Thread* self, mirror::ArtMethod* m)
3173 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07003174 const DexFile::CodeItem* code_item = m->GetCodeItem();
Sebastien Hertza76a6d42014-03-20 16:40:17 +01003175 if (code_item == nullptr) {
3176 // TODO We should not be asked to watch location in a native or abstract method so the code item
3177 // should never be null. We could just check we never encounter this case.
3178 return false;
Sebastien Hertz138dbfc2013-12-04 18:15:25 +01003179 }
Sebastien Hertz4d1e9ab2014-09-18 16:03:34 +02003180 // Note: method verifier may cause thread suspension.
3181 self->AssertThreadSuspensionIsAllowable();
Hiroshi Yamauchidc376172014-08-22 11:13:12 -07003182 StackHandleScope<3> hs(self);
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07003183 mirror::Class* declaring_class = m->GetDeclaringClass();
3184 Handle<mirror::DexCache> dex_cache(hs.NewHandle(declaring_class->GetDexCache()));
3185 Handle<mirror::ClassLoader> class_loader(hs.NewHandle(declaring_class->GetClassLoader()));
Hiroshi Yamauchidc376172014-08-22 11:13:12 -07003186 Handle<mirror::ArtMethod> method(hs.NewHandle(m));
Ian Rogers7b078e82014-09-10 14:44:24 -07003187 verifier::MethodVerifier verifier(self, dex_cache->GetDexFile(), dex_cache, class_loader,
Hiroshi Yamauchidc376172014-08-22 11:13:12 -07003188 &m->GetClassDef(), code_item, m->GetDexMethodIndex(), method,
Mathieu Chartier4306ef82014-12-19 18:41:47 -08003189 m->GetAccessFlags(), false, true, false, true);
Sebastien Hertza76a6d42014-03-20 16:40:17 +01003190 // Note: we don't need to verify the method.
3191 return InlineMethodAnalyser::AnalyseMethodCode(&verifier, nullptr);
3192}
Sebastien Hertz138dbfc2013-12-04 18:15:25 +01003193
Sebastien Hertza76a6d42014-03-20 16:40:17 +01003194static const Breakpoint* FindFirstBreakpointForMethod(mirror::ArtMethod* m)
Sebastien Hertzed2be172014-08-19 15:33:43 +02003195 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_, Locks::breakpoint_lock_) {
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003196 for (Breakpoint& breakpoint : gBreakpoints) {
3197 if (breakpoint.Method() == m) {
Sebastien Hertza76a6d42014-03-20 16:40:17 +01003198 return &breakpoint;
3199 }
3200 }
3201 return nullptr;
3202}
3203
3204// Sanity checks all existing breakpoints on the same method.
Sebastien Hertzf3928792014-11-17 19:00:37 +01003205static void SanityCheckExistingBreakpoints(mirror::ArtMethod* m,
3206 DeoptimizationRequest::Kind deoptimization_kind)
Sebastien Hertzed2be172014-08-19 15:33:43 +02003207 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_, Locks::breakpoint_lock_) {
Sebastien Hertz4d1e9ab2014-09-18 16:03:34 +02003208 for (const Breakpoint& breakpoint : gBreakpoints) {
Sebastien Hertzf3928792014-11-17 19:00:37 +01003209 if (breakpoint.Method() == m) {
3210 CHECK_EQ(deoptimization_kind, breakpoint.GetDeoptimizationKind());
3211 }
Sebastien Hertz4d1e9ab2014-09-18 16:03:34 +02003212 }
Sebastien Hertzf3928792014-11-17 19:00:37 +01003213 instrumentation::Instrumentation* instrumentation = Runtime::Current()->GetInstrumentation();
3214 if (deoptimization_kind == DeoptimizationRequest::kFullDeoptimization) {
Sebastien Hertz4d1e9ab2014-09-18 16:03:34 +02003215 // We should have deoptimized everything but not "selectively" deoptimized this method.
Sebastien Hertzf3928792014-11-17 19:00:37 +01003216 CHECK(instrumentation->AreAllMethodsDeoptimized());
3217 CHECK(!instrumentation->IsDeoptimized(m));
3218 } else if (deoptimization_kind == DeoptimizationRequest::kSelectiveDeoptimization) {
Sebastien Hertz4d1e9ab2014-09-18 16:03:34 +02003219 // We should have "selectively" deoptimized this method.
3220 // Note: while we have not deoptimized everything for this method, we may have done it for
3221 // another event.
Sebastien Hertzf3928792014-11-17 19:00:37 +01003222 CHECK(instrumentation->IsDeoptimized(m));
3223 } else {
3224 // This method does not require deoptimization.
3225 CHECK_EQ(deoptimization_kind, DeoptimizationRequest::kNothing);
3226 CHECK(!instrumentation->IsDeoptimized(m));
3227 }
3228}
3229
Sebastien Hertzabe93e02014-12-17 16:35:50 +01003230// Returns the deoptimization kind required to set a breakpoint in a method.
3231// If a breakpoint has already been set, we also return the first breakpoint
3232// through the given 'existing_brkpt' pointer.
Sebastien Hertzf3928792014-11-17 19:00:37 +01003233static DeoptimizationRequest::Kind GetRequiredDeoptimizationKind(Thread* self,
Sebastien Hertzabe93e02014-12-17 16:35:50 +01003234 mirror::ArtMethod* m,
3235 const Breakpoint** existing_brkpt)
Sebastien Hertzf3928792014-11-17 19:00:37 +01003236 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
3237 if (!Dbg::RequiresDeoptimization()) {
3238 // We already run in interpreter-only mode so we don't need to deoptimize anything.
3239 VLOG(jdwp) << "No need for deoptimization when fully running with interpreter for method "
3240 << PrettyMethod(m);
3241 return DeoptimizationRequest::kNothing;
3242 }
Sebastien Hertzabe93e02014-12-17 16:35:50 +01003243 const Breakpoint* first_breakpoint;
Sebastien Hertzf3928792014-11-17 19:00:37 +01003244 {
3245 ReaderMutexLock mu(self, *Locks::breakpoint_lock_);
Sebastien Hertzabe93e02014-12-17 16:35:50 +01003246 first_breakpoint = FindFirstBreakpointForMethod(m);
3247 *existing_brkpt = first_breakpoint;
Sebastien Hertzf3928792014-11-17 19:00:37 +01003248 }
Sebastien Hertzabe93e02014-12-17 16:35:50 +01003249
3250 if (first_breakpoint == nullptr) {
Sebastien Hertzf3928792014-11-17 19:00:37 +01003251 // There is no breakpoint on this method yet: we need to deoptimize. If this method may be
3252 // inlined, we deoptimize everything; otherwise we deoptimize only this method.
3253 // Note: IsMethodPossiblyInlined goes into the method verifier and may cause thread suspension.
3254 // Therefore we must not hold any lock when we call it.
3255 bool need_full_deoptimization = IsMethodPossiblyInlined(self, m);
3256 if (need_full_deoptimization) {
3257 VLOG(jdwp) << "Need full deoptimization because of possible inlining of method "
3258 << PrettyMethod(m);
3259 return DeoptimizationRequest::kFullDeoptimization;
3260 } else {
3261 // We don't need to deoptimize if the method has not been compiled.
3262 ClassLinker* const class_linker = Runtime::Current()->GetClassLinker();
3263 const bool is_compiled = class_linker->GetOatMethodQuickCodeFor(m) != nullptr;
3264 if (is_compiled) {
Sebastien Hertz6963e442014-11-26 22:11:27 +01003265 // If the method may be called through its direct code pointer (without loading
3266 // its updated entrypoint), we need full deoptimization to not miss the breakpoint.
3267 if (class_linker->MayBeCalledWithDirectCodePointer(m)) {
3268 VLOG(jdwp) << "Need full deoptimization because of possible direct code call "
3269 << "into image for compiled method " << PrettyMethod(m);
3270 return DeoptimizationRequest::kFullDeoptimization;
3271 } else {
3272 VLOG(jdwp) << "Need selective deoptimization for compiled method " << PrettyMethod(m);
3273 return DeoptimizationRequest::kSelectiveDeoptimization;
3274 }
Sebastien Hertzf3928792014-11-17 19:00:37 +01003275 } else {
3276 // Method is not compiled: we don't need to deoptimize.
3277 VLOG(jdwp) << "No need for deoptimization for non-compiled method " << PrettyMethod(m);
3278 return DeoptimizationRequest::kNothing;
3279 }
3280 }
3281 } else {
3282 // There is at least one breakpoint for this method: we don't need to deoptimize.
3283 // Let's check that all breakpoints are configured the same way for deoptimization.
3284 VLOG(jdwp) << "Breakpoint already set: no deoptimization is required";
Sebastien Hertzabe93e02014-12-17 16:35:50 +01003285 DeoptimizationRequest::Kind deoptimization_kind = first_breakpoint->GetDeoptimizationKind();
Sebastien Hertzf3928792014-11-17 19:00:37 +01003286 if (kIsDebugBuild) {
3287 ReaderMutexLock mu(self, *Locks::breakpoint_lock_);
3288 SanityCheckExistingBreakpoints(m, deoptimization_kind);
3289 }
3290 return DeoptimizationRequest::kNothing;
Sebastien Hertz138dbfc2013-12-04 18:15:25 +01003291 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -07003292}
3293
Sebastien Hertza76a6d42014-03-20 16:40:17 +01003294// Installs a breakpoint at the specified location. Also indicates through the deoptimization
3295// request if we need to deoptimize.
3296void Dbg::WatchLocation(const JDWP::JdwpLocation* location, DeoptimizationRequest* req) {
3297 Thread* const self = Thread::Current();
Brian Carlstromea46f952013-07-30 01:26:50 -07003298 mirror::ArtMethod* m = FromMethodId(location->method_id);
Sebastien Hertza76a6d42014-03-20 16:40:17 +01003299 DCHECK(m != nullptr) << "No method for method id " << location->method_id;
Sebastien Hertz138dbfc2013-12-04 18:15:25 +01003300
Sebastien Hertzabe93e02014-12-17 16:35:50 +01003301 const Breakpoint* existing_breakpoint = nullptr;
3302 const DeoptimizationRequest::Kind deoptimization_kind =
3303 GetRequiredDeoptimizationKind(self, m, &existing_breakpoint);
Sebastien Hertzf3928792014-11-17 19:00:37 +01003304 req->SetKind(deoptimization_kind);
3305 if (deoptimization_kind == DeoptimizationRequest::kSelectiveDeoptimization) {
3306 req->SetMethod(m);
Sebastien Hertza76a6d42014-03-20 16:40:17 +01003307 } else {
Sebastien Hertzf3928792014-11-17 19:00:37 +01003308 CHECK(deoptimization_kind == DeoptimizationRequest::kNothing ||
3309 deoptimization_kind == DeoptimizationRequest::kFullDeoptimization);
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003310 req->SetMethod(nullptr);
Sebastien Hertz138dbfc2013-12-04 18:15:25 +01003311 }
3312
Sebastien Hertz4d1e9ab2014-09-18 16:03:34 +02003313 {
3314 WriterMutexLock mu(self, *Locks::breakpoint_lock_);
Sebastien Hertzabe93e02014-12-17 16:35:50 +01003315 // If there is at least one existing breakpoint on the same method, the new breakpoint
3316 // must have the same deoptimization kind than the existing breakpoint(s).
3317 DeoptimizationRequest::Kind breakpoint_deoptimization_kind;
3318 if (existing_breakpoint != nullptr) {
3319 breakpoint_deoptimization_kind = existing_breakpoint->GetDeoptimizationKind();
3320 } else {
3321 breakpoint_deoptimization_kind = deoptimization_kind;
3322 }
3323 gBreakpoints.push_back(Breakpoint(m, location->dex_pc, breakpoint_deoptimization_kind));
Sebastien Hertz4d1e9ab2014-09-18 16:03:34 +02003324 VLOG(jdwp) << "Set breakpoint #" << (gBreakpoints.size() - 1) << ": "
3325 << gBreakpoints[gBreakpoints.size() - 1];
3326 }
Sebastien Hertza76a6d42014-03-20 16:40:17 +01003327}
3328
3329// Uninstalls a breakpoint at the specified location. Also indicates through the deoptimization
3330// request if we need to undeoptimize.
3331void Dbg::UnwatchLocation(const JDWP::JdwpLocation* location, DeoptimizationRequest* req) {
Sebastien Hertzed2be172014-08-19 15:33:43 +02003332 WriterMutexLock mu(Thread::Current(), *Locks::breakpoint_lock_);
Sebastien Hertza76a6d42014-03-20 16:40:17 +01003333 mirror::ArtMethod* m = FromMethodId(location->method_id);
3334 DCHECK(m != nullptr) << "No method for method id " << location->method_id;
Sebastien Hertzf3928792014-11-17 19:00:37 +01003335 DeoptimizationRequest::Kind deoptimization_kind = DeoptimizationRequest::kNothing;
Sebastien Hertza76a6d42014-03-20 16:40:17 +01003336 for (size_t i = 0, e = gBreakpoints.size(); i < e; ++i) {
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003337 if (gBreakpoints[i].DexPc() == location->dex_pc && gBreakpoints[i].Method() == m) {
Sebastien Hertza76a6d42014-03-20 16:40:17 +01003338 VLOG(jdwp) << "Removed breakpoint #" << i << ": " << gBreakpoints[i];
Sebastien Hertzf3928792014-11-17 19:00:37 +01003339 deoptimization_kind = gBreakpoints[i].GetDeoptimizationKind();
3340 DCHECK_EQ(deoptimization_kind == DeoptimizationRequest::kSelectiveDeoptimization,
3341 Runtime::Current()->GetInstrumentation()->IsDeoptimized(m));
Sebastien Hertza76a6d42014-03-20 16:40:17 +01003342 gBreakpoints.erase(gBreakpoints.begin() + i);
3343 break;
3344 }
3345 }
3346 const Breakpoint* const existing_breakpoint = FindFirstBreakpointForMethod(m);
3347 if (existing_breakpoint == nullptr) {
3348 // There is no more breakpoint on this method: we need to undeoptimize.
Sebastien Hertzf3928792014-11-17 19:00:37 +01003349 if (deoptimization_kind == DeoptimizationRequest::kFullDeoptimization) {
Sebastien Hertza76a6d42014-03-20 16:40:17 +01003350 // This method required full deoptimization: we need to undeoptimize everything.
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003351 req->SetKind(DeoptimizationRequest::kFullUndeoptimization);
3352 req->SetMethod(nullptr);
Sebastien Hertzf3928792014-11-17 19:00:37 +01003353 } else if (deoptimization_kind == DeoptimizationRequest::kSelectiveDeoptimization) {
Sebastien Hertza76a6d42014-03-20 16:40:17 +01003354 // This method required selective deoptimization: we need to undeoptimize only that method.
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003355 req->SetKind(DeoptimizationRequest::kSelectiveUndeoptimization);
3356 req->SetMethod(m);
Sebastien Hertzf3928792014-11-17 19:00:37 +01003357 } else {
3358 // This method had no need for deoptimization: do nothing.
3359 CHECK_EQ(deoptimization_kind, DeoptimizationRequest::kNothing);
3360 req->SetKind(DeoptimizationRequest::kNothing);
3361 req->SetMethod(nullptr);
Sebastien Hertza76a6d42014-03-20 16:40:17 +01003362 }
3363 } else {
3364 // There is at least one breakpoint for this method: we don't need to undeoptimize.
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003365 req->SetKind(DeoptimizationRequest::kNothing);
3366 req->SetMethod(nullptr);
Sebastien Hertz4d1e9ab2014-09-18 16:03:34 +02003367 if (kIsDebugBuild) {
Sebastien Hertzf3928792014-11-17 19:00:37 +01003368 SanityCheckExistingBreakpoints(m, deoptimization_kind);
Sebastien Hertz4d1e9ab2014-09-18 16:03:34 +02003369 }
Elliott Hughes86964332012-02-15 19:37:42 -08003370 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -07003371}
3372
Jeff Hao449db332013-04-12 18:30:52 -07003373// Scoped utility class to suspend a thread so that we may do tasks such as walk its stack. Doesn't
3374// cause suspension if the thread is the current thread.
3375class ScopedThreadSuspension {
3376 public:
Ian Rogers33e95662013-05-20 20:29:14 -07003377 ScopedThreadSuspension(Thread* self, JDWP::ObjectId thread_id)
Sebastien Hertz52d131d2014-03-13 16:17:40 +01003378 LOCKS_EXCLUDED(Locks::thread_list_lock_)
Ian Rogers33e95662013-05-20 20:29:14 -07003379 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) :
Ian Rogersf3d874c2014-07-17 18:52:42 -07003380 thread_(nullptr),
Jeff Hao449db332013-04-12 18:30:52 -07003381 error_(JDWP::ERR_NONE),
3382 self_suspend_(false),
Ian Rogers33e95662013-05-20 20:29:14 -07003383 other_suspend_(false) {
Jeff Hao449db332013-04-12 18:30:52 -07003384 ScopedObjectAccessUnchecked soa(self);
3385 {
3386 MutexLock mu(soa.Self(), *Locks::thread_list_lock_);
Ian Rogersc0542af2014-09-03 16:16:56 -07003387 thread_ = DecodeThread(soa, thread_id, &error_);
Jeff Hao449db332013-04-12 18:30:52 -07003388 }
3389 if (error_ == JDWP::ERR_NONE) {
3390 if (thread_ == soa.Self()) {
3391 self_suspend_ = true;
3392 } else {
3393 soa.Self()->TransitionFromRunnableToSuspended(kWaitingForDebuggerSuspension);
Sebastien Hertz6995c602014-09-09 12:10:13 +02003394 jobject thread_peer = Dbg::GetObjectRegistry()->GetJObject(thread_id);
Jeff Hao449db332013-04-12 18:30:52 -07003395 bool timed_out;
Ian Rogers4ad5cd32014-11-11 23:08:07 -08003396 ThreadList* thread_list = Runtime::Current()->GetThreadList();
3397 Thread* suspended_thread = thread_list->SuspendThreadByPeer(thread_peer, true, true,
3398 &timed_out);
Jeff Hao449db332013-04-12 18:30:52 -07003399 CHECK_EQ(soa.Self()->TransitionFromSuspendedToRunnable(), kWaitingForDebuggerSuspension);
Ian Rogersf3d874c2014-07-17 18:52:42 -07003400 if (suspended_thread == nullptr) {
Jeff Hao449db332013-04-12 18:30:52 -07003401 // Thread terminated from under us while suspending.
3402 error_ = JDWP::ERR_INVALID_THREAD;
3403 } else {
3404 CHECK_EQ(suspended_thread, thread_);
3405 other_suspend_ = true;
3406 }
3407 }
3408 }
Elliott Hughes2435a572012-02-17 16:07:41 -08003409 }
Elliott Hughes86964332012-02-15 19:37:42 -08003410
Jeff Hao449db332013-04-12 18:30:52 -07003411 Thread* GetThread() const {
3412 return thread_;
3413 }
3414
3415 JDWP::JdwpError GetError() const {
3416 return error_;
3417 }
3418
3419 ~ScopedThreadSuspension() {
3420 if (other_suspend_) {
3421 Runtime::Current()->GetThreadList()->Resume(thread_, true);
3422 }
3423 }
3424
3425 private:
3426 Thread* thread_;
3427 JDWP::JdwpError error_;
3428 bool self_suspend_;
3429 bool other_suspend_;
3430};
3431
3432JDWP::JdwpError Dbg::ConfigureStep(JDWP::ObjectId thread_id, JDWP::JdwpStepSize step_size,
3433 JDWP::JdwpStepDepth step_depth) {
3434 Thread* self = Thread::Current();
3435 ScopedThreadSuspension sts(self, thread_id);
3436 if (sts.GetError() != JDWP::ERR_NONE) {
3437 return sts.GetError();
3438 }
3439
Sebastien Hertz597c4f02015-01-26 17:37:14 +01003440 // Work out what ArtMethod* we're in, the current line number, and how deep the stack currently
Elliott Hughes2435a572012-02-17 16:07:41 -08003441 // is for step-out.
Ian Rogers0399dde2012-06-06 17:09:28 -07003442 struct SingleStepStackVisitor : public StackVisitor {
Sebastien Hertz597c4f02015-01-26 17:37:14 +01003443 explicit SingleStepStackVisitor(Thread* thread) SHARED_LOCKS_REQUIRED(Locks::mutator_lock_)
3444 : StackVisitor(thread, nullptr), stack_depth(0), method(nullptr), line_number(-1) {
Elliott Hughes86964332012-02-15 19:37:42 -08003445 }
Ian Rogersca190662012-06-26 15:45:57 -07003446
Ian Rogers00f7d0e2012-07-19 15:28:27 -07003447 // TODO: Enable annotalysis. We know lock is held in constructor, but abstraction confuses
3448 // annotalysis.
3449 bool VisitFrame() NO_THREAD_SAFETY_ANALYSIS {
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01003450 mirror::ArtMethod* m = GetMethod();
Ian Rogers0399dde2012-06-06 17:09:28 -07003451 if (!m->IsRuntimeMethod()) {
Sebastien Hertz597c4f02015-01-26 17:37:14 +01003452 ++stack_depth;
3453 if (method == nullptr) {
Ian Rogersef7d42f2014-01-06 12:55:46 -08003454 mirror::DexCache* dex_cache = m->GetDeclaringClass()->GetDexCache();
Sebastien Hertz597c4f02015-01-26 17:37:14 +01003455 method = m;
Ian Rogersc0542af2014-09-03 16:16:56 -07003456 if (dex_cache != nullptr) {
Ian Rogers4445a7e2012-10-05 17:19:13 -07003457 const DexFile& dex_file = *dex_cache->GetDexFile();
Sebastien Hertz597c4f02015-01-26 17:37:14 +01003458 line_number = dex_file.GetLineNumFromPC(m, GetDexPc());
Elliott Hughes2435a572012-02-17 16:07:41 -08003459 }
Elliott Hughes86964332012-02-15 19:37:42 -08003460 }
3461 }
Elliott Hughes530fa002012-03-12 11:44:49 -07003462 return true;
Elliott Hughes86964332012-02-15 19:37:42 -08003463 }
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01003464
Sebastien Hertz597c4f02015-01-26 17:37:14 +01003465 int stack_depth;
3466 mirror::ArtMethod* method;
3467 int32_t line_number;
Elliott Hughes86964332012-02-15 19:37:42 -08003468 };
Jeff Hao449db332013-04-12 18:30:52 -07003469
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01003470 Thread* const thread = sts.GetThread();
Sebastien Hertz597c4f02015-01-26 17:37:14 +01003471 SingleStepStackVisitor visitor(thread);
Ian Rogers0399dde2012-06-06 17:09:28 -07003472 visitor.WalkStack();
Elliott Hughes86964332012-02-15 19:37:42 -08003473
Elliott Hughes2435a572012-02-17 16:07:41 -08003474 // Find the dex_pc values that correspond to the current line, for line-based single-stepping.
Elliott Hughes2435a572012-02-17 16:07:41 -08003475 struct DebugCallbackContext {
Sebastien Hertz597c4f02015-01-26 17:37:14 +01003476 explicit DebugCallbackContext(SingleStepControl* single_step_control_cb,
3477 int32_t line_number_cb, const DexFile::CodeItem* code_item)
Andreas Gampe277ccbd2014-11-03 21:36:10 -08003478 : single_step_control_(single_step_control_cb), line_number_(line_number_cb),
3479 code_item_(code_item), last_pc_valid(false), last_pc(0) {
Elliott Hughes2435a572012-02-17 16:07:41 -08003480 }
3481
Andreas Gampe277ccbd2014-11-03 21:36:10 -08003482 static bool Callback(void* raw_context, uint32_t address, uint32_t line_number_cb) {
Elliott Hughes2435a572012-02-17 16:07:41 -08003483 DebugCallbackContext* context = reinterpret_cast<DebugCallbackContext*>(raw_context);
Andreas Gampe277ccbd2014-11-03 21:36:10 -08003484 if (static_cast<int32_t>(line_number_cb) == context->line_number_) {
Elliott Hughes2435a572012-02-17 16:07:41 -08003485 if (!context->last_pc_valid) {
3486 // Everything from this address until the next line change is ours.
3487 context->last_pc = address;
3488 context->last_pc_valid = true;
3489 }
3490 // Otherwise, if we're already in a valid range for this line,
3491 // just keep going (shouldn't really happen)...
Brian Carlstrom7934ac22013-07-26 10:54:15 -07003492 } else if (context->last_pc_valid) { // and the line number is new
Elliott Hughes2435a572012-02-17 16:07:41 -08003493 // Add everything from the last entry up until here to the set
3494 for (uint32_t dex_pc = context->last_pc; dex_pc < address; ++dex_pc) {
Sebastien Hertz597c4f02015-01-26 17:37:14 +01003495 context->single_step_control_->AddDexPc(dex_pc);
Elliott Hughes2435a572012-02-17 16:07:41 -08003496 }
3497 context->last_pc_valid = false;
3498 }
Brian Carlstrom7934ac22013-07-26 10:54:15 -07003499 return false; // There may be multiple entries for any given line.
Elliott Hughes2435a572012-02-17 16:07:41 -08003500 }
3501
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01003502 ~DebugCallbackContext() {
Elliott Hughes2435a572012-02-17 16:07:41 -08003503 // If the line number was the last in the position table...
3504 if (last_pc_valid) {
Sebastien Hertzbb43b432014-04-14 11:59:08 +02003505 size_t end = code_item_->insns_size_in_code_units_;
Elliott Hughes2435a572012-02-17 16:07:41 -08003506 for (uint32_t dex_pc = last_pc; dex_pc < end; ++dex_pc) {
Sebastien Hertz597c4f02015-01-26 17:37:14 +01003507 single_step_control_->AddDexPc(dex_pc);
Elliott Hughes2435a572012-02-17 16:07:41 -08003508 }
3509 }
3510 }
3511
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01003512 SingleStepControl* const single_step_control_;
3513 const int32_t line_number_;
Sebastien Hertzbb43b432014-04-14 11:59:08 +02003514 const DexFile::CodeItem* const code_item_;
Elliott Hughes2435a572012-02-17 16:07:41 -08003515 bool last_pc_valid;
3516 uint32_t last_pc;
3517 };
Sebastien Hertz597c4f02015-01-26 17:37:14 +01003518
3519 // Allocate single step.
3520 SingleStepControl* single_step_control = new SingleStepControl(step_size, step_depth,
3521 visitor.stack_depth,
3522 visitor.method);
3523 CHECK(single_step_control != nullptr) << "Failed to allocate SingleStepControl";
3524 mirror::ArtMethod* m = single_step_control->GetMethod();
3525 const int32_t line_number = visitor.line_number;
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01003526 if (!m->IsNative()) {
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07003527 const DexFile::CodeItem* const code_item = m->GetCodeItem();
Sebastien Hertzbb43b432014-04-14 11:59:08 +02003528 DebugCallbackContext context(single_step_control, line_number, code_item);
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07003529 m->GetDexFile()->DecodeDebugInfo(code_item, m->IsStatic(), m->GetDexMethodIndex(),
Ian Rogersc0542af2014-09-03 16:16:56 -07003530 DebugCallbackContext::Callback, nullptr, &context);
Elliott Hughes3e2e1a22012-02-21 11:33:41 -08003531 }
Elliott Hughes2435a572012-02-17 16:07:41 -08003532
Sebastien Hertz597c4f02015-01-26 17:37:14 +01003533 // Activate single-step in the thread.
3534 thread->ActivateSingleStepControl(single_step_control);
Elliott Hughes86964332012-02-15 19:37:42 -08003535
Elliott Hughes2435a572012-02-17 16:07:41 -08003536 if (VLOG_IS_ON(jdwp)) {
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01003537 VLOG(jdwp) << "Single-step thread: " << *thread;
Sebastien Hertz597c4f02015-01-26 17:37:14 +01003538 VLOG(jdwp) << "Single-step step size: " << single_step_control->GetStepSize();
3539 VLOG(jdwp) << "Single-step step depth: " << single_step_control->GetStepDepth();
3540 VLOG(jdwp) << "Single-step current method: " << PrettyMethod(single_step_control->GetMethod());
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01003541 VLOG(jdwp) << "Single-step current line: " << line_number;
Sebastien Hertz597c4f02015-01-26 17:37:14 +01003542 VLOG(jdwp) << "Single-step current stack depth: " << single_step_control->GetStackDepth();
Elliott Hughes2435a572012-02-17 16:07:41 -08003543 VLOG(jdwp) << "Single-step dex_pc values:";
Sebastien Hertz597c4f02015-01-26 17:37:14 +01003544 for (uint32_t dex_pc : single_step_control->GetDexPcs()) {
Sebastien Hertzbb43b432014-04-14 11:59:08 +02003545 VLOG(jdwp) << StringPrintf(" %#x", dex_pc);
Elliott Hughes2435a572012-02-17 16:07:41 -08003546 }
3547 }
3548
3549 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07003550}
3551
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01003552void Dbg::UnconfigureStep(JDWP::ObjectId thread_id) {
3553 ScopedObjectAccessUnchecked soa(Thread::Current());
3554 MutexLock mu(soa.Self(), *Locks::thread_list_lock_);
Ian Rogersc0542af2014-09-03 16:16:56 -07003555 JDWP::JdwpError error;
3556 Thread* thread = DecodeThread(soa, thread_id, &error);
Sebastien Hertz87118ed2013-11-26 17:57:18 +01003557 if (error == JDWP::ERR_NONE) {
Sebastien Hertz597c4f02015-01-26 17:37:14 +01003558 thread->DeactivateSingleStepControl();
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01003559 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -07003560}
3561
Elliott Hughes45651fd2012-02-21 15:48:20 -08003562static char JdwpTagToShortyChar(JDWP::JdwpTag tag) {
3563 switch (tag) {
3564 default:
3565 LOG(FATAL) << "unknown JDWP tag: " << PrintableChar(tag);
Ian Rogersfc787ec2014-10-09 21:56:44 -07003566 UNREACHABLE();
Elliott Hughes45651fd2012-02-21 15:48:20 -08003567
3568 // Primitives.
3569 case JDWP::JT_BYTE: return 'B';
3570 case JDWP::JT_CHAR: return 'C';
3571 case JDWP::JT_FLOAT: return 'F';
3572 case JDWP::JT_DOUBLE: return 'D';
3573 case JDWP::JT_INT: return 'I';
3574 case JDWP::JT_LONG: return 'J';
3575 case JDWP::JT_SHORT: return 'S';
3576 case JDWP::JT_VOID: return 'V';
3577 case JDWP::JT_BOOLEAN: return 'Z';
3578
3579 // Reference types.
3580 case JDWP::JT_ARRAY:
3581 case JDWP::JT_OBJECT:
3582 case JDWP::JT_STRING:
3583 case JDWP::JT_THREAD:
3584 case JDWP::JT_THREAD_GROUP:
3585 case JDWP::JT_CLASS_LOADER:
3586 case JDWP::JT_CLASS_OBJECT:
3587 return 'L';
3588 }
3589}
3590
Elliott Hughes88d63092013-01-09 09:55:54 -08003591JDWP::JdwpError Dbg::InvokeMethod(JDWP::ObjectId thread_id, JDWP::ObjectId object_id,
3592 JDWP::RefTypeId class_id, JDWP::MethodId method_id,
Ian Rogers00f7d0e2012-07-19 15:28:27 -07003593 uint32_t arg_count, uint64_t* arg_values,
3594 JDWP::JdwpTag* arg_types, uint32_t options,
3595 JDWP::JdwpTag* pResultTag, uint64_t* pResultValue,
3596 JDWP::ObjectId* pExceptionId) {
Elliott Hughesd07986f2011-12-06 18:27:45 -08003597 ThreadList* thread_list = Runtime::Current()->GetThreadList();
3598
Ian Rogersc0542af2014-09-03 16:16:56 -07003599 Thread* targetThread = nullptr;
3600 DebugInvokeReq* req = nullptr;
Ian Rogers00f7d0e2012-07-19 15:28:27 -07003601 Thread* self = Thread::Current();
Elliott Hughesd07986f2011-12-06 18:27:45 -08003602 {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07003603 ScopedObjectAccessUnchecked soa(self);
Ian Rogers50b35e22012-10-04 10:09:15 -07003604 MutexLock mu(soa.Self(), *Locks::thread_list_lock_);
Ian Rogersc0542af2014-09-03 16:16:56 -07003605 JDWP::JdwpError error;
3606 targetThread = DecodeThread(soa, thread_id, &error);
Elliott Hughes221229c2013-01-08 18:17:50 -08003607 if (error != JDWP::ERR_NONE) {
3608 LOG(ERROR) << "InvokeMethod request for invalid thread id " << thread_id;
3609 return error;
Elliott Hughesd07986f2011-12-06 18:27:45 -08003610 }
3611 req = targetThread->GetInvokeReq();
3612 if (!req->ready) {
3613 LOG(ERROR) << "InvokeMethod request for thread not stopped by event: " << *targetThread;
3614 return JDWP::ERR_INVALID_THREAD;
3615 }
3616
3617 /*
3618 * We currently have a bug where we don't successfully resume the
3619 * target thread if the suspend count is too deep. We're expected to
3620 * require one "resume" for each "suspend", but when asked to execute
3621 * a method we have to resume fully and then re-suspend it back to the
3622 * same level. (The easiest way to cause this is to type "suspend"
3623 * multiple times in jdb.)
3624 *
3625 * It's unclear what this means when the event specifies "resume all"
3626 * and some threads are suspended more deeply than others. This is
3627 * a rare problem, so for now we just prevent it from hanging forever
3628 * by rejecting the method invocation request. Without this, we will
3629 * be stuck waiting on a suspended thread.
3630 */
Ian Rogers00f7d0e2012-07-19 15:28:27 -07003631 int suspend_count;
3632 {
Ian Rogers50b35e22012-10-04 10:09:15 -07003633 MutexLock mu2(soa.Self(), *Locks::thread_suspend_count_lock_);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07003634 suspend_count = targetThread->GetSuspendCount();
3635 }
Elliott Hughesd07986f2011-12-06 18:27:45 -08003636 if (suspend_count > 1) {
3637 LOG(ERROR) << *targetThread << " suspend count too deep for method invocation: " << suspend_count;
Brian Carlstrom7934ac22013-07-26 10:54:15 -07003638 return JDWP::ERR_THREAD_SUSPENDED; // Probably not expected here.
Elliott Hughesd07986f2011-12-06 18:27:45 -08003639 }
3640
Ian Rogersc0542af2014-09-03 16:16:56 -07003641 mirror::Object* receiver = gRegistry->Get<mirror::Object*>(object_id, &error);
3642 if (error != JDWP::ERR_NONE) {
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08003643 return JDWP::ERR_INVALID_OBJECT;
3644 }
Elliott Hughes45651fd2012-02-21 15:48:20 -08003645
Ian Rogersc0542af2014-09-03 16:16:56 -07003646 mirror::Object* thread = gRegistry->Get<mirror::Object*>(thread_id, &error);
3647 if (error != JDWP::ERR_NONE) {
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08003648 return JDWP::ERR_INVALID_OBJECT;
3649 }
Elliott Hughes45651fd2012-02-21 15:48:20 -08003650 // TODO: check that 'thread' is actually a java.lang.Thread!
3651
Ian Rogersc0542af2014-09-03 16:16:56 -07003652 mirror::Class* c = DecodeClass(class_id, &error);
3653 if (c == nullptr) {
3654 return error;
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08003655 }
Elliott Hughes45651fd2012-02-21 15:48:20 -08003656
Brian Carlstromea46f952013-07-30 01:26:50 -07003657 mirror::ArtMethod* m = FromMethodId(method_id);
Ian Rogersc0542af2014-09-03 16:16:56 -07003658 if (m->IsStatic() != (receiver == nullptr)) {
Elliott Hughes45651fd2012-02-21 15:48:20 -08003659 return JDWP::ERR_INVALID_METHODID;
3660 }
3661 if (m->IsStatic()) {
3662 if (m->GetDeclaringClass() != c) {
3663 return JDWP::ERR_INVALID_METHODID;
3664 }
3665 } else {
3666 if (!m->GetDeclaringClass()->IsAssignableFrom(c)) {
3667 return JDWP::ERR_INVALID_METHODID;
3668 }
3669 }
3670
3671 // Check the argument list matches the method.
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07003672 uint32_t shorty_len = 0;
3673 const char* shorty = m->GetShorty(&shorty_len);
3674 if (shorty_len - 1 != arg_count) {
Elliott Hughes45651fd2012-02-21 15:48:20 -08003675 return JDWP::ERR_ILLEGAL_ARGUMENT;
3676 }
Elliott Hughes09201632013-04-15 15:50:07 -07003677
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07003678 {
3679 StackHandleScope<3> hs(soa.Self());
Ian Rogersa0485602014-12-02 15:48:04 -08003680 HandleWrapper<mirror::ArtMethod> h_m(hs.NewHandleWrapper(&m));
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07003681 HandleWrapper<mirror::Object> h_obj(hs.NewHandleWrapper(&receiver));
3682 HandleWrapper<mirror::Class> h_klass(hs.NewHandleWrapper(&c));
3683 const DexFile::TypeList* types = m->GetParameterTypeList();
3684 for (size_t i = 0; i < arg_count; ++i) {
3685 if (shorty[i + 1] != JdwpTagToShortyChar(arg_types[i])) {
Elliott Hughes09201632013-04-15 15:50:07 -07003686 return JDWP::ERR_ILLEGAL_ARGUMENT;
3687 }
3688
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07003689 if (shorty[i + 1] == 'L') {
3690 // Did we really get an argument of an appropriate reference type?
Ian Rogersa0485602014-12-02 15:48:04 -08003691 mirror::Class* parameter_type =
3692 h_m->GetClassFromTypeIndex(types->GetTypeItem(i).type_idx_, true);
Ian Rogersc0542af2014-09-03 16:16:56 -07003693 mirror::Object* argument = gRegistry->Get<mirror::Object*>(arg_values[i], &error);
3694 if (error != JDWP::ERR_NONE) {
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07003695 return JDWP::ERR_INVALID_OBJECT;
3696 }
Ian Rogersc0542af2014-09-03 16:16:56 -07003697 if (argument != nullptr && !argument->InstanceOf(parameter_type)) {
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07003698 return JDWP::ERR_ILLEGAL_ARGUMENT;
3699 }
3700
3701 // Turn the on-the-wire ObjectId into a jobject.
3702 jvalue& v = reinterpret_cast<jvalue&>(arg_values[i]);
3703 v.l = gRegistry->GetJObject(arg_values[i]);
3704 }
Elliott Hughes09201632013-04-15 15:50:07 -07003705 }
Elliott Hughes45651fd2012-02-21 15:48:20 -08003706 }
3707
Sebastien Hertzd38667a2013-11-25 15:43:54 +01003708 req->receiver = receiver;
3709 req->thread = thread;
3710 req->klass = c;
3711 req->method = m;
3712 req->arg_count = arg_count;
3713 req->arg_values = arg_values;
3714 req->options = options;
3715 req->invoke_needed = true;
Elliott Hughesd07986f2011-12-06 18:27:45 -08003716 }
3717
3718 // The fact that we've released the thread list lock is a bit risky --- if the thread goes
3719 // away we're sitting high and dry -- but we must release this before the ResumeAllThreads
3720 // call, and it's unwise to hold it during WaitForSuspend.
3721
3722 {
3723 /*
3724 * We change our (JDWP thread) status, which should be THREAD_RUNNING,
Elliott Hughes81ff3182012-03-23 20:35:56 -07003725 * so we can suspend for a GC if the invoke request causes us to
Elliott Hughesd07986f2011-12-06 18:27:45 -08003726 * run out of memory. It's also a good idea to change it before locking
3727 * the invokeReq mutex, although that should never be held for long.
3728 */
Ian Rogers00f7d0e2012-07-19 15:28:27 -07003729 self->TransitionFromRunnableToSuspended(kWaitingForDebuggerSend);
Elliott Hughesd07986f2011-12-06 18:27:45 -08003730
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08003731 VLOG(jdwp) << " Transferring control to event thread";
Elliott Hughesd07986f2011-12-06 18:27:45 -08003732 {
Sebastien Hertzd38667a2013-11-25 15:43:54 +01003733 MutexLock mu(self, req->lock);
Elliott Hughesd07986f2011-12-06 18:27:45 -08003734
3735 if ((options & JDWP::INVOKE_SINGLE_THREADED) == 0) {
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08003736 VLOG(jdwp) << " Resuming all threads";
Ian Rogers00f7d0e2012-07-19 15:28:27 -07003737 thread_list->UndoDebuggerSuspensions();
Elliott Hughesd07986f2011-12-06 18:27:45 -08003738 } else {
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08003739 VLOG(jdwp) << " Resuming event thread only";
Elliott Hughesd07986f2011-12-06 18:27:45 -08003740 thread_list->Resume(targetThread, true);
3741 }
3742
Sebastien Hertz2bf93f42015-01-09 18:44:05 +01003743 // The target thread is resumed but needs the JDWP token we're holding.
3744 // We release it now and will acquire it again when the invocation is
3745 // complete and the target thread suspends itself.
3746 gJdwpState->ReleaseJdwpTokenForCommand();
3747
Elliott Hughesd07986f2011-12-06 18:27:45 -08003748 // Wait for the request to finish executing.
Sebastien Hertzd38667a2013-11-25 15:43:54 +01003749 while (req->invoke_needed) {
3750 req->cond.Wait(self);
Elliott Hughesd07986f2011-12-06 18:27:45 -08003751 }
3752 }
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08003753 VLOG(jdwp) << " Control has returned from event thread";
Elliott Hughesd07986f2011-12-06 18:27:45 -08003754
3755 /* wait for thread to re-suspend itself */
Brian Carlstromdf629502013-07-17 22:39:56 -07003756 SuspendThread(thread_id, false /* request_suspension */);
Sebastien Hertz2bf93f42015-01-09 18:44:05 +01003757
3758 // Now the thread is suspended again, we can re-acquire the JDWP token.
3759 gJdwpState->AcquireJdwpTokenForCommand();
3760
Ian Rogers00f7d0e2012-07-19 15:28:27 -07003761 self->TransitionFromSuspendedToRunnable();
Elliott Hughesd07986f2011-12-06 18:27:45 -08003762 }
3763
3764 /*
3765 * Suspend the threads. We waited for the target thread to suspend
3766 * itself, so all we need to do is suspend the others.
3767 *
Sebastien Hertz2bf93f42015-01-09 18:44:05 +01003768 * The SuspendAllForDebugger() call will double-suspend the event thread,
Elliott Hughesd07986f2011-12-06 18:27:45 -08003769 * so we want to resume the target thread once to keep the books straight.
3770 */
3771 if ((options & JDWP::INVOKE_SINGLE_THREADED) == 0) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07003772 self->TransitionFromRunnableToSuspended(kWaitingForDebuggerSuspension);
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08003773 VLOG(jdwp) << " Suspending all threads";
Ian Rogers00f7d0e2012-07-19 15:28:27 -07003774 thread_list->SuspendAllForDebugger();
3775 self->TransitionFromSuspendedToRunnable();
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08003776 VLOG(jdwp) << " Resuming event thread to balance the count";
Elliott Hughesd07986f2011-12-06 18:27:45 -08003777 thread_list->Resume(targetThread, true);
3778 }
3779
3780 // Copy the result.
3781 *pResultTag = req->result_tag;
3782 if (IsPrimitiveTag(req->result_tag)) {
Elliott Hughesf24d3ce2012-04-11 17:43:37 -07003783 *pResultValue = req->result_value.GetJ();
Elliott Hughesd07986f2011-12-06 18:27:45 -08003784 } else {
Elliott Hughesf24d3ce2012-04-11 17:43:37 -07003785 *pResultValue = gRegistry->Add(req->result_value.GetL());
Elliott Hughesd07986f2011-12-06 18:27:45 -08003786 }
3787 *pExceptionId = req->exception;
3788 return req->error;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07003789}
3790
3791void Dbg::ExecuteMethod(DebugInvokeReq* pReq) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07003792 ScopedObjectAccess soa(Thread::Current());
Elliott Hughesd07986f2011-12-06 18:27:45 -08003793
Elliott Hughes81ff3182012-03-23 20:35:56 -07003794 // We can be called while an exception is pending. We need
Elliott Hughesd07986f2011-12-06 18:27:45 -08003795 // to preserve that across the method invocation.
Nicolas Geoffray14691c52015-03-05 10:40:17 +00003796 StackHandleScope<2> hs(soa.Self());
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003797 auto old_exception = hs.NewHandle<mirror::Throwable>(nullptr);
Ian Rogers62d6c772013-02-27 08:32:07 -08003798 {
3799 ThrowLocation old_throw_location;
Nicolas Geoffray14691c52015-03-05 10:40:17 +00003800 mirror::Throwable* old_exception_obj = soa.Self()->GetException();
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003801 old_exception.Assign(old_exception_obj);
Ian Rogers62d6c772013-02-27 08:32:07 -08003802 soa.Self()->ClearException();
3803 }
Elliott Hughesd07986f2011-12-06 18:27:45 -08003804
3805 // Translate the method through the vtable, unless the debugger wants to suppress it.
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07003806 MutableHandle<mirror::ArtMethod> m(hs.NewHandle(pReq->method));
Ian Rogersc0542af2014-09-03 16:16:56 -07003807 if ((pReq->options & JDWP::INVOKE_NONVIRTUAL) == 0 && pReq->receiver != nullptr) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003808 mirror::ArtMethod* actual_method = pReq->klass->FindVirtualMethodForVirtualOrInterface(m.Get());
3809 if (actual_method != m.Get()) {
3810 VLOG(jdwp) << "ExecuteMethod translated " << PrettyMethod(m.Get()) << " to " << PrettyMethod(actual_method);
3811 m.Assign(actual_method);
Elliott Hughes45651fd2012-02-21 15:48:20 -08003812 }
Elliott Hughesd07986f2011-12-06 18:27:45 -08003813 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003814 VLOG(jdwp) << "ExecuteMethod " << PrettyMethod(m.Get())
Sebastien Hertzd38667a2013-11-25 15:43:54 +01003815 << " receiver=" << pReq->receiver
3816 << " arg_count=" << pReq->arg_count;
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003817 CHECK(m.Get() != nullptr);
Elliott Hughesd07986f2011-12-06 18:27:45 -08003818
3819 CHECK_EQ(sizeof(jvalue), sizeof(uint64_t));
3820
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003821 pReq->result_value = InvokeWithJValues(soa, pReq->receiver, soa.EncodeMethod(m.Get()),
Ian Rogers53b8b092014-03-13 23:45:53 -07003822 reinterpret_cast<jvalue*>(pReq->arg_values));
Elliott Hughesd07986f2011-12-06 18:27:45 -08003823
Nicolas Geoffray14691c52015-03-05 10:40:17 +00003824 mirror::Throwable* exception = soa.Self()->GetException();
Ian Rogers62d6c772013-02-27 08:32:07 -08003825 soa.Self()->ClearException();
3826 pReq->exception = gRegistry->Add(exception);
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07003827 pReq->result_tag = BasicTagFromDescriptor(m.Get()->GetShorty());
Elliott Hughesd07986f2011-12-06 18:27:45 -08003828 if (pReq->exception != 0) {
Ian Rogers62d6c772013-02-27 08:32:07 -08003829 VLOG(jdwp) << " JDWP invocation returning with exception=" << exception
3830 << " " << exception->Dump();
Elliott Hughesf24d3ce2012-04-11 17:43:37 -07003831 pReq->result_value.SetJ(0);
Elliott Hughesd07986f2011-12-06 18:27:45 -08003832 } else if (pReq->result_tag == JDWP::JT_OBJECT) {
3833 /* if no exception thrown, examine object result more closely */
Ian Rogers98379392014-02-24 16:53:16 -08003834 JDWP::JdwpTag new_tag = TagFromObject(soa, pReq->result_value.GetL());
Elliott Hughesd07986f2011-12-06 18:27:45 -08003835 if (new_tag != pReq->result_tag) {
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08003836 VLOG(jdwp) << " JDWP promoted result from " << pReq->result_tag << " to " << new_tag;
Elliott Hughesd07986f2011-12-06 18:27:45 -08003837 pReq->result_tag = new_tag;
3838 }
3839
3840 /*
3841 * Register the object. We don't actually need an ObjectId yet,
3842 * but we do need to be sure that the GC won't move or discard the
3843 * object when we switch out of RUNNING. The ObjectId conversion
3844 * will add the object to the "do not touch" list.
3845 *
3846 * We can't use the "tracked allocation" mechanism here because
3847 * the object is going to be handed off to a different thread.
3848 */
Elliott Hughesf24d3ce2012-04-11 17:43:37 -07003849 gRegistry->Add(pReq->result_value.GetL());
Elliott Hughesd07986f2011-12-06 18:27:45 -08003850 }
3851
Ian Rogersc0542af2014-09-03 16:16:56 -07003852 if (old_exception.Get() != nullptr) {
Nicolas Geoffray14691c52015-03-05 10:40:17 +00003853 soa.Self()->SetException(old_exception.Get());
Elliott Hughesd07986f2011-12-06 18:27:45 -08003854 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -07003855}
3856
Elliott Hughesd07986f2011-12-06 18:27:45 -08003857/*
Elliott Hughes4b9702c2013-02-20 18:13:24 -08003858 * "request" contains a full JDWP packet, possibly with multiple chunks. We
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07003859 * need to process each, accumulate the replies, and ship the whole thing
3860 * back.
3861 *
3862 * Returns "true" if we have a reply. The reply buffer is newly allocated,
3863 * and includes the chunk type/length, followed by the data.
3864 *
Elliott Hughes3d30d9b2011-12-07 17:35:48 -08003865 * OLD-TODO: we currently assume that the request and reply include a single
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07003866 * chunk. If this becomes inconvenient we will need to adapt.
3867 */
Ian Rogersc0542af2014-09-03 16:16:56 -07003868bool Dbg::DdmHandlePacket(JDWP::Request* request, uint8_t** pReplyBuf, int* pReplyLen) {
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07003869 Thread* self = Thread::Current();
3870 JNIEnv* env = self->GetJniEnv();
3871
Ian Rogersc0542af2014-09-03 16:16:56 -07003872 uint32_t type = request->ReadUnsigned32("type");
3873 uint32_t length = request->ReadUnsigned32("length");
Elliott Hughes4b9702c2013-02-20 18:13:24 -08003874
3875 // Create a byte[] corresponding to 'request'.
Ian Rogersc0542af2014-09-03 16:16:56 -07003876 size_t request_length = request->size();
Elliott Hughes4b9702c2013-02-20 18:13:24 -08003877 ScopedLocalRef<jbyteArray> dataArray(env, env->NewByteArray(request_length));
Ian Rogersc0542af2014-09-03 16:16:56 -07003878 if (dataArray.get() == nullptr) {
Elliott Hughes4b9702c2013-02-20 18:13:24 -08003879 LOG(WARNING) << "byte[] allocation failed: " << request_length;
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07003880 env->ExceptionClear();
3881 return false;
3882 }
Ian Rogersc0542af2014-09-03 16:16:56 -07003883 env->SetByteArrayRegion(dataArray.get(), 0, request_length,
3884 reinterpret_cast<const jbyte*>(request->data()));
3885 request->Skip(request_length);
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07003886
3887 // Run through and find all chunks. [Currently just find the first.]
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003888 ScopedByteArrayRO contents(env, dataArray.get());
Elliott Hughes4b9702c2013-02-20 18:13:24 -08003889 if (length != request_length) {
Ian Rogersef7d42f2014-01-06 12:55:46 -08003890 LOG(WARNING) << StringPrintf("bad chunk found (len=%u pktLen=%zd)", length, request_length);
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07003891 return false;
3892 }
3893
3894 // Call "private static Chunk dispatch(int type, byte[] data, int offset, int length)".
Elliott Hugheseac76672012-05-24 21:56:51 -07003895 ScopedLocalRef<jobject> chunk(env, env->CallStaticObjectMethod(WellKnownClasses::org_apache_harmony_dalvik_ddmc_DdmServer,
3896 WellKnownClasses::org_apache_harmony_dalvik_ddmc_DdmServer_dispatch,
Elliott Hughes4b9702c2013-02-20 18:13:24 -08003897 type, dataArray.get(), 0, length));
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07003898 if (env->ExceptionCheck()) {
3899 LOG(INFO) << StringPrintf("Exception thrown by dispatcher for 0x%08x", type);
3900 env->ExceptionDescribe();
3901 env->ExceptionClear();
3902 return false;
3903 }
3904
Ian Rogersc0542af2014-09-03 16:16:56 -07003905 if (chunk.get() == nullptr) {
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07003906 return false;
3907 }
3908
3909 /*
3910 * Pull the pieces out of the chunk. We copy the results into a
3911 * newly-allocated buffer that the caller can free. We don't want to
3912 * continue using the Chunk object because nothing has a reference to it.
3913 *
3914 * We could avoid this by returning type/data/offset/length and having
3915 * the caller be aware of the object lifetime issues, but that
Elliott Hughes81ff3182012-03-23 20:35:56 -07003916 * integrates the JDWP code more tightly into the rest of the runtime, and doesn't work
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07003917 * if we have responses for multiple chunks.
3918 *
3919 * So we're pretty much stuck with copying data around multiple times.
3920 */
Elliott Hugheseac76672012-05-24 21:56:51 -07003921 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 -08003922 jint offset = env->GetIntField(chunk.get(), WellKnownClasses::org_apache_harmony_dalvik_ddmc_Chunk_offset);
Elliott Hugheseac76672012-05-24 21:56:51 -07003923 length = env->GetIntField(chunk.get(), WellKnownClasses::org_apache_harmony_dalvik_ddmc_Chunk_length);
Elliott Hugheseac76672012-05-24 21:56:51 -07003924 type = env->GetIntField(chunk.get(), WellKnownClasses::org_apache_harmony_dalvik_ddmc_Chunk_type);
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07003925
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08003926 VLOG(jdwp) << StringPrintf("DDM reply: type=0x%08x data=%p offset=%d length=%d", type, replyData.get(), offset, length);
Ian Rogersc0542af2014-09-03 16:16:56 -07003927 if (length == 0 || replyData.get() == nullptr) {
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07003928 return false;
3929 }
3930
Elliott Hughes4b9702c2013-02-20 18:13:24 -08003931 const int kChunkHdrLen = 8;
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07003932 uint8_t* reply = new uint8_t[length + kChunkHdrLen];
Ian Rogersc0542af2014-09-03 16:16:56 -07003933 if (reply == nullptr) {
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07003934 LOG(WARNING) << "malloc failed: " << (length + kChunkHdrLen);
3935 return false;
3936 }
Elliott Hughesf7c3b662011-10-27 12:04:56 -07003937 JDWP::Set4BE(reply + 0, type);
3938 JDWP::Set4BE(reply + 4, length);
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003939 env->GetByteArrayRegion(replyData.get(), offset, length, reinterpret_cast<jbyte*>(reply + kChunkHdrLen));
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07003940
3941 *pReplyBuf = reply;
3942 *pReplyLen = length + kChunkHdrLen;
3943
Elliott Hughes4b9702c2013-02-20 18:13:24 -08003944 VLOG(jdwp) << StringPrintf("dvmHandleDdm returning type=%.4s %p len=%d", reinterpret_cast<char*>(reply), reply, length);
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07003945 return true;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07003946}
3947
Elliott Hughesa2155262011-11-16 16:26:58 -08003948void Dbg::DdmBroadcast(bool connect) {
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08003949 VLOG(jdwp) << "Broadcasting DDM " << (connect ? "connect" : "disconnect") << "...";
Elliott Hughes47fce012011-10-25 18:37:19 -07003950
3951 Thread* self = Thread::Current();
Ian Rogers50b35e22012-10-04 10:09:15 -07003952 if (self->GetState() != kRunnable) {
3953 LOG(ERROR) << "DDM broadcast in thread state " << self->GetState();
3954 /* try anyway? */
Elliott Hughes47fce012011-10-25 18:37:19 -07003955 }
3956
3957 JNIEnv* env = self->GetJniEnv();
Elliott Hughes47fce012011-10-25 18:37:19 -07003958 jint event = connect ? 1 /*DdmServer.CONNECTED*/ : 2 /*DdmServer.DISCONNECTED*/;
Elliott Hugheseac76672012-05-24 21:56:51 -07003959 env->CallStaticVoidMethod(WellKnownClasses::org_apache_harmony_dalvik_ddmc_DdmServer,
3960 WellKnownClasses::org_apache_harmony_dalvik_ddmc_DdmServer_broadcast,
3961 event);
Elliott Hughes47fce012011-10-25 18:37:19 -07003962 if (env->ExceptionCheck()) {
3963 LOG(ERROR) << "DdmServer.broadcast " << event << " failed";
3964 env->ExceptionDescribe();
3965 env->ExceptionClear();
3966 }
3967}
3968
Elliott Hughes872d4ec2011-10-21 17:07:15 -07003969void Dbg::DdmConnected() {
Elliott Hughesa2155262011-11-16 16:26:58 -08003970 Dbg::DdmBroadcast(true);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07003971}
3972
3973void Dbg::DdmDisconnected() {
Elliott Hughesa2155262011-11-16 16:26:58 -08003974 Dbg::DdmBroadcast(false);
Elliott Hughes47fce012011-10-25 18:37:19 -07003975 gDdmThreadNotification = false;
3976}
3977
3978/*
Elliott Hughes82188472011-11-07 18:11:48 -08003979 * Send a notification when a thread starts, stops, or changes its name.
Elliott Hughes47fce012011-10-25 18:37:19 -07003980 *
3981 * Because we broadcast the full set of threads when the notifications are
3982 * first enabled, it's possible for "thread" to be actively executing.
3983 */
Elliott Hughes82188472011-11-07 18:11:48 -08003984void Dbg::DdmSendThreadNotification(Thread* t, uint32_t type) {
Elliott Hughes47fce012011-10-25 18:37:19 -07003985 if (!gDdmThreadNotification) {
3986 return;
3987 }
3988
Elliott Hughes82188472011-11-07 18:11:48 -08003989 if (type == CHUNK_TYPE("THDE")) {
Elliott Hughes47fce012011-10-25 18:37:19 -07003990 uint8_t buf[4];
Ian Rogersd9c4fc92013-10-01 19:45:43 -07003991 JDWP::Set4BE(&buf[0], t->GetThreadId());
Elliott Hughes47fce012011-10-25 18:37:19 -07003992 Dbg::DdmSendChunk(CHUNK_TYPE("THDE"), 4, buf);
Elliott Hughes82188472011-11-07 18:11:48 -08003993 } else {
3994 CHECK(type == CHUNK_TYPE("THCR") || type == CHUNK_TYPE("THNM")) << type;
Ian Rogers00f7d0e2012-07-19 15:28:27 -07003995 ScopedObjectAccessUnchecked soa(Thread::Current());
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003996 StackHandleScope<1> hs(soa.Self());
3997 Handle<mirror::String> name(hs.NewHandle(t->GetThreadName(soa)));
Ian Rogersc0542af2014-09-03 16:16:56 -07003998 size_t char_count = (name.Get() != nullptr) ? name->GetLength() : 0;
3999 const jchar* chars = (name.Get() != nullptr) ? name->GetCharArray()->GetData() : nullptr;
Elliott Hughes82188472011-11-07 18:11:48 -08004000
Elliott Hughes21f32d72011-11-09 17:44:13 -08004001 std::vector<uint8_t> bytes;
Ian Rogersd9c4fc92013-10-01 19:45:43 -07004002 JDWP::Append4BE(bytes, t->GetThreadId());
Elliott Hughes545a0642011-11-08 19:10:03 -08004003 JDWP::AppendUtf16BE(bytes, chars, char_count);
Elliott Hughes21f32d72011-11-09 17:44:13 -08004004 CHECK_EQ(bytes.size(), char_count*2 + sizeof(uint32_t)*2);
4005 Dbg::DdmSendChunk(type, bytes);
Elliott Hughes47fce012011-10-25 18:37:19 -07004006 }
4007}
4008
Elliott Hughes47fce012011-10-25 18:37:19 -07004009void Dbg::DdmSetThreadNotification(bool enable) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07004010 // Enable/disable thread notifications.
Elliott Hughes47fce012011-10-25 18:37:19 -07004011 gDdmThreadNotification = enable;
4012 if (enable) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07004013 // Suspend the VM then post thread start notifications for all threads. Threads attaching will
4014 // see a suspension in progress and block until that ends. They then post their own start
4015 // notification.
4016 SuspendVM();
4017 std::list<Thread*> threads;
Ian Rogers50b35e22012-10-04 10:09:15 -07004018 Thread* self = Thread::Current();
Ian Rogers00f7d0e2012-07-19 15:28:27 -07004019 {
Ian Rogers50b35e22012-10-04 10:09:15 -07004020 MutexLock mu(self, *Locks::thread_list_lock_);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07004021 threads = Runtime::Current()->GetThreadList()->GetList();
4022 }
4023 {
Ian Rogers50b35e22012-10-04 10:09:15 -07004024 ScopedObjectAccess soa(self);
Mathieu Chartier02e25112013-08-14 16:14:24 -07004025 for (Thread* thread : threads) {
4026 Dbg::DdmSendThreadNotification(thread, CHUNK_TYPE("THCR"));
Ian Rogers00f7d0e2012-07-19 15:28:27 -07004027 }
4028 }
4029 ResumeVM();
Elliott Hughes47fce012011-10-25 18:37:19 -07004030 }
4031}
4032
Elliott Hughesa2155262011-11-16 16:26:58 -08004033void Dbg::PostThreadStartOrStop(Thread* t, uint32_t type) {
Elliott Hughesc0f09332012-03-26 13:27:06 -07004034 if (IsDebuggerActive()) {
Sebastien Hertz6995c602014-09-09 12:10:13 +02004035 gJdwpState->PostThreadChange(t, type == CHUNK_TYPE("THCR"));
Elliott Hughes47fce012011-10-25 18:37:19 -07004036 }
Elliott Hughes82188472011-11-07 18:11:48 -08004037 Dbg::DdmSendThreadNotification(t, type);
Elliott Hughes47fce012011-10-25 18:37:19 -07004038}
4039
4040void Dbg::PostThreadStart(Thread* t) {
Elliott Hughesa2155262011-11-16 16:26:58 -08004041 Dbg::PostThreadStartOrStop(t, CHUNK_TYPE("THCR"));
Elliott Hughes47fce012011-10-25 18:37:19 -07004042}
4043
4044void Dbg::PostThreadDeath(Thread* t) {
Elliott Hughesa2155262011-11-16 16:26:58 -08004045 Dbg::PostThreadStartOrStop(t, CHUNK_TYPE("THDE"));
Elliott Hughes872d4ec2011-10-21 17:07:15 -07004046}
4047
Elliott Hughes82188472011-11-07 18:11:48 -08004048void Dbg::DdmSendChunk(uint32_t type, size_t byte_count, const uint8_t* buf) {
Ian Rogersc0542af2014-09-03 16:16:56 -07004049 CHECK(buf != nullptr);
Elliott Hughes3bb81562011-10-21 18:52:59 -07004050 iovec vec[1];
4051 vec[0].iov_base = reinterpret_cast<void*>(const_cast<uint8_t*>(buf));
4052 vec[0].iov_len = byte_count;
4053 Dbg::DdmSendChunkV(type, vec, 1);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07004054}
4055
Elliott Hughes21f32d72011-11-09 17:44:13 -08004056void Dbg::DdmSendChunk(uint32_t type, const std::vector<uint8_t>& bytes) {
4057 DdmSendChunk(type, bytes.size(), &bytes[0]);
4058}
4059
Brian Carlstromf5293522013-07-19 00:24:00 -07004060void Dbg::DdmSendChunkV(uint32_t type, const iovec* iov, int iov_count) {
Ian Rogersc0542af2014-09-03 16:16:56 -07004061 if (gJdwpState == nullptr) {
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08004062 VLOG(jdwp) << "Debugger thread not active, ignoring DDM send: " << type;
Elliott Hughes3bb81562011-10-21 18:52:59 -07004063 } else {
Elliott Hughescccd84f2011-12-05 16:51:54 -08004064 gJdwpState->DdmSendChunkV(type, iov, iov_count);
Elliott Hughes3bb81562011-10-21 18:52:59 -07004065 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -07004066}
4067
Mathieu Chartierad466ad2015-01-08 16:28:08 -08004068JDWP::JdwpState* Dbg::GetJdwpState() {
4069 return gJdwpState;
4070}
4071
Elliott Hughes767a1472011-10-26 18:49:02 -07004072int Dbg::DdmHandleHpifChunk(HpifWhen when) {
4073 if (when == HPIF_WHEN_NOW) {
Elliott Hughes7162ad92011-10-27 14:08:42 -07004074 DdmSendHeapInfo(when);
Elliott Hughes767a1472011-10-26 18:49:02 -07004075 return true;
4076 }
4077
4078 if (when != HPIF_WHEN_NEVER && when != HPIF_WHEN_NEXT_GC && when != HPIF_WHEN_EVERY_GC) {
4079 LOG(ERROR) << "invalid HpifWhen value: " << static_cast<int>(when);
4080 return false;
4081 }
4082
4083 gDdmHpifWhen = when;
4084 return true;
4085}
4086
4087bool Dbg::DdmHandleHpsgNhsgChunk(Dbg::HpsgWhen when, Dbg::HpsgWhat what, bool native) {
4088 if (when != HPSG_WHEN_NEVER && when != HPSG_WHEN_EVERY_GC) {
4089 LOG(ERROR) << "invalid HpsgWhen value: " << static_cast<int>(when);
4090 return false;
4091 }
4092
4093 if (what != HPSG_WHAT_MERGED_OBJECTS && what != HPSG_WHAT_DISTINCT_OBJECTS) {
4094 LOG(ERROR) << "invalid HpsgWhat value: " << static_cast<int>(what);
4095 return false;
4096 }
4097
4098 if (native) {
4099 gDdmNhsgWhen = when;
4100 gDdmNhsgWhat = what;
4101 } else {
4102 gDdmHpsgWhen = when;
4103 gDdmHpsgWhat = what;
4104 }
4105 return true;
4106}
4107
Elliott Hughes7162ad92011-10-27 14:08:42 -07004108void Dbg::DdmSendHeapInfo(HpifWhen reason) {
4109 // If there's a one-shot 'when', reset it.
4110 if (reason == gDdmHpifWhen) {
4111 if (gDdmHpifWhen == HPIF_WHEN_NEXT_GC) {
4112 gDdmHpifWhen = HPIF_WHEN_NEVER;
4113 }
4114 }
4115
4116 /*
4117 * Chunk HPIF (client --> server)
4118 *
4119 * Heap Info. General information about the heap,
4120 * suitable for a summary display.
4121 *
4122 * [u4]: number of heaps
4123 *
4124 * For each heap:
4125 * [u4]: heap ID
4126 * [u8]: timestamp in ms since Unix epoch
4127 * [u1]: capture reason (same as 'when' value from server)
4128 * [u4]: max heap size in bytes (-Xmx)
4129 * [u4]: current heap size in bytes
4130 * [u4]: current number of bytes allocated
4131 * [u4]: current number of objects allocated
4132 */
4133 uint8_t heap_count = 1;
Ian Rogers1d54e732013-05-02 21:10:01 -07004134 gc::Heap* heap = Runtime::Current()->GetHeap();
Elliott Hughes21f32d72011-11-09 17:44:13 -08004135 std::vector<uint8_t> bytes;
Elliott Hughes545a0642011-11-08 19:10:03 -08004136 JDWP::Append4BE(bytes, heap_count);
Brian Carlstrom7934ac22013-07-26 10:54:15 -07004137 JDWP::Append4BE(bytes, 1); // Heap id (bogus; we only have one heap).
Elliott Hughes545a0642011-11-08 19:10:03 -08004138 JDWP::Append8BE(bytes, MilliTime());
4139 JDWP::Append1BE(bytes, reason);
Brian Carlstrom7934ac22013-07-26 10:54:15 -07004140 JDWP::Append4BE(bytes, heap->GetMaxMemory()); // Max allowed heap size in bytes.
4141 JDWP::Append4BE(bytes, heap->GetTotalMemory()); // Current heap size in bytes.
Elliott Hughesb3bd5f02012-03-08 21:05:27 -08004142 JDWP::Append4BE(bytes, heap->GetBytesAllocated());
4143 JDWP::Append4BE(bytes, heap->GetObjectsAllocated());
Elliott Hughes21f32d72011-11-09 17:44:13 -08004144 CHECK_EQ(bytes.size(), 4U + (heap_count * (4 + 8 + 1 + 4 + 4 + 4 + 4)));
4145 Dbg::DdmSendChunk(CHUNK_TYPE("HPIF"), bytes);
Elliott Hughes767a1472011-10-26 18:49:02 -07004146}
4147
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004148enum HpsgSolidity {
4149 SOLIDITY_FREE = 0,
4150 SOLIDITY_HARD = 1,
4151 SOLIDITY_SOFT = 2,
4152 SOLIDITY_WEAK = 3,
4153 SOLIDITY_PHANTOM = 4,
4154 SOLIDITY_FINALIZABLE = 5,
4155 SOLIDITY_SWEEP = 6,
4156};
4157
4158enum HpsgKind {
4159 KIND_OBJECT = 0,
4160 KIND_CLASS_OBJECT = 1,
4161 KIND_ARRAY_1 = 2,
4162 KIND_ARRAY_2 = 3,
4163 KIND_ARRAY_4 = 4,
4164 KIND_ARRAY_8 = 5,
4165 KIND_UNKNOWN = 6,
4166 KIND_NATIVE = 7,
4167};
4168
4169#define HPSG_PARTIAL (1<<7)
4170#define HPSG_STATE(solidity, kind) ((uint8_t)((((kind) & 0x7) << 3) | ((solidity) & 0x7)))
4171
Ian Rogers30fab402012-01-23 15:43:46 -08004172class HeapChunkContext {
4173 public:
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004174 // Maximum chunk size. Obtain this from the formula:
4175 // (((maximum_heap_size / ALLOCATION_UNIT_SIZE) + 255) / 256) * 2
4176 HeapChunkContext(bool merge, bool native)
Ian Rogers30fab402012-01-23 15:43:46 -08004177 : buf_(16384 - 16),
4178 type_(0),
Mathieu Chartier36dab362014-07-30 14:59:56 -07004179 chunk_overhead_(0) {
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004180 Reset();
4181 if (native) {
Ian Rogers30fab402012-01-23 15:43:46 -08004182 type_ = CHUNK_TYPE("NHSG");
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004183 } else {
Ian Rogers30fab402012-01-23 15:43:46 -08004184 type_ = merge ? CHUNK_TYPE("HPSG") : CHUNK_TYPE("HPSO");
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004185 }
4186 }
4187
4188 ~HeapChunkContext() {
Ian Rogers30fab402012-01-23 15:43:46 -08004189 if (p_ > &buf_[0]) {
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004190 Flush();
4191 }
4192 }
4193
Mathieu Chartier36dab362014-07-30 14:59:56 -07004194 void SetChunkOverhead(size_t chunk_overhead) {
4195 chunk_overhead_ = chunk_overhead;
4196 }
4197
4198 void ResetStartOfNextChunk() {
4199 startOfNextMemoryChunk_ = nullptr;
4200 }
4201
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004202 void EnsureHeader(const void* chunk_ptr) {
Ian Rogers30fab402012-01-23 15:43:46 -08004203 if (!needHeader_) {
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004204 return;
4205 }
4206
4207 // Start a new HPSx chunk.
Brian Carlstrom7934ac22013-07-26 10:54:15 -07004208 JDWP::Write4BE(&p_, 1); // Heap id (bogus; we only have one heap).
4209 JDWP::Write1BE(&p_, 8); // Size of allocation unit, in bytes.
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004210
Brian Carlstrom7934ac22013-07-26 10:54:15 -07004211 JDWP::Write4BE(&p_, reinterpret_cast<uintptr_t>(chunk_ptr)); // virtual address of segment start.
4212 JDWP::Write4BE(&p_, 0); // offset of this piece (relative to the virtual address).
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004213 // [u4]: length of piece, in allocation units
4214 // 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 -08004215 pieceLenField_ = p_;
4216 JDWP::Write4BE(&p_, 0x55555555);
4217 needHeader_ = false;
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004218 }
4219
Ian Rogersb726dcb2012-09-05 08:57:23 -07004220 void Flush() SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Ian Rogersc0542af2014-09-03 16:16:56 -07004221 if (pieceLenField_ == nullptr) {
Ian Rogersd636b062013-01-18 17:51:18 -08004222 // Flush immediately post Reset (maybe back-to-back Flush). Ignore.
4223 CHECK(needHeader_);
4224 return;
4225 }
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004226 // Patch the "length of piece" field.
Ian Rogers30fab402012-01-23 15:43:46 -08004227 CHECK_LE(&buf_[0], pieceLenField_);
4228 CHECK_LE(pieceLenField_, p_);
4229 JDWP::Set4BE(pieceLenField_, totalAllocationUnits_);
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004230
Ian Rogers30fab402012-01-23 15:43:46 -08004231 Dbg::DdmSendChunk(type_, p_ - &buf_[0], &buf_[0]);
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004232 Reset();
4233 }
4234
Mathieu Chartierbc689b72014-12-14 17:01:31 -08004235 static void HeapChunkJavaCallback(void* start, void* end, size_t used_bytes, void* arg)
Ian Rogersb726dcb2012-09-05 08:57:23 -07004236 SHARED_LOCKS_REQUIRED(Locks::heap_bitmap_lock_,
4237 Locks::mutator_lock_) {
Mathieu Chartierbc689b72014-12-14 17:01:31 -08004238 reinterpret_cast<HeapChunkContext*>(arg)->HeapChunkJavaCallback(start, end, used_bytes);
4239 }
4240
4241 static void HeapChunkNativeCallback(void* start, void* end, size_t used_bytes, void* arg)
4242 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
4243 reinterpret_cast<HeapChunkContext*>(arg)->HeapChunkNativeCallback(start, end, used_bytes);
Elliott Hughesa2155262011-11-16 16:26:58 -08004244 }
4245
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004246 private:
Elliott Hughesa2155262011-11-16 16:26:58 -08004247 enum { ALLOCATION_UNIT_SIZE = 8 };
4248
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004249 void Reset() {
Ian Rogers30fab402012-01-23 15:43:46 -08004250 p_ = &buf_[0];
Mathieu Chartier36dab362014-07-30 14:59:56 -07004251 ResetStartOfNextChunk();
Ian Rogers30fab402012-01-23 15:43:46 -08004252 totalAllocationUnits_ = 0;
4253 needHeader_ = true;
Ian Rogersc0542af2014-09-03 16:16:56 -07004254 pieceLenField_ = nullptr;
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004255 }
4256
Mathieu Chartierbc689b72014-12-14 17:01:31 -08004257 bool IsNative() const {
4258 return type_ == CHUNK_TYPE("NHSG");
4259 }
4260
4261 // Returns true if the object is not an empty chunk.
4262 bool ProcessRecord(void* start, size_t used_bytes) SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Ian Rogers30fab402012-01-23 15:43:46 -08004263 // Note: heap call backs cannot manipulate the heap upon which they are crawling, care is taken
4264 // in the following code not to allocate memory, by ensuring buf_ is of the correct size
Ian Rogers15bf2d32012-08-28 17:33:04 -07004265 if (used_bytes == 0) {
Mathieu Chartierbc689b72014-12-14 17:01:31 -08004266 if (start == nullptr) {
4267 // Reset for start of new heap.
4268 startOfNextMemoryChunk_ = nullptr;
4269 Flush();
4270 }
4271 // Only process in use memory so that free region information
4272 // also includes dlmalloc book keeping.
4273 return false;
Elliott Hughesa2155262011-11-16 16:26:58 -08004274 }
Ian Rogersc0542af2014-09-03 16:16:56 -07004275 if (startOfNextMemoryChunk_ != nullptr) {
Mathieu Chartierbc689b72014-12-14 17:01:31 -08004276 // Transmit any pending free memory. Native free memory of over kMaxFreeLen could be because
4277 // of the use of mmaps, so don't report. If not free memory then start a new segment.
4278 bool flush = true;
4279 if (start > startOfNextMemoryChunk_) {
4280 const size_t kMaxFreeLen = 2 * kPageSize;
4281 void* free_start = startOfNextMemoryChunk_;
4282 void* free_end = start;
4283 const size_t free_len =
4284 reinterpret_cast<uintptr_t>(free_end) - reinterpret_cast<uintptr_t>(free_start);
4285 if (!IsNative() || free_len < kMaxFreeLen) {
4286 AppendChunk(HPSG_STATE(SOLIDITY_FREE, 0), free_start, free_len, IsNative());
4287 flush = false;
Ian Rogers15bf2d32012-08-28 17:33:04 -07004288 }
Mathieu Chartierbc689b72014-12-14 17:01:31 -08004289 }
4290 if (flush) {
4291 startOfNextMemoryChunk_ = nullptr;
4292 Flush();
4293 }
Ian Rogers15bf2d32012-08-28 17:33:04 -07004294 }
Mathieu Chartierbc689b72014-12-14 17:01:31 -08004295 return true;
Ian Rogers15bf2d32012-08-28 17:33:04 -07004296 }
Elliott Hughesa2155262011-11-16 16:26:58 -08004297
Mathieu Chartierbc689b72014-12-14 17:01:31 -08004298 void HeapChunkNativeCallback(void* start, void* /*end*/, size_t used_bytes)
4299 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
4300 if (ProcessRecord(start, used_bytes)) {
4301 uint8_t state = ExamineNativeObject(start);
4302 AppendChunk(state, start, used_bytes + chunk_overhead_, true /*is_native*/);
4303 startOfNextMemoryChunk_ = reinterpret_cast<char*>(start) + used_bytes + chunk_overhead_;
4304 }
4305 }
4306
4307 void HeapChunkJavaCallback(void* start, void* /*end*/, size_t used_bytes)
4308 SHARED_LOCKS_REQUIRED(Locks::heap_bitmap_lock_, Locks::mutator_lock_) {
4309 if (ProcessRecord(start, used_bytes)) {
4310 // Determine the type of this chunk.
4311 // OLD-TODO: if context.merge, see if this chunk is different from the last chunk.
4312 // If it's the same, we should combine them.
4313 uint8_t state = ExamineJavaObject(reinterpret_cast<mirror::Object*>(start));
4314 AppendChunk(state, start, used_bytes + chunk_overhead_, false /*is_native*/);
4315 startOfNextMemoryChunk_ = reinterpret_cast<char*>(start) + used_bytes + chunk_overhead_;
4316 }
4317 }
4318
4319 void AppendChunk(uint8_t state, void* ptr, size_t length, bool is_native)
Ian Rogersb726dcb2012-09-05 08:57:23 -07004320 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Ian Rogers15bf2d32012-08-28 17:33:04 -07004321 // Make sure there's enough room left in the buffer.
4322 // We need to use two bytes for every fractional 256 allocation units used by the chunk plus
4323 // 17 bytes for any header.
Mathieu Chartierbc689b72014-12-14 17:01:31 -08004324 const size_t needed = ((RoundUp(length / ALLOCATION_UNIT_SIZE, 256) / 256) * 2) + 17;
4325 size_t byte_left = &buf_.back() - p_;
4326 if (byte_left < needed) {
4327 if (is_native) {
Pavel Vyssotski7522c742014-12-08 13:38:26 +06004328 // Cannot trigger memory allocation while walking native heap.
Pavel Vyssotski7522c742014-12-08 13:38:26 +06004329 return;
4330 }
Ian Rogers15bf2d32012-08-28 17:33:04 -07004331 Flush();
4332 }
4333
Mathieu Chartierbc689b72014-12-14 17:01:31 -08004334 byte_left = &buf_.back() - p_;
4335 if (byte_left < needed) {
Ian Rogers15bf2d32012-08-28 17:33:04 -07004336 LOG(WARNING) << "Chunk is too big to transmit (chunk_len=" << length << ", "
4337 << needed << " bytes)";
4338 return;
4339 }
4340 EnsureHeader(ptr);
Elliott Hughesa2155262011-11-16 16:26:58 -08004341 // Write out the chunk description.
Ian Rogers15bf2d32012-08-28 17:33:04 -07004342 length /= ALLOCATION_UNIT_SIZE; // Convert to allocation units.
4343 totalAllocationUnits_ += length;
4344 while (length > 256) {
Ian Rogers30fab402012-01-23 15:43:46 -08004345 *p_++ = state | HPSG_PARTIAL;
4346 *p_++ = 255; // length - 1
Ian Rogers15bf2d32012-08-28 17:33:04 -07004347 length -= 256;
Elliott Hughesa2155262011-11-16 16:26:58 -08004348 }
Ian Rogers30fab402012-01-23 15:43:46 -08004349 *p_++ = state;
Ian Rogers15bf2d32012-08-28 17:33:04 -07004350 *p_++ = length - 1;
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004351 }
4352
Mathieu Chartierbc689b72014-12-14 17:01:31 -08004353 uint8_t ExamineNativeObject(const void* p) SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
4354 return p == nullptr ? HPSG_STATE(SOLIDITY_FREE, 0) : HPSG_STATE(SOLIDITY_HARD, KIND_NATIVE);
4355 }
4356
4357 uint8_t ExamineJavaObject(mirror::Object* o)
Ian Rogersef7d42f2014-01-06 12:55:46 -08004358 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_, Locks::heap_bitmap_lock_) {
Ian Rogersc0542af2014-09-03 16:16:56 -07004359 if (o == nullptr) {
Elliott Hughesa2155262011-11-16 16:26:58 -08004360 return HPSG_STATE(SOLIDITY_FREE, 0);
4361 }
Elliott Hughesa2155262011-11-16 16:26:58 -08004362 // It's an allocated chunk. Figure out what it is.
Mathieu Chartierbc689b72014-12-14 17:01:31 -08004363 gc::Heap* heap = Runtime::Current()->GetHeap();
4364 if (!heap->IsLiveObjectLocked(o)) {
4365 LOG(ERROR) << "Invalid object in managed heap: " << o;
Elliott Hughesa2155262011-11-16 16:26:58 -08004366 return HPSG_STATE(SOLIDITY_HARD, KIND_NATIVE);
4367 }
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08004368 mirror::Class* c = o->GetClass();
Ian Rogersc0542af2014-09-03 16:16:56 -07004369 if (c == nullptr) {
Elliott Hughesa2155262011-11-16 16:26:58 -08004370 // The object was probably just created but hasn't been initialized yet.
4371 return HPSG_STATE(SOLIDITY_HARD, KIND_OBJECT);
4372 }
Mathieu Chartierbc689b72014-12-14 17:01:31 -08004373 if (!heap->IsValidObjectAddress(c)) {
Ian Rogers15bf2d32012-08-28 17:33:04 -07004374 LOG(ERROR) << "Invalid class for managed heap object: " << o << " " << c;
Elliott Hughesa2155262011-11-16 16:26:58 -08004375 return HPSG_STATE(SOLIDITY_HARD, KIND_UNKNOWN);
4376 }
Mathieu Chartierf26e1b32015-01-29 10:47:10 -08004377 if (c->GetClass() == nullptr) {
4378 LOG(ERROR) << "Null class of class " << c << " for object " << o;
4379 return HPSG_STATE(SOLIDITY_HARD, KIND_UNKNOWN);
4380 }
Elliott Hughesa2155262011-11-16 16:26:58 -08004381 if (c->IsClassClass()) {
4382 return HPSG_STATE(SOLIDITY_HARD, KIND_CLASS_OBJECT);
4383 }
Elliott Hughesa2155262011-11-16 16:26:58 -08004384 if (c->IsArrayClass()) {
Elliott Hughesa2155262011-11-16 16:26:58 -08004385 switch (c->GetComponentSize()) {
4386 case 1: return HPSG_STATE(SOLIDITY_HARD, KIND_ARRAY_1);
4387 case 2: return HPSG_STATE(SOLIDITY_HARD, KIND_ARRAY_2);
4388 case 4: return HPSG_STATE(SOLIDITY_HARD, KIND_ARRAY_4);
4389 case 8: return HPSG_STATE(SOLIDITY_HARD, KIND_ARRAY_8);
4390 }
4391 }
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004392 return HPSG_STATE(SOLIDITY_HARD, KIND_OBJECT);
4393 }
4394
Ian Rogers30fab402012-01-23 15:43:46 -08004395 std::vector<uint8_t> buf_;
4396 uint8_t* p_;
4397 uint8_t* pieceLenField_;
Ian Rogers15bf2d32012-08-28 17:33:04 -07004398 void* startOfNextMemoryChunk_;
Ian Rogers30fab402012-01-23 15:43:46 -08004399 size_t totalAllocationUnits_;
4400 uint32_t type_;
Ian Rogers30fab402012-01-23 15:43:46 -08004401 bool needHeader_;
Mathieu Chartier36dab362014-07-30 14:59:56 -07004402 size_t chunk_overhead_;
Ian Rogers30fab402012-01-23 15:43:46 -08004403
Elliott Hughesa2155262011-11-16 16:26:58 -08004404 DISALLOW_COPY_AND_ASSIGN(HeapChunkContext);
4405};
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004406
Mathieu Chartier36dab362014-07-30 14:59:56 -07004407static void BumpPointerSpaceCallback(mirror::Object* obj, void* arg)
4408 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) EXCLUSIVE_LOCKS_REQUIRED(Locks::heap_bitmap_lock_) {
4409 const size_t size = RoundUp(obj->SizeOf(), kObjectAlignment);
Mathieu Chartierbc689b72014-12-14 17:01:31 -08004410 HeapChunkContext::HeapChunkJavaCallback(
Mathieu Chartier36dab362014-07-30 14:59:56 -07004411 obj, reinterpret_cast<void*>(reinterpret_cast<uintptr_t>(obj) + size), size, arg);
4412}
4413
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004414void Dbg::DdmSendHeapSegments(bool native) {
Mathieu Chartierbc689b72014-12-14 17:01:31 -08004415 Dbg::HpsgWhen when = native ? gDdmNhsgWhen : gDdmHpsgWhen;
4416 Dbg::HpsgWhat what = native ? gDdmNhsgWhat : gDdmHpsgWhat;
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004417 if (when == HPSG_WHEN_NEVER) {
4418 return;
4419 }
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004420 // Figure out what kind of chunks we'll be sending.
Mathieu Chartierbc689b72014-12-14 17:01:31 -08004421 CHECK(what == HPSG_WHAT_MERGED_OBJECTS || what == HPSG_WHAT_DISTINCT_OBJECTS)
4422 << static_cast<int>(what);
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004423
4424 // First, send a heap start chunk.
4425 uint8_t heap_id[4];
Brian Carlstrom7934ac22013-07-26 10:54:15 -07004426 JDWP::Set4BE(&heap_id[0], 1); // Heap id (bogus; we only have one heap).
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004427 Dbg::DdmSendChunk(native ? CHUNK_TYPE("NHST") : CHUNK_TYPE("HPST"), sizeof(heap_id), heap_id);
Hiroshi Yamauchicf58d4a2013-09-26 14:21:22 -07004428 Thread* self = Thread::Current();
Hiroshi Yamauchicf58d4a2013-09-26 14:21:22 -07004429 Locks::mutator_lock_->AssertSharedHeld(self);
Hiroshi Yamauchicf58d4a2013-09-26 14:21:22 -07004430
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004431 // Send a series of heap segment chunks.
Mathieu Chartierbc689b72014-12-14 17:01:31 -08004432 HeapChunkContext context(what == HPSG_WHAT_MERGED_OBJECTS, native);
Elliott Hughesa2155262011-11-16 16:26:58 -08004433 if (native) {
Ian Rogers872dd822014-10-30 11:19:14 -07004434#if defined(HAVE_ANDROID_OS) && defined(USE_DLMALLOC)
Mathieu Chartierbc689b72014-12-14 17:01:31 -08004435 dlmalloc_inspect_all(HeapChunkContext::HeapChunkNativeCallback, &context);
4436 HeapChunkContext::HeapChunkNativeCallback(nullptr, nullptr, 0, &context); // Indicate end of a space.
Christopher Ferrisc4ddc042014-05-13 14:47:50 -07004437#else
4438 UNIMPLEMENTED(WARNING) << "Native heap inspection is only supported with dlmalloc";
4439#endif
Elliott Hughesa2155262011-11-16 16:26:58 -08004440 } else {
Ian Rogers1d54e732013-05-02 21:10:01 -07004441 gc::Heap* heap = Runtime::Current()->GetHeap();
Mathieu Chartier36dab362014-07-30 14:59:56 -07004442 for (const auto& space : heap->GetContinuousSpaces()) {
4443 if (space->IsDlMallocSpace()) {
Mathieu Chartier4c69d7f2014-10-10 12:45:50 -07004444 ReaderMutexLock mu(self, *Locks::heap_bitmap_lock_);
Mathieu Chartier36dab362014-07-30 14:59:56 -07004445 // dlmalloc's chunk header is 2 * sizeof(size_t), but if the previous chunk is in use for an
4446 // allocation then the first sizeof(size_t) may belong to it.
4447 context.SetChunkOverhead(sizeof(size_t));
Mathieu Chartierbc689b72014-12-14 17:01:31 -08004448 space->AsDlMallocSpace()->Walk(HeapChunkContext::HeapChunkJavaCallback, &context);
Mathieu Chartier36dab362014-07-30 14:59:56 -07004449 } else if (space->IsRosAllocSpace()) {
4450 context.SetChunkOverhead(0);
Mathieu Chartier4c69d7f2014-10-10 12:45:50 -07004451 // Need to acquire the mutator lock before the heap bitmap lock with exclusive access since
4452 // RosAlloc's internal logic doesn't know to release and reacquire the heap bitmap lock.
4453 self->TransitionFromRunnableToSuspended(kSuspended);
4454 ThreadList* tl = Runtime::Current()->GetThreadList();
4455 tl->SuspendAll();
4456 {
4457 ReaderMutexLock mu(self, *Locks::heap_bitmap_lock_);
Mathieu Chartierbc689b72014-12-14 17:01:31 -08004458 space->AsRosAllocSpace()->Walk(HeapChunkContext::HeapChunkJavaCallback, &context);
Mathieu Chartier4c69d7f2014-10-10 12:45:50 -07004459 }
4460 tl->ResumeAll();
4461 self->TransitionFromSuspendedToRunnable();
Mathieu Chartier36dab362014-07-30 14:59:56 -07004462 } else if (space->IsBumpPointerSpace()) {
Mathieu Chartier4c69d7f2014-10-10 12:45:50 -07004463 ReaderMutexLock mu(self, *Locks::heap_bitmap_lock_);
Mathieu Chartier36dab362014-07-30 14:59:56 -07004464 context.SetChunkOverhead(0);
Mathieu Chartier36dab362014-07-30 14:59:56 -07004465 space->AsBumpPointerSpace()->Walk(BumpPointerSpaceCallback, &context);
Mathieu Chartierbc689b72014-12-14 17:01:31 -08004466 HeapChunkContext::HeapChunkJavaCallback(nullptr, nullptr, 0, &context);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08004467 } else if (space->IsRegionSpace()) {
4468 heap->IncrementDisableMovingGC(self);
4469 self->TransitionFromRunnableToSuspended(kSuspended);
4470 ThreadList* tl = Runtime::Current()->GetThreadList();
4471 tl->SuspendAll();
4472 ReaderMutexLock mu(self, *Locks::heap_bitmap_lock_);
4473 context.SetChunkOverhead(0);
4474 space->AsRegionSpace()->Walk(BumpPointerSpaceCallback, &context);
4475 HeapChunkContext::HeapChunkJavaCallback(nullptr, nullptr, 0, &context);
4476 tl->ResumeAll();
4477 self->TransitionFromSuspendedToRunnable();
4478 heap->DecrementDisableMovingGC(self);
Mathieu Chartier36dab362014-07-30 14:59:56 -07004479 } else {
4480 UNIMPLEMENTED(WARNING) << "Not counting objects in space " << *space;
Mathieu Chartierb062fdd2012-07-03 09:51:48 -07004481 }
Mathieu Chartier36dab362014-07-30 14:59:56 -07004482 context.ResetStartOfNextChunk();
Mathieu Chartierb062fdd2012-07-03 09:51:48 -07004483 }
Mathieu Chartier4c69d7f2014-10-10 12:45:50 -07004484 ReaderMutexLock mu(self, *Locks::heap_bitmap_lock_);
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -07004485 // Walk the large objects, these are not in the AllocSpace.
Mathieu Chartier36dab362014-07-30 14:59:56 -07004486 context.SetChunkOverhead(0);
Mathieu Chartierbc689b72014-12-14 17:01:31 -08004487 heap->GetLargeObjectsSpace()->Walk(HeapChunkContext::HeapChunkJavaCallback, &context);
Elliott Hughesa2155262011-11-16 16:26:58 -08004488 }
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004489
4490 // Finally, send a heap end chunk.
4491 Dbg::DdmSendChunk(native ? CHUNK_TYPE("NHEN") : CHUNK_TYPE("HPEN"), sizeof(heap_id), heap_id);
Elliott Hughes767a1472011-10-26 18:49:02 -07004492}
4493
Elliott Hughesb1a58792013-07-11 18:10:58 -07004494static size_t GetAllocTrackerMax() {
4495#ifdef HAVE_ANDROID_OS
4496 // Check whether there's a system property overriding the number of records.
4497 const char* propertyName = "dalvik.vm.allocTrackerMax";
4498 char allocRecordMaxString[PROPERTY_VALUE_MAX];
4499 if (property_get(propertyName, allocRecordMaxString, "") > 0) {
4500 char* end;
4501 size_t value = strtoul(allocRecordMaxString, &end, 10);
4502 if (*end != '\0') {
Ruben Brunk3e47a742013-09-09 17:56:07 -07004503 LOG(ERROR) << "Ignoring " << propertyName << " '" << allocRecordMaxString
4504 << "' --- invalid";
Elliott Hughesb1a58792013-07-11 18:10:58 -07004505 return kDefaultNumAllocRecords;
4506 }
4507 if (!IsPowerOfTwo(value)) {
Ruben Brunk3e47a742013-09-09 17:56:07 -07004508 LOG(ERROR) << "Ignoring " << propertyName << " '" << allocRecordMaxString
4509 << "' --- not power of two";
Elliott Hughesb1a58792013-07-11 18:10:58 -07004510 return kDefaultNumAllocRecords;
4511 }
4512 return value;
4513 }
4514#endif
4515 return kDefaultNumAllocRecords;
4516}
4517
Brian Carlstrom306db812014-09-05 13:01:41 -07004518void Dbg::SetAllocTrackingEnabled(bool enable) {
4519 Thread* self = Thread::Current();
4520 if (enable) {
Sebastien Hertzb98063a2014-03-26 10:57:20 +01004521 {
Brian Carlstrom306db812014-09-05 13:01:41 -07004522 MutexLock mu(self, *Locks::alloc_tracker_lock_);
4523 if (recent_allocation_records_ != nullptr) {
4524 return; // Already enabled, bail.
Sebastien Hertzb98063a2014-03-26 10:57:20 +01004525 }
Brian Carlstrom306db812014-09-05 13:01:41 -07004526 alloc_record_max_ = GetAllocTrackerMax();
4527 LOG(INFO) << "Enabling alloc tracker (" << alloc_record_max_ << " entries of "
4528 << kMaxAllocRecordStackDepth << " frames, taking "
4529 << PrettySize(sizeof(AllocRecord) * alloc_record_max_) << ")";
4530 DCHECK_EQ(alloc_record_head_, 0U);
4531 DCHECK_EQ(alloc_record_count_, 0U);
4532 recent_allocation_records_ = new AllocRecord[alloc_record_max_];
4533 CHECK(recent_allocation_records_ != nullptr);
Elliott Hughes545a0642011-11-08 19:10:03 -08004534 }
Mathieu Chartier9ef78b52014-09-25 17:03:12 -07004535 Runtime::Current()->GetInstrumentation()->InstrumentQuickAllocEntryPoints();
Elliott Hughes545a0642011-11-08 19:10:03 -08004536 } else {
Sebastien Hertzb98063a2014-03-26 10:57:20 +01004537 {
Brian Carlstrom306db812014-09-05 13:01:41 -07004538 ScopedObjectAccess soa(self); // For type_cache_.Clear();
4539 MutexLock mu(self, *Locks::alloc_tracker_lock_);
4540 if (recent_allocation_records_ == nullptr) {
4541 return; // Already disabled, bail.
4542 }
Mathieu Chartier4345c462014-06-27 10:20:14 -07004543 LOG(INFO) << "Disabling alloc tracker";
Sebastien Hertzb98063a2014-03-26 10:57:20 +01004544 delete[] recent_allocation_records_;
Ian Rogersc0542af2014-09-03 16:16:56 -07004545 recent_allocation_records_ = nullptr;
Brian Carlstrom306db812014-09-05 13:01:41 -07004546 alloc_record_head_ = 0;
4547 alloc_record_count_ = 0;
Mathieu Chartier4345c462014-06-27 10:20:14 -07004548 type_cache_.Clear();
Sebastien Hertzb98063a2014-03-26 10:57:20 +01004549 }
Brian Carlstrom306db812014-09-05 13:01:41 -07004550 // If an allocation comes in before we uninstrument, we will safely drop it on the floor.
Mathieu Chartier9ef78b52014-09-25 17:03:12 -07004551 Runtime::Current()->GetInstrumentation()->UninstrumentQuickAllocEntryPoints();
Elliott Hughes545a0642011-11-08 19:10:03 -08004552 }
4553}
4554
Ian Rogers0399dde2012-06-06 17:09:28 -07004555struct AllocRecordStackVisitor : public StackVisitor {
Andreas Gampe277ccbd2014-11-03 21:36:10 -08004556 AllocRecordStackVisitor(Thread* thread, AllocRecord* record_in)
Ian Rogersb726dcb2012-09-05 08:57:23 -07004557 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_)
Andreas Gampe277ccbd2014-11-03 21:36:10 -08004558 : StackVisitor(thread, nullptr), record(record_in), depth(0) {}
Elliott Hughes545a0642011-11-08 19:10:03 -08004559
Ian Rogers00f7d0e2012-07-19 15:28:27 -07004560 // TODO: Enable annotalysis. We know lock is held in constructor, but abstraction confuses
4561 // annotalysis.
4562 bool VisitFrame() NO_THREAD_SAFETY_ANALYSIS {
Elliott Hughes545a0642011-11-08 19:10:03 -08004563 if (depth >= kMaxAllocRecordStackDepth) {
Elliott Hughes530fa002012-03-12 11:44:49 -07004564 return false;
Elliott Hughes545a0642011-11-08 19:10:03 -08004565 }
Brian Carlstromea46f952013-07-30 01:26:50 -07004566 mirror::ArtMethod* m = GetMethod();
Ian Rogers0399dde2012-06-06 17:09:28 -07004567 if (!m->IsRuntimeMethod()) {
Hiroshi Yamauchib5a9e3d2014-06-09 12:11:20 -07004568 record->StackElement(depth)->SetMethod(m);
4569 record->StackElement(depth)->SetDexPc(GetDexPc());
Elliott Hughes530fa002012-03-12 11:44:49 -07004570 ++depth;
Elliott Hughes545a0642011-11-08 19:10:03 -08004571 }
Elliott Hughes530fa002012-03-12 11:44:49 -07004572 return true;
Elliott Hughes545a0642011-11-08 19:10:03 -08004573 }
4574
4575 ~AllocRecordStackVisitor() {
4576 // Clear out any unused stack trace elements.
4577 for (; depth < kMaxAllocRecordStackDepth; ++depth) {
Hiroshi Yamauchib5a9e3d2014-06-09 12:11:20 -07004578 record->StackElement(depth)->SetMethod(nullptr);
4579 record->StackElement(depth)->SetDexPc(0);
Elliott Hughes545a0642011-11-08 19:10:03 -08004580 }
4581 }
4582
4583 AllocRecord* record;
4584 size_t depth;
4585};
4586
Ian Rogers844506b2014-09-12 19:59:33 -07004587void Dbg::RecordAllocation(Thread* self, mirror::Class* type, size_t byte_count) {
Brian Carlstrom306db812014-09-05 13:01:41 -07004588 MutexLock mu(self, *Locks::alloc_tracker_lock_);
Ian Rogersc0542af2014-09-03 16:16:56 -07004589 if (recent_allocation_records_ == nullptr) {
Brian Carlstrom306db812014-09-05 13:01:41 -07004590 // In the process of shutting down recording, bail.
Elliott Hughes545a0642011-11-08 19:10:03 -08004591 return;
4592 }
4593
4594 // Advance and clip.
Ian Rogers719d1a32014-03-06 12:13:39 -08004595 if (++alloc_record_head_ == alloc_record_max_) {
4596 alloc_record_head_ = 0;
Elliott Hughes545a0642011-11-08 19:10:03 -08004597 }
4598
4599 // Fill in the basics.
Ian Rogers719d1a32014-03-06 12:13:39 -08004600 AllocRecord* record = &recent_allocation_records_[alloc_record_head_];
Hiroshi Yamauchib5a9e3d2014-06-09 12:11:20 -07004601 record->SetType(type);
4602 record->SetByteCount(byte_count);
4603 record->SetThinLockId(self->GetThreadId());
Elliott Hughes545a0642011-11-08 19:10:03 -08004604
4605 // Fill in the stack trace.
Ian Rogers7a22fa62013-01-23 12:16:16 -08004606 AllocRecordStackVisitor visitor(self, record);
Ian Rogers0399dde2012-06-06 17:09:28 -07004607 visitor.WalkStack();
Elliott Hughes545a0642011-11-08 19:10:03 -08004608
Ian Rogers719d1a32014-03-06 12:13:39 -08004609 if (alloc_record_count_ < alloc_record_max_) {
4610 ++alloc_record_count_;
Elliott Hughes545a0642011-11-08 19:10:03 -08004611 }
4612}
4613
Elliott Hughesa8f93cb2012-06-08 17:08:48 -07004614// Returns the index of the head element.
4615//
Brian Carlstrom306db812014-09-05 13:01:41 -07004616// We point at the most-recently-written record, so if alloc_record_count_ is 1
Elliott Hughesa8f93cb2012-06-08 17:08:48 -07004617// we want to use the current element. Take "head+1" and subtract count
4618// from it.
4619//
4620// We need to handle underflow in our circular buffer, so we add
Brian Carlstrom306db812014-09-05 13:01:41 -07004621// alloc_record_max_ and then mask it back down.
Ian Rogers719d1a32014-03-06 12:13:39 -08004622size_t Dbg::HeadIndex() {
4623 return (Dbg::alloc_record_head_ + 1 + Dbg::alloc_record_max_ - Dbg::alloc_record_count_) &
4624 (Dbg::alloc_record_max_ - 1);
Elliott Hughes545a0642011-11-08 19:10:03 -08004625}
4626
4627void Dbg::DumpRecentAllocations() {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07004628 ScopedObjectAccess soa(Thread::Current());
Brian Carlstrom306db812014-09-05 13:01:41 -07004629 MutexLock mu(soa.Self(), *Locks::alloc_tracker_lock_);
Ian Rogersc0542af2014-09-03 16:16:56 -07004630 if (recent_allocation_records_ == nullptr) {
Elliott Hughes545a0642011-11-08 19:10:03 -08004631 LOG(INFO) << "Not recording tracked allocations";
4632 return;
4633 }
4634
4635 // "i" is the head of the list. We want to start at the end of the
4636 // list and move forward to the tail.
Elliott Hughesa8f93cb2012-06-08 17:08:48 -07004637 size_t i = HeadIndex();
Brian Carlstrom306db812014-09-05 13:01:41 -07004638 const uint16_t capped_count = CappedAllocRecordCount(Dbg::alloc_record_count_);
4639 uint16_t count = capped_count;
Elliott Hughes545a0642011-11-08 19:10:03 -08004640
Ian Rogers719d1a32014-03-06 12:13:39 -08004641 LOG(INFO) << "Tracked allocations, (head=" << alloc_record_head_ << " count=" << count << ")";
Elliott Hughes545a0642011-11-08 19:10:03 -08004642 while (count--) {
4643 AllocRecord* record = &recent_allocation_records_[i];
4644
Hiroshi Yamauchib5a9e3d2014-06-09 12:11:20 -07004645 LOG(INFO) << StringPrintf(" Thread %-2d %6zd bytes ", record->ThinLockId(), record->ByteCount())
4646 << PrettyClass(record->Type());
Elliott Hughes545a0642011-11-08 19:10:03 -08004647
4648 for (size_t stack_frame = 0; stack_frame < kMaxAllocRecordStackDepth; ++stack_frame) {
Hiroshi Yamauchib5a9e3d2014-06-09 12:11:20 -07004649 AllocRecordStackTraceElement* stack_element = record->StackElement(stack_frame);
4650 mirror::ArtMethod* m = stack_element->Method();
Ian Rogersc0542af2014-09-03 16:16:56 -07004651 if (m == nullptr) {
Elliott Hughes545a0642011-11-08 19:10:03 -08004652 break;
4653 }
Hiroshi Yamauchib5a9e3d2014-06-09 12:11:20 -07004654 LOG(INFO) << " " << PrettyMethod(m) << " line " << stack_element->LineNumber();
Elliott Hughes545a0642011-11-08 19:10:03 -08004655 }
4656
4657 // pause periodically to help logcat catch up
4658 if ((count % 5) == 0) {
4659 usleep(40000);
4660 }
4661
Ian Rogers719d1a32014-03-06 12:13:39 -08004662 i = (i + 1) & (alloc_record_max_ - 1);
Elliott Hughes545a0642011-11-08 19:10:03 -08004663 }
4664}
4665
4666class StringTable {
4667 public:
4668 StringTable() {
4669 }
4670
Mathieu Chartier4345c462014-06-27 10:20:14 -07004671 void Add(const std::string& str) {
4672 table_.insert(str);
4673 }
4674
4675 void Add(const char* str) {
4676 table_.insert(str);
Elliott Hughes545a0642011-11-08 19:10:03 -08004677 }
4678
Elliott Hughesa8f93cb2012-06-08 17:08:48 -07004679 size_t IndexOf(const char* s) const {
Mathieu Chartier02e25112013-08-14 16:14:24 -07004680 auto it = table_.find(s);
Elliott Hughesa8f93cb2012-06-08 17:08:48 -07004681 if (it == table_.end()) {
4682 LOG(FATAL) << "IndexOf(\"" << s << "\") failed";
4683 }
4684 return std::distance(table_.begin(), it);
Elliott Hughes545a0642011-11-08 19:10:03 -08004685 }
4686
Elliott Hughesa8f93cb2012-06-08 17:08:48 -07004687 size_t Size() const {
Elliott Hughes545a0642011-11-08 19:10:03 -08004688 return table_.size();
4689 }
4690
Elliott Hughesa8f93cb2012-06-08 17:08:48 -07004691 void WriteTo(std::vector<uint8_t>& bytes) const {
Mathieu Chartier02e25112013-08-14 16:14:24 -07004692 for (const std::string& str : table_) {
4693 const char* s = str.c_str();
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08004694 size_t s_len = CountModifiedUtf8Chars(s);
Ian Rogers700a4022014-05-19 16:49:03 -07004695 std::unique_ptr<uint16_t> s_utf16(new uint16_t[s_len]);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08004696 ConvertModifiedUtf8ToUtf16(s_utf16.get(), s);
4697 JDWP::AppendUtf16BE(bytes, s_utf16.get(), s_len);
Elliott Hughes545a0642011-11-08 19:10:03 -08004698 }
4699 }
4700
4701 private:
Elliott Hughesa8f93cb2012-06-08 17:08:48 -07004702 std::set<std::string> table_;
Elliott Hughes545a0642011-11-08 19:10:03 -08004703 DISALLOW_COPY_AND_ASSIGN(StringTable);
4704};
4705
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07004706static const char* GetMethodSourceFile(mirror::ArtMethod* method)
Sebastien Hertz280286a2014-04-28 09:26:50 +02004707 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07004708 DCHECK(method != nullptr);
4709 const char* source_file = method->GetDeclaringClassSourceFile();
Sebastien Hertz280286a2014-04-28 09:26:50 +02004710 return (source_file != nullptr) ? source_file : "";
4711}
4712
Elliott Hughes545a0642011-11-08 19:10:03 -08004713/*
4714 * The data we send to DDMS contains everything we have recorded.
4715 *
4716 * Message header (all values big-endian):
4717 * (1b) message header len (to allow future expansion); includes itself
4718 * (1b) entry header len
4719 * (1b) stack frame len
4720 * (2b) number of entries
4721 * (4b) offset to string table from start of message
4722 * (2b) number of class name strings
4723 * (2b) number of method name strings
4724 * (2b) number of source file name strings
4725 * For each entry:
4726 * (4b) total allocation size
Elliott Hughes221229c2013-01-08 18:17:50 -08004727 * (2b) thread id
Elliott Hughes545a0642011-11-08 19:10:03 -08004728 * (2b) allocated object's class name index
4729 * (1b) stack depth
4730 * For each stack frame:
4731 * (2b) method's class name
4732 * (2b) method name
4733 * (2b) method source file
4734 * (2b) line number, clipped to 32767; -2 if native; -1 if no source
4735 * (xb) class name strings
4736 * (xb) method name strings
4737 * (xb) source file strings
4738 *
4739 * As with other DDM traffic, strings are sent as a 4-byte length
4740 * followed by UTF-16 data.
4741 *
4742 * We send up 16-bit unsigned indexes into string tables. In theory there
Brian Carlstrom306db812014-09-05 13:01:41 -07004743 * can be (kMaxAllocRecordStackDepth * alloc_record_max_) unique strings in
Elliott Hughes545a0642011-11-08 19:10:03 -08004744 * each table, but in practice there should be far fewer.
4745 *
4746 * The chief reason for using a string table here is to keep the size of
4747 * the DDMS message to a minimum. This is partly to make the protocol
4748 * efficient, but also because we have to form the whole thing up all at
4749 * once in a memory buffer.
4750 *
4751 * We use separate string tables for class names, method names, and source
4752 * files to keep the indexes small. There will generally be no overlap
4753 * between the contents of these tables.
4754 */
4755jbyteArray Dbg::GetRecentAllocations() {
Ian Rogerscf7f1912014-10-22 22:06:39 -07004756 if ((false)) {
Elliott Hughes545a0642011-11-08 19:10:03 -08004757 DumpRecentAllocations();
4758 }
4759
Ian Rogers50b35e22012-10-04 10:09:15 -07004760 Thread* self = Thread::Current();
Elliott Hughes545a0642011-11-08 19:10:03 -08004761 std::vector<uint8_t> bytes;
Mathieu Chartier46e811b2013-07-10 17:09:14 -07004762 {
Brian Carlstrom306db812014-09-05 13:01:41 -07004763 MutexLock mu(self, *Locks::alloc_tracker_lock_);
Mathieu Chartier46e811b2013-07-10 17:09:14 -07004764 //
4765 // Part 1: generate string tables.
4766 //
4767 StringTable class_names;
4768 StringTable method_names;
4769 StringTable filenames;
Elliott Hughes545a0642011-11-08 19:10:03 -08004770
Brian Carlstrom306db812014-09-05 13:01:41 -07004771 const uint16_t capped_count = CappedAllocRecordCount(Dbg::alloc_record_count_);
4772 uint16_t count = capped_count;
4773 size_t idx = HeadIndex();
Mathieu Chartier46e811b2013-07-10 17:09:14 -07004774 while (count--) {
4775 AllocRecord* record = &recent_allocation_records_[idx];
Ian Rogers1ff3c982014-08-12 02:30:58 -07004776 std::string temp;
4777 class_names.Add(record->Type()->GetDescriptor(&temp));
Mathieu Chartier46e811b2013-07-10 17:09:14 -07004778 for (size_t i = 0; i < kMaxAllocRecordStackDepth; i++) {
Hiroshi Yamauchib5a9e3d2014-06-09 12:11:20 -07004779 mirror::ArtMethod* m = record->StackElement(i)->Method();
Ian Rogersc0542af2014-09-03 16:16:56 -07004780 if (m != nullptr) {
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07004781 class_names.Add(m->GetDeclaringClassDescriptor());
4782 method_names.Add(m->GetName());
4783 filenames.Add(GetMethodSourceFile(m));
Mathieu Chartier46e811b2013-07-10 17:09:14 -07004784 }
4785 }
Elliott Hughes545a0642011-11-08 19:10:03 -08004786
Ian Rogers719d1a32014-03-06 12:13:39 -08004787 idx = (idx + 1) & (alloc_record_max_ - 1);
Elliott Hughes545a0642011-11-08 19:10:03 -08004788 }
4789
Brian Carlstrom306db812014-09-05 13:01:41 -07004790 LOG(INFO) << "allocation records: " << capped_count;
Mathieu Chartier46e811b2013-07-10 17:09:14 -07004791
4792 //
4793 // Part 2: Generate the output and store it in the buffer.
4794 //
4795
4796 // (1b) message header len (to allow future expansion); includes itself
4797 // (1b) entry header len
4798 // (1b) stack frame len
4799 const int kMessageHeaderLen = 15;
4800 const int kEntryHeaderLen = 9;
4801 const int kStackFrameLen = 8;
4802 JDWP::Append1BE(bytes, kMessageHeaderLen);
4803 JDWP::Append1BE(bytes, kEntryHeaderLen);
4804 JDWP::Append1BE(bytes, kStackFrameLen);
4805
4806 // (2b) number of entries
4807 // (4b) offset to string table from start of message
4808 // (2b) number of class name strings
4809 // (2b) number of method name strings
4810 // (2b) number of source file name strings
Brian Carlstrom306db812014-09-05 13:01:41 -07004811 JDWP::Append2BE(bytes, capped_count);
Mathieu Chartier46e811b2013-07-10 17:09:14 -07004812 size_t string_table_offset = bytes.size();
Brian Carlstrom7934ac22013-07-26 10:54:15 -07004813 JDWP::Append4BE(bytes, 0); // We'll patch this later...
Mathieu Chartier46e811b2013-07-10 17:09:14 -07004814 JDWP::Append2BE(bytes, class_names.Size());
4815 JDWP::Append2BE(bytes, method_names.Size());
4816 JDWP::Append2BE(bytes, filenames.Size());
4817
Mathieu Chartier46e811b2013-07-10 17:09:14 -07004818 idx = HeadIndex();
Ian Rogers1ff3c982014-08-12 02:30:58 -07004819 std::string temp;
Brian Carlstrom306db812014-09-05 13:01:41 -07004820 for (count = capped_count; count != 0; --count) {
Mathieu Chartier46e811b2013-07-10 17:09:14 -07004821 // For each entry:
4822 // (4b) total allocation size
4823 // (2b) thread id
4824 // (2b) allocated object's class name index
4825 // (1b) stack depth
4826 AllocRecord* record = &recent_allocation_records_[idx];
4827 size_t stack_depth = record->GetDepth();
Mathieu Chartierf8322842014-05-16 10:59:25 -07004828 size_t allocated_object_class_name_index =
Ian Rogers1ff3c982014-08-12 02:30:58 -07004829 class_names.IndexOf(record->Type()->GetDescriptor(&temp));
Hiroshi Yamauchib5a9e3d2014-06-09 12:11:20 -07004830 JDWP::Append4BE(bytes, record->ByteCount());
4831 JDWP::Append2BE(bytes, record->ThinLockId());
Mathieu Chartier46e811b2013-07-10 17:09:14 -07004832 JDWP::Append2BE(bytes, allocated_object_class_name_index);
4833 JDWP::Append1BE(bytes, stack_depth);
4834
Mathieu Chartier46e811b2013-07-10 17:09:14 -07004835 for (size_t stack_frame = 0; stack_frame < stack_depth; ++stack_frame) {
4836 // For each stack frame:
4837 // (2b) method's class name
4838 // (2b) method name
4839 // (2b) method source file
4840 // (2b) line number, clipped to 32767; -2 if native; -1 if no source
Hiroshi Yamauchib5a9e3d2014-06-09 12:11:20 -07004841 mirror::ArtMethod* m = record->StackElement(stack_frame)->Method();
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07004842 size_t class_name_index = class_names.IndexOf(m->GetDeclaringClassDescriptor());
4843 size_t method_name_index = method_names.IndexOf(m->GetName());
4844 size_t file_name_index = filenames.IndexOf(GetMethodSourceFile(m));
Mathieu Chartier46e811b2013-07-10 17:09:14 -07004845 JDWP::Append2BE(bytes, class_name_index);
4846 JDWP::Append2BE(bytes, method_name_index);
4847 JDWP::Append2BE(bytes, file_name_index);
Hiroshi Yamauchib5a9e3d2014-06-09 12:11:20 -07004848 JDWP::Append2BE(bytes, record->StackElement(stack_frame)->LineNumber());
Mathieu Chartier46e811b2013-07-10 17:09:14 -07004849 }
Ian Rogers719d1a32014-03-06 12:13:39 -08004850 idx = (idx + 1) & (alloc_record_max_ - 1);
Mathieu Chartier46e811b2013-07-10 17:09:14 -07004851 }
4852
4853 // (xb) class name strings
4854 // (xb) method name strings
4855 // (xb) source file strings
4856 JDWP::Set4BE(&bytes[string_table_offset], bytes.size());
4857 class_names.WriteTo(bytes);
4858 method_names.WriteTo(bytes);
4859 filenames.WriteTo(bytes);
Elliott Hughes545a0642011-11-08 19:10:03 -08004860 }
Ian Rogers50b35e22012-10-04 10:09:15 -07004861 JNIEnv* env = self->GetJniEnv();
Elliott Hughes545a0642011-11-08 19:10:03 -08004862 jbyteArray result = env->NewByteArray(bytes.size());
Ian Rogersc0542af2014-09-03 16:16:56 -07004863 if (result != nullptr) {
Elliott Hughes545a0642011-11-08 19:10:03 -08004864 env->SetByteArrayRegion(result, 0, bytes.size(), reinterpret_cast<const jbyte*>(&bytes[0]));
4865 }
4866 return result;
4867}
4868
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07004869mirror::ArtMethod* DeoptimizationRequest::Method() const {
4870 ScopedObjectAccessUnchecked soa(Thread::Current());
4871 return soa.DecodeMethod(method_);
4872}
4873
4874void DeoptimizationRequest::SetMethod(mirror::ArtMethod* m) {
4875 ScopedObjectAccessUnchecked soa(Thread::Current());
4876 method_ = soa.EncodeMethod(m);
4877}
4878
Elliott Hughes872d4ec2011-10-21 17:07:15 -07004879} // namespace art