blob: 80fd18e86414aebf04faf4d397ab4843927d8834 [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"
Elliott Hughes545a0642011-11-08 19:10:03 -080025#include "class_linker.h"
Ian Rogers2dd0e2c2013-01-24 12:42:14 -080026#include "class_linker-inl.h"
Ian Rogers4f6ad8a2013-03-18 15:27:28 -070027#include "dex_file-inl.h"
Ian Rogers776ac1f2012-04-13 23:36:36 -070028#include "dex_instruction.h"
Ian Rogers1d54e732013-05-02 21:10:01 -070029#include "gc/accounting/card_table-inl.h"
30#include "gc/space/large_object_space.h"
31#include "gc/space/space-inl.h"
Mathieu Chartiereb8167a2014-05-07 15:43:14 -070032#include "handle_scope.h"
Elliott Hughes64f574f2013-02-20 14:57:12 -080033#include "jdwp/object_registry.h"
Brian Carlstromea46f952013-07-30 01:26:50 -070034#include "mirror/art_method-inl.h"
Ian Rogers2dd0e2c2013-01-24 12:42:14 -080035#include "mirror/class.h"
36#include "mirror/class-inl.h"
37#include "mirror/class_loader.h"
Ian Rogers2dd0e2c2013-01-24 12:42:14 -080038#include "mirror/object-inl.h"
39#include "mirror/object_array-inl.h"
Ian Rogersb0fa5dc2014-04-28 16:47:08 -070040#include "mirror/string-inl.h"
Ian Rogers2dd0e2c2013-01-24 12:42:14 -080041#include "mirror/throwable.h"
Sebastien Hertza76a6d42014-03-20 16:40:17 +010042#include "quick/inline_method_analyser.h"
Ian Rogers53b8b092014-03-13 23:45:53 -070043#include "reflection.h"
Elliott Hughesa0e18062012-04-13 15:59:59 -070044#include "safe_map.h"
Elliott Hughes64f574f2013-02-20 14:57:12 -080045#include "scoped_thread_state_change.h"
Elliott Hughes6a5bd492011-10-28 14:33:57 -070046#include "ScopedLocalRef.h"
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -070047#include "ScopedPrimitiveArray.h"
Mathieu Chartiereb8167a2014-05-07 15:43:14 -070048#include "handle_scope-inl.h"
Elliott Hughes475fc232011-10-25 15:00:35 -070049#include "thread_list.h"
Ian Rogers2dd0e2c2013-01-24 12:42:14 -080050#include "utf.h"
Sebastien Hertza76a6d42014-03-20 16:40:17 +010051#include "verifier/method_verifier-inl.h"
Elliott Hugheseac76672012-05-24 21:56:51 -070052#include "well_known_classes.h"
Elliott Hughes475fc232011-10-25 15:00:35 -070053
Brian Carlstrom3d92d522013-07-12 09:03:08 -070054#ifdef HAVE_ANDROID_OS
55#include "cutils/properties.h"
56#endif
57
Elliott Hughes872d4ec2011-10-21 17:07:15 -070058namespace art {
59
Sebastien Hertz0462c4c2015-04-01 16:34:17 +020060// The key identifying the debugger to update instrumentation.
61static constexpr const char* kDbgInstrumentationKey = "Debugger";
62
Brian Carlstrom7934ac22013-07-26 10:54:15 -070063static const size_t kMaxAllocRecordStackDepth = 16; // Max 255.
Brian Carlstrom306db812014-09-05 13:01:41 -070064static const size_t kDefaultNumAllocRecords = 64*1024; // Must be a power of 2. 2BE can hold 64k-1.
65
66// Limit alloc_record_count to the 2BE value that is the limit of the current protocol.
67static uint16_t CappedAllocRecordCount(size_t alloc_record_count) {
68 if (alloc_record_count > 0xffff) {
69 return 0xffff;
70 }
71 return alloc_record_count;
72}
Elliott Hughes475fc232011-10-25 15:00:35 -070073
Hiroshi Yamauchib5a9e3d2014-06-09 12:11:20 -070074class AllocRecordStackTraceElement {
75 public:
76 AllocRecordStackTraceElement() : method_(nullptr), dex_pc_(0) {
Mathieu Chartier412c7fc2014-02-07 12:18:39 -080077 }
78
Hiroshi Yamauchib5a9e3d2014-06-09 12:11:20 -070079 int32_t LineNumber() SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
80 mirror::ArtMethod* method = Method();
81 DCHECK(method != nullptr);
82 return method->GetLineNumFromDexPC(DexPc());
Elliott Hughes545a0642011-11-08 19:10:03 -080083 }
Hiroshi Yamauchib5a9e3d2014-06-09 12:11:20 -070084
85 mirror::ArtMethod* Method() SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Mathieu Chartier4345c462014-06-27 10:20:14 -070086 ScopedObjectAccessUnchecked soa(Thread::Current());
87 return soa.DecodeMethod(method_);
Hiroshi Yamauchib5a9e3d2014-06-09 12:11:20 -070088 }
89
90 void SetMethod(mirror::ArtMethod* m) SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
91 ScopedObjectAccessUnchecked soa(Thread::Current());
Mathieu Chartier4345c462014-06-27 10:20:14 -070092 method_ = soa.EncodeMethod(m);
Hiroshi Yamauchib5a9e3d2014-06-09 12:11:20 -070093 }
94
95 uint32_t DexPc() const {
96 return dex_pc_;
97 }
98
99 void SetDexPc(uint32_t pc) {
100 dex_pc_ = pc;
101 }
102
103 private:
Mathieu Chartier4345c462014-06-27 10:20:14 -0700104 jmethodID method_;
Hiroshi Yamauchib5a9e3d2014-06-09 12:11:20 -0700105 uint32_t dex_pc_;
Elliott Hughes545a0642011-11-08 19:10:03 -0800106};
107
Mathieu Chartier4345c462014-06-27 10:20:14 -0700108jobject Dbg::TypeCache::Add(mirror::Class* t) {
109 ScopedObjectAccessUnchecked soa(Thread::Current());
Mathieu Chartier4c4d6092015-01-22 17:02:27 -0800110 JNIEnv* const env = soa.Env();
111 ScopedLocalRef<jobject> local_ref(soa.Env(), soa.AddLocalReference<jobject>(t));
112 const int32_t hash_code = soa.Decode<mirror::Class*>(local_ref.get())->IdentityHashCode();
Mathieu Chartier4345c462014-06-27 10:20:14 -0700113 auto range = objects_.equal_range(hash_code);
114 for (auto it = range.first; it != range.second; ++it) {
Mathieu Chartier4c4d6092015-01-22 17:02:27 -0800115 if (soa.Decode<mirror::Class*>(it->second) == soa.Decode<mirror::Class*>(local_ref.get())) {
Mathieu Chartier4345c462014-06-27 10:20:14 -0700116 // Found a matching weak global, return it.
117 return it->second;
118 }
119 }
Mathieu Chartier4c4d6092015-01-22 17:02:27 -0800120 const jobject weak_global = env->NewWeakGlobalRef(local_ref.get());
Mathieu Chartier4345c462014-06-27 10:20:14 -0700121 objects_.insert(std::make_pair(hash_code, weak_global));
122 return weak_global;
123}
124
125void Dbg::TypeCache::Clear() {
Brian Carlstrom306db812014-09-05 13:01:41 -0700126 JavaVMExt* vm = Runtime::Current()->GetJavaVM();
127 Thread* self = Thread::Current();
Mathieu Chartier4345c462014-06-27 10:20:14 -0700128 for (const auto& p : objects_) {
Brian Carlstrom306db812014-09-05 13:01:41 -0700129 vm->DeleteWeakGlobalRef(self, p.second);
Mathieu Chartier4345c462014-06-27 10:20:14 -0700130 }
131 objects_.clear();
132}
133
Hiroshi Yamauchib5a9e3d2014-06-09 12:11:20 -0700134class AllocRecord {
135 public:
136 AllocRecord() : type_(nullptr), byte_count_(0), thin_lock_id_(0) {}
Elliott Hughes545a0642011-11-08 19:10:03 -0800137
Hiroshi Yamauchib5a9e3d2014-06-09 12:11:20 -0700138 mirror::Class* Type() SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Mathieu Chartier4345c462014-06-27 10:20:14 -0700139 return down_cast<mirror::Class*>(Thread::Current()->DecodeJObject(type_));
Hiroshi Yamauchib5a9e3d2014-06-09 12:11:20 -0700140 }
141
Brian Carlstrom306db812014-09-05 13:01:41 -0700142 void SetType(mirror::Class* t) SHARED_LOCKS_REQUIRED(Locks::mutator_lock_,
143 Locks::alloc_tracker_lock_) {
144 type_ = Dbg::type_cache_.Add(t);
Hiroshi Yamauchib5a9e3d2014-06-09 12:11:20 -0700145 }
146
147 size_t GetDepth() SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Elliott Hughes545a0642011-11-08 19:10:03 -0800148 size_t depth = 0;
Ian Rogersc0542af2014-09-03 16:16:56 -0700149 while (depth < kMaxAllocRecordStackDepth && stack_[depth].Method() != nullptr) {
Elliott Hughes545a0642011-11-08 19:10:03 -0800150 ++depth;
151 }
152 return depth;
153 }
Mathieu Chartier412c7fc2014-02-07 12:18:39 -0800154
Hiroshi Yamauchib5a9e3d2014-06-09 12:11:20 -0700155 size_t ByteCount() const {
156 return byte_count_;
Mathieu Chartier412c7fc2014-02-07 12:18:39 -0800157 }
Hiroshi Yamauchib5a9e3d2014-06-09 12:11:20 -0700158
159 void SetByteCount(size_t count) {
160 byte_count_ = count;
161 }
162
163 uint16_t ThinLockId() const {
164 return thin_lock_id_;
165 }
166
167 void SetThinLockId(uint16_t id) {
168 thin_lock_id_ = id;
169 }
170
171 AllocRecordStackTraceElement* StackElement(size_t index) {
172 DCHECK_LT(index, kMaxAllocRecordStackDepth);
173 return &stack_[index];
174 }
175
176 private:
177 jobject type_; // This is a weak global.
178 size_t byte_count_;
179 uint16_t thin_lock_id_;
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700180 // Unused entries have null method.
181 AllocRecordStackTraceElement stack_[kMaxAllocRecordStackDepth];
Elliott Hughes545a0642011-11-08 19:10:03 -0800182};
183
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -0700184class Breakpoint {
185 public:
Sebastien Hertzf3928792014-11-17 19:00:37 +0100186 Breakpoint(mirror::ArtMethod* method, uint32_t dex_pc,
187 DeoptimizationRequest::Kind deoptimization_kind)
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -0700188 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_)
Sebastien Hertzf3928792014-11-17 19:00:37 +0100189 : method_(nullptr), dex_pc_(dex_pc), deoptimization_kind_(deoptimization_kind) {
190 CHECK(deoptimization_kind_ == DeoptimizationRequest::kNothing ||
191 deoptimization_kind_ == DeoptimizationRequest::kSelectiveDeoptimization ||
192 deoptimization_kind_ == DeoptimizationRequest::kFullDeoptimization);
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -0700193 ScopedObjectAccessUnchecked soa(Thread::Current());
194 method_ = soa.EncodeMethod(method);
195 }
196
197 Breakpoint(const Breakpoint& other) SHARED_LOCKS_REQUIRED(Locks::mutator_lock_)
198 : method_(nullptr), dex_pc_(other.dex_pc_),
Sebastien Hertzf3928792014-11-17 19:00:37 +0100199 deoptimization_kind_(other.deoptimization_kind_) {
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -0700200 ScopedObjectAccessUnchecked soa(Thread::Current());
201 method_ = soa.EncodeMethod(other.Method());
202 }
203
204 mirror::ArtMethod* Method() const SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
205 ScopedObjectAccessUnchecked soa(Thread::Current());
206 return soa.DecodeMethod(method_);
207 }
208
209 uint32_t DexPc() const {
210 return dex_pc_;
211 }
212
Sebastien Hertzf3928792014-11-17 19:00:37 +0100213 DeoptimizationRequest::Kind GetDeoptimizationKind() const {
214 return deoptimization_kind_;
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -0700215 }
216
217 private:
Sebastien Hertza76a6d42014-03-20 16:40:17 +0100218 // The location of this breakpoint.
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -0700219 jmethodID method_;
220 uint32_t dex_pc_;
Sebastien Hertza76a6d42014-03-20 16:40:17 +0100221
222 // Indicates whether breakpoint needs full deoptimization or selective deoptimization.
Sebastien Hertzf3928792014-11-17 19:00:37 +0100223 DeoptimizationRequest::Kind deoptimization_kind_;
Elliott Hughes86964332012-02-15 19:37:42 -0800224};
225
Sebastien Hertzed2be172014-08-19 15:33:43 +0200226static std::ostream& operator<<(std::ostream& os, const Breakpoint& rhs)
Ian Rogersb726dcb2012-09-05 08:57:23 -0700227 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -0700228 os << StringPrintf("Breakpoint[%s @%#x]", PrettyMethod(rhs.Method()).c_str(), rhs.DexPc());
Elliott Hughes86964332012-02-15 19:37:42 -0800229 return os;
230}
231
Sebastien Hertz3f52eaf2014-04-04 17:50:18 +0200232class DebugInstrumentationListener FINAL : public instrumentation::InstrumentationListener {
Ian Rogers62d6c772013-02-27 08:32:07 -0800233 public:
234 DebugInstrumentationListener() {}
235 virtual ~DebugInstrumentationListener() {}
236
Sebastien Hertz3f52eaf2014-04-04 17:50:18 +0200237 void MethodEntered(Thread* thread, mirror::Object* this_object, mirror::ArtMethod* method,
Sebastien Hertz9d6bf692015-04-10 12:12:33 +0200238 uint32_t dex_pc)
Sebastien Hertz3f52eaf2014-04-04 17:50:18 +0200239 OVERRIDE SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Ian Rogers62d6c772013-02-27 08:32:07 -0800240 if (method->IsNative()) {
241 // TODO: post location events is a suspension point and native method entry stubs aren't.
242 return;
243 }
Sebastien Hertz9d6bf692015-04-10 12:12:33 +0200244 if (IsListeningToDexPcMoved()) {
245 // We also listen to kDexPcMoved instrumentation event so we know the DexPcMoved method is
246 // going to be called right after us. To avoid sending JDWP events twice for this location,
247 // we report the event in DexPcMoved. However, we must remind this is method entry so we
248 // send the METHOD_ENTRY event. And we can also group it with other events for this location
249 // like BREAKPOINT or SINGLE_STEP (or even METHOD_EXIT if this is a RETURN instruction).
250 thread->SetDebugMethodEntry();
251 } else if (IsListeningToMethodExit() && IsReturn(method, dex_pc)) {
252 // We also listen to kMethodExited instrumentation event and the current instruction is a
253 // RETURN so we know the MethodExited method is going to be called right after us. To avoid
254 // sending JDWP events twice for this location, we report the event(s) in MethodExited.
255 // However, we must remind this is method entry so we send the METHOD_ENTRY event. And we can
256 // also group it with other events for this location like BREAKPOINT or SINGLE_STEP.
257 thread->SetDebugMethodEntry();
258 } else {
259 Dbg::UpdateDebugger(thread, this_object, method, 0, Dbg::kMethodEntry, nullptr);
260 }
Ian Rogers62d6c772013-02-27 08:32:07 -0800261 }
262
Sebastien Hertz3f52eaf2014-04-04 17:50:18 +0200263 void MethodExited(Thread* thread, mirror::Object* this_object, mirror::ArtMethod* method,
264 uint32_t dex_pc, const JValue& return_value)
265 OVERRIDE SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Ian Rogers62d6c772013-02-27 08:32:07 -0800266 if (method->IsNative()) {
267 // TODO: post location events is a suspension point and native method entry stubs aren't.
268 return;
269 }
Sebastien Hertz9d6bf692015-04-10 12:12:33 +0200270 uint32_t events = Dbg::kMethodExit;
271 if (thread->IsDebugMethodEntry()) {
272 // It is also the method entry.
273 DCHECK(IsReturn(method, dex_pc));
274 events |= Dbg::kMethodEntry;
275 thread->ClearDebugMethodEntry();
276 }
277 Dbg::UpdateDebugger(thread, this_object, method, dex_pc, events, &return_value);
Ian Rogers62d6c772013-02-27 08:32:07 -0800278 }
279
Sebastien Hertz9d6bf692015-04-10 12:12:33 +0200280 void MethodUnwind(Thread* thread ATTRIBUTE_UNUSED, mirror::Object* this_object ATTRIBUTE_UNUSED,
281 mirror::ArtMethod* method, uint32_t dex_pc)
Sebastien Hertz3f52eaf2014-04-04 17:50:18 +0200282 OVERRIDE SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Ian Rogers62d6c772013-02-27 08:32:07 -0800283 // We're not recorded to listen to this kind of event, so complain.
284 LOG(ERROR) << "Unexpected method unwind event in debugger " << PrettyMethod(method)
Sebastien Hertz51db44a2013-11-19 10:00:29 +0100285 << " " << dex_pc;
Ian Rogers62d6c772013-02-27 08:32:07 -0800286 }
287
Sebastien Hertz3f52eaf2014-04-04 17:50:18 +0200288 void DexPcMoved(Thread* thread, mirror::Object* this_object, mirror::ArtMethod* method,
289 uint32_t new_dex_pc)
290 OVERRIDE SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Sebastien Hertz9d6bf692015-04-10 12:12:33 +0200291 if (IsListeningToMethodExit() && IsReturn(method, new_dex_pc)) {
292 // We also listen to kMethodExited instrumentation event and the current instruction is a
293 // RETURN so we know the MethodExited method is going to be called right after us. Like in
294 // MethodEntered, we delegate event reporting to MethodExited.
295 // Besides, if this RETURN instruction is the only one in the method, we can send multiple
296 // JDWP events in the same packet: METHOD_ENTRY, METHOD_EXIT, BREAKPOINT and/or SINGLE_STEP.
297 // Therefore, we must not clear the debug method entry flag here.
298 } else {
299 uint32_t events = 0;
300 if (thread->IsDebugMethodEntry()) {
301 // It is also the method entry.
302 events = Dbg::kMethodEntry;
303 thread->ClearDebugMethodEntry();
304 }
305 Dbg::UpdateDebugger(thread, this_object, method, new_dex_pc, events, nullptr);
306 }
Ian Rogers62d6c772013-02-27 08:32:07 -0800307 }
308
Sebastien Hertz9d6bf692015-04-10 12:12:33 +0200309 void FieldRead(Thread* thread ATTRIBUTE_UNUSED, mirror::Object* this_object,
310 mirror::ArtMethod* method, uint32_t dex_pc, ArtField* field)
Sebastien Hertz3f52eaf2014-04-04 17:50:18 +0200311 OVERRIDE SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
312 Dbg::PostFieldAccessEvent(method, dex_pc, this_object, field);
Ian Rogers62d6c772013-02-27 08:32:07 -0800313 }
Sebastien Hertz3f52eaf2014-04-04 17:50:18 +0200314
Ian Rogers6a3c1fc2014-10-31 00:33:20 -0700315 void FieldWritten(Thread* thread ATTRIBUTE_UNUSED, mirror::Object* this_object,
Mathieu Chartierc7853442015-03-27 14:35:38 -0700316 mirror::ArtMethod* method, uint32_t dex_pc, ArtField* field,
Ian Rogers6a3c1fc2014-10-31 00:33:20 -0700317 const JValue& field_value)
Sebastien Hertz3f52eaf2014-04-04 17:50:18 +0200318 OVERRIDE SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
319 Dbg::PostFieldModificationEvent(method, dex_pc, this_object, field, &field_value);
320 }
321
Nicolas Geoffray14691c52015-03-05 10:40:17 +0000322 void ExceptionCaught(Thread* thread ATTRIBUTE_UNUSED, mirror::Throwable* exception_object)
Sebastien Hertz3f52eaf2014-04-04 17:50:18 +0200323 OVERRIDE SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Nicolas Geoffray14691c52015-03-05 10:40:17 +0000324 Dbg::PostException(exception_object);
Sebastien Hertz3f52eaf2014-04-04 17:50:18 +0200325 }
326
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800327 // We only care about how many backward branches were executed in the Jit.
328 void BackwardBranch(Thread* /*thread*/, mirror::ArtMethod* method, int32_t dex_pc_offset)
329 OVERRIDE SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
330 LOG(ERROR) << "Unexpected backward branch event in debugger " << PrettyMethod(method)
331 << " " << dex_pc_offset;
332 }
333
Sebastien Hertz3f52eaf2014-04-04 17:50:18 +0200334 private:
Sebastien Hertz9d6bf692015-04-10 12:12:33 +0200335 static bool IsReturn(mirror::ArtMethod* method, uint32_t dex_pc)
336 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
337 const DexFile::CodeItem* code_item = method->GetCodeItem();
338 const Instruction* instruction = Instruction::At(&code_item->insns_[dex_pc]);
339 return instruction->IsReturn();
340 }
341
342 static bool IsListeningToDexPcMoved() SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
343 return IsListeningTo(instrumentation::Instrumentation::kDexPcMoved);
344 }
345
346 static bool IsListeningToMethodExit() SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
347 return IsListeningTo(instrumentation::Instrumentation::kMethodExited);
348 }
349
350 static bool IsListeningTo(instrumentation::Instrumentation::InstrumentationEvent event)
351 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
352 return (Dbg::GetInstrumentationEvents() & event) != 0;
353 }
354
Sebastien Hertz3f52eaf2014-04-04 17:50:18 +0200355 DISALLOW_COPY_AND_ASSIGN(DebugInstrumentationListener);
Ian Rogers62d6c772013-02-27 08:32:07 -0800356} gDebugInstrumentationListener;
357
Elliott Hughes4ffd3132011-10-24 12:06:42 -0700358// JDWP is allowed unless the Zygote forbids it.
359static bool gJdwpAllowed = true;
360
Elliott Hughesc0f09332012-03-26 13:27:06 -0700361// Was there a -Xrunjdwp or -agentlib:jdwp= argument on the command line?
Elliott Hughes3bb81562011-10-21 18:52:59 -0700362static bool gJdwpConfigured = false;
363
Sebastien Hertzb3b173b2015-02-06 09:16:32 +0100364// JDWP options for debugging. Only valid if IsJdwpConfigured() is true.
365static JDWP::JdwpOptions gJdwpOptions;
366
Elliott Hughes3bb81562011-10-21 18:52:59 -0700367// Runtime JDWP state.
Ian Rogersc0542af2014-09-03 16:16:56 -0700368static JDWP::JdwpState* gJdwpState = nullptr;
Elliott Hughes3bb81562011-10-21 18:52:59 -0700369static bool gDebuggerConnected; // debugger or DDMS is connected.
Elliott Hughes3bb81562011-10-21 18:52:59 -0700370
Elliott Hughes47fce012011-10-25 18:37:19 -0700371static bool gDdmThreadNotification = false;
372
Elliott Hughes767a1472011-10-26 18:49:02 -0700373// DDMS GC-related settings.
374static Dbg::HpifWhen gDdmHpifWhen = Dbg::HPIF_WHEN_NEVER;
375static Dbg::HpsgWhen gDdmHpsgWhen = Dbg::HPSG_WHEN_NEVER;
376static Dbg::HpsgWhat gDdmHpsgWhat;
377static Dbg::HpsgWhen gDdmNhsgWhen = Dbg::HPSG_WHEN_NEVER;
378static Dbg::HpsgWhat gDdmNhsgWhat;
379
Daniel Mihalyieb076692014-08-22 17:33:31 +0200380bool Dbg::gDebuggerActive = false;
Sebastien Hertz4e5b2082015-03-24 19:03:40 +0100381bool Dbg::gDisposed = false;
Sebastien Hertz6995c602014-09-09 12:10:13 +0200382ObjectRegistry* Dbg::gRegistry = nullptr;
Elliott Hughes475fc232011-10-25 15:00:35 -0700383
Elliott Hughes545a0642011-11-08 19:10:03 -0800384// Recent allocation tracking.
Ian Rogers719d1a32014-03-06 12:13:39 -0800385AllocRecord* Dbg::recent_allocation_records_ = nullptr; // TODO: CircularBuffer<AllocRecord>
386size_t Dbg::alloc_record_max_ = 0;
387size_t Dbg::alloc_record_head_ = 0;
388size_t Dbg::alloc_record_count_ = 0;
Mathieu Chartier4345c462014-06-27 10:20:14 -0700389Dbg::TypeCache Dbg::type_cache_;
Elliott Hughes545a0642011-11-08 19:10:03 -0800390
Sebastien Hertz138dbfc2013-12-04 18:15:25 +0100391// Deoptimization support.
Sebastien Hertz4d25df32014-03-21 17:44:46 +0100392std::vector<DeoptimizationRequest> Dbg::deoptimization_requests_;
393size_t Dbg::full_deoptimization_event_count_ = 0;
Sebastien Hertz138dbfc2013-12-04 18:15:25 +0100394
Sebastien Hertz42cd43f2014-05-13 14:15:41 +0200395// Instrumentation event reference counters.
396size_t Dbg::dex_pc_change_event_ref_count_ = 0;
397size_t Dbg::method_enter_event_ref_count_ = 0;
398size_t Dbg::method_exit_event_ref_count_ = 0;
399size_t Dbg::field_read_event_ref_count_ = 0;
400size_t Dbg::field_write_event_ref_count_ = 0;
401size_t Dbg::exception_catch_event_ref_count_ = 0;
402uint32_t Dbg::instrumentation_events_ = 0;
403
Sebastien Hertz138dbfc2013-12-04 18:15:25 +0100404// Breakpoints.
jeffhao09bfc6a2012-12-11 18:11:43 -0800405static std::vector<Breakpoint> gBreakpoints GUARDED_BY(Locks::breakpoint_lock_);
Elliott Hughes86964332012-02-15 19:37:42 -0800406
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -0700407void DebugInvokeReq::VisitRoots(RootVisitor* visitor, const RootInfo& root_info) {
408 receiver.VisitRootIfNonNull(visitor, root_info); // null for static method call.
409 klass.VisitRoot(visitor, root_info);
410 method.VisitRoot(visitor, root_info);
Sebastien Hertzbb43b432014-04-14 11:59:08 +0200411}
412
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -0700413void SingleStepControl::VisitRoots(RootVisitor* visitor, const RootInfo& root_info) {
Sebastien Hertz261bc042015-04-08 09:36:07 +0200414 method_.VisitRootIfNonNull(visitor, root_info);
Mathieu Chartier3b05e9b2014-03-25 09:29:43 -0700415}
416
Sebastien Hertz597c4f02015-01-26 17:37:14 +0100417void SingleStepControl::AddDexPc(uint32_t dex_pc) {
418 dex_pcs_.insert(dex_pc);
Sebastien Hertzbb43b432014-04-14 11:59:08 +0200419}
420
Sebastien Hertz597c4f02015-01-26 17:37:14 +0100421bool SingleStepControl::ContainsDexPc(uint32_t dex_pc) const {
422 return dex_pcs_.find(dex_pc) == dex_pcs_.end();
Sebastien Hertzbb43b432014-04-14 11:59:08 +0200423}
424
Brian Carlstromea46f952013-07-30 01:26:50 -0700425static bool IsBreakpoint(const mirror::ArtMethod* m, uint32_t dex_pc)
jeffhao09bfc6a2012-12-11 18:11:43 -0800426 LOCKS_EXCLUDED(Locks::breakpoint_lock_)
Ian Rogersb726dcb2012-09-05 08:57:23 -0700427 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Sebastien Hertzed2be172014-08-19 15:33:43 +0200428 ReaderMutexLock mu(Thread::Current(), *Locks::breakpoint_lock_);
Sebastien Hertz138dbfc2013-12-04 18:15:25 +0100429 for (size_t i = 0, e = gBreakpoints.size(); i < e; ++i) {
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -0700430 if (gBreakpoints[i].DexPc() == dex_pc && gBreakpoints[i].Method() == m) {
Elliott Hughes86964332012-02-15 19:37:42 -0800431 VLOG(jdwp) << "Hit breakpoint #" << i << ": " << gBreakpoints[i];
432 return true;
433 }
434 }
435 return false;
436}
437
Sebastien Hertz52d131d2014-03-13 16:17:40 +0100438static bool IsSuspendedForDebugger(ScopedObjectAccessUnchecked& soa, Thread* thread)
439 LOCKS_EXCLUDED(Locks::thread_suspend_count_lock_) {
Elliott Hughes9e0c1752013-01-09 14:02:58 -0800440 MutexLock mu(soa.Self(), *Locks::thread_suspend_count_lock_);
441 // A thread may be suspended for GC; in this code, we really want to know whether
442 // there's a debugger suspension active.
443 return thread->IsSuspended() && thread->GetDebugSuspendCount() > 0;
444}
445
Ian Rogersc0542af2014-09-03 16:16:56 -0700446static mirror::Array* DecodeNonNullArray(JDWP::RefTypeId id, JDWP::JdwpError* error)
Ian Rogersb726dcb2012-09-05 08:57:23 -0700447 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Sebastien Hertz6995c602014-09-09 12:10:13 +0200448 mirror::Object* o = Dbg::GetObjectRegistry()->Get<mirror::Object*>(id, error);
Ian Rogersc0542af2014-09-03 16:16:56 -0700449 if (o == nullptr) {
450 *error = JDWP::ERR_INVALID_OBJECT;
451 return nullptr;
Elliott Hughes436e3722012-02-17 20:01:47 -0800452 }
453 if (!o->IsArrayInstance()) {
Ian Rogersc0542af2014-09-03 16:16:56 -0700454 *error = JDWP::ERR_INVALID_ARRAY;
455 return nullptr;
Elliott Hughes436e3722012-02-17 20:01:47 -0800456 }
Ian Rogersc0542af2014-09-03 16:16:56 -0700457 *error = JDWP::ERR_NONE;
Elliott Hughes436e3722012-02-17 20:01:47 -0800458 return o->AsArray();
459}
460
Ian Rogersc0542af2014-09-03 16:16:56 -0700461static mirror::Class* DecodeClass(JDWP::RefTypeId id, JDWP::JdwpError* error)
Ian Rogersb726dcb2012-09-05 08:57:23 -0700462 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Sebastien Hertz6995c602014-09-09 12:10:13 +0200463 mirror::Object* o = Dbg::GetObjectRegistry()->Get<mirror::Object*>(id, error);
Ian Rogersc0542af2014-09-03 16:16:56 -0700464 if (o == nullptr) {
465 *error = JDWP::ERR_INVALID_OBJECT;
466 return nullptr;
Elliott Hughes436e3722012-02-17 20:01:47 -0800467 }
468 if (!o->IsClass()) {
Ian Rogersc0542af2014-09-03 16:16:56 -0700469 *error = JDWP::ERR_INVALID_CLASS;
470 return nullptr;
Elliott Hughes436e3722012-02-17 20:01:47 -0800471 }
Ian Rogersc0542af2014-09-03 16:16:56 -0700472 *error = JDWP::ERR_NONE;
Elliott Hughes436e3722012-02-17 20:01:47 -0800473 return o->AsClass();
474}
475
Ian Rogersc0542af2014-09-03 16:16:56 -0700476static Thread* DecodeThread(ScopedObjectAccessUnchecked& soa, JDWP::ObjectId thread_id,
477 JDWP::JdwpError* error)
Sebastien Hertz69206392015-04-07 15:54:25 +0200478 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_)
479 LOCKS_EXCLUDED(Locks::thread_list_lock_, Locks::thread_suspend_count_lock_) {
Sebastien Hertz6995c602014-09-09 12:10:13 +0200480 mirror::Object* thread_peer = Dbg::GetObjectRegistry()->Get<mirror::Object*>(thread_id, error);
Ian Rogersc0542af2014-09-03 16:16:56 -0700481 if (thread_peer == nullptr) {
Elliott Hughes221229c2013-01-08 18:17:50 -0800482 // This isn't even an object.
Ian Rogersc0542af2014-09-03 16:16:56 -0700483 *error = JDWP::ERR_INVALID_OBJECT;
484 return nullptr;
Elliott Hughes436e3722012-02-17 20:01:47 -0800485 }
Elliott Hughes221229c2013-01-08 18:17:50 -0800486
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800487 mirror::Class* java_lang_Thread = soa.Decode<mirror::Class*>(WellKnownClasses::java_lang_Thread);
Elliott Hughes221229c2013-01-08 18:17:50 -0800488 if (!java_lang_Thread->IsAssignableFrom(thread_peer->GetClass())) {
489 // This isn't a thread.
Ian Rogersc0542af2014-09-03 16:16:56 -0700490 *error = JDWP::ERR_INVALID_THREAD;
491 return nullptr;
Elliott Hughes221229c2013-01-08 18:17:50 -0800492 }
493
Sebastien Hertz69206392015-04-07 15:54:25 +0200494 MutexLock mu(soa.Self(), *Locks::thread_list_lock_);
Ian Rogersc0542af2014-09-03 16:16:56 -0700495 Thread* thread = Thread::FromManagedThread(soa, thread_peer);
496 // If thread is null then this a java.lang.Thread without a Thread*. Must be a un-started or a
497 // zombie.
498 *error = (thread == nullptr) ? JDWP::ERR_THREAD_NOT_ALIVE : JDWP::ERR_NONE;
499 return thread;
Elliott Hughes436e3722012-02-17 20:01:47 -0800500}
501
Elliott Hughes24437992011-11-30 14:49:33 -0800502static JDWP::JdwpTag BasicTagFromDescriptor(const char* descriptor) {
503 // JDWP deliberately uses the descriptor characters' ASCII values for its enum.
504 // Note that by "basic" we mean that we don't get more specific than JT_OBJECT.
505 return static_cast<JDWP::JdwpTag>(descriptor[0]);
506}
507
Ian Rogers1ff3c982014-08-12 02:30:58 -0700508static JDWP::JdwpTag BasicTagFromClass(mirror::Class* klass)
509 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
510 std::string temp;
511 const char* descriptor = klass->GetDescriptor(&temp);
512 return BasicTagFromDescriptor(descriptor);
513}
514
Ian Rogers98379392014-02-24 16:53:16 -0800515static JDWP::JdwpTag TagFromClass(const ScopedObjectAccessUnchecked& soa, mirror::Class* c)
Ian Rogersb726dcb2012-09-05 08:57:23 -0700516 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Ian Rogersc0542af2014-09-03 16:16:56 -0700517 CHECK(c != nullptr);
Elliott Hughes24437992011-11-30 14:49:33 -0800518 if (c->IsArrayClass()) {
519 return JDWP::JT_ARRAY;
520 }
Elliott Hughes24437992011-11-30 14:49:33 -0800521 if (c->IsStringClass()) {
522 return JDWP::JT_STRING;
Elliott Hughes24437992011-11-30 14:49:33 -0800523 }
Ian Rogers98379392014-02-24 16:53:16 -0800524 if (c->IsClassClass()) {
525 return JDWP::JT_CLASS_OBJECT;
526 }
527 {
528 mirror::Class* thread_class = soa.Decode<mirror::Class*>(WellKnownClasses::java_lang_Thread);
529 if (thread_class->IsAssignableFrom(c)) {
530 return JDWP::JT_THREAD;
531 }
532 }
533 {
534 mirror::Class* thread_group_class =
535 soa.Decode<mirror::Class*>(WellKnownClasses::java_lang_ThreadGroup);
536 if (thread_group_class->IsAssignableFrom(c)) {
537 return JDWP::JT_THREAD_GROUP;
538 }
539 }
540 {
541 mirror::Class* class_loader_class =
542 soa.Decode<mirror::Class*>(WellKnownClasses::java_lang_ClassLoader);
543 if (class_loader_class->IsAssignableFrom(c)) {
544 return JDWP::JT_CLASS_LOADER;
545 }
546 }
547 return JDWP::JT_OBJECT;
Elliott Hughes24437992011-11-30 14:49:33 -0800548}
549
550/*
551 * Objects declared to hold Object might actually hold a more specific
552 * type. The debugger may take a special interest in these (e.g. it
553 * wants to display the contents of Strings), so we want to return an
554 * appropriate tag.
555 *
556 * Null objects are tagged JT_OBJECT.
557 */
Sebastien Hertz6995c602014-09-09 12:10:13 +0200558JDWP::JdwpTag Dbg::TagFromObject(const ScopedObjectAccessUnchecked& soa, mirror::Object* o) {
Ian Rogersc0542af2014-09-03 16:16:56 -0700559 return (o == nullptr) ? JDWP::JT_OBJECT : TagFromClass(soa, o->GetClass());
Elliott Hughes24437992011-11-30 14:49:33 -0800560}
561
562static bool IsPrimitiveTag(JDWP::JdwpTag tag) {
563 switch (tag) {
564 case JDWP::JT_BOOLEAN:
565 case JDWP::JT_BYTE:
566 case JDWP::JT_CHAR:
567 case JDWP::JT_FLOAT:
568 case JDWP::JT_DOUBLE:
569 case JDWP::JT_INT:
570 case JDWP::JT_LONG:
571 case JDWP::JT_SHORT:
572 case JDWP::JT_VOID:
573 return true;
574 default:
575 return false;
576 }
577}
578
Sebastien Hertzb3b173b2015-02-06 09:16:32 +0100579void Dbg::StartJdwp() {
Elliott Hughesc0f09332012-03-26 13:27:06 -0700580 if (!gJdwpAllowed || !IsJdwpConfigured()) {
Elliott Hughes376a7a02011-10-24 18:35:55 -0700581 // No JDWP for you!
582 return;
583 }
584
Ian Rogers719d1a32014-03-06 12:13:39 -0800585 CHECK(gRegistry == nullptr);
Elliott Hughes475fc232011-10-25 15:00:35 -0700586 gRegistry = new ObjectRegistry;
587
Elliott Hughesd1cc8362011-10-24 16:58:50 -0700588 // Init JDWP if the debugger is enabled. This may connect out to a
589 // debugger, passively listen for a debugger, or block waiting for a
590 // debugger.
Sebastien Hertzb3b173b2015-02-06 09:16:32 +0100591 gJdwpState = JDWP::JdwpState::Create(&gJdwpOptions);
Ian Rogersc0542af2014-09-03 16:16:56 -0700592 if (gJdwpState == nullptr) {
Elliott Hughesf8a2df72011-12-01 12:19:54 -0800593 // We probably failed because some other process has the port already, which means that
594 // if we don't abort the user is likely to think they're talking to us when they're actually
595 // talking to that other process.
Elliott Hughes3d30d9b2011-12-07 17:35:48 -0800596 LOG(FATAL) << "Debugger thread failed to initialize";
Elliott Hughesd1cc8362011-10-24 16:58:50 -0700597 }
598
599 // If a debugger has already attached, send the "welcome" message.
600 // This may cause us to suspend all threads.
Elliott Hughes376a7a02011-10-24 18:35:55 -0700601 if (gJdwpState->IsActive()) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700602 ScopedObjectAccess soa(Thread::Current());
Sebastien Hertz7d955652014-10-22 10:57:10 +0200603 gJdwpState->PostVMStart();
Elliott Hughesd1cc8362011-10-24 16:58:50 -0700604 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700605}
606
Elliott Hughesd1cc8362011-10-24 16:58:50 -0700607void Dbg::StopJdwp() {
Sebastien Hertzc6345ef2014-08-18 19:26:39 +0200608 // Post VM_DEATH event before the JDWP connection is closed (either by the JDWP thread or the
609 // destruction of gJdwpState).
610 if (gJdwpState != nullptr && gJdwpState->IsActive()) {
611 gJdwpState->PostVMDeath();
612 }
Sebastien Hertz0376e6b2014-02-06 18:12:59 +0100613 // Prevent the JDWP thread from processing JDWP incoming packets after we close the connection.
Sebastien Hertz4e5b2082015-03-24 19:03:40 +0100614 Dispose();
Elliott Hughes376a7a02011-10-24 18:35:55 -0700615 delete gJdwpState;
Ian Rogers719d1a32014-03-06 12:13:39 -0800616 gJdwpState = nullptr;
Elliott Hughes475fc232011-10-25 15:00:35 -0700617 delete gRegistry;
Ian Rogers719d1a32014-03-06 12:13:39 -0800618 gRegistry = nullptr;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700619}
620
Elliott Hughes767a1472011-10-26 18:49:02 -0700621void Dbg::GcDidFinish() {
622 if (gDdmHpifWhen != HPIF_WHEN_NEVER) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700623 ScopedObjectAccess soa(Thread::Current());
Brian Carlstrom4d466a82014-05-08 19:05:29 -0700624 VLOG(jdwp) << "Sending heap info to DDM";
Elliott Hughes7162ad92011-10-27 14:08:42 -0700625 DdmSendHeapInfo(gDdmHpifWhen);
Elliott Hughes767a1472011-10-26 18:49:02 -0700626 }
627 if (gDdmHpsgWhen != HPSG_WHEN_NEVER) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700628 ScopedObjectAccess soa(Thread::Current());
Brian Carlstrom4d466a82014-05-08 19:05:29 -0700629 VLOG(jdwp) << "Dumping heap to DDM";
Elliott Hughes6a5bd492011-10-28 14:33:57 -0700630 DdmSendHeapSegments(false);
Elliott Hughes767a1472011-10-26 18:49:02 -0700631 }
632 if (gDdmNhsgWhen != HPSG_WHEN_NEVER) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700633 ScopedObjectAccess soa(Thread::Current());
Brian Carlstrom4d466a82014-05-08 19:05:29 -0700634 VLOG(jdwp) << "Dumping native heap to DDM";
Elliott Hughes6a5bd492011-10-28 14:33:57 -0700635 DdmSendHeapSegments(true);
Elliott Hughes767a1472011-10-26 18:49:02 -0700636 }
637}
638
Elliott Hughes4ffd3132011-10-24 12:06:42 -0700639void Dbg::SetJdwpAllowed(bool allowed) {
640 gJdwpAllowed = allowed;
641}
642
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700643DebugInvokeReq* Dbg::GetInvokeReq() {
Elliott Hughes475fc232011-10-25 15:00:35 -0700644 return Thread::Current()->GetInvokeReq();
645}
646
647Thread* Dbg::GetDebugThread() {
Ian Rogersc0542af2014-09-03 16:16:56 -0700648 return (gJdwpState != nullptr) ? gJdwpState->GetDebugThread() : nullptr;
Elliott Hughes475fc232011-10-25 15:00:35 -0700649}
650
651void Dbg::ClearWaitForEventThread() {
Sebastien Hertz2bf93f42015-01-09 18:44:05 +0100652 gJdwpState->ReleaseJdwpTokenForEvent();
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700653}
654
655void Dbg::Connected() {
Elliott Hughes3bb81562011-10-21 18:52:59 -0700656 CHECK(!gDebuggerConnected);
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -0800657 VLOG(jdwp) << "JDWP has attached";
Elliott Hughes3bb81562011-10-21 18:52:59 -0700658 gDebuggerConnected = true;
Elliott Hughes86964332012-02-15 19:37:42 -0800659 gDisposed = false;
660}
661
Sebastien Hertzf3928792014-11-17 19:00:37 +0100662bool Dbg::RequiresDeoptimization() {
663 // We don't need deoptimization if everything runs with interpreter after
664 // enabling -Xint mode.
665 return !Runtime::Current()->GetInstrumentation()->IsForcedInterpretOnly();
666}
667
Elliott Hughesa2155262011-11-16 16:26:58 -0800668void Dbg::GoActive() {
669 // Enable all debugging features, including scans for breakpoints.
670 // This is a no-op if we're already active.
671 // Only called from the JDWP handler thread.
Daniel Mihalyieb076692014-08-22 17:33:31 +0200672 if (IsDebuggerActive()) {
Elliott Hughesa2155262011-11-16 16:26:58 -0800673 return;
674 }
675
Elliott Hughesc0f09332012-03-26 13:27:06 -0700676 {
677 // TODO: dalvik only warned if there were breakpoints left over. clear in Dbg::Disconnected?
Sebastien Hertzed2be172014-08-19 15:33:43 +0200678 ReaderMutexLock mu(Thread::Current(), *Locks::breakpoint_lock_);
Elliott Hughesc0f09332012-03-26 13:27:06 -0700679 CHECK_EQ(gBreakpoints.size(), 0U);
680 }
Elliott Hughesa2155262011-11-16 16:26:58 -0800681
Sebastien Hertz138dbfc2013-12-04 18:15:25 +0100682 {
Brian Carlstrom306db812014-09-05 13:01:41 -0700683 MutexLock mu(Thread::Current(), *Locks::deoptimization_lock_);
Sebastien Hertz4d25df32014-03-21 17:44:46 +0100684 CHECK_EQ(deoptimization_requests_.size(), 0U);
685 CHECK_EQ(full_deoptimization_event_count_, 0U);
Sebastien Hertz42cd43f2014-05-13 14:15:41 +0200686 CHECK_EQ(dex_pc_change_event_ref_count_, 0U);
687 CHECK_EQ(method_enter_event_ref_count_, 0U);
688 CHECK_EQ(method_exit_event_ref_count_, 0U);
689 CHECK_EQ(field_read_event_ref_count_, 0U);
690 CHECK_EQ(field_write_event_ref_count_, 0U);
691 CHECK_EQ(exception_catch_event_ref_count_, 0U);
Sebastien Hertz138dbfc2013-12-04 18:15:25 +0100692 }
693
Ian Rogers62d6c772013-02-27 08:32:07 -0800694 Runtime* runtime = Runtime::Current();
Mathieu Chartierbf9fc582015-03-13 17:21:25 -0700695 runtime->GetThreadList()->SuspendAll(__FUNCTION__);
Ian Rogers62d6c772013-02-27 08:32:07 -0800696 Thread* self = Thread::Current();
697 ThreadState old_state = self->SetStateUnsafe(kRunnable);
698 CHECK_NE(old_state, kRunnable);
Sebastien Hertzf3928792014-11-17 19:00:37 +0100699 if (RequiresDeoptimization()) {
700 runtime->GetInstrumentation()->EnableDeoptimization();
701 }
Sebastien Hertz42cd43f2014-05-13 14:15:41 +0200702 instrumentation_events_ = 0;
Elliott Hughesa2155262011-11-16 16:26:58 -0800703 gDebuggerActive = true;
Ian Rogers62d6c772013-02-27 08:32:07 -0800704 CHECK_EQ(self->SetStateUnsafe(old_state), kRunnable);
705 runtime->GetThreadList()->ResumeAll();
706
707 LOG(INFO) << "Debugger is active";
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700708}
709
710void Dbg::Disconnected() {
Elliott Hughes234ab152011-10-26 14:02:26 -0700711 CHECK(gDebuggerConnected);
712
Elliott Hughesc0f09332012-03-26 13:27:06 -0700713 LOG(INFO) << "Debugger is no longer active";
Elliott Hughes234ab152011-10-26 14:02:26 -0700714
Ian Rogers62d6c772013-02-27 08:32:07 -0800715 // Suspend all threads and exclusively acquire the mutator lock. Set the state of the thread
716 // to kRunnable to avoid scoped object access transitions. Remove the debugger as a listener
717 // and clear the object registry.
718 Runtime* runtime = Runtime::Current();
Mathieu Chartierbf9fc582015-03-13 17:21:25 -0700719 runtime->GetThreadList()->SuspendAll(__FUNCTION__);
Ian Rogers62d6c772013-02-27 08:32:07 -0800720 Thread* self = Thread::Current();
721 ThreadState old_state = self->SetStateUnsafe(kRunnable);
Sebastien Hertzaaea7342014-02-25 15:10:04 +0100722
723 // Debugger may not be active at this point.
Daniel Mihalyieb076692014-08-22 17:33:31 +0200724 if (IsDebuggerActive()) {
Sebastien Hertzaaea7342014-02-25 15:10:04 +0100725 {
726 // Since we're going to disable deoptimization, we clear the deoptimization requests queue.
727 // This prevents us from having any pending deoptimization request when the debugger attaches
728 // to us again while no event has been requested yet.
Brian Carlstrom306db812014-09-05 13:01:41 -0700729 MutexLock mu(Thread::Current(), *Locks::deoptimization_lock_);
Sebastien Hertz4d25df32014-03-21 17:44:46 +0100730 deoptimization_requests_.clear();
731 full_deoptimization_event_count_ = 0U;
Sebastien Hertzaaea7342014-02-25 15:10:04 +0100732 }
Sebastien Hertz42cd43f2014-05-13 14:15:41 +0200733 if (instrumentation_events_ != 0) {
734 runtime->GetInstrumentation()->RemoveListener(&gDebugInstrumentationListener,
735 instrumentation_events_);
736 instrumentation_events_ = 0;
737 }
Sebastien Hertzf3928792014-11-17 19:00:37 +0100738 if (RequiresDeoptimization()) {
Sebastien Hertz0462c4c2015-04-01 16:34:17 +0200739 runtime->GetInstrumentation()->DisableDeoptimization(kDbgInstrumentationKey);
Sebastien Hertzf3928792014-11-17 19:00:37 +0100740 }
Sebastien Hertzaaea7342014-02-25 15:10:04 +0100741 gDebuggerActive = false;
Sebastien Hertz138dbfc2013-12-04 18:15:25 +0100742 }
Ian Rogers62d6c772013-02-27 08:32:07 -0800743 CHECK_EQ(self->SetStateUnsafe(old_state), kRunnable);
744 runtime->GetThreadList()->ResumeAll();
Sebastien Hertz55f65342015-01-13 22:48:34 +0100745
746 {
747 ScopedObjectAccess soa(self);
748 gRegistry->Clear();
749 }
750
751 gDebuggerConnected = false;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700752}
753
Sebastien Hertzb3b173b2015-02-06 09:16:32 +0100754void Dbg::ConfigureJdwp(const JDWP::JdwpOptions& jdwp_options) {
755 CHECK_NE(jdwp_options.transport, JDWP::kJdwpTransportUnknown);
756 gJdwpOptions = jdwp_options;
757 gJdwpConfigured = true;
758}
759
Elliott Hughesc0f09332012-03-26 13:27:06 -0700760bool Dbg::IsJdwpConfigured() {
Elliott Hughes3bb81562011-10-21 18:52:59 -0700761 return gJdwpConfigured;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700762}
763
764int64_t Dbg::LastDebuggerActivity() {
Elliott Hughesca951522011-12-05 12:01:32 -0800765 return gJdwpState->LastDebuggerActivity();
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700766}
767
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700768void Dbg::UndoDebuggerSuspensions() {
Elliott Hughes234ab152011-10-26 14:02:26 -0700769 Runtime::Current()->GetThreadList()->UndoDebuggerSuspensions();
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700770}
771
Elliott Hughes88d63092013-01-09 09:55:54 -0800772std::string Dbg::GetClassName(JDWP::RefTypeId class_id) {
Ian Rogersc0542af2014-09-03 16:16:56 -0700773 JDWP::JdwpError error;
774 mirror::Object* o = gRegistry->Get<mirror::Object*>(class_id, &error);
775 if (o == nullptr) {
776 if (error == JDWP::ERR_NONE) {
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700777 return "null";
Ian Rogersc0542af2014-09-03 16:16:56 -0700778 } else {
779 return StringPrintf("invalid object %p", reinterpret_cast<void*>(class_id));
780 }
Elliott Hughes436e3722012-02-17 20:01:47 -0800781 }
782 if (!o->IsClass()) {
Brian Carlstrom7934ac22013-07-26 10:54:15 -0700783 return StringPrintf("non-class %p", o); // This is only used for debugging output anyway.
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -0800784 }
Sebastien Hertz6995c602014-09-09 12:10:13 +0200785 return GetClassName(o->AsClass());
786}
787
788std::string Dbg::GetClassName(mirror::Class* klass) {
Sebastien Hertza9aa0ff2014-09-19 12:07:51 +0200789 if (klass == nullptr) {
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700790 return "null";
Sebastien Hertza9aa0ff2014-09-19 12:07:51 +0200791 }
Ian Rogers1ff3c982014-08-12 02:30:58 -0700792 std::string temp;
Sebastien Hertz6995c602014-09-09 12:10:13 +0200793 return DescriptorToName(klass->GetDescriptor(&temp));
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700794}
795
Ian Rogersc0542af2014-09-03 16:16:56 -0700796JDWP::JdwpError Dbg::GetClassObject(JDWP::RefTypeId id, JDWP::ObjectId* class_object_id) {
Elliott Hughes436e3722012-02-17 20:01:47 -0800797 JDWP::JdwpError status;
Ian Rogersc0542af2014-09-03 16:16:56 -0700798 mirror::Class* c = DecodeClass(id, &status);
799 if (c == nullptr) {
800 *class_object_id = 0;
Elliott Hughes436e3722012-02-17 20:01:47 -0800801 return status;
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -0800802 }
Ian Rogersc0542af2014-09-03 16:16:56 -0700803 *class_object_id = gRegistry->Add(c);
Elliott Hughes436e3722012-02-17 20:01:47 -0800804 return JDWP::ERR_NONE;
Elliott Hughes86964332012-02-15 19:37:42 -0800805}
806
Ian Rogersc0542af2014-09-03 16:16:56 -0700807JDWP::JdwpError Dbg::GetSuperclass(JDWP::RefTypeId id, JDWP::RefTypeId* superclass_id) {
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -0800808 JDWP::JdwpError status;
Ian Rogersc0542af2014-09-03 16:16:56 -0700809 mirror::Class* c = DecodeClass(id, &status);
810 if (c == nullptr) {
811 *superclass_id = 0;
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -0800812 return status;
813 }
814 if (c->IsInterface()) {
815 // http://code.google.com/p/android/issues/detail?id=20856
Ian Rogersc0542af2014-09-03 16:16:56 -0700816 *superclass_id = 0;
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -0800817 } else {
Ian Rogersc0542af2014-09-03 16:16:56 -0700818 *superclass_id = gRegistry->Add(c->GetSuperClass());
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -0800819 }
820 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700821}
822
Elliott Hughes436e3722012-02-17 20:01:47 -0800823JDWP::JdwpError Dbg::GetClassLoader(JDWP::RefTypeId id, JDWP::ExpandBuf* pReply) {
Ian Rogersc0542af2014-09-03 16:16:56 -0700824 JDWP::JdwpError error;
825 mirror::Object* o = gRegistry->Get<mirror::Object*>(id, &error);
826 if (o == nullptr) {
Elliott Hughes436e3722012-02-17 20:01:47 -0800827 return JDWP::ERR_INVALID_OBJECT;
828 }
829 expandBufAddObjectId(pReply, gRegistry->Add(o->GetClass()->GetClassLoader()));
830 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700831}
832
Elliott Hughes436e3722012-02-17 20:01:47 -0800833JDWP::JdwpError Dbg::GetModifiers(JDWP::RefTypeId id, JDWP::ExpandBuf* pReply) {
Ian Rogersc0542af2014-09-03 16:16:56 -0700834 JDWP::JdwpError error;
835 mirror::Class* c = DecodeClass(id, &error);
836 if (c == nullptr) {
837 return error;
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -0800838 }
Elliott Hughes436e3722012-02-17 20:01:47 -0800839
840 uint32_t access_flags = c->GetAccessFlags() & kAccJavaFlagsMask;
841
Yevgeny Roubande34eea2014-02-15 01:06:03 +0700842 // Set ACC_SUPER. Dex files don't contain this flag but only classes are supposed to have it set,
843 // not interfaces.
Elliott Hughes436e3722012-02-17 20:01:47 -0800844 // Class.getModifiers doesn't return it, but JDWP does, so we set it here.
Yevgeny Roubande34eea2014-02-15 01:06:03 +0700845 if ((access_flags & kAccInterface) == 0) {
846 access_flags |= kAccSuper;
847 }
Elliott Hughes436e3722012-02-17 20:01:47 -0800848
849 expandBufAdd4BE(pReply, access_flags);
850
851 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700852}
853
Ian Rogersc0542af2014-09-03 16:16:56 -0700854JDWP::JdwpError Dbg::GetMonitorInfo(JDWP::ObjectId object_id, JDWP::ExpandBuf* reply) {
855 JDWP::JdwpError error;
856 mirror::Object* o = gRegistry->Get<mirror::Object*>(object_id, &error);
857 if (o == nullptr) {
Elliott Hughesf327e072013-01-09 16:01:26 -0800858 return JDWP::ERR_INVALID_OBJECT;
859 }
860
861 // Ensure all threads are suspended while we read objects' lock words.
862 Thread* self = Thread::Current();
Sebastien Hertz54263242014-03-19 18:16:50 +0100863 CHECK_EQ(self->GetState(), kRunnable);
864 self->TransitionFromRunnableToSuspended(kSuspended);
Mathieu Chartierbf9fc582015-03-13 17:21:25 -0700865 Runtime::Current()->GetThreadList()->SuspendAll(__FUNCTION__);
Elliott Hughesf327e072013-01-09 16:01:26 -0800866
867 MonitorInfo monitor_info(o);
868
Sebastien Hertz54263242014-03-19 18:16:50 +0100869 Runtime::Current()->GetThreadList()->ResumeAll();
870 self->TransitionFromSuspendedToRunnable();
Elliott Hughesf327e072013-01-09 16:01:26 -0800871
Ian Rogersc0542af2014-09-03 16:16:56 -0700872 if (monitor_info.owner_ != nullptr) {
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700873 expandBufAddObjectId(reply, gRegistry->Add(monitor_info.owner_->GetPeer()));
Elliott Hughesf327e072013-01-09 16:01:26 -0800874 } else {
Ian Rogersc0542af2014-09-03 16:16:56 -0700875 expandBufAddObjectId(reply, gRegistry->Add(nullptr));
Elliott Hughesf327e072013-01-09 16:01:26 -0800876 }
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700877 expandBufAdd4BE(reply, monitor_info.entry_count_);
878 expandBufAdd4BE(reply, monitor_info.waiters_.size());
879 for (size_t i = 0; i < monitor_info.waiters_.size(); ++i) {
880 expandBufAddObjectId(reply, gRegistry->Add(monitor_info.waiters_[i]->GetPeer()));
Elliott Hughesf327e072013-01-09 16:01:26 -0800881 }
882 return JDWP::ERR_NONE;
883}
884
Elliott Hughes734b8c62013-01-11 15:32:45 -0800885JDWP::JdwpError Dbg::GetOwnedMonitors(JDWP::ObjectId thread_id,
Ian Rogersc0542af2014-09-03 16:16:56 -0700886 std::vector<JDWP::ObjectId>* monitors,
887 std::vector<uint32_t>* stack_depths) {
Elliott Hughes4993bbc2013-01-10 15:41:25 -0800888 struct OwnedMonitorVisitor : public StackVisitor {
Hiroshi Yamauchib5a9e3d2014-06-09 12:11:20 -0700889 OwnedMonitorVisitor(Thread* thread, Context* context,
Hiroshi Yamauchicc8c5c52014-06-13 15:08:05 -0700890 std::vector<JDWP::ObjectId>* monitor_vector,
Hiroshi Yamauchib5a9e3d2014-06-09 12:11:20 -0700891 std::vector<uint32_t>* stack_depth_vector)
Elliott Hughes4993bbc2013-01-10 15:41:25 -0800892 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_)
Nicolas Geoffray8e5bd182015-05-06 11:34:34 +0100893 : StackVisitor(thread, context, StackVisitor::StackWalkKind::kIncludeInlinedFrames),
894 current_stack_depth(0),
895 monitors(monitor_vector),
896 stack_depths(stack_depth_vector) {}
Elliott Hughes4993bbc2013-01-10 15:41:25 -0800897
898 // TODO: Enable annotalysis. We know lock is held in constructor, but abstraction confuses
899 // annotalysis.
900 bool VisitFrame() NO_THREAD_SAFETY_ANALYSIS {
901 if (!GetMethod()->IsRuntimeMethod()) {
902 Monitor::VisitLocks(this, AppendOwnedMonitors, this);
Elliott Hughes734b8c62013-01-11 15:32:45 -0800903 ++current_stack_depth;
Elliott Hughes4993bbc2013-01-10 15:41:25 -0800904 }
905 return true;
906 }
907
Hiroshi Yamauchicc8c5c52014-06-13 15:08:05 -0700908 static void AppendOwnedMonitors(mirror::Object* owned_monitor, void* arg)
909 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Ian Rogers7a22fa62013-01-23 12:16:16 -0800910 OwnedMonitorVisitor* visitor = reinterpret_cast<OwnedMonitorVisitor*>(arg);
Hiroshi Yamauchicc8c5c52014-06-13 15:08:05 -0700911 visitor->monitors->push_back(gRegistry->Add(owned_monitor));
Hiroshi Yamauchib5a9e3d2014-06-09 12:11:20 -0700912 visitor->stack_depths->push_back(visitor->current_stack_depth);
Elliott Hughes4993bbc2013-01-10 15:41:25 -0800913 }
914
Elliott Hughes734b8c62013-01-11 15:32:45 -0800915 size_t current_stack_depth;
Ian Rogersc0542af2014-09-03 16:16:56 -0700916 std::vector<JDWP::ObjectId>* const monitors;
917 std::vector<uint32_t>* const stack_depths;
Elliott Hughes4993bbc2013-01-10 15:41:25 -0800918 };
Elliott Hughes4993bbc2013-01-10 15:41:25 -0800919
Hiroshi Yamauchib5a9e3d2014-06-09 12:11:20 -0700920 ScopedObjectAccessUnchecked soa(Thread::Current());
Sebastien Hertz69206392015-04-07 15:54:25 +0200921 JDWP::JdwpError error;
922 Thread* thread = DecodeThread(soa, thread_id, &error);
923 if (thread == nullptr) {
924 return error;
925 }
926 if (!IsSuspendedForDebugger(soa, thread)) {
927 return JDWP::ERR_THREAD_NOT_SUSPENDED;
Hiroshi Yamauchib5a9e3d2014-06-09 12:11:20 -0700928 }
Hiroshi Yamauchicc8c5c52014-06-13 15:08:05 -0700929 std::unique_ptr<Context> context(Context::Create());
Ian Rogersc0542af2014-09-03 16:16:56 -0700930 OwnedMonitorVisitor visitor(thread, context.get(), monitors, stack_depths);
Hiroshi Yamauchicc8c5c52014-06-13 15:08:05 -0700931 visitor.WalkStack();
Elliott Hughes4993bbc2013-01-10 15:41:25 -0800932 return JDWP::ERR_NONE;
933}
934
Sebastien Hertz52d131d2014-03-13 16:17:40 +0100935JDWP::JdwpError Dbg::GetContendedMonitor(JDWP::ObjectId thread_id,
Ian Rogersc0542af2014-09-03 16:16:56 -0700936 JDWP::ObjectId* contended_monitor) {
Elliott Hughesf9501702013-01-11 11:22:27 -0800937 ScopedObjectAccessUnchecked soa(Thread::Current());
Ian Rogersc0542af2014-09-03 16:16:56 -0700938 *contended_monitor = 0;
Sebastien Hertz69206392015-04-07 15:54:25 +0200939 JDWP::JdwpError error;
940 Thread* thread = DecodeThread(soa, thread_id, &error);
941 if (thread == nullptr) {
942 return error;
Elliott Hughesf9501702013-01-11 11:22:27 -0800943 }
Sebastien Hertz69206392015-04-07 15:54:25 +0200944 if (!IsSuspendedForDebugger(soa, thread)) {
945 return JDWP::ERR_THREAD_NOT_SUSPENDED;
946 }
947 mirror::Object* contended_monitor_obj = Monitor::GetContendedMonitor(thread);
Hiroshi Yamauchib5a9e3d2014-06-09 12:11:20 -0700948 // Add() requires the thread_list_lock_ not held to avoid the lock
949 // level violation.
Ian Rogersc0542af2014-09-03 16:16:56 -0700950 *contended_monitor = gRegistry->Add(contended_monitor_obj);
Elliott Hughesf9501702013-01-11 11:22:27 -0800951 return JDWP::ERR_NONE;
952}
953
Elliott Hughesec0f83d2013-01-15 16:54:08 -0800954JDWP::JdwpError Dbg::GetInstanceCounts(const std::vector<JDWP::RefTypeId>& class_ids,
Ian Rogersc0542af2014-09-03 16:16:56 -0700955 std::vector<uint64_t>* counts) {
Mathieu Chartier412c7fc2014-02-07 12:18:39 -0800956 gc::Heap* heap = Runtime::Current()->GetHeap();
957 heap->CollectGarbage(false);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800958 std::vector<mirror::Class*> classes;
Ian Rogersc0542af2014-09-03 16:16:56 -0700959 counts->clear();
Elliott Hughesec0f83d2013-01-15 16:54:08 -0800960 for (size_t i = 0; i < class_ids.size(); ++i) {
Ian Rogersc0542af2014-09-03 16:16:56 -0700961 JDWP::JdwpError error;
962 mirror::Class* c = DecodeClass(class_ids[i], &error);
963 if (c == nullptr) {
964 return error;
Elliott Hughesec0f83d2013-01-15 16:54:08 -0800965 }
966 classes.push_back(c);
Ian Rogersc0542af2014-09-03 16:16:56 -0700967 counts->push_back(0);
Elliott Hughesec0f83d2013-01-15 16:54:08 -0800968 }
Ian Rogersc0542af2014-09-03 16:16:56 -0700969 heap->CountInstances(classes, false, &(*counts)[0]);
Elliott Hughesec0f83d2013-01-15 16:54:08 -0800970 return JDWP::ERR_NONE;
971}
972
Ian Rogersc0542af2014-09-03 16:16:56 -0700973JDWP::JdwpError Dbg::GetInstances(JDWP::RefTypeId class_id, int32_t max_count,
974 std::vector<JDWP::ObjectId>* instances) {
Mathieu Chartier412c7fc2014-02-07 12:18:39 -0800975 gc::Heap* heap = Runtime::Current()->GetHeap();
976 // We only want reachable instances, so do a GC.
977 heap->CollectGarbage(false);
Ian Rogersc0542af2014-09-03 16:16:56 -0700978 JDWP::JdwpError error;
979 mirror::Class* c = DecodeClass(class_id, &error);
Mathieu Chartier412c7fc2014-02-07 12:18:39 -0800980 if (c == nullptr) {
Ian Rogersc0542af2014-09-03 16:16:56 -0700981 return error;
Elliott Hughes3b78c942013-01-15 17:35:41 -0800982 }
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800983 std::vector<mirror::Object*> raw_instances;
Elliott Hughes3b78c942013-01-15 17:35:41 -0800984 Runtime::Current()->GetHeap()->GetInstances(c, max_count, raw_instances);
985 for (size_t i = 0; i < raw_instances.size(); ++i) {
Ian Rogersc0542af2014-09-03 16:16:56 -0700986 instances->push_back(gRegistry->Add(raw_instances[i]));
Elliott Hughes3b78c942013-01-15 17:35:41 -0800987 }
988 return JDWP::ERR_NONE;
989}
990
Elliott Hughes0cbaff52013-01-16 15:28:01 -0800991JDWP::JdwpError Dbg::GetReferringObjects(JDWP::ObjectId object_id, int32_t max_count,
Ian Rogersc0542af2014-09-03 16:16:56 -0700992 std::vector<JDWP::ObjectId>* referring_objects) {
Mathieu Chartier412c7fc2014-02-07 12:18:39 -0800993 gc::Heap* heap = Runtime::Current()->GetHeap();
994 heap->CollectGarbage(false);
Ian Rogersc0542af2014-09-03 16:16:56 -0700995 JDWP::JdwpError error;
996 mirror::Object* o = gRegistry->Get<mirror::Object*>(object_id, &error);
997 if (o == nullptr) {
Elliott Hughes0cbaff52013-01-16 15:28:01 -0800998 return JDWP::ERR_INVALID_OBJECT;
999 }
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001000 std::vector<mirror::Object*> raw_instances;
Mathieu Chartier412c7fc2014-02-07 12:18:39 -08001001 heap->GetReferringObjects(o, max_count, raw_instances);
Elliott Hughes0cbaff52013-01-16 15:28:01 -08001002 for (size_t i = 0; i < raw_instances.size(); ++i) {
Ian Rogersc0542af2014-09-03 16:16:56 -07001003 referring_objects->push_back(gRegistry->Add(raw_instances[i]));
Elliott Hughes0cbaff52013-01-16 15:28:01 -08001004 }
1005 return JDWP::ERR_NONE;
1006}
1007
Ian Rogersc0542af2014-09-03 16:16:56 -07001008JDWP::JdwpError Dbg::DisableCollection(JDWP::ObjectId object_id) {
1009 JDWP::JdwpError error;
1010 mirror::Object* o = gRegistry->Get<mirror::Object*>(object_id, &error);
1011 if (o == nullptr) {
Sebastien Hertze96060a2013-12-11 12:06:28 +01001012 return JDWP::ERR_INVALID_OBJECT;
1013 }
Elliott Hughes64f574f2013-02-20 14:57:12 -08001014 gRegistry->DisableCollection(object_id);
1015 return JDWP::ERR_NONE;
1016}
1017
Ian Rogersc0542af2014-09-03 16:16:56 -07001018JDWP::JdwpError Dbg::EnableCollection(JDWP::ObjectId object_id) {
1019 JDWP::JdwpError error;
1020 mirror::Object* o = gRegistry->Get<mirror::Object*>(object_id, &error);
Sebastien Hertze96060a2013-12-11 12:06:28 +01001021 // Unlike DisableCollection, JDWP specs do not state an invalid object causes an error. The RI
1022 // also ignores these cases and never return an error. However it's not obvious why this command
1023 // should behave differently from DisableCollection and IsCollected commands. So let's be more
1024 // strict and return an error if this happens.
Ian Rogersc0542af2014-09-03 16:16:56 -07001025 if (o == nullptr) {
Sebastien Hertze96060a2013-12-11 12:06:28 +01001026 return JDWP::ERR_INVALID_OBJECT;
1027 }
Elliott Hughes64f574f2013-02-20 14:57:12 -08001028 gRegistry->EnableCollection(object_id);
1029 return JDWP::ERR_NONE;
1030}
1031
Ian Rogersc0542af2014-09-03 16:16:56 -07001032JDWP::JdwpError Dbg::IsCollected(JDWP::ObjectId object_id, bool* is_collected) {
1033 *is_collected = true;
Sebastien Hertz65637eb2014-01-10 17:40:02 +01001034 if (object_id == 0) {
1035 // Null object id is invalid.
Sebastien Hertze96060a2013-12-11 12:06:28 +01001036 return JDWP::ERR_INVALID_OBJECT;
1037 }
Sebastien Hertz65637eb2014-01-10 17:40:02 +01001038 // JDWP specs state an INVALID_OBJECT error is returned if the object ID is not valid. However
1039 // the RI seems to ignore this and assume object has been collected.
Ian Rogersc0542af2014-09-03 16:16:56 -07001040 JDWP::JdwpError error;
1041 mirror::Object* o = gRegistry->Get<mirror::Object*>(object_id, &error);
1042 if (o != nullptr) {
1043 *is_collected = gRegistry->IsCollected(object_id);
Sebastien Hertz65637eb2014-01-10 17:40:02 +01001044 }
Elliott Hughes64f574f2013-02-20 14:57:12 -08001045 return JDWP::ERR_NONE;
1046}
1047
Ian Rogersc0542af2014-09-03 16:16:56 -07001048void Dbg::DisposeObject(JDWP::ObjectId object_id, uint32_t reference_count) {
Elliott Hughes64f574f2013-02-20 14:57:12 -08001049 gRegistry->DisposeObject(object_id, reference_count);
1050}
1051
Sebastien Hertz6995c602014-09-09 12:10:13 +02001052JDWP::JdwpTypeTag Dbg::GetTypeTag(mirror::Class* klass) {
Sebastien Hertz4d8fd492014-03-28 16:29:41 +01001053 DCHECK(klass != nullptr);
1054 if (klass->IsArrayClass()) {
1055 return JDWP::TT_ARRAY;
1056 } else if (klass->IsInterface()) {
1057 return JDWP::TT_INTERFACE;
1058 } else {
1059 return JDWP::TT_CLASS;
1060 }
1061}
1062
Elliott Hughes88d63092013-01-09 09:55:54 -08001063JDWP::JdwpError Dbg::GetReflectedType(JDWP::RefTypeId class_id, JDWP::ExpandBuf* pReply) {
Ian Rogersc0542af2014-09-03 16:16:56 -07001064 JDWP::JdwpError error;
1065 mirror::Class* c = DecodeClass(class_id, &error);
1066 if (c == nullptr) {
1067 return error;
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -08001068 }
Elliott Hughes436e3722012-02-17 20:01:47 -08001069
Sebastien Hertz4d8fd492014-03-28 16:29:41 +01001070 JDWP::JdwpTypeTag type_tag = GetTypeTag(c);
1071 expandBufAdd1(pReply, type_tag);
Elliott Hughes88d63092013-01-09 09:55:54 -08001072 expandBufAddRefTypeId(pReply, class_id);
Elliott Hughes436e3722012-02-17 20:01:47 -08001073 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001074}
1075
Ian Rogersc0542af2014-09-03 16:16:56 -07001076void Dbg::GetClassList(std::vector<JDWP::RefTypeId>* classes) {
Elliott Hughesa2155262011-11-16 16:26:58 -08001077 // Get the complete list of reference classes (i.e. all classes except
1078 // the primitive types).
1079 // Returns a newly-allocated buffer full of RefTypeId values.
1080 struct ClassListCreator {
Andreas Gampe277ccbd2014-11-03 21:36:10 -08001081 explicit ClassListCreator(std::vector<JDWP::RefTypeId>* classes_in) : classes(classes_in) {
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -08001082 }
1083
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001084 static bool Visit(mirror::Class* c, void* arg) {
Elliott Hughesa2155262011-11-16 16:26:58 -08001085 return reinterpret_cast<ClassListCreator*>(arg)->Visit(c);
1086 }
1087
Elliott Hughes64f574f2013-02-20 14:57:12 -08001088 // TODO: Enable annotalysis. We know lock is held in constructor, but abstraction confuses
1089 // annotalysis.
1090 bool Visit(mirror::Class* c) NO_THREAD_SAFETY_ANALYSIS {
Elliott Hughesa2155262011-11-16 16:26:58 -08001091 if (!c->IsPrimitive()) {
Ian Rogersc0542af2014-09-03 16:16:56 -07001092 classes->push_back(gRegistry->AddRefType(c));
Elliott Hughesa2155262011-11-16 16:26:58 -08001093 }
1094 return true;
1095 }
1096
Ian Rogersc0542af2014-09-03 16:16:56 -07001097 std::vector<JDWP::RefTypeId>* const classes;
Elliott Hughesa2155262011-11-16 16:26:58 -08001098 };
1099
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -08001100 ClassListCreator clc(classes);
Sebastien Hertz4537c412014-08-28 14:41:50 +02001101 Runtime::Current()->GetClassLinker()->VisitClassesWithoutClassesLock(ClassListCreator::Visit,
1102 &clc);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001103}
1104
Ian Rogers1ff3c982014-08-12 02:30:58 -07001105JDWP::JdwpError Dbg::GetClassInfo(JDWP::RefTypeId class_id, JDWP::JdwpTypeTag* pTypeTag,
1106 uint32_t* pStatus, std::string* pDescriptor) {
Ian Rogersc0542af2014-09-03 16:16:56 -07001107 JDWP::JdwpError error;
1108 mirror::Class* c = DecodeClass(class_id, &error);
1109 if (c == nullptr) {
1110 return error;
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -08001111 }
1112
Elliott Hughesa2155262011-11-16 16:26:58 -08001113 if (c->IsArrayClass()) {
1114 *pStatus = JDWP::CS_VERIFIED | JDWP::CS_PREPARED;
1115 *pTypeTag = JDWP::TT_ARRAY;
1116 } else {
1117 if (c->IsErroneous()) {
1118 *pStatus = JDWP::CS_ERROR;
1119 } else {
1120 *pStatus = JDWP::CS_VERIFIED | JDWP::CS_PREPARED | JDWP::CS_INITIALIZED;
1121 }
1122 *pTypeTag = c->IsInterface() ? JDWP::TT_INTERFACE : JDWP::TT_CLASS;
1123 }
1124
Ian Rogersc0542af2014-09-03 16:16:56 -07001125 if (pDescriptor != nullptr) {
Ian Rogers1ff3c982014-08-12 02:30:58 -07001126 std::string temp;
1127 *pDescriptor = c->GetDescriptor(&temp);
Elliott Hughesa2155262011-11-16 16:26:58 -08001128 }
Elliott Hughes436e3722012-02-17 20:01:47 -08001129 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001130}
1131
Ian Rogersc0542af2014-09-03 16:16:56 -07001132void Dbg::FindLoadedClassBySignature(const char* descriptor, std::vector<JDWP::RefTypeId>* ids) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001133 std::vector<mirror::Class*> classes;
Elliott Hughes6fa602d2011-12-02 17:54:25 -08001134 Runtime::Current()->GetClassLinker()->LookupClasses(descriptor, classes);
Ian Rogersc0542af2014-09-03 16:16:56 -07001135 ids->clear();
Elliott Hughes6fa602d2011-12-02 17:54:25 -08001136 for (size_t i = 0; i < classes.size(); ++i) {
Ian Rogersc0542af2014-09-03 16:16:56 -07001137 ids->push_back(gRegistry->Add(classes[i]));
Elliott Hughes6fa602d2011-12-02 17:54:25 -08001138 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001139}
1140
Ian Rogersc0542af2014-09-03 16:16:56 -07001141JDWP::JdwpError Dbg::GetReferenceType(JDWP::ObjectId object_id, JDWP::ExpandBuf* pReply) {
1142 JDWP::JdwpError error;
1143 mirror::Object* o = gRegistry->Get<mirror::Object*>(object_id, &error);
1144 if (o == nullptr) {
Elliott Hughes2435a572012-02-17 16:07:41 -08001145 return JDWP::ERR_INVALID_OBJECT;
Elliott Hughes499c5132011-11-17 14:55:11 -08001146 }
Elliott Hughes2435a572012-02-17 16:07:41 -08001147
Sebastien Hertz4d8fd492014-03-28 16:29:41 +01001148 JDWP::JdwpTypeTag type_tag = GetTypeTag(o->GetClass());
Elliott Hughes64f574f2013-02-20 14:57:12 -08001149 JDWP::RefTypeId type_id = gRegistry->AddRefType(o->GetClass());
Elliott Hughes2435a572012-02-17 16:07:41 -08001150
1151 expandBufAdd1(pReply, type_tag);
1152 expandBufAddRefTypeId(pReply, type_id);
1153
1154 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001155}
1156
Ian Rogersfc0e94b2013-09-23 23:51:32 -07001157JDWP::JdwpError Dbg::GetSignature(JDWP::RefTypeId class_id, std::string* signature) {
Ian Rogersc0542af2014-09-03 16:16:56 -07001158 JDWP::JdwpError error;
1159 mirror::Class* c = DecodeClass(class_id, &error);
1160 if (c == nullptr) {
1161 return error;
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -08001162 }
Ian Rogers1ff3c982014-08-12 02:30:58 -07001163 std::string temp;
1164 *signature = c->GetDescriptor(&temp);
Elliott Hughes1fe7afb2012-02-13 17:23:03 -08001165 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001166}
1167
Ian Rogersc0542af2014-09-03 16:16:56 -07001168JDWP::JdwpError Dbg::GetSourceFile(JDWP::RefTypeId class_id, std::string* result) {
1169 JDWP::JdwpError error;
1170 mirror::Class* c = DecodeClass(class_id, &error);
Sebastien Hertz4206eb52014-06-05 10:15:45 +02001171 if (c == nullptr) {
Ian Rogersc0542af2014-09-03 16:16:56 -07001172 return error;
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -08001173 }
Sebastien Hertz4206eb52014-06-05 10:15:45 +02001174 const char* source_file = c->GetSourceFile();
1175 if (source_file == nullptr) {
Sebastien Hertzb7054ba2014-03-13 11:52:31 +01001176 return JDWP::ERR_ABSENT_INFORMATION;
1177 }
Ian Rogersc0542af2014-09-03 16:16:56 -07001178 *result = source_file;
Elliott Hughes436e3722012-02-17 20:01:47 -08001179 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001180}
1181
Ian Rogersc0542af2014-09-03 16:16:56 -07001182JDWP::JdwpError Dbg::GetObjectTag(JDWP::ObjectId object_id, uint8_t* tag) {
Ian Rogers98379392014-02-24 16:53:16 -08001183 ScopedObjectAccessUnchecked soa(Thread::Current());
Ian Rogersc0542af2014-09-03 16:16:56 -07001184 JDWP::JdwpError error;
1185 mirror::Object* o = gRegistry->Get<mirror::Object*>(object_id, &error);
1186 if (error != JDWP::ERR_NONE) {
1187 *tag = JDWP::JT_VOID;
1188 return error;
Elliott Hughes546b9862012-06-20 16:06:13 -07001189 }
Ian Rogersc0542af2014-09-03 16:16:56 -07001190 *tag = TagFromObject(soa, o);
Elliott Hughes546b9862012-06-20 16:06:13 -07001191 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001192}
1193
Elliott Hughesaed4be92011-12-02 16:16:23 -08001194size_t Dbg::GetTagWidth(JDWP::JdwpTag tag) {
Elliott Hughesdbb40792011-11-18 17:05:22 -08001195 switch (tag) {
1196 case JDWP::JT_VOID:
1197 return 0;
1198 case JDWP::JT_BYTE:
1199 case JDWP::JT_BOOLEAN:
1200 return 1;
1201 case JDWP::JT_CHAR:
1202 case JDWP::JT_SHORT:
1203 return 2;
1204 case JDWP::JT_FLOAT:
1205 case JDWP::JT_INT:
1206 return 4;
1207 case JDWP::JT_ARRAY:
1208 case JDWP::JT_OBJECT:
1209 case JDWP::JT_STRING:
1210 case JDWP::JT_THREAD:
1211 case JDWP::JT_THREAD_GROUP:
1212 case JDWP::JT_CLASS_LOADER:
1213 case JDWP::JT_CLASS_OBJECT:
1214 return sizeof(JDWP::ObjectId);
1215 case JDWP::JT_DOUBLE:
1216 case JDWP::JT_LONG:
1217 return 8;
1218 default:
Elliott Hughes3d30d9b2011-12-07 17:35:48 -08001219 LOG(FATAL) << "Unknown tag " << tag;
Elliott Hughesdbb40792011-11-18 17:05:22 -08001220 return -1;
1221 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001222}
1223
Ian Rogersc0542af2014-09-03 16:16:56 -07001224JDWP::JdwpError Dbg::GetArrayLength(JDWP::ObjectId array_id, int32_t* length) {
1225 JDWP::JdwpError error;
1226 mirror::Array* a = DecodeNonNullArray(array_id, &error);
1227 if (a == nullptr) {
1228 return error;
Elliott Hughes24437992011-11-30 14:49:33 -08001229 }
Ian Rogersc0542af2014-09-03 16:16:56 -07001230 *length = a->GetLength();
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -08001231 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001232}
1233
Elliott Hughes88d63092013-01-09 09:55:54 -08001234JDWP::JdwpError Dbg::OutputArray(JDWP::ObjectId array_id, int offset, int count, JDWP::ExpandBuf* pReply) {
Ian Rogersc0542af2014-09-03 16:16:56 -07001235 JDWP::JdwpError error;
1236 mirror::Array* a = DecodeNonNullArray(array_id, &error);
Ian Rogers98379392014-02-24 16:53:16 -08001237 if (a == nullptr) {
Ian Rogersc0542af2014-09-03 16:16:56 -07001238 return error;
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -08001239 }
Elliott Hughes24437992011-11-30 14:49:33 -08001240
1241 if (offset < 0 || count < 0 || offset > a->GetLength() || a->GetLength() - offset < count) {
1242 LOG(WARNING) << __FUNCTION__ << " access out of bounds: offset=" << offset << "; count=" << count;
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -08001243 return JDWP::ERR_INVALID_LENGTH;
Elliott Hughes24437992011-11-30 14:49:33 -08001244 }
Ian Rogers1ff3c982014-08-12 02:30:58 -07001245 JDWP::JdwpTag element_tag = BasicTagFromClass(a->GetClass()->GetComponentType());
1246 expandBufAdd1(pReply, element_tag);
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -08001247 expandBufAdd4BE(pReply, count);
1248
Ian Rogers1ff3c982014-08-12 02:30:58 -07001249 if (IsPrimitiveTag(element_tag)) {
1250 size_t width = GetTagWidth(element_tag);
Elliott Hughes24437992011-11-30 14:49:33 -08001251 uint8_t* dst = expandBufAddSpace(pReply, count * width);
1252 if (width == 8) {
Ian Rogersef7d42f2014-01-06 12:55:46 -08001253 const uint64_t* src8 = reinterpret_cast<uint64_t*>(a->GetRawData(sizeof(uint64_t), 0));
Elliott Hughes24437992011-11-30 14:49:33 -08001254 for (int i = 0; i < count; ++i) JDWP::Write8BE(&dst, src8[offset + i]);
1255 } else if (width == 4) {
Ian Rogersef7d42f2014-01-06 12:55:46 -08001256 const uint32_t* src4 = reinterpret_cast<uint32_t*>(a->GetRawData(sizeof(uint32_t), 0));
Elliott Hughes24437992011-11-30 14:49:33 -08001257 for (int i = 0; i < count; ++i) JDWP::Write4BE(&dst, src4[offset + i]);
1258 } else if (width == 2) {
Ian Rogersef7d42f2014-01-06 12:55:46 -08001259 const uint16_t* src2 = reinterpret_cast<uint16_t*>(a->GetRawData(sizeof(uint16_t), 0));
Elliott Hughes24437992011-11-30 14:49:33 -08001260 for (int i = 0; i < count; ++i) JDWP::Write2BE(&dst, src2[offset + i]);
1261 } else {
Ian Rogersef7d42f2014-01-06 12:55:46 -08001262 const uint8_t* src = reinterpret_cast<uint8_t*>(a->GetRawData(sizeof(uint8_t), 0));
Elliott Hughes24437992011-11-30 14:49:33 -08001263 memcpy(dst, &src[offset * width], count * width);
1264 }
1265 } else {
Ian Rogers98379392014-02-24 16:53:16 -08001266 ScopedObjectAccessUnchecked soa(Thread::Current());
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001267 mirror::ObjectArray<mirror::Object>* oa = a->AsObjectArray<mirror::Object>();
Elliott Hughes24437992011-11-30 14:49:33 -08001268 for (int i = 0; i < count; ++i) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001269 mirror::Object* element = oa->Get(offset + i);
Ian Rogers98379392014-02-24 16:53:16 -08001270 JDWP::JdwpTag specific_tag = (element != nullptr) ? TagFromObject(soa, element)
Ian Rogers1ff3c982014-08-12 02:30:58 -07001271 : element_tag;
Elliott Hughes24437992011-11-30 14:49:33 -08001272 expandBufAdd1(pReply, specific_tag);
1273 expandBufAddObjectId(pReply, gRegistry->Add(element));
1274 }
1275 }
1276
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -08001277 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001278}
1279
Ian Rogersef7d42f2014-01-06 12:55:46 -08001280template <typename T>
Ian Rogersc0542af2014-09-03 16:16:56 -07001281static void CopyArrayData(mirror::Array* a, JDWP::Request* src, int offset, int count)
Ian Rogersef7d42f2014-01-06 12:55:46 -08001282 NO_THREAD_SAFETY_ANALYSIS {
1283 // TODO: fix when annotalysis correctly handles non-member functions.
Elliott Hughes4b9702c2013-02-20 18:13:24 -08001284 DCHECK(a->GetClass()->IsPrimitiveArray());
1285
Ian Rogersef7d42f2014-01-06 12:55:46 -08001286 T* dst = reinterpret_cast<T*>(a->GetRawData(sizeof(T), offset));
Elliott Hughes4b9702c2013-02-20 18:13:24 -08001287 for (int i = 0; i < count; ++i) {
Ian Rogersc0542af2014-09-03 16:16:56 -07001288 *dst++ = src->ReadValue(sizeof(T));
Elliott Hughes4b9702c2013-02-20 18:13:24 -08001289 }
1290}
1291
Elliott Hughes88d63092013-01-09 09:55:54 -08001292JDWP::JdwpError Dbg::SetArrayElements(JDWP::ObjectId array_id, int offset, int count,
Ian Rogersc0542af2014-09-03 16:16:56 -07001293 JDWP::Request* request) {
1294 JDWP::JdwpError error;
1295 mirror::Array* dst = DecodeNonNullArray(array_id, &error);
1296 if (dst == nullptr) {
1297 return error;
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -08001298 }
Elliott Hughesf03b8f62011-12-02 14:26:25 -08001299
Elliott Hughes4b9702c2013-02-20 18:13:24 -08001300 if (offset < 0 || count < 0 || offset > dst->GetLength() || dst->GetLength() - offset < count) {
Elliott Hughesf03b8f62011-12-02 14:26:25 -08001301 LOG(WARNING) << __FUNCTION__ << " access out of bounds: offset=" << offset << "; count=" << count;
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -08001302 return JDWP::ERR_INVALID_LENGTH;
Elliott Hughesf03b8f62011-12-02 14:26:25 -08001303 }
Ian Rogers1ff3c982014-08-12 02:30:58 -07001304 JDWP::JdwpTag element_tag = BasicTagFromClass(dst->GetClass()->GetComponentType());
Elliott Hughesf03b8f62011-12-02 14:26:25 -08001305
Ian Rogers1ff3c982014-08-12 02:30:58 -07001306 if (IsPrimitiveTag(element_tag)) {
1307 size_t width = GetTagWidth(element_tag);
Elliott Hughesf03b8f62011-12-02 14:26:25 -08001308 if (width == 8) {
Elliott Hughes4b9702c2013-02-20 18:13:24 -08001309 CopyArrayData<uint64_t>(dst, request, offset, count);
Elliott Hughesf03b8f62011-12-02 14:26:25 -08001310 } else if (width == 4) {
Elliott Hughes4b9702c2013-02-20 18:13:24 -08001311 CopyArrayData<uint32_t>(dst, request, offset, count);
Elliott Hughesf03b8f62011-12-02 14:26:25 -08001312 } else if (width == 2) {
Elliott Hughes4b9702c2013-02-20 18:13:24 -08001313 CopyArrayData<uint16_t>(dst, request, offset, count);
Elliott Hughesf03b8f62011-12-02 14:26:25 -08001314 } else {
Elliott Hughes4b9702c2013-02-20 18:13:24 -08001315 CopyArrayData<uint8_t>(dst, request, offset, count);
Elliott Hughesf03b8f62011-12-02 14:26:25 -08001316 }
1317 } else {
Elliott Hughes4b9702c2013-02-20 18:13:24 -08001318 mirror::ObjectArray<mirror::Object>* oa = dst->AsObjectArray<mirror::Object>();
Elliott Hughesf03b8f62011-12-02 14:26:25 -08001319 for (int i = 0; i < count; ++i) {
Ian Rogersc0542af2014-09-03 16:16:56 -07001320 JDWP::ObjectId id = request->ReadObjectId();
Ian Rogersc0542af2014-09-03 16:16:56 -07001321 mirror::Object* o = gRegistry->Get<mirror::Object*>(id, &error);
1322 if (error != JDWP::ERR_NONE) {
1323 return error;
Elliott Hughes436e3722012-02-17 20:01:47 -08001324 }
Sebastien Hertzd2fe10a2014-01-15 10:20:56 +01001325 oa->Set<false>(offset + i, o);
Elliott Hughesf03b8f62011-12-02 14:26:25 -08001326 }
1327 }
1328
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -08001329 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001330}
1331
Sebastien Hertz2c3e77a2015-04-02 16:26:48 +02001332JDWP::JdwpError Dbg::CreateString(const std::string& str, JDWP::ObjectId* new_string_id) {
1333 Thread* self = Thread::Current();
1334 mirror::String* new_string = mirror::String::AllocFromModifiedUtf8(self, str.c_str());
1335 if (new_string == nullptr) {
1336 DCHECK(self->IsExceptionPending());
1337 self->ClearException();
1338 LOG(ERROR) << "Could not allocate string";
1339 *new_string_id = 0;
1340 return JDWP::ERR_OUT_OF_MEMORY;
1341 }
1342 *new_string_id = gRegistry->Add(new_string);
1343 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001344}
1345
Sebastien Hertz2c3e77a2015-04-02 16:26:48 +02001346JDWP::JdwpError Dbg::CreateObject(JDWP::RefTypeId class_id, JDWP::ObjectId* new_object_id) {
Ian Rogersc0542af2014-09-03 16:16:56 -07001347 JDWP::JdwpError error;
1348 mirror::Class* c = DecodeClass(class_id, &error);
1349 if (c == nullptr) {
Sebastien Hertz2c3e77a2015-04-02 16:26:48 +02001350 *new_object_id = 0;
Ian Rogersc0542af2014-09-03 16:16:56 -07001351 return error;
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -08001352 }
Sebastien Hertz2c3e77a2015-04-02 16:26:48 +02001353 Thread* self = Thread::Current();
1354 mirror::Object* new_object = c->AllocObject(self);
1355 if (new_object == nullptr) {
1356 DCHECK(self->IsExceptionPending());
1357 self->ClearException();
1358 LOG(ERROR) << "Could not allocate object of type " << PrettyDescriptor(c);
1359 *new_object_id = 0;
1360 return JDWP::ERR_OUT_OF_MEMORY;
1361 }
1362 *new_object_id = gRegistry->Add(new_object);
Elliott Hughes436e3722012-02-17 20:01:47 -08001363 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001364}
1365
Elliott Hughesbf13d362011-12-08 15:51:37 -08001366/*
1367 * Used by Eclipse's "Display" view to evaluate "new byte[5]" to get "(byte[]) [0, 0, 0, 0, 0]".
1368 */
Elliott Hughes88d63092013-01-09 09:55:54 -08001369JDWP::JdwpError Dbg::CreateArrayObject(JDWP::RefTypeId array_class_id, uint32_t length,
Sebastien Hertz2c3e77a2015-04-02 16:26:48 +02001370 JDWP::ObjectId* new_array_id) {
Ian Rogersc0542af2014-09-03 16:16:56 -07001371 JDWP::JdwpError error;
1372 mirror::Class* c = DecodeClass(array_class_id, &error);
1373 if (c == nullptr) {
Sebastien Hertz2c3e77a2015-04-02 16:26:48 +02001374 *new_array_id = 0;
Ian Rogersc0542af2014-09-03 16:16:56 -07001375 return error;
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -08001376 }
Sebastien Hertz2c3e77a2015-04-02 16:26:48 +02001377 Thread* self = Thread::Current();
1378 gc::Heap* heap = Runtime::Current()->GetHeap();
1379 mirror::Array* new_array = mirror::Array::Alloc<true>(self, c, length,
1380 c->GetComponentSizeShift(),
1381 heap->GetCurrentAllocator());
1382 if (new_array == nullptr) {
1383 DCHECK(self->IsExceptionPending());
1384 self->ClearException();
1385 LOG(ERROR) << "Could not allocate array of type " << PrettyDescriptor(c);
1386 *new_array_id = 0;
1387 return JDWP::ERR_OUT_OF_MEMORY;
1388 }
1389 *new_array_id = gRegistry->Add(new_array);
Elliott Hughes436e3722012-02-17 20:01:47 -08001390 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001391}
1392
Mathieu Chartierc7853442015-03-27 14:35:38 -07001393JDWP::FieldId Dbg::ToFieldId(const ArtField* f) {
Elliott Hughes03181a82011-11-17 17:22:21 -08001394 return static_cast<JDWP::FieldId>(reinterpret_cast<uintptr_t>(f));
Elliott Hughes03181a82011-11-17 17:22:21 -08001395}
1396
Brian Carlstromea46f952013-07-30 01:26:50 -07001397static JDWP::MethodId ToMethodId(const mirror::ArtMethod* m)
Ian Rogersb726dcb2012-09-05 08:57:23 -07001398 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Mathieu Chartier590fee92013-09-13 13:46:47 -07001399 CHECK(!kMovingMethods);
Elliott Hughes03181a82011-11-17 17:22:21 -08001400 return static_cast<JDWP::MethodId>(reinterpret_cast<uintptr_t>(m));
Elliott Hughes03181a82011-11-17 17:22:21 -08001401}
1402
Mathieu Chartierc7853442015-03-27 14:35:38 -07001403static ArtField* FromFieldId(JDWP::FieldId fid)
Ian Rogersb726dcb2012-09-05 08:57:23 -07001404 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Mathieu Chartierc7853442015-03-27 14:35:38 -07001405 return reinterpret_cast<ArtField*>(static_cast<uintptr_t>(fid));
Elliott Hughesaed4be92011-12-02 16:16:23 -08001406}
1407
Brian Carlstromea46f952013-07-30 01:26:50 -07001408static mirror::ArtMethod* FromMethodId(JDWP::MethodId mid)
Ian Rogersb726dcb2012-09-05 08:57:23 -07001409 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Mathieu Chartier590fee92013-09-13 13:46:47 -07001410 CHECK(!kMovingMethods);
Brian Carlstromea46f952013-07-30 01:26:50 -07001411 return reinterpret_cast<mirror::ArtMethod*>(static_cast<uintptr_t>(mid));
Elliott Hughes03181a82011-11-17 17:22:21 -08001412}
1413
Sebastien Hertz6995c602014-09-09 12:10:13 +02001414bool Dbg::MatchThread(JDWP::ObjectId expected_thread_id, Thread* event_thread) {
1415 CHECK(event_thread != nullptr);
1416 JDWP::JdwpError error;
1417 mirror::Object* expected_thread_peer = gRegistry->Get<mirror::Object*>(expected_thread_id,
1418 &error);
1419 return expected_thread_peer == event_thread->GetPeer();
1420}
1421
1422bool Dbg::MatchLocation(const JDWP::JdwpLocation& expected_location,
1423 const JDWP::EventLocation& event_location) {
1424 if (expected_location.dex_pc != event_location.dex_pc) {
1425 return false;
1426 }
1427 mirror::ArtMethod* m = FromMethodId(expected_location.method_id);
1428 return m == event_location.method;
1429}
1430
1431bool Dbg::MatchType(mirror::Class* event_class, JDWP::RefTypeId class_id) {
Sebastien Hertza9aa0ff2014-09-19 12:07:51 +02001432 if (event_class == nullptr) {
1433 return false;
1434 }
Sebastien Hertz6995c602014-09-09 12:10:13 +02001435 JDWP::JdwpError error;
1436 mirror::Class* expected_class = DecodeClass(class_id, &error);
1437 CHECK(expected_class != nullptr);
1438 return expected_class->IsAssignableFrom(event_class);
1439}
1440
1441bool Dbg::MatchField(JDWP::RefTypeId expected_type_id, JDWP::FieldId expected_field_id,
Mathieu Chartierc7853442015-03-27 14:35:38 -07001442 ArtField* event_field) {
1443 ArtField* expected_field = FromFieldId(expected_field_id);
Sebastien Hertz6995c602014-09-09 12:10:13 +02001444 if (expected_field != event_field) {
1445 return false;
1446 }
1447 return Dbg::MatchType(event_field->GetDeclaringClass(), expected_type_id);
1448}
1449
1450bool Dbg::MatchInstance(JDWP::ObjectId expected_instance_id, mirror::Object* event_instance) {
1451 JDWP::JdwpError error;
1452 mirror::Object* modifier_instance = gRegistry->Get<mirror::Object*>(expected_instance_id, &error);
1453 return modifier_instance == event_instance;
1454}
1455
1456void Dbg::SetJdwpLocation(JDWP::JdwpLocation* location, mirror::ArtMethod* m, uint32_t dex_pc)
Sebastien Hertz69206392015-04-07 15:54:25 +02001457 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_)
1458 LOCKS_EXCLUDED(Locks::thread_list_lock_,
1459 Locks::thread_suspend_count_lock_) {
Ian Rogersc0542af2014-09-03 16:16:56 -07001460 if (m == nullptr) {
Sebastien Hertza9aa0ff2014-09-19 12:07:51 +02001461 memset(location, 0, sizeof(*location));
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08001462 } else {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001463 mirror::Class* c = m->GetDeclaringClass();
Ian Rogersc0542af2014-09-03 16:16:56 -07001464 location->type_tag = GetTypeTag(c);
1465 location->class_id = gRegistry->AddRefType(c);
1466 location->method_id = ToMethodId(m);
1467 location->dex_pc = (m->IsNative() || m->IsProxyMethod()) ? static_cast<uint64_t>(-1) : dex_pc;
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08001468 }
Elliott Hughesd07986f2011-12-06 18:27:45 -08001469}
1470
Ian Rogersc0542af2014-09-03 16:16:56 -07001471std::string Dbg::GetMethodName(JDWP::MethodId method_id) {
Brian Carlstromea46f952013-07-30 01:26:50 -07001472 mirror::ArtMethod* m = FromMethodId(method_id);
Sebastien Hertza9aa0ff2014-09-19 12:07:51 +02001473 if (m == nullptr) {
Mathieu Chartier2cebb242015-04-21 16:50:40 -07001474 return "null";
Sebastien Hertza9aa0ff2014-09-19 12:07:51 +02001475 }
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07001476 return m->GetName();
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001477}
1478
Ian Rogersc0542af2014-09-03 16:16:56 -07001479std::string Dbg::GetFieldName(JDWP::FieldId field_id) {
Mathieu Chartierc7853442015-03-27 14:35:38 -07001480 ArtField* f = FromFieldId(field_id);
Sebastien Hertza9aa0ff2014-09-19 12:07:51 +02001481 if (f == nullptr) {
Mathieu Chartier2cebb242015-04-21 16:50:40 -07001482 return "null";
Sebastien Hertza9aa0ff2014-09-19 12:07:51 +02001483 }
1484 return f->GetName();
Elliott Hughesa96836a2013-01-17 12:27:49 -08001485}
1486
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001487/*
1488 * Augment the access flags for synthetic methods and fields by setting
1489 * the (as described by the spec) "0xf0000000 bit". Also, strip out any
1490 * flags not specified by the Java programming language.
1491 */
1492static uint32_t MangleAccessFlags(uint32_t accessFlags) {
1493 accessFlags &= kAccJavaFlagsMask;
1494 if ((accessFlags & kAccSynthetic) != 0) {
1495 accessFlags |= 0xf0000000;
1496 }
1497 return accessFlags;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001498}
1499
Elliott Hughesdbb40792011-11-18 17:05:22 -08001500/*
Jeff Haob7cefc72013-11-14 14:51:09 -08001501 * Circularly shifts registers so that arguments come first. Debuggers
1502 * expect slots to begin with arguments, but dex code places them at
1503 * the end.
Elliott Hughesdbb40792011-11-18 17:05:22 -08001504 */
Jeff Haob7cefc72013-11-14 14:51:09 -08001505static uint16_t MangleSlot(uint16_t slot, mirror::ArtMethod* m)
1506 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07001507 const DexFile::CodeItem* code_item = m->GetCodeItem();
Sebastien Hertzcb19ebf2014-03-11 15:26:35 +01001508 if (code_item == nullptr) {
1509 // We should not get here for a method without code (native, proxy or abstract). Log it and
1510 // return the slot as is since all registers are arguments.
1511 LOG(WARNING) << "Trying to mangle slot for method without code " << PrettyMethod(m);
1512 return slot;
1513 }
Jeff Haob7cefc72013-11-14 14:51:09 -08001514 uint16_t ins_size = code_item->ins_size_;
1515 uint16_t locals_size = code_item->registers_size_ - ins_size;
1516 if (slot >= locals_size) {
1517 return slot - locals_size;
1518 } else {
1519 return slot + ins_size;
Elliott Hughesdbb40792011-11-18 17:05:22 -08001520 }
Elliott Hughesdbb40792011-11-18 17:05:22 -08001521}
1522
Jeff Haob7cefc72013-11-14 14:51:09 -08001523/*
1524 * Circularly shifts registers so that arguments come last. Reverts
1525 * slots to dex style argument placement.
1526 */
Sebastien Hertzabbabc82015-03-26 08:47:47 +01001527static uint16_t DemangleSlot(uint16_t slot, mirror::ArtMethod* m, JDWP::JdwpError* error)
Ian Rogersb726dcb2012-09-05 08:57:23 -07001528 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07001529 const DexFile::CodeItem* code_item = m->GetCodeItem();
Sebastien Hertzcb19ebf2014-03-11 15:26:35 +01001530 if (code_item == nullptr) {
1531 // We should not get here for a method without code (native, proxy or abstract). Log it and
1532 // return the slot as is since all registers are arguments.
1533 LOG(WARNING) << "Trying to demangle slot for method without code " << PrettyMethod(m);
Sebastien Hertzabbabc82015-03-26 08:47:47 +01001534 uint16_t vreg_count = mirror::ArtMethod::NumArgRegisters(m->GetShorty());
1535 if (slot < vreg_count) {
1536 *error = JDWP::ERR_NONE;
1537 return slot;
1538 }
Jeff Haob7cefc72013-11-14 14:51:09 -08001539 } else {
Sebastien Hertzabbabc82015-03-26 08:47:47 +01001540 if (slot < code_item->registers_size_) {
1541 uint16_t ins_size = code_item->ins_size_;
1542 uint16_t locals_size = code_item->registers_size_ - ins_size;
1543 *error = JDWP::ERR_NONE;
1544 return (slot < ins_size) ? slot + locals_size : slot - ins_size;
1545 }
Elliott Hughesdbb40792011-11-18 17:05:22 -08001546 }
Sebastien Hertzabbabc82015-03-26 08:47:47 +01001547
1548 // Slot is invalid in the method.
1549 LOG(ERROR) << "Invalid local slot " << slot << " for method " << PrettyMethod(m);
1550 *error = JDWP::ERR_INVALID_SLOT;
1551 return DexFile::kDexNoIndex16;
Elliott Hughesdbb40792011-11-18 17:05:22 -08001552}
1553
Elliott Hughes88d63092013-01-09 09:55:54 -08001554JDWP::JdwpError Dbg::OutputDeclaredFields(JDWP::RefTypeId class_id, bool with_generic, JDWP::ExpandBuf* pReply) {
Ian Rogersc0542af2014-09-03 16:16:56 -07001555 JDWP::JdwpError error;
1556 mirror::Class* c = DecodeClass(class_id, &error);
1557 if (c == nullptr) {
1558 return error;
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -08001559 }
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001560
1561 size_t instance_field_count = c->NumInstanceFields();
1562 size_t static_field_count = c->NumStaticFields();
1563
1564 expandBufAdd4BE(pReply, instance_field_count + static_field_count);
1565
1566 for (size_t i = 0; i < instance_field_count + static_field_count; ++i) {
Mathieu Chartierc7853442015-03-27 14:35:38 -07001567 ArtField* f = (i < instance_field_count) ? c->GetInstanceField(i) : c->GetStaticField(i - instance_field_count);
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001568 expandBufAddFieldId(pReply, ToFieldId(f));
Mathieu Chartier61c5ebc2014-06-05 17:42:53 -07001569 expandBufAddUtf8String(pReply, f->GetName());
1570 expandBufAddUtf8String(pReply, f->GetTypeDescriptor());
Elliott Hughesc5b734a2011-12-01 17:20:58 -08001571 if (with_generic) {
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001572 static const char genericSignature[1] = "";
1573 expandBufAddUtf8String(pReply, genericSignature);
1574 }
1575 expandBufAdd4BE(pReply, MangleAccessFlags(f->GetAccessFlags()));
1576 }
Elliott Hughes436e3722012-02-17 20:01:47 -08001577 return JDWP::ERR_NONE;
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001578}
1579
Elliott Hughes88d63092013-01-09 09:55:54 -08001580JDWP::JdwpError Dbg::OutputDeclaredMethods(JDWP::RefTypeId class_id, bool with_generic,
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001581 JDWP::ExpandBuf* pReply) {
Ian Rogersc0542af2014-09-03 16:16:56 -07001582 JDWP::JdwpError error;
1583 mirror::Class* c = DecodeClass(class_id, &error);
1584 if (c == nullptr) {
1585 return error;
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -08001586 }
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001587
1588 size_t direct_method_count = c->NumDirectMethods();
1589 size_t virtual_method_count = c->NumVirtualMethods();
1590
1591 expandBufAdd4BE(pReply, direct_method_count + virtual_method_count);
1592
1593 for (size_t i = 0; i < direct_method_count + virtual_method_count; ++i) {
Brian Carlstromea46f952013-07-30 01:26:50 -07001594 mirror::ArtMethod* m = (i < direct_method_count) ? c->GetDirectMethod(i) : c->GetVirtualMethod(i - direct_method_count);
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001595 expandBufAddMethodId(pReply, ToMethodId(m));
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07001596 expandBufAddUtf8String(pReply, m->GetName());
1597 expandBufAddUtf8String(pReply, m->GetSignature().ToString());
Elliott Hughesc5b734a2011-12-01 17:20:58 -08001598 if (with_generic) {
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001599 static const char genericSignature[1] = "";
1600 expandBufAddUtf8String(pReply, genericSignature);
1601 }
1602 expandBufAdd4BE(pReply, MangleAccessFlags(m->GetAccessFlags()));
1603 }
Elliott Hughes436e3722012-02-17 20:01:47 -08001604 return JDWP::ERR_NONE;
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001605}
1606
Elliott Hughes88d63092013-01-09 09:55:54 -08001607JDWP::JdwpError Dbg::OutputDeclaredInterfaces(JDWP::RefTypeId class_id, JDWP::ExpandBuf* pReply) {
Ian Rogersc0542af2014-09-03 16:16:56 -07001608 JDWP::JdwpError error;
Mathieu Chartierf8322842014-05-16 10:59:25 -07001609 Thread* self = Thread::Current();
1610 StackHandleScope<1> hs(self);
Ian Rogersc0542af2014-09-03 16:16:56 -07001611 Handle<mirror::Class> c(hs.NewHandle(DecodeClass(class_id, &error)));
Mathieu Chartierf8322842014-05-16 10:59:25 -07001612 if (c.Get() == nullptr) {
Ian Rogersc0542af2014-09-03 16:16:56 -07001613 return error;
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -08001614 }
Mathieu Chartierf8322842014-05-16 10:59:25 -07001615 size_t interface_count = c->NumDirectInterfaces();
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001616 expandBufAdd4BE(pReply, interface_count);
1617 for (size_t i = 0; i < interface_count; ++i) {
Mathieu Chartierf8322842014-05-16 10:59:25 -07001618 expandBufAddRefTypeId(pReply,
1619 gRegistry->AddRefType(mirror::Class::GetDirectInterface(self, c, i)));
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001620 }
Elliott Hughes436e3722012-02-17 20:01:47 -08001621 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001622}
1623
Ian Rogersc0542af2014-09-03 16:16:56 -07001624void Dbg::OutputLineTable(JDWP::RefTypeId, JDWP::MethodId method_id, JDWP::ExpandBuf* pReply) {
Elliott Hughes03181a82011-11-17 17:22:21 -08001625 struct DebugCallbackContext {
1626 int numItems;
1627 JDWP::ExpandBuf* pReply;
1628
Elliott Hughes2435a572012-02-17 16:07:41 -08001629 static bool Callback(void* context, uint32_t address, uint32_t line_number) {
Elliott Hughes03181a82011-11-17 17:22:21 -08001630 DebugCallbackContext* pContext = reinterpret_cast<DebugCallbackContext*>(context);
1631 expandBufAdd8BE(pContext->pReply, address);
Elliott Hughes2435a572012-02-17 16:07:41 -08001632 expandBufAdd4BE(pContext->pReply, line_number);
Elliott Hughes03181a82011-11-17 17:22:21 -08001633 pContext->numItems++;
Sebastien Hertzf2910ee2013-10-19 16:39:24 +02001634 return false;
Elliott Hughes03181a82011-11-17 17:22:21 -08001635 }
1636 };
Brian Carlstromea46f952013-07-30 01:26:50 -07001637 mirror::ArtMethod* m = FromMethodId(method_id);
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07001638 const DexFile::CodeItem* code_item = m->GetCodeItem();
Elliott Hughes03181a82011-11-17 17:22:21 -08001639 uint64_t start, end;
Sebastien Hertzcb19ebf2014-03-11 15:26:35 +01001640 if (code_item == nullptr) {
1641 DCHECK(m->IsNative() || m->IsProxyMethod());
Elliott Hughes03181a82011-11-17 17:22:21 -08001642 start = -1;
1643 end = -1;
1644 } else {
1645 start = 0;
jeffhao14f0db92012-12-14 17:50:42 -08001646 // Return the index of the last instruction
Sebastien Hertzcb19ebf2014-03-11 15:26:35 +01001647 end = code_item->insns_size_in_code_units_ - 1;
Elliott Hughes03181a82011-11-17 17:22:21 -08001648 }
1649
1650 expandBufAdd8BE(pReply, start);
1651 expandBufAdd8BE(pReply, end);
1652
1653 // Add numLines later
1654 size_t numLinesOffset = expandBufGetLength(pReply);
1655 expandBufAdd4BE(pReply, 0);
1656
1657 DebugCallbackContext context;
1658 context.numItems = 0;
1659 context.pReply = pReply;
1660
Sebastien Hertzcb19ebf2014-03-11 15:26:35 +01001661 if (code_item != nullptr) {
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07001662 m->GetDexFile()->DecodeDebugInfo(code_item, m->IsStatic(), m->GetDexMethodIndex(),
Ian Rogersc0542af2014-09-03 16:16:56 -07001663 DebugCallbackContext::Callback, nullptr, &context);
Sebastien Hertzcb19ebf2014-03-11 15:26:35 +01001664 }
Elliott Hughes03181a82011-11-17 17:22:21 -08001665
1666 JDWP::Set4BE(expandBufGetBuffer(pReply) + numLinesOffset, context.numItems);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001667}
1668
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07001669void Dbg::OutputVariableTable(JDWP::RefTypeId, JDWP::MethodId method_id, bool with_generic,
1670 JDWP::ExpandBuf* pReply) {
Elliott Hughesdbb40792011-11-18 17:05:22 -08001671 struct DebugCallbackContext {
Jeff Haob7cefc72013-11-14 14:51:09 -08001672 mirror::ArtMethod* method;
Elliott Hughesdbb40792011-11-18 17:05:22 -08001673 JDWP::ExpandBuf* pReply;
Elliott Hughesc5b734a2011-12-01 17:20:58 -08001674 size_t variable_count;
1675 bool with_generic;
Elliott Hughesdbb40792011-11-18 17:05:22 -08001676
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07001677 static void Callback(void* context, uint16_t slot, uint32_t startAddress, uint32_t endAddress,
1678 const char* name, const char* descriptor, const char* signature)
Jeff Haob7cefc72013-11-14 14:51:09 -08001679 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Elliott Hughesdbb40792011-11-18 17:05:22 -08001680 DebugCallbackContext* pContext = reinterpret_cast<DebugCallbackContext*>(context);
1681
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07001682 VLOG(jdwp) << StringPrintf(" %2zd: %d(%d) '%s' '%s' '%s' actual slot=%d mangled slot=%d",
1683 pContext->variable_count, startAddress, endAddress - startAddress,
1684 name, descriptor, signature, slot,
1685 MangleSlot(slot, pContext->method));
Elliott Hughesdbb40792011-11-18 17:05:22 -08001686
Jeff Haob7cefc72013-11-14 14:51:09 -08001687 slot = MangleSlot(slot, pContext->method);
Elliott Hughes68fdbd02011-11-29 19:22:47 -08001688
Elliott Hughesdbb40792011-11-18 17:05:22 -08001689 expandBufAdd8BE(pContext->pReply, startAddress);
1690 expandBufAddUtf8String(pContext->pReply, name);
1691 expandBufAddUtf8String(pContext->pReply, descriptor);
Elliott Hughesc5b734a2011-12-01 17:20:58 -08001692 if (pContext->with_generic) {
Elliott Hughesdbb40792011-11-18 17:05:22 -08001693 expandBufAddUtf8String(pContext->pReply, signature);
1694 }
1695 expandBufAdd4BE(pContext->pReply, endAddress - startAddress);
1696 expandBufAdd4BE(pContext->pReply, slot);
1697
Elliott Hughesc5b734a2011-12-01 17:20:58 -08001698 ++pContext->variable_count;
Elliott Hughesdbb40792011-11-18 17:05:22 -08001699 }
1700 };
Brian Carlstromea46f952013-07-30 01:26:50 -07001701 mirror::ArtMethod* m = FromMethodId(method_id);
Elliott Hughesdbb40792011-11-18 17:05:22 -08001702
Elliott Hughesc5b734a2011-12-01 17:20:58 -08001703 // arg_count considers doubles and longs to take 2 units.
1704 // variable_count considers everything to take 1 unit.
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07001705 std::string shorty(m->GetShorty());
Brian Carlstromea46f952013-07-30 01:26:50 -07001706 expandBufAdd4BE(pReply, mirror::ArtMethod::NumArgRegisters(shorty));
Elliott Hughesdbb40792011-11-18 17:05:22 -08001707
Elliott Hughesc5b734a2011-12-01 17:20:58 -08001708 // We don't know the total number of variables yet, so leave a blank and update it later.
1709 size_t variable_count_offset = expandBufGetLength(pReply);
Elliott Hughesdbb40792011-11-18 17:05:22 -08001710 expandBufAdd4BE(pReply, 0);
1711
1712 DebugCallbackContext context;
Jeff Haob7cefc72013-11-14 14:51:09 -08001713 context.method = m;
Elliott Hughesdbb40792011-11-18 17:05:22 -08001714 context.pReply = pReply;
Elliott Hughesc5b734a2011-12-01 17:20:58 -08001715 context.variable_count = 0;
1716 context.with_generic = with_generic;
Elliott Hughesdbb40792011-11-18 17:05:22 -08001717
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07001718 const DexFile::CodeItem* code_item = m->GetCodeItem();
Sebastien Hertzcb19ebf2014-03-11 15:26:35 +01001719 if (code_item != nullptr) {
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07001720 m->GetDexFile()->DecodeDebugInfo(
Ian Rogersc0542af2014-09-03 16:16:56 -07001721 code_item, m->IsStatic(), m->GetDexMethodIndex(), nullptr, DebugCallbackContext::Callback,
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07001722 &context);
Sebastien Hertzcb19ebf2014-03-11 15:26:35 +01001723 }
Elliott Hughesdbb40792011-11-18 17:05:22 -08001724
Elliott Hughesc5b734a2011-12-01 17:20:58 -08001725 JDWP::Set4BE(expandBufGetBuffer(pReply) + variable_count_offset, context.variable_count);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001726}
1727
Jeff Hao579b0242013-11-18 13:16:49 -08001728void Dbg::OutputMethodReturnValue(JDWP::MethodId method_id, const JValue* return_value,
1729 JDWP::ExpandBuf* pReply) {
1730 mirror::ArtMethod* m = FromMethodId(method_id);
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07001731 JDWP::JdwpTag tag = BasicTagFromDescriptor(m->GetShorty());
Jeff Hao579b0242013-11-18 13:16:49 -08001732 OutputJValue(tag, return_value, pReply);
1733}
1734
Sebastien Hertz3f52eaf2014-04-04 17:50:18 +02001735void Dbg::OutputFieldValue(JDWP::FieldId field_id, const JValue* field_value,
1736 JDWP::ExpandBuf* pReply) {
Mathieu Chartierc7853442015-03-27 14:35:38 -07001737 ArtField* f = FromFieldId(field_id);
Mathieu Chartier61c5ebc2014-06-05 17:42:53 -07001738 JDWP::JdwpTag tag = BasicTagFromDescriptor(f->GetTypeDescriptor());
Sebastien Hertz3f52eaf2014-04-04 17:50:18 +02001739 OutputJValue(tag, field_value, pReply);
1740}
1741
Elliott Hughes9777ba22013-01-17 09:04:19 -08001742JDWP::JdwpError Dbg::GetBytecodes(JDWP::RefTypeId, JDWP::MethodId method_id,
Ian Rogersc0542af2014-09-03 16:16:56 -07001743 std::vector<uint8_t>* bytecodes) {
Brian Carlstromea46f952013-07-30 01:26:50 -07001744 mirror::ArtMethod* m = FromMethodId(method_id);
Ian Rogersc0542af2014-09-03 16:16:56 -07001745 if (m == nullptr) {
Elliott Hughes9777ba22013-01-17 09:04:19 -08001746 return JDWP::ERR_INVALID_METHODID;
1747 }
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07001748 const DexFile::CodeItem* code_item = m->GetCodeItem();
Elliott Hughes9777ba22013-01-17 09:04:19 -08001749 size_t byte_count = code_item->insns_size_in_code_units_ * 2;
1750 const uint8_t* begin = reinterpret_cast<const uint8_t*>(code_item->insns_);
1751 const uint8_t* end = begin + byte_count;
1752 for (const uint8_t* p = begin; p != end; ++p) {
Ian Rogersc0542af2014-09-03 16:16:56 -07001753 bytecodes->push_back(*p);
Elliott Hughes9777ba22013-01-17 09:04:19 -08001754 }
1755 return JDWP::ERR_NONE;
1756}
1757
Elliott Hughes88d63092013-01-09 09:55:54 -08001758JDWP::JdwpTag Dbg::GetFieldBasicTag(JDWP::FieldId field_id) {
Mathieu Chartier61c5ebc2014-06-05 17:42:53 -07001759 return BasicTagFromDescriptor(FromFieldId(field_id)->GetTypeDescriptor());
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001760}
1761
Elliott Hughes88d63092013-01-09 09:55:54 -08001762JDWP::JdwpTag Dbg::GetStaticFieldBasicTag(JDWP::FieldId field_id) {
Mathieu Chartier61c5ebc2014-06-05 17:42:53 -07001763 return BasicTagFromDescriptor(FromFieldId(field_id)->GetTypeDescriptor());
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001764}
1765
Elliott Hughes88d63092013-01-09 09:55:54 -08001766static JDWP::JdwpError GetFieldValueImpl(JDWP::RefTypeId ref_type_id, JDWP::ObjectId object_id,
1767 JDWP::FieldId field_id, JDWP::ExpandBuf* pReply,
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001768 bool is_static)
Ian Rogersb726dcb2012-09-05 08:57:23 -07001769 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Ian Rogersc0542af2014-09-03 16:16:56 -07001770 JDWP::JdwpError error;
1771 mirror::Class* c = DecodeClass(ref_type_id, &error);
1772 if (ref_type_id != 0 && c == nullptr) {
1773 return error;
Elliott Hughes0cf74332012-02-23 23:14:00 -08001774 }
1775
Sebastien Hertz6995c602014-09-09 12:10:13 +02001776 mirror::Object* o = Dbg::GetObjectRegistry()->Get<mirror::Object*>(object_id, &error);
Ian Rogersc0542af2014-09-03 16:16:56 -07001777 if ((!is_static && o == nullptr) || error != JDWP::ERR_NONE) {
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08001778 return JDWP::ERR_INVALID_OBJECT;
1779 }
Mathieu Chartierc7853442015-03-27 14:35:38 -07001780 ArtField* f = FromFieldId(field_id);
Elliott Hughes0cf74332012-02-23 23:14:00 -08001781
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001782 mirror::Class* receiver_class = c;
Ian Rogersc0542af2014-09-03 16:16:56 -07001783 if (receiver_class == nullptr && o != nullptr) {
Elliott Hughes0cf74332012-02-23 23:14:00 -08001784 receiver_class = o->GetClass();
1785 }
Mathieu Chartier2cebb242015-04-21 16:50:40 -07001786 // TODO: should we give up now if receiver_class is null?
Ian Rogersc0542af2014-09-03 16:16:56 -07001787 if (receiver_class != nullptr && !f->GetDeclaringClass()->IsAssignableFrom(receiver_class)) {
Elliott Hughes0cf74332012-02-23 23:14:00 -08001788 LOG(INFO) << "ERR_INVALID_FIELDID: " << PrettyField(f) << " " << PrettyClass(receiver_class);
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08001789 return JDWP::ERR_INVALID_FIELDID;
1790 }
Elliott Hughesaed4be92011-12-02 16:16:23 -08001791
Elliott Hughes0cf74332012-02-23 23:14:00 -08001792 // The RI only enforces the static/non-static mismatch in one direction.
1793 // TODO: should we change the tests and check both?
1794 if (is_static) {
1795 if (!f->IsStatic()) {
1796 return JDWP::ERR_INVALID_FIELDID;
1797 }
1798 } else {
1799 if (f->IsStatic()) {
Ian Rogersc0542af2014-09-03 16:16:56 -07001800 LOG(WARNING) << "Ignoring non-nullptr receiver for ObjectReference.SetValues on static field "
1801 << PrettyField(f);
Elliott Hughes0cf74332012-02-23 23:14:00 -08001802 }
1803 }
jeffhao0dfbb7e2012-11-28 15:26:03 -08001804 if (f->IsStatic()) {
1805 o = f->GetDeclaringClass();
1806 }
Elliott Hughes0cf74332012-02-23 23:14:00 -08001807
Mathieu Chartier61c5ebc2014-06-05 17:42:53 -07001808 JDWP::JdwpTag tag = BasicTagFromDescriptor(f->GetTypeDescriptor());
Jeff Hao579b0242013-11-18 13:16:49 -08001809 JValue field_value;
1810 if (tag == JDWP::JT_VOID) {
1811 LOG(FATAL) << "Unknown tag: " << tag;
1812 } else if (!IsPrimitiveTag(tag)) {
1813 field_value.SetL(f->GetObject(o));
1814 } else if (tag == JDWP::JT_DOUBLE || tag == JDWP::JT_LONG) {
1815 field_value.SetJ(f->Get64(o));
Elliott Hughesaed4be92011-12-02 16:16:23 -08001816 } else {
Jeff Hao579b0242013-11-18 13:16:49 -08001817 field_value.SetI(f->Get32(o));
Elliott Hughesaed4be92011-12-02 16:16:23 -08001818 }
Jeff Hao579b0242013-11-18 13:16:49 -08001819 Dbg::OutputJValue(tag, &field_value, pReply);
1820
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08001821 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001822}
1823
Elliott Hughes88d63092013-01-09 09:55:54 -08001824JDWP::JdwpError Dbg::GetFieldValue(JDWP::ObjectId object_id, JDWP::FieldId field_id,
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001825 JDWP::ExpandBuf* pReply) {
Elliott Hughes88d63092013-01-09 09:55:54 -08001826 return GetFieldValueImpl(0, object_id, field_id, pReply, false);
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08001827}
1828
Ian Rogersc0542af2014-09-03 16:16:56 -07001829JDWP::JdwpError Dbg::GetStaticFieldValue(JDWP::RefTypeId ref_type_id, JDWP::FieldId field_id,
1830 JDWP::ExpandBuf* pReply) {
Elliott Hughes88d63092013-01-09 09:55:54 -08001831 return GetFieldValueImpl(ref_type_id, 0, field_id, pReply, true);
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08001832}
1833
Elliott Hughes88d63092013-01-09 09:55:54 -08001834static JDWP::JdwpError SetFieldValueImpl(JDWP::ObjectId object_id, JDWP::FieldId field_id,
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001835 uint64_t value, int width, bool is_static)
Ian Rogersb726dcb2012-09-05 08:57:23 -07001836 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Ian Rogersc0542af2014-09-03 16:16:56 -07001837 JDWP::JdwpError error;
Sebastien Hertz6995c602014-09-09 12:10:13 +02001838 mirror::Object* o = Dbg::GetObjectRegistry()->Get<mirror::Object*>(object_id, &error);
Ian Rogersc0542af2014-09-03 16:16:56 -07001839 if ((!is_static && o == nullptr) || error != JDWP::ERR_NONE) {
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08001840 return JDWP::ERR_INVALID_OBJECT;
1841 }
Mathieu Chartierc7853442015-03-27 14:35:38 -07001842 ArtField* f = FromFieldId(field_id);
Elliott Hughes0cf74332012-02-23 23:14:00 -08001843
1844 // The RI only enforces the static/non-static mismatch in one direction.
1845 // TODO: should we change the tests and check both?
1846 if (is_static) {
1847 if (!f->IsStatic()) {
1848 return JDWP::ERR_INVALID_FIELDID;
1849 }
1850 } else {
1851 if (f->IsStatic()) {
Ian Rogersc0542af2014-09-03 16:16:56 -07001852 LOG(WARNING) << "Ignoring non-nullptr receiver for ObjectReference.SetValues on static field " << PrettyField(f);
Elliott Hughes0cf74332012-02-23 23:14:00 -08001853 }
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08001854 }
jeffhao0dfbb7e2012-11-28 15:26:03 -08001855 if (f->IsStatic()) {
1856 o = f->GetDeclaringClass();
1857 }
Elliott Hughesaed4be92011-12-02 16:16:23 -08001858
Mathieu Chartier61c5ebc2014-06-05 17:42:53 -07001859 JDWP::JdwpTag tag = BasicTagFromDescriptor(f->GetTypeDescriptor());
Elliott Hughesaed4be92011-12-02 16:16:23 -08001860
1861 if (IsPrimitiveTag(tag)) {
1862 if (tag == JDWP::JT_DOUBLE || tag == JDWP::JT_LONG) {
Elliott Hughes1bac54f2012-03-16 12:48:31 -07001863 CHECK_EQ(width, 8);
Sebastien Hertzd2fe10a2014-01-15 10:20:56 +01001864 // Debugging can't use transactional mode (runtime only).
1865 f->Set64<false>(o, value);
Elliott Hughesaed4be92011-12-02 16:16:23 -08001866 } else {
Elliott Hughes1bac54f2012-03-16 12:48:31 -07001867 CHECK_LE(width, 4);
Sebastien Hertzd2fe10a2014-01-15 10:20:56 +01001868 // Debugging can't use transactional mode (runtime only).
1869 f->Set32<false>(o, value);
Elliott Hughesaed4be92011-12-02 16:16:23 -08001870 }
1871 } else {
Sebastien Hertz6995c602014-09-09 12:10:13 +02001872 mirror::Object* v = Dbg::GetObjectRegistry()->Get<mirror::Object*>(value, &error);
Ian Rogersc0542af2014-09-03 16:16:56 -07001873 if (error != JDWP::ERR_NONE) {
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -08001874 return JDWP::ERR_INVALID_OBJECT;
1875 }
Ian Rogersc0542af2014-09-03 16:16:56 -07001876 if (v != nullptr) {
Mathieu Chartier61c5ebc2014-06-05 17:42:53 -07001877 mirror::Class* field_type;
1878 {
Mathieu Chartierc7853442015-03-27 14:35:38 -07001879 StackHandleScope<2> hs(Thread::Current());
Mathieu Chartier61c5ebc2014-06-05 17:42:53 -07001880 HandleWrapper<mirror::Object> h_v(hs.NewHandleWrapper(&v));
Mathieu Chartier61c5ebc2014-06-05 17:42:53 -07001881 HandleWrapper<mirror::Object> h_o(hs.NewHandleWrapper(&o));
Mathieu Chartierc7853442015-03-27 14:35:38 -07001882 field_type = f->GetType<true>();
Mathieu Chartier61c5ebc2014-06-05 17:42:53 -07001883 }
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08001884 if (!field_type->IsAssignableFrom(v->GetClass())) {
1885 return JDWP::ERR_INVALID_OBJECT;
1886 }
1887 }
Sebastien Hertzd2fe10a2014-01-15 10:20:56 +01001888 // Debugging can't use transactional mode (runtime only).
1889 f->SetObject<false>(o, v);
Elliott Hughesaed4be92011-12-02 16:16:23 -08001890 }
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -08001891
1892 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001893}
1894
Elliott Hughes88d63092013-01-09 09:55:54 -08001895JDWP::JdwpError Dbg::SetFieldValue(JDWP::ObjectId object_id, JDWP::FieldId field_id, uint64_t value,
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001896 int width) {
Elliott Hughes88d63092013-01-09 09:55:54 -08001897 return SetFieldValueImpl(object_id, field_id, value, width, false);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001898}
1899
Elliott Hughes88d63092013-01-09 09:55:54 -08001900JDWP::JdwpError Dbg::SetStaticFieldValue(JDWP::FieldId field_id, uint64_t value, int width) {
1901 return SetFieldValueImpl(0, field_id, value, width, true);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001902}
1903
Sebastien Hertzb0b0b492014-09-15 11:27:27 +02001904JDWP::JdwpError Dbg::StringToUtf8(JDWP::ObjectId string_id, std::string* str) {
Ian Rogersc0542af2014-09-03 16:16:56 -07001905 JDWP::JdwpError error;
Sebastien Hertzb0b0b492014-09-15 11:27:27 +02001906 mirror::Object* obj = gRegistry->Get<mirror::Object*>(string_id, &error);
1907 if (error != JDWP::ERR_NONE) {
1908 return error;
1909 }
1910 if (obj == nullptr) {
1911 return JDWP::ERR_INVALID_OBJECT;
1912 }
1913 {
1914 ScopedObjectAccessUnchecked soa(Thread::Current());
1915 mirror::Class* java_lang_String = soa.Decode<mirror::Class*>(WellKnownClasses::java_lang_String);
1916 if (!java_lang_String->IsAssignableFrom(obj->GetClass())) {
1917 // This isn't a string.
1918 return JDWP::ERR_INVALID_STRING;
1919 }
1920 }
1921 *str = obj->AsString()->ToModifiedUtf8();
1922 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001923}
1924
Jeff Hao579b0242013-11-18 13:16:49 -08001925void Dbg::OutputJValue(JDWP::JdwpTag tag, const JValue* return_value, JDWP::ExpandBuf* pReply) {
1926 if (IsPrimitiveTag(tag)) {
1927 expandBufAdd1(pReply, tag);
1928 if (tag == JDWP::JT_BOOLEAN || tag == JDWP::JT_BYTE) {
1929 expandBufAdd1(pReply, return_value->GetI());
1930 } else if (tag == JDWP::JT_CHAR || tag == JDWP::JT_SHORT) {
1931 expandBufAdd2BE(pReply, return_value->GetI());
1932 } else if (tag == JDWP::JT_FLOAT || tag == JDWP::JT_INT) {
1933 expandBufAdd4BE(pReply, return_value->GetI());
1934 } else if (tag == JDWP::JT_DOUBLE || tag == JDWP::JT_LONG) {
1935 expandBufAdd8BE(pReply, return_value->GetJ());
1936 } else {
1937 CHECK_EQ(tag, JDWP::JT_VOID);
1938 }
1939 } else {
Ian Rogers98379392014-02-24 16:53:16 -08001940 ScopedObjectAccessUnchecked soa(Thread::Current());
Jeff Hao579b0242013-11-18 13:16:49 -08001941 mirror::Object* value = return_value->GetL();
Ian Rogers98379392014-02-24 16:53:16 -08001942 expandBufAdd1(pReply, TagFromObject(soa, value));
Jeff Hao579b0242013-11-18 13:16:49 -08001943 expandBufAddObjectId(pReply, gRegistry->Add(value));
1944 }
1945}
1946
Ian Rogersc0542af2014-09-03 16:16:56 -07001947JDWP::JdwpError Dbg::GetThreadName(JDWP::ObjectId thread_id, std::string* name) {
jeffhaoa77f0f62012-12-05 17:19:31 -08001948 ScopedObjectAccessUnchecked soa(Thread::Current());
Ian Rogersc0542af2014-09-03 16:16:56 -07001949 JDWP::JdwpError error;
1950 Thread* thread = DecodeThread(soa, thread_id, &error);
1951 UNUSED(thread);
Elliott Hughes221229c2013-01-08 18:17:50 -08001952 if (error != JDWP::ERR_NONE && error != JDWP::ERR_THREAD_NOT_ALIVE) {
1953 return error;
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001954 }
Elliott Hughes221229c2013-01-08 18:17:50 -08001955
1956 // We still need to report the zombie threads' names, so we can't just call Thread::GetThreadName.
Ian Rogersc0542af2014-09-03 16:16:56 -07001957 mirror::Object* thread_object = gRegistry->Get<mirror::Object*>(thread_id, &error);
1958 CHECK(thread_object != nullptr) << error;
Mathieu Chartierc7853442015-03-27 14:35:38 -07001959 ArtField* java_lang_Thread_name_field =
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001960 soa.DecodeField(WellKnownClasses::java_lang_Thread_name);
1961 mirror::String* s =
1962 reinterpret_cast<mirror::String*>(java_lang_Thread_name_field->GetObject(thread_object));
Ian Rogersc0542af2014-09-03 16:16:56 -07001963 if (s != nullptr) {
1964 *name = s->ToModifiedUtf8();
Elliott Hughes221229c2013-01-08 18:17:50 -08001965 }
1966 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001967}
1968
Elliott Hughes221229c2013-01-08 18:17:50 -08001969JDWP::JdwpError Dbg::GetThreadGroup(JDWP::ObjectId thread_id, JDWP::ExpandBuf* pReply) {
Sebastien Hertza06430c2014-09-15 19:21:30 +02001970 ScopedObjectAccessUnchecked soa(Thread::Current());
Ian Rogersc0542af2014-09-03 16:16:56 -07001971 JDWP::JdwpError error;
1972 mirror::Object* thread_object = gRegistry->Get<mirror::Object*>(thread_id, &error);
1973 if (error != JDWP::ERR_NONE) {
Elliott Hughes2435a572012-02-17 16:07:41 -08001974 return JDWP::ERR_INVALID_OBJECT;
1975 }
Mathieu Chartier2d5f39e2014-09-19 17:52:37 -07001976 ScopedAssertNoThreadSuspension ants(soa.Self(), "Debugger: GetThreadGroup");
Elliott Hughes2435a572012-02-17 16:07:41 -08001977 // Okay, so it's an object, but is it actually a thread?
Sebastien Hertz69206392015-04-07 15:54:25 +02001978 Thread* thread = DecodeThread(soa, thread_id, &error);
1979 UNUSED(thread);
Elliott Hughes221229c2013-01-08 18:17:50 -08001980 if (error == JDWP::ERR_THREAD_NOT_ALIVE) {
1981 // Zombie threads are in the null group.
1982 expandBufAddObjectId(pReply, JDWP::ObjectId(0));
Sebastien Hertz52d131d2014-03-13 16:17:40 +01001983 error = JDWP::ERR_NONE;
1984 } else if (error == JDWP::ERR_NONE) {
1985 mirror::Class* c = soa.Decode<mirror::Class*>(WellKnownClasses::java_lang_Thread);
1986 CHECK(c != nullptr);
Mathieu Chartierc7853442015-03-27 14:35:38 -07001987 ArtField* f = soa.DecodeField(WellKnownClasses::java_lang_Thread_group);
Hiroshi Yamauchib5a9e3d2014-06-09 12:11:20 -07001988 CHECK(f != nullptr);
Sebastien Hertz52d131d2014-03-13 16:17:40 +01001989 mirror::Object* group = f->GetObject(thread_object);
Hiroshi Yamauchib5a9e3d2014-06-09 12:11:20 -07001990 CHECK(group != nullptr);
Sebastien Hertz52d131d2014-03-13 16:17:40 +01001991 JDWP::ObjectId thread_group_id = gRegistry->Add(group);
1992 expandBufAddObjectId(pReply, thread_group_id);
Elliott Hughes221229c2013-01-08 18:17:50 -08001993 }
Sebastien Hertz52d131d2014-03-13 16:17:40 +01001994 return error;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001995}
1996
Sebastien Hertza06430c2014-09-15 19:21:30 +02001997static mirror::Object* DecodeThreadGroup(ScopedObjectAccessUnchecked& soa,
1998 JDWP::ObjectId thread_group_id, JDWP::JdwpError* error)
1999 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Sebastien Hertz6995c602014-09-09 12:10:13 +02002000 mirror::Object* thread_group = Dbg::GetObjectRegistry()->Get<mirror::Object*>(thread_group_id,
2001 error);
Sebastien Hertza06430c2014-09-15 19:21:30 +02002002 if (*error != JDWP::ERR_NONE) {
2003 return nullptr;
2004 }
2005 if (thread_group == nullptr) {
2006 *error = JDWP::ERR_INVALID_OBJECT;
2007 return nullptr;
2008 }
Ian Rogers98379392014-02-24 16:53:16 -08002009 mirror::Class* c = soa.Decode<mirror::Class*>(WellKnownClasses::java_lang_ThreadGroup);
2010 CHECK(c != nullptr);
Sebastien Hertza06430c2014-09-15 19:21:30 +02002011 if (!c->IsAssignableFrom(thread_group->GetClass())) {
2012 // This is not a java.lang.ThreadGroup.
2013 *error = JDWP::ERR_INVALID_THREAD_GROUP;
2014 return nullptr;
2015 }
2016 *error = JDWP::ERR_NONE;
2017 return thread_group;
2018}
2019
2020JDWP::JdwpError Dbg::GetThreadGroupName(JDWP::ObjectId thread_group_id, JDWP::ExpandBuf* pReply) {
2021 ScopedObjectAccessUnchecked soa(Thread::Current());
2022 JDWP::JdwpError error;
2023 mirror::Object* thread_group = DecodeThreadGroup(soa, thread_group_id, &error);
2024 if (error != JDWP::ERR_NONE) {
2025 return error;
2026 }
Mathieu Chartier2d5f39e2014-09-19 17:52:37 -07002027 ScopedAssertNoThreadSuspension ants(soa.Self(), "Debugger: GetThreadGroupName");
Mathieu Chartierc7853442015-03-27 14:35:38 -07002028 ArtField* f = soa.DecodeField(WellKnownClasses::java_lang_ThreadGroup_name);
Ian Rogersc0542af2014-09-03 16:16:56 -07002029 CHECK(f != nullptr);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002030 mirror::String* s = reinterpret_cast<mirror::String*>(f->GetObject(thread_group));
Sebastien Hertza06430c2014-09-15 19:21:30 +02002031
2032 std::string thread_group_name(s->ToModifiedUtf8());
2033 expandBufAddUtf8String(pReply, thread_group_name);
2034 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002035}
2036
Sebastien Hertza06430c2014-09-15 19:21:30 +02002037JDWP::JdwpError Dbg::GetThreadGroupParent(JDWP::ObjectId thread_group_id, JDWP::ExpandBuf* pReply) {
Ian Rogers98379392014-02-24 16:53:16 -08002038 ScopedObjectAccessUnchecked soa(Thread::Current());
Ian Rogersc0542af2014-09-03 16:16:56 -07002039 JDWP::JdwpError error;
Sebastien Hertza06430c2014-09-15 19:21:30 +02002040 mirror::Object* thread_group = DecodeThreadGroup(soa, thread_group_id, &error);
2041 if (error != JDWP::ERR_NONE) {
2042 return error;
2043 }
Mathieu Chartier2d5f39e2014-09-19 17:52:37 -07002044 mirror::Object* parent;
2045 {
2046 ScopedAssertNoThreadSuspension ants(soa.Self(), "Debugger: GetThreadGroupParent");
Mathieu Chartierc7853442015-03-27 14:35:38 -07002047 ArtField* f = soa.DecodeField(WellKnownClasses::java_lang_ThreadGroup_parent);
Mathieu Chartier2d5f39e2014-09-19 17:52:37 -07002048 CHECK(f != nullptr);
2049 parent = f->GetObject(thread_group);
2050 }
Sebastien Hertza06430c2014-09-15 19:21:30 +02002051 JDWP::ObjectId parent_group_id = gRegistry->Add(parent);
2052 expandBufAddObjectId(pReply, parent_group_id);
2053 return JDWP::ERR_NONE;
2054}
2055
2056static void GetChildThreadGroups(ScopedObjectAccessUnchecked& soa, mirror::Object* thread_group,
2057 std::vector<JDWP::ObjectId>* child_thread_group_ids)
2058 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
2059 CHECK(thread_group != nullptr);
2060
2061 // Get the ArrayList<ThreadGroup> "groups" out of this thread group...
Mathieu Chartierc7853442015-03-27 14:35:38 -07002062 ArtField* groups_field = soa.DecodeField(WellKnownClasses::java_lang_ThreadGroup_groups);
Sebastien Hertza06430c2014-09-15 19:21:30 +02002063 mirror::Object* groups_array_list = groups_field->GetObject(thread_group);
Sebastien Hertze49e1952014-10-13 11:27:13 +02002064 {
2065 // The "groups" field is declared as a java.util.List: check it really is
2066 // an instance of java.util.ArrayList.
2067 CHECK(groups_array_list != nullptr);
2068 mirror::Class* java_util_ArrayList_class =
2069 soa.Decode<mirror::Class*>(WellKnownClasses::java_util_ArrayList);
2070 CHECK(groups_array_list->InstanceOf(java_util_ArrayList_class));
2071 }
Sebastien Hertza06430c2014-09-15 19:21:30 +02002072
2073 // Get the array and size out of the ArrayList<ThreadGroup>...
Mathieu Chartierc7853442015-03-27 14:35:38 -07002074 ArtField* array_field = soa.DecodeField(WellKnownClasses::java_util_ArrayList_array);
2075 ArtField* size_field = soa.DecodeField(WellKnownClasses::java_util_ArrayList_size);
Sebastien Hertza06430c2014-09-15 19:21:30 +02002076 mirror::ObjectArray<mirror::Object>* groups_array =
2077 array_field->GetObject(groups_array_list)->AsObjectArray<mirror::Object>();
2078 const int32_t size = size_field->GetInt(groups_array_list);
2079
2080 // Copy the first 'size' elements out of the array into the result.
Sebastien Hertz6995c602014-09-09 12:10:13 +02002081 ObjectRegistry* registry = Dbg::GetObjectRegistry();
Sebastien Hertza06430c2014-09-15 19:21:30 +02002082 for (int32_t i = 0; i < size; ++i) {
Sebastien Hertz6995c602014-09-09 12:10:13 +02002083 child_thread_group_ids->push_back(registry->Add(groups_array->Get(i)));
Sebastien Hertza06430c2014-09-15 19:21:30 +02002084 }
2085}
2086
2087JDWP::JdwpError Dbg::GetThreadGroupChildren(JDWP::ObjectId thread_group_id,
2088 JDWP::ExpandBuf* pReply) {
2089 ScopedObjectAccessUnchecked soa(Thread::Current());
2090 JDWP::JdwpError error;
2091 mirror::Object* thread_group = DecodeThreadGroup(soa, thread_group_id, &error);
2092 if (error != JDWP::ERR_NONE) {
2093 return error;
2094 }
2095
2096 // Add child threads.
2097 {
2098 std::vector<JDWP::ObjectId> child_thread_ids;
2099 GetThreads(thread_group, &child_thread_ids);
2100 expandBufAdd4BE(pReply, child_thread_ids.size());
2101 for (JDWP::ObjectId child_thread_id : child_thread_ids) {
2102 expandBufAddObjectId(pReply, child_thread_id);
2103 }
2104 }
2105
2106 // Add child thread groups.
2107 {
2108 std::vector<JDWP::ObjectId> child_thread_groups_ids;
2109 GetChildThreadGroups(soa, thread_group, &child_thread_groups_ids);
2110 expandBufAdd4BE(pReply, child_thread_groups_ids.size());
2111 for (JDWP::ObjectId child_thread_group_id : child_thread_groups_ids) {
2112 expandBufAddObjectId(pReply, child_thread_group_id);
2113 }
2114 }
2115
2116 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002117}
2118
2119JDWP::ObjectId Dbg::GetSystemThreadGroupId() {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002120 ScopedObjectAccessUnchecked soa(Thread::Current());
Mathieu Chartierc7853442015-03-27 14:35:38 -07002121 ArtField* f = soa.DecodeField(WellKnownClasses::java_lang_ThreadGroup_systemThreadGroup);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002122 mirror::Object* group = f->GetObject(f->GetDeclaringClass());
Ian Rogers365c1022012-06-22 15:05:28 -07002123 return gRegistry->Add(group);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002124}
2125
Jeff Hao920af3e2013-08-28 15:46:38 -07002126JDWP::JdwpThreadStatus Dbg::ToJdwpThreadStatus(ThreadState state) {
2127 switch (state) {
2128 case kBlocked:
2129 return JDWP::TS_MONITOR;
2130 case kNative:
2131 case kRunnable:
2132 case kSuspended:
2133 return JDWP::TS_RUNNING;
2134 case kSleeping:
2135 return JDWP::TS_SLEEPING;
2136 case kStarting:
2137 case kTerminated:
2138 return JDWP::TS_ZOMBIE;
2139 case kTimedWaiting:
Sebastien Hertzbae182c2013-12-17 10:42:03 +01002140 case kWaitingForCheckPointsToRun:
Jeff Hao920af3e2013-08-28 15:46:38 -07002141 case kWaitingForDebuggerSend:
2142 case kWaitingForDebuggerSuspension:
2143 case kWaitingForDebuggerToAttach:
Sebastien Hertz138dbfc2013-12-04 18:15:25 +01002144 case kWaitingForDeoptimization:
Jeff Hao920af3e2013-08-28 15:46:38 -07002145 case kWaitingForGcToComplete:
Jeff Hao920af3e2013-08-28 15:46:38 -07002146 case kWaitingForJniOnLoad:
Sebastien Hertzbae182c2013-12-17 10:42:03 +01002147 case kWaitingForMethodTracingStart:
Jeff Hao920af3e2013-08-28 15:46:38 -07002148 case kWaitingForSignalCatcherOutput:
Hiroshi Yamauchi0c8c3032015-01-16 16:54:35 -08002149 case kWaitingForVisitObjects:
Jeff Hao920af3e2013-08-28 15:46:38 -07002150 case kWaitingInMainDebuggerLoop:
2151 case kWaitingInMainSignalCatcherLoop:
2152 case kWaitingPerformingGc:
2153 case kWaiting:
2154 return JDWP::TS_WAIT;
2155 // Don't add a 'default' here so the compiler can spot incompatible enum changes.
2156 }
2157 LOG(FATAL) << "Unknown thread state: " << state;
2158 return JDWP::TS_ZOMBIE;
2159}
2160
Sebastien Hertz52d131d2014-03-13 16:17:40 +01002161JDWP::JdwpError Dbg::GetThreadStatus(JDWP::ObjectId thread_id, JDWP::JdwpThreadStatus* pThreadStatus,
2162 JDWP::JdwpSuspendStatus* pSuspendStatus) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002163 ScopedObjectAccess soa(Thread::Current());
Elliott Hughes499c5132011-11-17 14:55:11 -08002164
Elliott Hughes9e0c1752013-01-09 14:02:58 -08002165 *pSuspendStatus = JDWP::SUSPEND_STATUS_NOT_SUSPENDED;
2166
Ian Rogersc0542af2014-09-03 16:16:56 -07002167 JDWP::JdwpError error;
2168 Thread* thread = DecodeThread(soa, thread_id, &error);
Elliott Hughes221229c2013-01-08 18:17:50 -08002169 if (error != JDWP::ERR_NONE) {
2170 if (error == JDWP::ERR_THREAD_NOT_ALIVE) {
2171 *pThreadStatus = JDWP::TS_ZOMBIE;
Elliott Hughes221229c2013-01-08 18:17:50 -08002172 return JDWP::ERR_NONE;
2173 }
2174 return error;
Elliott Hughes499c5132011-11-17 14:55:11 -08002175 }
2176
Elliott Hughes9e0c1752013-01-09 14:02:58 -08002177 if (IsSuspendedForDebugger(soa, thread)) {
2178 *pSuspendStatus = JDWP::SUSPEND_STATUS_SUSPENDED;
Elliott Hughes499c5132011-11-17 14:55:11 -08002179 }
2180
Jeff Hao920af3e2013-08-28 15:46:38 -07002181 *pThreadStatus = ToJdwpThreadStatus(thread->GetState());
Elliott Hughes221229c2013-01-08 18:17:50 -08002182 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002183}
2184
Elliott Hughes221229c2013-01-08 18:17:50 -08002185JDWP::JdwpError Dbg::GetThreadDebugSuspendCount(JDWP::ObjectId thread_id, JDWP::ExpandBuf* pReply) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002186 ScopedObjectAccess soa(Thread::Current());
Ian Rogersc0542af2014-09-03 16:16:56 -07002187 JDWP::JdwpError error;
2188 Thread* thread = DecodeThread(soa, thread_id, &error);
Elliott Hughes221229c2013-01-08 18:17:50 -08002189 if (error != JDWP::ERR_NONE) {
2190 return error;
Elliott Hughes2435a572012-02-17 16:07:41 -08002191 }
Ian Rogers50b35e22012-10-04 10:09:15 -07002192 MutexLock mu2(soa.Self(), *Locks::thread_suspend_count_lock_);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002193 expandBufAdd4BE(pReply, thread->GetDebugSuspendCount());
Elliott Hughes2435a572012-02-17 16:07:41 -08002194 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002195}
2196
Elliott Hughesf9501702013-01-11 11:22:27 -08002197JDWP::JdwpError Dbg::Interrupt(JDWP::ObjectId thread_id) {
2198 ScopedObjectAccess soa(Thread::Current());
Ian Rogersc0542af2014-09-03 16:16:56 -07002199 JDWP::JdwpError error;
2200 Thread* thread = DecodeThread(soa, thread_id, &error);
Elliott Hughesf9501702013-01-11 11:22:27 -08002201 if (error != JDWP::ERR_NONE) {
2202 return error;
2203 }
Ian Rogersdd7624d2014-03-14 17:43:00 -07002204 thread->Interrupt(soa.Self());
Elliott Hughesf9501702013-01-11 11:22:27 -08002205 return JDWP::ERR_NONE;
2206}
2207
Sebastien Hertz070f7322014-09-09 12:08:49 +02002208static bool IsInDesiredThreadGroup(ScopedObjectAccessUnchecked& soa,
2209 mirror::Object* desired_thread_group, mirror::Object* peer)
2210 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
2211 // Do we want threads from all thread groups?
2212 if (desired_thread_group == nullptr) {
2213 return true;
2214 }
Mathieu Chartierc7853442015-03-27 14:35:38 -07002215 ArtField* thread_group_field = soa.DecodeField(WellKnownClasses::java_lang_Thread_group);
Sebastien Hertz070f7322014-09-09 12:08:49 +02002216 DCHECK(thread_group_field != nullptr);
2217 mirror::Object* group = thread_group_field->GetObject(peer);
2218 return (group == desired_thread_group);
2219}
2220
Sebastien Hertza06430c2014-09-15 19:21:30 +02002221void Dbg::GetThreads(mirror::Object* thread_group, std::vector<JDWP::ObjectId>* thread_ids) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002222 ScopedObjectAccessUnchecked soa(Thread::Current());
Sebastien Hertz070f7322014-09-09 12:08:49 +02002223 std::list<Thread*> all_threads_list;
2224 {
2225 MutexLock mu(Thread::Current(), *Locks::thread_list_lock_);
2226 all_threads_list = Runtime::Current()->GetThreadList()->GetList();
2227 }
2228 for (Thread* t : all_threads_list) {
2229 if (t == Dbg::GetDebugThread()) {
2230 // Skip the JDWP thread. Some debuggers get bent out of shape when they can't suspend and
2231 // query all threads, so it's easier if we just don't tell them about this thread.
2232 continue;
2233 }
2234 if (t->IsStillStarting()) {
2235 // This thread is being started (and has been registered in the thread list). However, it is
2236 // not completely started yet so we must ignore it.
2237 continue;
2238 }
2239 mirror::Object* peer = t->GetPeer();
2240 if (peer == nullptr) {
Mathieu Chartier2cebb242015-04-21 16:50:40 -07002241 // 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 +02002242 // this thread yet.
2243 // TODO: if we identified threads to the debugger by their Thread*
2244 // rather than their peer's mirror::Object*, we could fix this.
2245 // Doing so might help us report ZOMBIE threads too.
2246 continue;
2247 }
2248 if (IsInDesiredThreadGroup(soa, thread_group, peer)) {
2249 thread_ids->push_back(gRegistry->Add(peer));
2250 }
2251 }
Elliott Hughescaf76542012-06-28 16:08:22 -07002252}
Elliott Hughesa2155262011-11-16 16:26:58 -08002253
Ian Rogersc0542af2014-09-03 16:16:56 -07002254static int GetStackDepth(Thread* thread) SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Ian Rogers0399dde2012-06-06 17:09:28 -07002255 struct CountStackDepthVisitor : public StackVisitor {
Andreas Gampe277ccbd2014-11-03 21:36:10 -08002256 explicit CountStackDepthVisitor(Thread* thread_in)
Nicolas Geoffray8e5bd182015-05-06 11:34:34 +01002257 : StackVisitor(thread_in, nullptr, StackVisitor::StackWalkKind::kIncludeInlinedFrames),
2258 depth(0) {}
Ian Rogers0399dde2012-06-06 17:09:28 -07002259
Elliott Hughes64f574f2013-02-20 14:57:12 -08002260 // TODO: Enable annotalysis. We know lock is held in constructor, but abstraction confuses
2261 // annotalysis.
2262 bool VisitFrame() NO_THREAD_SAFETY_ANALYSIS {
Ian Rogers0399dde2012-06-06 17:09:28 -07002263 if (!GetMethod()->IsRuntimeMethod()) {
Elliott Hughesf8a2df72011-12-01 12:19:54 -08002264 ++depth;
2265 }
Elliott Hughes530fa002012-03-12 11:44:49 -07002266 return true;
Elliott Hughesa2e54f62011-11-17 13:01:30 -08002267 }
2268 size_t depth;
2269 };
Elliott Hughes08fc03a2012-06-26 17:34:00 -07002270
Ian Rogers7a22fa62013-01-23 12:16:16 -08002271 CountStackDepthVisitor visitor(thread);
Ian Rogers0399dde2012-06-06 17:09:28 -07002272 visitor.WalkStack();
Elliott Hughesa2e54f62011-11-17 13:01:30 -08002273 return visitor.depth;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002274}
2275
Ian Rogersc0542af2014-09-03 16:16:56 -07002276JDWP::JdwpError Dbg::GetThreadFrameCount(JDWP::ObjectId thread_id, size_t* result) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002277 ScopedObjectAccess soa(Thread::Current());
Ian Rogersc0542af2014-09-03 16:16:56 -07002278 JDWP::JdwpError error;
2279 *result = 0;
2280 Thread* thread = DecodeThread(soa, thread_id, &error);
Elliott Hughes221229c2013-01-08 18:17:50 -08002281 if (error != JDWP::ERR_NONE) {
2282 return error;
2283 }
Elliott Hughesf15f4a02013-01-09 10:09:38 -08002284 if (!IsSuspendedForDebugger(soa, thread)) {
2285 return JDWP::ERR_THREAD_NOT_SUSPENDED;
2286 }
Ian Rogersc0542af2014-09-03 16:16:56 -07002287 *result = GetStackDepth(thread);
Elliott Hughes221229c2013-01-08 18:17:50 -08002288 return JDWP::ERR_NONE;
Elliott Hughes86964332012-02-15 19:37:42 -08002289}
2290
Ian Rogers306057f2012-11-26 12:45:53 -08002291JDWP::JdwpError Dbg::GetThreadFrames(JDWP::ObjectId thread_id, size_t start_frame,
2292 size_t frame_count, JDWP::ExpandBuf* buf) {
Elliott Hughes6e9d22c2012-06-22 15:02:37 -07002293 class GetFrameVisitor : public StackVisitor {
2294 public:
Andreas Gampe277ccbd2014-11-03 21:36:10 -08002295 GetFrameVisitor(Thread* thread, size_t start_frame_in, size_t frame_count_in,
2296 JDWP::ExpandBuf* buf_in)
Ian Rogersb726dcb2012-09-05 08:57:23 -07002297 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_)
Nicolas Geoffray8e5bd182015-05-06 11:34:34 +01002298 : StackVisitor(thread, nullptr, StackVisitor::StackWalkKind::kIncludeInlinedFrames),
2299 depth_(0),
2300 start_frame_(start_frame_in),
2301 frame_count_(frame_count_in),
2302 buf_(buf_in) {
Elliott Hughes6e9d22c2012-06-22 15:02:37 -07002303 expandBufAdd4BE(buf_, frame_count_);
Elliott Hughes03181a82011-11-17 17:22:21 -08002304 }
Ian Rogers0399dde2012-06-06 17:09:28 -07002305
Sebastien Hertz69206392015-04-07 15:54:25 +02002306 bool VisitFrame() OVERRIDE SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Ian Rogers0399dde2012-06-06 17:09:28 -07002307 if (GetMethod()->IsRuntimeMethod()) {
Brian Carlstrom7934ac22013-07-26 10:54:15 -07002308 return true; // The debugger can't do anything useful with a frame that has no Method*.
Elliott Hughes03181a82011-11-17 17:22:21 -08002309 }
Elliott Hughes6e9d22c2012-06-22 15:02:37 -07002310 if (depth_ >= start_frame_ + frame_count_) {
Elliott Hughes530fa002012-03-12 11:44:49 -07002311 return false;
Elliott Hughes03181a82011-11-17 17:22:21 -08002312 }
Elliott Hughes6e9d22c2012-06-22 15:02:37 -07002313 if (depth_ >= start_frame_) {
2314 JDWP::FrameId frame_id(GetFrameId());
2315 JDWP::JdwpLocation location;
Sebastien Hertz6995c602014-09-09 12:10:13 +02002316 SetJdwpLocation(&location, GetMethod(), GetDexPc());
Ian Rogersef7d42f2014-01-06 12:55:46 -08002317 VLOG(jdwp) << StringPrintf(" Frame %3zd: id=%3" PRIu64 " ", depth_, frame_id) << location;
Elliott Hughes6e9d22c2012-06-22 15:02:37 -07002318 expandBufAdd8BE(buf_, frame_id);
2319 expandBufAddLocation(buf_, location);
2320 }
2321 ++depth_;
Elliott Hughes530fa002012-03-12 11:44:49 -07002322 return true;
Elliott Hughes03181a82011-11-17 17:22:21 -08002323 }
Elliott Hughes6e9d22c2012-06-22 15:02:37 -07002324
2325 private:
2326 size_t depth_;
2327 const size_t start_frame_;
2328 const size_t frame_count_;
2329 JDWP::ExpandBuf* buf_;
Elliott Hughes03181a82011-11-17 17:22:21 -08002330 };
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002331
2332 ScopedObjectAccessUnchecked soa(Thread::Current());
Ian Rogersc0542af2014-09-03 16:16:56 -07002333 JDWP::JdwpError error;
2334 Thread* thread = DecodeThread(soa, thread_id, &error);
Elliott Hughes221229c2013-01-08 18:17:50 -08002335 if (error != JDWP::ERR_NONE) {
2336 return error;
2337 }
Elliott Hughesf15f4a02013-01-09 10:09:38 -08002338 if (!IsSuspendedForDebugger(soa, thread)) {
2339 return JDWP::ERR_THREAD_NOT_SUSPENDED;
2340 }
Ian Rogers7a22fa62013-01-23 12:16:16 -08002341 GetFrameVisitor visitor(thread, start_frame, frame_count, buf);
Ian Rogers0399dde2012-06-06 17:09:28 -07002342 visitor.WalkStack();
Elliott Hughes6e9d22c2012-06-22 15:02:37 -07002343 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002344}
2345
2346JDWP::ObjectId Dbg::GetThreadSelfId() {
Sebastien Hertz6995c602014-09-09 12:10:13 +02002347 return GetThreadId(Thread::Current());
2348}
2349
2350JDWP::ObjectId Dbg::GetThreadId(Thread* thread) {
Mathieu Chartierdbe6f462012-09-25 16:54:50 -07002351 ScopedObjectAccessUnchecked soa(Thread::Current());
Sebastien Hertz6995c602014-09-09 12:10:13 +02002352 return gRegistry->Add(thread->GetPeer());
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002353}
2354
Elliott Hughes475fc232011-10-25 15:00:35 -07002355void Dbg::SuspendVM() {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002356 Runtime::Current()->GetThreadList()->SuspendAllForDebugger();
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002357}
2358
2359void Dbg::ResumeVM() {
Sebastien Hertz253fa552014-10-14 17:27:15 +02002360 Runtime::Current()->GetThreadList()->ResumeAllForDebugger();
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002361}
2362
Elliott Hughes221229c2013-01-08 18:17:50 -08002363JDWP::JdwpError Dbg::SuspendThread(JDWP::ObjectId thread_id, bool request_suspension) {
Ian Rogersf3d874c2014-07-17 18:52:42 -07002364 Thread* self = Thread::Current();
Ian Rogersc0542af2014-09-03 16:16:56 -07002365 ScopedLocalRef<jobject> peer(self->GetJniEnv(), nullptr);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002366 {
Ian Rogersf3d874c2014-07-17 18:52:42 -07002367 ScopedObjectAccess soa(self);
Ian Rogersc0542af2014-09-03 16:16:56 -07002368 JDWP::JdwpError error;
2369 peer.reset(soa.AddLocalReference<jobject>(gRegistry->Get<mirror::Object*>(thread_id, &error)));
Elliott Hughes4e235312011-12-02 11:34:15 -08002370 }
Ian Rogersc0542af2014-09-03 16:16:56 -07002371 if (peer.get() == nullptr) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002372 return JDWP::ERR_THREAD_NOT_ALIVE;
2373 }
Ian Rogers4ad5cd32014-11-11 23:08:07 -08002374 // Suspend thread to build stack trace.
Elliott Hughesf327e072013-01-09 16:01:26 -08002375 bool timed_out;
Brian Carlstromba32de42014-08-27 23:43:46 -07002376 ThreadList* thread_list = Runtime::Current()->GetThreadList();
2377 Thread* thread = thread_list->SuspendThreadByPeer(peer.get(), request_suspension, true,
2378 &timed_out);
Ian Rogersc0542af2014-09-03 16:16:56 -07002379 if (thread != nullptr) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002380 return JDWP::ERR_NONE;
Elliott Hughesf327e072013-01-09 16:01:26 -08002381 } else if (timed_out) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002382 return JDWP::ERR_INTERNAL;
2383 } else {
2384 return JDWP::ERR_THREAD_NOT_ALIVE;
2385 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002386}
2387
Elliott Hughes221229c2013-01-08 18:17:50 -08002388void Dbg::ResumeThread(JDWP::ObjectId thread_id) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002389 ScopedObjectAccessUnchecked soa(Thread::Current());
Ian Rogersc0542af2014-09-03 16:16:56 -07002390 JDWP::JdwpError error;
2391 mirror::Object* peer = gRegistry->Get<mirror::Object*>(thread_id, &error);
2392 CHECK(peer != nullptr) << error;
jeffhaoa77f0f62012-12-05 17:19:31 -08002393 Thread* thread;
2394 {
2395 MutexLock mu(soa.Self(), *Locks::thread_list_lock_);
2396 thread = Thread::FromManagedThread(soa, peer);
2397 }
Ian Rogersc0542af2014-09-03 16:16:56 -07002398 if (thread == nullptr) {
Elliott Hughes4e235312011-12-02 11:34:15 -08002399 LOG(WARNING) << "No such thread for resume: " << peer;
2400 return;
2401 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002402 bool needs_resume;
2403 {
Ian Rogers50b35e22012-10-04 10:09:15 -07002404 MutexLock mu2(soa.Self(), *Locks::thread_suspend_count_lock_);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002405 needs_resume = thread->GetSuspendCount() > 0;
2406 }
2407 if (needs_resume) {
Elliott Hughes546b9862012-06-20 16:06:13 -07002408 Runtime::Current()->GetThreadList()->Resume(thread, true);
2409 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002410}
2411
2412void Dbg::SuspendSelf() {
Elliott Hughes475fc232011-10-25 15:00:35 -07002413 Runtime::Current()->GetThreadList()->SuspendSelfForDebugger();
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002414}
2415
Ian Rogers0399dde2012-06-06 17:09:28 -07002416struct GetThisVisitor : public StackVisitor {
Andreas Gampe277ccbd2014-11-03 21:36:10 -08002417 GetThisVisitor(Thread* thread, Context* context, JDWP::FrameId frame_id_in)
Ian Rogersb726dcb2012-09-05 08:57:23 -07002418 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_)
Nicolas Geoffray8e5bd182015-05-06 11:34:34 +01002419 : StackVisitor(thread, context, StackVisitor::StackWalkKind::kIncludeInlinedFrames),
2420 this_object(nullptr),
2421 frame_id(frame_id_in) {}
Ian Rogers0399dde2012-06-06 17:09:28 -07002422
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002423 // TODO: Enable annotalysis. We know lock is held in constructor, but abstraction confuses
2424 // annotalysis.
2425 virtual bool VisitFrame() NO_THREAD_SAFETY_ANALYSIS {
Elliott Hughes6e9d22c2012-06-22 15:02:37 -07002426 if (frame_id != GetFrameId()) {
Ian Rogers0399dde2012-06-06 17:09:28 -07002427 return true; // continue
Ian Rogers0399dde2012-06-06 17:09:28 -07002428 } else {
Ian Rogers62d6c772013-02-27 08:32:07 -08002429 this_object = GetThisObject();
2430 return false;
Ian Rogers0399dde2012-06-06 17:09:28 -07002431 }
Elliott Hughes86b00102011-12-05 17:54:26 -08002432 }
Ian Rogers0399dde2012-06-06 17:09:28 -07002433
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002434 mirror::Object* this_object;
Elliott Hughes6e9d22c2012-06-22 15:02:37 -07002435 JDWP::FrameId frame_id;
Ian Rogers0399dde2012-06-06 17:09:28 -07002436};
2437
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002438JDWP::JdwpError Dbg::GetThisObject(JDWP::ObjectId thread_id, JDWP::FrameId frame_id,
2439 JDWP::ObjectId* result) {
2440 ScopedObjectAccessUnchecked soa(Thread::Current());
Sebastien Hertz69206392015-04-07 15:54:25 +02002441 JDWP::JdwpError error;
2442 Thread* thread = DecodeThread(soa, thread_id, &error);
2443 if (error != JDWP::ERR_NONE) {
2444 return error;
2445 }
2446 if (!IsSuspendedForDebugger(soa, thread)) {
2447 return JDWP::ERR_THREAD_NOT_SUSPENDED;
Elliott Hughes6e9d22c2012-06-22 15:02:37 -07002448 }
Ian Rogers700a4022014-05-19 16:49:03 -07002449 std::unique_ptr<Context> context(Context::Create());
Ian Rogers7a22fa62013-01-23 12:16:16 -08002450 GetThisVisitor visitor(thread, context.get(), frame_id);
Ian Rogers0399dde2012-06-06 17:09:28 -07002451 visitor.WalkStack();
Elliott Hughes6e9d22c2012-06-22 15:02:37 -07002452 *result = gRegistry->Add(visitor.this_object);
2453 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002454}
2455
Sebastien Hertz8009f392014-09-01 17:07:11 +02002456// Walks the stack until we find the frame with the given FrameId.
2457class FindFrameVisitor FINAL : public StackVisitor {
2458 public:
2459 FindFrameVisitor(Thread* thread, Context* context, JDWP::FrameId frame_id)
2460 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_)
Nicolas Geoffray8e5bd182015-05-06 11:34:34 +01002461 : StackVisitor(thread, context, StackVisitor::StackWalkKind::kIncludeInlinedFrames),
2462 frame_id_(frame_id),
2463 error_(JDWP::ERR_INVALID_FRAMEID) {}
Ian Rogersca190662012-06-26 15:45:57 -07002464
Sebastien Hertz8009f392014-09-01 17:07:11 +02002465 // TODO: Enable annotalysis. We know lock is held in constructor, but abstraction confuses
2466 // annotalysis.
2467 bool VisitFrame() NO_THREAD_SAFETY_ANALYSIS {
2468 if (GetFrameId() != frame_id_) {
2469 return true; // Not our frame, carry on.
Ian Rogers0399dde2012-06-06 17:09:28 -07002470 }
Sebastien Hertz8009f392014-09-01 17:07:11 +02002471 mirror::ArtMethod* m = GetMethod();
2472 if (m->IsNative()) {
2473 // We can't read/write local value from/into native method.
2474 error_ = JDWP::ERR_OPAQUE_FRAME;
2475 } else {
2476 // We found our frame.
2477 error_ = JDWP::ERR_NONE;
2478 }
2479 return false;
2480 }
2481
2482 JDWP::JdwpError GetError() const {
2483 return error_;
2484 }
2485
2486 private:
2487 const JDWP::FrameId frame_id_;
2488 JDWP::JdwpError error_;
2489};
2490
2491JDWP::JdwpError Dbg::GetLocalValues(JDWP::Request* request, JDWP::ExpandBuf* pReply) {
2492 JDWP::ObjectId thread_id = request->ReadThreadId();
2493 JDWP::FrameId frame_id = request->ReadFrameId();
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002494
2495 ScopedObjectAccessUnchecked soa(Thread::Current());
Sebastien Hertz69206392015-04-07 15:54:25 +02002496 JDWP::JdwpError error;
2497 Thread* thread = DecodeThread(soa, thread_id, &error);
2498 if (error != JDWP::ERR_NONE) {
2499 return error;
2500 }
2501 if (!IsSuspendedForDebugger(soa, thread)) {
2502 return JDWP::ERR_THREAD_NOT_SUSPENDED;
Elliott Hughes221229c2013-01-08 18:17:50 -08002503 }
Sebastien Hertz8009f392014-09-01 17:07:11 +02002504 // Find the frame with the given frame_id.
Ian Rogers700a4022014-05-19 16:49:03 -07002505 std::unique_ptr<Context> context(Context::Create());
Sebastien Hertz8009f392014-09-01 17:07:11 +02002506 FindFrameVisitor visitor(thread, context.get(), frame_id);
Ian Rogers0399dde2012-06-06 17:09:28 -07002507 visitor.WalkStack();
Sebastien Hertz8009f392014-09-01 17:07:11 +02002508 if (visitor.GetError() != JDWP::ERR_NONE) {
2509 return visitor.GetError();
2510 }
2511
2512 // Read the values from visitor's context.
2513 int32_t slot_count = request->ReadSigned32("slot count");
2514 expandBufAdd4BE(pReply, slot_count); /* "int values" */
2515 for (int32_t i = 0; i < slot_count; ++i) {
2516 uint32_t slot = request->ReadUnsigned32("slot");
2517 JDWP::JdwpTag reqSigByte = request->ReadTag();
2518
2519 VLOG(jdwp) << " --> slot " << slot << " " << reqSigByte;
2520
2521 size_t width = Dbg::GetTagWidth(reqSigByte);
Sebastien Hertz7d955652014-10-22 10:57:10 +02002522 uint8_t* ptr = expandBufAddSpace(pReply, width + 1);
Sebastien Hertz69206392015-04-07 15:54:25 +02002523 error = Dbg::GetLocalValue(visitor, soa, slot, reqSigByte, ptr, width);
Sebastien Hertz8009f392014-09-01 17:07:11 +02002524 if (error != JDWP::ERR_NONE) {
2525 return error;
2526 }
2527 }
2528 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002529}
2530
Sebastien Hertzabbabc82015-03-26 08:47:47 +01002531constexpr JDWP::JdwpError kStackFrameLocalAccessError = JDWP::ERR_ABSENT_INFORMATION;
2532
2533static std::string GetStackContextAsString(const StackVisitor& visitor)
2534 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
2535 return StringPrintf(" at DEX pc 0x%08x in method %s", visitor.GetDexPc(false),
2536 PrettyMethod(visitor.GetMethod()).c_str());
2537}
2538
2539static JDWP::JdwpError FailGetLocalValue(const StackVisitor& visitor, uint16_t vreg,
2540 JDWP::JdwpTag tag)
2541 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
2542 LOG(ERROR) << "Failed to read " << tag << " local from register v" << vreg
2543 << GetStackContextAsString(visitor);
2544 return kStackFrameLocalAccessError;
2545}
2546
Sebastien Hertz8009f392014-09-01 17:07:11 +02002547JDWP::JdwpError Dbg::GetLocalValue(const StackVisitor& visitor, ScopedObjectAccessUnchecked& soa,
2548 int slot, JDWP::JdwpTag tag, uint8_t* buf, size_t width) {
2549 mirror::ArtMethod* m = visitor.GetMethod();
Sebastien Hertzabbabc82015-03-26 08:47:47 +01002550 JDWP::JdwpError error = JDWP::ERR_NONE;
2551 uint16_t vreg = DemangleSlot(slot, m, &error);
2552 if (error != JDWP::ERR_NONE) {
2553 return error;
2554 }
Sebastien Hertz8009f392014-09-01 17:07:11 +02002555 // TODO: check that the tag is compatible with the actual type of the slot!
Sebastien Hertz8009f392014-09-01 17:07:11 +02002556 switch (tag) {
2557 case JDWP::JT_BOOLEAN: {
2558 CHECK_EQ(width, 1U);
2559 uint32_t intVal;
Sebastien Hertzabbabc82015-03-26 08:47:47 +01002560 if (!visitor.GetVReg(m, vreg, kIntVReg, &intVal)) {
2561 return FailGetLocalValue(visitor, vreg, tag);
Ian Rogers0399dde2012-06-06 17:09:28 -07002562 }
Sebastien Hertzabbabc82015-03-26 08:47:47 +01002563 VLOG(jdwp) << "get boolean local " << vreg << " = " << intVal;
2564 JDWP::Set1(buf + 1, intVal != 0);
Sebastien Hertz8009f392014-09-01 17:07:11 +02002565 break;
Ian Rogers0399dde2012-06-06 17:09:28 -07002566 }
Sebastien Hertz8009f392014-09-01 17:07:11 +02002567 case JDWP::JT_BYTE: {
2568 CHECK_EQ(width, 1U);
2569 uint32_t intVal;
Sebastien Hertzabbabc82015-03-26 08:47:47 +01002570 if (!visitor.GetVReg(m, vreg, kIntVReg, &intVal)) {
2571 return FailGetLocalValue(visitor, vreg, tag);
Sebastien Hertz8009f392014-09-01 17:07:11 +02002572 }
Sebastien Hertzabbabc82015-03-26 08:47:47 +01002573 VLOG(jdwp) << "get byte local " << vreg << " = " << intVal;
2574 JDWP::Set1(buf + 1, intVal);
Sebastien Hertz8009f392014-09-01 17:07:11 +02002575 break;
2576 }
2577 case JDWP::JT_SHORT:
2578 case JDWP::JT_CHAR: {
2579 CHECK_EQ(width, 2U);
2580 uint32_t intVal;
Sebastien Hertzabbabc82015-03-26 08:47:47 +01002581 if (!visitor.GetVReg(m, vreg, kIntVReg, &intVal)) {
2582 return FailGetLocalValue(visitor, vreg, tag);
Sebastien Hertz8009f392014-09-01 17:07:11 +02002583 }
Sebastien Hertzabbabc82015-03-26 08:47:47 +01002584 VLOG(jdwp) << "get short/char local " << vreg << " = " << intVal;
2585 JDWP::Set2BE(buf + 1, intVal);
Sebastien Hertz8009f392014-09-01 17:07:11 +02002586 break;
2587 }
2588 case JDWP::JT_INT: {
2589 CHECK_EQ(width, 4U);
2590 uint32_t intVal;
Sebastien Hertzabbabc82015-03-26 08:47:47 +01002591 if (!visitor.GetVReg(m, vreg, kIntVReg, &intVal)) {
2592 return FailGetLocalValue(visitor, vreg, tag);
Sebastien Hertz8009f392014-09-01 17:07:11 +02002593 }
Sebastien Hertzabbabc82015-03-26 08:47:47 +01002594 VLOG(jdwp) << "get int local " << vreg << " = " << intVal;
2595 JDWP::Set4BE(buf + 1, intVal);
Sebastien Hertz8009f392014-09-01 17:07:11 +02002596 break;
2597 }
2598 case JDWP::JT_FLOAT: {
2599 CHECK_EQ(width, 4U);
2600 uint32_t intVal;
Sebastien Hertzabbabc82015-03-26 08:47:47 +01002601 if (!visitor.GetVReg(m, vreg, kFloatVReg, &intVal)) {
2602 return FailGetLocalValue(visitor, vreg, tag);
Sebastien Hertz8009f392014-09-01 17:07:11 +02002603 }
Sebastien Hertzabbabc82015-03-26 08:47:47 +01002604 VLOG(jdwp) << "get float local " << vreg << " = " << intVal;
2605 JDWP::Set4BE(buf + 1, intVal);
Sebastien Hertz8009f392014-09-01 17:07:11 +02002606 break;
2607 }
2608 case JDWP::JT_ARRAY:
2609 case JDWP::JT_CLASS_LOADER:
2610 case JDWP::JT_CLASS_OBJECT:
2611 case JDWP::JT_OBJECT:
2612 case JDWP::JT_STRING:
2613 case JDWP::JT_THREAD:
2614 case JDWP::JT_THREAD_GROUP: {
2615 CHECK_EQ(width, sizeof(JDWP::ObjectId));
2616 uint32_t intVal;
Sebastien Hertzabbabc82015-03-26 08:47:47 +01002617 if (!visitor.GetVReg(m, vreg, kReferenceVReg, &intVal)) {
2618 return FailGetLocalValue(visitor, vreg, tag);
Sebastien Hertz8009f392014-09-01 17:07:11 +02002619 }
Sebastien Hertzabbabc82015-03-26 08:47:47 +01002620 mirror::Object* o = reinterpret_cast<mirror::Object*>(intVal);
2621 VLOG(jdwp) << "get " << tag << " object local " << vreg << " = " << o;
2622 if (!Runtime::Current()->GetHeap()->IsValidObjectAddress(o)) {
2623 LOG(FATAL) << StringPrintf("Found invalid object %#" PRIxPTR " in register v%u",
2624 reinterpret_cast<uintptr_t>(o), vreg)
2625 << GetStackContextAsString(visitor);
2626 UNREACHABLE();
2627 }
2628 tag = TagFromObject(soa, o);
2629 JDWP::SetObjectId(buf + 1, gRegistry->Add(o));
Sebastien Hertz8009f392014-09-01 17:07:11 +02002630 break;
2631 }
2632 case JDWP::JT_DOUBLE: {
2633 CHECK_EQ(width, 8U);
2634 uint64_t longVal;
Sebastien Hertzabbabc82015-03-26 08:47:47 +01002635 if (!visitor.GetVRegPair(m, vreg, kDoubleLoVReg, kDoubleHiVReg, &longVal)) {
2636 return FailGetLocalValue(visitor, vreg, tag);
Sebastien Hertz8009f392014-09-01 17:07:11 +02002637 }
Sebastien Hertzabbabc82015-03-26 08:47:47 +01002638 VLOG(jdwp) << "get double local " << vreg << " = " << longVal;
2639 JDWP::Set8BE(buf + 1, longVal);
Sebastien Hertz8009f392014-09-01 17:07:11 +02002640 break;
2641 }
2642 case JDWP::JT_LONG: {
2643 CHECK_EQ(width, 8U);
2644 uint64_t longVal;
Sebastien Hertzabbabc82015-03-26 08:47:47 +01002645 if (!visitor.GetVRegPair(m, vreg, kLongLoVReg, kLongHiVReg, &longVal)) {
2646 return FailGetLocalValue(visitor, vreg, tag);
Sebastien Hertz8009f392014-09-01 17:07:11 +02002647 }
Sebastien Hertzabbabc82015-03-26 08:47:47 +01002648 VLOG(jdwp) << "get long local " << vreg << " = " << longVal;
2649 JDWP::Set8BE(buf + 1, longVal);
Sebastien Hertz8009f392014-09-01 17:07:11 +02002650 break;
2651 }
2652 default:
2653 LOG(FATAL) << "Unknown tag " << tag;
Sebastien Hertzabbabc82015-03-26 08:47:47 +01002654 UNREACHABLE();
Sebastien Hertz8009f392014-09-01 17:07:11 +02002655 }
Ian Rogers0399dde2012-06-06 17:09:28 -07002656
Sebastien Hertz8009f392014-09-01 17:07:11 +02002657 // Prepend tag, which may have been updated.
2658 JDWP::Set1(buf, tag);
2659 return JDWP::ERR_NONE;
2660}
2661
2662JDWP::JdwpError Dbg::SetLocalValues(JDWP::Request* request) {
2663 JDWP::ObjectId thread_id = request->ReadThreadId();
2664 JDWP::FrameId frame_id = request->ReadFrameId();
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002665
2666 ScopedObjectAccessUnchecked soa(Thread::Current());
Sebastien Hertz69206392015-04-07 15:54:25 +02002667 JDWP::JdwpError error;
2668 Thread* thread = DecodeThread(soa, thread_id, &error);
2669 if (error != JDWP::ERR_NONE) {
2670 return error;
2671 }
2672 if (!IsSuspendedForDebugger(soa, thread)) {
2673 return JDWP::ERR_THREAD_NOT_SUSPENDED;
Elliott Hughes221229c2013-01-08 18:17:50 -08002674 }
Sebastien Hertz8009f392014-09-01 17:07:11 +02002675 // Find the frame with the given frame_id.
Ian Rogers700a4022014-05-19 16:49:03 -07002676 std::unique_ptr<Context> context(Context::Create());
Sebastien Hertz8009f392014-09-01 17:07:11 +02002677 FindFrameVisitor visitor(thread, context.get(), frame_id);
Ian Rogers0399dde2012-06-06 17:09:28 -07002678 visitor.WalkStack();
Sebastien Hertz8009f392014-09-01 17:07:11 +02002679 if (visitor.GetError() != JDWP::ERR_NONE) {
2680 return visitor.GetError();
2681 }
2682
2683 // Writes the values into visitor's context.
2684 int32_t slot_count = request->ReadSigned32("slot count");
2685 for (int32_t i = 0; i < slot_count; ++i) {
2686 uint32_t slot = request->ReadUnsigned32("slot");
2687 JDWP::JdwpTag sigByte = request->ReadTag();
2688 size_t width = Dbg::GetTagWidth(sigByte);
2689 uint64_t value = request->ReadValue(width);
2690
2691 VLOG(jdwp) << " --> slot " << slot << " " << sigByte << " " << value;
Sebastien Hertz69206392015-04-07 15:54:25 +02002692 error = Dbg::SetLocalValue(visitor, slot, sigByte, value, width);
Sebastien Hertz8009f392014-09-01 17:07:11 +02002693 if (error != JDWP::ERR_NONE) {
2694 return error;
2695 }
2696 }
2697 return JDWP::ERR_NONE;
2698}
2699
Sebastien Hertzabbabc82015-03-26 08:47:47 +01002700template<typename T>
2701static JDWP::JdwpError FailSetLocalValue(const StackVisitor& visitor, uint16_t vreg,
2702 JDWP::JdwpTag tag, T value)
2703 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
2704 LOG(ERROR) << "Failed to write " << tag << " local " << value
2705 << " (0x" << std::hex << value << ") into register v" << vreg
2706 << GetStackContextAsString(visitor);
2707 return kStackFrameLocalAccessError;
2708}
2709
Sebastien Hertz8009f392014-09-01 17:07:11 +02002710JDWP::JdwpError Dbg::SetLocalValue(StackVisitor& visitor, int slot, JDWP::JdwpTag tag,
2711 uint64_t value, size_t width) {
2712 mirror::ArtMethod* m = visitor.GetMethod();
Sebastien Hertzabbabc82015-03-26 08:47:47 +01002713 JDWP::JdwpError error = JDWP::ERR_NONE;
2714 uint16_t vreg = DemangleSlot(slot, m, &error);
2715 if (error != JDWP::ERR_NONE) {
2716 return error;
2717 }
Sebastien Hertz8009f392014-09-01 17:07:11 +02002718 // TODO: check that the tag is compatible with the actual type of the slot!
Sebastien Hertz8009f392014-09-01 17:07:11 +02002719 switch (tag) {
2720 case JDWP::JT_BOOLEAN:
2721 case JDWP::JT_BYTE:
2722 CHECK_EQ(width, 1U);
Sebastien Hertzabbabc82015-03-26 08:47:47 +01002723 if (!visitor.SetVReg(m, vreg, static_cast<uint32_t>(value), kIntVReg)) {
2724 return FailSetLocalValue(visitor, vreg, tag, static_cast<uint32_t>(value));
Sebastien Hertz8009f392014-09-01 17:07:11 +02002725 }
2726 break;
2727 case JDWP::JT_SHORT:
2728 case JDWP::JT_CHAR:
2729 CHECK_EQ(width, 2U);
Sebastien Hertzabbabc82015-03-26 08:47:47 +01002730 if (!visitor.SetVReg(m, vreg, static_cast<uint32_t>(value), kIntVReg)) {
2731 return FailSetLocalValue(visitor, vreg, tag, static_cast<uint32_t>(value));
Sebastien Hertz8009f392014-09-01 17:07:11 +02002732 }
2733 break;
2734 case JDWP::JT_INT:
2735 CHECK_EQ(width, 4U);
Sebastien Hertzabbabc82015-03-26 08:47:47 +01002736 if (!visitor.SetVReg(m, vreg, static_cast<uint32_t>(value), kIntVReg)) {
2737 return FailSetLocalValue(visitor, vreg, tag, static_cast<uint32_t>(value));
Sebastien Hertz8009f392014-09-01 17:07:11 +02002738 }
2739 break;
2740 case JDWP::JT_FLOAT:
2741 CHECK_EQ(width, 4U);
Sebastien Hertzabbabc82015-03-26 08:47:47 +01002742 if (!visitor.SetVReg(m, vreg, static_cast<uint32_t>(value), kFloatVReg)) {
2743 return FailSetLocalValue(visitor, vreg, tag, static_cast<uint32_t>(value));
Sebastien Hertz8009f392014-09-01 17:07:11 +02002744 }
2745 break;
2746 case JDWP::JT_ARRAY:
2747 case JDWP::JT_CLASS_LOADER:
2748 case JDWP::JT_CLASS_OBJECT:
2749 case JDWP::JT_OBJECT:
2750 case JDWP::JT_STRING:
2751 case JDWP::JT_THREAD:
2752 case JDWP::JT_THREAD_GROUP: {
2753 CHECK_EQ(width, sizeof(JDWP::ObjectId));
Sebastien Hertz8009f392014-09-01 17:07:11 +02002754 mirror::Object* o = gRegistry->Get<mirror::Object*>(static_cast<JDWP::ObjectId>(value),
2755 &error);
2756 if (error != JDWP::ERR_NONE) {
2757 VLOG(jdwp) << tag << " object " << o << " is an invalid object";
2758 return JDWP::ERR_INVALID_OBJECT;
Sebastien Hertzabbabc82015-03-26 08:47:47 +01002759 }
2760 if (!visitor.SetVReg(m, vreg, static_cast<uint32_t>(reinterpret_cast<uintptr_t>(o)),
2761 kReferenceVReg)) {
2762 return FailSetLocalValue(visitor, vreg, tag, reinterpret_cast<uintptr_t>(o));
Sebastien Hertz8009f392014-09-01 17:07:11 +02002763 }
2764 break;
2765 }
2766 case JDWP::JT_DOUBLE: {
2767 CHECK_EQ(width, 8U);
Sebastien Hertzabbabc82015-03-26 08:47:47 +01002768 if (!visitor.SetVRegPair(m, vreg, value, kDoubleLoVReg, kDoubleHiVReg)) {
2769 return FailSetLocalValue(visitor, vreg, tag, value);
Sebastien Hertz8009f392014-09-01 17:07:11 +02002770 }
2771 break;
2772 }
2773 case JDWP::JT_LONG: {
2774 CHECK_EQ(width, 8U);
Sebastien Hertzabbabc82015-03-26 08:47:47 +01002775 if (!visitor.SetVRegPair(m, vreg, value, kLongLoVReg, kLongHiVReg)) {
2776 return FailSetLocalValue(visitor, vreg, tag, value);
Sebastien Hertz8009f392014-09-01 17:07:11 +02002777 }
2778 break;
2779 }
2780 default:
2781 LOG(FATAL) << "Unknown tag " << tag;
Sebastien Hertzabbabc82015-03-26 08:47:47 +01002782 UNREACHABLE();
Sebastien Hertz8009f392014-09-01 17:07:11 +02002783 }
2784 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002785}
2786
Sebastien Hertz6995c602014-09-09 12:10:13 +02002787static void SetEventLocation(JDWP::EventLocation* location, mirror::ArtMethod* m, uint32_t dex_pc)
2788 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
2789 DCHECK(location != nullptr);
2790 if (m == nullptr) {
2791 memset(location, 0, sizeof(*location));
2792 } else {
2793 location->method = m;
2794 location->dex_pc = (m->IsNative() || m->IsProxyMethod()) ? static_cast<uint32_t>(-1) : dex_pc;
Sebastien Hertz3f52eaf2014-04-04 17:50:18 +02002795 }
Sebastien Hertz3f52eaf2014-04-04 17:50:18 +02002796}
2797
Ian Rogersef7d42f2014-01-06 12:55:46 -08002798void Dbg::PostLocationEvent(mirror::ArtMethod* m, int dex_pc, mirror::Object* this_object,
Jeff Hao579b0242013-11-18 13:16:49 -08002799 int event_flags, const JValue* return_value) {
Sebastien Hertz3f52eaf2014-04-04 17:50:18 +02002800 if (!IsDebuggerActive()) {
2801 return;
2802 }
2803 DCHECK(m != nullptr);
2804 DCHECK_EQ(m->IsStatic(), this_object == nullptr);
Sebastien Hertz6995c602014-09-09 12:10:13 +02002805 JDWP::EventLocation location;
2806 SetEventLocation(&location, m, dex_pc);
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08002807
Sebastien Hertz6995c602014-09-09 12:10:13 +02002808 gJdwpState->PostLocationEvent(&location, this_object, event_flags, return_value);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002809}
2810
Sebastien Hertz3f52eaf2014-04-04 17:50:18 +02002811void Dbg::PostFieldAccessEvent(mirror::ArtMethod* m, int dex_pc,
Mathieu Chartierc7853442015-03-27 14:35:38 -07002812 mirror::Object* this_object, ArtField* f) {
Sebastien Hertz3f52eaf2014-04-04 17:50:18 +02002813 if (!IsDebuggerActive()) {
2814 return;
2815 }
2816 DCHECK(m != nullptr);
2817 DCHECK(f != nullptr);
Sebastien Hertz6995c602014-09-09 12:10:13 +02002818 JDWP::EventLocation location;
2819 SetEventLocation(&location, m, dex_pc);
Sebastien Hertz3f52eaf2014-04-04 17:50:18 +02002820
Sebastien Hertz6995c602014-09-09 12:10:13 +02002821 gJdwpState->PostFieldEvent(&location, f, this_object, nullptr, false);
Sebastien Hertz3f52eaf2014-04-04 17:50:18 +02002822}
2823
2824void Dbg::PostFieldModificationEvent(mirror::ArtMethod* m, int dex_pc,
Mathieu Chartierc7853442015-03-27 14:35:38 -07002825 mirror::Object* this_object, ArtField* f,
Sebastien Hertz3f52eaf2014-04-04 17:50:18 +02002826 const JValue* field_value) {
2827 if (!IsDebuggerActive()) {
2828 return;
2829 }
2830 DCHECK(m != nullptr);
2831 DCHECK(f != nullptr);
2832 DCHECK(field_value != nullptr);
Sebastien Hertz6995c602014-09-09 12:10:13 +02002833 JDWP::EventLocation location;
2834 SetEventLocation(&location, m, dex_pc);
Sebastien Hertz3f52eaf2014-04-04 17:50:18 +02002835
Sebastien Hertz6995c602014-09-09 12:10:13 +02002836 gJdwpState->PostFieldEvent(&location, f, this_object, field_value, true);
Sebastien Hertz3f52eaf2014-04-04 17:50:18 +02002837}
2838
Nicolas Geoffray14691c52015-03-05 10:40:17 +00002839/**
2840 * Finds the location where this exception will be caught. We search until we reach the top
2841 * frame, in which case this exception is considered uncaught.
2842 */
2843class CatchLocationFinder : public StackVisitor {
2844 public:
2845 CatchLocationFinder(Thread* self, const Handle<mirror::Throwable>& exception, Context* context)
2846 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_)
Nicolas Geoffray8e5bd182015-05-06 11:34:34 +01002847 : StackVisitor(self, context, StackVisitor::StackWalkKind::kIncludeInlinedFrames),
Nicolas Geoffray14691c52015-03-05 10:40:17 +00002848 self_(self),
2849 exception_(exception),
2850 handle_scope_(self),
2851 this_at_throw_(handle_scope_.NewHandle<mirror::Object>(nullptr)),
2852 catch_method_(handle_scope_.NewHandle<mirror::ArtMethod>(nullptr)),
2853 throw_method_(handle_scope_.NewHandle<mirror::ArtMethod>(nullptr)),
2854 catch_dex_pc_(DexFile::kDexNoIndex),
2855 throw_dex_pc_(DexFile::kDexNoIndex) {
2856 }
2857
2858 bool VisitFrame() OVERRIDE SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
2859 mirror::ArtMethod* method = GetMethod();
2860 DCHECK(method != nullptr);
2861 if (method->IsRuntimeMethod()) {
2862 // Ignore callee save method.
2863 DCHECK(method->IsCalleeSaveMethod());
2864 return true;
2865 }
2866
2867 uint32_t dex_pc = GetDexPc();
2868 if (throw_method_.Get() == nullptr) {
2869 // First Java method found. It is either the method that threw the exception,
2870 // or the Java native method that is reporting an exception thrown by
2871 // native code.
2872 this_at_throw_.Assign(GetThisObject());
2873 throw_method_.Assign(method);
2874 throw_dex_pc_ = dex_pc;
2875 }
2876
2877 if (dex_pc != DexFile::kDexNoIndex) {
2878 StackHandleScope<2> hs(self_);
2879 uint32_t found_dex_pc;
2880 Handle<mirror::Class> exception_class(hs.NewHandle(exception_->GetClass()));
2881 Handle<mirror::ArtMethod> h_method(hs.NewHandle(method));
2882 bool unused_clear_exception;
2883 found_dex_pc = mirror::ArtMethod::FindCatchBlock(
2884 h_method, exception_class, dex_pc, &unused_clear_exception);
2885 if (found_dex_pc != DexFile::kDexNoIndex) {
2886 catch_method_.Assign(method);
2887 catch_dex_pc_ = found_dex_pc;
2888 return false; // End stack walk.
2889 }
2890 }
2891 return true; // Continue stack walk.
2892 }
2893
2894 mirror::ArtMethod* GetCatchMethod() SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
2895 return catch_method_.Get();
2896 }
2897
2898 mirror::ArtMethod* GetThrowMethod() SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
2899 return throw_method_.Get();
2900 }
2901
2902 mirror::Object* GetThisAtThrow() SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
2903 return this_at_throw_.Get();
2904 }
2905
2906 uint32_t GetCatchDexPc() const {
2907 return catch_dex_pc_;
2908 }
2909
2910 uint32_t GetThrowDexPc() const {
2911 return throw_dex_pc_;
2912 }
2913
2914 private:
2915 Thread* const self_;
2916 const Handle<mirror::Throwable>& exception_;
2917 StackHandleScope<3> handle_scope_;
2918 MutableHandle<mirror::Object> this_at_throw_;
2919 MutableHandle<mirror::ArtMethod> catch_method_;
2920 MutableHandle<mirror::ArtMethod> throw_method_;
2921 uint32_t catch_dex_pc_;
2922 uint32_t throw_dex_pc_;
2923
2924 DISALLOW_COPY_AND_ASSIGN(CatchLocationFinder);
2925};
2926
2927void Dbg::PostException(mirror::Throwable* exception_object) {
Elliott Hughesc0f09332012-03-26 13:27:06 -07002928 if (!IsDebuggerActive()) {
Ian Rogers0ad5bb82011-12-07 10:16:32 -08002929 return;
2930 }
Sebastien Hertz261bc042015-04-08 09:36:07 +02002931 Thread* const self = Thread::Current();
2932 StackHandleScope<1> handle_scope(self);
Nicolas Geoffray14691c52015-03-05 10:40:17 +00002933 Handle<mirror::Throwable> h_exception(handle_scope.NewHandle(exception_object));
2934 std::unique_ptr<Context> context(Context::Create());
Sebastien Hertz261bc042015-04-08 09:36:07 +02002935 CatchLocationFinder clf(self, h_exception, context.get());
Nicolas Geoffray14691c52015-03-05 10:40:17 +00002936 clf.WalkStack(/* include_transitions */ false);
Sebastien Hertz6995c602014-09-09 12:10:13 +02002937 JDWP::EventLocation exception_throw_location;
Nicolas Geoffray14691c52015-03-05 10:40:17 +00002938 SetEventLocation(&exception_throw_location, clf.GetThrowMethod(), clf.GetThrowDexPc());
Sebastien Hertz6995c602014-09-09 12:10:13 +02002939 JDWP::EventLocation exception_catch_location;
Nicolas Geoffray14691c52015-03-05 10:40:17 +00002940 SetEventLocation(&exception_catch_location, clf.GetCatchMethod(), clf.GetCatchDexPc());
Elliott Hughes4740cdf2011-12-07 14:07:12 -08002941
Nicolas Geoffray14691c52015-03-05 10:40:17 +00002942 gJdwpState->PostException(&exception_throw_location, h_exception.Get(), &exception_catch_location,
2943 clf.GetThisAtThrow());
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002944}
2945
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002946void Dbg::PostClassPrepare(mirror::Class* c) {
Elliott Hughesc0f09332012-03-26 13:27:06 -07002947 if (!IsDebuggerActive()) {
Elliott Hughes4740cdf2011-12-07 14:07:12 -08002948 return;
2949 }
Sebastien Hertz6995c602014-09-09 12:10:13 +02002950 gJdwpState->PostClassPrepare(c);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002951}
2952
Ian Rogers62d6c772013-02-27 08:32:07 -08002953void Dbg::UpdateDebugger(Thread* thread, mirror::Object* this_object,
Sebastien Hertz8379b222014-02-24 17:38:15 +01002954 mirror::ArtMethod* m, uint32_t dex_pc,
2955 int event_flags, const JValue* return_value) {
Ian Rogers62d6c772013-02-27 08:32:07 -08002956 if (!IsDebuggerActive() || dex_pc == static_cast<uint32_t>(-2) /* fake method exit */) {
Elliott Hughes2aa2e392012-02-17 17:15:43 -08002957 return;
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08002958 }
2959
Elliott Hughes86964332012-02-15 19:37:42 -08002960 if (IsBreakpoint(m, dex_pc)) {
2961 event_flags |= kBreakpoint;
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08002962 }
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08002963
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01002964 // If the debugger is single-stepping one of our threads, check to
2965 // see if we're that thread and we've reached a step point.
2966 const SingleStepControl* single_step_control = thread->GetSingleStepControl();
Sebastien Hertz597c4f02015-01-26 17:37:14 +01002967 if (single_step_control != nullptr) {
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01002968 CHECK(!m->IsNative());
Sebastien Hertz597c4f02015-01-26 17:37:14 +01002969 if (single_step_control->GetStepDepth() == JDWP::SD_INTO) {
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01002970 // Step into method calls. We break when the line number
2971 // or method pointer changes. If we're in SS_MIN mode, we
2972 // always stop.
Sebastien Hertz597c4f02015-01-26 17:37:14 +01002973 if (single_step_control->GetMethod() != m) {
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01002974 event_flags |= kSingleStep;
2975 VLOG(jdwp) << "SS new method";
Sebastien Hertz597c4f02015-01-26 17:37:14 +01002976 } else if (single_step_control->GetStepSize() == JDWP::SS_MIN) {
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01002977 event_flags |= kSingleStep;
2978 VLOG(jdwp) << "SS new instruction";
Sebastien Hertzbb43b432014-04-14 11:59:08 +02002979 } else if (single_step_control->ContainsDexPc(dex_pc)) {
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01002980 event_flags |= kSingleStep;
2981 VLOG(jdwp) << "SS new line";
2982 }
Sebastien Hertz597c4f02015-01-26 17:37:14 +01002983 } else if (single_step_control->GetStepDepth() == JDWP::SD_OVER) {
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01002984 // Step over method calls. We break when the line number is
2985 // different and the frame depth is <= the original frame
2986 // depth. (We can't just compare on the method, because we
2987 // might get unrolled past it by an exception, and it's tricky
2988 // to identify recursion.)
2989
2990 int stack_depth = GetStackDepth(thread);
2991
Sebastien Hertz597c4f02015-01-26 17:37:14 +01002992 if (stack_depth < single_step_control->GetStackDepth()) {
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01002993 // Popped up one or more frames, always trigger.
2994 event_flags |= kSingleStep;
2995 VLOG(jdwp) << "SS method pop";
Sebastien Hertz597c4f02015-01-26 17:37:14 +01002996 } else if (stack_depth == single_step_control->GetStackDepth()) {
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01002997 // Same depth, see if we moved.
Sebastien Hertz597c4f02015-01-26 17:37:14 +01002998 if (single_step_control->GetStepSize() == JDWP::SS_MIN) {
Elliott Hughes86964332012-02-15 19:37:42 -08002999 event_flags |= kSingleStep;
3000 VLOG(jdwp) << "SS new instruction";
Sebastien Hertzbb43b432014-04-14 11:59:08 +02003001 } else if (single_step_control->ContainsDexPc(dex_pc)) {
Elliott Hughes2435a572012-02-17 16:07:41 -08003002 event_flags |= kSingleStep;
3003 VLOG(jdwp) << "SS new line";
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08003004 }
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01003005 }
3006 } else {
Sebastien Hertz597c4f02015-01-26 17:37:14 +01003007 CHECK_EQ(single_step_control->GetStepDepth(), JDWP::SD_OUT);
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01003008 // Return from the current method. We break when the frame
3009 // depth pops up.
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08003010
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01003011 // This differs from the "method exit" break in that it stops
3012 // with the PC at the next instruction in the returned-to
3013 // function, rather than the end of the returning function.
Elliott Hughes86964332012-02-15 19:37:42 -08003014
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01003015 int stack_depth = GetStackDepth(thread);
Sebastien Hertz597c4f02015-01-26 17:37:14 +01003016 if (stack_depth < single_step_control->GetStackDepth()) {
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01003017 event_flags |= kSingleStep;
3018 VLOG(jdwp) << "SS method pop";
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08003019 }
3020 }
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08003021 }
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08003022
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08003023 // If there's something interesting going on, see if it matches one
3024 // of the debugger filters.
3025 if (event_flags != 0) {
Sebastien Hertz8379b222014-02-24 17:38:15 +01003026 Dbg::PostLocationEvent(m, dex_pc, this_object, event_flags, return_value);
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08003027 }
3028}
3029
Sebastien Hertz42cd43f2014-05-13 14:15:41 +02003030size_t* Dbg::GetReferenceCounterForEvent(uint32_t instrumentation_event) {
3031 switch (instrumentation_event) {
3032 case instrumentation::Instrumentation::kMethodEntered:
3033 return &method_enter_event_ref_count_;
3034 case instrumentation::Instrumentation::kMethodExited:
3035 return &method_exit_event_ref_count_;
3036 case instrumentation::Instrumentation::kDexPcMoved:
3037 return &dex_pc_change_event_ref_count_;
3038 case instrumentation::Instrumentation::kFieldRead:
3039 return &field_read_event_ref_count_;
3040 case instrumentation::Instrumentation::kFieldWritten:
3041 return &field_write_event_ref_count_;
3042 case instrumentation::Instrumentation::kExceptionCaught:
3043 return &exception_catch_event_ref_count_;
3044 default:
3045 return nullptr;
3046 }
3047}
3048
Sebastien Hertz4d25df32014-03-21 17:44:46 +01003049// Process request while all mutator threads are suspended.
3050void Dbg::ProcessDeoptimizationRequest(const DeoptimizationRequest& request) {
Sebastien Hertz138dbfc2013-12-04 18:15:25 +01003051 instrumentation::Instrumentation* instrumentation = Runtime::Current()->GetInstrumentation();
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003052 switch (request.GetKind()) {
Sebastien Hertz4d25df32014-03-21 17:44:46 +01003053 case DeoptimizationRequest::kNothing:
3054 LOG(WARNING) << "Ignoring empty deoptimization request.";
3055 break;
Sebastien Hertz42cd43f2014-05-13 14:15:41 +02003056 case DeoptimizationRequest::kRegisterForEvent:
3057 VLOG(jdwp) << StringPrintf("Add debugger as listener for instrumentation event 0x%x",
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003058 request.InstrumentationEvent());
3059 instrumentation->AddListener(&gDebugInstrumentationListener, request.InstrumentationEvent());
3060 instrumentation_events_ |= request.InstrumentationEvent();
Sebastien Hertz42cd43f2014-05-13 14:15:41 +02003061 break;
3062 case DeoptimizationRequest::kUnregisterForEvent:
3063 VLOG(jdwp) << StringPrintf("Remove debugger as listener for instrumentation event 0x%x",
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003064 request.InstrumentationEvent());
Sebastien Hertz42cd43f2014-05-13 14:15:41 +02003065 instrumentation->RemoveListener(&gDebugInstrumentationListener,
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003066 request.InstrumentationEvent());
3067 instrumentation_events_ &= ~request.InstrumentationEvent();
Sebastien Hertz42cd43f2014-05-13 14:15:41 +02003068 break;
Sebastien Hertz4d25df32014-03-21 17:44:46 +01003069 case DeoptimizationRequest::kFullDeoptimization:
Sebastien Hertz7ec2f1c2014-03-27 20:06:47 +01003070 VLOG(jdwp) << "Deoptimize the world ...";
Sebastien Hertz0462c4c2015-04-01 16:34:17 +02003071 instrumentation->DeoptimizeEverything(kDbgInstrumentationKey);
Sebastien Hertz7ec2f1c2014-03-27 20:06:47 +01003072 VLOG(jdwp) << "Deoptimize the world DONE";
Sebastien Hertz4d25df32014-03-21 17:44:46 +01003073 break;
3074 case DeoptimizationRequest::kFullUndeoptimization:
Sebastien Hertz7ec2f1c2014-03-27 20:06:47 +01003075 VLOG(jdwp) << "Undeoptimize the world ...";
Sebastien Hertz0462c4c2015-04-01 16:34:17 +02003076 instrumentation->UndeoptimizeEverything(kDbgInstrumentationKey);
Sebastien Hertz7ec2f1c2014-03-27 20:06:47 +01003077 VLOG(jdwp) << "Undeoptimize the world DONE";
Sebastien Hertz4d25df32014-03-21 17:44:46 +01003078 break;
3079 case DeoptimizationRequest::kSelectiveDeoptimization:
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003080 VLOG(jdwp) << "Deoptimize method " << PrettyMethod(request.Method()) << " ...";
3081 instrumentation->Deoptimize(request.Method());
3082 VLOG(jdwp) << "Deoptimize method " << PrettyMethod(request.Method()) << " DONE";
Sebastien Hertz4d25df32014-03-21 17:44:46 +01003083 break;
3084 case DeoptimizationRequest::kSelectiveUndeoptimization:
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003085 VLOG(jdwp) << "Undeoptimize method " << PrettyMethod(request.Method()) << " ...";
3086 instrumentation->Undeoptimize(request.Method());
3087 VLOG(jdwp) << "Undeoptimize method " << PrettyMethod(request.Method()) << " DONE";
Sebastien Hertz4d25df32014-03-21 17:44:46 +01003088 break;
3089 default:
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003090 LOG(FATAL) << "Unsupported deoptimization request kind " << request.GetKind();
Sebastien Hertz4d25df32014-03-21 17:44:46 +01003091 break;
Sebastien Hertz138dbfc2013-12-04 18:15:25 +01003092 }
Sebastien Hertz138dbfc2013-12-04 18:15:25 +01003093}
3094
Sebastien Hertz4d25df32014-03-21 17:44:46 +01003095void Dbg::RequestDeoptimization(const DeoptimizationRequest& req) {
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003096 if (req.GetKind() == DeoptimizationRequest::kNothing) {
Sebastien Hertz4d25df32014-03-21 17:44:46 +01003097 // Nothing to do.
3098 return;
3099 }
Brian Carlstrom306db812014-09-05 13:01:41 -07003100 MutexLock mu(Thread::Current(), *Locks::deoptimization_lock_);
Sebastien Hertz7ec2f1c2014-03-27 20:06:47 +01003101 RequestDeoptimizationLocked(req);
3102}
3103
3104void Dbg::RequestDeoptimizationLocked(const DeoptimizationRequest& req) {
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003105 switch (req.GetKind()) {
Sebastien Hertz42cd43f2014-05-13 14:15:41 +02003106 case DeoptimizationRequest::kRegisterForEvent: {
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003107 DCHECK_NE(req.InstrumentationEvent(), 0u);
3108 size_t* counter = GetReferenceCounterForEvent(req.InstrumentationEvent());
Sebastien Hertz42cd43f2014-05-13 14:15:41 +02003109 CHECK(counter != nullptr) << StringPrintf("No counter for instrumentation event 0x%x",
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003110 req.InstrumentationEvent());
Sebastien Hertz42cd43f2014-05-13 14:15:41 +02003111 if (*counter == 0) {
Sebastien Hertz7d2ae432014-05-15 11:26:34 +02003112 VLOG(jdwp) << StringPrintf("Queue request #%zd to start listening to instrumentation event 0x%x",
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003113 deoptimization_requests_.size(), req.InstrumentationEvent());
Sebastien Hertz42cd43f2014-05-13 14:15:41 +02003114 deoptimization_requests_.push_back(req);
3115 }
3116 *counter = *counter + 1;
3117 break;
3118 }
3119 case DeoptimizationRequest::kUnregisterForEvent: {
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003120 DCHECK_NE(req.InstrumentationEvent(), 0u);
3121 size_t* counter = GetReferenceCounterForEvent(req.InstrumentationEvent());
Sebastien Hertz42cd43f2014-05-13 14:15:41 +02003122 CHECK(counter != nullptr) << StringPrintf("No counter for instrumentation event 0x%x",
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003123 req.InstrumentationEvent());
Sebastien Hertz42cd43f2014-05-13 14:15:41 +02003124 *counter = *counter - 1;
3125 if (*counter == 0) {
Sebastien Hertz7d2ae432014-05-15 11:26:34 +02003126 VLOG(jdwp) << StringPrintf("Queue request #%zd to stop listening to instrumentation event 0x%x",
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003127 deoptimization_requests_.size(), req.InstrumentationEvent());
Sebastien Hertz42cd43f2014-05-13 14:15:41 +02003128 deoptimization_requests_.push_back(req);
3129 }
3130 break;
3131 }
Sebastien Hertz4d25df32014-03-21 17:44:46 +01003132 case DeoptimizationRequest::kFullDeoptimization: {
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003133 DCHECK(req.Method() == nullptr);
Sebastien Hertz4d25df32014-03-21 17:44:46 +01003134 if (full_deoptimization_event_count_ == 0) {
Sebastien Hertz7ec2f1c2014-03-27 20:06:47 +01003135 VLOG(jdwp) << "Queue request #" << deoptimization_requests_.size()
3136 << " for full deoptimization";
Sebastien Hertz4d25df32014-03-21 17:44:46 +01003137 deoptimization_requests_.push_back(req);
3138 }
3139 ++full_deoptimization_event_count_;
3140 break;
3141 }
3142 case DeoptimizationRequest::kFullUndeoptimization: {
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003143 DCHECK(req.Method() == nullptr);
Sebastien Hertze713d932014-05-15 10:48:53 +02003144 DCHECK_GT(full_deoptimization_event_count_, 0U);
Sebastien Hertz4d25df32014-03-21 17:44:46 +01003145 --full_deoptimization_event_count_;
3146 if (full_deoptimization_event_count_ == 0) {
Sebastien Hertz7ec2f1c2014-03-27 20:06:47 +01003147 VLOG(jdwp) << "Queue request #" << deoptimization_requests_.size()
3148 << " for full undeoptimization";
Sebastien Hertz4d25df32014-03-21 17:44:46 +01003149 deoptimization_requests_.push_back(req);
3150 }
3151 break;
3152 }
3153 case DeoptimizationRequest::kSelectiveDeoptimization: {
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003154 DCHECK(req.Method() != nullptr);
Sebastien Hertz7ec2f1c2014-03-27 20:06:47 +01003155 VLOG(jdwp) << "Queue request #" << deoptimization_requests_.size()
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003156 << " for deoptimization of " << PrettyMethod(req.Method());
Sebastien Hertz4d25df32014-03-21 17:44:46 +01003157 deoptimization_requests_.push_back(req);
3158 break;
3159 }
3160 case DeoptimizationRequest::kSelectiveUndeoptimization: {
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003161 DCHECK(req.Method() != nullptr);
Sebastien Hertz7ec2f1c2014-03-27 20:06:47 +01003162 VLOG(jdwp) << "Queue request #" << deoptimization_requests_.size()
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003163 << " for undeoptimization of " << PrettyMethod(req.Method());
Sebastien Hertz4d25df32014-03-21 17:44:46 +01003164 deoptimization_requests_.push_back(req);
3165 break;
3166 }
3167 default: {
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003168 LOG(FATAL) << "Unknown deoptimization request kind " << req.GetKind();
Sebastien Hertz4d25df32014-03-21 17:44:46 +01003169 break;
3170 }
3171 }
3172}
3173
Sebastien Hertz138dbfc2013-12-04 18:15:25 +01003174void Dbg::ManageDeoptimization() {
3175 Thread* const self = Thread::Current();
3176 {
3177 // Avoid suspend/resume if there is no pending request.
Brian Carlstrom306db812014-09-05 13:01:41 -07003178 MutexLock mu(self, *Locks::deoptimization_lock_);
Sebastien Hertz4d25df32014-03-21 17:44:46 +01003179 if (deoptimization_requests_.empty()) {
Sebastien Hertz138dbfc2013-12-04 18:15:25 +01003180 return;
3181 }
3182 }
3183 CHECK_EQ(self->GetState(), kRunnable);
3184 self->TransitionFromRunnableToSuspended(kWaitingForDeoptimization);
3185 // We need to suspend mutator threads first.
3186 Runtime* const runtime = Runtime::Current();
Mathieu Chartierbf9fc582015-03-13 17:21:25 -07003187 runtime->GetThreadList()->SuspendAll(__FUNCTION__);
Sebastien Hertz138dbfc2013-12-04 18:15:25 +01003188 const ThreadState old_state = self->SetStateUnsafe(kRunnable);
Sebastien Hertz4d25df32014-03-21 17:44:46 +01003189 {
Brian Carlstrom306db812014-09-05 13:01:41 -07003190 MutexLock mu(self, *Locks::deoptimization_lock_);
Sebastien Hertz7ec2f1c2014-03-27 20:06:47 +01003191 size_t req_index = 0;
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003192 for (DeoptimizationRequest& request : deoptimization_requests_) {
Sebastien Hertz7ec2f1c2014-03-27 20:06:47 +01003193 VLOG(jdwp) << "Process deoptimization request #" << req_index++;
Sebastien Hertz4d25df32014-03-21 17:44:46 +01003194 ProcessDeoptimizationRequest(request);
3195 }
3196 deoptimization_requests_.clear();
3197 }
Sebastien Hertz138dbfc2013-12-04 18:15:25 +01003198 CHECK_EQ(self->SetStateUnsafe(old_state), kRunnable);
3199 runtime->GetThreadList()->ResumeAll();
3200 self->TransitionFromSuspendedToRunnable();
3201}
3202
Sebastien Hertza76a6d42014-03-20 16:40:17 +01003203static bool IsMethodPossiblyInlined(Thread* self, mirror::ArtMethod* m)
3204 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07003205 const DexFile::CodeItem* code_item = m->GetCodeItem();
Sebastien Hertza76a6d42014-03-20 16:40:17 +01003206 if (code_item == nullptr) {
3207 // TODO We should not be asked to watch location in a native or abstract method so the code item
3208 // should never be null. We could just check we never encounter this case.
3209 return false;
Sebastien Hertz138dbfc2013-12-04 18:15:25 +01003210 }
Sebastien Hertz4d1e9ab2014-09-18 16:03:34 +02003211 // Note: method verifier may cause thread suspension.
3212 self->AssertThreadSuspensionIsAllowable();
Hiroshi Yamauchidc376172014-08-22 11:13:12 -07003213 StackHandleScope<3> hs(self);
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07003214 mirror::Class* declaring_class = m->GetDeclaringClass();
3215 Handle<mirror::DexCache> dex_cache(hs.NewHandle(declaring_class->GetDexCache()));
3216 Handle<mirror::ClassLoader> class_loader(hs.NewHandle(declaring_class->GetClassLoader()));
Hiroshi Yamauchidc376172014-08-22 11:13:12 -07003217 Handle<mirror::ArtMethod> method(hs.NewHandle(m));
Ian Rogers7b078e82014-09-10 14:44:24 -07003218 verifier::MethodVerifier verifier(self, dex_cache->GetDexFile(), dex_cache, class_loader,
Hiroshi Yamauchidc376172014-08-22 11:13:12 -07003219 &m->GetClassDef(), code_item, m->GetDexMethodIndex(), method,
Mathieu Chartier4306ef82014-12-19 18:41:47 -08003220 m->GetAccessFlags(), false, true, false, true);
Sebastien Hertza76a6d42014-03-20 16:40:17 +01003221 // Note: we don't need to verify the method.
3222 return InlineMethodAnalyser::AnalyseMethodCode(&verifier, nullptr);
3223}
Sebastien Hertz138dbfc2013-12-04 18:15:25 +01003224
Sebastien Hertza76a6d42014-03-20 16:40:17 +01003225static const Breakpoint* FindFirstBreakpointForMethod(mirror::ArtMethod* m)
Sebastien Hertzed2be172014-08-19 15:33:43 +02003226 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_, Locks::breakpoint_lock_) {
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003227 for (Breakpoint& breakpoint : gBreakpoints) {
3228 if (breakpoint.Method() == m) {
Sebastien Hertza76a6d42014-03-20 16:40:17 +01003229 return &breakpoint;
3230 }
3231 }
3232 return nullptr;
3233}
3234
Mathieu Chartierd8565452015-03-26 09:41:50 -07003235bool Dbg::MethodHasAnyBreakpoints(mirror::ArtMethod* method) {
3236 ReaderMutexLock mu(Thread::Current(), *Locks::breakpoint_lock_);
3237 return FindFirstBreakpointForMethod(method) != nullptr;
3238}
3239
Sebastien Hertza76a6d42014-03-20 16:40:17 +01003240// Sanity checks all existing breakpoints on the same method.
Sebastien Hertzf3928792014-11-17 19:00:37 +01003241static void SanityCheckExistingBreakpoints(mirror::ArtMethod* m,
3242 DeoptimizationRequest::Kind deoptimization_kind)
Sebastien Hertzed2be172014-08-19 15:33:43 +02003243 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_, Locks::breakpoint_lock_) {
Sebastien Hertz4d1e9ab2014-09-18 16:03:34 +02003244 for (const Breakpoint& breakpoint : gBreakpoints) {
Sebastien Hertzf3928792014-11-17 19:00:37 +01003245 if (breakpoint.Method() == m) {
3246 CHECK_EQ(deoptimization_kind, breakpoint.GetDeoptimizationKind());
3247 }
Sebastien Hertz4d1e9ab2014-09-18 16:03:34 +02003248 }
Sebastien Hertzf3928792014-11-17 19:00:37 +01003249 instrumentation::Instrumentation* instrumentation = Runtime::Current()->GetInstrumentation();
3250 if (deoptimization_kind == DeoptimizationRequest::kFullDeoptimization) {
Sebastien Hertz4d1e9ab2014-09-18 16:03:34 +02003251 // We should have deoptimized everything but not "selectively" deoptimized this method.
Sebastien Hertzf3928792014-11-17 19:00:37 +01003252 CHECK(instrumentation->AreAllMethodsDeoptimized());
3253 CHECK(!instrumentation->IsDeoptimized(m));
3254 } else if (deoptimization_kind == DeoptimizationRequest::kSelectiveDeoptimization) {
Sebastien Hertz4d1e9ab2014-09-18 16:03:34 +02003255 // We should have "selectively" deoptimized this method.
3256 // Note: while we have not deoptimized everything for this method, we may have done it for
3257 // another event.
Sebastien Hertzf3928792014-11-17 19:00:37 +01003258 CHECK(instrumentation->IsDeoptimized(m));
3259 } else {
3260 // This method does not require deoptimization.
3261 CHECK_EQ(deoptimization_kind, DeoptimizationRequest::kNothing);
3262 CHECK(!instrumentation->IsDeoptimized(m));
3263 }
3264}
3265
Sebastien Hertzabe93e02014-12-17 16:35:50 +01003266// Returns the deoptimization kind required to set a breakpoint in a method.
3267// If a breakpoint has already been set, we also return the first breakpoint
3268// through the given 'existing_brkpt' pointer.
Sebastien Hertzf3928792014-11-17 19:00:37 +01003269static DeoptimizationRequest::Kind GetRequiredDeoptimizationKind(Thread* self,
Sebastien Hertzabe93e02014-12-17 16:35:50 +01003270 mirror::ArtMethod* m,
3271 const Breakpoint** existing_brkpt)
Sebastien Hertzf3928792014-11-17 19:00:37 +01003272 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
3273 if (!Dbg::RequiresDeoptimization()) {
3274 // We already run in interpreter-only mode so we don't need to deoptimize anything.
3275 VLOG(jdwp) << "No need for deoptimization when fully running with interpreter for method "
3276 << PrettyMethod(m);
3277 return DeoptimizationRequest::kNothing;
3278 }
Sebastien Hertzabe93e02014-12-17 16:35:50 +01003279 const Breakpoint* first_breakpoint;
Sebastien Hertzf3928792014-11-17 19:00:37 +01003280 {
3281 ReaderMutexLock mu(self, *Locks::breakpoint_lock_);
Sebastien Hertzabe93e02014-12-17 16:35:50 +01003282 first_breakpoint = FindFirstBreakpointForMethod(m);
3283 *existing_brkpt = first_breakpoint;
Sebastien Hertzf3928792014-11-17 19:00:37 +01003284 }
Sebastien Hertzabe93e02014-12-17 16:35:50 +01003285
3286 if (first_breakpoint == nullptr) {
Sebastien Hertzf3928792014-11-17 19:00:37 +01003287 // There is no breakpoint on this method yet: we need to deoptimize. If this method may be
3288 // inlined, we deoptimize everything; otherwise we deoptimize only this method.
3289 // Note: IsMethodPossiblyInlined goes into the method verifier and may cause thread suspension.
3290 // Therefore we must not hold any lock when we call it.
3291 bool need_full_deoptimization = IsMethodPossiblyInlined(self, m);
3292 if (need_full_deoptimization) {
3293 VLOG(jdwp) << "Need full deoptimization because of possible inlining of method "
3294 << PrettyMethod(m);
3295 return DeoptimizationRequest::kFullDeoptimization;
3296 } else {
3297 // We don't need to deoptimize if the method has not been compiled.
3298 ClassLinker* const class_linker = Runtime::Current()->GetClassLinker();
3299 const bool is_compiled = class_linker->GetOatMethodQuickCodeFor(m) != nullptr;
3300 if (is_compiled) {
Sebastien Hertz6963e442014-11-26 22:11:27 +01003301 // If the method may be called through its direct code pointer (without loading
3302 // its updated entrypoint), we need full deoptimization to not miss the breakpoint.
3303 if (class_linker->MayBeCalledWithDirectCodePointer(m)) {
3304 VLOG(jdwp) << "Need full deoptimization because of possible direct code call "
3305 << "into image for compiled method " << PrettyMethod(m);
3306 return DeoptimizationRequest::kFullDeoptimization;
3307 } else {
3308 VLOG(jdwp) << "Need selective deoptimization for compiled method " << PrettyMethod(m);
3309 return DeoptimizationRequest::kSelectiveDeoptimization;
3310 }
Sebastien Hertzf3928792014-11-17 19:00:37 +01003311 } else {
3312 // Method is not compiled: we don't need to deoptimize.
3313 VLOG(jdwp) << "No need for deoptimization for non-compiled method " << PrettyMethod(m);
3314 return DeoptimizationRequest::kNothing;
3315 }
3316 }
3317 } else {
3318 // There is at least one breakpoint for this method: we don't need to deoptimize.
3319 // Let's check that all breakpoints are configured the same way for deoptimization.
3320 VLOG(jdwp) << "Breakpoint already set: no deoptimization is required";
Sebastien Hertzabe93e02014-12-17 16:35:50 +01003321 DeoptimizationRequest::Kind deoptimization_kind = first_breakpoint->GetDeoptimizationKind();
Sebastien Hertzf3928792014-11-17 19:00:37 +01003322 if (kIsDebugBuild) {
3323 ReaderMutexLock mu(self, *Locks::breakpoint_lock_);
3324 SanityCheckExistingBreakpoints(m, deoptimization_kind);
3325 }
3326 return DeoptimizationRequest::kNothing;
Sebastien Hertz138dbfc2013-12-04 18:15:25 +01003327 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -07003328}
3329
Sebastien Hertza76a6d42014-03-20 16:40:17 +01003330// Installs a breakpoint at the specified location. Also indicates through the deoptimization
3331// request if we need to deoptimize.
3332void Dbg::WatchLocation(const JDWP::JdwpLocation* location, DeoptimizationRequest* req) {
3333 Thread* const self = Thread::Current();
Brian Carlstromea46f952013-07-30 01:26:50 -07003334 mirror::ArtMethod* m = FromMethodId(location->method_id);
Sebastien Hertza76a6d42014-03-20 16:40:17 +01003335 DCHECK(m != nullptr) << "No method for method id " << location->method_id;
Sebastien Hertz138dbfc2013-12-04 18:15:25 +01003336
Sebastien Hertzabe93e02014-12-17 16:35:50 +01003337 const Breakpoint* existing_breakpoint = nullptr;
3338 const DeoptimizationRequest::Kind deoptimization_kind =
3339 GetRequiredDeoptimizationKind(self, m, &existing_breakpoint);
Sebastien Hertzf3928792014-11-17 19:00:37 +01003340 req->SetKind(deoptimization_kind);
3341 if (deoptimization_kind == DeoptimizationRequest::kSelectiveDeoptimization) {
3342 req->SetMethod(m);
Sebastien Hertza76a6d42014-03-20 16:40:17 +01003343 } else {
Sebastien Hertzf3928792014-11-17 19:00:37 +01003344 CHECK(deoptimization_kind == DeoptimizationRequest::kNothing ||
3345 deoptimization_kind == DeoptimizationRequest::kFullDeoptimization);
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003346 req->SetMethod(nullptr);
Sebastien Hertz138dbfc2013-12-04 18:15:25 +01003347 }
3348
Sebastien Hertz4d1e9ab2014-09-18 16:03:34 +02003349 {
3350 WriterMutexLock mu(self, *Locks::breakpoint_lock_);
Sebastien Hertzabe93e02014-12-17 16:35:50 +01003351 // If there is at least one existing breakpoint on the same method, the new breakpoint
3352 // must have the same deoptimization kind than the existing breakpoint(s).
3353 DeoptimizationRequest::Kind breakpoint_deoptimization_kind;
3354 if (existing_breakpoint != nullptr) {
3355 breakpoint_deoptimization_kind = existing_breakpoint->GetDeoptimizationKind();
3356 } else {
3357 breakpoint_deoptimization_kind = deoptimization_kind;
3358 }
3359 gBreakpoints.push_back(Breakpoint(m, location->dex_pc, breakpoint_deoptimization_kind));
Sebastien Hertz4d1e9ab2014-09-18 16:03:34 +02003360 VLOG(jdwp) << "Set breakpoint #" << (gBreakpoints.size() - 1) << ": "
3361 << gBreakpoints[gBreakpoints.size() - 1];
3362 }
Sebastien Hertza76a6d42014-03-20 16:40:17 +01003363}
3364
3365// Uninstalls a breakpoint at the specified location. Also indicates through the deoptimization
3366// request if we need to undeoptimize.
3367void Dbg::UnwatchLocation(const JDWP::JdwpLocation* location, DeoptimizationRequest* req) {
Sebastien Hertzed2be172014-08-19 15:33:43 +02003368 WriterMutexLock mu(Thread::Current(), *Locks::breakpoint_lock_);
Sebastien Hertza76a6d42014-03-20 16:40:17 +01003369 mirror::ArtMethod* m = FromMethodId(location->method_id);
3370 DCHECK(m != nullptr) << "No method for method id " << location->method_id;
Sebastien Hertzf3928792014-11-17 19:00:37 +01003371 DeoptimizationRequest::Kind deoptimization_kind = DeoptimizationRequest::kNothing;
Sebastien Hertza76a6d42014-03-20 16:40:17 +01003372 for (size_t i = 0, e = gBreakpoints.size(); i < e; ++i) {
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003373 if (gBreakpoints[i].DexPc() == location->dex_pc && gBreakpoints[i].Method() == m) {
Sebastien Hertza76a6d42014-03-20 16:40:17 +01003374 VLOG(jdwp) << "Removed breakpoint #" << i << ": " << gBreakpoints[i];
Sebastien Hertzf3928792014-11-17 19:00:37 +01003375 deoptimization_kind = gBreakpoints[i].GetDeoptimizationKind();
3376 DCHECK_EQ(deoptimization_kind == DeoptimizationRequest::kSelectiveDeoptimization,
3377 Runtime::Current()->GetInstrumentation()->IsDeoptimized(m));
Sebastien Hertza76a6d42014-03-20 16:40:17 +01003378 gBreakpoints.erase(gBreakpoints.begin() + i);
3379 break;
3380 }
3381 }
3382 const Breakpoint* const existing_breakpoint = FindFirstBreakpointForMethod(m);
3383 if (existing_breakpoint == nullptr) {
3384 // There is no more breakpoint on this method: we need to undeoptimize.
Sebastien Hertzf3928792014-11-17 19:00:37 +01003385 if (deoptimization_kind == DeoptimizationRequest::kFullDeoptimization) {
Sebastien Hertza76a6d42014-03-20 16:40:17 +01003386 // This method required full deoptimization: we need to undeoptimize everything.
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003387 req->SetKind(DeoptimizationRequest::kFullUndeoptimization);
3388 req->SetMethod(nullptr);
Sebastien Hertzf3928792014-11-17 19:00:37 +01003389 } else if (deoptimization_kind == DeoptimizationRequest::kSelectiveDeoptimization) {
Sebastien Hertza76a6d42014-03-20 16:40:17 +01003390 // This method required selective deoptimization: we need to undeoptimize only that method.
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003391 req->SetKind(DeoptimizationRequest::kSelectiveUndeoptimization);
3392 req->SetMethod(m);
Sebastien Hertzf3928792014-11-17 19:00:37 +01003393 } else {
3394 // This method had no need for deoptimization: do nothing.
3395 CHECK_EQ(deoptimization_kind, DeoptimizationRequest::kNothing);
3396 req->SetKind(DeoptimizationRequest::kNothing);
3397 req->SetMethod(nullptr);
Sebastien Hertza76a6d42014-03-20 16:40:17 +01003398 }
3399 } else {
3400 // There is at least one breakpoint for this method: we don't need to undeoptimize.
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003401 req->SetKind(DeoptimizationRequest::kNothing);
3402 req->SetMethod(nullptr);
Sebastien Hertz4d1e9ab2014-09-18 16:03:34 +02003403 if (kIsDebugBuild) {
Sebastien Hertzf3928792014-11-17 19:00:37 +01003404 SanityCheckExistingBreakpoints(m, deoptimization_kind);
Sebastien Hertz4d1e9ab2014-09-18 16:03:34 +02003405 }
Elliott Hughes86964332012-02-15 19:37:42 -08003406 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -07003407}
3408
Daniel Mihalyieb076692014-08-22 17:33:31 +02003409bool Dbg::IsForcedInterpreterNeededForCallingImpl(Thread* thread, mirror::ArtMethod* m) {
3410 const SingleStepControl* const ssc = thread->GetSingleStepControl();
3411 if (ssc == nullptr) {
3412 // If we are not single-stepping, then we don't have to force interpreter.
3413 return false;
3414 }
3415 if (Runtime::Current()->GetInstrumentation()->InterpretOnly()) {
3416 // If we are in interpreter only mode, then we don't have to force interpreter.
3417 return false;
3418 }
3419
3420 if (!m->IsNative() && !m->IsProxyMethod()) {
3421 // If we want to step into a method, then we have to force interpreter on that call.
3422 if (ssc->GetStepDepth() == JDWP::SD_INTO) {
3423 return true;
3424 }
3425 }
3426 return false;
3427}
3428
3429bool Dbg::IsForcedInterpreterNeededForResolutionImpl(Thread* thread, mirror::ArtMethod* m) {
3430 instrumentation::Instrumentation* const instrumentation =
3431 Runtime::Current()->GetInstrumentation();
3432 // If we are in interpreter only mode, then we don't have to force interpreter.
3433 if (instrumentation->InterpretOnly()) {
3434 return false;
3435 }
3436 // We can only interpret pure Java method.
3437 if (m->IsNative() || m->IsProxyMethod()) {
3438 return false;
3439 }
3440 const SingleStepControl* const ssc = thread->GetSingleStepControl();
3441 if (ssc != nullptr) {
3442 // If we want to step into a method, then we have to force interpreter on that call.
3443 if (ssc->GetStepDepth() == JDWP::SD_INTO) {
3444 return true;
3445 }
3446 // If we are stepping out from a static initializer, by issuing a step
3447 // in or step over, that was implicitly invoked by calling a static method,
3448 // then we need to step into that method. Having a lower stack depth than
3449 // the one the single step control has indicates that the step originates
3450 // from the static initializer.
3451 if (ssc->GetStepDepth() != JDWP::SD_OUT &&
3452 ssc->GetStackDepth() > GetStackDepth(thread)) {
3453 return true;
3454 }
3455 }
3456 // There are cases where we have to force interpreter on deoptimized methods,
3457 // because in some cases the call will not be performed by invoking an entry
3458 // point that has been replaced by the deoptimization, but instead by directly
3459 // invoking the compiled code of the method, for example.
3460 return instrumentation->IsDeoptimized(m);
3461}
3462
3463bool Dbg::IsForcedInstrumentationNeededForResolutionImpl(Thread* thread, mirror::ArtMethod* m) {
Mathieu Chartier2cebb242015-04-21 16:50:40 -07003464 // The upcall can be null and in that case we don't need to do anything.
Daniel Mihalyieb076692014-08-22 17:33:31 +02003465 if (m == nullptr) {
3466 return false;
3467 }
3468 instrumentation::Instrumentation* const instrumentation =
3469 Runtime::Current()->GetInstrumentation();
3470 // If we are in interpreter only mode, then we don't have to force interpreter.
3471 if (instrumentation->InterpretOnly()) {
3472 return false;
3473 }
3474 // We can only interpret pure Java method.
3475 if (m->IsNative() || m->IsProxyMethod()) {
3476 return false;
3477 }
3478 const SingleStepControl* const ssc = thread->GetSingleStepControl();
3479 if (ssc != nullptr) {
3480 // If we are stepping out from a static initializer, by issuing a step
3481 // out, that was implicitly invoked by calling a static method, then we
3482 // need to step into the caller of that method. Having a lower stack
3483 // depth than the one the single step control has indicates that the
3484 // step originates from the static initializer.
3485 if (ssc->GetStepDepth() == JDWP::SD_OUT &&
3486 ssc->GetStackDepth() > GetStackDepth(thread)) {
3487 return true;
3488 }
3489 }
3490 // If we are returning from a static intializer, that was implicitly
3491 // invoked by calling a static method and the caller is deoptimized,
3492 // then we have to deoptimize the stack without forcing interpreter
3493 // on the static method that was called originally. This problem can
3494 // be solved easily by forcing instrumentation on the called method,
3495 // because the instrumentation exit hook will recognise the need of
3496 // stack deoptimization by calling IsForcedInterpreterNeededForUpcall.
3497 return instrumentation->IsDeoptimized(m);
3498}
3499
3500bool Dbg::IsForcedInterpreterNeededForUpcallImpl(Thread* thread, mirror::ArtMethod* m) {
Mathieu Chartier2cebb242015-04-21 16:50:40 -07003501 // The upcall can be null and in that case we don't need to do anything.
Daniel Mihalyieb076692014-08-22 17:33:31 +02003502 if (m == nullptr) {
3503 return false;
3504 }
3505 instrumentation::Instrumentation* const instrumentation =
3506 Runtime::Current()->GetInstrumentation();
3507 // If we are in interpreter only mode, then we don't have to force interpreter.
3508 if (instrumentation->InterpretOnly()) {
3509 return false;
3510 }
3511 // We can only interpret pure Java method.
3512 if (m->IsNative() || m->IsProxyMethod()) {
3513 return false;
3514 }
3515 const SingleStepControl* const ssc = thread->GetSingleStepControl();
3516 if (ssc != nullptr) {
3517 // The debugger is not interested in what is happening under the level
3518 // of the step, thus we only force interpreter when we are not below of
3519 // the step.
3520 if (ssc->GetStackDepth() >= GetStackDepth(thread)) {
3521 return true;
3522 }
3523 }
3524 // We have to require stack deoptimization if the upcall is deoptimized.
3525 return instrumentation->IsDeoptimized(m);
3526}
3527
Jeff Hao449db332013-04-12 18:30:52 -07003528// Scoped utility class to suspend a thread so that we may do tasks such as walk its stack. Doesn't
3529// cause suspension if the thread is the current thread.
3530class ScopedThreadSuspension {
3531 public:
Ian Rogers33e95662013-05-20 20:29:14 -07003532 ScopedThreadSuspension(Thread* self, JDWP::ObjectId thread_id)
Sebastien Hertz52d131d2014-03-13 16:17:40 +01003533 LOCKS_EXCLUDED(Locks::thread_list_lock_)
Ian Rogers33e95662013-05-20 20:29:14 -07003534 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) :
Ian Rogersf3d874c2014-07-17 18:52:42 -07003535 thread_(nullptr),
Jeff Hao449db332013-04-12 18:30:52 -07003536 error_(JDWP::ERR_NONE),
3537 self_suspend_(false),
Ian Rogers33e95662013-05-20 20:29:14 -07003538 other_suspend_(false) {
Jeff Hao449db332013-04-12 18:30:52 -07003539 ScopedObjectAccessUnchecked soa(self);
Sebastien Hertz69206392015-04-07 15:54:25 +02003540 thread_ = DecodeThread(soa, thread_id, &error_);
Jeff Hao449db332013-04-12 18:30:52 -07003541 if (error_ == JDWP::ERR_NONE) {
3542 if (thread_ == soa.Self()) {
3543 self_suspend_ = true;
3544 } else {
3545 soa.Self()->TransitionFromRunnableToSuspended(kWaitingForDebuggerSuspension);
Sebastien Hertz6995c602014-09-09 12:10:13 +02003546 jobject thread_peer = Dbg::GetObjectRegistry()->GetJObject(thread_id);
Jeff Hao449db332013-04-12 18:30:52 -07003547 bool timed_out;
Ian Rogers4ad5cd32014-11-11 23:08:07 -08003548 ThreadList* thread_list = Runtime::Current()->GetThreadList();
3549 Thread* suspended_thread = thread_list->SuspendThreadByPeer(thread_peer, true, true,
3550 &timed_out);
Jeff Hao449db332013-04-12 18:30:52 -07003551 CHECK_EQ(soa.Self()->TransitionFromSuspendedToRunnable(), kWaitingForDebuggerSuspension);
Ian Rogersf3d874c2014-07-17 18:52:42 -07003552 if (suspended_thread == nullptr) {
Jeff Hao449db332013-04-12 18:30:52 -07003553 // Thread terminated from under us while suspending.
3554 error_ = JDWP::ERR_INVALID_THREAD;
3555 } else {
3556 CHECK_EQ(suspended_thread, thread_);
3557 other_suspend_ = true;
3558 }
3559 }
3560 }
Elliott Hughes2435a572012-02-17 16:07:41 -08003561 }
Elliott Hughes86964332012-02-15 19:37:42 -08003562
Jeff Hao449db332013-04-12 18:30:52 -07003563 Thread* GetThread() const {
3564 return thread_;
3565 }
3566
3567 JDWP::JdwpError GetError() const {
3568 return error_;
3569 }
3570
3571 ~ScopedThreadSuspension() {
3572 if (other_suspend_) {
3573 Runtime::Current()->GetThreadList()->Resume(thread_, true);
3574 }
3575 }
3576
3577 private:
3578 Thread* thread_;
3579 JDWP::JdwpError error_;
3580 bool self_suspend_;
3581 bool other_suspend_;
3582};
3583
3584JDWP::JdwpError Dbg::ConfigureStep(JDWP::ObjectId thread_id, JDWP::JdwpStepSize step_size,
3585 JDWP::JdwpStepDepth step_depth) {
3586 Thread* self = Thread::Current();
3587 ScopedThreadSuspension sts(self, thread_id);
3588 if (sts.GetError() != JDWP::ERR_NONE) {
3589 return sts.GetError();
3590 }
3591
Sebastien Hertz597c4f02015-01-26 17:37:14 +01003592 // Work out what ArtMethod* we're in, the current line number, and how deep the stack currently
Elliott Hughes2435a572012-02-17 16:07:41 -08003593 // is for step-out.
Ian Rogers0399dde2012-06-06 17:09:28 -07003594 struct SingleStepStackVisitor : public StackVisitor {
Sebastien Hertz597c4f02015-01-26 17:37:14 +01003595 explicit SingleStepStackVisitor(Thread* thread) SHARED_LOCKS_REQUIRED(Locks::mutator_lock_)
Nicolas Geoffray8e5bd182015-05-06 11:34:34 +01003596 : StackVisitor(thread, nullptr, StackVisitor::StackWalkKind::kIncludeInlinedFrames),
3597 stack_depth(0),
3598 method(nullptr),
3599 line_number(-1) {}
Ian Rogersca190662012-06-26 15:45:57 -07003600
Ian Rogers00f7d0e2012-07-19 15:28:27 -07003601 // TODO: Enable annotalysis. We know lock is held in constructor, but abstraction confuses
3602 // annotalysis.
3603 bool VisitFrame() NO_THREAD_SAFETY_ANALYSIS {
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01003604 mirror::ArtMethod* m = GetMethod();
Ian Rogers0399dde2012-06-06 17:09:28 -07003605 if (!m->IsRuntimeMethod()) {
Sebastien Hertz597c4f02015-01-26 17:37:14 +01003606 ++stack_depth;
3607 if (method == nullptr) {
Ian Rogersef7d42f2014-01-06 12:55:46 -08003608 mirror::DexCache* dex_cache = m->GetDeclaringClass()->GetDexCache();
Sebastien Hertz597c4f02015-01-26 17:37:14 +01003609 method = m;
Ian Rogersc0542af2014-09-03 16:16:56 -07003610 if (dex_cache != nullptr) {
Ian Rogers4445a7e2012-10-05 17:19:13 -07003611 const DexFile& dex_file = *dex_cache->GetDexFile();
Sebastien Hertz597c4f02015-01-26 17:37:14 +01003612 line_number = dex_file.GetLineNumFromPC(m, GetDexPc());
Elliott Hughes2435a572012-02-17 16:07:41 -08003613 }
Elliott Hughes86964332012-02-15 19:37:42 -08003614 }
3615 }
Elliott Hughes530fa002012-03-12 11:44:49 -07003616 return true;
Elliott Hughes86964332012-02-15 19:37:42 -08003617 }
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01003618
Sebastien Hertz597c4f02015-01-26 17:37:14 +01003619 int stack_depth;
3620 mirror::ArtMethod* method;
3621 int32_t line_number;
Elliott Hughes86964332012-02-15 19:37:42 -08003622 };
Jeff Hao449db332013-04-12 18:30:52 -07003623
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01003624 Thread* const thread = sts.GetThread();
Sebastien Hertz597c4f02015-01-26 17:37:14 +01003625 SingleStepStackVisitor visitor(thread);
Ian Rogers0399dde2012-06-06 17:09:28 -07003626 visitor.WalkStack();
Elliott Hughes86964332012-02-15 19:37:42 -08003627
Elliott Hughes2435a572012-02-17 16:07:41 -08003628 // Find the dex_pc values that correspond to the current line, for line-based single-stepping.
Elliott Hughes2435a572012-02-17 16:07:41 -08003629 struct DebugCallbackContext {
Sebastien Hertz597c4f02015-01-26 17:37:14 +01003630 explicit DebugCallbackContext(SingleStepControl* single_step_control_cb,
3631 int32_t line_number_cb, const DexFile::CodeItem* code_item)
Andreas Gampe277ccbd2014-11-03 21:36:10 -08003632 : single_step_control_(single_step_control_cb), line_number_(line_number_cb),
3633 code_item_(code_item), last_pc_valid(false), last_pc(0) {
Elliott Hughes2435a572012-02-17 16:07:41 -08003634 }
3635
Andreas Gampe277ccbd2014-11-03 21:36:10 -08003636 static bool Callback(void* raw_context, uint32_t address, uint32_t line_number_cb) {
Elliott Hughes2435a572012-02-17 16:07:41 -08003637 DebugCallbackContext* context = reinterpret_cast<DebugCallbackContext*>(raw_context);
Andreas Gampe277ccbd2014-11-03 21:36:10 -08003638 if (static_cast<int32_t>(line_number_cb) == context->line_number_) {
Elliott Hughes2435a572012-02-17 16:07:41 -08003639 if (!context->last_pc_valid) {
3640 // Everything from this address until the next line change is ours.
3641 context->last_pc = address;
3642 context->last_pc_valid = true;
3643 }
3644 // Otherwise, if we're already in a valid range for this line,
3645 // just keep going (shouldn't really happen)...
Brian Carlstrom7934ac22013-07-26 10:54:15 -07003646 } else if (context->last_pc_valid) { // and the line number is new
Elliott Hughes2435a572012-02-17 16:07:41 -08003647 // Add everything from the last entry up until here to the set
3648 for (uint32_t dex_pc = context->last_pc; dex_pc < address; ++dex_pc) {
Sebastien Hertz597c4f02015-01-26 17:37:14 +01003649 context->single_step_control_->AddDexPc(dex_pc);
Elliott Hughes2435a572012-02-17 16:07:41 -08003650 }
3651 context->last_pc_valid = false;
3652 }
Brian Carlstrom7934ac22013-07-26 10:54:15 -07003653 return false; // There may be multiple entries for any given line.
Elliott Hughes2435a572012-02-17 16:07:41 -08003654 }
3655
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01003656 ~DebugCallbackContext() {
Elliott Hughes2435a572012-02-17 16:07:41 -08003657 // If the line number was the last in the position table...
3658 if (last_pc_valid) {
Sebastien Hertzbb43b432014-04-14 11:59:08 +02003659 size_t end = code_item_->insns_size_in_code_units_;
Elliott Hughes2435a572012-02-17 16:07:41 -08003660 for (uint32_t dex_pc = last_pc; dex_pc < end; ++dex_pc) {
Sebastien Hertz597c4f02015-01-26 17:37:14 +01003661 single_step_control_->AddDexPc(dex_pc);
Elliott Hughes2435a572012-02-17 16:07:41 -08003662 }
3663 }
3664 }
3665
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01003666 SingleStepControl* const single_step_control_;
3667 const int32_t line_number_;
Sebastien Hertzbb43b432014-04-14 11:59:08 +02003668 const DexFile::CodeItem* const code_item_;
Elliott Hughes2435a572012-02-17 16:07:41 -08003669 bool last_pc_valid;
3670 uint32_t last_pc;
3671 };
Sebastien Hertz597c4f02015-01-26 17:37:14 +01003672
3673 // Allocate single step.
Sebastien Hertz1558b572015-02-25 15:05:59 +01003674 SingleStepControl* single_step_control =
3675 new (std::nothrow) SingleStepControl(step_size, step_depth,
3676 visitor.stack_depth, visitor.method);
3677 if (single_step_control == nullptr) {
3678 LOG(ERROR) << "Failed to allocate SingleStepControl";
3679 return JDWP::ERR_OUT_OF_MEMORY;
3680 }
3681
Sebastien Hertz597c4f02015-01-26 17:37:14 +01003682 mirror::ArtMethod* m = single_step_control->GetMethod();
3683 const int32_t line_number = visitor.line_number;
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01003684 if (!m->IsNative()) {
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07003685 const DexFile::CodeItem* const code_item = m->GetCodeItem();
Sebastien Hertzbb43b432014-04-14 11:59:08 +02003686 DebugCallbackContext context(single_step_control, line_number, code_item);
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07003687 m->GetDexFile()->DecodeDebugInfo(code_item, m->IsStatic(), m->GetDexMethodIndex(),
Ian Rogersc0542af2014-09-03 16:16:56 -07003688 DebugCallbackContext::Callback, nullptr, &context);
Elliott Hughes3e2e1a22012-02-21 11:33:41 -08003689 }
Elliott Hughes2435a572012-02-17 16:07:41 -08003690
Sebastien Hertz597c4f02015-01-26 17:37:14 +01003691 // Activate single-step in the thread.
3692 thread->ActivateSingleStepControl(single_step_control);
Elliott Hughes86964332012-02-15 19:37:42 -08003693
Elliott Hughes2435a572012-02-17 16:07:41 -08003694 if (VLOG_IS_ON(jdwp)) {
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01003695 VLOG(jdwp) << "Single-step thread: " << *thread;
Sebastien Hertz597c4f02015-01-26 17:37:14 +01003696 VLOG(jdwp) << "Single-step step size: " << single_step_control->GetStepSize();
3697 VLOG(jdwp) << "Single-step step depth: " << single_step_control->GetStepDepth();
3698 VLOG(jdwp) << "Single-step current method: " << PrettyMethod(single_step_control->GetMethod());
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01003699 VLOG(jdwp) << "Single-step current line: " << line_number;
Sebastien Hertz597c4f02015-01-26 17:37:14 +01003700 VLOG(jdwp) << "Single-step current stack depth: " << single_step_control->GetStackDepth();
Elliott Hughes2435a572012-02-17 16:07:41 -08003701 VLOG(jdwp) << "Single-step dex_pc values:";
Sebastien Hertz597c4f02015-01-26 17:37:14 +01003702 for (uint32_t dex_pc : single_step_control->GetDexPcs()) {
Sebastien Hertzbb43b432014-04-14 11:59:08 +02003703 VLOG(jdwp) << StringPrintf(" %#x", dex_pc);
Elliott Hughes2435a572012-02-17 16:07:41 -08003704 }
3705 }
3706
3707 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07003708}
3709
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01003710void Dbg::UnconfigureStep(JDWP::ObjectId thread_id) {
3711 ScopedObjectAccessUnchecked soa(Thread::Current());
Ian Rogersc0542af2014-09-03 16:16:56 -07003712 JDWP::JdwpError error;
3713 Thread* thread = DecodeThread(soa, thread_id, &error);
Sebastien Hertz87118ed2013-11-26 17:57:18 +01003714 if (error == JDWP::ERR_NONE) {
Sebastien Hertz597c4f02015-01-26 17:37:14 +01003715 thread->DeactivateSingleStepControl();
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01003716 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -07003717}
3718
Elliott Hughes45651fd2012-02-21 15:48:20 -08003719static char JdwpTagToShortyChar(JDWP::JdwpTag tag) {
3720 switch (tag) {
3721 default:
3722 LOG(FATAL) << "unknown JDWP tag: " << PrintableChar(tag);
Ian Rogersfc787ec2014-10-09 21:56:44 -07003723 UNREACHABLE();
Elliott Hughes45651fd2012-02-21 15:48:20 -08003724
3725 // Primitives.
3726 case JDWP::JT_BYTE: return 'B';
3727 case JDWP::JT_CHAR: return 'C';
3728 case JDWP::JT_FLOAT: return 'F';
3729 case JDWP::JT_DOUBLE: return 'D';
3730 case JDWP::JT_INT: return 'I';
3731 case JDWP::JT_LONG: return 'J';
3732 case JDWP::JT_SHORT: return 'S';
3733 case JDWP::JT_VOID: return 'V';
3734 case JDWP::JT_BOOLEAN: return 'Z';
3735
3736 // Reference types.
3737 case JDWP::JT_ARRAY:
3738 case JDWP::JT_OBJECT:
3739 case JDWP::JT_STRING:
3740 case JDWP::JT_THREAD:
3741 case JDWP::JT_THREAD_GROUP:
3742 case JDWP::JT_CLASS_LOADER:
3743 case JDWP::JT_CLASS_OBJECT:
3744 return 'L';
3745 }
3746}
3747
Elliott Hughes88d63092013-01-09 09:55:54 -08003748JDWP::JdwpError Dbg::InvokeMethod(JDWP::ObjectId thread_id, JDWP::ObjectId object_id,
3749 JDWP::RefTypeId class_id, JDWP::MethodId method_id,
Ian Rogers00f7d0e2012-07-19 15:28:27 -07003750 uint32_t arg_count, uint64_t* arg_values,
3751 JDWP::JdwpTag* arg_types, uint32_t options,
3752 JDWP::JdwpTag* pResultTag, uint64_t* pResultValue,
3753 JDWP::ObjectId* pExceptionId) {
Elliott Hughesd07986f2011-12-06 18:27:45 -08003754 ThreadList* thread_list = Runtime::Current()->GetThreadList();
3755
Ian Rogersc0542af2014-09-03 16:16:56 -07003756 Thread* targetThread = nullptr;
Sebastien Hertz1558b572015-02-25 15:05:59 +01003757 std::unique_ptr<DebugInvokeReq> req;
Ian Rogers00f7d0e2012-07-19 15:28:27 -07003758 Thread* self = Thread::Current();
Elliott Hughesd07986f2011-12-06 18:27:45 -08003759 {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07003760 ScopedObjectAccessUnchecked soa(self);
Ian Rogersc0542af2014-09-03 16:16:56 -07003761 JDWP::JdwpError error;
3762 targetThread = DecodeThread(soa, thread_id, &error);
Elliott Hughes221229c2013-01-08 18:17:50 -08003763 if (error != JDWP::ERR_NONE) {
3764 LOG(ERROR) << "InvokeMethod request for invalid thread id " << thread_id;
3765 return error;
Elliott Hughesd07986f2011-12-06 18:27:45 -08003766 }
Sebastien Hertz1558b572015-02-25 15:05:59 +01003767 if (targetThread->GetInvokeReq() != nullptr) {
3768 // Thread is already invoking a method on behalf of the debugger.
3769 LOG(ERROR) << "InvokeMethod request for thread already invoking a method: " << *targetThread;
3770 return JDWP::ERR_ALREADY_INVOKING;
3771 }
3772 if (!targetThread->IsReadyForDebugInvoke()) {
3773 // Thread is not suspended by an event so it cannot invoke a method.
Elliott Hughesd07986f2011-12-06 18:27:45 -08003774 LOG(ERROR) << "InvokeMethod request for thread not stopped by event: " << *targetThread;
3775 return JDWP::ERR_INVALID_THREAD;
3776 }
3777
3778 /*
3779 * We currently have a bug where we don't successfully resume the
3780 * target thread if the suspend count is too deep. We're expected to
3781 * require one "resume" for each "suspend", but when asked to execute
3782 * a method we have to resume fully and then re-suspend it back to the
3783 * same level. (The easiest way to cause this is to type "suspend"
3784 * multiple times in jdb.)
3785 *
3786 * It's unclear what this means when the event specifies "resume all"
3787 * and some threads are suspended more deeply than others. This is
3788 * a rare problem, so for now we just prevent it from hanging forever
3789 * by rejecting the method invocation request. Without this, we will
3790 * be stuck waiting on a suspended thread.
3791 */
Ian Rogers00f7d0e2012-07-19 15:28:27 -07003792 int suspend_count;
3793 {
Ian Rogers50b35e22012-10-04 10:09:15 -07003794 MutexLock mu2(soa.Self(), *Locks::thread_suspend_count_lock_);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07003795 suspend_count = targetThread->GetSuspendCount();
3796 }
Elliott Hughesd07986f2011-12-06 18:27:45 -08003797 if (suspend_count > 1) {
3798 LOG(ERROR) << *targetThread << " suspend count too deep for method invocation: " << suspend_count;
Brian Carlstrom7934ac22013-07-26 10:54:15 -07003799 return JDWP::ERR_THREAD_SUSPENDED; // Probably not expected here.
Elliott Hughesd07986f2011-12-06 18:27:45 -08003800 }
3801
Ian Rogersc0542af2014-09-03 16:16:56 -07003802 mirror::Object* receiver = gRegistry->Get<mirror::Object*>(object_id, &error);
3803 if (error != JDWP::ERR_NONE) {
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08003804 return JDWP::ERR_INVALID_OBJECT;
3805 }
Elliott Hughes45651fd2012-02-21 15:48:20 -08003806
Sebastien Hertz1558b572015-02-25 15:05:59 +01003807 gRegistry->Get<mirror::Object*>(thread_id, &error);
Ian Rogersc0542af2014-09-03 16:16:56 -07003808 if (error != JDWP::ERR_NONE) {
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08003809 return JDWP::ERR_INVALID_OBJECT;
3810 }
Elliott Hughes45651fd2012-02-21 15:48:20 -08003811
Ian Rogersc0542af2014-09-03 16:16:56 -07003812 mirror::Class* c = DecodeClass(class_id, &error);
3813 if (c == nullptr) {
3814 return error;
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08003815 }
Elliott Hughes45651fd2012-02-21 15:48:20 -08003816
Brian Carlstromea46f952013-07-30 01:26:50 -07003817 mirror::ArtMethod* m = FromMethodId(method_id);
Ian Rogersc0542af2014-09-03 16:16:56 -07003818 if (m->IsStatic() != (receiver == nullptr)) {
Elliott Hughes45651fd2012-02-21 15:48:20 -08003819 return JDWP::ERR_INVALID_METHODID;
3820 }
3821 if (m->IsStatic()) {
3822 if (m->GetDeclaringClass() != c) {
3823 return JDWP::ERR_INVALID_METHODID;
3824 }
3825 } else {
3826 if (!m->GetDeclaringClass()->IsAssignableFrom(c)) {
3827 return JDWP::ERR_INVALID_METHODID;
3828 }
3829 }
3830
3831 // Check the argument list matches the method.
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07003832 uint32_t shorty_len = 0;
3833 const char* shorty = m->GetShorty(&shorty_len);
3834 if (shorty_len - 1 != arg_count) {
Elliott Hughes45651fd2012-02-21 15:48:20 -08003835 return JDWP::ERR_ILLEGAL_ARGUMENT;
3836 }
Elliott Hughes09201632013-04-15 15:50:07 -07003837
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07003838 {
3839 StackHandleScope<3> hs(soa.Self());
Ian Rogersa0485602014-12-02 15:48:04 -08003840 HandleWrapper<mirror::ArtMethod> h_m(hs.NewHandleWrapper(&m));
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07003841 HandleWrapper<mirror::Object> h_obj(hs.NewHandleWrapper(&receiver));
3842 HandleWrapper<mirror::Class> h_klass(hs.NewHandleWrapper(&c));
3843 const DexFile::TypeList* types = m->GetParameterTypeList();
3844 for (size_t i = 0; i < arg_count; ++i) {
3845 if (shorty[i + 1] != JdwpTagToShortyChar(arg_types[i])) {
Elliott Hughes09201632013-04-15 15:50:07 -07003846 return JDWP::ERR_ILLEGAL_ARGUMENT;
3847 }
3848
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07003849 if (shorty[i + 1] == 'L') {
3850 // Did we really get an argument of an appropriate reference type?
Ian Rogersa0485602014-12-02 15:48:04 -08003851 mirror::Class* parameter_type =
3852 h_m->GetClassFromTypeIndex(types->GetTypeItem(i).type_idx_, true);
Ian Rogersc0542af2014-09-03 16:16:56 -07003853 mirror::Object* argument = gRegistry->Get<mirror::Object*>(arg_values[i], &error);
3854 if (error != JDWP::ERR_NONE) {
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07003855 return JDWP::ERR_INVALID_OBJECT;
3856 }
Ian Rogersc0542af2014-09-03 16:16:56 -07003857 if (argument != nullptr && !argument->InstanceOf(parameter_type)) {
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07003858 return JDWP::ERR_ILLEGAL_ARGUMENT;
3859 }
3860
3861 // Turn the on-the-wire ObjectId into a jobject.
3862 jvalue& v = reinterpret_cast<jvalue&>(arg_values[i]);
3863 v.l = gRegistry->GetJObject(arg_values[i]);
3864 }
Elliott Hughes09201632013-04-15 15:50:07 -07003865 }
Elliott Hughes45651fd2012-02-21 15:48:20 -08003866 }
3867
Sebastien Hertz1558b572015-02-25 15:05:59 +01003868 // Allocates a DebugInvokeReq.
3869 req.reset(new (std::nothrow) DebugInvokeReq(receiver, c, m, options, arg_values, arg_count));
3870 if (req.get() == nullptr) {
3871 LOG(ERROR) << "Failed to allocate DebugInvokeReq";
3872 return JDWP::ERR_OUT_OF_MEMORY;
3873 }
3874
3875 // Attach the DebugInvokeReq to the target thread so it executes the method when
3876 // it is resumed. Once the invocation completes, it will detach it and signal us
3877 // before suspending itself.
3878 targetThread->SetDebugInvokeReq(req.get());
Elliott Hughesd07986f2011-12-06 18:27:45 -08003879 }
3880
3881 // The fact that we've released the thread list lock is a bit risky --- if the thread goes
3882 // away we're sitting high and dry -- but we must release this before the ResumeAllThreads
3883 // call, and it's unwise to hold it during WaitForSuspend.
3884
3885 {
3886 /*
3887 * We change our (JDWP thread) status, which should be THREAD_RUNNING,
Elliott Hughes81ff3182012-03-23 20:35:56 -07003888 * so we can suspend for a GC if the invoke request causes us to
Elliott Hughesd07986f2011-12-06 18:27:45 -08003889 * run out of memory. It's also a good idea to change it before locking
3890 * the invokeReq mutex, although that should never be held for long.
3891 */
Ian Rogers00f7d0e2012-07-19 15:28:27 -07003892 self->TransitionFromRunnableToSuspended(kWaitingForDebuggerSend);
Elliott Hughesd07986f2011-12-06 18:27:45 -08003893
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08003894 VLOG(jdwp) << " Transferring control to event thread";
Elliott Hughesd07986f2011-12-06 18:27:45 -08003895 {
Sebastien Hertzd38667a2013-11-25 15:43:54 +01003896 MutexLock mu(self, req->lock);
Elliott Hughesd07986f2011-12-06 18:27:45 -08003897
3898 if ((options & JDWP::INVOKE_SINGLE_THREADED) == 0) {
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08003899 VLOG(jdwp) << " Resuming all threads";
Ian Rogers00f7d0e2012-07-19 15:28:27 -07003900 thread_list->UndoDebuggerSuspensions();
Elliott Hughesd07986f2011-12-06 18:27:45 -08003901 } else {
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08003902 VLOG(jdwp) << " Resuming event thread only";
Elliott Hughesd07986f2011-12-06 18:27:45 -08003903 thread_list->Resume(targetThread, true);
3904 }
3905
Sebastien Hertz2bf93f42015-01-09 18:44:05 +01003906 // The target thread is resumed but needs the JDWP token we're holding.
3907 // We release it now and will acquire it again when the invocation is
3908 // complete and the target thread suspends itself.
3909 gJdwpState->ReleaseJdwpTokenForCommand();
3910
Elliott Hughesd07986f2011-12-06 18:27:45 -08003911 // Wait for the request to finish executing.
Sebastien Hertz1558b572015-02-25 15:05:59 +01003912 while (targetThread->GetInvokeReq() != nullptr) {
Sebastien Hertzd38667a2013-11-25 15:43:54 +01003913 req->cond.Wait(self);
Elliott Hughesd07986f2011-12-06 18:27:45 -08003914 }
3915 }
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08003916 VLOG(jdwp) << " Control has returned from event thread";
Elliott Hughesd07986f2011-12-06 18:27:45 -08003917
3918 /* wait for thread to re-suspend itself */
Brian Carlstromdf629502013-07-17 22:39:56 -07003919 SuspendThread(thread_id, false /* request_suspension */);
Sebastien Hertz2bf93f42015-01-09 18:44:05 +01003920
3921 // Now the thread is suspended again, we can re-acquire the JDWP token.
3922 gJdwpState->AcquireJdwpTokenForCommand();
3923
Ian Rogers00f7d0e2012-07-19 15:28:27 -07003924 self->TransitionFromSuspendedToRunnable();
Elliott Hughesd07986f2011-12-06 18:27:45 -08003925 }
3926
3927 /*
3928 * Suspend the threads. We waited for the target thread to suspend
3929 * itself, so all we need to do is suspend the others.
3930 *
Sebastien Hertz2bf93f42015-01-09 18:44:05 +01003931 * The SuspendAllForDebugger() call will double-suspend the event thread,
Elliott Hughesd07986f2011-12-06 18:27:45 -08003932 * so we want to resume the target thread once to keep the books straight.
3933 */
3934 if ((options & JDWP::INVOKE_SINGLE_THREADED) == 0) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07003935 self->TransitionFromRunnableToSuspended(kWaitingForDebuggerSuspension);
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08003936 VLOG(jdwp) << " Suspending all threads";
Ian Rogers00f7d0e2012-07-19 15:28:27 -07003937 thread_list->SuspendAllForDebugger();
3938 self->TransitionFromSuspendedToRunnable();
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08003939 VLOG(jdwp) << " Resuming event thread to balance the count";
Elliott Hughesd07986f2011-12-06 18:27:45 -08003940 thread_list->Resume(targetThread, true);
3941 }
3942
3943 // Copy the result.
3944 *pResultTag = req->result_tag;
Sebastien Hertz1558b572015-02-25 15:05:59 +01003945 *pResultValue = req->result_value;
Elliott Hughesd07986f2011-12-06 18:27:45 -08003946 *pExceptionId = req->exception;
3947 return req->error;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07003948}
3949
3950void Dbg::ExecuteMethod(DebugInvokeReq* pReq) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07003951 ScopedObjectAccess soa(Thread::Current());
Elliott Hughesd07986f2011-12-06 18:27:45 -08003952
Elliott Hughes81ff3182012-03-23 20:35:56 -07003953 // We can be called while an exception is pending. We need
Elliott Hughesd07986f2011-12-06 18:27:45 -08003954 // to preserve that across the method invocation.
Sebastien Hertz1558b572015-02-25 15:05:59 +01003955 StackHandleScope<4> hs(soa.Self());
3956 auto old_exception = hs.NewHandle<mirror::Throwable>(soa.Self()->GetException());
3957 soa.Self()->ClearException();
Elliott Hughesd07986f2011-12-06 18:27:45 -08003958
3959 // Translate the method through the vtable, unless the debugger wants to suppress it.
Sebastien Hertz1558b572015-02-25 15:05:59 +01003960 MutableHandle<mirror::ArtMethod> m(hs.NewHandle(pReq->method.Read()));
3961 if ((pReq->options & JDWP::INVOKE_NONVIRTUAL) == 0 && pReq->receiver.Read() != nullptr) {
3962 mirror::ArtMethod* actual_method = pReq->klass.Read()->FindVirtualMethodForVirtualOrInterface(m.Get());
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003963 if (actual_method != m.Get()) {
Sebastien Hertz1558b572015-02-25 15:05:59 +01003964 VLOG(jdwp) << "ExecuteMethod translated " << PrettyMethod(m.Get())
3965 << " to " << PrettyMethod(actual_method);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003966 m.Assign(actual_method);
Elliott Hughes45651fd2012-02-21 15:48:20 -08003967 }
Elliott Hughesd07986f2011-12-06 18:27:45 -08003968 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003969 VLOG(jdwp) << "ExecuteMethod " << PrettyMethod(m.Get())
Sebastien Hertz1558b572015-02-25 15:05:59 +01003970 << " receiver=" << pReq->receiver.Read()
Sebastien Hertzd38667a2013-11-25 15:43:54 +01003971 << " arg_count=" << pReq->arg_count;
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003972 CHECK(m.Get() != nullptr);
Elliott Hughesd07986f2011-12-06 18:27:45 -08003973
3974 CHECK_EQ(sizeof(jvalue), sizeof(uint64_t));
3975
Sebastien Hertz1558b572015-02-25 15:05:59 +01003976 JValue result = InvokeWithJValues(soa, pReq->receiver.Read(), soa.EncodeMethod(m.Get()),
3977 reinterpret_cast<jvalue*>(pReq->arg_values));
Elliott Hughesd07986f2011-12-06 18:27:45 -08003978
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07003979 pReq->result_tag = BasicTagFromDescriptor(m.Get()->GetShorty());
Sebastien Hertz1558b572015-02-25 15:05:59 +01003980 const bool is_object_result = (pReq->result_tag == JDWP::JT_OBJECT);
3981 Handle<mirror::Object> object_result = hs.NewHandle(is_object_result ? result.GetL() : nullptr);
3982 Handle<mirror::Throwable> exception = hs.NewHandle(soa.Self()->GetException());
3983 soa.Self()->ClearException();
Sebastien Hertz261bc042015-04-08 09:36:07 +02003984 pReq->exception = gRegistry->Add(exception);
Elliott Hughesd07986f2011-12-06 18:27:45 -08003985 if (pReq->exception != 0) {
Sebastien Hertz1558b572015-02-25 15:05:59 +01003986 VLOG(jdwp) << " JDWP invocation returning with exception=" << exception.Get()
3987 << " " << exception->Dump();
3988 pReq->result_value = 0;
3989 } else if (is_object_result) {
Elliott Hughesd07986f2011-12-06 18:27:45 -08003990 /* if no exception thrown, examine object result more closely */
Sebastien Hertz1558b572015-02-25 15:05:59 +01003991 JDWP::JdwpTag new_tag = TagFromObject(soa, object_result.Get());
Elliott Hughesd07986f2011-12-06 18:27:45 -08003992 if (new_tag != pReq->result_tag) {
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08003993 VLOG(jdwp) << " JDWP promoted result from " << pReq->result_tag << " to " << new_tag;
Elliott Hughesd07986f2011-12-06 18:27:45 -08003994 pReq->result_tag = new_tag;
3995 }
3996
Sebastien Hertz1558b572015-02-25 15:05:59 +01003997 // Register the object in the registry and reference its ObjectId. This ensures
3998 // GC safety and prevents from accessing stale reference if the object is moved.
3999 pReq->result_value = gRegistry->Add(object_result.Get());
4000 } else {
4001 // Primitive result.
4002 DCHECK(IsPrimitiveTag(pReq->result_tag));
4003 pReq->result_value = result.GetJ();
Elliott Hughesd07986f2011-12-06 18:27:45 -08004004 }
4005
Ian Rogersc0542af2014-09-03 16:16:56 -07004006 if (old_exception.Get() != nullptr) {
Nicolas Geoffray14691c52015-03-05 10:40:17 +00004007 soa.Self()->SetException(old_exception.Get());
Elliott Hughesd07986f2011-12-06 18:27:45 -08004008 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -07004009}
4010
Elliott Hughesd07986f2011-12-06 18:27:45 -08004011/*
Elliott Hughes4b9702c2013-02-20 18:13:24 -08004012 * "request" contains a full JDWP packet, possibly with multiple chunks. We
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07004013 * need to process each, accumulate the replies, and ship the whole thing
4014 * back.
4015 *
4016 * Returns "true" if we have a reply. The reply buffer is newly allocated,
4017 * and includes the chunk type/length, followed by the data.
4018 *
Elliott Hughes3d30d9b2011-12-07 17:35:48 -08004019 * OLD-TODO: we currently assume that the request and reply include a single
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07004020 * chunk. If this becomes inconvenient we will need to adapt.
4021 */
Ian Rogersc0542af2014-09-03 16:16:56 -07004022bool Dbg::DdmHandlePacket(JDWP::Request* request, uint8_t** pReplyBuf, int* pReplyLen) {
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07004023 Thread* self = Thread::Current();
4024 JNIEnv* env = self->GetJniEnv();
4025
Ian Rogersc0542af2014-09-03 16:16:56 -07004026 uint32_t type = request->ReadUnsigned32("type");
4027 uint32_t length = request->ReadUnsigned32("length");
Elliott Hughes4b9702c2013-02-20 18:13:24 -08004028
4029 // Create a byte[] corresponding to 'request'.
Ian Rogersc0542af2014-09-03 16:16:56 -07004030 size_t request_length = request->size();
Elliott Hughes4b9702c2013-02-20 18:13:24 -08004031 ScopedLocalRef<jbyteArray> dataArray(env, env->NewByteArray(request_length));
Ian Rogersc0542af2014-09-03 16:16:56 -07004032 if (dataArray.get() == nullptr) {
Elliott Hughes4b9702c2013-02-20 18:13:24 -08004033 LOG(WARNING) << "byte[] allocation failed: " << request_length;
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07004034 env->ExceptionClear();
4035 return false;
4036 }
Ian Rogersc0542af2014-09-03 16:16:56 -07004037 env->SetByteArrayRegion(dataArray.get(), 0, request_length,
4038 reinterpret_cast<const jbyte*>(request->data()));
4039 request->Skip(request_length);
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07004040
4041 // Run through and find all chunks. [Currently just find the first.]
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004042 ScopedByteArrayRO contents(env, dataArray.get());
Elliott Hughes4b9702c2013-02-20 18:13:24 -08004043 if (length != request_length) {
Ian Rogersef7d42f2014-01-06 12:55:46 -08004044 LOG(WARNING) << StringPrintf("bad chunk found (len=%u pktLen=%zd)", length, request_length);
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07004045 return false;
4046 }
4047
4048 // Call "private static Chunk dispatch(int type, byte[] data, int offset, int length)".
Elliott Hugheseac76672012-05-24 21:56:51 -07004049 ScopedLocalRef<jobject> chunk(env, env->CallStaticObjectMethod(WellKnownClasses::org_apache_harmony_dalvik_ddmc_DdmServer,
4050 WellKnownClasses::org_apache_harmony_dalvik_ddmc_DdmServer_dispatch,
Elliott Hughes4b9702c2013-02-20 18:13:24 -08004051 type, dataArray.get(), 0, length));
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07004052 if (env->ExceptionCheck()) {
4053 LOG(INFO) << StringPrintf("Exception thrown by dispatcher for 0x%08x", type);
4054 env->ExceptionDescribe();
4055 env->ExceptionClear();
4056 return false;
4057 }
4058
Ian Rogersc0542af2014-09-03 16:16:56 -07004059 if (chunk.get() == nullptr) {
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07004060 return false;
4061 }
4062
4063 /*
4064 * Pull the pieces out of the chunk. We copy the results into a
4065 * newly-allocated buffer that the caller can free. We don't want to
4066 * continue using the Chunk object because nothing has a reference to it.
4067 *
4068 * We could avoid this by returning type/data/offset/length and having
4069 * the caller be aware of the object lifetime issues, but that
Elliott Hughes81ff3182012-03-23 20:35:56 -07004070 * integrates the JDWP code more tightly into the rest of the runtime, and doesn't work
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07004071 * if we have responses for multiple chunks.
4072 *
4073 * So we're pretty much stuck with copying data around multiple times.
4074 */
Elliott Hugheseac76672012-05-24 21:56:51 -07004075 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 -08004076 jint offset = env->GetIntField(chunk.get(), WellKnownClasses::org_apache_harmony_dalvik_ddmc_Chunk_offset);
Elliott Hugheseac76672012-05-24 21:56:51 -07004077 length = env->GetIntField(chunk.get(), WellKnownClasses::org_apache_harmony_dalvik_ddmc_Chunk_length);
Elliott Hugheseac76672012-05-24 21:56:51 -07004078 type = env->GetIntField(chunk.get(), WellKnownClasses::org_apache_harmony_dalvik_ddmc_Chunk_type);
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07004079
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08004080 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 -07004081 if (length == 0 || replyData.get() == nullptr) {
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07004082 return false;
4083 }
4084
Elliott Hughes4b9702c2013-02-20 18:13:24 -08004085 const int kChunkHdrLen = 8;
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07004086 uint8_t* reply = new uint8_t[length + kChunkHdrLen];
Ian Rogersc0542af2014-09-03 16:16:56 -07004087 if (reply == nullptr) {
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07004088 LOG(WARNING) << "malloc failed: " << (length + kChunkHdrLen);
4089 return false;
4090 }
Elliott Hughesf7c3b662011-10-27 12:04:56 -07004091 JDWP::Set4BE(reply + 0, type);
4092 JDWP::Set4BE(reply + 4, length);
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004093 env->GetByteArrayRegion(replyData.get(), offset, length, reinterpret_cast<jbyte*>(reply + kChunkHdrLen));
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07004094
4095 *pReplyBuf = reply;
4096 *pReplyLen = length + kChunkHdrLen;
4097
Elliott Hughes4b9702c2013-02-20 18:13:24 -08004098 VLOG(jdwp) << StringPrintf("dvmHandleDdm returning type=%.4s %p len=%d", reinterpret_cast<char*>(reply), reply, length);
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07004099 return true;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07004100}
4101
Elliott Hughesa2155262011-11-16 16:26:58 -08004102void Dbg::DdmBroadcast(bool connect) {
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08004103 VLOG(jdwp) << "Broadcasting DDM " << (connect ? "connect" : "disconnect") << "...";
Elliott Hughes47fce012011-10-25 18:37:19 -07004104
4105 Thread* self = Thread::Current();
Ian Rogers50b35e22012-10-04 10:09:15 -07004106 if (self->GetState() != kRunnable) {
4107 LOG(ERROR) << "DDM broadcast in thread state " << self->GetState();
4108 /* try anyway? */
Elliott Hughes47fce012011-10-25 18:37:19 -07004109 }
4110
4111 JNIEnv* env = self->GetJniEnv();
Elliott Hughes47fce012011-10-25 18:37:19 -07004112 jint event = connect ? 1 /*DdmServer.CONNECTED*/ : 2 /*DdmServer.DISCONNECTED*/;
Elliott Hugheseac76672012-05-24 21:56:51 -07004113 env->CallStaticVoidMethod(WellKnownClasses::org_apache_harmony_dalvik_ddmc_DdmServer,
4114 WellKnownClasses::org_apache_harmony_dalvik_ddmc_DdmServer_broadcast,
4115 event);
Elliott Hughes47fce012011-10-25 18:37:19 -07004116 if (env->ExceptionCheck()) {
4117 LOG(ERROR) << "DdmServer.broadcast " << event << " failed";
4118 env->ExceptionDescribe();
4119 env->ExceptionClear();
4120 }
4121}
4122
Elliott Hughes872d4ec2011-10-21 17:07:15 -07004123void Dbg::DdmConnected() {
Elliott Hughesa2155262011-11-16 16:26:58 -08004124 Dbg::DdmBroadcast(true);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07004125}
4126
4127void Dbg::DdmDisconnected() {
Elliott Hughesa2155262011-11-16 16:26:58 -08004128 Dbg::DdmBroadcast(false);
Elliott Hughes47fce012011-10-25 18:37:19 -07004129 gDdmThreadNotification = false;
4130}
4131
4132/*
Elliott Hughes82188472011-11-07 18:11:48 -08004133 * Send a notification when a thread starts, stops, or changes its name.
Elliott Hughes47fce012011-10-25 18:37:19 -07004134 *
4135 * Because we broadcast the full set of threads when the notifications are
4136 * first enabled, it's possible for "thread" to be actively executing.
4137 */
Elliott Hughes82188472011-11-07 18:11:48 -08004138void Dbg::DdmSendThreadNotification(Thread* t, uint32_t type) {
Elliott Hughes47fce012011-10-25 18:37:19 -07004139 if (!gDdmThreadNotification) {
4140 return;
4141 }
4142
Elliott Hughes82188472011-11-07 18:11:48 -08004143 if (type == CHUNK_TYPE("THDE")) {
Elliott Hughes47fce012011-10-25 18:37:19 -07004144 uint8_t buf[4];
Ian Rogersd9c4fc92013-10-01 19:45:43 -07004145 JDWP::Set4BE(&buf[0], t->GetThreadId());
Elliott Hughes47fce012011-10-25 18:37:19 -07004146 Dbg::DdmSendChunk(CHUNK_TYPE("THDE"), 4, buf);
Elliott Hughes82188472011-11-07 18:11:48 -08004147 } else {
4148 CHECK(type == CHUNK_TYPE("THCR") || type == CHUNK_TYPE("THNM")) << type;
Ian Rogers00f7d0e2012-07-19 15:28:27 -07004149 ScopedObjectAccessUnchecked soa(Thread::Current());
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004150 StackHandleScope<1> hs(soa.Self());
4151 Handle<mirror::String> name(hs.NewHandle(t->GetThreadName(soa)));
Ian Rogersc0542af2014-09-03 16:16:56 -07004152 size_t char_count = (name.Get() != nullptr) ? name->GetLength() : 0;
Jeff Hao848f70a2014-01-15 13:49:50 -08004153 const jchar* chars = (name.Get() != nullptr) ? name->GetValue() : nullptr;
Elliott Hughes82188472011-11-07 18:11:48 -08004154
Elliott Hughes21f32d72011-11-09 17:44:13 -08004155 std::vector<uint8_t> bytes;
Ian Rogersd9c4fc92013-10-01 19:45:43 -07004156 JDWP::Append4BE(bytes, t->GetThreadId());
Elliott Hughes545a0642011-11-08 19:10:03 -08004157 JDWP::AppendUtf16BE(bytes, chars, char_count);
Elliott Hughes21f32d72011-11-09 17:44:13 -08004158 CHECK_EQ(bytes.size(), char_count*2 + sizeof(uint32_t)*2);
4159 Dbg::DdmSendChunk(type, bytes);
Elliott Hughes47fce012011-10-25 18:37:19 -07004160 }
4161}
4162
Elliott Hughes47fce012011-10-25 18:37:19 -07004163void Dbg::DdmSetThreadNotification(bool enable) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07004164 // Enable/disable thread notifications.
Elliott Hughes47fce012011-10-25 18:37:19 -07004165 gDdmThreadNotification = enable;
4166 if (enable) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07004167 // Suspend the VM then post thread start notifications for all threads. Threads attaching will
4168 // see a suspension in progress and block until that ends. They then post their own start
4169 // notification.
4170 SuspendVM();
4171 std::list<Thread*> threads;
Ian Rogers50b35e22012-10-04 10:09:15 -07004172 Thread* self = Thread::Current();
Ian Rogers00f7d0e2012-07-19 15:28:27 -07004173 {
Ian Rogers50b35e22012-10-04 10:09:15 -07004174 MutexLock mu(self, *Locks::thread_list_lock_);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07004175 threads = Runtime::Current()->GetThreadList()->GetList();
4176 }
4177 {
Ian Rogers50b35e22012-10-04 10:09:15 -07004178 ScopedObjectAccess soa(self);
Mathieu Chartier02e25112013-08-14 16:14:24 -07004179 for (Thread* thread : threads) {
4180 Dbg::DdmSendThreadNotification(thread, CHUNK_TYPE("THCR"));
Ian Rogers00f7d0e2012-07-19 15:28:27 -07004181 }
4182 }
4183 ResumeVM();
Elliott Hughes47fce012011-10-25 18:37:19 -07004184 }
4185}
4186
Elliott Hughesa2155262011-11-16 16:26:58 -08004187void Dbg::PostThreadStartOrStop(Thread* t, uint32_t type) {
Elliott Hughesc0f09332012-03-26 13:27:06 -07004188 if (IsDebuggerActive()) {
Sebastien Hertz6995c602014-09-09 12:10:13 +02004189 gJdwpState->PostThreadChange(t, type == CHUNK_TYPE("THCR"));
Elliott Hughes47fce012011-10-25 18:37:19 -07004190 }
Elliott Hughes82188472011-11-07 18:11:48 -08004191 Dbg::DdmSendThreadNotification(t, type);
Elliott Hughes47fce012011-10-25 18:37:19 -07004192}
4193
4194void Dbg::PostThreadStart(Thread* t) {
Elliott Hughesa2155262011-11-16 16:26:58 -08004195 Dbg::PostThreadStartOrStop(t, CHUNK_TYPE("THCR"));
Elliott Hughes47fce012011-10-25 18:37:19 -07004196}
4197
4198void Dbg::PostThreadDeath(Thread* t) {
Elliott Hughesa2155262011-11-16 16:26:58 -08004199 Dbg::PostThreadStartOrStop(t, CHUNK_TYPE("THDE"));
Elliott Hughes872d4ec2011-10-21 17:07:15 -07004200}
4201
Elliott Hughes82188472011-11-07 18:11:48 -08004202void Dbg::DdmSendChunk(uint32_t type, size_t byte_count, const uint8_t* buf) {
Ian Rogersc0542af2014-09-03 16:16:56 -07004203 CHECK(buf != nullptr);
Elliott Hughes3bb81562011-10-21 18:52:59 -07004204 iovec vec[1];
4205 vec[0].iov_base = reinterpret_cast<void*>(const_cast<uint8_t*>(buf));
4206 vec[0].iov_len = byte_count;
4207 Dbg::DdmSendChunkV(type, vec, 1);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07004208}
4209
Elliott Hughes21f32d72011-11-09 17:44:13 -08004210void Dbg::DdmSendChunk(uint32_t type, const std::vector<uint8_t>& bytes) {
4211 DdmSendChunk(type, bytes.size(), &bytes[0]);
4212}
4213
Brian Carlstromf5293522013-07-19 00:24:00 -07004214void Dbg::DdmSendChunkV(uint32_t type, const iovec* iov, int iov_count) {
Ian Rogersc0542af2014-09-03 16:16:56 -07004215 if (gJdwpState == nullptr) {
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08004216 VLOG(jdwp) << "Debugger thread not active, ignoring DDM send: " << type;
Elliott Hughes3bb81562011-10-21 18:52:59 -07004217 } else {
Elliott Hughescccd84f2011-12-05 16:51:54 -08004218 gJdwpState->DdmSendChunkV(type, iov, iov_count);
Elliott Hughes3bb81562011-10-21 18:52:59 -07004219 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -07004220}
4221
Mathieu Chartierad466ad2015-01-08 16:28:08 -08004222JDWP::JdwpState* Dbg::GetJdwpState() {
4223 return gJdwpState;
4224}
4225
Elliott Hughes767a1472011-10-26 18:49:02 -07004226int Dbg::DdmHandleHpifChunk(HpifWhen when) {
4227 if (when == HPIF_WHEN_NOW) {
Elliott Hughes7162ad92011-10-27 14:08:42 -07004228 DdmSendHeapInfo(when);
Elliott Hughes767a1472011-10-26 18:49:02 -07004229 return true;
4230 }
4231
4232 if (when != HPIF_WHEN_NEVER && when != HPIF_WHEN_NEXT_GC && when != HPIF_WHEN_EVERY_GC) {
4233 LOG(ERROR) << "invalid HpifWhen value: " << static_cast<int>(when);
4234 return false;
4235 }
4236
4237 gDdmHpifWhen = when;
4238 return true;
4239}
4240
4241bool Dbg::DdmHandleHpsgNhsgChunk(Dbg::HpsgWhen when, Dbg::HpsgWhat what, bool native) {
4242 if (when != HPSG_WHEN_NEVER && when != HPSG_WHEN_EVERY_GC) {
4243 LOG(ERROR) << "invalid HpsgWhen value: " << static_cast<int>(when);
4244 return false;
4245 }
4246
4247 if (what != HPSG_WHAT_MERGED_OBJECTS && what != HPSG_WHAT_DISTINCT_OBJECTS) {
4248 LOG(ERROR) << "invalid HpsgWhat value: " << static_cast<int>(what);
4249 return false;
4250 }
4251
4252 if (native) {
4253 gDdmNhsgWhen = when;
4254 gDdmNhsgWhat = what;
4255 } else {
4256 gDdmHpsgWhen = when;
4257 gDdmHpsgWhat = what;
4258 }
4259 return true;
4260}
4261
Elliott Hughes7162ad92011-10-27 14:08:42 -07004262void Dbg::DdmSendHeapInfo(HpifWhen reason) {
4263 // If there's a one-shot 'when', reset it.
4264 if (reason == gDdmHpifWhen) {
4265 if (gDdmHpifWhen == HPIF_WHEN_NEXT_GC) {
4266 gDdmHpifWhen = HPIF_WHEN_NEVER;
4267 }
4268 }
4269
4270 /*
4271 * Chunk HPIF (client --> server)
4272 *
4273 * Heap Info. General information about the heap,
4274 * suitable for a summary display.
4275 *
4276 * [u4]: number of heaps
4277 *
4278 * For each heap:
4279 * [u4]: heap ID
4280 * [u8]: timestamp in ms since Unix epoch
4281 * [u1]: capture reason (same as 'when' value from server)
4282 * [u4]: max heap size in bytes (-Xmx)
4283 * [u4]: current heap size in bytes
4284 * [u4]: current number of bytes allocated
4285 * [u4]: current number of objects allocated
4286 */
4287 uint8_t heap_count = 1;
Ian Rogers1d54e732013-05-02 21:10:01 -07004288 gc::Heap* heap = Runtime::Current()->GetHeap();
Elliott Hughes21f32d72011-11-09 17:44:13 -08004289 std::vector<uint8_t> bytes;
Elliott Hughes545a0642011-11-08 19:10:03 -08004290 JDWP::Append4BE(bytes, heap_count);
Brian Carlstrom7934ac22013-07-26 10:54:15 -07004291 JDWP::Append4BE(bytes, 1); // Heap id (bogus; we only have one heap).
Elliott Hughes545a0642011-11-08 19:10:03 -08004292 JDWP::Append8BE(bytes, MilliTime());
4293 JDWP::Append1BE(bytes, reason);
Brian Carlstrom7934ac22013-07-26 10:54:15 -07004294 JDWP::Append4BE(bytes, heap->GetMaxMemory()); // Max allowed heap size in bytes.
4295 JDWP::Append4BE(bytes, heap->GetTotalMemory()); // Current heap size in bytes.
Elliott Hughesb3bd5f02012-03-08 21:05:27 -08004296 JDWP::Append4BE(bytes, heap->GetBytesAllocated());
4297 JDWP::Append4BE(bytes, heap->GetObjectsAllocated());
Elliott Hughes21f32d72011-11-09 17:44:13 -08004298 CHECK_EQ(bytes.size(), 4U + (heap_count * (4 + 8 + 1 + 4 + 4 + 4 + 4)));
4299 Dbg::DdmSendChunk(CHUNK_TYPE("HPIF"), bytes);
Elliott Hughes767a1472011-10-26 18:49:02 -07004300}
4301
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004302enum HpsgSolidity {
4303 SOLIDITY_FREE = 0,
4304 SOLIDITY_HARD = 1,
4305 SOLIDITY_SOFT = 2,
4306 SOLIDITY_WEAK = 3,
4307 SOLIDITY_PHANTOM = 4,
4308 SOLIDITY_FINALIZABLE = 5,
4309 SOLIDITY_SWEEP = 6,
4310};
4311
4312enum HpsgKind {
4313 KIND_OBJECT = 0,
4314 KIND_CLASS_OBJECT = 1,
4315 KIND_ARRAY_1 = 2,
4316 KIND_ARRAY_2 = 3,
4317 KIND_ARRAY_4 = 4,
4318 KIND_ARRAY_8 = 5,
4319 KIND_UNKNOWN = 6,
4320 KIND_NATIVE = 7,
4321};
4322
4323#define HPSG_PARTIAL (1<<7)
4324#define HPSG_STATE(solidity, kind) ((uint8_t)((((kind) & 0x7) << 3) | ((solidity) & 0x7)))
4325
Ian Rogers30fab402012-01-23 15:43:46 -08004326class HeapChunkContext {
4327 public:
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004328 // Maximum chunk size. Obtain this from the formula:
4329 // (((maximum_heap_size / ALLOCATION_UNIT_SIZE) + 255) / 256) * 2
4330 HeapChunkContext(bool merge, bool native)
Ian Rogers30fab402012-01-23 15:43:46 -08004331 : buf_(16384 - 16),
4332 type_(0),
Mathieu Chartier36dab362014-07-30 14:59:56 -07004333 chunk_overhead_(0) {
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004334 Reset();
4335 if (native) {
Ian Rogers30fab402012-01-23 15:43:46 -08004336 type_ = CHUNK_TYPE("NHSG");
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004337 } else {
Ian Rogers30fab402012-01-23 15:43:46 -08004338 type_ = merge ? CHUNK_TYPE("HPSG") : CHUNK_TYPE("HPSO");
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004339 }
4340 }
4341
4342 ~HeapChunkContext() {
Ian Rogers30fab402012-01-23 15:43:46 -08004343 if (p_ > &buf_[0]) {
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004344 Flush();
4345 }
4346 }
4347
Mathieu Chartier36dab362014-07-30 14:59:56 -07004348 void SetChunkOverhead(size_t chunk_overhead) {
4349 chunk_overhead_ = chunk_overhead;
4350 }
4351
4352 void ResetStartOfNextChunk() {
4353 startOfNextMemoryChunk_ = nullptr;
4354 }
4355
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004356 void EnsureHeader(const void* chunk_ptr) {
Ian Rogers30fab402012-01-23 15:43:46 -08004357 if (!needHeader_) {
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004358 return;
4359 }
4360
4361 // Start a new HPSx chunk.
Brian Carlstrom7934ac22013-07-26 10:54:15 -07004362 JDWP::Write4BE(&p_, 1); // Heap id (bogus; we only have one heap).
4363 JDWP::Write1BE(&p_, 8); // Size of allocation unit, in bytes.
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004364
Brian Carlstrom7934ac22013-07-26 10:54:15 -07004365 JDWP::Write4BE(&p_, reinterpret_cast<uintptr_t>(chunk_ptr)); // virtual address of segment start.
4366 JDWP::Write4BE(&p_, 0); // offset of this piece (relative to the virtual address).
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004367 // [u4]: length of piece, in allocation units
4368 // 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 -08004369 pieceLenField_ = p_;
4370 JDWP::Write4BE(&p_, 0x55555555);
4371 needHeader_ = false;
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004372 }
4373
Ian Rogersb726dcb2012-09-05 08:57:23 -07004374 void Flush() SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Ian Rogersc0542af2014-09-03 16:16:56 -07004375 if (pieceLenField_ == nullptr) {
Ian Rogersd636b062013-01-18 17:51:18 -08004376 // Flush immediately post Reset (maybe back-to-back Flush). Ignore.
4377 CHECK(needHeader_);
4378 return;
4379 }
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004380 // Patch the "length of piece" field.
Ian Rogers30fab402012-01-23 15:43:46 -08004381 CHECK_LE(&buf_[0], pieceLenField_);
4382 CHECK_LE(pieceLenField_, p_);
4383 JDWP::Set4BE(pieceLenField_, totalAllocationUnits_);
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004384
Ian Rogers30fab402012-01-23 15:43:46 -08004385 Dbg::DdmSendChunk(type_, p_ - &buf_[0], &buf_[0]);
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004386 Reset();
4387 }
4388
Mathieu Chartierbc689b72014-12-14 17:01:31 -08004389 static void HeapChunkJavaCallback(void* start, void* end, size_t used_bytes, void* arg)
Ian Rogersb726dcb2012-09-05 08:57:23 -07004390 SHARED_LOCKS_REQUIRED(Locks::heap_bitmap_lock_,
4391 Locks::mutator_lock_) {
Mathieu Chartierbc689b72014-12-14 17:01:31 -08004392 reinterpret_cast<HeapChunkContext*>(arg)->HeapChunkJavaCallback(start, end, used_bytes);
4393 }
4394
4395 static void HeapChunkNativeCallback(void* start, void* end, size_t used_bytes, void* arg)
4396 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
4397 reinterpret_cast<HeapChunkContext*>(arg)->HeapChunkNativeCallback(start, end, used_bytes);
Elliott Hughesa2155262011-11-16 16:26:58 -08004398 }
4399
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004400 private:
Elliott Hughesa2155262011-11-16 16:26:58 -08004401 enum { ALLOCATION_UNIT_SIZE = 8 };
4402
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004403 void Reset() {
Ian Rogers30fab402012-01-23 15:43:46 -08004404 p_ = &buf_[0];
Mathieu Chartier36dab362014-07-30 14:59:56 -07004405 ResetStartOfNextChunk();
Ian Rogers30fab402012-01-23 15:43:46 -08004406 totalAllocationUnits_ = 0;
4407 needHeader_ = true;
Ian Rogersc0542af2014-09-03 16:16:56 -07004408 pieceLenField_ = nullptr;
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004409 }
4410
Mathieu Chartierbc689b72014-12-14 17:01:31 -08004411 bool IsNative() const {
4412 return type_ == CHUNK_TYPE("NHSG");
4413 }
4414
4415 // Returns true if the object is not an empty chunk.
4416 bool ProcessRecord(void* start, size_t used_bytes) SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Ian Rogers30fab402012-01-23 15:43:46 -08004417 // Note: heap call backs cannot manipulate the heap upon which they are crawling, care is taken
4418 // in the following code not to allocate memory, by ensuring buf_ is of the correct size
Ian Rogers15bf2d32012-08-28 17:33:04 -07004419 if (used_bytes == 0) {
Mathieu Chartierbc689b72014-12-14 17:01:31 -08004420 if (start == nullptr) {
4421 // Reset for start of new heap.
4422 startOfNextMemoryChunk_ = nullptr;
4423 Flush();
4424 }
4425 // Only process in use memory so that free region information
4426 // also includes dlmalloc book keeping.
4427 return false;
Elliott Hughesa2155262011-11-16 16:26:58 -08004428 }
Ian Rogersc0542af2014-09-03 16:16:56 -07004429 if (startOfNextMemoryChunk_ != nullptr) {
Mathieu Chartierbc689b72014-12-14 17:01:31 -08004430 // Transmit any pending free memory. Native free memory of over kMaxFreeLen could be because
4431 // of the use of mmaps, so don't report. If not free memory then start a new segment.
4432 bool flush = true;
4433 if (start > startOfNextMemoryChunk_) {
4434 const size_t kMaxFreeLen = 2 * kPageSize;
4435 void* free_start = startOfNextMemoryChunk_;
4436 void* free_end = start;
4437 const size_t free_len =
4438 reinterpret_cast<uintptr_t>(free_end) - reinterpret_cast<uintptr_t>(free_start);
4439 if (!IsNative() || free_len < kMaxFreeLen) {
4440 AppendChunk(HPSG_STATE(SOLIDITY_FREE, 0), free_start, free_len, IsNative());
4441 flush = false;
Ian Rogers15bf2d32012-08-28 17:33:04 -07004442 }
Mathieu Chartierbc689b72014-12-14 17:01:31 -08004443 }
4444 if (flush) {
4445 startOfNextMemoryChunk_ = nullptr;
4446 Flush();
4447 }
Ian Rogers15bf2d32012-08-28 17:33:04 -07004448 }
Mathieu Chartierbc689b72014-12-14 17:01:31 -08004449 return true;
Ian Rogers15bf2d32012-08-28 17:33:04 -07004450 }
Elliott Hughesa2155262011-11-16 16:26:58 -08004451
Mathieu Chartierbc689b72014-12-14 17:01:31 -08004452 void HeapChunkNativeCallback(void* start, void* /*end*/, size_t used_bytes)
4453 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
4454 if (ProcessRecord(start, used_bytes)) {
4455 uint8_t state = ExamineNativeObject(start);
4456 AppendChunk(state, start, used_bytes + chunk_overhead_, true /*is_native*/);
4457 startOfNextMemoryChunk_ = reinterpret_cast<char*>(start) + used_bytes + chunk_overhead_;
4458 }
4459 }
4460
4461 void HeapChunkJavaCallback(void* start, void* /*end*/, size_t used_bytes)
4462 SHARED_LOCKS_REQUIRED(Locks::heap_bitmap_lock_, Locks::mutator_lock_) {
4463 if (ProcessRecord(start, used_bytes)) {
4464 // Determine the type of this chunk.
4465 // OLD-TODO: if context.merge, see if this chunk is different from the last chunk.
4466 // If it's the same, we should combine them.
4467 uint8_t state = ExamineJavaObject(reinterpret_cast<mirror::Object*>(start));
4468 AppendChunk(state, start, used_bytes + chunk_overhead_, false /*is_native*/);
4469 startOfNextMemoryChunk_ = reinterpret_cast<char*>(start) + used_bytes + chunk_overhead_;
4470 }
4471 }
4472
4473 void AppendChunk(uint8_t state, void* ptr, size_t length, bool is_native)
Ian Rogersb726dcb2012-09-05 08:57:23 -07004474 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Ian Rogers15bf2d32012-08-28 17:33:04 -07004475 // Make sure there's enough room left in the buffer.
4476 // We need to use two bytes for every fractional 256 allocation units used by the chunk plus
4477 // 17 bytes for any header.
Mathieu Chartierbc689b72014-12-14 17:01:31 -08004478 const size_t needed = ((RoundUp(length / ALLOCATION_UNIT_SIZE, 256) / 256) * 2) + 17;
4479 size_t byte_left = &buf_.back() - p_;
4480 if (byte_left < needed) {
4481 if (is_native) {
Pavel Vyssotski7522c742014-12-08 13:38:26 +06004482 // Cannot trigger memory allocation while walking native heap.
Pavel Vyssotski7522c742014-12-08 13:38:26 +06004483 return;
4484 }
Ian Rogers15bf2d32012-08-28 17:33:04 -07004485 Flush();
4486 }
4487
Mathieu Chartierbc689b72014-12-14 17:01:31 -08004488 byte_left = &buf_.back() - p_;
4489 if (byte_left < needed) {
Ian Rogers15bf2d32012-08-28 17:33:04 -07004490 LOG(WARNING) << "Chunk is too big to transmit (chunk_len=" << length << ", "
4491 << needed << " bytes)";
4492 return;
4493 }
4494 EnsureHeader(ptr);
Elliott Hughesa2155262011-11-16 16:26:58 -08004495 // Write out the chunk description.
Ian Rogers15bf2d32012-08-28 17:33:04 -07004496 length /= ALLOCATION_UNIT_SIZE; // Convert to allocation units.
4497 totalAllocationUnits_ += length;
4498 while (length > 256) {
Ian Rogers30fab402012-01-23 15:43:46 -08004499 *p_++ = state | HPSG_PARTIAL;
4500 *p_++ = 255; // length - 1
Ian Rogers15bf2d32012-08-28 17:33:04 -07004501 length -= 256;
Elliott Hughesa2155262011-11-16 16:26:58 -08004502 }
Ian Rogers30fab402012-01-23 15:43:46 -08004503 *p_++ = state;
Ian Rogers15bf2d32012-08-28 17:33:04 -07004504 *p_++ = length - 1;
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004505 }
4506
Mathieu Chartierbc689b72014-12-14 17:01:31 -08004507 uint8_t ExamineNativeObject(const void* p) SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
4508 return p == nullptr ? HPSG_STATE(SOLIDITY_FREE, 0) : HPSG_STATE(SOLIDITY_HARD, KIND_NATIVE);
4509 }
4510
4511 uint8_t ExamineJavaObject(mirror::Object* o)
Ian Rogersef7d42f2014-01-06 12:55:46 -08004512 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_, Locks::heap_bitmap_lock_) {
Ian Rogersc0542af2014-09-03 16:16:56 -07004513 if (o == nullptr) {
Elliott Hughesa2155262011-11-16 16:26:58 -08004514 return HPSG_STATE(SOLIDITY_FREE, 0);
4515 }
Elliott Hughesa2155262011-11-16 16:26:58 -08004516 // It's an allocated chunk. Figure out what it is.
Mathieu Chartierbc689b72014-12-14 17:01:31 -08004517 gc::Heap* heap = Runtime::Current()->GetHeap();
4518 if (!heap->IsLiveObjectLocked(o)) {
4519 LOG(ERROR) << "Invalid object in managed heap: " << o;
Elliott Hughesa2155262011-11-16 16:26:58 -08004520 return HPSG_STATE(SOLIDITY_HARD, KIND_NATIVE);
4521 }
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08004522 mirror::Class* c = o->GetClass();
Ian Rogersc0542af2014-09-03 16:16:56 -07004523 if (c == nullptr) {
Elliott Hughesa2155262011-11-16 16:26:58 -08004524 // The object was probably just created but hasn't been initialized yet.
4525 return HPSG_STATE(SOLIDITY_HARD, KIND_OBJECT);
4526 }
Mathieu Chartierbc689b72014-12-14 17:01:31 -08004527 if (!heap->IsValidObjectAddress(c)) {
Ian Rogers15bf2d32012-08-28 17:33:04 -07004528 LOG(ERROR) << "Invalid class for managed heap object: " << o << " " << c;
Elliott Hughesa2155262011-11-16 16:26:58 -08004529 return HPSG_STATE(SOLIDITY_HARD, KIND_UNKNOWN);
4530 }
Mathieu Chartierf26e1b32015-01-29 10:47:10 -08004531 if (c->GetClass() == nullptr) {
4532 LOG(ERROR) << "Null class of class " << c << " for object " << o;
4533 return HPSG_STATE(SOLIDITY_HARD, KIND_UNKNOWN);
4534 }
Elliott Hughesa2155262011-11-16 16:26:58 -08004535 if (c->IsClassClass()) {
4536 return HPSG_STATE(SOLIDITY_HARD, KIND_CLASS_OBJECT);
4537 }
Elliott Hughesa2155262011-11-16 16:26:58 -08004538 if (c->IsArrayClass()) {
Elliott Hughesa2155262011-11-16 16:26:58 -08004539 switch (c->GetComponentSize()) {
4540 case 1: return HPSG_STATE(SOLIDITY_HARD, KIND_ARRAY_1);
4541 case 2: return HPSG_STATE(SOLIDITY_HARD, KIND_ARRAY_2);
4542 case 4: return HPSG_STATE(SOLIDITY_HARD, KIND_ARRAY_4);
4543 case 8: return HPSG_STATE(SOLIDITY_HARD, KIND_ARRAY_8);
4544 }
4545 }
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004546 return HPSG_STATE(SOLIDITY_HARD, KIND_OBJECT);
4547 }
4548
Ian Rogers30fab402012-01-23 15:43:46 -08004549 std::vector<uint8_t> buf_;
4550 uint8_t* p_;
4551 uint8_t* pieceLenField_;
Ian Rogers15bf2d32012-08-28 17:33:04 -07004552 void* startOfNextMemoryChunk_;
Ian Rogers30fab402012-01-23 15:43:46 -08004553 size_t totalAllocationUnits_;
4554 uint32_t type_;
Ian Rogers30fab402012-01-23 15:43:46 -08004555 bool needHeader_;
Mathieu Chartier36dab362014-07-30 14:59:56 -07004556 size_t chunk_overhead_;
Ian Rogers30fab402012-01-23 15:43:46 -08004557
Elliott Hughesa2155262011-11-16 16:26:58 -08004558 DISALLOW_COPY_AND_ASSIGN(HeapChunkContext);
4559};
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004560
Mathieu Chartier36dab362014-07-30 14:59:56 -07004561static void BumpPointerSpaceCallback(mirror::Object* obj, void* arg)
4562 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) EXCLUSIVE_LOCKS_REQUIRED(Locks::heap_bitmap_lock_) {
4563 const size_t size = RoundUp(obj->SizeOf(), kObjectAlignment);
Mathieu Chartierbc689b72014-12-14 17:01:31 -08004564 HeapChunkContext::HeapChunkJavaCallback(
Mathieu Chartier36dab362014-07-30 14:59:56 -07004565 obj, reinterpret_cast<void*>(reinterpret_cast<uintptr_t>(obj) + size), size, arg);
4566}
4567
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004568void Dbg::DdmSendHeapSegments(bool native) {
Mathieu Chartierbc689b72014-12-14 17:01:31 -08004569 Dbg::HpsgWhen when = native ? gDdmNhsgWhen : gDdmHpsgWhen;
4570 Dbg::HpsgWhat what = native ? gDdmNhsgWhat : gDdmHpsgWhat;
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004571 if (when == HPSG_WHEN_NEVER) {
4572 return;
4573 }
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004574 // Figure out what kind of chunks we'll be sending.
Mathieu Chartierbc689b72014-12-14 17:01:31 -08004575 CHECK(what == HPSG_WHAT_MERGED_OBJECTS || what == HPSG_WHAT_DISTINCT_OBJECTS)
4576 << static_cast<int>(what);
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004577
4578 // First, send a heap start chunk.
4579 uint8_t heap_id[4];
Brian Carlstrom7934ac22013-07-26 10:54:15 -07004580 JDWP::Set4BE(&heap_id[0], 1); // Heap id (bogus; we only have one heap).
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004581 Dbg::DdmSendChunk(native ? CHUNK_TYPE("NHST") : CHUNK_TYPE("HPST"), sizeof(heap_id), heap_id);
Hiroshi Yamauchicf58d4a2013-09-26 14:21:22 -07004582 Thread* self = Thread::Current();
Hiroshi Yamauchicf58d4a2013-09-26 14:21:22 -07004583 Locks::mutator_lock_->AssertSharedHeld(self);
Hiroshi Yamauchicf58d4a2013-09-26 14:21:22 -07004584
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004585 // Send a series of heap segment chunks.
Mathieu Chartierbc689b72014-12-14 17:01:31 -08004586 HeapChunkContext context(what == HPSG_WHAT_MERGED_OBJECTS, native);
Elliott Hughesa2155262011-11-16 16:26:58 -08004587 if (native) {
Ian Rogers872dd822014-10-30 11:19:14 -07004588#if defined(HAVE_ANDROID_OS) && defined(USE_DLMALLOC)
Mathieu Chartierbc689b72014-12-14 17:01:31 -08004589 dlmalloc_inspect_all(HeapChunkContext::HeapChunkNativeCallback, &context);
4590 HeapChunkContext::HeapChunkNativeCallback(nullptr, nullptr, 0, &context); // Indicate end of a space.
Christopher Ferrisc4ddc042014-05-13 14:47:50 -07004591#else
4592 UNIMPLEMENTED(WARNING) << "Native heap inspection is only supported with dlmalloc";
4593#endif
Elliott Hughesa2155262011-11-16 16:26:58 -08004594 } else {
Ian Rogers1d54e732013-05-02 21:10:01 -07004595 gc::Heap* heap = Runtime::Current()->GetHeap();
Mathieu Chartier36dab362014-07-30 14:59:56 -07004596 for (const auto& space : heap->GetContinuousSpaces()) {
4597 if (space->IsDlMallocSpace()) {
Mathieu Chartier4c69d7f2014-10-10 12:45:50 -07004598 ReaderMutexLock mu(self, *Locks::heap_bitmap_lock_);
Mathieu Chartier36dab362014-07-30 14:59:56 -07004599 // dlmalloc's chunk header is 2 * sizeof(size_t), but if the previous chunk is in use for an
4600 // allocation then the first sizeof(size_t) may belong to it.
4601 context.SetChunkOverhead(sizeof(size_t));
Mathieu Chartierbc689b72014-12-14 17:01:31 -08004602 space->AsDlMallocSpace()->Walk(HeapChunkContext::HeapChunkJavaCallback, &context);
Mathieu Chartier36dab362014-07-30 14:59:56 -07004603 } else if (space->IsRosAllocSpace()) {
4604 context.SetChunkOverhead(0);
Mathieu Chartier4c69d7f2014-10-10 12:45:50 -07004605 // Need to acquire the mutator lock before the heap bitmap lock with exclusive access since
4606 // RosAlloc's internal logic doesn't know to release and reacquire the heap bitmap lock.
4607 self->TransitionFromRunnableToSuspended(kSuspended);
4608 ThreadList* tl = Runtime::Current()->GetThreadList();
Mathieu Chartierbf9fc582015-03-13 17:21:25 -07004609 tl->SuspendAll(__FUNCTION__);
Mathieu Chartier4c69d7f2014-10-10 12:45:50 -07004610 {
4611 ReaderMutexLock mu(self, *Locks::heap_bitmap_lock_);
Mathieu Chartierbc689b72014-12-14 17:01:31 -08004612 space->AsRosAllocSpace()->Walk(HeapChunkContext::HeapChunkJavaCallback, &context);
Mathieu Chartier4c69d7f2014-10-10 12:45:50 -07004613 }
4614 tl->ResumeAll();
4615 self->TransitionFromSuspendedToRunnable();
Mathieu Chartier36dab362014-07-30 14:59:56 -07004616 } else if (space->IsBumpPointerSpace()) {
Mathieu Chartier4c69d7f2014-10-10 12:45:50 -07004617 ReaderMutexLock mu(self, *Locks::heap_bitmap_lock_);
Mathieu Chartier36dab362014-07-30 14:59:56 -07004618 context.SetChunkOverhead(0);
Mathieu Chartier36dab362014-07-30 14:59:56 -07004619 space->AsBumpPointerSpace()->Walk(BumpPointerSpaceCallback, &context);
Mathieu Chartierbc689b72014-12-14 17:01:31 -08004620 HeapChunkContext::HeapChunkJavaCallback(nullptr, nullptr, 0, &context);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08004621 } else if (space->IsRegionSpace()) {
4622 heap->IncrementDisableMovingGC(self);
4623 self->TransitionFromRunnableToSuspended(kSuspended);
4624 ThreadList* tl = Runtime::Current()->GetThreadList();
Mathieu Chartierbf9fc582015-03-13 17:21:25 -07004625 tl->SuspendAll(__FUNCTION__);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08004626 ReaderMutexLock mu(self, *Locks::heap_bitmap_lock_);
4627 context.SetChunkOverhead(0);
4628 space->AsRegionSpace()->Walk(BumpPointerSpaceCallback, &context);
4629 HeapChunkContext::HeapChunkJavaCallback(nullptr, nullptr, 0, &context);
4630 tl->ResumeAll();
4631 self->TransitionFromSuspendedToRunnable();
4632 heap->DecrementDisableMovingGC(self);
Mathieu Chartier36dab362014-07-30 14:59:56 -07004633 } else {
4634 UNIMPLEMENTED(WARNING) << "Not counting objects in space " << *space;
Mathieu Chartierb062fdd2012-07-03 09:51:48 -07004635 }
Mathieu Chartier36dab362014-07-30 14:59:56 -07004636 context.ResetStartOfNextChunk();
Mathieu Chartierb062fdd2012-07-03 09:51:48 -07004637 }
Mathieu Chartier4c69d7f2014-10-10 12:45:50 -07004638 ReaderMutexLock mu(self, *Locks::heap_bitmap_lock_);
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -07004639 // Walk the large objects, these are not in the AllocSpace.
Mathieu Chartier36dab362014-07-30 14:59:56 -07004640 context.SetChunkOverhead(0);
Mathieu Chartierbc689b72014-12-14 17:01:31 -08004641 heap->GetLargeObjectsSpace()->Walk(HeapChunkContext::HeapChunkJavaCallback, &context);
Elliott Hughesa2155262011-11-16 16:26:58 -08004642 }
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004643
4644 // Finally, send a heap end chunk.
4645 Dbg::DdmSendChunk(native ? CHUNK_TYPE("NHEN") : CHUNK_TYPE("HPEN"), sizeof(heap_id), heap_id);
Elliott Hughes767a1472011-10-26 18:49:02 -07004646}
4647
Elliott Hughesb1a58792013-07-11 18:10:58 -07004648static size_t GetAllocTrackerMax() {
4649#ifdef HAVE_ANDROID_OS
4650 // Check whether there's a system property overriding the number of records.
4651 const char* propertyName = "dalvik.vm.allocTrackerMax";
4652 char allocRecordMaxString[PROPERTY_VALUE_MAX];
4653 if (property_get(propertyName, allocRecordMaxString, "") > 0) {
4654 char* end;
4655 size_t value = strtoul(allocRecordMaxString, &end, 10);
4656 if (*end != '\0') {
Ruben Brunk3e47a742013-09-09 17:56:07 -07004657 LOG(ERROR) << "Ignoring " << propertyName << " '" << allocRecordMaxString
4658 << "' --- invalid";
Elliott Hughesb1a58792013-07-11 18:10:58 -07004659 return kDefaultNumAllocRecords;
4660 }
4661 if (!IsPowerOfTwo(value)) {
Ruben Brunk3e47a742013-09-09 17:56:07 -07004662 LOG(ERROR) << "Ignoring " << propertyName << " '" << allocRecordMaxString
4663 << "' --- not power of two";
Elliott Hughesb1a58792013-07-11 18:10:58 -07004664 return kDefaultNumAllocRecords;
4665 }
4666 return value;
4667 }
4668#endif
4669 return kDefaultNumAllocRecords;
4670}
4671
Brian Carlstrom306db812014-09-05 13:01:41 -07004672void Dbg::SetAllocTrackingEnabled(bool enable) {
4673 Thread* self = Thread::Current();
4674 if (enable) {
Sebastien Hertzb98063a2014-03-26 10:57:20 +01004675 {
Brian Carlstrom306db812014-09-05 13:01:41 -07004676 MutexLock mu(self, *Locks::alloc_tracker_lock_);
4677 if (recent_allocation_records_ != nullptr) {
4678 return; // Already enabled, bail.
Sebastien Hertzb98063a2014-03-26 10:57:20 +01004679 }
Brian Carlstrom306db812014-09-05 13:01:41 -07004680 alloc_record_max_ = GetAllocTrackerMax();
4681 LOG(INFO) << "Enabling alloc tracker (" << alloc_record_max_ << " entries of "
4682 << kMaxAllocRecordStackDepth << " frames, taking "
4683 << PrettySize(sizeof(AllocRecord) * alloc_record_max_) << ")";
4684 DCHECK_EQ(alloc_record_head_, 0U);
4685 DCHECK_EQ(alloc_record_count_, 0U);
4686 recent_allocation_records_ = new AllocRecord[alloc_record_max_];
4687 CHECK(recent_allocation_records_ != nullptr);
Elliott Hughes545a0642011-11-08 19:10:03 -08004688 }
Mathieu Chartier9ef78b52014-09-25 17:03:12 -07004689 Runtime::Current()->GetInstrumentation()->InstrumentQuickAllocEntryPoints();
Elliott Hughes545a0642011-11-08 19:10:03 -08004690 } else {
Sebastien Hertzb98063a2014-03-26 10:57:20 +01004691 {
Brian Carlstrom306db812014-09-05 13:01:41 -07004692 ScopedObjectAccess soa(self); // For type_cache_.Clear();
4693 MutexLock mu(self, *Locks::alloc_tracker_lock_);
4694 if (recent_allocation_records_ == nullptr) {
4695 return; // Already disabled, bail.
4696 }
Mathieu Chartier4345c462014-06-27 10:20:14 -07004697 LOG(INFO) << "Disabling alloc tracker";
Sebastien Hertzb98063a2014-03-26 10:57:20 +01004698 delete[] recent_allocation_records_;
Ian Rogersc0542af2014-09-03 16:16:56 -07004699 recent_allocation_records_ = nullptr;
Brian Carlstrom306db812014-09-05 13:01:41 -07004700 alloc_record_head_ = 0;
4701 alloc_record_count_ = 0;
Mathieu Chartier4345c462014-06-27 10:20:14 -07004702 type_cache_.Clear();
Sebastien Hertzb98063a2014-03-26 10:57:20 +01004703 }
Brian Carlstrom306db812014-09-05 13:01:41 -07004704 // If an allocation comes in before we uninstrument, we will safely drop it on the floor.
Mathieu Chartier9ef78b52014-09-25 17:03:12 -07004705 Runtime::Current()->GetInstrumentation()->UninstrumentQuickAllocEntryPoints();
Elliott Hughes545a0642011-11-08 19:10:03 -08004706 }
4707}
4708
Ian Rogers0399dde2012-06-06 17:09:28 -07004709struct AllocRecordStackVisitor : public StackVisitor {
Andreas Gampe277ccbd2014-11-03 21:36:10 -08004710 AllocRecordStackVisitor(Thread* thread, AllocRecord* record_in)
Ian Rogersb726dcb2012-09-05 08:57:23 -07004711 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_)
Nicolas Geoffray8e5bd182015-05-06 11:34:34 +01004712 : StackVisitor(thread, nullptr, StackVisitor::StackWalkKind::kIncludeInlinedFrames),
4713 record(record_in),
4714 depth(0) {}
Elliott Hughes545a0642011-11-08 19:10:03 -08004715
Ian Rogers00f7d0e2012-07-19 15:28:27 -07004716 // TODO: Enable annotalysis. We know lock is held in constructor, but abstraction confuses
4717 // annotalysis.
4718 bool VisitFrame() NO_THREAD_SAFETY_ANALYSIS {
Elliott Hughes545a0642011-11-08 19:10:03 -08004719 if (depth >= kMaxAllocRecordStackDepth) {
Elliott Hughes530fa002012-03-12 11:44:49 -07004720 return false;
Elliott Hughes545a0642011-11-08 19:10:03 -08004721 }
Brian Carlstromea46f952013-07-30 01:26:50 -07004722 mirror::ArtMethod* m = GetMethod();
Ian Rogers0399dde2012-06-06 17:09:28 -07004723 if (!m->IsRuntimeMethod()) {
Hiroshi Yamauchib5a9e3d2014-06-09 12:11:20 -07004724 record->StackElement(depth)->SetMethod(m);
4725 record->StackElement(depth)->SetDexPc(GetDexPc());
Elliott Hughes530fa002012-03-12 11:44:49 -07004726 ++depth;
Elliott Hughes545a0642011-11-08 19:10:03 -08004727 }
Elliott Hughes530fa002012-03-12 11:44:49 -07004728 return true;
Elliott Hughes545a0642011-11-08 19:10:03 -08004729 }
4730
4731 ~AllocRecordStackVisitor() {
4732 // Clear out any unused stack trace elements.
4733 for (; depth < kMaxAllocRecordStackDepth; ++depth) {
Hiroshi Yamauchib5a9e3d2014-06-09 12:11:20 -07004734 record->StackElement(depth)->SetMethod(nullptr);
4735 record->StackElement(depth)->SetDexPc(0);
Elliott Hughes545a0642011-11-08 19:10:03 -08004736 }
4737 }
4738
4739 AllocRecord* record;
4740 size_t depth;
4741};
4742
Ian Rogers844506b2014-09-12 19:59:33 -07004743void Dbg::RecordAllocation(Thread* self, mirror::Class* type, size_t byte_count) {
Brian Carlstrom306db812014-09-05 13:01:41 -07004744 MutexLock mu(self, *Locks::alloc_tracker_lock_);
Ian Rogersc0542af2014-09-03 16:16:56 -07004745 if (recent_allocation_records_ == nullptr) {
Brian Carlstrom306db812014-09-05 13:01:41 -07004746 // In the process of shutting down recording, bail.
Elliott Hughes545a0642011-11-08 19:10:03 -08004747 return;
4748 }
4749
4750 // Advance and clip.
Ian Rogers719d1a32014-03-06 12:13:39 -08004751 if (++alloc_record_head_ == alloc_record_max_) {
4752 alloc_record_head_ = 0;
Elliott Hughes545a0642011-11-08 19:10:03 -08004753 }
4754
4755 // Fill in the basics.
Ian Rogers719d1a32014-03-06 12:13:39 -08004756 AllocRecord* record = &recent_allocation_records_[alloc_record_head_];
Hiroshi Yamauchib5a9e3d2014-06-09 12:11:20 -07004757 record->SetType(type);
4758 record->SetByteCount(byte_count);
4759 record->SetThinLockId(self->GetThreadId());
Elliott Hughes545a0642011-11-08 19:10:03 -08004760
4761 // Fill in the stack trace.
Ian Rogers7a22fa62013-01-23 12:16:16 -08004762 AllocRecordStackVisitor visitor(self, record);
Ian Rogers0399dde2012-06-06 17:09:28 -07004763 visitor.WalkStack();
Elliott Hughes545a0642011-11-08 19:10:03 -08004764
Ian Rogers719d1a32014-03-06 12:13:39 -08004765 if (alloc_record_count_ < alloc_record_max_) {
4766 ++alloc_record_count_;
Elliott Hughes545a0642011-11-08 19:10:03 -08004767 }
4768}
4769
Elliott Hughesa8f93cb2012-06-08 17:08:48 -07004770// Returns the index of the head element.
4771//
Brian Carlstrom306db812014-09-05 13:01:41 -07004772// We point at the most-recently-written record, so if alloc_record_count_ is 1
Elliott Hughesa8f93cb2012-06-08 17:08:48 -07004773// we want to use the current element. Take "head+1" and subtract count
4774// from it.
4775//
4776// We need to handle underflow in our circular buffer, so we add
Brian Carlstrom306db812014-09-05 13:01:41 -07004777// alloc_record_max_ and then mask it back down.
Ian Rogers719d1a32014-03-06 12:13:39 -08004778size_t Dbg::HeadIndex() {
4779 return (Dbg::alloc_record_head_ + 1 + Dbg::alloc_record_max_ - Dbg::alloc_record_count_) &
4780 (Dbg::alloc_record_max_ - 1);
Elliott Hughes545a0642011-11-08 19:10:03 -08004781}
4782
4783void Dbg::DumpRecentAllocations() {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07004784 ScopedObjectAccess soa(Thread::Current());
Brian Carlstrom306db812014-09-05 13:01:41 -07004785 MutexLock mu(soa.Self(), *Locks::alloc_tracker_lock_);
Ian Rogersc0542af2014-09-03 16:16:56 -07004786 if (recent_allocation_records_ == nullptr) {
Elliott Hughes545a0642011-11-08 19:10:03 -08004787 LOG(INFO) << "Not recording tracked allocations";
4788 return;
4789 }
4790
4791 // "i" is the head of the list. We want to start at the end of the
4792 // list and move forward to the tail.
Elliott Hughesa8f93cb2012-06-08 17:08:48 -07004793 size_t i = HeadIndex();
Brian Carlstrom306db812014-09-05 13:01:41 -07004794 const uint16_t capped_count = CappedAllocRecordCount(Dbg::alloc_record_count_);
4795 uint16_t count = capped_count;
Elliott Hughes545a0642011-11-08 19:10:03 -08004796
Ian Rogers719d1a32014-03-06 12:13:39 -08004797 LOG(INFO) << "Tracked allocations, (head=" << alloc_record_head_ << " count=" << count << ")";
Elliott Hughes545a0642011-11-08 19:10:03 -08004798 while (count--) {
4799 AllocRecord* record = &recent_allocation_records_[i];
4800
Hiroshi Yamauchib5a9e3d2014-06-09 12:11:20 -07004801 LOG(INFO) << StringPrintf(" Thread %-2d %6zd bytes ", record->ThinLockId(), record->ByteCount())
4802 << PrettyClass(record->Type());
Elliott Hughes545a0642011-11-08 19:10:03 -08004803
4804 for (size_t stack_frame = 0; stack_frame < kMaxAllocRecordStackDepth; ++stack_frame) {
Hiroshi Yamauchib5a9e3d2014-06-09 12:11:20 -07004805 AllocRecordStackTraceElement* stack_element = record->StackElement(stack_frame);
4806 mirror::ArtMethod* m = stack_element->Method();
Ian Rogersc0542af2014-09-03 16:16:56 -07004807 if (m == nullptr) {
Elliott Hughes545a0642011-11-08 19:10:03 -08004808 break;
4809 }
Hiroshi Yamauchib5a9e3d2014-06-09 12:11:20 -07004810 LOG(INFO) << " " << PrettyMethod(m) << " line " << stack_element->LineNumber();
Elliott Hughes545a0642011-11-08 19:10:03 -08004811 }
4812
4813 // pause periodically to help logcat catch up
4814 if ((count % 5) == 0) {
4815 usleep(40000);
4816 }
4817
Ian Rogers719d1a32014-03-06 12:13:39 -08004818 i = (i + 1) & (alloc_record_max_ - 1);
Elliott Hughes545a0642011-11-08 19:10:03 -08004819 }
4820}
4821
4822class StringTable {
4823 public:
4824 StringTable() {
4825 }
4826
Mathieu Chartier4345c462014-06-27 10:20:14 -07004827 void Add(const std::string& str) {
4828 table_.insert(str);
4829 }
4830
4831 void Add(const char* str) {
4832 table_.insert(str);
Elliott Hughes545a0642011-11-08 19:10:03 -08004833 }
4834
Elliott Hughesa8f93cb2012-06-08 17:08:48 -07004835 size_t IndexOf(const char* s) const {
Mathieu Chartier02e25112013-08-14 16:14:24 -07004836 auto it = table_.find(s);
Elliott Hughesa8f93cb2012-06-08 17:08:48 -07004837 if (it == table_.end()) {
4838 LOG(FATAL) << "IndexOf(\"" << s << "\") failed";
4839 }
4840 return std::distance(table_.begin(), it);
Elliott Hughes545a0642011-11-08 19:10:03 -08004841 }
4842
Elliott Hughesa8f93cb2012-06-08 17:08:48 -07004843 size_t Size() const {
Elliott Hughes545a0642011-11-08 19:10:03 -08004844 return table_.size();
4845 }
4846
Elliott Hughesa8f93cb2012-06-08 17:08:48 -07004847 void WriteTo(std::vector<uint8_t>& bytes) const {
Mathieu Chartier02e25112013-08-14 16:14:24 -07004848 for (const std::string& str : table_) {
4849 const char* s = str.c_str();
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08004850 size_t s_len = CountModifiedUtf8Chars(s);
Christopher Ferris8a354052015-04-24 17:23:53 -07004851 std::unique_ptr<uint16_t[]> s_utf16(new uint16_t[s_len]);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08004852 ConvertModifiedUtf8ToUtf16(s_utf16.get(), s);
4853 JDWP::AppendUtf16BE(bytes, s_utf16.get(), s_len);
Elliott Hughes545a0642011-11-08 19:10:03 -08004854 }
4855 }
4856
4857 private:
Elliott Hughesa8f93cb2012-06-08 17:08:48 -07004858 std::set<std::string> table_;
Elliott Hughes545a0642011-11-08 19:10:03 -08004859 DISALLOW_COPY_AND_ASSIGN(StringTable);
4860};
4861
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07004862static const char* GetMethodSourceFile(mirror::ArtMethod* method)
Sebastien Hertz280286a2014-04-28 09:26:50 +02004863 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07004864 DCHECK(method != nullptr);
4865 const char* source_file = method->GetDeclaringClassSourceFile();
Sebastien Hertz280286a2014-04-28 09:26:50 +02004866 return (source_file != nullptr) ? source_file : "";
4867}
4868
Elliott Hughes545a0642011-11-08 19:10:03 -08004869/*
4870 * The data we send to DDMS contains everything we have recorded.
4871 *
4872 * Message header (all values big-endian):
4873 * (1b) message header len (to allow future expansion); includes itself
4874 * (1b) entry header len
4875 * (1b) stack frame len
4876 * (2b) number of entries
4877 * (4b) offset to string table from start of message
4878 * (2b) number of class name strings
4879 * (2b) number of method name strings
4880 * (2b) number of source file name strings
4881 * For each entry:
4882 * (4b) total allocation size
Elliott Hughes221229c2013-01-08 18:17:50 -08004883 * (2b) thread id
Elliott Hughes545a0642011-11-08 19:10:03 -08004884 * (2b) allocated object's class name index
4885 * (1b) stack depth
4886 * For each stack frame:
4887 * (2b) method's class name
4888 * (2b) method name
4889 * (2b) method source file
4890 * (2b) line number, clipped to 32767; -2 if native; -1 if no source
4891 * (xb) class name strings
4892 * (xb) method name strings
4893 * (xb) source file strings
4894 *
4895 * As with other DDM traffic, strings are sent as a 4-byte length
4896 * followed by UTF-16 data.
4897 *
4898 * We send up 16-bit unsigned indexes into string tables. In theory there
Brian Carlstrom306db812014-09-05 13:01:41 -07004899 * can be (kMaxAllocRecordStackDepth * alloc_record_max_) unique strings in
Elliott Hughes545a0642011-11-08 19:10:03 -08004900 * each table, but in practice there should be far fewer.
4901 *
4902 * The chief reason for using a string table here is to keep the size of
4903 * the DDMS message to a minimum. This is partly to make the protocol
4904 * efficient, but also because we have to form the whole thing up all at
4905 * once in a memory buffer.
4906 *
4907 * We use separate string tables for class names, method names, and source
4908 * files to keep the indexes small. There will generally be no overlap
4909 * between the contents of these tables.
4910 */
4911jbyteArray Dbg::GetRecentAllocations() {
Ian Rogerscf7f1912014-10-22 22:06:39 -07004912 if ((false)) {
Elliott Hughes545a0642011-11-08 19:10:03 -08004913 DumpRecentAllocations();
4914 }
4915
Ian Rogers50b35e22012-10-04 10:09:15 -07004916 Thread* self = Thread::Current();
Elliott Hughes545a0642011-11-08 19:10:03 -08004917 std::vector<uint8_t> bytes;
Mathieu Chartier46e811b2013-07-10 17:09:14 -07004918 {
Brian Carlstrom306db812014-09-05 13:01:41 -07004919 MutexLock mu(self, *Locks::alloc_tracker_lock_);
Mathieu Chartier46e811b2013-07-10 17:09:14 -07004920 //
4921 // Part 1: generate string tables.
4922 //
4923 StringTable class_names;
4924 StringTable method_names;
4925 StringTable filenames;
Elliott Hughes545a0642011-11-08 19:10:03 -08004926
Brian Carlstrom306db812014-09-05 13:01:41 -07004927 const uint16_t capped_count = CappedAllocRecordCount(Dbg::alloc_record_count_);
4928 uint16_t count = capped_count;
4929 size_t idx = HeadIndex();
Mathieu Chartier46e811b2013-07-10 17:09:14 -07004930 while (count--) {
4931 AllocRecord* record = &recent_allocation_records_[idx];
Ian Rogers1ff3c982014-08-12 02:30:58 -07004932 std::string temp;
4933 class_names.Add(record->Type()->GetDescriptor(&temp));
Mathieu Chartier46e811b2013-07-10 17:09:14 -07004934 for (size_t i = 0; i < kMaxAllocRecordStackDepth; i++) {
Hiroshi Yamauchib5a9e3d2014-06-09 12:11:20 -07004935 mirror::ArtMethod* m = record->StackElement(i)->Method();
Ian Rogersc0542af2014-09-03 16:16:56 -07004936 if (m != nullptr) {
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07004937 class_names.Add(m->GetDeclaringClassDescriptor());
4938 method_names.Add(m->GetName());
4939 filenames.Add(GetMethodSourceFile(m));
Mathieu Chartier46e811b2013-07-10 17:09:14 -07004940 }
4941 }
Elliott Hughes545a0642011-11-08 19:10:03 -08004942
Ian Rogers719d1a32014-03-06 12:13:39 -08004943 idx = (idx + 1) & (alloc_record_max_ - 1);
Elliott Hughes545a0642011-11-08 19:10:03 -08004944 }
4945
Brian Carlstrom306db812014-09-05 13:01:41 -07004946 LOG(INFO) << "allocation records: " << capped_count;
Mathieu Chartier46e811b2013-07-10 17:09:14 -07004947
4948 //
4949 // Part 2: Generate the output and store it in the buffer.
4950 //
4951
4952 // (1b) message header len (to allow future expansion); includes itself
4953 // (1b) entry header len
4954 // (1b) stack frame len
4955 const int kMessageHeaderLen = 15;
4956 const int kEntryHeaderLen = 9;
4957 const int kStackFrameLen = 8;
4958 JDWP::Append1BE(bytes, kMessageHeaderLen);
4959 JDWP::Append1BE(bytes, kEntryHeaderLen);
4960 JDWP::Append1BE(bytes, kStackFrameLen);
4961
4962 // (2b) number of entries
4963 // (4b) offset to string table from start of message
4964 // (2b) number of class name strings
4965 // (2b) number of method name strings
4966 // (2b) number of source file name strings
Brian Carlstrom306db812014-09-05 13:01:41 -07004967 JDWP::Append2BE(bytes, capped_count);
Mathieu Chartier46e811b2013-07-10 17:09:14 -07004968 size_t string_table_offset = bytes.size();
Brian Carlstrom7934ac22013-07-26 10:54:15 -07004969 JDWP::Append4BE(bytes, 0); // We'll patch this later...
Mathieu Chartier46e811b2013-07-10 17:09:14 -07004970 JDWP::Append2BE(bytes, class_names.Size());
4971 JDWP::Append2BE(bytes, method_names.Size());
4972 JDWP::Append2BE(bytes, filenames.Size());
4973
Mathieu Chartier46e811b2013-07-10 17:09:14 -07004974 idx = HeadIndex();
Ian Rogers1ff3c982014-08-12 02:30:58 -07004975 std::string temp;
Brian Carlstrom306db812014-09-05 13:01:41 -07004976 for (count = capped_count; count != 0; --count) {
Mathieu Chartier46e811b2013-07-10 17:09:14 -07004977 // For each entry:
4978 // (4b) total allocation size
4979 // (2b) thread id
4980 // (2b) allocated object's class name index
4981 // (1b) stack depth
4982 AllocRecord* record = &recent_allocation_records_[idx];
4983 size_t stack_depth = record->GetDepth();
Mathieu Chartierf8322842014-05-16 10:59:25 -07004984 size_t allocated_object_class_name_index =
Ian Rogers1ff3c982014-08-12 02:30:58 -07004985 class_names.IndexOf(record->Type()->GetDescriptor(&temp));
Hiroshi Yamauchib5a9e3d2014-06-09 12:11:20 -07004986 JDWP::Append4BE(bytes, record->ByteCount());
4987 JDWP::Append2BE(bytes, record->ThinLockId());
Mathieu Chartier46e811b2013-07-10 17:09:14 -07004988 JDWP::Append2BE(bytes, allocated_object_class_name_index);
4989 JDWP::Append1BE(bytes, stack_depth);
4990
Mathieu Chartier46e811b2013-07-10 17:09:14 -07004991 for (size_t stack_frame = 0; stack_frame < stack_depth; ++stack_frame) {
4992 // For each stack frame:
4993 // (2b) method's class name
4994 // (2b) method name
4995 // (2b) method source file
4996 // (2b) line number, clipped to 32767; -2 if native; -1 if no source
Hiroshi Yamauchib5a9e3d2014-06-09 12:11:20 -07004997 mirror::ArtMethod* m = record->StackElement(stack_frame)->Method();
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07004998 size_t class_name_index = class_names.IndexOf(m->GetDeclaringClassDescriptor());
4999 size_t method_name_index = method_names.IndexOf(m->GetName());
5000 size_t file_name_index = filenames.IndexOf(GetMethodSourceFile(m));
Mathieu Chartier46e811b2013-07-10 17:09:14 -07005001 JDWP::Append2BE(bytes, class_name_index);
5002 JDWP::Append2BE(bytes, method_name_index);
5003 JDWP::Append2BE(bytes, file_name_index);
Hiroshi Yamauchib5a9e3d2014-06-09 12:11:20 -07005004 JDWP::Append2BE(bytes, record->StackElement(stack_frame)->LineNumber());
Mathieu Chartier46e811b2013-07-10 17:09:14 -07005005 }
Ian Rogers719d1a32014-03-06 12:13:39 -08005006 idx = (idx + 1) & (alloc_record_max_ - 1);
Mathieu Chartier46e811b2013-07-10 17:09:14 -07005007 }
5008
5009 // (xb) class name strings
5010 // (xb) method name strings
5011 // (xb) source file strings
5012 JDWP::Set4BE(&bytes[string_table_offset], bytes.size());
5013 class_names.WriteTo(bytes);
5014 method_names.WriteTo(bytes);
5015 filenames.WriteTo(bytes);
Elliott Hughes545a0642011-11-08 19:10:03 -08005016 }
Ian Rogers50b35e22012-10-04 10:09:15 -07005017 JNIEnv* env = self->GetJniEnv();
Elliott Hughes545a0642011-11-08 19:10:03 -08005018 jbyteArray result = env->NewByteArray(bytes.size());
Ian Rogersc0542af2014-09-03 16:16:56 -07005019 if (result != nullptr) {
Elliott Hughes545a0642011-11-08 19:10:03 -08005020 env->SetByteArrayRegion(result, 0, bytes.size(), reinterpret_cast<const jbyte*>(&bytes[0]));
5021 }
5022 return result;
5023}
5024
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07005025mirror::ArtMethod* DeoptimizationRequest::Method() const {
5026 ScopedObjectAccessUnchecked soa(Thread::Current());
5027 return soa.DecodeMethod(method_);
5028}
5029
5030void DeoptimizationRequest::SetMethod(mirror::ArtMethod* m) {
5031 ScopedObjectAccessUnchecked soa(Thread::Current());
5032 method_ = soa.EncodeMethod(m);
5033}
5034
Elliott Hughes872d4ec2011-10-21 17:07:15 -07005035} // namespace art