blob: 488e6e73dd531ae0618502152aef60bfaec26a27 [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);
Elliott Hughesa2155262011-11-16 16:26:58 -08001161 Runtime::Current()->GetClassLinker()->VisitClasses(ClassListCreator::Visit, &clc);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001162}
1163
Ian Rogers1ff3c982014-08-12 02:30:58 -07001164JDWP::JdwpError Dbg::GetClassInfo(JDWP::RefTypeId class_id, JDWP::JdwpTypeTag* pTypeTag,
1165 uint32_t* pStatus, std::string* pDescriptor) {
Ian Rogersc0542af2014-09-03 16:16:56 -07001166 JDWP::JdwpError error;
1167 mirror::Class* c = DecodeClass(class_id, &error);
1168 if (c == nullptr) {
1169 return error;
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -08001170 }
1171
Elliott Hughesa2155262011-11-16 16:26:58 -08001172 if (c->IsArrayClass()) {
1173 *pStatus = JDWP::CS_VERIFIED | JDWP::CS_PREPARED;
1174 *pTypeTag = JDWP::TT_ARRAY;
1175 } else {
1176 if (c->IsErroneous()) {
1177 *pStatus = JDWP::CS_ERROR;
1178 } else {
1179 *pStatus = JDWP::CS_VERIFIED | JDWP::CS_PREPARED | JDWP::CS_INITIALIZED;
1180 }
1181 *pTypeTag = c->IsInterface() ? JDWP::TT_INTERFACE : JDWP::TT_CLASS;
1182 }
1183
Ian Rogersc0542af2014-09-03 16:16:56 -07001184 if (pDescriptor != nullptr) {
Ian Rogers1ff3c982014-08-12 02:30:58 -07001185 std::string temp;
1186 *pDescriptor = c->GetDescriptor(&temp);
Elliott Hughesa2155262011-11-16 16:26:58 -08001187 }
Elliott Hughes436e3722012-02-17 20:01:47 -08001188 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001189}
1190
Ian Rogersc0542af2014-09-03 16:16:56 -07001191void Dbg::FindLoadedClassBySignature(const char* descriptor, std::vector<JDWP::RefTypeId>* ids) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001192 std::vector<mirror::Class*> classes;
Elliott Hughes6fa602d2011-12-02 17:54:25 -08001193 Runtime::Current()->GetClassLinker()->LookupClasses(descriptor, classes);
Ian Rogersc0542af2014-09-03 16:16:56 -07001194 ids->clear();
Elliott Hughes6fa602d2011-12-02 17:54:25 -08001195 for (size_t i = 0; i < classes.size(); ++i) {
Ian Rogersc0542af2014-09-03 16:16:56 -07001196 ids->push_back(gRegistry->Add(classes[i]));
Elliott Hughes6fa602d2011-12-02 17:54:25 -08001197 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001198}
1199
Ian Rogersc0542af2014-09-03 16:16:56 -07001200JDWP::JdwpError Dbg::GetReferenceType(JDWP::ObjectId object_id, JDWP::ExpandBuf* pReply) {
1201 JDWP::JdwpError error;
1202 mirror::Object* o = gRegistry->Get<mirror::Object*>(object_id, &error);
1203 if (o == nullptr) {
Elliott Hughes2435a572012-02-17 16:07:41 -08001204 return JDWP::ERR_INVALID_OBJECT;
Elliott Hughes499c5132011-11-17 14:55:11 -08001205 }
Elliott Hughes2435a572012-02-17 16:07:41 -08001206
Sebastien Hertz4d8fd492014-03-28 16:29:41 +01001207 JDWP::JdwpTypeTag type_tag = GetTypeTag(o->GetClass());
Elliott Hughes64f574f2013-02-20 14:57:12 -08001208 JDWP::RefTypeId type_id = gRegistry->AddRefType(o->GetClass());
Elliott Hughes2435a572012-02-17 16:07:41 -08001209
1210 expandBufAdd1(pReply, type_tag);
1211 expandBufAddRefTypeId(pReply, type_id);
1212
1213 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001214}
1215
Ian Rogersfc0e94b2013-09-23 23:51:32 -07001216JDWP::JdwpError Dbg::GetSignature(JDWP::RefTypeId class_id, std::string* signature) {
Ian Rogersc0542af2014-09-03 16:16:56 -07001217 JDWP::JdwpError error;
1218 mirror::Class* c = DecodeClass(class_id, &error);
1219 if (c == nullptr) {
1220 return error;
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -08001221 }
Ian Rogers1ff3c982014-08-12 02:30:58 -07001222 std::string temp;
1223 *signature = c->GetDescriptor(&temp);
Elliott Hughes1fe7afb2012-02-13 17:23:03 -08001224 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001225}
1226
Ian Rogersc0542af2014-09-03 16:16:56 -07001227JDWP::JdwpError Dbg::GetSourceFile(JDWP::RefTypeId class_id, std::string* result) {
1228 JDWP::JdwpError error;
1229 mirror::Class* c = DecodeClass(class_id, &error);
Sebastien Hertz4206eb52014-06-05 10:15:45 +02001230 if (c == nullptr) {
Ian Rogersc0542af2014-09-03 16:16:56 -07001231 return error;
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -08001232 }
Sebastien Hertz4206eb52014-06-05 10:15:45 +02001233 const char* source_file = c->GetSourceFile();
1234 if (source_file == nullptr) {
Sebastien Hertzb7054ba2014-03-13 11:52:31 +01001235 return JDWP::ERR_ABSENT_INFORMATION;
1236 }
Ian Rogersc0542af2014-09-03 16:16:56 -07001237 *result = source_file;
Elliott Hughes436e3722012-02-17 20:01:47 -08001238 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001239}
1240
Ian Rogersc0542af2014-09-03 16:16:56 -07001241JDWP::JdwpError Dbg::GetObjectTag(JDWP::ObjectId object_id, uint8_t* tag) {
Ian Rogers98379392014-02-24 16:53:16 -08001242 ScopedObjectAccessUnchecked soa(Thread::Current());
Ian Rogersc0542af2014-09-03 16:16:56 -07001243 JDWP::JdwpError error;
1244 mirror::Object* o = gRegistry->Get<mirror::Object*>(object_id, &error);
1245 if (error != JDWP::ERR_NONE) {
1246 *tag = JDWP::JT_VOID;
1247 return error;
Elliott Hughes546b9862012-06-20 16:06:13 -07001248 }
Ian Rogersc0542af2014-09-03 16:16:56 -07001249 *tag = TagFromObject(soa, o);
Elliott Hughes546b9862012-06-20 16:06:13 -07001250 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001251}
1252
Elliott Hughesaed4be92011-12-02 16:16:23 -08001253size_t Dbg::GetTagWidth(JDWP::JdwpTag tag) {
Elliott Hughesdbb40792011-11-18 17:05:22 -08001254 switch (tag) {
1255 case JDWP::JT_VOID:
1256 return 0;
1257 case JDWP::JT_BYTE:
1258 case JDWP::JT_BOOLEAN:
1259 return 1;
1260 case JDWP::JT_CHAR:
1261 case JDWP::JT_SHORT:
1262 return 2;
1263 case JDWP::JT_FLOAT:
1264 case JDWP::JT_INT:
1265 return 4;
1266 case JDWP::JT_ARRAY:
1267 case JDWP::JT_OBJECT:
1268 case JDWP::JT_STRING:
1269 case JDWP::JT_THREAD:
1270 case JDWP::JT_THREAD_GROUP:
1271 case JDWP::JT_CLASS_LOADER:
1272 case JDWP::JT_CLASS_OBJECT:
1273 return sizeof(JDWP::ObjectId);
1274 case JDWP::JT_DOUBLE:
1275 case JDWP::JT_LONG:
1276 return 8;
1277 default:
Elliott Hughes3d30d9b2011-12-07 17:35:48 -08001278 LOG(FATAL) << "Unknown tag " << tag;
Elliott Hughesdbb40792011-11-18 17:05:22 -08001279 return -1;
1280 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001281}
1282
Ian Rogersc0542af2014-09-03 16:16:56 -07001283JDWP::JdwpError Dbg::GetArrayLength(JDWP::ObjectId array_id, int32_t* length) {
1284 JDWP::JdwpError error;
1285 mirror::Array* a = DecodeNonNullArray(array_id, &error);
1286 if (a == nullptr) {
1287 return error;
Elliott Hughes24437992011-11-30 14:49:33 -08001288 }
Ian Rogersc0542af2014-09-03 16:16:56 -07001289 *length = a->GetLength();
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -08001290 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001291}
1292
Elliott Hughes88d63092013-01-09 09:55:54 -08001293JDWP::JdwpError Dbg::OutputArray(JDWP::ObjectId array_id, int offset, int count, JDWP::ExpandBuf* pReply) {
Ian Rogersc0542af2014-09-03 16:16:56 -07001294 JDWP::JdwpError error;
1295 mirror::Array* a = DecodeNonNullArray(array_id, &error);
Ian Rogers98379392014-02-24 16:53:16 -08001296 if (a == nullptr) {
Ian Rogersc0542af2014-09-03 16:16:56 -07001297 return error;
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -08001298 }
Elliott Hughes24437992011-11-30 14:49:33 -08001299
1300 if (offset < 0 || count < 0 || offset > a->GetLength() || a->GetLength() - offset < count) {
1301 LOG(WARNING) << __FUNCTION__ << " access out of bounds: offset=" << offset << "; count=" << count;
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -08001302 return JDWP::ERR_INVALID_LENGTH;
Elliott Hughes24437992011-11-30 14:49:33 -08001303 }
Ian Rogers1ff3c982014-08-12 02:30:58 -07001304 JDWP::JdwpTag element_tag = BasicTagFromClass(a->GetClass()->GetComponentType());
1305 expandBufAdd1(pReply, element_tag);
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -08001306 expandBufAdd4BE(pReply, count);
1307
Ian Rogers1ff3c982014-08-12 02:30:58 -07001308 if (IsPrimitiveTag(element_tag)) {
1309 size_t width = GetTagWidth(element_tag);
Elliott Hughes24437992011-11-30 14:49:33 -08001310 uint8_t* dst = expandBufAddSpace(pReply, count * width);
1311 if (width == 8) {
Ian Rogersef7d42f2014-01-06 12:55:46 -08001312 const uint64_t* src8 = reinterpret_cast<uint64_t*>(a->GetRawData(sizeof(uint64_t), 0));
Elliott Hughes24437992011-11-30 14:49:33 -08001313 for (int i = 0; i < count; ++i) JDWP::Write8BE(&dst, src8[offset + i]);
1314 } else if (width == 4) {
Ian Rogersef7d42f2014-01-06 12:55:46 -08001315 const uint32_t* src4 = reinterpret_cast<uint32_t*>(a->GetRawData(sizeof(uint32_t), 0));
Elliott Hughes24437992011-11-30 14:49:33 -08001316 for (int i = 0; i < count; ++i) JDWP::Write4BE(&dst, src4[offset + i]);
1317 } else if (width == 2) {
Ian Rogersef7d42f2014-01-06 12:55:46 -08001318 const uint16_t* src2 = reinterpret_cast<uint16_t*>(a->GetRawData(sizeof(uint16_t), 0));
Elliott Hughes24437992011-11-30 14:49:33 -08001319 for (int i = 0; i < count; ++i) JDWP::Write2BE(&dst, src2[offset + i]);
1320 } else {
Ian Rogersef7d42f2014-01-06 12:55:46 -08001321 const uint8_t* src = reinterpret_cast<uint8_t*>(a->GetRawData(sizeof(uint8_t), 0));
Elliott Hughes24437992011-11-30 14:49:33 -08001322 memcpy(dst, &src[offset * width], count * width);
1323 }
1324 } else {
Ian Rogers98379392014-02-24 16:53:16 -08001325 ScopedObjectAccessUnchecked soa(Thread::Current());
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001326 mirror::ObjectArray<mirror::Object>* oa = a->AsObjectArray<mirror::Object>();
Elliott Hughes24437992011-11-30 14:49:33 -08001327 for (int i = 0; i < count; ++i) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001328 mirror::Object* element = oa->Get(offset + i);
Ian Rogers98379392014-02-24 16:53:16 -08001329 JDWP::JdwpTag specific_tag = (element != nullptr) ? TagFromObject(soa, element)
Ian Rogers1ff3c982014-08-12 02:30:58 -07001330 : element_tag;
Elliott Hughes24437992011-11-30 14:49:33 -08001331 expandBufAdd1(pReply, specific_tag);
1332 expandBufAddObjectId(pReply, gRegistry->Add(element));
1333 }
1334 }
1335
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -08001336 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001337}
1338
Ian Rogersef7d42f2014-01-06 12:55:46 -08001339template <typename T>
Ian Rogersc0542af2014-09-03 16:16:56 -07001340static void CopyArrayData(mirror::Array* a, JDWP::Request* src, int offset, int count)
Ian Rogersef7d42f2014-01-06 12:55:46 -08001341 NO_THREAD_SAFETY_ANALYSIS {
1342 // TODO: fix when annotalysis correctly handles non-member functions.
Elliott Hughes4b9702c2013-02-20 18:13:24 -08001343 DCHECK(a->GetClass()->IsPrimitiveArray());
1344
Ian Rogersef7d42f2014-01-06 12:55:46 -08001345 T* dst = reinterpret_cast<T*>(a->GetRawData(sizeof(T), offset));
Elliott Hughes4b9702c2013-02-20 18:13:24 -08001346 for (int i = 0; i < count; ++i) {
Ian Rogersc0542af2014-09-03 16:16:56 -07001347 *dst++ = src->ReadValue(sizeof(T));
Elliott Hughes4b9702c2013-02-20 18:13:24 -08001348 }
1349}
1350
Elliott Hughes88d63092013-01-09 09:55:54 -08001351JDWP::JdwpError Dbg::SetArrayElements(JDWP::ObjectId array_id, int offset, int count,
Ian Rogersc0542af2014-09-03 16:16:56 -07001352 JDWP::Request* request) {
1353 JDWP::JdwpError error;
1354 mirror::Array* dst = DecodeNonNullArray(array_id, &error);
1355 if (dst == nullptr) {
1356 return error;
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -08001357 }
Elliott Hughesf03b8f62011-12-02 14:26:25 -08001358
Elliott Hughes4b9702c2013-02-20 18:13:24 -08001359 if (offset < 0 || count < 0 || offset > dst->GetLength() || dst->GetLength() - offset < count) {
Elliott Hughesf03b8f62011-12-02 14:26:25 -08001360 LOG(WARNING) << __FUNCTION__ << " access out of bounds: offset=" << offset << "; count=" << count;
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -08001361 return JDWP::ERR_INVALID_LENGTH;
Elliott Hughesf03b8f62011-12-02 14:26:25 -08001362 }
Ian Rogers1ff3c982014-08-12 02:30:58 -07001363 JDWP::JdwpTag element_tag = BasicTagFromClass(dst->GetClass()->GetComponentType());
Elliott Hughesf03b8f62011-12-02 14:26:25 -08001364
Ian Rogers1ff3c982014-08-12 02:30:58 -07001365 if (IsPrimitiveTag(element_tag)) {
1366 size_t width = GetTagWidth(element_tag);
Elliott Hughesf03b8f62011-12-02 14:26:25 -08001367 if (width == 8) {
Elliott Hughes4b9702c2013-02-20 18:13:24 -08001368 CopyArrayData<uint64_t>(dst, request, offset, count);
Elliott Hughesf03b8f62011-12-02 14:26:25 -08001369 } else if (width == 4) {
Elliott Hughes4b9702c2013-02-20 18:13:24 -08001370 CopyArrayData<uint32_t>(dst, request, offset, count);
Elliott Hughesf03b8f62011-12-02 14:26:25 -08001371 } else if (width == 2) {
Elliott Hughes4b9702c2013-02-20 18:13:24 -08001372 CopyArrayData<uint16_t>(dst, request, offset, count);
Elliott Hughesf03b8f62011-12-02 14:26:25 -08001373 } else {
Elliott Hughes4b9702c2013-02-20 18:13:24 -08001374 CopyArrayData<uint8_t>(dst, request, offset, count);
Elliott Hughesf03b8f62011-12-02 14:26:25 -08001375 }
1376 } else {
Elliott Hughes4b9702c2013-02-20 18:13:24 -08001377 mirror::ObjectArray<mirror::Object>* oa = dst->AsObjectArray<mirror::Object>();
Elliott Hughesf03b8f62011-12-02 14:26:25 -08001378 for (int i = 0; i < count; ++i) {
Ian Rogersc0542af2014-09-03 16:16:56 -07001379 JDWP::ObjectId id = request->ReadObjectId();
1380 JDWP::JdwpError error;
1381 mirror::Object* o = gRegistry->Get<mirror::Object*>(id, &error);
1382 if (error != JDWP::ERR_NONE) {
1383 return error;
Elliott Hughes436e3722012-02-17 20:01:47 -08001384 }
Sebastien Hertzd2fe10a2014-01-15 10:20:56 +01001385 oa->Set<false>(offset + i, o);
Elliott Hughesf03b8f62011-12-02 14:26:25 -08001386 }
1387 }
1388
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -08001389 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001390}
1391
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -08001392JDWP::ObjectId Dbg::CreateString(const std::string& str) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001393 return gRegistry->Add(mirror::String::AllocFromModifiedUtf8(Thread::Current(), str.c_str()));
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001394}
1395
Ian Rogersc0542af2014-09-03 16:16:56 -07001396JDWP::JdwpError Dbg::CreateObject(JDWP::RefTypeId class_id, JDWP::ObjectId* new_object) {
1397 JDWP::JdwpError error;
1398 mirror::Class* c = DecodeClass(class_id, &error);
1399 if (c == nullptr) {
1400 *new_object = 0;
1401 return error;
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -08001402 }
Ian Rogersc0542af2014-09-03 16:16:56 -07001403 *new_object = gRegistry->Add(c->AllocObject(Thread::Current()));
Elliott Hughes436e3722012-02-17 20:01:47 -08001404 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001405}
1406
Elliott Hughesbf13d362011-12-08 15:51:37 -08001407/*
1408 * Used by Eclipse's "Display" view to evaluate "new byte[5]" to get "(byte[]) [0, 0, 0, 0, 0]".
1409 */
Elliott Hughes88d63092013-01-09 09:55:54 -08001410JDWP::JdwpError Dbg::CreateArrayObject(JDWP::RefTypeId array_class_id, uint32_t length,
Ian Rogersc0542af2014-09-03 16:16:56 -07001411 JDWP::ObjectId* new_array) {
1412 JDWP::JdwpError error;
1413 mirror::Class* c = DecodeClass(array_class_id, &error);
1414 if (c == nullptr) {
1415 *new_array = 0;
1416 return error;
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -08001417 }
Ian Rogersc0542af2014-09-03 16:16:56 -07001418 *new_array = gRegistry->Add(mirror::Array::Alloc<true>(Thread::Current(), c, length,
1419 c->GetComponentSize(),
1420 Runtime::Current()->GetHeap()->GetCurrentAllocator()));
Elliott Hughes436e3722012-02-17 20:01:47 -08001421 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001422}
1423
Elliott Hughes88d63092013-01-09 09:55:54 -08001424bool Dbg::MatchType(JDWP::RefTypeId instance_class_id, JDWP::RefTypeId class_id) {
Ian Rogersc0542af2014-09-03 16:16:56 -07001425 JDWP::JdwpError error;
1426 mirror::Class* c1 = DecodeClass(instance_class_id, &error);
1427 CHECK(c1 != nullptr);
1428 mirror::Class* c2 = DecodeClass(class_id, &error);
1429 CHECK(c2 != nullptr);
Sebastien Hertz123756a2013-11-27 15:49:42 +01001430 return c2->IsAssignableFrom(c1);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001431}
1432
Brian Carlstromea46f952013-07-30 01:26:50 -07001433static JDWP::FieldId ToFieldId(const mirror::ArtField* f)
Ian Rogersb726dcb2012-09-05 08:57:23 -07001434 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Mathieu Chartier590fee92013-09-13 13:46:47 -07001435 CHECK(!kMovingFields);
Elliott Hughes03181a82011-11-17 17:22:21 -08001436 return static_cast<JDWP::FieldId>(reinterpret_cast<uintptr_t>(f));
Elliott Hughes03181a82011-11-17 17:22:21 -08001437}
1438
Brian Carlstromea46f952013-07-30 01:26:50 -07001439static JDWP::MethodId ToMethodId(const mirror::ArtMethod* m)
Ian Rogersb726dcb2012-09-05 08:57:23 -07001440 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Mathieu Chartier590fee92013-09-13 13:46:47 -07001441 CHECK(!kMovingMethods);
Elliott Hughes03181a82011-11-17 17:22:21 -08001442 return static_cast<JDWP::MethodId>(reinterpret_cast<uintptr_t>(m));
Elliott Hughes03181a82011-11-17 17:22:21 -08001443}
1444
Brian Carlstromea46f952013-07-30 01:26:50 -07001445static mirror::ArtField* FromFieldId(JDWP::FieldId fid)
Ian Rogersb726dcb2012-09-05 08:57:23 -07001446 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Mathieu Chartier590fee92013-09-13 13:46:47 -07001447 CHECK(!kMovingFields);
Brian Carlstromea46f952013-07-30 01:26:50 -07001448 return reinterpret_cast<mirror::ArtField*>(static_cast<uintptr_t>(fid));
Elliott Hughesaed4be92011-12-02 16:16:23 -08001449}
1450
Brian Carlstromea46f952013-07-30 01:26:50 -07001451static mirror::ArtMethod* FromMethodId(JDWP::MethodId mid)
Ian Rogersb726dcb2012-09-05 08:57:23 -07001452 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Mathieu Chartier590fee92013-09-13 13:46:47 -07001453 CHECK(!kMovingMethods);
Brian Carlstromea46f952013-07-30 01:26:50 -07001454 return reinterpret_cast<mirror::ArtMethod*>(static_cast<uintptr_t>(mid));
Elliott Hughes03181a82011-11-17 17:22:21 -08001455}
1456
Ian Rogersc0542af2014-09-03 16:16:56 -07001457static void SetLocation(JDWP::JdwpLocation* location, mirror::ArtMethod* m, uint32_t dex_pc)
Ian Rogersb726dcb2012-09-05 08:57:23 -07001458 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Ian Rogersc0542af2014-09-03 16:16:56 -07001459 if (m == nullptr) {
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08001460 memset(&location, 0, sizeof(location));
1461 } else {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001462 mirror::Class* c = m->GetDeclaringClass();
Ian Rogersc0542af2014-09-03 16:16:56 -07001463 location->type_tag = GetTypeTag(c);
1464 location->class_id = gRegistry->AddRefType(c);
1465 location->method_id = ToMethodId(m);
1466 location->dex_pc = (m->IsNative() || m->IsProxyMethod()) ? static_cast<uint64_t>(-1) : dex_pc;
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08001467 }
Elliott Hughesd07986f2011-12-06 18:27:45 -08001468}
1469
Ian Rogersc0542af2014-09-03 16:16:56 -07001470std::string Dbg::GetMethodName(JDWP::MethodId method_id) {
Brian Carlstromea46f952013-07-30 01:26:50 -07001471 mirror::ArtMethod* m = FromMethodId(method_id);
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07001472 return m->GetName();
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001473}
1474
Ian Rogersc0542af2014-09-03 16:16:56 -07001475std::string Dbg::GetFieldName(JDWP::FieldId field_id) {
Mathieu Chartier61c5ebc2014-06-05 17:42:53 -07001476 return FromFieldId(field_id)->GetName();
Elliott Hughesa96836a2013-01-17 12:27:49 -08001477}
1478
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001479/*
1480 * Augment the access flags for synthetic methods and fields by setting
1481 * the (as described by the spec) "0xf0000000 bit". Also, strip out any
1482 * flags not specified by the Java programming language.
1483 */
1484static uint32_t MangleAccessFlags(uint32_t accessFlags) {
1485 accessFlags &= kAccJavaFlagsMask;
1486 if ((accessFlags & kAccSynthetic) != 0) {
1487 accessFlags |= 0xf0000000;
1488 }
1489 return accessFlags;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001490}
1491
Elliott Hughesdbb40792011-11-18 17:05:22 -08001492/*
Jeff Haob7cefc72013-11-14 14:51:09 -08001493 * Circularly shifts registers so that arguments come first. Debuggers
1494 * expect slots to begin with arguments, but dex code places them at
1495 * the end.
Elliott Hughesdbb40792011-11-18 17:05:22 -08001496 */
Jeff Haob7cefc72013-11-14 14:51:09 -08001497static uint16_t MangleSlot(uint16_t slot, mirror::ArtMethod* m)
1498 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07001499 const DexFile::CodeItem* code_item = m->GetCodeItem();
Sebastien Hertzcb19ebf2014-03-11 15:26:35 +01001500 if (code_item == nullptr) {
1501 // We should not get here for a method without code (native, proxy or abstract). Log it and
1502 // return the slot as is since all registers are arguments.
1503 LOG(WARNING) << "Trying to mangle slot for method without code " << PrettyMethod(m);
1504 return slot;
1505 }
Jeff Haob7cefc72013-11-14 14:51:09 -08001506 uint16_t ins_size = code_item->ins_size_;
1507 uint16_t locals_size = code_item->registers_size_ - ins_size;
1508 if (slot >= locals_size) {
1509 return slot - locals_size;
1510 } else {
1511 return slot + ins_size;
Elliott Hughesdbb40792011-11-18 17:05:22 -08001512 }
Elliott Hughesdbb40792011-11-18 17:05:22 -08001513}
1514
Jeff Haob7cefc72013-11-14 14:51:09 -08001515/*
1516 * Circularly shifts registers so that arguments come last. Reverts
1517 * slots to dex style argument placement.
1518 */
Brian Carlstromea46f952013-07-30 01:26:50 -07001519static uint16_t DemangleSlot(uint16_t slot, mirror::ArtMethod* m)
Ian Rogersb726dcb2012-09-05 08:57:23 -07001520 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07001521 const DexFile::CodeItem* code_item = m->GetCodeItem();
Sebastien Hertzcb19ebf2014-03-11 15:26:35 +01001522 if (code_item == nullptr) {
1523 // We should not get here for a method without code (native, proxy or abstract). Log it and
1524 // return the slot as is since all registers are arguments.
1525 LOG(WARNING) << "Trying to demangle slot for method without code " << PrettyMethod(m);
1526 return slot;
1527 }
Jeff Haob7cefc72013-11-14 14:51:09 -08001528 uint16_t ins_size = code_item->ins_size_;
1529 uint16_t locals_size = code_item->registers_size_ - ins_size;
1530 if (slot < ins_size) {
1531 return slot + locals_size;
1532 } else {
1533 return slot - ins_size;
Elliott Hughesdbb40792011-11-18 17:05:22 -08001534 }
Elliott Hughesdbb40792011-11-18 17:05:22 -08001535}
1536
Elliott Hughes88d63092013-01-09 09:55:54 -08001537JDWP::JdwpError Dbg::OutputDeclaredFields(JDWP::RefTypeId class_id, bool with_generic, JDWP::ExpandBuf* pReply) {
Ian Rogersc0542af2014-09-03 16:16:56 -07001538 JDWP::JdwpError error;
1539 mirror::Class* c = DecodeClass(class_id, &error);
1540 if (c == nullptr) {
1541 return error;
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -08001542 }
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001543
1544 size_t instance_field_count = c->NumInstanceFields();
1545 size_t static_field_count = c->NumStaticFields();
1546
1547 expandBufAdd4BE(pReply, instance_field_count + static_field_count);
1548
1549 for (size_t i = 0; i < instance_field_count + static_field_count; ++i) {
Brian Carlstromea46f952013-07-30 01:26:50 -07001550 mirror::ArtField* f = (i < instance_field_count) ? c->GetInstanceField(i) : c->GetStaticField(i - instance_field_count);
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001551 expandBufAddFieldId(pReply, ToFieldId(f));
Mathieu Chartier61c5ebc2014-06-05 17:42:53 -07001552 expandBufAddUtf8String(pReply, f->GetName());
1553 expandBufAddUtf8String(pReply, f->GetTypeDescriptor());
Elliott Hughesc5b734a2011-12-01 17:20:58 -08001554 if (with_generic) {
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001555 static const char genericSignature[1] = "";
1556 expandBufAddUtf8String(pReply, genericSignature);
1557 }
1558 expandBufAdd4BE(pReply, MangleAccessFlags(f->GetAccessFlags()));
1559 }
Elliott Hughes436e3722012-02-17 20:01:47 -08001560 return JDWP::ERR_NONE;
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001561}
1562
Elliott Hughes88d63092013-01-09 09:55:54 -08001563JDWP::JdwpError Dbg::OutputDeclaredMethods(JDWP::RefTypeId class_id, bool with_generic,
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001564 JDWP::ExpandBuf* pReply) {
Ian Rogersc0542af2014-09-03 16:16:56 -07001565 JDWP::JdwpError error;
1566 mirror::Class* c = DecodeClass(class_id, &error);
1567 if (c == nullptr) {
1568 return error;
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -08001569 }
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001570
1571 size_t direct_method_count = c->NumDirectMethods();
1572 size_t virtual_method_count = c->NumVirtualMethods();
1573
1574 expandBufAdd4BE(pReply, direct_method_count + virtual_method_count);
1575
1576 for (size_t i = 0; i < direct_method_count + virtual_method_count; ++i) {
Brian Carlstromea46f952013-07-30 01:26:50 -07001577 mirror::ArtMethod* m = (i < direct_method_count) ? c->GetDirectMethod(i) : c->GetVirtualMethod(i - direct_method_count);
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001578 expandBufAddMethodId(pReply, ToMethodId(m));
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07001579 expandBufAddUtf8String(pReply, m->GetName());
1580 expandBufAddUtf8String(pReply, m->GetSignature().ToString());
Elliott Hughesc5b734a2011-12-01 17:20:58 -08001581 if (with_generic) {
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001582 static const char genericSignature[1] = "";
1583 expandBufAddUtf8String(pReply, genericSignature);
1584 }
1585 expandBufAdd4BE(pReply, MangleAccessFlags(m->GetAccessFlags()));
1586 }
Elliott Hughes436e3722012-02-17 20:01:47 -08001587 return JDWP::ERR_NONE;
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001588}
1589
Elliott Hughes88d63092013-01-09 09:55:54 -08001590JDWP::JdwpError Dbg::OutputDeclaredInterfaces(JDWP::RefTypeId class_id, JDWP::ExpandBuf* pReply) {
Ian Rogersc0542af2014-09-03 16:16:56 -07001591 JDWP::JdwpError error;
Mathieu Chartierf8322842014-05-16 10:59:25 -07001592 Thread* self = Thread::Current();
1593 StackHandleScope<1> hs(self);
Ian Rogersc0542af2014-09-03 16:16:56 -07001594 Handle<mirror::Class> c(hs.NewHandle(DecodeClass(class_id, &error)));
Mathieu Chartierf8322842014-05-16 10:59:25 -07001595 if (c.Get() == nullptr) {
Ian Rogersc0542af2014-09-03 16:16:56 -07001596 return error;
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -08001597 }
Mathieu Chartierf8322842014-05-16 10:59:25 -07001598 size_t interface_count = c->NumDirectInterfaces();
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001599 expandBufAdd4BE(pReply, interface_count);
1600 for (size_t i = 0; i < interface_count; ++i) {
Mathieu Chartierf8322842014-05-16 10:59:25 -07001601 expandBufAddRefTypeId(pReply,
1602 gRegistry->AddRefType(mirror::Class::GetDirectInterface(self, c, i)));
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001603 }
Elliott Hughes436e3722012-02-17 20:01:47 -08001604 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001605}
1606
Ian Rogersc0542af2014-09-03 16:16:56 -07001607void Dbg::OutputLineTable(JDWP::RefTypeId, JDWP::MethodId method_id, JDWP::ExpandBuf* pReply) {
Elliott Hughes03181a82011-11-17 17:22:21 -08001608 struct DebugCallbackContext {
1609 int numItems;
1610 JDWP::ExpandBuf* pReply;
1611
Elliott Hughes2435a572012-02-17 16:07:41 -08001612 static bool Callback(void* context, uint32_t address, uint32_t line_number) {
Elliott Hughes03181a82011-11-17 17:22:21 -08001613 DebugCallbackContext* pContext = reinterpret_cast<DebugCallbackContext*>(context);
1614 expandBufAdd8BE(pContext->pReply, address);
Elliott Hughes2435a572012-02-17 16:07:41 -08001615 expandBufAdd4BE(pContext->pReply, line_number);
Elliott Hughes03181a82011-11-17 17:22:21 -08001616 pContext->numItems++;
Sebastien Hertzf2910ee2013-10-19 16:39:24 +02001617 return false;
Elliott Hughes03181a82011-11-17 17:22:21 -08001618 }
1619 };
Brian Carlstromea46f952013-07-30 01:26:50 -07001620 mirror::ArtMethod* m = FromMethodId(method_id);
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07001621 const DexFile::CodeItem* code_item = m->GetCodeItem();
Elliott Hughes03181a82011-11-17 17:22:21 -08001622 uint64_t start, end;
Sebastien Hertzcb19ebf2014-03-11 15:26:35 +01001623 if (code_item == nullptr) {
1624 DCHECK(m->IsNative() || m->IsProxyMethod());
Elliott Hughes03181a82011-11-17 17:22:21 -08001625 start = -1;
1626 end = -1;
1627 } else {
1628 start = 0;
jeffhao14f0db92012-12-14 17:50:42 -08001629 // Return the index of the last instruction
Sebastien Hertzcb19ebf2014-03-11 15:26:35 +01001630 end = code_item->insns_size_in_code_units_ - 1;
Elliott Hughes03181a82011-11-17 17:22:21 -08001631 }
1632
1633 expandBufAdd8BE(pReply, start);
1634 expandBufAdd8BE(pReply, end);
1635
1636 // Add numLines later
1637 size_t numLinesOffset = expandBufGetLength(pReply);
1638 expandBufAdd4BE(pReply, 0);
1639
1640 DebugCallbackContext context;
1641 context.numItems = 0;
1642 context.pReply = pReply;
1643
Sebastien Hertzcb19ebf2014-03-11 15:26:35 +01001644 if (code_item != nullptr) {
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07001645 m->GetDexFile()->DecodeDebugInfo(code_item, m->IsStatic(), m->GetDexMethodIndex(),
Ian Rogersc0542af2014-09-03 16:16:56 -07001646 DebugCallbackContext::Callback, nullptr, &context);
Sebastien Hertzcb19ebf2014-03-11 15:26:35 +01001647 }
Elliott Hughes03181a82011-11-17 17:22:21 -08001648
1649 JDWP::Set4BE(expandBufGetBuffer(pReply) + numLinesOffset, context.numItems);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001650}
1651
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07001652void Dbg::OutputVariableTable(JDWP::RefTypeId, JDWP::MethodId method_id, bool with_generic,
1653 JDWP::ExpandBuf* pReply) {
Elliott Hughesdbb40792011-11-18 17:05:22 -08001654 struct DebugCallbackContext {
Jeff Haob7cefc72013-11-14 14:51:09 -08001655 mirror::ArtMethod* method;
Elliott Hughesdbb40792011-11-18 17:05:22 -08001656 JDWP::ExpandBuf* pReply;
Elliott Hughesc5b734a2011-12-01 17:20:58 -08001657 size_t variable_count;
1658 bool with_generic;
Elliott Hughesdbb40792011-11-18 17:05:22 -08001659
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07001660 static void Callback(void* context, uint16_t slot, uint32_t startAddress, uint32_t endAddress,
1661 const char* name, const char* descriptor, const char* signature)
Jeff Haob7cefc72013-11-14 14:51:09 -08001662 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Elliott Hughesdbb40792011-11-18 17:05:22 -08001663 DebugCallbackContext* pContext = reinterpret_cast<DebugCallbackContext*>(context);
1664
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07001665 VLOG(jdwp) << StringPrintf(" %2zd: %d(%d) '%s' '%s' '%s' actual slot=%d mangled slot=%d",
1666 pContext->variable_count, startAddress, endAddress - startAddress,
1667 name, descriptor, signature, slot,
1668 MangleSlot(slot, pContext->method));
Elliott Hughesdbb40792011-11-18 17:05:22 -08001669
Jeff Haob7cefc72013-11-14 14:51:09 -08001670 slot = MangleSlot(slot, pContext->method);
Elliott Hughes68fdbd02011-11-29 19:22:47 -08001671
Elliott Hughesdbb40792011-11-18 17:05:22 -08001672 expandBufAdd8BE(pContext->pReply, startAddress);
1673 expandBufAddUtf8String(pContext->pReply, name);
1674 expandBufAddUtf8String(pContext->pReply, descriptor);
Elliott Hughesc5b734a2011-12-01 17:20:58 -08001675 if (pContext->with_generic) {
Elliott Hughesdbb40792011-11-18 17:05:22 -08001676 expandBufAddUtf8String(pContext->pReply, signature);
1677 }
1678 expandBufAdd4BE(pContext->pReply, endAddress - startAddress);
1679 expandBufAdd4BE(pContext->pReply, slot);
1680
Elliott Hughesc5b734a2011-12-01 17:20:58 -08001681 ++pContext->variable_count;
Elliott Hughesdbb40792011-11-18 17:05:22 -08001682 }
1683 };
Brian Carlstromea46f952013-07-30 01:26:50 -07001684 mirror::ArtMethod* m = FromMethodId(method_id);
Elliott Hughesdbb40792011-11-18 17:05:22 -08001685
Elliott Hughesc5b734a2011-12-01 17:20:58 -08001686 // arg_count considers doubles and longs to take 2 units.
1687 // variable_count considers everything to take 1 unit.
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07001688 std::string shorty(m->GetShorty());
Brian Carlstromea46f952013-07-30 01:26:50 -07001689 expandBufAdd4BE(pReply, mirror::ArtMethod::NumArgRegisters(shorty));
Elliott Hughesdbb40792011-11-18 17:05:22 -08001690
Elliott Hughesc5b734a2011-12-01 17:20:58 -08001691 // We don't know the total number of variables yet, so leave a blank and update it later.
1692 size_t variable_count_offset = expandBufGetLength(pReply);
Elliott Hughesdbb40792011-11-18 17:05:22 -08001693 expandBufAdd4BE(pReply, 0);
1694
1695 DebugCallbackContext context;
Jeff Haob7cefc72013-11-14 14:51:09 -08001696 context.method = m;
Elliott Hughesdbb40792011-11-18 17:05:22 -08001697 context.pReply = pReply;
Elliott Hughesc5b734a2011-12-01 17:20:58 -08001698 context.variable_count = 0;
1699 context.with_generic = with_generic;
Elliott Hughesdbb40792011-11-18 17:05:22 -08001700
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07001701 const DexFile::CodeItem* code_item = m->GetCodeItem();
Sebastien Hertzcb19ebf2014-03-11 15:26:35 +01001702 if (code_item != nullptr) {
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07001703 m->GetDexFile()->DecodeDebugInfo(
Ian Rogersc0542af2014-09-03 16:16:56 -07001704 code_item, m->IsStatic(), m->GetDexMethodIndex(), nullptr, DebugCallbackContext::Callback,
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07001705 &context);
Sebastien Hertzcb19ebf2014-03-11 15:26:35 +01001706 }
Elliott Hughesdbb40792011-11-18 17:05:22 -08001707
Elliott Hughesc5b734a2011-12-01 17:20:58 -08001708 JDWP::Set4BE(expandBufGetBuffer(pReply) + variable_count_offset, context.variable_count);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001709}
1710
Jeff Hao579b0242013-11-18 13:16:49 -08001711void Dbg::OutputMethodReturnValue(JDWP::MethodId method_id, const JValue* return_value,
1712 JDWP::ExpandBuf* pReply) {
1713 mirror::ArtMethod* m = FromMethodId(method_id);
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07001714 JDWP::JdwpTag tag = BasicTagFromDescriptor(m->GetShorty());
Jeff Hao579b0242013-11-18 13:16:49 -08001715 OutputJValue(tag, return_value, pReply);
1716}
1717
Sebastien Hertz3f52eaf2014-04-04 17:50:18 +02001718void Dbg::OutputFieldValue(JDWP::FieldId field_id, const JValue* field_value,
1719 JDWP::ExpandBuf* pReply) {
1720 mirror::ArtField* f = FromFieldId(field_id);
Mathieu Chartier61c5ebc2014-06-05 17:42:53 -07001721 JDWP::JdwpTag tag = BasicTagFromDescriptor(f->GetTypeDescriptor());
Sebastien Hertz3f52eaf2014-04-04 17:50:18 +02001722 OutputJValue(tag, field_value, pReply);
1723}
1724
Elliott Hughes9777ba22013-01-17 09:04:19 -08001725JDWP::JdwpError Dbg::GetBytecodes(JDWP::RefTypeId, JDWP::MethodId method_id,
Ian Rogersc0542af2014-09-03 16:16:56 -07001726 std::vector<uint8_t>* bytecodes) {
Brian Carlstromea46f952013-07-30 01:26:50 -07001727 mirror::ArtMethod* m = FromMethodId(method_id);
Ian Rogersc0542af2014-09-03 16:16:56 -07001728 if (m == nullptr) {
Elliott Hughes9777ba22013-01-17 09:04:19 -08001729 return JDWP::ERR_INVALID_METHODID;
1730 }
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07001731 const DexFile::CodeItem* code_item = m->GetCodeItem();
Elliott Hughes9777ba22013-01-17 09:04:19 -08001732 size_t byte_count = code_item->insns_size_in_code_units_ * 2;
1733 const uint8_t* begin = reinterpret_cast<const uint8_t*>(code_item->insns_);
1734 const uint8_t* end = begin + byte_count;
1735 for (const uint8_t* p = begin; p != end; ++p) {
Ian Rogersc0542af2014-09-03 16:16:56 -07001736 bytecodes->push_back(*p);
Elliott Hughes9777ba22013-01-17 09:04:19 -08001737 }
1738 return JDWP::ERR_NONE;
1739}
1740
Elliott Hughes88d63092013-01-09 09:55:54 -08001741JDWP::JdwpTag Dbg::GetFieldBasicTag(JDWP::FieldId field_id) {
Mathieu Chartier61c5ebc2014-06-05 17:42:53 -07001742 return BasicTagFromDescriptor(FromFieldId(field_id)->GetTypeDescriptor());
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001743}
1744
Elliott Hughes88d63092013-01-09 09:55:54 -08001745JDWP::JdwpTag Dbg::GetStaticFieldBasicTag(JDWP::FieldId field_id) {
Mathieu Chartier61c5ebc2014-06-05 17:42:53 -07001746 return BasicTagFromDescriptor(FromFieldId(field_id)->GetTypeDescriptor());
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001747}
1748
Elliott Hughes88d63092013-01-09 09:55:54 -08001749static JDWP::JdwpError GetFieldValueImpl(JDWP::RefTypeId ref_type_id, JDWP::ObjectId object_id,
1750 JDWP::FieldId field_id, JDWP::ExpandBuf* pReply,
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001751 bool is_static)
Ian Rogersb726dcb2012-09-05 08:57:23 -07001752 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Ian Rogersc0542af2014-09-03 16:16:56 -07001753 JDWP::JdwpError error;
1754 mirror::Class* c = DecodeClass(ref_type_id, &error);
1755 if (ref_type_id != 0 && c == nullptr) {
1756 return error;
Elliott Hughes0cf74332012-02-23 23:14:00 -08001757 }
1758
Ian Rogersc0542af2014-09-03 16:16:56 -07001759 mirror::Object* o = gRegistry->Get<mirror::Object*>(object_id, &error);
1760 if ((!is_static && o == nullptr) || error != JDWP::ERR_NONE) {
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08001761 return JDWP::ERR_INVALID_OBJECT;
1762 }
Brian Carlstromea46f952013-07-30 01:26:50 -07001763 mirror::ArtField* f = FromFieldId(field_id);
Elliott Hughes0cf74332012-02-23 23:14:00 -08001764
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001765 mirror::Class* receiver_class = c;
Ian Rogersc0542af2014-09-03 16:16:56 -07001766 if (receiver_class == nullptr && o != nullptr) {
Elliott Hughes0cf74332012-02-23 23:14:00 -08001767 receiver_class = o->GetClass();
1768 }
Ian Rogersc0542af2014-09-03 16:16:56 -07001769 // TODO: should we give up now if receiver_class is nullptr?
1770 if (receiver_class != nullptr && !f->GetDeclaringClass()->IsAssignableFrom(receiver_class)) {
Elliott Hughes0cf74332012-02-23 23:14:00 -08001771 LOG(INFO) << "ERR_INVALID_FIELDID: " << PrettyField(f) << " " << PrettyClass(receiver_class);
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08001772 return JDWP::ERR_INVALID_FIELDID;
1773 }
Elliott Hughesaed4be92011-12-02 16:16:23 -08001774
Elliott Hughes0cf74332012-02-23 23:14:00 -08001775 // The RI only enforces the static/non-static mismatch in one direction.
1776 // TODO: should we change the tests and check both?
1777 if (is_static) {
1778 if (!f->IsStatic()) {
1779 return JDWP::ERR_INVALID_FIELDID;
1780 }
1781 } else {
1782 if (f->IsStatic()) {
Ian Rogersc0542af2014-09-03 16:16:56 -07001783 LOG(WARNING) << "Ignoring non-nullptr receiver for ObjectReference.SetValues on static field "
1784 << PrettyField(f);
Elliott Hughes0cf74332012-02-23 23:14:00 -08001785 }
1786 }
jeffhao0dfbb7e2012-11-28 15:26:03 -08001787 if (f->IsStatic()) {
1788 o = f->GetDeclaringClass();
1789 }
Elliott Hughes0cf74332012-02-23 23:14:00 -08001790
Mathieu Chartier61c5ebc2014-06-05 17:42:53 -07001791 JDWP::JdwpTag tag = BasicTagFromDescriptor(f->GetTypeDescriptor());
Jeff Hao579b0242013-11-18 13:16:49 -08001792 JValue field_value;
1793 if (tag == JDWP::JT_VOID) {
1794 LOG(FATAL) << "Unknown tag: " << tag;
1795 } else if (!IsPrimitiveTag(tag)) {
1796 field_value.SetL(f->GetObject(o));
1797 } else if (tag == JDWP::JT_DOUBLE || tag == JDWP::JT_LONG) {
1798 field_value.SetJ(f->Get64(o));
Elliott Hughesaed4be92011-12-02 16:16:23 -08001799 } else {
Jeff Hao579b0242013-11-18 13:16:49 -08001800 field_value.SetI(f->Get32(o));
Elliott Hughesaed4be92011-12-02 16:16:23 -08001801 }
Jeff Hao579b0242013-11-18 13:16:49 -08001802 Dbg::OutputJValue(tag, &field_value, pReply);
1803
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08001804 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001805}
1806
Elliott Hughes88d63092013-01-09 09:55:54 -08001807JDWP::JdwpError Dbg::GetFieldValue(JDWP::ObjectId object_id, JDWP::FieldId field_id,
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001808 JDWP::ExpandBuf* pReply) {
Elliott Hughes88d63092013-01-09 09:55:54 -08001809 return GetFieldValueImpl(0, object_id, field_id, pReply, false);
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08001810}
1811
Ian Rogersc0542af2014-09-03 16:16:56 -07001812JDWP::JdwpError Dbg::GetStaticFieldValue(JDWP::RefTypeId ref_type_id, JDWP::FieldId field_id,
1813 JDWP::ExpandBuf* pReply) {
Elliott Hughes88d63092013-01-09 09:55:54 -08001814 return GetFieldValueImpl(ref_type_id, 0, field_id, pReply, true);
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08001815}
1816
Elliott Hughes88d63092013-01-09 09:55:54 -08001817static JDWP::JdwpError SetFieldValueImpl(JDWP::ObjectId object_id, JDWP::FieldId field_id,
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001818 uint64_t value, int width, bool is_static)
Ian Rogersb726dcb2012-09-05 08:57:23 -07001819 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Ian Rogersc0542af2014-09-03 16:16:56 -07001820 JDWP::JdwpError error;
1821 mirror::Object* o = gRegistry->Get<mirror::Object*>(object_id, &error);
1822 if ((!is_static && o == nullptr) || error != JDWP::ERR_NONE) {
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08001823 return JDWP::ERR_INVALID_OBJECT;
1824 }
Brian Carlstromea46f952013-07-30 01:26:50 -07001825 mirror::ArtField* f = FromFieldId(field_id);
Elliott Hughes0cf74332012-02-23 23:14:00 -08001826
1827 // The RI only enforces the static/non-static mismatch in one direction.
1828 // TODO: should we change the tests and check both?
1829 if (is_static) {
1830 if (!f->IsStatic()) {
1831 return JDWP::ERR_INVALID_FIELDID;
1832 }
1833 } else {
1834 if (f->IsStatic()) {
Ian Rogersc0542af2014-09-03 16:16:56 -07001835 LOG(WARNING) << "Ignoring non-nullptr receiver for ObjectReference.SetValues on static field " << PrettyField(f);
Elliott Hughes0cf74332012-02-23 23:14:00 -08001836 }
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08001837 }
jeffhao0dfbb7e2012-11-28 15:26:03 -08001838 if (f->IsStatic()) {
1839 o = f->GetDeclaringClass();
1840 }
Elliott Hughesaed4be92011-12-02 16:16:23 -08001841
Mathieu Chartier61c5ebc2014-06-05 17:42:53 -07001842 JDWP::JdwpTag tag = BasicTagFromDescriptor(f->GetTypeDescriptor());
Elliott Hughesaed4be92011-12-02 16:16:23 -08001843
1844 if (IsPrimitiveTag(tag)) {
1845 if (tag == JDWP::JT_DOUBLE || tag == JDWP::JT_LONG) {
Elliott Hughes1bac54f2012-03-16 12:48:31 -07001846 CHECK_EQ(width, 8);
Sebastien Hertzd2fe10a2014-01-15 10:20:56 +01001847 // Debugging can't use transactional mode (runtime only).
1848 f->Set64<false>(o, value);
Elliott Hughesaed4be92011-12-02 16:16:23 -08001849 } else {
Elliott Hughes1bac54f2012-03-16 12:48:31 -07001850 CHECK_LE(width, 4);
Sebastien Hertzd2fe10a2014-01-15 10:20:56 +01001851 // Debugging can't use transactional mode (runtime only).
1852 f->Set32<false>(o, value);
Elliott Hughesaed4be92011-12-02 16:16:23 -08001853 }
1854 } else {
Ian Rogersc0542af2014-09-03 16:16:56 -07001855 mirror::Object* v = gRegistry->Get<mirror::Object*>(value, &error);
1856 if (error != JDWP::ERR_NONE) {
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -08001857 return JDWP::ERR_INVALID_OBJECT;
1858 }
Ian Rogersc0542af2014-09-03 16:16:56 -07001859 if (v != nullptr) {
Mathieu Chartier61c5ebc2014-06-05 17:42:53 -07001860 mirror::Class* field_type;
1861 {
1862 StackHandleScope<3> hs(Thread::Current());
1863 HandleWrapper<mirror::Object> h_v(hs.NewHandleWrapper(&v));
1864 HandleWrapper<mirror::ArtField> h_f(hs.NewHandleWrapper(&f));
1865 HandleWrapper<mirror::Object> h_o(hs.NewHandleWrapper(&o));
1866 field_type = FieldHelper(h_f).GetType();
1867 }
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08001868 if (!field_type->IsAssignableFrom(v->GetClass())) {
1869 return JDWP::ERR_INVALID_OBJECT;
1870 }
1871 }
Sebastien Hertzd2fe10a2014-01-15 10:20:56 +01001872 // Debugging can't use transactional mode (runtime only).
1873 f->SetObject<false>(o, v);
Elliott Hughesaed4be92011-12-02 16:16:23 -08001874 }
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -08001875
1876 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001877}
1878
Elliott Hughes88d63092013-01-09 09:55:54 -08001879JDWP::JdwpError Dbg::SetFieldValue(JDWP::ObjectId object_id, JDWP::FieldId field_id, uint64_t value,
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001880 int width) {
Elliott Hughes88d63092013-01-09 09:55:54 -08001881 return SetFieldValueImpl(object_id, field_id, value, width, false);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001882}
1883
Elliott Hughes88d63092013-01-09 09:55:54 -08001884JDWP::JdwpError Dbg::SetStaticFieldValue(JDWP::FieldId field_id, uint64_t value, int width) {
1885 return SetFieldValueImpl(0, field_id, value, width, true);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001886}
1887
Elliott Hughes88d63092013-01-09 09:55:54 -08001888std::string Dbg::StringToUtf8(JDWP::ObjectId string_id) {
Ian Rogersc0542af2014-09-03 16:16:56 -07001889 JDWP::JdwpError error;
1890 mirror::String* s = gRegistry->Get<mirror::String*>(string_id, &error);
1891 CHECK(s != nullptr) << error;
Elliott Hughes68fdbd02011-11-29 19:22:47 -08001892 return s->ToModifiedUtf8();
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001893}
1894
Jeff Hao579b0242013-11-18 13:16:49 -08001895void Dbg::OutputJValue(JDWP::JdwpTag tag, const JValue* return_value, JDWP::ExpandBuf* pReply) {
1896 if (IsPrimitiveTag(tag)) {
1897 expandBufAdd1(pReply, tag);
1898 if (tag == JDWP::JT_BOOLEAN || tag == JDWP::JT_BYTE) {
1899 expandBufAdd1(pReply, return_value->GetI());
1900 } else if (tag == JDWP::JT_CHAR || tag == JDWP::JT_SHORT) {
1901 expandBufAdd2BE(pReply, return_value->GetI());
1902 } else if (tag == JDWP::JT_FLOAT || tag == JDWP::JT_INT) {
1903 expandBufAdd4BE(pReply, return_value->GetI());
1904 } else if (tag == JDWP::JT_DOUBLE || tag == JDWP::JT_LONG) {
1905 expandBufAdd8BE(pReply, return_value->GetJ());
1906 } else {
1907 CHECK_EQ(tag, JDWP::JT_VOID);
1908 }
1909 } else {
Ian Rogers98379392014-02-24 16:53:16 -08001910 ScopedObjectAccessUnchecked soa(Thread::Current());
Jeff Hao579b0242013-11-18 13:16:49 -08001911 mirror::Object* value = return_value->GetL();
Ian Rogers98379392014-02-24 16:53:16 -08001912 expandBufAdd1(pReply, TagFromObject(soa, value));
Jeff Hao579b0242013-11-18 13:16:49 -08001913 expandBufAddObjectId(pReply, gRegistry->Add(value));
1914 }
1915}
1916
Ian Rogersc0542af2014-09-03 16:16:56 -07001917JDWP::JdwpError Dbg::GetThreadName(JDWP::ObjectId thread_id, std::string* name) {
jeffhaoa77f0f62012-12-05 17:19:31 -08001918 ScopedObjectAccessUnchecked soa(Thread::Current());
1919 MutexLock mu(soa.Self(), *Locks::thread_list_lock_);
Ian Rogersc0542af2014-09-03 16:16:56 -07001920 JDWP::JdwpError error;
1921 Thread* thread = DecodeThread(soa, thread_id, &error);
1922 UNUSED(thread);
Elliott Hughes221229c2013-01-08 18:17:50 -08001923 if (error != JDWP::ERR_NONE && error != JDWP::ERR_THREAD_NOT_ALIVE) {
1924 return error;
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001925 }
Elliott Hughes221229c2013-01-08 18:17:50 -08001926
1927 // We still need to report the zombie threads' names, so we can't just call Thread::GetThreadName.
Ian Rogersc0542af2014-09-03 16:16:56 -07001928 mirror::Object* thread_object = gRegistry->Get<mirror::Object*>(thread_id, &error);
1929 CHECK(thread_object != nullptr) << error;
Brian Carlstromea46f952013-07-30 01:26:50 -07001930 mirror::ArtField* java_lang_Thread_name_field =
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001931 soa.DecodeField(WellKnownClasses::java_lang_Thread_name);
1932 mirror::String* s =
1933 reinterpret_cast<mirror::String*>(java_lang_Thread_name_field->GetObject(thread_object));
Ian Rogersc0542af2014-09-03 16:16:56 -07001934 if (s != nullptr) {
1935 *name = s->ToModifiedUtf8();
Elliott Hughes221229c2013-01-08 18:17:50 -08001936 }
1937 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001938}
1939
Elliott Hughes221229c2013-01-08 18:17:50 -08001940JDWP::JdwpError Dbg::GetThreadGroup(JDWP::ObjectId thread_id, JDWP::ExpandBuf* pReply) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001941 ScopedObjectAccess soa(Thread::Current());
Ian Rogersc0542af2014-09-03 16:16:56 -07001942 JDWP::JdwpError error;
1943 mirror::Object* thread_object = gRegistry->Get<mirror::Object*>(thread_id, &error);
1944 if (error != JDWP::ERR_NONE) {
Elliott Hughes2435a572012-02-17 16:07:41 -08001945 return JDWP::ERR_INVALID_OBJECT;
1946 }
Ian Rogers98379392014-02-24 16:53:16 -08001947 const char* old_cause = soa.Self()->StartAssertNoThreadSuspension("Debugger: GetThreadGroup");
Elliott Hughes2435a572012-02-17 16:07:41 -08001948 // Okay, so it's an object, but is it actually a thread?
Hiroshi Yamauchib5a9e3d2014-06-09 12:11:20 -07001949 {
1950 MutexLock mu(soa.Self(), *Locks::thread_list_lock_);
Ian Rogersc0542af2014-09-03 16:16:56 -07001951 Thread* thread = DecodeThread(soa, thread_id, &error);
1952 UNUSED(thread);
Hiroshi Yamauchib5a9e3d2014-06-09 12:11:20 -07001953 }
Elliott Hughes221229c2013-01-08 18:17:50 -08001954 if (error == JDWP::ERR_THREAD_NOT_ALIVE) {
1955 // Zombie threads are in the null group.
1956 expandBufAddObjectId(pReply, JDWP::ObjectId(0));
Sebastien Hertz52d131d2014-03-13 16:17:40 +01001957 error = JDWP::ERR_NONE;
1958 } else if (error == JDWP::ERR_NONE) {
1959 mirror::Class* c = soa.Decode<mirror::Class*>(WellKnownClasses::java_lang_Thread);
1960 CHECK(c != nullptr);
1961 mirror::ArtField* f = c->FindInstanceField("group", "Ljava/lang/ThreadGroup;");
Hiroshi Yamauchib5a9e3d2014-06-09 12:11:20 -07001962 CHECK(f != nullptr);
Sebastien Hertz52d131d2014-03-13 16:17:40 +01001963 mirror::Object* group = f->GetObject(thread_object);
Hiroshi Yamauchib5a9e3d2014-06-09 12:11:20 -07001964 CHECK(group != nullptr);
Sebastien Hertz52d131d2014-03-13 16:17:40 +01001965 JDWP::ObjectId thread_group_id = gRegistry->Add(group);
1966 expandBufAddObjectId(pReply, thread_group_id);
Elliott Hughes221229c2013-01-08 18:17:50 -08001967 }
Ian Rogers98379392014-02-24 16:53:16 -08001968 soa.Self()->EndAssertNoThreadSuspension(old_cause);
Sebastien Hertz52d131d2014-03-13 16:17:40 +01001969 return error;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001970}
1971
Elliott Hughes88d63092013-01-09 09:55:54 -08001972std::string Dbg::GetThreadGroupName(JDWP::ObjectId thread_group_id) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001973 ScopedObjectAccess soa(Thread::Current());
Ian Rogersc0542af2014-09-03 16:16:56 -07001974 JDWP::JdwpError error;
1975 mirror::Object* thread_group = gRegistry->Get<mirror::Object*>(thread_group_id, &error);
1976 CHECK(thread_group != nullptr) << error;
Ian Rogers98379392014-02-24 16:53:16 -08001977 const char* old_cause = soa.Self()->StartAssertNoThreadSuspension("Debugger: GetThreadGroupName");
1978 mirror::Class* c = soa.Decode<mirror::Class*>(WellKnownClasses::java_lang_ThreadGroup);
1979 CHECK(c != nullptr);
Brian Carlstromea46f952013-07-30 01:26:50 -07001980 mirror::ArtField* f = c->FindInstanceField("name", "Ljava/lang/String;");
Ian Rogersc0542af2014-09-03 16:16:56 -07001981 CHECK(f != nullptr);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001982 mirror::String* s = reinterpret_cast<mirror::String*>(f->GetObject(thread_group));
Ian Rogers98379392014-02-24 16:53:16 -08001983 soa.Self()->EndAssertNoThreadSuspension(old_cause);
Elliott Hughes499c5132011-11-17 14:55:11 -08001984 return s->ToModifiedUtf8();
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001985}
1986
Elliott Hughes88d63092013-01-09 09:55:54 -08001987JDWP::ObjectId Dbg::GetThreadGroupParent(JDWP::ObjectId thread_group_id) {
Ian Rogers98379392014-02-24 16:53:16 -08001988 ScopedObjectAccessUnchecked soa(Thread::Current());
Ian Rogersc0542af2014-09-03 16:16:56 -07001989 JDWP::JdwpError error;
1990 mirror::Object* thread_group = gRegistry->Get<mirror::Object*>(thread_group_id, &error);
1991 CHECK(thread_group != nullptr) << error;
Ian Rogers98379392014-02-24 16:53:16 -08001992 const char* old_cause = soa.Self()->StartAssertNoThreadSuspension("Debugger: GetThreadGroupParent");
1993 mirror::Class* c = soa.Decode<mirror::Class*>(WellKnownClasses::java_lang_ThreadGroup);
1994 CHECK(c != nullptr);
Brian Carlstromea46f952013-07-30 01:26:50 -07001995 mirror::ArtField* f = c->FindInstanceField("parent", "Ljava/lang/ThreadGroup;");
Ian Rogersc0542af2014-09-03 16:16:56 -07001996 CHECK(f != nullptr);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001997 mirror::Object* parent = f->GetObject(thread_group);
Ian Rogers98379392014-02-24 16:53:16 -08001998 soa.Self()->EndAssertNoThreadSuspension(old_cause);
Elliott Hughes4e235312011-12-02 11:34:15 -08001999 return gRegistry->Add(parent);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002000}
2001
2002JDWP::ObjectId Dbg::GetSystemThreadGroupId() {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002003 ScopedObjectAccessUnchecked soa(Thread::Current());
Brian Carlstromea46f952013-07-30 01:26:50 -07002004 mirror::ArtField* f = soa.DecodeField(WellKnownClasses::java_lang_ThreadGroup_systemThreadGroup);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002005 mirror::Object* group = f->GetObject(f->GetDeclaringClass());
Ian Rogers365c1022012-06-22 15:05:28 -07002006 return gRegistry->Add(group);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002007}
2008
2009JDWP::ObjectId Dbg::GetMainThreadGroupId() {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002010 ScopedObjectAccess soa(Thread::Current());
Brian Carlstromea46f952013-07-30 01:26:50 -07002011 mirror::ArtField* f = soa.DecodeField(WellKnownClasses::java_lang_ThreadGroup_mainThreadGroup);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002012 mirror::Object* group = f->GetObject(f->GetDeclaringClass());
Ian Rogers365c1022012-06-22 15:05:28 -07002013 return gRegistry->Add(group);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002014}
2015
Jeff Hao920af3e2013-08-28 15:46:38 -07002016JDWP::JdwpThreadStatus Dbg::ToJdwpThreadStatus(ThreadState state) {
2017 switch (state) {
2018 case kBlocked:
2019 return JDWP::TS_MONITOR;
2020 case kNative:
2021 case kRunnable:
2022 case kSuspended:
2023 return JDWP::TS_RUNNING;
2024 case kSleeping:
2025 return JDWP::TS_SLEEPING;
2026 case kStarting:
2027 case kTerminated:
2028 return JDWP::TS_ZOMBIE;
2029 case kTimedWaiting:
Sebastien Hertzbae182c2013-12-17 10:42:03 +01002030 case kWaitingForCheckPointsToRun:
Jeff Hao920af3e2013-08-28 15:46:38 -07002031 case kWaitingForDebuggerSend:
2032 case kWaitingForDebuggerSuspension:
2033 case kWaitingForDebuggerToAttach:
Sebastien Hertz138dbfc2013-12-04 18:15:25 +01002034 case kWaitingForDeoptimization:
Jeff Hao920af3e2013-08-28 15:46:38 -07002035 case kWaitingForGcToComplete:
Jeff Hao920af3e2013-08-28 15:46:38 -07002036 case kWaitingForJniOnLoad:
Sebastien Hertzbae182c2013-12-17 10:42:03 +01002037 case kWaitingForMethodTracingStart:
Jeff Hao920af3e2013-08-28 15:46:38 -07002038 case kWaitingForSignalCatcherOutput:
2039 case kWaitingInMainDebuggerLoop:
2040 case kWaitingInMainSignalCatcherLoop:
2041 case kWaitingPerformingGc:
2042 case kWaiting:
2043 return JDWP::TS_WAIT;
2044 // Don't add a 'default' here so the compiler can spot incompatible enum changes.
2045 }
2046 LOG(FATAL) << "Unknown thread state: " << state;
2047 return JDWP::TS_ZOMBIE;
2048}
2049
Sebastien Hertz52d131d2014-03-13 16:17:40 +01002050JDWP::JdwpError Dbg::GetThreadStatus(JDWP::ObjectId thread_id, JDWP::JdwpThreadStatus* pThreadStatus,
2051 JDWP::JdwpSuspendStatus* pSuspendStatus) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002052 ScopedObjectAccess soa(Thread::Current());
Elliott Hughes499c5132011-11-17 14:55:11 -08002053
Elliott Hughes9e0c1752013-01-09 14:02:58 -08002054 *pSuspendStatus = JDWP::SUSPEND_STATUS_NOT_SUSPENDED;
2055
Ian Rogers50b35e22012-10-04 10:09:15 -07002056 MutexLock mu(soa.Self(), *Locks::thread_list_lock_);
Ian Rogersc0542af2014-09-03 16:16:56 -07002057 JDWP::JdwpError error;
2058 Thread* thread = DecodeThread(soa, thread_id, &error);
Elliott Hughes221229c2013-01-08 18:17:50 -08002059 if (error != JDWP::ERR_NONE) {
2060 if (error == JDWP::ERR_THREAD_NOT_ALIVE) {
2061 *pThreadStatus = JDWP::TS_ZOMBIE;
Elliott Hughes221229c2013-01-08 18:17:50 -08002062 return JDWP::ERR_NONE;
2063 }
2064 return error;
Elliott Hughes499c5132011-11-17 14:55:11 -08002065 }
2066
Elliott Hughes9e0c1752013-01-09 14:02:58 -08002067 if (IsSuspendedForDebugger(soa, thread)) {
2068 *pSuspendStatus = JDWP::SUSPEND_STATUS_SUSPENDED;
Elliott Hughes499c5132011-11-17 14:55:11 -08002069 }
2070
Jeff Hao920af3e2013-08-28 15:46:38 -07002071 *pThreadStatus = ToJdwpThreadStatus(thread->GetState());
Elliott Hughes221229c2013-01-08 18:17:50 -08002072 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002073}
2074
Elliott Hughes221229c2013-01-08 18:17:50 -08002075JDWP::JdwpError Dbg::GetThreadDebugSuspendCount(JDWP::ObjectId thread_id, JDWP::ExpandBuf* pReply) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002076 ScopedObjectAccess soa(Thread::Current());
Ian Rogers50b35e22012-10-04 10:09:15 -07002077 MutexLock mu(soa.Self(), *Locks::thread_list_lock_);
Ian Rogersc0542af2014-09-03 16:16:56 -07002078 JDWP::JdwpError error;
2079 Thread* thread = DecodeThread(soa, thread_id, &error);
Elliott Hughes221229c2013-01-08 18:17:50 -08002080 if (error != JDWP::ERR_NONE) {
2081 return error;
Elliott Hughes2435a572012-02-17 16:07:41 -08002082 }
Ian Rogers50b35e22012-10-04 10:09:15 -07002083 MutexLock mu2(soa.Self(), *Locks::thread_suspend_count_lock_);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002084 expandBufAdd4BE(pReply, thread->GetDebugSuspendCount());
Elliott Hughes2435a572012-02-17 16:07:41 -08002085 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002086}
2087
Elliott Hughesf9501702013-01-11 11:22:27 -08002088JDWP::JdwpError Dbg::Interrupt(JDWP::ObjectId thread_id) {
2089 ScopedObjectAccess soa(Thread::Current());
2090 MutexLock mu(soa.Self(), *Locks::thread_list_lock_);
Ian Rogersc0542af2014-09-03 16:16:56 -07002091 JDWP::JdwpError error;
2092 Thread* thread = DecodeThread(soa, thread_id, &error);
Elliott Hughesf9501702013-01-11 11:22:27 -08002093 if (error != JDWP::ERR_NONE) {
2094 return error;
2095 }
Ian Rogersdd7624d2014-03-14 17:43:00 -07002096 thread->Interrupt(soa.Self());
Elliott Hughesf9501702013-01-11 11:22:27 -08002097 return JDWP::ERR_NONE;
2098}
2099
Ian Rogersc0542af2014-09-03 16:16:56 -07002100void Dbg::GetThreads(JDWP::ObjectId thread_group_id, std::vector<JDWP::ObjectId>* thread_ids) {
Ian Rogers365c1022012-06-22 15:05:28 -07002101 class ThreadListVisitor {
2102 public:
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002103 ThreadListVisitor(const ScopedObjectAccessUnchecked& soa, mirror::Object* desired_thread_group,
Ian Rogersc0542af2014-09-03 16:16:56 -07002104 std::vector<JDWP::ObjectId>* thread_ids)
Ian Rogersb726dcb2012-09-05 08:57:23 -07002105 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_)
jeffhao0dfbb7e2012-11-28 15:26:03 -08002106 : soa_(soa), desired_thread_group_(desired_thread_group), thread_ids_(thread_ids) {}
Ian Rogers365c1022012-06-22 15:05:28 -07002107
Elliott Hughesa2155262011-11-16 16:26:58 -08002108 static void Visit(Thread* t, void* arg) {
2109 reinterpret_cast<ThreadListVisitor*>(arg)->Visit(t);
2110 }
2111
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002112 // TODO: Enable annotalysis. We know lock is held in constructor, but abstraction confuses
2113 // annotalysis.
2114 void Visit(Thread* t) NO_THREAD_SAFETY_ANALYSIS {
Elliott Hughesa2155262011-11-16 16:26:58 -08002115 if (t == Dbg::GetDebugThread()) {
2116 // Skip the JDWP thread. Some debuggers get bent out of shape when they can't suspend and
2117 // query all threads, so it's easier if we just don't tell them about this thread.
2118 return;
2119 }
Sebastien Hertz9ac56022014-08-12 09:09:37 +02002120 if (t->IsStillStarting()) {
2121 // This thread is being started (and has been registered in the thread list). However, it is
2122 // not completely started yet so we must ignore it.
2123 return;
2124 }
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002125 mirror::Object* peer = t->GetPeer();
jeffhao0dfbb7e2012-11-28 15:26:03 -08002126 if (IsInDesiredThreadGroup(peer)) {
Ian Rogersc0542af2014-09-03 16:16:56 -07002127 thread_ids_->push_back(gRegistry->Add(peer));
Elliott Hughesa2155262011-11-16 16:26:58 -08002128 }
2129 }
2130
Ian Rogers365c1022012-06-22 15:05:28 -07002131 private:
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002132 bool IsInDesiredThreadGroup(mirror::Object* peer)
jeffhao0dfbb7e2012-11-28 15:26:03 -08002133 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Ian Rogersc0542af2014-09-03 16:16:56 -07002134 // peer might be nullptr if the thread is still starting up.
2135 if (peer == nullptr) {
jeffhao0dfbb7e2012-11-28 15:26:03 -08002136 // We can't tell the debugger about this thread yet.
2137 // TODO: if we identified threads to the debugger by their Thread*
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002138 // rather than their peer's mirror::Object*, we could fix this.
jeffhao0dfbb7e2012-11-28 15:26:03 -08002139 // Doing so might help us report ZOMBIE threads too.
2140 return false;
2141 }
jeffhaoc1e04902012-12-13 12:41:10 -08002142 // Do we want threads from all thread groups?
Ian Rogersc0542af2014-09-03 16:16:56 -07002143 if (desired_thread_group_ == nullptr) {
jeffhaoc1e04902012-12-13 12:41:10 -08002144 return true;
2145 }
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002146 mirror::Object* group = soa_.DecodeField(WellKnownClasses::java_lang_Thread_group)->GetObject(peer);
jeffhao0dfbb7e2012-11-28 15:26:03 -08002147 return (group == desired_thread_group_);
2148 }
2149
Mathieu Chartierdbe6f462012-09-25 16:54:50 -07002150 const ScopedObjectAccessUnchecked& soa_;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002151 mirror::Object* const desired_thread_group_;
Ian Rogersc0542af2014-09-03 16:16:56 -07002152 std::vector<JDWP::ObjectId>* const thread_ids_;
Elliott Hughesa2155262011-11-16 16:26:58 -08002153 };
2154
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002155 ScopedObjectAccessUnchecked soa(Thread::Current());
Ian Rogersc0542af2014-09-03 16:16:56 -07002156 JDWP::JdwpError error;
2157 mirror::Object* thread_group = gRegistry->Get<mirror::Object*>(thread_group_id, &error);
2158 CHECK_EQ(error, JDWP::ERR_NONE);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002159 ThreadListVisitor tlv(soa, thread_group, thread_ids);
Ian Rogers50b35e22012-10-04 10:09:15 -07002160 MutexLock mu(soa.Self(), *Locks::thread_list_lock_);
Elliott Hughesf8349362012-06-18 15:00:06 -07002161 Runtime::Current()->GetThreadList()->ForEach(ThreadListVisitor::Visit, &tlv);
Elliott Hughescaf76542012-06-28 16:08:22 -07002162}
Elliott Hughesa2155262011-11-16 16:26:58 -08002163
Ian Rogersc0542af2014-09-03 16:16:56 -07002164void Dbg::GetChildThreadGroups(JDWP::ObjectId thread_group_id,
2165 std::vector<JDWP::ObjectId>* child_thread_group_ids) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002166 ScopedObjectAccess soa(Thread::Current());
Ian Rogersc0542af2014-09-03 16:16:56 -07002167 JDWP::JdwpError error;
2168 mirror::Object* thread_group = gRegistry->Get<mirror::Object*>(thread_group_id, &error);
2169 CHECK(thread_group != nullptr) << error;
Elliott Hughescaf76542012-06-28 16:08:22 -07002170
2171 // Get the ArrayList<ThreadGroup> "groups" out of this thread group...
Brian Carlstromea46f952013-07-30 01:26:50 -07002172 mirror::ArtField* groups_field = thread_group->GetClass()->FindInstanceField("groups", "Ljava/util/List;");
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002173 mirror::Object* groups_array_list = groups_field->GetObject(thread_group);
Elliott Hughescaf76542012-06-28 16:08:22 -07002174
2175 // Get the array and size out of the ArrayList<ThreadGroup>...
Brian Carlstromea46f952013-07-30 01:26:50 -07002176 mirror::ArtField* array_field = groups_array_list->GetClass()->FindInstanceField("array", "[Ljava/lang/Object;");
2177 mirror::ArtField* size_field = groups_array_list->GetClass()->FindInstanceField("size", "I");
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002178 mirror::ObjectArray<mirror::Object>* groups_array =
2179 array_field->GetObject(groups_array_list)->AsObjectArray<mirror::Object>();
Elliott Hughescaf76542012-06-28 16:08:22 -07002180 const int32_t size = size_field->GetInt(groups_array_list);
2181
2182 // Copy the first 'size' elements out of the array into the result.
2183 for (int32_t i = 0; i < size; ++i) {
Ian Rogersc0542af2014-09-03 16:16:56 -07002184 child_thread_group_ids->push_back(gRegistry->Add(groups_array->Get(i)));
Elliott Hughesa2155262011-11-16 16:26:58 -08002185 }
2186}
2187
Ian Rogersc0542af2014-09-03 16:16:56 -07002188static int GetStackDepth(Thread* thread) SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Ian Rogers0399dde2012-06-06 17:09:28 -07002189 struct CountStackDepthVisitor : public StackVisitor {
Brian Carlstrom93ba8932013-07-17 21:31:49 -07002190 explicit CountStackDepthVisitor(Thread* thread)
Ian Rogersc0542af2014-09-03 16:16:56 -07002191 : StackVisitor(thread, nullptr), depth(0) {}
Ian Rogers0399dde2012-06-06 17:09:28 -07002192
Elliott Hughes64f574f2013-02-20 14:57:12 -08002193 // TODO: Enable annotalysis. We know lock is held in constructor, but abstraction confuses
2194 // annotalysis.
2195 bool VisitFrame() NO_THREAD_SAFETY_ANALYSIS {
Ian Rogers0399dde2012-06-06 17:09:28 -07002196 if (!GetMethod()->IsRuntimeMethod()) {
Elliott Hughesf8a2df72011-12-01 12:19:54 -08002197 ++depth;
2198 }
Elliott Hughes530fa002012-03-12 11:44:49 -07002199 return true;
Elliott Hughesa2e54f62011-11-17 13:01:30 -08002200 }
2201 size_t depth;
2202 };
Elliott Hughes08fc03a2012-06-26 17:34:00 -07002203
Ian Rogers7a22fa62013-01-23 12:16:16 -08002204 CountStackDepthVisitor visitor(thread);
Ian Rogers0399dde2012-06-06 17:09:28 -07002205 visitor.WalkStack();
Elliott Hughesa2e54f62011-11-17 13:01:30 -08002206 return visitor.depth;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002207}
2208
Ian Rogersc0542af2014-09-03 16:16:56 -07002209JDWP::JdwpError Dbg::GetThreadFrameCount(JDWP::ObjectId thread_id, size_t* result) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002210 ScopedObjectAccess soa(Thread::Current());
jeffhaoa77f0f62012-12-05 17:19:31 -08002211 MutexLock mu(soa.Self(), *Locks::thread_list_lock_);
Ian Rogersc0542af2014-09-03 16:16:56 -07002212 JDWP::JdwpError error;
2213 *result = 0;
2214 Thread* thread = DecodeThread(soa, thread_id, &error);
Elliott Hughes221229c2013-01-08 18:17:50 -08002215 if (error != JDWP::ERR_NONE) {
2216 return error;
2217 }
Elliott Hughesf15f4a02013-01-09 10:09:38 -08002218 if (!IsSuspendedForDebugger(soa, thread)) {
2219 return JDWP::ERR_THREAD_NOT_SUSPENDED;
2220 }
Ian Rogersc0542af2014-09-03 16:16:56 -07002221 *result = GetStackDepth(thread);
Elliott Hughes221229c2013-01-08 18:17:50 -08002222 return JDWP::ERR_NONE;
Elliott Hughes86964332012-02-15 19:37:42 -08002223}
2224
Ian Rogers306057f2012-11-26 12:45:53 -08002225JDWP::JdwpError Dbg::GetThreadFrames(JDWP::ObjectId thread_id, size_t start_frame,
2226 size_t frame_count, JDWP::ExpandBuf* buf) {
Elliott Hughes6e9d22c2012-06-22 15:02:37 -07002227 class GetFrameVisitor : public StackVisitor {
2228 public:
Ian Rogers7a22fa62013-01-23 12:16:16 -08002229 GetFrameVisitor(Thread* thread, size_t start_frame, size_t frame_count, JDWP::ExpandBuf* buf)
Ian Rogersb726dcb2012-09-05 08:57:23 -07002230 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_)
Ian Rogersc0542af2014-09-03 16:16:56 -07002231 : StackVisitor(thread, nullptr), depth_(0),
Elliott Hughes6e9d22c2012-06-22 15:02:37 -07002232 start_frame_(start_frame), frame_count_(frame_count), buf_(buf) {
2233 expandBufAdd4BE(buf_, frame_count_);
Elliott Hughes03181a82011-11-17 17:22:21 -08002234 }
Ian Rogers0399dde2012-06-06 17:09:28 -07002235
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002236 // TODO: Enable annotalysis. We know lock is held in constructor, but abstraction confuses
2237 // annotalysis.
2238 virtual bool VisitFrame() NO_THREAD_SAFETY_ANALYSIS {
Ian Rogers0399dde2012-06-06 17:09:28 -07002239 if (GetMethod()->IsRuntimeMethod()) {
Brian Carlstrom7934ac22013-07-26 10:54:15 -07002240 return true; // The debugger can't do anything useful with a frame that has no Method*.
Elliott Hughes03181a82011-11-17 17:22:21 -08002241 }
Elliott Hughes6e9d22c2012-06-22 15:02:37 -07002242 if (depth_ >= start_frame_ + frame_count_) {
Elliott Hughes530fa002012-03-12 11:44:49 -07002243 return false;
Elliott Hughes03181a82011-11-17 17:22:21 -08002244 }
Elliott Hughes6e9d22c2012-06-22 15:02:37 -07002245 if (depth_ >= start_frame_) {
2246 JDWP::FrameId frame_id(GetFrameId());
2247 JDWP::JdwpLocation location;
Ian Rogersc0542af2014-09-03 16:16:56 -07002248 SetLocation(&location, GetMethod(), GetDexPc());
Ian Rogersef7d42f2014-01-06 12:55:46 -08002249 VLOG(jdwp) << StringPrintf(" Frame %3zd: id=%3" PRIu64 " ", depth_, frame_id) << location;
Elliott Hughes6e9d22c2012-06-22 15:02:37 -07002250 expandBufAdd8BE(buf_, frame_id);
2251 expandBufAddLocation(buf_, location);
2252 }
2253 ++depth_;
Elliott Hughes530fa002012-03-12 11:44:49 -07002254 return true;
Elliott Hughes03181a82011-11-17 17:22:21 -08002255 }
Elliott Hughes6e9d22c2012-06-22 15:02:37 -07002256
2257 private:
2258 size_t depth_;
2259 const size_t start_frame_;
2260 const size_t frame_count_;
2261 JDWP::ExpandBuf* buf_;
Elliott Hughes03181a82011-11-17 17:22:21 -08002262 };
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002263
2264 ScopedObjectAccessUnchecked soa(Thread::Current());
jeffhaoa77f0f62012-12-05 17:19:31 -08002265 MutexLock mu(soa.Self(), *Locks::thread_list_lock_);
Ian Rogersc0542af2014-09-03 16:16:56 -07002266 JDWP::JdwpError error;
2267 Thread* thread = DecodeThread(soa, thread_id, &error);
Elliott Hughes221229c2013-01-08 18:17:50 -08002268 if (error != JDWP::ERR_NONE) {
2269 return error;
2270 }
Elliott Hughesf15f4a02013-01-09 10:09:38 -08002271 if (!IsSuspendedForDebugger(soa, thread)) {
2272 return JDWP::ERR_THREAD_NOT_SUSPENDED;
2273 }
Ian Rogers7a22fa62013-01-23 12:16:16 -08002274 GetFrameVisitor visitor(thread, start_frame, frame_count, buf);
Ian Rogers0399dde2012-06-06 17:09:28 -07002275 visitor.WalkStack();
Elliott Hughes6e9d22c2012-06-22 15:02:37 -07002276 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002277}
2278
2279JDWP::ObjectId Dbg::GetThreadSelfId() {
Mathieu Chartierdbe6f462012-09-25 16:54:50 -07002280 ScopedObjectAccessUnchecked soa(Thread::Current());
Ian Rogerscfaa4552012-11-26 21:00:08 -08002281 return gRegistry->Add(soa.Self()->GetPeer());
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002282}
2283
Elliott Hughes475fc232011-10-25 15:00:35 -07002284void Dbg::SuspendVM() {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002285 Runtime::Current()->GetThreadList()->SuspendAllForDebugger();
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002286}
2287
2288void Dbg::ResumeVM() {
Elliott Hughesc61a2672012-06-21 14:52:29 -07002289 Runtime::Current()->GetThreadList()->UndoDebuggerSuspensions();
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002290}
2291
Elliott Hughes221229c2013-01-08 18:17:50 -08002292JDWP::JdwpError Dbg::SuspendThread(JDWP::ObjectId thread_id, bool request_suspension) {
Ian Rogersf3d874c2014-07-17 18:52:42 -07002293 Thread* self = Thread::Current();
Ian Rogersc0542af2014-09-03 16:16:56 -07002294 ScopedLocalRef<jobject> peer(self->GetJniEnv(), nullptr);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002295 {
Ian Rogersf3d874c2014-07-17 18:52:42 -07002296 ScopedObjectAccess soa(self);
Ian Rogersc0542af2014-09-03 16:16:56 -07002297 JDWP::JdwpError error;
2298 peer.reset(soa.AddLocalReference<jobject>(gRegistry->Get<mirror::Object*>(thread_id, &error)));
Elliott Hughes4e235312011-12-02 11:34:15 -08002299 }
Ian Rogersc0542af2014-09-03 16:16:56 -07002300 if (peer.get() == nullptr) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002301 return JDWP::ERR_THREAD_NOT_ALIVE;
2302 }
Ian Rogersf3d874c2014-07-17 18:52:42 -07002303 // Suspend thread to build stack trace. Take suspend thread lock to avoid races with threads
2304 // trying to suspend this one.
2305 MutexLock mu(self, *Locks::thread_list_suspend_thread_lock_);
Elliott Hughesf327e072013-01-09 16:01:26 -08002306 bool timed_out;
Brian Carlstromba32de42014-08-27 23:43:46 -07002307 ThreadList* thread_list = Runtime::Current()->GetThreadList();
2308 Thread* thread = thread_list->SuspendThreadByPeer(peer.get(), request_suspension, true,
2309 &timed_out);
Ian Rogersc0542af2014-09-03 16:16:56 -07002310 if (thread != nullptr) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002311 return JDWP::ERR_NONE;
Elliott Hughesf327e072013-01-09 16:01:26 -08002312 } else if (timed_out) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002313 return JDWP::ERR_INTERNAL;
2314 } else {
2315 return JDWP::ERR_THREAD_NOT_ALIVE;
2316 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002317}
2318
Elliott Hughes221229c2013-01-08 18:17:50 -08002319void Dbg::ResumeThread(JDWP::ObjectId thread_id) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002320 ScopedObjectAccessUnchecked soa(Thread::Current());
Ian Rogersc0542af2014-09-03 16:16:56 -07002321 JDWP::JdwpError error;
2322 mirror::Object* peer = gRegistry->Get<mirror::Object*>(thread_id, &error);
2323 CHECK(peer != nullptr) << error;
jeffhaoa77f0f62012-12-05 17:19:31 -08002324 Thread* thread;
2325 {
2326 MutexLock mu(soa.Self(), *Locks::thread_list_lock_);
2327 thread = Thread::FromManagedThread(soa, peer);
2328 }
Ian Rogersc0542af2014-09-03 16:16:56 -07002329 if (thread == nullptr) {
Elliott Hughes4e235312011-12-02 11:34:15 -08002330 LOG(WARNING) << "No such thread for resume: " << peer;
2331 return;
2332 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002333 bool needs_resume;
2334 {
Ian Rogers50b35e22012-10-04 10:09:15 -07002335 MutexLock mu2(soa.Self(), *Locks::thread_suspend_count_lock_);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002336 needs_resume = thread->GetSuspendCount() > 0;
2337 }
2338 if (needs_resume) {
Elliott Hughes546b9862012-06-20 16:06:13 -07002339 Runtime::Current()->GetThreadList()->Resume(thread, true);
2340 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002341}
2342
2343void Dbg::SuspendSelf() {
Elliott Hughes475fc232011-10-25 15:00:35 -07002344 Runtime::Current()->GetThreadList()->SuspendSelfForDebugger();
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002345}
2346
Ian Rogers0399dde2012-06-06 17:09:28 -07002347struct GetThisVisitor : public StackVisitor {
Ian Rogers7a22fa62013-01-23 12:16:16 -08002348 GetThisVisitor(Thread* thread, Context* context, JDWP::FrameId frame_id)
Ian Rogersb726dcb2012-09-05 08:57:23 -07002349 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_)
Ian Rogersc0542af2014-09-03 16:16:56 -07002350 : StackVisitor(thread, context), this_object(nullptr), frame_id(frame_id) {}
Ian Rogers0399dde2012-06-06 17:09:28 -07002351
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002352 // TODO: Enable annotalysis. We know lock is held in constructor, but abstraction confuses
2353 // annotalysis.
2354 virtual bool VisitFrame() NO_THREAD_SAFETY_ANALYSIS {
Elliott Hughes6e9d22c2012-06-22 15:02:37 -07002355 if (frame_id != GetFrameId()) {
Ian Rogers0399dde2012-06-06 17:09:28 -07002356 return true; // continue
Ian Rogers0399dde2012-06-06 17:09:28 -07002357 } else {
Ian Rogers62d6c772013-02-27 08:32:07 -08002358 this_object = GetThisObject();
2359 return false;
Ian Rogers0399dde2012-06-06 17:09:28 -07002360 }
Elliott Hughes86b00102011-12-05 17:54:26 -08002361 }
Ian Rogers0399dde2012-06-06 17:09:28 -07002362
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002363 mirror::Object* this_object;
Elliott Hughes6e9d22c2012-06-22 15:02:37 -07002364 JDWP::FrameId frame_id;
Ian Rogers0399dde2012-06-06 17:09:28 -07002365};
2366
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002367JDWP::JdwpError Dbg::GetThisObject(JDWP::ObjectId thread_id, JDWP::FrameId frame_id,
2368 JDWP::ObjectId* result) {
2369 ScopedObjectAccessUnchecked soa(Thread::Current());
2370 Thread* thread;
2371 {
Ian Rogers50b35e22012-10-04 10:09:15 -07002372 MutexLock mu(soa.Self(), *Locks::thread_list_lock_);
Ian Rogersc0542af2014-09-03 16:16:56 -07002373 JDWP::JdwpError error;
2374 thread = DecodeThread(soa, thread_id, &error);
Elliott Hughes221229c2013-01-08 18:17:50 -08002375 if (error != JDWP::ERR_NONE) {
2376 return error;
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002377 }
Elliott Hughes9e0c1752013-01-09 14:02:58 -08002378 if (!IsSuspendedForDebugger(soa, thread)) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002379 return JDWP::ERR_THREAD_NOT_SUSPENDED;
2380 }
Elliott Hughes6e9d22c2012-06-22 15:02:37 -07002381 }
Ian Rogers700a4022014-05-19 16:49:03 -07002382 std::unique_ptr<Context> context(Context::Create());
Ian Rogers7a22fa62013-01-23 12:16:16 -08002383 GetThisVisitor visitor(thread, context.get(), frame_id);
Ian Rogers0399dde2012-06-06 17:09:28 -07002384 visitor.WalkStack();
Elliott Hughes6e9d22c2012-06-22 15:02:37 -07002385 *result = gRegistry->Add(visitor.this_object);
2386 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002387}
2388
Sebastien Hertzcb19ebf2014-03-11 15:26:35 +01002389JDWP::JdwpError Dbg::GetLocalValue(JDWP::ObjectId thread_id, JDWP::FrameId frame_id, int slot,
2390 JDWP::JdwpTag tag, uint8_t* buf, size_t width) {
Ian Rogers0399dde2012-06-06 17:09:28 -07002391 struct GetLocalVisitor : public StackVisitor {
Ian Rogers98379392014-02-24 16:53:16 -08002392 GetLocalVisitor(const ScopedObjectAccessUnchecked& soa, Thread* thread, Context* context,
2393 JDWP::FrameId frame_id, int slot, JDWP::JdwpTag tag, uint8_t* buf, size_t width)
Ian Rogersb726dcb2012-09-05 08:57:23 -07002394 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_)
Ian Rogers98379392014-02-24 16:53:16 -08002395 : StackVisitor(thread, context), soa_(soa), frame_id_(frame_id), slot_(slot), tag_(tag),
Sebastien Hertzcb19ebf2014-03-11 15:26:35 +01002396 buf_(buf), width_(width), error_(JDWP::ERR_NONE) {}
Ian Rogersca190662012-06-26 15:45:57 -07002397
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002398 // TODO: Enable annotalysis. We know lock is held in constructor, but abstraction confuses
2399 // annotalysis.
2400 bool VisitFrame() NO_THREAD_SAFETY_ANALYSIS {
Ian Rogers0399dde2012-06-06 17:09:28 -07002401 if (GetFrameId() != frame_id_) {
2402 return true; // Not our frame, carry on.
Elliott Hughesdbb40792011-11-18 17:05:22 -08002403 }
Ian Rogers0399dde2012-06-06 17:09:28 -07002404 // TODO: check that the tag is compatible with the actual type of the slot!
Sebastien Hertzcb19ebf2014-03-11 15:26:35 +01002405 // TODO: check slot is valid for this method or return INVALID_SLOT error.
Brian Carlstromea46f952013-07-30 01:26:50 -07002406 mirror::ArtMethod* m = GetMethod();
Sebastien Hertzcb19ebf2014-03-11 15:26:35 +01002407 if (m->IsNative()) {
2408 // We can't read local value from native method.
2409 error_ = JDWP::ERR_OPAQUE_FRAME;
2410 return false;
2411 }
Ian Rogers0399dde2012-06-06 17:09:28 -07002412 uint16_t reg = DemangleSlot(slot_, m);
Sebastien Hertz0bcb2902014-06-17 15:52:45 +02002413 constexpr JDWP::JdwpError kFailureErrorCode = JDWP::ERR_ABSENT_INFORMATION;
Ian Rogers0399dde2012-06-06 17:09:28 -07002414 switch (tag_) {
Sebastien Hertz0bcb2902014-06-17 15:52:45 +02002415 case JDWP::JT_BOOLEAN: {
Ian Rogers0399dde2012-06-06 17:09:28 -07002416 CHECK_EQ(width_, 1U);
Sebastien Hertz0bcb2902014-06-17 15:52:45 +02002417 uint32_t intVal;
2418 if (GetVReg(m, reg, kIntVReg, &intVal)) {
2419 VLOG(jdwp) << "get boolean local " << reg << " = " << intVal;
2420 JDWP::Set1(buf_+1, intVal != 0);
2421 } else {
2422 VLOG(jdwp) << "failed to get boolean local " << reg;
2423 error_ = kFailureErrorCode;
2424 }
2425 break;
Ian Rogers0399dde2012-06-06 17:09:28 -07002426 }
Sebastien Hertz0bcb2902014-06-17 15:52:45 +02002427 case JDWP::JT_BYTE: {
Ian Rogers0399dde2012-06-06 17:09:28 -07002428 CHECK_EQ(width_, 1U);
Sebastien Hertz0bcb2902014-06-17 15:52:45 +02002429 uint32_t intVal;
2430 if (GetVReg(m, reg, kIntVReg, &intVal)) {
2431 VLOG(jdwp) << "get byte local " << reg << " = " << intVal;
2432 JDWP::Set1(buf_+1, intVal);
2433 } else {
2434 VLOG(jdwp) << "failed to get byte local " << reg;
2435 error_ = kFailureErrorCode;
2436 }
2437 break;
Ian Rogers0399dde2012-06-06 17:09:28 -07002438 }
Sebastien Hertz0bcb2902014-06-17 15:52:45 +02002439 case JDWP::JT_SHORT:
2440 case JDWP::JT_CHAR: {
Ian Rogers0399dde2012-06-06 17:09:28 -07002441 CHECK_EQ(width_, 2U);
Sebastien Hertz0bcb2902014-06-17 15:52:45 +02002442 uint32_t intVal;
2443 if (GetVReg(m, reg, kIntVReg, &intVal)) {
2444 VLOG(jdwp) << "get short/char local " << reg << " = " << intVal;
2445 JDWP::Set2BE(buf_+1, intVal);
2446 } else {
2447 VLOG(jdwp) << "failed to get short/char local " << reg;
2448 error_ = kFailureErrorCode;
Sebastien Hertzaa9b3ae2014-06-13 14:49:27 +02002449 }
Sebastien Hertz0bcb2902014-06-17 15:52:45 +02002450 break;
Sebastien Hertzaa9b3ae2014-06-13 14:49:27 +02002451 }
Sebastien Hertz0bcb2902014-06-17 15:52:45 +02002452 case JDWP::JT_INT: {
2453 CHECK_EQ(width_, 4U);
2454 uint32_t intVal;
2455 if (GetVReg(m, reg, kIntVReg, &intVal)) {
2456 VLOG(jdwp) << "get int local " << reg << " = " << intVal;
2457 JDWP::Set4BE(buf_+1, intVal);
2458 } else {
2459 VLOG(jdwp) << "failed to get int local " << reg;
2460 error_ = kFailureErrorCode;
Sebastien Hertz8ebd94a2014-06-17 09:49:21 +00002461 }
Sebastien Hertz0bcb2902014-06-17 15:52:45 +02002462 break;
Sebastien Hertz8ebd94a2014-06-17 09:49:21 +00002463 }
Sebastien Hertz0bcb2902014-06-17 15:52:45 +02002464 case JDWP::JT_FLOAT: {
2465 CHECK_EQ(width_, 4U);
2466 uint32_t intVal;
2467 if (GetVReg(m, reg, kFloatVReg, &intVal)) {
2468 VLOG(jdwp) << "get float local " << reg << " = " << intVal;
2469 JDWP::Set4BE(buf_+1, intVal);
2470 } else {
2471 VLOG(jdwp) << "failed to get float local " << reg;
2472 error_ = kFailureErrorCode;
2473 }
2474 break;
2475 }
2476 case JDWP::JT_ARRAY:
2477 case JDWP::JT_CLASS_LOADER:
2478 case JDWP::JT_CLASS_OBJECT:
2479 case JDWP::JT_OBJECT:
2480 case JDWP::JT_STRING:
2481 case JDWP::JT_THREAD:
2482 case JDWP::JT_THREAD_GROUP: {
2483 CHECK_EQ(width_, sizeof(JDWP::ObjectId));
2484 uint32_t intVal;
2485 if (GetVReg(m, reg, kReferenceVReg, &intVal)) {
2486 mirror::Object* o = reinterpret_cast<mirror::Object*>(intVal);
2487 VLOG(jdwp) << "get " << tag_ << " object local " << reg << " = " << o;
2488 if (!Runtime::Current()->GetHeap()->IsValidObjectAddress(o)) {
2489 LOG(FATAL) << "Register " << reg << " expected to hold " << tag_ << " object: " << o;
2490 }
2491 tag_ = TagFromObject(soa_, o);
2492 JDWP::SetObjectId(buf_+1, gRegistry->Add(o));
2493 } else {
2494 VLOG(jdwp) << "failed to get " << tag_ << " object local " << reg;
2495 error_ = kFailureErrorCode;
2496 }
2497 break;
2498 }
2499 case JDWP::JT_DOUBLE: {
Ian Rogers2bcb4a42012-11-08 10:39:18 -08002500 CHECK_EQ(width_, 8U);
Sebastien Hertzc901dd72014-07-16 11:56:07 +02002501 uint64_t longVal;
2502 if (GetVRegPair(m, reg, kDoubleLoVReg, kDoubleHiVReg, &longVal)) {
2503 VLOG(jdwp) << "get double local " << reg << " = " << longVal;
Sebastien Hertz0bcb2902014-06-17 15:52:45 +02002504 JDWP::Set8BE(buf_+1, longVal);
2505 } else {
2506 VLOG(jdwp) << "failed to get double local " << reg;
2507 error_ = kFailureErrorCode;
2508 }
2509 break;
Ian Rogers2bcb4a42012-11-08 10:39:18 -08002510 }
Sebastien Hertz0bcb2902014-06-17 15:52:45 +02002511 case JDWP::JT_LONG: {
Ian Rogers0399dde2012-06-06 17:09:28 -07002512 CHECK_EQ(width_, 8U);
Sebastien Hertzc901dd72014-07-16 11:56:07 +02002513 uint64_t longVal;
2514 if (GetVRegPair(m, reg, kLongLoVReg, kLongHiVReg, &longVal)) {
2515 VLOG(jdwp) << "get long local " << reg << " = " << longVal;
Sebastien Hertz0bcb2902014-06-17 15:52:45 +02002516 JDWP::Set8BE(buf_+1, longVal);
2517 } else {
2518 VLOG(jdwp) << "failed to get long local " << reg;
2519 error_ = kFailureErrorCode;
2520 }
2521 break;
Ian Rogers0399dde2012-06-06 17:09:28 -07002522 }
Sebastien Hertz0bcb2902014-06-17 15:52:45 +02002523 default:
2524 LOG(FATAL) << "Unknown tag " << tag_;
2525 break;
Ian Rogers0399dde2012-06-06 17:09:28 -07002526 }
2527
2528 // Prepend tag, which may have been updated.
2529 JDWP::Set1(buf_, tag_);
2530 return false;
2531 }
Ian Rogers98379392014-02-24 16:53:16 -08002532 const ScopedObjectAccessUnchecked& soa_;
Ian Rogers0399dde2012-06-06 17:09:28 -07002533 const JDWP::FrameId frame_id_;
2534 const int slot_;
2535 JDWP::JdwpTag tag_;
2536 uint8_t* const buf_;
2537 const size_t width_;
Sebastien Hertzcb19ebf2014-03-11 15:26:35 +01002538 JDWP::JdwpError error_;
Ian Rogers0399dde2012-06-06 17:09:28 -07002539 };
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002540
2541 ScopedObjectAccessUnchecked soa(Thread::Current());
jeffhaoa77f0f62012-12-05 17:19:31 -08002542 MutexLock mu(soa.Self(), *Locks::thread_list_lock_);
Ian Rogersc0542af2014-09-03 16:16:56 -07002543 JDWP::JdwpError error;
2544 Thread* thread = DecodeThread(soa, thread_id, &error);
Elliott Hughes221229c2013-01-08 18:17:50 -08002545 if (error != JDWP::ERR_NONE) {
Sebastien Hertzcb19ebf2014-03-11 15:26:35 +01002546 return error;
Elliott Hughes221229c2013-01-08 18:17:50 -08002547 }
Sebastien Hertzcb19ebf2014-03-11 15:26:35 +01002548 // TODO check thread is suspended by the debugger ?
Ian Rogers700a4022014-05-19 16:49:03 -07002549 std::unique_ptr<Context> context(Context::Create());
Ian Rogers98379392014-02-24 16:53:16 -08002550 GetLocalVisitor visitor(soa, thread, context.get(), frame_id, slot, tag, buf, width);
Ian Rogers0399dde2012-06-06 17:09:28 -07002551 visitor.WalkStack();
Sebastien Hertzcb19ebf2014-03-11 15:26:35 +01002552 return visitor.error_;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002553}
2554
Sebastien Hertzcb19ebf2014-03-11 15:26:35 +01002555JDWP::JdwpError Dbg::SetLocalValue(JDWP::ObjectId thread_id, JDWP::FrameId frame_id, int slot,
2556 JDWP::JdwpTag tag, uint64_t value, size_t width) {
Ian Rogers0399dde2012-06-06 17:09:28 -07002557 struct SetLocalVisitor : public StackVisitor {
Ian Rogers7a22fa62013-01-23 12:16:16 -08002558 SetLocalVisitor(Thread* thread, Context* context,
Ian Rogers0399dde2012-06-06 17:09:28 -07002559 JDWP::FrameId frame_id, int slot, JDWP::JdwpTag tag, uint64_t value,
Ian Rogersca190662012-06-26 15:45:57 -07002560 size_t width)
Ian Rogersb726dcb2012-09-05 08:57:23 -07002561 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_)
Ian Rogers7a22fa62013-01-23 12:16:16 -08002562 : StackVisitor(thread, context),
Sebastien Hertzcb19ebf2014-03-11 15:26:35 +01002563 frame_id_(frame_id), slot_(slot), tag_(tag), value_(value), width_(width),
2564 error_(JDWP::ERR_NONE) {}
Ian Rogersca190662012-06-26 15:45:57 -07002565
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002566 // TODO: Enable annotalysis. We know lock is held in constructor, but abstraction confuses
2567 // annotalysis.
2568 bool VisitFrame() NO_THREAD_SAFETY_ANALYSIS {
Ian Rogers0399dde2012-06-06 17:09:28 -07002569 if (GetFrameId() != frame_id_) {
2570 return true; // Not our frame, carry on.
2571 }
2572 // TODO: check that the tag is compatible with the actual type of the slot!
Sebastien Hertzcb19ebf2014-03-11 15:26:35 +01002573 // TODO: check slot is valid for this method or return INVALID_SLOT error.
Brian Carlstromea46f952013-07-30 01:26:50 -07002574 mirror::ArtMethod* m = GetMethod();
Sebastien Hertzcb19ebf2014-03-11 15:26:35 +01002575 if (m->IsNative()) {
2576 // We can't read local value from native method.
2577 error_ = JDWP::ERR_OPAQUE_FRAME;
2578 return false;
2579 }
Ian Rogers0399dde2012-06-06 17:09:28 -07002580 uint16_t reg = DemangleSlot(slot_, m);
Sebastien Hertz0bcb2902014-06-17 15:52:45 +02002581 constexpr JDWP::JdwpError kFailureErrorCode = JDWP::ERR_ABSENT_INFORMATION;
Ian Rogers0399dde2012-06-06 17:09:28 -07002582 switch (tag_) {
2583 case JDWP::JT_BOOLEAN:
2584 case JDWP::JT_BYTE:
2585 CHECK_EQ(width_, 1U);
Sebastien Hertz0bcb2902014-06-17 15:52:45 +02002586 if (!SetVReg(m, reg, static_cast<uint32_t>(value_), kIntVReg)) {
2587 VLOG(jdwp) << "failed to set boolean/byte local " << reg << " = "
2588 << static_cast<uint32_t>(value_);
2589 error_ = kFailureErrorCode;
2590 }
Ian Rogers0399dde2012-06-06 17:09:28 -07002591 break;
2592 case JDWP::JT_SHORT:
2593 case JDWP::JT_CHAR:
2594 CHECK_EQ(width_, 2U);
Sebastien Hertz0bcb2902014-06-17 15:52:45 +02002595 if (!SetVReg(m, reg, static_cast<uint32_t>(value_), kIntVReg)) {
2596 VLOG(jdwp) << "failed to set short/char local " << reg << " = "
2597 << static_cast<uint32_t>(value_);
2598 error_ = kFailureErrorCode;
2599 }
Ian Rogers0399dde2012-06-06 17:09:28 -07002600 break;
2601 case JDWP::JT_INT:
Ian Rogers2bcb4a42012-11-08 10:39:18 -08002602 CHECK_EQ(width_, 4U);
Sebastien Hertz0bcb2902014-06-17 15:52:45 +02002603 if (!SetVReg(m, reg, static_cast<uint32_t>(value_), kIntVReg)) {
2604 VLOG(jdwp) << "failed to set int local " << reg << " = "
2605 << static_cast<uint32_t>(value_);
2606 error_ = kFailureErrorCode;
2607 }
Ian Rogers2bcb4a42012-11-08 10:39:18 -08002608 break;
Ian Rogers0399dde2012-06-06 17:09:28 -07002609 case JDWP::JT_FLOAT:
2610 CHECK_EQ(width_, 4U);
Sebastien Hertz0bcb2902014-06-17 15:52:45 +02002611 if (!SetVReg(m, reg, static_cast<uint32_t>(value_), kFloatVReg)) {
2612 VLOG(jdwp) << "failed to set float local " << reg << " = "
2613 << static_cast<uint32_t>(value_);
2614 error_ = kFailureErrorCode;
2615 }
Ian Rogers0399dde2012-06-06 17:09:28 -07002616 break;
2617 case JDWP::JT_ARRAY:
Sebastien Hertz0bcb2902014-06-17 15:52:45 +02002618 case JDWP::JT_CLASS_LOADER:
2619 case JDWP::JT_CLASS_OBJECT:
Ian Rogers0399dde2012-06-06 17:09:28 -07002620 case JDWP::JT_OBJECT:
2621 case JDWP::JT_STRING:
Sebastien Hertz0bcb2902014-06-17 15:52:45 +02002622 case JDWP::JT_THREAD:
2623 case JDWP::JT_THREAD_GROUP: {
Ian Rogers0399dde2012-06-06 17:09:28 -07002624 CHECK_EQ(width_, sizeof(JDWP::ObjectId));
Ian Rogersc0542af2014-09-03 16:16:56 -07002625 JDWP::JdwpError error;
2626 mirror::Object* o =
2627 gRegistry->Get<mirror::Object*>(static_cast<JDWP::ObjectId>(value_), &error);
2628 if (error != JDWP::ERR_NONE) {
2629 VLOG(jdwp) << tag_ << " object " << value_ << " is an invalid object";
Sebastien Hertz0bcb2902014-06-17 15:52:45 +02002630 error_ = JDWP::ERR_INVALID_OBJECT;
2631 } else if (!SetVReg(m, reg, static_cast<uint32_t>(reinterpret_cast<uintptr_t>(o)),
2632 kReferenceVReg)) {
2633 VLOG(jdwp) << "failed to set " << tag_ << " object local " << reg << " = " << o;
2634 error_ = kFailureErrorCode;
Ian Rogers0399dde2012-06-06 17:09:28 -07002635 }
Sebastien Hertz0bcb2902014-06-17 15:52:45 +02002636 break;
Ian Rogers0399dde2012-06-06 17:09:28 -07002637 }
Sebastien Hertz0bcb2902014-06-17 15:52:45 +02002638 case JDWP::JT_DOUBLE: {
Ian Rogers2bcb4a42012-11-08 10:39:18 -08002639 CHECK_EQ(width_, 8U);
Sebastien Hertzc901dd72014-07-16 11:56:07 +02002640 bool success = SetVRegPair(m, reg, value_, kDoubleLoVReg, kDoubleHiVReg);
Sebastien Hertz0bcb2902014-06-17 15:52:45 +02002641 if (!success) {
Sebastien Hertzc901dd72014-07-16 11:56:07 +02002642 VLOG(jdwp) << "failed to set double local " << reg << " = " << value_;
Sebastien Hertz0bcb2902014-06-17 15:52:45 +02002643 error_ = kFailureErrorCode;
2644 }
Ian Rogers2bcb4a42012-11-08 10:39:18 -08002645 break;
Sebastien Hertz0bcb2902014-06-17 15:52:45 +02002646 }
2647 case JDWP::JT_LONG: {
Ian Rogers0399dde2012-06-06 17:09:28 -07002648 CHECK_EQ(width_, 8U);
Sebastien Hertzc901dd72014-07-16 11:56:07 +02002649 bool success = SetVRegPair(m, reg, value_, kLongLoVReg, kLongHiVReg);
Sebastien Hertz0bcb2902014-06-17 15:52:45 +02002650 if (!success) {
Sebastien Hertzc901dd72014-07-16 11:56:07 +02002651 VLOG(jdwp) << "failed to set double local " << reg << " = " << value_;
Sebastien Hertz0bcb2902014-06-17 15:52:45 +02002652 error_ = kFailureErrorCode;
2653 }
Ian Rogers0399dde2012-06-06 17:09:28 -07002654 break;
Sebastien Hertz0bcb2902014-06-17 15:52:45 +02002655 }
Ian Rogers0399dde2012-06-06 17:09:28 -07002656 default:
2657 LOG(FATAL) << "Unknown tag " << tag_;
2658 break;
2659 }
2660 return false;
2661 }
2662
2663 const JDWP::FrameId frame_id_;
2664 const int slot_;
2665 const JDWP::JdwpTag tag_;
2666 const uint64_t value_;
2667 const size_t width_;
Sebastien Hertzcb19ebf2014-03-11 15:26:35 +01002668 JDWP::JdwpError error_;
Ian Rogers0399dde2012-06-06 17:09:28 -07002669 };
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002670
2671 ScopedObjectAccessUnchecked soa(Thread::Current());
jeffhaoa77f0f62012-12-05 17:19:31 -08002672 MutexLock mu(soa.Self(), *Locks::thread_list_lock_);
Ian Rogersc0542af2014-09-03 16:16:56 -07002673 JDWP::JdwpError error;
2674 Thread* thread = DecodeThread(soa, thread_id, &error);
Elliott Hughes221229c2013-01-08 18:17:50 -08002675 if (error != JDWP::ERR_NONE) {
Sebastien Hertzcb19ebf2014-03-11 15:26:35 +01002676 return error;
Elliott Hughes221229c2013-01-08 18:17:50 -08002677 }
Sebastien Hertzcb19ebf2014-03-11 15:26:35 +01002678 // TODO check thread is suspended by the debugger ?
Ian Rogers700a4022014-05-19 16:49:03 -07002679 std::unique_ptr<Context> context(Context::Create());
Ian Rogers7a22fa62013-01-23 12:16:16 -08002680 SetLocalVisitor visitor(thread, context.get(), frame_id, slot, tag, value, width);
Ian Rogers0399dde2012-06-06 17:09:28 -07002681 visitor.WalkStack();
Sebastien Hertzcb19ebf2014-03-11 15:26:35 +01002682 return visitor.error_;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002683}
2684
Sebastien Hertz3f52eaf2014-04-04 17:50:18 +02002685JDWP::ObjectId Dbg::GetThisObjectIdForEvent(mirror::Object* this_object) {
2686 // If 'this_object' isn't already in the registry, we know that we're not looking for it, so
2687 // there's no point adding it to the registry and burning through ids.
2688 // When registering an event request with an instance filter, we've been given an existing object
2689 // id so it must already be present in the registry when the event fires.
2690 JDWP::ObjectId this_id = 0;
2691 if (this_object != nullptr && gRegistry->Contains(this_object)) {
2692 this_id = gRegistry->Add(this_object);
2693 }
2694 return this_id;
2695}
2696
Ian Rogersef7d42f2014-01-06 12:55:46 -08002697void Dbg::PostLocationEvent(mirror::ArtMethod* m, int dex_pc, mirror::Object* this_object,
Jeff Hao579b0242013-11-18 13:16:49 -08002698 int event_flags, const JValue* return_value) {
Sebastien Hertz3f52eaf2014-04-04 17:50:18 +02002699 if (!IsDebuggerActive()) {
2700 return;
2701 }
2702 DCHECK(m != nullptr);
2703 DCHECK_EQ(m->IsStatic(), this_object == nullptr);
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08002704 JDWP::JdwpLocation location;
Ian Rogersc0542af2014-09-03 16:16:56 -07002705 SetLocation(&location, m, dex_pc);
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08002706
Sebastien Hertz3f52eaf2014-04-04 17:50:18 +02002707 // We need 'this' for InstanceOnly filters only.
2708 JDWP::ObjectId this_id = GetThisObjectIdForEvent(this_object);
Jeff Hao579b0242013-11-18 13:16:49 -08002709 gJdwpState->PostLocationEvent(&location, this_id, event_flags, return_value);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002710}
2711
Sebastien Hertz3f52eaf2014-04-04 17:50:18 +02002712void Dbg::PostFieldAccessEvent(mirror::ArtMethod* m, int dex_pc,
2713 mirror::Object* this_object, mirror::ArtField* f) {
2714 if (!IsDebuggerActive()) {
2715 return;
2716 }
2717 DCHECK(m != nullptr);
2718 DCHECK(f != nullptr);
2719 JDWP::JdwpLocation location;
Ian Rogersc0542af2014-09-03 16:16:56 -07002720 SetLocation(&location, m, dex_pc);
Sebastien Hertz3f52eaf2014-04-04 17:50:18 +02002721
2722 JDWP::RefTypeId type_id = gRegistry->AddRefType(f->GetDeclaringClass());
2723 JDWP::FieldId field_id = ToFieldId(f);
2724 JDWP::ObjectId this_id = gRegistry->Add(this_object);
2725
2726 gJdwpState->PostFieldEvent(&location, type_id, field_id, this_id, nullptr, false);
2727}
2728
2729void Dbg::PostFieldModificationEvent(mirror::ArtMethod* m, int dex_pc,
2730 mirror::Object* this_object, mirror::ArtField* f,
2731 const JValue* field_value) {
2732 if (!IsDebuggerActive()) {
2733 return;
2734 }
2735 DCHECK(m != nullptr);
2736 DCHECK(f != nullptr);
2737 DCHECK(field_value != nullptr);
2738 JDWP::JdwpLocation location;
Ian Rogersc0542af2014-09-03 16:16:56 -07002739 SetLocation(&location, m, dex_pc);
Sebastien Hertz3f52eaf2014-04-04 17:50:18 +02002740
2741 JDWP::RefTypeId type_id = gRegistry->AddRefType(f->GetDeclaringClass());
2742 JDWP::FieldId field_id = ToFieldId(f);
2743 JDWP::ObjectId this_id = gRegistry->Add(this_object);
2744
2745 gJdwpState->PostFieldEvent(&location, type_id, field_id, this_id, field_value, true);
2746}
2747
2748void Dbg::PostException(const ThrowLocation& throw_location,
Brian Carlstromea46f952013-07-30 01:26:50 -07002749 mirror::ArtMethod* catch_method,
Elliott Hughes64f574f2013-02-20 14:57:12 -08002750 uint32_t catch_dex_pc, mirror::Throwable* exception_object) {
Elliott Hughesc0f09332012-03-26 13:27:06 -07002751 if (!IsDebuggerActive()) {
Ian Rogers0ad5bb82011-12-07 10:16:32 -08002752 return;
2753 }
Elliott Hughes4740cdf2011-12-07 14:07:12 -08002754
Ian Rogers62d6c772013-02-27 08:32:07 -08002755 JDWP::JdwpLocation jdwp_throw_location;
Ian Rogersc0542af2014-09-03 16:16:56 -07002756 SetLocation(&jdwp_throw_location, throw_location.GetMethod(), throw_location.GetDexPc());
Elliott Hughesd07986f2011-12-06 18:27:45 -08002757 JDWP::JdwpLocation catch_location;
Ian Rogersc0542af2014-09-03 16:16:56 -07002758 SetLocation(&catch_location, catch_method, catch_dex_pc);
Elliott Hughesd07986f2011-12-06 18:27:45 -08002759
Sebastien Hertz3f52eaf2014-04-04 17:50:18 +02002760 // We need 'this' for InstanceOnly filters only.
2761 JDWP::ObjectId this_id = GetThisObjectIdForEvent(throw_location.GetThis());
Elliott Hughes64f574f2013-02-20 14:57:12 -08002762 JDWP::ObjectId exception_id = gRegistry->Add(exception_object);
2763 JDWP::RefTypeId exception_class_id = gRegistry->AddRefType(exception_object->GetClass());
Elliott Hughesd07986f2011-12-06 18:27:45 -08002764
Ian Rogers62d6c772013-02-27 08:32:07 -08002765 gJdwpState->PostException(&jdwp_throw_location, exception_id, exception_class_id, &catch_location,
2766 this_id);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002767}
2768
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002769void Dbg::PostClassPrepare(mirror::Class* c) {
Elliott Hughesc0f09332012-03-26 13:27:06 -07002770 if (!IsDebuggerActive()) {
Elliott Hughes4740cdf2011-12-07 14:07:12 -08002771 return;
2772 }
2773
Elliott Hughes3d30d9b2011-12-07 17:35:48 -08002774 // OLD-TODO - we currently always send both "verified" and "prepared" since
Elliott Hughes4740cdf2011-12-07 14:07:12 -08002775 // debuggers seem to like that. There might be some advantage to honesty,
2776 // since the class may not yet be verified.
2777 int state = JDWP::CS_VERIFIED | JDWP::CS_PREPARED;
Sebastien Hertz4d8fd492014-03-28 16:29:41 +01002778 JDWP::JdwpTypeTag tag = GetTypeTag(c);
Ian Rogers1ff3c982014-08-12 02:30:58 -07002779 std::string temp;
2780 gJdwpState->PostClassPrepare(tag, gRegistry->Add(c), c->GetDescriptor(&temp), state);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002781}
2782
Ian Rogers62d6c772013-02-27 08:32:07 -08002783void Dbg::UpdateDebugger(Thread* thread, mirror::Object* this_object,
Sebastien Hertz8379b222014-02-24 17:38:15 +01002784 mirror::ArtMethod* m, uint32_t dex_pc,
2785 int event_flags, const JValue* return_value) {
Ian Rogers62d6c772013-02-27 08:32:07 -08002786 if (!IsDebuggerActive() || dex_pc == static_cast<uint32_t>(-2) /* fake method exit */) {
Elliott Hughes2aa2e392012-02-17 17:15:43 -08002787 return;
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08002788 }
2789
Elliott Hughes86964332012-02-15 19:37:42 -08002790 if (IsBreakpoint(m, dex_pc)) {
2791 event_flags |= kBreakpoint;
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08002792 }
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08002793
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01002794 // If the debugger is single-stepping one of our threads, check to
2795 // see if we're that thread and we've reached a step point.
2796 const SingleStepControl* single_step_control = thread->GetSingleStepControl();
2797 DCHECK(single_step_control != nullptr);
2798 if (single_step_control->is_active) {
2799 CHECK(!m->IsNative());
2800 if (single_step_control->step_depth == JDWP::SD_INTO) {
2801 // Step into method calls. We break when the line number
2802 // or method pointer changes. If we're in SS_MIN mode, we
2803 // always stop.
2804 if (single_step_control->method != m) {
2805 event_flags |= kSingleStep;
2806 VLOG(jdwp) << "SS new method";
2807 } else if (single_step_control->step_size == JDWP::SS_MIN) {
2808 event_flags |= kSingleStep;
2809 VLOG(jdwp) << "SS new instruction";
Sebastien Hertzbb43b432014-04-14 11:59:08 +02002810 } else if (single_step_control->ContainsDexPc(dex_pc)) {
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01002811 event_flags |= kSingleStep;
2812 VLOG(jdwp) << "SS new line";
2813 }
2814 } else if (single_step_control->step_depth == JDWP::SD_OVER) {
2815 // Step over method calls. We break when the line number is
2816 // different and the frame depth is <= the original frame
2817 // depth. (We can't just compare on the method, because we
2818 // might get unrolled past it by an exception, and it's tricky
2819 // to identify recursion.)
2820
2821 int stack_depth = GetStackDepth(thread);
2822
2823 if (stack_depth < single_step_control->stack_depth) {
2824 // Popped up one or more frames, always trigger.
2825 event_flags |= kSingleStep;
2826 VLOG(jdwp) << "SS method pop";
2827 } else if (stack_depth == single_step_control->stack_depth) {
2828 // Same depth, see if we moved.
2829 if (single_step_control->step_size == JDWP::SS_MIN) {
Elliott Hughes86964332012-02-15 19:37:42 -08002830 event_flags |= kSingleStep;
2831 VLOG(jdwp) << "SS new instruction";
Sebastien Hertzbb43b432014-04-14 11:59:08 +02002832 } else if (single_step_control->ContainsDexPc(dex_pc)) {
Elliott Hughes2435a572012-02-17 16:07:41 -08002833 event_flags |= kSingleStep;
2834 VLOG(jdwp) << "SS new line";
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08002835 }
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01002836 }
2837 } else {
2838 CHECK_EQ(single_step_control->step_depth, JDWP::SD_OUT);
2839 // Return from the current method. We break when the frame
2840 // depth pops up.
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08002841
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01002842 // This differs from the "method exit" break in that it stops
2843 // with the PC at the next instruction in the returned-to
2844 // function, rather than the end of the returning function.
Elliott Hughes86964332012-02-15 19:37:42 -08002845
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01002846 int stack_depth = GetStackDepth(thread);
2847 if (stack_depth < single_step_control->stack_depth) {
2848 event_flags |= kSingleStep;
2849 VLOG(jdwp) << "SS method pop";
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08002850 }
2851 }
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08002852 }
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08002853
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08002854 // If there's something interesting going on, see if it matches one
2855 // of the debugger filters.
2856 if (event_flags != 0) {
Sebastien Hertz8379b222014-02-24 17:38:15 +01002857 Dbg::PostLocationEvent(m, dex_pc, this_object, event_flags, return_value);
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08002858 }
2859}
2860
Sebastien Hertz42cd43f2014-05-13 14:15:41 +02002861size_t* Dbg::GetReferenceCounterForEvent(uint32_t instrumentation_event) {
2862 switch (instrumentation_event) {
2863 case instrumentation::Instrumentation::kMethodEntered:
2864 return &method_enter_event_ref_count_;
2865 case instrumentation::Instrumentation::kMethodExited:
2866 return &method_exit_event_ref_count_;
2867 case instrumentation::Instrumentation::kDexPcMoved:
2868 return &dex_pc_change_event_ref_count_;
2869 case instrumentation::Instrumentation::kFieldRead:
2870 return &field_read_event_ref_count_;
2871 case instrumentation::Instrumentation::kFieldWritten:
2872 return &field_write_event_ref_count_;
2873 case instrumentation::Instrumentation::kExceptionCaught:
2874 return &exception_catch_event_ref_count_;
2875 default:
2876 return nullptr;
2877 }
2878}
2879
Sebastien Hertz4d25df32014-03-21 17:44:46 +01002880// Process request while all mutator threads are suspended.
2881void Dbg::ProcessDeoptimizationRequest(const DeoptimizationRequest& request) {
Sebastien Hertz138dbfc2013-12-04 18:15:25 +01002882 instrumentation::Instrumentation* instrumentation = Runtime::Current()->GetInstrumentation();
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07002883 switch (request.GetKind()) {
Sebastien Hertz4d25df32014-03-21 17:44:46 +01002884 case DeoptimizationRequest::kNothing:
2885 LOG(WARNING) << "Ignoring empty deoptimization request.";
2886 break;
Sebastien Hertz42cd43f2014-05-13 14:15:41 +02002887 case DeoptimizationRequest::kRegisterForEvent:
2888 VLOG(jdwp) << StringPrintf("Add debugger as listener for instrumentation event 0x%x",
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07002889 request.InstrumentationEvent());
2890 instrumentation->AddListener(&gDebugInstrumentationListener, request.InstrumentationEvent());
2891 instrumentation_events_ |= request.InstrumentationEvent();
Sebastien Hertz42cd43f2014-05-13 14:15:41 +02002892 break;
2893 case DeoptimizationRequest::kUnregisterForEvent:
2894 VLOG(jdwp) << StringPrintf("Remove debugger as listener for instrumentation event 0x%x",
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07002895 request.InstrumentationEvent());
Sebastien Hertz42cd43f2014-05-13 14:15:41 +02002896 instrumentation->RemoveListener(&gDebugInstrumentationListener,
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07002897 request.InstrumentationEvent());
2898 instrumentation_events_ &= ~request.InstrumentationEvent();
Sebastien Hertz42cd43f2014-05-13 14:15:41 +02002899 break;
Sebastien Hertz4d25df32014-03-21 17:44:46 +01002900 case DeoptimizationRequest::kFullDeoptimization:
Sebastien Hertz7ec2f1c2014-03-27 20:06:47 +01002901 VLOG(jdwp) << "Deoptimize the world ...";
Sebastien Hertz4d25df32014-03-21 17:44:46 +01002902 instrumentation->DeoptimizeEverything();
Sebastien Hertz7ec2f1c2014-03-27 20:06:47 +01002903 VLOG(jdwp) << "Deoptimize the world DONE";
Sebastien Hertz4d25df32014-03-21 17:44:46 +01002904 break;
2905 case DeoptimizationRequest::kFullUndeoptimization:
Sebastien Hertz7ec2f1c2014-03-27 20:06:47 +01002906 VLOG(jdwp) << "Undeoptimize the world ...";
Sebastien Hertz4d25df32014-03-21 17:44:46 +01002907 instrumentation->UndeoptimizeEverything();
Sebastien Hertz7ec2f1c2014-03-27 20:06:47 +01002908 VLOG(jdwp) << "Undeoptimize the world DONE";
Sebastien Hertz4d25df32014-03-21 17:44:46 +01002909 break;
2910 case DeoptimizationRequest::kSelectiveDeoptimization:
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07002911 VLOG(jdwp) << "Deoptimize method " << PrettyMethod(request.Method()) << " ...";
2912 instrumentation->Deoptimize(request.Method());
2913 VLOG(jdwp) << "Deoptimize method " << PrettyMethod(request.Method()) << " DONE";
Sebastien Hertz4d25df32014-03-21 17:44:46 +01002914 break;
2915 case DeoptimizationRequest::kSelectiveUndeoptimization:
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07002916 VLOG(jdwp) << "Undeoptimize method " << PrettyMethod(request.Method()) << " ...";
2917 instrumentation->Undeoptimize(request.Method());
2918 VLOG(jdwp) << "Undeoptimize method " << PrettyMethod(request.Method()) << " DONE";
Sebastien Hertz4d25df32014-03-21 17:44:46 +01002919 break;
2920 default:
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07002921 LOG(FATAL) << "Unsupported deoptimization request kind " << request.GetKind();
Sebastien Hertz4d25df32014-03-21 17:44:46 +01002922 break;
Sebastien Hertz138dbfc2013-12-04 18:15:25 +01002923 }
Sebastien Hertz138dbfc2013-12-04 18:15:25 +01002924}
2925
Sebastien Hertz7ec2f1c2014-03-27 20:06:47 +01002926void Dbg::DelayFullUndeoptimization() {
Brian Carlstrom306db812014-09-05 13:01:41 -07002927 MutexLock mu(Thread::Current(), *Locks::deoptimization_lock_);
Sebastien Hertz7ec2f1c2014-03-27 20:06:47 +01002928 ++delayed_full_undeoptimization_count_;
2929 DCHECK_LE(delayed_full_undeoptimization_count_, full_deoptimization_event_count_);
2930}
2931
2932void Dbg::ProcessDelayedFullUndeoptimizations() {
2933 // TODO: avoid taking the lock twice (once here and once in ManageDeoptimization).
2934 {
Brian Carlstrom306db812014-09-05 13:01:41 -07002935 MutexLock mu(Thread::Current(), *Locks::deoptimization_lock_);
Sebastien Hertz7ec2f1c2014-03-27 20:06:47 +01002936 while (delayed_full_undeoptimization_count_ > 0) {
2937 DeoptimizationRequest req;
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07002938 req.SetKind(DeoptimizationRequest::kFullUndeoptimization);
2939 req.SetMethod(nullptr);
Sebastien Hertz7ec2f1c2014-03-27 20:06:47 +01002940 RequestDeoptimizationLocked(req);
2941 --delayed_full_undeoptimization_count_;
2942 }
2943 }
2944 ManageDeoptimization();
2945}
2946
Sebastien Hertz4d25df32014-03-21 17:44:46 +01002947void Dbg::RequestDeoptimization(const DeoptimizationRequest& req) {
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07002948 if (req.GetKind() == DeoptimizationRequest::kNothing) {
Sebastien Hertz4d25df32014-03-21 17:44:46 +01002949 // Nothing to do.
2950 return;
2951 }
Brian Carlstrom306db812014-09-05 13:01:41 -07002952 MutexLock mu(Thread::Current(), *Locks::deoptimization_lock_);
Sebastien Hertz7ec2f1c2014-03-27 20:06:47 +01002953 RequestDeoptimizationLocked(req);
2954}
2955
2956void Dbg::RequestDeoptimizationLocked(const DeoptimizationRequest& req) {
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07002957 switch (req.GetKind()) {
Sebastien Hertz42cd43f2014-05-13 14:15:41 +02002958 case DeoptimizationRequest::kRegisterForEvent: {
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07002959 DCHECK_NE(req.InstrumentationEvent(), 0u);
2960 size_t* counter = GetReferenceCounterForEvent(req.InstrumentationEvent());
Sebastien Hertz42cd43f2014-05-13 14:15:41 +02002961 CHECK(counter != nullptr) << StringPrintf("No counter for instrumentation event 0x%x",
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07002962 req.InstrumentationEvent());
Sebastien Hertz42cd43f2014-05-13 14:15:41 +02002963 if (*counter == 0) {
Sebastien Hertz7d2ae432014-05-15 11:26:34 +02002964 VLOG(jdwp) << StringPrintf("Queue request #%zd to start listening to instrumentation event 0x%x",
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07002965 deoptimization_requests_.size(), req.InstrumentationEvent());
Sebastien Hertz42cd43f2014-05-13 14:15:41 +02002966 deoptimization_requests_.push_back(req);
2967 }
2968 *counter = *counter + 1;
2969 break;
2970 }
2971 case DeoptimizationRequest::kUnregisterForEvent: {
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07002972 DCHECK_NE(req.InstrumentationEvent(), 0u);
2973 size_t* counter = GetReferenceCounterForEvent(req.InstrumentationEvent());
Sebastien Hertz42cd43f2014-05-13 14:15:41 +02002974 CHECK(counter != nullptr) << StringPrintf("No counter for instrumentation event 0x%x",
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07002975 req.InstrumentationEvent());
Sebastien Hertz42cd43f2014-05-13 14:15:41 +02002976 *counter = *counter - 1;
2977 if (*counter == 0) {
Sebastien Hertz7d2ae432014-05-15 11:26:34 +02002978 VLOG(jdwp) << StringPrintf("Queue request #%zd to stop listening to instrumentation event 0x%x",
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07002979 deoptimization_requests_.size(), req.InstrumentationEvent());
Sebastien Hertz42cd43f2014-05-13 14:15:41 +02002980 deoptimization_requests_.push_back(req);
2981 }
2982 break;
2983 }
Sebastien Hertz4d25df32014-03-21 17:44:46 +01002984 case DeoptimizationRequest::kFullDeoptimization: {
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07002985 DCHECK(req.Method() == nullptr);
Sebastien Hertz4d25df32014-03-21 17:44:46 +01002986 if (full_deoptimization_event_count_ == 0) {
Sebastien Hertz7ec2f1c2014-03-27 20:06:47 +01002987 VLOG(jdwp) << "Queue request #" << deoptimization_requests_.size()
2988 << " for full deoptimization";
Sebastien Hertz4d25df32014-03-21 17:44:46 +01002989 deoptimization_requests_.push_back(req);
2990 }
2991 ++full_deoptimization_event_count_;
2992 break;
2993 }
2994 case DeoptimizationRequest::kFullUndeoptimization: {
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07002995 DCHECK(req.Method() == nullptr);
Sebastien Hertze713d932014-05-15 10:48:53 +02002996 DCHECK_GT(full_deoptimization_event_count_, 0U);
Sebastien Hertz4d25df32014-03-21 17:44:46 +01002997 --full_deoptimization_event_count_;
2998 if (full_deoptimization_event_count_ == 0) {
Sebastien Hertz7ec2f1c2014-03-27 20:06:47 +01002999 VLOG(jdwp) << "Queue request #" << deoptimization_requests_.size()
3000 << " for full undeoptimization";
Sebastien Hertz4d25df32014-03-21 17:44:46 +01003001 deoptimization_requests_.push_back(req);
3002 }
3003 break;
3004 }
3005 case DeoptimizationRequest::kSelectiveDeoptimization: {
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003006 DCHECK(req.Method() != nullptr);
Sebastien Hertz7ec2f1c2014-03-27 20:06:47 +01003007 VLOG(jdwp) << "Queue request #" << deoptimization_requests_.size()
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003008 << " for deoptimization of " << PrettyMethod(req.Method());
Sebastien Hertz4d25df32014-03-21 17:44:46 +01003009 deoptimization_requests_.push_back(req);
3010 break;
3011 }
3012 case DeoptimizationRequest::kSelectiveUndeoptimization: {
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003013 DCHECK(req.Method() != nullptr);
Sebastien Hertz7ec2f1c2014-03-27 20:06:47 +01003014 VLOG(jdwp) << "Queue request #" << deoptimization_requests_.size()
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003015 << " for undeoptimization of " << PrettyMethod(req.Method());
Sebastien Hertz4d25df32014-03-21 17:44:46 +01003016 deoptimization_requests_.push_back(req);
3017 break;
3018 }
3019 default: {
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003020 LOG(FATAL) << "Unknown deoptimization request kind " << req.GetKind();
Sebastien Hertz4d25df32014-03-21 17:44:46 +01003021 break;
3022 }
3023 }
3024}
3025
Sebastien Hertz138dbfc2013-12-04 18:15:25 +01003026void Dbg::ManageDeoptimization() {
3027 Thread* const self = Thread::Current();
3028 {
3029 // Avoid suspend/resume if there is no pending request.
Brian Carlstrom306db812014-09-05 13:01:41 -07003030 MutexLock mu(self, *Locks::deoptimization_lock_);
Sebastien Hertz4d25df32014-03-21 17:44:46 +01003031 if (deoptimization_requests_.empty()) {
Sebastien Hertz138dbfc2013-12-04 18:15:25 +01003032 return;
3033 }
3034 }
3035 CHECK_EQ(self->GetState(), kRunnable);
3036 self->TransitionFromRunnableToSuspended(kWaitingForDeoptimization);
3037 // We need to suspend mutator threads first.
3038 Runtime* const runtime = Runtime::Current();
3039 runtime->GetThreadList()->SuspendAll();
3040 const ThreadState old_state = self->SetStateUnsafe(kRunnable);
Sebastien Hertz4d25df32014-03-21 17:44:46 +01003041 {
Brian Carlstrom306db812014-09-05 13:01:41 -07003042 MutexLock mu(self, *Locks::deoptimization_lock_);
Sebastien Hertz7ec2f1c2014-03-27 20:06:47 +01003043 size_t req_index = 0;
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003044 for (DeoptimizationRequest& request : deoptimization_requests_) {
Sebastien Hertz7ec2f1c2014-03-27 20:06:47 +01003045 VLOG(jdwp) << "Process deoptimization request #" << req_index++;
Sebastien Hertz4d25df32014-03-21 17:44:46 +01003046 ProcessDeoptimizationRequest(request);
3047 }
3048 deoptimization_requests_.clear();
3049 }
Sebastien Hertz138dbfc2013-12-04 18:15:25 +01003050 CHECK_EQ(self->SetStateUnsafe(old_state), kRunnable);
3051 runtime->GetThreadList()->ResumeAll();
3052 self->TransitionFromSuspendedToRunnable();
3053}
3054
Sebastien Hertza76a6d42014-03-20 16:40:17 +01003055static bool IsMethodPossiblyInlined(Thread* self, mirror::ArtMethod* m)
3056 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07003057 const DexFile::CodeItem* code_item = m->GetCodeItem();
Sebastien Hertza76a6d42014-03-20 16:40:17 +01003058 if (code_item == nullptr) {
3059 // TODO We should not be asked to watch location in a native or abstract method so the code item
3060 // should never be null. We could just check we never encounter this case.
3061 return false;
Sebastien Hertz138dbfc2013-12-04 18:15:25 +01003062 }
Hiroshi Yamauchidc376172014-08-22 11:13:12 -07003063 StackHandleScope<3> hs(self);
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07003064 mirror::Class* declaring_class = m->GetDeclaringClass();
3065 Handle<mirror::DexCache> dex_cache(hs.NewHandle(declaring_class->GetDexCache()));
3066 Handle<mirror::ClassLoader> class_loader(hs.NewHandle(declaring_class->GetClassLoader()));
Hiroshi Yamauchidc376172014-08-22 11:13:12 -07003067 Handle<mirror::ArtMethod> method(hs.NewHandle(m));
Mathieu Chartierbf99f772014-08-23 16:37:27 -07003068 verifier::MethodVerifier verifier(dex_cache->GetDexFile(), dex_cache, class_loader,
Hiroshi Yamauchidc376172014-08-22 11:13:12 -07003069 &m->GetClassDef(), code_item, m->GetDexMethodIndex(), method,
Ian Rogers46960fe2014-05-23 10:43:43 -07003070 m->GetAccessFlags(), false, true, false);
Sebastien Hertza76a6d42014-03-20 16:40:17 +01003071 // Note: we don't need to verify the method.
3072 return InlineMethodAnalyser::AnalyseMethodCode(&verifier, nullptr);
3073}
Sebastien Hertz138dbfc2013-12-04 18:15:25 +01003074
Sebastien Hertza76a6d42014-03-20 16:40:17 +01003075static const Breakpoint* FindFirstBreakpointForMethod(mirror::ArtMethod* m)
Sebastien Hertzed2be172014-08-19 15:33:43 +02003076 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_, Locks::breakpoint_lock_) {
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003077 for (Breakpoint& breakpoint : gBreakpoints) {
3078 if (breakpoint.Method() == m) {
Sebastien Hertza76a6d42014-03-20 16:40:17 +01003079 return &breakpoint;
3080 }
3081 }
3082 return nullptr;
3083}
3084
3085// Sanity checks all existing breakpoints on the same method.
3086static void SanityCheckExistingBreakpoints(mirror::ArtMethod* m, bool need_full_deoptimization)
Sebastien Hertzed2be172014-08-19 15:33:43 +02003087 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_, Locks::breakpoint_lock_) {
Sebastien Hertza76a6d42014-03-20 16:40:17 +01003088 if (kIsDebugBuild) {
3089 for (const Breakpoint& breakpoint : gBreakpoints) {
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003090 CHECK_EQ(need_full_deoptimization, breakpoint.NeedFullDeoptimization());
Sebastien Hertza76a6d42014-03-20 16:40:17 +01003091 }
3092 if (need_full_deoptimization) {
3093 // We should have deoptimized everything but not "selectively" deoptimized this method.
3094 CHECK(Runtime::Current()->GetInstrumentation()->AreAllMethodsDeoptimized());
3095 CHECK(!Runtime::Current()->GetInstrumentation()->IsDeoptimized(m));
3096 } else {
3097 // We should have "selectively" deoptimized this method.
3098 // Note: while we have not deoptimized everything for this method, we may have done it for
3099 // another event.
3100 CHECK(Runtime::Current()->GetInstrumentation()->IsDeoptimized(m));
3101 }
Sebastien Hertz138dbfc2013-12-04 18:15:25 +01003102 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -07003103}
3104
Sebastien Hertza76a6d42014-03-20 16:40:17 +01003105// Installs a breakpoint at the specified location. Also indicates through the deoptimization
3106// request if we need to deoptimize.
3107void Dbg::WatchLocation(const JDWP::JdwpLocation* location, DeoptimizationRequest* req) {
3108 Thread* const self = Thread::Current();
Brian Carlstromea46f952013-07-30 01:26:50 -07003109 mirror::ArtMethod* m = FromMethodId(location->method_id);
Sebastien Hertza76a6d42014-03-20 16:40:17 +01003110 DCHECK(m != nullptr) << "No method for method id " << location->method_id;
Sebastien Hertz138dbfc2013-12-04 18:15:25 +01003111
Sebastien Hertzed2be172014-08-19 15:33:43 +02003112 WriterMutexLock mu(self, *Locks::breakpoint_lock_);
Sebastien Hertza76a6d42014-03-20 16:40:17 +01003113 const Breakpoint* const existing_breakpoint = FindFirstBreakpointForMethod(m);
3114 bool need_full_deoptimization;
3115 if (existing_breakpoint == nullptr) {
3116 // There is no breakpoint on this method yet: we need to deoptimize. If this method may be
3117 // inlined, we deoptimize everything; otherwise we deoptimize only this method.
3118 need_full_deoptimization = IsMethodPossiblyInlined(self, m);
3119 if (need_full_deoptimization) {
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003120 req->SetKind(DeoptimizationRequest::kFullDeoptimization);
3121 req->SetMethod(nullptr);
Sebastien Hertza76a6d42014-03-20 16:40:17 +01003122 } else {
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003123 req->SetKind(DeoptimizationRequest::kSelectiveDeoptimization);
3124 req->SetMethod(m);
Sebastien Hertz138dbfc2013-12-04 18:15:25 +01003125 }
Sebastien Hertza76a6d42014-03-20 16:40:17 +01003126 } else {
3127 // There is at least one breakpoint for this method: we don't need to deoptimize.
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003128 req->SetKind(DeoptimizationRequest::kNothing);
3129 req->SetMethod(nullptr);
Sebastien Hertza76a6d42014-03-20 16:40:17 +01003130
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003131 need_full_deoptimization = existing_breakpoint->NeedFullDeoptimization();
Sebastien Hertza76a6d42014-03-20 16:40:17 +01003132 SanityCheckExistingBreakpoints(m, need_full_deoptimization);
Sebastien Hertz138dbfc2013-12-04 18:15:25 +01003133 }
3134
Sebastien Hertza76a6d42014-03-20 16:40:17 +01003135 gBreakpoints.push_back(Breakpoint(m, location->dex_pc, need_full_deoptimization));
3136 VLOG(jdwp) << "Set breakpoint #" << (gBreakpoints.size() - 1) << ": "
3137 << gBreakpoints[gBreakpoints.size() - 1];
3138}
3139
3140// Uninstalls a breakpoint at the specified location. Also indicates through the deoptimization
3141// request if we need to undeoptimize.
3142void Dbg::UnwatchLocation(const JDWP::JdwpLocation* location, DeoptimizationRequest* req) {
Sebastien Hertzed2be172014-08-19 15:33:43 +02003143 WriterMutexLock mu(Thread::Current(), *Locks::breakpoint_lock_);
Sebastien Hertza76a6d42014-03-20 16:40:17 +01003144 mirror::ArtMethod* m = FromMethodId(location->method_id);
3145 DCHECK(m != nullptr) << "No method for method id " << location->method_id;
Sebastien Hertza76a6d42014-03-20 16:40:17 +01003146 bool need_full_deoptimization = false;
3147 for (size_t i = 0, e = gBreakpoints.size(); i < e; ++i) {
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003148 if (gBreakpoints[i].DexPc() == location->dex_pc && gBreakpoints[i].Method() == m) {
Sebastien Hertza76a6d42014-03-20 16:40:17 +01003149 VLOG(jdwp) << "Removed breakpoint #" << i << ": " << gBreakpoints[i];
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003150 need_full_deoptimization = gBreakpoints[i].NeedFullDeoptimization();
Sebastien Hertza76a6d42014-03-20 16:40:17 +01003151 DCHECK_NE(need_full_deoptimization, Runtime::Current()->GetInstrumentation()->IsDeoptimized(m));
3152 gBreakpoints.erase(gBreakpoints.begin() + i);
3153 break;
3154 }
3155 }
3156 const Breakpoint* const existing_breakpoint = FindFirstBreakpointForMethod(m);
3157 if (existing_breakpoint == nullptr) {
3158 // There is no more breakpoint on this method: we need to undeoptimize.
3159 if (need_full_deoptimization) {
3160 // This method required full deoptimization: we need to undeoptimize everything.
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003161 req->SetKind(DeoptimizationRequest::kFullUndeoptimization);
3162 req->SetMethod(nullptr);
Sebastien Hertza76a6d42014-03-20 16:40:17 +01003163 } else {
3164 // This method required selective deoptimization: we need to undeoptimize only that method.
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003165 req->SetKind(DeoptimizationRequest::kSelectiveUndeoptimization);
3166 req->SetMethod(m);
Sebastien Hertza76a6d42014-03-20 16:40:17 +01003167 }
3168 } else {
3169 // There is at least one breakpoint for this method: we don't need to undeoptimize.
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003170 req->SetKind(DeoptimizationRequest::kNothing);
3171 req->SetMethod(nullptr);
Sebastien Hertza76a6d42014-03-20 16:40:17 +01003172 SanityCheckExistingBreakpoints(m, need_full_deoptimization);
Elliott Hughes86964332012-02-15 19:37:42 -08003173 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -07003174}
3175
Jeff Hao449db332013-04-12 18:30:52 -07003176// Scoped utility class to suspend a thread so that we may do tasks such as walk its stack. Doesn't
3177// cause suspension if the thread is the current thread.
3178class ScopedThreadSuspension {
3179 public:
Ian Rogers33e95662013-05-20 20:29:14 -07003180 ScopedThreadSuspension(Thread* self, JDWP::ObjectId thread_id)
Sebastien Hertz52d131d2014-03-13 16:17:40 +01003181 LOCKS_EXCLUDED(Locks::thread_list_lock_)
Ian Rogers33e95662013-05-20 20:29:14 -07003182 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) :
Ian Rogersf3d874c2014-07-17 18:52:42 -07003183 thread_(nullptr),
Jeff Hao449db332013-04-12 18:30:52 -07003184 error_(JDWP::ERR_NONE),
3185 self_suspend_(false),
Ian Rogers33e95662013-05-20 20:29:14 -07003186 other_suspend_(false) {
Jeff Hao449db332013-04-12 18:30:52 -07003187 ScopedObjectAccessUnchecked soa(self);
3188 {
3189 MutexLock mu(soa.Self(), *Locks::thread_list_lock_);
Ian Rogersc0542af2014-09-03 16:16:56 -07003190 thread_ = DecodeThread(soa, thread_id, &error_);
Jeff Hao449db332013-04-12 18:30:52 -07003191 }
3192 if (error_ == JDWP::ERR_NONE) {
3193 if (thread_ == soa.Self()) {
3194 self_suspend_ = true;
3195 } else {
3196 soa.Self()->TransitionFromRunnableToSuspended(kWaitingForDebuggerSuspension);
3197 jobject thread_peer = gRegistry->GetJObject(thread_id);
3198 bool timed_out;
Ian Rogersf3d874c2014-07-17 18:52:42 -07003199 Thread* suspended_thread;
3200 {
3201 // Take suspend thread lock to avoid races with threads trying to suspend this one.
3202 MutexLock mu(soa.Self(), *Locks::thread_list_suspend_thread_lock_);
Brian Carlstromba32de42014-08-27 23:43:46 -07003203 ThreadList* thread_list = Runtime::Current()->GetThreadList();
3204 suspended_thread = thread_list->SuspendThreadByPeer(thread_peer, true, true, &timed_out);
Ian Rogersf3d874c2014-07-17 18:52:42 -07003205 }
Jeff Hao449db332013-04-12 18:30:52 -07003206 CHECK_EQ(soa.Self()->TransitionFromSuspendedToRunnable(), kWaitingForDebuggerSuspension);
Ian Rogersf3d874c2014-07-17 18:52:42 -07003207 if (suspended_thread == nullptr) {
Jeff Hao449db332013-04-12 18:30:52 -07003208 // Thread terminated from under us while suspending.
3209 error_ = JDWP::ERR_INVALID_THREAD;
3210 } else {
3211 CHECK_EQ(suspended_thread, thread_);
3212 other_suspend_ = true;
3213 }
3214 }
3215 }
Elliott Hughes2435a572012-02-17 16:07:41 -08003216 }
Elliott Hughes86964332012-02-15 19:37:42 -08003217
Jeff Hao449db332013-04-12 18:30:52 -07003218 Thread* GetThread() const {
3219 return thread_;
3220 }
3221
3222 JDWP::JdwpError GetError() const {
3223 return error_;
3224 }
3225
3226 ~ScopedThreadSuspension() {
3227 if (other_suspend_) {
3228 Runtime::Current()->GetThreadList()->Resume(thread_, true);
3229 }
3230 }
3231
3232 private:
3233 Thread* thread_;
3234 JDWP::JdwpError error_;
3235 bool self_suspend_;
3236 bool other_suspend_;
3237};
3238
3239JDWP::JdwpError Dbg::ConfigureStep(JDWP::ObjectId thread_id, JDWP::JdwpStepSize step_size,
3240 JDWP::JdwpStepDepth step_depth) {
3241 Thread* self = Thread::Current();
3242 ScopedThreadSuspension sts(self, thread_id);
3243 if (sts.GetError() != JDWP::ERR_NONE) {
3244 return sts.GetError();
3245 }
3246
Elliott Hughes2435a572012-02-17 16:07:41 -08003247 //
3248 // Work out what Method* we're in, the current line number, and how deep the stack currently
3249 // is for step-out.
3250 //
3251
Ian Rogers0399dde2012-06-06 17:09:28 -07003252 struct SingleStepStackVisitor : public StackVisitor {
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01003253 explicit SingleStepStackVisitor(Thread* thread, SingleStepControl* single_step_control,
3254 int32_t* line_number)
Ian Rogersb726dcb2012-09-05 08:57:23 -07003255 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_)
Ian Rogersc0542af2014-09-03 16:16:56 -07003256 : StackVisitor(thread, nullptr), single_step_control_(single_step_control),
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01003257 line_number_(line_number) {
3258 DCHECK_EQ(single_step_control_, thread->GetSingleStepControl());
Ian Rogersc0542af2014-09-03 16:16:56 -07003259 single_step_control_->method = nullptr;
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01003260 single_step_control_->stack_depth = 0;
Elliott Hughes86964332012-02-15 19:37:42 -08003261 }
Ian Rogersca190662012-06-26 15:45:57 -07003262
Ian Rogers00f7d0e2012-07-19 15:28:27 -07003263 // TODO: Enable annotalysis. We know lock is held in constructor, but abstraction confuses
3264 // annotalysis.
3265 bool VisitFrame() NO_THREAD_SAFETY_ANALYSIS {
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01003266 mirror::ArtMethod* m = GetMethod();
Ian Rogers0399dde2012-06-06 17:09:28 -07003267 if (!m->IsRuntimeMethod()) {
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01003268 ++single_step_control_->stack_depth;
Ian Rogersc0542af2014-09-03 16:16:56 -07003269 if (single_step_control_->method == nullptr) {
Ian Rogersef7d42f2014-01-06 12:55:46 -08003270 mirror::DexCache* dex_cache = m->GetDeclaringClass()->GetDexCache();
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01003271 single_step_control_->method = m;
3272 *line_number_ = -1;
Ian Rogersc0542af2014-09-03 16:16:56 -07003273 if (dex_cache != nullptr) {
Ian Rogers4445a7e2012-10-05 17:19:13 -07003274 const DexFile& dex_file = *dex_cache->GetDexFile();
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01003275 *line_number_ = dex_file.GetLineNumFromPC(m, GetDexPc());
Elliott Hughes2435a572012-02-17 16:07:41 -08003276 }
Elliott Hughes86964332012-02-15 19:37:42 -08003277 }
3278 }
Elliott Hughes530fa002012-03-12 11:44:49 -07003279 return true;
Elliott Hughes86964332012-02-15 19:37:42 -08003280 }
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01003281
3282 SingleStepControl* const single_step_control_;
3283 int32_t* const line_number_;
Elliott Hughes86964332012-02-15 19:37:42 -08003284 };
Jeff Hao449db332013-04-12 18:30:52 -07003285
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01003286 Thread* const thread = sts.GetThread();
3287 SingleStepControl* const single_step_control = thread->GetSingleStepControl();
3288 DCHECK(single_step_control != nullptr);
3289 int32_t line_number = -1;
3290 SingleStepStackVisitor visitor(thread, single_step_control, &line_number);
Ian Rogers0399dde2012-06-06 17:09:28 -07003291 visitor.WalkStack();
Elliott Hughes86964332012-02-15 19:37:42 -08003292
Elliott Hughes2435a572012-02-17 16:07:41 -08003293 //
3294 // Find the dex_pc values that correspond to the current line, for line-based single-stepping.
3295 //
3296
3297 struct DebugCallbackContext {
Sebastien Hertzbb43b432014-04-14 11:59:08 +02003298 explicit DebugCallbackContext(SingleStepControl* single_step_control, int32_t line_number,
3299 const DexFile::CodeItem* code_item)
3300 : single_step_control_(single_step_control), line_number_(line_number), code_item_(code_item),
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01003301 last_pc_valid(false), last_pc(0) {
Elliott Hughes2435a572012-02-17 16:07:41 -08003302 }
3303
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01003304 static bool Callback(void* raw_context, uint32_t address, uint32_t line_number) {
Elliott Hughes2435a572012-02-17 16:07:41 -08003305 DebugCallbackContext* context = reinterpret_cast<DebugCallbackContext*>(raw_context);
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01003306 if (static_cast<int32_t>(line_number) == context->line_number_) {
Elliott Hughes2435a572012-02-17 16:07:41 -08003307 if (!context->last_pc_valid) {
3308 // Everything from this address until the next line change is ours.
3309 context->last_pc = address;
3310 context->last_pc_valid = true;
3311 }
3312 // Otherwise, if we're already in a valid range for this line,
3313 // just keep going (shouldn't really happen)...
Brian Carlstrom7934ac22013-07-26 10:54:15 -07003314 } else if (context->last_pc_valid) { // and the line number is new
Elliott Hughes2435a572012-02-17 16:07:41 -08003315 // Add everything from the last entry up until here to the set
3316 for (uint32_t dex_pc = context->last_pc; dex_pc < address; ++dex_pc) {
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01003317 context->single_step_control_->dex_pcs.insert(dex_pc);
Elliott Hughes2435a572012-02-17 16:07:41 -08003318 }
3319 context->last_pc_valid = false;
3320 }
Brian Carlstrom7934ac22013-07-26 10:54:15 -07003321 return false; // There may be multiple entries for any given line.
Elliott Hughes2435a572012-02-17 16:07:41 -08003322 }
3323
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01003324 ~DebugCallbackContext() {
Elliott Hughes2435a572012-02-17 16:07:41 -08003325 // If the line number was the last in the position table...
3326 if (last_pc_valid) {
Sebastien Hertzbb43b432014-04-14 11:59:08 +02003327 size_t end = code_item_->insns_size_in_code_units_;
Elliott Hughes2435a572012-02-17 16:07:41 -08003328 for (uint32_t dex_pc = last_pc; dex_pc < end; ++dex_pc) {
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01003329 single_step_control_->dex_pcs.insert(dex_pc);
Elliott Hughes2435a572012-02-17 16:07:41 -08003330 }
3331 }
3332 }
3333
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01003334 SingleStepControl* const single_step_control_;
3335 const int32_t line_number_;
Sebastien Hertzbb43b432014-04-14 11:59:08 +02003336 const DexFile::CodeItem* const code_item_;
Elliott Hughes2435a572012-02-17 16:07:41 -08003337 bool last_pc_valid;
3338 uint32_t last_pc;
3339 };
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01003340 single_step_control->dex_pcs.clear();
Ian Rogersef7d42f2014-01-06 12:55:46 -08003341 mirror::ArtMethod* m = single_step_control->method;
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01003342 if (!m->IsNative()) {
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07003343 const DexFile::CodeItem* const code_item = m->GetCodeItem();
Sebastien Hertzbb43b432014-04-14 11:59:08 +02003344 DebugCallbackContext context(single_step_control, line_number, code_item);
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07003345 m->GetDexFile()->DecodeDebugInfo(code_item, m->IsStatic(), m->GetDexMethodIndex(),
Ian Rogersc0542af2014-09-03 16:16:56 -07003346 DebugCallbackContext::Callback, nullptr, &context);
Elliott Hughes3e2e1a22012-02-21 11:33:41 -08003347 }
Elliott Hughes2435a572012-02-17 16:07:41 -08003348
3349 //
3350 // Everything else...
3351 //
3352
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01003353 single_step_control->step_size = step_size;
3354 single_step_control->step_depth = step_depth;
3355 single_step_control->is_active = true;
Elliott Hughes86964332012-02-15 19:37:42 -08003356
Elliott Hughes2435a572012-02-17 16:07:41 -08003357 if (VLOG_IS_ON(jdwp)) {
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01003358 VLOG(jdwp) << "Single-step thread: " << *thread;
3359 VLOG(jdwp) << "Single-step step size: " << single_step_control->step_size;
3360 VLOG(jdwp) << "Single-step step depth: " << single_step_control->step_depth;
3361 VLOG(jdwp) << "Single-step current method: " << PrettyMethod(single_step_control->method);
3362 VLOG(jdwp) << "Single-step current line: " << line_number;
3363 VLOG(jdwp) << "Single-step current stack depth: " << single_step_control->stack_depth;
Elliott Hughes2435a572012-02-17 16:07:41 -08003364 VLOG(jdwp) << "Single-step dex_pc values:";
Sebastien Hertzbb43b432014-04-14 11:59:08 +02003365 for (uint32_t dex_pc : single_step_control->dex_pcs) {
3366 VLOG(jdwp) << StringPrintf(" %#x", dex_pc);
Elliott Hughes2435a572012-02-17 16:07:41 -08003367 }
3368 }
3369
3370 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07003371}
3372
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01003373void Dbg::UnconfigureStep(JDWP::ObjectId thread_id) {
3374 ScopedObjectAccessUnchecked soa(Thread::Current());
3375 MutexLock mu(soa.Self(), *Locks::thread_list_lock_);
Ian Rogersc0542af2014-09-03 16:16:56 -07003376 JDWP::JdwpError error;
3377 Thread* thread = DecodeThread(soa, thread_id, &error);
Sebastien Hertz87118ed2013-11-26 17:57:18 +01003378 if (error == JDWP::ERR_NONE) {
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01003379 SingleStepControl* single_step_control = thread->GetSingleStepControl();
3380 DCHECK(single_step_control != nullptr);
Sebastien Hertzbb43b432014-04-14 11:59:08 +02003381 single_step_control->Clear();
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01003382 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -07003383}
3384
Elliott Hughes45651fd2012-02-21 15:48:20 -08003385static char JdwpTagToShortyChar(JDWP::JdwpTag tag) {
3386 switch (tag) {
3387 default:
3388 LOG(FATAL) << "unknown JDWP tag: " << PrintableChar(tag);
3389
3390 // Primitives.
3391 case JDWP::JT_BYTE: return 'B';
3392 case JDWP::JT_CHAR: return 'C';
3393 case JDWP::JT_FLOAT: return 'F';
3394 case JDWP::JT_DOUBLE: return 'D';
3395 case JDWP::JT_INT: return 'I';
3396 case JDWP::JT_LONG: return 'J';
3397 case JDWP::JT_SHORT: return 'S';
3398 case JDWP::JT_VOID: return 'V';
3399 case JDWP::JT_BOOLEAN: return 'Z';
3400
3401 // Reference types.
3402 case JDWP::JT_ARRAY:
3403 case JDWP::JT_OBJECT:
3404 case JDWP::JT_STRING:
3405 case JDWP::JT_THREAD:
3406 case JDWP::JT_THREAD_GROUP:
3407 case JDWP::JT_CLASS_LOADER:
3408 case JDWP::JT_CLASS_OBJECT:
3409 return 'L';
3410 }
3411}
3412
Elliott Hughes88d63092013-01-09 09:55:54 -08003413JDWP::JdwpError Dbg::InvokeMethod(JDWP::ObjectId thread_id, JDWP::ObjectId object_id,
3414 JDWP::RefTypeId class_id, JDWP::MethodId method_id,
Ian Rogers00f7d0e2012-07-19 15:28:27 -07003415 uint32_t arg_count, uint64_t* arg_values,
3416 JDWP::JdwpTag* arg_types, uint32_t options,
3417 JDWP::JdwpTag* pResultTag, uint64_t* pResultValue,
3418 JDWP::ObjectId* pExceptionId) {
Elliott Hughesd07986f2011-12-06 18:27:45 -08003419 ThreadList* thread_list = Runtime::Current()->GetThreadList();
3420
Ian Rogersc0542af2014-09-03 16:16:56 -07003421 Thread* targetThread = nullptr;
3422 DebugInvokeReq* req = nullptr;
Ian Rogers00f7d0e2012-07-19 15:28:27 -07003423 Thread* self = Thread::Current();
Elliott Hughesd07986f2011-12-06 18:27:45 -08003424 {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07003425 ScopedObjectAccessUnchecked soa(self);
Ian Rogers50b35e22012-10-04 10:09:15 -07003426 MutexLock mu(soa.Self(), *Locks::thread_list_lock_);
Ian Rogersc0542af2014-09-03 16:16:56 -07003427 JDWP::JdwpError error;
3428 targetThread = DecodeThread(soa, thread_id, &error);
Elliott Hughes221229c2013-01-08 18:17:50 -08003429 if (error != JDWP::ERR_NONE) {
3430 LOG(ERROR) << "InvokeMethod request for invalid thread id " << thread_id;
3431 return error;
Elliott Hughesd07986f2011-12-06 18:27:45 -08003432 }
3433 req = targetThread->GetInvokeReq();
3434 if (!req->ready) {
3435 LOG(ERROR) << "InvokeMethod request for thread not stopped by event: " << *targetThread;
3436 return JDWP::ERR_INVALID_THREAD;
3437 }
3438
3439 /*
3440 * We currently have a bug where we don't successfully resume the
3441 * target thread if the suspend count is too deep. We're expected to
3442 * require one "resume" for each "suspend", but when asked to execute
3443 * a method we have to resume fully and then re-suspend it back to the
3444 * same level. (The easiest way to cause this is to type "suspend"
3445 * multiple times in jdb.)
3446 *
3447 * It's unclear what this means when the event specifies "resume all"
3448 * and some threads are suspended more deeply than others. This is
3449 * a rare problem, so for now we just prevent it from hanging forever
3450 * by rejecting the method invocation request. Without this, we will
3451 * be stuck waiting on a suspended thread.
3452 */
Ian Rogers00f7d0e2012-07-19 15:28:27 -07003453 int suspend_count;
3454 {
Ian Rogers50b35e22012-10-04 10:09:15 -07003455 MutexLock mu2(soa.Self(), *Locks::thread_suspend_count_lock_);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07003456 suspend_count = targetThread->GetSuspendCount();
3457 }
Elliott Hughesd07986f2011-12-06 18:27:45 -08003458 if (suspend_count > 1) {
3459 LOG(ERROR) << *targetThread << " suspend count too deep for method invocation: " << suspend_count;
Brian Carlstrom7934ac22013-07-26 10:54:15 -07003460 return JDWP::ERR_THREAD_SUSPENDED; // Probably not expected here.
Elliott Hughesd07986f2011-12-06 18:27:45 -08003461 }
3462
Ian Rogersc0542af2014-09-03 16:16:56 -07003463 mirror::Object* receiver = gRegistry->Get<mirror::Object*>(object_id, &error);
3464 if (error != JDWP::ERR_NONE) {
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08003465 return JDWP::ERR_INVALID_OBJECT;
3466 }
Elliott Hughes45651fd2012-02-21 15:48:20 -08003467
Ian Rogersc0542af2014-09-03 16:16:56 -07003468 mirror::Object* thread = gRegistry->Get<mirror::Object*>(thread_id, &error);
3469 if (error != JDWP::ERR_NONE) {
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08003470 return JDWP::ERR_INVALID_OBJECT;
3471 }
Elliott Hughes45651fd2012-02-21 15:48:20 -08003472 // TODO: check that 'thread' is actually a java.lang.Thread!
3473
Ian Rogersc0542af2014-09-03 16:16:56 -07003474 mirror::Class* c = DecodeClass(class_id, &error);
3475 if (c == nullptr) {
3476 return error;
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08003477 }
Elliott Hughes45651fd2012-02-21 15:48:20 -08003478
Brian Carlstromea46f952013-07-30 01:26:50 -07003479 mirror::ArtMethod* m = FromMethodId(method_id);
Ian Rogersc0542af2014-09-03 16:16:56 -07003480 if (m->IsStatic() != (receiver == nullptr)) {
Elliott Hughes45651fd2012-02-21 15:48:20 -08003481 return JDWP::ERR_INVALID_METHODID;
3482 }
3483 if (m->IsStatic()) {
3484 if (m->GetDeclaringClass() != c) {
3485 return JDWP::ERR_INVALID_METHODID;
3486 }
3487 } else {
3488 if (!m->GetDeclaringClass()->IsAssignableFrom(c)) {
3489 return JDWP::ERR_INVALID_METHODID;
3490 }
3491 }
3492
3493 // Check the argument list matches the method.
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07003494 uint32_t shorty_len = 0;
3495 const char* shorty = m->GetShorty(&shorty_len);
3496 if (shorty_len - 1 != arg_count) {
Elliott Hughes45651fd2012-02-21 15:48:20 -08003497 return JDWP::ERR_ILLEGAL_ARGUMENT;
3498 }
Elliott Hughes09201632013-04-15 15:50:07 -07003499
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07003500 {
3501 StackHandleScope<3> hs(soa.Self());
3502 MethodHelper mh(hs.NewHandle(m));
3503 HandleWrapper<mirror::Object> h_obj(hs.NewHandleWrapper(&receiver));
3504 HandleWrapper<mirror::Class> h_klass(hs.NewHandleWrapper(&c));
3505 const DexFile::TypeList* types = m->GetParameterTypeList();
3506 for (size_t i = 0; i < arg_count; ++i) {
3507 if (shorty[i + 1] != JdwpTagToShortyChar(arg_types[i])) {
Elliott Hughes09201632013-04-15 15:50:07 -07003508 return JDWP::ERR_ILLEGAL_ARGUMENT;
3509 }
3510
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07003511 if (shorty[i + 1] == 'L') {
3512 // Did we really get an argument of an appropriate reference type?
3513 mirror::Class* parameter_type = mh.GetClassFromTypeIdx(types->GetTypeItem(i).type_idx_);
Ian Rogersc0542af2014-09-03 16:16:56 -07003514 mirror::Object* argument = gRegistry->Get<mirror::Object*>(arg_values[i], &error);
3515 if (error != JDWP::ERR_NONE) {
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07003516 return JDWP::ERR_INVALID_OBJECT;
3517 }
Ian Rogersc0542af2014-09-03 16:16:56 -07003518 if (argument != nullptr && !argument->InstanceOf(parameter_type)) {
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07003519 return JDWP::ERR_ILLEGAL_ARGUMENT;
3520 }
3521
3522 // Turn the on-the-wire ObjectId into a jobject.
3523 jvalue& v = reinterpret_cast<jvalue&>(arg_values[i]);
3524 v.l = gRegistry->GetJObject(arg_values[i]);
3525 }
Elliott Hughes09201632013-04-15 15:50:07 -07003526 }
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07003527 // Update in case it moved.
3528 m = mh.GetMethod();
Elliott Hughes45651fd2012-02-21 15:48:20 -08003529 }
3530
Sebastien Hertzd38667a2013-11-25 15:43:54 +01003531 req->receiver = receiver;
3532 req->thread = thread;
3533 req->klass = c;
3534 req->method = m;
3535 req->arg_count = arg_count;
3536 req->arg_values = arg_values;
3537 req->options = options;
3538 req->invoke_needed = true;
Elliott Hughesd07986f2011-12-06 18:27:45 -08003539 }
3540
3541 // The fact that we've released the thread list lock is a bit risky --- if the thread goes
3542 // away we're sitting high and dry -- but we must release this before the ResumeAllThreads
3543 // call, and it's unwise to hold it during WaitForSuspend.
3544
3545 {
3546 /*
3547 * We change our (JDWP thread) status, which should be THREAD_RUNNING,
Elliott Hughes81ff3182012-03-23 20:35:56 -07003548 * so we can suspend for a GC if the invoke request causes us to
Elliott Hughesd07986f2011-12-06 18:27:45 -08003549 * run out of memory. It's also a good idea to change it before locking
3550 * the invokeReq mutex, although that should never be held for long.
3551 */
Ian Rogers00f7d0e2012-07-19 15:28:27 -07003552 self->TransitionFromRunnableToSuspended(kWaitingForDebuggerSend);
Elliott Hughesd07986f2011-12-06 18:27:45 -08003553
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08003554 VLOG(jdwp) << " Transferring control to event thread";
Elliott Hughesd07986f2011-12-06 18:27:45 -08003555 {
Sebastien Hertzd38667a2013-11-25 15:43:54 +01003556 MutexLock mu(self, req->lock);
Elliott Hughesd07986f2011-12-06 18:27:45 -08003557
3558 if ((options & JDWP::INVOKE_SINGLE_THREADED) == 0) {
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08003559 VLOG(jdwp) << " Resuming all threads";
Ian Rogers00f7d0e2012-07-19 15:28:27 -07003560 thread_list->UndoDebuggerSuspensions();
Elliott Hughesd07986f2011-12-06 18:27:45 -08003561 } else {
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08003562 VLOG(jdwp) << " Resuming event thread only";
Elliott Hughesd07986f2011-12-06 18:27:45 -08003563 thread_list->Resume(targetThread, true);
3564 }
3565
3566 // Wait for the request to finish executing.
Sebastien Hertzd38667a2013-11-25 15:43:54 +01003567 while (req->invoke_needed) {
3568 req->cond.Wait(self);
Elliott Hughesd07986f2011-12-06 18:27:45 -08003569 }
3570 }
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08003571 VLOG(jdwp) << " Control has returned from event thread";
Elliott Hughesd07986f2011-12-06 18:27:45 -08003572
3573 /* wait for thread to re-suspend itself */
Brian Carlstromdf629502013-07-17 22:39:56 -07003574 SuspendThread(thread_id, false /* request_suspension */);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07003575 self->TransitionFromSuspendedToRunnable();
Elliott Hughesd07986f2011-12-06 18:27:45 -08003576 }
3577
3578 /*
3579 * Suspend the threads. We waited for the target thread to suspend
3580 * itself, so all we need to do is suspend the others.
3581 *
3582 * The suspendAllThreads() call will double-suspend the event thread,
3583 * so we want to resume the target thread once to keep the books straight.
3584 */
3585 if ((options & JDWP::INVOKE_SINGLE_THREADED) == 0) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07003586 self->TransitionFromRunnableToSuspended(kWaitingForDebuggerSuspension);
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08003587 VLOG(jdwp) << " Suspending all threads";
Ian Rogers00f7d0e2012-07-19 15:28:27 -07003588 thread_list->SuspendAllForDebugger();
3589 self->TransitionFromSuspendedToRunnable();
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08003590 VLOG(jdwp) << " Resuming event thread to balance the count";
Elliott Hughesd07986f2011-12-06 18:27:45 -08003591 thread_list->Resume(targetThread, true);
3592 }
3593
3594 // Copy the result.
3595 *pResultTag = req->result_tag;
3596 if (IsPrimitiveTag(req->result_tag)) {
Elliott Hughesf24d3ce2012-04-11 17:43:37 -07003597 *pResultValue = req->result_value.GetJ();
Elliott Hughesd07986f2011-12-06 18:27:45 -08003598 } else {
Elliott Hughesf24d3ce2012-04-11 17:43:37 -07003599 *pResultValue = gRegistry->Add(req->result_value.GetL());
Elliott Hughesd07986f2011-12-06 18:27:45 -08003600 }
3601 *pExceptionId = req->exception;
3602 return req->error;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07003603}
3604
3605void Dbg::ExecuteMethod(DebugInvokeReq* pReq) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07003606 ScopedObjectAccess soa(Thread::Current());
Elliott Hughesd07986f2011-12-06 18:27:45 -08003607
Elliott Hughes81ff3182012-03-23 20:35:56 -07003608 // We can be called while an exception is pending. We need
Elliott Hughesd07986f2011-12-06 18:27:45 -08003609 // to preserve that across the method invocation.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003610 StackHandleScope<4> hs(soa.Self());
3611 auto old_throw_this_object = hs.NewHandle<mirror::Object>(nullptr);
3612 auto old_throw_method = hs.NewHandle<mirror::ArtMethod>(nullptr);
3613 auto old_exception = hs.NewHandle<mirror::Throwable>(nullptr);
Ian Rogers62d6c772013-02-27 08:32:07 -08003614 uint32_t old_throw_dex_pc;
Sebastien Hertz9f102032014-05-23 08:59:42 +02003615 bool old_exception_report_flag;
Ian Rogers62d6c772013-02-27 08:32:07 -08003616 {
3617 ThrowLocation old_throw_location;
3618 mirror::Throwable* old_exception_obj = soa.Self()->GetException(&old_throw_location);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003619 old_throw_this_object.Assign(old_throw_location.GetThis());
3620 old_throw_method.Assign(old_throw_location.GetMethod());
3621 old_exception.Assign(old_exception_obj);
Ian Rogers62d6c772013-02-27 08:32:07 -08003622 old_throw_dex_pc = old_throw_location.GetDexPc();
Sebastien Hertz9f102032014-05-23 08:59:42 +02003623 old_exception_report_flag = soa.Self()->IsExceptionReportedToInstrumentation();
Ian Rogers62d6c772013-02-27 08:32:07 -08003624 soa.Self()->ClearException();
3625 }
Elliott Hughesd07986f2011-12-06 18:27:45 -08003626
3627 // Translate the method through the vtable, unless the debugger wants to suppress it.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003628 Handle<mirror::ArtMethod> m(hs.NewHandle(pReq->method));
Ian Rogersc0542af2014-09-03 16:16:56 -07003629 if ((pReq->options & JDWP::INVOKE_NONVIRTUAL) == 0 && pReq->receiver != nullptr) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003630 mirror::ArtMethod* actual_method = pReq->klass->FindVirtualMethodForVirtualOrInterface(m.Get());
3631 if (actual_method != m.Get()) {
3632 VLOG(jdwp) << "ExecuteMethod translated " << PrettyMethod(m.Get()) << " to " << PrettyMethod(actual_method);
3633 m.Assign(actual_method);
Elliott Hughes45651fd2012-02-21 15:48:20 -08003634 }
Elliott Hughesd07986f2011-12-06 18:27:45 -08003635 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003636 VLOG(jdwp) << "ExecuteMethod " << PrettyMethod(m.Get())
Sebastien Hertzd38667a2013-11-25 15:43:54 +01003637 << " receiver=" << pReq->receiver
3638 << " arg_count=" << pReq->arg_count;
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003639 CHECK(m.Get() != nullptr);
Elliott Hughesd07986f2011-12-06 18:27:45 -08003640
3641 CHECK_EQ(sizeof(jvalue), sizeof(uint64_t));
3642
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003643 pReq->result_value = InvokeWithJValues(soa, pReq->receiver, soa.EncodeMethod(m.Get()),
Ian Rogers53b8b092014-03-13 23:45:53 -07003644 reinterpret_cast<jvalue*>(pReq->arg_values));
Elliott Hughesd07986f2011-12-06 18:27:45 -08003645
Ian Rogersc0542af2014-09-03 16:16:56 -07003646 mirror::Throwable* exception = soa.Self()->GetException(nullptr);
Ian Rogers62d6c772013-02-27 08:32:07 -08003647 soa.Self()->ClearException();
3648 pReq->exception = gRegistry->Add(exception);
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07003649 pReq->result_tag = BasicTagFromDescriptor(m.Get()->GetShorty());
Elliott Hughesd07986f2011-12-06 18:27:45 -08003650 if (pReq->exception != 0) {
Ian Rogers62d6c772013-02-27 08:32:07 -08003651 VLOG(jdwp) << " JDWP invocation returning with exception=" << exception
3652 << " " << exception->Dump();
Elliott Hughesf24d3ce2012-04-11 17:43:37 -07003653 pReq->result_value.SetJ(0);
Elliott Hughesd07986f2011-12-06 18:27:45 -08003654 } else if (pReq->result_tag == JDWP::JT_OBJECT) {
3655 /* if no exception thrown, examine object result more closely */
Ian Rogers98379392014-02-24 16:53:16 -08003656 JDWP::JdwpTag new_tag = TagFromObject(soa, pReq->result_value.GetL());
Elliott Hughesd07986f2011-12-06 18:27:45 -08003657 if (new_tag != pReq->result_tag) {
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08003658 VLOG(jdwp) << " JDWP promoted result from " << pReq->result_tag << " to " << new_tag;
Elliott Hughesd07986f2011-12-06 18:27:45 -08003659 pReq->result_tag = new_tag;
3660 }
3661
3662 /*
3663 * Register the object. We don't actually need an ObjectId yet,
3664 * but we do need to be sure that the GC won't move or discard the
3665 * object when we switch out of RUNNING. The ObjectId conversion
3666 * will add the object to the "do not touch" list.
3667 *
3668 * We can't use the "tracked allocation" mechanism here because
3669 * the object is going to be handed off to a different thread.
3670 */
Elliott Hughesf24d3ce2012-04-11 17:43:37 -07003671 gRegistry->Add(pReq->result_value.GetL());
Elliott Hughesd07986f2011-12-06 18:27:45 -08003672 }
3673
Ian Rogersc0542af2014-09-03 16:16:56 -07003674 if (old_exception.Get() != nullptr) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003675 ThrowLocation gc_safe_throw_location(old_throw_this_object.Get(), old_throw_method.Get(),
Ian Rogers62d6c772013-02-27 08:32:07 -08003676 old_throw_dex_pc);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003677 soa.Self()->SetException(gc_safe_throw_location, old_exception.Get());
Sebastien Hertz9f102032014-05-23 08:59:42 +02003678 soa.Self()->SetExceptionReportedToInstrumentation(old_exception_report_flag);
Elliott Hughesd07986f2011-12-06 18:27:45 -08003679 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -07003680}
3681
Elliott Hughesd07986f2011-12-06 18:27:45 -08003682/*
Elliott Hughes4b9702c2013-02-20 18:13:24 -08003683 * "request" contains a full JDWP packet, possibly with multiple chunks. We
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07003684 * need to process each, accumulate the replies, and ship the whole thing
3685 * back.
3686 *
3687 * Returns "true" if we have a reply. The reply buffer is newly allocated,
3688 * and includes the chunk type/length, followed by the data.
3689 *
Elliott Hughes3d30d9b2011-12-07 17:35:48 -08003690 * OLD-TODO: we currently assume that the request and reply include a single
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07003691 * chunk. If this becomes inconvenient we will need to adapt.
3692 */
Ian Rogersc0542af2014-09-03 16:16:56 -07003693bool Dbg::DdmHandlePacket(JDWP::Request* request, uint8_t** pReplyBuf, int* pReplyLen) {
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07003694 Thread* self = Thread::Current();
3695 JNIEnv* env = self->GetJniEnv();
3696
Ian Rogersc0542af2014-09-03 16:16:56 -07003697 uint32_t type = request->ReadUnsigned32("type");
3698 uint32_t length = request->ReadUnsigned32("length");
Elliott Hughes4b9702c2013-02-20 18:13:24 -08003699
3700 // Create a byte[] corresponding to 'request'.
Ian Rogersc0542af2014-09-03 16:16:56 -07003701 size_t request_length = request->size();
Elliott Hughes4b9702c2013-02-20 18:13:24 -08003702 ScopedLocalRef<jbyteArray> dataArray(env, env->NewByteArray(request_length));
Ian Rogersc0542af2014-09-03 16:16:56 -07003703 if (dataArray.get() == nullptr) {
Elliott Hughes4b9702c2013-02-20 18:13:24 -08003704 LOG(WARNING) << "byte[] allocation failed: " << request_length;
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07003705 env->ExceptionClear();
3706 return false;
3707 }
Ian Rogersc0542af2014-09-03 16:16:56 -07003708 env->SetByteArrayRegion(dataArray.get(), 0, request_length,
3709 reinterpret_cast<const jbyte*>(request->data()));
3710 request->Skip(request_length);
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07003711
3712 // Run through and find all chunks. [Currently just find the first.]
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003713 ScopedByteArrayRO contents(env, dataArray.get());
Elliott Hughes4b9702c2013-02-20 18:13:24 -08003714 if (length != request_length) {
Ian Rogersef7d42f2014-01-06 12:55:46 -08003715 LOG(WARNING) << StringPrintf("bad chunk found (len=%u pktLen=%zd)", length, request_length);
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07003716 return false;
3717 }
3718
3719 // Call "private static Chunk dispatch(int type, byte[] data, int offset, int length)".
Elliott Hugheseac76672012-05-24 21:56:51 -07003720 ScopedLocalRef<jobject> chunk(env, env->CallStaticObjectMethod(WellKnownClasses::org_apache_harmony_dalvik_ddmc_DdmServer,
3721 WellKnownClasses::org_apache_harmony_dalvik_ddmc_DdmServer_dispatch,
Elliott Hughes4b9702c2013-02-20 18:13:24 -08003722 type, dataArray.get(), 0, length));
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07003723 if (env->ExceptionCheck()) {
3724 LOG(INFO) << StringPrintf("Exception thrown by dispatcher for 0x%08x", type);
3725 env->ExceptionDescribe();
3726 env->ExceptionClear();
3727 return false;
3728 }
3729
Ian Rogersc0542af2014-09-03 16:16:56 -07003730 if (chunk.get() == nullptr) {
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07003731 return false;
3732 }
3733
3734 /*
3735 * Pull the pieces out of the chunk. We copy the results into a
3736 * newly-allocated buffer that the caller can free. We don't want to
3737 * continue using the Chunk object because nothing has a reference to it.
3738 *
3739 * We could avoid this by returning type/data/offset/length and having
3740 * the caller be aware of the object lifetime issues, but that
Elliott Hughes81ff3182012-03-23 20:35:56 -07003741 * integrates the JDWP code more tightly into the rest of the runtime, and doesn't work
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07003742 * if we have responses for multiple chunks.
3743 *
3744 * So we're pretty much stuck with copying data around multiple times.
3745 */
Elliott Hugheseac76672012-05-24 21:56:51 -07003746 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 -08003747 jint offset = env->GetIntField(chunk.get(), WellKnownClasses::org_apache_harmony_dalvik_ddmc_Chunk_offset);
Elliott Hugheseac76672012-05-24 21:56:51 -07003748 length = env->GetIntField(chunk.get(), WellKnownClasses::org_apache_harmony_dalvik_ddmc_Chunk_length);
Elliott Hugheseac76672012-05-24 21:56:51 -07003749 type = env->GetIntField(chunk.get(), WellKnownClasses::org_apache_harmony_dalvik_ddmc_Chunk_type);
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07003750
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08003751 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 -07003752 if (length == 0 || replyData.get() == nullptr) {
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07003753 return false;
3754 }
3755
Elliott Hughes4b9702c2013-02-20 18:13:24 -08003756 const int kChunkHdrLen = 8;
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07003757 uint8_t* reply = new uint8_t[length + kChunkHdrLen];
Ian Rogersc0542af2014-09-03 16:16:56 -07003758 if (reply == nullptr) {
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07003759 LOG(WARNING) << "malloc failed: " << (length + kChunkHdrLen);
3760 return false;
3761 }
Elliott Hughesf7c3b662011-10-27 12:04:56 -07003762 JDWP::Set4BE(reply + 0, type);
3763 JDWP::Set4BE(reply + 4, length);
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003764 env->GetByteArrayRegion(replyData.get(), offset, length, reinterpret_cast<jbyte*>(reply + kChunkHdrLen));
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07003765
3766 *pReplyBuf = reply;
3767 *pReplyLen = length + kChunkHdrLen;
3768
Elliott Hughes4b9702c2013-02-20 18:13:24 -08003769 VLOG(jdwp) << StringPrintf("dvmHandleDdm returning type=%.4s %p len=%d", reinterpret_cast<char*>(reply), reply, length);
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07003770 return true;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07003771}
3772
Elliott Hughesa2155262011-11-16 16:26:58 -08003773void Dbg::DdmBroadcast(bool connect) {
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08003774 VLOG(jdwp) << "Broadcasting DDM " << (connect ? "connect" : "disconnect") << "...";
Elliott Hughes47fce012011-10-25 18:37:19 -07003775
3776 Thread* self = Thread::Current();
Ian Rogers50b35e22012-10-04 10:09:15 -07003777 if (self->GetState() != kRunnable) {
3778 LOG(ERROR) << "DDM broadcast in thread state " << self->GetState();
3779 /* try anyway? */
Elliott Hughes47fce012011-10-25 18:37:19 -07003780 }
3781
3782 JNIEnv* env = self->GetJniEnv();
Elliott Hughes47fce012011-10-25 18:37:19 -07003783 jint event = connect ? 1 /*DdmServer.CONNECTED*/ : 2 /*DdmServer.DISCONNECTED*/;
Elliott Hugheseac76672012-05-24 21:56:51 -07003784 env->CallStaticVoidMethod(WellKnownClasses::org_apache_harmony_dalvik_ddmc_DdmServer,
3785 WellKnownClasses::org_apache_harmony_dalvik_ddmc_DdmServer_broadcast,
3786 event);
Elliott Hughes47fce012011-10-25 18:37:19 -07003787 if (env->ExceptionCheck()) {
3788 LOG(ERROR) << "DdmServer.broadcast " << event << " failed";
3789 env->ExceptionDescribe();
3790 env->ExceptionClear();
3791 }
3792}
3793
Elliott Hughes872d4ec2011-10-21 17:07:15 -07003794void Dbg::DdmConnected() {
Elliott Hughesa2155262011-11-16 16:26:58 -08003795 Dbg::DdmBroadcast(true);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07003796}
3797
3798void Dbg::DdmDisconnected() {
Elliott Hughesa2155262011-11-16 16:26:58 -08003799 Dbg::DdmBroadcast(false);
Elliott Hughes47fce012011-10-25 18:37:19 -07003800 gDdmThreadNotification = false;
3801}
3802
3803/*
Elliott Hughes82188472011-11-07 18:11:48 -08003804 * Send a notification when a thread starts, stops, or changes its name.
Elliott Hughes47fce012011-10-25 18:37:19 -07003805 *
3806 * Because we broadcast the full set of threads when the notifications are
3807 * first enabled, it's possible for "thread" to be actively executing.
3808 */
Elliott Hughes82188472011-11-07 18:11:48 -08003809void Dbg::DdmSendThreadNotification(Thread* t, uint32_t type) {
Elliott Hughes47fce012011-10-25 18:37:19 -07003810 if (!gDdmThreadNotification) {
3811 return;
3812 }
3813
Elliott Hughes82188472011-11-07 18:11:48 -08003814 if (type == CHUNK_TYPE("THDE")) {
Elliott Hughes47fce012011-10-25 18:37:19 -07003815 uint8_t buf[4];
Ian Rogersd9c4fc92013-10-01 19:45:43 -07003816 JDWP::Set4BE(&buf[0], t->GetThreadId());
Elliott Hughes47fce012011-10-25 18:37:19 -07003817 Dbg::DdmSendChunk(CHUNK_TYPE("THDE"), 4, buf);
Elliott Hughes82188472011-11-07 18:11:48 -08003818 } else {
3819 CHECK(type == CHUNK_TYPE("THCR") || type == CHUNK_TYPE("THNM")) << type;
Ian Rogers00f7d0e2012-07-19 15:28:27 -07003820 ScopedObjectAccessUnchecked soa(Thread::Current());
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003821 StackHandleScope<1> hs(soa.Self());
3822 Handle<mirror::String> name(hs.NewHandle(t->GetThreadName(soa)));
Ian Rogersc0542af2014-09-03 16:16:56 -07003823 size_t char_count = (name.Get() != nullptr) ? name->GetLength() : 0;
3824 const jchar* chars = (name.Get() != nullptr) ? name->GetCharArray()->GetData() : nullptr;
Elliott Hughes82188472011-11-07 18:11:48 -08003825
Elliott Hughes21f32d72011-11-09 17:44:13 -08003826 std::vector<uint8_t> bytes;
Ian Rogersd9c4fc92013-10-01 19:45:43 -07003827 JDWP::Append4BE(bytes, t->GetThreadId());
Elliott Hughes545a0642011-11-08 19:10:03 -08003828 JDWP::AppendUtf16BE(bytes, chars, char_count);
Elliott Hughes21f32d72011-11-09 17:44:13 -08003829 CHECK_EQ(bytes.size(), char_count*2 + sizeof(uint32_t)*2);
3830 Dbg::DdmSendChunk(type, bytes);
Elliott Hughes47fce012011-10-25 18:37:19 -07003831 }
3832}
3833
Elliott Hughes47fce012011-10-25 18:37:19 -07003834void Dbg::DdmSetThreadNotification(bool enable) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07003835 // Enable/disable thread notifications.
Elliott Hughes47fce012011-10-25 18:37:19 -07003836 gDdmThreadNotification = enable;
3837 if (enable) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07003838 // Suspend the VM then post thread start notifications for all threads. Threads attaching will
3839 // see a suspension in progress and block until that ends. They then post their own start
3840 // notification.
3841 SuspendVM();
3842 std::list<Thread*> threads;
Ian Rogers50b35e22012-10-04 10:09:15 -07003843 Thread* self = Thread::Current();
Ian Rogers00f7d0e2012-07-19 15:28:27 -07003844 {
Ian Rogers50b35e22012-10-04 10:09:15 -07003845 MutexLock mu(self, *Locks::thread_list_lock_);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07003846 threads = Runtime::Current()->GetThreadList()->GetList();
3847 }
3848 {
Ian Rogers50b35e22012-10-04 10:09:15 -07003849 ScopedObjectAccess soa(self);
Mathieu Chartier02e25112013-08-14 16:14:24 -07003850 for (Thread* thread : threads) {
3851 Dbg::DdmSendThreadNotification(thread, CHUNK_TYPE("THCR"));
Ian Rogers00f7d0e2012-07-19 15:28:27 -07003852 }
3853 }
3854 ResumeVM();
Elliott Hughes47fce012011-10-25 18:37:19 -07003855 }
3856}
3857
Elliott Hughesa2155262011-11-16 16:26:58 -08003858void Dbg::PostThreadStartOrStop(Thread* t, uint32_t type) {
Elliott Hughesc0f09332012-03-26 13:27:06 -07003859 if (IsDebuggerActive()) {
Mathieu Chartierdbe6f462012-09-25 16:54:50 -07003860 ScopedObjectAccessUnchecked soa(Thread::Current());
Ian Rogerscfaa4552012-11-26 21:00:08 -08003861 JDWP::ObjectId id = gRegistry->Add(t->GetPeer());
Elliott Hughes82188472011-11-07 18:11:48 -08003862 gJdwpState->PostThreadChange(id, type == CHUNK_TYPE("THCR"));
Elliott Hughes47fce012011-10-25 18:37:19 -07003863 }
Elliott Hughes82188472011-11-07 18:11:48 -08003864 Dbg::DdmSendThreadNotification(t, type);
Elliott Hughes47fce012011-10-25 18:37:19 -07003865}
3866
3867void Dbg::PostThreadStart(Thread* t) {
Elliott Hughesa2155262011-11-16 16:26:58 -08003868 Dbg::PostThreadStartOrStop(t, CHUNK_TYPE("THCR"));
Elliott Hughes47fce012011-10-25 18:37:19 -07003869}
3870
3871void Dbg::PostThreadDeath(Thread* t) {
Elliott Hughesa2155262011-11-16 16:26:58 -08003872 Dbg::PostThreadStartOrStop(t, CHUNK_TYPE("THDE"));
Elliott Hughes872d4ec2011-10-21 17:07:15 -07003873}
3874
Elliott Hughes82188472011-11-07 18:11:48 -08003875void Dbg::DdmSendChunk(uint32_t type, size_t byte_count, const uint8_t* buf) {
Ian Rogersc0542af2014-09-03 16:16:56 -07003876 CHECK(buf != nullptr);
Elliott Hughes3bb81562011-10-21 18:52:59 -07003877 iovec vec[1];
3878 vec[0].iov_base = reinterpret_cast<void*>(const_cast<uint8_t*>(buf));
3879 vec[0].iov_len = byte_count;
3880 Dbg::DdmSendChunkV(type, vec, 1);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07003881}
3882
Elliott Hughes21f32d72011-11-09 17:44:13 -08003883void Dbg::DdmSendChunk(uint32_t type, const std::vector<uint8_t>& bytes) {
3884 DdmSendChunk(type, bytes.size(), &bytes[0]);
3885}
3886
Brian Carlstromf5293522013-07-19 00:24:00 -07003887void Dbg::DdmSendChunkV(uint32_t type, const iovec* iov, int iov_count) {
Ian Rogersc0542af2014-09-03 16:16:56 -07003888 if (gJdwpState == nullptr) {
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08003889 VLOG(jdwp) << "Debugger thread not active, ignoring DDM send: " << type;
Elliott Hughes3bb81562011-10-21 18:52:59 -07003890 } else {
Elliott Hughescccd84f2011-12-05 16:51:54 -08003891 gJdwpState->DdmSendChunkV(type, iov, iov_count);
Elliott Hughes3bb81562011-10-21 18:52:59 -07003892 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -07003893}
3894
Elliott Hughes767a1472011-10-26 18:49:02 -07003895int Dbg::DdmHandleHpifChunk(HpifWhen when) {
3896 if (when == HPIF_WHEN_NOW) {
Elliott Hughes7162ad92011-10-27 14:08:42 -07003897 DdmSendHeapInfo(when);
Elliott Hughes767a1472011-10-26 18:49:02 -07003898 return true;
3899 }
3900
3901 if (when != HPIF_WHEN_NEVER && when != HPIF_WHEN_NEXT_GC && when != HPIF_WHEN_EVERY_GC) {
3902 LOG(ERROR) << "invalid HpifWhen value: " << static_cast<int>(when);
3903 return false;
3904 }
3905
3906 gDdmHpifWhen = when;
3907 return true;
3908}
3909
3910bool Dbg::DdmHandleHpsgNhsgChunk(Dbg::HpsgWhen when, Dbg::HpsgWhat what, bool native) {
3911 if (when != HPSG_WHEN_NEVER && when != HPSG_WHEN_EVERY_GC) {
3912 LOG(ERROR) << "invalid HpsgWhen value: " << static_cast<int>(when);
3913 return false;
3914 }
3915
3916 if (what != HPSG_WHAT_MERGED_OBJECTS && what != HPSG_WHAT_DISTINCT_OBJECTS) {
3917 LOG(ERROR) << "invalid HpsgWhat value: " << static_cast<int>(what);
3918 return false;
3919 }
3920
3921 if (native) {
3922 gDdmNhsgWhen = when;
3923 gDdmNhsgWhat = what;
3924 } else {
3925 gDdmHpsgWhen = when;
3926 gDdmHpsgWhat = what;
3927 }
3928 return true;
3929}
3930
Elliott Hughes7162ad92011-10-27 14:08:42 -07003931void Dbg::DdmSendHeapInfo(HpifWhen reason) {
3932 // If there's a one-shot 'when', reset it.
3933 if (reason == gDdmHpifWhen) {
3934 if (gDdmHpifWhen == HPIF_WHEN_NEXT_GC) {
3935 gDdmHpifWhen = HPIF_WHEN_NEVER;
3936 }
3937 }
3938
3939 /*
3940 * Chunk HPIF (client --> server)
3941 *
3942 * Heap Info. General information about the heap,
3943 * suitable for a summary display.
3944 *
3945 * [u4]: number of heaps
3946 *
3947 * For each heap:
3948 * [u4]: heap ID
3949 * [u8]: timestamp in ms since Unix epoch
3950 * [u1]: capture reason (same as 'when' value from server)
3951 * [u4]: max heap size in bytes (-Xmx)
3952 * [u4]: current heap size in bytes
3953 * [u4]: current number of bytes allocated
3954 * [u4]: current number of objects allocated
3955 */
3956 uint8_t heap_count = 1;
Ian Rogers1d54e732013-05-02 21:10:01 -07003957 gc::Heap* heap = Runtime::Current()->GetHeap();
Elliott Hughes21f32d72011-11-09 17:44:13 -08003958 std::vector<uint8_t> bytes;
Elliott Hughes545a0642011-11-08 19:10:03 -08003959 JDWP::Append4BE(bytes, heap_count);
Brian Carlstrom7934ac22013-07-26 10:54:15 -07003960 JDWP::Append4BE(bytes, 1); // Heap id (bogus; we only have one heap).
Elliott Hughes545a0642011-11-08 19:10:03 -08003961 JDWP::Append8BE(bytes, MilliTime());
3962 JDWP::Append1BE(bytes, reason);
Brian Carlstrom7934ac22013-07-26 10:54:15 -07003963 JDWP::Append4BE(bytes, heap->GetMaxMemory()); // Max allowed heap size in bytes.
3964 JDWP::Append4BE(bytes, heap->GetTotalMemory()); // Current heap size in bytes.
Elliott Hughesb3bd5f02012-03-08 21:05:27 -08003965 JDWP::Append4BE(bytes, heap->GetBytesAllocated());
3966 JDWP::Append4BE(bytes, heap->GetObjectsAllocated());
Elliott Hughes21f32d72011-11-09 17:44:13 -08003967 CHECK_EQ(bytes.size(), 4U + (heap_count * (4 + 8 + 1 + 4 + 4 + 4 + 4)));
3968 Dbg::DdmSendChunk(CHUNK_TYPE("HPIF"), bytes);
Elliott Hughes767a1472011-10-26 18:49:02 -07003969}
3970
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003971enum HpsgSolidity {
3972 SOLIDITY_FREE = 0,
3973 SOLIDITY_HARD = 1,
3974 SOLIDITY_SOFT = 2,
3975 SOLIDITY_WEAK = 3,
3976 SOLIDITY_PHANTOM = 4,
3977 SOLIDITY_FINALIZABLE = 5,
3978 SOLIDITY_SWEEP = 6,
3979};
3980
3981enum HpsgKind {
3982 KIND_OBJECT = 0,
3983 KIND_CLASS_OBJECT = 1,
3984 KIND_ARRAY_1 = 2,
3985 KIND_ARRAY_2 = 3,
3986 KIND_ARRAY_4 = 4,
3987 KIND_ARRAY_8 = 5,
3988 KIND_UNKNOWN = 6,
3989 KIND_NATIVE = 7,
3990};
3991
3992#define HPSG_PARTIAL (1<<7)
3993#define HPSG_STATE(solidity, kind) ((uint8_t)((((kind) & 0x7) << 3) | ((solidity) & 0x7)))
3994
Ian Rogers30fab402012-01-23 15:43:46 -08003995class HeapChunkContext {
3996 public:
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003997 // Maximum chunk size. Obtain this from the formula:
3998 // (((maximum_heap_size / ALLOCATION_UNIT_SIZE) + 255) / 256) * 2
3999 HeapChunkContext(bool merge, bool native)
Ian Rogers30fab402012-01-23 15:43:46 -08004000 : buf_(16384 - 16),
4001 type_(0),
Mathieu Chartier36dab362014-07-30 14:59:56 -07004002 merge_(merge),
4003 chunk_overhead_(0) {
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004004 Reset();
4005 if (native) {
Ian Rogers30fab402012-01-23 15:43:46 -08004006 type_ = CHUNK_TYPE("NHSG");
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004007 } else {
Ian Rogers30fab402012-01-23 15:43:46 -08004008 type_ = merge ? CHUNK_TYPE("HPSG") : CHUNK_TYPE("HPSO");
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004009 }
4010 }
4011
4012 ~HeapChunkContext() {
Ian Rogers30fab402012-01-23 15:43:46 -08004013 if (p_ > &buf_[0]) {
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004014 Flush();
4015 }
4016 }
4017
Mathieu Chartier36dab362014-07-30 14:59:56 -07004018 void SetChunkOverhead(size_t chunk_overhead) {
4019 chunk_overhead_ = chunk_overhead;
4020 }
4021
4022 void ResetStartOfNextChunk() {
4023 startOfNextMemoryChunk_ = nullptr;
4024 }
4025
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004026 void EnsureHeader(const void* chunk_ptr) {
Ian Rogers30fab402012-01-23 15:43:46 -08004027 if (!needHeader_) {
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004028 return;
4029 }
4030
4031 // Start a new HPSx chunk.
Brian Carlstrom7934ac22013-07-26 10:54:15 -07004032 JDWP::Write4BE(&p_, 1); // Heap id (bogus; we only have one heap).
4033 JDWP::Write1BE(&p_, 8); // Size of allocation unit, in bytes.
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004034
Brian Carlstrom7934ac22013-07-26 10:54:15 -07004035 JDWP::Write4BE(&p_, reinterpret_cast<uintptr_t>(chunk_ptr)); // virtual address of segment start.
4036 JDWP::Write4BE(&p_, 0); // offset of this piece (relative to the virtual address).
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004037 // [u4]: length of piece, in allocation units
4038 // 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 -08004039 pieceLenField_ = p_;
4040 JDWP::Write4BE(&p_, 0x55555555);
4041 needHeader_ = false;
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004042 }
4043
Ian Rogersb726dcb2012-09-05 08:57:23 -07004044 void Flush() SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Ian Rogersc0542af2014-09-03 16:16:56 -07004045 if (pieceLenField_ == nullptr) {
Ian Rogersd636b062013-01-18 17:51:18 -08004046 // Flush immediately post Reset (maybe back-to-back Flush). Ignore.
4047 CHECK(needHeader_);
4048 return;
4049 }
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004050 // Patch the "length of piece" field.
Ian Rogers30fab402012-01-23 15:43:46 -08004051 CHECK_LE(&buf_[0], pieceLenField_);
4052 CHECK_LE(pieceLenField_, p_);
4053 JDWP::Set4BE(pieceLenField_, totalAllocationUnits_);
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004054
Ian Rogers30fab402012-01-23 15:43:46 -08004055 Dbg::DdmSendChunk(type_, p_ - &buf_[0], &buf_[0]);
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004056 Reset();
4057 }
4058
Ian Rogers00f7d0e2012-07-19 15:28:27 -07004059 static void HeapChunkCallback(void* start, void* end, size_t used_bytes, void* arg)
Ian Rogersb726dcb2012-09-05 08:57:23 -07004060 SHARED_LOCKS_REQUIRED(Locks::heap_bitmap_lock_,
4061 Locks::mutator_lock_) {
Ian Rogers30fab402012-01-23 15:43:46 -08004062 reinterpret_cast<HeapChunkContext*>(arg)->HeapChunkCallback(start, end, used_bytes);
Elliott Hughesa2155262011-11-16 16:26:58 -08004063 }
4064
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004065 private:
Elliott Hughesa2155262011-11-16 16:26:58 -08004066 enum { ALLOCATION_UNIT_SIZE = 8 };
4067
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004068 void Reset() {
Ian Rogers30fab402012-01-23 15:43:46 -08004069 p_ = &buf_[0];
Mathieu Chartier36dab362014-07-30 14:59:56 -07004070 ResetStartOfNextChunk();
Ian Rogers30fab402012-01-23 15:43:46 -08004071 totalAllocationUnits_ = 0;
4072 needHeader_ = true;
Ian Rogersc0542af2014-09-03 16:16:56 -07004073 pieceLenField_ = nullptr;
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004074 }
4075
Ian Rogers00f7d0e2012-07-19 15:28:27 -07004076 void HeapChunkCallback(void* start, void* /*end*/, size_t used_bytes)
Ian Rogersb726dcb2012-09-05 08:57:23 -07004077 SHARED_LOCKS_REQUIRED(Locks::heap_bitmap_lock_,
4078 Locks::mutator_lock_) {
Ian Rogers30fab402012-01-23 15:43:46 -08004079 // Note: heap call backs cannot manipulate the heap upon which they are crawling, care is taken
4080 // in the following code not to allocate memory, by ensuring buf_ is of the correct size
Ian Rogers15bf2d32012-08-28 17:33:04 -07004081 if (used_bytes == 0) {
Ian Rogersc0542af2014-09-03 16:16:56 -07004082 if (start == nullptr) {
Ian Rogers15bf2d32012-08-28 17:33:04 -07004083 // Reset for start of new heap.
Ian Rogersc0542af2014-09-03 16:16:56 -07004084 startOfNextMemoryChunk_ = nullptr;
Ian Rogers15bf2d32012-08-28 17:33:04 -07004085 Flush();
4086 }
4087 // Only process in use memory so that free region information
4088 // also includes dlmalloc book keeping.
Elliott Hughesa2155262011-11-16 16:26:58 -08004089 return;
Elliott Hughesa2155262011-11-16 16:26:58 -08004090 }
4091
Ian Rogers15bf2d32012-08-28 17:33:04 -07004092 /* If we're looking at the native heap, we'll just return
4093 * (SOLIDITY_HARD, KIND_NATIVE) for all allocated chunks
4094 */
4095 bool native = type_ == CHUNK_TYPE("NHSG");
4096
Mathieu Chartier36dab362014-07-30 14:59:56 -07004097 // TODO: I'm not sure using start of next chunk works well with multiple spaces. We shouldn't
4098 // count gaps inbetween spaces as free memory.
Ian Rogersc0542af2014-09-03 16:16:56 -07004099 if (startOfNextMemoryChunk_ != nullptr) {
Ian Rogers15bf2d32012-08-28 17:33:04 -07004100 // Transmit any pending free memory. Native free memory of
4101 // over kMaxFreeLen could be because of the use of mmaps, so
4102 // don't report. If not free memory then start a new segment.
4103 bool flush = true;
4104 if (start > startOfNextMemoryChunk_) {
4105 const size_t kMaxFreeLen = 2 * kPageSize;
4106 void* freeStart = startOfNextMemoryChunk_;
4107 void* freeEnd = start;
Brian Carlstrom2d888622013-07-18 17:02:00 -07004108 size_t freeLen = reinterpret_cast<char*>(freeEnd) - reinterpret_cast<char*>(freeStart);
Ian Rogers15bf2d32012-08-28 17:33:04 -07004109 if (!native || freeLen < kMaxFreeLen) {
4110 AppendChunk(HPSG_STATE(SOLIDITY_FREE, 0), freeStart, freeLen);
4111 flush = false;
4112 }
4113 }
4114 if (flush) {
Ian Rogersc0542af2014-09-03 16:16:56 -07004115 startOfNextMemoryChunk_ = nullptr;
Ian Rogers15bf2d32012-08-28 17:33:04 -07004116 Flush();
4117 }
4118 }
Ian Rogersef7d42f2014-01-06 12:55:46 -08004119 mirror::Object* obj = reinterpret_cast<mirror::Object*>(start);
Elliott Hughesa2155262011-11-16 16:26:58 -08004120
4121 // Determine the type of this chunk.
4122 // OLD-TODO: if context.merge, see if this chunk is different from the last chunk.
4123 // If it's the same, we should combine them.
Ian Rogers15bf2d32012-08-28 17:33:04 -07004124 uint8_t state = ExamineObject(obj, native);
Mathieu Chartier36dab362014-07-30 14:59:56 -07004125 AppendChunk(state, start, used_bytes + chunk_overhead_);
4126 startOfNextMemoryChunk_ = reinterpret_cast<char*>(start) + used_bytes + chunk_overhead_;
Ian Rogers15bf2d32012-08-28 17:33:04 -07004127 }
Elliott Hughesa2155262011-11-16 16:26:58 -08004128
Ian Rogers15bf2d32012-08-28 17:33:04 -07004129 void AppendChunk(uint8_t state, void* ptr, size_t length)
Ian Rogersb726dcb2012-09-05 08:57:23 -07004130 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Ian Rogers15bf2d32012-08-28 17:33:04 -07004131 // Make sure there's enough room left in the buffer.
4132 // We need to use two bytes for every fractional 256 allocation units used by the chunk plus
4133 // 17 bytes for any header.
4134 size_t needed = (((length/ALLOCATION_UNIT_SIZE + 255) / 256) * 2) + 17;
4135 size_t bytesLeft = buf_.size() - (size_t)(p_ - &buf_[0]);
4136 if (bytesLeft < needed) {
4137 Flush();
4138 }
4139
4140 bytesLeft = buf_.size() - (size_t)(p_ - &buf_[0]);
4141 if (bytesLeft < needed) {
4142 LOG(WARNING) << "Chunk is too big to transmit (chunk_len=" << length << ", "
4143 << needed << " bytes)";
4144 return;
4145 }
4146 EnsureHeader(ptr);
Elliott Hughesa2155262011-11-16 16:26:58 -08004147 // Write out the chunk description.
Ian Rogers15bf2d32012-08-28 17:33:04 -07004148 length /= ALLOCATION_UNIT_SIZE; // Convert to allocation units.
4149 totalAllocationUnits_ += length;
4150 while (length > 256) {
Ian Rogers30fab402012-01-23 15:43:46 -08004151 *p_++ = state | HPSG_PARTIAL;
4152 *p_++ = 255; // length - 1
Ian Rogers15bf2d32012-08-28 17:33:04 -07004153 length -= 256;
Elliott Hughesa2155262011-11-16 16:26:58 -08004154 }
Ian Rogers30fab402012-01-23 15:43:46 -08004155 *p_++ = state;
Ian Rogers15bf2d32012-08-28 17:33:04 -07004156 *p_++ = length - 1;
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004157 }
4158
Ian Rogersef7d42f2014-01-06 12:55:46 -08004159 uint8_t ExamineObject(mirror::Object* o, bool is_native_heap)
4160 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_, Locks::heap_bitmap_lock_) {
Ian Rogersc0542af2014-09-03 16:16:56 -07004161 if (o == nullptr) {
Elliott Hughesa2155262011-11-16 16:26:58 -08004162 return HPSG_STATE(SOLIDITY_FREE, 0);
4163 }
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004164
Elliott Hughesa2155262011-11-16 16:26:58 -08004165 // It's an allocated chunk. Figure out what it is.
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004166
Elliott Hughesa2155262011-11-16 16:26:58 -08004167 // If we're looking at the native heap, we'll just return
4168 // (SOLIDITY_HARD, KIND_NATIVE) for all allocated chunks.
Ian Rogers00f7d0e2012-07-19 15:28:27 -07004169 if (is_native_heap) {
Elliott Hughesa2155262011-11-16 16:26:58 -08004170 return HPSG_STATE(SOLIDITY_HARD, KIND_NATIVE);
4171 }
4172
Ian Rogers5bfa60f2012-09-02 21:17:56 -07004173 if (!Runtime::Current()->GetHeap()->IsLiveObjectLocked(o)) {
Ian Rogers15bf2d32012-08-28 17:33:04 -07004174 return HPSG_STATE(SOLIDITY_HARD, KIND_NATIVE);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07004175 }
4176
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08004177 mirror::Class* c = o->GetClass();
Ian Rogersc0542af2014-09-03 16:16:56 -07004178 if (c == nullptr) {
Elliott Hughesa2155262011-11-16 16:26:58 -08004179 // The object was probably just created but hasn't been initialized yet.
4180 return HPSG_STATE(SOLIDITY_HARD, KIND_OBJECT);
4181 }
4182
Mathieu Chartier590fee92013-09-13 13:46:47 -07004183 if (!Runtime::Current()->GetHeap()->IsValidObjectAddress(c)) {
Ian Rogers15bf2d32012-08-28 17:33:04 -07004184 LOG(ERROR) << "Invalid class for managed heap object: " << o << " " << c;
Elliott Hughesa2155262011-11-16 16:26:58 -08004185 return HPSG_STATE(SOLIDITY_HARD, KIND_UNKNOWN);
4186 }
4187
4188 if (c->IsClassClass()) {
4189 return HPSG_STATE(SOLIDITY_HARD, KIND_CLASS_OBJECT);
4190 }
4191
4192 if (c->IsArrayClass()) {
4193 if (o->IsObjectArray()) {
4194 return HPSG_STATE(SOLIDITY_HARD, KIND_ARRAY_4);
4195 }
4196 switch (c->GetComponentSize()) {
4197 case 1: return HPSG_STATE(SOLIDITY_HARD, KIND_ARRAY_1);
4198 case 2: return HPSG_STATE(SOLIDITY_HARD, KIND_ARRAY_2);
4199 case 4: return HPSG_STATE(SOLIDITY_HARD, KIND_ARRAY_4);
4200 case 8: return HPSG_STATE(SOLIDITY_HARD, KIND_ARRAY_8);
4201 }
4202 }
4203
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004204 return HPSG_STATE(SOLIDITY_HARD, KIND_OBJECT);
4205 }
4206
Ian Rogers30fab402012-01-23 15:43:46 -08004207 std::vector<uint8_t> buf_;
4208 uint8_t* p_;
4209 uint8_t* pieceLenField_;
Ian Rogers15bf2d32012-08-28 17:33:04 -07004210 void* startOfNextMemoryChunk_;
Ian Rogers30fab402012-01-23 15:43:46 -08004211 size_t totalAllocationUnits_;
4212 uint32_t type_;
4213 bool merge_;
4214 bool needHeader_;
Mathieu Chartier36dab362014-07-30 14:59:56 -07004215 size_t chunk_overhead_;
Ian Rogers30fab402012-01-23 15:43:46 -08004216
Elliott Hughesa2155262011-11-16 16:26:58 -08004217 DISALLOW_COPY_AND_ASSIGN(HeapChunkContext);
4218};
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004219
Mathieu Chartier36dab362014-07-30 14:59:56 -07004220static void BumpPointerSpaceCallback(mirror::Object* obj, void* arg)
4221 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) EXCLUSIVE_LOCKS_REQUIRED(Locks::heap_bitmap_lock_) {
4222 const size_t size = RoundUp(obj->SizeOf(), kObjectAlignment);
4223 HeapChunkContext::HeapChunkCallback(
4224 obj, reinterpret_cast<void*>(reinterpret_cast<uintptr_t>(obj) + size), size, arg);
4225}
4226
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004227void Dbg::DdmSendHeapSegments(bool native) {
4228 Dbg::HpsgWhen when;
4229 Dbg::HpsgWhat what;
4230 if (!native) {
4231 when = gDdmHpsgWhen;
4232 what = gDdmHpsgWhat;
4233 } else {
4234 when = gDdmNhsgWhen;
4235 what = gDdmNhsgWhat;
4236 }
4237 if (when == HPSG_WHEN_NEVER) {
4238 return;
4239 }
4240
4241 // Figure out what kind of chunks we'll be sending.
4242 CHECK(what == HPSG_WHAT_MERGED_OBJECTS || what == HPSG_WHAT_DISTINCT_OBJECTS) << static_cast<int>(what);
4243
4244 // First, send a heap start chunk.
4245 uint8_t heap_id[4];
Brian Carlstrom7934ac22013-07-26 10:54:15 -07004246 JDWP::Set4BE(&heap_id[0], 1); // Heap id (bogus; we only have one heap).
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004247 Dbg::DdmSendChunk(native ? CHUNK_TYPE("NHST") : CHUNK_TYPE("HPST"), sizeof(heap_id), heap_id);
4248
Hiroshi Yamauchicf58d4a2013-09-26 14:21:22 -07004249 Thread* self = Thread::Current();
4250
4251 // To allow the Walk/InspectAll() below to exclusively-lock the
4252 // mutator lock, temporarily release the shared access to the
4253 // mutator lock here by transitioning to the suspended state.
4254 Locks::mutator_lock_->AssertSharedHeld(self);
4255 self->TransitionFromRunnableToSuspended(kSuspended);
4256
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004257 // Send a series of heap segment chunks.
Elliott Hughesa2155262011-11-16 16:26:58 -08004258 HeapChunkContext context((what == HPSG_WHAT_MERGED_OBJECTS), native);
4259 if (native) {
Christopher Ferrisc4ddc042014-05-13 14:47:50 -07004260#ifdef USE_DLMALLOC
Ian Rogers1d54e732013-05-02 21:10:01 -07004261 dlmalloc_inspect_all(HeapChunkContext::HeapChunkCallback, &context);
Christopher Ferrisc4ddc042014-05-13 14:47:50 -07004262#else
4263 UNIMPLEMENTED(WARNING) << "Native heap inspection is only supported with dlmalloc";
4264#endif
Elliott Hughesa2155262011-11-16 16:26:58 -08004265 } else {
Ian Rogers1d54e732013-05-02 21:10:01 -07004266 gc::Heap* heap = Runtime::Current()->GetHeap();
Mathieu Chartier36dab362014-07-30 14:59:56 -07004267 for (const auto& space : heap->GetContinuousSpaces()) {
4268 if (space->IsDlMallocSpace()) {
4269 // dlmalloc's chunk header is 2 * sizeof(size_t), but if the previous chunk is in use for an
4270 // allocation then the first sizeof(size_t) may belong to it.
4271 context.SetChunkOverhead(sizeof(size_t));
4272 space->AsDlMallocSpace()->Walk(HeapChunkContext::HeapChunkCallback, &context);
4273 } else if (space->IsRosAllocSpace()) {
4274 context.SetChunkOverhead(0);
4275 space->AsRosAllocSpace()->Walk(HeapChunkContext::HeapChunkCallback, &context);
4276 } else if (space->IsBumpPointerSpace()) {
4277 context.SetChunkOverhead(0);
4278 ReaderMutexLock mu(self, *Locks::mutator_lock_);
4279 WriterMutexLock mu2(self, *Locks::heap_bitmap_lock_);
4280 space->AsBumpPointerSpace()->Walk(BumpPointerSpaceCallback, &context);
4281 } else {
4282 UNIMPLEMENTED(WARNING) << "Not counting objects in space " << *space;
Mathieu Chartierb062fdd2012-07-03 09:51:48 -07004283 }
Mathieu Chartier36dab362014-07-30 14:59:56 -07004284 context.ResetStartOfNextChunk();
Mathieu Chartierb062fdd2012-07-03 09:51:48 -07004285 }
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -07004286 // Walk the large objects, these are not in the AllocSpace.
Mathieu Chartier36dab362014-07-30 14:59:56 -07004287 context.SetChunkOverhead(0);
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -07004288 heap->GetLargeObjectsSpace()->Walk(HeapChunkContext::HeapChunkCallback, &context);
Elliott Hughesa2155262011-11-16 16:26:58 -08004289 }
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004290
Hiroshi Yamauchicf58d4a2013-09-26 14:21:22 -07004291 // Shared-lock the mutator lock back.
4292 self->TransitionFromSuspendedToRunnable();
4293 Locks::mutator_lock_->AssertSharedHeld(self);
4294
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004295 // Finally, send a heap end chunk.
4296 Dbg::DdmSendChunk(native ? CHUNK_TYPE("NHEN") : CHUNK_TYPE("HPEN"), sizeof(heap_id), heap_id);
Elliott Hughes767a1472011-10-26 18:49:02 -07004297}
4298
Elliott Hughesb1a58792013-07-11 18:10:58 -07004299static size_t GetAllocTrackerMax() {
4300#ifdef HAVE_ANDROID_OS
4301 // Check whether there's a system property overriding the number of records.
4302 const char* propertyName = "dalvik.vm.allocTrackerMax";
4303 char allocRecordMaxString[PROPERTY_VALUE_MAX];
4304 if (property_get(propertyName, allocRecordMaxString, "") > 0) {
4305 char* end;
4306 size_t value = strtoul(allocRecordMaxString, &end, 10);
4307 if (*end != '\0') {
Ruben Brunk3e47a742013-09-09 17:56:07 -07004308 LOG(ERROR) << "Ignoring " << propertyName << " '" << allocRecordMaxString
4309 << "' --- invalid";
Elliott Hughesb1a58792013-07-11 18:10:58 -07004310 return kDefaultNumAllocRecords;
4311 }
4312 if (!IsPowerOfTwo(value)) {
Ruben Brunk3e47a742013-09-09 17:56:07 -07004313 LOG(ERROR) << "Ignoring " << propertyName << " '" << allocRecordMaxString
4314 << "' --- not power of two";
Elliott Hughesb1a58792013-07-11 18:10:58 -07004315 return kDefaultNumAllocRecords;
4316 }
4317 return value;
4318 }
4319#endif
4320 return kDefaultNumAllocRecords;
4321}
4322
Brian Carlstrom306db812014-09-05 13:01:41 -07004323void Dbg::SetAllocTrackingEnabled(bool enable) {
4324 Thread* self = Thread::Current();
4325 if (enable) {
Sebastien Hertzb98063a2014-03-26 10:57:20 +01004326 {
Brian Carlstrom306db812014-09-05 13:01:41 -07004327 MutexLock mu(self, *Locks::alloc_tracker_lock_);
4328 if (recent_allocation_records_ != nullptr) {
4329 return; // Already enabled, bail.
Sebastien Hertzb98063a2014-03-26 10:57:20 +01004330 }
Brian Carlstrom306db812014-09-05 13:01:41 -07004331 alloc_record_max_ = GetAllocTrackerMax();
4332 LOG(INFO) << "Enabling alloc tracker (" << alloc_record_max_ << " entries of "
4333 << kMaxAllocRecordStackDepth << " frames, taking "
4334 << PrettySize(sizeof(AllocRecord) * alloc_record_max_) << ")";
4335 DCHECK_EQ(alloc_record_head_, 0U);
4336 DCHECK_EQ(alloc_record_count_, 0U);
4337 recent_allocation_records_ = new AllocRecord[alloc_record_max_];
4338 CHECK(recent_allocation_records_ != nullptr);
Elliott Hughes545a0642011-11-08 19:10:03 -08004339 }
Ian Rogersfa824272013-11-05 16:12:57 -08004340 Runtime::Current()->GetInstrumentation()->InstrumentQuickAllocEntryPoints();
Elliott Hughes545a0642011-11-08 19:10:03 -08004341 } else {
Sebastien Hertzb98063a2014-03-26 10:57:20 +01004342 {
Brian Carlstrom306db812014-09-05 13:01:41 -07004343 ScopedObjectAccess soa(self); // For type_cache_.Clear();
4344 MutexLock mu(self, *Locks::alloc_tracker_lock_);
4345 if (recent_allocation_records_ == nullptr) {
4346 return; // Already disabled, bail.
4347 }
Mathieu Chartier4345c462014-06-27 10:20:14 -07004348 LOG(INFO) << "Disabling alloc tracker";
Sebastien Hertzb98063a2014-03-26 10:57:20 +01004349 delete[] recent_allocation_records_;
Ian Rogersc0542af2014-09-03 16:16:56 -07004350 recent_allocation_records_ = nullptr;
Brian Carlstrom306db812014-09-05 13:01:41 -07004351 alloc_record_head_ = 0;
4352 alloc_record_count_ = 0;
Mathieu Chartier4345c462014-06-27 10:20:14 -07004353 type_cache_.Clear();
Sebastien Hertzb98063a2014-03-26 10:57:20 +01004354 }
Brian Carlstrom306db812014-09-05 13:01:41 -07004355 // If an allocation comes in before we uninstrument, we will safely drop it on the floor.
4356 Runtime::Current()->GetInstrumentation()->UninstrumentQuickAllocEntryPoints();
Elliott Hughes545a0642011-11-08 19:10:03 -08004357 }
4358}
4359
Ian Rogers0399dde2012-06-06 17:09:28 -07004360struct AllocRecordStackVisitor : public StackVisitor {
Ian Rogers7a22fa62013-01-23 12:16:16 -08004361 AllocRecordStackVisitor(Thread* thread, AllocRecord* record)
Ian Rogersb726dcb2012-09-05 08:57:23 -07004362 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_)
Ian Rogersc0542af2014-09-03 16:16:56 -07004363 : StackVisitor(thread, nullptr), record(record), depth(0) {}
Elliott Hughes545a0642011-11-08 19:10:03 -08004364
Ian Rogers00f7d0e2012-07-19 15:28:27 -07004365 // TODO: Enable annotalysis. We know lock is held in constructor, but abstraction confuses
4366 // annotalysis.
4367 bool VisitFrame() NO_THREAD_SAFETY_ANALYSIS {
Elliott Hughes545a0642011-11-08 19:10:03 -08004368 if (depth >= kMaxAllocRecordStackDepth) {
Elliott Hughes530fa002012-03-12 11:44:49 -07004369 return false;
Elliott Hughes545a0642011-11-08 19:10:03 -08004370 }
Brian Carlstromea46f952013-07-30 01:26:50 -07004371 mirror::ArtMethod* m = GetMethod();
Ian Rogers0399dde2012-06-06 17:09:28 -07004372 if (!m->IsRuntimeMethod()) {
Hiroshi Yamauchib5a9e3d2014-06-09 12:11:20 -07004373 record->StackElement(depth)->SetMethod(m);
4374 record->StackElement(depth)->SetDexPc(GetDexPc());
Elliott Hughes530fa002012-03-12 11:44:49 -07004375 ++depth;
Elliott Hughes545a0642011-11-08 19:10:03 -08004376 }
Elliott Hughes530fa002012-03-12 11:44:49 -07004377 return true;
Elliott Hughes545a0642011-11-08 19:10:03 -08004378 }
4379
4380 ~AllocRecordStackVisitor() {
4381 // Clear out any unused stack trace elements.
4382 for (; depth < kMaxAllocRecordStackDepth; ++depth) {
Hiroshi Yamauchib5a9e3d2014-06-09 12:11:20 -07004383 record->StackElement(depth)->SetMethod(nullptr);
4384 record->StackElement(depth)->SetDexPc(0);
Elliott Hughes545a0642011-11-08 19:10:03 -08004385 }
4386 }
4387
4388 AllocRecord* record;
4389 size_t depth;
4390};
4391
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08004392void Dbg::RecordAllocation(mirror::Class* type, size_t byte_count) {
Elliott Hughes545a0642011-11-08 19:10:03 -08004393 Thread* self = Thread::Current();
Ian Rogersc0542af2014-09-03 16:16:56 -07004394 CHECK(self != nullptr);
Elliott Hughes545a0642011-11-08 19:10:03 -08004395
Brian Carlstrom306db812014-09-05 13:01:41 -07004396 MutexLock mu(self, *Locks::alloc_tracker_lock_);
Ian Rogersc0542af2014-09-03 16:16:56 -07004397 if (recent_allocation_records_ == nullptr) {
Brian Carlstrom306db812014-09-05 13:01:41 -07004398 // In the process of shutting down recording, bail.
Elliott Hughes545a0642011-11-08 19:10:03 -08004399 return;
4400 }
4401
4402 // Advance and clip.
Ian Rogers719d1a32014-03-06 12:13:39 -08004403 if (++alloc_record_head_ == alloc_record_max_) {
4404 alloc_record_head_ = 0;
Elliott Hughes545a0642011-11-08 19:10:03 -08004405 }
4406
4407 // Fill in the basics.
Ian Rogers719d1a32014-03-06 12:13:39 -08004408 AllocRecord* record = &recent_allocation_records_[alloc_record_head_];
Hiroshi Yamauchib5a9e3d2014-06-09 12:11:20 -07004409 record->SetType(type);
4410 record->SetByteCount(byte_count);
4411 record->SetThinLockId(self->GetThreadId());
Elliott Hughes545a0642011-11-08 19:10:03 -08004412
4413 // Fill in the stack trace.
Ian Rogers7a22fa62013-01-23 12:16:16 -08004414 AllocRecordStackVisitor visitor(self, record);
Ian Rogers0399dde2012-06-06 17:09:28 -07004415 visitor.WalkStack();
Elliott Hughes545a0642011-11-08 19:10:03 -08004416
Ian Rogers719d1a32014-03-06 12:13:39 -08004417 if (alloc_record_count_ < alloc_record_max_) {
4418 ++alloc_record_count_;
Elliott Hughes545a0642011-11-08 19:10:03 -08004419 }
4420}
4421
Elliott Hughesa8f93cb2012-06-08 17:08:48 -07004422// Returns the index of the head element.
4423//
Brian Carlstrom306db812014-09-05 13:01:41 -07004424// We point at the most-recently-written record, so if alloc_record_count_ is 1
Elliott Hughesa8f93cb2012-06-08 17:08:48 -07004425// we want to use the current element. Take "head+1" and subtract count
4426// from it.
4427//
4428// We need to handle underflow in our circular buffer, so we add
Brian Carlstrom306db812014-09-05 13:01:41 -07004429// alloc_record_max_ and then mask it back down.
Ian Rogers719d1a32014-03-06 12:13:39 -08004430size_t Dbg::HeadIndex() {
4431 return (Dbg::alloc_record_head_ + 1 + Dbg::alloc_record_max_ - Dbg::alloc_record_count_) &
4432 (Dbg::alloc_record_max_ - 1);
Elliott Hughes545a0642011-11-08 19:10:03 -08004433}
4434
4435void Dbg::DumpRecentAllocations() {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07004436 ScopedObjectAccess soa(Thread::Current());
Brian Carlstrom306db812014-09-05 13:01:41 -07004437 MutexLock mu(soa.Self(), *Locks::alloc_tracker_lock_);
Ian Rogersc0542af2014-09-03 16:16:56 -07004438 if (recent_allocation_records_ == nullptr) {
Elliott Hughes545a0642011-11-08 19:10:03 -08004439 LOG(INFO) << "Not recording tracked allocations";
4440 return;
4441 }
4442
4443 // "i" is the head of the list. We want to start at the end of the
4444 // list and move forward to the tail.
Elliott Hughesa8f93cb2012-06-08 17:08:48 -07004445 size_t i = HeadIndex();
Brian Carlstrom306db812014-09-05 13:01:41 -07004446 const uint16_t capped_count = CappedAllocRecordCount(Dbg::alloc_record_count_);
4447 uint16_t count = capped_count;
Elliott Hughes545a0642011-11-08 19:10:03 -08004448
Ian Rogers719d1a32014-03-06 12:13:39 -08004449 LOG(INFO) << "Tracked allocations, (head=" << alloc_record_head_ << " count=" << count << ")";
Elliott Hughes545a0642011-11-08 19:10:03 -08004450 while (count--) {
4451 AllocRecord* record = &recent_allocation_records_[i];
4452
Hiroshi Yamauchib5a9e3d2014-06-09 12:11:20 -07004453 LOG(INFO) << StringPrintf(" Thread %-2d %6zd bytes ", record->ThinLockId(), record->ByteCount())
4454 << PrettyClass(record->Type());
Elliott Hughes545a0642011-11-08 19:10:03 -08004455
4456 for (size_t stack_frame = 0; stack_frame < kMaxAllocRecordStackDepth; ++stack_frame) {
Hiroshi Yamauchib5a9e3d2014-06-09 12:11:20 -07004457 AllocRecordStackTraceElement* stack_element = record->StackElement(stack_frame);
4458 mirror::ArtMethod* m = stack_element->Method();
Ian Rogersc0542af2014-09-03 16:16:56 -07004459 if (m == nullptr) {
Elliott Hughes545a0642011-11-08 19:10:03 -08004460 break;
4461 }
Hiroshi Yamauchib5a9e3d2014-06-09 12:11:20 -07004462 LOG(INFO) << " " << PrettyMethod(m) << " line " << stack_element->LineNumber();
Elliott Hughes545a0642011-11-08 19:10:03 -08004463 }
4464
4465 // pause periodically to help logcat catch up
4466 if ((count % 5) == 0) {
4467 usleep(40000);
4468 }
4469
Ian Rogers719d1a32014-03-06 12:13:39 -08004470 i = (i + 1) & (alloc_record_max_ - 1);
Elliott Hughes545a0642011-11-08 19:10:03 -08004471 }
4472}
4473
4474class StringTable {
4475 public:
4476 StringTable() {
4477 }
4478
Mathieu Chartier4345c462014-06-27 10:20:14 -07004479 void Add(const std::string& str) {
4480 table_.insert(str);
4481 }
4482
4483 void Add(const char* str) {
4484 table_.insert(str);
Elliott Hughes545a0642011-11-08 19:10:03 -08004485 }
4486
Elliott Hughesa8f93cb2012-06-08 17:08:48 -07004487 size_t IndexOf(const char* s) const {
Mathieu Chartier02e25112013-08-14 16:14:24 -07004488 auto it = table_.find(s);
Elliott Hughesa8f93cb2012-06-08 17:08:48 -07004489 if (it == table_.end()) {
4490 LOG(FATAL) << "IndexOf(\"" << s << "\") failed";
4491 }
4492 return std::distance(table_.begin(), it);
Elliott Hughes545a0642011-11-08 19:10:03 -08004493 }
4494
Elliott Hughesa8f93cb2012-06-08 17:08:48 -07004495 size_t Size() const {
Elliott Hughes545a0642011-11-08 19:10:03 -08004496 return table_.size();
4497 }
4498
Elliott Hughesa8f93cb2012-06-08 17:08:48 -07004499 void WriteTo(std::vector<uint8_t>& bytes) const {
Mathieu Chartier02e25112013-08-14 16:14:24 -07004500 for (const std::string& str : table_) {
4501 const char* s = str.c_str();
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08004502 size_t s_len = CountModifiedUtf8Chars(s);
Ian Rogers700a4022014-05-19 16:49:03 -07004503 std::unique_ptr<uint16_t> s_utf16(new uint16_t[s_len]);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08004504 ConvertModifiedUtf8ToUtf16(s_utf16.get(), s);
4505 JDWP::AppendUtf16BE(bytes, s_utf16.get(), s_len);
Elliott Hughes545a0642011-11-08 19:10:03 -08004506 }
4507 }
4508
4509 private:
Elliott Hughesa8f93cb2012-06-08 17:08:48 -07004510 std::set<std::string> table_;
Elliott Hughes545a0642011-11-08 19:10:03 -08004511 DISALLOW_COPY_AND_ASSIGN(StringTable);
4512};
4513
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07004514static const char* GetMethodSourceFile(mirror::ArtMethod* method)
Sebastien Hertz280286a2014-04-28 09:26:50 +02004515 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07004516 DCHECK(method != nullptr);
4517 const char* source_file = method->GetDeclaringClassSourceFile();
Sebastien Hertz280286a2014-04-28 09:26:50 +02004518 return (source_file != nullptr) ? source_file : "";
4519}
4520
Elliott Hughes545a0642011-11-08 19:10:03 -08004521/*
4522 * The data we send to DDMS contains everything we have recorded.
4523 *
4524 * Message header (all values big-endian):
4525 * (1b) message header len (to allow future expansion); includes itself
4526 * (1b) entry header len
4527 * (1b) stack frame len
4528 * (2b) number of entries
4529 * (4b) offset to string table from start of message
4530 * (2b) number of class name strings
4531 * (2b) number of method name strings
4532 * (2b) number of source file name strings
4533 * For each entry:
4534 * (4b) total allocation size
Elliott Hughes221229c2013-01-08 18:17:50 -08004535 * (2b) thread id
Elliott Hughes545a0642011-11-08 19:10:03 -08004536 * (2b) allocated object's class name index
4537 * (1b) stack depth
4538 * For each stack frame:
4539 * (2b) method's class name
4540 * (2b) method name
4541 * (2b) method source file
4542 * (2b) line number, clipped to 32767; -2 if native; -1 if no source
4543 * (xb) class name strings
4544 * (xb) method name strings
4545 * (xb) source file strings
4546 *
4547 * As with other DDM traffic, strings are sent as a 4-byte length
4548 * followed by UTF-16 data.
4549 *
4550 * We send up 16-bit unsigned indexes into string tables. In theory there
Brian Carlstrom306db812014-09-05 13:01:41 -07004551 * can be (kMaxAllocRecordStackDepth * alloc_record_max_) unique strings in
Elliott Hughes545a0642011-11-08 19:10:03 -08004552 * each table, but in practice there should be far fewer.
4553 *
4554 * The chief reason for using a string table here is to keep the size of
4555 * the DDMS message to a minimum. This is partly to make the protocol
4556 * efficient, but also because we have to form the whole thing up all at
4557 * once in a memory buffer.
4558 *
4559 * We use separate string tables for class names, method names, and source
4560 * files to keep the indexes small. There will generally be no overlap
4561 * between the contents of these tables.
4562 */
4563jbyteArray Dbg::GetRecentAllocations() {
4564 if (false) {
4565 DumpRecentAllocations();
4566 }
4567
Ian Rogers50b35e22012-10-04 10:09:15 -07004568 Thread* self = Thread::Current();
Elliott Hughes545a0642011-11-08 19:10:03 -08004569 std::vector<uint8_t> bytes;
Mathieu Chartier46e811b2013-07-10 17:09:14 -07004570 {
Brian Carlstrom306db812014-09-05 13:01:41 -07004571 MutexLock mu(self, *Locks::alloc_tracker_lock_);
Mathieu Chartier46e811b2013-07-10 17:09:14 -07004572 //
4573 // Part 1: generate string tables.
4574 //
4575 StringTable class_names;
4576 StringTable method_names;
4577 StringTable filenames;
Elliott Hughes545a0642011-11-08 19:10:03 -08004578
Brian Carlstrom306db812014-09-05 13:01:41 -07004579 const uint16_t capped_count = CappedAllocRecordCount(Dbg::alloc_record_count_);
4580 uint16_t count = capped_count;
4581 size_t idx = HeadIndex();
Mathieu Chartier46e811b2013-07-10 17:09:14 -07004582 while (count--) {
4583 AllocRecord* record = &recent_allocation_records_[idx];
Ian Rogers1ff3c982014-08-12 02:30:58 -07004584 std::string temp;
4585 class_names.Add(record->Type()->GetDescriptor(&temp));
Mathieu Chartier46e811b2013-07-10 17:09:14 -07004586 for (size_t i = 0; i < kMaxAllocRecordStackDepth; i++) {
Hiroshi Yamauchib5a9e3d2014-06-09 12:11:20 -07004587 mirror::ArtMethod* m = record->StackElement(i)->Method();
Ian Rogersc0542af2014-09-03 16:16:56 -07004588 if (m != nullptr) {
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07004589 class_names.Add(m->GetDeclaringClassDescriptor());
4590 method_names.Add(m->GetName());
4591 filenames.Add(GetMethodSourceFile(m));
Mathieu Chartier46e811b2013-07-10 17:09:14 -07004592 }
4593 }
Elliott Hughes545a0642011-11-08 19:10:03 -08004594
Ian Rogers719d1a32014-03-06 12:13:39 -08004595 idx = (idx + 1) & (alloc_record_max_ - 1);
Elliott Hughes545a0642011-11-08 19:10:03 -08004596 }
4597
Brian Carlstrom306db812014-09-05 13:01:41 -07004598 LOG(INFO) << "allocation records: " << capped_count;
Mathieu Chartier46e811b2013-07-10 17:09:14 -07004599
4600 //
4601 // Part 2: Generate the output and store it in the buffer.
4602 //
4603
4604 // (1b) message header len (to allow future expansion); includes itself
4605 // (1b) entry header len
4606 // (1b) stack frame len
4607 const int kMessageHeaderLen = 15;
4608 const int kEntryHeaderLen = 9;
4609 const int kStackFrameLen = 8;
4610 JDWP::Append1BE(bytes, kMessageHeaderLen);
4611 JDWP::Append1BE(bytes, kEntryHeaderLen);
4612 JDWP::Append1BE(bytes, kStackFrameLen);
4613
4614 // (2b) number of entries
4615 // (4b) offset to string table from start of message
4616 // (2b) number of class name strings
4617 // (2b) number of method name strings
4618 // (2b) number of source file name strings
Brian Carlstrom306db812014-09-05 13:01:41 -07004619 JDWP::Append2BE(bytes, capped_count);
Mathieu Chartier46e811b2013-07-10 17:09:14 -07004620 size_t string_table_offset = bytes.size();
Brian Carlstrom7934ac22013-07-26 10:54:15 -07004621 JDWP::Append4BE(bytes, 0); // We'll patch this later...
Mathieu Chartier46e811b2013-07-10 17:09:14 -07004622 JDWP::Append2BE(bytes, class_names.Size());
4623 JDWP::Append2BE(bytes, method_names.Size());
4624 JDWP::Append2BE(bytes, filenames.Size());
4625
Mathieu Chartier46e811b2013-07-10 17:09:14 -07004626 idx = HeadIndex();
Ian Rogers1ff3c982014-08-12 02:30:58 -07004627 std::string temp;
Brian Carlstrom306db812014-09-05 13:01:41 -07004628 for (count = capped_count; count != 0; --count) {
Mathieu Chartier46e811b2013-07-10 17:09:14 -07004629 // For each entry:
4630 // (4b) total allocation size
4631 // (2b) thread id
4632 // (2b) allocated object's class name index
4633 // (1b) stack depth
4634 AllocRecord* record = &recent_allocation_records_[idx];
4635 size_t stack_depth = record->GetDepth();
Mathieu Chartierf8322842014-05-16 10:59:25 -07004636 size_t allocated_object_class_name_index =
Ian Rogers1ff3c982014-08-12 02:30:58 -07004637 class_names.IndexOf(record->Type()->GetDescriptor(&temp));
Hiroshi Yamauchib5a9e3d2014-06-09 12:11:20 -07004638 JDWP::Append4BE(bytes, record->ByteCount());
4639 JDWP::Append2BE(bytes, record->ThinLockId());
Mathieu Chartier46e811b2013-07-10 17:09:14 -07004640 JDWP::Append2BE(bytes, allocated_object_class_name_index);
4641 JDWP::Append1BE(bytes, stack_depth);
4642
Mathieu Chartier46e811b2013-07-10 17:09:14 -07004643 for (size_t stack_frame = 0; stack_frame < stack_depth; ++stack_frame) {
4644 // For each stack frame:
4645 // (2b) method's class name
4646 // (2b) method name
4647 // (2b) method source file
4648 // (2b) line number, clipped to 32767; -2 if native; -1 if no source
Hiroshi Yamauchib5a9e3d2014-06-09 12:11:20 -07004649 mirror::ArtMethod* m = record->StackElement(stack_frame)->Method();
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07004650 size_t class_name_index = class_names.IndexOf(m->GetDeclaringClassDescriptor());
4651 size_t method_name_index = method_names.IndexOf(m->GetName());
4652 size_t file_name_index = filenames.IndexOf(GetMethodSourceFile(m));
Mathieu Chartier46e811b2013-07-10 17:09:14 -07004653 JDWP::Append2BE(bytes, class_name_index);
4654 JDWP::Append2BE(bytes, method_name_index);
4655 JDWP::Append2BE(bytes, file_name_index);
Hiroshi Yamauchib5a9e3d2014-06-09 12:11:20 -07004656 JDWP::Append2BE(bytes, record->StackElement(stack_frame)->LineNumber());
Mathieu Chartier46e811b2013-07-10 17:09:14 -07004657 }
Ian Rogers719d1a32014-03-06 12:13:39 -08004658 idx = (idx + 1) & (alloc_record_max_ - 1);
Mathieu Chartier46e811b2013-07-10 17:09:14 -07004659 }
4660
4661 // (xb) class name strings
4662 // (xb) method name strings
4663 // (xb) source file strings
4664 JDWP::Set4BE(&bytes[string_table_offset], bytes.size());
4665 class_names.WriteTo(bytes);
4666 method_names.WriteTo(bytes);
4667 filenames.WriteTo(bytes);
Elliott Hughes545a0642011-11-08 19:10:03 -08004668 }
Ian Rogers50b35e22012-10-04 10:09:15 -07004669 JNIEnv* env = self->GetJniEnv();
Elliott Hughes545a0642011-11-08 19:10:03 -08004670 jbyteArray result = env->NewByteArray(bytes.size());
Ian Rogersc0542af2014-09-03 16:16:56 -07004671 if (result != nullptr) {
Elliott Hughes545a0642011-11-08 19:10:03 -08004672 env->SetByteArrayRegion(result, 0, bytes.size(), reinterpret_cast<const jbyte*>(&bytes[0]));
4673 }
4674 return result;
4675}
4676
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07004677mirror::ArtMethod* DeoptimizationRequest::Method() const {
4678 ScopedObjectAccessUnchecked soa(Thread::Current());
4679 return soa.DecodeMethod(method_);
4680}
4681
4682void DeoptimizationRequest::SetMethod(mirror::ArtMethod* m) {
4683 ScopedObjectAccessUnchecked soa(Thread::Current());
4684 method_ = soa.EncodeMethod(m);
4685}
4686
Elliott Hughes872d4ec2011-10-21 17:07:15 -07004687} // namespace art