blob: 546a1fb94a4229a41b0dd7c42b5536d36bed6dfe [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"
Mathieu Chartierc7853442015-03-27 14:35:38 -070024#include "art_field-inl.h"
Mathieu Chartier3d21bdf2015-04-22 13:56:20 -070025#include "art_method-inl.h"
Vladimir Marko41b175a2015-05-19 18:08:00 +010026#include "base/time_utils.h"
Elliott Hughes545a0642011-11-08 19:10:03 -080027#include "class_linker.h"
Ian Rogers2dd0e2c2013-01-24 12:42:14 -080028#include "class_linker-inl.h"
Ian Rogers4f6ad8a2013-03-18 15:27:28 -070029#include "dex_file-inl.h"
Ian Rogers776ac1f2012-04-13 23:36:36 -070030#include "dex_instruction.h"
Ian Rogers1d54e732013-05-02 21:10:01 -070031#include "gc/accounting/card_table-inl.h"
32#include "gc/space/large_object_space.h"
33#include "gc/space/space-inl.h"
Mathieu Chartiereb8167a2014-05-07 15:43:14 -070034#include "handle_scope.h"
Sebastien Hertz6ba35b52015-06-01 17:33:12 +020035#include "jdwp/jdwp_priv.h"
Elliott Hughes64f574f2013-02-20 14:57:12 -080036#include "jdwp/object_registry.h"
Ian Rogers2dd0e2c2013-01-24 12:42:14 -080037#include "mirror/class.h"
38#include "mirror/class-inl.h"
39#include "mirror/class_loader.h"
Ian Rogers2dd0e2c2013-01-24 12:42:14 -080040#include "mirror/object-inl.h"
41#include "mirror/object_array-inl.h"
Ian Rogersb0fa5dc2014-04-28 16:47:08 -070042#include "mirror/string-inl.h"
Ian Rogers2dd0e2c2013-01-24 12:42:14 -080043#include "mirror/throwable.h"
Sebastien Hertza76a6d42014-03-20 16:40:17 +010044#include "quick/inline_method_analyser.h"
Ian Rogers53b8b092014-03-13 23:45:53 -070045#include "reflection.h"
Elliott Hughesa0e18062012-04-13 15:59:59 -070046#include "safe_map.h"
Elliott Hughes64f574f2013-02-20 14:57:12 -080047#include "scoped_thread_state_change.h"
Elliott Hughes6a5bd492011-10-28 14:33:57 -070048#include "ScopedLocalRef.h"
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -070049#include "ScopedPrimitiveArray.h"
Mathieu Chartiereb8167a2014-05-07 15:43:14 -070050#include "handle_scope-inl.h"
Elliott Hughes475fc232011-10-25 15:00:35 -070051#include "thread_list.h"
Ian Rogers2dd0e2c2013-01-24 12:42:14 -080052#include "utf.h"
Sebastien Hertza76a6d42014-03-20 16:40:17 +010053#include "verifier/method_verifier-inl.h"
Elliott Hugheseac76672012-05-24 21:56:51 -070054#include "well_known_classes.h"
Elliott Hughes475fc232011-10-25 15:00:35 -070055
Brian Carlstrom3d92d522013-07-12 09:03:08 -070056#ifdef HAVE_ANDROID_OS
57#include "cutils/properties.h"
58#endif
59
Elliott Hughes872d4ec2011-10-21 17:07:15 -070060namespace art {
61
Sebastien Hertz0462c4c2015-04-01 16:34:17 +020062// The key identifying the debugger to update instrumentation.
63static constexpr const char* kDbgInstrumentationKey = "Debugger";
64
Brian Carlstrom7934ac22013-07-26 10:54:15 -070065static const size_t kMaxAllocRecordStackDepth = 16; // Max 255.
Brian Carlstrom306db812014-09-05 13:01:41 -070066static const size_t kDefaultNumAllocRecords = 64*1024; // Must be a power of 2. 2BE can hold 64k-1.
67
68// Limit alloc_record_count to the 2BE value that is the limit of the current protocol.
69static uint16_t CappedAllocRecordCount(size_t alloc_record_count) {
70 if (alloc_record_count > 0xffff) {
71 return 0xffff;
72 }
73 return alloc_record_count;
74}
Elliott Hughes475fc232011-10-25 15:00:35 -070075
Hiroshi Yamauchib5a9e3d2014-06-09 12:11:20 -070076class AllocRecordStackTraceElement {
77 public:
78 AllocRecordStackTraceElement() : method_(nullptr), dex_pc_(0) {
Mathieu Chartier412c7fc2014-02-07 12:18:39 -080079 }
80
Hiroshi Yamauchib5a9e3d2014-06-09 12:11:20 -070081 int32_t LineNumber() SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Mathieu Chartier3d21bdf2015-04-22 13:56:20 -070082 ArtMethod* method = Method();
Hiroshi Yamauchib5a9e3d2014-06-09 12:11:20 -070083 DCHECK(method != nullptr);
84 return method->GetLineNumFromDexPC(DexPc());
Elliott Hughes545a0642011-11-08 19:10:03 -080085 }
Hiroshi Yamauchib5a9e3d2014-06-09 12:11:20 -070086
Mathieu Chartier3d21bdf2015-04-22 13:56:20 -070087 ArtMethod* Method() SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Mathieu Chartier4345c462014-06-27 10:20:14 -070088 ScopedObjectAccessUnchecked soa(Thread::Current());
89 return soa.DecodeMethod(method_);
Hiroshi Yamauchib5a9e3d2014-06-09 12:11:20 -070090 }
91
Mathieu Chartier3d21bdf2015-04-22 13:56:20 -070092 void SetMethod(ArtMethod* m) SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Hiroshi Yamauchib5a9e3d2014-06-09 12:11:20 -070093 ScopedObjectAccessUnchecked soa(Thread::Current());
Mathieu Chartier4345c462014-06-27 10:20:14 -070094 method_ = soa.EncodeMethod(m);
Hiroshi Yamauchib5a9e3d2014-06-09 12:11:20 -070095 }
96
97 uint32_t DexPc() const {
98 return dex_pc_;
99 }
100
101 void SetDexPc(uint32_t pc) {
102 dex_pc_ = pc;
103 }
104
105 private:
Mathieu Chartier4345c462014-06-27 10:20:14 -0700106 jmethodID method_;
Hiroshi Yamauchib5a9e3d2014-06-09 12:11:20 -0700107 uint32_t dex_pc_;
Elliott Hughes545a0642011-11-08 19:10:03 -0800108};
109
Mathieu Chartier4345c462014-06-27 10:20:14 -0700110jobject Dbg::TypeCache::Add(mirror::Class* t) {
111 ScopedObjectAccessUnchecked soa(Thread::Current());
Mathieu Chartier4c4d6092015-01-22 17:02:27 -0800112 JNIEnv* const env = soa.Env();
113 ScopedLocalRef<jobject> local_ref(soa.Env(), soa.AddLocalReference<jobject>(t));
114 const int32_t hash_code = soa.Decode<mirror::Class*>(local_ref.get())->IdentityHashCode();
Mathieu Chartier4345c462014-06-27 10:20:14 -0700115 auto range = objects_.equal_range(hash_code);
116 for (auto it = range.first; it != range.second; ++it) {
Mathieu Chartier4c4d6092015-01-22 17:02:27 -0800117 if (soa.Decode<mirror::Class*>(it->second) == soa.Decode<mirror::Class*>(local_ref.get())) {
Mathieu Chartier4345c462014-06-27 10:20:14 -0700118 // Found a matching weak global, return it.
119 return it->second;
120 }
121 }
Mathieu Chartier4c4d6092015-01-22 17:02:27 -0800122 const jobject weak_global = env->NewWeakGlobalRef(local_ref.get());
Mathieu Chartier4345c462014-06-27 10:20:14 -0700123 objects_.insert(std::make_pair(hash_code, weak_global));
124 return weak_global;
125}
126
127void Dbg::TypeCache::Clear() {
Brian Carlstrom306db812014-09-05 13:01:41 -0700128 JavaVMExt* vm = Runtime::Current()->GetJavaVM();
129 Thread* self = Thread::Current();
Mathieu Chartier4345c462014-06-27 10:20:14 -0700130 for (const auto& p : objects_) {
Brian Carlstrom306db812014-09-05 13:01:41 -0700131 vm->DeleteWeakGlobalRef(self, p.second);
Mathieu Chartier4345c462014-06-27 10:20:14 -0700132 }
133 objects_.clear();
134}
135
Hiroshi Yamauchib5a9e3d2014-06-09 12:11:20 -0700136class AllocRecord {
137 public:
138 AllocRecord() : type_(nullptr), byte_count_(0), thin_lock_id_(0) {}
Elliott Hughes545a0642011-11-08 19:10:03 -0800139
Hiroshi Yamauchib5a9e3d2014-06-09 12:11:20 -0700140 mirror::Class* Type() SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Mathieu Chartier4345c462014-06-27 10:20:14 -0700141 return down_cast<mirror::Class*>(Thread::Current()->DecodeJObject(type_));
Hiroshi Yamauchib5a9e3d2014-06-09 12:11:20 -0700142 }
143
Brian Carlstrom306db812014-09-05 13:01:41 -0700144 void SetType(mirror::Class* t) SHARED_LOCKS_REQUIRED(Locks::mutator_lock_,
145 Locks::alloc_tracker_lock_) {
146 type_ = Dbg::type_cache_.Add(t);
Hiroshi Yamauchib5a9e3d2014-06-09 12:11:20 -0700147 }
148
149 size_t GetDepth() SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Elliott Hughes545a0642011-11-08 19:10:03 -0800150 size_t depth = 0;
Ian Rogersc0542af2014-09-03 16:16:56 -0700151 while (depth < kMaxAllocRecordStackDepth && stack_[depth].Method() != nullptr) {
Elliott Hughes545a0642011-11-08 19:10:03 -0800152 ++depth;
153 }
154 return depth;
155 }
Mathieu Chartier412c7fc2014-02-07 12:18:39 -0800156
Hiroshi Yamauchib5a9e3d2014-06-09 12:11:20 -0700157 size_t ByteCount() const {
158 return byte_count_;
Mathieu Chartier412c7fc2014-02-07 12:18:39 -0800159 }
Hiroshi Yamauchib5a9e3d2014-06-09 12:11:20 -0700160
161 void SetByteCount(size_t count) {
162 byte_count_ = count;
163 }
164
165 uint16_t ThinLockId() const {
166 return thin_lock_id_;
167 }
168
169 void SetThinLockId(uint16_t id) {
170 thin_lock_id_ = id;
171 }
172
173 AllocRecordStackTraceElement* StackElement(size_t index) {
174 DCHECK_LT(index, kMaxAllocRecordStackDepth);
175 return &stack_[index];
176 }
177
178 private:
179 jobject type_; // This is a weak global.
180 size_t byte_count_;
181 uint16_t thin_lock_id_;
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700182 // Unused entries have null method.
183 AllocRecordStackTraceElement stack_[kMaxAllocRecordStackDepth];
Elliott Hughes545a0642011-11-08 19:10:03 -0800184};
185
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -0700186class Breakpoint {
187 public:
Mathieu Chartier3d21bdf2015-04-22 13:56:20 -0700188 Breakpoint(ArtMethod* method, uint32_t dex_pc,
Sebastien Hertzf3928792014-11-17 19:00:37 +0100189 DeoptimizationRequest::Kind deoptimization_kind)
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -0700190 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_)
Sebastien Hertzf3928792014-11-17 19:00:37 +0100191 : method_(nullptr), dex_pc_(dex_pc), deoptimization_kind_(deoptimization_kind) {
192 CHECK(deoptimization_kind_ == DeoptimizationRequest::kNothing ||
193 deoptimization_kind_ == DeoptimizationRequest::kSelectiveDeoptimization ||
194 deoptimization_kind_ == DeoptimizationRequest::kFullDeoptimization);
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -0700195 ScopedObjectAccessUnchecked soa(Thread::Current());
196 method_ = soa.EncodeMethod(method);
197 }
198
199 Breakpoint(const Breakpoint& other) SHARED_LOCKS_REQUIRED(Locks::mutator_lock_)
200 : method_(nullptr), dex_pc_(other.dex_pc_),
Sebastien Hertzf3928792014-11-17 19:00:37 +0100201 deoptimization_kind_(other.deoptimization_kind_) {
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -0700202 ScopedObjectAccessUnchecked soa(Thread::Current());
203 method_ = soa.EncodeMethod(other.Method());
204 }
205
Mathieu Chartier3d21bdf2015-04-22 13:56:20 -0700206 ArtMethod* Method() const SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -0700207 ScopedObjectAccessUnchecked soa(Thread::Current());
208 return soa.DecodeMethod(method_);
209 }
210
211 uint32_t DexPc() const {
212 return dex_pc_;
213 }
214
Sebastien Hertzf3928792014-11-17 19:00:37 +0100215 DeoptimizationRequest::Kind GetDeoptimizationKind() const {
216 return deoptimization_kind_;
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -0700217 }
218
219 private:
Sebastien Hertza76a6d42014-03-20 16:40:17 +0100220 // The location of this breakpoint.
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -0700221 jmethodID method_;
222 uint32_t dex_pc_;
Sebastien Hertza76a6d42014-03-20 16:40:17 +0100223
224 // Indicates whether breakpoint needs full deoptimization or selective deoptimization.
Sebastien Hertzf3928792014-11-17 19:00:37 +0100225 DeoptimizationRequest::Kind deoptimization_kind_;
Elliott Hughes86964332012-02-15 19:37:42 -0800226};
227
Sebastien Hertzed2be172014-08-19 15:33:43 +0200228static std::ostream& operator<<(std::ostream& os, const Breakpoint& rhs)
Ian Rogersb726dcb2012-09-05 08:57:23 -0700229 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -0700230 os << StringPrintf("Breakpoint[%s @%#x]", PrettyMethod(rhs.Method()).c_str(), rhs.DexPc());
Elliott Hughes86964332012-02-15 19:37:42 -0800231 return os;
232}
233
Sebastien Hertz3f52eaf2014-04-04 17:50:18 +0200234class DebugInstrumentationListener FINAL : public instrumentation::InstrumentationListener {
Ian Rogers62d6c772013-02-27 08:32:07 -0800235 public:
236 DebugInstrumentationListener() {}
237 virtual ~DebugInstrumentationListener() {}
238
Mathieu Chartier3d21bdf2015-04-22 13:56:20 -0700239 void MethodEntered(Thread* thread, mirror::Object* this_object, ArtMethod* method,
Sebastien Hertz9d6bf692015-04-10 12:12:33 +0200240 uint32_t dex_pc)
Sebastien Hertz3f52eaf2014-04-04 17:50:18 +0200241 OVERRIDE SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Ian Rogers62d6c772013-02-27 08:32:07 -0800242 if (method->IsNative()) {
243 // TODO: post location events is a suspension point and native method entry stubs aren't.
244 return;
245 }
Sebastien Hertz9d6bf692015-04-10 12:12:33 +0200246 if (IsListeningToDexPcMoved()) {
247 // We also listen to kDexPcMoved instrumentation event so we know the DexPcMoved method is
248 // going to be called right after us. To avoid sending JDWP events twice for this location,
249 // we report the event in DexPcMoved. However, we must remind this is method entry so we
250 // send the METHOD_ENTRY event. And we can also group it with other events for this location
251 // like BREAKPOINT or SINGLE_STEP (or even METHOD_EXIT if this is a RETURN instruction).
252 thread->SetDebugMethodEntry();
253 } else if (IsListeningToMethodExit() && IsReturn(method, dex_pc)) {
254 // We also listen to kMethodExited instrumentation event and the current instruction is a
255 // RETURN so we know the MethodExited method is going to be called right after us. To avoid
256 // sending JDWP events twice for this location, we report the event(s) in MethodExited.
257 // However, we must remind this is method entry so we send the METHOD_ENTRY event. And we can
258 // also group it with other events for this location like BREAKPOINT or SINGLE_STEP.
259 thread->SetDebugMethodEntry();
260 } else {
261 Dbg::UpdateDebugger(thread, this_object, method, 0, Dbg::kMethodEntry, nullptr);
262 }
Ian Rogers62d6c772013-02-27 08:32:07 -0800263 }
264
Mathieu Chartier3d21bdf2015-04-22 13:56:20 -0700265 void MethodExited(Thread* thread, mirror::Object* this_object, ArtMethod* method,
Sebastien Hertz3f52eaf2014-04-04 17:50:18 +0200266 uint32_t dex_pc, const JValue& return_value)
267 OVERRIDE SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Ian Rogers62d6c772013-02-27 08:32:07 -0800268 if (method->IsNative()) {
269 // TODO: post location events is a suspension point and native method entry stubs aren't.
270 return;
271 }
Sebastien Hertz9d6bf692015-04-10 12:12:33 +0200272 uint32_t events = Dbg::kMethodExit;
273 if (thread->IsDebugMethodEntry()) {
274 // It is also the method entry.
275 DCHECK(IsReturn(method, dex_pc));
276 events |= Dbg::kMethodEntry;
277 thread->ClearDebugMethodEntry();
278 }
279 Dbg::UpdateDebugger(thread, this_object, method, dex_pc, events, &return_value);
Ian Rogers62d6c772013-02-27 08:32:07 -0800280 }
281
Sebastien Hertz9d6bf692015-04-10 12:12:33 +0200282 void MethodUnwind(Thread* thread ATTRIBUTE_UNUSED, mirror::Object* this_object ATTRIBUTE_UNUSED,
Mathieu Chartier3d21bdf2015-04-22 13:56:20 -0700283 ArtMethod* method, uint32_t dex_pc)
Sebastien Hertz3f52eaf2014-04-04 17:50:18 +0200284 OVERRIDE SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Ian Rogers62d6c772013-02-27 08:32:07 -0800285 // We're not recorded to listen to this kind of event, so complain.
286 LOG(ERROR) << "Unexpected method unwind event in debugger " << PrettyMethod(method)
Sebastien Hertz51db44a2013-11-19 10:00:29 +0100287 << " " << dex_pc;
Ian Rogers62d6c772013-02-27 08:32:07 -0800288 }
289
Mathieu Chartier3d21bdf2015-04-22 13:56:20 -0700290 void DexPcMoved(Thread* thread, mirror::Object* this_object, ArtMethod* method,
Sebastien Hertz3f52eaf2014-04-04 17:50:18 +0200291 uint32_t new_dex_pc)
292 OVERRIDE SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Sebastien Hertz9d6bf692015-04-10 12:12:33 +0200293 if (IsListeningToMethodExit() && IsReturn(method, new_dex_pc)) {
294 // We also listen to kMethodExited instrumentation event and the current instruction is a
295 // RETURN so we know the MethodExited method is going to be called right after us. Like in
296 // MethodEntered, we delegate event reporting to MethodExited.
297 // Besides, if this RETURN instruction is the only one in the method, we can send multiple
298 // JDWP events in the same packet: METHOD_ENTRY, METHOD_EXIT, BREAKPOINT and/or SINGLE_STEP.
299 // Therefore, we must not clear the debug method entry flag here.
300 } else {
301 uint32_t events = 0;
302 if (thread->IsDebugMethodEntry()) {
303 // It is also the method entry.
304 events = Dbg::kMethodEntry;
305 thread->ClearDebugMethodEntry();
306 }
307 Dbg::UpdateDebugger(thread, this_object, method, new_dex_pc, events, nullptr);
308 }
Ian Rogers62d6c772013-02-27 08:32:07 -0800309 }
310
Sebastien Hertz9d6bf692015-04-10 12:12:33 +0200311 void FieldRead(Thread* thread ATTRIBUTE_UNUSED, mirror::Object* this_object,
Mathieu Chartier3d21bdf2015-04-22 13:56:20 -0700312 ArtMethod* method, uint32_t dex_pc, ArtField* field)
Sebastien Hertz3f52eaf2014-04-04 17:50:18 +0200313 OVERRIDE SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
314 Dbg::PostFieldAccessEvent(method, dex_pc, this_object, field);
Ian Rogers62d6c772013-02-27 08:32:07 -0800315 }
Sebastien Hertz3f52eaf2014-04-04 17:50:18 +0200316
Ian Rogers6a3c1fc2014-10-31 00:33:20 -0700317 void FieldWritten(Thread* thread ATTRIBUTE_UNUSED, mirror::Object* this_object,
Mathieu Chartier3d21bdf2015-04-22 13:56:20 -0700318 ArtMethod* method, uint32_t dex_pc, ArtField* field,
Ian Rogers6a3c1fc2014-10-31 00:33:20 -0700319 const JValue& field_value)
Sebastien Hertz3f52eaf2014-04-04 17:50:18 +0200320 OVERRIDE SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
321 Dbg::PostFieldModificationEvent(method, dex_pc, this_object, field, &field_value);
322 }
323
Nicolas Geoffray14691c52015-03-05 10:40:17 +0000324 void ExceptionCaught(Thread* thread ATTRIBUTE_UNUSED, mirror::Throwable* exception_object)
Sebastien Hertz3f52eaf2014-04-04 17:50:18 +0200325 OVERRIDE SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Nicolas Geoffray14691c52015-03-05 10:40:17 +0000326 Dbg::PostException(exception_object);
Sebastien Hertz3f52eaf2014-04-04 17:50:18 +0200327 }
328
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800329 // We only care about how many backward branches were executed in the Jit.
Mathieu Chartier3d21bdf2015-04-22 13:56:20 -0700330 void BackwardBranch(Thread* /*thread*/, ArtMethod* method, int32_t dex_pc_offset)
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800331 OVERRIDE SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
332 LOG(ERROR) << "Unexpected backward branch event in debugger " << PrettyMethod(method)
333 << " " << dex_pc_offset;
334 }
335
Sebastien Hertz3f52eaf2014-04-04 17:50:18 +0200336 private:
Mathieu Chartier3d21bdf2015-04-22 13:56:20 -0700337 static bool IsReturn(ArtMethod* method, uint32_t dex_pc)
Sebastien Hertz9d6bf692015-04-10 12:12:33 +0200338 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
339 const DexFile::CodeItem* code_item = method->GetCodeItem();
340 const Instruction* instruction = Instruction::At(&code_item->insns_[dex_pc]);
341 return instruction->IsReturn();
342 }
343
344 static bool IsListeningToDexPcMoved() SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
345 return IsListeningTo(instrumentation::Instrumentation::kDexPcMoved);
346 }
347
348 static bool IsListeningToMethodExit() SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
349 return IsListeningTo(instrumentation::Instrumentation::kMethodExited);
350 }
351
352 static bool IsListeningTo(instrumentation::Instrumentation::InstrumentationEvent event)
353 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
354 return (Dbg::GetInstrumentationEvents() & event) != 0;
355 }
356
Sebastien Hertz3f52eaf2014-04-04 17:50:18 +0200357 DISALLOW_COPY_AND_ASSIGN(DebugInstrumentationListener);
Ian Rogers62d6c772013-02-27 08:32:07 -0800358} gDebugInstrumentationListener;
359
Elliott Hughes4ffd3132011-10-24 12:06:42 -0700360// JDWP is allowed unless the Zygote forbids it.
361static bool gJdwpAllowed = true;
362
Elliott Hughesc0f09332012-03-26 13:27:06 -0700363// Was there a -Xrunjdwp or -agentlib:jdwp= argument on the command line?
Elliott Hughes3bb81562011-10-21 18:52:59 -0700364static bool gJdwpConfigured = false;
365
Sebastien Hertzb3b173b2015-02-06 09:16:32 +0100366// JDWP options for debugging. Only valid if IsJdwpConfigured() is true.
367static JDWP::JdwpOptions gJdwpOptions;
368
Elliott Hughes3bb81562011-10-21 18:52:59 -0700369// Runtime JDWP state.
Ian Rogersc0542af2014-09-03 16:16:56 -0700370static JDWP::JdwpState* gJdwpState = nullptr;
Elliott Hughes3bb81562011-10-21 18:52:59 -0700371static bool gDebuggerConnected; // debugger or DDMS is connected.
Elliott Hughes3bb81562011-10-21 18:52:59 -0700372
Elliott Hughes47fce012011-10-25 18:37:19 -0700373static bool gDdmThreadNotification = false;
374
Elliott Hughes767a1472011-10-26 18:49:02 -0700375// DDMS GC-related settings.
376static Dbg::HpifWhen gDdmHpifWhen = Dbg::HPIF_WHEN_NEVER;
377static Dbg::HpsgWhen gDdmHpsgWhen = Dbg::HPSG_WHEN_NEVER;
378static Dbg::HpsgWhat gDdmHpsgWhat;
379static Dbg::HpsgWhen gDdmNhsgWhen = Dbg::HPSG_WHEN_NEVER;
380static Dbg::HpsgWhat gDdmNhsgWhat;
381
Daniel Mihalyieb076692014-08-22 17:33:31 +0200382bool Dbg::gDebuggerActive = false;
Sebastien Hertz4e5b2082015-03-24 19:03:40 +0100383bool Dbg::gDisposed = false;
Sebastien Hertz6995c602014-09-09 12:10:13 +0200384ObjectRegistry* Dbg::gRegistry = nullptr;
Elliott Hughes475fc232011-10-25 15:00:35 -0700385
Elliott Hughes545a0642011-11-08 19:10:03 -0800386// Recent allocation tracking.
Ian Rogers719d1a32014-03-06 12:13:39 -0800387AllocRecord* Dbg::recent_allocation_records_ = nullptr; // TODO: CircularBuffer<AllocRecord>
388size_t Dbg::alloc_record_max_ = 0;
389size_t Dbg::alloc_record_head_ = 0;
390size_t Dbg::alloc_record_count_ = 0;
Mathieu Chartier4345c462014-06-27 10:20:14 -0700391Dbg::TypeCache Dbg::type_cache_;
Elliott Hughes545a0642011-11-08 19:10:03 -0800392
Sebastien Hertz138dbfc2013-12-04 18:15:25 +0100393// Deoptimization support.
Sebastien Hertz4d25df32014-03-21 17:44:46 +0100394std::vector<DeoptimizationRequest> Dbg::deoptimization_requests_;
395size_t Dbg::full_deoptimization_event_count_ = 0;
Sebastien Hertz138dbfc2013-12-04 18:15:25 +0100396
Sebastien Hertz42cd43f2014-05-13 14:15:41 +0200397// Instrumentation event reference counters.
398size_t Dbg::dex_pc_change_event_ref_count_ = 0;
399size_t Dbg::method_enter_event_ref_count_ = 0;
400size_t Dbg::method_exit_event_ref_count_ = 0;
401size_t Dbg::field_read_event_ref_count_ = 0;
402size_t Dbg::field_write_event_ref_count_ = 0;
403size_t Dbg::exception_catch_event_ref_count_ = 0;
404uint32_t Dbg::instrumentation_events_ = 0;
405
Sebastien Hertz138dbfc2013-12-04 18:15:25 +0100406// Breakpoints.
jeffhao09bfc6a2012-12-11 18:11:43 -0800407static std::vector<Breakpoint> gBreakpoints GUARDED_BY(Locks::breakpoint_lock_);
Elliott Hughes86964332012-02-15 19:37:42 -0800408
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -0700409void DebugInvokeReq::VisitRoots(RootVisitor* visitor, const RootInfo& root_info) {
410 receiver.VisitRootIfNonNull(visitor, root_info); // null for static method call.
411 klass.VisitRoot(visitor, root_info);
Mathieu Chartier3b05e9b2014-03-25 09:29:43 -0700412}
413
Sebastien Hertz597c4f02015-01-26 17:37:14 +0100414void SingleStepControl::AddDexPc(uint32_t dex_pc) {
415 dex_pcs_.insert(dex_pc);
Sebastien Hertzbb43b432014-04-14 11:59:08 +0200416}
417
Sebastien Hertz597c4f02015-01-26 17:37:14 +0100418bool SingleStepControl::ContainsDexPc(uint32_t dex_pc) const {
419 return dex_pcs_.find(dex_pc) == dex_pcs_.end();
Sebastien Hertzbb43b432014-04-14 11:59:08 +0200420}
421
Mathieu Chartier3d21bdf2015-04-22 13:56:20 -0700422static bool IsBreakpoint(const ArtMethod* m, uint32_t dex_pc)
jeffhao09bfc6a2012-12-11 18:11:43 -0800423 LOCKS_EXCLUDED(Locks::breakpoint_lock_)
Ian Rogersb726dcb2012-09-05 08:57:23 -0700424 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Sebastien Hertzed2be172014-08-19 15:33:43 +0200425 ReaderMutexLock mu(Thread::Current(), *Locks::breakpoint_lock_);
Sebastien Hertz138dbfc2013-12-04 18:15:25 +0100426 for (size_t i = 0, e = gBreakpoints.size(); i < e; ++i) {
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -0700427 if (gBreakpoints[i].DexPc() == dex_pc && gBreakpoints[i].Method() == m) {
Elliott Hughes86964332012-02-15 19:37:42 -0800428 VLOG(jdwp) << "Hit breakpoint #" << i << ": " << gBreakpoints[i];
429 return true;
430 }
431 }
432 return false;
433}
434
Sebastien Hertz52d131d2014-03-13 16:17:40 +0100435static bool IsSuspendedForDebugger(ScopedObjectAccessUnchecked& soa, Thread* thread)
436 LOCKS_EXCLUDED(Locks::thread_suspend_count_lock_) {
Elliott Hughes9e0c1752013-01-09 14:02:58 -0800437 MutexLock mu(soa.Self(), *Locks::thread_suspend_count_lock_);
438 // A thread may be suspended for GC; in this code, we really want to know whether
439 // there's a debugger suspension active.
440 return thread->IsSuspended() && thread->GetDebugSuspendCount() > 0;
441}
442
Ian Rogersc0542af2014-09-03 16:16:56 -0700443static mirror::Array* DecodeNonNullArray(JDWP::RefTypeId id, JDWP::JdwpError* error)
Ian Rogersb726dcb2012-09-05 08:57:23 -0700444 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Sebastien Hertz6995c602014-09-09 12:10:13 +0200445 mirror::Object* o = Dbg::GetObjectRegistry()->Get<mirror::Object*>(id, error);
Ian Rogersc0542af2014-09-03 16:16:56 -0700446 if (o == nullptr) {
447 *error = JDWP::ERR_INVALID_OBJECT;
448 return nullptr;
Elliott Hughes436e3722012-02-17 20:01:47 -0800449 }
450 if (!o->IsArrayInstance()) {
Ian Rogersc0542af2014-09-03 16:16:56 -0700451 *error = JDWP::ERR_INVALID_ARRAY;
452 return nullptr;
Elliott Hughes436e3722012-02-17 20:01:47 -0800453 }
Ian Rogersc0542af2014-09-03 16:16:56 -0700454 *error = JDWP::ERR_NONE;
Elliott Hughes436e3722012-02-17 20:01:47 -0800455 return o->AsArray();
456}
457
Ian Rogersc0542af2014-09-03 16:16:56 -0700458static mirror::Class* DecodeClass(JDWP::RefTypeId id, JDWP::JdwpError* error)
Ian Rogersb726dcb2012-09-05 08:57:23 -0700459 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Sebastien Hertz6995c602014-09-09 12:10:13 +0200460 mirror::Object* o = Dbg::GetObjectRegistry()->Get<mirror::Object*>(id, error);
Ian Rogersc0542af2014-09-03 16:16:56 -0700461 if (o == nullptr) {
462 *error = JDWP::ERR_INVALID_OBJECT;
463 return nullptr;
Elliott Hughes436e3722012-02-17 20:01:47 -0800464 }
465 if (!o->IsClass()) {
Ian Rogersc0542af2014-09-03 16:16:56 -0700466 *error = JDWP::ERR_INVALID_CLASS;
467 return nullptr;
Elliott Hughes436e3722012-02-17 20:01:47 -0800468 }
Ian Rogersc0542af2014-09-03 16:16:56 -0700469 *error = JDWP::ERR_NONE;
Elliott Hughes436e3722012-02-17 20:01:47 -0800470 return o->AsClass();
471}
472
Ian Rogersc0542af2014-09-03 16:16:56 -0700473static Thread* DecodeThread(ScopedObjectAccessUnchecked& soa, JDWP::ObjectId thread_id,
474 JDWP::JdwpError* error)
Sebastien Hertz69206392015-04-07 15:54:25 +0200475 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_)
476 LOCKS_EXCLUDED(Locks::thread_list_lock_, Locks::thread_suspend_count_lock_) {
Sebastien Hertz6995c602014-09-09 12:10:13 +0200477 mirror::Object* thread_peer = Dbg::GetObjectRegistry()->Get<mirror::Object*>(thread_id, error);
Ian Rogersc0542af2014-09-03 16:16:56 -0700478 if (thread_peer == nullptr) {
Elliott Hughes221229c2013-01-08 18:17:50 -0800479 // This isn't even an object.
Ian Rogersc0542af2014-09-03 16:16:56 -0700480 *error = JDWP::ERR_INVALID_OBJECT;
481 return nullptr;
Elliott Hughes436e3722012-02-17 20:01:47 -0800482 }
Elliott Hughes221229c2013-01-08 18:17:50 -0800483
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800484 mirror::Class* java_lang_Thread = soa.Decode<mirror::Class*>(WellKnownClasses::java_lang_Thread);
Elliott Hughes221229c2013-01-08 18:17:50 -0800485 if (!java_lang_Thread->IsAssignableFrom(thread_peer->GetClass())) {
486 // This isn't a thread.
Ian Rogersc0542af2014-09-03 16:16:56 -0700487 *error = JDWP::ERR_INVALID_THREAD;
488 return nullptr;
Elliott Hughes221229c2013-01-08 18:17:50 -0800489 }
490
Sebastien Hertz69206392015-04-07 15:54:25 +0200491 MutexLock mu(soa.Self(), *Locks::thread_list_lock_);
Ian Rogersc0542af2014-09-03 16:16:56 -0700492 Thread* thread = Thread::FromManagedThread(soa, thread_peer);
493 // If thread is null then this a java.lang.Thread without a Thread*. Must be a un-started or a
494 // zombie.
495 *error = (thread == nullptr) ? JDWP::ERR_THREAD_NOT_ALIVE : JDWP::ERR_NONE;
496 return thread;
Elliott Hughes436e3722012-02-17 20:01:47 -0800497}
498
Elliott Hughes24437992011-11-30 14:49:33 -0800499static JDWP::JdwpTag BasicTagFromDescriptor(const char* descriptor) {
500 // JDWP deliberately uses the descriptor characters' ASCII values for its enum.
501 // Note that by "basic" we mean that we don't get more specific than JT_OBJECT.
502 return static_cast<JDWP::JdwpTag>(descriptor[0]);
503}
504
Ian Rogers1ff3c982014-08-12 02:30:58 -0700505static JDWP::JdwpTag BasicTagFromClass(mirror::Class* klass)
506 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
507 std::string temp;
508 const char* descriptor = klass->GetDescriptor(&temp);
509 return BasicTagFromDescriptor(descriptor);
510}
511
Ian Rogers98379392014-02-24 16:53:16 -0800512static JDWP::JdwpTag TagFromClass(const ScopedObjectAccessUnchecked& soa, mirror::Class* c)
Ian Rogersb726dcb2012-09-05 08:57:23 -0700513 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Ian Rogersc0542af2014-09-03 16:16:56 -0700514 CHECK(c != nullptr);
Elliott Hughes24437992011-11-30 14:49:33 -0800515 if (c->IsArrayClass()) {
516 return JDWP::JT_ARRAY;
517 }
Elliott Hughes24437992011-11-30 14:49:33 -0800518 if (c->IsStringClass()) {
519 return JDWP::JT_STRING;
Elliott Hughes24437992011-11-30 14:49:33 -0800520 }
Ian Rogers98379392014-02-24 16:53:16 -0800521 if (c->IsClassClass()) {
522 return JDWP::JT_CLASS_OBJECT;
523 }
524 {
525 mirror::Class* thread_class = soa.Decode<mirror::Class*>(WellKnownClasses::java_lang_Thread);
526 if (thread_class->IsAssignableFrom(c)) {
527 return JDWP::JT_THREAD;
528 }
529 }
530 {
531 mirror::Class* thread_group_class =
532 soa.Decode<mirror::Class*>(WellKnownClasses::java_lang_ThreadGroup);
533 if (thread_group_class->IsAssignableFrom(c)) {
534 return JDWP::JT_THREAD_GROUP;
535 }
536 }
537 {
538 mirror::Class* class_loader_class =
539 soa.Decode<mirror::Class*>(WellKnownClasses::java_lang_ClassLoader);
540 if (class_loader_class->IsAssignableFrom(c)) {
541 return JDWP::JT_CLASS_LOADER;
542 }
543 }
544 return JDWP::JT_OBJECT;
Elliott Hughes24437992011-11-30 14:49:33 -0800545}
546
547/*
548 * Objects declared to hold Object might actually hold a more specific
549 * type. The debugger may take a special interest in these (e.g. it
550 * wants to display the contents of Strings), so we want to return an
551 * appropriate tag.
552 *
553 * Null objects are tagged JT_OBJECT.
554 */
Sebastien Hertz6995c602014-09-09 12:10:13 +0200555JDWP::JdwpTag Dbg::TagFromObject(const ScopedObjectAccessUnchecked& soa, mirror::Object* o) {
Ian Rogersc0542af2014-09-03 16:16:56 -0700556 return (o == nullptr) ? JDWP::JT_OBJECT : TagFromClass(soa, o->GetClass());
Elliott Hughes24437992011-11-30 14:49:33 -0800557}
558
559static bool IsPrimitiveTag(JDWP::JdwpTag tag) {
560 switch (tag) {
561 case JDWP::JT_BOOLEAN:
562 case JDWP::JT_BYTE:
563 case JDWP::JT_CHAR:
564 case JDWP::JT_FLOAT:
565 case JDWP::JT_DOUBLE:
566 case JDWP::JT_INT:
567 case JDWP::JT_LONG:
568 case JDWP::JT_SHORT:
569 case JDWP::JT_VOID:
570 return true;
571 default:
572 return false;
573 }
574}
575
Sebastien Hertzb3b173b2015-02-06 09:16:32 +0100576void Dbg::StartJdwp() {
Elliott Hughesc0f09332012-03-26 13:27:06 -0700577 if (!gJdwpAllowed || !IsJdwpConfigured()) {
Elliott Hughes376a7a02011-10-24 18:35:55 -0700578 // No JDWP for you!
579 return;
580 }
581
Ian Rogers719d1a32014-03-06 12:13:39 -0800582 CHECK(gRegistry == nullptr);
Elliott Hughes475fc232011-10-25 15:00:35 -0700583 gRegistry = new ObjectRegistry;
584
Elliott Hughesd1cc8362011-10-24 16:58:50 -0700585 // Init JDWP if the debugger is enabled. This may connect out to a
586 // debugger, passively listen for a debugger, or block waiting for a
587 // debugger.
Sebastien Hertzb3b173b2015-02-06 09:16:32 +0100588 gJdwpState = JDWP::JdwpState::Create(&gJdwpOptions);
Ian Rogersc0542af2014-09-03 16:16:56 -0700589 if (gJdwpState == nullptr) {
Elliott Hughesf8a2df72011-12-01 12:19:54 -0800590 // We probably failed because some other process has the port already, which means that
591 // if we don't abort the user is likely to think they're talking to us when they're actually
592 // talking to that other process.
Elliott Hughes3d30d9b2011-12-07 17:35:48 -0800593 LOG(FATAL) << "Debugger thread failed to initialize";
Elliott Hughesd1cc8362011-10-24 16:58:50 -0700594 }
595
596 // If a debugger has already attached, send the "welcome" message.
597 // This may cause us to suspend all threads.
Elliott Hughes376a7a02011-10-24 18:35:55 -0700598 if (gJdwpState->IsActive()) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700599 ScopedObjectAccess soa(Thread::Current());
Sebastien Hertz7d955652014-10-22 10:57:10 +0200600 gJdwpState->PostVMStart();
Elliott Hughesd1cc8362011-10-24 16:58:50 -0700601 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700602}
603
Elliott Hughesd1cc8362011-10-24 16:58:50 -0700604void Dbg::StopJdwp() {
Sebastien Hertzc6345ef2014-08-18 19:26:39 +0200605 // Post VM_DEATH event before the JDWP connection is closed (either by the JDWP thread or the
606 // destruction of gJdwpState).
607 if (gJdwpState != nullptr && gJdwpState->IsActive()) {
608 gJdwpState->PostVMDeath();
609 }
Sebastien Hertz0376e6b2014-02-06 18:12:59 +0100610 // Prevent the JDWP thread from processing JDWP incoming packets after we close the connection.
Sebastien Hertz4e5b2082015-03-24 19:03:40 +0100611 Dispose();
Elliott Hughes376a7a02011-10-24 18:35:55 -0700612 delete gJdwpState;
Ian Rogers719d1a32014-03-06 12:13:39 -0800613 gJdwpState = nullptr;
Elliott Hughes475fc232011-10-25 15:00:35 -0700614 delete gRegistry;
Ian Rogers719d1a32014-03-06 12:13:39 -0800615 gRegistry = nullptr;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700616}
617
Elliott Hughes767a1472011-10-26 18:49:02 -0700618void Dbg::GcDidFinish() {
619 if (gDdmHpifWhen != HPIF_WHEN_NEVER) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700620 ScopedObjectAccess soa(Thread::Current());
Brian Carlstrom4d466a82014-05-08 19:05:29 -0700621 VLOG(jdwp) << "Sending heap info to DDM";
Elliott Hughes7162ad92011-10-27 14:08:42 -0700622 DdmSendHeapInfo(gDdmHpifWhen);
Elliott Hughes767a1472011-10-26 18:49:02 -0700623 }
624 if (gDdmHpsgWhen != HPSG_WHEN_NEVER) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700625 ScopedObjectAccess soa(Thread::Current());
Brian Carlstrom4d466a82014-05-08 19:05:29 -0700626 VLOG(jdwp) << "Dumping heap to DDM";
Elliott Hughes6a5bd492011-10-28 14:33:57 -0700627 DdmSendHeapSegments(false);
Elliott Hughes767a1472011-10-26 18:49:02 -0700628 }
629 if (gDdmNhsgWhen != HPSG_WHEN_NEVER) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700630 ScopedObjectAccess soa(Thread::Current());
Brian Carlstrom4d466a82014-05-08 19:05:29 -0700631 VLOG(jdwp) << "Dumping native heap to DDM";
Elliott Hughes6a5bd492011-10-28 14:33:57 -0700632 DdmSendHeapSegments(true);
Elliott Hughes767a1472011-10-26 18:49:02 -0700633 }
634}
635
Elliott Hughes4ffd3132011-10-24 12:06:42 -0700636void Dbg::SetJdwpAllowed(bool allowed) {
637 gJdwpAllowed = allowed;
638}
639
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700640DebugInvokeReq* Dbg::GetInvokeReq() {
Elliott Hughes475fc232011-10-25 15:00:35 -0700641 return Thread::Current()->GetInvokeReq();
642}
643
644Thread* Dbg::GetDebugThread() {
Ian Rogersc0542af2014-09-03 16:16:56 -0700645 return (gJdwpState != nullptr) ? gJdwpState->GetDebugThread() : nullptr;
Elliott Hughes475fc232011-10-25 15:00:35 -0700646}
647
648void Dbg::ClearWaitForEventThread() {
Sebastien Hertz2bf93f42015-01-09 18:44:05 +0100649 gJdwpState->ReleaseJdwpTokenForEvent();
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700650}
651
652void Dbg::Connected() {
Elliott Hughes3bb81562011-10-21 18:52:59 -0700653 CHECK(!gDebuggerConnected);
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -0800654 VLOG(jdwp) << "JDWP has attached";
Elliott Hughes3bb81562011-10-21 18:52:59 -0700655 gDebuggerConnected = true;
Elliott Hughes86964332012-02-15 19:37:42 -0800656 gDisposed = false;
657}
658
Sebastien Hertzf3928792014-11-17 19:00:37 +0100659bool Dbg::RequiresDeoptimization() {
660 // We don't need deoptimization if everything runs with interpreter after
661 // enabling -Xint mode.
662 return !Runtime::Current()->GetInstrumentation()->IsForcedInterpretOnly();
663}
664
Elliott Hughesa2155262011-11-16 16:26:58 -0800665void Dbg::GoActive() {
666 // Enable all debugging features, including scans for breakpoints.
667 // This is a no-op if we're already active.
668 // Only called from the JDWP handler thread.
Daniel Mihalyieb076692014-08-22 17:33:31 +0200669 if (IsDebuggerActive()) {
Elliott Hughesa2155262011-11-16 16:26:58 -0800670 return;
671 }
672
Elliott Hughesc0f09332012-03-26 13:27:06 -0700673 {
674 // TODO: dalvik only warned if there were breakpoints left over. clear in Dbg::Disconnected?
Sebastien Hertzed2be172014-08-19 15:33:43 +0200675 ReaderMutexLock mu(Thread::Current(), *Locks::breakpoint_lock_);
Elliott Hughesc0f09332012-03-26 13:27:06 -0700676 CHECK_EQ(gBreakpoints.size(), 0U);
677 }
Elliott Hughesa2155262011-11-16 16:26:58 -0800678
Sebastien Hertz138dbfc2013-12-04 18:15:25 +0100679 {
Brian Carlstrom306db812014-09-05 13:01:41 -0700680 MutexLock mu(Thread::Current(), *Locks::deoptimization_lock_);
Sebastien Hertz4d25df32014-03-21 17:44:46 +0100681 CHECK_EQ(deoptimization_requests_.size(), 0U);
682 CHECK_EQ(full_deoptimization_event_count_, 0U);
Sebastien Hertz42cd43f2014-05-13 14:15:41 +0200683 CHECK_EQ(dex_pc_change_event_ref_count_, 0U);
684 CHECK_EQ(method_enter_event_ref_count_, 0U);
685 CHECK_EQ(method_exit_event_ref_count_, 0U);
686 CHECK_EQ(field_read_event_ref_count_, 0U);
687 CHECK_EQ(field_write_event_ref_count_, 0U);
688 CHECK_EQ(exception_catch_event_ref_count_, 0U);
Sebastien Hertz138dbfc2013-12-04 18:15:25 +0100689 }
690
Ian Rogers62d6c772013-02-27 08:32:07 -0800691 Runtime* runtime = Runtime::Current();
Mathieu Chartierbf9fc582015-03-13 17:21:25 -0700692 runtime->GetThreadList()->SuspendAll(__FUNCTION__);
Ian Rogers62d6c772013-02-27 08:32:07 -0800693 Thread* self = Thread::Current();
694 ThreadState old_state = self->SetStateUnsafe(kRunnable);
695 CHECK_NE(old_state, kRunnable);
Sebastien Hertzf3928792014-11-17 19:00:37 +0100696 if (RequiresDeoptimization()) {
697 runtime->GetInstrumentation()->EnableDeoptimization();
698 }
Sebastien Hertz42cd43f2014-05-13 14:15:41 +0200699 instrumentation_events_ = 0;
Elliott Hughesa2155262011-11-16 16:26:58 -0800700 gDebuggerActive = true;
Ian Rogers62d6c772013-02-27 08:32:07 -0800701 CHECK_EQ(self->SetStateUnsafe(old_state), kRunnable);
702 runtime->GetThreadList()->ResumeAll();
703
704 LOG(INFO) << "Debugger is active";
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700705}
706
707void Dbg::Disconnected() {
Elliott Hughes234ab152011-10-26 14:02:26 -0700708 CHECK(gDebuggerConnected);
709
Elliott Hughesc0f09332012-03-26 13:27:06 -0700710 LOG(INFO) << "Debugger is no longer active";
Elliott Hughes234ab152011-10-26 14:02:26 -0700711
Ian Rogers62d6c772013-02-27 08:32:07 -0800712 // Suspend all threads and exclusively acquire the mutator lock. Set the state of the thread
713 // to kRunnable to avoid scoped object access transitions. Remove the debugger as a listener
714 // and clear the object registry.
715 Runtime* runtime = Runtime::Current();
Mathieu Chartierbf9fc582015-03-13 17:21:25 -0700716 runtime->GetThreadList()->SuspendAll(__FUNCTION__);
Ian Rogers62d6c772013-02-27 08:32:07 -0800717 Thread* self = Thread::Current();
718 ThreadState old_state = self->SetStateUnsafe(kRunnable);
Sebastien Hertzaaea7342014-02-25 15:10:04 +0100719
720 // Debugger may not be active at this point.
Daniel Mihalyieb076692014-08-22 17:33:31 +0200721 if (IsDebuggerActive()) {
Sebastien Hertzaaea7342014-02-25 15:10:04 +0100722 {
723 // Since we're going to disable deoptimization, we clear the deoptimization requests queue.
724 // This prevents us from having any pending deoptimization request when the debugger attaches
725 // to us again while no event has been requested yet.
Brian Carlstrom306db812014-09-05 13:01:41 -0700726 MutexLock mu(Thread::Current(), *Locks::deoptimization_lock_);
Sebastien Hertz4d25df32014-03-21 17:44:46 +0100727 deoptimization_requests_.clear();
728 full_deoptimization_event_count_ = 0U;
Sebastien Hertzaaea7342014-02-25 15:10:04 +0100729 }
Sebastien Hertz42cd43f2014-05-13 14:15:41 +0200730 if (instrumentation_events_ != 0) {
731 runtime->GetInstrumentation()->RemoveListener(&gDebugInstrumentationListener,
732 instrumentation_events_);
733 instrumentation_events_ = 0;
734 }
Sebastien Hertzf3928792014-11-17 19:00:37 +0100735 if (RequiresDeoptimization()) {
Sebastien Hertz0462c4c2015-04-01 16:34:17 +0200736 runtime->GetInstrumentation()->DisableDeoptimization(kDbgInstrumentationKey);
Sebastien Hertzf3928792014-11-17 19:00:37 +0100737 }
Sebastien Hertzaaea7342014-02-25 15:10:04 +0100738 gDebuggerActive = false;
Sebastien Hertz138dbfc2013-12-04 18:15:25 +0100739 }
Ian Rogers62d6c772013-02-27 08:32:07 -0800740 CHECK_EQ(self->SetStateUnsafe(old_state), kRunnable);
741 runtime->GetThreadList()->ResumeAll();
Sebastien Hertz55f65342015-01-13 22:48:34 +0100742
743 {
744 ScopedObjectAccess soa(self);
745 gRegistry->Clear();
746 }
747
748 gDebuggerConnected = false;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700749}
750
Sebastien Hertzb3b173b2015-02-06 09:16:32 +0100751void Dbg::ConfigureJdwp(const JDWP::JdwpOptions& jdwp_options) {
752 CHECK_NE(jdwp_options.transport, JDWP::kJdwpTransportUnknown);
753 gJdwpOptions = jdwp_options;
754 gJdwpConfigured = true;
755}
756
Elliott Hughesc0f09332012-03-26 13:27:06 -0700757bool Dbg::IsJdwpConfigured() {
Elliott Hughes3bb81562011-10-21 18:52:59 -0700758 return gJdwpConfigured;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700759}
760
761int64_t Dbg::LastDebuggerActivity() {
Elliott Hughesca951522011-12-05 12:01:32 -0800762 return gJdwpState->LastDebuggerActivity();
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700763}
764
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700765void Dbg::UndoDebuggerSuspensions() {
Elliott Hughes234ab152011-10-26 14:02:26 -0700766 Runtime::Current()->GetThreadList()->UndoDebuggerSuspensions();
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700767}
768
Elliott Hughes88d63092013-01-09 09:55:54 -0800769std::string Dbg::GetClassName(JDWP::RefTypeId class_id) {
Ian Rogersc0542af2014-09-03 16:16:56 -0700770 JDWP::JdwpError error;
771 mirror::Object* o = gRegistry->Get<mirror::Object*>(class_id, &error);
772 if (o == nullptr) {
773 if (error == JDWP::ERR_NONE) {
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700774 return "null";
Ian Rogersc0542af2014-09-03 16:16:56 -0700775 } else {
776 return StringPrintf("invalid object %p", reinterpret_cast<void*>(class_id));
777 }
Elliott Hughes436e3722012-02-17 20:01:47 -0800778 }
779 if (!o->IsClass()) {
Brian Carlstrom7934ac22013-07-26 10:54:15 -0700780 return StringPrintf("non-class %p", o); // This is only used for debugging output anyway.
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -0800781 }
Sebastien Hertz6995c602014-09-09 12:10:13 +0200782 return GetClassName(o->AsClass());
783}
784
785std::string Dbg::GetClassName(mirror::Class* klass) {
Sebastien Hertza9aa0ff2014-09-19 12:07:51 +0200786 if (klass == nullptr) {
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700787 return "null";
Sebastien Hertza9aa0ff2014-09-19 12:07:51 +0200788 }
Ian Rogers1ff3c982014-08-12 02:30:58 -0700789 std::string temp;
Sebastien Hertz6995c602014-09-09 12:10:13 +0200790 return DescriptorToName(klass->GetDescriptor(&temp));
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700791}
792
Ian Rogersc0542af2014-09-03 16:16:56 -0700793JDWP::JdwpError Dbg::GetClassObject(JDWP::RefTypeId id, JDWP::ObjectId* class_object_id) {
Elliott Hughes436e3722012-02-17 20:01:47 -0800794 JDWP::JdwpError status;
Ian Rogersc0542af2014-09-03 16:16:56 -0700795 mirror::Class* c = DecodeClass(id, &status);
796 if (c == nullptr) {
797 *class_object_id = 0;
Elliott Hughes436e3722012-02-17 20:01:47 -0800798 return status;
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -0800799 }
Ian Rogersc0542af2014-09-03 16:16:56 -0700800 *class_object_id = gRegistry->Add(c);
Elliott Hughes436e3722012-02-17 20:01:47 -0800801 return JDWP::ERR_NONE;
Elliott Hughes86964332012-02-15 19:37:42 -0800802}
803
Ian Rogersc0542af2014-09-03 16:16:56 -0700804JDWP::JdwpError Dbg::GetSuperclass(JDWP::RefTypeId id, JDWP::RefTypeId* superclass_id) {
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -0800805 JDWP::JdwpError status;
Ian Rogersc0542af2014-09-03 16:16:56 -0700806 mirror::Class* c = DecodeClass(id, &status);
807 if (c == nullptr) {
808 *superclass_id = 0;
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -0800809 return status;
810 }
811 if (c->IsInterface()) {
812 // http://code.google.com/p/android/issues/detail?id=20856
Ian Rogersc0542af2014-09-03 16:16:56 -0700813 *superclass_id = 0;
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -0800814 } else {
Ian Rogersc0542af2014-09-03 16:16:56 -0700815 *superclass_id = gRegistry->Add(c->GetSuperClass());
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -0800816 }
817 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700818}
819
Elliott Hughes436e3722012-02-17 20:01:47 -0800820JDWP::JdwpError Dbg::GetClassLoader(JDWP::RefTypeId id, JDWP::ExpandBuf* pReply) {
Ian Rogersc0542af2014-09-03 16:16:56 -0700821 JDWP::JdwpError error;
822 mirror::Object* o = gRegistry->Get<mirror::Object*>(id, &error);
823 if (o == nullptr) {
Elliott Hughes436e3722012-02-17 20:01:47 -0800824 return JDWP::ERR_INVALID_OBJECT;
825 }
826 expandBufAddObjectId(pReply, gRegistry->Add(o->GetClass()->GetClassLoader()));
827 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700828}
829
Elliott Hughes436e3722012-02-17 20:01:47 -0800830JDWP::JdwpError Dbg::GetModifiers(JDWP::RefTypeId id, JDWP::ExpandBuf* pReply) {
Ian Rogersc0542af2014-09-03 16:16:56 -0700831 JDWP::JdwpError error;
832 mirror::Class* c = DecodeClass(id, &error);
833 if (c == nullptr) {
834 return error;
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -0800835 }
Elliott Hughes436e3722012-02-17 20:01:47 -0800836
837 uint32_t access_flags = c->GetAccessFlags() & kAccJavaFlagsMask;
838
Yevgeny Roubande34eea2014-02-15 01:06:03 +0700839 // Set ACC_SUPER. Dex files don't contain this flag but only classes are supposed to have it set,
840 // not interfaces.
Elliott Hughes436e3722012-02-17 20:01:47 -0800841 // Class.getModifiers doesn't return it, but JDWP does, so we set it here.
Yevgeny Roubande34eea2014-02-15 01:06:03 +0700842 if ((access_flags & kAccInterface) == 0) {
843 access_flags |= kAccSuper;
844 }
Elliott Hughes436e3722012-02-17 20:01:47 -0800845
846 expandBufAdd4BE(pReply, access_flags);
847
848 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700849}
850
Ian Rogersc0542af2014-09-03 16:16:56 -0700851JDWP::JdwpError Dbg::GetMonitorInfo(JDWP::ObjectId object_id, JDWP::ExpandBuf* reply) {
852 JDWP::JdwpError error;
853 mirror::Object* o = gRegistry->Get<mirror::Object*>(object_id, &error);
854 if (o == nullptr) {
Elliott Hughesf327e072013-01-09 16:01:26 -0800855 return JDWP::ERR_INVALID_OBJECT;
856 }
857
858 // Ensure all threads are suspended while we read objects' lock words.
859 Thread* self = Thread::Current();
Sebastien Hertz54263242014-03-19 18:16:50 +0100860 CHECK_EQ(self->GetState(), kRunnable);
861 self->TransitionFromRunnableToSuspended(kSuspended);
Mathieu Chartierbf9fc582015-03-13 17:21:25 -0700862 Runtime::Current()->GetThreadList()->SuspendAll(__FUNCTION__);
Elliott Hughesf327e072013-01-09 16:01:26 -0800863
864 MonitorInfo monitor_info(o);
865
Sebastien Hertz54263242014-03-19 18:16:50 +0100866 Runtime::Current()->GetThreadList()->ResumeAll();
867 self->TransitionFromSuspendedToRunnable();
Elliott Hughesf327e072013-01-09 16:01:26 -0800868
Ian Rogersc0542af2014-09-03 16:16:56 -0700869 if (monitor_info.owner_ != nullptr) {
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700870 expandBufAddObjectId(reply, gRegistry->Add(monitor_info.owner_->GetPeer()));
Elliott Hughesf327e072013-01-09 16:01:26 -0800871 } else {
Ian Rogersc0542af2014-09-03 16:16:56 -0700872 expandBufAddObjectId(reply, gRegistry->Add(nullptr));
Elliott Hughesf327e072013-01-09 16:01:26 -0800873 }
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700874 expandBufAdd4BE(reply, monitor_info.entry_count_);
875 expandBufAdd4BE(reply, monitor_info.waiters_.size());
876 for (size_t i = 0; i < monitor_info.waiters_.size(); ++i) {
877 expandBufAddObjectId(reply, gRegistry->Add(monitor_info.waiters_[i]->GetPeer()));
Elliott Hughesf327e072013-01-09 16:01:26 -0800878 }
879 return JDWP::ERR_NONE;
880}
881
Elliott Hughes734b8c62013-01-11 15:32:45 -0800882JDWP::JdwpError Dbg::GetOwnedMonitors(JDWP::ObjectId thread_id,
Ian Rogersc0542af2014-09-03 16:16:56 -0700883 std::vector<JDWP::ObjectId>* monitors,
884 std::vector<uint32_t>* stack_depths) {
Elliott Hughes4993bbc2013-01-10 15:41:25 -0800885 struct OwnedMonitorVisitor : public StackVisitor {
Hiroshi Yamauchib5a9e3d2014-06-09 12:11:20 -0700886 OwnedMonitorVisitor(Thread* thread, Context* context,
Hiroshi Yamauchicc8c5c52014-06-13 15:08:05 -0700887 std::vector<JDWP::ObjectId>* monitor_vector,
Hiroshi Yamauchib5a9e3d2014-06-09 12:11:20 -0700888 std::vector<uint32_t>* stack_depth_vector)
Elliott Hughes4993bbc2013-01-10 15:41:25 -0800889 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_)
Nicolas Geoffray8e5bd182015-05-06 11:34:34 +0100890 : StackVisitor(thread, context, StackVisitor::StackWalkKind::kIncludeInlinedFrames),
891 current_stack_depth(0),
892 monitors(monitor_vector),
893 stack_depths(stack_depth_vector) {}
Elliott Hughes4993bbc2013-01-10 15:41:25 -0800894
895 // TODO: Enable annotalysis. We know lock is held in constructor, but abstraction confuses
896 // annotalysis.
897 bool VisitFrame() NO_THREAD_SAFETY_ANALYSIS {
898 if (!GetMethod()->IsRuntimeMethod()) {
899 Monitor::VisitLocks(this, AppendOwnedMonitors, this);
Elliott Hughes734b8c62013-01-11 15:32:45 -0800900 ++current_stack_depth;
Elliott Hughes4993bbc2013-01-10 15:41:25 -0800901 }
902 return true;
903 }
904
Hiroshi Yamauchicc8c5c52014-06-13 15:08:05 -0700905 static void AppendOwnedMonitors(mirror::Object* owned_monitor, void* arg)
906 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Ian Rogers7a22fa62013-01-23 12:16:16 -0800907 OwnedMonitorVisitor* visitor = reinterpret_cast<OwnedMonitorVisitor*>(arg);
Hiroshi Yamauchicc8c5c52014-06-13 15:08:05 -0700908 visitor->monitors->push_back(gRegistry->Add(owned_monitor));
Hiroshi Yamauchib5a9e3d2014-06-09 12:11:20 -0700909 visitor->stack_depths->push_back(visitor->current_stack_depth);
Elliott Hughes4993bbc2013-01-10 15:41:25 -0800910 }
911
Elliott Hughes734b8c62013-01-11 15:32:45 -0800912 size_t current_stack_depth;
Ian Rogersc0542af2014-09-03 16:16:56 -0700913 std::vector<JDWP::ObjectId>* const monitors;
914 std::vector<uint32_t>* const stack_depths;
Elliott Hughes4993bbc2013-01-10 15:41:25 -0800915 };
Elliott Hughes4993bbc2013-01-10 15:41:25 -0800916
Hiroshi Yamauchib5a9e3d2014-06-09 12:11:20 -0700917 ScopedObjectAccessUnchecked soa(Thread::Current());
Sebastien Hertz69206392015-04-07 15:54:25 +0200918 JDWP::JdwpError error;
919 Thread* thread = DecodeThread(soa, thread_id, &error);
920 if (thread == nullptr) {
921 return error;
922 }
923 if (!IsSuspendedForDebugger(soa, thread)) {
924 return JDWP::ERR_THREAD_NOT_SUSPENDED;
Hiroshi Yamauchib5a9e3d2014-06-09 12:11:20 -0700925 }
Hiroshi Yamauchicc8c5c52014-06-13 15:08:05 -0700926 std::unique_ptr<Context> context(Context::Create());
Ian Rogersc0542af2014-09-03 16:16:56 -0700927 OwnedMonitorVisitor visitor(thread, context.get(), monitors, stack_depths);
Hiroshi Yamauchicc8c5c52014-06-13 15:08:05 -0700928 visitor.WalkStack();
Elliott Hughes4993bbc2013-01-10 15:41:25 -0800929 return JDWP::ERR_NONE;
930}
931
Sebastien Hertz52d131d2014-03-13 16:17:40 +0100932JDWP::JdwpError Dbg::GetContendedMonitor(JDWP::ObjectId thread_id,
Ian Rogersc0542af2014-09-03 16:16:56 -0700933 JDWP::ObjectId* contended_monitor) {
Elliott Hughesf9501702013-01-11 11:22:27 -0800934 ScopedObjectAccessUnchecked soa(Thread::Current());
Ian Rogersc0542af2014-09-03 16:16:56 -0700935 *contended_monitor = 0;
Sebastien Hertz69206392015-04-07 15:54:25 +0200936 JDWP::JdwpError error;
937 Thread* thread = DecodeThread(soa, thread_id, &error);
938 if (thread == nullptr) {
939 return error;
Elliott Hughesf9501702013-01-11 11:22:27 -0800940 }
Sebastien Hertz69206392015-04-07 15:54:25 +0200941 if (!IsSuspendedForDebugger(soa, thread)) {
942 return JDWP::ERR_THREAD_NOT_SUSPENDED;
943 }
944 mirror::Object* contended_monitor_obj = Monitor::GetContendedMonitor(thread);
Hiroshi Yamauchib5a9e3d2014-06-09 12:11:20 -0700945 // Add() requires the thread_list_lock_ not held to avoid the lock
946 // level violation.
Ian Rogersc0542af2014-09-03 16:16:56 -0700947 *contended_monitor = gRegistry->Add(contended_monitor_obj);
Elliott Hughesf9501702013-01-11 11:22:27 -0800948 return JDWP::ERR_NONE;
949}
950
Elliott Hughesec0f83d2013-01-15 16:54:08 -0800951JDWP::JdwpError Dbg::GetInstanceCounts(const std::vector<JDWP::RefTypeId>& class_ids,
Ian Rogersc0542af2014-09-03 16:16:56 -0700952 std::vector<uint64_t>* counts) {
Mathieu Chartier412c7fc2014-02-07 12:18:39 -0800953 gc::Heap* heap = Runtime::Current()->GetHeap();
954 heap->CollectGarbage(false);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800955 std::vector<mirror::Class*> classes;
Ian Rogersc0542af2014-09-03 16:16:56 -0700956 counts->clear();
Elliott Hughesec0f83d2013-01-15 16:54:08 -0800957 for (size_t i = 0; i < class_ids.size(); ++i) {
Ian Rogersc0542af2014-09-03 16:16:56 -0700958 JDWP::JdwpError error;
959 mirror::Class* c = DecodeClass(class_ids[i], &error);
960 if (c == nullptr) {
961 return error;
Elliott Hughesec0f83d2013-01-15 16:54:08 -0800962 }
963 classes.push_back(c);
Ian Rogersc0542af2014-09-03 16:16:56 -0700964 counts->push_back(0);
Elliott Hughesec0f83d2013-01-15 16:54:08 -0800965 }
Ian Rogersc0542af2014-09-03 16:16:56 -0700966 heap->CountInstances(classes, false, &(*counts)[0]);
Elliott Hughesec0f83d2013-01-15 16:54:08 -0800967 return JDWP::ERR_NONE;
968}
969
Ian Rogersc0542af2014-09-03 16:16:56 -0700970JDWP::JdwpError Dbg::GetInstances(JDWP::RefTypeId class_id, int32_t max_count,
971 std::vector<JDWP::ObjectId>* instances) {
Mathieu Chartier412c7fc2014-02-07 12:18:39 -0800972 gc::Heap* heap = Runtime::Current()->GetHeap();
973 // We only want reachable instances, so do a GC.
974 heap->CollectGarbage(false);
Ian Rogersc0542af2014-09-03 16:16:56 -0700975 JDWP::JdwpError error;
976 mirror::Class* c = DecodeClass(class_id, &error);
Mathieu Chartier412c7fc2014-02-07 12:18:39 -0800977 if (c == nullptr) {
Ian Rogersc0542af2014-09-03 16:16:56 -0700978 return error;
Elliott Hughes3b78c942013-01-15 17:35:41 -0800979 }
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800980 std::vector<mirror::Object*> raw_instances;
Elliott Hughes3b78c942013-01-15 17:35:41 -0800981 Runtime::Current()->GetHeap()->GetInstances(c, max_count, raw_instances);
982 for (size_t i = 0; i < raw_instances.size(); ++i) {
Ian Rogersc0542af2014-09-03 16:16:56 -0700983 instances->push_back(gRegistry->Add(raw_instances[i]));
Elliott Hughes3b78c942013-01-15 17:35:41 -0800984 }
985 return JDWP::ERR_NONE;
986}
987
Elliott Hughes0cbaff52013-01-16 15:28:01 -0800988JDWP::JdwpError Dbg::GetReferringObjects(JDWP::ObjectId object_id, int32_t max_count,
Ian Rogersc0542af2014-09-03 16:16:56 -0700989 std::vector<JDWP::ObjectId>* referring_objects) {
Mathieu Chartier412c7fc2014-02-07 12:18:39 -0800990 gc::Heap* heap = Runtime::Current()->GetHeap();
991 heap->CollectGarbage(false);
Ian Rogersc0542af2014-09-03 16:16:56 -0700992 JDWP::JdwpError error;
993 mirror::Object* o = gRegistry->Get<mirror::Object*>(object_id, &error);
994 if (o == nullptr) {
Elliott Hughes0cbaff52013-01-16 15:28:01 -0800995 return JDWP::ERR_INVALID_OBJECT;
996 }
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800997 std::vector<mirror::Object*> raw_instances;
Mathieu Chartier412c7fc2014-02-07 12:18:39 -0800998 heap->GetReferringObjects(o, max_count, raw_instances);
Elliott Hughes0cbaff52013-01-16 15:28:01 -0800999 for (size_t i = 0; i < raw_instances.size(); ++i) {
Ian Rogersc0542af2014-09-03 16:16:56 -07001000 referring_objects->push_back(gRegistry->Add(raw_instances[i]));
Elliott Hughes0cbaff52013-01-16 15:28:01 -08001001 }
1002 return JDWP::ERR_NONE;
1003}
1004
Ian Rogersc0542af2014-09-03 16:16:56 -07001005JDWP::JdwpError Dbg::DisableCollection(JDWP::ObjectId object_id) {
1006 JDWP::JdwpError error;
1007 mirror::Object* o = gRegistry->Get<mirror::Object*>(object_id, &error);
1008 if (o == nullptr) {
Sebastien Hertze96060a2013-12-11 12:06:28 +01001009 return JDWP::ERR_INVALID_OBJECT;
1010 }
Elliott Hughes64f574f2013-02-20 14:57:12 -08001011 gRegistry->DisableCollection(object_id);
1012 return JDWP::ERR_NONE;
1013}
1014
Ian Rogersc0542af2014-09-03 16:16:56 -07001015JDWP::JdwpError Dbg::EnableCollection(JDWP::ObjectId object_id) {
1016 JDWP::JdwpError error;
1017 mirror::Object* o = gRegistry->Get<mirror::Object*>(object_id, &error);
Sebastien Hertze96060a2013-12-11 12:06:28 +01001018 // Unlike DisableCollection, JDWP specs do not state an invalid object causes an error. The RI
1019 // also ignores these cases and never return an error. However it's not obvious why this command
1020 // should behave differently from DisableCollection and IsCollected commands. So let's be more
1021 // strict and return an error if this happens.
Ian Rogersc0542af2014-09-03 16:16:56 -07001022 if (o == nullptr) {
Sebastien Hertze96060a2013-12-11 12:06:28 +01001023 return JDWP::ERR_INVALID_OBJECT;
1024 }
Elliott Hughes64f574f2013-02-20 14:57:12 -08001025 gRegistry->EnableCollection(object_id);
1026 return JDWP::ERR_NONE;
1027}
1028
Ian Rogersc0542af2014-09-03 16:16:56 -07001029JDWP::JdwpError Dbg::IsCollected(JDWP::ObjectId object_id, bool* is_collected) {
1030 *is_collected = true;
Sebastien Hertz65637eb2014-01-10 17:40:02 +01001031 if (object_id == 0) {
1032 // Null object id is invalid.
Sebastien Hertze96060a2013-12-11 12:06:28 +01001033 return JDWP::ERR_INVALID_OBJECT;
1034 }
Sebastien Hertz65637eb2014-01-10 17:40:02 +01001035 // JDWP specs state an INVALID_OBJECT error is returned if the object ID is not valid. However
1036 // the RI seems to ignore this and assume object has been collected.
Ian Rogersc0542af2014-09-03 16:16:56 -07001037 JDWP::JdwpError error;
1038 mirror::Object* o = gRegistry->Get<mirror::Object*>(object_id, &error);
1039 if (o != nullptr) {
1040 *is_collected = gRegistry->IsCollected(object_id);
Sebastien Hertz65637eb2014-01-10 17:40:02 +01001041 }
Elliott Hughes64f574f2013-02-20 14:57:12 -08001042 return JDWP::ERR_NONE;
1043}
1044
Ian Rogersc0542af2014-09-03 16:16:56 -07001045void Dbg::DisposeObject(JDWP::ObjectId object_id, uint32_t reference_count) {
Elliott Hughes64f574f2013-02-20 14:57:12 -08001046 gRegistry->DisposeObject(object_id, reference_count);
1047}
1048
Sebastien Hertz6995c602014-09-09 12:10:13 +02001049JDWP::JdwpTypeTag Dbg::GetTypeTag(mirror::Class* klass) {
Sebastien Hertz4d8fd492014-03-28 16:29:41 +01001050 DCHECK(klass != nullptr);
1051 if (klass->IsArrayClass()) {
1052 return JDWP::TT_ARRAY;
1053 } else if (klass->IsInterface()) {
1054 return JDWP::TT_INTERFACE;
1055 } else {
1056 return JDWP::TT_CLASS;
1057 }
1058}
1059
Elliott Hughes88d63092013-01-09 09:55:54 -08001060JDWP::JdwpError Dbg::GetReflectedType(JDWP::RefTypeId class_id, JDWP::ExpandBuf* pReply) {
Ian Rogersc0542af2014-09-03 16:16:56 -07001061 JDWP::JdwpError error;
1062 mirror::Class* c = DecodeClass(class_id, &error);
1063 if (c == nullptr) {
1064 return error;
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -08001065 }
Elliott Hughes436e3722012-02-17 20:01:47 -08001066
Sebastien Hertz4d8fd492014-03-28 16:29:41 +01001067 JDWP::JdwpTypeTag type_tag = GetTypeTag(c);
1068 expandBufAdd1(pReply, type_tag);
Elliott Hughes88d63092013-01-09 09:55:54 -08001069 expandBufAddRefTypeId(pReply, class_id);
Elliott Hughes436e3722012-02-17 20:01:47 -08001070 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001071}
1072
Ian Rogersc0542af2014-09-03 16:16:56 -07001073void Dbg::GetClassList(std::vector<JDWP::RefTypeId>* classes) {
Elliott Hughesa2155262011-11-16 16:26:58 -08001074 // Get the complete list of reference classes (i.e. all classes except
1075 // the primitive types).
1076 // Returns a newly-allocated buffer full of RefTypeId values.
1077 struct ClassListCreator {
Andreas Gampe277ccbd2014-11-03 21:36:10 -08001078 explicit ClassListCreator(std::vector<JDWP::RefTypeId>* classes_in) : classes(classes_in) {
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -08001079 }
1080
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001081 static bool Visit(mirror::Class* c, void* arg) {
Elliott Hughesa2155262011-11-16 16:26:58 -08001082 return reinterpret_cast<ClassListCreator*>(arg)->Visit(c);
1083 }
1084
Elliott Hughes64f574f2013-02-20 14:57:12 -08001085 // TODO: Enable annotalysis. We know lock is held in constructor, but abstraction confuses
1086 // annotalysis.
1087 bool Visit(mirror::Class* c) NO_THREAD_SAFETY_ANALYSIS {
Elliott Hughesa2155262011-11-16 16:26:58 -08001088 if (!c->IsPrimitive()) {
Ian Rogersc0542af2014-09-03 16:16:56 -07001089 classes->push_back(gRegistry->AddRefType(c));
Elliott Hughesa2155262011-11-16 16:26:58 -08001090 }
1091 return true;
1092 }
1093
Ian Rogersc0542af2014-09-03 16:16:56 -07001094 std::vector<JDWP::RefTypeId>* const classes;
Elliott Hughesa2155262011-11-16 16:26:58 -08001095 };
1096
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -08001097 ClassListCreator clc(classes);
Sebastien Hertz4537c412014-08-28 14:41:50 +02001098 Runtime::Current()->GetClassLinker()->VisitClassesWithoutClassesLock(ClassListCreator::Visit,
1099 &clc);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001100}
1101
Ian Rogers1ff3c982014-08-12 02:30:58 -07001102JDWP::JdwpError Dbg::GetClassInfo(JDWP::RefTypeId class_id, JDWP::JdwpTypeTag* pTypeTag,
1103 uint32_t* pStatus, std::string* pDescriptor) {
Ian Rogersc0542af2014-09-03 16:16:56 -07001104 JDWP::JdwpError error;
1105 mirror::Class* c = DecodeClass(class_id, &error);
1106 if (c == nullptr) {
1107 return error;
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -08001108 }
1109
Elliott Hughesa2155262011-11-16 16:26:58 -08001110 if (c->IsArrayClass()) {
1111 *pStatus = JDWP::CS_VERIFIED | JDWP::CS_PREPARED;
1112 *pTypeTag = JDWP::TT_ARRAY;
1113 } else {
1114 if (c->IsErroneous()) {
1115 *pStatus = JDWP::CS_ERROR;
1116 } else {
1117 *pStatus = JDWP::CS_VERIFIED | JDWP::CS_PREPARED | JDWP::CS_INITIALIZED;
1118 }
1119 *pTypeTag = c->IsInterface() ? JDWP::TT_INTERFACE : JDWP::TT_CLASS;
1120 }
1121
Ian Rogersc0542af2014-09-03 16:16:56 -07001122 if (pDescriptor != nullptr) {
Ian Rogers1ff3c982014-08-12 02:30:58 -07001123 std::string temp;
1124 *pDescriptor = c->GetDescriptor(&temp);
Elliott Hughesa2155262011-11-16 16:26:58 -08001125 }
Elliott Hughes436e3722012-02-17 20:01:47 -08001126 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001127}
1128
Ian Rogersc0542af2014-09-03 16:16:56 -07001129void Dbg::FindLoadedClassBySignature(const char* descriptor, std::vector<JDWP::RefTypeId>* ids) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001130 std::vector<mirror::Class*> classes;
Elliott Hughes6fa602d2011-12-02 17:54:25 -08001131 Runtime::Current()->GetClassLinker()->LookupClasses(descriptor, classes);
Ian Rogersc0542af2014-09-03 16:16:56 -07001132 ids->clear();
Elliott Hughes6fa602d2011-12-02 17:54:25 -08001133 for (size_t i = 0; i < classes.size(); ++i) {
Ian Rogersc0542af2014-09-03 16:16:56 -07001134 ids->push_back(gRegistry->Add(classes[i]));
Elliott Hughes6fa602d2011-12-02 17:54:25 -08001135 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001136}
1137
Ian Rogersc0542af2014-09-03 16:16:56 -07001138JDWP::JdwpError Dbg::GetReferenceType(JDWP::ObjectId object_id, JDWP::ExpandBuf* pReply) {
1139 JDWP::JdwpError error;
1140 mirror::Object* o = gRegistry->Get<mirror::Object*>(object_id, &error);
1141 if (o == nullptr) {
Elliott Hughes2435a572012-02-17 16:07:41 -08001142 return JDWP::ERR_INVALID_OBJECT;
Elliott Hughes499c5132011-11-17 14:55:11 -08001143 }
Elliott Hughes2435a572012-02-17 16:07:41 -08001144
Sebastien Hertz4d8fd492014-03-28 16:29:41 +01001145 JDWP::JdwpTypeTag type_tag = GetTypeTag(o->GetClass());
Elliott Hughes64f574f2013-02-20 14:57:12 -08001146 JDWP::RefTypeId type_id = gRegistry->AddRefType(o->GetClass());
Elliott Hughes2435a572012-02-17 16:07:41 -08001147
1148 expandBufAdd1(pReply, type_tag);
1149 expandBufAddRefTypeId(pReply, type_id);
1150
1151 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001152}
1153
Ian Rogersfc0e94b2013-09-23 23:51:32 -07001154JDWP::JdwpError Dbg::GetSignature(JDWP::RefTypeId class_id, std::string* signature) {
Ian Rogersc0542af2014-09-03 16:16:56 -07001155 JDWP::JdwpError error;
1156 mirror::Class* c = DecodeClass(class_id, &error);
1157 if (c == nullptr) {
1158 return error;
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -08001159 }
Ian Rogers1ff3c982014-08-12 02:30:58 -07001160 std::string temp;
1161 *signature = c->GetDescriptor(&temp);
Elliott Hughes1fe7afb2012-02-13 17:23:03 -08001162 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001163}
1164
Ian Rogersc0542af2014-09-03 16:16:56 -07001165JDWP::JdwpError Dbg::GetSourceFile(JDWP::RefTypeId class_id, std::string* result) {
1166 JDWP::JdwpError error;
1167 mirror::Class* c = DecodeClass(class_id, &error);
Sebastien Hertz4206eb52014-06-05 10:15:45 +02001168 if (c == nullptr) {
Ian Rogersc0542af2014-09-03 16:16:56 -07001169 return error;
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -08001170 }
Sebastien Hertz4206eb52014-06-05 10:15:45 +02001171 const char* source_file = c->GetSourceFile();
1172 if (source_file == nullptr) {
Sebastien Hertzb7054ba2014-03-13 11:52:31 +01001173 return JDWP::ERR_ABSENT_INFORMATION;
1174 }
Ian Rogersc0542af2014-09-03 16:16:56 -07001175 *result = source_file;
Elliott Hughes436e3722012-02-17 20:01:47 -08001176 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001177}
1178
Ian Rogersc0542af2014-09-03 16:16:56 -07001179JDWP::JdwpError Dbg::GetObjectTag(JDWP::ObjectId object_id, uint8_t* tag) {
Ian Rogers98379392014-02-24 16:53:16 -08001180 ScopedObjectAccessUnchecked soa(Thread::Current());
Ian Rogersc0542af2014-09-03 16:16:56 -07001181 JDWP::JdwpError error;
1182 mirror::Object* o = gRegistry->Get<mirror::Object*>(object_id, &error);
1183 if (error != JDWP::ERR_NONE) {
1184 *tag = JDWP::JT_VOID;
1185 return error;
Elliott Hughes546b9862012-06-20 16:06:13 -07001186 }
Ian Rogersc0542af2014-09-03 16:16:56 -07001187 *tag = TagFromObject(soa, o);
Elliott Hughes546b9862012-06-20 16:06:13 -07001188 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001189}
1190
Elliott Hughesaed4be92011-12-02 16:16:23 -08001191size_t Dbg::GetTagWidth(JDWP::JdwpTag tag) {
Elliott Hughesdbb40792011-11-18 17:05:22 -08001192 switch (tag) {
1193 case JDWP::JT_VOID:
1194 return 0;
1195 case JDWP::JT_BYTE:
1196 case JDWP::JT_BOOLEAN:
1197 return 1;
1198 case JDWP::JT_CHAR:
1199 case JDWP::JT_SHORT:
1200 return 2;
1201 case JDWP::JT_FLOAT:
1202 case JDWP::JT_INT:
1203 return 4;
1204 case JDWP::JT_ARRAY:
1205 case JDWP::JT_OBJECT:
1206 case JDWP::JT_STRING:
1207 case JDWP::JT_THREAD:
1208 case JDWP::JT_THREAD_GROUP:
1209 case JDWP::JT_CLASS_LOADER:
1210 case JDWP::JT_CLASS_OBJECT:
1211 return sizeof(JDWP::ObjectId);
1212 case JDWP::JT_DOUBLE:
1213 case JDWP::JT_LONG:
1214 return 8;
1215 default:
Elliott Hughes3d30d9b2011-12-07 17:35:48 -08001216 LOG(FATAL) << "Unknown tag " << tag;
Elliott Hughesdbb40792011-11-18 17:05:22 -08001217 return -1;
1218 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001219}
1220
Ian Rogersc0542af2014-09-03 16:16:56 -07001221JDWP::JdwpError Dbg::GetArrayLength(JDWP::ObjectId array_id, int32_t* length) {
1222 JDWP::JdwpError error;
1223 mirror::Array* a = DecodeNonNullArray(array_id, &error);
1224 if (a == nullptr) {
1225 return error;
Elliott Hughes24437992011-11-30 14:49:33 -08001226 }
Ian Rogersc0542af2014-09-03 16:16:56 -07001227 *length = a->GetLength();
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -08001228 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001229}
1230
Elliott Hughes88d63092013-01-09 09:55:54 -08001231JDWP::JdwpError Dbg::OutputArray(JDWP::ObjectId array_id, int offset, int count, JDWP::ExpandBuf* pReply) {
Ian Rogersc0542af2014-09-03 16:16:56 -07001232 JDWP::JdwpError error;
1233 mirror::Array* a = DecodeNonNullArray(array_id, &error);
Ian Rogers98379392014-02-24 16:53:16 -08001234 if (a == nullptr) {
Ian Rogersc0542af2014-09-03 16:16:56 -07001235 return error;
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -08001236 }
Elliott Hughes24437992011-11-30 14:49:33 -08001237
1238 if (offset < 0 || count < 0 || offset > a->GetLength() || a->GetLength() - offset < count) {
1239 LOG(WARNING) << __FUNCTION__ << " access out of bounds: offset=" << offset << "; count=" << count;
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -08001240 return JDWP::ERR_INVALID_LENGTH;
Elliott Hughes24437992011-11-30 14:49:33 -08001241 }
Ian Rogers1ff3c982014-08-12 02:30:58 -07001242 JDWP::JdwpTag element_tag = BasicTagFromClass(a->GetClass()->GetComponentType());
1243 expandBufAdd1(pReply, element_tag);
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -08001244 expandBufAdd4BE(pReply, count);
1245
Ian Rogers1ff3c982014-08-12 02:30:58 -07001246 if (IsPrimitiveTag(element_tag)) {
1247 size_t width = GetTagWidth(element_tag);
Elliott Hughes24437992011-11-30 14:49:33 -08001248 uint8_t* dst = expandBufAddSpace(pReply, count * width);
1249 if (width == 8) {
Ian Rogersef7d42f2014-01-06 12:55:46 -08001250 const uint64_t* src8 = reinterpret_cast<uint64_t*>(a->GetRawData(sizeof(uint64_t), 0));
Elliott Hughes24437992011-11-30 14:49:33 -08001251 for (int i = 0; i < count; ++i) JDWP::Write8BE(&dst, src8[offset + i]);
1252 } else if (width == 4) {
Ian Rogersef7d42f2014-01-06 12:55:46 -08001253 const uint32_t* src4 = reinterpret_cast<uint32_t*>(a->GetRawData(sizeof(uint32_t), 0));
Elliott Hughes24437992011-11-30 14:49:33 -08001254 for (int i = 0; i < count; ++i) JDWP::Write4BE(&dst, src4[offset + i]);
1255 } else if (width == 2) {
Ian Rogersef7d42f2014-01-06 12:55:46 -08001256 const uint16_t* src2 = reinterpret_cast<uint16_t*>(a->GetRawData(sizeof(uint16_t), 0));
Elliott Hughes24437992011-11-30 14:49:33 -08001257 for (int i = 0; i < count; ++i) JDWP::Write2BE(&dst, src2[offset + i]);
1258 } else {
Ian Rogersef7d42f2014-01-06 12:55:46 -08001259 const uint8_t* src = reinterpret_cast<uint8_t*>(a->GetRawData(sizeof(uint8_t), 0));
Elliott Hughes24437992011-11-30 14:49:33 -08001260 memcpy(dst, &src[offset * width], count * width);
1261 }
1262 } else {
Ian Rogers98379392014-02-24 16:53:16 -08001263 ScopedObjectAccessUnchecked soa(Thread::Current());
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001264 mirror::ObjectArray<mirror::Object>* oa = a->AsObjectArray<mirror::Object>();
Elliott Hughes24437992011-11-30 14:49:33 -08001265 for (int i = 0; i < count; ++i) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001266 mirror::Object* element = oa->Get(offset + i);
Ian Rogers98379392014-02-24 16:53:16 -08001267 JDWP::JdwpTag specific_tag = (element != nullptr) ? TagFromObject(soa, element)
Ian Rogers1ff3c982014-08-12 02:30:58 -07001268 : element_tag;
Elliott Hughes24437992011-11-30 14:49:33 -08001269 expandBufAdd1(pReply, specific_tag);
1270 expandBufAddObjectId(pReply, gRegistry->Add(element));
1271 }
1272 }
1273
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -08001274 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001275}
1276
Ian Rogersef7d42f2014-01-06 12:55:46 -08001277template <typename T>
Ian Rogersc0542af2014-09-03 16:16:56 -07001278static void CopyArrayData(mirror::Array* a, JDWP::Request* src, int offset, int count)
Ian Rogersef7d42f2014-01-06 12:55:46 -08001279 NO_THREAD_SAFETY_ANALYSIS {
1280 // TODO: fix when annotalysis correctly handles non-member functions.
Elliott Hughes4b9702c2013-02-20 18:13:24 -08001281 DCHECK(a->GetClass()->IsPrimitiveArray());
1282
Ian Rogersef7d42f2014-01-06 12:55:46 -08001283 T* dst = reinterpret_cast<T*>(a->GetRawData(sizeof(T), offset));
Elliott Hughes4b9702c2013-02-20 18:13:24 -08001284 for (int i = 0; i < count; ++i) {
Ian Rogersc0542af2014-09-03 16:16:56 -07001285 *dst++ = src->ReadValue(sizeof(T));
Elliott Hughes4b9702c2013-02-20 18:13:24 -08001286 }
1287}
1288
Elliott Hughes88d63092013-01-09 09:55:54 -08001289JDWP::JdwpError Dbg::SetArrayElements(JDWP::ObjectId array_id, int offset, int count,
Ian Rogersc0542af2014-09-03 16:16:56 -07001290 JDWP::Request* request) {
1291 JDWP::JdwpError error;
1292 mirror::Array* dst = DecodeNonNullArray(array_id, &error);
1293 if (dst == nullptr) {
1294 return error;
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -08001295 }
Elliott Hughesf03b8f62011-12-02 14:26:25 -08001296
Elliott Hughes4b9702c2013-02-20 18:13:24 -08001297 if (offset < 0 || count < 0 || offset > dst->GetLength() || dst->GetLength() - offset < count) {
Elliott Hughesf03b8f62011-12-02 14:26:25 -08001298 LOG(WARNING) << __FUNCTION__ << " access out of bounds: offset=" << offset << "; count=" << count;
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -08001299 return JDWP::ERR_INVALID_LENGTH;
Elliott Hughesf03b8f62011-12-02 14:26:25 -08001300 }
Ian Rogers1ff3c982014-08-12 02:30:58 -07001301 JDWP::JdwpTag element_tag = BasicTagFromClass(dst->GetClass()->GetComponentType());
Elliott Hughesf03b8f62011-12-02 14:26:25 -08001302
Ian Rogers1ff3c982014-08-12 02:30:58 -07001303 if (IsPrimitiveTag(element_tag)) {
1304 size_t width = GetTagWidth(element_tag);
Elliott Hughesf03b8f62011-12-02 14:26:25 -08001305 if (width == 8) {
Elliott Hughes4b9702c2013-02-20 18:13:24 -08001306 CopyArrayData<uint64_t>(dst, request, offset, count);
Elliott Hughesf03b8f62011-12-02 14:26:25 -08001307 } else if (width == 4) {
Elliott Hughes4b9702c2013-02-20 18:13:24 -08001308 CopyArrayData<uint32_t>(dst, request, offset, count);
Elliott Hughesf03b8f62011-12-02 14:26:25 -08001309 } else if (width == 2) {
Elliott Hughes4b9702c2013-02-20 18:13:24 -08001310 CopyArrayData<uint16_t>(dst, request, offset, count);
Elliott Hughesf03b8f62011-12-02 14:26:25 -08001311 } else {
Elliott Hughes4b9702c2013-02-20 18:13:24 -08001312 CopyArrayData<uint8_t>(dst, request, offset, count);
Elliott Hughesf03b8f62011-12-02 14:26:25 -08001313 }
1314 } else {
Elliott Hughes4b9702c2013-02-20 18:13:24 -08001315 mirror::ObjectArray<mirror::Object>* oa = dst->AsObjectArray<mirror::Object>();
Elliott Hughesf03b8f62011-12-02 14:26:25 -08001316 for (int i = 0; i < count; ++i) {
Ian Rogersc0542af2014-09-03 16:16:56 -07001317 JDWP::ObjectId id = request->ReadObjectId();
Ian Rogersc0542af2014-09-03 16:16:56 -07001318 mirror::Object* o = gRegistry->Get<mirror::Object*>(id, &error);
1319 if (error != JDWP::ERR_NONE) {
1320 return error;
Elliott Hughes436e3722012-02-17 20:01:47 -08001321 }
Sebastien Hertzd2fe10a2014-01-15 10:20:56 +01001322 oa->Set<false>(offset + i, o);
Elliott Hughesf03b8f62011-12-02 14:26:25 -08001323 }
1324 }
1325
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -08001326 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001327}
1328
Sebastien Hertz2c3e77a2015-04-02 16:26:48 +02001329JDWP::JdwpError Dbg::CreateString(const std::string& str, JDWP::ObjectId* new_string_id) {
1330 Thread* self = Thread::Current();
1331 mirror::String* new_string = mirror::String::AllocFromModifiedUtf8(self, str.c_str());
1332 if (new_string == nullptr) {
1333 DCHECK(self->IsExceptionPending());
1334 self->ClearException();
1335 LOG(ERROR) << "Could not allocate string";
1336 *new_string_id = 0;
1337 return JDWP::ERR_OUT_OF_MEMORY;
1338 }
1339 *new_string_id = gRegistry->Add(new_string);
1340 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001341}
1342
Sebastien Hertz2c3e77a2015-04-02 16:26:48 +02001343JDWP::JdwpError Dbg::CreateObject(JDWP::RefTypeId class_id, JDWP::ObjectId* new_object_id) {
Ian Rogersc0542af2014-09-03 16:16:56 -07001344 JDWP::JdwpError error;
1345 mirror::Class* c = DecodeClass(class_id, &error);
1346 if (c == nullptr) {
Sebastien Hertz2c3e77a2015-04-02 16:26:48 +02001347 *new_object_id = 0;
Ian Rogersc0542af2014-09-03 16:16:56 -07001348 return error;
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -08001349 }
Sebastien Hertz2c3e77a2015-04-02 16:26:48 +02001350 Thread* self = Thread::Current();
1351 mirror::Object* new_object = c->AllocObject(self);
1352 if (new_object == nullptr) {
1353 DCHECK(self->IsExceptionPending());
1354 self->ClearException();
1355 LOG(ERROR) << "Could not allocate object of type " << PrettyDescriptor(c);
1356 *new_object_id = 0;
1357 return JDWP::ERR_OUT_OF_MEMORY;
1358 }
1359 *new_object_id = gRegistry->Add(new_object);
Elliott Hughes436e3722012-02-17 20:01:47 -08001360 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001361}
1362
Elliott Hughesbf13d362011-12-08 15:51:37 -08001363/*
1364 * Used by Eclipse's "Display" view to evaluate "new byte[5]" to get "(byte[]) [0, 0, 0, 0, 0]".
1365 */
Elliott Hughes88d63092013-01-09 09:55:54 -08001366JDWP::JdwpError Dbg::CreateArrayObject(JDWP::RefTypeId array_class_id, uint32_t length,
Sebastien Hertz2c3e77a2015-04-02 16:26:48 +02001367 JDWP::ObjectId* new_array_id) {
Ian Rogersc0542af2014-09-03 16:16:56 -07001368 JDWP::JdwpError error;
1369 mirror::Class* c = DecodeClass(array_class_id, &error);
1370 if (c == nullptr) {
Sebastien Hertz2c3e77a2015-04-02 16:26:48 +02001371 *new_array_id = 0;
Ian Rogersc0542af2014-09-03 16:16:56 -07001372 return error;
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -08001373 }
Sebastien Hertz2c3e77a2015-04-02 16:26:48 +02001374 Thread* self = Thread::Current();
1375 gc::Heap* heap = Runtime::Current()->GetHeap();
1376 mirror::Array* new_array = mirror::Array::Alloc<true>(self, c, length,
1377 c->GetComponentSizeShift(),
1378 heap->GetCurrentAllocator());
1379 if (new_array == nullptr) {
1380 DCHECK(self->IsExceptionPending());
1381 self->ClearException();
1382 LOG(ERROR) << "Could not allocate array of type " << PrettyDescriptor(c);
1383 *new_array_id = 0;
1384 return JDWP::ERR_OUT_OF_MEMORY;
1385 }
1386 *new_array_id = gRegistry->Add(new_array);
Elliott Hughes436e3722012-02-17 20:01:47 -08001387 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001388}
1389
Mathieu Chartierc7853442015-03-27 14:35:38 -07001390JDWP::FieldId Dbg::ToFieldId(const ArtField* f) {
Elliott Hughes03181a82011-11-17 17:22:21 -08001391 return static_cast<JDWP::FieldId>(reinterpret_cast<uintptr_t>(f));
Elliott Hughes03181a82011-11-17 17:22:21 -08001392}
1393
Mathieu Chartier3d21bdf2015-04-22 13:56:20 -07001394static JDWP::MethodId ToMethodId(const ArtMethod* m)
Ian Rogersb726dcb2012-09-05 08:57:23 -07001395 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Elliott Hughes03181a82011-11-17 17:22:21 -08001396 return static_cast<JDWP::MethodId>(reinterpret_cast<uintptr_t>(m));
Elliott Hughes03181a82011-11-17 17:22:21 -08001397}
1398
Mathieu Chartierc7853442015-03-27 14:35:38 -07001399static ArtField* FromFieldId(JDWP::FieldId fid)
Ian Rogersb726dcb2012-09-05 08:57:23 -07001400 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Mathieu Chartierc7853442015-03-27 14:35:38 -07001401 return reinterpret_cast<ArtField*>(static_cast<uintptr_t>(fid));
Elliott Hughesaed4be92011-12-02 16:16:23 -08001402}
1403
Mathieu Chartier3d21bdf2015-04-22 13:56:20 -07001404static ArtMethod* FromMethodId(JDWP::MethodId mid)
Ian Rogersb726dcb2012-09-05 08:57:23 -07001405 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Mathieu Chartier3d21bdf2015-04-22 13:56:20 -07001406 return reinterpret_cast<ArtMethod*>(static_cast<uintptr_t>(mid));
Elliott Hughes03181a82011-11-17 17:22:21 -08001407}
1408
Sebastien Hertz6995c602014-09-09 12:10:13 +02001409bool Dbg::MatchThread(JDWP::ObjectId expected_thread_id, Thread* event_thread) {
1410 CHECK(event_thread != nullptr);
1411 JDWP::JdwpError error;
Mathieu Chartier3d21bdf2015-04-22 13:56:20 -07001412 mirror::Object* expected_thread_peer = gRegistry->Get<mirror::Object*>(
1413 expected_thread_id, &error);
Sebastien Hertz6995c602014-09-09 12:10:13 +02001414 return expected_thread_peer == event_thread->GetPeer();
1415}
1416
1417bool Dbg::MatchLocation(const JDWP::JdwpLocation& expected_location,
1418 const JDWP::EventLocation& event_location) {
1419 if (expected_location.dex_pc != event_location.dex_pc) {
1420 return false;
1421 }
Mathieu Chartier3d21bdf2015-04-22 13:56:20 -07001422 ArtMethod* m = FromMethodId(expected_location.method_id);
Sebastien Hertz6995c602014-09-09 12:10:13 +02001423 return m == event_location.method;
1424}
1425
1426bool Dbg::MatchType(mirror::Class* event_class, JDWP::RefTypeId class_id) {
Sebastien Hertza9aa0ff2014-09-19 12:07:51 +02001427 if (event_class == nullptr) {
1428 return false;
1429 }
Sebastien Hertz6995c602014-09-09 12:10:13 +02001430 JDWP::JdwpError error;
1431 mirror::Class* expected_class = DecodeClass(class_id, &error);
1432 CHECK(expected_class != nullptr);
1433 return expected_class->IsAssignableFrom(event_class);
1434}
1435
1436bool Dbg::MatchField(JDWP::RefTypeId expected_type_id, JDWP::FieldId expected_field_id,
Mathieu Chartierc7853442015-03-27 14:35:38 -07001437 ArtField* event_field) {
1438 ArtField* expected_field = FromFieldId(expected_field_id);
Sebastien Hertz6995c602014-09-09 12:10:13 +02001439 if (expected_field != event_field) {
1440 return false;
1441 }
1442 return Dbg::MatchType(event_field->GetDeclaringClass(), expected_type_id);
1443}
1444
1445bool Dbg::MatchInstance(JDWP::ObjectId expected_instance_id, mirror::Object* event_instance) {
1446 JDWP::JdwpError error;
1447 mirror::Object* modifier_instance = gRegistry->Get<mirror::Object*>(expected_instance_id, &error);
1448 return modifier_instance == event_instance;
1449}
1450
Mathieu Chartier3d21bdf2015-04-22 13:56:20 -07001451void Dbg::SetJdwpLocation(JDWP::JdwpLocation* location, ArtMethod* m, uint32_t dex_pc)
Sebastien Hertz69206392015-04-07 15:54:25 +02001452 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_)
1453 LOCKS_EXCLUDED(Locks::thread_list_lock_,
1454 Locks::thread_suspend_count_lock_) {
Ian Rogersc0542af2014-09-03 16:16:56 -07001455 if (m == nullptr) {
Sebastien Hertza9aa0ff2014-09-19 12:07:51 +02001456 memset(location, 0, sizeof(*location));
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08001457 } else {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001458 mirror::Class* c = m->GetDeclaringClass();
Ian Rogersc0542af2014-09-03 16:16:56 -07001459 location->type_tag = GetTypeTag(c);
1460 location->class_id = gRegistry->AddRefType(c);
1461 location->method_id = ToMethodId(m);
1462 location->dex_pc = (m->IsNative() || m->IsProxyMethod()) ? static_cast<uint64_t>(-1) : dex_pc;
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08001463 }
Elliott Hughesd07986f2011-12-06 18:27:45 -08001464}
1465
Ian Rogersc0542af2014-09-03 16:16:56 -07001466std::string Dbg::GetMethodName(JDWP::MethodId method_id) {
Mathieu Chartier3d21bdf2015-04-22 13:56:20 -07001467 ArtMethod* m = FromMethodId(method_id);
Sebastien Hertza9aa0ff2014-09-19 12:07:51 +02001468 if (m == nullptr) {
Mathieu Chartier2cebb242015-04-21 16:50:40 -07001469 return "null";
Sebastien Hertza9aa0ff2014-09-19 12:07:51 +02001470 }
Mathieu Chartier3d21bdf2015-04-22 13:56:20 -07001471 return m->GetInterfaceMethodIfProxy(sizeof(void*))->GetName();
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001472}
1473
Ian Rogersc0542af2014-09-03 16:16:56 -07001474std::string Dbg::GetFieldName(JDWP::FieldId field_id) {
Mathieu Chartierc7853442015-03-27 14:35:38 -07001475 ArtField* f = FromFieldId(field_id);
Sebastien Hertza9aa0ff2014-09-19 12:07:51 +02001476 if (f == nullptr) {
Mathieu Chartier2cebb242015-04-21 16:50:40 -07001477 return "null";
Sebastien Hertza9aa0ff2014-09-19 12:07:51 +02001478 }
1479 return f->GetName();
Elliott Hughesa96836a2013-01-17 12:27:49 -08001480}
1481
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001482/*
1483 * Augment the access flags for synthetic methods and fields by setting
1484 * the (as described by the spec) "0xf0000000 bit". Also, strip out any
1485 * flags not specified by the Java programming language.
1486 */
1487static uint32_t MangleAccessFlags(uint32_t accessFlags) {
1488 accessFlags &= kAccJavaFlagsMask;
1489 if ((accessFlags & kAccSynthetic) != 0) {
1490 accessFlags |= 0xf0000000;
1491 }
1492 return accessFlags;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001493}
1494
Elliott Hughesdbb40792011-11-18 17:05:22 -08001495/*
Jeff Haob7cefc72013-11-14 14:51:09 -08001496 * Circularly shifts registers so that arguments come first. Debuggers
1497 * expect slots to begin with arguments, but dex code places them at
1498 * the end.
Elliott Hughesdbb40792011-11-18 17:05:22 -08001499 */
Mathieu Chartier3d21bdf2015-04-22 13:56:20 -07001500static uint16_t MangleSlot(uint16_t slot, ArtMethod* m)
Jeff Haob7cefc72013-11-14 14:51:09 -08001501 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07001502 const DexFile::CodeItem* code_item = m->GetCodeItem();
Sebastien Hertzcb19ebf2014-03-11 15:26:35 +01001503 if (code_item == nullptr) {
1504 // We should not get here for a method without code (native, proxy or abstract). Log it and
1505 // return the slot as is since all registers are arguments.
1506 LOG(WARNING) << "Trying to mangle slot for method without code " << PrettyMethod(m);
1507 return slot;
1508 }
Jeff Haob7cefc72013-11-14 14:51:09 -08001509 uint16_t ins_size = code_item->ins_size_;
1510 uint16_t locals_size = code_item->registers_size_ - ins_size;
1511 if (slot >= locals_size) {
1512 return slot - locals_size;
1513 } else {
1514 return slot + ins_size;
Elliott Hughesdbb40792011-11-18 17:05:22 -08001515 }
Elliott Hughesdbb40792011-11-18 17:05:22 -08001516}
1517
Jeff Haob7cefc72013-11-14 14:51:09 -08001518/*
1519 * Circularly shifts registers so that arguments come last. Reverts
1520 * slots to dex style argument placement.
1521 */
Mathieu Chartier3d21bdf2015-04-22 13:56:20 -07001522static uint16_t DemangleSlot(uint16_t slot, ArtMethod* m, JDWP::JdwpError* error)
Ian Rogersb726dcb2012-09-05 08:57:23 -07001523 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07001524 const DexFile::CodeItem* code_item = m->GetCodeItem();
Sebastien Hertzcb19ebf2014-03-11 15:26:35 +01001525 if (code_item == nullptr) {
1526 // We should not get here for a method without code (native, proxy or abstract). Log it and
1527 // return the slot as is since all registers are arguments.
1528 LOG(WARNING) << "Trying to demangle slot for method without code " << PrettyMethod(m);
Mathieu Chartier3d21bdf2015-04-22 13:56:20 -07001529 uint16_t vreg_count = ArtMethod::NumArgRegisters(m->GetShorty());
Sebastien Hertzabbabc82015-03-26 08:47:47 +01001530 if (slot < vreg_count) {
1531 *error = JDWP::ERR_NONE;
1532 return slot;
1533 }
Jeff Haob7cefc72013-11-14 14:51:09 -08001534 } else {
Sebastien Hertzabbabc82015-03-26 08:47:47 +01001535 if (slot < code_item->registers_size_) {
1536 uint16_t ins_size = code_item->ins_size_;
1537 uint16_t locals_size = code_item->registers_size_ - ins_size;
1538 *error = JDWP::ERR_NONE;
1539 return (slot < ins_size) ? slot + locals_size : slot - ins_size;
1540 }
Elliott Hughesdbb40792011-11-18 17:05:22 -08001541 }
Sebastien Hertzabbabc82015-03-26 08:47:47 +01001542
1543 // Slot is invalid in the method.
1544 LOG(ERROR) << "Invalid local slot " << slot << " for method " << PrettyMethod(m);
1545 *error = JDWP::ERR_INVALID_SLOT;
1546 return DexFile::kDexNoIndex16;
Elliott Hughesdbb40792011-11-18 17:05:22 -08001547}
1548
Elliott Hughes88d63092013-01-09 09:55:54 -08001549JDWP::JdwpError Dbg::OutputDeclaredFields(JDWP::RefTypeId class_id, bool with_generic, JDWP::ExpandBuf* pReply) {
Ian Rogersc0542af2014-09-03 16:16:56 -07001550 JDWP::JdwpError error;
1551 mirror::Class* c = DecodeClass(class_id, &error);
1552 if (c == nullptr) {
1553 return error;
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -08001554 }
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001555
1556 size_t instance_field_count = c->NumInstanceFields();
1557 size_t static_field_count = c->NumStaticFields();
1558
1559 expandBufAdd4BE(pReply, instance_field_count + static_field_count);
1560
1561 for (size_t i = 0; i < instance_field_count + static_field_count; ++i) {
Mathieu Chartierc7853442015-03-27 14:35:38 -07001562 ArtField* f = (i < instance_field_count) ? c->GetInstanceField(i) : c->GetStaticField(i - instance_field_count);
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001563 expandBufAddFieldId(pReply, ToFieldId(f));
Mathieu Chartier61c5ebc2014-06-05 17:42:53 -07001564 expandBufAddUtf8String(pReply, f->GetName());
1565 expandBufAddUtf8String(pReply, f->GetTypeDescriptor());
Elliott Hughesc5b734a2011-12-01 17:20:58 -08001566 if (with_generic) {
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001567 static const char genericSignature[1] = "";
1568 expandBufAddUtf8String(pReply, genericSignature);
1569 }
1570 expandBufAdd4BE(pReply, MangleAccessFlags(f->GetAccessFlags()));
1571 }
Elliott Hughes436e3722012-02-17 20:01:47 -08001572 return JDWP::ERR_NONE;
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001573}
1574
Elliott Hughes88d63092013-01-09 09:55:54 -08001575JDWP::JdwpError Dbg::OutputDeclaredMethods(JDWP::RefTypeId class_id, bool with_generic,
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001576 JDWP::ExpandBuf* pReply) {
Ian Rogersc0542af2014-09-03 16:16:56 -07001577 JDWP::JdwpError error;
1578 mirror::Class* c = DecodeClass(class_id, &error);
1579 if (c == nullptr) {
1580 return error;
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -08001581 }
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001582
1583 size_t direct_method_count = c->NumDirectMethods();
1584 size_t virtual_method_count = c->NumVirtualMethods();
1585
1586 expandBufAdd4BE(pReply, direct_method_count + virtual_method_count);
1587
Mathieu Chartier3d21bdf2015-04-22 13:56:20 -07001588 auto* cl = Runtime::Current()->GetClassLinker();
1589 auto ptr_size = cl->GetImagePointerSize();
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001590 for (size_t i = 0; i < direct_method_count + virtual_method_count; ++i) {
Mathieu Chartier3d21bdf2015-04-22 13:56:20 -07001591 ArtMethod* m = i < direct_method_count ?
1592 c->GetDirectMethod(i, ptr_size) : c->GetVirtualMethod(i - direct_method_count, ptr_size);
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001593 expandBufAddMethodId(pReply, ToMethodId(m));
Mathieu Chartier3d21bdf2015-04-22 13:56:20 -07001594 expandBufAddUtf8String(pReply, m->GetInterfaceMethodIfProxy(sizeof(void*))->GetName());
1595 expandBufAddUtf8String(pReply,
1596 m->GetInterfaceMethodIfProxy(sizeof(void*))->GetSignature().ToString());
Elliott Hughesc5b734a2011-12-01 17:20:58 -08001597 if (with_generic) {
Mathieu Chartier3d21bdf2015-04-22 13:56:20 -07001598 const char* generic_signature = "";
1599 expandBufAddUtf8String(pReply, generic_signature);
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001600 }
1601 expandBufAdd4BE(pReply, MangleAccessFlags(m->GetAccessFlags()));
1602 }
Elliott Hughes436e3722012-02-17 20:01:47 -08001603 return JDWP::ERR_NONE;
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001604}
1605
Elliott Hughes88d63092013-01-09 09:55:54 -08001606JDWP::JdwpError Dbg::OutputDeclaredInterfaces(JDWP::RefTypeId class_id, JDWP::ExpandBuf* pReply) {
Ian Rogersc0542af2014-09-03 16:16:56 -07001607 JDWP::JdwpError error;
Mathieu Chartierf8322842014-05-16 10:59:25 -07001608 Thread* self = Thread::Current();
1609 StackHandleScope<1> hs(self);
Ian Rogersc0542af2014-09-03 16:16:56 -07001610 Handle<mirror::Class> c(hs.NewHandle(DecodeClass(class_id, &error)));
Mathieu Chartierf8322842014-05-16 10:59:25 -07001611 if (c.Get() == nullptr) {
Ian Rogersc0542af2014-09-03 16:16:56 -07001612 return error;
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -08001613 }
Mathieu Chartierf8322842014-05-16 10:59:25 -07001614 size_t interface_count = c->NumDirectInterfaces();
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001615 expandBufAdd4BE(pReply, interface_count);
1616 for (size_t i = 0; i < interface_count; ++i) {
Mathieu Chartierf8322842014-05-16 10:59:25 -07001617 expandBufAddRefTypeId(pReply,
1618 gRegistry->AddRefType(mirror::Class::GetDirectInterface(self, c, i)));
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001619 }
Elliott Hughes436e3722012-02-17 20:01:47 -08001620 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001621}
1622
Ian Rogersc0542af2014-09-03 16:16:56 -07001623void Dbg::OutputLineTable(JDWP::RefTypeId, JDWP::MethodId method_id, JDWP::ExpandBuf* pReply) {
Elliott Hughes03181a82011-11-17 17:22:21 -08001624 struct DebugCallbackContext {
1625 int numItems;
1626 JDWP::ExpandBuf* pReply;
1627
Elliott Hughes2435a572012-02-17 16:07:41 -08001628 static bool Callback(void* context, uint32_t address, uint32_t line_number) {
Elliott Hughes03181a82011-11-17 17:22:21 -08001629 DebugCallbackContext* pContext = reinterpret_cast<DebugCallbackContext*>(context);
1630 expandBufAdd8BE(pContext->pReply, address);
Elliott Hughes2435a572012-02-17 16:07:41 -08001631 expandBufAdd4BE(pContext->pReply, line_number);
Elliott Hughes03181a82011-11-17 17:22:21 -08001632 pContext->numItems++;
Sebastien Hertzf2910ee2013-10-19 16:39:24 +02001633 return false;
Elliott Hughes03181a82011-11-17 17:22:21 -08001634 }
1635 };
Mathieu Chartier3d21bdf2015-04-22 13:56:20 -07001636 ArtMethod* m = FromMethodId(method_id);
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07001637 const DexFile::CodeItem* code_item = m->GetCodeItem();
Elliott Hughes03181a82011-11-17 17:22:21 -08001638 uint64_t start, end;
Sebastien Hertzcb19ebf2014-03-11 15:26:35 +01001639 if (code_item == nullptr) {
1640 DCHECK(m->IsNative() || m->IsProxyMethod());
Elliott Hughes03181a82011-11-17 17:22:21 -08001641 start = -1;
1642 end = -1;
1643 } else {
1644 start = 0;
jeffhao14f0db92012-12-14 17:50:42 -08001645 // Return the index of the last instruction
Sebastien Hertzcb19ebf2014-03-11 15:26:35 +01001646 end = code_item->insns_size_in_code_units_ - 1;
Elliott Hughes03181a82011-11-17 17:22:21 -08001647 }
1648
1649 expandBufAdd8BE(pReply, start);
1650 expandBufAdd8BE(pReply, end);
1651
1652 // Add numLines later
1653 size_t numLinesOffset = expandBufGetLength(pReply);
1654 expandBufAdd4BE(pReply, 0);
1655
1656 DebugCallbackContext context;
1657 context.numItems = 0;
1658 context.pReply = pReply;
1659
Sebastien Hertzcb19ebf2014-03-11 15:26:35 +01001660 if (code_item != nullptr) {
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07001661 m->GetDexFile()->DecodeDebugInfo(code_item, m->IsStatic(), m->GetDexMethodIndex(),
Ian Rogersc0542af2014-09-03 16:16:56 -07001662 DebugCallbackContext::Callback, nullptr, &context);
Sebastien Hertzcb19ebf2014-03-11 15:26:35 +01001663 }
Elliott Hughes03181a82011-11-17 17:22:21 -08001664
1665 JDWP::Set4BE(expandBufGetBuffer(pReply) + numLinesOffset, context.numItems);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001666}
1667
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07001668void Dbg::OutputVariableTable(JDWP::RefTypeId, JDWP::MethodId method_id, bool with_generic,
1669 JDWP::ExpandBuf* pReply) {
Elliott Hughesdbb40792011-11-18 17:05:22 -08001670 struct DebugCallbackContext {
Mathieu Chartier3d21bdf2015-04-22 13:56:20 -07001671 ArtMethod* method;
Elliott Hughesdbb40792011-11-18 17:05:22 -08001672 JDWP::ExpandBuf* pReply;
Elliott Hughesc5b734a2011-12-01 17:20:58 -08001673 size_t variable_count;
1674 bool with_generic;
Elliott Hughesdbb40792011-11-18 17:05:22 -08001675
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07001676 static void Callback(void* context, uint16_t slot, uint32_t startAddress, uint32_t endAddress,
1677 const char* name, const char* descriptor, const char* signature)
Jeff Haob7cefc72013-11-14 14:51:09 -08001678 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Elliott Hughesdbb40792011-11-18 17:05:22 -08001679 DebugCallbackContext* pContext = reinterpret_cast<DebugCallbackContext*>(context);
1680
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07001681 VLOG(jdwp) << StringPrintf(" %2zd: %d(%d) '%s' '%s' '%s' actual slot=%d mangled slot=%d",
1682 pContext->variable_count, startAddress, endAddress - startAddress,
1683 name, descriptor, signature, slot,
1684 MangleSlot(slot, pContext->method));
Elliott Hughesdbb40792011-11-18 17:05:22 -08001685
Jeff Haob7cefc72013-11-14 14:51:09 -08001686 slot = MangleSlot(slot, pContext->method);
Elliott Hughes68fdbd02011-11-29 19:22:47 -08001687
Elliott Hughesdbb40792011-11-18 17:05:22 -08001688 expandBufAdd8BE(pContext->pReply, startAddress);
1689 expandBufAddUtf8String(pContext->pReply, name);
1690 expandBufAddUtf8String(pContext->pReply, descriptor);
Elliott Hughesc5b734a2011-12-01 17:20:58 -08001691 if (pContext->with_generic) {
Elliott Hughesdbb40792011-11-18 17:05:22 -08001692 expandBufAddUtf8String(pContext->pReply, signature);
1693 }
1694 expandBufAdd4BE(pContext->pReply, endAddress - startAddress);
1695 expandBufAdd4BE(pContext->pReply, slot);
1696
Elliott Hughesc5b734a2011-12-01 17:20:58 -08001697 ++pContext->variable_count;
Elliott Hughesdbb40792011-11-18 17:05:22 -08001698 }
1699 };
Mathieu Chartier3d21bdf2015-04-22 13:56:20 -07001700 ArtMethod* m = FromMethodId(method_id);
Elliott Hughesdbb40792011-11-18 17:05:22 -08001701
Elliott Hughesc5b734a2011-12-01 17:20:58 -08001702 // arg_count considers doubles and longs to take 2 units.
1703 // variable_count considers everything to take 1 unit.
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07001704 std::string shorty(m->GetShorty());
Mathieu Chartier3d21bdf2015-04-22 13:56:20 -07001705 expandBufAdd4BE(pReply, ArtMethod::NumArgRegisters(shorty));
Elliott Hughesdbb40792011-11-18 17:05:22 -08001706
Elliott Hughesc5b734a2011-12-01 17:20:58 -08001707 // We don't know the total number of variables yet, so leave a blank and update it later.
1708 size_t variable_count_offset = expandBufGetLength(pReply);
Elliott Hughesdbb40792011-11-18 17:05:22 -08001709 expandBufAdd4BE(pReply, 0);
1710
1711 DebugCallbackContext context;
Jeff Haob7cefc72013-11-14 14:51:09 -08001712 context.method = m;
Elliott Hughesdbb40792011-11-18 17:05:22 -08001713 context.pReply = pReply;
Elliott Hughesc5b734a2011-12-01 17:20:58 -08001714 context.variable_count = 0;
1715 context.with_generic = with_generic;
Elliott Hughesdbb40792011-11-18 17:05:22 -08001716
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07001717 const DexFile::CodeItem* code_item = m->GetCodeItem();
Sebastien Hertzcb19ebf2014-03-11 15:26:35 +01001718 if (code_item != nullptr) {
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07001719 m->GetDexFile()->DecodeDebugInfo(
Ian Rogersc0542af2014-09-03 16:16:56 -07001720 code_item, m->IsStatic(), m->GetDexMethodIndex(), nullptr, DebugCallbackContext::Callback,
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07001721 &context);
Sebastien Hertzcb19ebf2014-03-11 15:26:35 +01001722 }
Elliott Hughesdbb40792011-11-18 17:05:22 -08001723
Elliott Hughesc5b734a2011-12-01 17:20:58 -08001724 JDWP::Set4BE(expandBufGetBuffer(pReply) + variable_count_offset, context.variable_count);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001725}
1726
Jeff Hao579b0242013-11-18 13:16:49 -08001727void Dbg::OutputMethodReturnValue(JDWP::MethodId method_id, const JValue* return_value,
1728 JDWP::ExpandBuf* pReply) {
Mathieu Chartier3d21bdf2015-04-22 13:56:20 -07001729 ArtMethod* m = FromMethodId(method_id);
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07001730 JDWP::JdwpTag tag = BasicTagFromDescriptor(m->GetShorty());
Jeff Hao579b0242013-11-18 13:16:49 -08001731 OutputJValue(tag, return_value, pReply);
1732}
1733
Sebastien Hertz3f52eaf2014-04-04 17:50:18 +02001734void Dbg::OutputFieldValue(JDWP::FieldId field_id, const JValue* field_value,
1735 JDWP::ExpandBuf* pReply) {
Mathieu Chartierc7853442015-03-27 14:35:38 -07001736 ArtField* f = FromFieldId(field_id);
Mathieu Chartier61c5ebc2014-06-05 17:42:53 -07001737 JDWP::JdwpTag tag = BasicTagFromDescriptor(f->GetTypeDescriptor());
Sebastien Hertz3f52eaf2014-04-04 17:50:18 +02001738 OutputJValue(tag, field_value, pReply);
1739}
1740
Elliott Hughes9777ba22013-01-17 09:04:19 -08001741JDWP::JdwpError Dbg::GetBytecodes(JDWP::RefTypeId, JDWP::MethodId method_id,
Ian Rogersc0542af2014-09-03 16:16:56 -07001742 std::vector<uint8_t>* bytecodes) {
Mathieu Chartier3d21bdf2015-04-22 13:56:20 -07001743 ArtMethod* m = FromMethodId(method_id);
Ian Rogersc0542af2014-09-03 16:16:56 -07001744 if (m == nullptr) {
Elliott Hughes9777ba22013-01-17 09:04:19 -08001745 return JDWP::ERR_INVALID_METHODID;
1746 }
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07001747 const DexFile::CodeItem* code_item = m->GetCodeItem();
Elliott Hughes9777ba22013-01-17 09:04:19 -08001748 size_t byte_count = code_item->insns_size_in_code_units_ * 2;
1749 const uint8_t* begin = reinterpret_cast<const uint8_t*>(code_item->insns_);
1750 const uint8_t* end = begin + byte_count;
1751 for (const uint8_t* p = begin; p != end; ++p) {
Ian Rogersc0542af2014-09-03 16:16:56 -07001752 bytecodes->push_back(*p);
Elliott Hughes9777ba22013-01-17 09:04:19 -08001753 }
1754 return JDWP::ERR_NONE;
1755}
1756
Elliott Hughes88d63092013-01-09 09:55:54 -08001757JDWP::JdwpTag Dbg::GetFieldBasicTag(JDWP::FieldId field_id) {
Mathieu Chartier61c5ebc2014-06-05 17:42:53 -07001758 return BasicTagFromDescriptor(FromFieldId(field_id)->GetTypeDescriptor());
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001759}
1760
Elliott Hughes88d63092013-01-09 09:55:54 -08001761JDWP::JdwpTag Dbg::GetStaticFieldBasicTag(JDWP::FieldId field_id) {
Mathieu Chartier61c5ebc2014-06-05 17:42:53 -07001762 return BasicTagFromDescriptor(FromFieldId(field_id)->GetTypeDescriptor());
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001763}
1764
Sebastien Hertz49983742015-06-11 18:42:58 +02001765static JValue GetArtFieldValue(ArtField* f, mirror::Object* o)
1766 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
1767 Primitive::Type fieldType = f->GetTypeAsPrimitiveType();
1768 JValue field_value;
1769 switch (fieldType) {
1770 case Primitive::kPrimBoolean:
1771 field_value.SetZ(f->GetBoolean(o));
1772 return field_value;
1773
1774 case Primitive::kPrimByte:
1775 field_value.SetB(f->GetByte(o));
1776 return field_value;
1777
1778 case Primitive::kPrimChar:
1779 field_value.SetC(f->GetChar(o));
1780 return field_value;
1781
1782 case Primitive::kPrimShort:
1783 field_value.SetS(f->GetShort(o));
1784 return field_value;
1785
1786 case Primitive::kPrimInt:
1787 case Primitive::kPrimFloat:
1788 // Int and Float must be treated as 32-bit values in JDWP.
1789 field_value.SetI(f->GetInt(o));
1790 return field_value;
1791
1792 case Primitive::kPrimLong:
1793 case Primitive::kPrimDouble:
1794 // Long and Double must be treated as 64-bit values in JDWP.
1795 field_value.SetJ(f->GetLong(o));
1796 return field_value;
1797
1798 case Primitive::kPrimNot:
1799 field_value.SetL(f->GetObject(o));
1800 return field_value;
1801
1802 case Primitive::kPrimVoid:
1803 LOG(FATAL) << "Attempt to read from field of type 'void'";
1804 UNREACHABLE();
1805 }
1806 LOG(FATAL) << "Attempt to read from field of unknown type";
1807 UNREACHABLE();
1808}
1809
Elliott Hughes88d63092013-01-09 09:55:54 -08001810static JDWP::JdwpError GetFieldValueImpl(JDWP::RefTypeId ref_type_id, JDWP::ObjectId object_id,
1811 JDWP::FieldId field_id, JDWP::ExpandBuf* pReply,
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001812 bool is_static)
Ian Rogersb726dcb2012-09-05 08:57:23 -07001813 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Ian Rogersc0542af2014-09-03 16:16:56 -07001814 JDWP::JdwpError error;
1815 mirror::Class* c = DecodeClass(ref_type_id, &error);
1816 if (ref_type_id != 0 && c == nullptr) {
1817 return error;
Elliott Hughes0cf74332012-02-23 23:14:00 -08001818 }
1819
Sebastien Hertz6995c602014-09-09 12:10:13 +02001820 mirror::Object* o = Dbg::GetObjectRegistry()->Get<mirror::Object*>(object_id, &error);
Ian Rogersc0542af2014-09-03 16:16:56 -07001821 if ((!is_static && o == nullptr) || error != JDWP::ERR_NONE) {
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08001822 return JDWP::ERR_INVALID_OBJECT;
1823 }
Mathieu Chartierc7853442015-03-27 14:35:38 -07001824 ArtField* f = FromFieldId(field_id);
Elliott Hughes0cf74332012-02-23 23:14:00 -08001825
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001826 mirror::Class* receiver_class = c;
Ian Rogersc0542af2014-09-03 16:16:56 -07001827 if (receiver_class == nullptr && o != nullptr) {
Elliott Hughes0cf74332012-02-23 23:14:00 -08001828 receiver_class = o->GetClass();
1829 }
Mathieu Chartier2cebb242015-04-21 16:50:40 -07001830 // TODO: should we give up now if receiver_class is null?
Ian Rogersc0542af2014-09-03 16:16:56 -07001831 if (receiver_class != nullptr && !f->GetDeclaringClass()->IsAssignableFrom(receiver_class)) {
Elliott Hughes0cf74332012-02-23 23:14:00 -08001832 LOG(INFO) << "ERR_INVALID_FIELDID: " << PrettyField(f) << " " << PrettyClass(receiver_class);
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08001833 return JDWP::ERR_INVALID_FIELDID;
1834 }
Elliott Hughesaed4be92011-12-02 16:16:23 -08001835
Elliott Hughes0cf74332012-02-23 23:14:00 -08001836 // The RI only enforces the static/non-static mismatch in one direction.
1837 // TODO: should we change the tests and check both?
1838 if (is_static) {
1839 if (!f->IsStatic()) {
1840 return JDWP::ERR_INVALID_FIELDID;
1841 }
1842 } else {
1843 if (f->IsStatic()) {
Sebastien Hertz49983742015-06-11 18:42:58 +02001844 LOG(WARNING) << "Ignoring non-nullptr receiver for ObjectReference.GetValues"
1845 << " on static field " << PrettyField(f);
Elliott Hughes0cf74332012-02-23 23:14:00 -08001846 }
1847 }
jeffhao0dfbb7e2012-11-28 15:26:03 -08001848 if (f->IsStatic()) {
1849 o = f->GetDeclaringClass();
1850 }
Elliott Hughes0cf74332012-02-23 23:14:00 -08001851
Sebastien Hertz49983742015-06-11 18:42:58 +02001852 JValue field_value(GetArtFieldValue(f, o));
Mathieu Chartier61c5ebc2014-06-05 17:42:53 -07001853 JDWP::JdwpTag tag = BasicTagFromDescriptor(f->GetTypeDescriptor());
Jeff Hao579b0242013-11-18 13:16:49 -08001854 Dbg::OutputJValue(tag, &field_value, pReply);
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08001855 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001856}
1857
Elliott Hughes88d63092013-01-09 09:55:54 -08001858JDWP::JdwpError Dbg::GetFieldValue(JDWP::ObjectId object_id, JDWP::FieldId field_id,
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001859 JDWP::ExpandBuf* pReply) {
Elliott Hughes88d63092013-01-09 09:55:54 -08001860 return GetFieldValueImpl(0, object_id, field_id, pReply, false);
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08001861}
1862
Ian Rogersc0542af2014-09-03 16:16:56 -07001863JDWP::JdwpError Dbg::GetStaticFieldValue(JDWP::RefTypeId ref_type_id, JDWP::FieldId field_id,
1864 JDWP::ExpandBuf* pReply) {
Elliott Hughes88d63092013-01-09 09:55:54 -08001865 return GetFieldValueImpl(ref_type_id, 0, field_id, pReply, true);
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08001866}
1867
Sebastien Hertz49983742015-06-11 18:42:58 +02001868static JDWP::JdwpError SetArtFieldValue(ArtField* f, mirror::Object* o, uint64_t value, int width)
1869 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
1870 Primitive::Type fieldType = f->GetTypeAsPrimitiveType();
1871 // Debugging only happens at runtime so we know we are not running in a transaction.
1872 static constexpr bool kNoTransactionMode = false;
1873 switch (fieldType) {
1874 case Primitive::kPrimBoolean:
1875 CHECK_EQ(width, 1);
1876 f->SetBoolean<kNoTransactionMode>(o, static_cast<uint8_t>(value));
1877 return JDWP::ERR_NONE;
1878
1879 case Primitive::kPrimByte:
1880 CHECK_EQ(width, 1);
1881 f->SetByte<kNoTransactionMode>(o, static_cast<uint8_t>(value));
1882 return JDWP::ERR_NONE;
1883
1884 case Primitive::kPrimChar:
1885 CHECK_EQ(width, 2);
1886 f->SetChar<kNoTransactionMode>(o, static_cast<uint16_t>(value));
1887 return JDWP::ERR_NONE;
1888
1889 case Primitive::kPrimShort:
1890 CHECK_EQ(width, 2);
1891 f->SetShort<kNoTransactionMode>(o, static_cast<int16_t>(value));
1892 return JDWP::ERR_NONE;
1893
1894 case Primitive::kPrimInt:
1895 case Primitive::kPrimFloat:
1896 CHECK_EQ(width, 4);
1897 // Int and Float must be treated as 32-bit values in JDWP.
1898 f->SetInt<kNoTransactionMode>(o, static_cast<int32_t>(value));
1899 return JDWP::ERR_NONE;
1900
1901 case Primitive::kPrimLong:
1902 case Primitive::kPrimDouble:
1903 CHECK_EQ(width, 8);
1904 // Long and Double must be treated as 64-bit values in JDWP.
1905 f->SetLong<kNoTransactionMode>(o, value);
1906 return JDWP::ERR_NONE;
1907
1908 case Primitive::kPrimNot: {
1909 JDWP::JdwpError error;
1910 mirror::Object* v = Dbg::GetObjectRegistry()->Get<mirror::Object*>(value, &error);
1911 if (error != JDWP::ERR_NONE) {
1912 return JDWP::ERR_INVALID_OBJECT;
1913 }
1914 if (v != nullptr) {
1915 mirror::Class* field_type;
1916 {
1917 StackHandleScope<2> hs(Thread::Current());
1918 HandleWrapper<mirror::Object> h_v(hs.NewHandleWrapper(&v));
1919 HandleWrapper<mirror::Object> h_o(hs.NewHandleWrapper(&o));
1920 field_type = f->GetType<true>();
1921 }
1922 if (!field_type->IsAssignableFrom(v->GetClass())) {
1923 return JDWP::ERR_INVALID_OBJECT;
1924 }
1925 }
1926 f->SetObject<kNoTransactionMode>(o, v);
1927 return JDWP::ERR_NONE;
1928 }
1929
1930 case Primitive::kPrimVoid:
1931 LOG(FATAL) << "Attempt to write to field of type 'void'";
1932 UNREACHABLE();
1933 }
1934 LOG(FATAL) << "Attempt to write to field of unknown type";
1935 UNREACHABLE();
1936}
1937
Elliott Hughes88d63092013-01-09 09:55:54 -08001938static JDWP::JdwpError SetFieldValueImpl(JDWP::ObjectId object_id, JDWP::FieldId field_id,
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001939 uint64_t value, int width, bool is_static)
Ian Rogersb726dcb2012-09-05 08:57:23 -07001940 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Ian Rogersc0542af2014-09-03 16:16:56 -07001941 JDWP::JdwpError error;
Sebastien Hertz6995c602014-09-09 12:10:13 +02001942 mirror::Object* o = Dbg::GetObjectRegistry()->Get<mirror::Object*>(object_id, &error);
Ian Rogersc0542af2014-09-03 16:16:56 -07001943 if ((!is_static && o == nullptr) || error != JDWP::ERR_NONE) {
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08001944 return JDWP::ERR_INVALID_OBJECT;
1945 }
Mathieu Chartierc7853442015-03-27 14:35:38 -07001946 ArtField* f = FromFieldId(field_id);
Elliott Hughes0cf74332012-02-23 23:14:00 -08001947
1948 // The RI only enforces the static/non-static mismatch in one direction.
1949 // TODO: should we change the tests and check both?
1950 if (is_static) {
1951 if (!f->IsStatic()) {
1952 return JDWP::ERR_INVALID_FIELDID;
1953 }
1954 } else {
1955 if (f->IsStatic()) {
Sebastien Hertz49983742015-06-11 18:42:58 +02001956 LOG(WARNING) << "Ignoring non-nullptr receiver for ObjectReference.SetValues"
1957 << " on static field " << PrettyField(f);
Elliott Hughes0cf74332012-02-23 23:14:00 -08001958 }
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08001959 }
jeffhao0dfbb7e2012-11-28 15:26:03 -08001960 if (f->IsStatic()) {
1961 o = f->GetDeclaringClass();
1962 }
Sebastien Hertz49983742015-06-11 18:42:58 +02001963 return SetArtFieldValue(f, o, value, width);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001964}
1965
Elliott Hughes88d63092013-01-09 09:55:54 -08001966JDWP::JdwpError Dbg::SetFieldValue(JDWP::ObjectId object_id, JDWP::FieldId field_id, uint64_t value,
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001967 int width) {
Elliott Hughes88d63092013-01-09 09:55:54 -08001968 return SetFieldValueImpl(object_id, field_id, value, width, false);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001969}
1970
Elliott Hughes88d63092013-01-09 09:55:54 -08001971JDWP::JdwpError Dbg::SetStaticFieldValue(JDWP::FieldId field_id, uint64_t value, int width) {
1972 return SetFieldValueImpl(0, field_id, value, width, true);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001973}
1974
Sebastien Hertzb0b0b492014-09-15 11:27:27 +02001975JDWP::JdwpError Dbg::StringToUtf8(JDWP::ObjectId string_id, std::string* str) {
Ian Rogersc0542af2014-09-03 16:16:56 -07001976 JDWP::JdwpError error;
Sebastien Hertzb0b0b492014-09-15 11:27:27 +02001977 mirror::Object* obj = gRegistry->Get<mirror::Object*>(string_id, &error);
1978 if (error != JDWP::ERR_NONE) {
1979 return error;
1980 }
1981 if (obj == nullptr) {
1982 return JDWP::ERR_INVALID_OBJECT;
1983 }
1984 {
1985 ScopedObjectAccessUnchecked soa(Thread::Current());
1986 mirror::Class* java_lang_String = soa.Decode<mirror::Class*>(WellKnownClasses::java_lang_String);
1987 if (!java_lang_String->IsAssignableFrom(obj->GetClass())) {
1988 // This isn't a string.
1989 return JDWP::ERR_INVALID_STRING;
1990 }
1991 }
1992 *str = obj->AsString()->ToModifiedUtf8();
1993 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001994}
1995
Jeff Hao579b0242013-11-18 13:16:49 -08001996void Dbg::OutputJValue(JDWP::JdwpTag tag, const JValue* return_value, JDWP::ExpandBuf* pReply) {
1997 if (IsPrimitiveTag(tag)) {
1998 expandBufAdd1(pReply, tag);
1999 if (tag == JDWP::JT_BOOLEAN || tag == JDWP::JT_BYTE) {
2000 expandBufAdd1(pReply, return_value->GetI());
2001 } else if (tag == JDWP::JT_CHAR || tag == JDWP::JT_SHORT) {
2002 expandBufAdd2BE(pReply, return_value->GetI());
2003 } else if (tag == JDWP::JT_FLOAT || tag == JDWP::JT_INT) {
2004 expandBufAdd4BE(pReply, return_value->GetI());
2005 } else if (tag == JDWP::JT_DOUBLE || tag == JDWP::JT_LONG) {
2006 expandBufAdd8BE(pReply, return_value->GetJ());
2007 } else {
2008 CHECK_EQ(tag, JDWP::JT_VOID);
2009 }
2010 } else {
Ian Rogers98379392014-02-24 16:53:16 -08002011 ScopedObjectAccessUnchecked soa(Thread::Current());
Jeff Hao579b0242013-11-18 13:16:49 -08002012 mirror::Object* value = return_value->GetL();
Ian Rogers98379392014-02-24 16:53:16 -08002013 expandBufAdd1(pReply, TagFromObject(soa, value));
Jeff Hao579b0242013-11-18 13:16:49 -08002014 expandBufAddObjectId(pReply, gRegistry->Add(value));
2015 }
2016}
2017
Ian Rogersc0542af2014-09-03 16:16:56 -07002018JDWP::JdwpError Dbg::GetThreadName(JDWP::ObjectId thread_id, std::string* name) {
jeffhaoa77f0f62012-12-05 17:19:31 -08002019 ScopedObjectAccessUnchecked soa(Thread::Current());
Ian Rogersc0542af2014-09-03 16:16:56 -07002020 JDWP::JdwpError error;
2021 Thread* thread = DecodeThread(soa, thread_id, &error);
2022 UNUSED(thread);
Elliott Hughes221229c2013-01-08 18:17:50 -08002023 if (error != JDWP::ERR_NONE && error != JDWP::ERR_THREAD_NOT_ALIVE) {
2024 return error;
Elliott Hughesa2e54f62011-11-17 13:01:30 -08002025 }
Elliott Hughes221229c2013-01-08 18:17:50 -08002026
2027 // We still need to report the zombie threads' names, so we can't just call Thread::GetThreadName.
Ian Rogersc0542af2014-09-03 16:16:56 -07002028 mirror::Object* thread_object = gRegistry->Get<mirror::Object*>(thread_id, &error);
2029 CHECK(thread_object != nullptr) << error;
Mathieu Chartierc7853442015-03-27 14:35:38 -07002030 ArtField* java_lang_Thread_name_field =
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002031 soa.DecodeField(WellKnownClasses::java_lang_Thread_name);
2032 mirror::String* s =
2033 reinterpret_cast<mirror::String*>(java_lang_Thread_name_field->GetObject(thread_object));
Ian Rogersc0542af2014-09-03 16:16:56 -07002034 if (s != nullptr) {
2035 *name = s->ToModifiedUtf8();
Elliott Hughes221229c2013-01-08 18:17:50 -08002036 }
2037 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002038}
2039
Elliott Hughes221229c2013-01-08 18:17:50 -08002040JDWP::JdwpError Dbg::GetThreadGroup(JDWP::ObjectId thread_id, JDWP::ExpandBuf* pReply) {
Sebastien Hertza06430c2014-09-15 19:21:30 +02002041 ScopedObjectAccessUnchecked soa(Thread::Current());
Ian Rogersc0542af2014-09-03 16:16:56 -07002042 JDWP::JdwpError error;
2043 mirror::Object* thread_object = gRegistry->Get<mirror::Object*>(thread_id, &error);
2044 if (error != JDWP::ERR_NONE) {
Elliott Hughes2435a572012-02-17 16:07:41 -08002045 return JDWP::ERR_INVALID_OBJECT;
2046 }
Mathieu Chartier2d5f39e2014-09-19 17:52:37 -07002047 ScopedAssertNoThreadSuspension ants(soa.Self(), "Debugger: GetThreadGroup");
Elliott Hughes2435a572012-02-17 16:07:41 -08002048 // Okay, so it's an object, but is it actually a thread?
Sebastien Hertz69206392015-04-07 15:54:25 +02002049 Thread* thread = DecodeThread(soa, thread_id, &error);
2050 UNUSED(thread);
Elliott Hughes221229c2013-01-08 18:17:50 -08002051 if (error == JDWP::ERR_THREAD_NOT_ALIVE) {
2052 // Zombie threads are in the null group.
2053 expandBufAddObjectId(pReply, JDWP::ObjectId(0));
Sebastien Hertz52d131d2014-03-13 16:17:40 +01002054 error = JDWP::ERR_NONE;
2055 } else if (error == JDWP::ERR_NONE) {
2056 mirror::Class* c = soa.Decode<mirror::Class*>(WellKnownClasses::java_lang_Thread);
2057 CHECK(c != nullptr);
Mathieu Chartierc7853442015-03-27 14:35:38 -07002058 ArtField* f = soa.DecodeField(WellKnownClasses::java_lang_Thread_group);
Hiroshi Yamauchib5a9e3d2014-06-09 12:11:20 -07002059 CHECK(f != nullptr);
Sebastien Hertz52d131d2014-03-13 16:17:40 +01002060 mirror::Object* group = f->GetObject(thread_object);
Hiroshi Yamauchib5a9e3d2014-06-09 12:11:20 -07002061 CHECK(group != nullptr);
Sebastien Hertz52d131d2014-03-13 16:17:40 +01002062 JDWP::ObjectId thread_group_id = gRegistry->Add(group);
2063 expandBufAddObjectId(pReply, thread_group_id);
Elliott Hughes221229c2013-01-08 18:17:50 -08002064 }
Sebastien Hertz52d131d2014-03-13 16:17:40 +01002065 return error;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002066}
2067
Sebastien Hertza06430c2014-09-15 19:21:30 +02002068static mirror::Object* DecodeThreadGroup(ScopedObjectAccessUnchecked& soa,
2069 JDWP::ObjectId thread_group_id, JDWP::JdwpError* error)
2070 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Sebastien Hertz6995c602014-09-09 12:10:13 +02002071 mirror::Object* thread_group = Dbg::GetObjectRegistry()->Get<mirror::Object*>(thread_group_id,
2072 error);
Sebastien Hertza06430c2014-09-15 19:21:30 +02002073 if (*error != JDWP::ERR_NONE) {
2074 return nullptr;
2075 }
2076 if (thread_group == nullptr) {
2077 *error = JDWP::ERR_INVALID_OBJECT;
2078 return nullptr;
2079 }
Ian Rogers98379392014-02-24 16:53:16 -08002080 mirror::Class* c = soa.Decode<mirror::Class*>(WellKnownClasses::java_lang_ThreadGroup);
2081 CHECK(c != nullptr);
Sebastien Hertza06430c2014-09-15 19:21:30 +02002082 if (!c->IsAssignableFrom(thread_group->GetClass())) {
2083 // This is not a java.lang.ThreadGroup.
2084 *error = JDWP::ERR_INVALID_THREAD_GROUP;
2085 return nullptr;
2086 }
2087 *error = JDWP::ERR_NONE;
2088 return thread_group;
2089}
2090
2091JDWP::JdwpError Dbg::GetThreadGroupName(JDWP::ObjectId thread_group_id, JDWP::ExpandBuf* pReply) {
2092 ScopedObjectAccessUnchecked soa(Thread::Current());
2093 JDWP::JdwpError error;
2094 mirror::Object* thread_group = DecodeThreadGroup(soa, thread_group_id, &error);
2095 if (error != JDWP::ERR_NONE) {
2096 return error;
2097 }
Mathieu Chartier2d5f39e2014-09-19 17:52:37 -07002098 ScopedAssertNoThreadSuspension ants(soa.Self(), "Debugger: GetThreadGroupName");
Mathieu Chartierc7853442015-03-27 14:35:38 -07002099 ArtField* f = soa.DecodeField(WellKnownClasses::java_lang_ThreadGroup_name);
Ian Rogersc0542af2014-09-03 16:16:56 -07002100 CHECK(f != nullptr);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002101 mirror::String* s = reinterpret_cast<mirror::String*>(f->GetObject(thread_group));
Sebastien Hertza06430c2014-09-15 19:21:30 +02002102
2103 std::string thread_group_name(s->ToModifiedUtf8());
2104 expandBufAddUtf8String(pReply, thread_group_name);
2105 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002106}
2107
Sebastien Hertza06430c2014-09-15 19:21:30 +02002108JDWP::JdwpError Dbg::GetThreadGroupParent(JDWP::ObjectId thread_group_id, JDWP::ExpandBuf* pReply) {
Ian Rogers98379392014-02-24 16:53:16 -08002109 ScopedObjectAccessUnchecked soa(Thread::Current());
Ian Rogersc0542af2014-09-03 16:16:56 -07002110 JDWP::JdwpError error;
Sebastien Hertza06430c2014-09-15 19:21:30 +02002111 mirror::Object* thread_group = DecodeThreadGroup(soa, thread_group_id, &error);
2112 if (error != JDWP::ERR_NONE) {
2113 return error;
2114 }
Mathieu Chartier2d5f39e2014-09-19 17:52:37 -07002115 mirror::Object* parent;
2116 {
2117 ScopedAssertNoThreadSuspension ants(soa.Self(), "Debugger: GetThreadGroupParent");
Mathieu Chartierc7853442015-03-27 14:35:38 -07002118 ArtField* f = soa.DecodeField(WellKnownClasses::java_lang_ThreadGroup_parent);
Mathieu Chartier2d5f39e2014-09-19 17:52:37 -07002119 CHECK(f != nullptr);
2120 parent = f->GetObject(thread_group);
2121 }
Sebastien Hertza06430c2014-09-15 19:21:30 +02002122 JDWP::ObjectId parent_group_id = gRegistry->Add(parent);
2123 expandBufAddObjectId(pReply, parent_group_id);
2124 return JDWP::ERR_NONE;
2125}
2126
2127static void GetChildThreadGroups(ScopedObjectAccessUnchecked& soa, mirror::Object* thread_group,
2128 std::vector<JDWP::ObjectId>* child_thread_group_ids)
2129 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
2130 CHECK(thread_group != nullptr);
2131
2132 // Get the ArrayList<ThreadGroup> "groups" out of this thread group...
Mathieu Chartierc7853442015-03-27 14:35:38 -07002133 ArtField* groups_field = soa.DecodeField(WellKnownClasses::java_lang_ThreadGroup_groups);
Sebastien Hertza06430c2014-09-15 19:21:30 +02002134 mirror::Object* groups_array_list = groups_field->GetObject(thread_group);
Sebastien Hertze49e1952014-10-13 11:27:13 +02002135 {
2136 // The "groups" field is declared as a java.util.List: check it really is
2137 // an instance of java.util.ArrayList.
2138 CHECK(groups_array_list != nullptr);
2139 mirror::Class* java_util_ArrayList_class =
2140 soa.Decode<mirror::Class*>(WellKnownClasses::java_util_ArrayList);
2141 CHECK(groups_array_list->InstanceOf(java_util_ArrayList_class));
2142 }
Sebastien Hertza06430c2014-09-15 19:21:30 +02002143
2144 // Get the array and size out of the ArrayList<ThreadGroup>...
Mathieu Chartierc7853442015-03-27 14:35:38 -07002145 ArtField* array_field = soa.DecodeField(WellKnownClasses::java_util_ArrayList_array);
2146 ArtField* size_field = soa.DecodeField(WellKnownClasses::java_util_ArrayList_size);
Sebastien Hertza06430c2014-09-15 19:21:30 +02002147 mirror::ObjectArray<mirror::Object>* groups_array =
2148 array_field->GetObject(groups_array_list)->AsObjectArray<mirror::Object>();
2149 const int32_t size = size_field->GetInt(groups_array_list);
2150
2151 // Copy the first 'size' elements out of the array into the result.
Sebastien Hertz6995c602014-09-09 12:10:13 +02002152 ObjectRegistry* registry = Dbg::GetObjectRegistry();
Sebastien Hertza06430c2014-09-15 19:21:30 +02002153 for (int32_t i = 0; i < size; ++i) {
Sebastien Hertz6995c602014-09-09 12:10:13 +02002154 child_thread_group_ids->push_back(registry->Add(groups_array->Get(i)));
Sebastien Hertza06430c2014-09-15 19:21:30 +02002155 }
2156}
2157
2158JDWP::JdwpError Dbg::GetThreadGroupChildren(JDWP::ObjectId thread_group_id,
2159 JDWP::ExpandBuf* pReply) {
2160 ScopedObjectAccessUnchecked soa(Thread::Current());
2161 JDWP::JdwpError error;
2162 mirror::Object* thread_group = DecodeThreadGroup(soa, thread_group_id, &error);
2163 if (error != JDWP::ERR_NONE) {
2164 return error;
2165 }
2166
2167 // Add child threads.
2168 {
2169 std::vector<JDWP::ObjectId> child_thread_ids;
2170 GetThreads(thread_group, &child_thread_ids);
2171 expandBufAdd4BE(pReply, child_thread_ids.size());
2172 for (JDWP::ObjectId child_thread_id : child_thread_ids) {
2173 expandBufAddObjectId(pReply, child_thread_id);
2174 }
2175 }
2176
2177 // Add child thread groups.
2178 {
2179 std::vector<JDWP::ObjectId> child_thread_groups_ids;
2180 GetChildThreadGroups(soa, thread_group, &child_thread_groups_ids);
2181 expandBufAdd4BE(pReply, child_thread_groups_ids.size());
2182 for (JDWP::ObjectId child_thread_group_id : child_thread_groups_ids) {
2183 expandBufAddObjectId(pReply, child_thread_group_id);
2184 }
2185 }
2186
2187 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002188}
2189
2190JDWP::ObjectId Dbg::GetSystemThreadGroupId() {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002191 ScopedObjectAccessUnchecked soa(Thread::Current());
Mathieu Chartierc7853442015-03-27 14:35:38 -07002192 ArtField* f = soa.DecodeField(WellKnownClasses::java_lang_ThreadGroup_systemThreadGroup);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002193 mirror::Object* group = f->GetObject(f->GetDeclaringClass());
Ian Rogers365c1022012-06-22 15:05:28 -07002194 return gRegistry->Add(group);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002195}
2196
Jeff Hao920af3e2013-08-28 15:46:38 -07002197JDWP::JdwpThreadStatus Dbg::ToJdwpThreadStatus(ThreadState state) {
2198 switch (state) {
2199 case kBlocked:
2200 return JDWP::TS_MONITOR;
2201 case kNative:
2202 case kRunnable:
2203 case kSuspended:
2204 return JDWP::TS_RUNNING;
2205 case kSleeping:
2206 return JDWP::TS_SLEEPING;
2207 case kStarting:
2208 case kTerminated:
2209 return JDWP::TS_ZOMBIE;
2210 case kTimedWaiting:
Sebastien Hertzbae182c2013-12-17 10:42:03 +01002211 case kWaitingForCheckPointsToRun:
Jeff Hao920af3e2013-08-28 15:46:38 -07002212 case kWaitingForDebuggerSend:
2213 case kWaitingForDebuggerSuspension:
2214 case kWaitingForDebuggerToAttach:
Sebastien Hertz138dbfc2013-12-04 18:15:25 +01002215 case kWaitingForDeoptimization:
Jeff Hao920af3e2013-08-28 15:46:38 -07002216 case kWaitingForGcToComplete:
Mathieu Chartiera395c0a2015-05-12 10:47:11 -07002217 case kWaitingForGetObjectsAllocated:
Jeff Hao920af3e2013-08-28 15:46:38 -07002218 case kWaitingForJniOnLoad:
Sebastien Hertzbae182c2013-12-17 10:42:03 +01002219 case kWaitingForMethodTracingStart:
Jeff Hao920af3e2013-08-28 15:46:38 -07002220 case kWaitingForSignalCatcherOutput:
Hiroshi Yamauchi0c8c3032015-01-16 16:54:35 -08002221 case kWaitingForVisitObjects:
Jeff Hao920af3e2013-08-28 15:46:38 -07002222 case kWaitingInMainDebuggerLoop:
2223 case kWaitingInMainSignalCatcherLoop:
2224 case kWaitingPerformingGc:
2225 case kWaiting:
2226 return JDWP::TS_WAIT;
2227 // Don't add a 'default' here so the compiler can spot incompatible enum changes.
2228 }
2229 LOG(FATAL) << "Unknown thread state: " << state;
2230 return JDWP::TS_ZOMBIE;
2231}
2232
Sebastien Hertz52d131d2014-03-13 16:17:40 +01002233JDWP::JdwpError Dbg::GetThreadStatus(JDWP::ObjectId thread_id, JDWP::JdwpThreadStatus* pThreadStatus,
2234 JDWP::JdwpSuspendStatus* pSuspendStatus) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002235 ScopedObjectAccess soa(Thread::Current());
Elliott Hughes499c5132011-11-17 14:55:11 -08002236
Elliott Hughes9e0c1752013-01-09 14:02:58 -08002237 *pSuspendStatus = JDWP::SUSPEND_STATUS_NOT_SUSPENDED;
2238
Ian Rogersc0542af2014-09-03 16:16:56 -07002239 JDWP::JdwpError error;
2240 Thread* thread = DecodeThread(soa, thread_id, &error);
Elliott Hughes221229c2013-01-08 18:17:50 -08002241 if (error != JDWP::ERR_NONE) {
2242 if (error == JDWP::ERR_THREAD_NOT_ALIVE) {
2243 *pThreadStatus = JDWP::TS_ZOMBIE;
Elliott Hughes221229c2013-01-08 18:17:50 -08002244 return JDWP::ERR_NONE;
2245 }
2246 return error;
Elliott Hughes499c5132011-11-17 14:55:11 -08002247 }
2248
Elliott Hughes9e0c1752013-01-09 14:02:58 -08002249 if (IsSuspendedForDebugger(soa, thread)) {
2250 *pSuspendStatus = JDWP::SUSPEND_STATUS_SUSPENDED;
Elliott Hughes499c5132011-11-17 14:55:11 -08002251 }
2252
Jeff Hao920af3e2013-08-28 15:46:38 -07002253 *pThreadStatus = ToJdwpThreadStatus(thread->GetState());
Elliott Hughes221229c2013-01-08 18:17:50 -08002254 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002255}
2256
Elliott Hughes221229c2013-01-08 18:17:50 -08002257JDWP::JdwpError Dbg::GetThreadDebugSuspendCount(JDWP::ObjectId thread_id, JDWP::ExpandBuf* pReply) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002258 ScopedObjectAccess soa(Thread::Current());
Ian Rogersc0542af2014-09-03 16:16:56 -07002259 JDWP::JdwpError error;
2260 Thread* thread = DecodeThread(soa, thread_id, &error);
Elliott Hughes221229c2013-01-08 18:17:50 -08002261 if (error != JDWP::ERR_NONE) {
2262 return error;
Elliott Hughes2435a572012-02-17 16:07:41 -08002263 }
Ian Rogers50b35e22012-10-04 10:09:15 -07002264 MutexLock mu2(soa.Self(), *Locks::thread_suspend_count_lock_);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002265 expandBufAdd4BE(pReply, thread->GetDebugSuspendCount());
Elliott Hughes2435a572012-02-17 16:07:41 -08002266 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002267}
2268
Elliott Hughesf9501702013-01-11 11:22:27 -08002269JDWP::JdwpError Dbg::Interrupt(JDWP::ObjectId thread_id) {
2270 ScopedObjectAccess soa(Thread::Current());
Ian Rogersc0542af2014-09-03 16:16:56 -07002271 JDWP::JdwpError error;
2272 Thread* thread = DecodeThread(soa, thread_id, &error);
Elliott Hughesf9501702013-01-11 11:22:27 -08002273 if (error != JDWP::ERR_NONE) {
2274 return error;
2275 }
Ian Rogersdd7624d2014-03-14 17:43:00 -07002276 thread->Interrupt(soa.Self());
Elliott Hughesf9501702013-01-11 11:22:27 -08002277 return JDWP::ERR_NONE;
2278}
2279
Sebastien Hertz070f7322014-09-09 12:08:49 +02002280static bool IsInDesiredThreadGroup(ScopedObjectAccessUnchecked& soa,
2281 mirror::Object* desired_thread_group, mirror::Object* peer)
2282 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
2283 // Do we want threads from all thread groups?
2284 if (desired_thread_group == nullptr) {
2285 return true;
2286 }
Mathieu Chartierc7853442015-03-27 14:35:38 -07002287 ArtField* thread_group_field = soa.DecodeField(WellKnownClasses::java_lang_Thread_group);
Sebastien Hertz070f7322014-09-09 12:08:49 +02002288 DCHECK(thread_group_field != nullptr);
2289 mirror::Object* group = thread_group_field->GetObject(peer);
2290 return (group == desired_thread_group);
2291}
2292
Sebastien Hertza06430c2014-09-15 19:21:30 +02002293void Dbg::GetThreads(mirror::Object* thread_group, std::vector<JDWP::ObjectId>* thread_ids) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002294 ScopedObjectAccessUnchecked soa(Thread::Current());
Sebastien Hertz070f7322014-09-09 12:08:49 +02002295 std::list<Thread*> all_threads_list;
2296 {
2297 MutexLock mu(Thread::Current(), *Locks::thread_list_lock_);
2298 all_threads_list = Runtime::Current()->GetThreadList()->GetList();
2299 }
2300 for (Thread* t : all_threads_list) {
2301 if (t == Dbg::GetDebugThread()) {
2302 // Skip the JDWP thread. Some debuggers get bent out of shape when they can't suspend and
2303 // query all threads, so it's easier if we just don't tell them about this thread.
2304 continue;
2305 }
2306 if (t->IsStillStarting()) {
2307 // This thread is being started (and has been registered in the thread list). However, it is
2308 // not completely started yet so we must ignore it.
2309 continue;
2310 }
2311 mirror::Object* peer = t->GetPeer();
2312 if (peer == nullptr) {
Mathieu Chartier2cebb242015-04-21 16:50:40 -07002313 // peer might be null if the thread is still starting up. We can't tell the debugger about
Sebastien Hertz070f7322014-09-09 12:08:49 +02002314 // this thread yet.
2315 // TODO: if we identified threads to the debugger by their Thread*
2316 // rather than their peer's mirror::Object*, we could fix this.
2317 // Doing so might help us report ZOMBIE threads too.
2318 continue;
2319 }
2320 if (IsInDesiredThreadGroup(soa, thread_group, peer)) {
2321 thread_ids->push_back(gRegistry->Add(peer));
2322 }
2323 }
Elliott Hughescaf76542012-06-28 16:08:22 -07002324}
Elliott Hughesa2155262011-11-16 16:26:58 -08002325
Ian Rogersc0542af2014-09-03 16:16:56 -07002326static int GetStackDepth(Thread* thread) SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Ian Rogers0399dde2012-06-06 17:09:28 -07002327 struct CountStackDepthVisitor : public StackVisitor {
Andreas Gampe277ccbd2014-11-03 21:36:10 -08002328 explicit CountStackDepthVisitor(Thread* thread_in)
Nicolas Geoffray8e5bd182015-05-06 11:34:34 +01002329 : StackVisitor(thread_in, nullptr, StackVisitor::StackWalkKind::kIncludeInlinedFrames),
2330 depth(0) {}
Ian Rogers0399dde2012-06-06 17:09:28 -07002331
Elliott Hughes64f574f2013-02-20 14:57:12 -08002332 // TODO: Enable annotalysis. We know lock is held in constructor, but abstraction confuses
2333 // annotalysis.
2334 bool VisitFrame() NO_THREAD_SAFETY_ANALYSIS {
Ian Rogers0399dde2012-06-06 17:09:28 -07002335 if (!GetMethod()->IsRuntimeMethod()) {
Elliott Hughesf8a2df72011-12-01 12:19:54 -08002336 ++depth;
2337 }
Elliott Hughes530fa002012-03-12 11:44:49 -07002338 return true;
Elliott Hughesa2e54f62011-11-17 13:01:30 -08002339 }
2340 size_t depth;
2341 };
Elliott Hughes08fc03a2012-06-26 17:34:00 -07002342
Ian Rogers7a22fa62013-01-23 12:16:16 -08002343 CountStackDepthVisitor visitor(thread);
Ian Rogers0399dde2012-06-06 17:09:28 -07002344 visitor.WalkStack();
Elliott Hughesa2e54f62011-11-17 13:01:30 -08002345 return visitor.depth;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002346}
2347
Ian Rogersc0542af2014-09-03 16:16:56 -07002348JDWP::JdwpError Dbg::GetThreadFrameCount(JDWP::ObjectId thread_id, size_t* result) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002349 ScopedObjectAccess soa(Thread::Current());
Ian Rogersc0542af2014-09-03 16:16:56 -07002350 JDWP::JdwpError error;
2351 *result = 0;
2352 Thread* thread = DecodeThread(soa, thread_id, &error);
Elliott Hughes221229c2013-01-08 18:17:50 -08002353 if (error != JDWP::ERR_NONE) {
2354 return error;
2355 }
Elliott Hughesf15f4a02013-01-09 10:09:38 -08002356 if (!IsSuspendedForDebugger(soa, thread)) {
2357 return JDWP::ERR_THREAD_NOT_SUSPENDED;
2358 }
Ian Rogersc0542af2014-09-03 16:16:56 -07002359 *result = GetStackDepth(thread);
Elliott Hughes221229c2013-01-08 18:17:50 -08002360 return JDWP::ERR_NONE;
Elliott Hughes86964332012-02-15 19:37:42 -08002361}
2362
Ian Rogers306057f2012-11-26 12:45:53 -08002363JDWP::JdwpError Dbg::GetThreadFrames(JDWP::ObjectId thread_id, size_t start_frame,
2364 size_t frame_count, JDWP::ExpandBuf* buf) {
Elliott Hughes6e9d22c2012-06-22 15:02:37 -07002365 class GetFrameVisitor : public StackVisitor {
2366 public:
Andreas Gampe277ccbd2014-11-03 21:36:10 -08002367 GetFrameVisitor(Thread* thread, size_t start_frame_in, size_t frame_count_in,
2368 JDWP::ExpandBuf* buf_in)
Ian Rogersb726dcb2012-09-05 08:57:23 -07002369 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_)
Nicolas Geoffray8e5bd182015-05-06 11:34:34 +01002370 : StackVisitor(thread, nullptr, StackVisitor::StackWalkKind::kIncludeInlinedFrames),
2371 depth_(0),
2372 start_frame_(start_frame_in),
2373 frame_count_(frame_count_in),
2374 buf_(buf_in) {
Elliott Hughes6e9d22c2012-06-22 15:02:37 -07002375 expandBufAdd4BE(buf_, frame_count_);
Elliott Hughes03181a82011-11-17 17:22:21 -08002376 }
Ian Rogers0399dde2012-06-06 17:09:28 -07002377
Sebastien Hertz69206392015-04-07 15:54:25 +02002378 bool VisitFrame() OVERRIDE SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Ian Rogers0399dde2012-06-06 17:09:28 -07002379 if (GetMethod()->IsRuntimeMethod()) {
Brian Carlstrom7934ac22013-07-26 10:54:15 -07002380 return true; // The debugger can't do anything useful with a frame that has no Method*.
Elliott Hughes03181a82011-11-17 17:22:21 -08002381 }
Elliott Hughes6e9d22c2012-06-22 15:02:37 -07002382 if (depth_ >= start_frame_ + frame_count_) {
Elliott Hughes530fa002012-03-12 11:44:49 -07002383 return false;
Elliott Hughes03181a82011-11-17 17:22:21 -08002384 }
Elliott Hughes6e9d22c2012-06-22 15:02:37 -07002385 if (depth_ >= start_frame_) {
2386 JDWP::FrameId frame_id(GetFrameId());
2387 JDWP::JdwpLocation location;
Sebastien Hertz6995c602014-09-09 12:10:13 +02002388 SetJdwpLocation(&location, GetMethod(), GetDexPc());
Ian Rogersef7d42f2014-01-06 12:55:46 -08002389 VLOG(jdwp) << StringPrintf(" Frame %3zd: id=%3" PRIu64 " ", depth_, frame_id) << location;
Elliott Hughes6e9d22c2012-06-22 15:02:37 -07002390 expandBufAdd8BE(buf_, frame_id);
2391 expandBufAddLocation(buf_, location);
2392 }
2393 ++depth_;
Elliott Hughes530fa002012-03-12 11:44:49 -07002394 return true;
Elliott Hughes03181a82011-11-17 17:22:21 -08002395 }
Elliott Hughes6e9d22c2012-06-22 15:02:37 -07002396
2397 private:
2398 size_t depth_;
2399 const size_t start_frame_;
2400 const size_t frame_count_;
2401 JDWP::ExpandBuf* buf_;
Elliott Hughes03181a82011-11-17 17:22:21 -08002402 };
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002403
2404 ScopedObjectAccessUnchecked soa(Thread::Current());
Ian Rogersc0542af2014-09-03 16:16:56 -07002405 JDWP::JdwpError error;
2406 Thread* thread = DecodeThread(soa, thread_id, &error);
Elliott Hughes221229c2013-01-08 18:17:50 -08002407 if (error != JDWP::ERR_NONE) {
2408 return error;
2409 }
Elliott Hughesf15f4a02013-01-09 10:09:38 -08002410 if (!IsSuspendedForDebugger(soa, thread)) {
2411 return JDWP::ERR_THREAD_NOT_SUSPENDED;
2412 }
Ian Rogers7a22fa62013-01-23 12:16:16 -08002413 GetFrameVisitor visitor(thread, start_frame, frame_count, buf);
Ian Rogers0399dde2012-06-06 17:09:28 -07002414 visitor.WalkStack();
Elliott Hughes6e9d22c2012-06-22 15:02:37 -07002415 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002416}
2417
2418JDWP::ObjectId Dbg::GetThreadSelfId() {
Sebastien Hertz6995c602014-09-09 12:10:13 +02002419 return GetThreadId(Thread::Current());
2420}
2421
2422JDWP::ObjectId Dbg::GetThreadId(Thread* thread) {
Mathieu Chartierdbe6f462012-09-25 16:54:50 -07002423 ScopedObjectAccessUnchecked soa(Thread::Current());
Sebastien Hertz6995c602014-09-09 12:10:13 +02002424 return gRegistry->Add(thread->GetPeer());
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002425}
2426
Elliott Hughes475fc232011-10-25 15:00:35 -07002427void Dbg::SuspendVM() {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002428 Runtime::Current()->GetThreadList()->SuspendAllForDebugger();
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002429}
2430
2431void Dbg::ResumeVM() {
Sebastien Hertz253fa552014-10-14 17:27:15 +02002432 Runtime::Current()->GetThreadList()->ResumeAllForDebugger();
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002433}
2434
Elliott Hughes221229c2013-01-08 18:17:50 -08002435JDWP::JdwpError Dbg::SuspendThread(JDWP::ObjectId thread_id, bool request_suspension) {
Ian Rogersf3d874c2014-07-17 18:52:42 -07002436 Thread* self = Thread::Current();
Ian Rogersc0542af2014-09-03 16:16:56 -07002437 ScopedLocalRef<jobject> peer(self->GetJniEnv(), nullptr);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002438 {
Ian Rogersf3d874c2014-07-17 18:52:42 -07002439 ScopedObjectAccess soa(self);
Ian Rogersc0542af2014-09-03 16:16:56 -07002440 JDWP::JdwpError error;
2441 peer.reset(soa.AddLocalReference<jobject>(gRegistry->Get<mirror::Object*>(thread_id, &error)));
Elliott Hughes4e235312011-12-02 11:34:15 -08002442 }
Ian Rogersc0542af2014-09-03 16:16:56 -07002443 if (peer.get() == nullptr) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002444 return JDWP::ERR_THREAD_NOT_ALIVE;
2445 }
Ian Rogers4ad5cd32014-11-11 23:08:07 -08002446 // Suspend thread to build stack trace.
Elliott Hughesf327e072013-01-09 16:01:26 -08002447 bool timed_out;
Brian Carlstromba32de42014-08-27 23:43:46 -07002448 ThreadList* thread_list = Runtime::Current()->GetThreadList();
2449 Thread* thread = thread_list->SuspendThreadByPeer(peer.get(), request_suspension, true,
2450 &timed_out);
Ian Rogersc0542af2014-09-03 16:16:56 -07002451 if (thread != nullptr) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002452 return JDWP::ERR_NONE;
Elliott Hughesf327e072013-01-09 16:01:26 -08002453 } else if (timed_out) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002454 return JDWP::ERR_INTERNAL;
2455 } else {
2456 return JDWP::ERR_THREAD_NOT_ALIVE;
2457 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002458}
2459
Elliott Hughes221229c2013-01-08 18:17:50 -08002460void Dbg::ResumeThread(JDWP::ObjectId thread_id) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002461 ScopedObjectAccessUnchecked soa(Thread::Current());
Ian Rogersc0542af2014-09-03 16:16:56 -07002462 JDWP::JdwpError error;
2463 mirror::Object* peer = gRegistry->Get<mirror::Object*>(thread_id, &error);
2464 CHECK(peer != nullptr) << error;
jeffhaoa77f0f62012-12-05 17:19:31 -08002465 Thread* thread;
2466 {
2467 MutexLock mu(soa.Self(), *Locks::thread_list_lock_);
2468 thread = Thread::FromManagedThread(soa, peer);
2469 }
Ian Rogersc0542af2014-09-03 16:16:56 -07002470 if (thread == nullptr) {
Elliott Hughes4e235312011-12-02 11:34:15 -08002471 LOG(WARNING) << "No such thread for resume: " << peer;
2472 return;
2473 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002474 bool needs_resume;
2475 {
Ian Rogers50b35e22012-10-04 10:09:15 -07002476 MutexLock mu2(soa.Self(), *Locks::thread_suspend_count_lock_);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002477 needs_resume = thread->GetSuspendCount() > 0;
2478 }
2479 if (needs_resume) {
Elliott Hughes546b9862012-06-20 16:06:13 -07002480 Runtime::Current()->GetThreadList()->Resume(thread, true);
2481 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002482}
2483
2484void Dbg::SuspendSelf() {
Elliott Hughes475fc232011-10-25 15:00:35 -07002485 Runtime::Current()->GetThreadList()->SuspendSelfForDebugger();
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002486}
2487
Ian Rogers0399dde2012-06-06 17:09:28 -07002488struct GetThisVisitor : public StackVisitor {
Andreas Gampe277ccbd2014-11-03 21:36:10 -08002489 GetThisVisitor(Thread* thread, Context* context, JDWP::FrameId frame_id_in)
Ian Rogersb726dcb2012-09-05 08:57:23 -07002490 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_)
Nicolas Geoffray8e5bd182015-05-06 11:34:34 +01002491 : StackVisitor(thread, context, StackVisitor::StackWalkKind::kIncludeInlinedFrames),
2492 this_object(nullptr),
2493 frame_id(frame_id_in) {}
Ian Rogers0399dde2012-06-06 17:09:28 -07002494
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002495 // TODO: Enable annotalysis. We know lock is held in constructor, but abstraction confuses
2496 // annotalysis.
2497 virtual bool VisitFrame() NO_THREAD_SAFETY_ANALYSIS {
Elliott Hughes6e9d22c2012-06-22 15:02:37 -07002498 if (frame_id != GetFrameId()) {
Ian Rogers0399dde2012-06-06 17:09:28 -07002499 return true; // continue
Ian Rogers0399dde2012-06-06 17:09:28 -07002500 } else {
Ian Rogers62d6c772013-02-27 08:32:07 -08002501 this_object = GetThisObject();
2502 return false;
Ian Rogers0399dde2012-06-06 17:09:28 -07002503 }
Elliott Hughes86b00102011-12-05 17:54:26 -08002504 }
Ian Rogers0399dde2012-06-06 17:09:28 -07002505
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002506 mirror::Object* this_object;
Elliott Hughes6e9d22c2012-06-22 15:02:37 -07002507 JDWP::FrameId frame_id;
Ian Rogers0399dde2012-06-06 17:09:28 -07002508};
2509
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002510JDWP::JdwpError Dbg::GetThisObject(JDWP::ObjectId thread_id, JDWP::FrameId frame_id,
2511 JDWP::ObjectId* result) {
2512 ScopedObjectAccessUnchecked soa(Thread::Current());
Sebastien Hertz69206392015-04-07 15:54:25 +02002513 JDWP::JdwpError error;
2514 Thread* thread = DecodeThread(soa, thread_id, &error);
2515 if (error != JDWP::ERR_NONE) {
2516 return error;
2517 }
2518 if (!IsSuspendedForDebugger(soa, thread)) {
2519 return JDWP::ERR_THREAD_NOT_SUSPENDED;
Elliott Hughes6e9d22c2012-06-22 15:02:37 -07002520 }
Ian Rogers700a4022014-05-19 16:49:03 -07002521 std::unique_ptr<Context> context(Context::Create());
Ian Rogers7a22fa62013-01-23 12:16:16 -08002522 GetThisVisitor visitor(thread, context.get(), frame_id);
Ian Rogers0399dde2012-06-06 17:09:28 -07002523 visitor.WalkStack();
Elliott Hughes6e9d22c2012-06-22 15:02:37 -07002524 *result = gRegistry->Add(visitor.this_object);
2525 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002526}
2527
Sebastien Hertz8009f392014-09-01 17:07:11 +02002528// Walks the stack until we find the frame with the given FrameId.
2529class FindFrameVisitor FINAL : public StackVisitor {
2530 public:
2531 FindFrameVisitor(Thread* thread, Context* context, JDWP::FrameId frame_id)
2532 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_)
Nicolas Geoffray8e5bd182015-05-06 11:34:34 +01002533 : StackVisitor(thread, context, StackVisitor::StackWalkKind::kIncludeInlinedFrames),
2534 frame_id_(frame_id),
2535 error_(JDWP::ERR_INVALID_FRAMEID) {}
Ian Rogersca190662012-06-26 15:45:57 -07002536
Sebastien Hertz8009f392014-09-01 17:07:11 +02002537 // TODO: Enable annotalysis. We know lock is held in constructor, but abstraction confuses
2538 // annotalysis.
2539 bool VisitFrame() NO_THREAD_SAFETY_ANALYSIS {
2540 if (GetFrameId() != frame_id_) {
2541 return true; // Not our frame, carry on.
Ian Rogers0399dde2012-06-06 17:09:28 -07002542 }
Mathieu Chartier3d21bdf2015-04-22 13:56:20 -07002543 ArtMethod* m = GetMethod();
Sebastien Hertz8009f392014-09-01 17:07:11 +02002544 if (m->IsNative()) {
2545 // We can't read/write local value from/into native method.
2546 error_ = JDWP::ERR_OPAQUE_FRAME;
2547 } else {
2548 // We found our frame.
2549 error_ = JDWP::ERR_NONE;
2550 }
2551 return false;
2552 }
2553
2554 JDWP::JdwpError GetError() const {
2555 return error_;
2556 }
2557
2558 private:
2559 const JDWP::FrameId frame_id_;
2560 JDWP::JdwpError error_;
2561};
2562
2563JDWP::JdwpError Dbg::GetLocalValues(JDWP::Request* request, JDWP::ExpandBuf* pReply) {
2564 JDWP::ObjectId thread_id = request->ReadThreadId();
2565 JDWP::FrameId frame_id = request->ReadFrameId();
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002566
2567 ScopedObjectAccessUnchecked soa(Thread::Current());
Sebastien Hertz69206392015-04-07 15:54:25 +02002568 JDWP::JdwpError error;
2569 Thread* thread = DecodeThread(soa, thread_id, &error);
2570 if (error != JDWP::ERR_NONE) {
2571 return error;
2572 }
2573 if (!IsSuspendedForDebugger(soa, thread)) {
2574 return JDWP::ERR_THREAD_NOT_SUSPENDED;
Elliott Hughes221229c2013-01-08 18:17:50 -08002575 }
Sebastien Hertz8009f392014-09-01 17:07:11 +02002576 // Find the frame with the given frame_id.
Ian Rogers700a4022014-05-19 16:49:03 -07002577 std::unique_ptr<Context> context(Context::Create());
Sebastien Hertz8009f392014-09-01 17:07:11 +02002578 FindFrameVisitor visitor(thread, context.get(), frame_id);
Ian Rogers0399dde2012-06-06 17:09:28 -07002579 visitor.WalkStack();
Sebastien Hertz8009f392014-09-01 17:07:11 +02002580 if (visitor.GetError() != JDWP::ERR_NONE) {
2581 return visitor.GetError();
2582 }
2583
2584 // Read the values from visitor's context.
2585 int32_t slot_count = request->ReadSigned32("slot count");
2586 expandBufAdd4BE(pReply, slot_count); /* "int values" */
2587 for (int32_t i = 0; i < slot_count; ++i) {
2588 uint32_t slot = request->ReadUnsigned32("slot");
2589 JDWP::JdwpTag reqSigByte = request->ReadTag();
2590
2591 VLOG(jdwp) << " --> slot " << slot << " " << reqSigByte;
2592
2593 size_t width = Dbg::GetTagWidth(reqSigByte);
Sebastien Hertz7d955652014-10-22 10:57:10 +02002594 uint8_t* ptr = expandBufAddSpace(pReply, width + 1);
Sebastien Hertz69206392015-04-07 15:54:25 +02002595 error = Dbg::GetLocalValue(visitor, soa, slot, reqSigByte, ptr, width);
Sebastien Hertz8009f392014-09-01 17:07:11 +02002596 if (error != JDWP::ERR_NONE) {
2597 return error;
2598 }
2599 }
2600 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002601}
2602
Sebastien Hertzabbabc82015-03-26 08:47:47 +01002603constexpr JDWP::JdwpError kStackFrameLocalAccessError = JDWP::ERR_ABSENT_INFORMATION;
2604
2605static std::string GetStackContextAsString(const StackVisitor& visitor)
2606 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
2607 return StringPrintf(" at DEX pc 0x%08x in method %s", visitor.GetDexPc(false),
2608 PrettyMethod(visitor.GetMethod()).c_str());
2609}
2610
2611static JDWP::JdwpError FailGetLocalValue(const StackVisitor& visitor, uint16_t vreg,
2612 JDWP::JdwpTag tag)
2613 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
2614 LOG(ERROR) << "Failed to read " << tag << " local from register v" << vreg
2615 << GetStackContextAsString(visitor);
2616 return kStackFrameLocalAccessError;
2617}
2618
Sebastien Hertz8009f392014-09-01 17:07:11 +02002619JDWP::JdwpError Dbg::GetLocalValue(const StackVisitor& visitor, ScopedObjectAccessUnchecked& soa,
2620 int slot, JDWP::JdwpTag tag, uint8_t* buf, size_t width) {
Mathieu Chartier3d21bdf2015-04-22 13:56:20 -07002621 ArtMethod* m = visitor.GetMethod();
Sebastien Hertzabbabc82015-03-26 08:47:47 +01002622 JDWP::JdwpError error = JDWP::ERR_NONE;
2623 uint16_t vreg = DemangleSlot(slot, m, &error);
2624 if (error != JDWP::ERR_NONE) {
2625 return error;
2626 }
Sebastien Hertz8009f392014-09-01 17:07:11 +02002627 // TODO: check that the tag is compatible with the actual type of the slot!
Sebastien Hertz8009f392014-09-01 17:07:11 +02002628 switch (tag) {
2629 case JDWP::JT_BOOLEAN: {
2630 CHECK_EQ(width, 1U);
2631 uint32_t intVal;
Sebastien Hertzabbabc82015-03-26 08:47:47 +01002632 if (!visitor.GetVReg(m, vreg, kIntVReg, &intVal)) {
2633 return FailGetLocalValue(visitor, vreg, tag);
Ian Rogers0399dde2012-06-06 17:09:28 -07002634 }
Sebastien Hertzabbabc82015-03-26 08:47:47 +01002635 VLOG(jdwp) << "get boolean local " << vreg << " = " << intVal;
2636 JDWP::Set1(buf + 1, intVal != 0);
Sebastien Hertz8009f392014-09-01 17:07:11 +02002637 break;
Ian Rogers0399dde2012-06-06 17:09:28 -07002638 }
Sebastien Hertz8009f392014-09-01 17:07:11 +02002639 case JDWP::JT_BYTE: {
2640 CHECK_EQ(width, 1U);
2641 uint32_t intVal;
Sebastien Hertzabbabc82015-03-26 08:47:47 +01002642 if (!visitor.GetVReg(m, vreg, kIntVReg, &intVal)) {
2643 return FailGetLocalValue(visitor, vreg, tag);
Sebastien Hertz8009f392014-09-01 17:07:11 +02002644 }
Sebastien Hertzabbabc82015-03-26 08:47:47 +01002645 VLOG(jdwp) << "get byte local " << vreg << " = " << intVal;
2646 JDWP::Set1(buf + 1, intVal);
Sebastien Hertz8009f392014-09-01 17:07:11 +02002647 break;
2648 }
2649 case JDWP::JT_SHORT:
2650 case JDWP::JT_CHAR: {
2651 CHECK_EQ(width, 2U);
2652 uint32_t intVal;
Sebastien Hertzabbabc82015-03-26 08:47:47 +01002653 if (!visitor.GetVReg(m, vreg, kIntVReg, &intVal)) {
2654 return FailGetLocalValue(visitor, vreg, tag);
Sebastien Hertz8009f392014-09-01 17:07:11 +02002655 }
Sebastien Hertzabbabc82015-03-26 08:47:47 +01002656 VLOG(jdwp) << "get short/char local " << vreg << " = " << intVal;
2657 JDWP::Set2BE(buf + 1, intVal);
Sebastien Hertz8009f392014-09-01 17:07:11 +02002658 break;
2659 }
2660 case JDWP::JT_INT: {
2661 CHECK_EQ(width, 4U);
2662 uint32_t intVal;
Sebastien Hertzabbabc82015-03-26 08:47:47 +01002663 if (!visitor.GetVReg(m, vreg, kIntVReg, &intVal)) {
2664 return FailGetLocalValue(visitor, vreg, tag);
Sebastien Hertz8009f392014-09-01 17:07:11 +02002665 }
Sebastien Hertzabbabc82015-03-26 08:47:47 +01002666 VLOG(jdwp) << "get int local " << vreg << " = " << intVal;
2667 JDWP::Set4BE(buf + 1, intVal);
Sebastien Hertz8009f392014-09-01 17:07:11 +02002668 break;
2669 }
2670 case JDWP::JT_FLOAT: {
2671 CHECK_EQ(width, 4U);
2672 uint32_t intVal;
Sebastien Hertzabbabc82015-03-26 08:47:47 +01002673 if (!visitor.GetVReg(m, vreg, kFloatVReg, &intVal)) {
2674 return FailGetLocalValue(visitor, vreg, tag);
Sebastien Hertz8009f392014-09-01 17:07:11 +02002675 }
Sebastien Hertzabbabc82015-03-26 08:47:47 +01002676 VLOG(jdwp) << "get float local " << vreg << " = " << intVal;
2677 JDWP::Set4BE(buf + 1, intVal);
Sebastien Hertz8009f392014-09-01 17:07:11 +02002678 break;
2679 }
2680 case JDWP::JT_ARRAY:
2681 case JDWP::JT_CLASS_LOADER:
2682 case JDWP::JT_CLASS_OBJECT:
2683 case JDWP::JT_OBJECT:
2684 case JDWP::JT_STRING:
2685 case JDWP::JT_THREAD:
2686 case JDWP::JT_THREAD_GROUP: {
2687 CHECK_EQ(width, sizeof(JDWP::ObjectId));
2688 uint32_t intVal;
Sebastien Hertzabbabc82015-03-26 08:47:47 +01002689 if (!visitor.GetVReg(m, vreg, kReferenceVReg, &intVal)) {
2690 return FailGetLocalValue(visitor, vreg, tag);
Sebastien Hertz8009f392014-09-01 17:07:11 +02002691 }
Sebastien Hertzabbabc82015-03-26 08:47:47 +01002692 mirror::Object* o = reinterpret_cast<mirror::Object*>(intVal);
2693 VLOG(jdwp) << "get " << tag << " object local " << vreg << " = " << o;
2694 if (!Runtime::Current()->GetHeap()->IsValidObjectAddress(o)) {
2695 LOG(FATAL) << StringPrintf("Found invalid object %#" PRIxPTR " in register v%u",
2696 reinterpret_cast<uintptr_t>(o), vreg)
2697 << GetStackContextAsString(visitor);
2698 UNREACHABLE();
2699 }
2700 tag = TagFromObject(soa, o);
2701 JDWP::SetObjectId(buf + 1, gRegistry->Add(o));
Sebastien Hertz8009f392014-09-01 17:07:11 +02002702 break;
2703 }
2704 case JDWP::JT_DOUBLE: {
2705 CHECK_EQ(width, 8U);
2706 uint64_t longVal;
Sebastien Hertzabbabc82015-03-26 08:47:47 +01002707 if (!visitor.GetVRegPair(m, vreg, kDoubleLoVReg, kDoubleHiVReg, &longVal)) {
2708 return FailGetLocalValue(visitor, vreg, tag);
Sebastien Hertz8009f392014-09-01 17:07:11 +02002709 }
Sebastien Hertzabbabc82015-03-26 08:47:47 +01002710 VLOG(jdwp) << "get double local " << vreg << " = " << longVal;
2711 JDWP::Set8BE(buf + 1, longVal);
Sebastien Hertz8009f392014-09-01 17:07:11 +02002712 break;
2713 }
2714 case JDWP::JT_LONG: {
2715 CHECK_EQ(width, 8U);
2716 uint64_t longVal;
Sebastien Hertzabbabc82015-03-26 08:47:47 +01002717 if (!visitor.GetVRegPair(m, vreg, kLongLoVReg, kLongHiVReg, &longVal)) {
2718 return FailGetLocalValue(visitor, vreg, tag);
Sebastien Hertz8009f392014-09-01 17:07:11 +02002719 }
Sebastien Hertzabbabc82015-03-26 08:47:47 +01002720 VLOG(jdwp) << "get long local " << vreg << " = " << longVal;
2721 JDWP::Set8BE(buf + 1, longVal);
Sebastien Hertz8009f392014-09-01 17:07:11 +02002722 break;
2723 }
2724 default:
2725 LOG(FATAL) << "Unknown tag " << tag;
Sebastien Hertzabbabc82015-03-26 08:47:47 +01002726 UNREACHABLE();
Sebastien Hertz8009f392014-09-01 17:07:11 +02002727 }
Ian Rogers0399dde2012-06-06 17:09:28 -07002728
Sebastien Hertz8009f392014-09-01 17:07:11 +02002729 // Prepend tag, which may have been updated.
2730 JDWP::Set1(buf, tag);
2731 return JDWP::ERR_NONE;
2732}
2733
2734JDWP::JdwpError Dbg::SetLocalValues(JDWP::Request* request) {
2735 JDWP::ObjectId thread_id = request->ReadThreadId();
2736 JDWP::FrameId frame_id = request->ReadFrameId();
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002737
2738 ScopedObjectAccessUnchecked soa(Thread::Current());
Sebastien Hertz69206392015-04-07 15:54:25 +02002739 JDWP::JdwpError error;
2740 Thread* thread = DecodeThread(soa, thread_id, &error);
2741 if (error != JDWP::ERR_NONE) {
2742 return error;
2743 }
2744 if (!IsSuspendedForDebugger(soa, thread)) {
2745 return JDWP::ERR_THREAD_NOT_SUSPENDED;
Elliott Hughes221229c2013-01-08 18:17:50 -08002746 }
Sebastien Hertz8009f392014-09-01 17:07:11 +02002747 // Find the frame with the given frame_id.
Ian Rogers700a4022014-05-19 16:49:03 -07002748 std::unique_ptr<Context> context(Context::Create());
Sebastien Hertz8009f392014-09-01 17:07:11 +02002749 FindFrameVisitor visitor(thread, context.get(), frame_id);
Ian Rogers0399dde2012-06-06 17:09:28 -07002750 visitor.WalkStack();
Sebastien Hertz8009f392014-09-01 17:07:11 +02002751 if (visitor.GetError() != JDWP::ERR_NONE) {
2752 return visitor.GetError();
2753 }
2754
2755 // Writes the values into visitor's context.
2756 int32_t slot_count = request->ReadSigned32("slot count");
2757 for (int32_t i = 0; i < slot_count; ++i) {
2758 uint32_t slot = request->ReadUnsigned32("slot");
2759 JDWP::JdwpTag sigByte = request->ReadTag();
2760 size_t width = Dbg::GetTagWidth(sigByte);
2761 uint64_t value = request->ReadValue(width);
2762
2763 VLOG(jdwp) << " --> slot " << slot << " " << sigByte << " " << value;
Sebastien Hertz69206392015-04-07 15:54:25 +02002764 error = Dbg::SetLocalValue(visitor, slot, sigByte, value, width);
Sebastien Hertz8009f392014-09-01 17:07:11 +02002765 if (error != JDWP::ERR_NONE) {
2766 return error;
2767 }
2768 }
2769 return JDWP::ERR_NONE;
2770}
2771
Sebastien Hertzabbabc82015-03-26 08:47:47 +01002772template<typename T>
2773static JDWP::JdwpError FailSetLocalValue(const StackVisitor& visitor, uint16_t vreg,
2774 JDWP::JdwpTag tag, T value)
2775 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
2776 LOG(ERROR) << "Failed to write " << tag << " local " << value
2777 << " (0x" << std::hex << value << ") into register v" << vreg
2778 << GetStackContextAsString(visitor);
2779 return kStackFrameLocalAccessError;
2780}
2781
Sebastien Hertz8009f392014-09-01 17:07:11 +02002782JDWP::JdwpError Dbg::SetLocalValue(StackVisitor& visitor, int slot, JDWP::JdwpTag tag,
2783 uint64_t value, size_t width) {
Mathieu Chartier3d21bdf2015-04-22 13:56:20 -07002784 ArtMethod* m = visitor.GetMethod();
Sebastien Hertzabbabc82015-03-26 08:47:47 +01002785 JDWP::JdwpError error = JDWP::ERR_NONE;
2786 uint16_t vreg = DemangleSlot(slot, m, &error);
2787 if (error != JDWP::ERR_NONE) {
2788 return error;
2789 }
Sebastien Hertz8009f392014-09-01 17:07:11 +02002790 // TODO: check that the tag is compatible with the actual type of the slot!
Sebastien Hertz8009f392014-09-01 17:07:11 +02002791 switch (tag) {
2792 case JDWP::JT_BOOLEAN:
2793 case JDWP::JT_BYTE:
2794 CHECK_EQ(width, 1U);
Sebastien Hertzabbabc82015-03-26 08:47:47 +01002795 if (!visitor.SetVReg(m, vreg, static_cast<uint32_t>(value), kIntVReg)) {
2796 return FailSetLocalValue(visitor, vreg, tag, static_cast<uint32_t>(value));
Sebastien Hertz8009f392014-09-01 17:07:11 +02002797 }
2798 break;
2799 case JDWP::JT_SHORT:
2800 case JDWP::JT_CHAR:
2801 CHECK_EQ(width, 2U);
Sebastien Hertzabbabc82015-03-26 08:47:47 +01002802 if (!visitor.SetVReg(m, vreg, static_cast<uint32_t>(value), kIntVReg)) {
2803 return FailSetLocalValue(visitor, vreg, tag, static_cast<uint32_t>(value));
Sebastien Hertz8009f392014-09-01 17:07:11 +02002804 }
2805 break;
2806 case JDWP::JT_INT:
2807 CHECK_EQ(width, 4U);
Sebastien Hertzabbabc82015-03-26 08:47:47 +01002808 if (!visitor.SetVReg(m, vreg, static_cast<uint32_t>(value), kIntVReg)) {
2809 return FailSetLocalValue(visitor, vreg, tag, static_cast<uint32_t>(value));
Sebastien Hertz8009f392014-09-01 17:07:11 +02002810 }
2811 break;
2812 case JDWP::JT_FLOAT:
2813 CHECK_EQ(width, 4U);
Sebastien Hertzabbabc82015-03-26 08:47:47 +01002814 if (!visitor.SetVReg(m, vreg, static_cast<uint32_t>(value), kFloatVReg)) {
2815 return FailSetLocalValue(visitor, vreg, tag, static_cast<uint32_t>(value));
Sebastien Hertz8009f392014-09-01 17:07:11 +02002816 }
2817 break;
2818 case JDWP::JT_ARRAY:
2819 case JDWP::JT_CLASS_LOADER:
2820 case JDWP::JT_CLASS_OBJECT:
2821 case JDWP::JT_OBJECT:
2822 case JDWP::JT_STRING:
2823 case JDWP::JT_THREAD:
2824 case JDWP::JT_THREAD_GROUP: {
2825 CHECK_EQ(width, sizeof(JDWP::ObjectId));
Sebastien Hertz8009f392014-09-01 17:07:11 +02002826 mirror::Object* o = gRegistry->Get<mirror::Object*>(static_cast<JDWP::ObjectId>(value),
2827 &error);
2828 if (error != JDWP::ERR_NONE) {
2829 VLOG(jdwp) << tag << " object " << o << " is an invalid object";
2830 return JDWP::ERR_INVALID_OBJECT;
Sebastien Hertzabbabc82015-03-26 08:47:47 +01002831 }
2832 if (!visitor.SetVReg(m, vreg, static_cast<uint32_t>(reinterpret_cast<uintptr_t>(o)),
2833 kReferenceVReg)) {
2834 return FailSetLocalValue(visitor, vreg, tag, reinterpret_cast<uintptr_t>(o));
Sebastien Hertz8009f392014-09-01 17:07:11 +02002835 }
2836 break;
2837 }
2838 case JDWP::JT_DOUBLE: {
2839 CHECK_EQ(width, 8U);
Sebastien Hertzabbabc82015-03-26 08:47:47 +01002840 if (!visitor.SetVRegPair(m, vreg, value, kDoubleLoVReg, kDoubleHiVReg)) {
2841 return FailSetLocalValue(visitor, vreg, tag, value);
Sebastien Hertz8009f392014-09-01 17:07:11 +02002842 }
2843 break;
2844 }
2845 case JDWP::JT_LONG: {
2846 CHECK_EQ(width, 8U);
Sebastien Hertzabbabc82015-03-26 08:47:47 +01002847 if (!visitor.SetVRegPair(m, vreg, value, kLongLoVReg, kLongHiVReg)) {
2848 return FailSetLocalValue(visitor, vreg, tag, value);
Sebastien Hertz8009f392014-09-01 17:07:11 +02002849 }
2850 break;
2851 }
2852 default:
2853 LOG(FATAL) << "Unknown tag " << tag;
Sebastien Hertzabbabc82015-03-26 08:47:47 +01002854 UNREACHABLE();
Sebastien Hertz8009f392014-09-01 17:07:11 +02002855 }
2856 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002857}
2858
Mathieu Chartier3d21bdf2015-04-22 13:56:20 -07002859static void SetEventLocation(JDWP::EventLocation* location, ArtMethod* m, uint32_t dex_pc)
Sebastien Hertz6995c602014-09-09 12:10:13 +02002860 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
2861 DCHECK(location != nullptr);
2862 if (m == nullptr) {
2863 memset(location, 0, sizeof(*location));
2864 } else {
2865 location->method = m;
2866 location->dex_pc = (m->IsNative() || m->IsProxyMethod()) ? static_cast<uint32_t>(-1) : dex_pc;
Sebastien Hertz3f52eaf2014-04-04 17:50:18 +02002867 }
Sebastien Hertz3f52eaf2014-04-04 17:50:18 +02002868}
2869
Mathieu Chartier3d21bdf2015-04-22 13:56:20 -07002870void Dbg::PostLocationEvent(ArtMethod* m, int dex_pc, mirror::Object* this_object,
Jeff Hao579b0242013-11-18 13:16:49 -08002871 int event_flags, const JValue* return_value) {
Sebastien Hertz3f52eaf2014-04-04 17:50:18 +02002872 if (!IsDebuggerActive()) {
2873 return;
2874 }
2875 DCHECK(m != nullptr);
2876 DCHECK_EQ(m->IsStatic(), this_object == nullptr);
Sebastien Hertz6995c602014-09-09 12:10:13 +02002877 JDWP::EventLocation location;
2878 SetEventLocation(&location, m, dex_pc);
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08002879
Sebastien Hertz54d65732015-05-26 11:53:39 +02002880 // We need to be sure no exception is pending when calling JdwpState::PostLocationEvent.
2881 // This is required to be able to call JNI functions to create JDWP ids. To achieve this,
2882 // we temporarily clear the current thread's exception (if any) and will restore it after
2883 // the call.
2884 // Note: the only way to get a pending exception here is to suspend on a move-exception
2885 // instruction.
2886 Thread* const self = Thread::Current();
2887 StackHandleScope<1> hs(self);
2888 Handle<mirror::Throwable> pending_exception(hs.NewHandle(self->GetException()));
2889 self->ClearException();
2890 if (kIsDebugBuild && pending_exception.Get() != nullptr) {
2891 const DexFile::CodeItem* code_item = location.method->GetCodeItem();
2892 const Instruction* instr = Instruction::At(&code_item->insns_[location.dex_pc]);
2893 CHECK_EQ(Instruction::MOVE_EXCEPTION, instr->Opcode());
2894 }
2895
Sebastien Hertz6995c602014-09-09 12:10:13 +02002896 gJdwpState->PostLocationEvent(&location, this_object, event_flags, return_value);
Sebastien Hertz54d65732015-05-26 11:53:39 +02002897
2898 if (pending_exception.Get() != nullptr) {
2899 self->SetException(pending_exception.Get());
2900 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002901}
2902
Mathieu Chartier3d21bdf2015-04-22 13:56:20 -07002903void Dbg::PostFieldAccessEvent(ArtMethod* m, int dex_pc,
Mathieu Chartierc7853442015-03-27 14:35:38 -07002904 mirror::Object* this_object, ArtField* f) {
Sebastien Hertz3f52eaf2014-04-04 17:50:18 +02002905 if (!IsDebuggerActive()) {
2906 return;
2907 }
2908 DCHECK(m != nullptr);
2909 DCHECK(f != nullptr);
Sebastien Hertz6995c602014-09-09 12:10:13 +02002910 JDWP::EventLocation location;
2911 SetEventLocation(&location, m, dex_pc);
Sebastien Hertz3f52eaf2014-04-04 17:50:18 +02002912
Sebastien Hertz6995c602014-09-09 12:10:13 +02002913 gJdwpState->PostFieldEvent(&location, f, this_object, nullptr, false);
Sebastien Hertz3f52eaf2014-04-04 17:50:18 +02002914}
2915
Mathieu Chartier3d21bdf2015-04-22 13:56:20 -07002916void Dbg::PostFieldModificationEvent(ArtMethod* m, int dex_pc,
Mathieu Chartierc7853442015-03-27 14:35:38 -07002917 mirror::Object* this_object, ArtField* f,
Sebastien Hertz3f52eaf2014-04-04 17:50:18 +02002918 const JValue* field_value) {
2919 if (!IsDebuggerActive()) {
2920 return;
2921 }
2922 DCHECK(m != nullptr);
2923 DCHECK(f != nullptr);
2924 DCHECK(field_value != nullptr);
Sebastien Hertz6995c602014-09-09 12:10:13 +02002925 JDWP::EventLocation location;
2926 SetEventLocation(&location, m, dex_pc);
Sebastien Hertz3f52eaf2014-04-04 17:50:18 +02002927
Sebastien Hertz6995c602014-09-09 12:10:13 +02002928 gJdwpState->PostFieldEvent(&location, f, this_object, field_value, true);
Sebastien Hertz3f52eaf2014-04-04 17:50:18 +02002929}
2930
Nicolas Geoffray14691c52015-03-05 10:40:17 +00002931/**
2932 * Finds the location where this exception will be caught. We search until we reach the top
2933 * frame, in which case this exception is considered uncaught.
2934 */
2935class CatchLocationFinder : public StackVisitor {
2936 public:
2937 CatchLocationFinder(Thread* self, const Handle<mirror::Throwable>& exception, Context* context)
2938 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_)
Nicolas Geoffray8e5bd182015-05-06 11:34:34 +01002939 : StackVisitor(self, context, StackVisitor::StackWalkKind::kIncludeInlinedFrames),
Nicolas Geoffray14691c52015-03-05 10:40:17 +00002940 self_(self),
2941 exception_(exception),
2942 handle_scope_(self),
2943 this_at_throw_(handle_scope_.NewHandle<mirror::Object>(nullptr)),
Mathieu Chartier3d21bdf2015-04-22 13:56:20 -07002944 catch_method_(nullptr),
2945 throw_method_(nullptr),
Nicolas Geoffray14691c52015-03-05 10:40:17 +00002946 catch_dex_pc_(DexFile::kDexNoIndex),
2947 throw_dex_pc_(DexFile::kDexNoIndex) {
2948 }
2949
2950 bool VisitFrame() OVERRIDE SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Mathieu Chartier3d21bdf2015-04-22 13:56:20 -07002951 ArtMethod* method = GetMethod();
Nicolas Geoffray14691c52015-03-05 10:40:17 +00002952 DCHECK(method != nullptr);
2953 if (method->IsRuntimeMethod()) {
2954 // Ignore callee save method.
2955 DCHECK(method->IsCalleeSaveMethod());
2956 return true;
2957 }
2958
2959 uint32_t dex_pc = GetDexPc();
Mathieu Chartier3d21bdf2015-04-22 13:56:20 -07002960 if (throw_method_ == nullptr) {
Nicolas Geoffray14691c52015-03-05 10:40:17 +00002961 // First Java method found. It is either the method that threw the exception,
2962 // or the Java native method that is reporting an exception thrown by
2963 // native code.
2964 this_at_throw_.Assign(GetThisObject());
Mathieu Chartier3d21bdf2015-04-22 13:56:20 -07002965 throw_method_ = method;
Nicolas Geoffray14691c52015-03-05 10:40:17 +00002966 throw_dex_pc_ = dex_pc;
2967 }
2968
2969 if (dex_pc != DexFile::kDexNoIndex) {
Mathieu Chartier3d21bdf2015-04-22 13:56:20 -07002970 StackHandleScope<1> hs(self_);
Nicolas Geoffray14691c52015-03-05 10:40:17 +00002971 uint32_t found_dex_pc;
2972 Handle<mirror::Class> exception_class(hs.NewHandle(exception_->GetClass()));
Nicolas Geoffray14691c52015-03-05 10:40:17 +00002973 bool unused_clear_exception;
Mathieu Chartier3d21bdf2015-04-22 13:56:20 -07002974 found_dex_pc = method->FindCatchBlock(exception_class, dex_pc, &unused_clear_exception);
Nicolas Geoffray14691c52015-03-05 10:40:17 +00002975 if (found_dex_pc != DexFile::kDexNoIndex) {
Mathieu Chartier3d21bdf2015-04-22 13:56:20 -07002976 catch_method_ = method;
Nicolas Geoffray14691c52015-03-05 10:40:17 +00002977 catch_dex_pc_ = found_dex_pc;
2978 return false; // End stack walk.
2979 }
2980 }
2981 return true; // Continue stack walk.
2982 }
2983
Mathieu Chartier3d21bdf2015-04-22 13:56:20 -07002984 ArtMethod* GetCatchMethod() SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
2985 return catch_method_;
Nicolas Geoffray14691c52015-03-05 10:40:17 +00002986 }
2987
Mathieu Chartier3d21bdf2015-04-22 13:56:20 -07002988 ArtMethod* GetThrowMethod() SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
2989 return throw_method_;
Nicolas Geoffray14691c52015-03-05 10:40:17 +00002990 }
2991
2992 mirror::Object* GetThisAtThrow() SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
2993 return this_at_throw_.Get();
2994 }
2995
2996 uint32_t GetCatchDexPc() const {
2997 return catch_dex_pc_;
2998 }
2999
3000 uint32_t GetThrowDexPc() const {
3001 return throw_dex_pc_;
3002 }
3003
3004 private:
3005 Thread* const self_;
3006 const Handle<mirror::Throwable>& exception_;
Mathieu Chartier3d21bdf2015-04-22 13:56:20 -07003007 StackHandleScope<1> handle_scope_;
Nicolas Geoffray14691c52015-03-05 10:40:17 +00003008 MutableHandle<mirror::Object> this_at_throw_;
Mathieu Chartier3d21bdf2015-04-22 13:56:20 -07003009 ArtMethod* catch_method_;
3010 ArtMethod* throw_method_;
Nicolas Geoffray14691c52015-03-05 10:40:17 +00003011 uint32_t catch_dex_pc_;
3012 uint32_t throw_dex_pc_;
3013
3014 DISALLOW_COPY_AND_ASSIGN(CatchLocationFinder);
3015};
3016
3017void Dbg::PostException(mirror::Throwable* exception_object) {
Elliott Hughesc0f09332012-03-26 13:27:06 -07003018 if (!IsDebuggerActive()) {
Ian Rogers0ad5bb82011-12-07 10:16:32 -08003019 return;
3020 }
Sebastien Hertz66500752015-04-08 09:36:07 +02003021 Thread* const self = Thread::Current();
3022 StackHandleScope<1> handle_scope(self);
Nicolas Geoffray14691c52015-03-05 10:40:17 +00003023 Handle<mirror::Throwable> h_exception(handle_scope.NewHandle(exception_object));
3024 std::unique_ptr<Context> context(Context::Create());
Sebastien Hertz66500752015-04-08 09:36:07 +02003025 CatchLocationFinder clf(self, h_exception, context.get());
Nicolas Geoffray14691c52015-03-05 10:40:17 +00003026 clf.WalkStack(/* include_transitions */ false);
Sebastien Hertz6995c602014-09-09 12:10:13 +02003027 JDWP::EventLocation exception_throw_location;
Nicolas Geoffray14691c52015-03-05 10:40:17 +00003028 SetEventLocation(&exception_throw_location, clf.GetThrowMethod(), clf.GetThrowDexPc());
Sebastien Hertz6995c602014-09-09 12:10:13 +02003029 JDWP::EventLocation exception_catch_location;
Nicolas Geoffray14691c52015-03-05 10:40:17 +00003030 SetEventLocation(&exception_catch_location, clf.GetCatchMethod(), clf.GetCatchDexPc());
Elliott Hughes4740cdf2011-12-07 14:07:12 -08003031
Nicolas Geoffray14691c52015-03-05 10:40:17 +00003032 gJdwpState->PostException(&exception_throw_location, h_exception.Get(), &exception_catch_location,
3033 clf.GetThisAtThrow());
Elliott Hughes872d4ec2011-10-21 17:07:15 -07003034}
3035
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003036void Dbg::PostClassPrepare(mirror::Class* c) {
Elliott Hughesc0f09332012-03-26 13:27:06 -07003037 if (!IsDebuggerActive()) {
Elliott Hughes4740cdf2011-12-07 14:07:12 -08003038 return;
3039 }
Sebastien Hertz6995c602014-09-09 12:10:13 +02003040 gJdwpState->PostClassPrepare(c);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07003041}
3042
Ian Rogers62d6c772013-02-27 08:32:07 -08003043void Dbg::UpdateDebugger(Thread* thread, mirror::Object* this_object,
Mathieu Chartier3d21bdf2015-04-22 13:56:20 -07003044 ArtMethod* m, uint32_t dex_pc,
Sebastien Hertz8379b222014-02-24 17:38:15 +01003045 int event_flags, const JValue* return_value) {
Ian Rogers62d6c772013-02-27 08:32:07 -08003046 if (!IsDebuggerActive() || dex_pc == static_cast<uint32_t>(-2) /* fake method exit */) {
Elliott Hughes2aa2e392012-02-17 17:15:43 -08003047 return;
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08003048 }
3049
Elliott Hughes86964332012-02-15 19:37:42 -08003050 if (IsBreakpoint(m, dex_pc)) {
3051 event_flags |= kBreakpoint;
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08003052 }
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08003053
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01003054 // If the debugger is single-stepping one of our threads, check to
3055 // see if we're that thread and we've reached a step point.
3056 const SingleStepControl* single_step_control = thread->GetSingleStepControl();
Sebastien Hertz597c4f02015-01-26 17:37:14 +01003057 if (single_step_control != nullptr) {
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01003058 CHECK(!m->IsNative());
Sebastien Hertz597c4f02015-01-26 17:37:14 +01003059 if (single_step_control->GetStepDepth() == JDWP::SD_INTO) {
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01003060 // Step into method calls. We break when the line number
3061 // or method pointer changes. If we're in SS_MIN mode, we
3062 // always stop.
Sebastien Hertz597c4f02015-01-26 17:37:14 +01003063 if (single_step_control->GetMethod() != m) {
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01003064 event_flags |= kSingleStep;
3065 VLOG(jdwp) << "SS new method";
Sebastien Hertz597c4f02015-01-26 17:37:14 +01003066 } else if (single_step_control->GetStepSize() == JDWP::SS_MIN) {
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01003067 event_flags |= kSingleStep;
3068 VLOG(jdwp) << "SS new instruction";
Sebastien Hertzbb43b432014-04-14 11:59:08 +02003069 } else if (single_step_control->ContainsDexPc(dex_pc)) {
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01003070 event_flags |= kSingleStep;
3071 VLOG(jdwp) << "SS new line";
3072 }
Sebastien Hertz597c4f02015-01-26 17:37:14 +01003073 } else if (single_step_control->GetStepDepth() == JDWP::SD_OVER) {
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01003074 // Step over method calls. We break when the line number is
3075 // different and the frame depth is <= the original frame
3076 // depth. (We can't just compare on the method, because we
3077 // might get unrolled past it by an exception, and it's tricky
3078 // to identify recursion.)
3079
3080 int stack_depth = GetStackDepth(thread);
3081
Sebastien Hertz597c4f02015-01-26 17:37:14 +01003082 if (stack_depth < single_step_control->GetStackDepth()) {
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01003083 // Popped up one or more frames, always trigger.
3084 event_flags |= kSingleStep;
3085 VLOG(jdwp) << "SS method pop";
Sebastien Hertz597c4f02015-01-26 17:37:14 +01003086 } else if (stack_depth == single_step_control->GetStackDepth()) {
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01003087 // Same depth, see if we moved.
Sebastien Hertz597c4f02015-01-26 17:37:14 +01003088 if (single_step_control->GetStepSize() == JDWP::SS_MIN) {
Elliott Hughes86964332012-02-15 19:37:42 -08003089 event_flags |= kSingleStep;
3090 VLOG(jdwp) << "SS new instruction";
Sebastien Hertzbb43b432014-04-14 11:59:08 +02003091 } else if (single_step_control->ContainsDexPc(dex_pc)) {
Elliott Hughes2435a572012-02-17 16:07:41 -08003092 event_flags |= kSingleStep;
3093 VLOG(jdwp) << "SS new line";
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08003094 }
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01003095 }
3096 } else {
Sebastien Hertz597c4f02015-01-26 17:37:14 +01003097 CHECK_EQ(single_step_control->GetStepDepth(), JDWP::SD_OUT);
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01003098 // Return from the current method. We break when the frame
3099 // depth pops up.
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08003100
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01003101 // This differs from the "method exit" break in that it stops
3102 // with the PC at the next instruction in the returned-to
3103 // function, rather than the end of the returning function.
Elliott Hughes86964332012-02-15 19:37:42 -08003104
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01003105 int stack_depth = GetStackDepth(thread);
Sebastien Hertz597c4f02015-01-26 17:37:14 +01003106 if (stack_depth < single_step_control->GetStackDepth()) {
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01003107 event_flags |= kSingleStep;
3108 VLOG(jdwp) << "SS method pop";
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08003109 }
3110 }
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08003111 }
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08003112
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08003113 // If there's something interesting going on, see if it matches one
3114 // of the debugger filters.
3115 if (event_flags != 0) {
Sebastien Hertz8379b222014-02-24 17:38:15 +01003116 Dbg::PostLocationEvent(m, dex_pc, this_object, event_flags, return_value);
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08003117 }
3118}
3119
Sebastien Hertz42cd43f2014-05-13 14:15:41 +02003120size_t* Dbg::GetReferenceCounterForEvent(uint32_t instrumentation_event) {
3121 switch (instrumentation_event) {
3122 case instrumentation::Instrumentation::kMethodEntered:
3123 return &method_enter_event_ref_count_;
3124 case instrumentation::Instrumentation::kMethodExited:
3125 return &method_exit_event_ref_count_;
3126 case instrumentation::Instrumentation::kDexPcMoved:
3127 return &dex_pc_change_event_ref_count_;
3128 case instrumentation::Instrumentation::kFieldRead:
3129 return &field_read_event_ref_count_;
3130 case instrumentation::Instrumentation::kFieldWritten:
3131 return &field_write_event_ref_count_;
3132 case instrumentation::Instrumentation::kExceptionCaught:
3133 return &exception_catch_event_ref_count_;
3134 default:
3135 return nullptr;
3136 }
3137}
3138
Sebastien Hertz4d25df32014-03-21 17:44:46 +01003139// Process request while all mutator threads are suspended.
3140void Dbg::ProcessDeoptimizationRequest(const DeoptimizationRequest& request) {
Sebastien Hertz138dbfc2013-12-04 18:15:25 +01003141 instrumentation::Instrumentation* instrumentation = Runtime::Current()->GetInstrumentation();
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003142 switch (request.GetKind()) {
Sebastien Hertz4d25df32014-03-21 17:44:46 +01003143 case DeoptimizationRequest::kNothing:
3144 LOG(WARNING) << "Ignoring empty deoptimization request.";
3145 break;
Sebastien Hertz42cd43f2014-05-13 14:15:41 +02003146 case DeoptimizationRequest::kRegisterForEvent:
3147 VLOG(jdwp) << StringPrintf("Add debugger as listener for instrumentation event 0x%x",
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003148 request.InstrumentationEvent());
3149 instrumentation->AddListener(&gDebugInstrumentationListener, request.InstrumentationEvent());
3150 instrumentation_events_ |= request.InstrumentationEvent();
Sebastien Hertz42cd43f2014-05-13 14:15:41 +02003151 break;
3152 case DeoptimizationRequest::kUnregisterForEvent:
3153 VLOG(jdwp) << StringPrintf("Remove debugger as listener for instrumentation event 0x%x",
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003154 request.InstrumentationEvent());
Sebastien Hertz42cd43f2014-05-13 14:15:41 +02003155 instrumentation->RemoveListener(&gDebugInstrumentationListener,
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003156 request.InstrumentationEvent());
3157 instrumentation_events_ &= ~request.InstrumentationEvent();
Sebastien Hertz42cd43f2014-05-13 14:15:41 +02003158 break;
Sebastien Hertz4d25df32014-03-21 17:44:46 +01003159 case DeoptimizationRequest::kFullDeoptimization:
Sebastien Hertz7ec2f1c2014-03-27 20:06:47 +01003160 VLOG(jdwp) << "Deoptimize the world ...";
Sebastien Hertz0462c4c2015-04-01 16:34:17 +02003161 instrumentation->DeoptimizeEverything(kDbgInstrumentationKey);
Sebastien Hertz7ec2f1c2014-03-27 20:06:47 +01003162 VLOG(jdwp) << "Deoptimize the world DONE";
Sebastien Hertz4d25df32014-03-21 17:44:46 +01003163 break;
3164 case DeoptimizationRequest::kFullUndeoptimization:
Sebastien Hertz7ec2f1c2014-03-27 20:06:47 +01003165 VLOG(jdwp) << "Undeoptimize the world ...";
Sebastien Hertz0462c4c2015-04-01 16:34:17 +02003166 instrumentation->UndeoptimizeEverything(kDbgInstrumentationKey);
Sebastien Hertz7ec2f1c2014-03-27 20:06:47 +01003167 VLOG(jdwp) << "Undeoptimize the world DONE";
Sebastien Hertz4d25df32014-03-21 17:44:46 +01003168 break;
3169 case DeoptimizationRequest::kSelectiveDeoptimization:
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003170 VLOG(jdwp) << "Deoptimize method " << PrettyMethod(request.Method()) << " ...";
3171 instrumentation->Deoptimize(request.Method());
3172 VLOG(jdwp) << "Deoptimize method " << PrettyMethod(request.Method()) << " DONE";
Sebastien Hertz4d25df32014-03-21 17:44:46 +01003173 break;
3174 case DeoptimizationRequest::kSelectiveUndeoptimization:
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003175 VLOG(jdwp) << "Undeoptimize method " << PrettyMethod(request.Method()) << " ...";
3176 instrumentation->Undeoptimize(request.Method());
3177 VLOG(jdwp) << "Undeoptimize method " << PrettyMethod(request.Method()) << " DONE";
Sebastien Hertz4d25df32014-03-21 17:44:46 +01003178 break;
3179 default:
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003180 LOG(FATAL) << "Unsupported deoptimization request kind " << request.GetKind();
Sebastien Hertz4d25df32014-03-21 17:44:46 +01003181 break;
Sebastien Hertz138dbfc2013-12-04 18:15:25 +01003182 }
Sebastien Hertz138dbfc2013-12-04 18:15:25 +01003183}
3184
Sebastien Hertz4d25df32014-03-21 17:44:46 +01003185void Dbg::RequestDeoptimization(const DeoptimizationRequest& req) {
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003186 if (req.GetKind() == DeoptimizationRequest::kNothing) {
Sebastien Hertz4d25df32014-03-21 17:44:46 +01003187 // Nothing to do.
3188 return;
3189 }
Brian Carlstrom306db812014-09-05 13:01:41 -07003190 MutexLock mu(Thread::Current(), *Locks::deoptimization_lock_);
Sebastien Hertz7ec2f1c2014-03-27 20:06:47 +01003191 RequestDeoptimizationLocked(req);
3192}
3193
3194void Dbg::RequestDeoptimizationLocked(const DeoptimizationRequest& req) {
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003195 switch (req.GetKind()) {
Sebastien Hertz42cd43f2014-05-13 14:15:41 +02003196 case DeoptimizationRequest::kRegisterForEvent: {
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003197 DCHECK_NE(req.InstrumentationEvent(), 0u);
3198 size_t* counter = GetReferenceCounterForEvent(req.InstrumentationEvent());
Sebastien Hertz42cd43f2014-05-13 14:15:41 +02003199 CHECK(counter != nullptr) << StringPrintf("No counter for instrumentation event 0x%x",
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003200 req.InstrumentationEvent());
Sebastien Hertz42cd43f2014-05-13 14:15:41 +02003201 if (*counter == 0) {
Sebastien Hertz7d2ae432014-05-15 11:26:34 +02003202 VLOG(jdwp) << StringPrintf("Queue request #%zd to start listening to instrumentation event 0x%x",
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003203 deoptimization_requests_.size(), req.InstrumentationEvent());
Sebastien Hertz42cd43f2014-05-13 14:15:41 +02003204 deoptimization_requests_.push_back(req);
3205 }
3206 *counter = *counter + 1;
3207 break;
3208 }
3209 case DeoptimizationRequest::kUnregisterForEvent: {
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003210 DCHECK_NE(req.InstrumentationEvent(), 0u);
3211 size_t* counter = GetReferenceCounterForEvent(req.InstrumentationEvent());
Sebastien Hertz42cd43f2014-05-13 14:15:41 +02003212 CHECK(counter != nullptr) << StringPrintf("No counter for instrumentation event 0x%x",
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003213 req.InstrumentationEvent());
Sebastien Hertz42cd43f2014-05-13 14:15:41 +02003214 *counter = *counter - 1;
3215 if (*counter == 0) {
Sebastien Hertz7d2ae432014-05-15 11:26:34 +02003216 VLOG(jdwp) << StringPrintf("Queue request #%zd to stop listening to instrumentation event 0x%x",
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003217 deoptimization_requests_.size(), req.InstrumentationEvent());
Sebastien Hertz42cd43f2014-05-13 14:15:41 +02003218 deoptimization_requests_.push_back(req);
3219 }
3220 break;
3221 }
Sebastien Hertz4d25df32014-03-21 17:44:46 +01003222 case DeoptimizationRequest::kFullDeoptimization: {
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003223 DCHECK(req.Method() == nullptr);
Sebastien Hertz4d25df32014-03-21 17:44:46 +01003224 if (full_deoptimization_event_count_ == 0) {
Sebastien Hertz7ec2f1c2014-03-27 20:06:47 +01003225 VLOG(jdwp) << "Queue request #" << deoptimization_requests_.size()
3226 << " for full deoptimization";
Sebastien Hertz4d25df32014-03-21 17:44:46 +01003227 deoptimization_requests_.push_back(req);
3228 }
3229 ++full_deoptimization_event_count_;
3230 break;
3231 }
3232 case DeoptimizationRequest::kFullUndeoptimization: {
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003233 DCHECK(req.Method() == nullptr);
Sebastien Hertze713d932014-05-15 10:48:53 +02003234 DCHECK_GT(full_deoptimization_event_count_, 0U);
Sebastien Hertz4d25df32014-03-21 17:44:46 +01003235 --full_deoptimization_event_count_;
3236 if (full_deoptimization_event_count_ == 0) {
Sebastien Hertz7ec2f1c2014-03-27 20:06:47 +01003237 VLOG(jdwp) << "Queue request #" << deoptimization_requests_.size()
3238 << " for full undeoptimization";
Sebastien Hertz4d25df32014-03-21 17:44:46 +01003239 deoptimization_requests_.push_back(req);
3240 }
3241 break;
3242 }
3243 case DeoptimizationRequest::kSelectiveDeoptimization: {
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003244 DCHECK(req.Method() != nullptr);
Sebastien Hertz7ec2f1c2014-03-27 20:06:47 +01003245 VLOG(jdwp) << "Queue request #" << deoptimization_requests_.size()
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003246 << " for deoptimization of " << PrettyMethod(req.Method());
Sebastien Hertz4d25df32014-03-21 17:44:46 +01003247 deoptimization_requests_.push_back(req);
3248 break;
3249 }
3250 case DeoptimizationRequest::kSelectiveUndeoptimization: {
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003251 DCHECK(req.Method() != nullptr);
Sebastien Hertz7ec2f1c2014-03-27 20:06:47 +01003252 VLOG(jdwp) << "Queue request #" << deoptimization_requests_.size()
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003253 << " for undeoptimization of " << PrettyMethod(req.Method());
Sebastien Hertz4d25df32014-03-21 17:44:46 +01003254 deoptimization_requests_.push_back(req);
3255 break;
3256 }
3257 default: {
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003258 LOG(FATAL) << "Unknown deoptimization request kind " << req.GetKind();
Sebastien Hertz4d25df32014-03-21 17:44:46 +01003259 break;
3260 }
3261 }
3262}
3263
Sebastien Hertz138dbfc2013-12-04 18:15:25 +01003264void Dbg::ManageDeoptimization() {
3265 Thread* const self = Thread::Current();
3266 {
3267 // Avoid suspend/resume if there is no pending request.
Brian Carlstrom306db812014-09-05 13:01:41 -07003268 MutexLock mu(self, *Locks::deoptimization_lock_);
Sebastien Hertz4d25df32014-03-21 17:44:46 +01003269 if (deoptimization_requests_.empty()) {
Sebastien Hertz138dbfc2013-12-04 18:15:25 +01003270 return;
3271 }
3272 }
3273 CHECK_EQ(self->GetState(), kRunnable);
3274 self->TransitionFromRunnableToSuspended(kWaitingForDeoptimization);
3275 // We need to suspend mutator threads first.
3276 Runtime* const runtime = Runtime::Current();
Mathieu Chartierbf9fc582015-03-13 17:21:25 -07003277 runtime->GetThreadList()->SuspendAll(__FUNCTION__);
Sebastien Hertz138dbfc2013-12-04 18:15:25 +01003278 const ThreadState old_state = self->SetStateUnsafe(kRunnable);
Sebastien Hertz4d25df32014-03-21 17:44:46 +01003279 {
Brian Carlstrom306db812014-09-05 13:01:41 -07003280 MutexLock mu(self, *Locks::deoptimization_lock_);
Sebastien Hertz7ec2f1c2014-03-27 20:06:47 +01003281 size_t req_index = 0;
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003282 for (DeoptimizationRequest& request : deoptimization_requests_) {
Sebastien Hertz7ec2f1c2014-03-27 20:06:47 +01003283 VLOG(jdwp) << "Process deoptimization request #" << req_index++;
Sebastien Hertz4d25df32014-03-21 17:44:46 +01003284 ProcessDeoptimizationRequest(request);
3285 }
3286 deoptimization_requests_.clear();
3287 }
Sebastien Hertz138dbfc2013-12-04 18:15:25 +01003288 CHECK_EQ(self->SetStateUnsafe(old_state), kRunnable);
3289 runtime->GetThreadList()->ResumeAll();
3290 self->TransitionFromSuspendedToRunnable();
3291}
3292
Mathieu Chartier3d21bdf2015-04-22 13:56:20 -07003293static bool IsMethodPossiblyInlined(Thread* self, ArtMethod* m)
Sebastien Hertza76a6d42014-03-20 16:40:17 +01003294 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07003295 const DexFile::CodeItem* code_item = m->GetCodeItem();
Sebastien Hertza76a6d42014-03-20 16:40:17 +01003296 if (code_item == nullptr) {
3297 // TODO We should not be asked to watch location in a native or abstract method so the code item
3298 // should never be null. We could just check we never encounter this case.
3299 return false;
Sebastien Hertz138dbfc2013-12-04 18:15:25 +01003300 }
Sebastien Hertz4d1e9ab2014-09-18 16:03:34 +02003301 // Note: method verifier may cause thread suspension.
3302 self->AssertThreadSuspensionIsAllowable();
Mathieu Chartier3d21bdf2015-04-22 13:56:20 -07003303 StackHandleScope<2> hs(self);
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07003304 mirror::Class* declaring_class = m->GetDeclaringClass();
3305 Handle<mirror::DexCache> dex_cache(hs.NewHandle(declaring_class->GetDexCache()));
3306 Handle<mirror::ClassLoader> class_loader(hs.NewHandle(declaring_class->GetClassLoader()));
Ian Rogers7b078e82014-09-10 14:44:24 -07003307 verifier::MethodVerifier verifier(self, dex_cache->GetDexFile(), dex_cache, class_loader,
Mathieu Chartier3d21bdf2015-04-22 13:56:20 -07003308 &m->GetClassDef(), code_item, m->GetDexMethodIndex(), m,
Mathieu Chartier4306ef82014-12-19 18:41:47 -08003309 m->GetAccessFlags(), false, true, false, true);
Sebastien Hertza76a6d42014-03-20 16:40:17 +01003310 // Note: we don't need to verify the method.
3311 return InlineMethodAnalyser::AnalyseMethodCode(&verifier, nullptr);
3312}
Sebastien Hertz138dbfc2013-12-04 18:15:25 +01003313
Mathieu Chartier3d21bdf2015-04-22 13:56:20 -07003314static const Breakpoint* FindFirstBreakpointForMethod(ArtMethod* m)
Sebastien Hertzed2be172014-08-19 15:33:43 +02003315 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_, Locks::breakpoint_lock_) {
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003316 for (Breakpoint& breakpoint : gBreakpoints) {
3317 if (breakpoint.Method() == m) {
Sebastien Hertza76a6d42014-03-20 16:40:17 +01003318 return &breakpoint;
3319 }
3320 }
3321 return nullptr;
3322}
3323
Mathieu Chartier3d21bdf2015-04-22 13:56:20 -07003324bool Dbg::MethodHasAnyBreakpoints(ArtMethod* method) {
Mathieu Chartierd8565452015-03-26 09:41:50 -07003325 ReaderMutexLock mu(Thread::Current(), *Locks::breakpoint_lock_);
3326 return FindFirstBreakpointForMethod(method) != nullptr;
3327}
3328
Sebastien Hertza76a6d42014-03-20 16:40:17 +01003329// Sanity checks all existing breakpoints on the same method.
Mathieu Chartier3d21bdf2015-04-22 13:56:20 -07003330static void SanityCheckExistingBreakpoints(ArtMethod* m,
Sebastien Hertzf3928792014-11-17 19:00:37 +01003331 DeoptimizationRequest::Kind deoptimization_kind)
Sebastien Hertzed2be172014-08-19 15:33:43 +02003332 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_, Locks::breakpoint_lock_) {
Sebastien Hertz4d1e9ab2014-09-18 16:03:34 +02003333 for (const Breakpoint& breakpoint : gBreakpoints) {
Sebastien Hertzf3928792014-11-17 19:00:37 +01003334 if (breakpoint.Method() == m) {
3335 CHECK_EQ(deoptimization_kind, breakpoint.GetDeoptimizationKind());
3336 }
Sebastien Hertz4d1e9ab2014-09-18 16:03:34 +02003337 }
Sebastien Hertzf3928792014-11-17 19:00:37 +01003338 instrumentation::Instrumentation* instrumentation = Runtime::Current()->GetInstrumentation();
3339 if (deoptimization_kind == DeoptimizationRequest::kFullDeoptimization) {
Sebastien Hertz4d1e9ab2014-09-18 16:03:34 +02003340 // We should have deoptimized everything but not "selectively" deoptimized this method.
Sebastien Hertzf3928792014-11-17 19:00:37 +01003341 CHECK(instrumentation->AreAllMethodsDeoptimized());
3342 CHECK(!instrumentation->IsDeoptimized(m));
3343 } else if (deoptimization_kind == DeoptimizationRequest::kSelectiveDeoptimization) {
Sebastien Hertz4d1e9ab2014-09-18 16:03:34 +02003344 // We should have "selectively" deoptimized this method.
3345 // Note: while we have not deoptimized everything for this method, we may have done it for
3346 // another event.
Sebastien Hertzf3928792014-11-17 19:00:37 +01003347 CHECK(instrumentation->IsDeoptimized(m));
3348 } else {
3349 // This method does not require deoptimization.
3350 CHECK_EQ(deoptimization_kind, DeoptimizationRequest::kNothing);
3351 CHECK(!instrumentation->IsDeoptimized(m));
3352 }
3353}
3354
Sebastien Hertzabe93e02014-12-17 16:35:50 +01003355// Returns the deoptimization kind required to set a breakpoint in a method.
3356// If a breakpoint has already been set, we also return the first breakpoint
3357// through the given 'existing_brkpt' pointer.
Sebastien Hertzf3928792014-11-17 19:00:37 +01003358static DeoptimizationRequest::Kind GetRequiredDeoptimizationKind(Thread* self,
Mathieu Chartier3d21bdf2015-04-22 13:56:20 -07003359 ArtMethod* m,
Sebastien Hertzabe93e02014-12-17 16:35:50 +01003360 const Breakpoint** existing_brkpt)
Sebastien Hertzf3928792014-11-17 19:00:37 +01003361 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
3362 if (!Dbg::RequiresDeoptimization()) {
3363 // We already run in interpreter-only mode so we don't need to deoptimize anything.
3364 VLOG(jdwp) << "No need for deoptimization when fully running with interpreter for method "
3365 << PrettyMethod(m);
3366 return DeoptimizationRequest::kNothing;
3367 }
Sebastien Hertzabe93e02014-12-17 16:35:50 +01003368 const Breakpoint* first_breakpoint;
Sebastien Hertzf3928792014-11-17 19:00:37 +01003369 {
3370 ReaderMutexLock mu(self, *Locks::breakpoint_lock_);
Sebastien Hertzabe93e02014-12-17 16:35:50 +01003371 first_breakpoint = FindFirstBreakpointForMethod(m);
3372 *existing_brkpt = first_breakpoint;
Sebastien Hertzf3928792014-11-17 19:00:37 +01003373 }
Sebastien Hertzabe93e02014-12-17 16:35:50 +01003374
3375 if (first_breakpoint == nullptr) {
Sebastien Hertzf3928792014-11-17 19:00:37 +01003376 // There is no breakpoint on this method yet: we need to deoptimize. If this method may be
3377 // inlined, we deoptimize everything; otherwise we deoptimize only this method.
3378 // Note: IsMethodPossiblyInlined goes into the method verifier and may cause thread suspension.
3379 // Therefore we must not hold any lock when we call it.
3380 bool need_full_deoptimization = IsMethodPossiblyInlined(self, m);
3381 if (need_full_deoptimization) {
3382 VLOG(jdwp) << "Need full deoptimization because of possible inlining of method "
3383 << PrettyMethod(m);
3384 return DeoptimizationRequest::kFullDeoptimization;
3385 } else {
3386 // We don't need to deoptimize if the method has not been compiled.
3387 ClassLinker* const class_linker = Runtime::Current()->GetClassLinker();
3388 const bool is_compiled = class_linker->GetOatMethodQuickCodeFor(m) != nullptr;
3389 if (is_compiled) {
Sebastien Hertz6963e442014-11-26 22:11:27 +01003390 // If the method may be called through its direct code pointer (without loading
3391 // its updated entrypoint), we need full deoptimization to not miss the breakpoint.
3392 if (class_linker->MayBeCalledWithDirectCodePointer(m)) {
3393 VLOG(jdwp) << "Need full deoptimization because of possible direct code call "
3394 << "into image for compiled method " << PrettyMethod(m);
3395 return DeoptimizationRequest::kFullDeoptimization;
3396 } else {
3397 VLOG(jdwp) << "Need selective deoptimization for compiled method " << PrettyMethod(m);
3398 return DeoptimizationRequest::kSelectiveDeoptimization;
3399 }
Sebastien Hertzf3928792014-11-17 19:00:37 +01003400 } else {
3401 // Method is not compiled: we don't need to deoptimize.
3402 VLOG(jdwp) << "No need for deoptimization for non-compiled method " << PrettyMethod(m);
3403 return DeoptimizationRequest::kNothing;
3404 }
3405 }
3406 } else {
3407 // There is at least one breakpoint for this method: we don't need to deoptimize.
3408 // Let's check that all breakpoints are configured the same way for deoptimization.
3409 VLOG(jdwp) << "Breakpoint already set: no deoptimization is required";
Sebastien Hertzabe93e02014-12-17 16:35:50 +01003410 DeoptimizationRequest::Kind deoptimization_kind = first_breakpoint->GetDeoptimizationKind();
Sebastien Hertzf3928792014-11-17 19:00:37 +01003411 if (kIsDebugBuild) {
3412 ReaderMutexLock mu(self, *Locks::breakpoint_lock_);
3413 SanityCheckExistingBreakpoints(m, deoptimization_kind);
3414 }
3415 return DeoptimizationRequest::kNothing;
Sebastien Hertz138dbfc2013-12-04 18:15:25 +01003416 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -07003417}
3418
Sebastien Hertza76a6d42014-03-20 16:40:17 +01003419// Installs a breakpoint at the specified location. Also indicates through the deoptimization
3420// request if we need to deoptimize.
3421void Dbg::WatchLocation(const JDWP::JdwpLocation* location, DeoptimizationRequest* req) {
3422 Thread* const self = Thread::Current();
Mathieu Chartier3d21bdf2015-04-22 13:56:20 -07003423 ArtMethod* m = FromMethodId(location->method_id);
Sebastien Hertza76a6d42014-03-20 16:40:17 +01003424 DCHECK(m != nullptr) << "No method for method id " << location->method_id;
Sebastien Hertz138dbfc2013-12-04 18:15:25 +01003425
Sebastien Hertzabe93e02014-12-17 16:35:50 +01003426 const Breakpoint* existing_breakpoint = nullptr;
3427 const DeoptimizationRequest::Kind deoptimization_kind =
3428 GetRequiredDeoptimizationKind(self, m, &existing_breakpoint);
Sebastien Hertzf3928792014-11-17 19:00:37 +01003429 req->SetKind(deoptimization_kind);
3430 if (deoptimization_kind == DeoptimizationRequest::kSelectiveDeoptimization) {
3431 req->SetMethod(m);
Sebastien Hertza76a6d42014-03-20 16:40:17 +01003432 } else {
Sebastien Hertzf3928792014-11-17 19:00:37 +01003433 CHECK(deoptimization_kind == DeoptimizationRequest::kNothing ||
3434 deoptimization_kind == DeoptimizationRequest::kFullDeoptimization);
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003435 req->SetMethod(nullptr);
Sebastien Hertz138dbfc2013-12-04 18:15:25 +01003436 }
3437
Sebastien Hertz4d1e9ab2014-09-18 16:03:34 +02003438 {
3439 WriterMutexLock mu(self, *Locks::breakpoint_lock_);
Sebastien Hertzabe93e02014-12-17 16:35:50 +01003440 // If there is at least one existing breakpoint on the same method, the new breakpoint
3441 // must have the same deoptimization kind than the existing breakpoint(s).
3442 DeoptimizationRequest::Kind breakpoint_deoptimization_kind;
3443 if (existing_breakpoint != nullptr) {
3444 breakpoint_deoptimization_kind = existing_breakpoint->GetDeoptimizationKind();
3445 } else {
3446 breakpoint_deoptimization_kind = deoptimization_kind;
3447 }
3448 gBreakpoints.push_back(Breakpoint(m, location->dex_pc, breakpoint_deoptimization_kind));
Sebastien Hertz4d1e9ab2014-09-18 16:03:34 +02003449 VLOG(jdwp) << "Set breakpoint #" << (gBreakpoints.size() - 1) << ": "
3450 << gBreakpoints[gBreakpoints.size() - 1];
3451 }
Sebastien Hertza76a6d42014-03-20 16:40:17 +01003452}
3453
3454// Uninstalls a breakpoint at the specified location. Also indicates through the deoptimization
3455// request if we need to undeoptimize.
3456void Dbg::UnwatchLocation(const JDWP::JdwpLocation* location, DeoptimizationRequest* req) {
Sebastien Hertzed2be172014-08-19 15:33:43 +02003457 WriterMutexLock mu(Thread::Current(), *Locks::breakpoint_lock_);
Mathieu Chartier3d21bdf2015-04-22 13:56:20 -07003458 ArtMethod* m = FromMethodId(location->method_id);
Sebastien Hertza76a6d42014-03-20 16:40:17 +01003459 DCHECK(m != nullptr) << "No method for method id " << location->method_id;
Sebastien Hertzf3928792014-11-17 19:00:37 +01003460 DeoptimizationRequest::Kind deoptimization_kind = DeoptimizationRequest::kNothing;
Sebastien Hertza76a6d42014-03-20 16:40:17 +01003461 for (size_t i = 0, e = gBreakpoints.size(); i < e; ++i) {
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003462 if (gBreakpoints[i].DexPc() == location->dex_pc && gBreakpoints[i].Method() == m) {
Sebastien Hertza76a6d42014-03-20 16:40:17 +01003463 VLOG(jdwp) << "Removed breakpoint #" << i << ": " << gBreakpoints[i];
Sebastien Hertzf3928792014-11-17 19:00:37 +01003464 deoptimization_kind = gBreakpoints[i].GetDeoptimizationKind();
3465 DCHECK_EQ(deoptimization_kind == DeoptimizationRequest::kSelectiveDeoptimization,
3466 Runtime::Current()->GetInstrumentation()->IsDeoptimized(m));
Sebastien Hertza76a6d42014-03-20 16:40:17 +01003467 gBreakpoints.erase(gBreakpoints.begin() + i);
3468 break;
3469 }
3470 }
3471 const Breakpoint* const existing_breakpoint = FindFirstBreakpointForMethod(m);
3472 if (existing_breakpoint == nullptr) {
3473 // There is no more breakpoint on this method: we need to undeoptimize.
Sebastien Hertzf3928792014-11-17 19:00:37 +01003474 if (deoptimization_kind == DeoptimizationRequest::kFullDeoptimization) {
Sebastien Hertza76a6d42014-03-20 16:40:17 +01003475 // This method required full deoptimization: we need to undeoptimize everything.
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003476 req->SetKind(DeoptimizationRequest::kFullUndeoptimization);
3477 req->SetMethod(nullptr);
Sebastien Hertzf3928792014-11-17 19:00:37 +01003478 } else if (deoptimization_kind == DeoptimizationRequest::kSelectiveDeoptimization) {
Sebastien Hertza76a6d42014-03-20 16:40:17 +01003479 // This method required selective deoptimization: we need to undeoptimize only that method.
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003480 req->SetKind(DeoptimizationRequest::kSelectiveUndeoptimization);
3481 req->SetMethod(m);
Sebastien Hertzf3928792014-11-17 19:00:37 +01003482 } else {
3483 // This method had no need for deoptimization: do nothing.
3484 CHECK_EQ(deoptimization_kind, DeoptimizationRequest::kNothing);
3485 req->SetKind(DeoptimizationRequest::kNothing);
3486 req->SetMethod(nullptr);
Sebastien Hertza76a6d42014-03-20 16:40:17 +01003487 }
3488 } else {
3489 // There is at least one breakpoint for this method: we don't need to undeoptimize.
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003490 req->SetKind(DeoptimizationRequest::kNothing);
3491 req->SetMethod(nullptr);
Sebastien Hertz4d1e9ab2014-09-18 16:03:34 +02003492 if (kIsDebugBuild) {
Sebastien Hertzf3928792014-11-17 19:00:37 +01003493 SanityCheckExistingBreakpoints(m, deoptimization_kind);
Sebastien Hertz4d1e9ab2014-09-18 16:03:34 +02003494 }
Elliott Hughes86964332012-02-15 19:37:42 -08003495 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -07003496}
3497
Mathieu Chartier3d21bdf2015-04-22 13:56:20 -07003498bool Dbg::IsForcedInterpreterNeededForCallingImpl(Thread* thread, ArtMethod* m) {
Daniel Mihalyieb076692014-08-22 17:33:31 +02003499 const SingleStepControl* const ssc = thread->GetSingleStepControl();
3500 if (ssc == nullptr) {
3501 // If we are not single-stepping, then we don't have to force interpreter.
3502 return false;
3503 }
3504 if (Runtime::Current()->GetInstrumentation()->InterpretOnly()) {
3505 // If we are in interpreter only mode, then we don't have to force interpreter.
3506 return false;
3507 }
3508
3509 if (!m->IsNative() && !m->IsProxyMethod()) {
3510 // If we want to step into a method, then we have to force interpreter on that call.
3511 if (ssc->GetStepDepth() == JDWP::SD_INTO) {
3512 return true;
3513 }
3514 }
3515 return false;
3516}
3517
Mathieu Chartier3d21bdf2015-04-22 13:56:20 -07003518bool Dbg::IsForcedInterpreterNeededForResolutionImpl(Thread* thread, ArtMethod* m) {
Daniel Mihalyieb076692014-08-22 17:33:31 +02003519 instrumentation::Instrumentation* const instrumentation =
3520 Runtime::Current()->GetInstrumentation();
3521 // If we are in interpreter only mode, then we don't have to force interpreter.
3522 if (instrumentation->InterpretOnly()) {
3523 return false;
3524 }
3525 // We can only interpret pure Java method.
3526 if (m->IsNative() || m->IsProxyMethod()) {
3527 return false;
3528 }
3529 const SingleStepControl* const ssc = thread->GetSingleStepControl();
3530 if (ssc != nullptr) {
3531 // If we want to step into a method, then we have to force interpreter on that call.
3532 if (ssc->GetStepDepth() == JDWP::SD_INTO) {
3533 return true;
3534 }
3535 // If we are stepping out from a static initializer, by issuing a step
3536 // in or step over, that was implicitly invoked by calling a static method,
3537 // then we need to step into that method. Having a lower stack depth than
3538 // the one the single step control has indicates that the step originates
3539 // from the static initializer.
3540 if (ssc->GetStepDepth() != JDWP::SD_OUT &&
3541 ssc->GetStackDepth() > GetStackDepth(thread)) {
3542 return true;
3543 }
3544 }
3545 // There are cases where we have to force interpreter on deoptimized methods,
3546 // because in some cases the call will not be performed by invoking an entry
3547 // point that has been replaced by the deoptimization, but instead by directly
3548 // invoking the compiled code of the method, for example.
3549 return instrumentation->IsDeoptimized(m);
3550}
3551
Mathieu Chartier3d21bdf2015-04-22 13:56:20 -07003552bool Dbg::IsForcedInstrumentationNeededForResolutionImpl(Thread* thread, ArtMethod* m) {
Mathieu Chartier2cebb242015-04-21 16:50:40 -07003553 // The upcall can be null and in that case we don't need to do anything.
Daniel Mihalyieb076692014-08-22 17:33:31 +02003554 if (m == nullptr) {
3555 return false;
3556 }
3557 instrumentation::Instrumentation* const instrumentation =
3558 Runtime::Current()->GetInstrumentation();
3559 // If we are in interpreter only mode, then we don't have to force interpreter.
3560 if (instrumentation->InterpretOnly()) {
3561 return false;
3562 }
3563 // We can only interpret pure Java method.
3564 if (m->IsNative() || m->IsProxyMethod()) {
3565 return false;
3566 }
3567 const SingleStepControl* const ssc = thread->GetSingleStepControl();
3568 if (ssc != nullptr) {
3569 // If we are stepping out from a static initializer, by issuing a step
3570 // out, that was implicitly invoked by calling a static method, then we
3571 // need to step into the caller of that method. Having a lower stack
3572 // depth than the one the single step control has indicates that the
3573 // step originates from the static initializer.
3574 if (ssc->GetStepDepth() == JDWP::SD_OUT &&
3575 ssc->GetStackDepth() > GetStackDepth(thread)) {
3576 return true;
3577 }
3578 }
3579 // If we are returning from a static intializer, that was implicitly
3580 // invoked by calling a static method and the caller is deoptimized,
3581 // then we have to deoptimize the stack without forcing interpreter
3582 // on the static method that was called originally. This problem can
3583 // be solved easily by forcing instrumentation on the called method,
3584 // because the instrumentation exit hook will recognise the need of
3585 // stack deoptimization by calling IsForcedInterpreterNeededForUpcall.
3586 return instrumentation->IsDeoptimized(m);
3587}
3588
Mathieu Chartier3d21bdf2015-04-22 13:56:20 -07003589bool Dbg::IsForcedInterpreterNeededForUpcallImpl(Thread* thread, ArtMethod* m) {
Mathieu Chartier2cebb242015-04-21 16:50:40 -07003590 // The upcall can be null and in that case we don't need to do anything.
Daniel Mihalyieb076692014-08-22 17:33:31 +02003591 if (m == nullptr) {
3592 return false;
3593 }
3594 instrumentation::Instrumentation* const instrumentation =
3595 Runtime::Current()->GetInstrumentation();
3596 // If we are in interpreter only mode, then we don't have to force interpreter.
3597 if (instrumentation->InterpretOnly()) {
3598 return false;
3599 }
3600 // We can only interpret pure Java method.
3601 if (m->IsNative() || m->IsProxyMethod()) {
3602 return false;
3603 }
3604 const SingleStepControl* const ssc = thread->GetSingleStepControl();
3605 if (ssc != nullptr) {
3606 // The debugger is not interested in what is happening under the level
3607 // of the step, thus we only force interpreter when we are not below of
3608 // the step.
3609 if (ssc->GetStackDepth() >= GetStackDepth(thread)) {
3610 return true;
3611 }
3612 }
3613 // We have to require stack deoptimization if the upcall is deoptimized.
3614 return instrumentation->IsDeoptimized(m);
3615}
3616
Jeff Hao449db332013-04-12 18:30:52 -07003617// Scoped utility class to suspend a thread so that we may do tasks such as walk its stack. Doesn't
3618// cause suspension if the thread is the current thread.
3619class ScopedThreadSuspension {
3620 public:
Ian Rogers33e95662013-05-20 20:29:14 -07003621 ScopedThreadSuspension(Thread* self, JDWP::ObjectId thread_id)
Sebastien Hertz52d131d2014-03-13 16:17:40 +01003622 LOCKS_EXCLUDED(Locks::thread_list_lock_)
Ian Rogers33e95662013-05-20 20:29:14 -07003623 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) :
Ian Rogersf3d874c2014-07-17 18:52:42 -07003624 thread_(nullptr),
Jeff Hao449db332013-04-12 18:30:52 -07003625 error_(JDWP::ERR_NONE),
3626 self_suspend_(false),
Ian Rogers33e95662013-05-20 20:29:14 -07003627 other_suspend_(false) {
Jeff Hao449db332013-04-12 18:30:52 -07003628 ScopedObjectAccessUnchecked soa(self);
Sebastien Hertz69206392015-04-07 15:54:25 +02003629 thread_ = DecodeThread(soa, thread_id, &error_);
Jeff Hao449db332013-04-12 18:30:52 -07003630 if (error_ == JDWP::ERR_NONE) {
3631 if (thread_ == soa.Self()) {
3632 self_suspend_ = true;
3633 } else {
3634 soa.Self()->TransitionFromRunnableToSuspended(kWaitingForDebuggerSuspension);
Sebastien Hertz6995c602014-09-09 12:10:13 +02003635 jobject thread_peer = Dbg::GetObjectRegistry()->GetJObject(thread_id);
Jeff Hao449db332013-04-12 18:30:52 -07003636 bool timed_out;
Ian Rogers4ad5cd32014-11-11 23:08:07 -08003637 ThreadList* thread_list = Runtime::Current()->GetThreadList();
3638 Thread* suspended_thread = thread_list->SuspendThreadByPeer(thread_peer, true, true,
3639 &timed_out);
Jeff Hao449db332013-04-12 18:30:52 -07003640 CHECK_EQ(soa.Self()->TransitionFromSuspendedToRunnable(), kWaitingForDebuggerSuspension);
Ian Rogersf3d874c2014-07-17 18:52:42 -07003641 if (suspended_thread == nullptr) {
Jeff Hao449db332013-04-12 18:30:52 -07003642 // Thread terminated from under us while suspending.
3643 error_ = JDWP::ERR_INVALID_THREAD;
3644 } else {
3645 CHECK_EQ(suspended_thread, thread_);
3646 other_suspend_ = true;
3647 }
3648 }
3649 }
Elliott Hughes2435a572012-02-17 16:07:41 -08003650 }
Elliott Hughes86964332012-02-15 19:37:42 -08003651
Jeff Hao449db332013-04-12 18:30:52 -07003652 Thread* GetThread() const {
3653 return thread_;
3654 }
3655
3656 JDWP::JdwpError GetError() const {
3657 return error_;
3658 }
3659
3660 ~ScopedThreadSuspension() {
3661 if (other_suspend_) {
3662 Runtime::Current()->GetThreadList()->Resume(thread_, true);
3663 }
3664 }
3665
3666 private:
3667 Thread* thread_;
3668 JDWP::JdwpError error_;
3669 bool self_suspend_;
3670 bool other_suspend_;
3671};
3672
3673JDWP::JdwpError Dbg::ConfigureStep(JDWP::ObjectId thread_id, JDWP::JdwpStepSize step_size,
3674 JDWP::JdwpStepDepth step_depth) {
3675 Thread* self = Thread::Current();
3676 ScopedThreadSuspension sts(self, thread_id);
3677 if (sts.GetError() != JDWP::ERR_NONE) {
3678 return sts.GetError();
3679 }
3680
Sebastien Hertz597c4f02015-01-26 17:37:14 +01003681 // Work out what ArtMethod* we're in, the current line number, and how deep the stack currently
Elliott Hughes2435a572012-02-17 16:07:41 -08003682 // is for step-out.
Ian Rogers0399dde2012-06-06 17:09:28 -07003683 struct SingleStepStackVisitor : public StackVisitor {
Sebastien Hertz597c4f02015-01-26 17:37:14 +01003684 explicit SingleStepStackVisitor(Thread* thread) SHARED_LOCKS_REQUIRED(Locks::mutator_lock_)
Nicolas Geoffray8e5bd182015-05-06 11:34:34 +01003685 : StackVisitor(thread, nullptr, StackVisitor::StackWalkKind::kIncludeInlinedFrames),
3686 stack_depth(0),
3687 method(nullptr),
3688 line_number(-1) {}
Ian Rogersca190662012-06-26 15:45:57 -07003689
Ian Rogers00f7d0e2012-07-19 15:28:27 -07003690 // TODO: Enable annotalysis. We know lock is held in constructor, but abstraction confuses
3691 // annotalysis.
3692 bool VisitFrame() NO_THREAD_SAFETY_ANALYSIS {
Mathieu Chartier3d21bdf2015-04-22 13:56:20 -07003693 ArtMethod* m = GetMethod();
Ian Rogers0399dde2012-06-06 17:09:28 -07003694 if (!m->IsRuntimeMethod()) {
Sebastien Hertz597c4f02015-01-26 17:37:14 +01003695 ++stack_depth;
3696 if (method == nullptr) {
Ian Rogersef7d42f2014-01-06 12:55:46 -08003697 mirror::DexCache* dex_cache = m->GetDeclaringClass()->GetDexCache();
Sebastien Hertz597c4f02015-01-26 17:37:14 +01003698 method = m;
Ian Rogersc0542af2014-09-03 16:16:56 -07003699 if (dex_cache != nullptr) {
Ian Rogers4445a7e2012-10-05 17:19:13 -07003700 const DexFile& dex_file = *dex_cache->GetDexFile();
Sebastien Hertz597c4f02015-01-26 17:37:14 +01003701 line_number = dex_file.GetLineNumFromPC(m, GetDexPc());
Elliott Hughes2435a572012-02-17 16:07:41 -08003702 }
Elliott Hughes86964332012-02-15 19:37:42 -08003703 }
3704 }
Elliott Hughes530fa002012-03-12 11:44:49 -07003705 return true;
Elliott Hughes86964332012-02-15 19:37:42 -08003706 }
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01003707
Sebastien Hertz597c4f02015-01-26 17:37:14 +01003708 int stack_depth;
Mathieu Chartier3d21bdf2015-04-22 13:56:20 -07003709 ArtMethod* method;
Sebastien Hertz597c4f02015-01-26 17:37:14 +01003710 int32_t line_number;
Elliott Hughes86964332012-02-15 19:37:42 -08003711 };
Jeff Hao449db332013-04-12 18:30:52 -07003712
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01003713 Thread* const thread = sts.GetThread();
Sebastien Hertz597c4f02015-01-26 17:37:14 +01003714 SingleStepStackVisitor visitor(thread);
Ian Rogers0399dde2012-06-06 17:09:28 -07003715 visitor.WalkStack();
Elliott Hughes86964332012-02-15 19:37:42 -08003716
Elliott Hughes2435a572012-02-17 16:07:41 -08003717 // Find the dex_pc values that correspond to the current line, for line-based single-stepping.
Elliott Hughes2435a572012-02-17 16:07:41 -08003718 struct DebugCallbackContext {
Sebastien Hertz597c4f02015-01-26 17:37:14 +01003719 explicit DebugCallbackContext(SingleStepControl* single_step_control_cb,
3720 int32_t line_number_cb, const DexFile::CodeItem* code_item)
Andreas Gampe277ccbd2014-11-03 21:36:10 -08003721 : single_step_control_(single_step_control_cb), line_number_(line_number_cb),
3722 code_item_(code_item), last_pc_valid(false), last_pc(0) {
Elliott Hughes2435a572012-02-17 16:07:41 -08003723 }
3724
Andreas Gampe277ccbd2014-11-03 21:36:10 -08003725 static bool Callback(void* raw_context, uint32_t address, uint32_t line_number_cb) {
Elliott Hughes2435a572012-02-17 16:07:41 -08003726 DebugCallbackContext* context = reinterpret_cast<DebugCallbackContext*>(raw_context);
Andreas Gampe277ccbd2014-11-03 21:36:10 -08003727 if (static_cast<int32_t>(line_number_cb) == context->line_number_) {
Elliott Hughes2435a572012-02-17 16:07:41 -08003728 if (!context->last_pc_valid) {
3729 // Everything from this address until the next line change is ours.
3730 context->last_pc = address;
3731 context->last_pc_valid = true;
3732 }
3733 // Otherwise, if we're already in a valid range for this line,
3734 // just keep going (shouldn't really happen)...
Brian Carlstrom7934ac22013-07-26 10:54:15 -07003735 } else if (context->last_pc_valid) { // and the line number is new
Elliott Hughes2435a572012-02-17 16:07:41 -08003736 // Add everything from the last entry up until here to the set
3737 for (uint32_t dex_pc = context->last_pc; dex_pc < address; ++dex_pc) {
Sebastien Hertz597c4f02015-01-26 17:37:14 +01003738 context->single_step_control_->AddDexPc(dex_pc);
Elliott Hughes2435a572012-02-17 16:07:41 -08003739 }
3740 context->last_pc_valid = false;
3741 }
Brian Carlstrom7934ac22013-07-26 10:54:15 -07003742 return false; // There may be multiple entries for any given line.
Elliott Hughes2435a572012-02-17 16:07:41 -08003743 }
3744
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01003745 ~DebugCallbackContext() {
Elliott Hughes2435a572012-02-17 16:07:41 -08003746 // If the line number was the last in the position table...
3747 if (last_pc_valid) {
Sebastien Hertzbb43b432014-04-14 11:59:08 +02003748 size_t end = code_item_->insns_size_in_code_units_;
Elliott Hughes2435a572012-02-17 16:07:41 -08003749 for (uint32_t dex_pc = last_pc; dex_pc < end; ++dex_pc) {
Sebastien Hertz597c4f02015-01-26 17:37:14 +01003750 single_step_control_->AddDexPc(dex_pc);
Elliott Hughes2435a572012-02-17 16:07:41 -08003751 }
3752 }
3753 }
3754
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01003755 SingleStepControl* const single_step_control_;
3756 const int32_t line_number_;
Sebastien Hertzbb43b432014-04-14 11:59:08 +02003757 const DexFile::CodeItem* const code_item_;
Elliott Hughes2435a572012-02-17 16:07:41 -08003758 bool last_pc_valid;
3759 uint32_t last_pc;
3760 };
Sebastien Hertz597c4f02015-01-26 17:37:14 +01003761
3762 // Allocate single step.
Sebastien Hertz1558b572015-02-25 15:05:59 +01003763 SingleStepControl* single_step_control =
3764 new (std::nothrow) SingleStepControl(step_size, step_depth,
3765 visitor.stack_depth, visitor.method);
3766 if (single_step_control == nullptr) {
3767 LOG(ERROR) << "Failed to allocate SingleStepControl";
3768 return JDWP::ERR_OUT_OF_MEMORY;
3769 }
3770
Mathieu Chartier3d21bdf2015-04-22 13:56:20 -07003771 ArtMethod* m = single_step_control->GetMethod();
Sebastien Hertz597c4f02015-01-26 17:37:14 +01003772 const int32_t line_number = visitor.line_number;
Sebastien Hertz1309ba22015-05-28 11:00:57 +02003773 // Note: if the thread is not running Java code (pure native thread), there is no "current"
3774 // method on the stack (and no line number either).
3775 if (m != nullptr && !m->IsNative()) {
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07003776 const DexFile::CodeItem* const code_item = m->GetCodeItem();
Sebastien Hertzbb43b432014-04-14 11:59:08 +02003777 DebugCallbackContext context(single_step_control, line_number, code_item);
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07003778 m->GetDexFile()->DecodeDebugInfo(code_item, m->IsStatic(), m->GetDexMethodIndex(),
Ian Rogersc0542af2014-09-03 16:16:56 -07003779 DebugCallbackContext::Callback, nullptr, &context);
Elliott Hughes3e2e1a22012-02-21 11:33:41 -08003780 }
Elliott Hughes2435a572012-02-17 16:07:41 -08003781
Sebastien Hertz597c4f02015-01-26 17:37:14 +01003782 // Activate single-step in the thread.
3783 thread->ActivateSingleStepControl(single_step_control);
Elliott Hughes86964332012-02-15 19:37:42 -08003784
Elliott Hughes2435a572012-02-17 16:07:41 -08003785 if (VLOG_IS_ON(jdwp)) {
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01003786 VLOG(jdwp) << "Single-step thread: " << *thread;
Sebastien Hertz597c4f02015-01-26 17:37:14 +01003787 VLOG(jdwp) << "Single-step step size: " << single_step_control->GetStepSize();
3788 VLOG(jdwp) << "Single-step step depth: " << single_step_control->GetStepDepth();
3789 VLOG(jdwp) << "Single-step current method: " << PrettyMethod(single_step_control->GetMethod());
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01003790 VLOG(jdwp) << "Single-step current line: " << line_number;
Sebastien Hertz597c4f02015-01-26 17:37:14 +01003791 VLOG(jdwp) << "Single-step current stack depth: " << single_step_control->GetStackDepth();
Elliott Hughes2435a572012-02-17 16:07:41 -08003792 VLOG(jdwp) << "Single-step dex_pc values:";
Sebastien Hertz597c4f02015-01-26 17:37:14 +01003793 for (uint32_t dex_pc : single_step_control->GetDexPcs()) {
Sebastien Hertzbb43b432014-04-14 11:59:08 +02003794 VLOG(jdwp) << StringPrintf(" %#x", dex_pc);
Elliott Hughes2435a572012-02-17 16:07:41 -08003795 }
3796 }
3797
3798 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07003799}
3800
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01003801void Dbg::UnconfigureStep(JDWP::ObjectId thread_id) {
3802 ScopedObjectAccessUnchecked soa(Thread::Current());
Ian Rogersc0542af2014-09-03 16:16:56 -07003803 JDWP::JdwpError error;
3804 Thread* thread = DecodeThread(soa, thread_id, &error);
Sebastien Hertz87118ed2013-11-26 17:57:18 +01003805 if (error == JDWP::ERR_NONE) {
Sebastien Hertz597c4f02015-01-26 17:37:14 +01003806 thread->DeactivateSingleStepControl();
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01003807 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -07003808}
3809
Elliott Hughes45651fd2012-02-21 15:48:20 -08003810static char JdwpTagToShortyChar(JDWP::JdwpTag tag) {
3811 switch (tag) {
3812 default:
3813 LOG(FATAL) << "unknown JDWP tag: " << PrintableChar(tag);
Ian Rogersfc787ec2014-10-09 21:56:44 -07003814 UNREACHABLE();
Elliott Hughes45651fd2012-02-21 15:48:20 -08003815
3816 // Primitives.
3817 case JDWP::JT_BYTE: return 'B';
3818 case JDWP::JT_CHAR: return 'C';
3819 case JDWP::JT_FLOAT: return 'F';
3820 case JDWP::JT_DOUBLE: return 'D';
3821 case JDWP::JT_INT: return 'I';
3822 case JDWP::JT_LONG: return 'J';
3823 case JDWP::JT_SHORT: return 'S';
3824 case JDWP::JT_VOID: return 'V';
3825 case JDWP::JT_BOOLEAN: return 'Z';
3826
3827 // Reference types.
3828 case JDWP::JT_ARRAY:
3829 case JDWP::JT_OBJECT:
3830 case JDWP::JT_STRING:
3831 case JDWP::JT_THREAD:
3832 case JDWP::JT_THREAD_GROUP:
3833 case JDWP::JT_CLASS_LOADER:
3834 case JDWP::JT_CLASS_OBJECT:
3835 return 'L';
3836 }
3837}
3838
Sebastien Hertz6ba35b52015-06-01 17:33:12 +02003839JDWP::JdwpError Dbg::PrepareInvokeMethod(uint32_t request_id, JDWP::ObjectId thread_id,
3840 JDWP::ObjectId object_id, JDWP::RefTypeId class_id,
3841 JDWP::MethodId method_id, uint32_t arg_count,
3842 uint64_t arg_values[], JDWP::JdwpTag* arg_types,
3843 uint32_t options) {
3844 Thread* const self = Thread::Current();
3845 CHECK_EQ(self, GetDebugThread()) << "This must be called by the JDWP thread";
Elliott Hughesd07986f2011-12-06 18:27:45 -08003846
Sebastien Hertz6ba35b52015-06-01 17:33:12 +02003847 ThreadList* thread_list = Runtime::Current()->GetThreadList();
Ian Rogersc0542af2014-09-03 16:16:56 -07003848 Thread* targetThread = nullptr;
Elliott Hughesd07986f2011-12-06 18:27:45 -08003849 {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07003850 ScopedObjectAccessUnchecked soa(self);
Ian Rogersc0542af2014-09-03 16:16:56 -07003851 JDWP::JdwpError error;
3852 targetThread = DecodeThread(soa, thread_id, &error);
Elliott Hughes221229c2013-01-08 18:17:50 -08003853 if (error != JDWP::ERR_NONE) {
3854 LOG(ERROR) << "InvokeMethod request for invalid thread id " << thread_id;
3855 return error;
Elliott Hughesd07986f2011-12-06 18:27:45 -08003856 }
Sebastien Hertz1558b572015-02-25 15:05:59 +01003857 if (targetThread->GetInvokeReq() != nullptr) {
3858 // Thread is already invoking a method on behalf of the debugger.
3859 LOG(ERROR) << "InvokeMethod request for thread already invoking a method: " << *targetThread;
3860 return JDWP::ERR_ALREADY_INVOKING;
3861 }
3862 if (!targetThread->IsReadyForDebugInvoke()) {
3863 // Thread is not suspended by an event so it cannot invoke a method.
Elliott Hughesd07986f2011-12-06 18:27:45 -08003864 LOG(ERROR) << "InvokeMethod request for thread not stopped by event: " << *targetThread;
3865 return JDWP::ERR_INVALID_THREAD;
3866 }
3867
3868 /*
3869 * We currently have a bug where we don't successfully resume the
3870 * target thread if the suspend count is too deep. We're expected to
3871 * require one "resume" for each "suspend", but when asked to execute
3872 * a method we have to resume fully and then re-suspend it back to the
3873 * same level. (The easiest way to cause this is to type "suspend"
3874 * multiple times in jdb.)
3875 *
3876 * It's unclear what this means when the event specifies "resume all"
3877 * and some threads are suspended more deeply than others. This is
3878 * a rare problem, so for now we just prevent it from hanging forever
3879 * by rejecting the method invocation request. Without this, we will
3880 * be stuck waiting on a suspended thread.
3881 */
Ian Rogers00f7d0e2012-07-19 15:28:27 -07003882 int suspend_count;
3883 {
Ian Rogers50b35e22012-10-04 10:09:15 -07003884 MutexLock mu2(soa.Self(), *Locks::thread_suspend_count_lock_);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07003885 suspend_count = targetThread->GetSuspendCount();
3886 }
Elliott Hughesd07986f2011-12-06 18:27:45 -08003887 if (suspend_count > 1) {
3888 LOG(ERROR) << *targetThread << " suspend count too deep for method invocation: " << suspend_count;
Brian Carlstrom7934ac22013-07-26 10:54:15 -07003889 return JDWP::ERR_THREAD_SUSPENDED; // Probably not expected here.
Elliott Hughesd07986f2011-12-06 18:27:45 -08003890 }
3891
Ian Rogersc0542af2014-09-03 16:16:56 -07003892 mirror::Object* receiver = gRegistry->Get<mirror::Object*>(object_id, &error);
3893 if (error != JDWP::ERR_NONE) {
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08003894 return JDWP::ERR_INVALID_OBJECT;
3895 }
Elliott Hughes45651fd2012-02-21 15:48:20 -08003896
Sebastien Hertz1558b572015-02-25 15:05:59 +01003897 gRegistry->Get<mirror::Object*>(thread_id, &error);
Ian Rogersc0542af2014-09-03 16:16:56 -07003898 if (error != JDWP::ERR_NONE) {
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08003899 return JDWP::ERR_INVALID_OBJECT;
3900 }
Elliott Hughes45651fd2012-02-21 15:48:20 -08003901
Ian Rogersc0542af2014-09-03 16:16:56 -07003902 mirror::Class* c = DecodeClass(class_id, &error);
3903 if (c == nullptr) {
3904 return error;
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08003905 }
Elliott Hughes45651fd2012-02-21 15:48:20 -08003906
Mathieu Chartier3d21bdf2015-04-22 13:56:20 -07003907 ArtMethod* m = FromMethodId(method_id);
Ian Rogersc0542af2014-09-03 16:16:56 -07003908 if (m->IsStatic() != (receiver == nullptr)) {
Elliott Hughes45651fd2012-02-21 15:48:20 -08003909 return JDWP::ERR_INVALID_METHODID;
3910 }
3911 if (m->IsStatic()) {
3912 if (m->GetDeclaringClass() != c) {
3913 return JDWP::ERR_INVALID_METHODID;
3914 }
3915 } else {
3916 if (!m->GetDeclaringClass()->IsAssignableFrom(c)) {
3917 return JDWP::ERR_INVALID_METHODID;
3918 }
3919 }
3920
3921 // Check the argument list matches the method.
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07003922 uint32_t shorty_len = 0;
3923 const char* shorty = m->GetShorty(&shorty_len);
3924 if (shorty_len - 1 != arg_count) {
Elliott Hughes45651fd2012-02-21 15:48:20 -08003925 return JDWP::ERR_ILLEGAL_ARGUMENT;
3926 }
Elliott Hughes09201632013-04-15 15:50:07 -07003927
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07003928 {
Mathieu Chartier3d21bdf2015-04-22 13:56:20 -07003929 StackHandleScope<2> hs(soa.Self());
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07003930 HandleWrapper<mirror::Object> h_obj(hs.NewHandleWrapper(&receiver));
3931 HandleWrapper<mirror::Class> h_klass(hs.NewHandleWrapper(&c));
3932 const DexFile::TypeList* types = m->GetParameterTypeList();
3933 for (size_t i = 0; i < arg_count; ++i) {
3934 if (shorty[i + 1] != JdwpTagToShortyChar(arg_types[i])) {
Elliott Hughes09201632013-04-15 15:50:07 -07003935 return JDWP::ERR_ILLEGAL_ARGUMENT;
3936 }
3937
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07003938 if (shorty[i + 1] == 'L') {
3939 // Did we really get an argument of an appropriate reference type?
Ian Rogersa0485602014-12-02 15:48:04 -08003940 mirror::Class* parameter_type =
Mathieu Chartier3d21bdf2015-04-22 13:56:20 -07003941 m->GetClassFromTypeIndex(types->GetTypeItem(i).type_idx_, true);
Ian Rogersc0542af2014-09-03 16:16:56 -07003942 mirror::Object* argument = gRegistry->Get<mirror::Object*>(arg_values[i], &error);
3943 if (error != JDWP::ERR_NONE) {
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07003944 return JDWP::ERR_INVALID_OBJECT;
3945 }
Ian Rogersc0542af2014-09-03 16:16:56 -07003946 if (argument != nullptr && !argument->InstanceOf(parameter_type)) {
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07003947 return JDWP::ERR_ILLEGAL_ARGUMENT;
3948 }
3949
3950 // Turn the on-the-wire ObjectId into a jobject.
3951 jvalue& v = reinterpret_cast<jvalue&>(arg_values[i]);
3952 v.l = gRegistry->GetJObject(arg_values[i]);
3953 }
Elliott Hughes09201632013-04-15 15:50:07 -07003954 }
Elliott Hughes45651fd2012-02-21 15:48:20 -08003955 }
3956
Sebastien Hertz1558b572015-02-25 15:05:59 +01003957 // Allocates a DebugInvokeReq.
Sebastien Hertz6ba35b52015-06-01 17:33:12 +02003958 DebugInvokeReq* req = new (std::nothrow) DebugInvokeReq(request_id, thread_id, receiver, c, m,
3959 options, arg_values, arg_count);
3960 if (req == nullptr) {
Sebastien Hertz1558b572015-02-25 15:05:59 +01003961 LOG(ERROR) << "Failed to allocate DebugInvokeReq";
3962 return JDWP::ERR_OUT_OF_MEMORY;
3963 }
3964
Sebastien Hertz6ba35b52015-06-01 17:33:12 +02003965 // Attaches the DebugInvokeReq to the target thread so it executes the method when
3966 // it is resumed. Once the invocation completes, the target thread will delete it before
3967 // suspending itself (see ThreadList::SuspendSelfForDebugger).
3968 targetThread->SetDebugInvokeReq(req);
Elliott Hughesd07986f2011-12-06 18:27:45 -08003969 }
3970
3971 // The fact that we've released the thread list lock is a bit risky --- if the thread goes
Sebastien Hertz6ba35b52015-06-01 17:33:12 +02003972 // away we're sitting high and dry -- but we must release this before the UndoDebuggerSuspensions
3973 // call.
Elliott Hughesd07986f2011-12-06 18:27:45 -08003974
Elliott Hughesd07986f2011-12-06 18:27:45 -08003975 if ((options & JDWP::INVOKE_SINGLE_THREADED) == 0) {
Sebastien Hertz6ba35b52015-06-01 17:33:12 +02003976 VLOG(jdwp) << " Resuming all threads";
3977 thread_list->UndoDebuggerSuspensions();
3978 } else {
3979 VLOG(jdwp) << " Resuming event thread only";
Elliott Hughesd07986f2011-12-06 18:27:45 -08003980 thread_list->Resume(targetThread, true);
3981 }
3982
Sebastien Hertz6ba35b52015-06-01 17:33:12 +02003983 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07003984}
3985
3986void Dbg::ExecuteMethod(DebugInvokeReq* pReq) {
Sebastien Hertz6ba35b52015-06-01 17:33:12 +02003987 Thread* const self = Thread::Current();
3988 CHECK_NE(self, GetDebugThread()) << "This must be called by the event thread";
3989
3990 ScopedObjectAccess soa(self);
Elliott Hughesd07986f2011-12-06 18:27:45 -08003991
Elliott Hughes81ff3182012-03-23 20:35:56 -07003992 // We can be called while an exception is pending. We need
Elliott Hughesd07986f2011-12-06 18:27:45 -08003993 // to preserve that across the method invocation.
Sebastien Hertz6ba35b52015-06-01 17:33:12 +02003994 StackHandleScope<1> hs(soa.Self());
3995 Handle<mirror::Throwable> old_exception = hs.NewHandle(soa.Self()->GetException());
Sebastien Hertz1558b572015-02-25 15:05:59 +01003996 soa.Self()->ClearException();
Elliott Hughesd07986f2011-12-06 18:27:45 -08003997
Sebastien Hertz6ba35b52015-06-01 17:33:12 +02003998 // Execute the method then sends reply to the debugger.
3999 ExecuteMethodWithoutPendingException(soa, pReq);
4000
4001 // If an exception was pending before the invoke, restore it now.
4002 if (old_exception.Get() != nullptr) {
4003 soa.Self()->SetException(old_exception.Get());
4004 }
4005}
4006
4007// Helper function: write a variable-width value into the output input buffer.
4008static void WriteValue(JDWP::ExpandBuf* pReply, int width, uint64_t value) {
4009 switch (width) {
4010 case 1:
4011 expandBufAdd1(pReply, value);
4012 break;
4013 case 2:
4014 expandBufAdd2BE(pReply, value);
4015 break;
4016 case 4:
4017 expandBufAdd4BE(pReply, value);
4018 break;
4019 case 8:
4020 expandBufAdd8BE(pReply, value);
4021 break;
4022 default:
4023 LOG(FATAL) << width;
4024 UNREACHABLE();
4025 }
4026}
4027
4028void Dbg::ExecuteMethodWithoutPendingException(ScopedObjectAccess& soa, DebugInvokeReq* pReq) {
4029 soa.Self()->AssertNoPendingException();
4030
Elliott Hughesd07986f2011-12-06 18:27:45 -08004031 // Translate the method through the vtable, unless the debugger wants to suppress it.
Sebastien Hertz6ba35b52015-06-01 17:33:12 +02004032 ArtMethod* m = pReq->method;
4033 size_t image_pointer_size = Runtime::Current()->GetClassLinker()->GetImagePointerSize();
Sebastien Hertz1558b572015-02-25 15:05:59 +01004034 if ((pReq->options & JDWP::INVOKE_NONVIRTUAL) == 0 && pReq->receiver.Read() != nullptr) {
Mathieu Chartier3d21bdf2015-04-22 13:56:20 -07004035 ArtMethod* actual_method =
4036 pReq->klass.Read()->FindVirtualMethodForVirtualOrInterface(m, image_pointer_size);
4037 if (actual_method != m) {
4038 VLOG(jdwp) << "ExecuteMethod translated " << PrettyMethod(m)
Sebastien Hertz1558b572015-02-25 15:05:59 +01004039 << " to " << PrettyMethod(actual_method);
Mathieu Chartier3d21bdf2015-04-22 13:56:20 -07004040 m = actual_method;
Elliott Hughes45651fd2012-02-21 15:48:20 -08004041 }
Elliott Hughesd07986f2011-12-06 18:27:45 -08004042 }
Mathieu Chartier3d21bdf2015-04-22 13:56:20 -07004043 VLOG(jdwp) << "ExecuteMethod " << PrettyMethod(m)
Sebastien Hertz1558b572015-02-25 15:05:59 +01004044 << " receiver=" << pReq->receiver.Read()
Sebastien Hertzd38667a2013-11-25 15:43:54 +01004045 << " arg_count=" << pReq->arg_count;
Mathieu Chartier3d21bdf2015-04-22 13:56:20 -07004046 CHECK(m != nullptr);
Elliott Hughesd07986f2011-12-06 18:27:45 -08004047
4048 CHECK_EQ(sizeof(jvalue), sizeof(uint64_t));
4049
Sebastien Hertz6ba35b52015-06-01 17:33:12 +02004050 // Invoke the method.
Jeff Hao15e9ad12015-05-19 20:30:23 -07004051 ScopedLocalRef<jobject> ref(soa.Env(), soa.AddLocalReference<jobject>(pReq->receiver.Read()));
Mathieu Chartier3d21bdf2015-04-22 13:56:20 -07004052 JValue result = InvokeWithJValues(soa, ref.get(), soa.EncodeMethod(m),
Sebastien Hertz6ba35b52015-06-01 17:33:12 +02004053 reinterpret_cast<jvalue*>(pReq->arg_values.get()));
Elliott Hughesd07986f2011-12-06 18:27:45 -08004054
Sebastien Hertz6ba35b52015-06-01 17:33:12 +02004055 // Prepare JDWP ids for the reply.
4056 JDWP::JdwpTag result_tag = BasicTagFromDescriptor(m->GetShorty());
4057 const bool is_object_result = (result_tag == JDWP::JT_OBJECT);
4058 StackHandleScope<2> hs(soa.Self());
Sebastien Hertz1558b572015-02-25 15:05:59 +01004059 Handle<mirror::Object> object_result = hs.NewHandle(is_object_result ? result.GetL() : nullptr);
4060 Handle<mirror::Throwable> exception = hs.NewHandle(soa.Self()->GetException());
4061 soa.Self()->ClearException();
Sebastien Hertz6ba35b52015-06-01 17:33:12 +02004062
4063 if (!IsDebuggerActive()) {
4064 // The debugger detached: we must not re-suspend threads. We also don't need to fill the reply
4065 // because it won't be sent either.
4066 return;
4067 }
4068
4069 JDWP::ObjectId exceptionObjectId = gRegistry->Add(exception);
4070 uint64_t result_value = 0;
4071 if (exceptionObjectId != 0) {
Sebastien Hertz1558b572015-02-25 15:05:59 +01004072 VLOG(jdwp) << " JDWP invocation returning with exception=" << exception.Get()
4073 << " " << exception->Dump();
Sebastien Hertz6ba35b52015-06-01 17:33:12 +02004074 result_value = 0;
Sebastien Hertz1558b572015-02-25 15:05:59 +01004075 } else if (is_object_result) {
Sebastien Hertz6ba35b52015-06-01 17:33:12 +02004076 /* if no exception was thrown, examine object result more closely */
Sebastien Hertz1558b572015-02-25 15:05:59 +01004077 JDWP::JdwpTag new_tag = TagFromObject(soa, object_result.Get());
Sebastien Hertz6ba35b52015-06-01 17:33:12 +02004078 if (new_tag != result_tag) {
4079 VLOG(jdwp) << " JDWP promoted result from " << result_tag << " to " << new_tag;
4080 result_tag = new_tag;
Elliott Hughesd07986f2011-12-06 18:27:45 -08004081 }
4082
Sebastien Hertz1558b572015-02-25 15:05:59 +01004083 // Register the object in the registry and reference its ObjectId. This ensures
4084 // GC safety and prevents from accessing stale reference if the object is moved.
Sebastien Hertz6ba35b52015-06-01 17:33:12 +02004085 result_value = gRegistry->Add(object_result.Get());
Sebastien Hertz1558b572015-02-25 15:05:59 +01004086 } else {
4087 // Primitive result.
Sebastien Hertz6ba35b52015-06-01 17:33:12 +02004088 DCHECK(IsPrimitiveTag(result_tag));
4089 result_value = result.GetJ();
4090 }
4091 const bool is_constructor = m->IsConstructor() && !m->IsStatic();
4092 if (is_constructor) {
4093 // If we invoked a constructor (which actually returns void), return the receiver,
4094 // unless we threw, in which case we return null.
4095 result_tag = JDWP::JT_OBJECT;
4096 if (exceptionObjectId == 0) {
4097 // TODO we could keep the receiver ObjectId in the DebugInvokeReq to avoid looking into the
4098 // object registry.
4099 result_value = GetObjectRegistry()->Add(pReq->receiver.Read());
4100 } else {
4101 result_value = 0;
4102 }
Elliott Hughesd07986f2011-12-06 18:27:45 -08004103 }
4104
Sebastien Hertz6ba35b52015-06-01 17:33:12 +02004105 // Suspend other threads if the invoke is not single-threaded.
4106 if ((pReq->options & JDWP::INVOKE_SINGLE_THREADED) == 0) {
4107 soa.Self()->TransitionFromRunnableToSuspended(kWaitingForDebuggerSuspension);
4108 VLOG(jdwp) << " Suspending all threads";
4109 Runtime::Current()->GetThreadList()->SuspendAllForDebugger();
4110 soa.Self()->TransitionFromSuspendedToRunnable();
4111 }
4112
4113 VLOG(jdwp) << " --> returned " << result_tag
4114 << StringPrintf(" %#" PRIx64 " (except=%#" PRIx64 ")", result_value,
4115 exceptionObjectId);
4116
4117 // Show detailed debug output.
4118 if (result_tag == JDWP::JT_STRING && exceptionObjectId == 0) {
4119 if (result_value != 0) {
4120 if (VLOG_IS_ON(jdwp)) {
4121 std::string result_string;
4122 JDWP::JdwpError error = Dbg::StringToUtf8(result_value, &result_string);
4123 CHECK_EQ(error, JDWP::ERR_NONE);
4124 VLOG(jdwp) << " string '" << result_string << "'";
4125 }
4126 } else {
4127 VLOG(jdwp) << " string (null)";
4128 }
4129 }
4130
4131 // Attach the reply to DebugInvokeReq so it can be sent to the debugger when the event thread
4132 // is ready to suspend.
4133 BuildInvokeReply(pReq->reply, pReq->request_id, result_tag, result_value, exceptionObjectId);
4134}
4135
4136void Dbg::BuildInvokeReply(JDWP::ExpandBuf* pReply, uint32_t request_id, JDWP::JdwpTag result_tag,
4137 uint64_t result_value, JDWP::ObjectId exception) {
4138 // Make room for the JDWP header since we do not know the size of the reply yet.
4139 JDWP::expandBufAddSpace(pReply, kJDWPHeaderLen);
4140
4141 size_t width = GetTagWidth(result_tag);
4142 JDWP::expandBufAdd1(pReply, result_tag);
4143 if (width != 0) {
4144 WriteValue(pReply, width, result_value);
4145 }
4146 JDWP::expandBufAdd1(pReply, JDWP::JT_OBJECT);
4147 JDWP::expandBufAddObjectId(pReply, exception);
4148
4149 // Now we know the size, we can complete the JDWP header.
4150 uint8_t* buf = expandBufGetBuffer(pReply);
4151 JDWP::Set4BE(buf + kJDWPHeaderSizeOffset, expandBufGetLength(pReply));
4152 JDWP::Set4BE(buf + kJDWPHeaderIdOffset, request_id);
4153 JDWP::Set1(buf + kJDWPHeaderFlagsOffset, kJDWPFlagReply); // flags
4154 JDWP::Set2BE(buf + kJDWPHeaderErrorCodeOffset, JDWP::ERR_NONE);
4155}
4156
4157void Dbg::FinishInvokeMethod(DebugInvokeReq* pReq) {
4158 CHECK_NE(Thread::Current(), GetDebugThread()) << "This must be called by the event thread";
4159
4160 JDWP::ExpandBuf* const pReply = pReq->reply;
4161 CHECK(pReply != nullptr) << "No reply attached to DebugInvokeReq";
4162
4163 // We need to prevent other threads (including JDWP thread) from interacting with the debugger
4164 // while we send the reply but are not yet suspended. The JDWP token will be released just before
4165 // we suspend ourself again (see ThreadList::SuspendSelfForDebugger).
4166 gJdwpState->AcquireJdwpTokenForEvent(pReq->thread_id);
4167
4168 // Send the reply unless the debugger detached before the completion of the method.
4169 if (IsDebuggerActive()) {
4170 const size_t replyDataLength = expandBufGetLength(pReply) - kJDWPHeaderLen;
4171 VLOG(jdwp) << StringPrintf("REPLY INVOKE id=0x%06x (length=%zu)",
4172 pReq->request_id, replyDataLength);
4173
4174 gJdwpState->SendRequest(pReply);
4175 } else {
4176 VLOG(jdwp) << "Not sending invoke reply because debugger detached";
Elliott Hughesd07986f2011-12-06 18:27:45 -08004177 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -07004178}
4179
Elliott Hughesd07986f2011-12-06 18:27:45 -08004180/*
Elliott Hughes4b9702c2013-02-20 18:13:24 -08004181 * "request" contains a full JDWP packet, possibly with multiple chunks. We
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07004182 * need to process each, accumulate the replies, and ship the whole thing
4183 * back.
4184 *
4185 * Returns "true" if we have a reply. The reply buffer is newly allocated,
4186 * and includes the chunk type/length, followed by the data.
4187 *
Elliott Hughes3d30d9b2011-12-07 17:35:48 -08004188 * OLD-TODO: we currently assume that the request and reply include a single
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07004189 * chunk. If this becomes inconvenient we will need to adapt.
4190 */
Ian Rogersc0542af2014-09-03 16:16:56 -07004191bool Dbg::DdmHandlePacket(JDWP::Request* request, uint8_t** pReplyBuf, int* pReplyLen) {
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07004192 Thread* self = Thread::Current();
4193 JNIEnv* env = self->GetJniEnv();
4194
Ian Rogersc0542af2014-09-03 16:16:56 -07004195 uint32_t type = request->ReadUnsigned32("type");
4196 uint32_t length = request->ReadUnsigned32("length");
Elliott Hughes4b9702c2013-02-20 18:13:24 -08004197
4198 // Create a byte[] corresponding to 'request'.
Ian Rogersc0542af2014-09-03 16:16:56 -07004199 size_t request_length = request->size();
Elliott Hughes4b9702c2013-02-20 18:13:24 -08004200 ScopedLocalRef<jbyteArray> dataArray(env, env->NewByteArray(request_length));
Ian Rogersc0542af2014-09-03 16:16:56 -07004201 if (dataArray.get() == nullptr) {
Elliott Hughes4b9702c2013-02-20 18:13:24 -08004202 LOG(WARNING) << "byte[] allocation failed: " << request_length;
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07004203 env->ExceptionClear();
4204 return false;
4205 }
Ian Rogersc0542af2014-09-03 16:16:56 -07004206 env->SetByteArrayRegion(dataArray.get(), 0, request_length,
4207 reinterpret_cast<const jbyte*>(request->data()));
4208 request->Skip(request_length);
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07004209
4210 // Run through and find all chunks. [Currently just find the first.]
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004211 ScopedByteArrayRO contents(env, dataArray.get());
Elliott Hughes4b9702c2013-02-20 18:13:24 -08004212 if (length != request_length) {
Ian Rogersef7d42f2014-01-06 12:55:46 -08004213 LOG(WARNING) << StringPrintf("bad chunk found (len=%u pktLen=%zd)", length, request_length);
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07004214 return false;
4215 }
4216
4217 // Call "private static Chunk dispatch(int type, byte[] data, int offset, int length)".
Elliott Hugheseac76672012-05-24 21:56:51 -07004218 ScopedLocalRef<jobject> chunk(env, env->CallStaticObjectMethod(WellKnownClasses::org_apache_harmony_dalvik_ddmc_DdmServer,
4219 WellKnownClasses::org_apache_harmony_dalvik_ddmc_DdmServer_dispatch,
Elliott Hughes4b9702c2013-02-20 18:13:24 -08004220 type, dataArray.get(), 0, length));
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07004221 if (env->ExceptionCheck()) {
4222 LOG(INFO) << StringPrintf("Exception thrown by dispatcher for 0x%08x", type);
4223 env->ExceptionDescribe();
4224 env->ExceptionClear();
4225 return false;
4226 }
4227
Ian Rogersc0542af2014-09-03 16:16:56 -07004228 if (chunk.get() == nullptr) {
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07004229 return false;
4230 }
4231
4232 /*
4233 * Pull the pieces out of the chunk. We copy the results into a
4234 * newly-allocated buffer that the caller can free. We don't want to
4235 * continue using the Chunk object because nothing has a reference to it.
4236 *
4237 * We could avoid this by returning type/data/offset/length and having
4238 * the caller be aware of the object lifetime issues, but that
Elliott Hughes81ff3182012-03-23 20:35:56 -07004239 * integrates the JDWP code more tightly into the rest of the runtime, and doesn't work
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07004240 * if we have responses for multiple chunks.
4241 *
4242 * So we're pretty much stuck with copying data around multiple times.
4243 */
Elliott Hugheseac76672012-05-24 21:56:51 -07004244 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 -08004245 jint offset = env->GetIntField(chunk.get(), WellKnownClasses::org_apache_harmony_dalvik_ddmc_Chunk_offset);
Elliott Hugheseac76672012-05-24 21:56:51 -07004246 length = env->GetIntField(chunk.get(), WellKnownClasses::org_apache_harmony_dalvik_ddmc_Chunk_length);
Elliott Hugheseac76672012-05-24 21:56:51 -07004247 type = env->GetIntField(chunk.get(), WellKnownClasses::org_apache_harmony_dalvik_ddmc_Chunk_type);
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07004248
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08004249 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 -07004250 if (length == 0 || replyData.get() == nullptr) {
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07004251 return false;
4252 }
4253
Elliott Hughes4b9702c2013-02-20 18:13:24 -08004254 const int kChunkHdrLen = 8;
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07004255 uint8_t* reply = new uint8_t[length + kChunkHdrLen];
Ian Rogersc0542af2014-09-03 16:16:56 -07004256 if (reply == nullptr) {
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07004257 LOG(WARNING) << "malloc failed: " << (length + kChunkHdrLen);
4258 return false;
4259 }
Elliott Hughesf7c3b662011-10-27 12:04:56 -07004260 JDWP::Set4BE(reply + 0, type);
4261 JDWP::Set4BE(reply + 4, length);
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004262 env->GetByteArrayRegion(replyData.get(), offset, length, reinterpret_cast<jbyte*>(reply + kChunkHdrLen));
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07004263
4264 *pReplyBuf = reply;
4265 *pReplyLen = length + kChunkHdrLen;
4266
Elliott Hughes4b9702c2013-02-20 18:13:24 -08004267 VLOG(jdwp) << StringPrintf("dvmHandleDdm returning type=%.4s %p len=%d", reinterpret_cast<char*>(reply), reply, length);
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07004268 return true;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07004269}
4270
Elliott Hughesa2155262011-11-16 16:26:58 -08004271void Dbg::DdmBroadcast(bool connect) {
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08004272 VLOG(jdwp) << "Broadcasting DDM " << (connect ? "connect" : "disconnect") << "...";
Elliott Hughes47fce012011-10-25 18:37:19 -07004273
4274 Thread* self = Thread::Current();
Ian Rogers50b35e22012-10-04 10:09:15 -07004275 if (self->GetState() != kRunnable) {
4276 LOG(ERROR) << "DDM broadcast in thread state " << self->GetState();
4277 /* try anyway? */
Elliott Hughes47fce012011-10-25 18:37:19 -07004278 }
4279
4280 JNIEnv* env = self->GetJniEnv();
Elliott Hughes47fce012011-10-25 18:37:19 -07004281 jint event = connect ? 1 /*DdmServer.CONNECTED*/ : 2 /*DdmServer.DISCONNECTED*/;
Elliott Hugheseac76672012-05-24 21:56:51 -07004282 env->CallStaticVoidMethod(WellKnownClasses::org_apache_harmony_dalvik_ddmc_DdmServer,
4283 WellKnownClasses::org_apache_harmony_dalvik_ddmc_DdmServer_broadcast,
4284 event);
Elliott Hughes47fce012011-10-25 18:37:19 -07004285 if (env->ExceptionCheck()) {
4286 LOG(ERROR) << "DdmServer.broadcast " << event << " failed";
4287 env->ExceptionDescribe();
4288 env->ExceptionClear();
4289 }
4290}
4291
Elliott Hughes872d4ec2011-10-21 17:07:15 -07004292void Dbg::DdmConnected() {
Elliott Hughesa2155262011-11-16 16:26:58 -08004293 Dbg::DdmBroadcast(true);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07004294}
4295
4296void Dbg::DdmDisconnected() {
Elliott Hughesa2155262011-11-16 16:26:58 -08004297 Dbg::DdmBroadcast(false);
Elliott Hughes47fce012011-10-25 18:37:19 -07004298 gDdmThreadNotification = false;
4299}
4300
4301/*
Elliott Hughes82188472011-11-07 18:11:48 -08004302 * Send a notification when a thread starts, stops, or changes its name.
Elliott Hughes47fce012011-10-25 18:37:19 -07004303 *
4304 * Because we broadcast the full set of threads when the notifications are
4305 * first enabled, it's possible for "thread" to be actively executing.
4306 */
Elliott Hughes82188472011-11-07 18:11:48 -08004307void Dbg::DdmSendThreadNotification(Thread* t, uint32_t type) {
Elliott Hughes47fce012011-10-25 18:37:19 -07004308 if (!gDdmThreadNotification) {
4309 return;
4310 }
4311
Elliott Hughes82188472011-11-07 18:11:48 -08004312 if (type == CHUNK_TYPE("THDE")) {
Elliott Hughes47fce012011-10-25 18:37:19 -07004313 uint8_t buf[4];
Ian Rogersd9c4fc92013-10-01 19:45:43 -07004314 JDWP::Set4BE(&buf[0], t->GetThreadId());
Elliott Hughes47fce012011-10-25 18:37:19 -07004315 Dbg::DdmSendChunk(CHUNK_TYPE("THDE"), 4, buf);
Elliott Hughes82188472011-11-07 18:11:48 -08004316 } else {
4317 CHECK(type == CHUNK_TYPE("THCR") || type == CHUNK_TYPE("THNM")) << type;
Ian Rogers00f7d0e2012-07-19 15:28:27 -07004318 ScopedObjectAccessUnchecked soa(Thread::Current());
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004319 StackHandleScope<1> hs(soa.Self());
4320 Handle<mirror::String> name(hs.NewHandle(t->GetThreadName(soa)));
Ian Rogersc0542af2014-09-03 16:16:56 -07004321 size_t char_count = (name.Get() != nullptr) ? name->GetLength() : 0;
Jeff Hao848f70a2014-01-15 13:49:50 -08004322 const jchar* chars = (name.Get() != nullptr) ? name->GetValue() : nullptr;
Elliott Hughes82188472011-11-07 18:11:48 -08004323
Elliott Hughes21f32d72011-11-09 17:44:13 -08004324 std::vector<uint8_t> bytes;
Ian Rogersd9c4fc92013-10-01 19:45:43 -07004325 JDWP::Append4BE(bytes, t->GetThreadId());
Elliott Hughes545a0642011-11-08 19:10:03 -08004326 JDWP::AppendUtf16BE(bytes, chars, char_count);
Elliott Hughes21f32d72011-11-09 17:44:13 -08004327 CHECK_EQ(bytes.size(), char_count*2 + sizeof(uint32_t)*2);
4328 Dbg::DdmSendChunk(type, bytes);
Elliott Hughes47fce012011-10-25 18:37:19 -07004329 }
4330}
4331
Elliott Hughes47fce012011-10-25 18:37:19 -07004332void Dbg::DdmSetThreadNotification(bool enable) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07004333 // Enable/disable thread notifications.
Elliott Hughes47fce012011-10-25 18:37:19 -07004334 gDdmThreadNotification = enable;
4335 if (enable) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07004336 // Suspend the VM then post thread start notifications for all threads. Threads attaching will
4337 // see a suspension in progress and block until that ends. They then post their own start
4338 // notification.
4339 SuspendVM();
4340 std::list<Thread*> threads;
Ian Rogers50b35e22012-10-04 10:09:15 -07004341 Thread* self = Thread::Current();
Ian Rogers00f7d0e2012-07-19 15:28:27 -07004342 {
Ian Rogers50b35e22012-10-04 10:09:15 -07004343 MutexLock mu(self, *Locks::thread_list_lock_);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07004344 threads = Runtime::Current()->GetThreadList()->GetList();
4345 }
4346 {
Ian Rogers50b35e22012-10-04 10:09:15 -07004347 ScopedObjectAccess soa(self);
Mathieu Chartier02e25112013-08-14 16:14:24 -07004348 for (Thread* thread : threads) {
4349 Dbg::DdmSendThreadNotification(thread, CHUNK_TYPE("THCR"));
Ian Rogers00f7d0e2012-07-19 15:28:27 -07004350 }
4351 }
4352 ResumeVM();
Elliott Hughes47fce012011-10-25 18:37:19 -07004353 }
4354}
4355
Elliott Hughesa2155262011-11-16 16:26:58 -08004356void Dbg::PostThreadStartOrStop(Thread* t, uint32_t type) {
Elliott Hughesc0f09332012-03-26 13:27:06 -07004357 if (IsDebuggerActive()) {
Sebastien Hertz6995c602014-09-09 12:10:13 +02004358 gJdwpState->PostThreadChange(t, type == CHUNK_TYPE("THCR"));
Elliott Hughes47fce012011-10-25 18:37:19 -07004359 }
Elliott Hughes82188472011-11-07 18:11:48 -08004360 Dbg::DdmSendThreadNotification(t, type);
Elliott Hughes47fce012011-10-25 18:37:19 -07004361}
4362
4363void Dbg::PostThreadStart(Thread* t) {
Elliott Hughesa2155262011-11-16 16:26:58 -08004364 Dbg::PostThreadStartOrStop(t, CHUNK_TYPE("THCR"));
Elliott Hughes47fce012011-10-25 18:37:19 -07004365}
4366
4367void Dbg::PostThreadDeath(Thread* t) {
Elliott Hughesa2155262011-11-16 16:26:58 -08004368 Dbg::PostThreadStartOrStop(t, CHUNK_TYPE("THDE"));
Elliott Hughes872d4ec2011-10-21 17:07:15 -07004369}
4370
Elliott Hughes82188472011-11-07 18:11:48 -08004371void Dbg::DdmSendChunk(uint32_t type, size_t byte_count, const uint8_t* buf) {
Ian Rogersc0542af2014-09-03 16:16:56 -07004372 CHECK(buf != nullptr);
Elliott Hughes3bb81562011-10-21 18:52:59 -07004373 iovec vec[1];
4374 vec[0].iov_base = reinterpret_cast<void*>(const_cast<uint8_t*>(buf));
4375 vec[0].iov_len = byte_count;
4376 Dbg::DdmSendChunkV(type, vec, 1);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07004377}
4378
Elliott Hughes21f32d72011-11-09 17:44:13 -08004379void Dbg::DdmSendChunk(uint32_t type, const std::vector<uint8_t>& bytes) {
4380 DdmSendChunk(type, bytes.size(), &bytes[0]);
4381}
4382
Brian Carlstromf5293522013-07-19 00:24:00 -07004383void Dbg::DdmSendChunkV(uint32_t type, const iovec* iov, int iov_count) {
Ian Rogersc0542af2014-09-03 16:16:56 -07004384 if (gJdwpState == nullptr) {
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08004385 VLOG(jdwp) << "Debugger thread not active, ignoring DDM send: " << type;
Elliott Hughes3bb81562011-10-21 18:52:59 -07004386 } else {
Elliott Hughescccd84f2011-12-05 16:51:54 -08004387 gJdwpState->DdmSendChunkV(type, iov, iov_count);
Elliott Hughes3bb81562011-10-21 18:52:59 -07004388 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -07004389}
4390
Mathieu Chartierad466ad2015-01-08 16:28:08 -08004391JDWP::JdwpState* Dbg::GetJdwpState() {
4392 return gJdwpState;
4393}
4394
Elliott Hughes767a1472011-10-26 18:49:02 -07004395int Dbg::DdmHandleHpifChunk(HpifWhen when) {
4396 if (when == HPIF_WHEN_NOW) {
Elliott Hughes7162ad92011-10-27 14:08:42 -07004397 DdmSendHeapInfo(when);
Elliott Hughes767a1472011-10-26 18:49:02 -07004398 return true;
4399 }
4400
4401 if (when != HPIF_WHEN_NEVER && when != HPIF_WHEN_NEXT_GC && when != HPIF_WHEN_EVERY_GC) {
4402 LOG(ERROR) << "invalid HpifWhen value: " << static_cast<int>(when);
4403 return false;
4404 }
4405
4406 gDdmHpifWhen = when;
4407 return true;
4408}
4409
4410bool Dbg::DdmHandleHpsgNhsgChunk(Dbg::HpsgWhen when, Dbg::HpsgWhat what, bool native) {
4411 if (when != HPSG_WHEN_NEVER && when != HPSG_WHEN_EVERY_GC) {
4412 LOG(ERROR) << "invalid HpsgWhen value: " << static_cast<int>(when);
4413 return false;
4414 }
4415
4416 if (what != HPSG_WHAT_MERGED_OBJECTS && what != HPSG_WHAT_DISTINCT_OBJECTS) {
4417 LOG(ERROR) << "invalid HpsgWhat value: " << static_cast<int>(what);
4418 return false;
4419 }
4420
4421 if (native) {
4422 gDdmNhsgWhen = when;
4423 gDdmNhsgWhat = what;
4424 } else {
4425 gDdmHpsgWhen = when;
4426 gDdmHpsgWhat = what;
4427 }
4428 return true;
4429}
4430
Elliott Hughes7162ad92011-10-27 14:08:42 -07004431void Dbg::DdmSendHeapInfo(HpifWhen reason) {
4432 // If there's a one-shot 'when', reset it.
4433 if (reason == gDdmHpifWhen) {
4434 if (gDdmHpifWhen == HPIF_WHEN_NEXT_GC) {
4435 gDdmHpifWhen = HPIF_WHEN_NEVER;
4436 }
4437 }
4438
4439 /*
4440 * Chunk HPIF (client --> server)
4441 *
4442 * Heap Info. General information about the heap,
4443 * suitable for a summary display.
4444 *
4445 * [u4]: number of heaps
4446 *
4447 * For each heap:
4448 * [u4]: heap ID
4449 * [u8]: timestamp in ms since Unix epoch
4450 * [u1]: capture reason (same as 'when' value from server)
4451 * [u4]: max heap size in bytes (-Xmx)
4452 * [u4]: current heap size in bytes
4453 * [u4]: current number of bytes allocated
4454 * [u4]: current number of objects allocated
4455 */
4456 uint8_t heap_count = 1;
Ian Rogers1d54e732013-05-02 21:10:01 -07004457 gc::Heap* heap = Runtime::Current()->GetHeap();
Elliott Hughes21f32d72011-11-09 17:44:13 -08004458 std::vector<uint8_t> bytes;
Elliott Hughes545a0642011-11-08 19:10:03 -08004459 JDWP::Append4BE(bytes, heap_count);
Brian Carlstrom7934ac22013-07-26 10:54:15 -07004460 JDWP::Append4BE(bytes, 1); // Heap id (bogus; we only have one heap).
Elliott Hughes545a0642011-11-08 19:10:03 -08004461 JDWP::Append8BE(bytes, MilliTime());
4462 JDWP::Append1BE(bytes, reason);
Brian Carlstrom7934ac22013-07-26 10:54:15 -07004463 JDWP::Append4BE(bytes, heap->GetMaxMemory()); // Max allowed heap size in bytes.
4464 JDWP::Append4BE(bytes, heap->GetTotalMemory()); // Current heap size in bytes.
Elliott Hughesb3bd5f02012-03-08 21:05:27 -08004465 JDWP::Append4BE(bytes, heap->GetBytesAllocated());
4466 JDWP::Append4BE(bytes, heap->GetObjectsAllocated());
Elliott Hughes21f32d72011-11-09 17:44:13 -08004467 CHECK_EQ(bytes.size(), 4U + (heap_count * (4 + 8 + 1 + 4 + 4 + 4 + 4)));
4468 Dbg::DdmSendChunk(CHUNK_TYPE("HPIF"), bytes);
Elliott Hughes767a1472011-10-26 18:49:02 -07004469}
4470
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004471enum HpsgSolidity {
4472 SOLIDITY_FREE = 0,
4473 SOLIDITY_HARD = 1,
4474 SOLIDITY_SOFT = 2,
4475 SOLIDITY_WEAK = 3,
4476 SOLIDITY_PHANTOM = 4,
4477 SOLIDITY_FINALIZABLE = 5,
4478 SOLIDITY_SWEEP = 6,
4479};
4480
4481enum HpsgKind {
4482 KIND_OBJECT = 0,
4483 KIND_CLASS_OBJECT = 1,
4484 KIND_ARRAY_1 = 2,
4485 KIND_ARRAY_2 = 3,
4486 KIND_ARRAY_4 = 4,
4487 KIND_ARRAY_8 = 5,
4488 KIND_UNKNOWN = 6,
4489 KIND_NATIVE = 7,
4490};
4491
4492#define HPSG_PARTIAL (1<<7)
4493#define HPSG_STATE(solidity, kind) ((uint8_t)((((kind) & 0x7) << 3) | ((solidity) & 0x7)))
4494
Ian Rogers30fab402012-01-23 15:43:46 -08004495class HeapChunkContext {
4496 public:
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004497 // Maximum chunk size. Obtain this from the formula:
4498 // (((maximum_heap_size / ALLOCATION_UNIT_SIZE) + 255) / 256) * 2
4499 HeapChunkContext(bool merge, bool native)
Ian Rogers30fab402012-01-23 15:43:46 -08004500 : buf_(16384 - 16),
4501 type_(0),
Mathieu Chartier36dab362014-07-30 14:59:56 -07004502 chunk_overhead_(0) {
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004503 Reset();
4504 if (native) {
Ian Rogers30fab402012-01-23 15:43:46 -08004505 type_ = CHUNK_TYPE("NHSG");
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004506 } else {
Ian Rogers30fab402012-01-23 15:43:46 -08004507 type_ = merge ? CHUNK_TYPE("HPSG") : CHUNK_TYPE("HPSO");
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004508 }
4509 }
4510
4511 ~HeapChunkContext() {
Ian Rogers30fab402012-01-23 15:43:46 -08004512 if (p_ > &buf_[0]) {
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004513 Flush();
4514 }
4515 }
4516
Mathieu Chartier36dab362014-07-30 14:59:56 -07004517 void SetChunkOverhead(size_t chunk_overhead) {
4518 chunk_overhead_ = chunk_overhead;
4519 }
4520
4521 void ResetStartOfNextChunk() {
4522 startOfNextMemoryChunk_ = nullptr;
4523 }
4524
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004525 void EnsureHeader(const void* chunk_ptr) {
Ian Rogers30fab402012-01-23 15:43:46 -08004526 if (!needHeader_) {
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004527 return;
4528 }
4529
4530 // Start a new HPSx chunk.
Brian Carlstrom7934ac22013-07-26 10:54:15 -07004531 JDWP::Write4BE(&p_, 1); // Heap id (bogus; we only have one heap).
4532 JDWP::Write1BE(&p_, 8); // Size of allocation unit, in bytes.
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004533
Brian Carlstrom7934ac22013-07-26 10:54:15 -07004534 JDWP::Write4BE(&p_, reinterpret_cast<uintptr_t>(chunk_ptr)); // virtual address of segment start.
4535 JDWP::Write4BE(&p_, 0); // offset of this piece (relative to the virtual address).
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004536 // [u4]: length of piece, in allocation units
4537 // 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 -08004538 pieceLenField_ = p_;
4539 JDWP::Write4BE(&p_, 0x55555555);
4540 needHeader_ = false;
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004541 }
4542
Ian Rogersb726dcb2012-09-05 08:57:23 -07004543 void Flush() SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Ian Rogersc0542af2014-09-03 16:16:56 -07004544 if (pieceLenField_ == nullptr) {
Ian Rogersd636b062013-01-18 17:51:18 -08004545 // Flush immediately post Reset (maybe back-to-back Flush). Ignore.
4546 CHECK(needHeader_);
4547 return;
4548 }
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004549 // Patch the "length of piece" field.
Ian Rogers30fab402012-01-23 15:43:46 -08004550 CHECK_LE(&buf_[0], pieceLenField_);
4551 CHECK_LE(pieceLenField_, p_);
4552 JDWP::Set4BE(pieceLenField_, totalAllocationUnits_);
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004553
Ian Rogers30fab402012-01-23 15:43:46 -08004554 Dbg::DdmSendChunk(type_, p_ - &buf_[0], &buf_[0]);
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004555 Reset();
4556 }
4557
Mathieu Chartierbc689b72014-12-14 17:01:31 -08004558 static void HeapChunkJavaCallback(void* start, void* end, size_t used_bytes, void* arg)
Ian Rogersb726dcb2012-09-05 08:57:23 -07004559 SHARED_LOCKS_REQUIRED(Locks::heap_bitmap_lock_,
4560 Locks::mutator_lock_) {
Mathieu Chartierbc689b72014-12-14 17:01:31 -08004561 reinterpret_cast<HeapChunkContext*>(arg)->HeapChunkJavaCallback(start, end, used_bytes);
4562 }
4563
4564 static void HeapChunkNativeCallback(void* start, void* end, size_t used_bytes, void* arg)
4565 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
4566 reinterpret_cast<HeapChunkContext*>(arg)->HeapChunkNativeCallback(start, end, used_bytes);
Elliott Hughesa2155262011-11-16 16:26:58 -08004567 }
4568
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004569 private:
Elliott Hughesa2155262011-11-16 16:26:58 -08004570 enum { ALLOCATION_UNIT_SIZE = 8 };
4571
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004572 void Reset() {
Ian Rogers30fab402012-01-23 15:43:46 -08004573 p_ = &buf_[0];
Mathieu Chartier36dab362014-07-30 14:59:56 -07004574 ResetStartOfNextChunk();
Ian Rogers30fab402012-01-23 15:43:46 -08004575 totalAllocationUnits_ = 0;
4576 needHeader_ = true;
Ian Rogersc0542af2014-09-03 16:16:56 -07004577 pieceLenField_ = nullptr;
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004578 }
4579
Mathieu Chartierbc689b72014-12-14 17:01:31 -08004580 bool IsNative() const {
4581 return type_ == CHUNK_TYPE("NHSG");
4582 }
4583
4584 // Returns true if the object is not an empty chunk.
4585 bool ProcessRecord(void* start, size_t used_bytes) SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Ian Rogers30fab402012-01-23 15:43:46 -08004586 // Note: heap call backs cannot manipulate the heap upon which they are crawling, care is taken
4587 // in the following code not to allocate memory, by ensuring buf_ is of the correct size
Ian Rogers15bf2d32012-08-28 17:33:04 -07004588 if (used_bytes == 0) {
Mathieu Chartierbc689b72014-12-14 17:01:31 -08004589 if (start == nullptr) {
4590 // Reset for start of new heap.
4591 startOfNextMemoryChunk_ = nullptr;
4592 Flush();
4593 }
4594 // Only process in use memory so that free region information
4595 // also includes dlmalloc book keeping.
4596 return false;
Elliott Hughesa2155262011-11-16 16:26:58 -08004597 }
Ian Rogersc0542af2014-09-03 16:16:56 -07004598 if (startOfNextMemoryChunk_ != nullptr) {
Mathieu Chartierbc689b72014-12-14 17:01:31 -08004599 // Transmit any pending free memory. Native free memory of over kMaxFreeLen could be because
4600 // of the use of mmaps, so don't report. If not free memory then start a new segment.
4601 bool flush = true;
4602 if (start > startOfNextMemoryChunk_) {
4603 const size_t kMaxFreeLen = 2 * kPageSize;
4604 void* free_start = startOfNextMemoryChunk_;
4605 void* free_end = start;
4606 const size_t free_len =
4607 reinterpret_cast<uintptr_t>(free_end) - reinterpret_cast<uintptr_t>(free_start);
4608 if (!IsNative() || free_len < kMaxFreeLen) {
4609 AppendChunk(HPSG_STATE(SOLIDITY_FREE, 0), free_start, free_len, IsNative());
4610 flush = false;
Ian Rogers15bf2d32012-08-28 17:33:04 -07004611 }
Mathieu Chartierbc689b72014-12-14 17:01:31 -08004612 }
4613 if (flush) {
4614 startOfNextMemoryChunk_ = nullptr;
4615 Flush();
4616 }
Ian Rogers15bf2d32012-08-28 17:33:04 -07004617 }
Mathieu Chartierbc689b72014-12-14 17:01:31 -08004618 return true;
Ian Rogers15bf2d32012-08-28 17:33:04 -07004619 }
Elliott Hughesa2155262011-11-16 16:26:58 -08004620
Mathieu Chartierbc689b72014-12-14 17:01:31 -08004621 void HeapChunkNativeCallback(void* start, void* /*end*/, size_t used_bytes)
4622 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
4623 if (ProcessRecord(start, used_bytes)) {
4624 uint8_t state = ExamineNativeObject(start);
4625 AppendChunk(state, start, used_bytes + chunk_overhead_, true /*is_native*/);
4626 startOfNextMemoryChunk_ = reinterpret_cast<char*>(start) + used_bytes + chunk_overhead_;
4627 }
4628 }
4629
4630 void HeapChunkJavaCallback(void* start, void* /*end*/, size_t used_bytes)
4631 SHARED_LOCKS_REQUIRED(Locks::heap_bitmap_lock_, Locks::mutator_lock_) {
4632 if (ProcessRecord(start, used_bytes)) {
4633 // Determine the type of this chunk.
4634 // OLD-TODO: if context.merge, see if this chunk is different from the last chunk.
4635 // If it's the same, we should combine them.
4636 uint8_t state = ExamineJavaObject(reinterpret_cast<mirror::Object*>(start));
4637 AppendChunk(state, start, used_bytes + chunk_overhead_, false /*is_native*/);
4638 startOfNextMemoryChunk_ = reinterpret_cast<char*>(start) + used_bytes + chunk_overhead_;
4639 }
4640 }
4641
4642 void AppendChunk(uint8_t state, void* ptr, size_t length, bool is_native)
Ian Rogersb726dcb2012-09-05 08:57:23 -07004643 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Ian Rogers15bf2d32012-08-28 17:33:04 -07004644 // Make sure there's enough room left in the buffer.
4645 // We need to use two bytes for every fractional 256 allocation units used by the chunk plus
4646 // 17 bytes for any header.
Mathieu Chartierbc689b72014-12-14 17:01:31 -08004647 const size_t needed = ((RoundUp(length / ALLOCATION_UNIT_SIZE, 256) / 256) * 2) + 17;
4648 size_t byte_left = &buf_.back() - p_;
4649 if (byte_left < needed) {
4650 if (is_native) {
Pavel Vyssotski7522c742014-12-08 13:38:26 +06004651 // Cannot trigger memory allocation while walking native heap.
Pavel Vyssotski7522c742014-12-08 13:38:26 +06004652 return;
4653 }
Ian Rogers15bf2d32012-08-28 17:33:04 -07004654 Flush();
4655 }
4656
Mathieu Chartierbc689b72014-12-14 17:01:31 -08004657 byte_left = &buf_.back() - p_;
4658 if (byte_left < needed) {
Ian Rogers15bf2d32012-08-28 17:33:04 -07004659 LOG(WARNING) << "Chunk is too big to transmit (chunk_len=" << length << ", "
4660 << needed << " bytes)";
4661 return;
4662 }
4663 EnsureHeader(ptr);
Elliott Hughesa2155262011-11-16 16:26:58 -08004664 // Write out the chunk description.
Ian Rogers15bf2d32012-08-28 17:33:04 -07004665 length /= ALLOCATION_UNIT_SIZE; // Convert to allocation units.
4666 totalAllocationUnits_ += length;
4667 while (length > 256) {
Ian Rogers30fab402012-01-23 15:43:46 -08004668 *p_++ = state | HPSG_PARTIAL;
4669 *p_++ = 255; // length - 1
Ian Rogers15bf2d32012-08-28 17:33:04 -07004670 length -= 256;
Elliott Hughesa2155262011-11-16 16:26:58 -08004671 }
Ian Rogers30fab402012-01-23 15:43:46 -08004672 *p_++ = state;
Ian Rogers15bf2d32012-08-28 17:33:04 -07004673 *p_++ = length - 1;
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004674 }
4675
Mathieu Chartierbc689b72014-12-14 17:01:31 -08004676 uint8_t ExamineNativeObject(const void* p) SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
4677 return p == nullptr ? HPSG_STATE(SOLIDITY_FREE, 0) : HPSG_STATE(SOLIDITY_HARD, KIND_NATIVE);
4678 }
4679
4680 uint8_t ExamineJavaObject(mirror::Object* o)
Ian Rogersef7d42f2014-01-06 12:55:46 -08004681 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_, Locks::heap_bitmap_lock_) {
Ian Rogersc0542af2014-09-03 16:16:56 -07004682 if (o == nullptr) {
Elliott Hughesa2155262011-11-16 16:26:58 -08004683 return HPSG_STATE(SOLIDITY_FREE, 0);
4684 }
Elliott Hughesa2155262011-11-16 16:26:58 -08004685 // It's an allocated chunk. Figure out what it is.
Mathieu Chartierbc689b72014-12-14 17:01:31 -08004686 gc::Heap* heap = Runtime::Current()->GetHeap();
4687 if (!heap->IsLiveObjectLocked(o)) {
4688 LOG(ERROR) << "Invalid object in managed heap: " << o;
Elliott Hughesa2155262011-11-16 16:26:58 -08004689 return HPSG_STATE(SOLIDITY_HARD, KIND_NATIVE);
4690 }
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08004691 mirror::Class* c = o->GetClass();
Ian Rogersc0542af2014-09-03 16:16:56 -07004692 if (c == nullptr) {
Elliott Hughesa2155262011-11-16 16:26:58 -08004693 // The object was probably just created but hasn't been initialized yet.
4694 return HPSG_STATE(SOLIDITY_HARD, KIND_OBJECT);
4695 }
Mathieu Chartierbc689b72014-12-14 17:01:31 -08004696 if (!heap->IsValidObjectAddress(c)) {
Ian Rogers15bf2d32012-08-28 17:33:04 -07004697 LOG(ERROR) << "Invalid class for managed heap object: " << o << " " << c;
Elliott Hughesa2155262011-11-16 16:26:58 -08004698 return HPSG_STATE(SOLIDITY_HARD, KIND_UNKNOWN);
4699 }
Mathieu Chartierf26e1b32015-01-29 10:47:10 -08004700 if (c->GetClass() == nullptr) {
4701 LOG(ERROR) << "Null class of class " << c << " for object " << o;
4702 return HPSG_STATE(SOLIDITY_HARD, KIND_UNKNOWN);
4703 }
Elliott Hughesa2155262011-11-16 16:26:58 -08004704 if (c->IsClassClass()) {
4705 return HPSG_STATE(SOLIDITY_HARD, KIND_CLASS_OBJECT);
4706 }
Elliott Hughesa2155262011-11-16 16:26:58 -08004707 if (c->IsArrayClass()) {
Elliott Hughesa2155262011-11-16 16:26:58 -08004708 switch (c->GetComponentSize()) {
4709 case 1: return HPSG_STATE(SOLIDITY_HARD, KIND_ARRAY_1);
4710 case 2: return HPSG_STATE(SOLIDITY_HARD, KIND_ARRAY_2);
4711 case 4: return HPSG_STATE(SOLIDITY_HARD, KIND_ARRAY_4);
4712 case 8: return HPSG_STATE(SOLIDITY_HARD, KIND_ARRAY_8);
4713 }
4714 }
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004715 return HPSG_STATE(SOLIDITY_HARD, KIND_OBJECT);
4716 }
4717
Ian Rogers30fab402012-01-23 15:43:46 -08004718 std::vector<uint8_t> buf_;
4719 uint8_t* p_;
4720 uint8_t* pieceLenField_;
Ian Rogers15bf2d32012-08-28 17:33:04 -07004721 void* startOfNextMemoryChunk_;
Ian Rogers30fab402012-01-23 15:43:46 -08004722 size_t totalAllocationUnits_;
4723 uint32_t type_;
Ian Rogers30fab402012-01-23 15:43:46 -08004724 bool needHeader_;
Mathieu Chartier36dab362014-07-30 14:59:56 -07004725 size_t chunk_overhead_;
Ian Rogers30fab402012-01-23 15:43:46 -08004726
Elliott Hughesa2155262011-11-16 16:26:58 -08004727 DISALLOW_COPY_AND_ASSIGN(HeapChunkContext);
4728};
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004729
Mathieu Chartier36dab362014-07-30 14:59:56 -07004730static void BumpPointerSpaceCallback(mirror::Object* obj, void* arg)
4731 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) EXCLUSIVE_LOCKS_REQUIRED(Locks::heap_bitmap_lock_) {
4732 const size_t size = RoundUp(obj->SizeOf(), kObjectAlignment);
Mathieu Chartierbc689b72014-12-14 17:01:31 -08004733 HeapChunkContext::HeapChunkJavaCallback(
Mathieu Chartier36dab362014-07-30 14:59:56 -07004734 obj, reinterpret_cast<void*>(reinterpret_cast<uintptr_t>(obj) + size), size, arg);
4735}
4736
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004737void Dbg::DdmSendHeapSegments(bool native) {
Mathieu Chartierbc689b72014-12-14 17:01:31 -08004738 Dbg::HpsgWhen when = native ? gDdmNhsgWhen : gDdmHpsgWhen;
4739 Dbg::HpsgWhat what = native ? gDdmNhsgWhat : gDdmHpsgWhat;
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004740 if (when == HPSG_WHEN_NEVER) {
4741 return;
4742 }
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004743 // Figure out what kind of chunks we'll be sending.
Mathieu Chartierbc689b72014-12-14 17:01:31 -08004744 CHECK(what == HPSG_WHAT_MERGED_OBJECTS || what == HPSG_WHAT_DISTINCT_OBJECTS)
4745 << static_cast<int>(what);
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004746
4747 // First, send a heap start chunk.
4748 uint8_t heap_id[4];
Brian Carlstrom7934ac22013-07-26 10:54:15 -07004749 JDWP::Set4BE(&heap_id[0], 1); // Heap id (bogus; we only have one heap).
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004750 Dbg::DdmSendChunk(native ? CHUNK_TYPE("NHST") : CHUNK_TYPE("HPST"), sizeof(heap_id), heap_id);
Hiroshi Yamauchicf58d4a2013-09-26 14:21:22 -07004751 Thread* self = Thread::Current();
Hiroshi Yamauchicf58d4a2013-09-26 14:21:22 -07004752 Locks::mutator_lock_->AssertSharedHeld(self);
Hiroshi Yamauchicf58d4a2013-09-26 14:21:22 -07004753
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004754 // Send a series of heap segment chunks.
Mathieu Chartierbc689b72014-12-14 17:01:31 -08004755 HeapChunkContext context(what == HPSG_WHAT_MERGED_OBJECTS, native);
Elliott Hughesa2155262011-11-16 16:26:58 -08004756 if (native) {
Ian Rogers872dd822014-10-30 11:19:14 -07004757#if defined(HAVE_ANDROID_OS) && defined(USE_DLMALLOC)
Mathieu Chartierbc689b72014-12-14 17:01:31 -08004758 dlmalloc_inspect_all(HeapChunkContext::HeapChunkNativeCallback, &context);
4759 HeapChunkContext::HeapChunkNativeCallback(nullptr, nullptr, 0, &context); // Indicate end of a space.
Christopher Ferrisc4ddc042014-05-13 14:47:50 -07004760#else
4761 UNIMPLEMENTED(WARNING) << "Native heap inspection is only supported with dlmalloc";
4762#endif
Elliott Hughesa2155262011-11-16 16:26:58 -08004763 } else {
Ian Rogers1d54e732013-05-02 21:10:01 -07004764 gc::Heap* heap = Runtime::Current()->GetHeap();
Mathieu Chartier36dab362014-07-30 14:59:56 -07004765 for (const auto& space : heap->GetContinuousSpaces()) {
4766 if (space->IsDlMallocSpace()) {
Mathieu Chartier4c69d7f2014-10-10 12:45:50 -07004767 ReaderMutexLock mu(self, *Locks::heap_bitmap_lock_);
Mathieu Chartier36dab362014-07-30 14:59:56 -07004768 // dlmalloc's chunk header is 2 * sizeof(size_t), but if the previous chunk is in use for an
4769 // allocation then the first sizeof(size_t) may belong to it.
4770 context.SetChunkOverhead(sizeof(size_t));
Mathieu Chartierbc689b72014-12-14 17:01:31 -08004771 space->AsDlMallocSpace()->Walk(HeapChunkContext::HeapChunkJavaCallback, &context);
Mathieu Chartier36dab362014-07-30 14:59:56 -07004772 } else if (space->IsRosAllocSpace()) {
4773 context.SetChunkOverhead(0);
Mathieu Chartier4c69d7f2014-10-10 12:45:50 -07004774 // Need to acquire the mutator lock before the heap bitmap lock with exclusive access since
4775 // RosAlloc's internal logic doesn't know to release and reacquire the heap bitmap lock.
4776 self->TransitionFromRunnableToSuspended(kSuspended);
4777 ThreadList* tl = Runtime::Current()->GetThreadList();
Mathieu Chartierbf9fc582015-03-13 17:21:25 -07004778 tl->SuspendAll(__FUNCTION__);
Mathieu Chartier4c69d7f2014-10-10 12:45:50 -07004779 {
4780 ReaderMutexLock mu(self, *Locks::heap_bitmap_lock_);
Mathieu Chartierbc689b72014-12-14 17:01:31 -08004781 space->AsRosAllocSpace()->Walk(HeapChunkContext::HeapChunkJavaCallback, &context);
Mathieu Chartier4c69d7f2014-10-10 12:45:50 -07004782 }
4783 tl->ResumeAll();
4784 self->TransitionFromSuspendedToRunnable();
Mathieu Chartier36dab362014-07-30 14:59:56 -07004785 } else if (space->IsBumpPointerSpace()) {
Mathieu Chartier4c69d7f2014-10-10 12:45:50 -07004786 ReaderMutexLock mu(self, *Locks::heap_bitmap_lock_);
Mathieu Chartier36dab362014-07-30 14:59:56 -07004787 context.SetChunkOverhead(0);
Mathieu Chartier36dab362014-07-30 14:59:56 -07004788 space->AsBumpPointerSpace()->Walk(BumpPointerSpaceCallback, &context);
Mathieu Chartierbc689b72014-12-14 17:01:31 -08004789 HeapChunkContext::HeapChunkJavaCallback(nullptr, nullptr, 0, &context);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08004790 } else if (space->IsRegionSpace()) {
4791 heap->IncrementDisableMovingGC(self);
4792 self->TransitionFromRunnableToSuspended(kSuspended);
4793 ThreadList* tl = Runtime::Current()->GetThreadList();
Mathieu Chartierbf9fc582015-03-13 17:21:25 -07004794 tl->SuspendAll(__FUNCTION__);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08004795 ReaderMutexLock mu(self, *Locks::heap_bitmap_lock_);
4796 context.SetChunkOverhead(0);
4797 space->AsRegionSpace()->Walk(BumpPointerSpaceCallback, &context);
4798 HeapChunkContext::HeapChunkJavaCallback(nullptr, nullptr, 0, &context);
4799 tl->ResumeAll();
4800 self->TransitionFromSuspendedToRunnable();
4801 heap->DecrementDisableMovingGC(self);
Mathieu Chartier36dab362014-07-30 14:59:56 -07004802 } else {
4803 UNIMPLEMENTED(WARNING) << "Not counting objects in space " << *space;
Mathieu Chartierb062fdd2012-07-03 09:51:48 -07004804 }
Mathieu Chartier36dab362014-07-30 14:59:56 -07004805 context.ResetStartOfNextChunk();
Mathieu Chartierb062fdd2012-07-03 09:51:48 -07004806 }
Mathieu Chartier4c69d7f2014-10-10 12:45:50 -07004807 ReaderMutexLock mu(self, *Locks::heap_bitmap_lock_);
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -07004808 // Walk the large objects, these are not in the AllocSpace.
Mathieu Chartier36dab362014-07-30 14:59:56 -07004809 context.SetChunkOverhead(0);
Mathieu Chartierbc689b72014-12-14 17:01:31 -08004810 heap->GetLargeObjectsSpace()->Walk(HeapChunkContext::HeapChunkJavaCallback, &context);
Elliott Hughesa2155262011-11-16 16:26:58 -08004811 }
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004812
4813 // Finally, send a heap end chunk.
4814 Dbg::DdmSendChunk(native ? CHUNK_TYPE("NHEN") : CHUNK_TYPE("HPEN"), sizeof(heap_id), heap_id);
Elliott Hughes767a1472011-10-26 18:49:02 -07004815}
4816
Elliott Hughesb1a58792013-07-11 18:10:58 -07004817static size_t GetAllocTrackerMax() {
4818#ifdef HAVE_ANDROID_OS
4819 // Check whether there's a system property overriding the number of records.
4820 const char* propertyName = "dalvik.vm.allocTrackerMax";
4821 char allocRecordMaxString[PROPERTY_VALUE_MAX];
4822 if (property_get(propertyName, allocRecordMaxString, "") > 0) {
4823 char* end;
4824 size_t value = strtoul(allocRecordMaxString, &end, 10);
4825 if (*end != '\0') {
Ruben Brunk3e47a742013-09-09 17:56:07 -07004826 LOG(ERROR) << "Ignoring " << propertyName << " '" << allocRecordMaxString
4827 << "' --- invalid";
Elliott Hughesb1a58792013-07-11 18:10:58 -07004828 return kDefaultNumAllocRecords;
4829 }
4830 if (!IsPowerOfTwo(value)) {
Ruben Brunk3e47a742013-09-09 17:56:07 -07004831 LOG(ERROR) << "Ignoring " << propertyName << " '" << allocRecordMaxString
4832 << "' --- not power of two";
Elliott Hughesb1a58792013-07-11 18:10:58 -07004833 return kDefaultNumAllocRecords;
4834 }
4835 return value;
4836 }
4837#endif
4838 return kDefaultNumAllocRecords;
4839}
4840
Brian Carlstrom306db812014-09-05 13:01:41 -07004841void Dbg::SetAllocTrackingEnabled(bool enable) {
4842 Thread* self = Thread::Current();
4843 if (enable) {
Sebastien Hertzb98063a2014-03-26 10:57:20 +01004844 {
Brian Carlstrom306db812014-09-05 13:01:41 -07004845 MutexLock mu(self, *Locks::alloc_tracker_lock_);
4846 if (recent_allocation_records_ != nullptr) {
4847 return; // Already enabled, bail.
Sebastien Hertzb98063a2014-03-26 10:57:20 +01004848 }
Brian Carlstrom306db812014-09-05 13:01:41 -07004849 alloc_record_max_ = GetAllocTrackerMax();
4850 LOG(INFO) << "Enabling alloc tracker (" << alloc_record_max_ << " entries of "
4851 << kMaxAllocRecordStackDepth << " frames, taking "
4852 << PrettySize(sizeof(AllocRecord) * alloc_record_max_) << ")";
4853 DCHECK_EQ(alloc_record_head_, 0U);
4854 DCHECK_EQ(alloc_record_count_, 0U);
4855 recent_allocation_records_ = new AllocRecord[alloc_record_max_];
4856 CHECK(recent_allocation_records_ != nullptr);
Elliott Hughes545a0642011-11-08 19:10:03 -08004857 }
Mathieu Chartier9ef78b52014-09-25 17:03:12 -07004858 Runtime::Current()->GetInstrumentation()->InstrumentQuickAllocEntryPoints();
Elliott Hughes545a0642011-11-08 19:10:03 -08004859 } else {
Sebastien Hertzb98063a2014-03-26 10:57:20 +01004860 {
Brian Carlstrom306db812014-09-05 13:01:41 -07004861 ScopedObjectAccess soa(self); // For type_cache_.Clear();
4862 MutexLock mu(self, *Locks::alloc_tracker_lock_);
4863 if (recent_allocation_records_ == nullptr) {
4864 return; // Already disabled, bail.
4865 }
Mathieu Chartier4345c462014-06-27 10:20:14 -07004866 LOG(INFO) << "Disabling alloc tracker";
Sebastien Hertzb98063a2014-03-26 10:57:20 +01004867 delete[] recent_allocation_records_;
Ian Rogersc0542af2014-09-03 16:16:56 -07004868 recent_allocation_records_ = nullptr;
Brian Carlstrom306db812014-09-05 13:01:41 -07004869 alloc_record_head_ = 0;
4870 alloc_record_count_ = 0;
Mathieu Chartier4345c462014-06-27 10:20:14 -07004871 type_cache_.Clear();
Sebastien Hertzb98063a2014-03-26 10:57:20 +01004872 }
Brian Carlstrom306db812014-09-05 13:01:41 -07004873 // If an allocation comes in before we uninstrument, we will safely drop it on the floor.
Mathieu Chartier9ef78b52014-09-25 17:03:12 -07004874 Runtime::Current()->GetInstrumentation()->UninstrumentQuickAllocEntryPoints();
Elliott Hughes545a0642011-11-08 19:10:03 -08004875 }
4876}
4877
Ian Rogers0399dde2012-06-06 17:09:28 -07004878struct AllocRecordStackVisitor : public StackVisitor {
Andreas Gampe277ccbd2014-11-03 21:36:10 -08004879 AllocRecordStackVisitor(Thread* thread, AllocRecord* record_in)
Ian Rogersb726dcb2012-09-05 08:57:23 -07004880 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_)
Nicolas Geoffray8e5bd182015-05-06 11:34:34 +01004881 : StackVisitor(thread, nullptr, StackVisitor::StackWalkKind::kIncludeInlinedFrames),
4882 record(record_in),
4883 depth(0) {}
Elliott Hughes545a0642011-11-08 19:10:03 -08004884
Ian Rogers00f7d0e2012-07-19 15:28:27 -07004885 // TODO: Enable annotalysis. We know lock is held in constructor, but abstraction confuses
4886 // annotalysis.
4887 bool VisitFrame() NO_THREAD_SAFETY_ANALYSIS {
Elliott Hughes545a0642011-11-08 19:10:03 -08004888 if (depth >= kMaxAllocRecordStackDepth) {
Elliott Hughes530fa002012-03-12 11:44:49 -07004889 return false;
Elliott Hughes545a0642011-11-08 19:10:03 -08004890 }
Mathieu Chartier3d21bdf2015-04-22 13:56:20 -07004891 ArtMethod* m = GetMethod();
Ian Rogers0399dde2012-06-06 17:09:28 -07004892 if (!m->IsRuntimeMethod()) {
Hiroshi Yamauchib5a9e3d2014-06-09 12:11:20 -07004893 record->StackElement(depth)->SetMethod(m);
4894 record->StackElement(depth)->SetDexPc(GetDexPc());
Elliott Hughes530fa002012-03-12 11:44:49 -07004895 ++depth;
Elliott Hughes545a0642011-11-08 19:10:03 -08004896 }
Elliott Hughes530fa002012-03-12 11:44:49 -07004897 return true;
Elliott Hughes545a0642011-11-08 19:10:03 -08004898 }
4899
4900 ~AllocRecordStackVisitor() {
4901 // Clear out any unused stack trace elements.
4902 for (; depth < kMaxAllocRecordStackDepth; ++depth) {
Hiroshi Yamauchib5a9e3d2014-06-09 12:11:20 -07004903 record->StackElement(depth)->SetMethod(nullptr);
4904 record->StackElement(depth)->SetDexPc(0);
Elliott Hughes545a0642011-11-08 19:10:03 -08004905 }
4906 }
4907
4908 AllocRecord* record;
4909 size_t depth;
4910};
4911
Ian Rogers844506b2014-09-12 19:59:33 -07004912void Dbg::RecordAllocation(Thread* self, mirror::Class* type, size_t byte_count) {
Brian Carlstrom306db812014-09-05 13:01:41 -07004913 MutexLock mu(self, *Locks::alloc_tracker_lock_);
Ian Rogersc0542af2014-09-03 16:16:56 -07004914 if (recent_allocation_records_ == nullptr) {
Brian Carlstrom306db812014-09-05 13:01:41 -07004915 // In the process of shutting down recording, bail.
Elliott Hughes545a0642011-11-08 19:10:03 -08004916 return;
4917 }
4918
4919 // Advance and clip.
Ian Rogers719d1a32014-03-06 12:13:39 -08004920 if (++alloc_record_head_ == alloc_record_max_) {
4921 alloc_record_head_ = 0;
Elliott Hughes545a0642011-11-08 19:10:03 -08004922 }
4923
4924 // Fill in the basics.
Ian Rogers719d1a32014-03-06 12:13:39 -08004925 AllocRecord* record = &recent_allocation_records_[alloc_record_head_];
Hiroshi Yamauchib5a9e3d2014-06-09 12:11:20 -07004926 record->SetType(type);
4927 record->SetByteCount(byte_count);
4928 record->SetThinLockId(self->GetThreadId());
Elliott Hughes545a0642011-11-08 19:10:03 -08004929
4930 // Fill in the stack trace.
Ian Rogers7a22fa62013-01-23 12:16:16 -08004931 AllocRecordStackVisitor visitor(self, record);
Ian Rogers0399dde2012-06-06 17:09:28 -07004932 visitor.WalkStack();
Elliott Hughes545a0642011-11-08 19:10:03 -08004933
Ian Rogers719d1a32014-03-06 12:13:39 -08004934 if (alloc_record_count_ < alloc_record_max_) {
4935 ++alloc_record_count_;
Elliott Hughes545a0642011-11-08 19:10:03 -08004936 }
4937}
4938
Elliott Hughesa8f93cb2012-06-08 17:08:48 -07004939// Returns the index of the head element.
4940//
Brian Carlstrom306db812014-09-05 13:01:41 -07004941// We point at the most-recently-written record, so if alloc_record_count_ is 1
Elliott Hughesa8f93cb2012-06-08 17:08:48 -07004942// we want to use the current element. Take "head+1" and subtract count
4943// from it.
4944//
4945// We need to handle underflow in our circular buffer, so we add
Brian Carlstrom306db812014-09-05 13:01:41 -07004946// alloc_record_max_ and then mask it back down.
Ian Rogers719d1a32014-03-06 12:13:39 -08004947size_t Dbg::HeadIndex() {
4948 return (Dbg::alloc_record_head_ + 1 + Dbg::alloc_record_max_ - Dbg::alloc_record_count_) &
4949 (Dbg::alloc_record_max_ - 1);
Elliott Hughes545a0642011-11-08 19:10:03 -08004950}
4951
4952void Dbg::DumpRecentAllocations() {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07004953 ScopedObjectAccess soa(Thread::Current());
Brian Carlstrom306db812014-09-05 13:01:41 -07004954 MutexLock mu(soa.Self(), *Locks::alloc_tracker_lock_);
Ian Rogersc0542af2014-09-03 16:16:56 -07004955 if (recent_allocation_records_ == nullptr) {
Elliott Hughes545a0642011-11-08 19:10:03 -08004956 LOG(INFO) << "Not recording tracked allocations";
4957 return;
4958 }
4959
4960 // "i" is the head of the list. We want to start at the end of the
4961 // list and move forward to the tail.
Elliott Hughesa8f93cb2012-06-08 17:08:48 -07004962 size_t i = HeadIndex();
Brian Carlstrom306db812014-09-05 13:01:41 -07004963 const uint16_t capped_count = CappedAllocRecordCount(Dbg::alloc_record_count_);
4964 uint16_t count = capped_count;
Elliott Hughes545a0642011-11-08 19:10:03 -08004965
Ian Rogers719d1a32014-03-06 12:13:39 -08004966 LOG(INFO) << "Tracked allocations, (head=" << alloc_record_head_ << " count=" << count << ")";
Elliott Hughes545a0642011-11-08 19:10:03 -08004967 while (count--) {
4968 AllocRecord* record = &recent_allocation_records_[i];
4969
Hiroshi Yamauchib5a9e3d2014-06-09 12:11:20 -07004970 LOG(INFO) << StringPrintf(" Thread %-2d %6zd bytes ", record->ThinLockId(), record->ByteCount())
4971 << PrettyClass(record->Type());
Elliott Hughes545a0642011-11-08 19:10:03 -08004972
4973 for (size_t stack_frame = 0; stack_frame < kMaxAllocRecordStackDepth; ++stack_frame) {
Hiroshi Yamauchib5a9e3d2014-06-09 12:11:20 -07004974 AllocRecordStackTraceElement* stack_element = record->StackElement(stack_frame);
Mathieu Chartier3d21bdf2015-04-22 13:56:20 -07004975 ArtMethod* m = stack_element->Method();
Ian Rogersc0542af2014-09-03 16:16:56 -07004976 if (m == nullptr) {
Elliott Hughes545a0642011-11-08 19:10:03 -08004977 break;
4978 }
Hiroshi Yamauchib5a9e3d2014-06-09 12:11:20 -07004979 LOG(INFO) << " " << PrettyMethod(m) << " line " << stack_element->LineNumber();
Elliott Hughes545a0642011-11-08 19:10:03 -08004980 }
4981
4982 // pause periodically to help logcat catch up
4983 if ((count % 5) == 0) {
4984 usleep(40000);
4985 }
4986
Ian Rogers719d1a32014-03-06 12:13:39 -08004987 i = (i + 1) & (alloc_record_max_ - 1);
Elliott Hughes545a0642011-11-08 19:10:03 -08004988 }
4989}
4990
4991class StringTable {
4992 public:
4993 StringTable() {
4994 }
4995
Mathieu Chartier4345c462014-06-27 10:20:14 -07004996 void Add(const std::string& str) {
4997 table_.insert(str);
4998 }
4999
5000 void Add(const char* str) {
5001 table_.insert(str);
Elliott Hughes545a0642011-11-08 19:10:03 -08005002 }
5003
Elliott Hughesa8f93cb2012-06-08 17:08:48 -07005004 size_t IndexOf(const char* s) const {
Mathieu Chartier02e25112013-08-14 16:14:24 -07005005 auto it = table_.find(s);
Elliott Hughesa8f93cb2012-06-08 17:08:48 -07005006 if (it == table_.end()) {
5007 LOG(FATAL) << "IndexOf(\"" << s << "\") failed";
5008 }
5009 return std::distance(table_.begin(), it);
Elliott Hughes545a0642011-11-08 19:10:03 -08005010 }
5011
Elliott Hughesa8f93cb2012-06-08 17:08:48 -07005012 size_t Size() const {
Elliott Hughes545a0642011-11-08 19:10:03 -08005013 return table_.size();
5014 }
5015
Elliott Hughesa8f93cb2012-06-08 17:08:48 -07005016 void WriteTo(std::vector<uint8_t>& bytes) const {
Mathieu Chartier02e25112013-08-14 16:14:24 -07005017 for (const std::string& str : table_) {
5018 const char* s = str.c_str();
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08005019 size_t s_len = CountModifiedUtf8Chars(s);
Christopher Ferris8a354052015-04-24 17:23:53 -07005020 std::unique_ptr<uint16_t[]> s_utf16(new uint16_t[s_len]);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08005021 ConvertModifiedUtf8ToUtf16(s_utf16.get(), s);
5022 JDWP::AppendUtf16BE(bytes, s_utf16.get(), s_len);
Elliott Hughes545a0642011-11-08 19:10:03 -08005023 }
5024 }
5025
5026 private:
Elliott Hughesa8f93cb2012-06-08 17:08:48 -07005027 std::set<std::string> table_;
Elliott Hughes545a0642011-11-08 19:10:03 -08005028 DISALLOW_COPY_AND_ASSIGN(StringTable);
5029};
5030
Mathieu Chartier3d21bdf2015-04-22 13:56:20 -07005031static const char* GetMethodSourceFile(ArtMethod* method)
Sebastien Hertz280286a2014-04-28 09:26:50 +02005032 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07005033 DCHECK(method != nullptr);
5034 const char* source_file = method->GetDeclaringClassSourceFile();
Sebastien Hertz280286a2014-04-28 09:26:50 +02005035 return (source_file != nullptr) ? source_file : "";
5036}
5037
Elliott Hughes545a0642011-11-08 19:10:03 -08005038/*
5039 * The data we send to DDMS contains everything we have recorded.
5040 *
5041 * Message header (all values big-endian):
5042 * (1b) message header len (to allow future expansion); includes itself
5043 * (1b) entry header len
5044 * (1b) stack frame len
5045 * (2b) number of entries
5046 * (4b) offset to string table from start of message
5047 * (2b) number of class name strings
5048 * (2b) number of method name strings
5049 * (2b) number of source file name strings
5050 * For each entry:
5051 * (4b) total allocation size
Elliott Hughes221229c2013-01-08 18:17:50 -08005052 * (2b) thread id
Elliott Hughes545a0642011-11-08 19:10:03 -08005053 * (2b) allocated object's class name index
5054 * (1b) stack depth
5055 * For each stack frame:
5056 * (2b) method's class name
5057 * (2b) method name
5058 * (2b) method source file
5059 * (2b) line number, clipped to 32767; -2 if native; -1 if no source
5060 * (xb) class name strings
5061 * (xb) method name strings
5062 * (xb) source file strings
5063 *
5064 * As with other DDM traffic, strings are sent as a 4-byte length
5065 * followed by UTF-16 data.
5066 *
5067 * We send up 16-bit unsigned indexes into string tables. In theory there
Brian Carlstrom306db812014-09-05 13:01:41 -07005068 * can be (kMaxAllocRecordStackDepth * alloc_record_max_) unique strings in
Elliott Hughes545a0642011-11-08 19:10:03 -08005069 * each table, but in practice there should be far fewer.
5070 *
5071 * The chief reason for using a string table here is to keep the size of
5072 * the DDMS message to a minimum. This is partly to make the protocol
5073 * efficient, but also because we have to form the whole thing up all at
5074 * once in a memory buffer.
5075 *
5076 * We use separate string tables for class names, method names, and source
5077 * files to keep the indexes small. There will generally be no overlap
5078 * between the contents of these tables.
5079 */
5080jbyteArray Dbg::GetRecentAllocations() {
Ian Rogerscf7f1912014-10-22 22:06:39 -07005081 if ((false)) {
Elliott Hughes545a0642011-11-08 19:10:03 -08005082 DumpRecentAllocations();
5083 }
5084
Ian Rogers50b35e22012-10-04 10:09:15 -07005085 Thread* self = Thread::Current();
Elliott Hughes545a0642011-11-08 19:10:03 -08005086 std::vector<uint8_t> bytes;
Mathieu Chartier46e811b2013-07-10 17:09:14 -07005087 {
Brian Carlstrom306db812014-09-05 13:01:41 -07005088 MutexLock mu(self, *Locks::alloc_tracker_lock_);
Mathieu Chartier46e811b2013-07-10 17:09:14 -07005089 //
5090 // Part 1: generate string tables.
5091 //
5092 StringTable class_names;
5093 StringTable method_names;
5094 StringTable filenames;
Elliott Hughes545a0642011-11-08 19:10:03 -08005095
Brian Carlstrom306db812014-09-05 13:01:41 -07005096 const uint16_t capped_count = CappedAllocRecordCount(Dbg::alloc_record_count_);
5097 uint16_t count = capped_count;
5098 size_t idx = HeadIndex();
Mathieu Chartier46e811b2013-07-10 17:09:14 -07005099 while (count--) {
5100 AllocRecord* record = &recent_allocation_records_[idx];
Ian Rogers1ff3c982014-08-12 02:30:58 -07005101 std::string temp;
5102 class_names.Add(record->Type()->GetDescriptor(&temp));
Mathieu Chartier46e811b2013-07-10 17:09:14 -07005103 for (size_t i = 0; i < kMaxAllocRecordStackDepth; i++) {
Mathieu Chartier3d21bdf2015-04-22 13:56:20 -07005104 ArtMethod* m = record->StackElement(i)->Method();
Ian Rogersc0542af2014-09-03 16:16:56 -07005105 if (m != nullptr) {
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07005106 class_names.Add(m->GetDeclaringClassDescriptor());
5107 method_names.Add(m->GetName());
5108 filenames.Add(GetMethodSourceFile(m));
Mathieu Chartier46e811b2013-07-10 17:09:14 -07005109 }
5110 }
Elliott Hughes545a0642011-11-08 19:10:03 -08005111
Ian Rogers719d1a32014-03-06 12:13:39 -08005112 idx = (idx + 1) & (alloc_record_max_ - 1);
Elliott Hughes545a0642011-11-08 19:10:03 -08005113 }
5114
Brian Carlstrom306db812014-09-05 13:01:41 -07005115 LOG(INFO) << "allocation records: " << capped_count;
Mathieu Chartier46e811b2013-07-10 17:09:14 -07005116
5117 //
5118 // Part 2: Generate the output and store it in the buffer.
5119 //
5120
5121 // (1b) message header len (to allow future expansion); includes itself
5122 // (1b) entry header len
5123 // (1b) stack frame len
5124 const int kMessageHeaderLen = 15;
5125 const int kEntryHeaderLen = 9;
5126 const int kStackFrameLen = 8;
5127 JDWP::Append1BE(bytes, kMessageHeaderLen);
5128 JDWP::Append1BE(bytes, kEntryHeaderLen);
5129 JDWP::Append1BE(bytes, kStackFrameLen);
5130
5131 // (2b) number of entries
5132 // (4b) offset to string table from start of message
5133 // (2b) number of class name strings
5134 // (2b) number of method name strings
5135 // (2b) number of source file name strings
Brian Carlstrom306db812014-09-05 13:01:41 -07005136 JDWP::Append2BE(bytes, capped_count);
Mathieu Chartier46e811b2013-07-10 17:09:14 -07005137 size_t string_table_offset = bytes.size();
Brian Carlstrom7934ac22013-07-26 10:54:15 -07005138 JDWP::Append4BE(bytes, 0); // We'll patch this later...
Mathieu Chartier46e811b2013-07-10 17:09:14 -07005139 JDWP::Append2BE(bytes, class_names.Size());
5140 JDWP::Append2BE(bytes, method_names.Size());
5141 JDWP::Append2BE(bytes, filenames.Size());
5142
Mathieu Chartier46e811b2013-07-10 17:09:14 -07005143 idx = HeadIndex();
Ian Rogers1ff3c982014-08-12 02:30:58 -07005144 std::string temp;
Brian Carlstrom306db812014-09-05 13:01:41 -07005145 for (count = capped_count; count != 0; --count) {
Mathieu Chartier46e811b2013-07-10 17:09:14 -07005146 // For each entry:
5147 // (4b) total allocation size
5148 // (2b) thread id
5149 // (2b) allocated object's class name index
5150 // (1b) stack depth
5151 AllocRecord* record = &recent_allocation_records_[idx];
5152 size_t stack_depth = record->GetDepth();
Mathieu Chartierf8322842014-05-16 10:59:25 -07005153 size_t allocated_object_class_name_index =
Ian Rogers1ff3c982014-08-12 02:30:58 -07005154 class_names.IndexOf(record->Type()->GetDescriptor(&temp));
Hiroshi Yamauchib5a9e3d2014-06-09 12:11:20 -07005155 JDWP::Append4BE(bytes, record->ByteCount());
5156 JDWP::Append2BE(bytes, record->ThinLockId());
Mathieu Chartier46e811b2013-07-10 17:09:14 -07005157 JDWP::Append2BE(bytes, allocated_object_class_name_index);
5158 JDWP::Append1BE(bytes, stack_depth);
5159
Mathieu Chartier46e811b2013-07-10 17:09:14 -07005160 for (size_t stack_frame = 0; stack_frame < stack_depth; ++stack_frame) {
5161 // For each stack frame:
5162 // (2b) method's class name
5163 // (2b) method name
5164 // (2b) method source file
5165 // (2b) line number, clipped to 32767; -2 if native; -1 if no source
Mathieu Chartier3d21bdf2015-04-22 13:56:20 -07005166 ArtMethod* m = record->StackElement(stack_frame)->Method();
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07005167 size_t class_name_index = class_names.IndexOf(m->GetDeclaringClassDescriptor());
5168 size_t method_name_index = method_names.IndexOf(m->GetName());
5169 size_t file_name_index = filenames.IndexOf(GetMethodSourceFile(m));
Mathieu Chartier46e811b2013-07-10 17:09:14 -07005170 JDWP::Append2BE(bytes, class_name_index);
5171 JDWP::Append2BE(bytes, method_name_index);
5172 JDWP::Append2BE(bytes, file_name_index);
Hiroshi Yamauchib5a9e3d2014-06-09 12:11:20 -07005173 JDWP::Append2BE(bytes, record->StackElement(stack_frame)->LineNumber());
Mathieu Chartier46e811b2013-07-10 17:09:14 -07005174 }
Ian Rogers719d1a32014-03-06 12:13:39 -08005175 idx = (idx + 1) & (alloc_record_max_ - 1);
Mathieu Chartier46e811b2013-07-10 17:09:14 -07005176 }
5177
5178 // (xb) class name strings
5179 // (xb) method name strings
5180 // (xb) source file strings
5181 JDWP::Set4BE(&bytes[string_table_offset], bytes.size());
5182 class_names.WriteTo(bytes);
5183 method_names.WriteTo(bytes);
5184 filenames.WriteTo(bytes);
Elliott Hughes545a0642011-11-08 19:10:03 -08005185 }
Ian Rogers50b35e22012-10-04 10:09:15 -07005186 JNIEnv* env = self->GetJniEnv();
Elliott Hughes545a0642011-11-08 19:10:03 -08005187 jbyteArray result = env->NewByteArray(bytes.size());
Ian Rogersc0542af2014-09-03 16:16:56 -07005188 if (result != nullptr) {
Elliott Hughes545a0642011-11-08 19:10:03 -08005189 env->SetByteArrayRegion(result, 0, bytes.size(), reinterpret_cast<const jbyte*>(&bytes[0]));
5190 }
5191 return result;
5192}
5193
Mathieu Chartier3d21bdf2015-04-22 13:56:20 -07005194ArtMethod* DeoptimizationRequest::Method() const {
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07005195 ScopedObjectAccessUnchecked soa(Thread::Current());
5196 return soa.DecodeMethod(method_);
5197}
5198
Mathieu Chartier3d21bdf2015-04-22 13:56:20 -07005199void DeoptimizationRequest::SetMethod(ArtMethod* m) {
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07005200 ScopedObjectAccessUnchecked soa(Thread::Current());
5201 method_ = soa.EncodeMethod(m);
5202}
5203
Elliott Hughes872d4ec2011-10-21 17:07:15 -07005204} // namespace art