blob: 0eb7f2b85528d1585a7579b97d80b006f2b7b2ff [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 Hertz6995c602014-09-09 12:10:13 +02002809 gJdwpState->PostLocationEvent(&location, this_object, event_flags, return_value);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002810}
2811
Sebastien Hertz3f52eaf2014-04-04 17:50:18 +02002812void Dbg::PostFieldAccessEvent(mirror::ArtMethod* m, int dex_pc,
Mathieu Chartierc7853442015-03-27 14:35:38 -07002813 mirror::Object* this_object, ArtField* f) {
Sebastien Hertz3f52eaf2014-04-04 17:50:18 +02002814 if (!IsDebuggerActive()) {
2815 return;
2816 }
2817 DCHECK(m != nullptr);
2818 DCHECK(f != nullptr);
Sebastien Hertz6995c602014-09-09 12:10:13 +02002819 JDWP::EventLocation location;
2820 SetEventLocation(&location, m, dex_pc);
Sebastien Hertz3f52eaf2014-04-04 17:50:18 +02002821
Sebastien Hertz6995c602014-09-09 12:10:13 +02002822 gJdwpState->PostFieldEvent(&location, f, this_object, nullptr, false);
Sebastien Hertz3f52eaf2014-04-04 17:50:18 +02002823}
2824
2825void Dbg::PostFieldModificationEvent(mirror::ArtMethod* m, int dex_pc,
Mathieu Chartierc7853442015-03-27 14:35:38 -07002826 mirror::Object* this_object, ArtField* f,
Sebastien Hertz3f52eaf2014-04-04 17:50:18 +02002827 const JValue* field_value) {
2828 if (!IsDebuggerActive()) {
2829 return;
2830 }
2831 DCHECK(m != nullptr);
2832 DCHECK(f != nullptr);
2833 DCHECK(field_value != nullptr);
Sebastien Hertz6995c602014-09-09 12:10:13 +02002834 JDWP::EventLocation location;
2835 SetEventLocation(&location, m, dex_pc);
Sebastien Hertz3f52eaf2014-04-04 17:50:18 +02002836
Sebastien Hertz6995c602014-09-09 12:10:13 +02002837 gJdwpState->PostFieldEvent(&location, f, this_object, field_value, true);
Sebastien Hertz3f52eaf2014-04-04 17:50:18 +02002838}
2839
Nicolas Geoffray14691c52015-03-05 10:40:17 +00002840/**
2841 * Finds the location where this exception will be caught. We search until we reach the top
2842 * frame, in which case this exception is considered uncaught.
2843 */
2844class CatchLocationFinder : public StackVisitor {
2845 public:
2846 CatchLocationFinder(Thread* self, const Handle<mirror::Throwable>& exception, Context* context)
2847 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_)
Nicolas Geoffray8e5bd182015-05-06 11:34:34 +01002848 : StackVisitor(self, context, StackVisitor::StackWalkKind::kIncludeInlinedFrames),
Nicolas Geoffray14691c52015-03-05 10:40:17 +00002849 self_(self),
2850 exception_(exception),
2851 handle_scope_(self),
2852 this_at_throw_(handle_scope_.NewHandle<mirror::Object>(nullptr)),
2853 catch_method_(handle_scope_.NewHandle<mirror::ArtMethod>(nullptr)),
2854 throw_method_(handle_scope_.NewHandle<mirror::ArtMethod>(nullptr)),
2855 catch_dex_pc_(DexFile::kDexNoIndex),
2856 throw_dex_pc_(DexFile::kDexNoIndex) {
2857 }
2858
2859 bool VisitFrame() OVERRIDE SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
2860 mirror::ArtMethod* method = GetMethod();
2861 DCHECK(method != nullptr);
2862 if (method->IsRuntimeMethod()) {
2863 // Ignore callee save method.
2864 DCHECK(method->IsCalleeSaveMethod());
2865 return true;
2866 }
2867
2868 uint32_t dex_pc = GetDexPc();
2869 if (throw_method_.Get() == nullptr) {
2870 // First Java method found. It is either the method that threw the exception,
2871 // or the Java native method that is reporting an exception thrown by
2872 // native code.
2873 this_at_throw_.Assign(GetThisObject());
2874 throw_method_.Assign(method);
2875 throw_dex_pc_ = dex_pc;
2876 }
2877
2878 if (dex_pc != DexFile::kDexNoIndex) {
2879 StackHandleScope<2> hs(self_);
2880 uint32_t found_dex_pc;
2881 Handle<mirror::Class> exception_class(hs.NewHandle(exception_->GetClass()));
2882 Handle<mirror::ArtMethod> h_method(hs.NewHandle(method));
2883 bool unused_clear_exception;
2884 found_dex_pc = mirror::ArtMethod::FindCatchBlock(
2885 h_method, exception_class, dex_pc, &unused_clear_exception);
2886 if (found_dex_pc != DexFile::kDexNoIndex) {
2887 catch_method_.Assign(method);
2888 catch_dex_pc_ = found_dex_pc;
2889 return false; // End stack walk.
2890 }
2891 }
2892 return true; // Continue stack walk.
2893 }
2894
2895 mirror::ArtMethod* GetCatchMethod() SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
2896 return catch_method_.Get();
2897 }
2898
2899 mirror::ArtMethod* GetThrowMethod() SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
2900 return throw_method_.Get();
2901 }
2902
2903 mirror::Object* GetThisAtThrow() SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
2904 return this_at_throw_.Get();
2905 }
2906
2907 uint32_t GetCatchDexPc() const {
2908 return catch_dex_pc_;
2909 }
2910
2911 uint32_t GetThrowDexPc() const {
2912 return throw_dex_pc_;
2913 }
2914
2915 private:
2916 Thread* const self_;
2917 const Handle<mirror::Throwable>& exception_;
2918 StackHandleScope<3> handle_scope_;
2919 MutableHandle<mirror::Object> this_at_throw_;
2920 MutableHandle<mirror::ArtMethod> catch_method_;
2921 MutableHandle<mirror::ArtMethod> throw_method_;
2922 uint32_t catch_dex_pc_;
2923 uint32_t throw_dex_pc_;
2924
2925 DISALLOW_COPY_AND_ASSIGN(CatchLocationFinder);
2926};
2927
2928void Dbg::PostException(mirror::Throwable* exception_object) {
Elliott Hughesc0f09332012-03-26 13:27:06 -07002929 if (!IsDebuggerActive()) {
Ian Rogers0ad5bb82011-12-07 10:16:32 -08002930 return;
2931 }
Sebastien Hertz261bc042015-04-08 09:36:07 +02002932 Thread* const self = Thread::Current();
2933 StackHandleScope<1> handle_scope(self);
Nicolas Geoffray14691c52015-03-05 10:40:17 +00002934 Handle<mirror::Throwable> h_exception(handle_scope.NewHandle(exception_object));
2935 std::unique_ptr<Context> context(Context::Create());
Sebastien Hertz261bc042015-04-08 09:36:07 +02002936 CatchLocationFinder clf(self, h_exception, context.get());
Nicolas Geoffray14691c52015-03-05 10:40:17 +00002937 clf.WalkStack(/* include_transitions */ false);
Sebastien Hertz6995c602014-09-09 12:10:13 +02002938 JDWP::EventLocation exception_throw_location;
Nicolas Geoffray14691c52015-03-05 10:40:17 +00002939 SetEventLocation(&exception_throw_location, clf.GetThrowMethod(), clf.GetThrowDexPc());
Sebastien Hertz6995c602014-09-09 12:10:13 +02002940 JDWP::EventLocation exception_catch_location;
Nicolas Geoffray14691c52015-03-05 10:40:17 +00002941 SetEventLocation(&exception_catch_location, clf.GetCatchMethod(), clf.GetCatchDexPc());
Elliott Hughes4740cdf2011-12-07 14:07:12 -08002942
Nicolas Geoffray14691c52015-03-05 10:40:17 +00002943 gJdwpState->PostException(&exception_throw_location, h_exception.Get(), &exception_catch_location,
2944 clf.GetThisAtThrow());
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002945}
2946
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002947void Dbg::PostClassPrepare(mirror::Class* c) {
Elliott Hughesc0f09332012-03-26 13:27:06 -07002948 if (!IsDebuggerActive()) {
Elliott Hughes4740cdf2011-12-07 14:07:12 -08002949 return;
2950 }
Sebastien Hertz6995c602014-09-09 12:10:13 +02002951 gJdwpState->PostClassPrepare(c);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002952}
2953
Ian Rogers62d6c772013-02-27 08:32:07 -08002954void Dbg::UpdateDebugger(Thread* thread, mirror::Object* this_object,
Sebastien Hertz8379b222014-02-24 17:38:15 +01002955 mirror::ArtMethod* m, uint32_t dex_pc,
2956 int event_flags, const JValue* return_value) {
Ian Rogers62d6c772013-02-27 08:32:07 -08002957 if (!IsDebuggerActive() || dex_pc == static_cast<uint32_t>(-2) /* fake method exit */) {
Elliott Hughes2aa2e392012-02-17 17:15:43 -08002958 return;
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08002959 }
2960
Elliott Hughes86964332012-02-15 19:37:42 -08002961 if (IsBreakpoint(m, dex_pc)) {
2962 event_flags |= kBreakpoint;
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08002963 }
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08002964
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01002965 // If the debugger is single-stepping one of our threads, check to
2966 // see if we're that thread and we've reached a step point.
2967 const SingleStepControl* single_step_control = thread->GetSingleStepControl();
Sebastien Hertz597c4f02015-01-26 17:37:14 +01002968 if (single_step_control != nullptr) {
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01002969 CHECK(!m->IsNative());
Sebastien Hertz597c4f02015-01-26 17:37:14 +01002970 if (single_step_control->GetStepDepth() == JDWP::SD_INTO) {
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01002971 // Step into method calls. We break when the line number
2972 // or method pointer changes. If we're in SS_MIN mode, we
2973 // always stop.
Sebastien Hertz597c4f02015-01-26 17:37:14 +01002974 if (single_step_control->GetMethod() != m) {
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01002975 event_flags |= kSingleStep;
2976 VLOG(jdwp) << "SS new method";
Sebastien Hertz597c4f02015-01-26 17:37:14 +01002977 } else if (single_step_control->GetStepSize() == JDWP::SS_MIN) {
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01002978 event_flags |= kSingleStep;
2979 VLOG(jdwp) << "SS new instruction";
Sebastien Hertzbb43b432014-04-14 11:59:08 +02002980 } else if (single_step_control->ContainsDexPc(dex_pc)) {
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01002981 event_flags |= kSingleStep;
2982 VLOG(jdwp) << "SS new line";
2983 }
Sebastien Hertz597c4f02015-01-26 17:37:14 +01002984 } else if (single_step_control->GetStepDepth() == JDWP::SD_OVER) {
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01002985 // Step over method calls. We break when the line number is
2986 // different and the frame depth is <= the original frame
2987 // depth. (We can't just compare on the method, because we
2988 // might get unrolled past it by an exception, and it's tricky
2989 // to identify recursion.)
2990
2991 int stack_depth = GetStackDepth(thread);
2992
Sebastien Hertz597c4f02015-01-26 17:37:14 +01002993 if (stack_depth < single_step_control->GetStackDepth()) {
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01002994 // Popped up one or more frames, always trigger.
2995 event_flags |= kSingleStep;
2996 VLOG(jdwp) << "SS method pop";
Sebastien Hertz597c4f02015-01-26 17:37:14 +01002997 } else if (stack_depth == single_step_control->GetStackDepth()) {
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01002998 // Same depth, see if we moved.
Sebastien Hertz597c4f02015-01-26 17:37:14 +01002999 if (single_step_control->GetStepSize() == JDWP::SS_MIN) {
Elliott Hughes86964332012-02-15 19:37:42 -08003000 event_flags |= kSingleStep;
3001 VLOG(jdwp) << "SS new instruction";
Sebastien Hertzbb43b432014-04-14 11:59:08 +02003002 } else if (single_step_control->ContainsDexPc(dex_pc)) {
Elliott Hughes2435a572012-02-17 16:07:41 -08003003 event_flags |= kSingleStep;
3004 VLOG(jdwp) << "SS new line";
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08003005 }
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01003006 }
3007 } else {
Sebastien Hertz597c4f02015-01-26 17:37:14 +01003008 CHECK_EQ(single_step_control->GetStepDepth(), JDWP::SD_OUT);
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01003009 // Return from the current method. We break when the frame
3010 // depth pops up.
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08003011
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01003012 // This differs from the "method exit" break in that it stops
3013 // with the PC at the next instruction in the returned-to
3014 // function, rather than the end of the returning function.
Elliott Hughes86964332012-02-15 19:37:42 -08003015
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01003016 int stack_depth = GetStackDepth(thread);
Sebastien Hertz597c4f02015-01-26 17:37:14 +01003017 if (stack_depth < single_step_control->GetStackDepth()) {
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01003018 event_flags |= kSingleStep;
3019 VLOG(jdwp) << "SS method pop";
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08003020 }
3021 }
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08003022 }
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08003023
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08003024 // If there's something interesting going on, see if it matches one
3025 // of the debugger filters.
3026 if (event_flags != 0) {
Sebastien Hertz8379b222014-02-24 17:38:15 +01003027 Dbg::PostLocationEvent(m, dex_pc, this_object, event_flags, return_value);
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08003028 }
3029}
3030
Sebastien Hertz42cd43f2014-05-13 14:15:41 +02003031size_t* Dbg::GetReferenceCounterForEvent(uint32_t instrumentation_event) {
3032 switch (instrumentation_event) {
3033 case instrumentation::Instrumentation::kMethodEntered:
3034 return &method_enter_event_ref_count_;
3035 case instrumentation::Instrumentation::kMethodExited:
3036 return &method_exit_event_ref_count_;
3037 case instrumentation::Instrumentation::kDexPcMoved:
3038 return &dex_pc_change_event_ref_count_;
3039 case instrumentation::Instrumentation::kFieldRead:
3040 return &field_read_event_ref_count_;
3041 case instrumentation::Instrumentation::kFieldWritten:
3042 return &field_write_event_ref_count_;
3043 case instrumentation::Instrumentation::kExceptionCaught:
3044 return &exception_catch_event_ref_count_;
3045 default:
3046 return nullptr;
3047 }
3048}
3049
Sebastien Hertz4d25df32014-03-21 17:44:46 +01003050// Process request while all mutator threads are suspended.
3051void Dbg::ProcessDeoptimizationRequest(const DeoptimizationRequest& request) {
Sebastien Hertz138dbfc2013-12-04 18:15:25 +01003052 instrumentation::Instrumentation* instrumentation = Runtime::Current()->GetInstrumentation();
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003053 switch (request.GetKind()) {
Sebastien Hertz4d25df32014-03-21 17:44:46 +01003054 case DeoptimizationRequest::kNothing:
3055 LOG(WARNING) << "Ignoring empty deoptimization request.";
3056 break;
Sebastien Hertz42cd43f2014-05-13 14:15:41 +02003057 case DeoptimizationRequest::kRegisterForEvent:
3058 VLOG(jdwp) << StringPrintf("Add debugger as listener for instrumentation event 0x%x",
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003059 request.InstrumentationEvent());
3060 instrumentation->AddListener(&gDebugInstrumentationListener, request.InstrumentationEvent());
3061 instrumentation_events_ |= request.InstrumentationEvent();
Sebastien Hertz42cd43f2014-05-13 14:15:41 +02003062 break;
3063 case DeoptimizationRequest::kUnregisterForEvent:
3064 VLOG(jdwp) << StringPrintf("Remove debugger as listener for instrumentation event 0x%x",
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003065 request.InstrumentationEvent());
Sebastien Hertz42cd43f2014-05-13 14:15:41 +02003066 instrumentation->RemoveListener(&gDebugInstrumentationListener,
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003067 request.InstrumentationEvent());
3068 instrumentation_events_ &= ~request.InstrumentationEvent();
Sebastien Hertz42cd43f2014-05-13 14:15:41 +02003069 break;
Sebastien Hertz4d25df32014-03-21 17:44:46 +01003070 case DeoptimizationRequest::kFullDeoptimization:
Sebastien Hertz7ec2f1c2014-03-27 20:06:47 +01003071 VLOG(jdwp) << "Deoptimize the world ...";
Sebastien Hertz0462c4c2015-04-01 16:34:17 +02003072 instrumentation->DeoptimizeEverything(kDbgInstrumentationKey);
Sebastien Hertz7ec2f1c2014-03-27 20:06:47 +01003073 VLOG(jdwp) << "Deoptimize the world DONE";
Sebastien Hertz4d25df32014-03-21 17:44:46 +01003074 break;
3075 case DeoptimizationRequest::kFullUndeoptimization:
Sebastien Hertz7ec2f1c2014-03-27 20:06:47 +01003076 VLOG(jdwp) << "Undeoptimize the world ...";
Sebastien Hertz0462c4c2015-04-01 16:34:17 +02003077 instrumentation->UndeoptimizeEverything(kDbgInstrumentationKey);
Sebastien Hertz7ec2f1c2014-03-27 20:06:47 +01003078 VLOG(jdwp) << "Undeoptimize the world DONE";
Sebastien Hertz4d25df32014-03-21 17:44:46 +01003079 break;
3080 case DeoptimizationRequest::kSelectiveDeoptimization:
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003081 VLOG(jdwp) << "Deoptimize method " << PrettyMethod(request.Method()) << " ...";
3082 instrumentation->Deoptimize(request.Method());
3083 VLOG(jdwp) << "Deoptimize method " << PrettyMethod(request.Method()) << " DONE";
Sebastien Hertz4d25df32014-03-21 17:44:46 +01003084 break;
3085 case DeoptimizationRequest::kSelectiveUndeoptimization:
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003086 VLOG(jdwp) << "Undeoptimize method " << PrettyMethod(request.Method()) << " ...";
3087 instrumentation->Undeoptimize(request.Method());
3088 VLOG(jdwp) << "Undeoptimize method " << PrettyMethod(request.Method()) << " DONE";
Sebastien Hertz4d25df32014-03-21 17:44:46 +01003089 break;
3090 default:
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003091 LOG(FATAL) << "Unsupported deoptimization request kind " << request.GetKind();
Sebastien Hertz4d25df32014-03-21 17:44:46 +01003092 break;
Sebastien Hertz138dbfc2013-12-04 18:15:25 +01003093 }
Sebastien Hertz138dbfc2013-12-04 18:15:25 +01003094}
3095
Sebastien Hertz4d25df32014-03-21 17:44:46 +01003096void Dbg::RequestDeoptimization(const DeoptimizationRequest& req) {
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003097 if (req.GetKind() == DeoptimizationRequest::kNothing) {
Sebastien Hertz4d25df32014-03-21 17:44:46 +01003098 // Nothing to do.
3099 return;
3100 }
Brian Carlstrom306db812014-09-05 13:01:41 -07003101 MutexLock mu(Thread::Current(), *Locks::deoptimization_lock_);
Sebastien Hertz7ec2f1c2014-03-27 20:06:47 +01003102 RequestDeoptimizationLocked(req);
3103}
3104
3105void Dbg::RequestDeoptimizationLocked(const DeoptimizationRequest& req) {
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003106 switch (req.GetKind()) {
Sebastien Hertz42cd43f2014-05-13 14:15:41 +02003107 case DeoptimizationRequest::kRegisterForEvent: {
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003108 DCHECK_NE(req.InstrumentationEvent(), 0u);
3109 size_t* counter = GetReferenceCounterForEvent(req.InstrumentationEvent());
Sebastien Hertz42cd43f2014-05-13 14:15:41 +02003110 CHECK(counter != nullptr) << StringPrintf("No counter for instrumentation event 0x%x",
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003111 req.InstrumentationEvent());
Sebastien Hertz42cd43f2014-05-13 14:15:41 +02003112 if (*counter == 0) {
Sebastien Hertz7d2ae432014-05-15 11:26:34 +02003113 VLOG(jdwp) << StringPrintf("Queue request #%zd to start listening to instrumentation event 0x%x",
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003114 deoptimization_requests_.size(), req.InstrumentationEvent());
Sebastien Hertz42cd43f2014-05-13 14:15:41 +02003115 deoptimization_requests_.push_back(req);
3116 }
3117 *counter = *counter + 1;
3118 break;
3119 }
3120 case DeoptimizationRequest::kUnregisterForEvent: {
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003121 DCHECK_NE(req.InstrumentationEvent(), 0u);
3122 size_t* counter = GetReferenceCounterForEvent(req.InstrumentationEvent());
Sebastien Hertz42cd43f2014-05-13 14:15:41 +02003123 CHECK(counter != nullptr) << StringPrintf("No counter for instrumentation event 0x%x",
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003124 req.InstrumentationEvent());
Sebastien Hertz42cd43f2014-05-13 14:15:41 +02003125 *counter = *counter - 1;
3126 if (*counter == 0) {
Sebastien Hertz7d2ae432014-05-15 11:26:34 +02003127 VLOG(jdwp) << StringPrintf("Queue request #%zd to stop listening to instrumentation event 0x%x",
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003128 deoptimization_requests_.size(), req.InstrumentationEvent());
Sebastien Hertz42cd43f2014-05-13 14:15:41 +02003129 deoptimization_requests_.push_back(req);
3130 }
3131 break;
3132 }
Sebastien Hertz4d25df32014-03-21 17:44:46 +01003133 case DeoptimizationRequest::kFullDeoptimization: {
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003134 DCHECK(req.Method() == nullptr);
Sebastien Hertz4d25df32014-03-21 17:44:46 +01003135 if (full_deoptimization_event_count_ == 0) {
Sebastien Hertz7ec2f1c2014-03-27 20:06:47 +01003136 VLOG(jdwp) << "Queue request #" << deoptimization_requests_.size()
3137 << " for full deoptimization";
Sebastien Hertz4d25df32014-03-21 17:44:46 +01003138 deoptimization_requests_.push_back(req);
3139 }
3140 ++full_deoptimization_event_count_;
3141 break;
3142 }
3143 case DeoptimizationRequest::kFullUndeoptimization: {
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003144 DCHECK(req.Method() == nullptr);
Sebastien Hertze713d932014-05-15 10:48:53 +02003145 DCHECK_GT(full_deoptimization_event_count_, 0U);
Sebastien Hertz4d25df32014-03-21 17:44:46 +01003146 --full_deoptimization_event_count_;
3147 if (full_deoptimization_event_count_ == 0) {
Sebastien Hertz7ec2f1c2014-03-27 20:06:47 +01003148 VLOG(jdwp) << "Queue request #" << deoptimization_requests_.size()
3149 << " for full undeoptimization";
Sebastien Hertz4d25df32014-03-21 17:44:46 +01003150 deoptimization_requests_.push_back(req);
3151 }
3152 break;
3153 }
3154 case DeoptimizationRequest::kSelectiveDeoptimization: {
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003155 DCHECK(req.Method() != nullptr);
Sebastien Hertz7ec2f1c2014-03-27 20:06:47 +01003156 VLOG(jdwp) << "Queue request #" << deoptimization_requests_.size()
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003157 << " for deoptimization of " << PrettyMethod(req.Method());
Sebastien Hertz4d25df32014-03-21 17:44:46 +01003158 deoptimization_requests_.push_back(req);
3159 break;
3160 }
3161 case DeoptimizationRequest::kSelectiveUndeoptimization: {
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003162 DCHECK(req.Method() != nullptr);
Sebastien Hertz7ec2f1c2014-03-27 20:06:47 +01003163 VLOG(jdwp) << "Queue request #" << deoptimization_requests_.size()
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003164 << " for undeoptimization of " << PrettyMethod(req.Method());
Sebastien Hertz4d25df32014-03-21 17:44:46 +01003165 deoptimization_requests_.push_back(req);
3166 break;
3167 }
3168 default: {
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003169 LOG(FATAL) << "Unknown deoptimization request kind " << req.GetKind();
Sebastien Hertz4d25df32014-03-21 17:44:46 +01003170 break;
3171 }
3172 }
3173}
3174
Sebastien Hertz138dbfc2013-12-04 18:15:25 +01003175void Dbg::ManageDeoptimization() {
3176 Thread* const self = Thread::Current();
3177 {
3178 // Avoid suspend/resume if there is no pending request.
Brian Carlstrom306db812014-09-05 13:01:41 -07003179 MutexLock mu(self, *Locks::deoptimization_lock_);
Sebastien Hertz4d25df32014-03-21 17:44:46 +01003180 if (deoptimization_requests_.empty()) {
Sebastien Hertz138dbfc2013-12-04 18:15:25 +01003181 return;
3182 }
3183 }
3184 CHECK_EQ(self->GetState(), kRunnable);
3185 self->TransitionFromRunnableToSuspended(kWaitingForDeoptimization);
3186 // We need to suspend mutator threads first.
3187 Runtime* const runtime = Runtime::Current();
Mathieu Chartierbf9fc582015-03-13 17:21:25 -07003188 runtime->GetThreadList()->SuspendAll(__FUNCTION__);
Sebastien Hertz138dbfc2013-12-04 18:15:25 +01003189 const ThreadState old_state = self->SetStateUnsafe(kRunnable);
Sebastien Hertz4d25df32014-03-21 17:44:46 +01003190 {
Brian Carlstrom306db812014-09-05 13:01:41 -07003191 MutexLock mu(self, *Locks::deoptimization_lock_);
Sebastien Hertz7ec2f1c2014-03-27 20:06:47 +01003192 size_t req_index = 0;
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003193 for (DeoptimizationRequest& request : deoptimization_requests_) {
Sebastien Hertz7ec2f1c2014-03-27 20:06:47 +01003194 VLOG(jdwp) << "Process deoptimization request #" << req_index++;
Sebastien Hertz4d25df32014-03-21 17:44:46 +01003195 ProcessDeoptimizationRequest(request);
3196 }
3197 deoptimization_requests_.clear();
3198 }
Sebastien Hertz138dbfc2013-12-04 18:15:25 +01003199 CHECK_EQ(self->SetStateUnsafe(old_state), kRunnable);
3200 runtime->GetThreadList()->ResumeAll();
3201 self->TransitionFromSuspendedToRunnable();
3202}
3203
Sebastien Hertza76a6d42014-03-20 16:40:17 +01003204static bool IsMethodPossiblyInlined(Thread* self, mirror::ArtMethod* m)
3205 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07003206 const DexFile::CodeItem* code_item = m->GetCodeItem();
Sebastien Hertza76a6d42014-03-20 16:40:17 +01003207 if (code_item == nullptr) {
3208 // TODO We should not be asked to watch location in a native or abstract method so the code item
3209 // should never be null. We could just check we never encounter this case.
3210 return false;
Sebastien Hertz138dbfc2013-12-04 18:15:25 +01003211 }
Sebastien Hertz4d1e9ab2014-09-18 16:03:34 +02003212 // Note: method verifier may cause thread suspension.
3213 self->AssertThreadSuspensionIsAllowable();
Hiroshi Yamauchidc376172014-08-22 11:13:12 -07003214 StackHandleScope<3> hs(self);
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07003215 mirror::Class* declaring_class = m->GetDeclaringClass();
3216 Handle<mirror::DexCache> dex_cache(hs.NewHandle(declaring_class->GetDexCache()));
3217 Handle<mirror::ClassLoader> class_loader(hs.NewHandle(declaring_class->GetClassLoader()));
Hiroshi Yamauchidc376172014-08-22 11:13:12 -07003218 Handle<mirror::ArtMethod> method(hs.NewHandle(m));
Ian Rogers7b078e82014-09-10 14:44:24 -07003219 verifier::MethodVerifier verifier(self, dex_cache->GetDexFile(), dex_cache, class_loader,
Hiroshi Yamauchidc376172014-08-22 11:13:12 -07003220 &m->GetClassDef(), code_item, m->GetDexMethodIndex(), method,
Mathieu Chartier4306ef82014-12-19 18:41:47 -08003221 m->GetAccessFlags(), false, true, false, true);
Sebastien Hertza76a6d42014-03-20 16:40:17 +01003222 // Note: we don't need to verify the method.
3223 return InlineMethodAnalyser::AnalyseMethodCode(&verifier, nullptr);
3224}
Sebastien Hertz138dbfc2013-12-04 18:15:25 +01003225
Sebastien Hertza76a6d42014-03-20 16:40:17 +01003226static const Breakpoint* FindFirstBreakpointForMethod(mirror::ArtMethod* m)
Sebastien Hertzed2be172014-08-19 15:33:43 +02003227 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_, Locks::breakpoint_lock_) {
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003228 for (Breakpoint& breakpoint : gBreakpoints) {
3229 if (breakpoint.Method() == m) {
Sebastien Hertza76a6d42014-03-20 16:40:17 +01003230 return &breakpoint;
3231 }
3232 }
3233 return nullptr;
3234}
3235
Mathieu Chartierd8565452015-03-26 09:41:50 -07003236bool Dbg::MethodHasAnyBreakpoints(mirror::ArtMethod* method) {
3237 ReaderMutexLock mu(Thread::Current(), *Locks::breakpoint_lock_);
3238 return FindFirstBreakpointForMethod(method) != nullptr;
3239}
3240
Sebastien Hertza76a6d42014-03-20 16:40:17 +01003241// Sanity checks all existing breakpoints on the same method.
Sebastien Hertzf3928792014-11-17 19:00:37 +01003242static void SanityCheckExistingBreakpoints(mirror::ArtMethod* m,
3243 DeoptimizationRequest::Kind deoptimization_kind)
Sebastien Hertzed2be172014-08-19 15:33:43 +02003244 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_, Locks::breakpoint_lock_) {
Sebastien Hertz4d1e9ab2014-09-18 16:03:34 +02003245 for (const Breakpoint& breakpoint : gBreakpoints) {
Sebastien Hertzf3928792014-11-17 19:00:37 +01003246 if (breakpoint.Method() == m) {
3247 CHECK_EQ(deoptimization_kind, breakpoint.GetDeoptimizationKind());
3248 }
Sebastien Hertz4d1e9ab2014-09-18 16:03:34 +02003249 }
Sebastien Hertzf3928792014-11-17 19:00:37 +01003250 instrumentation::Instrumentation* instrumentation = Runtime::Current()->GetInstrumentation();
3251 if (deoptimization_kind == DeoptimizationRequest::kFullDeoptimization) {
Sebastien Hertz4d1e9ab2014-09-18 16:03:34 +02003252 // We should have deoptimized everything but not "selectively" deoptimized this method.
Sebastien Hertzf3928792014-11-17 19:00:37 +01003253 CHECK(instrumentation->AreAllMethodsDeoptimized());
3254 CHECK(!instrumentation->IsDeoptimized(m));
3255 } else if (deoptimization_kind == DeoptimizationRequest::kSelectiveDeoptimization) {
Sebastien Hertz4d1e9ab2014-09-18 16:03:34 +02003256 // We should have "selectively" deoptimized this method.
3257 // Note: while we have not deoptimized everything for this method, we may have done it for
3258 // another event.
Sebastien Hertzf3928792014-11-17 19:00:37 +01003259 CHECK(instrumentation->IsDeoptimized(m));
3260 } else {
3261 // This method does not require deoptimization.
3262 CHECK_EQ(deoptimization_kind, DeoptimizationRequest::kNothing);
3263 CHECK(!instrumentation->IsDeoptimized(m));
3264 }
3265}
3266
Sebastien Hertzabe93e02014-12-17 16:35:50 +01003267// Returns the deoptimization kind required to set a breakpoint in a method.
3268// If a breakpoint has already been set, we also return the first breakpoint
3269// through the given 'existing_brkpt' pointer.
Sebastien Hertzf3928792014-11-17 19:00:37 +01003270static DeoptimizationRequest::Kind GetRequiredDeoptimizationKind(Thread* self,
Sebastien Hertzabe93e02014-12-17 16:35:50 +01003271 mirror::ArtMethod* m,
3272 const Breakpoint** existing_brkpt)
Sebastien Hertzf3928792014-11-17 19:00:37 +01003273 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
3274 if (!Dbg::RequiresDeoptimization()) {
3275 // We already run in interpreter-only mode so we don't need to deoptimize anything.
3276 VLOG(jdwp) << "No need for deoptimization when fully running with interpreter for method "
3277 << PrettyMethod(m);
3278 return DeoptimizationRequest::kNothing;
3279 }
Sebastien Hertzabe93e02014-12-17 16:35:50 +01003280 const Breakpoint* first_breakpoint;
Sebastien Hertzf3928792014-11-17 19:00:37 +01003281 {
3282 ReaderMutexLock mu(self, *Locks::breakpoint_lock_);
Sebastien Hertzabe93e02014-12-17 16:35:50 +01003283 first_breakpoint = FindFirstBreakpointForMethod(m);
3284 *existing_brkpt = first_breakpoint;
Sebastien Hertzf3928792014-11-17 19:00:37 +01003285 }
Sebastien Hertzabe93e02014-12-17 16:35:50 +01003286
3287 if (first_breakpoint == nullptr) {
Sebastien Hertzf3928792014-11-17 19:00:37 +01003288 // There is no breakpoint on this method yet: we need to deoptimize. If this method may be
3289 // inlined, we deoptimize everything; otherwise we deoptimize only this method.
3290 // Note: IsMethodPossiblyInlined goes into the method verifier and may cause thread suspension.
3291 // Therefore we must not hold any lock when we call it.
3292 bool need_full_deoptimization = IsMethodPossiblyInlined(self, m);
3293 if (need_full_deoptimization) {
3294 VLOG(jdwp) << "Need full deoptimization because of possible inlining of method "
3295 << PrettyMethod(m);
3296 return DeoptimizationRequest::kFullDeoptimization;
3297 } else {
3298 // We don't need to deoptimize if the method has not been compiled.
3299 ClassLinker* const class_linker = Runtime::Current()->GetClassLinker();
3300 const bool is_compiled = class_linker->GetOatMethodQuickCodeFor(m) != nullptr;
3301 if (is_compiled) {
Sebastien Hertz6963e442014-11-26 22:11:27 +01003302 // If the method may be called through its direct code pointer (without loading
3303 // its updated entrypoint), we need full deoptimization to not miss the breakpoint.
3304 if (class_linker->MayBeCalledWithDirectCodePointer(m)) {
3305 VLOG(jdwp) << "Need full deoptimization because of possible direct code call "
3306 << "into image for compiled method " << PrettyMethod(m);
3307 return DeoptimizationRequest::kFullDeoptimization;
3308 } else {
3309 VLOG(jdwp) << "Need selective deoptimization for compiled method " << PrettyMethod(m);
3310 return DeoptimizationRequest::kSelectiveDeoptimization;
3311 }
Sebastien Hertzf3928792014-11-17 19:00:37 +01003312 } else {
3313 // Method is not compiled: we don't need to deoptimize.
3314 VLOG(jdwp) << "No need for deoptimization for non-compiled method " << PrettyMethod(m);
3315 return DeoptimizationRequest::kNothing;
3316 }
3317 }
3318 } else {
3319 // There is at least one breakpoint for this method: we don't need to deoptimize.
3320 // Let's check that all breakpoints are configured the same way for deoptimization.
3321 VLOG(jdwp) << "Breakpoint already set: no deoptimization is required";
Sebastien Hertzabe93e02014-12-17 16:35:50 +01003322 DeoptimizationRequest::Kind deoptimization_kind = first_breakpoint->GetDeoptimizationKind();
Sebastien Hertzf3928792014-11-17 19:00:37 +01003323 if (kIsDebugBuild) {
3324 ReaderMutexLock mu(self, *Locks::breakpoint_lock_);
3325 SanityCheckExistingBreakpoints(m, deoptimization_kind);
3326 }
3327 return DeoptimizationRequest::kNothing;
Sebastien Hertz138dbfc2013-12-04 18:15:25 +01003328 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -07003329}
3330
Sebastien Hertza76a6d42014-03-20 16:40:17 +01003331// Installs a breakpoint at the specified location. Also indicates through the deoptimization
3332// request if we need to deoptimize.
3333void Dbg::WatchLocation(const JDWP::JdwpLocation* location, DeoptimizationRequest* req) {
3334 Thread* const self = Thread::Current();
Brian Carlstromea46f952013-07-30 01:26:50 -07003335 mirror::ArtMethod* m = FromMethodId(location->method_id);
Sebastien Hertza76a6d42014-03-20 16:40:17 +01003336 DCHECK(m != nullptr) << "No method for method id " << location->method_id;
Sebastien Hertz138dbfc2013-12-04 18:15:25 +01003337
Sebastien Hertzabe93e02014-12-17 16:35:50 +01003338 const Breakpoint* existing_breakpoint = nullptr;
3339 const DeoptimizationRequest::Kind deoptimization_kind =
3340 GetRequiredDeoptimizationKind(self, m, &existing_breakpoint);
Sebastien Hertzf3928792014-11-17 19:00:37 +01003341 req->SetKind(deoptimization_kind);
3342 if (deoptimization_kind == DeoptimizationRequest::kSelectiveDeoptimization) {
3343 req->SetMethod(m);
Sebastien Hertza76a6d42014-03-20 16:40:17 +01003344 } else {
Sebastien Hertzf3928792014-11-17 19:00:37 +01003345 CHECK(deoptimization_kind == DeoptimizationRequest::kNothing ||
3346 deoptimization_kind == DeoptimizationRequest::kFullDeoptimization);
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003347 req->SetMethod(nullptr);
Sebastien Hertz138dbfc2013-12-04 18:15:25 +01003348 }
3349
Sebastien Hertz4d1e9ab2014-09-18 16:03:34 +02003350 {
3351 WriterMutexLock mu(self, *Locks::breakpoint_lock_);
Sebastien Hertzabe93e02014-12-17 16:35:50 +01003352 // If there is at least one existing breakpoint on the same method, the new breakpoint
3353 // must have the same deoptimization kind than the existing breakpoint(s).
3354 DeoptimizationRequest::Kind breakpoint_deoptimization_kind;
3355 if (existing_breakpoint != nullptr) {
3356 breakpoint_deoptimization_kind = existing_breakpoint->GetDeoptimizationKind();
3357 } else {
3358 breakpoint_deoptimization_kind = deoptimization_kind;
3359 }
3360 gBreakpoints.push_back(Breakpoint(m, location->dex_pc, breakpoint_deoptimization_kind));
Sebastien Hertz4d1e9ab2014-09-18 16:03:34 +02003361 VLOG(jdwp) << "Set breakpoint #" << (gBreakpoints.size() - 1) << ": "
3362 << gBreakpoints[gBreakpoints.size() - 1];
3363 }
Sebastien Hertza76a6d42014-03-20 16:40:17 +01003364}
3365
3366// Uninstalls a breakpoint at the specified location. Also indicates through the deoptimization
3367// request if we need to undeoptimize.
3368void Dbg::UnwatchLocation(const JDWP::JdwpLocation* location, DeoptimizationRequest* req) {
Sebastien Hertzed2be172014-08-19 15:33:43 +02003369 WriterMutexLock mu(Thread::Current(), *Locks::breakpoint_lock_);
Sebastien Hertza76a6d42014-03-20 16:40:17 +01003370 mirror::ArtMethod* m = FromMethodId(location->method_id);
3371 DCHECK(m != nullptr) << "No method for method id " << location->method_id;
Sebastien Hertzf3928792014-11-17 19:00:37 +01003372 DeoptimizationRequest::Kind deoptimization_kind = DeoptimizationRequest::kNothing;
Sebastien Hertza76a6d42014-03-20 16:40:17 +01003373 for (size_t i = 0, e = gBreakpoints.size(); i < e; ++i) {
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003374 if (gBreakpoints[i].DexPc() == location->dex_pc && gBreakpoints[i].Method() == m) {
Sebastien Hertza76a6d42014-03-20 16:40:17 +01003375 VLOG(jdwp) << "Removed breakpoint #" << i << ": " << gBreakpoints[i];
Sebastien Hertzf3928792014-11-17 19:00:37 +01003376 deoptimization_kind = gBreakpoints[i].GetDeoptimizationKind();
3377 DCHECK_EQ(deoptimization_kind == DeoptimizationRequest::kSelectiveDeoptimization,
3378 Runtime::Current()->GetInstrumentation()->IsDeoptimized(m));
Sebastien Hertza76a6d42014-03-20 16:40:17 +01003379 gBreakpoints.erase(gBreakpoints.begin() + i);
3380 break;
3381 }
3382 }
3383 const Breakpoint* const existing_breakpoint = FindFirstBreakpointForMethod(m);
3384 if (existing_breakpoint == nullptr) {
3385 // There is no more breakpoint on this method: we need to undeoptimize.
Sebastien Hertzf3928792014-11-17 19:00:37 +01003386 if (deoptimization_kind == DeoptimizationRequest::kFullDeoptimization) {
Sebastien Hertza76a6d42014-03-20 16:40:17 +01003387 // This method required full deoptimization: we need to undeoptimize everything.
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003388 req->SetKind(DeoptimizationRequest::kFullUndeoptimization);
3389 req->SetMethod(nullptr);
Sebastien Hertzf3928792014-11-17 19:00:37 +01003390 } else if (deoptimization_kind == DeoptimizationRequest::kSelectiveDeoptimization) {
Sebastien Hertza76a6d42014-03-20 16:40:17 +01003391 // This method required selective deoptimization: we need to undeoptimize only that method.
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003392 req->SetKind(DeoptimizationRequest::kSelectiveUndeoptimization);
3393 req->SetMethod(m);
Sebastien Hertzf3928792014-11-17 19:00:37 +01003394 } else {
3395 // This method had no need for deoptimization: do nothing.
3396 CHECK_EQ(deoptimization_kind, DeoptimizationRequest::kNothing);
3397 req->SetKind(DeoptimizationRequest::kNothing);
3398 req->SetMethod(nullptr);
Sebastien Hertza76a6d42014-03-20 16:40:17 +01003399 }
3400 } else {
3401 // There is at least one breakpoint for this method: we don't need to undeoptimize.
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003402 req->SetKind(DeoptimizationRequest::kNothing);
3403 req->SetMethod(nullptr);
Sebastien Hertz4d1e9ab2014-09-18 16:03:34 +02003404 if (kIsDebugBuild) {
Sebastien Hertzf3928792014-11-17 19:00:37 +01003405 SanityCheckExistingBreakpoints(m, deoptimization_kind);
Sebastien Hertz4d1e9ab2014-09-18 16:03:34 +02003406 }
Elliott Hughes86964332012-02-15 19:37:42 -08003407 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -07003408}
3409
Daniel Mihalyieb076692014-08-22 17:33:31 +02003410bool Dbg::IsForcedInterpreterNeededForCallingImpl(Thread* thread, mirror::ArtMethod* m) {
3411 const SingleStepControl* const ssc = thread->GetSingleStepControl();
3412 if (ssc == nullptr) {
3413 // If we are not single-stepping, then we don't have to force interpreter.
3414 return false;
3415 }
3416 if (Runtime::Current()->GetInstrumentation()->InterpretOnly()) {
3417 // If we are in interpreter only mode, then we don't have to force interpreter.
3418 return false;
3419 }
3420
3421 if (!m->IsNative() && !m->IsProxyMethod()) {
3422 // If we want to step into a method, then we have to force interpreter on that call.
3423 if (ssc->GetStepDepth() == JDWP::SD_INTO) {
3424 return true;
3425 }
3426 }
3427 return false;
3428}
3429
3430bool Dbg::IsForcedInterpreterNeededForResolutionImpl(Thread* thread, mirror::ArtMethod* m) {
3431 instrumentation::Instrumentation* const instrumentation =
3432 Runtime::Current()->GetInstrumentation();
3433 // If we are in interpreter only mode, then we don't have to force interpreter.
3434 if (instrumentation->InterpretOnly()) {
3435 return false;
3436 }
3437 // We can only interpret pure Java method.
3438 if (m->IsNative() || m->IsProxyMethod()) {
3439 return false;
3440 }
3441 const SingleStepControl* const ssc = thread->GetSingleStepControl();
3442 if (ssc != nullptr) {
3443 // If we want to step into a method, then we have to force interpreter on that call.
3444 if (ssc->GetStepDepth() == JDWP::SD_INTO) {
3445 return true;
3446 }
3447 // If we are stepping out from a static initializer, by issuing a step
3448 // in or step over, that was implicitly invoked by calling a static method,
3449 // then we need to step into that method. Having a lower stack depth than
3450 // the one the single step control has indicates that the step originates
3451 // from the static initializer.
3452 if (ssc->GetStepDepth() != JDWP::SD_OUT &&
3453 ssc->GetStackDepth() > GetStackDepth(thread)) {
3454 return true;
3455 }
3456 }
3457 // There are cases where we have to force interpreter on deoptimized methods,
3458 // because in some cases the call will not be performed by invoking an entry
3459 // point that has been replaced by the deoptimization, but instead by directly
3460 // invoking the compiled code of the method, for example.
3461 return instrumentation->IsDeoptimized(m);
3462}
3463
3464bool Dbg::IsForcedInstrumentationNeededForResolutionImpl(Thread* thread, mirror::ArtMethod* m) {
Mathieu Chartier2cebb242015-04-21 16:50:40 -07003465 // The upcall can be null and in that case we don't need to do anything.
Daniel Mihalyieb076692014-08-22 17:33:31 +02003466 if (m == nullptr) {
3467 return false;
3468 }
3469 instrumentation::Instrumentation* const instrumentation =
3470 Runtime::Current()->GetInstrumentation();
3471 // If we are in interpreter only mode, then we don't have to force interpreter.
3472 if (instrumentation->InterpretOnly()) {
3473 return false;
3474 }
3475 // We can only interpret pure Java method.
3476 if (m->IsNative() || m->IsProxyMethod()) {
3477 return false;
3478 }
3479 const SingleStepControl* const ssc = thread->GetSingleStepControl();
3480 if (ssc != nullptr) {
3481 // If we are stepping out from a static initializer, by issuing a step
3482 // out, that was implicitly invoked by calling a static method, then we
3483 // need to step into the caller of that method. Having a lower stack
3484 // depth than the one the single step control has indicates that the
3485 // step originates from the static initializer.
3486 if (ssc->GetStepDepth() == JDWP::SD_OUT &&
3487 ssc->GetStackDepth() > GetStackDepth(thread)) {
3488 return true;
3489 }
3490 }
3491 // If we are returning from a static intializer, that was implicitly
3492 // invoked by calling a static method and the caller is deoptimized,
3493 // then we have to deoptimize the stack without forcing interpreter
3494 // on the static method that was called originally. This problem can
3495 // be solved easily by forcing instrumentation on the called method,
3496 // because the instrumentation exit hook will recognise the need of
3497 // stack deoptimization by calling IsForcedInterpreterNeededForUpcall.
3498 return instrumentation->IsDeoptimized(m);
3499}
3500
3501bool Dbg::IsForcedInterpreterNeededForUpcallImpl(Thread* thread, mirror::ArtMethod* m) {
Mathieu Chartier2cebb242015-04-21 16:50:40 -07003502 // The upcall can be null and in that case we don't need to do anything.
Daniel Mihalyieb076692014-08-22 17:33:31 +02003503 if (m == nullptr) {
3504 return false;
3505 }
3506 instrumentation::Instrumentation* const instrumentation =
3507 Runtime::Current()->GetInstrumentation();
3508 // If we are in interpreter only mode, then we don't have to force interpreter.
3509 if (instrumentation->InterpretOnly()) {
3510 return false;
3511 }
3512 // We can only interpret pure Java method.
3513 if (m->IsNative() || m->IsProxyMethod()) {
3514 return false;
3515 }
3516 const SingleStepControl* const ssc = thread->GetSingleStepControl();
3517 if (ssc != nullptr) {
3518 // The debugger is not interested in what is happening under the level
3519 // of the step, thus we only force interpreter when we are not below of
3520 // the step.
3521 if (ssc->GetStackDepth() >= GetStackDepth(thread)) {
3522 return true;
3523 }
3524 }
3525 // We have to require stack deoptimization if the upcall is deoptimized.
3526 return instrumentation->IsDeoptimized(m);
3527}
3528
Jeff Hao449db332013-04-12 18:30:52 -07003529// Scoped utility class to suspend a thread so that we may do tasks such as walk its stack. Doesn't
3530// cause suspension if the thread is the current thread.
3531class ScopedThreadSuspension {
3532 public:
Ian Rogers33e95662013-05-20 20:29:14 -07003533 ScopedThreadSuspension(Thread* self, JDWP::ObjectId thread_id)
Sebastien Hertz52d131d2014-03-13 16:17:40 +01003534 LOCKS_EXCLUDED(Locks::thread_list_lock_)
Ian Rogers33e95662013-05-20 20:29:14 -07003535 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) :
Ian Rogersf3d874c2014-07-17 18:52:42 -07003536 thread_(nullptr),
Jeff Hao449db332013-04-12 18:30:52 -07003537 error_(JDWP::ERR_NONE),
3538 self_suspend_(false),
Ian Rogers33e95662013-05-20 20:29:14 -07003539 other_suspend_(false) {
Jeff Hao449db332013-04-12 18:30:52 -07003540 ScopedObjectAccessUnchecked soa(self);
Sebastien Hertz69206392015-04-07 15:54:25 +02003541 thread_ = DecodeThread(soa, thread_id, &error_);
Jeff Hao449db332013-04-12 18:30:52 -07003542 if (error_ == JDWP::ERR_NONE) {
3543 if (thread_ == soa.Self()) {
3544 self_suspend_ = true;
3545 } else {
3546 soa.Self()->TransitionFromRunnableToSuspended(kWaitingForDebuggerSuspension);
Sebastien Hertz6995c602014-09-09 12:10:13 +02003547 jobject thread_peer = Dbg::GetObjectRegistry()->GetJObject(thread_id);
Jeff Hao449db332013-04-12 18:30:52 -07003548 bool timed_out;
Ian Rogers4ad5cd32014-11-11 23:08:07 -08003549 ThreadList* thread_list = Runtime::Current()->GetThreadList();
3550 Thread* suspended_thread = thread_list->SuspendThreadByPeer(thread_peer, true, true,
3551 &timed_out);
Jeff Hao449db332013-04-12 18:30:52 -07003552 CHECK_EQ(soa.Self()->TransitionFromSuspendedToRunnable(), kWaitingForDebuggerSuspension);
Ian Rogersf3d874c2014-07-17 18:52:42 -07003553 if (suspended_thread == nullptr) {
Jeff Hao449db332013-04-12 18:30:52 -07003554 // Thread terminated from under us while suspending.
3555 error_ = JDWP::ERR_INVALID_THREAD;
3556 } else {
3557 CHECK_EQ(suspended_thread, thread_);
3558 other_suspend_ = true;
3559 }
3560 }
3561 }
Elliott Hughes2435a572012-02-17 16:07:41 -08003562 }
Elliott Hughes86964332012-02-15 19:37:42 -08003563
Jeff Hao449db332013-04-12 18:30:52 -07003564 Thread* GetThread() const {
3565 return thread_;
3566 }
3567
3568 JDWP::JdwpError GetError() const {
3569 return error_;
3570 }
3571
3572 ~ScopedThreadSuspension() {
3573 if (other_suspend_) {
3574 Runtime::Current()->GetThreadList()->Resume(thread_, true);
3575 }
3576 }
3577
3578 private:
3579 Thread* thread_;
3580 JDWP::JdwpError error_;
3581 bool self_suspend_;
3582 bool other_suspend_;
3583};
3584
3585JDWP::JdwpError Dbg::ConfigureStep(JDWP::ObjectId thread_id, JDWP::JdwpStepSize step_size,
3586 JDWP::JdwpStepDepth step_depth) {
3587 Thread* self = Thread::Current();
3588 ScopedThreadSuspension sts(self, thread_id);
3589 if (sts.GetError() != JDWP::ERR_NONE) {
3590 return sts.GetError();
3591 }
3592
Sebastien Hertz597c4f02015-01-26 17:37:14 +01003593 // Work out what ArtMethod* we're in, the current line number, and how deep the stack currently
Elliott Hughes2435a572012-02-17 16:07:41 -08003594 // is for step-out.
Ian Rogers0399dde2012-06-06 17:09:28 -07003595 struct SingleStepStackVisitor : public StackVisitor {
Sebastien Hertz597c4f02015-01-26 17:37:14 +01003596 explicit SingleStepStackVisitor(Thread* thread) SHARED_LOCKS_REQUIRED(Locks::mutator_lock_)
Nicolas Geoffray8e5bd182015-05-06 11:34:34 +01003597 : StackVisitor(thread, nullptr, StackVisitor::StackWalkKind::kIncludeInlinedFrames),
3598 stack_depth(0),
3599 method(nullptr),
3600 line_number(-1) {}
Ian Rogersca190662012-06-26 15:45:57 -07003601
Ian Rogers00f7d0e2012-07-19 15:28:27 -07003602 // TODO: Enable annotalysis. We know lock is held in constructor, but abstraction confuses
3603 // annotalysis.
3604 bool VisitFrame() NO_THREAD_SAFETY_ANALYSIS {
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01003605 mirror::ArtMethod* m = GetMethod();
Ian Rogers0399dde2012-06-06 17:09:28 -07003606 if (!m->IsRuntimeMethod()) {
Sebastien Hertz597c4f02015-01-26 17:37:14 +01003607 ++stack_depth;
3608 if (method == nullptr) {
Ian Rogersef7d42f2014-01-06 12:55:46 -08003609 mirror::DexCache* dex_cache = m->GetDeclaringClass()->GetDexCache();
Sebastien Hertz597c4f02015-01-26 17:37:14 +01003610 method = m;
Ian Rogersc0542af2014-09-03 16:16:56 -07003611 if (dex_cache != nullptr) {
Ian Rogers4445a7e2012-10-05 17:19:13 -07003612 const DexFile& dex_file = *dex_cache->GetDexFile();
Sebastien Hertz597c4f02015-01-26 17:37:14 +01003613 line_number = dex_file.GetLineNumFromPC(m, GetDexPc());
Elliott Hughes2435a572012-02-17 16:07:41 -08003614 }
Elliott Hughes86964332012-02-15 19:37:42 -08003615 }
3616 }
Elliott Hughes530fa002012-03-12 11:44:49 -07003617 return true;
Elliott Hughes86964332012-02-15 19:37:42 -08003618 }
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01003619
Sebastien Hertz597c4f02015-01-26 17:37:14 +01003620 int stack_depth;
3621 mirror::ArtMethod* method;
3622 int32_t line_number;
Elliott Hughes86964332012-02-15 19:37:42 -08003623 };
Jeff Hao449db332013-04-12 18:30:52 -07003624
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01003625 Thread* const thread = sts.GetThread();
Sebastien Hertz597c4f02015-01-26 17:37:14 +01003626 SingleStepStackVisitor visitor(thread);
Ian Rogers0399dde2012-06-06 17:09:28 -07003627 visitor.WalkStack();
Elliott Hughes86964332012-02-15 19:37:42 -08003628
Elliott Hughes2435a572012-02-17 16:07:41 -08003629 // Find the dex_pc values that correspond to the current line, for line-based single-stepping.
Elliott Hughes2435a572012-02-17 16:07:41 -08003630 struct DebugCallbackContext {
Sebastien Hertz597c4f02015-01-26 17:37:14 +01003631 explicit DebugCallbackContext(SingleStepControl* single_step_control_cb,
3632 int32_t line_number_cb, const DexFile::CodeItem* code_item)
Andreas Gampe277ccbd2014-11-03 21:36:10 -08003633 : single_step_control_(single_step_control_cb), line_number_(line_number_cb),
3634 code_item_(code_item), last_pc_valid(false), last_pc(0) {
Elliott Hughes2435a572012-02-17 16:07:41 -08003635 }
3636
Andreas Gampe277ccbd2014-11-03 21:36:10 -08003637 static bool Callback(void* raw_context, uint32_t address, uint32_t line_number_cb) {
Elliott Hughes2435a572012-02-17 16:07:41 -08003638 DebugCallbackContext* context = reinterpret_cast<DebugCallbackContext*>(raw_context);
Andreas Gampe277ccbd2014-11-03 21:36:10 -08003639 if (static_cast<int32_t>(line_number_cb) == context->line_number_) {
Elliott Hughes2435a572012-02-17 16:07:41 -08003640 if (!context->last_pc_valid) {
3641 // Everything from this address until the next line change is ours.
3642 context->last_pc = address;
3643 context->last_pc_valid = true;
3644 }
3645 // Otherwise, if we're already in a valid range for this line,
3646 // just keep going (shouldn't really happen)...
Brian Carlstrom7934ac22013-07-26 10:54:15 -07003647 } else if (context->last_pc_valid) { // and the line number is new
Elliott Hughes2435a572012-02-17 16:07:41 -08003648 // Add everything from the last entry up until here to the set
3649 for (uint32_t dex_pc = context->last_pc; dex_pc < address; ++dex_pc) {
Sebastien Hertz597c4f02015-01-26 17:37:14 +01003650 context->single_step_control_->AddDexPc(dex_pc);
Elliott Hughes2435a572012-02-17 16:07:41 -08003651 }
3652 context->last_pc_valid = false;
3653 }
Brian Carlstrom7934ac22013-07-26 10:54:15 -07003654 return false; // There may be multiple entries for any given line.
Elliott Hughes2435a572012-02-17 16:07:41 -08003655 }
3656
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01003657 ~DebugCallbackContext() {
Elliott Hughes2435a572012-02-17 16:07:41 -08003658 // If the line number was the last in the position table...
3659 if (last_pc_valid) {
Sebastien Hertzbb43b432014-04-14 11:59:08 +02003660 size_t end = code_item_->insns_size_in_code_units_;
Elliott Hughes2435a572012-02-17 16:07:41 -08003661 for (uint32_t dex_pc = last_pc; dex_pc < end; ++dex_pc) {
Sebastien Hertz597c4f02015-01-26 17:37:14 +01003662 single_step_control_->AddDexPc(dex_pc);
Elliott Hughes2435a572012-02-17 16:07:41 -08003663 }
3664 }
3665 }
3666
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01003667 SingleStepControl* const single_step_control_;
3668 const int32_t line_number_;
Sebastien Hertzbb43b432014-04-14 11:59:08 +02003669 const DexFile::CodeItem* const code_item_;
Elliott Hughes2435a572012-02-17 16:07:41 -08003670 bool last_pc_valid;
3671 uint32_t last_pc;
3672 };
Sebastien Hertz597c4f02015-01-26 17:37:14 +01003673
3674 // Allocate single step.
Sebastien Hertz1558b572015-02-25 15:05:59 +01003675 SingleStepControl* single_step_control =
3676 new (std::nothrow) SingleStepControl(step_size, step_depth,
3677 visitor.stack_depth, visitor.method);
3678 if (single_step_control == nullptr) {
3679 LOG(ERROR) << "Failed to allocate SingleStepControl";
3680 return JDWP::ERR_OUT_OF_MEMORY;
3681 }
3682
Sebastien Hertz597c4f02015-01-26 17:37:14 +01003683 mirror::ArtMethod* m = single_step_control->GetMethod();
3684 const int32_t line_number = visitor.line_number;
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01003685 if (!m->IsNative()) {
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07003686 const DexFile::CodeItem* const code_item = m->GetCodeItem();
Sebastien Hertzbb43b432014-04-14 11:59:08 +02003687 DebugCallbackContext context(single_step_control, line_number, code_item);
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07003688 m->GetDexFile()->DecodeDebugInfo(code_item, m->IsStatic(), m->GetDexMethodIndex(),
Ian Rogersc0542af2014-09-03 16:16:56 -07003689 DebugCallbackContext::Callback, nullptr, &context);
Elliott Hughes3e2e1a22012-02-21 11:33:41 -08003690 }
Elliott Hughes2435a572012-02-17 16:07:41 -08003691
Sebastien Hertz597c4f02015-01-26 17:37:14 +01003692 // Activate single-step in the thread.
3693 thread->ActivateSingleStepControl(single_step_control);
Elliott Hughes86964332012-02-15 19:37:42 -08003694
Elliott Hughes2435a572012-02-17 16:07:41 -08003695 if (VLOG_IS_ON(jdwp)) {
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01003696 VLOG(jdwp) << "Single-step thread: " << *thread;
Sebastien Hertz597c4f02015-01-26 17:37:14 +01003697 VLOG(jdwp) << "Single-step step size: " << single_step_control->GetStepSize();
3698 VLOG(jdwp) << "Single-step step depth: " << single_step_control->GetStepDepth();
3699 VLOG(jdwp) << "Single-step current method: " << PrettyMethod(single_step_control->GetMethod());
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01003700 VLOG(jdwp) << "Single-step current line: " << line_number;
Sebastien Hertz597c4f02015-01-26 17:37:14 +01003701 VLOG(jdwp) << "Single-step current stack depth: " << single_step_control->GetStackDepth();
Elliott Hughes2435a572012-02-17 16:07:41 -08003702 VLOG(jdwp) << "Single-step dex_pc values:";
Sebastien Hertz597c4f02015-01-26 17:37:14 +01003703 for (uint32_t dex_pc : single_step_control->GetDexPcs()) {
Sebastien Hertzbb43b432014-04-14 11:59:08 +02003704 VLOG(jdwp) << StringPrintf(" %#x", dex_pc);
Elliott Hughes2435a572012-02-17 16:07:41 -08003705 }
3706 }
3707
3708 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07003709}
3710
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01003711void Dbg::UnconfigureStep(JDWP::ObjectId thread_id) {
3712 ScopedObjectAccessUnchecked soa(Thread::Current());
Ian Rogersc0542af2014-09-03 16:16:56 -07003713 JDWP::JdwpError error;
3714 Thread* thread = DecodeThread(soa, thread_id, &error);
Sebastien Hertz87118ed2013-11-26 17:57:18 +01003715 if (error == JDWP::ERR_NONE) {
Sebastien Hertz597c4f02015-01-26 17:37:14 +01003716 thread->DeactivateSingleStepControl();
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01003717 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -07003718}
3719
Elliott Hughes45651fd2012-02-21 15:48:20 -08003720static char JdwpTagToShortyChar(JDWP::JdwpTag tag) {
3721 switch (tag) {
3722 default:
3723 LOG(FATAL) << "unknown JDWP tag: " << PrintableChar(tag);
Ian Rogersfc787ec2014-10-09 21:56:44 -07003724 UNREACHABLE();
Elliott Hughes45651fd2012-02-21 15:48:20 -08003725
3726 // Primitives.
3727 case JDWP::JT_BYTE: return 'B';
3728 case JDWP::JT_CHAR: return 'C';
3729 case JDWP::JT_FLOAT: return 'F';
3730 case JDWP::JT_DOUBLE: return 'D';
3731 case JDWP::JT_INT: return 'I';
3732 case JDWP::JT_LONG: return 'J';
3733 case JDWP::JT_SHORT: return 'S';
3734 case JDWP::JT_VOID: return 'V';
3735 case JDWP::JT_BOOLEAN: return 'Z';
3736
3737 // Reference types.
3738 case JDWP::JT_ARRAY:
3739 case JDWP::JT_OBJECT:
3740 case JDWP::JT_STRING:
3741 case JDWP::JT_THREAD:
3742 case JDWP::JT_THREAD_GROUP:
3743 case JDWP::JT_CLASS_LOADER:
3744 case JDWP::JT_CLASS_OBJECT:
3745 return 'L';
3746 }
3747}
3748
Elliott Hughes88d63092013-01-09 09:55:54 -08003749JDWP::JdwpError Dbg::InvokeMethod(JDWP::ObjectId thread_id, JDWP::ObjectId object_id,
3750 JDWP::RefTypeId class_id, JDWP::MethodId method_id,
Ian Rogers00f7d0e2012-07-19 15:28:27 -07003751 uint32_t arg_count, uint64_t* arg_values,
3752 JDWP::JdwpTag* arg_types, uint32_t options,
3753 JDWP::JdwpTag* pResultTag, uint64_t* pResultValue,
3754 JDWP::ObjectId* pExceptionId) {
Elliott Hughesd07986f2011-12-06 18:27:45 -08003755 ThreadList* thread_list = Runtime::Current()->GetThreadList();
3756
Ian Rogersc0542af2014-09-03 16:16:56 -07003757 Thread* targetThread = nullptr;
Sebastien Hertz1558b572015-02-25 15:05:59 +01003758 std::unique_ptr<DebugInvokeReq> req;
Ian Rogers00f7d0e2012-07-19 15:28:27 -07003759 Thread* self = Thread::Current();
Elliott Hughesd07986f2011-12-06 18:27:45 -08003760 {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07003761 ScopedObjectAccessUnchecked soa(self);
Ian Rogersc0542af2014-09-03 16:16:56 -07003762 JDWP::JdwpError error;
3763 targetThread = DecodeThread(soa, thread_id, &error);
Elliott Hughes221229c2013-01-08 18:17:50 -08003764 if (error != JDWP::ERR_NONE) {
3765 LOG(ERROR) << "InvokeMethod request for invalid thread id " << thread_id;
3766 return error;
Elliott Hughesd07986f2011-12-06 18:27:45 -08003767 }
Sebastien Hertz1558b572015-02-25 15:05:59 +01003768 if (targetThread->GetInvokeReq() != nullptr) {
3769 // Thread is already invoking a method on behalf of the debugger.
3770 LOG(ERROR) << "InvokeMethod request for thread already invoking a method: " << *targetThread;
3771 return JDWP::ERR_ALREADY_INVOKING;
3772 }
3773 if (!targetThread->IsReadyForDebugInvoke()) {
3774 // Thread is not suspended by an event so it cannot invoke a method.
Elliott Hughesd07986f2011-12-06 18:27:45 -08003775 LOG(ERROR) << "InvokeMethod request for thread not stopped by event: " << *targetThread;
3776 return JDWP::ERR_INVALID_THREAD;
3777 }
3778
3779 /*
3780 * We currently have a bug where we don't successfully resume the
3781 * target thread if the suspend count is too deep. We're expected to
3782 * require one "resume" for each "suspend", but when asked to execute
3783 * a method we have to resume fully and then re-suspend it back to the
3784 * same level. (The easiest way to cause this is to type "suspend"
3785 * multiple times in jdb.)
3786 *
3787 * It's unclear what this means when the event specifies "resume all"
3788 * and some threads are suspended more deeply than others. This is
3789 * a rare problem, so for now we just prevent it from hanging forever
3790 * by rejecting the method invocation request. Without this, we will
3791 * be stuck waiting on a suspended thread.
3792 */
Ian Rogers00f7d0e2012-07-19 15:28:27 -07003793 int suspend_count;
3794 {
Ian Rogers50b35e22012-10-04 10:09:15 -07003795 MutexLock mu2(soa.Self(), *Locks::thread_suspend_count_lock_);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07003796 suspend_count = targetThread->GetSuspendCount();
3797 }
Elliott Hughesd07986f2011-12-06 18:27:45 -08003798 if (suspend_count > 1) {
3799 LOG(ERROR) << *targetThread << " suspend count too deep for method invocation: " << suspend_count;
Brian Carlstrom7934ac22013-07-26 10:54:15 -07003800 return JDWP::ERR_THREAD_SUSPENDED; // Probably not expected here.
Elliott Hughesd07986f2011-12-06 18:27:45 -08003801 }
3802
Ian Rogersc0542af2014-09-03 16:16:56 -07003803 mirror::Object* receiver = gRegistry->Get<mirror::Object*>(object_id, &error);
3804 if (error != JDWP::ERR_NONE) {
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08003805 return JDWP::ERR_INVALID_OBJECT;
3806 }
Elliott Hughes45651fd2012-02-21 15:48:20 -08003807
Sebastien Hertz1558b572015-02-25 15:05:59 +01003808 gRegistry->Get<mirror::Object*>(thread_id, &error);
Ian Rogersc0542af2014-09-03 16:16:56 -07003809 if (error != JDWP::ERR_NONE) {
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08003810 return JDWP::ERR_INVALID_OBJECT;
3811 }
Elliott Hughes45651fd2012-02-21 15:48:20 -08003812
Ian Rogersc0542af2014-09-03 16:16:56 -07003813 mirror::Class* c = DecodeClass(class_id, &error);
3814 if (c == nullptr) {
3815 return error;
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08003816 }
Elliott Hughes45651fd2012-02-21 15:48:20 -08003817
Brian Carlstromea46f952013-07-30 01:26:50 -07003818 mirror::ArtMethod* m = FromMethodId(method_id);
Ian Rogersc0542af2014-09-03 16:16:56 -07003819 if (m->IsStatic() != (receiver == nullptr)) {
Elliott Hughes45651fd2012-02-21 15:48:20 -08003820 return JDWP::ERR_INVALID_METHODID;
3821 }
3822 if (m->IsStatic()) {
3823 if (m->GetDeclaringClass() != c) {
3824 return JDWP::ERR_INVALID_METHODID;
3825 }
3826 } else {
3827 if (!m->GetDeclaringClass()->IsAssignableFrom(c)) {
3828 return JDWP::ERR_INVALID_METHODID;
3829 }
3830 }
3831
3832 // Check the argument list matches the method.
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07003833 uint32_t shorty_len = 0;
3834 const char* shorty = m->GetShorty(&shorty_len);
3835 if (shorty_len - 1 != arg_count) {
Elliott Hughes45651fd2012-02-21 15:48:20 -08003836 return JDWP::ERR_ILLEGAL_ARGUMENT;
3837 }
Elliott Hughes09201632013-04-15 15:50:07 -07003838
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07003839 {
3840 StackHandleScope<3> hs(soa.Self());
Ian Rogersa0485602014-12-02 15:48:04 -08003841 HandleWrapper<mirror::ArtMethod> h_m(hs.NewHandleWrapper(&m));
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07003842 HandleWrapper<mirror::Object> h_obj(hs.NewHandleWrapper(&receiver));
3843 HandleWrapper<mirror::Class> h_klass(hs.NewHandleWrapper(&c));
3844 const DexFile::TypeList* types = m->GetParameterTypeList();
3845 for (size_t i = 0; i < arg_count; ++i) {
3846 if (shorty[i + 1] != JdwpTagToShortyChar(arg_types[i])) {
Elliott Hughes09201632013-04-15 15:50:07 -07003847 return JDWP::ERR_ILLEGAL_ARGUMENT;
3848 }
3849
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07003850 if (shorty[i + 1] == 'L') {
3851 // Did we really get an argument of an appropriate reference type?
Ian Rogersa0485602014-12-02 15:48:04 -08003852 mirror::Class* parameter_type =
3853 h_m->GetClassFromTypeIndex(types->GetTypeItem(i).type_idx_, true);
Ian Rogersc0542af2014-09-03 16:16:56 -07003854 mirror::Object* argument = gRegistry->Get<mirror::Object*>(arg_values[i], &error);
3855 if (error != JDWP::ERR_NONE) {
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07003856 return JDWP::ERR_INVALID_OBJECT;
3857 }
Ian Rogersc0542af2014-09-03 16:16:56 -07003858 if (argument != nullptr && !argument->InstanceOf(parameter_type)) {
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07003859 return JDWP::ERR_ILLEGAL_ARGUMENT;
3860 }
3861
3862 // Turn the on-the-wire ObjectId into a jobject.
3863 jvalue& v = reinterpret_cast<jvalue&>(arg_values[i]);
3864 v.l = gRegistry->GetJObject(arg_values[i]);
3865 }
Elliott Hughes09201632013-04-15 15:50:07 -07003866 }
Elliott Hughes45651fd2012-02-21 15:48:20 -08003867 }
3868
Sebastien Hertz1558b572015-02-25 15:05:59 +01003869 // Allocates a DebugInvokeReq.
3870 req.reset(new (std::nothrow) DebugInvokeReq(receiver, c, m, options, arg_values, arg_count));
3871 if (req.get() == nullptr) {
3872 LOG(ERROR) << "Failed to allocate DebugInvokeReq";
3873 return JDWP::ERR_OUT_OF_MEMORY;
3874 }
3875
3876 // Attach the DebugInvokeReq to the target thread so it executes the method when
3877 // it is resumed. Once the invocation completes, it will detach it and signal us
3878 // before suspending itself.
3879 targetThread->SetDebugInvokeReq(req.get());
Elliott Hughesd07986f2011-12-06 18:27:45 -08003880 }
3881
3882 // The fact that we've released the thread list lock is a bit risky --- if the thread goes
3883 // away we're sitting high and dry -- but we must release this before the ResumeAllThreads
3884 // call, and it's unwise to hold it during WaitForSuspend.
3885
3886 {
3887 /*
3888 * We change our (JDWP thread) status, which should be THREAD_RUNNING,
Elliott Hughes81ff3182012-03-23 20:35:56 -07003889 * so we can suspend for a GC if the invoke request causes us to
Elliott Hughesd07986f2011-12-06 18:27:45 -08003890 * run out of memory. It's also a good idea to change it before locking
3891 * the invokeReq mutex, although that should never be held for long.
3892 */
Ian Rogers00f7d0e2012-07-19 15:28:27 -07003893 self->TransitionFromRunnableToSuspended(kWaitingForDebuggerSend);
Elliott Hughesd07986f2011-12-06 18:27:45 -08003894
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08003895 VLOG(jdwp) << " Transferring control to event thread";
Elliott Hughesd07986f2011-12-06 18:27:45 -08003896 {
Sebastien Hertzd38667a2013-11-25 15:43:54 +01003897 MutexLock mu(self, req->lock);
Elliott Hughesd07986f2011-12-06 18:27:45 -08003898
3899 if ((options & JDWP::INVOKE_SINGLE_THREADED) == 0) {
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08003900 VLOG(jdwp) << " Resuming all threads";
Ian Rogers00f7d0e2012-07-19 15:28:27 -07003901 thread_list->UndoDebuggerSuspensions();
Elliott Hughesd07986f2011-12-06 18:27:45 -08003902 } else {
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08003903 VLOG(jdwp) << " Resuming event thread only";
Elliott Hughesd07986f2011-12-06 18:27:45 -08003904 thread_list->Resume(targetThread, true);
3905 }
3906
Sebastien Hertz2bf93f42015-01-09 18:44:05 +01003907 // The target thread is resumed but needs the JDWP token we're holding.
3908 // We release it now and will acquire it again when the invocation is
3909 // complete and the target thread suspends itself.
3910 gJdwpState->ReleaseJdwpTokenForCommand();
3911
Elliott Hughesd07986f2011-12-06 18:27:45 -08003912 // Wait for the request to finish executing.
Sebastien Hertz1558b572015-02-25 15:05:59 +01003913 while (targetThread->GetInvokeReq() != nullptr) {
Sebastien Hertzd38667a2013-11-25 15:43:54 +01003914 req->cond.Wait(self);
Elliott Hughesd07986f2011-12-06 18:27:45 -08003915 }
3916 }
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08003917 VLOG(jdwp) << " Control has returned from event thread";
Elliott Hughesd07986f2011-12-06 18:27:45 -08003918
3919 /* wait for thread to re-suspend itself */
Brian Carlstromdf629502013-07-17 22:39:56 -07003920 SuspendThread(thread_id, false /* request_suspension */);
Sebastien Hertz2bf93f42015-01-09 18:44:05 +01003921
3922 // Now the thread is suspended again, we can re-acquire the JDWP token.
3923 gJdwpState->AcquireJdwpTokenForCommand();
3924
Ian Rogers00f7d0e2012-07-19 15:28:27 -07003925 self->TransitionFromSuspendedToRunnable();
Elliott Hughesd07986f2011-12-06 18:27:45 -08003926 }
3927
3928 /*
3929 * Suspend the threads. We waited for the target thread to suspend
3930 * itself, so all we need to do is suspend the others.
3931 *
Sebastien Hertz2bf93f42015-01-09 18:44:05 +01003932 * The SuspendAllForDebugger() call will double-suspend the event thread,
Elliott Hughesd07986f2011-12-06 18:27:45 -08003933 * so we want to resume the target thread once to keep the books straight.
3934 */
3935 if ((options & JDWP::INVOKE_SINGLE_THREADED) == 0) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07003936 self->TransitionFromRunnableToSuspended(kWaitingForDebuggerSuspension);
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08003937 VLOG(jdwp) << " Suspending all threads";
Ian Rogers00f7d0e2012-07-19 15:28:27 -07003938 thread_list->SuspendAllForDebugger();
3939 self->TransitionFromSuspendedToRunnable();
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08003940 VLOG(jdwp) << " Resuming event thread to balance the count";
Elliott Hughesd07986f2011-12-06 18:27:45 -08003941 thread_list->Resume(targetThread, true);
3942 }
3943
3944 // Copy the result.
3945 *pResultTag = req->result_tag;
Sebastien Hertz1558b572015-02-25 15:05:59 +01003946 *pResultValue = req->result_value;
Elliott Hughesd07986f2011-12-06 18:27:45 -08003947 *pExceptionId = req->exception;
3948 return req->error;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07003949}
3950
3951void Dbg::ExecuteMethod(DebugInvokeReq* pReq) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07003952 ScopedObjectAccess soa(Thread::Current());
Elliott Hughesd07986f2011-12-06 18:27:45 -08003953
Elliott Hughes81ff3182012-03-23 20:35:56 -07003954 // We can be called while an exception is pending. We need
Elliott Hughesd07986f2011-12-06 18:27:45 -08003955 // to preserve that across the method invocation.
Sebastien Hertz1558b572015-02-25 15:05:59 +01003956 StackHandleScope<4> hs(soa.Self());
3957 auto old_exception = hs.NewHandle<mirror::Throwable>(soa.Self()->GetException());
3958 soa.Self()->ClearException();
Elliott Hughesd07986f2011-12-06 18:27:45 -08003959
3960 // Translate the method through the vtable, unless the debugger wants to suppress it.
Sebastien Hertz1558b572015-02-25 15:05:59 +01003961 MutableHandle<mirror::ArtMethod> m(hs.NewHandle(pReq->method.Read()));
3962 if ((pReq->options & JDWP::INVOKE_NONVIRTUAL) == 0 && pReq->receiver.Read() != nullptr) {
3963 mirror::ArtMethod* actual_method = pReq->klass.Read()->FindVirtualMethodForVirtualOrInterface(m.Get());
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003964 if (actual_method != m.Get()) {
Sebastien Hertz1558b572015-02-25 15:05:59 +01003965 VLOG(jdwp) << "ExecuteMethod translated " << PrettyMethod(m.Get())
3966 << " to " << PrettyMethod(actual_method);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003967 m.Assign(actual_method);
Elliott Hughes45651fd2012-02-21 15:48:20 -08003968 }
Elliott Hughesd07986f2011-12-06 18:27:45 -08003969 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003970 VLOG(jdwp) << "ExecuteMethod " << PrettyMethod(m.Get())
Sebastien Hertz1558b572015-02-25 15:05:59 +01003971 << " receiver=" << pReq->receiver.Read()
Sebastien Hertzd38667a2013-11-25 15:43:54 +01003972 << " arg_count=" << pReq->arg_count;
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003973 CHECK(m.Get() != nullptr);
Elliott Hughesd07986f2011-12-06 18:27:45 -08003974
3975 CHECK_EQ(sizeof(jvalue), sizeof(uint64_t));
3976
Jeff Hao39b6c242015-05-19 20:30:23 -07003977 ScopedLocalRef<jobject> ref(soa.Env(), soa.AddLocalReference<jobject>(pReq->receiver.Read()));
3978 JValue result = InvokeWithJValues(soa, ref.get(), soa.EncodeMethod(m.Get()),
Sebastien Hertz1558b572015-02-25 15:05:59 +01003979 reinterpret_cast<jvalue*>(pReq->arg_values));
Elliott Hughesd07986f2011-12-06 18:27:45 -08003980
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07003981 pReq->result_tag = BasicTagFromDescriptor(m.Get()->GetShorty());
Sebastien Hertz1558b572015-02-25 15:05:59 +01003982 const bool is_object_result = (pReq->result_tag == JDWP::JT_OBJECT);
3983 Handle<mirror::Object> object_result = hs.NewHandle(is_object_result ? result.GetL() : nullptr);
3984 Handle<mirror::Throwable> exception = hs.NewHandle(soa.Self()->GetException());
3985 soa.Self()->ClearException();
Sebastien Hertz261bc042015-04-08 09:36:07 +02003986 pReq->exception = gRegistry->Add(exception);
Elliott Hughesd07986f2011-12-06 18:27:45 -08003987 if (pReq->exception != 0) {
Sebastien Hertz1558b572015-02-25 15:05:59 +01003988 VLOG(jdwp) << " JDWP invocation returning with exception=" << exception.Get()
3989 << " " << exception->Dump();
3990 pReq->result_value = 0;
3991 } else if (is_object_result) {
Elliott Hughesd07986f2011-12-06 18:27:45 -08003992 /* if no exception thrown, examine object result more closely */
Sebastien Hertz1558b572015-02-25 15:05:59 +01003993 JDWP::JdwpTag new_tag = TagFromObject(soa, object_result.Get());
Elliott Hughesd07986f2011-12-06 18:27:45 -08003994 if (new_tag != pReq->result_tag) {
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08003995 VLOG(jdwp) << " JDWP promoted result from " << pReq->result_tag << " to " << new_tag;
Elliott Hughesd07986f2011-12-06 18:27:45 -08003996 pReq->result_tag = new_tag;
3997 }
3998
Sebastien Hertz1558b572015-02-25 15:05:59 +01003999 // Register the object in the registry and reference its ObjectId. This ensures
4000 // GC safety and prevents from accessing stale reference if the object is moved.
4001 pReq->result_value = gRegistry->Add(object_result.Get());
4002 } else {
4003 // Primitive result.
4004 DCHECK(IsPrimitiveTag(pReq->result_tag));
4005 pReq->result_value = result.GetJ();
Elliott Hughesd07986f2011-12-06 18:27:45 -08004006 }
4007
Ian Rogersc0542af2014-09-03 16:16:56 -07004008 if (old_exception.Get() != nullptr) {
Nicolas Geoffray14691c52015-03-05 10:40:17 +00004009 soa.Self()->SetException(old_exception.Get());
Elliott Hughesd07986f2011-12-06 18:27:45 -08004010 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -07004011}
4012
Elliott Hughesd07986f2011-12-06 18:27:45 -08004013/*
Elliott Hughes4b9702c2013-02-20 18:13:24 -08004014 * "request" contains a full JDWP packet, possibly with multiple chunks. We
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07004015 * need to process each, accumulate the replies, and ship the whole thing
4016 * back.
4017 *
4018 * Returns "true" if we have a reply. The reply buffer is newly allocated,
4019 * and includes the chunk type/length, followed by the data.
4020 *
Elliott Hughes3d30d9b2011-12-07 17:35:48 -08004021 * OLD-TODO: we currently assume that the request and reply include a single
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07004022 * chunk. If this becomes inconvenient we will need to adapt.
4023 */
Ian Rogersc0542af2014-09-03 16:16:56 -07004024bool Dbg::DdmHandlePacket(JDWP::Request* request, uint8_t** pReplyBuf, int* pReplyLen) {
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07004025 Thread* self = Thread::Current();
4026 JNIEnv* env = self->GetJniEnv();
4027
Ian Rogersc0542af2014-09-03 16:16:56 -07004028 uint32_t type = request->ReadUnsigned32("type");
4029 uint32_t length = request->ReadUnsigned32("length");
Elliott Hughes4b9702c2013-02-20 18:13:24 -08004030
4031 // Create a byte[] corresponding to 'request'.
Ian Rogersc0542af2014-09-03 16:16:56 -07004032 size_t request_length = request->size();
Elliott Hughes4b9702c2013-02-20 18:13:24 -08004033 ScopedLocalRef<jbyteArray> dataArray(env, env->NewByteArray(request_length));
Ian Rogersc0542af2014-09-03 16:16:56 -07004034 if (dataArray.get() == nullptr) {
Elliott Hughes4b9702c2013-02-20 18:13:24 -08004035 LOG(WARNING) << "byte[] allocation failed: " << request_length;
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07004036 env->ExceptionClear();
4037 return false;
4038 }
Ian Rogersc0542af2014-09-03 16:16:56 -07004039 env->SetByteArrayRegion(dataArray.get(), 0, request_length,
4040 reinterpret_cast<const jbyte*>(request->data()));
4041 request->Skip(request_length);
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07004042
4043 // Run through and find all chunks. [Currently just find the first.]
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004044 ScopedByteArrayRO contents(env, dataArray.get());
Elliott Hughes4b9702c2013-02-20 18:13:24 -08004045 if (length != request_length) {
Ian Rogersef7d42f2014-01-06 12:55:46 -08004046 LOG(WARNING) << StringPrintf("bad chunk found (len=%u pktLen=%zd)", length, request_length);
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07004047 return false;
4048 }
4049
4050 // Call "private static Chunk dispatch(int type, byte[] data, int offset, int length)".
Elliott Hugheseac76672012-05-24 21:56:51 -07004051 ScopedLocalRef<jobject> chunk(env, env->CallStaticObjectMethod(WellKnownClasses::org_apache_harmony_dalvik_ddmc_DdmServer,
4052 WellKnownClasses::org_apache_harmony_dalvik_ddmc_DdmServer_dispatch,
Elliott Hughes4b9702c2013-02-20 18:13:24 -08004053 type, dataArray.get(), 0, length));
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07004054 if (env->ExceptionCheck()) {
4055 LOG(INFO) << StringPrintf("Exception thrown by dispatcher for 0x%08x", type);
4056 env->ExceptionDescribe();
4057 env->ExceptionClear();
4058 return false;
4059 }
4060
Ian Rogersc0542af2014-09-03 16:16:56 -07004061 if (chunk.get() == nullptr) {
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07004062 return false;
4063 }
4064
4065 /*
4066 * Pull the pieces out of the chunk. We copy the results into a
4067 * newly-allocated buffer that the caller can free. We don't want to
4068 * continue using the Chunk object because nothing has a reference to it.
4069 *
4070 * We could avoid this by returning type/data/offset/length and having
4071 * the caller be aware of the object lifetime issues, but that
Elliott Hughes81ff3182012-03-23 20:35:56 -07004072 * integrates the JDWP code more tightly into the rest of the runtime, and doesn't work
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07004073 * if we have responses for multiple chunks.
4074 *
4075 * So we're pretty much stuck with copying data around multiple times.
4076 */
Elliott Hugheseac76672012-05-24 21:56:51 -07004077 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 -08004078 jint offset = env->GetIntField(chunk.get(), WellKnownClasses::org_apache_harmony_dalvik_ddmc_Chunk_offset);
Elliott Hugheseac76672012-05-24 21:56:51 -07004079 length = env->GetIntField(chunk.get(), WellKnownClasses::org_apache_harmony_dalvik_ddmc_Chunk_length);
Elliott Hugheseac76672012-05-24 21:56:51 -07004080 type = env->GetIntField(chunk.get(), WellKnownClasses::org_apache_harmony_dalvik_ddmc_Chunk_type);
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07004081
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08004082 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 -07004083 if (length == 0 || replyData.get() == nullptr) {
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07004084 return false;
4085 }
4086
Elliott Hughes4b9702c2013-02-20 18:13:24 -08004087 const int kChunkHdrLen = 8;
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07004088 uint8_t* reply = new uint8_t[length + kChunkHdrLen];
Ian Rogersc0542af2014-09-03 16:16:56 -07004089 if (reply == nullptr) {
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07004090 LOG(WARNING) << "malloc failed: " << (length + kChunkHdrLen);
4091 return false;
4092 }
Elliott Hughesf7c3b662011-10-27 12:04:56 -07004093 JDWP::Set4BE(reply + 0, type);
4094 JDWP::Set4BE(reply + 4, length);
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004095 env->GetByteArrayRegion(replyData.get(), offset, length, reinterpret_cast<jbyte*>(reply + kChunkHdrLen));
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07004096
4097 *pReplyBuf = reply;
4098 *pReplyLen = length + kChunkHdrLen;
4099
Elliott Hughes4b9702c2013-02-20 18:13:24 -08004100 VLOG(jdwp) << StringPrintf("dvmHandleDdm returning type=%.4s %p len=%d", reinterpret_cast<char*>(reply), reply, length);
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07004101 return true;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07004102}
4103
Elliott Hughesa2155262011-11-16 16:26:58 -08004104void Dbg::DdmBroadcast(bool connect) {
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08004105 VLOG(jdwp) << "Broadcasting DDM " << (connect ? "connect" : "disconnect") << "...";
Elliott Hughes47fce012011-10-25 18:37:19 -07004106
4107 Thread* self = Thread::Current();
Ian Rogers50b35e22012-10-04 10:09:15 -07004108 if (self->GetState() != kRunnable) {
4109 LOG(ERROR) << "DDM broadcast in thread state " << self->GetState();
4110 /* try anyway? */
Elliott Hughes47fce012011-10-25 18:37:19 -07004111 }
4112
4113 JNIEnv* env = self->GetJniEnv();
Elliott Hughes47fce012011-10-25 18:37:19 -07004114 jint event = connect ? 1 /*DdmServer.CONNECTED*/ : 2 /*DdmServer.DISCONNECTED*/;
Elliott Hugheseac76672012-05-24 21:56:51 -07004115 env->CallStaticVoidMethod(WellKnownClasses::org_apache_harmony_dalvik_ddmc_DdmServer,
4116 WellKnownClasses::org_apache_harmony_dalvik_ddmc_DdmServer_broadcast,
4117 event);
Elliott Hughes47fce012011-10-25 18:37:19 -07004118 if (env->ExceptionCheck()) {
4119 LOG(ERROR) << "DdmServer.broadcast " << event << " failed";
4120 env->ExceptionDescribe();
4121 env->ExceptionClear();
4122 }
4123}
4124
Elliott Hughes872d4ec2011-10-21 17:07:15 -07004125void Dbg::DdmConnected() {
Elliott Hughesa2155262011-11-16 16:26:58 -08004126 Dbg::DdmBroadcast(true);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07004127}
4128
4129void Dbg::DdmDisconnected() {
Elliott Hughesa2155262011-11-16 16:26:58 -08004130 Dbg::DdmBroadcast(false);
Elliott Hughes47fce012011-10-25 18:37:19 -07004131 gDdmThreadNotification = false;
4132}
4133
4134/*
Elliott Hughes82188472011-11-07 18:11:48 -08004135 * Send a notification when a thread starts, stops, or changes its name.
Elliott Hughes47fce012011-10-25 18:37:19 -07004136 *
4137 * Because we broadcast the full set of threads when the notifications are
4138 * first enabled, it's possible for "thread" to be actively executing.
4139 */
Elliott Hughes82188472011-11-07 18:11:48 -08004140void Dbg::DdmSendThreadNotification(Thread* t, uint32_t type) {
Elliott Hughes47fce012011-10-25 18:37:19 -07004141 if (!gDdmThreadNotification) {
4142 return;
4143 }
4144
Elliott Hughes82188472011-11-07 18:11:48 -08004145 if (type == CHUNK_TYPE("THDE")) {
Elliott Hughes47fce012011-10-25 18:37:19 -07004146 uint8_t buf[4];
Ian Rogersd9c4fc92013-10-01 19:45:43 -07004147 JDWP::Set4BE(&buf[0], t->GetThreadId());
Elliott Hughes47fce012011-10-25 18:37:19 -07004148 Dbg::DdmSendChunk(CHUNK_TYPE("THDE"), 4, buf);
Elliott Hughes82188472011-11-07 18:11:48 -08004149 } else {
4150 CHECK(type == CHUNK_TYPE("THCR") || type == CHUNK_TYPE("THNM")) << type;
Ian Rogers00f7d0e2012-07-19 15:28:27 -07004151 ScopedObjectAccessUnchecked soa(Thread::Current());
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004152 StackHandleScope<1> hs(soa.Self());
4153 Handle<mirror::String> name(hs.NewHandle(t->GetThreadName(soa)));
Ian Rogersc0542af2014-09-03 16:16:56 -07004154 size_t char_count = (name.Get() != nullptr) ? name->GetLength() : 0;
Jeff Hao848f70a2014-01-15 13:49:50 -08004155 const jchar* chars = (name.Get() != nullptr) ? name->GetValue() : nullptr;
Elliott Hughes82188472011-11-07 18:11:48 -08004156
Elliott Hughes21f32d72011-11-09 17:44:13 -08004157 std::vector<uint8_t> bytes;
Ian Rogersd9c4fc92013-10-01 19:45:43 -07004158 JDWP::Append4BE(bytes, t->GetThreadId());
Elliott Hughes545a0642011-11-08 19:10:03 -08004159 JDWP::AppendUtf16BE(bytes, chars, char_count);
Elliott Hughes21f32d72011-11-09 17:44:13 -08004160 CHECK_EQ(bytes.size(), char_count*2 + sizeof(uint32_t)*2);
4161 Dbg::DdmSendChunk(type, bytes);
Elliott Hughes47fce012011-10-25 18:37:19 -07004162 }
4163}
4164
Elliott Hughes47fce012011-10-25 18:37:19 -07004165void Dbg::DdmSetThreadNotification(bool enable) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07004166 // Enable/disable thread notifications.
Elliott Hughes47fce012011-10-25 18:37:19 -07004167 gDdmThreadNotification = enable;
4168 if (enable) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07004169 // Suspend the VM then post thread start notifications for all threads. Threads attaching will
4170 // see a suspension in progress and block until that ends. They then post their own start
4171 // notification.
4172 SuspendVM();
4173 std::list<Thread*> threads;
Ian Rogers50b35e22012-10-04 10:09:15 -07004174 Thread* self = Thread::Current();
Ian Rogers00f7d0e2012-07-19 15:28:27 -07004175 {
Ian Rogers50b35e22012-10-04 10:09:15 -07004176 MutexLock mu(self, *Locks::thread_list_lock_);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07004177 threads = Runtime::Current()->GetThreadList()->GetList();
4178 }
4179 {
Ian Rogers50b35e22012-10-04 10:09:15 -07004180 ScopedObjectAccess soa(self);
Mathieu Chartier02e25112013-08-14 16:14:24 -07004181 for (Thread* thread : threads) {
4182 Dbg::DdmSendThreadNotification(thread, CHUNK_TYPE("THCR"));
Ian Rogers00f7d0e2012-07-19 15:28:27 -07004183 }
4184 }
4185 ResumeVM();
Elliott Hughes47fce012011-10-25 18:37:19 -07004186 }
4187}
4188
Elliott Hughesa2155262011-11-16 16:26:58 -08004189void Dbg::PostThreadStartOrStop(Thread* t, uint32_t type) {
Elliott Hughesc0f09332012-03-26 13:27:06 -07004190 if (IsDebuggerActive()) {
Sebastien Hertz6995c602014-09-09 12:10:13 +02004191 gJdwpState->PostThreadChange(t, type == CHUNK_TYPE("THCR"));
Elliott Hughes47fce012011-10-25 18:37:19 -07004192 }
Elliott Hughes82188472011-11-07 18:11:48 -08004193 Dbg::DdmSendThreadNotification(t, type);
Elliott Hughes47fce012011-10-25 18:37:19 -07004194}
4195
4196void Dbg::PostThreadStart(Thread* t) {
Elliott Hughesa2155262011-11-16 16:26:58 -08004197 Dbg::PostThreadStartOrStop(t, CHUNK_TYPE("THCR"));
Elliott Hughes47fce012011-10-25 18:37:19 -07004198}
4199
4200void Dbg::PostThreadDeath(Thread* t) {
Elliott Hughesa2155262011-11-16 16:26:58 -08004201 Dbg::PostThreadStartOrStop(t, CHUNK_TYPE("THDE"));
Elliott Hughes872d4ec2011-10-21 17:07:15 -07004202}
4203
Elliott Hughes82188472011-11-07 18:11:48 -08004204void Dbg::DdmSendChunk(uint32_t type, size_t byte_count, const uint8_t* buf) {
Ian Rogersc0542af2014-09-03 16:16:56 -07004205 CHECK(buf != nullptr);
Elliott Hughes3bb81562011-10-21 18:52:59 -07004206 iovec vec[1];
4207 vec[0].iov_base = reinterpret_cast<void*>(const_cast<uint8_t*>(buf));
4208 vec[0].iov_len = byte_count;
4209 Dbg::DdmSendChunkV(type, vec, 1);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07004210}
4211
Elliott Hughes21f32d72011-11-09 17:44:13 -08004212void Dbg::DdmSendChunk(uint32_t type, const std::vector<uint8_t>& bytes) {
4213 DdmSendChunk(type, bytes.size(), &bytes[0]);
4214}
4215
Brian Carlstromf5293522013-07-19 00:24:00 -07004216void Dbg::DdmSendChunkV(uint32_t type, const iovec* iov, int iov_count) {
Ian Rogersc0542af2014-09-03 16:16:56 -07004217 if (gJdwpState == nullptr) {
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08004218 VLOG(jdwp) << "Debugger thread not active, ignoring DDM send: " << type;
Elliott Hughes3bb81562011-10-21 18:52:59 -07004219 } else {
Elliott Hughescccd84f2011-12-05 16:51:54 -08004220 gJdwpState->DdmSendChunkV(type, iov, iov_count);
Elliott Hughes3bb81562011-10-21 18:52:59 -07004221 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -07004222}
4223
Mathieu Chartierad466ad2015-01-08 16:28:08 -08004224JDWP::JdwpState* Dbg::GetJdwpState() {
4225 return gJdwpState;
4226}
4227
Elliott Hughes767a1472011-10-26 18:49:02 -07004228int Dbg::DdmHandleHpifChunk(HpifWhen when) {
4229 if (when == HPIF_WHEN_NOW) {
Elliott Hughes7162ad92011-10-27 14:08:42 -07004230 DdmSendHeapInfo(when);
Elliott Hughes767a1472011-10-26 18:49:02 -07004231 return true;
4232 }
4233
4234 if (when != HPIF_WHEN_NEVER && when != HPIF_WHEN_NEXT_GC && when != HPIF_WHEN_EVERY_GC) {
4235 LOG(ERROR) << "invalid HpifWhen value: " << static_cast<int>(when);
4236 return false;
4237 }
4238
4239 gDdmHpifWhen = when;
4240 return true;
4241}
4242
4243bool Dbg::DdmHandleHpsgNhsgChunk(Dbg::HpsgWhen when, Dbg::HpsgWhat what, bool native) {
4244 if (when != HPSG_WHEN_NEVER && when != HPSG_WHEN_EVERY_GC) {
4245 LOG(ERROR) << "invalid HpsgWhen value: " << static_cast<int>(when);
4246 return false;
4247 }
4248
4249 if (what != HPSG_WHAT_MERGED_OBJECTS && what != HPSG_WHAT_DISTINCT_OBJECTS) {
4250 LOG(ERROR) << "invalid HpsgWhat value: " << static_cast<int>(what);
4251 return false;
4252 }
4253
4254 if (native) {
4255 gDdmNhsgWhen = when;
4256 gDdmNhsgWhat = what;
4257 } else {
4258 gDdmHpsgWhen = when;
4259 gDdmHpsgWhat = what;
4260 }
4261 return true;
4262}
4263
Elliott Hughes7162ad92011-10-27 14:08:42 -07004264void Dbg::DdmSendHeapInfo(HpifWhen reason) {
4265 // If there's a one-shot 'when', reset it.
4266 if (reason == gDdmHpifWhen) {
4267 if (gDdmHpifWhen == HPIF_WHEN_NEXT_GC) {
4268 gDdmHpifWhen = HPIF_WHEN_NEVER;
4269 }
4270 }
4271
4272 /*
4273 * Chunk HPIF (client --> server)
4274 *
4275 * Heap Info. General information about the heap,
4276 * suitable for a summary display.
4277 *
4278 * [u4]: number of heaps
4279 *
4280 * For each heap:
4281 * [u4]: heap ID
4282 * [u8]: timestamp in ms since Unix epoch
4283 * [u1]: capture reason (same as 'when' value from server)
4284 * [u4]: max heap size in bytes (-Xmx)
4285 * [u4]: current heap size in bytes
4286 * [u4]: current number of bytes allocated
4287 * [u4]: current number of objects allocated
4288 */
4289 uint8_t heap_count = 1;
Ian Rogers1d54e732013-05-02 21:10:01 -07004290 gc::Heap* heap = Runtime::Current()->GetHeap();
Elliott Hughes21f32d72011-11-09 17:44:13 -08004291 std::vector<uint8_t> bytes;
Elliott Hughes545a0642011-11-08 19:10:03 -08004292 JDWP::Append4BE(bytes, heap_count);
Brian Carlstrom7934ac22013-07-26 10:54:15 -07004293 JDWP::Append4BE(bytes, 1); // Heap id (bogus; we only have one heap).
Elliott Hughes545a0642011-11-08 19:10:03 -08004294 JDWP::Append8BE(bytes, MilliTime());
4295 JDWP::Append1BE(bytes, reason);
Brian Carlstrom7934ac22013-07-26 10:54:15 -07004296 JDWP::Append4BE(bytes, heap->GetMaxMemory()); // Max allowed heap size in bytes.
4297 JDWP::Append4BE(bytes, heap->GetTotalMemory()); // Current heap size in bytes.
Elliott Hughesb3bd5f02012-03-08 21:05:27 -08004298 JDWP::Append4BE(bytes, heap->GetBytesAllocated());
4299 JDWP::Append4BE(bytes, heap->GetObjectsAllocated());
Elliott Hughes21f32d72011-11-09 17:44:13 -08004300 CHECK_EQ(bytes.size(), 4U + (heap_count * (4 + 8 + 1 + 4 + 4 + 4 + 4)));
4301 Dbg::DdmSendChunk(CHUNK_TYPE("HPIF"), bytes);
Elliott Hughes767a1472011-10-26 18:49:02 -07004302}
4303
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004304enum HpsgSolidity {
4305 SOLIDITY_FREE = 0,
4306 SOLIDITY_HARD = 1,
4307 SOLIDITY_SOFT = 2,
4308 SOLIDITY_WEAK = 3,
4309 SOLIDITY_PHANTOM = 4,
4310 SOLIDITY_FINALIZABLE = 5,
4311 SOLIDITY_SWEEP = 6,
4312};
4313
4314enum HpsgKind {
4315 KIND_OBJECT = 0,
4316 KIND_CLASS_OBJECT = 1,
4317 KIND_ARRAY_1 = 2,
4318 KIND_ARRAY_2 = 3,
4319 KIND_ARRAY_4 = 4,
4320 KIND_ARRAY_8 = 5,
4321 KIND_UNKNOWN = 6,
4322 KIND_NATIVE = 7,
4323};
4324
4325#define HPSG_PARTIAL (1<<7)
4326#define HPSG_STATE(solidity, kind) ((uint8_t)((((kind) & 0x7) << 3) | ((solidity) & 0x7)))
4327
Ian Rogers30fab402012-01-23 15:43:46 -08004328class HeapChunkContext {
4329 public:
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004330 // Maximum chunk size. Obtain this from the formula:
4331 // (((maximum_heap_size / ALLOCATION_UNIT_SIZE) + 255) / 256) * 2
4332 HeapChunkContext(bool merge, bool native)
Ian Rogers30fab402012-01-23 15:43:46 -08004333 : buf_(16384 - 16),
4334 type_(0),
Mathieu Chartier36dab362014-07-30 14:59:56 -07004335 chunk_overhead_(0) {
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004336 Reset();
4337 if (native) {
Ian Rogers30fab402012-01-23 15:43:46 -08004338 type_ = CHUNK_TYPE("NHSG");
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004339 } else {
Ian Rogers30fab402012-01-23 15:43:46 -08004340 type_ = merge ? CHUNK_TYPE("HPSG") : CHUNK_TYPE("HPSO");
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004341 }
4342 }
4343
4344 ~HeapChunkContext() {
Ian Rogers30fab402012-01-23 15:43:46 -08004345 if (p_ > &buf_[0]) {
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004346 Flush();
4347 }
4348 }
4349
Mathieu Chartier36dab362014-07-30 14:59:56 -07004350 void SetChunkOverhead(size_t chunk_overhead) {
4351 chunk_overhead_ = chunk_overhead;
4352 }
4353
4354 void ResetStartOfNextChunk() {
4355 startOfNextMemoryChunk_ = nullptr;
4356 }
4357
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004358 void EnsureHeader(const void* chunk_ptr) {
Ian Rogers30fab402012-01-23 15:43:46 -08004359 if (!needHeader_) {
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004360 return;
4361 }
4362
4363 // Start a new HPSx chunk.
Brian Carlstrom7934ac22013-07-26 10:54:15 -07004364 JDWP::Write4BE(&p_, 1); // Heap id (bogus; we only have one heap).
4365 JDWP::Write1BE(&p_, 8); // Size of allocation unit, in bytes.
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004366
Brian Carlstrom7934ac22013-07-26 10:54:15 -07004367 JDWP::Write4BE(&p_, reinterpret_cast<uintptr_t>(chunk_ptr)); // virtual address of segment start.
4368 JDWP::Write4BE(&p_, 0); // offset of this piece (relative to the virtual address).
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004369 // [u4]: length of piece, in allocation units
4370 // 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 -08004371 pieceLenField_ = p_;
4372 JDWP::Write4BE(&p_, 0x55555555);
4373 needHeader_ = false;
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004374 }
4375
Ian Rogersb726dcb2012-09-05 08:57:23 -07004376 void Flush() SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Ian Rogersc0542af2014-09-03 16:16:56 -07004377 if (pieceLenField_ == nullptr) {
Ian Rogersd636b062013-01-18 17:51:18 -08004378 // Flush immediately post Reset (maybe back-to-back Flush). Ignore.
4379 CHECK(needHeader_);
4380 return;
4381 }
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004382 // Patch the "length of piece" field.
Ian Rogers30fab402012-01-23 15:43:46 -08004383 CHECK_LE(&buf_[0], pieceLenField_);
4384 CHECK_LE(pieceLenField_, p_);
4385 JDWP::Set4BE(pieceLenField_, totalAllocationUnits_);
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004386
Ian Rogers30fab402012-01-23 15:43:46 -08004387 Dbg::DdmSendChunk(type_, p_ - &buf_[0], &buf_[0]);
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004388 Reset();
4389 }
4390
Mathieu Chartierbc689b72014-12-14 17:01:31 -08004391 static void HeapChunkJavaCallback(void* start, void* end, size_t used_bytes, void* arg)
Ian Rogersb726dcb2012-09-05 08:57:23 -07004392 SHARED_LOCKS_REQUIRED(Locks::heap_bitmap_lock_,
4393 Locks::mutator_lock_) {
Mathieu Chartierbc689b72014-12-14 17:01:31 -08004394 reinterpret_cast<HeapChunkContext*>(arg)->HeapChunkJavaCallback(start, end, used_bytes);
4395 }
4396
4397 static void HeapChunkNativeCallback(void* start, void* end, size_t used_bytes, void* arg)
4398 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
4399 reinterpret_cast<HeapChunkContext*>(arg)->HeapChunkNativeCallback(start, end, used_bytes);
Elliott Hughesa2155262011-11-16 16:26:58 -08004400 }
4401
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004402 private:
Elliott Hughesa2155262011-11-16 16:26:58 -08004403 enum { ALLOCATION_UNIT_SIZE = 8 };
4404
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004405 void Reset() {
Ian Rogers30fab402012-01-23 15:43:46 -08004406 p_ = &buf_[0];
Mathieu Chartier36dab362014-07-30 14:59:56 -07004407 ResetStartOfNextChunk();
Ian Rogers30fab402012-01-23 15:43:46 -08004408 totalAllocationUnits_ = 0;
4409 needHeader_ = true;
Ian Rogersc0542af2014-09-03 16:16:56 -07004410 pieceLenField_ = nullptr;
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004411 }
4412
Mathieu Chartierbc689b72014-12-14 17:01:31 -08004413 bool IsNative() const {
4414 return type_ == CHUNK_TYPE("NHSG");
4415 }
4416
4417 // Returns true if the object is not an empty chunk.
4418 bool ProcessRecord(void* start, size_t used_bytes) SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Ian Rogers30fab402012-01-23 15:43:46 -08004419 // Note: heap call backs cannot manipulate the heap upon which they are crawling, care is taken
4420 // in the following code not to allocate memory, by ensuring buf_ is of the correct size
Ian Rogers15bf2d32012-08-28 17:33:04 -07004421 if (used_bytes == 0) {
Mathieu Chartierbc689b72014-12-14 17:01:31 -08004422 if (start == nullptr) {
4423 // Reset for start of new heap.
4424 startOfNextMemoryChunk_ = nullptr;
4425 Flush();
4426 }
4427 // Only process in use memory so that free region information
4428 // also includes dlmalloc book keeping.
4429 return false;
Elliott Hughesa2155262011-11-16 16:26:58 -08004430 }
Ian Rogersc0542af2014-09-03 16:16:56 -07004431 if (startOfNextMemoryChunk_ != nullptr) {
Mathieu Chartierbc689b72014-12-14 17:01:31 -08004432 // Transmit any pending free memory. Native free memory of over kMaxFreeLen could be because
4433 // of the use of mmaps, so don't report. If not free memory then start a new segment.
4434 bool flush = true;
4435 if (start > startOfNextMemoryChunk_) {
4436 const size_t kMaxFreeLen = 2 * kPageSize;
4437 void* free_start = startOfNextMemoryChunk_;
4438 void* free_end = start;
4439 const size_t free_len =
4440 reinterpret_cast<uintptr_t>(free_end) - reinterpret_cast<uintptr_t>(free_start);
4441 if (!IsNative() || free_len < kMaxFreeLen) {
4442 AppendChunk(HPSG_STATE(SOLIDITY_FREE, 0), free_start, free_len, IsNative());
4443 flush = false;
Ian Rogers15bf2d32012-08-28 17:33:04 -07004444 }
Mathieu Chartierbc689b72014-12-14 17:01:31 -08004445 }
4446 if (flush) {
4447 startOfNextMemoryChunk_ = nullptr;
4448 Flush();
4449 }
Ian Rogers15bf2d32012-08-28 17:33:04 -07004450 }
Mathieu Chartierbc689b72014-12-14 17:01:31 -08004451 return true;
Ian Rogers15bf2d32012-08-28 17:33:04 -07004452 }
Elliott Hughesa2155262011-11-16 16:26:58 -08004453
Mathieu Chartierbc689b72014-12-14 17:01:31 -08004454 void HeapChunkNativeCallback(void* start, void* /*end*/, size_t used_bytes)
4455 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
4456 if (ProcessRecord(start, used_bytes)) {
4457 uint8_t state = ExamineNativeObject(start);
4458 AppendChunk(state, start, used_bytes + chunk_overhead_, true /*is_native*/);
4459 startOfNextMemoryChunk_ = reinterpret_cast<char*>(start) + used_bytes + chunk_overhead_;
4460 }
4461 }
4462
4463 void HeapChunkJavaCallback(void* start, void* /*end*/, size_t used_bytes)
4464 SHARED_LOCKS_REQUIRED(Locks::heap_bitmap_lock_, Locks::mutator_lock_) {
4465 if (ProcessRecord(start, used_bytes)) {
4466 // Determine the type of this chunk.
4467 // OLD-TODO: if context.merge, see if this chunk is different from the last chunk.
4468 // If it's the same, we should combine them.
4469 uint8_t state = ExamineJavaObject(reinterpret_cast<mirror::Object*>(start));
4470 AppendChunk(state, start, used_bytes + chunk_overhead_, false /*is_native*/);
4471 startOfNextMemoryChunk_ = reinterpret_cast<char*>(start) + used_bytes + chunk_overhead_;
4472 }
4473 }
4474
4475 void AppendChunk(uint8_t state, void* ptr, size_t length, bool is_native)
Ian Rogersb726dcb2012-09-05 08:57:23 -07004476 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Ian Rogers15bf2d32012-08-28 17:33:04 -07004477 // Make sure there's enough room left in the buffer.
4478 // We need to use two bytes for every fractional 256 allocation units used by the chunk plus
4479 // 17 bytes for any header.
Mathieu Chartierbc689b72014-12-14 17:01:31 -08004480 const size_t needed = ((RoundUp(length / ALLOCATION_UNIT_SIZE, 256) / 256) * 2) + 17;
4481 size_t byte_left = &buf_.back() - p_;
4482 if (byte_left < needed) {
4483 if (is_native) {
Pavel Vyssotski7522c742014-12-08 13:38:26 +06004484 // Cannot trigger memory allocation while walking native heap.
Pavel Vyssotski7522c742014-12-08 13:38:26 +06004485 return;
4486 }
Ian Rogers15bf2d32012-08-28 17:33:04 -07004487 Flush();
4488 }
4489
Mathieu Chartierbc689b72014-12-14 17:01:31 -08004490 byte_left = &buf_.back() - p_;
4491 if (byte_left < needed) {
Ian Rogers15bf2d32012-08-28 17:33:04 -07004492 LOG(WARNING) << "Chunk is too big to transmit (chunk_len=" << length << ", "
4493 << needed << " bytes)";
4494 return;
4495 }
4496 EnsureHeader(ptr);
Elliott Hughesa2155262011-11-16 16:26:58 -08004497 // Write out the chunk description.
Ian Rogers15bf2d32012-08-28 17:33:04 -07004498 length /= ALLOCATION_UNIT_SIZE; // Convert to allocation units.
4499 totalAllocationUnits_ += length;
4500 while (length > 256) {
Ian Rogers30fab402012-01-23 15:43:46 -08004501 *p_++ = state | HPSG_PARTIAL;
4502 *p_++ = 255; // length - 1
Ian Rogers15bf2d32012-08-28 17:33:04 -07004503 length -= 256;
Elliott Hughesa2155262011-11-16 16:26:58 -08004504 }
Ian Rogers30fab402012-01-23 15:43:46 -08004505 *p_++ = state;
Ian Rogers15bf2d32012-08-28 17:33:04 -07004506 *p_++ = length - 1;
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004507 }
4508
Mathieu Chartierbc689b72014-12-14 17:01:31 -08004509 uint8_t ExamineNativeObject(const void* p) SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
4510 return p == nullptr ? HPSG_STATE(SOLIDITY_FREE, 0) : HPSG_STATE(SOLIDITY_HARD, KIND_NATIVE);
4511 }
4512
4513 uint8_t ExamineJavaObject(mirror::Object* o)
Ian Rogersef7d42f2014-01-06 12:55:46 -08004514 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_, Locks::heap_bitmap_lock_) {
Ian Rogersc0542af2014-09-03 16:16:56 -07004515 if (o == nullptr) {
Elliott Hughesa2155262011-11-16 16:26:58 -08004516 return HPSG_STATE(SOLIDITY_FREE, 0);
4517 }
Elliott Hughesa2155262011-11-16 16:26:58 -08004518 // It's an allocated chunk. Figure out what it is.
Mathieu Chartierbc689b72014-12-14 17:01:31 -08004519 gc::Heap* heap = Runtime::Current()->GetHeap();
4520 if (!heap->IsLiveObjectLocked(o)) {
4521 LOG(ERROR) << "Invalid object in managed heap: " << o;
Elliott Hughesa2155262011-11-16 16:26:58 -08004522 return HPSG_STATE(SOLIDITY_HARD, KIND_NATIVE);
4523 }
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08004524 mirror::Class* c = o->GetClass();
Ian Rogersc0542af2014-09-03 16:16:56 -07004525 if (c == nullptr) {
Elliott Hughesa2155262011-11-16 16:26:58 -08004526 // The object was probably just created but hasn't been initialized yet.
4527 return HPSG_STATE(SOLIDITY_HARD, KIND_OBJECT);
4528 }
Mathieu Chartierbc689b72014-12-14 17:01:31 -08004529 if (!heap->IsValidObjectAddress(c)) {
Ian Rogers15bf2d32012-08-28 17:33:04 -07004530 LOG(ERROR) << "Invalid class for managed heap object: " << o << " " << c;
Elliott Hughesa2155262011-11-16 16:26:58 -08004531 return HPSG_STATE(SOLIDITY_HARD, KIND_UNKNOWN);
4532 }
Mathieu Chartierf26e1b32015-01-29 10:47:10 -08004533 if (c->GetClass() == nullptr) {
4534 LOG(ERROR) << "Null class of class " << c << " for object " << o;
4535 return HPSG_STATE(SOLIDITY_HARD, KIND_UNKNOWN);
4536 }
Elliott Hughesa2155262011-11-16 16:26:58 -08004537 if (c->IsClassClass()) {
4538 return HPSG_STATE(SOLIDITY_HARD, KIND_CLASS_OBJECT);
4539 }
Elliott Hughesa2155262011-11-16 16:26:58 -08004540 if (c->IsArrayClass()) {
Elliott Hughesa2155262011-11-16 16:26:58 -08004541 switch (c->GetComponentSize()) {
4542 case 1: return HPSG_STATE(SOLIDITY_HARD, KIND_ARRAY_1);
4543 case 2: return HPSG_STATE(SOLIDITY_HARD, KIND_ARRAY_2);
4544 case 4: return HPSG_STATE(SOLIDITY_HARD, KIND_ARRAY_4);
4545 case 8: return HPSG_STATE(SOLIDITY_HARD, KIND_ARRAY_8);
4546 }
4547 }
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004548 return HPSG_STATE(SOLIDITY_HARD, KIND_OBJECT);
4549 }
4550
Ian Rogers30fab402012-01-23 15:43:46 -08004551 std::vector<uint8_t> buf_;
4552 uint8_t* p_;
4553 uint8_t* pieceLenField_;
Ian Rogers15bf2d32012-08-28 17:33:04 -07004554 void* startOfNextMemoryChunk_;
Ian Rogers30fab402012-01-23 15:43:46 -08004555 size_t totalAllocationUnits_;
4556 uint32_t type_;
Ian Rogers30fab402012-01-23 15:43:46 -08004557 bool needHeader_;
Mathieu Chartier36dab362014-07-30 14:59:56 -07004558 size_t chunk_overhead_;
Ian Rogers30fab402012-01-23 15:43:46 -08004559
Elliott Hughesa2155262011-11-16 16:26:58 -08004560 DISALLOW_COPY_AND_ASSIGN(HeapChunkContext);
4561};
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004562
Mathieu Chartier36dab362014-07-30 14:59:56 -07004563static void BumpPointerSpaceCallback(mirror::Object* obj, void* arg)
4564 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) EXCLUSIVE_LOCKS_REQUIRED(Locks::heap_bitmap_lock_) {
4565 const size_t size = RoundUp(obj->SizeOf(), kObjectAlignment);
Mathieu Chartierbc689b72014-12-14 17:01:31 -08004566 HeapChunkContext::HeapChunkJavaCallback(
Mathieu Chartier36dab362014-07-30 14:59:56 -07004567 obj, reinterpret_cast<void*>(reinterpret_cast<uintptr_t>(obj) + size), size, arg);
4568}
4569
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004570void Dbg::DdmSendHeapSegments(bool native) {
Mathieu Chartierbc689b72014-12-14 17:01:31 -08004571 Dbg::HpsgWhen when = native ? gDdmNhsgWhen : gDdmHpsgWhen;
4572 Dbg::HpsgWhat what = native ? gDdmNhsgWhat : gDdmHpsgWhat;
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004573 if (when == HPSG_WHEN_NEVER) {
4574 return;
4575 }
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004576 // Figure out what kind of chunks we'll be sending.
Mathieu Chartierbc689b72014-12-14 17:01:31 -08004577 CHECK(what == HPSG_WHAT_MERGED_OBJECTS || what == HPSG_WHAT_DISTINCT_OBJECTS)
4578 << static_cast<int>(what);
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004579
4580 // First, send a heap start chunk.
4581 uint8_t heap_id[4];
Brian Carlstrom7934ac22013-07-26 10:54:15 -07004582 JDWP::Set4BE(&heap_id[0], 1); // Heap id (bogus; we only have one heap).
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004583 Dbg::DdmSendChunk(native ? CHUNK_TYPE("NHST") : CHUNK_TYPE("HPST"), sizeof(heap_id), heap_id);
Hiroshi Yamauchicf58d4a2013-09-26 14:21:22 -07004584 Thread* self = Thread::Current();
Hiroshi Yamauchicf58d4a2013-09-26 14:21:22 -07004585 Locks::mutator_lock_->AssertSharedHeld(self);
Hiroshi Yamauchicf58d4a2013-09-26 14:21:22 -07004586
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004587 // Send a series of heap segment chunks.
Mathieu Chartierbc689b72014-12-14 17:01:31 -08004588 HeapChunkContext context(what == HPSG_WHAT_MERGED_OBJECTS, native);
Elliott Hughesa2155262011-11-16 16:26:58 -08004589 if (native) {
Ian Rogers872dd822014-10-30 11:19:14 -07004590#if defined(HAVE_ANDROID_OS) && defined(USE_DLMALLOC)
Mathieu Chartierbc689b72014-12-14 17:01:31 -08004591 dlmalloc_inspect_all(HeapChunkContext::HeapChunkNativeCallback, &context);
4592 HeapChunkContext::HeapChunkNativeCallback(nullptr, nullptr, 0, &context); // Indicate end of a space.
Christopher Ferrisc4ddc042014-05-13 14:47:50 -07004593#else
4594 UNIMPLEMENTED(WARNING) << "Native heap inspection is only supported with dlmalloc";
4595#endif
Elliott Hughesa2155262011-11-16 16:26:58 -08004596 } else {
Ian Rogers1d54e732013-05-02 21:10:01 -07004597 gc::Heap* heap = Runtime::Current()->GetHeap();
Mathieu Chartier36dab362014-07-30 14:59:56 -07004598 for (const auto& space : heap->GetContinuousSpaces()) {
4599 if (space->IsDlMallocSpace()) {
Mathieu Chartier4c69d7f2014-10-10 12:45:50 -07004600 ReaderMutexLock mu(self, *Locks::heap_bitmap_lock_);
Mathieu Chartier36dab362014-07-30 14:59:56 -07004601 // dlmalloc's chunk header is 2 * sizeof(size_t), but if the previous chunk is in use for an
4602 // allocation then the first sizeof(size_t) may belong to it.
4603 context.SetChunkOverhead(sizeof(size_t));
Mathieu Chartierbc689b72014-12-14 17:01:31 -08004604 space->AsDlMallocSpace()->Walk(HeapChunkContext::HeapChunkJavaCallback, &context);
Mathieu Chartier36dab362014-07-30 14:59:56 -07004605 } else if (space->IsRosAllocSpace()) {
4606 context.SetChunkOverhead(0);
Mathieu Chartier4c69d7f2014-10-10 12:45:50 -07004607 // Need to acquire the mutator lock before the heap bitmap lock with exclusive access since
4608 // RosAlloc's internal logic doesn't know to release and reacquire the heap bitmap lock.
4609 self->TransitionFromRunnableToSuspended(kSuspended);
4610 ThreadList* tl = Runtime::Current()->GetThreadList();
Mathieu Chartierbf9fc582015-03-13 17:21:25 -07004611 tl->SuspendAll(__FUNCTION__);
Mathieu Chartier4c69d7f2014-10-10 12:45:50 -07004612 {
4613 ReaderMutexLock mu(self, *Locks::heap_bitmap_lock_);
Mathieu Chartierbc689b72014-12-14 17:01:31 -08004614 space->AsRosAllocSpace()->Walk(HeapChunkContext::HeapChunkJavaCallback, &context);
Mathieu Chartier4c69d7f2014-10-10 12:45:50 -07004615 }
4616 tl->ResumeAll();
4617 self->TransitionFromSuspendedToRunnable();
Mathieu Chartier36dab362014-07-30 14:59:56 -07004618 } else if (space->IsBumpPointerSpace()) {
Mathieu Chartier4c69d7f2014-10-10 12:45:50 -07004619 ReaderMutexLock mu(self, *Locks::heap_bitmap_lock_);
Mathieu Chartier36dab362014-07-30 14:59:56 -07004620 context.SetChunkOverhead(0);
Mathieu Chartier36dab362014-07-30 14:59:56 -07004621 space->AsBumpPointerSpace()->Walk(BumpPointerSpaceCallback, &context);
Mathieu Chartierbc689b72014-12-14 17:01:31 -08004622 HeapChunkContext::HeapChunkJavaCallback(nullptr, nullptr, 0, &context);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08004623 } else if (space->IsRegionSpace()) {
4624 heap->IncrementDisableMovingGC(self);
4625 self->TransitionFromRunnableToSuspended(kSuspended);
4626 ThreadList* tl = Runtime::Current()->GetThreadList();
Mathieu Chartierbf9fc582015-03-13 17:21:25 -07004627 tl->SuspendAll(__FUNCTION__);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08004628 ReaderMutexLock mu(self, *Locks::heap_bitmap_lock_);
4629 context.SetChunkOverhead(0);
4630 space->AsRegionSpace()->Walk(BumpPointerSpaceCallback, &context);
4631 HeapChunkContext::HeapChunkJavaCallback(nullptr, nullptr, 0, &context);
4632 tl->ResumeAll();
4633 self->TransitionFromSuspendedToRunnable();
4634 heap->DecrementDisableMovingGC(self);
Mathieu Chartier36dab362014-07-30 14:59:56 -07004635 } else {
4636 UNIMPLEMENTED(WARNING) << "Not counting objects in space " << *space;
Mathieu Chartierb062fdd2012-07-03 09:51:48 -07004637 }
Mathieu Chartier36dab362014-07-30 14:59:56 -07004638 context.ResetStartOfNextChunk();
Mathieu Chartierb062fdd2012-07-03 09:51:48 -07004639 }
Mathieu Chartier4c69d7f2014-10-10 12:45:50 -07004640 ReaderMutexLock mu(self, *Locks::heap_bitmap_lock_);
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -07004641 // Walk the large objects, these are not in the AllocSpace.
Mathieu Chartier36dab362014-07-30 14:59:56 -07004642 context.SetChunkOverhead(0);
Mathieu Chartierbc689b72014-12-14 17:01:31 -08004643 heap->GetLargeObjectsSpace()->Walk(HeapChunkContext::HeapChunkJavaCallback, &context);
Elliott Hughesa2155262011-11-16 16:26:58 -08004644 }
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004645
4646 // Finally, send a heap end chunk.
4647 Dbg::DdmSendChunk(native ? CHUNK_TYPE("NHEN") : CHUNK_TYPE("HPEN"), sizeof(heap_id), heap_id);
Elliott Hughes767a1472011-10-26 18:49:02 -07004648}
4649
Elliott Hughesb1a58792013-07-11 18:10:58 -07004650static size_t GetAllocTrackerMax() {
4651#ifdef HAVE_ANDROID_OS
4652 // Check whether there's a system property overriding the number of records.
4653 const char* propertyName = "dalvik.vm.allocTrackerMax";
4654 char allocRecordMaxString[PROPERTY_VALUE_MAX];
4655 if (property_get(propertyName, allocRecordMaxString, "") > 0) {
4656 char* end;
4657 size_t value = strtoul(allocRecordMaxString, &end, 10);
4658 if (*end != '\0') {
Ruben Brunk3e47a742013-09-09 17:56:07 -07004659 LOG(ERROR) << "Ignoring " << propertyName << " '" << allocRecordMaxString
4660 << "' --- invalid";
Elliott Hughesb1a58792013-07-11 18:10:58 -07004661 return kDefaultNumAllocRecords;
4662 }
4663 if (!IsPowerOfTwo(value)) {
Ruben Brunk3e47a742013-09-09 17:56:07 -07004664 LOG(ERROR) << "Ignoring " << propertyName << " '" << allocRecordMaxString
4665 << "' --- not power of two";
Elliott Hughesb1a58792013-07-11 18:10:58 -07004666 return kDefaultNumAllocRecords;
4667 }
4668 return value;
4669 }
4670#endif
4671 return kDefaultNumAllocRecords;
4672}
4673
Brian Carlstrom306db812014-09-05 13:01:41 -07004674void Dbg::SetAllocTrackingEnabled(bool enable) {
4675 Thread* self = Thread::Current();
4676 if (enable) {
Sebastien Hertzb98063a2014-03-26 10:57:20 +01004677 {
Brian Carlstrom306db812014-09-05 13:01:41 -07004678 MutexLock mu(self, *Locks::alloc_tracker_lock_);
4679 if (recent_allocation_records_ != nullptr) {
4680 return; // Already enabled, bail.
Sebastien Hertzb98063a2014-03-26 10:57:20 +01004681 }
Brian Carlstrom306db812014-09-05 13:01:41 -07004682 alloc_record_max_ = GetAllocTrackerMax();
4683 LOG(INFO) << "Enabling alloc tracker (" << alloc_record_max_ << " entries of "
4684 << kMaxAllocRecordStackDepth << " frames, taking "
4685 << PrettySize(sizeof(AllocRecord) * alloc_record_max_) << ")";
4686 DCHECK_EQ(alloc_record_head_, 0U);
4687 DCHECK_EQ(alloc_record_count_, 0U);
4688 recent_allocation_records_ = new AllocRecord[alloc_record_max_];
4689 CHECK(recent_allocation_records_ != nullptr);
Elliott Hughes545a0642011-11-08 19:10:03 -08004690 }
Mathieu Chartier9ef78b52014-09-25 17:03:12 -07004691 Runtime::Current()->GetInstrumentation()->InstrumentQuickAllocEntryPoints();
Elliott Hughes545a0642011-11-08 19:10:03 -08004692 } else {
Sebastien Hertzb98063a2014-03-26 10:57:20 +01004693 {
Brian Carlstrom306db812014-09-05 13:01:41 -07004694 ScopedObjectAccess soa(self); // For type_cache_.Clear();
4695 MutexLock mu(self, *Locks::alloc_tracker_lock_);
4696 if (recent_allocation_records_ == nullptr) {
4697 return; // Already disabled, bail.
4698 }
Mathieu Chartier4345c462014-06-27 10:20:14 -07004699 LOG(INFO) << "Disabling alloc tracker";
Sebastien Hertzb98063a2014-03-26 10:57:20 +01004700 delete[] recent_allocation_records_;
Ian Rogersc0542af2014-09-03 16:16:56 -07004701 recent_allocation_records_ = nullptr;
Brian Carlstrom306db812014-09-05 13:01:41 -07004702 alloc_record_head_ = 0;
4703 alloc_record_count_ = 0;
Mathieu Chartier4345c462014-06-27 10:20:14 -07004704 type_cache_.Clear();
Sebastien Hertzb98063a2014-03-26 10:57:20 +01004705 }
Brian Carlstrom306db812014-09-05 13:01:41 -07004706 // If an allocation comes in before we uninstrument, we will safely drop it on the floor.
Mathieu Chartier9ef78b52014-09-25 17:03:12 -07004707 Runtime::Current()->GetInstrumentation()->UninstrumentQuickAllocEntryPoints();
Elliott Hughes545a0642011-11-08 19:10:03 -08004708 }
4709}
4710
Ian Rogers0399dde2012-06-06 17:09:28 -07004711struct AllocRecordStackVisitor : public StackVisitor {
Andreas Gampe277ccbd2014-11-03 21:36:10 -08004712 AllocRecordStackVisitor(Thread* thread, AllocRecord* record_in)
Ian Rogersb726dcb2012-09-05 08:57:23 -07004713 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_)
Nicolas Geoffray8e5bd182015-05-06 11:34:34 +01004714 : StackVisitor(thread, nullptr, StackVisitor::StackWalkKind::kIncludeInlinedFrames),
4715 record(record_in),
4716 depth(0) {}
Elliott Hughes545a0642011-11-08 19:10:03 -08004717
Ian Rogers00f7d0e2012-07-19 15:28:27 -07004718 // TODO: Enable annotalysis. We know lock is held in constructor, but abstraction confuses
4719 // annotalysis.
4720 bool VisitFrame() NO_THREAD_SAFETY_ANALYSIS {
Elliott Hughes545a0642011-11-08 19:10:03 -08004721 if (depth >= kMaxAllocRecordStackDepth) {
Elliott Hughes530fa002012-03-12 11:44:49 -07004722 return false;
Elliott Hughes545a0642011-11-08 19:10:03 -08004723 }
Brian Carlstromea46f952013-07-30 01:26:50 -07004724 mirror::ArtMethod* m = GetMethod();
Ian Rogers0399dde2012-06-06 17:09:28 -07004725 if (!m->IsRuntimeMethod()) {
Hiroshi Yamauchib5a9e3d2014-06-09 12:11:20 -07004726 record->StackElement(depth)->SetMethod(m);
4727 record->StackElement(depth)->SetDexPc(GetDexPc());
Elliott Hughes530fa002012-03-12 11:44:49 -07004728 ++depth;
Elliott Hughes545a0642011-11-08 19:10:03 -08004729 }
Elliott Hughes530fa002012-03-12 11:44:49 -07004730 return true;
Elliott Hughes545a0642011-11-08 19:10:03 -08004731 }
4732
4733 ~AllocRecordStackVisitor() {
4734 // Clear out any unused stack trace elements.
4735 for (; depth < kMaxAllocRecordStackDepth; ++depth) {
Hiroshi Yamauchib5a9e3d2014-06-09 12:11:20 -07004736 record->StackElement(depth)->SetMethod(nullptr);
4737 record->StackElement(depth)->SetDexPc(0);
Elliott Hughes545a0642011-11-08 19:10:03 -08004738 }
4739 }
4740
4741 AllocRecord* record;
4742 size_t depth;
4743};
4744
Ian Rogers844506b2014-09-12 19:59:33 -07004745void Dbg::RecordAllocation(Thread* self, mirror::Class* type, size_t byte_count) {
Brian Carlstrom306db812014-09-05 13:01:41 -07004746 MutexLock mu(self, *Locks::alloc_tracker_lock_);
Ian Rogersc0542af2014-09-03 16:16:56 -07004747 if (recent_allocation_records_ == nullptr) {
Brian Carlstrom306db812014-09-05 13:01:41 -07004748 // In the process of shutting down recording, bail.
Elliott Hughes545a0642011-11-08 19:10:03 -08004749 return;
4750 }
4751
4752 // Advance and clip.
Ian Rogers719d1a32014-03-06 12:13:39 -08004753 if (++alloc_record_head_ == alloc_record_max_) {
4754 alloc_record_head_ = 0;
Elliott Hughes545a0642011-11-08 19:10:03 -08004755 }
4756
4757 // Fill in the basics.
Ian Rogers719d1a32014-03-06 12:13:39 -08004758 AllocRecord* record = &recent_allocation_records_[alloc_record_head_];
Hiroshi Yamauchib5a9e3d2014-06-09 12:11:20 -07004759 record->SetType(type);
4760 record->SetByteCount(byte_count);
4761 record->SetThinLockId(self->GetThreadId());
Elliott Hughes545a0642011-11-08 19:10:03 -08004762
4763 // Fill in the stack trace.
Ian Rogers7a22fa62013-01-23 12:16:16 -08004764 AllocRecordStackVisitor visitor(self, record);
Ian Rogers0399dde2012-06-06 17:09:28 -07004765 visitor.WalkStack();
Elliott Hughes545a0642011-11-08 19:10:03 -08004766
Ian Rogers719d1a32014-03-06 12:13:39 -08004767 if (alloc_record_count_ < alloc_record_max_) {
4768 ++alloc_record_count_;
Elliott Hughes545a0642011-11-08 19:10:03 -08004769 }
4770}
4771
Elliott Hughesa8f93cb2012-06-08 17:08:48 -07004772// Returns the index of the head element.
4773//
Brian Carlstrom306db812014-09-05 13:01:41 -07004774// We point at the most-recently-written record, so if alloc_record_count_ is 1
Elliott Hughesa8f93cb2012-06-08 17:08:48 -07004775// we want to use the current element. Take "head+1" and subtract count
4776// from it.
4777//
4778// We need to handle underflow in our circular buffer, so we add
Brian Carlstrom306db812014-09-05 13:01:41 -07004779// alloc_record_max_ and then mask it back down.
Ian Rogers719d1a32014-03-06 12:13:39 -08004780size_t Dbg::HeadIndex() {
4781 return (Dbg::alloc_record_head_ + 1 + Dbg::alloc_record_max_ - Dbg::alloc_record_count_) &
4782 (Dbg::alloc_record_max_ - 1);
Elliott Hughes545a0642011-11-08 19:10:03 -08004783}
4784
4785void Dbg::DumpRecentAllocations() {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07004786 ScopedObjectAccess soa(Thread::Current());
Brian Carlstrom306db812014-09-05 13:01:41 -07004787 MutexLock mu(soa.Self(), *Locks::alloc_tracker_lock_);
Ian Rogersc0542af2014-09-03 16:16:56 -07004788 if (recent_allocation_records_ == nullptr) {
Elliott Hughes545a0642011-11-08 19:10:03 -08004789 LOG(INFO) << "Not recording tracked allocations";
4790 return;
4791 }
4792
4793 // "i" is the head of the list. We want to start at the end of the
4794 // list and move forward to the tail.
Elliott Hughesa8f93cb2012-06-08 17:08:48 -07004795 size_t i = HeadIndex();
Brian Carlstrom306db812014-09-05 13:01:41 -07004796 const uint16_t capped_count = CappedAllocRecordCount(Dbg::alloc_record_count_);
4797 uint16_t count = capped_count;
Elliott Hughes545a0642011-11-08 19:10:03 -08004798
Ian Rogers719d1a32014-03-06 12:13:39 -08004799 LOG(INFO) << "Tracked allocations, (head=" << alloc_record_head_ << " count=" << count << ")";
Elliott Hughes545a0642011-11-08 19:10:03 -08004800 while (count--) {
4801 AllocRecord* record = &recent_allocation_records_[i];
4802
Hiroshi Yamauchib5a9e3d2014-06-09 12:11:20 -07004803 LOG(INFO) << StringPrintf(" Thread %-2d %6zd bytes ", record->ThinLockId(), record->ByteCount())
4804 << PrettyClass(record->Type());
Elliott Hughes545a0642011-11-08 19:10:03 -08004805
4806 for (size_t stack_frame = 0; stack_frame < kMaxAllocRecordStackDepth; ++stack_frame) {
Hiroshi Yamauchib5a9e3d2014-06-09 12:11:20 -07004807 AllocRecordStackTraceElement* stack_element = record->StackElement(stack_frame);
4808 mirror::ArtMethod* m = stack_element->Method();
Ian Rogersc0542af2014-09-03 16:16:56 -07004809 if (m == nullptr) {
Elliott Hughes545a0642011-11-08 19:10:03 -08004810 break;
4811 }
Hiroshi Yamauchib5a9e3d2014-06-09 12:11:20 -07004812 LOG(INFO) << " " << PrettyMethod(m) << " line " << stack_element->LineNumber();
Elliott Hughes545a0642011-11-08 19:10:03 -08004813 }
4814
4815 // pause periodically to help logcat catch up
4816 if ((count % 5) == 0) {
4817 usleep(40000);
4818 }
4819
Ian Rogers719d1a32014-03-06 12:13:39 -08004820 i = (i + 1) & (alloc_record_max_ - 1);
Elliott Hughes545a0642011-11-08 19:10:03 -08004821 }
4822}
4823
4824class StringTable {
4825 public:
4826 StringTable() {
4827 }
4828
Mathieu Chartier4345c462014-06-27 10:20:14 -07004829 void Add(const std::string& str) {
4830 table_.insert(str);
4831 }
4832
4833 void Add(const char* str) {
4834 table_.insert(str);
Elliott Hughes545a0642011-11-08 19:10:03 -08004835 }
4836
Elliott Hughesa8f93cb2012-06-08 17:08:48 -07004837 size_t IndexOf(const char* s) const {
Mathieu Chartier02e25112013-08-14 16:14:24 -07004838 auto it = table_.find(s);
Elliott Hughesa8f93cb2012-06-08 17:08:48 -07004839 if (it == table_.end()) {
4840 LOG(FATAL) << "IndexOf(\"" << s << "\") failed";
4841 }
4842 return std::distance(table_.begin(), it);
Elliott Hughes545a0642011-11-08 19:10:03 -08004843 }
4844
Elliott Hughesa8f93cb2012-06-08 17:08:48 -07004845 size_t Size() const {
Elliott Hughes545a0642011-11-08 19:10:03 -08004846 return table_.size();
4847 }
4848
Elliott Hughesa8f93cb2012-06-08 17:08:48 -07004849 void WriteTo(std::vector<uint8_t>& bytes) const {
Mathieu Chartier02e25112013-08-14 16:14:24 -07004850 for (const std::string& str : table_) {
4851 const char* s = str.c_str();
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08004852 size_t s_len = CountModifiedUtf8Chars(s);
Christopher Ferris8a354052015-04-24 17:23:53 -07004853 std::unique_ptr<uint16_t[]> s_utf16(new uint16_t[s_len]);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08004854 ConvertModifiedUtf8ToUtf16(s_utf16.get(), s);
4855 JDWP::AppendUtf16BE(bytes, s_utf16.get(), s_len);
Elliott Hughes545a0642011-11-08 19:10:03 -08004856 }
4857 }
4858
4859 private:
Elliott Hughesa8f93cb2012-06-08 17:08:48 -07004860 std::set<std::string> table_;
Elliott Hughes545a0642011-11-08 19:10:03 -08004861 DISALLOW_COPY_AND_ASSIGN(StringTable);
4862};
4863
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07004864static const char* GetMethodSourceFile(mirror::ArtMethod* method)
Sebastien Hertz280286a2014-04-28 09:26:50 +02004865 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07004866 DCHECK(method != nullptr);
4867 const char* source_file = method->GetDeclaringClassSourceFile();
Sebastien Hertz280286a2014-04-28 09:26:50 +02004868 return (source_file != nullptr) ? source_file : "";
4869}
4870
Elliott Hughes545a0642011-11-08 19:10:03 -08004871/*
4872 * The data we send to DDMS contains everything we have recorded.
4873 *
4874 * Message header (all values big-endian):
4875 * (1b) message header len (to allow future expansion); includes itself
4876 * (1b) entry header len
4877 * (1b) stack frame len
4878 * (2b) number of entries
4879 * (4b) offset to string table from start of message
4880 * (2b) number of class name strings
4881 * (2b) number of method name strings
4882 * (2b) number of source file name strings
4883 * For each entry:
4884 * (4b) total allocation size
Elliott Hughes221229c2013-01-08 18:17:50 -08004885 * (2b) thread id
Elliott Hughes545a0642011-11-08 19:10:03 -08004886 * (2b) allocated object's class name index
4887 * (1b) stack depth
4888 * For each stack frame:
4889 * (2b) method's class name
4890 * (2b) method name
4891 * (2b) method source file
4892 * (2b) line number, clipped to 32767; -2 if native; -1 if no source
4893 * (xb) class name strings
4894 * (xb) method name strings
4895 * (xb) source file strings
4896 *
4897 * As with other DDM traffic, strings are sent as a 4-byte length
4898 * followed by UTF-16 data.
4899 *
4900 * We send up 16-bit unsigned indexes into string tables. In theory there
Brian Carlstrom306db812014-09-05 13:01:41 -07004901 * can be (kMaxAllocRecordStackDepth * alloc_record_max_) unique strings in
Elliott Hughes545a0642011-11-08 19:10:03 -08004902 * each table, but in practice there should be far fewer.
4903 *
4904 * The chief reason for using a string table here is to keep the size of
4905 * the DDMS message to a minimum. This is partly to make the protocol
4906 * efficient, but also because we have to form the whole thing up all at
4907 * once in a memory buffer.
4908 *
4909 * We use separate string tables for class names, method names, and source
4910 * files to keep the indexes small. There will generally be no overlap
4911 * between the contents of these tables.
4912 */
4913jbyteArray Dbg::GetRecentAllocations() {
Ian Rogerscf7f1912014-10-22 22:06:39 -07004914 if ((false)) {
Elliott Hughes545a0642011-11-08 19:10:03 -08004915 DumpRecentAllocations();
4916 }
4917
Ian Rogers50b35e22012-10-04 10:09:15 -07004918 Thread* self = Thread::Current();
Elliott Hughes545a0642011-11-08 19:10:03 -08004919 std::vector<uint8_t> bytes;
Mathieu Chartier46e811b2013-07-10 17:09:14 -07004920 {
Brian Carlstrom306db812014-09-05 13:01:41 -07004921 MutexLock mu(self, *Locks::alloc_tracker_lock_);
Mathieu Chartier46e811b2013-07-10 17:09:14 -07004922 //
4923 // Part 1: generate string tables.
4924 //
4925 StringTable class_names;
4926 StringTable method_names;
4927 StringTable filenames;
Elliott Hughes545a0642011-11-08 19:10:03 -08004928
Brian Carlstrom306db812014-09-05 13:01:41 -07004929 const uint16_t capped_count = CappedAllocRecordCount(Dbg::alloc_record_count_);
4930 uint16_t count = capped_count;
4931 size_t idx = HeadIndex();
Mathieu Chartier46e811b2013-07-10 17:09:14 -07004932 while (count--) {
4933 AllocRecord* record = &recent_allocation_records_[idx];
Ian Rogers1ff3c982014-08-12 02:30:58 -07004934 std::string temp;
4935 class_names.Add(record->Type()->GetDescriptor(&temp));
Mathieu Chartier46e811b2013-07-10 17:09:14 -07004936 for (size_t i = 0; i < kMaxAllocRecordStackDepth; i++) {
Hiroshi Yamauchib5a9e3d2014-06-09 12:11:20 -07004937 mirror::ArtMethod* m = record->StackElement(i)->Method();
Ian Rogersc0542af2014-09-03 16:16:56 -07004938 if (m != nullptr) {
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07004939 class_names.Add(m->GetDeclaringClassDescriptor());
4940 method_names.Add(m->GetName());
4941 filenames.Add(GetMethodSourceFile(m));
Mathieu Chartier46e811b2013-07-10 17:09:14 -07004942 }
4943 }
Elliott Hughes545a0642011-11-08 19:10:03 -08004944
Ian Rogers719d1a32014-03-06 12:13:39 -08004945 idx = (idx + 1) & (alloc_record_max_ - 1);
Elliott Hughes545a0642011-11-08 19:10:03 -08004946 }
4947
Brian Carlstrom306db812014-09-05 13:01:41 -07004948 LOG(INFO) << "allocation records: " << capped_count;
Mathieu Chartier46e811b2013-07-10 17:09:14 -07004949
4950 //
4951 // Part 2: Generate the output and store it in the buffer.
4952 //
4953
4954 // (1b) message header len (to allow future expansion); includes itself
4955 // (1b) entry header len
4956 // (1b) stack frame len
4957 const int kMessageHeaderLen = 15;
4958 const int kEntryHeaderLen = 9;
4959 const int kStackFrameLen = 8;
4960 JDWP::Append1BE(bytes, kMessageHeaderLen);
4961 JDWP::Append1BE(bytes, kEntryHeaderLen);
4962 JDWP::Append1BE(bytes, kStackFrameLen);
4963
4964 // (2b) number of entries
4965 // (4b) offset to string table from start of message
4966 // (2b) number of class name strings
4967 // (2b) number of method name strings
4968 // (2b) number of source file name strings
Brian Carlstrom306db812014-09-05 13:01:41 -07004969 JDWP::Append2BE(bytes, capped_count);
Mathieu Chartier46e811b2013-07-10 17:09:14 -07004970 size_t string_table_offset = bytes.size();
Brian Carlstrom7934ac22013-07-26 10:54:15 -07004971 JDWP::Append4BE(bytes, 0); // We'll patch this later...
Mathieu Chartier46e811b2013-07-10 17:09:14 -07004972 JDWP::Append2BE(bytes, class_names.Size());
4973 JDWP::Append2BE(bytes, method_names.Size());
4974 JDWP::Append2BE(bytes, filenames.Size());
4975
Mathieu Chartier46e811b2013-07-10 17:09:14 -07004976 idx = HeadIndex();
Ian Rogers1ff3c982014-08-12 02:30:58 -07004977 std::string temp;
Brian Carlstrom306db812014-09-05 13:01:41 -07004978 for (count = capped_count; count != 0; --count) {
Mathieu Chartier46e811b2013-07-10 17:09:14 -07004979 // For each entry:
4980 // (4b) total allocation size
4981 // (2b) thread id
4982 // (2b) allocated object's class name index
4983 // (1b) stack depth
4984 AllocRecord* record = &recent_allocation_records_[idx];
4985 size_t stack_depth = record->GetDepth();
Mathieu Chartierf8322842014-05-16 10:59:25 -07004986 size_t allocated_object_class_name_index =
Ian Rogers1ff3c982014-08-12 02:30:58 -07004987 class_names.IndexOf(record->Type()->GetDescriptor(&temp));
Hiroshi Yamauchib5a9e3d2014-06-09 12:11:20 -07004988 JDWP::Append4BE(bytes, record->ByteCount());
4989 JDWP::Append2BE(bytes, record->ThinLockId());
Mathieu Chartier46e811b2013-07-10 17:09:14 -07004990 JDWP::Append2BE(bytes, allocated_object_class_name_index);
4991 JDWP::Append1BE(bytes, stack_depth);
4992
Mathieu Chartier46e811b2013-07-10 17:09:14 -07004993 for (size_t stack_frame = 0; stack_frame < stack_depth; ++stack_frame) {
4994 // For each stack frame:
4995 // (2b) method's class name
4996 // (2b) method name
4997 // (2b) method source file
4998 // (2b) line number, clipped to 32767; -2 if native; -1 if no source
Hiroshi Yamauchib5a9e3d2014-06-09 12:11:20 -07004999 mirror::ArtMethod* m = record->StackElement(stack_frame)->Method();
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07005000 size_t class_name_index = class_names.IndexOf(m->GetDeclaringClassDescriptor());
5001 size_t method_name_index = method_names.IndexOf(m->GetName());
5002 size_t file_name_index = filenames.IndexOf(GetMethodSourceFile(m));
Mathieu Chartier46e811b2013-07-10 17:09:14 -07005003 JDWP::Append2BE(bytes, class_name_index);
5004 JDWP::Append2BE(bytes, method_name_index);
5005 JDWP::Append2BE(bytes, file_name_index);
Hiroshi Yamauchib5a9e3d2014-06-09 12:11:20 -07005006 JDWP::Append2BE(bytes, record->StackElement(stack_frame)->LineNumber());
Mathieu Chartier46e811b2013-07-10 17:09:14 -07005007 }
Ian Rogers719d1a32014-03-06 12:13:39 -08005008 idx = (idx + 1) & (alloc_record_max_ - 1);
Mathieu Chartier46e811b2013-07-10 17:09:14 -07005009 }
5010
5011 // (xb) class name strings
5012 // (xb) method name strings
5013 // (xb) source file strings
5014 JDWP::Set4BE(&bytes[string_table_offset], bytes.size());
5015 class_names.WriteTo(bytes);
5016 method_names.WriteTo(bytes);
5017 filenames.WriteTo(bytes);
Elliott Hughes545a0642011-11-08 19:10:03 -08005018 }
Ian Rogers50b35e22012-10-04 10:09:15 -07005019 JNIEnv* env = self->GetJniEnv();
Elliott Hughes545a0642011-11-08 19:10:03 -08005020 jbyteArray result = env->NewByteArray(bytes.size());
Ian Rogersc0542af2014-09-03 16:16:56 -07005021 if (result != nullptr) {
Elliott Hughes545a0642011-11-08 19:10:03 -08005022 env->SetByteArrayRegion(result, 0, bytes.size(), reinterpret_cast<const jbyte*>(&bytes[0]));
5023 }
5024 return result;
5025}
5026
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07005027mirror::ArtMethod* DeoptimizationRequest::Method() const {
5028 ScopedObjectAccessUnchecked soa(Thread::Current());
5029 return soa.DecodeMethod(method_);
5030}
5031
5032void DeoptimizationRequest::SetMethod(mirror::ArtMethod* m) {
5033 ScopedObjectAccessUnchecked soa(Thread::Current());
5034 method_ = soa.EncodeMethod(m);
5035}
5036
Elliott Hughes872d4ec2011-10-21 17:07:15 -07005037} // namespace art