blob: fe1e3a4aa52d5e4c375e68cb9949d5b2fccea78b [file] [log] [blame]
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001/*
2 * Copyright (C) 2008 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17#include "debugger.h"
18
Elliott Hughes3bb81562011-10-21 18:52:59 -070019#include <sys/uio.h>
20
Elliott Hughes545a0642011-11-08 19:10:03 -080021#include <set>
22
Ian Rogers166db042013-07-26 12:05:57 -070023#include "arch/context.h"
Elliott Hughes545a0642011-11-08 19:10:03 -080024#include "class_linker.h"
Ian Rogers2dd0e2c2013-01-24 12:42:14 -080025#include "class_linker-inl.h"
Ian Rogers4f6ad8a2013-03-18 15:27:28 -070026#include "dex_file-inl.h"
Ian Rogers776ac1f2012-04-13 23:36:36 -070027#include "dex_instruction.h"
Ian Rogers1d54e732013-05-02 21:10:01 -070028#include "gc/accounting/card_table-inl.h"
29#include "gc/space/large_object_space.h"
30#include "gc/space/space-inl.h"
Mathieu Chartiereb8167a2014-05-07 15:43:14 -070031#include "handle_scope.h"
Elliott Hughes64f574f2013-02-20 14:57:12 -080032#include "jdwp/object_registry.h"
Brian Carlstromea46f952013-07-30 01:26:50 -070033#include "mirror/art_field-inl.h"
34#include "mirror/art_method-inl.h"
Ian Rogers2dd0e2c2013-01-24 12:42:14 -080035#include "mirror/class.h"
36#include "mirror/class-inl.h"
37#include "mirror/class_loader.h"
Ian Rogers2dd0e2c2013-01-24 12:42:14 -080038#include "mirror/object-inl.h"
39#include "mirror/object_array-inl.h"
Ian Rogersb0fa5dc2014-04-28 16:47:08 -070040#include "mirror/string-inl.h"
Ian Rogers2dd0e2c2013-01-24 12:42:14 -080041#include "mirror/throwable.h"
Sebastien Hertza76a6d42014-03-20 16:40:17 +010042#include "quick/inline_method_analyser.h"
Ian Rogers53b8b092014-03-13 23:45:53 -070043#include "reflection.h"
Elliott Hughesa0e18062012-04-13 15:59:59 -070044#include "safe_map.h"
Elliott Hughes64f574f2013-02-20 14:57:12 -080045#include "scoped_thread_state_change.h"
Elliott Hughes6a5bd492011-10-28 14:33:57 -070046#include "ScopedLocalRef.h"
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -070047#include "ScopedPrimitiveArray.h"
Mathieu Chartiereb8167a2014-05-07 15:43:14 -070048#include "handle_scope-inl.h"
Elliott Hughes475fc232011-10-25 15:00:35 -070049#include "thread_list.h"
Ian Rogers62d6c772013-02-27 08:32:07 -080050#include "throw_location.h"
Ian Rogers2dd0e2c2013-01-24 12:42:14 -080051#include "utf.h"
Sebastien Hertza76a6d42014-03-20 16:40:17 +010052#include "verifier/method_verifier-inl.h"
Elliott Hugheseac76672012-05-24 21:56:51 -070053#include "well_known_classes.h"
Elliott Hughes475fc232011-10-25 15:00:35 -070054
Brian Carlstrom3d92d522013-07-12 09:03:08 -070055#ifdef HAVE_ANDROID_OS
56#include "cutils/properties.h"
57#endif
58
Elliott Hughes872d4ec2011-10-21 17:07:15 -070059namespace art {
60
Brian Carlstrom7934ac22013-07-26 10:54:15 -070061static const size_t kMaxAllocRecordStackDepth = 16; // Max 255.
Brian Carlstrom306db812014-09-05 13:01:41 -070062static const size_t kDefaultNumAllocRecords = 64*1024; // Must be a power of 2. 2BE can hold 64k-1.
63
64// Limit alloc_record_count to the 2BE value that is the limit of the current protocol.
65static uint16_t CappedAllocRecordCount(size_t alloc_record_count) {
66 if (alloc_record_count > 0xffff) {
67 return 0xffff;
68 }
69 return alloc_record_count;
70}
Elliott Hughes475fc232011-10-25 15:00:35 -070071
Hiroshi Yamauchib5a9e3d2014-06-09 12:11:20 -070072class AllocRecordStackTraceElement {
73 public:
74 AllocRecordStackTraceElement() : method_(nullptr), dex_pc_(0) {
Mathieu Chartier412c7fc2014-02-07 12:18:39 -080075 }
76
Hiroshi Yamauchib5a9e3d2014-06-09 12:11:20 -070077 int32_t LineNumber() SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
78 mirror::ArtMethod* method = Method();
79 DCHECK(method != nullptr);
80 return method->GetLineNumFromDexPC(DexPc());
Elliott Hughes545a0642011-11-08 19:10:03 -080081 }
Hiroshi Yamauchib5a9e3d2014-06-09 12:11:20 -070082
83 mirror::ArtMethod* Method() SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Mathieu Chartier4345c462014-06-27 10:20:14 -070084 ScopedObjectAccessUnchecked soa(Thread::Current());
85 return soa.DecodeMethod(method_);
Hiroshi Yamauchib5a9e3d2014-06-09 12:11:20 -070086 }
87
88 void SetMethod(mirror::ArtMethod* m) SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
89 ScopedObjectAccessUnchecked soa(Thread::Current());
Mathieu Chartier4345c462014-06-27 10:20:14 -070090 method_ = soa.EncodeMethod(m);
Hiroshi Yamauchib5a9e3d2014-06-09 12:11:20 -070091 }
92
93 uint32_t DexPc() const {
94 return dex_pc_;
95 }
96
97 void SetDexPc(uint32_t pc) {
98 dex_pc_ = pc;
99 }
100
101 private:
Mathieu Chartier4345c462014-06-27 10:20:14 -0700102 jmethodID method_;
Hiroshi Yamauchib5a9e3d2014-06-09 12:11:20 -0700103 uint32_t dex_pc_;
Elliott Hughes545a0642011-11-08 19:10:03 -0800104};
105
Mathieu Chartier4345c462014-06-27 10:20:14 -0700106jobject Dbg::TypeCache::Add(mirror::Class* t) {
107 ScopedObjectAccessUnchecked soa(Thread::Current());
108 int32_t hash_code = t->IdentityHashCode();
109 auto range = objects_.equal_range(hash_code);
110 for (auto it = range.first; it != range.second; ++it) {
111 if (soa.Decode<mirror::Class*>(it->second) == t) {
112 // Found a matching weak global, return it.
113 return it->second;
114 }
115 }
116 JNIEnv* env = soa.Env();
117 const jobject local_ref = soa.AddLocalReference<jobject>(t);
118 const jobject weak_global = env->NewWeakGlobalRef(local_ref);
119 env->DeleteLocalRef(local_ref);
120 objects_.insert(std::make_pair(hash_code, weak_global));
121 return weak_global;
122}
123
124void Dbg::TypeCache::Clear() {
Brian Carlstrom306db812014-09-05 13:01:41 -0700125 JavaVMExt* vm = Runtime::Current()->GetJavaVM();
126 Thread* self = Thread::Current();
Mathieu Chartier4345c462014-06-27 10:20:14 -0700127 for (const auto& p : objects_) {
Brian Carlstrom306db812014-09-05 13:01:41 -0700128 vm->DeleteWeakGlobalRef(self, p.second);
Mathieu Chartier4345c462014-06-27 10:20:14 -0700129 }
130 objects_.clear();
131}
132
Hiroshi Yamauchib5a9e3d2014-06-09 12:11:20 -0700133class AllocRecord {
134 public:
135 AllocRecord() : type_(nullptr), byte_count_(0), thin_lock_id_(0) {}
Elliott Hughes545a0642011-11-08 19:10:03 -0800136
Hiroshi Yamauchib5a9e3d2014-06-09 12:11:20 -0700137 mirror::Class* Type() SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Mathieu Chartier4345c462014-06-27 10:20:14 -0700138 return down_cast<mirror::Class*>(Thread::Current()->DecodeJObject(type_));
Hiroshi Yamauchib5a9e3d2014-06-09 12:11:20 -0700139 }
140
Brian Carlstrom306db812014-09-05 13:01:41 -0700141 void SetType(mirror::Class* t) SHARED_LOCKS_REQUIRED(Locks::mutator_lock_,
142 Locks::alloc_tracker_lock_) {
143 type_ = Dbg::type_cache_.Add(t);
Hiroshi Yamauchib5a9e3d2014-06-09 12:11:20 -0700144 }
145
146 size_t GetDepth() SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Elliott Hughes545a0642011-11-08 19:10:03 -0800147 size_t depth = 0;
Ian Rogersc0542af2014-09-03 16:16:56 -0700148 while (depth < kMaxAllocRecordStackDepth && stack_[depth].Method() != nullptr) {
Elliott Hughes545a0642011-11-08 19:10:03 -0800149 ++depth;
150 }
151 return depth;
152 }
Mathieu Chartier412c7fc2014-02-07 12:18:39 -0800153
Hiroshi Yamauchib5a9e3d2014-06-09 12:11:20 -0700154 size_t ByteCount() const {
155 return byte_count_;
Mathieu Chartier412c7fc2014-02-07 12:18:39 -0800156 }
Hiroshi Yamauchib5a9e3d2014-06-09 12:11:20 -0700157
158 void SetByteCount(size_t count) {
159 byte_count_ = count;
160 }
161
162 uint16_t ThinLockId() const {
163 return thin_lock_id_;
164 }
165
166 void SetThinLockId(uint16_t id) {
167 thin_lock_id_ = id;
168 }
169
170 AllocRecordStackTraceElement* StackElement(size_t index) {
171 DCHECK_LT(index, kMaxAllocRecordStackDepth);
172 return &stack_[index];
173 }
174
175 private:
176 jobject type_; // This is a weak global.
177 size_t byte_count_;
178 uint16_t thin_lock_id_;
Ian Rogersc0542af2014-09-03 16:16:56 -0700179 AllocRecordStackTraceElement stack_[kMaxAllocRecordStackDepth]; // Unused entries have nullptr method.
Elliott Hughes545a0642011-11-08 19:10:03 -0800180};
181
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -0700182class Breakpoint {
183 public:
Sebastien Hertzf3928792014-11-17 19:00:37 +0100184 Breakpoint(mirror::ArtMethod* method, uint32_t dex_pc,
185 DeoptimizationRequest::Kind deoptimization_kind)
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -0700186 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_)
Sebastien Hertzf3928792014-11-17 19:00:37 +0100187 : method_(nullptr), dex_pc_(dex_pc), deoptimization_kind_(deoptimization_kind) {
188 CHECK(deoptimization_kind_ == DeoptimizationRequest::kNothing ||
189 deoptimization_kind_ == DeoptimizationRequest::kSelectiveDeoptimization ||
190 deoptimization_kind_ == DeoptimizationRequest::kFullDeoptimization);
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -0700191 ScopedObjectAccessUnchecked soa(Thread::Current());
192 method_ = soa.EncodeMethod(method);
193 }
194
195 Breakpoint(const Breakpoint& other) SHARED_LOCKS_REQUIRED(Locks::mutator_lock_)
196 : method_(nullptr), dex_pc_(other.dex_pc_),
Sebastien Hertzf3928792014-11-17 19:00:37 +0100197 deoptimization_kind_(other.deoptimization_kind_) {
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -0700198 ScopedObjectAccessUnchecked soa(Thread::Current());
199 method_ = soa.EncodeMethod(other.Method());
200 }
201
202 mirror::ArtMethod* Method() const SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
203 ScopedObjectAccessUnchecked soa(Thread::Current());
204 return soa.DecodeMethod(method_);
205 }
206
207 uint32_t DexPc() const {
208 return dex_pc_;
209 }
210
Sebastien Hertzf3928792014-11-17 19:00:37 +0100211 DeoptimizationRequest::Kind GetDeoptimizationKind() const {
212 return deoptimization_kind_;
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -0700213 }
214
215 private:
Sebastien Hertza76a6d42014-03-20 16:40:17 +0100216 // The location of this breakpoint.
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -0700217 jmethodID method_;
218 uint32_t dex_pc_;
Sebastien Hertza76a6d42014-03-20 16:40:17 +0100219
220 // Indicates whether breakpoint needs full deoptimization or selective deoptimization.
Sebastien Hertzf3928792014-11-17 19:00:37 +0100221 DeoptimizationRequest::Kind deoptimization_kind_;
Elliott Hughes86964332012-02-15 19:37:42 -0800222};
223
Sebastien Hertzed2be172014-08-19 15:33:43 +0200224static std::ostream& operator<<(std::ostream& os, const Breakpoint& rhs)
Ian Rogersb726dcb2012-09-05 08:57:23 -0700225 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -0700226 os << StringPrintf("Breakpoint[%s @%#x]", PrettyMethod(rhs.Method()).c_str(), rhs.DexPc());
Elliott Hughes86964332012-02-15 19:37:42 -0800227 return os;
228}
229
Sebastien Hertz3f52eaf2014-04-04 17:50:18 +0200230class DebugInstrumentationListener FINAL : public instrumentation::InstrumentationListener {
Ian Rogers62d6c772013-02-27 08:32:07 -0800231 public:
232 DebugInstrumentationListener() {}
233 virtual ~DebugInstrumentationListener() {}
234
Sebastien Hertz3f52eaf2014-04-04 17:50:18 +0200235 void MethodEntered(Thread* thread, mirror::Object* this_object, mirror::ArtMethod* method,
Ian Rogers6a3c1fc2014-10-31 00:33:20 -0700236 uint32_t dex_pc ATTRIBUTE_UNUSED)
Sebastien Hertz3f52eaf2014-04-04 17:50:18 +0200237 OVERRIDE SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Ian Rogers62d6c772013-02-27 08:32:07 -0800238 if (method->IsNative()) {
239 // TODO: post location events is a suspension point and native method entry stubs aren't.
240 return;
241 }
Sebastien Hertz8379b222014-02-24 17:38:15 +0100242 Dbg::UpdateDebugger(thread, this_object, method, 0, Dbg::kMethodEntry, nullptr);
Ian Rogers62d6c772013-02-27 08:32:07 -0800243 }
244
Sebastien Hertz3f52eaf2014-04-04 17:50:18 +0200245 void MethodExited(Thread* thread, mirror::Object* this_object, mirror::ArtMethod* method,
246 uint32_t dex_pc, const JValue& return_value)
247 OVERRIDE SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Ian Rogers62d6c772013-02-27 08:32:07 -0800248 if (method->IsNative()) {
249 // TODO: post location events is a suspension point and native method entry stubs aren't.
250 return;
251 }
Sebastien Hertz8379b222014-02-24 17:38:15 +0100252 Dbg::UpdateDebugger(thread, this_object, method, dex_pc, Dbg::kMethodExit, &return_value);
Ian Rogers62d6c772013-02-27 08:32:07 -0800253 }
254
Sebastien Hertz3f52eaf2014-04-04 17:50:18 +0200255 void MethodUnwind(Thread* thread, mirror::Object* this_object, mirror::ArtMethod* method,
256 uint32_t dex_pc)
257 OVERRIDE SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Ian Rogers62d6c772013-02-27 08:32:07 -0800258 // We're not recorded to listen to this kind of event, so complain.
Ian Rogers6a3c1fc2014-10-31 00:33:20 -0700259 UNUSED(thread, this_object, method, dex_pc);
Ian Rogers62d6c772013-02-27 08:32:07 -0800260 LOG(ERROR) << "Unexpected method unwind event in debugger " << PrettyMethod(method)
Sebastien Hertz51db44a2013-11-19 10:00:29 +0100261 << " " << dex_pc;
Ian Rogers62d6c772013-02-27 08:32:07 -0800262 }
263
Sebastien Hertz3f52eaf2014-04-04 17:50:18 +0200264 void DexPcMoved(Thread* thread, mirror::Object* this_object, mirror::ArtMethod* method,
265 uint32_t new_dex_pc)
266 OVERRIDE SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Sebastien Hertz8379b222014-02-24 17:38:15 +0100267 Dbg::UpdateDebugger(thread, this_object, method, new_dex_pc, 0, nullptr);
Ian Rogers62d6c772013-02-27 08:32:07 -0800268 }
269
Sebastien Hertz3f52eaf2014-04-04 17:50:18 +0200270 void FieldRead(Thread* thread, mirror::Object* this_object, mirror::ArtMethod* method,
271 uint32_t dex_pc, mirror::ArtField* field)
272 OVERRIDE SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Ian Rogers6a3c1fc2014-10-31 00:33:20 -0700273 UNUSED(thread);
Sebastien Hertz3f52eaf2014-04-04 17:50:18 +0200274 Dbg::PostFieldAccessEvent(method, dex_pc, this_object, field);
Ian Rogers62d6c772013-02-27 08:32:07 -0800275 }
Sebastien Hertz3f52eaf2014-04-04 17:50:18 +0200276
Ian Rogers6a3c1fc2014-10-31 00:33:20 -0700277 void FieldWritten(Thread* thread ATTRIBUTE_UNUSED, mirror::Object* this_object,
278 mirror::ArtMethod* method, uint32_t dex_pc, mirror::ArtField* field,
279 const JValue& field_value)
Sebastien Hertz3f52eaf2014-04-04 17:50:18 +0200280 OVERRIDE SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
281 Dbg::PostFieldModificationEvent(method, dex_pc, this_object, field, &field_value);
282 }
283
Ian Rogers6a3c1fc2014-10-31 00:33:20 -0700284 void ExceptionCaught(Thread* thread ATTRIBUTE_UNUSED, const ThrowLocation& throw_location,
Sebastien Hertz3f52eaf2014-04-04 17:50:18 +0200285 mirror::ArtMethod* catch_method, uint32_t catch_dex_pc,
286 mirror::Throwable* exception_object)
287 OVERRIDE SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
288 Dbg::PostException(throw_location, catch_method, catch_dex_pc, exception_object);
289 }
290
291 private:
292 DISALLOW_COPY_AND_ASSIGN(DebugInstrumentationListener);
Ian Rogers62d6c772013-02-27 08:32:07 -0800293} gDebugInstrumentationListener;
294
Elliott Hughes4ffd3132011-10-24 12:06:42 -0700295// JDWP is allowed unless the Zygote forbids it.
296static bool gJdwpAllowed = true;
297
Elliott Hughesc0f09332012-03-26 13:27:06 -0700298// Was there a -Xrunjdwp or -agentlib:jdwp= argument on the command line?
Elliott Hughes3bb81562011-10-21 18:52:59 -0700299static bool gJdwpConfigured = false;
300
Elliott Hughesc0f09332012-03-26 13:27:06 -0700301// Broken-down JDWP options. (Only valid if IsJdwpConfigured() is true.)
Elliott Hughes376a7a02011-10-24 18:35:55 -0700302static JDWP::JdwpOptions gJdwpOptions;
Elliott Hughes3bb81562011-10-21 18:52:59 -0700303
304// Runtime JDWP state.
Ian Rogersc0542af2014-09-03 16:16:56 -0700305static JDWP::JdwpState* gJdwpState = nullptr;
Elliott Hughes3bb81562011-10-21 18:52:59 -0700306static bool gDebuggerConnected; // debugger or DDMS is connected.
307static bool gDebuggerActive; // debugger is making requests.
Elliott Hughes86964332012-02-15 19:37:42 -0800308static bool gDisposed; // debugger called VirtualMachine.Dispose, so we should drop the connection.
Elliott Hughes3bb81562011-10-21 18:52:59 -0700309
Elliott Hughes47fce012011-10-25 18:37:19 -0700310static bool gDdmThreadNotification = false;
311
Elliott Hughes767a1472011-10-26 18:49:02 -0700312// DDMS GC-related settings.
313static Dbg::HpifWhen gDdmHpifWhen = Dbg::HPIF_WHEN_NEVER;
314static Dbg::HpsgWhen gDdmHpsgWhen = Dbg::HPSG_WHEN_NEVER;
315static Dbg::HpsgWhat gDdmHpsgWhat;
316static Dbg::HpsgWhen gDdmNhsgWhen = Dbg::HPSG_WHEN_NEVER;
317static Dbg::HpsgWhat gDdmNhsgWhat;
318
Sebastien Hertz6995c602014-09-09 12:10:13 +0200319ObjectRegistry* Dbg::gRegistry = nullptr;
Elliott Hughes475fc232011-10-25 15:00:35 -0700320
Elliott Hughes545a0642011-11-08 19:10:03 -0800321// Recent allocation tracking.
Ian Rogers719d1a32014-03-06 12:13:39 -0800322AllocRecord* Dbg::recent_allocation_records_ = nullptr; // TODO: CircularBuffer<AllocRecord>
323size_t Dbg::alloc_record_max_ = 0;
324size_t Dbg::alloc_record_head_ = 0;
325size_t Dbg::alloc_record_count_ = 0;
Mathieu Chartier4345c462014-06-27 10:20:14 -0700326Dbg::TypeCache Dbg::type_cache_;
Elliott Hughes545a0642011-11-08 19:10:03 -0800327
Sebastien Hertz138dbfc2013-12-04 18:15:25 +0100328// Deoptimization support.
Sebastien Hertz4d25df32014-03-21 17:44:46 +0100329std::vector<DeoptimizationRequest> Dbg::deoptimization_requests_;
330size_t Dbg::full_deoptimization_event_count_ = 0;
Sebastien Hertz7ec2f1c2014-03-27 20:06:47 +0100331size_t Dbg::delayed_full_undeoptimization_count_ = 0;
Sebastien Hertz138dbfc2013-12-04 18:15:25 +0100332
Sebastien Hertz42cd43f2014-05-13 14:15:41 +0200333// Instrumentation event reference counters.
334size_t Dbg::dex_pc_change_event_ref_count_ = 0;
335size_t Dbg::method_enter_event_ref_count_ = 0;
336size_t Dbg::method_exit_event_ref_count_ = 0;
337size_t Dbg::field_read_event_ref_count_ = 0;
338size_t Dbg::field_write_event_ref_count_ = 0;
339size_t Dbg::exception_catch_event_ref_count_ = 0;
340uint32_t Dbg::instrumentation_events_ = 0;
341
Sebastien Hertz138dbfc2013-12-04 18:15:25 +0100342// Breakpoints.
jeffhao09bfc6a2012-12-11 18:11:43 -0800343static std::vector<Breakpoint> gBreakpoints GUARDED_BY(Locks::breakpoint_lock_);
Elliott Hughes86964332012-02-15 19:37:42 -0800344
Mathieu Chartier3b05e9b2014-03-25 09:29:43 -0700345void DebugInvokeReq::VisitRoots(RootCallback* callback, void* arg, uint32_t tid,
346 RootType root_type) {
347 if (receiver != nullptr) {
348 callback(&receiver, arg, tid, root_type);
349 }
350 if (thread != nullptr) {
351 callback(&thread, arg, tid, root_type);
352 }
353 if (klass != nullptr) {
354 callback(reinterpret_cast<mirror::Object**>(&klass), arg, tid, root_type);
355 }
356 if (method != nullptr) {
357 callback(reinterpret_cast<mirror::Object**>(&method), arg, tid, root_type);
358 }
359}
360
Sebastien Hertzbb43b432014-04-14 11:59:08 +0200361void DebugInvokeReq::Clear() {
362 invoke_needed = false;
363 receiver = nullptr;
364 thread = nullptr;
365 klass = nullptr;
366 method = nullptr;
367}
368
Mathieu Chartier3b05e9b2014-03-25 09:29:43 -0700369void SingleStepControl::VisitRoots(RootCallback* callback, void* arg, uint32_t tid,
370 RootType root_type) {
371 if (method != nullptr) {
372 callback(reinterpret_cast<mirror::Object**>(&method), arg, tid, root_type);
373 }
374}
375
Sebastien Hertzbb43b432014-04-14 11:59:08 +0200376bool SingleStepControl::ContainsDexPc(uint32_t dex_pc) const {
377 return dex_pcs.find(dex_pc) == dex_pcs.end();
378}
379
380void SingleStepControl::Clear() {
381 is_active = false;
382 method = nullptr;
383 dex_pcs.clear();
384}
385
Brian Carlstromea46f952013-07-30 01:26:50 -0700386static bool IsBreakpoint(const mirror::ArtMethod* m, uint32_t dex_pc)
jeffhao09bfc6a2012-12-11 18:11:43 -0800387 LOCKS_EXCLUDED(Locks::breakpoint_lock_)
Ian Rogersb726dcb2012-09-05 08:57:23 -0700388 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Sebastien Hertzed2be172014-08-19 15:33:43 +0200389 ReaderMutexLock mu(Thread::Current(), *Locks::breakpoint_lock_);
Sebastien Hertz138dbfc2013-12-04 18:15:25 +0100390 for (size_t i = 0, e = gBreakpoints.size(); i < e; ++i) {
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -0700391 if (gBreakpoints[i].DexPc() == dex_pc && gBreakpoints[i].Method() == m) {
Elliott Hughes86964332012-02-15 19:37:42 -0800392 VLOG(jdwp) << "Hit breakpoint #" << i << ": " << gBreakpoints[i];
393 return true;
394 }
395 }
396 return false;
397}
398
Sebastien Hertz52d131d2014-03-13 16:17:40 +0100399static bool IsSuspendedForDebugger(ScopedObjectAccessUnchecked& soa, Thread* thread)
400 LOCKS_EXCLUDED(Locks::thread_suspend_count_lock_) {
Elliott Hughes9e0c1752013-01-09 14:02:58 -0800401 MutexLock mu(soa.Self(), *Locks::thread_suspend_count_lock_);
402 // A thread may be suspended for GC; in this code, we really want to know whether
403 // there's a debugger suspension active.
404 return thread->IsSuspended() && thread->GetDebugSuspendCount() > 0;
405}
406
Ian Rogersc0542af2014-09-03 16:16:56 -0700407static mirror::Array* DecodeNonNullArray(JDWP::RefTypeId id, JDWP::JdwpError* error)
Ian Rogersb726dcb2012-09-05 08:57:23 -0700408 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Sebastien Hertz6995c602014-09-09 12:10:13 +0200409 mirror::Object* o = Dbg::GetObjectRegistry()->Get<mirror::Object*>(id, error);
Ian Rogersc0542af2014-09-03 16:16:56 -0700410 if (o == nullptr) {
411 *error = JDWP::ERR_INVALID_OBJECT;
412 return nullptr;
Elliott Hughes436e3722012-02-17 20:01:47 -0800413 }
414 if (!o->IsArrayInstance()) {
Ian Rogersc0542af2014-09-03 16:16:56 -0700415 *error = JDWP::ERR_INVALID_ARRAY;
416 return nullptr;
Elliott Hughes436e3722012-02-17 20:01:47 -0800417 }
Ian Rogersc0542af2014-09-03 16:16:56 -0700418 *error = JDWP::ERR_NONE;
Elliott Hughes436e3722012-02-17 20:01:47 -0800419 return o->AsArray();
420}
421
Ian Rogersc0542af2014-09-03 16:16:56 -0700422static mirror::Class* DecodeClass(JDWP::RefTypeId id, JDWP::JdwpError* error)
Ian Rogersb726dcb2012-09-05 08:57:23 -0700423 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Sebastien Hertz6995c602014-09-09 12:10:13 +0200424 mirror::Object* o = Dbg::GetObjectRegistry()->Get<mirror::Object*>(id, error);
Ian Rogersc0542af2014-09-03 16:16:56 -0700425 if (o == nullptr) {
426 *error = JDWP::ERR_INVALID_OBJECT;
427 return nullptr;
Elliott Hughes436e3722012-02-17 20:01:47 -0800428 }
429 if (!o->IsClass()) {
Ian Rogersc0542af2014-09-03 16:16:56 -0700430 *error = JDWP::ERR_INVALID_CLASS;
431 return nullptr;
Elliott Hughes436e3722012-02-17 20:01:47 -0800432 }
Ian Rogersc0542af2014-09-03 16:16:56 -0700433 *error = JDWP::ERR_NONE;
Elliott Hughes436e3722012-02-17 20:01:47 -0800434 return o->AsClass();
435}
436
Ian Rogersc0542af2014-09-03 16:16:56 -0700437static Thread* DecodeThread(ScopedObjectAccessUnchecked& soa, JDWP::ObjectId thread_id,
438 JDWP::JdwpError* error)
jeffhaoa77f0f62012-12-05 17:19:31 -0800439 EXCLUSIVE_LOCKS_REQUIRED(Locks::thread_list_lock_)
Ian Rogersb726dcb2012-09-05 08:57:23 -0700440 LOCKS_EXCLUDED(Locks::thread_suspend_count_lock_)
441 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Sebastien Hertz6995c602014-09-09 12:10:13 +0200442 mirror::Object* thread_peer = Dbg::GetObjectRegistry()->Get<mirror::Object*>(thread_id, error);
Ian Rogersc0542af2014-09-03 16:16:56 -0700443 if (thread_peer == nullptr) {
Elliott Hughes221229c2013-01-08 18:17:50 -0800444 // This isn't even an object.
Ian Rogersc0542af2014-09-03 16:16:56 -0700445 *error = JDWP::ERR_INVALID_OBJECT;
446 return nullptr;
Elliott Hughes436e3722012-02-17 20:01:47 -0800447 }
Elliott Hughes221229c2013-01-08 18:17:50 -0800448
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800449 mirror::Class* java_lang_Thread = soa.Decode<mirror::Class*>(WellKnownClasses::java_lang_Thread);
Elliott Hughes221229c2013-01-08 18:17:50 -0800450 if (!java_lang_Thread->IsAssignableFrom(thread_peer->GetClass())) {
451 // This isn't a thread.
Ian Rogersc0542af2014-09-03 16:16:56 -0700452 *error = JDWP::ERR_INVALID_THREAD;
453 return nullptr;
Elliott Hughes221229c2013-01-08 18:17:50 -0800454 }
455
Ian Rogersc0542af2014-09-03 16:16:56 -0700456 Thread* thread = Thread::FromManagedThread(soa, thread_peer);
457 // If thread is null then this a java.lang.Thread without a Thread*. Must be a un-started or a
458 // zombie.
459 *error = (thread == nullptr) ? JDWP::ERR_THREAD_NOT_ALIVE : JDWP::ERR_NONE;
460 return thread;
Elliott Hughes436e3722012-02-17 20:01:47 -0800461}
462
Elliott Hughes24437992011-11-30 14:49:33 -0800463static JDWP::JdwpTag BasicTagFromDescriptor(const char* descriptor) {
464 // JDWP deliberately uses the descriptor characters' ASCII values for its enum.
465 // Note that by "basic" we mean that we don't get more specific than JT_OBJECT.
466 return static_cast<JDWP::JdwpTag>(descriptor[0]);
467}
468
Ian Rogers1ff3c982014-08-12 02:30:58 -0700469static JDWP::JdwpTag BasicTagFromClass(mirror::Class* klass)
470 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
471 std::string temp;
472 const char* descriptor = klass->GetDescriptor(&temp);
473 return BasicTagFromDescriptor(descriptor);
474}
475
Ian Rogers98379392014-02-24 16:53:16 -0800476static JDWP::JdwpTag TagFromClass(const ScopedObjectAccessUnchecked& soa, mirror::Class* c)
Ian Rogersb726dcb2012-09-05 08:57:23 -0700477 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Ian Rogersc0542af2014-09-03 16:16:56 -0700478 CHECK(c != nullptr);
Elliott Hughes24437992011-11-30 14:49:33 -0800479 if (c->IsArrayClass()) {
480 return JDWP::JT_ARRAY;
481 }
Elliott Hughes24437992011-11-30 14:49:33 -0800482 if (c->IsStringClass()) {
483 return JDWP::JT_STRING;
Elliott Hughes24437992011-11-30 14:49:33 -0800484 }
Ian Rogers98379392014-02-24 16:53:16 -0800485 if (c->IsClassClass()) {
486 return JDWP::JT_CLASS_OBJECT;
487 }
488 {
489 mirror::Class* thread_class = soa.Decode<mirror::Class*>(WellKnownClasses::java_lang_Thread);
490 if (thread_class->IsAssignableFrom(c)) {
491 return JDWP::JT_THREAD;
492 }
493 }
494 {
495 mirror::Class* thread_group_class =
496 soa.Decode<mirror::Class*>(WellKnownClasses::java_lang_ThreadGroup);
497 if (thread_group_class->IsAssignableFrom(c)) {
498 return JDWP::JT_THREAD_GROUP;
499 }
500 }
501 {
502 mirror::Class* class_loader_class =
503 soa.Decode<mirror::Class*>(WellKnownClasses::java_lang_ClassLoader);
504 if (class_loader_class->IsAssignableFrom(c)) {
505 return JDWP::JT_CLASS_LOADER;
506 }
507 }
508 return JDWP::JT_OBJECT;
Elliott Hughes24437992011-11-30 14:49:33 -0800509}
510
511/*
512 * Objects declared to hold Object might actually hold a more specific
513 * type. The debugger may take a special interest in these (e.g. it
514 * wants to display the contents of Strings), so we want to return an
515 * appropriate tag.
516 *
517 * Null objects are tagged JT_OBJECT.
518 */
Sebastien Hertz6995c602014-09-09 12:10:13 +0200519JDWP::JdwpTag Dbg::TagFromObject(const ScopedObjectAccessUnchecked& soa, mirror::Object* o) {
Ian Rogersc0542af2014-09-03 16:16:56 -0700520 return (o == nullptr) ? JDWP::JT_OBJECT : TagFromClass(soa, o->GetClass());
Elliott Hughes24437992011-11-30 14:49:33 -0800521}
522
523static bool IsPrimitiveTag(JDWP::JdwpTag tag) {
524 switch (tag) {
525 case JDWP::JT_BOOLEAN:
526 case JDWP::JT_BYTE:
527 case JDWP::JT_CHAR:
528 case JDWP::JT_FLOAT:
529 case JDWP::JT_DOUBLE:
530 case JDWP::JT_INT:
531 case JDWP::JT_LONG:
532 case JDWP::JT_SHORT:
533 case JDWP::JT_VOID:
534 return true;
535 default:
536 return false;
537 }
538}
539
Elliott Hughes3bb81562011-10-21 18:52:59 -0700540/*
541 * Handle one of the JDWP name/value pairs.
542 *
543 * JDWP options are:
544 * help: if specified, show help message and bail
545 * transport: may be dt_socket or dt_shmem
546 * address: for dt_socket, "host:port", or just "port" when listening
547 * server: if "y", wait for debugger to attach; if "n", attach to debugger
548 * timeout: how long to wait for debugger to connect / listen
549 *
550 * Useful with server=n (these aren't supported yet):
551 * onthrow=<exception-name>: connect to debugger when exception thrown
552 * onuncaught=y|n: connect to debugger when uncaught exception thrown
553 * launch=<command-line>: launch the debugger itself
554 *
555 * The "transport" option is required, as is "address" if server=n.
556 */
557static bool ParseJdwpOption(const std::string& name, const std::string& value) {
558 if (name == "transport") {
559 if (value == "dt_socket") {
Elliott Hughes376a7a02011-10-24 18:35:55 -0700560 gJdwpOptions.transport = JDWP::kJdwpTransportSocket;
Elliott Hughes3bb81562011-10-21 18:52:59 -0700561 } else if (value == "dt_android_adb") {
Elliott Hughes376a7a02011-10-24 18:35:55 -0700562 gJdwpOptions.transport = JDWP::kJdwpTransportAndroidAdb;
Elliott Hughes3bb81562011-10-21 18:52:59 -0700563 } else {
564 LOG(ERROR) << "JDWP transport not supported: " << value;
565 return false;
566 }
567 } else if (name == "server") {
568 if (value == "n") {
Elliott Hughes376a7a02011-10-24 18:35:55 -0700569 gJdwpOptions.server = false;
Elliott Hughes3bb81562011-10-21 18:52:59 -0700570 } else if (value == "y") {
Elliott Hughes376a7a02011-10-24 18:35:55 -0700571 gJdwpOptions.server = true;
Elliott Hughes3bb81562011-10-21 18:52:59 -0700572 } else {
573 LOG(ERROR) << "JDWP option 'server' must be 'y' or 'n'";
574 return false;
575 }
576 } else if (name == "suspend") {
577 if (value == "n") {
Elliott Hughes376a7a02011-10-24 18:35:55 -0700578 gJdwpOptions.suspend = false;
Elliott Hughes3bb81562011-10-21 18:52:59 -0700579 } else if (value == "y") {
Elliott Hughes376a7a02011-10-24 18:35:55 -0700580 gJdwpOptions.suspend = true;
Elliott Hughes3bb81562011-10-21 18:52:59 -0700581 } else {
582 LOG(ERROR) << "JDWP option 'suspend' must be 'y' or 'n'";
583 return false;
584 }
585 } else if (name == "address") {
586 /* this is either <port> or <host>:<port> */
587 std::string port_string;
Elliott Hughes376a7a02011-10-24 18:35:55 -0700588 gJdwpOptions.host.clear();
Elliott Hughes3bb81562011-10-21 18:52:59 -0700589 std::string::size_type colon = value.find(':');
590 if (colon != std::string::npos) {
Elliott Hughes376a7a02011-10-24 18:35:55 -0700591 gJdwpOptions.host = value.substr(0, colon);
Elliott Hughes3bb81562011-10-21 18:52:59 -0700592 port_string = value.substr(colon + 1);
593 } else {
594 port_string = value;
595 }
596 if (port_string.empty()) {
597 LOG(ERROR) << "JDWP address missing port: " << value;
598 return false;
599 }
600 char* end;
Elliott Hughesba8eee12012-01-24 20:25:24 -0800601 uint64_t port = strtoul(port_string.c_str(), &end, 10);
602 if (*end != '\0' || port > 0xffff) {
Elliott Hughes3bb81562011-10-21 18:52:59 -0700603 LOG(ERROR) << "JDWP address has junk in port field: " << value;
604 return false;
605 }
Elliott Hughes376a7a02011-10-24 18:35:55 -0700606 gJdwpOptions.port = port;
Elliott Hughes3bb81562011-10-21 18:52:59 -0700607 } else if (name == "launch" || name == "onthrow" || name == "oncaught" || name == "timeout") {
608 /* valid but unsupported */
609 LOG(INFO) << "Ignoring JDWP option '" << name << "'='" << value << "'";
610 } else {
611 LOG(INFO) << "Ignoring unrecognized JDWP option '" << name << "'='" << value << "'";
612 }
613
614 return true;
615}
616
617/*
618 * Parse the latter half of a -Xrunjdwp/-agentlib:jdwp= string, e.g.:
619 * "transport=dt_socket,address=8000,server=y,suspend=n"
620 */
621bool Dbg::ParseJdwpOptions(const std::string& options) {
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -0800622 VLOG(jdwp) << "ParseJdwpOptions: " << options;
Elliott Hughes47fce012011-10-25 18:37:19 -0700623
Elliott Hughes3bb81562011-10-21 18:52:59 -0700624 std::vector<std::string> pairs;
Ian Rogers6f3dbba2014-10-14 17:41:57 -0700625 Split(options, ',', &pairs);
Elliott Hughes3bb81562011-10-21 18:52:59 -0700626
627 for (size_t i = 0; i < pairs.size(); ++i) {
628 std::string::size_type equals = pairs[i].find('=');
629 if (equals == std::string::npos) {
630 LOG(ERROR) << "Can't parse JDWP option '" << pairs[i] << "' in '" << options << "'";
631 return false;
632 }
633 ParseJdwpOption(pairs[i].substr(0, equals), pairs[i].substr(equals + 1));
634 }
635
Elliott Hughes376a7a02011-10-24 18:35:55 -0700636 if (gJdwpOptions.transport == JDWP::kJdwpTransportUnknown) {
Elliott Hughes3bb81562011-10-21 18:52:59 -0700637 LOG(ERROR) << "Must specify JDWP transport: " << options;
638 }
Elliott Hughes376a7a02011-10-24 18:35:55 -0700639 if (!gJdwpOptions.server && (gJdwpOptions.host.empty() || gJdwpOptions.port == 0)) {
Elliott Hughes3bb81562011-10-21 18:52:59 -0700640 LOG(ERROR) << "Must specify JDWP host and port when server=n: " << options;
641 return false;
642 }
643
644 gJdwpConfigured = true;
645 return true;
646}
647
Elliott Hughesd1cc8362011-10-24 16:58:50 -0700648void Dbg::StartJdwp() {
Elliott Hughesc0f09332012-03-26 13:27:06 -0700649 if (!gJdwpAllowed || !IsJdwpConfigured()) {
Elliott Hughes376a7a02011-10-24 18:35:55 -0700650 // No JDWP for you!
651 return;
652 }
653
Ian Rogers719d1a32014-03-06 12:13:39 -0800654 CHECK(gRegistry == nullptr);
Elliott Hughes475fc232011-10-25 15:00:35 -0700655 gRegistry = new ObjectRegistry;
656
Elliott Hughesd1cc8362011-10-24 16:58:50 -0700657 // Init JDWP if the debugger is enabled. This may connect out to a
658 // debugger, passively listen for a debugger, or block waiting for a
659 // debugger.
Elliott Hughes376a7a02011-10-24 18:35:55 -0700660 gJdwpState = JDWP::JdwpState::Create(&gJdwpOptions);
Ian Rogersc0542af2014-09-03 16:16:56 -0700661 if (gJdwpState == nullptr) {
Elliott Hughesf8a2df72011-12-01 12:19:54 -0800662 // We probably failed because some other process has the port already, which means that
663 // if we don't abort the user is likely to think they're talking to us when they're actually
664 // talking to that other process.
Elliott Hughes3d30d9b2011-12-07 17:35:48 -0800665 LOG(FATAL) << "Debugger thread failed to initialize";
Elliott Hughesd1cc8362011-10-24 16:58:50 -0700666 }
667
668 // If a debugger has already attached, send the "welcome" message.
669 // This may cause us to suspend all threads.
Elliott Hughes376a7a02011-10-24 18:35:55 -0700670 if (gJdwpState->IsActive()) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700671 ScopedObjectAccess soa(Thread::Current());
Sebastien Hertz7d955652014-10-22 10:57:10 +0200672 gJdwpState->PostVMStart();
Elliott Hughesd1cc8362011-10-24 16:58:50 -0700673 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700674}
675
Elliott Hughesd1cc8362011-10-24 16:58:50 -0700676void Dbg::StopJdwp() {
Sebastien Hertzc6345ef2014-08-18 19:26:39 +0200677 // Post VM_DEATH event before the JDWP connection is closed (either by the JDWP thread or the
678 // destruction of gJdwpState).
679 if (gJdwpState != nullptr && gJdwpState->IsActive()) {
680 gJdwpState->PostVMDeath();
681 }
Sebastien Hertz0376e6b2014-02-06 18:12:59 +0100682 // Prevent the JDWP thread from processing JDWP incoming packets after we close the connection.
683 Disposed();
Elliott Hughes376a7a02011-10-24 18:35:55 -0700684 delete gJdwpState;
Ian Rogers719d1a32014-03-06 12:13:39 -0800685 gJdwpState = nullptr;
Elliott Hughes475fc232011-10-25 15:00:35 -0700686 delete gRegistry;
Ian Rogers719d1a32014-03-06 12:13:39 -0800687 gRegistry = nullptr;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700688}
689
Elliott Hughes767a1472011-10-26 18:49:02 -0700690void Dbg::GcDidFinish() {
691 if (gDdmHpifWhen != HPIF_WHEN_NEVER) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700692 ScopedObjectAccess soa(Thread::Current());
Brian Carlstrom4d466a82014-05-08 19:05:29 -0700693 VLOG(jdwp) << "Sending heap info to DDM";
Elliott Hughes7162ad92011-10-27 14:08:42 -0700694 DdmSendHeapInfo(gDdmHpifWhen);
Elliott Hughes767a1472011-10-26 18:49:02 -0700695 }
696 if (gDdmHpsgWhen != HPSG_WHEN_NEVER) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700697 ScopedObjectAccess soa(Thread::Current());
Brian Carlstrom4d466a82014-05-08 19:05:29 -0700698 VLOG(jdwp) << "Dumping heap to DDM";
Elliott Hughes6a5bd492011-10-28 14:33:57 -0700699 DdmSendHeapSegments(false);
Elliott Hughes767a1472011-10-26 18:49:02 -0700700 }
701 if (gDdmNhsgWhen != HPSG_WHEN_NEVER) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700702 ScopedObjectAccess soa(Thread::Current());
Brian Carlstrom4d466a82014-05-08 19:05:29 -0700703 VLOG(jdwp) << "Dumping native heap to DDM";
Elliott Hughes6a5bd492011-10-28 14:33:57 -0700704 DdmSendHeapSegments(true);
Elliott Hughes767a1472011-10-26 18:49:02 -0700705 }
706}
707
Elliott Hughes4ffd3132011-10-24 12:06:42 -0700708void Dbg::SetJdwpAllowed(bool allowed) {
709 gJdwpAllowed = allowed;
710}
711
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700712DebugInvokeReq* Dbg::GetInvokeReq() {
Elliott Hughes475fc232011-10-25 15:00:35 -0700713 return Thread::Current()->GetInvokeReq();
714}
715
716Thread* Dbg::GetDebugThread() {
Ian Rogersc0542af2014-09-03 16:16:56 -0700717 return (gJdwpState != nullptr) ? gJdwpState->GetDebugThread() : nullptr;
Elliott Hughes475fc232011-10-25 15:00:35 -0700718}
719
720void Dbg::ClearWaitForEventThread() {
721 gJdwpState->ClearWaitForEventThread();
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700722}
723
724void Dbg::Connected() {
Elliott Hughes3bb81562011-10-21 18:52:59 -0700725 CHECK(!gDebuggerConnected);
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -0800726 VLOG(jdwp) << "JDWP has attached";
Elliott Hughes3bb81562011-10-21 18:52:59 -0700727 gDebuggerConnected = true;
Elliott Hughes86964332012-02-15 19:37:42 -0800728 gDisposed = false;
729}
730
731void Dbg::Disposed() {
732 gDisposed = true;
733}
734
735bool Dbg::IsDisposed() {
736 return gDisposed;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700737}
738
Sebastien Hertzf3928792014-11-17 19:00:37 +0100739bool Dbg::RequiresDeoptimization() {
740 // We don't need deoptimization if everything runs with interpreter after
741 // enabling -Xint mode.
742 return !Runtime::Current()->GetInstrumentation()->IsForcedInterpretOnly();
743}
744
Elliott Hughesa2155262011-11-16 16:26:58 -0800745void Dbg::GoActive() {
746 // Enable all debugging features, including scans for breakpoints.
747 // This is a no-op if we're already active.
748 // Only called from the JDWP handler thread.
749 if (gDebuggerActive) {
750 return;
751 }
752
Elliott Hughesc0f09332012-03-26 13:27:06 -0700753 {
754 // TODO: dalvik only warned if there were breakpoints left over. clear in Dbg::Disconnected?
Sebastien Hertzed2be172014-08-19 15:33:43 +0200755 ReaderMutexLock mu(Thread::Current(), *Locks::breakpoint_lock_);
Elliott Hughesc0f09332012-03-26 13:27:06 -0700756 CHECK_EQ(gBreakpoints.size(), 0U);
757 }
Elliott Hughesa2155262011-11-16 16:26:58 -0800758
Sebastien Hertz138dbfc2013-12-04 18:15:25 +0100759 {
Brian Carlstrom306db812014-09-05 13:01:41 -0700760 MutexLock mu(Thread::Current(), *Locks::deoptimization_lock_);
Sebastien Hertz4d25df32014-03-21 17:44:46 +0100761 CHECK_EQ(deoptimization_requests_.size(), 0U);
762 CHECK_EQ(full_deoptimization_event_count_, 0U);
Sebastien Hertz7ec2f1c2014-03-27 20:06:47 +0100763 CHECK_EQ(delayed_full_undeoptimization_count_, 0U);
Sebastien Hertz42cd43f2014-05-13 14:15:41 +0200764 CHECK_EQ(dex_pc_change_event_ref_count_, 0U);
765 CHECK_EQ(method_enter_event_ref_count_, 0U);
766 CHECK_EQ(method_exit_event_ref_count_, 0U);
767 CHECK_EQ(field_read_event_ref_count_, 0U);
768 CHECK_EQ(field_write_event_ref_count_, 0U);
769 CHECK_EQ(exception_catch_event_ref_count_, 0U);
Sebastien Hertz138dbfc2013-12-04 18:15:25 +0100770 }
771
Ian Rogers62d6c772013-02-27 08:32:07 -0800772 Runtime* runtime = Runtime::Current();
773 runtime->GetThreadList()->SuspendAll();
774 Thread* self = Thread::Current();
775 ThreadState old_state = self->SetStateUnsafe(kRunnable);
776 CHECK_NE(old_state, kRunnable);
Sebastien Hertzf3928792014-11-17 19:00:37 +0100777 if (RequiresDeoptimization()) {
778 runtime->GetInstrumentation()->EnableDeoptimization();
779 }
Sebastien Hertz42cd43f2014-05-13 14:15:41 +0200780 instrumentation_events_ = 0;
Elliott Hughesa2155262011-11-16 16:26:58 -0800781 gDebuggerActive = true;
Ian Rogers62d6c772013-02-27 08:32:07 -0800782 CHECK_EQ(self->SetStateUnsafe(old_state), kRunnable);
783 runtime->GetThreadList()->ResumeAll();
784
785 LOG(INFO) << "Debugger is active";
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700786}
787
788void Dbg::Disconnected() {
Elliott Hughes234ab152011-10-26 14:02:26 -0700789 CHECK(gDebuggerConnected);
790
Elliott Hughesc0f09332012-03-26 13:27:06 -0700791 LOG(INFO) << "Debugger is no longer active";
Elliott Hughes234ab152011-10-26 14:02:26 -0700792
Ian Rogers62d6c772013-02-27 08:32:07 -0800793 // Suspend all threads and exclusively acquire the mutator lock. Set the state of the thread
794 // to kRunnable to avoid scoped object access transitions. Remove the debugger as a listener
795 // and clear the object registry.
796 Runtime* runtime = Runtime::Current();
797 runtime->GetThreadList()->SuspendAll();
798 Thread* self = Thread::Current();
799 ThreadState old_state = self->SetStateUnsafe(kRunnable);
Sebastien Hertzaaea7342014-02-25 15:10:04 +0100800
801 // Debugger may not be active at this point.
802 if (gDebuggerActive) {
803 {
804 // Since we're going to disable deoptimization, we clear the deoptimization requests queue.
805 // This prevents us from having any pending deoptimization request when the debugger attaches
806 // to us again while no event has been requested yet.
Brian Carlstrom306db812014-09-05 13:01:41 -0700807 MutexLock mu(Thread::Current(), *Locks::deoptimization_lock_);
Sebastien Hertz4d25df32014-03-21 17:44:46 +0100808 deoptimization_requests_.clear();
809 full_deoptimization_event_count_ = 0U;
Sebastien Hertz7ec2f1c2014-03-27 20:06:47 +0100810 delayed_full_undeoptimization_count_ = 0U;
Sebastien Hertzaaea7342014-02-25 15:10:04 +0100811 }
Sebastien Hertz42cd43f2014-05-13 14:15:41 +0200812 if (instrumentation_events_ != 0) {
813 runtime->GetInstrumentation()->RemoveListener(&gDebugInstrumentationListener,
814 instrumentation_events_);
815 instrumentation_events_ = 0;
816 }
Sebastien Hertzf3928792014-11-17 19:00:37 +0100817 if (RequiresDeoptimization()) {
818 runtime->GetInstrumentation()->DisableDeoptimization();
819 }
Sebastien Hertzaaea7342014-02-25 15:10:04 +0100820 gDebuggerActive = false;
Sebastien Hertz138dbfc2013-12-04 18:15:25 +0100821 }
Elliott Hughes234ab152011-10-26 14:02:26 -0700822 gRegistry->Clear();
823 gDebuggerConnected = false;
Ian Rogers62d6c772013-02-27 08:32:07 -0800824 CHECK_EQ(self->SetStateUnsafe(old_state), kRunnable);
825 runtime->GetThreadList()->ResumeAll();
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700826}
827
Elliott Hughesc0f09332012-03-26 13:27:06 -0700828bool Dbg::IsDebuggerActive() {
Elliott Hughes3bb81562011-10-21 18:52:59 -0700829 return gDebuggerActive;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700830}
831
Elliott Hughesc0f09332012-03-26 13:27:06 -0700832bool Dbg::IsJdwpConfigured() {
Elliott Hughes3bb81562011-10-21 18:52:59 -0700833 return gJdwpConfigured;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700834}
835
836int64_t Dbg::LastDebuggerActivity() {
Elliott Hughesca951522011-12-05 12:01:32 -0800837 return gJdwpState->LastDebuggerActivity();
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700838}
839
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700840void Dbg::UndoDebuggerSuspensions() {
Elliott Hughes234ab152011-10-26 14:02:26 -0700841 Runtime::Current()->GetThreadList()->UndoDebuggerSuspensions();
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700842}
843
Elliott Hughes88d63092013-01-09 09:55:54 -0800844std::string Dbg::GetClassName(JDWP::RefTypeId class_id) {
Ian Rogersc0542af2014-09-03 16:16:56 -0700845 JDWP::JdwpError error;
846 mirror::Object* o = gRegistry->Get<mirror::Object*>(class_id, &error);
847 if (o == nullptr) {
848 if (error == JDWP::ERR_NONE) {
849 return "NULL";
850 } else {
851 return StringPrintf("invalid object %p", reinterpret_cast<void*>(class_id));
852 }
Elliott Hughes436e3722012-02-17 20:01:47 -0800853 }
854 if (!o->IsClass()) {
Brian Carlstrom7934ac22013-07-26 10:54:15 -0700855 return StringPrintf("non-class %p", o); // This is only used for debugging output anyway.
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -0800856 }
Sebastien Hertz6995c602014-09-09 12:10:13 +0200857 return GetClassName(o->AsClass());
858}
859
860std::string Dbg::GetClassName(mirror::Class* klass) {
Sebastien Hertza9aa0ff2014-09-19 12:07:51 +0200861 if (klass == nullptr) {
862 return "NULL";
863 }
Ian Rogers1ff3c982014-08-12 02:30:58 -0700864 std::string temp;
Sebastien Hertz6995c602014-09-09 12:10:13 +0200865 return DescriptorToName(klass->GetDescriptor(&temp));
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700866}
867
Ian Rogersc0542af2014-09-03 16:16:56 -0700868JDWP::JdwpError Dbg::GetClassObject(JDWP::RefTypeId id, JDWP::ObjectId* class_object_id) {
Elliott Hughes436e3722012-02-17 20:01:47 -0800869 JDWP::JdwpError status;
Ian Rogersc0542af2014-09-03 16:16:56 -0700870 mirror::Class* c = DecodeClass(id, &status);
871 if (c == nullptr) {
872 *class_object_id = 0;
Elliott Hughes436e3722012-02-17 20:01:47 -0800873 return status;
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -0800874 }
Ian Rogersc0542af2014-09-03 16:16:56 -0700875 *class_object_id = gRegistry->Add(c);
Elliott Hughes436e3722012-02-17 20:01:47 -0800876 return JDWP::ERR_NONE;
Elliott Hughes86964332012-02-15 19:37:42 -0800877}
878
Ian Rogersc0542af2014-09-03 16:16:56 -0700879JDWP::JdwpError Dbg::GetSuperclass(JDWP::RefTypeId id, JDWP::RefTypeId* superclass_id) {
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -0800880 JDWP::JdwpError status;
Ian Rogersc0542af2014-09-03 16:16:56 -0700881 mirror::Class* c = DecodeClass(id, &status);
882 if (c == nullptr) {
883 *superclass_id = 0;
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -0800884 return status;
885 }
886 if (c->IsInterface()) {
887 // http://code.google.com/p/android/issues/detail?id=20856
Ian Rogersc0542af2014-09-03 16:16:56 -0700888 *superclass_id = 0;
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -0800889 } else {
Ian Rogersc0542af2014-09-03 16:16:56 -0700890 *superclass_id = gRegistry->Add(c->GetSuperClass());
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -0800891 }
892 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700893}
894
Elliott Hughes436e3722012-02-17 20:01:47 -0800895JDWP::JdwpError Dbg::GetClassLoader(JDWP::RefTypeId id, JDWP::ExpandBuf* pReply) {
Ian Rogersc0542af2014-09-03 16:16:56 -0700896 JDWP::JdwpError error;
897 mirror::Object* o = gRegistry->Get<mirror::Object*>(id, &error);
898 if (o == nullptr) {
Elliott Hughes436e3722012-02-17 20:01:47 -0800899 return JDWP::ERR_INVALID_OBJECT;
900 }
901 expandBufAddObjectId(pReply, gRegistry->Add(o->GetClass()->GetClassLoader()));
902 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700903}
904
Elliott Hughes436e3722012-02-17 20:01:47 -0800905JDWP::JdwpError Dbg::GetModifiers(JDWP::RefTypeId id, JDWP::ExpandBuf* pReply) {
Ian Rogersc0542af2014-09-03 16:16:56 -0700906 JDWP::JdwpError error;
907 mirror::Class* c = DecodeClass(id, &error);
908 if (c == nullptr) {
909 return error;
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -0800910 }
Elliott Hughes436e3722012-02-17 20:01:47 -0800911
912 uint32_t access_flags = c->GetAccessFlags() & kAccJavaFlagsMask;
913
Yevgeny Roubande34eea2014-02-15 01:06:03 +0700914 // Set ACC_SUPER. Dex files don't contain this flag but only classes are supposed to have it set,
915 // not interfaces.
Elliott Hughes436e3722012-02-17 20:01:47 -0800916 // Class.getModifiers doesn't return it, but JDWP does, so we set it here.
Yevgeny Roubande34eea2014-02-15 01:06:03 +0700917 if ((access_flags & kAccInterface) == 0) {
918 access_flags |= kAccSuper;
919 }
Elliott Hughes436e3722012-02-17 20:01:47 -0800920
921 expandBufAdd4BE(pReply, access_flags);
922
923 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700924}
925
Ian Rogersc0542af2014-09-03 16:16:56 -0700926JDWP::JdwpError Dbg::GetMonitorInfo(JDWP::ObjectId object_id, JDWP::ExpandBuf* reply) {
927 JDWP::JdwpError error;
928 mirror::Object* o = gRegistry->Get<mirror::Object*>(object_id, &error);
929 if (o == nullptr) {
Elliott Hughesf327e072013-01-09 16:01:26 -0800930 return JDWP::ERR_INVALID_OBJECT;
931 }
932
933 // Ensure all threads are suspended while we read objects' lock words.
934 Thread* self = Thread::Current();
Sebastien Hertz54263242014-03-19 18:16:50 +0100935 CHECK_EQ(self->GetState(), kRunnable);
936 self->TransitionFromRunnableToSuspended(kSuspended);
937 Runtime::Current()->GetThreadList()->SuspendAll();
Elliott Hughesf327e072013-01-09 16:01:26 -0800938
939 MonitorInfo monitor_info(o);
940
Sebastien Hertz54263242014-03-19 18:16:50 +0100941 Runtime::Current()->GetThreadList()->ResumeAll();
942 self->TransitionFromSuspendedToRunnable();
Elliott Hughesf327e072013-01-09 16:01:26 -0800943
Ian Rogersc0542af2014-09-03 16:16:56 -0700944 if (monitor_info.owner_ != nullptr) {
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700945 expandBufAddObjectId(reply, gRegistry->Add(monitor_info.owner_->GetPeer()));
Elliott Hughesf327e072013-01-09 16:01:26 -0800946 } else {
Ian Rogersc0542af2014-09-03 16:16:56 -0700947 expandBufAddObjectId(reply, gRegistry->Add(nullptr));
Elliott Hughesf327e072013-01-09 16:01:26 -0800948 }
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700949 expandBufAdd4BE(reply, monitor_info.entry_count_);
950 expandBufAdd4BE(reply, monitor_info.waiters_.size());
951 for (size_t i = 0; i < monitor_info.waiters_.size(); ++i) {
952 expandBufAddObjectId(reply, gRegistry->Add(monitor_info.waiters_[i]->GetPeer()));
Elliott Hughesf327e072013-01-09 16:01:26 -0800953 }
954 return JDWP::ERR_NONE;
955}
956
Elliott Hughes734b8c62013-01-11 15:32:45 -0800957JDWP::JdwpError Dbg::GetOwnedMonitors(JDWP::ObjectId thread_id,
Ian Rogersc0542af2014-09-03 16:16:56 -0700958 std::vector<JDWP::ObjectId>* monitors,
959 std::vector<uint32_t>* stack_depths) {
Elliott Hughes4993bbc2013-01-10 15:41:25 -0800960 struct OwnedMonitorVisitor : public StackVisitor {
Hiroshi Yamauchib5a9e3d2014-06-09 12:11:20 -0700961 OwnedMonitorVisitor(Thread* thread, Context* context,
Hiroshi Yamauchicc8c5c52014-06-13 15:08:05 -0700962 std::vector<JDWP::ObjectId>* monitor_vector,
Hiroshi Yamauchib5a9e3d2014-06-09 12:11:20 -0700963 std::vector<uint32_t>* stack_depth_vector)
Elliott Hughes4993bbc2013-01-10 15:41:25 -0800964 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_)
Hiroshi Yamauchib5a9e3d2014-06-09 12:11:20 -0700965 : StackVisitor(thread, context), current_stack_depth(0),
966 monitors(monitor_vector), stack_depths(stack_depth_vector) {}
Elliott Hughes4993bbc2013-01-10 15:41:25 -0800967
968 // TODO: Enable annotalysis. We know lock is held in constructor, but abstraction confuses
969 // annotalysis.
970 bool VisitFrame() NO_THREAD_SAFETY_ANALYSIS {
971 if (!GetMethod()->IsRuntimeMethod()) {
972 Monitor::VisitLocks(this, AppendOwnedMonitors, this);
Elliott Hughes734b8c62013-01-11 15:32:45 -0800973 ++current_stack_depth;
Elliott Hughes4993bbc2013-01-10 15:41:25 -0800974 }
975 return true;
976 }
977
Hiroshi Yamauchicc8c5c52014-06-13 15:08:05 -0700978 static void AppendOwnedMonitors(mirror::Object* owned_monitor, void* arg)
979 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Ian Rogers7a22fa62013-01-23 12:16:16 -0800980 OwnedMonitorVisitor* visitor = reinterpret_cast<OwnedMonitorVisitor*>(arg);
Hiroshi Yamauchicc8c5c52014-06-13 15:08:05 -0700981 visitor->monitors->push_back(gRegistry->Add(owned_monitor));
Hiroshi Yamauchib5a9e3d2014-06-09 12:11:20 -0700982 visitor->stack_depths->push_back(visitor->current_stack_depth);
Elliott Hughes4993bbc2013-01-10 15:41:25 -0800983 }
984
Elliott Hughes734b8c62013-01-11 15:32:45 -0800985 size_t current_stack_depth;
Ian Rogersc0542af2014-09-03 16:16:56 -0700986 std::vector<JDWP::ObjectId>* const monitors;
987 std::vector<uint32_t>* const stack_depths;
Elliott Hughes4993bbc2013-01-10 15:41:25 -0800988 };
Elliott Hughes4993bbc2013-01-10 15:41:25 -0800989
Hiroshi Yamauchib5a9e3d2014-06-09 12:11:20 -0700990 ScopedObjectAccessUnchecked soa(Thread::Current());
Hiroshi Yamauchicc8c5c52014-06-13 15:08:05 -0700991 Thread* thread;
Hiroshi Yamauchib5a9e3d2014-06-09 12:11:20 -0700992 {
993 MutexLock mu(soa.Self(), *Locks::thread_list_lock_);
Ian Rogersc0542af2014-09-03 16:16:56 -0700994 JDWP::JdwpError error;
995 thread = DecodeThread(soa, thread_id, &error);
996 if (thread == nullptr) {
Hiroshi Yamauchib5a9e3d2014-06-09 12:11:20 -0700997 return error;
998 }
999 if (!IsSuspendedForDebugger(soa, thread)) {
1000 return JDWP::ERR_THREAD_NOT_SUSPENDED;
1001 }
Hiroshi Yamauchib5a9e3d2014-06-09 12:11:20 -07001002 }
Hiroshi Yamauchicc8c5c52014-06-13 15:08:05 -07001003 std::unique_ptr<Context> context(Context::Create());
Ian Rogersc0542af2014-09-03 16:16:56 -07001004 OwnedMonitorVisitor visitor(thread, context.get(), monitors, stack_depths);
Hiroshi Yamauchicc8c5c52014-06-13 15:08:05 -07001005 visitor.WalkStack();
Elliott Hughes4993bbc2013-01-10 15:41:25 -08001006 return JDWP::ERR_NONE;
1007}
1008
Sebastien Hertz52d131d2014-03-13 16:17:40 +01001009JDWP::JdwpError Dbg::GetContendedMonitor(JDWP::ObjectId thread_id,
Ian Rogersc0542af2014-09-03 16:16:56 -07001010 JDWP::ObjectId* contended_monitor) {
Hiroshi Yamauchib5a9e3d2014-06-09 12:11:20 -07001011 mirror::Object* contended_monitor_obj;
Elliott Hughesf9501702013-01-11 11:22:27 -08001012 ScopedObjectAccessUnchecked soa(Thread::Current());
Ian Rogersc0542af2014-09-03 16:16:56 -07001013 *contended_monitor = 0;
Hiroshi Yamauchib5a9e3d2014-06-09 12:11:20 -07001014 {
1015 MutexLock mu(soa.Self(), *Locks::thread_list_lock_);
Ian Rogersc0542af2014-09-03 16:16:56 -07001016 JDWP::JdwpError error;
1017 Thread* thread = DecodeThread(soa, thread_id, &error);
1018 if (thread == nullptr) {
Hiroshi Yamauchib5a9e3d2014-06-09 12:11:20 -07001019 return error;
1020 }
1021 if (!IsSuspendedForDebugger(soa, thread)) {
1022 return JDWP::ERR_THREAD_NOT_SUSPENDED;
1023 }
1024 contended_monitor_obj = Monitor::GetContendedMonitor(thread);
Elliott Hughesf9501702013-01-11 11:22:27 -08001025 }
Hiroshi Yamauchib5a9e3d2014-06-09 12:11:20 -07001026 // Add() requires the thread_list_lock_ not held to avoid the lock
1027 // level violation.
Ian Rogersc0542af2014-09-03 16:16:56 -07001028 *contended_monitor = gRegistry->Add(contended_monitor_obj);
Elliott Hughesf9501702013-01-11 11:22:27 -08001029 return JDWP::ERR_NONE;
1030}
1031
Elliott Hughesec0f83d2013-01-15 16:54:08 -08001032JDWP::JdwpError Dbg::GetInstanceCounts(const std::vector<JDWP::RefTypeId>& class_ids,
Ian Rogersc0542af2014-09-03 16:16:56 -07001033 std::vector<uint64_t>* counts) {
Mathieu Chartier412c7fc2014-02-07 12:18:39 -08001034 gc::Heap* heap = Runtime::Current()->GetHeap();
1035 heap->CollectGarbage(false);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001036 std::vector<mirror::Class*> classes;
Ian Rogersc0542af2014-09-03 16:16:56 -07001037 counts->clear();
Elliott Hughesec0f83d2013-01-15 16:54:08 -08001038 for (size_t i = 0; i < class_ids.size(); ++i) {
Ian Rogersc0542af2014-09-03 16:16:56 -07001039 JDWP::JdwpError error;
1040 mirror::Class* c = DecodeClass(class_ids[i], &error);
1041 if (c == nullptr) {
1042 return error;
Elliott Hughesec0f83d2013-01-15 16:54:08 -08001043 }
1044 classes.push_back(c);
Ian Rogersc0542af2014-09-03 16:16:56 -07001045 counts->push_back(0);
Elliott Hughesec0f83d2013-01-15 16:54:08 -08001046 }
Ian Rogersc0542af2014-09-03 16:16:56 -07001047 heap->CountInstances(classes, false, &(*counts)[0]);
Elliott Hughesec0f83d2013-01-15 16:54:08 -08001048 return JDWP::ERR_NONE;
1049}
1050
Ian Rogersc0542af2014-09-03 16:16:56 -07001051JDWP::JdwpError Dbg::GetInstances(JDWP::RefTypeId class_id, int32_t max_count,
1052 std::vector<JDWP::ObjectId>* instances) {
Mathieu Chartier412c7fc2014-02-07 12:18:39 -08001053 gc::Heap* heap = Runtime::Current()->GetHeap();
1054 // We only want reachable instances, so do a GC.
1055 heap->CollectGarbage(false);
Ian Rogersc0542af2014-09-03 16:16:56 -07001056 JDWP::JdwpError error;
1057 mirror::Class* c = DecodeClass(class_id, &error);
Mathieu Chartier412c7fc2014-02-07 12:18:39 -08001058 if (c == nullptr) {
Ian Rogersc0542af2014-09-03 16:16:56 -07001059 return error;
Elliott Hughes3b78c942013-01-15 17:35:41 -08001060 }
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001061 std::vector<mirror::Object*> raw_instances;
Elliott Hughes3b78c942013-01-15 17:35:41 -08001062 Runtime::Current()->GetHeap()->GetInstances(c, max_count, raw_instances);
1063 for (size_t i = 0; i < raw_instances.size(); ++i) {
Ian Rogersc0542af2014-09-03 16:16:56 -07001064 instances->push_back(gRegistry->Add(raw_instances[i]));
Elliott Hughes3b78c942013-01-15 17:35:41 -08001065 }
1066 return JDWP::ERR_NONE;
1067}
1068
Elliott Hughes0cbaff52013-01-16 15:28:01 -08001069JDWP::JdwpError Dbg::GetReferringObjects(JDWP::ObjectId object_id, int32_t max_count,
Ian Rogersc0542af2014-09-03 16:16:56 -07001070 std::vector<JDWP::ObjectId>* referring_objects) {
Mathieu Chartier412c7fc2014-02-07 12:18:39 -08001071 gc::Heap* heap = Runtime::Current()->GetHeap();
1072 heap->CollectGarbage(false);
Ian Rogersc0542af2014-09-03 16:16:56 -07001073 JDWP::JdwpError error;
1074 mirror::Object* o = gRegistry->Get<mirror::Object*>(object_id, &error);
1075 if (o == nullptr) {
Elliott Hughes0cbaff52013-01-16 15:28:01 -08001076 return JDWP::ERR_INVALID_OBJECT;
1077 }
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001078 std::vector<mirror::Object*> raw_instances;
Mathieu Chartier412c7fc2014-02-07 12:18:39 -08001079 heap->GetReferringObjects(o, max_count, raw_instances);
Elliott Hughes0cbaff52013-01-16 15:28:01 -08001080 for (size_t i = 0; i < raw_instances.size(); ++i) {
Ian Rogersc0542af2014-09-03 16:16:56 -07001081 referring_objects->push_back(gRegistry->Add(raw_instances[i]));
Elliott Hughes0cbaff52013-01-16 15:28:01 -08001082 }
1083 return JDWP::ERR_NONE;
1084}
1085
Ian Rogersc0542af2014-09-03 16:16:56 -07001086JDWP::JdwpError Dbg::DisableCollection(JDWP::ObjectId object_id) {
1087 JDWP::JdwpError error;
1088 mirror::Object* o = gRegistry->Get<mirror::Object*>(object_id, &error);
1089 if (o == nullptr) {
Sebastien Hertze96060a2013-12-11 12:06:28 +01001090 return JDWP::ERR_INVALID_OBJECT;
1091 }
Elliott Hughes64f574f2013-02-20 14:57:12 -08001092 gRegistry->DisableCollection(object_id);
1093 return JDWP::ERR_NONE;
1094}
1095
Ian Rogersc0542af2014-09-03 16:16:56 -07001096JDWP::JdwpError Dbg::EnableCollection(JDWP::ObjectId object_id) {
1097 JDWP::JdwpError error;
1098 mirror::Object* o = gRegistry->Get<mirror::Object*>(object_id, &error);
Sebastien Hertze96060a2013-12-11 12:06:28 +01001099 // Unlike DisableCollection, JDWP specs do not state an invalid object causes an error. The RI
1100 // also ignores these cases and never return an error. However it's not obvious why this command
1101 // should behave differently from DisableCollection and IsCollected commands. So let's be more
1102 // strict and return an error if this happens.
Ian Rogersc0542af2014-09-03 16:16:56 -07001103 if (o == nullptr) {
Sebastien Hertze96060a2013-12-11 12:06:28 +01001104 return JDWP::ERR_INVALID_OBJECT;
1105 }
Elliott Hughes64f574f2013-02-20 14:57:12 -08001106 gRegistry->EnableCollection(object_id);
1107 return JDWP::ERR_NONE;
1108}
1109
Ian Rogersc0542af2014-09-03 16:16:56 -07001110JDWP::JdwpError Dbg::IsCollected(JDWP::ObjectId object_id, bool* is_collected) {
1111 *is_collected = true;
Sebastien Hertz65637eb2014-01-10 17:40:02 +01001112 if (object_id == 0) {
1113 // Null object id is invalid.
Sebastien Hertze96060a2013-12-11 12:06:28 +01001114 return JDWP::ERR_INVALID_OBJECT;
1115 }
Sebastien Hertz65637eb2014-01-10 17:40:02 +01001116 // JDWP specs state an INVALID_OBJECT error is returned if the object ID is not valid. However
1117 // the RI seems to ignore this and assume object has been collected.
Ian Rogersc0542af2014-09-03 16:16:56 -07001118 JDWP::JdwpError error;
1119 mirror::Object* o = gRegistry->Get<mirror::Object*>(object_id, &error);
1120 if (o != nullptr) {
1121 *is_collected = gRegistry->IsCollected(object_id);
Sebastien Hertz65637eb2014-01-10 17:40:02 +01001122 }
Elliott Hughes64f574f2013-02-20 14:57:12 -08001123 return JDWP::ERR_NONE;
1124}
1125
Ian Rogersc0542af2014-09-03 16:16:56 -07001126void Dbg::DisposeObject(JDWP::ObjectId object_id, uint32_t reference_count) {
Elliott Hughes64f574f2013-02-20 14:57:12 -08001127 gRegistry->DisposeObject(object_id, reference_count);
1128}
1129
Sebastien Hertz6995c602014-09-09 12:10:13 +02001130JDWP::JdwpTypeTag Dbg::GetTypeTag(mirror::Class* klass) {
Sebastien Hertz4d8fd492014-03-28 16:29:41 +01001131 DCHECK(klass != nullptr);
1132 if (klass->IsArrayClass()) {
1133 return JDWP::TT_ARRAY;
1134 } else if (klass->IsInterface()) {
1135 return JDWP::TT_INTERFACE;
1136 } else {
1137 return JDWP::TT_CLASS;
1138 }
1139}
1140
Elliott Hughes88d63092013-01-09 09:55:54 -08001141JDWP::JdwpError Dbg::GetReflectedType(JDWP::RefTypeId class_id, JDWP::ExpandBuf* pReply) {
Ian Rogersc0542af2014-09-03 16:16:56 -07001142 JDWP::JdwpError error;
1143 mirror::Class* c = DecodeClass(class_id, &error);
1144 if (c == nullptr) {
1145 return error;
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -08001146 }
Elliott Hughes436e3722012-02-17 20:01:47 -08001147
Sebastien Hertz4d8fd492014-03-28 16:29:41 +01001148 JDWP::JdwpTypeTag type_tag = GetTypeTag(c);
1149 expandBufAdd1(pReply, type_tag);
Elliott Hughes88d63092013-01-09 09:55:54 -08001150 expandBufAddRefTypeId(pReply, class_id);
Elliott Hughes436e3722012-02-17 20:01:47 -08001151 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001152}
1153
Ian Rogersc0542af2014-09-03 16:16:56 -07001154void Dbg::GetClassList(std::vector<JDWP::RefTypeId>* classes) {
Elliott Hughesa2155262011-11-16 16:26:58 -08001155 // Get the complete list of reference classes (i.e. all classes except
1156 // the primitive types).
1157 // Returns a newly-allocated buffer full of RefTypeId values.
1158 struct ClassListCreator {
Andreas Gampe277ccbd2014-11-03 21:36:10 -08001159 explicit ClassListCreator(std::vector<JDWP::RefTypeId>* classes_in) : classes(classes_in) {
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -08001160 }
1161
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001162 static bool Visit(mirror::Class* c, void* arg) {
Elliott Hughesa2155262011-11-16 16:26:58 -08001163 return reinterpret_cast<ClassListCreator*>(arg)->Visit(c);
1164 }
1165
Elliott Hughes64f574f2013-02-20 14:57:12 -08001166 // TODO: Enable annotalysis. We know lock is held in constructor, but abstraction confuses
1167 // annotalysis.
1168 bool Visit(mirror::Class* c) NO_THREAD_SAFETY_ANALYSIS {
Elliott Hughesa2155262011-11-16 16:26:58 -08001169 if (!c->IsPrimitive()) {
Ian Rogersc0542af2014-09-03 16:16:56 -07001170 classes->push_back(gRegistry->AddRefType(c));
Elliott Hughesa2155262011-11-16 16:26:58 -08001171 }
1172 return true;
1173 }
1174
Ian Rogersc0542af2014-09-03 16:16:56 -07001175 std::vector<JDWP::RefTypeId>* const classes;
Elliott Hughesa2155262011-11-16 16:26:58 -08001176 };
1177
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -08001178 ClassListCreator clc(classes);
Sebastien Hertz4537c412014-08-28 14:41:50 +02001179 Runtime::Current()->GetClassLinker()->VisitClassesWithoutClassesLock(ClassListCreator::Visit,
1180 &clc);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001181}
1182
Ian Rogers1ff3c982014-08-12 02:30:58 -07001183JDWP::JdwpError Dbg::GetClassInfo(JDWP::RefTypeId class_id, JDWP::JdwpTypeTag* pTypeTag,
1184 uint32_t* pStatus, std::string* pDescriptor) {
Ian Rogersc0542af2014-09-03 16:16:56 -07001185 JDWP::JdwpError error;
1186 mirror::Class* c = DecodeClass(class_id, &error);
1187 if (c == nullptr) {
1188 return error;
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -08001189 }
1190
Elliott Hughesa2155262011-11-16 16:26:58 -08001191 if (c->IsArrayClass()) {
1192 *pStatus = JDWP::CS_VERIFIED | JDWP::CS_PREPARED;
1193 *pTypeTag = JDWP::TT_ARRAY;
1194 } else {
1195 if (c->IsErroneous()) {
1196 *pStatus = JDWP::CS_ERROR;
1197 } else {
1198 *pStatus = JDWP::CS_VERIFIED | JDWP::CS_PREPARED | JDWP::CS_INITIALIZED;
1199 }
1200 *pTypeTag = c->IsInterface() ? JDWP::TT_INTERFACE : JDWP::TT_CLASS;
1201 }
1202
Ian Rogersc0542af2014-09-03 16:16:56 -07001203 if (pDescriptor != nullptr) {
Ian Rogers1ff3c982014-08-12 02:30:58 -07001204 std::string temp;
1205 *pDescriptor = c->GetDescriptor(&temp);
Elliott Hughesa2155262011-11-16 16:26:58 -08001206 }
Elliott Hughes436e3722012-02-17 20:01:47 -08001207 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001208}
1209
Ian Rogersc0542af2014-09-03 16:16:56 -07001210void Dbg::FindLoadedClassBySignature(const char* descriptor, std::vector<JDWP::RefTypeId>* ids) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001211 std::vector<mirror::Class*> classes;
Elliott Hughes6fa602d2011-12-02 17:54:25 -08001212 Runtime::Current()->GetClassLinker()->LookupClasses(descriptor, classes);
Ian Rogersc0542af2014-09-03 16:16:56 -07001213 ids->clear();
Elliott Hughes6fa602d2011-12-02 17:54:25 -08001214 for (size_t i = 0; i < classes.size(); ++i) {
Ian Rogersc0542af2014-09-03 16:16:56 -07001215 ids->push_back(gRegistry->Add(classes[i]));
Elliott Hughes6fa602d2011-12-02 17:54:25 -08001216 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001217}
1218
Ian Rogersc0542af2014-09-03 16:16:56 -07001219JDWP::JdwpError Dbg::GetReferenceType(JDWP::ObjectId object_id, JDWP::ExpandBuf* pReply) {
1220 JDWP::JdwpError error;
1221 mirror::Object* o = gRegistry->Get<mirror::Object*>(object_id, &error);
1222 if (o == nullptr) {
Elliott Hughes2435a572012-02-17 16:07:41 -08001223 return JDWP::ERR_INVALID_OBJECT;
Elliott Hughes499c5132011-11-17 14:55:11 -08001224 }
Elliott Hughes2435a572012-02-17 16:07:41 -08001225
Sebastien Hertz4d8fd492014-03-28 16:29:41 +01001226 JDWP::JdwpTypeTag type_tag = GetTypeTag(o->GetClass());
Elliott Hughes64f574f2013-02-20 14:57:12 -08001227 JDWP::RefTypeId type_id = gRegistry->AddRefType(o->GetClass());
Elliott Hughes2435a572012-02-17 16:07:41 -08001228
1229 expandBufAdd1(pReply, type_tag);
1230 expandBufAddRefTypeId(pReply, type_id);
1231
1232 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001233}
1234
Ian Rogersfc0e94b2013-09-23 23:51:32 -07001235JDWP::JdwpError Dbg::GetSignature(JDWP::RefTypeId class_id, std::string* signature) {
Ian Rogersc0542af2014-09-03 16:16:56 -07001236 JDWP::JdwpError error;
1237 mirror::Class* c = DecodeClass(class_id, &error);
1238 if (c == nullptr) {
1239 return error;
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -08001240 }
Ian Rogers1ff3c982014-08-12 02:30:58 -07001241 std::string temp;
1242 *signature = c->GetDescriptor(&temp);
Elliott Hughes1fe7afb2012-02-13 17:23:03 -08001243 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001244}
1245
Ian Rogersc0542af2014-09-03 16:16:56 -07001246JDWP::JdwpError Dbg::GetSourceFile(JDWP::RefTypeId class_id, std::string* result) {
1247 JDWP::JdwpError error;
1248 mirror::Class* c = DecodeClass(class_id, &error);
Sebastien Hertz4206eb52014-06-05 10:15:45 +02001249 if (c == nullptr) {
Ian Rogersc0542af2014-09-03 16:16:56 -07001250 return error;
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -08001251 }
Sebastien Hertz4206eb52014-06-05 10:15:45 +02001252 const char* source_file = c->GetSourceFile();
1253 if (source_file == nullptr) {
Sebastien Hertzb7054ba2014-03-13 11:52:31 +01001254 return JDWP::ERR_ABSENT_INFORMATION;
1255 }
Ian Rogersc0542af2014-09-03 16:16:56 -07001256 *result = source_file;
Elliott Hughes436e3722012-02-17 20:01:47 -08001257 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001258}
1259
Ian Rogersc0542af2014-09-03 16:16:56 -07001260JDWP::JdwpError Dbg::GetObjectTag(JDWP::ObjectId object_id, uint8_t* tag) {
Ian Rogers98379392014-02-24 16:53:16 -08001261 ScopedObjectAccessUnchecked soa(Thread::Current());
Ian Rogersc0542af2014-09-03 16:16:56 -07001262 JDWP::JdwpError error;
1263 mirror::Object* o = gRegistry->Get<mirror::Object*>(object_id, &error);
1264 if (error != JDWP::ERR_NONE) {
1265 *tag = JDWP::JT_VOID;
1266 return error;
Elliott Hughes546b9862012-06-20 16:06:13 -07001267 }
Ian Rogersc0542af2014-09-03 16:16:56 -07001268 *tag = TagFromObject(soa, o);
Elliott Hughes546b9862012-06-20 16:06:13 -07001269 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001270}
1271
Elliott Hughesaed4be92011-12-02 16:16:23 -08001272size_t Dbg::GetTagWidth(JDWP::JdwpTag tag) {
Elliott Hughesdbb40792011-11-18 17:05:22 -08001273 switch (tag) {
1274 case JDWP::JT_VOID:
1275 return 0;
1276 case JDWP::JT_BYTE:
1277 case JDWP::JT_BOOLEAN:
1278 return 1;
1279 case JDWP::JT_CHAR:
1280 case JDWP::JT_SHORT:
1281 return 2;
1282 case JDWP::JT_FLOAT:
1283 case JDWP::JT_INT:
1284 return 4;
1285 case JDWP::JT_ARRAY:
1286 case JDWP::JT_OBJECT:
1287 case JDWP::JT_STRING:
1288 case JDWP::JT_THREAD:
1289 case JDWP::JT_THREAD_GROUP:
1290 case JDWP::JT_CLASS_LOADER:
1291 case JDWP::JT_CLASS_OBJECT:
1292 return sizeof(JDWP::ObjectId);
1293 case JDWP::JT_DOUBLE:
1294 case JDWP::JT_LONG:
1295 return 8;
1296 default:
Elliott Hughes3d30d9b2011-12-07 17:35:48 -08001297 LOG(FATAL) << "Unknown tag " << tag;
Elliott Hughesdbb40792011-11-18 17:05:22 -08001298 return -1;
1299 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001300}
1301
Ian Rogersc0542af2014-09-03 16:16:56 -07001302JDWP::JdwpError Dbg::GetArrayLength(JDWP::ObjectId array_id, int32_t* length) {
1303 JDWP::JdwpError error;
1304 mirror::Array* a = DecodeNonNullArray(array_id, &error);
1305 if (a == nullptr) {
1306 return error;
Elliott Hughes24437992011-11-30 14:49:33 -08001307 }
Ian Rogersc0542af2014-09-03 16:16:56 -07001308 *length = a->GetLength();
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -08001309 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001310}
1311
Elliott Hughes88d63092013-01-09 09:55:54 -08001312JDWP::JdwpError Dbg::OutputArray(JDWP::ObjectId array_id, int offset, int count, JDWP::ExpandBuf* pReply) {
Ian Rogersc0542af2014-09-03 16:16:56 -07001313 JDWP::JdwpError error;
1314 mirror::Array* a = DecodeNonNullArray(array_id, &error);
Ian Rogers98379392014-02-24 16:53:16 -08001315 if (a == nullptr) {
Ian Rogersc0542af2014-09-03 16:16:56 -07001316 return error;
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -08001317 }
Elliott Hughes24437992011-11-30 14:49:33 -08001318
1319 if (offset < 0 || count < 0 || offset > a->GetLength() || a->GetLength() - offset < count) {
1320 LOG(WARNING) << __FUNCTION__ << " access out of bounds: offset=" << offset << "; count=" << count;
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -08001321 return JDWP::ERR_INVALID_LENGTH;
Elliott Hughes24437992011-11-30 14:49:33 -08001322 }
Ian Rogers1ff3c982014-08-12 02:30:58 -07001323 JDWP::JdwpTag element_tag = BasicTagFromClass(a->GetClass()->GetComponentType());
1324 expandBufAdd1(pReply, element_tag);
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -08001325 expandBufAdd4BE(pReply, count);
1326
Ian Rogers1ff3c982014-08-12 02:30:58 -07001327 if (IsPrimitiveTag(element_tag)) {
1328 size_t width = GetTagWidth(element_tag);
Elliott Hughes24437992011-11-30 14:49:33 -08001329 uint8_t* dst = expandBufAddSpace(pReply, count * width);
1330 if (width == 8) {
Ian Rogersef7d42f2014-01-06 12:55:46 -08001331 const uint64_t* src8 = reinterpret_cast<uint64_t*>(a->GetRawData(sizeof(uint64_t), 0));
Elliott Hughes24437992011-11-30 14:49:33 -08001332 for (int i = 0; i < count; ++i) JDWP::Write8BE(&dst, src8[offset + i]);
1333 } else if (width == 4) {
Ian Rogersef7d42f2014-01-06 12:55:46 -08001334 const uint32_t* src4 = reinterpret_cast<uint32_t*>(a->GetRawData(sizeof(uint32_t), 0));
Elliott Hughes24437992011-11-30 14:49:33 -08001335 for (int i = 0; i < count; ++i) JDWP::Write4BE(&dst, src4[offset + i]);
1336 } else if (width == 2) {
Ian Rogersef7d42f2014-01-06 12:55:46 -08001337 const uint16_t* src2 = reinterpret_cast<uint16_t*>(a->GetRawData(sizeof(uint16_t), 0));
Elliott Hughes24437992011-11-30 14:49:33 -08001338 for (int i = 0; i < count; ++i) JDWP::Write2BE(&dst, src2[offset + i]);
1339 } else {
Ian Rogersef7d42f2014-01-06 12:55:46 -08001340 const uint8_t* src = reinterpret_cast<uint8_t*>(a->GetRawData(sizeof(uint8_t), 0));
Elliott Hughes24437992011-11-30 14:49:33 -08001341 memcpy(dst, &src[offset * width], count * width);
1342 }
1343 } else {
Ian Rogers98379392014-02-24 16:53:16 -08001344 ScopedObjectAccessUnchecked soa(Thread::Current());
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001345 mirror::ObjectArray<mirror::Object>* oa = a->AsObjectArray<mirror::Object>();
Elliott Hughes24437992011-11-30 14:49:33 -08001346 for (int i = 0; i < count; ++i) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001347 mirror::Object* element = oa->Get(offset + i);
Ian Rogers98379392014-02-24 16:53:16 -08001348 JDWP::JdwpTag specific_tag = (element != nullptr) ? TagFromObject(soa, element)
Ian Rogers1ff3c982014-08-12 02:30:58 -07001349 : element_tag;
Elliott Hughes24437992011-11-30 14:49:33 -08001350 expandBufAdd1(pReply, specific_tag);
1351 expandBufAddObjectId(pReply, gRegistry->Add(element));
1352 }
1353 }
1354
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -08001355 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001356}
1357
Ian Rogersef7d42f2014-01-06 12:55:46 -08001358template <typename T>
Ian Rogersc0542af2014-09-03 16:16:56 -07001359static void CopyArrayData(mirror::Array* a, JDWP::Request* src, int offset, int count)
Ian Rogersef7d42f2014-01-06 12:55:46 -08001360 NO_THREAD_SAFETY_ANALYSIS {
1361 // TODO: fix when annotalysis correctly handles non-member functions.
Elliott Hughes4b9702c2013-02-20 18:13:24 -08001362 DCHECK(a->GetClass()->IsPrimitiveArray());
1363
Ian Rogersef7d42f2014-01-06 12:55:46 -08001364 T* dst = reinterpret_cast<T*>(a->GetRawData(sizeof(T), offset));
Elliott Hughes4b9702c2013-02-20 18:13:24 -08001365 for (int i = 0; i < count; ++i) {
Ian Rogersc0542af2014-09-03 16:16:56 -07001366 *dst++ = src->ReadValue(sizeof(T));
Elliott Hughes4b9702c2013-02-20 18:13:24 -08001367 }
1368}
1369
Elliott Hughes88d63092013-01-09 09:55:54 -08001370JDWP::JdwpError Dbg::SetArrayElements(JDWP::ObjectId array_id, int offset, int count,
Ian Rogersc0542af2014-09-03 16:16:56 -07001371 JDWP::Request* request) {
1372 JDWP::JdwpError error;
1373 mirror::Array* dst = DecodeNonNullArray(array_id, &error);
1374 if (dst == nullptr) {
1375 return error;
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -08001376 }
Elliott Hughesf03b8f62011-12-02 14:26:25 -08001377
Elliott Hughes4b9702c2013-02-20 18:13:24 -08001378 if (offset < 0 || count < 0 || offset > dst->GetLength() || dst->GetLength() - offset < count) {
Elliott Hughesf03b8f62011-12-02 14:26:25 -08001379 LOG(WARNING) << __FUNCTION__ << " access out of bounds: offset=" << offset << "; count=" << count;
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -08001380 return JDWP::ERR_INVALID_LENGTH;
Elliott Hughesf03b8f62011-12-02 14:26:25 -08001381 }
Ian Rogers1ff3c982014-08-12 02:30:58 -07001382 JDWP::JdwpTag element_tag = BasicTagFromClass(dst->GetClass()->GetComponentType());
Elliott Hughesf03b8f62011-12-02 14:26:25 -08001383
Ian Rogers1ff3c982014-08-12 02:30:58 -07001384 if (IsPrimitiveTag(element_tag)) {
1385 size_t width = GetTagWidth(element_tag);
Elliott Hughesf03b8f62011-12-02 14:26:25 -08001386 if (width == 8) {
Elliott Hughes4b9702c2013-02-20 18:13:24 -08001387 CopyArrayData<uint64_t>(dst, request, offset, count);
Elliott Hughesf03b8f62011-12-02 14:26:25 -08001388 } else if (width == 4) {
Elliott Hughes4b9702c2013-02-20 18:13:24 -08001389 CopyArrayData<uint32_t>(dst, request, offset, count);
Elliott Hughesf03b8f62011-12-02 14:26:25 -08001390 } else if (width == 2) {
Elliott Hughes4b9702c2013-02-20 18:13:24 -08001391 CopyArrayData<uint16_t>(dst, request, offset, count);
Elliott Hughesf03b8f62011-12-02 14:26:25 -08001392 } else {
Elliott Hughes4b9702c2013-02-20 18:13:24 -08001393 CopyArrayData<uint8_t>(dst, request, offset, count);
Elliott Hughesf03b8f62011-12-02 14:26:25 -08001394 }
1395 } else {
Elliott Hughes4b9702c2013-02-20 18:13:24 -08001396 mirror::ObjectArray<mirror::Object>* oa = dst->AsObjectArray<mirror::Object>();
Elliott Hughesf03b8f62011-12-02 14:26:25 -08001397 for (int i = 0; i < count; ++i) {
Ian Rogersc0542af2014-09-03 16:16:56 -07001398 JDWP::ObjectId id = request->ReadObjectId();
Ian Rogersc0542af2014-09-03 16:16:56 -07001399 mirror::Object* o = gRegistry->Get<mirror::Object*>(id, &error);
1400 if (error != JDWP::ERR_NONE) {
1401 return error;
Elliott Hughes436e3722012-02-17 20:01:47 -08001402 }
Sebastien Hertzd2fe10a2014-01-15 10:20:56 +01001403 oa->Set<false>(offset + i, o);
Elliott Hughesf03b8f62011-12-02 14:26:25 -08001404 }
1405 }
1406
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -08001407 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001408}
1409
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -08001410JDWP::ObjectId Dbg::CreateString(const std::string& str) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001411 return gRegistry->Add(mirror::String::AllocFromModifiedUtf8(Thread::Current(), str.c_str()));
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001412}
1413
Ian Rogersc0542af2014-09-03 16:16:56 -07001414JDWP::JdwpError Dbg::CreateObject(JDWP::RefTypeId class_id, JDWP::ObjectId* new_object) {
1415 JDWP::JdwpError error;
1416 mirror::Class* c = DecodeClass(class_id, &error);
1417 if (c == nullptr) {
1418 *new_object = 0;
1419 return error;
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -08001420 }
Ian Rogersc0542af2014-09-03 16:16:56 -07001421 *new_object = gRegistry->Add(c->AllocObject(Thread::Current()));
Elliott Hughes436e3722012-02-17 20:01:47 -08001422 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001423}
1424
Elliott Hughesbf13d362011-12-08 15:51:37 -08001425/*
1426 * Used by Eclipse's "Display" view to evaluate "new byte[5]" to get "(byte[]) [0, 0, 0, 0, 0]".
1427 */
Elliott Hughes88d63092013-01-09 09:55:54 -08001428JDWP::JdwpError Dbg::CreateArrayObject(JDWP::RefTypeId array_class_id, uint32_t length,
Ian Rogersc0542af2014-09-03 16:16:56 -07001429 JDWP::ObjectId* new_array) {
1430 JDWP::JdwpError error;
1431 mirror::Class* c = DecodeClass(array_class_id, &error);
1432 if (c == nullptr) {
1433 *new_array = 0;
1434 return error;
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -08001435 }
Ian Rogersc0542af2014-09-03 16:16:56 -07001436 *new_array = gRegistry->Add(mirror::Array::Alloc<true>(Thread::Current(), c, length,
Hiroshi Yamauchif0edfc32014-09-25 11:46:46 -07001437 c->GetComponentSizeShift(),
Ian Rogersc0542af2014-09-03 16:16:56 -07001438 Runtime::Current()->GetHeap()->GetCurrentAllocator()));
Elliott Hughes436e3722012-02-17 20:01:47 -08001439 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001440}
1441
Sebastien Hertz6995c602014-09-09 12:10:13 +02001442JDWP::FieldId Dbg::ToFieldId(const mirror::ArtField* f) {
Mathieu Chartier590fee92013-09-13 13:46:47 -07001443 CHECK(!kMovingFields);
Elliott Hughes03181a82011-11-17 17:22:21 -08001444 return static_cast<JDWP::FieldId>(reinterpret_cast<uintptr_t>(f));
Elliott Hughes03181a82011-11-17 17:22:21 -08001445}
1446
Brian Carlstromea46f952013-07-30 01:26:50 -07001447static JDWP::MethodId ToMethodId(const mirror::ArtMethod* m)
Ian Rogersb726dcb2012-09-05 08:57:23 -07001448 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Mathieu Chartier590fee92013-09-13 13:46:47 -07001449 CHECK(!kMovingMethods);
Elliott Hughes03181a82011-11-17 17:22:21 -08001450 return static_cast<JDWP::MethodId>(reinterpret_cast<uintptr_t>(m));
Elliott Hughes03181a82011-11-17 17:22:21 -08001451}
1452
Brian Carlstromea46f952013-07-30 01:26:50 -07001453static mirror::ArtField* FromFieldId(JDWP::FieldId fid)
Ian Rogersb726dcb2012-09-05 08:57:23 -07001454 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Mathieu Chartier590fee92013-09-13 13:46:47 -07001455 CHECK(!kMovingFields);
Brian Carlstromea46f952013-07-30 01:26:50 -07001456 return reinterpret_cast<mirror::ArtField*>(static_cast<uintptr_t>(fid));
Elliott Hughesaed4be92011-12-02 16:16:23 -08001457}
1458
Brian Carlstromea46f952013-07-30 01:26:50 -07001459static mirror::ArtMethod* FromMethodId(JDWP::MethodId mid)
Ian Rogersb726dcb2012-09-05 08:57:23 -07001460 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Mathieu Chartier590fee92013-09-13 13:46:47 -07001461 CHECK(!kMovingMethods);
Brian Carlstromea46f952013-07-30 01:26:50 -07001462 return reinterpret_cast<mirror::ArtMethod*>(static_cast<uintptr_t>(mid));
Elliott Hughes03181a82011-11-17 17:22:21 -08001463}
1464
Sebastien Hertz6995c602014-09-09 12:10:13 +02001465bool Dbg::MatchThread(JDWP::ObjectId expected_thread_id, Thread* event_thread) {
1466 CHECK(event_thread != nullptr);
1467 JDWP::JdwpError error;
1468 mirror::Object* expected_thread_peer = gRegistry->Get<mirror::Object*>(expected_thread_id,
1469 &error);
1470 return expected_thread_peer == event_thread->GetPeer();
1471}
1472
1473bool Dbg::MatchLocation(const JDWP::JdwpLocation& expected_location,
1474 const JDWP::EventLocation& event_location) {
1475 if (expected_location.dex_pc != event_location.dex_pc) {
1476 return false;
1477 }
1478 mirror::ArtMethod* m = FromMethodId(expected_location.method_id);
1479 return m == event_location.method;
1480}
1481
1482bool Dbg::MatchType(mirror::Class* event_class, JDWP::RefTypeId class_id) {
Sebastien Hertza9aa0ff2014-09-19 12:07:51 +02001483 if (event_class == nullptr) {
1484 return false;
1485 }
Sebastien Hertz6995c602014-09-09 12:10:13 +02001486 JDWP::JdwpError error;
1487 mirror::Class* expected_class = DecodeClass(class_id, &error);
1488 CHECK(expected_class != nullptr);
1489 return expected_class->IsAssignableFrom(event_class);
1490}
1491
1492bool Dbg::MatchField(JDWP::RefTypeId expected_type_id, JDWP::FieldId expected_field_id,
1493 mirror::ArtField* event_field) {
1494 mirror::ArtField* expected_field = FromFieldId(expected_field_id);
1495 if (expected_field != event_field) {
1496 return false;
1497 }
1498 return Dbg::MatchType(event_field->GetDeclaringClass(), expected_type_id);
1499}
1500
1501bool Dbg::MatchInstance(JDWP::ObjectId expected_instance_id, mirror::Object* event_instance) {
1502 JDWP::JdwpError error;
1503 mirror::Object* modifier_instance = gRegistry->Get<mirror::Object*>(expected_instance_id, &error);
1504 return modifier_instance == event_instance;
1505}
1506
1507void Dbg::SetJdwpLocation(JDWP::JdwpLocation* location, mirror::ArtMethod* m, uint32_t dex_pc)
Ian Rogersb726dcb2012-09-05 08:57:23 -07001508 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Ian Rogersc0542af2014-09-03 16:16:56 -07001509 if (m == nullptr) {
Sebastien Hertza9aa0ff2014-09-19 12:07:51 +02001510 memset(location, 0, sizeof(*location));
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08001511 } else {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001512 mirror::Class* c = m->GetDeclaringClass();
Ian Rogersc0542af2014-09-03 16:16:56 -07001513 location->type_tag = GetTypeTag(c);
1514 location->class_id = gRegistry->AddRefType(c);
1515 location->method_id = ToMethodId(m);
1516 location->dex_pc = (m->IsNative() || m->IsProxyMethod()) ? static_cast<uint64_t>(-1) : dex_pc;
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08001517 }
Elliott Hughesd07986f2011-12-06 18:27:45 -08001518}
1519
Ian Rogersc0542af2014-09-03 16:16:56 -07001520std::string Dbg::GetMethodName(JDWP::MethodId method_id) {
Brian Carlstromea46f952013-07-30 01:26:50 -07001521 mirror::ArtMethod* m = FromMethodId(method_id);
Sebastien Hertza9aa0ff2014-09-19 12:07:51 +02001522 if (m == nullptr) {
1523 return "NULL";
1524 }
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07001525 return m->GetName();
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001526}
1527
Ian Rogersc0542af2014-09-03 16:16:56 -07001528std::string Dbg::GetFieldName(JDWP::FieldId field_id) {
Sebastien Hertza9aa0ff2014-09-19 12:07:51 +02001529 mirror::ArtField* f = FromFieldId(field_id);
1530 if (f == nullptr) {
1531 return "NULL";
1532 }
1533 return f->GetName();
Elliott Hughesa96836a2013-01-17 12:27:49 -08001534}
1535
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001536/*
1537 * Augment the access flags for synthetic methods and fields by setting
1538 * the (as described by the spec) "0xf0000000 bit". Also, strip out any
1539 * flags not specified by the Java programming language.
1540 */
1541static uint32_t MangleAccessFlags(uint32_t accessFlags) {
1542 accessFlags &= kAccJavaFlagsMask;
1543 if ((accessFlags & kAccSynthetic) != 0) {
1544 accessFlags |= 0xf0000000;
1545 }
1546 return accessFlags;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001547}
1548
Elliott Hughesdbb40792011-11-18 17:05:22 -08001549/*
Jeff Haob7cefc72013-11-14 14:51:09 -08001550 * Circularly shifts registers so that arguments come first. Debuggers
1551 * expect slots to begin with arguments, but dex code places them at
1552 * the end.
Elliott Hughesdbb40792011-11-18 17:05:22 -08001553 */
Jeff Haob7cefc72013-11-14 14:51:09 -08001554static uint16_t MangleSlot(uint16_t slot, mirror::ArtMethod* m)
1555 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07001556 const DexFile::CodeItem* code_item = m->GetCodeItem();
Sebastien Hertzcb19ebf2014-03-11 15:26:35 +01001557 if (code_item == nullptr) {
1558 // We should not get here for a method without code (native, proxy or abstract). Log it and
1559 // return the slot as is since all registers are arguments.
1560 LOG(WARNING) << "Trying to mangle slot for method without code " << PrettyMethod(m);
1561 return slot;
1562 }
Jeff Haob7cefc72013-11-14 14:51:09 -08001563 uint16_t ins_size = code_item->ins_size_;
1564 uint16_t locals_size = code_item->registers_size_ - ins_size;
1565 if (slot >= locals_size) {
1566 return slot - locals_size;
1567 } else {
1568 return slot + ins_size;
Elliott Hughesdbb40792011-11-18 17:05:22 -08001569 }
Elliott Hughesdbb40792011-11-18 17:05:22 -08001570}
1571
Jeff Haob7cefc72013-11-14 14:51:09 -08001572/*
1573 * Circularly shifts registers so that arguments come last. Reverts
1574 * slots to dex style argument placement.
1575 */
Brian Carlstromea46f952013-07-30 01:26:50 -07001576static uint16_t DemangleSlot(uint16_t slot, mirror::ArtMethod* m)
Ian Rogersb726dcb2012-09-05 08:57:23 -07001577 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07001578 const DexFile::CodeItem* code_item = m->GetCodeItem();
Sebastien Hertzcb19ebf2014-03-11 15:26:35 +01001579 if (code_item == nullptr) {
1580 // We should not get here for a method without code (native, proxy or abstract). Log it and
1581 // return the slot as is since all registers are arguments.
1582 LOG(WARNING) << "Trying to demangle slot for method without code " << PrettyMethod(m);
1583 return slot;
1584 }
Jeff Haob7cefc72013-11-14 14:51:09 -08001585 uint16_t ins_size = code_item->ins_size_;
1586 uint16_t locals_size = code_item->registers_size_ - ins_size;
1587 if (slot < ins_size) {
1588 return slot + locals_size;
1589 } else {
1590 return slot - ins_size;
Elliott Hughesdbb40792011-11-18 17:05:22 -08001591 }
Elliott Hughesdbb40792011-11-18 17:05:22 -08001592}
1593
Elliott Hughes88d63092013-01-09 09:55:54 -08001594JDWP::JdwpError Dbg::OutputDeclaredFields(JDWP::RefTypeId class_id, bool with_generic, JDWP::ExpandBuf* pReply) {
Ian Rogersc0542af2014-09-03 16:16:56 -07001595 JDWP::JdwpError error;
1596 mirror::Class* c = DecodeClass(class_id, &error);
1597 if (c == nullptr) {
1598 return error;
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -08001599 }
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001600
1601 size_t instance_field_count = c->NumInstanceFields();
1602 size_t static_field_count = c->NumStaticFields();
1603
1604 expandBufAdd4BE(pReply, instance_field_count + static_field_count);
1605
1606 for (size_t i = 0; i < instance_field_count + static_field_count; ++i) {
Brian Carlstromea46f952013-07-30 01:26:50 -07001607 mirror::ArtField* f = (i < instance_field_count) ? c->GetInstanceField(i) : c->GetStaticField(i - instance_field_count);
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001608 expandBufAddFieldId(pReply, ToFieldId(f));
Mathieu Chartier61c5ebc2014-06-05 17:42:53 -07001609 expandBufAddUtf8String(pReply, f->GetName());
1610 expandBufAddUtf8String(pReply, f->GetTypeDescriptor());
Elliott Hughesc5b734a2011-12-01 17:20:58 -08001611 if (with_generic) {
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001612 static const char genericSignature[1] = "";
1613 expandBufAddUtf8String(pReply, genericSignature);
1614 }
1615 expandBufAdd4BE(pReply, MangleAccessFlags(f->GetAccessFlags()));
1616 }
Elliott Hughes436e3722012-02-17 20:01:47 -08001617 return JDWP::ERR_NONE;
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001618}
1619
Elliott Hughes88d63092013-01-09 09:55:54 -08001620JDWP::JdwpError Dbg::OutputDeclaredMethods(JDWP::RefTypeId class_id, bool with_generic,
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001621 JDWP::ExpandBuf* pReply) {
Ian Rogersc0542af2014-09-03 16:16:56 -07001622 JDWP::JdwpError error;
1623 mirror::Class* c = DecodeClass(class_id, &error);
1624 if (c == nullptr) {
1625 return error;
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -08001626 }
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001627
1628 size_t direct_method_count = c->NumDirectMethods();
1629 size_t virtual_method_count = c->NumVirtualMethods();
1630
1631 expandBufAdd4BE(pReply, direct_method_count + virtual_method_count);
1632
1633 for (size_t i = 0; i < direct_method_count + virtual_method_count; ++i) {
Brian Carlstromea46f952013-07-30 01:26:50 -07001634 mirror::ArtMethod* m = (i < direct_method_count) ? c->GetDirectMethod(i) : c->GetVirtualMethod(i - direct_method_count);
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001635 expandBufAddMethodId(pReply, ToMethodId(m));
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07001636 expandBufAddUtf8String(pReply, m->GetName());
1637 expandBufAddUtf8String(pReply, m->GetSignature().ToString());
Elliott Hughesc5b734a2011-12-01 17:20:58 -08001638 if (with_generic) {
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001639 static const char genericSignature[1] = "";
1640 expandBufAddUtf8String(pReply, genericSignature);
1641 }
1642 expandBufAdd4BE(pReply, MangleAccessFlags(m->GetAccessFlags()));
1643 }
Elliott Hughes436e3722012-02-17 20:01:47 -08001644 return JDWP::ERR_NONE;
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001645}
1646
Elliott Hughes88d63092013-01-09 09:55:54 -08001647JDWP::JdwpError Dbg::OutputDeclaredInterfaces(JDWP::RefTypeId class_id, JDWP::ExpandBuf* pReply) {
Ian Rogersc0542af2014-09-03 16:16:56 -07001648 JDWP::JdwpError error;
Mathieu Chartierf8322842014-05-16 10:59:25 -07001649 Thread* self = Thread::Current();
1650 StackHandleScope<1> hs(self);
Ian Rogersc0542af2014-09-03 16:16:56 -07001651 Handle<mirror::Class> c(hs.NewHandle(DecodeClass(class_id, &error)));
Mathieu Chartierf8322842014-05-16 10:59:25 -07001652 if (c.Get() == nullptr) {
Ian Rogersc0542af2014-09-03 16:16:56 -07001653 return error;
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -08001654 }
Mathieu Chartierf8322842014-05-16 10:59:25 -07001655 size_t interface_count = c->NumDirectInterfaces();
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001656 expandBufAdd4BE(pReply, interface_count);
1657 for (size_t i = 0; i < interface_count; ++i) {
Mathieu Chartierf8322842014-05-16 10:59:25 -07001658 expandBufAddRefTypeId(pReply,
1659 gRegistry->AddRefType(mirror::Class::GetDirectInterface(self, c, i)));
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001660 }
Elliott Hughes436e3722012-02-17 20:01:47 -08001661 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001662}
1663
Ian Rogersc0542af2014-09-03 16:16:56 -07001664void Dbg::OutputLineTable(JDWP::RefTypeId, JDWP::MethodId method_id, JDWP::ExpandBuf* pReply) {
Elliott Hughes03181a82011-11-17 17:22:21 -08001665 struct DebugCallbackContext {
1666 int numItems;
1667 JDWP::ExpandBuf* pReply;
1668
Elliott Hughes2435a572012-02-17 16:07:41 -08001669 static bool Callback(void* context, uint32_t address, uint32_t line_number) {
Elliott Hughes03181a82011-11-17 17:22:21 -08001670 DebugCallbackContext* pContext = reinterpret_cast<DebugCallbackContext*>(context);
1671 expandBufAdd8BE(pContext->pReply, address);
Elliott Hughes2435a572012-02-17 16:07:41 -08001672 expandBufAdd4BE(pContext->pReply, line_number);
Elliott Hughes03181a82011-11-17 17:22:21 -08001673 pContext->numItems++;
Sebastien Hertzf2910ee2013-10-19 16:39:24 +02001674 return false;
Elliott Hughes03181a82011-11-17 17:22:21 -08001675 }
1676 };
Brian Carlstromea46f952013-07-30 01:26:50 -07001677 mirror::ArtMethod* m = FromMethodId(method_id);
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07001678 const DexFile::CodeItem* code_item = m->GetCodeItem();
Elliott Hughes03181a82011-11-17 17:22:21 -08001679 uint64_t start, end;
Sebastien Hertzcb19ebf2014-03-11 15:26:35 +01001680 if (code_item == nullptr) {
1681 DCHECK(m->IsNative() || m->IsProxyMethod());
Elliott Hughes03181a82011-11-17 17:22:21 -08001682 start = -1;
1683 end = -1;
1684 } else {
1685 start = 0;
jeffhao14f0db92012-12-14 17:50:42 -08001686 // Return the index of the last instruction
Sebastien Hertzcb19ebf2014-03-11 15:26:35 +01001687 end = code_item->insns_size_in_code_units_ - 1;
Elliott Hughes03181a82011-11-17 17:22:21 -08001688 }
1689
1690 expandBufAdd8BE(pReply, start);
1691 expandBufAdd8BE(pReply, end);
1692
1693 // Add numLines later
1694 size_t numLinesOffset = expandBufGetLength(pReply);
1695 expandBufAdd4BE(pReply, 0);
1696
1697 DebugCallbackContext context;
1698 context.numItems = 0;
1699 context.pReply = pReply;
1700
Sebastien Hertzcb19ebf2014-03-11 15:26:35 +01001701 if (code_item != nullptr) {
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07001702 m->GetDexFile()->DecodeDebugInfo(code_item, m->IsStatic(), m->GetDexMethodIndex(),
Ian Rogersc0542af2014-09-03 16:16:56 -07001703 DebugCallbackContext::Callback, nullptr, &context);
Sebastien Hertzcb19ebf2014-03-11 15:26:35 +01001704 }
Elliott Hughes03181a82011-11-17 17:22:21 -08001705
1706 JDWP::Set4BE(expandBufGetBuffer(pReply) + numLinesOffset, context.numItems);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001707}
1708
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07001709void Dbg::OutputVariableTable(JDWP::RefTypeId, JDWP::MethodId method_id, bool with_generic,
1710 JDWP::ExpandBuf* pReply) {
Elliott Hughesdbb40792011-11-18 17:05:22 -08001711 struct DebugCallbackContext {
Jeff Haob7cefc72013-11-14 14:51:09 -08001712 mirror::ArtMethod* method;
Elliott Hughesdbb40792011-11-18 17:05:22 -08001713 JDWP::ExpandBuf* pReply;
Elliott Hughesc5b734a2011-12-01 17:20:58 -08001714 size_t variable_count;
1715 bool with_generic;
Elliott Hughesdbb40792011-11-18 17:05:22 -08001716
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07001717 static void Callback(void* context, uint16_t slot, uint32_t startAddress, uint32_t endAddress,
1718 const char* name, const char* descriptor, const char* signature)
Jeff Haob7cefc72013-11-14 14:51:09 -08001719 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Elliott Hughesdbb40792011-11-18 17:05:22 -08001720 DebugCallbackContext* pContext = reinterpret_cast<DebugCallbackContext*>(context);
1721
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07001722 VLOG(jdwp) << StringPrintf(" %2zd: %d(%d) '%s' '%s' '%s' actual slot=%d mangled slot=%d",
1723 pContext->variable_count, startAddress, endAddress - startAddress,
1724 name, descriptor, signature, slot,
1725 MangleSlot(slot, pContext->method));
Elliott Hughesdbb40792011-11-18 17:05:22 -08001726
Jeff Haob7cefc72013-11-14 14:51:09 -08001727 slot = MangleSlot(slot, pContext->method);
Elliott Hughes68fdbd02011-11-29 19:22:47 -08001728
Elliott Hughesdbb40792011-11-18 17:05:22 -08001729 expandBufAdd8BE(pContext->pReply, startAddress);
1730 expandBufAddUtf8String(pContext->pReply, name);
1731 expandBufAddUtf8String(pContext->pReply, descriptor);
Elliott Hughesc5b734a2011-12-01 17:20:58 -08001732 if (pContext->with_generic) {
Elliott Hughesdbb40792011-11-18 17:05:22 -08001733 expandBufAddUtf8String(pContext->pReply, signature);
1734 }
1735 expandBufAdd4BE(pContext->pReply, endAddress - startAddress);
1736 expandBufAdd4BE(pContext->pReply, slot);
1737
Elliott Hughesc5b734a2011-12-01 17:20:58 -08001738 ++pContext->variable_count;
Elliott Hughesdbb40792011-11-18 17:05:22 -08001739 }
1740 };
Brian Carlstromea46f952013-07-30 01:26:50 -07001741 mirror::ArtMethod* m = FromMethodId(method_id);
Elliott Hughesdbb40792011-11-18 17:05:22 -08001742
Elliott Hughesc5b734a2011-12-01 17:20:58 -08001743 // arg_count considers doubles and longs to take 2 units.
1744 // variable_count considers everything to take 1 unit.
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07001745 std::string shorty(m->GetShorty());
Brian Carlstromea46f952013-07-30 01:26:50 -07001746 expandBufAdd4BE(pReply, mirror::ArtMethod::NumArgRegisters(shorty));
Elliott Hughesdbb40792011-11-18 17:05:22 -08001747
Elliott Hughesc5b734a2011-12-01 17:20:58 -08001748 // We don't know the total number of variables yet, so leave a blank and update it later.
1749 size_t variable_count_offset = expandBufGetLength(pReply);
Elliott Hughesdbb40792011-11-18 17:05:22 -08001750 expandBufAdd4BE(pReply, 0);
1751
1752 DebugCallbackContext context;
Jeff Haob7cefc72013-11-14 14:51:09 -08001753 context.method = m;
Elliott Hughesdbb40792011-11-18 17:05:22 -08001754 context.pReply = pReply;
Elliott Hughesc5b734a2011-12-01 17:20:58 -08001755 context.variable_count = 0;
1756 context.with_generic = with_generic;
Elliott Hughesdbb40792011-11-18 17:05:22 -08001757
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07001758 const DexFile::CodeItem* code_item = m->GetCodeItem();
Sebastien Hertzcb19ebf2014-03-11 15:26:35 +01001759 if (code_item != nullptr) {
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07001760 m->GetDexFile()->DecodeDebugInfo(
Ian Rogersc0542af2014-09-03 16:16:56 -07001761 code_item, m->IsStatic(), m->GetDexMethodIndex(), nullptr, DebugCallbackContext::Callback,
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07001762 &context);
Sebastien Hertzcb19ebf2014-03-11 15:26:35 +01001763 }
Elliott Hughesdbb40792011-11-18 17:05:22 -08001764
Elliott Hughesc5b734a2011-12-01 17:20:58 -08001765 JDWP::Set4BE(expandBufGetBuffer(pReply) + variable_count_offset, context.variable_count);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001766}
1767
Jeff Hao579b0242013-11-18 13:16:49 -08001768void Dbg::OutputMethodReturnValue(JDWP::MethodId method_id, const JValue* return_value,
1769 JDWP::ExpandBuf* pReply) {
1770 mirror::ArtMethod* m = FromMethodId(method_id);
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07001771 JDWP::JdwpTag tag = BasicTagFromDescriptor(m->GetShorty());
Jeff Hao579b0242013-11-18 13:16:49 -08001772 OutputJValue(tag, return_value, pReply);
1773}
1774
Sebastien Hertz3f52eaf2014-04-04 17:50:18 +02001775void Dbg::OutputFieldValue(JDWP::FieldId field_id, const JValue* field_value,
1776 JDWP::ExpandBuf* pReply) {
1777 mirror::ArtField* f = FromFieldId(field_id);
Mathieu Chartier61c5ebc2014-06-05 17:42:53 -07001778 JDWP::JdwpTag tag = BasicTagFromDescriptor(f->GetTypeDescriptor());
Sebastien Hertz3f52eaf2014-04-04 17:50:18 +02001779 OutputJValue(tag, field_value, pReply);
1780}
1781
Elliott Hughes9777ba22013-01-17 09:04:19 -08001782JDWP::JdwpError Dbg::GetBytecodes(JDWP::RefTypeId, JDWP::MethodId method_id,
Ian Rogersc0542af2014-09-03 16:16:56 -07001783 std::vector<uint8_t>* bytecodes) {
Brian Carlstromea46f952013-07-30 01:26:50 -07001784 mirror::ArtMethod* m = FromMethodId(method_id);
Ian Rogersc0542af2014-09-03 16:16:56 -07001785 if (m == nullptr) {
Elliott Hughes9777ba22013-01-17 09:04:19 -08001786 return JDWP::ERR_INVALID_METHODID;
1787 }
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07001788 const DexFile::CodeItem* code_item = m->GetCodeItem();
Elliott Hughes9777ba22013-01-17 09:04:19 -08001789 size_t byte_count = code_item->insns_size_in_code_units_ * 2;
1790 const uint8_t* begin = reinterpret_cast<const uint8_t*>(code_item->insns_);
1791 const uint8_t* end = begin + byte_count;
1792 for (const uint8_t* p = begin; p != end; ++p) {
Ian Rogersc0542af2014-09-03 16:16:56 -07001793 bytecodes->push_back(*p);
Elliott Hughes9777ba22013-01-17 09:04:19 -08001794 }
1795 return JDWP::ERR_NONE;
1796}
1797
Elliott Hughes88d63092013-01-09 09:55:54 -08001798JDWP::JdwpTag Dbg::GetFieldBasicTag(JDWP::FieldId field_id) {
Mathieu Chartier61c5ebc2014-06-05 17:42:53 -07001799 return BasicTagFromDescriptor(FromFieldId(field_id)->GetTypeDescriptor());
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001800}
1801
Elliott Hughes88d63092013-01-09 09:55:54 -08001802JDWP::JdwpTag Dbg::GetStaticFieldBasicTag(JDWP::FieldId field_id) {
Mathieu Chartier61c5ebc2014-06-05 17:42:53 -07001803 return BasicTagFromDescriptor(FromFieldId(field_id)->GetTypeDescriptor());
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001804}
1805
Elliott Hughes88d63092013-01-09 09:55:54 -08001806static JDWP::JdwpError GetFieldValueImpl(JDWP::RefTypeId ref_type_id, JDWP::ObjectId object_id,
1807 JDWP::FieldId field_id, JDWP::ExpandBuf* pReply,
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001808 bool is_static)
Ian Rogersb726dcb2012-09-05 08:57:23 -07001809 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Ian Rogersc0542af2014-09-03 16:16:56 -07001810 JDWP::JdwpError error;
1811 mirror::Class* c = DecodeClass(ref_type_id, &error);
1812 if (ref_type_id != 0 && c == nullptr) {
1813 return error;
Elliott Hughes0cf74332012-02-23 23:14:00 -08001814 }
1815
Sebastien Hertz6995c602014-09-09 12:10:13 +02001816 mirror::Object* o = Dbg::GetObjectRegistry()->Get<mirror::Object*>(object_id, &error);
Ian Rogersc0542af2014-09-03 16:16:56 -07001817 if ((!is_static && o == nullptr) || error != JDWP::ERR_NONE) {
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08001818 return JDWP::ERR_INVALID_OBJECT;
1819 }
Brian Carlstromea46f952013-07-30 01:26:50 -07001820 mirror::ArtField* f = FromFieldId(field_id);
Elliott Hughes0cf74332012-02-23 23:14:00 -08001821
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001822 mirror::Class* receiver_class = c;
Ian Rogersc0542af2014-09-03 16:16:56 -07001823 if (receiver_class == nullptr && o != nullptr) {
Elliott Hughes0cf74332012-02-23 23:14:00 -08001824 receiver_class = o->GetClass();
1825 }
Ian Rogersc0542af2014-09-03 16:16:56 -07001826 // TODO: should we give up now if receiver_class is nullptr?
1827 if (receiver_class != nullptr && !f->GetDeclaringClass()->IsAssignableFrom(receiver_class)) {
Elliott Hughes0cf74332012-02-23 23:14:00 -08001828 LOG(INFO) << "ERR_INVALID_FIELDID: " << PrettyField(f) << " " << PrettyClass(receiver_class);
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08001829 return JDWP::ERR_INVALID_FIELDID;
1830 }
Elliott Hughesaed4be92011-12-02 16:16:23 -08001831
Elliott Hughes0cf74332012-02-23 23:14:00 -08001832 // The RI only enforces the static/non-static mismatch in one direction.
1833 // TODO: should we change the tests and check both?
1834 if (is_static) {
1835 if (!f->IsStatic()) {
1836 return JDWP::ERR_INVALID_FIELDID;
1837 }
1838 } else {
1839 if (f->IsStatic()) {
Ian Rogersc0542af2014-09-03 16:16:56 -07001840 LOG(WARNING) << "Ignoring non-nullptr receiver for ObjectReference.SetValues on static field "
1841 << PrettyField(f);
Elliott Hughes0cf74332012-02-23 23:14:00 -08001842 }
1843 }
jeffhao0dfbb7e2012-11-28 15:26:03 -08001844 if (f->IsStatic()) {
1845 o = f->GetDeclaringClass();
1846 }
Elliott Hughes0cf74332012-02-23 23:14:00 -08001847
Mathieu Chartier61c5ebc2014-06-05 17:42:53 -07001848 JDWP::JdwpTag tag = BasicTagFromDescriptor(f->GetTypeDescriptor());
Jeff Hao579b0242013-11-18 13:16:49 -08001849 JValue field_value;
1850 if (tag == JDWP::JT_VOID) {
1851 LOG(FATAL) << "Unknown tag: " << tag;
1852 } else if (!IsPrimitiveTag(tag)) {
1853 field_value.SetL(f->GetObject(o));
1854 } else if (tag == JDWP::JT_DOUBLE || tag == JDWP::JT_LONG) {
1855 field_value.SetJ(f->Get64(o));
Elliott Hughesaed4be92011-12-02 16:16:23 -08001856 } else {
Jeff Hao579b0242013-11-18 13:16:49 -08001857 field_value.SetI(f->Get32(o));
Elliott Hughesaed4be92011-12-02 16:16:23 -08001858 }
Jeff Hao579b0242013-11-18 13:16:49 -08001859 Dbg::OutputJValue(tag, &field_value, pReply);
1860
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08001861 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001862}
1863
Elliott Hughes88d63092013-01-09 09:55:54 -08001864JDWP::JdwpError Dbg::GetFieldValue(JDWP::ObjectId object_id, JDWP::FieldId field_id,
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001865 JDWP::ExpandBuf* pReply) {
Elliott Hughes88d63092013-01-09 09:55:54 -08001866 return GetFieldValueImpl(0, object_id, field_id, pReply, false);
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08001867}
1868
Ian Rogersc0542af2014-09-03 16:16:56 -07001869JDWP::JdwpError Dbg::GetStaticFieldValue(JDWP::RefTypeId ref_type_id, JDWP::FieldId field_id,
1870 JDWP::ExpandBuf* pReply) {
Elliott Hughes88d63092013-01-09 09:55:54 -08001871 return GetFieldValueImpl(ref_type_id, 0, field_id, pReply, true);
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08001872}
1873
Elliott Hughes88d63092013-01-09 09:55:54 -08001874static JDWP::JdwpError SetFieldValueImpl(JDWP::ObjectId object_id, JDWP::FieldId field_id,
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001875 uint64_t value, int width, bool is_static)
Ian Rogersb726dcb2012-09-05 08:57:23 -07001876 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Ian Rogersc0542af2014-09-03 16:16:56 -07001877 JDWP::JdwpError error;
Sebastien Hertz6995c602014-09-09 12:10:13 +02001878 mirror::Object* o = Dbg::GetObjectRegistry()->Get<mirror::Object*>(object_id, &error);
Ian Rogersc0542af2014-09-03 16:16:56 -07001879 if ((!is_static && o == nullptr) || error != JDWP::ERR_NONE) {
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08001880 return JDWP::ERR_INVALID_OBJECT;
1881 }
Brian Carlstromea46f952013-07-30 01:26:50 -07001882 mirror::ArtField* f = FromFieldId(field_id);
Elliott Hughes0cf74332012-02-23 23:14:00 -08001883
1884 // The RI only enforces the static/non-static mismatch in one direction.
1885 // TODO: should we change the tests and check both?
1886 if (is_static) {
1887 if (!f->IsStatic()) {
1888 return JDWP::ERR_INVALID_FIELDID;
1889 }
1890 } else {
1891 if (f->IsStatic()) {
Ian Rogersc0542af2014-09-03 16:16:56 -07001892 LOG(WARNING) << "Ignoring non-nullptr receiver for ObjectReference.SetValues on static field " << PrettyField(f);
Elliott Hughes0cf74332012-02-23 23:14:00 -08001893 }
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08001894 }
jeffhao0dfbb7e2012-11-28 15:26:03 -08001895 if (f->IsStatic()) {
1896 o = f->GetDeclaringClass();
1897 }
Elliott Hughesaed4be92011-12-02 16:16:23 -08001898
Mathieu Chartier61c5ebc2014-06-05 17:42:53 -07001899 JDWP::JdwpTag tag = BasicTagFromDescriptor(f->GetTypeDescriptor());
Elliott Hughesaed4be92011-12-02 16:16:23 -08001900
1901 if (IsPrimitiveTag(tag)) {
1902 if (tag == JDWP::JT_DOUBLE || tag == JDWP::JT_LONG) {
Elliott Hughes1bac54f2012-03-16 12:48:31 -07001903 CHECK_EQ(width, 8);
Sebastien Hertzd2fe10a2014-01-15 10:20:56 +01001904 // Debugging can't use transactional mode (runtime only).
1905 f->Set64<false>(o, value);
Elliott Hughesaed4be92011-12-02 16:16:23 -08001906 } else {
Elliott Hughes1bac54f2012-03-16 12:48:31 -07001907 CHECK_LE(width, 4);
Sebastien Hertzd2fe10a2014-01-15 10:20:56 +01001908 // Debugging can't use transactional mode (runtime only).
1909 f->Set32<false>(o, value);
Elliott Hughesaed4be92011-12-02 16:16:23 -08001910 }
1911 } else {
Sebastien Hertz6995c602014-09-09 12:10:13 +02001912 mirror::Object* v = Dbg::GetObjectRegistry()->Get<mirror::Object*>(value, &error);
Ian Rogersc0542af2014-09-03 16:16:56 -07001913 if (error != JDWP::ERR_NONE) {
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -08001914 return JDWP::ERR_INVALID_OBJECT;
1915 }
Ian Rogersc0542af2014-09-03 16:16:56 -07001916 if (v != nullptr) {
Mathieu Chartier61c5ebc2014-06-05 17:42:53 -07001917 mirror::Class* field_type;
1918 {
1919 StackHandleScope<3> hs(Thread::Current());
1920 HandleWrapper<mirror::Object> h_v(hs.NewHandleWrapper(&v));
1921 HandleWrapper<mirror::ArtField> h_f(hs.NewHandleWrapper(&f));
1922 HandleWrapper<mirror::Object> h_o(hs.NewHandleWrapper(&o));
Ian Rogers08f1f502014-12-02 15:04:37 -08001923 field_type = h_f->GetType(true);
Mathieu Chartier61c5ebc2014-06-05 17:42:53 -07001924 }
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08001925 if (!field_type->IsAssignableFrom(v->GetClass())) {
1926 return JDWP::ERR_INVALID_OBJECT;
1927 }
1928 }
Sebastien Hertzd2fe10a2014-01-15 10:20:56 +01001929 // Debugging can't use transactional mode (runtime only).
1930 f->SetObject<false>(o, v);
Elliott Hughesaed4be92011-12-02 16:16:23 -08001931 }
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -08001932
1933 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001934}
1935
Elliott Hughes88d63092013-01-09 09:55:54 -08001936JDWP::JdwpError Dbg::SetFieldValue(JDWP::ObjectId object_id, JDWP::FieldId field_id, uint64_t value,
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001937 int width) {
Elliott Hughes88d63092013-01-09 09:55:54 -08001938 return SetFieldValueImpl(object_id, field_id, value, width, false);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001939}
1940
Elliott Hughes88d63092013-01-09 09:55:54 -08001941JDWP::JdwpError Dbg::SetStaticFieldValue(JDWP::FieldId field_id, uint64_t value, int width) {
1942 return SetFieldValueImpl(0, field_id, value, width, true);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001943}
1944
Sebastien Hertzb0b0b492014-09-15 11:27:27 +02001945JDWP::JdwpError Dbg::StringToUtf8(JDWP::ObjectId string_id, std::string* str) {
Ian Rogersc0542af2014-09-03 16:16:56 -07001946 JDWP::JdwpError error;
Sebastien Hertzb0b0b492014-09-15 11:27:27 +02001947 mirror::Object* obj = gRegistry->Get<mirror::Object*>(string_id, &error);
1948 if (error != JDWP::ERR_NONE) {
1949 return error;
1950 }
1951 if (obj == nullptr) {
1952 return JDWP::ERR_INVALID_OBJECT;
1953 }
1954 {
1955 ScopedObjectAccessUnchecked soa(Thread::Current());
1956 mirror::Class* java_lang_String = soa.Decode<mirror::Class*>(WellKnownClasses::java_lang_String);
1957 if (!java_lang_String->IsAssignableFrom(obj->GetClass())) {
1958 // This isn't a string.
1959 return JDWP::ERR_INVALID_STRING;
1960 }
1961 }
1962 *str = obj->AsString()->ToModifiedUtf8();
1963 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001964}
1965
Jeff Hao579b0242013-11-18 13:16:49 -08001966void Dbg::OutputJValue(JDWP::JdwpTag tag, const JValue* return_value, JDWP::ExpandBuf* pReply) {
1967 if (IsPrimitiveTag(tag)) {
1968 expandBufAdd1(pReply, tag);
1969 if (tag == JDWP::JT_BOOLEAN || tag == JDWP::JT_BYTE) {
1970 expandBufAdd1(pReply, return_value->GetI());
1971 } else if (tag == JDWP::JT_CHAR || tag == JDWP::JT_SHORT) {
1972 expandBufAdd2BE(pReply, return_value->GetI());
1973 } else if (tag == JDWP::JT_FLOAT || tag == JDWP::JT_INT) {
1974 expandBufAdd4BE(pReply, return_value->GetI());
1975 } else if (tag == JDWP::JT_DOUBLE || tag == JDWP::JT_LONG) {
1976 expandBufAdd8BE(pReply, return_value->GetJ());
1977 } else {
1978 CHECK_EQ(tag, JDWP::JT_VOID);
1979 }
1980 } else {
Ian Rogers98379392014-02-24 16:53:16 -08001981 ScopedObjectAccessUnchecked soa(Thread::Current());
Jeff Hao579b0242013-11-18 13:16:49 -08001982 mirror::Object* value = return_value->GetL();
Ian Rogers98379392014-02-24 16:53:16 -08001983 expandBufAdd1(pReply, TagFromObject(soa, value));
Jeff Hao579b0242013-11-18 13:16:49 -08001984 expandBufAddObjectId(pReply, gRegistry->Add(value));
1985 }
1986}
1987
Ian Rogersc0542af2014-09-03 16:16:56 -07001988JDWP::JdwpError Dbg::GetThreadName(JDWP::ObjectId thread_id, std::string* name) {
jeffhaoa77f0f62012-12-05 17:19:31 -08001989 ScopedObjectAccessUnchecked soa(Thread::Current());
1990 MutexLock mu(soa.Self(), *Locks::thread_list_lock_);
Ian Rogersc0542af2014-09-03 16:16:56 -07001991 JDWP::JdwpError error;
1992 Thread* thread = DecodeThread(soa, thread_id, &error);
1993 UNUSED(thread);
Elliott Hughes221229c2013-01-08 18:17:50 -08001994 if (error != JDWP::ERR_NONE && error != JDWP::ERR_THREAD_NOT_ALIVE) {
1995 return error;
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001996 }
Elliott Hughes221229c2013-01-08 18:17:50 -08001997
1998 // We still need to report the zombie threads' names, so we can't just call Thread::GetThreadName.
Ian Rogersc0542af2014-09-03 16:16:56 -07001999 mirror::Object* thread_object = gRegistry->Get<mirror::Object*>(thread_id, &error);
2000 CHECK(thread_object != nullptr) << error;
Brian Carlstromea46f952013-07-30 01:26:50 -07002001 mirror::ArtField* java_lang_Thread_name_field =
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002002 soa.DecodeField(WellKnownClasses::java_lang_Thread_name);
2003 mirror::String* s =
2004 reinterpret_cast<mirror::String*>(java_lang_Thread_name_field->GetObject(thread_object));
Ian Rogersc0542af2014-09-03 16:16:56 -07002005 if (s != nullptr) {
2006 *name = s->ToModifiedUtf8();
Elliott Hughes221229c2013-01-08 18:17:50 -08002007 }
2008 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002009}
2010
Elliott Hughes221229c2013-01-08 18:17:50 -08002011JDWP::JdwpError Dbg::GetThreadGroup(JDWP::ObjectId thread_id, JDWP::ExpandBuf* pReply) {
Sebastien Hertza06430c2014-09-15 19:21:30 +02002012 ScopedObjectAccessUnchecked soa(Thread::Current());
Ian Rogersc0542af2014-09-03 16:16:56 -07002013 JDWP::JdwpError error;
2014 mirror::Object* thread_object = gRegistry->Get<mirror::Object*>(thread_id, &error);
2015 if (error != JDWP::ERR_NONE) {
Elliott Hughes2435a572012-02-17 16:07:41 -08002016 return JDWP::ERR_INVALID_OBJECT;
2017 }
Mathieu Chartier2d5f39e2014-09-19 17:52:37 -07002018 ScopedAssertNoThreadSuspension ants(soa.Self(), "Debugger: GetThreadGroup");
Elliott Hughes2435a572012-02-17 16:07:41 -08002019 // Okay, so it's an object, but is it actually a thread?
Hiroshi Yamauchib5a9e3d2014-06-09 12:11:20 -07002020 {
2021 MutexLock mu(soa.Self(), *Locks::thread_list_lock_);
Ian Rogersc0542af2014-09-03 16:16:56 -07002022 Thread* thread = DecodeThread(soa, thread_id, &error);
2023 UNUSED(thread);
Hiroshi Yamauchib5a9e3d2014-06-09 12:11:20 -07002024 }
Elliott Hughes221229c2013-01-08 18:17:50 -08002025 if (error == JDWP::ERR_THREAD_NOT_ALIVE) {
2026 // Zombie threads are in the null group.
2027 expandBufAddObjectId(pReply, JDWP::ObjectId(0));
Sebastien Hertz52d131d2014-03-13 16:17:40 +01002028 error = JDWP::ERR_NONE;
2029 } else if (error == JDWP::ERR_NONE) {
2030 mirror::Class* c = soa.Decode<mirror::Class*>(WellKnownClasses::java_lang_Thread);
2031 CHECK(c != nullptr);
Sebastien Hertze49e1952014-10-13 11:27:13 +02002032 mirror::ArtField* f = soa.DecodeField(WellKnownClasses::java_lang_Thread_group);
Hiroshi Yamauchib5a9e3d2014-06-09 12:11:20 -07002033 CHECK(f != nullptr);
Sebastien Hertz52d131d2014-03-13 16:17:40 +01002034 mirror::Object* group = f->GetObject(thread_object);
Hiroshi Yamauchib5a9e3d2014-06-09 12:11:20 -07002035 CHECK(group != nullptr);
Sebastien Hertz52d131d2014-03-13 16:17:40 +01002036 JDWP::ObjectId thread_group_id = gRegistry->Add(group);
2037 expandBufAddObjectId(pReply, thread_group_id);
Elliott Hughes221229c2013-01-08 18:17:50 -08002038 }
Sebastien Hertz52d131d2014-03-13 16:17:40 +01002039 return error;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002040}
2041
Sebastien Hertza06430c2014-09-15 19:21:30 +02002042static mirror::Object* DecodeThreadGroup(ScopedObjectAccessUnchecked& soa,
2043 JDWP::ObjectId thread_group_id, JDWP::JdwpError* error)
2044 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Sebastien Hertz6995c602014-09-09 12:10:13 +02002045 mirror::Object* thread_group = Dbg::GetObjectRegistry()->Get<mirror::Object*>(thread_group_id,
2046 error);
Sebastien Hertza06430c2014-09-15 19:21:30 +02002047 if (*error != JDWP::ERR_NONE) {
2048 return nullptr;
2049 }
2050 if (thread_group == nullptr) {
2051 *error = JDWP::ERR_INVALID_OBJECT;
2052 return nullptr;
2053 }
Ian Rogers98379392014-02-24 16:53:16 -08002054 mirror::Class* c = soa.Decode<mirror::Class*>(WellKnownClasses::java_lang_ThreadGroup);
2055 CHECK(c != nullptr);
Sebastien Hertza06430c2014-09-15 19:21:30 +02002056 if (!c->IsAssignableFrom(thread_group->GetClass())) {
2057 // This is not a java.lang.ThreadGroup.
2058 *error = JDWP::ERR_INVALID_THREAD_GROUP;
2059 return nullptr;
2060 }
2061 *error = JDWP::ERR_NONE;
2062 return thread_group;
2063}
2064
2065JDWP::JdwpError Dbg::GetThreadGroupName(JDWP::ObjectId thread_group_id, JDWP::ExpandBuf* pReply) {
2066 ScopedObjectAccessUnchecked soa(Thread::Current());
2067 JDWP::JdwpError error;
2068 mirror::Object* thread_group = DecodeThreadGroup(soa, thread_group_id, &error);
2069 if (error != JDWP::ERR_NONE) {
2070 return error;
2071 }
Mathieu Chartier2d5f39e2014-09-19 17:52:37 -07002072 ScopedAssertNoThreadSuspension ants(soa.Self(), "Debugger: GetThreadGroupName");
Sebastien Hertze49e1952014-10-13 11:27:13 +02002073 mirror::ArtField* f = soa.DecodeField(WellKnownClasses::java_lang_ThreadGroup_name);
Ian Rogersc0542af2014-09-03 16:16:56 -07002074 CHECK(f != nullptr);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002075 mirror::String* s = reinterpret_cast<mirror::String*>(f->GetObject(thread_group));
Sebastien Hertza06430c2014-09-15 19:21:30 +02002076
2077 std::string thread_group_name(s->ToModifiedUtf8());
2078 expandBufAddUtf8String(pReply, thread_group_name);
2079 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002080}
2081
Sebastien Hertza06430c2014-09-15 19:21:30 +02002082JDWP::JdwpError Dbg::GetThreadGroupParent(JDWP::ObjectId thread_group_id, JDWP::ExpandBuf* pReply) {
Ian Rogers98379392014-02-24 16:53:16 -08002083 ScopedObjectAccessUnchecked soa(Thread::Current());
Ian Rogersc0542af2014-09-03 16:16:56 -07002084 JDWP::JdwpError error;
Sebastien Hertza06430c2014-09-15 19:21:30 +02002085 mirror::Object* thread_group = DecodeThreadGroup(soa, thread_group_id, &error);
2086 if (error != JDWP::ERR_NONE) {
2087 return error;
2088 }
Mathieu Chartier2d5f39e2014-09-19 17:52:37 -07002089 mirror::Object* parent;
2090 {
2091 ScopedAssertNoThreadSuspension ants(soa.Self(), "Debugger: GetThreadGroupParent");
Sebastien Hertze49e1952014-10-13 11:27:13 +02002092 mirror::ArtField* f = soa.DecodeField(WellKnownClasses::java_lang_ThreadGroup_parent);
Mathieu Chartier2d5f39e2014-09-19 17:52:37 -07002093 CHECK(f != nullptr);
2094 parent = f->GetObject(thread_group);
2095 }
Sebastien Hertza06430c2014-09-15 19:21:30 +02002096 JDWP::ObjectId parent_group_id = gRegistry->Add(parent);
2097 expandBufAddObjectId(pReply, parent_group_id);
2098 return JDWP::ERR_NONE;
2099}
2100
2101static void GetChildThreadGroups(ScopedObjectAccessUnchecked& soa, mirror::Object* thread_group,
2102 std::vector<JDWP::ObjectId>* child_thread_group_ids)
2103 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
2104 CHECK(thread_group != nullptr);
2105
2106 // Get the ArrayList<ThreadGroup> "groups" out of this thread group...
Sebastien Hertze49e1952014-10-13 11:27:13 +02002107 mirror::ArtField* groups_field = soa.DecodeField(WellKnownClasses::java_lang_ThreadGroup_groups);
Sebastien Hertza06430c2014-09-15 19:21:30 +02002108 mirror::Object* groups_array_list = groups_field->GetObject(thread_group);
Sebastien Hertze49e1952014-10-13 11:27:13 +02002109 {
2110 // The "groups" field is declared as a java.util.List: check it really is
2111 // an instance of java.util.ArrayList.
2112 CHECK(groups_array_list != nullptr);
2113 mirror::Class* java_util_ArrayList_class =
2114 soa.Decode<mirror::Class*>(WellKnownClasses::java_util_ArrayList);
2115 CHECK(groups_array_list->InstanceOf(java_util_ArrayList_class));
2116 }
Sebastien Hertza06430c2014-09-15 19:21:30 +02002117
2118 // Get the array and size out of the ArrayList<ThreadGroup>...
Sebastien Hertze49e1952014-10-13 11:27:13 +02002119 mirror::ArtField* array_field = soa.DecodeField(WellKnownClasses::java_util_ArrayList_array);
2120 mirror::ArtField* size_field = soa.DecodeField(WellKnownClasses::java_util_ArrayList_size);
Sebastien Hertza06430c2014-09-15 19:21:30 +02002121 mirror::ObjectArray<mirror::Object>* groups_array =
2122 array_field->GetObject(groups_array_list)->AsObjectArray<mirror::Object>();
2123 const int32_t size = size_field->GetInt(groups_array_list);
2124
2125 // Copy the first 'size' elements out of the array into the result.
Sebastien Hertz6995c602014-09-09 12:10:13 +02002126 ObjectRegistry* registry = Dbg::GetObjectRegistry();
Sebastien Hertza06430c2014-09-15 19:21:30 +02002127 for (int32_t i = 0; i < size; ++i) {
Sebastien Hertz6995c602014-09-09 12:10:13 +02002128 child_thread_group_ids->push_back(registry->Add(groups_array->Get(i)));
Sebastien Hertza06430c2014-09-15 19:21:30 +02002129 }
2130}
2131
2132JDWP::JdwpError Dbg::GetThreadGroupChildren(JDWP::ObjectId thread_group_id,
2133 JDWP::ExpandBuf* pReply) {
2134 ScopedObjectAccessUnchecked soa(Thread::Current());
2135 JDWP::JdwpError error;
2136 mirror::Object* thread_group = DecodeThreadGroup(soa, thread_group_id, &error);
2137 if (error != JDWP::ERR_NONE) {
2138 return error;
2139 }
2140
2141 // Add child threads.
2142 {
2143 std::vector<JDWP::ObjectId> child_thread_ids;
2144 GetThreads(thread_group, &child_thread_ids);
2145 expandBufAdd4BE(pReply, child_thread_ids.size());
2146 for (JDWP::ObjectId child_thread_id : child_thread_ids) {
2147 expandBufAddObjectId(pReply, child_thread_id);
2148 }
2149 }
2150
2151 // Add child thread groups.
2152 {
2153 std::vector<JDWP::ObjectId> child_thread_groups_ids;
2154 GetChildThreadGroups(soa, thread_group, &child_thread_groups_ids);
2155 expandBufAdd4BE(pReply, child_thread_groups_ids.size());
2156 for (JDWP::ObjectId child_thread_group_id : child_thread_groups_ids) {
2157 expandBufAddObjectId(pReply, child_thread_group_id);
2158 }
2159 }
2160
2161 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002162}
2163
2164JDWP::ObjectId Dbg::GetSystemThreadGroupId() {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002165 ScopedObjectAccessUnchecked soa(Thread::Current());
Brian Carlstromea46f952013-07-30 01:26:50 -07002166 mirror::ArtField* f = soa.DecodeField(WellKnownClasses::java_lang_ThreadGroup_systemThreadGroup);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002167 mirror::Object* group = f->GetObject(f->GetDeclaringClass());
Ian Rogers365c1022012-06-22 15:05:28 -07002168 return gRegistry->Add(group);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002169}
2170
Jeff Hao920af3e2013-08-28 15:46:38 -07002171JDWP::JdwpThreadStatus Dbg::ToJdwpThreadStatus(ThreadState state) {
2172 switch (state) {
2173 case kBlocked:
2174 return JDWP::TS_MONITOR;
2175 case kNative:
2176 case kRunnable:
2177 case kSuspended:
2178 return JDWP::TS_RUNNING;
2179 case kSleeping:
2180 return JDWP::TS_SLEEPING;
2181 case kStarting:
2182 case kTerminated:
2183 return JDWP::TS_ZOMBIE;
2184 case kTimedWaiting:
Sebastien Hertzbae182c2013-12-17 10:42:03 +01002185 case kWaitingForCheckPointsToRun:
Jeff Hao920af3e2013-08-28 15:46:38 -07002186 case kWaitingForDebuggerSend:
2187 case kWaitingForDebuggerSuspension:
2188 case kWaitingForDebuggerToAttach:
Sebastien Hertz138dbfc2013-12-04 18:15:25 +01002189 case kWaitingForDeoptimization:
Jeff Hao920af3e2013-08-28 15:46:38 -07002190 case kWaitingForGcToComplete:
Jeff Hao920af3e2013-08-28 15:46:38 -07002191 case kWaitingForJniOnLoad:
Sebastien Hertzbae182c2013-12-17 10:42:03 +01002192 case kWaitingForMethodTracingStart:
Jeff Hao920af3e2013-08-28 15:46:38 -07002193 case kWaitingForSignalCatcherOutput:
2194 case kWaitingInMainDebuggerLoop:
2195 case kWaitingInMainSignalCatcherLoop:
2196 case kWaitingPerformingGc:
2197 case kWaiting:
2198 return JDWP::TS_WAIT;
2199 // Don't add a 'default' here so the compiler can spot incompatible enum changes.
2200 }
2201 LOG(FATAL) << "Unknown thread state: " << state;
2202 return JDWP::TS_ZOMBIE;
2203}
2204
Sebastien Hertz52d131d2014-03-13 16:17:40 +01002205JDWP::JdwpError Dbg::GetThreadStatus(JDWP::ObjectId thread_id, JDWP::JdwpThreadStatus* pThreadStatus,
2206 JDWP::JdwpSuspendStatus* pSuspendStatus) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002207 ScopedObjectAccess soa(Thread::Current());
Elliott Hughes499c5132011-11-17 14:55:11 -08002208
Elliott Hughes9e0c1752013-01-09 14:02:58 -08002209 *pSuspendStatus = JDWP::SUSPEND_STATUS_NOT_SUSPENDED;
2210
Ian Rogers50b35e22012-10-04 10:09:15 -07002211 MutexLock mu(soa.Self(), *Locks::thread_list_lock_);
Ian Rogersc0542af2014-09-03 16:16:56 -07002212 JDWP::JdwpError error;
2213 Thread* thread = DecodeThread(soa, thread_id, &error);
Elliott Hughes221229c2013-01-08 18:17:50 -08002214 if (error != JDWP::ERR_NONE) {
2215 if (error == JDWP::ERR_THREAD_NOT_ALIVE) {
2216 *pThreadStatus = JDWP::TS_ZOMBIE;
Elliott Hughes221229c2013-01-08 18:17:50 -08002217 return JDWP::ERR_NONE;
2218 }
2219 return error;
Elliott Hughes499c5132011-11-17 14:55:11 -08002220 }
2221
Elliott Hughes9e0c1752013-01-09 14:02:58 -08002222 if (IsSuspendedForDebugger(soa, thread)) {
2223 *pSuspendStatus = JDWP::SUSPEND_STATUS_SUSPENDED;
Elliott Hughes499c5132011-11-17 14:55:11 -08002224 }
2225
Jeff Hao920af3e2013-08-28 15:46:38 -07002226 *pThreadStatus = ToJdwpThreadStatus(thread->GetState());
Elliott Hughes221229c2013-01-08 18:17:50 -08002227 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002228}
2229
Elliott Hughes221229c2013-01-08 18:17:50 -08002230JDWP::JdwpError Dbg::GetThreadDebugSuspendCount(JDWP::ObjectId thread_id, JDWP::ExpandBuf* pReply) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002231 ScopedObjectAccess soa(Thread::Current());
Ian Rogers50b35e22012-10-04 10:09:15 -07002232 MutexLock mu(soa.Self(), *Locks::thread_list_lock_);
Ian Rogersc0542af2014-09-03 16:16:56 -07002233 JDWP::JdwpError error;
2234 Thread* thread = DecodeThread(soa, thread_id, &error);
Elliott Hughes221229c2013-01-08 18:17:50 -08002235 if (error != JDWP::ERR_NONE) {
2236 return error;
Elliott Hughes2435a572012-02-17 16:07:41 -08002237 }
Ian Rogers50b35e22012-10-04 10:09:15 -07002238 MutexLock mu2(soa.Self(), *Locks::thread_suspend_count_lock_);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002239 expandBufAdd4BE(pReply, thread->GetDebugSuspendCount());
Elliott Hughes2435a572012-02-17 16:07:41 -08002240 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002241}
2242
Elliott Hughesf9501702013-01-11 11:22:27 -08002243JDWP::JdwpError Dbg::Interrupt(JDWP::ObjectId thread_id) {
2244 ScopedObjectAccess soa(Thread::Current());
2245 MutexLock mu(soa.Self(), *Locks::thread_list_lock_);
Ian Rogersc0542af2014-09-03 16:16:56 -07002246 JDWP::JdwpError error;
2247 Thread* thread = DecodeThread(soa, thread_id, &error);
Elliott Hughesf9501702013-01-11 11:22:27 -08002248 if (error != JDWP::ERR_NONE) {
2249 return error;
2250 }
Ian Rogersdd7624d2014-03-14 17:43:00 -07002251 thread->Interrupt(soa.Self());
Elliott Hughesf9501702013-01-11 11:22:27 -08002252 return JDWP::ERR_NONE;
2253}
2254
Sebastien Hertz070f7322014-09-09 12:08:49 +02002255static bool IsInDesiredThreadGroup(ScopedObjectAccessUnchecked& soa,
2256 mirror::Object* desired_thread_group, mirror::Object* peer)
2257 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
2258 // Do we want threads from all thread groups?
2259 if (desired_thread_group == nullptr) {
2260 return true;
2261 }
2262 mirror::ArtField* thread_group_field = soa.DecodeField(WellKnownClasses::java_lang_Thread_group);
2263 DCHECK(thread_group_field != nullptr);
2264 mirror::Object* group = thread_group_field->GetObject(peer);
2265 return (group == desired_thread_group);
2266}
2267
Sebastien Hertza06430c2014-09-15 19:21:30 +02002268void Dbg::GetThreads(mirror::Object* thread_group, std::vector<JDWP::ObjectId>* thread_ids) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002269 ScopedObjectAccessUnchecked soa(Thread::Current());
Sebastien Hertz070f7322014-09-09 12:08:49 +02002270 std::list<Thread*> all_threads_list;
2271 {
2272 MutexLock mu(Thread::Current(), *Locks::thread_list_lock_);
2273 all_threads_list = Runtime::Current()->GetThreadList()->GetList();
2274 }
2275 for (Thread* t : all_threads_list) {
2276 if (t == Dbg::GetDebugThread()) {
2277 // Skip the JDWP thread. Some debuggers get bent out of shape when they can't suspend and
2278 // query all threads, so it's easier if we just don't tell them about this thread.
2279 continue;
2280 }
2281 if (t->IsStillStarting()) {
2282 // This thread is being started (and has been registered in the thread list). However, it is
2283 // not completely started yet so we must ignore it.
2284 continue;
2285 }
2286 mirror::Object* peer = t->GetPeer();
2287 if (peer == nullptr) {
2288 // peer might be NULL if the thread is still starting up. We can't tell the debugger about
2289 // this thread yet.
2290 // TODO: if we identified threads to the debugger by their Thread*
2291 // rather than their peer's mirror::Object*, we could fix this.
2292 // Doing so might help us report ZOMBIE threads too.
2293 continue;
2294 }
2295 if (IsInDesiredThreadGroup(soa, thread_group, peer)) {
2296 thread_ids->push_back(gRegistry->Add(peer));
2297 }
2298 }
Elliott Hughescaf76542012-06-28 16:08:22 -07002299}
Elliott Hughesa2155262011-11-16 16:26:58 -08002300
Ian Rogersc0542af2014-09-03 16:16:56 -07002301static int GetStackDepth(Thread* thread) SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Ian Rogers0399dde2012-06-06 17:09:28 -07002302 struct CountStackDepthVisitor : public StackVisitor {
Andreas Gampe277ccbd2014-11-03 21:36:10 -08002303 explicit CountStackDepthVisitor(Thread* thread_in)
2304 : StackVisitor(thread_in, nullptr), depth(0) {}
Ian Rogers0399dde2012-06-06 17:09:28 -07002305
Elliott Hughes64f574f2013-02-20 14:57:12 -08002306 // TODO: Enable annotalysis. We know lock is held in constructor, but abstraction confuses
2307 // annotalysis.
2308 bool VisitFrame() NO_THREAD_SAFETY_ANALYSIS {
Ian Rogers0399dde2012-06-06 17:09:28 -07002309 if (!GetMethod()->IsRuntimeMethod()) {
Elliott Hughesf8a2df72011-12-01 12:19:54 -08002310 ++depth;
2311 }
Elliott Hughes530fa002012-03-12 11:44:49 -07002312 return true;
Elliott Hughesa2e54f62011-11-17 13:01:30 -08002313 }
2314 size_t depth;
2315 };
Elliott Hughes08fc03a2012-06-26 17:34:00 -07002316
Ian Rogers7a22fa62013-01-23 12:16:16 -08002317 CountStackDepthVisitor visitor(thread);
Ian Rogers0399dde2012-06-06 17:09:28 -07002318 visitor.WalkStack();
Elliott Hughesa2e54f62011-11-17 13:01:30 -08002319 return visitor.depth;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002320}
2321
Ian Rogersc0542af2014-09-03 16:16:56 -07002322JDWP::JdwpError Dbg::GetThreadFrameCount(JDWP::ObjectId thread_id, size_t* result) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002323 ScopedObjectAccess soa(Thread::Current());
jeffhaoa77f0f62012-12-05 17:19:31 -08002324 MutexLock mu(soa.Self(), *Locks::thread_list_lock_);
Ian Rogersc0542af2014-09-03 16:16:56 -07002325 JDWP::JdwpError error;
2326 *result = 0;
2327 Thread* thread = DecodeThread(soa, thread_id, &error);
Elliott Hughes221229c2013-01-08 18:17:50 -08002328 if (error != JDWP::ERR_NONE) {
2329 return error;
2330 }
Elliott Hughesf15f4a02013-01-09 10:09:38 -08002331 if (!IsSuspendedForDebugger(soa, thread)) {
2332 return JDWP::ERR_THREAD_NOT_SUSPENDED;
2333 }
Ian Rogersc0542af2014-09-03 16:16:56 -07002334 *result = GetStackDepth(thread);
Elliott Hughes221229c2013-01-08 18:17:50 -08002335 return JDWP::ERR_NONE;
Elliott Hughes86964332012-02-15 19:37:42 -08002336}
2337
Ian Rogers306057f2012-11-26 12:45:53 -08002338JDWP::JdwpError Dbg::GetThreadFrames(JDWP::ObjectId thread_id, size_t start_frame,
2339 size_t frame_count, JDWP::ExpandBuf* buf) {
Elliott Hughes6e9d22c2012-06-22 15:02:37 -07002340 class GetFrameVisitor : public StackVisitor {
2341 public:
Andreas Gampe277ccbd2014-11-03 21:36:10 -08002342 GetFrameVisitor(Thread* thread, size_t start_frame_in, size_t frame_count_in,
2343 JDWP::ExpandBuf* buf_in)
Ian Rogersb726dcb2012-09-05 08:57:23 -07002344 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_)
Ian Rogersc0542af2014-09-03 16:16:56 -07002345 : StackVisitor(thread, nullptr), depth_(0),
Andreas Gampe277ccbd2014-11-03 21:36:10 -08002346 start_frame_(start_frame_in), frame_count_(frame_count_in), buf_(buf_in) {
Elliott Hughes6e9d22c2012-06-22 15:02:37 -07002347 expandBufAdd4BE(buf_, frame_count_);
Elliott Hughes03181a82011-11-17 17:22:21 -08002348 }
Ian Rogers0399dde2012-06-06 17:09:28 -07002349
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002350 // TODO: Enable annotalysis. We know lock is held in constructor, but abstraction confuses
2351 // annotalysis.
2352 virtual bool VisitFrame() NO_THREAD_SAFETY_ANALYSIS {
Ian Rogers0399dde2012-06-06 17:09:28 -07002353 if (GetMethod()->IsRuntimeMethod()) {
Brian Carlstrom7934ac22013-07-26 10:54:15 -07002354 return true; // The debugger can't do anything useful with a frame that has no Method*.
Elliott Hughes03181a82011-11-17 17:22:21 -08002355 }
Elliott Hughes6e9d22c2012-06-22 15:02:37 -07002356 if (depth_ >= start_frame_ + frame_count_) {
Elliott Hughes530fa002012-03-12 11:44:49 -07002357 return false;
Elliott Hughes03181a82011-11-17 17:22:21 -08002358 }
Elliott Hughes6e9d22c2012-06-22 15:02:37 -07002359 if (depth_ >= start_frame_) {
2360 JDWP::FrameId frame_id(GetFrameId());
2361 JDWP::JdwpLocation location;
Sebastien Hertz6995c602014-09-09 12:10:13 +02002362 SetJdwpLocation(&location, GetMethod(), GetDexPc());
Ian Rogersef7d42f2014-01-06 12:55:46 -08002363 VLOG(jdwp) << StringPrintf(" Frame %3zd: id=%3" PRIu64 " ", depth_, frame_id) << location;
Elliott Hughes6e9d22c2012-06-22 15:02:37 -07002364 expandBufAdd8BE(buf_, frame_id);
2365 expandBufAddLocation(buf_, location);
2366 }
2367 ++depth_;
Elliott Hughes530fa002012-03-12 11:44:49 -07002368 return true;
Elliott Hughes03181a82011-11-17 17:22:21 -08002369 }
Elliott Hughes6e9d22c2012-06-22 15:02:37 -07002370
2371 private:
2372 size_t depth_;
2373 const size_t start_frame_;
2374 const size_t frame_count_;
2375 JDWP::ExpandBuf* buf_;
Elliott Hughes03181a82011-11-17 17:22:21 -08002376 };
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002377
2378 ScopedObjectAccessUnchecked soa(Thread::Current());
jeffhaoa77f0f62012-12-05 17:19:31 -08002379 MutexLock mu(soa.Self(), *Locks::thread_list_lock_);
Ian Rogersc0542af2014-09-03 16:16:56 -07002380 JDWP::JdwpError error;
2381 Thread* thread = DecodeThread(soa, thread_id, &error);
Elliott Hughes221229c2013-01-08 18:17:50 -08002382 if (error != JDWP::ERR_NONE) {
2383 return error;
2384 }
Elliott Hughesf15f4a02013-01-09 10:09:38 -08002385 if (!IsSuspendedForDebugger(soa, thread)) {
2386 return JDWP::ERR_THREAD_NOT_SUSPENDED;
2387 }
Ian Rogers7a22fa62013-01-23 12:16:16 -08002388 GetFrameVisitor visitor(thread, start_frame, frame_count, buf);
Ian Rogers0399dde2012-06-06 17:09:28 -07002389 visitor.WalkStack();
Elliott Hughes6e9d22c2012-06-22 15:02:37 -07002390 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002391}
2392
2393JDWP::ObjectId Dbg::GetThreadSelfId() {
Sebastien Hertz6995c602014-09-09 12:10:13 +02002394 return GetThreadId(Thread::Current());
2395}
2396
2397JDWP::ObjectId Dbg::GetThreadId(Thread* thread) {
Mathieu Chartierdbe6f462012-09-25 16:54:50 -07002398 ScopedObjectAccessUnchecked soa(Thread::Current());
Sebastien Hertz6995c602014-09-09 12:10:13 +02002399 return gRegistry->Add(thread->GetPeer());
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002400}
2401
Elliott Hughes475fc232011-10-25 15:00:35 -07002402void Dbg::SuspendVM() {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002403 Runtime::Current()->GetThreadList()->SuspendAllForDebugger();
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002404}
2405
2406void Dbg::ResumeVM() {
Sebastien Hertz253fa552014-10-14 17:27:15 +02002407 Runtime::Current()->GetThreadList()->ResumeAllForDebugger();
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002408}
2409
Elliott Hughes221229c2013-01-08 18:17:50 -08002410JDWP::JdwpError Dbg::SuspendThread(JDWP::ObjectId thread_id, bool request_suspension) {
Ian Rogersf3d874c2014-07-17 18:52:42 -07002411 Thread* self = Thread::Current();
Ian Rogersc0542af2014-09-03 16:16:56 -07002412 ScopedLocalRef<jobject> peer(self->GetJniEnv(), nullptr);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002413 {
Ian Rogersf3d874c2014-07-17 18:52:42 -07002414 ScopedObjectAccess soa(self);
Ian Rogersc0542af2014-09-03 16:16:56 -07002415 JDWP::JdwpError error;
2416 peer.reset(soa.AddLocalReference<jobject>(gRegistry->Get<mirror::Object*>(thread_id, &error)));
Elliott Hughes4e235312011-12-02 11:34:15 -08002417 }
Ian Rogersc0542af2014-09-03 16:16:56 -07002418 if (peer.get() == nullptr) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002419 return JDWP::ERR_THREAD_NOT_ALIVE;
2420 }
Ian Rogers4ad5cd32014-11-11 23:08:07 -08002421 // Suspend thread to build stack trace.
Elliott Hughesf327e072013-01-09 16:01:26 -08002422 bool timed_out;
Brian Carlstromba32de42014-08-27 23:43:46 -07002423 ThreadList* thread_list = Runtime::Current()->GetThreadList();
2424 Thread* thread = thread_list->SuspendThreadByPeer(peer.get(), request_suspension, true,
2425 &timed_out);
Ian Rogersc0542af2014-09-03 16:16:56 -07002426 if (thread != nullptr) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002427 return JDWP::ERR_NONE;
Elliott Hughesf327e072013-01-09 16:01:26 -08002428 } else if (timed_out) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002429 return JDWP::ERR_INTERNAL;
2430 } else {
2431 return JDWP::ERR_THREAD_NOT_ALIVE;
2432 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002433}
2434
Elliott Hughes221229c2013-01-08 18:17:50 -08002435void Dbg::ResumeThread(JDWP::ObjectId thread_id) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002436 ScopedObjectAccessUnchecked soa(Thread::Current());
Ian Rogersc0542af2014-09-03 16:16:56 -07002437 JDWP::JdwpError error;
2438 mirror::Object* peer = gRegistry->Get<mirror::Object*>(thread_id, &error);
2439 CHECK(peer != nullptr) << error;
jeffhaoa77f0f62012-12-05 17:19:31 -08002440 Thread* thread;
2441 {
2442 MutexLock mu(soa.Self(), *Locks::thread_list_lock_);
2443 thread = Thread::FromManagedThread(soa, peer);
2444 }
Ian Rogersc0542af2014-09-03 16:16:56 -07002445 if (thread == nullptr) {
Elliott Hughes4e235312011-12-02 11:34:15 -08002446 LOG(WARNING) << "No such thread for resume: " << peer;
2447 return;
2448 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002449 bool needs_resume;
2450 {
Ian Rogers50b35e22012-10-04 10:09:15 -07002451 MutexLock mu2(soa.Self(), *Locks::thread_suspend_count_lock_);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002452 needs_resume = thread->GetSuspendCount() > 0;
2453 }
2454 if (needs_resume) {
Elliott Hughes546b9862012-06-20 16:06:13 -07002455 Runtime::Current()->GetThreadList()->Resume(thread, true);
2456 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002457}
2458
2459void Dbg::SuspendSelf() {
Elliott Hughes475fc232011-10-25 15:00:35 -07002460 Runtime::Current()->GetThreadList()->SuspendSelfForDebugger();
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002461}
2462
Ian Rogers0399dde2012-06-06 17:09:28 -07002463struct GetThisVisitor : public StackVisitor {
Andreas Gampe277ccbd2014-11-03 21:36:10 -08002464 GetThisVisitor(Thread* thread, Context* context, JDWP::FrameId frame_id_in)
Ian Rogersb726dcb2012-09-05 08:57:23 -07002465 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_)
Andreas Gampe277ccbd2014-11-03 21:36:10 -08002466 : StackVisitor(thread, context), this_object(nullptr), frame_id(frame_id_in) {}
Ian Rogers0399dde2012-06-06 17:09:28 -07002467
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002468 // TODO: Enable annotalysis. We know lock is held in constructor, but abstraction confuses
2469 // annotalysis.
2470 virtual bool VisitFrame() NO_THREAD_SAFETY_ANALYSIS {
Elliott Hughes6e9d22c2012-06-22 15:02:37 -07002471 if (frame_id != GetFrameId()) {
Ian Rogers0399dde2012-06-06 17:09:28 -07002472 return true; // continue
Ian Rogers0399dde2012-06-06 17:09:28 -07002473 } else {
Ian Rogers62d6c772013-02-27 08:32:07 -08002474 this_object = GetThisObject();
2475 return false;
Ian Rogers0399dde2012-06-06 17:09:28 -07002476 }
Elliott Hughes86b00102011-12-05 17:54:26 -08002477 }
Ian Rogers0399dde2012-06-06 17:09:28 -07002478
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002479 mirror::Object* this_object;
Elliott Hughes6e9d22c2012-06-22 15:02:37 -07002480 JDWP::FrameId frame_id;
Ian Rogers0399dde2012-06-06 17:09:28 -07002481};
2482
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002483JDWP::JdwpError Dbg::GetThisObject(JDWP::ObjectId thread_id, JDWP::FrameId frame_id,
2484 JDWP::ObjectId* result) {
2485 ScopedObjectAccessUnchecked soa(Thread::Current());
2486 Thread* thread;
2487 {
Ian Rogers50b35e22012-10-04 10:09:15 -07002488 MutexLock mu(soa.Self(), *Locks::thread_list_lock_);
Ian Rogersc0542af2014-09-03 16:16:56 -07002489 JDWP::JdwpError error;
2490 thread = DecodeThread(soa, thread_id, &error);
Elliott Hughes221229c2013-01-08 18:17:50 -08002491 if (error != JDWP::ERR_NONE) {
2492 return error;
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002493 }
Elliott Hughes9e0c1752013-01-09 14:02:58 -08002494 if (!IsSuspendedForDebugger(soa, thread)) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002495 return JDWP::ERR_THREAD_NOT_SUSPENDED;
2496 }
Elliott Hughes6e9d22c2012-06-22 15:02:37 -07002497 }
Ian Rogers700a4022014-05-19 16:49:03 -07002498 std::unique_ptr<Context> context(Context::Create());
Ian Rogers7a22fa62013-01-23 12:16:16 -08002499 GetThisVisitor visitor(thread, context.get(), frame_id);
Ian Rogers0399dde2012-06-06 17:09:28 -07002500 visitor.WalkStack();
Elliott Hughes6e9d22c2012-06-22 15:02:37 -07002501 *result = gRegistry->Add(visitor.this_object);
2502 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002503}
2504
Sebastien Hertz8009f392014-09-01 17:07:11 +02002505// Walks the stack until we find the frame with the given FrameId.
2506class FindFrameVisitor FINAL : public StackVisitor {
2507 public:
2508 FindFrameVisitor(Thread* thread, Context* context, JDWP::FrameId frame_id)
2509 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_)
2510 : StackVisitor(thread, context), frame_id_(frame_id), error_(JDWP::ERR_INVALID_FRAMEID) {}
Ian Rogersca190662012-06-26 15:45:57 -07002511
Sebastien Hertz8009f392014-09-01 17:07:11 +02002512 // TODO: Enable annotalysis. We know lock is held in constructor, but abstraction confuses
2513 // annotalysis.
2514 bool VisitFrame() NO_THREAD_SAFETY_ANALYSIS {
2515 if (GetFrameId() != frame_id_) {
2516 return true; // Not our frame, carry on.
Ian Rogers0399dde2012-06-06 17:09:28 -07002517 }
Sebastien Hertz8009f392014-09-01 17:07:11 +02002518 mirror::ArtMethod* m = GetMethod();
2519 if (m->IsNative()) {
2520 // We can't read/write local value from/into native method.
2521 error_ = JDWP::ERR_OPAQUE_FRAME;
2522 } else {
2523 // We found our frame.
2524 error_ = JDWP::ERR_NONE;
2525 }
2526 return false;
2527 }
2528
2529 JDWP::JdwpError GetError() const {
2530 return error_;
2531 }
2532
2533 private:
2534 const JDWP::FrameId frame_id_;
2535 JDWP::JdwpError error_;
2536};
2537
2538JDWP::JdwpError Dbg::GetLocalValues(JDWP::Request* request, JDWP::ExpandBuf* pReply) {
2539 JDWP::ObjectId thread_id = request->ReadThreadId();
2540 JDWP::FrameId frame_id = request->ReadFrameId();
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002541
2542 ScopedObjectAccessUnchecked soa(Thread::Current());
Sebastien Hertz8009f392014-09-01 17:07:11 +02002543 Thread* thread;
2544 {
2545 MutexLock mu(soa.Self(), *Locks::thread_list_lock_);
2546 JDWP::JdwpError error;
2547 thread = DecodeThread(soa, thread_id, &error);
2548 if (error != JDWP::ERR_NONE) {
2549 return error;
2550 }
Elliott Hughes221229c2013-01-08 18:17:50 -08002551 }
Sebastien Hertz8009f392014-09-01 17:07:11 +02002552 // Find the frame with the given frame_id.
Ian Rogers700a4022014-05-19 16:49:03 -07002553 std::unique_ptr<Context> context(Context::Create());
Sebastien Hertz8009f392014-09-01 17:07:11 +02002554 FindFrameVisitor visitor(thread, context.get(), frame_id);
Ian Rogers0399dde2012-06-06 17:09:28 -07002555 visitor.WalkStack();
Sebastien Hertz8009f392014-09-01 17:07:11 +02002556 if (visitor.GetError() != JDWP::ERR_NONE) {
2557 return visitor.GetError();
2558 }
2559
2560 // Read the values from visitor's context.
2561 int32_t slot_count = request->ReadSigned32("slot count");
2562 expandBufAdd4BE(pReply, slot_count); /* "int values" */
2563 for (int32_t i = 0; i < slot_count; ++i) {
2564 uint32_t slot = request->ReadUnsigned32("slot");
2565 JDWP::JdwpTag reqSigByte = request->ReadTag();
2566
2567 VLOG(jdwp) << " --> slot " << slot << " " << reqSigByte;
2568
2569 size_t width = Dbg::GetTagWidth(reqSigByte);
Sebastien Hertz7d955652014-10-22 10:57:10 +02002570 uint8_t* ptr = expandBufAddSpace(pReply, width + 1);
Sebastien Hertz8009f392014-09-01 17:07:11 +02002571 JDWP::JdwpError error = Dbg::GetLocalValue(visitor, soa, slot, reqSigByte, ptr, width);
2572 if (error != JDWP::ERR_NONE) {
2573 return error;
2574 }
2575 }
2576 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002577}
2578
Sebastien Hertz8009f392014-09-01 17:07:11 +02002579JDWP::JdwpError Dbg::GetLocalValue(const StackVisitor& visitor, ScopedObjectAccessUnchecked& soa,
2580 int slot, JDWP::JdwpTag tag, uint8_t* buf, size_t width) {
2581 mirror::ArtMethod* m = visitor.GetMethod();
2582 uint16_t reg = DemangleSlot(slot, m);
2583 // TODO: check that the tag is compatible with the actual type of the slot!
2584 // TODO: check slot is valid for this method or return INVALID_SLOT error.
2585 constexpr JDWP::JdwpError kFailureErrorCode = JDWP::ERR_ABSENT_INFORMATION;
2586 switch (tag) {
2587 case JDWP::JT_BOOLEAN: {
2588 CHECK_EQ(width, 1U);
2589 uint32_t intVal;
2590 if (visitor.GetVReg(m, reg, kIntVReg, &intVal)) {
2591 VLOG(jdwp) << "get boolean local " << reg << " = " << intVal;
2592 JDWP::Set1(buf + 1, intVal != 0);
2593 } else {
2594 VLOG(jdwp) << "failed to get boolean local " << reg;
2595 return kFailureErrorCode;
Ian Rogers0399dde2012-06-06 17:09:28 -07002596 }
Sebastien Hertz8009f392014-09-01 17:07:11 +02002597 break;
Ian Rogers0399dde2012-06-06 17:09:28 -07002598 }
Sebastien Hertz8009f392014-09-01 17:07:11 +02002599 case JDWP::JT_BYTE: {
2600 CHECK_EQ(width, 1U);
2601 uint32_t intVal;
2602 if (visitor.GetVReg(m, reg, kIntVReg, &intVal)) {
2603 VLOG(jdwp) << "get byte local " << reg << " = " << intVal;
2604 JDWP::Set1(buf + 1, intVal);
2605 } else {
2606 VLOG(jdwp) << "failed to get byte local " << reg;
2607 return kFailureErrorCode;
2608 }
2609 break;
2610 }
2611 case JDWP::JT_SHORT:
2612 case JDWP::JT_CHAR: {
2613 CHECK_EQ(width, 2U);
2614 uint32_t intVal;
2615 if (visitor.GetVReg(m, reg, kIntVReg, &intVal)) {
2616 VLOG(jdwp) << "get short/char local " << reg << " = " << intVal;
2617 JDWP::Set2BE(buf + 1, intVal);
2618 } else {
2619 VLOG(jdwp) << "failed to get short/char local " << reg;
2620 return kFailureErrorCode;
2621 }
2622 break;
2623 }
2624 case JDWP::JT_INT: {
2625 CHECK_EQ(width, 4U);
2626 uint32_t intVal;
2627 if (visitor.GetVReg(m, reg, kIntVReg, &intVal)) {
2628 VLOG(jdwp) << "get int local " << reg << " = " << intVal;
2629 JDWP::Set4BE(buf + 1, intVal);
2630 } else {
2631 VLOG(jdwp) << "failed to get int local " << reg;
2632 return kFailureErrorCode;
2633 }
2634 break;
2635 }
2636 case JDWP::JT_FLOAT: {
2637 CHECK_EQ(width, 4U);
2638 uint32_t intVal;
2639 if (visitor.GetVReg(m, reg, kFloatVReg, &intVal)) {
2640 VLOG(jdwp) << "get float local " << reg << " = " << intVal;
2641 JDWP::Set4BE(buf + 1, intVal);
2642 } else {
2643 VLOG(jdwp) << "failed to get float local " << reg;
2644 return kFailureErrorCode;
2645 }
2646 break;
2647 }
2648 case JDWP::JT_ARRAY:
2649 case JDWP::JT_CLASS_LOADER:
2650 case JDWP::JT_CLASS_OBJECT:
2651 case JDWP::JT_OBJECT:
2652 case JDWP::JT_STRING:
2653 case JDWP::JT_THREAD:
2654 case JDWP::JT_THREAD_GROUP: {
2655 CHECK_EQ(width, sizeof(JDWP::ObjectId));
2656 uint32_t intVal;
2657 if (visitor.GetVReg(m, reg, kReferenceVReg, &intVal)) {
2658 mirror::Object* o = reinterpret_cast<mirror::Object*>(intVal);
2659 VLOG(jdwp) << "get " << tag << " object local " << reg << " = " << o;
2660 if (!Runtime::Current()->GetHeap()->IsValidObjectAddress(o)) {
2661 LOG(FATAL) << "Register " << reg << " expected to hold " << tag << " object: " << o;
2662 }
2663 tag = TagFromObject(soa, o);
2664 JDWP::SetObjectId(buf + 1, gRegistry->Add(o));
2665 } else {
2666 VLOG(jdwp) << "failed to get " << tag << " object local " << reg;
2667 return kFailureErrorCode;
2668 }
2669 break;
2670 }
2671 case JDWP::JT_DOUBLE: {
2672 CHECK_EQ(width, 8U);
2673 uint64_t longVal;
2674 if (visitor.GetVRegPair(m, reg, kDoubleLoVReg, kDoubleHiVReg, &longVal)) {
2675 VLOG(jdwp) << "get double local " << reg << " = " << longVal;
2676 JDWP::Set8BE(buf + 1, longVal);
2677 } else {
2678 VLOG(jdwp) << "failed to get double local " << reg;
2679 return kFailureErrorCode;
2680 }
2681 break;
2682 }
2683 case JDWP::JT_LONG: {
2684 CHECK_EQ(width, 8U);
2685 uint64_t longVal;
2686 if (visitor.GetVRegPair(m, reg, kLongLoVReg, kLongHiVReg, &longVal)) {
2687 VLOG(jdwp) << "get long local " << reg << " = " << longVal;
2688 JDWP::Set8BE(buf + 1, longVal);
2689 } else {
2690 VLOG(jdwp) << "failed to get long local " << reg;
2691 return kFailureErrorCode;
2692 }
2693 break;
2694 }
2695 default:
2696 LOG(FATAL) << "Unknown tag " << tag;
2697 break;
2698 }
Ian Rogers0399dde2012-06-06 17:09:28 -07002699
Sebastien Hertz8009f392014-09-01 17:07:11 +02002700 // Prepend tag, which may have been updated.
2701 JDWP::Set1(buf, tag);
2702 return JDWP::ERR_NONE;
2703}
2704
2705JDWP::JdwpError Dbg::SetLocalValues(JDWP::Request* request) {
2706 JDWP::ObjectId thread_id = request->ReadThreadId();
2707 JDWP::FrameId frame_id = request->ReadFrameId();
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002708
2709 ScopedObjectAccessUnchecked soa(Thread::Current());
Sebastien Hertz8009f392014-09-01 17:07:11 +02002710 Thread* thread;
2711 {
2712 MutexLock mu(soa.Self(), *Locks::thread_list_lock_);
2713 JDWP::JdwpError error;
2714 thread = DecodeThread(soa, thread_id, &error);
2715 if (error != JDWP::ERR_NONE) {
2716 return error;
2717 }
Elliott Hughes221229c2013-01-08 18:17:50 -08002718 }
Sebastien Hertz8009f392014-09-01 17:07:11 +02002719 // Find the frame with the given frame_id.
Ian Rogers700a4022014-05-19 16:49:03 -07002720 std::unique_ptr<Context> context(Context::Create());
Sebastien Hertz8009f392014-09-01 17:07:11 +02002721 FindFrameVisitor visitor(thread, context.get(), frame_id);
Ian Rogers0399dde2012-06-06 17:09:28 -07002722 visitor.WalkStack();
Sebastien Hertz8009f392014-09-01 17:07:11 +02002723 if (visitor.GetError() != JDWP::ERR_NONE) {
2724 return visitor.GetError();
2725 }
2726
2727 // Writes the values into visitor's context.
2728 int32_t slot_count = request->ReadSigned32("slot count");
2729 for (int32_t i = 0; i < slot_count; ++i) {
2730 uint32_t slot = request->ReadUnsigned32("slot");
2731 JDWP::JdwpTag sigByte = request->ReadTag();
2732 size_t width = Dbg::GetTagWidth(sigByte);
2733 uint64_t value = request->ReadValue(width);
2734
2735 VLOG(jdwp) << " --> slot " << slot << " " << sigByte << " " << value;
2736 JDWP::JdwpError error = Dbg::SetLocalValue(visitor, slot, sigByte, value, width);
2737 if (error != JDWP::ERR_NONE) {
2738 return error;
2739 }
2740 }
2741 return JDWP::ERR_NONE;
2742}
2743
2744JDWP::JdwpError Dbg::SetLocalValue(StackVisitor& visitor, int slot, JDWP::JdwpTag tag,
2745 uint64_t value, size_t width) {
2746 mirror::ArtMethod* m = visitor.GetMethod();
2747 uint16_t reg = DemangleSlot(slot, m);
2748 // TODO: check that the tag is compatible with the actual type of the slot!
2749 // TODO: check slot is valid for this method or return INVALID_SLOT error.
2750 constexpr JDWP::JdwpError kFailureErrorCode = JDWP::ERR_ABSENT_INFORMATION;
2751 switch (tag) {
2752 case JDWP::JT_BOOLEAN:
2753 case JDWP::JT_BYTE:
2754 CHECK_EQ(width, 1U);
2755 if (!visitor.SetVReg(m, reg, static_cast<uint32_t>(value), kIntVReg)) {
2756 VLOG(jdwp) << "failed to set boolean/byte local " << reg << " = "
2757 << static_cast<uint32_t>(value);
2758 return kFailureErrorCode;
2759 }
2760 break;
2761 case JDWP::JT_SHORT:
2762 case JDWP::JT_CHAR:
2763 CHECK_EQ(width, 2U);
2764 if (!visitor.SetVReg(m, reg, static_cast<uint32_t>(value), kIntVReg)) {
2765 VLOG(jdwp) << "failed to set short/char local " << reg << " = "
2766 << static_cast<uint32_t>(value);
2767 return kFailureErrorCode;
2768 }
2769 break;
2770 case JDWP::JT_INT:
2771 CHECK_EQ(width, 4U);
2772 if (!visitor.SetVReg(m, reg, static_cast<uint32_t>(value), kIntVReg)) {
2773 VLOG(jdwp) << "failed to set int local " << reg << " = "
2774 << static_cast<uint32_t>(value);
2775 return kFailureErrorCode;
2776 }
2777 break;
2778 case JDWP::JT_FLOAT:
2779 CHECK_EQ(width, 4U);
2780 if (!visitor.SetVReg(m, reg, static_cast<uint32_t>(value), kFloatVReg)) {
2781 VLOG(jdwp) << "failed to set float local " << reg << " = "
2782 << static_cast<uint32_t>(value);
2783 return kFailureErrorCode;
2784 }
2785 break;
2786 case JDWP::JT_ARRAY:
2787 case JDWP::JT_CLASS_LOADER:
2788 case JDWP::JT_CLASS_OBJECT:
2789 case JDWP::JT_OBJECT:
2790 case JDWP::JT_STRING:
2791 case JDWP::JT_THREAD:
2792 case JDWP::JT_THREAD_GROUP: {
2793 CHECK_EQ(width, sizeof(JDWP::ObjectId));
2794 JDWP::JdwpError error;
2795 mirror::Object* o = gRegistry->Get<mirror::Object*>(static_cast<JDWP::ObjectId>(value),
2796 &error);
2797 if (error != JDWP::ERR_NONE) {
2798 VLOG(jdwp) << tag << " object " << o << " is an invalid object";
2799 return JDWP::ERR_INVALID_OBJECT;
2800 } else if (!visitor.SetVReg(m, reg, static_cast<uint32_t>(reinterpret_cast<uintptr_t>(o)),
2801 kReferenceVReg)) {
2802 VLOG(jdwp) << "failed to set " << tag << " object local " << reg << " = " << o;
2803 return kFailureErrorCode;
2804 }
2805 break;
2806 }
2807 case JDWP::JT_DOUBLE: {
2808 CHECK_EQ(width, 8U);
2809 if (!visitor.SetVRegPair(m, reg, value, kDoubleLoVReg, kDoubleHiVReg)) {
2810 VLOG(jdwp) << "failed to set double local " << reg << " = " << value;
2811 return kFailureErrorCode;
2812 }
2813 break;
2814 }
2815 case JDWP::JT_LONG: {
2816 CHECK_EQ(width, 8U);
2817 if (!visitor.SetVRegPair(m, reg, value, kLongLoVReg, kLongHiVReg)) {
2818 VLOG(jdwp) << "failed to set double local " << reg << " = " << value;
2819 return kFailureErrorCode;
2820 }
2821 break;
2822 }
2823 default:
2824 LOG(FATAL) << "Unknown tag " << tag;
2825 break;
2826 }
2827 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002828}
2829
Sebastien Hertz6995c602014-09-09 12:10:13 +02002830static void SetEventLocation(JDWP::EventLocation* location, mirror::ArtMethod* m, uint32_t dex_pc)
2831 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
2832 DCHECK(location != nullptr);
2833 if (m == nullptr) {
2834 memset(location, 0, sizeof(*location));
2835 } else {
2836 location->method = m;
2837 location->dex_pc = (m->IsNative() || m->IsProxyMethod()) ? static_cast<uint32_t>(-1) : dex_pc;
Sebastien Hertz3f52eaf2014-04-04 17:50:18 +02002838 }
Sebastien Hertz3f52eaf2014-04-04 17:50:18 +02002839}
2840
Ian Rogersef7d42f2014-01-06 12:55:46 -08002841void Dbg::PostLocationEvent(mirror::ArtMethod* m, int dex_pc, mirror::Object* this_object,
Jeff Hao579b0242013-11-18 13:16:49 -08002842 int event_flags, const JValue* return_value) {
Sebastien Hertz3f52eaf2014-04-04 17:50:18 +02002843 if (!IsDebuggerActive()) {
2844 return;
2845 }
2846 DCHECK(m != nullptr);
2847 DCHECK_EQ(m->IsStatic(), this_object == nullptr);
Sebastien Hertz6995c602014-09-09 12:10:13 +02002848 JDWP::EventLocation location;
2849 SetEventLocation(&location, m, dex_pc);
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08002850
Sebastien Hertz6995c602014-09-09 12:10:13 +02002851 gJdwpState->PostLocationEvent(&location, this_object, event_flags, return_value);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002852}
2853
Sebastien Hertz3f52eaf2014-04-04 17:50:18 +02002854void Dbg::PostFieldAccessEvent(mirror::ArtMethod* m, int dex_pc,
2855 mirror::Object* this_object, mirror::ArtField* f) {
2856 if (!IsDebuggerActive()) {
2857 return;
2858 }
2859 DCHECK(m != nullptr);
2860 DCHECK(f != nullptr);
Sebastien Hertz6995c602014-09-09 12:10:13 +02002861 JDWP::EventLocation location;
2862 SetEventLocation(&location, m, dex_pc);
Sebastien Hertz3f52eaf2014-04-04 17:50:18 +02002863
Sebastien Hertz6995c602014-09-09 12:10:13 +02002864 gJdwpState->PostFieldEvent(&location, f, this_object, nullptr, false);
Sebastien Hertz3f52eaf2014-04-04 17:50:18 +02002865}
2866
2867void Dbg::PostFieldModificationEvent(mirror::ArtMethod* m, int dex_pc,
2868 mirror::Object* this_object, mirror::ArtField* f,
2869 const JValue* field_value) {
2870 if (!IsDebuggerActive()) {
2871 return;
2872 }
2873 DCHECK(m != nullptr);
2874 DCHECK(f != nullptr);
2875 DCHECK(field_value != nullptr);
Sebastien Hertz6995c602014-09-09 12:10:13 +02002876 JDWP::EventLocation location;
2877 SetEventLocation(&location, m, dex_pc);
Sebastien Hertz3f52eaf2014-04-04 17:50:18 +02002878
Sebastien Hertz6995c602014-09-09 12:10:13 +02002879 gJdwpState->PostFieldEvent(&location, f, this_object, field_value, true);
Sebastien Hertz3f52eaf2014-04-04 17:50:18 +02002880}
2881
2882void Dbg::PostException(const ThrowLocation& throw_location,
Brian Carlstromea46f952013-07-30 01:26:50 -07002883 mirror::ArtMethod* catch_method,
Elliott Hughes64f574f2013-02-20 14:57:12 -08002884 uint32_t catch_dex_pc, mirror::Throwable* exception_object) {
Elliott Hughesc0f09332012-03-26 13:27:06 -07002885 if (!IsDebuggerActive()) {
Ian Rogers0ad5bb82011-12-07 10:16:32 -08002886 return;
2887 }
Sebastien Hertz6995c602014-09-09 12:10:13 +02002888 JDWP::EventLocation exception_throw_location;
2889 SetEventLocation(&exception_throw_location, throw_location.GetMethod(), throw_location.GetDexPc());
2890 JDWP::EventLocation exception_catch_location;
2891 SetEventLocation(&exception_catch_location, catch_method, catch_dex_pc);
Elliott Hughes4740cdf2011-12-07 14:07:12 -08002892
Sebastien Hertz6995c602014-09-09 12:10:13 +02002893 gJdwpState->PostException(&exception_throw_location, exception_object, &exception_catch_location,
2894 throw_location.GetThis());
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002895}
2896
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002897void Dbg::PostClassPrepare(mirror::Class* c) {
Elliott Hughesc0f09332012-03-26 13:27:06 -07002898 if (!IsDebuggerActive()) {
Elliott Hughes4740cdf2011-12-07 14:07:12 -08002899 return;
2900 }
Sebastien Hertz6995c602014-09-09 12:10:13 +02002901 gJdwpState->PostClassPrepare(c);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002902}
2903
Ian Rogers62d6c772013-02-27 08:32:07 -08002904void Dbg::UpdateDebugger(Thread* thread, mirror::Object* this_object,
Sebastien Hertz8379b222014-02-24 17:38:15 +01002905 mirror::ArtMethod* m, uint32_t dex_pc,
2906 int event_flags, const JValue* return_value) {
Ian Rogers62d6c772013-02-27 08:32:07 -08002907 if (!IsDebuggerActive() || dex_pc == static_cast<uint32_t>(-2) /* fake method exit */) {
Elliott Hughes2aa2e392012-02-17 17:15:43 -08002908 return;
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08002909 }
2910
Elliott Hughes86964332012-02-15 19:37:42 -08002911 if (IsBreakpoint(m, dex_pc)) {
2912 event_flags |= kBreakpoint;
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08002913 }
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08002914
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01002915 // If the debugger is single-stepping one of our threads, check to
2916 // see if we're that thread and we've reached a step point.
2917 const SingleStepControl* single_step_control = thread->GetSingleStepControl();
2918 DCHECK(single_step_control != nullptr);
2919 if (single_step_control->is_active) {
2920 CHECK(!m->IsNative());
2921 if (single_step_control->step_depth == JDWP::SD_INTO) {
2922 // Step into method calls. We break when the line number
2923 // or method pointer changes. If we're in SS_MIN mode, we
2924 // always stop.
2925 if (single_step_control->method != m) {
2926 event_flags |= kSingleStep;
2927 VLOG(jdwp) << "SS new method";
2928 } else if (single_step_control->step_size == JDWP::SS_MIN) {
2929 event_flags |= kSingleStep;
2930 VLOG(jdwp) << "SS new instruction";
Sebastien Hertzbb43b432014-04-14 11:59:08 +02002931 } else if (single_step_control->ContainsDexPc(dex_pc)) {
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01002932 event_flags |= kSingleStep;
2933 VLOG(jdwp) << "SS new line";
2934 }
2935 } else if (single_step_control->step_depth == JDWP::SD_OVER) {
2936 // Step over method calls. We break when the line number is
2937 // different and the frame depth is <= the original frame
2938 // depth. (We can't just compare on the method, because we
2939 // might get unrolled past it by an exception, and it's tricky
2940 // to identify recursion.)
2941
2942 int stack_depth = GetStackDepth(thread);
2943
2944 if (stack_depth < single_step_control->stack_depth) {
2945 // Popped up one or more frames, always trigger.
2946 event_flags |= kSingleStep;
2947 VLOG(jdwp) << "SS method pop";
2948 } else if (stack_depth == single_step_control->stack_depth) {
2949 // Same depth, see if we moved.
2950 if (single_step_control->step_size == JDWP::SS_MIN) {
Elliott Hughes86964332012-02-15 19:37:42 -08002951 event_flags |= kSingleStep;
2952 VLOG(jdwp) << "SS new instruction";
Sebastien Hertzbb43b432014-04-14 11:59:08 +02002953 } else if (single_step_control->ContainsDexPc(dex_pc)) {
Elliott Hughes2435a572012-02-17 16:07:41 -08002954 event_flags |= kSingleStep;
2955 VLOG(jdwp) << "SS new line";
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08002956 }
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01002957 }
2958 } else {
2959 CHECK_EQ(single_step_control->step_depth, JDWP::SD_OUT);
2960 // Return from the current method. We break when the frame
2961 // depth pops up.
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08002962
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01002963 // This differs from the "method exit" break in that it stops
2964 // with the PC at the next instruction in the returned-to
2965 // function, rather than the end of the returning function.
Elliott Hughes86964332012-02-15 19:37:42 -08002966
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01002967 int stack_depth = GetStackDepth(thread);
2968 if (stack_depth < single_step_control->stack_depth) {
2969 event_flags |= kSingleStep;
2970 VLOG(jdwp) << "SS method pop";
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08002971 }
2972 }
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08002973 }
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08002974
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08002975 // If there's something interesting going on, see if it matches one
2976 // of the debugger filters.
2977 if (event_flags != 0) {
Sebastien Hertz8379b222014-02-24 17:38:15 +01002978 Dbg::PostLocationEvent(m, dex_pc, this_object, event_flags, return_value);
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08002979 }
2980}
2981
Sebastien Hertz42cd43f2014-05-13 14:15:41 +02002982size_t* Dbg::GetReferenceCounterForEvent(uint32_t instrumentation_event) {
2983 switch (instrumentation_event) {
2984 case instrumentation::Instrumentation::kMethodEntered:
2985 return &method_enter_event_ref_count_;
2986 case instrumentation::Instrumentation::kMethodExited:
2987 return &method_exit_event_ref_count_;
2988 case instrumentation::Instrumentation::kDexPcMoved:
2989 return &dex_pc_change_event_ref_count_;
2990 case instrumentation::Instrumentation::kFieldRead:
2991 return &field_read_event_ref_count_;
2992 case instrumentation::Instrumentation::kFieldWritten:
2993 return &field_write_event_ref_count_;
2994 case instrumentation::Instrumentation::kExceptionCaught:
2995 return &exception_catch_event_ref_count_;
2996 default:
2997 return nullptr;
2998 }
2999}
3000
Sebastien Hertz4d25df32014-03-21 17:44:46 +01003001// Process request while all mutator threads are suspended.
3002void Dbg::ProcessDeoptimizationRequest(const DeoptimizationRequest& request) {
Sebastien Hertz138dbfc2013-12-04 18:15:25 +01003003 instrumentation::Instrumentation* instrumentation = Runtime::Current()->GetInstrumentation();
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003004 switch (request.GetKind()) {
Sebastien Hertz4d25df32014-03-21 17:44:46 +01003005 case DeoptimizationRequest::kNothing:
3006 LOG(WARNING) << "Ignoring empty deoptimization request.";
3007 break;
Sebastien Hertz42cd43f2014-05-13 14:15:41 +02003008 case DeoptimizationRequest::kRegisterForEvent:
3009 VLOG(jdwp) << StringPrintf("Add debugger as listener for instrumentation event 0x%x",
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003010 request.InstrumentationEvent());
3011 instrumentation->AddListener(&gDebugInstrumentationListener, request.InstrumentationEvent());
3012 instrumentation_events_ |= request.InstrumentationEvent();
Sebastien Hertz42cd43f2014-05-13 14:15:41 +02003013 break;
3014 case DeoptimizationRequest::kUnregisterForEvent:
3015 VLOG(jdwp) << StringPrintf("Remove debugger as listener for instrumentation event 0x%x",
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003016 request.InstrumentationEvent());
Sebastien Hertz42cd43f2014-05-13 14:15:41 +02003017 instrumentation->RemoveListener(&gDebugInstrumentationListener,
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003018 request.InstrumentationEvent());
3019 instrumentation_events_ &= ~request.InstrumentationEvent();
Sebastien Hertz42cd43f2014-05-13 14:15:41 +02003020 break;
Sebastien Hertz4d25df32014-03-21 17:44:46 +01003021 case DeoptimizationRequest::kFullDeoptimization:
Sebastien Hertz7ec2f1c2014-03-27 20:06:47 +01003022 VLOG(jdwp) << "Deoptimize the world ...";
Sebastien Hertz4d25df32014-03-21 17:44:46 +01003023 instrumentation->DeoptimizeEverything();
Sebastien Hertz7ec2f1c2014-03-27 20:06:47 +01003024 VLOG(jdwp) << "Deoptimize the world DONE";
Sebastien Hertz4d25df32014-03-21 17:44:46 +01003025 break;
3026 case DeoptimizationRequest::kFullUndeoptimization:
Sebastien Hertz7ec2f1c2014-03-27 20:06:47 +01003027 VLOG(jdwp) << "Undeoptimize the world ...";
Sebastien Hertz4d25df32014-03-21 17:44:46 +01003028 instrumentation->UndeoptimizeEverything();
Sebastien Hertz7ec2f1c2014-03-27 20:06:47 +01003029 VLOG(jdwp) << "Undeoptimize the world DONE";
Sebastien Hertz4d25df32014-03-21 17:44:46 +01003030 break;
3031 case DeoptimizationRequest::kSelectiveDeoptimization:
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003032 VLOG(jdwp) << "Deoptimize method " << PrettyMethod(request.Method()) << " ...";
3033 instrumentation->Deoptimize(request.Method());
3034 VLOG(jdwp) << "Deoptimize method " << PrettyMethod(request.Method()) << " DONE";
Sebastien Hertz4d25df32014-03-21 17:44:46 +01003035 break;
3036 case DeoptimizationRequest::kSelectiveUndeoptimization:
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003037 VLOG(jdwp) << "Undeoptimize method " << PrettyMethod(request.Method()) << " ...";
3038 instrumentation->Undeoptimize(request.Method());
3039 VLOG(jdwp) << "Undeoptimize method " << PrettyMethod(request.Method()) << " DONE";
Sebastien Hertz4d25df32014-03-21 17:44:46 +01003040 break;
3041 default:
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003042 LOG(FATAL) << "Unsupported deoptimization request kind " << request.GetKind();
Sebastien Hertz4d25df32014-03-21 17:44:46 +01003043 break;
Sebastien Hertz138dbfc2013-12-04 18:15:25 +01003044 }
Sebastien Hertz138dbfc2013-12-04 18:15:25 +01003045}
3046
Sebastien Hertz7ec2f1c2014-03-27 20:06:47 +01003047void Dbg::DelayFullUndeoptimization() {
Sebastien Hertzf3928792014-11-17 19:00:37 +01003048 if (RequiresDeoptimization()) {
3049 MutexLock mu(Thread::Current(), *Locks::deoptimization_lock_);
3050 ++delayed_full_undeoptimization_count_;
3051 DCHECK_LE(delayed_full_undeoptimization_count_, full_deoptimization_event_count_);
3052 }
Sebastien Hertz7ec2f1c2014-03-27 20:06:47 +01003053}
3054
3055void Dbg::ProcessDelayedFullUndeoptimizations() {
3056 // TODO: avoid taking the lock twice (once here and once in ManageDeoptimization).
3057 {
Brian Carlstrom306db812014-09-05 13:01:41 -07003058 MutexLock mu(Thread::Current(), *Locks::deoptimization_lock_);
Sebastien Hertz7ec2f1c2014-03-27 20:06:47 +01003059 while (delayed_full_undeoptimization_count_ > 0) {
3060 DeoptimizationRequest req;
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003061 req.SetKind(DeoptimizationRequest::kFullUndeoptimization);
3062 req.SetMethod(nullptr);
Sebastien Hertz7ec2f1c2014-03-27 20:06:47 +01003063 RequestDeoptimizationLocked(req);
3064 --delayed_full_undeoptimization_count_;
3065 }
3066 }
3067 ManageDeoptimization();
3068}
3069
Sebastien Hertz4d25df32014-03-21 17:44:46 +01003070void Dbg::RequestDeoptimization(const DeoptimizationRequest& req) {
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003071 if (req.GetKind() == DeoptimizationRequest::kNothing) {
Sebastien Hertz4d25df32014-03-21 17:44:46 +01003072 // Nothing to do.
3073 return;
3074 }
Brian Carlstrom306db812014-09-05 13:01:41 -07003075 MutexLock mu(Thread::Current(), *Locks::deoptimization_lock_);
Sebastien Hertz7ec2f1c2014-03-27 20:06:47 +01003076 RequestDeoptimizationLocked(req);
3077}
3078
3079void Dbg::RequestDeoptimizationLocked(const DeoptimizationRequest& req) {
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003080 switch (req.GetKind()) {
Sebastien Hertz42cd43f2014-05-13 14:15:41 +02003081 case DeoptimizationRequest::kRegisterForEvent: {
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003082 DCHECK_NE(req.InstrumentationEvent(), 0u);
3083 size_t* counter = GetReferenceCounterForEvent(req.InstrumentationEvent());
Sebastien Hertz42cd43f2014-05-13 14:15:41 +02003084 CHECK(counter != nullptr) << StringPrintf("No counter for instrumentation event 0x%x",
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003085 req.InstrumentationEvent());
Sebastien Hertz42cd43f2014-05-13 14:15:41 +02003086 if (*counter == 0) {
Sebastien Hertz7d2ae432014-05-15 11:26:34 +02003087 VLOG(jdwp) << StringPrintf("Queue request #%zd to start listening to instrumentation event 0x%x",
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003088 deoptimization_requests_.size(), req.InstrumentationEvent());
Sebastien Hertz42cd43f2014-05-13 14:15:41 +02003089 deoptimization_requests_.push_back(req);
3090 }
3091 *counter = *counter + 1;
3092 break;
3093 }
3094 case DeoptimizationRequest::kUnregisterForEvent: {
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003095 DCHECK_NE(req.InstrumentationEvent(), 0u);
3096 size_t* counter = GetReferenceCounterForEvent(req.InstrumentationEvent());
Sebastien Hertz42cd43f2014-05-13 14:15:41 +02003097 CHECK(counter != nullptr) << StringPrintf("No counter for instrumentation event 0x%x",
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003098 req.InstrumentationEvent());
Sebastien Hertz42cd43f2014-05-13 14:15:41 +02003099 *counter = *counter - 1;
3100 if (*counter == 0) {
Sebastien Hertz7d2ae432014-05-15 11:26:34 +02003101 VLOG(jdwp) << StringPrintf("Queue request #%zd to stop listening to instrumentation event 0x%x",
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003102 deoptimization_requests_.size(), req.InstrumentationEvent());
Sebastien Hertz42cd43f2014-05-13 14:15:41 +02003103 deoptimization_requests_.push_back(req);
3104 }
3105 break;
3106 }
Sebastien Hertz4d25df32014-03-21 17:44:46 +01003107 case DeoptimizationRequest::kFullDeoptimization: {
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003108 DCHECK(req.Method() == nullptr);
Sebastien Hertz4d25df32014-03-21 17:44:46 +01003109 if (full_deoptimization_event_count_ == 0) {
Sebastien Hertz7ec2f1c2014-03-27 20:06:47 +01003110 VLOG(jdwp) << "Queue request #" << deoptimization_requests_.size()
3111 << " for full deoptimization";
Sebastien Hertz4d25df32014-03-21 17:44:46 +01003112 deoptimization_requests_.push_back(req);
3113 }
3114 ++full_deoptimization_event_count_;
3115 break;
3116 }
3117 case DeoptimizationRequest::kFullUndeoptimization: {
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003118 DCHECK(req.Method() == nullptr);
Sebastien Hertze713d932014-05-15 10:48:53 +02003119 DCHECK_GT(full_deoptimization_event_count_, 0U);
Sebastien Hertz4d25df32014-03-21 17:44:46 +01003120 --full_deoptimization_event_count_;
3121 if (full_deoptimization_event_count_ == 0) {
Sebastien Hertz7ec2f1c2014-03-27 20:06:47 +01003122 VLOG(jdwp) << "Queue request #" << deoptimization_requests_.size()
3123 << " for full undeoptimization";
Sebastien Hertz4d25df32014-03-21 17:44:46 +01003124 deoptimization_requests_.push_back(req);
3125 }
3126 break;
3127 }
3128 case DeoptimizationRequest::kSelectiveDeoptimization: {
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003129 DCHECK(req.Method() != nullptr);
Sebastien Hertz7ec2f1c2014-03-27 20:06:47 +01003130 VLOG(jdwp) << "Queue request #" << deoptimization_requests_.size()
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003131 << " for deoptimization of " << PrettyMethod(req.Method());
Sebastien Hertz4d25df32014-03-21 17:44:46 +01003132 deoptimization_requests_.push_back(req);
3133 break;
3134 }
3135 case DeoptimizationRequest::kSelectiveUndeoptimization: {
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003136 DCHECK(req.Method() != nullptr);
Sebastien Hertz7ec2f1c2014-03-27 20:06:47 +01003137 VLOG(jdwp) << "Queue request #" << deoptimization_requests_.size()
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003138 << " for undeoptimization of " << PrettyMethod(req.Method());
Sebastien Hertz4d25df32014-03-21 17:44:46 +01003139 deoptimization_requests_.push_back(req);
3140 break;
3141 }
3142 default: {
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003143 LOG(FATAL) << "Unknown deoptimization request kind " << req.GetKind();
Sebastien Hertz4d25df32014-03-21 17:44:46 +01003144 break;
3145 }
3146 }
3147}
3148
Sebastien Hertz138dbfc2013-12-04 18:15:25 +01003149void Dbg::ManageDeoptimization() {
3150 Thread* const self = Thread::Current();
3151 {
3152 // Avoid suspend/resume if there is no pending request.
Brian Carlstrom306db812014-09-05 13:01:41 -07003153 MutexLock mu(self, *Locks::deoptimization_lock_);
Sebastien Hertz4d25df32014-03-21 17:44:46 +01003154 if (deoptimization_requests_.empty()) {
Sebastien Hertz138dbfc2013-12-04 18:15:25 +01003155 return;
3156 }
3157 }
3158 CHECK_EQ(self->GetState(), kRunnable);
3159 self->TransitionFromRunnableToSuspended(kWaitingForDeoptimization);
3160 // We need to suspend mutator threads first.
3161 Runtime* const runtime = Runtime::Current();
3162 runtime->GetThreadList()->SuspendAll();
3163 const ThreadState old_state = self->SetStateUnsafe(kRunnable);
Sebastien Hertz4d25df32014-03-21 17:44:46 +01003164 {
Brian Carlstrom306db812014-09-05 13:01:41 -07003165 MutexLock mu(self, *Locks::deoptimization_lock_);
Sebastien Hertz7ec2f1c2014-03-27 20:06:47 +01003166 size_t req_index = 0;
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003167 for (DeoptimizationRequest& request : deoptimization_requests_) {
Sebastien Hertz7ec2f1c2014-03-27 20:06:47 +01003168 VLOG(jdwp) << "Process deoptimization request #" << req_index++;
Sebastien Hertz4d25df32014-03-21 17:44:46 +01003169 ProcessDeoptimizationRequest(request);
3170 }
3171 deoptimization_requests_.clear();
3172 }
Sebastien Hertz138dbfc2013-12-04 18:15:25 +01003173 CHECK_EQ(self->SetStateUnsafe(old_state), kRunnable);
3174 runtime->GetThreadList()->ResumeAll();
3175 self->TransitionFromSuspendedToRunnable();
3176}
3177
Sebastien Hertza76a6d42014-03-20 16:40:17 +01003178static bool IsMethodPossiblyInlined(Thread* self, mirror::ArtMethod* m)
3179 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07003180 const DexFile::CodeItem* code_item = m->GetCodeItem();
Sebastien Hertza76a6d42014-03-20 16:40:17 +01003181 if (code_item == nullptr) {
3182 // TODO We should not be asked to watch location in a native or abstract method so the code item
3183 // should never be null. We could just check we never encounter this case.
3184 return false;
Sebastien Hertz138dbfc2013-12-04 18:15:25 +01003185 }
Sebastien Hertz4d1e9ab2014-09-18 16:03:34 +02003186 // Note: method verifier may cause thread suspension.
3187 self->AssertThreadSuspensionIsAllowable();
Hiroshi Yamauchidc376172014-08-22 11:13:12 -07003188 StackHandleScope<3> hs(self);
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07003189 mirror::Class* declaring_class = m->GetDeclaringClass();
3190 Handle<mirror::DexCache> dex_cache(hs.NewHandle(declaring_class->GetDexCache()));
3191 Handle<mirror::ClassLoader> class_loader(hs.NewHandle(declaring_class->GetClassLoader()));
Hiroshi Yamauchidc376172014-08-22 11:13:12 -07003192 Handle<mirror::ArtMethod> method(hs.NewHandle(m));
Ian Rogers7b078e82014-09-10 14:44:24 -07003193 verifier::MethodVerifier verifier(self, dex_cache->GetDexFile(), dex_cache, class_loader,
Hiroshi Yamauchidc376172014-08-22 11:13:12 -07003194 &m->GetClassDef(), code_item, m->GetDexMethodIndex(), method,
Mathieu Chartier4306ef82014-12-19 18:41:47 -08003195 m->GetAccessFlags(), false, true, false, true);
Sebastien Hertza76a6d42014-03-20 16:40:17 +01003196 // Note: we don't need to verify the method.
3197 return InlineMethodAnalyser::AnalyseMethodCode(&verifier, nullptr);
3198}
Sebastien Hertz138dbfc2013-12-04 18:15:25 +01003199
Sebastien Hertza76a6d42014-03-20 16:40:17 +01003200static const Breakpoint* FindFirstBreakpointForMethod(mirror::ArtMethod* m)
Sebastien Hertzed2be172014-08-19 15:33:43 +02003201 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_, Locks::breakpoint_lock_) {
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003202 for (Breakpoint& breakpoint : gBreakpoints) {
3203 if (breakpoint.Method() == m) {
Sebastien Hertza76a6d42014-03-20 16:40:17 +01003204 return &breakpoint;
3205 }
3206 }
3207 return nullptr;
3208}
3209
3210// Sanity checks all existing breakpoints on the same method.
Sebastien Hertzf3928792014-11-17 19:00:37 +01003211static void SanityCheckExistingBreakpoints(mirror::ArtMethod* m,
3212 DeoptimizationRequest::Kind deoptimization_kind)
Sebastien Hertzed2be172014-08-19 15:33:43 +02003213 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_, Locks::breakpoint_lock_) {
Sebastien Hertz4d1e9ab2014-09-18 16:03:34 +02003214 for (const Breakpoint& breakpoint : gBreakpoints) {
Sebastien Hertzf3928792014-11-17 19:00:37 +01003215 if (breakpoint.Method() == m) {
3216 CHECK_EQ(deoptimization_kind, breakpoint.GetDeoptimizationKind());
3217 }
Sebastien Hertz4d1e9ab2014-09-18 16:03:34 +02003218 }
Sebastien Hertzf3928792014-11-17 19:00:37 +01003219 instrumentation::Instrumentation* instrumentation = Runtime::Current()->GetInstrumentation();
3220 if (deoptimization_kind == DeoptimizationRequest::kFullDeoptimization) {
Sebastien Hertz4d1e9ab2014-09-18 16:03:34 +02003221 // We should have deoptimized everything but not "selectively" deoptimized this method.
Sebastien Hertzf3928792014-11-17 19:00:37 +01003222 CHECK(instrumentation->AreAllMethodsDeoptimized());
3223 CHECK(!instrumentation->IsDeoptimized(m));
3224 } else if (deoptimization_kind == DeoptimizationRequest::kSelectiveDeoptimization) {
Sebastien Hertz4d1e9ab2014-09-18 16:03:34 +02003225 // We should have "selectively" deoptimized this method.
3226 // Note: while we have not deoptimized everything for this method, we may have done it for
3227 // another event.
Sebastien Hertzf3928792014-11-17 19:00:37 +01003228 CHECK(instrumentation->IsDeoptimized(m));
3229 } else {
3230 // This method does not require deoptimization.
3231 CHECK_EQ(deoptimization_kind, DeoptimizationRequest::kNothing);
3232 CHECK(!instrumentation->IsDeoptimized(m));
3233 }
3234}
3235
Sebastien Hertzabe93e02014-12-17 16:35:50 +01003236// Returns the deoptimization kind required to set a breakpoint in a method.
3237// If a breakpoint has already been set, we also return the first breakpoint
3238// through the given 'existing_brkpt' pointer.
Sebastien Hertzf3928792014-11-17 19:00:37 +01003239static DeoptimizationRequest::Kind GetRequiredDeoptimizationKind(Thread* self,
Sebastien Hertzabe93e02014-12-17 16:35:50 +01003240 mirror::ArtMethod* m,
3241 const Breakpoint** existing_brkpt)
Sebastien Hertzf3928792014-11-17 19:00:37 +01003242 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
3243 if (!Dbg::RequiresDeoptimization()) {
3244 // We already run in interpreter-only mode so we don't need to deoptimize anything.
3245 VLOG(jdwp) << "No need for deoptimization when fully running with interpreter for method "
3246 << PrettyMethod(m);
3247 return DeoptimizationRequest::kNothing;
3248 }
Sebastien Hertzabe93e02014-12-17 16:35:50 +01003249 const Breakpoint* first_breakpoint;
Sebastien Hertzf3928792014-11-17 19:00:37 +01003250 {
3251 ReaderMutexLock mu(self, *Locks::breakpoint_lock_);
Sebastien Hertzabe93e02014-12-17 16:35:50 +01003252 first_breakpoint = FindFirstBreakpointForMethod(m);
3253 *existing_brkpt = first_breakpoint;
Sebastien Hertzf3928792014-11-17 19:00:37 +01003254 }
Sebastien Hertzabe93e02014-12-17 16:35:50 +01003255
3256 if (first_breakpoint == nullptr) {
Sebastien Hertzf3928792014-11-17 19:00:37 +01003257 // There is no breakpoint on this method yet: we need to deoptimize. If this method may be
3258 // inlined, we deoptimize everything; otherwise we deoptimize only this method.
3259 // Note: IsMethodPossiblyInlined goes into the method verifier and may cause thread suspension.
3260 // Therefore we must not hold any lock when we call it.
3261 bool need_full_deoptimization = IsMethodPossiblyInlined(self, m);
3262 if (need_full_deoptimization) {
3263 VLOG(jdwp) << "Need full deoptimization because of possible inlining of method "
3264 << PrettyMethod(m);
3265 return DeoptimizationRequest::kFullDeoptimization;
3266 } else {
3267 // We don't need to deoptimize if the method has not been compiled.
3268 ClassLinker* const class_linker = Runtime::Current()->GetClassLinker();
3269 const bool is_compiled = class_linker->GetOatMethodQuickCodeFor(m) != nullptr;
3270 if (is_compiled) {
Sebastien Hertz6963e442014-11-26 22:11:27 +01003271 // If the method may be called through its direct code pointer (without loading
3272 // its updated entrypoint), we need full deoptimization to not miss the breakpoint.
3273 if (class_linker->MayBeCalledWithDirectCodePointer(m)) {
3274 VLOG(jdwp) << "Need full deoptimization because of possible direct code call "
3275 << "into image for compiled method " << PrettyMethod(m);
3276 return DeoptimizationRequest::kFullDeoptimization;
3277 } else {
3278 VLOG(jdwp) << "Need selective deoptimization for compiled method " << PrettyMethod(m);
3279 return DeoptimizationRequest::kSelectiveDeoptimization;
3280 }
Sebastien Hertzf3928792014-11-17 19:00:37 +01003281 } else {
3282 // Method is not compiled: we don't need to deoptimize.
3283 VLOG(jdwp) << "No need for deoptimization for non-compiled method " << PrettyMethod(m);
3284 return DeoptimizationRequest::kNothing;
3285 }
3286 }
3287 } else {
3288 // There is at least one breakpoint for this method: we don't need to deoptimize.
3289 // Let's check that all breakpoints are configured the same way for deoptimization.
3290 VLOG(jdwp) << "Breakpoint already set: no deoptimization is required";
Sebastien Hertzabe93e02014-12-17 16:35:50 +01003291 DeoptimizationRequest::Kind deoptimization_kind = first_breakpoint->GetDeoptimizationKind();
Sebastien Hertzf3928792014-11-17 19:00:37 +01003292 if (kIsDebugBuild) {
3293 ReaderMutexLock mu(self, *Locks::breakpoint_lock_);
3294 SanityCheckExistingBreakpoints(m, deoptimization_kind);
3295 }
3296 return DeoptimizationRequest::kNothing;
Sebastien Hertz138dbfc2013-12-04 18:15:25 +01003297 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -07003298}
3299
Sebastien Hertza76a6d42014-03-20 16:40:17 +01003300// Installs a breakpoint at the specified location. Also indicates through the deoptimization
3301// request if we need to deoptimize.
3302void Dbg::WatchLocation(const JDWP::JdwpLocation* location, DeoptimizationRequest* req) {
3303 Thread* const self = Thread::Current();
Brian Carlstromea46f952013-07-30 01:26:50 -07003304 mirror::ArtMethod* m = FromMethodId(location->method_id);
Sebastien Hertza76a6d42014-03-20 16:40:17 +01003305 DCHECK(m != nullptr) << "No method for method id " << location->method_id;
Sebastien Hertz138dbfc2013-12-04 18:15:25 +01003306
Sebastien Hertzabe93e02014-12-17 16:35:50 +01003307 const Breakpoint* existing_breakpoint = nullptr;
3308 const DeoptimizationRequest::Kind deoptimization_kind =
3309 GetRequiredDeoptimizationKind(self, m, &existing_breakpoint);
Sebastien Hertzf3928792014-11-17 19:00:37 +01003310 req->SetKind(deoptimization_kind);
3311 if (deoptimization_kind == DeoptimizationRequest::kSelectiveDeoptimization) {
3312 req->SetMethod(m);
Sebastien Hertza76a6d42014-03-20 16:40:17 +01003313 } else {
Sebastien Hertzf3928792014-11-17 19:00:37 +01003314 CHECK(deoptimization_kind == DeoptimizationRequest::kNothing ||
3315 deoptimization_kind == DeoptimizationRequest::kFullDeoptimization);
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003316 req->SetMethod(nullptr);
Sebastien Hertz138dbfc2013-12-04 18:15:25 +01003317 }
3318
Sebastien Hertz4d1e9ab2014-09-18 16:03:34 +02003319 {
3320 WriterMutexLock mu(self, *Locks::breakpoint_lock_);
Sebastien Hertzabe93e02014-12-17 16:35:50 +01003321 // If there is at least one existing breakpoint on the same method, the new breakpoint
3322 // must have the same deoptimization kind than the existing breakpoint(s).
3323 DeoptimizationRequest::Kind breakpoint_deoptimization_kind;
3324 if (existing_breakpoint != nullptr) {
3325 breakpoint_deoptimization_kind = existing_breakpoint->GetDeoptimizationKind();
3326 } else {
3327 breakpoint_deoptimization_kind = deoptimization_kind;
3328 }
3329 gBreakpoints.push_back(Breakpoint(m, location->dex_pc, breakpoint_deoptimization_kind));
Sebastien Hertz4d1e9ab2014-09-18 16:03:34 +02003330 VLOG(jdwp) << "Set breakpoint #" << (gBreakpoints.size() - 1) << ": "
3331 << gBreakpoints[gBreakpoints.size() - 1];
3332 }
Sebastien Hertza76a6d42014-03-20 16:40:17 +01003333}
3334
3335// Uninstalls a breakpoint at the specified location. Also indicates through the deoptimization
3336// request if we need to undeoptimize.
3337void Dbg::UnwatchLocation(const JDWP::JdwpLocation* location, DeoptimizationRequest* req) {
Sebastien Hertzed2be172014-08-19 15:33:43 +02003338 WriterMutexLock mu(Thread::Current(), *Locks::breakpoint_lock_);
Sebastien Hertza76a6d42014-03-20 16:40:17 +01003339 mirror::ArtMethod* m = FromMethodId(location->method_id);
3340 DCHECK(m != nullptr) << "No method for method id " << location->method_id;
Sebastien Hertzf3928792014-11-17 19:00:37 +01003341 DeoptimizationRequest::Kind deoptimization_kind = DeoptimizationRequest::kNothing;
Sebastien Hertza76a6d42014-03-20 16:40:17 +01003342 for (size_t i = 0, e = gBreakpoints.size(); i < e; ++i) {
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003343 if (gBreakpoints[i].DexPc() == location->dex_pc && gBreakpoints[i].Method() == m) {
Sebastien Hertza76a6d42014-03-20 16:40:17 +01003344 VLOG(jdwp) << "Removed breakpoint #" << i << ": " << gBreakpoints[i];
Sebastien Hertzf3928792014-11-17 19:00:37 +01003345 deoptimization_kind = gBreakpoints[i].GetDeoptimizationKind();
3346 DCHECK_EQ(deoptimization_kind == DeoptimizationRequest::kSelectiveDeoptimization,
3347 Runtime::Current()->GetInstrumentation()->IsDeoptimized(m));
Sebastien Hertza76a6d42014-03-20 16:40:17 +01003348 gBreakpoints.erase(gBreakpoints.begin() + i);
3349 break;
3350 }
3351 }
3352 const Breakpoint* const existing_breakpoint = FindFirstBreakpointForMethod(m);
3353 if (existing_breakpoint == nullptr) {
3354 // There is no more breakpoint on this method: we need to undeoptimize.
Sebastien Hertzf3928792014-11-17 19:00:37 +01003355 if (deoptimization_kind == DeoptimizationRequest::kFullDeoptimization) {
Sebastien Hertza76a6d42014-03-20 16:40:17 +01003356 // This method required full deoptimization: we need to undeoptimize everything.
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003357 req->SetKind(DeoptimizationRequest::kFullUndeoptimization);
3358 req->SetMethod(nullptr);
Sebastien Hertzf3928792014-11-17 19:00:37 +01003359 } else if (deoptimization_kind == DeoptimizationRequest::kSelectiveDeoptimization) {
Sebastien Hertza76a6d42014-03-20 16:40:17 +01003360 // This method required selective deoptimization: we need to undeoptimize only that method.
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003361 req->SetKind(DeoptimizationRequest::kSelectiveUndeoptimization);
3362 req->SetMethod(m);
Sebastien Hertzf3928792014-11-17 19:00:37 +01003363 } else {
3364 // This method had no need for deoptimization: do nothing.
3365 CHECK_EQ(deoptimization_kind, DeoptimizationRequest::kNothing);
3366 req->SetKind(DeoptimizationRequest::kNothing);
3367 req->SetMethod(nullptr);
Sebastien Hertza76a6d42014-03-20 16:40:17 +01003368 }
3369 } else {
3370 // There is at least one breakpoint for this method: we don't need to undeoptimize.
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003371 req->SetKind(DeoptimizationRequest::kNothing);
3372 req->SetMethod(nullptr);
Sebastien Hertz4d1e9ab2014-09-18 16:03:34 +02003373 if (kIsDebugBuild) {
Sebastien Hertzf3928792014-11-17 19:00:37 +01003374 SanityCheckExistingBreakpoints(m, deoptimization_kind);
Sebastien Hertz4d1e9ab2014-09-18 16:03:34 +02003375 }
Elliott Hughes86964332012-02-15 19:37:42 -08003376 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -07003377}
3378
Jeff Hao449db332013-04-12 18:30:52 -07003379// Scoped utility class to suspend a thread so that we may do tasks such as walk its stack. Doesn't
3380// cause suspension if the thread is the current thread.
3381class ScopedThreadSuspension {
3382 public:
Ian Rogers33e95662013-05-20 20:29:14 -07003383 ScopedThreadSuspension(Thread* self, JDWP::ObjectId thread_id)
Sebastien Hertz52d131d2014-03-13 16:17:40 +01003384 LOCKS_EXCLUDED(Locks::thread_list_lock_)
Ian Rogers33e95662013-05-20 20:29:14 -07003385 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) :
Ian Rogersf3d874c2014-07-17 18:52:42 -07003386 thread_(nullptr),
Jeff Hao449db332013-04-12 18:30:52 -07003387 error_(JDWP::ERR_NONE),
3388 self_suspend_(false),
Ian Rogers33e95662013-05-20 20:29:14 -07003389 other_suspend_(false) {
Jeff Hao449db332013-04-12 18:30:52 -07003390 ScopedObjectAccessUnchecked soa(self);
3391 {
3392 MutexLock mu(soa.Self(), *Locks::thread_list_lock_);
Ian Rogersc0542af2014-09-03 16:16:56 -07003393 thread_ = DecodeThread(soa, thread_id, &error_);
Jeff Hao449db332013-04-12 18:30:52 -07003394 }
3395 if (error_ == JDWP::ERR_NONE) {
3396 if (thread_ == soa.Self()) {
3397 self_suspend_ = true;
3398 } else {
3399 soa.Self()->TransitionFromRunnableToSuspended(kWaitingForDebuggerSuspension);
Sebastien Hertz6995c602014-09-09 12:10:13 +02003400 jobject thread_peer = Dbg::GetObjectRegistry()->GetJObject(thread_id);
Jeff Hao449db332013-04-12 18:30:52 -07003401 bool timed_out;
Ian Rogers4ad5cd32014-11-11 23:08:07 -08003402 ThreadList* thread_list = Runtime::Current()->GetThreadList();
3403 Thread* suspended_thread = thread_list->SuspendThreadByPeer(thread_peer, true, true,
3404 &timed_out);
Jeff Hao449db332013-04-12 18:30:52 -07003405 CHECK_EQ(soa.Self()->TransitionFromSuspendedToRunnable(), kWaitingForDebuggerSuspension);
Ian Rogersf3d874c2014-07-17 18:52:42 -07003406 if (suspended_thread == nullptr) {
Jeff Hao449db332013-04-12 18:30:52 -07003407 // Thread terminated from under us while suspending.
3408 error_ = JDWP::ERR_INVALID_THREAD;
3409 } else {
3410 CHECK_EQ(suspended_thread, thread_);
3411 other_suspend_ = true;
3412 }
3413 }
3414 }
Elliott Hughes2435a572012-02-17 16:07:41 -08003415 }
Elliott Hughes86964332012-02-15 19:37:42 -08003416
Jeff Hao449db332013-04-12 18:30:52 -07003417 Thread* GetThread() const {
3418 return thread_;
3419 }
3420
3421 JDWP::JdwpError GetError() const {
3422 return error_;
3423 }
3424
3425 ~ScopedThreadSuspension() {
3426 if (other_suspend_) {
3427 Runtime::Current()->GetThreadList()->Resume(thread_, true);
3428 }
3429 }
3430
3431 private:
3432 Thread* thread_;
3433 JDWP::JdwpError error_;
3434 bool self_suspend_;
3435 bool other_suspend_;
3436};
3437
3438JDWP::JdwpError Dbg::ConfigureStep(JDWP::ObjectId thread_id, JDWP::JdwpStepSize step_size,
3439 JDWP::JdwpStepDepth step_depth) {
3440 Thread* self = Thread::Current();
3441 ScopedThreadSuspension sts(self, thread_id);
3442 if (sts.GetError() != JDWP::ERR_NONE) {
3443 return sts.GetError();
3444 }
3445
Elliott Hughes2435a572012-02-17 16:07:41 -08003446 //
3447 // Work out what Method* we're in, the current line number, and how deep the stack currently
3448 // is for step-out.
3449 //
3450
Ian Rogers0399dde2012-06-06 17:09:28 -07003451 struct SingleStepStackVisitor : public StackVisitor {
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01003452 explicit SingleStepStackVisitor(Thread* thread, SingleStepControl* single_step_control,
3453 int32_t* line_number)
Ian Rogersb726dcb2012-09-05 08:57:23 -07003454 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_)
Ian Rogersc0542af2014-09-03 16:16:56 -07003455 : StackVisitor(thread, nullptr), single_step_control_(single_step_control),
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01003456 line_number_(line_number) {
3457 DCHECK_EQ(single_step_control_, thread->GetSingleStepControl());
Ian Rogersc0542af2014-09-03 16:16:56 -07003458 single_step_control_->method = nullptr;
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01003459 single_step_control_->stack_depth = 0;
Elliott Hughes86964332012-02-15 19:37:42 -08003460 }
Ian Rogersca190662012-06-26 15:45:57 -07003461
Ian Rogers00f7d0e2012-07-19 15:28:27 -07003462 // TODO: Enable annotalysis. We know lock is held in constructor, but abstraction confuses
3463 // annotalysis.
3464 bool VisitFrame() NO_THREAD_SAFETY_ANALYSIS {
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01003465 mirror::ArtMethod* m = GetMethod();
Ian Rogers0399dde2012-06-06 17:09:28 -07003466 if (!m->IsRuntimeMethod()) {
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01003467 ++single_step_control_->stack_depth;
Ian Rogersc0542af2014-09-03 16:16:56 -07003468 if (single_step_control_->method == nullptr) {
Ian Rogersef7d42f2014-01-06 12:55:46 -08003469 mirror::DexCache* dex_cache = m->GetDeclaringClass()->GetDexCache();
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01003470 single_step_control_->method = m;
3471 *line_number_ = -1;
Ian Rogersc0542af2014-09-03 16:16:56 -07003472 if (dex_cache != nullptr) {
Ian Rogers4445a7e2012-10-05 17:19:13 -07003473 const DexFile& dex_file = *dex_cache->GetDexFile();
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01003474 *line_number_ = dex_file.GetLineNumFromPC(m, GetDexPc());
Elliott Hughes2435a572012-02-17 16:07:41 -08003475 }
Elliott Hughes86964332012-02-15 19:37:42 -08003476 }
3477 }
Elliott Hughes530fa002012-03-12 11:44:49 -07003478 return true;
Elliott Hughes86964332012-02-15 19:37:42 -08003479 }
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01003480
3481 SingleStepControl* const single_step_control_;
3482 int32_t* const line_number_;
Elliott Hughes86964332012-02-15 19:37:42 -08003483 };
Jeff Hao449db332013-04-12 18:30:52 -07003484
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01003485 Thread* const thread = sts.GetThread();
3486 SingleStepControl* const single_step_control = thread->GetSingleStepControl();
3487 DCHECK(single_step_control != nullptr);
3488 int32_t line_number = -1;
3489 SingleStepStackVisitor visitor(thread, single_step_control, &line_number);
Ian Rogers0399dde2012-06-06 17:09:28 -07003490 visitor.WalkStack();
Elliott Hughes86964332012-02-15 19:37:42 -08003491
Elliott Hughes2435a572012-02-17 16:07:41 -08003492 //
3493 // Find the dex_pc values that correspond to the current line, for line-based single-stepping.
3494 //
3495
3496 struct DebugCallbackContext {
Andreas Gampe277ccbd2014-11-03 21:36:10 -08003497 explicit DebugCallbackContext(SingleStepControl* single_step_control_cb, int32_t line_number_cb,
Sebastien Hertzbb43b432014-04-14 11:59:08 +02003498 const DexFile::CodeItem* code_item)
Andreas Gampe277ccbd2014-11-03 21:36:10 -08003499 : single_step_control_(single_step_control_cb), line_number_(line_number_cb),
3500 code_item_(code_item), last_pc_valid(false), last_pc(0) {
Elliott Hughes2435a572012-02-17 16:07:41 -08003501 }
3502
Andreas Gampe277ccbd2014-11-03 21:36:10 -08003503 static bool Callback(void* raw_context, uint32_t address, uint32_t line_number_cb) {
Elliott Hughes2435a572012-02-17 16:07:41 -08003504 DebugCallbackContext* context = reinterpret_cast<DebugCallbackContext*>(raw_context);
Andreas Gampe277ccbd2014-11-03 21:36:10 -08003505 if (static_cast<int32_t>(line_number_cb) == context->line_number_) {
Elliott Hughes2435a572012-02-17 16:07:41 -08003506 if (!context->last_pc_valid) {
3507 // Everything from this address until the next line change is ours.
3508 context->last_pc = address;
3509 context->last_pc_valid = true;
3510 }
3511 // Otherwise, if we're already in a valid range for this line,
3512 // just keep going (shouldn't really happen)...
Brian Carlstrom7934ac22013-07-26 10:54:15 -07003513 } else if (context->last_pc_valid) { // and the line number is new
Elliott Hughes2435a572012-02-17 16:07:41 -08003514 // Add everything from the last entry up until here to the set
3515 for (uint32_t dex_pc = context->last_pc; dex_pc < address; ++dex_pc) {
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01003516 context->single_step_control_->dex_pcs.insert(dex_pc);
Elliott Hughes2435a572012-02-17 16:07:41 -08003517 }
3518 context->last_pc_valid = false;
3519 }
Brian Carlstrom7934ac22013-07-26 10:54:15 -07003520 return false; // There may be multiple entries for any given line.
Elliott Hughes2435a572012-02-17 16:07:41 -08003521 }
3522
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01003523 ~DebugCallbackContext() {
Elliott Hughes2435a572012-02-17 16:07:41 -08003524 // If the line number was the last in the position table...
3525 if (last_pc_valid) {
Sebastien Hertzbb43b432014-04-14 11:59:08 +02003526 size_t end = code_item_->insns_size_in_code_units_;
Elliott Hughes2435a572012-02-17 16:07:41 -08003527 for (uint32_t dex_pc = last_pc; dex_pc < end; ++dex_pc) {
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01003528 single_step_control_->dex_pcs.insert(dex_pc);
Elliott Hughes2435a572012-02-17 16:07:41 -08003529 }
3530 }
3531 }
3532
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01003533 SingleStepControl* const single_step_control_;
3534 const int32_t line_number_;
Sebastien Hertzbb43b432014-04-14 11:59:08 +02003535 const DexFile::CodeItem* const code_item_;
Elliott Hughes2435a572012-02-17 16:07:41 -08003536 bool last_pc_valid;
3537 uint32_t last_pc;
3538 };
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01003539 single_step_control->dex_pcs.clear();
Ian Rogersef7d42f2014-01-06 12:55:46 -08003540 mirror::ArtMethod* m = single_step_control->method;
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01003541 if (!m->IsNative()) {
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07003542 const DexFile::CodeItem* const code_item = m->GetCodeItem();
Sebastien Hertzbb43b432014-04-14 11:59:08 +02003543 DebugCallbackContext context(single_step_control, line_number, code_item);
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07003544 m->GetDexFile()->DecodeDebugInfo(code_item, m->IsStatic(), m->GetDexMethodIndex(),
Ian Rogersc0542af2014-09-03 16:16:56 -07003545 DebugCallbackContext::Callback, nullptr, &context);
Elliott Hughes3e2e1a22012-02-21 11:33:41 -08003546 }
Elliott Hughes2435a572012-02-17 16:07:41 -08003547
3548 //
3549 // Everything else...
3550 //
3551
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01003552 single_step_control->step_size = step_size;
3553 single_step_control->step_depth = step_depth;
3554 single_step_control->is_active = true;
Elliott Hughes86964332012-02-15 19:37:42 -08003555
Elliott Hughes2435a572012-02-17 16:07:41 -08003556 if (VLOG_IS_ON(jdwp)) {
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01003557 VLOG(jdwp) << "Single-step thread: " << *thread;
3558 VLOG(jdwp) << "Single-step step size: " << single_step_control->step_size;
3559 VLOG(jdwp) << "Single-step step depth: " << single_step_control->step_depth;
3560 VLOG(jdwp) << "Single-step current method: " << PrettyMethod(single_step_control->method);
3561 VLOG(jdwp) << "Single-step current line: " << line_number;
3562 VLOG(jdwp) << "Single-step current stack depth: " << single_step_control->stack_depth;
Elliott Hughes2435a572012-02-17 16:07:41 -08003563 VLOG(jdwp) << "Single-step dex_pc values:";
Sebastien Hertzbb43b432014-04-14 11:59:08 +02003564 for (uint32_t dex_pc : single_step_control->dex_pcs) {
3565 VLOG(jdwp) << StringPrintf(" %#x", dex_pc);
Elliott Hughes2435a572012-02-17 16:07:41 -08003566 }
3567 }
3568
3569 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07003570}
3571
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01003572void Dbg::UnconfigureStep(JDWP::ObjectId thread_id) {
3573 ScopedObjectAccessUnchecked soa(Thread::Current());
3574 MutexLock mu(soa.Self(), *Locks::thread_list_lock_);
Ian Rogersc0542af2014-09-03 16:16:56 -07003575 JDWP::JdwpError error;
3576 Thread* thread = DecodeThread(soa, thread_id, &error);
Sebastien Hertz87118ed2013-11-26 17:57:18 +01003577 if (error == JDWP::ERR_NONE) {
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01003578 SingleStepControl* single_step_control = thread->GetSingleStepControl();
3579 DCHECK(single_step_control != nullptr);
Sebastien Hertzbb43b432014-04-14 11:59:08 +02003580 single_step_control->Clear();
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01003581 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -07003582}
3583
Elliott Hughes45651fd2012-02-21 15:48:20 -08003584static char JdwpTagToShortyChar(JDWP::JdwpTag tag) {
3585 switch (tag) {
3586 default:
3587 LOG(FATAL) << "unknown JDWP tag: " << PrintableChar(tag);
Ian Rogersfc787ec2014-10-09 21:56:44 -07003588 UNREACHABLE();
Elliott Hughes45651fd2012-02-21 15:48:20 -08003589
3590 // Primitives.
3591 case JDWP::JT_BYTE: return 'B';
3592 case JDWP::JT_CHAR: return 'C';
3593 case JDWP::JT_FLOAT: return 'F';
3594 case JDWP::JT_DOUBLE: return 'D';
3595 case JDWP::JT_INT: return 'I';
3596 case JDWP::JT_LONG: return 'J';
3597 case JDWP::JT_SHORT: return 'S';
3598 case JDWP::JT_VOID: return 'V';
3599 case JDWP::JT_BOOLEAN: return 'Z';
3600
3601 // Reference types.
3602 case JDWP::JT_ARRAY:
3603 case JDWP::JT_OBJECT:
3604 case JDWP::JT_STRING:
3605 case JDWP::JT_THREAD:
3606 case JDWP::JT_THREAD_GROUP:
3607 case JDWP::JT_CLASS_LOADER:
3608 case JDWP::JT_CLASS_OBJECT:
3609 return 'L';
3610 }
3611}
3612
Elliott Hughes88d63092013-01-09 09:55:54 -08003613JDWP::JdwpError Dbg::InvokeMethod(JDWP::ObjectId thread_id, JDWP::ObjectId object_id,
3614 JDWP::RefTypeId class_id, JDWP::MethodId method_id,
Ian Rogers00f7d0e2012-07-19 15:28:27 -07003615 uint32_t arg_count, uint64_t* arg_values,
3616 JDWP::JdwpTag* arg_types, uint32_t options,
3617 JDWP::JdwpTag* pResultTag, uint64_t* pResultValue,
3618 JDWP::ObjectId* pExceptionId) {
Elliott Hughesd07986f2011-12-06 18:27:45 -08003619 ThreadList* thread_list = Runtime::Current()->GetThreadList();
3620
Ian Rogersc0542af2014-09-03 16:16:56 -07003621 Thread* targetThread = nullptr;
3622 DebugInvokeReq* req = nullptr;
Ian Rogers00f7d0e2012-07-19 15:28:27 -07003623 Thread* self = Thread::Current();
Elliott Hughesd07986f2011-12-06 18:27:45 -08003624 {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07003625 ScopedObjectAccessUnchecked soa(self);
Ian Rogers50b35e22012-10-04 10:09:15 -07003626 MutexLock mu(soa.Self(), *Locks::thread_list_lock_);
Ian Rogersc0542af2014-09-03 16:16:56 -07003627 JDWP::JdwpError error;
3628 targetThread = DecodeThread(soa, thread_id, &error);
Elliott Hughes221229c2013-01-08 18:17:50 -08003629 if (error != JDWP::ERR_NONE) {
3630 LOG(ERROR) << "InvokeMethod request for invalid thread id " << thread_id;
3631 return error;
Elliott Hughesd07986f2011-12-06 18:27:45 -08003632 }
3633 req = targetThread->GetInvokeReq();
3634 if (!req->ready) {
3635 LOG(ERROR) << "InvokeMethod request for thread not stopped by event: " << *targetThread;
3636 return JDWP::ERR_INVALID_THREAD;
3637 }
3638
3639 /*
3640 * We currently have a bug where we don't successfully resume the
3641 * target thread if the suspend count is too deep. We're expected to
3642 * require one "resume" for each "suspend", but when asked to execute
3643 * a method we have to resume fully and then re-suspend it back to the
3644 * same level. (The easiest way to cause this is to type "suspend"
3645 * multiple times in jdb.)
3646 *
3647 * It's unclear what this means when the event specifies "resume all"
3648 * and some threads are suspended more deeply than others. This is
3649 * a rare problem, so for now we just prevent it from hanging forever
3650 * by rejecting the method invocation request. Without this, we will
3651 * be stuck waiting on a suspended thread.
3652 */
Ian Rogers00f7d0e2012-07-19 15:28:27 -07003653 int suspend_count;
3654 {
Ian Rogers50b35e22012-10-04 10:09:15 -07003655 MutexLock mu2(soa.Self(), *Locks::thread_suspend_count_lock_);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07003656 suspend_count = targetThread->GetSuspendCount();
3657 }
Elliott Hughesd07986f2011-12-06 18:27:45 -08003658 if (suspend_count > 1) {
3659 LOG(ERROR) << *targetThread << " suspend count too deep for method invocation: " << suspend_count;
Brian Carlstrom7934ac22013-07-26 10:54:15 -07003660 return JDWP::ERR_THREAD_SUSPENDED; // Probably not expected here.
Elliott Hughesd07986f2011-12-06 18:27:45 -08003661 }
3662
Ian Rogersc0542af2014-09-03 16:16:56 -07003663 mirror::Object* receiver = gRegistry->Get<mirror::Object*>(object_id, &error);
3664 if (error != JDWP::ERR_NONE) {
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08003665 return JDWP::ERR_INVALID_OBJECT;
3666 }
Elliott Hughes45651fd2012-02-21 15:48:20 -08003667
Ian Rogersc0542af2014-09-03 16:16:56 -07003668 mirror::Object* thread = gRegistry->Get<mirror::Object*>(thread_id, &error);
3669 if (error != JDWP::ERR_NONE) {
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08003670 return JDWP::ERR_INVALID_OBJECT;
3671 }
Elliott Hughes45651fd2012-02-21 15:48:20 -08003672 // TODO: check that 'thread' is actually a java.lang.Thread!
3673
Ian Rogersc0542af2014-09-03 16:16:56 -07003674 mirror::Class* c = DecodeClass(class_id, &error);
3675 if (c == nullptr) {
3676 return error;
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08003677 }
Elliott Hughes45651fd2012-02-21 15:48:20 -08003678
Brian Carlstromea46f952013-07-30 01:26:50 -07003679 mirror::ArtMethod* m = FromMethodId(method_id);
Ian Rogersc0542af2014-09-03 16:16:56 -07003680 if (m->IsStatic() != (receiver == nullptr)) {
Elliott Hughes45651fd2012-02-21 15:48:20 -08003681 return JDWP::ERR_INVALID_METHODID;
3682 }
3683 if (m->IsStatic()) {
3684 if (m->GetDeclaringClass() != c) {
3685 return JDWP::ERR_INVALID_METHODID;
3686 }
3687 } else {
3688 if (!m->GetDeclaringClass()->IsAssignableFrom(c)) {
3689 return JDWP::ERR_INVALID_METHODID;
3690 }
3691 }
3692
3693 // Check the argument list matches the method.
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07003694 uint32_t shorty_len = 0;
3695 const char* shorty = m->GetShorty(&shorty_len);
3696 if (shorty_len - 1 != arg_count) {
Elliott Hughes45651fd2012-02-21 15:48:20 -08003697 return JDWP::ERR_ILLEGAL_ARGUMENT;
3698 }
Elliott Hughes09201632013-04-15 15:50:07 -07003699
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07003700 {
3701 StackHandleScope<3> hs(soa.Self());
Ian Rogersa0485602014-12-02 15:48:04 -08003702 HandleWrapper<mirror::ArtMethod> h_m(hs.NewHandleWrapper(&m));
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07003703 HandleWrapper<mirror::Object> h_obj(hs.NewHandleWrapper(&receiver));
3704 HandleWrapper<mirror::Class> h_klass(hs.NewHandleWrapper(&c));
3705 const DexFile::TypeList* types = m->GetParameterTypeList();
3706 for (size_t i = 0; i < arg_count; ++i) {
3707 if (shorty[i + 1] != JdwpTagToShortyChar(arg_types[i])) {
Elliott Hughes09201632013-04-15 15:50:07 -07003708 return JDWP::ERR_ILLEGAL_ARGUMENT;
3709 }
3710
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07003711 if (shorty[i + 1] == 'L') {
3712 // Did we really get an argument of an appropriate reference type?
Ian Rogersa0485602014-12-02 15:48:04 -08003713 mirror::Class* parameter_type =
3714 h_m->GetClassFromTypeIndex(types->GetTypeItem(i).type_idx_, true);
Ian Rogersc0542af2014-09-03 16:16:56 -07003715 mirror::Object* argument = gRegistry->Get<mirror::Object*>(arg_values[i], &error);
3716 if (error != JDWP::ERR_NONE) {
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07003717 return JDWP::ERR_INVALID_OBJECT;
3718 }
Ian Rogersc0542af2014-09-03 16:16:56 -07003719 if (argument != nullptr && !argument->InstanceOf(parameter_type)) {
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07003720 return JDWP::ERR_ILLEGAL_ARGUMENT;
3721 }
3722
3723 // Turn the on-the-wire ObjectId into a jobject.
3724 jvalue& v = reinterpret_cast<jvalue&>(arg_values[i]);
3725 v.l = gRegistry->GetJObject(arg_values[i]);
3726 }
Elliott Hughes09201632013-04-15 15:50:07 -07003727 }
Elliott Hughes45651fd2012-02-21 15:48:20 -08003728 }
3729
Sebastien Hertzd38667a2013-11-25 15:43:54 +01003730 req->receiver = receiver;
3731 req->thread = thread;
3732 req->klass = c;
3733 req->method = m;
3734 req->arg_count = arg_count;
3735 req->arg_values = arg_values;
3736 req->options = options;
3737 req->invoke_needed = true;
Elliott Hughesd07986f2011-12-06 18:27:45 -08003738 }
3739
3740 // The fact that we've released the thread list lock is a bit risky --- if the thread goes
3741 // away we're sitting high and dry -- but we must release this before the ResumeAllThreads
3742 // call, and it's unwise to hold it during WaitForSuspend.
3743
3744 {
3745 /*
3746 * We change our (JDWP thread) status, which should be THREAD_RUNNING,
Elliott Hughes81ff3182012-03-23 20:35:56 -07003747 * so we can suspend for a GC if the invoke request causes us to
Elliott Hughesd07986f2011-12-06 18:27:45 -08003748 * run out of memory. It's also a good idea to change it before locking
3749 * the invokeReq mutex, although that should never be held for long.
3750 */
Ian Rogers00f7d0e2012-07-19 15:28:27 -07003751 self->TransitionFromRunnableToSuspended(kWaitingForDebuggerSend);
Elliott Hughesd07986f2011-12-06 18:27:45 -08003752
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08003753 VLOG(jdwp) << " Transferring control to event thread";
Elliott Hughesd07986f2011-12-06 18:27:45 -08003754 {
Sebastien Hertzd38667a2013-11-25 15:43:54 +01003755 MutexLock mu(self, req->lock);
Elliott Hughesd07986f2011-12-06 18:27:45 -08003756
3757 if ((options & JDWP::INVOKE_SINGLE_THREADED) == 0) {
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08003758 VLOG(jdwp) << " Resuming all threads";
Ian Rogers00f7d0e2012-07-19 15:28:27 -07003759 thread_list->UndoDebuggerSuspensions();
Elliott Hughesd07986f2011-12-06 18:27:45 -08003760 } else {
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08003761 VLOG(jdwp) << " Resuming event thread only";
Elliott Hughesd07986f2011-12-06 18:27:45 -08003762 thread_list->Resume(targetThread, true);
3763 }
3764
3765 // Wait for the request to finish executing.
Sebastien Hertzd38667a2013-11-25 15:43:54 +01003766 while (req->invoke_needed) {
3767 req->cond.Wait(self);
Elliott Hughesd07986f2011-12-06 18:27:45 -08003768 }
3769 }
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08003770 VLOG(jdwp) << " Control has returned from event thread";
Elliott Hughesd07986f2011-12-06 18:27:45 -08003771
3772 /* wait for thread to re-suspend itself */
Brian Carlstromdf629502013-07-17 22:39:56 -07003773 SuspendThread(thread_id, false /* request_suspension */);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07003774 self->TransitionFromSuspendedToRunnable();
Elliott Hughesd07986f2011-12-06 18:27:45 -08003775 }
3776
3777 /*
3778 * Suspend the threads. We waited for the target thread to suspend
3779 * itself, so all we need to do is suspend the others.
3780 *
3781 * The suspendAllThreads() call will double-suspend the event thread,
3782 * so we want to resume the target thread once to keep the books straight.
3783 */
3784 if ((options & JDWP::INVOKE_SINGLE_THREADED) == 0) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07003785 self->TransitionFromRunnableToSuspended(kWaitingForDebuggerSuspension);
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08003786 VLOG(jdwp) << " Suspending all threads";
Ian Rogers00f7d0e2012-07-19 15:28:27 -07003787 thread_list->SuspendAllForDebugger();
3788 self->TransitionFromSuspendedToRunnable();
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08003789 VLOG(jdwp) << " Resuming event thread to balance the count";
Elliott Hughesd07986f2011-12-06 18:27:45 -08003790 thread_list->Resume(targetThread, true);
3791 }
3792
3793 // Copy the result.
3794 *pResultTag = req->result_tag;
3795 if (IsPrimitiveTag(req->result_tag)) {
Elliott Hughesf24d3ce2012-04-11 17:43:37 -07003796 *pResultValue = req->result_value.GetJ();
Elliott Hughesd07986f2011-12-06 18:27:45 -08003797 } else {
Elliott Hughesf24d3ce2012-04-11 17:43:37 -07003798 *pResultValue = gRegistry->Add(req->result_value.GetL());
Elliott Hughesd07986f2011-12-06 18:27:45 -08003799 }
3800 *pExceptionId = req->exception;
3801 return req->error;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07003802}
3803
3804void Dbg::ExecuteMethod(DebugInvokeReq* pReq) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07003805 ScopedObjectAccess soa(Thread::Current());
Elliott Hughesd07986f2011-12-06 18:27:45 -08003806
Elliott Hughes81ff3182012-03-23 20:35:56 -07003807 // We can be called while an exception is pending. We need
Elliott Hughesd07986f2011-12-06 18:27:45 -08003808 // to preserve that across the method invocation.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003809 StackHandleScope<4> hs(soa.Self());
3810 auto old_throw_this_object = hs.NewHandle<mirror::Object>(nullptr);
3811 auto old_throw_method = hs.NewHandle<mirror::ArtMethod>(nullptr);
3812 auto old_exception = hs.NewHandle<mirror::Throwable>(nullptr);
Ian Rogers62d6c772013-02-27 08:32:07 -08003813 uint32_t old_throw_dex_pc;
Sebastien Hertz9f102032014-05-23 08:59:42 +02003814 bool old_exception_report_flag;
Ian Rogers62d6c772013-02-27 08:32:07 -08003815 {
3816 ThrowLocation old_throw_location;
3817 mirror::Throwable* old_exception_obj = soa.Self()->GetException(&old_throw_location);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003818 old_throw_this_object.Assign(old_throw_location.GetThis());
3819 old_throw_method.Assign(old_throw_location.GetMethod());
3820 old_exception.Assign(old_exception_obj);
Ian Rogers62d6c772013-02-27 08:32:07 -08003821 old_throw_dex_pc = old_throw_location.GetDexPc();
Sebastien Hertz9f102032014-05-23 08:59:42 +02003822 old_exception_report_flag = soa.Self()->IsExceptionReportedToInstrumentation();
Ian Rogers62d6c772013-02-27 08:32:07 -08003823 soa.Self()->ClearException();
3824 }
Elliott Hughesd07986f2011-12-06 18:27:45 -08003825
3826 // Translate the method through the vtable, unless the debugger wants to suppress it.
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07003827 MutableHandle<mirror::ArtMethod> m(hs.NewHandle(pReq->method));
Ian Rogersc0542af2014-09-03 16:16:56 -07003828 if ((pReq->options & JDWP::INVOKE_NONVIRTUAL) == 0 && pReq->receiver != nullptr) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003829 mirror::ArtMethod* actual_method = pReq->klass->FindVirtualMethodForVirtualOrInterface(m.Get());
3830 if (actual_method != m.Get()) {
3831 VLOG(jdwp) << "ExecuteMethod translated " << PrettyMethod(m.Get()) << " to " << PrettyMethod(actual_method);
3832 m.Assign(actual_method);
Elliott Hughes45651fd2012-02-21 15:48:20 -08003833 }
Elliott Hughesd07986f2011-12-06 18:27:45 -08003834 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003835 VLOG(jdwp) << "ExecuteMethod " << PrettyMethod(m.Get())
Sebastien Hertzd38667a2013-11-25 15:43:54 +01003836 << " receiver=" << pReq->receiver
3837 << " arg_count=" << pReq->arg_count;
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003838 CHECK(m.Get() != nullptr);
Elliott Hughesd07986f2011-12-06 18:27:45 -08003839
3840 CHECK_EQ(sizeof(jvalue), sizeof(uint64_t));
3841
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003842 pReq->result_value = InvokeWithJValues(soa, pReq->receiver, soa.EncodeMethod(m.Get()),
Ian Rogers53b8b092014-03-13 23:45:53 -07003843 reinterpret_cast<jvalue*>(pReq->arg_values));
Elliott Hughesd07986f2011-12-06 18:27:45 -08003844
Ian Rogersc0542af2014-09-03 16:16:56 -07003845 mirror::Throwable* exception = soa.Self()->GetException(nullptr);
Ian Rogers62d6c772013-02-27 08:32:07 -08003846 soa.Self()->ClearException();
3847 pReq->exception = gRegistry->Add(exception);
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07003848 pReq->result_tag = BasicTagFromDescriptor(m.Get()->GetShorty());
Elliott Hughesd07986f2011-12-06 18:27:45 -08003849 if (pReq->exception != 0) {
Ian Rogers62d6c772013-02-27 08:32:07 -08003850 VLOG(jdwp) << " JDWP invocation returning with exception=" << exception
3851 << " " << exception->Dump();
Elliott Hughesf24d3ce2012-04-11 17:43:37 -07003852 pReq->result_value.SetJ(0);
Elliott Hughesd07986f2011-12-06 18:27:45 -08003853 } else if (pReq->result_tag == JDWP::JT_OBJECT) {
3854 /* if no exception thrown, examine object result more closely */
Ian Rogers98379392014-02-24 16:53:16 -08003855 JDWP::JdwpTag new_tag = TagFromObject(soa, pReq->result_value.GetL());
Elliott Hughesd07986f2011-12-06 18:27:45 -08003856 if (new_tag != pReq->result_tag) {
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08003857 VLOG(jdwp) << " JDWP promoted result from " << pReq->result_tag << " to " << new_tag;
Elliott Hughesd07986f2011-12-06 18:27:45 -08003858 pReq->result_tag = new_tag;
3859 }
3860
3861 /*
3862 * Register the object. We don't actually need an ObjectId yet,
3863 * but we do need to be sure that the GC won't move or discard the
3864 * object when we switch out of RUNNING. The ObjectId conversion
3865 * will add the object to the "do not touch" list.
3866 *
3867 * We can't use the "tracked allocation" mechanism here because
3868 * the object is going to be handed off to a different thread.
3869 */
Elliott Hughesf24d3ce2012-04-11 17:43:37 -07003870 gRegistry->Add(pReq->result_value.GetL());
Elliott Hughesd07986f2011-12-06 18:27:45 -08003871 }
3872
Ian Rogersc0542af2014-09-03 16:16:56 -07003873 if (old_exception.Get() != nullptr) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003874 ThrowLocation gc_safe_throw_location(old_throw_this_object.Get(), old_throw_method.Get(),
Ian Rogers62d6c772013-02-27 08:32:07 -08003875 old_throw_dex_pc);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003876 soa.Self()->SetException(gc_safe_throw_location, old_exception.Get());
Sebastien Hertz9f102032014-05-23 08:59:42 +02003877 soa.Self()->SetExceptionReportedToInstrumentation(old_exception_report_flag);
Elliott Hughesd07986f2011-12-06 18:27:45 -08003878 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -07003879}
3880
Elliott Hughesd07986f2011-12-06 18:27:45 -08003881/*
Elliott Hughes4b9702c2013-02-20 18:13:24 -08003882 * "request" contains a full JDWP packet, possibly with multiple chunks. We
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07003883 * need to process each, accumulate the replies, and ship the whole thing
3884 * back.
3885 *
3886 * Returns "true" if we have a reply. The reply buffer is newly allocated,
3887 * and includes the chunk type/length, followed by the data.
3888 *
Elliott Hughes3d30d9b2011-12-07 17:35:48 -08003889 * OLD-TODO: we currently assume that the request and reply include a single
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07003890 * chunk. If this becomes inconvenient we will need to adapt.
3891 */
Ian Rogersc0542af2014-09-03 16:16:56 -07003892bool Dbg::DdmHandlePacket(JDWP::Request* request, uint8_t** pReplyBuf, int* pReplyLen) {
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07003893 Thread* self = Thread::Current();
3894 JNIEnv* env = self->GetJniEnv();
3895
Ian Rogersc0542af2014-09-03 16:16:56 -07003896 uint32_t type = request->ReadUnsigned32("type");
3897 uint32_t length = request->ReadUnsigned32("length");
Elliott Hughes4b9702c2013-02-20 18:13:24 -08003898
3899 // Create a byte[] corresponding to 'request'.
Ian Rogersc0542af2014-09-03 16:16:56 -07003900 size_t request_length = request->size();
Elliott Hughes4b9702c2013-02-20 18:13:24 -08003901 ScopedLocalRef<jbyteArray> dataArray(env, env->NewByteArray(request_length));
Ian Rogersc0542af2014-09-03 16:16:56 -07003902 if (dataArray.get() == nullptr) {
Elliott Hughes4b9702c2013-02-20 18:13:24 -08003903 LOG(WARNING) << "byte[] allocation failed: " << request_length;
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07003904 env->ExceptionClear();
3905 return false;
3906 }
Ian Rogersc0542af2014-09-03 16:16:56 -07003907 env->SetByteArrayRegion(dataArray.get(), 0, request_length,
3908 reinterpret_cast<const jbyte*>(request->data()));
3909 request->Skip(request_length);
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07003910
3911 // Run through and find all chunks. [Currently just find the first.]
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003912 ScopedByteArrayRO contents(env, dataArray.get());
Elliott Hughes4b9702c2013-02-20 18:13:24 -08003913 if (length != request_length) {
Ian Rogersef7d42f2014-01-06 12:55:46 -08003914 LOG(WARNING) << StringPrintf("bad chunk found (len=%u pktLen=%zd)", length, request_length);
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07003915 return false;
3916 }
3917
3918 // Call "private static Chunk dispatch(int type, byte[] data, int offset, int length)".
Elliott Hugheseac76672012-05-24 21:56:51 -07003919 ScopedLocalRef<jobject> chunk(env, env->CallStaticObjectMethod(WellKnownClasses::org_apache_harmony_dalvik_ddmc_DdmServer,
3920 WellKnownClasses::org_apache_harmony_dalvik_ddmc_DdmServer_dispatch,
Elliott Hughes4b9702c2013-02-20 18:13:24 -08003921 type, dataArray.get(), 0, length));
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07003922 if (env->ExceptionCheck()) {
3923 LOG(INFO) << StringPrintf("Exception thrown by dispatcher for 0x%08x", type);
3924 env->ExceptionDescribe();
3925 env->ExceptionClear();
3926 return false;
3927 }
3928
Ian Rogersc0542af2014-09-03 16:16:56 -07003929 if (chunk.get() == nullptr) {
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07003930 return false;
3931 }
3932
3933 /*
3934 * Pull the pieces out of the chunk. We copy the results into a
3935 * newly-allocated buffer that the caller can free. We don't want to
3936 * continue using the Chunk object because nothing has a reference to it.
3937 *
3938 * We could avoid this by returning type/data/offset/length and having
3939 * the caller be aware of the object lifetime issues, but that
Elliott Hughes81ff3182012-03-23 20:35:56 -07003940 * integrates the JDWP code more tightly into the rest of the runtime, and doesn't work
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07003941 * if we have responses for multiple chunks.
3942 *
3943 * So we're pretty much stuck with copying data around multiple times.
3944 */
Elliott Hugheseac76672012-05-24 21:56:51 -07003945 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 -08003946 jint offset = env->GetIntField(chunk.get(), WellKnownClasses::org_apache_harmony_dalvik_ddmc_Chunk_offset);
Elliott Hugheseac76672012-05-24 21:56:51 -07003947 length = env->GetIntField(chunk.get(), WellKnownClasses::org_apache_harmony_dalvik_ddmc_Chunk_length);
Elliott Hugheseac76672012-05-24 21:56:51 -07003948 type = env->GetIntField(chunk.get(), WellKnownClasses::org_apache_harmony_dalvik_ddmc_Chunk_type);
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07003949
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08003950 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 -07003951 if (length == 0 || replyData.get() == nullptr) {
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07003952 return false;
3953 }
3954
Elliott Hughes4b9702c2013-02-20 18:13:24 -08003955 const int kChunkHdrLen = 8;
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07003956 uint8_t* reply = new uint8_t[length + kChunkHdrLen];
Ian Rogersc0542af2014-09-03 16:16:56 -07003957 if (reply == nullptr) {
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07003958 LOG(WARNING) << "malloc failed: " << (length + kChunkHdrLen);
3959 return false;
3960 }
Elliott Hughesf7c3b662011-10-27 12:04:56 -07003961 JDWP::Set4BE(reply + 0, type);
3962 JDWP::Set4BE(reply + 4, length);
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003963 env->GetByteArrayRegion(replyData.get(), offset, length, reinterpret_cast<jbyte*>(reply + kChunkHdrLen));
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07003964
3965 *pReplyBuf = reply;
3966 *pReplyLen = length + kChunkHdrLen;
3967
Elliott Hughes4b9702c2013-02-20 18:13:24 -08003968 VLOG(jdwp) << StringPrintf("dvmHandleDdm returning type=%.4s %p len=%d", reinterpret_cast<char*>(reply), reply, length);
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07003969 return true;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07003970}
3971
Elliott Hughesa2155262011-11-16 16:26:58 -08003972void Dbg::DdmBroadcast(bool connect) {
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08003973 VLOG(jdwp) << "Broadcasting DDM " << (connect ? "connect" : "disconnect") << "...";
Elliott Hughes47fce012011-10-25 18:37:19 -07003974
3975 Thread* self = Thread::Current();
Ian Rogers50b35e22012-10-04 10:09:15 -07003976 if (self->GetState() != kRunnable) {
3977 LOG(ERROR) << "DDM broadcast in thread state " << self->GetState();
3978 /* try anyway? */
Elliott Hughes47fce012011-10-25 18:37:19 -07003979 }
3980
3981 JNIEnv* env = self->GetJniEnv();
Elliott Hughes47fce012011-10-25 18:37:19 -07003982 jint event = connect ? 1 /*DdmServer.CONNECTED*/ : 2 /*DdmServer.DISCONNECTED*/;
Elliott Hugheseac76672012-05-24 21:56:51 -07003983 env->CallStaticVoidMethod(WellKnownClasses::org_apache_harmony_dalvik_ddmc_DdmServer,
3984 WellKnownClasses::org_apache_harmony_dalvik_ddmc_DdmServer_broadcast,
3985 event);
Elliott Hughes47fce012011-10-25 18:37:19 -07003986 if (env->ExceptionCheck()) {
3987 LOG(ERROR) << "DdmServer.broadcast " << event << " failed";
3988 env->ExceptionDescribe();
3989 env->ExceptionClear();
3990 }
3991}
3992
Elliott Hughes872d4ec2011-10-21 17:07:15 -07003993void Dbg::DdmConnected() {
Elliott Hughesa2155262011-11-16 16:26:58 -08003994 Dbg::DdmBroadcast(true);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07003995}
3996
3997void Dbg::DdmDisconnected() {
Elliott Hughesa2155262011-11-16 16:26:58 -08003998 Dbg::DdmBroadcast(false);
Elliott Hughes47fce012011-10-25 18:37:19 -07003999 gDdmThreadNotification = false;
4000}
4001
4002/*
Elliott Hughes82188472011-11-07 18:11:48 -08004003 * Send a notification when a thread starts, stops, or changes its name.
Elliott Hughes47fce012011-10-25 18:37:19 -07004004 *
4005 * Because we broadcast the full set of threads when the notifications are
4006 * first enabled, it's possible for "thread" to be actively executing.
4007 */
Elliott Hughes82188472011-11-07 18:11:48 -08004008void Dbg::DdmSendThreadNotification(Thread* t, uint32_t type) {
Elliott Hughes47fce012011-10-25 18:37:19 -07004009 if (!gDdmThreadNotification) {
4010 return;
4011 }
4012
Elliott Hughes82188472011-11-07 18:11:48 -08004013 if (type == CHUNK_TYPE("THDE")) {
Elliott Hughes47fce012011-10-25 18:37:19 -07004014 uint8_t buf[4];
Ian Rogersd9c4fc92013-10-01 19:45:43 -07004015 JDWP::Set4BE(&buf[0], t->GetThreadId());
Elliott Hughes47fce012011-10-25 18:37:19 -07004016 Dbg::DdmSendChunk(CHUNK_TYPE("THDE"), 4, buf);
Elliott Hughes82188472011-11-07 18:11:48 -08004017 } else {
4018 CHECK(type == CHUNK_TYPE("THCR") || type == CHUNK_TYPE("THNM")) << type;
Ian Rogers00f7d0e2012-07-19 15:28:27 -07004019 ScopedObjectAccessUnchecked soa(Thread::Current());
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004020 StackHandleScope<1> hs(soa.Self());
4021 Handle<mirror::String> name(hs.NewHandle(t->GetThreadName(soa)));
Ian Rogersc0542af2014-09-03 16:16:56 -07004022 size_t char_count = (name.Get() != nullptr) ? name->GetLength() : 0;
4023 const jchar* chars = (name.Get() != nullptr) ? name->GetCharArray()->GetData() : nullptr;
Elliott Hughes82188472011-11-07 18:11:48 -08004024
Elliott Hughes21f32d72011-11-09 17:44:13 -08004025 std::vector<uint8_t> bytes;
Ian Rogersd9c4fc92013-10-01 19:45:43 -07004026 JDWP::Append4BE(bytes, t->GetThreadId());
Elliott Hughes545a0642011-11-08 19:10:03 -08004027 JDWP::AppendUtf16BE(bytes, chars, char_count);
Elliott Hughes21f32d72011-11-09 17:44:13 -08004028 CHECK_EQ(bytes.size(), char_count*2 + sizeof(uint32_t)*2);
4029 Dbg::DdmSendChunk(type, bytes);
Elliott Hughes47fce012011-10-25 18:37:19 -07004030 }
4031}
4032
Elliott Hughes47fce012011-10-25 18:37:19 -07004033void Dbg::DdmSetThreadNotification(bool enable) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07004034 // Enable/disable thread notifications.
Elliott Hughes47fce012011-10-25 18:37:19 -07004035 gDdmThreadNotification = enable;
4036 if (enable) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07004037 // Suspend the VM then post thread start notifications for all threads. Threads attaching will
4038 // see a suspension in progress and block until that ends. They then post their own start
4039 // notification.
4040 SuspendVM();
4041 std::list<Thread*> threads;
Ian Rogers50b35e22012-10-04 10:09:15 -07004042 Thread* self = Thread::Current();
Ian Rogers00f7d0e2012-07-19 15:28:27 -07004043 {
Ian Rogers50b35e22012-10-04 10:09:15 -07004044 MutexLock mu(self, *Locks::thread_list_lock_);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07004045 threads = Runtime::Current()->GetThreadList()->GetList();
4046 }
4047 {
Ian Rogers50b35e22012-10-04 10:09:15 -07004048 ScopedObjectAccess soa(self);
Mathieu Chartier02e25112013-08-14 16:14:24 -07004049 for (Thread* thread : threads) {
4050 Dbg::DdmSendThreadNotification(thread, CHUNK_TYPE("THCR"));
Ian Rogers00f7d0e2012-07-19 15:28:27 -07004051 }
4052 }
4053 ResumeVM();
Elliott Hughes47fce012011-10-25 18:37:19 -07004054 }
4055}
4056
Elliott Hughesa2155262011-11-16 16:26:58 -08004057void Dbg::PostThreadStartOrStop(Thread* t, uint32_t type) {
Elliott Hughesc0f09332012-03-26 13:27:06 -07004058 if (IsDebuggerActive()) {
Sebastien Hertz6995c602014-09-09 12:10:13 +02004059 gJdwpState->PostThreadChange(t, type == CHUNK_TYPE("THCR"));
Elliott Hughes47fce012011-10-25 18:37:19 -07004060 }
Elliott Hughes82188472011-11-07 18:11:48 -08004061 Dbg::DdmSendThreadNotification(t, type);
Elliott Hughes47fce012011-10-25 18:37:19 -07004062}
4063
4064void Dbg::PostThreadStart(Thread* t) {
Elliott Hughesa2155262011-11-16 16:26:58 -08004065 Dbg::PostThreadStartOrStop(t, CHUNK_TYPE("THCR"));
Elliott Hughes47fce012011-10-25 18:37:19 -07004066}
4067
4068void Dbg::PostThreadDeath(Thread* t) {
Elliott Hughesa2155262011-11-16 16:26:58 -08004069 Dbg::PostThreadStartOrStop(t, CHUNK_TYPE("THDE"));
Elliott Hughes872d4ec2011-10-21 17:07:15 -07004070}
4071
Elliott Hughes82188472011-11-07 18:11:48 -08004072void Dbg::DdmSendChunk(uint32_t type, size_t byte_count, const uint8_t* buf) {
Ian Rogersc0542af2014-09-03 16:16:56 -07004073 CHECK(buf != nullptr);
Elliott Hughes3bb81562011-10-21 18:52:59 -07004074 iovec vec[1];
4075 vec[0].iov_base = reinterpret_cast<void*>(const_cast<uint8_t*>(buf));
4076 vec[0].iov_len = byte_count;
4077 Dbg::DdmSendChunkV(type, vec, 1);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07004078}
4079
Elliott Hughes21f32d72011-11-09 17:44:13 -08004080void Dbg::DdmSendChunk(uint32_t type, const std::vector<uint8_t>& bytes) {
4081 DdmSendChunk(type, bytes.size(), &bytes[0]);
4082}
4083
Brian Carlstromf5293522013-07-19 00:24:00 -07004084void Dbg::DdmSendChunkV(uint32_t type, const iovec* iov, int iov_count) {
Ian Rogersc0542af2014-09-03 16:16:56 -07004085 if (gJdwpState == nullptr) {
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08004086 VLOG(jdwp) << "Debugger thread not active, ignoring DDM send: " << type;
Elliott Hughes3bb81562011-10-21 18:52:59 -07004087 } else {
Elliott Hughescccd84f2011-12-05 16:51:54 -08004088 gJdwpState->DdmSendChunkV(type, iov, iov_count);
Elliott Hughes3bb81562011-10-21 18:52:59 -07004089 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -07004090}
4091
Mathieu Chartierad466ad2015-01-08 16:28:08 -08004092JDWP::JdwpState* Dbg::GetJdwpState() {
4093 return gJdwpState;
4094}
4095
Elliott Hughes767a1472011-10-26 18:49:02 -07004096int Dbg::DdmHandleHpifChunk(HpifWhen when) {
4097 if (when == HPIF_WHEN_NOW) {
Elliott Hughes7162ad92011-10-27 14:08:42 -07004098 DdmSendHeapInfo(when);
Elliott Hughes767a1472011-10-26 18:49:02 -07004099 return true;
4100 }
4101
4102 if (when != HPIF_WHEN_NEVER && when != HPIF_WHEN_NEXT_GC && when != HPIF_WHEN_EVERY_GC) {
4103 LOG(ERROR) << "invalid HpifWhen value: " << static_cast<int>(when);
4104 return false;
4105 }
4106
4107 gDdmHpifWhen = when;
4108 return true;
4109}
4110
4111bool Dbg::DdmHandleHpsgNhsgChunk(Dbg::HpsgWhen when, Dbg::HpsgWhat what, bool native) {
4112 if (when != HPSG_WHEN_NEVER && when != HPSG_WHEN_EVERY_GC) {
4113 LOG(ERROR) << "invalid HpsgWhen value: " << static_cast<int>(when);
4114 return false;
4115 }
4116
4117 if (what != HPSG_WHAT_MERGED_OBJECTS && what != HPSG_WHAT_DISTINCT_OBJECTS) {
4118 LOG(ERROR) << "invalid HpsgWhat value: " << static_cast<int>(what);
4119 return false;
4120 }
4121
4122 if (native) {
4123 gDdmNhsgWhen = when;
4124 gDdmNhsgWhat = what;
4125 } else {
4126 gDdmHpsgWhen = when;
4127 gDdmHpsgWhat = what;
4128 }
4129 return true;
4130}
4131
Elliott Hughes7162ad92011-10-27 14:08:42 -07004132void Dbg::DdmSendHeapInfo(HpifWhen reason) {
4133 // If there's a one-shot 'when', reset it.
4134 if (reason == gDdmHpifWhen) {
4135 if (gDdmHpifWhen == HPIF_WHEN_NEXT_GC) {
4136 gDdmHpifWhen = HPIF_WHEN_NEVER;
4137 }
4138 }
4139
4140 /*
4141 * Chunk HPIF (client --> server)
4142 *
4143 * Heap Info. General information about the heap,
4144 * suitable for a summary display.
4145 *
4146 * [u4]: number of heaps
4147 *
4148 * For each heap:
4149 * [u4]: heap ID
4150 * [u8]: timestamp in ms since Unix epoch
4151 * [u1]: capture reason (same as 'when' value from server)
4152 * [u4]: max heap size in bytes (-Xmx)
4153 * [u4]: current heap size in bytes
4154 * [u4]: current number of bytes allocated
4155 * [u4]: current number of objects allocated
4156 */
4157 uint8_t heap_count = 1;
Ian Rogers1d54e732013-05-02 21:10:01 -07004158 gc::Heap* heap = Runtime::Current()->GetHeap();
Elliott Hughes21f32d72011-11-09 17:44:13 -08004159 std::vector<uint8_t> bytes;
Elliott Hughes545a0642011-11-08 19:10:03 -08004160 JDWP::Append4BE(bytes, heap_count);
Brian Carlstrom7934ac22013-07-26 10:54:15 -07004161 JDWP::Append4BE(bytes, 1); // Heap id (bogus; we only have one heap).
Elliott Hughes545a0642011-11-08 19:10:03 -08004162 JDWP::Append8BE(bytes, MilliTime());
4163 JDWP::Append1BE(bytes, reason);
Brian Carlstrom7934ac22013-07-26 10:54:15 -07004164 JDWP::Append4BE(bytes, heap->GetMaxMemory()); // Max allowed heap size in bytes.
4165 JDWP::Append4BE(bytes, heap->GetTotalMemory()); // Current heap size in bytes.
Elliott Hughesb3bd5f02012-03-08 21:05:27 -08004166 JDWP::Append4BE(bytes, heap->GetBytesAllocated());
4167 JDWP::Append4BE(bytes, heap->GetObjectsAllocated());
Elliott Hughes21f32d72011-11-09 17:44:13 -08004168 CHECK_EQ(bytes.size(), 4U + (heap_count * (4 + 8 + 1 + 4 + 4 + 4 + 4)));
4169 Dbg::DdmSendChunk(CHUNK_TYPE("HPIF"), bytes);
Elliott Hughes767a1472011-10-26 18:49:02 -07004170}
4171
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004172enum HpsgSolidity {
4173 SOLIDITY_FREE = 0,
4174 SOLIDITY_HARD = 1,
4175 SOLIDITY_SOFT = 2,
4176 SOLIDITY_WEAK = 3,
4177 SOLIDITY_PHANTOM = 4,
4178 SOLIDITY_FINALIZABLE = 5,
4179 SOLIDITY_SWEEP = 6,
4180};
4181
4182enum HpsgKind {
4183 KIND_OBJECT = 0,
4184 KIND_CLASS_OBJECT = 1,
4185 KIND_ARRAY_1 = 2,
4186 KIND_ARRAY_2 = 3,
4187 KIND_ARRAY_4 = 4,
4188 KIND_ARRAY_8 = 5,
4189 KIND_UNKNOWN = 6,
4190 KIND_NATIVE = 7,
4191};
4192
4193#define HPSG_PARTIAL (1<<7)
4194#define HPSG_STATE(solidity, kind) ((uint8_t)((((kind) & 0x7) << 3) | ((solidity) & 0x7)))
4195
Ian Rogers30fab402012-01-23 15:43:46 -08004196class HeapChunkContext {
4197 public:
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004198 // Maximum chunk size. Obtain this from the formula:
4199 // (((maximum_heap_size / ALLOCATION_UNIT_SIZE) + 255) / 256) * 2
4200 HeapChunkContext(bool merge, bool native)
Ian Rogers30fab402012-01-23 15:43:46 -08004201 : buf_(16384 - 16),
4202 type_(0),
Mathieu Chartier36dab362014-07-30 14:59:56 -07004203 chunk_overhead_(0) {
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004204 Reset();
4205 if (native) {
Ian Rogers30fab402012-01-23 15:43:46 -08004206 type_ = CHUNK_TYPE("NHSG");
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004207 } else {
Ian Rogers30fab402012-01-23 15:43:46 -08004208 type_ = merge ? CHUNK_TYPE("HPSG") : CHUNK_TYPE("HPSO");
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004209 }
4210 }
4211
4212 ~HeapChunkContext() {
Ian Rogers30fab402012-01-23 15:43:46 -08004213 if (p_ > &buf_[0]) {
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004214 Flush();
4215 }
4216 }
4217
Mathieu Chartier36dab362014-07-30 14:59:56 -07004218 void SetChunkOverhead(size_t chunk_overhead) {
4219 chunk_overhead_ = chunk_overhead;
4220 }
4221
4222 void ResetStartOfNextChunk() {
4223 startOfNextMemoryChunk_ = nullptr;
4224 }
4225
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004226 void EnsureHeader(const void* chunk_ptr) {
Ian Rogers30fab402012-01-23 15:43:46 -08004227 if (!needHeader_) {
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004228 return;
4229 }
4230
4231 // Start a new HPSx chunk.
Brian Carlstrom7934ac22013-07-26 10:54:15 -07004232 JDWP::Write4BE(&p_, 1); // Heap id (bogus; we only have one heap).
4233 JDWP::Write1BE(&p_, 8); // Size of allocation unit, in bytes.
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004234
Brian Carlstrom7934ac22013-07-26 10:54:15 -07004235 JDWP::Write4BE(&p_, reinterpret_cast<uintptr_t>(chunk_ptr)); // virtual address of segment start.
4236 JDWP::Write4BE(&p_, 0); // offset of this piece (relative to the virtual address).
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004237 // [u4]: length of piece, in allocation units
4238 // 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 -08004239 pieceLenField_ = p_;
4240 JDWP::Write4BE(&p_, 0x55555555);
4241 needHeader_ = false;
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004242 }
4243
Ian Rogersb726dcb2012-09-05 08:57:23 -07004244 void Flush() SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Ian Rogersc0542af2014-09-03 16:16:56 -07004245 if (pieceLenField_ == nullptr) {
Ian Rogersd636b062013-01-18 17:51:18 -08004246 // Flush immediately post Reset (maybe back-to-back Flush). Ignore.
4247 CHECK(needHeader_);
4248 return;
4249 }
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004250 // Patch the "length of piece" field.
Ian Rogers30fab402012-01-23 15:43:46 -08004251 CHECK_LE(&buf_[0], pieceLenField_);
4252 CHECK_LE(pieceLenField_, p_);
4253 JDWP::Set4BE(pieceLenField_, totalAllocationUnits_);
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004254
Ian Rogers30fab402012-01-23 15:43:46 -08004255 Dbg::DdmSendChunk(type_, p_ - &buf_[0], &buf_[0]);
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004256 Reset();
4257 }
4258
Mathieu Chartierbc689b72014-12-14 17:01:31 -08004259 static void HeapChunkJavaCallback(void* start, void* end, size_t used_bytes, void* arg)
Ian Rogersb726dcb2012-09-05 08:57:23 -07004260 SHARED_LOCKS_REQUIRED(Locks::heap_bitmap_lock_,
4261 Locks::mutator_lock_) {
Mathieu Chartierbc689b72014-12-14 17:01:31 -08004262 reinterpret_cast<HeapChunkContext*>(arg)->HeapChunkJavaCallback(start, end, used_bytes);
4263 }
4264
4265 static void HeapChunkNativeCallback(void* start, void* end, size_t used_bytes, void* arg)
4266 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
4267 reinterpret_cast<HeapChunkContext*>(arg)->HeapChunkNativeCallback(start, end, used_bytes);
Elliott Hughesa2155262011-11-16 16:26:58 -08004268 }
4269
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004270 private:
Elliott Hughesa2155262011-11-16 16:26:58 -08004271 enum { ALLOCATION_UNIT_SIZE = 8 };
4272
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004273 void Reset() {
Ian Rogers30fab402012-01-23 15:43:46 -08004274 p_ = &buf_[0];
Mathieu Chartier36dab362014-07-30 14:59:56 -07004275 ResetStartOfNextChunk();
Ian Rogers30fab402012-01-23 15:43:46 -08004276 totalAllocationUnits_ = 0;
4277 needHeader_ = true;
Ian Rogersc0542af2014-09-03 16:16:56 -07004278 pieceLenField_ = nullptr;
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004279 }
4280
Mathieu Chartierbc689b72014-12-14 17:01:31 -08004281 bool IsNative() const {
4282 return type_ == CHUNK_TYPE("NHSG");
4283 }
4284
4285 // Returns true if the object is not an empty chunk.
4286 bool ProcessRecord(void* start, size_t used_bytes) SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Ian Rogers30fab402012-01-23 15:43:46 -08004287 // Note: heap call backs cannot manipulate the heap upon which they are crawling, care is taken
4288 // in the following code not to allocate memory, by ensuring buf_ is of the correct size
Ian Rogers15bf2d32012-08-28 17:33:04 -07004289 if (used_bytes == 0) {
Mathieu Chartierbc689b72014-12-14 17:01:31 -08004290 if (start == nullptr) {
4291 // Reset for start of new heap.
4292 startOfNextMemoryChunk_ = nullptr;
4293 Flush();
4294 }
4295 // Only process in use memory so that free region information
4296 // also includes dlmalloc book keeping.
4297 return false;
Elliott Hughesa2155262011-11-16 16:26:58 -08004298 }
Ian Rogersc0542af2014-09-03 16:16:56 -07004299 if (startOfNextMemoryChunk_ != nullptr) {
Mathieu Chartierbc689b72014-12-14 17:01:31 -08004300 // Transmit any pending free memory. Native free memory of over kMaxFreeLen could be because
4301 // of the use of mmaps, so don't report. If not free memory then start a new segment.
4302 bool flush = true;
4303 if (start > startOfNextMemoryChunk_) {
4304 const size_t kMaxFreeLen = 2 * kPageSize;
4305 void* free_start = startOfNextMemoryChunk_;
4306 void* free_end = start;
4307 const size_t free_len =
4308 reinterpret_cast<uintptr_t>(free_end) - reinterpret_cast<uintptr_t>(free_start);
4309 if (!IsNative() || free_len < kMaxFreeLen) {
4310 AppendChunk(HPSG_STATE(SOLIDITY_FREE, 0), free_start, free_len, IsNative());
4311 flush = false;
Ian Rogers15bf2d32012-08-28 17:33:04 -07004312 }
Mathieu Chartierbc689b72014-12-14 17:01:31 -08004313 }
4314 if (flush) {
4315 startOfNextMemoryChunk_ = nullptr;
4316 Flush();
4317 }
Ian Rogers15bf2d32012-08-28 17:33:04 -07004318 }
Mathieu Chartierbc689b72014-12-14 17:01:31 -08004319 return true;
Ian Rogers15bf2d32012-08-28 17:33:04 -07004320 }
Elliott Hughesa2155262011-11-16 16:26:58 -08004321
Mathieu Chartierbc689b72014-12-14 17:01:31 -08004322 void HeapChunkNativeCallback(void* start, void* /*end*/, size_t used_bytes)
4323 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
4324 if (ProcessRecord(start, used_bytes)) {
4325 uint8_t state = ExamineNativeObject(start);
4326 AppendChunk(state, start, used_bytes + chunk_overhead_, true /*is_native*/);
4327 startOfNextMemoryChunk_ = reinterpret_cast<char*>(start) + used_bytes + chunk_overhead_;
4328 }
4329 }
4330
4331 void HeapChunkJavaCallback(void* start, void* /*end*/, size_t used_bytes)
4332 SHARED_LOCKS_REQUIRED(Locks::heap_bitmap_lock_, Locks::mutator_lock_) {
4333 if (ProcessRecord(start, used_bytes)) {
4334 // Determine the type of this chunk.
4335 // OLD-TODO: if context.merge, see if this chunk is different from the last chunk.
4336 // If it's the same, we should combine them.
4337 uint8_t state = ExamineJavaObject(reinterpret_cast<mirror::Object*>(start));
4338 AppendChunk(state, start, used_bytes + chunk_overhead_, false /*is_native*/);
4339 startOfNextMemoryChunk_ = reinterpret_cast<char*>(start) + used_bytes + chunk_overhead_;
4340 }
4341 }
4342
4343 void AppendChunk(uint8_t state, void* ptr, size_t length, bool is_native)
Ian Rogersb726dcb2012-09-05 08:57:23 -07004344 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Ian Rogers15bf2d32012-08-28 17:33:04 -07004345 // Make sure there's enough room left in the buffer.
4346 // We need to use two bytes for every fractional 256 allocation units used by the chunk plus
4347 // 17 bytes for any header.
Mathieu Chartierbc689b72014-12-14 17:01:31 -08004348 const size_t needed = ((RoundUp(length / ALLOCATION_UNIT_SIZE, 256) / 256) * 2) + 17;
4349 size_t byte_left = &buf_.back() - p_;
4350 if (byte_left < needed) {
4351 if (is_native) {
Pavel Vyssotski7522c742014-12-08 13:38:26 +06004352 // Cannot trigger memory allocation while walking native heap.
Pavel Vyssotski7522c742014-12-08 13:38:26 +06004353 return;
4354 }
Ian Rogers15bf2d32012-08-28 17:33:04 -07004355 Flush();
4356 }
4357
Mathieu Chartierbc689b72014-12-14 17:01:31 -08004358 byte_left = &buf_.back() - p_;
4359 if (byte_left < needed) {
Ian Rogers15bf2d32012-08-28 17:33:04 -07004360 LOG(WARNING) << "Chunk is too big to transmit (chunk_len=" << length << ", "
4361 << needed << " bytes)";
4362 return;
4363 }
4364 EnsureHeader(ptr);
Elliott Hughesa2155262011-11-16 16:26:58 -08004365 // Write out the chunk description.
Ian Rogers15bf2d32012-08-28 17:33:04 -07004366 length /= ALLOCATION_UNIT_SIZE; // Convert to allocation units.
4367 totalAllocationUnits_ += length;
4368 while (length > 256) {
Ian Rogers30fab402012-01-23 15:43:46 -08004369 *p_++ = state | HPSG_PARTIAL;
4370 *p_++ = 255; // length - 1
Ian Rogers15bf2d32012-08-28 17:33:04 -07004371 length -= 256;
Elliott Hughesa2155262011-11-16 16:26:58 -08004372 }
Ian Rogers30fab402012-01-23 15:43:46 -08004373 *p_++ = state;
Ian Rogers15bf2d32012-08-28 17:33:04 -07004374 *p_++ = length - 1;
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004375 }
4376
Mathieu Chartierbc689b72014-12-14 17:01:31 -08004377 uint8_t ExamineNativeObject(const void* p) SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
4378 return p == nullptr ? HPSG_STATE(SOLIDITY_FREE, 0) : HPSG_STATE(SOLIDITY_HARD, KIND_NATIVE);
4379 }
4380
4381 uint8_t ExamineJavaObject(mirror::Object* o)
Ian Rogersef7d42f2014-01-06 12:55:46 -08004382 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_, Locks::heap_bitmap_lock_) {
Ian Rogersc0542af2014-09-03 16:16:56 -07004383 if (o == nullptr) {
Elliott Hughesa2155262011-11-16 16:26:58 -08004384 return HPSG_STATE(SOLIDITY_FREE, 0);
4385 }
Elliott Hughesa2155262011-11-16 16:26:58 -08004386 // It's an allocated chunk. Figure out what it is.
Mathieu Chartierbc689b72014-12-14 17:01:31 -08004387 gc::Heap* heap = Runtime::Current()->GetHeap();
4388 if (!heap->IsLiveObjectLocked(o)) {
4389 LOG(ERROR) << "Invalid object in managed heap: " << o;
Elliott Hughesa2155262011-11-16 16:26:58 -08004390 return HPSG_STATE(SOLIDITY_HARD, KIND_NATIVE);
4391 }
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08004392 mirror::Class* c = o->GetClass();
Ian Rogersc0542af2014-09-03 16:16:56 -07004393 if (c == nullptr) {
Elliott Hughesa2155262011-11-16 16:26:58 -08004394 // The object was probably just created but hasn't been initialized yet.
4395 return HPSG_STATE(SOLIDITY_HARD, KIND_OBJECT);
4396 }
Mathieu Chartierbc689b72014-12-14 17:01:31 -08004397 if (!heap->IsValidObjectAddress(c)) {
Ian Rogers15bf2d32012-08-28 17:33:04 -07004398 LOG(ERROR) << "Invalid class for managed heap object: " << o << " " << c;
Elliott Hughesa2155262011-11-16 16:26:58 -08004399 return HPSG_STATE(SOLIDITY_HARD, KIND_UNKNOWN);
4400 }
Elliott Hughesa2155262011-11-16 16:26:58 -08004401 if (c->IsClassClass()) {
4402 return HPSG_STATE(SOLIDITY_HARD, KIND_CLASS_OBJECT);
4403 }
Elliott Hughesa2155262011-11-16 16:26:58 -08004404 if (c->IsArrayClass()) {
Elliott Hughesa2155262011-11-16 16:26:58 -08004405 switch (c->GetComponentSize()) {
4406 case 1: return HPSG_STATE(SOLIDITY_HARD, KIND_ARRAY_1);
4407 case 2: return HPSG_STATE(SOLIDITY_HARD, KIND_ARRAY_2);
4408 case 4: return HPSG_STATE(SOLIDITY_HARD, KIND_ARRAY_4);
4409 case 8: return HPSG_STATE(SOLIDITY_HARD, KIND_ARRAY_8);
4410 }
4411 }
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004412 return HPSG_STATE(SOLIDITY_HARD, KIND_OBJECT);
4413 }
4414
Ian Rogers30fab402012-01-23 15:43:46 -08004415 std::vector<uint8_t> buf_;
4416 uint8_t* p_;
4417 uint8_t* pieceLenField_;
Ian Rogers15bf2d32012-08-28 17:33:04 -07004418 void* startOfNextMemoryChunk_;
Ian Rogers30fab402012-01-23 15:43:46 -08004419 size_t totalAllocationUnits_;
4420 uint32_t type_;
Ian Rogers30fab402012-01-23 15:43:46 -08004421 bool needHeader_;
Mathieu Chartier36dab362014-07-30 14:59:56 -07004422 size_t chunk_overhead_;
Ian Rogers30fab402012-01-23 15:43:46 -08004423
Elliott Hughesa2155262011-11-16 16:26:58 -08004424 DISALLOW_COPY_AND_ASSIGN(HeapChunkContext);
4425};
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004426
Mathieu Chartier36dab362014-07-30 14:59:56 -07004427static void BumpPointerSpaceCallback(mirror::Object* obj, void* arg)
4428 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) EXCLUSIVE_LOCKS_REQUIRED(Locks::heap_bitmap_lock_) {
4429 const size_t size = RoundUp(obj->SizeOf(), kObjectAlignment);
Mathieu Chartierbc689b72014-12-14 17:01:31 -08004430 HeapChunkContext::HeapChunkJavaCallback(
Mathieu Chartier36dab362014-07-30 14:59:56 -07004431 obj, reinterpret_cast<void*>(reinterpret_cast<uintptr_t>(obj) + size), size, arg);
4432}
4433
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004434void Dbg::DdmSendHeapSegments(bool native) {
Mathieu Chartierbc689b72014-12-14 17:01:31 -08004435 Dbg::HpsgWhen when = native ? gDdmNhsgWhen : gDdmHpsgWhen;
4436 Dbg::HpsgWhat what = native ? gDdmNhsgWhat : gDdmHpsgWhat;
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004437 if (when == HPSG_WHEN_NEVER) {
4438 return;
4439 }
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004440 // Figure out what kind of chunks we'll be sending.
Mathieu Chartierbc689b72014-12-14 17:01:31 -08004441 CHECK(what == HPSG_WHAT_MERGED_OBJECTS || what == HPSG_WHAT_DISTINCT_OBJECTS)
4442 << static_cast<int>(what);
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004443
4444 // First, send a heap start chunk.
4445 uint8_t heap_id[4];
Brian Carlstrom7934ac22013-07-26 10:54:15 -07004446 JDWP::Set4BE(&heap_id[0], 1); // Heap id (bogus; we only have one heap).
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004447 Dbg::DdmSendChunk(native ? CHUNK_TYPE("NHST") : CHUNK_TYPE("HPST"), sizeof(heap_id), heap_id);
Hiroshi Yamauchicf58d4a2013-09-26 14:21:22 -07004448 Thread* self = Thread::Current();
Hiroshi Yamauchicf58d4a2013-09-26 14:21:22 -07004449 Locks::mutator_lock_->AssertSharedHeld(self);
Hiroshi Yamauchicf58d4a2013-09-26 14:21:22 -07004450
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004451 // Send a series of heap segment chunks.
Mathieu Chartierbc689b72014-12-14 17:01:31 -08004452 HeapChunkContext context(what == HPSG_WHAT_MERGED_OBJECTS, native);
Elliott Hughesa2155262011-11-16 16:26:58 -08004453 if (native) {
Ian Rogers872dd822014-10-30 11:19:14 -07004454#if defined(HAVE_ANDROID_OS) && defined(USE_DLMALLOC)
Mathieu Chartierbc689b72014-12-14 17:01:31 -08004455 dlmalloc_inspect_all(HeapChunkContext::HeapChunkNativeCallback, &context);
4456 HeapChunkContext::HeapChunkNativeCallback(nullptr, nullptr, 0, &context); // Indicate end of a space.
Christopher Ferrisc4ddc042014-05-13 14:47:50 -07004457#else
4458 UNIMPLEMENTED(WARNING) << "Native heap inspection is only supported with dlmalloc";
4459#endif
Elliott Hughesa2155262011-11-16 16:26:58 -08004460 } else {
Ian Rogers1d54e732013-05-02 21:10:01 -07004461 gc::Heap* heap = Runtime::Current()->GetHeap();
Mathieu Chartier36dab362014-07-30 14:59:56 -07004462 for (const auto& space : heap->GetContinuousSpaces()) {
4463 if (space->IsDlMallocSpace()) {
Mathieu Chartier4c69d7f2014-10-10 12:45:50 -07004464 ReaderMutexLock mu(self, *Locks::heap_bitmap_lock_);
Mathieu Chartier36dab362014-07-30 14:59:56 -07004465 // dlmalloc's chunk header is 2 * sizeof(size_t), but if the previous chunk is in use for an
4466 // allocation then the first sizeof(size_t) may belong to it.
4467 context.SetChunkOverhead(sizeof(size_t));
Mathieu Chartierbc689b72014-12-14 17:01:31 -08004468 space->AsDlMallocSpace()->Walk(HeapChunkContext::HeapChunkJavaCallback, &context);
Mathieu Chartier36dab362014-07-30 14:59:56 -07004469 } else if (space->IsRosAllocSpace()) {
4470 context.SetChunkOverhead(0);
Mathieu Chartier4c69d7f2014-10-10 12:45:50 -07004471 // Need to acquire the mutator lock before the heap bitmap lock with exclusive access since
4472 // RosAlloc's internal logic doesn't know to release and reacquire the heap bitmap lock.
4473 self->TransitionFromRunnableToSuspended(kSuspended);
4474 ThreadList* tl = Runtime::Current()->GetThreadList();
4475 tl->SuspendAll();
4476 {
4477 ReaderMutexLock mu(self, *Locks::heap_bitmap_lock_);
Mathieu Chartierbc689b72014-12-14 17:01:31 -08004478 space->AsRosAllocSpace()->Walk(HeapChunkContext::HeapChunkJavaCallback, &context);
Mathieu Chartier4c69d7f2014-10-10 12:45:50 -07004479 }
4480 tl->ResumeAll();
4481 self->TransitionFromSuspendedToRunnable();
Mathieu Chartier36dab362014-07-30 14:59:56 -07004482 } else if (space->IsBumpPointerSpace()) {
Mathieu Chartier4c69d7f2014-10-10 12:45:50 -07004483 ReaderMutexLock mu(self, *Locks::heap_bitmap_lock_);
Mathieu Chartier36dab362014-07-30 14:59:56 -07004484 context.SetChunkOverhead(0);
Mathieu Chartier36dab362014-07-30 14:59:56 -07004485 space->AsBumpPointerSpace()->Walk(BumpPointerSpaceCallback, &context);
Mathieu Chartierbc689b72014-12-14 17:01:31 -08004486 HeapChunkContext::HeapChunkJavaCallback(nullptr, nullptr, 0, &context);
Mathieu Chartier36dab362014-07-30 14:59:56 -07004487 } else {
4488 UNIMPLEMENTED(WARNING) << "Not counting objects in space " << *space;
Mathieu Chartierb062fdd2012-07-03 09:51:48 -07004489 }
Mathieu Chartier36dab362014-07-30 14:59:56 -07004490 context.ResetStartOfNextChunk();
Mathieu Chartierb062fdd2012-07-03 09:51:48 -07004491 }
Mathieu Chartier4c69d7f2014-10-10 12:45:50 -07004492 ReaderMutexLock mu(self, *Locks::heap_bitmap_lock_);
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -07004493 // Walk the large objects, these are not in the AllocSpace.
Mathieu Chartier36dab362014-07-30 14:59:56 -07004494 context.SetChunkOverhead(0);
Mathieu Chartierbc689b72014-12-14 17:01:31 -08004495 heap->GetLargeObjectsSpace()->Walk(HeapChunkContext::HeapChunkJavaCallback, &context);
Elliott Hughesa2155262011-11-16 16:26:58 -08004496 }
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004497
4498 // Finally, send a heap end chunk.
4499 Dbg::DdmSendChunk(native ? CHUNK_TYPE("NHEN") : CHUNK_TYPE("HPEN"), sizeof(heap_id), heap_id);
Elliott Hughes767a1472011-10-26 18:49:02 -07004500}
4501
Elliott Hughesb1a58792013-07-11 18:10:58 -07004502static size_t GetAllocTrackerMax() {
4503#ifdef HAVE_ANDROID_OS
4504 // Check whether there's a system property overriding the number of records.
4505 const char* propertyName = "dalvik.vm.allocTrackerMax";
4506 char allocRecordMaxString[PROPERTY_VALUE_MAX];
4507 if (property_get(propertyName, allocRecordMaxString, "") > 0) {
4508 char* end;
4509 size_t value = strtoul(allocRecordMaxString, &end, 10);
4510 if (*end != '\0') {
Ruben Brunk3e47a742013-09-09 17:56:07 -07004511 LOG(ERROR) << "Ignoring " << propertyName << " '" << allocRecordMaxString
4512 << "' --- invalid";
Elliott Hughesb1a58792013-07-11 18:10:58 -07004513 return kDefaultNumAllocRecords;
4514 }
4515 if (!IsPowerOfTwo(value)) {
Ruben Brunk3e47a742013-09-09 17:56:07 -07004516 LOG(ERROR) << "Ignoring " << propertyName << " '" << allocRecordMaxString
4517 << "' --- not power of two";
Elliott Hughesb1a58792013-07-11 18:10:58 -07004518 return kDefaultNumAllocRecords;
4519 }
4520 return value;
4521 }
4522#endif
4523 return kDefaultNumAllocRecords;
4524}
4525
Brian Carlstrom306db812014-09-05 13:01:41 -07004526void Dbg::SetAllocTrackingEnabled(bool enable) {
4527 Thread* self = Thread::Current();
4528 if (enable) {
Sebastien Hertzb98063a2014-03-26 10:57:20 +01004529 {
Brian Carlstrom306db812014-09-05 13:01:41 -07004530 MutexLock mu(self, *Locks::alloc_tracker_lock_);
4531 if (recent_allocation_records_ != nullptr) {
4532 return; // Already enabled, bail.
Sebastien Hertzb98063a2014-03-26 10:57:20 +01004533 }
Brian Carlstrom306db812014-09-05 13:01:41 -07004534 alloc_record_max_ = GetAllocTrackerMax();
4535 LOG(INFO) << "Enabling alloc tracker (" << alloc_record_max_ << " entries of "
4536 << kMaxAllocRecordStackDepth << " frames, taking "
4537 << PrettySize(sizeof(AllocRecord) * alloc_record_max_) << ")";
4538 DCHECK_EQ(alloc_record_head_, 0U);
4539 DCHECK_EQ(alloc_record_count_, 0U);
4540 recent_allocation_records_ = new AllocRecord[alloc_record_max_];
4541 CHECK(recent_allocation_records_ != nullptr);
Elliott Hughes545a0642011-11-08 19:10:03 -08004542 }
Mathieu Chartier9ef78b52014-09-25 17:03:12 -07004543 Runtime::Current()->GetInstrumentation()->InstrumentQuickAllocEntryPoints();
Elliott Hughes545a0642011-11-08 19:10:03 -08004544 } else {
Sebastien Hertzb98063a2014-03-26 10:57:20 +01004545 {
Brian Carlstrom306db812014-09-05 13:01:41 -07004546 ScopedObjectAccess soa(self); // For type_cache_.Clear();
4547 MutexLock mu(self, *Locks::alloc_tracker_lock_);
4548 if (recent_allocation_records_ == nullptr) {
4549 return; // Already disabled, bail.
4550 }
Mathieu Chartier4345c462014-06-27 10:20:14 -07004551 LOG(INFO) << "Disabling alloc tracker";
Sebastien Hertzb98063a2014-03-26 10:57:20 +01004552 delete[] recent_allocation_records_;
Ian Rogersc0542af2014-09-03 16:16:56 -07004553 recent_allocation_records_ = nullptr;
Brian Carlstrom306db812014-09-05 13:01:41 -07004554 alloc_record_head_ = 0;
4555 alloc_record_count_ = 0;
Mathieu Chartier4345c462014-06-27 10:20:14 -07004556 type_cache_.Clear();
Sebastien Hertzb98063a2014-03-26 10:57:20 +01004557 }
Brian Carlstrom306db812014-09-05 13:01:41 -07004558 // If an allocation comes in before we uninstrument, we will safely drop it on the floor.
Mathieu Chartier9ef78b52014-09-25 17:03:12 -07004559 Runtime::Current()->GetInstrumentation()->UninstrumentQuickAllocEntryPoints();
Elliott Hughes545a0642011-11-08 19:10:03 -08004560 }
4561}
4562
Ian Rogers0399dde2012-06-06 17:09:28 -07004563struct AllocRecordStackVisitor : public StackVisitor {
Andreas Gampe277ccbd2014-11-03 21:36:10 -08004564 AllocRecordStackVisitor(Thread* thread, AllocRecord* record_in)
Ian Rogersb726dcb2012-09-05 08:57:23 -07004565 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_)
Andreas Gampe277ccbd2014-11-03 21:36:10 -08004566 : StackVisitor(thread, nullptr), record(record_in), depth(0) {}
Elliott Hughes545a0642011-11-08 19:10:03 -08004567
Ian Rogers00f7d0e2012-07-19 15:28:27 -07004568 // TODO: Enable annotalysis. We know lock is held in constructor, but abstraction confuses
4569 // annotalysis.
4570 bool VisitFrame() NO_THREAD_SAFETY_ANALYSIS {
Elliott Hughes545a0642011-11-08 19:10:03 -08004571 if (depth >= kMaxAllocRecordStackDepth) {
Elliott Hughes530fa002012-03-12 11:44:49 -07004572 return false;
Elliott Hughes545a0642011-11-08 19:10:03 -08004573 }
Brian Carlstromea46f952013-07-30 01:26:50 -07004574 mirror::ArtMethod* m = GetMethod();
Ian Rogers0399dde2012-06-06 17:09:28 -07004575 if (!m->IsRuntimeMethod()) {
Hiroshi Yamauchib5a9e3d2014-06-09 12:11:20 -07004576 record->StackElement(depth)->SetMethod(m);
4577 record->StackElement(depth)->SetDexPc(GetDexPc());
Elliott Hughes530fa002012-03-12 11:44:49 -07004578 ++depth;
Elliott Hughes545a0642011-11-08 19:10:03 -08004579 }
Elliott Hughes530fa002012-03-12 11:44:49 -07004580 return true;
Elliott Hughes545a0642011-11-08 19:10:03 -08004581 }
4582
4583 ~AllocRecordStackVisitor() {
4584 // Clear out any unused stack trace elements.
4585 for (; depth < kMaxAllocRecordStackDepth; ++depth) {
Hiroshi Yamauchib5a9e3d2014-06-09 12:11:20 -07004586 record->StackElement(depth)->SetMethod(nullptr);
4587 record->StackElement(depth)->SetDexPc(0);
Elliott Hughes545a0642011-11-08 19:10:03 -08004588 }
4589 }
4590
4591 AllocRecord* record;
4592 size_t depth;
4593};
4594
Ian Rogers844506b2014-09-12 19:59:33 -07004595void Dbg::RecordAllocation(Thread* self, mirror::Class* type, size_t byte_count) {
Brian Carlstrom306db812014-09-05 13:01:41 -07004596 MutexLock mu(self, *Locks::alloc_tracker_lock_);
Ian Rogersc0542af2014-09-03 16:16:56 -07004597 if (recent_allocation_records_ == nullptr) {
Brian Carlstrom306db812014-09-05 13:01:41 -07004598 // In the process of shutting down recording, bail.
Elliott Hughes545a0642011-11-08 19:10:03 -08004599 return;
4600 }
4601
4602 // Advance and clip.
Ian Rogers719d1a32014-03-06 12:13:39 -08004603 if (++alloc_record_head_ == alloc_record_max_) {
4604 alloc_record_head_ = 0;
Elliott Hughes545a0642011-11-08 19:10:03 -08004605 }
4606
4607 // Fill in the basics.
Ian Rogers719d1a32014-03-06 12:13:39 -08004608 AllocRecord* record = &recent_allocation_records_[alloc_record_head_];
Hiroshi Yamauchib5a9e3d2014-06-09 12:11:20 -07004609 record->SetType(type);
4610 record->SetByteCount(byte_count);
4611 record->SetThinLockId(self->GetThreadId());
Elliott Hughes545a0642011-11-08 19:10:03 -08004612
4613 // Fill in the stack trace.
Ian Rogers7a22fa62013-01-23 12:16:16 -08004614 AllocRecordStackVisitor visitor(self, record);
Ian Rogers0399dde2012-06-06 17:09:28 -07004615 visitor.WalkStack();
Elliott Hughes545a0642011-11-08 19:10:03 -08004616
Ian Rogers719d1a32014-03-06 12:13:39 -08004617 if (alloc_record_count_ < alloc_record_max_) {
4618 ++alloc_record_count_;
Elliott Hughes545a0642011-11-08 19:10:03 -08004619 }
4620}
4621
Elliott Hughesa8f93cb2012-06-08 17:08:48 -07004622// Returns the index of the head element.
4623//
Brian Carlstrom306db812014-09-05 13:01:41 -07004624// We point at the most-recently-written record, so if alloc_record_count_ is 1
Elliott Hughesa8f93cb2012-06-08 17:08:48 -07004625// we want to use the current element. Take "head+1" and subtract count
4626// from it.
4627//
4628// We need to handle underflow in our circular buffer, so we add
Brian Carlstrom306db812014-09-05 13:01:41 -07004629// alloc_record_max_ and then mask it back down.
Ian Rogers719d1a32014-03-06 12:13:39 -08004630size_t Dbg::HeadIndex() {
4631 return (Dbg::alloc_record_head_ + 1 + Dbg::alloc_record_max_ - Dbg::alloc_record_count_) &
4632 (Dbg::alloc_record_max_ - 1);
Elliott Hughes545a0642011-11-08 19:10:03 -08004633}
4634
4635void Dbg::DumpRecentAllocations() {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07004636 ScopedObjectAccess soa(Thread::Current());
Brian Carlstrom306db812014-09-05 13:01:41 -07004637 MutexLock mu(soa.Self(), *Locks::alloc_tracker_lock_);
Ian Rogersc0542af2014-09-03 16:16:56 -07004638 if (recent_allocation_records_ == nullptr) {
Elliott Hughes545a0642011-11-08 19:10:03 -08004639 LOG(INFO) << "Not recording tracked allocations";
4640 return;
4641 }
4642
4643 // "i" is the head of the list. We want to start at the end of the
4644 // list and move forward to the tail.
Elliott Hughesa8f93cb2012-06-08 17:08:48 -07004645 size_t i = HeadIndex();
Brian Carlstrom306db812014-09-05 13:01:41 -07004646 const uint16_t capped_count = CappedAllocRecordCount(Dbg::alloc_record_count_);
4647 uint16_t count = capped_count;
Elliott Hughes545a0642011-11-08 19:10:03 -08004648
Ian Rogers719d1a32014-03-06 12:13:39 -08004649 LOG(INFO) << "Tracked allocations, (head=" << alloc_record_head_ << " count=" << count << ")";
Elliott Hughes545a0642011-11-08 19:10:03 -08004650 while (count--) {
4651 AllocRecord* record = &recent_allocation_records_[i];
4652
Hiroshi Yamauchib5a9e3d2014-06-09 12:11:20 -07004653 LOG(INFO) << StringPrintf(" Thread %-2d %6zd bytes ", record->ThinLockId(), record->ByteCount())
4654 << PrettyClass(record->Type());
Elliott Hughes545a0642011-11-08 19:10:03 -08004655
4656 for (size_t stack_frame = 0; stack_frame < kMaxAllocRecordStackDepth; ++stack_frame) {
Hiroshi Yamauchib5a9e3d2014-06-09 12:11:20 -07004657 AllocRecordStackTraceElement* stack_element = record->StackElement(stack_frame);
4658 mirror::ArtMethod* m = stack_element->Method();
Ian Rogersc0542af2014-09-03 16:16:56 -07004659 if (m == nullptr) {
Elliott Hughes545a0642011-11-08 19:10:03 -08004660 break;
4661 }
Hiroshi Yamauchib5a9e3d2014-06-09 12:11:20 -07004662 LOG(INFO) << " " << PrettyMethod(m) << " line " << stack_element->LineNumber();
Elliott Hughes545a0642011-11-08 19:10:03 -08004663 }
4664
4665 // pause periodically to help logcat catch up
4666 if ((count % 5) == 0) {
4667 usleep(40000);
4668 }
4669
Ian Rogers719d1a32014-03-06 12:13:39 -08004670 i = (i + 1) & (alloc_record_max_ - 1);
Elliott Hughes545a0642011-11-08 19:10:03 -08004671 }
4672}
4673
4674class StringTable {
4675 public:
4676 StringTable() {
4677 }
4678
Mathieu Chartier4345c462014-06-27 10:20:14 -07004679 void Add(const std::string& str) {
4680 table_.insert(str);
4681 }
4682
4683 void Add(const char* str) {
4684 table_.insert(str);
Elliott Hughes545a0642011-11-08 19:10:03 -08004685 }
4686
Elliott Hughesa8f93cb2012-06-08 17:08:48 -07004687 size_t IndexOf(const char* s) const {
Mathieu Chartier02e25112013-08-14 16:14:24 -07004688 auto it = table_.find(s);
Elliott Hughesa8f93cb2012-06-08 17:08:48 -07004689 if (it == table_.end()) {
4690 LOG(FATAL) << "IndexOf(\"" << s << "\") failed";
4691 }
4692 return std::distance(table_.begin(), it);
Elliott Hughes545a0642011-11-08 19:10:03 -08004693 }
4694
Elliott Hughesa8f93cb2012-06-08 17:08:48 -07004695 size_t Size() const {
Elliott Hughes545a0642011-11-08 19:10:03 -08004696 return table_.size();
4697 }
4698
Elliott Hughesa8f93cb2012-06-08 17:08:48 -07004699 void WriteTo(std::vector<uint8_t>& bytes) const {
Mathieu Chartier02e25112013-08-14 16:14:24 -07004700 for (const std::string& str : table_) {
4701 const char* s = str.c_str();
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08004702 size_t s_len = CountModifiedUtf8Chars(s);
Ian Rogers700a4022014-05-19 16:49:03 -07004703 std::unique_ptr<uint16_t> s_utf16(new uint16_t[s_len]);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08004704 ConvertModifiedUtf8ToUtf16(s_utf16.get(), s);
4705 JDWP::AppendUtf16BE(bytes, s_utf16.get(), s_len);
Elliott Hughes545a0642011-11-08 19:10:03 -08004706 }
4707 }
4708
4709 private:
Elliott Hughesa8f93cb2012-06-08 17:08:48 -07004710 std::set<std::string> table_;
Elliott Hughes545a0642011-11-08 19:10:03 -08004711 DISALLOW_COPY_AND_ASSIGN(StringTable);
4712};
4713
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07004714static const char* GetMethodSourceFile(mirror::ArtMethod* method)
Sebastien Hertz280286a2014-04-28 09:26:50 +02004715 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07004716 DCHECK(method != nullptr);
4717 const char* source_file = method->GetDeclaringClassSourceFile();
Sebastien Hertz280286a2014-04-28 09:26:50 +02004718 return (source_file != nullptr) ? source_file : "";
4719}
4720
Elliott Hughes545a0642011-11-08 19:10:03 -08004721/*
4722 * The data we send to DDMS contains everything we have recorded.
4723 *
4724 * Message header (all values big-endian):
4725 * (1b) message header len (to allow future expansion); includes itself
4726 * (1b) entry header len
4727 * (1b) stack frame len
4728 * (2b) number of entries
4729 * (4b) offset to string table from start of message
4730 * (2b) number of class name strings
4731 * (2b) number of method name strings
4732 * (2b) number of source file name strings
4733 * For each entry:
4734 * (4b) total allocation size
Elliott Hughes221229c2013-01-08 18:17:50 -08004735 * (2b) thread id
Elliott Hughes545a0642011-11-08 19:10:03 -08004736 * (2b) allocated object's class name index
4737 * (1b) stack depth
4738 * For each stack frame:
4739 * (2b) method's class name
4740 * (2b) method name
4741 * (2b) method source file
4742 * (2b) line number, clipped to 32767; -2 if native; -1 if no source
4743 * (xb) class name strings
4744 * (xb) method name strings
4745 * (xb) source file strings
4746 *
4747 * As with other DDM traffic, strings are sent as a 4-byte length
4748 * followed by UTF-16 data.
4749 *
4750 * We send up 16-bit unsigned indexes into string tables. In theory there
Brian Carlstrom306db812014-09-05 13:01:41 -07004751 * can be (kMaxAllocRecordStackDepth * alloc_record_max_) unique strings in
Elliott Hughes545a0642011-11-08 19:10:03 -08004752 * each table, but in practice there should be far fewer.
4753 *
4754 * The chief reason for using a string table here is to keep the size of
4755 * the DDMS message to a minimum. This is partly to make the protocol
4756 * efficient, but also because we have to form the whole thing up all at
4757 * once in a memory buffer.
4758 *
4759 * We use separate string tables for class names, method names, and source
4760 * files to keep the indexes small. There will generally be no overlap
4761 * between the contents of these tables.
4762 */
4763jbyteArray Dbg::GetRecentAllocations() {
Ian Rogerscf7f1912014-10-22 22:06:39 -07004764 if ((false)) {
Elliott Hughes545a0642011-11-08 19:10:03 -08004765 DumpRecentAllocations();
4766 }
4767
Ian Rogers50b35e22012-10-04 10:09:15 -07004768 Thread* self = Thread::Current();
Elliott Hughes545a0642011-11-08 19:10:03 -08004769 std::vector<uint8_t> bytes;
Mathieu Chartier46e811b2013-07-10 17:09:14 -07004770 {
Brian Carlstrom306db812014-09-05 13:01:41 -07004771 MutexLock mu(self, *Locks::alloc_tracker_lock_);
Mathieu Chartier46e811b2013-07-10 17:09:14 -07004772 //
4773 // Part 1: generate string tables.
4774 //
4775 StringTable class_names;
4776 StringTable method_names;
4777 StringTable filenames;
Elliott Hughes545a0642011-11-08 19:10:03 -08004778
Brian Carlstrom306db812014-09-05 13:01:41 -07004779 const uint16_t capped_count = CappedAllocRecordCount(Dbg::alloc_record_count_);
4780 uint16_t count = capped_count;
4781 size_t idx = HeadIndex();
Mathieu Chartier46e811b2013-07-10 17:09:14 -07004782 while (count--) {
4783 AllocRecord* record = &recent_allocation_records_[idx];
Ian Rogers1ff3c982014-08-12 02:30:58 -07004784 std::string temp;
4785 class_names.Add(record->Type()->GetDescriptor(&temp));
Mathieu Chartier46e811b2013-07-10 17:09:14 -07004786 for (size_t i = 0; i < kMaxAllocRecordStackDepth; i++) {
Hiroshi Yamauchib5a9e3d2014-06-09 12:11:20 -07004787 mirror::ArtMethod* m = record->StackElement(i)->Method();
Ian Rogersc0542af2014-09-03 16:16:56 -07004788 if (m != nullptr) {
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07004789 class_names.Add(m->GetDeclaringClassDescriptor());
4790 method_names.Add(m->GetName());
4791 filenames.Add(GetMethodSourceFile(m));
Mathieu Chartier46e811b2013-07-10 17:09:14 -07004792 }
4793 }
Elliott Hughes545a0642011-11-08 19:10:03 -08004794
Ian Rogers719d1a32014-03-06 12:13:39 -08004795 idx = (idx + 1) & (alloc_record_max_ - 1);
Elliott Hughes545a0642011-11-08 19:10:03 -08004796 }
4797
Brian Carlstrom306db812014-09-05 13:01:41 -07004798 LOG(INFO) << "allocation records: " << capped_count;
Mathieu Chartier46e811b2013-07-10 17:09:14 -07004799
4800 //
4801 // Part 2: Generate the output and store it in the buffer.
4802 //
4803
4804 // (1b) message header len (to allow future expansion); includes itself
4805 // (1b) entry header len
4806 // (1b) stack frame len
4807 const int kMessageHeaderLen = 15;
4808 const int kEntryHeaderLen = 9;
4809 const int kStackFrameLen = 8;
4810 JDWP::Append1BE(bytes, kMessageHeaderLen);
4811 JDWP::Append1BE(bytes, kEntryHeaderLen);
4812 JDWP::Append1BE(bytes, kStackFrameLen);
4813
4814 // (2b) number of entries
4815 // (4b) offset to string table from start of message
4816 // (2b) number of class name strings
4817 // (2b) number of method name strings
4818 // (2b) number of source file name strings
Brian Carlstrom306db812014-09-05 13:01:41 -07004819 JDWP::Append2BE(bytes, capped_count);
Mathieu Chartier46e811b2013-07-10 17:09:14 -07004820 size_t string_table_offset = bytes.size();
Brian Carlstrom7934ac22013-07-26 10:54:15 -07004821 JDWP::Append4BE(bytes, 0); // We'll patch this later...
Mathieu Chartier46e811b2013-07-10 17:09:14 -07004822 JDWP::Append2BE(bytes, class_names.Size());
4823 JDWP::Append2BE(bytes, method_names.Size());
4824 JDWP::Append2BE(bytes, filenames.Size());
4825
Mathieu Chartier46e811b2013-07-10 17:09:14 -07004826 idx = HeadIndex();
Ian Rogers1ff3c982014-08-12 02:30:58 -07004827 std::string temp;
Brian Carlstrom306db812014-09-05 13:01:41 -07004828 for (count = capped_count; count != 0; --count) {
Mathieu Chartier46e811b2013-07-10 17:09:14 -07004829 // For each entry:
4830 // (4b) total allocation size
4831 // (2b) thread id
4832 // (2b) allocated object's class name index
4833 // (1b) stack depth
4834 AllocRecord* record = &recent_allocation_records_[idx];
4835 size_t stack_depth = record->GetDepth();
Mathieu Chartierf8322842014-05-16 10:59:25 -07004836 size_t allocated_object_class_name_index =
Ian Rogers1ff3c982014-08-12 02:30:58 -07004837 class_names.IndexOf(record->Type()->GetDescriptor(&temp));
Hiroshi Yamauchib5a9e3d2014-06-09 12:11:20 -07004838 JDWP::Append4BE(bytes, record->ByteCount());
4839 JDWP::Append2BE(bytes, record->ThinLockId());
Mathieu Chartier46e811b2013-07-10 17:09:14 -07004840 JDWP::Append2BE(bytes, allocated_object_class_name_index);
4841 JDWP::Append1BE(bytes, stack_depth);
4842
Mathieu Chartier46e811b2013-07-10 17:09:14 -07004843 for (size_t stack_frame = 0; stack_frame < stack_depth; ++stack_frame) {
4844 // For each stack frame:
4845 // (2b) method's class name
4846 // (2b) method name
4847 // (2b) method source file
4848 // (2b) line number, clipped to 32767; -2 if native; -1 if no source
Hiroshi Yamauchib5a9e3d2014-06-09 12:11:20 -07004849 mirror::ArtMethod* m = record->StackElement(stack_frame)->Method();
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07004850 size_t class_name_index = class_names.IndexOf(m->GetDeclaringClassDescriptor());
4851 size_t method_name_index = method_names.IndexOf(m->GetName());
4852 size_t file_name_index = filenames.IndexOf(GetMethodSourceFile(m));
Mathieu Chartier46e811b2013-07-10 17:09:14 -07004853 JDWP::Append2BE(bytes, class_name_index);
4854 JDWP::Append2BE(bytes, method_name_index);
4855 JDWP::Append2BE(bytes, file_name_index);
Hiroshi Yamauchib5a9e3d2014-06-09 12:11:20 -07004856 JDWP::Append2BE(bytes, record->StackElement(stack_frame)->LineNumber());
Mathieu Chartier46e811b2013-07-10 17:09:14 -07004857 }
Ian Rogers719d1a32014-03-06 12:13:39 -08004858 idx = (idx + 1) & (alloc_record_max_ - 1);
Mathieu Chartier46e811b2013-07-10 17:09:14 -07004859 }
4860
4861 // (xb) class name strings
4862 // (xb) method name strings
4863 // (xb) source file strings
4864 JDWP::Set4BE(&bytes[string_table_offset], bytes.size());
4865 class_names.WriteTo(bytes);
4866 method_names.WriteTo(bytes);
4867 filenames.WriteTo(bytes);
Elliott Hughes545a0642011-11-08 19:10:03 -08004868 }
Ian Rogers50b35e22012-10-04 10:09:15 -07004869 JNIEnv* env = self->GetJniEnv();
Elliott Hughes545a0642011-11-08 19:10:03 -08004870 jbyteArray result = env->NewByteArray(bytes.size());
Ian Rogersc0542af2014-09-03 16:16:56 -07004871 if (result != nullptr) {
Elliott Hughes545a0642011-11-08 19:10:03 -08004872 env->SetByteArrayRegion(result, 0, bytes.size(), reinterpret_cast<const jbyte*>(&bytes[0]));
4873 }
4874 return result;
4875}
4876
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07004877mirror::ArtMethod* DeoptimizationRequest::Method() const {
4878 ScopedObjectAccessUnchecked soa(Thread::Current());
4879 return soa.DecodeMethod(method_);
4880}
4881
4882void DeoptimizationRequest::SetMethod(mirror::ArtMethod* m) {
4883 ScopedObjectAccessUnchecked soa(Thread::Current());
4884 method_ = soa.EncodeMethod(m);
4885}
4886
Elliott Hughes872d4ec2011-10-21 17:07:15 -07004887} // namespace art