blob: 6c374029d83bcdb3d8f44cf3a458945f51e36185 [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
Sebastien Hertzb0b0b492014-09-15 11:27:27 +02001889JDWP::JdwpError Dbg::StringToUtf8(JDWP::ObjectId string_id, std::string* str) {
Ian Rogersc0542af2014-09-03 16:16:56 -07001890 JDWP::JdwpError error;
Sebastien Hertzb0b0b492014-09-15 11:27:27 +02001891 mirror::Object* obj = gRegistry->Get<mirror::Object*>(string_id, &error);
1892 if (error != JDWP::ERR_NONE) {
1893 return error;
1894 }
1895 if (obj == nullptr) {
1896 return JDWP::ERR_INVALID_OBJECT;
1897 }
1898 {
1899 ScopedObjectAccessUnchecked soa(Thread::Current());
1900 mirror::Class* java_lang_String = soa.Decode<mirror::Class*>(WellKnownClasses::java_lang_String);
1901 if (!java_lang_String->IsAssignableFrom(obj->GetClass())) {
1902 // This isn't a string.
1903 return JDWP::ERR_INVALID_STRING;
1904 }
1905 }
1906 *str = obj->AsString()->ToModifiedUtf8();
1907 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001908}
1909
Jeff Hao579b0242013-11-18 13:16:49 -08001910void Dbg::OutputJValue(JDWP::JdwpTag tag, const JValue* return_value, JDWP::ExpandBuf* pReply) {
1911 if (IsPrimitiveTag(tag)) {
1912 expandBufAdd1(pReply, tag);
1913 if (tag == JDWP::JT_BOOLEAN || tag == JDWP::JT_BYTE) {
1914 expandBufAdd1(pReply, return_value->GetI());
1915 } else if (tag == JDWP::JT_CHAR || tag == JDWP::JT_SHORT) {
1916 expandBufAdd2BE(pReply, return_value->GetI());
1917 } else if (tag == JDWP::JT_FLOAT || tag == JDWP::JT_INT) {
1918 expandBufAdd4BE(pReply, return_value->GetI());
1919 } else if (tag == JDWP::JT_DOUBLE || tag == JDWP::JT_LONG) {
1920 expandBufAdd8BE(pReply, return_value->GetJ());
1921 } else {
1922 CHECK_EQ(tag, JDWP::JT_VOID);
1923 }
1924 } else {
Ian Rogers98379392014-02-24 16:53:16 -08001925 ScopedObjectAccessUnchecked soa(Thread::Current());
Jeff Hao579b0242013-11-18 13:16:49 -08001926 mirror::Object* value = return_value->GetL();
Ian Rogers98379392014-02-24 16:53:16 -08001927 expandBufAdd1(pReply, TagFromObject(soa, value));
Jeff Hao579b0242013-11-18 13:16:49 -08001928 expandBufAddObjectId(pReply, gRegistry->Add(value));
1929 }
1930}
1931
Ian Rogersc0542af2014-09-03 16:16:56 -07001932JDWP::JdwpError Dbg::GetThreadName(JDWP::ObjectId thread_id, std::string* name) {
jeffhaoa77f0f62012-12-05 17:19:31 -08001933 ScopedObjectAccessUnchecked soa(Thread::Current());
1934 MutexLock mu(soa.Self(), *Locks::thread_list_lock_);
Ian Rogersc0542af2014-09-03 16:16:56 -07001935 JDWP::JdwpError error;
1936 Thread* thread = DecodeThread(soa, thread_id, &error);
1937 UNUSED(thread);
Elliott Hughes221229c2013-01-08 18:17:50 -08001938 if (error != JDWP::ERR_NONE && error != JDWP::ERR_THREAD_NOT_ALIVE) {
1939 return error;
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001940 }
Elliott Hughes221229c2013-01-08 18:17:50 -08001941
1942 // We still need to report the zombie threads' names, so we can't just call Thread::GetThreadName.
Ian Rogersc0542af2014-09-03 16:16:56 -07001943 mirror::Object* thread_object = gRegistry->Get<mirror::Object*>(thread_id, &error);
1944 CHECK(thread_object != nullptr) << error;
Brian Carlstromea46f952013-07-30 01:26:50 -07001945 mirror::ArtField* java_lang_Thread_name_field =
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001946 soa.DecodeField(WellKnownClasses::java_lang_Thread_name);
1947 mirror::String* s =
1948 reinterpret_cast<mirror::String*>(java_lang_Thread_name_field->GetObject(thread_object));
Ian Rogersc0542af2014-09-03 16:16:56 -07001949 if (s != nullptr) {
1950 *name = s->ToModifiedUtf8();
Elliott Hughes221229c2013-01-08 18:17:50 -08001951 }
1952 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001953}
1954
Elliott Hughes221229c2013-01-08 18:17:50 -08001955JDWP::JdwpError Dbg::GetThreadGroup(JDWP::ObjectId thread_id, JDWP::ExpandBuf* pReply) {
Sebastien Hertza06430c2014-09-15 19:21:30 +02001956 ScopedObjectAccessUnchecked soa(Thread::Current());
Ian Rogersc0542af2014-09-03 16:16:56 -07001957 JDWP::JdwpError error;
1958 mirror::Object* thread_object = gRegistry->Get<mirror::Object*>(thread_id, &error);
1959 if (error != JDWP::ERR_NONE) {
Elliott Hughes2435a572012-02-17 16:07:41 -08001960 return JDWP::ERR_INVALID_OBJECT;
1961 }
Ian Rogers98379392014-02-24 16:53:16 -08001962 const char* old_cause = soa.Self()->StartAssertNoThreadSuspension("Debugger: GetThreadGroup");
Elliott Hughes2435a572012-02-17 16:07:41 -08001963 // Okay, so it's an object, but is it actually a thread?
Hiroshi Yamauchib5a9e3d2014-06-09 12:11:20 -07001964 {
1965 MutexLock mu(soa.Self(), *Locks::thread_list_lock_);
Ian Rogersc0542af2014-09-03 16:16:56 -07001966 Thread* thread = DecodeThread(soa, thread_id, &error);
1967 UNUSED(thread);
Hiroshi Yamauchib5a9e3d2014-06-09 12:11:20 -07001968 }
Elliott Hughes221229c2013-01-08 18:17:50 -08001969 if (error == JDWP::ERR_THREAD_NOT_ALIVE) {
1970 // Zombie threads are in the null group.
1971 expandBufAddObjectId(pReply, JDWP::ObjectId(0));
Sebastien Hertz52d131d2014-03-13 16:17:40 +01001972 error = JDWP::ERR_NONE;
1973 } else if (error == JDWP::ERR_NONE) {
1974 mirror::Class* c = soa.Decode<mirror::Class*>(WellKnownClasses::java_lang_Thread);
1975 CHECK(c != nullptr);
1976 mirror::ArtField* f = c->FindInstanceField("group", "Ljava/lang/ThreadGroup;");
Hiroshi Yamauchib5a9e3d2014-06-09 12:11:20 -07001977 CHECK(f != nullptr);
Sebastien Hertz52d131d2014-03-13 16:17:40 +01001978 mirror::Object* group = f->GetObject(thread_object);
Hiroshi Yamauchib5a9e3d2014-06-09 12:11:20 -07001979 CHECK(group != nullptr);
Sebastien Hertz52d131d2014-03-13 16:17:40 +01001980 JDWP::ObjectId thread_group_id = gRegistry->Add(group);
1981 expandBufAddObjectId(pReply, thread_group_id);
Elliott Hughes221229c2013-01-08 18:17:50 -08001982 }
Ian Rogers98379392014-02-24 16:53:16 -08001983 soa.Self()->EndAssertNoThreadSuspension(old_cause);
Sebastien Hertz52d131d2014-03-13 16:17:40 +01001984 return error;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001985}
1986
Sebastien Hertza06430c2014-09-15 19:21:30 +02001987static mirror::Object* DecodeThreadGroup(ScopedObjectAccessUnchecked& soa,
1988 JDWP::ObjectId thread_group_id, JDWP::JdwpError* error)
1989 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
1990 mirror::Object* thread_group = gRegistry->Get<mirror::Object*>(thread_group_id, error);
1991 if (*error != JDWP::ERR_NONE) {
1992 return nullptr;
1993 }
1994 if (thread_group == nullptr) {
1995 *error = JDWP::ERR_INVALID_OBJECT;
1996 return nullptr;
1997 }
Ian Rogers98379392014-02-24 16:53:16 -08001998 mirror::Class* c = soa.Decode<mirror::Class*>(WellKnownClasses::java_lang_ThreadGroup);
1999 CHECK(c != nullptr);
Sebastien Hertza06430c2014-09-15 19:21:30 +02002000 if (!c->IsAssignableFrom(thread_group->GetClass())) {
2001 // This is not a java.lang.ThreadGroup.
2002 *error = JDWP::ERR_INVALID_THREAD_GROUP;
2003 return nullptr;
2004 }
2005 *error = JDWP::ERR_NONE;
2006 return thread_group;
2007}
2008
2009JDWP::JdwpError Dbg::GetThreadGroupName(JDWP::ObjectId thread_group_id, JDWP::ExpandBuf* pReply) {
2010 ScopedObjectAccessUnchecked soa(Thread::Current());
2011 JDWP::JdwpError error;
2012 mirror::Object* thread_group = DecodeThreadGroup(soa, thread_group_id, &error);
2013 if (error != JDWP::ERR_NONE) {
2014 return error;
2015 }
2016 const char* old_cause = soa.Self()->StartAssertNoThreadSuspension("Debugger: GetThreadGroupName");
2017 mirror::Class* c = soa.Decode<mirror::Class*>(WellKnownClasses::java_lang_ThreadGroup);
Brian Carlstromea46f952013-07-30 01:26:50 -07002018 mirror::ArtField* f = c->FindInstanceField("name", "Ljava/lang/String;");
Ian Rogersc0542af2014-09-03 16:16:56 -07002019 CHECK(f != nullptr);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002020 mirror::String* s = reinterpret_cast<mirror::String*>(f->GetObject(thread_group));
Ian Rogers98379392014-02-24 16:53:16 -08002021 soa.Self()->EndAssertNoThreadSuspension(old_cause);
Sebastien Hertza06430c2014-09-15 19:21:30 +02002022
2023 std::string thread_group_name(s->ToModifiedUtf8());
2024 expandBufAddUtf8String(pReply, thread_group_name);
2025 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002026}
2027
Sebastien Hertza06430c2014-09-15 19:21:30 +02002028JDWP::JdwpError Dbg::GetThreadGroupParent(JDWP::ObjectId thread_group_id, JDWP::ExpandBuf* pReply) {
Ian Rogers98379392014-02-24 16:53:16 -08002029 ScopedObjectAccessUnchecked soa(Thread::Current());
Ian Rogersc0542af2014-09-03 16:16:56 -07002030 JDWP::JdwpError error;
Sebastien Hertza06430c2014-09-15 19:21:30 +02002031 mirror::Object* thread_group = DecodeThreadGroup(soa, thread_group_id, &error);
2032 if (error != JDWP::ERR_NONE) {
2033 return error;
2034 }
Ian Rogers98379392014-02-24 16:53:16 -08002035 const char* old_cause = soa.Self()->StartAssertNoThreadSuspension("Debugger: GetThreadGroupParent");
2036 mirror::Class* c = soa.Decode<mirror::Class*>(WellKnownClasses::java_lang_ThreadGroup);
2037 CHECK(c != nullptr);
Brian Carlstromea46f952013-07-30 01:26:50 -07002038 mirror::ArtField* f = c->FindInstanceField("parent", "Ljava/lang/ThreadGroup;");
Ian Rogersc0542af2014-09-03 16:16:56 -07002039 CHECK(f != nullptr);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002040 mirror::Object* parent = f->GetObject(thread_group);
Ian Rogers98379392014-02-24 16:53:16 -08002041 soa.Self()->EndAssertNoThreadSuspension(old_cause);
Sebastien Hertza06430c2014-09-15 19:21:30 +02002042
2043 JDWP::ObjectId parent_group_id = gRegistry->Add(parent);
2044 expandBufAddObjectId(pReply, parent_group_id);
2045 return JDWP::ERR_NONE;
2046}
2047
2048static void GetChildThreadGroups(ScopedObjectAccessUnchecked& soa, mirror::Object* thread_group,
2049 std::vector<JDWP::ObjectId>* child_thread_group_ids)
2050 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
2051 CHECK(thread_group != nullptr);
2052
2053 // Get the ArrayList<ThreadGroup> "groups" out of this thread group...
2054 mirror::ArtField* groups_field = thread_group->GetClass()->FindInstanceField("groups", "Ljava/util/List;");
2055 mirror::Object* groups_array_list = groups_field->GetObject(thread_group);
2056
2057 // Get the array and size out of the ArrayList<ThreadGroup>...
2058 mirror::ArtField* array_field = groups_array_list->GetClass()->FindInstanceField("array", "[Ljava/lang/Object;");
2059 mirror::ArtField* size_field = groups_array_list->GetClass()->FindInstanceField("size", "I");
2060 mirror::ObjectArray<mirror::Object>* groups_array =
2061 array_field->GetObject(groups_array_list)->AsObjectArray<mirror::Object>();
2062 const int32_t size = size_field->GetInt(groups_array_list);
2063
2064 // Copy the first 'size' elements out of the array into the result.
2065 for (int32_t i = 0; i < size; ++i) {
2066 child_thread_group_ids->push_back(gRegistry->Add(groups_array->Get(i)));
2067 }
2068}
2069
2070JDWP::JdwpError Dbg::GetThreadGroupChildren(JDWP::ObjectId thread_group_id,
2071 JDWP::ExpandBuf* pReply) {
2072 ScopedObjectAccessUnchecked soa(Thread::Current());
2073 JDWP::JdwpError error;
2074 mirror::Object* thread_group = DecodeThreadGroup(soa, thread_group_id, &error);
2075 if (error != JDWP::ERR_NONE) {
2076 return error;
2077 }
2078
2079 // Add child threads.
2080 {
2081 std::vector<JDWP::ObjectId> child_thread_ids;
2082 GetThreads(thread_group, &child_thread_ids);
2083 expandBufAdd4BE(pReply, child_thread_ids.size());
2084 for (JDWP::ObjectId child_thread_id : child_thread_ids) {
2085 expandBufAddObjectId(pReply, child_thread_id);
2086 }
2087 }
2088
2089 // Add child thread groups.
2090 {
2091 std::vector<JDWP::ObjectId> child_thread_groups_ids;
2092 GetChildThreadGroups(soa, thread_group, &child_thread_groups_ids);
2093 expandBufAdd4BE(pReply, child_thread_groups_ids.size());
2094 for (JDWP::ObjectId child_thread_group_id : child_thread_groups_ids) {
2095 expandBufAddObjectId(pReply, child_thread_group_id);
2096 }
2097 }
2098
2099 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002100}
2101
2102JDWP::ObjectId Dbg::GetSystemThreadGroupId() {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002103 ScopedObjectAccessUnchecked soa(Thread::Current());
Brian Carlstromea46f952013-07-30 01:26:50 -07002104 mirror::ArtField* f = soa.DecodeField(WellKnownClasses::java_lang_ThreadGroup_systemThreadGroup);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002105 mirror::Object* group = f->GetObject(f->GetDeclaringClass());
Ian Rogers365c1022012-06-22 15:05:28 -07002106 return gRegistry->Add(group);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002107}
2108
Jeff Hao920af3e2013-08-28 15:46:38 -07002109JDWP::JdwpThreadStatus Dbg::ToJdwpThreadStatus(ThreadState state) {
2110 switch (state) {
2111 case kBlocked:
2112 return JDWP::TS_MONITOR;
2113 case kNative:
2114 case kRunnable:
2115 case kSuspended:
2116 return JDWP::TS_RUNNING;
2117 case kSleeping:
2118 return JDWP::TS_SLEEPING;
2119 case kStarting:
2120 case kTerminated:
2121 return JDWP::TS_ZOMBIE;
2122 case kTimedWaiting:
Sebastien Hertzbae182c2013-12-17 10:42:03 +01002123 case kWaitingForCheckPointsToRun:
Jeff Hao920af3e2013-08-28 15:46:38 -07002124 case kWaitingForDebuggerSend:
2125 case kWaitingForDebuggerSuspension:
2126 case kWaitingForDebuggerToAttach:
Sebastien Hertz138dbfc2013-12-04 18:15:25 +01002127 case kWaitingForDeoptimization:
Jeff Hao920af3e2013-08-28 15:46:38 -07002128 case kWaitingForGcToComplete:
Jeff Hao920af3e2013-08-28 15:46:38 -07002129 case kWaitingForJniOnLoad:
Sebastien Hertzbae182c2013-12-17 10:42:03 +01002130 case kWaitingForMethodTracingStart:
Jeff Hao920af3e2013-08-28 15:46:38 -07002131 case kWaitingForSignalCatcherOutput:
2132 case kWaitingInMainDebuggerLoop:
2133 case kWaitingInMainSignalCatcherLoop:
2134 case kWaitingPerformingGc:
2135 case kWaiting:
2136 return JDWP::TS_WAIT;
2137 // Don't add a 'default' here so the compiler can spot incompatible enum changes.
2138 }
2139 LOG(FATAL) << "Unknown thread state: " << state;
2140 return JDWP::TS_ZOMBIE;
2141}
2142
Sebastien Hertz52d131d2014-03-13 16:17:40 +01002143JDWP::JdwpError Dbg::GetThreadStatus(JDWP::ObjectId thread_id, JDWP::JdwpThreadStatus* pThreadStatus,
2144 JDWP::JdwpSuspendStatus* pSuspendStatus) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002145 ScopedObjectAccess soa(Thread::Current());
Elliott Hughes499c5132011-11-17 14:55:11 -08002146
Elliott Hughes9e0c1752013-01-09 14:02:58 -08002147 *pSuspendStatus = JDWP::SUSPEND_STATUS_NOT_SUSPENDED;
2148
Ian Rogers50b35e22012-10-04 10:09:15 -07002149 MutexLock mu(soa.Self(), *Locks::thread_list_lock_);
Ian Rogersc0542af2014-09-03 16:16:56 -07002150 JDWP::JdwpError error;
2151 Thread* thread = DecodeThread(soa, thread_id, &error);
Elliott Hughes221229c2013-01-08 18:17:50 -08002152 if (error != JDWP::ERR_NONE) {
2153 if (error == JDWP::ERR_THREAD_NOT_ALIVE) {
2154 *pThreadStatus = JDWP::TS_ZOMBIE;
Elliott Hughes221229c2013-01-08 18:17:50 -08002155 return JDWP::ERR_NONE;
2156 }
2157 return error;
Elliott Hughes499c5132011-11-17 14:55:11 -08002158 }
2159
Elliott Hughes9e0c1752013-01-09 14:02:58 -08002160 if (IsSuspendedForDebugger(soa, thread)) {
2161 *pSuspendStatus = JDWP::SUSPEND_STATUS_SUSPENDED;
Elliott Hughes499c5132011-11-17 14:55:11 -08002162 }
2163
Jeff Hao920af3e2013-08-28 15:46:38 -07002164 *pThreadStatus = ToJdwpThreadStatus(thread->GetState());
Elliott Hughes221229c2013-01-08 18:17:50 -08002165 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002166}
2167
Elliott Hughes221229c2013-01-08 18:17:50 -08002168JDWP::JdwpError Dbg::GetThreadDebugSuspendCount(JDWP::ObjectId thread_id, JDWP::ExpandBuf* pReply) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002169 ScopedObjectAccess soa(Thread::Current());
Ian Rogers50b35e22012-10-04 10:09:15 -07002170 MutexLock mu(soa.Self(), *Locks::thread_list_lock_);
Ian Rogersc0542af2014-09-03 16:16:56 -07002171 JDWP::JdwpError error;
2172 Thread* thread = DecodeThread(soa, thread_id, &error);
Elliott Hughes221229c2013-01-08 18:17:50 -08002173 if (error != JDWP::ERR_NONE) {
2174 return error;
Elliott Hughes2435a572012-02-17 16:07:41 -08002175 }
Ian Rogers50b35e22012-10-04 10:09:15 -07002176 MutexLock mu2(soa.Self(), *Locks::thread_suspend_count_lock_);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002177 expandBufAdd4BE(pReply, thread->GetDebugSuspendCount());
Elliott Hughes2435a572012-02-17 16:07:41 -08002178 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002179}
2180
Elliott Hughesf9501702013-01-11 11:22:27 -08002181JDWP::JdwpError Dbg::Interrupt(JDWP::ObjectId thread_id) {
2182 ScopedObjectAccess soa(Thread::Current());
2183 MutexLock mu(soa.Self(), *Locks::thread_list_lock_);
Ian Rogersc0542af2014-09-03 16:16:56 -07002184 JDWP::JdwpError error;
2185 Thread* thread = DecodeThread(soa, thread_id, &error);
Elliott Hughesf9501702013-01-11 11:22:27 -08002186 if (error != JDWP::ERR_NONE) {
2187 return error;
2188 }
Ian Rogersdd7624d2014-03-14 17:43:00 -07002189 thread->Interrupt(soa.Self());
Elliott Hughesf9501702013-01-11 11:22:27 -08002190 return JDWP::ERR_NONE;
2191}
2192
Sebastien Hertz070f7322014-09-09 12:08:49 +02002193static bool IsInDesiredThreadGroup(ScopedObjectAccessUnchecked& soa,
2194 mirror::Object* desired_thread_group, mirror::Object* peer)
2195 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
2196 // Do we want threads from all thread groups?
2197 if (desired_thread_group == nullptr) {
2198 return true;
2199 }
2200 mirror::ArtField* thread_group_field = soa.DecodeField(WellKnownClasses::java_lang_Thread_group);
2201 DCHECK(thread_group_field != nullptr);
2202 mirror::Object* group = thread_group_field->GetObject(peer);
2203 return (group == desired_thread_group);
2204}
2205
Sebastien Hertza06430c2014-09-15 19:21:30 +02002206void Dbg::GetThreads(mirror::Object* thread_group, std::vector<JDWP::ObjectId>* thread_ids) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002207 ScopedObjectAccessUnchecked soa(Thread::Current());
Sebastien Hertz070f7322014-09-09 12:08:49 +02002208 std::list<Thread*> all_threads_list;
2209 {
2210 MutexLock mu(Thread::Current(), *Locks::thread_list_lock_);
2211 all_threads_list = Runtime::Current()->GetThreadList()->GetList();
2212 }
2213 for (Thread* t : all_threads_list) {
2214 if (t == Dbg::GetDebugThread()) {
2215 // Skip the JDWP thread. Some debuggers get bent out of shape when they can't suspend and
2216 // query all threads, so it's easier if we just don't tell them about this thread.
2217 continue;
2218 }
2219 if (t->IsStillStarting()) {
2220 // This thread is being started (and has been registered in the thread list). However, it is
2221 // not completely started yet so we must ignore it.
2222 continue;
2223 }
2224 mirror::Object* peer = t->GetPeer();
2225 if (peer == nullptr) {
2226 // peer might be NULL if the thread is still starting up. We can't tell the debugger about
2227 // this thread yet.
2228 // TODO: if we identified threads to the debugger by their Thread*
2229 // rather than their peer's mirror::Object*, we could fix this.
2230 // Doing so might help us report ZOMBIE threads too.
2231 continue;
2232 }
2233 if (IsInDesiredThreadGroup(soa, thread_group, peer)) {
2234 thread_ids->push_back(gRegistry->Add(peer));
2235 }
2236 }
Elliott Hughescaf76542012-06-28 16:08:22 -07002237}
Elliott Hughesa2155262011-11-16 16:26:58 -08002238
Ian Rogersc0542af2014-09-03 16:16:56 -07002239static int GetStackDepth(Thread* thread) SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Ian Rogers0399dde2012-06-06 17:09:28 -07002240 struct CountStackDepthVisitor : public StackVisitor {
Brian Carlstrom93ba8932013-07-17 21:31:49 -07002241 explicit CountStackDepthVisitor(Thread* thread)
Ian Rogersc0542af2014-09-03 16:16:56 -07002242 : StackVisitor(thread, nullptr), depth(0) {}
Ian Rogers0399dde2012-06-06 17:09:28 -07002243
Elliott Hughes64f574f2013-02-20 14:57:12 -08002244 // TODO: Enable annotalysis. We know lock is held in constructor, but abstraction confuses
2245 // annotalysis.
2246 bool VisitFrame() NO_THREAD_SAFETY_ANALYSIS {
Ian Rogers0399dde2012-06-06 17:09:28 -07002247 if (!GetMethod()->IsRuntimeMethod()) {
Elliott Hughesf8a2df72011-12-01 12:19:54 -08002248 ++depth;
2249 }
Elliott Hughes530fa002012-03-12 11:44:49 -07002250 return true;
Elliott Hughesa2e54f62011-11-17 13:01:30 -08002251 }
2252 size_t depth;
2253 };
Elliott Hughes08fc03a2012-06-26 17:34:00 -07002254
Ian Rogers7a22fa62013-01-23 12:16:16 -08002255 CountStackDepthVisitor visitor(thread);
Ian Rogers0399dde2012-06-06 17:09:28 -07002256 visitor.WalkStack();
Elliott Hughesa2e54f62011-11-17 13:01:30 -08002257 return visitor.depth;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002258}
2259
Ian Rogersc0542af2014-09-03 16:16:56 -07002260JDWP::JdwpError Dbg::GetThreadFrameCount(JDWP::ObjectId thread_id, size_t* result) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002261 ScopedObjectAccess soa(Thread::Current());
jeffhaoa77f0f62012-12-05 17:19:31 -08002262 MutexLock mu(soa.Self(), *Locks::thread_list_lock_);
Ian Rogersc0542af2014-09-03 16:16:56 -07002263 JDWP::JdwpError error;
2264 *result = 0;
2265 Thread* thread = DecodeThread(soa, thread_id, &error);
Elliott Hughes221229c2013-01-08 18:17:50 -08002266 if (error != JDWP::ERR_NONE) {
2267 return error;
2268 }
Elliott Hughesf15f4a02013-01-09 10:09:38 -08002269 if (!IsSuspendedForDebugger(soa, thread)) {
2270 return JDWP::ERR_THREAD_NOT_SUSPENDED;
2271 }
Ian Rogersc0542af2014-09-03 16:16:56 -07002272 *result = GetStackDepth(thread);
Elliott Hughes221229c2013-01-08 18:17:50 -08002273 return JDWP::ERR_NONE;
Elliott Hughes86964332012-02-15 19:37:42 -08002274}
2275
Ian Rogers306057f2012-11-26 12:45:53 -08002276JDWP::JdwpError Dbg::GetThreadFrames(JDWP::ObjectId thread_id, size_t start_frame,
2277 size_t frame_count, JDWP::ExpandBuf* buf) {
Elliott Hughes6e9d22c2012-06-22 15:02:37 -07002278 class GetFrameVisitor : public StackVisitor {
2279 public:
Ian Rogers7a22fa62013-01-23 12:16:16 -08002280 GetFrameVisitor(Thread* thread, size_t start_frame, size_t frame_count, JDWP::ExpandBuf* buf)
Ian Rogersb726dcb2012-09-05 08:57:23 -07002281 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_)
Ian Rogersc0542af2014-09-03 16:16:56 -07002282 : StackVisitor(thread, nullptr), depth_(0),
Elliott Hughes6e9d22c2012-06-22 15:02:37 -07002283 start_frame_(start_frame), frame_count_(frame_count), buf_(buf) {
2284 expandBufAdd4BE(buf_, frame_count_);
Elliott Hughes03181a82011-11-17 17:22:21 -08002285 }
Ian Rogers0399dde2012-06-06 17:09:28 -07002286
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002287 // TODO: Enable annotalysis. We know lock is held in constructor, but abstraction confuses
2288 // annotalysis.
2289 virtual bool VisitFrame() NO_THREAD_SAFETY_ANALYSIS {
Ian Rogers0399dde2012-06-06 17:09:28 -07002290 if (GetMethod()->IsRuntimeMethod()) {
Brian Carlstrom7934ac22013-07-26 10:54:15 -07002291 return true; // The debugger can't do anything useful with a frame that has no Method*.
Elliott Hughes03181a82011-11-17 17:22:21 -08002292 }
Elliott Hughes6e9d22c2012-06-22 15:02:37 -07002293 if (depth_ >= start_frame_ + frame_count_) {
Elliott Hughes530fa002012-03-12 11:44:49 -07002294 return false;
Elliott Hughes03181a82011-11-17 17:22:21 -08002295 }
Elliott Hughes6e9d22c2012-06-22 15:02:37 -07002296 if (depth_ >= start_frame_) {
2297 JDWP::FrameId frame_id(GetFrameId());
2298 JDWP::JdwpLocation location;
Ian Rogersc0542af2014-09-03 16:16:56 -07002299 SetLocation(&location, GetMethod(), GetDexPc());
Ian Rogersef7d42f2014-01-06 12:55:46 -08002300 VLOG(jdwp) << StringPrintf(" Frame %3zd: id=%3" PRIu64 " ", depth_, frame_id) << location;
Elliott Hughes6e9d22c2012-06-22 15:02:37 -07002301 expandBufAdd8BE(buf_, frame_id);
2302 expandBufAddLocation(buf_, location);
2303 }
2304 ++depth_;
Elliott Hughes530fa002012-03-12 11:44:49 -07002305 return true;
Elliott Hughes03181a82011-11-17 17:22:21 -08002306 }
Elliott Hughes6e9d22c2012-06-22 15:02:37 -07002307
2308 private:
2309 size_t depth_;
2310 const size_t start_frame_;
2311 const size_t frame_count_;
2312 JDWP::ExpandBuf* buf_;
Elliott Hughes03181a82011-11-17 17:22:21 -08002313 };
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002314
2315 ScopedObjectAccessUnchecked soa(Thread::Current());
jeffhaoa77f0f62012-12-05 17:19:31 -08002316 MutexLock mu(soa.Self(), *Locks::thread_list_lock_);
Ian Rogersc0542af2014-09-03 16:16:56 -07002317 JDWP::JdwpError error;
2318 Thread* thread = DecodeThread(soa, thread_id, &error);
Elliott Hughes221229c2013-01-08 18:17:50 -08002319 if (error != JDWP::ERR_NONE) {
2320 return error;
2321 }
Elliott Hughesf15f4a02013-01-09 10:09:38 -08002322 if (!IsSuspendedForDebugger(soa, thread)) {
2323 return JDWP::ERR_THREAD_NOT_SUSPENDED;
2324 }
Ian Rogers7a22fa62013-01-23 12:16:16 -08002325 GetFrameVisitor visitor(thread, start_frame, frame_count, buf);
Ian Rogers0399dde2012-06-06 17:09:28 -07002326 visitor.WalkStack();
Elliott Hughes6e9d22c2012-06-22 15:02:37 -07002327 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002328}
2329
2330JDWP::ObjectId Dbg::GetThreadSelfId() {
Mathieu Chartierdbe6f462012-09-25 16:54:50 -07002331 ScopedObjectAccessUnchecked soa(Thread::Current());
Ian Rogerscfaa4552012-11-26 21:00:08 -08002332 return gRegistry->Add(soa.Self()->GetPeer());
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002333}
2334
Elliott Hughes475fc232011-10-25 15:00:35 -07002335void Dbg::SuspendVM() {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002336 Runtime::Current()->GetThreadList()->SuspendAllForDebugger();
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002337}
2338
2339void Dbg::ResumeVM() {
Elliott Hughesc61a2672012-06-21 14:52:29 -07002340 Runtime::Current()->GetThreadList()->UndoDebuggerSuspensions();
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002341}
2342
Elliott Hughes221229c2013-01-08 18:17:50 -08002343JDWP::JdwpError Dbg::SuspendThread(JDWP::ObjectId thread_id, bool request_suspension) {
Ian Rogersf3d874c2014-07-17 18:52:42 -07002344 Thread* self = Thread::Current();
Ian Rogersc0542af2014-09-03 16:16:56 -07002345 ScopedLocalRef<jobject> peer(self->GetJniEnv(), nullptr);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002346 {
Ian Rogersf3d874c2014-07-17 18:52:42 -07002347 ScopedObjectAccess soa(self);
Ian Rogersc0542af2014-09-03 16:16:56 -07002348 JDWP::JdwpError error;
2349 peer.reset(soa.AddLocalReference<jobject>(gRegistry->Get<mirror::Object*>(thread_id, &error)));
Elliott Hughes4e235312011-12-02 11:34:15 -08002350 }
Ian Rogersc0542af2014-09-03 16:16:56 -07002351 if (peer.get() == nullptr) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002352 return JDWP::ERR_THREAD_NOT_ALIVE;
2353 }
Ian Rogersf3d874c2014-07-17 18:52:42 -07002354 // Suspend thread to build stack trace. Take suspend thread lock to avoid races with threads
2355 // trying to suspend this one.
2356 MutexLock mu(self, *Locks::thread_list_suspend_thread_lock_);
Elliott Hughesf327e072013-01-09 16:01:26 -08002357 bool timed_out;
Brian Carlstromba32de42014-08-27 23:43:46 -07002358 ThreadList* thread_list = Runtime::Current()->GetThreadList();
2359 Thread* thread = thread_list->SuspendThreadByPeer(peer.get(), request_suspension, true,
2360 &timed_out);
Ian Rogersc0542af2014-09-03 16:16:56 -07002361 if (thread != nullptr) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002362 return JDWP::ERR_NONE;
Elliott Hughesf327e072013-01-09 16:01:26 -08002363 } else if (timed_out) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002364 return JDWP::ERR_INTERNAL;
2365 } else {
2366 return JDWP::ERR_THREAD_NOT_ALIVE;
2367 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002368}
2369
Elliott Hughes221229c2013-01-08 18:17:50 -08002370void Dbg::ResumeThread(JDWP::ObjectId thread_id) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002371 ScopedObjectAccessUnchecked soa(Thread::Current());
Ian Rogersc0542af2014-09-03 16:16:56 -07002372 JDWP::JdwpError error;
2373 mirror::Object* peer = gRegistry->Get<mirror::Object*>(thread_id, &error);
2374 CHECK(peer != nullptr) << error;
jeffhaoa77f0f62012-12-05 17:19:31 -08002375 Thread* thread;
2376 {
2377 MutexLock mu(soa.Self(), *Locks::thread_list_lock_);
2378 thread = Thread::FromManagedThread(soa, peer);
2379 }
Ian Rogersc0542af2014-09-03 16:16:56 -07002380 if (thread == nullptr) {
Elliott Hughes4e235312011-12-02 11:34:15 -08002381 LOG(WARNING) << "No such thread for resume: " << peer;
2382 return;
2383 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002384 bool needs_resume;
2385 {
Ian Rogers50b35e22012-10-04 10:09:15 -07002386 MutexLock mu2(soa.Self(), *Locks::thread_suspend_count_lock_);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002387 needs_resume = thread->GetSuspendCount() > 0;
2388 }
2389 if (needs_resume) {
Elliott Hughes546b9862012-06-20 16:06:13 -07002390 Runtime::Current()->GetThreadList()->Resume(thread, true);
2391 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002392}
2393
2394void Dbg::SuspendSelf() {
Elliott Hughes475fc232011-10-25 15:00:35 -07002395 Runtime::Current()->GetThreadList()->SuspendSelfForDebugger();
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002396}
2397
Ian Rogers0399dde2012-06-06 17:09:28 -07002398struct GetThisVisitor : public StackVisitor {
Ian Rogers7a22fa62013-01-23 12:16:16 -08002399 GetThisVisitor(Thread* thread, Context* context, JDWP::FrameId frame_id)
Ian Rogersb726dcb2012-09-05 08:57:23 -07002400 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_)
Ian Rogersc0542af2014-09-03 16:16:56 -07002401 : StackVisitor(thread, context), this_object(nullptr), frame_id(frame_id) {}
Ian Rogers0399dde2012-06-06 17:09:28 -07002402
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002403 // TODO: Enable annotalysis. We know lock is held in constructor, but abstraction confuses
2404 // annotalysis.
2405 virtual bool VisitFrame() NO_THREAD_SAFETY_ANALYSIS {
Elliott Hughes6e9d22c2012-06-22 15:02:37 -07002406 if (frame_id != GetFrameId()) {
Ian Rogers0399dde2012-06-06 17:09:28 -07002407 return true; // continue
Ian Rogers0399dde2012-06-06 17:09:28 -07002408 } else {
Ian Rogers62d6c772013-02-27 08:32:07 -08002409 this_object = GetThisObject();
2410 return false;
Ian Rogers0399dde2012-06-06 17:09:28 -07002411 }
Elliott Hughes86b00102011-12-05 17:54:26 -08002412 }
Ian Rogers0399dde2012-06-06 17:09:28 -07002413
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002414 mirror::Object* this_object;
Elliott Hughes6e9d22c2012-06-22 15:02:37 -07002415 JDWP::FrameId frame_id;
Ian Rogers0399dde2012-06-06 17:09:28 -07002416};
2417
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002418JDWP::JdwpError Dbg::GetThisObject(JDWP::ObjectId thread_id, JDWP::FrameId frame_id,
2419 JDWP::ObjectId* result) {
2420 ScopedObjectAccessUnchecked soa(Thread::Current());
2421 Thread* thread;
2422 {
Ian Rogers50b35e22012-10-04 10:09:15 -07002423 MutexLock mu(soa.Self(), *Locks::thread_list_lock_);
Ian Rogersc0542af2014-09-03 16:16:56 -07002424 JDWP::JdwpError error;
2425 thread = DecodeThread(soa, thread_id, &error);
Elliott Hughes221229c2013-01-08 18:17:50 -08002426 if (error != JDWP::ERR_NONE) {
2427 return error;
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002428 }
Elliott Hughes9e0c1752013-01-09 14:02:58 -08002429 if (!IsSuspendedForDebugger(soa, thread)) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002430 return JDWP::ERR_THREAD_NOT_SUSPENDED;
2431 }
Elliott Hughes6e9d22c2012-06-22 15:02:37 -07002432 }
Ian Rogers700a4022014-05-19 16:49:03 -07002433 std::unique_ptr<Context> context(Context::Create());
Ian Rogers7a22fa62013-01-23 12:16:16 -08002434 GetThisVisitor visitor(thread, context.get(), frame_id);
Ian Rogers0399dde2012-06-06 17:09:28 -07002435 visitor.WalkStack();
Elliott Hughes6e9d22c2012-06-22 15:02:37 -07002436 *result = gRegistry->Add(visitor.this_object);
2437 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002438}
2439
Sebastien Hertzcb19ebf2014-03-11 15:26:35 +01002440JDWP::JdwpError Dbg::GetLocalValue(JDWP::ObjectId thread_id, JDWP::FrameId frame_id, int slot,
2441 JDWP::JdwpTag tag, uint8_t* buf, size_t width) {
Ian Rogers0399dde2012-06-06 17:09:28 -07002442 struct GetLocalVisitor : public StackVisitor {
Ian Rogers98379392014-02-24 16:53:16 -08002443 GetLocalVisitor(const ScopedObjectAccessUnchecked& soa, Thread* thread, Context* context,
2444 JDWP::FrameId frame_id, int slot, JDWP::JdwpTag tag, uint8_t* buf, size_t width)
Ian Rogersb726dcb2012-09-05 08:57:23 -07002445 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_)
Ian Rogers98379392014-02-24 16:53:16 -08002446 : StackVisitor(thread, context), soa_(soa), frame_id_(frame_id), slot_(slot), tag_(tag),
Sebastien Hertzcb19ebf2014-03-11 15:26:35 +01002447 buf_(buf), width_(width), error_(JDWP::ERR_NONE) {}
Ian Rogersca190662012-06-26 15:45:57 -07002448
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002449 // TODO: Enable annotalysis. We know lock is held in constructor, but abstraction confuses
2450 // annotalysis.
2451 bool VisitFrame() NO_THREAD_SAFETY_ANALYSIS {
Ian Rogers0399dde2012-06-06 17:09:28 -07002452 if (GetFrameId() != frame_id_) {
2453 return true; // Not our frame, carry on.
Elliott Hughesdbb40792011-11-18 17:05:22 -08002454 }
Ian Rogers0399dde2012-06-06 17:09:28 -07002455 // TODO: check that the tag is compatible with the actual type of the slot!
Sebastien Hertzcb19ebf2014-03-11 15:26:35 +01002456 // TODO: check slot is valid for this method or return INVALID_SLOT error.
Brian Carlstromea46f952013-07-30 01:26:50 -07002457 mirror::ArtMethod* m = GetMethod();
Sebastien Hertzcb19ebf2014-03-11 15:26:35 +01002458 if (m->IsNative()) {
2459 // We can't read local value from native method.
2460 error_ = JDWP::ERR_OPAQUE_FRAME;
2461 return false;
2462 }
Ian Rogers0399dde2012-06-06 17:09:28 -07002463 uint16_t reg = DemangleSlot(slot_, m);
Sebastien Hertz0bcb2902014-06-17 15:52:45 +02002464 constexpr JDWP::JdwpError kFailureErrorCode = JDWP::ERR_ABSENT_INFORMATION;
Ian Rogers0399dde2012-06-06 17:09:28 -07002465 switch (tag_) {
Sebastien Hertz0bcb2902014-06-17 15:52:45 +02002466 case JDWP::JT_BOOLEAN: {
Ian Rogers0399dde2012-06-06 17:09:28 -07002467 CHECK_EQ(width_, 1U);
Sebastien Hertz0bcb2902014-06-17 15:52:45 +02002468 uint32_t intVal;
2469 if (GetVReg(m, reg, kIntVReg, &intVal)) {
2470 VLOG(jdwp) << "get boolean local " << reg << " = " << intVal;
2471 JDWP::Set1(buf_+1, intVal != 0);
2472 } else {
2473 VLOG(jdwp) << "failed to get boolean local " << reg;
2474 error_ = kFailureErrorCode;
2475 }
2476 break;
Ian Rogers0399dde2012-06-06 17:09:28 -07002477 }
Sebastien Hertz0bcb2902014-06-17 15:52:45 +02002478 case JDWP::JT_BYTE: {
Ian Rogers0399dde2012-06-06 17:09:28 -07002479 CHECK_EQ(width_, 1U);
Sebastien Hertz0bcb2902014-06-17 15:52:45 +02002480 uint32_t intVal;
2481 if (GetVReg(m, reg, kIntVReg, &intVal)) {
2482 VLOG(jdwp) << "get byte local " << reg << " = " << intVal;
2483 JDWP::Set1(buf_+1, intVal);
2484 } else {
2485 VLOG(jdwp) << "failed to get byte local " << reg;
2486 error_ = kFailureErrorCode;
2487 }
2488 break;
Ian Rogers0399dde2012-06-06 17:09:28 -07002489 }
Sebastien Hertz0bcb2902014-06-17 15:52:45 +02002490 case JDWP::JT_SHORT:
2491 case JDWP::JT_CHAR: {
Ian Rogers0399dde2012-06-06 17:09:28 -07002492 CHECK_EQ(width_, 2U);
Sebastien Hertz0bcb2902014-06-17 15:52:45 +02002493 uint32_t intVal;
2494 if (GetVReg(m, reg, kIntVReg, &intVal)) {
2495 VLOG(jdwp) << "get short/char local " << reg << " = " << intVal;
2496 JDWP::Set2BE(buf_+1, intVal);
2497 } else {
2498 VLOG(jdwp) << "failed to get short/char local " << reg;
2499 error_ = kFailureErrorCode;
Sebastien Hertzaa9b3ae2014-06-13 14:49:27 +02002500 }
Sebastien Hertz0bcb2902014-06-17 15:52:45 +02002501 break;
Sebastien Hertzaa9b3ae2014-06-13 14:49:27 +02002502 }
Sebastien Hertz0bcb2902014-06-17 15:52:45 +02002503 case JDWP::JT_INT: {
2504 CHECK_EQ(width_, 4U);
2505 uint32_t intVal;
2506 if (GetVReg(m, reg, kIntVReg, &intVal)) {
2507 VLOG(jdwp) << "get int local " << reg << " = " << intVal;
2508 JDWP::Set4BE(buf_+1, intVal);
2509 } else {
2510 VLOG(jdwp) << "failed to get int local " << reg;
2511 error_ = kFailureErrorCode;
Sebastien Hertz8ebd94a2014-06-17 09:49:21 +00002512 }
Sebastien Hertz0bcb2902014-06-17 15:52:45 +02002513 break;
Sebastien Hertz8ebd94a2014-06-17 09:49:21 +00002514 }
Sebastien Hertz0bcb2902014-06-17 15:52:45 +02002515 case JDWP::JT_FLOAT: {
2516 CHECK_EQ(width_, 4U);
2517 uint32_t intVal;
2518 if (GetVReg(m, reg, kFloatVReg, &intVal)) {
2519 VLOG(jdwp) << "get float local " << reg << " = " << intVal;
2520 JDWP::Set4BE(buf_+1, intVal);
2521 } else {
2522 VLOG(jdwp) << "failed to get float local " << reg;
2523 error_ = kFailureErrorCode;
2524 }
2525 break;
2526 }
2527 case JDWP::JT_ARRAY:
2528 case JDWP::JT_CLASS_LOADER:
2529 case JDWP::JT_CLASS_OBJECT:
2530 case JDWP::JT_OBJECT:
2531 case JDWP::JT_STRING:
2532 case JDWP::JT_THREAD:
2533 case JDWP::JT_THREAD_GROUP: {
2534 CHECK_EQ(width_, sizeof(JDWP::ObjectId));
2535 uint32_t intVal;
2536 if (GetVReg(m, reg, kReferenceVReg, &intVal)) {
2537 mirror::Object* o = reinterpret_cast<mirror::Object*>(intVal);
2538 VLOG(jdwp) << "get " << tag_ << " object local " << reg << " = " << o;
2539 if (!Runtime::Current()->GetHeap()->IsValidObjectAddress(o)) {
2540 LOG(FATAL) << "Register " << reg << " expected to hold " << tag_ << " object: " << o;
2541 }
2542 tag_ = TagFromObject(soa_, o);
2543 JDWP::SetObjectId(buf_+1, gRegistry->Add(o));
2544 } else {
2545 VLOG(jdwp) << "failed to get " << tag_ << " object local " << reg;
2546 error_ = kFailureErrorCode;
2547 }
2548 break;
2549 }
2550 case JDWP::JT_DOUBLE: {
Ian Rogers2bcb4a42012-11-08 10:39:18 -08002551 CHECK_EQ(width_, 8U);
Sebastien Hertzc901dd72014-07-16 11:56:07 +02002552 uint64_t longVal;
2553 if (GetVRegPair(m, reg, kDoubleLoVReg, kDoubleHiVReg, &longVal)) {
2554 VLOG(jdwp) << "get double local " << reg << " = " << longVal;
Sebastien Hertz0bcb2902014-06-17 15:52:45 +02002555 JDWP::Set8BE(buf_+1, longVal);
2556 } else {
2557 VLOG(jdwp) << "failed to get double local " << reg;
2558 error_ = kFailureErrorCode;
2559 }
2560 break;
Ian Rogers2bcb4a42012-11-08 10:39:18 -08002561 }
Sebastien Hertz0bcb2902014-06-17 15:52:45 +02002562 case JDWP::JT_LONG: {
Ian Rogers0399dde2012-06-06 17:09:28 -07002563 CHECK_EQ(width_, 8U);
Sebastien Hertzc901dd72014-07-16 11:56:07 +02002564 uint64_t longVal;
2565 if (GetVRegPair(m, reg, kLongLoVReg, kLongHiVReg, &longVal)) {
2566 VLOG(jdwp) << "get long local " << reg << " = " << longVal;
Sebastien Hertz0bcb2902014-06-17 15:52:45 +02002567 JDWP::Set8BE(buf_+1, longVal);
2568 } else {
2569 VLOG(jdwp) << "failed to get long local " << reg;
2570 error_ = kFailureErrorCode;
2571 }
2572 break;
Ian Rogers0399dde2012-06-06 17:09:28 -07002573 }
Sebastien Hertz0bcb2902014-06-17 15:52:45 +02002574 default:
2575 LOG(FATAL) << "Unknown tag " << tag_;
2576 break;
Ian Rogers0399dde2012-06-06 17:09:28 -07002577 }
2578
2579 // Prepend tag, which may have been updated.
2580 JDWP::Set1(buf_, tag_);
2581 return false;
2582 }
Ian Rogers98379392014-02-24 16:53:16 -08002583 const ScopedObjectAccessUnchecked& soa_;
Ian Rogers0399dde2012-06-06 17:09:28 -07002584 const JDWP::FrameId frame_id_;
2585 const int slot_;
2586 JDWP::JdwpTag tag_;
2587 uint8_t* const buf_;
2588 const size_t width_;
Sebastien Hertzcb19ebf2014-03-11 15:26:35 +01002589 JDWP::JdwpError error_;
Ian Rogers0399dde2012-06-06 17:09:28 -07002590 };
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002591
2592 ScopedObjectAccessUnchecked soa(Thread::Current());
jeffhaoa77f0f62012-12-05 17:19:31 -08002593 MutexLock mu(soa.Self(), *Locks::thread_list_lock_);
Ian Rogersc0542af2014-09-03 16:16:56 -07002594 JDWP::JdwpError error;
2595 Thread* thread = DecodeThread(soa, thread_id, &error);
Elliott Hughes221229c2013-01-08 18:17:50 -08002596 if (error != JDWP::ERR_NONE) {
Sebastien Hertzcb19ebf2014-03-11 15:26:35 +01002597 return error;
Elliott Hughes221229c2013-01-08 18:17:50 -08002598 }
Sebastien Hertzcb19ebf2014-03-11 15:26:35 +01002599 // TODO check thread is suspended by the debugger ?
Ian Rogers700a4022014-05-19 16:49:03 -07002600 std::unique_ptr<Context> context(Context::Create());
Ian Rogers98379392014-02-24 16:53:16 -08002601 GetLocalVisitor visitor(soa, thread, context.get(), frame_id, slot, tag, buf, width);
Ian Rogers0399dde2012-06-06 17:09:28 -07002602 visitor.WalkStack();
Sebastien Hertzcb19ebf2014-03-11 15:26:35 +01002603 return visitor.error_;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002604}
2605
Sebastien Hertzcb19ebf2014-03-11 15:26:35 +01002606JDWP::JdwpError Dbg::SetLocalValue(JDWP::ObjectId thread_id, JDWP::FrameId frame_id, int slot,
2607 JDWP::JdwpTag tag, uint64_t value, size_t width) {
Ian Rogers0399dde2012-06-06 17:09:28 -07002608 struct SetLocalVisitor : public StackVisitor {
Ian Rogers7a22fa62013-01-23 12:16:16 -08002609 SetLocalVisitor(Thread* thread, Context* context,
Ian Rogers0399dde2012-06-06 17:09:28 -07002610 JDWP::FrameId frame_id, int slot, JDWP::JdwpTag tag, uint64_t value,
Ian Rogersca190662012-06-26 15:45:57 -07002611 size_t width)
Ian Rogersb726dcb2012-09-05 08:57:23 -07002612 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_)
Ian Rogers7a22fa62013-01-23 12:16:16 -08002613 : StackVisitor(thread, context),
Sebastien Hertzcb19ebf2014-03-11 15:26:35 +01002614 frame_id_(frame_id), slot_(slot), tag_(tag), value_(value), width_(width),
2615 error_(JDWP::ERR_NONE) {}
Ian Rogersca190662012-06-26 15:45:57 -07002616
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002617 // TODO: Enable annotalysis. We know lock is held in constructor, but abstraction confuses
2618 // annotalysis.
2619 bool VisitFrame() NO_THREAD_SAFETY_ANALYSIS {
Ian Rogers0399dde2012-06-06 17:09:28 -07002620 if (GetFrameId() != frame_id_) {
2621 return true; // Not our frame, carry on.
2622 }
2623 // TODO: check that the tag is compatible with the actual type of the slot!
Sebastien Hertzcb19ebf2014-03-11 15:26:35 +01002624 // TODO: check slot is valid for this method or return INVALID_SLOT error.
Brian Carlstromea46f952013-07-30 01:26:50 -07002625 mirror::ArtMethod* m = GetMethod();
Sebastien Hertzcb19ebf2014-03-11 15:26:35 +01002626 if (m->IsNative()) {
2627 // We can't read local value from native method.
2628 error_ = JDWP::ERR_OPAQUE_FRAME;
2629 return false;
2630 }
Ian Rogers0399dde2012-06-06 17:09:28 -07002631 uint16_t reg = DemangleSlot(slot_, m);
Sebastien Hertz0bcb2902014-06-17 15:52:45 +02002632 constexpr JDWP::JdwpError kFailureErrorCode = JDWP::ERR_ABSENT_INFORMATION;
Ian Rogers0399dde2012-06-06 17:09:28 -07002633 switch (tag_) {
2634 case JDWP::JT_BOOLEAN:
2635 case JDWP::JT_BYTE:
2636 CHECK_EQ(width_, 1U);
Sebastien Hertz0bcb2902014-06-17 15:52:45 +02002637 if (!SetVReg(m, reg, static_cast<uint32_t>(value_), kIntVReg)) {
2638 VLOG(jdwp) << "failed to set boolean/byte local " << reg << " = "
2639 << static_cast<uint32_t>(value_);
2640 error_ = kFailureErrorCode;
2641 }
Ian Rogers0399dde2012-06-06 17:09:28 -07002642 break;
2643 case JDWP::JT_SHORT:
2644 case JDWP::JT_CHAR:
2645 CHECK_EQ(width_, 2U);
Sebastien Hertz0bcb2902014-06-17 15:52:45 +02002646 if (!SetVReg(m, reg, static_cast<uint32_t>(value_), kIntVReg)) {
2647 VLOG(jdwp) << "failed to set short/char local " << reg << " = "
2648 << static_cast<uint32_t>(value_);
2649 error_ = kFailureErrorCode;
2650 }
Ian Rogers0399dde2012-06-06 17:09:28 -07002651 break;
2652 case JDWP::JT_INT:
Ian Rogers2bcb4a42012-11-08 10:39:18 -08002653 CHECK_EQ(width_, 4U);
Sebastien Hertz0bcb2902014-06-17 15:52:45 +02002654 if (!SetVReg(m, reg, static_cast<uint32_t>(value_), kIntVReg)) {
2655 VLOG(jdwp) << "failed to set int local " << reg << " = "
2656 << static_cast<uint32_t>(value_);
2657 error_ = kFailureErrorCode;
2658 }
Ian Rogers2bcb4a42012-11-08 10:39:18 -08002659 break;
Ian Rogers0399dde2012-06-06 17:09:28 -07002660 case JDWP::JT_FLOAT:
2661 CHECK_EQ(width_, 4U);
Sebastien Hertz0bcb2902014-06-17 15:52:45 +02002662 if (!SetVReg(m, reg, static_cast<uint32_t>(value_), kFloatVReg)) {
2663 VLOG(jdwp) << "failed to set float local " << reg << " = "
2664 << static_cast<uint32_t>(value_);
2665 error_ = kFailureErrorCode;
2666 }
Ian Rogers0399dde2012-06-06 17:09:28 -07002667 break;
2668 case JDWP::JT_ARRAY:
Sebastien Hertz0bcb2902014-06-17 15:52:45 +02002669 case JDWP::JT_CLASS_LOADER:
2670 case JDWP::JT_CLASS_OBJECT:
Ian Rogers0399dde2012-06-06 17:09:28 -07002671 case JDWP::JT_OBJECT:
2672 case JDWP::JT_STRING:
Sebastien Hertz0bcb2902014-06-17 15:52:45 +02002673 case JDWP::JT_THREAD:
2674 case JDWP::JT_THREAD_GROUP: {
Ian Rogers0399dde2012-06-06 17:09:28 -07002675 CHECK_EQ(width_, sizeof(JDWP::ObjectId));
Ian Rogersc0542af2014-09-03 16:16:56 -07002676 JDWP::JdwpError error;
2677 mirror::Object* o =
2678 gRegistry->Get<mirror::Object*>(static_cast<JDWP::ObjectId>(value_), &error);
2679 if (error != JDWP::ERR_NONE) {
2680 VLOG(jdwp) << tag_ << " object " << value_ << " is an invalid object";
Sebastien Hertz0bcb2902014-06-17 15:52:45 +02002681 error_ = JDWP::ERR_INVALID_OBJECT;
2682 } else if (!SetVReg(m, reg, static_cast<uint32_t>(reinterpret_cast<uintptr_t>(o)),
2683 kReferenceVReg)) {
2684 VLOG(jdwp) << "failed to set " << tag_ << " object local " << reg << " = " << o;
2685 error_ = kFailureErrorCode;
Ian Rogers0399dde2012-06-06 17:09:28 -07002686 }
Sebastien Hertz0bcb2902014-06-17 15:52:45 +02002687 break;
Ian Rogers0399dde2012-06-06 17:09:28 -07002688 }
Sebastien Hertz0bcb2902014-06-17 15:52:45 +02002689 case JDWP::JT_DOUBLE: {
Ian Rogers2bcb4a42012-11-08 10:39:18 -08002690 CHECK_EQ(width_, 8U);
Sebastien Hertzc901dd72014-07-16 11:56:07 +02002691 bool success = SetVRegPair(m, reg, value_, kDoubleLoVReg, kDoubleHiVReg);
Sebastien Hertz0bcb2902014-06-17 15:52:45 +02002692 if (!success) {
Sebastien Hertzc901dd72014-07-16 11:56:07 +02002693 VLOG(jdwp) << "failed to set double local " << reg << " = " << value_;
Sebastien Hertz0bcb2902014-06-17 15:52:45 +02002694 error_ = kFailureErrorCode;
2695 }
Ian Rogers2bcb4a42012-11-08 10:39:18 -08002696 break;
Sebastien Hertz0bcb2902014-06-17 15:52:45 +02002697 }
2698 case JDWP::JT_LONG: {
Ian Rogers0399dde2012-06-06 17:09:28 -07002699 CHECK_EQ(width_, 8U);
Sebastien Hertzc901dd72014-07-16 11:56:07 +02002700 bool success = SetVRegPair(m, reg, value_, kLongLoVReg, kLongHiVReg);
Sebastien Hertz0bcb2902014-06-17 15:52:45 +02002701 if (!success) {
Sebastien Hertzc901dd72014-07-16 11:56:07 +02002702 VLOG(jdwp) << "failed to set double local " << reg << " = " << value_;
Sebastien Hertz0bcb2902014-06-17 15:52:45 +02002703 error_ = kFailureErrorCode;
2704 }
Ian Rogers0399dde2012-06-06 17:09:28 -07002705 break;
Sebastien Hertz0bcb2902014-06-17 15:52:45 +02002706 }
Ian Rogers0399dde2012-06-06 17:09:28 -07002707 default:
2708 LOG(FATAL) << "Unknown tag " << tag_;
2709 break;
2710 }
2711 return false;
2712 }
2713
2714 const JDWP::FrameId frame_id_;
2715 const int slot_;
2716 const JDWP::JdwpTag tag_;
2717 const uint64_t value_;
2718 const size_t width_;
Sebastien Hertzcb19ebf2014-03-11 15:26:35 +01002719 JDWP::JdwpError error_;
Ian Rogers0399dde2012-06-06 17:09:28 -07002720 };
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002721
2722 ScopedObjectAccessUnchecked soa(Thread::Current());
jeffhaoa77f0f62012-12-05 17:19:31 -08002723 MutexLock mu(soa.Self(), *Locks::thread_list_lock_);
Ian Rogersc0542af2014-09-03 16:16:56 -07002724 JDWP::JdwpError error;
2725 Thread* thread = DecodeThread(soa, thread_id, &error);
Elliott Hughes221229c2013-01-08 18:17:50 -08002726 if (error != JDWP::ERR_NONE) {
Sebastien Hertzcb19ebf2014-03-11 15:26:35 +01002727 return error;
Elliott Hughes221229c2013-01-08 18:17:50 -08002728 }
Sebastien Hertzcb19ebf2014-03-11 15:26:35 +01002729 // TODO check thread is suspended by the debugger ?
Ian Rogers700a4022014-05-19 16:49:03 -07002730 std::unique_ptr<Context> context(Context::Create());
Ian Rogers7a22fa62013-01-23 12:16:16 -08002731 SetLocalVisitor visitor(thread, context.get(), frame_id, slot, tag, value, width);
Ian Rogers0399dde2012-06-06 17:09:28 -07002732 visitor.WalkStack();
Sebastien Hertzcb19ebf2014-03-11 15:26:35 +01002733 return visitor.error_;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002734}
2735
Sebastien Hertz3f52eaf2014-04-04 17:50:18 +02002736JDWP::ObjectId Dbg::GetThisObjectIdForEvent(mirror::Object* this_object) {
2737 // If 'this_object' isn't already in the registry, we know that we're not looking for it, so
2738 // there's no point adding it to the registry and burning through ids.
2739 // When registering an event request with an instance filter, we've been given an existing object
2740 // id so it must already be present in the registry when the event fires.
2741 JDWP::ObjectId this_id = 0;
2742 if (this_object != nullptr && gRegistry->Contains(this_object)) {
2743 this_id = gRegistry->Add(this_object);
2744 }
2745 return this_id;
2746}
2747
Ian Rogersef7d42f2014-01-06 12:55:46 -08002748void Dbg::PostLocationEvent(mirror::ArtMethod* m, int dex_pc, mirror::Object* this_object,
Jeff Hao579b0242013-11-18 13:16:49 -08002749 int event_flags, const JValue* return_value) {
Sebastien Hertz3f52eaf2014-04-04 17:50:18 +02002750 if (!IsDebuggerActive()) {
2751 return;
2752 }
2753 DCHECK(m != nullptr);
2754 DCHECK_EQ(m->IsStatic(), this_object == nullptr);
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08002755 JDWP::JdwpLocation location;
Ian Rogersc0542af2014-09-03 16:16:56 -07002756 SetLocation(&location, m, dex_pc);
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08002757
Sebastien Hertz3f52eaf2014-04-04 17:50:18 +02002758 // We need 'this' for InstanceOnly filters only.
2759 JDWP::ObjectId this_id = GetThisObjectIdForEvent(this_object);
Jeff Hao579b0242013-11-18 13:16:49 -08002760 gJdwpState->PostLocationEvent(&location, this_id, event_flags, return_value);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002761}
2762
Sebastien Hertz3f52eaf2014-04-04 17:50:18 +02002763void Dbg::PostFieldAccessEvent(mirror::ArtMethod* m, int dex_pc,
2764 mirror::Object* this_object, mirror::ArtField* f) {
2765 if (!IsDebuggerActive()) {
2766 return;
2767 }
2768 DCHECK(m != nullptr);
2769 DCHECK(f != nullptr);
2770 JDWP::JdwpLocation location;
Ian Rogersc0542af2014-09-03 16:16:56 -07002771 SetLocation(&location, m, dex_pc);
Sebastien Hertz3f52eaf2014-04-04 17:50:18 +02002772
2773 JDWP::RefTypeId type_id = gRegistry->AddRefType(f->GetDeclaringClass());
2774 JDWP::FieldId field_id = ToFieldId(f);
2775 JDWP::ObjectId this_id = gRegistry->Add(this_object);
2776
2777 gJdwpState->PostFieldEvent(&location, type_id, field_id, this_id, nullptr, false);
2778}
2779
2780void Dbg::PostFieldModificationEvent(mirror::ArtMethod* m, int dex_pc,
2781 mirror::Object* this_object, mirror::ArtField* f,
2782 const JValue* field_value) {
2783 if (!IsDebuggerActive()) {
2784 return;
2785 }
2786 DCHECK(m != nullptr);
2787 DCHECK(f != nullptr);
2788 DCHECK(field_value != nullptr);
2789 JDWP::JdwpLocation location;
Ian Rogersc0542af2014-09-03 16:16:56 -07002790 SetLocation(&location, m, dex_pc);
Sebastien Hertz3f52eaf2014-04-04 17:50:18 +02002791
2792 JDWP::RefTypeId type_id = gRegistry->AddRefType(f->GetDeclaringClass());
2793 JDWP::FieldId field_id = ToFieldId(f);
2794 JDWP::ObjectId this_id = gRegistry->Add(this_object);
2795
2796 gJdwpState->PostFieldEvent(&location, type_id, field_id, this_id, field_value, true);
2797}
2798
2799void Dbg::PostException(const ThrowLocation& throw_location,
Brian Carlstromea46f952013-07-30 01:26:50 -07002800 mirror::ArtMethod* catch_method,
Elliott Hughes64f574f2013-02-20 14:57:12 -08002801 uint32_t catch_dex_pc, mirror::Throwable* exception_object) {
Elliott Hughesc0f09332012-03-26 13:27:06 -07002802 if (!IsDebuggerActive()) {
Ian Rogers0ad5bb82011-12-07 10:16:32 -08002803 return;
2804 }
Elliott Hughes4740cdf2011-12-07 14:07:12 -08002805
Ian Rogers62d6c772013-02-27 08:32:07 -08002806 JDWP::JdwpLocation jdwp_throw_location;
Ian Rogersc0542af2014-09-03 16:16:56 -07002807 SetLocation(&jdwp_throw_location, throw_location.GetMethod(), throw_location.GetDexPc());
Elliott Hughesd07986f2011-12-06 18:27:45 -08002808 JDWP::JdwpLocation catch_location;
Ian Rogersc0542af2014-09-03 16:16:56 -07002809 SetLocation(&catch_location, catch_method, catch_dex_pc);
Elliott Hughesd07986f2011-12-06 18:27:45 -08002810
Sebastien Hertz3f52eaf2014-04-04 17:50:18 +02002811 // We need 'this' for InstanceOnly filters only.
2812 JDWP::ObjectId this_id = GetThisObjectIdForEvent(throw_location.GetThis());
Elliott Hughes64f574f2013-02-20 14:57:12 -08002813 JDWP::ObjectId exception_id = gRegistry->Add(exception_object);
2814 JDWP::RefTypeId exception_class_id = gRegistry->AddRefType(exception_object->GetClass());
Elliott Hughesd07986f2011-12-06 18:27:45 -08002815
Ian Rogers62d6c772013-02-27 08:32:07 -08002816 gJdwpState->PostException(&jdwp_throw_location, exception_id, exception_class_id, &catch_location,
2817 this_id);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002818}
2819
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002820void Dbg::PostClassPrepare(mirror::Class* c) {
Elliott Hughesc0f09332012-03-26 13:27:06 -07002821 if (!IsDebuggerActive()) {
Elliott Hughes4740cdf2011-12-07 14:07:12 -08002822 return;
2823 }
2824
Elliott Hughes3d30d9b2011-12-07 17:35:48 -08002825 // OLD-TODO - we currently always send both "verified" and "prepared" since
Elliott Hughes4740cdf2011-12-07 14:07:12 -08002826 // debuggers seem to like that. There might be some advantage to honesty,
2827 // since the class may not yet be verified.
2828 int state = JDWP::CS_VERIFIED | JDWP::CS_PREPARED;
Sebastien Hertz4d8fd492014-03-28 16:29:41 +01002829 JDWP::JdwpTypeTag tag = GetTypeTag(c);
Ian Rogers1ff3c982014-08-12 02:30:58 -07002830 std::string temp;
2831 gJdwpState->PostClassPrepare(tag, gRegistry->Add(c), c->GetDescriptor(&temp), state);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002832}
2833
Ian Rogers62d6c772013-02-27 08:32:07 -08002834void Dbg::UpdateDebugger(Thread* thread, mirror::Object* this_object,
Sebastien Hertz8379b222014-02-24 17:38:15 +01002835 mirror::ArtMethod* m, uint32_t dex_pc,
2836 int event_flags, const JValue* return_value) {
Ian Rogers62d6c772013-02-27 08:32:07 -08002837 if (!IsDebuggerActive() || dex_pc == static_cast<uint32_t>(-2) /* fake method exit */) {
Elliott Hughes2aa2e392012-02-17 17:15:43 -08002838 return;
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08002839 }
2840
Elliott Hughes86964332012-02-15 19:37:42 -08002841 if (IsBreakpoint(m, dex_pc)) {
2842 event_flags |= kBreakpoint;
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08002843 }
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08002844
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01002845 // If the debugger is single-stepping one of our threads, check to
2846 // see if we're that thread and we've reached a step point.
2847 const SingleStepControl* single_step_control = thread->GetSingleStepControl();
2848 DCHECK(single_step_control != nullptr);
2849 if (single_step_control->is_active) {
2850 CHECK(!m->IsNative());
2851 if (single_step_control->step_depth == JDWP::SD_INTO) {
2852 // Step into method calls. We break when the line number
2853 // or method pointer changes. If we're in SS_MIN mode, we
2854 // always stop.
2855 if (single_step_control->method != m) {
2856 event_flags |= kSingleStep;
2857 VLOG(jdwp) << "SS new method";
2858 } else if (single_step_control->step_size == JDWP::SS_MIN) {
2859 event_flags |= kSingleStep;
2860 VLOG(jdwp) << "SS new instruction";
Sebastien Hertzbb43b432014-04-14 11:59:08 +02002861 } else if (single_step_control->ContainsDexPc(dex_pc)) {
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01002862 event_flags |= kSingleStep;
2863 VLOG(jdwp) << "SS new line";
2864 }
2865 } else if (single_step_control->step_depth == JDWP::SD_OVER) {
2866 // Step over method calls. We break when the line number is
2867 // different and the frame depth is <= the original frame
2868 // depth. (We can't just compare on the method, because we
2869 // might get unrolled past it by an exception, and it's tricky
2870 // to identify recursion.)
2871
2872 int stack_depth = GetStackDepth(thread);
2873
2874 if (stack_depth < single_step_control->stack_depth) {
2875 // Popped up one or more frames, always trigger.
2876 event_flags |= kSingleStep;
2877 VLOG(jdwp) << "SS method pop";
2878 } else if (stack_depth == single_step_control->stack_depth) {
2879 // Same depth, see if we moved.
2880 if (single_step_control->step_size == JDWP::SS_MIN) {
Elliott Hughes86964332012-02-15 19:37:42 -08002881 event_flags |= kSingleStep;
2882 VLOG(jdwp) << "SS new instruction";
Sebastien Hertzbb43b432014-04-14 11:59:08 +02002883 } else if (single_step_control->ContainsDexPc(dex_pc)) {
Elliott Hughes2435a572012-02-17 16:07:41 -08002884 event_flags |= kSingleStep;
2885 VLOG(jdwp) << "SS new line";
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08002886 }
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01002887 }
2888 } else {
2889 CHECK_EQ(single_step_control->step_depth, JDWP::SD_OUT);
2890 // Return from the current method. We break when the frame
2891 // depth pops up.
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08002892
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01002893 // This differs from the "method exit" break in that it stops
2894 // with the PC at the next instruction in the returned-to
2895 // function, rather than the end of the returning function.
Elliott Hughes86964332012-02-15 19:37:42 -08002896
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01002897 int stack_depth = GetStackDepth(thread);
2898 if (stack_depth < single_step_control->stack_depth) {
2899 event_flags |= kSingleStep;
2900 VLOG(jdwp) << "SS method pop";
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08002901 }
2902 }
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08002903 }
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08002904
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08002905 // If there's something interesting going on, see if it matches one
2906 // of the debugger filters.
2907 if (event_flags != 0) {
Sebastien Hertz8379b222014-02-24 17:38:15 +01002908 Dbg::PostLocationEvent(m, dex_pc, this_object, event_flags, return_value);
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08002909 }
2910}
2911
Sebastien Hertz42cd43f2014-05-13 14:15:41 +02002912size_t* Dbg::GetReferenceCounterForEvent(uint32_t instrumentation_event) {
2913 switch (instrumentation_event) {
2914 case instrumentation::Instrumentation::kMethodEntered:
2915 return &method_enter_event_ref_count_;
2916 case instrumentation::Instrumentation::kMethodExited:
2917 return &method_exit_event_ref_count_;
2918 case instrumentation::Instrumentation::kDexPcMoved:
2919 return &dex_pc_change_event_ref_count_;
2920 case instrumentation::Instrumentation::kFieldRead:
2921 return &field_read_event_ref_count_;
2922 case instrumentation::Instrumentation::kFieldWritten:
2923 return &field_write_event_ref_count_;
2924 case instrumentation::Instrumentation::kExceptionCaught:
2925 return &exception_catch_event_ref_count_;
2926 default:
2927 return nullptr;
2928 }
2929}
2930
Sebastien Hertz4d25df32014-03-21 17:44:46 +01002931// Process request while all mutator threads are suspended.
2932void Dbg::ProcessDeoptimizationRequest(const DeoptimizationRequest& request) {
Sebastien Hertz138dbfc2013-12-04 18:15:25 +01002933 instrumentation::Instrumentation* instrumentation = Runtime::Current()->GetInstrumentation();
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07002934 switch (request.GetKind()) {
Sebastien Hertz4d25df32014-03-21 17:44:46 +01002935 case DeoptimizationRequest::kNothing:
2936 LOG(WARNING) << "Ignoring empty deoptimization request.";
2937 break;
Sebastien Hertz42cd43f2014-05-13 14:15:41 +02002938 case DeoptimizationRequest::kRegisterForEvent:
2939 VLOG(jdwp) << StringPrintf("Add debugger as listener for instrumentation event 0x%x",
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07002940 request.InstrumentationEvent());
2941 instrumentation->AddListener(&gDebugInstrumentationListener, request.InstrumentationEvent());
2942 instrumentation_events_ |= request.InstrumentationEvent();
Sebastien Hertz42cd43f2014-05-13 14:15:41 +02002943 break;
2944 case DeoptimizationRequest::kUnregisterForEvent:
2945 VLOG(jdwp) << StringPrintf("Remove debugger as listener for instrumentation event 0x%x",
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07002946 request.InstrumentationEvent());
Sebastien Hertz42cd43f2014-05-13 14:15:41 +02002947 instrumentation->RemoveListener(&gDebugInstrumentationListener,
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07002948 request.InstrumentationEvent());
2949 instrumentation_events_ &= ~request.InstrumentationEvent();
Sebastien Hertz42cd43f2014-05-13 14:15:41 +02002950 break;
Sebastien Hertz4d25df32014-03-21 17:44:46 +01002951 case DeoptimizationRequest::kFullDeoptimization:
Sebastien Hertz7ec2f1c2014-03-27 20:06:47 +01002952 VLOG(jdwp) << "Deoptimize the world ...";
Sebastien Hertz4d25df32014-03-21 17:44:46 +01002953 instrumentation->DeoptimizeEverything();
Sebastien Hertz7ec2f1c2014-03-27 20:06:47 +01002954 VLOG(jdwp) << "Deoptimize the world DONE";
Sebastien Hertz4d25df32014-03-21 17:44:46 +01002955 break;
2956 case DeoptimizationRequest::kFullUndeoptimization:
Sebastien Hertz7ec2f1c2014-03-27 20:06:47 +01002957 VLOG(jdwp) << "Undeoptimize the world ...";
Sebastien Hertz4d25df32014-03-21 17:44:46 +01002958 instrumentation->UndeoptimizeEverything();
Sebastien Hertz7ec2f1c2014-03-27 20:06:47 +01002959 VLOG(jdwp) << "Undeoptimize the world DONE";
Sebastien Hertz4d25df32014-03-21 17:44:46 +01002960 break;
2961 case DeoptimizationRequest::kSelectiveDeoptimization:
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07002962 VLOG(jdwp) << "Deoptimize method " << PrettyMethod(request.Method()) << " ...";
2963 instrumentation->Deoptimize(request.Method());
2964 VLOG(jdwp) << "Deoptimize method " << PrettyMethod(request.Method()) << " DONE";
Sebastien Hertz4d25df32014-03-21 17:44:46 +01002965 break;
2966 case DeoptimizationRequest::kSelectiveUndeoptimization:
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07002967 VLOG(jdwp) << "Undeoptimize method " << PrettyMethod(request.Method()) << " ...";
2968 instrumentation->Undeoptimize(request.Method());
2969 VLOG(jdwp) << "Undeoptimize method " << PrettyMethod(request.Method()) << " DONE";
Sebastien Hertz4d25df32014-03-21 17:44:46 +01002970 break;
2971 default:
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07002972 LOG(FATAL) << "Unsupported deoptimization request kind " << request.GetKind();
Sebastien Hertz4d25df32014-03-21 17:44:46 +01002973 break;
Sebastien Hertz138dbfc2013-12-04 18:15:25 +01002974 }
Sebastien Hertz138dbfc2013-12-04 18:15:25 +01002975}
2976
Sebastien Hertz7ec2f1c2014-03-27 20:06:47 +01002977void Dbg::DelayFullUndeoptimization() {
Brian Carlstrom306db812014-09-05 13:01:41 -07002978 MutexLock mu(Thread::Current(), *Locks::deoptimization_lock_);
Sebastien Hertz7ec2f1c2014-03-27 20:06:47 +01002979 ++delayed_full_undeoptimization_count_;
2980 DCHECK_LE(delayed_full_undeoptimization_count_, full_deoptimization_event_count_);
2981}
2982
2983void Dbg::ProcessDelayedFullUndeoptimizations() {
2984 // TODO: avoid taking the lock twice (once here and once in ManageDeoptimization).
2985 {
Brian Carlstrom306db812014-09-05 13:01:41 -07002986 MutexLock mu(Thread::Current(), *Locks::deoptimization_lock_);
Sebastien Hertz7ec2f1c2014-03-27 20:06:47 +01002987 while (delayed_full_undeoptimization_count_ > 0) {
2988 DeoptimizationRequest req;
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07002989 req.SetKind(DeoptimizationRequest::kFullUndeoptimization);
2990 req.SetMethod(nullptr);
Sebastien Hertz7ec2f1c2014-03-27 20:06:47 +01002991 RequestDeoptimizationLocked(req);
2992 --delayed_full_undeoptimization_count_;
2993 }
2994 }
2995 ManageDeoptimization();
2996}
2997
Sebastien Hertz4d25df32014-03-21 17:44:46 +01002998void Dbg::RequestDeoptimization(const DeoptimizationRequest& req) {
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07002999 if (req.GetKind() == DeoptimizationRequest::kNothing) {
Sebastien Hertz4d25df32014-03-21 17:44:46 +01003000 // Nothing to do.
3001 return;
3002 }
Brian Carlstrom306db812014-09-05 13:01:41 -07003003 MutexLock mu(Thread::Current(), *Locks::deoptimization_lock_);
Sebastien Hertz7ec2f1c2014-03-27 20:06:47 +01003004 RequestDeoptimizationLocked(req);
3005}
3006
3007void Dbg::RequestDeoptimizationLocked(const DeoptimizationRequest& req) {
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003008 switch (req.GetKind()) {
Sebastien Hertz42cd43f2014-05-13 14:15:41 +02003009 case DeoptimizationRequest::kRegisterForEvent: {
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003010 DCHECK_NE(req.InstrumentationEvent(), 0u);
3011 size_t* counter = GetReferenceCounterForEvent(req.InstrumentationEvent());
Sebastien Hertz42cd43f2014-05-13 14:15:41 +02003012 CHECK(counter != nullptr) << StringPrintf("No counter for instrumentation event 0x%x",
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003013 req.InstrumentationEvent());
Sebastien Hertz42cd43f2014-05-13 14:15:41 +02003014 if (*counter == 0) {
Sebastien Hertz7d2ae432014-05-15 11:26:34 +02003015 VLOG(jdwp) << StringPrintf("Queue request #%zd to start 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 *counter = *counter + 1;
3020 break;
3021 }
3022 case DeoptimizationRequest::kUnregisterForEvent: {
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003023 DCHECK_NE(req.InstrumentationEvent(), 0u);
3024 size_t* counter = GetReferenceCounterForEvent(req.InstrumentationEvent());
Sebastien Hertz42cd43f2014-05-13 14:15:41 +02003025 CHECK(counter != nullptr) << StringPrintf("No counter for instrumentation event 0x%x",
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003026 req.InstrumentationEvent());
Sebastien Hertz42cd43f2014-05-13 14:15:41 +02003027 *counter = *counter - 1;
3028 if (*counter == 0) {
Sebastien Hertz7d2ae432014-05-15 11:26:34 +02003029 VLOG(jdwp) << StringPrintf("Queue request #%zd to stop listening to instrumentation event 0x%x",
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003030 deoptimization_requests_.size(), req.InstrumentationEvent());
Sebastien Hertz42cd43f2014-05-13 14:15:41 +02003031 deoptimization_requests_.push_back(req);
3032 }
3033 break;
3034 }
Sebastien Hertz4d25df32014-03-21 17:44:46 +01003035 case DeoptimizationRequest::kFullDeoptimization: {
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003036 DCHECK(req.Method() == nullptr);
Sebastien Hertz4d25df32014-03-21 17:44:46 +01003037 if (full_deoptimization_event_count_ == 0) {
Sebastien Hertz7ec2f1c2014-03-27 20:06:47 +01003038 VLOG(jdwp) << "Queue request #" << deoptimization_requests_.size()
3039 << " for full deoptimization";
Sebastien Hertz4d25df32014-03-21 17:44:46 +01003040 deoptimization_requests_.push_back(req);
3041 }
3042 ++full_deoptimization_event_count_;
3043 break;
3044 }
3045 case DeoptimizationRequest::kFullUndeoptimization: {
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003046 DCHECK(req.Method() == nullptr);
Sebastien Hertze713d932014-05-15 10:48:53 +02003047 DCHECK_GT(full_deoptimization_event_count_, 0U);
Sebastien Hertz4d25df32014-03-21 17:44:46 +01003048 --full_deoptimization_event_count_;
3049 if (full_deoptimization_event_count_ == 0) {
Sebastien Hertz7ec2f1c2014-03-27 20:06:47 +01003050 VLOG(jdwp) << "Queue request #" << deoptimization_requests_.size()
3051 << " for full undeoptimization";
Sebastien Hertz4d25df32014-03-21 17:44:46 +01003052 deoptimization_requests_.push_back(req);
3053 }
3054 break;
3055 }
3056 case DeoptimizationRequest::kSelectiveDeoptimization: {
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003057 DCHECK(req.Method() != nullptr);
Sebastien Hertz7ec2f1c2014-03-27 20:06:47 +01003058 VLOG(jdwp) << "Queue request #" << deoptimization_requests_.size()
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003059 << " for deoptimization of " << PrettyMethod(req.Method());
Sebastien Hertz4d25df32014-03-21 17:44:46 +01003060 deoptimization_requests_.push_back(req);
3061 break;
3062 }
3063 case DeoptimizationRequest::kSelectiveUndeoptimization: {
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003064 DCHECK(req.Method() != nullptr);
Sebastien Hertz7ec2f1c2014-03-27 20:06:47 +01003065 VLOG(jdwp) << "Queue request #" << deoptimization_requests_.size()
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003066 << " for undeoptimization of " << PrettyMethod(req.Method());
Sebastien Hertz4d25df32014-03-21 17:44:46 +01003067 deoptimization_requests_.push_back(req);
3068 break;
3069 }
3070 default: {
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003071 LOG(FATAL) << "Unknown deoptimization request kind " << req.GetKind();
Sebastien Hertz4d25df32014-03-21 17:44:46 +01003072 break;
3073 }
3074 }
3075}
3076
Sebastien Hertz138dbfc2013-12-04 18:15:25 +01003077void Dbg::ManageDeoptimization() {
3078 Thread* const self = Thread::Current();
3079 {
3080 // Avoid suspend/resume if there is no pending request.
Brian Carlstrom306db812014-09-05 13:01:41 -07003081 MutexLock mu(self, *Locks::deoptimization_lock_);
Sebastien Hertz4d25df32014-03-21 17:44:46 +01003082 if (deoptimization_requests_.empty()) {
Sebastien Hertz138dbfc2013-12-04 18:15:25 +01003083 return;
3084 }
3085 }
3086 CHECK_EQ(self->GetState(), kRunnable);
3087 self->TransitionFromRunnableToSuspended(kWaitingForDeoptimization);
3088 // We need to suspend mutator threads first.
3089 Runtime* const runtime = Runtime::Current();
3090 runtime->GetThreadList()->SuspendAll();
3091 const ThreadState old_state = self->SetStateUnsafe(kRunnable);
Sebastien Hertz4d25df32014-03-21 17:44:46 +01003092 {
Brian Carlstrom306db812014-09-05 13:01:41 -07003093 MutexLock mu(self, *Locks::deoptimization_lock_);
Sebastien Hertz7ec2f1c2014-03-27 20:06:47 +01003094 size_t req_index = 0;
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003095 for (DeoptimizationRequest& request : deoptimization_requests_) {
Sebastien Hertz7ec2f1c2014-03-27 20:06:47 +01003096 VLOG(jdwp) << "Process deoptimization request #" << req_index++;
Sebastien Hertz4d25df32014-03-21 17:44:46 +01003097 ProcessDeoptimizationRequest(request);
3098 }
3099 deoptimization_requests_.clear();
3100 }
Sebastien Hertz138dbfc2013-12-04 18:15:25 +01003101 CHECK_EQ(self->SetStateUnsafe(old_state), kRunnable);
3102 runtime->GetThreadList()->ResumeAll();
3103 self->TransitionFromSuspendedToRunnable();
3104}
3105
Sebastien Hertza76a6d42014-03-20 16:40:17 +01003106static bool IsMethodPossiblyInlined(Thread* self, mirror::ArtMethod* m)
3107 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07003108 const DexFile::CodeItem* code_item = m->GetCodeItem();
Sebastien Hertza76a6d42014-03-20 16:40:17 +01003109 if (code_item == nullptr) {
3110 // TODO We should not be asked to watch location in a native or abstract method so the code item
3111 // should never be null. We could just check we never encounter this case.
3112 return false;
Sebastien Hertz138dbfc2013-12-04 18:15:25 +01003113 }
Hiroshi Yamauchidc376172014-08-22 11:13:12 -07003114 StackHandleScope<3> hs(self);
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07003115 mirror::Class* declaring_class = m->GetDeclaringClass();
3116 Handle<mirror::DexCache> dex_cache(hs.NewHandle(declaring_class->GetDexCache()));
3117 Handle<mirror::ClassLoader> class_loader(hs.NewHandle(declaring_class->GetClassLoader()));
Hiroshi Yamauchidc376172014-08-22 11:13:12 -07003118 Handle<mirror::ArtMethod> method(hs.NewHandle(m));
Ian Rogers7b078e82014-09-10 14:44:24 -07003119 verifier::MethodVerifier verifier(self, dex_cache->GetDexFile(), dex_cache, class_loader,
Hiroshi Yamauchidc376172014-08-22 11:13:12 -07003120 &m->GetClassDef(), code_item, m->GetDexMethodIndex(), method,
Ian Rogers46960fe2014-05-23 10:43:43 -07003121 m->GetAccessFlags(), false, true, false);
Sebastien Hertza76a6d42014-03-20 16:40:17 +01003122 // Note: we don't need to verify the method.
3123 return InlineMethodAnalyser::AnalyseMethodCode(&verifier, nullptr);
3124}
Sebastien Hertz138dbfc2013-12-04 18:15:25 +01003125
Sebastien Hertza76a6d42014-03-20 16:40:17 +01003126static const Breakpoint* FindFirstBreakpointForMethod(mirror::ArtMethod* m)
Sebastien Hertzed2be172014-08-19 15:33:43 +02003127 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_, Locks::breakpoint_lock_) {
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003128 for (Breakpoint& breakpoint : gBreakpoints) {
3129 if (breakpoint.Method() == m) {
Sebastien Hertza76a6d42014-03-20 16:40:17 +01003130 return &breakpoint;
3131 }
3132 }
3133 return nullptr;
3134}
3135
3136// Sanity checks all existing breakpoints on the same method.
3137static void SanityCheckExistingBreakpoints(mirror::ArtMethod* m, bool need_full_deoptimization)
Sebastien Hertzed2be172014-08-19 15:33:43 +02003138 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_, Locks::breakpoint_lock_) {
Sebastien Hertza76a6d42014-03-20 16:40:17 +01003139 if (kIsDebugBuild) {
3140 for (const Breakpoint& breakpoint : gBreakpoints) {
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003141 CHECK_EQ(need_full_deoptimization, breakpoint.NeedFullDeoptimization());
Sebastien Hertza76a6d42014-03-20 16:40:17 +01003142 }
3143 if (need_full_deoptimization) {
3144 // We should have deoptimized everything but not "selectively" deoptimized this method.
3145 CHECK(Runtime::Current()->GetInstrumentation()->AreAllMethodsDeoptimized());
3146 CHECK(!Runtime::Current()->GetInstrumentation()->IsDeoptimized(m));
3147 } else {
3148 // We should have "selectively" deoptimized this method.
3149 // Note: while we have not deoptimized everything for this method, we may have done it for
3150 // another event.
3151 CHECK(Runtime::Current()->GetInstrumentation()->IsDeoptimized(m));
3152 }
Sebastien Hertz138dbfc2013-12-04 18:15:25 +01003153 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -07003154}
3155
Sebastien Hertza76a6d42014-03-20 16:40:17 +01003156// Installs a breakpoint at the specified location. Also indicates through the deoptimization
3157// request if we need to deoptimize.
3158void Dbg::WatchLocation(const JDWP::JdwpLocation* location, DeoptimizationRequest* req) {
3159 Thread* const self = Thread::Current();
Brian Carlstromea46f952013-07-30 01:26:50 -07003160 mirror::ArtMethod* m = FromMethodId(location->method_id);
Sebastien Hertza76a6d42014-03-20 16:40:17 +01003161 DCHECK(m != nullptr) << "No method for method id " << location->method_id;
Sebastien Hertz138dbfc2013-12-04 18:15:25 +01003162
Sebastien Hertzed2be172014-08-19 15:33:43 +02003163 WriterMutexLock mu(self, *Locks::breakpoint_lock_);
Sebastien Hertza76a6d42014-03-20 16:40:17 +01003164 const Breakpoint* const existing_breakpoint = FindFirstBreakpointForMethod(m);
3165 bool need_full_deoptimization;
3166 if (existing_breakpoint == nullptr) {
3167 // There is no breakpoint on this method yet: we need to deoptimize. If this method may be
3168 // inlined, we deoptimize everything; otherwise we deoptimize only this method.
3169 need_full_deoptimization = IsMethodPossiblyInlined(self, m);
3170 if (need_full_deoptimization) {
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003171 req->SetKind(DeoptimizationRequest::kFullDeoptimization);
3172 req->SetMethod(nullptr);
Sebastien Hertza76a6d42014-03-20 16:40:17 +01003173 } else {
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003174 req->SetKind(DeoptimizationRequest::kSelectiveDeoptimization);
3175 req->SetMethod(m);
Sebastien Hertz138dbfc2013-12-04 18:15:25 +01003176 }
Sebastien Hertza76a6d42014-03-20 16:40:17 +01003177 } else {
3178 // There is at least one breakpoint for this method: we don't need to deoptimize.
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003179 req->SetKind(DeoptimizationRequest::kNothing);
3180 req->SetMethod(nullptr);
Sebastien Hertza76a6d42014-03-20 16:40:17 +01003181
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003182 need_full_deoptimization = existing_breakpoint->NeedFullDeoptimization();
Sebastien Hertza76a6d42014-03-20 16:40:17 +01003183 SanityCheckExistingBreakpoints(m, need_full_deoptimization);
Sebastien Hertz138dbfc2013-12-04 18:15:25 +01003184 }
3185
Sebastien Hertza76a6d42014-03-20 16:40:17 +01003186 gBreakpoints.push_back(Breakpoint(m, location->dex_pc, need_full_deoptimization));
3187 VLOG(jdwp) << "Set breakpoint #" << (gBreakpoints.size() - 1) << ": "
3188 << gBreakpoints[gBreakpoints.size() - 1];
3189}
3190
3191// Uninstalls a breakpoint at the specified location. Also indicates through the deoptimization
3192// request if we need to undeoptimize.
3193void Dbg::UnwatchLocation(const JDWP::JdwpLocation* location, DeoptimizationRequest* req) {
Sebastien Hertzed2be172014-08-19 15:33:43 +02003194 WriterMutexLock mu(Thread::Current(), *Locks::breakpoint_lock_);
Sebastien Hertza76a6d42014-03-20 16:40:17 +01003195 mirror::ArtMethod* m = FromMethodId(location->method_id);
3196 DCHECK(m != nullptr) << "No method for method id " << location->method_id;
Sebastien Hertza76a6d42014-03-20 16:40:17 +01003197 bool need_full_deoptimization = false;
3198 for (size_t i = 0, e = gBreakpoints.size(); i < e; ++i) {
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003199 if (gBreakpoints[i].DexPc() == location->dex_pc && gBreakpoints[i].Method() == m) {
Sebastien Hertza76a6d42014-03-20 16:40:17 +01003200 VLOG(jdwp) << "Removed breakpoint #" << i << ": " << gBreakpoints[i];
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003201 need_full_deoptimization = gBreakpoints[i].NeedFullDeoptimization();
Sebastien Hertza76a6d42014-03-20 16:40:17 +01003202 DCHECK_NE(need_full_deoptimization, Runtime::Current()->GetInstrumentation()->IsDeoptimized(m));
3203 gBreakpoints.erase(gBreakpoints.begin() + i);
3204 break;
3205 }
3206 }
3207 const Breakpoint* const existing_breakpoint = FindFirstBreakpointForMethod(m);
3208 if (existing_breakpoint == nullptr) {
3209 // There is no more breakpoint on this method: we need to undeoptimize.
3210 if (need_full_deoptimization) {
3211 // This method required full deoptimization: we need to undeoptimize everything.
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003212 req->SetKind(DeoptimizationRequest::kFullUndeoptimization);
3213 req->SetMethod(nullptr);
Sebastien Hertza76a6d42014-03-20 16:40:17 +01003214 } else {
3215 // This method required selective deoptimization: we need to undeoptimize only that method.
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003216 req->SetKind(DeoptimizationRequest::kSelectiveUndeoptimization);
3217 req->SetMethod(m);
Sebastien Hertza76a6d42014-03-20 16:40:17 +01003218 }
3219 } else {
3220 // There is at least one breakpoint for this method: we don't need to undeoptimize.
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003221 req->SetKind(DeoptimizationRequest::kNothing);
3222 req->SetMethod(nullptr);
Sebastien Hertza76a6d42014-03-20 16:40:17 +01003223 SanityCheckExistingBreakpoints(m, need_full_deoptimization);
Elliott Hughes86964332012-02-15 19:37:42 -08003224 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -07003225}
3226
Jeff Hao449db332013-04-12 18:30:52 -07003227// Scoped utility class to suspend a thread so that we may do tasks such as walk its stack. Doesn't
3228// cause suspension if the thread is the current thread.
3229class ScopedThreadSuspension {
3230 public:
Ian Rogers33e95662013-05-20 20:29:14 -07003231 ScopedThreadSuspension(Thread* self, JDWP::ObjectId thread_id)
Sebastien Hertz52d131d2014-03-13 16:17:40 +01003232 LOCKS_EXCLUDED(Locks::thread_list_lock_)
Ian Rogers33e95662013-05-20 20:29:14 -07003233 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) :
Ian Rogersf3d874c2014-07-17 18:52:42 -07003234 thread_(nullptr),
Jeff Hao449db332013-04-12 18:30:52 -07003235 error_(JDWP::ERR_NONE),
3236 self_suspend_(false),
Ian Rogers33e95662013-05-20 20:29:14 -07003237 other_suspend_(false) {
Jeff Hao449db332013-04-12 18:30:52 -07003238 ScopedObjectAccessUnchecked soa(self);
3239 {
3240 MutexLock mu(soa.Self(), *Locks::thread_list_lock_);
Ian Rogersc0542af2014-09-03 16:16:56 -07003241 thread_ = DecodeThread(soa, thread_id, &error_);
Jeff Hao449db332013-04-12 18:30:52 -07003242 }
3243 if (error_ == JDWP::ERR_NONE) {
3244 if (thread_ == soa.Self()) {
3245 self_suspend_ = true;
3246 } else {
3247 soa.Self()->TransitionFromRunnableToSuspended(kWaitingForDebuggerSuspension);
3248 jobject thread_peer = gRegistry->GetJObject(thread_id);
3249 bool timed_out;
Ian Rogersf3d874c2014-07-17 18:52:42 -07003250 Thread* suspended_thread;
3251 {
3252 // Take suspend thread lock to avoid races with threads trying to suspend this one.
3253 MutexLock mu(soa.Self(), *Locks::thread_list_suspend_thread_lock_);
Brian Carlstromba32de42014-08-27 23:43:46 -07003254 ThreadList* thread_list = Runtime::Current()->GetThreadList();
3255 suspended_thread = thread_list->SuspendThreadByPeer(thread_peer, true, true, &timed_out);
Ian Rogersf3d874c2014-07-17 18:52:42 -07003256 }
Jeff Hao449db332013-04-12 18:30:52 -07003257 CHECK_EQ(soa.Self()->TransitionFromSuspendedToRunnable(), kWaitingForDebuggerSuspension);
Ian Rogersf3d874c2014-07-17 18:52:42 -07003258 if (suspended_thread == nullptr) {
Jeff Hao449db332013-04-12 18:30:52 -07003259 // Thread terminated from under us while suspending.
3260 error_ = JDWP::ERR_INVALID_THREAD;
3261 } else {
3262 CHECK_EQ(suspended_thread, thread_);
3263 other_suspend_ = true;
3264 }
3265 }
3266 }
Elliott Hughes2435a572012-02-17 16:07:41 -08003267 }
Elliott Hughes86964332012-02-15 19:37:42 -08003268
Jeff Hao449db332013-04-12 18:30:52 -07003269 Thread* GetThread() const {
3270 return thread_;
3271 }
3272
3273 JDWP::JdwpError GetError() const {
3274 return error_;
3275 }
3276
3277 ~ScopedThreadSuspension() {
3278 if (other_suspend_) {
3279 Runtime::Current()->GetThreadList()->Resume(thread_, true);
3280 }
3281 }
3282
3283 private:
3284 Thread* thread_;
3285 JDWP::JdwpError error_;
3286 bool self_suspend_;
3287 bool other_suspend_;
3288};
3289
3290JDWP::JdwpError Dbg::ConfigureStep(JDWP::ObjectId thread_id, JDWP::JdwpStepSize step_size,
3291 JDWP::JdwpStepDepth step_depth) {
3292 Thread* self = Thread::Current();
3293 ScopedThreadSuspension sts(self, thread_id);
3294 if (sts.GetError() != JDWP::ERR_NONE) {
3295 return sts.GetError();
3296 }
3297
Elliott Hughes2435a572012-02-17 16:07:41 -08003298 //
3299 // Work out what Method* we're in, the current line number, and how deep the stack currently
3300 // is for step-out.
3301 //
3302
Ian Rogers0399dde2012-06-06 17:09:28 -07003303 struct SingleStepStackVisitor : public StackVisitor {
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01003304 explicit SingleStepStackVisitor(Thread* thread, SingleStepControl* single_step_control,
3305 int32_t* line_number)
Ian Rogersb726dcb2012-09-05 08:57:23 -07003306 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_)
Ian Rogersc0542af2014-09-03 16:16:56 -07003307 : StackVisitor(thread, nullptr), single_step_control_(single_step_control),
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01003308 line_number_(line_number) {
3309 DCHECK_EQ(single_step_control_, thread->GetSingleStepControl());
Ian Rogersc0542af2014-09-03 16:16:56 -07003310 single_step_control_->method = nullptr;
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01003311 single_step_control_->stack_depth = 0;
Elliott Hughes86964332012-02-15 19:37:42 -08003312 }
Ian Rogersca190662012-06-26 15:45:57 -07003313
Ian Rogers00f7d0e2012-07-19 15:28:27 -07003314 // TODO: Enable annotalysis. We know lock is held in constructor, but abstraction confuses
3315 // annotalysis.
3316 bool VisitFrame() NO_THREAD_SAFETY_ANALYSIS {
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01003317 mirror::ArtMethod* m = GetMethod();
Ian Rogers0399dde2012-06-06 17:09:28 -07003318 if (!m->IsRuntimeMethod()) {
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01003319 ++single_step_control_->stack_depth;
Ian Rogersc0542af2014-09-03 16:16:56 -07003320 if (single_step_control_->method == nullptr) {
Ian Rogersef7d42f2014-01-06 12:55:46 -08003321 mirror::DexCache* dex_cache = m->GetDeclaringClass()->GetDexCache();
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01003322 single_step_control_->method = m;
3323 *line_number_ = -1;
Ian Rogersc0542af2014-09-03 16:16:56 -07003324 if (dex_cache != nullptr) {
Ian Rogers4445a7e2012-10-05 17:19:13 -07003325 const DexFile& dex_file = *dex_cache->GetDexFile();
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01003326 *line_number_ = dex_file.GetLineNumFromPC(m, GetDexPc());
Elliott Hughes2435a572012-02-17 16:07:41 -08003327 }
Elliott Hughes86964332012-02-15 19:37:42 -08003328 }
3329 }
Elliott Hughes530fa002012-03-12 11:44:49 -07003330 return true;
Elliott Hughes86964332012-02-15 19:37:42 -08003331 }
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01003332
3333 SingleStepControl* const single_step_control_;
3334 int32_t* const line_number_;
Elliott Hughes86964332012-02-15 19:37:42 -08003335 };
Jeff Hao449db332013-04-12 18:30:52 -07003336
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01003337 Thread* const thread = sts.GetThread();
3338 SingleStepControl* const single_step_control = thread->GetSingleStepControl();
3339 DCHECK(single_step_control != nullptr);
3340 int32_t line_number = -1;
3341 SingleStepStackVisitor visitor(thread, single_step_control, &line_number);
Ian Rogers0399dde2012-06-06 17:09:28 -07003342 visitor.WalkStack();
Elliott Hughes86964332012-02-15 19:37:42 -08003343
Elliott Hughes2435a572012-02-17 16:07:41 -08003344 //
3345 // Find the dex_pc values that correspond to the current line, for line-based single-stepping.
3346 //
3347
3348 struct DebugCallbackContext {
Sebastien Hertzbb43b432014-04-14 11:59:08 +02003349 explicit DebugCallbackContext(SingleStepControl* single_step_control, int32_t line_number,
3350 const DexFile::CodeItem* code_item)
3351 : single_step_control_(single_step_control), line_number_(line_number), code_item_(code_item),
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01003352 last_pc_valid(false), last_pc(0) {
Elliott Hughes2435a572012-02-17 16:07:41 -08003353 }
3354
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01003355 static bool Callback(void* raw_context, uint32_t address, uint32_t line_number) {
Elliott Hughes2435a572012-02-17 16:07:41 -08003356 DebugCallbackContext* context = reinterpret_cast<DebugCallbackContext*>(raw_context);
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01003357 if (static_cast<int32_t>(line_number) == context->line_number_) {
Elliott Hughes2435a572012-02-17 16:07:41 -08003358 if (!context->last_pc_valid) {
3359 // Everything from this address until the next line change is ours.
3360 context->last_pc = address;
3361 context->last_pc_valid = true;
3362 }
3363 // Otherwise, if we're already in a valid range for this line,
3364 // just keep going (shouldn't really happen)...
Brian Carlstrom7934ac22013-07-26 10:54:15 -07003365 } else if (context->last_pc_valid) { // and the line number is new
Elliott Hughes2435a572012-02-17 16:07:41 -08003366 // Add everything from the last entry up until here to the set
3367 for (uint32_t dex_pc = context->last_pc; dex_pc < address; ++dex_pc) {
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01003368 context->single_step_control_->dex_pcs.insert(dex_pc);
Elliott Hughes2435a572012-02-17 16:07:41 -08003369 }
3370 context->last_pc_valid = false;
3371 }
Brian Carlstrom7934ac22013-07-26 10:54:15 -07003372 return false; // There may be multiple entries for any given line.
Elliott Hughes2435a572012-02-17 16:07:41 -08003373 }
3374
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01003375 ~DebugCallbackContext() {
Elliott Hughes2435a572012-02-17 16:07:41 -08003376 // If the line number was the last in the position table...
3377 if (last_pc_valid) {
Sebastien Hertzbb43b432014-04-14 11:59:08 +02003378 size_t end = code_item_->insns_size_in_code_units_;
Elliott Hughes2435a572012-02-17 16:07:41 -08003379 for (uint32_t dex_pc = last_pc; dex_pc < end; ++dex_pc) {
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01003380 single_step_control_->dex_pcs.insert(dex_pc);
Elliott Hughes2435a572012-02-17 16:07:41 -08003381 }
3382 }
3383 }
3384
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01003385 SingleStepControl* const single_step_control_;
3386 const int32_t line_number_;
Sebastien Hertzbb43b432014-04-14 11:59:08 +02003387 const DexFile::CodeItem* const code_item_;
Elliott Hughes2435a572012-02-17 16:07:41 -08003388 bool last_pc_valid;
3389 uint32_t last_pc;
3390 };
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01003391 single_step_control->dex_pcs.clear();
Ian Rogersef7d42f2014-01-06 12:55:46 -08003392 mirror::ArtMethod* m = single_step_control->method;
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01003393 if (!m->IsNative()) {
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07003394 const DexFile::CodeItem* const code_item = m->GetCodeItem();
Sebastien Hertzbb43b432014-04-14 11:59:08 +02003395 DebugCallbackContext context(single_step_control, line_number, code_item);
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07003396 m->GetDexFile()->DecodeDebugInfo(code_item, m->IsStatic(), m->GetDexMethodIndex(),
Ian Rogersc0542af2014-09-03 16:16:56 -07003397 DebugCallbackContext::Callback, nullptr, &context);
Elliott Hughes3e2e1a22012-02-21 11:33:41 -08003398 }
Elliott Hughes2435a572012-02-17 16:07:41 -08003399
3400 //
3401 // Everything else...
3402 //
3403
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01003404 single_step_control->step_size = step_size;
3405 single_step_control->step_depth = step_depth;
3406 single_step_control->is_active = true;
Elliott Hughes86964332012-02-15 19:37:42 -08003407
Elliott Hughes2435a572012-02-17 16:07:41 -08003408 if (VLOG_IS_ON(jdwp)) {
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01003409 VLOG(jdwp) << "Single-step thread: " << *thread;
3410 VLOG(jdwp) << "Single-step step size: " << single_step_control->step_size;
3411 VLOG(jdwp) << "Single-step step depth: " << single_step_control->step_depth;
3412 VLOG(jdwp) << "Single-step current method: " << PrettyMethod(single_step_control->method);
3413 VLOG(jdwp) << "Single-step current line: " << line_number;
3414 VLOG(jdwp) << "Single-step current stack depth: " << single_step_control->stack_depth;
Elliott Hughes2435a572012-02-17 16:07:41 -08003415 VLOG(jdwp) << "Single-step dex_pc values:";
Sebastien Hertzbb43b432014-04-14 11:59:08 +02003416 for (uint32_t dex_pc : single_step_control->dex_pcs) {
3417 VLOG(jdwp) << StringPrintf(" %#x", dex_pc);
Elliott Hughes2435a572012-02-17 16:07:41 -08003418 }
3419 }
3420
3421 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07003422}
3423
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01003424void Dbg::UnconfigureStep(JDWP::ObjectId thread_id) {
3425 ScopedObjectAccessUnchecked soa(Thread::Current());
3426 MutexLock mu(soa.Self(), *Locks::thread_list_lock_);
Ian Rogersc0542af2014-09-03 16:16:56 -07003427 JDWP::JdwpError error;
3428 Thread* thread = DecodeThread(soa, thread_id, &error);
Sebastien Hertz87118ed2013-11-26 17:57:18 +01003429 if (error == JDWP::ERR_NONE) {
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01003430 SingleStepControl* single_step_control = thread->GetSingleStepControl();
3431 DCHECK(single_step_control != nullptr);
Sebastien Hertzbb43b432014-04-14 11:59:08 +02003432 single_step_control->Clear();
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01003433 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -07003434}
3435
Elliott Hughes45651fd2012-02-21 15:48:20 -08003436static char JdwpTagToShortyChar(JDWP::JdwpTag tag) {
3437 switch (tag) {
3438 default:
3439 LOG(FATAL) << "unknown JDWP tag: " << PrintableChar(tag);
3440
3441 // Primitives.
3442 case JDWP::JT_BYTE: return 'B';
3443 case JDWP::JT_CHAR: return 'C';
3444 case JDWP::JT_FLOAT: return 'F';
3445 case JDWP::JT_DOUBLE: return 'D';
3446 case JDWP::JT_INT: return 'I';
3447 case JDWP::JT_LONG: return 'J';
3448 case JDWP::JT_SHORT: return 'S';
3449 case JDWP::JT_VOID: return 'V';
3450 case JDWP::JT_BOOLEAN: return 'Z';
3451
3452 // Reference types.
3453 case JDWP::JT_ARRAY:
3454 case JDWP::JT_OBJECT:
3455 case JDWP::JT_STRING:
3456 case JDWP::JT_THREAD:
3457 case JDWP::JT_THREAD_GROUP:
3458 case JDWP::JT_CLASS_LOADER:
3459 case JDWP::JT_CLASS_OBJECT:
3460 return 'L';
3461 }
3462}
3463
Elliott Hughes88d63092013-01-09 09:55:54 -08003464JDWP::JdwpError Dbg::InvokeMethod(JDWP::ObjectId thread_id, JDWP::ObjectId object_id,
3465 JDWP::RefTypeId class_id, JDWP::MethodId method_id,
Ian Rogers00f7d0e2012-07-19 15:28:27 -07003466 uint32_t arg_count, uint64_t* arg_values,
3467 JDWP::JdwpTag* arg_types, uint32_t options,
3468 JDWP::JdwpTag* pResultTag, uint64_t* pResultValue,
3469 JDWP::ObjectId* pExceptionId) {
Elliott Hughesd07986f2011-12-06 18:27:45 -08003470 ThreadList* thread_list = Runtime::Current()->GetThreadList();
3471
Ian Rogersc0542af2014-09-03 16:16:56 -07003472 Thread* targetThread = nullptr;
3473 DebugInvokeReq* req = nullptr;
Ian Rogers00f7d0e2012-07-19 15:28:27 -07003474 Thread* self = Thread::Current();
Elliott Hughesd07986f2011-12-06 18:27:45 -08003475 {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07003476 ScopedObjectAccessUnchecked soa(self);
Ian Rogers50b35e22012-10-04 10:09:15 -07003477 MutexLock mu(soa.Self(), *Locks::thread_list_lock_);
Ian Rogersc0542af2014-09-03 16:16:56 -07003478 JDWP::JdwpError error;
3479 targetThread = DecodeThread(soa, thread_id, &error);
Elliott Hughes221229c2013-01-08 18:17:50 -08003480 if (error != JDWP::ERR_NONE) {
3481 LOG(ERROR) << "InvokeMethod request for invalid thread id " << thread_id;
3482 return error;
Elliott Hughesd07986f2011-12-06 18:27:45 -08003483 }
3484 req = targetThread->GetInvokeReq();
3485 if (!req->ready) {
3486 LOG(ERROR) << "InvokeMethod request for thread not stopped by event: " << *targetThread;
3487 return JDWP::ERR_INVALID_THREAD;
3488 }
3489
3490 /*
3491 * We currently have a bug where we don't successfully resume the
3492 * target thread if the suspend count is too deep. We're expected to
3493 * require one "resume" for each "suspend", but when asked to execute
3494 * a method we have to resume fully and then re-suspend it back to the
3495 * same level. (The easiest way to cause this is to type "suspend"
3496 * multiple times in jdb.)
3497 *
3498 * It's unclear what this means when the event specifies "resume all"
3499 * and some threads are suspended more deeply than others. This is
3500 * a rare problem, so for now we just prevent it from hanging forever
3501 * by rejecting the method invocation request. Without this, we will
3502 * be stuck waiting on a suspended thread.
3503 */
Ian Rogers00f7d0e2012-07-19 15:28:27 -07003504 int suspend_count;
3505 {
Ian Rogers50b35e22012-10-04 10:09:15 -07003506 MutexLock mu2(soa.Self(), *Locks::thread_suspend_count_lock_);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07003507 suspend_count = targetThread->GetSuspendCount();
3508 }
Elliott Hughesd07986f2011-12-06 18:27:45 -08003509 if (suspend_count > 1) {
3510 LOG(ERROR) << *targetThread << " suspend count too deep for method invocation: " << suspend_count;
Brian Carlstrom7934ac22013-07-26 10:54:15 -07003511 return JDWP::ERR_THREAD_SUSPENDED; // Probably not expected here.
Elliott Hughesd07986f2011-12-06 18:27:45 -08003512 }
3513
Ian Rogersc0542af2014-09-03 16:16:56 -07003514 mirror::Object* receiver = gRegistry->Get<mirror::Object*>(object_id, &error);
3515 if (error != JDWP::ERR_NONE) {
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08003516 return JDWP::ERR_INVALID_OBJECT;
3517 }
Elliott Hughes45651fd2012-02-21 15:48:20 -08003518
Ian Rogersc0542af2014-09-03 16:16:56 -07003519 mirror::Object* thread = gRegistry->Get<mirror::Object*>(thread_id, &error);
3520 if (error != JDWP::ERR_NONE) {
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08003521 return JDWP::ERR_INVALID_OBJECT;
3522 }
Elliott Hughes45651fd2012-02-21 15:48:20 -08003523 // TODO: check that 'thread' is actually a java.lang.Thread!
3524
Ian Rogersc0542af2014-09-03 16:16:56 -07003525 mirror::Class* c = DecodeClass(class_id, &error);
3526 if (c == nullptr) {
3527 return error;
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08003528 }
Elliott Hughes45651fd2012-02-21 15:48:20 -08003529
Brian Carlstromea46f952013-07-30 01:26:50 -07003530 mirror::ArtMethod* m = FromMethodId(method_id);
Ian Rogersc0542af2014-09-03 16:16:56 -07003531 if (m->IsStatic() != (receiver == nullptr)) {
Elliott Hughes45651fd2012-02-21 15:48:20 -08003532 return JDWP::ERR_INVALID_METHODID;
3533 }
3534 if (m->IsStatic()) {
3535 if (m->GetDeclaringClass() != c) {
3536 return JDWP::ERR_INVALID_METHODID;
3537 }
3538 } else {
3539 if (!m->GetDeclaringClass()->IsAssignableFrom(c)) {
3540 return JDWP::ERR_INVALID_METHODID;
3541 }
3542 }
3543
3544 // Check the argument list matches the method.
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07003545 uint32_t shorty_len = 0;
3546 const char* shorty = m->GetShorty(&shorty_len);
3547 if (shorty_len - 1 != arg_count) {
Elliott Hughes45651fd2012-02-21 15:48:20 -08003548 return JDWP::ERR_ILLEGAL_ARGUMENT;
3549 }
Elliott Hughes09201632013-04-15 15:50:07 -07003550
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07003551 {
3552 StackHandleScope<3> hs(soa.Self());
3553 MethodHelper mh(hs.NewHandle(m));
3554 HandleWrapper<mirror::Object> h_obj(hs.NewHandleWrapper(&receiver));
3555 HandleWrapper<mirror::Class> h_klass(hs.NewHandleWrapper(&c));
3556 const DexFile::TypeList* types = m->GetParameterTypeList();
3557 for (size_t i = 0; i < arg_count; ++i) {
3558 if (shorty[i + 1] != JdwpTagToShortyChar(arg_types[i])) {
Elliott Hughes09201632013-04-15 15:50:07 -07003559 return JDWP::ERR_ILLEGAL_ARGUMENT;
3560 }
3561
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07003562 if (shorty[i + 1] == 'L') {
3563 // Did we really get an argument of an appropriate reference type?
3564 mirror::Class* parameter_type = mh.GetClassFromTypeIdx(types->GetTypeItem(i).type_idx_);
Ian Rogersc0542af2014-09-03 16:16:56 -07003565 mirror::Object* argument = gRegistry->Get<mirror::Object*>(arg_values[i], &error);
3566 if (error != JDWP::ERR_NONE) {
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07003567 return JDWP::ERR_INVALID_OBJECT;
3568 }
Ian Rogersc0542af2014-09-03 16:16:56 -07003569 if (argument != nullptr && !argument->InstanceOf(parameter_type)) {
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07003570 return JDWP::ERR_ILLEGAL_ARGUMENT;
3571 }
3572
3573 // Turn the on-the-wire ObjectId into a jobject.
3574 jvalue& v = reinterpret_cast<jvalue&>(arg_values[i]);
3575 v.l = gRegistry->GetJObject(arg_values[i]);
3576 }
Elliott Hughes09201632013-04-15 15:50:07 -07003577 }
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07003578 // Update in case it moved.
3579 m = mh.GetMethod();
Elliott Hughes45651fd2012-02-21 15:48:20 -08003580 }
3581
Sebastien Hertzd38667a2013-11-25 15:43:54 +01003582 req->receiver = receiver;
3583 req->thread = thread;
3584 req->klass = c;
3585 req->method = m;
3586 req->arg_count = arg_count;
3587 req->arg_values = arg_values;
3588 req->options = options;
3589 req->invoke_needed = true;
Elliott Hughesd07986f2011-12-06 18:27:45 -08003590 }
3591
3592 // The fact that we've released the thread list lock is a bit risky --- if the thread goes
3593 // away we're sitting high and dry -- but we must release this before the ResumeAllThreads
3594 // call, and it's unwise to hold it during WaitForSuspend.
3595
3596 {
3597 /*
3598 * We change our (JDWP thread) status, which should be THREAD_RUNNING,
Elliott Hughes81ff3182012-03-23 20:35:56 -07003599 * so we can suspend for a GC if the invoke request causes us to
Elliott Hughesd07986f2011-12-06 18:27:45 -08003600 * run out of memory. It's also a good idea to change it before locking
3601 * the invokeReq mutex, although that should never be held for long.
3602 */
Ian Rogers00f7d0e2012-07-19 15:28:27 -07003603 self->TransitionFromRunnableToSuspended(kWaitingForDebuggerSend);
Elliott Hughesd07986f2011-12-06 18:27:45 -08003604
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08003605 VLOG(jdwp) << " Transferring control to event thread";
Elliott Hughesd07986f2011-12-06 18:27:45 -08003606 {
Sebastien Hertzd38667a2013-11-25 15:43:54 +01003607 MutexLock mu(self, req->lock);
Elliott Hughesd07986f2011-12-06 18:27:45 -08003608
3609 if ((options & JDWP::INVOKE_SINGLE_THREADED) == 0) {
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08003610 VLOG(jdwp) << " Resuming all threads";
Ian Rogers00f7d0e2012-07-19 15:28:27 -07003611 thread_list->UndoDebuggerSuspensions();
Elliott Hughesd07986f2011-12-06 18:27:45 -08003612 } else {
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08003613 VLOG(jdwp) << " Resuming event thread only";
Elliott Hughesd07986f2011-12-06 18:27:45 -08003614 thread_list->Resume(targetThread, true);
3615 }
3616
3617 // Wait for the request to finish executing.
Sebastien Hertzd38667a2013-11-25 15:43:54 +01003618 while (req->invoke_needed) {
3619 req->cond.Wait(self);
Elliott Hughesd07986f2011-12-06 18:27:45 -08003620 }
3621 }
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08003622 VLOG(jdwp) << " Control has returned from event thread";
Elliott Hughesd07986f2011-12-06 18:27:45 -08003623
3624 /* wait for thread to re-suspend itself */
Brian Carlstromdf629502013-07-17 22:39:56 -07003625 SuspendThread(thread_id, false /* request_suspension */);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07003626 self->TransitionFromSuspendedToRunnable();
Elliott Hughesd07986f2011-12-06 18:27:45 -08003627 }
3628
3629 /*
3630 * Suspend the threads. We waited for the target thread to suspend
3631 * itself, so all we need to do is suspend the others.
3632 *
3633 * The suspendAllThreads() call will double-suspend the event thread,
3634 * so we want to resume the target thread once to keep the books straight.
3635 */
3636 if ((options & JDWP::INVOKE_SINGLE_THREADED) == 0) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07003637 self->TransitionFromRunnableToSuspended(kWaitingForDebuggerSuspension);
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08003638 VLOG(jdwp) << " Suspending all threads";
Ian Rogers00f7d0e2012-07-19 15:28:27 -07003639 thread_list->SuspendAllForDebugger();
3640 self->TransitionFromSuspendedToRunnable();
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08003641 VLOG(jdwp) << " Resuming event thread to balance the count";
Elliott Hughesd07986f2011-12-06 18:27:45 -08003642 thread_list->Resume(targetThread, true);
3643 }
3644
3645 // Copy the result.
3646 *pResultTag = req->result_tag;
3647 if (IsPrimitiveTag(req->result_tag)) {
Elliott Hughesf24d3ce2012-04-11 17:43:37 -07003648 *pResultValue = req->result_value.GetJ();
Elliott Hughesd07986f2011-12-06 18:27:45 -08003649 } else {
Elliott Hughesf24d3ce2012-04-11 17:43:37 -07003650 *pResultValue = gRegistry->Add(req->result_value.GetL());
Elliott Hughesd07986f2011-12-06 18:27:45 -08003651 }
3652 *pExceptionId = req->exception;
3653 return req->error;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07003654}
3655
3656void Dbg::ExecuteMethod(DebugInvokeReq* pReq) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07003657 ScopedObjectAccess soa(Thread::Current());
Elliott Hughesd07986f2011-12-06 18:27:45 -08003658
Elliott Hughes81ff3182012-03-23 20:35:56 -07003659 // We can be called while an exception is pending. We need
Elliott Hughesd07986f2011-12-06 18:27:45 -08003660 // to preserve that across the method invocation.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003661 StackHandleScope<4> hs(soa.Self());
3662 auto old_throw_this_object = hs.NewHandle<mirror::Object>(nullptr);
3663 auto old_throw_method = hs.NewHandle<mirror::ArtMethod>(nullptr);
3664 auto old_exception = hs.NewHandle<mirror::Throwable>(nullptr);
Ian Rogers62d6c772013-02-27 08:32:07 -08003665 uint32_t old_throw_dex_pc;
Sebastien Hertz9f102032014-05-23 08:59:42 +02003666 bool old_exception_report_flag;
Ian Rogers62d6c772013-02-27 08:32:07 -08003667 {
3668 ThrowLocation old_throw_location;
3669 mirror::Throwable* old_exception_obj = soa.Self()->GetException(&old_throw_location);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003670 old_throw_this_object.Assign(old_throw_location.GetThis());
3671 old_throw_method.Assign(old_throw_location.GetMethod());
3672 old_exception.Assign(old_exception_obj);
Ian Rogers62d6c772013-02-27 08:32:07 -08003673 old_throw_dex_pc = old_throw_location.GetDexPc();
Sebastien Hertz9f102032014-05-23 08:59:42 +02003674 old_exception_report_flag = soa.Self()->IsExceptionReportedToInstrumentation();
Ian Rogers62d6c772013-02-27 08:32:07 -08003675 soa.Self()->ClearException();
3676 }
Elliott Hughesd07986f2011-12-06 18:27:45 -08003677
3678 // Translate the method through the vtable, unless the debugger wants to suppress it.
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07003679 MutableHandle<mirror::ArtMethod> m(hs.NewHandle(pReq->method));
Ian Rogersc0542af2014-09-03 16:16:56 -07003680 if ((pReq->options & JDWP::INVOKE_NONVIRTUAL) == 0 && pReq->receiver != nullptr) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003681 mirror::ArtMethod* actual_method = pReq->klass->FindVirtualMethodForVirtualOrInterface(m.Get());
3682 if (actual_method != m.Get()) {
3683 VLOG(jdwp) << "ExecuteMethod translated " << PrettyMethod(m.Get()) << " to " << PrettyMethod(actual_method);
3684 m.Assign(actual_method);
Elliott Hughes45651fd2012-02-21 15:48:20 -08003685 }
Elliott Hughesd07986f2011-12-06 18:27:45 -08003686 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003687 VLOG(jdwp) << "ExecuteMethod " << PrettyMethod(m.Get())
Sebastien Hertzd38667a2013-11-25 15:43:54 +01003688 << " receiver=" << pReq->receiver
3689 << " arg_count=" << pReq->arg_count;
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003690 CHECK(m.Get() != nullptr);
Elliott Hughesd07986f2011-12-06 18:27:45 -08003691
3692 CHECK_EQ(sizeof(jvalue), sizeof(uint64_t));
3693
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003694 pReq->result_value = InvokeWithJValues(soa, pReq->receiver, soa.EncodeMethod(m.Get()),
Ian Rogers53b8b092014-03-13 23:45:53 -07003695 reinterpret_cast<jvalue*>(pReq->arg_values));
Elliott Hughesd07986f2011-12-06 18:27:45 -08003696
Ian Rogersc0542af2014-09-03 16:16:56 -07003697 mirror::Throwable* exception = soa.Self()->GetException(nullptr);
Ian Rogers62d6c772013-02-27 08:32:07 -08003698 soa.Self()->ClearException();
3699 pReq->exception = gRegistry->Add(exception);
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07003700 pReq->result_tag = BasicTagFromDescriptor(m.Get()->GetShorty());
Elliott Hughesd07986f2011-12-06 18:27:45 -08003701 if (pReq->exception != 0) {
Ian Rogers62d6c772013-02-27 08:32:07 -08003702 VLOG(jdwp) << " JDWP invocation returning with exception=" << exception
3703 << " " << exception->Dump();
Elliott Hughesf24d3ce2012-04-11 17:43:37 -07003704 pReq->result_value.SetJ(0);
Elliott Hughesd07986f2011-12-06 18:27:45 -08003705 } else if (pReq->result_tag == JDWP::JT_OBJECT) {
3706 /* if no exception thrown, examine object result more closely */
Ian Rogers98379392014-02-24 16:53:16 -08003707 JDWP::JdwpTag new_tag = TagFromObject(soa, pReq->result_value.GetL());
Elliott Hughesd07986f2011-12-06 18:27:45 -08003708 if (new_tag != pReq->result_tag) {
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08003709 VLOG(jdwp) << " JDWP promoted result from " << pReq->result_tag << " to " << new_tag;
Elliott Hughesd07986f2011-12-06 18:27:45 -08003710 pReq->result_tag = new_tag;
3711 }
3712
3713 /*
3714 * Register the object. We don't actually need an ObjectId yet,
3715 * but we do need to be sure that the GC won't move or discard the
3716 * object when we switch out of RUNNING. The ObjectId conversion
3717 * will add the object to the "do not touch" list.
3718 *
3719 * We can't use the "tracked allocation" mechanism here because
3720 * the object is going to be handed off to a different thread.
3721 */
Elliott Hughesf24d3ce2012-04-11 17:43:37 -07003722 gRegistry->Add(pReq->result_value.GetL());
Elliott Hughesd07986f2011-12-06 18:27:45 -08003723 }
3724
Ian Rogersc0542af2014-09-03 16:16:56 -07003725 if (old_exception.Get() != nullptr) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003726 ThrowLocation gc_safe_throw_location(old_throw_this_object.Get(), old_throw_method.Get(),
Ian Rogers62d6c772013-02-27 08:32:07 -08003727 old_throw_dex_pc);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003728 soa.Self()->SetException(gc_safe_throw_location, old_exception.Get());
Sebastien Hertz9f102032014-05-23 08:59:42 +02003729 soa.Self()->SetExceptionReportedToInstrumentation(old_exception_report_flag);
Elliott Hughesd07986f2011-12-06 18:27:45 -08003730 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -07003731}
3732
Elliott Hughesd07986f2011-12-06 18:27:45 -08003733/*
Elliott Hughes4b9702c2013-02-20 18:13:24 -08003734 * "request" contains a full JDWP packet, possibly with multiple chunks. We
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07003735 * need to process each, accumulate the replies, and ship the whole thing
3736 * back.
3737 *
3738 * Returns "true" if we have a reply. The reply buffer is newly allocated,
3739 * and includes the chunk type/length, followed by the data.
3740 *
Elliott Hughes3d30d9b2011-12-07 17:35:48 -08003741 * OLD-TODO: we currently assume that the request and reply include a single
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07003742 * chunk. If this becomes inconvenient we will need to adapt.
3743 */
Ian Rogersc0542af2014-09-03 16:16:56 -07003744bool Dbg::DdmHandlePacket(JDWP::Request* request, uint8_t** pReplyBuf, int* pReplyLen) {
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07003745 Thread* self = Thread::Current();
3746 JNIEnv* env = self->GetJniEnv();
3747
Ian Rogersc0542af2014-09-03 16:16:56 -07003748 uint32_t type = request->ReadUnsigned32("type");
3749 uint32_t length = request->ReadUnsigned32("length");
Elliott Hughes4b9702c2013-02-20 18:13:24 -08003750
3751 // Create a byte[] corresponding to 'request'.
Ian Rogersc0542af2014-09-03 16:16:56 -07003752 size_t request_length = request->size();
Elliott Hughes4b9702c2013-02-20 18:13:24 -08003753 ScopedLocalRef<jbyteArray> dataArray(env, env->NewByteArray(request_length));
Ian Rogersc0542af2014-09-03 16:16:56 -07003754 if (dataArray.get() == nullptr) {
Elliott Hughes4b9702c2013-02-20 18:13:24 -08003755 LOG(WARNING) << "byte[] allocation failed: " << request_length;
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07003756 env->ExceptionClear();
3757 return false;
3758 }
Ian Rogersc0542af2014-09-03 16:16:56 -07003759 env->SetByteArrayRegion(dataArray.get(), 0, request_length,
3760 reinterpret_cast<const jbyte*>(request->data()));
3761 request->Skip(request_length);
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07003762
3763 // Run through and find all chunks. [Currently just find the first.]
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003764 ScopedByteArrayRO contents(env, dataArray.get());
Elliott Hughes4b9702c2013-02-20 18:13:24 -08003765 if (length != request_length) {
Ian Rogersef7d42f2014-01-06 12:55:46 -08003766 LOG(WARNING) << StringPrintf("bad chunk found (len=%u pktLen=%zd)", length, request_length);
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07003767 return false;
3768 }
3769
3770 // Call "private static Chunk dispatch(int type, byte[] data, int offset, int length)".
Elliott Hugheseac76672012-05-24 21:56:51 -07003771 ScopedLocalRef<jobject> chunk(env, env->CallStaticObjectMethod(WellKnownClasses::org_apache_harmony_dalvik_ddmc_DdmServer,
3772 WellKnownClasses::org_apache_harmony_dalvik_ddmc_DdmServer_dispatch,
Elliott Hughes4b9702c2013-02-20 18:13:24 -08003773 type, dataArray.get(), 0, length));
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07003774 if (env->ExceptionCheck()) {
3775 LOG(INFO) << StringPrintf("Exception thrown by dispatcher for 0x%08x", type);
3776 env->ExceptionDescribe();
3777 env->ExceptionClear();
3778 return false;
3779 }
3780
Ian Rogersc0542af2014-09-03 16:16:56 -07003781 if (chunk.get() == nullptr) {
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07003782 return false;
3783 }
3784
3785 /*
3786 * Pull the pieces out of the chunk. We copy the results into a
3787 * newly-allocated buffer that the caller can free. We don't want to
3788 * continue using the Chunk object because nothing has a reference to it.
3789 *
3790 * We could avoid this by returning type/data/offset/length and having
3791 * the caller be aware of the object lifetime issues, but that
Elliott Hughes81ff3182012-03-23 20:35:56 -07003792 * integrates the JDWP code more tightly into the rest of the runtime, and doesn't work
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07003793 * if we have responses for multiple chunks.
3794 *
3795 * So we're pretty much stuck with copying data around multiple times.
3796 */
Elliott Hugheseac76672012-05-24 21:56:51 -07003797 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 -08003798 jint offset = env->GetIntField(chunk.get(), WellKnownClasses::org_apache_harmony_dalvik_ddmc_Chunk_offset);
Elliott Hugheseac76672012-05-24 21:56:51 -07003799 length = env->GetIntField(chunk.get(), WellKnownClasses::org_apache_harmony_dalvik_ddmc_Chunk_length);
Elliott Hugheseac76672012-05-24 21:56:51 -07003800 type = env->GetIntField(chunk.get(), WellKnownClasses::org_apache_harmony_dalvik_ddmc_Chunk_type);
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07003801
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08003802 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 -07003803 if (length == 0 || replyData.get() == nullptr) {
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07003804 return false;
3805 }
3806
Elliott Hughes4b9702c2013-02-20 18:13:24 -08003807 const int kChunkHdrLen = 8;
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07003808 uint8_t* reply = new uint8_t[length + kChunkHdrLen];
Ian Rogersc0542af2014-09-03 16:16:56 -07003809 if (reply == nullptr) {
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07003810 LOG(WARNING) << "malloc failed: " << (length + kChunkHdrLen);
3811 return false;
3812 }
Elliott Hughesf7c3b662011-10-27 12:04:56 -07003813 JDWP::Set4BE(reply + 0, type);
3814 JDWP::Set4BE(reply + 4, length);
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003815 env->GetByteArrayRegion(replyData.get(), offset, length, reinterpret_cast<jbyte*>(reply + kChunkHdrLen));
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07003816
3817 *pReplyBuf = reply;
3818 *pReplyLen = length + kChunkHdrLen;
3819
Elliott Hughes4b9702c2013-02-20 18:13:24 -08003820 VLOG(jdwp) << StringPrintf("dvmHandleDdm returning type=%.4s %p len=%d", reinterpret_cast<char*>(reply), reply, length);
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07003821 return true;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07003822}
3823
Elliott Hughesa2155262011-11-16 16:26:58 -08003824void Dbg::DdmBroadcast(bool connect) {
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08003825 VLOG(jdwp) << "Broadcasting DDM " << (connect ? "connect" : "disconnect") << "...";
Elliott Hughes47fce012011-10-25 18:37:19 -07003826
3827 Thread* self = Thread::Current();
Ian Rogers50b35e22012-10-04 10:09:15 -07003828 if (self->GetState() != kRunnable) {
3829 LOG(ERROR) << "DDM broadcast in thread state " << self->GetState();
3830 /* try anyway? */
Elliott Hughes47fce012011-10-25 18:37:19 -07003831 }
3832
3833 JNIEnv* env = self->GetJniEnv();
Elliott Hughes47fce012011-10-25 18:37:19 -07003834 jint event = connect ? 1 /*DdmServer.CONNECTED*/ : 2 /*DdmServer.DISCONNECTED*/;
Elliott Hugheseac76672012-05-24 21:56:51 -07003835 env->CallStaticVoidMethod(WellKnownClasses::org_apache_harmony_dalvik_ddmc_DdmServer,
3836 WellKnownClasses::org_apache_harmony_dalvik_ddmc_DdmServer_broadcast,
3837 event);
Elliott Hughes47fce012011-10-25 18:37:19 -07003838 if (env->ExceptionCheck()) {
3839 LOG(ERROR) << "DdmServer.broadcast " << event << " failed";
3840 env->ExceptionDescribe();
3841 env->ExceptionClear();
3842 }
3843}
3844
Elliott Hughes872d4ec2011-10-21 17:07:15 -07003845void Dbg::DdmConnected() {
Elliott Hughesa2155262011-11-16 16:26:58 -08003846 Dbg::DdmBroadcast(true);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07003847}
3848
3849void Dbg::DdmDisconnected() {
Elliott Hughesa2155262011-11-16 16:26:58 -08003850 Dbg::DdmBroadcast(false);
Elliott Hughes47fce012011-10-25 18:37:19 -07003851 gDdmThreadNotification = false;
3852}
3853
3854/*
Elliott Hughes82188472011-11-07 18:11:48 -08003855 * Send a notification when a thread starts, stops, or changes its name.
Elliott Hughes47fce012011-10-25 18:37:19 -07003856 *
3857 * Because we broadcast the full set of threads when the notifications are
3858 * first enabled, it's possible for "thread" to be actively executing.
3859 */
Elliott Hughes82188472011-11-07 18:11:48 -08003860void Dbg::DdmSendThreadNotification(Thread* t, uint32_t type) {
Elliott Hughes47fce012011-10-25 18:37:19 -07003861 if (!gDdmThreadNotification) {
3862 return;
3863 }
3864
Elliott Hughes82188472011-11-07 18:11:48 -08003865 if (type == CHUNK_TYPE("THDE")) {
Elliott Hughes47fce012011-10-25 18:37:19 -07003866 uint8_t buf[4];
Ian Rogersd9c4fc92013-10-01 19:45:43 -07003867 JDWP::Set4BE(&buf[0], t->GetThreadId());
Elliott Hughes47fce012011-10-25 18:37:19 -07003868 Dbg::DdmSendChunk(CHUNK_TYPE("THDE"), 4, buf);
Elliott Hughes82188472011-11-07 18:11:48 -08003869 } else {
3870 CHECK(type == CHUNK_TYPE("THCR") || type == CHUNK_TYPE("THNM")) << type;
Ian Rogers00f7d0e2012-07-19 15:28:27 -07003871 ScopedObjectAccessUnchecked soa(Thread::Current());
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003872 StackHandleScope<1> hs(soa.Self());
3873 Handle<mirror::String> name(hs.NewHandle(t->GetThreadName(soa)));
Ian Rogersc0542af2014-09-03 16:16:56 -07003874 size_t char_count = (name.Get() != nullptr) ? name->GetLength() : 0;
3875 const jchar* chars = (name.Get() != nullptr) ? name->GetCharArray()->GetData() : nullptr;
Elliott Hughes82188472011-11-07 18:11:48 -08003876
Elliott Hughes21f32d72011-11-09 17:44:13 -08003877 std::vector<uint8_t> bytes;
Ian Rogersd9c4fc92013-10-01 19:45:43 -07003878 JDWP::Append4BE(bytes, t->GetThreadId());
Elliott Hughes545a0642011-11-08 19:10:03 -08003879 JDWP::AppendUtf16BE(bytes, chars, char_count);
Elliott Hughes21f32d72011-11-09 17:44:13 -08003880 CHECK_EQ(bytes.size(), char_count*2 + sizeof(uint32_t)*2);
3881 Dbg::DdmSendChunk(type, bytes);
Elliott Hughes47fce012011-10-25 18:37:19 -07003882 }
3883}
3884
Elliott Hughes47fce012011-10-25 18:37:19 -07003885void Dbg::DdmSetThreadNotification(bool enable) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07003886 // Enable/disable thread notifications.
Elliott Hughes47fce012011-10-25 18:37:19 -07003887 gDdmThreadNotification = enable;
3888 if (enable) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07003889 // Suspend the VM then post thread start notifications for all threads. Threads attaching will
3890 // see a suspension in progress and block until that ends. They then post their own start
3891 // notification.
3892 SuspendVM();
3893 std::list<Thread*> threads;
Ian Rogers50b35e22012-10-04 10:09:15 -07003894 Thread* self = Thread::Current();
Ian Rogers00f7d0e2012-07-19 15:28:27 -07003895 {
Ian Rogers50b35e22012-10-04 10:09:15 -07003896 MutexLock mu(self, *Locks::thread_list_lock_);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07003897 threads = Runtime::Current()->GetThreadList()->GetList();
3898 }
3899 {
Ian Rogers50b35e22012-10-04 10:09:15 -07003900 ScopedObjectAccess soa(self);
Mathieu Chartier02e25112013-08-14 16:14:24 -07003901 for (Thread* thread : threads) {
3902 Dbg::DdmSendThreadNotification(thread, CHUNK_TYPE("THCR"));
Ian Rogers00f7d0e2012-07-19 15:28:27 -07003903 }
3904 }
3905 ResumeVM();
Elliott Hughes47fce012011-10-25 18:37:19 -07003906 }
3907}
3908
Elliott Hughesa2155262011-11-16 16:26:58 -08003909void Dbg::PostThreadStartOrStop(Thread* t, uint32_t type) {
Elliott Hughesc0f09332012-03-26 13:27:06 -07003910 if (IsDebuggerActive()) {
Mathieu Chartierdbe6f462012-09-25 16:54:50 -07003911 ScopedObjectAccessUnchecked soa(Thread::Current());
Ian Rogerscfaa4552012-11-26 21:00:08 -08003912 JDWP::ObjectId id = gRegistry->Add(t->GetPeer());
Elliott Hughes82188472011-11-07 18:11:48 -08003913 gJdwpState->PostThreadChange(id, type == CHUNK_TYPE("THCR"));
Elliott Hughes47fce012011-10-25 18:37:19 -07003914 }
Elliott Hughes82188472011-11-07 18:11:48 -08003915 Dbg::DdmSendThreadNotification(t, type);
Elliott Hughes47fce012011-10-25 18:37:19 -07003916}
3917
3918void Dbg::PostThreadStart(Thread* t) {
Elliott Hughesa2155262011-11-16 16:26:58 -08003919 Dbg::PostThreadStartOrStop(t, CHUNK_TYPE("THCR"));
Elliott Hughes47fce012011-10-25 18:37:19 -07003920}
3921
3922void Dbg::PostThreadDeath(Thread* t) {
Elliott Hughesa2155262011-11-16 16:26:58 -08003923 Dbg::PostThreadStartOrStop(t, CHUNK_TYPE("THDE"));
Elliott Hughes872d4ec2011-10-21 17:07:15 -07003924}
3925
Elliott Hughes82188472011-11-07 18:11:48 -08003926void Dbg::DdmSendChunk(uint32_t type, size_t byte_count, const uint8_t* buf) {
Ian Rogersc0542af2014-09-03 16:16:56 -07003927 CHECK(buf != nullptr);
Elliott Hughes3bb81562011-10-21 18:52:59 -07003928 iovec vec[1];
3929 vec[0].iov_base = reinterpret_cast<void*>(const_cast<uint8_t*>(buf));
3930 vec[0].iov_len = byte_count;
3931 Dbg::DdmSendChunkV(type, vec, 1);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07003932}
3933
Elliott Hughes21f32d72011-11-09 17:44:13 -08003934void Dbg::DdmSendChunk(uint32_t type, const std::vector<uint8_t>& bytes) {
3935 DdmSendChunk(type, bytes.size(), &bytes[0]);
3936}
3937
Brian Carlstromf5293522013-07-19 00:24:00 -07003938void Dbg::DdmSendChunkV(uint32_t type, const iovec* iov, int iov_count) {
Ian Rogersc0542af2014-09-03 16:16:56 -07003939 if (gJdwpState == nullptr) {
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08003940 VLOG(jdwp) << "Debugger thread not active, ignoring DDM send: " << type;
Elliott Hughes3bb81562011-10-21 18:52:59 -07003941 } else {
Elliott Hughescccd84f2011-12-05 16:51:54 -08003942 gJdwpState->DdmSendChunkV(type, iov, iov_count);
Elliott Hughes3bb81562011-10-21 18:52:59 -07003943 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -07003944}
3945
Elliott Hughes767a1472011-10-26 18:49:02 -07003946int Dbg::DdmHandleHpifChunk(HpifWhen when) {
3947 if (when == HPIF_WHEN_NOW) {
Elliott Hughes7162ad92011-10-27 14:08:42 -07003948 DdmSendHeapInfo(when);
Elliott Hughes767a1472011-10-26 18:49:02 -07003949 return true;
3950 }
3951
3952 if (when != HPIF_WHEN_NEVER && when != HPIF_WHEN_NEXT_GC && when != HPIF_WHEN_EVERY_GC) {
3953 LOG(ERROR) << "invalid HpifWhen value: " << static_cast<int>(when);
3954 return false;
3955 }
3956
3957 gDdmHpifWhen = when;
3958 return true;
3959}
3960
3961bool Dbg::DdmHandleHpsgNhsgChunk(Dbg::HpsgWhen when, Dbg::HpsgWhat what, bool native) {
3962 if (when != HPSG_WHEN_NEVER && when != HPSG_WHEN_EVERY_GC) {
3963 LOG(ERROR) << "invalid HpsgWhen value: " << static_cast<int>(when);
3964 return false;
3965 }
3966
3967 if (what != HPSG_WHAT_MERGED_OBJECTS && what != HPSG_WHAT_DISTINCT_OBJECTS) {
3968 LOG(ERROR) << "invalid HpsgWhat value: " << static_cast<int>(what);
3969 return false;
3970 }
3971
3972 if (native) {
3973 gDdmNhsgWhen = when;
3974 gDdmNhsgWhat = what;
3975 } else {
3976 gDdmHpsgWhen = when;
3977 gDdmHpsgWhat = what;
3978 }
3979 return true;
3980}
3981
Elliott Hughes7162ad92011-10-27 14:08:42 -07003982void Dbg::DdmSendHeapInfo(HpifWhen reason) {
3983 // If there's a one-shot 'when', reset it.
3984 if (reason == gDdmHpifWhen) {
3985 if (gDdmHpifWhen == HPIF_WHEN_NEXT_GC) {
3986 gDdmHpifWhen = HPIF_WHEN_NEVER;
3987 }
3988 }
3989
3990 /*
3991 * Chunk HPIF (client --> server)
3992 *
3993 * Heap Info. General information about the heap,
3994 * suitable for a summary display.
3995 *
3996 * [u4]: number of heaps
3997 *
3998 * For each heap:
3999 * [u4]: heap ID
4000 * [u8]: timestamp in ms since Unix epoch
4001 * [u1]: capture reason (same as 'when' value from server)
4002 * [u4]: max heap size in bytes (-Xmx)
4003 * [u4]: current heap size in bytes
4004 * [u4]: current number of bytes allocated
4005 * [u4]: current number of objects allocated
4006 */
4007 uint8_t heap_count = 1;
Ian Rogers1d54e732013-05-02 21:10:01 -07004008 gc::Heap* heap = Runtime::Current()->GetHeap();
Elliott Hughes21f32d72011-11-09 17:44:13 -08004009 std::vector<uint8_t> bytes;
Elliott Hughes545a0642011-11-08 19:10:03 -08004010 JDWP::Append4BE(bytes, heap_count);
Brian Carlstrom7934ac22013-07-26 10:54:15 -07004011 JDWP::Append4BE(bytes, 1); // Heap id (bogus; we only have one heap).
Elliott Hughes545a0642011-11-08 19:10:03 -08004012 JDWP::Append8BE(bytes, MilliTime());
4013 JDWP::Append1BE(bytes, reason);
Brian Carlstrom7934ac22013-07-26 10:54:15 -07004014 JDWP::Append4BE(bytes, heap->GetMaxMemory()); // Max allowed heap size in bytes.
4015 JDWP::Append4BE(bytes, heap->GetTotalMemory()); // Current heap size in bytes.
Elliott Hughesb3bd5f02012-03-08 21:05:27 -08004016 JDWP::Append4BE(bytes, heap->GetBytesAllocated());
4017 JDWP::Append4BE(bytes, heap->GetObjectsAllocated());
Elliott Hughes21f32d72011-11-09 17:44:13 -08004018 CHECK_EQ(bytes.size(), 4U + (heap_count * (4 + 8 + 1 + 4 + 4 + 4 + 4)));
4019 Dbg::DdmSendChunk(CHUNK_TYPE("HPIF"), bytes);
Elliott Hughes767a1472011-10-26 18:49:02 -07004020}
4021
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004022enum HpsgSolidity {
4023 SOLIDITY_FREE = 0,
4024 SOLIDITY_HARD = 1,
4025 SOLIDITY_SOFT = 2,
4026 SOLIDITY_WEAK = 3,
4027 SOLIDITY_PHANTOM = 4,
4028 SOLIDITY_FINALIZABLE = 5,
4029 SOLIDITY_SWEEP = 6,
4030};
4031
4032enum HpsgKind {
4033 KIND_OBJECT = 0,
4034 KIND_CLASS_OBJECT = 1,
4035 KIND_ARRAY_1 = 2,
4036 KIND_ARRAY_2 = 3,
4037 KIND_ARRAY_4 = 4,
4038 KIND_ARRAY_8 = 5,
4039 KIND_UNKNOWN = 6,
4040 KIND_NATIVE = 7,
4041};
4042
4043#define HPSG_PARTIAL (1<<7)
4044#define HPSG_STATE(solidity, kind) ((uint8_t)((((kind) & 0x7) << 3) | ((solidity) & 0x7)))
4045
Ian Rogers30fab402012-01-23 15:43:46 -08004046class HeapChunkContext {
4047 public:
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004048 // Maximum chunk size. Obtain this from the formula:
4049 // (((maximum_heap_size / ALLOCATION_UNIT_SIZE) + 255) / 256) * 2
4050 HeapChunkContext(bool merge, bool native)
Ian Rogers30fab402012-01-23 15:43:46 -08004051 : buf_(16384 - 16),
4052 type_(0),
Mathieu Chartier36dab362014-07-30 14:59:56 -07004053 merge_(merge),
4054 chunk_overhead_(0) {
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004055 Reset();
4056 if (native) {
Ian Rogers30fab402012-01-23 15:43:46 -08004057 type_ = CHUNK_TYPE("NHSG");
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004058 } else {
Ian Rogers30fab402012-01-23 15:43:46 -08004059 type_ = merge ? CHUNK_TYPE("HPSG") : CHUNK_TYPE("HPSO");
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004060 }
4061 }
4062
4063 ~HeapChunkContext() {
Ian Rogers30fab402012-01-23 15:43:46 -08004064 if (p_ > &buf_[0]) {
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004065 Flush();
4066 }
4067 }
4068
Mathieu Chartier36dab362014-07-30 14:59:56 -07004069 void SetChunkOverhead(size_t chunk_overhead) {
4070 chunk_overhead_ = chunk_overhead;
4071 }
4072
4073 void ResetStartOfNextChunk() {
4074 startOfNextMemoryChunk_ = nullptr;
4075 }
4076
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004077 void EnsureHeader(const void* chunk_ptr) {
Ian Rogers30fab402012-01-23 15:43:46 -08004078 if (!needHeader_) {
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004079 return;
4080 }
4081
4082 // Start a new HPSx chunk.
Brian Carlstrom7934ac22013-07-26 10:54:15 -07004083 JDWP::Write4BE(&p_, 1); // Heap id (bogus; we only have one heap).
4084 JDWP::Write1BE(&p_, 8); // Size of allocation unit, in bytes.
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004085
Brian Carlstrom7934ac22013-07-26 10:54:15 -07004086 JDWP::Write4BE(&p_, reinterpret_cast<uintptr_t>(chunk_ptr)); // virtual address of segment start.
4087 JDWP::Write4BE(&p_, 0); // offset of this piece (relative to the virtual address).
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004088 // [u4]: length of piece, in allocation units
4089 // 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 -08004090 pieceLenField_ = p_;
4091 JDWP::Write4BE(&p_, 0x55555555);
4092 needHeader_ = false;
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004093 }
4094
Ian Rogersb726dcb2012-09-05 08:57:23 -07004095 void Flush() SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Ian Rogersc0542af2014-09-03 16:16:56 -07004096 if (pieceLenField_ == nullptr) {
Ian Rogersd636b062013-01-18 17:51:18 -08004097 // Flush immediately post Reset (maybe back-to-back Flush). Ignore.
4098 CHECK(needHeader_);
4099 return;
4100 }
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004101 // Patch the "length of piece" field.
Ian Rogers30fab402012-01-23 15:43:46 -08004102 CHECK_LE(&buf_[0], pieceLenField_);
4103 CHECK_LE(pieceLenField_, p_);
4104 JDWP::Set4BE(pieceLenField_, totalAllocationUnits_);
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004105
Ian Rogers30fab402012-01-23 15:43:46 -08004106 Dbg::DdmSendChunk(type_, p_ - &buf_[0], &buf_[0]);
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004107 Reset();
4108 }
4109
Ian Rogers00f7d0e2012-07-19 15:28:27 -07004110 static void HeapChunkCallback(void* start, void* end, size_t used_bytes, void* arg)
Ian Rogersb726dcb2012-09-05 08:57:23 -07004111 SHARED_LOCKS_REQUIRED(Locks::heap_bitmap_lock_,
4112 Locks::mutator_lock_) {
Ian Rogers30fab402012-01-23 15:43:46 -08004113 reinterpret_cast<HeapChunkContext*>(arg)->HeapChunkCallback(start, end, used_bytes);
Elliott Hughesa2155262011-11-16 16:26:58 -08004114 }
4115
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004116 private:
Elliott Hughesa2155262011-11-16 16:26:58 -08004117 enum { ALLOCATION_UNIT_SIZE = 8 };
4118
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004119 void Reset() {
Ian Rogers30fab402012-01-23 15:43:46 -08004120 p_ = &buf_[0];
Mathieu Chartier36dab362014-07-30 14:59:56 -07004121 ResetStartOfNextChunk();
Ian Rogers30fab402012-01-23 15:43:46 -08004122 totalAllocationUnits_ = 0;
4123 needHeader_ = true;
Ian Rogersc0542af2014-09-03 16:16:56 -07004124 pieceLenField_ = nullptr;
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004125 }
4126
Ian Rogers00f7d0e2012-07-19 15:28:27 -07004127 void HeapChunkCallback(void* start, void* /*end*/, size_t used_bytes)
Ian Rogersb726dcb2012-09-05 08:57:23 -07004128 SHARED_LOCKS_REQUIRED(Locks::heap_bitmap_lock_,
4129 Locks::mutator_lock_) {
Ian Rogers30fab402012-01-23 15:43:46 -08004130 // Note: heap call backs cannot manipulate the heap upon which they are crawling, care is taken
4131 // in the following code not to allocate memory, by ensuring buf_ is of the correct size
Ian Rogers15bf2d32012-08-28 17:33:04 -07004132 if (used_bytes == 0) {
Ian Rogersc0542af2014-09-03 16:16:56 -07004133 if (start == nullptr) {
Ian Rogers15bf2d32012-08-28 17:33:04 -07004134 // Reset for start of new heap.
Ian Rogersc0542af2014-09-03 16:16:56 -07004135 startOfNextMemoryChunk_ = nullptr;
Ian Rogers15bf2d32012-08-28 17:33:04 -07004136 Flush();
4137 }
4138 // Only process in use memory so that free region information
4139 // also includes dlmalloc book keeping.
Elliott Hughesa2155262011-11-16 16:26:58 -08004140 return;
Elliott Hughesa2155262011-11-16 16:26:58 -08004141 }
4142
Ian Rogers15bf2d32012-08-28 17:33:04 -07004143 /* If we're looking at the native heap, we'll just return
4144 * (SOLIDITY_HARD, KIND_NATIVE) for all allocated chunks
4145 */
4146 bool native = type_ == CHUNK_TYPE("NHSG");
4147
Mathieu Chartier36dab362014-07-30 14:59:56 -07004148 // TODO: I'm not sure using start of next chunk works well with multiple spaces. We shouldn't
4149 // count gaps inbetween spaces as free memory.
Ian Rogersc0542af2014-09-03 16:16:56 -07004150 if (startOfNextMemoryChunk_ != nullptr) {
Ian Rogers15bf2d32012-08-28 17:33:04 -07004151 // Transmit any pending free memory. Native free memory of
4152 // over kMaxFreeLen could be because of the use of mmaps, so
4153 // don't report. If not free memory then start a new segment.
4154 bool flush = true;
4155 if (start > startOfNextMemoryChunk_) {
4156 const size_t kMaxFreeLen = 2 * kPageSize;
4157 void* freeStart = startOfNextMemoryChunk_;
4158 void* freeEnd = start;
Brian Carlstrom2d888622013-07-18 17:02:00 -07004159 size_t freeLen = reinterpret_cast<char*>(freeEnd) - reinterpret_cast<char*>(freeStart);
Ian Rogers15bf2d32012-08-28 17:33:04 -07004160 if (!native || freeLen < kMaxFreeLen) {
4161 AppendChunk(HPSG_STATE(SOLIDITY_FREE, 0), freeStart, freeLen);
4162 flush = false;
4163 }
4164 }
4165 if (flush) {
Ian Rogersc0542af2014-09-03 16:16:56 -07004166 startOfNextMemoryChunk_ = nullptr;
Ian Rogers15bf2d32012-08-28 17:33:04 -07004167 Flush();
4168 }
4169 }
Ian Rogersef7d42f2014-01-06 12:55:46 -08004170 mirror::Object* obj = reinterpret_cast<mirror::Object*>(start);
Elliott Hughesa2155262011-11-16 16:26:58 -08004171
4172 // Determine the type of this chunk.
4173 // OLD-TODO: if context.merge, see if this chunk is different from the last chunk.
4174 // If it's the same, we should combine them.
Ian Rogers15bf2d32012-08-28 17:33:04 -07004175 uint8_t state = ExamineObject(obj, native);
Mathieu Chartier36dab362014-07-30 14:59:56 -07004176 AppendChunk(state, start, used_bytes + chunk_overhead_);
4177 startOfNextMemoryChunk_ = reinterpret_cast<char*>(start) + used_bytes + chunk_overhead_;
Ian Rogers15bf2d32012-08-28 17:33:04 -07004178 }
Elliott Hughesa2155262011-11-16 16:26:58 -08004179
Ian Rogers15bf2d32012-08-28 17:33:04 -07004180 void AppendChunk(uint8_t state, void* ptr, size_t length)
Ian Rogersb726dcb2012-09-05 08:57:23 -07004181 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Ian Rogers15bf2d32012-08-28 17:33:04 -07004182 // Make sure there's enough room left in the buffer.
4183 // We need to use two bytes for every fractional 256 allocation units used by the chunk plus
4184 // 17 bytes for any header.
4185 size_t needed = (((length/ALLOCATION_UNIT_SIZE + 255) / 256) * 2) + 17;
4186 size_t bytesLeft = buf_.size() - (size_t)(p_ - &buf_[0]);
4187 if (bytesLeft < needed) {
4188 Flush();
4189 }
4190
4191 bytesLeft = buf_.size() - (size_t)(p_ - &buf_[0]);
4192 if (bytesLeft < needed) {
4193 LOG(WARNING) << "Chunk is too big to transmit (chunk_len=" << length << ", "
4194 << needed << " bytes)";
4195 return;
4196 }
4197 EnsureHeader(ptr);
Elliott Hughesa2155262011-11-16 16:26:58 -08004198 // Write out the chunk description.
Ian Rogers15bf2d32012-08-28 17:33:04 -07004199 length /= ALLOCATION_UNIT_SIZE; // Convert to allocation units.
4200 totalAllocationUnits_ += length;
4201 while (length > 256) {
Ian Rogers30fab402012-01-23 15:43:46 -08004202 *p_++ = state | HPSG_PARTIAL;
4203 *p_++ = 255; // length - 1
Ian Rogers15bf2d32012-08-28 17:33:04 -07004204 length -= 256;
Elliott Hughesa2155262011-11-16 16:26:58 -08004205 }
Ian Rogers30fab402012-01-23 15:43:46 -08004206 *p_++ = state;
Ian Rogers15bf2d32012-08-28 17:33:04 -07004207 *p_++ = length - 1;
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004208 }
4209
Ian Rogersef7d42f2014-01-06 12:55:46 -08004210 uint8_t ExamineObject(mirror::Object* o, bool is_native_heap)
4211 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_, Locks::heap_bitmap_lock_) {
Ian Rogersc0542af2014-09-03 16:16:56 -07004212 if (o == nullptr) {
Elliott Hughesa2155262011-11-16 16:26:58 -08004213 return HPSG_STATE(SOLIDITY_FREE, 0);
4214 }
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004215
Elliott Hughesa2155262011-11-16 16:26:58 -08004216 // It's an allocated chunk. Figure out what it is.
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004217
Elliott Hughesa2155262011-11-16 16:26:58 -08004218 // If we're looking at the native heap, we'll just return
4219 // (SOLIDITY_HARD, KIND_NATIVE) for all allocated chunks.
Ian Rogers00f7d0e2012-07-19 15:28:27 -07004220 if (is_native_heap) {
Elliott Hughesa2155262011-11-16 16:26:58 -08004221 return HPSG_STATE(SOLIDITY_HARD, KIND_NATIVE);
4222 }
4223
Ian Rogers5bfa60f2012-09-02 21:17:56 -07004224 if (!Runtime::Current()->GetHeap()->IsLiveObjectLocked(o)) {
Ian Rogers15bf2d32012-08-28 17:33:04 -07004225 return HPSG_STATE(SOLIDITY_HARD, KIND_NATIVE);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07004226 }
4227
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08004228 mirror::Class* c = o->GetClass();
Ian Rogersc0542af2014-09-03 16:16:56 -07004229 if (c == nullptr) {
Elliott Hughesa2155262011-11-16 16:26:58 -08004230 // The object was probably just created but hasn't been initialized yet.
4231 return HPSG_STATE(SOLIDITY_HARD, KIND_OBJECT);
4232 }
4233
Mathieu Chartier590fee92013-09-13 13:46:47 -07004234 if (!Runtime::Current()->GetHeap()->IsValidObjectAddress(c)) {
Ian Rogers15bf2d32012-08-28 17:33:04 -07004235 LOG(ERROR) << "Invalid class for managed heap object: " << o << " " << c;
Elliott Hughesa2155262011-11-16 16:26:58 -08004236 return HPSG_STATE(SOLIDITY_HARD, KIND_UNKNOWN);
4237 }
4238
4239 if (c->IsClassClass()) {
4240 return HPSG_STATE(SOLIDITY_HARD, KIND_CLASS_OBJECT);
4241 }
4242
4243 if (c->IsArrayClass()) {
4244 if (o->IsObjectArray()) {
4245 return HPSG_STATE(SOLIDITY_HARD, KIND_ARRAY_4);
4246 }
4247 switch (c->GetComponentSize()) {
4248 case 1: return HPSG_STATE(SOLIDITY_HARD, KIND_ARRAY_1);
4249 case 2: return HPSG_STATE(SOLIDITY_HARD, KIND_ARRAY_2);
4250 case 4: return HPSG_STATE(SOLIDITY_HARD, KIND_ARRAY_4);
4251 case 8: return HPSG_STATE(SOLIDITY_HARD, KIND_ARRAY_8);
4252 }
4253 }
4254
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004255 return HPSG_STATE(SOLIDITY_HARD, KIND_OBJECT);
4256 }
4257
Ian Rogers30fab402012-01-23 15:43:46 -08004258 std::vector<uint8_t> buf_;
4259 uint8_t* p_;
4260 uint8_t* pieceLenField_;
Ian Rogers15bf2d32012-08-28 17:33:04 -07004261 void* startOfNextMemoryChunk_;
Ian Rogers30fab402012-01-23 15:43:46 -08004262 size_t totalAllocationUnits_;
4263 uint32_t type_;
4264 bool merge_;
4265 bool needHeader_;
Mathieu Chartier36dab362014-07-30 14:59:56 -07004266 size_t chunk_overhead_;
Ian Rogers30fab402012-01-23 15:43:46 -08004267
Elliott Hughesa2155262011-11-16 16:26:58 -08004268 DISALLOW_COPY_AND_ASSIGN(HeapChunkContext);
4269};
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004270
Mathieu Chartier36dab362014-07-30 14:59:56 -07004271static void BumpPointerSpaceCallback(mirror::Object* obj, void* arg)
4272 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) EXCLUSIVE_LOCKS_REQUIRED(Locks::heap_bitmap_lock_) {
4273 const size_t size = RoundUp(obj->SizeOf(), kObjectAlignment);
4274 HeapChunkContext::HeapChunkCallback(
4275 obj, reinterpret_cast<void*>(reinterpret_cast<uintptr_t>(obj) + size), size, arg);
4276}
4277
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004278void Dbg::DdmSendHeapSegments(bool native) {
4279 Dbg::HpsgWhen when;
4280 Dbg::HpsgWhat what;
4281 if (!native) {
4282 when = gDdmHpsgWhen;
4283 what = gDdmHpsgWhat;
4284 } else {
4285 when = gDdmNhsgWhen;
4286 what = gDdmNhsgWhat;
4287 }
4288 if (when == HPSG_WHEN_NEVER) {
4289 return;
4290 }
4291
4292 // Figure out what kind of chunks we'll be sending.
4293 CHECK(what == HPSG_WHAT_MERGED_OBJECTS || what == HPSG_WHAT_DISTINCT_OBJECTS) << static_cast<int>(what);
4294
4295 // First, send a heap start chunk.
4296 uint8_t heap_id[4];
Brian Carlstrom7934ac22013-07-26 10:54:15 -07004297 JDWP::Set4BE(&heap_id[0], 1); // Heap id (bogus; we only have one heap).
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004298 Dbg::DdmSendChunk(native ? CHUNK_TYPE("NHST") : CHUNK_TYPE("HPST"), sizeof(heap_id), heap_id);
4299
Hiroshi Yamauchicf58d4a2013-09-26 14:21:22 -07004300 Thread* self = Thread::Current();
4301
4302 // To allow the Walk/InspectAll() below to exclusively-lock the
4303 // mutator lock, temporarily release the shared access to the
4304 // mutator lock here by transitioning to the suspended state.
4305 Locks::mutator_lock_->AssertSharedHeld(self);
4306 self->TransitionFromRunnableToSuspended(kSuspended);
4307
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004308 // Send a series of heap segment chunks.
Elliott Hughesa2155262011-11-16 16:26:58 -08004309 HeapChunkContext context((what == HPSG_WHAT_MERGED_OBJECTS), native);
4310 if (native) {
Christopher Ferrisc4ddc042014-05-13 14:47:50 -07004311#ifdef USE_DLMALLOC
Ian Rogers1d54e732013-05-02 21:10:01 -07004312 dlmalloc_inspect_all(HeapChunkContext::HeapChunkCallback, &context);
Christopher Ferrisc4ddc042014-05-13 14:47:50 -07004313#else
4314 UNIMPLEMENTED(WARNING) << "Native heap inspection is only supported with dlmalloc";
4315#endif
Elliott Hughesa2155262011-11-16 16:26:58 -08004316 } else {
Ian Rogers1d54e732013-05-02 21:10:01 -07004317 gc::Heap* heap = Runtime::Current()->GetHeap();
Mathieu Chartier36dab362014-07-30 14:59:56 -07004318 for (const auto& space : heap->GetContinuousSpaces()) {
4319 if (space->IsDlMallocSpace()) {
4320 // dlmalloc's chunk header is 2 * sizeof(size_t), but if the previous chunk is in use for an
4321 // allocation then the first sizeof(size_t) may belong to it.
4322 context.SetChunkOverhead(sizeof(size_t));
4323 space->AsDlMallocSpace()->Walk(HeapChunkContext::HeapChunkCallback, &context);
4324 } else if (space->IsRosAllocSpace()) {
4325 context.SetChunkOverhead(0);
4326 space->AsRosAllocSpace()->Walk(HeapChunkContext::HeapChunkCallback, &context);
4327 } else if (space->IsBumpPointerSpace()) {
4328 context.SetChunkOverhead(0);
4329 ReaderMutexLock mu(self, *Locks::mutator_lock_);
4330 WriterMutexLock mu2(self, *Locks::heap_bitmap_lock_);
4331 space->AsBumpPointerSpace()->Walk(BumpPointerSpaceCallback, &context);
4332 } else {
4333 UNIMPLEMENTED(WARNING) << "Not counting objects in space " << *space;
Mathieu Chartierb062fdd2012-07-03 09:51:48 -07004334 }
Mathieu Chartier36dab362014-07-30 14:59:56 -07004335 context.ResetStartOfNextChunk();
Mathieu Chartierb062fdd2012-07-03 09:51:48 -07004336 }
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -07004337 // Walk the large objects, these are not in the AllocSpace.
Mathieu Chartier36dab362014-07-30 14:59:56 -07004338 context.SetChunkOverhead(0);
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -07004339 heap->GetLargeObjectsSpace()->Walk(HeapChunkContext::HeapChunkCallback, &context);
Elliott Hughesa2155262011-11-16 16:26:58 -08004340 }
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004341
Hiroshi Yamauchicf58d4a2013-09-26 14:21:22 -07004342 // Shared-lock the mutator lock back.
4343 self->TransitionFromSuspendedToRunnable();
4344 Locks::mutator_lock_->AssertSharedHeld(self);
4345
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004346 // Finally, send a heap end chunk.
4347 Dbg::DdmSendChunk(native ? CHUNK_TYPE("NHEN") : CHUNK_TYPE("HPEN"), sizeof(heap_id), heap_id);
Elliott Hughes767a1472011-10-26 18:49:02 -07004348}
4349
Elliott Hughesb1a58792013-07-11 18:10:58 -07004350static size_t GetAllocTrackerMax() {
4351#ifdef HAVE_ANDROID_OS
4352 // Check whether there's a system property overriding the number of records.
4353 const char* propertyName = "dalvik.vm.allocTrackerMax";
4354 char allocRecordMaxString[PROPERTY_VALUE_MAX];
4355 if (property_get(propertyName, allocRecordMaxString, "") > 0) {
4356 char* end;
4357 size_t value = strtoul(allocRecordMaxString, &end, 10);
4358 if (*end != '\0') {
Ruben Brunk3e47a742013-09-09 17:56:07 -07004359 LOG(ERROR) << "Ignoring " << propertyName << " '" << allocRecordMaxString
4360 << "' --- invalid";
Elliott Hughesb1a58792013-07-11 18:10:58 -07004361 return kDefaultNumAllocRecords;
4362 }
4363 if (!IsPowerOfTwo(value)) {
Ruben Brunk3e47a742013-09-09 17:56:07 -07004364 LOG(ERROR) << "Ignoring " << propertyName << " '" << allocRecordMaxString
4365 << "' --- not power of two";
Elliott Hughesb1a58792013-07-11 18:10:58 -07004366 return kDefaultNumAllocRecords;
4367 }
4368 return value;
4369 }
4370#endif
4371 return kDefaultNumAllocRecords;
4372}
4373
Brian Carlstrom306db812014-09-05 13:01:41 -07004374void Dbg::SetAllocTrackingEnabled(bool enable) {
4375 Thread* self = Thread::Current();
4376 if (enable) {
Sebastien Hertzb98063a2014-03-26 10:57:20 +01004377 {
Brian Carlstrom306db812014-09-05 13:01:41 -07004378 MutexLock mu(self, *Locks::alloc_tracker_lock_);
4379 if (recent_allocation_records_ != nullptr) {
4380 return; // Already enabled, bail.
Sebastien Hertzb98063a2014-03-26 10:57:20 +01004381 }
Brian Carlstrom306db812014-09-05 13:01:41 -07004382 alloc_record_max_ = GetAllocTrackerMax();
4383 LOG(INFO) << "Enabling alloc tracker (" << alloc_record_max_ << " entries of "
4384 << kMaxAllocRecordStackDepth << " frames, taking "
4385 << PrettySize(sizeof(AllocRecord) * alloc_record_max_) << ")";
4386 DCHECK_EQ(alloc_record_head_, 0U);
4387 DCHECK_EQ(alloc_record_count_, 0U);
4388 recent_allocation_records_ = new AllocRecord[alloc_record_max_];
4389 CHECK(recent_allocation_records_ != nullptr);
Elliott Hughes545a0642011-11-08 19:10:03 -08004390 }
Jeff Hao69dbec62014-09-15 18:03:41 -07004391 Runtime::Current()->GetInstrumentation()->InstrumentQuickAllocEntryPoints(false);
Elliott Hughes545a0642011-11-08 19:10:03 -08004392 } else {
Sebastien Hertzb98063a2014-03-26 10:57:20 +01004393 {
Brian Carlstrom306db812014-09-05 13:01:41 -07004394 ScopedObjectAccess soa(self); // For type_cache_.Clear();
4395 MutexLock mu(self, *Locks::alloc_tracker_lock_);
4396 if (recent_allocation_records_ == nullptr) {
4397 return; // Already disabled, bail.
4398 }
Mathieu Chartier4345c462014-06-27 10:20:14 -07004399 LOG(INFO) << "Disabling alloc tracker";
Sebastien Hertzb98063a2014-03-26 10:57:20 +01004400 delete[] recent_allocation_records_;
Ian Rogersc0542af2014-09-03 16:16:56 -07004401 recent_allocation_records_ = nullptr;
Brian Carlstrom306db812014-09-05 13:01:41 -07004402 alloc_record_head_ = 0;
4403 alloc_record_count_ = 0;
Mathieu Chartier4345c462014-06-27 10:20:14 -07004404 type_cache_.Clear();
Sebastien Hertzb98063a2014-03-26 10:57:20 +01004405 }
Brian Carlstrom306db812014-09-05 13:01:41 -07004406 // If an allocation comes in before we uninstrument, we will safely drop it on the floor.
Jeff Hao69dbec62014-09-15 18:03:41 -07004407 Runtime::Current()->GetInstrumentation()->UninstrumentQuickAllocEntryPoints(false);
Elliott Hughes545a0642011-11-08 19:10:03 -08004408 }
4409}
4410
Ian Rogers0399dde2012-06-06 17:09:28 -07004411struct AllocRecordStackVisitor : public StackVisitor {
Ian Rogers7a22fa62013-01-23 12:16:16 -08004412 AllocRecordStackVisitor(Thread* thread, AllocRecord* record)
Ian Rogersb726dcb2012-09-05 08:57:23 -07004413 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_)
Ian Rogersc0542af2014-09-03 16:16:56 -07004414 : StackVisitor(thread, nullptr), record(record), depth(0) {}
Elliott Hughes545a0642011-11-08 19:10:03 -08004415
Ian Rogers00f7d0e2012-07-19 15:28:27 -07004416 // TODO: Enable annotalysis. We know lock is held in constructor, but abstraction confuses
4417 // annotalysis.
4418 bool VisitFrame() NO_THREAD_SAFETY_ANALYSIS {
Elliott Hughes545a0642011-11-08 19:10:03 -08004419 if (depth >= kMaxAllocRecordStackDepth) {
Elliott Hughes530fa002012-03-12 11:44:49 -07004420 return false;
Elliott Hughes545a0642011-11-08 19:10:03 -08004421 }
Brian Carlstromea46f952013-07-30 01:26:50 -07004422 mirror::ArtMethod* m = GetMethod();
Ian Rogers0399dde2012-06-06 17:09:28 -07004423 if (!m->IsRuntimeMethod()) {
Hiroshi Yamauchib5a9e3d2014-06-09 12:11:20 -07004424 record->StackElement(depth)->SetMethod(m);
4425 record->StackElement(depth)->SetDexPc(GetDexPc());
Elliott Hughes530fa002012-03-12 11:44:49 -07004426 ++depth;
Elliott Hughes545a0642011-11-08 19:10:03 -08004427 }
Elliott Hughes530fa002012-03-12 11:44:49 -07004428 return true;
Elliott Hughes545a0642011-11-08 19:10:03 -08004429 }
4430
4431 ~AllocRecordStackVisitor() {
4432 // Clear out any unused stack trace elements.
4433 for (; depth < kMaxAllocRecordStackDepth; ++depth) {
Hiroshi Yamauchib5a9e3d2014-06-09 12:11:20 -07004434 record->StackElement(depth)->SetMethod(nullptr);
4435 record->StackElement(depth)->SetDexPc(0);
Elliott Hughes545a0642011-11-08 19:10:03 -08004436 }
4437 }
4438
4439 AllocRecord* record;
4440 size_t depth;
4441};
4442
Ian Rogers844506b2014-09-12 19:59:33 -07004443void Dbg::RecordAllocation(Thread* self, mirror::Class* type, size_t byte_count) {
Brian Carlstrom306db812014-09-05 13:01:41 -07004444 MutexLock mu(self, *Locks::alloc_tracker_lock_);
Ian Rogersc0542af2014-09-03 16:16:56 -07004445 if (recent_allocation_records_ == nullptr) {
Brian Carlstrom306db812014-09-05 13:01:41 -07004446 // In the process of shutting down recording, bail.
Elliott Hughes545a0642011-11-08 19:10:03 -08004447 return;
4448 }
4449
4450 // Advance and clip.
Ian Rogers719d1a32014-03-06 12:13:39 -08004451 if (++alloc_record_head_ == alloc_record_max_) {
4452 alloc_record_head_ = 0;
Elliott Hughes545a0642011-11-08 19:10:03 -08004453 }
4454
4455 // Fill in the basics.
Ian Rogers719d1a32014-03-06 12:13:39 -08004456 AllocRecord* record = &recent_allocation_records_[alloc_record_head_];
Hiroshi Yamauchib5a9e3d2014-06-09 12:11:20 -07004457 record->SetType(type);
4458 record->SetByteCount(byte_count);
4459 record->SetThinLockId(self->GetThreadId());
Elliott Hughes545a0642011-11-08 19:10:03 -08004460
4461 // Fill in the stack trace.
Ian Rogers7a22fa62013-01-23 12:16:16 -08004462 AllocRecordStackVisitor visitor(self, record);
Ian Rogers0399dde2012-06-06 17:09:28 -07004463 visitor.WalkStack();
Elliott Hughes545a0642011-11-08 19:10:03 -08004464
Ian Rogers719d1a32014-03-06 12:13:39 -08004465 if (alloc_record_count_ < alloc_record_max_) {
4466 ++alloc_record_count_;
Elliott Hughes545a0642011-11-08 19:10:03 -08004467 }
4468}
4469
Elliott Hughesa8f93cb2012-06-08 17:08:48 -07004470// Returns the index of the head element.
4471//
Brian Carlstrom306db812014-09-05 13:01:41 -07004472// We point at the most-recently-written record, so if alloc_record_count_ is 1
Elliott Hughesa8f93cb2012-06-08 17:08:48 -07004473// we want to use the current element. Take "head+1" and subtract count
4474// from it.
4475//
4476// We need to handle underflow in our circular buffer, so we add
Brian Carlstrom306db812014-09-05 13:01:41 -07004477// alloc_record_max_ and then mask it back down.
Ian Rogers719d1a32014-03-06 12:13:39 -08004478size_t Dbg::HeadIndex() {
4479 return (Dbg::alloc_record_head_ + 1 + Dbg::alloc_record_max_ - Dbg::alloc_record_count_) &
4480 (Dbg::alloc_record_max_ - 1);
Elliott Hughes545a0642011-11-08 19:10:03 -08004481}
4482
4483void Dbg::DumpRecentAllocations() {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07004484 ScopedObjectAccess soa(Thread::Current());
Brian Carlstrom306db812014-09-05 13:01:41 -07004485 MutexLock mu(soa.Self(), *Locks::alloc_tracker_lock_);
Ian Rogersc0542af2014-09-03 16:16:56 -07004486 if (recent_allocation_records_ == nullptr) {
Elliott Hughes545a0642011-11-08 19:10:03 -08004487 LOG(INFO) << "Not recording tracked allocations";
4488 return;
4489 }
4490
4491 // "i" is the head of the list. We want to start at the end of the
4492 // list and move forward to the tail.
Elliott Hughesa8f93cb2012-06-08 17:08:48 -07004493 size_t i = HeadIndex();
Brian Carlstrom306db812014-09-05 13:01:41 -07004494 const uint16_t capped_count = CappedAllocRecordCount(Dbg::alloc_record_count_);
4495 uint16_t count = capped_count;
Elliott Hughes545a0642011-11-08 19:10:03 -08004496
Ian Rogers719d1a32014-03-06 12:13:39 -08004497 LOG(INFO) << "Tracked allocations, (head=" << alloc_record_head_ << " count=" << count << ")";
Elliott Hughes545a0642011-11-08 19:10:03 -08004498 while (count--) {
4499 AllocRecord* record = &recent_allocation_records_[i];
4500
Hiroshi Yamauchib5a9e3d2014-06-09 12:11:20 -07004501 LOG(INFO) << StringPrintf(" Thread %-2d %6zd bytes ", record->ThinLockId(), record->ByteCount())
4502 << PrettyClass(record->Type());
Elliott Hughes545a0642011-11-08 19:10:03 -08004503
4504 for (size_t stack_frame = 0; stack_frame < kMaxAllocRecordStackDepth; ++stack_frame) {
Hiroshi Yamauchib5a9e3d2014-06-09 12:11:20 -07004505 AllocRecordStackTraceElement* stack_element = record->StackElement(stack_frame);
4506 mirror::ArtMethod* m = stack_element->Method();
Ian Rogersc0542af2014-09-03 16:16:56 -07004507 if (m == nullptr) {
Elliott Hughes545a0642011-11-08 19:10:03 -08004508 break;
4509 }
Hiroshi Yamauchib5a9e3d2014-06-09 12:11:20 -07004510 LOG(INFO) << " " << PrettyMethod(m) << " line " << stack_element->LineNumber();
Elliott Hughes545a0642011-11-08 19:10:03 -08004511 }
4512
4513 // pause periodically to help logcat catch up
4514 if ((count % 5) == 0) {
4515 usleep(40000);
4516 }
4517
Ian Rogers719d1a32014-03-06 12:13:39 -08004518 i = (i + 1) & (alloc_record_max_ - 1);
Elliott Hughes545a0642011-11-08 19:10:03 -08004519 }
4520}
4521
4522class StringTable {
4523 public:
4524 StringTable() {
4525 }
4526
Mathieu Chartier4345c462014-06-27 10:20:14 -07004527 void Add(const std::string& str) {
4528 table_.insert(str);
4529 }
4530
4531 void Add(const char* str) {
4532 table_.insert(str);
Elliott Hughes545a0642011-11-08 19:10:03 -08004533 }
4534
Elliott Hughesa8f93cb2012-06-08 17:08:48 -07004535 size_t IndexOf(const char* s) const {
Mathieu Chartier02e25112013-08-14 16:14:24 -07004536 auto it = table_.find(s);
Elliott Hughesa8f93cb2012-06-08 17:08:48 -07004537 if (it == table_.end()) {
4538 LOG(FATAL) << "IndexOf(\"" << s << "\") failed";
4539 }
4540 return std::distance(table_.begin(), it);
Elliott Hughes545a0642011-11-08 19:10:03 -08004541 }
4542
Elliott Hughesa8f93cb2012-06-08 17:08:48 -07004543 size_t Size() const {
Elliott Hughes545a0642011-11-08 19:10:03 -08004544 return table_.size();
4545 }
4546
Elliott Hughesa8f93cb2012-06-08 17:08:48 -07004547 void WriteTo(std::vector<uint8_t>& bytes) const {
Mathieu Chartier02e25112013-08-14 16:14:24 -07004548 for (const std::string& str : table_) {
4549 const char* s = str.c_str();
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08004550 size_t s_len = CountModifiedUtf8Chars(s);
Ian Rogers700a4022014-05-19 16:49:03 -07004551 std::unique_ptr<uint16_t> s_utf16(new uint16_t[s_len]);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08004552 ConvertModifiedUtf8ToUtf16(s_utf16.get(), s);
4553 JDWP::AppendUtf16BE(bytes, s_utf16.get(), s_len);
Elliott Hughes545a0642011-11-08 19:10:03 -08004554 }
4555 }
4556
4557 private:
Elliott Hughesa8f93cb2012-06-08 17:08:48 -07004558 std::set<std::string> table_;
Elliott Hughes545a0642011-11-08 19:10:03 -08004559 DISALLOW_COPY_AND_ASSIGN(StringTable);
4560};
4561
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07004562static const char* GetMethodSourceFile(mirror::ArtMethod* method)
Sebastien Hertz280286a2014-04-28 09:26:50 +02004563 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07004564 DCHECK(method != nullptr);
4565 const char* source_file = method->GetDeclaringClassSourceFile();
Sebastien Hertz280286a2014-04-28 09:26:50 +02004566 return (source_file != nullptr) ? source_file : "";
4567}
4568
Elliott Hughes545a0642011-11-08 19:10:03 -08004569/*
4570 * The data we send to DDMS contains everything we have recorded.
4571 *
4572 * Message header (all values big-endian):
4573 * (1b) message header len (to allow future expansion); includes itself
4574 * (1b) entry header len
4575 * (1b) stack frame len
4576 * (2b) number of entries
4577 * (4b) offset to string table from start of message
4578 * (2b) number of class name strings
4579 * (2b) number of method name strings
4580 * (2b) number of source file name strings
4581 * For each entry:
4582 * (4b) total allocation size
Elliott Hughes221229c2013-01-08 18:17:50 -08004583 * (2b) thread id
Elliott Hughes545a0642011-11-08 19:10:03 -08004584 * (2b) allocated object's class name index
4585 * (1b) stack depth
4586 * For each stack frame:
4587 * (2b) method's class name
4588 * (2b) method name
4589 * (2b) method source file
4590 * (2b) line number, clipped to 32767; -2 if native; -1 if no source
4591 * (xb) class name strings
4592 * (xb) method name strings
4593 * (xb) source file strings
4594 *
4595 * As with other DDM traffic, strings are sent as a 4-byte length
4596 * followed by UTF-16 data.
4597 *
4598 * We send up 16-bit unsigned indexes into string tables. In theory there
Brian Carlstrom306db812014-09-05 13:01:41 -07004599 * can be (kMaxAllocRecordStackDepth * alloc_record_max_) unique strings in
Elliott Hughes545a0642011-11-08 19:10:03 -08004600 * each table, but in practice there should be far fewer.
4601 *
4602 * The chief reason for using a string table here is to keep the size of
4603 * the DDMS message to a minimum. This is partly to make the protocol
4604 * efficient, but also because we have to form the whole thing up all at
4605 * once in a memory buffer.
4606 *
4607 * We use separate string tables for class names, method names, and source
4608 * files to keep the indexes small. There will generally be no overlap
4609 * between the contents of these tables.
4610 */
4611jbyteArray Dbg::GetRecentAllocations() {
4612 if (false) {
4613 DumpRecentAllocations();
4614 }
4615
Ian Rogers50b35e22012-10-04 10:09:15 -07004616 Thread* self = Thread::Current();
Elliott Hughes545a0642011-11-08 19:10:03 -08004617 std::vector<uint8_t> bytes;
Mathieu Chartier46e811b2013-07-10 17:09:14 -07004618 {
Brian Carlstrom306db812014-09-05 13:01:41 -07004619 MutexLock mu(self, *Locks::alloc_tracker_lock_);
Mathieu Chartier46e811b2013-07-10 17:09:14 -07004620 //
4621 // Part 1: generate string tables.
4622 //
4623 StringTable class_names;
4624 StringTable method_names;
4625 StringTable filenames;
Elliott Hughes545a0642011-11-08 19:10:03 -08004626
Brian Carlstrom306db812014-09-05 13:01:41 -07004627 const uint16_t capped_count = CappedAllocRecordCount(Dbg::alloc_record_count_);
4628 uint16_t count = capped_count;
4629 size_t idx = HeadIndex();
Mathieu Chartier46e811b2013-07-10 17:09:14 -07004630 while (count--) {
4631 AllocRecord* record = &recent_allocation_records_[idx];
Ian Rogers1ff3c982014-08-12 02:30:58 -07004632 std::string temp;
4633 class_names.Add(record->Type()->GetDescriptor(&temp));
Mathieu Chartier46e811b2013-07-10 17:09:14 -07004634 for (size_t i = 0; i < kMaxAllocRecordStackDepth; i++) {
Hiroshi Yamauchib5a9e3d2014-06-09 12:11:20 -07004635 mirror::ArtMethod* m = record->StackElement(i)->Method();
Ian Rogersc0542af2014-09-03 16:16:56 -07004636 if (m != nullptr) {
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07004637 class_names.Add(m->GetDeclaringClassDescriptor());
4638 method_names.Add(m->GetName());
4639 filenames.Add(GetMethodSourceFile(m));
Mathieu Chartier46e811b2013-07-10 17:09:14 -07004640 }
4641 }
Elliott Hughes545a0642011-11-08 19:10:03 -08004642
Ian Rogers719d1a32014-03-06 12:13:39 -08004643 idx = (idx + 1) & (alloc_record_max_ - 1);
Elliott Hughes545a0642011-11-08 19:10:03 -08004644 }
4645
Brian Carlstrom306db812014-09-05 13:01:41 -07004646 LOG(INFO) << "allocation records: " << capped_count;
Mathieu Chartier46e811b2013-07-10 17:09:14 -07004647
4648 //
4649 // Part 2: Generate the output and store it in the buffer.
4650 //
4651
4652 // (1b) message header len (to allow future expansion); includes itself
4653 // (1b) entry header len
4654 // (1b) stack frame len
4655 const int kMessageHeaderLen = 15;
4656 const int kEntryHeaderLen = 9;
4657 const int kStackFrameLen = 8;
4658 JDWP::Append1BE(bytes, kMessageHeaderLen);
4659 JDWP::Append1BE(bytes, kEntryHeaderLen);
4660 JDWP::Append1BE(bytes, kStackFrameLen);
4661
4662 // (2b) number of entries
4663 // (4b) offset to string table from start of message
4664 // (2b) number of class name strings
4665 // (2b) number of method name strings
4666 // (2b) number of source file name strings
Brian Carlstrom306db812014-09-05 13:01:41 -07004667 JDWP::Append2BE(bytes, capped_count);
Mathieu Chartier46e811b2013-07-10 17:09:14 -07004668 size_t string_table_offset = bytes.size();
Brian Carlstrom7934ac22013-07-26 10:54:15 -07004669 JDWP::Append4BE(bytes, 0); // We'll patch this later...
Mathieu Chartier46e811b2013-07-10 17:09:14 -07004670 JDWP::Append2BE(bytes, class_names.Size());
4671 JDWP::Append2BE(bytes, method_names.Size());
4672 JDWP::Append2BE(bytes, filenames.Size());
4673
Mathieu Chartier46e811b2013-07-10 17:09:14 -07004674 idx = HeadIndex();
Ian Rogers1ff3c982014-08-12 02:30:58 -07004675 std::string temp;
Brian Carlstrom306db812014-09-05 13:01:41 -07004676 for (count = capped_count; count != 0; --count) {
Mathieu Chartier46e811b2013-07-10 17:09:14 -07004677 // For each entry:
4678 // (4b) total allocation size
4679 // (2b) thread id
4680 // (2b) allocated object's class name index
4681 // (1b) stack depth
4682 AllocRecord* record = &recent_allocation_records_[idx];
4683 size_t stack_depth = record->GetDepth();
Mathieu Chartierf8322842014-05-16 10:59:25 -07004684 size_t allocated_object_class_name_index =
Ian Rogers1ff3c982014-08-12 02:30:58 -07004685 class_names.IndexOf(record->Type()->GetDescriptor(&temp));
Hiroshi Yamauchib5a9e3d2014-06-09 12:11:20 -07004686 JDWP::Append4BE(bytes, record->ByteCount());
4687 JDWP::Append2BE(bytes, record->ThinLockId());
Mathieu Chartier46e811b2013-07-10 17:09:14 -07004688 JDWP::Append2BE(bytes, allocated_object_class_name_index);
4689 JDWP::Append1BE(bytes, stack_depth);
4690
Mathieu Chartier46e811b2013-07-10 17:09:14 -07004691 for (size_t stack_frame = 0; stack_frame < stack_depth; ++stack_frame) {
4692 // For each stack frame:
4693 // (2b) method's class name
4694 // (2b) method name
4695 // (2b) method source file
4696 // (2b) line number, clipped to 32767; -2 if native; -1 if no source
Hiroshi Yamauchib5a9e3d2014-06-09 12:11:20 -07004697 mirror::ArtMethod* m = record->StackElement(stack_frame)->Method();
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07004698 size_t class_name_index = class_names.IndexOf(m->GetDeclaringClassDescriptor());
4699 size_t method_name_index = method_names.IndexOf(m->GetName());
4700 size_t file_name_index = filenames.IndexOf(GetMethodSourceFile(m));
Mathieu Chartier46e811b2013-07-10 17:09:14 -07004701 JDWP::Append2BE(bytes, class_name_index);
4702 JDWP::Append2BE(bytes, method_name_index);
4703 JDWP::Append2BE(bytes, file_name_index);
Hiroshi Yamauchib5a9e3d2014-06-09 12:11:20 -07004704 JDWP::Append2BE(bytes, record->StackElement(stack_frame)->LineNumber());
Mathieu Chartier46e811b2013-07-10 17:09:14 -07004705 }
Ian Rogers719d1a32014-03-06 12:13:39 -08004706 idx = (idx + 1) & (alloc_record_max_ - 1);
Mathieu Chartier46e811b2013-07-10 17:09:14 -07004707 }
4708
4709 // (xb) class name strings
4710 // (xb) method name strings
4711 // (xb) source file strings
4712 JDWP::Set4BE(&bytes[string_table_offset], bytes.size());
4713 class_names.WriteTo(bytes);
4714 method_names.WriteTo(bytes);
4715 filenames.WriteTo(bytes);
Elliott Hughes545a0642011-11-08 19:10:03 -08004716 }
Ian Rogers50b35e22012-10-04 10:09:15 -07004717 JNIEnv* env = self->GetJniEnv();
Elliott Hughes545a0642011-11-08 19:10:03 -08004718 jbyteArray result = env->NewByteArray(bytes.size());
Ian Rogersc0542af2014-09-03 16:16:56 -07004719 if (result != nullptr) {
Elliott Hughes545a0642011-11-08 19:10:03 -08004720 env->SetByteArrayRegion(result, 0, bytes.size(), reinterpret_cast<const jbyte*>(&bytes[0]));
4721 }
4722 return result;
4723}
4724
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07004725mirror::ArtMethod* DeoptimizationRequest::Method() const {
4726 ScopedObjectAccessUnchecked soa(Thread::Current());
4727 return soa.DecodeMethod(method_);
4728}
4729
4730void DeoptimizationRequest::SetMethod(mirror::ArtMethod* m) {
4731 ScopedObjectAccessUnchecked soa(Thread::Current());
4732 method_ = soa.EncodeMethod(m);
4733}
4734
Elliott Hughes872d4ec2011-10-21 17:07:15 -07004735} // namespace art