blob: a0e978b7e0b88539584a2682bd1f6e22ea16f5dd [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"
Elliott Hughes545a0642011-11-08 19:10:03 -080024#include "class_linker.h"
Ian Rogers2dd0e2c2013-01-24 12:42:14 -080025#include "class_linker-inl.h"
Ian Rogers4f6ad8a2013-03-18 15:27:28 -070026#include "dex_file-inl.h"
Ian Rogers776ac1f2012-04-13 23:36:36 -070027#include "dex_instruction.h"
Ian Rogers1d54e732013-05-02 21:10:01 -070028#include "gc/accounting/card_table-inl.h"
29#include "gc/space/large_object_space.h"
30#include "gc/space/space-inl.h"
Mathieu Chartiereb8167a2014-05-07 15:43:14 -070031#include "handle_scope.h"
Elliott Hughes64f574f2013-02-20 14:57:12 -080032#include "jdwp/object_registry.h"
Brian Carlstromea46f952013-07-30 01:26:50 -070033#include "mirror/art_field-inl.h"
34#include "mirror/art_method-inl.h"
Ian Rogers2dd0e2c2013-01-24 12:42:14 -080035#include "mirror/class.h"
36#include "mirror/class-inl.h"
37#include "mirror/class_loader.h"
Ian Rogers2dd0e2c2013-01-24 12:42:14 -080038#include "mirror/object-inl.h"
39#include "mirror/object_array-inl.h"
Ian Rogersb0fa5dc2014-04-28 16:47:08 -070040#include "mirror/string-inl.h"
Ian Rogers2dd0e2c2013-01-24 12:42:14 -080041#include "mirror/throwable.h"
Sebastien Hertza76a6d42014-03-20 16:40:17 +010042#include "quick/inline_method_analyser.h"
Ian Rogers53b8b092014-03-13 23:45:53 -070043#include "reflection.h"
Elliott Hughesa0e18062012-04-13 15:59:59 -070044#include "safe_map.h"
Elliott Hughes64f574f2013-02-20 14:57:12 -080045#include "scoped_thread_state_change.h"
Elliott Hughes6a5bd492011-10-28 14:33:57 -070046#include "ScopedLocalRef.h"
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -070047#include "ScopedPrimitiveArray.h"
Mathieu Chartiereb8167a2014-05-07 15:43:14 -070048#include "handle_scope-inl.h"
Elliott Hughes475fc232011-10-25 15:00:35 -070049#include "thread_list.h"
Ian Rogers62d6c772013-02-27 08:32:07 -080050#include "throw_location.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
Brian Carlstrom7934ac22013-07-26 10:54:15 -070061static const size_t kMaxAllocRecordStackDepth = 16; // Max 255.
Brian Carlstrom306db812014-09-05 13:01:41 -070062static const size_t kDefaultNumAllocRecords = 64*1024; // Must be a power of 2. 2BE can hold 64k-1.
63
64// Limit alloc_record_count to the 2BE value that is the limit of the current protocol.
65static uint16_t CappedAllocRecordCount(size_t alloc_record_count) {
66 if (alloc_record_count > 0xffff) {
67 return 0xffff;
68 }
69 return alloc_record_count;
70}
Elliott Hughes475fc232011-10-25 15:00:35 -070071
Hiroshi Yamauchib5a9e3d2014-06-09 12:11:20 -070072class AllocRecordStackTraceElement {
73 public:
74 AllocRecordStackTraceElement() : method_(nullptr), dex_pc_(0) {
Mathieu Chartier412c7fc2014-02-07 12:18:39 -080075 }
76
Hiroshi Yamauchib5a9e3d2014-06-09 12:11:20 -070077 int32_t LineNumber() SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
78 mirror::ArtMethod* method = Method();
79 DCHECK(method != nullptr);
80 return method->GetLineNumFromDexPC(DexPc());
Elliott Hughes545a0642011-11-08 19:10:03 -080081 }
Hiroshi Yamauchib5a9e3d2014-06-09 12:11:20 -070082
83 mirror::ArtMethod* Method() SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Mathieu Chartier4345c462014-06-27 10:20:14 -070084 ScopedObjectAccessUnchecked soa(Thread::Current());
85 return soa.DecodeMethod(method_);
Hiroshi Yamauchib5a9e3d2014-06-09 12:11:20 -070086 }
87
88 void SetMethod(mirror::ArtMethod* m) SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
89 ScopedObjectAccessUnchecked soa(Thread::Current());
Mathieu Chartier4345c462014-06-27 10:20:14 -070090 method_ = soa.EncodeMethod(m);
Hiroshi Yamauchib5a9e3d2014-06-09 12:11:20 -070091 }
92
93 uint32_t DexPc() const {
94 return dex_pc_;
95 }
96
97 void SetDexPc(uint32_t pc) {
98 dex_pc_ = pc;
99 }
100
101 private:
Mathieu Chartier4345c462014-06-27 10:20:14 -0700102 jmethodID method_;
Hiroshi Yamauchib5a9e3d2014-06-09 12:11:20 -0700103 uint32_t dex_pc_;
Elliott Hughes545a0642011-11-08 19:10:03 -0800104};
105
Mathieu Chartier4345c462014-06-27 10:20:14 -0700106jobject Dbg::TypeCache::Add(mirror::Class* t) {
107 ScopedObjectAccessUnchecked soa(Thread::Current());
Mathieu Chartier4c4d6092015-01-22 17:02:27 -0800108 JNIEnv* const env = soa.Env();
109 ScopedLocalRef<jobject> local_ref(soa.Env(), soa.AddLocalReference<jobject>(t));
110 const int32_t hash_code = soa.Decode<mirror::Class*>(local_ref.get())->IdentityHashCode();
Mathieu Chartier4345c462014-06-27 10:20:14 -0700111 auto range = objects_.equal_range(hash_code);
112 for (auto it = range.first; it != range.second; ++it) {
Mathieu Chartier4c4d6092015-01-22 17:02:27 -0800113 if (soa.Decode<mirror::Class*>(it->second) == soa.Decode<mirror::Class*>(local_ref.get())) {
Mathieu Chartier4345c462014-06-27 10:20:14 -0700114 // Found a matching weak global, return it.
115 return it->second;
116 }
117 }
Mathieu Chartier4c4d6092015-01-22 17:02:27 -0800118 const jobject weak_global = env->NewWeakGlobalRef(local_ref.get());
Mathieu Chartier4345c462014-06-27 10:20:14 -0700119 objects_.insert(std::make_pair(hash_code, weak_global));
120 return weak_global;
121}
122
123void Dbg::TypeCache::Clear() {
Brian Carlstrom306db812014-09-05 13:01:41 -0700124 JavaVMExt* vm = Runtime::Current()->GetJavaVM();
125 Thread* self = Thread::Current();
Mathieu Chartier4345c462014-06-27 10:20:14 -0700126 for (const auto& p : objects_) {
Brian Carlstrom306db812014-09-05 13:01:41 -0700127 vm->DeleteWeakGlobalRef(self, p.second);
Mathieu Chartier4345c462014-06-27 10:20:14 -0700128 }
129 objects_.clear();
130}
131
Hiroshi Yamauchib5a9e3d2014-06-09 12:11:20 -0700132class AllocRecord {
133 public:
134 AllocRecord() : type_(nullptr), byte_count_(0), thin_lock_id_(0) {}
Elliott Hughes545a0642011-11-08 19:10:03 -0800135
Hiroshi Yamauchib5a9e3d2014-06-09 12:11:20 -0700136 mirror::Class* Type() SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Mathieu Chartier4345c462014-06-27 10:20:14 -0700137 return down_cast<mirror::Class*>(Thread::Current()->DecodeJObject(type_));
Hiroshi Yamauchib5a9e3d2014-06-09 12:11:20 -0700138 }
139
Brian Carlstrom306db812014-09-05 13:01:41 -0700140 void SetType(mirror::Class* t) SHARED_LOCKS_REQUIRED(Locks::mutator_lock_,
141 Locks::alloc_tracker_lock_) {
142 type_ = Dbg::type_cache_.Add(t);
Hiroshi Yamauchib5a9e3d2014-06-09 12:11:20 -0700143 }
144
145 size_t GetDepth() SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Elliott Hughes545a0642011-11-08 19:10:03 -0800146 size_t depth = 0;
Ian Rogersc0542af2014-09-03 16:16:56 -0700147 while (depth < kMaxAllocRecordStackDepth && stack_[depth].Method() != nullptr) {
Elliott Hughes545a0642011-11-08 19:10:03 -0800148 ++depth;
149 }
150 return depth;
151 }
Mathieu Chartier412c7fc2014-02-07 12:18:39 -0800152
Hiroshi Yamauchib5a9e3d2014-06-09 12:11:20 -0700153 size_t ByteCount() const {
154 return byte_count_;
Mathieu Chartier412c7fc2014-02-07 12:18:39 -0800155 }
Hiroshi Yamauchib5a9e3d2014-06-09 12:11:20 -0700156
157 void SetByteCount(size_t count) {
158 byte_count_ = count;
159 }
160
161 uint16_t ThinLockId() const {
162 return thin_lock_id_;
163 }
164
165 void SetThinLockId(uint16_t id) {
166 thin_lock_id_ = id;
167 }
168
169 AllocRecordStackTraceElement* StackElement(size_t index) {
170 DCHECK_LT(index, kMaxAllocRecordStackDepth);
171 return &stack_[index];
172 }
173
174 private:
175 jobject type_; // This is a weak global.
176 size_t byte_count_;
177 uint16_t thin_lock_id_;
Ian Rogersc0542af2014-09-03 16:16:56 -0700178 AllocRecordStackTraceElement stack_[kMaxAllocRecordStackDepth]; // Unused entries have nullptr method.
Elliott Hughes545a0642011-11-08 19:10:03 -0800179};
180
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -0700181class Breakpoint {
182 public:
Sebastien Hertzf3928792014-11-17 19:00:37 +0100183 Breakpoint(mirror::ArtMethod* method, uint32_t dex_pc,
184 DeoptimizationRequest::Kind deoptimization_kind)
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -0700185 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_)
Sebastien Hertzf3928792014-11-17 19:00:37 +0100186 : method_(nullptr), dex_pc_(dex_pc), deoptimization_kind_(deoptimization_kind) {
187 CHECK(deoptimization_kind_ == DeoptimizationRequest::kNothing ||
188 deoptimization_kind_ == DeoptimizationRequest::kSelectiveDeoptimization ||
189 deoptimization_kind_ == DeoptimizationRequest::kFullDeoptimization);
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -0700190 ScopedObjectAccessUnchecked soa(Thread::Current());
191 method_ = soa.EncodeMethod(method);
192 }
193
194 Breakpoint(const Breakpoint& other) SHARED_LOCKS_REQUIRED(Locks::mutator_lock_)
195 : method_(nullptr), dex_pc_(other.dex_pc_),
Sebastien Hertzf3928792014-11-17 19:00:37 +0100196 deoptimization_kind_(other.deoptimization_kind_) {
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -0700197 ScopedObjectAccessUnchecked soa(Thread::Current());
198 method_ = soa.EncodeMethod(other.Method());
199 }
200
201 mirror::ArtMethod* Method() const SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
202 ScopedObjectAccessUnchecked soa(Thread::Current());
203 return soa.DecodeMethod(method_);
204 }
205
206 uint32_t DexPc() const {
207 return dex_pc_;
208 }
209
Sebastien Hertzf3928792014-11-17 19:00:37 +0100210 DeoptimizationRequest::Kind GetDeoptimizationKind() const {
211 return deoptimization_kind_;
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -0700212 }
213
214 private:
Sebastien Hertza76a6d42014-03-20 16:40:17 +0100215 // The location of this breakpoint.
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -0700216 jmethodID method_;
217 uint32_t dex_pc_;
Sebastien Hertza76a6d42014-03-20 16:40:17 +0100218
219 // Indicates whether breakpoint needs full deoptimization or selective deoptimization.
Sebastien Hertzf3928792014-11-17 19:00:37 +0100220 DeoptimizationRequest::Kind deoptimization_kind_;
Elliott Hughes86964332012-02-15 19:37:42 -0800221};
222
Sebastien Hertzed2be172014-08-19 15:33:43 +0200223static std::ostream& operator<<(std::ostream& os, const Breakpoint& rhs)
Ian Rogersb726dcb2012-09-05 08:57:23 -0700224 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -0700225 os << StringPrintf("Breakpoint[%s @%#x]", PrettyMethod(rhs.Method()).c_str(), rhs.DexPc());
Elliott Hughes86964332012-02-15 19:37:42 -0800226 return os;
227}
228
Sebastien Hertz3f52eaf2014-04-04 17:50:18 +0200229class DebugInstrumentationListener FINAL : public instrumentation::InstrumentationListener {
Ian Rogers62d6c772013-02-27 08:32:07 -0800230 public:
231 DebugInstrumentationListener() {}
232 virtual ~DebugInstrumentationListener() {}
233
Sebastien Hertz3f52eaf2014-04-04 17:50:18 +0200234 void MethodEntered(Thread* thread, mirror::Object* this_object, mirror::ArtMethod* method,
Ian Rogers6a3c1fc2014-10-31 00:33:20 -0700235 uint32_t dex_pc ATTRIBUTE_UNUSED)
Sebastien Hertz3f52eaf2014-04-04 17:50:18 +0200236 OVERRIDE SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Ian Rogers62d6c772013-02-27 08:32:07 -0800237 if (method->IsNative()) {
238 // TODO: post location events is a suspension point and native method entry stubs aren't.
239 return;
240 }
Sebastien Hertz8379b222014-02-24 17:38:15 +0100241 Dbg::UpdateDebugger(thread, this_object, method, 0, Dbg::kMethodEntry, nullptr);
Ian Rogers62d6c772013-02-27 08:32:07 -0800242 }
243
Sebastien Hertz3f52eaf2014-04-04 17:50:18 +0200244 void MethodExited(Thread* thread, mirror::Object* this_object, mirror::ArtMethod* method,
245 uint32_t dex_pc, const JValue& return_value)
246 OVERRIDE SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Ian Rogers62d6c772013-02-27 08:32:07 -0800247 if (method->IsNative()) {
248 // TODO: post location events is a suspension point and native method entry stubs aren't.
249 return;
250 }
Sebastien Hertz8379b222014-02-24 17:38:15 +0100251 Dbg::UpdateDebugger(thread, this_object, method, dex_pc, Dbg::kMethodExit, &return_value);
Ian Rogers62d6c772013-02-27 08:32:07 -0800252 }
253
Sebastien Hertz3f52eaf2014-04-04 17:50:18 +0200254 void MethodUnwind(Thread* thread, mirror::Object* this_object, mirror::ArtMethod* method,
255 uint32_t dex_pc)
256 OVERRIDE SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Ian Rogers62d6c772013-02-27 08:32:07 -0800257 // We're not recorded to listen to this kind of event, so complain.
Ian Rogers6a3c1fc2014-10-31 00:33:20 -0700258 UNUSED(thread, this_object, method, dex_pc);
Ian Rogers62d6c772013-02-27 08:32:07 -0800259 LOG(ERROR) << "Unexpected method unwind event in debugger " << PrettyMethod(method)
Sebastien Hertz51db44a2013-11-19 10:00:29 +0100260 << " " << dex_pc;
Ian Rogers62d6c772013-02-27 08:32:07 -0800261 }
262
Sebastien Hertz3f52eaf2014-04-04 17:50:18 +0200263 void DexPcMoved(Thread* thread, mirror::Object* this_object, mirror::ArtMethod* method,
264 uint32_t new_dex_pc)
265 OVERRIDE SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Sebastien Hertz8379b222014-02-24 17:38:15 +0100266 Dbg::UpdateDebugger(thread, this_object, method, new_dex_pc, 0, nullptr);
Ian Rogers62d6c772013-02-27 08:32:07 -0800267 }
268
Sebastien Hertz3f52eaf2014-04-04 17:50:18 +0200269 void FieldRead(Thread* thread, mirror::Object* this_object, mirror::ArtMethod* method,
270 uint32_t dex_pc, mirror::ArtField* field)
271 OVERRIDE SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Ian Rogers6a3c1fc2014-10-31 00:33:20 -0700272 UNUSED(thread);
Sebastien Hertz3f52eaf2014-04-04 17:50:18 +0200273 Dbg::PostFieldAccessEvent(method, dex_pc, this_object, field);
Ian Rogers62d6c772013-02-27 08:32:07 -0800274 }
Sebastien Hertz3f52eaf2014-04-04 17:50:18 +0200275
Ian Rogers6a3c1fc2014-10-31 00:33:20 -0700276 void FieldWritten(Thread* thread ATTRIBUTE_UNUSED, mirror::Object* this_object,
277 mirror::ArtMethod* method, uint32_t dex_pc, mirror::ArtField* field,
278 const JValue& field_value)
Sebastien Hertz3f52eaf2014-04-04 17:50:18 +0200279 OVERRIDE SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
280 Dbg::PostFieldModificationEvent(method, dex_pc, this_object, field, &field_value);
281 }
282
Ian Rogers6a3c1fc2014-10-31 00:33:20 -0700283 void ExceptionCaught(Thread* thread ATTRIBUTE_UNUSED, const ThrowLocation& throw_location,
Sebastien Hertz3f52eaf2014-04-04 17:50:18 +0200284 mirror::ArtMethod* catch_method, uint32_t catch_dex_pc,
285 mirror::Throwable* exception_object)
286 OVERRIDE SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
287 Dbg::PostException(throw_location, catch_method, catch_dex_pc, exception_object);
288 }
289
290 private:
291 DISALLOW_COPY_AND_ASSIGN(DebugInstrumentationListener);
Ian Rogers62d6c772013-02-27 08:32:07 -0800292} gDebugInstrumentationListener;
293
Elliott Hughes4ffd3132011-10-24 12:06:42 -0700294// JDWP is allowed unless the Zygote forbids it.
295static bool gJdwpAllowed = true;
296
Elliott Hughesc0f09332012-03-26 13:27:06 -0700297// Was there a -Xrunjdwp or -agentlib:jdwp= argument on the command line?
Elliott Hughes3bb81562011-10-21 18:52:59 -0700298static bool gJdwpConfigured = false;
299
Elliott Hughesc0f09332012-03-26 13:27:06 -0700300// Broken-down JDWP options. (Only valid if IsJdwpConfigured() is true.)
Elliott Hughes376a7a02011-10-24 18:35:55 -0700301static JDWP::JdwpOptions gJdwpOptions;
Elliott Hughes3bb81562011-10-21 18:52:59 -0700302
303// Runtime JDWP state.
Ian Rogersc0542af2014-09-03 16:16:56 -0700304static JDWP::JdwpState* gJdwpState = nullptr;
Elliott Hughes3bb81562011-10-21 18:52:59 -0700305static bool gDebuggerConnected; // debugger or DDMS is connected.
306static bool gDebuggerActive; // debugger is making requests.
Elliott Hughes86964332012-02-15 19:37:42 -0800307static bool gDisposed; // debugger called VirtualMachine.Dispose, so we should drop the connection.
Elliott Hughes3bb81562011-10-21 18:52:59 -0700308
Elliott Hughes47fce012011-10-25 18:37:19 -0700309static bool gDdmThreadNotification = false;
310
Elliott Hughes767a1472011-10-26 18:49:02 -0700311// DDMS GC-related settings.
312static Dbg::HpifWhen gDdmHpifWhen = Dbg::HPIF_WHEN_NEVER;
313static Dbg::HpsgWhen gDdmHpsgWhen = Dbg::HPSG_WHEN_NEVER;
314static Dbg::HpsgWhat gDdmHpsgWhat;
315static Dbg::HpsgWhen gDdmNhsgWhen = Dbg::HPSG_WHEN_NEVER;
316static Dbg::HpsgWhat gDdmNhsgWhat;
317
Sebastien Hertz6995c602014-09-09 12:10:13 +0200318ObjectRegistry* Dbg::gRegistry = nullptr;
Elliott Hughes475fc232011-10-25 15:00:35 -0700319
Elliott Hughes545a0642011-11-08 19:10:03 -0800320// Recent allocation tracking.
Ian Rogers719d1a32014-03-06 12:13:39 -0800321AllocRecord* Dbg::recent_allocation_records_ = nullptr; // TODO: CircularBuffer<AllocRecord>
322size_t Dbg::alloc_record_max_ = 0;
323size_t Dbg::alloc_record_head_ = 0;
324size_t Dbg::alloc_record_count_ = 0;
Mathieu Chartier4345c462014-06-27 10:20:14 -0700325Dbg::TypeCache Dbg::type_cache_;
Elliott Hughes545a0642011-11-08 19:10:03 -0800326
Sebastien Hertz138dbfc2013-12-04 18:15:25 +0100327// Deoptimization support.
Sebastien Hertz4d25df32014-03-21 17:44:46 +0100328std::vector<DeoptimizationRequest> Dbg::deoptimization_requests_;
329size_t Dbg::full_deoptimization_event_count_ = 0;
Sebastien Hertz7ec2f1c2014-03-27 20:06:47 +0100330size_t Dbg::delayed_full_undeoptimization_count_ = 0;
Sebastien Hertz138dbfc2013-12-04 18:15:25 +0100331
Sebastien Hertz42cd43f2014-05-13 14:15:41 +0200332// Instrumentation event reference counters.
333size_t Dbg::dex_pc_change_event_ref_count_ = 0;
334size_t Dbg::method_enter_event_ref_count_ = 0;
335size_t Dbg::method_exit_event_ref_count_ = 0;
336size_t Dbg::field_read_event_ref_count_ = 0;
337size_t Dbg::field_write_event_ref_count_ = 0;
338size_t Dbg::exception_catch_event_ref_count_ = 0;
339uint32_t Dbg::instrumentation_events_ = 0;
340
Sebastien Hertz138dbfc2013-12-04 18:15:25 +0100341// Breakpoints.
jeffhao09bfc6a2012-12-11 18:11:43 -0800342static std::vector<Breakpoint> gBreakpoints GUARDED_BY(Locks::breakpoint_lock_);
Elliott Hughes86964332012-02-15 19:37:42 -0800343
Mathieu Chartiere34fa1d2015-01-14 14:55:47 -0800344void DebugInvokeReq::VisitRoots(RootCallback* callback, void* arg, const RootInfo& root_info) {
Mathieu Chartier3b05e9b2014-03-25 09:29:43 -0700345 if (receiver != nullptr) {
Mathieu Chartiere34fa1d2015-01-14 14:55:47 -0800346 callback(&receiver, arg, root_info);
Mathieu Chartier3b05e9b2014-03-25 09:29:43 -0700347 }
348 if (thread != nullptr) {
Mathieu Chartiere34fa1d2015-01-14 14:55:47 -0800349 callback(&thread, arg, root_info);
Mathieu Chartier3b05e9b2014-03-25 09:29:43 -0700350 }
351 if (klass != nullptr) {
Mathieu Chartiere34fa1d2015-01-14 14:55:47 -0800352 callback(reinterpret_cast<mirror::Object**>(&klass), arg, root_info);
Mathieu Chartier3b05e9b2014-03-25 09:29:43 -0700353 }
354 if (method != nullptr) {
Mathieu Chartiere34fa1d2015-01-14 14:55:47 -0800355 callback(reinterpret_cast<mirror::Object**>(&method), arg, root_info);
Mathieu Chartier3b05e9b2014-03-25 09:29:43 -0700356 }
357}
358
Sebastien Hertzbb43b432014-04-14 11:59:08 +0200359void DebugInvokeReq::Clear() {
360 invoke_needed = false;
361 receiver = nullptr;
362 thread = nullptr;
363 klass = nullptr;
364 method = nullptr;
365}
366
Mathieu Chartiere34fa1d2015-01-14 14:55:47 -0800367void SingleStepControl::VisitRoots(RootCallback* callback, void* arg, const RootInfo& root_info) {
Sebastien Hertz597c4f02015-01-26 17:37:14 +0100368 if (method_ != nullptr) {
369 callback(reinterpret_cast<mirror::Object**>(&method_), arg, root_info);
Mathieu Chartier3b05e9b2014-03-25 09:29:43 -0700370 }
371}
372
Sebastien Hertz597c4f02015-01-26 17:37:14 +0100373void SingleStepControl::AddDexPc(uint32_t dex_pc) {
374 dex_pcs_.insert(dex_pc);
Sebastien Hertzbb43b432014-04-14 11:59:08 +0200375}
376
Sebastien Hertz597c4f02015-01-26 17:37:14 +0100377bool SingleStepControl::ContainsDexPc(uint32_t dex_pc) const {
378 return dex_pcs_.find(dex_pc) == dex_pcs_.end();
Sebastien Hertzbb43b432014-04-14 11:59:08 +0200379}
380
Brian Carlstromea46f952013-07-30 01:26:50 -0700381static bool IsBreakpoint(const mirror::ArtMethod* m, uint32_t dex_pc)
jeffhao09bfc6a2012-12-11 18:11:43 -0800382 LOCKS_EXCLUDED(Locks::breakpoint_lock_)
Ian Rogersb726dcb2012-09-05 08:57:23 -0700383 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Sebastien Hertzed2be172014-08-19 15:33:43 +0200384 ReaderMutexLock mu(Thread::Current(), *Locks::breakpoint_lock_);
Sebastien Hertz138dbfc2013-12-04 18:15:25 +0100385 for (size_t i = 0, e = gBreakpoints.size(); i < e; ++i) {
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -0700386 if (gBreakpoints[i].DexPc() == dex_pc && gBreakpoints[i].Method() == m) {
Elliott Hughes86964332012-02-15 19:37:42 -0800387 VLOG(jdwp) << "Hit breakpoint #" << i << ": " << gBreakpoints[i];
388 return true;
389 }
390 }
391 return false;
392}
393
Sebastien Hertz52d131d2014-03-13 16:17:40 +0100394static bool IsSuspendedForDebugger(ScopedObjectAccessUnchecked& soa, Thread* thread)
395 LOCKS_EXCLUDED(Locks::thread_suspend_count_lock_) {
Elliott Hughes9e0c1752013-01-09 14:02:58 -0800396 MutexLock mu(soa.Self(), *Locks::thread_suspend_count_lock_);
397 // A thread may be suspended for GC; in this code, we really want to know whether
398 // there's a debugger suspension active.
399 return thread->IsSuspended() && thread->GetDebugSuspendCount() > 0;
400}
401
Ian Rogersc0542af2014-09-03 16:16:56 -0700402static mirror::Array* DecodeNonNullArray(JDWP::RefTypeId id, JDWP::JdwpError* error)
Ian Rogersb726dcb2012-09-05 08:57:23 -0700403 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Sebastien Hertz6995c602014-09-09 12:10:13 +0200404 mirror::Object* o = Dbg::GetObjectRegistry()->Get<mirror::Object*>(id, error);
Ian Rogersc0542af2014-09-03 16:16:56 -0700405 if (o == nullptr) {
406 *error = JDWP::ERR_INVALID_OBJECT;
407 return nullptr;
Elliott Hughes436e3722012-02-17 20:01:47 -0800408 }
409 if (!o->IsArrayInstance()) {
Ian Rogersc0542af2014-09-03 16:16:56 -0700410 *error = JDWP::ERR_INVALID_ARRAY;
411 return nullptr;
Elliott Hughes436e3722012-02-17 20:01:47 -0800412 }
Ian Rogersc0542af2014-09-03 16:16:56 -0700413 *error = JDWP::ERR_NONE;
Elliott Hughes436e3722012-02-17 20:01:47 -0800414 return o->AsArray();
415}
416
Ian Rogersc0542af2014-09-03 16:16:56 -0700417static mirror::Class* DecodeClass(JDWP::RefTypeId id, JDWP::JdwpError* error)
Ian Rogersb726dcb2012-09-05 08:57:23 -0700418 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Sebastien Hertz6995c602014-09-09 12:10:13 +0200419 mirror::Object* o = Dbg::GetObjectRegistry()->Get<mirror::Object*>(id, error);
Ian Rogersc0542af2014-09-03 16:16:56 -0700420 if (o == nullptr) {
421 *error = JDWP::ERR_INVALID_OBJECT;
422 return nullptr;
Elliott Hughes436e3722012-02-17 20:01:47 -0800423 }
424 if (!o->IsClass()) {
Ian Rogersc0542af2014-09-03 16:16:56 -0700425 *error = JDWP::ERR_INVALID_CLASS;
426 return nullptr;
Elliott Hughes436e3722012-02-17 20:01:47 -0800427 }
Ian Rogersc0542af2014-09-03 16:16:56 -0700428 *error = JDWP::ERR_NONE;
Elliott Hughes436e3722012-02-17 20:01:47 -0800429 return o->AsClass();
430}
431
Ian Rogersc0542af2014-09-03 16:16:56 -0700432static Thread* DecodeThread(ScopedObjectAccessUnchecked& soa, JDWP::ObjectId thread_id,
433 JDWP::JdwpError* error)
jeffhaoa77f0f62012-12-05 17:19:31 -0800434 EXCLUSIVE_LOCKS_REQUIRED(Locks::thread_list_lock_)
Ian Rogersb726dcb2012-09-05 08:57:23 -0700435 LOCKS_EXCLUDED(Locks::thread_suspend_count_lock_)
436 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Sebastien Hertz6995c602014-09-09 12:10:13 +0200437 mirror::Object* thread_peer = Dbg::GetObjectRegistry()->Get<mirror::Object*>(thread_id, error);
Ian Rogersc0542af2014-09-03 16:16:56 -0700438 if (thread_peer == nullptr) {
Elliott Hughes221229c2013-01-08 18:17:50 -0800439 // This isn't even an object.
Ian Rogersc0542af2014-09-03 16:16:56 -0700440 *error = JDWP::ERR_INVALID_OBJECT;
441 return nullptr;
Elliott Hughes436e3722012-02-17 20:01:47 -0800442 }
Elliott Hughes221229c2013-01-08 18:17:50 -0800443
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800444 mirror::Class* java_lang_Thread = soa.Decode<mirror::Class*>(WellKnownClasses::java_lang_Thread);
Elliott Hughes221229c2013-01-08 18:17:50 -0800445 if (!java_lang_Thread->IsAssignableFrom(thread_peer->GetClass())) {
446 // This isn't a thread.
Ian Rogersc0542af2014-09-03 16:16:56 -0700447 *error = JDWP::ERR_INVALID_THREAD;
448 return nullptr;
Elliott Hughes221229c2013-01-08 18:17:50 -0800449 }
450
Ian Rogersc0542af2014-09-03 16:16:56 -0700451 Thread* thread = Thread::FromManagedThread(soa, thread_peer);
452 // If thread is null then this a java.lang.Thread without a Thread*. Must be a un-started or a
453 // zombie.
454 *error = (thread == nullptr) ? JDWP::ERR_THREAD_NOT_ALIVE : JDWP::ERR_NONE;
455 return thread;
Elliott Hughes436e3722012-02-17 20:01:47 -0800456}
457
Elliott Hughes24437992011-11-30 14:49:33 -0800458static JDWP::JdwpTag BasicTagFromDescriptor(const char* descriptor) {
459 // JDWP deliberately uses the descriptor characters' ASCII values for its enum.
460 // Note that by "basic" we mean that we don't get more specific than JT_OBJECT.
461 return static_cast<JDWP::JdwpTag>(descriptor[0]);
462}
463
Ian Rogers1ff3c982014-08-12 02:30:58 -0700464static JDWP::JdwpTag BasicTagFromClass(mirror::Class* klass)
465 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
466 std::string temp;
467 const char* descriptor = klass->GetDescriptor(&temp);
468 return BasicTagFromDescriptor(descriptor);
469}
470
Ian Rogers98379392014-02-24 16:53:16 -0800471static JDWP::JdwpTag TagFromClass(const ScopedObjectAccessUnchecked& soa, mirror::Class* c)
Ian Rogersb726dcb2012-09-05 08:57:23 -0700472 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Ian Rogersc0542af2014-09-03 16:16:56 -0700473 CHECK(c != nullptr);
Elliott Hughes24437992011-11-30 14:49:33 -0800474 if (c->IsArrayClass()) {
475 return JDWP::JT_ARRAY;
476 }
Elliott Hughes24437992011-11-30 14:49:33 -0800477 if (c->IsStringClass()) {
478 return JDWP::JT_STRING;
Elliott Hughes24437992011-11-30 14:49:33 -0800479 }
Ian Rogers98379392014-02-24 16:53:16 -0800480 if (c->IsClassClass()) {
481 return JDWP::JT_CLASS_OBJECT;
482 }
483 {
484 mirror::Class* thread_class = soa.Decode<mirror::Class*>(WellKnownClasses::java_lang_Thread);
485 if (thread_class->IsAssignableFrom(c)) {
486 return JDWP::JT_THREAD;
487 }
488 }
489 {
490 mirror::Class* thread_group_class =
491 soa.Decode<mirror::Class*>(WellKnownClasses::java_lang_ThreadGroup);
492 if (thread_group_class->IsAssignableFrom(c)) {
493 return JDWP::JT_THREAD_GROUP;
494 }
495 }
496 {
497 mirror::Class* class_loader_class =
498 soa.Decode<mirror::Class*>(WellKnownClasses::java_lang_ClassLoader);
499 if (class_loader_class->IsAssignableFrom(c)) {
500 return JDWP::JT_CLASS_LOADER;
501 }
502 }
503 return JDWP::JT_OBJECT;
Elliott Hughes24437992011-11-30 14:49:33 -0800504}
505
506/*
507 * Objects declared to hold Object might actually hold a more specific
508 * type. The debugger may take a special interest in these (e.g. it
509 * wants to display the contents of Strings), so we want to return an
510 * appropriate tag.
511 *
512 * Null objects are tagged JT_OBJECT.
513 */
Sebastien Hertz6995c602014-09-09 12:10:13 +0200514JDWP::JdwpTag Dbg::TagFromObject(const ScopedObjectAccessUnchecked& soa, mirror::Object* o) {
Ian Rogersc0542af2014-09-03 16:16:56 -0700515 return (o == nullptr) ? JDWP::JT_OBJECT : TagFromClass(soa, o->GetClass());
Elliott Hughes24437992011-11-30 14:49:33 -0800516}
517
518static bool IsPrimitiveTag(JDWP::JdwpTag tag) {
519 switch (tag) {
520 case JDWP::JT_BOOLEAN:
521 case JDWP::JT_BYTE:
522 case JDWP::JT_CHAR:
523 case JDWP::JT_FLOAT:
524 case JDWP::JT_DOUBLE:
525 case JDWP::JT_INT:
526 case JDWP::JT_LONG:
527 case JDWP::JT_SHORT:
528 case JDWP::JT_VOID:
529 return true;
530 default:
531 return false;
532 }
533}
534
Elliott Hughes3bb81562011-10-21 18:52:59 -0700535/*
536 * Handle one of the JDWP name/value pairs.
537 *
538 * JDWP options are:
539 * help: if specified, show help message and bail
540 * transport: may be dt_socket or dt_shmem
541 * address: for dt_socket, "host:port", or just "port" when listening
542 * server: if "y", wait for debugger to attach; if "n", attach to debugger
543 * timeout: how long to wait for debugger to connect / listen
544 *
545 * Useful with server=n (these aren't supported yet):
546 * onthrow=<exception-name>: connect to debugger when exception thrown
547 * onuncaught=y|n: connect to debugger when uncaught exception thrown
548 * launch=<command-line>: launch the debugger itself
549 *
550 * The "transport" option is required, as is "address" if server=n.
551 */
552static bool ParseJdwpOption(const std::string& name, const std::string& value) {
553 if (name == "transport") {
554 if (value == "dt_socket") {
Elliott Hughes376a7a02011-10-24 18:35:55 -0700555 gJdwpOptions.transport = JDWP::kJdwpTransportSocket;
Elliott Hughes3bb81562011-10-21 18:52:59 -0700556 } else if (value == "dt_android_adb") {
Elliott Hughes376a7a02011-10-24 18:35:55 -0700557 gJdwpOptions.transport = JDWP::kJdwpTransportAndroidAdb;
Elliott Hughes3bb81562011-10-21 18:52:59 -0700558 } else {
559 LOG(ERROR) << "JDWP transport not supported: " << value;
560 return false;
561 }
562 } else if (name == "server") {
563 if (value == "n") {
Elliott Hughes376a7a02011-10-24 18:35:55 -0700564 gJdwpOptions.server = false;
Elliott Hughes3bb81562011-10-21 18:52:59 -0700565 } else if (value == "y") {
Elliott Hughes376a7a02011-10-24 18:35:55 -0700566 gJdwpOptions.server = true;
Elliott Hughes3bb81562011-10-21 18:52:59 -0700567 } else {
568 LOG(ERROR) << "JDWP option 'server' must be 'y' or 'n'";
569 return false;
570 }
571 } else if (name == "suspend") {
572 if (value == "n") {
Elliott Hughes376a7a02011-10-24 18:35:55 -0700573 gJdwpOptions.suspend = false;
Elliott Hughes3bb81562011-10-21 18:52:59 -0700574 } else if (value == "y") {
Elliott Hughes376a7a02011-10-24 18:35:55 -0700575 gJdwpOptions.suspend = true;
Elliott Hughes3bb81562011-10-21 18:52:59 -0700576 } else {
577 LOG(ERROR) << "JDWP option 'suspend' must be 'y' or 'n'";
578 return false;
579 }
580 } else if (name == "address") {
581 /* this is either <port> or <host>:<port> */
582 std::string port_string;
Elliott Hughes376a7a02011-10-24 18:35:55 -0700583 gJdwpOptions.host.clear();
Elliott Hughes3bb81562011-10-21 18:52:59 -0700584 std::string::size_type colon = value.find(':');
585 if (colon != std::string::npos) {
Elliott Hughes376a7a02011-10-24 18:35:55 -0700586 gJdwpOptions.host = value.substr(0, colon);
Elliott Hughes3bb81562011-10-21 18:52:59 -0700587 port_string = value.substr(colon + 1);
588 } else {
589 port_string = value;
590 }
591 if (port_string.empty()) {
592 LOG(ERROR) << "JDWP address missing port: " << value;
593 return false;
594 }
595 char* end;
Elliott Hughesba8eee12012-01-24 20:25:24 -0800596 uint64_t port = strtoul(port_string.c_str(), &end, 10);
597 if (*end != '\0' || port > 0xffff) {
Elliott Hughes3bb81562011-10-21 18:52:59 -0700598 LOG(ERROR) << "JDWP address has junk in port field: " << value;
599 return false;
600 }
Elliott Hughes376a7a02011-10-24 18:35:55 -0700601 gJdwpOptions.port = port;
Elliott Hughes3bb81562011-10-21 18:52:59 -0700602 } else if (name == "launch" || name == "onthrow" || name == "oncaught" || name == "timeout") {
603 /* valid but unsupported */
604 LOG(INFO) << "Ignoring JDWP option '" << name << "'='" << value << "'";
605 } else {
606 LOG(INFO) << "Ignoring unrecognized JDWP option '" << name << "'='" << value << "'";
607 }
608
609 return true;
610}
611
612/*
613 * Parse the latter half of a -Xrunjdwp/-agentlib:jdwp= string, e.g.:
614 * "transport=dt_socket,address=8000,server=y,suspend=n"
615 */
616bool Dbg::ParseJdwpOptions(const std::string& options) {
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -0800617 VLOG(jdwp) << "ParseJdwpOptions: " << options;
Elliott Hughes47fce012011-10-25 18:37:19 -0700618
Elliott Hughes3bb81562011-10-21 18:52:59 -0700619 std::vector<std::string> pairs;
Ian Rogers6f3dbba2014-10-14 17:41:57 -0700620 Split(options, ',', &pairs);
Elliott Hughes3bb81562011-10-21 18:52:59 -0700621
622 for (size_t i = 0; i < pairs.size(); ++i) {
623 std::string::size_type equals = pairs[i].find('=');
624 if (equals == std::string::npos) {
625 LOG(ERROR) << "Can't parse JDWP option '" << pairs[i] << "' in '" << options << "'";
626 return false;
627 }
628 ParseJdwpOption(pairs[i].substr(0, equals), pairs[i].substr(equals + 1));
629 }
630
Elliott Hughes376a7a02011-10-24 18:35:55 -0700631 if (gJdwpOptions.transport == JDWP::kJdwpTransportUnknown) {
Elliott Hughes3bb81562011-10-21 18:52:59 -0700632 LOG(ERROR) << "Must specify JDWP transport: " << options;
633 }
Elliott Hughes376a7a02011-10-24 18:35:55 -0700634 if (!gJdwpOptions.server && (gJdwpOptions.host.empty() || gJdwpOptions.port == 0)) {
Elliott Hughes3bb81562011-10-21 18:52:59 -0700635 LOG(ERROR) << "Must specify JDWP host and port when server=n: " << options;
636 return false;
637 }
638
639 gJdwpConfigured = true;
640 return true;
641}
642
Elliott Hughesd1cc8362011-10-24 16:58:50 -0700643void Dbg::StartJdwp() {
Elliott Hughesc0f09332012-03-26 13:27:06 -0700644 if (!gJdwpAllowed || !IsJdwpConfigured()) {
Elliott Hughes376a7a02011-10-24 18:35:55 -0700645 // No JDWP for you!
646 return;
647 }
648
Ian Rogers719d1a32014-03-06 12:13:39 -0800649 CHECK(gRegistry == nullptr);
Elliott Hughes475fc232011-10-25 15:00:35 -0700650 gRegistry = new ObjectRegistry;
651
Elliott Hughesd1cc8362011-10-24 16:58:50 -0700652 // Init JDWP if the debugger is enabled. This may connect out to a
653 // debugger, passively listen for a debugger, or block waiting for a
654 // debugger.
Elliott Hughes376a7a02011-10-24 18:35:55 -0700655 gJdwpState = JDWP::JdwpState::Create(&gJdwpOptions);
Ian Rogersc0542af2014-09-03 16:16:56 -0700656 if (gJdwpState == nullptr) {
Elliott Hughesf8a2df72011-12-01 12:19:54 -0800657 // We probably failed because some other process has the port already, which means that
658 // if we don't abort the user is likely to think they're talking to us when they're actually
659 // talking to that other process.
Elliott Hughes3d30d9b2011-12-07 17:35:48 -0800660 LOG(FATAL) << "Debugger thread failed to initialize";
Elliott Hughesd1cc8362011-10-24 16:58:50 -0700661 }
662
663 // If a debugger has already attached, send the "welcome" message.
664 // This may cause us to suspend all threads.
Elliott Hughes376a7a02011-10-24 18:35:55 -0700665 if (gJdwpState->IsActive()) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700666 ScopedObjectAccess soa(Thread::Current());
Sebastien Hertz7d955652014-10-22 10:57:10 +0200667 gJdwpState->PostVMStart();
Elliott Hughesd1cc8362011-10-24 16:58:50 -0700668 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700669}
670
Elliott Hughesd1cc8362011-10-24 16:58:50 -0700671void Dbg::StopJdwp() {
Sebastien Hertzc6345ef2014-08-18 19:26:39 +0200672 // Post VM_DEATH event before the JDWP connection is closed (either by the JDWP thread or the
673 // destruction of gJdwpState).
674 if (gJdwpState != nullptr && gJdwpState->IsActive()) {
675 gJdwpState->PostVMDeath();
676 }
Sebastien Hertz0376e6b2014-02-06 18:12:59 +0100677 // Prevent the JDWP thread from processing JDWP incoming packets after we close the connection.
678 Disposed();
Elliott Hughes376a7a02011-10-24 18:35:55 -0700679 delete gJdwpState;
Ian Rogers719d1a32014-03-06 12:13:39 -0800680 gJdwpState = nullptr;
Elliott Hughes475fc232011-10-25 15:00:35 -0700681 delete gRegistry;
Ian Rogers719d1a32014-03-06 12:13:39 -0800682 gRegistry = nullptr;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700683}
684
Elliott Hughes767a1472011-10-26 18:49:02 -0700685void Dbg::GcDidFinish() {
686 if (gDdmHpifWhen != HPIF_WHEN_NEVER) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700687 ScopedObjectAccess soa(Thread::Current());
Brian Carlstrom4d466a82014-05-08 19:05:29 -0700688 VLOG(jdwp) << "Sending heap info to DDM";
Elliott Hughes7162ad92011-10-27 14:08:42 -0700689 DdmSendHeapInfo(gDdmHpifWhen);
Elliott Hughes767a1472011-10-26 18:49:02 -0700690 }
691 if (gDdmHpsgWhen != HPSG_WHEN_NEVER) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700692 ScopedObjectAccess soa(Thread::Current());
Brian Carlstrom4d466a82014-05-08 19:05:29 -0700693 VLOG(jdwp) << "Dumping heap to DDM";
Elliott Hughes6a5bd492011-10-28 14:33:57 -0700694 DdmSendHeapSegments(false);
Elliott Hughes767a1472011-10-26 18:49:02 -0700695 }
696 if (gDdmNhsgWhen != HPSG_WHEN_NEVER) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700697 ScopedObjectAccess soa(Thread::Current());
Brian Carlstrom4d466a82014-05-08 19:05:29 -0700698 VLOG(jdwp) << "Dumping native heap to DDM";
Elliott Hughes6a5bd492011-10-28 14:33:57 -0700699 DdmSendHeapSegments(true);
Elliott Hughes767a1472011-10-26 18:49:02 -0700700 }
701}
702
Elliott Hughes4ffd3132011-10-24 12:06:42 -0700703void Dbg::SetJdwpAllowed(bool allowed) {
704 gJdwpAllowed = allowed;
705}
706
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700707DebugInvokeReq* Dbg::GetInvokeReq() {
Elliott Hughes475fc232011-10-25 15:00:35 -0700708 return Thread::Current()->GetInvokeReq();
709}
710
711Thread* Dbg::GetDebugThread() {
Ian Rogersc0542af2014-09-03 16:16:56 -0700712 return (gJdwpState != nullptr) ? gJdwpState->GetDebugThread() : nullptr;
Elliott Hughes475fc232011-10-25 15:00:35 -0700713}
714
715void Dbg::ClearWaitForEventThread() {
716 gJdwpState->ClearWaitForEventThread();
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700717}
718
719void Dbg::Connected() {
Elliott Hughes3bb81562011-10-21 18:52:59 -0700720 CHECK(!gDebuggerConnected);
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -0800721 VLOG(jdwp) << "JDWP has attached";
Elliott Hughes3bb81562011-10-21 18:52:59 -0700722 gDebuggerConnected = true;
Elliott Hughes86964332012-02-15 19:37:42 -0800723 gDisposed = false;
724}
725
726void Dbg::Disposed() {
727 gDisposed = true;
728}
729
730bool Dbg::IsDisposed() {
731 return gDisposed;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700732}
733
Sebastien Hertzf3928792014-11-17 19:00:37 +0100734bool Dbg::RequiresDeoptimization() {
735 // We don't need deoptimization if everything runs with interpreter after
736 // enabling -Xint mode.
737 return !Runtime::Current()->GetInstrumentation()->IsForcedInterpretOnly();
738}
739
Elliott Hughesa2155262011-11-16 16:26:58 -0800740void Dbg::GoActive() {
741 // Enable all debugging features, including scans for breakpoints.
742 // This is a no-op if we're already active.
743 // Only called from the JDWP handler thread.
744 if (gDebuggerActive) {
745 return;
746 }
747
Elliott Hughesc0f09332012-03-26 13:27:06 -0700748 {
749 // TODO: dalvik only warned if there were breakpoints left over. clear in Dbg::Disconnected?
Sebastien Hertzed2be172014-08-19 15:33:43 +0200750 ReaderMutexLock mu(Thread::Current(), *Locks::breakpoint_lock_);
Elliott Hughesc0f09332012-03-26 13:27:06 -0700751 CHECK_EQ(gBreakpoints.size(), 0U);
752 }
Elliott Hughesa2155262011-11-16 16:26:58 -0800753
Sebastien Hertz138dbfc2013-12-04 18:15:25 +0100754 {
Brian Carlstrom306db812014-09-05 13:01:41 -0700755 MutexLock mu(Thread::Current(), *Locks::deoptimization_lock_);
Sebastien Hertz4d25df32014-03-21 17:44:46 +0100756 CHECK_EQ(deoptimization_requests_.size(), 0U);
757 CHECK_EQ(full_deoptimization_event_count_, 0U);
Sebastien Hertz7ec2f1c2014-03-27 20:06:47 +0100758 CHECK_EQ(delayed_full_undeoptimization_count_, 0U);
Sebastien Hertz42cd43f2014-05-13 14:15:41 +0200759 CHECK_EQ(dex_pc_change_event_ref_count_, 0U);
760 CHECK_EQ(method_enter_event_ref_count_, 0U);
761 CHECK_EQ(method_exit_event_ref_count_, 0U);
762 CHECK_EQ(field_read_event_ref_count_, 0U);
763 CHECK_EQ(field_write_event_ref_count_, 0U);
764 CHECK_EQ(exception_catch_event_ref_count_, 0U);
Sebastien Hertz138dbfc2013-12-04 18:15:25 +0100765 }
766
Ian Rogers62d6c772013-02-27 08:32:07 -0800767 Runtime* runtime = Runtime::Current();
768 runtime->GetThreadList()->SuspendAll();
769 Thread* self = Thread::Current();
770 ThreadState old_state = self->SetStateUnsafe(kRunnable);
771 CHECK_NE(old_state, kRunnable);
Sebastien Hertzf3928792014-11-17 19:00:37 +0100772 if (RequiresDeoptimization()) {
773 runtime->GetInstrumentation()->EnableDeoptimization();
774 }
Sebastien Hertz42cd43f2014-05-13 14:15:41 +0200775 instrumentation_events_ = 0;
Elliott Hughesa2155262011-11-16 16:26:58 -0800776 gDebuggerActive = true;
Ian Rogers62d6c772013-02-27 08:32:07 -0800777 CHECK_EQ(self->SetStateUnsafe(old_state), kRunnable);
778 runtime->GetThreadList()->ResumeAll();
779
780 LOG(INFO) << "Debugger is active";
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700781}
782
783void Dbg::Disconnected() {
Elliott Hughes234ab152011-10-26 14:02:26 -0700784 CHECK(gDebuggerConnected);
785
Elliott Hughesc0f09332012-03-26 13:27:06 -0700786 LOG(INFO) << "Debugger is no longer active";
Elliott Hughes234ab152011-10-26 14:02:26 -0700787
Ian Rogers62d6c772013-02-27 08:32:07 -0800788 // Suspend all threads and exclusively acquire the mutator lock. Set the state of the thread
789 // to kRunnable to avoid scoped object access transitions. Remove the debugger as a listener
790 // and clear the object registry.
791 Runtime* runtime = Runtime::Current();
792 runtime->GetThreadList()->SuspendAll();
793 Thread* self = Thread::Current();
794 ThreadState old_state = self->SetStateUnsafe(kRunnable);
Sebastien Hertzaaea7342014-02-25 15:10:04 +0100795
796 // Debugger may not be active at this point.
797 if (gDebuggerActive) {
798 {
799 // Since we're going to disable deoptimization, we clear the deoptimization requests queue.
800 // This prevents us from having any pending deoptimization request when the debugger attaches
801 // to us again while no event has been requested yet.
Brian Carlstrom306db812014-09-05 13:01:41 -0700802 MutexLock mu(Thread::Current(), *Locks::deoptimization_lock_);
Sebastien Hertz4d25df32014-03-21 17:44:46 +0100803 deoptimization_requests_.clear();
804 full_deoptimization_event_count_ = 0U;
Sebastien Hertz7ec2f1c2014-03-27 20:06:47 +0100805 delayed_full_undeoptimization_count_ = 0U;
Sebastien Hertzaaea7342014-02-25 15:10:04 +0100806 }
Sebastien Hertz42cd43f2014-05-13 14:15:41 +0200807 if (instrumentation_events_ != 0) {
808 runtime->GetInstrumentation()->RemoveListener(&gDebugInstrumentationListener,
809 instrumentation_events_);
810 instrumentation_events_ = 0;
811 }
Sebastien Hertzf3928792014-11-17 19:00:37 +0100812 if (RequiresDeoptimization()) {
813 runtime->GetInstrumentation()->DisableDeoptimization();
814 }
Sebastien Hertzaaea7342014-02-25 15:10:04 +0100815 gDebuggerActive = false;
Sebastien Hertz138dbfc2013-12-04 18:15:25 +0100816 }
Ian Rogers62d6c772013-02-27 08:32:07 -0800817 CHECK_EQ(self->SetStateUnsafe(old_state), kRunnable);
818 runtime->GetThreadList()->ResumeAll();
Sebastien Hertz55f65342015-01-13 22:48:34 +0100819
820 {
821 ScopedObjectAccess soa(self);
822 gRegistry->Clear();
823 }
824
825 gDebuggerConnected = false;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700826}
827
Elliott Hughesc0f09332012-03-26 13:27:06 -0700828bool Dbg::IsDebuggerActive() {
Elliott Hughes3bb81562011-10-21 18:52:59 -0700829 return gDebuggerActive;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700830}
831
Elliott Hughesc0f09332012-03-26 13:27:06 -0700832bool Dbg::IsJdwpConfigured() {
Elliott Hughes3bb81562011-10-21 18:52:59 -0700833 return gJdwpConfigured;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700834}
835
836int64_t Dbg::LastDebuggerActivity() {
Elliott Hughesca951522011-12-05 12:01:32 -0800837 return gJdwpState->LastDebuggerActivity();
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700838}
839
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700840void Dbg::UndoDebuggerSuspensions() {
Elliott Hughes234ab152011-10-26 14:02:26 -0700841 Runtime::Current()->GetThreadList()->UndoDebuggerSuspensions();
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700842}
843
Elliott Hughes88d63092013-01-09 09:55:54 -0800844std::string Dbg::GetClassName(JDWP::RefTypeId class_id) {
Ian Rogersc0542af2014-09-03 16:16:56 -0700845 JDWP::JdwpError error;
846 mirror::Object* o = gRegistry->Get<mirror::Object*>(class_id, &error);
847 if (o == nullptr) {
848 if (error == JDWP::ERR_NONE) {
849 return "NULL";
850 } else {
851 return StringPrintf("invalid object %p", reinterpret_cast<void*>(class_id));
852 }
Elliott Hughes436e3722012-02-17 20:01:47 -0800853 }
854 if (!o->IsClass()) {
Brian Carlstrom7934ac22013-07-26 10:54:15 -0700855 return StringPrintf("non-class %p", o); // This is only used for debugging output anyway.
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -0800856 }
Sebastien Hertz6995c602014-09-09 12:10:13 +0200857 return GetClassName(o->AsClass());
858}
859
860std::string Dbg::GetClassName(mirror::Class* klass) {
Sebastien Hertza9aa0ff2014-09-19 12:07:51 +0200861 if (klass == nullptr) {
862 return "NULL";
863 }
Ian Rogers1ff3c982014-08-12 02:30:58 -0700864 std::string temp;
Sebastien Hertz6995c602014-09-09 12:10:13 +0200865 return DescriptorToName(klass->GetDescriptor(&temp));
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700866}
867
Ian Rogersc0542af2014-09-03 16:16:56 -0700868JDWP::JdwpError Dbg::GetClassObject(JDWP::RefTypeId id, JDWP::ObjectId* class_object_id) {
Elliott Hughes436e3722012-02-17 20:01:47 -0800869 JDWP::JdwpError status;
Ian Rogersc0542af2014-09-03 16:16:56 -0700870 mirror::Class* c = DecodeClass(id, &status);
871 if (c == nullptr) {
872 *class_object_id = 0;
Elliott Hughes436e3722012-02-17 20:01:47 -0800873 return status;
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -0800874 }
Ian Rogersc0542af2014-09-03 16:16:56 -0700875 *class_object_id = gRegistry->Add(c);
Elliott Hughes436e3722012-02-17 20:01:47 -0800876 return JDWP::ERR_NONE;
Elliott Hughes86964332012-02-15 19:37:42 -0800877}
878
Ian Rogersc0542af2014-09-03 16:16:56 -0700879JDWP::JdwpError Dbg::GetSuperclass(JDWP::RefTypeId id, JDWP::RefTypeId* superclass_id) {
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -0800880 JDWP::JdwpError status;
Ian Rogersc0542af2014-09-03 16:16:56 -0700881 mirror::Class* c = DecodeClass(id, &status);
882 if (c == nullptr) {
883 *superclass_id = 0;
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -0800884 return status;
885 }
886 if (c->IsInterface()) {
887 // http://code.google.com/p/android/issues/detail?id=20856
Ian Rogersc0542af2014-09-03 16:16:56 -0700888 *superclass_id = 0;
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -0800889 } else {
Ian Rogersc0542af2014-09-03 16:16:56 -0700890 *superclass_id = gRegistry->Add(c->GetSuperClass());
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -0800891 }
892 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700893}
894
Elliott Hughes436e3722012-02-17 20:01:47 -0800895JDWP::JdwpError Dbg::GetClassLoader(JDWP::RefTypeId id, JDWP::ExpandBuf* pReply) {
Ian Rogersc0542af2014-09-03 16:16:56 -0700896 JDWP::JdwpError error;
897 mirror::Object* o = gRegistry->Get<mirror::Object*>(id, &error);
898 if (o == nullptr) {
Elliott Hughes436e3722012-02-17 20:01:47 -0800899 return JDWP::ERR_INVALID_OBJECT;
900 }
901 expandBufAddObjectId(pReply, gRegistry->Add(o->GetClass()->GetClassLoader()));
902 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700903}
904
Elliott Hughes436e3722012-02-17 20:01:47 -0800905JDWP::JdwpError Dbg::GetModifiers(JDWP::RefTypeId id, JDWP::ExpandBuf* pReply) {
Ian Rogersc0542af2014-09-03 16:16:56 -0700906 JDWP::JdwpError error;
907 mirror::Class* c = DecodeClass(id, &error);
908 if (c == nullptr) {
909 return error;
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -0800910 }
Elliott Hughes436e3722012-02-17 20:01:47 -0800911
912 uint32_t access_flags = c->GetAccessFlags() & kAccJavaFlagsMask;
913
Yevgeny Roubande34eea2014-02-15 01:06:03 +0700914 // Set ACC_SUPER. Dex files don't contain this flag but only classes are supposed to have it set,
915 // not interfaces.
Elliott Hughes436e3722012-02-17 20:01:47 -0800916 // Class.getModifiers doesn't return it, but JDWP does, so we set it here.
Yevgeny Roubande34eea2014-02-15 01:06:03 +0700917 if ((access_flags & kAccInterface) == 0) {
918 access_flags |= kAccSuper;
919 }
Elliott Hughes436e3722012-02-17 20:01:47 -0800920
921 expandBufAdd4BE(pReply, access_flags);
922
923 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700924}
925
Ian Rogersc0542af2014-09-03 16:16:56 -0700926JDWP::JdwpError Dbg::GetMonitorInfo(JDWP::ObjectId object_id, JDWP::ExpandBuf* reply) {
927 JDWP::JdwpError error;
928 mirror::Object* o = gRegistry->Get<mirror::Object*>(object_id, &error);
929 if (o == nullptr) {
Elliott Hughesf327e072013-01-09 16:01:26 -0800930 return JDWP::ERR_INVALID_OBJECT;
931 }
932
933 // Ensure all threads are suspended while we read objects' lock words.
934 Thread* self = Thread::Current();
Sebastien Hertz54263242014-03-19 18:16:50 +0100935 CHECK_EQ(self->GetState(), kRunnable);
936 self->TransitionFromRunnableToSuspended(kSuspended);
937 Runtime::Current()->GetThreadList()->SuspendAll();
Elliott Hughesf327e072013-01-09 16:01:26 -0800938
939 MonitorInfo monitor_info(o);
940
Sebastien Hertz54263242014-03-19 18:16:50 +0100941 Runtime::Current()->GetThreadList()->ResumeAll();
942 self->TransitionFromSuspendedToRunnable();
Elliott Hughesf327e072013-01-09 16:01:26 -0800943
Ian Rogersc0542af2014-09-03 16:16:56 -0700944 if (monitor_info.owner_ != nullptr) {
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700945 expandBufAddObjectId(reply, gRegistry->Add(monitor_info.owner_->GetPeer()));
Elliott Hughesf327e072013-01-09 16:01:26 -0800946 } else {
Ian Rogersc0542af2014-09-03 16:16:56 -0700947 expandBufAddObjectId(reply, gRegistry->Add(nullptr));
Elliott Hughesf327e072013-01-09 16:01:26 -0800948 }
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700949 expandBufAdd4BE(reply, monitor_info.entry_count_);
950 expandBufAdd4BE(reply, monitor_info.waiters_.size());
951 for (size_t i = 0; i < monitor_info.waiters_.size(); ++i) {
952 expandBufAddObjectId(reply, gRegistry->Add(monitor_info.waiters_[i]->GetPeer()));
Elliott Hughesf327e072013-01-09 16:01:26 -0800953 }
954 return JDWP::ERR_NONE;
955}
956
Elliott Hughes734b8c62013-01-11 15:32:45 -0800957JDWP::JdwpError Dbg::GetOwnedMonitors(JDWP::ObjectId thread_id,
Ian Rogersc0542af2014-09-03 16:16:56 -0700958 std::vector<JDWP::ObjectId>* monitors,
959 std::vector<uint32_t>* stack_depths) {
Elliott Hughes4993bbc2013-01-10 15:41:25 -0800960 struct OwnedMonitorVisitor : public StackVisitor {
Hiroshi Yamauchib5a9e3d2014-06-09 12:11:20 -0700961 OwnedMonitorVisitor(Thread* thread, Context* context,
Hiroshi Yamauchicc8c5c52014-06-13 15:08:05 -0700962 std::vector<JDWP::ObjectId>* monitor_vector,
Hiroshi Yamauchib5a9e3d2014-06-09 12:11:20 -0700963 std::vector<uint32_t>* stack_depth_vector)
Elliott Hughes4993bbc2013-01-10 15:41:25 -0800964 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_)
Hiroshi Yamauchib5a9e3d2014-06-09 12:11:20 -0700965 : StackVisitor(thread, context), current_stack_depth(0),
966 monitors(monitor_vector), stack_depths(stack_depth_vector) {}
Elliott Hughes4993bbc2013-01-10 15:41:25 -0800967
968 // TODO: Enable annotalysis. We know lock is held in constructor, but abstraction confuses
969 // annotalysis.
970 bool VisitFrame() NO_THREAD_SAFETY_ANALYSIS {
971 if (!GetMethod()->IsRuntimeMethod()) {
972 Monitor::VisitLocks(this, AppendOwnedMonitors, this);
Elliott Hughes734b8c62013-01-11 15:32:45 -0800973 ++current_stack_depth;
Elliott Hughes4993bbc2013-01-10 15:41:25 -0800974 }
975 return true;
976 }
977
Hiroshi Yamauchicc8c5c52014-06-13 15:08:05 -0700978 static void AppendOwnedMonitors(mirror::Object* owned_monitor, void* arg)
979 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Ian Rogers7a22fa62013-01-23 12:16:16 -0800980 OwnedMonitorVisitor* visitor = reinterpret_cast<OwnedMonitorVisitor*>(arg);
Hiroshi Yamauchicc8c5c52014-06-13 15:08:05 -0700981 visitor->monitors->push_back(gRegistry->Add(owned_monitor));
Hiroshi Yamauchib5a9e3d2014-06-09 12:11:20 -0700982 visitor->stack_depths->push_back(visitor->current_stack_depth);
Elliott Hughes4993bbc2013-01-10 15:41:25 -0800983 }
984
Elliott Hughes734b8c62013-01-11 15:32:45 -0800985 size_t current_stack_depth;
Ian Rogersc0542af2014-09-03 16:16:56 -0700986 std::vector<JDWP::ObjectId>* const monitors;
987 std::vector<uint32_t>* const stack_depths;
Elliott Hughes4993bbc2013-01-10 15:41:25 -0800988 };
Elliott Hughes4993bbc2013-01-10 15:41:25 -0800989
Hiroshi Yamauchib5a9e3d2014-06-09 12:11:20 -0700990 ScopedObjectAccessUnchecked soa(Thread::Current());
Hiroshi Yamauchicc8c5c52014-06-13 15:08:05 -0700991 Thread* thread;
Hiroshi Yamauchib5a9e3d2014-06-09 12:11:20 -0700992 {
993 MutexLock mu(soa.Self(), *Locks::thread_list_lock_);
Ian Rogersc0542af2014-09-03 16:16:56 -0700994 JDWP::JdwpError error;
995 thread = DecodeThread(soa, thread_id, &error);
996 if (thread == nullptr) {
Hiroshi Yamauchib5a9e3d2014-06-09 12:11:20 -0700997 return error;
998 }
999 if (!IsSuspendedForDebugger(soa, thread)) {
1000 return JDWP::ERR_THREAD_NOT_SUSPENDED;
1001 }
Hiroshi Yamauchib5a9e3d2014-06-09 12:11:20 -07001002 }
Hiroshi Yamauchicc8c5c52014-06-13 15:08:05 -07001003 std::unique_ptr<Context> context(Context::Create());
Ian Rogersc0542af2014-09-03 16:16:56 -07001004 OwnedMonitorVisitor visitor(thread, context.get(), monitors, stack_depths);
Hiroshi Yamauchicc8c5c52014-06-13 15:08:05 -07001005 visitor.WalkStack();
Elliott Hughes4993bbc2013-01-10 15:41:25 -08001006 return JDWP::ERR_NONE;
1007}
1008
Sebastien Hertz52d131d2014-03-13 16:17:40 +01001009JDWP::JdwpError Dbg::GetContendedMonitor(JDWP::ObjectId thread_id,
Ian Rogersc0542af2014-09-03 16:16:56 -07001010 JDWP::ObjectId* contended_monitor) {
Hiroshi Yamauchib5a9e3d2014-06-09 12:11:20 -07001011 mirror::Object* contended_monitor_obj;
Elliott Hughesf9501702013-01-11 11:22:27 -08001012 ScopedObjectAccessUnchecked soa(Thread::Current());
Ian Rogersc0542af2014-09-03 16:16:56 -07001013 *contended_monitor = 0;
Hiroshi Yamauchib5a9e3d2014-06-09 12:11:20 -07001014 {
1015 MutexLock mu(soa.Self(), *Locks::thread_list_lock_);
Ian Rogersc0542af2014-09-03 16:16:56 -07001016 JDWP::JdwpError error;
1017 Thread* thread = DecodeThread(soa, thread_id, &error);
1018 if (thread == nullptr) {
Hiroshi Yamauchib5a9e3d2014-06-09 12:11:20 -07001019 return error;
1020 }
1021 if (!IsSuspendedForDebugger(soa, thread)) {
1022 return JDWP::ERR_THREAD_NOT_SUSPENDED;
1023 }
1024 contended_monitor_obj = Monitor::GetContendedMonitor(thread);
Elliott Hughesf9501702013-01-11 11:22:27 -08001025 }
Hiroshi Yamauchib5a9e3d2014-06-09 12:11:20 -07001026 // Add() requires the thread_list_lock_ not held to avoid the lock
1027 // level violation.
Ian Rogersc0542af2014-09-03 16:16:56 -07001028 *contended_monitor = gRegistry->Add(contended_monitor_obj);
Elliott Hughesf9501702013-01-11 11:22:27 -08001029 return JDWP::ERR_NONE;
1030}
1031
Elliott Hughesec0f83d2013-01-15 16:54:08 -08001032JDWP::JdwpError Dbg::GetInstanceCounts(const std::vector<JDWP::RefTypeId>& class_ids,
Ian Rogersc0542af2014-09-03 16:16:56 -07001033 std::vector<uint64_t>* counts) {
Mathieu Chartier412c7fc2014-02-07 12:18:39 -08001034 gc::Heap* heap = Runtime::Current()->GetHeap();
1035 heap->CollectGarbage(false);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001036 std::vector<mirror::Class*> classes;
Ian Rogersc0542af2014-09-03 16:16:56 -07001037 counts->clear();
Elliott Hughesec0f83d2013-01-15 16:54:08 -08001038 for (size_t i = 0; i < class_ids.size(); ++i) {
Ian Rogersc0542af2014-09-03 16:16:56 -07001039 JDWP::JdwpError error;
1040 mirror::Class* c = DecodeClass(class_ids[i], &error);
1041 if (c == nullptr) {
1042 return error;
Elliott Hughesec0f83d2013-01-15 16:54:08 -08001043 }
1044 classes.push_back(c);
Ian Rogersc0542af2014-09-03 16:16:56 -07001045 counts->push_back(0);
Elliott Hughesec0f83d2013-01-15 16:54:08 -08001046 }
Ian Rogersc0542af2014-09-03 16:16:56 -07001047 heap->CountInstances(classes, false, &(*counts)[0]);
Elliott Hughesec0f83d2013-01-15 16:54:08 -08001048 return JDWP::ERR_NONE;
1049}
1050
Ian Rogersc0542af2014-09-03 16:16:56 -07001051JDWP::JdwpError Dbg::GetInstances(JDWP::RefTypeId class_id, int32_t max_count,
1052 std::vector<JDWP::ObjectId>* instances) {
Mathieu Chartier412c7fc2014-02-07 12:18:39 -08001053 gc::Heap* heap = Runtime::Current()->GetHeap();
1054 // We only want reachable instances, so do a GC.
1055 heap->CollectGarbage(false);
Ian Rogersc0542af2014-09-03 16:16:56 -07001056 JDWP::JdwpError error;
1057 mirror::Class* c = DecodeClass(class_id, &error);
Mathieu Chartier412c7fc2014-02-07 12:18:39 -08001058 if (c == nullptr) {
Ian Rogersc0542af2014-09-03 16:16:56 -07001059 return error;
Elliott Hughes3b78c942013-01-15 17:35:41 -08001060 }
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001061 std::vector<mirror::Object*> raw_instances;
Elliott Hughes3b78c942013-01-15 17:35:41 -08001062 Runtime::Current()->GetHeap()->GetInstances(c, max_count, raw_instances);
1063 for (size_t i = 0; i < raw_instances.size(); ++i) {
Ian Rogersc0542af2014-09-03 16:16:56 -07001064 instances->push_back(gRegistry->Add(raw_instances[i]));
Elliott Hughes3b78c942013-01-15 17:35:41 -08001065 }
1066 return JDWP::ERR_NONE;
1067}
1068
Elliott Hughes0cbaff52013-01-16 15:28:01 -08001069JDWP::JdwpError Dbg::GetReferringObjects(JDWP::ObjectId object_id, int32_t max_count,
Ian Rogersc0542af2014-09-03 16:16:56 -07001070 std::vector<JDWP::ObjectId>* referring_objects) {
Mathieu Chartier412c7fc2014-02-07 12:18:39 -08001071 gc::Heap* heap = Runtime::Current()->GetHeap();
1072 heap->CollectGarbage(false);
Ian Rogersc0542af2014-09-03 16:16:56 -07001073 JDWP::JdwpError error;
1074 mirror::Object* o = gRegistry->Get<mirror::Object*>(object_id, &error);
1075 if (o == nullptr) {
Elliott Hughes0cbaff52013-01-16 15:28:01 -08001076 return JDWP::ERR_INVALID_OBJECT;
1077 }
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001078 std::vector<mirror::Object*> raw_instances;
Mathieu Chartier412c7fc2014-02-07 12:18:39 -08001079 heap->GetReferringObjects(o, max_count, raw_instances);
Elliott Hughes0cbaff52013-01-16 15:28:01 -08001080 for (size_t i = 0; i < raw_instances.size(); ++i) {
Ian Rogersc0542af2014-09-03 16:16:56 -07001081 referring_objects->push_back(gRegistry->Add(raw_instances[i]));
Elliott Hughes0cbaff52013-01-16 15:28:01 -08001082 }
1083 return JDWP::ERR_NONE;
1084}
1085
Ian Rogersc0542af2014-09-03 16:16:56 -07001086JDWP::JdwpError Dbg::DisableCollection(JDWP::ObjectId object_id) {
1087 JDWP::JdwpError error;
1088 mirror::Object* o = gRegistry->Get<mirror::Object*>(object_id, &error);
1089 if (o == nullptr) {
Sebastien Hertze96060a2013-12-11 12:06:28 +01001090 return JDWP::ERR_INVALID_OBJECT;
1091 }
Elliott Hughes64f574f2013-02-20 14:57:12 -08001092 gRegistry->DisableCollection(object_id);
1093 return JDWP::ERR_NONE;
1094}
1095
Ian Rogersc0542af2014-09-03 16:16:56 -07001096JDWP::JdwpError Dbg::EnableCollection(JDWP::ObjectId object_id) {
1097 JDWP::JdwpError error;
1098 mirror::Object* o = gRegistry->Get<mirror::Object*>(object_id, &error);
Sebastien Hertze96060a2013-12-11 12:06:28 +01001099 // Unlike DisableCollection, JDWP specs do not state an invalid object causes an error. The RI
1100 // also ignores these cases and never return an error. However it's not obvious why this command
1101 // should behave differently from DisableCollection and IsCollected commands. So let's be more
1102 // strict and return an error if this happens.
Ian Rogersc0542af2014-09-03 16:16:56 -07001103 if (o == nullptr) {
Sebastien Hertze96060a2013-12-11 12:06:28 +01001104 return JDWP::ERR_INVALID_OBJECT;
1105 }
Elliott Hughes64f574f2013-02-20 14:57:12 -08001106 gRegistry->EnableCollection(object_id);
1107 return JDWP::ERR_NONE;
1108}
1109
Ian Rogersc0542af2014-09-03 16:16:56 -07001110JDWP::JdwpError Dbg::IsCollected(JDWP::ObjectId object_id, bool* is_collected) {
1111 *is_collected = true;
Sebastien Hertz65637eb2014-01-10 17:40:02 +01001112 if (object_id == 0) {
1113 // Null object id is invalid.
Sebastien Hertze96060a2013-12-11 12:06:28 +01001114 return JDWP::ERR_INVALID_OBJECT;
1115 }
Sebastien Hertz65637eb2014-01-10 17:40:02 +01001116 // JDWP specs state an INVALID_OBJECT error is returned if the object ID is not valid. However
1117 // the RI seems to ignore this and assume object has been collected.
Ian Rogersc0542af2014-09-03 16:16:56 -07001118 JDWP::JdwpError error;
1119 mirror::Object* o = gRegistry->Get<mirror::Object*>(object_id, &error);
1120 if (o != nullptr) {
1121 *is_collected = gRegistry->IsCollected(object_id);
Sebastien Hertz65637eb2014-01-10 17:40:02 +01001122 }
Elliott Hughes64f574f2013-02-20 14:57:12 -08001123 return JDWP::ERR_NONE;
1124}
1125
Ian Rogersc0542af2014-09-03 16:16:56 -07001126void Dbg::DisposeObject(JDWP::ObjectId object_id, uint32_t reference_count) {
Elliott Hughes64f574f2013-02-20 14:57:12 -08001127 gRegistry->DisposeObject(object_id, reference_count);
1128}
1129
Sebastien Hertz6995c602014-09-09 12:10:13 +02001130JDWP::JdwpTypeTag Dbg::GetTypeTag(mirror::Class* klass) {
Sebastien Hertz4d8fd492014-03-28 16:29:41 +01001131 DCHECK(klass != nullptr);
1132 if (klass->IsArrayClass()) {
1133 return JDWP::TT_ARRAY;
1134 } else if (klass->IsInterface()) {
1135 return JDWP::TT_INTERFACE;
1136 } else {
1137 return JDWP::TT_CLASS;
1138 }
1139}
1140
Elliott Hughes88d63092013-01-09 09:55:54 -08001141JDWP::JdwpError Dbg::GetReflectedType(JDWP::RefTypeId class_id, JDWP::ExpandBuf* pReply) {
Ian Rogersc0542af2014-09-03 16:16:56 -07001142 JDWP::JdwpError error;
1143 mirror::Class* c = DecodeClass(class_id, &error);
1144 if (c == nullptr) {
1145 return error;
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -08001146 }
Elliott Hughes436e3722012-02-17 20:01:47 -08001147
Sebastien Hertz4d8fd492014-03-28 16:29:41 +01001148 JDWP::JdwpTypeTag type_tag = GetTypeTag(c);
1149 expandBufAdd1(pReply, type_tag);
Elliott Hughes88d63092013-01-09 09:55:54 -08001150 expandBufAddRefTypeId(pReply, class_id);
Elliott Hughes436e3722012-02-17 20:01:47 -08001151 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001152}
1153
Ian Rogersc0542af2014-09-03 16:16:56 -07001154void Dbg::GetClassList(std::vector<JDWP::RefTypeId>* classes) {
Elliott Hughesa2155262011-11-16 16:26:58 -08001155 // Get the complete list of reference classes (i.e. all classes except
1156 // the primitive types).
1157 // Returns a newly-allocated buffer full of RefTypeId values.
1158 struct ClassListCreator {
Andreas Gampe277ccbd2014-11-03 21:36:10 -08001159 explicit ClassListCreator(std::vector<JDWP::RefTypeId>* classes_in) : classes(classes_in) {
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -08001160 }
1161
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001162 static bool Visit(mirror::Class* c, void* arg) {
Elliott Hughesa2155262011-11-16 16:26:58 -08001163 return reinterpret_cast<ClassListCreator*>(arg)->Visit(c);
1164 }
1165
Elliott Hughes64f574f2013-02-20 14:57:12 -08001166 // TODO: Enable annotalysis. We know lock is held in constructor, but abstraction confuses
1167 // annotalysis.
1168 bool Visit(mirror::Class* c) NO_THREAD_SAFETY_ANALYSIS {
Elliott Hughesa2155262011-11-16 16:26:58 -08001169 if (!c->IsPrimitive()) {
Ian Rogersc0542af2014-09-03 16:16:56 -07001170 classes->push_back(gRegistry->AddRefType(c));
Elliott Hughesa2155262011-11-16 16:26:58 -08001171 }
1172 return true;
1173 }
1174
Ian Rogersc0542af2014-09-03 16:16:56 -07001175 std::vector<JDWP::RefTypeId>* const classes;
Elliott Hughesa2155262011-11-16 16:26:58 -08001176 };
1177
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -08001178 ClassListCreator clc(classes);
Sebastien Hertz4537c412014-08-28 14:41:50 +02001179 Runtime::Current()->GetClassLinker()->VisitClassesWithoutClassesLock(ClassListCreator::Visit,
1180 &clc);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001181}
1182
Ian Rogers1ff3c982014-08-12 02:30:58 -07001183JDWP::JdwpError Dbg::GetClassInfo(JDWP::RefTypeId class_id, JDWP::JdwpTypeTag* pTypeTag,
1184 uint32_t* pStatus, std::string* pDescriptor) {
Ian Rogersc0542af2014-09-03 16:16:56 -07001185 JDWP::JdwpError error;
1186 mirror::Class* c = DecodeClass(class_id, &error);
1187 if (c == nullptr) {
1188 return error;
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -08001189 }
1190
Elliott Hughesa2155262011-11-16 16:26:58 -08001191 if (c->IsArrayClass()) {
1192 *pStatus = JDWP::CS_VERIFIED | JDWP::CS_PREPARED;
1193 *pTypeTag = JDWP::TT_ARRAY;
1194 } else {
1195 if (c->IsErroneous()) {
1196 *pStatus = JDWP::CS_ERROR;
1197 } else {
1198 *pStatus = JDWP::CS_VERIFIED | JDWP::CS_PREPARED | JDWP::CS_INITIALIZED;
1199 }
1200 *pTypeTag = c->IsInterface() ? JDWP::TT_INTERFACE : JDWP::TT_CLASS;
1201 }
1202
Ian Rogersc0542af2014-09-03 16:16:56 -07001203 if (pDescriptor != nullptr) {
Ian Rogers1ff3c982014-08-12 02:30:58 -07001204 std::string temp;
1205 *pDescriptor = c->GetDescriptor(&temp);
Elliott Hughesa2155262011-11-16 16:26:58 -08001206 }
Elliott Hughes436e3722012-02-17 20:01:47 -08001207 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001208}
1209
Ian Rogersc0542af2014-09-03 16:16:56 -07001210void Dbg::FindLoadedClassBySignature(const char* descriptor, std::vector<JDWP::RefTypeId>* ids) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001211 std::vector<mirror::Class*> classes;
Elliott Hughes6fa602d2011-12-02 17:54:25 -08001212 Runtime::Current()->GetClassLinker()->LookupClasses(descriptor, classes);
Ian Rogersc0542af2014-09-03 16:16:56 -07001213 ids->clear();
Elliott Hughes6fa602d2011-12-02 17:54:25 -08001214 for (size_t i = 0; i < classes.size(); ++i) {
Ian Rogersc0542af2014-09-03 16:16:56 -07001215 ids->push_back(gRegistry->Add(classes[i]));
Elliott Hughes6fa602d2011-12-02 17:54:25 -08001216 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001217}
1218
Ian Rogersc0542af2014-09-03 16:16:56 -07001219JDWP::JdwpError Dbg::GetReferenceType(JDWP::ObjectId object_id, JDWP::ExpandBuf* pReply) {
1220 JDWP::JdwpError error;
1221 mirror::Object* o = gRegistry->Get<mirror::Object*>(object_id, &error);
1222 if (o == nullptr) {
Elliott Hughes2435a572012-02-17 16:07:41 -08001223 return JDWP::ERR_INVALID_OBJECT;
Elliott Hughes499c5132011-11-17 14:55:11 -08001224 }
Elliott Hughes2435a572012-02-17 16:07:41 -08001225
Sebastien Hertz4d8fd492014-03-28 16:29:41 +01001226 JDWP::JdwpTypeTag type_tag = GetTypeTag(o->GetClass());
Elliott Hughes64f574f2013-02-20 14:57:12 -08001227 JDWP::RefTypeId type_id = gRegistry->AddRefType(o->GetClass());
Elliott Hughes2435a572012-02-17 16:07:41 -08001228
1229 expandBufAdd1(pReply, type_tag);
1230 expandBufAddRefTypeId(pReply, type_id);
1231
1232 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001233}
1234
Ian Rogersfc0e94b2013-09-23 23:51:32 -07001235JDWP::JdwpError Dbg::GetSignature(JDWP::RefTypeId class_id, std::string* signature) {
Ian Rogersc0542af2014-09-03 16:16:56 -07001236 JDWP::JdwpError error;
1237 mirror::Class* c = DecodeClass(class_id, &error);
1238 if (c == nullptr) {
1239 return error;
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -08001240 }
Ian Rogers1ff3c982014-08-12 02:30:58 -07001241 std::string temp;
1242 *signature = c->GetDescriptor(&temp);
Elliott Hughes1fe7afb2012-02-13 17:23:03 -08001243 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001244}
1245
Ian Rogersc0542af2014-09-03 16:16:56 -07001246JDWP::JdwpError Dbg::GetSourceFile(JDWP::RefTypeId class_id, std::string* result) {
1247 JDWP::JdwpError error;
1248 mirror::Class* c = DecodeClass(class_id, &error);
Sebastien Hertz4206eb52014-06-05 10:15:45 +02001249 if (c == nullptr) {
Ian Rogersc0542af2014-09-03 16:16:56 -07001250 return error;
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -08001251 }
Sebastien Hertz4206eb52014-06-05 10:15:45 +02001252 const char* source_file = c->GetSourceFile();
1253 if (source_file == nullptr) {
Sebastien Hertzb7054ba2014-03-13 11:52:31 +01001254 return JDWP::ERR_ABSENT_INFORMATION;
1255 }
Ian Rogersc0542af2014-09-03 16:16:56 -07001256 *result = source_file;
Elliott Hughes436e3722012-02-17 20:01:47 -08001257 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001258}
1259
Ian Rogersc0542af2014-09-03 16:16:56 -07001260JDWP::JdwpError Dbg::GetObjectTag(JDWP::ObjectId object_id, uint8_t* tag) {
Ian Rogers98379392014-02-24 16:53:16 -08001261 ScopedObjectAccessUnchecked soa(Thread::Current());
Ian Rogersc0542af2014-09-03 16:16:56 -07001262 JDWP::JdwpError error;
1263 mirror::Object* o = gRegistry->Get<mirror::Object*>(object_id, &error);
1264 if (error != JDWP::ERR_NONE) {
1265 *tag = JDWP::JT_VOID;
1266 return error;
Elliott Hughes546b9862012-06-20 16:06:13 -07001267 }
Ian Rogersc0542af2014-09-03 16:16:56 -07001268 *tag = TagFromObject(soa, o);
Elliott Hughes546b9862012-06-20 16:06:13 -07001269 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001270}
1271
Elliott Hughesaed4be92011-12-02 16:16:23 -08001272size_t Dbg::GetTagWidth(JDWP::JdwpTag tag) {
Elliott Hughesdbb40792011-11-18 17:05:22 -08001273 switch (tag) {
1274 case JDWP::JT_VOID:
1275 return 0;
1276 case JDWP::JT_BYTE:
1277 case JDWP::JT_BOOLEAN:
1278 return 1;
1279 case JDWP::JT_CHAR:
1280 case JDWP::JT_SHORT:
1281 return 2;
1282 case JDWP::JT_FLOAT:
1283 case JDWP::JT_INT:
1284 return 4;
1285 case JDWP::JT_ARRAY:
1286 case JDWP::JT_OBJECT:
1287 case JDWP::JT_STRING:
1288 case JDWP::JT_THREAD:
1289 case JDWP::JT_THREAD_GROUP:
1290 case JDWP::JT_CLASS_LOADER:
1291 case JDWP::JT_CLASS_OBJECT:
1292 return sizeof(JDWP::ObjectId);
1293 case JDWP::JT_DOUBLE:
1294 case JDWP::JT_LONG:
1295 return 8;
1296 default:
Elliott Hughes3d30d9b2011-12-07 17:35:48 -08001297 LOG(FATAL) << "Unknown tag " << tag;
Elliott Hughesdbb40792011-11-18 17:05:22 -08001298 return -1;
1299 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001300}
1301
Ian Rogersc0542af2014-09-03 16:16:56 -07001302JDWP::JdwpError Dbg::GetArrayLength(JDWP::ObjectId array_id, int32_t* length) {
1303 JDWP::JdwpError error;
1304 mirror::Array* a = DecodeNonNullArray(array_id, &error);
1305 if (a == nullptr) {
1306 return error;
Elliott Hughes24437992011-11-30 14:49:33 -08001307 }
Ian Rogersc0542af2014-09-03 16:16:56 -07001308 *length = a->GetLength();
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -08001309 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001310}
1311
Elliott Hughes88d63092013-01-09 09:55:54 -08001312JDWP::JdwpError Dbg::OutputArray(JDWP::ObjectId array_id, int offset, int count, JDWP::ExpandBuf* pReply) {
Ian Rogersc0542af2014-09-03 16:16:56 -07001313 JDWP::JdwpError error;
1314 mirror::Array* a = DecodeNonNullArray(array_id, &error);
Ian Rogers98379392014-02-24 16:53:16 -08001315 if (a == nullptr) {
Ian Rogersc0542af2014-09-03 16:16:56 -07001316 return error;
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -08001317 }
Elliott Hughes24437992011-11-30 14:49:33 -08001318
1319 if (offset < 0 || count < 0 || offset > a->GetLength() || a->GetLength() - offset < count) {
1320 LOG(WARNING) << __FUNCTION__ << " access out of bounds: offset=" << offset << "; count=" << count;
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -08001321 return JDWP::ERR_INVALID_LENGTH;
Elliott Hughes24437992011-11-30 14:49:33 -08001322 }
Ian Rogers1ff3c982014-08-12 02:30:58 -07001323 JDWP::JdwpTag element_tag = BasicTagFromClass(a->GetClass()->GetComponentType());
1324 expandBufAdd1(pReply, element_tag);
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -08001325 expandBufAdd4BE(pReply, count);
1326
Ian Rogers1ff3c982014-08-12 02:30:58 -07001327 if (IsPrimitiveTag(element_tag)) {
1328 size_t width = GetTagWidth(element_tag);
Elliott Hughes24437992011-11-30 14:49:33 -08001329 uint8_t* dst = expandBufAddSpace(pReply, count * width);
1330 if (width == 8) {
Ian Rogersef7d42f2014-01-06 12:55:46 -08001331 const uint64_t* src8 = reinterpret_cast<uint64_t*>(a->GetRawData(sizeof(uint64_t), 0));
Elliott Hughes24437992011-11-30 14:49:33 -08001332 for (int i = 0; i < count; ++i) JDWP::Write8BE(&dst, src8[offset + i]);
1333 } else if (width == 4) {
Ian Rogersef7d42f2014-01-06 12:55:46 -08001334 const uint32_t* src4 = reinterpret_cast<uint32_t*>(a->GetRawData(sizeof(uint32_t), 0));
Elliott Hughes24437992011-11-30 14:49:33 -08001335 for (int i = 0; i < count; ++i) JDWP::Write4BE(&dst, src4[offset + i]);
1336 } else if (width == 2) {
Ian Rogersef7d42f2014-01-06 12:55:46 -08001337 const uint16_t* src2 = reinterpret_cast<uint16_t*>(a->GetRawData(sizeof(uint16_t), 0));
Elliott Hughes24437992011-11-30 14:49:33 -08001338 for (int i = 0; i < count; ++i) JDWP::Write2BE(&dst, src2[offset + i]);
1339 } else {
Ian Rogersef7d42f2014-01-06 12:55:46 -08001340 const uint8_t* src = reinterpret_cast<uint8_t*>(a->GetRawData(sizeof(uint8_t), 0));
Elliott Hughes24437992011-11-30 14:49:33 -08001341 memcpy(dst, &src[offset * width], count * width);
1342 }
1343 } else {
Ian Rogers98379392014-02-24 16:53:16 -08001344 ScopedObjectAccessUnchecked soa(Thread::Current());
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001345 mirror::ObjectArray<mirror::Object>* oa = a->AsObjectArray<mirror::Object>();
Elliott Hughes24437992011-11-30 14:49:33 -08001346 for (int i = 0; i < count; ++i) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001347 mirror::Object* element = oa->Get(offset + i);
Ian Rogers98379392014-02-24 16:53:16 -08001348 JDWP::JdwpTag specific_tag = (element != nullptr) ? TagFromObject(soa, element)
Ian Rogers1ff3c982014-08-12 02:30:58 -07001349 : element_tag;
Elliott Hughes24437992011-11-30 14:49:33 -08001350 expandBufAdd1(pReply, specific_tag);
1351 expandBufAddObjectId(pReply, gRegistry->Add(element));
1352 }
1353 }
1354
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -08001355 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001356}
1357
Ian Rogersef7d42f2014-01-06 12:55:46 -08001358template <typename T>
Ian Rogersc0542af2014-09-03 16:16:56 -07001359static void CopyArrayData(mirror::Array* a, JDWP::Request* src, int offset, int count)
Ian Rogersef7d42f2014-01-06 12:55:46 -08001360 NO_THREAD_SAFETY_ANALYSIS {
1361 // TODO: fix when annotalysis correctly handles non-member functions.
Elliott Hughes4b9702c2013-02-20 18:13:24 -08001362 DCHECK(a->GetClass()->IsPrimitiveArray());
1363
Ian Rogersef7d42f2014-01-06 12:55:46 -08001364 T* dst = reinterpret_cast<T*>(a->GetRawData(sizeof(T), offset));
Elliott Hughes4b9702c2013-02-20 18:13:24 -08001365 for (int i = 0; i < count; ++i) {
Ian Rogersc0542af2014-09-03 16:16:56 -07001366 *dst++ = src->ReadValue(sizeof(T));
Elliott Hughes4b9702c2013-02-20 18:13:24 -08001367 }
1368}
1369
Elliott Hughes88d63092013-01-09 09:55:54 -08001370JDWP::JdwpError Dbg::SetArrayElements(JDWP::ObjectId array_id, int offset, int count,
Ian Rogersc0542af2014-09-03 16:16:56 -07001371 JDWP::Request* request) {
1372 JDWP::JdwpError error;
1373 mirror::Array* dst = DecodeNonNullArray(array_id, &error);
1374 if (dst == nullptr) {
1375 return error;
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -08001376 }
Elliott Hughesf03b8f62011-12-02 14:26:25 -08001377
Elliott Hughes4b9702c2013-02-20 18:13:24 -08001378 if (offset < 0 || count < 0 || offset > dst->GetLength() || dst->GetLength() - offset < count) {
Elliott Hughesf03b8f62011-12-02 14:26:25 -08001379 LOG(WARNING) << __FUNCTION__ << " access out of bounds: offset=" << offset << "; count=" << count;
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -08001380 return JDWP::ERR_INVALID_LENGTH;
Elliott Hughesf03b8f62011-12-02 14:26:25 -08001381 }
Ian Rogers1ff3c982014-08-12 02:30:58 -07001382 JDWP::JdwpTag element_tag = BasicTagFromClass(dst->GetClass()->GetComponentType());
Elliott Hughesf03b8f62011-12-02 14:26:25 -08001383
Ian Rogers1ff3c982014-08-12 02:30:58 -07001384 if (IsPrimitiveTag(element_tag)) {
1385 size_t width = GetTagWidth(element_tag);
Elliott Hughesf03b8f62011-12-02 14:26:25 -08001386 if (width == 8) {
Elliott Hughes4b9702c2013-02-20 18:13:24 -08001387 CopyArrayData<uint64_t>(dst, request, offset, count);
Elliott Hughesf03b8f62011-12-02 14:26:25 -08001388 } else if (width == 4) {
Elliott Hughes4b9702c2013-02-20 18:13:24 -08001389 CopyArrayData<uint32_t>(dst, request, offset, count);
Elliott Hughesf03b8f62011-12-02 14:26:25 -08001390 } else if (width == 2) {
Elliott Hughes4b9702c2013-02-20 18:13:24 -08001391 CopyArrayData<uint16_t>(dst, request, offset, count);
Elliott Hughesf03b8f62011-12-02 14:26:25 -08001392 } else {
Elliott Hughes4b9702c2013-02-20 18:13:24 -08001393 CopyArrayData<uint8_t>(dst, request, offset, count);
Elliott Hughesf03b8f62011-12-02 14:26:25 -08001394 }
1395 } else {
Elliott Hughes4b9702c2013-02-20 18:13:24 -08001396 mirror::ObjectArray<mirror::Object>* oa = dst->AsObjectArray<mirror::Object>();
Elliott Hughesf03b8f62011-12-02 14:26:25 -08001397 for (int i = 0; i < count; ++i) {
Ian Rogersc0542af2014-09-03 16:16:56 -07001398 JDWP::ObjectId id = request->ReadObjectId();
Ian Rogersc0542af2014-09-03 16:16:56 -07001399 mirror::Object* o = gRegistry->Get<mirror::Object*>(id, &error);
1400 if (error != JDWP::ERR_NONE) {
1401 return error;
Elliott Hughes436e3722012-02-17 20:01:47 -08001402 }
Sebastien Hertzd2fe10a2014-01-15 10:20:56 +01001403 oa->Set<false>(offset + i, o);
Elliott Hughesf03b8f62011-12-02 14:26:25 -08001404 }
1405 }
1406
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -08001407 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001408}
1409
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -08001410JDWP::ObjectId Dbg::CreateString(const std::string& str) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001411 return gRegistry->Add(mirror::String::AllocFromModifiedUtf8(Thread::Current(), str.c_str()));
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001412}
1413
Ian Rogersc0542af2014-09-03 16:16:56 -07001414JDWP::JdwpError Dbg::CreateObject(JDWP::RefTypeId class_id, JDWP::ObjectId* new_object) {
1415 JDWP::JdwpError error;
1416 mirror::Class* c = DecodeClass(class_id, &error);
1417 if (c == nullptr) {
1418 *new_object = 0;
1419 return error;
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -08001420 }
Ian Rogersc0542af2014-09-03 16:16:56 -07001421 *new_object = gRegistry->Add(c->AllocObject(Thread::Current()));
Elliott Hughes436e3722012-02-17 20:01:47 -08001422 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001423}
1424
Elliott Hughesbf13d362011-12-08 15:51:37 -08001425/*
1426 * Used by Eclipse's "Display" view to evaluate "new byte[5]" to get "(byte[]) [0, 0, 0, 0, 0]".
1427 */
Elliott Hughes88d63092013-01-09 09:55:54 -08001428JDWP::JdwpError Dbg::CreateArrayObject(JDWP::RefTypeId array_class_id, uint32_t length,
Ian Rogersc0542af2014-09-03 16:16:56 -07001429 JDWP::ObjectId* new_array) {
1430 JDWP::JdwpError error;
1431 mirror::Class* c = DecodeClass(array_class_id, &error);
1432 if (c == nullptr) {
1433 *new_array = 0;
1434 return error;
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -08001435 }
Ian Rogersc0542af2014-09-03 16:16:56 -07001436 *new_array = gRegistry->Add(mirror::Array::Alloc<true>(Thread::Current(), c, length,
Hiroshi Yamauchif0edfc32014-09-25 11:46:46 -07001437 c->GetComponentSizeShift(),
Ian Rogersc0542af2014-09-03 16:16:56 -07001438 Runtime::Current()->GetHeap()->GetCurrentAllocator()));
Elliott Hughes436e3722012-02-17 20:01:47 -08001439 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001440}
1441
Sebastien Hertz6995c602014-09-09 12:10:13 +02001442JDWP::FieldId Dbg::ToFieldId(const mirror::ArtField* f) {
Mathieu Chartier590fee92013-09-13 13:46:47 -07001443 CHECK(!kMovingFields);
Elliott Hughes03181a82011-11-17 17:22:21 -08001444 return static_cast<JDWP::FieldId>(reinterpret_cast<uintptr_t>(f));
Elliott Hughes03181a82011-11-17 17:22:21 -08001445}
1446
Brian Carlstromea46f952013-07-30 01:26:50 -07001447static JDWP::MethodId ToMethodId(const mirror::ArtMethod* m)
Ian Rogersb726dcb2012-09-05 08:57:23 -07001448 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Mathieu Chartier590fee92013-09-13 13:46:47 -07001449 CHECK(!kMovingMethods);
Elliott Hughes03181a82011-11-17 17:22:21 -08001450 return static_cast<JDWP::MethodId>(reinterpret_cast<uintptr_t>(m));
Elliott Hughes03181a82011-11-17 17:22:21 -08001451}
1452
Brian Carlstromea46f952013-07-30 01:26:50 -07001453static mirror::ArtField* FromFieldId(JDWP::FieldId fid)
Ian Rogersb726dcb2012-09-05 08:57:23 -07001454 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Mathieu Chartier590fee92013-09-13 13:46:47 -07001455 CHECK(!kMovingFields);
Brian Carlstromea46f952013-07-30 01:26:50 -07001456 return reinterpret_cast<mirror::ArtField*>(static_cast<uintptr_t>(fid));
Elliott Hughesaed4be92011-12-02 16:16:23 -08001457}
1458
Brian Carlstromea46f952013-07-30 01:26:50 -07001459static mirror::ArtMethod* FromMethodId(JDWP::MethodId mid)
Ian Rogersb726dcb2012-09-05 08:57:23 -07001460 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Mathieu Chartier590fee92013-09-13 13:46:47 -07001461 CHECK(!kMovingMethods);
Brian Carlstromea46f952013-07-30 01:26:50 -07001462 return reinterpret_cast<mirror::ArtMethod*>(static_cast<uintptr_t>(mid));
Elliott Hughes03181a82011-11-17 17:22:21 -08001463}
1464
Sebastien Hertz6995c602014-09-09 12:10:13 +02001465bool Dbg::MatchThread(JDWP::ObjectId expected_thread_id, Thread* event_thread) {
1466 CHECK(event_thread != nullptr);
1467 JDWP::JdwpError error;
1468 mirror::Object* expected_thread_peer = gRegistry->Get<mirror::Object*>(expected_thread_id,
1469 &error);
1470 return expected_thread_peer == event_thread->GetPeer();
1471}
1472
1473bool Dbg::MatchLocation(const JDWP::JdwpLocation& expected_location,
1474 const JDWP::EventLocation& event_location) {
1475 if (expected_location.dex_pc != event_location.dex_pc) {
1476 return false;
1477 }
1478 mirror::ArtMethod* m = FromMethodId(expected_location.method_id);
1479 return m == event_location.method;
1480}
1481
1482bool Dbg::MatchType(mirror::Class* event_class, JDWP::RefTypeId class_id) {
Sebastien Hertza9aa0ff2014-09-19 12:07:51 +02001483 if (event_class == nullptr) {
1484 return false;
1485 }
Sebastien Hertz6995c602014-09-09 12:10:13 +02001486 JDWP::JdwpError error;
1487 mirror::Class* expected_class = DecodeClass(class_id, &error);
1488 CHECK(expected_class != nullptr);
1489 return expected_class->IsAssignableFrom(event_class);
1490}
1491
1492bool Dbg::MatchField(JDWP::RefTypeId expected_type_id, JDWP::FieldId expected_field_id,
1493 mirror::ArtField* event_field) {
1494 mirror::ArtField* expected_field = FromFieldId(expected_field_id);
1495 if (expected_field != event_field) {
1496 return false;
1497 }
1498 return Dbg::MatchType(event_field->GetDeclaringClass(), expected_type_id);
1499}
1500
1501bool Dbg::MatchInstance(JDWP::ObjectId expected_instance_id, mirror::Object* event_instance) {
1502 JDWP::JdwpError error;
1503 mirror::Object* modifier_instance = gRegistry->Get<mirror::Object*>(expected_instance_id, &error);
1504 return modifier_instance == event_instance;
1505}
1506
1507void Dbg::SetJdwpLocation(JDWP::JdwpLocation* location, mirror::ArtMethod* m, uint32_t dex_pc)
Ian Rogersb726dcb2012-09-05 08:57:23 -07001508 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Ian Rogersc0542af2014-09-03 16:16:56 -07001509 if (m == nullptr) {
Sebastien Hertza9aa0ff2014-09-19 12:07:51 +02001510 memset(location, 0, sizeof(*location));
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08001511 } else {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001512 mirror::Class* c = m->GetDeclaringClass();
Ian Rogersc0542af2014-09-03 16:16:56 -07001513 location->type_tag = GetTypeTag(c);
1514 location->class_id = gRegistry->AddRefType(c);
1515 location->method_id = ToMethodId(m);
1516 location->dex_pc = (m->IsNative() || m->IsProxyMethod()) ? static_cast<uint64_t>(-1) : dex_pc;
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08001517 }
Elliott Hughesd07986f2011-12-06 18:27:45 -08001518}
1519
Ian Rogersc0542af2014-09-03 16:16:56 -07001520std::string Dbg::GetMethodName(JDWP::MethodId method_id) {
Brian Carlstromea46f952013-07-30 01:26:50 -07001521 mirror::ArtMethod* m = FromMethodId(method_id);
Sebastien Hertza9aa0ff2014-09-19 12:07:51 +02001522 if (m == nullptr) {
1523 return "NULL";
1524 }
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07001525 return m->GetName();
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001526}
1527
Ian Rogersc0542af2014-09-03 16:16:56 -07001528std::string Dbg::GetFieldName(JDWP::FieldId field_id) {
Sebastien Hertza9aa0ff2014-09-19 12:07:51 +02001529 mirror::ArtField* f = FromFieldId(field_id);
1530 if (f == nullptr) {
1531 return "NULL";
1532 }
1533 return f->GetName();
Elliott Hughesa96836a2013-01-17 12:27:49 -08001534}
1535
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001536/*
1537 * Augment the access flags for synthetic methods and fields by setting
1538 * the (as described by the spec) "0xf0000000 bit". Also, strip out any
1539 * flags not specified by the Java programming language.
1540 */
1541static uint32_t MangleAccessFlags(uint32_t accessFlags) {
1542 accessFlags &= kAccJavaFlagsMask;
1543 if ((accessFlags & kAccSynthetic) != 0) {
1544 accessFlags |= 0xf0000000;
1545 }
1546 return accessFlags;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001547}
1548
Elliott Hughesdbb40792011-11-18 17:05:22 -08001549/*
Jeff Haob7cefc72013-11-14 14:51:09 -08001550 * Circularly shifts registers so that arguments come first. Debuggers
1551 * expect slots to begin with arguments, but dex code places them at
1552 * the end.
Elliott Hughesdbb40792011-11-18 17:05:22 -08001553 */
Jeff Haob7cefc72013-11-14 14:51:09 -08001554static uint16_t MangleSlot(uint16_t slot, mirror::ArtMethod* m)
1555 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07001556 const DexFile::CodeItem* code_item = m->GetCodeItem();
Sebastien Hertzcb19ebf2014-03-11 15:26:35 +01001557 if (code_item == nullptr) {
1558 // We should not get here for a method without code (native, proxy or abstract). Log it and
1559 // return the slot as is since all registers are arguments.
1560 LOG(WARNING) << "Trying to mangle slot for method without code " << PrettyMethod(m);
1561 return slot;
1562 }
Jeff Haob7cefc72013-11-14 14:51:09 -08001563 uint16_t ins_size = code_item->ins_size_;
1564 uint16_t locals_size = code_item->registers_size_ - ins_size;
1565 if (slot >= locals_size) {
1566 return slot - locals_size;
1567 } else {
1568 return slot + ins_size;
Elliott Hughesdbb40792011-11-18 17:05:22 -08001569 }
Elliott Hughesdbb40792011-11-18 17:05:22 -08001570}
1571
Jeff Haob7cefc72013-11-14 14:51:09 -08001572/*
1573 * Circularly shifts registers so that arguments come last. Reverts
1574 * slots to dex style argument placement.
1575 */
Brian Carlstromea46f952013-07-30 01:26:50 -07001576static uint16_t DemangleSlot(uint16_t slot, mirror::ArtMethod* m)
Ian Rogersb726dcb2012-09-05 08:57:23 -07001577 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07001578 const DexFile::CodeItem* code_item = m->GetCodeItem();
Sebastien Hertzcb19ebf2014-03-11 15:26:35 +01001579 if (code_item == nullptr) {
1580 // We should not get here for a method without code (native, proxy or abstract). Log it and
1581 // return the slot as is since all registers are arguments.
1582 LOG(WARNING) << "Trying to demangle slot for method without code " << PrettyMethod(m);
1583 return slot;
1584 }
Jeff Haob7cefc72013-11-14 14:51:09 -08001585 uint16_t ins_size = code_item->ins_size_;
1586 uint16_t locals_size = code_item->registers_size_ - ins_size;
1587 if (slot < ins_size) {
1588 return slot + locals_size;
1589 } else {
1590 return slot - ins_size;
Elliott Hughesdbb40792011-11-18 17:05:22 -08001591 }
Elliott Hughesdbb40792011-11-18 17:05:22 -08001592}
1593
Elliott Hughes88d63092013-01-09 09:55:54 -08001594JDWP::JdwpError Dbg::OutputDeclaredFields(JDWP::RefTypeId class_id, bool with_generic, JDWP::ExpandBuf* pReply) {
Ian Rogersc0542af2014-09-03 16:16:56 -07001595 JDWP::JdwpError error;
1596 mirror::Class* c = DecodeClass(class_id, &error);
1597 if (c == nullptr) {
1598 return error;
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -08001599 }
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001600
1601 size_t instance_field_count = c->NumInstanceFields();
1602 size_t static_field_count = c->NumStaticFields();
1603
1604 expandBufAdd4BE(pReply, instance_field_count + static_field_count);
1605
1606 for (size_t i = 0; i < instance_field_count + static_field_count; ++i) {
Brian Carlstromea46f952013-07-30 01:26:50 -07001607 mirror::ArtField* f = (i < instance_field_count) ? c->GetInstanceField(i) : c->GetStaticField(i - instance_field_count);
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001608 expandBufAddFieldId(pReply, ToFieldId(f));
Mathieu Chartier61c5ebc2014-06-05 17:42:53 -07001609 expandBufAddUtf8String(pReply, f->GetName());
1610 expandBufAddUtf8String(pReply, f->GetTypeDescriptor());
Elliott Hughesc5b734a2011-12-01 17:20:58 -08001611 if (with_generic) {
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001612 static const char genericSignature[1] = "";
1613 expandBufAddUtf8String(pReply, genericSignature);
1614 }
1615 expandBufAdd4BE(pReply, MangleAccessFlags(f->GetAccessFlags()));
1616 }
Elliott Hughes436e3722012-02-17 20:01:47 -08001617 return JDWP::ERR_NONE;
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001618}
1619
Elliott Hughes88d63092013-01-09 09:55:54 -08001620JDWP::JdwpError Dbg::OutputDeclaredMethods(JDWP::RefTypeId class_id, bool with_generic,
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001621 JDWP::ExpandBuf* pReply) {
Ian Rogersc0542af2014-09-03 16:16:56 -07001622 JDWP::JdwpError error;
1623 mirror::Class* c = DecodeClass(class_id, &error);
1624 if (c == nullptr) {
1625 return error;
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -08001626 }
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001627
1628 size_t direct_method_count = c->NumDirectMethods();
1629 size_t virtual_method_count = c->NumVirtualMethods();
1630
1631 expandBufAdd4BE(pReply, direct_method_count + virtual_method_count);
1632
1633 for (size_t i = 0; i < direct_method_count + virtual_method_count; ++i) {
Brian Carlstromea46f952013-07-30 01:26:50 -07001634 mirror::ArtMethod* m = (i < direct_method_count) ? c->GetDirectMethod(i) : c->GetVirtualMethod(i - direct_method_count);
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001635 expandBufAddMethodId(pReply, ToMethodId(m));
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07001636 expandBufAddUtf8String(pReply, m->GetName());
1637 expandBufAddUtf8String(pReply, m->GetSignature().ToString());
Elliott Hughesc5b734a2011-12-01 17:20:58 -08001638 if (with_generic) {
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001639 static const char genericSignature[1] = "";
1640 expandBufAddUtf8String(pReply, genericSignature);
1641 }
1642 expandBufAdd4BE(pReply, MangleAccessFlags(m->GetAccessFlags()));
1643 }
Elliott Hughes436e3722012-02-17 20:01:47 -08001644 return JDWP::ERR_NONE;
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001645}
1646
Elliott Hughes88d63092013-01-09 09:55:54 -08001647JDWP::JdwpError Dbg::OutputDeclaredInterfaces(JDWP::RefTypeId class_id, JDWP::ExpandBuf* pReply) {
Ian Rogersc0542af2014-09-03 16:16:56 -07001648 JDWP::JdwpError error;
Mathieu Chartierf8322842014-05-16 10:59:25 -07001649 Thread* self = Thread::Current();
1650 StackHandleScope<1> hs(self);
Ian Rogersc0542af2014-09-03 16:16:56 -07001651 Handle<mirror::Class> c(hs.NewHandle(DecodeClass(class_id, &error)));
Mathieu Chartierf8322842014-05-16 10:59:25 -07001652 if (c.Get() == nullptr) {
Ian Rogersc0542af2014-09-03 16:16:56 -07001653 return error;
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -08001654 }
Mathieu Chartierf8322842014-05-16 10:59:25 -07001655 size_t interface_count = c->NumDirectInterfaces();
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001656 expandBufAdd4BE(pReply, interface_count);
1657 for (size_t i = 0; i < interface_count; ++i) {
Mathieu Chartierf8322842014-05-16 10:59:25 -07001658 expandBufAddRefTypeId(pReply,
1659 gRegistry->AddRefType(mirror::Class::GetDirectInterface(self, c, i)));
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001660 }
Elliott Hughes436e3722012-02-17 20:01:47 -08001661 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001662}
1663
Ian Rogersc0542af2014-09-03 16:16:56 -07001664void Dbg::OutputLineTable(JDWP::RefTypeId, JDWP::MethodId method_id, JDWP::ExpandBuf* pReply) {
Elliott Hughes03181a82011-11-17 17:22:21 -08001665 struct DebugCallbackContext {
1666 int numItems;
1667 JDWP::ExpandBuf* pReply;
1668
Elliott Hughes2435a572012-02-17 16:07:41 -08001669 static bool Callback(void* context, uint32_t address, uint32_t line_number) {
Elliott Hughes03181a82011-11-17 17:22:21 -08001670 DebugCallbackContext* pContext = reinterpret_cast<DebugCallbackContext*>(context);
1671 expandBufAdd8BE(pContext->pReply, address);
Elliott Hughes2435a572012-02-17 16:07:41 -08001672 expandBufAdd4BE(pContext->pReply, line_number);
Elliott Hughes03181a82011-11-17 17:22:21 -08001673 pContext->numItems++;
Sebastien Hertzf2910ee2013-10-19 16:39:24 +02001674 return false;
Elliott Hughes03181a82011-11-17 17:22:21 -08001675 }
1676 };
Brian Carlstromea46f952013-07-30 01:26:50 -07001677 mirror::ArtMethod* m = FromMethodId(method_id);
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07001678 const DexFile::CodeItem* code_item = m->GetCodeItem();
Elliott Hughes03181a82011-11-17 17:22:21 -08001679 uint64_t start, end;
Sebastien Hertzcb19ebf2014-03-11 15:26:35 +01001680 if (code_item == nullptr) {
1681 DCHECK(m->IsNative() || m->IsProxyMethod());
Elliott Hughes03181a82011-11-17 17:22:21 -08001682 start = -1;
1683 end = -1;
1684 } else {
1685 start = 0;
jeffhao14f0db92012-12-14 17:50:42 -08001686 // Return the index of the last instruction
Sebastien Hertzcb19ebf2014-03-11 15:26:35 +01001687 end = code_item->insns_size_in_code_units_ - 1;
Elliott Hughes03181a82011-11-17 17:22:21 -08001688 }
1689
1690 expandBufAdd8BE(pReply, start);
1691 expandBufAdd8BE(pReply, end);
1692
1693 // Add numLines later
1694 size_t numLinesOffset = expandBufGetLength(pReply);
1695 expandBufAdd4BE(pReply, 0);
1696
1697 DebugCallbackContext context;
1698 context.numItems = 0;
1699 context.pReply = pReply;
1700
Sebastien Hertzcb19ebf2014-03-11 15:26:35 +01001701 if (code_item != nullptr) {
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07001702 m->GetDexFile()->DecodeDebugInfo(code_item, m->IsStatic(), m->GetDexMethodIndex(),
Ian Rogersc0542af2014-09-03 16:16:56 -07001703 DebugCallbackContext::Callback, nullptr, &context);
Sebastien Hertzcb19ebf2014-03-11 15:26:35 +01001704 }
Elliott Hughes03181a82011-11-17 17:22:21 -08001705
1706 JDWP::Set4BE(expandBufGetBuffer(pReply) + numLinesOffset, context.numItems);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001707}
1708
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07001709void Dbg::OutputVariableTable(JDWP::RefTypeId, JDWP::MethodId method_id, bool with_generic,
1710 JDWP::ExpandBuf* pReply) {
Elliott Hughesdbb40792011-11-18 17:05:22 -08001711 struct DebugCallbackContext {
Jeff Haob7cefc72013-11-14 14:51:09 -08001712 mirror::ArtMethod* method;
Elliott Hughesdbb40792011-11-18 17:05:22 -08001713 JDWP::ExpandBuf* pReply;
Elliott Hughesc5b734a2011-12-01 17:20:58 -08001714 size_t variable_count;
1715 bool with_generic;
Elliott Hughesdbb40792011-11-18 17:05:22 -08001716
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07001717 static void Callback(void* context, uint16_t slot, uint32_t startAddress, uint32_t endAddress,
1718 const char* name, const char* descriptor, const char* signature)
Jeff Haob7cefc72013-11-14 14:51:09 -08001719 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Elliott Hughesdbb40792011-11-18 17:05:22 -08001720 DebugCallbackContext* pContext = reinterpret_cast<DebugCallbackContext*>(context);
1721
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07001722 VLOG(jdwp) << StringPrintf(" %2zd: %d(%d) '%s' '%s' '%s' actual slot=%d mangled slot=%d",
1723 pContext->variable_count, startAddress, endAddress - startAddress,
1724 name, descriptor, signature, slot,
1725 MangleSlot(slot, pContext->method));
Elliott Hughesdbb40792011-11-18 17:05:22 -08001726
Jeff Haob7cefc72013-11-14 14:51:09 -08001727 slot = MangleSlot(slot, pContext->method);
Elliott Hughes68fdbd02011-11-29 19:22:47 -08001728
Elliott Hughesdbb40792011-11-18 17:05:22 -08001729 expandBufAdd8BE(pContext->pReply, startAddress);
1730 expandBufAddUtf8String(pContext->pReply, name);
1731 expandBufAddUtf8String(pContext->pReply, descriptor);
Elliott Hughesc5b734a2011-12-01 17:20:58 -08001732 if (pContext->with_generic) {
Elliott Hughesdbb40792011-11-18 17:05:22 -08001733 expandBufAddUtf8String(pContext->pReply, signature);
1734 }
1735 expandBufAdd4BE(pContext->pReply, endAddress - startAddress);
1736 expandBufAdd4BE(pContext->pReply, slot);
1737
Elliott Hughesc5b734a2011-12-01 17:20:58 -08001738 ++pContext->variable_count;
Elliott Hughesdbb40792011-11-18 17:05:22 -08001739 }
1740 };
Brian Carlstromea46f952013-07-30 01:26:50 -07001741 mirror::ArtMethod* m = FromMethodId(method_id);
Elliott Hughesdbb40792011-11-18 17:05:22 -08001742
Elliott Hughesc5b734a2011-12-01 17:20:58 -08001743 // arg_count considers doubles and longs to take 2 units.
1744 // variable_count considers everything to take 1 unit.
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07001745 std::string shorty(m->GetShorty());
Brian Carlstromea46f952013-07-30 01:26:50 -07001746 expandBufAdd4BE(pReply, mirror::ArtMethod::NumArgRegisters(shorty));
Elliott Hughesdbb40792011-11-18 17:05:22 -08001747
Elliott Hughesc5b734a2011-12-01 17:20:58 -08001748 // We don't know the total number of variables yet, so leave a blank and update it later.
1749 size_t variable_count_offset = expandBufGetLength(pReply);
Elliott Hughesdbb40792011-11-18 17:05:22 -08001750 expandBufAdd4BE(pReply, 0);
1751
1752 DebugCallbackContext context;
Jeff Haob7cefc72013-11-14 14:51:09 -08001753 context.method = m;
Elliott Hughesdbb40792011-11-18 17:05:22 -08001754 context.pReply = pReply;
Elliott Hughesc5b734a2011-12-01 17:20:58 -08001755 context.variable_count = 0;
1756 context.with_generic = with_generic;
Elliott Hughesdbb40792011-11-18 17:05:22 -08001757
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07001758 const DexFile::CodeItem* code_item = m->GetCodeItem();
Sebastien Hertzcb19ebf2014-03-11 15:26:35 +01001759 if (code_item != nullptr) {
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07001760 m->GetDexFile()->DecodeDebugInfo(
Ian Rogersc0542af2014-09-03 16:16:56 -07001761 code_item, m->IsStatic(), m->GetDexMethodIndex(), nullptr, DebugCallbackContext::Callback,
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07001762 &context);
Sebastien Hertzcb19ebf2014-03-11 15:26:35 +01001763 }
Elliott Hughesdbb40792011-11-18 17:05:22 -08001764
Elliott Hughesc5b734a2011-12-01 17:20:58 -08001765 JDWP::Set4BE(expandBufGetBuffer(pReply) + variable_count_offset, context.variable_count);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001766}
1767
Jeff Hao579b0242013-11-18 13:16:49 -08001768void Dbg::OutputMethodReturnValue(JDWP::MethodId method_id, const JValue* return_value,
1769 JDWP::ExpandBuf* pReply) {
1770 mirror::ArtMethod* m = FromMethodId(method_id);
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07001771 JDWP::JdwpTag tag = BasicTagFromDescriptor(m->GetShorty());
Jeff Hao579b0242013-11-18 13:16:49 -08001772 OutputJValue(tag, return_value, pReply);
1773}
1774
Sebastien Hertz3f52eaf2014-04-04 17:50:18 +02001775void Dbg::OutputFieldValue(JDWP::FieldId field_id, const JValue* field_value,
1776 JDWP::ExpandBuf* pReply) {
1777 mirror::ArtField* f = FromFieldId(field_id);
Mathieu Chartier61c5ebc2014-06-05 17:42:53 -07001778 JDWP::JdwpTag tag = BasicTagFromDescriptor(f->GetTypeDescriptor());
Sebastien Hertz3f52eaf2014-04-04 17:50:18 +02001779 OutputJValue(tag, field_value, pReply);
1780}
1781
Elliott Hughes9777ba22013-01-17 09:04:19 -08001782JDWP::JdwpError Dbg::GetBytecodes(JDWP::RefTypeId, JDWP::MethodId method_id,
Ian Rogersc0542af2014-09-03 16:16:56 -07001783 std::vector<uint8_t>* bytecodes) {
Brian Carlstromea46f952013-07-30 01:26:50 -07001784 mirror::ArtMethod* m = FromMethodId(method_id);
Ian Rogersc0542af2014-09-03 16:16:56 -07001785 if (m == nullptr) {
Elliott Hughes9777ba22013-01-17 09:04:19 -08001786 return JDWP::ERR_INVALID_METHODID;
1787 }
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07001788 const DexFile::CodeItem* code_item = m->GetCodeItem();
Elliott Hughes9777ba22013-01-17 09:04:19 -08001789 size_t byte_count = code_item->insns_size_in_code_units_ * 2;
1790 const uint8_t* begin = reinterpret_cast<const uint8_t*>(code_item->insns_);
1791 const uint8_t* end = begin + byte_count;
1792 for (const uint8_t* p = begin; p != end; ++p) {
Ian Rogersc0542af2014-09-03 16:16:56 -07001793 bytecodes->push_back(*p);
Elliott Hughes9777ba22013-01-17 09:04:19 -08001794 }
1795 return JDWP::ERR_NONE;
1796}
1797
Elliott Hughes88d63092013-01-09 09:55:54 -08001798JDWP::JdwpTag Dbg::GetFieldBasicTag(JDWP::FieldId field_id) {
Mathieu Chartier61c5ebc2014-06-05 17:42:53 -07001799 return BasicTagFromDescriptor(FromFieldId(field_id)->GetTypeDescriptor());
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001800}
1801
Elliott Hughes88d63092013-01-09 09:55:54 -08001802JDWP::JdwpTag Dbg::GetStaticFieldBasicTag(JDWP::FieldId field_id) {
Mathieu Chartier61c5ebc2014-06-05 17:42:53 -07001803 return BasicTagFromDescriptor(FromFieldId(field_id)->GetTypeDescriptor());
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001804}
1805
Elliott Hughes88d63092013-01-09 09:55:54 -08001806static JDWP::JdwpError GetFieldValueImpl(JDWP::RefTypeId ref_type_id, JDWP::ObjectId object_id,
1807 JDWP::FieldId field_id, JDWP::ExpandBuf* pReply,
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001808 bool is_static)
Ian Rogersb726dcb2012-09-05 08:57:23 -07001809 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Ian Rogersc0542af2014-09-03 16:16:56 -07001810 JDWP::JdwpError error;
1811 mirror::Class* c = DecodeClass(ref_type_id, &error);
1812 if (ref_type_id != 0 && c == nullptr) {
1813 return error;
Elliott Hughes0cf74332012-02-23 23:14:00 -08001814 }
1815
Sebastien Hertz6995c602014-09-09 12:10:13 +02001816 mirror::Object* o = Dbg::GetObjectRegistry()->Get<mirror::Object*>(object_id, &error);
Ian Rogersc0542af2014-09-03 16:16:56 -07001817 if ((!is_static && o == nullptr) || error != JDWP::ERR_NONE) {
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08001818 return JDWP::ERR_INVALID_OBJECT;
1819 }
Brian Carlstromea46f952013-07-30 01:26:50 -07001820 mirror::ArtField* f = FromFieldId(field_id);
Elliott Hughes0cf74332012-02-23 23:14:00 -08001821
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001822 mirror::Class* receiver_class = c;
Ian Rogersc0542af2014-09-03 16:16:56 -07001823 if (receiver_class == nullptr && o != nullptr) {
Elliott Hughes0cf74332012-02-23 23:14:00 -08001824 receiver_class = o->GetClass();
1825 }
Ian Rogersc0542af2014-09-03 16:16:56 -07001826 // TODO: should we give up now if receiver_class is nullptr?
1827 if (receiver_class != nullptr && !f->GetDeclaringClass()->IsAssignableFrom(receiver_class)) {
Elliott Hughes0cf74332012-02-23 23:14:00 -08001828 LOG(INFO) << "ERR_INVALID_FIELDID: " << PrettyField(f) << " " << PrettyClass(receiver_class);
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08001829 return JDWP::ERR_INVALID_FIELDID;
1830 }
Elliott Hughesaed4be92011-12-02 16:16:23 -08001831
Elliott Hughes0cf74332012-02-23 23:14:00 -08001832 // The RI only enforces the static/non-static mismatch in one direction.
1833 // TODO: should we change the tests and check both?
1834 if (is_static) {
1835 if (!f->IsStatic()) {
1836 return JDWP::ERR_INVALID_FIELDID;
1837 }
1838 } else {
1839 if (f->IsStatic()) {
Ian Rogersc0542af2014-09-03 16:16:56 -07001840 LOG(WARNING) << "Ignoring non-nullptr receiver for ObjectReference.SetValues on static field "
1841 << PrettyField(f);
Elliott Hughes0cf74332012-02-23 23:14:00 -08001842 }
1843 }
jeffhao0dfbb7e2012-11-28 15:26:03 -08001844 if (f->IsStatic()) {
1845 o = f->GetDeclaringClass();
1846 }
Elliott Hughes0cf74332012-02-23 23:14:00 -08001847
Mathieu Chartier61c5ebc2014-06-05 17:42:53 -07001848 JDWP::JdwpTag tag = BasicTagFromDescriptor(f->GetTypeDescriptor());
Jeff Hao579b0242013-11-18 13:16:49 -08001849 JValue field_value;
1850 if (tag == JDWP::JT_VOID) {
1851 LOG(FATAL) << "Unknown tag: " << tag;
1852 } else if (!IsPrimitiveTag(tag)) {
1853 field_value.SetL(f->GetObject(o));
1854 } else if (tag == JDWP::JT_DOUBLE || tag == JDWP::JT_LONG) {
1855 field_value.SetJ(f->Get64(o));
Elliott Hughesaed4be92011-12-02 16:16:23 -08001856 } else {
Jeff Hao579b0242013-11-18 13:16:49 -08001857 field_value.SetI(f->Get32(o));
Elliott Hughesaed4be92011-12-02 16:16:23 -08001858 }
Jeff Hao579b0242013-11-18 13:16:49 -08001859 Dbg::OutputJValue(tag, &field_value, pReply);
1860
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08001861 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001862}
1863
Elliott Hughes88d63092013-01-09 09:55:54 -08001864JDWP::JdwpError Dbg::GetFieldValue(JDWP::ObjectId object_id, JDWP::FieldId field_id,
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001865 JDWP::ExpandBuf* pReply) {
Elliott Hughes88d63092013-01-09 09:55:54 -08001866 return GetFieldValueImpl(0, object_id, field_id, pReply, false);
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08001867}
1868
Ian Rogersc0542af2014-09-03 16:16:56 -07001869JDWP::JdwpError Dbg::GetStaticFieldValue(JDWP::RefTypeId ref_type_id, JDWP::FieldId field_id,
1870 JDWP::ExpandBuf* pReply) {
Elliott Hughes88d63092013-01-09 09:55:54 -08001871 return GetFieldValueImpl(ref_type_id, 0, field_id, pReply, true);
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08001872}
1873
Elliott Hughes88d63092013-01-09 09:55:54 -08001874static JDWP::JdwpError SetFieldValueImpl(JDWP::ObjectId object_id, JDWP::FieldId field_id,
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001875 uint64_t value, int width, bool is_static)
Ian Rogersb726dcb2012-09-05 08:57:23 -07001876 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Ian Rogersc0542af2014-09-03 16:16:56 -07001877 JDWP::JdwpError error;
Sebastien Hertz6995c602014-09-09 12:10:13 +02001878 mirror::Object* o = Dbg::GetObjectRegistry()->Get<mirror::Object*>(object_id, &error);
Ian Rogersc0542af2014-09-03 16:16:56 -07001879 if ((!is_static && o == nullptr) || error != JDWP::ERR_NONE) {
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08001880 return JDWP::ERR_INVALID_OBJECT;
1881 }
Brian Carlstromea46f952013-07-30 01:26:50 -07001882 mirror::ArtField* f = FromFieldId(field_id);
Elliott Hughes0cf74332012-02-23 23:14:00 -08001883
1884 // The RI only enforces the static/non-static mismatch in one direction.
1885 // TODO: should we change the tests and check both?
1886 if (is_static) {
1887 if (!f->IsStatic()) {
1888 return JDWP::ERR_INVALID_FIELDID;
1889 }
1890 } else {
1891 if (f->IsStatic()) {
Ian Rogersc0542af2014-09-03 16:16:56 -07001892 LOG(WARNING) << "Ignoring non-nullptr receiver for ObjectReference.SetValues on static field " << PrettyField(f);
Elliott Hughes0cf74332012-02-23 23:14:00 -08001893 }
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08001894 }
jeffhao0dfbb7e2012-11-28 15:26:03 -08001895 if (f->IsStatic()) {
1896 o = f->GetDeclaringClass();
1897 }
Elliott Hughesaed4be92011-12-02 16:16:23 -08001898
Mathieu Chartier61c5ebc2014-06-05 17:42:53 -07001899 JDWP::JdwpTag tag = BasicTagFromDescriptor(f->GetTypeDescriptor());
Elliott Hughesaed4be92011-12-02 16:16:23 -08001900
1901 if (IsPrimitiveTag(tag)) {
1902 if (tag == JDWP::JT_DOUBLE || tag == JDWP::JT_LONG) {
Elliott Hughes1bac54f2012-03-16 12:48:31 -07001903 CHECK_EQ(width, 8);
Sebastien Hertzd2fe10a2014-01-15 10:20:56 +01001904 // Debugging can't use transactional mode (runtime only).
1905 f->Set64<false>(o, value);
Elliott Hughesaed4be92011-12-02 16:16:23 -08001906 } else {
Elliott Hughes1bac54f2012-03-16 12:48:31 -07001907 CHECK_LE(width, 4);
Sebastien Hertzd2fe10a2014-01-15 10:20:56 +01001908 // Debugging can't use transactional mode (runtime only).
1909 f->Set32<false>(o, value);
Elliott Hughesaed4be92011-12-02 16:16:23 -08001910 }
1911 } else {
Sebastien Hertz6995c602014-09-09 12:10:13 +02001912 mirror::Object* v = Dbg::GetObjectRegistry()->Get<mirror::Object*>(value, &error);
Ian Rogersc0542af2014-09-03 16:16:56 -07001913 if (error != JDWP::ERR_NONE) {
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -08001914 return JDWP::ERR_INVALID_OBJECT;
1915 }
Ian Rogersc0542af2014-09-03 16:16:56 -07001916 if (v != nullptr) {
Mathieu Chartier61c5ebc2014-06-05 17:42:53 -07001917 mirror::Class* field_type;
1918 {
1919 StackHandleScope<3> hs(Thread::Current());
1920 HandleWrapper<mirror::Object> h_v(hs.NewHandleWrapper(&v));
1921 HandleWrapper<mirror::ArtField> h_f(hs.NewHandleWrapper(&f));
1922 HandleWrapper<mirror::Object> h_o(hs.NewHandleWrapper(&o));
Ian Rogers08f1f502014-12-02 15:04:37 -08001923 field_type = h_f->GetType(true);
Mathieu Chartier61c5ebc2014-06-05 17:42:53 -07001924 }
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08001925 if (!field_type->IsAssignableFrom(v->GetClass())) {
1926 return JDWP::ERR_INVALID_OBJECT;
1927 }
1928 }
Sebastien Hertzd2fe10a2014-01-15 10:20:56 +01001929 // Debugging can't use transactional mode (runtime only).
1930 f->SetObject<false>(o, v);
Elliott Hughesaed4be92011-12-02 16:16:23 -08001931 }
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -08001932
1933 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001934}
1935
Elliott Hughes88d63092013-01-09 09:55:54 -08001936JDWP::JdwpError Dbg::SetFieldValue(JDWP::ObjectId object_id, JDWP::FieldId field_id, uint64_t value,
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001937 int width) {
Elliott Hughes88d63092013-01-09 09:55:54 -08001938 return SetFieldValueImpl(object_id, field_id, value, width, false);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001939}
1940
Elliott Hughes88d63092013-01-09 09:55:54 -08001941JDWP::JdwpError Dbg::SetStaticFieldValue(JDWP::FieldId field_id, uint64_t value, int width) {
1942 return SetFieldValueImpl(0, field_id, value, width, true);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001943}
1944
Sebastien Hertzb0b0b492014-09-15 11:27:27 +02001945JDWP::JdwpError Dbg::StringToUtf8(JDWP::ObjectId string_id, std::string* str) {
Ian Rogersc0542af2014-09-03 16:16:56 -07001946 JDWP::JdwpError error;
Sebastien Hertzb0b0b492014-09-15 11:27:27 +02001947 mirror::Object* obj = gRegistry->Get<mirror::Object*>(string_id, &error);
1948 if (error != JDWP::ERR_NONE) {
1949 return error;
1950 }
1951 if (obj == nullptr) {
1952 return JDWP::ERR_INVALID_OBJECT;
1953 }
1954 {
1955 ScopedObjectAccessUnchecked soa(Thread::Current());
1956 mirror::Class* java_lang_String = soa.Decode<mirror::Class*>(WellKnownClasses::java_lang_String);
1957 if (!java_lang_String->IsAssignableFrom(obj->GetClass())) {
1958 // This isn't a string.
1959 return JDWP::ERR_INVALID_STRING;
1960 }
1961 }
1962 *str = obj->AsString()->ToModifiedUtf8();
1963 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001964}
1965
Jeff Hao579b0242013-11-18 13:16:49 -08001966void Dbg::OutputJValue(JDWP::JdwpTag tag, const JValue* return_value, JDWP::ExpandBuf* pReply) {
1967 if (IsPrimitiveTag(tag)) {
1968 expandBufAdd1(pReply, tag);
1969 if (tag == JDWP::JT_BOOLEAN || tag == JDWP::JT_BYTE) {
1970 expandBufAdd1(pReply, return_value->GetI());
1971 } else if (tag == JDWP::JT_CHAR || tag == JDWP::JT_SHORT) {
1972 expandBufAdd2BE(pReply, return_value->GetI());
1973 } else if (tag == JDWP::JT_FLOAT || tag == JDWP::JT_INT) {
1974 expandBufAdd4BE(pReply, return_value->GetI());
1975 } else if (tag == JDWP::JT_DOUBLE || tag == JDWP::JT_LONG) {
1976 expandBufAdd8BE(pReply, return_value->GetJ());
1977 } else {
1978 CHECK_EQ(tag, JDWP::JT_VOID);
1979 }
1980 } else {
Ian Rogers98379392014-02-24 16:53:16 -08001981 ScopedObjectAccessUnchecked soa(Thread::Current());
Jeff Hao579b0242013-11-18 13:16:49 -08001982 mirror::Object* value = return_value->GetL();
Ian Rogers98379392014-02-24 16:53:16 -08001983 expandBufAdd1(pReply, TagFromObject(soa, value));
Jeff Hao579b0242013-11-18 13:16:49 -08001984 expandBufAddObjectId(pReply, gRegistry->Add(value));
1985 }
1986}
1987
Ian Rogersc0542af2014-09-03 16:16:56 -07001988JDWP::JdwpError Dbg::GetThreadName(JDWP::ObjectId thread_id, std::string* name) {
jeffhaoa77f0f62012-12-05 17:19:31 -08001989 ScopedObjectAccessUnchecked soa(Thread::Current());
1990 MutexLock mu(soa.Self(), *Locks::thread_list_lock_);
Ian Rogersc0542af2014-09-03 16:16:56 -07001991 JDWP::JdwpError error;
1992 Thread* thread = DecodeThread(soa, thread_id, &error);
1993 UNUSED(thread);
Elliott Hughes221229c2013-01-08 18:17:50 -08001994 if (error != JDWP::ERR_NONE && error != JDWP::ERR_THREAD_NOT_ALIVE) {
1995 return error;
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001996 }
Elliott Hughes221229c2013-01-08 18:17:50 -08001997
1998 // We still need to report the zombie threads' names, so we can't just call Thread::GetThreadName.
Ian Rogersc0542af2014-09-03 16:16:56 -07001999 mirror::Object* thread_object = gRegistry->Get<mirror::Object*>(thread_id, &error);
2000 CHECK(thread_object != nullptr) << error;
Brian Carlstromea46f952013-07-30 01:26:50 -07002001 mirror::ArtField* java_lang_Thread_name_field =
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002002 soa.DecodeField(WellKnownClasses::java_lang_Thread_name);
2003 mirror::String* s =
2004 reinterpret_cast<mirror::String*>(java_lang_Thread_name_field->GetObject(thread_object));
Ian Rogersc0542af2014-09-03 16:16:56 -07002005 if (s != nullptr) {
2006 *name = s->ToModifiedUtf8();
Elliott Hughes221229c2013-01-08 18:17:50 -08002007 }
2008 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002009}
2010
Elliott Hughes221229c2013-01-08 18:17:50 -08002011JDWP::JdwpError Dbg::GetThreadGroup(JDWP::ObjectId thread_id, JDWP::ExpandBuf* pReply) {
Sebastien Hertza06430c2014-09-15 19:21:30 +02002012 ScopedObjectAccessUnchecked soa(Thread::Current());
Ian Rogersc0542af2014-09-03 16:16:56 -07002013 JDWP::JdwpError error;
2014 mirror::Object* thread_object = gRegistry->Get<mirror::Object*>(thread_id, &error);
2015 if (error != JDWP::ERR_NONE) {
Elliott Hughes2435a572012-02-17 16:07:41 -08002016 return JDWP::ERR_INVALID_OBJECT;
2017 }
Mathieu Chartier2d5f39e2014-09-19 17:52:37 -07002018 ScopedAssertNoThreadSuspension ants(soa.Self(), "Debugger: GetThreadGroup");
Elliott Hughes2435a572012-02-17 16:07:41 -08002019 // Okay, so it's an object, but is it actually a thread?
Hiroshi Yamauchib5a9e3d2014-06-09 12:11:20 -07002020 {
2021 MutexLock mu(soa.Self(), *Locks::thread_list_lock_);
Ian Rogersc0542af2014-09-03 16:16:56 -07002022 Thread* thread = DecodeThread(soa, thread_id, &error);
2023 UNUSED(thread);
Hiroshi Yamauchib5a9e3d2014-06-09 12:11:20 -07002024 }
Elliott Hughes221229c2013-01-08 18:17:50 -08002025 if (error == JDWP::ERR_THREAD_NOT_ALIVE) {
2026 // Zombie threads are in the null group.
2027 expandBufAddObjectId(pReply, JDWP::ObjectId(0));
Sebastien Hertz52d131d2014-03-13 16:17:40 +01002028 error = JDWP::ERR_NONE;
2029 } else if (error == JDWP::ERR_NONE) {
2030 mirror::Class* c = soa.Decode<mirror::Class*>(WellKnownClasses::java_lang_Thread);
2031 CHECK(c != nullptr);
Sebastien Hertze49e1952014-10-13 11:27:13 +02002032 mirror::ArtField* f = soa.DecodeField(WellKnownClasses::java_lang_Thread_group);
Hiroshi Yamauchib5a9e3d2014-06-09 12:11:20 -07002033 CHECK(f != nullptr);
Sebastien Hertz52d131d2014-03-13 16:17:40 +01002034 mirror::Object* group = f->GetObject(thread_object);
Hiroshi Yamauchib5a9e3d2014-06-09 12:11:20 -07002035 CHECK(group != nullptr);
Sebastien Hertz52d131d2014-03-13 16:17:40 +01002036 JDWP::ObjectId thread_group_id = gRegistry->Add(group);
2037 expandBufAddObjectId(pReply, thread_group_id);
Elliott Hughes221229c2013-01-08 18:17:50 -08002038 }
Sebastien Hertz52d131d2014-03-13 16:17:40 +01002039 return error;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002040}
2041
Sebastien Hertza06430c2014-09-15 19:21:30 +02002042static mirror::Object* DecodeThreadGroup(ScopedObjectAccessUnchecked& soa,
2043 JDWP::ObjectId thread_group_id, JDWP::JdwpError* error)
2044 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Sebastien Hertz6995c602014-09-09 12:10:13 +02002045 mirror::Object* thread_group = Dbg::GetObjectRegistry()->Get<mirror::Object*>(thread_group_id,
2046 error);
Sebastien Hertza06430c2014-09-15 19:21:30 +02002047 if (*error != JDWP::ERR_NONE) {
2048 return nullptr;
2049 }
2050 if (thread_group == nullptr) {
2051 *error = JDWP::ERR_INVALID_OBJECT;
2052 return nullptr;
2053 }
Ian Rogers98379392014-02-24 16:53:16 -08002054 mirror::Class* c = soa.Decode<mirror::Class*>(WellKnownClasses::java_lang_ThreadGroup);
2055 CHECK(c != nullptr);
Sebastien Hertza06430c2014-09-15 19:21:30 +02002056 if (!c->IsAssignableFrom(thread_group->GetClass())) {
2057 // This is not a java.lang.ThreadGroup.
2058 *error = JDWP::ERR_INVALID_THREAD_GROUP;
2059 return nullptr;
2060 }
2061 *error = JDWP::ERR_NONE;
2062 return thread_group;
2063}
2064
2065JDWP::JdwpError Dbg::GetThreadGroupName(JDWP::ObjectId thread_group_id, JDWP::ExpandBuf* pReply) {
2066 ScopedObjectAccessUnchecked soa(Thread::Current());
2067 JDWP::JdwpError error;
2068 mirror::Object* thread_group = DecodeThreadGroup(soa, thread_group_id, &error);
2069 if (error != JDWP::ERR_NONE) {
2070 return error;
2071 }
Mathieu Chartier2d5f39e2014-09-19 17:52:37 -07002072 ScopedAssertNoThreadSuspension ants(soa.Self(), "Debugger: GetThreadGroupName");
Sebastien Hertze49e1952014-10-13 11:27:13 +02002073 mirror::ArtField* f = soa.DecodeField(WellKnownClasses::java_lang_ThreadGroup_name);
Ian Rogersc0542af2014-09-03 16:16:56 -07002074 CHECK(f != nullptr);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002075 mirror::String* s = reinterpret_cast<mirror::String*>(f->GetObject(thread_group));
Sebastien Hertza06430c2014-09-15 19:21:30 +02002076
2077 std::string thread_group_name(s->ToModifiedUtf8());
2078 expandBufAddUtf8String(pReply, thread_group_name);
2079 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002080}
2081
Sebastien Hertza06430c2014-09-15 19:21:30 +02002082JDWP::JdwpError Dbg::GetThreadGroupParent(JDWP::ObjectId thread_group_id, JDWP::ExpandBuf* pReply) {
Ian Rogers98379392014-02-24 16:53:16 -08002083 ScopedObjectAccessUnchecked soa(Thread::Current());
Ian Rogersc0542af2014-09-03 16:16:56 -07002084 JDWP::JdwpError error;
Sebastien Hertza06430c2014-09-15 19:21:30 +02002085 mirror::Object* thread_group = DecodeThreadGroup(soa, thread_group_id, &error);
2086 if (error != JDWP::ERR_NONE) {
2087 return error;
2088 }
Mathieu Chartier2d5f39e2014-09-19 17:52:37 -07002089 mirror::Object* parent;
2090 {
2091 ScopedAssertNoThreadSuspension ants(soa.Self(), "Debugger: GetThreadGroupParent");
Sebastien Hertze49e1952014-10-13 11:27:13 +02002092 mirror::ArtField* f = soa.DecodeField(WellKnownClasses::java_lang_ThreadGroup_parent);
Mathieu Chartier2d5f39e2014-09-19 17:52:37 -07002093 CHECK(f != nullptr);
2094 parent = f->GetObject(thread_group);
2095 }
Sebastien Hertza06430c2014-09-15 19:21:30 +02002096 JDWP::ObjectId parent_group_id = gRegistry->Add(parent);
2097 expandBufAddObjectId(pReply, parent_group_id);
2098 return JDWP::ERR_NONE;
2099}
2100
2101static void GetChildThreadGroups(ScopedObjectAccessUnchecked& soa, mirror::Object* thread_group,
2102 std::vector<JDWP::ObjectId>* child_thread_group_ids)
2103 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
2104 CHECK(thread_group != nullptr);
2105
2106 // Get the ArrayList<ThreadGroup> "groups" out of this thread group...
Sebastien Hertze49e1952014-10-13 11:27:13 +02002107 mirror::ArtField* groups_field = soa.DecodeField(WellKnownClasses::java_lang_ThreadGroup_groups);
Sebastien Hertza06430c2014-09-15 19:21:30 +02002108 mirror::Object* groups_array_list = groups_field->GetObject(thread_group);
Sebastien Hertze49e1952014-10-13 11:27:13 +02002109 {
2110 // The "groups" field is declared as a java.util.List: check it really is
2111 // an instance of java.util.ArrayList.
2112 CHECK(groups_array_list != nullptr);
2113 mirror::Class* java_util_ArrayList_class =
2114 soa.Decode<mirror::Class*>(WellKnownClasses::java_util_ArrayList);
2115 CHECK(groups_array_list->InstanceOf(java_util_ArrayList_class));
2116 }
Sebastien Hertza06430c2014-09-15 19:21:30 +02002117
2118 // Get the array and size out of the ArrayList<ThreadGroup>...
Sebastien Hertze49e1952014-10-13 11:27:13 +02002119 mirror::ArtField* array_field = soa.DecodeField(WellKnownClasses::java_util_ArrayList_array);
2120 mirror::ArtField* size_field = soa.DecodeField(WellKnownClasses::java_util_ArrayList_size);
Sebastien Hertza06430c2014-09-15 19:21:30 +02002121 mirror::ObjectArray<mirror::Object>* groups_array =
2122 array_field->GetObject(groups_array_list)->AsObjectArray<mirror::Object>();
2123 const int32_t size = size_field->GetInt(groups_array_list);
2124
2125 // Copy the first 'size' elements out of the array into the result.
Sebastien Hertz6995c602014-09-09 12:10:13 +02002126 ObjectRegistry* registry = Dbg::GetObjectRegistry();
Sebastien Hertza06430c2014-09-15 19:21:30 +02002127 for (int32_t i = 0; i < size; ++i) {
Sebastien Hertz6995c602014-09-09 12:10:13 +02002128 child_thread_group_ids->push_back(registry->Add(groups_array->Get(i)));
Sebastien Hertza06430c2014-09-15 19:21:30 +02002129 }
2130}
2131
2132JDWP::JdwpError Dbg::GetThreadGroupChildren(JDWP::ObjectId thread_group_id,
2133 JDWP::ExpandBuf* pReply) {
2134 ScopedObjectAccessUnchecked soa(Thread::Current());
2135 JDWP::JdwpError error;
2136 mirror::Object* thread_group = DecodeThreadGroup(soa, thread_group_id, &error);
2137 if (error != JDWP::ERR_NONE) {
2138 return error;
2139 }
2140
2141 // Add child threads.
2142 {
2143 std::vector<JDWP::ObjectId> child_thread_ids;
2144 GetThreads(thread_group, &child_thread_ids);
2145 expandBufAdd4BE(pReply, child_thread_ids.size());
2146 for (JDWP::ObjectId child_thread_id : child_thread_ids) {
2147 expandBufAddObjectId(pReply, child_thread_id);
2148 }
2149 }
2150
2151 // Add child thread groups.
2152 {
2153 std::vector<JDWP::ObjectId> child_thread_groups_ids;
2154 GetChildThreadGroups(soa, thread_group, &child_thread_groups_ids);
2155 expandBufAdd4BE(pReply, child_thread_groups_ids.size());
2156 for (JDWP::ObjectId child_thread_group_id : child_thread_groups_ids) {
2157 expandBufAddObjectId(pReply, child_thread_group_id);
2158 }
2159 }
2160
2161 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002162}
2163
2164JDWP::ObjectId Dbg::GetSystemThreadGroupId() {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002165 ScopedObjectAccessUnchecked soa(Thread::Current());
Brian Carlstromea46f952013-07-30 01:26:50 -07002166 mirror::ArtField* f = soa.DecodeField(WellKnownClasses::java_lang_ThreadGroup_systemThreadGroup);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002167 mirror::Object* group = f->GetObject(f->GetDeclaringClass());
Ian Rogers365c1022012-06-22 15:05:28 -07002168 return gRegistry->Add(group);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002169}
2170
Jeff Hao920af3e2013-08-28 15:46:38 -07002171JDWP::JdwpThreadStatus Dbg::ToJdwpThreadStatus(ThreadState state) {
2172 switch (state) {
2173 case kBlocked:
2174 return JDWP::TS_MONITOR;
2175 case kNative:
2176 case kRunnable:
2177 case kSuspended:
2178 return JDWP::TS_RUNNING;
2179 case kSleeping:
2180 return JDWP::TS_SLEEPING;
2181 case kStarting:
2182 case kTerminated:
2183 return JDWP::TS_ZOMBIE;
2184 case kTimedWaiting:
Sebastien Hertzbae182c2013-12-17 10:42:03 +01002185 case kWaitingForCheckPointsToRun:
Jeff Hao920af3e2013-08-28 15:46:38 -07002186 case kWaitingForDebuggerSend:
2187 case kWaitingForDebuggerSuspension:
2188 case kWaitingForDebuggerToAttach:
Sebastien Hertz138dbfc2013-12-04 18:15:25 +01002189 case kWaitingForDeoptimization:
Jeff Hao920af3e2013-08-28 15:46:38 -07002190 case kWaitingForGcToComplete:
Jeff Hao920af3e2013-08-28 15:46:38 -07002191 case kWaitingForJniOnLoad:
Sebastien Hertzbae182c2013-12-17 10:42:03 +01002192 case kWaitingForMethodTracingStart:
Jeff Hao920af3e2013-08-28 15:46:38 -07002193 case kWaitingForSignalCatcherOutput:
Hiroshi Yamauchi0c8c3032015-01-16 16:54:35 -08002194 case kWaitingForVisitObjects:
Jeff Hao920af3e2013-08-28 15:46:38 -07002195 case kWaitingInMainDebuggerLoop:
2196 case kWaitingInMainSignalCatcherLoop:
2197 case kWaitingPerformingGc:
2198 case kWaiting:
2199 return JDWP::TS_WAIT;
2200 // Don't add a 'default' here so the compiler can spot incompatible enum changes.
2201 }
2202 LOG(FATAL) << "Unknown thread state: " << state;
2203 return JDWP::TS_ZOMBIE;
2204}
2205
Sebastien Hertz52d131d2014-03-13 16:17:40 +01002206JDWP::JdwpError Dbg::GetThreadStatus(JDWP::ObjectId thread_id, JDWP::JdwpThreadStatus* pThreadStatus,
2207 JDWP::JdwpSuspendStatus* pSuspendStatus) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002208 ScopedObjectAccess soa(Thread::Current());
Elliott Hughes499c5132011-11-17 14:55:11 -08002209
Elliott Hughes9e0c1752013-01-09 14:02:58 -08002210 *pSuspendStatus = JDWP::SUSPEND_STATUS_NOT_SUSPENDED;
2211
Ian Rogers50b35e22012-10-04 10:09:15 -07002212 MutexLock mu(soa.Self(), *Locks::thread_list_lock_);
Ian Rogersc0542af2014-09-03 16:16:56 -07002213 JDWP::JdwpError error;
2214 Thread* thread = DecodeThread(soa, thread_id, &error);
Elliott Hughes221229c2013-01-08 18:17:50 -08002215 if (error != JDWP::ERR_NONE) {
2216 if (error == JDWP::ERR_THREAD_NOT_ALIVE) {
2217 *pThreadStatus = JDWP::TS_ZOMBIE;
Elliott Hughes221229c2013-01-08 18:17:50 -08002218 return JDWP::ERR_NONE;
2219 }
2220 return error;
Elliott Hughes499c5132011-11-17 14:55:11 -08002221 }
2222
Elliott Hughes9e0c1752013-01-09 14:02:58 -08002223 if (IsSuspendedForDebugger(soa, thread)) {
2224 *pSuspendStatus = JDWP::SUSPEND_STATUS_SUSPENDED;
Elliott Hughes499c5132011-11-17 14:55:11 -08002225 }
2226
Jeff Hao920af3e2013-08-28 15:46:38 -07002227 *pThreadStatus = ToJdwpThreadStatus(thread->GetState());
Elliott Hughes221229c2013-01-08 18:17:50 -08002228 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002229}
2230
Elliott Hughes221229c2013-01-08 18:17:50 -08002231JDWP::JdwpError Dbg::GetThreadDebugSuspendCount(JDWP::ObjectId thread_id, JDWP::ExpandBuf* pReply) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002232 ScopedObjectAccess soa(Thread::Current());
Ian Rogers50b35e22012-10-04 10:09:15 -07002233 MutexLock mu(soa.Self(), *Locks::thread_list_lock_);
Ian Rogersc0542af2014-09-03 16:16:56 -07002234 JDWP::JdwpError error;
2235 Thread* thread = DecodeThread(soa, thread_id, &error);
Elliott Hughes221229c2013-01-08 18:17:50 -08002236 if (error != JDWP::ERR_NONE) {
2237 return error;
Elliott Hughes2435a572012-02-17 16:07:41 -08002238 }
Ian Rogers50b35e22012-10-04 10:09:15 -07002239 MutexLock mu2(soa.Self(), *Locks::thread_suspend_count_lock_);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002240 expandBufAdd4BE(pReply, thread->GetDebugSuspendCount());
Elliott Hughes2435a572012-02-17 16:07:41 -08002241 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002242}
2243
Elliott Hughesf9501702013-01-11 11:22:27 -08002244JDWP::JdwpError Dbg::Interrupt(JDWP::ObjectId thread_id) {
2245 ScopedObjectAccess soa(Thread::Current());
2246 MutexLock mu(soa.Self(), *Locks::thread_list_lock_);
Ian Rogersc0542af2014-09-03 16:16:56 -07002247 JDWP::JdwpError error;
2248 Thread* thread = DecodeThread(soa, thread_id, &error);
Elliott Hughesf9501702013-01-11 11:22:27 -08002249 if (error != JDWP::ERR_NONE) {
2250 return error;
2251 }
Ian Rogersdd7624d2014-03-14 17:43:00 -07002252 thread->Interrupt(soa.Self());
Elliott Hughesf9501702013-01-11 11:22:27 -08002253 return JDWP::ERR_NONE;
2254}
2255
Sebastien Hertz070f7322014-09-09 12:08:49 +02002256static bool IsInDesiredThreadGroup(ScopedObjectAccessUnchecked& soa,
2257 mirror::Object* desired_thread_group, mirror::Object* peer)
2258 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
2259 // Do we want threads from all thread groups?
2260 if (desired_thread_group == nullptr) {
2261 return true;
2262 }
2263 mirror::ArtField* thread_group_field = soa.DecodeField(WellKnownClasses::java_lang_Thread_group);
2264 DCHECK(thread_group_field != nullptr);
2265 mirror::Object* group = thread_group_field->GetObject(peer);
2266 return (group == desired_thread_group);
2267}
2268
Sebastien Hertza06430c2014-09-15 19:21:30 +02002269void Dbg::GetThreads(mirror::Object* thread_group, std::vector<JDWP::ObjectId>* thread_ids) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002270 ScopedObjectAccessUnchecked soa(Thread::Current());
Sebastien Hertz070f7322014-09-09 12:08:49 +02002271 std::list<Thread*> all_threads_list;
2272 {
2273 MutexLock mu(Thread::Current(), *Locks::thread_list_lock_);
2274 all_threads_list = Runtime::Current()->GetThreadList()->GetList();
2275 }
2276 for (Thread* t : all_threads_list) {
2277 if (t == Dbg::GetDebugThread()) {
2278 // Skip the JDWP thread. Some debuggers get bent out of shape when they can't suspend and
2279 // query all threads, so it's easier if we just don't tell them about this thread.
2280 continue;
2281 }
2282 if (t->IsStillStarting()) {
2283 // This thread is being started (and has been registered in the thread list). However, it is
2284 // not completely started yet so we must ignore it.
2285 continue;
2286 }
2287 mirror::Object* peer = t->GetPeer();
2288 if (peer == nullptr) {
2289 // peer might be NULL if the thread is still starting up. We can't tell the debugger about
2290 // this thread yet.
2291 // TODO: if we identified threads to the debugger by their Thread*
2292 // rather than their peer's mirror::Object*, we could fix this.
2293 // Doing so might help us report ZOMBIE threads too.
2294 continue;
2295 }
2296 if (IsInDesiredThreadGroup(soa, thread_group, peer)) {
2297 thread_ids->push_back(gRegistry->Add(peer));
2298 }
2299 }
Elliott Hughescaf76542012-06-28 16:08:22 -07002300}
Elliott Hughesa2155262011-11-16 16:26:58 -08002301
Ian Rogersc0542af2014-09-03 16:16:56 -07002302static int GetStackDepth(Thread* thread) SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Ian Rogers0399dde2012-06-06 17:09:28 -07002303 struct CountStackDepthVisitor : public StackVisitor {
Andreas Gampe277ccbd2014-11-03 21:36:10 -08002304 explicit CountStackDepthVisitor(Thread* thread_in)
2305 : StackVisitor(thread_in, nullptr), depth(0) {}
Ian Rogers0399dde2012-06-06 17:09:28 -07002306
Elliott Hughes64f574f2013-02-20 14:57:12 -08002307 // TODO: Enable annotalysis. We know lock is held in constructor, but abstraction confuses
2308 // annotalysis.
2309 bool VisitFrame() NO_THREAD_SAFETY_ANALYSIS {
Ian Rogers0399dde2012-06-06 17:09:28 -07002310 if (!GetMethod()->IsRuntimeMethod()) {
Elliott Hughesf8a2df72011-12-01 12:19:54 -08002311 ++depth;
2312 }
Elliott Hughes530fa002012-03-12 11:44:49 -07002313 return true;
Elliott Hughesa2e54f62011-11-17 13:01:30 -08002314 }
2315 size_t depth;
2316 };
Elliott Hughes08fc03a2012-06-26 17:34:00 -07002317
Ian Rogers7a22fa62013-01-23 12:16:16 -08002318 CountStackDepthVisitor visitor(thread);
Ian Rogers0399dde2012-06-06 17:09:28 -07002319 visitor.WalkStack();
Elliott Hughesa2e54f62011-11-17 13:01:30 -08002320 return visitor.depth;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002321}
2322
Ian Rogersc0542af2014-09-03 16:16:56 -07002323JDWP::JdwpError Dbg::GetThreadFrameCount(JDWP::ObjectId thread_id, size_t* result) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002324 ScopedObjectAccess soa(Thread::Current());
jeffhaoa77f0f62012-12-05 17:19:31 -08002325 MutexLock mu(soa.Self(), *Locks::thread_list_lock_);
Ian Rogersc0542af2014-09-03 16:16:56 -07002326 JDWP::JdwpError error;
2327 *result = 0;
2328 Thread* thread = DecodeThread(soa, thread_id, &error);
Elliott Hughes221229c2013-01-08 18:17:50 -08002329 if (error != JDWP::ERR_NONE) {
2330 return error;
2331 }
Elliott Hughesf15f4a02013-01-09 10:09:38 -08002332 if (!IsSuspendedForDebugger(soa, thread)) {
2333 return JDWP::ERR_THREAD_NOT_SUSPENDED;
2334 }
Ian Rogersc0542af2014-09-03 16:16:56 -07002335 *result = GetStackDepth(thread);
Elliott Hughes221229c2013-01-08 18:17:50 -08002336 return JDWP::ERR_NONE;
Elliott Hughes86964332012-02-15 19:37:42 -08002337}
2338
Ian Rogers306057f2012-11-26 12:45:53 -08002339JDWP::JdwpError Dbg::GetThreadFrames(JDWP::ObjectId thread_id, size_t start_frame,
2340 size_t frame_count, JDWP::ExpandBuf* buf) {
Elliott Hughes6e9d22c2012-06-22 15:02:37 -07002341 class GetFrameVisitor : public StackVisitor {
2342 public:
Andreas Gampe277ccbd2014-11-03 21:36:10 -08002343 GetFrameVisitor(Thread* thread, size_t start_frame_in, size_t frame_count_in,
2344 JDWP::ExpandBuf* buf_in)
Ian Rogersb726dcb2012-09-05 08:57:23 -07002345 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_)
Ian Rogersc0542af2014-09-03 16:16:56 -07002346 : StackVisitor(thread, nullptr), depth_(0),
Andreas Gampe277ccbd2014-11-03 21:36:10 -08002347 start_frame_(start_frame_in), frame_count_(frame_count_in), buf_(buf_in) {
Elliott Hughes6e9d22c2012-06-22 15:02:37 -07002348 expandBufAdd4BE(buf_, frame_count_);
Elliott Hughes03181a82011-11-17 17:22:21 -08002349 }
Ian Rogers0399dde2012-06-06 17:09:28 -07002350
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002351 // TODO: Enable annotalysis. We know lock is held in constructor, but abstraction confuses
2352 // annotalysis.
2353 virtual bool VisitFrame() NO_THREAD_SAFETY_ANALYSIS {
Ian Rogers0399dde2012-06-06 17:09:28 -07002354 if (GetMethod()->IsRuntimeMethod()) {
Brian Carlstrom7934ac22013-07-26 10:54:15 -07002355 return true; // The debugger can't do anything useful with a frame that has no Method*.
Elliott Hughes03181a82011-11-17 17:22:21 -08002356 }
Elliott Hughes6e9d22c2012-06-22 15:02:37 -07002357 if (depth_ >= start_frame_ + frame_count_) {
Elliott Hughes530fa002012-03-12 11:44:49 -07002358 return false;
Elliott Hughes03181a82011-11-17 17:22:21 -08002359 }
Elliott Hughes6e9d22c2012-06-22 15:02:37 -07002360 if (depth_ >= start_frame_) {
2361 JDWP::FrameId frame_id(GetFrameId());
2362 JDWP::JdwpLocation location;
Sebastien Hertz6995c602014-09-09 12:10:13 +02002363 SetJdwpLocation(&location, GetMethod(), GetDexPc());
Ian Rogersef7d42f2014-01-06 12:55:46 -08002364 VLOG(jdwp) << StringPrintf(" Frame %3zd: id=%3" PRIu64 " ", depth_, frame_id) << location;
Elliott Hughes6e9d22c2012-06-22 15:02:37 -07002365 expandBufAdd8BE(buf_, frame_id);
2366 expandBufAddLocation(buf_, location);
2367 }
2368 ++depth_;
Elliott Hughes530fa002012-03-12 11:44:49 -07002369 return true;
Elliott Hughes03181a82011-11-17 17:22:21 -08002370 }
Elliott Hughes6e9d22c2012-06-22 15:02:37 -07002371
2372 private:
2373 size_t depth_;
2374 const size_t start_frame_;
2375 const size_t frame_count_;
2376 JDWP::ExpandBuf* buf_;
Elliott Hughes03181a82011-11-17 17:22:21 -08002377 };
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002378
2379 ScopedObjectAccessUnchecked soa(Thread::Current());
jeffhaoa77f0f62012-12-05 17:19:31 -08002380 MutexLock mu(soa.Self(), *Locks::thread_list_lock_);
Ian Rogersc0542af2014-09-03 16:16:56 -07002381 JDWP::JdwpError error;
2382 Thread* thread = DecodeThread(soa, thread_id, &error);
Elliott Hughes221229c2013-01-08 18:17:50 -08002383 if (error != JDWP::ERR_NONE) {
2384 return error;
2385 }
Elliott Hughesf15f4a02013-01-09 10:09:38 -08002386 if (!IsSuspendedForDebugger(soa, thread)) {
2387 return JDWP::ERR_THREAD_NOT_SUSPENDED;
2388 }
Ian Rogers7a22fa62013-01-23 12:16:16 -08002389 GetFrameVisitor visitor(thread, start_frame, frame_count, buf);
Ian Rogers0399dde2012-06-06 17:09:28 -07002390 visitor.WalkStack();
Elliott Hughes6e9d22c2012-06-22 15:02:37 -07002391 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002392}
2393
2394JDWP::ObjectId Dbg::GetThreadSelfId() {
Sebastien Hertz6995c602014-09-09 12:10:13 +02002395 return GetThreadId(Thread::Current());
2396}
2397
2398JDWP::ObjectId Dbg::GetThreadId(Thread* thread) {
Mathieu Chartierdbe6f462012-09-25 16:54:50 -07002399 ScopedObjectAccessUnchecked soa(Thread::Current());
Sebastien Hertz6995c602014-09-09 12:10:13 +02002400 return gRegistry->Add(thread->GetPeer());
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002401}
2402
Elliott Hughes475fc232011-10-25 15:00:35 -07002403void Dbg::SuspendVM() {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002404 Runtime::Current()->GetThreadList()->SuspendAllForDebugger();
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002405}
2406
2407void Dbg::ResumeVM() {
Sebastien Hertz253fa552014-10-14 17:27:15 +02002408 Runtime::Current()->GetThreadList()->ResumeAllForDebugger();
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002409}
2410
Elliott Hughes221229c2013-01-08 18:17:50 -08002411JDWP::JdwpError Dbg::SuspendThread(JDWP::ObjectId thread_id, bool request_suspension) {
Ian Rogersf3d874c2014-07-17 18:52:42 -07002412 Thread* self = Thread::Current();
Ian Rogersc0542af2014-09-03 16:16:56 -07002413 ScopedLocalRef<jobject> peer(self->GetJniEnv(), nullptr);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002414 {
Ian Rogersf3d874c2014-07-17 18:52:42 -07002415 ScopedObjectAccess soa(self);
Ian Rogersc0542af2014-09-03 16:16:56 -07002416 JDWP::JdwpError error;
2417 peer.reset(soa.AddLocalReference<jobject>(gRegistry->Get<mirror::Object*>(thread_id, &error)));
Elliott Hughes4e235312011-12-02 11:34:15 -08002418 }
Ian Rogersc0542af2014-09-03 16:16:56 -07002419 if (peer.get() == nullptr) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002420 return JDWP::ERR_THREAD_NOT_ALIVE;
2421 }
Ian Rogers4ad5cd32014-11-11 23:08:07 -08002422 // Suspend thread to build stack trace.
Elliott Hughesf327e072013-01-09 16:01:26 -08002423 bool timed_out;
Brian Carlstromba32de42014-08-27 23:43:46 -07002424 ThreadList* thread_list = Runtime::Current()->GetThreadList();
2425 Thread* thread = thread_list->SuspendThreadByPeer(peer.get(), request_suspension, true,
2426 &timed_out);
Ian Rogersc0542af2014-09-03 16:16:56 -07002427 if (thread != nullptr) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002428 return JDWP::ERR_NONE;
Elliott Hughesf327e072013-01-09 16:01:26 -08002429 } else if (timed_out) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002430 return JDWP::ERR_INTERNAL;
2431 } else {
2432 return JDWP::ERR_THREAD_NOT_ALIVE;
2433 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002434}
2435
Elliott Hughes221229c2013-01-08 18:17:50 -08002436void Dbg::ResumeThread(JDWP::ObjectId thread_id) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002437 ScopedObjectAccessUnchecked soa(Thread::Current());
Ian Rogersc0542af2014-09-03 16:16:56 -07002438 JDWP::JdwpError error;
2439 mirror::Object* peer = gRegistry->Get<mirror::Object*>(thread_id, &error);
2440 CHECK(peer != nullptr) << error;
jeffhaoa77f0f62012-12-05 17:19:31 -08002441 Thread* thread;
2442 {
2443 MutexLock mu(soa.Self(), *Locks::thread_list_lock_);
2444 thread = Thread::FromManagedThread(soa, peer);
2445 }
Ian Rogersc0542af2014-09-03 16:16:56 -07002446 if (thread == nullptr) {
Elliott Hughes4e235312011-12-02 11:34:15 -08002447 LOG(WARNING) << "No such thread for resume: " << peer;
2448 return;
2449 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002450 bool needs_resume;
2451 {
Ian Rogers50b35e22012-10-04 10:09:15 -07002452 MutexLock mu2(soa.Self(), *Locks::thread_suspend_count_lock_);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002453 needs_resume = thread->GetSuspendCount() > 0;
2454 }
2455 if (needs_resume) {
Elliott Hughes546b9862012-06-20 16:06:13 -07002456 Runtime::Current()->GetThreadList()->Resume(thread, true);
2457 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002458}
2459
2460void Dbg::SuspendSelf() {
Elliott Hughes475fc232011-10-25 15:00:35 -07002461 Runtime::Current()->GetThreadList()->SuspendSelfForDebugger();
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002462}
2463
Ian Rogers0399dde2012-06-06 17:09:28 -07002464struct GetThisVisitor : public StackVisitor {
Andreas Gampe277ccbd2014-11-03 21:36:10 -08002465 GetThisVisitor(Thread* thread, Context* context, JDWP::FrameId frame_id_in)
Ian Rogersb726dcb2012-09-05 08:57:23 -07002466 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_)
Andreas Gampe277ccbd2014-11-03 21:36:10 -08002467 : StackVisitor(thread, context), this_object(nullptr), frame_id(frame_id_in) {}
Ian Rogers0399dde2012-06-06 17:09:28 -07002468
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002469 // TODO: Enable annotalysis. We know lock is held in constructor, but abstraction confuses
2470 // annotalysis.
2471 virtual bool VisitFrame() NO_THREAD_SAFETY_ANALYSIS {
Elliott Hughes6e9d22c2012-06-22 15:02:37 -07002472 if (frame_id != GetFrameId()) {
Ian Rogers0399dde2012-06-06 17:09:28 -07002473 return true; // continue
Ian Rogers0399dde2012-06-06 17:09:28 -07002474 } else {
Ian Rogers62d6c772013-02-27 08:32:07 -08002475 this_object = GetThisObject();
2476 return false;
Ian Rogers0399dde2012-06-06 17:09:28 -07002477 }
Elliott Hughes86b00102011-12-05 17:54:26 -08002478 }
Ian Rogers0399dde2012-06-06 17:09:28 -07002479
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002480 mirror::Object* this_object;
Elliott Hughes6e9d22c2012-06-22 15:02:37 -07002481 JDWP::FrameId frame_id;
Ian Rogers0399dde2012-06-06 17:09:28 -07002482};
2483
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002484JDWP::JdwpError Dbg::GetThisObject(JDWP::ObjectId thread_id, JDWP::FrameId frame_id,
2485 JDWP::ObjectId* result) {
2486 ScopedObjectAccessUnchecked soa(Thread::Current());
2487 Thread* thread;
2488 {
Ian Rogers50b35e22012-10-04 10:09:15 -07002489 MutexLock mu(soa.Self(), *Locks::thread_list_lock_);
Ian Rogersc0542af2014-09-03 16:16:56 -07002490 JDWP::JdwpError error;
2491 thread = DecodeThread(soa, thread_id, &error);
Elliott Hughes221229c2013-01-08 18:17:50 -08002492 if (error != JDWP::ERR_NONE) {
2493 return error;
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002494 }
Elliott Hughes9e0c1752013-01-09 14:02:58 -08002495 if (!IsSuspendedForDebugger(soa, thread)) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002496 return JDWP::ERR_THREAD_NOT_SUSPENDED;
2497 }
Elliott Hughes6e9d22c2012-06-22 15:02:37 -07002498 }
Ian Rogers700a4022014-05-19 16:49:03 -07002499 std::unique_ptr<Context> context(Context::Create());
Ian Rogers7a22fa62013-01-23 12:16:16 -08002500 GetThisVisitor visitor(thread, context.get(), frame_id);
Ian Rogers0399dde2012-06-06 17:09:28 -07002501 visitor.WalkStack();
Elliott Hughes6e9d22c2012-06-22 15:02:37 -07002502 *result = gRegistry->Add(visitor.this_object);
2503 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002504}
2505
Sebastien Hertz8009f392014-09-01 17:07:11 +02002506// Walks the stack until we find the frame with the given FrameId.
2507class FindFrameVisitor FINAL : public StackVisitor {
2508 public:
2509 FindFrameVisitor(Thread* thread, Context* context, JDWP::FrameId frame_id)
2510 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_)
2511 : StackVisitor(thread, context), frame_id_(frame_id), error_(JDWP::ERR_INVALID_FRAMEID) {}
Ian Rogersca190662012-06-26 15:45:57 -07002512
Sebastien Hertz8009f392014-09-01 17:07:11 +02002513 // TODO: Enable annotalysis. We know lock is held in constructor, but abstraction confuses
2514 // annotalysis.
2515 bool VisitFrame() NO_THREAD_SAFETY_ANALYSIS {
2516 if (GetFrameId() != frame_id_) {
2517 return true; // Not our frame, carry on.
Ian Rogers0399dde2012-06-06 17:09:28 -07002518 }
Sebastien Hertz8009f392014-09-01 17:07:11 +02002519 mirror::ArtMethod* m = GetMethod();
2520 if (m->IsNative()) {
2521 // We can't read/write local value from/into native method.
2522 error_ = JDWP::ERR_OPAQUE_FRAME;
2523 } else {
2524 // We found our frame.
2525 error_ = JDWP::ERR_NONE;
2526 }
2527 return false;
2528 }
2529
2530 JDWP::JdwpError GetError() const {
2531 return error_;
2532 }
2533
2534 private:
2535 const JDWP::FrameId frame_id_;
2536 JDWP::JdwpError error_;
2537};
2538
2539JDWP::JdwpError Dbg::GetLocalValues(JDWP::Request* request, JDWP::ExpandBuf* pReply) {
2540 JDWP::ObjectId thread_id = request->ReadThreadId();
2541 JDWP::FrameId frame_id = request->ReadFrameId();
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002542
2543 ScopedObjectAccessUnchecked soa(Thread::Current());
Sebastien Hertz8009f392014-09-01 17:07:11 +02002544 Thread* thread;
2545 {
2546 MutexLock mu(soa.Self(), *Locks::thread_list_lock_);
2547 JDWP::JdwpError error;
2548 thread = DecodeThread(soa, thread_id, &error);
2549 if (error != JDWP::ERR_NONE) {
2550 return error;
2551 }
Elliott Hughes221229c2013-01-08 18:17:50 -08002552 }
Sebastien Hertz8009f392014-09-01 17:07:11 +02002553 // Find the frame with the given frame_id.
Ian Rogers700a4022014-05-19 16:49:03 -07002554 std::unique_ptr<Context> context(Context::Create());
Sebastien Hertz8009f392014-09-01 17:07:11 +02002555 FindFrameVisitor visitor(thread, context.get(), frame_id);
Ian Rogers0399dde2012-06-06 17:09:28 -07002556 visitor.WalkStack();
Sebastien Hertz8009f392014-09-01 17:07:11 +02002557 if (visitor.GetError() != JDWP::ERR_NONE) {
2558 return visitor.GetError();
2559 }
2560
2561 // Read the values from visitor's context.
2562 int32_t slot_count = request->ReadSigned32("slot count");
2563 expandBufAdd4BE(pReply, slot_count); /* "int values" */
2564 for (int32_t i = 0; i < slot_count; ++i) {
2565 uint32_t slot = request->ReadUnsigned32("slot");
2566 JDWP::JdwpTag reqSigByte = request->ReadTag();
2567
2568 VLOG(jdwp) << " --> slot " << slot << " " << reqSigByte;
2569
2570 size_t width = Dbg::GetTagWidth(reqSigByte);
Sebastien Hertz7d955652014-10-22 10:57:10 +02002571 uint8_t* ptr = expandBufAddSpace(pReply, width + 1);
Sebastien Hertz8009f392014-09-01 17:07:11 +02002572 JDWP::JdwpError error = Dbg::GetLocalValue(visitor, soa, slot, reqSigByte, ptr, width);
2573 if (error != JDWP::ERR_NONE) {
2574 return error;
2575 }
2576 }
2577 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002578}
2579
Sebastien Hertz8009f392014-09-01 17:07:11 +02002580JDWP::JdwpError Dbg::GetLocalValue(const StackVisitor& visitor, ScopedObjectAccessUnchecked& soa,
2581 int slot, JDWP::JdwpTag tag, uint8_t* buf, size_t width) {
2582 mirror::ArtMethod* m = visitor.GetMethod();
2583 uint16_t reg = DemangleSlot(slot, m);
2584 // TODO: check that the tag is compatible with the actual type of the slot!
2585 // TODO: check slot is valid for this method or return INVALID_SLOT error.
2586 constexpr JDWP::JdwpError kFailureErrorCode = JDWP::ERR_ABSENT_INFORMATION;
2587 switch (tag) {
2588 case JDWP::JT_BOOLEAN: {
2589 CHECK_EQ(width, 1U);
2590 uint32_t intVal;
2591 if (visitor.GetVReg(m, reg, kIntVReg, &intVal)) {
2592 VLOG(jdwp) << "get boolean local " << reg << " = " << intVal;
2593 JDWP::Set1(buf + 1, intVal != 0);
2594 } else {
2595 VLOG(jdwp) << "failed to get boolean local " << reg;
2596 return kFailureErrorCode;
Ian Rogers0399dde2012-06-06 17:09:28 -07002597 }
Sebastien Hertz8009f392014-09-01 17:07:11 +02002598 break;
Ian Rogers0399dde2012-06-06 17:09:28 -07002599 }
Sebastien Hertz8009f392014-09-01 17:07:11 +02002600 case JDWP::JT_BYTE: {
2601 CHECK_EQ(width, 1U);
2602 uint32_t intVal;
2603 if (visitor.GetVReg(m, reg, kIntVReg, &intVal)) {
2604 VLOG(jdwp) << "get byte local " << reg << " = " << intVal;
2605 JDWP::Set1(buf + 1, intVal);
2606 } else {
2607 VLOG(jdwp) << "failed to get byte local " << reg;
2608 return kFailureErrorCode;
2609 }
2610 break;
2611 }
2612 case JDWP::JT_SHORT:
2613 case JDWP::JT_CHAR: {
2614 CHECK_EQ(width, 2U);
2615 uint32_t intVal;
2616 if (visitor.GetVReg(m, reg, kIntVReg, &intVal)) {
2617 VLOG(jdwp) << "get short/char local " << reg << " = " << intVal;
2618 JDWP::Set2BE(buf + 1, intVal);
2619 } else {
2620 VLOG(jdwp) << "failed to get short/char local " << reg;
2621 return kFailureErrorCode;
2622 }
2623 break;
2624 }
2625 case JDWP::JT_INT: {
2626 CHECK_EQ(width, 4U);
2627 uint32_t intVal;
2628 if (visitor.GetVReg(m, reg, kIntVReg, &intVal)) {
2629 VLOG(jdwp) << "get int local " << reg << " = " << intVal;
2630 JDWP::Set4BE(buf + 1, intVal);
2631 } else {
2632 VLOG(jdwp) << "failed to get int local " << reg;
2633 return kFailureErrorCode;
2634 }
2635 break;
2636 }
2637 case JDWP::JT_FLOAT: {
2638 CHECK_EQ(width, 4U);
2639 uint32_t intVal;
2640 if (visitor.GetVReg(m, reg, kFloatVReg, &intVal)) {
2641 VLOG(jdwp) << "get float local " << reg << " = " << intVal;
2642 JDWP::Set4BE(buf + 1, intVal);
2643 } else {
2644 VLOG(jdwp) << "failed to get float local " << reg;
2645 return kFailureErrorCode;
2646 }
2647 break;
2648 }
2649 case JDWP::JT_ARRAY:
2650 case JDWP::JT_CLASS_LOADER:
2651 case JDWP::JT_CLASS_OBJECT:
2652 case JDWP::JT_OBJECT:
2653 case JDWP::JT_STRING:
2654 case JDWP::JT_THREAD:
2655 case JDWP::JT_THREAD_GROUP: {
2656 CHECK_EQ(width, sizeof(JDWP::ObjectId));
2657 uint32_t intVal;
2658 if (visitor.GetVReg(m, reg, kReferenceVReg, &intVal)) {
2659 mirror::Object* o = reinterpret_cast<mirror::Object*>(intVal);
2660 VLOG(jdwp) << "get " << tag << " object local " << reg << " = " << o;
2661 if (!Runtime::Current()->GetHeap()->IsValidObjectAddress(o)) {
2662 LOG(FATAL) << "Register " << reg << " expected to hold " << tag << " object: " << o;
2663 }
2664 tag = TagFromObject(soa, o);
2665 JDWP::SetObjectId(buf + 1, gRegistry->Add(o));
2666 } else {
2667 VLOG(jdwp) << "failed to get " << tag << " object local " << reg;
2668 return kFailureErrorCode;
2669 }
2670 break;
2671 }
2672 case JDWP::JT_DOUBLE: {
2673 CHECK_EQ(width, 8U);
2674 uint64_t longVal;
2675 if (visitor.GetVRegPair(m, reg, kDoubleLoVReg, kDoubleHiVReg, &longVal)) {
2676 VLOG(jdwp) << "get double local " << reg << " = " << longVal;
2677 JDWP::Set8BE(buf + 1, longVal);
2678 } else {
2679 VLOG(jdwp) << "failed to get double local " << reg;
2680 return kFailureErrorCode;
2681 }
2682 break;
2683 }
2684 case JDWP::JT_LONG: {
2685 CHECK_EQ(width, 8U);
2686 uint64_t longVal;
2687 if (visitor.GetVRegPair(m, reg, kLongLoVReg, kLongHiVReg, &longVal)) {
2688 VLOG(jdwp) << "get long local " << reg << " = " << longVal;
2689 JDWP::Set8BE(buf + 1, longVal);
2690 } else {
2691 VLOG(jdwp) << "failed to get long local " << reg;
2692 return kFailureErrorCode;
2693 }
2694 break;
2695 }
2696 default:
2697 LOG(FATAL) << "Unknown tag " << tag;
2698 break;
2699 }
Ian Rogers0399dde2012-06-06 17:09:28 -07002700
Sebastien Hertz8009f392014-09-01 17:07:11 +02002701 // Prepend tag, which may have been updated.
2702 JDWP::Set1(buf, tag);
2703 return JDWP::ERR_NONE;
2704}
2705
2706JDWP::JdwpError Dbg::SetLocalValues(JDWP::Request* request) {
2707 JDWP::ObjectId thread_id = request->ReadThreadId();
2708 JDWP::FrameId frame_id = request->ReadFrameId();
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002709
2710 ScopedObjectAccessUnchecked soa(Thread::Current());
Sebastien Hertz8009f392014-09-01 17:07:11 +02002711 Thread* thread;
2712 {
2713 MutexLock mu(soa.Self(), *Locks::thread_list_lock_);
2714 JDWP::JdwpError error;
2715 thread = DecodeThread(soa, thread_id, &error);
2716 if (error != JDWP::ERR_NONE) {
2717 return error;
2718 }
Elliott Hughes221229c2013-01-08 18:17:50 -08002719 }
Sebastien Hertz8009f392014-09-01 17:07:11 +02002720 // Find the frame with the given frame_id.
Ian Rogers700a4022014-05-19 16:49:03 -07002721 std::unique_ptr<Context> context(Context::Create());
Sebastien Hertz8009f392014-09-01 17:07:11 +02002722 FindFrameVisitor visitor(thread, context.get(), frame_id);
Ian Rogers0399dde2012-06-06 17:09:28 -07002723 visitor.WalkStack();
Sebastien Hertz8009f392014-09-01 17:07:11 +02002724 if (visitor.GetError() != JDWP::ERR_NONE) {
2725 return visitor.GetError();
2726 }
2727
2728 // Writes the values into visitor's context.
2729 int32_t slot_count = request->ReadSigned32("slot count");
2730 for (int32_t i = 0; i < slot_count; ++i) {
2731 uint32_t slot = request->ReadUnsigned32("slot");
2732 JDWP::JdwpTag sigByte = request->ReadTag();
2733 size_t width = Dbg::GetTagWidth(sigByte);
2734 uint64_t value = request->ReadValue(width);
2735
2736 VLOG(jdwp) << " --> slot " << slot << " " << sigByte << " " << value;
2737 JDWP::JdwpError error = Dbg::SetLocalValue(visitor, slot, sigByte, value, width);
2738 if (error != JDWP::ERR_NONE) {
2739 return error;
2740 }
2741 }
2742 return JDWP::ERR_NONE;
2743}
2744
2745JDWP::JdwpError Dbg::SetLocalValue(StackVisitor& visitor, int slot, JDWP::JdwpTag tag,
2746 uint64_t value, size_t width) {
2747 mirror::ArtMethod* m = visitor.GetMethod();
2748 uint16_t reg = DemangleSlot(slot, m);
2749 // TODO: check that the tag is compatible with the actual type of the slot!
2750 // TODO: check slot is valid for this method or return INVALID_SLOT error.
2751 constexpr JDWP::JdwpError kFailureErrorCode = JDWP::ERR_ABSENT_INFORMATION;
2752 switch (tag) {
2753 case JDWP::JT_BOOLEAN:
2754 case JDWP::JT_BYTE:
2755 CHECK_EQ(width, 1U);
2756 if (!visitor.SetVReg(m, reg, static_cast<uint32_t>(value), kIntVReg)) {
2757 VLOG(jdwp) << "failed to set boolean/byte local " << reg << " = "
2758 << static_cast<uint32_t>(value);
2759 return kFailureErrorCode;
2760 }
2761 break;
2762 case JDWP::JT_SHORT:
2763 case JDWP::JT_CHAR:
2764 CHECK_EQ(width, 2U);
2765 if (!visitor.SetVReg(m, reg, static_cast<uint32_t>(value), kIntVReg)) {
2766 VLOG(jdwp) << "failed to set short/char local " << reg << " = "
2767 << static_cast<uint32_t>(value);
2768 return kFailureErrorCode;
2769 }
2770 break;
2771 case JDWP::JT_INT:
2772 CHECK_EQ(width, 4U);
2773 if (!visitor.SetVReg(m, reg, static_cast<uint32_t>(value), kIntVReg)) {
2774 VLOG(jdwp) << "failed to set int local " << reg << " = "
2775 << static_cast<uint32_t>(value);
2776 return kFailureErrorCode;
2777 }
2778 break;
2779 case JDWP::JT_FLOAT:
2780 CHECK_EQ(width, 4U);
2781 if (!visitor.SetVReg(m, reg, static_cast<uint32_t>(value), kFloatVReg)) {
2782 VLOG(jdwp) << "failed to set float local " << reg << " = "
2783 << static_cast<uint32_t>(value);
2784 return kFailureErrorCode;
2785 }
2786 break;
2787 case JDWP::JT_ARRAY:
2788 case JDWP::JT_CLASS_LOADER:
2789 case JDWP::JT_CLASS_OBJECT:
2790 case JDWP::JT_OBJECT:
2791 case JDWP::JT_STRING:
2792 case JDWP::JT_THREAD:
2793 case JDWP::JT_THREAD_GROUP: {
2794 CHECK_EQ(width, sizeof(JDWP::ObjectId));
2795 JDWP::JdwpError error;
2796 mirror::Object* o = gRegistry->Get<mirror::Object*>(static_cast<JDWP::ObjectId>(value),
2797 &error);
2798 if (error != JDWP::ERR_NONE) {
2799 VLOG(jdwp) << tag << " object " << o << " is an invalid object";
2800 return JDWP::ERR_INVALID_OBJECT;
2801 } else if (!visitor.SetVReg(m, reg, static_cast<uint32_t>(reinterpret_cast<uintptr_t>(o)),
2802 kReferenceVReg)) {
2803 VLOG(jdwp) << "failed to set " << tag << " object local " << reg << " = " << o;
2804 return kFailureErrorCode;
2805 }
2806 break;
2807 }
2808 case JDWP::JT_DOUBLE: {
2809 CHECK_EQ(width, 8U);
2810 if (!visitor.SetVRegPair(m, reg, value, kDoubleLoVReg, kDoubleHiVReg)) {
2811 VLOG(jdwp) << "failed to set double local " << reg << " = " << value;
2812 return kFailureErrorCode;
2813 }
2814 break;
2815 }
2816 case JDWP::JT_LONG: {
2817 CHECK_EQ(width, 8U);
2818 if (!visitor.SetVRegPair(m, reg, value, kLongLoVReg, kLongHiVReg)) {
2819 VLOG(jdwp) << "failed to set double local " << reg << " = " << value;
2820 return kFailureErrorCode;
2821 }
2822 break;
2823 }
2824 default:
2825 LOG(FATAL) << "Unknown tag " << tag;
2826 break;
2827 }
2828 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002829}
2830
Sebastien Hertz6995c602014-09-09 12:10:13 +02002831static void SetEventLocation(JDWP::EventLocation* location, mirror::ArtMethod* m, uint32_t dex_pc)
2832 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
2833 DCHECK(location != nullptr);
2834 if (m == nullptr) {
2835 memset(location, 0, sizeof(*location));
2836 } else {
2837 location->method = m;
2838 location->dex_pc = (m->IsNative() || m->IsProxyMethod()) ? static_cast<uint32_t>(-1) : dex_pc;
Sebastien Hertz3f52eaf2014-04-04 17:50:18 +02002839 }
Sebastien Hertz3f52eaf2014-04-04 17:50:18 +02002840}
2841
Ian Rogersef7d42f2014-01-06 12:55:46 -08002842void Dbg::PostLocationEvent(mirror::ArtMethod* m, int dex_pc, mirror::Object* this_object,
Jeff Hao579b0242013-11-18 13:16:49 -08002843 int event_flags, const JValue* return_value) {
Sebastien Hertz3f52eaf2014-04-04 17:50:18 +02002844 if (!IsDebuggerActive()) {
2845 return;
2846 }
2847 DCHECK(m != nullptr);
2848 DCHECK_EQ(m->IsStatic(), this_object == nullptr);
Sebastien Hertz6995c602014-09-09 12:10:13 +02002849 JDWP::EventLocation location;
2850 SetEventLocation(&location, m, dex_pc);
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08002851
Sebastien Hertz6995c602014-09-09 12:10:13 +02002852 gJdwpState->PostLocationEvent(&location, this_object, event_flags, return_value);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002853}
2854
Sebastien Hertz3f52eaf2014-04-04 17:50:18 +02002855void Dbg::PostFieldAccessEvent(mirror::ArtMethod* m, int dex_pc,
2856 mirror::Object* this_object, mirror::ArtField* f) {
2857 if (!IsDebuggerActive()) {
2858 return;
2859 }
2860 DCHECK(m != nullptr);
2861 DCHECK(f != nullptr);
Sebastien Hertz6995c602014-09-09 12:10:13 +02002862 JDWP::EventLocation location;
2863 SetEventLocation(&location, m, dex_pc);
Sebastien Hertz3f52eaf2014-04-04 17:50:18 +02002864
Sebastien Hertz6995c602014-09-09 12:10:13 +02002865 gJdwpState->PostFieldEvent(&location, f, this_object, nullptr, false);
Sebastien Hertz3f52eaf2014-04-04 17:50:18 +02002866}
2867
2868void Dbg::PostFieldModificationEvent(mirror::ArtMethod* m, int dex_pc,
2869 mirror::Object* this_object, mirror::ArtField* f,
2870 const JValue* field_value) {
2871 if (!IsDebuggerActive()) {
2872 return;
2873 }
2874 DCHECK(m != nullptr);
2875 DCHECK(f != nullptr);
2876 DCHECK(field_value != nullptr);
Sebastien Hertz6995c602014-09-09 12:10:13 +02002877 JDWP::EventLocation location;
2878 SetEventLocation(&location, m, dex_pc);
Sebastien Hertz3f52eaf2014-04-04 17:50:18 +02002879
Sebastien Hertz6995c602014-09-09 12:10:13 +02002880 gJdwpState->PostFieldEvent(&location, f, this_object, field_value, true);
Sebastien Hertz3f52eaf2014-04-04 17:50:18 +02002881}
2882
2883void Dbg::PostException(const ThrowLocation& throw_location,
Brian Carlstromea46f952013-07-30 01:26:50 -07002884 mirror::ArtMethod* catch_method,
Elliott Hughes64f574f2013-02-20 14:57:12 -08002885 uint32_t catch_dex_pc, mirror::Throwable* exception_object) {
Elliott Hughesc0f09332012-03-26 13:27:06 -07002886 if (!IsDebuggerActive()) {
Ian Rogers0ad5bb82011-12-07 10:16:32 -08002887 return;
2888 }
Sebastien Hertz6995c602014-09-09 12:10:13 +02002889 JDWP::EventLocation exception_throw_location;
2890 SetEventLocation(&exception_throw_location, throw_location.GetMethod(), throw_location.GetDexPc());
2891 JDWP::EventLocation exception_catch_location;
2892 SetEventLocation(&exception_catch_location, catch_method, catch_dex_pc);
Elliott Hughes4740cdf2011-12-07 14:07:12 -08002893
Sebastien Hertz6995c602014-09-09 12:10:13 +02002894 gJdwpState->PostException(&exception_throw_location, exception_object, &exception_catch_location,
2895 throw_location.GetThis());
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002896}
2897
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002898void Dbg::PostClassPrepare(mirror::Class* c) {
Elliott Hughesc0f09332012-03-26 13:27:06 -07002899 if (!IsDebuggerActive()) {
Elliott Hughes4740cdf2011-12-07 14:07:12 -08002900 return;
2901 }
Sebastien Hertz6995c602014-09-09 12:10:13 +02002902 gJdwpState->PostClassPrepare(c);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002903}
2904
Ian Rogers62d6c772013-02-27 08:32:07 -08002905void Dbg::UpdateDebugger(Thread* thread, mirror::Object* this_object,
Sebastien Hertz8379b222014-02-24 17:38:15 +01002906 mirror::ArtMethod* m, uint32_t dex_pc,
2907 int event_flags, const JValue* return_value) {
Ian Rogers62d6c772013-02-27 08:32:07 -08002908 if (!IsDebuggerActive() || dex_pc == static_cast<uint32_t>(-2) /* fake method exit */) {
Elliott Hughes2aa2e392012-02-17 17:15:43 -08002909 return;
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08002910 }
2911
Elliott Hughes86964332012-02-15 19:37:42 -08002912 if (IsBreakpoint(m, dex_pc)) {
2913 event_flags |= kBreakpoint;
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08002914 }
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08002915
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01002916 // If the debugger is single-stepping one of our threads, check to
2917 // see if we're that thread and we've reached a step point.
2918 const SingleStepControl* single_step_control = thread->GetSingleStepControl();
Sebastien Hertz597c4f02015-01-26 17:37:14 +01002919 if (single_step_control != nullptr) {
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01002920 CHECK(!m->IsNative());
Sebastien Hertz597c4f02015-01-26 17:37:14 +01002921 if (single_step_control->GetStepDepth() == JDWP::SD_INTO) {
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01002922 // Step into method calls. We break when the line number
2923 // or method pointer changes. If we're in SS_MIN mode, we
2924 // always stop.
Sebastien Hertz597c4f02015-01-26 17:37:14 +01002925 if (single_step_control->GetMethod() != m) {
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01002926 event_flags |= kSingleStep;
2927 VLOG(jdwp) << "SS new method";
Sebastien Hertz597c4f02015-01-26 17:37:14 +01002928 } else if (single_step_control->GetStepSize() == JDWP::SS_MIN) {
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01002929 event_flags |= kSingleStep;
2930 VLOG(jdwp) << "SS new instruction";
Sebastien Hertzbb43b432014-04-14 11:59:08 +02002931 } else if (single_step_control->ContainsDexPc(dex_pc)) {
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01002932 event_flags |= kSingleStep;
2933 VLOG(jdwp) << "SS new line";
2934 }
Sebastien Hertz597c4f02015-01-26 17:37:14 +01002935 } else if (single_step_control->GetStepDepth() == JDWP::SD_OVER) {
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01002936 // Step over method calls. We break when the line number is
2937 // different and the frame depth is <= the original frame
2938 // depth. (We can't just compare on the method, because we
2939 // might get unrolled past it by an exception, and it's tricky
2940 // to identify recursion.)
2941
2942 int stack_depth = GetStackDepth(thread);
2943
Sebastien Hertz597c4f02015-01-26 17:37:14 +01002944 if (stack_depth < single_step_control->GetStackDepth()) {
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01002945 // Popped up one or more frames, always trigger.
2946 event_flags |= kSingleStep;
2947 VLOG(jdwp) << "SS method pop";
Sebastien Hertz597c4f02015-01-26 17:37:14 +01002948 } else if (stack_depth == single_step_control->GetStackDepth()) {
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01002949 // Same depth, see if we moved.
Sebastien Hertz597c4f02015-01-26 17:37:14 +01002950 if (single_step_control->GetStepSize() == JDWP::SS_MIN) {
Elliott Hughes86964332012-02-15 19:37:42 -08002951 event_flags |= kSingleStep;
2952 VLOG(jdwp) << "SS new instruction";
Sebastien Hertzbb43b432014-04-14 11:59:08 +02002953 } else if (single_step_control->ContainsDexPc(dex_pc)) {
Elliott Hughes2435a572012-02-17 16:07:41 -08002954 event_flags |= kSingleStep;
2955 VLOG(jdwp) << "SS new line";
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08002956 }
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01002957 }
2958 } else {
Sebastien Hertz597c4f02015-01-26 17:37:14 +01002959 CHECK_EQ(single_step_control->GetStepDepth(), JDWP::SD_OUT);
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01002960 // Return from the current method. We break when the frame
2961 // depth pops up.
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08002962
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01002963 // This differs from the "method exit" break in that it stops
2964 // with the PC at the next instruction in the returned-to
2965 // function, rather than the end of the returning function.
Elliott Hughes86964332012-02-15 19:37:42 -08002966
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01002967 int stack_depth = GetStackDepth(thread);
Sebastien Hertz597c4f02015-01-26 17:37:14 +01002968 if (stack_depth < single_step_control->GetStackDepth()) {
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01002969 event_flags |= kSingleStep;
2970 VLOG(jdwp) << "SS method pop";
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08002971 }
2972 }
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08002973 }
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08002974
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08002975 // If there's something interesting going on, see if it matches one
2976 // of the debugger filters.
2977 if (event_flags != 0) {
Sebastien Hertz8379b222014-02-24 17:38:15 +01002978 Dbg::PostLocationEvent(m, dex_pc, this_object, event_flags, return_value);
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08002979 }
2980}
2981
Sebastien Hertz42cd43f2014-05-13 14:15:41 +02002982size_t* Dbg::GetReferenceCounterForEvent(uint32_t instrumentation_event) {
2983 switch (instrumentation_event) {
2984 case instrumentation::Instrumentation::kMethodEntered:
2985 return &method_enter_event_ref_count_;
2986 case instrumentation::Instrumentation::kMethodExited:
2987 return &method_exit_event_ref_count_;
2988 case instrumentation::Instrumentation::kDexPcMoved:
2989 return &dex_pc_change_event_ref_count_;
2990 case instrumentation::Instrumentation::kFieldRead:
2991 return &field_read_event_ref_count_;
2992 case instrumentation::Instrumentation::kFieldWritten:
2993 return &field_write_event_ref_count_;
2994 case instrumentation::Instrumentation::kExceptionCaught:
2995 return &exception_catch_event_ref_count_;
2996 default:
2997 return nullptr;
2998 }
2999}
3000
Sebastien Hertz4d25df32014-03-21 17:44:46 +01003001// Process request while all mutator threads are suspended.
3002void Dbg::ProcessDeoptimizationRequest(const DeoptimizationRequest& request) {
Sebastien Hertz138dbfc2013-12-04 18:15:25 +01003003 instrumentation::Instrumentation* instrumentation = Runtime::Current()->GetInstrumentation();
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003004 switch (request.GetKind()) {
Sebastien Hertz4d25df32014-03-21 17:44:46 +01003005 case DeoptimizationRequest::kNothing:
3006 LOG(WARNING) << "Ignoring empty deoptimization request.";
3007 break;
Sebastien Hertz42cd43f2014-05-13 14:15:41 +02003008 case DeoptimizationRequest::kRegisterForEvent:
3009 VLOG(jdwp) << StringPrintf("Add debugger as listener for instrumentation event 0x%x",
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003010 request.InstrumentationEvent());
3011 instrumentation->AddListener(&gDebugInstrumentationListener, request.InstrumentationEvent());
3012 instrumentation_events_ |= request.InstrumentationEvent();
Sebastien Hertz42cd43f2014-05-13 14:15:41 +02003013 break;
3014 case DeoptimizationRequest::kUnregisterForEvent:
3015 VLOG(jdwp) << StringPrintf("Remove debugger as listener for instrumentation event 0x%x",
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003016 request.InstrumentationEvent());
Sebastien Hertz42cd43f2014-05-13 14:15:41 +02003017 instrumentation->RemoveListener(&gDebugInstrumentationListener,
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003018 request.InstrumentationEvent());
3019 instrumentation_events_ &= ~request.InstrumentationEvent();
Sebastien Hertz42cd43f2014-05-13 14:15:41 +02003020 break;
Sebastien Hertz4d25df32014-03-21 17:44:46 +01003021 case DeoptimizationRequest::kFullDeoptimization:
Sebastien Hertz7ec2f1c2014-03-27 20:06:47 +01003022 VLOG(jdwp) << "Deoptimize the world ...";
Sebastien Hertz4d25df32014-03-21 17:44:46 +01003023 instrumentation->DeoptimizeEverything();
Sebastien Hertz7ec2f1c2014-03-27 20:06:47 +01003024 VLOG(jdwp) << "Deoptimize the world DONE";
Sebastien Hertz4d25df32014-03-21 17:44:46 +01003025 break;
3026 case DeoptimizationRequest::kFullUndeoptimization:
Sebastien Hertz7ec2f1c2014-03-27 20:06:47 +01003027 VLOG(jdwp) << "Undeoptimize the world ...";
Sebastien Hertz4d25df32014-03-21 17:44:46 +01003028 instrumentation->UndeoptimizeEverything();
Sebastien Hertz7ec2f1c2014-03-27 20:06:47 +01003029 VLOG(jdwp) << "Undeoptimize the world DONE";
Sebastien Hertz4d25df32014-03-21 17:44:46 +01003030 break;
3031 case DeoptimizationRequest::kSelectiveDeoptimization:
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003032 VLOG(jdwp) << "Deoptimize method " << PrettyMethod(request.Method()) << " ...";
3033 instrumentation->Deoptimize(request.Method());
3034 VLOG(jdwp) << "Deoptimize method " << PrettyMethod(request.Method()) << " DONE";
Sebastien Hertz4d25df32014-03-21 17:44:46 +01003035 break;
3036 case DeoptimizationRequest::kSelectiveUndeoptimization:
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003037 VLOG(jdwp) << "Undeoptimize method " << PrettyMethod(request.Method()) << " ...";
3038 instrumentation->Undeoptimize(request.Method());
3039 VLOG(jdwp) << "Undeoptimize method " << PrettyMethod(request.Method()) << " DONE";
Sebastien Hertz4d25df32014-03-21 17:44:46 +01003040 break;
3041 default:
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003042 LOG(FATAL) << "Unsupported deoptimization request kind " << request.GetKind();
Sebastien Hertz4d25df32014-03-21 17:44:46 +01003043 break;
Sebastien Hertz138dbfc2013-12-04 18:15:25 +01003044 }
Sebastien Hertz138dbfc2013-12-04 18:15:25 +01003045}
3046
Sebastien Hertz7ec2f1c2014-03-27 20:06:47 +01003047void Dbg::DelayFullUndeoptimization() {
Sebastien Hertzf3928792014-11-17 19:00:37 +01003048 if (RequiresDeoptimization()) {
3049 MutexLock mu(Thread::Current(), *Locks::deoptimization_lock_);
3050 ++delayed_full_undeoptimization_count_;
3051 DCHECK_LE(delayed_full_undeoptimization_count_, full_deoptimization_event_count_);
3052 }
Sebastien Hertz7ec2f1c2014-03-27 20:06:47 +01003053}
3054
3055void Dbg::ProcessDelayedFullUndeoptimizations() {
3056 // TODO: avoid taking the lock twice (once here and once in ManageDeoptimization).
3057 {
Brian Carlstrom306db812014-09-05 13:01:41 -07003058 MutexLock mu(Thread::Current(), *Locks::deoptimization_lock_);
Sebastien Hertz7ec2f1c2014-03-27 20:06:47 +01003059 while (delayed_full_undeoptimization_count_ > 0) {
3060 DeoptimizationRequest req;
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003061 req.SetKind(DeoptimizationRequest::kFullUndeoptimization);
3062 req.SetMethod(nullptr);
Sebastien Hertz7ec2f1c2014-03-27 20:06:47 +01003063 RequestDeoptimizationLocked(req);
3064 --delayed_full_undeoptimization_count_;
3065 }
3066 }
3067 ManageDeoptimization();
3068}
3069
Sebastien Hertz4d25df32014-03-21 17:44:46 +01003070void Dbg::RequestDeoptimization(const DeoptimizationRequest& req) {
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003071 if (req.GetKind() == DeoptimizationRequest::kNothing) {
Sebastien Hertz4d25df32014-03-21 17:44:46 +01003072 // Nothing to do.
3073 return;
3074 }
Brian Carlstrom306db812014-09-05 13:01:41 -07003075 MutexLock mu(Thread::Current(), *Locks::deoptimization_lock_);
Sebastien Hertz7ec2f1c2014-03-27 20:06:47 +01003076 RequestDeoptimizationLocked(req);
3077}
3078
3079void Dbg::RequestDeoptimizationLocked(const DeoptimizationRequest& req) {
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003080 switch (req.GetKind()) {
Sebastien Hertz42cd43f2014-05-13 14:15:41 +02003081 case DeoptimizationRequest::kRegisterForEvent: {
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003082 DCHECK_NE(req.InstrumentationEvent(), 0u);
3083 size_t* counter = GetReferenceCounterForEvent(req.InstrumentationEvent());
Sebastien Hertz42cd43f2014-05-13 14:15:41 +02003084 CHECK(counter != nullptr) << StringPrintf("No counter for instrumentation event 0x%x",
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003085 req.InstrumentationEvent());
Sebastien Hertz42cd43f2014-05-13 14:15:41 +02003086 if (*counter == 0) {
Sebastien Hertz7d2ae432014-05-15 11:26:34 +02003087 VLOG(jdwp) << StringPrintf("Queue request #%zd to start listening to instrumentation event 0x%x",
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003088 deoptimization_requests_.size(), req.InstrumentationEvent());
Sebastien Hertz42cd43f2014-05-13 14:15:41 +02003089 deoptimization_requests_.push_back(req);
3090 }
3091 *counter = *counter + 1;
3092 break;
3093 }
3094 case DeoptimizationRequest::kUnregisterForEvent: {
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003095 DCHECK_NE(req.InstrumentationEvent(), 0u);
3096 size_t* counter = GetReferenceCounterForEvent(req.InstrumentationEvent());
Sebastien Hertz42cd43f2014-05-13 14:15:41 +02003097 CHECK(counter != nullptr) << StringPrintf("No counter for instrumentation event 0x%x",
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003098 req.InstrumentationEvent());
Sebastien Hertz42cd43f2014-05-13 14:15:41 +02003099 *counter = *counter - 1;
3100 if (*counter == 0) {
Sebastien Hertz7d2ae432014-05-15 11:26:34 +02003101 VLOG(jdwp) << StringPrintf("Queue request #%zd to stop listening to instrumentation event 0x%x",
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003102 deoptimization_requests_.size(), req.InstrumentationEvent());
Sebastien Hertz42cd43f2014-05-13 14:15:41 +02003103 deoptimization_requests_.push_back(req);
3104 }
3105 break;
3106 }
Sebastien Hertz4d25df32014-03-21 17:44:46 +01003107 case DeoptimizationRequest::kFullDeoptimization: {
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003108 DCHECK(req.Method() == nullptr);
Sebastien Hertz4d25df32014-03-21 17:44:46 +01003109 if (full_deoptimization_event_count_ == 0) {
Sebastien Hertz7ec2f1c2014-03-27 20:06:47 +01003110 VLOG(jdwp) << "Queue request #" << deoptimization_requests_.size()
3111 << " for full deoptimization";
Sebastien Hertz4d25df32014-03-21 17:44:46 +01003112 deoptimization_requests_.push_back(req);
3113 }
3114 ++full_deoptimization_event_count_;
3115 break;
3116 }
3117 case DeoptimizationRequest::kFullUndeoptimization: {
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003118 DCHECK(req.Method() == nullptr);
Sebastien Hertze713d932014-05-15 10:48:53 +02003119 DCHECK_GT(full_deoptimization_event_count_, 0U);
Sebastien Hertz4d25df32014-03-21 17:44:46 +01003120 --full_deoptimization_event_count_;
3121 if (full_deoptimization_event_count_ == 0) {
Sebastien Hertz7ec2f1c2014-03-27 20:06:47 +01003122 VLOG(jdwp) << "Queue request #" << deoptimization_requests_.size()
3123 << " for full undeoptimization";
Sebastien Hertz4d25df32014-03-21 17:44:46 +01003124 deoptimization_requests_.push_back(req);
3125 }
3126 break;
3127 }
3128 case DeoptimizationRequest::kSelectiveDeoptimization: {
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003129 DCHECK(req.Method() != nullptr);
Sebastien Hertz7ec2f1c2014-03-27 20:06:47 +01003130 VLOG(jdwp) << "Queue request #" << deoptimization_requests_.size()
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003131 << " for deoptimization of " << PrettyMethod(req.Method());
Sebastien Hertz4d25df32014-03-21 17:44:46 +01003132 deoptimization_requests_.push_back(req);
3133 break;
3134 }
3135 case DeoptimizationRequest::kSelectiveUndeoptimization: {
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003136 DCHECK(req.Method() != nullptr);
Sebastien Hertz7ec2f1c2014-03-27 20:06:47 +01003137 VLOG(jdwp) << "Queue request #" << deoptimization_requests_.size()
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003138 << " for undeoptimization of " << PrettyMethod(req.Method());
Sebastien Hertz4d25df32014-03-21 17:44:46 +01003139 deoptimization_requests_.push_back(req);
3140 break;
3141 }
3142 default: {
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003143 LOG(FATAL) << "Unknown deoptimization request kind " << req.GetKind();
Sebastien Hertz4d25df32014-03-21 17:44:46 +01003144 break;
3145 }
3146 }
3147}
3148
Sebastien Hertz138dbfc2013-12-04 18:15:25 +01003149void Dbg::ManageDeoptimization() {
3150 Thread* const self = Thread::Current();
3151 {
3152 // Avoid suspend/resume if there is no pending request.
Brian Carlstrom306db812014-09-05 13:01:41 -07003153 MutexLock mu(self, *Locks::deoptimization_lock_);
Sebastien Hertz4d25df32014-03-21 17:44:46 +01003154 if (deoptimization_requests_.empty()) {
Sebastien Hertz138dbfc2013-12-04 18:15:25 +01003155 return;
3156 }
3157 }
3158 CHECK_EQ(self->GetState(), kRunnable);
3159 self->TransitionFromRunnableToSuspended(kWaitingForDeoptimization);
3160 // We need to suspend mutator threads first.
3161 Runtime* const runtime = Runtime::Current();
3162 runtime->GetThreadList()->SuspendAll();
3163 const ThreadState old_state = self->SetStateUnsafe(kRunnable);
Sebastien Hertz4d25df32014-03-21 17:44:46 +01003164 {
Brian Carlstrom306db812014-09-05 13:01:41 -07003165 MutexLock mu(self, *Locks::deoptimization_lock_);
Sebastien Hertz7ec2f1c2014-03-27 20:06:47 +01003166 size_t req_index = 0;
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003167 for (DeoptimizationRequest& request : deoptimization_requests_) {
Sebastien Hertz7ec2f1c2014-03-27 20:06:47 +01003168 VLOG(jdwp) << "Process deoptimization request #" << req_index++;
Sebastien Hertz4d25df32014-03-21 17:44:46 +01003169 ProcessDeoptimizationRequest(request);
3170 }
3171 deoptimization_requests_.clear();
3172 }
Sebastien Hertz138dbfc2013-12-04 18:15:25 +01003173 CHECK_EQ(self->SetStateUnsafe(old_state), kRunnable);
3174 runtime->GetThreadList()->ResumeAll();
3175 self->TransitionFromSuspendedToRunnable();
3176}
3177
Sebastien Hertza76a6d42014-03-20 16:40:17 +01003178static bool IsMethodPossiblyInlined(Thread* self, mirror::ArtMethod* m)
3179 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07003180 const DexFile::CodeItem* code_item = m->GetCodeItem();
Sebastien Hertza76a6d42014-03-20 16:40:17 +01003181 if (code_item == nullptr) {
3182 // TODO We should not be asked to watch location in a native or abstract method so the code item
3183 // should never be null. We could just check we never encounter this case.
3184 return false;
Sebastien Hertz138dbfc2013-12-04 18:15:25 +01003185 }
Sebastien Hertz4d1e9ab2014-09-18 16:03:34 +02003186 // Note: method verifier may cause thread suspension.
3187 self->AssertThreadSuspensionIsAllowable();
Hiroshi Yamauchidc376172014-08-22 11:13:12 -07003188 StackHandleScope<3> hs(self);
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07003189 mirror::Class* declaring_class = m->GetDeclaringClass();
3190 Handle<mirror::DexCache> dex_cache(hs.NewHandle(declaring_class->GetDexCache()));
3191 Handle<mirror::ClassLoader> class_loader(hs.NewHandle(declaring_class->GetClassLoader()));
Hiroshi Yamauchidc376172014-08-22 11:13:12 -07003192 Handle<mirror::ArtMethod> method(hs.NewHandle(m));
Ian Rogers7b078e82014-09-10 14:44:24 -07003193 verifier::MethodVerifier verifier(self, dex_cache->GetDexFile(), dex_cache, class_loader,
Hiroshi Yamauchidc376172014-08-22 11:13:12 -07003194 &m->GetClassDef(), code_item, m->GetDexMethodIndex(), method,
Mathieu Chartier4306ef82014-12-19 18:41:47 -08003195 m->GetAccessFlags(), false, true, false, true);
Sebastien Hertza76a6d42014-03-20 16:40:17 +01003196 // Note: we don't need to verify the method.
3197 return InlineMethodAnalyser::AnalyseMethodCode(&verifier, nullptr);
3198}
Sebastien Hertz138dbfc2013-12-04 18:15:25 +01003199
Sebastien Hertza76a6d42014-03-20 16:40:17 +01003200static const Breakpoint* FindFirstBreakpointForMethod(mirror::ArtMethod* m)
Sebastien Hertzed2be172014-08-19 15:33:43 +02003201 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_, Locks::breakpoint_lock_) {
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003202 for (Breakpoint& breakpoint : gBreakpoints) {
3203 if (breakpoint.Method() == m) {
Sebastien Hertza76a6d42014-03-20 16:40:17 +01003204 return &breakpoint;
3205 }
3206 }
3207 return nullptr;
3208}
3209
3210// Sanity checks all existing breakpoints on the same method.
Sebastien Hertzf3928792014-11-17 19:00:37 +01003211static void SanityCheckExistingBreakpoints(mirror::ArtMethod* m,
3212 DeoptimizationRequest::Kind deoptimization_kind)
Sebastien Hertzed2be172014-08-19 15:33:43 +02003213 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_, Locks::breakpoint_lock_) {
Sebastien Hertz4d1e9ab2014-09-18 16:03:34 +02003214 for (const Breakpoint& breakpoint : gBreakpoints) {
Sebastien Hertzf3928792014-11-17 19:00:37 +01003215 if (breakpoint.Method() == m) {
3216 CHECK_EQ(deoptimization_kind, breakpoint.GetDeoptimizationKind());
3217 }
Sebastien Hertz4d1e9ab2014-09-18 16:03:34 +02003218 }
Sebastien Hertzf3928792014-11-17 19:00:37 +01003219 instrumentation::Instrumentation* instrumentation = Runtime::Current()->GetInstrumentation();
3220 if (deoptimization_kind == DeoptimizationRequest::kFullDeoptimization) {
Sebastien Hertz4d1e9ab2014-09-18 16:03:34 +02003221 // We should have deoptimized everything but not "selectively" deoptimized this method.
Sebastien Hertzf3928792014-11-17 19:00:37 +01003222 CHECK(instrumentation->AreAllMethodsDeoptimized());
3223 CHECK(!instrumentation->IsDeoptimized(m));
3224 } else if (deoptimization_kind == DeoptimizationRequest::kSelectiveDeoptimization) {
Sebastien Hertz4d1e9ab2014-09-18 16:03:34 +02003225 // We should have "selectively" deoptimized this method.
3226 // Note: while we have not deoptimized everything for this method, we may have done it for
3227 // another event.
Sebastien Hertzf3928792014-11-17 19:00:37 +01003228 CHECK(instrumentation->IsDeoptimized(m));
3229 } else {
3230 // This method does not require deoptimization.
3231 CHECK_EQ(deoptimization_kind, DeoptimizationRequest::kNothing);
3232 CHECK(!instrumentation->IsDeoptimized(m));
3233 }
3234}
3235
Sebastien Hertzabe93e02014-12-17 16:35:50 +01003236// Returns the deoptimization kind required to set a breakpoint in a method.
3237// If a breakpoint has already been set, we also return the first breakpoint
3238// through the given 'existing_brkpt' pointer.
Sebastien Hertzf3928792014-11-17 19:00:37 +01003239static DeoptimizationRequest::Kind GetRequiredDeoptimizationKind(Thread* self,
Sebastien Hertzabe93e02014-12-17 16:35:50 +01003240 mirror::ArtMethod* m,
3241 const Breakpoint** existing_brkpt)
Sebastien Hertzf3928792014-11-17 19:00:37 +01003242 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
3243 if (!Dbg::RequiresDeoptimization()) {
3244 // We already run in interpreter-only mode so we don't need to deoptimize anything.
3245 VLOG(jdwp) << "No need for deoptimization when fully running with interpreter for method "
3246 << PrettyMethod(m);
3247 return DeoptimizationRequest::kNothing;
3248 }
Sebastien Hertzabe93e02014-12-17 16:35:50 +01003249 const Breakpoint* first_breakpoint;
Sebastien Hertzf3928792014-11-17 19:00:37 +01003250 {
3251 ReaderMutexLock mu(self, *Locks::breakpoint_lock_);
Sebastien Hertzabe93e02014-12-17 16:35:50 +01003252 first_breakpoint = FindFirstBreakpointForMethod(m);
3253 *existing_brkpt = first_breakpoint;
Sebastien Hertzf3928792014-11-17 19:00:37 +01003254 }
Sebastien Hertzabe93e02014-12-17 16:35:50 +01003255
3256 if (first_breakpoint == nullptr) {
Sebastien Hertzf3928792014-11-17 19:00:37 +01003257 // There is no breakpoint on this method yet: we need to deoptimize. If this method may be
3258 // inlined, we deoptimize everything; otherwise we deoptimize only this method.
3259 // Note: IsMethodPossiblyInlined goes into the method verifier and may cause thread suspension.
3260 // Therefore we must not hold any lock when we call it.
3261 bool need_full_deoptimization = IsMethodPossiblyInlined(self, m);
3262 if (need_full_deoptimization) {
3263 VLOG(jdwp) << "Need full deoptimization because of possible inlining of method "
3264 << PrettyMethod(m);
3265 return DeoptimizationRequest::kFullDeoptimization;
3266 } else {
3267 // We don't need to deoptimize if the method has not been compiled.
3268 ClassLinker* const class_linker = Runtime::Current()->GetClassLinker();
3269 const bool is_compiled = class_linker->GetOatMethodQuickCodeFor(m) != nullptr;
3270 if (is_compiled) {
Sebastien Hertz6963e442014-11-26 22:11:27 +01003271 // If the method may be called through its direct code pointer (without loading
3272 // its updated entrypoint), we need full deoptimization to not miss the breakpoint.
3273 if (class_linker->MayBeCalledWithDirectCodePointer(m)) {
3274 VLOG(jdwp) << "Need full deoptimization because of possible direct code call "
3275 << "into image for compiled method " << PrettyMethod(m);
3276 return DeoptimizationRequest::kFullDeoptimization;
3277 } else {
3278 VLOG(jdwp) << "Need selective deoptimization for compiled method " << PrettyMethod(m);
3279 return DeoptimizationRequest::kSelectiveDeoptimization;
3280 }
Sebastien Hertzf3928792014-11-17 19:00:37 +01003281 } else {
3282 // Method is not compiled: we don't need to deoptimize.
3283 VLOG(jdwp) << "No need for deoptimization for non-compiled method " << PrettyMethod(m);
3284 return DeoptimizationRequest::kNothing;
3285 }
3286 }
3287 } else {
3288 // There is at least one breakpoint for this method: we don't need to deoptimize.
3289 // Let's check that all breakpoints are configured the same way for deoptimization.
3290 VLOG(jdwp) << "Breakpoint already set: no deoptimization is required";
Sebastien Hertzabe93e02014-12-17 16:35:50 +01003291 DeoptimizationRequest::Kind deoptimization_kind = first_breakpoint->GetDeoptimizationKind();
Sebastien Hertzf3928792014-11-17 19:00:37 +01003292 if (kIsDebugBuild) {
3293 ReaderMutexLock mu(self, *Locks::breakpoint_lock_);
3294 SanityCheckExistingBreakpoints(m, deoptimization_kind);
3295 }
3296 return DeoptimizationRequest::kNothing;
Sebastien Hertz138dbfc2013-12-04 18:15:25 +01003297 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -07003298}
3299
Sebastien Hertza76a6d42014-03-20 16:40:17 +01003300// Installs a breakpoint at the specified location. Also indicates through the deoptimization
3301// request if we need to deoptimize.
3302void Dbg::WatchLocation(const JDWP::JdwpLocation* location, DeoptimizationRequest* req) {
3303 Thread* const self = Thread::Current();
Brian Carlstromea46f952013-07-30 01:26:50 -07003304 mirror::ArtMethod* m = FromMethodId(location->method_id);
Sebastien Hertza76a6d42014-03-20 16:40:17 +01003305 DCHECK(m != nullptr) << "No method for method id " << location->method_id;
Sebastien Hertz138dbfc2013-12-04 18:15:25 +01003306
Sebastien Hertzabe93e02014-12-17 16:35:50 +01003307 const Breakpoint* existing_breakpoint = nullptr;
3308 const DeoptimizationRequest::Kind deoptimization_kind =
3309 GetRequiredDeoptimizationKind(self, m, &existing_breakpoint);
Sebastien Hertzf3928792014-11-17 19:00:37 +01003310 req->SetKind(deoptimization_kind);
3311 if (deoptimization_kind == DeoptimizationRequest::kSelectiveDeoptimization) {
3312 req->SetMethod(m);
Sebastien Hertza76a6d42014-03-20 16:40:17 +01003313 } else {
Sebastien Hertzf3928792014-11-17 19:00:37 +01003314 CHECK(deoptimization_kind == DeoptimizationRequest::kNothing ||
3315 deoptimization_kind == DeoptimizationRequest::kFullDeoptimization);
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003316 req->SetMethod(nullptr);
Sebastien Hertz138dbfc2013-12-04 18:15:25 +01003317 }
3318
Sebastien Hertz4d1e9ab2014-09-18 16:03:34 +02003319 {
3320 WriterMutexLock mu(self, *Locks::breakpoint_lock_);
Sebastien Hertzabe93e02014-12-17 16:35:50 +01003321 // If there is at least one existing breakpoint on the same method, the new breakpoint
3322 // must have the same deoptimization kind than the existing breakpoint(s).
3323 DeoptimizationRequest::Kind breakpoint_deoptimization_kind;
3324 if (existing_breakpoint != nullptr) {
3325 breakpoint_deoptimization_kind = existing_breakpoint->GetDeoptimizationKind();
3326 } else {
3327 breakpoint_deoptimization_kind = deoptimization_kind;
3328 }
3329 gBreakpoints.push_back(Breakpoint(m, location->dex_pc, breakpoint_deoptimization_kind));
Sebastien Hertz4d1e9ab2014-09-18 16:03:34 +02003330 VLOG(jdwp) << "Set breakpoint #" << (gBreakpoints.size() - 1) << ": "
3331 << gBreakpoints[gBreakpoints.size() - 1];
3332 }
Sebastien Hertza76a6d42014-03-20 16:40:17 +01003333}
3334
3335// Uninstalls a breakpoint at the specified location. Also indicates through the deoptimization
3336// request if we need to undeoptimize.
3337void Dbg::UnwatchLocation(const JDWP::JdwpLocation* location, DeoptimizationRequest* req) {
Sebastien Hertzed2be172014-08-19 15:33:43 +02003338 WriterMutexLock mu(Thread::Current(), *Locks::breakpoint_lock_);
Sebastien Hertza76a6d42014-03-20 16:40:17 +01003339 mirror::ArtMethod* m = FromMethodId(location->method_id);
3340 DCHECK(m != nullptr) << "No method for method id " << location->method_id;
Sebastien Hertzf3928792014-11-17 19:00:37 +01003341 DeoptimizationRequest::Kind deoptimization_kind = DeoptimizationRequest::kNothing;
Sebastien Hertza76a6d42014-03-20 16:40:17 +01003342 for (size_t i = 0, e = gBreakpoints.size(); i < e; ++i) {
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003343 if (gBreakpoints[i].DexPc() == location->dex_pc && gBreakpoints[i].Method() == m) {
Sebastien Hertza76a6d42014-03-20 16:40:17 +01003344 VLOG(jdwp) << "Removed breakpoint #" << i << ": " << gBreakpoints[i];
Sebastien Hertzf3928792014-11-17 19:00:37 +01003345 deoptimization_kind = gBreakpoints[i].GetDeoptimizationKind();
3346 DCHECK_EQ(deoptimization_kind == DeoptimizationRequest::kSelectiveDeoptimization,
3347 Runtime::Current()->GetInstrumentation()->IsDeoptimized(m));
Sebastien Hertza76a6d42014-03-20 16:40:17 +01003348 gBreakpoints.erase(gBreakpoints.begin() + i);
3349 break;
3350 }
3351 }
3352 const Breakpoint* const existing_breakpoint = FindFirstBreakpointForMethod(m);
3353 if (existing_breakpoint == nullptr) {
3354 // There is no more breakpoint on this method: we need to undeoptimize.
Sebastien Hertzf3928792014-11-17 19:00:37 +01003355 if (deoptimization_kind == DeoptimizationRequest::kFullDeoptimization) {
Sebastien Hertza76a6d42014-03-20 16:40:17 +01003356 // This method required full deoptimization: we need to undeoptimize everything.
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003357 req->SetKind(DeoptimizationRequest::kFullUndeoptimization);
3358 req->SetMethod(nullptr);
Sebastien Hertzf3928792014-11-17 19:00:37 +01003359 } else if (deoptimization_kind == DeoptimizationRequest::kSelectiveDeoptimization) {
Sebastien Hertza76a6d42014-03-20 16:40:17 +01003360 // This method required selective deoptimization: we need to undeoptimize only that method.
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003361 req->SetKind(DeoptimizationRequest::kSelectiveUndeoptimization);
3362 req->SetMethod(m);
Sebastien Hertzf3928792014-11-17 19:00:37 +01003363 } else {
3364 // This method had no need for deoptimization: do nothing.
3365 CHECK_EQ(deoptimization_kind, DeoptimizationRequest::kNothing);
3366 req->SetKind(DeoptimizationRequest::kNothing);
3367 req->SetMethod(nullptr);
Sebastien Hertza76a6d42014-03-20 16:40:17 +01003368 }
3369 } else {
3370 // There is at least one breakpoint for this method: we don't need to undeoptimize.
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003371 req->SetKind(DeoptimizationRequest::kNothing);
3372 req->SetMethod(nullptr);
Sebastien Hertz4d1e9ab2014-09-18 16:03:34 +02003373 if (kIsDebugBuild) {
Sebastien Hertzf3928792014-11-17 19:00:37 +01003374 SanityCheckExistingBreakpoints(m, deoptimization_kind);
Sebastien Hertz4d1e9ab2014-09-18 16:03:34 +02003375 }
Elliott Hughes86964332012-02-15 19:37:42 -08003376 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -07003377}
3378
Jeff Hao449db332013-04-12 18:30:52 -07003379// Scoped utility class to suspend a thread so that we may do tasks such as walk its stack. Doesn't
3380// cause suspension if the thread is the current thread.
3381class ScopedThreadSuspension {
3382 public:
Ian Rogers33e95662013-05-20 20:29:14 -07003383 ScopedThreadSuspension(Thread* self, JDWP::ObjectId thread_id)
Sebastien Hertz52d131d2014-03-13 16:17:40 +01003384 LOCKS_EXCLUDED(Locks::thread_list_lock_)
Ian Rogers33e95662013-05-20 20:29:14 -07003385 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) :
Ian Rogersf3d874c2014-07-17 18:52:42 -07003386 thread_(nullptr),
Jeff Hao449db332013-04-12 18:30:52 -07003387 error_(JDWP::ERR_NONE),
3388 self_suspend_(false),
Ian Rogers33e95662013-05-20 20:29:14 -07003389 other_suspend_(false) {
Jeff Hao449db332013-04-12 18:30:52 -07003390 ScopedObjectAccessUnchecked soa(self);
3391 {
3392 MutexLock mu(soa.Self(), *Locks::thread_list_lock_);
Ian Rogersc0542af2014-09-03 16:16:56 -07003393 thread_ = DecodeThread(soa, thread_id, &error_);
Jeff Hao449db332013-04-12 18:30:52 -07003394 }
3395 if (error_ == JDWP::ERR_NONE) {
3396 if (thread_ == soa.Self()) {
3397 self_suspend_ = true;
3398 } else {
3399 soa.Self()->TransitionFromRunnableToSuspended(kWaitingForDebuggerSuspension);
Sebastien Hertz6995c602014-09-09 12:10:13 +02003400 jobject thread_peer = Dbg::GetObjectRegistry()->GetJObject(thread_id);
Jeff Hao449db332013-04-12 18:30:52 -07003401 bool timed_out;
Ian Rogers4ad5cd32014-11-11 23:08:07 -08003402 ThreadList* thread_list = Runtime::Current()->GetThreadList();
3403 Thread* suspended_thread = thread_list->SuspendThreadByPeer(thread_peer, true, true,
3404 &timed_out);
Jeff Hao449db332013-04-12 18:30:52 -07003405 CHECK_EQ(soa.Self()->TransitionFromSuspendedToRunnable(), kWaitingForDebuggerSuspension);
Ian Rogersf3d874c2014-07-17 18:52:42 -07003406 if (suspended_thread == nullptr) {
Jeff Hao449db332013-04-12 18:30:52 -07003407 // Thread terminated from under us while suspending.
3408 error_ = JDWP::ERR_INVALID_THREAD;
3409 } else {
3410 CHECK_EQ(suspended_thread, thread_);
3411 other_suspend_ = true;
3412 }
3413 }
3414 }
Elliott Hughes2435a572012-02-17 16:07:41 -08003415 }
Elliott Hughes86964332012-02-15 19:37:42 -08003416
Jeff Hao449db332013-04-12 18:30:52 -07003417 Thread* GetThread() const {
3418 return thread_;
3419 }
3420
3421 JDWP::JdwpError GetError() const {
3422 return error_;
3423 }
3424
3425 ~ScopedThreadSuspension() {
3426 if (other_suspend_) {
3427 Runtime::Current()->GetThreadList()->Resume(thread_, true);
3428 }
3429 }
3430
3431 private:
3432 Thread* thread_;
3433 JDWP::JdwpError error_;
3434 bool self_suspend_;
3435 bool other_suspend_;
3436};
3437
3438JDWP::JdwpError Dbg::ConfigureStep(JDWP::ObjectId thread_id, JDWP::JdwpStepSize step_size,
3439 JDWP::JdwpStepDepth step_depth) {
3440 Thread* self = Thread::Current();
3441 ScopedThreadSuspension sts(self, thread_id);
3442 if (sts.GetError() != JDWP::ERR_NONE) {
3443 return sts.GetError();
3444 }
3445
Sebastien Hertz597c4f02015-01-26 17:37:14 +01003446 // Work out what ArtMethod* we're in, the current line number, and how deep the stack currently
Elliott Hughes2435a572012-02-17 16:07:41 -08003447 // is for step-out.
Ian Rogers0399dde2012-06-06 17:09:28 -07003448 struct SingleStepStackVisitor : public StackVisitor {
Sebastien Hertz597c4f02015-01-26 17:37:14 +01003449 explicit SingleStepStackVisitor(Thread* thread) SHARED_LOCKS_REQUIRED(Locks::mutator_lock_)
3450 : StackVisitor(thread, nullptr), stack_depth(0), method(nullptr), line_number(-1) {
Elliott Hughes86964332012-02-15 19:37:42 -08003451 }
Ian Rogersca190662012-06-26 15:45:57 -07003452
Ian Rogers00f7d0e2012-07-19 15:28:27 -07003453 // TODO: Enable annotalysis. We know lock is held in constructor, but abstraction confuses
3454 // annotalysis.
3455 bool VisitFrame() NO_THREAD_SAFETY_ANALYSIS {
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01003456 mirror::ArtMethod* m = GetMethod();
Ian Rogers0399dde2012-06-06 17:09:28 -07003457 if (!m->IsRuntimeMethod()) {
Sebastien Hertz597c4f02015-01-26 17:37:14 +01003458 ++stack_depth;
3459 if (method == nullptr) {
Ian Rogersef7d42f2014-01-06 12:55:46 -08003460 mirror::DexCache* dex_cache = m->GetDeclaringClass()->GetDexCache();
Sebastien Hertz597c4f02015-01-26 17:37:14 +01003461 method = m;
Ian Rogersc0542af2014-09-03 16:16:56 -07003462 if (dex_cache != nullptr) {
Ian Rogers4445a7e2012-10-05 17:19:13 -07003463 const DexFile& dex_file = *dex_cache->GetDexFile();
Sebastien Hertz597c4f02015-01-26 17:37:14 +01003464 line_number = dex_file.GetLineNumFromPC(m, GetDexPc());
Elliott Hughes2435a572012-02-17 16:07:41 -08003465 }
Elliott Hughes86964332012-02-15 19:37:42 -08003466 }
3467 }
Elliott Hughes530fa002012-03-12 11:44:49 -07003468 return true;
Elliott Hughes86964332012-02-15 19:37:42 -08003469 }
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01003470
Sebastien Hertz597c4f02015-01-26 17:37:14 +01003471 int stack_depth;
3472 mirror::ArtMethod* method;
3473 int32_t line_number;
Elliott Hughes86964332012-02-15 19:37:42 -08003474 };
Jeff Hao449db332013-04-12 18:30:52 -07003475
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01003476 Thread* const thread = sts.GetThread();
Sebastien Hertz597c4f02015-01-26 17:37:14 +01003477 SingleStepStackVisitor visitor(thread);
Ian Rogers0399dde2012-06-06 17:09:28 -07003478 visitor.WalkStack();
Elliott Hughes86964332012-02-15 19:37:42 -08003479
Elliott Hughes2435a572012-02-17 16:07:41 -08003480 // Find the dex_pc values that correspond to the current line, for line-based single-stepping.
Elliott Hughes2435a572012-02-17 16:07:41 -08003481 struct DebugCallbackContext {
Sebastien Hertz597c4f02015-01-26 17:37:14 +01003482 explicit DebugCallbackContext(SingleStepControl* single_step_control_cb,
3483 int32_t line_number_cb, const DexFile::CodeItem* code_item)
Andreas Gampe277ccbd2014-11-03 21:36:10 -08003484 : single_step_control_(single_step_control_cb), line_number_(line_number_cb),
3485 code_item_(code_item), last_pc_valid(false), last_pc(0) {
Elliott Hughes2435a572012-02-17 16:07:41 -08003486 }
3487
Andreas Gampe277ccbd2014-11-03 21:36:10 -08003488 static bool Callback(void* raw_context, uint32_t address, uint32_t line_number_cb) {
Elliott Hughes2435a572012-02-17 16:07:41 -08003489 DebugCallbackContext* context = reinterpret_cast<DebugCallbackContext*>(raw_context);
Andreas Gampe277ccbd2014-11-03 21:36:10 -08003490 if (static_cast<int32_t>(line_number_cb) == context->line_number_) {
Elliott Hughes2435a572012-02-17 16:07:41 -08003491 if (!context->last_pc_valid) {
3492 // Everything from this address until the next line change is ours.
3493 context->last_pc = address;
3494 context->last_pc_valid = true;
3495 }
3496 // Otherwise, if we're already in a valid range for this line,
3497 // just keep going (shouldn't really happen)...
Brian Carlstrom7934ac22013-07-26 10:54:15 -07003498 } else if (context->last_pc_valid) { // and the line number is new
Elliott Hughes2435a572012-02-17 16:07:41 -08003499 // Add everything from the last entry up until here to the set
3500 for (uint32_t dex_pc = context->last_pc; dex_pc < address; ++dex_pc) {
Sebastien Hertz597c4f02015-01-26 17:37:14 +01003501 context->single_step_control_->AddDexPc(dex_pc);
Elliott Hughes2435a572012-02-17 16:07:41 -08003502 }
3503 context->last_pc_valid = false;
3504 }
Brian Carlstrom7934ac22013-07-26 10:54:15 -07003505 return false; // There may be multiple entries for any given line.
Elliott Hughes2435a572012-02-17 16:07:41 -08003506 }
3507
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01003508 ~DebugCallbackContext() {
Elliott Hughes2435a572012-02-17 16:07:41 -08003509 // If the line number was the last in the position table...
3510 if (last_pc_valid) {
Sebastien Hertzbb43b432014-04-14 11:59:08 +02003511 size_t end = code_item_->insns_size_in_code_units_;
Elliott Hughes2435a572012-02-17 16:07:41 -08003512 for (uint32_t dex_pc = last_pc; dex_pc < end; ++dex_pc) {
Sebastien Hertz597c4f02015-01-26 17:37:14 +01003513 single_step_control_->AddDexPc(dex_pc);
Elliott Hughes2435a572012-02-17 16:07:41 -08003514 }
3515 }
3516 }
3517
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01003518 SingleStepControl* const single_step_control_;
3519 const int32_t line_number_;
Sebastien Hertzbb43b432014-04-14 11:59:08 +02003520 const DexFile::CodeItem* const code_item_;
Elliott Hughes2435a572012-02-17 16:07:41 -08003521 bool last_pc_valid;
3522 uint32_t last_pc;
3523 };
Sebastien Hertz597c4f02015-01-26 17:37:14 +01003524
3525 // Allocate single step.
3526 SingleStepControl* single_step_control = new SingleStepControl(step_size, step_depth,
3527 visitor.stack_depth,
3528 visitor.method);
3529 CHECK(single_step_control != nullptr) << "Failed to allocate SingleStepControl";
3530 mirror::ArtMethod* m = single_step_control->GetMethod();
3531 const int32_t line_number = visitor.line_number;
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01003532 if (!m->IsNative()) {
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07003533 const DexFile::CodeItem* const code_item = m->GetCodeItem();
Sebastien Hertzbb43b432014-04-14 11:59:08 +02003534 DebugCallbackContext context(single_step_control, line_number, code_item);
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07003535 m->GetDexFile()->DecodeDebugInfo(code_item, m->IsStatic(), m->GetDexMethodIndex(),
Ian Rogersc0542af2014-09-03 16:16:56 -07003536 DebugCallbackContext::Callback, nullptr, &context);
Elliott Hughes3e2e1a22012-02-21 11:33:41 -08003537 }
Elliott Hughes2435a572012-02-17 16:07:41 -08003538
Sebastien Hertz597c4f02015-01-26 17:37:14 +01003539 // Activate single-step in the thread.
3540 thread->ActivateSingleStepControl(single_step_control);
Elliott Hughes86964332012-02-15 19:37:42 -08003541
Elliott Hughes2435a572012-02-17 16:07:41 -08003542 if (VLOG_IS_ON(jdwp)) {
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01003543 VLOG(jdwp) << "Single-step thread: " << *thread;
Sebastien Hertz597c4f02015-01-26 17:37:14 +01003544 VLOG(jdwp) << "Single-step step size: " << single_step_control->GetStepSize();
3545 VLOG(jdwp) << "Single-step step depth: " << single_step_control->GetStepDepth();
3546 VLOG(jdwp) << "Single-step current method: " << PrettyMethod(single_step_control->GetMethod());
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01003547 VLOG(jdwp) << "Single-step current line: " << line_number;
Sebastien Hertz597c4f02015-01-26 17:37:14 +01003548 VLOG(jdwp) << "Single-step current stack depth: " << single_step_control->GetStackDepth();
Elliott Hughes2435a572012-02-17 16:07:41 -08003549 VLOG(jdwp) << "Single-step dex_pc values:";
Sebastien Hertz597c4f02015-01-26 17:37:14 +01003550 for (uint32_t dex_pc : single_step_control->GetDexPcs()) {
Sebastien Hertzbb43b432014-04-14 11:59:08 +02003551 VLOG(jdwp) << StringPrintf(" %#x", dex_pc);
Elliott Hughes2435a572012-02-17 16:07:41 -08003552 }
3553 }
3554
3555 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07003556}
3557
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01003558void Dbg::UnconfigureStep(JDWP::ObjectId thread_id) {
3559 ScopedObjectAccessUnchecked soa(Thread::Current());
3560 MutexLock mu(soa.Self(), *Locks::thread_list_lock_);
Ian Rogersc0542af2014-09-03 16:16:56 -07003561 JDWP::JdwpError error;
3562 Thread* thread = DecodeThread(soa, thread_id, &error);
Sebastien Hertz87118ed2013-11-26 17:57:18 +01003563 if (error == JDWP::ERR_NONE) {
Sebastien Hertz597c4f02015-01-26 17:37:14 +01003564 thread->DeactivateSingleStepControl();
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01003565 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -07003566}
3567
Elliott Hughes45651fd2012-02-21 15:48:20 -08003568static char JdwpTagToShortyChar(JDWP::JdwpTag tag) {
3569 switch (tag) {
3570 default:
3571 LOG(FATAL) << "unknown JDWP tag: " << PrintableChar(tag);
Ian Rogersfc787ec2014-10-09 21:56:44 -07003572 UNREACHABLE();
Elliott Hughes45651fd2012-02-21 15:48:20 -08003573
3574 // Primitives.
3575 case JDWP::JT_BYTE: return 'B';
3576 case JDWP::JT_CHAR: return 'C';
3577 case JDWP::JT_FLOAT: return 'F';
3578 case JDWP::JT_DOUBLE: return 'D';
3579 case JDWP::JT_INT: return 'I';
3580 case JDWP::JT_LONG: return 'J';
3581 case JDWP::JT_SHORT: return 'S';
3582 case JDWP::JT_VOID: return 'V';
3583 case JDWP::JT_BOOLEAN: return 'Z';
3584
3585 // Reference types.
3586 case JDWP::JT_ARRAY:
3587 case JDWP::JT_OBJECT:
3588 case JDWP::JT_STRING:
3589 case JDWP::JT_THREAD:
3590 case JDWP::JT_THREAD_GROUP:
3591 case JDWP::JT_CLASS_LOADER:
3592 case JDWP::JT_CLASS_OBJECT:
3593 return 'L';
3594 }
3595}
3596
Elliott Hughes88d63092013-01-09 09:55:54 -08003597JDWP::JdwpError Dbg::InvokeMethod(JDWP::ObjectId thread_id, JDWP::ObjectId object_id,
3598 JDWP::RefTypeId class_id, JDWP::MethodId method_id,
Ian Rogers00f7d0e2012-07-19 15:28:27 -07003599 uint32_t arg_count, uint64_t* arg_values,
3600 JDWP::JdwpTag* arg_types, uint32_t options,
3601 JDWP::JdwpTag* pResultTag, uint64_t* pResultValue,
3602 JDWP::ObjectId* pExceptionId) {
Elliott Hughesd07986f2011-12-06 18:27:45 -08003603 ThreadList* thread_list = Runtime::Current()->GetThreadList();
3604
Ian Rogersc0542af2014-09-03 16:16:56 -07003605 Thread* targetThread = nullptr;
3606 DebugInvokeReq* req = nullptr;
Ian Rogers00f7d0e2012-07-19 15:28:27 -07003607 Thread* self = Thread::Current();
Elliott Hughesd07986f2011-12-06 18:27:45 -08003608 {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07003609 ScopedObjectAccessUnchecked soa(self);
Ian Rogers50b35e22012-10-04 10:09:15 -07003610 MutexLock mu(soa.Self(), *Locks::thread_list_lock_);
Ian Rogersc0542af2014-09-03 16:16:56 -07003611 JDWP::JdwpError error;
3612 targetThread = DecodeThread(soa, thread_id, &error);
Elliott Hughes221229c2013-01-08 18:17:50 -08003613 if (error != JDWP::ERR_NONE) {
3614 LOG(ERROR) << "InvokeMethod request for invalid thread id " << thread_id;
3615 return error;
Elliott Hughesd07986f2011-12-06 18:27:45 -08003616 }
3617 req = targetThread->GetInvokeReq();
3618 if (!req->ready) {
3619 LOG(ERROR) << "InvokeMethod request for thread not stopped by event: " << *targetThread;
3620 return JDWP::ERR_INVALID_THREAD;
3621 }
3622
3623 /*
3624 * We currently have a bug where we don't successfully resume the
3625 * target thread if the suspend count is too deep. We're expected to
3626 * require one "resume" for each "suspend", but when asked to execute
3627 * a method we have to resume fully and then re-suspend it back to the
3628 * same level. (The easiest way to cause this is to type "suspend"
3629 * multiple times in jdb.)
3630 *
3631 * It's unclear what this means when the event specifies "resume all"
3632 * and some threads are suspended more deeply than others. This is
3633 * a rare problem, so for now we just prevent it from hanging forever
3634 * by rejecting the method invocation request. Without this, we will
3635 * be stuck waiting on a suspended thread.
3636 */
Ian Rogers00f7d0e2012-07-19 15:28:27 -07003637 int suspend_count;
3638 {
Ian Rogers50b35e22012-10-04 10:09:15 -07003639 MutexLock mu2(soa.Self(), *Locks::thread_suspend_count_lock_);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07003640 suspend_count = targetThread->GetSuspendCount();
3641 }
Elliott Hughesd07986f2011-12-06 18:27:45 -08003642 if (suspend_count > 1) {
3643 LOG(ERROR) << *targetThread << " suspend count too deep for method invocation: " << suspend_count;
Brian Carlstrom7934ac22013-07-26 10:54:15 -07003644 return JDWP::ERR_THREAD_SUSPENDED; // Probably not expected here.
Elliott Hughesd07986f2011-12-06 18:27:45 -08003645 }
3646
Ian Rogersc0542af2014-09-03 16:16:56 -07003647 mirror::Object* receiver = gRegistry->Get<mirror::Object*>(object_id, &error);
3648 if (error != JDWP::ERR_NONE) {
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08003649 return JDWP::ERR_INVALID_OBJECT;
3650 }
Elliott Hughes45651fd2012-02-21 15:48:20 -08003651
Ian Rogersc0542af2014-09-03 16:16:56 -07003652 mirror::Object* thread = gRegistry->Get<mirror::Object*>(thread_id, &error);
3653 if (error != JDWP::ERR_NONE) {
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08003654 return JDWP::ERR_INVALID_OBJECT;
3655 }
Elliott Hughes45651fd2012-02-21 15:48:20 -08003656 // TODO: check that 'thread' is actually a java.lang.Thread!
3657
Ian Rogersc0542af2014-09-03 16:16:56 -07003658 mirror::Class* c = DecodeClass(class_id, &error);
3659 if (c == nullptr) {
3660 return error;
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08003661 }
Elliott Hughes45651fd2012-02-21 15:48:20 -08003662
Brian Carlstromea46f952013-07-30 01:26:50 -07003663 mirror::ArtMethod* m = FromMethodId(method_id);
Ian Rogersc0542af2014-09-03 16:16:56 -07003664 if (m->IsStatic() != (receiver == nullptr)) {
Elliott Hughes45651fd2012-02-21 15:48:20 -08003665 return JDWP::ERR_INVALID_METHODID;
3666 }
3667 if (m->IsStatic()) {
3668 if (m->GetDeclaringClass() != c) {
3669 return JDWP::ERR_INVALID_METHODID;
3670 }
3671 } else {
3672 if (!m->GetDeclaringClass()->IsAssignableFrom(c)) {
3673 return JDWP::ERR_INVALID_METHODID;
3674 }
3675 }
3676
3677 // Check the argument list matches the method.
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07003678 uint32_t shorty_len = 0;
3679 const char* shorty = m->GetShorty(&shorty_len);
3680 if (shorty_len - 1 != arg_count) {
Elliott Hughes45651fd2012-02-21 15:48:20 -08003681 return JDWP::ERR_ILLEGAL_ARGUMENT;
3682 }
Elliott Hughes09201632013-04-15 15:50:07 -07003683
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07003684 {
3685 StackHandleScope<3> hs(soa.Self());
Ian Rogersa0485602014-12-02 15:48:04 -08003686 HandleWrapper<mirror::ArtMethod> h_m(hs.NewHandleWrapper(&m));
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07003687 HandleWrapper<mirror::Object> h_obj(hs.NewHandleWrapper(&receiver));
3688 HandleWrapper<mirror::Class> h_klass(hs.NewHandleWrapper(&c));
3689 const DexFile::TypeList* types = m->GetParameterTypeList();
3690 for (size_t i = 0; i < arg_count; ++i) {
3691 if (shorty[i + 1] != JdwpTagToShortyChar(arg_types[i])) {
Elliott Hughes09201632013-04-15 15:50:07 -07003692 return JDWP::ERR_ILLEGAL_ARGUMENT;
3693 }
3694
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07003695 if (shorty[i + 1] == 'L') {
3696 // Did we really get an argument of an appropriate reference type?
Ian Rogersa0485602014-12-02 15:48:04 -08003697 mirror::Class* parameter_type =
3698 h_m->GetClassFromTypeIndex(types->GetTypeItem(i).type_idx_, true);
Ian Rogersc0542af2014-09-03 16:16:56 -07003699 mirror::Object* argument = gRegistry->Get<mirror::Object*>(arg_values[i], &error);
3700 if (error != JDWP::ERR_NONE) {
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07003701 return JDWP::ERR_INVALID_OBJECT;
3702 }
Ian Rogersc0542af2014-09-03 16:16:56 -07003703 if (argument != nullptr && !argument->InstanceOf(parameter_type)) {
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07003704 return JDWP::ERR_ILLEGAL_ARGUMENT;
3705 }
3706
3707 // Turn the on-the-wire ObjectId into a jobject.
3708 jvalue& v = reinterpret_cast<jvalue&>(arg_values[i]);
3709 v.l = gRegistry->GetJObject(arg_values[i]);
3710 }
Elliott Hughes09201632013-04-15 15:50:07 -07003711 }
Elliott Hughes45651fd2012-02-21 15:48:20 -08003712 }
3713
Sebastien Hertzd38667a2013-11-25 15:43:54 +01003714 req->receiver = receiver;
3715 req->thread = thread;
3716 req->klass = c;
3717 req->method = m;
3718 req->arg_count = arg_count;
3719 req->arg_values = arg_values;
3720 req->options = options;
3721 req->invoke_needed = true;
Elliott Hughesd07986f2011-12-06 18:27:45 -08003722 }
3723
3724 // The fact that we've released the thread list lock is a bit risky --- if the thread goes
3725 // away we're sitting high and dry -- but we must release this before the ResumeAllThreads
3726 // call, and it's unwise to hold it during WaitForSuspend.
3727
3728 {
3729 /*
3730 * We change our (JDWP thread) status, which should be THREAD_RUNNING,
Elliott Hughes81ff3182012-03-23 20:35:56 -07003731 * so we can suspend for a GC if the invoke request causes us to
Elliott Hughesd07986f2011-12-06 18:27:45 -08003732 * run out of memory. It's also a good idea to change it before locking
3733 * the invokeReq mutex, although that should never be held for long.
3734 */
Ian Rogers00f7d0e2012-07-19 15:28:27 -07003735 self->TransitionFromRunnableToSuspended(kWaitingForDebuggerSend);
Elliott Hughesd07986f2011-12-06 18:27:45 -08003736
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08003737 VLOG(jdwp) << " Transferring control to event thread";
Elliott Hughesd07986f2011-12-06 18:27:45 -08003738 {
Sebastien Hertzd38667a2013-11-25 15:43:54 +01003739 MutexLock mu(self, req->lock);
Elliott Hughesd07986f2011-12-06 18:27:45 -08003740
3741 if ((options & JDWP::INVOKE_SINGLE_THREADED) == 0) {
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08003742 VLOG(jdwp) << " Resuming all threads";
Ian Rogers00f7d0e2012-07-19 15:28:27 -07003743 thread_list->UndoDebuggerSuspensions();
Elliott Hughesd07986f2011-12-06 18:27:45 -08003744 } else {
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08003745 VLOG(jdwp) << " Resuming event thread only";
Elliott Hughesd07986f2011-12-06 18:27:45 -08003746 thread_list->Resume(targetThread, true);
3747 }
3748
3749 // Wait for the request to finish executing.
Sebastien Hertzd38667a2013-11-25 15:43:54 +01003750 while (req->invoke_needed) {
3751 req->cond.Wait(self);
Elliott Hughesd07986f2011-12-06 18:27:45 -08003752 }
3753 }
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08003754 VLOG(jdwp) << " Control has returned from event thread";
Elliott Hughesd07986f2011-12-06 18:27:45 -08003755
3756 /* wait for thread to re-suspend itself */
Brian Carlstromdf629502013-07-17 22:39:56 -07003757 SuspendThread(thread_id, false /* request_suspension */);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07003758 self->TransitionFromSuspendedToRunnable();
Elliott Hughesd07986f2011-12-06 18:27:45 -08003759 }
3760
3761 /*
3762 * Suspend the threads. We waited for the target thread to suspend
3763 * itself, so all we need to do is suspend the others.
3764 *
3765 * The suspendAllThreads() call will double-suspend the event thread,
3766 * so we want to resume the target thread once to keep the books straight.
3767 */
3768 if ((options & JDWP::INVOKE_SINGLE_THREADED) == 0) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07003769 self->TransitionFromRunnableToSuspended(kWaitingForDebuggerSuspension);
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08003770 VLOG(jdwp) << " Suspending all threads";
Ian Rogers00f7d0e2012-07-19 15:28:27 -07003771 thread_list->SuspendAllForDebugger();
3772 self->TransitionFromSuspendedToRunnable();
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08003773 VLOG(jdwp) << " Resuming event thread to balance the count";
Elliott Hughesd07986f2011-12-06 18:27:45 -08003774 thread_list->Resume(targetThread, true);
3775 }
3776
3777 // Copy the result.
3778 *pResultTag = req->result_tag;
3779 if (IsPrimitiveTag(req->result_tag)) {
Elliott Hughesf24d3ce2012-04-11 17:43:37 -07003780 *pResultValue = req->result_value.GetJ();
Elliott Hughesd07986f2011-12-06 18:27:45 -08003781 } else {
Elliott Hughesf24d3ce2012-04-11 17:43:37 -07003782 *pResultValue = gRegistry->Add(req->result_value.GetL());
Elliott Hughesd07986f2011-12-06 18:27:45 -08003783 }
3784 *pExceptionId = req->exception;
3785 return req->error;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07003786}
3787
3788void Dbg::ExecuteMethod(DebugInvokeReq* pReq) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07003789 ScopedObjectAccess soa(Thread::Current());
Elliott Hughesd07986f2011-12-06 18:27:45 -08003790
Elliott Hughes81ff3182012-03-23 20:35:56 -07003791 // We can be called while an exception is pending. We need
Elliott Hughesd07986f2011-12-06 18:27:45 -08003792 // to preserve that across the method invocation.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003793 StackHandleScope<4> hs(soa.Self());
3794 auto old_throw_this_object = hs.NewHandle<mirror::Object>(nullptr);
3795 auto old_throw_method = hs.NewHandle<mirror::ArtMethod>(nullptr);
3796 auto old_exception = hs.NewHandle<mirror::Throwable>(nullptr);
Ian Rogers62d6c772013-02-27 08:32:07 -08003797 uint32_t old_throw_dex_pc;
Sebastien Hertz9f102032014-05-23 08:59:42 +02003798 bool old_exception_report_flag;
Ian Rogers62d6c772013-02-27 08:32:07 -08003799 {
3800 ThrowLocation old_throw_location;
3801 mirror::Throwable* old_exception_obj = soa.Self()->GetException(&old_throw_location);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003802 old_throw_this_object.Assign(old_throw_location.GetThis());
3803 old_throw_method.Assign(old_throw_location.GetMethod());
3804 old_exception.Assign(old_exception_obj);
Ian Rogers62d6c772013-02-27 08:32:07 -08003805 old_throw_dex_pc = old_throw_location.GetDexPc();
Sebastien Hertz9f102032014-05-23 08:59:42 +02003806 old_exception_report_flag = soa.Self()->IsExceptionReportedToInstrumentation();
Ian Rogers62d6c772013-02-27 08:32:07 -08003807 soa.Self()->ClearException();
3808 }
Elliott Hughesd07986f2011-12-06 18:27:45 -08003809
3810 // Translate the method through the vtable, unless the debugger wants to suppress it.
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07003811 MutableHandle<mirror::ArtMethod> m(hs.NewHandle(pReq->method));
Ian Rogersc0542af2014-09-03 16:16:56 -07003812 if ((pReq->options & JDWP::INVOKE_NONVIRTUAL) == 0 && pReq->receiver != nullptr) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003813 mirror::ArtMethod* actual_method = pReq->klass->FindVirtualMethodForVirtualOrInterface(m.Get());
3814 if (actual_method != m.Get()) {
3815 VLOG(jdwp) << "ExecuteMethod translated " << PrettyMethod(m.Get()) << " to " << PrettyMethod(actual_method);
3816 m.Assign(actual_method);
Elliott Hughes45651fd2012-02-21 15:48:20 -08003817 }
Elliott Hughesd07986f2011-12-06 18:27:45 -08003818 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003819 VLOG(jdwp) << "ExecuteMethod " << PrettyMethod(m.Get())
Sebastien Hertzd38667a2013-11-25 15:43:54 +01003820 << " receiver=" << pReq->receiver
3821 << " arg_count=" << pReq->arg_count;
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003822 CHECK(m.Get() != nullptr);
Elliott Hughesd07986f2011-12-06 18:27:45 -08003823
3824 CHECK_EQ(sizeof(jvalue), sizeof(uint64_t));
3825
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003826 pReq->result_value = InvokeWithJValues(soa, pReq->receiver, soa.EncodeMethod(m.Get()),
Ian Rogers53b8b092014-03-13 23:45:53 -07003827 reinterpret_cast<jvalue*>(pReq->arg_values));
Elliott Hughesd07986f2011-12-06 18:27:45 -08003828
Ian Rogersc0542af2014-09-03 16:16:56 -07003829 mirror::Throwable* exception = soa.Self()->GetException(nullptr);
Ian Rogers62d6c772013-02-27 08:32:07 -08003830 soa.Self()->ClearException();
3831 pReq->exception = gRegistry->Add(exception);
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07003832 pReq->result_tag = BasicTagFromDescriptor(m.Get()->GetShorty());
Elliott Hughesd07986f2011-12-06 18:27:45 -08003833 if (pReq->exception != 0) {
Ian Rogers62d6c772013-02-27 08:32:07 -08003834 VLOG(jdwp) << " JDWP invocation returning with exception=" << exception
3835 << " " << exception->Dump();
Elliott Hughesf24d3ce2012-04-11 17:43:37 -07003836 pReq->result_value.SetJ(0);
Elliott Hughesd07986f2011-12-06 18:27:45 -08003837 } else if (pReq->result_tag == JDWP::JT_OBJECT) {
3838 /* if no exception thrown, examine object result more closely */
Ian Rogers98379392014-02-24 16:53:16 -08003839 JDWP::JdwpTag new_tag = TagFromObject(soa, pReq->result_value.GetL());
Elliott Hughesd07986f2011-12-06 18:27:45 -08003840 if (new_tag != pReq->result_tag) {
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08003841 VLOG(jdwp) << " JDWP promoted result from " << pReq->result_tag << " to " << new_tag;
Elliott Hughesd07986f2011-12-06 18:27:45 -08003842 pReq->result_tag = new_tag;
3843 }
3844
3845 /*
3846 * Register the object. We don't actually need an ObjectId yet,
3847 * but we do need to be sure that the GC won't move or discard the
3848 * object when we switch out of RUNNING. The ObjectId conversion
3849 * will add the object to the "do not touch" list.
3850 *
3851 * We can't use the "tracked allocation" mechanism here because
3852 * the object is going to be handed off to a different thread.
3853 */
Elliott Hughesf24d3ce2012-04-11 17:43:37 -07003854 gRegistry->Add(pReq->result_value.GetL());
Elliott Hughesd07986f2011-12-06 18:27:45 -08003855 }
3856
Ian Rogersc0542af2014-09-03 16:16:56 -07003857 if (old_exception.Get() != nullptr) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003858 ThrowLocation gc_safe_throw_location(old_throw_this_object.Get(), old_throw_method.Get(),
Ian Rogers62d6c772013-02-27 08:32:07 -08003859 old_throw_dex_pc);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003860 soa.Self()->SetException(gc_safe_throw_location, old_exception.Get());
Sebastien Hertz9f102032014-05-23 08:59:42 +02003861 soa.Self()->SetExceptionReportedToInstrumentation(old_exception_report_flag);
Elliott Hughesd07986f2011-12-06 18:27:45 -08003862 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -07003863}
3864
Elliott Hughesd07986f2011-12-06 18:27:45 -08003865/*
Elliott Hughes4b9702c2013-02-20 18:13:24 -08003866 * "request" contains a full JDWP packet, possibly with multiple chunks. We
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07003867 * need to process each, accumulate the replies, and ship the whole thing
3868 * back.
3869 *
3870 * Returns "true" if we have a reply. The reply buffer is newly allocated,
3871 * and includes the chunk type/length, followed by the data.
3872 *
Elliott Hughes3d30d9b2011-12-07 17:35:48 -08003873 * OLD-TODO: we currently assume that the request and reply include a single
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07003874 * chunk. If this becomes inconvenient we will need to adapt.
3875 */
Ian Rogersc0542af2014-09-03 16:16:56 -07003876bool Dbg::DdmHandlePacket(JDWP::Request* request, uint8_t** pReplyBuf, int* pReplyLen) {
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07003877 Thread* self = Thread::Current();
3878 JNIEnv* env = self->GetJniEnv();
3879
Ian Rogersc0542af2014-09-03 16:16:56 -07003880 uint32_t type = request->ReadUnsigned32("type");
3881 uint32_t length = request->ReadUnsigned32("length");
Elliott Hughes4b9702c2013-02-20 18:13:24 -08003882
3883 // Create a byte[] corresponding to 'request'.
Ian Rogersc0542af2014-09-03 16:16:56 -07003884 size_t request_length = request->size();
Elliott Hughes4b9702c2013-02-20 18:13:24 -08003885 ScopedLocalRef<jbyteArray> dataArray(env, env->NewByteArray(request_length));
Ian Rogersc0542af2014-09-03 16:16:56 -07003886 if (dataArray.get() == nullptr) {
Elliott Hughes4b9702c2013-02-20 18:13:24 -08003887 LOG(WARNING) << "byte[] allocation failed: " << request_length;
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07003888 env->ExceptionClear();
3889 return false;
3890 }
Ian Rogersc0542af2014-09-03 16:16:56 -07003891 env->SetByteArrayRegion(dataArray.get(), 0, request_length,
3892 reinterpret_cast<const jbyte*>(request->data()));
3893 request->Skip(request_length);
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07003894
3895 // Run through and find all chunks. [Currently just find the first.]
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003896 ScopedByteArrayRO contents(env, dataArray.get());
Elliott Hughes4b9702c2013-02-20 18:13:24 -08003897 if (length != request_length) {
Ian Rogersef7d42f2014-01-06 12:55:46 -08003898 LOG(WARNING) << StringPrintf("bad chunk found (len=%u pktLen=%zd)", length, request_length);
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07003899 return false;
3900 }
3901
3902 // Call "private static Chunk dispatch(int type, byte[] data, int offset, int length)".
Elliott Hugheseac76672012-05-24 21:56:51 -07003903 ScopedLocalRef<jobject> chunk(env, env->CallStaticObjectMethod(WellKnownClasses::org_apache_harmony_dalvik_ddmc_DdmServer,
3904 WellKnownClasses::org_apache_harmony_dalvik_ddmc_DdmServer_dispatch,
Elliott Hughes4b9702c2013-02-20 18:13:24 -08003905 type, dataArray.get(), 0, length));
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07003906 if (env->ExceptionCheck()) {
3907 LOG(INFO) << StringPrintf("Exception thrown by dispatcher for 0x%08x", type);
3908 env->ExceptionDescribe();
3909 env->ExceptionClear();
3910 return false;
3911 }
3912
Ian Rogersc0542af2014-09-03 16:16:56 -07003913 if (chunk.get() == nullptr) {
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07003914 return false;
3915 }
3916
3917 /*
3918 * Pull the pieces out of the chunk. We copy the results into a
3919 * newly-allocated buffer that the caller can free. We don't want to
3920 * continue using the Chunk object because nothing has a reference to it.
3921 *
3922 * We could avoid this by returning type/data/offset/length and having
3923 * the caller be aware of the object lifetime issues, but that
Elliott Hughes81ff3182012-03-23 20:35:56 -07003924 * integrates the JDWP code more tightly into the rest of the runtime, and doesn't work
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07003925 * if we have responses for multiple chunks.
3926 *
3927 * So we're pretty much stuck with copying data around multiple times.
3928 */
Elliott Hugheseac76672012-05-24 21:56:51 -07003929 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 -08003930 jint offset = env->GetIntField(chunk.get(), WellKnownClasses::org_apache_harmony_dalvik_ddmc_Chunk_offset);
Elliott Hugheseac76672012-05-24 21:56:51 -07003931 length = env->GetIntField(chunk.get(), WellKnownClasses::org_apache_harmony_dalvik_ddmc_Chunk_length);
Elliott Hugheseac76672012-05-24 21:56:51 -07003932 type = env->GetIntField(chunk.get(), WellKnownClasses::org_apache_harmony_dalvik_ddmc_Chunk_type);
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07003933
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08003934 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 -07003935 if (length == 0 || replyData.get() == nullptr) {
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07003936 return false;
3937 }
3938
Elliott Hughes4b9702c2013-02-20 18:13:24 -08003939 const int kChunkHdrLen = 8;
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07003940 uint8_t* reply = new uint8_t[length + kChunkHdrLen];
Ian Rogersc0542af2014-09-03 16:16:56 -07003941 if (reply == nullptr) {
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07003942 LOG(WARNING) << "malloc failed: " << (length + kChunkHdrLen);
3943 return false;
3944 }
Elliott Hughesf7c3b662011-10-27 12:04:56 -07003945 JDWP::Set4BE(reply + 0, type);
3946 JDWP::Set4BE(reply + 4, length);
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003947 env->GetByteArrayRegion(replyData.get(), offset, length, reinterpret_cast<jbyte*>(reply + kChunkHdrLen));
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07003948
3949 *pReplyBuf = reply;
3950 *pReplyLen = length + kChunkHdrLen;
3951
Elliott Hughes4b9702c2013-02-20 18:13:24 -08003952 VLOG(jdwp) << StringPrintf("dvmHandleDdm returning type=%.4s %p len=%d", reinterpret_cast<char*>(reply), reply, length);
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07003953 return true;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07003954}
3955
Elliott Hughesa2155262011-11-16 16:26:58 -08003956void Dbg::DdmBroadcast(bool connect) {
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08003957 VLOG(jdwp) << "Broadcasting DDM " << (connect ? "connect" : "disconnect") << "...";
Elliott Hughes47fce012011-10-25 18:37:19 -07003958
3959 Thread* self = Thread::Current();
Ian Rogers50b35e22012-10-04 10:09:15 -07003960 if (self->GetState() != kRunnable) {
3961 LOG(ERROR) << "DDM broadcast in thread state " << self->GetState();
3962 /* try anyway? */
Elliott Hughes47fce012011-10-25 18:37:19 -07003963 }
3964
3965 JNIEnv* env = self->GetJniEnv();
Elliott Hughes47fce012011-10-25 18:37:19 -07003966 jint event = connect ? 1 /*DdmServer.CONNECTED*/ : 2 /*DdmServer.DISCONNECTED*/;
Elliott Hugheseac76672012-05-24 21:56:51 -07003967 env->CallStaticVoidMethod(WellKnownClasses::org_apache_harmony_dalvik_ddmc_DdmServer,
3968 WellKnownClasses::org_apache_harmony_dalvik_ddmc_DdmServer_broadcast,
3969 event);
Elliott Hughes47fce012011-10-25 18:37:19 -07003970 if (env->ExceptionCheck()) {
3971 LOG(ERROR) << "DdmServer.broadcast " << event << " failed";
3972 env->ExceptionDescribe();
3973 env->ExceptionClear();
3974 }
3975}
3976
Elliott Hughes872d4ec2011-10-21 17:07:15 -07003977void Dbg::DdmConnected() {
Elliott Hughesa2155262011-11-16 16:26:58 -08003978 Dbg::DdmBroadcast(true);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07003979}
3980
3981void Dbg::DdmDisconnected() {
Elliott Hughesa2155262011-11-16 16:26:58 -08003982 Dbg::DdmBroadcast(false);
Elliott Hughes47fce012011-10-25 18:37:19 -07003983 gDdmThreadNotification = false;
3984}
3985
3986/*
Elliott Hughes82188472011-11-07 18:11:48 -08003987 * Send a notification when a thread starts, stops, or changes its name.
Elliott Hughes47fce012011-10-25 18:37:19 -07003988 *
3989 * Because we broadcast the full set of threads when the notifications are
3990 * first enabled, it's possible for "thread" to be actively executing.
3991 */
Elliott Hughes82188472011-11-07 18:11:48 -08003992void Dbg::DdmSendThreadNotification(Thread* t, uint32_t type) {
Elliott Hughes47fce012011-10-25 18:37:19 -07003993 if (!gDdmThreadNotification) {
3994 return;
3995 }
3996
Elliott Hughes82188472011-11-07 18:11:48 -08003997 if (type == CHUNK_TYPE("THDE")) {
Elliott Hughes47fce012011-10-25 18:37:19 -07003998 uint8_t buf[4];
Ian Rogersd9c4fc92013-10-01 19:45:43 -07003999 JDWP::Set4BE(&buf[0], t->GetThreadId());
Elliott Hughes47fce012011-10-25 18:37:19 -07004000 Dbg::DdmSendChunk(CHUNK_TYPE("THDE"), 4, buf);
Elliott Hughes82188472011-11-07 18:11:48 -08004001 } else {
4002 CHECK(type == CHUNK_TYPE("THCR") || type == CHUNK_TYPE("THNM")) << type;
Ian Rogers00f7d0e2012-07-19 15:28:27 -07004003 ScopedObjectAccessUnchecked soa(Thread::Current());
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004004 StackHandleScope<1> hs(soa.Self());
4005 Handle<mirror::String> name(hs.NewHandle(t->GetThreadName(soa)));
Ian Rogersc0542af2014-09-03 16:16:56 -07004006 size_t char_count = (name.Get() != nullptr) ? name->GetLength() : 0;
4007 const jchar* chars = (name.Get() != nullptr) ? name->GetCharArray()->GetData() : nullptr;
Elliott Hughes82188472011-11-07 18:11:48 -08004008
Elliott Hughes21f32d72011-11-09 17:44:13 -08004009 std::vector<uint8_t> bytes;
Ian Rogersd9c4fc92013-10-01 19:45:43 -07004010 JDWP::Append4BE(bytes, t->GetThreadId());
Elliott Hughes545a0642011-11-08 19:10:03 -08004011 JDWP::AppendUtf16BE(bytes, chars, char_count);
Elliott Hughes21f32d72011-11-09 17:44:13 -08004012 CHECK_EQ(bytes.size(), char_count*2 + sizeof(uint32_t)*2);
4013 Dbg::DdmSendChunk(type, bytes);
Elliott Hughes47fce012011-10-25 18:37:19 -07004014 }
4015}
4016
Elliott Hughes47fce012011-10-25 18:37:19 -07004017void Dbg::DdmSetThreadNotification(bool enable) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07004018 // Enable/disable thread notifications.
Elliott Hughes47fce012011-10-25 18:37:19 -07004019 gDdmThreadNotification = enable;
4020 if (enable) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07004021 // Suspend the VM then post thread start notifications for all threads. Threads attaching will
4022 // see a suspension in progress and block until that ends. They then post their own start
4023 // notification.
4024 SuspendVM();
4025 std::list<Thread*> threads;
Ian Rogers50b35e22012-10-04 10:09:15 -07004026 Thread* self = Thread::Current();
Ian Rogers00f7d0e2012-07-19 15:28:27 -07004027 {
Ian Rogers50b35e22012-10-04 10:09:15 -07004028 MutexLock mu(self, *Locks::thread_list_lock_);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07004029 threads = Runtime::Current()->GetThreadList()->GetList();
4030 }
4031 {
Ian Rogers50b35e22012-10-04 10:09:15 -07004032 ScopedObjectAccess soa(self);
Mathieu Chartier02e25112013-08-14 16:14:24 -07004033 for (Thread* thread : threads) {
4034 Dbg::DdmSendThreadNotification(thread, CHUNK_TYPE("THCR"));
Ian Rogers00f7d0e2012-07-19 15:28:27 -07004035 }
4036 }
4037 ResumeVM();
Elliott Hughes47fce012011-10-25 18:37:19 -07004038 }
4039}
4040
Elliott Hughesa2155262011-11-16 16:26:58 -08004041void Dbg::PostThreadStartOrStop(Thread* t, uint32_t type) {
Elliott Hughesc0f09332012-03-26 13:27:06 -07004042 if (IsDebuggerActive()) {
Sebastien Hertz6995c602014-09-09 12:10:13 +02004043 gJdwpState->PostThreadChange(t, type == CHUNK_TYPE("THCR"));
Elliott Hughes47fce012011-10-25 18:37:19 -07004044 }
Elliott Hughes82188472011-11-07 18:11:48 -08004045 Dbg::DdmSendThreadNotification(t, type);
Elliott Hughes47fce012011-10-25 18:37:19 -07004046}
4047
4048void Dbg::PostThreadStart(Thread* t) {
Elliott Hughesa2155262011-11-16 16:26:58 -08004049 Dbg::PostThreadStartOrStop(t, CHUNK_TYPE("THCR"));
Elliott Hughes47fce012011-10-25 18:37:19 -07004050}
4051
4052void Dbg::PostThreadDeath(Thread* t) {
Elliott Hughesa2155262011-11-16 16:26:58 -08004053 Dbg::PostThreadStartOrStop(t, CHUNK_TYPE("THDE"));
Elliott Hughes872d4ec2011-10-21 17:07:15 -07004054}
4055
Elliott Hughes82188472011-11-07 18:11:48 -08004056void Dbg::DdmSendChunk(uint32_t type, size_t byte_count, const uint8_t* buf) {
Ian Rogersc0542af2014-09-03 16:16:56 -07004057 CHECK(buf != nullptr);
Elliott Hughes3bb81562011-10-21 18:52:59 -07004058 iovec vec[1];
4059 vec[0].iov_base = reinterpret_cast<void*>(const_cast<uint8_t*>(buf));
4060 vec[0].iov_len = byte_count;
4061 Dbg::DdmSendChunkV(type, vec, 1);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07004062}
4063
Elliott Hughes21f32d72011-11-09 17:44:13 -08004064void Dbg::DdmSendChunk(uint32_t type, const std::vector<uint8_t>& bytes) {
4065 DdmSendChunk(type, bytes.size(), &bytes[0]);
4066}
4067
Brian Carlstromf5293522013-07-19 00:24:00 -07004068void Dbg::DdmSendChunkV(uint32_t type, const iovec* iov, int iov_count) {
Ian Rogersc0542af2014-09-03 16:16:56 -07004069 if (gJdwpState == nullptr) {
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08004070 VLOG(jdwp) << "Debugger thread not active, ignoring DDM send: " << type;
Elliott Hughes3bb81562011-10-21 18:52:59 -07004071 } else {
Elliott Hughescccd84f2011-12-05 16:51:54 -08004072 gJdwpState->DdmSendChunkV(type, iov, iov_count);
Elliott Hughes3bb81562011-10-21 18:52:59 -07004073 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -07004074}
4075
Mathieu Chartierad466ad2015-01-08 16:28:08 -08004076JDWP::JdwpState* Dbg::GetJdwpState() {
4077 return gJdwpState;
4078}
4079
Elliott Hughes767a1472011-10-26 18:49:02 -07004080int Dbg::DdmHandleHpifChunk(HpifWhen when) {
4081 if (when == HPIF_WHEN_NOW) {
Elliott Hughes7162ad92011-10-27 14:08:42 -07004082 DdmSendHeapInfo(when);
Elliott Hughes767a1472011-10-26 18:49:02 -07004083 return true;
4084 }
4085
4086 if (when != HPIF_WHEN_NEVER && when != HPIF_WHEN_NEXT_GC && when != HPIF_WHEN_EVERY_GC) {
4087 LOG(ERROR) << "invalid HpifWhen value: " << static_cast<int>(when);
4088 return false;
4089 }
4090
4091 gDdmHpifWhen = when;
4092 return true;
4093}
4094
4095bool Dbg::DdmHandleHpsgNhsgChunk(Dbg::HpsgWhen when, Dbg::HpsgWhat what, bool native) {
4096 if (when != HPSG_WHEN_NEVER && when != HPSG_WHEN_EVERY_GC) {
4097 LOG(ERROR) << "invalid HpsgWhen value: " << static_cast<int>(when);
4098 return false;
4099 }
4100
4101 if (what != HPSG_WHAT_MERGED_OBJECTS && what != HPSG_WHAT_DISTINCT_OBJECTS) {
4102 LOG(ERROR) << "invalid HpsgWhat value: " << static_cast<int>(what);
4103 return false;
4104 }
4105
4106 if (native) {
4107 gDdmNhsgWhen = when;
4108 gDdmNhsgWhat = what;
4109 } else {
4110 gDdmHpsgWhen = when;
4111 gDdmHpsgWhat = what;
4112 }
4113 return true;
4114}
4115
Elliott Hughes7162ad92011-10-27 14:08:42 -07004116void Dbg::DdmSendHeapInfo(HpifWhen reason) {
4117 // If there's a one-shot 'when', reset it.
4118 if (reason == gDdmHpifWhen) {
4119 if (gDdmHpifWhen == HPIF_WHEN_NEXT_GC) {
4120 gDdmHpifWhen = HPIF_WHEN_NEVER;
4121 }
4122 }
4123
4124 /*
4125 * Chunk HPIF (client --> server)
4126 *
4127 * Heap Info. General information about the heap,
4128 * suitable for a summary display.
4129 *
4130 * [u4]: number of heaps
4131 *
4132 * For each heap:
4133 * [u4]: heap ID
4134 * [u8]: timestamp in ms since Unix epoch
4135 * [u1]: capture reason (same as 'when' value from server)
4136 * [u4]: max heap size in bytes (-Xmx)
4137 * [u4]: current heap size in bytes
4138 * [u4]: current number of bytes allocated
4139 * [u4]: current number of objects allocated
4140 */
4141 uint8_t heap_count = 1;
Ian Rogers1d54e732013-05-02 21:10:01 -07004142 gc::Heap* heap = Runtime::Current()->GetHeap();
Elliott Hughes21f32d72011-11-09 17:44:13 -08004143 std::vector<uint8_t> bytes;
Elliott Hughes545a0642011-11-08 19:10:03 -08004144 JDWP::Append4BE(bytes, heap_count);
Brian Carlstrom7934ac22013-07-26 10:54:15 -07004145 JDWP::Append4BE(bytes, 1); // Heap id (bogus; we only have one heap).
Elliott Hughes545a0642011-11-08 19:10:03 -08004146 JDWP::Append8BE(bytes, MilliTime());
4147 JDWP::Append1BE(bytes, reason);
Brian Carlstrom7934ac22013-07-26 10:54:15 -07004148 JDWP::Append4BE(bytes, heap->GetMaxMemory()); // Max allowed heap size in bytes.
4149 JDWP::Append4BE(bytes, heap->GetTotalMemory()); // Current heap size in bytes.
Elliott Hughesb3bd5f02012-03-08 21:05:27 -08004150 JDWP::Append4BE(bytes, heap->GetBytesAllocated());
4151 JDWP::Append4BE(bytes, heap->GetObjectsAllocated());
Elliott Hughes21f32d72011-11-09 17:44:13 -08004152 CHECK_EQ(bytes.size(), 4U + (heap_count * (4 + 8 + 1 + 4 + 4 + 4 + 4)));
4153 Dbg::DdmSendChunk(CHUNK_TYPE("HPIF"), bytes);
Elliott Hughes767a1472011-10-26 18:49:02 -07004154}
4155
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004156enum HpsgSolidity {
4157 SOLIDITY_FREE = 0,
4158 SOLIDITY_HARD = 1,
4159 SOLIDITY_SOFT = 2,
4160 SOLIDITY_WEAK = 3,
4161 SOLIDITY_PHANTOM = 4,
4162 SOLIDITY_FINALIZABLE = 5,
4163 SOLIDITY_SWEEP = 6,
4164};
4165
4166enum HpsgKind {
4167 KIND_OBJECT = 0,
4168 KIND_CLASS_OBJECT = 1,
4169 KIND_ARRAY_1 = 2,
4170 KIND_ARRAY_2 = 3,
4171 KIND_ARRAY_4 = 4,
4172 KIND_ARRAY_8 = 5,
4173 KIND_UNKNOWN = 6,
4174 KIND_NATIVE = 7,
4175};
4176
4177#define HPSG_PARTIAL (1<<7)
4178#define HPSG_STATE(solidity, kind) ((uint8_t)((((kind) & 0x7) << 3) | ((solidity) & 0x7)))
4179
Ian Rogers30fab402012-01-23 15:43:46 -08004180class HeapChunkContext {
4181 public:
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004182 // Maximum chunk size. Obtain this from the formula:
4183 // (((maximum_heap_size / ALLOCATION_UNIT_SIZE) + 255) / 256) * 2
4184 HeapChunkContext(bool merge, bool native)
Ian Rogers30fab402012-01-23 15:43:46 -08004185 : buf_(16384 - 16),
4186 type_(0),
Mathieu Chartier36dab362014-07-30 14:59:56 -07004187 chunk_overhead_(0) {
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004188 Reset();
4189 if (native) {
Ian Rogers30fab402012-01-23 15:43:46 -08004190 type_ = CHUNK_TYPE("NHSG");
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004191 } else {
Ian Rogers30fab402012-01-23 15:43:46 -08004192 type_ = merge ? CHUNK_TYPE("HPSG") : CHUNK_TYPE("HPSO");
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004193 }
4194 }
4195
4196 ~HeapChunkContext() {
Ian Rogers30fab402012-01-23 15:43:46 -08004197 if (p_ > &buf_[0]) {
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004198 Flush();
4199 }
4200 }
4201
Mathieu Chartier36dab362014-07-30 14:59:56 -07004202 void SetChunkOverhead(size_t chunk_overhead) {
4203 chunk_overhead_ = chunk_overhead;
4204 }
4205
4206 void ResetStartOfNextChunk() {
4207 startOfNextMemoryChunk_ = nullptr;
4208 }
4209
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004210 void EnsureHeader(const void* chunk_ptr) {
Ian Rogers30fab402012-01-23 15:43:46 -08004211 if (!needHeader_) {
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004212 return;
4213 }
4214
4215 // Start a new HPSx chunk.
Brian Carlstrom7934ac22013-07-26 10:54:15 -07004216 JDWP::Write4BE(&p_, 1); // Heap id (bogus; we only have one heap).
4217 JDWP::Write1BE(&p_, 8); // Size of allocation unit, in bytes.
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004218
Brian Carlstrom7934ac22013-07-26 10:54:15 -07004219 JDWP::Write4BE(&p_, reinterpret_cast<uintptr_t>(chunk_ptr)); // virtual address of segment start.
4220 JDWP::Write4BE(&p_, 0); // offset of this piece (relative to the virtual address).
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004221 // [u4]: length of piece, in allocation units
4222 // 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 -08004223 pieceLenField_ = p_;
4224 JDWP::Write4BE(&p_, 0x55555555);
4225 needHeader_ = false;
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004226 }
4227
Ian Rogersb726dcb2012-09-05 08:57:23 -07004228 void Flush() SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Ian Rogersc0542af2014-09-03 16:16:56 -07004229 if (pieceLenField_ == nullptr) {
Ian Rogersd636b062013-01-18 17:51:18 -08004230 // Flush immediately post Reset (maybe back-to-back Flush). Ignore.
4231 CHECK(needHeader_);
4232 return;
4233 }
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004234 // Patch the "length of piece" field.
Ian Rogers30fab402012-01-23 15:43:46 -08004235 CHECK_LE(&buf_[0], pieceLenField_);
4236 CHECK_LE(pieceLenField_, p_);
4237 JDWP::Set4BE(pieceLenField_, totalAllocationUnits_);
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004238
Ian Rogers30fab402012-01-23 15:43:46 -08004239 Dbg::DdmSendChunk(type_, p_ - &buf_[0], &buf_[0]);
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004240 Reset();
4241 }
4242
Mathieu Chartierbc689b72014-12-14 17:01:31 -08004243 static void HeapChunkJavaCallback(void* start, void* end, size_t used_bytes, void* arg)
Ian Rogersb726dcb2012-09-05 08:57:23 -07004244 SHARED_LOCKS_REQUIRED(Locks::heap_bitmap_lock_,
4245 Locks::mutator_lock_) {
Mathieu Chartierbc689b72014-12-14 17:01:31 -08004246 reinterpret_cast<HeapChunkContext*>(arg)->HeapChunkJavaCallback(start, end, used_bytes);
4247 }
4248
4249 static void HeapChunkNativeCallback(void* start, void* end, size_t used_bytes, void* arg)
4250 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
4251 reinterpret_cast<HeapChunkContext*>(arg)->HeapChunkNativeCallback(start, end, used_bytes);
Elliott Hughesa2155262011-11-16 16:26:58 -08004252 }
4253
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004254 private:
Elliott Hughesa2155262011-11-16 16:26:58 -08004255 enum { ALLOCATION_UNIT_SIZE = 8 };
4256
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004257 void Reset() {
Ian Rogers30fab402012-01-23 15:43:46 -08004258 p_ = &buf_[0];
Mathieu Chartier36dab362014-07-30 14:59:56 -07004259 ResetStartOfNextChunk();
Ian Rogers30fab402012-01-23 15:43:46 -08004260 totalAllocationUnits_ = 0;
4261 needHeader_ = true;
Ian Rogersc0542af2014-09-03 16:16:56 -07004262 pieceLenField_ = nullptr;
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004263 }
4264
Mathieu Chartierbc689b72014-12-14 17:01:31 -08004265 bool IsNative() const {
4266 return type_ == CHUNK_TYPE("NHSG");
4267 }
4268
4269 // Returns true if the object is not an empty chunk.
4270 bool ProcessRecord(void* start, size_t used_bytes) SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Ian Rogers30fab402012-01-23 15:43:46 -08004271 // Note: heap call backs cannot manipulate the heap upon which they are crawling, care is taken
4272 // in the following code not to allocate memory, by ensuring buf_ is of the correct size
Ian Rogers15bf2d32012-08-28 17:33:04 -07004273 if (used_bytes == 0) {
Mathieu Chartierbc689b72014-12-14 17:01:31 -08004274 if (start == nullptr) {
4275 // Reset for start of new heap.
4276 startOfNextMemoryChunk_ = nullptr;
4277 Flush();
4278 }
4279 // Only process in use memory so that free region information
4280 // also includes dlmalloc book keeping.
4281 return false;
Elliott Hughesa2155262011-11-16 16:26:58 -08004282 }
Ian Rogersc0542af2014-09-03 16:16:56 -07004283 if (startOfNextMemoryChunk_ != nullptr) {
Mathieu Chartierbc689b72014-12-14 17:01:31 -08004284 // Transmit any pending free memory. Native free memory of over kMaxFreeLen could be because
4285 // of the use of mmaps, so don't report. If not free memory then start a new segment.
4286 bool flush = true;
4287 if (start > startOfNextMemoryChunk_) {
4288 const size_t kMaxFreeLen = 2 * kPageSize;
4289 void* free_start = startOfNextMemoryChunk_;
4290 void* free_end = start;
4291 const size_t free_len =
4292 reinterpret_cast<uintptr_t>(free_end) - reinterpret_cast<uintptr_t>(free_start);
4293 if (!IsNative() || free_len < kMaxFreeLen) {
4294 AppendChunk(HPSG_STATE(SOLIDITY_FREE, 0), free_start, free_len, IsNative());
4295 flush = false;
Ian Rogers15bf2d32012-08-28 17:33:04 -07004296 }
Mathieu Chartierbc689b72014-12-14 17:01:31 -08004297 }
4298 if (flush) {
4299 startOfNextMemoryChunk_ = nullptr;
4300 Flush();
4301 }
Ian Rogers15bf2d32012-08-28 17:33:04 -07004302 }
Mathieu Chartierbc689b72014-12-14 17:01:31 -08004303 return true;
Ian Rogers15bf2d32012-08-28 17:33:04 -07004304 }
Elliott Hughesa2155262011-11-16 16:26:58 -08004305
Mathieu Chartierbc689b72014-12-14 17:01:31 -08004306 void HeapChunkNativeCallback(void* start, void* /*end*/, size_t used_bytes)
4307 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
4308 if (ProcessRecord(start, used_bytes)) {
4309 uint8_t state = ExamineNativeObject(start);
4310 AppendChunk(state, start, used_bytes + chunk_overhead_, true /*is_native*/);
4311 startOfNextMemoryChunk_ = reinterpret_cast<char*>(start) + used_bytes + chunk_overhead_;
4312 }
4313 }
4314
4315 void HeapChunkJavaCallback(void* start, void* /*end*/, size_t used_bytes)
4316 SHARED_LOCKS_REQUIRED(Locks::heap_bitmap_lock_, Locks::mutator_lock_) {
4317 if (ProcessRecord(start, used_bytes)) {
4318 // Determine the type of this chunk.
4319 // OLD-TODO: if context.merge, see if this chunk is different from the last chunk.
4320 // If it's the same, we should combine them.
4321 uint8_t state = ExamineJavaObject(reinterpret_cast<mirror::Object*>(start));
4322 AppendChunk(state, start, used_bytes + chunk_overhead_, false /*is_native*/);
4323 startOfNextMemoryChunk_ = reinterpret_cast<char*>(start) + used_bytes + chunk_overhead_;
4324 }
4325 }
4326
4327 void AppendChunk(uint8_t state, void* ptr, size_t length, bool is_native)
Ian Rogersb726dcb2012-09-05 08:57:23 -07004328 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Ian Rogers15bf2d32012-08-28 17:33:04 -07004329 // Make sure there's enough room left in the buffer.
4330 // We need to use two bytes for every fractional 256 allocation units used by the chunk plus
4331 // 17 bytes for any header.
Mathieu Chartierbc689b72014-12-14 17:01:31 -08004332 const size_t needed = ((RoundUp(length / ALLOCATION_UNIT_SIZE, 256) / 256) * 2) + 17;
4333 size_t byte_left = &buf_.back() - p_;
4334 if (byte_left < needed) {
4335 if (is_native) {
Pavel Vyssotski7522c742014-12-08 13:38:26 +06004336 // Cannot trigger memory allocation while walking native heap.
Pavel Vyssotski7522c742014-12-08 13:38:26 +06004337 return;
4338 }
Ian Rogers15bf2d32012-08-28 17:33:04 -07004339 Flush();
4340 }
4341
Mathieu Chartierbc689b72014-12-14 17:01:31 -08004342 byte_left = &buf_.back() - p_;
4343 if (byte_left < needed) {
Ian Rogers15bf2d32012-08-28 17:33:04 -07004344 LOG(WARNING) << "Chunk is too big to transmit (chunk_len=" << length << ", "
4345 << needed << " bytes)";
4346 return;
4347 }
4348 EnsureHeader(ptr);
Elliott Hughesa2155262011-11-16 16:26:58 -08004349 // Write out the chunk description.
Ian Rogers15bf2d32012-08-28 17:33:04 -07004350 length /= ALLOCATION_UNIT_SIZE; // Convert to allocation units.
4351 totalAllocationUnits_ += length;
4352 while (length > 256) {
Ian Rogers30fab402012-01-23 15:43:46 -08004353 *p_++ = state | HPSG_PARTIAL;
4354 *p_++ = 255; // length - 1
Ian Rogers15bf2d32012-08-28 17:33:04 -07004355 length -= 256;
Elliott Hughesa2155262011-11-16 16:26:58 -08004356 }
Ian Rogers30fab402012-01-23 15:43:46 -08004357 *p_++ = state;
Ian Rogers15bf2d32012-08-28 17:33:04 -07004358 *p_++ = length - 1;
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004359 }
4360
Mathieu Chartierbc689b72014-12-14 17:01:31 -08004361 uint8_t ExamineNativeObject(const void* p) SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
4362 return p == nullptr ? HPSG_STATE(SOLIDITY_FREE, 0) : HPSG_STATE(SOLIDITY_HARD, KIND_NATIVE);
4363 }
4364
4365 uint8_t ExamineJavaObject(mirror::Object* o)
Ian Rogersef7d42f2014-01-06 12:55:46 -08004366 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_, Locks::heap_bitmap_lock_) {
Ian Rogersc0542af2014-09-03 16:16:56 -07004367 if (o == nullptr) {
Elliott Hughesa2155262011-11-16 16:26:58 -08004368 return HPSG_STATE(SOLIDITY_FREE, 0);
4369 }
Elliott Hughesa2155262011-11-16 16:26:58 -08004370 // It's an allocated chunk. Figure out what it is.
Mathieu Chartierbc689b72014-12-14 17:01:31 -08004371 gc::Heap* heap = Runtime::Current()->GetHeap();
4372 if (!heap->IsLiveObjectLocked(o)) {
4373 LOG(ERROR) << "Invalid object in managed heap: " << o;
Elliott Hughesa2155262011-11-16 16:26:58 -08004374 return HPSG_STATE(SOLIDITY_HARD, KIND_NATIVE);
4375 }
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08004376 mirror::Class* c = o->GetClass();
Ian Rogersc0542af2014-09-03 16:16:56 -07004377 if (c == nullptr) {
Elliott Hughesa2155262011-11-16 16:26:58 -08004378 // The object was probably just created but hasn't been initialized yet.
4379 return HPSG_STATE(SOLIDITY_HARD, KIND_OBJECT);
4380 }
Mathieu Chartierbc689b72014-12-14 17:01:31 -08004381 if (!heap->IsValidObjectAddress(c)) {
Ian Rogers15bf2d32012-08-28 17:33:04 -07004382 LOG(ERROR) << "Invalid class for managed heap object: " << o << " " << c;
Elliott Hughesa2155262011-11-16 16:26:58 -08004383 return HPSG_STATE(SOLIDITY_HARD, KIND_UNKNOWN);
4384 }
Mathieu Chartierf26e1b32015-01-29 10:47:10 -08004385 if (c->GetClass() == nullptr) {
4386 LOG(ERROR) << "Null class of class " << c << " for object " << o;
4387 return HPSG_STATE(SOLIDITY_HARD, KIND_UNKNOWN);
4388 }
Elliott Hughesa2155262011-11-16 16:26:58 -08004389 if (c->IsClassClass()) {
4390 return HPSG_STATE(SOLIDITY_HARD, KIND_CLASS_OBJECT);
4391 }
Elliott Hughesa2155262011-11-16 16:26:58 -08004392 if (c->IsArrayClass()) {
Elliott Hughesa2155262011-11-16 16:26:58 -08004393 switch (c->GetComponentSize()) {
4394 case 1: return HPSG_STATE(SOLIDITY_HARD, KIND_ARRAY_1);
4395 case 2: return HPSG_STATE(SOLIDITY_HARD, KIND_ARRAY_2);
4396 case 4: return HPSG_STATE(SOLIDITY_HARD, KIND_ARRAY_4);
4397 case 8: return HPSG_STATE(SOLIDITY_HARD, KIND_ARRAY_8);
4398 }
4399 }
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004400 return HPSG_STATE(SOLIDITY_HARD, KIND_OBJECT);
4401 }
4402
Ian Rogers30fab402012-01-23 15:43:46 -08004403 std::vector<uint8_t> buf_;
4404 uint8_t* p_;
4405 uint8_t* pieceLenField_;
Ian Rogers15bf2d32012-08-28 17:33:04 -07004406 void* startOfNextMemoryChunk_;
Ian Rogers30fab402012-01-23 15:43:46 -08004407 size_t totalAllocationUnits_;
4408 uint32_t type_;
Ian Rogers30fab402012-01-23 15:43:46 -08004409 bool needHeader_;
Mathieu Chartier36dab362014-07-30 14:59:56 -07004410 size_t chunk_overhead_;
Ian Rogers30fab402012-01-23 15:43:46 -08004411
Elliott Hughesa2155262011-11-16 16:26:58 -08004412 DISALLOW_COPY_AND_ASSIGN(HeapChunkContext);
4413};
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004414
Mathieu Chartier36dab362014-07-30 14:59:56 -07004415static void BumpPointerSpaceCallback(mirror::Object* obj, void* arg)
4416 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) EXCLUSIVE_LOCKS_REQUIRED(Locks::heap_bitmap_lock_) {
4417 const size_t size = RoundUp(obj->SizeOf(), kObjectAlignment);
Mathieu Chartierbc689b72014-12-14 17:01:31 -08004418 HeapChunkContext::HeapChunkJavaCallback(
Mathieu Chartier36dab362014-07-30 14:59:56 -07004419 obj, reinterpret_cast<void*>(reinterpret_cast<uintptr_t>(obj) + size), size, arg);
4420}
4421
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004422void Dbg::DdmSendHeapSegments(bool native) {
Mathieu Chartierbc689b72014-12-14 17:01:31 -08004423 Dbg::HpsgWhen when = native ? gDdmNhsgWhen : gDdmHpsgWhen;
4424 Dbg::HpsgWhat what = native ? gDdmNhsgWhat : gDdmHpsgWhat;
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004425 if (when == HPSG_WHEN_NEVER) {
4426 return;
4427 }
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004428 // Figure out what kind of chunks we'll be sending.
Mathieu Chartierbc689b72014-12-14 17:01:31 -08004429 CHECK(what == HPSG_WHAT_MERGED_OBJECTS || what == HPSG_WHAT_DISTINCT_OBJECTS)
4430 << static_cast<int>(what);
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004431
4432 // First, send a heap start chunk.
4433 uint8_t heap_id[4];
Brian Carlstrom7934ac22013-07-26 10:54:15 -07004434 JDWP::Set4BE(&heap_id[0], 1); // Heap id (bogus; we only have one heap).
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004435 Dbg::DdmSendChunk(native ? CHUNK_TYPE("NHST") : CHUNK_TYPE("HPST"), sizeof(heap_id), heap_id);
Hiroshi Yamauchicf58d4a2013-09-26 14:21:22 -07004436 Thread* self = Thread::Current();
Hiroshi Yamauchicf58d4a2013-09-26 14:21:22 -07004437 Locks::mutator_lock_->AssertSharedHeld(self);
Hiroshi Yamauchicf58d4a2013-09-26 14:21:22 -07004438
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004439 // Send a series of heap segment chunks.
Mathieu Chartierbc689b72014-12-14 17:01:31 -08004440 HeapChunkContext context(what == HPSG_WHAT_MERGED_OBJECTS, native);
Elliott Hughesa2155262011-11-16 16:26:58 -08004441 if (native) {
Ian Rogers872dd822014-10-30 11:19:14 -07004442#if defined(HAVE_ANDROID_OS) && defined(USE_DLMALLOC)
Mathieu Chartierbc689b72014-12-14 17:01:31 -08004443 dlmalloc_inspect_all(HeapChunkContext::HeapChunkNativeCallback, &context);
4444 HeapChunkContext::HeapChunkNativeCallback(nullptr, nullptr, 0, &context); // Indicate end of a space.
Christopher Ferrisc4ddc042014-05-13 14:47:50 -07004445#else
4446 UNIMPLEMENTED(WARNING) << "Native heap inspection is only supported with dlmalloc";
4447#endif
Elliott Hughesa2155262011-11-16 16:26:58 -08004448 } else {
Ian Rogers1d54e732013-05-02 21:10:01 -07004449 gc::Heap* heap = Runtime::Current()->GetHeap();
Mathieu Chartier36dab362014-07-30 14:59:56 -07004450 for (const auto& space : heap->GetContinuousSpaces()) {
4451 if (space->IsDlMallocSpace()) {
Mathieu Chartier4c69d7f2014-10-10 12:45:50 -07004452 ReaderMutexLock mu(self, *Locks::heap_bitmap_lock_);
Mathieu Chartier36dab362014-07-30 14:59:56 -07004453 // dlmalloc's chunk header is 2 * sizeof(size_t), but if the previous chunk is in use for an
4454 // allocation then the first sizeof(size_t) may belong to it.
4455 context.SetChunkOverhead(sizeof(size_t));
Mathieu Chartierbc689b72014-12-14 17:01:31 -08004456 space->AsDlMallocSpace()->Walk(HeapChunkContext::HeapChunkJavaCallback, &context);
Mathieu Chartier36dab362014-07-30 14:59:56 -07004457 } else if (space->IsRosAllocSpace()) {
4458 context.SetChunkOverhead(0);
Mathieu Chartier4c69d7f2014-10-10 12:45:50 -07004459 // Need to acquire the mutator lock before the heap bitmap lock with exclusive access since
4460 // RosAlloc's internal logic doesn't know to release and reacquire the heap bitmap lock.
4461 self->TransitionFromRunnableToSuspended(kSuspended);
4462 ThreadList* tl = Runtime::Current()->GetThreadList();
4463 tl->SuspendAll();
4464 {
4465 ReaderMutexLock mu(self, *Locks::heap_bitmap_lock_);
Mathieu Chartierbc689b72014-12-14 17:01:31 -08004466 space->AsRosAllocSpace()->Walk(HeapChunkContext::HeapChunkJavaCallback, &context);
Mathieu Chartier4c69d7f2014-10-10 12:45:50 -07004467 }
4468 tl->ResumeAll();
4469 self->TransitionFromSuspendedToRunnable();
Mathieu Chartier36dab362014-07-30 14:59:56 -07004470 } else if (space->IsBumpPointerSpace()) {
Mathieu Chartier4c69d7f2014-10-10 12:45:50 -07004471 ReaderMutexLock mu(self, *Locks::heap_bitmap_lock_);
Mathieu Chartier36dab362014-07-30 14:59:56 -07004472 context.SetChunkOverhead(0);
Mathieu Chartier36dab362014-07-30 14:59:56 -07004473 space->AsBumpPointerSpace()->Walk(BumpPointerSpaceCallback, &context);
Mathieu Chartierbc689b72014-12-14 17:01:31 -08004474 HeapChunkContext::HeapChunkJavaCallback(nullptr, nullptr, 0, &context);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08004475 } else if (space->IsRegionSpace()) {
4476 heap->IncrementDisableMovingGC(self);
4477 self->TransitionFromRunnableToSuspended(kSuspended);
4478 ThreadList* tl = Runtime::Current()->GetThreadList();
4479 tl->SuspendAll();
4480 ReaderMutexLock mu(self, *Locks::heap_bitmap_lock_);
4481 context.SetChunkOverhead(0);
4482 space->AsRegionSpace()->Walk(BumpPointerSpaceCallback, &context);
4483 HeapChunkContext::HeapChunkJavaCallback(nullptr, nullptr, 0, &context);
4484 tl->ResumeAll();
4485 self->TransitionFromSuspendedToRunnable();
4486 heap->DecrementDisableMovingGC(self);
Mathieu Chartier36dab362014-07-30 14:59:56 -07004487 } else {
4488 UNIMPLEMENTED(WARNING) << "Not counting objects in space " << *space;
Mathieu Chartierb062fdd2012-07-03 09:51:48 -07004489 }
Mathieu Chartier36dab362014-07-30 14:59:56 -07004490 context.ResetStartOfNextChunk();
Mathieu Chartierb062fdd2012-07-03 09:51:48 -07004491 }
Mathieu Chartier4c69d7f2014-10-10 12:45:50 -07004492 ReaderMutexLock mu(self, *Locks::heap_bitmap_lock_);
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -07004493 // Walk the large objects, these are not in the AllocSpace.
Mathieu Chartier36dab362014-07-30 14:59:56 -07004494 context.SetChunkOverhead(0);
Mathieu Chartierbc689b72014-12-14 17:01:31 -08004495 heap->GetLargeObjectsSpace()->Walk(HeapChunkContext::HeapChunkJavaCallback, &context);
Elliott Hughesa2155262011-11-16 16:26:58 -08004496 }
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004497
4498 // Finally, send a heap end chunk.
4499 Dbg::DdmSendChunk(native ? CHUNK_TYPE("NHEN") : CHUNK_TYPE("HPEN"), sizeof(heap_id), heap_id);
Elliott Hughes767a1472011-10-26 18:49:02 -07004500}
4501
Elliott Hughesb1a58792013-07-11 18:10:58 -07004502static size_t GetAllocTrackerMax() {
4503#ifdef HAVE_ANDROID_OS
4504 // Check whether there's a system property overriding the number of records.
4505 const char* propertyName = "dalvik.vm.allocTrackerMax";
4506 char allocRecordMaxString[PROPERTY_VALUE_MAX];
4507 if (property_get(propertyName, allocRecordMaxString, "") > 0) {
4508 char* end;
4509 size_t value = strtoul(allocRecordMaxString, &end, 10);
4510 if (*end != '\0') {
Ruben Brunk3e47a742013-09-09 17:56:07 -07004511 LOG(ERROR) << "Ignoring " << propertyName << " '" << allocRecordMaxString
4512 << "' --- invalid";
Elliott Hughesb1a58792013-07-11 18:10:58 -07004513 return kDefaultNumAllocRecords;
4514 }
4515 if (!IsPowerOfTwo(value)) {
Ruben Brunk3e47a742013-09-09 17:56:07 -07004516 LOG(ERROR) << "Ignoring " << propertyName << " '" << allocRecordMaxString
4517 << "' --- not power of two";
Elliott Hughesb1a58792013-07-11 18:10:58 -07004518 return kDefaultNumAllocRecords;
4519 }
4520 return value;
4521 }
4522#endif
4523 return kDefaultNumAllocRecords;
4524}
4525
Brian Carlstrom306db812014-09-05 13:01:41 -07004526void Dbg::SetAllocTrackingEnabled(bool enable) {
4527 Thread* self = Thread::Current();
4528 if (enable) {
Sebastien Hertzb98063a2014-03-26 10:57:20 +01004529 {
Brian Carlstrom306db812014-09-05 13:01:41 -07004530 MutexLock mu(self, *Locks::alloc_tracker_lock_);
4531 if (recent_allocation_records_ != nullptr) {
4532 return; // Already enabled, bail.
Sebastien Hertzb98063a2014-03-26 10:57:20 +01004533 }
Brian Carlstrom306db812014-09-05 13:01:41 -07004534 alloc_record_max_ = GetAllocTrackerMax();
4535 LOG(INFO) << "Enabling alloc tracker (" << alloc_record_max_ << " entries of "
4536 << kMaxAllocRecordStackDepth << " frames, taking "
4537 << PrettySize(sizeof(AllocRecord) * alloc_record_max_) << ")";
4538 DCHECK_EQ(alloc_record_head_, 0U);
4539 DCHECK_EQ(alloc_record_count_, 0U);
4540 recent_allocation_records_ = new AllocRecord[alloc_record_max_];
4541 CHECK(recent_allocation_records_ != nullptr);
Elliott Hughes545a0642011-11-08 19:10:03 -08004542 }
Mathieu Chartier9ef78b52014-09-25 17:03:12 -07004543 Runtime::Current()->GetInstrumentation()->InstrumentQuickAllocEntryPoints();
Elliott Hughes545a0642011-11-08 19:10:03 -08004544 } else {
Sebastien Hertzb98063a2014-03-26 10:57:20 +01004545 {
Brian Carlstrom306db812014-09-05 13:01:41 -07004546 ScopedObjectAccess soa(self); // For type_cache_.Clear();
4547 MutexLock mu(self, *Locks::alloc_tracker_lock_);
4548 if (recent_allocation_records_ == nullptr) {
4549 return; // Already disabled, bail.
4550 }
Mathieu Chartier4345c462014-06-27 10:20:14 -07004551 LOG(INFO) << "Disabling alloc tracker";
Sebastien Hertzb98063a2014-03-26 10:57:20 +01004552 delete[] recent_allocation_records_;
Ian Rogersc0542af2014-09-03 16:16:56 -07004553 recent_allocation_records_ = nullptr;
Brian Carlstrom306db812014-09-05 13:01:41 -07004554 alloc_record_head_ = 0;
4555 alloc_record_count_ = 0;
Mathieu Chartier4345c462014-06-27 10:20:14 -07004556 type_cache_.Clear();
Sebastien Hertzb98063a2014-03-26 10:57:20 +01004557 }
Brian Carlstrom306db812014-09-05 13:01:41 -07004558 // If an allocation comes in before we uninstrument, we will safely drop it on the floor.
Mathieu Chartier9ef78b52014-09-25 17:03:12 -07004559 Runtime::Current()->GetInstrumentation()->UninstrumentQuickAllocEntryPoints();
Elliott Hughes545a0642011-11-08 19:10:03 -08004560 }
4561}
4562
Ian Rogers0399dde2012-06-06 17:09:28 -07004563struct AllocRecordStackVisitor : public StackVisitor {
Andreas Gampe277ccbd2014-11-03 21:36:10 -08004564 AllocRecordStackVisitor(Thread* thread, AllocRecord* record_in)
Ian Rogersb726dcb2012-09-05 08:57:23 -07004565 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_)
Andreas Gampe277ccbd2014-11-03 21:36:10 -08004566 : StackVisitor(thread, nullptr), record(record_in), depth(0) {}
Elliott Hughes545a0642011-11-08 19:10:03 -08004567
Ian Rogers00f7d0e2012-07-19 15:28:27 -07004568 // TODO: Enable annotalysis. We know lock is held in constructor, but abstraction confuses
4569 // annotalysis.
4570 bool VisitFrame() NO_THREAD_SAFETY_ANALYSIS {
Elliott Hughes545a0642011-11-08 19:10:03 -08004571 if (depth >= kMaxAllocRecordStackDepth) {
Elliott Hughes530fa002012-03-12 11:44:49 -07004572 return false;
Elliott Hughes545a0642011-11-08 19:10:03 -08004573 }
Brian Carlstromea46f952013-07-30 01:26:50 -07004574 mirror::ArtMethod* m = GetMethod();
Ian Rogers0399dde2012-06-06 17:09:28 -07004575 if (!m->IsRuntimeMethod()) {
Hiroshi Yamauchib5a9e3d2014-06-09 12:11:20 -07004576 record->StackElement(depth)->SetMethod(m);
4577 record->StackElement(depth)->SetDexPc(GetDexPc());
Elliott Hughes530fa002012-03-12 11:44:49 -07004578 ++depth;
Elliott Hughes545a0642011-11-08 19:10:03 -08004579 }
Elliott Hughes530fa002012-03-12 11:44:49 -07004580 return true;
Elliott Hughes545a0642011-11-08 19:10:03 -08004581 }
4582
4583 ~AllocRecordStackVisitor() {
4584 // Clear out any unused stack trace elements.
4585 for (; depth < kMaxAllocRecordStackDepth; ++depth) {
Hiroshi Yamauchib5a9e3d2014-06-09 12:11:20 -07004586 record->StackElement(depth)->SetMethod(nullptr);
4587 record->StackElement(depth)->SetDexPc(0);
Elliott Hughes545a0642011-11-08 19:10:03 -08004588 }
4589 }
4590
4591 AllocRecord* record;
4592 size_t depth;
4593};
4594
Ian Rogers844506b2014-09-12 19:59:33 -07004595void Dbg::RecordAllocation(Thread* self, mirror::Class* type, size_t byte_count) {
Brian Carlstrom306db812014-09-05 13:01:41 -07004596 MutexLock mu(self, *Locks::alloc_tracker_lock_);
Ian Rogersc0542af2014-09-03 16:16:56 -07004597 if (recent_allocation_records_ == nullptr) {
Brian Carlstrom306db812014-09-05 13:01:41 -07004598 // In the process of shutting down recording, bail.
Elliott Hughes545a0642011-11-08 19:10:03 -08004599 return;
4600 }
4601
4602 // Advance and clip.
Ian Rogers719d1a32014-03-06 12:13:39 -08004603 if (++alloc_record_head_ == alloc_record_max_) {
4604 alloc_record_head_ = 0;
Elliott Hughes545a0642011-11-08 19:10:03 -08004605 }
4606
4607 // Fill in the basics.
Ian Rogers719d1a32014-03-06 12:13:39 -08004608 AllocRecord* record = &recent_allocation_records_[alloc_record_head_];
Hiroshi Yamauchib5a9e3d2014-06-09 12:11:20 -07004609 record->SetType(type);
4610 record->SetByteCount(byte_count);
4611 record->SetThinLockId(self->GetThreadId());
Elliott Hughes545a0642011-11-08 19:10:03 -08004612
4613 // Fill in the stack trace.
Ian Rogers7a22fa62013-01-23 12:16:16 -08004614 AllocRecordStackVisitor visitor(self, record);
Ian Rogers0399dde2012-06-06 17:09:28 -07004615 visitor.WalkStack();
Elliott Hughes545a0642011-11-08 19:10:03 -08004616
Ian Rogers719d1a32014-03-06 12:13:39 -08004617 if (alloc_record_count_ < alloc_record_max_) {
4618 ++alloc_record_count_;
Elliott Hughes545a0642011-11-08 19:10:03 -08004619 }
4620}
4621
Elliott Hughesa8f93cb2012-06-08 17:08:48 -07004622// Returns the index of the head element.
4623//
Brian Carlstrom306db812014-09-05 13:01:41 -07004624// We point at the most-recently-written record, so if alloc_record_count_ is 1
Elliott Hughesa8f93cb2012-06-08 17:08:48 -07004625// we want to use the current element. Take "head+1" and subtract count
4626// from it.
4627//
4628// We need to handle underflow in our circular buffer, so we add
Brian Carlstrom306db812014-09-05 13:01:41 -07004629// alloc_record_max_ and then mask it back down.
Ian Rogers719d1a32014-03-06 12:13:39 -08004630size_t Dbg::HeadIndex() {
4631 return (Dbg::alloc_record_head_ + 1 + Dbg::alloc_record_max_ - Dbg::alloc_record_count_) &
4632 (Dbg::alloc_record_max_ - 1);
Elliott Hughes545a0642011-11-08 19:10:03 -08004633}
4634
4635void Dbg::DumpRecentAllocations() {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07004636 ScopedObjectAccess soa(Thread::Current());
Brian Carlstrom306db812014-09-05 13:01:41 -07004637 MutexLock mu(soa.Self(), *Locks::alloc_tracker_lock_);
Ian Rogersc0542af2014-09-03 16:16:56 -07004638 if (recent_allocation_records_ == nullptr) {
Elliott Hughes545a0642011-11-08 19:10:03 -08004639 LOG(INFO) << "Not recording tracked allocations";
4640 return;
4641 }
4642
4643 // "i" is the head of the list. We want to start at the end of the
4644 // list and move forward to the tail.
Elliott Hughesa8f93cb2012-06-08 17:08:48 -07004645 size_t i = HeadIndex();
Brian Carlstrom306db812014-09-05 13:01:41 -07004646 const uint16_t capped_count = CappedAllocRecordCount(Dbg::alloc_record_count_);
4647 uint16_t count = capped_count;
Elliott Hughes545a0642011-11-08 19:10:03 -08004648
Ian Rogers719d1a32014-03-06 12:13:39 -08004649 LOG(INFO) << "Tracked allocations, (head=" << alloc_record_head_ << " count=" << count << ")";
Elliott Hughes545a0642011-11-08 19:10:03 -08004650 while (count--) {
4651 AllocRecord* record = &recent_allocation_records_[i];
4652
Hiroshi Yamauchib5a9e3d2014-06-09 12:11:20 -07004653 LOG(INFO) << StringPrintf(" Thread %-2d %6zd bytes ", record->ThinLockId(), record->ByteCount())
4654 << PrettyClass(record->Type());
Elliott Hughes545a0642011-11-08 19:10:03 -08004655
4656 for (size_t stack_frame = 0; stack_frame < kMaxAllocRecordStackDepth; ++stack_frame) {
Hiroshi Yamauchib5a9e3d2014-06-09 12:11:20 -07004657 AllocRecordStackTraceElement* stack_element = record->StackElement(stack_frame);
4658 mirror::ArtMethod* m = stack_element->Method();
Ian Rogersc0542af2014-09-03 16:16:56 -07004659 if (m == nullptr) {
Elliott Hughes545a0642011-11-08 19:10:03 -08004660 break;
4661 }
Hiroshi Yamauchib5a9e3d2014-06-09 12:11:20 -07004662 LOG(INFO) << " " << PrettyMethod(m) << " line " << stack_element->LineNumber();
Elliott Hughes545a0642011-11-08 19:10:03 -08004663 }
4664
4665 // pause periodically to help logcat catch up
4666 if ((count % 5) == 0) {
4667 usleep(40000);
4668 }
4669
Ian Rogers719d1a32014-03-06 12:13:39 -08004670 i = (i + 1) & (alloc_record_max_ - 1);
Elliott Hughes545a0642011-11-08 19:10:03 -08004671 }
4672}
4673
4674class StringTable {
4675 public:
4676 StringTable() {
4677 }
4678
Mathieu Chartier4345c462014-06-27 10:20:14 -07004679 void Add(const std::string& str) {
4680 table_.insert(str);
4681 }
4682
4683 void Add(const char* str) {
4684 table_.insert(str);
Elliott Hughes545a0642011-11-08 19:10:03 -08004685 }
4686
Elliott Hughesa8f93cb2012-06-08 17:08:48 -07004687 size_t IndexOf(const char* s) const {
Mathieu Chartier02e25112013-08-14 16:14:24 -07004688 auto it = table_.find(s);
Elliott Hughesa8f93cb2012-06-08 17:08:48 -07004689 if (it == table_.end()) {
4690 LOG(FATAL) << "IndexOf(\"" << s << "\") failed";
4691 }
4692 return std::distance(table_.begin(), it);
Elliott Hughes545a0642011-11-08 19:10:03 -08004693 }
4694
Elliott Hughesa8f93cb2012-06-08 17:08:48 -07004695 size_t Size() const {
Elliott Hughes545a0642011-11-08 19:10:03 -08004696 return table_.size();
4697 }
4698
Elliott Hughesa8f93cb2012-06-08 17:08:48 -07004699 void WriteTo(std::vector<uint8_t>& bytes) const {
Mathieu Chartier02e25112013-08-14 16:14:24 -07004700 for (const std::string& str : table_) {
4701 const char* s = str.c_str();
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08004702 size_t s_len = CountModifiedUtf8Chars(s);
Ian Rogers700a4022014-05-19 16:49:03 -07004703 std::unique_ptr<uint16_t> s_utf16(new uint16_t[s_len]);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08004704 ConvertModifiedUtf8ToUtf16(s_utf16.get(), s);
4705 JDWP::AppendUtf16BE(bytes, s_utf16.get(), s_len);
Elliott Hughes545a0642011-11-08 19:10:03 -08004706 }
4707 }
4708
4709 private:
Elliott Hughesa8f93cb2012-06-08 17:08:48 -07004710 std::set<std::string> table_;
Elliott Hughes545a0642011-11-08 19:10:03 -08004711 DISALLOW_COPY_AND_ASSIGN(StringTable);
4712};
4713
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07004714static const char* GetMethodSourceFile(mirror::ArtMethod* method)
Sebastien Hertz280286a2014-04-28 09:26:50 +02004715 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07004716 DCHECK(method != nullptr);
4717 const char* source_file = method->GetDeclaringClassSourceFile();
Sebastien Hertz280286a2014-04-28 09:26:50 +02004718 return (source_file != nullptr) ? source_file : "";
4719}
4720
Elliott Hughes545a0642011-11-08 19:10:03 -08004721/*
4722 * The data we send to DDMS contains everything we have recorded.
4723 *
4724 * Message header (all values big-endian):
4725 * (1b) message header len (to allow future expansion); includes itself
4726 * (1b) entry header len
4727 * (1b) stack frame len
4728 * (2b) number of entries
4729 * (4b) offset to string table from start of message
4730 * (2b) number of class name strings
4731 * (2b) number of method name strings
4732 * (2b) number of source file name strings
4733 * For each entry:
4734 * (4b) total allocation size
Elliott Hughes221229c2013-01-08 18:17:50 -08004735 * (2b) thread id
Elliott Hughes545a0642011-11-08 19:10:03 -08004736 * (2b) allocated object's class name index
4737 * (1b) stack depth
4738 * For each stack frame:
4739 * (2b) method's class name
4740 * (2b) method name
4741 * (2b) method source file
4742 * (2b) line number, clipped to 32767; -2 if native; -1 if no source
4743 * (xb) class name strings
4744 * (xb) method name strings
4745 * (xb) source file strings
4746 *
4747 * As with other DDM traffic, strings are sent as a 4-byte length
4748 * followed by UTF-16 data.
4749 *
4750 * We send up 16-bit unsigned indexes into string tables. In theory there
Brian Carlstrom306db812014-09-05 13:01:41 -07004751 * can be (kMaxAllocRecordStackDepth * alloc_record_max_) unique strings in
Elliott Hughes545a0642011-11-08 19:10:03 -08004752 * each table, but in practice there should be far fewer.
4753 *
4754 * The chief reason for using a string table here is to keep the size of
4755 * the DDMS message to a minimum. This is partly to make the protocol
4756 * efficient, but also because we have to form the whole thing up all at
4757 * once in a memory buffer.
4758 *
4759 * We use separate string tables for class names, method names, and source
4760 * files to keep the indexes small. There will generally be no overlap
4761 * between the contents of these tables.
4762 */
4763jbyteArray Dbg::GetRecentAllocations() {
Ian Rogerscf7f1912014-10-22 22:06:39 -07004764 if ((false)) {
Elliott Hughes545a0642011-11-08 19:10:03 -08004765 DumpRecentAllocations();
4766 }
4767
Ian Rogers50b35e22012-10-04 10:09:15 -07004768 Thread* self = Thread::Current();
Elliott Hughes545a0642011-11-08 19:10:03 -08004769 std::vector<uint8_t> bytes;
Mathieu Chartier46e811b2013-07-10 17:09:14 -07004770 {
Brian Carlstrom306db812014-09-05 13:01:41 -07004771 MutexLock mu(self, *Locks::alloc_tracker_lock_);
Mathieu Chartier46e811b2013-07-10 17:09:14 -07004772 //
4773 // Part 1: generate string tables.
4774 //
4775 StringTable class_names;
4776 StringTable method_names;
4777 StringTable filenames;
Elliott Hughes545a0642011-11-08 19:10:03 -08004778
Brian Carlstrom306db812014-09-05 13:01:41 -07004779 const uint16_t capped_count = CappedAllocRecordCount(Dbg::alloc_record_count_);
4780 uint16_t count = capped_count;
4781 size_t idx = HeadIndex();
Mathieu Chartier46e811b2013-07-10 17:09:14 -07004782 while (count--) {
4783 AllocRecord* record = &recent_allocation_records_[idx];
Ian Rogers1ff3c982014-08-12 02:30:58 -07004784 std::string temp;
4785 class_names.Add(record->Type()->GetDescriptor(&temp));
Mathieu Chartier46e811b2013-07-10 17:09:14 -07004786 for (size_t i = 0; i < kMaxAllocRecordStackDepth; i++) {
Hiroshi Yamauchib5a9e3d2014-06-09 12:11:20 -07004787 mirror::ArtMethod* m = record->StackElement(i)->Method();
Ian Rogersc0542af2014-09-03 16:16:56 -07004788 if (m != nullptr) {
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07004789 class_names.Add(m->GetDeclaringClassDescriptor());
4790 method_names.Add(m->GetName());
4791 filenames.Add(GetMethodSourceFile(m));
Mathieu Chartier46e811b2013-07-10 17:09:14 -07004792 }
4793 }
Elliott Hughes545a0642011-11-08 19:10:03 -08004794
Ian Rogers719d1a32014-03-06 12:13:39 -08004795 idx = (idx + 1) & (alloc_record_max_ - 1);
Elliott Hughes545a0642011-11-08 19:10:03 -08004796 }
4797
Brian Carlstrom306db812014-09-05 13:01:41 -07004798 LOG(INFO) << "allocation records: " << capped_count;
Mathieu Chartier46e811b2013-07-10 17:09:14 -07004799
4800 //
4801 // Part 2: Generate the output and store it in the buffer.
4802 //
4803
4804 // (1b) message header len (to allow future expansion); includes itself
4805 // (1b) entry header len
4806 // (1b) stack frame len
4807 const int kMessageHeaderLen = 15;
4808 const int kEntryHeaderLen = 9;
4809 const int kStackFrameLen = 8;
4810 JDWP::Append1BE(bytes, kMessageHeaderLen);
4811 JDWP::Append1BE(bytes, kEntryHeaderLen);
4812 JDWP::Append1BE(bytes, kStackFrameLen);
4813
4814 // (2b) number of entries
4815 // (4b) offset to string table from start of message
4816 // (2b) number of class name strings
4817 // (2b) number of method name strings
4818 // (2b) number of source file name strings
Brian Carlstrom306db812014-09-05 13:01:41 -07004819 JDWP::Append2BE(bytes, capped_count);
Mathieu Chartier46e811b2013-07-10 17:09:14 -07004820 size_t string_table_offset = bytes.size();
Brian Carlstrom7934ac22013-07-26 10:54:15 -07004821 JDWP::Append4BE(bytes, 0); // We'll patch this later...
Mathieu Chartier46e811b2013-07-10 17:09:14 -07004822 JDWP::Append2BE(bytes, class_names.Size());
4823 JDWP::Append2BE(bytes, method_names.Size());
4824 JDWP::Append2BE(bytes, filenames.Size());
4825
Mathieu Chartier46e811b2013-07-10 17:09:14 -07004826 idx = HeadIndex();
Ian Rogers1ff3c982014-08-12 02:30:58 -07004827 std::string temp;
Brian Carlstrom306db812014-09-05 13:01:41 -07004828 for (count = capped_count; count != 0; --count) {
Mathieu Chartier46e811b2013-07-10 17:09:14 -07004829 // For each entry:
4830 // (4b) total allocation size
4831 // (2b) thread id
4832 // (2b) allocated object's class name index
4833 // (1b) stack depth
4834 AllocRecord* record = &recent_allocation_records_[idx];
4835 size_t stack_depth = record->GetDepth();
Mathieu Chartierf8322842014-05-16 10:59:25 -07004836 size_t allocated_object_class_name_index =
Ian Rogers1ff3c982014-08-12 02:30:58 -07004837 class_names.IndexOf(record->Type()->GetDescriptor(&temp));
Hiroshi Yamauchib5a9e3d2014-06-09 12:11:20 -07004838 JDWP::Append4BE(bytes, record->ByteCount());
4839 JDWP::Append2BE(bytes, record->ThinLockId());
Mathieu Chartier46e811b2013-07-10 17:09:14 -07004840 JDWP::Append2BE(bytes, allocated_object_class_name_index);
4841 JDWP::Append1BE(bytes, stack_depth);
4842
Mathieu Chartier46e811b2013-07-10 17:09:14 -07004843 for (size_t stack_frame = 0; stack_frame < stack_depth; ++stack_frame) {
4844 // For each stack frame:
4845 // (2b) method's class name
4846 // (2b) method name
4847 // (2b) method source file
4848 // (2b) line number, clipped to 32767; -2 if native; -1 if no source
Hiroshi Yamauchib5a9e3d2014-06-09 12:11:20 -07004849 mirror::ArtMethod* m = record->StackElement(stack_frame)->Method();
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07004850 size_t class_name_index = class_names.IndexOf(m->GetDeclaringClassDescriptor());
4851 size_t method_name_index = method_names.IndexOf(m->GetName());
4852 size_t file_name_index = filenames.IndexOf(GetMethodSourceFile(m));
Mathieu Chartier46e811b2013-07-10 17:09:14 -07004853 JDWP::Append2BE(bytes, class_name_index);
4854 JDWP::Append2BE(bytes, method_name_index);
4855 JDWP::Append2BE(bytes, file_name_index);
Hiroshi Yamauchib5a9e3d2014-06-09 12:11:20 -07004856 JDWP::Append2BE(bytes, record->StackElement(stack_frame)->LineNumber());
Mathieu Chartier46e811b2013-07-10 17:09:14 -07004857 }
Ian Rogers719d1a32014-03-06 12:13:39 -08004858 idx = (idx + 1) & (alloc_record_max_ - 1);
Mathieu Chartier46e811b2013-07-10 17:09:14 -07004859 }
4860
4861 // (xb) class name strings
4862 // (xb) method name strings
4863 // (xb) source file strings
4864 JDWP::Set4BE(&bytes[string_table_offset], bytes.size());
4865 class_names.WriteTo(bytes);
4866 method_names.WriteTo(bytes);
4867 filenames.WriteTo(bytes);
Elliott Hughes545a0642011-11-08 19:10:03 -08004868 }
Ian Rogers50b35e22012-10-04 10:09:15 -07004869 JNIEnv* env = self->GetJniEnv();
Elliott Hughes545a0642011-11-08 19:10:03 -08004870 jbyteArray result = env->NewByteArray(bytes.size());
Ian Rogersc0542af2014-09-03 16:16:56 -07004871 if (result != nullptr) {
Elliott Hughes545a0642011-11-08 19:10:03 -08004872 env->SetByteArrayRegion(result, 0, bytes.size(), reinterpret_cast<const jbyte*>(&bytes[0]));
4873 }
4874 return result;
4875}
4876
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07004877mirror::ArtMethod* DeoptimizationRequest::Method() const {
4878 ScopedObjectAccessUnchecked soa(Thread::Current());
4879 return soa.DecodeMethod(method_);
4880}
4881
4882void DeoptimizationRequest::SetMethod(mirror::ArtMethod* m) {
4883 ScopedObjectAccessUnchecked soa(Thread::Current());
4884 method_ = soa.EncodeMethod(m);
4885}
4886
Elliott Hughes872d4ec2011-10-21 17:07:15 -07004887} // namespace art