blob: 1f60b5492e084c98601e3012035c29469cc8d7e1 [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:
Mathieu Chartierb43390c2015-05-12 10:47:11 -07002146 case kWaitingForGetObjectsAllocated:
Jeff Hao920af3e2013-08-28 15:46:38 -07002147 case kWaitingForJniOnLoad:
Sebastien Hertzbae182c2013-12-17 10:42:03 +01002148 case kWaitingForMethodTracingStart:
Jeff Hao920af3e2013-08-28 15:46:38 -07002149 case kWaitingForSignalCatcherOutput:
Hiroshi Yamauchi0c8c3032015-01-16 16:54:35 -08002150 case kWaitingForVisitObjects:
Jeff Hao920af3e2013-08-28 15:46:38 -07002151 case kWaitingInMainDebuggerLoop:
2152 case kWaitingInMainSignalCatcherLoop:
2153 case kWaitingPerformingGc:
2154 case kWaiting:
2155 return JDWP::TS_WAIT;
2156 // Don't add a 'default' here so the compiler can spot incompatible enum changes.
2157 }
2158 LOG(FATAL) << "Unknown thread state: " << state;
2159 return JDWP::TS_ZOMBIE;
2160}
2161
Sebastien Hertz52d131d2014-03-13 16:17:40 +01002162JDWP::JdwpError Dbg::GetThreadStatus(JDWP::ObjectId thread_id, JDWP::JdwpThreadStatus* pThreadStatus,
2163 JDWP::JdwpSuspendStatus* pSuspendStatus) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002164 ScopedObjectAccess soa(Thread::Current());
Elliott Hughes499c5132011-11-17 14:55:11 -08002165
Elliott Hughes9e0c1752013-01-09 14:02:58 -08002166 *pSuspendStatus = JDWP::SUSPEND_STATUS_NOT_SUSPENDED;
2167
Ian Rogersc0542af2014-09-03 16:16:56 -07002168 JDWP::JdwpError error;
2169 Thread* thread = DecodeThread(soa, thread_id, &error);
Elliott Hughes221229c2013-01-08 18:17:50 -08002170 if (error != JDWP::ERR_NONE) {
2171 if (error == JDWP::ERR_THREAD_NOT_ALIVE) {
2172 *pThreadStatus = JDWP::TS_ZOMBIE;
Elliott Hughes221229c2013-01-08 18:17:50 -08002173 return JDWP::ERR_NONE;
2174 }
2175 return error;
Elliott Hughes499c5132011-11-17 14:55:11 -08002176 }
2177
Elliott Hughes9e0c1752013-01-09 14:02:58 -08002178 if (IsSuspendedForDebugger(soa, thread)) {
2179 *pSuspendStatus = JDWP::SUSPEND_STATUS_SUSPENDED;
Elliott Hughes499c5132011-11-17 14:55:11 -08002180 }
2181
Jeff Hao920af3e2013-08-28 15:46:38 -07002182 *pThreadStatus = ToJdwpThreadStatus(thread->GetState());
Elliott Hughes221229c2013-01-08 18:17:50 -08002183 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002184}
2185
Elliott Hughes221229c2013-01-08 18:17:50 -08002186JDWP::JdwpError Dbg::GetThreadDebugSuspendCount(JDWP::ObjectId thread_id, JDWP::ExpandBuf* pReply) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002187 ScopedObjectAccess soa(Thread::Current());
Ian Rogersc0542af2014-09-03 16:16:56 -07002188 JDWP::JdwpError error;
2189 Thread* thread = DecodeThread(soa, thread_id, &error);
Elliott Hughes221229c2013-01-08 18:17:50 -08002190 if (error != JDWP::ERR_NONE) {
2191 return error;
Elliott Hughes2435a572012-02-17 16:07:41 -08002192 }
Ian Rogers50b35e22012-10-04 10:09:15 -07002193 MutexLock mu2(soa.Self(), *Locks::thread_suspend_count_lock_);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002194 expandBufAdd4BE(pReply, thread->GetDebugSuspendCount());
Elliott Hughes2435a572012-02-17 16:07:41 -08002195 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002196}
2197
Elliott Hughesf9501702013-01-11 11:22:27 -08002198JDWP::JdwpError Dbg::Interrupt(JDWP::ObjectId thread_id) {
2199 ScopedObjectAccess soa(Thread::Current());
Ian Rogersc0542af2014-09-03 16:16:56 -07002200 JDWP::JdwpError error;
2201 Thread* thread = DecodeThread(soa, thread_id, &error);
Elliott Hughesf9501702013-01-11 11:22:27 -08002202 if (error != JDWP::ERR_NONE) {
2203 return error;
2204 }
Ian Rogersdd7624d2014-03-14 17:43:00 -07002205 thread->Interrupt(soa.Self());
Elliott Hughesf9501702013-01-11 11:22:27 -08002206 return JDWP::ERR_NONE;
2207}
2208
Sebastien Hertz070f7322014-09-09 12:08:49 +02002209static bool IsInDesiredThreadGroup(ScopedObjectAccessUnchecked& soa,
2210 mirror::Object* desired_thread_group, mirror::Object* peer)
2211 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
2212 // Do we want threads from all thread groups?
2213 if (desired_thread_group == nullptr) {
2214 return true;
2215 }
Mathieu Chartierc7853442015-03-27 14:35:38 -07002216 ArtField* thread_group_field = soa.DecodeField(WellKnownClasses::java_lang_Thread_group);
Sebastien Hertz070f7322014-09-09 12:08:49 +02002217 DCHECK(thread_group_field != nullptr);
2218 mirror::Object* group = thread_group_field->GetObject(peer);
2219 return (group == desired_thread_group);
2220}
2221
Sebastien Hertza06430c2014-09-15 19:21:30 +02002222void Dbg::GetThreads(mirror::Object* thread_group, std::vector<JDWP::ObjectId>* thread_ids) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002223 ScopedObjectAccessUnchecked soa(Thread::Current());
Sebastien Hertz070f7322014-09-09 12:08:49 +02002224 std::list<Thread*> all_threads_list;
2225 {
2226 MutexLock mu(Thread::Current(), *Locks::thread_list_lock_);
2227 all_threads_list = Runtime::Current()->GetThreadList()->GetList();
2228 }
2229 for (Thread* t : all_threads_list) {
2230 if (t == Dbg::GetDebugThread()) {
2231 // Skip the JDWP thread. Some debuggers get bent out of shape when they can't suspend and
2232 // query all threads, so it's easier if we just don't tell them about this thread.
2233 continue;
2234 }
2235 if (t->IsStillStarting()) {
2236 // This thread is being started (and has been registered in the thread list). However, it is
2237 // not completely started yet so we must ignore it.
2238 continue;
2239 }
2240 mirror::Object* peer = t->GetPeer();
2241 if (peer == nullptr) {
Mathieu Chartier2cebb242015-04-21 16:50:40 -07002242 // 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 +02002243 // this thread yet.
2244 // TODO: if we identified threads to the debugger by their Thread*
2245 // rather than their peer's mirror::Object*, we could fix this.
2246 // Doing so might help us report ZOMBIE threads too.
2247 continue;
2248 }
2249 if (IsInDesiredThreadGroup(soa, thread_group, peer)) {
2250 thread_ids->push_back(gRegistry->Add(peer));
2251 }
2252 }
Elliott Hughescaf76542012-06-28 16:08:22 -07002253}
Elliott Hughesa2155262011-11-16 16:26:58 -08002254
Ian Rogersc0542af2014-09-03 16:16:56 -07002255static int GetStackDepth(Thread* thread) SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Ian Rogers0399dde2012-06-06 17:09:28 -07002256 struct CountStackDepthVisitor : public StackVisitor {
Andreas Gampe277ccbd2014-11-03 21:36:10 -08002257 explicit CountStackDepthVisitor(Thread* thread_in)
Nicolas Geoffray8e5bd182015-05-06 11:34:34 +01002258 : StackVisitor(thread_in, nullptr, StackVisitor::StackWalkKind::kIncludeInlinedFrames),
2259 depth(0) {}
Ian Rogers0399dde2012-06-06 17:09:28 -07002260
Elliott Hughes64f574f2013-02-20 14:57:12 -08002261 // TODO: Enable annotalysis. We know lock is held in constructor, but abstraction confuses
2262 // annotalysis.
2263 bool VisitFrame() NO_THREAD_SAFETY_ANALYSIS {
Ian Rogers0399dde2012-06-06 17:09:28 -07002264 if (!GetMethod()->IsRuntimeMethod()) {
Elliott Hughesf8a2df72011-12-01 12:19:54 -08002265 ++depth;
2266 }
Elliott Hughes530fa002012-03-12 11:44:49 -07002267 return true;
Elliott Hughesa2e54f62011-11-17 13:01:30 -08002268 }
2269 size_t depth;
2270 };
Elliott Hughes08fc03a2012-06-26 17:34:00 -07002271
Ian Rogers7a22fa62013-01-23 12:16:16 -08002272 CountStackDepthVisitor visitor(thread);
Ian Rogers0399dde2012-06-06 17:09:28 -07002273 visitor.WalkStack();
Elliott Hughesa2e54f62011-11-17 13:01:30 -08002274 return visitor.depth;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002275}
2276
Ian Rogersc0542af2014-09-03 16:16:56 -07002277JDWP::JdwpError Dbg::GetThreadFrameCount(JDWP::ObjectId thread_id, size_t* result) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002278 ScopedObjectAccess soa(Thread::Current());
Ian Rogersc0542af2014-09-03 16:16:56 -07002279 JDWP::JdwpError error;
2280 *result = 0;
2281 Thread* thread = DecodeThread(soa, thread_id, &error);
Elliott Hughes221229c2013-01-08 18:17:50 -08002282 if (error != JDWP::ERR_NONE) {
2283 return error;
2284 }
Elliott Hughesf15f4a02013-01-09 10:09:38 -08002285 if (!IsSuspendedForDebugger(soa, thread)) {
2286 return JDWP::ERR_THREAD_NOT_SUSPENDED;
2287 }
Ian Rogersc0542af2014-09-03 16:16:56 -07002288 *result = GetStackDepth(thread);
Elliott Hughes221229c2013-01-08 18:17:50 -08002289 return JDWP::ERR_NONE;
Elliott Hughes86964332012-02-15 19:37:42 -08002290}
2291
Ian Rogers306057f2012-11-26 12:45:53 -08002292JDWP::JdwpError Dbg::GetThreadFrames(JDWP::ObjectId thread_id, size_t start_frame,
2293 size_t frame_count, JDWP::ExpandBuf* buf) {
Elliott Hughes6e9d22c2012-06-22 15:02:37 -07002294 class GetFrameVisitor : public StackVisitor {
2295 public:
Andreas Gampe277ccbd2014-11-03 21:36:10 -08002296 GetFrameVisitor(Thread* thread, size_t start_frame_in, size_t frame_count_in,
2297 JDWP::ExpandBuf* buf_in)
Ian Rogersb726dcb2012-09-05 08:57:23 -07002298 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_)
Nicolas Geoffray8e5bd182015-05-06 11:34:34 +01002299 : StackVisitor(thread, nullptr, StackVisitor::StackWalkKind::kIncludeInlinedFrames),
2300 depth_(0),
2301 start_frame_(start_frame_in),
2302 frame_count_(frame_count_in),
2303 buf_(buf_in) {
Elliott Hughes6e9d22c2012-06-22 15:02:37 -07002304 expandBufAdd4BE(buf_, frame_count_);
Elliott Hughes03181a82011-11-17 17:22:21 -08002305 }
Ian Rogers0399dde2012-06-06 17:09:28 -07002306
Sebastien Hertz69206392015-04-07 15:54:25 +02002307 bool VisitFrame() OVERRIDE SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Ian Rogers0399dde2012-06-06 17:09:28 -07002308 if (GetMethod()->IsRuntimeMethod()) {
Brian Carlstrom7934ac22013-07-26 10:54:15 -07002309 return true; // The debugger can't do anything useful with a frame that has no Method*.
Elliott Hughes03181a82011-11-17 17:22:21 -08002310 }
Elliott Hughes6e9d22c2012-06-22 15:02:37 -07002311 if (depth_ >= start_frame_ + frame_count_) {
Elliott Hughes530fa002012-03-12 11:44:49 -07002312 return false;
Elliott Hughes03181a82011-11-17 17:22:21 -08002313 }
Elliott Hughes6e9d22c2012-06-22 15:02:37 -07002314 if (depth_ >= start_frame_) {
2315 JDWP::FrameId frame_id(GetFrameId());
2316 JDWP::JdwpLocation location;
Sebastien Hertz6995c602014-09-09 12:10:13 +02002317 SetJdwpLocation(&location, GetMethod(), GetDexPc());
Ian Rogersef7d42f2014-01-06 12:55:46 -08002318 VLOG(jdwp) << StringPrintf(" Frame %3zd: id=%3" PRIu64 " ", depth_, frame_id) << location;
Elliott Hughes6e9d22c2012-06-22 15:02:37 -07002319 expandBufAdd8BE(buf_, frame_id);
2320 expandBufAddLocation(buf_, location);
2321 }
2322 ++depth_;
Elliott Hughes530fa002012-03-12 11:44:49 -07002323 return true;
Elliott Hughes03181a82011-11-17 17:22:21 -08002324 }
Elliott Hughes6e9d22c2012-06-22 15:02:37 -07002325
2326 private:
2327 size_t depth_;
2328 const size_t start_frame_;
2329 const size_t frame_count_;
2330 JDWP::ExpandBuf* buf_;
Elliott Hughes03181a82011-11-17 17:22:21 -08002331 };
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002332
2333 ScopedObjectAccessUnchecked soa(Thread::Current());
Ian Rogersc0542af2014-09-03 16:16:56 -07002334 JDWP::JdwpError error;
2335 Thread* thread = DecodeThread(soa, thread_id, &error);
Elliott Hughes221229c2013-01-08 18:17:50 -08002336 if (error != JDWP::ERR_NONE) {
2337 return error;
2338 }
Elliott Hughesf15f4a02013-01-09 10:09:38 -08002339 if (!IsSuspendedForDebugger(soa, thread)) {
2340 return JDWP::ERR_THREAD_NOT_SUSPENDED;
2341 }
Ian Rogers7a22fa62013-01-23 12:16:16 -08002342 GetFrameVisitor visitor(thread, start_frame, frame_count, buf);
Ian Rogers0399dde2012-06-06 17:09:28 -07002343 visitor.WalkStack();
Elliott Hughes6e9d22c2012-06-22 15:02:37 -07002344 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002345}
2346
2347JDWP::ObjectId Dbg::GetThreadSelfId() {
Sebastien Hertz6995c602014-09-09 12:10:13 +02002348 return GetThreadId(Thread::Current());
2349}
2350
2351JDWP::ObjectId Dbg::GetThreadId(Thread* thread) {
Mathieu Chartierdbe6f462012-09-25 16:54:50 -07002352 ScopedObjectAccessUnchecked soa(Thread::Current());
Sebastien Hertz6995c602014-09-09 12:10:13 +02002353 return gRegistry->Add(thread->GetPeer());
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002354}
2355
Elliott Hughes475fc232011-10-25 15:00:35 -07002356void Dbg::SuspendVM() {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002357 Runtime::Current()->GetThreadList()->SuspendAllForDebugger();
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002358}
2359
2360void Dbg::ResumeVM() {
Sebastien Hertz253fa552014-10-14 17:27:15 +02002361 Runtime::Current()->GetThreadList()->ResumeAllForDebugger();
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002362}
2363
Elliott Hughes221229c2013-01-08 18:17:50 -08002364JDWP::JdwpError Dbg::SuspendThread(JDWP::ObjectId thread_id, bool request_suspension) {
Ian Rogersf3d874c2014-07-17 18:52:42 -07002365 Thread* self = Thread::Current();
Ian Rogersc0542af2014-09-03 16:16:56 -07002366 ScopedLocalRef<jobject> peer(self->GetJniEnv(), nullptr);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002367 {
Ian Rogersf3d874c2014-07-17 18:52:42 -07002368 ScopedObjectAccess soa(self);
Ian Rogersc0542af2014-09-03 16:16:56 -07002369 JDWP::JdwpError error;
2370 peer.reset(soa.AddLocalReference<jobject>(gRegistry->Get<mirror::Object*>(thread_id, &error)));
Elliott Hughes4e235312011-12-02 11:34:15 -08002371 }
Ian Rogersc0542af2014-09-03 16:16:56 -07002372 if (peer.get() == nullptr) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002373 return JDWP::ERR_THREAD_NOT_ALIVE;
2374 }
Ian Rogers4ad5cd32014-11-11 23:08:07 -08002375 // Suspend thread to build stack trace.
Elliott Hughesf327e072013-01-09 16:01:26 -08002376 bool timed_out;
Brian Carlstromba32de42014-08-27 23:43:46 -07002377 ThreadList* thread_list = Runtime::Current()->GetThreadList();
2378 Thread* thread = thread_list->SuspendThreadByPeer(peer.get(), request_suspension, true,
2379 &timed_out);
Ian Rogersc0542af2014-09-03 16:16:56 -07002380 if (thread != nullptr) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002381 return JDWP::ERR_NONE;
Elliott Hughesf327e072013-01-09 16:01:26 -08002382 } else if (timed_out) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002383 return JDWP::ERR_INTERNAL;
2384 } else {
2385 return JDWP::ERR_THREAD_NOT_ALIVE;
2386 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002387}
2388
Elliott Hughes221229c2013-01-08 18:17:50 -08002389void Dbg::ResumeThread(JDWP::ObjectId thread_id) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002390 ScopedObjectAccessUnchecked soa(Thread::Current());
Ian Rogersc0542af2014-09-03 16:16:56 -07002391 JDWP::JdwpError error;
2392 mirror::Object* peer = gRegistry->Get<mirror::Object*>(thread_id, &error);
2393 CHECK(peer != nullptr) << error;
jeffhaoa77f0f62012-12-05 17:19:31 -08002394 Thread* thread;
2395 {
2396 MutexLock mu(soa.Self(), *Locks::thread_list_lock_);
2397 thread = Thread::FromManagedThread(soa, peer);
2398 }
Ian Rogersc0542af2014-09-03 16:16:56 -07002399 if (thread == nullptr) {
Elliott Hughes4e235312011-12-02 11:34:15 -08002400 LOG(WARNING) << "No such thread for resume: " << peer;
2401 return;
2402 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002403 bool needs_resume;
2404 {
Ian Rogers50b35e22012-10-04 10:09:15 -07002405 MutexLock mu2(soa.Self(), *Locks::thread_suspend_count_lock_);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002406 needs_resume = thread->GetSuspendCount() > 0;
2407 }
2408 if (needs_resume) {
Elliott Hughes546b9862012-06-20 16:06:13 -07002409 Runtime::Current()->GetThreadList()->Resume(thread, true);
2410 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002411}
2412
2413void Dbg::SuspendSelf() {
Elliott Hughes475fc232011-10-25 15:00:35 -07002414 Runtime::Current()->GetThreadList()->SuspendSelfForDebugger();
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002415}
2416
Ian Rogers0399dde2012-06-06 17:09:28 -07002417struct GetThisVisitor : public StackVisitor {
Andreas Gampe277ccbd2014-11-03 21:36:10 -08002418 GetThisVisitor(Thread* thread, Context* context, JDWP::FrameId frame_id_in)
Ian Rogersb726dcb2012-09-05 08:57:23 -07002419 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_)
Nicolas Geoffray8e5bd182015-05-06 11:34:34 +01002420 : StackVisitor(thread, context, StackVisitor::StackWalkKind::kIncludeInlinedFrames),
2421 this_object(nullptr),
2422 frame_id(frame_id_in) {}
Ian Rogers0399dde2012-06-06 17:09:28 -07002423
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002424 // TODO: Enable annotalysis. We know lock is held in constructor, but abstraction confuses
2425 // annotalysis.
2426 virtual bool VisitFrame() NO_THREAD_SAFETY_ANALYSIS {
Elliott Hughes6e9d22c2012-06-22 15:02:37 -07002427 if (frame_id != GetFrameId()) {
Ian Rogers0399dde2012-06-06 17:09:28 -07002428 return true; // continue
Ian Rogers0399dde2012-06-06 17:09:28 -07002429 } else {
Ian Rogers62d6c772013-02-27 08:32:07 -08002430 this_object = GetThisObject();
2431 return false;
Ian Rogers0399dde2012-06-06 17:09:28 -07002432 }
Elliott Hughes86b00102011-12-05 17:54:26 -08002433 }
Ian Rogers0399dde2012-06-06 17:09:28 -07002434
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002435 mirror::Object* this_object;
Elliott Hughes6e9d22c2012-06-22 15:02:37 -07002436 JDWP::FrameId frame_id;
Ian Rogers0399dde2012-06-06 17:09:28 -07002437};
2438
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002439JDWP::JdwpError Dbg::GetThisObject(JDWP::ObjectId thread_id, JDWP::FrameId frame_id,
2440 JDWP::ObjectId* result) {
2441 ScopedObjectAccessUnchecked soa(Thread::Current());
Sebastien Hertz69206392015-04-07 15:54:25 +02002442 JDWP::JdwpError error;
2443 Thread* thread = DecodeThread(soa, thread_id, &error);
2444 if (error != JDWP::ERR_NONE) {
2445 return error;
2446 }
2447 if (!IsSuspendedForDebugger(soa, thread)) {
2448 return JDWP::ERR_THREAD_NOT_SUSPENDED;
Elliott Hughes6e9d22c2012-06-22 15:02:37 -07002449 }
Ian Rogers700a4022014-05-19 16:49:03 -07002450 std::unique_ptr<Context> context(Context::Create());
Ian Rogers7a22fa62013-01-23 12:16:16 -08002451 GetThisVisitor visitor(thread, context.get(), frame_id);
Ian Rogers0399dde2012-06-06 17:09:28 -07002452 visitor.WalkStack();
Elliott Hughes6e9d22c2012-06-22 15:02:37 -07002453 *result = gRegistry->Add(visitor.this_object);
2454 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002455}
2456
Sebastien Hertz8009f392014-09-01 17:07:11 +02002457// Walks the stack until we find the frame with the given FrameId.
2458class FindFrameVisitor FINAL : public StackVisitor {
2459 public:
2460 FindFrameVisitor(Thread* thread, Context* context, JDWP::FrameId frame_id)
2461 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_)
Nicolas Geoffray8e5bd182015-05-06 11:34:34 +01002462 : StackVisitor(thread, context, StackVisitor::StackWalkKind::kIncludeInlinedFrames),
2463 frame_id_(frame_id),
2464 error_(JDWP::ERR_INVALID_FRAMEID) {}
Ian Rogersca190662012-06-26 15:45:57 -07002465
Sebastien Hertz8009f392014-09-01 17:07:11 +02002466 // TODO: Enable annotalysis. We know lock is held in constructor, but abstraction confuses
2467 // annotalysis.
2468 bool VisitFrame() NO_THREAD_SAFETY_ANALYSIS {
2469 if (GetFrameId() != frame_id_) {
2470 return true; // Not our frame, carry on.
Ian Rogers0399dde2012-06-06 17:09:28 -07002471 }
Sebastien Hertz8009f392014-09-01 17:07:11 +02002472 mirror::ArtMethod* m = GetMethod();
2473 if (m->IsNative()) {
2474 // We can't read/write local value from/into native method.
2475 error_ = JDWP::ERR_OPAQUE_FRAME;
2476 } else {
2477 // We found our frame.
2478 error_ = JDWP::ERR_NONE;
2479 }
2480 return false;
2481 }
2482
2483 JDWP::JdwpError GetError() const {
2484 return error_;
2485 }
2486
2487 private:
2488 const JDWP::FrameId frame_id_;
2489 JDWP::JdwpError error_;
2490};
2491
2492JDWP::JdwpError Dbg::GetLocalValues(JDWP::Request* request, JDWP::ExpandBuf* pReply) {
2493 JDWP::ObjectId thread_id = request->ReadThreadId();
2494 JDWP::FrameId frame_id = request->ReadFrameId();
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002495
2496 ScopedObjectAccessUnchecked soa(Thread::Current());
Sebastien Hertz69206392015-04-07 15:54:25 +02002497 JDWP::JdwpError error;
2498 Thread* thread = DecodeThread(soa, thread_id, &error);
2499 if (error != JDWP::ERR_NONE) {
2500 return error;
2501 }
2502 if (!IsSuspendedForDebugger(soa, thread)) {
2503 return JDWP::ERR_THREAD_NOT_SUSPENDED;
Elliott Hughes221229c2013-01-08 18:17:50 -08002504 }
Sebastien Hertz8009f392014-09-01 17:07:11 +02002505 // Find the frame with the given frame_id.
Ian Rogers700a4022014-05-19 16:49:03 -07002506 std::unique_ptr<Context> context(Context::Create());
Sebastien Hertz8009f392014-09-01 17:07:11 +02002507 FindFrameVisitor visitor(thread, context.get(), frame_id);
Ian Rogers0399dde2012-06-06 17:09:28 -07002508 visitor.WalkStack();
Sebastien Hertz8009f392014-09-01 17:07:11 +02002509 if (visitor.GetError() != JDWP::ERR_NONE) {
2510 return visitor.GetError();
2511 }
2512
2513 // Read the values from visitor's context.
2514 int32_t slot_count = request->ReadSigned32("slot count");
2515 expandBufAdd4BE(pReply, slot_count); /* "int values" */
2516 for (int32_t i = 0; i < slot_count; ++i) {
2517 uint32_t slot = request->ReadUnsigned32("slot");
2518 JDWP::JdwpTag reqSigByte = request->ReadTag();
2519
2520 VLOG(jdwp) << " --> slot " << slot << " " << reqSigByte;
2521
2522 size_t width = Dbg::GetTagWidth(reqSigByte);
Sebastien Hertz7d955652014-10-22 10:57:10 +02002523 uint8_t* ptr = expandBufAddSpace(pReply, width + 1);
Sebastien Hertz69206392015-04-07 15:54:25 +02002524 error = Dbg::GetLocalValue(visitor, soa, slot, reqSigByte, ptr, width);
Sebastien Hertz8009f392014-09-01 17:07:11 +02002525 if (error != JDWP::ERR_NONE) {
2526 return error;
2527 }
2528 }
2529 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002530}
2531
Sebastien Hertzabbabc82015-03-26 08:47:47 +01002532constexpr JDWP::JdwpError kStackFrameLocalAccessError = JDWP::ERR_ABSENT_INFORMATION;
2533
2534static std::string GetStackContextAsString(const StackVisitor& visitor)
2535 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
2536 return StringPrintf(" at DEX pc 0x%08x in method %s", visitor.GetDexPc(false),
2537 PrettyMethod(visitor.GetMethod()).c_str());
2538}
2539
2540static JDWP::JdwpError FailGetLocalValue(const StackVisitor& visitor, uint16_t vreg,
2541 JDWP::JdwpTag tag)
2542 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
2543 LOG(ERROR) << "Failed to read " << tag << " local from register v" << vreg
2544 << GetStackContextAsString(visitor);
2545 return kStackFrameLocalAccessError;
2546}
2547
Sebastien Hertz8009f392014-09-01 17:07:11 +02002548JDWP::JdwpError Dbg::GetLocalValue(const StackVisitor& visitor, ScopedObjectAccessUnchecked& soa,
2549 int slot, JDWP::JdwpTag tag, uint8_t* buf, size_t width) {
2550 mirror::ArtMethod* m = visitor.GetMethod();
Sebastien Hertzabbabc82015-03-26 08:47:47 +01002551 JDWP::JdwpError error = JDWP::ERR_NONE;
2552 uint16_t vreg = DemangleSlot(slot, m, &error);
2553 if (error != JDWP::ERR_NONE) {
2554 return error;
2555 }
Sebastien Hertz8009f392014-09-01 17:07:11 +02002556 // TODO: check that the tag is compatible with the actual type of the slot!
Sebastien Hertz8009f392014-09-01 17:07:11 +02002557 switch (tag) {
2558 case JDWP::JT_BOOLEAN: {
2559 CHECK_EQ(width, 1U);
2560 uint32_t intVal;
Sebastien Hertzabbabc82015-03-26 08:47:47 +01002561 if (!visitor.GetVReg(m, vreg, kIntVReg, &intVal)) {
2562 return FailGetLocalValue(visitor, vreg, tag);
Ian Rogers0399dde2012-06-06 17:09:28 -07002563 }
Sebastien Hertzabbabc82015-03-26 08:47:47 +01002564 VLOG(jdwp) << "get boolean local " << vreg << " = " << intVal;
2565 JDWP::Set1(buf + 1, intVal != 0);
Sebastien Hertz8009f392014-09-01 17:07:11 +02002566 break;
Ian Rogers0399dde2012-06-06 17:09:28 -07002567 }
Sebastien Hertz8009f392014-09-01 17:07:11 +02002568 case JDWP::JT_BYTE: {
2569 CHECK_EQ(width, 1U);
2570 uint32_t intVal;
Sebastien Hertzabbabc82015-03-26 08:47:47 +01002571 if (!visitor.GetVReg(m, vreg, kIntVReg, &intVal)) {
2572 return FailGetLocalValue(visitor, vreg, tag);
Sebastien Hertz8009f392014-09-01 17:07:11 +02002573 }
Sebastien Hertzabbabc82015-03-26 08:47:47 +01002574 VLOG(jdwp) << "get byte local " << vreg << " = " << intVal;
2575 JDWP::Set1(buf + 1, intVal);
Sebastien Hertz8009f392014-09-01 17:07:11 +02002576 break;
2577 }
2578 case JDWP::JT_SHORT:
2579 case JDWP::JT_CHAR: {
2580 CHECK_EQ(width, 2U);
2581 uint32_t intVal;
Sebastien Hertzabbabc82015-03-26 08:47:47 +01002582 if (!visitor.GetVReg(m, vreg, kIntVReg, &intVal)) {
2583 return FailGetLocalValue(visitor, vreg, tag);
Sebastien Hertz8009f392014-09-01 17:07:11 +02002584 }
Sebastien Hertzabbabc82015-03-26 08:47:47 +01002585 VLOG(jdwp) << "get short/char local " << vreg << " = " << intVal;
2586 JDWP::Set2BE(buf + 1, intVal);
Sebastien Hertz8009f392014-09-01 17:07:11 +02002587 break;
2588 }
2589 case JDWP::JT_INT: {
2590 CHECK_EQ(width, 4U);
2591 uint32_t intVal;
Sebastien Hertzabbabc82015-03-26 08:47:47 +01002592 if (!visitor.GetVReg(m, vreg, kIntVReg, &intVal)) {
2593 return FailGetLocalValue(visitor, vreg, tag);
Sebastien Hertz8009f392014-09-01 17:07:11 +02002594 }
Sebastien Hertzabbabc82015-03-26 08:47:47 +01002595 VLOG(jdwp) << "get int local " << vreg << " = " << intVal;
2596 JDWP::Set4BE(buf + 1, intVal);
Sebastien Hertz8009f392014-09-01 17:07:11 +02002597 break;
2598 }
2599 case JDWP::JT_FLOAT: {
2600 CHECK_EQ(width, 4U);
2601 uint32_t intVal;
Sebastien Hertzabbabc82015-03-26 08:47:47 +01002602 if (!visitor.GetVReg(m, vreg, kFloatVReg, &intVal)) {
2603 return FailGetLocalValue(visitor, vreg, tag);
Sebastien Hertz8009f392014-09-01 17:07:11 +02002604 }
Sebastien Hertzabbabc82015-03-26 08:47:47 +01002605 VLOG(jdwp) << "get float local " << vreg << " = " << intVal;
2606 JDWP::Set4BE(buf + 1, intVal);
Sebastien Hertz8009f392014-09-01 17:07:11 +02002607 break;
2608 }
2609 case JDWP::JT_ARRAY:
2610 case JDWP::JT_CLASS_LOADER:
2611 case JDWP::JT_CLASS_OBJECT:
2612 case JDWP::JT_OBJECT:
2613 case JDWP::JT_STRING:
2614 case JDWP::JT_THREAD:
2615 case JDWP::JT_THREAD_GROUP: {
2616 CHECK_EQ(width, sizeof(JDWP::ObjectId));
2617 uint32_t intVal;
Sebastien Hertzabbabc82015-03-26 08:47:47 +01002618 if (!visitor.GetVReg(m, vreg, kReferenceVReg, &intVal)) {
2619 return FailGetLocalValue(visitor, vreg, tag);
Sebastien Hertz8009f392014-09-01 17:07:11 +02002620 }
Sebastien Hertzabbabc82015-03-26 08:47:47 +01002621 mirror::Object* o = reinterpret_cast<mirror::Object*>(intVal);
2622 VLOG(jdwp) << "get " << tag << " object local " << vreg << " = " << o;
2623 if (!Runtime::Current()->GetHeap()->IsValidObjectAddress(o)) {
2624 LOG(FATAL) << StringPrintf("Found invalid object %#" PRIxPTR " in register v%u",
2625 reinterpret_cast<uintptr_t>(o), vreg)
2626 << GetStackContextAsString(visitor);
2627 UNREACHABLE();
2628 }
2629 tag = TagFromObject(soa, o);
2630 JDWP::SetObjectId(buf + 1, gRegistry->Add(o));
Sebastien Hertz8009f392014-09-01 17:07:11 +02002631 break;
2632 }
2633 case JDWP::JT_DOUBLE: {
2634 CHECK_EQ(width, 8U);
2635 uint64_t longVal;
Sebastien Hertzabbabc82015-03-26 08:47:47 +01002636 if (!visitor.GetVRegPair(m, vreg, kDoubleLoVReg, kDoubleHiVReg, &longVal)) {
2637 return FailGetLocalValue(visitor, vreg, tag);
Sebastien Hertz8009f392014-09-01 17:07:11 +02002638 }
Sebastien Hertzabbabc82015-03-26 08:47:47 +01002639 VLOG(jdwp) << "get double local " << vreg << " = " << longVal;
2640 JDWP::Set8BE(buf + 1, longVal);
Sebastien Hertz8009f392014-09-01 17:07:11 +02002641 break;
2642 }
2643 case JDWP::JT_LONG: {
2644 CHECK_EQ(width, 8U);
2645 uint64_t longVal;
Sebastien Hertzabbabc82015-03-26 08:47:47 +01002646 if (!visitor.GetVRegPair(m, vreg, kLongLoVReg, kLongHiVReg, &longVal)) {
2647 return FailGetLocalValue(visitor, vreg, tag);
Sebastien Hertz8009f392014-09-01 17:07:11 +02002648 }
Sebastien Hertzabbabc82015-03-26 08:47:47 +01002649 VLOG(jdwp) << "get long local " << vreg << " = " << longVal;
2650 JDWP::Set8BE(buf + 1, longVal);
Sebastien Hertz8009f392014-09-01 17:07:11 +02002651 break;
2652 }
2653 default:
2654 LOG(FATAL) << "Unknown tag " << tag;
Sebastien Hertzabbabc82015-03-26 08:47:47 +01002655 UNREACHABLE();
Sebastien Hertz8009f392014-09-01 17:07:11 +02002656 }
Ian Rogers0399dde2012-06-06 17:09:28 -07002657
Sebastien Hertz8009f392014-09-01 17:07:11 +02002658 // Prepend tag, which may have been updated.
2659 JDWP::Set1(buf, tag);
2660 return JDWP::ERR_NONE;
2661}
2662
2663JDWP::JdwpError Dbg::SetLocalValues(JDWP::Request* request) {
2664 JDWP::ObjectId thread_id = request->ReadThreadId();
2665 JDWP::FrameId frame_id = request->ReadFrameId();
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002666
2667 ScopedObjectAccessUnchecked soa(Thread::Current());
Sebastien Hertz69206392015-04-07 15:54:25 +02002668 JDWP::JdwpError error;
2669 Thread* thread = DecodeThread(soa, thread_id, &error);
2670 if (error != JDWP::ERR_NONE) {
2671 return error;
2672 }
2673 if (!IsSuspendedForDebugger(soa, thread)) {
2674 return JDWP::ERR_THREAD_NOT_SUSPENDED;
Elliott Hughes221229c2013-01-08 18:17:50 -08002675 }
Sebastien Hertz8009f392014-09-01 17:07:11 +02002676 // Find the frame with the given frame_id.
Ian Rogers700a4022014-05-19 16:49:03 -07002677 std::unique_ptr<Context> context(Context::Create());
Sebastien Hertz8009f392014-09-01 17:07:11 +02002678 FindFrameVisitor visitor(thread, context.get(), frame_id);
Ian Rogers0399dde2012-06-06 17:09:28 -07002679 visitor.WalkStack();
Sebastien Hertz8009f392014-09-01 17:07:11 +02002680 if (visitor.GetError() != JDWP::ERR_NONE) {
2681 return visitor.GetError();
2682 }
2683
2684 // Writes the values into visitor's context.
2685 int32_t slot_count = request->ReadSigned32("slot count");
2686 for (int32_t i = 0; i < slot_count; ++i) {
2687 uint32_t slot = request->ReadUnsigned32("slot");
2688 JDWP::JdwpTag sigByte = request->ReadTag();
2689 size_t width = Dbg::GetTagWidth(sigByte);
2690 uint64_t value = request->ReadValue(width);
2691
2692 VLOG(jdwp) << " --> slot " << slot << " " << sigByte << " " << value;
Sebastien Hertz69206392015-04-07 15:54:25 +02002693 error = Dbg::SetLocalValue(visitor, slot, sigByte, value, width);
Sebastien Hertz8009f392014-09-01 17:07:11 +02002694 if (error != JDWP::ERR_NONE) {
2695 return error;
2696 }
2697 }
2698 return JDWP::ERR_NONE;
2699}
2700
Sebastien Hertzabbabc82015-03-26 08:47:47 +01002701template<typename T>
2702static JDWP::JdwpError FailSetLocalValue(const StackVisitor& visitor, uint16_t vreg,
2703 JDWP::JdwpTag tag, T value)
2704 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
2705 LOG(ERROR) << "Failed to write " << tag << " local " << value
2706 << " (0x" << std::hex << value << ") into register v" << vreg
2707 << GetStackContextAsString(visitor);
2708 return kStackFrameLocalAccessError;
2709}
2710
Sebastien Hertz8009f392014-09-01 17:07:11 +02002711JDWP::JdwpError Dbg::SetLocalValue(StackVisitor& visitor, int slot, JDWP::JdwpTag tag,
2712 uint64_t value, size_t width) {
2713 mirror::ArtMethod* m = visitor.GetMethod();
Sebastien Hertzabbabc82015-03-26 08:47:47 +01002714 JDWP::JdwpError error = JDWP::ERR_NONE;
2715 uint16_t vreg = DemangleSlot(slot, m, &error);
2716 if (error != JDWP::ERR_NONE) {
2717 return error;
2718 }
Sebastien Hertz8009f392014-09-01 17:07:11 +02002719 // TODO: check that the tag is compatible with the actual type of the slot!
Sebastien Hertz8009f392014-09-01 17:07:11 +02002720 switch (tag) {
2721 case JDWP::JT_BOOLEAN:
2722 case JDWP::JT_BYTE:
2723 CHECK_EQ(width, 1U);
Sebastien Hertzabbabc82015-03-26 08:47:47 +01002724 if (!visitor.SetVReg(m, vreg, static_cast<uint32_t>(value), kIntVReg)) {
2725 return FailSetLocalValue(visitor, vreg, tag, static_cast<uint32_t>(value));
Sebastien Hertz8009f392014-09-01 17:07:11 +02002726 }
2727 break;
2728 case JDWP::JT_SHORT:
2729 case JDWP::JT_CHAR:
2730 CHECK_EQ(width, 2U);
Sebastien Hertzabbabc82015-03-26 08:47:47 +01002731 if (!visitor.SetVReg(m, vreg, static_cast<uint32_t>(value), kIntVReg)) {
2732 return FailSetLocalValue(visitor, vreg, tag, static_cast<uint32_t>(value));
Sebastien Hertz8009f392014-09-01 17:07:11 +02002733 }
2734 break;
2735 case JDWP::JT_INT:
2736 CHECK_EQ(width, 4U);
Sebastien Hertzabbabc82015-03-26 08:47:47 +01002737 if (!visitor.SetVReg(m, vreg, static_cast<uint32_t>(value), kIntVReg)) {
2738 return FailSetLocalValue(visitor, vreg, tag, static_cast<uint32_t>(value));
Sebastien Hertz8009f392014-09-01 17:07:11 +02002739 }
2740 break;
2741 case JDWP::JT_FLOAT:
2742 CHECK_EQ(width, 4U);
Sebastien Hertzabbabc82015-03-26 08:47:47 +01002743 if (!visitor.SetVReg(m, vreg, static_cast<uint32_t>(value), kFloatVReg)) {
2744 return FailSetLocalValue(visitor, vreg, tag, static_cast<uint32_t>(value));
Sebastien Hertz8009f392014-09-01 17:07:11 +02002745 }
2746 break;
2747 case JDWP::JT_ARRAY:
2748 case JDWP::JT_CLASS_LOADER:
2749 case JDWP::JT_CLASS_OBJECT:
2750 case JDWP::JT_OBJECT:
2751 case JDWP::JT_STRING:
2752 case JDWP::JT_THREAD:
2753 case JDWP::JT_THREAD_GROUP: {
2754 CHECK_EQ(width, sizeof(JDWP::ObjectId));
Sebastien Hertz8009f392014-09-01 17:07:11 +02002755 mirror::Object* o = gRegistry->Get<mirror::Object*>(static_cast<JDWP::ObjectId>(value),
2756 &error);
2757 if (error != JDWP::ERR_NONE) {
2758 VLOG(jdwp) << tag << " object " << o << " is an invalid object";
2759 return JDWP::ERR_INVALID_OBJECT;
Sebastien Hertzabbabc82015-03-26 08:47:47 +01002760 }
2761 if (!visitor.SetVReg(m, vreg, static_cast<uint32_t>(reinterpret_cast<uintptr_t>(o)),
2762 kReferenceVReg)) {
2763 return FailSetLocalValue(visitor, vreg, tag, reinterpret_cast<uintptr_t>(o));
Sebastien Hertz8009f392014-09-01 17:07:11 +02002764 }
2765 break;
2766 }
2767 case JDWP::JT_DOUBLE: {
2768 CHECK_EQ(width, 8U);
Sebastien Hertzabbabc82015-03-26 08:47:47 +01002769 if (!visitor.SetVRegPair(m, vreg, value, kDoubleLoVReg, kDoubleHiVReg)) {
2770 return FailSetLocalValue(visitor, vreg, tag, value);
Sebastien Hertz8009f392014-09-01 17:07:11 +02002771 }
2772 break;
2773 }
2774 case JDWP::JT_LONG: {
2775 CHECK_EQ(width, 8U);
Sebastien Hertzabbabc82015-03-26 08:47:47 +01002776 if (!visitor.SetVRegPair(m, vreg, value, kLongLoVReg, kLongHiVReg)) {
2777 return FailSetLocalValue(visitor, vreg, tag, value);
Sebastien Hertz8009f392014-09-01 17:07:11 +02002778 }
2779 break;
2780 }
2781 default:
2782 LOG(FATAL) << "Unknown tag " << tag;
Sebastien Hertzabbabc82015-03-26 08:47:47 +01002783 UNREACHABLE();
Sebastien Hertz8009f392014-09-01 17:07:11 +02002784 }
2785 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002786}
2787
Sebastien Hertz6995c602014-09-09 12:10:13 +02002788static void SetEventLocation(JDWP::EventLocation* location, mirror::ArtMethod* m, uint32_t dex_pc)
2789 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
2790 DCHECK(location != nullptr);
2791 if (m == nullptr) {
2792 memset(location, 0, sizeof(*location));
2793 } else {
2794 location->method = m;
2795 location->dex_pc = (m->IsNative() || m->IsProxyMethod()) ? static_cast<uint32_t>(-1) : dex_pc;
Sebastien Hertz3f52eaf2014-04-04 17:50:18 +02002796 }
Sebastien Hertz3f52eaf2014-04-04 17:50:18 +02002797}
2798
Ian Rogersef7d42f2014-01-06 12:55:46 -08002799void Dbg::PostLocationEvent(mirror::ArtMethod* m, int dex_pc, mirror::Object* this_object,
Jeff Hao579b0242013-11-18 13:16:49 -08002800 int event_flags, const JValue* return_value) {
Sebastien Hertz3f52eaf2014-04-04 17:50:18 +02002801 if (!IsDebuggerActive()) {
2802 return;
2803 }
2804 DCHECK(m != nullptr);
2805 DCHECK_EQ(m->IsStatic(), this_object == nullptr);
Sebastien Hertz6995c602014-09-09 12:10:13 +02002806 JDWP::EventLocation location;
2807 SetEventLocation(&location, m, dex_pc);
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08002808
Sebastien Hertzde48aa62015-05-26 11:53:39 +02002809 // We need to be sure no exception is pending when calling JdwpState::PostLocationEvent.
2810 // This is required to be able to call JNI functions to create JDWP ids. To achieve this,
2811 // we temporarily clear the current thread's exception (if any) and will restore it after
2812 // the call.
2813 // Note: the only way to get a pending exception here is to suspend on a move-exception
2814 // instruction.
2815 Thread* const self = Thread::Current();
2816 StackHandleScope<1> hs(self);
2817 Handle<mirror::Throwable> pending_exception(hs.NewHandle(self->GetException()));
2818 self->ClearException();
2819 if (kIsDebugBuild && pending_exception.Get() != nullptr) {
2820 const DexFile::CodeItem* code_item = location.method->GetCodeItem();
2821 const Instruction* instr = Instruction::At(&code_item->insns_[location.dex_pc]);
2822 CHECK_EQ(Instruction::MOVE_EXCEPTION, instr->Opcode());
2823 }
2824
Sebastien Hertz6995c602014-09-09 12:10:13 +02002825 gJdwpState->PostLocationEvent(&location, this_object, event_flags, return_value);
Sebastien Hertzde48aa62015-05-26 11:53:39 +02002826
2827 if (pending_exception.Get() != nullptr) {
2828 self->SetException(pending_exception.Get());
2829 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002830}
2831
Sebastien Hertz3f52eaf2014-04-04 17:50:18 +02002832void Dbg::PostFieldAccessEvent(mirror::ArtMethod* m, int dex_pc,
Mathieu Chartierc7853442015-03-27 14:35:38 -07002833 mirror::Object* this_object, ArtField* f) {
Sebastien Hertz3f52eaf2014-04-04 17:50:18 +02002834 if (!IsDebuggerActive()) {
2835 return;
2836 }
2837 DCHECK(m != nullptr);
2838 DCHECK(f != nullptr);
Sebastien Hertz6995c602014-09-09 12:10:13 +02002839 JDWP::EventLocation location;
2840 SetEventLocation(&location, m, dex_pc);
Sebastien Hertz3f52eaf2014-04-04 17:50:18 +02002841
Sebastien Hertz6995c602014-09-09 12:10:13 +02002842 gJdwpState->PostFieldEvent(&location, f, this_object, nullptr, false);
Sebastien Hertz3f52eaf2014-04-04 17:50:18 +02002843}
2844
2845void Dbg::PostFieldModificationEvent(mirror::ArtMethod* m, int dex_pc,
Mathieu Chartierc7853442015-03-27 14:35:38 -07002846 mirror::Object* this_object, ArtField* f,
Sebastien Hertz3f52eaf2014-04-04 17:50:18 +02002847 const JValue* field_value) {
2848 if (!IsDebuggerActive()) {
2849 return;
2850 }
2851 DCHECK(m != nullptr);
2852 DCHECK(f != nullptr);
2853 DCHECK(field_value != nullptr);
Sebastien Hertz6995c602014-09-09 12:10:13 +02002854 JDWP::EventLocation location;
2855 SetEventLocation(&location, m, dex_pc);
Sebastien Hertz3f52eaf2014-04-04 17:50:18 +02002856
Sebastien Hertz6995c602014-09-09 12:10:13 +02002857 gJdwpState->PostFieldEvent(&location, f, this_object, field_value, true);
Sebastien Hertz3f52eaf2014-04-04 17:50:18 +02002858}
2859
Nicolas Geoffray14691c52015-03-05 10:40:17 +00002860/**
2861 * Finds the location where this exception will be caught. We search until we reach the top
2862 * frame, in which case this exception is considered uncaught.
2863 */
2864class CatchLocationFinder : public StackVisitor {
2865 public:
2866 CatchLocationFinder(Thread* self, const Handle<mirror::Throwable>& exception, Context* context)
2867 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_)
Nicolas Geoffray8e5bd182015-05-06 11:34:34 +01002868 : StackVisitor(self, context, StackVisitor::StackWalkKind::kIncludeInlinedFrames),
Nicolas Geoffray14691c52015-03-05 10:40:17 +00002869 self_(self),
2870 exception_(exception),
2871 handle_scope_(self),
2872 this_at_throw_(handle_scope_.NewHandle<mirror::Object>(nullptr)),
2873 catch_method_(handle_scope_.NewHandle<mirror::ArtMethod>(nullptr)),
2874 throw_method_(handle_scope_.NewHandle<mirror::ArtMethod>(nullptr)),
2875 catch_dex_pc_(DexFile::kDexNoIndex),
2876 throw_dex_pc_(DexFile::kDexNoIndex) {
2877 }
2878
2879 bool VisitFrame() OVERRIDE SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
2880 mirror::ArtMethod* method = GetMethod();
2881 DCHECK(method != nullptr);
2882 if (method->IsRuntimeMethod()) {
2883 // Ignore callee save method.
2884 DCHECK(method->IsCalleeSaveMethod());
2885 return true;
2886 }
2887
2888 uint32_t dex_pc = GetDexPc();
2889 if (throw_method_.Get() == nullptr) {
2890 // First Java method found. It is either the method that threw the exception,
2891 // or the Java native method that is reporting an exception thrown by
2892 // native code.
2893 this_at_throw_.Assign(GetThisObject());
2894 throw_method_.Assign(method);
2895 throw_dex_pc_ = dex_pc;
2896 }
2897
2898 if (dex_pc != DexFile::kDexNoIndex) {
2899 StackHandleScope<2> hs(self_);
2900 uint32_t found_dex_pc;
2901 Handle<mirror::Class> exception_class(hs.NewHandle(exception_->GetClass()));
2902 Handle<mirror::ArtMethod> h_method(hs.NewHandle(method));
2903 bool unused_clear_exception;
2904 found_dex_pc = mirror::ArtMethod::FindCatchBlock(
2905 h_method, exception_class, dex_pc, &unused_clear_exception);
2906 if (found_dex_pc != DexFile::kDexNoIndex) {
2907 catch_method_.Assign(method);
2908 catch_dex_pc_ = found_dex_pc;
2909 return false; // End stack walk.
2910 }
2911 }
2912 return true; // Continue stack walk.
2913 }
2914
2915 mirror::ArtMethod* GetCatchMethod() SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
2916 return catch_method_.Get();
2917 }
2918
2919 mirror::ArtMethod* GetThrowMethod() SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
2920 return throw_method_.Get();
2921 }
2922
2923 mirror::Object* GetThisAtThrow() SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
2924 return this_at_throw_.Get();
2925 }
2926
2927 uint32_t GetCatchDexPc() const {
2928 return catch_dex_pc_;
2929 }
2930
2931 uint32_t GetThrowDexPc() const {
2932 return throw_dex_pc_;
2933 }
2934
2935 private:
2936 Thread* const self_;
2937 const Handle<mirror::Throwable>& exception_;
2938 StackHandleScope<3> handle_scope_;
2939 MutableHandle<mirror::Object> this_at_throw_;
2940 MutableHandle<mirror::ArtMethod> catch_method_;
2941 MutableHandle<mirror::ArtMethod> throw_method_;
2942 uint32_t catch_dex_pc_;
2943 uint32_t throw_dex_pc_;
2944
2945 DISALLOW_COPY_AND_ASSIGN(CatchLocationFinder);
2946};
2947
2948void Dbg::PostException(mirror::Throwable* exception_object) {
Elliott Hughesc0f09332012-03-26 13:27:06 -07002949 if (!IsDebuggerActive()) {
Ian Rogers0ad5bb82011-12-07 10:16:32 -08002950 return;
2951 }
Sebastien Hertz261bc042015-04-08 09:36:07 +02002952 Thread* const self = Thread::Current();
2953 StackHandleScope<1> handle_scope(self);
Nicolas Geoffray14691c52015-03-05 10:40:17 +00002954 Handle<mirror::Throwable> h_exception(handle_scope.NewHandle(exception_object));
2955 std::unique_ptr<Context> context(Context::Create());
Sebastien Hertz261bc042015-04-08 09:36:07 +02002956 CatchLocationFinder clf(self, h_exception, context.get());
Nicolas Geoffray14691c52015-03-05 10:40:17 +00002957 clf.WalkStack(/* include_transitions */ false);
Sebastien Hertz6995c602014-09-09 12:10:13 +02002958 JDWP::EventLocation exception_throw_location;
Nicolas Geoffray14691c52015-03-05 10:40:17 +00002959 SetEventLocation(&exception_throw_location, clf.GetThrowMethod(), clf.GetThrowDexPc());
Sebastien Hertz6995c602014-09-09 12:10:13 +02002960 JDWP::EventLocation exception_catch_location;
Nicolas Geoffray14691c52015-03-05 10:40:17 +00002961 SetEventLocation(&exception_catch_location, clf.GetCatchMethod(), clf.GetCatchDexPc());
Elliott Hughes4740cdf2011-12-07 14:07:12 -08002962
Nicolas Geoffray14691c52015-03-05 10:40:17 +00002963 gJdwpState->PostException(&exception_throw_location, h_exception.Get(), &exception_catch_location,
2964 clf.GetThisAtThrow());
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002965}
2966
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002967void Dbg::PostClassPrepare(mirror::Class* c) {
Elliott Hughesc0f09332012-03-26 13:27:06 -07002968 if (!IsDebuggerActive()) {
Elliott Hughes4740cdf2011-12-07 14:07:12 -08002969 return;
2970 }
Sebastien Hertz6995c602014-09-09 12:10:13 +02002971 gJdwpState->PostClassPrepare(c);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002972}
2973
Ian Rogers62d6c772013-02-27 08:32:07 -08002974void Dbg::UpdateDebugger(Thread* thread, mirror::Object* this_object,
Sebastien Hertz8379b222014-02-24 17:38:15 +01002975 mirror::ArtMethod* m, uint32_t dex_pc,
2976 int event_flags, const JValue* return_value) {
Ian Rogers62d6c772013-02-27 08:32:07 -08002977 if (!IsDebuggerActive() || dex_pc == static_cast<uint32_t>(-2) /* fake method exit */) {
Elliott Hughes2aa2e392012-02-17 17:15:43 -08002978 return;
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08002979 }
2980
Elliott Hughes86964332012-02-15 19:37:42 -08002981 if (IsBreakpoint(m, dex_pc)) {
2982 event_flags |= kBreakpoint;
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08002983 }
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08002984
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01002985 // If the debugger is single-stepping one of our threads, check to
2986 // see if we're that thread and we've reached a step point.
2987 const SingleStepControl* single_step_control = thread->GetSingleStepControl();
Sebastien Hertz597c4f02015-01-26 17:37:14 +01002988 if (single_step_control != nullptr) {
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01002989 CHECK(!m->IsNative());
Sebastien Hertz597c4f02015-01-26 17:37:14 +01002990 if (single_step_control->GetStepDepth() == JDWP::SD_INTO) {
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01002991 // Step into method calls. We break when the line number
2992 // or method pointer changes. If we're in SS_MIN mode, we
2993 // always stop.
Sebastien Hertz597c4f02015-01-26 17:37:14 +01002994 if (single_step_control->GetMethod() != m) {
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01002995 event_flags |= kSingleStep;
2996 VLOG(jdwp) << "SS new method";
Sebastien Hertz597c4f02015-01-26 17:37:14 +01002997 } else if (single_step_control->GetStepSize() == JDWP::SS_MIN) {
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01002998 event_flags |= kSingleStep;
2999 VLOG(jdwp) << "SS new instruction";
Sebastien Hertzbb43b432014-04-14 11:59:08 +02003000 } else if (single_step_control->ContainsDexPc(dex_pc)) {
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01003001 event_flags |= kSingleStep;
3002 VLOG(jdwp) << "SS new line";
3003 }
Sebastien Hertz597c4f02015-01-26 17:37:14 +01003004 } else if (single_step_control->GetStepDepth() == JDWP::SD_OVER) {
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01003005 // Step over method calls. We break when the line number is
3006 // different and the frame depth is <= the original frame
3007 // depth. (We can't just compare on the method, because we
3008 // might get unrolled past it by an exception, and it's tricky
3009 // to identify recursion.)
3010
3011 int stack_depth = GetStackDepth(thread);
3012
Sebastien Hertz597c4f02015-01-26 17:37:14 +01003013 if (stack_depth < single_step_control->GetStackDepth()) {
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01003014 // Popped up one or more frames, always trigger.
3015 event_flags |= kSingleStep;
3016 VLOG(jdwp) << "SS method pop";
Sebastien Hertz597c4f02015-01-26 17:37:14 +01003017 } else if (stack_depth == single_step_control->GetStackDepth()) {
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01003018 // Same depth, see if we moved.
Sebastien Hertz597c4f02015-01-26 17:37:14 +01003019 if (single_step_control->GetStepSize() == JDWP::SS_MIN) {
Elliott Hughes86964332012-02-15 19:37:42 -08003020 event_flags |= kSingleStep;
3021 VLOG(jdwp) << "SS new instruction";
Sebastien Hertzbb43b432014-04-14 11:59:08 +02003022 } else if (single_step_control->ContainsDexPc(dex_pc)) {
Elliott Hughes2435a572012-02-17 16:07:41 -08003023 event_flags |= kSingleStep;
3024 VLOG(jdwp) << "SS new line";
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08003025 }
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01003026 }
3027 } else {
Sebastien Hertz597c4f02015-01-26 17:37:14 +01003028 CHECK_EQ(single_step_control->GetStepDepth(), JDWP::SD_OUT);
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01003029 // Return from the current method. We break when the frame
3030 // depth pops up.
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08003031
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01003032 // This differs from the "method exit" break in that it stops
3033 // with the PC at the next instruction in the returned-to
3034 // function, rather than the end of the returning function.
Elliott Hughes86964332012-02-15 19:37:42 -08003035
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01003036 int stack_depth = GetStackDepth(thread);
Sebastien Hertz597c4f02015-01-26 17:37:14 +01003037 if (stack_depth < single_step_control->GetStackDepth()) {
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01003038 event_flags |= kSingleStep;
3039 VLOG(jdwp) << "SS method pop";
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08003040 }
3041 }
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08003042 }
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08003043
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08003044 // If there's something interesting going on, see if it matches one
3045 // of the debugger filters.
3046 if (event_flags != 0) {
Sebastien Hertz8379b222014-02-24 17:38:15 +01003047 Dbg::PostLocationEvent(m, dex_pc, this_object, event_flags, return_value);
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08003048 }
3049}
3050
Sebastien Hertz42cd43f2014-05-13 14:15:41 +02003051size_t* Dbg::GetReferenceCounterForEvent(uint32_t instrumentation_event) {
3052 switch (instrumentation_event) {
3053 case instrumentation::Instrumentation::kMethodEntered:
3054 return &method_enter_event_ref_count_;
3055 case instrumentation::Instrumentation::kMethodExited:
3056 return &method_exit_event_ref_count_;
3057 case instrumentation::Instrumentation::kDexPcMoved:
3058 return &dex_pc_change_event_ref_count_;
3059 case instrumentation::Instrumentation::kFieldRead:
3060 return &field_read_event_ref_count_;
3061 case instrumentation::Instrumentation::kFieldWritten:
3062 return &field_write_event_ref_count_;
3063 case instrumentation::Instrumentation::kExceptionCaught:
3064 return &exception_catch_event_ref_count_;
3065 default:
3066 return nullptr;
3067 }
3068}
3069
Sebastien Hertz4d25df32014-03-21 17:44:46 +01003070// Process request while all mutator threads are suspended.
3071void Dbg::ProcessDeoptimizationRequest(const DeoptimizationRequest& request) {
Sebastien Hertz138dbfc2013-12-04 18:15:25 +01003072 instrumentation::Instrumentation* instrumentation = Runtime::Current()->GetInstrumentation();
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003073 switch (request.GetKind()) {
Sebastien Hertz4d25df32014-03-21 17:44:46 +01003074 case DeoptimizationRequest::kNothing:
3075 LOG(WARNING) << "Ignoring empty deoptimization request.";
3076 break;
Sebastien Hertz42cd43f2014-05-13 14:15:41 +02003077 case DeoptimizationRequest::kRegisterForEvent:
3078 VLOG(jdwp) << StringPrintf("Add debugger as listener for instrumentation event 0x%x",
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003079 request.InstrumentationEvent());
3080 instrumentation->AddListener(&gDebugInstrumentationListener, request.InstrumentationEvent());
3081 instrumentation_events_ |= request.InstrumentationEvent();
Sebastien Hertz42cd43f2014-05-13 14:15:41 +02003082 break;
3083 case DeoptimizationRequest::kUnregisterForEvent:
3084 VLOG(jdwp) << StringPrintf("Remove debugger as listener for instrumentation event 0x%x",
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003085 request.InstrumentationEvent());
Sebastien Hertz42cd43f2014-05-13 14:15:41 +02003086 instrumentation->RemoveListener(&gDebugInstrumentationListener,
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003087 request.InstrumentationEvent());
3088 instrumentation_events_ &= ~request.InstrumentationEvent();
Sebastien Hertz42cd43f2014-05-13 14:15:41 +02003089 break;
Sebastien Hertz4d25df32014-03-21 17:44:46 +01003090 case DeoptimizationRequest::kFullDeoptimization:
Sebastien Hertz7ec2f1c2014-03-27 20:06:47 +01003091 VLOG(jdwp) << "Deoptimize the world ...";
Sebastien Hertz0462c4c2015-04-01 16:34:17 +02003092 instrumentation->DeoptimizeEverything(kDbgInstrumentationKey);
Sebastien Hertz7ec2f1c2014-03-27 20:06:47 +01003093 VLOG(jdwp) << "Deoptimize the world DONE";
Sebastien Hertz4d25df32014-03-21 17:44:46 +01003094 break;
3095 case DeoptimizationRequest::kFullUndeoptimization:
Sebastien Hertz7ec2f1c2014-03-27 20:06:47 +01003096 VLOG(jdwp) << "Undeoptimize the world ...";
Sebastien Hertz0462c4c2015-04-01 16:34:17 +02003097 instrumentation->UndeoptimizeEverything(kDbgInstrumentationKey);
Sebastien Hertz7ec2f1c2014-03-27 20:06:47 +01003098 VLOG(jdwp) << "Undeoptimize the world DONE";
Sebastien Hertz4d25df32014-03-21 17:44:46 +01003099 break;
3100 case DeoptimizationRequest::kSelectiveDeoptimization:
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003101 VLOG(jdwp) << "Deoptimize method " << PrettyMethod(request.Method()) << " ...";
3102 instrumentation->Deoptimize(request.Method());
3103 VLOG(jdwp) << "Deoptimize method " << PrettyMethod(request.Method()) << " DONE";
Sebastien Hertz4d25df32014-03-21 17:44:46 +01003104 break;
3105 case DeoptimizationRequest::kSelectiveUndeoptimization:
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003106 VLOG(jdwp) << "Undeoptimize method " << PrettyMethod(request.Method()) << " ...";
3107 instrumentation->Undeoptimize(request.Method());
3108 VLOG(jdwp) << "Undeoptimize method " << PrettyMethod(request.Method()) << " DONE";
Sebastien Hertz4d25df32014-03-21 17:44:46 +01003109 break;
3110 default:
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003111 LOG(FATAL) << "Unsupported deoptimization request kind " << request.GetKind();
Sebastien Hertz4d25df32014-03-21 17:44:46 +01003112 break;
Sebastien Hertz138dbfc2013-12-04 18:15:25 +01003113 }
Sebastien Hertz138dbfc2013-12-04 18:15:25 +01003114}
3115
Sebastien Hertz4d25df32014-03-21 17:44:46 +01003116void Dbg::RequestDeoptimization(const DeoptimizationRequest& req) {
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003117 if (req.GetKind() == DeoptimizationRequest::kNothing) {
Sebastien Hertz4d25df32014-03-21 17:44:46 +01003118 // Nothing to do.
3119 return;
3120 }
Brian Carlstrom306db812014-09-05 13:01:41 -07003121 MutexLock mu(Thread::Current(), *Locks::deoptimization_lock_);
Sebastien Hertz7ec2f1c2014-03-27 20:06:47 +01003122 RequestDeoptimizationLocked(req);
3123}
3124
3125void Dbg::RequestDeoptimizationLocked(const DeoptimizationRequest& req) {
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003126 switch (req.GetKind()) {
Sebastien Hertz42cd43f2014-05-13 14:15:41 +02003127 case DeoptimizationRequest::kRegisterForEvent: {
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003128 DCHECK_NE(req.InstrumentationEvent(), 0u);
3129 size_t* counter = GetReferenceCounterForEvent(req.InstrumentationEvent());
Sebastien Hertz42cd43f2014-05-13 14:15:41 +02003130 CHECK(counter != nullptr) << StringPrintf("No counter for instrumentation event 0x%x",
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003131 req.InstrumentationEvent());
Sebastien Hertz42cd43f2014-05-13 14:15:41 +02003132 if (*counter == 0) {
Sebastien Hertz7d2ae432014-05-15 11:26:34 +02003133 VLOG(jdwp) << StringPrintf("Queue request #%zd to start listening to instrumentation event 0x%x",
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003134 deoptimization_requests_.size(), req.InstrumentationEvent());
Sebastien Hertz42cd43f2014-05-13 14:15:41 +02003135 deoptimization_requests_.push_back(req);
3136 }
3137 *counter = *counter + 1;
3138 break;
3139 }
3140 case DeoptimizationRequest::kUnregisterForEvent: {
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003141 DCHECK_NE(req.InstrumentationEvent(), 0u);
3142 size_t* counter = GetReferenceCounterForEvent(req.InstrumentationEvent());
Sebastien Hertz42cd43f2014-05-13 14:15:41 +02003143 CHECK(counter != nullptr) << StringPrintf("No counter for instrumentation event 0x%x",
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003144 req.InstrumentationEvent());
Sebastien Hertz42cd43f2014-05-13 14:15:41 +02003145 *counter = *counter - 1;
3146 if (*counter == 0) {
Sebastien Hertz7d2ae432014-05-15 11:26:34 +02003147 VLOG(jdwp) << StringPrintf("Queue request #%zd to stop listening to instrumentation event 0x%x",
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003148 deoptimization_requests_.size(), req.InstrumentationEvent());
Sebastien Hertz42cd43f2014-05-13 14:15:41 +02003149 deoptimization_requests_.push_back(req);
3150 }
3151 break;
3152 }
Sebastien Hertz4d25df32014-03-21 17:44:46 +01003153 case DeoptimizationRequest::kFullDeoptimization: {
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003154 DCHECK(req.Method() == nullptr);
Sebastien Hertz4d25df32014-03-21 17:44:46 +01003155 if (full_deoptimization_event_count_ == 0) {
Sebastien Hertz7ec2f1c2014-03-27 20:06:47 +01003156 VLOG(jdwp) << "Queue request #" << deoptimization_requests_.size()
3157 << " for full deoptimization";
Sebastien Hertz4d25df32014-03-21 17:44:46 +01003158 deoptimization_requests_.push_back(req);
3159 }
3160 ++full_deoptimization_event_count_;
3161 break;
3162 }
3163 case DeoptimizationRequest::kFullUndeoptimization: {
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003164 DCHECK(req.Method() == nullptr);
Sebastien Hertze713d932014-05-15 10:48:53 +02003165 DCHECK_GT(full_deoptimization_event_count_, 0U);
Sebastien Hertz4d25df32014-03-21 17:44:46 +01003166 --full_deoptimization_event_count_;
3167 if (full_deoptimization_event_count_ == 0) {
Sebastien Hertz7ec2f1c2014-03-27 20:06:47 +01003168 VLOG(jdwp) << "Queue request #" << deoptimization_requests_.size()
3169 << " for full undeoptimization";
Sebastien Hertz4d25df32014-03-21 17:44:46 +01003170 deoptimization_requests_.push_back(req);
3171 }
3172 break;
3173 }
3174 case DeoptimizationRequest::kSelectiveDeoptimization: {
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003175 DCHECK(req.Method() != nullptr);
Sebastien Hertz7ec2f1c2014-03-27 20:06:47 +01003176 VLOG(jdwp) << "Queue request #" << deoptimization_requests_.size()
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003177 << " for deoptimization of " << PrettyMethod(req.Method());
Sebastien Hertz4d25df32014-03-21 17:44:46 +01003178 deoptimization_requests_.push_back(req);
3179 break;
3180 }
3181 case DeoptimizationRequest::kSelectiveUndeoptimization: {
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003182 DCHECK(req.Method() != nullptr);
Sebastien Hertz7ec2f1c2014-03-27 20:06:47 +01003183 VLOG(jdwp) << "Queue request #" << deoptimization_requests_.size()
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003184 << " for undeoptimization of " << PrettyMethod(req.Method());
Sebastien Hertz4d25df32014-03-21 17:44:46 +01003185 deoptimization_requests_.push_back(req);
3186 break;
3187 }
3188 default: {
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003189 LOG(FATAL) << "Unknown deoptimization request kind " << req.GetKind();
Sebastien Hertz4d25df32014-03-21 17:44:46 +01003190 break;
3191 }
3192 }
3193}
3194
Sebastien Hertz138dbfc2013-12-04 18:15:25 +01003195void Dbg::ManageDeoptimization() {
3196 Thread* const self = Thread::Current();
3197 {
3198 // Avoid suspend/resume if there is no pending request.
Brian Carlstrom306db812014-09-05 13:01:41 -07003199 MutexLock mu(self, *Locks::deoptimization_lock_);
Sebastien Hertz4d25df32014-03-21 17:44:46 +01003200 if (deoptimization_requests_.empty()) {
Sebastien Hertz138dbfc2013-12-04 18:15:25 +01003201 return;
3202 }
3203 }
3204 CHECK_EQ(self->GetState(), kRunnable);
3205 self->TransitionFromRunnableToSuspended(kWaitingForDeoptimization);
3206 // We need to suspend mutator threads first.
3207 Runtime* const runtime = Runtime::Current();
Mathieu Chartierbf9fc582015-03-13 17:21:25 -07003208 runtime->GetThreadList()->SuspendAll(__FUNCTION__);
Sebastien Hertz138dbfc2013-12-04 18:15:25 +01003209 const ThreadState old_state = self->SetStateUnsafe(kRunnable);
Sebastien Hertz4d25df32014-03-21 17:44:46 +01003210 {
Brian Carlstrom306db812014-09-05 13:01:41 -07003211 MutexLock mu(self, *Locks::deoptimization_lock_);
Sebastien Hertz7ec2f1c2014-03-27 20:06:47 +01003212 size_t req_index = 0;
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003213 for (DeoptimizationRequest& request : deoptimization_requests_) {
Sebastien Hertz7ec2f1c2014-03-27 20:06:47 +01003214 VLOG(jdwp) << "Process deoptimization request #" << req_index++;
Sebastien Hertz4d25df32014-03-21 17:44:46 +01003215 ProcessDeoptimizationRequest(request);
3216 }
3217 deoptimization_requests_.clear();
3218 }
Sebastien Hertz138dbfc2013-12-04 18:15:25 +01003219 CHECK_EQ(self->SetStateUnsafe(old_state), kRunnable);
3220 runtime->GetThreadList()->ResumeAll();
3221 self->TransitionFromSuspendedToRunnable();
3222}
3223
Sebastien Hertza76a6d42014-03-20 16:40:17 +01003224static bool IsMethodPossiblyInlined(Thread* self, mirror::ArtMethod* m)
3225 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07003226 const DexFile::CodeItem* code_item = m->GetCodeItem();
Sebastien Hertza76a6d42014-03-20 16:40:17 +01003227 if (code_item == nullptr) {
3228 // TODO We should not be asked to watch location in a native or abstract method so the code item
3229 // should never be null. We could just check we never encounter this case.
3230 return false;
Sebastien Hertz138dbfc2013-12-04 18:15:25 +01003231 }
Sebastien Hertz4d1e9ab2014-09-18 16:03:34 +02003232 // Note: method verifier may cause thread suspension.
3233 self->AssertThreadSuspensionIsAllowable();
Hiroshi Yamauchidc376172014-08-22 11:13:12 -07003234 StackHandleScope<3> hs(self);
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07003235 mirror::Class* declaring_class = m->GetDeclaringClass();
3236 Handle<mirror::DexCache> dex_cache(hs.NewHandle(declaring_class->GetDexCache()));
3237 Handle<mirror::ClassLoader> class_loader(hs.NewHandle(declaring_class->GetClassLoader()));
Hiroshi Yamauchidc376172014-08-22 11:13:12 -07003238 Handle<mirror::ArtMethod> method(hs.NewHandle(m));
Ian Rogers7b078e82014-09-10 14:44:24 -07003239 verifier::MethodVerifier verifier(self, dex_cache->GetDexFile(), dex_cache, class_loader,
Hiroshi Yamauchidc376172014-08-22 11:13:12 -07003240 &m->GetClassDef(), code_item, m->GetDexMethodIndex(), method,
Mathieu Chartier4306ef82014-12-19 18:41:47 -08003241 m->GetAccessFlags(), false, true, false, true);
Sebastien Hertza76a6d42014-03-20 16:40:17 +01003242 // Note: we don't need to verify the method.
3243 return InlineMethodAnalyser::AnalyseMethodCode(&verifier, nullptr);
3244}
Sebastien Hertz138dbfc2013-12-04 18:15:25 +01003245
Sebastien Hertza76a6d42014-03-20 16:40:17 +01003246static const Breakpoint* FindFirstBreakpointForMethod(mirror::ArtMethod* m)
Sebastien Hertzed2be172014-08-19 15:33:43 +02003247 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_, Locks::breakpoint_lock_) {
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003248 for (Breakpoint& breakpoint : gBreakpoints) {
3249 if (breakpoint.Method() == m) {
Sebastien Hertza76a6d42014-03-20 16:40:17 +01003250 return &breakpoint;
3251 }
3252 }
3253 return nullptr;
3254}
3255
Mathieu Chartierd8565452015-03-26 09:41:50 -07003256bool Dbg::MethodHasAnyBreakpoints(mirror::ArtMethod* method) {
3257 ReaderMutexLock mu(Thread::Current(), *Locks::breakpoint_lock_);
3258 return FindFirstBreakpointForMethod(method) != nullptr;
3259}
3260
Sebastien Hertza76a6d42014-03-20 16:40:17 +01003261// Sanity checks all existing breakpoints on the same method.
Sebastien Hertzf3928792014-11-17 19:00:37 +01003262static void SanityCheckExistingBreakpoints(mirror::ArtMethod* m,
3263 DeoptimizationRequest::Kind deoptimization_kind)
Sebastien Hertzed2be172014-08-19 15:33:43 +02003264 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_, Locks::breakpoint_lock_) {
Sebastien Hertz4d1e9ab2014-09-18 16:03:34 +02003265 for (const Breakpoint& breakpoint : gBreakpoints) {
Sebastien Hertzf3928792014-11-17 19:00:37 +01003266 if (breakpoint.Method() == m) {
3267 CHECK_EQ(deoptimization_kind, breakpoint.GetDeoptimizationKind());
3268 }
Sebastien Hertz4d1e9ab2014-09-18 16:03:34 +02003269 }
Sebastien Hertzf3928792014-11-17 19:00:37 +01003270 instrumentation::Instrumentation* instrumentation = Runtime::Current()->GetInstrumentation();
3271 if (deoptimization_kind == DeoptimizationRequest::kFullDeoptimization) {
Sebastien Hertz4d1e9ab2014-09-18 16:03:34 +02003272 // We should have deoptimized everything but not "selectively" deoptimized this method.
Sebastien Hertzf3928792014-11-17 19:00:37 +01003273 CHECK(instrumentation->AreAllMethodsDeoptimized());
3274 CHECK(!instrumentation->IsDeoptimized(m));
3275 } else if (deoptimization_kind == DeoptimizationRequest::kSelectiveDeoptimization) {
Sebastien Hertz4d1e9ab2014-09-18 16:03:34 +02003276 // We should have "selectively" deoptimized this method.
3277 // Note: while we have not deoptimized everything for this method, we may have done it for
3278 // another event.
Sebastien Hertzf3928792014-11-17 19:00:37 +01003279 CHECK(instrumentation->IsDeoptimized(m));
3280 } else {
3281 // This method does not require deoptimization.
3282 CHECK_EQ(deoptimization_kind, DeoptimizationRequest::kNothing);
3283 CHECK(!instrumentation->IsDeoptimized(m));
3284 }
3285}
3286
Sebastien Hertzabe93e02014-12-17 16:35:50 +01003287// Returns the deoptimization kind required to set a breakpoint in a method.
3288// If a breakpoint has already been set, we also return the first breakpoint
3289// through the given 'existing_brkpt' pointer.
Sebastien Hertzf3928792014-11-17 19:00:37 +01003290static DeoptimizationRequest::Kind GetRequiredDeoptimizationKind(Thread* self,
Sebastien Hertzabe93e02014-12-17 16:35:50 +01003291 mirror::ArtMethod* m,
3292 const Breakpoint** existing_brkpt)
Sebastien Hertzf3928792014-11-17 19:00:37 +01003293 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
3294 if (!Dbg::RequiresDeoptimization()) {
3295 // We already run in interpreter-only mode so we don't need to deoptimize anything.
3296 VLOG(jdwp) << "No need for deoptimization when fully running with interpreter for method "
3297 << PrettyMethod(m);
3298 return DeoptimizationRequest::kNothing;
3299 }
Sebastien Hertzabe93e02014-12-17 16:35:50 +01003300 const Breakpoint* first_breakpoint;
Sebastien Hertzf3928792014-11-17 19:00:37 +01003301 {
3302 ReaderMutexLock mu(self, *Locks::breakpoint_lock_);
Sebastien Hertzabe93e02014-12-17 16:35:50 +01003303 first_breakpoint = FindFirstBreakpointForMethod(m);
3304 *existing_brkpt = first_breakpoint;
Sebastien Hertzf3928792014-11-17 19:00:37 +01003305 }
Sebastien Hertzabe93e02014-12-17 16:35:50 +01003306
3307 if (first_breakpoint == nullptr) {
Sebastien Hertzf3928792014-11-17 19:00:37 +01003308 // There is no breakpoint on this method yet: we need to deoptimize. If this method may be
3309 // inlined, we deoptimize everything; otherwise we deoptimize only this method.
3310 // Note: IsMethodPossiblyInlined goes into the method verifier and may cause thread suspension.
3311 // Therefore we must not hold any lock when we call it.
3312 bool need_full_deoptimization = IsMethodPossiblyInlined(self, m);
3313 if (need_full_deoptimization) {
3314 VLOG(jdwp) << "Need full deoptimization because of possible inlining of method "
3315 << PrettyMethod(m);
3316 return DeoptimizationRequest::kFullDeoptimization;
3317 } else {
3318 // We don't need to deoptimize if the method has not been compiled.
3319 ClassLinker* const class_linker = Runtime::Current()->GetClassLinker();
3320 const bool is_compiled = class_linker->GetOatMethodQuickCodeFor(m) != nullptr;
3321 if (is_compiled) {
Sebastien Hertz6963e442014-11-26 22:11:27 +01003322 // If the method may be called through its direct code pointer (without loading
3323 // its updated entrypoint), we need full deoptimization to not miss the breakpoint.
3324 if (class_linker->MayBeCalledWithDirectCodePointer(m)) {
3325 VLOG(jdwp) << "Need full deoptimization because of possible direct code call "
3326 << "into image for compiled method " << PrettyMethod(m);
3327 return DeoptimizationRequest::kFullDeoptimization;
3328 } else {
3329 VLOG(jdwp) << "Need selective deoptimization for compiled method " << PrettyMethod(m);
3330 return DeoptimizationRequest::kSelectiveDeoptimization;
3331 }
Sebastien Hertzf3928792014-11-17 19:00:37 +01003332 } else {
3333 // Method is not compiled: we don't need to deoptimize.
3334 VLOG(jdwp) << "No need for deoptimization for non-compiled method " << PrettyMethod(m);
3335 return DeoptimizationRequest::kNothing;
3336 }
3337 }
3338 } else {
3339 // There is at least one breakpoint for this method: we don't need to deoptimize.
3340 // Let's check that all breakpoints are configured the same way for deoptimization.
3341 VLOG(jdwp) << "Breakpoint already set: no deoptimization is required";
Sebastien Hertzabe93e02014-12-17 16:35:50 +01003342 DeoptimizationRequest::Kind deoptimization_kind = first_breakpoint->GetDeoptimizationKind();
Sebastien Hertzf3928792014-11-17 19:00:37 +01003343 if (kIsDebugBuild) {
3344 ReaderMutexLock mu(self, *Locks::breakpoint_lock_);
3345 SanityCheckExistingBreakpoints(m, deoptimization_kind);
3346 }
3347 return DeoptimizationRequest::kNothing;
Sebastien Hertz138dbfc2013-12-04 18:15:25 +01003348 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -07003349}
3350
Sebastien Hertza76a6d42014-03-20 16:40:17 +01003351// Installs a breakpoint at the specified location. Also indicates through the deoptimization
3352// request if we need to deoptimize.
3353void Dbg::WatchLocation(const JDWP::JdwpLocation* location, DeoptimizationRequest* req) {
3354 Thread* const self = Thread::Current();
Brian Carlstromea46f952013-07-30 01:26:50 -07003355 mirror::ArtMethod* m = FromMethodId(location->method_id);
Sebastien Hertza76a6d42014-03-20 16:40:17 +01003356 DCHECK(m != nullptr) << "No method for method id " << location->method_id;
Sebastien Hertz138dbfc2013-12-04 18:15:25 +01003357
Sebastien Hertzabe93e02014-12-17 16:35:50 +01003358 const Breakpoint* existing_breakpoint = nullptr;
3359 const DeoptimizationRequest::Kind deoptimization_kind =
3360 GetRequiredDeoptimizationKind(self, m, &existing_breakpoint);
Sebastien Hertzf3928792014-11-17 19:00:37 +01003361 req->SetKind(deoptimization_kind);
3362 if (deoptimization_kind == DeoptimizationRequest::kSelectiveDeoptimization) {
3363 req->SetMethod(m);
Sebastien Hertza76a6d42014-03-20 16:40:17 +01003364 } else {
Sebastien Hertzf3928792014-11-17 19:00:37 +01003365 CHECK(deoptimization_kind == DeoptimizationRequest::kNothing ||
3366 deoptimization_kind == DeoptimizationRequest::kFullDeoptimization);
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003367 req->SetMethod(nullptr);
Sebastien Hertz138dbfc2013-12-04 18:15:25 +01003368 }
3369
Sebastien Hertz4d1e9ab2014-09-18 16:03:34 +02003370 {
3371 WriterMutexLock mu(self, *Locks::breakpoint_lock_);
Sebastien Hertzabe93e02014-12-17 16:35:50 +01003372 // If there is at least one existing breakpoint on the same method, the new breakpoint
3373 // must have the same deoptimization kind than the existing breakpoint(s).
3374 DeoptimizationRequest::Kind breakpoint_deoptimization_kind;
3375 if (existing_breakpoint != nullptr) {
3376 breakpoint_deoptimization_kind = existing_breakpoint->GetDeoptimizationKind();
3377 } else {
3378 breakpoint_deoptimization_kind = deoptimization_kind;
3379 }
3380 gBreakpoints.push_back(Breakpoint(m, location->dex_pc, breakpoint_deoptimization_kind));
Sebastien Hertz4d1e9ab2014-09-18 16:03:34 +02003381 VLOG(jdwp) << "Set breakpoint #" << (gBreakpoints.size() - 1) << ": "
3382 << gBreakpoints[gBreakpoints.size() - 1];
3383 }
Sebastien Hertza76a6d42014-03-20 16:40:17 +01003384}
3385
3386// Uninstalls a breakpoint at the specified location. Also indicates through the deoptimization
3387// request if we need to undeoptimize.
3388void Dbg::UnwatchLocation(const JDWP::JdwpLocation* location, DeoptimizationRequest* req) {
Sebastien Hertzed2be172014-08-19 15:33:43 +02003389 WriterMutexLock mu(Thread::Current(), *Locks::breakpoint_lock_);
Sebastien Hertza76a6d42014-03-20 16:40:17 +01003390 mirror::ArtMethod* m = FromMethodId(location->method_id);
3391 DCHECK(m != nullptr) << "No method for method id " << location->method_id;
Sebastien Hertzf3928792014-11-17 19:00:37 +01003392 DeoptimizationRequest::Kind deoptimization_kind = DeoptimizationRequest::kNothing;
Sebastien Hertza76a6d42014-03-20 16:40:17 +01003393 for (size_t i = 0, e = gBreakpoints.size(); i < e; ++i) {
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003394 if (gBreakpoints[i].DexPc() == location->dex_pc && gBreakpoints[i].Method() == m) {
Sebastien Hertza76a6d42014-03-20 16:40:17 +01003395 VLOG(jdwp) << "Removed breakpoint #" << i << ": " << gBreakpoints[i];
Sebastien Hertzf3928792014-11-17 19:00:37 +01003396 deoptimization_kind = gBreakpoints[i].GetDeoptimizationKind();
3397 DCHECK_EQ(deoptimization_kind == DeoptimizationRequest::kSelectiveDeoptimization,
3398 Runtime::Current()->GetInstrumentation()->IsDeoptimized(m));
Sebastien Hertza76a6d42014-03-20 16:40:17 +01003399 gBreakpoints.erase(gBreakpoints.begin() + i);
3400 break;
3401 }
3402 }
3403 const Breakpoint* const existing_breakpoint = FindFirstBreakpointForMethod(m);
3404 if (existing_breakpoint == nullptr) {
3405 // There is no more breakpoint on this method: we need to undeoptimize.
Sebastien Hertzf3928792014-11-17 19:00:37 +01003406 if (deoptimization_kind == DeoptimizationRequest::kFullDeoptimization) {
Sebastien Hertza76a6d42014-03-20 16:40:17 +01003407 // This method required full deoptimization: we need to undeoptimize everything.
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003408 req->SetKind(DeoptimizationRequest::kFullUndeoptimization);
3409 req->SetMethod(nullptr);
Sebastien Hertzf3928792014-11-17 19:00:37 +01003410 } else if (deoptimization_kind == DeoptimizationRequest::kSelectiveDeoptimization) {
Sebastien Hertza76a6d42014-03-20 16:40:17 +01003411 // This method required selective deoptimization: we need to undeoptimize only that method.
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003412 req->SetKind(DeoptimizationRequest::kSelectiveUndeoptimization);
3413 req->SetMethod(m);
Sebastien Hertzf3928792014-11-17 19:00:37 +01003414 } else {
3415 // This method had no need for deoptimization: do nothing.
3416 CHECK_EQ(deoptimization_kind, DeoptimizationRequest::kNothing);
3417 req->SetKind(DeoptimizationRequest::kNothing);
3418 req->SetMethod(nullptr);
Sebastien Hertza76a6d42014-03-20 16:40:17 +01003419 }
3420 } else {
3421 // There is at least one breakpoint for this method: we don't need to undeoptimize.
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003422 req->SetKind(DeoptimizationRequest::kNothing);
3423 req->SetMethod(nullptr);
Sebastien Hertz4d1e9ab2014-09-18 16:03:34 +02003424 if (kIsDebugBuild) {
Sebastien Hertzf3928792014-11-17 19:00:37 +01003425 SanityCheckExistingBreakpoints(m, deoptimization_kind);
Sebastien Hertz4d1e9ab2014-09-18 16:03:34 +02003426 }
Elliott Hughes86964332012-02-15 19:37:42 -08003427 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -07003428}
3429
Daniel Mihalyieb076692014-08-22 17:33:31 +02003430bool Dbg::IsForcedInterpreterNeededForCallingImpl(Thread* thread, mirror::ArtMethod* m) {
3431 const SingleStepControl* const ssc = thread->GetSingleStepControl();
3432 if (ssc == nullptr) {
3433 // If we are not single-stepping, then we don't have to force interpreter.
3434 return false;
3435 }
3436 if (Runtime::Current()->GetInstrumentation()->InterpretOnly()) {
3437 // If we are in interpreter only mode, then we don't have to force interpreter.
3438 return false;
3439 }
3440
3441 if (!m->IsNative() && !m->IsProxyMethod()) {
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 }
3447 return false;
3448}
3449
3450bool Dbg::IsForcedInterpreterNeededForResolutionImpl(Thread* thread, mirror::ArtMethod* m) {
3451 instrumentation::Instrumentation* const instrumentation =
3452 Runtime::Current()->GetInstrumentation();
3453 // If we are in interpreter only mode, then we don't have to force interpreter.
3454 if (instrumentation->InterpretOnly()) {
3455 return false;
3456 }
3457 // We can only interpret pure Java method.
3458 if (m->IsNative() || m->IsProxyMethod()) {
3459 return false;
3460 }
3461 const SingleStepControl* const ssc = thread->GetSingleStepControl();
3462 if (ssc != nullptr) {
3463 // If we want to step into a method, then we have to force interpreter on that call.
3464 if (ssc->GetStepDepth() == JDWP::SD_INTO) {
3465 return true;
3466 }
3467 // If we are stepping out from a static initializer, by issuing a step
3468 // in or step over, that was implicitly invoked by calling a static method,
3469 // then we need to step into that method. Having a lower stack depth than
3470 // the one the single step control has indicates that the step originates
3471 // from the static initializer.
3472 if (ssc->GetStepDepth() != JDWP::SD_OUT &&
3473 ssc->GetStackDepth() > GetStackDepth(thread)) {
3474 return true;
3475 }
3476 }
3477 // There are cases where we have to force interpreter on deoptimized methods,
3478 // because in some cases the call will not be performed by invoking an entry
3479 // point that has been replaced by the deoptimization, but instead by directly
3480 // invoking the compiled code of the method, for example.
3481 return instrumentation->IsDeoptimized(m);
3482}
3483
3484bool Dbg::IsForcedInstrumentationNeededForResolutionImpl(Thread* thread, mirror::ArtMethod* m) {
Mathieu Chartier2cebb242015-04-21 16:50:40 -07003485 // The upcall can be null and in that case we don't need to do anything.
Daniel Mihalyieb076692014-08-22 17:33:31 +02003486 if (m == nullptr) {
3487 return false;
3488 }
3489 instrumentation::Instrumentation* const instrumentation =
3490 Runtime::Current()->GetInstrumentation();
3491 // If we are in interpreter only mode, then we don't have to force interpreter.
3492 if (instrumentation->InterpretOnly()) {
3493 return false;
3494 }
3495 // We can only interpret pure Java method.
3496 if (m->IsNative() || m->IsProxyMethod()) {
3497 return false;
3498 }
3499 const SingleStepControl* const ssc = thread->GetSingleStepControl();
3500 if (ssc != nullptr) {
3501 // If we are stepping out from a static initializer, by issuing a step
3502 // out, that was implicitly invoked by calling a static method, then we
3503 // need to step into the caller of that method. Having a lower stack
3504 // depth than the one the single step control has indicates that the
3505 // step originates from the static initializer.
3506 if (ssc->GetStepDepth() == JDWP::SD_OUT &&
3507 ssc->GetStackDepth() > GetStackDepth(thread)) {
3508 return true;
3509 }
3510 }
3511 // If we are returning from a static intializer, that was implicitly
3512 // invoked by calling a static method and the caller is deoptimized,
3513 // then we have to deoptimize the stack without forcing interpreter
3514 // on the static method that was called originally. This problem can
3515 // be solved easily by forcing instrumentation on the called method,
3516 // because the instrumentation exit hook will recognise the need of
3517 // stack deoptimization by calling IsForcedInterpreterNeededForUpcall.
3518 return instrumentation->IsDeoptimized(m);
3519}
3520
3521bool Dbg::IsForcedInterpreterNeededForUpcallImpl(Thread* thread, mirror::ArtMethod* m) {
Mathieu Chartier2cebb242015-04-21 16:50:40 -07003522 // The upcall can be null and in that case we don't need to do anything.
Daniel Mihalyieb076692014-08-22 17:33:31 +02003523 if (m == nullptr) {
3524 return false;
3525 }
3526 instrumentation::Instrumentation* const instrumentation =
3527 Runtime::Current()->GetInstrumentation();
3528 // If we are in interpreter only mode, then we don't have to force interpreter.
3529 if (instrumentation->InterpretOnly()) {
3530 return false;
3531 }
3532 // We can only interpret pure Java method.
3533 if (m->IsNative() || m->IsProxyMethod()) {
3534 return false;
3535 }
3536 const SingleStepControl* const ssc = thread->GetSingleStepControl();
3537 if (ssc != nullptr) {
3538 // The debugger is not interested in what is happening under the level
3539 // of the step, thus we only force interpreter when we are not below of
3540 // the step.
3541 if (ssc->GetStackDepth() >= GetStackDepth(thread)) {
3542 return true;
3543 }
3544 }
3545 // We have to require stack deoptimization if the upcall is deoptimized.
3546 return instrumentation->IsDeoptimized(m);
3547}
3548
Jeff Hao449db332013-04-12 18:30:52 -07003549// Scoped utility class to suspend a thread so that we may do tasks such as walk its stack. Doesn't
3550// cause suspension if the thread is the current thread.
3551class ScopedThreadSuspension {
3552 public:
Ian Rogers33e95662013-05-20 20:29:14 -07003553 ScopedThreadSuspension(Thread* self, JDWP::ObjectId thread_id)
Sebastien Hertz52d131d2014-03-13 16:17:40 +01003554 LOCKS_EXCLUDED(Locks::thread_list_lock_)
Ian Rogers33e95662013-05-20 20:29:14 -07003555 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) :
Ian Rogersf3d874c2014-07-17 18:52:42 -07003556 thread_(nullptr),
Jeff Hao449db332013-04-12 18:30:52 -07003557 error_(JDWP::ERR_NONE),
3558 self_suspend_(false),
Ian Rogers33e95662013-05-20 20:29:14 -07003559 other_suspend_(false) {
Jeff Hao449db332013-04-12 18:30:52 -07003560 ScopedObjectAccessUnchecked soa(self);
Sebastien Hertz69206392015-04-07 15:54:25 +02003561 thread_ = DecodeThread(soa, thread_id, &error_);
Jeff Hao449db332013-04-12 18:30:52 -07003562 if (error_ == JDWP::ERR_NONE) {
3563 if (thread_ == soa.Self()) {
3564 self_suspend_ = true;
3565 } else {
3566 soa.Self()->TransitionFromRunnableToSuspended(kWaitingForDebuggerSuspension);
Sebastien Hertz6995c602014-09-09 12:10:13 +02003567 jobject thread_peer = Dbg::GetObjectRegistry()->GetJObject(thread_id);
Jeff Hao449db332013-04-12 18:30:52 -07003568 bool timed_out;
Ian Rogers4ad5cd32014-11-11 23:08:07 -08003569 ThreadList* thread_list = Runtime::Current()->GetThreadList();
3570 Thread* suspended_thread = thread_list->SuspendThreadByPeer(thread_peer, true, true,
3571 &timed_out);
Jeff Hao449db332013-04-12 18:30:52 -07003572 CHECK_EQ(soa.Self()->TransitionFromSuspendedToRunnable(), kWaitingForDebuggerSuspension);
Ian Rogersf3d874c2014-07-17 18:52:42 -07003573 if (suspended_thread == nullptr) {
Jeff Hao449db332013-04-12 18:30:52 -07003574 // Thread terminated from under us while suspending.
3575 error_ = JDWP::ERR_INVALID_THREAD;
3576 } else {
3577 CHECK_EQ(suspended_thread, thread_);
3578 other_suspend_ = true;
3579 }
3580 }
3581 }
Elliott Hughes2435a572012-02-17 16:07:41 -08003582 }
Elliott Hughes86964332012-02-15 19:37:42 -08003583
Jeff Hao449db332013-04-12 18:30:52 -07003584 Thread* GetThread() const {
3585 return thread_;
3586 }
3587
3588 JDWP::JdwpError GetError() const {
3589 return error_;
3590 }
3591
3592 ~ScopedThreadSuspension() {
3593 if (other_suspend_) {
3594 Runtime::Current()->GetThreadList()->Resume(thread_, true);
3595 }
3596 }
3597
3598 private:
3599 Thread* thread_;
3600 JDWP::JdwpError error_;
3601 bool self_suspend_;
3602 bool other_suspend_;
3603};
3604
3605JDWP::JdwpError Dbg::ConfigureStep(JDWP::ObjectId thread_id, JDWP::JdwpStepSize step_size,
3606 JDWP::JdwpStepDepth step_depth) {
3607 Thread* self = Thread::Current();
3608 ScopedThreadSuspension sts(self, thread_id);
3609 if (sts.GetError() != JDWP::ERR_NONE) {
3610 return sts.GetError();
3611 }
3612
Sebastien Hertz597c4f02015-01-26 17:37:14 +01003613 // Work out what ArtMethod* we're in, the current line number, and how deep the stack currently
Elliott Hughes2435a572012-02-17 16:07:41 -08003614 // is for step-out.
Ian Rogers0399dde2012-06-06 17:09:28 -07003615 struct SingleStepStackVisitor : public StackVisitor {
Sebastien Hertz597c4f02015-01-26 17:37:14 +01003616 explicit SingleStepStackVisitor(Thread* thread) SHARED_LOCKS_REQUIRED(Locks::mutator_lock_)
Nicolas Geoffray8e5bd182015-05-06 11:34:34 +01003617 : StackVisitor(thread, nullptr, StackVisitor::StackWalkKind::kIncludeInlinedFrames),
3618 stack_depth(0),
3619 method(nullptr),
3620 line_number(-1) {}
Ian Rogersca190662012-06-26 15:45:57 -07003621
Ian Rogers00f7d0e2012-07-19 15:28:27 -07003622 // TODO: Enable annotalysis. We know lock is held in constructor, but abstraction confuses
3623 // annotalysis.
3624 bool VisitFrame() NO_THREAD_SAFETY_ANALYSIS {
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01003625 mirror::ArtMethod* m = GetMethod();
Ian Rogers0399dde2012-06-06 17:09:28 -07003626 if (!m->IsRuntimeMethod()) {
Sebastien Hertz597c4f02015-01-26 17:37:14 +01003627 ++stack_depth;
3628 if (method == nullptr) {
Ian Rogersef7d42f2014-01-06 12:55:46 -08003629 mirror::DexCache* dex_cache = m->GetDeclaringClass()->GetDexCache();
Sebastien Hertz597c4f02015-01-26 17:37:14 +01003630 method = m;
Ian Rogersc0542af2014-09-03 16:16:56 -07003631 if (dex_cache != nullptr) {
Ian Rogers4445a7e2012-10-05 17:19:13 -07003632 const DexFile& dex_file = *dex_cache->GetDexFile();
Sebastien Hertz597c4f02015-01-26 17:37:14 +01003633 line_number = dex_file.GetLineNumFromPC(m, GetDexPc());
Elliott Hughes2435a572012-02-17 16:07:41 -08003634 }
Elliott Hughes86964332012-02-15 19:37:42 -08003635 }
3636 }
Elliott Hughes530fa002012-03-12 11:44:49 -07003637 return true;
Elliott Hughes86964332012-02-15 19:37:42 -08003638 }
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01003639
Sebastien Hertz597c4f02015-01-26 17:37:14 +01003640 int stack_depth;
3641 mirror::ArtMethod* method;
3642 int32_t line_number;
Elliott Hughes86964332012-02-15 19:37:42 -08003643 };
Jeff Hao449db332013-04-12 18:30:52 -07003644
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01003645 Thread* const thread = sts.GetThread();
Sebastien Hertz597c4f02015-01-26 17:37:14 +01003646 SingleStepStackVisitor visitor(thread);
Ian Rogers0399dde2012-06-06 17:09:28 -07003647 visitor.WalkStack();
Elliott Hughes86964332012-02-15 19:37:42 -08003648
Elliott Hughes2435a572012-02-17 16:07:41 -08003649 // Find the dex_pc values that correspond to the current line, for line-based single-stepping.
Elliott Hughes2435a572012-02-17 16:07:41 -08003650 struct DebugCallbackContext {
Sebastien Hertz597c4f02015-01-26 17:37:14 +01003651 explicit DebugCallbackContext(SingleStepControl* single_step_control_cb,
3652 int32_t line_number_cb, const DexFile::CodeItem* code_item)
Andreas Gampe277ccbd2014-11-03 21:36:10 -08003653 : single_step_control_(single_step_control_cb), line_number_(line_number_cb),
3654 code_item_(code_item), last_pc_valid(false), last_pc(0) {
Elliott Hughes2435a572012-02-17 16:07:41 -08003655 }
3656
Andreas Gampe277ccbd2014-11-03 21:36:10 -08003657 static bool Callback(void* raw_context, uint32_t address, uint32_t line_number_cb) {
Elliott Hughes2435a572012-02-17 16:07:41 -08003658 DebugCallbackContext* context = reinterpret_cast<DebugCallbackContext*>(raw_context);
Andreas Gampe277ccbd2014-11-03 21:36:10 -08003659 if (static_cast<int32_t>(line_number_cb) == context->line_number_) {
Elliott Hughes2435a572012-02-17 16:07:41 -08003660 if (!context->last_pc_valid) {
3661 // Everything from this address until the next line change is ours.
3662 context->last_pc = address;
3663 context->last_pc_valid = true;
3664 }
3665 // Otherwise, if we're already in a valid range for this line,
3666 // just keep going (shouldn't really happen)...
Brian Carlstrom7934ac22013-07-26 10:54:15 -07003667 } else if (context->last_pc_valid) { // and the line number is new
Elliott Hughes2435a572012-02-17 16:07:41 -08003668 // Add everything from the last entry up until here to the set
3669 for (uint32_t dex_pc = context->last_pc; dex_pc < address; ++dex_pc) {
Sebastien Hertz597c4f02015-01-26 17:37:14 +01003670 context->single_step_control_->AddDexPc(dex_pc);
Elliott Hughes2435a572012-02-17 16:07:41 -08003671 }
3672 context->last_pc_valid = false;
3673 }
Brian Carlstrom7934ac22013-07-26 10:54:15 -07003674 return false; // There may be multiple entries for any given line.
Elliott Hughes2435a572012-02-17 16:07:41 -08003675 }
3676
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01003677 ~DebugCallbackContext() {
Elliott Hughes2435a572012-02-17 16:07:41 -08003678 // If the line number was the last in the position table...
3679 if (last_pc_valid) {
Sebastien Hertzbb43b432014-04-14 11:59:08 +02003680 size_t end = code_item_->insns_size_in_code_units_;
Elliott Hughes2435a572012-02-17 16:07:41 -08003681 for (uint32_t dex_pc = last_pc; dex_pc < end; ++dex_pc) {
Sebastien Hertz597c4f02015-01-26 17:37:14 +01003682 single_step_control_->AddDexPc(dex_pc);
Elliott Hughes2435a572012-02-17 16:07:41 -08003683 }
3684 }
3685 }
3686
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01003687 SingleStepControl* const single_step_control_;
3688 const int32_t line_number_;
Sebastien Hertzbb43b432014-04-14 11:59:08 +02003689 const DexFile::CodeItem* const code_item_;
Elliott Hughes2435a572012-02-17 16:07:41 -08003690 bool last_pc_valid;
3691 uint32_t last_pc;
3692 };
Sebastien Hertz597c4f02015-01-26 17:37:14 +01003693
3694 // Allocate single step.
Sebastien Hertz1558b572015-02-25 15:05:59 +01003695 SingleStepControl* single_step_control =
3696 new (std::nothrow) SingleStepControl(step_size, step_depth,
3697 visitor.stack_depth, visitor.method);
3698 if (single_step_control == nullptr) {
3699 LOG(ERROR) << "Failed to allocate SingleStepControl";
3700 return JDWP::ERR_OUT_OF_MEMORY;
3701 }
3702
Sebastien Hertz597c4f02015-01-26 17:37:14 +01003703 mirror::ArtMethod* m = single_step_control->GetMethod();
3704 const int32_t line_number = visitor.line_number;
Sebastien Hertz52f5f932015-05-28 11:00:57 +02003705 // Note: if the thread is not running Java code (pure native thread), there is no "current"
3706 // method on the stack (and no line number either).
3707 if (m != nullptr && !m->IsNative()) {
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07003708 const DexFile::CodeItem* const code_item = m->GetCodeItem();
Sebastien Hertzbb43b432014-04-14 11:59:08 +02003709 DebugCallbackContext context(single_step_control, line_number, code_item);
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07003710 m->GetDexFile()->DecodeDebugInfo(code_item, m->IsStatic(), m->GetDexMethodIndex(),
Ian Rogersc0542af2014-09-03 16:16:56 -07003711 DebugCallbackContext::Callback, nullptr, &context);
Elliott Hughes3e2e1a22012-02-21 11:33:41 -08003712 }
Elliott Hughes2435a572012-02-17 16:07:41 -08003713
Sebastien Hertz597c4f02015-01-26 17:37:14 +01003714 // Activate single-step in the thread.
3715 thread->ActivateSingleStepControl(single_step_control);
Elliott Hughes86964332012-02-15 19:37:42 -08003716
Elliott Hughes2435a572012-02-17 16:07:41 -08003717 if (VLOG_IS_ON(jdwp)) {
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01003718 VLOG(jdwp) << "Single-step thread: " << *thread;
Sebastien Hertz597c4f02015-01-26 17:37:14 +01003719 VLOG(jdwp) << "Single-step step size: " << single_step_control->GetStepSize();
3720 VLOG(jdwp) << "Single-step step depth: " << single_step_control->GetStepDepth();
3721 VLOG(jdwp) << "Single-step current method: " << PrettyMethod(single_step_control->GetMethod());
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01003722 VLOG(jdwp) << "Single-step current line: " << line_number;
Sebastien Hertz597c4f02015-01-26 17:37:14 +01003723 VLOG(jdwp) << "Single-step current stack depth: " << single_step_control->GetStackDepth();
Elliott Hughes2435a572012-02-17 16:07:41 -08003724 VLOG(jdwp) << "Single-step dex_pc values:";
Sebastien Hertz597c4f02015-01-26 17:37:14 +01003725 for (uint32_t dex_pc : single_step_control->GetDexPcs()) {
Sebastien Hertzbb43b432014-04-14 11:59:08 +02003726 VLOG(jdwp) << StringPrintf(" %#x", dex_pc);
Elliott Hughes2435a572012-02-17 16:07:41 -08003727 }
3728 }
3729
3730 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07003731}
3732
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01003733void Dbg::UnconfigureStep(JDWP::ObjectId thread_id) {
3734 ScopedObjectAccessUnchecked soa(Thread::Current());
Ian Rogersc0542af2014-09-03 16:16:56 -07003735 JDWP::JdwpError error;
3736 Thread* thread = DecodeThread(soa, thread_id, &error);
Sebastien Hertz87118ed2013-11-26 17:57:18 +01003737 if (error == JDWP::ERR_NONE) {
Sebastien Hertz597c4f02015-01-26 17:37:14 +01003738 thread->DeactivateSingleStepControl();
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01003739 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -07003740}
3741
Elliott Hughes45651fd2012-02-21 15:48:20 -08003742static char JdwpTagToShortyChar(JDWP::JdwpTag tag) {
3743 switch (tag) {
3744 default:
3745 LOG(FATAL) << "unknown JDWP tag: " << PrintableChar(tag);
Ian Rogersfc787ec2014-10-09 21:56:44 -07003746 UNREACHABLE();
Elliott Hughes45651fd2012-02-21 15:48:20 -08003747
3748 // Primitives.
3749 case JDWP::JT_BYTE: return 'B';
3750 case JDWP::JT_CHAR: return 'C';
3751 case JDWP::JT_FLOAT: return 'F';
3752 case JDWP::JT_DOUBLE: return 'D';
3753 case JDWP::JT_INT: return 'I';
3754 case JDWP::JT_LONG: return 'J';
3755 case JDWP::JT_SHORT: return 'S';
3756 case JDWP::JT_VOID: return 'V';
3757 case JDWP::JT_BOOLEAN: return 'Z';
3758
3759 // Reference types.
3760 case JDWP::JT_ARRAY:
3761 case JDWP::JT_OBJECT:
3762 case JDWP::JT_STRING:
3763 case JDWP::JT_THREAD:
3764 case JDWP::JT_THREAD_GROUP:
3765 case JDWP::JT_CLASS_LOADER:
3766 case JDWP::JT_CLASS_OBJECT:
3767 return 'L';
3768 }
3769}
3770
Elliott Hughes88d63092013-01-09 09:55:54 -08003771JDWP::JdwpError Dbg::InvokeMethod(JDWP::ObjectId thread_id, JDWP::ObjectId object_id,
3772 JDWP::RefTypeId class_id, JDWP::MethodId method_id,
Ian Rogers00f7d0e2012-07-19 15:28:27 -07003773 uint32_t arg_count, uint64_t* arg_values,
3774 JDWP::JdwpTag* arg_types, uint32_t options,
3775 JDWP::JdwpTag* pResultTag, uint64_t* pResultValue,
3776 JDWP::ObjectId* pExceptionId) {
Elliott Hughesd07986f2011-12-06 18:27:45 -08003777 ThreadList* thread_list = Runtime::Current()->GetThreadList();
3778
Ian Rogersc0542af2014-09-03 16:16:56 -07003779 Thread* targetThread = nullptr;
Sebastien Hertz1558b572015-02-25 15:05:59 +01003780 std::unique_ptr<DebugInvokeReq> req;
Ian Rogers00f7d0e2012-07-19 15:28:27 -07003781 Thread* self = Thread::Current();
Elliott Hughesd07986f2011-12-06 18:27:45 -08003782 {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07003783 ScopedObjectAccessUnchecked soa(self);
Ian Rogersc0542af2014-09-03 16:16:56 -07003784 JDWP::JdwpError error;
3785 targetThread = DecodeThread(soa, thread_id, &error);
Elliott Hughes221229c2013-01-08 18:17:50 -08003786 if (error != JDWP::ERR_NONE) {
3787 LOG(ERROR) << "InvokeMethod request for invalid thread id " << thread_id;
3788 return error;
Elliott Hughesd07986f2011-12-06 18:27:45 -08003789 }
Sebastien Hertz1558b572015-02-25 15:05:59 +01003790 if (targetThread->GetInvokeReq() != nullptr) {
3791 // Thread is already invoking a method on behalf of the debugger.
3792 LOG(ERROR) << "InvokeMethod request for thread already invoking a method: " << *targetThread;
3793 return JDWP::ERR_ALREADY_INVOKING;
3794 }
3795 if (!targetThread->IsReadyForDebugInvoke()) {
3796 // Thread is not suspended by an event so it cannot invoke a method.
Elliott Hughesd07986f2011-12-06 18:27:45 -08003797 LOG(ERROR) << "InvokeMethod request for thread not stopped by event: " << *targetThread;
3798 return JDWP::ERR_INVALID_THREAD;
3799 }
3800
3801 /*
3802 * We currently have a bug where we don't successfully resume the
3803 * target thread if the suspend count is too deep. We're expected to
3804 * require one "resume" for each "suspend", but when asked to execute
3805 * a method we have to resume fully and then re-suspend it back to the
3806 * same level. (The easiest way to cause this is to type "suspend"
3807 * multiple times in jdb.)
3808 *
3809 * It's unclear what this means when the event specifies "resume all"
3810 * and some threads are suspended more deeply than others. This is
3811 * a rare problem, so for now we just prevent it from hanging forever
3812 * by rejecting the method invocation request. Without this, we will
3813 * be stuck waiting on a suspended thread.
3814 */
Ian Rogers00f7d0e2012-07-19 15:28:27 -07003815 int suspend_count;
3816 {
Ian Rogers50b35e22012-10-04 10:09:15 -07003817 MutexLock mu2(soa.Self(), *Locks::thread_suspend_count_lock_);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07003818 suspend_count = targetThread->GetSuspendCount();
3819 }
Elliott Hughesd07986f2011-12-06 18:27:45 -08003820 if (suspend_count > 1) {
3821 LOG(ERROR) << *targetThread << " suspend count too deep for method invocation: " << suspend_count;
Brian Carlstrom7934ac22013-07-26 10:54:15 -07003822 return JDWP::ERR_THREAD_SUSPENDED; // Probably not expected here.
Elliott Hughesd07986f2011-12-06 18:27:45 -08003823 }
3824
Ian Rogersc0542af2014-09-03 16:16:56 -07003825 mirror::Object* receiver = gRegistry->Get<mirror::Object*>(object_id, &error);
3826 if (error != JDWP::ERR_NONE) {
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08003827 return JDWP::ERR_INVALID_OBJECT;
3828 }
Elliott Hughes45651fd2012-02-21 15:48:20 -08003829
Sebastien Hertz1558b572015-02-25 15:05:59 +01003830 gRegistry->Get<mirror::Object*>(thread_id, &error);
Ian Rogersc0542af2014-09-03 16:16:56 -07003831 if (error != JDWP::ERR_NONE) {
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08003832 return JDWP::ERR_INVALID_OBJECT;
3833 }
Elliott Hughes45651fd2012-02-21 15:48:20 -08003834
Ian Rogersc0542af2014-09-03 16:16:56 -07003835 mirror::Class* c = DecodeClass(class_id, &error);
3836 if (c == nullptr) {
3837 return error;
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08003838 }
Elliott Hughes45651fd2012-02-21 15:48:20 -08003839
Brian Carlstromea46f952013-07-30 01:26:50 -07003840 mirror::ArtMethod* m = FromMethodId(method_id);
Ian Rogersc0542af2014-09-03 16:16:56 -07003841 if (m->IsStatic() != (receiver == nullptr)) {
Elliott Hughes45651fd2012-02-21 15:48:20 -08003842 return JDWP::ERR_INVALID_METHODID;
3843 }
3844 if (m->IsStatic()) {
3845 if (m->GetDeclaringClass() != c) {
3846 return JDWP::ERR_INVALID_METHODID;
3847 }
3848 } else {
3849 if (!m->GetDeclaringClass()->IsAssignableFrom(c)) {
3850 return JDWP::ERR_INVALID_METHODID;
3851 }
3852 }
3853
3854 // Check the argument list matches the method.
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07003855 uint32_t shorty_len = 0;
3856 const char* shorty = m->GetShorty(&shorty_len);
3857 if (shorty_len - 1 != arg_count) {
Elliott Hughes45651fd2012-02-21 15:48:20 -08003858 return JDWP::ERR_ILLEGAL_ARGUMENT;
3859 }
Elliott Hughes09201632013-04-15 15:50:07 -07003860
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07003861 {
3862 StackHandleScope<3> hs(soa.Self());
Ian Rogersa0485602014-12-02 15:48:04 -08003863 HandleWrapper<mirror::ArtMethod> h_m(hs.NewHandleWrapper(&m));
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07003864 HandleWrapper<mirror::Object> h_obj(hs.NewHandleWrapper(&receiver));
3865 HandleWrapper<mirror::Class> h_klass(hs.NewHandleWrapper(&c));
3866 const DexFile::TypeList* types = m->GetParameterTypeList();
3867 for (size_t i = 0; i < arg_count; ++i) {
3868 if (shorty[i + 1] != JdwpTagToShortyChar(arg_types[i])) {
Elliott Hughes09201632013-04-15 15:50:07 -07003869 return JDWP::ERR_ILLEGAL_ARGUMENT;
3870 }
3871
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07003872 if (shorty[i + 1] == 'L') {
3873 // Did we really get an argument of an appropriate reference type?
Ian Rogersa0485602014-12-02 15:48:04 -08003874 mirror::Class* parameter_type =
3875 h_m->GetClassFromTypeIndex(types->GetTypeItem(i).type_idx_, true);
Ian Rogersc0542af2014-09-03 16:16:56 -07003876 mirror::Object* argument = gRegistry->Get<mirror::Object*>(arg_values[i], &error);
3877 if (error != JDWP::ERR_NONE) {
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07003878 return JDWP::ERR_INVALID_OBJECT;
3879 }
Ian Rogersc0542af2014-09-03 16:16:56 -07003880 if (argument != nullptr && !argument->InstanceOf(parameter_type)) {
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07003881 return JDWP::ERR_ILLEGAL_ARGUMENT;
3882 }
3883
3884 // Turn the on-the-wire ObjectId into a jobject.
3885 jvalue& v = reinterpret_cast<jvalue&>(arg_values[i]);
3886 v.l = gRegistry->GetJObject(arg_values[i]);
3887 }
Elliott Hughes09201632013-04-15 15:50:07 -07003888 }
Elliott Hughes45651fd2012-02-21 15:48:20 -08003889 }
3890
Sebastien Hertz1558b572015-02-25 15:05:59 +01003891 // Allocates a DebugInvokeReq.
3892 req.reset(new (std::nothrow) DebugInvokeReq(receiver, c, m, options, arg_values, arg_count));
3893 if (req.get() == nullptr) {
3894 LOG(ERROR) << "Failed to allocate DebugInvokeReq";
3895 return JDWP::ERR_OUT_OF_MEMORY;
3896 }
3897
3898 // Attach the DebugInvokeReq to the target thread so it executes the method when
3899 // it is resumed. Once the invocation completes, it will detach it and signal us
3900 // before suspending itself.
3901 targetThread->SetDebugInvokeReq(req.get());
Elliott Hughesd07986f2011-12-06 18:27:45 -08003902 }
3903
3904 // The fact that we've released the thread list lock is a bit risky --- if the thread goes
3905 // away we're sitting high and dry -- but we must release this before the ResumeAllThreads
3906 // call, and it's unwise to hold it during WaitForSuspend.
3907
3908 {
3909 /*
3910 * We change our (JDWP thread) status, which should be THREAD_RUNNING,
Elliott Hughes81ff3182012-03-23 20:35:56 -07003911 * so we can suspend for a GC if the invoke request causes us to
Elliott Hughesd07986f2011-12-06 18:27:45 -08003912 * run out of memory. It's also a good idea to change it before locking
3913 * the invokeReq mutex, although that should never be held for long.
3914 */
Ian Rogers00f7d0e2012-07-19 15:28:27 -07003915 self->TransitionFromRunnableToSuspended(kWaitingForDebuggerSend);
Elliott Hughesd07986f2011-12-06 18:27:45 -08003916
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08003917 VLOG(jdwp) << " Transferring control to event thread";
Elliott Hughesd07986f2011-12-06 18:27:45 -08003918 {
Sebastien Hertzd38667a2013-11-25 15:43:54 +01003919 MutexLock mu(self, req->lock);
Elliott Hughesd07986f2011-12-06 18:27:45 -08003920
3921 if ((options & JDWP::INVOKE_SINGLE_THREADED) == 0) {
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08003922 VLOG(jdwp) << " Resuming all threads";
Ian Rogers00f7d0e2012-07-19 15:28:27 -07003923 thread_list->UndoDebuggerSuspensions();
Elliott Hughesd07986f2011-12-06 18:27:45 -08003924 } else {
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08003925 VLOG(jdwp) << " Resuming event thread only";
Elliott Hughesd07986f2011-12-06 18:27:45 -08003926 thread_list->Resume(targetThread, true);
3927 }
3928
Sebastien Hertz2bf93f42015-01-09 18:44:05 +01003929 // The target thread is resumed but needs the JDWP token we're holding.
3930 // We release it now and will acquire it again when the invocation is
3931 // complete and the target thread suspends itself.
3932 gJdwpState->ReleaseJdwpTokenForCommand();
3933
Elliott Hughesd07986f2011-12-06 18:27:45 -08003934 // Wait for the request to finish executing.
Sebastien Hertz1558b572015-02-25 15:05:59 +01003935 while (targetThread->GetInvokeReq() != nullptr) {
Sebastien Hertzd38667a2013-11-25 15:43:54 +01003936 req->cond.Wait(self);
Elliott Hughesd07986f2011-12-06 18:27:45 -08003937 }
3938 }
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08003939 VLOG(jdwp) << " Control has returned from event thread";
Elliott Hughesd07986f2011-12-06 18:27:45 -08003940
3941 /* wait for thread to re-suspend itself */
Brian Carlstromdf629502013-07-17 22:39:56 -07003942 SuspendThread(thread_id, false /* request_suspension */);
Sebastien Hertz2bf93f42015-01-09 18:44:05 +01003943
3944 // Now the thread is suspended again, we can re-acquire the JDWP token.
3945 gJdwpState->AcquireJdwpTokenForCommand();
3946
Ian Rogers00f7d0e2012-07-19 15:28:27 -07003947 self->TransitionFromSuspendedToRunnable();
Elliott Hughesd07986f2011-12-06 18:27:45 -08003948 }
3949
3950 /*
3951 * Suspend the threads. We waited for the target thread to suspend
3952 * itself, so all we need to do is suspend the others.
3953 *
Sebastien Hertz2bf93f42015-01-09 18:44:05 +01003954 * The SuspendAllForDebugger() call will double-suspend the event thread,
Elliott Hughesd07986f2011-12-06 18:27:45 -08003955 * so we want to resume the target thread once to keep the books straight.
3956 */
3957 if ((options & JDWP::INVOKE_SINGLE_THREADED) == 0) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07003958 self->TransitionFromRunnableToSuspended(kWaitingForDebuggerSuspension);
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08003959 VLOG(jdwp) << " Suspending all threads";
Ian Rogers00f7d0e2012-07-19 15:28:27 -07003960 thread_list->SuspendAllForDebugger();
3961 self->TransitionFromSuspendedToRunnable();
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08003962 VLOG(jdwp) << " Resuming event thread to balance the count";
Elliott Hughesd07986f2011-12-06 18:27:45 -08003963 thread_list->Resume(targetThread, true);
3964 }
3965
3966 // Copy the result.
3967 *pResultTag = req->result_tag;
Sebastien Hertz1558b572015-02-25 15:05:59 +01003968 *pResultValue = req->result_value;
Elliott Hughesd07986f2011-12-06 18:27:45 -08003969 *pExceptionId = req->exception;
3970 return req->error;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07003971}
3972
3973void Dbg::ExecuteMethod(DebugInvokeReq* pReq) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07003974 ScopedObjectAccess soa(Thread::Current());
Elliott Hughesd07986f2011-12-06 18:27:45 -08003975
Elliott Hughes81ff3182012-03-23 20:35:56 -07003976 // We can be called while an exception is pending. We need
Elliott Hughesd07986f2011-12-06 18:27:45 -08003977 // to preserve that across the method invocation.
Sebastien Hertz1558b572015-02-25 15:05:59 +01003978 StackHandleScope<4> hs(soa.Self());
3979 auto old_exception = hs.NewHandle<mirror::Throwable>(soa.Self()->GetException());
3980 soa.Self()->ClearException();
Elliott Hughesd07986f2011-12-06 18:27:45 -08003981
3982 // Translate the method through the vtable, unless the debugger wants to suppress it.
Sebastien Hertz1558b572015-02-25 15:05:59 +01003983 MutableHandle<mirror::ArtMethod> m(hs.NewHandle(pReq->method.Read()));
3984 if ((pReq->options & JDWP::INVOKE_NONVIRTUAL) == 0 && pReq->receiver.Read() != nullptr) {
3985 mirror::ArtMethod* actual_method = pReq->klass.Read()->FindVirtualMethodForVirtualOrInterface(m.Get());
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003986 if (actual_method != m.Get()) {
Sebastien Hertz1558b572015-02-25 15:05:59 +01003987 VLOG(jdwp) << "ExecuteMethod translated " << PrettyMethod(m.Get())
3988 << " to " << PrettyMethod(actual_method);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003989 m.Assign(actual_method);
Elliott Hughes45651fd2012-02-21 15:48:20 -08003990 }
Elliott Hughesd07986f2011-12-06 18:27:45 -08003991 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003992 VLOG(jdwp) << "ExecuteMethod " << PrettyMethod(m.Get())
Sebastien Hertz1558b572015-02-25 15:05:59 +01003993 << " receiver=" << pReq->receiver.Read()
Sebastien Hertzd38667a2013-11-25 15:43:54 +01003994 << " arg_count=" << pReq->arg_count;
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003995 CHECK(m.Get() != nullptr);
Elliott Hughesd07986f2011-12-06 18:27:45 -08003996
3997 CHECK_EQ(sizeof(jvalue), sizeof(uint64_t));
3998
Jeff Hao39b6c242015-05-19 20:30:23 -07003999 ScopedLocalRef<jobject> ref(soa.Env(), soa.AddLocalReference<jobject>(pReq->receiver.Read()));
4000 JValue result = InvokeWithJValues(soa, ref.get(), soa.EncodeMethod(m.Get()),
Sebastien Hertz1558b572015-02-25 15:05:59 +01004001 reinterpret_cast<jvalue*>(pReq->arg_values));
Elliott Hughesd07986f2011-12-06 18:27:45 -08004002
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07004003 pReq->result_tag = BasicTagFromDescriptor(m.Get()->GetShorty());
Sebastien Hertz1558b572015-02-25 15:05:59 +01004004 const bool is_object_result = (pReq->result_tag == JDWP::JT_OBJECT);
4005 Handle<mirror::Object> object_result = hs.NewHandle(is_object_result ? result.GetL() : nullptr);
4006 Handle<mirror::Throwable> exception = hs.NewHandle(soa.Self()->GetException());
4007 soa.Self()->ClearException();
Sebastien Hertz261bc042015-04-08 09:36:07 +02004008 pReq->exception = gRegistry->Add(exception);
Elliott Hughesd07986f2011-12-06 18:27:45 -08004009 if (pReq->exception != 0) {
Sebastien Hertz1558b572015-02-25 15:05:59 +01004010 VLOG(jdwp) << " JDWP invocation returning with exception=" << exception.Get()
4011 << " " << exception->Dump();
4012 pReq->result_value = 0;
4013 } else if (is_object_result) {
Elliott Hughesd07986f2011-12-06 18:27:45 -08004014 /* if no exception thrown, examine object result more closely */
Sebastien Hertz1558b572015-02-25 15:05:59 +01004015 JDWP::JdwpTag new_tag = TagFromObject(soa, object_result.Get());
Elliott Hughesd07986f2011-12-06 18:27:45 -08004016 if (new_tag != pReq->result_tag) {
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08004017 VLOG(jdwp) << " JDWP promoted result from " << pReq->result_tag << " to " << new_tag;
Elliott Hughesd07986f2011-12-06 18:27:45 -08004018 pReq->result_tag = new_tag;
4019 }
4020
Sebastien Hertz1558b572015-02-25 15:05:59 +01004021 // Register the object in the registry and reference its ObjectId. This ensures
4022 // GC safety and prevents from accessing stale reference if the object is moved.
4023 pReq->result_value = gRegistry->Add(object_result.Get());
4024 } else {
4025 // Primitive result.
4026 DCHECK(IsPrimitiveTag(pReq->result_tag));
4027 pReq->result_value = result.GetJ();
Elliott Hughesd07986f2011-12-06 18:27:45 -08004028 }
4029
Ian Rogersc0542af2014-09-03 16:16:56 -07004030 if (old_exception.Get() != nullptr) {
Nicolas Geoffray14691c52015-03-05 10:40:17 +00004031 soa.Self()->SetException(old_exception.Get());
Elliott Hughesd07986f2011-12-06 18:27:45 -08004032 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -07004033}
4034
Elliott Hughesd07986f2011-12-06 18:27:45 -08004035/*
Elliott Hughes4b9702c2013-02-20 18:13:24 -08004036 * "request" contains a full JDWP packet, possibly with multiple chunks. We
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07004037 * need to process each, accumulate the replies, and ship the whole thing
4038 * back.
4039 *
4040 * Returns "true" if we have a reply. The reply buffer is newly allocated,
4041 * and includes the chunk type/length, followed by the data.
4042 *
Elliott Hughes3d30d9b2011-12-07 17:35:48 -08004043 * OLD-TODO: we currently assume that the request and reply include a single
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07004044 * chunk. If this becomes inconvenient we will need to adapt.
4045 */
Ian Rogersc0542af2014-09-03 16:16:56 -07004046bool Dbg::DdmHandlePacket(JDWP::Request* request, uint8_t** pReplyBuf, int* pReplyLen) {
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07004047 Thread* self = Thread::Current();
4048 JNIEnv* env = self->GetJniEnv();
4049
Ian Rogersc0542af2014-09-03 16:16:56 -07004050 uint32_t type = request->ReadUnsigned32("type");
4051 uint32_t length = request->ReadUnsigned32("length");
Elliott Hughes4b9702c2013-02-20 18:13:24 -08004052
4053 // Create a byte[] corresponding to 'request'.
Ian Rogersc0542af2014-09-03 16:16:56 -07004054 size_t request_length = request->size();
Elliott Hughes4b9702c2013-02-20 18:13:24 -08004055 ScopedLocalRef<jbyteArray> dataArray(env, env->NewByteArray(request_length));
Ian Rogersc0542af2014-09-03 16:16:56 -07004056 if (dataArray.get() == nullptr) {
Elliott Hughes4b9702c2013-02-20 18:13:24 -08004057 LOG(WARNING) << "byte[] allocation failed: " << request_length;
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07004058 env->ExceptionClear();
4059 return false;
4060 }
Ian Rogersc0542af2014-09-03 16:16:56 -07004061 env->SetByteArrayRegion(dataArray.get(), 0, request_length,
4062 reinterpret_cast<const jbyte*>(request->data()));
4063 request->Skip(request_length);
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07004064
4065 // Run through and find all chunks. [Currently just find the first.]
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004066 ScopedByteArrayRO contents(env, dataArray.get());
Elliott Hughes4b9702c2013-02-20 18:13:24 -08004067 if (length != request_length) {
Ian Rogersef7d42f2014-01-06 12:55:46 -08004068 LOG(WARNING) << StringPrintf("bad chunk found (len=%u pktLen=%zd)", length, request_length);
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07004069 return false;
4070 }
4071
4072 // Call "private static Chunk dispatch(int type, byte[] data, int offset, int length)".
Elliott Hugheseac76672012-05-24 21:56:51 -07004073 ScopedLocalRef<jobject> chunk(env, env->CallStaticObjectMethod(WellKnownClasses::org_apache_harmony_dalvik_ddmc_DdmServer,
4074 WellKnownClasses::org_apache_harmony_dalvik_ddmc_DdmServer_dispatch,
Elliott Hughes4b9702c2013-02-20 18:13:24 -08004075 type, dataArray.get(), 0, length));
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07004076 if (env->ExceptionCheck()) {
4077 LOG(INFO) << StringPrintf("Exception thrown by dispatcher for 0x%08x", type);
4078 env->ExceptionDescribe();
4079 env->ExceptionClear();
4080 return false;
4081 }
4082
Ian Rogersc0542af2014-09-03 16:16:56 -07004083 if (chunk.get() == nullptr) {
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07004084 return false;
4085 }
4086
4087 /*
4088 * Pull the pieces out of the chunk. We copy the results into a
4089 * newly-allocated buffer that the caller can free. We don't want to
4090 * continue using the Chunk object because nothing has a reference to it.
4091 *
4092 * We could avoid this by returning type/data/offset/length and having
4093 * the caller be aware of the object lifetime issues, but that
Elliott Hughes81ff3182012-03-23 20:35:56 -07004094 * integrates the JDWP code more tightly into the rest of the runtime, and doesn't work
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07004095 * if we have responses for multiple chunks.
4096 *
4097 * So we're pretty much stuck with copying data around multiple times.
4098 */
Elliott Hugheseac76672012-05-24 21:56:51 -07004099 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 -08004100 jint offset = env->GetIntField(chunk.get(), WellKnownClasses::org_apache_harmony_dalvik_ddmc_Chunk_offset);
Elliott Hugheseac76672012-05-24 21:56:51 -07004101 length = env->GetIntField(chunk.get(), WellKnownClasses::org_apache_harmony_dalvik_ddmc_Chunk_length);
Elliott Hugheseac76672012-05-24 21:56:51 -07004102 type = env->GetIntField(chunk.get(), WellKnownClasses::org_apache_harmony_dalvik_ddmc_Chunk_type);
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07004103
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08004104 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 -07004105 if (length == 0 || replyData.get() == nullptr) {
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07004106 return false;
4107 }
4108
Elliott Hughes4b9702c2013-02-20 18:13:24 -08004109 const int kChunkHdrLen = 8;
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07004110 uint8_t* reply = new uint8_t[length + kChunkHdrLen];
Ian Rogersc0542af2014-09-03 16:16:56 -07004111 if (reply == nullptr) {
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07004112 LOG(WARNING) << "malloc failed: " << (length + kChunkHdrLen);
4113 return false;
4114 }
Elliott Hughesf7c3b662011-10-27 12:04:56 -07004115 JDWP::Set4BE(reply + 0, type);
4116 JDWP::Set4BE(reply + 4, length);
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004117 env->GetByteArrayRegion(replyData.get(), offset, length, reinterpret_cast<jbyte*>(reply + kChunkHdrLen));
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07004118
4119 *pReplyBuf = reply;
4120 *pReplyLen = length + kChunkHdrLen;
4121
Elliott Hughes4b9702c2013-02-20 18:13:24 -08004122 VLOG(jdwp) << StringPrintf("dvmHandleDdm returning type=%.4s %p len=%d", reinterpret_cast<char*>(reply), reply, length);
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07004123 return true;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07004124}
4125
Elliott Hughesa2155262011-11-16 16:26:58 -08004126void Dbg::DdmBroadcast(bool connect) {
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08004127 VLOG(jdwp) << "Broadcasting DDM " << (connect ? "connect" : "disconnect") << "...";
Elliott Hughes47fce012011-10-25 18:37:19 -07004128
4129 Thread* self = Thread::Current();
Ian Rogers50b35e22012-10-04 10:09:15 -07004130 if (self->GetState() != kRunnable) {
4131 LOG(ERROR) << "DDM broadcast in thread state " << self->GetState();
4132 /* try anyway? */
Elliott Hughes47fce012011-10-25 18:37:19 -07004133 }
4134
4135 JNIEnv* env = self->GetJniEnv();
Elliott Hughes47fce012011-10-25 18:37:19 -07004136 jint event = connect ? 1 /*DdmServer.CONNECTED*/ : 2 /*DdmServer.DISCONNECTED*/;
Elliott Hugheseac76672012-05-24 21:56:51 -07004137 env->CallStaticVoidMethod(WellKnownClasses::org_apache_harmony_dalvik_ddmc_DdmServer,
4138 WellKnownClasses::org_apache_harmony_dalvik_ddmc_DdmServer_broadcast,
4139 event);
Elliott Hughes47fce012011-10-25 18:37:19 -07004140 if (env->ExceptionCheck()) {
4141 LOG(ERROR) << "DdmServer.broadcast " << event << " failed";
4142 env->ExceptionDescribe();
4143 env->ExceptionClear();
4144 }
4145}
4146
Elliott Hughes872d4ec2011-10-21 17:07:15 -07004147void Dbg::DdmConnected() {
Elliott Hughesa2155262011-11-16 16:26:58 -08004148 Dbg::DdmBroadcast(true);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07004149}
4150
4151void Dbg::DdmDisconnected() {
Elliott Hughesa2155262011-11-16 16:26:58 -08004152 Dbg::DdmBroadcast(false);
Elliott Hughes47fce012011-10-25 18:37:19 -07004153 gDdmThreadNotification = false;
4154}
4155
4156/*
Elliott Hughes82188472011-11-07 18:11:48 -08004157 * Send a notification when a thread starts, stops, or changes its name.
Elliott Hughes47fce012011-10-25 18:37:19 -07004158 *
4159 * Because we broadcast the full set of threads when the notifications are
4160 * first enabled, it's possible for "thread" to be actively executing.
4161 */
Elliott Hughes82188472011-11-07 18:11:48 -08004162void Dbg::DdmSendThreadNotification(Thread* t, uint32_t type) {
Elliott Hughes47fce012011-10-25 18:37:19 -07004163 if (!gDdmThreadNotification) {
4164 return;
4165 }
4166
Elliott Hughes82188472011-11-07 18:11:48 -08004167 if (type == CHUNK_TYPE("THDE")) {
Elliott Hughes47fce012011-10-25 18:37:19 -07004168 uint8_t buf[4];
Ian Rogersd9c4fc92013-10-01 19:45:43 -07004169 JDWP::Set4BE(&buf[0], t->GetThreadId());
Elliott Hughes47fce012011-10-25 18:37:19 -07004170 Dbg::DdmSendChunk(CHUNK_TYPE("THDE"), 4, buf);
Elliott Hughes82188472011-11-07 18:11:48 -08004171 } else {
4172 CHECK(type == CHUNK_TYPE("THCR") || type == CHUNK_TYPE("THNM")) << type;
Ian Rogers00f7d0e2012-07-19 15:28:27 -07004173 ScopedObjectAccessUnchecked soa(Thread::Current());
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004174 StackHandleScope<1> hs(soa.Self());
4175 Handle<mirror::String> name(hs.NewHandle(t->GetThreadName(soa)));
Ian Rogersc0542af2014-09-03 16:16:56 -07004176 size_t char_count = (name.Get() != nullptr) ? name->GetLength() : 0;
Jeff Hao848f70a2014-01-15 13:49:50 -08004177 const jchar* chars = (name.Get() != nullptr) ? name->GetValue() : nullptr;
Elliott Hughes82188472011-11-07 18:11:48 -08004178
Elliott Hughes21f32d72011-11-09 17:44:13 -08004179 std::vector<uint8_t> bytes;
Ian Rogersd9c4fc92013-10-01 19:45:43 -07004180 JDWP::Append4BE(bytes, t->GetThreadId());
Elliott Hughes545a0642011-11-08 19:10:03 -08004181 JDWP::AppendUtf16BE(bytes, chars, char_count);
Elliott Hughes21f32d72011-11-09 17:44:13 -08004182 CHECK_EQ(bytes.size(), char_count*2 + sizeof(uint32_t)*2);
4183 Dbg::DdmSendChunk(type, bytes);
Elliott Hughes47fce012011-10-25 18:37:19 -07004184 }
4185}
4186
Elliott Hughes47fce012011-10-25 18:37:19 -07004187void Dbg::DdmSetThreadNotification(bool enable) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07004188 // Enable/disable thread notifications.
Elliott Hughes47fce012011-10-25 18:37:19 -07004189 gDdmThreadNotification = enable;
4190 if (enable) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07004191 // Suspend the VM then post thread start notifications for all threads. Threads attaching will
4192 // see a suspension in progress and block until that ends. They then post their own start
4193 // notification.
4194 SuspendVM();
4195 std::list<Thread*> threads;
Ian Rogers50b35e22012-10-04 10:09:15 -07004196 Thread* self = Thread::Current();
Ian Rogers00f7d0e2012-07-19 15:28:27 -07004197 {
Ian Rogers50b35e22012-10-04 10:09:15 -07004198 MutexLock mu(self, *Locks::thread_list_lock_);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07004199 threads = Runtime::Current()->GetThreadList()->GetList();
4200 }
4201 {
Ian Rogers50b35e22012-10-04 10:09:15 -07004202 ScopedObjectAccess soa(self);
Mathieu Chartier02e25112013-08-14 16:14:24 -07004203 for (Thread* thread : threads) {
4204 Dbg::DdmSendThreadNotification(thread, CHUNK_TYPE("THCR"));
Ian Rogers00f7d0e2012-07-19 15:28:27 -07004205 }
4206 }
4207 ResumeVM();
Elliott Hughes47fce012011-10-25 18:37:19 -07004208 }
4209}
4210
Elliott Hughesa2155262011-11-16 16:26:58 -08004211void Dbg::PostThreadStartOrStop(Thread* t, uint32_t type) {
Elliott Hughesc0f09332012-03-26 13:27:06 -07004212 if (IsDebuggerActive()) {
Sebastien Hertz6995c602014-09-09 12:10:13 +02004213 gJdwpState->PostThreadChange(t, type == CHUNK_TYPE("THCR"));
Elliott Hughes47fce012011-10-25 18:37:19 -07004214 }
Elliott Hughes82188472011-11-07 18:11:48 -08004215 Dbg::DdmSendThreadNotification(t, type);
Elliott Hughes47fce012011-10-25 18:37:19 -07004216}
4217
4218void Dbg::PostThreadStart(Thread* t) {
Elliott Hughesa2155262011-11-16 16:26:58 -08004219 Dbg::PostThreadStartOrStop(t, CHUNK_TYPE("THCR"));
Elliott Hughes47fce012011-10-25 18:37:19 -07004220}
4221
4222void Dbg::PostThreadDeath(Thread* t) {
Elliott Hughesa2155262011-11-16 16:26:58 -08004223 Dbg::PostThreadStartOrStop(t, CHUNK_TYPE("THDE"));
Elliott Hughes872d4ec2011-10-21 17:07:15 -07004224}
4225
Elliott Hughes82188472011-11-07 18:11:48 -08004226void Dbg::DdmSendChunk(uint32_t type, size_t byte_count, const uint8_t* buf) {
Ian Rogersc0542af2014-09-03 16:16:56 -07004227 CHECK(buf != nullptr);
Elliott Hughes3bb81562011-10-21 18:52:59 -07004228 iovec vec[1];
4229 vec[0].iov_base = reinterpret_cast<void*>(const_cast<uint8_t*>(buf));
4230 vec[0].iov_len = byte_count;
4231 Dbg::DdmSendChunkV(type, vec, 1);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07004232}
4233
Elliott Hughes21f32d72011-11-09 17:44:13 -08004234void Dbg::DdmSendChunk(uint32_t type, const std::vector<uint8_t>& bytes) {
4235 DdmSendChunk(type, bytes.size(), &bytes[0]);
4236}
4237
Brian Carlstromf5293522013-07-19 00:24:00 -07004238void Dbg::DdmSendChunkV(uint32_t type, const iovec* iov, int iov_count) {
Ian Rogersc0542af2014-09-03 16:16:56 -07004239 if (gJdwpState == nullptr) {
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08004240 VLOG(jdwp) << "Debugger thread not active, ignoring DDM send: " << type;
Elliott Hughes3bb81562011-10-21 18:52:59 -07004241 } else {
Elliott Hughescccd84f2011-12-05 16:51:54 -08004242 gJdwpState->DdmSendChunkV(type, iov, iov_count);
Elliott Hughes3bb81562011-10-21 18:52:59 -07004243 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -07004244}
4245
Mathieu Chartierad466ad2015-01-08 16:28:08 -08004246JDWP::JdwpState* Dbg::GetJdwpState() {
4247 return gJdwpState;
4248}
4249
Elliott Hughes767a1472011-10-26 18:49:02 -07004250int Dbg::DdmHandleHpifChunk(HpifWhen when) {
4251 if (when == HPIF_WHEN_NOW) {
Elliott Hughes7162ad92011-10-27 14:08:42 -07004252 DdmSendHeapInfo(when);
Elliott Hughes767a1472011-10-26 18:49:02 -07004253 return true;
4254 }
4255
4256 if (when != HPIF_WHEN_NEVER && when != HPIF_WHEN_NEXT_GC && when != HPIF_WHEN_EVERY_GC) {
4257 LOG(ERROR) << "invalid HpifWhen value: " << static_cast<int>(when);
4258 return false;
4259 }
4260
4261 gDdmHpifWhen = when;
4262 return true;
4263}
4264
4265bool Dbg::DdmHandleHpsgNhsgChunk(Dbg::HpsgWhen when, Dbg::HpsgWhat what, bool native) {
4266 if (when != HPSG_WHEN_NEVER && when != HPSG_WHEN_EVERY_GC) {
4267 LOG(ERROR) << "invalid HpsgWhen value: " << static_cast<int>(when);
4268 return false;
4269 }
4270
4271 if (what != HPSG_WHAT_MERGED_OBJECTS && what != HPSG_WHAT_DISTINCT_OBJECTS) {
4272 LOG(ERROR) << "invalid HpsgWhat value: " << static_cast<int>(what);
4273 return false;
4274 }
4275
4276 if (native) {
4277 gDdmNhsgWhen = when;
4278 gDdmNhsgWhat = what;
4279 } else {
4280 gDdmHpsgWhen = when;
4281 gDdmHpsgWhat = what;
4282 }
4283 return true;
4284}
4285
Elliott Hughes7162ad92011-10-27 14:08:42 -07004286void Dbg::DdmSendHeapInfo(HpifWhen reason) {
4287 // If there's a one-shot 'when', reset it.
4288 if (reason == gDdmHpifWhen) {
4289 if (gDdmHpifWhen == HPIF_WHEN_NEXT_GC) {
4290 gDdmHpifWhen = HPIF_WHEN_NEVER;
4291 }
4292 }
4293
4294 /*
4295 * Chunk HPIF (client --> server)
4296 *
4297 * Heap Info. General information about the heap,
4298 * suitable for a summary display.
4299 *
4300 * [u4]: number of heaps
4301 *
4302 * For each heap:
4303 * [u4]: heap ID
4304 * [u8]: timestamp in ms since Unix epoch
4305 * [u1]: capture reason (same as 'when' value from server)
4306 * [u4]: max heap size in bytes (-Xmx)
4307 * [u4]: current heap size in bytes
4308 * [u4]: current number of bytes allocated
4309 * [u4]: current number of objects allocated
4310 */
4311 uint8_t heap_count = 1;
Ian Rogers1d54e732013-05-02 21:10:01 -07004312 gc::Heap* heap = Runtime::Current()->GetHeap();
Elliott Hughes21f32d72011-11-09 17:44:13 -08004313 std::vector<uint8_t> bytes;
Elliott Hughes545a0642011-11-08 19:10:03 -08004314 JDWP::Append4BE(bytes, heap_count);
Brian Carlstrom7934ac22013-07-26 10:54:15 -07004315 JDWP::Append4BE(bytes, 1); // Heap id (bogus; we only have one heap).
Elliott Hughes545a0642011-11-08 19:10:03 -08004316 JDWP::Append8BE(bytes, MilliTime());
4317 JDWP::Append1BE(bytes, reason);
Brian Carlstrom7934ac22013-07-26 10:54:15 -07004318 JDWP::Append4BE(bytes, heap->GetMaxMemory()); // Max allowed heap size in bytes.
4319 JDWP::Append4BE(bytes, heap->GetTotalMemory()); // Current heap size in bytes.
Elliott Hughesb3bd5f02012-03-08 21:05:27 -08004320 JDWP::Append4BE(bytes, heap->GetBytesAllocated());
4321 JDWP::Append4BE(bytes, heap->GetObjectsAllocated());
Elliott Hughes21f32d72011-11-09 17:44:13 -08004322 CHECK_EQ(bytes.size(), 4U + (heap_count * (4 + 8 + 1 + 4 + 4 + 4 + 4)));
4323 Dbg::DdmSendChunk(CHUNK_TYPE("HPIF"), bytes);
Elliott Hughes767a1472011-10-26 18:49:02 -07004324}
4325
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004326enum HpsgSolidity {
4327 SOLIDITY_FREE = 0,
4328 SOLIDITY_HARD = 1,
4329 SOLIDITY_SOFT = 2,
4330 SOLIDITY_WEAK = 3,
4331 SOLIDITY_PHANTOM = 4,
4332 SOLIDITY_FINALIZABLE = 5,
4333 SOLIDITY_SWEEP = 6,
4334};
4335
4336enum HpsgKind {
4337 KIND_OBJECT = 0,
4338 KIND_CLASS_OBJECT = 1,
4339 KIND_ARRAY_1 = 2,
4340 KIND_ARRAY_2 = 3,
4341 KIND_ARRAY_4 = 4,
4342 KIND_ARRAY_8 = 5,
4343 KIND_UNKNOWN = 6,
4344 KIND_NATIVE = 7,
4345};
4346
4347#define HPSG_PARTIAL (1<<7)
4348#define HPSG_STATE(solidity, kind) ((uint8_t)((((kind) & 0x7) << 3) | ((solidity) & 0x7)))
4349
Ian Rogers30fab402012-01-23 15:43:46 -08004350class HeapChunkContext {
4351 public:
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004352 // Maximum chunk size. Obtain this from the formula:
4353 // (((maximum_heap_size / ALLOCATION_UNIT_SIZE) + 255) / 256) * 2
4354 HeapChunkContext(bool merge, bool native)
Ian Rogers30fab402012-01-23 15:43:46 -08004355 : buf_(16384 - 16),
4356 type_(0),
Mathieu Chartier36dab362014-07-30 14:59:56 -07004357 chunk_overhead_(0) {
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004358 Reset();
4359 if (native) {
Ian Rogers30fab402012-01-23 15:43:46 -08004360 type_ = CHUNK_TYPE("NHSG");
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004361 } else {
Ian Rogers30fab402012-01-23 15:43:46 -08004362 type_ = merge ? CHUNK_TYPE("HPSG") : CHUNK_TYPE("HPSO");
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004363 }
4364 }
4365
4366 ~HeapChunkContext() {
Ian Rogers30fab402012-01-23 15:43:46 -08004367 if (p_ > &buf_[0]) {
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004368 Flush();
4369 }
4370 }
4371
Mathieu Chartier36dab362014-07-30 14:59:56 -07004372 void SetChunkOverhead(size_t chunk_overhead) {
4373 chunk_overhead_ = chunk_overhead;
4374 }
4375
4376 void ResetStartOfNextChunk() {
4377 startOfNextMemoryChunk_ = nullptr;
4378 }
4379
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004380 void EnsureHeader(const void* chunk_ptr) {
Ian Rogers30fab402012-01-23 15:43:46 -08004381 if (!needHeader_) {
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004382 return;
4383 }
4384
4385 // Start a new HPSx chunk.
Brian Carlstrom7934ac22013-07-26 10:54:15 -07004386 JDWP::Write4BE(&p_, 1); // Heap id (bogus; we only have one heap).
4387 JDWP::Write1BE(&p_, 8); // Size of allocation unit, in bytes.
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004388
Brian Carlstrom7934ac22013-07-26 10:54:15 -07004389 JDWP::Write4BE(&p_, reinterpret_cast<uintptr_t>(chunk_ptr)); // virtual address of segment start.
4390 JDWP::Write4BE(&p_, 0); // offset of this piece (relative to the virtual address).
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004391 // [u4]: length of piece, in allocation units
4392 // 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 -08004393 pieceLenField_ = p_;
4394 JDWP::Write4BE(&p_, 0x55555555);
4395 needHeader_ = false;
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004396 }
4397
Ian Rogersb726dcb2012-09-05 08:57:23 -07004398 void Flush() SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Ian Rogersc0542af2014-09-03 16:16:56 -07004399 if (pieceLenField_ == nullptr) {
Ian Rogersd636b062013-01-18 17:51:18 -08004400 // Flush immediately post Reset (maybe back-to-back Flush). Ignore.
4401 CHECK(needHeader_);
4402 return;
4403 }
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004404 // Patch the "length of piece" field.
Ian Rogers30fab402012-01-23 15:43:46 -08004405 CHECK_LE(&buf_[0], pieceLenField_);
4406 CHECK_LE(pieceLenField_, p_);
4407 JDWP::Set4BE(pieceLenField_, totalAllocationUnits_);
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004408
Ian Rogers30fab402012-01-23 15:43:46 -08004409 Dbg::DdmSendChunk(type_, p_ - &buf_[0], &buf_[0]);
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004410 Reset();
4411 }
4412
Mathieu Chartierbc689b72014-12-14 17:01:31 -08004413 static void HeapChunkJavaCallback(void* start, void* end, size_t used_bytes, void* arg)
Ian Rogersb726dcb2012-09-05 08:57:23 -07004414 SHARED_LOCKS_REQUIRED(Locks::heap_bitmap_lock_,
4415 Locks::mutator_lock_) {
Mathieu Chartierbc689b72014-12-14 17:01:31 -08004416 reinterpret_cast<HeapChunkContext*>(arg)->HeapChunkJavaCallback(start, end, used_bytes);
4417 }
4418
4419 static void HeapChunkNativeCallback(void* start, void* end, size_t used_bytes, void* arg)
4420 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
4421 reinterpret_cast<HeapChunkContext*>(arg)->HeapChunkNativeCallback(start, end, used_bytes);
Elliott Hughesa2155262011-11-16 16:26:58 -08004422 }
4423
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004424 private:
Elliott Hughesa2155262011-11-16 16:26:58 -08004425 enum { ALLOCATION_UNIT_SIZE = 8 };
4426
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004427 void Reset() {
Ian Rogers30fab402012-01-23 15:43:46 -08004428 p_ = &buf_[0];
Mathieu Chartier36dab362014-07-30 14:59:56 -07004429 ResetStartOfNextChunk();
Ian Rogers30fab402012-01-23 15:43:46 -08004430 totalAllocationUnits_ = 0;
4431 needHeader_ = true;
Ian Rogersc0542af2014-09-03 16:16:56 -07004432 pieceLenField_ = nullptr;
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004433 }
4434
Mathieu Chartierbc689b72014-12-14 17:01:31 -08004435 bool IsNative() const {
4436 return type_ == CHUNK_TYPE("NHSG");
4437 }
4438
4439 // Returns true if the object is not an empty chunk.
4440 bool ProcessRecord(void* start, size_t used_bytes) SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Ian Rogers30fab402012-01-23 15:43:46 -08004441 // Note: heap call backs cannot manipulate the heap upon which they are crawling, care is taken
4442 // in the following code not to allocate memory, by ensuring buf_ is of the correct size
Ian Rogers15bf2d32012-08-28 17:33:04 -07004443 if (used_bytes == 0) {
Mathieu Chartierbc689b72014-12-14 17:01:31 -08004444 if (start == nullptr) {
4445 // Reset for start of new heap.
4446 startOfNextMemoryChunk_ = nullptr;
4447 Flush();
4448 }
4449 // Only process in use memory so that free region information
4450 // also includes dlmalloc book keeping.
4451 return false;
Elliott Hughesa2155262011-11-16 16:26:58 -08004452 }
Ian Rogersc0542af2014-09-03 16:16:56 -07004453 if (startOfNextMemoryChunk_ != nullptr) {
Mathieu Chartierbc689b72014-12-14 17:01:31 -08004454 // Transmit any pending free memory. Native free memory of over kMaxFreeLen could be because
4455 // of the use of mmaps, so don't report. If not free memory then start a new segment.
4456 bool flush = true;
4457 if (start > startOfNextMemoryChunk_) {
4458 const size_t kMaxFreeLen = 2 * kPageSize;
4459 void* free_start = startOfNextMemoryChunk_;
4460 void* free_end = start;
4461 const size_t free_len =
4462 reinterpret_cast<uintptr_t>(free_end) - reinterpret_cast<uintptr_t>(free_start);
4463 if (!IsNative() || free_len < kMaxFreeLen) {
4464 AppendChunk(HPSG_STATE(SOLIDITY_FREE, 0), free_start, free_len, IsNative());
4465 flush = false;
Ian Rogers15bf2d32012-08-28 17:33:04 -07004466 }
Mathieu Chartierbc689b72014-12-14 17:01:31 -08004467 }
4468 if (flush) {
4469 startOfNextMemoryChunk_ = nullptr;
4470 Flush();
4471 }
Ian Rogers15bf2d32012-08-28 17:33:04 -07004472 }
Mathieu Chartierbc689b72014-12-14 17:01:31 -08004473 return true;
Ian Rogers15bf2d32012-08-28 17:33:04 -07004474 }
Elliott Hughesa2155262011-11-16 16:26:58 -08004475
Mathieu Chartierbc689b72014-12-14 17:01:31 -08004476 void HeapChunkNativeCallback(void* start, void* /*end*/, size_t used_bytes)
4477 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
4478 if (ProcessRecord(start, used_bytes)) {
4479 uint8_t state = ExamineNativeObject(start);
4480 AppendChunk(state, start, used_bytes + chunk_overhead_, true /*is_native*/);
4481 startOfNextMemoryChunk_ = reinterpret_cast<char*>(start) + used_bytes + chunk_overhead_;
4482 }
4483 }
4484
4485 void HeapChunkJavaCallback(void* start, void* /*end*/, size_t used_bytes)
4486 SHARED_LOCKS_REQUIRED(Locks::heap_bitmap_lock_, Locks::mutator_lock_) {
4487 if (ProcessRecord(start, used_bytes)) {
4488 // Determine the type of this chunk.
4489 // OLD-TODO: if context.merge, see if this chunk is different from the last chunk.
4490 // If it's the same, we should combine them.
4491 uint8_t state = ExamineJavaObject(reinterpret_cast<mirror::Object*>(start));
4492 AppendChunk(state, start, used_bytes + chunk_overhead_, false /*is_native*/);
4493 startOfNextMemoryChunk_ = reinterpret_cast<char*>(start) + used_bytes + chunk_overhead_;
4494 }
4495 }
4496
4497 void AppendChunk(uint8_t state, void* ptr, size_t length, bool is_native)
Ian Rogersb726dcb2012-09-05 08:57:23 -07004498 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Ian Rogers15bf2d32012-08-28 17:33:04 -07004499 // Make sure there's enough room left in the buffer.
4500 // We need to use two bytes for every fractional 256 allocation units used by the chunk plus
4501 // 17 bytes for any header.
Mathieu Chartierbc689b72014-12-14 17:01:31 -08004502 const size_t needed = ((RoundUp(length / ALLOCATION_UNIT_SIZE, 256) / 256) * 2) + 17;
4503 size_t byte_left = &buf_.back() - p_;
4504 if (byte_left < needed) {
4505 if (is_native) {
Pavel Vyssotski7522c742014-12-08 13:38:26 +06004506 // Cannot trigger memory allocation while walking native heap.
Pavel Vyssotski7522c742014-12-08 13:38:26 +06004507 return;
4508 }
Ian Rogers15bf2d32012-08-28 17:33:04 -07004509 Flush();
4510 }
4511
Mathieu Chartierbc689b72014-12-14 17:01:31 -08004512 byte_left = &buf_.back() - p_;
4513 if (byte_left < needed) {
Ian Rogers15bf2d32012-08-28 17:33:04 -07004514 LOG(WARNING) << "Chunk is too big to transmit (chunk_len=" << length << ", "
4515 << needed << " bytes)";
4516 return;
4517 }
4518 EnsureHeader(ptr);
Elliott Hughesa2155262011-11-16 16:26:58 -08004519 // Write out the chunk description.
Ian Rogers15bf2d32012-08-28 17:33:04 -07004520 length /= ALLOCATION_UNIT_SIZE; // Convert to allocation units.
4521 totalAllocationUnits_ += length;
4522 while (length > 256) {
Ian Rogers30fab402012-01-23 15:43:46 -08004523 *p_++ = state | HPSG_PARTIAL;
4524 *p_++ = 255; // length - 1
Ian Rogers15bf2d32012-08-28 17:33:04 -07004525 length -= 256;
Elliott Hughesa2155262011-11-16 16:26:58 -08004526 }
Ian Rogers30fab402012-01-23 15:43:46 -08004527 *p_++ = state;
Ian Rogers15bf2d32012-08-28 17:33:04 -07004528 *p_++ = length - 1;
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004529 }
4530
Mathieu Chartierbc689b72014-12-14 17:01:31 -08004531 uint8_t ExamineNativeObject(const void* p) SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
4532 return p == nullptr ? HPSG_STATE(SOLIDITY_FREE, 0) : HPSG_STATE(SOLIDITY_HARD, KIND_NATIVE);
4533 }
4534
4535 uint8_t ExamineJavaObject(mirror::Object* o)
Ian Rogersef7d42f2014-01-06 12:55:46 -08004536 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_, Locks::heap_bitmap_lock_) {
Ian Rogersc0542af2014-09-03 16:16:56 -07004537 if (o == nullptr) {
Elliott Hughesa2155262011-11-16 16:26:58 -08004538 return HPSG_STATE(SOLIDITY_FREE, 0);
4539 }
Elliott Hughesa2155262011-11-16 16:26:58 -08004540 // It's an allocated chunk. Figure out what it is.
Mathieu Chartierbc689b72014-12-14 17:01:31 -08004541 gc::Heap* heap = Runtime::Current()->GetHeap();
4542 if (!heap->IsLiveObjectLocked(o)) {
4543 LOG(ERROR) << "Invalid object in managed heap: " << o;
Elliott Hughesa2155262011-11-16 16:26:58 -08004544 return HPSG_STATE(SOLIDITY_HARD, KIND_NATIVE);
4545 }
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08004546 mirror::Class* c = o->GetClass();
Ian Rogersc0542af2014-09-03 16:16:56 -07004547 if (c == nullptr) {
Elliott Hughesa2155262011-11-16 16:26:58 -08004548 // The object was probably just created but hasn't been initialized yet.
4549 return HPSG_STATE(SOLIDITY_HARD, KIND_OBJECT);
4550 }
Mathieu Chartierbc689b72014-12-14 17:01:31 -08004551 if (!heap->IsValidObjectAddress(c)) {
Ian Rogers15bf2d32012-08-28 17:33:04 -07004552 LOG(ERROR) << "Invalid class for managed heap object: " << o << " " << c;
Elliott Hughesa2155262011-11-16 16:26:58 -08004553 return HPSG_STATE(SOLIDITY_HARD, KIND_UNKNOWN);
4554 }
Mathieu Chartierf26e1b32015-01-29 10:47:10 -08004555 if (c->GetClass() == nullptr) {
4556 LOG(ERROR) << "Null class of class " << c << " for object " << o;
4557 return HPSG_STATE(SOLIDITY_HARD, KIND_UNKNOWN);
4558 }
Elliott Hughesa2155262011-11-16 16:26:58 -08004559 if (c->IsClassClass()) {
4560 return HPSG_STATE(SOLIDITY_HARD, KIND_CLASS_OBJECT);
4561 }
Elliott Hughesa2155262011-11-16 16:26:58 -08004562 if (c->IsArrayClass()) {
Elliott Hughesa2155262011-11-16 16:26:58 -08004563 switch (c->GetComponentSize()) {
4564 case 1: return HPSG_STATE(SOLIDITY_HARD, KIND_ARRAY_1);
4565 case 2: return HPSG_STATE(SOLIDITY_HARD, KIND_ARRAY_2);
4566 case 4: return HPSG_STATE(SOLIDITY_HARD, KIND_ARRAY_4);
4567 case 8: return HPSG_STATE(SOLIDITY_HARD, KIND_ARRAY_8);
4568 }
4569 }
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004570 return HPSG_STATE(SOLIDITY_HARD, KIND_OBJECT);
4571 }
4572
Ian Rogers30fab402012-01-23 15:43:46 -08004573 std::vector<uint8_t> buf_;
4574 uint8_t* p_;
4575 uint8_t* pieceLenField_;
Ian Rogers15bf2d32012-08-28 17:33:04 -07004576 void* startOfNextMemoryChunk_;
Ian Rogers30fab402012-01-23 15:43:46 -08004577 size_t totalAllocationUnits_;
4578 uint32_t type_;
Ian Rogers30fab402012-01-23 15:43:46 -08004579 bool needHeader_;
Mathieu Chartier36dab362014-07-30 14:59:56 -07004580 size_t chunk_overhead_;
Ian Rogers30fab402012-01-23 15:43:46 -08004581
Elliott Hughesa2155262011-11-16 16:26:58 -08004582 DISALLOW_COPY_AND_ASSIGN(HeapChunkContext);
4583};
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004584
Mathieu Chartier36dab362014-07-30 14:59:56 -07004585static void BumpPointerSpaceCallback(mirror::Object* obj, void* arg)
4586 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) EXCLUSIVE_LOCKS_REQUIRED(Locks::heap_bitmap_lock_) {
4587 const size_t size = RoundUp(obj->SizeOf(), kObjectAlignment);
Mathieu Chartierbc689b72014-12-14 17:01:31 -08004588 HeapChunkContext::HeapChunkJavaCallback(
Mathieu Chartier36dab362014-07-30 14:59:56 -07004589 obj, reinterpret_cast<void*>(reinterpret_cast<uintptr_t>(obj) + size), size, arg);
4590}
4591
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004592void Dbg::DdmSendHeapSegments(bool native) {
Mathieu Chartierbc689b72014-12-14 17:01:31 -08004593 Dbg::HpsgWhen when = native ? gDdmNhsgWhen : gDdmHpsgWhen;
4594 Dbg::HpsgWhat what = native ? gDdmNhsgWhat : gDdmHpsgWhat;
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004595 if (when == HPSG_WHEN_NEVER) {
4596 return;
4597 }
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004598 // Figure out what kind of chunks we'll be sending.
Mathieu Chartierbc689b72014-12-14 17:01:31 -08004599 CHECK(what == HPSG_WHAT_MERGED_OBJECTS || what == HPSG_WHAT_DISTINCT_OBJECTS)
4600 << static_cast<int>(what);
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004601
4602 // First, send a heap start chunk.
4603 uint8_t heap_id[4];
Brian Carlstrom7934ac22013-07-26 10:54:15 -07004604 JDWP::Set4BE(&heap_id[0], 1); // Heap id (bogus; we only have one heap).
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004605 Dbg::DdmSendChunk(native ? CHUNK_TYPE("NHST") : CHUNK_TYPE("HPST"), sizeof(heap_id), heap_id);
Hiroshi Yamauchicf58d4a2013-09-26 14:21:22 -07004606 Thread* self = Thread::Current();
Hiroshi Yamauchicf58d4a2013-09-26 14:21:22 -07004607 Locks::mutator_lock_->AssertSharedHeld(self);
Hiroshi Yamauchicf58d4a2013-09-26 14:21:22 -07004608
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004609 // Send a series of heap segment chunks.
Mathieu Chartierbc689b72014-12-14 17:01:31 -08004610 HeapChunkContext context(what == HPSG_WHAT_MERGED_OBJECTS, native);
Elliott Hughesa2155262011-11-16 16:26:58 -08004611 if (native) {
Ian Rogers872dd822014-10-30 11:19:14 -07004612#if defined(HAVE_ANDROID_OS) && defined(USE_DLMALLOC)
Mathieu Chartierbc689b72014-12-14 17:01:31 -08004613 dlmalloc_inspect_all(HeapChunkContext::HeapChunkNativeCallback, &context);
4614 HeapChunkContext::HeapChunkNativeCallback(nullptr, nullptr, 0, &context); // Indicate end of a space.
Christopher Ferrisc4ddc042014-05-13 14:47:50 -07004615#else
4616 UNIMPLEMENTED(WARNING) << "Native heap inspection is only supported with dlmalloc";
4617#endif
Elliott Hughesa2155262011-11-16 16:26:58 -08004618 } else {
Ian Rogers1d54e732013-05-02 21:10:01 -07004619 gc::Heap* heap = Runtime::Current()->GetHeap();
Mathieu Chartier36dab362014-07-30 14:59:56 -07004620 for (const auto& space : heap->GetContinuousSpaces()) {
4621 if (space->IsDlMallocSpace()) {
Mathieu Chartier4c69d7f2014-10-10 12:45:50 -07004622 ReaderMutexLock mu(self, *Locks::heap_bitmap_lock_);
Mathieu Chartier36dab362014-07-30 14:59:56 -07004623 // dlmalloc's chunk header is 2 * sizeof(size_t), but if the previous chunk is in use for an
4624 // allocation then the first sizeof(size_t) may belong to it.
4625 context.SetChunkOverhead(sizeof(size_t));
Mathieu Chartierbc689b72014-12-14 17:01:31 -08004626 space->AsDlMallocSpace()->Walk(HeapChunkContext::HeapChunkJavaCallback, &context);
Mathieu Chartier36dab362014-07-30 14:59:56 -07004627 } else if (space->IsRosAllocSpace()) {
4628 context.SetChunkOverhead(0);
Mathieu Chartier4c69d7f2014-10-10 12:45:50 -07004629 // Need to acquire the mutator lock before the heap bitmap lock with exclusive access since
4630 // RosAlloc's internal logic doesn't know to release and reacquire the heap bitmap lock.
4631 self->TransitionFromRunnableToSuspended(kSuspended);
4632 ThreadList* tl = Runtime::Current()->GetThreadList();
Mathieu Chartierbf9fc582015-03-13 17:21:25 -07004633 tl->SuspendAll(__FUNCTION__);
Mathieu Chartier4c69d7f2014-10-10 12:45:50 -07004634 {
4635 ReaderMutexLock mu(self, *Locks::heap_bitmap_lock_);
Mathieu Chartierbc689b72014-12-14 17:01:31 -08004636 space->AsRosAllocSpace()->Walk(HeapChunkContext::HeapChunkJavaCallback, &context);
Mathieu Chartier4c69d7f2014-10-10 12:45:50 -07004637 }
4638 tl->ResumeAll();
4639 self->TransitionFromSuspendedToRunnable();
Mathieu Chartier36dab362014-07-30 14:59:56 -07004640 } else if (space->IsBumpPointerSpace()) {
Mathieu Chartier4c69d7f2014-10-10 12:45:50 -07004641 ReaderMutexLock mu(self, *Locks::heap_bitmap_lock_);
Mathieu Chartier36dab362014-07-30 14:59:56 -07004642 context.SetChunkOverhead(0);
Mathieu Chartier36dab362014-07-30 14:59:56 -07004643 space->AsBumpPointerSpace()->Walk(BumpPointerSpaceCallback, &context);
Mathieu Chartierbc689b72014-12-14 17:01:31 -08004644 HeapChunkContext::HeapChunkJavaCallback(nullptr, nullptr, 0, &context);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08004645 } else if (space->IsRegionSpace()) {
4646 heap->IncrementDisableMovingGC(self);
4647 self->TransitionFromRunnableToSuspended(kSuspended);
4648 ThreadList* tl = Runtime::Current()->GetThreadList();
Mathieu Chartierbf9fc582015-03-13 17:21:25 -07004649 tl->SuspendAll(__FUNCTION__);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08004650 ReaderMutexLock mu(self, *Locks::heap_bitmap_lock_);
4651 context.SetChunkOverhead(0);
4652 space->AsRegionSpace()->Walk(BumpPointerSpaceCallback, &context);
4653 HeapChunkContext::HeapChunkJavaCallback(nullptr, nullptr, 0, &context);
4654 tl->ResumeAll();
4655 self->TransitionFromSuspendedToRunnable();
4656 heap->DecrementDisableMovingGC(self);
Mathieu Chartier36dab362014-07-30 14:59:56 -07004657 } else {
4658 UNIMPLEMENTED(WARNING) << "Not counting objects in space " << *space;
Mathieu Chartierb062fdd2012-07-03 09:51:48 -07004659 }
Mathieu Chartier36dab362014-07-30 14:59:56 -07004660 context.ResetStartOfNextChunk();
Mathieu Chartierb062fdd2012-07-03 09:51:48 -07004661 }
Mathieu Chartier4c69d7f2014-10-10 12:45:50 -07004662 ReaderMutexLock mu(self, *Locks::heap_bitmap_lock_);
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -07004663 // Walk the large objects, these are not in the AllocSpace.
Mathieu Chartier36dab362014-07-30 14:59:56 -07004664 context.SetChunkOverhead(0);
Mathieu Chartierbc689b72014-12-14 17:01:31 -08004665 heap->GetLargeObjectsSpace()->Walk(HeapChunkContext::HeapChunkJavaCallback, &context);
Elliott Hughesa2155262011-11-16 16:26:58 -08004666 }
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004667
4668 // Finally, send a heap end chunk.
4669 Dbg::DdmSendChunk(native ? CHUNK_TYPE("NHEN") : CHUNK_TYPE("HPEN"), sizeof(heap_id), heap_id);
Elliott Hughes767a1472011-10-26 18:49:02 -07004670}
4671
Elliott Hughesb1a58792013-07-11 18:10:58 -07004672static size_t GetAllocTrackerMax() {
4673#ifdef HAVE_ANDROID_OS
4674 // Check whether there's a system property overriding the number of records.
4675 const char* propertyName = "dalvik.vm.allocTrackerMax";
4676 char allocRecordMaxString[PROPERTY_VALUE_MAX];
4677 if (property_get(propertyName, allocRecordMaxString, "") > 0) {
4678 char* end;
4679 size_t value = strtoul(allocRecordMaxString, &end, 10);
4680 if (*end != '\0') {
Ruben Brunk3e47a742013-09-09 17:56:07 -07004681 LOG(ERROR) << "Ignoring " << propertyName << " '" << allocRecordMaxString
4682 << "' --- invalid";
Elliott Hughesb1a58792013-07-11 18:10:58 -07004683 return kDefaultNumAllocRecords;
4684 }
4685 if (!IsPowerOfTwo(value)) {
Ruben Brunk3e47a742013-09-09 17:56:07 -07004686 LOG(ERROR) << "Ignoring " << propertyName << " '" << allocRecordMaxString
4687 << "' --- not power of two";
Elliott Hughesb1a58792013-07-11 18:10:58 -07004688 return kDefaultNumAllocRecords;
4689 }
4690 return value;
4691 }
4692#endif
4693 return kDefaultNumAllocRecords;
4694}
4695
Brian Carlstrom306db812014-09-05 13:01:41 -07004696void Dbg::SetAllocTrackingEnabled(bool enable) {
4697 Thread* self = Thread::Current();
4698 if (enable) {
Sebastien Hertzb98063a2014-03-26 10:57:20 +01004699 {
Brian Carlstrom306db812014-09-05 13:01:41 -07004700 MutexLock mu(self, *Locks::alloc_tracker_lock_);
4701 if (recent_allocation_records_ != nullptr) {
4702 return; // Already enabled, bail.
Sebastien Hertzb98063a2014-03-26 10:57:20 +01004703 }
Brian Carlstrom306db812014-09-05 13:01:41 -07004704 alloc_record_max_ = GetAllocTrackerMax();
4705 LOG(INFO) << "Enabling alloc tracker (" << alloc_record_max_ << " entries of "
4706 << kMaxAllocRecordStackDepth << " frames, taking "
4707 << PrettySize(sizeof(AllocRecord) * alloc_record_max_) << ")";
4708 DCHECK_EQ(alloc_record_head_, 0U);
4709 DCHECK_EQ(alloc_record_count_, 0U);
4710 recent_allocation_records_ = new AllocRecord[alloc_record_max_];
4711 CHECK(recent_allocation_records_ != nullptr);
Elliott Hughes545a0642011-11-08 19:10:03 -08004712 }
Mathieu Chartier9ef78b52014-09-25 17:03:12 -07004713 Runtime::Current()->GetInstrumentation()->InstrumentQuickAllocEntryPoints();
Elliott Hughes545a0642011-11-08 19:10:03 -08004714 } else {
Sebastien Hertzb98063a2014-03-26 10:57:20 +01004715 {
Brian Carlstrom306db812014-09-05 13:01:41 -07004716 ScopedObjectAccess soa(self); // For type_cache_.Clear();
4717 MutexLock mu(self, *Locks::alloc_tracker_lock_);
4718 if (recent_allocation_records_ == nullptr) {
4719 return; // Already disabled, bail.
4720 }
Mathieu Chartier4345c462014-06-27 10:20:14 -07004721 LOG(INFO) << "Disabling alloc tracker";
Sebastien Hertzb98063a2014-03-26 10:57:20 +01004722 delete[] recent_allocation_records_;
Ian Rogersc0542af2014-09-03 16:16:56 -07004723 recent_allocation_records_ = nullptr;
Brian Carlstrom306db812014-09-05 13:01:41 -07004724 alloc_record_head_ = 0;
4725 alloc_record_count_ = 0;
Mathieu Chartier4345c462014-06-27 10:20:14 -07004726 type_cache_.Clear();
Sebastien Hertzb98063a2014-03-26 10:57:20 +01004727 }
Brian Carlstrom306db812014-09-05 13:01:41 -07004728 // If an allocation comes in before we uninstrument, we will safely drop it on the floor.
Mathieu Chartier9ef78b52014-09-25 17:03:12 -07004729 Runtime::Current()->GetInstrumentation()->UninstrumentQuickAllocEntryPoints();
Elliott Hughes545a0642011-11-08 19:10:03 -08004730 }
4731}
4732
Ian Rogers0399dde2012-06-06 17:09:28 -07004733struct AllocRecordStackVisitor : public StackVisitor {
Andreas Gampe277ccbd2014-11-03 21:36:10 -08004734 AllocRecordStackVisitor(Thread* thread, AllocRecord* record_in)
Ian Rogersb726dcb2012-09-05 08:57:23 -07004735 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_)
Nicolas Geoffray8e5bd182015-05-06 11:34:34 +01004736 : StackVisitor(thread, nullptr, StackVisitor::StackWalkKind::kIncludeInlinedFrames),
4737 record(record_in),
4738 depth(0) {}
Elliott Hughes545a0642011-11-08 19:10:03 -08004739
Ian Rogers00f7d0e2012-07-19 15:28:27 -07004740 // TODO: Enable annotalysis. We know lock is held in constructor, but abstraction confuses
4741 // annotalysis.
4742 bool VisitFrame() NO_THREAD_SAFETY_ANALYSIS {
Elliott Hughes545a0642011-11-08 19:10:03 -08004743 if (depth >= kMaxAllocRecordStackDepth) {
Elliott Hughes530fa002012-03-12 11:44:49 -07004744 return false;
Elliott Hughes545a0642011-11-08 19:10:03 -08004745 }
Brian Carlstromea46f952013-07-30 01:26:50 -07004746 mirror::ArtMethod* m = GetMethod();
Ian Rogers0399dde2012-06-06 17:09:28 -07004747 if (!m->IsRuntimeMethod()) {
Hiroshi Yamauchib5a9e3d2014-06-09 12:11:20 -07004748 record->StackElement(depth)->SetMethod(m);
4749 record->StackElement(depth)->SetDexPc(GetDexPc());
Elliott Hughes530fa002012-03-12 11:44:49 -07004750 ++depth;
Elliott Hughes545a0642011-11-08 19:10:03 -08004751 }
Elliott Hughes530fa002012-03-12 11:44:49 -07004752 return true;
Elliott Hughes545a0642011-11-08 19:10:03 -08004753 }
4754
4755 ~AllocRecordStackVisitor() {
4756 // Clear out any unused stack trace elements.
4757 for (; depth < kMaxAllocRecordStackDepth; ++depth) {
Hiroshi Yamauchib5a9e3d2014-06-09 12:11:20 -07004758 record->StackElement(depth)->SetMethod(nullptr);
4759 record->StackElement(depth)->SetDexPc(0);
Elliott Hughes545a0642011-11-08 19:10:03 -08004760 }
4761 }
4762
4763 AllocRecord* record;
4764 size_t depth;
4765};
4766
Ian Rogers844506b2014-09-12 19:59:33 -07004767void Dbg::RecordAllocation(Thread* self, mirror::Class* type, size_t byte_count) {
Brian Carlstrom306db812014-09-05 13:01:41 -07004768 MutexLock mu(self, *Locks::alloc_tracker_lock_);
Ian Rogersc0542af2014-09-03 16:16:56 -07004769 if (recent_allocation_records_ == nullptr) {
Brian Carlstrom306db812014-09-05 13:01:41 -07004770 // In the process of shutting down recording, bail.
Elliott Hughes545a0642011-11-08 19:10:03 -08004771 return;
4772 }
4773
4774 // Advance and clip.
Ian Rogers719d1a32014-03-06 12:13:39 -08004775 if (++alloc_record_head_ == alloc_record_max_) {
4776 alloc_record_head_ = 0;
Elliott Hughes545a0642011-11-08 19:10:03 -08004777 }
4778
4779 // Fill in the basics.
Ian Rogers719d1a32014-03-06 12:13:39 -08004780 AllocRecord* record = &recent_allocation_records_[alloc_record_head_];
Hiroshi Yamauchib5a9e3d2014-06-09 12:11:20 -07004781 record->SetType(type);
4782 record->SetByteCount(byte_count);
4783 record->SetThinLockId(self->GetThreadId());
Elliott Hughes545a0642011-11-08 19:10:03 -08004784
4785 // Fill in the stack trace.
Ian Rogers7a22fa62013-01-23 12:16:16 -08004786 AllocRecordStackVisitor visitor(self, record);
Ian Rogers0399dde2012-06-06 17:09:28 -07004787 visitor.WalkStack();
Elliott Hughes545a0642011-11-08 19:10:03 -08004788
Ian Rogers719d1a32014-03-06 12:13:39 -08004789 if (alloc_record_count_ < alloc_record_max_) {
4790 ++alloc_record_count_;
Elliott Hughes545a0642011-11-08 19:10:03 -08004791 }
4792}
4793
Elliott Hughesa8f93cb2012-06-08 17:08:48 -07004794// Returns the index of the head element.
4795//
Brian Carlstrom306db812014-09-05 13:01:41 -07004796// We point at the most-recently-written record, so if alloc_record_count_ is 1
Elliott Hughesa8f93cb2012-06-08 17:08:48 -07004797// we want to use the current element. Take "head+1" and subtract count
4798// from it.
4799//
4800// We need to handle underflow in our circular buffer, so we add
Brian Carlstrom306db812014-09-05 13:01:41 -07004801// alloc_record_max_ and then mask it back down.
Ian Rogers719d1a32014-03-06 12:13:39 -08004802size_t Dbg::HeadIndex() {
4803 return (Dbg::alloc_record_head_ + 1 + Dbg::alloc_record_max_ - Dbg::alloc_record_count_) &
4804 (Dbg::alloc_record_max_ - 1);
Elliott Hughes545a0642011-11-08 19:10:03 -08004805}
4806
4807void Dbg::DumpRecentAllocations() {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07004808 ScopedObjectAccess soa(Thread::Current());
Brian Carlstrom306db812014-09-05 13:01:41 -07004809 MutexLock mu(soa.Self(), *Locks::alloc_tracker_lock_);
Ian Rogersc0542af2014-09-03 16:16:56 -07004810 if (recent_allocation_records_ == nullptr) {
Elliott Hughes545a0642011-11-08 19:10:03 -08004811 LOG(INFO) << "Not recording tracked allocations";
4812 return;
4813 }
4814
4815 // "i" is the head of the list. We want to start at the end of the
4816 // list and move forward to the tail.
Elliott Hughesa8f93cb2012-06-08 17:08:48 -07004817 size_t i = HeadIndex();
Brian Carlstrom306db812014-09-05 13:01:41 -07004818 const uint16_t capped_count = CappedAllocRecordCount(Dbg::alloc_record_count_);
4819 uint16_t count = capped_count;
Elliott Hughes545a0642011-11-08 19:10:03 -08004820
Ian Rogers719d1a32014-03-06 12:13:39 -08004821 LOG(INFO) << "Tracked allocations, (head=" << alloc_record_head_ << " count=" << count << ")";
Elliott Hughes545a0642011-11-08 19:10:03 -08004822 while (count--) {
4823 AllocRecord* record = &recent_allocation_records_[i];
4824
Hiroshi Yamauchib5a9e3d2014-06-09 12:11:20 -07004825 LOG(INFO) << StringPrintf(" Thread %-2d %6zd bytes ", record->ThinLockId(), record->ByteCount())
4826 << PrettyClass(record->Type());
Elliott Hughes545a0642011-11-08 19:10:03 -08004827
4828 for (size_t stack_frame = 0; stack_frame < kMaxAllocRecordStackDepth; ++stack_frame) {
Hiroshi Yamauchib5a9e3d2014-06-09 12:11:20 -07004829 AllocRecordStackTraceElement* stack_element = record->StackElement(stack_frame);
4830 mirror::ArtMethod* m = stack_element->Method();
Ian Rogersc0542af2014-09-03 16:16:56 -07004831 if (m == nullptr) {
Elliott Hughes545a0642011-11-08 19:10:03 -08004832 break;
4833 }
Hiroshi Yamauchib5a9e3d2014-06-09 12:11:20 -07004834 LOG(INFO) << " " << PrettyMethod(m) << " line " << stack_element->LineNumber();
Elliott Hughes545a0642011-11-08 19:10:03 -08004835 }
4836
4837 // pause periodically to help logcat catch up
4838 if ((count % 5) == 0) {
4839 usleep(40000);
4840 }
4841
Ian Rogers719d1a32014-03-06 12:13:39 -08004842 i = (i + 1) & (alloc_record_max_ - 1);
Elliott Hughes545a0642011-11-08 19:10:03 -08004843 }
4844}
4845
4846class StringTable {
4847 public:
4848 StringTable() {
4849 }
4850
Mathieu Chartier4345c462014-06-27 10:20:14 -07004851 void Add(const std::string& str) {
4852 table_.insert(str);
4853 }
4854
4855 void Add(const char* str) {
4856 table_.insert(str);
Elliott Hughes545a0642011-11-08 19:10:03 -08004857 }
4858
Elliott Hughesa8f93cb2012-06-08 17:08:48 -07004859 size_t IndexOf(const char* s) const {
Mathieu Chartier02e25112013-08-14 16:14:24 -07004860 auto it = table_.find(s);
Elliott Hughesa8f93cb2012-06-08 17:08:48 -07004861 if (it == table_.end()) {
4862 LOG(FATAL) << "IndexOf(\"" << s << "\") failed";
4863 }
4864 return std::distance(table_.begin(), it);
Elliott Hughes545a0642011-11-08 19:10:03 -08004865 }
4866
Elliott Hughesa8f93cb2012-06-08 17:08:48 -07004867 size_t Size() const {
Elliott Hughes545a0642011-11-08 19:10:03 -08004868 return table_.size();
4869 }
4870
Elliott Hughesa8f93cb2012-06-08 17:08:48 -07004871 void WriteTo(std::vector<uint8_t>& bytes) const {
Mathieu Chartier02e25112013-08-14 16:14:24 -07004872 for (const std::string& str : table_) {
4873 const char* s = str.c_str();
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08004874 size_t s_len = CountModifiedUtf8Chars(s);
Christopher Ferris8a354052015-04-24 17:23:53 -07004875 std::unique_ptr<uint16_t[]> s_utf16(new uint16_t[s_len]);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08004876 ConvertModifiedUtf8ToUtf16(s_utf16.get(), s);
4877 JDWP::AppendUtf16BE(bytes, s_utf16.get(), s_len);
Elliott Hughes545a0642011-11-08 19:10:03 -08004878 }
4879 }
4880
4881 private:
Elliott Hughesa8f93cb2012-06-08 17:08:48 -07004882 std::set<std::string> table_;
Elliott Hughes545a0642011-11-08 19:10:03 -08004883 DISALLOW_COPY_AND_ASSIGN(StringTable);
4884};
4885
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07004886static const char* GetMethodSourceFile(mirror::ArtMethod* method)
Sebastien Hertz280286a2014-04-28 09:26:50 +02004887 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07004888 DCHECK(method != nullptr);
4889 const char* source_file = method->GetDeclaringClassSourceFile();
Sebastien Hertz280286a2014-04-28 09:26:50 +02004890 return (source_file != nullptr) ? source_file : "";
4891}
4892
Elliott Hughes545a0642011-11-08 19:10:03 -08004893/*
4894 * The data we send to DDMS contains everything we have recorded.
4895 *
4896 * Message header (all values big-endian):
4897 * (1b) message header len (to allow future expansion); includes itself
4898 * (1b) entry header len
4899 * (1b) stack frame len
4900 * (2b) number of entries
4901 * (4b) offset to string table from start of message
4902 * (2b) number of class name strings
4903 * (2b) number of method name strings
4904 * (2b) number of source file name strings
4905 * For each entry:
4906 * (4b) total allocation size
Elliott Hughes221229c2013-01-08 18:17:50 -08004907 * (2b) thread id
Elliott Hughes545a0642011-11-08 19:10:03 -08004908 * (2b) allocated object's class name index
4909 * (1b) stack depth
4910 * For each stack frame:
4911 * (2b) method's class name
4912 * (2b) method name
4913 * (2b) method source file
4914 * (2b) line number, clipped to 32767; -2 if native; -1 if no source
4915 * (xb) class name strings
4916 * (xb) method name strings
4917 * (xb) source file strings
4918 *
4919 * As with other DDM traffic, strings are sent as a 4-byte length
4920 * followed by UTF-16 data.
4921 *
4922 * We send up 16-bit unsigned indexes into string tables. In theory there
Brian Carlstrom306db812014-09-05 13:01:41 -07004923 * can be (kMaxAllocRecordStackDepth * alloc_record_max_) unique strings in
Elliott Hughes545a0642011-11-08 19:10:03 -08004924 * each table, but in practice there should be far fewer.
4925 *
4926 * The chief reason for using a string table here is to keep the size of
4927 * the DDMS message to a minimum. This is partly to make the protocol
4928 * efficient, but also because we have to form the whole thing up all at
4929 * once in a memory buffer.
4930 *
4931 * We use separate string tables for class names, method names, and source
4932 * files to keep the indexes small. There will generally be no overlap
4933 * between the contents of these tables.
4934 */
4935jbyteArray Dbg::GetRecentAllocations() {
Ian Rogerscf7f1912014-10-22 22:06:39 -07004936 if ((false)) {
Elliott Hughes545a0642011-11-08 19:10:03 -08004937 DumpRecentAllocations();
4938 }
4939
Ian Rogers50b35e22012-10-04 10:09:15 -07004940 Thread* self = Thread::Current();
Elliott Hughes545a0642011-11-08 19:10:03 -08004941 std::vector<uint8_t> bytes;
Mathieu Chartier46e811b2013-07-10 17:09:14 -07004942 {
Brian Carlstrom306db812014-09-05 13:01:41 -07004943 MutexLock mu(self, *Locks::alloc_tracker_lock_);
Mathieu Chartier46e811b2013-07-10 17:09:14 -07004944 //
4945 // Part 1: generate string tables.
4946 //
4947 StringTable class_names;
4948 StringTable method_names;
4949 StringTable filenames;
Elliott Hughes545a0642011-11-08 19:10:03 -08004950
Brian Carlstrom306db812014-09-05 13:01:41 -07004951 const uint16_t capped_count = CappedAllocRecordCount(Dbg::alloc_record_count_);
4952 uint16_t count = capped_count;
4953 size_t idx = HeadIndex();
Mathieu Chartier46e811b2013-07-10 17:09:14 -07004954 while (count--) {
4955 AllocRecord* record = &recent_allocation_records_[idx];
Ian Rogers1ff3c982014-08-12 02:30:58 -07004956 std::string temp;
4957 class_names.Add(record->Type()->GetDescriptor(&temp));
Mathieu Chartier46e811b2013-07-10 17:09:14 -07004958 for (size_t i = 0; i < kMaxAllocRecordStackDepth; i++) {
Hiroshi Yamauchib5a9e3d2014-06-09 12:11:20 -07004959 mirror::ArtMethod* m = record->StackElement(i)->Method();
Ian Rogersc0542af2014-09-03 16:16:56 -07004960 if (m != nullptr) {
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07004961 class_names.Add(m->GetDeclaringClassDescriptor());
4962 method_names.Add(m->GetName());
4963 filenames.Add(GetMethodSourceFile(m));
Mathieu Chartier46e811b2013-07-10 17:09:14 -07004964 }
4965 }
Elliott Hughes545a0642011-11-08 19:10:03 -08004966
Ian Rogers719d1a32014-03-06 12:13:39 -08004967 idx = (idx + 1) & (alloc_record_max_ - 1);
Elliott Hughes545a0642011-11-08 19:10:03 -08004968 }
4969
Brian Carlstrom306db812014-09-05 13:01:41 -07004970 LOG(INFO) << "allocation records: " << capped_count;
Mathieu Chartier46e811b2013-07-10 17:09:14 -07004971
4972 //
4973 // Part 2: Generate the output and store it in the buffer.
4974 //
4975
4976 // (1b) message header len (to allow future expansion); includes itself
4977 // (1b) entry header len
4978 // (1b) stack frame len
4979 const int kMessageHeaderLen = 15;
4980 const int kEntryHeaderLen = 9;
4981 const int kStackFrameLen = 8;
4982 JDWP::Append1BE(bytes, kMessageHeaderLen);
4983 JDWP::Append1BE(bytes, kEntryHeaderLen);
4984 JDWP::Append1BE(bytes, kStackFrameLen);
4985
4986 // (2b) number of entries
4987 // (4b) offset to string table from start of message
4988 // (2b) number of class name strings
4989 // (2b) number of method name strings
4990 // (2b) number of source file name strings
Brian Carlstrom306db812014-09-05 13:01:41 -07004991 JDWP::Append2BE(bytes, capped_count);
Mathieu Chartier46e811b2013-07-10 17:09:14 -07004992 size_t string_table_offset = bytes.size();
Brian Carlstrom7934ac22013-07-26 10:54:15 -07004993 JDWP::Append4BE(bytes, 0); // We'll patch this later...
Mathieu Chartier46e811b2013-07-10 17:09:14 -07004994 JDWP::Append2BE(bytes, class_names.Size());
4995 JDWP::Append2BE(bytes, method_names.Size());
4996 JDWP::Append2BE(bytes, filenames.Size());
4997
Mathieu Chartier46e811b2013-07-10 17:09:14 -07004998 idx = HeadIndex();
Ian Rogers1ff3c982014-08-12 02:30:58 -07004999 std::string temp;
Brian Carlstrom306db812014-09-05 13:01:41 -07005000 for (count = capped_count; count != 0; --count) {
Mathieu Chartier46e811b2013-07-10 17:09:14 -07005001 // For each entry:
5002 // (4b) total allocation size
5003 // (2b) thread id
5004 // (2b) allocated object's class name index
5005 // (1b) stack depth
5006 AllocRecord* record = &recent_allocation_records_[idx];
5007 size_t stack_depth = record->GetDepth();
Mathieu Chartierf8322842014-05-16 10:59:25 -07005008 size_t allocated_object_class_name_index =
Ian Rogers1ff3c982014-08-12 02:30:58 -07005009 class_names.IndexOf(record->Type()->GetDescriptor(&temp));
Hiroshi Yamauchib5a9e3d2014-06-09 12:11:20 -07005010 JDWP::Append4BE(bytes, record->ByteCount());
5011 JDWP::Append2BE(bytes, record->ThinLockId());
Mathieu Chartier46e811b2013-07-10 17:09:14 -07005012 JDWP::Append2BE(bytes, allocated_object_class_name_index);
5013 JDWP::Append1BE(bytes, stack_depth);
5014
Mathieu Chartier46e811b2013-07-10 17:09:14 -07005015 for (size_t stack_frame = 0; stack_frame < stack_depth; ++stack_frame) {
5016 // For each stack frame:
5017 // (2b) method's class name
5018 // (2b) method name
5019 // (2b) method source file
5020 // (2b) line number, clipped to 32767; -2 if native; -1 if no source
Hiroshi Yamauchib5a9e3d2014-06-09 12:11:20 -07005021 mirror::ArtMethod* m = record->StackElement(stack_frame)->Method();
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07005022 size_t class_name_index = class_names.IndexOf(m->GetDeclaringClassDescriptor());
5023 size_t method_name_index = method_names.IndexOf(m->GetName());
5024 size_t file_name_index = filenames.IndexOf(GetMethodSourceFile(m));
Mathieu Chartier46e811b2013-07-10 17:09:14 -07005025 JDWP::Append2BE(bytes, class_name_index);
5026 JDWP::Append2BE(bytes, method_name_index);
5027 JDWP::Append2BE(bytes, file_name_index);
Hiroshi Yamauchib5a9e3d2014-06-09 12:11:20 -07005028 JDWP::Append2BE(bytes, record->StackElement(stack_frame)->LineNumber());
Mathieu Chartier46e811b2013-07-10 17:09:14 -07005029 }
Ian Rogers719d1a32014-03-06 12:13:39 -08005030 idx = (idx + 1) & (alloc_record_max_ - 1);
Mathieu Chartier46e811b2013-07-10 17:09:14 -07005031 }
5032
5033 // (xb) class name strings
5034 // (xb) method name strings
5035 // (xb) source file strings
5036 JDWP::Set4BE(&bytes[string_table_offset], bytes.size());
5037 class_names.WriteTo(bytes);
5038 method_names.WriteTo(bytes);
5039 filenames.WriteTo(bytes);
Elliott Hughes545a0642011-11-08 19:10:03 -08005040 }
Ian Rogers50b35e22012-10-04 10:09:15 -07005041 JNIEnv* env = self->GetJniEnv();
Elliott Hughes545a0642011-11-08 19:10:03 -08005042 jbyteArray result = env->NewByteArray(bytes.size());
Ian Rogersc0542af2014-09-03 16:16:56 -07005043 if (result != nullptr) {
Elliott Hughes545a0642011-11-08 19:10:03 -08005044 env->SetByteArrayRegion(result, 0, bytes.size(), reinterpret_cast<const jbyte*>(&bytes[0]));
5045 }
5046 return result;
5047}
5048
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07005049mirror::ArtMethod* DeoptimizationRequest::Method() const {
5050 ScopedObjectAccessUnchecked soa(Thread::Current());
5051 return soa.DecodeMethod(method_);
5052}
5053
5054void DeoptimizationRequest::SetMethod(mirror::ArtMethod* m) {
5055 ScopedObjectAccessUnchecked soa(Thread::Current());
5056 method_ = soa.EncodeMethod(m);
5057}
5058
Elliott Hughes872d4ec2011-10-21 17:07:15 -07005059} // namespace art