blob: 24615e2a667273174699b734f7ddf8d2d5d906e8 [file] [log] [blame]
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001/*
2 * Copyright (C) 2008 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17#include "debugger.h"
18
Elliott Hughes3bb81562011-10-21 18:52:59 -070019#include <sys/uio.h>
20
Elliott Hughes545a0642011-11-08 19:10:03 -080021#include <set>
22
Ian Rogers166db042013-07-26 12:05:57 -070023#include "arch/context.h"
Mathieu Chartierc7853442015-03-27 14:35:38 -070024#include "art_field-inl.h"
Mathieu Chartiere401d142015-04-22 13:56:20 -070025#include "art_method-inl.h"
Vladimir Marko80afd022015-05-19 18:08:00 +010026#include "base/time_utils.h"
Elliott Hughes545a0642011-11-08 19:10:03 -080027#include "class_linker.h"
Ian Rogers2dd0e2c2013-01-24 12:42:14 -080028#include "class_linker-inl.h"
Ian Rogers4f6ad8a2013-03-18 15:27:28 -070029#include "dex_file-inl.h"
Ian Rogers776ac1f2012-04-13 23:36:36 -070030#include "dex_instruction.h"
Ian Rogers1d54e732013-05-02 21:10:01 -070031#include "gc/accounting/card_table-inl.h"
32#include "gc/space/large_object_space.h"
33#include "gc/space/space-inl.h"
Mathieu Chartiereb8167a2014-05-07 15:43:14 -070034#include "handle_scope.h"
Elliott Hughes64f574f2013-02-20 14:57:12 -080035#include "jdwp/object_registry.h"
Ian Rogers2dd0e2c2013-01-24 12:42:14 -080036#include "mirror/class.h"
37#include "mirror/class-inl.h"
38#include "mirror/class_loader.h"
Ian Rogers2dd0e2c2013-01-24 12:42:14 -080039#include "mirror/object-inl.h"
40#include "mirror/object_array-inl.h"
Ian Rogersb0fa5dc2014-04-28 16:47:08 -070041#include "mirror/string-inl.h"
Ian Rogers2dd0e2c2013-01-24 12:42:14 -080042#include "mirror/throwable.h"
Sebastien Hertza76a6d42014-03-20 16:40:17 +010043#include "quick/inline_method_analyser.h"
Ian Rogers53b8b092014-03-13 23:45:53 -070044#include "reflection.h"
Elliott Hughesa0e18062012-04-13 15:59:59 -070045#include "safe_map.h"
Elliott Hughes64f574f2013-02-20 14:57:12 -080046#include "scoped_thread_state_change.h"
Elliott Hughes6a5bd492011-10-28 14:33:57 -070047#include "ScopedLocalRef.h"
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -070048#include "ScopedPrimitiveArray.h"
Mathieu Chartiereb8167a2014-05-07 15:43:14 -070049#include "handle_scope-inl.h"
Elliott Hughes475fc232011-10-25 15:00:35 -070050#include "thread_list.h"
Ian Rogers2dd0e2c2013-01-24 12:42:14 -080051#include "utf.h"
Sebastien Hertza76a6d42014-03-20 16:40:17 +010052#include "verifier/method_verifier-inl.h"
Elliott Hugheseac76672012-05-24 21:56:51 -070053#include "well_known_classes.h"
Elliott Hughes475fc232011-10-25 15:00:35 -070054
Brian Carlstrom3d92d522013-07-12 09:03:08 -070055#ifdef HAVE_ANDROID_OS
56#include "cutils/properties.h"
57#endif
58
Elliott Hughes872d4ec2011-10-21 17:07:15 -070059namespace art {
60
Sebastien Hertz0462c4c2015-04-01 16:34:17 +020061// The key identifying the debugger to update instrumentation.
62static constexpr const char* kDbgInstrumentationKey = "Debugger";
63
Brian Carlstrom7934ac22013-07-26 10:54:15 -070064static const size_t kMaxAllocRecordStackDepth = 16; // Max 255.
Brian Carlstrom306db812014-09-05 13:01:41 -070065static const size_t kDefaultNumAllocRecords = 64*1024; // Must be a power of 2. 2BE can hold 64k-1.
66
67// Limit alloc_record_count to the 2BE value that is the limit of the current protocol.
68static uint16_t CappedAllocRecordCount(size_t alloc_record_count) {
69 if (alloc_record_count > 0xffff) {
70 return 0xffff;
71 }
72 return alloc_record_count;
73}
Elliott Hughes475fc232011-10-25 15:00:35 -070074
Hiroshi Yamauchib5a9e3d2014-06-09 12:11:20 -070075class AllocRecordStackTraceElement {
76 public:
77 AllocRecordStackTraceElement() : method_(nullptr), dex_pc_(0) {
Mathieu Chartier412c7fc2014-02-07 12:18:39 -080078 }
79
Hiroshi Yamauchib5a9e3d2014-06-09 12:11:20 -070080 int32_t LineNumber() SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Mathieu Chartiere401d142015-04-22 13:56:20 -070081 ArtMethod* method = Method();
Hiroshi Yamauchib5a9e3d2014-06-09 12:11:20 -070082 DCHECK(method != nullptr);
83 return method->GetLineNumFromDexPC(DexPc());
Elliott Hughes545a0642011-11-08 19:10:03 -080084 }
Hiroshi Yamauchib5a9e3d2014-06-09 12:11:20 -070085
Mathieu Chartiere401d142015-04-22 13:56:20 -070086 ArtMethod* Method() SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Mathieu Chartier4345c462014-06-27 10:20:14 -070087 ScopedObjectAccessUnchecked soa(Thread::Current());
88 return soa.DecodeMethod(method_);
Hiroshi Yamauchib5a9e3d2014-06-09 12:11:20 -070089 }
90
Mathieu Chartiere401d142015-04-22 13:56:20 -070091 void SetMethod(ArtMethod* m) SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Hiroshi Yamauchib5a9e3d2014-06-09 12:11:20 -070092 ScopedObjectAccessUnchecked soa(Thread::Current());
Mathieu Chartier4345c462014-06-27 10:20:14 -070093 method_ = soa.EncodeMethod(m);
Hiroshi Yamauchib5a9e3d2014-06-09 12:11:20 -070094 }
95
96 uint32_t DexPc() const {
97 return dex_pc_;
98 }
99
100 void SetDexPc(uint32_t pc) {
101 dex_pc_ = pc;
102 }
103
104 private:
Mathieu Chartier4345c462014-06-27 10:20:14 -0700105 jmethodID method_;
Hiroshi Yamauchib5a9e3d2014-06-09 12:11:20 -0700106 uint32_t dex_pc_;
Elliott Hughes545a0642011-11-08 19:10:03 -0800107};
108
Mathieu Chartier4345c462014-06-27 10:20:14 -0700109jobject Dbg::TypeCache::Add(mirror::Class* t) {
110 ScopedObjectAccessUnchecked soa(Thread::Current());
Mathieu Chartier4c4d6092015-01-22 17:02:27 -0800111 JNIEnv* const env = soa.Env();
112 ScopedLocalRef<jobject> local_ref(soa.Env(), soa.AddLocalReference<jobject>(t));
113 const int32_t hash_code = soa.Decode<mirror::Class*>(local_ref.get())->IdentityHashCode();
Mathieu Chartier4345c462014-06-27 10:20:14 -0700114 auto range = objects_.equal_range(hash_code);
115 for (auto it = range.first; it != range.second; ++it) {
Mathieu Chartier4c4d6092015-01-22 17:02:27 -0800116 if (soa.Decode<mirror::Class*>(it->second) == soa.Decode<mirror::Class*>(local_ref.get())) {
Mathieu Chartier4345c462014-06-27 10:20:14 -0700117 // Found a matching weak global, return it.
118 return it->second;
119 }
120 }
Mathieu Chartier4c4d6092015-01-22 17:02:27 -0800121 const jobject weak_global = env->NewWeakGlobalRef(local_ref.get());
Mathieu Chartier4345c462014-06-27 10:20:14 -0700122 objects_.insert(std::make_pair(hash_code, weak_global));
123 return weak_global;
124}
125
126void Dbg::TypeCache::Clear() {
Brian Carlstrom306db812014-09-05 13:01:41 -0700127 JavaVMExt* vm = Runtime::Current()->GetJavaVM();
128 Thread* self = Thread::Current();
Mathieu Chartier4345c462014-06-27 10:20:14 -0700129 for (const auto& p : objects_) {
Brian Carlstrom306db812014-09-05 13:01:41 -0700130 vm->DeleteWeakGlobalRef(self, p.second);
Mathieu Chartier4345c462014-06-27 10:20:14 -0700131 }
132 objects_.clear();
133}
134
Hiroshi Yamauchib5a9e3d2014-06-09 12:11:20 -0700135class AllocRecord {
136 public:
137 AllocRecord() : type_(nullptr), byte_count_(0), thin_lock_id_(0) {}
Elliott Hughes545a0642011-11-08 19:10:03 -0800138
Hiroshi Yamauchib5a9e3d2014-06-09 12:11:20 -0700139 mirror::Class* Type() SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Mathieu Chartier4345c462014-06-27 10:20:14 -0700140 return down_cast<mirror::Class*>(Thread::Current()->DecodeJObject(type_));
Hiroshi Yamauchib5a9e3d2014-06-09 12:11:20 -0700141 }
142
Brian Carlstrom306db812014-09-05 13:01:41 -0700143 void SetType(mirror::Class* t) SHARED_LOCKS_REQUIRED(Locks::mutator_lock_,
144 Locks::alloc_tracker_lock_) {
145 type_ = Dbg::type_cache_.Add(t);
Hiroshi Yamauchib5a9e3d2014-06-09 12:11:20 -0700146 }
147
148 size_t GetDepth() SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Elliott Hughes545a0642011-11-08 19:10:03 -0800149 size_t depth = 0;
Ian Rogersc0542af2014-09-03 16:16:56 -0700150 while (depth < kMaxAllocRecordStackDepth && stack_[depth].Method() != nullptr) {
Elliott Hughes545a0642011-11-08 19:10:03 -0800151 ++depth;
152 }
153 return depth;
154 }
Mathieu Chartier412c7fc2014-02-07 12:18:39 -0800155
Hiroshi Yamauchib5a9e3d2014-06-09 12:11:20 -0700156 size_t ByteCount() const {
157 return byte_count_;
Mathieu Chartier412c7fc2014-02-07 12:18:39 -0800158 }
Hiroshi Yamauchib5a9e3d2014-06-09 12:11:20 -0700159
160 void SetByteCount(size_t count) {
161 byte_count_ = count;
162 }
163
164 uint16_t ThinLockId() const {
165 return thin_lock_id_;
166 }
167
168 void SetThinLockId(uint16_t id) {
169 thin_lock_id_ = id;
170 }
171
172 AllocRecordStackTraceElement* StackElement(size_t index) {
173 DCHECK_LT(index, kMaxAllocRecordStackDepth);
174 return &stack_[index];
175 }
176
177 private:
178 jobject type_; // This is a weak global.
179 size_t byte_count_;
180 uint16_t thin_lock_id_;
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700181 // Unused entries have null method.
182 AllocRecordStackTraceElement stack_[kMaxAllocRecordStackDepth];
Elliott Hughes545a0642011-11-08 19:10:03 -0800183};
184
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -0700185class Breakpoint {
186 public:
Mathieu Chartiere401d142015-04-22 13:56:20 -0700187 Breakpoint(ArtMethod* method, uint32_t dex_pc,
Sebastien Hertzf3928792014-11-17 19:00:37 +0100188 DeoptimizationRequest::Kind deoptimization_kind)
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -0700189 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_)
Sebastien Hertzf3928792014-11-17 19:00:37 +0100190 : method_(nullptr), dex_pc_(dex_pc), deoptimization_kind_(deoptimization_kind) {
191 CHECK(deoptimization_kind_ == DeoptimizationRequest::kNothing ||
192 deoptimization_kind_ == DeoptimizationRequest::kSelectiveDeoptimization ||
193 deoptimization_kind_ == DeoptimizationRequest::kFullDeoptimization);
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -0700194 ScopedObjectAccessUnchecked soa(Thread::Current());
195 method_ = soa.EncodeMethod(method);
196 }
197
198 Breakpoint(const Breakpoint& other) SHARED_LOCKS_REQUIRED(Locks::mutator_lock_)
199 : method_(nullptr), dex_pc_(other.dex_pc_),
Sebastien Hertzf3928792014-11-17 19:00:37 +0100200 deoptimization_kind_(other.deoptimization_kind_) {
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -0700201 ScopedObjectAccessUnchecked soa(Thread::Current());
202 method_ = soa.EncodeMethod(other.Method());
203 }
204
Mathieu Chartiere401d142015-04-22 13:56:20 -0700205 ArtMethod* Method() const SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -0700206 ScopedObjectAccessUnchecked soa(Thread::Current());
207 return soa.DecodeMethod(method_);
208 }
209
210 uint32_t DexPc() const {
211 return dex_pc_;
212 }
213
Sebastien Hertzf3928792014-11-17 19:00:37 +0100214 DeoptimizationRequest::Kind GetDeoptimizationKind() const {
215 return deoptimization_kind_;
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -0700216 }
217
218 private:
Sebastien Hertza76a6d42014-03-20 16:40:17 +0100219 // The location of this breakpoint.
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -0700220 jmethodID method_;
221 uint32_t dex_pc_;
Sebastien Hertza76a6d42014-03-20 16:40:17 +0100222
223 // Indicates whether breakpoint needs full deoptimization or selective deoptimization.
Sebastien Hertzf3928792014-11-17 19:00:37 +0100224 DeoptimizationRequest::Kind deoptimization_kind_;
Elliott Hughes86964332012-02-15 19:37:42 -0800225};
226
Sebastien Hertzed2be172014-08-19 15:33:43 +0200227static std::ostream& operator<<(std::ostream& os, const Breakpoint& rhs)
Ian Rogersb726dcb2012-09-05 08:57:23 -0700228 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -0700229 os << StringPrintf("Breakpoint[%s @%#x]", PrettyMethod(rhs.Method()).c_str(), rhs.DexPc());
Elliott Hughes86964332012-02-15 19:37:42 -0800230 return os;
231}
232
Sebastien Hertz3f52eaf2014-04-04 17:50:18 +0200233class DebugInstrumentationListener FINAL : public instrumentation::InstrumentationListener {
Ian Rogers62d6c772013-02-27 08:32:07 -0800234 public:
235 DebugInstrumentationListener() {}
236 virtual ~DebugInstrumentationListener() {}
237
Mathieu Chartiere401d142015-04-22 13:56:20 -0700238 void MethodEntered(Thread* thread, mirror::Object* this_object, ArtMethod* method,
Sebastien Hertz9d6bf692015-04-10 12:12:33 +0200239 uint32_t dex_pc)
Sebastien Hertz3f52eaf2014-04-04 17:50:18 +0200240 OVERRIDE SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Ian Rogers62d6c772013-02-27 08:32:07 -0800241 if (method->IsNative()) {
242 // TODO: post location events is a suspension point and native method entry stubs aren't.
243 return;
244 }
Sebastien Hertz9d6bf692015-04-10 12:12:33 +0200245 if (IsListeningToDexPcMoved()) {
246 // We also listen to kDexPcMoved instrumentation event so we know the DexPcMoved method is
247 // going to be called right after us. To avoid sending JDWP events twice for this location,
248 // we report the event in DexPcMoved. However, we must remind this is method entry so we
249 // send the METHOD_ENTRY event. And we can also group it with other events for this location
250 // like BREAKPOINT or SINGLE_STEP (or even METHOD_EXIT if this is a RETURN instruction).
251 thread->SetDebugMethodEntry();
252 } else if (IsListeningToMethodExit() && IsReturn(method, dex_pc)) {
253 // We also listen to kMethodExited instrumentation event and the current instruction is a
254 // RETURN so we know the MethodExited method is going to be called right after us. To avoid
255 // sending JDWP events twice for this location, we report the event(s) in MethodExited.
256 // However, we must remind this is method entry so we send the METHOD_ENTRY event. And we can
257 // also group it with other events for this location like BREAKPOINT or SINGLE_STEP.
258 thread->SetDebugMethodEntry();
259 } else {
260 Dbg::UpdateDebugger(thread, this_object, method, 0, Dbg::kMethodEntry, nullptr);
261 }
Ian Rogers62d6c772013-02-27 08:32:07 -0800262 }
263
Mathieu Chartiere401d142015-04-22 13:56:20 -0700264 void MethodExited(Thread* thread, mirror::Object* this_object, ArtMethod* method,
Sebastien Hertz3f52eaf2014-04-04 17:50:18 +0200265 uint32_t dex_pc, const JValue& return_value)
266 OVERRIDE SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Ian Rogers62d6c772013-02-27 08:32:07 -0800267 if (method->IsNative()) {
268 // TODO: post location events is a suspension point and native method entry stubs aren't.
269 return;
270 }
Sebastien Hertz9d6bf692015-04-10 12:12:33 +0200271 uint32_t events = Dbg::kMethodExit;
272 if (thread->IsDebugMethodEntry()) {
273 // It is also the method entry.
274 DCHECK(IsReturn(method, dex_pc));
275 events |= Dbg::kMethodEntry;
276 thread->ClearDebugMethodEntry();
277 }
278 Dbg::UpdateDebugger(thread, this_object, method, dex_pc, events, &return_value);
Ian Rogers62d6c772013-02-27 08:32:07 -0800279 }
280
Sebastien Hertz9d6bf692015-04-10 12:12:33 +0200281 void MethodUnwind(Thread* thread ATTRIBUTE_UNUSED, mirror::Object* this_object ATTRIBUTE_UNUSED,
Mathieu Chartiere401d142015-04-22 13:56:20 -0700282 ArtMethod* method, uint32_t dex_pc)
Sebastien Hertz3f52eaf2014-04-04 17:50:18 +0200283 OVERRIDE SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Ian Rogers62d6c772013-02-27 08:32:07 -0800284 // We're not recorded to listen to this kind of event, so complain.
285 LOG(ERROR) << "Unexpected method unwind event in debugger " << PrettyMethod(method)
Sebastien Hertz51db44a2013-11-19 10:00:29 +0100286 << " " << dex_pc;
Ian Rogers62d6c772013-02-27 08:32:07 -0800287 }
288
Mathieu Chartiere401d142015-04-22 13:56:20 -0700289 void DexPcMoved(Thread* thread, mirror::Object* this_object, ArtMethod* method,
Sebastien Hertz3f52eaf2014-04-04 17:50:18 +0200290 uint32_t new_dex_pc)
291 OVERRIDE SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Sebastien Hertz9d6bf692015-04-10 12:12:33 +0200292 if (IsListeningToMethodExit() && IsReturn(method, new_dex_pc)) {
293 // We also listen to kMethodExited instrumentation event and the current instruction is a
294 // RETURN so we know the MethodExited method is going to be called right after us. Like in
295 // MethodEntered, we delegate event reporting to MethodExited.
296 // Besides, if this RETURN instruction is the only one in the method, we can send multiple
297 // JDWP events in the same packet: METHOD_ENTRY, METHOD_EXIT, BREAKPOINT and/or SINGLE_STEP.
298 // Therefore, we must not clear the debug method entry flag here.
299 } else {
300 uint32_t events = 0;
301 if (thread->IsDebugMethodEntry()) {
302 // It is also the method entry.
303 events = Dbg::kMethodEntry;
304 thread->ClearDebugMethodEntry();
305 }
306 Dbg::UpdateDebugger(thread, this_object, method, new_dex_pc, events, nullptr);
307 }
Ian Rogers62d6c772013-02-27 08:32:07 -0800308 }
309
Sebastien Hertz9d6bf692015-04-10 12:12:33 +0200310 void FieldRead(Thread* thread ATTRIBUTE_UNUSED, mirror::Object* this_object,
Mathieu Chartiere401d142015-04-22 13:56:20 -0700311 ArtMethod* method, uint32_t dex_pc, ArtField* field)
Sebastien Hertz3f52eaf2014-04-04 17:50:18 +0200312 OVERRIDE SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
313 Dbg::PostFieldAccessEvent(method, dex_pc, this_object, field);
Ian Rogers62d6c772013-02-27 08:32:07 -0800314 }
Sebastien Hertz3f52eaf2014-04-04 17:50:18 +0200315
Ian Rogers6a3c1fc2014-10-31 00:33:20 -0700316 void FieldWritten(Thread* thread ATTRIBUTE_UNUSED, mirror::Object* this_object,
Mathieu Chartiere401d142015-04-22 13:56:20 -0700317 ArtMethod* method, uint32_t dex_pc, ArtField* field,
Ian Rogers6a3c1fc2014-10-31 00:33:20 -0700318 const JValue& field_value)
Sebastien Hertz3f52eaf2014-04-04 17:50:18 +0200319 OVERRIDE SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
320 Dbg::PostFieldModificationEvent(method, dex_pc, this_object, field, &field_value);
321 }
322
Nicolas Geoffray14691c52015-03-05 10:40:17 +0000323 void ExceptionCaught(Thread* thread ATTRIBUTE_UNUSED, mirror::Throwable* exception_object)
Sebastien Hertz3f52eaf2014-04-04 17:50:18 +0200324 OVERRIDE SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Nicolas Geoffray14691c52015-03-05 10:40:17 +0000325 Dbg::PostException(exception_object);
Sebastien Hertz3f52eaf2014-04-04 17:50:18 +0200326 }
327
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800328 // We only care about how many backward branches were executed in the Jit.
Mathieu Chartiere401d142015-04-22 13:56:20 -0700329 void BackwardBranch(Thread* /*thread*/, ArtMethod* method, int32_t dex_pc_offset)
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800330 OVERRIDE SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
331 LOG(ERROR) << "Unexpected backward branch event in debugger " << PrettyMethod(method)
332 << " " << dex_pc_offset;
333 }
334
Sebastien Hertz3f52eaf2014-04-04 17:50:18 +0200335 private:
Mathieu Chartiere401d142015-04-22 13:56:20 -0700336 static bool IsReturn(ArtMethod* method, uint32_t dex_pc)
Sebastien Hertz9d6bf692015-04-10 12:12:33 +0200337 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
338 const DexFile::CodeItem* code_item = method->GetCodeItem();
339 const Instruction* instruction = Instruction::At(&code_item->insns_[dex_pc]);
340 return instruction->IsReturn();
341 }
342
343 static bool IsListeningToDexPcMoved() SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
344 return IsListeningTo(instrumentation::Instrumentation::kDexPcMoved);
345 }
346
347 static bool IsListeningToMethodExit() SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
348 return IsListeningTo(instrumentation::Instrumentation::kMethodExited);
349 }
350
351 static bool IsListeningTo(instrumentation::Instrumentation::InstrumentationEvent event)
352 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
353 return (Dbg::GetInstrumentationEvents() & event) != 0;
354 }
355
Sebastien Hertz3f52eaf2014-04-04 17:50:18 +0200356 DISALLOW_COPY_AND_ASSIGN(DebugInstrumentationListener);
Ian Rogers62d6c772013-02-27 08:32:07 -0800357} gDebugInstrumentationListener;
358
Elliott Hughes4ffd3132011-10-24 12:06:42 -0700359// JDWP is allowed unless the Zygote forbids it.
360static bool gJdwpAllowed = true;
361
Elliott Hughesc0f09332012-03-26 13:27:06 -0700362// Was there a -Xrunjdwp or -agentlib:jdwp= argument on the command line?
Elliott Hughes3bb81562011-10-21 18:52:59 -0700363static bool gJdwpConfigured = false;
364
Sebastien Hertzb3b173b2015-02-06 09:16:32 +0100365// JDWP options for debugging. Only valid if IsJdwpConfigured() is true.
366static JDWP::JdwpOptions gJdwpOptions;
367
Elliott Hughes3bb81562011-10-21 18:52:59 -0700368// Runtime JDWP state.
Ian Rogersc0542af2014-09-03 16:16:56 -0700369static JDWP::JdwpState* gJdwpState = nullptr;
Elliott Hughes3bb81562011-10-21 18:52:59 -0700370static bool gDebuggerConnected; // debugger or DDMS is connected.
Elliott Hughes3bb81562011-10-21 18:52:59 -0700371
Elliott Hughes47fce012011-10-25 18:37:19 -0700372static bool gDdmThreadNotification = false;
373
Elliott Hughes767a1472011-10-26 18:49:02 -0700374// DDMS GC-related settings.
375static Dbg::HpifWhen gDdmHpifWhen = Dbg::HPIF_WHEN_NEVER;
376static Dbg::HpsgWhen gDdmHpsgWhen = Dbg::HPSG_WHEN_NEVER;
377static Dbg::HpsgWhat gDdmHpsgWhat;
378static Dbg::HpsgWhen gDdmNhsgWhen = Dbg::HPSG_WHEN_NEVER;
379static Dbg::HpsgWhat gDdmNhsgWhat;
380
Daniel Mihalyieb076692014-08-22 17:33:31 +0200381bool Dbg::gDebuggerActive = false;
Sebastien Hertz4e5b2082015-03-24 19:03:40 +0100382bool Dbg::gDisposed = false;
Sebastien Hertz6995c602014-09-09 12:10:13 +0200383ObjectRegistry* Dbg::gRegistry = nullptr;
Elliott Hughes475fc232011-10-25 15:00:35 -0700384
Elliott Hughes545a0642011-11-08 19:10:03 -0800385// Recent allocation tracking.
Ian Rogers719d1a32014-03-06 12:13:39 -0800386AllocRecord* Dbg::recent_allocation_records_ = nullptr; // TODO: CircularBuffer<AllocRecord>
387size_t Dbg::alloc_record_max_ = 0;
388size_t Dbg::alloc_record_head_ = 0;
389size_t Dbg::alloc_record_count_ = 0;
Mathieu Chartier4345c462014-06-27 10:20:14 -0700390Dbg::TypeCache Dbg::type_cache_;
Elliott Hughes545a0642011-11-08 19:10:03 -0800391
Sebastien Hertz138dbfc2013-12-04 18:15:25 +0100392// Deoptimization support.
Sebastien Hertz4d25df32014-03-21 17:44:46 +0100393std::vector<DeoptimizationRequest> Dbg::deoptimization_requests_;
394size_t Dbg::full_deoptimization_event_count_ = 0;
Sebastien Hertz138dbfc2013-12-04 18:15:25 +0100395
Sebastien Hertz42cd43f2014-05-13 14:15:41 +0200396// Instrumentation event reference counters.
397size_t Dbg::dex_pc_change_event_ref_count_ = 0;
398size_t Dbg::method_enter_event_ref_count_ = 0;
399size_t Dbg::method_exit_event_ref_count_ = 0;
400size_t Dbg::field_read_event_ref_count_ = 0;
401size_t Dbg::field_write_event_ref_count_ = 0;
402size_t Dbg::exception_catch_event_ref_count_ = 0;
403uint32_t Dbg::instrumentation_events_ = 0;
404
Sebastien Hertz138dbfc2013-12-04 18:15:25 +0100405// Breakpoints.
jeffhao09bfc6a2012-12-11 18:11:43 -0800406static std::vector<Breakpoint> gBreakpoints GUARDED_BY(Locks::breakpoint_lock_);
Elliott Hughes86964332012-02-15 19:37:42 -0800407
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -0700408void DebugInvokeReq::VisitRoots(RootVisitor* visitor, const RootInfo& root_info) {
409 receiver.VisitRootIfNonNull(visitor, root_info); // null for static method call.
410 klass.VisitRoot(visitor, root_info);
Mathieu Chartier3b05e9b2014-03-25 09:29:43 -0700411}
412
Sebastien Hertz597c4f02015-01-26 17:37:14 +0100413void SingleStepControl::AddDexPc(uint32_t dex_pc) {
414 dex_pcs_.insert(dex_pc);
Sebastien Hertzbb43b432014-04-14 11:59:08 +0200415}
416
Sebastien Hertz597c4f02015-01-26 17:37:14 +0100417bool SingleStepControl::ContainsDexPc(uint32_t dex_pc) const {
418 return dex_pcs_.find(dex_pc) == dex_pcs_.end();
Sebastien Hertzbb43b432014-04-14 11:59:08 +0200419}
420
Mathieu Chartiere401d142015-04-22 13:56:20 -0700421static bool IsBreakpoint(const ArtMethod* m, uint32_t dex_pc)
jeffhao09bfc6a2012-12-11 18:11:43 -0800422 LOCKS_EXCLUDED(Locks::breakpoint_lock_)
Ian Rogersb726dcb2012-09-05 08:57:23 -0700423 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Sebastien Hertzed2be172014-08-19 15:33:43 +0200424 ReaderMutexLock mu(Thread::Current(), *Locks::breakpoint_lock_);
Sebastien Hertz138dbfc2013-12-04 18:15:25 +0100425 for (size_t i = 0, e = gBreakpoints.size(); i < e; ++i) {
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -0700426 if (gBreakpoints[i].DexPc() == dex_pc && gBreakpoints[i].Method() == m) {
Elliott Hughes86964332012-02-15 19:37:42 -0800427 VLOG(jdwp) << "Hit breakpoint #" << i << ": " << gBreakpoints[i];
428 return true;
429 }
430 }
431 return false;
432}
433
Sebastien Hertz52d131d2014-03-13 16:17:40 +0100434static bool IsSuspendedForDebugger(ScopedObjectAccessUnchecked& soa, Thread* thread)
435 LOCKS_EXCLUDED(Locks::thread_suspend_count_lock_) {
Elliott Hughes9e0c1752013-01-09 14:02:58 -0800436 MutexLock mu(soa.Self(), *Locks::thread_suspend_count_lock_);
437 // A thread may be suspended for GC; in this code, we really want to know whether
438 // there's a debugger suspension active.
439 return thread->IsSuspended() && thread->GetDebugSuspendCount() > 0;
440}
441
Ian Rogersc0542af2014-09-03 16:16:56 -0700442static mirror::Array* DecodeNonNullArray(JDWP::RefTypeId id, JDWP::JdwpError* error)
Ian Rogersb726dcb2012-09-05 08:57:23 -0700443 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Sebastien Hertz6995c602014-09-09 12:10:13 +0200444 mirror::Object* o = Dbg::GetObjectRegistry()->Get<mirror::Object*>(id, error);
Ian Rogersc0542af2014-09-03 16:16:56 -0700445 if (o == nullptr) {
446 *error = JDWP::ERR_INVALID_OBJECT;
447 return nullptr;
Elliott Hughes436e3722012-02-17 20:01:47 -0800448 }
449 if (!o->IsArrayInstance()) {
Ian Rogersc0542af2014-09-03 16:16:56 -0700450 *error = JDWP::ERR_INVALID_ARRAY;
451 return nullptr;
Elliott Hughes436e3722012-02-17 20:01:47 -0800452 }
Ian Rogersc0542af2014-09-03 16:16:56 -0700453 *error = JDWP::ERR_NONE;
Elliott Hughes436e3722012-02-17 20:01:47 -0800454 return o->AsArray();
455}
456
Ian Rogersc0542af2014-09-03 16:16:56 -0700457static mirror::Class* DecodeClass(JDWP::RefTypeId id, JDWP::JdwpError* error)
Ian Rogersb726dcb2012-09-05 08:57:23 -0700458 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Sebastien Hertz6995c602014-09-09 12:10:13 +0200459 mirror::Object* o = Dbg::GetObjectRegistry()->Get<mirror::Object*>(id, error);
Ian Rogersc0542af2014-09-03 16:16:56 -0700460 if (o == nullptr) {
461 *error = JDWP::ERR_INVALID_OBJECT;
462 return nullptr;
Elliott Hughes436e3722012-02-17 20:01:47 -0800463 }
464 if (!o->IsClass()) {
Ian Rogersc0542af2014-09-03 16:16:56 -0700465 *error = JDWP::ERR_INVALID_CLASS;
466 return nullptr;
Elliott Hughes436e3722012-02-17 20:01:47 -0800467 }
Ian Rogersc0542af2014-09-03 16:16:56 -0700468 *error = JDWP::ERR_NONE;
Elliott Hughes436e3722012-02-17 20:01:47 -0800469 return o->AsClass();
470}
471
Ian Rogersc0542af2014-09-03 16:16:56 -0700472static Thread* DecodeThread(ScopedObjectAccessUnchecked& soa, JDWP::ObjectId thread_id,
473 JDWP::JdwpError* error)
Sebastien Hertz69206392015-04-07 15:54:25 +0200474 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_)
475 LOCKS_EXCLUDED(Locks::thread_list_lock_, Locks::thread_suspend_count_lock_) {
Sebastien Hertz6995c602014-09-09 12:10:13 +0200476 mirror::Object* thread_peer = Dbg::GetObjectRegistry()->Get<mirror::Object*>(thread_id, error);
Ian Rogersc0542af2014-09-03 16:16:56 -0700477 if (thread_peer == nullptr) {
Elliott Hughes221229c2013-01-08 18:17:50 -0800478 // This isn't even an object.
Ian Rogersc0542af2014-09-03 16:16:56 -0700479 *error = JDWP::ERR_INVALID_OBJECT;
480 return nullptr;
Elliott Hughes436e3722012-02-17 20:01:47 -0800481 }
Elliott Hughes221229c2013-01-08 18:17:50 -0800482
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800483 mirror::Class* java_lang_Thread = soa.Decode<mirror::Class*>(WellKnownClasses::java_lang_Thread);
Elliott Hughes221229c2013-01-08 18:17:50 -0800484 if (!java_lang_Thread->IsAssignableFrom(thread_peer->GetClass())) {
485 // This isn't a thread.
Ian Rogersc0542af2014-09-03 16:16:56 -0700486 *error = JDWP::ERR_INVALID_THREAD;
487 return nullptr;
Elliott Hughes221229c2013-01-08 18:17:50 -0800488 }
489
Sebastien Hertz69206392015-04-07 15:54:25 +0200490 MutexLock mu(soa.Self(), *Locks::thread_list_lock_);
Ian Rogersc0542af2014-09-03 16:16:56 -0700491 Thread* thread = Thread::FromManagedThread(soa, thread_peer);
492 // If thread is null then this a java.lang.Thread without a Thread*. Must be a un-started or a
493 // zombie.
494 *error = (thread == nullptr) ? JDWP::ERR_THREAD_NOT_ALIVE : JDWP::ERR_NONE;
495 return thread;
Elliott Hughes436e3722012-02-17 20:01:47 -0800496}
497
Elliott Hughes24437992011-11-30 14:49:33 -0800498static JDWP::JdwpTag BasicTagFromDescriptor(const char* descriptor) {
499 // JDWP deliberately uses the descriptor characters' ASCII values for its enum.
500 // Note that by "basic" we mean that we don't get more specific than JT_OBJECT.
501 return static_cast<JDWP::JdwpTag>(descriptor[0]);
502}
503
Ian Rogers1ff3c982014-08-12 02:30:58 -0700504static JDWP::JdwpTag BasicTagFromClass(mirror::Class* klass)
505 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
506 std::string temp;
507 const char* descriptor = klass->GetDescriptor(&temp);
508 return BasicTagFromDescriptor(descriptor);
509}
510
Ian Rogers98379392014-02-24 16:53:16 -0800511static JDWP::JdwpTag TagFromClass(const ScopedObjectAccessUnchecked& soa, mirror::Class* c)
Ian Rogersb726dcb2012-09-05 08:57:23 -0700512 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Ian Rogersc0542af2014-09-03 16:16:56 -0700513 CHECK(c != nullptr);
Elliott Hughes24437992011-11-30 14:49:33 -0800514 if (c->IsArrayClass()) {
515 return JDWP::JT_ARRAY;
516 }
Elliott Hughes24437992011-11-30 14:49:33 -0800517 if (c->IsStringClass()) {
518 return JDWP::JT_STRING;
Elliott Hughes24437992011-11-30 14:49:33 -0800519 }
Ian Rogers98379392014-02-24 16:53:16 -0800520 if (c->IsClassClass()) {
521 return JDWP::JT_CLASS_OBJECT;
522 }
523 {
524 mirror::Class* thread_class = soa.Decode<mirror::Class*>(WellKnownClasses::java_lang_Thread);
525 if (thread_class->IsAssignableFrom(c)) {
526 return JDWP::JT_THREAD;
527 }
528 }
529 {
530 mirror::Class* thread_group_class =
531 soa.Decode<mirror::Class*>(WellKnownClasses::java_lang_ThreadGroup);
532 if (thread_group_class->IsAssignableFrom(c)) {
533 return JDWP::JT_THREAD_GROUP;
534 }
535 }
536 {
537 mirror::Class* class_loader_class =
538 soa.Decode<mirror::Class*>(WellKnownClasses::java_lang_ClassLoader);
539 if (class_loader_class->IsAssignableFrom(c)) {
540 return JDWP::JT_CLASS_LOADER;
541 }
542 }
543 return JDWP::JT_OBJECT;
Elliott Hughes24437992011-11-30 14:49:33 -0800544}
545
546/*
547 * Objects declared to hold Object might actually hold a more specific
548 * type. The debugger may take a special interest in these (e.g. it
549 * wants to display the contents of Strings), so we want to return an
550 * appropriate tag.
551 *
552 * Null objects are tagged JT_OBJECT.
553 */
Sebastien Hertz6995c602014-09-09 12:10:13 +0200554JDWP::JdwpTag Dbg::TagFromObject(const ScopedObjectAccessUnchecked& soa, mirror::Object* o) {
Ian Rogersc0542af2014-09-03 16:16:56 -0700555 return (o == nullptr) ? JDWP::JT_OBJECT : TagFromClass(soa, o->GetClass());
Elliott Hughes24437992011-11-30 14:49:33 -0800556}
557
558static bool IsPrimitiveTag(JDWP::JdwpTag tag) {
559 switch (tag) {
560 case JDWP::JT_BOOLEAN:
561 case JDWP::JT_BYTE:
562 case JDWP::JT_CHAR:
563 case JDWP::JT_FLOAT:
564 case JDWP::JT_DOUBLE:
565 case JDWP::JT_INT:
566 case JDWP::JT_LONG:
567 case JDWP::JT_SHORT:
568 case JDWP::JT_VOID:
569 return true;
570 default:
571 return false;
572 }
573}
574
Sebastien Hertzb3b173b2015-02-06 09:16:32 +0100575void Dbg::StartJdwp() {
Elliott Hughesc0f09332012-03-26 13:27:06 -0700576 if (!gJdwpAllowed || !IsJdwpConfigured()) {
Elliott Hughes376a7a02011-10-24 18:35:55 -0700577 // No JDWP for you!
578 return;
579 }
580
Ian Rogers719d1a32014-03-06 12:13:39 -0800581 CHECK(gRegistry == nullptr);
Elliott Hughes475fc232011-10-25 15:00:35 -0700582 gRegistry = new ObjectRegistry;
583
Elliott Hughesd1cc8362011-10-24 16:58:50 -0700584 // Init JDWP if the debugger is enabled. This may connect out to a
585 // debugger, passively listen for a debugger, or block waiting for a
586 // debugger.
Sebastien Hertzb3b173b2015-02-06 09:16:32 +0100587 gJdwpState = JDWP::JdwpState::Create(&gJdwpOptions);
Ian Rogersc0542af2014-09-03 16:16:56 -0700588 if (gJdwpState == nullptr) {
Elliott Hughesf8a2df72011-12-01 12:19:54 -0800589 // We probably failed because some other process has the port already, which means that
590 // if we don't abort the user is likely to think they're talking to us when they're actually
591 // talking to that other process.
Elliott Hughes3d30d9b2011-12-07 17:35:48 -0800592 LOG(FATAL) << "Debugger thread failed to initialize";
Elliott Hughesd1cc8362011-10-24 16:58:50 -0700593 }
594
595 // If a debugger has already attached, send the "welcome" message.
596 // This may cause us to suspend all threads.
Elliott Hughes376a7a02011-10-24 18:35:55 -0700597 if (gJdwpState->IsActive()) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700598 ScopedObjectAccess soa(Thread::Current());
Sebastien Hertz7d955652014-10-22 10:57:10 +0200599 gJdwpState->PostVMStart();
Elliott Hughesd1cc8362011-10-24 16:58:50 -0700600 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700601}
602
Elliott Hughesd1cc8362011-10-24 16:58:50 -0700603void Dbg::StopJdwp() {
Sebastien Hertzc6345ef2014-08-18 19:26:39 +0200604 // Post VM_DEATH event before the JDWP connection is closed (either by the JDWP thread or the
605 // destruction of gJdwpState).
606 if (gJdwpState != nullptr && gJdwpState->IsActive()) {
607 gJdwpState->PostVMDeath();
608 }
Sebastien Hertz0376e6b2014-02-06 18:12:59 +0100609 // Prevent the JDWP thread from processing JDWP incoming packets after we close the connection.
Sebastien Hertz4e5b2082015-03-24 19:03:40 +0100610 Dispose();
Elliott Hughes376a7a02011-10-24 18:35:55 -0700611 delete gJdwpState;
Ian Rogers719d1a32014-03-06 12:13:39 -0800612 gJdwpState = nullptr;
Elliott Hughes475fc232011-10-25 15:00:35 -0700613 delete gRegistry;
Ian Rogers719d1a32014-03-06 12:13:39 -0800614 gRegistry = nullptr;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700615}
616
Elliott Hughes767a1472011-10-26 18:49:02 -0700617void Dbg::GcDidFinish() {
618 if (gDdmHpifWhen != HPIF_WHEN_NEVER) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700619 ScopedObjectAccess soa(Thread::Current());
Brian Carlstrom4d466a82014-05-08 19:05:29 -0700620 VLOG(jdwp) << "Sending heap info to DDM";
Elliott Hughes7162ad92011-10-27 14:08:42 -0700621 DdmSendHeapInfo(gDdmHpifWhen);
Elliott Hughes767a1472011-10-26 18:49:02 -0700622 }
623 if (gDdmHpsgWhen != HPSG_WHEN_NEVER) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700624 ScopedObjectAccess soa(Thread::Current());
Brian Carlstrom4d466a82014-05-08 19:05:29 -0700625 VLOG(jdwp) << "Dumping heap to DDM";
Elliott Hughes6a5bd492011-10-28 14:33:57 -0700626 DdmSendHeapSegments(false);
Elliott Hughes767a1472011-10-26 18:49:02 -0700627 }
628 if (gDdmNhsgWhen != HPSG_WHEN_NEVER) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700629 ScopedObjectAccess soa(Thread::Current());
Brian Carlstrom4d466a82014-05-08 19:05:29 -0700630 VLOG(jdwp) << "Dumping native heap to DDM";
Elliott Hughes6a5bd492011-10-28 14:33:57 -0700631 DdmSendHeapSegments(true);
Elliott Hughes767a1472011-10-26 18:49:02 -0700632 }
633}
634
Elliott Hughes4ffd3132011-10-24 12:06:42 -0700635void Dbg::SetJdwpAllowed(bool allowed) {
636 gJdwpAllowed = allowed;
637}
638
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700639DebugInvokeReq* Dbg::GetInvokeReq() {
Elliott Hughes475fc232011-10-25 15:00:35 -0700640 return Thread::Current()->GetInvokeReq();
641}
642
643Thread* Dbg::GetDebugThread() {
Ian Rogersc0542af2014-09-03 16:16:56 -0700644 return (gJdwpState != nullptr) ? gJdwpState->GetDebugThread() : nullptr;
Elliott Hughes475fc232011-10-25 15:00:35 -0700645}
646
647void Dbg::ClearWaitForEventThread() {
Sebastien Hertz2bf93f42015-01-09 18:44:05 +0100648 gJdwpState->ReleaseJdwpTokenForEvent();
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700649}
650
651void Dbg::Connected() {
Elliott Hughes3bb81562011-10-21 18:52:59 -0700652 CHECK(!gDebuggerConnected);
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -0800653 VLOG(jdwp) << "JDWP has attached";
Elliott Hughes3bb81562011-10-21 18:52:59 -0700654 gDebuggerConnected = true;
Elliott Hughes86964332012-02-15 19:37:42 -0800655 gDisposed = false;
656}
657
Sebastien Hertzf3928792014-11-17 19:00:37 +0100658bool Dbg::RequiresDeoptimization() {
659 // We don't need deoptimization if everything runs with interpreter after
660 // enabling -Xint mode.
661 return !Runtime::Current()->GetInstrumentation()->IsForcedInterpretOnly();
662}
663
Elliott Hughesa2155262011-11-16 16:26:58 -0800664void Dbg::GoActive() {
665 // Enable all debugging features, including scans for breakpoints.
666 // This is a no-op if we're already active.
667 // Only called from the JDWP handler thread.
Daniel Mihalyieb076692014-08-22 17:33:31 +0200668 if (IsDebuggerActive()) {
Elliott Hughesa2155262011-11-16 16:26:58 -0800669 return;
670 }
671
Elliott Hughesc0f09332012-03-26 13:27:06 -0700672 {
673 // TODO: dalvik only warned if there were breakpoints left over. clear in Dbg::Disconnected?
Sebastien Hertzed2be172014-08-19 15:33:43 +0200674 ReaderMutexLock mu(Thread::Current(), *Locks::breakpoint_lock_);
Elliott Hughesc0f09332012-03-26 13:27:06 -0700675 CHECK_EQ(gBreakpoints.size(), 0U);
676 }
Elliott Hughesa2155262011-11-16 16:26:58 -0800677
Sebastien Hertz138dbfc2013-12-04 18:15:25 +0100678 {
Brian Carlstrom306db812014-09-05 13:01:41 -0700679 MutexLock mu(Thread::Current(), *Locks::deoptimization_lock_);
Sebastien Hertz4d25df32014-03-21 17:44:46 +0100680 CHECK_EQ(deoptimization_requests_.size(), 0U);
681 CHECK_EQ(full_deoptimization_event_count_, 0U);
Sebastien Hertz42cd43f2014-05-13 14:15:41 +0200682 CHECK_EQ(dex_pc_change_event_ref_count_, 0U);
683 CHECK_EQ(method_enter_event_ref_count_, 0U);
684 CHECK_EQ(method_exit_event_ref_count_, 0U);
685 CHECK_EQ(field_read_event_ref_count_, 0U);
686 CHECK_EQ(field_write_event_ref_count_, 0U);
687 CHECK_EQ(exception_catch_event_ref_count_, 0U);
Sebastien Hertz138dbfc2013-12-04 18:15:25 +0100688 }
689
Ian Rogers62d6c772013-02-27 08:32:07 -0800690 Runtime* runtime = Runtime::Current();
Mathieu Chartierbf9fc582015-03-13 17:21:25 -0700691 runtime->GetThreadList()->SuspendAll(__FUNCTION__);
Ian Rogers62d6c772013-02-27 08:32:07 -0800692 Thread* self = Thread::Current();
693 ThreadState old_state = self->SetStateUnsafe(kRunnable);
694 CHECK_NE(old_state, kRunnable);
Sebastien Hertzf3928792014-11-17 19:00:37 +0100695 if (RequiresDeoptimization()) {
696 runtime->GetInstrumentation()->EnableDeoptimization();
697 }
Sebastien Hertz42cd43f2014-05-13 14:15:41 +0200698 instrumentation_events_ = 0;
Elliott Hughesa2155262011-11-16 16:26:58 -0800699 gDebuggerActive = true;
Ian Rogers62d6c772013-02-27 08:32:07 -0800700 CHECK_EQ(self->SetStateUnsafe(old_state), kRunnable);
701 runtime->GetThreadList()->ResumeAll();
702
703 LOG(INFO) << "Debugger is active";
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700704}
705
706void Dbg::Disconnected() {
Elliott Hughes234ab152011-10-26 14:02:26 -0700707 CHECK(gDebuggerConnected);
708
Elliott Hughesc0f09332012-03-26 13:27:06 -0700709 LOG(INFO) << "Debugger is no longer active";
Elliott Hughes234ab152011-10-26 14:02:26 -0700710
Ian Rogers62d6c772013-02-27 08:32:07 -0800711 // Suspend all threads and exclusively acquire the mutator lock. Set the state of the thread
712 // to kRunnable to avoid scoped object access transitions. Remove the debugger as a listener
713 // and clear the object registry.
714 Runtime* runtime = Runtime::Current();
Mathieu Chartierbf9fc582015-03-13 17:21:25 -0700715 runtime->GetThreadList()->SuspendAll(__FUNCTION__);
Ian Rogers62d6c772013-02-27 08:32:07 -0800716 Thread* self = Thread::Current();
717 ThreadState old_state = self->SetStateUnsafe(kRunnable);
Sebastien Hertzaaea7342014-02-25 15:10:04 +0100718
719 // Debugger may not be active at this point.
Daniel Mihalyieb076692014-08-22 17:33:31 +0200720 if (IsDebuggerActive()) {
Sebastien Hertzaaea7342014-02-25 15:10:04 +0100721 {
722 // Since we're going to disable deoptimization, we clear the deoptimization requests queue.
723 // This prevents us from having any pending deoptimization request when the debugger attaches
724 // to us again while no event has been requested yet.
Brian Carlstrom306db812014-09-05 13:01:41 -0700725 MutexLock mu(Thread::Current(), *Locks::deoptimization_lock_);
Sebastien Hertz4d25df32014-03-21 17:44:46 +0100726 deoptimization_requests_.clear();
727 full_deoptimization_event_count_ = 0U;
Sebastien Hertzaaea7342014-02-25 15:10:04 +0100728 }
Sebastien Hertz42cd43f2014-05-13 14:15:41 +0200729 if (instrumentation_events_ != 0) {
730 runtime->GetInstrumentation()->RemoveListener(&gDebugInstrumentationListener,
731 instrumentation_events_);
732 instrumentation_events_ = 0;
733 }
Sebastien Hertzf3928792014-11-17 19:00:37 +0100734 if (RequiresDeoptimization()) {
Sebastien Hertz0462c4c2015-04-01 16:34:17 +0200735 runtime->GetInstrumentation()->DisableDeoptimization(kDbgInstrumentationKey);
Sebastien Hertzf3928792014-11-17 19:00:37 +0100736 }
Sebastien Hertzaaea7342014-02-25 15:10:04 +0100737 gDebuggerActive = false;
Sebastien Hertz138dbfc2013-12-04 18:15:25 +0100738 }
Ian Rogers62d6c772013-02-27 08:32:07 -0800739 CHECK_EQ(self->SetStateUnsafe(old_state), kRunnable);
740 runtime->GetThreadList()->ResumeAll();
Sebastien Hertz55f65342015-01-13 22:48:34 +0100741
742 {
743 ScopedObjectAccess soa(self);
744 gRegistry->Clear();
745 }
746
747 gDebuggerConnected = false;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700748}
749
Sebastien Hertzb3b173b2015-02-06 09:16:32 +0100750void Dbg::ConfigureJdwp(const JDWP::JdwpOptions& jdwp_options) {
751 CHECK_NE(jdwp_options.transport, JDWP::kJdwpTransportUnknown);
752 gJdwpOptions = jdwp_options;
753 gJdwpConfigured = true;
754}
755
Elliott Hughesc0f09332012-03-26 13:27:06 -0700756bool Dbg::IsJdwpConfigured() {
Elliott Hughes3bb81562011-10-21 18:52:59 -0700757 return gJdwpConfigured;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700758}
759
760int64_t Dbg::LastDebuggerActivity() {
Elliott Hughesca951522011-12-05 12:01:32 -0800761 return gJdwpState->LastDebuggerActivity();
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700762}
763
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700764void Dbg::UndoDebuggerSuspensions() {
Elliott Hughes234ab152011-10-26 14:02:26 -0700765 Runtime::Current()->GetThreadList()->UndoDebuggerSuspensions();
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700766}
767
Elliott Hughes88d63092013-01-09 09:55:54 -0800768std::string Dbg::GetClassName(JDWP::RefTypeId class_id) {
Ian Rogersc0542af2014-09-03 16:16:56 -0700769 JDWP::JdwpError error;
770 mirror::Object* o = gRegistry->Get<mirror::Object*>(class_id, &error);
771 if (o == nullptr) {
772 if (error == JDWP::ERR_NONE) {
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700773 return "null";
Ian Rogersc0542af2014-09-03 16:16:56 -0700774 } else {
775 return StringPrintf("invalid object %p", reinterpret_cast<void*>(class_id));
776 }
Elliott Hughes436e3722012-02-17 20:01:47 -0800777 }
778 if (!o->IsClass()) {
Brian Carlstrom7934ac22013-07-26 10:54:15 -0700779 return StringPrintf("non-class %p", o); // This is only used for debugging output anyway.
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -0800780 }
Sebastien Hertz6995c602014-09-09 12:10:13 +0200781 return GetClassName(o->AsClass());
782}
783
784std::string Dbg::GetClassName(mirror::Class* klass) {
Sebastien Hertza9aa0ff2014-09-19 12:07:51 +0200785 if (klass == nullptr) {
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700786 return "null";
Sebastien Hertza9aa0ff2014-09-19 12:07:51 +0200787 }
Ian Rogers1ff3c982014-08-12 02:30:58 -0700788 std::string temp;
Sebastien Hertz6995c602014-09-09 12:10:13 +0200789 return DescriptorToName(klass->GetDescriptor(&temp));
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700790}
791
Ian Rogersc0542af2014-09-03 16:16:56 -0700792JDWP::JdwpError Dbg::GetClassObject(JDWP::RefTypeId id, JDWP::ObjectId* class_object_id) {
Elliott Hughes436e3722012-02-17 20:01:47 -0800793 JDWP::JdwpError status;
Ian Rogersc0542af2014-09-03 16:16:56 -0700794 mirror::Class* c = DecodeClass(id, &status);
795 if (c == nullptr) {
796 *class_object_id = 0;
Elliott Hughes436e3722012-02-17 20:01:47 -0800797 return status;
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -0800798 }
Ian Rogersc0542af2014-09-03 16:16:56 -0700799 *class_object_id = gRegistry->Add(c);
Elliott Hughes436e3722012-02-17 20:01:47 -0800800 return JDWP::ERR_NONE;
Elliott Hughes86964332012-02-15 19:37:42 -0800801}
802
Ian Rogersc0542af2014-09-03 16:16:56 -0700803JDWP::JdwpError Dbg::GetSuperclass(JDWP::RefTypeId id, JDWP::RefTypeId* superclass_id) {
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -0800804 JDWP::JdwpError status;
Ian Rogersc0542af2014-09-03 16:16:56 -0700805 mirror::Class* c = DecodeClass(id, &status);
806 if (c == nullptr) {
807 *superclass_id = 0;
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -0800808 return status;
809 }
810 if (c->IsInterface()) {
811 // http://code.google.com/p/android/issues/detail?id=20856
Ian Rogersc0542af2014-09-03 16:16:56 -0700812 *superclass_id = 0;
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -0800813 } else {
Ian Rogersc0542af2014-09-03 16:16:56 -0700814 *superclass_id = gRegistry->Add(c->GetSuperClass());
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -0800815 }
816 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700817}
818
Elliott Hughes436e3722012-02-17 20:01:47 -0800819JDWP::JdwpError Dbg::GetClassLoader(JDWP::RefTypeId id, JDWP::ExpandBuf* pReply) {
Ian Rogersc0542af2014-09-03 16:16:56 -0700820 JDWP::JdwpError error;
821 mirror::Object* o = gRegistry->Get<mirror::Object*>(id, &error);
822 if (o == nullptr) {
Elliott Hughes436e3722012-02-17 20:01:47 -0800823 return JDWP::ERR_INVALID_OBJECT;
824 }
825 expandBufAddObjectId(pReply, gRegistry->Add(o->GetClass()->GetClassLoader()));
826 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700827}
828
Elliott Hughes436e3722012-02-17 20:01:47 -0800829JDWP::JdwpError Dbg::GetModifiers(JDWP::RefTypeId id, JDWP::ExpandBuf* pReply) {
Ian Rogersc0542af2014-09-03 16:16:56 -0700830 JDWP::JdwpError error;
831 mirror::Class* c = DecodeClass(id, &error);
832 if (c == nullptr) {
833 return error;
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -0800834 }
Elliott Hughes436e3722012-02-17 20:01:47 -0800835
836 uint32_t access_flags = c->GetAccessFlags() & kAccJavaFlagsMask;
837
Yevgeny Roubande34eea2014-02-15 01:06:03 +0700838 // Set ACC_SUPER. Dex files don't contain this flag but only classes are supposed to have it set,
839 // not interfaces.
Elliott Hughes436e3722012-02-17 20:01:47 -0800840 // Class.getModifiers doesn't return it, but JDWP does, so we set it here.
Yevgeny Roubande34eea2014-02-15 01:06:03 +0700841 if ((access_flags & kAccInterface) == 0) {
842 access_flags |= kAccSuper;
843 }
Elliott Hughes436e3722012-02-17 20:01:47 -0800844
845 expandBufAdd4BE(pReply, access_flags);
846
847 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700848}
849
Ian Rogersc0542af2014-09-03 16:16:56 -0700850JDWP::JdwpError Dbg::GetMonitorInfo(JDWP::ObjectId object_id, JDWP::ExpandBuf* reply) {
851 JDWP::JdwpError error;
852 mirror::Object* o = gRegistry->Get<mirror::Object*>(object_id, &error);
853 if (o == nullptr) {
Elliott Hughesf327e072013-01-09 16:01:26 -0800854 return JDWP::ERR_INVALID_OBJECT;
855 }
856
857 // Ensure all threads are suspended while we read objects' lock words.
858 Thread* self = Thread::Current();
Sebastien Hertz54263242014-03-19 18:16:50 +0100859 CHECK_EQ(self->GetState(), kRunnable);
860 self->TransitionFromRunnableToSuspended(kSuspended);
Mathieu Chartierbf9fc582015-03-13 17:21:25 -0700861 Runtime::Current()->GetThreadList()->SuspendAll(__FUNCTION__);
Elliott Hughesf327e072013-01-09 16:01:26 -0800862
863 MonitorInfo monitor_info(o);
864
Sebastien Hertz54263242014-03-19 18:16:50 +0100865 Runtime::Current()->GetThreadList()->ResumeAll();
866 self->TransitionFromSuspendedToRunnable();
Elliott Hughesf327e072013-01-09 16:01:26 -0800867
Ian Rogersc0542af2014-09-03 16:16:56 -0700868 if (monitor_info.owner_ != nullptr) {
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700869 expandBufAddObjectId(reply, gRegistry->Add(monitor_info.owner_->GetPeer()));
Elliott Hughesf327e072013-01-09 16:01:26 -0800870 } else {
Ian Rogersc0542af2014-09-03 16:16:56 -0700871 expandBufAddObjectId(reply, gRegistry->Add(nullptr));
Elliott Hughesf327e072013-01-09 16:01:26 -0800872 }
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700873 expandBufAdd4BE(reply, monitor_info.entry_count_);
874 expandBufAdd4BE(reply, monitor_info.waiters_.size());
875 for (size_t i = 0; i < monitor_info.waiters_.size(); ++i) {
876 expandBufAddObjectId(reply, gRegistry->Add(monitor_info.waiters_[i]->GetPeer()));
Elliott Hughesf327e072013-01-09 16:01:26 -0800877 }
878 return JDWP::ERR_NONE;
879}
880
Elliott Hughes734b8c62013-01-11 15:32:45 -0800881JDWP::JdwpError Dbg::GetOwnedMonitors(JDWP::ObjectId thread_id,
Ian Rogersc0542af2014-09-03 16:16:56 -0700882 std::vector<JDWP::ObjectId>* monitors,
883 std::vector<uint32_t>* stack_depths) {
Elliott Hughes4993bbc2013-01-10 15:41:25 -0800884 struct OwnedMonitorVisitor : public StackVisitor {
Hiroshi Yamauchib5a9e3d2014-06-09 12:11:20 -0700885 OwnedMonitorVisitor(Thread* thread, Context* context,
Hiroshi Yamauchicc8c5c52014-06-13 15:08:05 -0700886 std::vector<JDWP::ObjectId>* monitor_vector,
Hiroshi Yamauchib5a9e3d2014-06-09 12:11:20 -0700887 std::vector<uint32_t>* stack_depth_vector)
Elliott Hughes4993bbc2013-01-10 15:41:25 -0800888 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_)
Nicolas Geoffray8e5bd182015-05-06 11:34:34 +0100889 : StackVisitor(thread, context, StackVisitor::StackWalkKind::kIncludeInlinedFrames),
890 current_stack_depth(0),
891 monitors(monitor_vector),
892 stack_depths(stack_depth_vector) {}
Elliott Hughes4993bbc2013-01-10 15:41:25 -0800893
894 // TODO: Enable annotalysis. We know lock is held in constructor, but abstraction confuses
895 // annotalysis.
896 bool VisitFrame() NO_THREAD_SAFETY_ANALYSIS {
897 if (!GetMethod()->IsRuntimeMethod()) {
898 Monitor::VisitLocks(this, AppendOwnedMonitors, this);
Elliott Hughes734b8c62013-01-11 15:32:45 -0800899 ++current_stack_depth;
Elliott Hughes4993bbc2013-01-10 15:41:25 -0800900 }
901 return true;
902 }
903
Hiroshi Yamauchicc8c5c52014-06-13 15:08:05 -0700904 static void AppendOwnedMonitors(mirror::Object* owned_monitor, void* arg)
905 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Ian Rogers7a22fa62013-01-23 12:16:16 -0800906 OwnedMonitorVisitor* visitor = reinterpret_cast<OwnedMonitorVisitor*>(arg);
Hiroshi Yamauchicc8c5c52014-06-13 15:08:05 -0700907 visitor->monitors->push_back(gRegistry->Add(owned_monitor));
Hiroshi Yamauchib5a9e3d2014-06-09 12:11:20 -0700908 visitor->stack_depths->push_back(visitor->current_stack_depth);
Elliott Hughes4993bbc2013-01-10 15:41:25 -0800909 }
910
Elliott Hughes734b8c62013-01-11 15:32:45 -0800911 size_t current_stack_depth;
Ian Rogersc0542af2014-09-03 16:16:56 -0700912 std::vector<JDWP::ObjectId>* const monitors;
913 std::vector<uint32_t>* const stack_depths;
Elliott Hughes4993bbc2013-01-10 15:41:25 -0800914 };
Elliott Hughes4993bbc2013-01-10 15:41:25 -0800915
Hiroshi Yamauchib5a9e3d2014-06-09 12:11:20 -0700916 ScopedObjectAccessUnchecked soa(Thread::Current());
Sebastien Hertz69206392015-04-07 15:54:25 +0200917 JDWP::JdwpError error;
918 Thread* thread = DecodeThread(soa, thread_id, &error);
919 if (thread == nullptr) {
920 return error;
921 }
922 if (!IsSuspendedForDebugger(soa, thread)) {
923 return JDWP::ERR_THREAD_NOT_SUSPENDED;
Hiroshi Yamauchib5a9e3d2014-06-09 12:11:20 -0700924 }
Hiroshi Yamauchicc8c5c52014-06-13 15:08:05 -0700925 std::unique_ptr<Context> context(Context::Create());
Ian Rogersc0542af2014-09-03 16:16:56 -0700926 OwnedMonitorVisitor visitor(thread, context.get(), monitors, stack_depths);
Hiroshi Yamauchicc8c5c52014-06-13 15:08:05 -0700927 visitor.WalkStack();
Elliott Hughes4993bbc2013-01-10 15:41:25 -0800928 return JDWP::ERR_NONE;
929}
930
Sebastien Hertz52d131d2014-03-13 16:17:40 +0100931JDWP::JdwpError Dbg::GetContendedMonitor(JDWP::ObjectId thread_id,
Ian Rogersc0542af2014-09-03 16:16:56 -0700932 JDWP::ObjectId* contended_monitor) {
Elliott Hughesf9501702013-01-11 11:22:27 -0800933 ScopedObjectAccessUnchecked soa(Thread::Current());
Ian Rogersc0542af2014-09-03 16:16:56 -0700934 *contended_monitor = 0;
Sebastien Hertz69206392015-04-07 15:54:25 +0200935 JDWP::JdwpError error;
936 Thread* thread = DecodeThread(soa, thread_id, &error);
937 if (thread == nullptr) {
938 return error;
Elliott Hughesf9501702013-01-11 11:22:27 -0800939 }
Sebastien Hertz69206392015-04-07 15:54:25 +0200940 if (!IsSuspendedForDebugger(soa, thread)) {
941 return JDWP::ERR_THREAD_NOT_SUSPENDED;
942 }
943 mirror::Object* contended_monitor_obj = Monitor::GetContendedMonitor(thread);
Hiroshi Yamauchib5a9e3d2014-06-09 12:11:20 -0700944 // Add() requires the thread_list_lock_ not held to avoid the lock
945 // level violation.
Ian Rogersc0542af2014-09-03 16:16:56 -0700946 *contended_monitor = gRegistry->Add(contended_monitor_obj);
Elliott Hughesf9501702013-01-11 11:22:27 -0800947 return JDWP::ERR_NONE;
948}
949
Elliott Hughesec0f83d2013-01-15 16:54:08 -0800950JDWP::JdwpError Dbg::GetInstanceCounts(const std::vector<JDWP::RefTypeId>& class_ids,
Ian Rogersc0542af2014-09-03 16:16:56 -0700951 std::vector<uint64_t>* counts) {
Mathieu Chartier412c7fc2014-02-07 12:18:39 -0800952 gc::Heap* heap = Runtime::Current()->GetHeap();
953 heap->CollectGarbage(false);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800954 std::vector<mirror::Class*> classes;
Ian Rogersc0542af2014-09-03 16:16:56 -0700955 counts->clear();
Elliott Hughesec0f83d2013-01-15 16:54:08 -0800956 for (size_t i = 0; i < class_ids.size(); ++i) {
Ian Rogersc0542af2014-09-03 16:16:56 -0700957 JDWP::JdwpError error;
958 mirror::Class* c = DecodeClass(class_ids[i], &error);
959 if (c == nullptr) {
960 return error;
Elliott Hughesec0f83d2013-01-15 16:54:08 -0800961 }
962 classes.push_back(c);
Ian Rogersc0542af2014-09-03 16:16:56 -0700963 counts->push_back(0);
Elliott Hughesec0f83d2013-01-15 16:54:08 -0800964 }
Ian Rogersc0542af2014-09-03 16:16:56 -0700965 heap->CountInstances(classes, false, &(*counts)[0]);
Elliott Hughesec0f83d2013-01-15 16:54:08 -0800966 return JDWP::ERR_NONE;
967}
968
Ian Rogersc0542af2014-09-03 16:16:56 -0700969JDWP::JdwpError Dbg::GetInstances(JDWP::RefTypeId class_id, int32_t max_count,
970 std::vector<JDWP::ObjectId>* instances) {
Mathieu Chartier412c7fc2014-02-07 12:18:39 -0800971 gc::Heap* heap = Runtime::Current()->GetHeap();
972 // We only want reachable instances, so do a GC.
973 heap->CollectGarbage(false);
Ian Rogersc0542af2014-09-03 16:16:56 -0700974 JDWP::JdwpError error;
975 mirror::Class* c = DecodeClass(class_id, &error);
Mathieu Chartier412c7fc2014-02-07 12:18:39 -0800976 if (c == nullptr) {
Ian Rogersc0542af2014-09-03 16:16:56 -0700977 return error;
Elliott Hughes3b78c942013-01-15 17:35:41 -0800978 }
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800979 std::vector<mirror::Object*> raw_instances;
Elliott Hughes3b78c942013-01-15 17:35:41 -0800980 Runtime::Current()->GetHeap()->GetInstances(c, max_count, raw_instances);
981 for (size_t i = 0; i < raw_instances.size(); ++i) {
Ian Rogersc0542af2014-09-03 16:16:56 -0700982 instances->push_back(gRegistry->Add(raw_instances[i]));
Elliott Hughes3b78c942013-01-15 17:35:41 -0800983 }
984 return JDWP::ERR_NONE;
985}
986
Elliott Hughes0cbaff52013-01-16 15:28:01 -0800987JDWP::JdwpError Dbg::GetReferringObjects(JDWP::ObjectId object_id, int32_t max_count,
Ian Rogersc0542af2014-09-03 16:16:56 -0700988 std::vector<JDWP::ObjectId>* referring_objects) {
Mathieu Chartier412c7fc2014-02-07 12:18:39 -0800989 gc::Heap* heap = Runtime::Current()->GetHeap();
990 heap->CollectGarbage(false);
Ian Rogersc0542af2014-09-03 16:16:56 -0700991 JDWP::JdwpError error;
992 mirror::Object* o = gRegistry->Get<mirror::Object*>(object_id, &error);
993 if (o == nullptr) {
Elliott Hughes0cbaff52013-01-16 15:28:01 -0800994 return JDWP::ERR_INVALID_OBJECT;
995 }
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800996 std::vector<mirror::Object*> raw_instances;
Mathieu Chartier412c7fc2014-02-07 12:18:39 -0800997 heap->GetReferringObjects(o, max_count, raw_instances);
Elliott Hughes0cbaff52013-01-16 15:28:01 -0800998 for (size_t i = 0; i < raw_instances.size(); ++i) {
Ian Rogersc0542af2014-09-03 16:16:56 -0700999 referring_objects->push_back(gRegistry->Add(raw_instances[i]));
Elliott Hughes0cbaff52013-01-16 15:28:01 -08001000 }
1001 return JDWP::ERR_NONE;
1002}
1003
Ian Rogersc0542af2014-09-03 16:16:56 -07001004JDWP::JdwpError Dbg::DisableCollection(JDWP::ObjectId object_id) {
1005 JDWP::JdwpError error;
1006 mirror::Object* o = gRegistry->Get<mirror::Object*>(object_id, &error);
1007 if (o == nullptr) {
Sebastien Hertze96060a2013-12-11 12:06:28 +01001008 return JDWP::ERR_INVALID_OBJECT;
1009 }
Elliott Hughes64f574f2013-02-20 14:57:12 -08001010 gRegistry->DisableCollection(object_id);
1011 return JDWP::ERR_NONE;
1012}
1013
Ian Rogersc0542af2014-09-03 16:16:56 -07001014JDWP::JdwpError Dbg::EnableCollection(JDWP::ObjectId object_id) {
1015 JDWP::JdwpError error;
1016 mirror::Object* o = gRegistry->Get<mirror::Object*>(object_id, &error);
Sebastien Hertze96060a2013-12-11 12:06:28 +01001017 // Unlike DisableCollection, JDWP specs do not state an invalid object causes an error. The RI
1018 // also ignores these cases and never return an error. However it's not obvious why this command
1019 // should behave differently from DisableCollection and IsCollected commands. So let's be more
1020 // strict and return an error if this happens.
Ian Rogersc0542af2014-09-03 16:16:56 -07001021 if (o == nullptr) {
Sebastien Hertze96060a2013-12-11 12:06:28 +01001022 return JDWP::ERR_INVALID_OBJECT;
1023 }
Elliott Hughes64f574f2013-02-20 14:57:12 -08001024 gRegistry->EnableCollection(object_id);
1025 return JDWP::ERR_NONE;
1026}
1027
Ian Rogersc0542af2014-09-03 16:16:56 -07001028JDWP::JdwpError Dbg::IsCollected(JDWP::ObjectId object_id, bool* is_collected) {
1029 *is_collected = true;
Sebastien Hertz65637eb2014-01-10 17:40:02 +01001030 if (object_id == 0) {
1031 // Null object id is invalid.
Sebastien Hertze96060a2013-12-11 12:06:28 +01001032 return JDWP::ERR_INVALID_OBJECT;
1033 }
Sebastien Hertz65637eb2014-01-10 17:40:02 +01001034 // JDWP specs state an INVALID_OBJECT error is returned if the object ID is not valid. However
1035 // the RI seems to ignore this and assume object has been collected.
Ian Rogersc0542af2014-09-03 16:16:56 -07001036 JDWP::JdwpError error;
1037 mirror::Object* o = gRegistry->Get<mirror::Object*>(object_id, &error);
1038 if (o != nullptr) {
1039 *is_collected = gRegistry->IsCollected(object_id);
Sebastien Hertz65637eb2014-01-10 17:40:02 +01001040 }
Elliott Hughes64f574f2013-02-20 14:57:12 -08001041 return JDWP::ERR_NONE;
1042}
1043
Ian Rogersc0542af2014-09-03 16:16:56 -07001044void Dbg::DisposeObject(JDWP::ObjectId object_id, uint32_t reference_count) {
Elliott Hughes64f574f2013-02-20 14:57:12 -08001045 gRegistry->DisposeObject(object_id, reference_count);
1046}
1047
Sebastien Hertz6995c602014-09-09 12:10:13 +02001048JDWP::JdwpTypeTag Dbg::GetTypeTag(mirror::Class* klass) {
Sebastien Hertz4d8fd492014-03-28 16:29:41 +01001049 DCHECK(klass != nullptr);
1050 if (klass->IsArrayClass()) {
1051 return JDWP::TT_ARRAY;
1052 } else if (klass->IsInterface()) {
1053 return JDWP::TT_INTERFACE;
1054 } else {
1055 return JDWP::TT_CLASS;
1056 }
1057}
1058
Elliott Hughes88d63092013-01-09 09:55:54 -08001059JDWP::JdwpError Dbg::GetReflectedType(JDWP::RefTypeId class_id, JDWP::ExpandBuf* pReply) {
Ian Rogersc0542af2014-09-03 16:16:56 -07001060 JDWP::JdwpError error;
1061 mirror::Class* c = DecodeClass(class_id, &error);
1062 if (c == nullptr) {
1063 return error;
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -08001064 }
Elliott Hughes436e3722012-02-17 20:01:47 -08001065
Sebastien Hertz4d8fd492014-03-28 16:29:41 +01001066 JDWP::JdwpTypeTag type_tag = GetTypeTag(c);
1067 expandBufAdd1(pReply, type_tag);
Elliott Hughes88d63092013-01-09 09:55:54 -08001068 expandBufAddRefTypeId(pReply, class_id);
Elliott Hughes436e3722012-02-17 20:01:47 -08001069 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001070}
1071
Ian Rogersc0542af2014-09-03 16:16:56 -07001072void Dbg::GetClassList(std::vector<JDWP::RefTypeId>* classes) {
Elliott Hughesa2155262011-11-16 16:26:58 -08001073 // Get the complete list of reference classes (i.e. all classes except
1074 // the primitive types).
1075 // Returns a newly-allocated buffer full of RefTypeId values.
1076 struct ClassListCreator {
Andreas Gampe277ccbd2014-11-03 21:36:10 -08001077 explicit ClassListCreator(std::vector<JDWP::RefTypeId>* classes_in) : classes(classes_in) {
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -08001078 }
1079
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001080 static bool Visit(mirror::Class* c, void* arg) {
Elliott Hughesa2155262011-11-16 16:26:58 -08001081 return reinterpret_cast<ClassListCreator*>(arg)->Visit(c);
1082 }
1083
Elliott Hughes64f574f2013-02-20 14:57:12 -08001084 // TODO: Enable annotalysis. We know lock is held in constructor, but abstraction confuses
1085 // annotalysis.
1086 bool Visit(mirror::Class* c) NO_THREAD_SAFETY_ANALYSIS {
Elliott Hughesa2155262011-11-16 16:26:58 -08001087 if (!c->IsPrimitive()) {
Ian Rogersc0542af2014-09-03 16:16:56 -07001088 classes->push_back(gRegistry->AddRefType(c));
Elliott Hughesa2155262011-11-16 16:26:58 -08001089 }
1090 return true;
1091 }
1092
Ian Rogersc0542af2014-09-03 16:16:56 -07001093 std::vector<JDWP::RefTypeId>* const classes;
Elliott Hughesa2155262011-11-16 16:26:58 -08001094 };
1095
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -08001096 ClassListCreator clc(classes);
Sebastien Hertz4537c412014-08-28 14:41:50 +02001097 Runtime::Current()->GetClassLinker()->VisitClassesWithoutClassesLock(ClassListCreator::Visit,
1098 &clc);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001099}
1100
Ian Rogers1ff3c982014-08-12 02:30:58 -07001101JDWP::JdwpError Dbg::GetClassInfo(JDWP::RefTypeId class_id, JDWP::JdwpTypeTag* pTypeTag,
1102 uint32_t* pStatus, std::string* pDescriptor) {
Ian Rogersc0542af2014-09-03 16:16:56 -07001103 JDWP::JdwpError error;
1104 mirror::Class* c = DecodeClass(class_id, &error);
1105 if (c == nullptr) {
1106 return error;
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -08001107 }
1108
Elliott Hughesa2155262011-11-16 16:26:58 -08001109 if (c->IsArrayClass()) {
1110 *pStatus = JDWP::CS_VERIFIED | JDWP::CS_PREPARED;
1111 *pTypeTag = JDWP::TT_ARRAY;
1112 } else {
1113 if (c->IsErroneous()) {
1114 *pStatus = JDWP::CS_ERROR;
1115 } else {
1116 *pStatus = JDWP::CS_VERIFIED | JDWP::CS_PREPARED | JDWP::CS_INITIALIZED;
1117 }
1118 *pTypeTag = c->IsInterface() ? JDWP::TT_INTERFACE : JDWP::TT_CLASS;
1119 }
1120
Ian Rogersc0542af2014-09-03 16:16:56 -07001121 if (pDescriptor != nullptr) {
Ian Rogers1ff3c982014-08-12 02:30:58 -07001122 std::string temp;
1123 *pDescriptor = c->GetDescriptor(&temp);
Elliott Hughesa2155262011-11-16 16:26:58 -08001124 }
Elliott Hughes436e3722012-02-17 20:01:47 -08001125 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001126}
1127
Ian Rogersc0542af2014-09-03 16:16:56 -07001128void Dbg::FindLoadedClassBySignature(const char* descriptor, std::vector<JDWP::RefTypeId>* ids) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001129 std::vector<mirror::Class*> classes;
Elliott Hughes6fa602d2011-12-02 17:54:25 -08001130 Runtime::Current()->GetClassLinker()->LookupClasses(descriptor, classes);
Ian Rogersc0542af2014-09-03 16:16:56 -07001131 ids->clear();
Elliott Hughes6fa602d2011-12-02 17:54:25 -08001132 for (size_t i = 0; i < classes.size(); ++i) {
Ian Rogersc0542af2014-09-03 16:16:56 -07001133 ids->push_back(gRegistry->Add(classes[i]));
Elliott Hughes6fa602d2011-12-02 17:54:25 -08001134 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001135}
1136
Ian Rogersc0542af2014-09-03 16:16:56 -07001137JDWP::JdwpError Dbg::GetReferenceType(JDWP::ObjectId object_id, JDWP::ExpandBuf* pReply) {
1138 JDWP::JdwpError error;
1139 mirror::Object* o = gRegistry->Get<mirror::Object*>(object_id, &error);
1140 if (o == nullptr) {
Elliott Hughes2435a572012-02-17 16:07:41 -08001141 return JDWP::ERR_INVALID_OBJECT;
Elliott Hughes499c5132011-11-17 14:55:11 -08001142 }
Elliott Hughes2435a572012-02-17 16:07:41 -08001143
Sebastien Hertz4d8fd492014-03-28 16:29:41 +01001144 JDWP::JdwpTypeTag type_tag = GetTypeTag(o->GetClass());
Elliott Hughes64f574f2013-02-20 14:57:12 -08001145 JDWP::RefTypeId type_id = gRegistry->AddRefType(o->GetClass());
Elliott Hughes2435a572012-02-17 16:07:41 -08001146
1147 expandBufAdd1(pReply, type_tag);
1148 expandBufAddRefTypeId(pReply, type_id);
1149
1150 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001151}
1152
Ian Rogersfc0e94b2013-09-23 23:51:32 -07001153JDWP::JdwpError Dbg::GetSignature(JDWP::RefTypeId class_id, std::string* signature) {
Ian Rogersc0542af2014-09-03 16:16:56 -07001154 JDWP::JdwpError error;
1155 mirror::Class* c = DecodeClass(class_id, &error);
1156 if (c == nullptr) {
1157 return error;
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -08001158 }
Ian Rogers1ff3c982014-08-12 02:30:58 -07001159 std::string temp;
1160 *signature = c->GetDescriptor(&temp);
Elliott Hughes1fe7afb2012-02-13 17:23:03 -08001161 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001162}
1163
Ian Rogersc0542af2014-09-03 16:16:56 -07001164JDWP::JdwpError Dbg::GetSourceFile(JDWP::RefTypeId class_id, std::string* result) {
1165 JDWP::JdwpError error;
1166 mirror::Class* c = DecodeClass(class_id, &error);
Sebastien Hertz4206eb52014-06-05 10:15:45 +02001167 if (c == nullptr) {
Ian Rogersc0542af2014-09-03 16:16:56 -07001168 return error;
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -08001169 }
Sebastien Hertz4206eb52014-06-05 10:15:45 +02001170 const char* source_file = c->GetSourceFile();
1171 if (source_file == nullptr) {
Sebastien Hertzb7054ba2014-03-13 11:52:31 +01001172 return JDWP::ERR_ABSENT_INFORMATION;
1173 }
Ian Rogersc0542af2014-09-03 16:16:56 -07001174 *result = source_file;
Elliott Hughes436e3722012-02-17 20:01:47 -08001175 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001176}
1177
Ian Rogersc0542af2014-09-03 16:16:56 -07001178JDWP::JdwpError Dbg::GetObjectTag(JDWP::ObjectId object_id, uint8_t* tag) {
Ian Rogers98379392014-02-24 16:53:16 -08001179 ScopedObjectAccessUnchecked soa(Thread::Current());
Ian Rogersc0542af2014-09-03 16:16:56 -07001180 JDWP::JdwpError error;
1181 mirror::Object* o = gRegistry->Get<mirror::Object*>(object_id, &error);
1182 if (error != JDWP::ERR_NONE) {
1183 *tag = JDWP::JT_VOID;
1184 return error;
Elliott Hughes546b9862012-06-20 16:06:13 -07001185 }
Ian Rogersc0542af2014-09-03 16:16:56 -07001186 *tag = TagFromObject(soa, o);
Elliott Hughes546b9862012-06-20 16:06:13 -07001187 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001188}
1189
Elliott Hughesaed4be92011-12-02 16:16:23 -08001190size_t Dbg::GetTagWidth(JDWP::JdwpTag tag) {
Elliott Hughesdbb40792011-11-18 17:05:22 -08001191 switch (tag) {
1192 case JDWP::JT_VOID:
1193 return 0;
1194 case JDWP::JT_BYTE:
1195 case JDWP::JT_BOOLEAN:
1196 return 1;
1197 case JDWP::JT_CHAR:
1198 case JDWP::JT_SHORT:
1199 return 2;
1200 case JDWP::JT_FLOAT:
1201 case JDWP::JT_INT:
1202 return 4;
1203 case JDWP::JT_ARRAY:
1204 case JDWP::JT_OBJECT:
1205 case JDWP::JT_STRING:
1206 case JDWP::JT_THREAD:
1207 case JDWP::JT_THREAD_GROUP:
1208 case JDWP::JT_CLASS_LOADER:
1209 case JDWP::JT_CLASS_OBJECT:
1210 return sizeof(JDWP::ObjectId);
1211 case JDWP::JT_DOUBLE:
1212 case JDWP::JT_LONG:
1213 return 8;
1214 default:
Elliott Hughes3d30d9b2011-12-07 17:35:48 -08001215 LOG(FATAL) << "Unknown tag " << tag;
Elliott Hughesdbb40792011-11-18 17:05:22 -08001216 return -1;
1217 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001218}
1219
Ian Rogersc0542af2014-09-03 16:16:56 -07001220JDWP::JdwpError Dbg::GetArrayLength(JDWP::ObjectId array_id, int32_t* length) {
1221 JDWP::JdwpError error;
1222 mirror::Array* a = DecodeNonNullArray(array_id, &error);
1223 if (a == nullptr) {
1224 return error;
Elliott Hughes24437992011-11-30 14:49:33 -08001225 }
Ian Rogersc0542af2014-09-03 16:16:56 -07001226 *length = a->GetLength();
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -08001227 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001228}
1229
Elliott Hughes88d63092013-01-09 09:55:54 -08001230JDWP::JdwpError Dbg::OutputArray(JDWP::ObjectId array_id, int offset, int count, JDWP::ExpandBuf* pReply) {
Ian Rogersc0542af2014-09-03 16:16:56 -07001231 JDWP::JdwpError error;
1232 mirror::Array* a = DecodeNonNullArray(array_id, &error);
Ian Rogers98379392014-02-24 16:53:16 -08001233 if (a == nullptr) {
Ian Rogersc0542af2014-09-03 16:16:56 -07001234 return error;
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -08001235 }
Elliott Hughes24437992011-11-30 14:49:33 -08001236
1237 if (offset < 0 || count < 0 || offset > a->GetLength() || a->GetLength() - offset < count) {
1238 LOG(WARNING) << __FUNCTION__ << " access out of bounds: offset=" << offset << "; count=" << count;
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -08001239 return JDWP::ERR_INVALID_LENGTH;
Elliott Hughes24437992011-11-30 14:49:33 -08001240 }
Ian Rogers1ff3c982014-08-12 02:30:58 -07001241 JDWP::JdwpTag element_tag = BasicTagFromClass(a->GetClass()->GetComponentType());
1242 expandBufAdd1(pReply, element_tag);
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -08001243 expandBufAdd4BE(pReply, count);
1244
Ian Rogers1ff3c982014-08-12 02:30:58 -07001245 if (IsPrimitiveTag(element_tag)) {
1246 size_t width = GetTagWidth(element_tag);
Elliott Hughes24437992011-11-30 14:49:33 -08001247 uint8_t* dst = expandBufAddSpace(pReply, count * width);
1248 if (width == 8) {
Ian Rogersef7d42f2014-01-06 12:55:46 -08001249 const uint64_t* src8 = reinterpret_cast<uint64_t*>(a->GetRawData(sizeof(uint64_t), 0));
Elliott Hughes24437992011-11-30 14:49:33 -08001250 for (int i = 0; i < count; ++i) JDWP::Write8BE(&dst, src8[offset + i]);
1251 } else if (width == 4) {
Ian Rogersef7d42f2014-01-06 12:55:46 -08001252 const uint32_t* src4 = reinterpret_cast<uint32_t*>(a->GetRawData(sizeof(uint32_t), 0));
Elliott Hughes24437992011-11-30 14:49:33 -08001253 for (int i = 0; i < count; ++i) JDWP::Write4BE(&dst, src4[offset + i]);
1254 } else if (width == 2) {
Ian Rogersef7d42f2014-01-06 12:55:46 -08001255 const uint16_t* src2 = reinterpret_cast<uint16_t*>(a->GetRawData(sizeof(uint16_t), 0));
Elliott Hughes24437992011-11-30 14:49:33 -08001256 for (int i = 0; i < count; ++i) JDWP::Write2BE(&dst, src2[offset + i]);
1257 } else {
Ian Rogersef7d42f2014-01-06 12:55:46 -08001258 const uint8_t* src = reinterpret_cast<uint8_t*>(a->GetRawData(sizeof(uint8_t), 0));
Elliott Hughes24437992011-11-30 14:49:33 -08001259 memcpy(dst, &src[offset * width], count * width);
1260 }
1261 } else {
Ian Rogers98379392014-02-24 16:53:16 -08001262 ScopedObjectAccessUnchecked soa(Thread::Current());
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001263 mirror::ObjectArray<mirror::Object>* oa = a->AsObjectArray<mirror::Object>();
Elliott Hughes24437992011-11-30 14:49:33 -08001264 for (int i = 0; i < count; ++i) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001265 mirror::Object* element = oa->Get(offset + i);
Ian Rogers98379392014-02-24 16:53:16 -08001266 JDWP::JdwpTag specific_tag = (element != nullptr) ? TagFromObject(soa, element)
Ian Rogers1ff3c982014-08-12 02:30:58 -07001267 : element_tag;
Elliott Hughes24437992011-11-30 14:49:33 -08001268 expandBufAdd1(pReply, specific_tag);
1269 expandBufAddObjectId(pReply, gRegistry->Add(element));
1270 }
1271 }
1272
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -08001273 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001274}
1275
Ian Rogersef7d42f2014-01-06 12:55:46 -08001276template <typename T>
Ian Rogersc0542af2014-09-03 16:16:56 -07001277static void CopyArrayData(mirror::Array* a, JDWP::Request* src, int offset, int count)
Ian Rogersef7d42f2014-01-06 12:55:46 -08001278 NO_THREAD_SAFETY_ANALYSIS {
1279 // TODO: fix when annotalysis correctly handles non-member functions.
Elliott Hughes4b9702c2013-02-20 18:13:24 -08001280 DCHECK(a->GetClass()->IsPrimitiveArray());
1281
Ian Rogersef7d42f2014-01-06 12:55:46 -08001282 T* dst = reinterpret_cast<T*>(a->GetRawData(sizeof(T), offset));
Elliott Hughes4b9702c2013-02-20 18:13:24 -08001283 for (int i = 0; i < count; ++i) {
Ian Rogersc0542af2014-09-03 16:16:56 -07001284 *dst++ = src->ReadValue(sizeof(T));
Elliott Hughes4b9702c2013-02-20 18:13:24 -08001285 }
1286}
1287
Elliott Hughes88d63092013-01-09 09:55:54 -08001288JDWP::JdwpError Dbg::SetArrayElements(JDWP::ObjectId array_id, int offset, int count,
Ian Rogersc0542af2014-09-03 16:16:56 -07001289 JDWP::Request* request) {
1290 JDWP::JdwpError error;
1291 mirror::Array* dst = DecodeNonNullArray(array_id, &error);
1292 if (dst == nullptr) {
1293 return error;
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -08001294 }
Elliott Hughesf03b8f62011-12-02 14:26:25 -08001295
Elliott Hughes4b9702c2013-02-20 18:13:24 -08001296 if (offset < 0 || count < 0 || offset > dst->GetLength() || dst->GetLength() - offset < count) {
Elliott Hughesf03b8f62011-12-02 14:26:25 -08001297 LOG(WARNING) << __FUNCTION__ << " access out of bounds: offset=" << offset << "; count=" << count;
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -08001298 return JDWP::ERR_INVALID_LENGTH;
Elliott Hughesf03b8f62011-12-02 14:26:25 -08001299 }
Ian Rogers1ff3c982014-08-12 02:30:58 -07001300 JDWP::JdwpTag element_tag = BasicTagFromClass(dst->GetClass()->GetComponentType());
Elliott Hughesf03b8f62011-12-02 14:26:25 -08001301
Ian Rogers1ff3c982014-08-12 02:30:58 -07001302 if (IsPrimitiveTag(element_tag)) {
1303 size_t width = GetTagWidth(element_tag);
Elliott Hughesf03b8f62011-12-02 14:26:25 -08001304 if (width == 8) {
Elliott Hughes4b9702c2013-02-20 18:13:24 -08001305 CopyArrayData<uint64_t>(dst, request, offset, count);
Elliott Hughesf03b8f62011-12-02 14:26:25 -08001306 } else if (width == 4) {
Elliott Hughes4b9702c2013-02-20 18:13:24 -08001307 CopyArrayData<uint32_t>(dst, request, offset, count);
Elliott Hughesf03b8f62011-12-02 14:26:25 -08001308 } else if (width == 2) {
Elliott Hughes4b9702c2013-02-20 18:13:24 -08001309 CopyArrayData<uint16_t>(dst, request, offset, count);
Elliott Hughesf03b8f62011-12-02 14:26:25 -08001310 } else {
Elliott Hughes4b9702c2013-02-20 18:13:24 -08001311 CopyArrayData<uint8_t>(dst, request, offset, count);
Elliott Hughesf03b8f62011-12-02 14:26:25 -08001312 }
1313 } else {
Elliott Hughes4b9702c2013-02-20 18:13:24 -08001314 mirror::ObjectArray<mirror::Object>* oa = dst->AsObjectArray<mirror::Object>();
Elliott Hughesf03b8f62011-12-02 14:26:25 -08001315 for (int i = 0; i < count; ++i) {
Ian Rogersc0542af2014-09-03 16:16:56 -07001316 JDWP::ObjectId id = request->ReadObjectId();
Ian Rogersc0542af2014-09-03 16:16:56 -07001317 mirror::Object* o = gRegistry->Get<mirror::Object*>(id, &error);
1318 if (error != JDWP::ERR_NONE) {
1319 return error;
Elliott Hughes436e3722012-02-17 20:01:47 -08001320 }
Sebastien Hertzd2fe10a2014-01-15 10:20:56 +01001321 oa->Set<false>(offset + i, o);
Elliott Hughesf03b8f62011-12-02 14:26:25 -08001322 }
1323 }
1324
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -08001325 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001326}
1327
Sebastien Hertz2c3e77a2015-04-02 16:26:48 +02001328JDWP::JdwpError Dbg::CreateString(const std::string& str, JDWP::ObjectId* new_string_id) {
1329 Thread* self = Thread::Current();
1330 mirror::String* new_string = mirror::String::AllocFromModifiedUtf8(self, str.c_str());
1331 if (new_string == nullptr) {
1332 DCHECK(self->IsExceptionPending());
1333 self->ClearException();
1334 LOG(ERROR) << "Could not allocate string";
1335 *new_string_id = 0;
1336 return JDWP::ERR_OUT_OF_MEMORY;
1337 }
1338 *new_string_id = gRegistry->Add(new_string);
1339 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001340}
1341
Sebastien Hertz2c3e77a2015-04-02 16:26:48 +02001342JDWP::JdwpError Dbg::CreateObject(JDWP::RefTypeId class_id, JDWP::ObjectId* new_object_id) {
Ian Rogersc0542af2014-09-03 16:16:56 -07001343 JDWP::JdwpError error;
1344 mirror::Class* c = DecodeClass(class_id, &error);
1345 if (c == nullptr) {
Sebastien Hertz2c3e77a2015-04-02 16:26:48 +02001346 *new_object_id = 0;
Ian Rogersc0542af2014-09-03 16:16:56 -07001347 return error;
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -08001348 }
Sebastien Hertz2c3e77a2015-04-02 16:26:48 +02001349 Thread* self = Thread::Current();
1350 mirror::Object* new_object = c->AllocObject(self);
1351 if (new_object == nullptr) {
1352 DCHECK(self->IsExceptionPending());
1353 self->ClearException();
1354 LOG(ERROR) << "Could not allocate object of type " << PrettyDescriptor(c);
1355 *new_object_id = 0;
1356 return JDWP::ERR_OUT_OF_MEMORY;
1357 }
1358 *new_object_id = gRegistry->Add(new_object);
Elliott Hughes436e3722012-02-17 20:01:47 -08001359 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001360}
1361
Elliott Hughesbf13d362011-12-08 15:51:37 -08001362/*
1363 * Used by Eclipse's "Display" view to evaluate "new byte[5]" to get "(byte[]) [0, 0, 0, 0, 0]".
1364 */
Elliott Hughes88d63092013-01-09 09:55:54 -08001365JDWP::JdwpError Dbg::CreateArrayObject(JDWP::RefTypeId array_class_id, uint32_t length,
Sebastien Hertz2c3e77a2015-04-02 16:26:48 +02001366 JDWP::ObjectId* new_array_id) {
Ian Rogersc0542af2014-09-03 16:16:56 -07001367 JDWP::JdwpError error;
1368 mirror::Class* c = DecodeClass(array_class_id, &error);
1369 if (c == nullptr) {
Sebastien Hertz2c3e77a2015-04-02 16:26:48 +02001370 *new_array_id = 0;
Ian Rogersc0542af2014-09-03 16:16:56 -07001371 return error;
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -08001372 }
Sebastien Hertz2c3e77a2015-04-02 16:26:48 +02001373 Thread* self = Thread::Current();
1374 gc::Heap* heap = Runtime::Current()->GetHeap();
1375 mirror::Array* new_array = mirror::Array::Alloc<true>(self, c, length,
1376 c->GetComponentSizeShift(),
1377 heap->GetCurrentAllocator());
1378 if (new_array == nullptr) {
1379 DCHECK(self->IsExceptionPending());
1380 self->ClearException();
1381 LOG(ERROR) << "Could not allocate array of type " << PrettyDescriptor(c);
1382 *new_array_id = 0;
1383 return JDWP::ERR_OUT_OF_MEMORY;
1384 }
1385 *new_array_id = gRegistry->Add(new_array);
Elliott Hughes436e3722012-02-17 20:01:47 -08001386 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001387}
1388
Mathieu Chartierc7853442015-03-27 14:35:38 -07001389JDWP::FieldId Dbg::ToFieldId(const ArtField* f) {
Elliott Hughes03181a82011-11-17 17:22:21 -08001390 return static_cast<JDWP::FieldId>(reinterpret_cast<uintptr_t>(f));
Elliott Hughes03181a82011-11-17 17:22:21 -08001391}
1392
Mathieu Chartiere401d142015-04-22 13:56:20 -07001393static JDWP::MethodId ToMethodId(const ArtMethod* m)
Ian Rogersb726dcb2012-09-05 08:57:23 -07001394 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Elliott Hughes03181a82011-11-17 17:22:21 -08001395 return static_cast<JDWP::MethodId>(reinterpret_cast<uintptr_t>(m));
Elliott Hughes03181a82011-11-17 17:22:21 -08001396}
1397
Mathieu Chartierc7853442015-03-27 14:35:38 -07001398static ArtField* FromFieldId(JDWP::FieldId fid)
Ian Rogersb726dcb2012-09-05 08:57:23 -07001399 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Mathieu Chartierc7853442015-03-27 14:35:38 -07001400 return reinterpret_cast<ArtField*>(static_cast<uintptr_t>(fid));
Elliott Hughesaed4be92011-12-02 16:16:23 -08001401}
1402
Mathieu Chartiere401d142015-04-22 13:56:20 -07001403static ArtMethod* FromMethodId(JDWP::MethodId mid)
Ian Rogersb726dcb2012-09-05 08:57:23 -07001404 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07001405 return reinterpret_cast<ArtMethod*>(static_cast<uintptr_t>(mid));
Elliott Hughes03181a82011-11-17 17:22:21 -08001406}
1407
Sebastien Hertz6995c602014-09-09 12:10:13 +02001408bool Dbg::MatchThread(JDWP::ObjectId expected_thread_id, Thread* event_thread) {
1409 CHECK(event_thread != nullptr);
1410 JDWP::JdwpError error;
Mathieu Chartiere401d142015-04-22 13:56:20 -07001411 mirror::Object* expected_thread_peer = gRegistry->Get<mirror::Object*>(
1412 expected_thread_id, &error);
Sebastien Hertz6995c602014-09-09 12:10:13 +02001413 return expected_thread_peer == event_thread->GetPeer();
1414}
1415
1416bool Dbg::MatchLocation(const JDWP::JdwpLocation& expected_location,
1417 const JDWP::EventLocation& event_location) {
1418 if (expected_location.dex_pc != event_location.dex_pc) {
1419 return false;
1420 }
Mathieu Chartiere401d142015-04-22 13:56:20 -07001421 ArtMethod* m = FromMethodId(expected_location.method_id);
Sebastien Hertz6995c602014-09-09 12:10:13 +02001422 return m == event_location.method;
1423}
1424
1425bool Dbg::MatchType(mirror::Class* event_class, JDWP::RefTypeId class_id) {
Sebastien Hertza9aa0ff2014-09-19 12:07:51 +02001426 if (event_class == nullptr) {
1427 return false;
1428 }
Sebastien Hertz6995c602014-09-09 12:10:13 +02001429 JDWP::JdwpError error;
1430 mirror::Class* expected_class = DecodeClass(class_id, &error);
1431 CHECK(expected_class != nullptr);
1432 return expected_class->IsAssignableFrom(event_class);
1433}
1434
1435bool Dbg::MatchField(JDWP::RefTypeId expected_type_id, JDWP::FieldId expected_field_id,
Mathieu Chartierc7853442015-03-27 14:35:38 -07001436 ArtField* event_field) {
1437 ArtField* expected_field = FromFieldId(expected_field_id);
Sebastien Hertz6995c602014-09-09 12:10:13 +02001438 if (expected_field != event_field) {
1439 return false;
1440 }
1441 return Dbg::MatchType(event_field->GetDeclaringClass(), expected_type_id);
1442}
1443
1444bool Dbg::MatchInstance(JDWP::ObjectId expected_instance_id, mirror::Object* event_instance) {
1445 JDWP::JdwpError error;
1446 mirror::Object* modifier_instance = gRegistry->Get<mirror::Object*>(expected_instance_id, &error);
1447 return modifier_instance == event_instance;
1448}
1449
Mathieu Chartiere401d142015-04-22 13:56:20 -07001450void Dbg::SetJdwpLocation(JDWP::JdwpLocation* location, ArtMethod* m, uint32_t dex_pc)
Sebastien Hertz69206392015-04-07 15:54:25 +02001451 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_)
1452 LOCKS_EXCLUDED(Locks::thread_list_lock_,
1453 Locks::thread_suspend_count_lock_) {
Ian Rogersc0542af2014-09-03 16:16:56 -07001454 if (m == nullptr) {
Sebastien Hertza9aa0ff2014-09-19 12:07:51 +02001455 memset(location, 0, sizeof(*location));
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08001456 } else {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001457 mirror::Class* c = m->GetDeclaringClass();
Ian Rogersc0542af2014-09-03 16:16:56 -07001458 location->type_tag = GetTypeTag(c);
1459 location->class_id = gRegistry->AddRefType(c);
1460 location->method_id = ToMethodId(m);
1461 location->dex_pc = (m->IsNative() || m->IsProxyMethod()) ? static_cast<uint64_t>(-1) : dex_pc;
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08001462 }
Elliott Hughesd07986f2011-12-06 18:27:45 -08001463}
1464
Ian Rogersc0542af2014-09-03 16:16:56 -07001465std::string Dbg::GetMethodName(JDWP::MethodId method_id) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07001466 ArtMethod* m = FromMethodId(method_id);
Sebastien Hertza9aa0ff2014-09-19 12:07:51 +02001467 if (m == nullptr) {
Mathieu Chartier2cebb242015-04-21 16:50:40 -07001468 return "null";
Sebastien Hertza9aa0ff2014-09-19 12:07:51 +02001469 }
Sebastien Hertz415fd082015-06-01 11:42:27 +02001470 return m->GetInterfaceMethodIfProxy(sizeof(void*))->GetName();
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001471}
1472
Ian Rogersc0542af2014-09-03 16:16:56 -07001473std::string Dbg::GetFieldName(JDWP::FieldId field_id) {
Mathieu Chartierc7853442015-03-27 14:35:38 -07001474 ArtField* f = FromFieldId(field_id);
Sebastien Hertza9aa0ff2014-09-19 12:07:51 +02001475 if (f == nullptr) {
Mathieu Chartier2cebb242015-04-21 16:50:40 -07001476 return "null";
Sebastien Hertza9aa0ff2014-09-19 12:07:51 +02001477 }
1478 return f->GetName();
Elliott Hughesa96836a2013-01-17 12:27:49 -08001479}
1480
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001481/*
1482 * Augment the access flags for synthetic methods and fields by setting
1483 * the (as described by the spec) "0xf0000000 bit". Also, strip out any
1484 * flags not specified by the Java programming language.
1485 */
1486static uint32_t MangleAccessFlags(uint32_t accessFlags) {
1487 accessFlags &= kAccJavaFlagsMask;
1488 if ((accessFlags & kAccSynthetic) != 0) {
1489 accessFlags |= 0xf0000000;
1490 }
1491 return accessFlags;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001492}
1493
Elliott Hughesdbb40792011-11-18 17:05:22 -08001494/*
Jeff Haob7cefc72013-11-14 14:51:09 -08001495 * Circularly shifts registers so that arguments come first. Debuggers
1496 * expect slots to begin with arguments, but dex code places them at
1497 * the end.
Elliott Hughesdbb40792011-11-18 17:05:22 -08001498 */
Mathieu Chartiere401d142015-04-22 13:56:20 -07001499static uint16_t MangleSlot(uint16_t slot, ArtMethod* m)
Jeff Haob7cefc72013-11-14 14:51:09 -08001500 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07001501 const DexFile::CodeItem* code_item = m->GetCodeItem();
Sebastien Hertzcb19ebf2014-03-11 15:26:35 +01001502 if (code_item == nullptr) {
1503 // We should not get here for a method without code (native, proxy or abstract). Log it and
1504 // return the slot as is since all registers are arguments.
1505 LOG(WARNING) << "Trying to mangle slot for method without code " << PrettyMethod(m);
1506 return slot;
1507 }
Jeff Haob7cefc72013-11-14 14:51:09 -08001508 uint16_t ins_size = code_item->ins_size_;
1509 uint16_t locals_size = code_item->registers_size_ - ins_size;
1510 if (slot >= locals_size) {
1511 return slot - locals_size;
1512 } else {
1513 return slot + ins_size;
Elliott Hughesdbb40792011-11-18 17:05:22 -08001514 }
Elliott Hughesdbb40792011-11-18 17:05:22 -08001515}
1516
Jeff Haob7cefc72013-11-14 14:51:09 -08001517/*
1518 * Circularly shifts registers so that arguments come last. Reverts
1519 * slots to dex style argument placement.
1520 */
Mathieu Chartiere401d142015-04-22 13:56:20 -07001521static uint16_t DemangleSlot(uint16_t slot, ArtMethod* m, JDWP::JdwpError* error)
Ian Rogersb726dcb2012-09-05 08:57:23 -07001522 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07001523 const DexFile::CodeItem* code_item = m->GetCodeItem();
Sebastien Hertzcb19ebf2014-03-11 15:26:35 +01001524 if (code_item == nullptr) {
1525 // We should not get here for a method without code (native, proxy or abstract). Log it and
1526 // return the slot as is since all registers are arguments.
1527 LOG(WARNING) << "Trying to demangle slot for method without code " << PrettyMethod(m);
Mathieu Chartiere401d142015-04-22 13:56:20 -07001528 uint16_t vreg_count = ArtMethod::NumArgRegisters(m->GetShorty());
Sebastien Hertzabbabc82015-03-26 08:47:47 +01001529 if (slot < vreg_count) {
1530 *error = JDWP::ERR_NONE;
1531 return slot;
1532 }
Jeff Haob7cefc72013-11-14 14:51:09 -08001533 } else {
Sebastien Hertzabbabc82015-03-26 08:47:47 +01001534 if (slot < code_item->registers_size_) {
1535 uint16_t ins_size = code_item->ins_size_;
1536 uint16_t locals_size = code_item->registers_size_ - ins_size;
1537 *error = JDWP::ERR_NONE;
1538 return (slot < ins_size) ? slot + locals_size : slot - ins_size;
1539 }
Elliott Hughesdbb40792011-11-18 17:05:22 -08001540 }
Sebastien Hertzabbabc82015-03-26 08:47:47 +01001541
1542 // Slot is invalid in the method.
1543 LOG(ERROR) << "Invalid local slot " << slot << " for method " << PrettyMethod(m);
1544 *error = JDWP::ERR_INVALID_SLOT;
1545 return DexFile::kDexNoIndex16;
Elliott Hughesdbb40792011-11-18 17:05:22 -08001546}
1547
Elliott Hughes88d63092013-01-09 09:55:54 -08001548JDWP::JdwpError Dbg::OutputDeclaredFields(JDWP::RefTypeId class_id, bool with_generic, JDWP::ExpandBuf* pReply) {
Ian Rogersc0542af2014-09-03 16:16:56 -07001549 JDWP::JdwpError error;
1550 mirror::Class* c = DecodeClass(class_id, &error);
1551 if (c == nullptr) {
1552 return error;
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -08001553 }
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001554
1555 size_t instance_field_count = c->NumInstanceFields();
1556 size_t static_field_count = c->NumStaticFields();
1557
1558 expandBufAdd4BE(pReply, instance_field_count + static_field_count);
1559
1560 for (size_t i = 0; i < instance_field_count + static_field_count; ++i) {
Mathieu Chartierc7853442015-03-27 14:35:38 -07001561 ArtField* f = (i < instance_field_count) ? c->GetInstanceField(i) : c->GetStaticField(i - instance_field_count);
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001562 expandBufAddFieldId(pReply, ToFieldId(f));
Mathieu Chartier61c5ebc2014-06-05 17:42:53 -07001563 expandBufAddUtf8String(pReply, f->GetName());
1564 expandBufAddUtf8String(pReply, f->GetTypeDescriptor());
Elliott Hughesc5b734a2011-12-01 17:20:58 -08001565 if (with_generic) {
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001566 static const char genericSignature[1] = "";
1567 expandBufAddUtf8String(pReply, genericSignature);
1568 }
1569 expandBufAdd4BE(pReply, MangleAccessFlags(f->GetAccessFlags()));
1570 }
Elliott Hughes436e3722012-02-17 20:01:47 -08001571 return JDWP::ERR_NONE;
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001572}
1573
Elliott Hughes88d63092013-01-09 09:55:54 -08001574JDWP::JdwpError Dbg::OutputDeclaredMethods(JDWP::RefTypeId class_id, bool with_generic,
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001575 JDWP::ExpandBuf* pReply) {
Ian Rogersc0542af2014-09-03 16:16:56 -07001576 JDWP::JdwpError error;
1577 mirror::Class* c = DecodeClass(class_id, &error);
1578 if (c == nullptr) {
1579 return error;
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -08001580 }
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001581
1582 size_t direct_method_count = c->NumDirectMethods();
1583 size_t virtual_method_count = c->NumVirtualMethods();
1584
1585 expandBufAdd4BE(pReply, direct_method_count + virtual_method_count);
1586
Mathieu Chartiere401d142015-04-22 13:56:20 -07001587 auto* cl = Runtime::Current()->GetClassLinker();
1588 auto ptr_size = cl->GetImagePointerSize();
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001589 for (size_t i = 0; i < direct_method_count + virtual_method_count; ++i) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07001590 ArtMethod* m = i < direct_method_count ?
1591 c->GetDirectMethod(i, ptr_size) : c->GetVirtualMethod(i - direct_method_count, ptr_size);
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001592 expandBufAddMethodId(pReply, ToMethodId(m));
Sebastien Hertz415fd082015-06-01 11:42:27 +02001593 expandBufAddUtf8String(pReply, m->GetInterfaceMethodIfProxy(sizeof(void*))->GetName());
1594 expandBufAddUtf8String(pReply,
1595 m->GetInterfaceMethodIfProxy(sizeof(void*))->GetSignature().ToString());
Elliott Hughesc5b734a2011-12-01 17:20:58 -08001596 if (with_generic) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07001597 const char* generic_signature = "";
1598 expandBufAddUtf8String(pReply, generic_signature);
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001599 }
1600 expandBufAdd4BE(pReply, MangleAccessFlags(m->GetAccessFlags()));
1601 }
Elliott Hughes436e3722012-02-17 20:01:47 -08001602 return JDWP::ERR_NONE;
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001603}
1604
Elliott Hughes88d63092013-01-09 09:55:54 -08001605JDWP::JdwpError Dbg::OutputDeclaredInterfaces(JDWP::RefTypeId class_id, JDWP::ExpandBuf* pReply) {
Ian Rogersc0542af2014-09-03 16:16:56 -07001606 JDWP::JdwpError error;
Mathieu Chartierf8322842014-05-16 10:59:25 -07001607 Thread* self = Thread::Current();
1608 StackHandleScope<1> hs(self);
Ian Rogersc0542af2014-09-03 16:16:56 -07001609 Handle<mirror::Class> c(hs.NewHandle(DecodeClass(class_id, &error)));
Mathieu Chartierf8322842014-05-16 10:59:25 -07001610 if (c.Get() == nullptr) {
Ian Rogersc0542af2014-09-03 16:16:56 -07001611 return error;
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -08001612 }
Mathieu Chartierf8322842014-05-16 10:59:25 -07001613 size_t interface_count = c->NumDirectInterfaces();
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001614 expandBufAdd4BE(pReply, interface_count);
1615 for (size_t i = 0; i < interface_count; ++i) {
Mathieu Chartierf8322842014-05-16 10:59:25 -07001616 expandBufAddRefTypeId(pReply,
1617 gRegistry->AddRefType(mirror::Class::GetDirectInterface(self, c, i)));
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001618 }
Elliott Hughes436e3722012-02-17 20:01:47 -08001619 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001620}
1621
Ian Rogersc0542af2014-09-03 16:16:56 -07001622void Dbg::OutputLineTable(JDWP::RefTypeId, JDWP::MethodId method_id, JDWP::ExpandBuf* pReply) {
Elliott Hughes03181a82011-11-17 17:22:21 -08001623 struct DebugCallbackContext {
1624 int numItems;
1625 JDWP::ExpandBuf* pReply;
1626
Elliott Hughes2435a572012-02-17 16:07:41 -08001627 static bool Callback(void* context, uint32_t address, uint32_t line_number) {
Elliott Hughes03181a82011-11-17 17:22:21 -08001628 DebugCallbackContext* pContext = reinterpret_cast<DebugCallbackContext*>(context);
1629 expandBufAdd8BE(pContext->pReply, address);
Elliott Hughes2435a572012-02-17 16:07:41 -08001630 expandBufAdd4BE(pContext->pReply, line_number);
Elliott Hughes03181a82011-11-17 17:22:21 -08001631 pContext->numItems++;
Sebastien Hertzf2910ee2013-10-19 16:39:24 +02001632 return false;
Elliott Hughes03181a82011-11-17 17:22:21 -08001633 }
1634 };
Mathieu Chartiere401d142015-04-22 13:56:20 -07001635 ArtMethod* m = FromMethodId(method_id);
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07001636 const DexFile::CodeItem* code_item = m->GetCodeItem();
Elliott Hughes03181a82011-11-17 17:22:21 -08001637 uint64_t start, end;
Sebastien Hertzcb19ebf2014-03-11 15:26:35 +01001638 if (code_item == nullptr) {
1639 DCHECK(m->IsNative() || m->IsProxyMethod());
Elliott Hughes03181a82011-11-17 17:22:21 -08001640 start = -1;
1641 end = -1;
1642 } else {
1643 start = 0;
jeffhao14f0db92012-12-14 17:50:42 -08001644 // Return the index of the last instruction
Sebastien Hertzcb19ebf2014-03-11 15:26:35 +01001645 end = code_item->insns_size_in_code_units_ - 1;
Elliott Hughes03181a82011-11-17 17:22:21 -08001646 }
1647
1648 expandBufAdd8BE(pReply, start);
1649 expandBufAdd8BE(pReply, end);
1650
1651 // Add numLines later
1652 size_t numLinesOffset = expandBufGetLength(pReply);
1653 expandBufAdd4BE(pReply, 0);
1654
1655 DebugCallbackContext context;
1656 context.numItems = 0;
1657 context.pReply = pReply;
1658
Sebastien Hertzcb19ebf2014-03-11 15:26:35 +01001659 if (code_item != nullptr) {
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07001660 m->GetDexFile()->DecodeDebugInfo(code_item, m->IsStatic(), m->GetDexMethodIndex(),
Ian Rogersc0542af2014-09-03 16:16:56 -07001661 DebugCallbackContext::Callback, nullptr, &context);
Sebastien Hertzcb19ebf2014-03-11 15:26:35 +01001662 }
Elliott Hughes03181a82011-11-17 17:22:21 -08001663
1664 JDWP::Set4BE(expandBufGetBuffer(pReply) + numLinesOffset, context.numItems);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001665}
1666
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07001667void Dbg::OutputVariableTable(JDWP::RefTypeId, JDWP::MethodId method_id, bool with_generic,
1668 JDWP::ExpandBuf* pReply) {
Elliott Hughesdbb40792011-11-18 17:05:22 -08001669 struct DebugCallbackContext {
Mathieu Chartiere401d142015-04-22 13:56:20 -07001670 ArtMethod* method;
Elliott Hughesdbb40792011-11-18 17:05:22 -08001671 JDWP::ExpandBuf* pReply;
Elliott Hughesc5b734a2011-12-01 17:20:58 -08001672 size_t variable_count;
1673 bool with_generic;
Elliott Hughesdbb40792011-11-18 17:05:22 -08001674
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07001675 static void Callback(void* context, uint16_t slot, uint32_t startAddress, uint32_t endAddress,
1676 const char* name, const char* descriptor, const char* signature)
Jeff Haob7cefc72013-11-14 14:51:09 -08001677 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Elliott Hughesdbb40792011-11-18 17:05:22 -08001678 DebugCallbackContext* pContext = reinterpret_cast<DebugCallbackContext*>(context);
1679
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07001680 VLOG(jdwp) << StringPrintf(" %2zd: %d(%d) '%s' '%s' '%s' actual slot=%d mangled slot=%d",
1681 pContext->variable_count, startAddress, endAddress - startAddress,
1682 name, descriptor, signature, slot,
1683 MangleSlot(slot, pContext->method));
Elliott Hughesdbb40792011-11-18 17:05:22 -08001684
Jeff Haob7cefc72013-11-14 14:51:09 -08001685 slot = MangleSlot(slot, pContext->method);
Elliott Hughes68fdbd02011-11-29 19:22:47 -08001686
Elliott Hughesdbb40792011-11-18 17:05:22 -08001687 expandBufAdd8BE(pContext->pReply, startAddress);
1688 expandBufAddUtf8String(pContext->pReply, name);
1689 expandBufAddUtf8String(pContext->pReply, descriptor);
Elliott Hughesc5b734a2011-12-01 17:20:58 -08001690 if (pContext->with_generic) {
Elliott Hughesdbb40792011-11-18 17:05:22 -08001691 expandBufAddUtf8String(pContext->pReply, signature);
1692 }
1693 expandBufAdd4BE(pContext->pReply, endAddress - startAddress);
1694 expandBufAdd4BE(pContext->pReply, slot);
1695
Elliott Hughesc5b734a2011-12-01 17:20:58 -08001696 ++pContext->variable_count;
Elliott Hughesdbb40792011-11-18 17:05:22 -08001697 }
1698 };
Mathieu Chartiere401d142015-04-22 13:56:20 -07001699 ArtMethod* m = FromMethodId(method_id);
Elliott Hughesdbb40792011-11-18 17:05:22 -08001700
Elliott Hughesc5b734a2011-12-01 17:20:58 -08001701 // arg_count considers doubles and longs to take 2 units.
1702 // variable_count considers everything to take 1 unit.
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07001703 std::string shorty(m->GetShorty());
Mathieu Chartiere401d142015-04-22 13:56:20 -07001704 expandBufAdd4BE(pReply, ArtMethod::NumArgRegisters(shorty));
Elliott Hughesdbb40792011-11-18 17:05:22 -08001705
Elliott Hughesc5b734a2011-12-01 17:20:58 -08001706 // We don't know the total number of variables yet, so leave a blank and update it later.
1707 size_t variable_count_offset = expandBufGetLength(pReply);
Elliott Hughesdbb40792011-11-18 17:05:22 -08001708 expandBufAdd4BE(pReply, 0);
1709
1710 DebugCallbackContext context;
Jeff Haob7cefc72013-11-14 14:51:09 -08001711 context.method = m;
Elliott Hughesdbb40792011-11-18 17:05:22 -08001712 context.pReply = pReply;
Elliott Hughesc5b734a2011-12-01 17:20:58 -08001713 context.variable_count = 0;
1714 context.with_generic = with_generic;
Elliott Hughesdbb40792011-11-18 17:05:22 -08001715
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07001716 const DexFile::CodeItem* code_item = m->GetCodeItem();
Sebastien Hertzcb19ebf2014-03-11 15:26:35 +01001717 if (code_item != nullptr) {
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07001718 m->GetDexFile()->DecodeDebugInfo(
Ian Rogersc0542af2014-09-03 16:16:56 -07001719 code_item, m->IsStatic(), m->GetDexMethodIndex(), nullptr, DebugCallbackContext::Callback,
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07001720 &context);
Sebastien Hertzcb19ebf2014-03-11 15:26:35 +01001721 }
Elliott Hughesdbb40792011-11-18 17:05:22 -08001722
Elliott Hughesc5b734a2011-12-01 17:20:58 -08001723 JDWP::Set4BE(expandBufGetBuffer(pReply) + variable_count_offset, context.variable_count);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001724}
1725
Jeff Hao579b0242013-11-18 13:16:49 -08001726void Dbg::OutputMethodReturnValue(JDWP::MethodId method_id, const JValue* return_value,
1727 JDWP::ExpandBuf* pReply) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07001728 ArtMethod* m = FromMethodId(method_id);
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07001729 JDWP::JdwpTag tag = BasicTagFromDescriptor(m->GetShorty());
Jeff Hao579b0242013-11-18 13:16:49 -08001730 OutputJValue(tag, return_value, pReply);
1731}
1732
Sebastien Hertz3f52eaf2014-04-04 17:50:18 +02001733void Dbg::OutputFieldValue(JDWP::FieldId field_id, const JValue* field_value,
1734 JDWP::ExpandBuf* pReply) {
Mathieu Chartierc7853442015-03-27 14:35:38 -07001735 ArtField* f = FromFieldId(field_id);
Mathieu Chartier61c5ebc2014-06-05 17:42:53 -07001736 JDWP::JdwpTag tag = BasicTagFromDescriptor(f->GetTypeDescriptor());
Sebastien Hertz3f52eaf2014-04-04 17:50:18 +02001737 OutputJValue(tag, field_value, pReply);
1738}
1739
Elliott Hughes9777ba22013-01-17 09:04:19 -08001740JDWP::JdwpError Dbg::GetBytecodes(JDWP::RefTypeId, JDWP::MethodId method_id,
Ian Rogersc0542af2014-09-03 16:16:56 -07001741 std::vector<uint8_t>* bytecodes) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07001742 ArtMethod* m = FromMethodId(method_id);
Ian Rogersc0542af2014-09-03 16:16:56 -07001743 if (m == nullptr) {
Elliott Hughes9777ba22013-01-17 09:04:19 -08001744 return JDWP::ERR_INVALID_METHODID;
1745 }
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07001746 const DexFile::CodeItem* code_item = m->GetCodeItem();
Elliott Hughes9777ba22013-01-17 09:04:19 -08001747 size_t byte_count = code_item->insns_size_in_code_units_ * 2;
1748 const uint8_t* begin = reinterpret_cast<const uint8_t*>(code_item->insns_);
1749 const uint8_t* end = begin + byte_count;
1750 for (const uint8_t* p = begin; p != end; ++p) {
Ian Rogersc0542af2014-09-03 16:16:56 -07001751 bytecodes->push_back(*p);
Elliott Hughes9777ba22013-01-17 09:04:19 -08001752 }
1753 return JDWP::ERR_NONE;
1754}
1755
Elliott Hughes88d63092013-01-09 09:55:54 -08001756JDWP::JdwpTag Dbg::GetFieldBasicTag(JDWP::FieldId field_id) {
Mathieu Chartier61c5ebc2014-06-05 17:42:53 -07001757 return BasicTagFromDescriptor(FromFieldId(field_id)->GetTypeDescriptor());
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001758}
1759
Elliott Hughes88d63092013-01-09 09:55:54 -08001760JDWP::JdwpTag Dbg::GetStaticFieldBasicTag(JDWP::FieldId field_id) {
Mathieu Chartier61c5ebc2014-06-05 17:42:53 -07001761 return BasicTagFromDescriptor(FromFieldId(field_id)->GetTypeDescriptor());
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001762}
1763
Elliott Hughes88d63092013-01-09 09:55:54 -08001764static JDWP::JdwpError GetFieldValueImpl(JDWP::RefTypeId ref_type_id, JDWP::ObjectId object_id,
1765 JDWP::FieldId field_id, JDWP::ExpandBuf* pReply,
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001766 bool is_static)
Ian Rogersb726dcb2012-09-05 08:57:23 -07001767 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Ian Rogersc0542af2014-09-03 16:16:56 -07001768 JDWP::JdwpError error;
1769 mirror::Class* c = DecodeClass(ref_type_id, &error);
1770 if (ref_type_id != 0 && c == nullptr) {
1771 return error;
Elliott Hughes0cf74332012-02-23 23:14:00 -08001772 }
1773
Sebastien Hertz6995c602014-09-09 12:10:13 +02001774 mirror::Object* o = Dbg::GetObjectRegistry()->Get<mirror::Object*>(object_id, &error);
Ian Rogersc0542af2014-09-03 16:16:56 -07001775 if ((!is_static && o == nullptr) || error != JDWP::ERR_NONE) {
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08001776 return JDWP::ERR_INVALID_OBJECT;
1777 }
Mathieu Chartierc7853442015-03-27 14:35:38 -07001778 ArtField* f = FromFieldId(field_id);
Elliott Hughes0cf74332012-02-23 23:14:00 -08001779
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001780 mirror::Class* receiver_class = c;
Ian Rogersc0542af2014-09-03 16:16:56 -07001781 if (receiver_class == nullptr && o != nullptr) {
Elliott Hughes0cf74332012-02-23 23:14:00 -08001782 receiver_class = o->GetClass();
1783 }
Mathieu Chartier2cebb242015-04-21 16:50:40 -07001784 // TODO: should we give up now if receiver_class is null?
Ian Rogersc0542af2014-09-03 16:16:56 -07001785 if (receiver_class != nullptr && !f->GetDeclaringClass()->IsAssignableFrom(receiver_class)) {
Elliott Hughes0cf74332012-02-23 23:14:00 -08001786 LOG(INFO) << "ERR_INVALID_FIELDID: " << PrettyField(f) << " " << PrettyClass(receiver_class);
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08001787 return JDWP::ERR_INVALID_FIELDID;
1788 }
Elliott Hughesaed4be92011-12-02 16:16:23 -08001789
Elliott Hughes0cf74332012-02-23 23:14:00 -08001790 // The RI only enforces the static/non-static mismatch in one direction.
1791 // TODO: should we change the tests and check both?
1792 if (is_static) {
1793 if (!f->IsStatic()) {
1794 return JDWP::ERR_INVALID_FIELDID;
1795 }
1796 } else {
1797 if (f->IsStatic()) {
Ian Rogersc0542af2014-09-03 16:16:56 -07001798 LOG(WARNING) << "Ignoring non-nullptr receiver for ObjectReference.SetValues on static field "
1799 << PrettyField(f);
Elliott Hughes0cf74332012-02-23 23:14:00 -08001800 }
1801 }
jeffhao0dfbb7e2012-11-28 15:26:03 -08001802 if (f->IsStatic()) {
1803 o = f->GetDeclaringClass();
1804 }
Elliott Hughes0cf74332012-02-23 23:14:00 -08001805
Mathieu Chartier61c5ebc2014-06-05 17:42:53 -07001806 JDWP::JdwpTag tag = BasicTagFromDescriptor(f->GetTypeDescriptor());
Jeff Hao579b0242013-11-18 13:16:49 -08001807 JValue field_value;
1808 if (tag == JDWP::JT_VOID) {
1809 LOG(FATAL) << "Unknown tag: " << tag;
1810 } else if (!IsPrimitiveTag(tag)) {
1811 field_value.SetL(f->GetObject(o));
1812 } else if (tag == JDWP::JT_DOUBLE || tag == JDWP::JT_LONG) {
1813 field_value.SetJ(f->Get64(o));
Elliott Hughesaed4be92011-12-02 16:16:23 -08001814 } else {
Jeff Hao579b0242013-11-18 13:16:49 -08001815 field_value.SetI(f->Get32(o));
Elliott Hughesaed4be92011-12-02 16:16:23 -08001816 }
Jeff Hao579b0242013-11-18 13:16:49 -08001817 Dbg::OutputJValue(tag, &field_value, pReply);
1818
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08001819 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001820}
1821
Elliott Hughes88d63092013-01-09 09:55:54 -08001822JDWP::JdwpError Dbg::GetFieldValue(JDWP::ObjectId object_id, JDWP::FieldId field_id,
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001823 JDWP::ExpandBuf* pReply) {
Elliott Hughes88d63092013-01-09 09:55:54 -08001824 return GetFieldValueImpl(0, object_id, field_id, pReply, false);
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08001825}
1826
Ian Rogersc0542af2014-09-03 16:16:56 -07001827JDWP::JdwpError Dbg::GetStaticFieldValue(JDWP::RefTypeId ref_type_id, JDWP::FieldId field_id,
1828 JDWP::ExpandBuf* pReply) {
Elliott Hughes88d63092013-01-09 09:55:54 -08001829 return GetFieldValueImpl(ref_type_id, 0, field_id, pReply, true);
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08001830}
1831
Elliott Hughes88d63092013-01-09 09:55:54 -08001832static JDWP::JdwpError SetFieldValueImpl(JDWP::ObjectId object_id, JDWP::FieldId field_id,
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001833 uint64_t value, int width, bool is_static)
Ian Rogersb726dcb2012-09-05 08:57:23 -07001834 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Ian Rogersc0542af2014-09-03 16:16:56 -07001835 JDWP::JdwpError error;
Sebastien Hertz6995c602014-09-09 12:10:13 +02001836 mirror::Object* o = Dbg::GetObjectRegistry()->Get<mirror::Object*>(object_id, &error);
Ian Rogersc0542af2014-09-03 16:16:56 -07001837 if ((!is_static && o == nullptr) || error != JDWP::ERR_NONE) {
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08001838 return JDWP::ERR_INVALID_OBJECT;
1839 }
Mathieu Chartierc7853442015-03-27 14:35:38 -07001840 ArtField* f = FromFieldId(field_id);
Elliott Hughes0cf74332012-02-23 23:14:00 -08001841
1842 // The RI only enforces the static/non-static mismatch in one direction.
1843 // TODO: should we change the tests and check both?
1844 if (is_static) {
1845 if (!f->IsStatic()) {
1846 return JDWP::ERR_INVALID_FIELDID;
1847 }
1848 } else {
1849 if (f->IsStatic()) {
Ian Rogersc0542af2014-09-03 16:16:56 -07001850 LOG(WARNING) << "Ignoring non-nullptr receiver for ObjectReference.SetValues on static field " << PrettyField(f);
Elliott Hughes0cf74332012-02-23 23:14:00 -08001851 }
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08001852 }
jeffhao0dfbb7e2012-11-28 15:26:03 -08001853 if (f->IsStatic()) {
1854 o = f->GetDeclaringClass();
1855 }
Elliott Hughesaed4be92011-12-02 16:16:23 -08001856
Mathieu Chartier61c5ebc2014-06-05 17:42:53 -07001857 JDWP::JdwpTag tag = BasicTagFromDescriptor(f->GetTypeDescriptor());
Elliott Hughesaed4be92011-12-02 16:16:23 -08001858
1859 if (IsPrimitiveTag(tag)) {
1860 if (tag == JDWP::JT_DOUBLE || tag == JDWP::JT_LONG) {
Elliott Hughes1bac54f2012-03-16 12:48:31 -07001861 CHECK_EQ(width, 8);
Sebastien Hertzd2fe10a2014-01-15 10:20:56 +01001862 // Debugging can't use transactional mode (runtime only).
1863 f->Set64<false>(o, value);
Elliott Hughesaed4be92011-12-02 16:16:23 -08001864 } else {
Elliott Hughes1bac54f2012-03-16 12:48:31 -07001865 CHECK_LE(width, 4);
Sebastien Hertzd2fe10a2014-01-15 10:20:56 +01001866 // Debugging can't use transactional mode (runtime only).
1867 f->Set32<false>(o, value);
Elliott Hughesaed4be92011-12-02 16:16:23 -08001868 }
1869 } else {
Sebastien Hertz6995c602014-09-09 12:10:13 +02001870 mirror::Object* v = Dbg::GetObjectRegistry()->Get<mirror::Object*>(value, &error);
Ian Rogersc0542af2014-09-03 16:16:56 -07001871 if (error != JDWP::ERR_NONE) {
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -08001872 return JDWP::ERR_INVALID_OBJECT;
1873 }
Ian Rogersc0542af2014-09-03 16:16:56 -07001874 if (v != nullptr) {
Mathieu Chartier61c5ebc2014-06-05 17:42:53 -07001875 mirror::Class* field_type;
1876 {
Mathieu Chartierc7853442015-03-27 14:35:38 -07001877 StackHandleScope<2> hs(Thread::Current());
Mathieu Chartier61c5ebc2014-06-05 17:42:53 -07001878 HandleWrapper<mirror::Object> h_v(hs.NewHandleWrapper(&v));
Mathieu Chartier61c5ebc2014-06-05 17:42:53 -07001879 HandleWrapper<mirror::Object> h_o(hs.NewHandleWrapper(&o));
Mathieu Chartierc7853442015-03-27 14:35:38 -07001880 field_type = f->GetType<true>();
Mathieu Chartier61c5ebc2014-06-05 17:42:53 -07001881 }
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08001882 if (!field_type->IsAssignableFrom(v->GetClass())) {
1883 return JDWP::ERR_INVALID_OBJECT;
1884 }
1885 }
Sebastien Hertzd2fe10a2014-01-15 10:20:56 +01001886 // Debugging can't use transactional mode (runtime only).
1887 f->SetObject<false>(o, v);
Elliott Hughesaed4be92011-12-02 16:16:23 -08001888 }
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -08001889
1890 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001891}
1892
Elliott Hughes88d63092013-01-09 09:55:54 -08001893JDWP::JdwpError Dbg::SetFieldValue(JDWP::ObjectId object_id, JDWP::FieldId field_id, uint64_t value,
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001894 int width) {
Elliott Hughes88d63092013-01-09 09:55:54 -08001895 return SetFieldValueImpl(object_id, field_id, value, width, false);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001896}
1897
Elliott Hughes88d63092013-01-09 09:55:54 -08001898JDWP::JdwpError Dbg::SetStaticFieldValue(JDWP::FieldId field_id, uint64_t value, int width) {
1899 return SetFieldValueImpl(0, field_id, value, width, true);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001900}
1901
Sebastien Hertzb0b0b492014-09-15 11:27:27 +02001902JDWP::JdwpError Dbg::StringToUtf8(JDWP::ObjectId string_id, std::string* str) {
Ian Rogersc0542af2014-09-03 16:16:56 -07001903 JDWP::JdwpError error;
Sebastien Hertzb0b0b492014-09-15 11:27:27 +02001904 mirror::Object* obj = gRegistry->Get<mirror::Object*>(string_id, &error);
1905 if (error != JDWP::ERR_NONE) {
1906 return error;
1907 }
1908 if (obj == nullptr) {
1909 return JDWP::ERR_INVALID_OBJECT;
1910 }
1911 {
1912 ScopedObjectAccessUnchecked soa(Thread::Current());
1913 mirror::Class* java_lang_String = soa.Decode<mirror::Class*>(WellKnownClasses::java_lang_String);
1914 if (!java_lang_String->IsAssignableFrom(obj->GetClass())) {
1915 // This isn't a string.
1916 return JDWP::ERR_INVALID_STRING;
1917 }
1918 }
1919 *str = obj->AsString()->ToModifiedUtf8();
1920 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001921}
1922
Jeff Hao579b0242013-11-18 13:16:49 -08001923void Dbg::OutputJValue(JDWP::JdwpTag tag, const JValue* return_value, JDWP::ExpandBuf* pReply) {
1924 if (IsPrimitiveTag(tag)) {
1925 expandBufAdd1(pReply, tag);
1926 if (tag == JDWP::JT_BOOLEAN || tag == JDWP::JT_BYTE) {
1927 expandBufAdd1(pReply, return_value->GetI());
1928 } else if (tag == JDWP::JT_CHAR || tag == JDWP::JT_SHORT) {
1929 expandBufAdd2BE(pReply, return_value->GetI());
1930 } else if (tag == JDWP::JT_FLOAT || tag == JDWP::JT_INT) {
1931 expandBufAdd4BE(pReply, return_value->GetI());
1932 } else if (tag == JDWP::JT_DOUBLE || tag == JDWP::JT_LONG) {
1933 expandBufAdd8BE(pReply, return_value->GetJ());
1934 } else {
1935 CHECK_EQ(tag, JDWP::JT_VOID);
1936 }
1937 } else {
Ian Rogers98379392014-02-24 16:53:16 -08001938 ScopedObjectAccessUnchecked soa(Thread::Current());
Jeff Hao579b0242013-11-18 13:16:49 -08001939 mirror::Object* value = return_value->GetL();
Ian Rogers98379392014-02-24 16:53:16 -08001940 expandBufAdd1(pReply, TagFromObject(soa, value));
Jeff Hao579b0242013-11-18 13:16:49 -08001941 expandBufAddObjectId(pReply, gRegistry->Add(value));
1942 }
1943}
1944
Ian Rogersc0542af2014-09-03 16:16:56 -07001945JDWP::JdwpError Dbg::GetThreadName(JDWP::ObjectId thread_id, std::string* name) {
jeffhaoa77f0f62012-12-05 17:19:31 -08001946 ScopedObjectAccessUnchecked soa(Thread::Current());
Ian Rogersc0542af2014-09-03 16:16:56 -07001947 JDWP::JdwpError error;
1948 Thread* thread = DecodeThread(soa, thread_id, &error);
1949 UNUSED(thread);
Elliott Hughes221229c2013-01-08 18:17:50 -08001950 if (error != JDWP::ERR_NONE && error != JDWP::ERR_THREAD_NOT_ALIVE) {
1951 return error;
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001952 }
Elliott Hughes221229c2013-01-08 18:17:50 -08001953
1954 // We still need to report the zombie threads' names, so we can't just call Thread::GetThreadName.
Ian Rogersc0542af2014-09-03 16:16:56 -07001955 mirror::Object* thread_object = gRegistry->Get<mirror::Object*>(thread_id, &error);
1956 CHECK(thread_object != nullptr) << error;
Mathieu Chartierc7853442015-03-27 14:35:38 -07001957 ArtField* java_lang_Thread_name_field =
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001958 soa.DecodeField(WellKnownClasses::java_lang_Thread_name);
1959 mirror::String* s =
1960 reinterpret_cast<mirror::String*>(java_lang_Thread_name_field->GetObject(thread_object));
Ian Rogersc0542af2014-09-03 16:16:56 -07001961 if (s != nullptr) {
1962 *name = s->ToModifiedUtf8();
Elliott Hughes221229c2013-01-08 18:17:50 -08001963 }
1964 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001965}
1966
Elliott Hughes221229c2013-01-08 18:17:50 -08001967JDWP::JdwpError Dbg::GetThreadGroup(JDWP::ObjectId thread_id, JDWP::ExpandBuf* pReply) {
Sebastien Hertza06430c2014-09-15 19:21:30 +02001968 ScopedObjectAccessUnchecked soa(Thread::Current());
Ian Rogersc0542af2014-09-03 16:16:56 -07001969 JDWP::JdwpError error;
1970 mirror::Object* thread_object = gRegistry->Get<mirror::Object*>(thread_id, &error);
1971 if (error != JDWP::ERR_NONE) {
Elliott Hughes2435a572012-02-17 16:07:41 -08001972 return JDWP::ERR_INVALID_OBJECT;
1973 }
Mathieu Chartier2d5f39e2014-09-19 17:52:37 -07001974 ScopedAssertNoThreadSuspension ants(soa.Self(), "Debugger: GetThreadGroup");
Elliott Hughes2435a572012-02-17 16:07:41 -08001975 // Okay, so it's an object, but is it actually a thread?
Sebastien Hertz69206392015-04-07 15:54:25 +02001976 Thread* thread = DecodeThread(soa, thread_id, &error);
1977 UNUSED(thread);
Elliott Hughes221229c2013-01-08 18:17:50 -08001978 if (error == JDWP::ERR_THREAD_NOT_ALIVE) {
1979 // Zombie threads are in the null group.
1980 expandBufAddObjectId(pReply, JDWP::ObjectId(0));
Sebastien Hertz52d131d2014-03-13 16:17:40 +01001981 error = JDWP::ERR_NONE;
1982 } else if (error == JDWP::ERR_NONE) {
1983 mirror::Class* c = soa.Decode<mirror::Class*>(WellKnownClasses::java_lang_Thread);
1984 CHECK(c != nullptr);
Mathieu Chartierc7853442015-03-27 14:35:38 -07001985 ArtField* f = soa.DecodeField(WellKnownClasses::java_lang_Thread_group);
Hiroshi Yamauchib5a9e3d2014-06-09 12:11:20 -07001986 CHECK(f != nullptr);
Sebastien Hertz52d131d2014-03-13 16:17:40 +01001987 mirror::Object* group = f->GetObject(thread_object);
Hiroshi Yamauchib5a9e3d2014-06-09 12:11:20 -07001988 CHECK(group != nullptr);
Sebastien Hertz52d131d2014-03-13 16:17:40 +01001989 JDWP::ObjectId thread_group_id = gRegistry->Add(group);
1990 expandBufAddObjectId(pReply, thread_group_id);
Elliott Hughes221229c2013-01-08 18:17:50 -08001991 }
Sebastien Hertz52d131d2014-03-13 16:17:40 +01001992 return error;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001993}
1994
Sebastien Hertza06430c2014-09-15 19:21:30 +02001995static mirror::Object* DecodeThreadGroup(ScopedObjectAccessUnchecked& soa,
1996 JDWP::ObjectId thread_group_id, JDWP::JdwpError* error)
1997 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Sebastien Hertz6995c602014-09-09 12:10:13 +02001998 mirror::Object* thread_group = Dbg::GetObjectRegistry()->Get<mirror::Object*>(thread_group_id,
1999 error);
Sebastien Hertza06430c2014-09-15 19:21:30 +02002000 if (*error != JDWP::ERR_NONE) {
2001 return nullptr;
2002 }
2003 if (thread_group == nullptr) {
2004 *error = JDWP::ERR_INVALID_OBJECT;
2005 return nullptr;
2006 }
Ian Rogers98379392014-02-24 16:53:16 -08002007 mirror::Class* c = soa.Decode<mirror::Class*>(WellKnownClasses::java_lang_ThreadGroup);
2008 CHECK(c != nullptr);
Sebastien Hertza06430c2014-09-15 19:21:30 +02002009 if (!c->IsAssignableFrom(thread_group->GetClass())) {
2010 // This is not a java.lang.ThreadGroup.
2011 *error = JDWP::ERR_INVALID_THREAD_GROUP;
2012 return nullptr;
2013 }
2014 *error = JDWP::ERR_NONE;
2015 return thread_group;
2016}
2017
2018JDWP::JdwpError Dbg::GetThreadGroupName(JDWP::ObjectId thread_group_id, JDWP::ExpandBuf* pReply) {
2019 ScopedObjectAccessUnchecked soa(Thread::Current());
2020 JDWP::JdwpError error;
2021 mirror::Object* thread_group = DecodeThreadGroup(soa, thread_group_id, &error);
2022 if (error != JDWP::ERR_NONE) {
2023 return error;
2024 }
Mathieu Chartier2d5f39e2014-09-19 17:52:37 -07002025 ScopedAssertNoThreadSuspension ants(soa.Self(), "Debugger: GetThreadGroupName");
Mathieu Chartierc7853442015-03-27 14:35:38 -07002026 ArtField* f = soa.DecodeField(WellKnownClasses::java_lang_ThreadGroup_name);
Ian Rogersc0542af2014-09-03 16:16:56 -07002027 CHECK(f != nullptr);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002028 mirror::String* s = reinterpret_cast<mirror::String*>(f->GetObject(thread_group));
Sebastien Hertza06430c2014-09-15 19:21:30 +02002029
2030 std::string thread_group_name(s->ToModifiedUtf8());
2031 expandBufAddUtf8String(pReply, thread_group_name);
2032 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002033}
2034
Sebastien Hertza06430c2014-09-15 19:21:30 +02002035JDWP::JdwpError Dbg::GetThreadGroupParent(JDWP::ObjectId thread_group_id, JDWP::ExpandBuf* pReply) {
Ian Rogers98379392014-02-24 16:53:16 -08002036 ScopedObjectAccessUnchecked soa(Thread::Current());
Ian Rogersc0542af2014-09-03 16:16:56 -07002037 JDWP::JdwpError error;
Sebastien Hertza06430c2014-09-15 19:21:30 +02002038 mirror::Object* thread_group = DecodeThreadGroup(soa, thread_group_id, &error);
2039 if (error != JDWP::ERR_NONE) {
2040 return error;
2041 }
Mathieu Chartier2d5f39e2014-09-19 17:52:37 -07002042 mirror::Object* parent;
2043 {
2044 ScopedAssertNoThreadSuspension ants(soa.Self(), "Debugger: GetThreadGroupParent");
Mathieu Chartierc7853442015-03-27 14:35:38 -07002045 ArtField* f = soa.DecodeField(WellKnownClasses::java_lang_ThreadGroup_parent);
Mathieu Chartier2d5f39e2014-09-19 17:52:37 -07002046 CHECK(f != nullptr);
2047 parent = f->GetObject(thread_group);
2048 }
Sebastien Hertza06430c2014-09-15 19:21:30 +02002049 JDWP::ObjectId parent_group_id = gRegistry->Add(parent);
2050 expandBufAddObjectId(pReply, parent_group_id);
2051 return JDWP::ERR_NONE;
2052}
2053
2054static void GetChildThreadGroups(ScopedObjectAccessUnchecked& soa, mirror::Object* thread_group,
2055 std::vector<JDWP::ObjectId>* child_thread_group_ids)
2056 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
2057 CHECK(thread_group != nullptr);
2058
2059 // Get the ArrayList<ThreadGroup> "groups" out of this thread group...
Mathieu Chartierc7853442015-03-27 14:35:38 -07002060 ArtField* groups_field = soa.DecodeField(WellKnownClasses::java_lang_ThreadGroup_groups);
Sebastien Hertza06430c2014-09-15 19:21:30 +02002061 mirror::Object* groups_array_list = groups_field->GetObject(thread_group);
Sebastien Hertze49e1952014-10-13 11:27:13 +02002062 {
2063 // The "groups" field is declared as a java.util.List: check it really is
2064 // an instance of java.util.ArrayList.
2065 CHECK(groups_array_list != nullptr);
2066 mirror::Class* java_util_ArrayList_class =
2067 soa.Decode<mirror::Class*>(WellKnownClasses::java_util_ArrayList);
2068 CHECK(groups_array_list->InstanceOf(java_util_ArrayList_class));
2069 }
Sebastien Hertza06430c2014-09-15 19:21:30 +02002070
2071 // Get the array and size out of the ArrayList<ThreadGroup>...
Mathieu Chartierc7853442015-03-27 14:35:38 -07002072 ArtField* array_field = soa.DecodeField(WellKnownClasses::java_util_ArrayList_array);
2073 ArtField* size_field = soa.DecodeField(WellKnownClasses::java_util_ArrayList_size);
Sebastien Hertza06430c2014-09-15 19:21:30 +02002074 mirror::ObjectArray<mirror::Object>* groups_array =
2075 array_field->GetObject(groups_array_list)->AsObjectArray<mirror::Object>();
2076 const int32_t size = size_field->GetInt(groups_array_list);
2077
2078 // Copy the first 'size' elements out of the array into the result.
Sebastien Hertz6995c602014-09-09 12:10:13 +02002079 ObjectRegistry* registry = Dbg::GetObjectRegistry();
Sebastien Hertza06430c2014-09-15 19:21:30 +02002080 for (int32_t i = 0; i < size; ++i) {
Sebastien Hertz6995c602014-09-09 12:10:13 +02002081 child_thread_group_ids->push_back(registry->Add(groups_array->Get(i)));
Sebastien Hertza06430c2014-09-15 19:21:30 +02002082 }
2083}
2084
2085JDWP::JdwpError Dbg::GetThreadGroupChildren(JDWP::ObjectId thread_group_id,
2086 JDWP::ExpandBuf* pReply) {
2087 ScopedObjectAccessUnchecked soa(Thread::Current());
2088 JDWP::JdwpError error;
2089 mirror::Object* thread_group = DecodeThreadGroup(soa, thread_group_id, &error);
2090 if (error != JDWP::ERR_NONE) {
2091 return error;
2092 }
2093
2094 // Add child threads.
2095 {
2096 std::vector<JDWP::ObjectId> child_thread_ids;
2097 GetThreads(thread_group, &child_thread_ids);
2098 expandBufAdd4BE(pReply, child_thread_ids.size());
2099 for (JDWP::ObjectId child_thread_id : child_thread_ids) {
2100 expandBufAddObjectId(pReply, child_thread_id);
2101 }
2102 }
2103
2104 // Add child thread groups.
2105 {
2106 std::vector<JDWP::ObjectId> child_thread_groups_ids;
2107 GetChildThreadGroups(soa, thread_group, &child_thread_groups_ids);
2108 expandBufAdd4BE(pReply, child_thread_groups_ids.size());
2109 for (JDWP::ObjectId child_thread_group_id : child_thread_groups_ids) {
2110 expandBufAddObjectId(pReply, child_thread_group_id);
2111 }
2112 }
2113
2114 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002115}
2116
2117JDWP::ObjectId Dbg::GetSystemThreadGroupId() {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002118 ScopedObjectAccessUnchecked soa(Thread::Current());
Mathieu Chartierc7853442015-03-27 14:35:38 -07002119 ArtField* f = soa.DecodeField(WellKnownClasses::java_lang_ThreadGroup_systemThreadGroup);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002120 mirror::Object* group = f->GetObject(f->GetDeclaringClass());
Ian Rogers365c1022012-06-22 15:05:28 -07002121 return gRegistry->Add(group);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002122}
2123
Jeff Hao920af3e2013-08-28 15:46:38 -07002124JDWP::JdwpThreadStatus Dbg::ToJdwpThreadStatus(ThreadState state) {
2125 switch (state) {
2126 case kBlocked:
2127 return JDWP::TS_MONITOR;
2128 case kNative:
2129 case kRunnable:
2130 case kSuspended:
2131 return JDWP::TS_RUNNING;
2132 case kSleeping:
2133 return JDWP::TS_SLEEPING;
2134 case kStarting:
2135 case kTerminated:
2136 return JDWP::TS_ZOMBIE;
2137 case kTimedWaiting:
Sebastien Hertzbae182c2013-12-17 10:42:03 +01002138 case kWaitingForCheckPointsToRun:
Jeff Hao920af3e2013-08-28 15:46:38 -07002139 case kWaitingForDebuggerSend:
2140 case kWaitingForDebuggerSuspension:
2141 case kWaitingForDebuggerToAttach:
Sebastien Hertz138dbfc2013-12-04 18:15:25 +01002142 case kWaitingForDeoptimization:
Jeff Hao920af3e2013-08-28 15:46:38 -07002143 case kWaitingForGcToComplete:
Mathieu Chartierb43390c2015-05-12 10:47:11 -07002144 case kWaitingForGetObjectsAllocated:
Jeff Hao920af3e2013-08-28 15:46:38 -07002145 case kWaitingForJniOnLoad:
Sebastien Hertzbae182c2013-12-17 10:42:03 +01002146 case kWaitingForMethodTracingStart:
Jeff Hao920af3e2013-08-28 15:46:38 -07002147 case kWaitingForSignalCatcherOutput:
Hiroshi Yamauchi0c8c3032015-01-16 16:54:35 -08002148 case kWaitingForVisitObjects:
Jeff Hao920af3e2013-08-28 15:46:38 -07002149 case kWaitingInMainDebuggerLoop:
2150 case kWaitingInMainSignalCatcherLoop:
2151 case kWaitingPerformingGc:
2152 case kWaiting:
2153 return JDWP::TS_WAIT;
2154 // Don't add a 'default' here so the compiler can spot incompatible enum changes.
2155 }
2156 LOG(FATAL) << "Unknown thread state: " << state;
2157 return JDWP::TS_ZOMBIE;
2158}
2159
Sebastien Hertz52d131d2014-03-13 16:17:40 +01002160JDWP::JdwpError Dbg::GetThreadStatus(JDWP::ObjectId thread_id, JDWP::JdwpThreadStatus* pThreadStatus,
2161 JDWP::JdwpSuspendStatus* pSuspendStatus) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002162 ScopedObjectAccess soa(Thread::Current());
Elliott Hughes499c5132011-11-17 14:55:11 -08002163
Elliott Hughes9e0c1752013-01-09 14:02:58 -08002164 *pSuspendStatus = JDWP::SUSPEND_STATUS_NOT_SUSPENDED;
2165
Ian Rogersc0542af2014-09-03 16:16:56 -07002166 JDWP::JdwpError error;
2167 Thread* thread = DecodeThread(soa, thread_id, &error);
Elliott Hughes221229c2013-01-08 18:17:50 -08002168 if (error != JDWP::ERR_NONE) {
2169 if (error == JDWP::ERR_THREAD_NOT_ALIVE) {
2170 *pThreadStatus = JDWP::TS_ZOMBIE;
Elliott Hughes221229c2013-01-08 18:17:50 -08002171 return JDWP::ERR_NONE;
2172 }
2173 return error;
Elliott Hughes499c5132011-11-17 14:55:11 -08002174 }
2175
Elliott Hughes9e0c1752013-01-09 14:02:58 -08002176 if (IsSuspendedForDebugger(soa, thread)) {
2177 *pSuspendStatus = JDWP::SUSPEND_STATUS_SUSPENDED;
Elliott Hughes499c5132011-11-17 14:55:11 -08002178 }
2179
Jeff Hao920af3e2013-08-28 15:46:38 -07002180 *pThreadStatus = ToJdwpThreadStatus(thread->GetState());
Elliott Hughes221229c2013-01-08 18:17:50 -08002181 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002182}
2183
Elliott Hughes221229c2013-01-08 18:17:50 -08002184JDWP::JdwpError Dbg::GetThreadDebugSuspendCount(JDWP::ObjectId thread_id, JDWP::ExpandBuf* pReply) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002185 ScopedObjectAccess soa(Thread::Current());
Ian Rogersc0542af2014-09-03 16:16:56 -07002186 JDWP::JdwpError error;
2187 Thread* thread = DecodeThread(soa, thread_id, &error);
Elliott Hughes221229c2013-01-08 18:17:50 -08002188 if (error != JDWP::ERR_NONE) {
2189 return error;
Elliott Hughes2435a572012-02-17 16:07:41 -08002190 }
Ian Rogers50b35e22012-10-04 10:09:15 -07002191 MutexLock mu2(soa.Self(), *Locks::thread_suspend_count_lock_);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002192 expandBufAdd4BE(pReply, thread->GetDebugSuspendCount());
Elliott Hughes2435a572012-02-17 16:07:41 -08002193 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002194}
2195
Elliott Hughesf9501702013-01-11 11:22:27 -08002196JDWP::JdwpError Dbg::Interrupt(JDWP::ObjectId thread_id) {
2197 ScopedObjectAccess soa(Thread::Current());
Ian Rogersc0542af2014-09-03 16:16:56 -07002198 JDWP::JdwpError error;
2199 Thread* thread = DecodeThread(soa, thread_id, &error);
Elliott Hughesf9501702013-01-11 11:22:27 -08002200 if (error != JDWP::ERR_NONE) {
2201 return error;
2202 }
Ian Rogersdd7624d2014-03-14 17:43:00 -07002203 thread->Interrupt(soa.Self());
Elliott Hughesf9501702013-01-11 11:22:27 -08002204 return JDWP::ERR_NONE;
2205}
2206
Sebastien Hertz070f7322014-09-09 12:08:49 +02002207static bool IsInDesiredThreadGroup(ScopedObjectAccessUnchecked& soa,
2208 mirror::Object* desired_thread_group, mirror::Object* peer)
2209 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
2210 // Do we want threads from all thread groups?
2211 if (desired_thread_group == nullptr) {
2212 return true;
2213 }
Mathieu Chartierc7853442015-03-27 14:35:38 -07002214 ArtField* thread_group_field = soa.DecodeField(WellKnownClasses::java_lang_Thread_group);
Sebastien Hertz070f7322014-09-09 12:08:49 +02002215 DCHECK(thread_group_field != nullptr);
2216 mirror::Object* group = thread_group_field->GetObject(peer);
2217 return (group == desired_thread_group);
2218}
2219
Sebastien Hertza06430c2014-09-15 19:21:30 +02002220void Dbg::GetThreads(mirror::Object* thread_group, std::vector<JDWP::ObjectId>* thread_ids) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002221 ScopedObjectAccessUnchecked soa(Thread::Current());
Sebastien Hertz070f7322014-09-09 12:08:49 +02002222 std::list<Thread*> all_threads_list;
2223 {
2224 MutexLock mu(Thread::Current(), *Locks::thread_list_lock_);
2225 all_threads_list = Runtime::Current()->GetThreadList()->GetList();
2226 }
2227 for (Thread* t : all_threads_list) {
2228 if (t == Dbg::GetDebugThread()) {
2229 // Skip the JDWP thread. Some debuggers get bent out of shape when they can't suspend and
2230 // query all threads, so it's easier if we just don't tell them about this thread.
2231 continue;
2232 }
2233 if (t->IsStillStarting()) {
2234 // This thread is being started (and has been registered in the thread list). However, it is
2235 // not completely started yet so we must ignore it.
2236 continue;
2237 }
2238 mirror::Object* peer = t->GetPeer();
2239 if (peer == nullptr) {
Mathieu Chartier2cebb242015-04-21 16:50:40 -07002240 // 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 +02002241 // this thread yet.
2242 // TODO: if we identified threads to the debugger by their Thread*
2243 // rather than their peer's mirror::Object*, we could fix this.
2244 // Doing so might help us report ZOMBIE threads too.
2245 continue;
2246 }
2247 if (IsInDesiredThreadGroup(soa, thread_group, peer)) {
2248 thread_ids->push_back(gRegistry->Add(peer));
2249 }
2250 }
Elliott Hughescaf76542012-06-28 16:08:22 -07002251}
Elliott Hughesa2155262011-11-16 16:26:58 -08002252
Ian Rogersc0542af2014-09-03 16:16:56 -07002253static int GetStackDepth(Thread* thread) SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Ian Rogers0399dde2012-06-06 17:09:28 -07002254 struct CountStackDepthVisitor : public StackVisitor {
Andreas Gampe277ccbd2014-11-03 21:36:10 -08002255 explicit CountStackDepthVisitor(Thread* thread_in)
Nicolas Geoffray8e5bd182015-05-06 11:34:34 +01002256 : StackVisitor(thread_in, nullptr, StackVisitor::StackWalkKind::kIncludeInlinedFrames),
2257 depth(0) {}
Ian Rogers0399dde2012-06-06 17:09:28 -07002258
Elliott Hughes64f574f2013-02-20 14:57:12 -08002259 // TODO: Enable annotalysis. We know lock is held in constructor, but abstraction confuses
2260 // annotalysis.
2261 bool VisitFrame() NO_THREAD_SAFETY_ANALYSIS {
Ian Rogers0399dde2012-06-06 17:09:28 -07002262 if (!GetMethod()->IsRuntimeMethod()) {
Elliott Hughesf8a2df72011-12-01 12:19:54 -08002263 ++depth;
2264 }
Elliott Hughes530fa002012-03-12 11:44:49 -07002265 return true;
Elliott Hughesa2e54f62011-11-17 13:01:30 -08002266 }
2267 size_t depth;
2268 };
Elliott Hughes08fc03a2012-06-26 17:34:00 -07002269
Ian Rogers7a22fa62013-01-23 12:16:16 -08002270 CountStackDepthVisitor visitor(thread);
Ian Rogers0399dde2012-06-06 17:09:28 -07002271 visitor.WalkStack();
Elliott Hughesa2e54f62011-11-17 13:01:30 -08002272 return visitor.depth;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002273}
2274
Ian Rogersc0542af2014-09-03 16:16:56 -07002275JDWP::JdwpError Dbg::GetThreadFrameCount(JDWP::ObjectId thread_id, size_t* result) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002276 ScopedObjectAccess soa(Thread::Current());
Ian Rogersc0542af2014-09-03 16:16:56 -07002277 JDWP::JdwpError error;
2278 *result = 0;
2279 Thread* thread = DecodeThread(soa, thread_id, &error);
Elliott Hughes221229c2013-01-08 18:17:50 -08002280 if (error != JDWP::ERR_NONE) {
2281 return error;
2282 }
Elliott Hughesf15f4a02013-01-09 10:09:38 -08002283 if (!IsSuspendedForDebugger(soa, thread)) {
2284 return JDWP::ERR_THREAD_NOT_SUSPENDED;
2285 }
Ian Rogersc0542af2014-09-03 16:16:56 -07002286 *result = GetStackDepth(thread);
Elliott Hughes221229c2013-01-08 18:17:50 -08002287 return JDWP::ERR_NONE;
Elliott Hughes86964332012-02-15 19:37:42 -08002288}
2289
Ian Rogers306057f2012-11-26 12:45:53 -08002290JDWP::JdwpError Dbg::GetThreadFrames(JDWP::ObjectId thread_id, size_t start_frame,
2291 size_t frame_count, JDWP::ExpandBuf* buf) {
Elliott Hughes6e9d22c2012-06-22 15:02:37 -07002292 class GetFrameVisitor : public StackVisitor {
2293 public:
Andreas Gampe277ccbd2014-11-03 21:36:10 -08002294 GetFrameVisitor(Thread* thread, size_t start_frame_in, size_t frame_count_in,
2295 JDWP::ExpandBuf* buf_in)
Ian Rogersb726dcb2012-09-05 08:57:23 -07002296 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_)
Nicolas Geoffray8e5bd182015-05-06 11:34:34 +01002297 : StackVisitor(thread, nullptr, StackVisitor::StackWalkKind::kIncludeInlinedFrames),
2298 depth_(0),
2299 start_frame_(start_frame_in),
2300 frame_count_(frame_count_in),
2301 buf_(buf_in) {
Elliott Hughes6e9d22c2012-06-22 15:02:37 -07002302 expandBufAdd4BE(buf_, frame_count_);
Elliott Hughes03181a82011-11-17 17:22:21 -08002303 }
Ian Rogers0399dde2012-06-06 17:09:28 -07002304
Sebastien Hertz69206392015-04-07 15:54:25 +02002305 bool VisitFrame() OVERRIDE SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Ian Rogers0399dde2012-06-06 17:09:28 -07002306 if (GetMethod()->IsRuntimeMethod()) {
Brian Carlstrom7934ac22013-07-26 10:54:15 -07002307 return true; // The debugger can't do anything useful with a frame that has no Method*.
Elliott Hughes03181a82011-11-17 17:22:21 -08002308 }
Elliott Hughes6e9d22c2012-06-22 15:02:37 -07002309 if (depth_ >= start_frame_ + frame_count_) {
Elliott Hughes530fa002012-03-12 11:44:49 -07002310 return false;
Elliott Hughes03181a82011-11-17 17:22:21 -08002311 }
Elliott Hughes6e9d22c2012-06-22 15:02:37 -07002312 if (depth_ >= start_frame_) {
2313 JDWP::FrameId frame_id(GetFrameId());
2314 JDWP::JdwpLocation location;
Sebastien Hertz6995c602014-09-09 12:10:13 +02002315 SetJdwpLocation(&location, GetMethod(), GetDexPc());
Ian Rogersef7d42f2014-01-06 12:55:46 -08002316 VLOG(jdwp) << StringPrintf(" Frame %3zd: id=%3" PRIu64 " ", depth_, frame_id) << location;
Elliott Hughes6e9d22c2012-06-22 15:02:37 -07002317 expandBufAdd8BE(buf_, frame_id);
2318 expandBufAddLocation(buf_, location);
2319 }
2320 ++depth_;
Elliott Hughes530fa002012-03-12 11:44:49 -07002321 return true;
Elliott Hughes03181a82011-11-17 17:22:21 -08002322 }
Elliott Hughes6e9d22c2012-06-22 15:02:37 -07002323
2324 private:
2325 size_t depth_;
2326 const size_t start_frame_;
2327 const size_t frame_count_;
2328 JDWP::ExpandBuf* buf_;
Elliott Hughes03181a82011-11-17 17:22:21 -08002329 };
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002330
2331 ScopedObjectAccessUnchecked soa(Thread::Current());
Ian Rogersc0542af2014-09-03 16:16:56 -07002332 JDWP::JdwpError error;
2333 Thread* thread = DecodeThread(soa, thread_id, &error);
Elliott Hughes221229c2013-01-08 18:17:50 -08002334 if (error != JDWP::ERR_NONE) {
2335 return error;
2336 }
Elliott Hughesf15f4a02013-01-09 10:09:38 -08002337 if (!IsSuspendedForDebugger(soa, thread)) {
2338 return JDWP::ERR_THREAD_NOT_SUSPENDED;
2339 }
Ian Rogers7a22fa62013-01-23 12:16:16 -08002340 GetFrameVisitor visitor(thread, start_frame, frame_count, buf);
Ian Rogers0399dde2012-06-06 17:09:28 -07002341 visitor.WalkStack();
Elliott Hughes6e9d22c2012-06-22 15:02:37 -07002342 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002343}
2344
2345JDWP::ObjectId Dbg::GetThreadSelfId() {
Sebastien Hertz6995c602014-09-09 12:10:13 +02002346 return GetThreadId(Thread::Current());
2347}
2348
2349JDWP::ObjectId Dbg::GetThreadId(Thread* thread) {
Mathieu Chartierdbe6f462012-09-25 16:54:50 -07002350 ScopedObjectAccessUnchecked soa(Thread::Current());
Sebastien Hertz6995c602014-09-09 12:10:13 +02002351 return gRegistry->Add(thread->GetPeer());
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002352}
2353
Elliott Hughes475fc232011-10-25 15:00:35 -07002354void Dbg::SuspendVM() {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002355 Runtime::Current()->GetThreadList()->SuspendAllForDebugger();
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002356}
2357
2358void Dbg::ResumeVM() {
Sebastien Hertz253fa552014-10-14 17:27:15 +02002359 Runtime::Current()->GetThreadList()->ResumeAllForDebugger();
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002360}
2361
Elliott Hughes221229c2013-01-08 18:17:50 -08002362JDWP::JdwpError Dbg::SuspendThread(JDWP::ObjectId thread_id, bool request_suspension) {
Ian Rogersf3d874c2014-07-17 18:52:42 -07002363 Thread* self = Thread::Current();
Ian Rogersc0542af2014-09-03 16:16:56 -07002364 ScopedLocalRef<jobject> peer(self->GetJniEnv(), nullptr);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002365 {
Ian Rogersf3d874c2014-07-17 18:52:42 -07002366 ScopedObjectAccess soa(self);
Ian Rogersc0542af2014-09-03 16:16:56 -07002367 JDWP::JdwpError error;
2368 peer.reset(soa.AddLocalReference<jobject>(gRegistry->Get<mirror::Object*>(thread_id, &error)));
Elliott Hughes4e235312011-12-02 11:34:15 -08002369 }
Ian Rogersc0542af2014-09-03 16:16:56 -07002370 if (peer.get() == nullptr) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002371 return JDWP::ERR_THREAD_NOT_ALIVE;
2372 }
Ian Rogers4ad5cd32014-11-11 23:08:07 -08002373 // Suspend thread to build stack trace.
Elliott Hughesf327e072013-01-09 16:01:26 -08002374 bool timed_out;
Brian Carlstromba32de42014-08-27 23:43:46 -07002375 ThreadList* thread_list = Runtime::Current()->GetThreadList();
2376 Thread* thread = thread_list->SuspendThreadByPeer(peer.get(), request_suspension, true,
2377 &timed_out);
Ian Rogersc0542af2014-09-03 16:16:56 -07002378 if (thread != nullptr) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002379 return JDWP::ERR_NONE;
Elliott Hughesf327e072013-01-09 16:01:26 -08002380 } else if (timed_out) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002381 return JDWP::ERR_INTERNAL;
2382 } else {
2383 return JDWP::ERR_THREAD_NOT_ALIVE;
2384 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002385}
2386
Elliott Hughes221229c2013-01-08 18:17:50 -08002387void Dbg::ResumeThread(JDWP::ObjectId thread_id) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002388 ScopedObjectAccessUnchecked soa(Thread::Current());
Ian Rogersc0542af2014-09-03 16:16:56 -07002389 JDWP::JdwpError error;
2390 mirror::Object* peer = gRegistry->Get<mirror::Object*>(thread_id, &error);
2391 CHECK(peer != nullptr) << error;
jeffhaoa77f0f62012-12-05 17:19:31 -08002392 Thread* thread;
2393 {
2394 MutexLock mu(soa.Self(), *Locks::thread_list_lock_);
2395 thread = Thread::FromManagedThread(soa, peer);
2396 }
Ian Rogersc0542af2014-09-03 16:16:56 -07002397 if (thread == nullptr) {
Elliott Hughes4e235312011-12-02 11:34:15 -08002398 LOG(WARNING) << "No such thread for resume: " << peer;
2399 return;
2400 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002401 bool needs_resume;
2402 {
Ian Rogers50b35e22012-10-04 10:09:15 -07002403 MutexLock mu2(soa.Self(), *Locks::thread_suspend_count_lock_);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002404 needs_resume = thread->GetSuspendCount() > 0;
2405 }
2406 if (needs_resume) {
Elliott Hughes546b9862012-06-20 16:06:13 -07002407 Runtime::Current()->GetThreadList()->Resume(thread, true);
2408 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002409}
2410
2411void Dbg::SuspendSelf() {
Elliott Hughes475fc232011-10-25 15:00:35 -07002412 Runtime::Current()->GetThreadList()->SuspendSelfForDebugger();
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002413}
2414
Ian Rogers0399dde2012-06-06 17:09:28 -07002415struct GetThisVisitor : public StackVisitor {
Andreas Gampe277ccbd2014-11-03 21:36:10 -08002416 GetThisVisitor(Thread* thread, Context* context, JDWP::FrameId frame_id_in)
Ian Rogersb726dcb2012-09-05 08:57:23 -07002417 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_)
Nicolas Geoffray8e5bd182015-05-06 11:34:34 +01002418 : StackVisitor(thread, context, StackVisitor::StackWalkKind::kIncludeInlinedFrames),
2419 this_object(nullptr),
2420 frame_id(frame_id_in) {}
Ian Rogers0399dde2012-06-06 17:09:28 -07002421
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002422 // TODO: Enable annotalysis. We know lock is held in constructor, but abstraction confuses
2423 // annotalysis.
2424 virtual bool VisitFrame() NO_THREAD_SAFETY_ANALYSIS {
Elliott Hughes6e9d22c2012-06-22 15:02:37 -07002425 if (frame_id != GetFrameId()) {
Ian Rogers0399dde2012-06-06 17:09:28 -07002426 return true; // continue
Ian Rogers0399dde2012-06-06 17:09:28 -07002427 } else {
Ian Rogers62d6c772013-02-27 08:32:07 -08002428 this_object = GetThisObject();
2429 return false;
Ian Rogers0399dde2012-06-06 17:09:28 -07002430 }
Elliott Hughes86b00102011-12-05 17:54:26 -08002431 }
Ian Rogers0399dde2012-06-06 17:09:28 -07002432
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002433 mirror::Object* this_object;
Elliott Hughes6e9d22c2012-06-22 15:02:37 -07002434 JDWP::FrameId frame_id;
Ian Rogers0399dde2012-06-06 17:09:28 -07002435};
2436
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002437JDWP::JdwpError Dbg::GetThisObject(JDWP::ObjectId thread_id, JDWP::FrameId frame_id,
2438 JDWP::ObjectId* result) {
2439 ScopedObjectAccessUnchecked soa(Thread::Current());
Sebastien Hertz69206392015-04-07 15:54:25 +02002440 JDWP::JdwpError error;
2441 Thread* thread = DecodeThread(soa, thread_id, &error);
2442 if (error != JDWP::ERR_NONE) {
2443 return error;
2444 }
2445 if (!IsSuspendedForDebugger(soa, thread)) {
2446 return JDWP::ERR_THREAD_NOT_SUSPENDED;
Elliott Hughes6e9d22c2012-06-22 15:02:37 -07002447 }
Ian Rogers700a4022014-05-19 16:49:03 -07002448 std::unique_ptr<Context> context(Context::Create());
Ian Rogers7a22fa62013-01-23 12:16:16 -08002449 GetThisVisitor visitor(thread, context.get(), frame_id);
Ian Rogers0399dde2012-06-06 17:09:28 -07002450 visitor.WalkStack();
Elliott Hughes6e9d22c2012-06-22 15:02:37 -07002451 *result = gRegistry->Add(visitor.this_object);
2452 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002453}
2454
Sebastien Hertz8009f392014-09-01 17:07:11 +02002455// Walks the stack until we find the frame with the given FrameId.
2456class FindFrameVisitor FINAL : public StackVisitor {
2457 public:
2458 FindFrameVisitor(Thread* thread, Context* context, JDWP::FrameId frame_id)
2459 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_)
Nicolas Geoffray8e5bd182015-05-06 11:34:34 +01002460 : StackVisitor(thread, context, StackVisitor::StackWalkKind::kIncludeInlinedFrames),
2461 frame_id_(frame_id),
2462 error_(JDWP::ERR_INVALID_FRAMEID) {}
Ian Rogersca190662012-06-26 15:45:57 -07002463
Sebastien Hertz8009f392014-09-01 17:07:11 +02002464 // TODO: Enable annotalysis. We know lock is held in constructor, but abstraction confuses
2465 // annotalysis.
2466 bool VisitFrame() NO_THREAD_SAFETY_ANALYSIS {
2467 if (GetFrameId() != frame_id_) {
2468 return true; // Not our frame, carry on.
Ian Rogers0399dde2012-06-06 17:09:28 -07002469 }
Mathieu Chartiere401d142015-04-22 13:56:20 -07002470 ArtMethod* m = GetMethod();
Sebastien Hertz8009f392014-09-01 17:07:11 +02002471 if (m->IsNative()) {
2472 // We can't read/write local value from/into native method.
2473 error_ = JDWP::ERR_OPAQUE_FRAME;
2474 } else {
2475 // We found our frame.
2476 error_ = JDWP::ERR_NONE;
2477 }
2478 return false;
2479 }
2480
2481 JDWP::JdwpError GetError() const {
2482 return error_;
2483 }
2484
2485 private:
2486 const JDWP::FrameId frame_id_;
2487 JDWP::JdwpError error_;
2488};
2489
2490JDWP::JdwpError Dbg::GetLocalValues(JDWP::Request* request, JDWP::ExpandBuf* pReply) {
2491 JDWP::ObjectId thread_id = request->ReadThreadId();
2492 JDWP::FrameId frame_id = request->ReadFrameId();
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002493
2494 ScopedObjectAccessUnchecked soa(Thread::Current());
Sebastien Hertz69206392015-04-07 15:54:25 +02002495 JDWP::JdwpError error;
2496 Thread* thread = DecodeThread(soa, thread_id, &error);
2497 if (error != JDWP::ERR_NONE) {
2498 return error;
2499 }
2500 if (!IsSuspendedForDebugger(soa, thread)) {
2501 return JDWP::ERR_THREAD_NOT_SUSPENDED;
Elliott Hughes221229c2013-01-08 18:17:50 -08002502 }
Sebastien Hertz8009f392014-09-01 17:07:11 +02002503 // Find the frame with the given frame_id.
Ian Rogers700a4022014-05-19 16:49:03 -07002504 std::unique_ptr<Context> context(Context::Create());
Sebastien Hertz8009f392014-09-01 17:07:11 +02002505 FindFrameVisitor visitor(thread, context.get(), frame_id);
Ian Rogers0399dde2012-06-06 17:09:28 -07002506 visitor.WalkStack();
Sebastien Hertz8009f392014-09-01 17:07:11 +02002507 if (visitor.GetError() != JDWP::ERR_NONE) {
2508 return visitor.GetError();
2509 }
2510
2511 // Read the values from visitor's context.
2512 int32_t slot_count = request->ReadSigned32("slot count");
2513 expandBufAdd4BE(pReply, slot_count); /* "int values" */
2514 for (int32_t i = 0; i < slot_count; ++i) {
2515 uint32_t slot = request->ReadUnsigned32("slot");
2516 JDWP::JdwpTag reqSigByte = request->ReadTag();
2517
2518 VLOG(jdwp) << " --> slot " << slot << " " << reqSigByte;
2519
2520 size_t width = Dbg::GetTagWidth(reqSigByte);
Sebastien Hertz7d955652014-10-22 10:57:10 +02002521 uint8_t* ptr = expandBufAddSpace(pReply, width + 1);
Sebastien Hertz69206392015-04-07 15:54:25 +02002522 error = Dbg::GetLocalValue(visitor, soa, slot, reqSigByte, ptr, width);
Sebastien Hertz8009f392014-09-01 17:07:11 +02002523 if (error != JDWP::ERR_NONE) {
2524 return error;
2525 }
2526 }
2527 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002528}
2529
Sebastien Hertzabbabc82015-03-26 08:47:47 +01002530constexpr JDWP::JdwpError kStackFrameLocalAccessError = JDWP::ERR_ABSENT_INFORMATION;
2531
2532static std::string GetStackContextAsString(const StackVisitor& visitor)
2533 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
2534 return StringPrintf(" at DEX pc 0x%08x in method %s", visitor.GetDexPc(false),
2535 PrettyMethod(visitor.GetMethod()).c_str());
2536}
2537
2538static JDWP::JdwpError FailGetLocalValue(const StackVisitor& visitor, uint16_t vreg,
2539 JDWP::JdwpTag tag)
2540 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
2541 LOG(ERROR) << "Failed to read " << tag << " local from register v" << vreg
2542 << GetStackContextAsString(visitor);
2543 return kStackFrameLocalAccessError;
2544}
2545
Sebastien Hertz8009f392014-09-01 17:07:11 +02002546JDWP::JdwpError Dbg::GetLocalValue(const StackVisitor& visitor, ScopedObjectAccessUnchecked& soa,
2547 int slot, JDWP::JdwpTag tag, uint8_t* buf, size_t width) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07002548 ArtMethod* m = visitor.GetMethod();
Sebastien Hertzabbabc82015-03-26 08:47:47 +01002549 JDWP::JdwpError error = JDWP::ERR_NONE;
2550 uint16_t vreg = DemangleSlot(slot, m, &error);
2551 if (error != JDWP::ERR_NONE) {
2552 return error;
2553 }
Sebastien Hertz8009f392014-09-01 17:07:11 +02002554 // TODO: check that the tag is compatible with the actual type of the slot!
Sebastien Hertz8009f392014-09-01 17:07:11 +02002555 switch (tag) {
2556 case JDWP::JT_BOOLEAN: {
2557 CHECK_EQ(width, 1U);
2558 uint32_t intVal;
Sebastien Hertzabbabc82015-03-26 08:47:47 +01002559 if (!visitor.GetVReg(m, vreg, kIntVReg, &intVal)) {
2560 return FailGetLocalValue(visitor, vreg, tag);
Ian Rogers0399dde2012-06-06 17:09:28 -07002561 }
Sebastien Hertzabbabc82015-03-26 08:47:47 +01002562 VLOG(jdwp) << "get boolean local " << vreg << " = " << intVal;
2563 JDWP::Set1(buf + 1, intVal != 0);
Sebastien Hertz8009f392014-09-01 17:07:11 +02002564 break;
Ian Rogers0399dde2012-06-06 17:09:28 -07002565 }
Sebastien Hertz8009f392014-09-01 17:07:11 +02002566 case JDWP::JT_BYTE: {
2567 CHECK_EQ(width, 1U);
2568 uint32_t intVal;
Sebastien Hertzabbabc82015-03-26 08:47:47 +01002569 if (!visitor.GetVReg(m, vreg, kIntVReg, &intVal)) {
2570 return FailGetLocalValue(visitor, vreg, tag);
Sebastien Hertz8009f392014-09-01 17:07:11 +02002571 }
Sebastien Hertzabbabc82015-03-26 08:47:47 +01002572 VLOG(jdwp) << "get byte local " << vreg << " = " << intVal;
2573 JDWP::Set1(buf + 1, intVal);
Sebastien Hertz8009f392014-09-01 17:07:11 +02002574 break;
2575 }
2576 case JDWP::JT_SHORT:
2577 case JDWP::JT_CHAR: {
2578 CHECK_EQ(width, 2U);
2579 uint32_t intVal;
Sebastien Hertzabbabc82015-03-26 08:47:47 +01002580 if (!visitor.GetVReg(m, vreg, kIntVReg, &intVal)) {
2581 return FailGetLocalValue(visitor, vreg, tag);
Sebastien Hertz8009f392014-09-01 17:07:11 +02002582 }
Sebastien Hertzabbabc82015-03-26 08:47:47 +01002583 VLOG(jdwp) << "get short/char local " << vreg << " = " << intVal;
2584 JDWP::Set2BE(buf + 1, intVal);
Sebastien Hertz8009f392014-09-01 17:07:11 +02002585 break;
2586 }
2587 case JDWP::JT_INT: {
2588 CHECK_EQ(width, 4U);
2589 uint32_t intVal;
Sebastien Hertzabbabc82015-03-26 08:47:47 +01002590 if (!visitor.GetVReg(m, vreg, kIntVReg, &intVal)) {
2591 return FailGetLocalValue(visitor, vreg, tag);
Sebastien Hertz8009f392014-09-01 17:07:11 +02002592 }
Sebastien Hertzabbabc82015-03-26 08:47:47 +01002593 VLOG(jdwp) << "get int local " << vreg << " = " << intVal;
2594 JDWP::Set4BE(buf + 1, intVal);
Sebastien Hertz8009f392014-09-01 17:07:11 +02002595 break;
2596 }
2597 case JDWP::JT_FLOAT: {
2598 CHECK_EQ(width, 4U);
2599 uint32_t intVal;
Sebastien Hertzabbabc82015-03-26 08:47:47 +01002600 if (!visitor.GetVReg(m, vreg, kFloatVReg, &intVal)) {
2601 return FailGetLocalValue(visitor, vreg, tag);
Sebastien Hertz8009f392014-09-01 17:07:11 +02002602 }
Sebastien Hertzabbabc82015-03-26 08:47:47 +01002603 VLOG(jdwp) << "get float local " << vreg << " = " << intVal;
2604 JDWP::Set4BE(buf + 1, intVal);
Sebastien Hertz8009f392014-09-01 17:07:11 +02002605 break;
2606 }
2607 case JDWP::JT_ARRAY:
2608 case JDWP::JT_CLASS_LOADER:
2609 case JDWP::JT_CLASS_OBJECT:
2610 case JDWP::JT_OBJECT:
2611 case JDWP::JT_STRING:
2612 case JDWP::JT_THREAD:
2613 case JDWP::JT_THREAD_GROUP: {
2614 CHECK_EQ(width, sizeof(JDWP::ObjectId));
2615 uint32_t intVal;
Sebastien Hertzabbabc82015-03-26 08:47:47 +01002616 if (!visitor.GetVReg(m, vreg, kReferenceVReg, &intVal)) {
2617 return FailGetLocalValue(visitor, vreg, tag);
Sebastien Hertz8009f392014-09-01 17:07:11 +02002618 }
Sebastien Hertzabbabc82015-03-26 08:47:47 +01002619 mirror::Object* o = reinterpret_cast<mirror::Object*>(intVal);
2620 VLOG(jdwp) << "get " << tag << " object local " << vreg << " = " << o;
2621 if (!Runtime::Current()->GetHeap()->IsValidObjectAddress(o)) {
2622 LOG(FATAL) << StringPrintf("Found invalid object %#" PRIxPTR " in register v%u",
2623 reinterpret_cast<uintptr_t>(o), vreg)
2624 << GetStackContextAsString(visitor);
2625 UNREACHABLE();
2626 }
2627 tag = TagFromObject(soa, o);
2628 JDWP::SetObjectId(buf + 1, gRegistry->Add(o));
Sebastien Hertz8009f392014-09-01 17:07:11 +02002629 break;
2630 }
2631 case JDWP::JT_DOUBLE: {
2632 CHECK_EQ(width, 8U);
2633 uint64_t longVal;
Sebastien Hertzabbabc82015-03-26 08:47:47 +01002634 if (!visitor.GetVRegPair(m, vreg, kDoubleLoVReg, kDoubleHiVReg, &longVal)) {
2635 return FailGetLocalValue(visitor, vreg, tag);
Sebastien Hertz8009f392014-09-01 17:07:11 +02002636 }
Sebastien Hertzabbabc82015-03-26 08:47:47 +01002637 VLOG(jdwp) << "get double local " << vreg << " = " << longVal;
2638 JDWP::Set8BE(buf + 1, longVal);
Sebastien Hertz8009f392014-09-01 17:07:11 +02002639 break;
2640 }
2641 case JDWP::JT_LONG: {
2642 CHECK_EQ(width, 8U);
2643 uint64_t longVal;
Sebastien Hertzabbabc82015-03-26 08:47:47 +01002644 if (!visitor.GetVRegPair(m, vreg, kLongLoVReg, kLongHiVReg, &longVal)) {
2645 return FailGetLocalValue(visitor, vreg, tag);
Sebastien Hertz8009f392014-09-01 17:07:11 +02002646 }
Sebastien Hertzabbabc82015-03-26 08:47:47 +01002647 VLOG(jdwp) << "get long local " << vreg << " = " << longVal;
2648 JDWP::Set8BE(buf + 1, longVal);
Sebastien Hertz8009f392014-09-01 17:07:11 +02002649 break;
2650 }
2651 default:
2652 LOG(FATAL) << "Unknown tag " << tag;
Sebastien Hertzabbabc82015-03-26 08:47:47 +01002653 UNREACHABLE();
Sebastien Hertz8009f392014-09-01 17:07:11 +02002654 }
Ian Rogers0399dde2012-06-06 17:09:28 -07002655
Sebastien Hertz8009f392014-09-01 17:07:11 +02002656 // Prepend tag, which may have been updated.
2657 JDWP::Set1(buf, tag);
2658 return JDWP::ERR_NONE;
2659}
2660
2661JDWP::JdwpError Dbg::SetLocalValues(JDWP::Request* request) {
2662 JDWP::ObjectId thread_id = request->ReadThreadId();
2663 JDWP::FrameId frame_id = request->ReadFrameId();
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002664
2665 ScopedObjectAccessUnchecked soa(Thread::Current());
Sebastien Hertz69206392015-04-07 15:54:25 +02002666 JDWP::JdwpError error;
2667 Thread* thread = DecodeThread(soa, thread_id, &error);
2668 if (error != JDWP::ERR_NONE) {
2669 return error;
2670 }
2671 if (!IsSuspendedForDebugger(soa, thread)) {
2672 return JDWP::ERR_THREAD_NOT_SUSPENDED;
Elliott Hughes221229c2013-01-08 18:17:50 -08002673 }
Sebastien Hertz8009f392014-09-01 17:07:11 +02002674 // Find the frame with the given frame_id.
Ian Rogers700a4022014-05-19 16:49:03 -07002675 std::unique_ptr<Context> context(Context::Create());
Sebastien Hertz8009f392014-09-01 17:07:11 +02002676 FindFrameVisitor visitor(thread, context.get(), frame_id);
Ian Rogers0399dde2012-06-06 17:09:28 -07002677 visitor.WalkStack();
Sebastien Hertz8009f392014-09-01 17:07:11 +02002678 if (visitor.GetError() != JDWP::ERR_NONE) {
2679 return visitor.GetError();
2680 }
2681
2682 // Writes the values into visitor's context.
2683 int32_t slot_count = request->ReadSigned32("slot count");
2684 for (int32_t i = 0; i < slot_count; ++i) {
2685 uint32_t slot = request->ReadUnsigned32("slot");
2686 JDWP::JdwpTag sigByte = request->ReadTag();
2687 size_t width = Dbg::GetTagWidth(sigByte);
2688 uint64_t value = request->ReadValue(width);
2689
2690 VLOG(jdwp) << " --> slot " << slot << " " << sigByte << " " << value;
Sebastien Hertz69206392015-04-07 15:54:25 +02002691 error = Dbg::SetLocalValue(visitor, slot, sigByte, value, width);
Sebastien Hertz8009f392014-09-01 17:07:11 +02002692 if (error != JDWP::ERR_NONE) {
2693 return error;
2694 }
2695 }
2696 return JDWP::ERR_NONE;
2697}
2698
Sebastien Hertzabbabc82015-03-26 08:47:47 +01002699template<typename T>
2700static JDWP::JdwpError FailSetLocalValue(const StackVisitor& visitor, uint16_t vreg,
2701 JDWP::JdwpTag tag, T value)
2702 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
2703 LOG(ERROR) << "Failed to write " << tag << " local " << value
2704 << " (0x" << std::hex << value << ") into register v" << vreg
2705 << GetStackContextAsString(visitor);
2706 return kStackFrameLocalAccessError;
2707}
2708
Sebastien Hertz8009f392014-09-01 17:07:11 +02002709JDWP::JdwpError Dbg::SetLocalValue(StackVisitor& visitor, int slot, JDWP::JdwpTag tag,
2710 uint64_t value, size_t width) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07002711 ArtMethod* m = visitor.GetMethod();
Sebastien Hertzabbabc82015-03-26 08:47:47 +01002712 JDWP::JdwpError error = JDWP::ERR_NONE;
2713 uint16_t vreg = DemangleSlot(slot, m, &error);
2714 if (error != JDWP::ERR_NONE) {
2715 return error;
2716 }
Sebastien Hertz8009f392014-09-01 17:07:11 +02002717 // TODO: check that the tag is compatible with the actual type of the slot!
Sebastien Hertz8009f392014-09-01 17:07:11 +02002718 switch (tag) {
2719 case JDWP::JT_BOOLEAN:
2720 case JDWP::JT_BYTE:
2721 CHECK_EQ(width, 1U);
Sebastien Hertzabbabc82015-03-26 08:47:47 +01002722 if (!visitor.SetVReg(m, vreg, static_cast<uint32_t>(value), kIntVReg)) {
2723 return FailSetLocalValue(visitor, vreg, tag, static_cast<uint32_t>(value));
Sebastien Hertz8009f392014-09-01 17:07:11 +02002724 }
2725 break;
2726 case JDWP::JT_SHORT:
2727 case JDWP::JT_CHAR:
2728 CHECK_EQ(width, 2U);
Sebastien Hertzabbabc82015-03-26 08:47:47 +01002729 if (!visitor.SetVReg(m, vreg, static_cast<uint32_t>(value), kIntVReg)) {
2730 return FailSetLocalValue(visitor, vreg, tag, static_cast<uint32_t>(value));
Sebastien Hertz8009f392014-09-01 17:07:11 +02002731 }
2732 break;
2733 case JDWP::JT_INT:
2734 CHECK_EQ(width, 4U);
Sebastien Hertzabbabc82015-03-26 08:47:47 +01002735 if (!visitor.SetVReg(m, vreg, static_cast<uint32_t>(value), kIntVReg)) {
2736 return FailSetLocalValue(visitor, vreg, tag, static_cast<uint32_t>(value));
Sebastien Hertz8009f392014-09-01 17:07:11 +02002737 }
2738 break;
2739 case JDWP::JT_FLOAT:
2740 CHECK_EQ(width, 4U);
Sebastien Hertzabbabc82015-03-26 08:47:47 +01002741 if (!visitor.SetVReg(m, vreg, static_cast<uint32_t>(value), kFloatVReg)) {
2742 return FailSetLocalValue(visitor, vreg, tag, static_cast<uint32_t>(value));
Sebastien Hertz8009f392014-09-01 17:07:11 +02002743 }
2744 break;
2745 case JDWP::JT_ARRAY:
2746 case JDWP::JT_CLASS_LOADER:
2747 case JDWP::JT_CLASS_OBJECT:
2748 case JDWP::JT_OBJECT:
2749 case JDWP::JT_STRING:
2750 case JDWP::JT_THREAD:
2751 case JDWP::JT_THREAD_GROUP: {
2752 CHECK_EQ(width, sizeof(JDWP::ObjectId));
Sebastien Hertz8009f392014-09-01 17:07:11 +02002753 mirror::Object* o = gRegistry->Get<mirror::Object*>(static_cast<JDWP::ObjectId>(value),
2754 &error);
2755 if (error != JDWP::ERR_NONE) {
2756 VLOG(jdwp) << tag << " object " << o << " is an invalid object";
2757 return JDWP::ERR_INVALID_OBJECT;
Sebastien Hertzabbabc82015-03-26 08:47:47 +01002758 }
2759 if (!visitor.SetVReg(m, vreg, static_cast<uint32_t>(reinterpret_cast<uintptr_t>(o)),
2760 kReferenceVReg)) {
2761 return FailSetLocalValue(visitor, vreg, tag, reinterpret_cast<uintptr_t>(o));
Sebastien Hertz8009f392014-09-01 17:07:11 +02002762 }
2763 break;
2764 }
2765 case JDWP::JT_DOUBLE: {
2766 CHECK_EQ(width, 8U);
Sebastien Hertzabbabc82015-03-26 08:47:47 +01002767 if (!visitor.SetVRegPair(m, vreg, value, kDoubleLoVReg, kDoubleHiVReg)) {
2768 return FailSetLocalValue(visitor, vreg, tag, value);
Sebastien Hertz8009f392014-09-01 17:07:11 +02002769 }
2770 break;
2771 }
2772 case JDWP::JT_LONG: {
2773 CHECK_EQ(width, 8U);
Sebastien Hertzabbabc82015-03-26 08:47:47 +01002774 if (!visitor.SetVRegPair(m, vreg, value, kLongLoVReg, kLongHiVReg)) {
2775 return FailSetLocalValue(visitor, vreg, tag, value);
Sebastien Hertz8009f392014-09-01 17:07:11 +02002776 }
2777 break;
2778 }
2779 default:
2780 LOG(FATAL) << "Unknown tag " << tag;
Sebastien Hertzabbabc82015-03-26 08:47:47 +01002781 UNREACHABLE();
Sebastien Hertz8009f392014-09-01 17:07:11 +02002782 }
2783 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002784}
2785
Mathieu Chartiere401d142015-04-22 13:56:20 -07002786static void SetEventLocation(JDWP::EventLocation* location, ArtMethod* m, uint32_t dex_pc)
Sebastien Hertz6995c602014-09-09 12:10:13 +02002787 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
2788 DCHECK(location != nullptr);
2789 if (m == nullptr) {
2790 memset(location, 0, sizeof(*location));
2791 } else {
2792 location->method = m;
2793 location->dex_pc = (m->IsNative() || m->IsProxyMethod()) ? static_cast<uint32_t>(-1) : dex_pc;
Sebastien Hertz3f52eaf2014-04-04 17:50:18 +02002794 }
Sebastien Hertz3f52eaf2014-04-04 17:50:18 +02002795}
2796
Mathieu Chartiere401d142015-04-22 13:56:20 -07002797void Dbg::PostLocationEvent(ArtMethod* m, int dex_pc, mirror::Object* this_object,
Jeff Hao579b0242013-11-18 13:16:49 -08002798 int event_flags, const JValue* return_value) {
Sebastien Hertz3f52eaf2014-04-04 17:50:18 +02002799 if (!IsDebuggerActive()) {
2800 return;
2801 }
2802 DCHECK(m != nullptr);
2803 DCHECK_EQ(m->IsStatic(), this_object == nullptr);
Sebastien Hertz6995c602014-09-09 12:10:13 +02002804 JDWP::EventLocation location;
2805 SetEventLocation(&location, m, dex_pc);
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08002806
Sebastien Hertzde48aa62015-05-26 11:53:39 +02002807 // We need to be sure no exception is pending when calling JdwpState::PostLocationEvent.
2808 // This is required to be able to call JNI functions to create JDWP ids. To achieve this,
2809 // we temporarily clear the current thread's exception (if any) and will restore it after
2810 // the call.
2811 // Note: the only way to get a pending exception here is to suspend on a move-exception
2812 // instruction.
2813 Thread* const self = Thread::Current();
2814 StackHandleScope<1> hs(self);
2815 Handle<mirror::Throwable> pending_exception(hs.NewHandle(self->GetException()));
2816 self->ClearException();
2817 if (kIsDebugBuild && pending_exception.Get() != nullptr) {
2818 const DexFile::CodeItem* code_item = location.method->GetCodeItem();
2819 const Instruction* instr = Instruction::At(&code_item->insns_[location.dex_pc]);
2820 CHECK_EQ(Instruction::MOVE_EXCEPTION, instr->Opcode());
2821 }
2822
Sebastien Hertz6995c602014-09-09 12:10:13 +02002823 gJdwpState->PostLocationEvent(&location, this_object, event_flags, return_value);
Sebastien Hertzde48aa62015-05-26 11:53:39 +02002824
2825 if (pending_exception.Get() != nullptr) {
2826 self->SetException(pending_exception.Get());
2827 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002828}
2829
Mathieu Chartiere401d142015-04-22 13:56:20 -07002830void Dbg::PostFieldAccessEvent(ArtMethod* m, int dex_pc,
Mathieu Chartierc7853442015-03-27 14:35:38 -07002831 mirror::Object* this_object, ArtField* f) {
Sebastien Hertz3f52eaf2014-04-04 17:50:18 +02002832 if (!IsDebuggerActive()) {
2833 return;
2834 }
2835 DCHECK(m != nullptr);
2836 DCHECK(f != nullptr);
Sebastien Hertz6995c602014-09-09 12:10:13 +02002837 JDWP::EventLocation location;
2838 SetEventLocation(&location, m, dex_pc);
Sebastien Hertz3f52eaf2014-04-04 17:50:18 +02002839
Sebastien Hertz6995c602014-09-09 12:10:13 +02002840 gJdwpState->PostFieldEvent(&location, f, this_object, nullptr, false);
Sebastien Hertz3f52eaf2014-04-04 17:50:18 +02002841}
2842
Mathieu Chartiere401d142015-04-22 13:56:20 -07002843void Dbg::PostFieldModificationEvent(ArtMethod* m, int dex_pc,
Mathieu Chartierc7853442015-03-27 14:35:38 -07002844 mirror::Object* this_object, ArtField* f,
Sebastien Hertz3f52eaf2014-04-04 17:50:18 +02002845 const JValue* field_value) {
2846 if (!IsDebuggerActive()) {
2847 return;
2848 }
2849 DCHECK(m != nullptr);
2850 DCHECK(f != nullptr);
2851 DCHECK(field_value != nullptr);
Sebastien Hertz6995c602014-09-09 12:10:13 +02002852 JDWP::EventLocation location;
2853 SetEventLocation(&location, m, dex_pc);
Sebastien Hertz3f52eaf2014-04-04 17:50:18 +02002854
Sebastien Hertz6995c602014-09-09 12:10:13 +02002855 gJdwpState->PostFieldEvent(&location, f, this_object, field_value, true);
Sebastien Hertz3f52eaf2014-04-04 17:50:18 +02002856}
2857
Nicolas Geoffray14691c52015-03-05 10:40:17 +00002858/**
2859 * Finds the location where this exception will be caught. We search until we reach the top
2860 * frame, in which case this exception is considered uncaught.
2861 */
2862class CatchLocationFinder : public StackVisitor {
2863 public:
2864 CatchLocationFinder(Thread* self, const Handle<mirror::Throwable>& exception, Context* context)
2865 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_)
Nicolas Geoffray8e5bd182015-05-06 11:34:34 +01002866 : StackVisitor(self, context, StackVisitor::StackWalkKind::kIncludeInlinedFrames),
Nicolas Geoffray14691c52015-03-05 10:40:17 +00002867 self_(self),
2868 exception_(exception),
2869 handle_scope_(self),
2870 this_at_throw_(handle_scope_.NewHandle<mirror::Object>(nullptr)),
Mathieu Chartiere401d142015-04-22 13:56:20 -07002871 catch_method_(nullptr),
2872 throw_method_(nullptr),
Nicolas Geoffray14691c52015-03-05 10:40:17 +00002873 catch_dex_pc_(DexFile::kDexNoIndex),
2874 throw_dex_pc_(DexFile::kDexNoIndex) {
2875 }
2876
2877 bool VisitFrame() OVERRIDE SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07002878 ArtMethod* method = GetMethod();
Nicolas Geoffray14691c52015-03-05 10:40:17 +00002879 DCHECK(method != nullptr);
2880 if (method->IsRuntimeMethod()) {
2881 // Ignore callee save method.
2882 DCHECK(method->IsCalleeSaveMethod());
2883 return true;
2884 }
2885
2886 uint32_t dex_pc = GetDexPc();
Mathieu Chartiere401d142015-04-22 13:56:20 -07002887 if (throw_method_ == nullptr) {
Nicolas Geoffray14691c52015-03-05 10:40:17 +00002888 // First Java method found. It is either the method that threw the exception,
2889 // or the Java native method that is reporting an exception thrown by
2890 // native code.
2891 this_at_throw_.Assign(GetThisObject());
Mathieu Chartiere401d142015-04-22 13:56:20 -07002892 throw_method_ = method;
Nicolas Geoffray14691c52015-03-05 10:40:17 +00002893 throw_dex_pc_ = dex_pc;
2894 }
2895
2896 if (dex_pc != DexFile::kDexNoIndex) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07002897 StackHandleScope<1> hs(self_);
Nicolas Geoffray14691c52015-03-05 10:40:17 +00002898 uint32_t found_dex_pc;
2899 Handle<mirror::Class> exception_class(hs.NewHandle(exception_->GetClass()));
Nicolas Geoffray14691c52015-03-05 10:40:17 +00002900 bool unused_clear_exception;
Mathieu Chartiere401d142015-04-22 13:56:20 -07002901 found_dex_pc = method->FindCatchBlock(exception_class, dex_pc, &unused_clear_exception);
Nicolas Geoffray14691c52015-03-05 10:40:17 +00002902 if (found_dex_pc != DexFile::kDexNoIndex) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07002903 catch_method_ = method;
Nicolas Geoffray14691c52015-03-05 10:40:17 +00002904 catch_dex_pc_ = found_dex_pc;
2905 return false; // End stack walk.
2906 }
2907 }
2908 return true; // Continue stack walk.
2909 }
2910
Mathieu Chartiere401d142015-04-22 13:56:20 -07002911 ArtMethod* GetCatchMethod() SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
2912 return catch_method_;
Nicolas Geoffray14691c52015-03-05 10:40:17 +00002913 }
2914
Mathieu Chartiere401d142015-04-22 13:56:20 -07002915 ArtMethod* GetThrowMethod() SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
2916 return throw_method_;
Nicolas Geoffray14691c52015-03-05 10:40:17 +00002917 }
2918
2919 mirror::Object* GetThisAtThrow() SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
2920 return this_at_throw_.Get();
2921 }
2922
2923 uint32_t GetCatchDexPc() const {
2924 return catch_dex_pc_;
2925 }
2926
2927 uint32_t GetThrowDexPc() const {
2928 return throw_dex_pc_;
2929 }
2930
2931 private:
2932 Thread* const self_;
2933 const Handle<mirror::Throwable>& exception_;
Mathieu Chartiere401d142015-04-22 13:56:20 -07002934 StackHandleScope<1> handle_scope_;
Nicolas Geoffray14691c52015-03-05 10:40:17 +00002935 MutableHandle<mirror::Object> this_at_throw_;
Mathieu Chartiere401d142015-04-22 13:56:20 -07002936 ArtMethod* catch_method_;
2937 ArtMethod* throw_method_;
Nicolas Geoffray14691c52015-03-05 10:40:17 +00002938 uint32_t catch_dex_pc_;
2939 uint32_t throw_dex_pc_;
2940
2941 DISALLOW_COPY_AND_ASSIGN(CatchLocationFinder);
2942};
2943
2944void Dbg::PostException(mirror::Throwable* exception_object) {
Elliott Hughesc0f09332012-03-26 13:27:06 -07002945 if (!IsDebuggerActive()) {
Ian Rogers0ad5bb82011-12-07 10:16:32 -08002946 return;
2947 }
Sebastien Hertz261bc042015-04-08 09:36:07 +02002948 Thread* const self = Thread::Current();
2949 StackHandleScope<1> handle_scope(self);
Nicolas Geoffray14691c52015-03-05 10:40:17 +00002950 Handle<mirror::Throwable> h_exception(handle_scope.NewHandle(exception_object));
2951 std::unique_ptr<Context> context(Context::Create());
Sebastien Hertz261bc042015-04-08 09:36:07 +02002952 CatchLocationFinder clf(self, h_exception, context.get());
Nicolas Geoffray14691c52015-03-05 10:40:17 +00002953 clf.WalkStack(/* include_transitions */ false);
Sebastien Hertz6995c602014-09-09 12:10:13 +02002954 JDWP::EventLocation exception_throw_location;
Nicolas Geoffray14691c52015-03-05 10:40:17 +00002955 SetEventLocation(&exception_throw_location, clf.GetThrowMethod(), clf.GetThrowDexPc());
Sebastien Hertz6995c602014-09-09 12:10:13 +02002956 JDWP::EventLocation exception_catch_location;
Nicolas Geoffray14691c52015-03-05 10:40:17 +00002957 SetEventLocation(&exception_catch_location, clf.GetCatchMethod(), clf.GetCatchDexPc());
Elliott Hughes4740cdf2011-12-07 14:07:12 -08002958
Nicolas Geoffray14691c52015-03-05 10:40:17 +00002959 gJdwpState->PostException(&exception_throw_location, h_exception.Get(), &exception_catch_location,
2960 clf.GetThisAtThrow());
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002961}
2962
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002963void Dbg::PostClassPrepare(mirror::Class* c) {
Elliott Hughesc0f09332012-03-26 13:27:06 -07002964 if (!IsDebuggerActive()) {
Elliott Hughes4740cdf2011-12-07 14:07:12 -08002965 return;
2966 }
Sebastien Hertz6995c602014-09-09 12:10:13 +02002967 gJdwpState->PostClassPrepare(c);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002968}
2969
Ian Rogers62d6c772013-02-27 08:32:07 -08002970void Dbg::UpdateDebugger(Thread* thread, mirror::Object* this_object,
Mathieu Chartiere401d142015-04-22 13:56:20 -07002971 ArtMethod* m, uint32_t dex_pc,
Sebastien Hertz8379b222014-02-24 17:38:15 +01002972 int event_flags, const JValue* return_value) {
Ian Rogers62d6c772013-02-27 08:32:07 -08002973 if (!IsDebuggerActive() || dex_pc == static_cast<uint32_t>(-2) /* fake method exit */) {
Elliott Hughes2aa2e392012-02-17 17:15:43 -08002974 return;
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08002975 }
2976
Elliott Hughes86964332012-02-15 19:37:42 -08002977 if (IsBreakpoint(m, dex_pc)) {
2978 event_flags |= kBreakpoint;
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08002979 }
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08002980
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01002981 // If the debugger is single-stepping one of our threads, check to
2982 // see if we're that thread and we've reached a step point.
2983 const SingleStepControl* single_step_control = thread->GetSingleStepControl();
Sebastien Hertz597c4f02015-01-26 17:37:14 +01002984 if (single_step_control != nullptr) {
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01002985 CHECK(!m->IsNative());
Sebastien Hertz597c4f02015-01-26 17:37:14 +01002986 if (single_step_control->GetStepDepth() == JDWP::SD_INTO) {
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01002987 // Step into method calls. We break when the line number
2988 // or method pointer changes. If we're in SS_MIN mode, we
2989 // always stop.
Sebastien Hertz597c4f02015-01-26 17:37:14 +01002990 if (single_step_control->GetMethod() != m) {
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01002991 event_flags |= kSingleStep;
2992 VLOG(jdwp) << "SS new method";
Sebastien Hertz597c4f02015-01-26 17:37:14 +01002993 } else if (single_step_control->GetStepSize() == JDWP::SS_MIN) {
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01002994 event_flags |= kSingleStep;
2995 VLOG(jdwp) << "SS new instruction";
Sebastien Hertzbb43b432014-04-14 11:59:08 +02002996 } else if (single_step_control->ContainsDexPc(dex_pc)) {
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01002997 event_flags |= kSingleStep;
2998 VLOG(jdwp) << "SS new line";
2999 }
Sebastien Hertz597c4f02015-01-26 17:37:14 +01003000 } else if (single_step_control->GetStepDepth() == JDWP::SD_OVER) {
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01003001 // Step over method calls. We break when the line number is
3002 // different and the frame depth is <= the original frame
3003 // depth. (We can't just compare on the method, because we
3004 // might get unrolled past it by an exception, and it's tricky
3005 // to identify recursion.)
3006
3007 int stack_depth = GetStackDepth(thread);
3008
Sebastien Hertz597c4f02015-01-26 17:37:14 +01003009 if (stack_depth < single_step_control->GetStackDepth()) {
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01003010 // Popped up one or more frames, always trigger.
3011 event_flags |= kSingleStep;
3012 VLOG(jdwp) << "SS method pop";
Sebastien Hertz597c4f02015-01-26 17:37:14 +01003013 } else if (stack_depth == single_step_control->GetStackDepth()) {
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01003014 // Same depth, see if we moved.
Sebastien Hertz597c4f02015-01-26 17:37:14 +01003015 if (single_step_control->GetStepSize() == JDWP::SS_MIN) {
Elliott Hughes86964332012-02-15 19:37:42 -08003016 event_flags |= kSingleStep;
3017 VLOG(jdwp) << "SS new instruction";
Sebastien Hertzbb43b432014-04-14 11:59:08 +02003018 } else if (single_step_control->ContainsDexPc(dex_pc)) {
Elliott Hughes2435a572012-02-17 16:07:41 -08003019 event_flags |= kSingleStep;
3020 VLOG(jdwp) << "SS new line";
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08003021 }
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01003022 }
3023 } else {
Sebastien Hertz597c4f02015-01-26 17:37:14 +01003024 CHECK_EQ(single_step_control->GetStepDepth(), JDWP::SD_OUT);
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01003025 // Return from the current method. We break when the frame
3026 // depth pops up.
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08003027
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01003028 // This differs from the "method exit" break in that it stops
3029 // with the PC at the next instruction in the returned-to
3030 // function, rather than the end of the returning function.
Elliott Hughes86964332012-02-15 19:37:42 -08003031
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01003032 int stack_depth = GetStackDepth(thread);
Sebastien Hertz597c4f02015-01-26 17:37:14 +01003033 if (stack_depth < single_step_control->GetStackDepth()) {
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01003034 event_flags |= kSingleStep;
3035 VLOG(jdwp) << "SS method pop";
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08003036 }
3037 }
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08003038 }
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08003039
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08003040 // If there's something interesting going on, see if it matches one
3041 // of the debugger filters.
3042 if (event_flags != 0) {
Sebastien Hertz8379b222014-02-24 17:38:15 +01003043 Dbg::PostLocationEvent(m, dex_pc, this_object, event_flags, return_value);
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08003044 }
3045}
3046
Sebastien Hertz42cd43f2014-05-13 14:15:41 +02003047size_t* Dbg::GetReferenceCounterForEvent(uint32_t instrumentation_event) {
3048 switch (instrumentation_event) {
3049 case instrumentation::Instrumentation::kMethodEntered:
3050 return &method_enter_event_ref_count_;
3051 case instrumentation::Instrumentation::kMethodExited:
3052 return &method_exit_event_ref_count_;
3053 case instrumentation::Instrumentation::kDexPcMoved:
3054 return &dex_pc_change_event_ref_count_;
3055 case instrumentation::Instrumentation::kFieldRead:
3056 return &field_read_event_ref_count_;
3057 case instrumentation::Instrumentation::kFieldWritten:
3058 return &field_write_event_ref_count_;
3059 case instrumentation::Instrumentation::kExceptionCaught:
3060 return &exception_catch_event_ref_count_;
3061 default:
3062 return nullptr;
3063 }
3064}
3065
Sebastien Hertz4d25df32014-03-21 17:44:46 +01003066// Process request while all mutator threads are suspended.
3067void Dbg::ProcessDeoptimizationRequest(const DeoptimizationRequest& request) {
Sebastien Hertz138dbfc2013-12-04 18:15:25 +01003068 instrumentation::Instrumentation* instrumentation = Runtime::Current()->GetInstrumentation();
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003069 switch (request.GetKind()) {
Sebastien Hertz4d25df32014-03-21 17:44:46 +01003070 case DeoptimizationRequest::kNothing:
3071 LOG(WARNING) << "Ignoring empty deoptimization request.";
3072 break;
Sebastien Hertz42cd43f2014-05-13 14:15:41 +02003073 case DeoptimizationRequest::kRegisterForEvent:
3074 VLOG(jdwp) << StringPrintf("Add debugger as listener for instrumentation event 0x%x",
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003075 request.InstrumentationEvent());
3076 instrumentation->AddListener(&gDebugInstrumentationListener, request.InstrumentationEvent());
3077 instrumentation_events_ |= request.InstrumentationEvent();
Sebastien Hertz42cd43f2014-05-13 14:15:41 +02003078 break;
3079 case DeoptimizationRequest::kUnregisterForEvent:
3080 VLOG(jdwp) << StringPrintf("Remove debugger as listener for instrumentation event 0x%x",
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003081 request.InstrumentationEvent());
Sebastien Hertz42cd43f2014-05-13 14:15:41 +02003082 instrumentation->RemoveListener(&gDebugInstrumentationListener,
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003083 request.InstrumentationEvent());
3084 instrumentation_events_ &= ~request.InstrumentationEvent();
Sebastien Hertz42cd43f2014-05-13 14:15:41 +02003085 break;
Sebastien Hertz4d25df32014-03-21 17:44:46 +01003086 case DeoptimizationRequest::kFullDeoptimization:
Sebastien Hertz7ec2f1c2014-03-27 20:06:47 +01003087 VLOG(jdwp) << "Deoptimize the world ...";
Sebastien Hertz0462c4c2015-04-01 16:34:17 +02003088 instrumentation->DeoptimizeEverything(kDbgInstrumentationKey);
Sebastien Hertz7ec2f1c2014-03-27 20:06:47 +01003089 VLOG(jdwp) << "Deoptimize the world DONE";
Sebastien Hertz4d25df32014-03-21 17:44:46 +01003090 break;
3091 case DeoptimizationRequest::kFullUndeoptimization:
Sebastien Hertz7ec2f1c2014-03-27 20:06:47 +01003092 VLOG(jdwp) << "Undeoptimize the world ...";
Sebastien Hertz0462c4c2015-04-01 16:34:17 +02003093 instrumentation->UndeoptimizeEverything(kDbgInstrumentationKey);
Sebastien Hertz7ec2f1c2014-03-27 20:06:47 +01003094 VLOG(jdwp) << "Undeoptimize the world DONE";
Sebastien Hertz4d25df32014-03-21 17:44:46 +01003095 break;
3096 case DeoptimizationRequest::kSelectiveDeoptimization:
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003097 VLOG(jdwp) << "Deoptimize method " << PrettyMethod(request.Method()) << " ...";
3098 instrumentation->Deoptimize(request.Method());
3099 VLOG(jdwp) << "Deoptimize method " << PrettyMethod(request.Method()) << " DONE";
Sebastien Hertz4d25df32014-03-21 17:44:46 +01003100 break;
3101 case DeoptimizationRequest::kSelectiveUndeoptimization:
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003102 VLOG(jdwp) << "Undeoptimize method " << PrettyMethod(request.Method()) << " ...";
3103 instrumentation->Undeoptimize(request.Method());
3104 VLOG(jdwp) << "Undeoptimize method " << PrettyMethod(request.Method()) << " DONE";
Sebastien Hertz4d25df32014-03-21 17:44:46 +01003105 break;
3106 default:
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003107 LOG(FATAL) << "Unsupported deoptimization request kind " << request.GetKind();
Sebastien Hertz4d25df32014-03-21 17:44:46 +01003108 break;
Sebastien Hertz138dbfc2013-12-04 18:15:25 +01003109 }
Sebastien Hertz138dbfc2013-12-04 18:15:25 +01003110}
3111
Sebastien Hertz4d25df32014-03-21 17:44:46 +01003112void Dbg::RequestDeoptimization(const DeoptimizationRequest& req) {
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003113 if (req.GetKind() == DeoptimizationRequest::kNothing) {
Sebastien Hertz4d25df32014-03-21 17:44:46 +01003114 // Nothing to do.
3115 return;
3116 }
Brian Carlstrom306db812014-09-05 13:01:41 -07003117 MutexLock mu(Thread::Current(), *Locks::deoptimization_lock_);
Sebastien Hertz7ec2f1c2014-03-27 20:06:47 +01003118 RequestDeoptimizationLocked(req);
3119}
3120
3121void Dbg::RequestDeoptimizationLocked(const DeoptimizationRequest& req) {
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003122 switch (req.GetKind()) {
Sebastien Hertz42cd43f2014-05-13 14:15:41 +02003123 case DeoptimizationRequest::kRegisterForEvent: {
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003124 DCHECK_NE(req.InstrumentationEvent(), 0u);
3125 size_t* counter = GetReferenceCounterForEvent(req.InstrumentationEvent());
Sebastien Hertz42cd43f2014-05-13 14:15:41 +02003126 CHECK(counter != nullptr) << StringPrintf("No counter for instrumentation event 0x%x",
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003127 req.InstrumentationEvent());
Sebastien Hertz42cd43f2014-05-13 14:15:41 +02003128 if (*counter == 0) {
Sebastien Hertz7d2ae432014-05-15 11:26:34 +02003129 VLOG(jdwp) << StringPrintf("Queue request #%zd to start listening to instrumentation event 0x%x",
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003130 deoptimization_requests_.size(), req.InstrumentationEvent());
Sebastien Hertz42cd43f2014-05-13 14:15:41 +02003131 deoptimization_requests_.push_back(req);
3132 }
3133 *counter = *counter + 1;
3134 break;
3135 }
3136 case DeoptimizationRequest::kUnregisterForEvent: {
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003137 DCHECK_NE(req.InstrumentationEvent(), 0u);
3138 size_t* counter = GetReferenceCounterForEvent(req.InstrumentationEvent());
Sebastien Hertz42cd43f2014-05-13 14:15:41 +02003139 CHECK(counter != nullptr) << StringPrintf("No counter for instrumentation event 0x%x",
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003140 req.InstrumentationEvent());
Sebastien Hertz42cd43f2014-05-13 14:15:41 +02003141 *counter = *counter - 1;
3142 if (*counter == 0) {
Sebastien Hertz7d2ae432014-05-15 11:26:34 +02003143 VLOG(jdwp) << StringPrintf("Queue request #%zd to stop listening to instrumentation event 0x%x",
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003144 deoptimization_requests_.size(), req.InstrumentationEvent());
Sebastien Hertz42cd43f2014-05-13 14:15:41 +02003145 deoptimization_requests_.push_back(req);
3146 }
3147 break;
3148 }
Sebastien Hertz4d25df32014-03-21 17:44:46 +01003149 case DeoptimizationRequest::kFullDeoptimization: {
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003150 DCHECK(req.Method() == nullptr);
Sebastien Hertz4d25df32014-03-21 17:44:46 +01003151 if (full_deoptimization_event_count_ == 0) {
Sebastien Hertz7ec2f1c2014-03-27 20:06:47 +01003152 VLOG(jdwp) << "Queue request #" << deoptimization_requests_.size()
3153 << " for full deoptimization";
Sebastien Hertz4d25df32014-03-21 17:44:46 +01003154 deoptimization_requests_.push_back(req);
3155 }
3156 ++full_deoptimization_event_count_;
3157 break;
3158 }
3159 case DeoptimizationRequest::kFullUndeoptimization: {
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003160 DCHECK(req.Method() == nullptr);
Sebastien Hertze713d932014-05-15 10:48:53 +02003161 DCHECK_GT(full_deoptimization_event_count_, 0U);
Sebastien Hertz4d25df32014-03-21 17:44:46 +01003162 --full_deoptimization_event_count_;
3163 if (full_deoptimization_event_count_ == 0) {
Sebastien Hertz7ec2f1c2014-03-27 20:06:47 +01003164 VLOG(jdwp) << "Queue request #" << deoptimization_requests_.size()
3165 << " for full undeoptimization";
Sebastien Hertz4d25df32014-03-21 17:44:46 +01003166 deoptimization_requests_.push_back(req);
3167 }
3168 break;
3169 }
3170 case DeoptimizationRequest::kSelectiveDeoptimization: {
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003171 DCHECK(req.Method() != nullptr);
Sebastien Hertz7ec2f1c2014-03-27 20:06:47 +01003172 VLOG(jdwp) << "Queue request #" << deoptimization_requests_.size()
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003173 << " for deoptimization of " << PrettyMethod(req.Method());
Sebastien Hertz4d25df32014-03-21 17:44:46 +01003174 deoptimization_requests_.push_back(req);
3175 break;
3176 }
3177 case DeoptimizationRequest::kSelectiveUndeoptimization: {
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003178 DCHECK(req.Method() != nullptr);
Sebastien Hertz7ec2f1c2014-03-27 20:06:47 +01003179 VLOG(jdwp) << "Queue request #" << deoptimization_requests_.size()
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003180 << " for undeoptimization of " << PrettyMethod(req.Method());
Sebastien Hertz4d25df32014-03-21 17:44:46 +01003181 deoptimization_requests_.push_back(req);
3182 break;
3183 }
3184 default: {
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003185 LOG(FATAL) << "Unknown deoptimization request kind " << req.GetKind();
Sebastien Hertz4d25df32014-03-21 17:44:46 +01003186 break;
3187 }
3188 }
3189}
3190
Sebastien Hertz138dbfc2013-12-04 18:15:25 +01003191void Dbg::ManageDeoptimization() {
3192 Thread* const self = Thread::Current();
3193 {
3194 // Avoid suspend/resume if there is no pending request.
Brian Carlstrom306db812014-09-05 13:01:41 -07003195 MutexLock mu(self, *Locks::deoptimization_lock_);
Sebastien Hertz4d25df32014-03-21 17:44:46 +01003196 if (deoptimization_requests_.empty()) {
Sebastien Hertz138dbfc2013-12-04 18:15:25 +01003197 return;
3198 }
3199 }
3200 CHECK_EQ(self->GetState(), kRunnable);
3201 self->TransitionFromRunnableToSuspended(kWaitingForDeoptimization);
3202 // We need to suspend mutator threads first.
3203 Runtime* const runtime = Runtime::Current();
Mathieu Chartierbf9fc582015-03-13 17:21:25 -07003204 runtime->GetThreadList()->SuspendAll(__FUNCTION__);
Sebastien Hertz138dbfc2013-12-04 18:15:25 +01003205 const ThreadState old_state = self->SetStateUnsafe(kRunnable);
Sebastien Hertz4d25df32014-03-21 17:44:46 +01003206 {
Brian Carlstrom306db812014-09-05 13:01:41 -07003207 MutexLock mu(self, *Locks::deoptimization_lock_);
Sebastien Hertz7ec2f1c2014-03-27 20:06:47 +01003208 size_t req_index = 0;
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003209 for (DeoptimizationRequest& request : deoptimization_requests_) {
Sebastien Hertz7ec2f1c2014-03-27 20:06:47 +01003210 VLOG(jdwp) << "Process deoptimization request #" << req_index++;
Sebastien Hertz4d25df32014-03-21 17:44:46 +01003211 ProcessDeoptimizationRequest(request);
3212 }
3213 deoptimization_requests_.clear();
3214 }
Sebastien Hertz138dbfc2013-12-04 18:15:25 +01003215 CHECK_EQ(self->SetStateUnsafe(old_state), kRunnable);
3216 runtime->GetThreadList()->ResumeAll();
3217 self->TransitionFromSuspendedToRunnable();
3218}
3219
Mathieu Chartiere401d142015-04-22 13:56:20 -07003220static bool IsMethodPossiblyInlined(Thread* self, ArtMethod* m)
Sebastien Hertza76a6d42014-03-20 16:40:17 +01003221 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07003222 const DexFile::CodeItem* code_item = m->GetCodeItem();
Sebastien Hertza76a6d42014-03-20 16:40:17 +01003223 if (code_item == nullptr) {
3224 // TODO We should not be asked to watch location in a native or abstract method so the code item
3225 // should never be null. We could just check we never encounter this case.
3226 return false;
Sebastien Hertz138dbfc2013-12-04 18:15:25 +01003227 }
Sebastien Hertz4d1e9ab2014-09-18 16:03:34 +02003228 // Note: method verifier may cause thread suspension.
3229 self->AssertThreadSuspensionIsAllowable();
Mathieu Chartiere401d142015-04-22 13:56:20 -07003230 StackHandleScope<2> hs(self);
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07003231 mirror::Class* declaring_class = m->GetDeclaringClass();
3232 Handle<mirror::DexCache> dex_cache(hs.NewHandle(declaring_class->GetDexCache()));
3233 Handle<mirror::ClassLoader> class_loader(hs.NewHandle(declaring_class->GetClassLoader()));
Ian Rogers7b078e82014-09-10 14:44:24 -07003234 verifier::MethodVerifier verifier(self, dex_cache->GetDexFile(), dex_cache, class_loader,
Mathieu Chartiere401d142015-04-22 13:56:20 -07003235 &m->GetClassDef(), code_item, m->GetDexMethodIndex(), m,
Mathieu Chartier4306ef82014-12-19 18:41:47 -08003236 m->GetAccessFlags(), false, true, false, true);
Sebastien Hertza76a6d42014-03-20 16:40:17 +01003237 // Note: we don't need to verify the method.
3238 return InlineMethodAnalyser::AnalyseMethodCode(&verifier, nullptr);
3239}
Sebastien Hertz138dbfc2013-12-04 18:15:25 +01003240
Mathieu Chartiere401d142015-04-22 13:56:20 -07003241static const Breakpoint* FindFirstBreakpointForMethod(ArtMethod* m)
Sebastien Hertzed2be172014-08-19 15:33:43 +02003242 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_, Locks::breakpoint_lock_) {
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003243 for (Breakpoint& breakpoint : gBreakpoints) {
3244 if (breakpoint.Method() == m) {
Sebastien Hertza76a6d42014-03-20 16:40:17 +01003245 return &breakpoint;
3246 }
3247 }
3248 return nullptr;
3249}
3250
Mathieu Chartiere401d142015-04-22 13:56:20 -07003251bool Dbg::MethodHasAnyBreakpoints(ArtMethod* method) {
Mathieu Chartierd8565452015-03-26 09:41:50 -07003252 ReaderMutexLock mu(Thread::Current(), *Locks::breakpoint_lock_);
3253 return FindFirstBreakpointForMethod(method) != nullptr;
3254}
3255
Sebastien Hertza76a6d42014-03-20 16:40:17 +01003256// Sanity checks all existing breakpoints on the same method.
Mathieu Chartiere401d142015-04-22 13:56:20 -07003257static void SanityCheckExistingBreakpoints(ArtMethod* m,
Sebastien Hertzf3928792014-11-17 19:00:37 +01003258 DeoptimizationRequest::Kind deoptimization_kind)
Sebastien Hertzed2be172014-08-19 15:33:43 +02003259 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_, Locks::breakpoint_lock_) {
Sebastien Hertz4d1e9ab2014-09-18 16:03:34 +02003260 for (const Breakpoint& breakpoint : gBreakpoints) {
Sebastien Hertzf3928792014-11-17 19:00:37 +01003261 if (breakpoint.Method() == m) {
3262 CHECK_EQ(deoptimization_kind, breakpoint.GetDeoptimizationKind());
3263 }
Sebastien Hertz4d1e9ab2014-09-18 16:03:34 +02003264 }
Sebastien Hertzf3928792014-11-17 19:00:37 +01003265 instrumentation::Instrumentation* instrumentation = Runtime::Current()->GetInstrumentation();
3266 if (deoptimization_kind == DeoptimizationRequest::kFullDeoptimization) {
Sebastien Hertz4d1e9ab2014-09-18 16:03:34 +02003267 // We should have deoptimized everything but not "selectively" deoptimized this method.
Sebastien Hertzf3928792014-11-17 19:00:37 +01003268 CHECK(instrumentation->AreAllMethodsDeoptimized());
3269 CHECK(!instrumentation->IsDeoptimized(m));
3270 } else if (deoptimization_kind == DeoptimizationRequest::kSelectiveDeoptimization) {
Sebastien Hertz4d1e9ab2014-09-18 16:03:34 +02003271 // We should have "selectively" deoptimized this method.
3272 // Note: while we have not deoptimized everything for this method, we may have done it for
3273 // another event.
Sebastien Hertzf3928792014-11-17 19:00:37 +01003274 CHECK(instrumentation->IsDeoptimized(m));
3275 } else {
3276 // This method does not require deoptimization.
3277 CHECK_EQ(deoptimization_kind, DeoptimizationRequest::kNothing);
3278 CHECK(!instrumentation->IsDeoptimized(m));
3279 }
3280}
3281
Sebastien Hertzabe93e02014-12-17 16:35:50 +01003282// Returns the deoptimization kind required to set a breakpoint in a method.
3283// If a breakpoint has already been set, we also return the first breakpoint
3284// through the given 'existing_brkpt' pointer.
Sebastien Hertzf3928792014-11-17 19:00:37 +01003285static DeoptimizationRequest::Kind GetRequiredDeoptimizationKind(Thread* self,
Mathieu Chartiere401d142015-04-22 13:56:20 -07003286 ArtMethod* m,
Sebastien Hertzabe93e02014-12-17 16:35:50 +01003287 const Breakpoint** existing_brkpt)
Sebastien Hertzf3928792014-11-17 19:00:37 +01003288 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
3289 if (!Dbg::RequiresDeoptimization()) {
3290 // We already run in interpreter-only mode so we don't need to deoptimize anything.
3291 VLOG(jdwp) << "No need for deoptimization when fully running with interpreter for method "
3292 << PrettyMethod(m);
3293 return DeoptimizationRequest::kNothing;
3294 }
Sebastien Hertzabe93e02014-12-17 16:35:50 +01003295 const Breakpoint* first_breakpoint;
Sebastien Hertzf3928792014-11-17 19:00:37 +01003296 {
3297 ReaderMutexLock mu(self, *Locks::breakpoint_lock_);
Sebastien Hertzabe93e02014-12-17 16:35:50 +01003298 first_breakpoint = FindFirstBreakpointForMethod(m);
3299 *existing_brkpt = first_breakpoint;
Sebastien Hertzf3928792014-11-17 19:00:37 +01003300 }
Sebastien Hertzabe93e02014-12-17 16:35:50 +01003301
3302 if (first_breakpoint == nullptr) {
Sebastien Hertzf3928792014-11-17 19:00:37 +01003303 // There is no breakpoint on this method yet: we need to deoptimize. If this method may be
3304 // inlined, we deoptimize everything; otherwise we deoptimize only this method.
3305 // Note: IsMethodPossiblyInlined goes into the method verifier and may cause thread suspension.
3306 // Therefore we must not hold any lock when we call it.
3307 bool need_full_deoptimization = IsMethodPossiblyInlined(self, m);
3308 if (need_full_deoptimization) {
3309 VLOG(jdwp) << "Need full deoptimization because of possible inlining of method "
3310 << PrettyMethod(m);
3311 return DeoptimizationRequest::kFullDeoptimization;
3312 } else {
3313 // We don't need to deoptimize if the method has not been compiled.
3314 ClassLinker* const class_linker = Runtime::Current()->GetClassLinker();
3315 const bool is_compiled = class_linker->GetOatMethodQuickCodeFor(m) != nullptr;
3316 if (is_compiled) {
Sebastien Hertz6963e442014-11-26 22:11:27 +01003317 // If the method may be called through its direct code pointer (without loading
3318 // its updated entrypoint), we need full deoptimization to not miss the breakpoint.
3319 if (class_linker->MayBeCalledWithDirectCodePointer(m)) {
3320 VLOG(jdwp) << "Need full deoptimization because of possible direct code call "
3321 << "into image for compiled method " << PrettyMethod(m);
3322 return DeoptimizationRequest::kFullDeoptimization;
3323 } else {
3324 VLOG(jdwp) << "Need selective deoptimization for compiled method " << PrettyMethod(m);
3325 return DeoptimizationRequest::kSelectiveDeoptimization;
3326 }
Sebastien Hertzf3928792014-11-17 19:00:37 +01003327 } else {
3328 // Method is not compiled: we don't need to deoptimize.
3329 VLOG(jdwp) << "No need for deoptimization for non-compiled method " << PrettyMethod(m);
3330 return DeoptimizationRequest::kNothing;
3331 }
3332 }
3333 } else {
3334 // There is at least one breakpoint for this method: we don't need to deoptimize.
3335 // Let's check that all breakpoints are configured the same way for deoptimization.
3336 VLOG(jdwp) << "Breakpoint already set: no deoptimization is required";
Sebastien Hertzabe93e02014-12-17 16:35:50 +01003337 DeoptimizationRequest::Kind deoptimization_kind = first_breakpoint->GetDeoptimizationKind();
Sebastien Hertzf3928792014-11-17 19:00:37 +01003338 if (kIsDebugBuild) {
3339 ReaderMutexLock mu(self, *Locks::breakpoint_lock_);
3340 SanityCheckExistingBreakpoints(m, deoptimization_kind);
3341 }
3342 return DeoptimizationRequest::kNothing;
Sebastien Hertz138dbfc2013-12-04 18:15:25 +01003343 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -07003344}
3345
Sebastien Hertza76a6d42014-03-20 16:40:17 +01003346// Installs a breakpoint at the specified location. Also indicates through the deoptimization
3347// request if we need to deoptimize.
3348void Dbg::WatchLocation(const JDWP::JdwpLocation* location, DeoptimizationRequest* req) {
3349 Thread* const self = Thread::Current();
Mathieu Chartiere401d142015-04-22 13:56:20 -07003350 ArtMethod* m = FromMethodId(location->method_id);
Sebastien Hertza76a6d42014-03-20 16:40:17 +01003351 DCHECK(m != nullptr) << "No method for method id " << location->method_id;
Sebastien Hertz138dbfc2013-12-04 18:15:25 +01003352
Sebastien Hertzabe93e02014-12-17 16:35:50 +01003353 const Breakpoint* existing_breakpoint = nullptr;
3354 const DeoptimizationRequest::Kind deoptimization_kind =
3355 GetRequiredDeoptimizationKind(self, m, &existing_breakpoint);
Sebastien Hertzf3928792014-11-17 19:00:37 +01003356 req->SetKind(deoptimization_kind);
3357 if (deoptimization_kind == DeoptimizationRequest::kSelectiveDeoptimization) {
3358 req->SetMethod(m);
Sebastien Hertza76a6d42014-03-20 16:40:17 +01003359 } else {
Sebastien Hertzf3928792014-11-17 19:00:37 +01003360 CHECK(deoptimization_kind == DeoptimizationRequest::kNothing ||
3361 deoptimization_kind == DeoptimizationRequest::kFullDeoptimization);
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003362 req->SetMethod(nullptr);
Sebastien Hertz138dbfc2013-12-04 18:15:25 +01003363 }
3364
Sebastien Hertz4d1e9ab2014-09-18 16:03:34 +02003365 {
3366 WriterMutexLock mu(self, *Locks::breakpoint_lock_);
Sebastien Hertzabe93e02014-12-17 16:35:50 +01003367 // If there is at least one existing breakpoint on the same method, the new breakpoint
3368 // must have the same deoptimization kind than the existing breakpoint(s).
3369 DeoptimizationRequest::Kind breakpoint_deoptimization_kind;
3370 if (existing_breakpoint != nullptr) {
3371 breakpoint_deoptimization_kind = existing_breakpoint->GetDeoptimizationKind();
3372 } else {
3373 breakpoint_deoptimization_kind = deoptimization_kind;
3374 }
3375 gBreakpoints.push_back(Breakpoint(m, location->dex_pc, breakpoint_deoptimization_kind));
Sebastien Hertz4d1e9ab2014-09-18 16:03:34 +02003376 VLOG(jdwp) << "Set breakpoint #" << (gBreakpoints.size() - 1) << ": "
3377 << gBreakpoints[gBreakpoints.size() - 1];
3378 }
Sebastien Hertza76a6d42014-03-20 16:40:17 +01003379}
3380
3381// Uninstalls a breakpoint at the specified location. Also indicates through the deoptimization
3382// request if we need to undeoptimize.
3383void Dbg::UnwatchLocation(const JDWP::JdwpLocation* location, DeoptimizationRequest* req) {
Sebastien Hertzed2be172014-08-19 15:33:43 +02003384 WriterMutexLock mu(Thread::Current(), *Locks::breakpoint_lock_);
Mathieu Chartiere401d142015-04-22 13:56:20 -07003385 ArtMethod* m = FromMethodId(location->method_id);
Sebastien Hertza76a6d42014-03-20 16:40:17 +01003386 DCHECK(m != nullptr) << "No method for method id " << location->method_id;
Sebastien Hertzf3928792014-11-17 19:00:37 +01003387 DeoptimizationRequest::Kind deoptimization_kind = DeoptimizationRequest::kNothing;
Sebastien Hertza76a6d42014-03-20 16:40:17 +01003388 for (size_t i = 0, e = gBreakpoints.size(); i < e; ++i) {
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003389 if (gBreakpoints[i].DexPc() == location->dex_pc && gBreakpoints[i].Method() == m) {
Sebastien Hertza76a6d42014-03-20 16:40:17 +01003390 VLOG(jdwp) << "Removed breakpoint #" << i << ": " << gBreakpoints[i];
Sebastien Hertzf3928792014-11-17 19:00:37 +01003391 deoptimization_kind = gBreakpoints[i].GetDeoptimizationKind();
3392 DCHECK_EQ(deoptimization_kind == DeoptimizationRequest::kSelectiveDeoptimization,
3393 Runtime::Current()->GetInstrumentation()->IsDeoptimized(m));
Sebastien Hertza76a6d42014-03-20 16:40:17 +01003394 gBreakpoints.erase(gBreakpoints.begin() + i);
3395 break;
3396 }
3397 }
3398 const Breakpoint* const existing_breakpoint = FindFirstBreakpointForMethod(m);
3399 if (existing_breakpoint == nullptr) {
3400 // There is no more breakpoint on this method: we need to undeoptimize.
Sebastien Hertzf3928792014-11-17 19:00:37 +01003401 if (deoptimization_kind == DeoptimizationRequest::kFullDeoptimization) {
Sebastien Hertza76a6d42014-03-20 16:40:17 +01003402 // This method required full deoptimization: we need to undeoptimize everything.
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003403 req->SetKind(DeoptimizationRequest::kFullUndeoptimization);
3404 req->SetMethod(nullptr);
Sebastien Hertzf3928792014-11-17 19:00:37 +01003405 } else if (deoptimization_kind == DeoptimizationRequest::kSelectiveDeoptimization) {
Sebastien Hertza76a6d42014-03-20 16:40:17 +01003406 // This method required selective deoptimization: we need to undeoptimize only that method.
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003407 req->SetKind(DeoptimizationRequest::kSelectiveUndeoptimization);
3408 req->SetMethod(m);
Sebastien Hertzf3928792014-11-17 19:00:37 +01003409 } else {
3410 // This method had no need for deoptimization: do nothing.
3411 CHECK_EQ(deoptimization_kind, DeoptimizationRequest::kNothing);
3412 req->SetKind(DeoptimizationRequest::kNothing);
3413 req->SetMethod(nullptr);
Sebastien Hertza76a6d42014-03-20 16:40:17 +01003414 }
3415 } else {
3416 // There is at least one breakpoint for this method: we don't need to undeoptimize.
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003417 req->SetKind(DeoptimizationRequest::kNothing);
3418 req->SetMethod(nullptr);
Sebastien Hertz4d1e9ab2014-09-18 16:03:34 +02003419 if (kIsDebugBuild) {
Sebastien Hertzf3928792014-11-17 19:00:37 +01003420 SanityCheckExistingBreakpoints(m, deoptimization_kind);
Sebastien Hertz4d1e9ab2014-09-18 16:03:34 +02003421 }
Elliott Hughes86964332012-02-15 19:37:42 -08003422 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -07003423}
3424
Mathieu Chartiere401d142015-04-22 13:56:20 -07003425bool Dbg::IsForcedInterpreterNeededForCallingImpl(Thread* thread, ArtMethod* m) {
Daniel Mihalyieb076692014-08-22 17:33:31 +02003426 const SingleStepControl* const ssc = thread->GetSingleStepControl();
3427 if (ssc == nullptr) {
3428 // If we are not single-stepping, then we don't have to force interpreter.
3429 return false;
3430 }
3431 if (Runtime::Current()->GetInstrumentation()->InterpretOnly()) {
3432 // If we are in interpreter only mode, then we don't have to force interpreter.
3433 return false;
3434 }
3435
3436 if (!m->IsNative() && !m->IsProxyMethod()) {
3437 // If we want to step into a method, then we have to force interpreter on that call.
3438 if (ssc->GetStepDepth() == JDWP::SD_INTO) {
3439 return true;
3440 }
3441 }
3442 return false;
3443}
3444
Mathieu Chartiere401d142015-04-22 13:56:20 -07003445bool Dbg::IsForcedInterpreterNeededForResolutionImpl(Thread* thread, ArtMethod* m) {
Daniel Mihalyieb076692014-08-22 17:33:31 +02003446 instrumentation::Instrumentation* const instrumentation =
3447 Runtime::Current()->GetInstrumentation();
3448 // If we are in interpreter only mode, then we don't have to force interpreter.
3449 if (instrumentation->InterpretOnly()) {
3450 return false;
3451 }
3452 // We can only interpret pure Java method.
3453 if (m->IsNative() || m->IsProxyMethod()) {
3454 return false;
3455 }
3456 const SingleStepControl* const ssc = thread->GetSingleStepControl();
3457 if (ssc != nullptr) {
3458 // If we want to step into a method, then we have to force interpreter on that call.
3459 if (ssc->GetStepDepth() == JDWP::SD_INTO) {
3460 return true;
3461 }
3462 // If we are stepping out from a static initializer, by issuing a step
3463 // in or step over, that was implicitly invoked by calling a static method,
3464 // then we need to step into that method. Having a lower stack depth than
3465 // the one the single step control has indicates that the step originates
3466 // from the static initializer.
3467 if (ssc->GetStepDepth() != JDWP::SD_OUT &&
3468 ssc->GetStackDepth() > GetStackDepth(thread)) {
3469 return true;
3470 }
3471 }
3472 // There are cases where we have to force interpreter on deoptimized methods,
3473 // because in some cases the call will not be performed by invoking an entry
3474 // point that has been replaced by the deoptimization, but instead by directly
3475 // invoking the compiled code of the method, for example.
3476 return instrumentation->IsDeoptimized(m);
3477}
3478
Mathieu Chartiere401d142015-04-22 13:56:20 -07003479bool Dbg::IsForcedInstrumentationNeededForResolutionImpl(Thread* thread, ArtMethod* m) {
Mathieu Chartier2cebb242015-04-21 16:50:40 -07003480 // The upcall can be null and in that case we don't need to do anything.
Daniel Mihalyieb076692014-08-22 17:33:31 +02003481 if (m == nullptr) {
3482 return false;
3483 }
3484 instrumentation::Instrumentation* const instrumentation =
3485 Runtime::Current()->GetInstrumentation();
3486 // If we are in interpreter only mode, then we don't have to force interpreter.
3487 if (instrumentation->InterpretOnly()) {
3488 return false;
3489 }
3490 // We can only interpret pure Java method.
3491 if (m->IsNative() || m->IsProxyMethod()) {
3492 return false;
3493 }
3494 const SingleStepControl* const ssc = thread->GetSingleStepControl();
3495 if (ssc != nullptr) {
3496 // If we are stepping out from a static initializer, by issuing a step
3497 // out, that was implicitly invoked by calling a static method, then we
3498 // need to step into the caller of that method. Having a lower stack
3499 // depth than the one the single step control has indicates that the
3500 // step originates from the static initializer.
3501 if (ssc->GetStepDepth() == JDWP::SD_OUT &&
3502 ssc->GetStackDepth() > GetStackDepth(thread)) {
3503 return true;
3504 }
3505 }
3506 // If we are returning from a static intializer, that was implicitly
3507 // invoked by calling a static method and the caller is deoptimized,
3508 // then we have to deoptimize the stack without forcing interpreter
3509 // on the static method that was called originally. This problem can
3510 // be solved easily by forcing instrumentation on the called method,
3511 // because the instrumentation exit hook will recognise the need of
3512 // stack deoptimization by calling IsForcedInterpreterNeededForUpcall.
3513 return instrumentation->IsDeoptimized(m);
3514}
3515
Mathieu Chartiere401d142015-04-22 13:56:20 -07003516bool Dbg::IsForcedInterpreterNeededForUpcallImpl(Thread* thread, ArtMethod* m) {
Mathieu Chartier2cebb242015-04-21 16:50:40 -07003517 // The upcall can be null and in that case we don't need to do anything.
Daniel Mihalyieb076692014-08-22 17:33:31 +02003518 if (m == nullptr) {
3519 return false;
3520 }
3521 instrumentation::Instrumentation* const instrumentation =
3522 Runtime::Current()->GetInstrumentation();
3523 // If we are in interpreter only mode, then we don't have to force interpreter.
3524 if (instrumentation->InterpretOnly()) {
3525 return false;
3526 }
3527 // We can only interpret pure Java method.
3528 if (m->IsNative() || m->IsProxyMethod()) {
3529 return false;
3530 }
3531 const SingleStepControl* const ssc = thread->GetSingleStepControl();
3532 if (ssc != nullptr) {
3533 // The debugger is not interested in what is happening under the level
3534 // of the step, thus we only force interpreter when we are not below of
3535 // the step.
3536 if (ssc->GetStackDepth() >= GetStackDepth(thread)) {
3537 return true;
3538 }
3539 }
3540 // We have to require stack deoptimization if the upcall is deoptimized.
3541 return instrumentation->IsDeoptimized(m);
3542}
3543
Jeff Hao449db332013-04-12 18:30:52 -07003544// Scoped utility class to suspend a thread so that we may do tasks such as walk its stack. Doesn't
3545// cause suspension if the thread is the current thread.
3546class ScopedThreadSuspension {
3547 public:
Ian Rogers33e95662013-05-20 20:29:14 -07003548 ScopedThreadSuspension(Thread* self, JDWP::ObjectId thread_id)
Sebastien Hertz52d131d2014-03-13 16:17:40 +01003549 LOCKS_EXCLUDED(Locks::thread_list_lock_)
Ian Rogers33e95662013-05-20 20:29:14 -07003550 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) :
Ian Rogersf3d874c2014-07-17 18:52:42 -07003551 thread_(nullptr),
Jeff Hao449db332013-04-12 18:30:52 -07003552 error_(JDWP::ERR_NONE),
3553 self_suspend_(false),
Ian Rogers33e95662013-05-20 20:29:14 -07003554 other_suspend_(false) {
Jeff Hao449db332013-04-12 18:30:52 -07003555 ScopedObjectAccessUnchecked soa(self);
Sebastien Hertz69206392015-04-07 15:54:25 +02003556 thread_ = DecodeThread(soa, thread_id, &error_);
Jeff Hao449db332013-04-12 18:30:52 -07003557 if (error_ == JDWP::ERR_NONE) {
3558 if (thread_ == soa.Self()) {
3559 self_suspend_ = true;
3560 } else {
3561 soa.Self()->TransitionFromRunnableToSuspended(kWaitingForDebuggerSuspension);
Sebastien Hertz6995c602014-09-09 12:10:13 +02003562 jobject thread_peer = Dbg::GetObjectRegistry()->GetJObject(thread_id);
Jeff Hao449db332013-04-12 18:30:52 -07003563 bool timed_out;
Ian Rogers4ad5cd32014-11-11 23:08:07 -08003564 ThreadList* thread_list = Runtime::Current()->GetThreadList();
3565 Thread* suspended_thread = thread_list->SuspendThreadByPeer(thread_peer, true, true,
3566 &timed_out);
Jeff Hao449db332013-04-12 18:30:52 -07003567 CHECK_EQ(soa.Self()->TransitionFromSuspendedToRunnable(), kWaitingForDebuggerSuspension);
Ian Rogersf3d874c2014-07-17 18:52:42 -07003568 if (suspended_thread == nullptr) {
Jeff Hao449db332013-04-12 18:30:52 -07003569 // Thread terminated from under us while suspending.
3570 error_ = JDWP::ERR_INVALID_THREAD;
3571 } else {
3572 CHECK_EQ(suspended_thread, thread_);
3573 other_suspend_ = true;
3574 }
3575 }
3576 }
Elliott Hughes2435a572012-02-17 16:07:41 -08003577 }
Elliott Hughes86964332012-02-15 19:37:42 -08003578
Jeff Hao449db332013-04-12 18:30:52 -07003579 Thread* GetThread() const {
3580 return thread_;
3581 }
3582
3583 JDWP::JdwpError GetError() const {
3584 return error_;
3585 }
3586
3587 ~ScopedThreadSuspension() {
3588 if (other_suspend_) {
3589 Runtime::Current()->GetThreadList()->Resume(thread_, true);
3590 }
3591 }
3592
3593 private:
3594 Thread* thread_;
3595 JDWP::JdwpError error_;
3596 bool self_suspend_;
3597 bool other_suspend_;
3598};
3599
3600JDWP::JdwpError Dbg::ConfigureStep(JDWP::ObjectId thread_id, JDWP::JdwpStepSize step_size,
3601 JDWP::JdwpStepDepth step_depth) {
3602 Thread* self = Thread::Current();
3603 ScopedThreadSuspension sts(self, thread_id);
3604 if (sts.GetError() != JDWP::ERR_NONE) {
3605 return sts.GetError();
3606 }
3607
Sebastien Hertz597c4f02015-01-26 17:37:14 +01003608 // Work out what ArtMethod* we're in, the current line number, and how deep the stack currently
Elliott Hughes2435a572012-02-17 16:07:41 -08003609 // is for step-out.
Ian Rogers0399dde2012-06-06 17:09:28 -07003610 struct SingleStepStackVisitor : public StackVisitor {
Sebastien Hertz597c4f02015-01-26 17:37:14 +01003611 explicit SingleStepStackVisitor(Thread* thread) SHARED_LOCKS_REQUIRED(Locks::mutator_lock_)
Nicolas Geoffray8e5bd182015-05-06 11:34:34 +01003612 : StackVisitor(thread, nullptr, StackVisitor::StackWalkKind::kIncludeInlinedFrames),
3613 stack_depth(0),
3614 method(nullptr),
3615 line_number(-1) {}
Ian Rogersca190662012-06-26 15:45:57 -07003616
Ian Rogers00f7d0e2012-07-19 15:28:27 -07003617 // TODO: Enable annotalysis. We know lock is held in constructor, but abstraction confuses
3618 // annotalysis.
3619 bool VisitFrame() NO_THREAD_SAFETY_ANALYSIS {
Mathieu Chartiere401d142015-04-22 13:56:20 -07003620 ArtMethod* m = GetMethod();
Ian Rogers0399dde2012-06-06 17:09:28 -07003621 if (!m->IsRuntimeMethod()) {
Sebastien Hertz597c4f02015-01-26 17:37:14 +01003622 ++stack_depth;
3623 if (method == nullptr) {
Ian Rogersef7d42f2014-01-06 12:55:46 -08003624 mirror::DexCache* dex_cache = m->GetDeclaringClass()->GetDexCache();
Sebastien Hertz597c4f02015-01-26 17:37:14 +01003625 method = m;
Ian Rogersc0542af2014-09-03 16:16:56 -07003626 if (dex_cache != nullptr) {
Ian Rogers4445a7e2012-10-05 17:19:13 -07003627 const DexFile& dex_file = *dex_cache->GetDexFile();
Sebastien Hertz597c4f02015-01-26 17:37:14 +01003628 line_number = dex_file.GetLineNumFromPC(m, GetDexPc());
Elliott Hughes2435a572012-02-17 16:07:41 -08003629 }
Elliott Hughes86964332012-02-15 19:37:42 -08003630 }
3631 }
Elliott Hughes530fa002012-03-12 11:44:49 -07003632 return true;
Elliott Hughes86964332012-02-15 19:37:42 -08003633 }
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01003634
Sebastien Hertz597c4f02015-01-26 17:37:14 +01003635 int stack_depth;
Mathieu Chartiere401d142015-04-22 13:56:20 -07003636 ArtMethod* method;
Sebastien Hertz597c4f02015-01-26 17:37:14 +01003637 int32_t line_number;
Elliott Hughes86964332012-02-15 19:37:42 -08003638 };
Jeff Hao449db332013-04-12 18:30:52 -07003639
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01003640 Thread* const thread = sts.GetThread();
Sebastien Hertz597c4f02015-01-26 17:37:14 +01003641 SingleStepStackVisitor visitor(thread);
Ian Rogers0399dde2012-06-06 17:09:28 -07003642 visitor.WalkStack();
Elliott Hughes86964332012-02-15 19:37:42 -08003643
Elliott Hughes2435a572012-02-17 16:07:41 -08003644 // Find the dex_pc values that correspond to the current line, for line-based single-stepping.
Elliott Hughes2435a572012-02-17 16:07:41 -08003645 struct DebugCallbackContext {
Sebastien Hertz597c4f02015-01-26 17:37:14 +01003646 explicit DebugCallbackContext(SingleStepControl* single_step_control_cb,
3647 int32_t line_number_cb, const DexFile::CodeItem* code_item)
Andreas Gampe277ccbd2014-11-03 21:36:10 -08003648 : single_step_control_(single_step_control_cb), line_number_(line_number_cb),
3649 code_item_(code_item), last_pc_valid(false), last_pc(0) {
Elliott Hughes2435a572012-02-17 16:07:41 -08003650 }
3651
Andreas Gampe277ccbd2014-11-03 21:36:10 -08003652 static bool Callback(void* raw_context, uint32_t address, uint32_t line_number_cb) {
Elliott Hughes2435a572012-02-17 16:07:41 -08003653 DebugCallbackContext* context = reinterpret_cast<DebugCallbackContext*>(raw_context);
Andreas Gampe277ccbd2014-11-03 21:36:10 -08003654 if (static_cast<int32_t>(line_number_cb) == context->line_number_) {
Elliott Hughes2435a572012-02-17 16:07:41 -08003655 if (!context->last_pc_valid) {
3656 // Everything from this address until the next line change is ours.
3657 context->last_pc = address;
3658 context->last_pc_valid = true;
3659 }
3660 // Otherwise, if we're already in a valid range for this line,
3661 // just keep going (shouldn't really happen)...
Brian Carlstrom7934ac22013-07-26 10:54:15 -07003662 } else if (context->last_pc_valid) { // and the line number is new
Elliott Hughes2435a572012-02-17 16:07:41 -08003663 // Add everything from the last entry up until here to the set
3664 for (uint32_t dex_pc = context->last_pc; dex_pc < address; ++dex_pc) {
Sebastien Hertz597c4f02015-01-26 17:37:14 +01003665 context->single_step_control_->AddDexPc(dex_pc);
Elliott Hughes2435a572012-02-17 16:07:41 -08003666 }
3667 context->last_pc_valid = false;
3668 }
Brian Carlstrom7934ac22013-07-26 10:54:15 -07003669 return false; // There may be multiple entries for any given line.
Elliott Hughes2435a572012-02-17 16:07:41 -08003670 }
3671
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01003672 ~DebugCallbackContext() {
Elliott Hughes2435a572012-02-17 16:07:41 -08003673 // If the line number was the last in the position table...
3674 if (last_pc_valid) {
Sebastien Hertzbb43b432014-04-14 11:59:08 +02003675 size_t end = code_item_->insns_size_in_code_units_;
Elliott Hughes2435a572012-02-17 16:07:41 -08003676 for (uint32_t dex_pc = last_pc; dex_pc < end; ++dex_pc) {
Sebastien Hertz597c4f02015-01-26 17:37:14 +01003677 single_step_control_->AddDexPc(dex_pc);
Elliott Hughes2435a572012-02-17 16:07:41 -08003678 }
3679 }
3680 }
3681
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01003682 SingleStepControl* const single_step_control_;
3683 const int32_t line_number_;
Sebastien Hertzbb43b432014-04-14 11:59:08 +02003684 const DexFile::CodeItem* const code_item_;
Elliott Hughes2435a572012-02-17 16:07:41 -08003685 bool last_pc_valid;
3686 uint32_t last_pc;
3687 };
Sebastien Hertz597c4f02015-01-26 17:37:14 +01003688
3689 // Allocate single step.
Sebastien Hertz1558b572015-02-25 15:05:59 +01003690 SingleStepControl* single_step_control =
3691 new (std::nothrow) SingleStepControl(step_size, step_depth,
3692 visitor.stack_depth, visitor.method);
3693 if (single_step_control == nullptr) {
3694 LOG(ERROR) << "Failed to allocate SingleStepControl";
3695 return JDWP::ERR_OUT_OF_MEMORY;
3696 }
3697
Mathieu Chartiere401d142015-04-22 13:56:20 -07003698 ArtMethod* m = single_step_control->GetMethod();
Sebastien Hertz597c4f02015-01-26 17:37:14 +01003699 const int32_t line_number = visitor.line_number;
Sebastien Hertz52f5f932015-05-28 11:00:57 +02003700 // Note: if the thread is not running Java code (pure native thread), there is no "current"
3701 // method on the stack (and no line number either).
3702 if (m != nullptr && !m->IsNative()) {
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07003703 const DexFile::CodeItem* const code_item = m->GetCodeItem();
Sebastien Hertzbb43b432014-04-14 11:59:08 +02003704 DebugCallbackContext context(single_step_control, line_number, code_item);
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07003705 m->GetDexFile()->DecodeDebugInfo(code_item, m->IsStatic(), m->GetDexMethodIndex(),
Ian Rogersc0542af2014-09-03 16:16:56 -07003706 DebugCallbackContext::Callback, nullptr, &context);
Elliott Hughes3e2e1a22012-02-21 11:33:41 -08003707 }
Elliott Hughes2435a572012-02-17 16:07:41 -08003708
Sebastien Hertz597c4f02015-01-26 17:37:14 +01003709 // Activate single-step in the thread.
3710 thread->ActivateSingleStepControl(single_step_control);
Elliott Hughes86964332012-02-15 19:37:42 -08003711
Elliott Hughes2435a572012-02-17 16:07:41 -08003712 if (VLOG_IS_ON(jdwp)) {
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01003713 VLOG(jdwp) << "Single-step thread: " << *thread;
Sebastien Hertz597c4f02015-01-26 17:37:14 +01003714 VLOG(jdwp) << "Single-step step size: " << single_step_control->GetStepSize();
3715 VLOG(jdwp) << "Single-step step depth: " << single_step_control->GetStepDepth();
3716 VLOG(jdwp) << "Single-step current method: " << PrettyMethod(single_step_control->GetMethod());
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01003717 VLOG(jdwp) << "Single-step current line: " << line_number;
Sebastien Hertz597c4f02015-01-26 17:37:14 +01003718 VLOG(jdwp) << "Single-step current stack depth: " << single_step_control->GetStackDepth();
Elliott Hughes2435a572012-02-17 16:07:41 -08003719 VLOG(jdwp) << "Single-step dex_pc values:";
Sebastien Hertz597c4f02015-01-26 17:37:14 +01003720 for (uint32_t dex_pc : single_step_control->GetDexPcs()) {
Sebastien Hertzbb43b432014-04-14 11:59:08 +02003721 VLOG(jdwp) << StringPrintf(" %#x", dex_pc);
Elliott Hughes2435a572012-02-17 16:07:41 -08003722 }
3723 }
3724
3725 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07003726}
3727
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01003728void Dbg::UnconfigureStep(JDWP::ObjectId thread_id) {
3729 ScopedObjectAccessUnchecked soa(Thread::Current());
Ian Rogersc0542af2014-09-03 16:16:56 -07003730 JDWP::JdwpError error;
3731 Thread* thread = DecodeThread(soa, thread_id, &error);
Sebastien Hertz87118ed2013-11-26 17:57:18 +01003732 if (error == JDWP::ERR_NONE) {
Sebastien Hertz597c4f02015-01-26 17:37:14 +01003733 thread->DeactivateSingleStepControl();
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01003734 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -07003735}
3736
Elliott Hughes45651fd2012-02-21 15:48:20 -08003737static char JdwpTagToShortyChar(JDWP::JdwpTag tag) {
3738 switch (tag) {
3739 default:
3740 LOG(FATAL) << "unknown JDWP tag: " << PrintableChar(tag);
Ian Rogersfc787ec2014-10-09 21:56:44 -07003741 UNREACHABLE();
Elliott Hughes45651fd2012-02-21 15:48:20 -08003742
3743 // Primitives.
3744 case JDWP::JT_BYTE: return 'B';
3745 case JDWP::JT_CHAR: return 'C';
3746 case JDWP::JT_FLOAT: return 'F';
3747 case JDWP::JT_DOUBLE: return 'D';
3748 case JDWP::JT_INT: return 'I';
3749 case JDWP::JT_LONG: return 'J';
3750 case JDWP::JT_SHORT: return 'S';
3751 case JDWP::JT_VOID: return 'V';
3752 case JDWP::JT_BOOLEAN: return 'Z';
3753
3754 // Reference types.
3755 case JDWP::JT_ARRAY:
3756 case JDWP::JT_OBJECT:
3757 case JDWP::JT_STRING:
3758 case JDWP::JT_THREAD:
3759 case JDWP::JT_THREAD_GROUP:
3760 case JDWP::JT_CLASS_LOADER:
3761 case JDWP::JT_CLASS_OBJECT:
3762 return 'L';
3763 }
3764}
3765
Elliott Hughes88d63092013-01-09 09:55:54 -08003766JDWP::JdwpError Dbg::InvokeMethod(JDWP::ObjectId thread_id, JDWP::ObjectId object_id,
3767 JDWP::RefTypeId class_id, JDWP::MethodId method_id,
Ian Rogers00f7d0e2012-07-19 15:28:27 -07003768 uint32_t arg_count, uint64_t* arg_values,
3769 JDWP::JdwpTag* arg_types, uint32_t options,
3770 JDWP::JdwpTag* pResultTag, uint64_t* pResultValue,
3771 JDWP::ObjectId* pExceptionId) {
Elliott Hughesd07986f2011-12-06 18:27:45 -08003772 ThreadList* thread_list = Runtime::Current()->GetThreadList();
3773
Ian Rogersc0542af2014-09-03 16:16:56 -07003774 Thread* targetThread = nullptr;
Sebastien Hertz1558b572015-02-25 15:05:59 +01003775 std::unique_ptr<DebugInvokeReq> req;
Ian Rogers00f7d0e2012-07-19 15:28:27 -07003776 Thread* self = Thread::Current();
Elliott Hughesd07986f2011-12-06 18:27:45 -08003777 {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07003778 ScopedObjectAccessUnchecked soa(self);
Ian Rogersc0542af2014-09-03 16:16:56 -07003779 JDWP::JdwpError error;
3780 targetThread = DecodeThread(soa, thread_id, &error);
Elliott Hughes221229c2013-01-08 18:17:50 -08003781 if (error != JDWP::ERR_NONE) {
3782 LOG(ERROR) << "InvokeMethod request for invalid thread id " << thread_id;
3783 return error;
Elliott Hughesd07986f2011-12-06 18:27:45 -08003784 }
Sebastien Hertz1558b572015-02-25 15:05:59 +01003785 if (targetThread->GetInvokeReq() != nullptr) {
3786 // Thread is already invoking a method on behalf of the debugger.
3787 LOG(ERROR) << "InvokeMethod request for thread already invoking a method: " << *targetThread;
3788 return JDWP::ERR_ALREADY_INVOKING;
3789 }
3790 if (!targetThread->IsReadyForDebugInvoke()) {
3791 // Thread is not suspended by an event so it cannot invoke a method.
Elliott Hughesd07986f2011-12-06 18:27:45 -08003792 LOG(ERROR) << "InvokeMethod request for thread not stopped by event: " << *targetThread;
3793 return JDWP::ERR_INVALID_THREAD;
3794 }
3795
3796 /*
3797 * We currently have a bug where we don't successfully resume the
3798 * target thread if the suspend count is too deep. We're expected to
3799 * require one "resume" for each "suspend", but when asked to execute
3800 * a method we have to resume fully and then re-suspend it back to the
3801 * same level. (The easiest way to cause this is to type "suspend"
3802 * multiple times in jdb.)
3803 *
3804 * It's unclear what this means when the event specifies "resume all"
3805 * and some threads are suspended more deeply than others. This is
3806 * a rare problem, so for now we just prevent it from hanging forever
3807 * by rejecting the method invocation request. Without this, we will
3808 * be stuck waiting on a suspended thread.
3809 */
Ian Rogers00f7d0e2012-07-19 15:28:27 -07003810 int suspend_count;
3811 {
Ian Rogers50b35e22012-10-04 10:09:15 -07003812 MutexLock mu2(soa.Self(), *Locks::thread_suspend_count_lock_);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07003813 suspend_count = targetThread->GetSuspendCount();
3814 }
Elliott Hughesd07986f2011-12-06 18:27:45 -08003815 if (suspend_count > 1) {
3816 LOG(ERROR) << *targetThread << " suspend count too deep for method invocation: " << suspend_count;
Brian Carlstrom7934ac22013-07-26 10:54:15 -07003817 return JDWP::ERR_THREAD_SUSPENDED; // Probably not expected here.
Elliott Hughesd07986f2011-12-06 18:27:45 -08003818 }
3819
Ian Rogersc0542af2014-09-03 16:16:56 -07003820 mirror::Object* receiver = gRegistry->Get<mirror::Object*>(object_id, &error);
3821 if (error != JDWP::ERR_NONE) {
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08003822 return JDWP::ERR_INVALID_OBJECT;
3823 }
Elliott Hughes45651fd2012-02-21 15:48:20 -08003824
Sebastien Hertz1558b572015-02-25 15:05:59 +01003825 gRegistry->Get<mirror::Object*>(thread_id, &error);
Ian Rogersc0542af2014-09-03 16:16:56 -07003826 if (error != JDWP::ERR_NONE) {
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08003827 return JDWP::ERR_INVALID_OBJECT;
3828 }
Elliott Hughes45651fd2012-02-21 15:48:20 -08003829
Ian Rogersc0542af2014-09-03 16:16:56 -07003830 mirror::Class* c = DecodeClass(class_id, &error);
3831 if (c == nullptr) {
3832 return error;
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08003833 }
Elliott Hughes45651fd2012-02-21 15:48:20 -08003834
Mathieu Chartiere401d142015-04-22 13:56:20 -07003835 ArtMethod* m = FromMethodId(method_id);
Ian Rogersc0542af2014-09-03 16:16:56 -07003836 if (m->IsStatic() != (receiver == nullptr)) {
Elliott Hughes45651fd2012-02-21 15:48:20 -08003837 return JDWP::ERR_INVALID_METHODID;
3838 }
3839 if (m->IsStatic()) {
3840 if (m->GetDeclaringClass() != c) {
3841 return JDWP::ERR_INVALID_METHODID;
3842 }
3843 } else {
3844 if (!m->GetDeclaringClass()->IsAssignableFrom(c)) {
3845 return JDWP::ERR_INVALID_METHODID;
3846 }
3847 }
3848
3849 // Check the argument list matches the method.
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07003850 uint32_t shorty_len = 0;
3851 const char* shorty = m->GetShorty(&shorty_len);
3852 if (shorty_len - 1 != arg_count) {
Elliott Hughes45651fd2012-02-21 15:48:20 -08003853 return JDWP::ERR_ILLEGAL_ARGUMENT;
3854 }
Elliott Hughes09201632013-04-15 15:50:07 -07003855
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07003856 {
Mathieu Chartiere401d142015-04-22 13:56:20 -07003857 StackHandleScope<2> hs(soa.Self());
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07003858 HandleWrapper<mirror::Object> h_obj(hs.NewHandleWrapper(&receiver));
3859 HandleWrapper<mirror::Class> h_klass(hs.NewHandleWrapper(&c));
3860 const DexFile::TypeList* types = m->GetParameterTypeList();
3861 for (size_t i = 0; i < arg_count; ++i) {
3862 if (shorty[i + 1] != JdwpTagToShortyChar(arg_types[i])) {
Elliott Hughes09201632013-04-15 15:50:07 -07003863 return JDWP::ERR_ILLEGAL_ARGUMENT;
3864 }
3865
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07003866 if (shorty[i + 1] == 'L') {
3867 // Did we really get an argument of an appropriate reference type?
Ian Rogersa0485602014-12-02 15:48:04 -08003868 mirror::Class* parameter_type =
Mathieu Chartiere401d142015-04-22 13:56:20 -07003869 m->GetClassFromTypeIndex(types->GetTypeItem(i).type_idx_, true);
Ian Rogersc0542af2014-09-03 16:16:56 -07003870 mirror::Object* argument = gRegistry->Get<mirror::Object*>(arg_values[i], &error);
3871 if (error != JDWP::ERR_NONE) {
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07003872 return JDWP::ERR_INVALID_OBJECT;
3873 }
Ian Rogersc0542af2014-09-03 16:16:56 -07003874 if (argument != nullptr && !argument->InstanceOf(parameter_type)) {
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07003875 return JDWP::ERR_ILLEGAL_ARGUMENT;
3876 }
3877
3878 // Turn the on-the-wire ObjectId into a jobject.
3879 jvalue& v = reinterpret_cast<jvalue&>(arg_values[i]);
3880 v.l = gRegistry->GetJObject(arg_values[i]);
3881 }
Elliott Hughes09201632013-04-15 15:50:07 -07003882 }
Elliott Hughes45651fd2012-02-21 15:48:20 -08003883 }
3884
Sebastien Hertz1558b572015-02-25 15:05:59 +01003885 // Allocates a DebugInvokeReq.
3886 req.reset(new (std::nothrow) DebugInvokeReq(receiver, c, m, options, arg_values, arg_count));
3887 if (req.get() == nullptr) {
3888 LOG(ERROR) << "Failed to allocate DebugInvokeReq";
3889 return JDWP::ERR_OUT_OF_MEMORY;
3890 }
3891
3892 // Attach the DebugInvokeReq to the target thread so it executes the method when
3893 // it is resumed. Once the invocation completes, it will detach it and signal us
3894 // before suspending itself.
3895 targetThread->SetDebugInvokeReq(req.get());
Elliott Hughesd07986f2011-12-06 18:27:45 -08003896 }
3897
3898 // The fact that we've released the thread list lock is a bit risky --- if the thread goes
3899 // away we're sitting high and dry -- but we must release this before the ResumeAllThreads
3900 // call, and it's unwise to hold it during WaitForSuspend.
3901
3902 {
3903 /*
3904 * We change our (JDWP thread) status, which should be THREAD_RUNNING,
Elliott Hughes81ff3182012-03-23 20:35:56 -07003905 * so we can suspend for a GC if the invoke request causes us to
Elliott Hughesd07986f2011-12-06 18:27:45 -08003906 * run out of memory. It's also a good idea to change it before locking
3907 * the invokeReq mutex, although that should never be held for long.
3908 */
Ian Rogers00f7d0e2012-07-19 15:28:27 -07003909 self->TransitionFromRunnableToSuspended(kWaitingForDebuggerSend);
Elliott Hughesd07986f2011-12-06 18:27:45 -08003910
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08003911 VLOG(jdwp) << " Transferring control to event thread";
Elliott Hughesd07986f2011-12-06 18:27:45 -08003912 {
Sebastien Hertzd38667a2013-11-25 15:43:54 +01003913 MutexLock mu(self, req->lock);
Elliott Hughesd07986f2011-12-06 18:27:45 -08003914
3915 if ((options & JDWP::INVOKE_SINGLE_THREADED) == 0) {
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08003916 VLOG(jdwp) << " Resuming all threads";
Ian Rogers00f7d0e2012-07-19 15:28:27 -07003917 thread_list->UndoDebuggerSuspensions();
Elliott Hughesd07986f2011-12-06 18:27:45 -08003918 } else {
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08003919 VLOG(jdwp) << " Resuming event thread only";
Elliott Hughesd07986f2011-12-06 18:27:45 -08003920 thread_list->Resume(targetThread, true);
3921 }
3922
Sebastien Hertz2bf93f42015-01-09 18:44:05 +01003923 // The target thread is resumed but needs the JDWP token we're holding.
3924 // We release it now and will acquire it again when the invocation is
3925 // complete and the target thread suspends itself.
3926 gJdwpState->ReleaseJdwpTokenForCommand();
3927
Elliott Hughesd07986f2011-12-06 18:27:45 -08003928 // Wait for the request to finish executing.
Sebastien Hertz1558b572015-02-25 15:05:59 +01003929 while (targetThread->GetInvokeReq() != nullptr) {
Sebastien Hertzd38667a2013-11-25 15:43:54 +01003930 req->cond.Wait(self);
Elliott Hughesd07986f2011-12-06 18:27:45 -08003931 }
3932 }
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08003933 VLOG(jdwp) << " Control has returned from event thread";
Elliott Hughesd07986f2011-12-06 18:27:45 -08003934
3935 /* wait for thread to re-suspend itself */
Brian Carlstromdf629502013-07-17 22:39:56 -07003936 SuspendThread(thread_id, false /* request_suspension */);
Sebastien Hertz2bf93f42015-01-09 18:44:05 +01003937
3938 // Now the thread is suspended again, we can re-acquire the JDWP token.
3939 gJdwpState->AcquireJdwpTokenForCommand();
3940
Ian Rogers00f7d0e2012-07-19 15:28:27 -07003941 self->TransitionFromSuspendedToRunnable();
Elliott Hughesd07986f2011-12-06 18:27:45 -08003942 }
3943
3944 /*
3945 * Suspend the threads. We waited for the target thread to suspend
3946 * itself, so all we need to do is suspend the others.
3947 *
Sebastien Hertz2bf93f42015-01-09 18:44:05 +01003948 * The SuspendAllForDebugger() call will double-suspend the event thread,
Elliott Hughesd07986f2011-12-06 18:27:45 -08003949 * so we want to resume the target thread once to keep the books straight.
3950 */
3951 if ((options & JDWP::INVOKE_SINGLE_THREADED) == 0) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07003952 self->TransitionFromRunnableToSuspended(kWaitingForDebuggerSuspension);
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08003953 VLOG(jdwp) << " Suspending all threads";
Ian Rogers00f7d0e2012-07-19 15:28:27 -07003954 thread_list->SuspendAllForDebugger();
3955 self->TransitionFromSuspendedToRunnable();
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08003956 VLOG(jdwp) << " Resuming event thread to balance the count";
Elliott Hughesd07986f2011-12-06 18:27:45 -08003957 thread_list->Resume(targetThread, true);
3958 }
3959
3960 // Copy the result.
3961 *pResultTag = req->result_tag;
Sebastien Hertz1558b572015-02-25 15:05:59 +01003962 *pResultValue = req->result_value;
Elliott Hughesd07986f2011-12-06 18:27:45 -08003963 *pExceptionId = req->exception;
3964 return req->error;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07003965}
3966
3967void Dbg::ExecuteMethod(DebugInvokeReq* pReq) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07003968 ScopedObjectAccess soa(Thread::Current());
Elliott Hughesd07986f2011-12-06 18:27:45 -08003969
Elliott Hughes81ff3182012-03-23 20:35:56 -07003970 // We can be called while an exception is pending. We need
Elliott Hughesd07986f2011-12-06 18:27:45 -08003971 // to preserve that across the method invocation.
Mathieu Chartiere401d142015-04-22 13:56:20 -07003972 StackHandleScope<3> hs(soa.Self());
Sebastien Hertz1558b572015-02-25 15:05:59 +01003973 auto old_exception = hs.NewHandle<mirror::Throwable>(soa.Self()->GetException());
3974 soa.Self()->ClearException();
Elliott Hughesd07986f2011-12-06 18:27:45 -08003975
3976 // Translate the method through the vtable, unless the debugger wants to suppress it.
Mathieu Chartiere401d142015-04-22 13:56:20 -07003977 auto* m = pReq->method;
3978 auto image_pointer_size = Runtime::Current()->GetClassLinker()->GetImagePointerSize();
Sebastien Hertz1558b572015-02-25 15:05:59 +01003979 if ((pReq->options & JDWP::INVOKE_NONVIRTUAL) == 0 && pReq->receiver.Read() != nullptr) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07003980 ArtMethod* actual_method =
3981 pReq->klass.Read()->FindVirtualMethodForVirtualOrInterface(m, image_pointer_size);
3982 if (actual_method != m) {
3983 VLOG(jdwp) << "ExecuteMethod translated " << PrettyMethod(m)
Sebastien Hertz1558b572015-02-25 15:05:59 +01003984 << " to " << PrettyMethod(actual_method);
Mathieu Chartiere401d142015-04-22 13:56:20 -07003985 m = actual_method;
Elliott Hughes45651fd2012-02-21 15:48:20 -08003986 }
Elliott Hughesd07986f2011-12-06 18:27:45 -08003987 }
Mathieu Chartiere401d142015-04-22 13:56:20 -07003988 VLOG(jdwp) << "ExecuteMethod " << PrettyMethod(m)
Sebastien Hertz1558b572015-02-25 15:05:59 +01003989 << " receiver=" << pReq->receiver.Read()
Sebastien Hertzd38667a2013-11-25 15:43:54 +01003990 << " arg_count=" << pReq->arg_count;
Mathieu Chartiere401d142015-04-22 13:56:20 -07003991 CHECK(m != nullptr);
Elliott Hughesd07986f2011-12-06 18:27:45 -08003992
3993 CHECK_EQ(sizeof(jvalue), sizeof(uint64_t));
3994
Jeff Hao39b6c242015-05-19 20:30:23 -07003995 ScopedLocalRef<jobject> ref(soa.Env(), soa.AddLocalReference<jobject>(pReq->receiver.Read()));
Mathieu Chartiere401d142015-04-22 13:56:20 -07003996 JValue result = InvokeWithJValues(soa, ref.get(), soa.EncodeMethod(m),
Sebastien Hertz1558b572015-02-25 15:05:59 +01003997 reinterpret_cast<jvalue*>(pReq->arg_values));
Elliott Hughesd07986f2011-12-06 18:27:45 -08003998
Mathieu Chartiere401d142015-04-22 13:56:20 -07003999 pReq->result_tag = BasicTagFromDescriptor(m->GetShorty());
Sebastien Hertz1558b572015-02-25 15:05:59 +01004000 const bool is_object_result = (pReq->result_tag == JDWP::JT_OBJECT);
4001 Handle<mirror::Object> object_result = hs.NewHandle(is_object_result ? result.GetL() : nullptr);
4002 Handle<mirror::Throwable> exception = hs.NewHandle(soa.Self()->GetException());
4003 soa.Self()->ClearException();
Sebastien Hertz261bc042015-04-08 09:36:07 +02004004 pReq->exception = gRegistry->Add(exception);
Elliott Hughesd07986f2011-12-06 18:27:45 -08004005 if (pReq->exception != 0) {
Sebastien Hertz1558b572015-02-25 15:05:59 +01004006 VLOG(jdwp) << " JDWP invocation returning with exception=" << exception.Get()
4007 << " " << exception->Dump();
4008 pReq->result_value = 0;
4009 } else if (is_object_result) {
Elliott Hughesd07986f2011-12-06 18:27:45 -08004010 /* if no exception thrown, examine object result more closely */
Sebastien Hertz1558b572015-02-25 15:05:59 +01004011 JDWP::JdwpTag new_tag = TagFromObject(soa, object_result.Get());
Elliott Hughesd07986f2011-12-06 18:27:45 -08004012 if (new_tag != pReq->result_tag) {
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08004013 VLOG(jdwp) << " JDWP promoted result from " << pReq->result_tag << " to " << new_tag;
Elliott Hughesd07986f2011-12-06 18:27:45 -08004014 pReq->result_tag = new_tag;
4015 }
4016
Sebastien Hertz1558b572015-02-25 15:05:59 +01004017 // Register the object in the registry and reference its ObjectId. This ensures
4018 // GC safety and prevents from accessing stale reference if the object is moved.
4019 pReq->result_value = gRegistry->Add(object_result.Get());
4020 } else {
4021 // Primitive result.
4022 DCHECK(IsPrimitiveTag(pReq->result_tag));
4023 pReq->result_value = result.GetJ();
Elliott Hughesd07986f2011-12-06 18:27:45 -08004024 }
4025
Ian Rogersc0542af2014-09-03 16:16:56 -07004026 if (old_exception.Get() != nullptr) {
Nicolas Geoffray14691c52015-03-05 10:40:17 +00004027 soa.Self()->SetException(old_exception.Get());
Elliott Hughesd07986f2011-12-06 18:27:45 -08004028 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -07004029}
4030
Elliott Hughesd07986f2011-12-06 18:27:45 -08004031/*
Elliott Hughes4b9702c2013-02-20 18:13:24 -08004032 * "request" contains a full JDWP packet, possibly with multiple chunks. We
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07004033 * need to process each, accumulate the replies, and ship the whole thing
4034 * back.
4035 *
4036 * Returns "true" if we have a reply. The reply buffer is newly allocated,
4037 * and includes the chunk type/length, followed by the data.
4038 *
Elliott Hughes3d30d9b2011-12-07 17:35:48 -08004039 * OLD-TODO: we currently assume that the request and reply include a single
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07004040 * chunk. If this becomes inconvenient we will need to adapt.
4041 */
Ian Rogersc0542af2014-09-03 16:16:56 -07004042bool Dbg::DdmHandlePacket(JDWP::Request* request, uint8_t** pReplyBuf, int* pReplyLen) {
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07004043 Thread* self = Thread::Current();
4044 JNIEnv* env = self->GetJniEnv();
4045
Ian Rogersc0542af2014-09-03 16:16:56 -07004046 uint32_t type = request->ReadUnsigned32("type");
4047 uint32_t length = request->ReadUnsigned32("length");
Elliott Hughes4b9702c2013-02-20 18:13:24 -08004048
4049 // Create a byte[] corresponding to 'request'.
Ian Rogersc0542af2014-09-03 16:16:56 -07004050 size_t request_length = request->size();
Elliott Hughes4b9702c2013-02-20 18:13:24 -08004051 ScopedLocalRef<jbyteArray> dataArray(env, env->NewByteArray(request_length));
Ian Rogersc0542af2014-09-03 16:16:56 -07004052 if (dataArray.get() == nullptr) {
Elliott Hughes4b9702c2013-02-20 18:13:24 -08004053 LOG(WARNING) << "byte[] allocation failed: " << request_length;
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07004054 env->ExceptionClear();
4055 return false;
4056 }
Ian Rogersc0542af2014-09-03 16:16:56 -07004057 env->SetByteArrayRegion(dataArray.get(), 0, request_length,
4058 reinterpret_cast<const jbyte*>(request->data()));
4059 request->Skip(request_length);
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07004060
4061 // Run through and find all chunks. [Currently just find the first.]
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004062 ScopedByteArrayRO contents(env, dataArray.get());
Elliott Hughes4b9702c2013-02-20 18:13:24 -08004063 if (length != request_length) {
Ian Rogersef7d42f2014-01-06 12:55:46 -08004064 LOG(WARNING) << StringPrintf("bad chunk found (len=%u pktLen=%zd)", length, request_length);
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07004065 return false;
4066 }
4067
4068 // Call "private static Chunk dispatch(int type, byte[] data, int offset, int length)".
Elliott Hugheseac76672012-05-24 21:56:51 -07004069 ScopedLocalRef<jobject> chunk(env, env->CallStaticObjectMethod(WellKnownClasses::org_apache_harmony_dalvik_ddmc_DdmServer,
4070 WellKnownClasses::org_apache_harmony_dalvik_ddmc_DdmServer_dispatch,
Elliott Hughes4b9702c2013-02-20 18:13:24 -08004071 type, dataArray.get(), 0, length));
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07004072 if (env->ExceptionCheck()) {
4073 LOG(INFO) << StringPrintf("Exception thrown by dispatcher for 0x%08x", type);
4074 env->ExceptionDescribe();
4075 env->ExceptionClear();
4076 return false;
4077 }
4078
Ian Rogersc0542af2014-09-03 16:16:56 -07004079 if (chunk.get() == nullptr) {
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07004080 return false;
4081 }
4082
4083 /*
4084 * Pull the pieces out of the chunk. We copy the results into a
4085 * newly-allocated buffer that the caller can free. We don't want to
4086 * continue using the Chunk object because nothing has a reference to it.
4087 *
4088 * We could avoid this by returning type/data/offset/length and having
4089 * the caller be aware of the object lifetime issues, but that
Elliott Hughes81ff3182012-03-23 20:35:56 -07004090 * integrates the JDWP code more tightly into the rest of the runtime, and doesn't work
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07004091 * if we have responses for multiple chunks.
4092 *
4093 * So we're pretty much stuck with copying data around multiple times.
4094 */
Elliott Hugheseac76672012-05-24 21:56:51 -07004095 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 -08004096 jint offset = env->GetIntField(chunk.get(), WellKnownClasses::org_apache_harmony_dalvik_ddmc_Chunk_offset);
Elliott Hugheseac76672012-05-24 21:56:51 -07004097 length = env->GetIntField(chunk.get(), WellKnownClasses::org_apache_harmony_dalvik_ddmc_Chunk_length);
Elliott Hugheseac76672012-05-24 21:56:51 -07004098 type = env->GetIntField(chunk.get(), WellKnownClasses::org_apache_harmony_dalvik_ddmc_Chunk_type);
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07004099
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08004100 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 -07004101 if (length == 0 || replyData.get() == nullptr) {
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07004102 return false;
4103 }
4104
Elliott Hughes4b9702c2013-02-20 18:13:24 -08004105 const int kChunkHdrLen = 8;
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07004106 uint8_t* reply = new uint8_t[length + kChunkHdrLen];
Ian Rogersc0542af2014-09-03 16:16:56 -07004107 if (reply == nullptr) {
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07004108 LOG(WARNING) << "malloc failed: " << (length + kChunkHdrLen);
4109 return false;
4110 }
Elliott Hughesf7c3b662011-10-27 12:04:56 -07004111 JDWP::Set4BE(reply + 0, type);
4112 JDWP::Set4BE(reply + 4, length);
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004113 env->GetByteArrayRegion(replyData.get(), offset, length, reinterpret_cast<jbyte*>(reply + kChunkHdrLen));
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07004114
4115 *pReplyBuf = reply;
4116 *pReplyLen = length + kChunkHdrLen;
4117
Elliott Hughes4b9702c2013-02-20 18:13:24 -08004118 VLOG(jdwp) << StringPrintf("dvmHandleDdm returning type=%.4s %p len=%d", reinterpret_cast<char*>(reply), reply, length);
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07004119 return true;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07004120}
4121
Elliott Hughesa2155262011-11-16 16:26:58 -08004122void Dbg::DdmBroadcast(bool connect) {
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08004123 VLOG(jdwp) << "Broadcasting DDM " << (connect ? "connect" : "disconnect") << "...";
Elliott Hughes47fce012011-10-25 18:37:19 -07004124
4125 Thread* self = Thread::Current();
Ian Rogers50b35e22012-10-04 10:09:15 -07004126 if (self->GetState() != kRunnable) {
4127 LOG(ERROR) << "DDM broadcast in thread state " << self->GetState();
4128 /* try anyway? */
Elliott Hughes47fce012011-10-25 18:37:19 -07004129 }
4130
4131 JNIEnv* env = self->GetJniEnv();
Elliott Hughes47fce012011-10-25 18:37:19 -07004132 jint event = connect ? 1 /*DdmServer.CONNECTED*/ : 2 /*DdmServer.DISCONNECTED*/;
Elliott Hugheseac76672012-05-24 21:56:51 -07004133 env->CallStaticVoidMethod(WellKnownClasses::org_apache_harmony_dalvik_ddmc_DdmServer,
4134 WellKnownClasses::org_apache_harmony_dalvik_ddmc_DdmServer_broadcast,
4135 event);
Elliott Hughes47fce012011-10-25 18:37:19 -07004136 if (env->ExceptionCheck()) {
4137 LOG(ERROR) << "DdmServer.broadcast " << event << " failed";
4138 env->ExceptionDescribe();
4139 env->ExceptionClear();
4140 }
4141}
4142
Elliott Hughes872d4ec2011-10-21 17:07:15 -07004143void Dbg::DdmConnected() {
Elliott Hughesa2155262011-11-16 16:26:58 -08004144 Dbg::DdmBroadcast(true);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07004145}
4146
4147void Dbg::DdmDisconnected() {
Elliott Hughesa2155262011-11-16 16:26:58 -08004148 Dbg::DdmBroadcast(false);
Elliott Hughes47fce012011-10-25 18:37:19 -07004149 gDdmThreadNotification = false;
4150}
4151
4152/*
Elliott Hughes82188472011-11-07 18:11:48 -08004153 * Send a notification when a thread starts, stops, or changes its name.
Elliott Hughes47fce012011-10-25 18:37:19 -07004154 *
4155 * Because we broadcast the full set of threads when the notifications are
4156 * first enabled, it's possible for "thread" to be actively executing.
4157 */
Elliott Hughes82188472011-11-07 18:11:48 -08004158void Dbg::DdmSendThreadNotification(Thread* t, uint32_t type) {
Elliott Hughes47fce012011-10-25 18:37:19 -07004159 if (!gDdmThreadNotification) {
4160 return;
4161 }
4162
Elliott Hughes82188472011-11-07 18:11:48 -08004163 if (type == CHUNK_TYPE("THDE")) {
Elliott Hughes47fce012011-10-25 18:37:19 -07004164 uint8_t buf[4];
Ian Rogersd9c4fc92013-10-01 19:45:43 -07004165 JDWP::Set4BE(&buf[0], t->GetThreadId());
Elliott Hughes47fce012011-10-25 18:37:19 -07004166 Dbg::DdmSendChunk(CHUNK_TYPE("THDE"), 4, buf);
Elliott Hughes82188472011-11-07 18:11:48 -08004167 } else {
4168 CHECK(type == CHUNK_TYPE("THCR") || type == CHUNK_TYPE("THNM")) << type;
Ian Rogers00f7d0e2012-07-19 15:28:27 -07004169 ScopedObjectAccessUnchecked soa(Thread::Current());
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004170 StackHandleScope<1> hs(soa.Self());
4171 Handle<mirror::String> name(hs.NewHandle(t->GetThreadName(soa)));
Ian Rogersc0542af2014-09-03 16:16:56 -07004172 size_t char_count = (name.Get() != nullptr) ? name->GetLength() : 0;
Jeff Hao848f70a2014-01-15 13:49:50 -08004173 const jchar* chars = (name.Get() != nullptr) ? name->GetValue() : nullptr;
Elliott Hughes82188472011-11-07 18:11:48 -08004174
Elliott Hughes21f32d72011-11-09 17:44:13 -08004175 std::vector<uint8_t> bytes;
Ian Rogersd9c4fc92013-10-01 19:45:43 -07004176 JDWP::Append4BE(bytes, t->GetThreadId());
Elliott Hughes545a0642011-11-08 19:10:03 -08004177 JDWP::AppendUtf16BE(bytes, chars, char_count);
Elliott Hughes21f32d72011-11-09 17:44:13 -08004178 CHECK_EQ(bytes.size(), char_count*2 + sizeof(uint32_t)*2);
4179 Dbg::DdmSendChunk(type, bytes);
Elliott Hughes47fce012011-10-25 18:37:19 -07004180 }
4181}
4182
Elliott Hughes47fce012011-10-25 18:37:19 -07004183void Dbg::DdmSetThreadNotification(bool enable) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07004184 // Enable/disable thread notifications.
Elliott Hughes47fce012011-10-25 18:37:19 -07004185 gDdmThreadNotification = enable;
4186 if (enable) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07004187 // Suspend the VM then post thread start notifications for all threads. Threads attaching will
4188 // see a suspension in progress and block until that ends. They then post their own start
4189 // notification.
4190 SuspendVM();
4191 std::list<Thread*> threads;
Ian Rogers50b35e22012-10-04 10:09:15 -07004192 Thread* self = Thread::Current();
Ian Rogers00f7d0e2012-07-19 15:28:27 -07004193 {
Ian Rogers50b35e22012-10-04 10:09:15 -07004194 MutexLock mu(self, *Locks::thread_list_lock_);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07004195 threads = Runtime::Current()->GetThreadList()->GetList();
4196 }
4197 {
Ian Rogers50b35e22012-10-04 10:09:15 -07004198 ScopedObjectAccess soa(self);
Mathieu Chartier02e25112013-08-14 16:14:24 -07004199 for (Thread* thread : threads) {
4200 Dbg::DdmSendThreadNotification(thread, CHUNK_TYPE("THCR"));
Ian Rogers00f7d0e2012-07-19 15:28:27 -07004201 }
4202 }
4203 ResumeVM();
Elliott Hughes47fce012011-10-25 18:37:19 -07004204 }
4205}
4206
Elliott Hughesa2155262011-11-16 16:26:58 -08004207void Dbg::PostThreadStartOrStop(Thread* t, uint32_t type) {
Elliott Hughesc0f09332012-03-26 13:27:06 -07004208 if (IsDebuggerActive()) {
Sebastien Hertz6995c602014-09-09 12:10:13 +02004209 gJdwpState->PostThreadChange(t, type == CHUNK_TYPE("THCR"));
Elliott Hughes47fce012011-10-25 18:37:19 -07004210 }
Elliott Hughes82188472011-11-07 18:11:48 -08004211 Dbg::DdmSendThreadNotification(t, type);
Elliott Hughes47fce012011-10-25 18:37:19 -07004212}
4213
4214void Dbg::PostThreadStart(Thread* t) {
Elliott Hughesa2155262011-11-16 16:26:58 -08004215 Dbg::PostThreadStartOrStop(t, CHUNK_TYPE("THCR"));
Elliott Hughes47fce012011-10-25 18:37:19 -07004216}
4217
4218void Dbg::PostThreadDeath(Thread* t) {
Elliott Hughesa2155262011-11-16 16:26:58 -08004219 Dbg::PostThreadStartOrStop(t, CHUNK_TYPE("THDE"));
Elliott Hughes872d4ec2011-10-21 17:07:15 -07004220}
4221
Elliott Hughes82188472011-11-07 18:11:48 -08004222void Dbg::DdmSendChunk(uint32_t type, size_t byte_count, const uint8_t* buf) {
Ian Rogersc0542af2014-09-03 16:16:56 -07004223 CHECK(buf != nullptr);
Elliott Hughes3bb81562011-10-21 18:52:59 -07004224 iovec vec[1];
4225 vec[0].iov_base = reinterpret_cast<void*>(const_cast<uint8_t*>(buf));
4226 vec[0].iov_len = byte_count;
4227 Dbg::DdmSendChunkV(type, vec, 1);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07004228}
4229
Elliott Hughes21f32d72011-11-09 17:44:13 -08004230void Dbg::DdmSendChunk(uint32_t type, const std::vector<uint8_t>& bytes) {
4231 DdmSendChunk(type, bytes.size(), &bytes[0]);
4232}
4233
Brian Carlstromf5293522013-07-19 00:24:00 -07004234void Dbg::DdmSendChunkV(uint32_t type, const iovec* iov, int iov_count) {
Ian Rogersc0542af2014-09-03 16:16:56 -07004235 if (gJdwpState == nullptr) {
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08004236 VLOG(jdwp) << "Debugger thread not active, ignoring DDM send: " << type;
Elliott Hughes3bb81562011-10-21 18:52:59 -07004237 } else {
Elliott Hughescccd84f2011-12-05 16:51:54 -08004238 gJdwpState->DdmSendChunkV(type, iov, iov_count);
Elliott Hughes3bb81562011-10-21 18:52:59 -07004239 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -07004240}
4241
Mathieu Chartierad466ad2015-01-08 16:28:08 -08004242JDWP::JdwpState* Dbg::GetJdwpState() {
4243 return gJdwpState;
4244}
4245
Elliott Hughes767a1472011-10-26 18:49:02 -07004246int Dbg::DdmHandleHpifChunk(HpifWhen when) {
4247 if (when == HPIF_WHEN_NOW) {
Elliott Hughes7162ad92011-10-27 14:08:42 -07004248 DdmSendHeapInfo(when);
Elliott Hughes767a1472011-10-26 18:49:02 -07004249 return true;
4250 }
4251
4252 if (when != HPIF_WHEN_NEVER && when != HPIF_WHEN_NEXT_GC && when != HPIF_WHEN_EVERY_GC) {
4253 LOG(ERROR) << "invalid HpifWhen value: " << static_cast<int>(when);
4254 return false;
4255 }
4256
4257 gDdmHpifWhen = when;
4258 return true;
4259}
4260
4261bool Dbg::DdmHandleHpsgNhsgChunk(Dbg::HpsgWhen when, Dbg::HpsgWhat what, bool native) {
4262 if (when != HPSG_WHEN_NEVER && when != HPSG_WHEN_EVERY_GC) {
4263 LOG(ERROR) << "invalid HpsgWhen value: " << static_cast<int>(when);
4264 return false;
4265 }
4266
4267 if (what != HPSG_WHAT_MERGED_OBJECTS && what != HPSG_WHAT_DISTINCT_OBJECTS) {
4268 LOG(ERROR) << "invalid HpsgWhat value: " << static_cast<int>(what);
4269 return false;
4270 }
4271
4272 if (native) {
4273 gDdmNhsgWhen = when;
4274 gDdmNhsgWhat = what;
4275 } else {
4276 gDdmHpsgWhen = when;
4277 gDdmHpsgWhat = what;
4278 }
4279 return true;
4280}
4281
Elliott Hughes7162ad92011-10-27 14:08:42 -07004282void Dbg::DdmSendHeapInfo(HpifWhen reason) {
4283 // If there's a one-shot 'when', reset it.
4284 if (reason == gDdmHpifWhen) {
4285 if (gDdmHpifWhen == HPIF_WHEN_NEXT_GC) {
4286 gDdmHpifWhen = HPIF_WHEN_NEVER;
4287 }
4288 }
4289
4290 /*
4291 * Chunk HPIF (client --> server)
4292 *
4293 * Heap Info. General information about the heap,
4294 * suitable for a summary display.
4295 *
4296 * [u4]: number of heaps
4297 *
4298 * For each heap:
4299 * [u4]: heap ID
4300 * [u8]: timestamp in ms since Unix epoch
4301 * [u1]: capture reason (same as 'when' value from server)
4302 * [u4]: max heap size in bytes (-Xmx)
4303 * [u4]: current heap size in bytes
4304 * [u4]: current number of bytes allocated
4305 * [u4]: current number of objects allocated
4306 */
4307 uint8_t heap_count = 1;
Ian Rogers1d54e732013-05-02 21:10:01 -07004308 gc::Heap* heap = Runtime::Current()->GetHeap();
Elliott Hughes21f32d72011-11-09 17:44:13 -08004309 std::vector<uint8_t> bytes;
Elliott Hughes545a0642011-11-08 19:10:03 -08004310 JDWP::Append4BE(bytes, heap_count);
Brian Carlstrom7934ac22013-07-26 10:54:15 -07004311 JDWP::Append4BE(bytes, 1); // Heap id (bogus; we only have one heap).
Elliott Hughes545a0642011-11-08 19:10:03 -08004312 JDWP::Append8BE(bytes, MilliTime());
4313 JDWP::Append1BE(bytes, reason);
Brian Carlstrom7934ac22013-07-26 10:54:15 -07004314 JDWP::Append4BE(bytes, heap->GetMaxMemory()); // Max allowed heap size in bytes.
4315 JDWP::Append4BE(bytes, heap->GetTotalMemory()); // Current heap size in bytes.
Elliott Hughesb3bd5f02012-03-08 21:05:27 -08004316 JDWP::Append4BE(bytes, heap->GetBytesAllocated());
4317 JDWP::Append4BE(bytes, heap->GetObjectsAllocated());
Elliott Hughes21f32d72011-11-09 17:44:13 -08004318 CHECK_EQ(bytes.size(), 4U + (heap_count * (4 + 8 + 1 + 4 + 4 + 4 + 4)));
4319 Dbg::DdmSendChunk(CHUNK_TYPE("HPIF"), bytes);
Elliott Hughes767a1472011-10-26 18:49:02 -07004320}
4321
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004322enum HpsgSolidity {
4323 SOLIDITY_FREE = 0,
4324 SOLIDITY_HARD = 1,
4325 SOLIDITY_SOFT = 2,
4326 SOLIDITY_WEAK = 3,
4327 SOLIDITY_PHANTOM = 4,
4328 SOLIDITY_FINALIZABLE = 5,
4329 SOLIDITY_SWEEP = 6,
4330};
4331
4332enum HpsgKind {
4333 KIND_OBJECT = 0,
4334 KIND_CLASS_OBJECT = 1,
4335 KIND_ARRAY_1 = 2,
4336 KIND_ARRAY_2 = 3,
4337 KIND_ARRAY_4 = 4,
4338 KIND_ARRAY_8 = 5,
4339 KIND_UNKNOWN = 6,
4340 KIND_NATIVE = 7,
4341};
4342
4343#define HPSG_PARTIAL (1<<7)
4344#define HPSG_STATE(solidity, kind) ((uint8_t)((((kind) & 0x7) << 3) | ((solidity) & 0x7)))
4345
Ian Rogers30fab402012-01-23 15:43:46 -08004346class HeapChunkContext {
4347 public:
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004348 // Maximum chunk size. Obtain this from the formula:
4349 // (((maximum_heap_size / ALLOCATION_UNIT_SIZE) + 255) / 256) * 2
4350 HeapChunkContext(bool merge, bool native)
Ian Rogers30fab402012-01-23 15:43:46 -08004351 : buf_(16384 - 16),
4352 type_(0),
Mathieu Chartier36dab362014-07-30 14:59:56 -07004353 chunk_overhead_(0) {
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004354 Reset();
4355 if (native) {
Ian Rogers30fab402012-01-23 15:43:46 -08004356 type_ = CHUNK_TYPE("NHSG");
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004357 } else {
Ian Rogers30fab402012-01-23 15:43:46 -08004358 type_ = merge ? CHUNK_TYPE("HPSG") : CHUNK_TYPE("HPSO");
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004359 }
4360 }
4361
4362 ~HeapChunkContext() {
Ian Rogers30fab402012-01-23 15:43:46 -08004363 if (p_ > &buf_[0]) {
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004364 Flush();
4365 }
4366 }
4367
Mathieu Chartier36dab362014-07-30 14:59:56 -07004368 void SetChunkOverhead(size_t chunk_overhead) {
4369 chunk_overhead_ = chunk_overhead;
4370 }
4371
4372 void ResetStartOfNextChunk() {
4373 startOfNextMemoryChunk_ = nullptr;
4374 }
4375
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004376 void EnsureHeader(const void* chunk_ptr) {
Ian Rogers30fab402012-01-23 15:43:46 -08004377 if (!needHeader_) {
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004378 return;
4379 }
4380
4381 // Start a new HPSx chunk.
Brian Carlstrom7934ac22013-07-26 10:54:15 -07004382 JDWP::Write4BE(&p_, 1); // Heap id (bogus; we only have one heap).
4383 JDWP::Write1BE(&p_, 8); // Size of allocation unit, in bytes.
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004384
Brian Carlstrom7934ac22013-07-26 10:54:15 -07004385 JDWP::Write4BE(&p_, reinterpret_cast<uintptr_t>(chunk_ptr)); // virtual address of segment start.
4386 JDWP::Write4BE(&p_, 0); // offset of this piece (relative to the virtual address).
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004387 // [u4]: length of piece, in allocation units
4388 // 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 -08004389 pieceLenField_ = p_;
4390 JDWP::Write4BE(&p_, 0x55555555);
4391 needHeader_ = false;
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004392 }
4393
Ian Rogersb726dcb2012-09-05 08:57:23 -07004394 void Flush() SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Ian Rogersc0542af2014-09-03 16:16:56 -07004395 if (pieceLenField_ == nullptr) {
Ian Rogersd636b062013-01-18 17:51:18 -08004396 // Flush immediately post Reset (maybe back-to-back Flush). Ignore.
4397 CHECK(needHeader_);
4398 return;
4399 }
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004400 // Patch the "length of piece" field.
Ian Rogers30fab402012-01-23 15:43:46 -08004401 CHECK_LE(&buf_[0], pieceLenField_);
4402 CHECK_LE(pieceLenField_, p_);
4403 JDWP::Set4BE(pieceLenField_, totalAllocationUnits_);
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004404
Ian Rogers30fab402012-01-23 15:43:46 -08004405 Dbg::DdmSendChunk(type_, p_ - &buf_[0], &buf_[0]);
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004406 Reset();
4407 }
4408
Mathieu Chartierbc689b72014-12-14 17:01:31 -08004409 static void HeapChunkJavaCallback(void* start, void* end, size_t used_bytes, void* arg)
Ian Rogersb726dcb2012-09-05 08:57:23 -07004410 SHARED_LOCKS_REQUIRED(Locks::heap_bitmap_lock_,
4411 Locks::mutator_lock_) {
Mathieu Chartierbc689b72014-12-14 17:01:31 -08004412 reinterpret_cast<HeapChunkContext*>(arg)->HeapChunkJavaCallback(start, end, used_bytes);
4413 }
4414
4415 static void HeapChunkNativeCallback(void* start, void* end, size_t used_bytes, void* arg)
4416 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
4417 reinterpret_cast<HeapChunkContext*>(arg)->HeapChunkNativeCallback(start, end, used_bytes);
Elliott Hughesa2155262011-11-16 16:26:58 -08004418 }
4419
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004420 private:
Elliott Hughesa2155262011-11-16 16:26:58 -08004421 enum { ALLOCATION_UNIT_SIZE = 8 };
4422
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004423 void Reset() {
Ian Rogers30fab402012-01-23 15:43:46 -08004424 p_ = &buf_[0];
Mathieu Chartier36dab362014-07-30 14:59:56 -07004425 ResetStartOfNextChunk();
Ian Rogers30fab402012-01-23 15:43:46 -08004426 totalAllocationUnits_ = 0;
4427 needHeader_ = true;
Ian Rogersc0542af2014-09-03 16:16:56 -07004428 pieceLenField_ = nullptr;
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004429 }
4430
Mathieu Chartierbc689b72014-12-14 17:01:31 -08004431 bool IsNative() const {
4432 return type_ == CHUNK_TYPE("NHSG");
4433 }
4434
4435 // Returns true if the object is not an empty chunk.
4436 bool ProcessRecord(void* start, size_t used_bytes) SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Ian Rogers30fab402012-01-23 15:43:46 -08004437 // Note: heap call backs cannot manipulate the heap upon which they are crawling, care is taken
4438 // in the following code not to allocate memory, by ensuring buf_ is of the correct size
Ian Rogers15bf2d32012-08-28 17:33:04 -07004439 if (used_bytes == 0) {
Mathieu Chartierbc689b72014-12-14 17:01:31 -08004440 if (start == nullptr) {
4441 // Reset for start of new heap.
4442 startOfNextMemoryChunk_ = nullptr;
4443 Flush();
4444 }
4445 // Only process in use memory so that free region information
4446 // also includes dlmalloc book keeping.
4447 return false;
Elliott Hughesa2155262011-11-16 16:26:58 -08004448 }
Ian Rogersc0542af2014-09-03 16:16:56 -07004449 if (startOfNextMemoryChunk_ != nullptr) {
Mathieu Chartierbc689b72014-12-14 17:01:31 -08004450 // Transmit any pending free memory. Native free memory of over kMaxFreeLen could be because
4451 // of the use of mmaps, so don't report. If not free memory then start a new segment.
4452 bool flush = true;
4453 if (start > startOfNextMemoryChunk_) {
4454 const size_t kMaxFreeLen = 2 * kPageSize;
4455 void* free_start = startOfNextMemoryChunk_;
4456 void* free_end = start;
4457 const size_t free_len =
4458 reinterpret_cast<uintptr_t>(free_end) - reinterpret_cast<uintptr_t>(free_start);
4459 if (!IsNative() || free_len < kMaxFreeLen) {
4460 AppendChunk(HPSG_STATE(SOLIDITY_FREE, 0), free_start, free_len, IsNative());
4461 flush = false;
Ian Rogers15bf2d32012-08-28 17:33:04 -07004462 }
Mathieu Chartierbc689b72014-12-14 17:01:31 -08004463 }
4464 if (flush) {
4465 startOfNextMemoryChunk_ = nullptr;
4466 Flush();
4467 }
Ian Rogers15bf2d32012-08-28 17:33:04 -07004468 }
Mathieu Chartierbc689b72014-12-14 17:01:31 -08004469 return true;
Ian Rogers15bf2d32012-08-28 17:33:04 -07004470 }
Elliott Hughesa2155262011-11-16 16:26:58 -08004471
Mathieu Chartierbc689b72014-12-14 17:01:31 -08004472 void HeapChunkNativeCallback(void* start, void* /*end*/, size_t used_bytes)
4473 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
4474 if (ProcessRecord(start, used_bytes)) {
4475 uint8_t state = ExamineNativeObject(start);
4476 AppendChunk(state, start, used_bytes + chunk_overhead_, true /*is_native*/);
4477 startOfNextMemoryChunk_ = reinterpret_cast<char*>(start) + used_bytes + chunk_overhead_;
4478 }
4479 }
4480
4481 void HeapChunkJavaCallback(void* start, void* /*end*/, size_t used_bytes)
4482 SHARED_LOCKS_REQUIRED(Locks::heap_bitmap_lock_, Locks::mutator_lock_) {
4483 if (ProcessRecord(start, used_bytes)) {
4484 // Determine the type of this chunk.
4485 // OLD-TODO: if context.merge, see if this chunk is different from the last chunk.
4486 // If it's the same, we should combine them.
4487 uint8_t state = ExamineJavaObject(reinterpret_cast<mirror::Object*>(start));
4488 AppendChunk(state, start, used_bytes + chunk_overhead_, false /*is_native*/);
4489 startOfNextMemoryChunk_ = reinterpret_cast<char*>(start) + used_bytes + chunk_overhead_;
4490 }
4491 }
4492
4493 void AppendChunk(uint8_t state, void* ptr, size_t length, bool is_native)
Ian Rogersb726dcb2012-09-05 08:57:23 -07004494 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Ian Rogers15bf2d32012-08-28 17:33:04 -07004495 // Make sure there's enough room left in the buffer.
4496 // We need to use two bytes for every fractional 256 allocation units used by the chunk plus
4497 // 17 bytes for any header.
Mathieu Chartierbc689b72014-12-14 17:01:31 -08004498 const size_t needed = ((RoundUp(length / ALLOCATION_UNIT_SIZE, 256) / 256) * 2) + 17;
4499 size_t byte_left = &buf_.back() - p_;
4500 if (byte_left < needed) {
4501 if (is_native) {
Pavel Vyssotski7522c742014-12-08 13:38:26 +06004502 // Cannot trigger memory allocation while walking native heap.
Pavel Vyssotski7522c742014-12-08 13:38:26 +06004503 return;
4504 }
Ian Rogers15bf2d32012-08-28 17:33:04 -07004505 Flush();
4506 }
4507
Mathieu Chartierbc689b72014-12-14 17:01:31 -08004508 byte_left = &buf_.back() - p_;
4509 if (byte_left < needed) {
Ian Rogers15bf2d32012-08-28 17:33:04 -07004510 LOG(WARNING) << "Chunk is too big to transmit (chunk_len=" << length << ", "
4511 << needed << " bytes)";
4512 return;
4513 }
4514 EnsureHeader(ptr);
Elliott Hughesa2155262011-11-16 16:26:58 -08004515 // Write out the chunk description.
Ian Rogers15bf2d32012-08-28 17:33:04 -07004516 length /= ALLOCATION_UNIT_SIZE; // Convert to allocation units.
4517 totalAllocationUnits_ += length;
4518 while (length > 256) {
Ian Rogers30fab402012-01-23 15:43:46 -08004519 *p_++ = state | HPSG_PARTIAL;
4520 *p_++ = 255; // length - 1
Ian Rogers15bf2d32012-08-28 17:33:04 -07004521 length -= 256;
Elliott Hughesa2155262011-11-16 16:26:58 -08004522 }
Ian Rogers30fab402012-01-23 15:43:46 -08004523 *p_++ = state;
Ian Rogers15bf2d32012-08-28 17:33:04 -07004524 *p_++ = length - 1;
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004525 }
4526
Mathieu Chartierbc689b72014-12-14 17:01:31 -08004527 uint8_t ExamineNativeObject(const void* p) SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
4528 return p == nullptr ? HPSG_STATE(SOLIDITY_FREE, 0) : HPSG_STATE(SOLIDITY_HARD, KIND_NATIVE);
4529 }
4530
4531 uint8_t ExamineJavaObject(mirror::Object* o)
Ian Rogersef7d42f2014-01-06 12:55:46 -08004532 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_, Locks::heap_bitmap_lock_) {
Ian Rogersc0542af2014-09-03 16:16:56 -07004533 if (o == nullptr) {
Elliott Hughesa2155262011-11-16 16:26:58 -08004534 return HPSG_STATE(SOLIDITY_FREE, 0);
4535 }
Elliott Hughesa2155262011-11-16 16:26:58 -08004536 // It's an allocated chunk. Figure out what it is.
Mathieu Chartierbc689b72014-12-14 17:01:31 -08004537 gc::Heap* heap = Runtime::Current()->GetHeap();
4538 if (!heap->IsLiveObjectLocked(o)) {
4539 LOG(ERROR) << "Invalid object in managed heap: " << o;
Elliott Hughesa2155262011-11-16 16:26:58 -08004540 return HPSG_STATE(SOLIDITY_HARD, KIND_NATIVE);
4541 }
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08004542 mirror::Class* c = o->GetClass();
Ian Rogersc0542af2014-09-03 16:16:56 -07004543 if (c == nullptr) {
Elliott Hughesa2155262011-11-16 16:26:58 -08004544 // The object was probably just created but hasn't been initialized yet.
4545 return HPSG_STATE(SOLIDITY_HARD, KIND_OBJECT);
4546 }
Mathieu Chartierbc689b72014-12-14 17:01:31 -08004547 if (!heap->IsValidObjectAddress(c)) {
Ian Rogers15bf2d32012-08-28 17:33:04 -07004548 LOG(ERROR) << "Invalid class for managed heap object: " << o << " " << c;
Elliott Hughesa2155262011-11-16 16:26:58 -08004549 return HPSG_STATE(SOLIDITY_HARD, KIND_UNKNOWN);
4550 }
Mathieu Chartierf26e1b32015-01-29 10:47:10 -08004551 if (c->GetClass() == nullptr) {
4552 LOG(ERROR) << "Null class of class " << c << " for object " << o;
4553 return HPSG_STATE(SOLIDITY_HARD, KIND_UNKNOWN);
4554 }
Elliott Hughesa2155262011-11-16 16:26:58 -08004555 if (c->IsClassClass()) {
4556 return HPSG_STATE(SOLIDITY_HARD, KIND_CLASS_OBJECT);
4557 }
Elliott Hughesa2155262011-11-16 16:26:58 -08004558 if (c->IsArrayClass()) {
Elliott Hughesa2155262011-11-16 16:26:58 -08004559 switch (c->GetComponentSize()) {
4560 case 1: return HPSG_STATE(SOLIDITY_HARD, KIND_ARRAY_1);
4561 case 2: return HPSG_STATE(SOLIDITY_HARD, KIND_ARRAY_2);
4562 case 4: return HPSG_STATE(SOLIDITY_HARD, KIND_ARRAY_4);
4563 case 8: return HPSG_STATE(SOLIDITY_HARD, KIND_ARRAY_8);
4564 }
4565 }
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004566 return HPSG_STATE(SOLIDITY_HARD, KIND_OBJECT);
4567 }
4568
Ian Rogers30fab402012-01-23 15:43:46 -08004569 std::vector<uint8_t> buf_;
4570 uint8_t* p_;
4571 uint8_t* pieceLenField_;
Ian Rogers15bf2d32012-08-28 17:33:04 -07004572 void* startOfNextMemoryChunk_;
Ian Rogers30fab402012-01-23 15:43:46 -08004573 size_t totalAllocationUnits_;
4574 uint32_t type_;
Ian Rogers30fab402012-01-23 15:43:46 -08004575 bool needHeader_;
Mathieu Chartier36dab362014-07-30 14:59:56 -07004576 size_t chunk_overhead_;
Ian Rogers30fab402012-01-23 15:43:46 -08004577
Elliott Hughesa2155262011-11-16 16:26:58 -08004578 DISALLOW_COPY_AND_ASSIGN(HeapChunkContext);
4579};
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004580
Mathieu Chartier36dab362014-07-30 14:59:56 -07004581static void BumpPointerSpaceCallback(mirror::Object* obj, void* arg)
4582 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) EXCLUSIVE_LOCKS_REQUIRED(Locks::heap_bitmap_lock_) {
4583 const size_t size = RoundUp(obj->SizeOf(), kObjectAlignment);
Mathieu Chartierbc689b72014-12-14 17:01:31 -08004584 HeapChunkContext::HeapChunkJavaCallback(
Mathieu Chartier36dab362014-07-30 14:59:56 -07004585 obj, reinterpret_cast<void*>(reinterpret_cast<uintptr_t>(obj) + size), size, arg);
4586}
4587
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004588void Dbg::DdmSendHeapSegments(bool native) {
Mathieu Chartierbc689b72014-12-14 17:01:31 -08004589 Dbg::HpsgWhen when = native ? gDdmNhsgWhen : gDdmHpsgWhen;
4590 Dbg::HpsgWhat what = native ? gDdmNhsgWhat : gDdmHpsgWhat;
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004591 if (when == HPSG_WHEN_NEVER) {
4592 return;
4593 }
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004594 // Figure out what kind of chunks we'll be sending.
Mathieu Chartierbc689b72014-12-14 17:01:31 -08004595 CHECK(what == HPSG_WHAT_MERGED_OBJECTS || what == HPSG_WHAT_DISTINCT_OBJECTS)
4596 << static_cast<int>(what);
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004597
4598 // First, send a heap start chunk.
4599 uint8_t heap_id[4];
Brian Carlstrom7934ac22013-07-26 10:54:15 -07004600 JDWP::Set4BE(&heap_id[0], 1); // Heap id (bogus; we only have one heap).
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004601 Dbg::DdmSendChunk(native ? CHUNK_TYPE("NHST") : CHUNK_TYPE("HPST"), sizeof(heap_id), heap_id);
Hiroshi Yamauchicf58d4a2013-09-26 14:21:22 -07004602 Thread* self = Thread::Current();
Hiroshi Yamauchicf58d4a2013-09-26 14:21:22 -07004603 Locks::mutator_lock_->AssertSharedHeld(self);
Hiroshi Yamauchicf58d4a2013-09-26 14:21:22 -07004604
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004605 // Send a series of heap segment chunks.
Mathieu Chartierbc689b72014-12-14 17:01:31 -08004606 HeapChunkContext context(what == HPSG_WHAT_MERGED_OBJECTS, native);
Elliott Hughesa2155262011-11-16 16:26:58 -08004607 if (native) {
Ian Rogers872dd822014-10-30 11:19:14 -07004608#if defined(HAVE_ANDROID_OS) && defined(USE_DLMALLOC)
Mathieu Chartierbc689b72014-12-14 17:01:31 -08004609 dlmalloc_inspect_all(HeapChunkContext::HeapChunkNativeCallback, &context);
4610 HeapChunkContext::HeapChunkNativeCallback(nullptr, nullptr, 0, &context); // Indicate end of a space.
Christopher Ferrisc4ddc042014-05-13 14:47:50 -07004611#else
4612 UNIMPLEMENTED(WARNING) << "Native heap inspection is only supported with dlmalloc";
4613#endif
Elliott Hughesa2155262011-11-16 16:26:58 -08004614 } else {
Ian Rogers1d54e732013-05-02 21:10:01 -07004615 gc::Heap* heap = Runtime::Current()->GetHeap();
Mathieu Chartier36dab362014-07-30 14:59:56 -07004616 for (const auto& space : heap->GetContinuousSpaces()) {
4617 if (space->IsDlMallocSpace()) {
Mathieu Chartier4c69d7f2014-10-10 12:45:50 -07004618 ReaderMutexLock mu(self, *Locks::heap_bitmap_lock_);
Mathieu Chartier36dab362014-07-30 14:59:56 -07004619 // dlmalloc's chunk header is 2 * sizeof(size_t), but if the previous chunk is in use for an
4620 // allocation then the first sizeof(size_t) may belong to it.
4621 context.SetChunkOverhead(sizeof(size_t));
Mathieu Chartierbc689b72014-12-14 17:01:31 -08004622 space->AsDlMallocSpace()->Walk(HeapChunkContext::HeapChunkJavaCallback, &context);
Mathieu Chartier36dab362014-07-30 14:59:56 -07004623 } else if (space->IsRosAllocSpace()) {
4624 context.SetChunkOverhead(0);
Mathieu Chartier4c69d7f2014-10-10 12:45:50 -07004625 // Need to acquire the mutator lock before the heap bitmap lock with exclusive access since
4626 // RosAlloc's internal logic doesn't know to release and reacquire the heap bitmap lock.
4627 self->TransitionFromRunnableToSuspended(kSuspended);
4628 ThreadList* tl = Runtime::Current()->GetThreadList();
Mathieu Chartierbf9fc582015-03-13 17:21:25 -07004629 tl->SuspendAll(__FUNCTION__);
Mathieu Chartier4c69d7f2014-10-10 12:45:50 -07004630 {
4631 ReaderMutexLock mu(self, *Locks::heap_bitmap_lock_);
Mathieu Chartierbc689b72014-12-14 17:01:31 -08004632 space->AsRosAllocSpace()->Walk(HeapChunkContext::HeapChunkJavaCallback, &context);
Mathieu Chartier4c69d7f2014-10-10 12:45:50 -07004633 }
4634 tl->ResumeAll();
4635 self->TransitionFromSuspendedToRunnable();
Mathieu Chartier36dab362014-07-30 14:59:56 -07004636 } else if (space->IsBumpPointerSpace()) {
Mathieu Chartier4c69d7f2014-10-10 12:45:50 -07004637 ReaderMutexLock mu(self, *Locks::heap_bitmap_lock_);
Mathieu Chartier36dab362014-07-30 14:59:56 -07004638 context.SetChunkOverhead(0);
Mathieu Chartier36dab362014-07-30 14:59:56 -07004639 space->AsBumpPointerSpace()->Walk(BumpPointerSpaceCallback, &context);
Mathieu Chartierbc689b72014-12-14 17:01:31 -08004640 HeapChunkContext::HeapChunkJavaCallback(nullptr, nullptr, 0, &context);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08004641 } else if (space->IsRegionSpace()) {
4642 heap->IncrementDisableMovingGC(self);
4643 self->TransitionFromRunnableToSuspended(kSuspended);
4644 ThreadList* tl = Runtime::Current()->GetThreadList();
Mathieu Chartierbf9fc582015-03-13 17:21:25 -07004645 tl->SuspendAll(__FUNCTION__);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08004646 ReaderMutexLock mu(self, *Locks::heap_bitmap_lock_);
4647 context.SetChunkOverhead(0);
4648 space->AsRegionSpace()->Walk(BumpPointerSpaceCallback, &context);
4649 HeapChunkContext::HeapChunkJavaCallback(nullptr, nullptr, 0, &context);
4650 tl->ResumeAll();
4651 self->TransitionFromSuspendedToRunnable();
4652 heap->DecrementDisableMovingGC(self);
Mathieu Chartier36dab362014-07-30 14:59:56 -07004653 } else {
4654 UNIMPLEMENTED(WARNING) << "Not counting objects in space " << *space;
Mathieu Chartierb062fdd2012-07-03 09:51:48 -07004655 }
Mathieu Chartier36dab362014-07-30 14:59:56 -07004656 context.ResetStartOfNextChunk();
Mathieu Chartierb062fdd2012-07-03 09:51:48 -07004657 }
Mathieu Chartier4c69d7f2014-10-10 12:45:50 -07004658 ReaderMutexLock mu(self, *Locks::heap_bitmap_lock_);
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -07004659 // Walk the large objects, these are not in the AllocSpace.
Mathieu Chartier36dab362014-07-30 14:59:56 -07004660 context.SetChunkOverhead(0);
Mathieu Chartierbc689b72014-12-14 17:01:31 -08004661 heap->GetLargeObjectsSpace()->Walk(HeapChunkContext::HeapChunkJavaCallback, &context);
Elliott Hughesa2155262011-11-16 16:26:58 -08004662 }
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004663
4664 // Finally, send a heap end chunk.
4665 Dbg::DdmSendChunk(native ? CHUNK_TYPE("NHEN") : CHUNK_TYPE("HPEN"), sizeof(heap_id), heap_id);
Elliott Hughes767a1472011-10-26 18:49:02 -07004666}
4667
Elliott Hughesb1a58792013-07-11 18:10:58 -07004668static size_t GetAllocTrackerMax() {
4669#ifdef HAVE_ANDROID_OS
4670 // Check whether there's a system property overriding the number of records.
4671 const char* propertyName = "dalvik.vm.allocTrackerMax";
4672 char allocRecordMaxString[PROPERTY_VALUE_MAX];
4673 if (property_get(propertyName, allocRecordMaxString, "") > 0) {
4674 char* end;
4675 size_t value = strtoul(allocRecordMaxString, &end, 10);
4676 if (*end != '\0') {
Ruben Brunk3e47a742013-09-09 17:56:07 -07004677 LOG(ERROR) << "Ignoring " << propertyName << " '" << allocRecordMaxString
4678 << "' --- invalid";
Elliott Hughesb1a58792013-07-11 18:10:58 -07004679 return kDefaultNumAllocRecords;
4680 }
4681 if (!IsPowerOfTwo(value)) {
Ruben Brunk3e47a742013-09-09 17:56:07 -07004682 LOG(ERROR) << "Ignoring " << propertyName << " '" << allocRecordMaxString
4683 << "' --- not power of two";
Elliott Hughesb1a58792013-07-11 18:10:58 -07004684 return kDefaultNumAllocRecords;
4685 }
4686 return value;
4687 }
4688#endif
4689 return kDefaultNumAllocRecords;
4690}
4691
Brian Carlstrom306db812014-09-05 13:01:41 -07004692void Dbg::SetAllocTrackingEnabled(bool enable) {
4693 Thread* self = Thread::Current();
4694 if (enable) {
Sebastien Hertzb98063a2014-03-26 10:57:20 +01004695 {
Brian Carlstrom306db812014-09-05 13:01:41 -07004696 MutexLock mu(self, *Locks::alloc_tracker_lock_);
4697 if (recent_allocation_records_ != nullptr) {
4698 return; // Already enabled, bail.
Sebastien Hertzb98063a2014-03-26 10:57:20 +01004699 }
Brian Carlstrom306db812014-09-05 13:01:41 -07004700 alloc_record_max_ = GetAllocTrackerMax();
4701 LOG(INFO) << "Enabling alloc tracker (" << alloc_record_max_ << " entries of "
4702 << kMaxAllocRecordStackDepth << " frames, taking "
4703 << PrettySize(sizeof(AllocRecord) * alloc_record_max_) << ")";
4704 DCHECK_EQ(alloc_record_head_, 0U);
4705 DCHECK_EQ(alloc_record_count_, 0U);
4706 recent_allocation_records_ = new AllocRecord[alloc_record_max_];
4707 CHECK(recent_allocation_records_ != nullptr);
Elliott Hughes545a0642011-11-08 19:10:03 -08004708 }
Mathieu Chartier9ef78b52014-09-25 17:03:12 -07004709 Runtime::Current()->GetInstrumentation()->InstrumentQuickAllocEntryPoints();
Elliott Hughes545a0642011-11-08 19:10:03 -08004710 } else {
Sebastien Hertzb98063a2014-03-26 10:57:20 +01004711 {
Brian Carlstrom306db812014-09-05 13:01:41 -07004712 ScopedObjectAccess soa(self); // For type_cache_.Clear();
4713 MutexLock mu(self, *Locks::alloc_tracker_lock_);
4714 if (recent_allocation_records_ == nullptr) {
4715 return; // Already disabled, bail.
4716 }
Mathieu Chartier4345c462014-06-27 10:20:14 -07004717 LOG(INFO) << "Disabling alloc tracker";
Sebastien Hertzb98063a2014-03-26 10:57:20 +01004718 delete[] recent_allocation_records_;
Ian Rogersc0542af2014-09-03 16:16:56 -07004719 recent_allocation_records_ = nullptr;
Brian Carlstrom306db812014-09-05 13:01:41 -07004720 alloc_record_head_ = 0;
4721 alloc_record_count_ = 0;
Mathieu Chartier4345c462014-06-27 10:20:14 -07004722 type_cache_.Clear();
Sebastien Hertzb98063a2014-03-26 10:57:20 +01004723 }
Brian Carlstrom306db812014-09-05 13:01:41 -07004724 // If an allocation comes in before we uninstrument, we will safely drop it on the floor.
Mathieu Chartier9ef78b52014-09-25 17:03:12 -07004725 Runtime::Current()->GetInstrumentation()->UninstrumentQuickAllocEntryPoints();
Elliott Hughes545a0642011-11-08 19:10:03 -08004726 }
4727}
4728
Ian Rogers0399dde2012-06-06 17:09:28 -07004729struct AllocRecordStackVisitor : public StackVisitor {
Andreas Gampe277ccbd2014-11-03 21:36:10 -08004730 AllocRecordStackVisitor(Thread* thread, AllocRecord* record_in)
Ian Rogersb726dcb2012-09-05 08:57:23 -07004731 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_)
Nicolas Geoffray8e5bd182015-05-06 11:34:34 +01004732 : StackVisitor(thread, nullptr, StackVisitor::StackWalkKind::kIncludeInlinedFrames),
4733 record(record_in),
4734 depth(0) {}
Elliott Hughes545a0642011-11-08 19:10:03 -08004735
Ian Rogers00f7d0e2012-07-19 15:28:27 -07004736 // TODO: Enable annotalysis. We know lock is held in constructor, but abstraction confuses
4737 // annotalysis.
4738 bool VisitFrame() NO_THREAD_SAFETY_ANALYSIS {
Elliott Hughes545a0642011-11-08 19:10:03 -08004739 if (depth >= kMaxAllocRecordStackDepth) {
Elliott Hughes530fa002012-03-12 11:44:49 -07004740 return false;
Elliott Hughes545a0642011-11-08 19:10:03 -08004741 }
Mathieu Chartiere401d142015-04-22 13:56:20 -07004742 ArtMethod* m = GetMethod();
Ian Rogers0399dde2012-06-06 17:09:28 -07004743 if (!m->IsRuntimeMethod()) {
Hiroshi Yamauchib5a9e3d2014-06-09 12:11:20 -07004744 record->StackElement(depth)->SetMethod(m);
4745 record->StackElement(depth)->SetDexPc(GetDexPc());
Elliott Hughes530fa002012-03-12 11:44:49 -07004746 ++depth;
Elliott Hughes545a0642011-11-08 19:10:03 -08004747 }
Elliott Hughes530fa002012-03-12 11:44:49 -07004748 return true;
Elliott Hughes545a0642011-11-08 19:10:03 -08004749 }
4750
4751 ~AllocRecordStackVisitor() {
4752 // Clear out any unused stack trace elements.
4753 for (; depth < kMaxAllocRecordStackDepth; ++depth) {
Hiroshi Yamauchib5a9e3d2014-06-09 12:11:20 -07004754 record->StackElement(depth)->SetMethod(nullptr);
4755 record->StackElement(depth)->SetDexPc(0);
Elliott Hughes545a0642011-11-08 19:10:03 -08004756 }
4757 }
4758
4759 AllocRecord* record;
4760 size_t depth;
4761};
4762
Ian Rogers844506b2014-09-12 19:59:33 -07004763void Dbg::RecordAllocation(Thread* self, mirror::Class* type, size_t byte_count) {
Brian Carlstrom306db812014-09-05 13:01:41 -07004764 MutexLock mu(self, *Locks::alloc_tracker_lock_);
Ian Rogersc0542af2014-09-03 16:16:56 -07004765 if (recent_allocation_records_ == nullptr) {
Brian Carlstrom306db812014-09-05 13:01:41 -07004766 // In the process of shutting down recording, bail.
Elliott Hughes545a0642011-11-08 19:10:03 -08004767 return;
4768 }
4769
4770 // Advance and clip.
Ian Rogers719d1a32014-03-06 12:13:39 -08004771 if (++alloc_record_head_ == alloc_record_max_) {
4772 alloc_record_head_ = 0;
Elliott Hughes545a0642011-11-08 19:10:03 -08004773 }
4774
4775 // Fill in the basics.
Ian Rogers719d1a32014-03-06 12:13:39 -08004776 AllocRecord* record = &recent_allocation_records_[alloc_record_head_];
Hiroshi Yamauchib5a9e3d2014-06-09 12:11:20 -07004777 record->SetType(type);
4778 record->SetByteCount(byte_count);
4779 record->SetThinLockId(self->GetThreadId());
Elliott Hughes545a0642011-11-08 19:10:03 -08004780
4781 // Fill in the stack trace.
Ian Rogers7a22fa62013-01-23 12:16:16 -08004782 AllocRecordStackVisitor visitor(self, record);
Ian Rogers0399dde2012-06-06 17:09:28 -07004783 visitor.WalkStack();
Elliott Hughes545a0642011-11-08 19:10:03 -08004784
Ian Rogers719d1a32014-03-06 12:13:39 -08004785 if (alloc_record_count_ < alloc_record_max_) {
4786 ++alloc_record_count_;
Elliott Hughes545a0642011-11-08 19:10:03 -08004787 }
4788}
4789
Elliott Hughesa8f93cb2012-06-08 17:08:48 -07004790// Returns the index of the head element.
4791//
Brian Carlstrom306db812014-09-05 13:01:41 -07004792// We point at the most-recently-written record, so if alloc_record_count_ is 1
Elliott Hughesa8f93cb2012-06-08 17:08:48 -07004793// we want to use the current element. Take "head+1" and subtract count
4794// from it.
4795//
4796// We need to handle underflow in our circular buffer, so we add
Brian Carlstrom306db812014-09-05 13:01:41 -07004797// alloc_record_max_ and then mask it back down.
Ian Rogers719d1a32014-03-06 12:13:39 -08004798size_t Dbg::HeadIndex() {
4799 return (Dbg::alloc_record_head_ + 1 + Dbg::alloc_record_max_ - Dbg::alloc_record_count_) &
4800 (Dbg::alloc_record_max_ - 1);
Elliott Hughes545a0642011-11-08 19:10:03 -08004801}
4802
4803void Dbg::DumpRecentAllocations() {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07004804 ScopedObjectAccess soa(Thread::Current());
Brian Carlstrom306db812014-09-05 13:01:41 -07004805 MutexLock mu(soa.Self(), *Locks::alloc_tracker_lock_);
Ian Rogersc0542af2014-09-03 16:16:56 -07004806 if (recent_allocation_records_ == nullptr) {
Elliott Hughes545a0642011-11-08 19:10:03 -08004807 LOG(INFO) << "Not recording tracked allocations";
4808 return;
4809 }
4810
4811 // "i" is the head of the list. We want to start at the end of the
4812 // list and move forward to the tail.
Elliott Hughesa8f93cb2012-06-08 17:08:48 -07004813 size_t i = HeadIndex();
Brian Carlstrom306db812014-09-05 13:01:41 -07004814 const uint16_t capped_count = CappedAllocRecordCount(Dbg::alloc_record_count_);
4815 uint16_t count = capped_count;
Elliott Hughes545a0642011-11-08 19:10:03 -08004816
Ian Rogers719d1a32014-03-06 12:13:39 -08004817 LOG(INFO) << "Tracked allocations, (head=" << alloc_record_head_ << " count=" << count << ")";
Elliott Hughes545a0642011-11-08 19:10:03 -08004818 while (count--) {
4819 AllocRecord* record = &recent_allocation_records_[i];
4820
Hiroshi Yamauchib5a9e3d2014-06-09 12:11:20 -07004821 LOG(INFO) << StringPrintf(" Thread %-2d %6zd bytes ", record->ThinLockId(), record->ByteCount())
4822 << PrettyClass(record->Type());
Elliott Hughes545a0642011-11-08 19:10:03 -08004823
4824 for (size_t stack_frame = 0; stack_frame < kMaxAllocRecordStackDepth; ++stack_frame) {
Hiroshi Yamauchib5a9e3d2014-06-09 12:11:20 -07004825 AllocRecordStackTraceElement* stack_element = record->StackElement(stack_frame);
Mathieu Chartiere401d142015-04-22 13:56:20 -07004826 ArtMethod* m = stack_element->Method();
Ian Rogersc0542af2014-09-03 16:16:56 -07004827 if (m == nullptr) {
Elliott Hughes545a0642011-11-08 19:10:03 -08004828 break;
4829 }
Hiroshi Yamauchib5a9e3d2014-06-09 12:11:20 -07004830 LOG(INFO) << " " << PrettyMethod(m) << " line " << stack_element->LineNumber();
Elliott Hughes545a0642011-11-08 19:10:03 -08004831 }
4832
4833 // pause periodically to help logcat catch up
4834 if ((count % 5) == 0) {
4835 usleep(40000);
4836 }
4837
Ian Rogers719d1a32014-03-06 12:13:39 -08004838 i = (i + 1) & (alloc_record_max_ - 1);
Elliott Hughes545a0642011-11-08 19:10:03 -08004839 }
4840}
4841
4842class StringTable {
4843 public:
4844 StringTable() {
4845 }
4846
Mathieu Chartier4345c462014-06-27 10:20:14 -07004847 void Add(const std::string& str) {
4848 table_.insert(str);
4849 }
4850
4851 void Add(const char* str) {
4852 table_.insert(str);
Elliott Hughes545a0642011-11-08 19:10:03 -08004853 }
4854
Elliott Hughesa8f93cb2012-06-08 17:08:48 -07004855 size_t IndexOf(const char* s) const {
Mathieu Chartier02e25112013-08-14 16:14:24 -07004856 auto it = table_.find(s);
Elliott Hughesa8f93cb2012-06-08 17:08:48 -07004857 if (it == table_.end()) {
4858 LOG(FATAL) << "IndexOf(\"" << s << "\") failed";
4859 }
4860 return std::distance(table_.begin(), it);
Elliott Hughes545a0642011-11-08 19:10:03 -08004861 }
4862
Elliott Hughesa8f93cb2012-06-08 17:08:48 -07004863 size_t Size() const {
Elliott Hughes545a0642011-11-08 19:10:03 -08004864 return table_.size();
4865 }
4866
Elliott Hughesa8f93cb2012-06-08 17:08:48 -07004867 void WriteTo(std::vector<uint8_t>& bytes) const {
Mathieu Chartier02e25112013-08-14 16:14:24 -07004868 for (const std::string& str : table_) {
4869 const char* s = str.c_str();
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08004870 size_t s_len = CountModifiedUtf8Chars(s);
Christopher Ferris8a354052015-04-24 17:23:53 -07004871 std::unique_ptr<uint16_t[]> s_utf16(new uint16_t[s_len]);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08004872 ConvertModifiedUtf8ToUtf16(s_utf16.get(), s);
4873 JDWP::AppendUtf16BE(bytes, s_utf16.get(), s_len);
Elliott Hughes545a0642011-11-08 19:10:03 -08004874 }
4875 }
4876
4877 private:
Elliott Hughesa8f93cb2012-06-08 17:08:48 -07004878 std::set<std::string> table_;
Elliott Hughes545a0642011-11-08 19:10:03 -08004879 DISALLOW_COPY_AND_ASSIGN(StringTable);
4880};
4881
Mathieu Chartiere401d142015-04-22 13:56:20 -07004882static const char* GetMethodSourceFile(ArtMethod* method)
Sebastien Hertz280286a2014-04-28 09:26:50 +02004883 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07004884 DCHECK(method != nullptr);
4885 const char* source_file = method->GetDeclaringClassSourceFile();
Sebastien Hertz280286a2014-04-28 09:26:50 +02004886 return (source_file != nullptr) ? source_file : "";
4887}
4888
Elliott Hughes545a0642011-11-08 19:10:03 -08004889/*
4890 * The data we send to DDMS contains everything we have recorded.
4891 *
4892 * Message header (all values big-endian):
4893 * (1b) message header len (to allow future expansion); includes itself
4894 * (1b) entry header len
4895 * (1b) stack frame len
4896 * (2b) number of entries
4897 * (4b) offset to string table from start of message
4898 * (2b) number of class name strings
4899 * (2b) number of method name strings
4900 * (2b) number of source file name strings
4901 * For each entry:
4902 * (4b) total allocation size
Elliott Hughes221229c2013-01-08 18:17:50 -08004903 * (2b) thread id
Elliott Hughes545a0642011-11-08 19:10:03 -08004904 * (2b) allocated object's class name index
4905 * (1b) stack depth
4906 * For each stack frame:
4907 * (2b) method's class name
4908 * (2b) method name
4909 * (2b) method source file
4910 * (2b) line number, clipped to 32767; -2 if native; -1 if no source
4911 * (xb) class name strings
4912 * (xb) method name strings
4913 * (xb) source file strings
4914 *
4915 * As with other DDM traffic, strings are sent as a 4-byte length
4916 * followed by UTF-16 data.
4917 *
4918 * We send up 16-bit unsigned indexes into string tables. In theory there
Brian Carlstrom306db812014-09-05 13:01:41 -07004919 * can be (kMaxAllocRecordStackDepth * alloc_record_max_) unique strings in
Elliott Hughes545a0642011-11-08 19:10:03 -08004920 * each table, but in practice there should be far fewer.
4921 *
4922 * The chief reason for using a string table here is to keep the size of
4923 * the DDMS message to a minimum. This is partly to make the protocol
4924 * efficient, but also because we have to form the whole thing up all at
4925 * once in a memory buffer.
4926 *
4927 * We use separate string tables for class names, method names, and source
4928 * files to keep the indexes small. There will generally be no overlap
4929 * between the contents of these tables.
4930 */
4931jbyteArray Dbg::GetRecentAllocations() {
Ian Rogerscf7f1912014-10-22 22:06:39 -07004932 if ((false)) {
Elliott Hughes545a0642011-11-08 19:10:03 -08004933 DumpRecentAllocations();
4934 }
4935
Ian Rogers50b35e22012-10-04 10:09:15 -07004936 Thread* self = Thread::Current();
Elliott Hughes545a0642011-11-08 19:10:03 -08004937 std::vector<uint8_t> bytes;
Mathieu Chartier46e811b2013-07-10 17:09:14 -07004938 {
Brian Carlstrom306db812014-09-05 13:01:41 -07004939 MutexLock mu(self, *Locks::alloc_tracker_lock_);
Mathieu Chartier46e811b2013-07-10 17:09:14 -07004940 //
4941 // Part 1: generate string tables.
4942 //
4943 StringTable class_names;
4944 StringTable method_names;
4945 StringTable filenames;
Elliott Hughes545a0642011-11-08 19:10:03 -08004946
Brian Carlstrom306db812014-09-05 13:01:41 -07004947 const uint16_t capped_count = CappedAllocRecordCount(Dbg::alloc_record_count_);
4948 uint16_t count = capped_count;
4949 size_t idx = HeadIndex();
Mathieu Chartier46e811b2013-07-10 17:09:14 -07004950 while (count--) {
4951 AllocRecord* record = &recent_allocation_records_[idx];
Ian Rogers1ff3c982014-08-12 02:30:58 -07004952 std::string temp;
4953 class_names.Add(record->Type()->GetDescriptor(&temp));
Mathieu Chartier46e811b2013-07-10 17:09:14 -07004954 for (size_t i = 0; i < kMaxAllocRecordStackDepth; i++) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07004955 ArtMethod* m = record->StackElement(i)->Method();
Ian Rogersc0542af2014-09-03 16:16:56 -07004956 if (m != nullptr) {
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07004957 class_names.Add(m->GetDeclaringClassDescriptor());
4958 method_names.Add(m->GetName());
4959 filenames.Add(GetMethodSourceFile(m));
Mathieu Chartier46e811b2013-07-10 17:09:14 -07004960 }
4961 }
Elliott Hughes545a0642011-11-08 19:10:03 -08004962
Ian Rogers719d1a32014-03-06 12:13:39 -08004963 idx = (idx + 1) & (alloc_record_max_ - 1);
Elliott Hughes545a0642011-11-08 19:10:03 -08004964 }
4965
Brian Carlstrom306db812014-09-05 13:01:41 -07004966 LOG(INFO) << "allocation records: " << capped_count;
Mathieu Chartier46e811b2013-07-10 17:09:14 -07004967
4968 //
4969 // Part 2: Generate the output and store it in the buffer.
4970 //
4971
4972 // (1b) message header len (to allow future expansion); includes itself
4973 // (1b) entry header len
4974 // (1b) stack frame len
4975 const int kMessageHeaderLen = 15;
4976 const int kEntryHeaderLen = 9;
4977 const int kStackFrameLen = 8;
4978 JDWP::Append1BE(bytes, kMessageHeaderLen);
4979 JDWP::Append1BE(bytes, kEntryHeaderLen);
4980 JDWP::Append1BE(bytes, kStackFrameLen);
4981
4982 // (2b) number of entries
4983 // (4b) offset to string table from start of message
4984 // (2b) number of class name strings
4985 // (2b) number of method name strings
4986 // (2b) number of source file name strings
Brian Carlstrom306db812014-09-05 13:01:41 -07004987 JDWP::Append2BE(bytes, capped_count);
Mathieu Chartier46e811b2013-07-10 17:09:14 -07004988 size_t string_table_offset = bytes.size();
Brian Carlstrom7934ac22013-07-26 10:54:15 -07004989 JDWP::Append4BE(bytes, 0); // We'll patch this later...
Mathieu Chartier46e811b2013-07-10 17:09:14 -07004990 JDWP::Append2BE(bytes, class_names.Size());
4991 JDWP::Append2BE(bytes, method_names.Size());
4992 JDWP::Append2BE(bytes, filenames.Size());
4993
Mathieu Chartier46e811b2013-07-10 17:09:14 -07004994 idx = HeadIndex();
Ian Rogers1ff3c982014-08-12 02:30:58 -07004995 std::string temp;
Brian Carlstrom306db812014-09-05 13:01:41 -07004996 for (count = capped_count; count != 0; --count) {
Mathieu Chartier46e811b2013-07-10 17:09:14 -07004997 // For each entry:
4998 // (4b) total allocation size
4999 // (2b) thread id
5000 // (2b) allocated object's class name index
5001 // (1b) stack depth
5002 AllocRecord* record = &recent_allocation_records_[idx];
5003 size_t stack_depth = record->GetDepth();
Mathieu Chartierf8322842014-05-16 10:59:25 -07005004 size_t allocated_object_class_name_index =
Ian Rogers1ff3c982014-08-12 02:30:58 -07005005 class_names.IndexOf(record->Type()->GetDescriptor(&temp));
Hiroshi Yamauchib5a9e3d2014-06-09 12:11:20 -07005006 JDWP::Append4BE(bytes, record->ByteCount());
5007 JDWP::Append2BE(bytes, record->ThinLockId());
Mathieu Chartier46e811b2013-07-10 17:09:14 -07005008 JDWP::Append2BE(bytes, allocated_object_class_name_index);
5009 JDWP::Append1BE(bytes, stack_depth);
5010
Mathieu Chartier46e811b2013-07-10 17:09:14 -07005011 for (size_t stack_frame = 0; stack_frame < stack_depth; ++stack_frame) {
5012 // For each stack frame:
5013 // (2b) method's class name
5014 // (2b) method name
5015 // (2b) method source file
5016 // (2b) line number, clipped to 32767; -2 if native; -1 if no source
Mathieu Chartiere401d142015-04-22 13:56:20 -07005017 ArtMethod* m = record->StackElement(stack_frame)->Method();
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07005018 size_t class_name_index = class_names.IndexOf(m->GetDeclaringClassDescriptor());
5019 size_t method_name_index = method_names.IndexOf(m->GetName());
5020 size_t file_name_index = filenames.IndexOf(GetMethodSourceFile(m));
Mathieu Chartier46e811b2013-07-10 17:09:14 -07005021 JDWP::Append2BE(bytes, class_name_index);
5022 JDWP::Append2BE(bytes, method_name_index);
5023 JDWP::Append2BE(bytes, file_name_index);
Hiroshi Yamauchib5a9e3d2014-06-09 12:11:20 -07005024 JDWP::Append2BE(bytes, record->StackElement(stack_frame)->LineNumber());
Mathieu Chartier46e811b2013-07-10 17:09:14 -07005025 }
Ian Rogers719d1a32014-03-06 12:13:39 -08005026 idx = (idx + 1) & (alloc_record_max_ - 1);
Mathieu Chartier46e811b2013-07-10 17:09:14 -07005027 }
5028
5029 // (xb) class name strings
5030 // (xb) method name strings
5031 // (xb) source file strings
5032 JDWP::Set4BE(&bytes[string_table_offset], bytes.size());
5033 class_names.WriteTo(bytes);
5034 method_names.WriteTo(bytes);
5035 filenames.WriteTo(bytes);
Elliott Hughes545a0642011-11-08 19:10:03 -08005036 }
Ian Rogers50b35e22012-10-04 10:09:15 -07005037 JNIEnv* env = self->GetJniEnv();
Elliott Hughes545a0642011-11-08 19:10:03 -08005038 jbyteArray result = env->NewByteArray(bytes.size());
Ian Rogersc0542af2014-09-03 16:16:56 -07005039 if (result != nullptr) {
Elliott Hughes545a0642011-11-08 19:10:03 -08005040 env->SetByteArrayRegion(result, 0, bytes.size(), reinterpret_cast<const jbyte*>(&bytes[0]));
5041 }
5042 return result;
5043}
5044
Mathieu Chartiere401d142015-04-22 13:56:20 -07005045ArtMethod* DeoptimizationRequest::Method() const {
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07005046 ScopedObjectAccessUnchecked soa(Thread::Current());
5047 return soa.DecodeMethod(method_);
5048}
5049
Mathieu Chartiere401d142015-04-22 13:56:20 -07005050void DeoptimizationRequest::SetMethod(ArtMethod* m) {
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07005051 ScopedObjectAccessUnchecked soa(Thread::Current());
5052 method_ = soa.EncodeMethod(m);
5053}
5054
Elliott Hughes872d4ec2011-10-21 17:07:15 -07005055} // namespace art