blob: efd7cc23f6d5214890cd7dcead0b887bd3be5b07 [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 Rogers22d5e732014-07-15 22:23:51 -070028#include "field_helper.h"
Ian Rogers1d54e732013-05-02 21:10:01 -070029#include "gc/accounting/card_table-inl.h"
30#include "gc/space/large_object_space.h"
31#include "gc/space/space-inl.h"
Mathieu Chartiereb8167a2014-05-07 15:43:14 -070032#include "handle_scope.h"
Elliott Hughes64f574f2013-02-20 14:57:12 -080033#include "jdwp/object_registry.h"
Ian Rogers22d5e732014-07-15 22:23:51 -070034#include "method_helper.h"
Brian Carlstromea46f952013-07-30 01:26:50 -070035#include "mirror/art_field-inl.h"
36#include "mirror/art_method-inl.h"
Ian Rogers2dd0e2c2013-01-24 12:42:14 -080037#include "mirror/class.h"
38#include "mirror/class-inl.h"
39#include "mirror/class_loader.h"
Ian Rogers2dd0e2c2013-01-24 12:42:14 -080040#include "mirror/object-inl.h"
41#include "mirror/object_array-inl.h"
Ian Rogersb0fa5dc2014-04-28 16:47:08 -070042#include "mirror/string-inl.h"
Ian Rogers2dd0e2c2013-01-24 12:42:14 -080043#include "mirror/throwable.h"
Sebastien Hertza76a6d42014-03-20 16:40:17 +010044#include "quick/inline_method_analyser.h"
Ian Rogers53b8b092014-03-13 23:45:53 -070045#include "reflection.h"
Elliott Hughesa0e18062012-04-13 15:59:59 -070046#include "safe_map.h"
Elliott Hughes64f574f2013-02-20 14:57:12 -080047#include "scoped_thread_state_change.h"
Elliott Hughes6a5bd492011-10-28 14:33:57 -070048#include "ScopedLocalRef.h"
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -070049#include "ScopedPrimitiveArray.h"
Mathieu Chartiereb8167a2014-05-07 15:43:14 -070050#include "handle_scope-inl.h"
Elliott Hughes475fc232011-10-25 15:00:35 -070051#include "thread_list.h"
Ian Rogers62d6c772013-02-27 08:32:07 -080052#include "throw_location.h"
Ian Rogers2dd0e2c2013-01-24 12:42:14 -080053#include "utf.h"
Sebastien Hertza76a6d42014-03-20 16:40:17 +010054#include "verifier/method_verifier-inl.h"
Elliott Hugheseac76672012-05-24 21:56:51 -070055#include "well_known_classes.h"
Elliott Hughes475fc232011-10-25 15:00:35 -070056
Brian Carlstrom3d92d522013-07-12 09:03:08 -070057#ifdef HAVE_ANDROID_OS
58#include "cutils/properties.h"
59#endif
60
Elliott Hughes872d4ec2011-10-21 17:07:15 -070061namespace art {
62
Brian Carlstrom7934ac22013-07-26 10:54:15 -070063static const size_t kMaxAllocRecordStackDepth = 16; // Max 255.
Brian Carlstrom306db812014-09-05 13:01:41 -070064static const size_t kDefaultNumAllocRecords = 64*1024; // Must be a power of 2. 2BE can hold 64k-1.
65
66// Limit alloc_record_count to the 2BE value that is the limit of the current protocol.
67static uint16_t CappedAllocRecordCount(size_t alloc_record_count) {
68 if (alloc_record_count > 0xffff) {
69 return 0xffff;
70 }
71 return alloc_record_count;
72}
Elliott Hughes475fc232011-10-25 15:00:35 -070073
Hiroshi Yamauchib5a9e3d2014-06-09 12:11:20 -070074class AllocRecordStackTraceElement {
75 public:
76 AllocRecordStackTraceElement() : method_(nullptr), dex_pc_(0) {
Mathieu Chartier412c7fc2014-02-07 12:18:39 -080077 }
78
Hiroshi Yamauchib5a9e3d2014-06-09 12:11:20 -070079 int32_t LineNumber() SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
80 mirror::ArtMethod* method = Method();
81 DCHECK(method != nullptr);
82 return method->GetLineNumFromDexPC(DexPc());
Elliott Hughes545a0642011-11-08 19:10:03 -080083 }
Hiroshi Yamauchib5a9e3d2014-06-09 12:11:20 -070084
85 mirror::ArtMethod* Method() SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Mathieu Chartier4345c462014-06-27 10:20:14 -070086 ScopedObjectAccessUnchecked soa(Thread::Current());
87 return soa.DecodeMethod(method_);
Hiroshi Yamauchib5a9e3d2014-06-09 12:11:20 -070088 }
89
90 void SetMethod(mirror::ArtMethod* m) SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
91 ScopedObjectAccessUnchecked soa(Thread::Current());
Mathieu Chartier4345c462014-06-27 10:20:14 -070092 method_ = soa.EncodeMethod(m);
Hiroshi Yamauchib5a9e3d2014-06-09 12:11:20 -070093 }
94
95 uint32_t DexPc() const {
96 return dex_pc_;
97 }
98
99 void SetDexPc(uint32_t pc) {
100 dex_pc_ = pc;
101 }
102
103 private:
Mathieu Chartier4345c462014-06-27 10:20:14 -0700104 jmethodID method_;
Hiroshi Yamauchib5a9e3d2014-06-09 12:11:20 -0700105 uint32_t dex_pc_;
Elliott Hughes545a0642011-11-08 19:10:03 -0800106};
107
Mathieu Chartier4345c462014-06-27 10:20:14 -0700108jobject Dbg::TypeCache::Add(mirror::Class* t) {
109 ScopedObjectAccessUnchecked soa(Thread::Current());
110 int32_t hash_code = t->IdentityHashCode();
111 auto range = objects_.equal_range(hash_code);
112 for (auto it = range.first; it != range.second; ++it) {
113 if (soa.Decode<mirror::Class*>(it->second) == t) {
114 // Found a matching weak global, return it.
115 return it->second;
116 }
117 }
118 JNIEnv* env = soa.Env();
119 const jobject local_ref = soa.AddLocalReference<jobject>(t);
120 const jobject weak_global = env->NewWeakGlobalRef(local_ref);
121 env->DeleteLocalRef(local_ref);
122 objects_.insert(std::make_pair(hash_code, weak_global));
123 return weak_global;
124}
125
126void Dbg::TypeCache::Clear() {
Brian Carlstrom306db812014-09-05 13:01:41 -0700127 JavaVMExt* vm = Runtime::Current()->GetJavaVM();
128 Thread* self = Thread::Current();
Mathieu Chartier4345c462014-06-27 10:20:14 -0700129 for (const auto& p : objects_) {
Brian Carlstrom306db812014-09-05 13:01:41 -0700130 vm->DeleteWeakGlobalRef(self, p.second);
Mathieu Chartier4345c462014-06-27 10:20:14 -0700131 }
132 objects_.clear();
133}
134
Hiroshi Yamauchib5a9e3d2014-06-09 12:11:20 -0700135class AllocRecord {
136 public:
137 AllocRecord() : type_(nullptr), byte_count_(0), thin_lock_id_(0) {}
Elliott Hughes545a0642011-11-08 19:10:03 -0800138
Hiroshi Yamauchib5a9e3d2014-06-09 12:11:20 -0700139 mirror::Class* Type() SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Mathieu Chartier4345c462014-06-27 10:20:14 -0700140 return down_cast<mirror::Class*>(Thread::Current()->DecodeJObject(type_));
Hiroshi Yamauchib5a9e3d2014-06-09 12:11:20 -0700141 }
142
Brian Carlstrom306db812014-09-05 13:01:41 -0700143 void SetType(mirror::Class* t) SHARED_LOCKS_REQUIRED(Locks::mutator_lock_,
144 Locks::alloc_tracker_lock_) {
145 type_ = Dbg::type_cache_.Add(t);
Hiroshi Yamauchib5a9e3d2014-06-09 12:11:20 -0700146 }
147
148 size_t GetDepth() SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Elliott Hughes545a0642011-11-08 19:10:03 -0800149 size_t depth = 0;
Ian Rogersc0542af2014-09-03 16:16:56 -0700150 while (depth < kMaxAllocRecordStackDepth && stack_[depth].Method() != nullptr) {
Elliott Hughes545a0642011-11-08 19:10:03 -0800151 ++depth;
152 }
153 return depth;
154 }
Mathieu Chartier412c7fc2014-02-07 12:18:39 -0800155
Hiroshi Yamauchib5a9e3d2014-06-09 12:11:20 -0700156 size_t ByteCount() const {
157 return byte_count_;
Mathieu Chartier412c7fc2014-02-07 12:18:39 -0800158 }
Hiroshi Yamauchib5a9e3d2014-06-09 12:11:20 -0700159
160 void SetByteCount(size_t count) {
161 byte_count_ = count;
162 }
163
164 uint16_t ThinLockId() const {
165 return thin_lock_id_;
166 }
167
168 void SetThinLockId(uint16_t id) {
169 thin_lock_id_ = id;
170 }
171
172 AllocRecordStackTraceElement* StackElement(size_t index) {
173 DCHECK_LT(index, kMaxAllocRecordStackDepth);
174 return &stack_[index];
175 }
176
177 private:
178 jobject type_; // This is a weak global.
179 size_t byte_count_;
180 uint16_t thin_lock_id_;
Ian Rogersc0542af2014-09-03 16:16:56 -0700181 AllocRecordStackTraceElement stack_[kMaxAllocRecordStackDepth]; // Unused entries have nullptr method.
Elliott Hughes545a0642011-11-08 19:10:03 -0800182};
183
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -0700184class Breakpoint {
185 public:
186 Breakpoint(mirror::ArtMethod* method, uint32_t dex_pc, bool need_full_deoptimization)
187 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_)
188 : method_(nullptr), dex_pc_(dex_pc), need_full_deoptimization_(need_full_deoptimization) {
189 ScopedObjectAccessUnchecked soa(Thread::Current());
190 method_ = soa.EncodeMethod(method);
191 }
192
193 Breakpoint(const Breakpoint& other) SHARED_LOCKS_REQUIRED(Locks::mutator_lock_)
194 : method_(nullptr), dex_pc_(other.dex_pc_),
195 need_full_deoptimization_(other.need_full_deoptimization_) {
196 ScopedObjectAccessUnchecked soa(Thread::Current());
197 method_ = soa.EncodeMethod(other.Method());
198 }
199
200 mirror::ArtMethod* Method() const SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
201 ScopedObjectAccessUnchecked soa(Thread::Current());
202 return soa.DecodeMethod(method_);
203 }
204
205 uint32_t DexPc() const {
206 return dex_pc_;
207 }
208
209 bool NeedFullDeoptimization() const {
210 return need_full_deoptimization_;
211 }
212
213 private:
Sebastien Hertza76a6d42014-03-20 16:40:17 +0100214 // The location of this breakpoint.
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -0700215 jmethodID method_;
216 uint32_t dex_pc_;
Sebastien Hertza76a6d42014-03-20 16:40:17 +0100217
218 // Indicates whether breakpoint needs full deoptimization or selective deoptimization.
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -0700219 bool need_full_deoptimization_;
Elliott Hughes86964332012-02-15 19:37:42 -0800220};
221
Sebastien Hertzed2be172014-08-19 15:33:43 +0200222static std::ostream& operator<<(std::ostream& os, const Breakpoint& rhs)
Ian Rogersb726dcb2012-09-05 08:57:23 -0700223 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -0700224 os << StringPrintf("Breakpoint[%s @%#x]", PrettyMethod(rhs.Method()).c_str(), rhs.DexPc());
Elliott Hughes86964332012-02-15 19:37:42 -0800225 return os;
226}
227
Sebastien Hertz3f52eaf2014-04-04 17:50:18 +0200228class DebugInstrumentationListener FINAL : public instrumentation::InstrumentationListener {
Ian Rogers62d6c772013-02-27 08:32:07 -0800229 public:
230 DebugInstrumentationListener() {}
231 virtual ~DebugInstrumentationListener() {}
232
Sebastien Hertz3f52eaf2014-04-04 17:50:18 +0200233 void MethodEntered(Thread* thread, mirror::Object* this_object, mirror::ArtMethod* method,
234 uint32_t dex_pc)
235 OVERRIDE SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Ian Rogers62d6c772013-02-27 08:32:07 -0800236 if (method->IsNative()) {
237 // TODO: post location events is a suspension point and native method entry stubs aren't.
238 return;
239 }
Sebastien Hertz8379b222014-02-24 17:38:15 +0100240 Dbg::UpdateDebugger(thread, this_object, method, 0, Dbg::kMethodEntry, nullptr);
Ian Rogers62d6c772013-02-27 08:32:07 -0800241 }
242
Sebastien Hertz3f52eaf2014-04-04 17:50:18 +0200243 void MethodExited(Thread* thread, mirror::Object* this_object, mirror::ArtMethod* method,
244 uint32_t dex_pc, const JValue& return_value)
245 OVERRIDE SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Ian Rogers62d6c772013-02-27 08:32:07 -0800246 if (method->IsNative()) {
247 // TODO: post location events is a suspension point and native method entry stubs aren't.
248 return;
249 }
Sebastien Hertz8379b222014-02-24 17:38:15 +0100250 Dbg::UpdateDebugger(thread, this_object, method, dex_pc, Dbg::kMethodExit, &return_value);
Ian Rogers62d6c772013-02-27 08:32:07 -0800251 }
252
Sebastien Hertz3f52eaf2014-04-04 17:50:18 +0200253 void MethodUnwind(Thread* thread, mirror::Object* this_object, mirror::ArtMethod* method,
254 uint32_t dex_pc)
255 OVERRIDE SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Ian Rogers62d6c772013-02-27 08:32:07 -0800256 // We're not recorded to listen to this kind of event, so complain.
257 LOG(ERROR) << "Unexpected method unwind event in debugger " << PrettyMethod(method)
Sebastien Hertz51db44a2013-11-19 10:00:29 +0100258 << " " << dex_pc;
Ian Rogers62d6c772013-02-27 08:32:07 -0800259 }
260
Sebastien Hertz3f52eaf2014-04-04 17:50:18 +0200261 void DexPcMoved(Thread* thread, mirror::Object* this_object, mirror::ArtMethod* method,
262 uint32_t new_dex_pc)
263 OVERRIDE SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Sebastien Hertz8379b222014-02-24 17:38:15 +0100264 Dbg::UpdateDebugger(thread, this_object, method, new_dex_pc, 0, nullptr);
Ian Rogers62d6c772013-02-27 08:32:07 -0800265 }
266
Sebastien Hertz3f52eaf2014-04-04 17:50:18 +0200267 void FieldRead(Thread* thread, mirror::Object* this_object, mirror::ArtMethod* method,
268 uint32_t dex_pc, mirror::ArtField* field)
269 OVERRIDE SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
270 Dbg::PostFieldAccessEvent(method, dex_pc, this_object, field);
Ian Rogers62d6c772013-02-27 08:32:07 -0800271 }
Sebastien Hertz3f52eaf2014-04-04 17:50:18 +0200272
273 void FieldWritten(Thread* thread, mirror::Object* this_object, mirror::ArtMethod* method,
274 uint32_t dex_pc, mirror::ArtField* field, const JValue& field_value)
275 OVERRIDE SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
276 Dbg::PostFieldModificationEvent(method, dex_pc, this_object, field, &field_value);
277 }
278
279 void ExceptionCaught(Thread* thread, const ThrowLocation& throw_location,
280 mirror::ArtMethod* catch_method, uint32_t catch_dex_pc,
281 mirror::Throwable* exception_object)
282 OVERRIDE SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
283 Dbg::PostException(throw_location, catch_method, catch_dex_pc, exception_object);
284 }
285
286 private:
287 DISALLOW_COPY_AND_ASSIGN(DebugInstrumentationListener);
Ian Rogers62d6c772013-02-27 08:32:07 -0800288} gDebugInstrumentationListener;
289
Elliott Hughes4ffd3132011-10-24 12:06:42 -0700290// JDWP is allowed unless the Zygote forbids it.
291static bool gJdwpAllowed = true;
292
Elliott Hughesc0f09332012-03-26 13:27:06 -0700293// Was there a -Xrunjdwp or -agentlib:jdwp= argument on the command line?
Elliott Hughes3bb81562011-10-21 18:52:59 -0700294static bool gJdwpConfigured = false;
295
Elliott Hughesc0f09332012-03-26 13:27:06 -0700296// Broken-down JDWP options. (Only valid if IsJdwpConfigured() is true.)
Elliott Hughes376a7a02011-10-24 18:35:55 -0700297static JDWP::JdwpOptions gJdwpOptions;
Elliott Hughes3bb81562011-10-21 18:52:59 -0700298
299// Runtime JDWP state.
Ian Rogersc0542af2014-09-03 16:16:56 -0700300static JDWP::JdwpState* gJdwpState = nullptr;
Elliott Hughes3bb81562011-10-21 18:52:59 -0700301static bool gDebuggerConnected; // debugger or DDMS is connected.
302static bool gDebuggerActive; // debugger is making requests.
Elliott Hughes86964332012-02-15 19:37:42 -0800303static bool gDisposed; // debugger called VirtualMachine.Dispose, so we should drop the connection.
Elliott Hughes3bb81562011-10-21 18:52:59 -0700304
Elliott Hughes47fce012011-10-25 18:37:19 -0700305static bool gDdmThreadNotification = false;
306
Elliott Hughes767a1472011-10-26 18:49:02 -0700307// DDMS GC-related settings.
308static Dbg::HpifWhen gDdmHpifWhen = Dbg::HPIF_WHEN_NEVER;
309static Dbg::HpsgWhen gDdmHpsgWhen = Dbg::HPSG_WHEN_NEVER;
310static Dbg::HpsgWhat gDdmHpsgWhat;
311static Dbg::HpsgWhen gDdmNhsgWhen = Dbg::HPSG_WHEN_NEVER;
312static Dbg::HpsgWhat gDdmNhsgWhat;
313
Ian Rogers719d1a32014-03-06 12:13:39 -0800314static ObjectRegistry* gRegistry = nullptr;
Elliott Hughes475fc232011-10-25 15:00:35 -0700315
Elliott Hughes545a0642011-11-08 19:10:03 -0800316// Recent allocation tracking.
Ian Rogers719d1a32014-03-06 12:13:39 -0800317AllocRecord* Dbg::recent_allocation_records_ = nullptr; // TODO: CircularBuffer<AllocRecord>
318size_t Dbg::alloc_record_max_ = 0;
319size_t Dbg::alloc_record_head_ = 0;
320size_t Dbg::alloc_record_count_ = 0;
Mathieu Chartier4345c462014-06-27 10:20:14 -0700321Dbg::TypeCache Dbg::type_cache_;
Elliott Hughes545a0642011-11-08 19:10:03 -0800322
Sebastien Hertz138dbfc2013-12-04 18:15:25 +0100323// Deoptimization support.
Sebastien Hertz4d25df32014-03-21 17:44:46 +0100324std::vector<DeoptimizationRequest> Dbg::deoptimization_requests_;
325size_t Dbg::full_deoptimization_event_count_ = 0;
Sebastien Hertz7ec2f1c2014-03-27 20:06:47 +0100326size_t Dbg::delayed_full_undeoptimization_count_ = 0;
Sebastien Hertz138dbfc2013-12-04 18:15:25 +0100327
Sebastien Hertz42cd43f2014-05-13 14:15:41 +0200328// Instrumentation event reference counters.
329size_t Dbg::dex_pc_change_event_ref_count_ = 0;
330size_t Dbg::method_enter_event_ref_count_ = 0;
331size_t Dbg::method_exit_event_ref_count_ = 0;
332size_t Dbg::field_read_event_ref_count_ = 0;
333size_t Dbg::field_write_event_ref_count_ = 0;
334size_t Dbg::exception_catch_event_ref_count_ = 0;
335uint32_t Dbg::instrumentation_events_ = 0;
336
Sebastien Hertz138dbfc2013-12-04 18:15:25 +0100337// Breakpoints.
jeffhao09bfc6a2012-12-11 18:11:43 -0800338static std::vector<Breakpoint> gBreakpoints GUARDED_BY(Locks::breakpoint_lock_);
Elliott Hughes86964332012-02-15 19:37:42 -0800339
Mathieu Chartier3b05e9b2014-03-25 09:29:43 -0700340void DebugInvokeReq::VisitRoots(RootCallback* callback, void* arg, uint32_t tid,
341 RootType root_type) {
342 if (receiver != nullptr) {
343 callback(&receiver, arg, tid, root_type);
344 }
345 if (thread != nullptr) {
346 callback(&thread, arg, tid, root_type);
347 }
348 if (klass != nullptr) {
349 callback(reinterpret_cast<mirror::Object**>(&klass), arg, tid, root_type);
350 }
351 if (method != nullptr) {
352 callback(reinterpret_cast<mirror::Object**>(&method), arg, tid, root_type);
353 }
354}
355
Sebastien Hertzbb43b432014-04-14 11:59:08 +0200356void DebugInvokeReq::Clear() {
357 invoke_needed = false;
358 receiver = nullptr;
359 thread = nullptr;
360 klass = nullptr;
361 method = nullptr;
362}
363
Mathieu Chartier3b05e9b2014-03-25 09:29:43 -0700364void SingleStepControl::VisitRoots(RootCallback* callback, void* arg, uint32_t tid,
365 RootType root_type) {
366 if (method != nullptr) {
367 callback(reinterpret_cast<mirror::Object**>(&method), arg, tid, root_type);
368 }
369}
370
Sebastien Hertzbb43b432014-04-14 11:59:08 +0200371bool SingleStepControl::ContainsDexPc(uint32_t dex_pc) const {
372 return dex_pcs.find(dex_pc) == dex_pcs.end();
373}
374
375void SingleStepControl::Clear() {
376 is_active = false;
377 method = nullptr;
378 dex_pcs.clear();
379}
380
Brian Carlstromea46f952013-07-30 01:26:50 -0700381static bool IsBreakpoint(const mirror::ArtMethod* m, uint32_t dex_pc)
jeffhao09bfc6a2012-12-11 18:11:43 -0800382 LOCKS_EXCLUDED(Locks::breakpoint_lock_)
Ian Rogersb726dcb2012-09-05 08:57:23 -0700383 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Sebastien Hertzed2be172014-08-19 15:33:43 +0200384 ReaderMutexLock mu(Thread::Current(), *Locks::breakpoint_lock_);
Sebastien Hertz138dbfc2013-12-04 18:15:25 +0100385 for (size_t i = 0, e = gBreakpoints.size(); i < e; ++i) {
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -0700386 if (gBreakpoints[i].DexPc() == dex_pc && gBreakpoints[i].Method() == m) {
Elliott Hughes86964332012-02-15 19:37:42 -0800387 VLOG(jdwp) << "Hit breakpoint #" << i << ": " << gBreakpoints[i];
388 return true;
389 }
390 }
391 return false;
392}
393
Sebastien Hertz52d131d2014-03-13 16:17:40 +0100394static bool IsSuspendedForDebugger(ScopedObjectAccessUnchecked& soa, Thread* thread)
395 LOCKS_EXCLUDED(Locks::thread_suspend_count_lock_) {
Elliott Hughes9e0c1752013-01-09 14:02:58 -0800396 MutexLock mu(soa.Self(), *Locks::thread_suspend_count_lock_);
397 // A thread may be suspended for GC; in this code, we really want to know whether
398 // there's a debugger suspension active.
399 return thread->IsSuspended() && thread->GetDebugSuspendCount() > 0;
400}
401
Ian Rogersc0542af2014-09-03 16:16:56 -0700402static mirror::Array* DecodeNonNullArray(JDWP::RefTypeId id, JDWP::JdwpError* error)
Ian Rogersb726dcb2012-09-05 08:57:23 -0700403 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Ian Rogersc0542af2014-09-03 16:16:56 -0700404 mirror::Object* o = gRegistry->Get<mirror::Object*>(id, error);
405 if (o == nullptr) {
406 *error = JDWP::ERR_INVALID_OBJECT;
407 return nullptr;
Elliott Hughes436e3722012-02-17 20:01:47 -0800408 }
409 if (!o->IsArrayInstance()) {
Ian Rogersc0542af2014-09-03 16:16:56 -0700410 *error = JDWP::ERR_INVALID_ARRAY;
411 return nullptr;
Elliott Hughes436e3722012-02-17 20:01:47 -0800412 }
Ian Rogersc0542af2014-09-03 16:16:56 -0700413 *error = JDWP::ERR_NONE;
Elliott Hughes436e3722012-02-17 20:01:47 -0800414 return o->AsArray();
415}
416
Ian Rogersc0542af2014-09-03 16:16:56 -0700417static mirror::Class* DecodeClass(JDWP::RefTypeId id, JDWP::JdwpError* error)
Ian Rogersb726dcb2012-09-05 08:57:23 -0700418 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Ian Rogersc0542af2014-09-03 16:16:56 -0700419 mirror::Object* o = gRegistry->Get<mirror::Object*>(id, error);
420 if (o == nullptr) {
421 *error = JDWP::ERR_INVALID_OBJECT;
422 return nullptr;
Elliott Hughes436e3722012-02-17 20:01:47 -0800423 }
424 if (!o->IsClass()) {
Ian Rogersc0542af2014-09-03 16:16:56 -0700425 *error = JDWP::ERR_INVALID_CLASS;
426 return nullptr;
Elliott Hughes436e3722012-02-17 20:01:47 -0800427 }
Ian Rogersc0542af2014-09-03 16:16:56 -0700428 *error = JDWP::ERR_NONE;
Elliott Hughes436e3722012-02-17 20:01:47 -0800429 return o->AsClass();
430}
431
Ian Rogersc0542af2014-09-03 16:16:56 -0700432static Thread* DecodeThread(ScopedObjectAccessUnchecked& soa, JDWP::ObjectId thread_id,
433 JDWP::JdwpError* error)
jeffhaoa77f0f62012-12-05 17:19:31 -0800434 EXCLUSIVE_LOCKS_REQUIRED(Locks::thread_list_lock_)
Ian Rogersb726dcb2012-09-05 08:57:23 -0700435 LOCKS_EXCLUDED(Locks::thread_suspend_count_lock_)
436 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Ian Rogersc0542af2014-09-03 16:16:56 -0700437 mirror::Object* thread_peer = gRegistry->Get<mirror::Object*>(thread_id, error);
438 if (thread_peer == nullptr) {
Elliott Hughes221229c2013-01-08 18:17:50 -0800439 // This isn't even an object.
Ian Rogersc0542af2014-09-03 16:16:56 -0700440 *error = JDWP::ERR_INVALID_OBJECT;
441 return nullptr;
Elliott Hughes436e3722012-02-17 20:01:47 -0800442 }
Elliott Hughes221229c2013-01-08 18:17:50 -0800443
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800444 mirror::Class* java_lang_Thread = soa.Decode<mirror::Class*>(WellKnownClasses::java_lang_Thread);
Elliott Hughes221229c2013-01-08 18:17:50 -0800445 if (!java_lang_Thread->IsAssignableFrom(thread_peer->GetClass())) {
446 // This isn't a thread.
Ian Rogersc0542af2014-09-03 16:16:56 -0700447 *error = JDWP::ERR_INVALID_THREAD;
448 return nullptr;
Elliott Hughes221229c2013-01-08 18:17:50 -0800449 }
450
Ian Rogersc0542af2014-09-03 16:16:56 -0700451 Thread* thread = Thread::FromManagedThread(soa, thread_peer);
452 // If thread is null then this a java.lang.Thread without a Thread*. Must be a un-started or a
453 // zombie.
454 *error = (thread == nullptr) ? JDWP::ERR_THREAD_NOT_ALIVE : JDWP::ERR_NONE;
455 return thread;
Elliott Hughes436e3722012-02-17 20:01:47 -0800456}
457
Elliott Hughes24437992011-11-30 14:49:33 -0800458static JDWP::JdwpTag BasicTagFromDescriptor(const char* descriptor) {
459 // JDWP deliberately uses the descriptor characters' ASCII values for its enum.
460 // Note that by "basic" we mean that we don't get more specific than JT_OBJECT.
461 return static_cast<JDWP::JdwpTag>(descriptor[0]);
462}
463
Ian Rogers1ff3c982014-08-12 02:30:58 -0700464static JDWP::JdwpTag BasicTagFromClass(mirror::Class* klass)
465 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
466 std::string temp;
467 const char* descriptor = klass->GetDescriptor(&temp);
468 return BasicTagFromDescriptor(descriptor);
469}
470
Ian Rogers98379392014-02-24 16:53:16 -0800471static JDWP::JdwpTag TagFromClass(const ScopedObjectAccessUnchecked& soa, mirror::Class* c)
Ian Rogersb726dcb2012-09-05 08:57:23 -0700472 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Ian Rogersc0542af2014-09-03 16:16:56 -0700473 CHECK(c != nullptr);
Elliott Hughes24437992011-11-30 14:49:33 -0800474 if (c->IsArrayClass()) {
475 return JDWP::JT_ARRAY;
476 }
Elliott Hughes24437992011-11-30 14:49:33 -0800477 if (c->IsStringClass()) {
478 return JDWP::JT_STRING;
Elliott Hughes24437992011-11-30 14:49:33 -0800479 }
Ian Rogers98379392014-02-24 16:53:16 -0800480 if (c->IsClassClass()) {
481 return JDWP::JT_CLASS_OBJECT;
482 }
483 {
484 mirror::Class* thread_class = soa.Decode<mirror::Class*>(WellKnownClasses::java_lang_Thread);
485 if (thread_class->IsAssignableFrom(c)) {
486 return JDWP::JT_THREAD;
487 }
488 }
489 {
490 mirror::Class* thread_group_class =
491 soa.Decode<mirror::Class*>(WellKnownClasses::java_lang_ThreadGroup);
492 if (thread_group_class->IsAssignableFrom(c)) {
493 return JDWP::JT_THREAD_GROUP;
494 }
495 }
496 {
497 mirror::Class* class_loader_class =
498 soa.Decode<mirror::Class*>(WellKnownClasses::java_lang_ClassLoader);
499 if (class_loader_class->IsAssignableFrom(c)) {
500 return JDWP::JT_CLASS_LOADER;
501 }
502 }
503 return JDWP::JT_OBJECT;
Elliott Hughes24437992011-11-30 14:49:33 -0800504}
505
506/*
507 * Objects declared to hold Object might actually hold a more specific
508 * type. The debugger may take a special interest in these (e.g. it
509 * wants to display the contents of Strings), so we want to return an
510 * appropriate tag.
511 *
512 * Null objects are tagged JT_OBJECT.
513 */
Ian Rogers98379392014-02-24 16:53:16 -0800514static JDWP::JdwpTag TagFromObject(const ScopedObjectAccessUnchecked& soa, mirror::Object* o)
Ian Rogersb726dcb2012-09-05 08:57:23 -0700515 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Ian Rogersc0542af2014-09-03 16:16:56 -0700516 return (o == nullptr) ? JDWP::JT_OBJECT : TagFromClass(soa, o->GetClass());
Elliott Hughes24437992011-11-30 14:49:33 -0800517}
518
519static bool IsPrimitiveTag(JDWP::JdwpTag tag) {
520 switch (tag) {
521 case JDWP::JT_BOOLEAN:
522 case JDWP::JT_BYTE:
523 case JDWP::JT_CHAR:
524 case JDWP::JT_FLOAT:
525 case JDWP::JT_DOUBLE:
526 case JDWP::JT_INT:
527 case JDWP::JT_LONG:
528 case JDWP::JT_SHORT:
529 case JDWP::JT_VOID:
530 return true;
531 default:
532 return false;
533 }
534}
535
Elliott Hughes3bb81562011-10-21 18:52:59 -0700536/*
537 * Handle one of the JDWP name/value pairs.
538 *
539 * JDWP options are:
540 * help: if specified, show help message and bail
541 * transport: may be dt_socket or dt_shmem
542 * address: for dt_socket, "host:port", or just "port" when listening
543 * server: if "y", wait for debugger to attach; if "n", attach to debugger
544 * timeout: how long to wait for debugger to connect / listen
545 *
546 * Useful with server=n (these aren't supported yet):
547 * onthrow=<exception-name>: connect to debugger when exception thrown
548 * onuncaught=y|n: connect to debugger when uncaught exception thrown
549 * launch=<command-line>: launch the debugger itself
550 *
551 * The "transport" option is required, as is "address" if server=n.
552 */
553static bool ParseJdwpOption(const std::string& name, const std::string& value) {
554 if (name == "transport") {
555 if (value == "dt_socket") {
Elliott Hughes376a7a02011-10-24 18:35:55 -0700556 gJdwpOptions.transport = JDWP::kJdwpTransportSocket;
Elliott Hughes3bb81562011-10-21 18:52:59 -0700557 } else if (value == "dt_android_adb") {
Elliott Hughes376a7a02011-10-24 18:35:55 -0700558 gJdwpOptions.transport = JDWP::kJdwpTransportAndroidAdb;
Elliott Hughes3bb81562011-10-21 18:52:59 -0700559 } else {
560 LOG(ERROR) << "JDWP transport not supported: " << value;
561 return false;
562 }
563 } else if (name == "server") {
564 if (value == "n") {
Elliott Hughes376a7a02011-10-24 18:35:55 -0700565 gJdwpOptions.server = false;
Elliott Hughes3bb81562011-10-21 18:52:59 -0700566 } else if (value == "y") {
Elliott Hughes376a7a02011-10-24 18:35:55 -0700567 gJdwpOptions.server = true;
Elliott Hughes3bb81562011-10-21 18:52:59 -0700568 } else {
569 LOG(ERROR) << "JDWP option 'server' must be 'y' or 'n'";
570 return false;
571 }
572 } else if (name == "suspend") {
573 if (value == "n") {
Elliott Hughes376a7a02011-10-24 18:35:55 -0700574 gJdwpOptions.suspend = false;
Elliott Hughes3bb81562011-10-21 18:52:59 -0700575 } else if (value == "y") {
Elliott Hughes376a7a02011-10-24 18:35:55 -0700576 gJdwpOptions.suspend = true;
Elliott Hughes3bb81562011-10-21 18:52:59 -0700577 } else {
578 LOG(ERROR) << "JDWP option 'suspend' must be 'y' or 'n'";
579 return false;
580 }
581 } else if (name == "address") {
582 /* this is either <port> or <host>:<port> */
583 std::string port_string;
Elliott Hughes376a7a02011-10-24 18:35:55 -0700584 gJdwpOptions.host.clear();
Elliott Hughes3bb81562011-10-21 18:52:59 -0700585 std::string::size_type colon = value.find(':');
586 if (colon != std::string::npos) {
Elliott Hughes376a7a02011-10-24 18:35:55 -0700587 gJdwpOptions.host = value.substr(0, colon);
Elliott Hughes3bb81562011-10-21 18:52:59 -0700588 port_string = value.substr(colon + 1);
589 } else {
590 port_string = value;
591 }
592 if (port_string.empty()) {
593 LOG(ERROR) << "JDWP address missing port: " << value;
594 return false;
595 }
596 char* end;
Elliott Hughesba8eee12012-01-24 20:25:24 -0800597 uint64_t port = strtoul(port_string.c_str(), &end, 10);
598 if (*end != '\0' || port > 0xffff) {
Elliott Hughes3bb81562011-10-21 18:52:59 -0700599 LOG(ERROR) << "JDWP address has junk in port field: " << value;
600 return false;
601 }
Elliott Hughes376a7a02011-10-24 18:35:55 -0700602 gJdwpOptions.port = port;
Elliott Hughes3bb81562011-10-21 18:52:59 -0700603 } else if (name == "launch" || name == "onthrow" || name == "oncaught" || name == "timeout") {
604 /* valid but unsupported */
605 LOG(INFO) << "Ignoring JDWP option '" << name << "'='" << value << "'";
606 } else {
607 LOG(INFO) << "Ignoring unrecognized JDWP option '" << name << "'='" << value << "'";
608 }
609
610 return true;
611}
612
613/*
614 * Parse the latter half of a -Xrunjdwp/-agentlib:jdwp= string, e.g.:
615 * "transport=dt_socket,address=8000,server=y,suspend=n"
616 */
617bool Dbg::ParseJdwpOptions(const std::string& options) {
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -0800618 VLOG(jdwp) << "ParseJdwpOptions: " << options;
Elliott Hughes47fce012011-10-25 18:37:19 -0700619
Elliott Hughes3bb81562011-10-21 18:52:59 -0700620 std::vector<std::string> pairs;
621 Split(options, ',', pairs);
622
623 for (size_t i = 0; i < pairs.size(); ++i) {
624 std::string::size_type equals = pairs[i].find('=');
625 if (equals == std::string::npos) {
626 LOG(ERROR) << "Can't parse JDWP option '" << pairs[i] << "' in '" << options << "'";
627 return false;
628 }
629 ParseJdwpOption(pairs[i].substr(0, equals), pairs[i].substr(equals + 1));
630 }
631
Elliott Hughes376a7a02011-10-24 18:35:55 -0700632 if (gJdwpOptions.transport == JDWP::kJdwpTransportUnknown) {
Elliott Hughes3bb81562011-10-21 18:52:59 -0700633 LOG(ERROR) << "Must specify JDWP transport: " << options;
634 }
Elliott Hughes376a7a02011-10-24 18:35:55 -0700635 if (!gJdwpOptions.server && (gJdwpOptions.host.empty() || gJdwpOptions.port == 0)) {
Elliott Hughes3bb81562011-10-21 18:52:59 -0700636 LOG(ERROR) << "Must specify JDWP host and port when server=n: " << options;
637 return false;
638 }
639
640 gJdwpConfigured = true;
641 return true;
642}
643
Elliott Hughesd1cc8362011-10-24 16:58:50 -0700644void Dbg::StartJdwp() {
Elliott Hughesc0f09332012-03-26 13:27:06 -0700645 if (!gJdwpAllowed || !IsJdwpConfigured()) {
Elliott Hughes376a7a02011-10-24 18:35:55 -0700646 // No JDWP for you!
647 return;
648 }
649
Ian Rogers719d1a32014-03-06 12:13:39 -0800650 CHECK(gRegistry == nullptr);
Elliott Hughes475fc232011-10-25 15:00:35 -0700651 gRegistry = new ObjectRegistry;
652
Elliott Hughesd1cc8362011-10-24 16:58:50 -0700653 // Init JDWP if the debugger is enabled. This may connect out to a
654 // debugger, passively listen for a debugger, or block waiting for a
655 // debugger.
Elliott Hughes376a7a02011-10-24 18:35:55 -0700656 gJdwpState = JDWP::JdwpState::Create(&gJdwpOptions);
Ian Rogersc0542af2014-09-03 16:16:56 -0700657 if (gJdwpState == nullptr) {
Elliott Hughesf8a2df72011-12-01 12:19:54 -0800658 // We probably failed because some other process has the port already, which means that
659 // if we don't abort the user is likely to think they're talking to us when they're actually
660 // talking to that other process.
Elliott Hughes3d30d9b2011-12-07 17:35:48 -0800661 LOG(FATAL) << "Debugger thread failed to initialize";
Elliott Hughesd1cc8362011-10-24 16:58:50 -0700662 }
663
664 // If a debugger has already attached, send the "welcome" message.
665 // This may cause us to suspend all threads.
Elliott Hughes376a7a02011-10-24 18:35:55 -0700666 if (gJdwpState->IsActive()) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700667 ScopedObjectAccess soa(Thread::Current());
Elliott Hughes376a7a02011-10-24 18:35:55 -0700668 if (!gJdwpState->PostVMStart()) {
Elliott Hughes3d30d9b2011-12-07 17:35:48 -0800669 LOG(WARNING) << "Failed to post 'start' message to debugger";
Elliott Hughesd1cc8362011-10-24 16:58:50 -0700670 }
671 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700672}
673
Elliott Hughesd1cc8362011-10-24 16:58:50 -0700674void Dbg::StopJdwp() {
Sebastien Hertzc6345ef2014-08-18 19:26:39 +0200675 // Post VM_DEATH event before the JDWP connection is closed (either by the JDWP thread or the
676 // destruction of gJdwpState).
677 if (gJdwpState != nullptr && gJdwpState->IsActive()) {
678 gJdwpState->PostVMDeath();
679 }
Sebastien Hertz0376e6b2014-02-06 18:12:59 +0100680 // Prevent the JDWP thread from processing JDWP incoming packets after we close the connection.
681 Disposed();
Elliott Hughes376a7a02011-10-24 18:35:55 -0700682 delete gJdwpState;
Ian Rogers719d1a32014-03-06 12:13:39 -0800683 gJdwpState = nullptr;
Elliott Hughes475fc232011-10-25 15:00:35 -0700684 delete gRegistry;
Ian Rogers719d1a32014-03-06 12:13:39 -0800685 gRegistry = nullptr;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700686}
687
Elliott Hughes767a1472011-10-26 18:49:02 -0700688void Dbg::GcDidFinish() {
689 if (gDdmHpifWhen != HPIF_WHEN_NEVER) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700690 ScopedObjectAccess soa(Thread::Current());
Brian Carlstrom4d466a82014-05-08 19:05:29 -0700691 VLOG(jdwp) << "Sending heap info to DDM";
Elliott Hughes7162ad92011-10-27 14:08:42 -0700692 DdmSendHeapInfo(gDdmHpifWhen);
Elliott Hughes767a1472011-10-26 18:49:02 -0700693 }
694 if (gDdmHpsgWhen != HPSG_WHEN_NEVER) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700695 ScopedObjectAccess soa(Thread::Current());
Brian Carlstrom4d466a82014-05-08 19:05:29 -0700696 VLOG(jdwp) << "Dumping heap to DDM";
Elliott Hughes6a5bd492011-10-28 14:33:57 -0700697 DdmSendHeapSegments(false);
Elliott Hughes767a1472011-10-26 18:49:02 -0700698 }
699 if (gDdmNhsgWhen != HPSG_WHEN_NEVER) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700700 ScopedObjectAccess soa(Thread::Current());
Brian Carlstrom4d466a82014-05-08 19:05:29 -0700701 VLOG(jdwp) << "Dumping native heap to DDM";
Elliott Hughes6a5bd492011-10-28 14:33:57 -0700702 DdmSendHeapSegments(true);
Elliott Hughes767a1472011-10-26 18:49:02 -0700703 }
704}
705
Elliott Hughes4ffd3132011-10-24 12:06:42 -0700706void Dbg::SetJdwpAllowed(bool allowed) {
707 gJdwpAllowed = allowed;
708}
709
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700710DebugInvokeReq* Dbg::GetInvokeReq() {
Elliott Hughes475fc232011-10-25 15:00:35 -0700711 return Thread::Current()->GetInvokeReq();
712}
713
714Thread* Dbg::GetDebugThread() {
Ian Rogersc0542af2014-09-03 16:16:56 -0700715 return (gJdwpState != nullptr) ? gJdwpState->GetDebugThread() : nullptr;
Elliott Hughes475fc232011-10-25 15:00:35 -0700716}
717
718void Dbg::ClearWaitForEventThread() {
719 gJdwpState->ClearWaitForEventThread();
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700720}
721
722void Dbg::Connected() {
Elliott Hughes3bb81562011-10-21 18:52:59 -0700723 CHECK(!gDebuggerConnected);
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -0800724 VLOG(jdwp) << "JDWP has attached";
Elliott Hughes3bb81562011-10-21 18:52:59 -0700725 gDebuggerConnected = true;
Elliott Hughes86964332012-02-15 19:37:42 -0800726 gDisposed = false;
727}
728
729void Dbg::Disposed() {
730 gDisposed = true;
731}
732
733bool Dbg::IsDisposed() {
734 return gDisposed;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700735}
736
Elliott Hughesa2155262011-11-16 16:26:58 -0800737void Dbg::GoActive() {
738 // Enable all debugging features, including scans for breakpoints.
739 // This is a no-op if we're already active.
740 // Only called from the JDWP handler thread.
741 if (gDebuggerActive) {
742 return;
743 }
744
Elliott Hughesc0f09332012-03-26 13:27:06 -0700745 {
746 // TODO: dalvik only warned if there were breakpoints left over. clear in Dbg::Disconnected?
Sebastien Hertzed2be172014-08-19 15:33:43 +0200747 ReaderMutexLock mu(Thread::Current(), *Locks::breakpoint_lock_);
Elliott Hughesc0f09332012-03-26 13:27:06 -0700748 CHECK_EQ(gBreakpoints.size(), 0U);
749 }
Elliott Hughesa2155262011-11-16 16:26:58 -0800750
Sebastien Hertz138dbfc2013-12-04 18:15:25 +0100751 {
Brian Carlstrom306db812014-09-05 13:01:41 -0700752 MutexLock mu(Thread::Current(), *Locks::deoptimization_lock_);
Sebastien Hertz4d25df32014-03-21 17:44:46 +0100753 CHECK_EQ(deoptimization_requests_.size(), 0U);
754 CHECK_EQ(full_deoptimization_event_count_, 0U);
Sebastien Hertz7ec2f1c2014-03-27 20:06:47 +0100755 CHECK_EQ(delayed_full_undeoptimization_count_, 0U);
Sebastien Hertz42cd43f2014-05-13 14:15:41 +0200756 CHECK_EQ(dex_pc_change_event_ref_count_, 0U);
757 CHECK_EQ(method_enter_event_ref_count_, 0U);
758 CHECK_EQ(method_exit_event_ref_count_, 0U);
759 CHECK_EQ(field_read_event_ref_count_, 0U);
760 CHECK_EQ(field_write_event_ref_count_, 0U);
761 CHECK_EQ(exception_catch_event_ref_count_, 0U);
Sebastien Hertz138dbfc2013-12-04 18:15:25 +0100762 }
763
Ian Rogers62d6c772013-02-27 08:32:07 -0800764 Runtime* runtime = Runtime::Current();
765 runtime->GetThreadList()->SuspendAll();
766 Thread* self = Thread::Current();
767 ThreadState old_state = self->SetStateUnsafe(kRunnable);
768 CHECK_NE(old_state, kRunnable);
Sebastien Hertz138dbfc2013-12-04 18:15:25 +0100769 runtime->GetInstrumentation()->EnableDeoptimization();
Sebastien Hertz42cd43f2014-05-13 14:15:41 +0200770 instrumentation_events_ = 0;
Elliott Hughesa2155262011-11-16 16:26:58 -0800771 gDebuggerActive = true;
Ian Rogers62d6c772013-02-27 08:32:07 -0800772 CHECK_EQ(self->SetStateUnsafe(old_state), kRunnable);
773 runtime->GetThreadList()->ResumeAll();
774
775 LOG(INFO) << "Debugger is active";
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700776}
777
778void Dbg::Disconnected() {
Elliott Hughes234ab152011-10-26 14:02:26 -0700779 CHECK(gDebuggerConnected);
780
Elliott Hughesc0f09332012-03-26 13:27:06 -0700781 LOG(INFO) << "Debugger is no longer active";
Elliott Hughes234ab152011-10-26 14:02:26 -0700782
Ian Rogers62d6c772013-02-27 08:32:07 -0800783 // Suspend all threads and exclusively acquire the mutator lock. Set the state of the thread
784 // to kRunnable to avoid scoped object access transitions. Remove the debugger as a listener
785 // and clear the object registry.
786 Runtime* runtime = Runtime::Current();
787 runtime->GetThreadList()->SuspendAll();
788 Thread* self = Thread::Current();
789 ThreadState old_state = self->SetStateUnsafe(kRunnable);
Sebastien Hertzaaea7342014-02-25 15:10:04 +0100790
791 // Debugger may not be active at this point.
792 if (gDebuggerActive) {
793 {
794 // Since we're going to disable deoptimization, we clear the deoptimization requests queue.
795 // This prevents us from having any pending deoptimization request when the debugger attaches
796 // to us again while no event has been requested yet.
Brian Carlstrom306db812014-09-05 13:01:41 -0700797 MutexLock mu(Thread::Current(), *Locks::deoptimization_lock_);
Sebastien Hertz4d25df32014-03-21 17:44:46 +0100798 deoptimization_requests_.clear();
799 full_deoptimization_event_count_ = 0U;
Sebastien Hertz7ec2f1c2014-03-27 20:06:47 +0100800 delayed_full_undeoptimization_count_ = 0U;
Sebastien Hertzaaea7342014-02-25 15:10:04 +0100801 }
Sebastien Hertz42cd43f2014-05-13 14:15:41 +0200802 if (instrumentation_events_ != 0) {
803 runtime->GetInstrumentation()->RemoveListener(&gDebugInstrumentationListener,
804 instrumentation_events_);
805 instrumentation_events_ = 0;
806 }
Sebastien Hertzaaea7342014-02-25 15:10:04 +0100807 runtime->GetInstrumentation()->DisableDeoptimization();
808 gDebuggerActive = false;
Sebastien Hertz138dbfc2013-12-04 18:15:25 +0100809 }
Elliott Hughes234ab152011-10-26 14:02:26 -0700810 gRegistry->Clear();
811 gDebuggerConnected = false;
Ian Rogers62d6c772013-02-27 08:32:07 -0800812 CHECK_EQ(self->SetStateUnsafe(old_state), kRunnable);
813 runtime->GetThreadList()->ResumeAll();
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700814}
815
Elliott Hughesc0f09332012-03-26 13:27:06 -0700816bool Dbg::IsDebuggerActive() {
Elliott Hughes3bb81562011-10-21 18:52:59 -0700817 return gDebuggerActive;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700818}
819
Elliott Hughesc0f09332012-03-26 13:27:06 -0700820bool Dbg::IsJdwpConfigured() {
Elliott Hughes3bb81562011-10-21 18:52:59 -0700821 return gJdwpConfigured;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700822}
823
824int64_t Dbg::LastDebuggerActivity() {
Elliott Hughesca951522011-12-05 12:01:32 -0800825 return gJdwpState->LastDebuggerActivity();
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700826}
827
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700828void Dbg::UndoDebuggerSuspensions() {
Elliott Hughes234ab152011-10-26 14:02:26 -0700829 Runtime::Current()->GetThreadList()->UndoDebuggerSuspensions();
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700830}
831
Elliott Hughes88d63092013-01-09 09:55:54 -0800832std::string Dbg::GetClassName(JDWP::RefTypeId class_id) {
Ian Rogersc0542af2014-09-03 16:16:56 -0700833 JDWP::JdwpError error;
834 mirror::Object* o = gRegistry->Get<mirror::Object*>(class_id, &error);
835 if (o == nullptr) {
836 if (error == JDWP::ERR_NONE) {
837 return "NULL";
838 } else {
839 return StringPrintf("invalid object %p", reinterpret_cast<void*>(class_id));
840 }
Elliott Hughes436e3722012-02-17 20:01:47 -0800841 }
842 if (!o->IsClass()) {
Brian Carlstrom7934ac22013-07-26 10:54:15 -0700843 return StringPrintf("non-class %p", o); // This is only used for debugging output anyway.
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -0800844 }
Ian Rogers1ff3c982014-08-12 02:30:58 -0700845 std::string temp;
846 return DescriptorToName(o->AsClass()->GetDescriptor(&temp));
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700847}
848
Ian Rogersc0542af2014-09-03 16:16:56 -0700849JDWP::JdwpError Dbg::GetClassObject(JDWP::RefTypeId id, JDWP::ObjectId* class_object_id) {
Elliott Hughes436e3722012-02-17 20:01:47 -0800850 JDWP::JdwpError status;
Ian Rogersc0542af2014-09-03 16:16:56 -0700851 mirror::Class* c = DecodeClass(id, &status);
852 if (c == nullptr) {
853 *class_object_id = 0;
Elliott Hughes436e3722012-02-17 20:01:47 -0800854 return status;
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -0800855 }
Ian Rogersc0542af2014-09-03 16:16:56 -0700856 *class_object_id = gRegistry->Add(c);
Elliott Hughes436e3722012-02-17 20:01:47 -0800857 return JDWP::ERR_NONE;
Elliott Hughes86964332012-02-15 19:37:42 -0800858}
859
Ian Rogersc0542af2014-09-03 16:16:56 -0700860JDWP::JdwpError Dbg::GetSuperclass(JDWP::RefTypeId id, JDWP::RefTypeId* superclass_id) {
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -0800861 JDWP::JdwpError status;
Ian Rogersc0542af2014-09-03 16:16:56 -0700862 mirror::Class* c = DecodeClass(id, &status);
863 if (c == nullptr) {
864 *superclass_id = 0;
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -0800865 return status;
866 }
867 if (c->IsInterface()) {
868 // http://code.google.com/p/android/issues/detail?id=20856
Ian Rogersc0542af2014-09-03 16:16:56 -0700869 *superclass_id = 0;
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -0800870 } else {
Ian Rogersc0542af2014-09-03 16:16:56 -0700871 *superclass_id = gRegistry->Add(c->GetSuperClass());
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -0800872 }
873 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700874}
875
Elliott Hughes436e3722012-02-17 20:01:47 -0800876JDWP::JdwpError Dbg::GetClassLoader(JDWP::RefTypeId id, JDWP::ExpandBuf* pReply) {
Ian Rogersc0542af2014-09-03 16:16:56 -0700877 JDWP::JdwpError error;
878 mirror::Object* o = gRegistry->Get<mirror::Object*>(id, &error);
879 if (o == nullptr) {
Elliott Hughes436e3722012-02-17 20:01:47 -0800880 return JDWP::ERR_INVALID_OBJECT;
881 }
882 expandBufAddObjectId(pReply, gRegistry->Add(o->GetClass()->GetClassLoader()));
883 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700884}
885
Elliott Hughes436e3722012-02-17 20:01:47 -0800886JDWP::JdwpError Dbg::GetModifiers(JDWP::RefTypeId id, JDWP::ExpandBuf* pReply) {
Ian Rogersc0542af2014-09-03 16:16:56 -0700887 JDWP::JdwpError error;
888 mirror::Class* c = DecodeClass(id, &error);
889 if (c == nullptr) {
890 return error;
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -0800891 }
Elliott Hughes436e3722012-02-17 20:01:47 -0800892
893 uint32_t access_flags = c->GetAccessFlags() & kAccJavaFlagsMask;
894
Yevgeny Roubande34eea2014-02-15 01:06:03 +0700895 // Set ACC_SUPER. Dex files don't contain this flag but only classes are supposed to have it set,
896 // not interfaces.
Elliott Hughes436e3722012-02-17 20:01:47 -0800897 // Class.getModifiers doesn't return it, but JDWP does, so we set it here.
Yevgeny Roubande34eea2014-02-15 01:06:03 +0700898 if ((access_flags & kAccInterface) == 0) {
899 access_flags |= kAccSuper;
900 }
Elliott Hughes436e3722012-02-17 20:01:47 -0800901
902 expandBufAdd4BE(pReply, access_flags);
903
904 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700905}
906
Ian Rogersc0542af2014-09-03 16:16:56 -0700907JDWP::JdwpError Dbg::GetMonitorInfo(JDWP::ObjectId object_id, JDWP::ExpandBuf* reply) {
908 JDWP::JdwpError error;
909 mirror::Object* o = gRegistry->Get<mirror::Object*>(object_id, &error);
910 if (o == nullptr) {
Elliott Hughesf327e072013-01-09 16:01:26 -0800911 return JDWP::ERR_INVALID_OBJECT;
912 }
913
914 // Ensure all threads are suspended while we read objects' lock words.
915 Thread* self = Thread::Current();
Sebastien Hertz54263242014-03-19 18:16:50 +0100916 CHECK_EQ(self->GetState(), kRunnable);
917 self->TransitionFromRunnableToSuspended(kSuspended);
918 Runtime::Current()->GetThreadList()->SuspendAll();
Elliott Hughesf327e072013-01-09 16:01:26 -0800919
920 MonitorInfo monitor_info(o);
921
Sebastien Hertz54263242014-03-19 18:16:50 +0100922 Runtime::Current()->GetThreadList()->ResumeAll();
923 self->TransitionFromSuspendedToRunnable();
Elliott Hughesf327e072013-01-09 16:01:26 -0800924
Ian Rogersc0542af2014-09-03 16:16:56 -0700925 if (monitor_info.owner_ != nullptr) {
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700926 expandBufAddObjectId(reply, gRegistry->Add(monitor_info.owner_->GetPeer()));
Elliott Hughesf327e072013-01-09 16:01:26 -0800927 } else {
Ian Rogersc0542af2014-09-03 16:16:56 -0700928 expandBufAddObjectId(reply, gRegistry->Add(nullptr));
Elliott Hughesf327e072013-01-09 16:01:26 -0800929 }
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700930 expandBufAdd4BE(reply, monitor_info.entry_count_);
931 expandBufAdd4BE(reply, monitor_info.waiters_.size());
932 for (size_t i = 0; i < monitor_info.waiters_.size(); ++i) {
933 expandBufAddObjectId(reply, gRegistry->Add(monitor_info.waiters_[i]->GetPeer()));
Elliott Hughesf327e072013-01-09 16:01:26 -0800934 }
935 return JDWP::ERR_NONE;
936}
937
Elliott Hughes734b8c62013-01-11 15:32:45 -0800938JDWP::JdwpError Dbg::GetOwnedMonitors(JDWP::ObjectId thread_id,
Ian Rogersc0542af2014-09-03 16:16:56 -0700939 std::vector<JDWP::ObjectId>* monitors,
940 std::vector<uint32_t>* stack_depths) {
Elliott Hughes4993bbc2013-01-10 15:41:25 -0800941 struct OwnedMonitorVisitor : public StackVisitor {
Hiroshi Yamauchib5a9e3d2014-06-09 12:11:20 -0700942 OwnedMonitorVisitor(Thread* thread, Context* context,
Hiroshi Yamauchicc8c5c52014-06-13 15:08:05 -0700943 std::vector<JDWP::ObjectId>* monitor_vector,
Hiroshi Yamauchib5a9e3d2014-06-09 12:11:20 -0700944 std::vector<uint32_t>* stack_depth_vector)
Elliott Hughes4993bbc2013-01-10 15:41:25 -0800945 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_)
Hiroshi Yamauchib5a9e3d2014-06-09 12:11:20 -0700946 : StackVisitor(thread, context), current_stack_depth(0),
947 monitors(monitor_vector), stack_depths(stack_depth_vector) {}
Elliott Hughes4993bbc2013-01-10 15:41:25 -0800948
949 // TODO: Enable annotalysis. We know lock is held in constructor, but abstraction confuses
950 // annotalysis.
951 bool VisitFrame() NO_THREAD_SAFETY_ANALYSIS {
952 if (!GetMethod()->IsRuntimeMethod()) {
953 Monitor::VisitLocks(this, AppendOwnedMonitors, this);
Elliott Hughes734b8c62013-01-11 15:32:45 -0800954 ++current_stack_depth;
Elliott Hughes4993bbc2013-01-10 15:41:25 -0800955 }
956 return true;
957 }
958
Hiroshi Yamauchicc8c5c52014-06-13 15:08:05 -0700959 static void AppendOwnedMonitors(mirror::Object* owned_monitor, void* arg)
960 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Ian Rogers7a22fa62013-01-23 12:16:16 -0800961 OwnedMonitorVisitor* visitor = reinterpret_cast<OwnedMonitorVisitor*>(arg);
Hiroshi Yamauchicc8c5c52014-06-13 15:08:05 -0700962 visitor->monitors->push_back(gRegistry->Add(owned_monitor));
Hiroshi Yamauchib5a9e3d2014-06-09 12:11:20 -0700963 visitor->stack_depths->push_back(visitor->current_stack_depth);
Elliott Hughes4993bbc2013-01-10 15:41:25 -0800964 }
965
Elliott Hughes734b8c62013-01-11 15:32:45 -0800966 size_t current_stack_depth;
Ian Rogersc0542af2014-09-03 16:16:56 -0700967 std::vector<JDWP::ObjectId>* const monitors;
968 std::vector<uint32_t>* const stack_depths;
Elliott Hughes4993bbc2013-01-10 15:41:25 -0800969 };
Elliott Hughes4993bbc2013-01-10 15:41:25 -0800970
Hiroshi Yamauchib5a9e3d2014-06-09 12:11:20 -0700971 ScopedObjectAccessUnchecked soa(Thread::Current());
Hiroshi Yamauchicc8c5c52014-06-13 15:08:05 -0700972 Thread* thread;
Hiroshi Yamauchib5a9e3d2014-06-09 12:11:20 -0700973 {
974 MutexLock mu(soa.Self(), *Locks::thread_list_lock_);
Ian Rogersc0542af2014-09-03 16:16:56 -0700975 JDWP::JdwpError error;
976 thread = DecodeThread(soa, thread_id, &error);
977 if (thread == nullptr) {
Hiroshi Yamauchib5a9e3d2014-06-09 12:11:20 -0700978 return error;
979 }
980 if (!IsSuspendedForDebugger(soa, thread)) {
981 return JDWP::ERR_THREAD_NOT_SUSPENDED;
982 }
Hiroshi Yamauchib5a9e3d2014-06-09 12:11:20 -0700983 }
Hiroshi Yamauchicc8c5c52014-06-13 15:08:05 -0700984 std::unique_ptr<Context> context(Context::Create());
Ian Rogersc0542af2014-09-03 16:16:56 -0700985 OwnedMonitorVisitor visitor(thread, context.get(), monitors, stack_depths);
Hiroshi Yamauchicc8c5c52014-06-13 15:08:05 -0700986 visitor.WalkStack();
Elliott Hughes4993bbc2013-01-10 15:41:25 -0800987 return JDWP::ERR_NONE;
988}
989
Sebastien Hertz52d131d2014-03-13 16:17:40 +0100990JDWP::JdwpError Dbg::GetContendedMonitor(JDWP::ObjectId thread_id,
Ian Rogersc0542af2014-09-03 16:16:56 -0700991 JDWP::ObjectId* contended_monitor) {
Hiroshi Yamauchib5a9e3d2014-06-09 12:11:20 -0700992 mirror::Object* contended_monitor_obj;
Elliott Hughesf9501702013-01-11 11:22:27 -0800993 ScopedObjectAccessUnchecked soa(Thread::Current());
Ian Rogersc0542af2014-09-03 16:16:56 -0700994 *contended_monitor = 0;
Hiroshi Yamauchib5a9e3d2014-06-09 12:11:20 -0700995 {
996 MutexLock mu(soa.Self(), *Locks::thread_list_lock_);
Ian Rogersc0542af2014-09-03 16:16:56 -0700997 JDWP::JdwpError error;
998 Thread* thread = DecodeThread(soa, thread_id, &error);
999 if (thread == nullptr) {
Hiroshi Yamauchib5a9e3d2014-06-09 12:11:20 -07001000 return error;
1001 }
1002 if (!IsSuspendedForDebugger(soa, thread)) {
1003 return JDWP::ERR_THREAD_NOT_SUSPENDED;
1004 }
1005 contended_monitor_obj = Monitor::GetContendedMonitor(thread);
Elliott Hughesf9501702013-01-11 11:22:27 -08001006 }
Hiroshi Yamauchib5a9e3d2014-06-09 12:11:20 -07001007 // Add() requires the thread_list_lock_ not held to avoid the lock
1008 // level violation.
Ian Rogersc0542af2014-09-03 16:16:56 -07001009 *contended_monitor = gRegistry->Add(contended_monitor_obj);
Elliott Hughesf9501702013-01-11 11:22:27 -08001010 return JDWP::ERR_NONE;
1011}
1012
Elliott Hughesec0f83d2013-01-15 16:54:08 -08001013JDWP::JdwpError Dbg::GetInstanceCounts(const std::vector<JDWP::RefTypeId>& class_ids,
Ian Rogersc0542af2014-09-03 16:16:56 -07001014 std::vector<uint64_t>* counts) {
Mathieu Chartier412c7fc2014-02-07 12:18:39 -08001015 gc::Heap* heap = Runtime::Current()->GetHeap();
1016 heap->CollectGarbage(false);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001017 std::vector<mirror::Class*> classes;
Ian Rogersc0542af2014-09-03 16:16:56 -07001018 counts->clear();
Elliott Hughesec0f83d2013-01-15 16:54:08 -08001019 for (size_t i = 0; i < class_ids.size(); ++i) {
Ian Rogersc0542af2014-09-03 16:16:56 -07001020 JDWP::JdwpError error;
1021 mirror::Class* c = DecodeClass(class_ids[i], &error);
1022 if (c == nullptr) {
1023 return error;
Elliott Hughesec0f83d2013-01-15 16:54:08 -08001024 }
1025 classes.push_back(c);
Ian Rogersc0542af2014-09-03 16:16:56 -07001026 counts->push_back(0);
Elliott Hughesec0f83d2013-01-15 16:54:08 -08001027 }
Ian Rogersc0542af2014-09-03 16:16:56 -07001028 heap->CountInstances(classes, false, &(*counts)[0]);
Elliott Hughesec0f83d2013-01-15 16:54:08 -08001029 return JDWP::ERR_NONE;
1030}
1031
Ian Rogersc0542af2014-09-03 16:16:56 -07001032JDWP::JdwpError Dbg::GetInstances(JDWP::RefTypeId class_id, int32_t max_count,
1033 std::vector<JDWP::ObjectId>* instances) {
Mathieu Chartier412c7fc2014-02-07 12:18:39 -08001034 gc::Heap* heap = Runtime::Current()->GetHeap();
1035 // We only want reachable instances, so do a GC.
1036 heap->CollectGarbage(false);
Ian Rogersc0542af2014-09-03 16:16:56 -07001037 JDWP::JdwpError error;
1038 mirror::Class* c = DecodeClass(class_id, &error);
Mathieu Chartier412c7fc2014-02-07 12:18:39 -08001039 if (c == nullptr) {
Ian Rogersc0542af2014-09-03 16:16:56 -07001040 return error;
Elliott Hughes3b78c942013-01-15 17:35:41 -08001041 }
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001042 std::vector<mirror::Object*> raw_instances;
Elliott Hughes3b78c942013-01-15 17:35:41 -08001043 Runtime::Current()->GetHeap()->GetInstances(c, max_count, raw_instances);
1044 for (size_t i = 0; i < raw_instances.size(); ++i) {
Ian Rogersc0542af2014-09-03 16:16:56 -07001045 instances->push_back(gRegistry->Add(raw_instances[i]));
Elliott Hughes3b78c942013-01-15 17:35:41 -08001046 }
1047 return JDWP::ERR_NONE;
1048}
1049
Elliott Hughes0cbaff52013-01-16 15:28:01 -08001050JDWP::JdwpError Dbg::GetReferringObjects(JDWP::ObjectId object_id, int32_t max_count,
Ian Rogersc0542af2014-09-03 16:16:56 -07001051 std::vector<JDWP::ObjectId>* referring_objects) {
Mathieu Chartier412c7fc2014-02-07 12:18:39 -08001052 gc::Heap* heap = Runtime::Current()->GetHeap();
1053 heap->CollectGarbage(false);
Ian Rogersc0542af2014-09-03 16:16:56 -07001054 JDWP::JdwpError error;
1055 mirror::Object* o = gRegistry->Get<mirror::Object*>(object_id, &error);
1056 if (o == nullptr) {
Elliott Hughes0cbaff52013-01-16 15:28:01 -08001057 return JDWP::ERR_INVALID_OBJECT;
1058 }
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001059 std::vector<mirror::Object*> raw_instances;
Mathieu Chartier412c7fc2014-02-07 12:18:39 -08001060 heap->GetReferringObjects(o, max_count, raw_instances);
Elliott Hughes0cbaff52013-01-16 15:28:01 -08001061 for (size_t i = 0; i < raw_instances.size(); ++i) {
Ian Rogersc0542af2014-09-03 16:16:56 -07001062 referring_objects->push_back(gRegistry->Add(raw_instances[i]));
Elliott Hughes0cbaff52013-01-16 15:28:01 -08001063 }
1064 return JDWP::ERR_NONE;
1065}
1066
Ian Rogersc0542af2014-09-03 16:16:56 -07001067JDWP::JdwpError Dbg::DisableCollection(JDWP::ObjectId object_id) {
1068 JDWP::JdwpError error;
1069 mirror::Object* o = gRegistry->Get<mirror::Object*>(object_id, &error);
1070 if (o == nullptr) {
Sebastien Hertze96060a2013-12-11 12:06:28 +01001071 return JDWP::ERR_INVALID_OBJECT;
1072 }
Elliott Hughes64f574f2013-02-20 14:57:12 -08001073 gRegistry->DisableCollection(object_id);
1074 return JDWP::ERR_NONE;
1075}
1076
Ian Rogersc0542af2014-09-03 16:16:56 -07001077JDWP::JdwpError Dbg::EnableCollection(JDWP::ObjectId object_id) {
1078 JDWP::JdwpError error;
1079 mirror::Object* o = gRegistry->Get<mirror::Object*>(object_id, &error);
Sebastien Hertze96060a2013-12-11 12:06:28 +01001080 // Unlike DisableCollection, JDWP specs do not state an invalid object causes an error. The RI
1081 // also ignores these cases and never return an error. However it's not obvious why this command
1082 // should behave differently from DisableCollection and IsCollected commands. So let's be more
1083 // strict and return an error if this happens.
Ian Rogersc0542af2014-09-03 16:16:56 -07001084 if (o == nullptr) {
Sebastien Hertze96060a2013-12-11 12:06:28 +01001085 return JDWP::ERR_INVALID_OBJECT;
1086 }
Elliott Hughes64f574f2013-02-20 14:57:12 -08001087 gRegistry->EnableCollection(object_id);
1088 return JDWP::ERR_NONE;
1089}
1090
Ian Rogersc0542af2014-09-03 16:16:56 -07001091JDWP::JdwpError Dbg::IsCollected(JDWP::ObjectId object_id, bool* is_collected) {
1092 *is_collected = true;
Sebastien Hertz65637eb2014-01-10 17:40:02 +01001093 if (object_id == 0) {
1094 // Null object id is invalid.
Sebastien Hertze96060a2013-12-11 12:06:28 +01001095 return JDWP::ERR_INVALID_OBJECT;
1096 }
Sebastien Hertz65637eb2014-01-10 17:40:02 +01001097 // JDWP specs state an INVALID_OBJECT error is returned if the object ID is not valid. However
1098 // the RI seems to ignore this and assume object has been collected.
Ian Rogersc0542af2014-09-03 16:16:56 -07001099 JDWP::JdwpError error;
1100 mirror::Object* o = gRegistry->Get<mirror::Object*>(object_id, &error);
1101 if (o != nullptr) {
1102 *is_collected = gRegistry->IsCollected(object_id);
Sebastien Hertz65637eb2014-01-10 17:40:02 +01001103 }
Elliott Hughes64f574f2013-02-20 14:57:12 -08001104 return JDWP::ERR_NONE;
1105}
1106
Ian Rogersc0542af2014-09-03 16:16:56 -07001107void Dbg::DisposeObject(JDWP::ObjectId object_id, uint32_t reference_count) {
Elliott Hughes64f574f2013-02-20 14:57:12 -08001108 gRegistry->DisposeObject(object_id, reference_count);
1109}
1110
Sebastien Hertz4d8fd492014-03-28 16:29:41 +01001111static JDWP::JdwpTypeTag GetTypeTag(mirror::Class* klass)
1112 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
1113 DCHECK(klass != nullptr);
1114 if (klass->IsArrayClass()) {
1115 return JDWP::TT_ARRAY;
1116 } else if (klass->IsInterface()) {
1117 return JDWP::TT_INTERFACE;
1118 } else {
1119 return JDWP::TT_CLASS;
1120 }
1121}
1122
Elliott Hughes88d63092013-01-09 09:55:54 -08001123JDWP::JdwpError Dbg::GetReflectedType(JDWP::RefTypeId class_id, JDWP::ExpandBuf* pReply) {
Ian Rogersc0542af2014-09-03 16:16:56 -07001124 JDWP::JdwpError error;
1125 mirror::Class* c = DecodeClass(class_id, &error);
1126 if (c == nullptr) {
1127 return error;
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -08001128 }
Elliott Hughes436e3722012-02-17 20:01:47 -08001129
Sebastien Hertz4d8fd492014-03-28 16:29:41 +01001130 JDWP::JdwpTypeTag type_tag = GetTypeTag(c);
1131 expandBufAdd1(pReply, type_tag);
Elliott Hughes88d63092013-01-09 09:55:54 -08001132 expandBufAddRefTypeId(pReply, class_id);
Elliott Hughes436e3722012-02-17 20:01:47 -08001133 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001134}
1135
Ian Rogersc0542af2014-09-03 16:16:56 -07001136void Dbg::GetClassList(std::vector<JDWP::RefTypeId>* classes) {
Elliott Hughesa2155262011-11-16 16:26:58 -08001137 // Get the complete list of reference classes (i.e. all classes except
1138 // the primitive types).
1139 // Returns a newly-allocated buffer full of RefTypeId values.
1140 struct ClassListCreator {
Ian Rogersc0542af2014-09-03 16:16:56 -07001141 explicit ClassListCreator(std::vector<JDWP::RefTypeId>* classes) : classes(classes) {
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -08001142 }
1143
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001144 static bool Visit(mirror::Class* c, void* arg) {
Elliott Hughesa2155262011-11-16 16:26:58 -08001145 return reinterpret_cast<ClassListCreator*>(arg)->Visit(c);
1146 }
1147
Elliott Hughes64f574f2013-02-20 14:57:12 -08001148 // TODO: Enable annotalysis. We know lock is held in constructor, but abstraction confuses
1149 // annotalysis.
1150 bool Visit(mirror::Class* c) NO_THREAD_SAFETY_ANALYSIS {
Elliott Hughesa2155262011-11-16 16:26:58 -08001151 if (!c->IsPrimitive()) {
Ian Rogersc0542af2014-09-03 16:16:56 -07001152 classes->push_back(gRegistry->AddRefType(c));
Elliott Hughesa2155262011-11-16 16:26:58 -08001153 }
1154 return true;
1155 }
1156
Ian Rogersc0542af2014-09-03 16:16:56 -07001157 std::vector<JDWP::RefTypeId>* const classes;
Elliott Hughesa2155262011-11-16 16:26:58 -08001158 };
1159
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -08001160 ClassListCreator clc(classes);
Sebastien Hertz4537c412014-08-28 14:41:50 +02001161 Runtime::Current()->GetClassLinker()->VisitClassesWithoutClassesLock(ClassListCreator::Visit,
1162 &clc);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001163}
1164
Ian Rogers1ff3c982014-08-12 02:30:58 -07001165JDWP::JdwpError Dbg::GetClassInfo(JDWP::RefTypeId class_id, JDWP::JdwpTypeTag* pTypeTag,
1166 uint32_t* pStatus, std::string* pDescriptor) {
Ian Rogersc0542af2014-09-03 16:16:56 -07001167 JDWP::JdwpError error;
1168 mirror::Class* c = DecodeClass(class_id, &error);
1169 if (c == nullptr) {
1170 return error;
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -08001171 }
1172
Elliott Hughesa2155262011-11-16 16:26:58 -08001173 if (c->IsArrayClass()) {
1174 *pStatus = JDWP::CS_VERIFIED | JDWP::CS_PREPARED;
1175 *pTypeTag = JDWP::TT_ARRAY;
1176 } else {
1177 if (c->IsErroneous()) {
1178 *pStatus = JDWP::CS_ERROR;
1179 } else {
1180 *pStatus = JDWP::CS_VERIFIED | JDWP::CS_PREPARED | JDWP::CS_INITIALIZED;
1181 }
1182 *pTypeTag = c->IsInterface() ? JDWP::TT_INTERFACE : JDWP::TT_CLASS;
1183 }
1184
Ian Rogersc0542af2014-09-03 16:16:56 -07001185 if (pDescriptor != nullptr) {
Ian Rogers1ff3c982014-08-12 02:30:58 -07001186 std::string temp;
1187 *pDescriptor = c->GetDescriptor(&temp);
Elliott Hughesa2155262011-11-16 16:26:58 -08001188 }
Elliott Hughes436e3722012-02-17 20:01:47 -08001189 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001190}
1191
Ian Rogersc0542af2014-09-03 16:16:56 -07001192void Dbg::FindLoadedClassBySignature(const char* descriptor, std::vector<JDWP::RefTypeId>* ids) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001193 std::vector<mirror::Class*> classes;
Elliott Hughes6fa602d2011-12-02 17:54:25 -08001194 Runtime::Current()->GetClassLinker()->LookupClasses(descriptor, classes);
Ian Rogersc0542af2014-09-03 16:16:56 -07001195 ids->clear();
Elliott Hughes6fa602d2011-12-02 17:54:25 -08001196 for (size_t i = 0; i < classes.size(); ++i) {
Ian Rogersc0542af2014-09-03 16:16:56 -07001197 ids->push_back(gRegistry->Add(classes[i]));
Elliott Hughes6fa602d2011-12-02 17:54:25 -08001198 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001199}
1200
Ian Rogersc0542af2014-09-03 16:16:56 -07001201JDWP::JdwpError Dbg::GetReferenceType(JDWP::ObjectId object_id, JDWP::ExpandBuf* pReply) {
1202 JDWP::JdwpError error;
1203 mirror::Object* o = gRegistry->Get<mirror::Object*>(object_id, &error);
1204 if (o == nullptr) {
Elliott Hughes2435a572012-02-17 16:07:41 -08001205 return JDWP::ERR_INVALID_OBJECT;
Elliott Hughes499c5132011-11-17 14:55:11 -08001206 }
Elliott Hughes2435a572012-02-17 16:07:41 -08001207
Sebastien Hertz4d8fd492014-03-28 16:29:41 +01001208 JDWP::JdwpTypeTag type_tag = GetTypeTag(o->GetClass());
Elliott Hughes64f574f2013-02-20 14:57:12 -08001209 JDWP::RefTypeId type_id = gRegistry->AddRefType(o->GetClass());
Elliott Hughes2435a572012-02-17 16:07:41 -08001210
1211 expandBufAdd1(pReply, type_tag);
1212 expandBufAddRefTypeId(pReply, type_id);
1213
1214 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001215}
1216
Ian Rogersfc0e94b2013-09-23 23:51:32 -07001217JDWP::JdwpError Dbg::GetSignature(JDWP::RefTypeId class_id, std::string* signature) {
Ian Rogersc0542af2014-09-03 16:16:56 -07001218 JDWP::JdwpError error;
1219 mirror::Class* c = DecodeClass(class_id, &error);
1220 if (c == nullptr) {
1221 return error;
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -08001222 }
Ian Rogers1ff3c982014-08-12 02:30:58 -07001223 std::string temp;
1224 *signature = c->GetDescriptor(&temp);
Elliott Hughes1fe7afb2012-02-13 17:23:03 -08001225 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001226}
1227
Ian Rogersc0542af2014-09-03 16:16:56 -07001228JDWP::JdwpError Dbg::GetSourceFile(JDWP::RefTypeId class_id, std::string* result) {
1229 JDWP::JdwpError error;
1230 mirror::Class* c = DecodeClass(class_id, &error);
Sebastien Hertz4206eb52014-06-05 10:15:45 +02001231 if (c == nullptr) {
Ian Rogersc0542af2014-09-03 16:16:56 -07001232 return error;
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -08001233 }
Sebastien Hertz4206eb52014-06-05 10:15:45 +02001234 const char* source_file = c->GetSourceFile();
1235 if (source_file == nullptr) {
Sebastien Hertzb7054ba2014-03-13 11:52:31 +01001236 return JDWP::ERR_ABSENT_INFORMATION;
1237 }
Ian Rogersc0542af2014-09-03 16:16:56 -07001238 *result = source_file;
Elliott Hughes436e3722012-02-17 20:01:47 -08001239 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001240}
1241
Ian Rogersc0542af2014-09-03 16:16:56 -07001242JDWP::JdwpError Dbg::GetObjectTag(JDWP::ObjectId object_id, uint8_t* tag) {
Ian Rogers98379392014-02-24 16:53:16 -08001243 ScopedObjectAccessUnchecked soa(Thread::Current());
Ian Rogersc0542af2014-09-03 16:16:56 -07001244 JDWP::JdwpError error;
1245 mirror::Object* o = gRegistry->Get<mirror::Object*>(object_id, &error);
1246 if (error != JDWP::ERR_NONE) {
1247 *tag = JDWP::JT_VOID;
1248 return error;
Elliott Hughes546b9862012-06-20 16:06:13 -07001249 }
Ian Rogersc0542af2014-09-03 16:16:56 -07001250 *tag = TagFromObject(soa, o);
Elliott Hughes546b9862012-06-20 16:06:13 -07001251 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001252}
1253
Elliott Hughesaed4be92011-12-02 16:16:23 -08001254size_t Dbg::GetTagWidth(JDWP::JdwpTag tag) {
Elliott Hughesdbb40792011-11-18 17:05:22 -08001255 switch (tag) {
1256 case JDWP::JT_VOID:
1257 return 0;
1258 case JDWP::JT_BYTE:
1259 case JDWP::JT_BOOLEAN:
1260 return 1;
1261 case JDWP::JT_CHAR:
1262 case JDWP::JT_SHORT:
1263 return 2;
1264 case JDWP::JT_FLOAT:
1265 case JDWP::JT_INT:
1266 return 4;
1267 case JDWP::JT_ARRAY:
1268 case JDWP::JT_OBJECT:
1269 case JDWP::JT_STRING:
1270 case JDWP::JT_THREAD:
1271 case JDWP::JT_THREAD_GROUP:
1272 case JDWP::JT_CLASS_LOADER:
1273 case JDWP::JT_CLASS_OBJECT:
1274 return sizeof(JDWP::ObjectId);
1275 case JDWP::JT_DOUBLE:
1276 case JDWP::JT_LONG:
1277 return 8;
1278 default:
Elliott Hughes3d30d9b2011-12-07 17:35:48 -08001279 LOG(FATAL) << "Unknown tag " << tag;
Elliott Hughesdbb40792011-11-18 17:05:22 -08001280 return -1;
1281 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001282}
1283
Ian Rogersc0542af2014-09-03 16:16:56 -07001284JDWP::JdwpError Dbg::GetArrayLength(JDWP::ObjectId array_id, int32_t* length) {
1285 JDWP::JdwpError error;
1286 mirror::Array* a = DecodeNonNullArray(array_id, &error);
1287 if (a == nullptr) {
1288 return error;
Elliott Hughes24437992011-11-30 14:49:33 -08001289 }
Ian Rogersc0542af2014-09-03 16:16:56 -07001290 *length = a->GetLength();
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -08001291 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001292}
1293
Elliott Hughes88d63092013-01-09 09:55:54 -08001294JDWP::JdwpError Dbg::OutputArray(JDWP::ObjectId array_id, int offset, int count, JDWP::ExpandBuf* pReply) {
Ian Rogersc0542af2014-09-03 16:16:56 -07001295 JDWP::JdwpError error;
1296 mirror::Array* a = DecodeNonNullArray(array_id, &error);
Ian Rogers98379392014-02-24 16:53:16 -08001297 if (a == nullptr) {
Ian Rogersc0542af2014-09-03 16:16:56 -07001298 return error;
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -08001299 }
Elliott Hughes24437992011-11-30 14:49:33 -08001300
1301 if (offset < 0 || count < 0 || offset > a->GetLength() || a->GetLength() - offset < count) {
1302 LOG(WARNING) << __FUNCTION__ << " access out of bounds: offset=" << offset << "; count=" << count;
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -08001303 return JDWP::ERR_INVALID_LENGTH;
Elliott Hughes24437992011-11-30 14:49:33 -08001304 }
Ian Rogers1ff3c982014-08-12 02:30:58 -07001305 JDWP::JdwpTag element_tag = BasicTagFromClass(a->GetClass()->GetComponentType());
1306 expandBufAdd1(pReply, element_tag);
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -08001307 expandBufAdd4BE(pReply, count);
1308
Ian Rogers1ff3c982014-08-12 02:30:58 -07001309 if (IsPrimitiveTag(element_tag)) {
1310 size_t width = GetTagWidth(element_tag);
Elliott Hughes24437992011-11-30 14:49:33 -08001311 uint8_t* dst = expandBufAddSpace(pReply, count * width);
1312 if (width == 8) {
Ian Rogersef7d42f2014-01-06 12:55:46 -08001313 const uint64_t* src8 = reinterpret_cast<uint64_t*>(a->GetRawData(sizeof(uint64_t), 0));
Elliott Hughes24437992011-11-30 14:49:33 -08001314 for (int i = 0; i < count; ++i) JDWP::Write8BE(&dst, src8[offset + i]);
1315 } else if (width == 4) {
Ian Rogersef7d42f2014-01-06 12:55:46 -08001316 const uint32_t* src4 = reinterpret_cast<uint32_t*>(a->GetRawData(sizeof(uint32_t), 0));
Elliott Hughes24437992011-11-30 14:49:33 -08001317 for (int i = 0; i < count; ++i) JDWP::Write4BE(&dst, src4[offset + i]);
1318 } else if (width == 2) {
Ian Rogersef7d42f2014-01-06 12:55:46 -08001319 const uint16_t* src2 = reinterpret_cast<uint16_t*>(a->GetRawData(sizeof(uint16_t), 0));
Elliott Hughes24437992011-11-30 14:49:33 -08001320 for (int i = 0; i < count; ++i) JDWP::Write2BE(&dst, src2[offset + i]);
1321 } else {
Ian Rogersef7d42f2014-01-06 12:55:46 -08001322 const uint8_t* src = reinterpret_cast<uint8_t*>(a->GetRawData(sizeof(uint8_t), 0));
Elliott Hughes24437992011-11-30 14:49:33 -08001323 memcpy(dst, &src[offset * width], count * width);
1324 }
1325 } else {
Ian Rogers98379392014-02-24 16:53:16 -08001326 ScopedObjectAccessUnchecked soa(Thread::Current());
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001327 mirror::ObjectArray<mirror::Object>* oa = a->AsObjectArray<mirror::Object>();
Elliott Hughes24437992011-11-30 14:49:33 -08001328 for (int i = 0; i < count; ++i) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001329 mirror::Object* element = oa->Get(offset + i);
Ian Rogers98379392014-02-24 16:53:16 -08001330 JDWP::JdwpTag specific_tag = (element != nullptr) ? TagFromObject(soa, element)
Ian Rogers1ff3c982014-08-12 02:30:58 -07001331 : element_tag;
Elliott Hughes24437992011-11-30 14:49:33 -08001332 expandBufAdd1(pReply, specific_tag);
1333 expandBufAddObjectId(pReply, gRegistry->Add(element));
1334 }
1335 }
1336
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -08001337 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001338}
1339
Ian Rogersef7d42f2014-01-06 12:55:46 -08001340template <typename T>
Ian Rogersc0542af2014-09-03 16:16:56 -07001341static void CopyArrayData(mirror::Array* a, JDWP::Request* src, int offset, int count)
Ian Rogersef7d42f2014-01-06 12:55:46 -08001342 NO_THREAD_SAFETY_ANALYSIS {
1343 // TODO: fix when annotalysis correctly handles non-member functions.
Elliott Hughes4b9702c2013-02-20 18:13:24 -08001344 DCHECK(a->GetClass()->IsPrimitiveArray());
1345
Ian Rogersef7d42f2014-01-06 12:55:46 -08001346 T* dst = reinterpret_cast<T*>(a->GetRawData(sizeof(T), offset));
Elliott Hughes4b9702c2013-02-20 18:13:24 -08001347 for (int i = 0; i < count; ++i) {
Ian Rogersc0542af2014-09-03 16:16:56 -07001348 *dst++ = src->ReadValue(sizeof(T));
Elliott Hughes4b9702c2013-02-20 18:13:24 -08001349 }
1350}
1351
Elliott Hughes88d63092013-01-09 09:55:54 -08001352JDWP::JdwpError Dbg::SetArrayElements(JDWP::ObjectId array_id, int offset, int count,
Ian Rogersc0542af2014-09-03 16:16:56 -07001353 JDWP::Request* request) {
1354 JDWP::JdwpError error;
1355 mirror::Array* dst = DecodeNonNullArray(array_id, &error);
1356 if (dst == nullptr) {
1357 return error;
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -08001358 }
Elliott Hughesf03b8f62011-12-02 14:26:25 -08001359
Elliott Hughes4b9702c2013-02-20 18:13:24 -08001360 if (offset < 0 || count < 0 || offset > dst->GetLength() || dst->GetLength() - offset < count) {
Elliott Hughesf03b8f62011-12-02 14:26:25 -08001361 LOG(WARNING) << __FUNCTION__ << " access out of bounds: offset=" << offset << "; count=" << count;
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -08001362 return JDWP::ERR_INVALID_LENGTH;
Elliott Hughesf03b8f62011-12-02 14:26:25 -08001363 }
Ian Rogers1ff3c982014-08-12 02:30:58 -07001364 JDWP::JdwpTag element_tag = BasicTagFromClass(dst->GetClass()->GetComponentType());
Elliott Hughesf03b8f62011-12-02 14:26:25 -08001365
Ian Rogers1ff3c982014-08-12 02:30:58 -07001366 if (IsPrimitiveTag(element_tag)) {
1367 size_t width = GetTagWidth(element_tag);
Elliott Hughesf03b8f62011-12-02 14:26:25 -08001368 if (width == 8) {
Elliott Hughes4b9702c2013-02-20 18:13:24 -08001369 CopyArrayData<uint64_t>(dst, request, offset, count);
Elliott Hughesf03b8f62011-12-02 14:26:25 -08001370 } else if (width == 4) {
Elliott Hughes4b9702c2013-02-20 18:13:24 -08001371 CopyArrayData<uint32_t>(dst, request, offset, count);
Elliott Hughesf03b8f62011-12-02 14:26:25 -08001372 } else if (width == 2) {
Elliott Hughes4b9702c2013-02-20 18:13:24 -08001373 CopyArrayData<uint16_t>(dst, request, offset, count);
Elliott Hughesf03b8f62011-12-02 14:26:25 -08001374 } else {
Elliott Hughes4b9702c2013-02-20 18:13:24 -08001375 CopyArrayData<uint8_t>(dst, request, offset, count);
Elliott Hughesf03b8f62011-12-02 14:26:25 -08001376 }
1377 } else {
Elliott Hughes4b9702c2013-02-20 18:13:24 -08001378 mirror::ObjectArray<mirror::Object>* oa = dst->AsObjectArray<mirror::Object>();
Elliott Hughesf03b8f62011-12-02 14:26:25 -08001379 for (int i = 0; i < count; ++i) {
Ian Rogersc0542af2014-09-03 16:16:56 -07001380 JDWP::ObjectId id = request->ReadObjectId();
1381 JDWP::JdwpError error;
1382 mirror::Object* o = gRegistry->Get<mirror::Object*>(id, &error);
1383 if (error != JDWP::ERR_NONE) {
1384 return error;
Elliott Hughes436e3722012-02-17 20:01:47 -08001385 }
Sebastien Hertzd2fe10a2014-01-15 10:20:56 +01001386 oa->Set<false>(offset + i, o);
Elliott Hughesf03b8f62011-12-02 14:26:25 -08001387 }
1388 }
1389
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -08001390 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001391}
1392
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -08001393JDWP::ObjectId Dbg::CreateString(const std::string& str) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001394 return gRegistry->Add(mirror::String::AllocFromModifiedUtf8(Thread::Current(), str.c_str()));
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001395}
1396
Ian Rogersc0542af2014-09-03 16:16:56 -07001397JDWP::JdwpError Dbg::CreateObject(JDWP::RefTypeId class_id, JDWP::ObjectId* new_object) {
1398 JDWP::JdwpError error;
1399 mirror::Class* c = DecodeClass(class_id, &error);
1400 if (c == nullptr) {
1401 *new_object = 0;
1402 return error;
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -08001403 }
Ian Rogersc0542af2014-09-03 16:16:56 -07001404 *new_object = gRegistry->Add(c->AllocObject(Thread::Current()));
Elliott Hughes436e3722012-02-17 20:01:47 -08001405 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001406}
1407
Elliott Hughesbf13d362011-12-08 15:51:37 -08001408/*
1409 * Used by Eclipse's "Display" view to evaluate "new byte[5]" to get "(byte[]) [0, 0, 0, 0, 0]".
1410 */
Elliott Hughes88d63092013-01-09 09:55:54 -08001411JDWP::JdwpError Dbg::CreateArrayObject(JDWP::RefTypeId array_class_id, uint32_t length,
Ian Rogersc0542af2014-09-03 16:16:56 -07001412 JDWP::ObjectId* new_array) {
1413 JDWP::JdwpError error;
1414 mirror::Class* c = DecodeClass(array_class_id, &error);
1415 if (c == nullptr) {
1416 *new_array = 0;
1417 return error;
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -08001418 }
Ian Rogersc0542af2014-09-03 16:16:56 -07001419 *new_array = gRegistry->Add(mirror::Array::Alloc<true>(Thread::Current(), c, length,
1420 c->GetComponentSize(),
1421 Runtime::Current()->GetHeap()->GetCurrentAllocator()));
Elliott Hughes436e3722012-02-17 20:01:47 -08001422 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001423}
1424
Elliott Hughes88d63092013-01-09 09:55:54 -08001425bool Dbg::MatchType(JDWP::RefTypeId instance_class_id, JDWP::RefTypeId class_id) {
Ian Rogersc0542af2014-09-03 16:16:56 -07001426 JDWP::JdwpError error;
1427 mirror::Class* c1 = DecodeClass(instance_class_id, &error);
1428 CHECK(c1 != nullptr);
1429 mirror::Class* c2 = DecodeClass(class_id, &error);
1430 CHECK(c2 != nullptr);
Sebastien Hertz123756a2013-11-27 15:49:42 +01001431 return c2->IsAssignableFrom(c1);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001432}
1433
Brian Carlstromea46f952013-07-30 01:26:50 -07001434static JDWP::FieldId ToFieldId(const mirror::ArtField* f)
Ian Rogersb726dcb2012-09-05 08:57:23 -07001435 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Mathieu Chartier590fee92013-09-13 13:46:47 -07001436 CHECK(!kMovingFields);
Elliott Hughes03181a82011-11-17 17:22:21 -08001437 return static_cast<JDWP::FieldId>(reinterpret_cast<uintptr_t>(f));
Elliott Hughes03181a82011-11-17 17:22:21 -08001438}
1439
Brian Carlstromea46f952013-07-30 01:26:50 -07001440static JDWP::MethodId ToMethodId(const mirror::ArtMethod* m)
Ian Rogersb726dcb2012-09-05 08:57:23 -07001441 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Mathieu Chartier590fee92013-09-13 13:46:47 -07001442 CHECK(!kMovingMethods);
Elliott Hughes03181a82011-11-17 17:22:21 -08001443 return static_cast<JDWP::MethodId>(reinterpret_cast<uintptr_t>(m));
Elliott Hughes03181a82011-11-17 17:22:21 -08001444}
1445
Brian Carlstromea46f952013-07-30 01:26:50 -07001446static mirror::ArtField* FromFieldId(JDWP::FieldId fid)
Ian Rogersb726dcb2012-09-05 08:57:23 -07001447 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Mathieu Chartier590fee92013-09-13 13:46:47 -07001448 CHECK(!kMovingFields);
Brian Carlstromea46f952013-07-30 01:26:50 -07001449 return reinterpret_cast<mirror::ArtField*>(static_cast<uintptr_t>(fid));
Elliott Hughesaed4be92011-12-02 16:16:23 -08001450}
1451
Brian Carlstromea46f952013-07-30 01:26:50 -07001452static mirror::ArtMethod* FromMethodId(JDWP::MethodId mid)
Ian Rogersb726dcb2012-09-05 08:57:23 -07001453 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Mathieu Chartier590fee92013-09-13 13:46:47 -07001454 CHECK(!kMovingMethods);
Brian Carlstromea46f952013-07-30 01:26:50 -07001455 return reinterpret_cast<mirror::ArtMethod*>(static_cast<uintptr_t>(mid));
Elliott Hughes03181a82011-11-17 17:22:21 -08001456}
1457
Ian Rogersc0542af2014-09-03 16:16:56 -07001458static void SetLocation(JDWP::JdwpLocation* location, mirror::ArtMethod* m, uint32_t dex_pc)
Ian Rogersb726dcb2012-09-05 08:57:23 -07001459 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Ian Rogersc0542af2014-09-03 16:16:56 -07001460 if (m == nullptr) {
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08001461 memset(&location, 0, sizeof(location));
1462 } else {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001463 mirror::Class* c = m->GetDeclaringClass();
Ian Rogersc0542af2014-09-03 16:16:56 -07001464 location->type_tag = GetTypeTag(c);
1465 location->class_id = gRegistry->AddRefType(c);
1466 location->method_id = ToMethodId(m);
1467 location->dex_pc = (m->IsNative() || m->IsProxyMethod()) ? static_cast<uint64_t>(-1) : dex_pc;
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08001468 }
Elliott Hughesd07986f2011-12-06 18:27:45 -08001469}
1470
Ian Rogersc0542af2014-09-03 16:16:56 -07001471std::string Dbg::GetMethodName(JDWP::MethodId method_id) {
Brian Carlstromea46f952013-07-30 01:26:50 -07001472 mirror::ArtMethod* m = FromMethodId(method_id);
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07001473 return m->GetName();
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001474}
1475
Ian Rogersc0542af2014-09-03 16:16:56 -07001476std::string Dbg::GetFieldName(JDWP::FieldId field_id) {
Mathieu Chartier61c5ebc2014-06-05 17:42:53 -07001477 return FromFieldId(field_id)->GetName();
Elliott Hughesa96836a2013-01-17 12:27:49 -08001478}
1479
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001480/*
1481 * Augment the access flags for synthetic methods and fields by setting
1482 * the (as described by the spec) "0xf0000000 bit". Also, strip out any
1483 * flags not specified by the Java programming language.
1484 */
1485static uint32_t MangleAccessFlags(uint32_t accessFlags) {
1486 accessFlags &= kAccJavaFlagsMask;
1487 if ((accessFlags & kAccSynthetic) != 0) {
1488 accessFlags |= 0xf0000000;
1489 }
1490 return accessFlags;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001491}
1492
Elliott Hughesdbb40792011-11-18 17:05:22 -08001493/*
Jeff Haob7cefc72013-11-14 14:51:09 -08001494 * Circularly shifts registers so that arguments come first. Debuggers
1495 * expect slots to begin with arguments, but dex code places them at
1496 * the end.
Elliott Hughesdbb40792011-11-18 17:05:22 -08001497 */
Jeff Haob7cefc72013-11-14 14:51:09 -08001498static uint16_t MangleSlot(uint16_t slot, mirror::ArtMethod* m)
1499 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07001500 const DexFile::CodeItem* code_item = m->GetCodeItem();
Sebastien Hertzcb19ebf2014-03-11 15:26:35 +01001501 if (code_item == nullptr) {
1502 // We should not get here for a method without code (native, proxy or abstract). Log it and
1503 // return the slot as is since all registers are arguments.
1504 LOG(WARNING) << "Trying to mangle slot for method without code " << PrettyMethod(m);
1505 return slot;
1506 }
Jeff Haob7cefc72013-11-14 14:51:09 -08001507 uint16_t ins_size = code_item->ins_size_;
1508 uint16_t locals_size = code_item->registers_size_ - ins_size;
1509 if (slot >= locals_size) {
1510 return slot - locals_size;
1511 } else {
1512 return slot + ins_size;
Elliott Hughesdbb40792011-11-18 17:05:22 -08001513 }
Elliott Hughesdbb40792011-11-18 17:05:22 -08001514}
1515
Jeff Haob7cefc72013-11-14 14:51:09 -08001516/*
1517 * Circularly shifts registers so that arguments come last. Reverts
1518 * slots to dex style argument placement.
1519 */
Brian Carlstromea46f952013-07-30 01:26:50 -07001520static uint16_t DemangleSlot(uint16_t slot, mirror::ArtMethod* m)
Ian Rogersb726dcb2012-09-05 08:57:23 -07001521 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07001522 const DexFile::CodeItem* code_item = m->GetCodeItem();
Sebastien Hertzcb19ebf2014-03-11 15:26:35 +01001523 if (code_item == nullptr) {
1524 // We should not get here for a method without code (native, proxy or abstract). Log it and
1525 // return the slot as is since all registers are arguments.
1526 LOG(WARNING) << "Trying to demangle slot for method without code " << PrettyMethod(m);
1527 return slot;
1528 }
Jeff Haob7cefc72013-11-14 14:51:09 -08001529 uint16_t ins_size = code_item->ins_size_;
1530 uint16_t locals_size = code_item->registers_size_ - ins_size;
1531 if (slot < ins_size) {
1532 return slot + locals_size;
1533 } else {
1534 return slot - ins_size;
Elliott Hughesdbb40792011-11-18 17:05:22 -08001535 }
Elliott Hughesdbb40792011-11-18 17:05:22 -08001536}
1537
Elliott Hughes88d63092013-01-09 09:55:54 -08001538JDWP::JdwpError Dbg::OutputDeclaredFields(JDWP::RefTypeId class_id, bool with_generic, JDWP::ExpandBuf* pReply) {
Ian Rogersc0542af2014-09-03 16:16:56 -07001539 JDWP::JdwpError error;
1540 mirror::Class* c = DecodeClass(class_id, &error);
1541 if (c == nullptr) {
1542 return error;
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -08001543 }
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001544
1545 size_t instance_field_count = c->NumInstanceFields();
1546 size_t static_field_count = c->NumStaticFields();
1547
1548 expandBufAdd4BE(pReply, instance_field_count + static_field_count);
1549
1550 for (size_t i = 0; i < instance_field_count + static_field_count; ++i) {
Brian Carlstromea46f952013-07-30 01:26:50 -07001551 mirror::ArtField* f = (i < instance_field_count) ? c->GetInstanceField(i) : c->GetStaticField(i - instance_field_count);
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001552 expandBufAddFieldId(pReply, ToFieldId(f));
Mathieu Chartier61c5ebc2014-06-05 17:42:53 -07001553 expandBufAddUtf8String(pReply, f->GetName());
1554 expandBufAddUtf8String(pReply, f->GetTypeDescriptor());
Elliott Hughesc5b734a2011-12-01 17:20:58 -08001555 if (with_generic) {
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001556 static const char genericSignature[1] = "";
1557 expandBufAddUtf8String(pReply, genericSignature);
1558 }
1559 expandBufAdd4BE(pReply, MangleAccessFlags(f->GetAccessFlags()));
1560 }
Elliott Hughes436e3722012-02-17 20:01:47 -08001561 return JDWP::ERR_NONE;
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001562}
1563
Elliott Hughes88d63092013-01-09 09:55:54 -08001564JDWP::JdwpError Dbg::OutputDeclaredMethods(JDWP::RefTypeId class_id, bool with_generic,
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001565 JDWP::ExpandBuf* pReply) {
Ian Rogersc0542af2014-09-03 16:16:56 -07001566 JDWP::JdwpError error;
1567 mirror::Class* c = DecodeClass(class_id, &error);
1568 if (c == nullptr) {
1569 return error;
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -08001570 }
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001571
1572 size_t direct_method_count = c->NumDirectMethods();
1573 size_t virtual_method_count = c->NumVirtualMethods();
1574
1575 expandBufAdd4BE(pReply, direct_method_count + virtual_method_count);
1576
1577 for (size_t i = 0; i < direct_method_count + virtual_method_count; ++i) {
Brian Carlstromea46f952013-07-30 01:26:50 -07001578 mirror::ArtMethod* m = (i < direct_method_count) ? c->GetDirectMethod(i) : c->GetVirtualMethod(i - direct_method_count);
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001579 expandBufAddMethodId(pReply, ToMethodId(m));
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07001580 expandBufAddUtf8String(pReply, m->GetName());
1581 expandBufAddUtf8String(pReply, m->GetSignature().ToString());
Elliott Hughesc5b734a2011-12-01 17:20:58 -08001582 if (with_generic) {
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001583 static const char genericSignature[1] = "";
1584 expandBufAddUtf8String(pReply, genericSignature);
1585 }
1586 expandBufAdd4BE(pReply, MangleAccessFlags(m->GetAccessFlags()));
1587 }
Elliott Hughes436e3722012-02-17 20:01:47 -08001588 return JDWP::ERR_NONE;
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001589}
1590
Elliott Hughes88d63092013-01-09 09:55:54 -08001591JDWP::JdwpError Dbg::OutputDeclaredInterfaces(JDWP::RefTypeId class_id, JDWP::ExpandBuf* pReply) {
Ian Rogersc0542af2014-09-03 16:16:56 -07001592 JDWP::JdwpError error;
Mathieu Chartierf8322842014-05-16 10:59:25 -07001593 Thread* self = Thread::Current();
1594 StackHandleScope<1> hs(self);
Ian Rogersc0542af2014-09-03 16:16:56 -07001595 Handle<mirror::Class> c(hs.NewHandle(DecodeClass(class_id, &error)));
Mathieu Chartierf8322842014-05-16 10:59:25 -07001596 if (c.Get() == nullptr) {
Ian Rogersc0542af2014-09-03 16:16:56 -07001597 return error;
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -08001598 }
Mathieu Chartierf8322842014-05-16 10:59:25 -07001599 size_t interface_count = c->NumDirectInterfaces();
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001600 expandBufAdd4BE(pReply, interface_count);
1601 for (size_t i = 0; i < interface_count; ++i) {
Mathieu Chartierf8322842014-05-16 10:59:25 -07001602 expandBufAddRefTypeId(pReply,
1603 gRegistry->AddRefType(mirror::Class::GetDirectInterface(self, c, i)));
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001604 }
Elliott Hughes436e3722012-02-17 20:01:47 -08001605 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001606}
1607
Ian Rogersc0542af2014-09-03 16:16:56 -07001608void Dbg::OutputLineTable(JDWP::RefTypeId, JDWP::MethodId method_id, JDWP::ExpandBuf* pReply) {
Elliott Hughes03181a82011-11-17 17:22:21 -08001609 struct DebugCallbackContext {
1610 int numItems;
1611 JDWP::ExpandBuf* pReply;
1612
Elliott Hughes2435a572012-02-17 16:07:41 -08001613 static bool Callback(void* context, uint32_t address, uint32_t line_number) {
Elliott Hughes03181a82011-11-17 17:22:21 -08001614 DebugCallbackContext* pContext = reinterpret_cast<DebugCallbackContext*>(context);
1615 expandBufAdd8BE(pContext->pReply, address);
Elliott Hughes2435a572012-02-17 16:07:41 -08001616 expandBufAdd4BE(pContext->pReply, line_number);
Elliott Hughes03181a82011-11-17 17:22:21 -08001617 pContext->numItems++;
Sebastien Hertzf2910ee2013-10-19 16:39:24 +02001618 return false;
Elliott Hughes03181a82011-11-17 17:22:21 -08001619 }
1620 };
Brian Carlstromea46f952013-07-30 01:26:50 -07001621 mirror::ArtMethod* m = FromMethodId(method_id);
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07001622 const DexFile::CodeItem* code_item = m->GetCodeItem();
Elliott Hughes03181a82011-11-17 17:22:21 -08001623 uint64_t start, end;
Sebastien Hertzcb19ebf2014-03-11 15:26:35 +01001624 if (code_item == nullptr) {
1625 DCHECK(m->IsNative() || m->IsProxyMethod());
Elliott Hughes03181a82011-11-17 17:22:21 -08001626 start = -1;
1627 end = -1;
1628 } else {
1629 start = 0;
jeffhao14f0db92012-12-14 17:50:42 -08001630 // Return the index of the last instruction
Sebastien Hertzcb19ebf2014-03-11 15:26:35 +01001631 end = code_item->insns_size_in_code_units_ - 1;
Elliott Hughes03181a82011-11-17 17:22:21 -08001632 }
1633
1634 expandBufAdd8BE(pReply, start);
1635 expandBufAdd8BE(pReply, end);
1636
1637 // Add numLines later
1638 size_t numLinesOffset = expandBufGetLength(pReply);
1639 expandBufAdd4BE(pReply, 0);
1640
1641 DebugCallbackContext context;
1642 context.numItems = 0;
1643 context.pReply = pReply;
1644
Sebastien Hertzcb19ebf2014-03-11 15:26:35 +01001645 if (code_item != nullptr) {
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07001646 m->GetDexFile()->DecodeDebugInfo(code_item, m->IsStatic(), m->GetDexMethodIndex(),
Ian Rogersc0542af2014-09-03 16:16:56 -07001647 DebugCallbackContext::Callback, nullptr, &context);
Sebastien Hertzcb19ebf2014-03-11 15:26:35 +01001648 }
Elliott Hughes03181a82011-11-17 17:22:21 -08001649
1650 JDWP::Set4BE(expandBufGetBuffer(pReply) + numLinesOffset, context.numItems);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001651}
1652
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07001653void Dbg::OutputVariableTable(JDWP::RefTypeId, JDWP::MethodId method_id, bool with_generic,
1654 JDWP::ExpandBuf* pReply) {
Elliott Hughesdbb40792011-11-18 17:05:22 -08001655 struct DebugCallbackContext {
Jeff Haob7cefc72013-11-14 14:51:09 -08001656 mirror::ArtMethod* method;
Elliott Hughesdbb40792011-11-18 17:05:22 -08001657 JDWP::ExpandBuf* pReply;
Elliott Hughesc5b734a2011-12-01 17:20:58 -08001658 size_t variable_count;
1659 bool with_generic;
Elliott Hughesdbb40792011-11-18 17:05:22 -08001660
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07001661 static void Callback(void* context, uint16_t slot, uint32_t startAddress, uint32_t endAddress,
1662 const char* name, const char* descriptor, const char* signature)
Jeff Haob7cefc72013-11-14 14:51:09 -08001663 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Elliott Hughesdbb40792011-11-18 17:05:22 -08001664 DebugCallbackContext* pContext = reinterpret_cast<DebugCallbackContext*>(context);
1665
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07001666 VLOG(jdwp) << StringPrintf(" %2zd: %d(%d) '%s' '%s' '%s' actual slot=%d mangled slot=%d",
1667 pContext->variable_count, startAddress, endAddress - startAddress,
1668 name, descriptor, signature, slot,
1669 MangleSlot(slot, pContext->method));
Elliott Hughesdbb40792011-11-18 17:05:22 -08001670
Jeff Haob7cefc72013-11-14 14:51:09 -08001671 slot = MangleSlot(slot, pContext->method);
Elliott Hughes68fdbd02011-11-29 19:22:47 -08001672
Elliott Hughesdbb40792011-11-18 17:05:22 -08001673 expandBufAdd8BE(pContext->pReply, startAddress);
1674 expandBufAddUtf8String(pContext->pReply, name);
1675 expandBufAddUtf8String(pContext->pReply, descriptor);
Elliott Hughesc5b734a2011-12-01 17:20:58 -08001676 if (pContext->with_generic) {
Elliott Hughesdbb40792011-11-18 17:05:22 -08001677 expandBufAddUtf8String(pContext->pReply, signature);
1678 }
1679 expandBufAdd4BE(pContext->pReply, endAddress - startAddress);
1680 expandBufAdd4BE(pContext->pReply, slot);
1681
Elliott Hughesc5b734a2011-12-01 17:20:58 -08001682 ++pContext->variable_count;
Elliott Hughesdbb40792011-11-18 17:05:22 -08001683 }
1684 };
Brian Carlstromea46f952013-07-30 01:26:50 -07001685 mirror::ArtMethod* m = FromMethodId(method_id);
Elliott Hughesdbb40792011-11-18 17:05:22 -08001686
Elliott Hughesc5b734a2011-12-01 17:20:58 -08001687 // arg_count considers doubles and longs to take 2 units.
1688 // variable_count considers everything to take 1 unit.
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07001689 std::string shorty(m->GetShorty());
Brian Carlstromea46f952013-07-30 01:26:50 -07001690 expandBufAdd4BE(pReply, mirror::ArtMethod::NumArgRegisters(shorty));
Elliott Hughesdbb40792011-11-18 17:05:22 -08001691
Elliott Hughesc5b734a2011-12-01 17:20:58 -08001692 // We don't know the total number of variables yet, so leave a blank and update it later.
1693 size_t variable_count_offset = expandBufGetLength(pReply);
Elliott Hughesdbb40792011-11-18 17:05:22 -08001694 expandBufAdd4BE(pReply, 0);
1695
1696 DebugCallbackContext context;
Jeff Haob7cefc72013-11-14 14:51:09 -08001697 context.method = m;
Elliott Hughesdbb40792011-11-18 17:05:22 -08001698 context.pReply = pReply;
Elliott Hughesc5b734a2011-12-01 17:20:58 -08001699 context.variable_count = 0;
1700 context.with_generic = with_generic;
Elliott Hughesdbb40792011-11-18 17:05:22 -08001701
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07001702 const DexFile::CodeItem* code_item = m->GetCodeItem();
Sebastien Hertzcb19ebf2014-03-11 15:26:35 +01001703 if (code_item != nullptr) {
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07001704 m->GetDexFile()->DecodeDebugInfo(
Ian Rogersc0542af2014-09-03 16:16:56 -07001705 code_item, m->IsStatic(), m->GetDexMethodIndex(), nullptr, DebugCallbackContext::Callback,
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07001706 &context);
Sebastien Hertzcb19ebf2014-03-11 15:26:35 +01001707 }
Elliott Hughesdbb40792011-11-18 17:05:22 -08001708
Elliott Hughesc5b734a2011-12-01 17:20:58 -08001709 JDWP::Set4BE(expandBufGetBuffer(pReply) + variable_count_offset, context.variable_count);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001710}
1711
Jeff Hao579b0242013-11-18 13:16:49 -08001712void Dbg::OutputMethodReturnValue(JDWP::MethodId method_id, const JValue* return_value,
1713 JDWP::ExpandBuf* pReply) {
1714 mirror::ArtMethod* m = FromMethodId(method_id);
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07001715 JDWP::JdwpTag tag = BasicTagFromDescriptor(m->GetShorty());
Jeff Hao579b0242013-11-18 13:16:49 -08001716 OutputJValue(tag, return_value, pReply);
1717}
1718
Sebastien Hertz3f52eaf2014-04-04 17:50:18 +02001719void Dbg::OutputFieldValue(JDWP::FieldId field_id, const JValue* field_value,
1720 JDWP::ExpandBuf* pReply) {
1721 mirror::ArtField* f = FromFieldId(field_id);
Mathieu Chartier61c5ebc2014-06-05 17:42:53 -07001722 JDWP::JdwpTag tag = BasicTagFromDescriptor(f->GetTypeDescriptor());
Sebastien Hertz3f52eaf2014-04-04 17:50:18 +02001723 OutputJValue(tag, field_value, pReply);
1724}
1725
Elliott Hughes9777ba22013-01-17 09:04:19 -08001726JDWP::JdwpError Dbg::GetBytecodes(JDWP::RefTypeId, JDWP::MethodId method_id,
Ian Rogersc0542af2014-09-03 16:16:56 -07001727 std::vector<uint8_t>* bytecodes) {
Brian Carlstromea46f952013-07-30 01:26:50 -07001728 mirror::ArtMethod* m = FromMethodId(method_id);
Ian Rogersc0542af2014-09-03 16:16:56 -07001729 if (m == nullptr) {
Elliott Hughes9777ba22013-01-17 09:04:19 -08001730 return JDWP::ERR_INVALID_METHODID;
1731 }
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07001732 const DexFile::CodeItem* code_item = m->GetCodeItem();
Elliott Hughes9777ba22013-01-17 09:04:19 -08001733 size_t byte_count = code_item->insns_size_in_code_units_ * 2;
1734 const uint8_t* begin = reinterpret_cast<const uint8_t*>(code_item->insns_);
1735 const uint8_t* end = begin + byte_count;
1736 for (const uint8_t* p = begin; p != end; ++p) {
Ian Rogersc0542af2014-09-03 16:16:56 -07001737 bytecodes->push_back(*p);
Elliott Hughes9777ba22013-01-17 09:04:19 -08001738 }
1739 return JDWP::ERR_NONE;
1740}
1741
Elliott Hughes88d63092013-01-09 09:55:54 -08001742JDWP::JdwpTag Dbg::GetFieldBasicTag(JDWP::FieldId field_id) {
Mathieu Chartier61c5ebc2014-06-05 17:42:53 -07001743 return BasicTagFromDescriptor(FromFieldId(field_id)->GetTypeDescriptor());
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001744}
1745
Elliott Hughes88d63092013-01-09 09:55:54 -08001746JDWP::JdwpTag Dbg::GetStaticFieldBasicTag(JDWP::FieldId field_id) {
Mathieu Chartier61c5ebc2014-06-05 17:42:53 -07001747 return BasicTagFromDescriptor(FromFieldId(field_id)->GetTypeDescriptor());
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001748}
1749
Elliott Hughes88d63092013-01-09 09:55:54 -08001750static JDWP::JdwpError GetFieldValueImpl(JDWP::RefTypeId ref_type_id, JDWP::ObjectId object_id,
1751 JDWP::FieldId field_id, JDWP::ExpandBuf* pReply,
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001752 bool is_static)
Ian Rogersb726dcb2012-09-05 08:57:23 -07001753 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Ian Rogersc0542af2014-09-03 16:16:56 -07001754 JDWP::JdwpError error;
1755 mirror::Class* c = DecodeClass(ref_type_id, &error);
1756 if (ref_type_id != 0 && c == nullptr) {
1757 return error;
Elliott Hughes0cf74332012-02-23 23:14:00 -08001758 }
1759
Ian Rogersc0542af2014-09-03 16:16:56 -07001760 mirror::Object* o = gRegistry->Get<mirror::Object*>(object_id, &error);
1761 if ((!is_static && o == nullptr) || error != JDWP::ERR_NONE) {
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08001762 return JDWP::ERR_INVALID_OBJECT;
1763 }
Brian Carlstromea46f952013-07-30 01:26:50 -07001764 mirror::ArtField* f = FromFieldId(field_id);
Elliott Hughes0cf74332012-02-23 23:14:00 -08001765
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001766 mirror::Class* receiver_class = c;
Ian Rogersc0542af2014-09-03 16:16:56 -07001767 if (receiver_class == nullptr && o != nullptr) {
Elliott Hughes0cf74332012-02-23 23:14:00 -08001768 receiver_class = o->GetClass();
1769 }
Ian Rogersc0542af2014-09-03 16:16:56 -07001770 // TODO: should we give up now if receiver_class is nullptr?
1771 if (receiver_class != nullptr && !f->GetDeclaringClass()->IsAssignableFrom(receiver_class)) {
Elliott Hughes0cf74332012-02-23 23:14:00 -08001772 LOG(INFO) << "ERR_INVALID_FIELDID: " << PrettyField(f) << " " << PrettyClass(receiver_class);
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08001773 return JDWP::ERR_INVALID_FIELDID;
1774 }
Elliott Hughesaed4be92011-12-02 16:16:23 -08001775
Elliott Hughes0cf74332012-02-23 23:14:00 -08001776 // The RI only enforces the static/non-static mismatch in one direction.
1777 // TODO: should we change the tests and check both?
1778 if (is_static) {
1779 if (!f->IsStatic()) {
1780 return JDWP::ERR_INVALID_FIELDID;
1781 }
1782 } else {
1783 if (f->IsStatic()) {
Ian Rogersc0542af2014-09-03 16:16:56 -07001784 LOG(WARNING) << "Ignoring non-nullptr receiver for ObjectReference.SetValues on static field "
1785 << PrettyField(f);
Elliott Hughes0cf74332012-02-23 23:14:00 -08001786 }
1787 }
jeffhao0dfbb7e2012-11-28 15:26:03 -08001788 if (f->IsStatic()) {
1789 o = f->GetDeclaringClass();
1790 }
Elliott Hughes0cf74332012-02-23 23:14:00 -08001791
Mathieu Chartier61c5ebc2014-06-05 17:42:53 -07001792 JDWP::JdwpTag tag = BasicTagFromDescriptor(f->GetTypeDescriptor());
Jeff Hao579b0242013-11-18 13:16:49 -08001793 JValue field_value;
1794 if (tag == JDWP::JT_VOID) {
1795 LOG(FATAL) << "Unknown tag: " << tag;
1796 } else if (!IsPrimitiveTag(tag)) {
1797 field_value.SetL(f->GetObject(o));
1798 } else if (tag == JDWP::JT_DOUBLE || tag == JDWP::JT_LONG) {
1799 field_value.SetJ(f->Get64(o));
Elliott Hughesaed4be92011-12-02 16:16:23 -08001800 } else {
Jeff Hao579b0242013-11-18 13:16:49 -08001801 field_value.SetI(f->Get32(o));
Elliott Hughesaed4be92011-12-02 16:16:23 -08001802 }
Jeff Hao579b0242013-11-18 13:16:49 -08001803 Dbg::OutputJValue(tag, &field_value, pReply);
1804
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08001805 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001806}
1807
Elliott Hughes88d63092013-01-09 09:55:54 -08001808JDWP::JdwpError Dbg::GetFieldValue(JDWP::ObjectId object_id, JDWP::FieldId field_id,
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001809 JDWP::ExpandBuf* pReply) {
Elliott Hughes88d63092013-01-09 09:55:54 -08001810 return GetFieldValueImpl(0, object_id, field_id, pReply, false);
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08001811}
1812
Ian Rogersc0542af2014-09-03 16:16:56 -07001813JDWP::JdwpError Dbg::GetStaticFieldValue(JDWP::RefTypeId ref_type_id, JDWP::FieldId field_id,
1814 JDWP::ExpandBuf* pReply) {
Elliott Hughes88d63092013-01-09 09:55:54 -08001815 return GetFieldValueImpl(ref_type_id, 0, field_id, pReply, true);
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08001816}
1817
Elliott Hughes88d63092013-01-09 09:55:54 -08001818static JDWP::JdwpError SetFieldValueImpl(JDWP::ObjectId object_id, JDWP::FieldId field_id,
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001819 uint64_t value, int width, bool is_static)
Ian Rogersb726dcb2012-09-05 08:57:23 -07001820 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Ian Rogersc0542af2014-09-03 16:16:56 -07001821 JDWP::JdwpError error;
1822 mirror::Object* o = gRegistry->Get<mirror::Object*>(object_id, &error);
1823 if ((!is_static && o == nullptr) || error != JDWP::ERR_NONE) {
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08001824 return JDWP::ERR_INVALID_OBJECT;
1825 }
Brian Carlstromea46f952013-07-30 01:26:50 -07001826 mirror::ArtField* f = FromFieldId(field_id);
Elliott Hughes0cf74332012-02-23 23:14:00 -08001827
1828 // The RI only enforces the static/non-static mismatch in one direction.
1829 // TODO: should we change the tests and check both?
1830 if (is_static) {
1831 if (!f->IsStatic()) {
1832 return JDWP::ERR_INVALID_FIELDID;
1833 }
1834 } else {
1835 if (f->IsStatic()) {
Ian Rogersc0542af2014-09-03 16:16:56 -07001836 LOG(WARNING) << "Ignoring non-nullptr receiver for ObjectReference.SetValues on static field " << PrettyField(f);
Elliott Hughes0cf74332012-02-23 23:14:00 -08001837 }
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08001838 }
jeffhao0dfbb7e2012-11-28 15:26:03 -08001839 if (f->IsStatic()) {
1840 o = f->GetDeclaringClass();
1841 }
Elliott Hughesaed4be92011-12-02 16:16:23 -08001842
Mathieu Chartier61c5ebc2014-06-05 17:42:53 -07001843 JDWP::JdwpTag tag = BasicTagFromDescriptor(f->GetTypeDescriptor());
Elliott Hughesaed4be92011-12-02 16:16:23 -08001844
1845 if (IsPrimitiveTag(tag)) {
1846 if (tag == JDWP::JT_DOUBLE || tag == JDWP::JT_LONG) {
Elliott Hughes1bac54f2012-03-16 12:48:31 -07001847 CHECK_EQ(width, 8);
Sebastien Hertzd2fe10a2014-01-15 10:20:56 +01001848 // Debugging can't use transactional mode (runtime only).
1849 f->Set64<false>(o, value);
Elliott Hughesaed4be92011-12-02 16:16:23 -08001850 } else {
Elliott Hughes1bac54f2012-03-16 12:48:31 -07001851 CHECK_LE(width, 4);
Sebastien Hertzd2fe10a2014-01-15 10:20:56 +01001852 // Debugging can't use transactional mode (runtime only).
1853 f->Set32<false>(o, value);
Elliott Hughesaed4be92011-12-02 16:16:23 -08001854 }
1855 } else {
Ian Rogersc0542af2014-09-03 16:16:56 -07001856 mirror::Object* v = gRegistry->Get<mirror::Object*>(value, &error);
1857 if (error != JDWP::ERR_NONE) {
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -08001858 return JDWP::ERR_INVALID_OBJECT;
1859 }
Ian Rogersc0542af2014-09-03 16:16:56 -07001860 if (v != nullptr) {
Mathieu Chartier61c5ebc2014-06-05 17:42:53 -07001861 mirror::Class* field_type;
1862 {
1863 StackHandleScope<3> hs(Thread::Current());
1864 HandleWrapper<mirror::Object> h_v(hs.NewHandleWrapper(&v));
1865 HandleWrapper<mirror::ArtField> h_f(hs.NewHandleWrapper(&f));
1866 HandleWrapper<mirror::Object> h_o(hs.NewHandleWrapper(&o));
1867 field_type = FieldHelper(h_f).GetType();
1868 }
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08001869 if (!field_type->IsAssignableFrom(v->GetClass())) {
1870 return JDWP::ERR_INVALID_OBJECT;
1871 }
1872 }
Sebastien Hertzd2fe10a2014-01-15 10:20:56 +01001873 // Debugging can't use transactional mode (runtime only).
1874 f->SetObject<false>(o, v);
Elliott Hughesaed4be92011-12-02 16:16:23 -08001875 }
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -08001876
1877 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001878}
1879
Elliott Hughes88d63092013-01-09 09:55:54 -08001880JDWP::JdwpError Dbg::SetFieldValue(JDWP::ObjectId object_id, JDWP::FieldId field_id, uint64_t value,
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001881 int width) {
Elliott Hughes88d63092013-01-09 09:55:54 -08001882 return SetFieldValueImpl(object_id, field_id, value, width, false);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001883}
1884
Elliott Hughes88d63092013-01-09 09:55:54 -08001885JDWP::JdwpError Dbg::SetStaticFieldValue(JDWP::FieldId field_id, uint64_t value, int width) {
1886 return SetFieldValueImpl(0, field_id, value, width, true);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001887}
1888
Elliott Hughes88d63092013-01-09 09:55:54 -08001889std::string Dbg::StringToUtf8(JDWP::ObjectId string_id) {
Ian Rogersc0542af2014-09-03 16:16:56 -07001890 JDWP::JdwpError error;
1891 mirror::String* s = gRegistry->Get<mirror::String*>(string_id, &error);
1892 CHECK(s != nullptr) << error;
Elliott Hughes68fdbd02011-11-29 19:22:47 -08001893 return s->ToModifiedUtf8();
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001894}
1895
Jeff Hao579b0242013-11-18 13:16:49 -08001896void Dbg::OutputJValue(JDWP::JdwpTag tag, const JValue* return_value, JDWP::ExpandBuf* pReply) {
1897 if (IsPrimitiveTag(tag)) {
1898 expandBufAdd1(pReply, tag);
1899 if (tag == JDWP::JT_BOOLEAN || tag == JDWP::JT_BYTE) {
1900 expandBufAdd1(pReply, return_value->GetI());
1901 } else if (tag == JDWP::JT_CHAR || tag == JDWP::JT_SHORT) {
1902 expandBufAdd2BE(pReply, return_value->GetI());
1903 } else if (tag == JDWP::JT_FLOAT || tag == JDWP::JT_INT) {
1904 expandBufAdd4BE(pReply, return_value->GetI());
1905 } else if (tag == JDWP::JT_DOUBLE || tag == JDWP::JT_LONG) {
1906 expandBufAdd8BE(pReply, return_value->GetJ());
1907 } else {
1908 CHECK_EQ(tag, JDWP::JT_VOID);
1909 }
1910 } else {
Ian Rogers98379392014-02-24 16:53:16 -08001911 ScopedObjectAccessUnchecked soa(Thread::Current());
Jeff Hao579b0242013-11-18 13:16:49 -08001912 mirror::Object* value = return_value->GetL();
Ian Rogers98379392014-02-24 16:53:16 -08001913 expandBufAdd1(pReply, TagFromObject(soa, value));
Jeff Hao579b0242013-11-18 13:16:49 -08001914 expandBufAddObjectId(pReply, gRegistry->Add(value));
1915 }
1916}
1917
Ian Rogersc0542af2014-09-03 16:16:56 -07001918JDWP::JdwpError Dbg::GetThreadName(JDWP::ObjectId thread_id, std::string* name) {
jeffhaoa77f0f62012-12-05 17:19:31 -08001919 ScopedObjectAccessUnchecked soa(Thread::Current());
1920 MutexLock mu(soa.Self(), *Locks::thread_list_lock_);
Ian Rogersc0542af2014-09-03 16:16:56 -07001921 JDWP::JdwpError error;
1922 Thread* thread = DecodeThread(soa, thread_id, &error);
1923 UNUSED(thread);
Elliott Hughes221229c2013-01-08 18:17:50 -08001924 if (error != JDWP::ERR_NONE && error != JDWP::ERR_THREAD_NOT_ALIVE) {
1925 return error;
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001926 }
Elliott Hughes221229c2013-01-08 18:17:50 -08001927
1928 // We still need to report the zombie threads' names, so we can't just call Thread::GetThreadName.
Ian Rogersc0542af2014-09-03 16:16:56 -07001929 mirror::Object* thread_object = gRegistry->Get<mirror::Object*>(thread_id, &error);
1930 CHECK(thread_object != nullptr) << error;
Brian Carlstromea46f952013-07-30 01:26:50 -07001931 mirror::ArtField* java_lang_Thread_name_field =
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001932 soa.DecodeField(WellKnownClasses::java_lang_Thread_name);
1933 mirror::String* s =
1934 reinterpret_cast<mirror::String*>(java_lang_Thread_name_field->GetObject(thread_object));
Ian Rogersc0542af2014-09-03 16:16:56 -07001935 if (s != nullptr) {
1936 *name = s->ToModifiedUtf8();
Elliott Hughes221229c2013-01-08 18:17:50 -08001937 }
1938 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001939}
1940
Elliott Hughes221229c2013-01-08 18:17:50 -08001941JDWP::JdwpError Dbg::GetThreadGroup(JDWP::ObjectId thread_id, JDWP::ExpandBuf* pReply) {
Sebastien Hertza06430c2014-09-15 19:21:30 +02001942 ScopedObjectAccessUnchecked soa(Thread::Current());
Ian Rogersc0542af2014-09-03 16:16:56 -07001943 JDWP::JdwpError error;
1944 mirror::Object* thread_object = gRegistry->Get<mirror::Object*>(thread_id, &error);
1945 if (error != JDWP::ERR_NONE) {
Elliott Hughes2435a572012-02-17 16:07:41 -08001946 return JDWP::ERR_INVALID_OBJECT;
1947 }
Ian Rogers98379392014-02-24 16:53:16 -08001948 const char* old_cause = soa.Self()->StartAssertNoThreadSuspension("Debugger: GetThreadGroup");
Elliott Hughes2435a572012-02-17 16:07:41 -08001949 // Okay, so it's an object, but is it actually a thread?
Hiroshi Yamauchib5a9e3d2014-06-09 12:11:20 -07001950 {
1951 MutexLock mu(soa.Self(), *Locks::thread_list_lock_);
Ian Rogersc0542af2014-09-03 16:16:56 -07001952 Thread* thread = DecodeThread(soa, thread_id, &error);
1953 UNUSED(thread);
Hiroshi Yamauchib5a9e3d2014-06-09 12:11:20 -07001954 }
Elliott Hughes221229c2013-01-08 18:17:50 -08001955 if (error == JDWP::ERR_THREAD_NOT_ALIVE) {
1956 // Zombie threads are in the null group.
1957 expandBufAddObjectId(pReply, JDWP::ObjectId(0));
Sebastien Hertz52d131d2014-03-13 16:17:40 +01001958 error = JDWP::ERR_NONE;
1959 } else if (error == JDWP::ERR_NONE) {
1960 mirror::Class* c = soa.Decode<mirror::Class*>(WellKnownClasses::java_lang_Thread);
1961 CHECK(c != nullptr);
1962 mirror::ArtField* f = c->FindInstanceField("group", "Ljava/lang/ThreadGroup;");
Hiroshi Yamauchib5a9e3d2014-06-09 12:11:20 -07001963 CHECK(f != nullptr);
Sebastien Hertz52d131d2014-03-13 16:17:40 +01001964 mirror::Object* group = f->GetObject(thread_object);
Hiroshi Yamauchib5a9e3d2014-06-09 12:11:20 -07001965 CHECK(group != nullptr);
Sebastien Hertz52d131d2014-03-13 16:17:40 +01001966 JDWP::ObjectId thread_group_id = gRegistry->Add(group);
1967 expandBufAddObjectId(pReply, thread_group_id);
Elliott Hughes221229c2013-01-08 18:17:50 -08001968 }
Ian Rogers98379392014-02-24 16:53:16 -08001969 soa.Self()->EndAssertNoThreadSuspension(old_cause);
Sebastien Hertz52d131d2014-03-13 16:17:40 +01001970 return error;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001971}
1972
Sebastien Hertza06430c2014-09-15 19:21:30 +02001973static mirror::Object* DecodeThreadGroup(ScopedObjectAccessUnchecked& soa,
1974 JDWP::ObjectId thread_group_id, JDWP::JdwpError* error)
1975 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
1976 mirror::Object* thread_group = gRegistry->Get<mirror::Object*>(thread_group_id, error);
1977 if (*error != JDWP::ERR_NONE) {
1978 return nullptr;
1979 }
1980 if (thread_group == nullptr) {
1981 *error = JDWP::ERR_INVALID_OBJECT;
1982 return nullptr;
1983 }
Ian Rogers98379392014-02-24 16:53:16 -08001984 mirror::Class* c = soa.Decode<mirror::Class*>(WellKnownClasses::java_lang_ThreadGroup);
1985 CHECK(c != nullptr);
Sebastien Hertza06430c2014-09-15 19:21:30 +02001986 if (!c->IsAssignableFrom(thread_group->GetClass())) {
1987 // This is not a java.lang.ThreadGroup.
1988 *error = JDWP::ERR_INVALID_THREAD_GROUP;
1989 return nullptr;
1990 }
1991 *error = JDWP::ERR_NONE;
1992 return thread_group;
1993}
1994
1995JDWP::JdwpError Dbg::GetThreadGroupName(JDWP::ObjectId thread_group_id, JDWP::ExpandBuf* pReply) {
1996 ScopedObjectAccessUnchecked soa(Thread::Current());
1997 JDWP::JdwpError error;
1998 mirror::Object* thread_group = DecodeThreadGroup(soa, thread_group_id, &error);
1999 if (error != JDWP::ERR_NONE) {
2000 return error;
2001 }
2002 const char* old_cause = soa.Self()->StartAssertNoThreadSuspension("Debugger: GetThreadGroupName");
2003 mirror::Class* c = soa.Decode<mirror::Class*>(WellKnownClasses::java_lang_ThreadGroup);
Brian Carlstromea46f952013-07-30 01:26:50 -07002004 mirror::ArtField* f = c->FindInstanceField("name", "Ljava/lang/String;");
Ian Rogersc0542af2014-09-03 16:16:56 -07002005 CHECK(f != nullptr);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002006 mirror::String* s = reinterpret_cast<mirror::String*>(f->GetObject(thread_group));
Ian Rogers98379392014-02-24 16:53:16 -08002007 soa.Self()->EndAssertNoThreadSuspension(old_cause);
Sebastien Hertza06430c2014-09-15 19:21:30 +02002008
2009 std::string thread_group_name(s->ToModifiedUtf8());
2010 expandBufAddUtf8String(pReply, thread_group_name);
2011 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002012}
2013
Sebastien Hertza06430c2014-09-15 19:21:30 +02002014JDWP::JdwpError Dbg::GetThreadGroupParent(JDWP::ObjectId thread_group_id, JDWP::ExpandBuf* pReply) {
Ian Rogers98379392014-02-24 16:53:16 -08002015 ScopedObjectAccessUnchecked soa(Thread::Current());
Ian Rogersc0542af2014-09-03 16:16:56 -07002016 JDWP::JdwpError error;
Sebastien Hertza06430c2014-09-15 19:21:30 +02002017 mirror::Object* thread_group = DecodeThreadGroup(soa, thread_group_id, &error);
2018 if (error != JDWP::ERR_NONE) {
2019 return error;
2020 }
Ian Rogers98379392014-02-24 16:53:16 -08002021 const char* old_cause = soa.Self()->StartAssertNoThreadSuspension("Debugger: GetThreadGroupParent");
2022 mirror::Class* c = soa.Decode<mirror::Class*>(WellKnownClasses::java_lang_ThreadGroup);
2023 CHECK(c != nullptr);
Brian Carlstromea46f952013-07-30 01:26:50 -07002024 mirror::ArtField* f = c->FindInstanceField("parent", "Ljava/lang/ThreadGroup;");
Ian Rogersc0542af2014-09-03 16:16:56 -07002025 CHECK(f != nullptr);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002026 mirror::Object* parent = f->GetObject(thread_group);
Ian Rogers98379392014-02-24 16:53:16 -08002027 soa.Self()->EndAssertNoThreadSuspension(old_cause);
Sebastien Hertza06430c2014-09-15 19:21:30 +02002028
2029 JDWP::ObjectId parent_group_id = gRegistry->Add(parent);
2030 expandBufAddObjectId(pReply, parent_group_id);
2031 return JDWP::ERR_NONE;
2032}
2033
2034static void GetChildThreadGroups(ScopedObjectAccessUnchecked& soa, mirror::Object* thread_group,
2035 std::vector<JDWP::ObjectId>* child_thread_group_ids)
2036 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
2037 CHECK(thread_group != nullptr);
2038
2039 // Get the ArrayList<ThreadGroup> "groups" out of this thread group...
2040 mirror::ArtField* groups_field = thread_group->GetClass()->FindInstanceField("groups", "Ljava/util/List;");
2041 mirror::Object* groups_array_list = groups_field->GetObject(thread_group);
2042
2043 // Get the array and size out of the ArrayList<ThreadGroup>...
2044 mirror::ArtField* array_field = groups_array_list->GetClass()->FindInstanceField("array", "[Ljava/lang/Object;");
2045 mirror::ArtField* size_field = groups_array_list->GetClass()->FindInstanceField("size", "I");
2046 mirror::ObjectArray<mirror::Object>* groups_array =
2047 array_field->GetObject(groups_array_list)->AsObjectArray<mirror::Object>();
2048 const int32_t size = size_field->GetInt(groups_array_list);
2049
2050 // Copy the first 'size' elements out of the array into the result.
2051 for (int32_t i = 0; i < size; ++i) {
2052 child_thread_group_ids->push_back(gRegistry->Add(groups_array->Get(i)));
2053 }
2054}
2055
2056JDWP::JdwpError Dbg::GetThreadGroupChildren(JDWP::ObjectId thread_group_id,
2057 JDWP::ExpandBuf* pReply) {
2058 ScopedObjectAccessUnchecked soa(Thread::Current());
2059 JDWP::JdwpError error;
2060 mirror::Object* thread_group = DecodeThreadGroup(soa, thread_group_id, &error);
2061 if (error != JDWP::ERR_NONE) {
2062 return error;
2063 }
2064
2065 // Add child threads.
2066 {
2067 std::vector<JDWP::ObjectId> child_thread_ids;
2068 GetThreads(thread_group, &child_thread_ids);
2069 expandBufAdd4BE(pReply, child_thread_ids.size());
2070 for (JDWP::ObjectId child_thread_id : child_thread_ids) {
2071 expandBufAddObjectId(pReply, child_thread_id);
2072 }
2073 }
2074
2075 // Add child thread groups.
2076 {
2077 std::vector<JDWP::ObjectId> child_thread_groups_ids;
2078 GetChildThreadGroups(soa, thread_group, &child_thread_groups_ids);
2079 expandBufAdd4BE(pReply, child_thread_groups_ids.size());
2080 for (JDWP::ObjectId child_thread_group_id : child_thread_groups_ids) {
2081 expandBufAddObjectId(pReply, child_thread_group_id);
2082 }
2083 }
2084
2085 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002086}
2087
2088JDWP::ObjectId Dbg::GetSystemThreadGroupId() {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002089 ScopedObjectAccessUnchecked soa(Thread::Current());
Brian Carlstromea46f952013-07-30 01:26:50 -07002090 mirror::ArtField* f = soa.DecodeField(WellKnownClasses::java_lang_ThreadGroup_systemThreadGroup);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002091 mirror::Object* group = f->GetObject(f->GetDeclaringClass());
Ian Rogers365c1022012-06-22 15:05:28 -07002092 return gRegistry->Add(group);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002093}
2094
Jeff Hao920af3e2013-08-28 15:46:38 -07002095JDWP::JdwpThreadStatus Dbg::ToJdwpThreadStatus(ThreadState state) {
2096 switch (state) {
2097 case kBlocked:
2098 return JDWP::TS_MONITOR;
2099 case kNative:
2100 case kRunnable:
2101 case kSuspended:
2102 return JDWP::TS_RUNNING;
2103 case kSleeping:
2104 return JDWP::TS_SLEEPING;
2105 case kStarting:
2106 case kTerminated:
2107 return JDWP::TS_ZOMBIE;
2108 case kTimedWaiting:
Sebastien Hertzbae182c2013-12-17 10:42:03 +01002109 case kWaitingForCheckPointsToRun:
Jeff Hao920af3e2013-08-28 15:46:38 -07002110 case kWaitingForDebuggerSend:
2111 case kWaitingForDebuggerSuspension:
2112 case kWaitingForDebuggerToAttach:
Sebastien Hertz138dbfc2013-12-04 18:15:25 +01002113 case kWaitingForDeoptimization:
Jeff Hao920af3e2013-08-28 15:46:38 -07002114 case kWaitingForGcToComplete:
Jeff Hao920af3e2013-08-28 15:46:38 -07002115 case kWaitingForJniOnLoad:
Sebastien Hertzbae182c2013-12-17 10:42:03 +01002116 case kWaitingForMethodTracingStart:
Jeff Hao920af3e2013-08-28 15:46:38 -07002117 case kWaitingForSignalCatcherOutput:
2118 case kWaitingInMainDebuggerLoop:
2119 case kWaitingInMainSignalCatcherLoop:
2120 case kWaitingPerformingGc:
2121 case kWaiting:
2122 return JDWP::TS_WAIT;
2123 // Don't add a 'default' here so the compiler can spot incompatible enum changes.
2124 }
2125 LOG(FATAL) << "Unknown thread state: " << state;
2126 return JDWP::TS_ZOMBIE;
2127}
2128
Sebastien Hertz52d131d2014-03-13 16:17:40 +01002129JDWP::JdwpError Dbg::GetThreadStatus(JDWP::ObjectId thread_id, JDWP::JdwpThreadStatus* pThreadStatus,
2130 JDWP::JdwpSuspendStatus* pSuspendStatus) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002131 ScopedObjectAccess soa(Thread::Current());
Elliott Hughes499c5132011-11-17 14:55:11 -08002132
Elliott Hughes9e0c1752013-01-09 14:02:58 -08002133 *pSuspendStatus = JDWP::SUSPEND_STATUS_NOT_SUSPENDED;
2134
Ian Rogers50b35e22012-10-04 10:09:15 -07002135 MutexLock mu(soa.Self(), *Locks::thread_list_lock_);
Ian Rogersc0542af2014-09-03 16:16:56 -07002136 JDWP::JdwpError error;
2137 Thread* thread = DecodeThread(soa, thread_id, &error);
Elliott Hughes221229c2013-01-08 18:17:50 -08002138 if (error != JDWP::ERR_NONE) {
2139 if (error == JDWP::ERR_THREAD_NOT_ALIVE) {
2140 *pThreadStatus = JDWP::TS_ZOMBIE;
Elliott Hughes221229c2013-01-08 18:17:50 -08002141 return JDWP::ERR_NONE;
2142 }
2143 return error;
Elliott Hughes499c5132011-11-17 14:55:11 -08002144 }
2145
Elliott Hughes9e0c1752013-01-09 14:02:58 -08002146 if (IsSuspendedForDebugger(soa, thread)) {
2147 *pSuspendStatus = JDWP::SUSPEND_STATUS_SUSPENDED;
Elliott Hughes499c5132011-11-17 14:55:11 -08002148 }
2149
Jeff Hao920af3e2013-08-28 15:46:38 -07002150 *pThreadStatus = ToJdwpThreadStatus(thread->GetState());
Elliott Hughes221229c2013-01-08 18:17:50 -08002151 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002152}
2153
Elliott Hughes221229c2013-01-08 18:17:50 -08002154JDWP::JdwpError Dbg::GetThreadDebugSuspendCount(JDWP::ObjectId thread_id, JDWP::ExpandBuf* pReply) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002155 ScopedObjectAccess soa(Thread::Current());
Ian Rogers50b35e22012-10-04 10:09:15 -07002156 MutexLock mu(soa.Self(), *Locks::thread_list_lock_);
Ian Rogersc0542af2014-09-03 16:16:56 -07002157 JDWP::JdwpError error;
2158 Thread* thread = DecodeThread(soa, thread_id, &error);
Elliott Hughes221229c2013-01-08 18:17:50 -08002159 if (error != JDWP::ERR_NONE) {
2160 return error;
Elliott Hughes2435a572012-02-17 16:07:41 -08002161 }
Ian Rogers50b35e22012-10-04 10:09:15 -07002162 MutexLock mu2(soa.Self(), *Locks::thread_suspend_count_lock_);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002163 expandBufAdd4BE(pReply, thread->GetDebugSuspendCount());
Elliott Hughes2435a572012-02-17 16:07:41 -08002164 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002165}
2166
Elliott Hughesf9501702013-01-11 11:22:27 -08002167JDWP::JdwpError Dbg::Interrupt(JDWP::ObjectId thread_id) {
2168 ScopedObjectAccess soa(Thread::Current());
2169 MutexLock mu(soa.Self(), *Locks::thread_list_lock_);
Ian Rogersc0542af2014-09-03 16:16:56 -07002170 JDWP::JdwpError error;
2171 Thread* thread = DecodeThread(soa, thread_id, &error);
Elliott Hughesf9501702013-01-11 11:22:27 -08002172 if (error != JDWP::ERR_NONE) {
2173 return error;
2174 }
Ian Rogersdd7624d2014-03-14 17:43:00 -07002175 thread->Interrupt(soa.Self());
Elliott Hughesf9501702013-01-11 11:22:27 -08002176 return JDWP::ERR_NONE;
2177}
2178
Sebastien Hertz070f7322014-09-09 12:08:49 +02002179static bool IsInDesiredThreadGroup(ScopedObjectAccessUnchecked& soa,
2180 mirror::Object* desired_thread_group, mirror::Object* peer)
2181 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
2182 // Do we want threads from all thread groups?
2183 if (desired_thread_group == nullptr) {
2184 return true;
2185 }
2186 mirror::ArtField* thread_group_field = soa.DecodeField(WellKnownClasses::java_lang_Thread_group);
2187 DCHECK(thread_group_field != nullptr);
2188 mirror::Object* group = thread_group_field->GetObject(peer);
2189 return (group == desired_thread_group);
2190}
2191
Sebastien Hertza06430c2014-09-15 19:21:30 +02002192void Dbg::GetThreads(mirror::Object* thread_group, std::vector<JDWP::ObjectId>* thread_ids) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002193 ScopedObjectAccessUnchecked soa(Thread::Current());
Sebastien Hertz070f7322014-09-09 12:08:49 +02002194 std::list<Thread*> all_threads_list;
2195 {
2196 MutexLock mu(Thread::Current(), *Locks::thread_list_lock_);
2197 all_threads_list = Runtime::Current()->GetThreadList()->GetList();
2198 }
2199 for (Thread* t : all_threads_list) {
2200 if (t == Dbg::GetDebugThread()) {
2201 // Skip the JDWP thread. Some debuggers get bent out of shape when they can't suspend and
2202 // query all threads, so it's easier if we just don't tell them about this thread.
2203 continue;
2204 }
2205 if (t->IsStillStarting()) {
2206 // This thread is being started (and has been registered in the thread list). However, it is
2207 // not completely started yet so we must ignore it.
2208 continue;
2209 }
2210 mirror::Object* peer = t->GetPeer();
2211 if (peer == nullptr) {
2212 // peer might be NULL if the thread is still starting up. We can't tell the debugger about
2213 // this thread yet.
2214 // TODO: if we identified threads to the debugger by their Thread*
2215 // rather than their peer's mirror::Object*, we could fix this.
2216 // Doing so might help us report ZOMBIE threads too.
2217 continue;
2218 }
2219 if (IsInDesiredThreadGroup(soa, thread_group, peer)) {
2220 thread_ids->push_back(gRegistry->Add(peer));
2221 }
2222 }
Elliott Hughescaf76542012-06-28 16:08:22 -07002223}
Elliott Hughesa2155262011-11-16 16:26:58 -08002224
Ian Rogersc0542af2014-09-03 16:16:56 -07002225static int GetStackDepth(Thread* thread) SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Ian Rogers0399dde2012-06-06 17:09:28 -07002226 struct CountStackDepthVisitor : public StackVisitor {
Brian Carlstrom93ba8932013-07-17 21:31:49 -07002227 explicit CountStackDepthVisitor(Thread* thread)
Ian Rogersc0542af2014-09-03 16:16:56 -07002228 : StackVisitor(thread, nullptr), depth(0) {}
Ian Rogers0399dde2012-06-06 17:09:28 -07002229
Elliott Hughes64f574f2013-02-20 14:57:12 -08002230 // TODO: Enable annotalysis. We know lock is held in constructor, but abstraction confuses
2231 // annotalysis.
2232 bool VisitFrame() NO_THREAD_SAFETY_ANALYSIS {
Ian Rogers0399dde2012-06-06 17:09:28 -07002233 if (!GetMethod()->IsRuntimeMethod()) {
Elliott Hughesf8a2df72011-12-01 12:19:54 -08002234 ++depth;
2235 }
Elliott Hughes530fa002012-03-12 11:44:49 -07002236 return true;
Elliott Hughesa2e54f62011-11-17 13:01:30 -08002237 }
2238 size_t depth;
2239 };
Elliott Hughes08fc03a2012-06-26 17:34:00 -07002240
Ian Rogers7a22fa62013-01-23 12:16:16 -08002241 CountStackDepthVisitor visitor(thread);
Ian Rogers0399dde2012-06-06 17:09:28 -07002242 visitor.WalkStack();
Elliott Hughesa2e54f62011-11-17 13:01:30 -08002243 return visitor.depth;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002244}
2245
Ian Rogersc0542af2014-09-03 16:16:56 -07002246JDWP::JdwpError Dbg::GetThreadFrameCount(JDWP::ObjectId thread_id, size_t* result) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002247 ScopedObjectAccess soa(Thread::Current());
jeffhaoa77f0f62012-12-05 17:19:31 -08002248 MutexLock mu(soa.Self(), *Locks::thread_list_lock_);
Ian Rogersc0542af2014-09-03 16:16:56 -07002249 JDWP::JdwpError error;
2250 *result = 0;
2251 Thread* thread = DecodeThread(soa, thread_id, &error);
Elliott Hughes221229c2013-01-08 18:17:50 -08002252 if (error != JDWP::ERR_NONE) {
2253 return error;
2254 }
Elliott Hughesf15f4a02013-01-09 10:09:38 -08002255 if (!IsSuspendedForDebugger(soa, thread)) {
2256 return JDWP::ERR_THREAD_NOT_SUSPENDED;
2257 }
Ian Rogersc0542af2014-09-03 16:16:56 -07002258 *result = GetStackDepth(thread);
Elliott Hughes221229c2013-01-08 18:17:50 -08002259 return JDWP::ERR_NONE;
Elliott Hughes86964332012-02-15 19:37:42 -08002260}
2261
Ian Rogers306057f2012-11-26 12:45:53 -08002262JDWP::JdwpError Dbg::GetThreadFrames(JDWP::ObjectId thread_id, size_t start_frame,
2263 size_t frame_count, JDWP::ExpandBuf* buf) {
Elliott Hughes6e9d22c2012-06-22 15:02:37 -07002264 class GetFrameVisitor : public StackVisitor {
2265 public:
Ian Rogers7a22fa62013-01-23 12:16:16 -08002266 GetFrameVisitor(Thread* thread, size_t start_frame, size_t frame_count, JDWP::ExpandBuf* buf)
Ian Rogersb726dcb2012-09-05 08:57:23 -07002267 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_)
Ian Rogersc0542af2014-09-03 16:16:56 -07002268 : StackVisitor(thread, nullptr), depth_(0),
Elliott Hughes6e9d22c2012-06-22 15:02:37 -07002269 start_frame_(start_frame), frame_count_(frame_count), buf_(buf) {
2270 expandBufAdd4BE(buf_, frame_count_);
Elliott Hughes03181a82011-11-17 17:22:21 -08002271 }
Ian Rogers0399dde2012-06-06 17:09:28 -07002272
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002273 // TODO: Enable annotalysis. We know lock is held in constructor, but abstraction confuses
2274 // annotalysis.
2275 virtual bool VisitFrame() NO_THREAD_SAFETY_ANALYSIS {
Ian Rogers0399dde2012-06-06 17:09:28 -07002276 if (GetMethod()->IsRuntimeMethod()) {
Brian Carlstrom7934ac22013-07-26 10:54:15 -07002277 return true; // The debugger can't do anything useful with a frame that has no Method*.
Elliott Hughes03181a82011-11-17 17:22:21 -08002278 }
Elliott Hughes6e9d22c2012-06-22 15:02:37 -07002279 if (depth_ >= start_frame_ + frame_count_) {
Elliott Hughes530fa002012-03-12 11:44:49 -07002280 return false;
Elliott Hughes03181a82011-11-17 17:22:21 -08002281 }
Elliott Hughes6e9d22c2012-06-22 15:02:37 -07002282 if (depth_ >= start_frame_) {
2283 JDWP::FrameId frame_id(GetFrameId());
2284 JDWP::JdwpLocation location;
Ian Rogersc0542af2014-09-03 16:16:56 -07002285 SetLocation(&location, GetMethod(), GetDexPc());
Ian Rogersef7d42f2014-01-06 12:55:46 -08002286 VLOG(jdwp) << StringPrintf(" Frame %3zd: id=%3" PRIu64 " ", depth_, frame_id) << location;
Elliott Hughes6e9d22c2012-06-22 15:02:37 -07002287 expandBufAdd8BE(buf_, frame_id);
2288 expandBufAddLocation(buf_, location);
2289 }
2290 ++depth_;
Elliott Hughes530fa002012-03-12 11:44:49 -07002291 return true;
Elliott Hughes03181a82011-11-17 17:22:21 -08002292 }
Elliott Hughes6e9d22c2012-06-22 15:02:37 -07002293
2294 private:
2295 size_t depth_;
2296 const size_t start_frame_;
2297 const size_t frame_count_;
2298 JDWP::ExpandBuf* buf_;
Elliott Hughes03181a82011-11-17 17:22:21 -08002299 };
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002300
2301 ScopedObjectAccessUnchecked soa(Thread::Current());
jeffhaoa77f0f62012-12-05 17:19:31 -08002302 MutexLock mu(soa.Self(), *Locks::thread_list_lock_);
Ian Rogersc0542af2014-09-03 16:16:56 -07002303 JDWP::JdwpError error;
2304 Thread* thread = DecodeThread(soa, thread_id, &error);
Elliott Hughes221229c2013-01-08 18:17:50 -08002305 if (error != JDWP::ERR_NONE) {
2306 return error;
2307 }
Elliott Hughesf15f4a02013-01-09 10:09:38 -08002308 if (!IsSuspendedForDebugger(soa, thread)) {
2309 return JDWP::ERR_THREAD_NOT_SUSPENDED;
2310 }
Ian Rogers7a22fa62013-01-23 12:16:16 -08002311 GetFrameVisitor visitor(thread, start_frame, frame_count, buf);
Ian Rogers0399dde2012-06-06 17:09:28 -07002312 visitor.WalkStack();
Elliott Hughes6e9d22c2012-06-22 15:02:37 -07002313 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002314}
2315
2316JDWP::ObjectId Dbg::GetThreadSelfId() {
Mathieu Chartierdbe6f462012-09-25 16:54:50 -07002317 ScopedObjectAccessUnchecked soa(Thread::Current());
Ian Rogerscfaa4552012-11-26 21:00:08 -08002318 return gRegistry->Add(soa.Self()->GetPeer());
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002319}
2320
Elliott Hughes475fc232011-10-25 15:00:35 -07002321void Dbg::SuspendVM() {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002322 Runtime::Current()->GetThreadList()->SuspendAllForDebugger();
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002323}
2324
2325void Dbg::ResumeVM() {
Elliott Hughesc61a2672012-06-21 14:52:29 -07002326 Runtime::Current()->GetThreadList()->UndoDebuggerSuspensions();
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002327}
2328
Elliott Hughes221229c2013-01-08 18:17:50 -08002329JDWP::JdwpError Dbg::SuspendThread(JDWP::ObjectId thread_id, bool request_suspension) {
Ian Rogersf3d874c2014-07-17 18:52:42 -07002330 Thread* self = Thread::Current();
Ian Rogersc0542af2014-09-03 16:16:56 -07002331 ScopedLocalRef<jobject> peer(self->GetJniEnv(), nullptr);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002332 {
Ian Rogersf3d874c2014-07-17 18:52:42 -07002333 ScopedObjectAccess soa(self);
Ian Rogersc0542af2014-09-03 16:16:56 -07002334 JDWP::JdwpError error;
2335 peer.reset(soa.AddLocalReference<jobject>(gRegistry->Get<mirror::Object*>(thread_id, &error)));
Elliott Hughes4e235312011-12-02 11:34:15 -08002336 }
Ian Rogersc0542af2014-09-03 16:16:56 -07002337 if (peer.get() == nullptr) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002338 return JDWP::ERR_THREAD_NOT_ALIVE;
2339 }
Ian Rogersf3d874c2014-07-17 18:52:42 -07002340 // Suspend thread to build stack trace. Take suspend thread lock to avoid races with threads
2341 // trying to suspend this one.
2342 MutexLock mu(self, *Locks::thread_list_suspend_thread_lock_);
Elliott Hughesf327e072013-01-09 16:01:26 -08002343 bool timed_out;
Brian Carlstromba32de42014-08-27 23:43:46 -07002344 ThreadList* thread_list = Runtime::Current()->GetThreadList();
2345 Thread* thread = thread_list->SuspendThreadByPeer(peer.get(), request_suspension, true,
2346 &timed_out);
Ian Rogersc0542af2014-09-03 16:16:56 -07002347 if (thread != nullptr) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002348 return JDWP::ERR_NONE;
Elliott Hughesf327e072013-01-09 16:01:26 -08002349 } else if (timed_out) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002350 return JDWP::ERR_INTERNAL;
2351 } else {
2352 return JDWP::ERR_THREAD_NOT_ALIVE;
2353 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002354}
2355
Elliott Hughes221229c2013-01-08 18:17:50 -08002356void Dbg::ResumeThread(JDWP::ObjectId thread_id) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002357 ScopedObjectAccessUnchecked soa(Thread::Current());
Ian Rogersc0542af2014-09-03 16:16:56 -07002358 JDWP::JdwpError error;
2359 mirror::Object* peer = gRegistry->Get<mirror::Object*>(thread_id, &error);
2360 CHECK(peer != nullptr) << error;
jeffhaoa77f0f62012-12-05 17:19:31 -08002361 Thread* thread;
2362 {
2363 MutexLock mu(soa.Self(), *Locks::thread_list_lock_);
2364 thread = Thread::FromManagedThread(soa, peer);
2365 }
Ian Rogersc0542af2014-09-03 16:16:56 -07002366 if (thread == nullptr) {
Elliott Hughes4e235312011-12-02 11:34:15 -08002367 LOG(WARNING) << "No such thread for resume: " << peer;
2368 return;
2369 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002370 bool needs_resume;
2371 {
Ian Rogers50b35e22012-10-04 10:09:15 -07002372 MutexLock mu2(soa.Self(), *Locks::thread_suspend_count_lock_);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002373 needs_resume = thread->GetSuspendCount() > 0;
2374 }
2375 if (needs_resume) {
Elliott Hughes546b9862012-06-20 16:06:13 -07002376 Runtime::Current()->GetThreadList()->Resume(thread, true);
2377 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002378}
2379
2380void Dbg::SuspendSelf() {
Elliott Hughes475fc232011-10-25 15:00:35 -07002381 Runtime::Current()->GetThreadList()->SuspendSelfForDebugger();
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002382}
2383
Ian Rogers0399dde2012-06-06 17:09:28 -07002384struct GetThisVisitor : public StackVisitor {
Ian Rogers7a22fa62013-01-23 12:16:16 -08002385 GetThisVisitor(Thread* thread, Context* context, JDWP::FrameId frame_id)
Ian Rogersb726dcb2012-09-05 08:57:23 -07002386 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_)
Ian Rogersc0542af2014-09-03 16:16:56 -07002387 : StackVisitor(thread, context), this_object(nullptr), frame_id(frame_id) {}
Ian Rogers0399dde2012-06-06 17:09:28 -07002388
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002389 // TODO: Enable annotalysis. We know lock is held in constructor, but abstraction confuses
2390 // annotalysis.
2391 virtual bool VisitFrame() NO_THREAD_SAFETY_ANALYSIS {
Elliott Hughes6e9d22c2012-06-22 15:02:37 -07002392 if (frame_id != GetFrameId()) {
Ian Rogers0399dde2012-06-06 17:09:28 -07002393 return true; // continue
Ian Rogers0399dde2012-06-06 17:09:28 -07002394 } else {
Ian Rogers62d6c772013-02-27 08:32:07 -08002395 this_object = GetThisObject();
2396 return false;
Ian Rogers0399dde2012-06-06 17:09:28 -07002397 }
Elliott Hughes86b00102011-12-05 17:54:26 -08002398 }
Ian Rogers0399dde2012-06-06 17:09:28 -07002399
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002400 mirror::Object* this_object;
Elliott Hughes6e9d22c2012-06-22 15:02:37 -07002401 JDWP::FrameId frame_id;
Ian Rogers0399dde2012-06-06 17:09:28 -07002402};
2403
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002404JDWP::JdwpError Dbg::GetThisObject(JDWP::ObjectId thread_id, JDWP::FrameId frame_id,
2405 JDWP::ObjectId* result) {
2406 ScopedObjectAccessUnchecked soa(Thread::Current());
2407 Thread* thread;
2408 {
Ian Rogers50b35e22012-10-04 10:09:15 -07002409 MutexLock mu(soa.Self(), *Locks::thread_list_lock_);
Ian Rogersc0542af2014-09-03 16:16:56 -07002410 JDWP::JdwpError error;
2411 thread = DecodeThread(soa, thread_id, &error);
Elliott Hughes221229c2013-01-08 18:17:50 -08002412 if (error != JDWP::ERR_NONE) {
2413 return error;
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002414 }
Elliott Hughes9e0c1752013-01-09 14:02:58 -08002415 if (!IsSuspendedForDebugger(soa, thread)) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002416 return JDWP::ERR_THREAD_NOT_SUSPENDED;
2417 }
Elliott Hughes6e9d22c2012-06-22 15:02:37 -07002418 }
Ian Rogers700a4022014-05-19 16:49:03 -07002419 std::unique_ptr<Context> context(Context::Create());
Ian Rogers7a22fa62013-01-23 12:16:16 -08002420 GetThisVisitor visitor(thread, context.get(), frame_id);
Ian Rogers0399dde2012-06-06 17:09:28 -07002421 visitor.WalkStack();
Elliott Hughes6e9d22c2012-06-22 15:02:37 -07002422 *result = gRegistry->Add(visitor.this_object);
2423 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002424}
2425
Sebastien Hertzcb19ebf2014-03-11 15:26:35 +01002426JDWP::JdwpError Dbg::GetLocalValue(JDWP::ObjectId thread_id, JDWP::FrameId frame_id, int slot,
2427 JDWP::JdwpTag tag, uint8_t* buf, size_t width) {
Ian Rogers0399dde2012-06-06 17:09:28 -07002428 struct GetLocalVisitor : public StackVisitor {
Ian Rogers98379392014-02-24 16:53:16 -08002429 GetLocalVisitor(const ScopedObjectAccessUnchecked& soa, Thread* thread, Context* context,
2430 JDWP::FrameId frame_id, int slot, JDWP::JdwpTag tag, uint8_t* buf, size_t width)
Ian Rogersb726dcb2012-09-05 08:57:23 -07002431 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_)
Ian Rogers98379392014-02-24 16:53:16 -08002432 : StackVisitor(thread, context), soa_(soa), frame_id_(frame_id), slot_(slot), tag_(tag),
Sebastien Hertzcb19ebf2014-03-11 15:26:35 +01002433 buf_(buf), width_(width), error_(JDWP::ERR_NONE) {}
Ian Rogersca190662012-06-26 15:45:57 -07002434
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002435 // TODO: Enable annotalysis. We know lock is held in constructor, but abstraction confuses
2436 // annotalysis.
2437 bool VisitFrame() NO_THREAD_SAFETY_ANALYSIS {
Ian Rogers0399dde2012-06-06 17:09:28 -07002438 if (GetFrameId() != frame_id_) {
2439 return true; // Not our frame, carry on.
Elliott Hughesdbb40792011-11-18 17:05:22 -08002440 }
Ian Rogers0399dde2012-06-06 17:09:28 -07002441 // TODO: check that the tag is compatible with the actual type of the slot!
Sebastien Hertzcb19ebf2014-03-11 15:26:35 +01002442 // TODO: check slot is valid for this method or return INVALID_SLOT error.
Brian Carlstromea46f952013-07-30 01:26:50 -07002443 mirror::ArtMethod* m = GetMethod();
Sebastien Hertzcb19ebf2014-03-11 15:26:35 +01002444 if (m->IsNative()) {
2445 // We can't read local value from native method.
2446 error_ = JDWP::ERR_OPAQUE_FRAME;
2447 return false;
2448 }
Ian Rogers0399dde2012-06-06 17:09:28 -07002449 uint16_t reg = DemangleSlot(slot_, m);
Sebastien Hertz0bcb2902014-06-17 15:52:45 +02002450 constexpr JDWP::JdwpError kFailureErrorCode = JDWP::ERR_ABSENT_INFORMATION;
Ian Rogers0399dde2012-06-06 17:09:28 -07002451 switch (tag_) {
Sebastien Hertz0bcb2902014-06-17 15:52:45 +02002452 case JDWP::JT_BOOLEAN: {
Ian Rogers0399dde2012-06-06 17:09:28 -07002453 CHECK_EQ(width_, 1U);
Sebastien Hertz0bcb2902014-06-17 15:52:45 +02002454 uint32_t intVal;
2455 if (GetVReg(m, reg, kIntVReg, &intVal)) {
2456 VLOG(jdwp) << "get boolean local " << reg << " = " << intVal;
2457 JDWP::Set1(buf_+1, intVal != 0);
2458 } else {
2459 VLOG(jdwp) << "failed to get boolean local " << reg;
2460 error_ = kFailureErrorCode;
2461 }
2462 break;
Ian Rogers0399dde2012-06-06 17:09:28 -07002463 }
Sebastien Hertz0bcb2902014-06-17 15:52:45 +02002464 case JDWP::JT_BYTE: {
Ian Rogers0399dde2012-06-06 17:09:28 -07002465 CHECK_EQ(width_, 1U);
Sebastien Hertz0bcb2902014-06-17 15:52:45 +02002466 uint32_t intVal;
2467 if (GetVReg(m, reg, kIntVReg, &intVal)) {
2468 VLOG(jdwp) << "get byte local " << reg << " = " << intVal;
2469 JDWP::Set1(buf_+1, intVal);
2470 } else {
2471 VLOG(jdwp) << "failed to get byte local " << reg;
2472 error_ = kFailureErrorCode;
2473 }
2474 break;
Ian Rogers0399dde2012-06-06 17:09:28 -07002475 }
Sebastien Hertz0bcb2902014-06-17 15:52:45 +02002476 case JDWP::JT_SHORT:
2477 case JDWP::JT_CHAR: {
Ian Rogers0399dde2012-06-06 17:09:28 -07002478 CHECK_EQ(width_, 2U);
Sebastien Hertz0bcb2902014-06-17 15:52:45 +02002479 uint32_t intVal;
2480 if (GetVReg(m, reg, kIntVReg, &intVal)) {
2481 VLOG(jdwp) << "get short/char local " << reg << " = " << intVal;
2482 JDWP::Set2BE(buf_+1, intVal);
2483 } else {
2484 VLOG(jdwp) << "failed to get short/char local " << reg;
2485 error_ = kFailureErrorCode;
Sebastien Hertzaa9b3ae2014-06-13 14:49:27 +02002486 }
Sebastien Hertz0bcb2902014-06-17 15:52:45 +02002487 break;
Sebastien Hertzaa9b3ae2014-06-13 14:49:27 +02002488 }
Sebastien Hertz0bcb2902014-06-17 15:52:45 +02002489 case JDWP::JT_INT: {
2490 CHECK_EQ(width_, 4U);
2491 uint32_t intVal;
2492 if (GetVReg(m, reg, kIntVReg, &intVal)) {
2493 VLOG(jdwp) << "get int local " << reg << " = " << intVal;
2494 JDWP::Set4BE(buf_+1, intVal);
2495 } else {
2496 VLOG(jdwp) << "failed to get int local " << reg;
2497 error_ = kFailureErrorCode;
Sebastien Hertz8ebd94a2014-06-17 09:49:21 +00002498 }
Sebastien Hertz0bcb2902014-06-17 15:52:45 +02002499 break;
Sebastien Hertz8ebd94a2014-06-17 09:49:21 +00002500 }
Sebastien Hertz0bcb2902014-06-17 15:52:45 +02002501 case JDWP::JT_FLOAT: {
2502 CHECK_EQ(width_, 4U);
2503 uint32_t intVal;
2504 if (GetVReg(m, reg, kFloatVReg, &intVal)) {
2505 VLOG(jdwp) << "get float local " << reg << " = " << intVal;
2506 JDWP::Set4BE(buf_+1, intVal);
2507 } else {
2508 VLOG(jdwp) << "failed to get float local " << reg;
2509 error_ = kFailureErrorCode;
2510 }
2511 break;
2512 }
2513 case JDWP::JT_ARRAY:
2514 case JDWP::JT_CLASS_LOADER:
2515 case JDWP::JT_CLASS_OBJECT:
2516 case JDWP::JT_OBJECT:
2517 case JDWP::JT_STRING:
2518 case JDWP::JT_THREAD:
2519 case JDWP::JT_THREAD_GROUP: {
2520 CHECK_EQ(width_, sizeof(JDWP::ObjectId));
2521 uint32_t intVal;
2522 if (GetVReg(m, reg, kReferenceVReg, &intVal)) {
2523 mirror::Object* o = reinterpret_cast<mirror::Object*>(intVal);
2524 VLOG(jdwp) << "get " << tag_ << " object local " << reg << " = " << o;
2525 if (!Runtime::Current()->GetHeap()->IsValidObjectAddress(o)) {
2526 LOG(FATAL) << "Register " << reg << " expected to hold " << tag_ << " object: " << o;
2527 }
2528 tag_ = TagFromObject(soa_, o);
2529 JDWP::SetObjectId(buf_+1, gRegistry->Add(o));
2530 } else {
2531 VLOG(jdwp) << "failed to get " << tag_ << " object local " << reg;
2532 error_ = kFailureErrorCode;
2533 }
2534 break;
2535 }
2536 case JDWP::JT_DOUBLE: {
Ian Rogers2bcb4a42012-11-08 10:39:18 -08002537 CHECK_EQ(width_, 8U);
Sebastien Hertzc901dd72014-07-16 11:56:07 +02002538 uint64_t longVal;
2539 if (GetVRegPair(m, reg, kDoubleLoVReg, kDoubleHiVReg, &longVal)) {
2540 VLOG(jdwp) << "get double local " << reg << " = " << longVal;
Sebastien Hertz0bcb2902014-06-17 15:52:45 +02002541 JDWP::Set8BE(buf_+1, longVal);
2542 } else {
2543 VLOG(jdwp) << "failed to get double local " << reg;
2544 error_ = kFailureErrorCode;
2545 }
2546 break;
Ian Rogers2bcb4a42012-11-08 10:39:18 -08002547 }
Sebastien Hertz0bcb2902014-06-17 15:52:45 +02002548 case JDWP::JT_LONG: {
Ian Rogers0399dde2012-06-06 17:09:28 -07002549 CHECK_EQ(width_, 8U);
Sebastien Hertzc901dd72014-07-16 11:56:07 +02002550 uint64_t longVal;
2551 if (GetVRegPair(m, reg, kLongLoVReg, kLongHiVReg, &longVal)) {
2552 VLOG(jdwp) << "get long local " << reg << " = " << longVal;
Sebastien Hertz0bcb2902014-06-17 15:52:45 +02002553 JDWP::Set8BE(buf_+1, longVal);
2554 } else {
2555 VLOG(jdwp) << "failed to get long local " << reg;
2556 error_ = kFailureErrorCode;
2557 }
2558 break;
Ian Rogers0399dde2012-06-06 17:09:28 -07002559 }
Sebastien Hertz0bcb2902014-06-17 15:52:45 +02002560 default:
2561 LOG(FATAL) << "Unknown tag " << tag_;
2562 break;
Ian Rogers0399dde2012-06-06 17:09:28 -07002563 }
2564
2565 // Prepend tag, which may have been updated.
2566 JDWP::Set1(buf_, tag_);
2567 return false;
2568 }
Ian Rogers98379392014-02-24 16:53:16 -08002569 const ScopedObjectAccessUnchecked& soa_;
Ian Rogers0399dde2012-06-06 17:09:28 -07002570 const JDWP::FrameId frame_id_;
2571 const int slot_;
2572 JDWP::JdwpTag tag_;
2573 uint8_t* const buf_;
2574 const size_t width_;
Sebastien Hertzcb19ebf2014-03-11 15:26:35 +01002575 JDWP::JdwpError error_;
Ian Rogers0399dde2012-06-06 17:09:28 -07002576 };
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002577
2578 ScopedObjectAccessUnchecked soa(Thread::Current());
jeffhaoa77f0f62012-12-05 17:19:31 -08002579 MutexLock mu(soa.Self(), *Locks::thread_list_lock_);
Ian Rogersc0542af2014-09-03 16:16:56 -07002580 JDWP::JdwpError error;
2581 Thread* thread = DecodeThread(soa, thread_id, &error);
Elliott Hughes221229c2013-01-08 18:17:50 -08002582 if (error != JDWP::ERR_NONE) {
Sebastien Hertzcb19ebf2014-03-11 15:26:35 +01002583 return error;
Elliott Hughes221229c2013-01-08 18:17:50 -08002584 }
Sebastien Hertzcb19ebf2014-03-11 15:26:35 +01002585 // TODO check thread is suspended by the debugger ?
Ian Rogers700a4022014-05-19 16:49:03 -07002586 std::unique_ptr<Context> context(Context::Create());
Ian Rogers98379392014-02-24 16:53:16 -08002587 GetLocalVisitor visitor(soa, thread, context.get(), frame_id, slot, tag, buf, width);
Ian Rogers0399dde2012-06-06 17:09:28 -07002588 visitor.WalkStack();
Sebastien Hertzcb19ebf2014-03-11 15:26:35 +01002589 return visitor.error_;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002590}
2591
Sebastien Hertzcb19ebf2014-03-11 15:26:35 +01002592JDWP::JdwpError Dbg::SetLocalValue(JDWP::ObjectId thread_id, JDWP::FrameId frame_id, int slot,
2593 JDWP::JdwpTag tag, uint64_t value, size_t width) {
Ian Rogers0399dde2012-06-06 17:09:28 -07002594 struct SetLocalVisitor : public StackVisitor {
Ian Rogers7a22fa62013-01-23 12:16:16 -08002595 SetLocalVisitor(Thread* thread, Context* context,
Ian Rogers0399dde2012-06-06 17:09:28 -07002596 JDWP::FrameId frame_id, int slot, JDWP::JdwpTag tag, uint64_t value,
Ian Rogersca190662012-06-26 15:45:57 -07002597 size_t width)
Ian Rogersb726dcb2012-09-05 08:57:23 -07002598 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_)
Ian Rogers7a22fa62013-01-23 12:16:16 -08002599 : StackVisitor(thread, context),
Sebastien Hertzcb19ebf2014-03-11 15:26:35 +01002600 frame_id_(frame_id), slot_(slot), tag_(tag), value_(value), width_(width),
2601 error_(JDWP::ERR_NONE) {}
Ian Rogersca190662012-06-26 15:45:57 -07002602
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002603 // TODO: Enable annotalysis. We know lock is held in constructor, but abstraction confuses
2604 // annotalysis.
2605 bool VisitFrame() NO_THREAD_SAFETY_ANALYSIS {
Ian Rogers0399dde2012-06-06 17:09:28 -07002606 if (GetFrameId() != frame_id_) {
2607 return true; // Not our frame, carry on.
2608 }
2609 // TODO: check that the tag is compatible with the actual type of the slot!
Sebastien Hertzcb19ebf2014-03-11 15:26:35 +01002610 // TODO: check slot is valid for this method or return INVALID_SLOT error.
Brian Carlstromea46f952013-07-30 01:26:50 -07002611 mirror::ArtMethod* m = GetMethod();
Sebastien Hertzcb19ebf2014-03-11 15:26:35 +01002612 if (m->IsNative()) {
2613 // We can't read local value from native method.
2614 error_ = JDWP::ERR_OPAQUE_FRAME;
2615 return false;
2616 }
Ian Rogers0399dde2012-06-06 17:09:28 -07002617 uint16_t reg = DemangleSlot(slot_, m);
Sebastien Hertz0bcb2902014-06-17 15:52:45 +02002618 constexpr JDWP::JdwpError kFailureErrorCode = JDWP::ERR_ABSENT_INFORMATION;
Ian Rogers0399dde2012-06-06 17:09:28 -07002619 switch (tag_) {
2620 case JDWP::JT_BOOLEAN:
2621 case JDWP::JT_BYTE:
2622 CHECK_EQ(width_, 1U);
Sebastien Hertz0bcb2902014-06-17 15:52:45 +02002623 if (!SetVReg(m, reg, static_cast<uint32_t>(value_), kIntVReg)) {
2624 VLOG(jdwp) << "failed to set boolean/byte local " << reg << " = "
2625 << static_cast<uint32_t>(value_);
2626 error_ = kFailureErrorCode;
2627 }
Ian Rogers0399dde2012-06-06 17:09:28 -07002628 break;
2629 case JDWP::JT_SHORT:
2630 case JDWP::JT_CHAR:
2631 CHECK_EQ(width_, 2U);
Sebastien Hertz0bcb2902014-06-17 15:52:45 +02002632 if (!SetVReg(m, reg, static_cast<uint32_t>(value_), kIntVReg)) {
2633 VLOG(jdwp) << "failed to set short/char local " << reg << " = "
2634 << static_cast<uint32_t>(value_);
2635 error_ = kFailureErrorCode;
2636 }
Ian Rogers0399dde2012-06-06 17:09:28 -07002637 break;
2638 case JDWP::JT_INT:
Ian Rogers2bcb4a42012-11-08 10:39:18 -08002639 CHECK_EQ(width_, 4U);
Sebastien Hertz0bcb2902014-06-17 15:52:45 +02002640 if (!SetVReg(m, reg, static_cast<uint32_t>(value_), kIntVReg)) {
2641 VLOG(jdwp) << "failed to set int local " << reg << " = "
2642 << static_cast<uint32_t>(value_);
2643 error_ = kFailureErrorCode;
2644 }
Ian Rogers2bcb4a42012-11-08 10:39:18 -08002645 break;
Ian Rogers0399dde2012-06-06 17:09:28 -07002646 case JDWP::JT_FLOAT:
2647 CHECK_EQ(width_, 4U);
Sebastien Hertz0bcb2902014-06-17 15:52:45 +02002648 if (!SetVReg(m, reg, static_cast<uint32_t>(value_), kFloatVReg)) {
2649 VLOG(jdwp) << "failed to set float local " << reg << " = "
2650 << static_cast<uint32_t>(value_);
2651 error_ = kFailureErrorCode;
2652 }
Ian Rogers0399dde2012-06-06 17:09:28 -07002653 break;
2654 case JDWP::JT_ARRAY:
Sebastien Hertz0bcb2902014-06-17 15:52:45 +02002655 case JDWP::JT_CLASS_LOADER:
2656 case JDWP::JT_CLASS_OBJECT:
Ian Rogers0399dde2012-06-06 17:09:28 -07002657 case JDWP::JT_OBJECT:
2658 case JDWP::JT_STRING:
Sebastien Hertz0bcb2902014-06-17 15:52:45 +02002659 case JDWP::JT_THREAD:
2660 case JDWP::JT_THREAD_GROUP: {
Ian Rogers0399dde2012-06-06 17:09:28 -07002661 CHECK_EQ(width_, sizeof(JDWP::ObjectId));
Ian Rogersc0542af2014-09-03 16:16:56 -07002662 JDWP::JdwpError error;
2663 mirror::Object* o =
2664 gRegistry->Get<mirror::Object*>(static_cast<JDWP::ObjectId>(value_), &error);
2665 if (error != JDWP::ERR_NONE) {
2666 VLOG(jdwp) << tag_ << " object " << value_ << " is an invalid object";
Sebastien Hertz0bcb2902014-06-17 15:52:45 +02002667 error_ = JDWP::ERR_INVALID_OBJECT;
2668 } else if (!SetVReg(m, reg, static_cast<uint32_t>(reinterpret_cast<uintptr_t>(o)),
2669 kReferenceVReg)) {
2670 VLOG(jdwp) << "failed to set " << tag_ << " object local " << reg << " = " << o;
2671 error_ = kFailureErrorCode;
Ian Rogers0399dde2012-06-06 17:09:28 -07002672 }
Sebastien Hertz0bcb2902014-06-17 15:52:45 +02002673 break;
Ian Rogers0399dde2012-06-06 17:09:28 -07002674 }
Sebastien Hertz0bcb2902014-06-17 15:52:45 +02002675 case JDWP::JT_DOUBLE: {
Ian Rogers2bcb4a42012-11-08 10:39:18 -08002676 CHECK_EQ(width_, 8U);
Sebastien Hertzc901dd72014-07-16 11:56:07 +02002677 bool success = SetVRegPair(m, reg, value_, kDoubleLoVReg, kDoubleHiVReg);
Sebastien Hertz0bcb2902014-06-17 15:52:45 +02002678 if (!success) {
Sebastien Hertzc901dd72014-07-16 11:56:07 +02002679 VLOG(jdwp) << "failed to set double local " << reg << " = " << value_;
Sebastien Hertz0bcb2902014-06-17 15:52:45 +02002680 error_ = kFailureErrorCode;
2681 }
Ian Rogers2bcb4a42012-11-08 10:39:18 -08002682 break;
Sebastien Hertz0bcb2902014-06-17 15:52:45 +02002683 }
2684 case JDWP::JT_LONG: {
Ian Rogers0399dde2012-06-06 17:09:28 -07002685 CHECK_EQ(width_, 8U);
Sebastien Hertzc901dd72014-07-16 11:56:07 +02002686 bool success = SetVRegPair(m, reg, value_, kLongLoVReg, kLongHiVReg);
Sebastien Hertz0bcb2902014-06-17 15:52:45 +02002687 if (!success) {
Sebastien Hertzc901dd72014-07-16 11:56:07 +02002688 VLOG(jdwp) << "failed to set double local " << reg << " = " << value_;
Sebastien Hertz0bcb2902014-06-17 15:52:45 +02002689 error_ = kFailureErrorCode;
2690 }
Ian Rogers0399dde2012-06-06 17:09:28 -07002691 break;
Sebastien Hertz0bcb2902014-06-17 15:52:45 +02002692 }
Ian Rogers0399dde2012-06-06 17:09:28 -07002693 default:
2694 LOG(FATAL) << "Unknown tag " << tag_;
2695 break;
2696 }
2697 return false;
2698 }
2699
2700 const JDWP::FrameId frame_id_;
2701 const int slot_;
2702 const JDWP::JdwpTag tag_;
2703 const uint64_t value_;
2704 const size_t width_;
Sebastien Hertzcb19ebf2014-03-11 15:26:35 +01002705 JDWP::JdwpError error_;
Ian Rogers0399dde2012-06-06 17:09:28 -07002706 };
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002707
2708 ScopedObjectAccessUnchecked soa(Thread::Current());
jeffhaoa77f0f62012-12-05 17:19:31 -08002709 MutexLock mu(soa.Self(), *Locks::thread_list_lock_);
Ian Rogersc0542af2014-09-03 16:16:56 -07002710 JDWP::JdwpError error;
2711 Thread* thread = DecodeThread(soa, thread_id, &error);
Elliott Hughes221229c2013-01-08 18:17:50 -08002712 if (error != JDWP::ERR_NONE) {
Sebastien Hertzcb19ebf2014-03-11 15:26:35 +01002713 return error;
Elliott Hughes221229c2013-01-08 18:17:50 -08002714 }
Sebastien Hertzcb19ebf2014-03-11 15:26:35 +01002715 // TODO check thread is suspended by the debugger ?
Ian Rogers700a4022014-05-19 16:49:03 -07002716 std::unique_ptr<Context> context(Context::Create());
Ian Rogers7a22fa62013-01-23 12:16:16 -08002717 SetLocalVisitor visitor(thread, context.get(), frame_id, slot, tag, value, width);
Ian Rogers0399dde2012-06-06 17:09:28 -07002718 visitor.WalkStack();
Sebastien Hertzcb19ebf2014-03-11 15:26:35 +01002719 return visitor.error_;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002720}
2721
Sebastien Hertz3f52eaf2014-04-04 17:50:18 +02002722JDWP::ObjectId Dbg::GetThisObjectIdForEvent(mirror::Object* this_object) {
2723 // If 'this_object' isn't already in the registry, we know that we're not looking for it, so
2724 // there's no point adding it to the registry and burning through ids.
2725 // When registering an event request with an instance filter, we've been given an existing object
2726 // id so it must already be present in the registry when the event fires.
2727 JDWP::ObjectId this_id = 0;
2728 if (this_object != nullptr && gRegistry->Contains(this_object)) {
2729 this_id = gRegistry->Add(this_object);
2730 }
2731 return this_id;
2732}
2733
Ian Rogersef7d42f2014-01-06 12:55:46 -08002734void Dbg::PostLocationEvent(mirror::ArtMethod* m, int dex_pc, mirror::Object* this_object,
Jeff Hao579b0242013-11-18 13:16:49 -08002735 int event_flags, const JValue* return_value) {
Sebastien Hertz3f52eaf2014-04-04 17:50:18 +02002736 if (!IsDebuggerActive()) {
2737 return;
2738 }
2739 DCHECK(m != nullptr);
2740 DCHECK_EQ(m->IsStatic(), this_object == nullptr);
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08002741 JDWP::JdwpLocation location;
Ian Rogersc0542af2014-09-03 16:16:56 -07002742 SetLocation(&location, m, dex_pc);
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08002743
Sebastien Hertz3f52eaf2014-04-04 17:50:18 +02002744 // We need 'this' for InstanceOnly filters only.
2745 JDWP::ObjectId this_id = GetThisObjectIdForEvent(this_object);
Jeff Hao579b0242013-11-18 13:16:49 -08002746 gJdwpState->PostLocationEvent(&location, this_id, event_flags, return_value);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002747}
2748
Sebastien Hertz3f52eaf2014-04-04 17:50:18 +02002749void Dbg::PostFieldAccessEvent(mirror::ArtMethod* m, int dex_pc,
2750 mirror::Object* this_object, mirror::ArtField* f) {
2751 if (!IsDebuggerActive()) {
2752 return;
2753 }
2754 DCHECK(m != nullptr);
2755 DCHECK(f != nullptr);
2756 JDWP::JdwpLocation location;
Ian Rogersc0542af2014-09-03 16:16:56 -07002757 SetLocation(&location, m, dex_pc);
Sebastien Hertz3f52eaf2014-04-04 17:50:18 +02002758
2759 JDWP::RefTypeId type_id = gRegistry->AddRefType(f->GetDeclaringClass());
2760 JDWP::FieldId field_id = ToFieldId(f);
2761 JDWP::ObjectId this_id = gRegistry->Add(this_object);
2762
2763 gJdwpState->PostFieldEvent(&location, type_id, field_id, this_id, nullptr, false);
2764}
2765
2766void Dbg::PostFieldModificationEvent(mirror::ArtMethod* m, int dex_pc,
2767 mirror::Object* this_object, mirror::ArtField* f,
2768 const JValue* field_value) {
2769 if (!IsDebuggerActive()) {
2770 return;
2771 }
2772 DCHECK(m != nullptr);
2773 DCHECK(f != nullptr);
2774 DCHECK(field_value != nullptr);
2775 JDWP::JdwpLocation location;
Ian Rogersc0542af2014-09-03 16:16:56 -07002776 SetLocation(&location, m, dex_pc);
Sebastien Hertz3f52eaf2014-04-04 17:50:18 +02002777
2778 JDWP::RefTypeId type_id = gRegistry->AddRefType(f->GetDeclaringClass());
2779 JDWP::FieldId field_id = ToFieldId(f);
2780 JDWP::ObjectId this_id = gRegistry->Add(this_object);
2781
2782 gJdwpState->PostFieldEvent(&location, type_id, field_id, this_id, field_value, true);
2783}
2784
2785void Dbg::PostException(const ThrowLocation& throw_location,
Brian Carlstromea46f952013-07-30 01:26:50 -07002786 mirror::ArtMethod* catch_method,
Elliott Hughes64f574f2013-02-20 14:57:12 -08002787 uint32_t catch_dex_pc, mirror::Throwable* exception_object) {
Elliott Hughesc0f09332012-03-26 13:27:06 -07002788 if (!IsDebuggerActive()) {
Ian Rogers0ad5bb82011-12-07 10:16:32 -08002789 return;
2790 }
Elliott Hughes4740cdf2011-12-07 14:07:12 -08002791
Ian Rogers62d6c772013-02-27 08:32:07 -08002792 JDWP::JdwpLocation jdwp_throw_location;
Ian Rogersc0542af2014-09-03 16:16:56 -07002793 SetLocation(&jdwp_throw_location, throw_location.GetMethod(), throw_location.GetDexPc());
Elliott Hughesd07986f2011-12-06 18:27:45 -08002794 JDWP::JdwpLocation catch_location;
Ian Rogersc0542af2014-09-03 16:16:56 -07002795 SetLocation(&catch_location, catch_method, catch_dex_pc);
Elliott Hughesd07986f2011-12-06 18:27:45 -08002796
Sebastien Hertz3f52eaf2014-04-04 17:50:18 +02002797 // We need 'this' for InstanceOnly filters only.
2798 JDWP::ObjectId this_id = GetThisObjectIdForEvent(throw_location.GetThis());
Elliott Hughes64f574f2013-02-20 14:57:12 -08002799 JDWP::ObjectId exception_id = gRegistry->Add(exception_object);
2800 JDWP::RefTypeId exception_class_id = gRegistry->AddRefType(exception_object->GetClass());
Elliott Hughesd07986f2011-12-06 18:27:45 -08002801
Ian Rogers62d6c772013-02-27 08:32:07 -08002802 gJdwpState->PostException(&jdwp_throw_location, exception_id, exception_class_id, &catch_location,
2803 this_id);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002804}
2805
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002806void Dbg::PostClassPrepare(mirror::Class* c) {
Elliott Hughesc0f09332012-03-26 13:27:06 -07002807 if (!IsDebuggerActive()) {
Elliott Hughes4740cdf2011-12-07 14:07:12 -08002808 return;
2809 }
2810
Elliott Hughes3d30d9b2011-12-07 17:35:48 -08002811 // OLD-TODO - we currently always send both "verified" and "prepared" since
Elliott Hughes4740cdf2011-12-07 14:07:12 -08002812 // debuggers seem to like that. There might be some advantage to honesty,
2813 // since the class may not yet be verified.
2814 int state = JDWP::CS_VERIFIED | JDWP::CS_PREPARED;
Sebastien Hertz4d8fd492014-03-28 16:29:41 +01002815 JDWP::JdwpTypeTag tag = GetTypeTag(c);
Ian Rogers1ff3c982014-08-12 02:30:58 -07002816 std::string temp;
2817 gJdwpState->PostClassPrepare(tag, gRegistry->Add(c), c->GetDescriptor(&temp), state);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002818}
2819
Ian Rogers62d6c772013-02-27 08:32:07 -08002820void Dbg::UpdateDebugger(Thread* thread, mirror::Object* this_object,
Sebastien Hertz8379b222014-02-24 17:38:15 +01002821 mirror::ArtMethod* m, uint32_t dex_pc,
2822 int event_flags, const JValue* return_value) {
Ian Rogers62d6c772013-02-27 08:32:07 -08002823 if (!IsDebuggerActive() || dex_pc == static_cast<uint32_t>(-2) /* fake method exit */) {
Elliott Hughes2aa2e392012-02-17 17:15:43 -08002824 return;
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08002825 }
2826
Elliott Hughes86964332012-02-15 19:37:42 -08002827 if (IsBreakpoint(m, dex_pc)) {
2828 event_flags |= kBreakpoint;
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08002829 }
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08002830
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01002831 // If the debugger is single-stepping one of our threads, check to
2832 // see if we're that thread and we've reached a step point.
2833 const SingleStepControl* single_step_control = thread->GetSingleStepControl();
2834 DCHECK(single_step_control != nullptr);
2835 if (single_step_control->is_active) {
2836 CHECK(!m->IsNative());
2837 if (single_step_control->step_depth == JDWP::SD_INTO) {
2838 // Step into method calls. We break when the line number
2839 // or method pointer changes. If we're in SS_MIN mode, we
2840 // always stop.
2841 if (single_step_control->method != m) {
2842 event_flags |= kSingleStep;
2843 VLOG(jdwp) << "SS new method";
2844 } else if (single_step_control->step_size == JDWP::SS_MIN) {
2845 event_flags |= kSingleStep;
2846 VLOG(jdwp) << "SS new instruction";
Sebastien Hertzbb43b432014-04-14 11:59:08 +02002847 } else if (single_step_control->ContainsDexPc(dex_pc)) {
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01002848 event_flags |= kSingleStep;
2849 VLOG(jdwp) << "SS new line";
2850 }
2851 } else if (single_step_control->step_depth == JDWP::SD_OVER) {
2852 // Step over method calls. We break when the line number is
2853 // different and the frame depth is <= the original frame
2854 // depth. (We can't just compare on the method, because we
2855 // might get unrolled past it by an exception, and it's tricky
2856 // to identify recursion.)
2857
2858 int stack_depth = GetStackDepth(thread);
2859
2860 if (stack_depth < single_step_control->stack_depth) {
2861 // Popped up one or more frames, always trigger.
2862 event_flags |= kSingleStep;
2863 VLOG(jdwp) << "SS method pop";
2864 } else if (stack_depth == single_step_control->stack_depth) {
2865 // Same depth, see if we moved.
2866 if (single_step_control->step_size == JDWP::SS_MIN) {
Elliott Hughes86964332012-02-15 19:37:42 -08002867 event_flags |= kSingleStep;
2868 VLOG(jdwp) << "SS new instruction";
Sebastien Hertzbb43b432014-04-14 11:59:08 +02002869 } else if (single_step_control->ContainsDexPc(dex_pc)) {
Elliott Hughes2435a572012-02-17 16:07:41 -08002870 event_flags |= kSingleStep;
2871 VLOG(jdwp) << "SS new line";
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08002872 }
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01002873 }
2874 } else {
2875 CHECK_EQ(single_step_control->step_depth, JDWP::SD_OUT);
2876 // Return from the current method. We break when the frame
2877 // depth pops up.
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08002878
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01002879 // This differs from the "method exit" break in that it stops
2880 // with the PC at the next instruction in the returned-to
2881 // function, rather than the end of the returning function.
Elliott Hughes86964332012-02-15 19:37:42 -08002882
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01002883 int stack_depth = GetStackDepth(thread);
2884 if (stack_depth < single_step_control->stack_depth) {
2885 event_flags |= kSingleStep;
2886 VLOG(jdwp) << "SS method pop";
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08002887 }
2888 }
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08002889 }
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08002890
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08002891 // If there's something interesting going on, see if it matches one
2892 // of the debugger filters.
2893 if (event_flags != 0) {
Sebastien Hertz8379b222014-02-24 17:38:15 +01002894 Dbg::PostLocationEvent(m, dex_pc, this_object, event_flags, return_value);
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08002895 }
2896}
2897
Sebastien Hertz42cd43f2014-05-13 14:15:41 +02002898size_t* Dbg::GetReferenceCounterForEvent(uint32_t instrumentation_event) {
2899 switch (instrumentation_event) {
2900 case instrumentation::Instrumentation::kMethodEntered:
2901 return &method_enter_event_ref_count_;
2902 case instrumentation::Instrumentation::kMethodExited:
2903 return &method_exit_event_ref_count_;
2904 case instrumentation::Instrumentation::kDexPcMoved:
2905 return &dex_pc_change_event_ref_count_;
2906 case instrumentation::Instrumentation::kFieldRead:
2907 return &field_read_event_ref_count_;
2908 case instrumentation::Instrumentation::kFieldWritten:
2909 return &field_write_event_ref_count_;
2910 case instrumentation::Instrumentation::kExceptionCaught:
2911 return &exception_catch_event_ref_count_;
2912 default:
2913 return nullptr;
2914 }
2915}
2916
Sebastien Hertz4d25df32014-03-21 17:44:46 +01002917// Process request while all mutator threads are suspended.
2918void Dbg::ProcessDeoptimizationRequest(const DeoptimizationRequest& request) {
Sebastien Hertz138dbfc2013-12-04 18:15:25 +01002919 instrumentation::Instrumentation* instrumentation = Runtime::Current()->GetInstrumentation();
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07002920 switch (request.GetKind()) {
Sebastien Hertz4d25df32014-03-21 17:44:46 +01002921 case DeoptimizationRequest::kNothing:
2922 LOG(WARNING) << "Ignoring empty deoptimization request.";
2923 break;
Sebastien Hertz42cd43f2014-05-13 14:15:41 +02002924 case DeoptimizationRequest::kRegisterForEvent:
2925 VLOG(jdwp) << StringPrintf("Add debugger as listener for instrumentation event 0x%x",
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07002926 request.InstrumentationEvent());
2927 instrumentation->AddListener(&gDebugInstrumentationListener, request.InstrumentationEvent());
2928 instrumentation_events_ |= request.InstrumentationEvent();
Sebastien Hertz42cd43f2014-05-13 14:15:41 +02002929 break;
2930 case DeoptimizationRequest::kUnregisterForEvent:
2931 VLOG(jdwp) << StringPrintf("Remove debugger as listener for instrumentation event 0x%x",
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07002932 request.InstrumentationEvent());
Sebastien Hertz42cd43f2014-05-13 14:15:41 +02002933 instrumentation->RemoveListener(&gDebugInstrumentationListener,
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07002934 request.InstrumentationEvent());
2935 instrumentation_events_ &= ~request.InstrumentationEvent();
Sebastien Hertz42cd43f2014-05-13 14:15:41 +02002936 break;
Sebastien Hertz4d25df32014-03-21 17:44:46 +01002937 case DeoptimizationRequest::kFullDeoptimization:
Sebastien Hertz7ec2f1c2014-03-27 20:06:47 +01002938 VLOG(jdwp) << "Deoptimize the world ...";
Sebastien Hertz4d25df32014-03-21 17:44:46 +01002939 instrumentation->DeoptimizeEverything();
Sebastien Hertz7ec2f1c2014-03-27 20:06:47 +01002940 VLOG(jdwp) << "Deoptimize the world DONE";
Sebastien Hertz4d25df32014-03-21 17:44:46 +01002941 break;
2942 case DeoptimizationRequest::kFullUndeoptimization:
Sebastien Hertz7ec2f1c2014-03-27 20:06:47 +01002943 VLOG(jdwp) << "Undeoptimize the world ...";
Sebastien Hertz4d25df32014-03-21 17:44:46 +01002944 instrumentation->UndeoptimizeEverything();
Sebastien Hertz7ec2f1c2014-03-27 20:06:47 +01002945 VLOG(jdwp) << "Undeoptimize the world DONE";
Sebastien Hertz4d25df32014-03-21 17:44:46 +01002946 break;
2947 case DeoptimizationRequest::kSelectiveDeoptimization:
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07002948 VLOG(jdwp) << "Deoptimize method " << PrettyMethod(request.Method()) << " ...";
2949 instrumentation->Deoptimize(request.Method());
2950 VLOG(jdwp) << "Deoptimize method " << PrettyMethod(request.Method()) << " DONE";
Sebastien Hertz4d25df32014-03-21 17:44:46 +01002951 break;
2952 case DeoptimizationRequest::kSelectiveUndeoptimization:
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07002953 VLOG(jdwp) << "Undeoptimize method " << PrettyMethod(request.Method()) << " ...";
2954 instrumentation->Undeoptimize(request.Method());
2955 VLOG(jdwp) << "Undeoptimize method " << PrettyMethod(request.Method()) << " DONE";
Sebastien Hertz4d25df32014-03-21 17:44:46 +01002956 break;
2957 default:
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07002958 LOG(FATAL) << "Unsupported deoptimization request kind " << request.GetKind();
Sebastien Hertz4d25df32014-03-21 17:44:46 +01002959 break;
Sebastien Hertz138dbfc2013-12-04 18:15:25 +01002960 }
Sebastien Hertz138dbfc2013-12-04 18:15:25 +01002961}
2962
Sebastien Hertz7ec2f1c2014-03-27 20:06:47 +01002963void Dbg::DelayFullUndeoptimization() {
Brian Carlstrom306db812014-09-05 13:01:41 -07002964 MutexLock mu(Thread::Current(), *Locks::deoptimization_lock_);
Sebastien Hertz7ec2f1c2014-03-27 20:06:47 +01002965 ++delayed_full_undeoptimization_count_;
2966 DCHECK_LE(delayed_full_undeoptimization_count_, full_deoptimization_event_count_);
2967}
2968
2969void Dbg::ProcessDelayedFullUndeoptimizations() {
2970 // TODO: avoid taking the lock twice (once here and once in ManageDeoptimization).
2971 {
Brian Carlstrom306db812014-09-05 13:01:41 -07002972 MutexLock mu(Thread::Current(), *Locks::deoptimization_lock_);
Sebastien Hertz7ec2f1c2014-03-27 20:06:47 +01002973 while (delayed_full_undeoptimization_count_ > 0) {
2974 DeoptimizationRequest req;
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07002975 req.SetKind(DeoptimizationRequest::kFullUndeoptimization);
2976 req.SetMethod(nullptr);
Sebastien Hertz7ec2f1c2014-03-27 20:06:47 +01002977 RequestDeoptimizationLocked(req);
2978 --delayed_full_undeoptimization_count_;
2979 }
2980 }
2981 ManageDeoptimization();
2982}
2983
Sebastien Hertz4d25df32014-03-21 17:44:46 +01002984void Dbg::RequestDeoptimization(const DeoptimizationRequest& req) {
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07002985 if (req.GetKind() == DeoptimizationRequest::kNothing) {
Sebastien Hertz4d25df32014-03-21 17:44:46 +01002986 // Nothing to do.
2987 return;
2988 }
Brian Carlstrom306db812014-09-05 13:01:41 -07002989 MutexLock mu(Thread::Current(), *Locks::deoptimization_lock_);
Sebastien Hertz7ec2f1c2014-03-27 20:06:47 +01002990 RequestDeoptimizationLocked(req);
2991}
2992
2993void Dbg::RequestDeoptimizationLocked(const DeoptimizationRequest& req) {
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07002994 switch (req.GetKind()) {
Sebastien Hertz42cd43f2014-05-13 14:15:41 +02002995 case DeoptimizationRequest::kRegisterForEvent: {
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07002996 DCHECK_NE(req.InstrumentationEvent(), 0u);
2997 size_t* counter = GetReferenceCounterForEvent(req.InstrumentationEvent());
Sebastien Hertz42cd43f2014-05-13 14:15:41 +02002998 CHECK(counter != nullptr) << StringPrintf("No counter for instrumentation event 0x%x",
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07002999 req.InstrumentationEvent());
Sebastien Hertz42cd43f2014-05-13 14:15:41 +02003000 if (*counter == 0) {
Sebastien Hertz7d2ae432014-05-15 11:26:34 +02003001 VLOG(jdwp) << StringPrintf("Queue request #%zd to start listening to instrumentation event 0x%x",
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003002 deoptimization_requests_.size(), req.InstrumentationEvent());
Sebastien Hertz42cd43f2014-05-13 14:15:41 +02003003 deoptimization_requests_.push_back(req);
3004 }
3005 *counter = *counter + 1;
3006 break;
3007 }
3008 case DeoptimizationRequest::kUnregisterForEvent: {
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003009 DCHECK_NE(req.InstrumentationEvent(), 0u);
3010 size_t* counter = GetReferenceCounterForEvent(req.InstrumentationEvent());
Sebastien Hertz42cd43f2014-05-13 14:15:41 +02003011 CHECK(counter != nullptr) << StringPrintf("No counter for instrumentation event 0x%x",
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003012 req.InstrumentationEvent());
Sebastien Hertz42cd43f2014-05-13 14:15:41 +02003013 *counter = *counter - 1;
3014 if (*counter == 0) {
Sebastien Hertz7d2ae432014-05-15 11:26:34 +02003015 VLOG(jdwp) << StringPrintf("Queue request #%zd to stop listening to instrumentation event 0x%x",
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003016 deoptimization_requests_.size(), req.InstrumentationEvent());
Sebastien Hertz42cd43f2014-05-13 14:15:41 +02003017 deoptimization_requests_.push_back(req);
3018 }
3019 break;
3020 }
Sebastien Hertz4d25df32014-03-21 17:44:46 +01003021 case DeoptimizationRequest::kFullDeoptimization: {
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003022 DCHECK(req.Method() == nullptr);
Sebastien Hertz4d25df32014-03-21 17:44:46 +01003023 if (full_deoptimization_event_count_ == 0) {
Sebastien Hertz7ec2f1c2014-03-27 20:06:47 +01003024 VLOG(jdwp) << "Queue request #" << deoptimization_requests_.size()
3025 << " for full deoptimization";
Sebastien Hertz4d25df32014-03-21 17:44:46 +01003026 deoptimization_requests_.push_back(req);
3027 }
3028 ++full_deoptimization_event_count_;
3029 break;
3030 }
3031 case DeoptimizationRequest::kFullUndeoptimization: {
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003032 DCHECK(req.Method() == nullptr);
Sebastien Hertze713d932014-05-15 10:48:53 +02003033 DCHECK_GT(full_deoptimization_event_count_, 0U);
Sebastien Hertz4d25df32014-03-21 17:44:46 +01003034 --full_deoptimization_event_count_;
3035 if (full_deoptimization_event_count_ == 0) {
Sebastien Hertz7ec2f1c2014-03-27 20:06:47 +01003036 VLOG(jdwp) << "Queue request #" << deoptimization_requests_.size()
3037 << " for full undeoptimization";
Sebastien Hertz4d25df32014-03-21 17:44:46 +01003038 deoptimization_requests_.push_back(req);
3039 }
3040 break;
3041 }
3042 case DeoptimizationRequest::kSelectiveDeoptimization: {
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003043 DCHECK(req.Method() != nullptr);
Sebastien Hertz7ec2f1c2014-03-27 20:06:47 +01003044 VLOG(jdwp) << "Queue request #" << deoptimization_requests_.size()
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003045 << " for deoptimization of " << PrettyMethod(req.Method());
Sebastien Hertz4d25df32014-03-21 17:44:46 +01003046 deoptimization_requests_.push_back(req);
3047 break;
3048 }
3049 case DeoptimizationRequest::kSelectiveUndeoptimization: {
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003050 DCHECK(req.Method() != nullptr);
Sebastien Hertz7ec2f1c2014-03-27 20:06:47 +01003051 VLOG(jdwp) << "Queue request #" << deoptimization_requests_.size()
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003052 << " for undeoptimization of " << PrettyMethod(req.Method());
Sebastien Hertz4d25df32014-03-21 17:44:46 +01003053 deoptimization_requests_.push_back(req);
3054 break;
3055 }
3056 default: {
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003057 LOG(FATAL) << "Unknown deoptimization request kind " << req.GetKind();
Sebastien Hertz4d25df32014-03-21 17:44:46 +01003058 break;
3059 }
3060 }
3061}
3062
Sebastien Hertz138dbfc2013-12-04 18:15:25 +01003063void Dbg::ManageDeoptimization() {
3064 Thread* const self = Thread::Current();
3065 {
3066 // Avoid suspend/resume if there is no pending request.
Brian Carlstrom306db812014-09-05 13:01:41 -07003067 MutexLock mu(self, *Locks::deoptimization_lock_);
Sebastien Hertz4d25df32014-03-21 17:44:46 +01003068 if (deoptimization_requests_.empty()) {
Sebastien Hertz138dbfc2013-12-04 18:15:25 +01003069 return;
3070 }
3071 }
3072 CHECK_EQ(self->GetState(), kRunnable);
3073 self->TransitionFromRunnableToSuspended(kWaitingForDeoptimization);
3074 // We need to suspend mutator threads first.
3075 Runtime* const runtime = Runtime::Current();
3076 runtime->GetThreadList()->SuspendAll();
3077 const ThreadState old_state = self->SetStateUnsafe(kRunnable);
Sebastien Hertz4d25df32014-03-21 17:44:46 +01003078 {
Brian Carlstrom306db812014-09-05 13:01:41 -07003079 MutexLock mu(self, *Locks::deoptimization_lock_);
Sebastien Hertz7ec2f1c2014-03-27 20:06:47 +01003080 size_t req_index = 0;
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003081 for (DeoptimizationRequest& request : deoptimization_requests_) {
Sebastien Hertz7ec2f1c2014-03-27 20:06:47 +01003082 VLOG(jdwp) << "Process deoptimization request #" << req_index++;
Sebastien Hertz4d25df32014-03-21 17:44:46 +01003083 ProcessDeoptimizationRequest(request);
3084 }
3085 deoptimization_requests_.clear();
3086 }
Sebastien Hertz138dbfc2013-12-04 18:15:25 +01003087 CHECK_EQ(self->SetStateUnsafe(old_state), kRunnable);
3088 runtime->GetThreadList()->ResumeAll();
3089 self->TransitionFromSuspendedToRunnable();
3090}
3091
Sebastien Hertza76a6d42014-03-20 16:40:17 +01003092static bool IsMethodPossiblyInlined(Thread* self, mirror::ArtMethod* m)
3093 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07003094 const DexFile::CodeItem* code_item = m->GetCodeItem();
Sebastien Hertza76a6d42014-03-20 16:40:17 +01003095 if (code_item == nullptr) {
3096 // TODO We should not be asked to watch location in a native or abstract method so the code item
3097 // should never be null. We could just check we never encounter this case.
3098 return false;
Sebastien Hertz138dbfc2013-12-04 18:15:25 +01003099 }
Hiroshi Yamauchidc376172014-08-22 11:13:12 -07003100 StackHandleScope<3> hs(self);
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07003101 mirror::Class* declaring_class = m->GetDeclaringClass();
3102 Handle<mirror::DexCache> dex_cache(hs.NewHandle(declaring_class->GetDexCache()));
3103 Handle<mirror::ClassLoader> class_loader(hs.NewHandle(declaring_class->GetClassLoader()));
Hiroshi Yamauchidc376172014-08-22 11:13:12 -07003104 Handle<mirror::ArtMethod> method(hs.NewHandle(m));
Ian Rogers7b078e82014-09-10 14:44:24 -07003105 verifier::MethodVerifier verifier(self, dex_cache->GetDexFile(), dex_cache, class_loader,
Hiroshi Yamauchidc376172014-08-22 11:13:12 -07003106 &m->GetClassDef(), code_item, m->GetDexMethodIndex(), method,
Ian Rogers46960fe2014-05-23 10:43:43 -07003107 m->GetAccessFlags(), false, true, false);
Sebastien Hertza76a6d42014-03-20 16:40:17 +01003108 // Note: we don't need to verify the method.
3109 return InlineMethodAnalyser::AnalyseMethodCode(&verifier, nullptr);
3110}
Sebastien Hertz138dbfc2013-12-04 18:15:25 +01003111
Sebastien Hertza76a6d42014-03-20 16:40:17 +01003112static const Breakpoint* FindFirstBreakpointForMethod(mirror::ArtMethod* m)
Sebastien Hertzed2be172014-08-19 15:33:43 +02003113 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_, Locks::breakpoint_lock_) {
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003114 for (Breakpoint& breakpoint : gBreakpoints) {
3115 if (breakpoint.Method() == m) {
Sebastien Hertza76a6d42014-03-20 16:40:17 +01003116 return &breakpoint;
3117 }
3118 }
3119 return nullptr;
3120}
3121
3122// Sanity checks all existing breakpoints on the same method.
3123static void SanityCheckExistingBreakpoints(mirror::ArtMethod* m, bool need_full_deoptimization)
Sebastien Hertzed2be172014-08-19 15:33:43 +02003124 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_, Locks::breakpoint_lock_) {
Sebastien Hertza76a6d42014-03-20 16:40:17 +01003125 if (kIsDebugBuild) {
3126 for (const Breakpoint& breakpoint : gBreakpoints) {
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003127 CHECK_EQ(need_full_deoptimization, breakpoint.NeedFullDeoptimization());
Sebastien Hertza76a6d42014-03-20 16:40:17 +01003128 }
3129 if (need_full_deoptimization) {
3130 // We should have deoptimized everything but not "selectively" deoptimized this method.
3131 CHECK(Runtime::Current()->GetInstrumentation()->AreAllMethodsDeoptimized());
3132 CHECK(!Runtime::Current()->GetInstrumentation()->IsDeoptimized(m));
3133 } else {
3134 // We should have "selectively" deoptimized this method.
3135 // Note: while we have not deoptimized everything for this method, we may have done it for
3136 // another event.
3137 CHECK(Runtime::Current()->GetInstrumentation()->IsDeoptimized(m));
3138 }
Sebastien Hertz138dbfc2013-12-04 18:15:25 +01003139 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -07003140}
3141
Sebastien Hertza76a6d42014-03-20 16:40:17 +01003142// Installs a breakpoint at the specified location. Also indicates through the deoptimization
3143// request if we need to deoptimize.
3144void Dbg::WatchLocation(const JDWP::JdwpLocation* location, DeoptimizationRequest* req) {
3145 Thread* const self = Thread::Current();
Brian Carlstromea46f952013-07-30 01:26:50 -07003146 mirror::ArtMethod* m = FromMethodId(location->method_id);
Sebastien Hertza76a6d42014-03-20 16:40:17 +01003147 DCHECK(m != nullptr) << "No method for method id " << location->method_id;
Sebastien Hertz138dbfc2013-12-04 18:15:25 +01003148
Sebastien Hertzed2be172014-08-19 15:33:43 +02003149 WriterMutexLock mu(self, *Locks::breakpoint_lock_);
Sebastien Hertza76a6d42014-03-20 16:40:17 +01003150 const Breakpoint* const existing_breakpoint = FindFirstBreakpointForMethod(m);
3151 bool need_full_deoptimization;
3152 if (existing_breakpoint == nullptr) {
3153 // There is no breakpoint on this method yet: we need to deoptimize. If this method may be
3154 // inlined, we deoptimize everything; otherwise we deoptimize only this method.
3155 need_full_deoptimization = IsMethodPossiblyInlined(self, m);
3156 if (need_full_deoptimization) {
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003157 req->SetKind(DeoptimizationRequest::kFullDeoptimization);
3158 req->SetMethod(nullptr);
Sebastien Hertza76a6d42014-03-20 16:40:17 +01003159 } else {
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003160 req->SetKind(DeoptimizationRequest::kSelectiveDeoptimization);
3161 req->SetMethod(m);
Sebastien Hertz138dbfc2013-12-04 18:15:25 +01003162 }
Sebastien Hertza76a6d42014-03-20 16:40:17 +01003163 } else {
3164 // There is at least one breakpoint for this method: we don't need to deoptimize.
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003165 req->SetKind(DeoptimizationRequest::kNothing);
3166 req->SetMethod(nullptr);
Sebastien Hertza76a6d42014-03-20 16:40:17 +01003167
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003168 need_full_deoptimization = existing_breakpoint->NeedFullDeoptimization();
Sebastien Hertza76a6d42014-03-20 16:40:17 +01003169 SanityCheckExistingBreakpoints(m, need_full_deoptimization);
Sebastien Hertz138dbfc2013-12-04 18:15:25 +01003170 }
3171
Sebastien Hertza76a6d42014-03-20 16:40:17 +01003172 gBreakpoints.push_back(Breakpoint(m, location->dex_pc, need_full_deoptimization));
3173 VLOG(jdwp) << "Set breakpoint #" << (gBreakpoints.size() - 1) << ": "
3174 << gBreakpoints[gBreakpoints.size() - 1];
3175}
3176
3177// Uninstalls a breakpoint at the specified location. Also indicates through the deoptimization
3178// request if we need to undeoptimize.
3179void Dbg::UnwatchLocation(const JDWP::JdwpLocation* location, DeoptimizationRequest* req) {
Sebastien Hertzed2be172014-08-19 15:33:43 +02003180 WriterMutexLock mu(Thread::Current(), *Locks::breakpoint_lock_);
Sebastien Hertza76a6d42014-03-20 16:40:17 +01003181 mirror::ArtMethod* m = FromMethodId(location->method_id);
3182 DCHECK(m != nullptr) << "No method for method id " << location->method_id;
Sebastien Hertza76a6d42014-03-20 16:40:17 +01003183 bool need_full_deoptimization = false;
3184 for (size_t i = 0, e = gBreakpoints.size(); i < e; ++i) {
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003185 if (gBreakpoints[i].DexPc() == location->dex_pc && gBreakpoints[i].Method() == m) {
Sebastien Hertza76a6d42014-03-20 16:40:17 +01003186 VLOG(jdwp) << "Removed breakpoint #" << i << ": " << gBreakpoints[i];
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003187 need_full_deoptimization = gBreakpoints[i].NeedFullDeoptimization();
Sebastien Hertza76a6d42014-03-20 16:40:17 +01003188 DCHECK_NE(need_full_deoptimization, Runtime::Current()->GetInstrumentation()->IsDeoptimized(m));
3189 gBreakpoints.erase(gBreakpoints.begin() + i);
3190 break;
3191 }
3192 }
3193 const Breakpoint* const existing_breakpoint = FindFirstBreakpointForMethod(m);
3194 if (existing_breakpoint == nullptr) {
3195 // There is no more breakpoint on this method: we need to undeoptimize.
3196 if (need_full_deoptimization) {
3197 // This method required full deoptimization: we need to undeoptimize everything.
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003198 req->SetKind(DeoptimizationRequest::kFullUndeoptimization);
3199 req->SetMethod(nullptr);
Sebastien Hertza76a6d42014-03-20 16:40:17 +01003200 } else {
3201 // This method required selective deoptimization: we need to undeoptimize only that method.
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003202 req->SetKind(DeoptimizationRequest::kSelectiveUndeoptimization);
3203 req->SetMethod(m);
Sebastien Hertza76a6d42014-03-20 16:40:17 +01003204 }
3205 } else {
3206 // There is at least one breakpoint for this method: we don't need to undeoptimize.
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003207 req->SetKind(DeoptimizationRequest::kNothing);
3208 req->SetMethod(nullptr);
Sebastien Hertza76a6d42014-03-20 16:40:17 +01003209 SanityCheckExistingBreakpoints(m, need_full_deoptimization);
Elliott Hughes86964332012-02-15 19:37:42 -08003210 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -07003211}
3212
Jeff Hao449db332013-04-12 18:30:52 -07003213// Scoped utility class to suspend a thread so that we may do tasks such as walk its stack. Doesn't
3214// cause suspension if the thread is the current thread.
3215class ScopedThreadSuspension {
3216 public:
Ian Rogers33e95662013-05-20 20:29:14 -07003217 ScopedThreadSuspension(Thread* self, JDWP::ObjectId thread_id)
Sebastien Hertz52d131d2014-03-13 16:17:40 +01003218 LOCKS_EXCLUDED(Locks::thread_list_lock_)
Ian Rogers33e95662013-05-20 20:29:14 -07003219 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) :
Ian Rogersf3d874c2014-07-17 18:52:42 -07003220 thread_(nullptr),
Jeff Hao449db332013-04-12 18:30:52 -07003221 error_(JDWP::ERR_NONE),
3222 self_suspend_(false),
Ian Rogers33e95662013-05-20 20:29:14 -07003223 other_suspend_(false) {
Jeff Hao449db332013-04-12 18:30:52 -07003224 ScopedObjectAccessUnchecked soa(self);
3225 {
3226 MutexLock mu(soa.Self(), *Locks::thread_list_lock_);
Ian Rogersc0542af2014-09-03 16:16:56 -07003227 thread_ = DecodeThread(soa, thread_id, &error_);
Jeff Hao449db332013-04-12 18:30:52 -07003228 }
3229 if (error_ == JDWP::ERR_NONE) {
3230 if (thread_ == soa.Self()) {
3231 self_suspend_ = true;
3232 } else {
3233 soa.Self()->TransitionFromRunnableToSuspended(kWaitingForDebuggerSuspension);
3234 jobject thread_peer = gRegistry->GetJObject(thread_id);
3235 bool timed_out;
Ian Rogersf3d874c2014-07-17 18:52:42 -07003236 Thread* suspended_thread;
3237 {
3238 // Take suspend thread lock to avoid races with threads trying to suspend this one.
3239 MutexLock mu(soa.Self(), *Locks::thread_list_suspend_thread_lock_);
Brian Carlstromba32de42014-08-27 23:43:46 -07003240 ThreadList* thread_list = Runtime::Current()->GetThreadList();
3241 suspended_thread = thread_list->SuspendThreadByPeer(thread_peer, true, true, &timed_out);
Ian Rogersf3d874c2014-07-17 18:52:42 -07003242 }
Jeff Hao449db332013-04-12 18:30:52 -07003243 CHECK_EQ(soa.Self()->TransitionFromSuspendedToRunnable(), kWaitingForDebuggerSuspension);
Ian Rogersf3d874c2014-07-17 18:52:42 -07003244 if (suspended_thread == nullptr) {
Jeff Hao449db332013-04-12 18:30:52 -07003245 // Thread terminated from under us while suspending.
3246 error_ = JDWP::ERR_INVALID_THREAD;
3247 } else {
3248 CHECK_EQ(suspended_thread, thread_);
3249 other_suspend_ = true;
3250 }
3251 }
3252 }
Elliott Hughes2435a572012-02-17 16:07:41 -08003253 }
Elliott Hughes86964332012-02-15 19:37:42 -08003254
Jeff Hao449db332013-04-12 18:30:52 -07003255 Thread* GetThread() const {
3256 return thread_;
3257 }
3258
3259 JDWP::JdwpError GetError() const {
3260 return error_;
3261 }
3262
3263 ~ScopedThreadSuspension() {
3264 if (other_suspend_) {
3265 Runtime::Current()->GetThreadList()->Resume(thread_, true);
3266 }
3267 }
3268
3269 private:
3270 Thread* thread_;
3271 JDWP::JdwpError error_;
3272 bool self_suspend_;
3273 bool other_suspend_;
3274};
3275
3276JDWP::JdwpError Dbg::ConfigureStep(JDWP::ObjectId thread_id, JDWP::JdwpStepSize step_size,
3277 JDWP::JdwpStepDepth step_depth) {
3278 Thread* self = Thread::Current();
3279 ScopedThreadSuspension sts(self, thread_id);
3280 if (sts.GetError() != JDWP::ERR_NONE) {
3281 return sts.GetError();
3282 }
3283
Elliott Hughes2435a572012-02-17 16:07:41 -08003284 //
3285 // Work out what Method* we're in, the current line number, and how deep the stack currently
3286 // is for step-out.
3287 //
3288
Ian Rogers0399dde2012-06-06 17:09:28 -07003289 struct SingleStepStackVisitor : public StackVisitor {
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01003290 explicit SingleStepStackVisitor(Thread* thread, SingleStepControl* single_step_control,
3291 int32_t* line_number)
Ian Rogersb726dcb2012-09-05 08:57:23 -07003292 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_)
Ian Rogersc0542af2014-09-03 16:16:56 -07003293 : StackVisitor(thread, nullptr), single_step_control_(single_step_control),
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01003294 line_number_(line_number) {
3295 DCHECK_EQ(single_step_control_, thread->GetSingleStepControl());
Ian Rogersc0542af2014-09-03 16:16:56 -07003296 single_step_control_->method = nullptr;
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01003297 single_step_control_->stack_depth = 0;
Elliott Hughes86964332012-02-15 19:37:42 -08003298 }
Ian Rogersca190662012-06-26 15:45:57 -07003299
Ian Rogers00f7d0e2012-07-19 15:28:27 -07003300 // TODO: Enable annotalysis. We know lock is held in constructor, but abstraction confuses
3301 // annotalysis.
3302 bool VisitFrame() NO_THREAD_SAFETY_ANALYSIS {
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01003303 mirror::ArtMethod* m = GetMethod();
Ian Rogers0399dde2012-06-06 17:09:28 -07003304 if (!m->IsRuntimeMethod()) {
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01003305 ++single_step_control_->stack_depth;
Ian Rogersc0542af2014-09-03 16:16:56 -07003306 if (single_step_control_->method == nullptr) {
Ian Rogersef7d42f2014-01-06 12:55:46 -08003307 mirror::DexCache* dex_cache = m->GetDeclaringClass()->GetDexCache();
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01003308 single_step_control_->method = m;
3309 *line_number_ = -1;
Ian Rogersc0542af2014-09-03 16:16:56 -07003310 if (dex_cache != nullptr) {
Ian Rogers4445a7e2012-10-05 17:19:13 -07003311 const DexFile& dex_file = *dex_cache->GetDexFile();
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01003312 *line_number_ = dex_file.GetLineNumFromPC(m, GetDexPc());
Elliott Hughes2435a572012-02-17 16:07:41 -08003313 }
Elliott Hughes86964332012-02-15 19:37:42 -08003314 }
3315 }
Elliott Hughes530fa002012-03-12 11:44:49 -07003316 return true;
Elliott Hughes86964332012-02-15 19:37:42 -08003317 }
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01003318
3319 SingleStepControl* const single_step_control_;
3320 int32_t* const line_number_;
Elliott Hughes86964332012-02-15 19:37:42 -08003321 };
Jeff Hao449db332013-04-12 18:30:52 -07003322
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01003323 Thread* const thread = sts.GetThread();
3324 SingleStepControl* const single_step_control = thread->GetSingleStepControl();
3325 DCHECK(single_step_control != nullptr);
3326 int32_t line_number = -1;
3327 SingleStepStackVisitor visitor(thread, single_step_control, &line_number);
Ian Rogers0399dde2012-06-06 17:09:28 -07003328 visitor.WalkStack();
Elliott Hughes86964332012-02-15 19:37:42 -08003329
Elliott Hughes2435a572012-02-17 16:07:41 -08003330 //
3331 // Find the dex_pc values that correspond to the current line, for line-based single-stepping.
3332 //
3333
3334 struct DebugCallbackContext {
Sebastien Hertzbb43b432014-04-14 11:59:08 +02003335 explicit DebugCallbackContext(SingleStepControl* single_step_control, int32_t line_number,
3336 const DexFile::CodeItem* code_item)
3337 : single_step_control_(single_step_control), line_number_(line_number), code_item_(code_item),
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01003338 last_pc_valid(false), last_pc(0) {
Elliott Hughes2435a572012-02-17 16:07:41 -08003339 }
3340
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01003341 static bool Callback(void* raw_context, uint32_t address, uint32_t line_number) {
Elliott Hughes2435a572012-02-17 16:07:41 -08003342 DebugCallbackContext* context = reinterpret_cast<DebugCallbackContext*>(raw_context);
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01003343 if (static_cast<int32_t>(line_number) == context->line_number_) {
Elliott Hughes2435a572012-02-17 16:07:41 -08003344 if (!context->last_pc_valid) {
3345 // Everything from this address until the next line change is ours.
3346 context->last_pc = address;
3347 context->last_pc_valid = true;
3348 }
3349 // Otherwise, if we're already in a valid range for this line,
3350 // just keep going (shouldn't really happen)...
Brian Carlstrom7934ac22013-07-26 10:54:15 -07003351 } else if (context->last_pc_valid) { // and the line number is new
Elliott Hughes2435a572012-02-17 16:07:41 -08003352 // Add everything from the last entry up until here to the set
3353 for (uint32_t dex_pc = context->last_pc; dex_pc < address; ++dex_pc) {
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01003354 context->single_step_control_->dex_pcs.insert(dex_pc);
Elliott Hughes2435a572012-02-17 16:07:41 -08003355 }
3356 context->last_pc_valid = false;
3357 }
Brian Carlstrom7934ac22013-07-26 10:54:15 -07003358 return false; // There may be multiple entries for any given line.
Elliott Hughes2435a572012-02-17 16:07:41 -08003359 }
3360
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01003361 ~DebugCallbackContext() {
Elliott Hughes2435a572012-02-17 16:07:41 -08003362 // If the line number was the last in the position table...
3363 if (last_pc_valid) {
Sebastien Hertzbb43b432014-04-14 11:59:08 +02003364 size_t end = code_item_->insns_size_in_code_units_;
Elliott Hughes2435a572012-02-17 16:07:41 -08003365 for (uint32_t dex_pc = last_pc; dex_pc < end; ++dex_pc) {
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01003366 single_step_control_->dex_pcs.insert(dex_pc);
Elliott Hughes2435a572012-02-17 16:07:41 -08003367 }
3368 }
3369 }
3370
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01003371 SingleStepControl* const single_step_control_;
3372 const int32_t line_number_;
Sebastien Hertzbb43b432014-04-14 11:59:08 +02003373 const DexFile::CodeItem* const code_item_;
Elliott Hughes2435a572012-02-17 16:07:41 -08003374 bool last_pc_valid;
3375 uint32_t last_pc;
3376 };
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01003377 single_step_control->dex_pcs.clear();
Ian Rogersef7d42f2014-01-06 12:55:46 -08003378 mirror::ArtMethod* m = single_step_control->method;
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01003379 if (!m->IsNative()) {
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07003380 const DexFile::CodeItem* const code_item = m->GetCodeItem();
Sebastien Hertzbb43b432014-04-14 11:59:08 +02003381 DebugCallbackContext context(single_step_control, line_number, code_item);
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07003382 m->GetDexFile()->DecodeDebugInfo(code_item, m->IsStatic(), m->GetDexMethodIndex(),
Ian Rogersc0542af2014-09-03 16:16:56 -07003383 DebugCallbackContext::Callback, nullptr, &context);
Elliott Hughes3e2e1a22012-02-21 11:33:41 -08003384 }
Elliott Hughes2435a572012-02-17 16:07:41 -08003385
3386 //
3387 // Everything else...
3388 //
3389
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01003390 single_step_control->step_size = step_size;
3391 single_step_control->step_depth = step_depth;
3392 single_step_control->is_active = true;
Elliott Hughes86964332012-02-15 19:37:42 -08003393
Elliott Hughes2435a572012-02-17 16:07:41 -08003394 if (VLOG_IS_ON(jdwp)) {
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01003395 VLOG(jdwp) << "Single-step thread: " << *thread;
3396 VLOG(jdwp) << "Single-step step size: " << single_step_control->step_size;
3397 VLOG(jdwp) << "Single-step step depth: " << single_step_control->step_depth;
3398 VLOG(jdwp) << "Single-step current method: " << PrettyMethod(single_step_control->method);
3399 VLOG(jdwp) << "Single-step current line: " << line_number;
3400 VLOG(jdwp) << "Single-step current stack depth: " << single_step_control->stack_depth;
Elliott Hughes2435a572012-02-17 16:07:41 -08003401 VLOG(jdwp) << "Single-step dex_pc values:";
Sebastien Hertzbb43b432014-04-14 11:59:08 +02003402 for (uint32_t dex_pc : single_step_control->dex_pcs) {
3403 VLOG(jdwp) << StringPrintf(" %#x", dex_pc);
Elliott Hughes2435a572012-02-17 16:07:41 -08003404 }
3405 }
3406
3407 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07003408}
3409
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01003410void Dbg::UnconfigureStep(JDWP::ObjectId thread_id) {
3411 ScopedObjectAccessUnchecked soa(Thread::Current());
3412 MutexLock mu(soa.Self(), *Locks::thread_list_lock_);
Ian Rogersc0542af2014-09-03 16:16:56 -07003413 JDWP::JdwpError error;
3414 Thread* thread = DecodeThread(soa, thread_id, &error);
Sebastien Hertz87118ed2013-11-26 17:57:18 +01003415 if (error == JDWP::ERR_NONE) {
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01003416 SingleStepControl* single_step_control = thread->GetSingleStepControl();
3417 DCHECK(single_step_control != nullptr);
Sebastien Hertzbb43b432014-04-14 11:59:08 +02003418 single_step_control->Clear();
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01003419 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -07003420}
3421
Elliott Hughes45651fd2012-02-21 15:48:20 -08003422static char JdwpTagToShortyChar(JDWP::JdwpTag tag) {
3423 switch (tag) {
3424 default:
3425 LOG(FATAL) << "unknown JDWP tag: " << PrintableChar(tag);
3426
3427 // Primitives.
3428 case JDWP::JT_BYTE: return 'B';
3429 case JDWP::JT_CHAR: return 'C';
3430 case JDWP::JT_FLOAT: return 'F';
3431 case JDWP::JT_DOUBLE: return 'D';
3432 case JDWP::JT_INT: return 'I';
3433 case JDWP::JT_LONG: return 'J';
3434 case JDWP::JT_SHORT: return 'S';
3435 case JDWP::JT_VOID: return 'V';
3436 case JDWP::JT_BOOLEAN: return 'Z';
3437
3438 // Reference types.
3439 case JDWP::JT_ARRAY:
3440 case JDWP::JT_OBJECT:
3441 case JDWP::JT_STRING:
3442 case JDWP::JT_THREAD:
3443 case JDWP::JT_THREAD_GROUP:
3444 case JDWP::JT_CLASS_LOADER:
3445 case JDWP::JT_CLASS_OBJECT:
3446 return 'L';
3447 }
3448}
3449
Elliott Hughes88d63092013-01-09 09:55:54 -08003450JDWP::JdwpError Dbg::InvokeMethod(JDWP::ObjectId thread_id, JDWP::ObjectId object_id,
3451 JDWP::RefTypeId class_id, JDWP::MethodId method_id,
Ian Rogers00f7d0e2012-07-19 15:28:27 -07003452 uint32_t arg_count, uint64_t* arg_values,
3453 JDWP::JdwpTag* arg_types, uint32_t options,
3454 JDWP::JdwpTag* pResultTag, uint64_t* pResultValue,
3455 JDWP::ObjectId* pExceptionId) {
Elliott Hughesd07986f2011-12-06 18:27:45 -08003456 ThreadList* thread_list = Runtime::Current()->GetThreadList();
3457
Ian Rogersc0542af2014-09-03 16:16:56 -07003458 Thread* targetThread = nullptr;
3459 DebugInvokeReq* req = nullptr;
Ian Rogers00f7d0e2012-07-19 15:28:27 -07003460 Thread* self = Thread::Current();
Elliott Hughesd07986f2011-12-06 18:27:45 -08003461 {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07003462 ScopedObjectAccessUnchecked soa(self);
Ian Rogers50b35e22012-10-04 10:09:15 -07003463 MutexLock mu(soa.Self(), *Locks::thread_list_lock_);
Ian Rogersc0542af2014-09-03 16:16:56 -07003464 JDWP::JdwpError error;
3465 targetThread = DecodeThread(soa, thread_id, &error);
Elliott Hughes221229c2013-01-08 18:17:50 -08003466 if (error != JDWP::ERR_NONE) {
3467 LOG(ERROR) << "InvokeMethod request for invalid thread id " << thread_id;
3468 return error;
Elliott Hughesd07986f2011-12-06 18:27:45 -08003469 }
3470 req = targetThread->GetInvokeReq();
3471 if (!req->ready) {
3472 LOG(ERROR) << "InvokeMethod request for thread not stopped by event: " << *targetThread;
3473 return JDWP::ERR_INVALID_THREAD;
3474 }
3475
3476 /*
3477 * We currently have a bug where we don't successfully resume the
3478 * target thread if the suspend count is too deep. We're expected to
3479 * require one "resume" for each "suspend", but when asked to execute
3480 * a method we have to resume fully and then re-suspend it back to the
3481 * same level. (The easiest way to cause this is to type "suspend"
3482 * multiple times in jdb.)
3483 *
3484 * It's unclear what this means when the event specifies "resume all"
3485 * and some threads are suspended more deeply than others. This is
3486 * a rare problem, so for now we just prevent it from hanging forever
3487 * by rejecting the method invocation request. Without this, we will
3488 * be stuck waiting on a suspended thread.
3489 */
Ian Rogers00f7d0e2012-07-19 15:28:27 -07003490 int suspend_count;
3491 {
Ian Rogers50b35e22012-10-04 10:09:15 -07003492 MutexLock mu2(soa.Self(), *Locks::thread_suspend_count_lock_);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07003493 suspend_count = targetThread->GetSuspendCount();
3494 }
Elliott Hughesd07986f2011-12-06 18:27:45 -08003495 if (suspend_count > 1) {
3496 LOG(ERROR) << *targetThread << " suspend count too deep for method invocation: " << suspend_count;
Brian Carlstrom7934ac22013-07-26 10:54:15 -07003497 return JDWP::ERR_THREAD_SUSPENDED; // Probably not expected here.
Elliott Hughesd07986f2011-12-06 18:27:45 -08003498 }
3499
Ian Rogersc0542af2014-09-03 16:16:56 -07003500 mirror::Object* receiver = gRegistry->Get<mirror::Object*>(object_id, &error);
3501 if (error != JDWP::ERR_NONE) {
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08003502 return JDWP::ERR_INVALID_OBJECT;
3503 }
Elliott Hughes45651fd2012-02-21 15:48:20 -08003504
Ian Rogersc0542af2014-09-03 16:16:56 -07003505 mirror::Object* thread = gRegistry->Get<mirror::Object*>(thread_id, &error);
3506 if (error != JDWP::ERR_NONE) {
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08003507 return JDWP::ERR_INVALID_OBJECT;
3508 }
Elliott Hughes45651fd2012-02-21 15:48:20 -08003509 // TODO: check that 'thread' is actually a java.lang.Thread!
3510
Ian Rogersc0542af2014-09-03 16:16:56 -07003511 mirror::Class* c = DecodeClass(class_id, &error);
3512 if (c == nullptr) {
3513 return error;
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08003514 }
Elliott Hughes45651fd2012-02-21 15:48:20 -08003515
Brian Carlstromea46f952013-07-30 01:26:50 -07003516 mirror::ArtMethod* m = FromMethodId(method_id);
Ian Rogersc0542af2014-09-03 16:16:56 -07003517 if (m->IsStatic() != (receiver == nullptr)) {
Elliott Hughes45651fd2012-02-21 15:48:20 -08003518 return JDWP::ERR_INVALID_METHODID;
3519 }
3520 if (m->IsStatic()) {
3521 if (m->GetDeclaringClass() != c) {
3522 return JDWP::ERR_INVALID_METHODID;
3523 }
3524 } else {
3525 if (!m->GetDeclaringClass()->IsAssignableFrom(c)) {
3526 return JDWP::ERR_INVALID_METHODID;
3527 }
3528 }
3529
3530 // Check the argument list matches the method.
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07003531 uint32_t shorty_len = 0;
3532 const char* shorty = m->GetShorty(&shorty_len);
3533 if (shorty_len - 1 != arg_count) {
Elliott Hughes45651fd2012-02-21 15:48:20 -08003534 return JDWP::ERR_ILLEGAL_ARGUMENT;
3535 }
Elliott Hughes09201632013-04-15 15:50:07 -07003536
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07003537 {
3538 StackHandleScope<3> hs(soa.Self());
3539 MethodHelper mh(hs.NewHandle(m));
3540 HandleWrapper<mirror::Object> h_obj(hs.NewHandleWrapper(&receiver));
3541 HandleWrapper<mirror::Class> h_klass(hs.NewHandleWrapper(&c));
3542 const DexFile::TypeList* types = m->GetParameterTypeList();
3543 for (size_t i = 0; i < arg_count; ++i) {
3544 if (shorty[i + 1] != JdwpTagToShortyChar(arg_types[i])) {
Elliott Hughes09201632013-04-15 15:50:07 -07003545 return JDWP::ERR_ILLEGAL_ARGUMENT;
3546 }
3547
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07003548 if (shorty[i + 1] == 'L') {
3549 // Did we really get an argument of an appropriate reference type?
3550 mirror::Class* parameter_type = mh.GetClassFromTypeIdx(types->GetTypeItem(i).type_idx_);
Ian Rogersc0542af2014-09-03 16:16:56 -07003551 mirror::Object* argument = gRegistry->Get<mirror::Object*>(arg_values[i], &error);
3552 if (error != JDWP::ERR_NONE) {
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07003553 return JDWP::ERR_INVALID_OBJECT;
3554 }
Ian Rogersc0542af2014-09-03 16:16:56 -07003555 if (argument != nullptr && !argument->InstanceOf(parameter_type)) {
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07003556 return JDWP::ERR_ILLEGAL_ARGUMENT;
3557 }
3558
3559 // Turn the on-the-wire ObjectId into a jobject.
3560 jvalue& v = reinterpret_cast<jvalue&>(arg_values[i]);
3561 v.l = gRegistry->GetJObject(arg_values[i]);
3562 }
Elliott Hughes09201632013-04-15 15:50:07 -07003563 }
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07003564 // Update in case it moved.
3565 m = mh.GetMethod();
Elliott Hughes45651fd2012-02-21 15:48:20 -08003566 }
3567
Sebastien Hertzd38667a2013-11-25 15:43:54 +01003568 req->receiver = receiver;
3569 req->thread = thread;
3570 req->klass = c;
3571 req->method = m;
3572 req->arg_count = arg_count;
3573 req->arg_values = arg_values;
3574 req->options = options;
3575 req->invoke_needed = true;
Elliott Hughesd07986f2011-12-06 18:27:45 -08003576 }
3577
3578 // The fact that we've released the thread list lock is a bit risky --- if the thread goes
3579 // away we're sitting high and dry -- but we must release this before the ResumeAllThreads
3580 // call, and it's unwise to hold it during WaitForSuspend.
3581
3582 {
3583 /*
3584 * We change our (JDWP thread) status, which should be THREAD_RUNNING,
Elliott Hughes81ff3182012-03-23 20:35:56 -07003585 * so we can suspend for a GC if the invoke request causes us to
Elliott Hughesd07986f2011-12-06 18:27:45 -08003586 * run out of memory. It's also a good idea to change it before locking
3587 * the invokeReq mutex, although that should never be held for long.
3588 */
Ian Rogers00f7d0e2012-07-19 15:28:27 -07003589 self->TransitionFromRunnableToSuspended(kWaitingForDebuggerSend);
Elliott Hughesd07986f2011-12-06 18:27:45 -08003590
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08003591 VLOG(jdwp) << " Transferring control to event thread";
Elliott Hughesd07986f2011-12-06 18:27:45 -08003592 {
Sebastien Hertzd38667a2013-11-25 15:43:54 +01003593 MutexLock mu(self, req->lock);
Elliott Hughesd07986f2011-12-06 18:27:45 -08003594
3595 if ((options & JDWP::INVOKE_SINGLE_THREADED) == 0) {
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08003596 VLOG(jdwp) << " Resuming all threads";
Ian Rogers00f7d0e2012-07-19 15:28:27 -07003597 thread_list->UndoDebuggerSuspensions();
Elliott Hughesd07986f2011-12-06 18:27:45 -08003598 } else {
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08003599 VLOG(jdwp) << " Resuming event thread only";
Elliott Hughesd07986f2011-12-06 18:27:45 -08003600 thread_list->Resume(targetThread, true);
3601 }
3602
3603 // Wait for the request to finish executing.
Sebastien Hertzd38667a2013-11-25 15:43:54 +01003604 while (req->invoke_needed) {
3605 req->cond.Wait(self);
Elliott Hughesd07986f2011-12-06 18:27:45 -08003606 }
3607 }
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08003608 VLOG(jdwp) << " Control has returned from event thread";
Elliott Hughesd07986f2011-12-06 18:27:45 -08003609
3610 /* wait for thread to re-suspend itself */
Brian Carlstromdf629502013-07-17 22:39:56 -07003611 SuspendThread(thread_id, false /* request_suspension */);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07003612 self->TransitionFromSuspendedToRunnable();
Elliott Hughesd07986f2011-12-06 18:27:45 -08003613 }
3614
3615 /*
3616 * Suspend the threads. We waited for the target thread to suspend
3617 * itself, so all we need to do is suspend the others.
3618 *
3619 * The suspendAllThreads() call will double-suspend the event thread,
3620 * so we want to resume the target thread once to keep the books straight.
3621 */
3622 if ((options & JDWP::INVOKE_SINGLE_THREADED) == 0) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07003623 self->TransitionFromRunnableToSuspended(kWaitingForDebuggerSuspension);
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08003624 VLOG(jdwp) << " Suspending all threads";
Ian Rogers00f7d0e2012-07-19 15:28:27 -07003625 thread_list->SuspendAllForDebugger();
3626 self->TransitionFromSuspendedToRunnable();
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08003627 VLOG(jdwp) << " Resuming event thread to balance the count";
Elliott Hughesd07986f2011-12-06 18:27:45 -08003628 thread_list->Resume(targetThread, true);
3629 }
3630
3631 // Copy the result.
3632 *pResultTag = req->result_tag;
3633 if (IsPrimitiveTag(req->result_tag)) {
Elliott Hughesf24d3ce2012-04-11 17:43:37 -07003634 *pResultValue = req->result_value.GetJ();
Elliott Hughesd07986f2011-12-06 18:27:45 -08003635 } else {
Elliott Hughesf24d3ce2012-04-11 17:43:37 -07003636 *pResultValue = gRegistry->Add(req->result_value.GetL());
Elliott Hughesd07986f2011-12-06 18:27:45 -08003637 }
3638 *pExceptionId = req->exception;
3639 return req->error;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07003640}
3641
3642void Dbg::ExecuteMethod(DebugInvokeReq* pReq) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07003643 ScopedObjectAccess soa(Thread::Current());
Elliott Hughesd07986f2011-12-06 18:27:45 -08003644
Elliott Hughes81ff3182012-03-23 20:35:56 -07003645 // We can be called while an exception is pending. We need
Elliott Hughesd07986f2011-12-06 18:27:45 -08003646 // to preserve that across the method invocation.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003647 StackHandleScope<4> hs(soa.Self());
3648 auto old_throw_this_object = hs.NewHandle<mirror::Object>(nullptr);
3649 auto old_throw_method = hs.NewHandle<mirror::ArtMethod>(nullptr);
3650 auto old_exception = hs.NewHandle<mirror::Throwable>(nullptr);
Ian Rogers62d6c772013-02-27 08:32:07 -08003651 uint32_t old_throw_dex_pc;
Sebastien Hertz9f102032014-05-23 08:59:42 +02003652 bool old_exception_report_flag;
Ian Rogers62d6c772013-02-27 08:32:07 -08003653 {
3654 ThrowLocation old_throw_location;
3655 mirror::Throwable* old_exception_obj = soa.Self()->GetException(&old_throw_location);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003656 old_throw_this_object.Assign(old_throw_location.GetThis());
3657 old_throw_method.Assign(old_throw_location.GetMethod());
3658 old_exception.Assign(old_exception_obj);
Ian Rogers62d6c772013-02-27 08:32:07 -08003659 old_throw_dex_pc = old_throw_location.GetDexPc();
Sebastien Hertz9f102032014-05-23 08:59:42 +02003660 old_exception_report_flag = soa.Self()->IsExceptionReportedToInstrumentation();
Ian Rogers62d6c772013-02-27 08:32:07 -08003661 soa.Self()->ClearException();
3662 }
Elliott Hughesd07986f2011-12-06 18:27:45 -08003663
3664 // Translate the method through the vtable, unless the debugger wants to suppress it.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003665 Handle<mirror::ArtMethod> m(hs.NewHandle(pReq->method));
Ian Rogersc0542af2014-09-03 16:16:56 -07003666 if ((pReq->options & JDWP::INVOKE_NONVIRTUAL) == 0 && pReq->receiver != nullptr) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003667 mirror::ArtMethod* actual_method = pReq->klass->FindVirtualMethodForVirtualOrInterface(m.Get());
3668 if (actual_method != m.Get()) {
3669 VLOG(jdwp) << "ExecuteMethod translated " << PrettyMethod(m.Get()) << " to " << PrettyMethod(actual_method);
3670 m.Assign(actual_method);
Elliott Hughes45651fd2012-02-21 15:48:20 -08003671 }
Elliott Hughesd07986f2011-12-06 18:27:45 -08003672 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003673 VLOG(jdwp) << "ExecuteMethod " << PrettyMethod(m.Get())
Sebastien Hertzd38667a2013-11-25 15:43:54 +01003674 << " receiver=" << pReq->receiver
3675 << " arg_count=" << pReq->arg_count;
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003676 CHECK(m.Get() != nullptr);
Elliott Hughesd07986f2011-12-06 18:27:45 -08003677
3678 CHECK_EQ(sizeof(jvalue), sizeof(uint64_t));
3679
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003680 pReq->result_value = InvokeWithJValues(soa, pReq->receiver, soa.EncodeMethod(m.Get()),
Ian Rogers53b8b092014-03-13 23:45:53 -07003681 reinterpret_cast<jvalue*>(pReq->arg_values));
Elliott Hughesd07986f2011-12-06 18:27:45 -08003682
Ian Rogersc0542af2014-09-03 16:16:56 -07003683 mirror::Throwable* exception = soa.Self()->GetException(nullptr);
Ian Rogers62d6c772013-02-27 08:32:07 -08003684 soa.Self()->ClearException();
3685 pReq->exception = gRegistry->Add(exception);
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07003686 pReq->result_tag = BasicTagFromDescriptor(m.Get()->GetShorty());
Elliott Hughesd07986f2011-12-06 18:27:45 -08003687 if (pReq->exception != 0) {
Ian Rogers62d6c772013-02-27 08:32:07 -08003688 VLOG(jdwp) << " JDWP invocation returning with exception=" << exception
3689 << " " << exception->Dump();
Elliott Hughesf24d3ce2012-04-11 17:43:37 -07003690 pReq->result_value.SetJ(0);
Elliott Hughesd07986f2011-12-06 18:27:45 -08003691 } else if (pReq->result_tag == JDWP::JT_OBJECT) {
3692 /* if no exception thrown, examine object result more closely */
Ian Rogers98379392014-02-24 16:53:16 -08003693 JDWP::JdwpTag new_tag = TagFromObject(soa, pReq->result_value.GetL());
Elliott Hughesd07986f2011-12-06 18:27:45 -08003694 if (new_tag != pReq->result_tag) {
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08003695 VLOG(jdwp) << " JDWP promoted result from " << pReq->result_tag << " to " << new_tag;
Elliott Hughesd07986f2011-12-06 18:27:45 -08003696 pReq->result_tag = new_tag;
3697 }
3698
3699 /*
3700 * Register the object. We don't actually need an ObjectId yet,
3701 * but we do need to be sure that the GC won't move or discard the
3702 * object when we switch out of RUNNING. The ObjectId conversion
3703 * will add the object to the "do not touch" list.
3704 *
3705 * We can't use the "tracked allocation" mechanism here because
3706 * the object is going to be handed off to a different thread.
3707 */
Elliott Hughesf24d3ce2012-04-11 17:43:37 -07003708 gRegistry->Add(pReq->result_value.GetL());
Elliott Hughesd07986f2011-12-06 18:27:45 -08003709 }
3710
Ian Rogersc0542af2014-09-03 16:16:56 -07003711 if (old_exception.Get() != nullptr) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003712 ThrowLocation gc_safe_throw_location(old_throw_this_object.Get(), old_throw_method.Get(),
Ian Rogers62d6c772013-02-27 08:32:07 -08003713 old_throw_dex_pc);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003714 soa.Self()->SetException(gc_safe_throw_location, old_exception.Get());
Sebastien Hertz9f102032014-05-23 08:59:42 +02003715 soa.Self()->SetExceptionReportedToInstrumentation(old_exception_report_flag);
Elliott Hughesd07986f2011-12-06 18:27:45 -08003716 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -07003717}
3718
Elliott Hughesd07986f2011-12-06 18:27:45 -08003719/*
Elliott Hughes4b9702c2013-02-20 18:13:24 -08003720 * "request" contains a full JDWP packet, possibly with multiple chunks. We
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07003721 * need to process each, accumulate the replies, and ship the whole thing
3722 * back.
3723 *
3724 * Returns "true" if we have a reply. The reply buffer is newly allocated,
3725 * and includes the chunk type/length, followed by the data.
3726 *
Elliott Hughes3d30d9b2011-12-07 17:35:48 -08003727 * OLD-TODO: we currently assume that the request and reply include a single
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07003728 * chunk. If this becomes inconvenient we will need to adapt.
3729 */
Ian Rogersc0542af2014-09-03 16:16:56 -07003730bool Dbg::DdmHandlePacket(JDWP::Request* request, uint8_t** pReplyBuf, int* pReplyLen) {
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07003731 Thread* self = Thread::Current();
3732 JNIEnv* env = self->GetJniEnv();
3733
Ian Rogersc0542af2014-09-03 16:16:56 -07003734 uint32_t type = request->ReadUnsigned32("type");
3735 uint32_t length = request->ReadUnsigned32("length");
Elliott Hughes4b9702c2013-02-20 18:13:24 -08003736
3737 // Create a byte[] corresponding to 'request'.
Ian Rogersc0542af2014-09-03 16:16:56 -07003738 size_t request_length = request->size();
Elliott Hughes4b9702c2013-02-20 18:13:24 -08003739 ScopedLocalRef<jbyteArray> dataArray(env, env->NewByteArray(request_length));
Ian Rogersc0542af2014-09-03 16:16:56 -07003740 if (dataArray.get() == nullptr) {
Elliott Hughes4b9702c2013-02-20 18:13:24 -08003741 LOG(WARNING) << "byte[] allocation failed: " << request_length;
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07003742 env->ExceptionClear();
3743 return false;
3744 }
Ian Rogersc0542af2014-09-03 16:16:56 -07003745 env->SetByteArrayRegion(dataArray.get(), 0, request_length,
3746 reinterpret_cast<const jbyte*>(request->data()));
3747 request->Skip(request_length);
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07003748
3749 // Run through and find all chunks. [Currently just find the first.]
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003750 ScopedByteArrayRO contents(env, dataArray.get());
Elliott Hughes4b9702c2013-02-20 18:13:24 -08003751 if (length != request_length) {
Ian Rogersef7d42f2014-01-06 12:55:46 -08003752 LOG(WARNING) << StringPrintf("bad chunk found (len=%u pktLen=%zd)", length, request_length);
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07003753 return false;
3754 }
3755
3756 // Call "private static Chunk dispatch(int type, byte[] data, int offset, int length)".
Elliott Hugheseac76672012-05-24 21:56:51 -07003757 ScopedLocalRef<jobject> chunk(env, env->CallStaticObjectMethod(WellKnownClasses::org_apache_harmony_dalvik_ddmc_DdmServer,
3758 WellKnownClasses::org_apache_harmony_dalvik_ddmc_DdmServer_dispatch,
Elliott Hughes4b9702c2013-02-20 18:13:24 -08003759 type, dataArray.get(), 0, length));
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07003760 if (env->ExceptionCheck()) {
3761 LOG(INFO) << StringPrintf("Exception thrown by dispatcher for 0x%08x", type);
3762 env->ExceptionDescribe();
3763 env->ExceptionClear();
3764 return false;
3765 }
3766
Ian Rogersc0542af2014-09-03 16:16:56 -07003767 if (chunk.get() == nullptr) {
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07003768 return false;
3769 }
3770
3771 /*
3772 * Pull the pieces out of the chunk. We copy the results into a
3773 * newly-allocated buffer that the caller can free. We don't want to
3774 * continue using the Chunk object because nothing has a reference to it.
3775 *
3776 * We could avoid this by returning type/data/offset/length and having
3777 * the caller be aware of the object lifetime issues, but that
Elliott Hughes81ff3182012-03-23 20:35:56 -07003778 * integrates the JDWP code more tightly into the rest of the runtime, and doesn't work
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07003779 * if we have responses for multiple chunks.
3780 *
3781 * So we're pretty much stuck with copying data around multiple times.
3782 */
Elliott Hugheseac76672012-05-24 21:56:51 -07003783 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 -08003784 jint offset = env->GetIntField(chunk.get(), WellKnownClasses::org_apache_harmony_dalvik_ddmc_Chunk_offset);
Elliott Hugheseac76672012-05-24 21:56:51 -07003785 length = env->GetIntField(chunk.get(), WellKnownClasses::org_apache_harmony_dalvik_ddmc_Chunk_length);
Elliott Hugheseac76672012-05-24 21:56:51 -07003786 type = env->GetIntField(chunk.get(), WellKnownClasses::org_apache_harmony_dalvik_ddmc_Chunk_type);
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07003787
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08003788 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 -07003789 if (length == 0 || replyData.get() == nullptr) {
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07003790 return false;
3791 }
3792
Elliott Hughes4b9702c2013-02-20 18:13:24 -08003793 const int kChunkHdrLen = 8;
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07003794 uint8_t* reply = new uint8_t[length + kChunkHdrLen];
Ian Rogersc0542af2014-09-03 16:16:56 -07003795 if (reply == nullptr) {
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07003796 LOG(WARNING) << "malloc failed: " << (length + kChunkHdrLen);
3797 return false;
3798 }
Elliott Hughesf7c3b662011-10-27 12:04:56 -07003799 JDWP::Set4BE(reply + 0, type);
3800 JDWP::Set4BE(reply + 4, length);
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003801 env->GetByteArrayRegion(replyData.get(), offset, length, reinterpret_cast<jbyte*>(reply + kChunkHdrLen));
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07003802
3803 *pReplyBuf = reply;
3804 *pReplyLen = length + kChunkHdrLen;
3805
Elliott Hughes4b9702c2013-02-20 18:13:24 -08003806 VLOG(jdwp) << StringPrintf("dvmHandleDdm returning type=%.4s %p len=%d", reinterpret_cast<char*>(reply), reply, length);
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07003807 return true;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07003808}
3809
Elliott Hughesa2155262011-11-16 16:26:58 -08003810void Dbg::DdmBroadcast(bool connect) {
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08003811 VLOG(jdwp) << "Broadcasting DDM " << (connect ? "connect" : "disconnect") << "...";
Elliott Hughes47fce012011-10-25 18:37:19 -07003812
3813 Thread* self = Thread::Current();
Ian Rogers50b35e22012-10-04 10:09:15 -07003814 if (self->GetState() != kRunnable) {
3815 LOG(ERROR) << "DDM broadcast in thread state " << self->GetState();
3816 /* try anyway? */
Elliott Hughes47fce012011-10-25 18:37:19 -07003817 }
3818
3819 JNIEnv* env = self->GetJniEnv();
Elliott Hughes47fce012011-10-25 18:37:19 -07003820 jint event = connect ? 1 /*DdmServer.CONNECTED*/ : 2 /*DdmServer.DISCONNECTED*/;
Elliott Hugheseac76672012-05-24 21:56:51 -07003821 env->CallStaticVoidMethod(WellKnownClasses::org_apache_harmony_dalvik_ddmc_DdmServer,
3822 WellKnownClasses::org_apache_harmony_dalvik_ddmc_DdmServer_broadcast,
3823 event);
Elliott Hughes47fce012011-10-25 18:37:19 -07003824 if (env->ExceptionCheck()) {
3825 LOG(ERROR) << "DdmServer.broadcast " << event << " failed";
3826 env->ExceptionDescribe();
3827 env->ExceptionClear();
3828 }
3829}
3830
Elliott Hughes872d4ec2011-10-21 17:07:15 -07003831void Dbg::DdmConnected() {
Elliott Hughesa2155262011-11-16 16:26:58 -08003832 Dbg::DdmBroadcast(true);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07003833}
3834
3835void Dbg::DdmDisconnected() {
Elliott Hughesa2155262011-11-16 16:26:58 -08003836 Dbg::DdmBroadcast(false);
Elliott Hughes47fce012011-10-25 18:37:19 -07003837 gDdmThreadNotification = false;
3838}
3839
3840/*
Elliott Hughes82188472011-11-07 18:11:48 -08003841 * Send a notification when a thread starts, stops, or changes its name.
Elliott Hughes47fce012011-10-25 18:37:19 -07003842 *
3843 * Because we broadcast the full set of threads when the notifications are
3844 * first enabled, it's possible for "thread" to be actively executing.
3845 */
Elliott Hughes82188472011-11-07 18:11:48 -08003846void Dbg::DdmSendThreadNotification(Thread* t, uint32_t type) {
Elliott Hughes47fce012011-10-25 18:37:19 -07003847 if (!gDdmThreadNotification) {
3848 return;
3849 }
3850
Elliott Hughes82188472011-11-07 18:11:48 -08003851 if (type == CHUNK_TYPE("THDE")) {
Elliott Hughes47fce012011-10-25 18:37:19 -07003852 uint8_t buf[4];
Ian Rogersd9c4fc92013-10-01 19:45:43 -07003853 JDWP::Set4BE(&buf[0], t->GetThreadId());
Elliott Hughes47fce012011-10-25 18:37:19 -07003854 Dbg::DdmSendChunk(CHUNK_TYPE("THDE"), 4, buf);
Elliott Hughes82188472011-11-07 18:11:48 -08003855 } else {
3856 CHECK(type == CHUNK_TYPE("THCR") || type == CHUNK_TYPE("THNM")) << type;
Ian Rogers00f7d0e2012-07-19 15:28:27 -07003857 ScopedObjectAccessUnchecked soa(Thread::Current());
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003858 StackHandleScope<1> hs(soa.Self());
3859 Handle<mirror::String> name(hs.NewHandle(t->GetThreadName(soa)));
Ian Rogersc0542af2014-09-03 16:16:56 -07003860 size_t char_count = (name.Get() != nullptr) ? name->GetLength() : 0;
3861 const jchar* chars = (name.Get() != nullptr) ? name->GetCharArray()->GetData() : nullptr;
Elliott Hughes82188472011-11-07 18:11:48 -08003862
Elliott Hughes21f32d72011-11-09 17:44:13 -08003863 std::vector<uint8_t> bytes;
Ian Rogersd9c4fc92013-10-01 19:45:43 -07003864 JDWP::Append4BE(bytes, t->GetThreadId());
Elliott Hughes545a0642011-11-08 19:10:03 -08003865 JDWP::AppendUtf16BE(bytes, chars, char_count);
Elliott Hughes21f32d72011-11-09 17:44:13 -08003866 CHECK_EQ(bytes.size(), char_count*2 + sizeof(uint32_t)*2);
3867 Dbg::DdmSendChunk(type, bytes);
Elliott Hughes47fce012011-10-25 18:37:19 -07003868 }
3869}
3870
Elliott Hughes47fce012011-10-25 18:37:19 -07003871void Dbg::DdmSetThreadNotification(bool enable) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07003872 // Enable/disable thread notifications.
Elliott Hughes47fce012011-10-25 18:37:19 -07003873 gDdmThreadNotification = enable;
3874 if (enable) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07003875 // Suspend the VM then post thread start notifications for all threads. Threads attaching will
3876 // see a suspension in progress and block until that ends. They then post their own start
3877 // notification.
3878 SuspendVM();
3879 std::list<Thread*> threads;
Ian Rogers50b35e22012-10-04 10:09:15 -07003880 Thread* self = Thread::Current();
Ian Rogers00f7d0e2012-07-19 15:28:27 -07003881 {
Ian Rogers50b35e22012-10-04 10:09:15 -07003882 MutexLock mu(self, *Locks::thread_list_lock_);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07003883 threads = Runtime::Current()->GetThreadList()->GetList();
3884 }
3885 {
Ian Rogers50b35e22012-10-04 10:09:15 -07003886 ScopedObjectAccess soa(self);
Mathieu Chartier02e25112013-08-14 16:14:24 -07003887 for (Thread* thread : threads) {
3888 Dbg::DdmSendThreadNotification(thread, CHUNK_TYPE("THCR"));
Ian Rogers00f7d0e2012-07-19 15:28:27 -07003889 }
3890 }
3891 ResumeVM();
Elliott Hughes47fce012011-10-25 18:37:19 -07003892 }
3893}
3894
Elliott Hughesa2155262011-11-16 16:26:58 -08003895void Dbg::PostThreadStartOrStop(Thread* t, uint32_t type) {
Elliott Hughesc0f09332012-03-26 13:27:06 -07003896 if (IsDebuggerActive()) {
Mathieu Chartierdbe6f462012-09-25 16:54:50 -07003897 ScopedObjectAccessUnchecked soa(Thread::Current());
Ian Rogerscfaa4552012-11-26 21:00:08 -08003898 JDWP::ObjectId id = gRegistry->Add(t->GetPeer());
Elliott Hughes82188472011-11-07 18:11:48 -08003899 gJdwpState->PostThreadChange(id, type == CHUNK_TYPE("THCR"));
Elliott Hughes47fce012011-10-25 18:37:19 -07003900 }
Elliott Hughes82188472011-11-07 18:11:48 -08003901 Dbg::DdmSendThreadNotification(t, type);
Elliott Hughes47fce012011-10-25 18:37:19 -07003902}
3903
3904void Dbg::PostThreadStart(Thread* t) {
Elliott Hughesa2155262011-11-16 16:26:58 -08003905 Dbg::PostThreadStartOrStop(t, CHUNK_TYPE("THCR"));
Elliott Hughes47fce012011-10-25 18:37:19 -07003906}
3907
3908void Dbg::PostThreadDeath(Thread* t) {
Elliott Hughesa2155262011-11-16 16:26:58 -08003909 Dbg::PostThreadStartOrStop(t, CHUNK_TYPE("THDE"));
Elliott Hughes872d4ec2011-10-21 17:07:15 -07003910}
3911
Elliott Hughes82188472011-11-07 18:11:48 -08003912void Dbg::DdmSendChunk(uint32_t type, size_t byte_count, const uint8_t* buf) {
Ian Rogersc0542af2014-09-03 16:16:56 -07003913 CHECK(buf != nullptr);
Elliott Hughes3bb81562011-10-21 18:52:59 -07003914 iovec vec[1];
3915 vec[0].iov_base = reinterpret_cast<void*>(const_cast<uint8_t*>(buf));
3916 vec[0].iov_len = byte_count;
3917 Dbg::DdmSendChunkV(type, vec, 1);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07003918}
3919
Elliott Hughes21f32d72011-11-09 17:44:13 -08003920void Dbg::DdmSendChunk(uint32_t type, const std::vector<uint8_t>& bytes) {
3921 DdmSendChunk(type, bytes.size(), &bytes[0]);
3922}
3923
Brian Carlstromf5293522013-07-19 00:24:00 -07003924void Dbg::DdmSendChunkV(uint32_t type, const iovec* iov, int iov_count) {
Ian Rogersc0542af2014-09-03 16:16:56 -07003925 if (gJdwpState == nullptr) {
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08003926 VLOG(jdwp) << "Debugger thread not active, ignoring DDM send: " << type;
Elliott Hughes3bb81562011-10-21 18:52:59 -07003927 } else {
Elliott Hughescccd84f2011-12-05 16:51:54 -08003928 gJdwpState->DdmSendChunkV(type, iov, iov_count);
Elliott Hughes3bb81562011-10-21 18:52:59 -07003929 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -07003930}
3931
Elliott Hughes767a1472011-10-26 18:49:02 -07003932int Dbg::DdmHandleHpifChunk(HpifWhen when) {
3933 if (when == HPIF_WHEN_NOW) {
Elliott Hughes7162ad92011-10-27 14:08:42 -07003934 DdmSendHeapInfo(when);
Elliott Hughes767a1472011-10-26 18:49:02 -07003935 return true;
3936 }
3937
3938 if (when != HPIF_WHEN_NEVER && when != HPIF_WHEN_NEXT_GC && when != HPIF_WHEN_EVERY_GC) {
3939 LOG(ERROR) << "invalid HpifWhen value: " << static_cast<int>(when);
3940 return false;
3941 }
3942
3943 gDdmHpifWhen = when;
3944 return true;
3945}
3946
3947bool Dbg::DdmHandleHpsgNhsgChunk(Dbg::HpsgWhen when, Dbg::HpsgWhat what, bool native) {
3948 if (when != HPSG_WHEN_NEVER && when != HPSG_WHEN_EVERY_GC) {
3949 LOG(ERROR) << "invalid HpsgWhen value: " << static_cast<int>(when);
3950 return false;
3951 }
3952
3953 if (what != HPSG_WHAT_MERGED_OBJECTS && what != HPSG_WHAT_DISTINCT_OBJECTS) {
3954 LOG(ERROR) << "invalid HpsgWhat value: " << static_cast<int>(what);
3955 return false;
3956 }
3957
3958 if (native) {
3959 gDdmNhsgWhen = when;
3960 gDdmNhsgWhat = what;
3961 } else {
3962 gDdmHpsgWhen = when;
3963 gDdmHpsgWhat = what;
3964 }
3965 return true;
3966}
3967
Elliott Hughes7162ad92011-10-27 14:08:42 -07003968void Dbg::DdmSendHeapInfo(HpifWhen reason) {
3969 // If there's a one-shot 'when', reset it.
3970 if (reason == gDdmHpifWhen) {
3971 if (gDdmHpifWhen == HPIF_WHEN_NEXT_GC) {
3972 gDdmHpifWhen = HPIF_WHEN_NEVER;
3973 }
3974 }
3975
3976 /*
3977 * Chunk HPIF (client --> server)
3978 *
3979 * Heap Info. General information about the heap,
3980 * suitable for a summary display.
3981 *
3982 * [u4]: number of heaps
3983 *
3984 * For each heap:
3985 * [u4]: heap ID
3986 * [u8]: timestamp in ms since Unix epoch
3987 * [u1]: capture reason (same as 'when' value from server)
3988 * [u4]: max heap size in bytes (-Xmx)
3989 * [u4]: current heap size in bytes
3990 * [u4]: current number of bytes allocated
3991 * [u4]: current number of objects allocated
3992 */
3993 uint8_t heap_count = 1;
Ian Rogers1d54e732013-05-02 21:10:01 -07003994 gc::Heap* heap = Runtime::Current()->GetHeap();
Elliott Hughes21f32d72011-11-09 17:44:13 -08003995 std::vector<uint8_t> bytes;
Elliott Hughes545a0642011-11-08 19:10:03 -08003996 JDWP::Append4BE(bytes, heap_count);
Brian Carlstrom7934ac22013-07-26 10:54:15 -07003997 JDWP::Append4BE(bytes, 1); // Heap id (bogus; we only have one heap).
Elliott Hughes545a0642011-11-08 19:10:03 -08003998 JDWP::Append8BE(bytes, MilliTime());
3999 JDWP::Append1BE(bytes, reason);
Brian Carlstrom7934ac22013-07-26 10:54:15 -07004000 JDWP::Append4BE(bytes, heap->GetMaxMemory()); // Max allowed heap size in bytes.
4001 JDWP::Append4BE(bytes, heap->GetTotalMemory()); // Current heap size in bytes.
Elliott Hughesb3bd5f02012-03-08 21:05:27 -08004002 JDWP::Append4BE(bytes, heap->GetBytesAllocated());
4003 JDWP::Append4BE(bytes, heap->GetObjectsAllocated());
Elliott Hughes21f32d72011-11-09 17:44:13 -08004004 CHECK_EQ(bytes.size(), 4U + (heap_count * (4 + 8 + 1 + 4 + 4 + 4 + 4)));
4005 Dbg::DdmSendChunk(CHUNK_TYPE("HPIF"), bytes);
Elliott Hughes767a1472011-10-26 18:49:02 -07004006}
4007
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004008enum HpsgSolidity {
4009 SOLIDITY_FREE = 0,
4010 SOLIDITY_HARD = 1,
4011 SOLIDITY_SOFT = 2,
4012 SOLIDITY_WEAK = 3,
4013 SOLIDITY_PHANTOM = 4,
4014 SOLIDITY_FINALIZABLE = 5,
4015 SOLIDITY_SWEEP = 6,
4016};
4017
4018enum HpsgKind {
4019 KIND_OBJECT = 0,
4020 KIND_CLASS_OBJECT = 1,
4021 KIND_ARRAY_1 = 2,
4022 KIND_ARRAY_2 = 3,
4023 KIND_ARRAY_4 = 4,
4024 KIND_ARRAY_8 = 5,
4025 KIND_UNKNOWN = 6,
4026 KIND_NATIVE = 7,
4027};
4028
4029#define HPSG_PARTIAL (1<<7)
4030#define HPSG_STATE(solidity, kind) ((uint8_t)((((kind) & 0x7) << 3) | ((solidity) & 0x7)))
4031
Ian Rogers30fab402012-01-23 15:43:46 -08004032class HeapChunkContext {
4033 public:
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004034 // Maximum chunk size. Obtain this from the formula:
4035 // (((maximum_heap_size / ALLOCATION_UNIT_SIZE) + 255) / 256) * 2
4036 HeapChunkContext(bool merge, bool native)
Ian Rogers30fab402012-01-23 15:43:46 -08004037 : buf_(16384 - 16),
4038 type_(0),
Mathieu Chartier36dab362014-07-30 14:59:56 -07004039 merge_(merge),
4040 chunk_overhead_(0) {
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004041 Reset();
4042 if (native) {
Ian Rogers30fab402012-01-23 15:43:46 -08004043 type_ = CHUNK_TYPE("NHSG");
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004044 } else {
Ian Rogers30fab402012-01-23 15:43:46 -08004045 type_ = merge ? CHUNK_TYPE("HPSG") : CHUNK_TYPE("HPSO");
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004046 }
4047 }
4048
4049 ~HeapChunkContext() {
Ian Rogers30fab402012-01-23 15:43:46 -08004050 if (p_ > &buf_[0]) {
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004051 Flush();
4052 }
4053 }
4054
Mathieu Chartier36dab362014-07-30 14:59:56 -07004055 void SetChunkOverhead(size_t chunk_overhead) {
4056 chunk_overhead_ = chunk_overhead;
4057 }
4058
4059 void ResetStartOfNextChunk() {
4060 startOfNextMemoryChunk_ = nullptr;
4061 }
4062
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004063 void EnsureHeader(const void* chunk_ptr) {
Ian Rogers30fab402012-01-23 15:43:46 -08004064 if (!needHeader_) {
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004065 return;
4066 }
4067
4068 // Start a new HPSx chunk.
Brian Carlstrom7934ac22013-07-26 10:54:15 -07004069 JDWP::Write4BE(&p_, 1); // Heap id (bogus; we only have one heap).
4070 JDWP::Write1BE(&p_, 8); // Size of allocation unit, in bytes.
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004071
Brian Carlstrom7934ac22013-07-26 10:54:15 -07004072 JDWP::Write4BE(&p_, reinterpret_cast<uintptr_t>(chunk_ptr)); // virtual address of segment start.
4073 JDWP::Write4BE(&p_, 0); // offset of this piece (relative to the virtual address).
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004074 // [u4]: length of piece, in allocation units
4075 // 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 -08004076 pieceLenField_ = p_;
4077 JDWP::Write4BE(&p_, 0x55555555);
4078 needHeader_ = false;
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004079 }
4080
Ian Rogersb726dcb2012-09-05 08:57:23 -07004081 void Flush() SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Ian Rogersc0542af2014-09-03 16:16:56 -07004082 if (pieceLenField_ == nullptr) {
Ian Rogersd636b062013-01-18 17:51:18 -08004083 // Flush immediately post Reset (maybe back-to-back Flush). Ignore.
4084 CHECK(needHeader_);
4085 return;
4086 }
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004087 // Patch the "length of piece" field.
Ian Rogers30fab402012-01-23 15:43:46 -08004088 CHECK_LE(&buf_[0], pieceLenField_);
4089 CHECK_LE(pieceLenField_, p_);
4090 JDWP::Set4BE(pieceLenField_, totalAllocationUnits_);
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004091
Ian Rogers30fab402012-01-23 15:43:46 -08004092 Dbg::DdmSendChunk(type_, p_ - &buf_[0], &buf_[0]);
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004093 Reset();
4094 }
4095
Ian Rogers00f7d0e2012-07-19 15:28:27 -07004096 static void HeapChunkCallback(void* start, void* end, size_t used_bytes, void* arg)
Ian Rogersb726dcb2012-09-05 08:57:23 -07004097 SHARED_LOCKS_REQUIRED(Locks::heap_bitmap_lock_,
4098 Locks::mutator_lock_) {
Ian Rogers30fab402012-01-23 15:43:46 -08004099 reinterpret_cast<HeapChunkContext*>(arg)->HeapChunkCallback(start, end, used_bytes);
Elliott Hughesa2155262011-11-16 16:26:58 -08004100 }
4101
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004102 private:
Elliott Hughesa2155262011-11-16 16:26:58 -08004103 enum { ALLOCATION_UNIT_SIZE = 8 };
4104
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004105 void Reset() {
Ian Rogers30fab402012-01-23 15:43:46 -08004106 p_ = &buf_[0];
Mathieu Chartier36dab362014-07-30 14:59:56 -07004107 ResetStartOfNextChunk();
Ian Rogers30fab402012-01-23 15:43:46 -08004108 totalAllocationUnits_ = 0;
4109 needHeader_ = true;
Ian Rogersc0542af2014-09-03 16:16:56 -07004110 pieceLenField_ = nullptr;
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004111 }
4112
Ian Rogers00f7d0e2012-07-19 15:28:27 -07004113 void HeapChunkCallback(void* start, void* /*end*/, size_t used_bytes)
Ian Rogersb726dcb2012-09-05 08:57:23 -07004114 SHARED_LOCKS_REQUIRED(Locks::heap_bitmap_lock_,
4115 Locks::mutator_lock_) {
Ian Rogers30fab402012-01-23 15:43:46 -08004116 // Note: heap call backs cannot manipulate the heap upon which they are crawling, care is taken
4117 // in the following code not to allocate memory, by ensuring buf_ is of the correct size
Ian Rogers15bf2d32012-08-28 17:33:04 -07004118 if (used_bytes == 0) {
Ian Rogersc0542af2014-09-03 16:16:56 -07004119 if (start == nullptr) {
Ian Rogers15bf2d32012-08-28 17:33:04 -07004120 // Reset for start of new heap.
Ian Rogersc0542af2014-09-03 16:16:56 -07004121 startOfNextMemoryChunk_ = nullptr;
Ian Rogers15bf2d32012-08-28 17:33:04 -07004122 Flush();
4123 }
4124 // Only process in use memory so that free region information
4125 // also includes dlmalloc book keeping.
Elliott Hughesa2155262011-11-16 16:26:58 -08004126 return;
Elliott Hughesa2155262011-11-16 16:26:58 -08004127 }
4128
Ian Rogers15bf2d32012-08-28 17:33:04 -07004129 /* If we're looking at the native heap, we'll just return
4130 * (SOLIDITY_HARD, KIND_NATIVE) for all allocated chunks
4131 */
4132 bool native = type_ == CHUNK_TYPE("NHSG");
4133
Mathieu Chartier36dab362014-07-30 14:59:56 -07004134 // TODO: I'm not sure using start of next chunk works well with multiple spaces. We shouldn't
4135 // count gaps inbetween spaces as free memory.
Ian Rogersc0542af2014-09-03 16:16:56 -07004136 if (startOfNextMemoryChunk_ != nullptr) {
Ian Rogers15bf2d32012-08-28 17:33:04 -07004137 // Transmit any pending free memory. Native free memory of
4138 // over kMaxFreeLen could be because of the use of mmaps, so
4139 // don't report. If not free memory then start a new segment.
4140 bool flush = true;
4141 if (start > startOfNextMemoryChunk_) {
4142 const size_t kMaxFreeLen = 2 * kPageSize;
4143 void* freeStart = startOfNextMemoryChunk_;
4144 void* freeEnd = start;
Brian Carlstrom2d888622013-07-18 17:02:00 -07004145 size_t freeLen = reinterpret_cast<char*>(freeEnd) - reinterpret_cast<char*>(freeStart);
Ian Rogers15bf2d32012-08-28 17:33:04 -07004146 if (!native || freeLen < kMaxFreeLen) {
4147 AppendChunk(HPSG_STATE(SOLIDITY_FREE, 0), freeStart, freeLen);
4148 flush = false;
4149 }
4150 }
4151 if (flush) {
Ian Rogersc0542af2014-09-03 16:16:56 -07004152 startOfNextMemoryChunk_ = nullptr;
Ian Rogers15bf2d32012-08-28 17:33:04 -07004153 Flush();
4154 }
4155 }
Ian Rogersef7d42f2014-01-06 12:55:46 -08004156 mirror::Object* obj = reinterpret_cast<mirror::Object*>(start);
Elliott Hughesa2155262011-11-16 16:26:58 -08004157
4158 // Determine the type of this chunk.
4159 // OLD-TODO: if context.merge, see if this chunk is different from the last chunk.
4160 // If it's the same, we should combine them.
Ian Rogers15bf2d32012-08-28 17:33:04 -07004161 uint8_t state = ExamineObject(obj, native);
Mathieu Chartier36dab362014-07-30 14:59:56 -07004162 AppendChunk(state, start, used_bytes + chunk_overhead_);
4163 startOfNextMemoryChunk_ = reinterpret_cast<char*>(start) + used_bytes + chunk_overhead_;
Ian Rogers15bf2d32012-08-28 17:33:04 -07004164 }
Elliott Hughesa2155262011-11-16 16:26:58 -08004165
Ian Rogers15bf2d32012-08-28 17:33:04 -07004166 void AppendChunk(uint8_t state, void* ptr, size_t length)
Ian Rogersb726dcb2012-09-05 08:57:23 -07004167 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Ian Rogers15bf2d32012-08-28 17:33:04 -07004168 // Make sure there's enough room left in the buffer.
4169 // We need to use two bytes for every fractional 256 allocation units used by the chunk plus
4170 // 17 bytes for any header.
4171 size_t needed = (((length/ALLOCATION_UNIT_SIZE + 255) / 256) * 2) + 17;
4172 size_t bytesLeft = buf_.size() - (size_t)(p_ - &buf_[0]);
4173 if (bytesLeft < needed) {
4174 Flush();
4175 }
4176
4177 bytesLeft = buf_.size() - (size_t)(p_ - &buf_[0]);
4178 if (bytesLeft < needed) {
4179 LOG(WARNING) << "Chunk is too big to transmit (chunk_len=" << length << ", "
4180 << needed << " bytes)";
4181 return;
4182 }
4183 EnsureHeader(ptr);
Elliott Hughesa2155262011-11-16 16:26:58 -08004184 // Write out the chunk description.
Ian Rogers15bf2d32012-08-28 17:33:04 -07004185 length /= ALLOCATION_UNIT_SIZE; // Convert to allocation units.
4186 totalAllocationUnits_ += length;
4187 while (length > 256) {
Ian Rogers30fab402012-01-23 15:43:46 -08004188 *p_++ = state | HPSG_PARTIAL;
4189 *p_++ = 255; // length - 1
Ian Rogers15bf2d32012-08-28 17:33:04 -07004190 length -= 256;
Elliott Hughesa2155262011-11-16 16:26:58 -08004191 }
Ian Rogers30fab402012-01-23 15:43:46 -08004192 *p_++ = state;
Ian Rogers15bf2d32012-08-28 17:33:04 -07004193 *p_++ = length - 1;
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004194 }
4195
Ian Rogersef7d42f2014-01-06 12:55:46 -08004196 uint8_t ExamineObject(mirror::Object* o, bool is_native_heap)
4197 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_, Locks::heap_bitmap_lock_) {
Ian Rogersc0542af2014-09-03 16:16:56 -07004198 if (o == nullptr) {
Elliott Hughesa2155262011-11-16 16:26:58 -08004199 return HPSG_STATE(SOLIDITY_FREE, 0);
4200 }
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004201
Elliott Hughesa2155262011-11-16 16:26:58 -08004202 // It's an allocated chunk. Figure out what it is.
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004203
Elliott Hughesa2155262011-11-16 16:26:58 -08004204 // If we're looking at the native heap, we'll just return
4205 // (SOLIDITY_HARD, KIND_NATIVE) for all allocated chunks.
Ian Rogers00f7d0e2012-07-19 15:28:27 -07004206 if (is_native_heap) {
Elliott Hughesa2155262011-11-16 16:26:58 -08004207 return HPSG_STATE(SOLIDITY_HARD, KIND_NATIVE);
4208 }
4209
Ian Rogers5bfa60f2012-09-02 21:17:56 -07004210 if (!Runtime::Current()->GetHeap()->IsLiveObjectLocked(o)) {
Ian Rogers15bf2d32012-08-28 17:33:04 -07004211 return HPSG_STATE(SOLIDITY_HARD, KIND_NATIVE);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07004212 }
4213
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08004214 mirror::Class* c = o->GetClass();
Ian Rogersc0542af2014-09-03 16:16:56 -07004215 if (c == nullptr) {
Elliott Hughesa2155262011-11-16 16:26:58 -08004216 // The object was probably just created but hasn't been initialized yet.
4217 return HPSG_STATE(SOLIDITY_HARD, KIND_OBJECT);
4218 }
4219
Mathieu Chartier590fee92013-09-13 13:46:47 -07004220 if (!Runtime::Current()->GetHeap()->IsValidObjectAddress(c)) {
Ian Rogers15bf2d32012-08-28 17:33:04 -07004221 LOG(ERROR) << "Invalid class for managed heap object: " << o << " " << c;
Elliott Hughesa2155262011-11-16 16:26:58 -08004222 return HPSG_STATE(SOLIDITY_HARD, KIND_UNKNOWN);
4223 }
4224
4225 if (c->IsClassClass()) {
4226 return HPSG_STATE(SOLIDITY_HARD, KIND_CLASS_OBJECT);
4227 }
4228
4229 if (c->IsArrayClass()) {
4230 if (o->IsObjectArray()) {
4231 return HPSG_STATE(SOLIDITY_HARD, KIND_ARRAY_4);
4232 }
4233 switch (c->GetComponentSize()) {
4234 case 1: return HPSG_STATE(SOLIDITY_HARD, KIND_ARRAY_1);
4235 case 2: return HPSG_STATE(SOLIDITY_HARD, KIND_ARRAY_2);
4236 case 4: return HPSG_STATE(SOLIDITY_HARD, KIND_ARRAY_4);
4237 case 8: return HPSG_STATE(SOLIDITY_HARD, KIND_ARRAY_8);
4238 }
4239 }
4240
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004241 return HPSG_STATE(SOLIDITY_HARD, KIND_OBJECT);
4242 }
4243
Ian Rogers30fab402012-01-23 15:43:46 -08004244 std::vector<uint8_t> buf_;
4245 uint8_t* p_;
4246 uint8_t* pieceLenField_;
Ian Rogers15bf2d32012-08-28 17:33:04 -07004247 void* startOfNextMemoryChunk_;
Ian Rogers30fab402012-01-23 15:43:46 -08004248 size_t totalAllocationUnits_;
4249 uint32_t type_;
4250 bool merge_;
4251 bool needHeader_;
Mathieu Chartier36dab362014-07-30 14:59:56 -07004252 size_t chunk_overhead_;
Ian Rogers30fab402012-01-23 15:43:46 -08004253
Elliott Hughesa2155262011-11-16 16:26:58 -08004254 DISALLOW_COPY_AND_ASSIGN(HeapChunkContext);
4255};
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004256
Mathieu Chartier36dab362014-07-30 14:59:56 -07004257static void BumpPointerSpaceCallback(mirror::Object* obj, void* arg)
4258 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) EXCLUSIVE_LOCKS_REQUIRED(Locks::heap_bitmap_lock_) {
4259 const size_t size = RoundUp(obj->SizeOf(), kObjectAlignment);
4260 HeapChunkContext::HeapChunkCallback(
4261 obj, reinterpret_cast<void*>(reinterpret_cast<uintptr_t>(obj) + size), size, arg);
4262}
4263
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004264void Dbg::DdmSendHeapSegments(bool native) {
4265 Dbg::HpsgWhen when;
4266 Dbg::HpsgWhat what;
4267 if (!native) {
4268 when = gDdmHpsgWhen;
4269 what = gDdmHpsgWhat;
4270 } else {
4271 when = gDdmNhsgWhen;
4272 what = gDdmNhsgWhat;
4273 }
4274 if (when == HPSG_WHEN_NEVER) {
4275 return;
4276 }
4277
4278 // Figure out what kind of chunks we'll be sending.
4279 CHECK(what == HPSG_WHAT_MERGED_OBJECTS || what == HPSG_WHAT_DISTINCT_OBJECTS) << static_cast<int>(what);
4280
4281 // First, send a heap start chunk.
4282 uint8_t heap_id[4];
Brian Carlstrom7934ac22013-07-26 10:54:15 -07004283 JDWP::Set4BE(&heap_id[0], 1); // Heap id (bogus; we only have one heap).
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004284 Dbg::DdmSendChunk(native ? CHUNK_TYPE("NHST") : CHUNK_TYPE("HPST"), sizeof(heap_id), heap_id);
4285
Hiroshi Yamauchicf58d4a2013-09-26 14:21:22 -07004286 Thread* self = Thread::Current();
4287
4288 // To allow the Walk/InspectAll() below to exclusively-lock the
4289 // mutator lock, temporarily release the shared access to the
4290 // mutator lock here by transitioning to the suspended state.
4291 Locks::mutator_lock_->AssertSharedHeld(self);
4292 self->TransitionFromRunnableToSuspended(kSuspended);
4293
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004294 // Send a series of heap segment chunks.
Elliott Hughesa2155262011-11-16 16:26:58 -08004295 HeapChunkContext context((what == HPSG_WHAT_MERGED_OBJECTS), native);
4296 if (native) {
Christopher Ferrisc4ddc042014-05-13 14:47:50 -07004297#ifdef USE_DLMALLOC
Ian Rogers1d54e732013-05-02 21:10:01 -07004298 dlmalloc_inspect_all(HeapChunkContext::HeapChunkCallback, &context);
Christopher Ferrisc4ddc042014-05-13 14:47:50 -07004299#else
4300 UNIMPLEMENTED(WARNING) << "Native heap inspection is only supported with dlmalloc";
4301#endif
Elliott Hughesa2155262011-11-16 16:26:58 -08004302 } else {
Ian Rogers1d54e732013-05-02 21:10:01 -07004303 gc::Heap* heap = Runtime::Current()->GetHeap();
Mathieu Chartier36dab362014-07-30 14:59:56 -07004304 for (const auto& space : heap->GetContinuousSpaces()) {
4305 if (space->IsDlMallocSpace()) {
4306 // dlmalloc's chunk header is 2 * sizeof(size_t), but if the previous chunk is in use for an
4307 // allocation then the first sizeof(size_t) may belong to it.
4308 context.SetChunkOverhead(sizeof(size_t));
4309 space->AsDlMallocSpace()->Walk(HeapChunkContext::HeapChunkCallback, &context);
4310 } else if (space->IsRosAllocSpace()) {
4311 context.SetChunkOverhead(0);
4312 space->AsRosAllocSpace()->Walk(HeapChunkContext::HeapChunkCallback, &context);
4313 } else if (space->IsBumpPointerSpace()) {
4314 context.SetChunkOverhead(0);
4315 ReaderMutexLock mu(self, *Locks::mutator_lock_);
4316 WriterMutexLock mu2(self, *Locks::heap_bitmap_lock_);
4317 space->AsBumpPointerSpace()->Walk(BumpPointerSpaceCallback, &context);
4318 } else {
4319 UNIMPLEMENTED(WARNING) << "Not counting objects in space " << *space;
Mathieu Chartierb062fdd2012-07-03 09:51:48 -07004320 }
Mathieu Chartier36dab362014-07-30 14:59:56 -07004321 context.ResetStartOfNextChunk();
Mathieu Chartierb062fdd2012-07-03 09:51:48 -07004322 }
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -07004323 // Walk the large objects, these are not in the AllocSpace.
Mathieu Chartier36dab362014-07-30 14:59:56 -07004324 context.SetChunkOverhead(0);
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -07004325 heap->GetLargeObjectsSpace()->Walk(HeapChunkContext::HeapChunkCallback, &context);
Elliott Hughesa2155262011-11-16 16:26:58 -08004326 }
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004327
Hiroshi Yamauchicf58d4a2013-09-26 14:21:22 -07004328 // Shared-lock the mutator lock back.
4329 self->TransitionFromSuspendedToRunnable();
4330 Locks::mutator_lock_->AssertSharedHeld(self);
4331
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004332 // Finally, send a heap end chunk.
4333 Dbg::DdmSendChunk(native ? CHUNK_TYPE("NHEN") : CHUNK_TYPE("HPEN"), sizeof(heap_id), heap_id);
Elliott Hughes767a1472011-10-26 18:49:02 -07004334}
4335
Elliott Hughesb1a58792013-07-11 18:10:58 -07004336static size_t GetAllocTrackerMax() {
4337#ifdef HAVE_ANDROID_OS
4338 // Check whether there's a system property overriding the number of records.
4339 const char* propertyName = "dalvik.vm.allocTrackerMax";
4340 char allocRecordMaxString[PROPERTY_VALUE_MAX];
4341 if (property_get(propertyName, allocRecordMaxString, "") > 0) {
4342 char* end;
4343 size_t value = strtoul(allocRecordMaxString, &end, 10);
4344 if (*end != '\0') {
Ruben Brunk3e47a742013-09-09 17:56:07 -07004345 LOG(ERROR) << "Ignoring " << propertyName << " '" << allocRecordMaxString
4346 << "' --- invalid";
Elliott Hughesb1a58792013-07-11 18:10:58 -07004347 return kDefaultNumAllocRecords;
4348 }
4349 if (!IsPowerOfTwo(value)) {
Ruben Brunk3e47a742013-09-09 17:56:07 -07004350 LOG(ERROR) << "Ignoring " << propertyName << " '" << allocRecordMaxString
4351 << "' --- not power of two";
Elliott Hughesb1a58792013-07-11 18:10:58 -07004352 return kDefaultNumAllocRecords;
4353 }
4354 return value;
4355 }
4356#endif
4357 return kDefaultNumAllocRecords;
4358}
4359
Brian Carlstrom306db812014-09-05 13:01:41 -07004360void Dbg::SetAllocTrackingEnabled(bool enable) {
4361 Thread* self = Thread::Current();
4362 if (enable) {
Sebastien Hertzb98063a2014-03-26 10:57:20 +01004363 {
Brian Carlstrom306db812014-09-05 13:01:41 -07004364 MutexLock mu(self, *Locks::alloc_tracker_lock_);
4365 if (recent_allocation_records_ != nullptr) {
4366 return; // Already enabled, bail.
Sebastien Hertzb98063a2014-03-26 10:57:20 +01004367 }
Brian Carlstrom306db812014-09-05 13:01:41 -07004368 alloc_record_max_ = GetAllocTrackerMax();
4369 LOG(INFO) << "Enabling alloc tracker (" << alloc_record_max_ << " entries of "
4370 << kMaxAllocRecordStackDepth << " frames, taking "
4371 << PrettySize(sizeof(AllocRecord) * alloc_record_max_) << ")";
4372 DCHECK_EQ(alloc_record_head_, 0U);
4373 DCHECK_EQ(alloc_record_count_, 0U);
4374 recent_allocation_records_ = new AllocRecord[alloc_record_max_];
4375 CHECK(recent_allocation_records_ != nullptr);
Elliott Hughes545a0642011-11-08 19:10:03 -08004376 }
Ian Rogersfa824272013-11-05 16:12:57 -08004377 Runtime::Current()->GetInstrumentation()->InstrumentQuickAllocEntryPoints();
Elliott Hughes545a0642011-11-08 19:10:03 -08004378 } else {
Sebastien Hertzb98063a2014-03-26 10:57:20 +01004379 {
Brian Carlstrom306db812014-09-05 13:01:41 -07004380 ScopedObjectAccess soa(self); // For type_cache_.Clear();
4381 MutexLock mu(self, *Locks::alloc_tracker_lock_);
4382 if (recent_allocation_records_ == nullptr) {
4383 return; // Already disabled, bail.
4384 }
Mathieu Chartier4345c462014-06-27 10:20:14 -07004385 LOG(INFO) << "Disabling alloc tracker";
Sebastien Hertzb98063a2014-03-26 10:57:20 +01004386 delete[] recent_allocation_records_;
Ian Rogersc0542af2014-09-03 16:16:56 -07004387 recent_allocation_records_ = nullptr;
Brian Carlstrom306db812014-09-05 13:01:41 -07004388 alloc_record_head_ = 0;
4389 alloc_record_count_ = 0;
Mathieu Chartier4345c462014-06-27 10:20:14 -07004390 type_cache_.Clear();
Sebastien Hertzb98063a2014-03-26 10:57:20 +01004391 }
Brian Carlstrom306db812014-09-05 13:01:41 -07004392 // If an allocation comes in before we uninstrument, we will safely drop it on the floor.
4393 Runtime::Current()->GetInstrumentation()->UninstrumentQuickAllocEntryPoints();
Elliott Hughes545a0642011-11-08 19:10:03 -08004394 }
4395}
4396
Ian Rogers0399dde2012-06-06 17:09:28 -07004397struct AllocRecordStackVisitor : public StackVisitor {
Ian Rogers7a22fa62013-01-23 12:16:16 -08004398 AllocRecordStackVisitor(Thread* thread, AllocRecord* record)
Ian Rogersb726dcb2012-09-05 08:57:23 -07004399 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_)
Ian Rogersc0542af2014-09-03 16:16:56 -07004400 : StackVisitor(thread, nullptr), record(record), depth(0) {}
Elliott Hughes545a0642011-11-08 19:10:03 -08004401
Ian Rogers00f7d0e2012-07-19 15:28:27 -07004402 // TODO: Enable annotalysis. We know lock is held in constructor, but abstraction confuses
4403 // annotalysis.
4404 bool VisitFrame() NO_THREAD_SAFETY_ANALYSIS {
Elliott Hughes545a0642011-11-08 19:10:03 -08004405 if (depth >= kMaxAllocRecordStackDepth) {
Elliott Hughes530fa002012-03-12 11:44:49 -07004406 return false;
Elliott Hughes545a0642011-11-08 19:10:03 -08004407 }
Brian Carlstromea46f952013-07-30 01:26:50 -07004408 mirror::ArtMethod* m = GetMethod();
Ian Rogers0399dde2012-06-06 17:09:28 -07004409 if (!m->IsRuntimeMethod()) {
Hiroshi Yamauchib5a9e3d2014-06-09 12:11:20 -07004410 record->StackElement(depth)->SetMethod(m);
4411 record->StackElement(depth)->SetDexPc(GetDexPc());
Elliott Hughes530fa002012-03-12 11:44:49 -07004412 ++depth;
Elliott Hughes545a0642011-11-08 19:10:03 -08004413 }
Elliott Hughes530fa002012-03-12 11:44:49 -07004414 return true;
Elliott Hughes545a0642011-11-08 19:10:03 -08004415 }
4416
4417 ~AllocRecordStackVisitor() {
4418 // Clear out any unused stack trace elements.
4419 for (; depth < kMaxAllocRecordStackDepth; ++depth) {
Hiroshi Yamauchib5a9e3d2014-06-09 12:11:20 -07004420 record->StackElement(depth)->SetMethod(nullptr);
4421 record->StackElement(depth)->SetDexPc(0);
Elliott Hughes545a0642011-11-08 19:10:03 -08004422 }
4423 }
4424
4425 AllocRecord* record;
4426 size_t depth;
4427};
4428
Ian Rogers844506b2014-09-12 19:59:33 -07004429void Dbg::RecordAllocation(Thread* self, mirror::Class* type, size_t byte_count) {
Brian Carlstrom306db812014-09-05 13:01:41 -07004430 MutexLock mu(self, *Locks::alloc_tracker_lock_);
Ian Rogersc0542af2014-09-03 16:16:56 -07004431 if (recent_allocation_records_ == nullptr) {
Brian Carlstrom306db812014-09-05 13:01:41 -07004432 // In the process of shutting down recording, bail.
Elliott Hughes545a0642011-11-08 19:10:03 -08004433 return;
4434 }
4435
4436 // Advance and clip.
Ian Rogers719d1a32014-03-06 12:13:39 -08004437 if (++alloc_record_head_ == alloc_record_max_) {
4438 alloc_record_head_ = 0;
Elliott Hughes545a0642011-11-08 19:10:03 -08004439 }
4440
4441 // Fill in the basics.
Ian Rogers719d1a32014-03-06 12:13:39 -08004442 AllocRecord* record = &recent_allocation_records_[alloc_record_head_];
Hiroshi Yamauchib5a9e3d2014-06-09 12:11:20 -07004443 record->SetType(type);
4444 record->SetByteCount(byte_count);
4445 record->SetThinLockId(self->GetThreadId());
Elliott Hughes545a0642011-11-08 19:10:03 -08004446
4447 // Fill in the stack trace.
Ian Rogers7a22fa62013-01-23 12:16:16 -08004448 AllocRecordStackVisitor visitor(self, record);
Ian Rogers0399dde2012-06-06 17:09:28 -07004449 visitor.WalkStack();
Elliott Hughes545a0642011-11-08 19:10:03 -08004450
Ian Rogers719d1a32014-03-06 12:13:39 -08004451 if (alloc_record_count_ < alloc_record_max_) {
4452 ++alloc_record_count_;
Elliott Hughes545a0642011-11-08 19:10:03 -08004453 }
4454}
4455
Elliott Hughesa8f93cb2012-06-08 17:08:48 -07004456// Returns the index of the head element.
4457//
Brian Carlstrom306db812014-09-05 13:01:41 -07004458// We point at the most-recently-written record, so if alloc_record_count_ is 1
Elliott Hughesa8f93cb2012-06-08 17:08:48 -07004459// we want to use the current element. Take "head+1" and subtract count
4460// from it.
4461//
4462// We need to handle underflow in our circular buffer, so we add
Brian Carlstrom306db812014-09-05 13:01:41 -07004463// alloc_record_max_ and then mask it back down.
Ian Rogers719d1a32014-03-06 12:13:39 -08004464size_t Dbg::HeadIndex() {
4465 return (Dbg::alloc_record_head_ + 1 + Dbg::alloc_record_max_ - Dbg::alloc_record_count_) &
4466 (Dbg::alloc_record_max_ - 1);
Elliott Hughes545a0642011-11-08 19:10:03 -08004467}
4468
4469void Dbg::DumpRecentAllocations() {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07004470 ScopedObjectAccess soa(Thread::Current());
Brian Carlstrom306db812014-09-05 13:01:41 -07004471 MutexLock mu(soa.Self(), *Locks::alloc_tracker_lock_);
Ian Rogersc0542af2014-09-03 16:16:56 -07004472 if (recent_allocation_records_ == nullptr) {
Elliott Hughes545a0642011-11-08 19:10:03 -08004473 LOG(INFO) << "Not recording tracked allocations";
4474 return;
4475 }
4476
4477 // "i" is the head of the list. We want to start at the end of the
4478 // list and move forward to the tail.
Elliott Hughesa8f93cb2012-06-08 17:08:48 -07004479 size_t i = HeadIndex();
Brian Carlstrom306db812014-09-05 13:01:41 -07004480 const uint16_t capped_count = CappedAllocRecordCount(Dbg::alloc_record_count_);
4481 uint16_t count = capped_count;
Elliott Hughes545a0642011-11-08 19:10:03 -08004482
Ian Rogers719d1a32014-03-06 12:13:39 -08004483 LOG(INFO) << "Tracked allocations, (head=" << alloc_record_head_ << " count=" << count << ")";
Elliott Hughes545a0642011-11-08 19:10:03 -08004484 while (count--) {
4485 AllocRecord* record = &recent_allocation_records_[i];
4486
Hiroshi Yamauchib5a9e3d2014-06-09 12:11:20 -07004487 LOG(INFO) << StringPrintf(" Thread %-2d %6zd bytes ", record->ThinLockId(), record->ByteCount())
4488 << PrettyClass(record->Type());
Elliott Hughes545a0642011-11-08 19:10:03 -08004489
4490 for (size_t stack_frame = 0; stack_frame < kMaxAllocRecordStackDepth; ++stack_frame) {
Hiroshi Yamauchib5a9e3d2014-06-09 12:11:20 -07004491 AllocRecordStackTraceElement* stack_element = record->StackElement(stack_frame);
4492 mirror::ArtMethod* m = stack_element->Method();
Ian Rogersc0542af2014-09-03 16:16:56 -07004493 if (m == nullptr) {
Elliott Hughes545a0642011-11-08 19:10:03 -08004494 break;
4495 }
Hiroshi Yamauchib5a9e3d2014-06-09 12:11:20 -07004496 LOG(INFO) << " " << PrettyMethod(m) << " line " << stack_element->LineNumber();
Elliott Hughes545a0642011-11-08 19:10:03 -08004497 }
4498
4499 // pause periodically to help logcat catch up
4500 if ((count % 5) == 0) {
4501 usleep(40000);
4502 }
4503
Ian Rogers719d1a32014-03-06 12:13:39 -08004504 i = (i + 1) & (alloc_record_max_ - 1);
Elliott Hughes545a0642011-11-08 19:10:03 -08004505 }
4506}
4507
4508class StringTable {
4509 public:
4510 StringTable() {
4511 }
4512
Mathieu Chartier4345c462014-06-27 10:20:14 -07004513 void Add(const std::string& str) {
4514 table_.insert(str);
4515 }
4516
4517 void Add(const char* str) {
4518 table_.insert(str);
Elliott Hughes545a0642011-11-08 19:10:03 -08004519 }
4520
Elliott Hughesa8f93cb2012-06-08 17:08:48 -07004521 size_t IndexOf(const char* s) const {
Mathieu Chartier02e25112013-08-14 16:14:24 -07004522 auto it = table_.find(s);
Elliott Hughesa8f93cb2012-06-08 17:08:48 -07004523 if (it == table_.end()) {
4524 LOG(FATAL) << "IndexOf(\"" << s << "\") failed";
4525 }
4526 return std::distance(table_.begin(), it);
Elliott Hughes545a0642011-11-08 19:10:03 -08004527 }
4528
Elliott Hughesa8f93cb2012-06-08 17:08:48 -07004529 size_t Size() const {
Elliott Hughes545a0642011-11-08 19:10:03 -08004530 return table_.size();
4531 }
4532
Elliott Hughesa8f93cb2012-06-08 17:08:48 -07004533 void WriteTo(std::vector<uint8_t>& bytes) const {
Mathieu Chartier02e25112013-08-14 16:14:24 -07004534 for (const std::string& str : table_) {
4535 const char* s = str.c_str();
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08004536 size_t s_len = CountModifiedUtf8Chars(s);
Ian Rogers700a4022014-05-19 16:49:03 -07004537 std::unique_ptr<uint16_t> s_utf16(new uint16_t[s_len]);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08004538 ConvertModifiedUtf8ToUtf16(s_utf16.get(), s);
4539 JDWP::AppendUtf16BE(bytes, s_utf16.get(), s_len);
Elliott Hughes545a0642011-11-08 19:10:03 -08004540 }
4541 }
4542
4543 private:
Elliott Hughesa8f93cb2012-06-08 17:08:48 -07004544 std::set<std::string> table_;
Elliott Hughes545a0642011-11-08 19:10:03 -08004545 DISALLOW_COPY_AND_ASSIGN(StringTable);
4546};
4547
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07004548static const char* GetMethodSourceFile(mirror::ArtMethod* method)
Sebastien Hertz280286a2014-04-28 09:26:50 +02004549 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07004550 DCHECK(method != nullptr);
4551 const char* source_file = method->GetDeclaringClassSourceFile();
Sebastien Hertz280286a2014-04-28 09:26:50 +02004552 return (source_file != nullptr) ? source_file : "";
4553}
4554
Elliott Hughes545a0642011-11-08 19:10:03 -08004555/*
4556 * The data we send to DDMS contains everything we have recorded.
4557 *
4558 * Message header (all values big-endian):
4559 * (1b) message header len (to allow future expansion); includes itself
4560 * (1b) entry header len
4561 * (1b) stack frame len
4562 * (2b) number of entries
4563 * (4b) offset to string table from start of message
4564 * (2b) number of class name strings
4565 * (2b) number of method name strings
4566 * (2b) number of source file name strings
4567 * For each entry:
4568 * (4b) total allocation size
Elliott Hughes221229c2013-01-08 18:17:50 -08004569 * (2b) thread id
Elliott Hughes545a0642011-11-08 19:10:03 -08004570 * (2b) allocated object's class name index
4571 * (1b) stack depth
4572 * For each stack frame:
4573 * (2b) method's class name
4574 * (2b) method name
4575 * (2b) method source file
4576 * (2b) line number, clipped to 32767; -2 if native; -1 if no source
4577 * (xb) class name strings
4578 * (xb) method name strings
4579 * (xb) source file strings
4580 *
4581 * As with other DDM traffic, strings are sent as a 4-byte length
4582 * followed by UTF-16 data.
4583 *
4584 * We send up 16-bit unsigned indexes into string tables. In theory there
Brian Carlstrom306db812014-09-05 13:01:41 -07004585 * can be (kMaxAllocRecordStackDepth * alloc_record_max_) unique strings in
Elliott Hughes545a0642011-11-08 19:10:03 -08004586 * each table, but in practice there should be far fewer.
4587 *
4588 * The chief reason for using a string table here is to keep the size of
4589 * the DDMS message to a minimum. This is partly to make the protocol
4590 * efficient, but also because we have to form the whole thing up all at
4591 * once in a memory buffer.
4592 *
4593 * We use separate string tables for class names, method names, and source
4594 * files to keep the indexes small. There will generally be no overlap
4595 * between the contents of these tables.
4596 */
4597jbyteArray Dbg::GetRecentAllocations() {
4598 if (false) {
4599 DumpRecentAllocations();
4600 }
4601
Ian Rogers50b35e22012-10-04 10:09:15 -07004602 Thread* self = Thread::Current();
Elliott Hughes545a0642011-11-08 19:10:03 -08004603 std::vector<uint8_t> bytes;
Mathieu Chartier46e811b2013-07-10 17:09:14 -07004604 {
Brian Carlstrom306db812014-09-05 13:01:41 -07004605 MutexLock mu(self, *Locks::alloc_tracker_lock_);
Mathieu Chartier46e811b2013-07-10 17:09:14 -07004606 //
4607 // Part 1: generate string tables.
4608 //
4609 StringTable class_names;
4610 StringTable method_names;
4611 StringTable filenames;
Elliott Hughes545a0642011-11-08 19:10:03 -08004612
Brian Carlstrom306db812014-09-05 13:01:41 -07004613 const uint16_t capped_count = CappedAllocRecordCount(Dbg::alloc_record_count_);
4614 uint16_t count = capped_count;
4615 size_t idx = HeadIndex();
Mathieu Chartier46e811b2013-07-10 17:09:14 -07004616 while (count--) {
4617 AllocRecord* record = &recent_allocation_records_[idx];
Ian Rogers1ff3c982014-08-12 02:30:58 -07004618 std::string temp;
4619 class_names.Add(record->Type()->GetDescriptor(&temp));
Mathieu Chartier46e811b2013-07-10 17:09:14 -07004620 for (size_t i = 0; i < kMaxAllocRecordStackDepth; i++) {
Hiroshi Yamauchib5a9e3d2014-06-09 12:11:20 -07004621 mirror::ArtMethod* m = record->StackElement(i)->Method();
Ian Rogersc0542af2014-09-03 16:16:56 -07004622 if (m != nullptr) {
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07004623 class_names.Add(m->GetDeclaringClassDescriptor());
4624 method_names.Add(m->GetName());
4625 filenames.Add(GetMethodSourceFile(m));
Mathieu Chartier46e811b2013-07-10 17:09:14 -07004626 }
4627 }
Elliott Hughes545a0642011-11-08 19:10:03 -08004628
Ian Rogers719d1a32014-03-06 12:13:39 -08004629 idx = (idx + 1) & (alloc_record_max_ - 1);
Elliott Hughes545a0642011-11-08 19:10:03 -08004630 }
4631
Brian Carlstrom306db812014-09-05 13:01:41 -07004632 LOG(INFO) << "allocation records: " << capped_count;
Mathieu Chartier46e811b2013-07-10 17:09:14 -07004633
4634 //
4635 // Part 2: Generate the output and store it in the buffer.
4636 //
4637
4638 // (1b) message header len (to allow future expansion); includes itself
4639 // (1b) entry header len
4640 // (1b) stack frame len
4641 const int kMessageHeaderLen = 15;
4642 const int kEntryHeaderLen = 9;
4643 const int kStackFrameLen = 8;
4644 JDWP::Append1BE(bytes, kMessageHeaderLen);
4645 JDWP::Append1BE(bytes, kEntryHeaderLen);
4646 JDWP::Append1BE(bytes, kStackFrameLen);
4647
4648 // (2b) number of entries
4649 // (4b) offset to string table from start of message
4650 // (2b) number of class name strings
4651 // (2b) number of method name strings
4652 // (2b) number of source file name strings
Brian Carlstrom306db812014-09-05 13:01:41 -07004653 JDWP::Append2BE(bytes, capped_count);
Mathieu Chartier46e811b2013-07-10 17:09:14 -07004654 size_t string_table_offset = bytes.size();
Brian Carlstrom7934ac22013-07-26 10:54:15 -07004655 JDWP::Append4BE(bytes, 0); // We'll patch this later...
Mathieu Chartier46e811b2013-07-10 17:09:14 -07004656 JDWP::Append2BE(bytes, class_names.Size());
4657 JDWP::Append2BE(bytes, method_names.Size());
4658 JDWP::Append2BE(bytes, filenames.Size());
4659
Mathieu Chartier46e811b2013-07-10 17:09:14 -07004660 idx = HeadIndex();
Ian Rogers1ff3c982014-08-12 02:30:58 -07004661 std::string temp;
Brian Carlstrom306db812014-09-05 13:01:41 -07004662 for (count = capped_count; count != 0; --count) {
Mathieu Chartier46e811b2013-07-10 17:09:14 -07004663 // For each entry:
4664 // (4b) total allocation size
4665 // (2b) thread id
4666 // (2b) allocated object's class name index
4667 // (1b) stack depth
4668 AllocRecord* record = &recent_allocation_records_[idx];
4669 size_t stack_depth = record->GetDepth();
Mathieu Chartierf8322842014-05-16 10:59:25 -07004670 size_t allocated_object_class_name_index =
Ian Rogers1ff3c982014-08-12 02:30:58 -07004671 class_names.IndexOf(record->Type()->GetDescriptor(&temp));
Hiroshi Yamauchib5a9e3d2014-06-09 12:11:20 -07004672 JDWP::Append4BE(bytes, record->ByteCount());
4673 JDWP::Append2BE(bytes, record->ThinLockId());
Mathieu Chartier46e811b2013-07-10 17:09:14 -07004674 JDWP::Append2BE(bytes, allocated_object_class_name_index);
4675 JDWP::Append1BE(bytes, stack_depth);
4676
Mathieu Chartier46e811b2013-07-10 17:09:14 -07004677 for (size_t stack_frame = 0; stack_frame < stack_depth; ++stack_frame) {
4678 // For each stack frame:
4679 // (2b) method's class name
4680 // (2b) method name
4681 // (2b) method source file
4682 // (2b) line number, clipped to 32767; -2 if native; -1 if no source
Hiroshi Yamauchib5a9e3d2014-06-09 12:11:20 -07004683 mirror::ArtMethod* m = record->StackElement(stack_frame)->Method();
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07004684 size_t class_name_index = class_names.IndexOf(m->GetDeclaringClassDescriptor());
4685 size_t method_name_index = method_names.IndexOf(m->GetName());
4686 size_t file_name_index = filenames.IndexOf(GetMethodSourceFile(m));
Mathieu Chartier46e811b2013-07-10 17:09:14 -07004687 JDWP::Append2BE(bytes, class_name_index);
4688 JDWP::Append2BE(bytes, method_name_index);
4689 JDWP::Append2BE(bytes, file_name_index);
Hiroshi Yamauchib5a9e3d2014-06-09 12:11:20 -07004690 JDWP::Append2BE(bytes, record->StackElement(stack_frame)->LineNumber());
Mathieu Chartier46e811b2013-07-10 17:09:14 -07004691 }
Ian Rogers719d1a32014-03-06 12:13:39 -08004692 idx = (idx + 1) & (alloc_record_max_ - 1);
Mathieu Chartier46e811b2013-07-10 17:09:14 -07004693 }
4694
4695 // (xb) class name strings
4696 // (xb) method name strings
4697 // (xb) source file strings
4698 JDWP::Set4BE(&bytes[string_table_offset], bytes.size());
4699 class_names.WriteTo(bytes);
4700 method_names.WriteTo(bytes);
4701 filenames.WriteTo(bytes);
Elliott Hughes545a0642011-11-08 19:10:03 -08004702 }
Ian Rogers50b35e22012-10-04 10:09:15 -07004703 JNIEnv* env = self->GetJniEnv();
Elliott Hughes545a0642011-11-08 19:10:03 -08004704 jbyteArray result = env->NewByteArray(bytes.size());
Ian Rogersc0542af2014-09-03 16:16:56 -07004705 if (result != nullptr) {
Elliott Hughes545a0642011-11-08 19:10:03 -08004706 env->SetByteArrayRegion(result, 0, bytes.size(), reinterpret_cast<const jbyte*>(&bytes[0]));
4707 }
4708 return result;
4709}
4710
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07004711mirror::ArtMethod* DeoptimizationRequest::Method() const {
4712 ScopedObjectAccessUnchecked soa(Thread::Current());
4713 return soa.DecodeMethod(method_);
4714}
4715
4716void DeoptimizationRequest::SetMethod(mirror::ArtMethod* m) {
4717 ScopedObjectAccessUnchecked soa(Thread::Current());
4718 method_ = soa.EncodeMethod(m);
4719}
4720
Elliott Hughes872d4ec2011-10-21 17:07:15 -07004721} // namespace art