blob: 349700a1b8d98ca09fc83497aa02ff159f6bef3e [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"
Ian Rogers6d4d9fc2011-11-30 16:24:48 -080042#include "object_utils.h"
Sebastien Hertza76a6d42014-03-20 16:40:17 +010043#include "quick/inline_method_analyser.h"
Ian Rogers53b8b092014-03-13 23:45:53 -070044#include "reflection.h"
Elliott Hughesa0e18062012-04-13 15:59:59 -070045#include "safe_map.h"
Elliott Hughes64f574f2013-02-20 14:57:12 -080046#include "scoped_thread_state_change.h"
Elliott Hughes6a5bd492011-10-28 14:33:57 -070047#include "ScopedLocalRef.h"
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -070048#include "ScopedPrimitiveArray.h"
Mathieu Chartiereb8167a2014-05-07 15:43:14 -070049#include "handle_scope-inl.h"
Elliott Hughes475fc232011-10-25 15:00:35 -070050#include "thread_list.h"
Ian Rogers62d6c772013-02-27 08:32:07 -080051#include "throw_location.h"
Ian Rogers2dd0e2c2013-01-24 12:42:14 -080052#include "utf.h"
Sebastien Hertza76a6d42014-03-20 16:40:17 +010053#include "verifier/method_verifier-inl.h"
Elliott Hugheseac76672012-05-24 21:56:51 -070054#include "well_known_classes.h"
Elliott Hughes475fc232011-10-25 15:00:35 -070055
Brian Carlstrom3d92d522013-07-12 09:03:08 -070056#ifdef HAVE_ANDROID_OS
57#include "cutils/properties.h"
58#endif
59
Elliott Hughes872d4ec2011-10-21 17:07:15 -070060namespace art {
61
Brian Carlstrom7934ac22013-07-26 10:54:15 -070062static const size_t kMaxAllocRecordStackDepth = 16; // Max 255.
63static const size_t kDefaultNumAllocRecords = 64*1024; // Must be a power of 2.
Elliott Hughes475fc232011-10-25 15:00:35 -070064
Hiroshi Yamauchib5a9e3d2014-06-09 12:11:20 -070065class AllocRecordStackTraceElement {
66 public:
67 AllocRecordStackTraceElement() : method_(nullptr), dex_pc_(0) {
Mathieu Chartier412c7fc2014-02-07 12:18:39 -080068 }
69
Hiroshi Yamauchib5a9e3d2014-06-09 12:11:20 -070070 int32_t LineNumber() SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
71 mirror::ArtMethod* method = Method();
72 DCHECK(method != nullptr);
73 return method->GetLineNumFromDexPC(DexPc());
Elliott Hughes545a0642011-11-08 19:10:03 -080074 }
Hiroshi Yamauchib5a9e3d2014-06-09 12:11:20 -070075
76 mirror::ArtMethod* Method() SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
77 mirror::ArtMethod* method = reinterpret_cast<mirror::ArtMethod*>(
78 Thread::Current()->DecodeJObject(method_));
79 return method;
80 }
81
82 void SetMethod(mirror::ArtMethod* m) SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
83 ScopedObjectAccessUnchecked soa(Thread::Current());
84 JNIEnv* env = soa.Env();
85 if (method_ != nullptr) {
86 env->DeleteWeakGlobalRef(method_);
87 }
88 method_ = env->NewWeakGlobalRef(soa.AddLocalReference<jobject>(m));
89 }
90
91 uint32_t DexPc() const {
92 return dex_pc_;
93 }
94
95 void SetDexPc(uint32_t pc) {
96 dex_pc_ = pc;
97 }
98
99 private:
100 jobject method_; // This is a weak global.
101 uint32_t dex_pc_;
Elliott Hughes545a0642011-11-08 19:10:03 -0800102};
103
Hiroshi Yamauchib5a9e3d2014-06-09 12:11:20 -0700104class AllocRecord {
105 public:
106 AllocRecord() : type_(nullptr), byte_count_(0), thin_lock_id_(0) {}
Elliott Hughes545a0642011-11-08 19:10:03 -0800107
Hiroshi Yamauchib5a9e3d2014-06-09 12:11:20 -0700108 mirror::Class* Type() SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
109 mirror::Class* type = reinterpret_cast<mirror::Class*>(
110 Thread::Current()->DecodeJObject(type_));
111 return type;
112 }
113
114 void SetType(mirror::Class* t) SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
115 ScopedObjectAccessUnchecked soa(Thread::Current());
116 JNIEnv* env = soa.Env();
117 if (type_ != nullptr) {
118 env->DeleteWeakGlobalRef(type_);
119 }
120 type_ = env->NewWeakGlobalRef(soa.AddLocalReference<jobject>(t));
121 }
122
123 size_t GetDepth() SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Elliott Hughes545a0642011-11-08 19:10:03 -0800124 size_t depth = 0;
Hiroshi Yamauchib5a9e3d2014-06-09 12:11:20 -0700125 while (depth < kMaxAllocRecordStackDepth && stack_[depth].Method() != NULL) {
Elliott Hughes545a0642011-11-08 19:10:03 -0800126 ++depth;
127 }
128 return depth;
129 }
Mathieu Chartier412c7fc2014-02-07 12:18:39 -0800130
Hiroshi Yamauchib5a9e3d2014-06-09 12:11:20 -0700131 size_t ByteCount() const {
132 return byte_count_;
Mathieu Chartier412c7fc2014-02-07 12:18:39 -0800133 }
Hiroshi Yamauchib5a9e3d2014-06-09 12:11:20 -0700134
135 void SetByteCount(size_t count) {
136 byte_count_ = count;
137 }
138
139 uint16_t ThinLockId() const {
140 return thin_lock_id_;
141 }
142
143 void SetThinLockId(uint16_t id) {
144 thin_lock_id_ = id;
145 }
146
147 AllocRecordStackTraceElement* StackElement(size_t index) {
148 DCHECK_LT(index, kMaxAllocRecordStackDepth);
149 return &stack_[index];
150 }
151
152 private:
153 jobject type_; // This is a weak global.
154 size_t byte_count_;
155 uint16_t thin_lock_id_;
156 AllocRecordStackTraceElement stack_[kMaxAllocRecordStackDepth]; // Unused entries have NULL method.
Elliott Hughes545a0642011-11-08 19:10:03 -0800157};
158
Elliott Hughes86964332012-02-15 19:37:42 -0800159struct Breakpoint {
Sebastien Hertza76a6d42014-03-20 16:40:17 +0100160 // The location of this breakpoint.
Brian Carlstromea46f952013-07-30 01:26:50 -0700161 mirror::ArtMethod* method;
Elliott Hughesa656a0f2012-02-21 18:03:44 -0800162 uint32_t dex_pc;
Sebastien Hertza76a6d42014-03-20 16:40:17 +0100163
164 // Indicates whether breakpoint needs full deoptimization or selective deoptimization.
165 bool need_full_deoptimization;
166
167 Breakpoint(mirror::ArtMethod* method, uint32_t dex_pc, bool need_full_deoptimization)
168 : method(method), dex_pc(dex_pc), need_full_deoptimization(need_full_deoptimization) {}
Mathieu Chartier3b05e9b2014-03-25 09:29:43 -0700169
170 void VisitRoots(RootCallback* callback, void* arg) {
171 if (method != nullptr) {
172 callback(reinterpret_cast<mirror::Object**>(&method), arg, 0, kRootDebugger);
173 }
174 }
Elliott Hughes86964332012-02-15 19:37:42 -0800175};
176
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700177static std::ostream& operator<<(std::ostream& os, const Breakpoint& rhs)
Ian Rogersb726dcb2012-09-05 08:57:23 -0700178 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Elliott Hughes229feb72012-02-23 13:33:29 -0800179 os << StringPrintf("Breakpoint[%s @%#x]", PrettyMethod(rhs.method).c_str(), rhs.dex_pc);
Elliott Hughes86964332012-02-15 19:37:42 -0800180 return os;
181}
182
Sebastien Hertz3f52eaf2014-04-04 17:50:18 +0200183class DebugInstrumentationListener FINAL : public instrumentation::InstrumentationListener {
Ian Rogers62d6c772013-02-27 08:32:07 -0800184 public:
185 DebugInstrumentationListener() {}
186 virtual ~DebugInstrumentationListener() {}
187
Sebastien Hertz3f52eaf2014-04-04 17:50:18 +0200188 void MethodEntered(Thread* thread, mirror::Object* this_object, mirror::ArtMethod* method,
189 uint32_t dex_pc)
190 OVERRIDE SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Ian Rogers62d6c772013-02-27 08:32:07 -0800191 if (method->IsNative()) {
192 // TODO: post location events is a suspension point and native method entry stubs aren't.
193 return;
194 }
Sebastien Hertz8379b222014-02-24 17:38:15 +0100195 Dbg::UpdateDebugger(thread, this_object, method, 0, Dbg::kMethodEntry, nullptr);
Ian Rogers62d6c772013-02-27 08:32:07 -0800196 }
197
Sebastien Hertz3f52eaf2014-04-04 17:50:18 +0200198 void MethodExited(Thread* thread, mirror::Object* this_object, mirror::ArtMethod* method,
199 uint32_t dex_pc, const JValue& return_value)
200 OVERRIDE SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Ian Rogers62d6c772013-02-27 08:32:07 -0800201 if (method->IsNative()) {
202 // TODO: post location events is a suspension point and native method entry stubs aren't.
203 return;
204 }
Sebastien Hertz8379b222014-02-24 17:38:15 +0100205 Dbg::UpdateDebugger(thread, this_object, method, dex_pc, Dbg::kMethodExit, &return_value);
Ian Rogers62d6c772013-02-27 08:32:07 -0800206 }
207
Sebastien Hertz3f52eaf2014-04-04 17:50:18 +0200208 void MethodUnwind(Thread* thread, mirror::Object* this_object, mirror::ArtMethod* method,
209 uint32_t dex_pc)
210 OVERRIDE SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Ian Rogers62d6c772013-02-27 08:32:07 -0800211 // We're not recorded to listen to this kind of event, so complain.
212 LOG(ERROR) << "Unexpected method unwind event in debugger " << PrettyMethod(method)
Sebastien Hertz51db44a2013-11-19 10:00:29 +0100213 << " " << dex_pc;
Ian Rogers62d6c772013-02-27 08:32:07 -0800214 }
215
Sebastien Hertz3f52eaf2014-04-04 17:50:18 +0200216 void DexPcMoved(Thread* thread, mirror::Object* this_object, mirror::ArtMethod* method,
217 uint32_t new_dex_pc)
218 OVERRIDE SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Sebastien Hertz8379b222014-02-24 17:38:15 +0100219 Dbg::UpdateDebugger(thread, this_object, method, new_dex_pc, 0, nullptr);
Ian Rogers62d6c772013-02-27 08:32:07 -0800220 }
221
Sebastien Hertz3f52eaf2014-04-04 17:50:18 +0200222 void FieldRead(Thread* thread, mirror::Object* this_object, mirror::ArtMethod* method,
223 uint32_t dex_pc, mirror::ArtField* field)
224 OVERRIDE SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
225 Dbg::PostFieldAccessEvent(method, dex_pc, this_object, field);
Ian Rogers62d6c772013-02-27 08:32:07 -0800226 }
Sebastien Hertz3f52eaf2014-04-04 17:50:18 +0200227
228 void FieldWritten(Thread* thread, mirror::Object* this_object, mirror::ArtMethod* method,
229 uint32_t dex_pc, mirror::ArtField* field, const JValue& field_value)
230 OVERRIDE SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
231 Dbg::PostFieldModificationEvent(method, dex_pc, this_object, field, &field_value);
232 }
233
234 void ExceptionCaught(Thread* thread, const ThrowLocation& throw_location,
235 mirror::ArtMethod* catch_method, uint32_t catch_dex_pc,
236 mirror::Throwable* exception_object)
237 OVERRIDE SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
238 Dbg::PostException(throw_location, catch_method, catch_dex_pc, exception_object);
239 }
240
241 private:
242 DISALLOW_COPY_AND_ASSIGN(DebugInstrumentationListener);
Ian Rogers62d6c772013-02-27 08:32:07 -0800243} gDebugInstrumentationListener;
244
Elliott Hughes4ffd3132011-10-24 12:06:42 -0700245// JDWP is allowed unless the Zygote forbids it.
246static bool gJdwpAllowed = true;
247
Elliott Hughesc0f09332012-03-26 13:27:06 -0700248// Was there a -Xrunjdwp or -agentlib:jdwp= argument on the command line?
Elliott Hughes3bb81562011-10-21 18:52:59 -0700249static bool gJdwpConfigured = false;
250
Elliott Hughesc0f09332012-03-26 13:27:06 -0700251// Broken-down JDWP options. (Only valid if IsJdwpConfigured() is true.)
Elliott Hughes376a7a02011-10-24 18:35:55 -0700252static JDWP::JdwpOptions gJdwpOptions;
Elliott Hughes3bb81562011-10-21 18:52:59 -0700253
254// Runtime JDWP state.
255static JDWP::JdwpState* gJdwpState = NULL;
256static bool gDebuggerConnected; // debugger or DDMS is connected.
257static bool gDebuggerActive; // debugger is making requests.
Elliott Hughes86964332012-02-15 19:37:42 -0800258static bool gDisposed; // debugger called VirtualMachine.Dispose, so we should drop the connection.
Elliott Hughes3bb81562011-10-21 18:52:59 -0700259
Elliott Hughes47fce012011-10-25 18:37:19 -0700260static bool gDdmThreadNotification = false;
261
Elliott Hughes767a1472011-10-26 18:49:02 -0700262// DDMS GC-related settings.
263static Dbg::HpifWhen gDdmHpifWhen = Dbg::HPIF_WHEN_NEVER;
264static Dbg::HpsgWhen gDdmHpsgWhen = Dbg::HPSG_WHEN_NEVER;
265static Dbg::HpsgWhat gDdmHpsgWhat;
266static Dbg::HpsgWhen gDdmNhsgWhen = Dbg::HPSG_WHEN_NEVER;
267static Dbg::HpsgWhat gDdmNhsgWhat;
268
Ian Rogers719d1a32014-03-06 12:13:39 -0800269static ObjectRegistry* gRegistry = nullptr;
Elliott Hughes475fc232011-10-25 15:00:35 -0700270
Elliott Hughes545a0642011-11-08 19:10:03 -0800271// Recent allocation tracking.
Ian Rogers719d1a32014-03-06 12:13:39 -0800272Mutex* Dbg::alloc_tracker_lock_ = nullptr;
273AllocRecord* Dbg::recent_allocation_records_ = nullptr; // TODO: CircularBuffer<AllocRecord>
274size_t Dbg::alloc_record_max_ = 0;
275size_t Dbg::alloc_record_head_ = 0;
276size_t Dbg::alloc_record_count_ = 0;
Elliott Hughes545a0642011-11-08 19:10:03 -0800277
Sebastien Hertz138dbfc2013-12-04 18:15:25 +0100278// Deoptimization support.
Sebastien Hertz4d25df32014-03-21 17:44:46 +0100279Mutex* Dbg::deoptimization_lock_ = nullptr;
280std::vector<DeoptimizationRequest> Dbg::deoptimization_requests_;
281size_t Dbg::full_deoptimization_event_count_ = 0;
Sebastien Hertz7ec2f1c2014-03-27 20:06:47 +0100282size_t Dbg::delayed_full_undeoptimization_count_ = 0;
Sebastien Hertz138dbfc2013-12-04 18:15:25 +0100283
Sebastien Hertz42cd43f2014-05-13 14:15:41 +0200284// Instrumentation event reference counters.
285size_t Dbg::dex_pc_change_event_ref_count_ = 0;
286size_t Dbg::method_enter_event_ref_count_ = 0;
287size_t Dbg::method_exit_event_ref_count_ = 0;
288size_t Dbg::field_read_event_ref_count_ = 0;
289size_t Dbg::field_write_event_ref_count_ = 0;
290size_t Dbg::exception_catch_event_ref_count_ = 0;
291uint32_t Dbg::instrumentation_events_ = 0;
292
Sebastien Hertz138dbfc2013-12-04 18:15:25 +0100293// Breakpoints.
jeffhao09bfc6a2012-12-11 18:11:43 -0800294static std::vector<Breakpoint> gBreakpoints GUARDED_BY(Locks::breakpoint_lock_);
Elliott Hughes86964332012-02-15 19:37:42 -0800295
Mathieu Chartier3b05e9b2014-03-25 09:29:43 -0700296void DebugInvokeReq::VisitRoots(RootCallback* callback, void* arg, uint32_t tid,
297 RootType root_type) {
298 if (receiver != nullptr) {
299 callback(&receiver, arg, tid, root_type);
300 }
301 if (thread != nullptr) {
302 callback(&thread, arg, tid, root_type);
303 }
304 if (klass != nullptr) {
305 callback(reinterpret_cast<mirror::Object**>(&klass), arg, tid, root_type);
306 }
307 if (method != nullptr) {
308 callback(reinterpret_cast<mirror::Object**>(&method), arg, tid, root_type);
309 }
310}
311
Sebastien Hertzbb43b432014-04-14 11:59:08 +0200312void DebugInvokeReq::Clear() {
313 invoke_needed = false;
314 receiver = nullptr;
315 thread = nullptr;
316 klass = nullptr;
317 method = nullptr;
318}
319
Mathieu Chartier3b05e9b2014-03-25 09:29:43 -0700320void SingleStepControl::VisitRoots(RootCallback* callback, void* arg, uint32_t tid,
321 RootType root_type) {
322 if (method != nullptr) {
323 callback(reinterpret_cast<mirror::Object**>(&method), arg, tid, root_type);
324 }
325}
326
Sebastien Hertzbb43b432014-04-14 11:59:08 +0200327bool SingleStepControl::ContainsDexPc(uint32_t dex_pc) const {
328 return dex_pcs.find(dex_pc) == dex_pcs.end();
329}
330
331void SingleStepControl::Clear() {
332 is_active = false;
333 method = nullptr;
334 dex_pcs.clear();
335}
336
Sebastien Hertz4d25df32014-03-21 17:44:46 +0100337void DeoptimizationRequest::VisitRoots(RootCallback* callback, void* arg) {
338 if (method != nullptr) {
339 callback(reinterpret_cast<mirror::Object**>(&method), arg, 0, kRootDebugger);
340 }
341}
342
Brian Carlstromea46f952013-07-30 01:26:50 -0700343static bool IsBreakpoint(const mirror::ArtMethod* m, uint32_t dex_pc)
jeffhao09bfc6a2012-12-11 18:11:43 -0800344 LOCKS_EXCLUDED(Locks::breakpoint_lock_)
Ian Rogersb726dcb2012-09-05 08:57:23 -0700345 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
jeffhao09bfc6a2012-12-11 18:11:43 -0800346 MutexLock mu(Thread::Current(), *Locks::breakpoint_lock_);
Sebastien Hertz138dbfc2013-12-04 18:15:25 +0100347 for (size_t i = 0, e = gBreakpoints.size(); i < e; ++i) {
Elliott Hughesa656a0f2012-02-21 18:03:44 -0800348 if (gBreakpoints[i].method == m && gBreakpoints[i].dex_pc == dex_pc) {
Elliott Hughes86964332012-02-15 19:37:42 -0800349 VLOG(jdwp) << "Hit breakpoint #" << i << ": " << gBreakpoints[i];
350 return true;
351 }
352 }
353 return false;
354}
355
Sebastien Hertz52d131d2014-03-13 16:17:40 +0100356static bool IsSuspendedForDebugger(ScopedObjectAccessUnchecked& soa, Thread* thread)
357 LOCKS_EXCLUDED(Locks::thread_suspend_count_lock_) {
Elliott Hughes9e0c1752013-01-09 14:02:58 -0800358 MutexLock mu(soa.Self(), *Locks::thread_suspend_count_lock_);
359 // A thread may be suspended for GC; in this code, we really want to know whether
360 // there's a debugger suspension active.
361 return thread->IsSuspended() && thread->GetDebugSuspendCount() > 0;
362}
363
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800364static mirror::Array* DecodeArray(JDWP::RefTypeId id, JDWP::JdwpError& status)
Ian Rogersb726dcb2012-09-05 08:57:23 -0700365 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800366 mirror::Object* o = gRegistry->Get<mirror::Object*>(id);
Elliott Hughes64f574f2013-02-20 14:57:12 -0800367 if (o == NULL || o == ObjectRegistry::kInvalidObject) {
Elliott Hughes436e3722012-02-17 20:01:47 -0800368 status = JDWP::ERR_INVALID_OBJECT;
369 return NULL;
370 }
371 if (!o->IsArrayInstance()) {
372 status = JDWP::ERR_INVALID_ARRAY;
373 return NULL;
374 }
375 status = JDWP::ERR_NONE;
376 return o->AsArray();
377}
378
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800379static mirror::Class* DecodeClass(JDWP::RefTypeId id, JDWP::JdwpError& status)
Ian Rogersb726dcb2012-09-05 08:57:23 -0700380 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800381 mirror::Object* o = gRegistry->Get<mirror::Object*>(id);
Elliott Hughes64f574f2013-02-20 14:57:12 -0800382 if (o == NULL || o == ObjectRegistry::kInvalidObject) {
Elliott Hughes436e3722012-02-17 20:01:47 -0800383 status = JDWP::ERR_INVALID_OBJECT;
384 return NULL;
385 }
386 if (!o->IsClass()) {
387 status = JDWP::ERR_INVALID_CLASS;
388 return NULL;
389 }
390 status = JDWP::ERR_NONE;
391 return o->AsClass();
392}
393
Elliott Hughes221229c2013-01-08 18:17:50 -0800394static JDWP::JdwpError DecodeThread(ScopedObjectAccessUnchecked& soa, JDWP::ObjectId thread_id, Thread*& thread)
jeffhaoa77f0f62012-12-05 17:19:31 -0800395 EXCLUSIVE_LOCKS_REQUIRED(Locks::thread_list_lock_)
Ian Rogersb726dcb2012-09-05 08:57:23 -0700396 LOCKS_EXCLUDED(Locks::thread_suspend_count_lock_)
397 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800398 mirror::Object* thread_peer = gRegistry->Get<mirror::Object*>(thread_id);
Elliott Hughes64f574f2013-02-20 14:57:12 -0800399 if (thread_peer == NULL || thread_peer == ObjectRegistry::kInvalidObject) {
Elliott Hughes221229c2013-01-08 18:17:50 -0800400 // This isn't even an object.
401 return JDWP::ERR_INVALID_OBJECT;
Elliott Hughes436e3722012-02-17 20:01:47 -0800402 }
Elliott Hughes221229c2013-01-08 18:17:50 -0800403
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800404 mirror::Class* java_lang_Thread = soa.Decode<mirror::Class*>(WellKnownClasses::java_lang_Thread);
Elliott Hughes221229c2013-01-08 18:17:50 -0800405 if (!java_lang_Thread->IsAssignableFrom(thread_peer->GetClass())) {
406 // This isn't a thread.
407 return JDWP::ERR_INVALID_THREAD;
408 }
409
410 thread = Thread::FromManagedThread(soa, thread_peer);
411 if (thread == NULL) {
412 // This is a java.lang.Thread without a Thread*. Must be a zombie.
413 return JDWP::ERR_THREAD_NOT_ALIVE;
414 }
415 return JDWP::ERR_NONE;
Elliott Hughes436e3722012-02-17 20:01:47 -0800416}
417
Elliott Hughes24437992011-11-30 14:49:33 -0800418static JDWP::JdwpTag BasicTagFromDescriptor(const char* descriptor) {
419 // JDWP deliberately uses the descriptor characters' ASCII values for its enum.
420 // Note that by "basic" we mean that we don't get more specific than JT_OBJECT.
421 return static_cast<JDWP::JdwpTag>(descriptor[0]);
422}
423
Ian Rogers98379392014-02-24 16:53:16 -0800424static JDWP::JdwpTag TagFromClass(const ScopedObjectAccessUnchecked& soa, mirror::Class* c)
Ian Rogersb726dcb2012-09-05 08:57:23 -0700425 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Elliott Hughes86b00102011-12-05 17:54:26 -0800426 CHECK(c != NULL);
Elliott Hughes24437992011-11-30 14:49:33 -0800427 if (c->IsArrayClass()) {
428 return JDWP::JT_ARRAY;
429 }
Elliott Hughes24437992011-11-30 14:49:33 -0800430 if (c->IsStringClass()) {
431 return JDWP::JT_STRING;
Elliott Hughes24437992011-11-30 14:49:33 -0800432 }
Ian Rogers98379392014-02-24 16:53:16 -0800433 if (c->IsClassClass()) {
434 return JDWP::JT_CLASS_OBJECT;
435 }
436 {
437 mirror::Class* thread_class = soa.Decode<mirror::Class*>(WellKnownClasses::java_lang_Thread);
438 if (thread_class->IsAssignableFrom(c)) {
439 return JDWP::JT_THREAD;
440 }
441 }
442 {
443 mirror::Class* thread_group_class =
444 soa.Decode<mirror::Class*>(WellKnownClasses::java_lang_ThreadGroup);
445 if (thread_group_class->IsAssignableFrom(c)) {
446 return JDWP::JT_THREAD_GROUP;
447 }
448 }
449 {
450 mirror::Class* class_loader_class =
451 soa.Decode<mirror::Class*>(WellKnownClasses::java_lang_ClassLoader);
452 if (class_loader_class->IsAssignableFrom(c)) {
453 return JDWP::JT_CLASS_LOADER;
454 }
455 }
456 return JDWP::JT_OBJECT;
Elliott Hughes24437992011-11-30 14:49:33 -0800457}
458
459/*
460 * Objects declared to hold Object might actually hold a more specific
461 * type. The debugger may take a special interest in these (e.g. it
462 * wants to display the contents of Strings), so we want to return an
463 * appropriate tag.
464 *
465 * Null objects are tagged JT_OBJECT.
466 */
Ian Rogers98379392014-02-24 16:53:16 -0800467static JDWP::JdwpTag TagFromObject(const ScopedObjectAccessUnchecked& soa, mirror::Object* o)
Ian Rogersb726dcb2012-09-05 08:57:23 -0700468 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Ian Rogers98379392014-02-24 16:53:16 -0800469 return (o == NULL) ? JDWP::JT_OBJECT : TagFromClass(soa, o->GetClass());
Elliott Hughes24437992011-11-30 14:49:33 -0800470}
471
472static bool IsPrimitiveTag(JDWP::JdwpTag tag) {
473 switch (tag) {
474 case JDWP::JT_BOOLEAN:
475 case JDWP::JT_BYTE:
476 case JDWP::JT_CHAR:
477 case JDWP::JT_FLOAT:
478 case JDWP::JT_DOUBLE:
479 case JDWP::JT_INT:
480 case JDWP::JT_LONG:
481 case JDWP::JT_SHORT:
482 case JDWP::JT_VOID:
483 return true;
484 default:
485 return false;
486 }
487}
488
Elliott Hughes3bb81562011-10-21 18:52:59 -0700489/*
490 * Handle one of the JDWP name/value pairs.
491 *
492 * JDWP options are:
493 * help: if specified, show help message and bail
494 * transport: may be dt_socket or dt_shmem
495 * address: for dt_socket, "host:port", or just "port" when listening
496 * server: if "y", wait for debugger to attach; if "n", attach to debugger
497 * timeout: how long to wait for debugger to connect / listen
498 *
499 * Useful with server=n (these aren't supported yet):
500 * onthrow=<exception-name>: connect to debugger when exception thrown
501 * onuncaught=y|n: connect to debugger when uncaught exception thrown
502 * launch=<command-line>: launch the debugger itself
503 *
504 * The "transport" option is required, as is "address" if server=n.
505 */
506static bool ParseJdwpOption(const std::string& name, const std::string& value) {
507 if (name == "transport") {
508 if (value == "dt_socket") {
Elliott Hughes376a7a02011-10-24 18:35:55 -0700509 gJdwpOptions.transport = JDWP::kJdwpTransportSocket;
Elliott Hughes3bb81562011-10-21 18:52:59 -0700510 } else if (value == "dt_android_adb") {
Elliott Hughes376a7a02011-10-24 18:35:55 -0700511 gJdwpOptions.transport = JDWP::kJdwpTransportAndroidAdb;
Elliott Hughes3bb81562011-10-21 18:52:59 -0700512 } else {
513 LOG(ERROR) << "JDWP transport not supported: " << value;
514 return false;
515 }
516 } else if (name == "server") {
517 if (value == "n") {
Elliott Hughes376a7a02011-10-24 18:35:55 -0700518 gJdwpOptions.server = false;
Elliott Hughes3bb81562011-10-21 18:52:59 -0700519 } else if (value == "y") {
Elliott Hughes376a7a02011-10-24 18:35:55 -0700520 gJdwpOptions.server = true;
Elliott Hughes3bb81562011-10-21 18:52:59 -0700521 } else {
522 LOG(ERROR) << "JDWP option 'server' must be 'y' or 'n'";
523 return false;
524 }
525 } else if (name == "suspend") {
526 if (value == "n") {
Elliott Hughes376a7a02011-10-24 18:35:55 -0700527 gJdwpOptions.suspend = false;
Elliott Hughes3bb81562011-10-21 18:52:59 -0700528 } else if (value == "y") {
Elliott Hughes376a7a02011-10-24 18:35:55 -0700529 gJdwpOptions.suspend = true;
Elliott Hughes3bb81562011-10-21 18:52:59 -0700530 } else {
531 LOG(ERROR) << "JDWP option 'suspend' must be 'y' or 'n'";
532 return false;
533 }
534 } else if (name == "address") {
535 /* this is either <port> or <host>:<port> */
536 std::string port_string;
Elliott Hughes376a7a02011-10-24 18:35:55 -0700537 gJdwpOptions.host.clear();
Elliott Hughes3bb81562011-10-21 18:52:59 -0700538 std::string::size_type colon = value.find(':');
539 if (colon != std::string::npos) {
Elliott Hughes376a7a02011-10-24 18:35:55 -0700540 gJdwpOptions.host = value.substr(0, colon);
Elliott Hughes3bb81562011-10-21 18:52:59 -0700541 port_string = value.substr(colon + 1);
542 } else {
543 port_string = value;
544 }
545 if (port_string.empty()) {
546 LOG(ERROR) << "JDWP address missing port: " << value;
547 return false;
548 }
549 char* end;
Elliott Hughesba8eee12012-01-24 20:25:24 -0800550 uint64_t port = strtoul(port_string.c_str(), &end, 10);
551 if (*end != '\0' || port > 0xffff) {
Elliott Hughes3bb81562011-10-21 18:52:59 -0700552 LOG(ERROR) << "JDWP address has junk in port field: " << value;
553 return false;
554 }
Elliott Hughes376a7a02011-10-24 18:35:55 -0700555 gJdwpOptions.port = port;
Elliott Hughes3bb81562011-10-21 18:52:59 -0700556 } else if (name == "launch" || name == "onthrow" || name == "oncaught" || name == "timeout") {
557 /* valid but unsupported */
558 LOG(INFO) << "Ignoring JDWP option '" << name << "'='" << value << "'";
559 } else {
560 LOG(INFO) << "Ignoring unrecognized JDWP option '" << name << "'='" << value << "'";
561 }
562
563 return true;
564}
565
566/*
567 * Parse the latter half of a -Xrunjdwp/-agentlib:jdwp= string, e.g.:
568 * "transport=dt_socket,address=8000,server=y,suspend=n"
569 */
570bool Dbg::ParseJdwpOptions(const std::string& options) {
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -0800571 VLOG(jdwp) << "ParseJdwpOptions: " << options;
Elliott Hughes47fce012011-10-25 18:37:19 -0700572
Elliott Hughes3bb81562011-10-21 18:52:59 -0700573 std::vector<std::string> pairs;
574 Split(options, ',', pairs);
575
576 for (size_t i = 0; i < pairs.size(); ++i) {
577 std::string::size_type equals = pairs[i].find('=');
578 if (equals == std::string::npos) {
579 LOG(ERROR) << "Can't parse JDWP option '" << pairs[i] << "' in '" << options << "'";
580 return false;
581 }
582 ParseJdwpOption(pairs[i].substr(0, equals), pairs[i].substr(equals + 1));
583 }
584
Elliott Hughes376a7a02011-10-24 18:35:55 -0700585 if (gJdwpOptions.transport == JDWP::kJdwpTransportUnknown) {
Elliott Hughes3bb81562011-10-21 18:52:59 -0700586 LOG(ERROR) << "Must specify JDWP transport: " << options;
587 }
Elliott Hughes376a7a02011-10-24 18:35:55 -0700588 if (!gJdwpOptions.server && (gJdwpOptions.host.empty() || gJdwpOptions.port == 0)) {
Elliott Hughes3bb81562011-10-21 18:52:59 -0700589 LOG(ERROR) << "Must specify JDWP host and port when server=n: " << options;
590 return false;
591 }
592
593 gJdwpConfigured = true;
594 return true;
595}
596
Elliott Hughesd1cc8362011-10-24 16:58:50 -0700597void Dbg::StartJdwp() {
Elliott Hughesc0f09332012-03-26 13:27:06 -0700598 if (!gJdwpAllowed || !IsJdwpConfigured()) {
Elliott Hughes376a7a02011-10-24 18:35:55 -0700599 // No JDWP for you!
600 return;
601 }
602
Ian Rogers719d1a32014-03-06 12:13:39 -0800603 CHECK(gRegistry == nullptr);
Elliott Hughes475fc232011-10-25 15:00:35 -0700604 gRegistry = new ObjectRegistry;
605
Ian Rogers719d1a32014-03-06 12:13:39 -0800606 alloc_tracker_lock_ = new Mutex("AllocTracker lock");
Sebastien Hertz4d25df32014-03-21 17:44:46 +0100607 deoptimization_lock_ = new Mutex("deoptimization lock", kDeoptimizationLock);
Elliott Hughesd1cc8362011-10-24 16:58:50 -0700608 // Init JDWP if the debugger is enabled. This may connect out to a
609 // debugger, passively listen for a debugger, or block waiting for a
610 // debugger.
Elliott Hughes376a7a02011-10-24 18:35:55 -0700611 gJdwpState = JDWP::JdwpState::Create(&gJdwpOptions);
612 if (gJdwpState == NULL) {
Elliott Hughesf8a2df72011-12-01 12:19:54 -0800613 // We probably failed because some other process has the port already, which means that
614 // if we don't abort the user is likely to think they're talking to us when they're actually
615 // talking to that other process.
Elliott Hughes3d30d9b2011-12-07 17:35:48 -0800616 LOG(FATAL) << "Debugger thread failed to initialize";
Elliott Hughesd1cc8362011-10-24 16:58:50 -0700617 }
618
619 // If a debugger has already attached, send the "welcome" message.
620 // This may cause us to suspend all threads.
Elliott Hughes376a7a02011-10-24 18:35:55 -0700621 if (gJdwpState->IsActive()) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700622 ScopedObjectAccess soa(Thread::Current());
Elliott Hughes376a7a02011-10-24 18:35:55 -0700623 if (!gJdwpState->PostVMStart()) {
Elliott Hughes3d30d9b2011-12-07 17:35:48 -0800624 LOG(WARNING) << "Failed to post 'start' message to debugger";
Elliott Hughesd1cc8362011-10-24 16:58:50 -0700625 }
626 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700627}
628
Mathieu Chartier3b05e9b2014-03-25 09:29:43 -0700629void Dbg::VisitRoots(RootCallback* callback, void* arg) {
Sebastien Hertz4d25df32014-03-21 17:44:46 +0100630 {
631 MutexLock mu(Thread::Current(), *Locks::breakpoint_lock_);
632 for (Breakpoint& bp : gBreakpoints) {
633 bp.VisitRoots(callback, arg);
634 }
635 }
636 if (deoptimization_lock_ != nullptr) { // only true if the debugger is started.
637 MutexLock mu(Thread::Current(), *deoptimization_lock_);
638 for (DeoptimizationRequest& req : deoptimization_requests_) {
639 req.VisitRoots(callback, arg);
640 }
Mathieu Chartier3b05e9b2014-03-25 09:29:43 -0700641 }
642}
643
Elliott Hughesd1cc8362011-10-24 16:58:50 -0700644void Dbg::StopJdwp() {
Sebastien Hertz0376e6b2014-02-06 18:12:59 +0100645 // Prevent the JDWP thread from processing JDWP incoming packets after we close the connection.
646 Disposed();
Elliott Hughes376a7a02011-10-24 18:35:55 -0700647 delete gJdwpState;
Ian Rogers719d1a32014-03-06 12:13:39 -0800648 gJdwpState = nullptr;
Elliott Hughes475fc232011-10-25 15:00:35 -0700649 delete gRegistry;
Ian Rogers719d1a32014-03-06 12:13:39 -0800650 gRegistry = nullptr;
651 delete alloc_tracker_lock_;
652 alloc_tracker_lock_ = nullptr;
Sebastien Hertz4d25df32014-03-21 17:44:46 +0100653 delete deoptimization_lock_;
654 deoptimization_lock_ = nullptr;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700655}
656
Elliott Hughes767a1472011-10-26 18:49:02 -0700657void Dbg::GcDidFinish() {
658 if (gDdmHpifWhen != HPIF_WHEN_NEVER) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700659 ScopedObjectAccess soa(Thread::Current());
Brian Carlstrom4d466a82014-05-08 19:05:29 -0700660 VLOG(jdwp) << "Sending heap info to DDM";
Elliott Hughes7162ad92011-10-27 14:08:42 -0700661 DdmSendHeapInfo(gDdmHpifWhen);
Elliott Hughes767a1472011-10-26 18:49:02 -0700662 }
663 if (gDdmHpsgWhen != HPSG_WHEN_NEVER) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700664 ScopedObjectAccess soa(Thread::Current());
Brian Carlstrom4d466a82014-05-08 19:05:29 -0700665 VLOG(jdwp) << "Dumping heap to DDM";
Elliott Hughes6a5bd492011-10-28 14:33:57 -0700666 DdmSendHeapSegments(false);
Elliott Hughes767a1472011-10-26 18:49:02 -0700667 }
668 if (gDdmNhsgWhen != HPSG_WHEN_NEVER) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700669 ScopedObjectAccess soa(Thread::Current());
Brian Carlstrom4d466a82014-05-08 19:05:29 -0700670 VLOG(jdwp) << "Dumping native heap to DDM";
Elliott Hughes6a5bd492011-10-28 14:33:57 -0700671 DdmSendHeapSegments(true);
Elliott Hughes767a1472011-10-26 18:49:02 -0700672 }
673}
674
Elliott Hughes4ffd3132011-10-24 12:06:42 -0700675void Dbg::SetJdwpAllowed(bool allowed) {
676 gJdwpAllowed = allowed;
677}
678
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700679DebugInvokeReq* Dbg::GetInvokeReq() {
Elliott Hughes475fc232011-10-25 15:00:35 -0700680 return Thread::Current()->GetInvokeReq();
681}
682
683Thread* Dbg::GetDebugThread() {
684 return (gJdwpState != NULL) ? gJdwpState->GetDebugThread() : NULL;
685}
686
687void Dbg::ClearWaitForEventThread() {
688 gJdwpState->ClearWaitForEventThread();
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700689}
690
691void Dbg::Connected() {
Elliott Hughes3bb81562011-10-21 18:52:59 -0700692 CHECK(!gDebuggerConnected);
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -0800693 VLOG(jdwp) << "JDWP has attached";
Elliott Hughes3bb81562011-10-21 18:52:59 -0700694 gDebuggerConnected = true;
Elliott Hughes86964332012-02-15 19:37:42 -0800695 gDisposed = false;
696}
697
698void Dbg::Disposed() {
699 gDisposed = true;
700}
701
702bool Dbg::IsDisposed() {
703 return gDisposed;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700704}
705
Elliott Hughesa2155262011-11-16 16:26:58 -0800706void Dbg::GoActive() {
707 // Enable all debugging features, including scans for breakpoints.
708 // This is a no-op if we're already active.
709 // Only called from the JDWP handler thread.
710 if (gDebuggerActive) {
711 return;
712 }
713
Elliott Hughesc0f09332012-03-26 13:27:06 -0700714 {
715 // TODO: dalvik only warned if there were breakpoints left over. clear in Dbg::Disconnected?
jeffhao09bfc6a2012-12-11 18:11:43 -0800716 MutexLock mu(Thread::Current(), *Locks::breakpoint_lock_);
Elliott Hughesc0f09332012-03-26 13:27:06 -0700717 CHECK_EQ(gBreakpoints.size(), 0U);
718 }
Elliott Hughesa2155262011-11-16 16:26:58 -0800719
Sebastien Hertz138dbfc2013-12-04 18:15:25 +0100720 {
Sebastien Hertz4d25df32014-03-21 17:44:46 +0100721 MutexLock mu(Thread::Current(), *deoptimization_lock_);
722 CHECK_EQ(deoptimization_requests_.size(), 0U);
723 CHECK_EQ(full_deoptimization_event_count_, 0U);
Sebastien Hertz7ec2f1c2014-03-27 20:06:47 +0100724 CHECK_EQ(delayed_full_undeoptimization_count_, 0U);
Sebastien Hertz42cd43f2014-05-13 14:15:41 +0200725 CHECK_EQ(dex_pc_change_event_ref_count_, 0U);
726 CHECK_EQ(method_enter_event_ref_count_, 0U);
727 CHECK_EQ(method_exit_event_ref_count_, 0U);
728 CHECK_EQ(field_read_event_ref_count_, 0U);
729 CHECK_EQ(field_write_event_ref_count_, 0U);
730 CHECK_EQ(exception_catch_event_ref_count_, 0U);
Sebastien Hertz138dbfc2013-12-04 18:15:25 +0100731 }
732
Ian Rogers62d6c772013-02-27 08:32:07 -0800733 Runtime* runtime = Runtime::Current();
734 runtime->GetThreadList()->SuspendAll();
735 Thread* self = Thread::Current();
736 ThreadState old_state = self->SetStateUnsafe(kRunnable);
737 CHECK_NE(old_state, kRunnable);
Sebastien Hertz138dbfc2013-12-04 18:15:25 +0100738 runtime->GetInstrumentation()->EnableDeoptimization();
Sebastien Hertz42cd43f2014-05-13 14:15:41 +0200739 instrumentation_events_ = 0;
Elliott Hughesa2155262011-11-16 16:26:58 -0800740 gDebuggerActive = true;
Ian Rogers62d6c772013-02-27 08:32:07 -0800741 CHECK_EQ(self->SetStateUnsafe(old_state), kRunnable);
742 runtime->GetThreadList()->ResumeAll();
743
744 LOG(INFO) << "Debugger is active";
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700745}
746
747void Dbg::Disconnected() {
Elliott Hughes234ab152011-10-26 14:02:26 -0700748 CHECK(gDebuggerConnected);
749
Elliott Hughesc0f09332012-03-26 13:27:06 -0700750 LOG(INFO) << "Debugger is no longer active";
Elliott Hughes234ab152011-10-26 14:02:26 -0700751
Ian Rogers62d6c772013-02-27 08:32:07 -0800752 // Suspend all threads and exclusively acquire the mutator lock. Set the state of the thread
753 // to kRunnable to avoid scoped object access transitions. Remove the debugger as a listener
754 // and clear the object registry.
755 Runtime* runtime = Runtime::Current();
756 runtime->GetThreadList()->SuspendAll();
757 Thread* self = Thread::Current();
758 ThreadState old_state = self->SetStateUnsafe(kRunnable);
Sebastien Hertzaaea7342014-02-25 15:10:04 +0100759
760 // Debugger may not be active at this point.
761 if (gDebuggerActive) {
762 {
763 // Since we're going to disable deoptimization, we clear the deoptimization requests queue.
764 // This prevents us from having any pending deoptimization request when the debugger attaches
765 // to us again while no event has been requested yet.
Sebastien Hertz4d25df32014-03-21 17:44:46 +0100766 MutexLock mu(Thread::Current(), *deoptimization_lock_);
767 deoptimization_requests_.clear();
768 full_deoptimization_event_count_ = 0U;
Sebastien Hertz7ec2f1c2014-03-27 20:06:47 +0100769 delayed_full_undeoptimization_count_ = 0U;
Sebastien Hertzaaea7342014-02-25 15:10:04 +0100770 }
Sebastien Hertz42cd43f2014-05-13 14:15:41 +0200771 if (instrumentation_events_ != 0) {
772 runtime->GetInstrumentation()->RemoveListener(&gDebugInstrumentationListener,
773 instrumentation_events_);
774 instrumentation_events_ = 0;
775 }
Sebastien Hertzaaea7342014-02-25 15:10:04 +0100776 runtime->GetInstrumentation()->DisableDeoptimization();
777 gDebuggerActive = false;
Sebastien Hertz138dbfc2013-12-04 18:15:25 +0100778 }
Elliott Hughes234ab152011-10-26 14:02:26 -0700779 gRegistry->Clear();
780 gDebuggerConnected = false;
Ian Rogers62d6c772013-02-27 08:32:07 -0800781 CHECK_EQ(self->SetStateUnsafe(old_state), kRunnable);
782 runtime->GetThreadList()->ResumeAll();
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700783}
784
Elliott Hughesc0f09332012-03-26 13:27:06 -0700785bool Dbg::IsDebuggerActive() {
Elliott Hughes3bb81562011-10-21 18:52:59 -0700786 return gDebuggerActive;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700787}
788
Elliott Hughesc0f09332012-03-26 13:27:06 -0700789bool Dbg::IsJdwpConfigured() {
Elliott Hughes3bb81562011-10-21 18:52:59 -0700790 return gJdwpConfigured;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700791}
792
793int64_t Dbg::LastDebuggerActivity() {
Elliott Hughesca951522011-12-05 12:01:32 -0800794 return gJdwpState->LastDebuggerActivity();
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700795}
796
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700797void Dbg::UndoDebuggerSuspensions() {
Elliott Hughes234ab152011-10-26 14:02:26 -0700798 Runtime::Current()->GetThreadList()->UndoDebuggerSuspensions();
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700799}
800
Elliott Hughes88d63092013-01-09 09:55:54 -0800801std::string Dbg::GetClassName(JDWP::RefTypeId class_id) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800802 mirror::Object* o = gRegistry->Get<mirror::Object*>(class_id);
Elliott Hughes436e3722012-02-17 20:01:47 -0800803 if (o == NULL) {
804 return "NULL";
805 }
Elliott Hughes64f574f2013-02-20 14:57:12 -0800806 if (o == ObjectRegistry::kInvalidObject) {
Elliott Hughes88d63092013-01-09 09:55:54 -0800807 return StringPrintf("invalid object %p", reinterpret_cast<void*>(class_id));
Elliott Hughes436e3722012-02-17 20:01:47 -0800808 }
809 if (!o->IsClass()) {
Brian Carlstrom7934ac22013-07-26 10:54:15 -0700810 return StringPrintf("non-class %p", o); // This is only used for debugging output anyway.
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -0800811 }
Mathieu Chartierf8322842014-05-16 10:59:25 -0700812 return DescriptorToName(o->AsClass()->GetDescriptor().c_str());
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700813}
814
Elliott Hughes88d63092013-01-09 09:55:54 -0800815JDWP::JdwpError Dbg::GetClassObject(JDWP::RefTypeId id, JDWP::ObjectId& class_object_id) {
Elliott Hughes436e3722012-02-17 20:01:47 -0800816 JDWP::JdwpError status;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800817 mirror::Class* c = DecodeClass(id, status);
Elliott Hughes436e3722012-02-17 20:01:47 -0800818 if (c == NULL) {
819 return status;
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -0800820 }
Elliott Hughes88d63092013-01-09 09:55:54 -0800821 class_object_id = gRegistry->Add(c);
Elliott Hughes436e3722012-02-17 20:01:47 -0800822 return JDWP::ERR_NONE;
Elliott Hughes86964332012-02-15 19:37:42 -0800823}
824
Elliott Hughes88d63092013-01-09 09:55:54 -0800825JDWP::JdwpError Dbg::GetSuperclass(JDWP::RefTypeId id, JDWP::RefTypeId& superclass_id) {
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -0800826 JDWP::JdwpError status;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800827 mirror::Class* c = DecodeClass(id, status);
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -0800828 if (c == NULL) {
829 return status;
830 }
831 if (c->IsInterface()) {
832 // http://code.google.com/p/android/issues/detail?id=20856
Elliott Hughes88d63092013-01-09 09:55:54 -0800833 superclass_id = 0;
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -0800834 } else {
Elliott Hughes88d63092013-01-09 09:55:54 -0800835 superclass_id = gRegistry->Add(c->GetSuperClass());
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -0800836 }
837 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700838}
839
Elliott Hughes436e3722012-02-17 20:01:47 -0800840JDWP::JdwpError Dbg::GetClassLoader(JDWP::RefTypeId id, JDWP::ExpandBuf* pReply) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800841 mirror::Object* o = gRegistry->Get<mirror::Object*>(id);
Elliott Hughes64f574f2013-02-20 14:57:12 -0800842 if (o == NULL || o == ObjectRegistry::kInvalidObject) {
Elliott Hughes436e3722012-02-17 20:01:47 -0800843 return JDWP::ERR_INVALID_OBJECT;
844 }
845 expandBufAddObjectId(pReply, gRegistry->Add(o->GetClass()->GetClassLoader()));
846 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700847}
848
Elliott Hughes436e3722012-02-17 20:01:47 -0800849JDWP::JdwpError Dbg::GetModifiers(JDWP::RefTypeId id, JDWP::ExpandBuf* pReply) {
850 JDWP::JdwpError status;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800851 mirror::Class* c = DecodeClass(id, status);
Elliott Hughes436e3722012-02-17 20:01:47 -0800852 if (c == NULL) {
853 return status;
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -0800854 }
Elliott Hughes436e3722012-02-17 20:01:47 -0800855
856 uint32_t access_flags = c->GetAccessFlags() & kAccJavaFlagsMask;
857
Yevgeny Roubande34eea2014-02-15 01:06:03 +0700858 // Set ACC_SUPER. Dex files don't contain this flag but only classes are supposed to have it set,
859 // not interfaces.
Elliott Hughes436e3722012-02-17 20:01:47 -0800860 // Class.getModifiers doesn't return it, but JDWP does, so we set it here.
Yevgeny Roubande34eea2014-02-15 01:06:03 +0700861 if ((access_flags & kAccInterface) == 0) {
862 access_flags |= kAccSuper;
863 }
Elliott Hughes436e3722012-02-17 20:01:47 -0800864
865 expandBufAdd4BE(pReply, access_flags);
866
867 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700868}
869
Elliott Hughesf327e072013-01-09 16:01:26 -0800870JDWP::JdwpError Dbg::GetMonitorInfo(JDWP::ObjectId object_id, JDWP::ExpandBuf* reply)
871 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800872 mirror::Object* o = gRegistry->Get<mirror::Object*>(object_id);
Elliott Hughes64f574f2013-02-20 14:57:12 -0800873 if (o == NULL || o == ObjectRegistry::kInvalidObject) {
Elliott Hughesf327e072013-01-09 16:01:26 -0800874 return JDWP::ERR_INVALID_OBJECT;
875 }
876
877 // Ensure all threads are suspended while we read objects' lock words.
878 Thread* self = Thread::Current();
Sebastien Hertz54263242014-03-19 18:16:50 +0100879 CHECK_EQ(self->GetState(), kRunnable);
880 self->TransitionFromRunnableToSuspended(kSuspended);
881 Runtime::Current()->GetThreadList()->SuspendAll();
Elliott Hughesf327e072013-01-09 16:01:26 -0800882
883 MonitorInfo monitor_info(o);
884
Sebastien Hertz54263242014-03-19 18:16:50 +0100885 Runtime::Current()->GetThreadList()->ResumeAll();
886 self->TransitionFromSuspendedToRunnable();
Elliott Hughesf327e072013-01-09 16:01:26 -0800887
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700888 if (monitor_info.owner_ != NULL) {
889 expandBufAddObjectId(reply, gRegistry->Add(monitor_info.owner_->GetPeer()));
Elliott Hughesf327e072013-01-09 16:01:26 -0800890 } else {
891 expandBufAddObjectId(reply, gRegistry->Add(NULL));
892 }
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700893 expandBufAdd4BE(reply, monitor_info.entry_count_);
894 expandBufAdd4BE(reply, monitor_info.waiters_.size());
895 for (size_t i = 0; i < monitor_info.waiters_.size(); ++i) {
896 expandBufAddObjectId(reply, gRegistry->Add(monitor_info.waiters_[i]->GetPeer()));
Elliott Hughesf327e072013-01-09 16:01:26 -0800897 }
898 return JDWP::ERR_NONE;
899}
900
Elliott Hughes734b8c62013-01-11 15:32:45 -0800901JDWP::JdwpError Dbg::GetOwnedMonitors(JDWP::ObjectId thread_id,
902 std::vector<JDWP::ObjectId>& monitors,
Sebastien Hertz52d131d2014-03-13 16:17:40 +0100903 std::vector<uint32_t>& stack_depths) {
Elliott Hughes4993bbc2013-01-10 15:41:25 -0800904 struct OwnedMonitorVisitor : public StackVisitor {
Hiroshi Yamauchib5a9e3d2014-06-09 12:11:20 -0700905 OwnedMonitorVisitor(Thread* thread, Context* context,
906 std::vector<mirror::Object*>* monitor_vector,
907 std::vector<uint32_t>* stack_depth_vector)
Elliott Hughes4993bbc2013-01-10 15:41:25 -0800908 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_)
Hiroshi Yamauchib5a9e3d2014-06-09 12:11:20 -0700909 : StackVisitor(thread, context), current_stack_depth(0),
910 monitors(monitor_vector), stack_depths(stack_depth_vector) {}
Elliott Hughes4993bbc2013-01-10 15:41:25 -0800911
912 // TODO: Enable annotalysis. We know lock is held in constructor, but abstraction confuses
913 // annotalysis.
914 bool VisitFrame() NO_THREAD_SAFETY_ANALYSIS {
915 if (!GetMethod()->IsRuntimeMethod()) {
916 Monitor::VisitLocks(this, AppendOwnedMonitors, this);
Elliott Hughes734b8c62013-01-11 15:32:45 -0800917 ++current_stack_depth;
Elliott Hughes4993bbc2013-01-10 15:41:25 -0800918 }
919 return true;
920 }
921
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800922 static void AppendOwnedMonitors(mirror::Object* owned_monitor, void* arg) {
Ian Rogers7a22fa62013-01-23 12:16:16 -0800923 OwnedMonitorVisitor* visitor = reinterpret_cast<OwnedMonitorVisitor*>(arg);
Hiroshi Yamauchib5a9e3d2014-06-09 12:11:20 -0700924 visitor->monitors->push_back(owned_monitor);
925 visitor->stack_depths->push_back(visitor->current_stack_depth);
Elliott Hughes4993bbc2013-01-10 15:41:25 -0800926 }
927
Elliott Hughes734b8c62013-01-11 15:32:45 -0800928 size_t current_stack_depth;
Hiroshi Yamauchib5a9e3d2014-06-09 12:11:20 -0700929 std::vector<mirror::Object*>* monitors;
930 std::vector<uint32_t>* stack_depths;
Elliott Hughes4993bbc2013-01-10 15:41:25 -0800931 };
Elliott Hughes4993bbc2013-01-10 15:41:25 -0800932
Hiroshi Yamauchib5a9e3d2014-06-09 12:11:20 -0700933 std::vector<mirror::Object*> monitor_vector;
934 std::vector<uint32_t> stack_depth_vector;
935 ScopedObjectAccessUnchecked soa(Thread::Current());
936 {
937 MutexLock mu(soa.Self(), *Locks::thread_list_lock_);
938 Thread* thread;
939 JDWP::JdwpError error = DecodeThread(soa, thread_id, thread);
940 if (error != JDWP::ERR_NONE) {
941 return error;
942 }
943 if (!IsSuspendedForDebugger(soa, thread)) {
944 return JDWP::ERR_THREAD_NOT_SUSPENDED;
945 }
946 std::unique_ptr<Context> context(Context::Create());
947 OwnedMonitorVisitor visitor(thread, context.get(), &monitor_vector, &stack_depth_vector);
948 visitor.WalkStack();
949 }
950
951 // Add() requires the thread_list_lock_ not held to avoid the lock
952 // level violation.
953 for (size_t i = 0; i < monitor_vector.size(); ++i) {
954 monitors.push_back(gRegistry->Add(monitor_vector[i]));
955 stack_depths.push_back(stack_depth_vector[i]);
Elliott Hughes4993bbc2013-01-10 15:41:25 -0800956 }
957
958 return JDWP::ERR_NONE;
959}
960
Sebastien Hertz52d131d2014-03-13 16:17:40 +0100961JDWP::JdwpError Dbg::GetContendedMonitor(JDWP::ObjectId thread_id,
962 JDWP::ObjectId& contended_monitor) {
Hiroshi Yamauchib5a9e3d2014-06-09 12:11:20 -0700963 mirror::Object* contended_monitor_obj;
Elliott Hughesf9501702013-01-11 11:22:27 -0800964 ScopedObjectAccessUnchecked soa(Thread::Current());
Hiroshi Yamauchib5a9e3d2014-06-09 12:11:20 -0700965 {
966 MutexLock mu(soa.Self(), *Locks::thread_list_lock_);
967 Thread* thread;
968 JDWP::JdwpError error = DecodeThread(soa, thread_id, thread);
969 if (error != JDWP::ERR_NONE) {
970 return error;
971 }
972 if (!IsSuspendedForDebugger(soa, thread)) {
973 return JDWP::ERR_THREAD_NOT_SUSPENDED;
974 }
975 contended_monitor_obj = Monitor::GetContendedMonitor(thread);
Elliott Hughesf9501702013-01-11 11:22:27 -0800976 }
Hiroshi Yamauchib5a9e3d2014-06-09 12:11:20 -0700977 // Add() requires the thread_list_lock_ not held to avoid the lock
978 // level violation.
979 contended_monitor = gRegistry->Add(contended_monitor_obj);
Elliott Hughesf9501702013-01-11 11:22:27 -0800980 return JDWP::ERR_NONE;
981}
982
Elliott Hughesec0f83d2013-01-15 16:54:08 -0800983JDWP::JdwpError Dbg::GetInstanceCounts(const std::vector<JDWP::RefTypeId>& class_ids,
984 std::vector<uint64_t>& counts)
985 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Mathieu Chartier412c7fc2014-02-07 12:18:39 -0800986 gc::Heap* heap = Runtime::Current()->GetHeap();
987 heap->CollectGarbage(false);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800988 std::vector<mirror::Class*> classes;
Elliott Hughesec0f83d2013-01-15 16:54:08 -0800989 counts.clear();
990 for (size_t i = 0; i < class_ids.size(); ++i) {
991 JDWP::JdwpError status;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800992 mirror::Class* c = DecodeClass(class_ids[i], status);
Elliott Hughesec0f83d2013-01-15 16:54:08 -0800993 if (c == NULL) {
994 return status;
995 }
996 classes.push_back(c);
997 counts.push_back(0);
998 }
Mathieu Chartier412c7fc2014-02-07 12:18:39 -0800999 heap->CountInstances(classes, false, &counts[0]);
Elliott Hughesec0f83d2013-01-15 16:54:08 -08001000 return JDWP::ERR_NONE;
1001}
1002
Elliott Hughes3b78c942013-01-15 17:35:41 -08001003JDWP::JdwpError Dbg::GetInstances(JDWP::RefTypeId class_id, int32_t max_count, std::vector<JDWP::ObjectId>& instances)
1004 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Mathieu Chartier412c7fc2014-02-07 12:18:39 -08001005 gc::Heap* heap = Runtime::Current()->GetHeap();
1006 // We only want reachable instances, so do a GC.
1007 heap->CollectGarbage(false);
Elliott Hughes3b78c942013-01-15 17:35:41 -08001008 JDWP::JdwpError status;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001009 mirror::Class* c = DecodeClass(class_id, status);
Mathieu Chartier412c7fc2014-02-07 12:18:39 -08001010 if (c == nullptr) {
Elliott Hughes3b78c942013-01-15 17:35:41 -08001011 return status;
1012 }
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001013 std::vector<mirror::Object*> raw_instances;
Elliott Hughes3b78c942013-01-15 17:35:41 -08001014 Runtime::Current()->GetHeap()->GetInstances(c, max_count, raw_instances);
1015 for (size_t i = 0; i < raw_instances.size(); ++i) {
1016 instances.push_back(gRegistry->Add(raw_instances[i]));
1017 }
1018 return JDWP::ERR_NONE;
1019}
1020
Elliott Hughes0cbaff52013-01-16 15:28:01 -08001021JDWP::JdwpError Dbg::GetReferringObjects(JDWP::ObjectId object_id, int32_t max_count,
1022 std::vector<JDWP::ObjectId>& referring_objects)
1023 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Mathieu Chartier412c7fc2014-02-07 12:18:39 -08001024 gc::Heap* heap = Runtime::Current()->GetHeap();
1025 heap->CollectGarbage(false);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001026 mirror::Object* o = gRegistry->Get<mirror::Object*>(object_id);
Elliott Hughes64f574f2013-02-20 14:57:12 -08001027 if (o == NULL || o == ObjectRegistry::kInvalidObject) {
Elliott Hughes0cbaff52013-01-16 15:28:01 -08001028 return JDWP::ERR_INVALID_OBJECT;
1029 }
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001030 std::vector<mirror::Object*> raw_instances;
Mathieu Chartier412c7fc2014-02-07 12:18:39 -08001031 heap->GetReferringObjects(o, max_count, raw_instances);
Elliott Hughes0cbaff52013-01-16 15:28:01 -08001032 for (size_t i = 0; i < raw_instances.size(); ++i) {
1033 referring_objects.push_back(gRegistry->Add(raw_instances[i]));
1034 }
1035 return JDWP::ERR_NONE;
1036}
1037
Elliott Hughes64f574f2013-02-20 14:57:12 -08001038JDWP::JdwpError Dbg::DisableCollection(JDWP::ObjectId object_id)
1039 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Sebastien Hertze96060a2013-12-11 12:06:28 +01001040 mirror::Object* o = gRegistry->Get<mirror::Object*>(object_id);
1041 if (o == NULL || o == ObjectRegistry::kInvalidObject) {
1042 return JDWP::ERR_INVALID_OBJECT;
1043 }
Elliott Hughes64f574f2013-02-20 14:57:12 -08001044 gRegistry->DisableCollection(object_id);
1045 return JDWP::ERR_NONE;
1046}
1047
1048JDWP::JdwpError Dbg::EnableCollection(JDWP::ObjectId object_id)
1049 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Sebastien Hertze96060a2013-12-11 12:06:28 +01001050 mirror::Object* o = gRegistry->Get<mirror::Object*>(object_id);
1051 // Unlike DisableCollection, JDWP specs do not state an invalid object causes an error. The RI
1052 // also ignores these cases and never return an error. However it's not obvious why this command
1053 // should behave differently from DisableCollection and IsCollected commands. So let's be more
1054 // strict and return an error if this happens.
1055 if (o == NULL || o == ObjectRegistry::kInvalidObject) {
1056 return JDWP::ERR_INVALID_OBJECT;
1057 }
Elliott Hughes64f574f2013-02-20 14:57:12 -08001058 gRegistry->EnableCollection(object_id);
1059 return JDWP::ERR_NONE;
1060}
1061
1062JDWP::JdwpError Dbg::IsCollected(JDWP::ObjectId object_id, bool& is_collected)
1063 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Sebastien Hertz65637eb2014-01-10 17:40:02 +01001064 if (object_id == 0) {
1065 // Null object id is invalid.
Sebastien Hertze96060a2013-12-11 12:06:28 +01001066 return JDWP::ERR_INVALID_OBJECT;
1067 }
Sebastien Hertz65637eb2014-01-10 17:40:02 +01001068 // JDWP specs state an INVALID_OBJECT error is returned if the object ID is not valid. However
1069 // the RI seems to ignore this and assume object has been collected.
1070 mirror::Object* o = gRegistry->Get<mirror::Object*>(object_id);
1071 if (o == NULL || o == ObjectRegistry::kInvalidObject) {
1072 is_collected = true;
1073 } else {
1074 is_collected = gRegistry->IsCollected(object_id);
1075 }
Elliott Hughes64f574f2013-02-20 14:57:12 -08001076 return JDWP::ERR_NONE;
1077}
1078
1079void Dbg::DisposeObject(JDWP::ObjectId object_id, uint32_t reference_count)
1080 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
1081 gRegistry->DisposeObject(object_id, reference_count);
1082}
1083
Sebastien Hertz4d8fd492014-03-28 16:29:41 +01001084static JDWP::JdwpTypeTag GetTypeTag(mirror::Class* klass)
1085 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
1086 DCHECK(klass != nullptr);
1087 if (klass->IsArrayClass()) {
1088 return JDWP::TT_ARRAY;
1089 } else if (klass->IsInterface()) {
1090 return JDWP::TT_INTERFACE;
1091 } else {
1092 return JDWP::TT_CLASS;
1093 }
1094}
1095
Elliott Hughes88d63092013-01-09 09:55:54 -08001096JDWP::JdwpError Dbg::GetReflectedType(JDWP::RefTypeId class_id, JDWP::ExpandBuf* pReply) {
Elliott Hughes436e3722012-02-17 20:01:47 -08001097 JDWP::JdwpError status;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001098 mirror::Class* c = DecodeClass(class_id, status);
Elliott Hughes436e3722012-02-17 20:01:47 -08001099 if (c == NULL) {
1100 return status;
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -08001101 }
Elliott Hughes436e3722012-02-17 20:01:47 -08001102
Sebastien Hertz4d8fd492014-03-28 16:29:41 +01001103 JDWP::JdwpTypeTag type_tag = GetTypeTag(c);
1104 expandBufAdd1(pReply, type_tag);
Elliott Hughes88d63092013-01-09 09:55:54 -08001105 expandBufAddRefTypeId(pReply, class_id);
Elliott Hughes436e3722012-02-17 20:01:47 -08001106 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001107}
1108
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -08001109void Dbg::GetClassList(std::vector<JDWP::RefTypeId>& classes) {
Elliott Hughesa2155262011-11-16 16:26:58 -08001110 // Get the complete list of reference classes (i.e. all classes except
1111 // the primitive types).
1112 // Returns a newly-allocated buffer full of RefTypeId values.
1113 struct ClassListCreator {
Elliott Hughesba8eee12012-01-24 20:25:24 -08001114 explicit ClassListCreator(std::vector<JDWP::RefTypeId>& classes) : classes(classes) {
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -08001115 }
1116
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001117 static bool Visit(mirror::Class* c, void* arg) {
Elliott Hughesa2155262011-11-16 16:26:58 -08001118 return reinterpret_cast<ClassListCreator*>(arg)->Visit(c);
1119 }
1120
Elliott Hughes64f574f2013-02-20 14:57:12 -08001121 // TODO: Enable annotalysis. We know lock is held in constructor, but abstraction confuses
1122 // annotalysis.
1123 bool Visit(mirror::Class* c) NO_THREAD_SAFETY_ANALYSIS {
Elliott Hughesa2155262011-11-16 16:26:58 -08001124 if (!c->IsPrimitive()) {
Elliott Hughes64f574f2013-02-20 14:57:12 -08001125 classes.push_back(gRegistry->AddRefType(c));
Elliott Hughesa2155262011-11-16 16:26:58 -08001126 }
1127 return true;
1128 }
1129
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -08001130 std::vector<JDWP::RefTypeId>& classes;
Elliott Hughesa2155262011-11-16 16:26:58 -08001131 };
1132
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -08001133 ClassListCreator clc(classes);
Elliott Hughesa2155262011-11-16 16:26:58 -08001134 Runtime::Current()->GetClassLinker()->VisitClasses(ClassListCreator::Visit, &clc);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001135}
1136
Elliott Hughes88d63092013-01-09 09:55:54 -08001137JDWP::JdwpError Dbg::GetClassInfo(JDWP::RefTypeId class_id, JDWP::JdwpTypeTag* pTypeTag, uint32_t* pStatus, std::string* pDescriptor) {
Elliott Hughes436e3722012-02-17 20:01:47 -08001138 JDWP::JdwpError status;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001139 mirror::Class* c = DecodeClass(class_id, status);
Elliott Hughes436e3722012-02-17 20:01:47 -08001140 if (c == NULL) {
1141 return status;
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -08001142 }
1143
Elliott Hughesa2155262011-11-16 16:26:58 -08001144 if (c->IsArrayClass()) {
1145 *pStatus = JDWP::CS_VERIFIED | JDWP::CS_PREPARED;
1146 *pTypeTag = JDWP::TT_ARRAY;
1147 } else {
1148 if (c->IsErroneous()) {
1149 *pStatus = JDWP::CS_ERROR;
1150 } else {
1151 *pStatus = JDWP::CS_VERIFIED | JDWP::CS_PREPARED | JDWP::CS_INITIALIZED;
1152 }
1153 *pTypeTag = c->IsInterface() ? JDWP::TT_INTERFACE : JDWP::TT_CLASS;
1154 }
1155
1156 if (pDescriptor != NULL) {
Mathieu Chartierf8322842014-05-16 10:59:25 -07001157 *pDescriptor = c->GetDescriptor();
Elliott Hughesa2155262011-11-16 16:26:58 -08001158 }
Elliott Hughes436e3722012-02-17 20:01:47 -08001159 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001160}
1161
Elliott Hughesc3b77c72011-12-15 20:56:48 -08001162void Dbg::FindLoadedClassBySignature(const char* descriptor, std::vector<JDWP::RefTypeId>& ids) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001163 std::vector<mirror::Class*> classes;
Elliott Hughes6fa602d2011-12-02 17:54:25 -08001164 Runtime::Current()->GetClassLinker()->LookupClasses(descriptor, classes);
1165 ids.clear();
1166 for (size_t i = 0; i < classes.size(); ++i) {
1167 ids.push_back(gRegistry->Add(classes[i]));
1168 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001169}
1170
Elliott Hughes64f574f2013-02-20 14:57:12 -08001171JDWP::JdwpError Dbg::GetReferenceType(JDWP::ObjectId object_id, JDWP::ExpandBuf* pReply)
1172 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001173 mirror::Object* o = gRegistry->Get<mirror::Object*>(object_id);
Elliott Hughes64f574f2013-02-20 14:57:12 -08001174 if (o == NULL || o == ObjectRegistry::kInvalidObject) {
Elliott Hughes2435a572012-02-17 16:07:41 -08001175 return JDWP::ERR_INVALID_OBJECT;
Elliott Hughes499c5132011-11-17 14:55:11 -08001176 }
Elliott Hughes2435a572012-02-17 16:07:41 -08001177
Sebastien Hertz4d8fd492014-03-28 16:29:41 +01001178 JDWP::JdwpTypeTag type_tag = GetTypeTag(o->GetClass());
Elliott Hughes64f574f2013-02-20 14:57:12 -08001179 JDWP::RefTypeId type_id = gRegistry->AddRefType(o->GetClass());
Elliott Hughes2435a572012-02-17 16:07:41 -08001180
1181 expandBufAdd1(pReply, type_tag);
1182 expandBufAddRefTypeId(pReply, type_id);
1183
1184 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001185}
1186
Ian Rogersfc0e94b2013-09-23 23:51:32 -07001187JDWP::JdwpError Dbg::GetSignature(JDWP::RefTypeId class_id, std::string* signature) {
Elliott Hughes1fe7afb2012-02-13 17:23:03 -08001188 JDWP::JdwpError status;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001189 mirror::Class* c = DecodeClass(class_id, status);
Elliott Hughes1fe7afb2012-02-13 17:23:03 -08001190 if (c == NULL) {
1191 return status;
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -08001192 }
Mathieu Chartierf8322842014-05-16 10:59:25 -07001193 *signature = c->GetDescriptor();
Elliott Hughes1fe7afb2012-02-13 17:23:03 -08001194 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001195}
1196
Elliott Hughes88d63092013-01-09 09:55:54 -08001197JDWP::JdwpError Dbg::GetSourceFile(JDWP::RefTypeId class_id, std::string& result) {
Elliott Hughes436e3722012-02-17 20:01:47 -08001198 JDWP::JdwpError status;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001199 mirror::Class* c = DecodeClass(class_id, status);
Sebastien Hertz4206eb52014-06-05 10:15:45 +02001200 if (c == nullptr) {
Elliott Hughes436e3722012-02-17 20:01:47 -08001201 return status;
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -08001202 }
Sebastien Hertz4206eb52014-06-05 10:15:45 +02001203 const char* source_file = c->GetSourceFile();
1204 if (source_file == nullptr) {
Sebastien Hertzb7054ba2014-03-13 11:52:31 +01001205 return JDWP::ERR_ABSENT_INFORMATION;
1206 }
Sebastien Hertz4206eb52014-06-05 10:15:45 +02001207 result = source_file;
Elliott Hughes436e3722012-02-17 20:01:47 -08001208 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001209}
1210
Elliott Hughes88d63092013-01-09 09:55:54 -08001211JDWP::JdwpError Dbg::GetObjectTag(JDWP::ObjectId object_id, uint8_t& tag) {
Ian Rogers98379392014-02-24 16:53:16 -08001212 ScopedObjectAccessUnchecked soa(Thread::Current());
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001213 mirror::Object* o = gRegistry->Get<mirror::Object*>(object_id);
Elliott Hughes64f574f2013-02-20 14:57:12 -08001214 if (o == ObjectRegistry::kInvalidObject) {
Elliott Hughes546b9862012-06-20 16:06:13 -07001215 return JDWP::ERR_INVALID_OBJECT;
1216 }
Ian Rogers98379392014-02-24 16:53:16 -08001217 tag = TagFromObject(soa, o);
Elliott Hughes546b9862012-06-20 16:06:13 -07001218 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001219}
1220
Elliott Hughesaed4be92011-12-02 16:16:23 -08001221size_t Dbg::GetTagWidth(JDWP::JdwpTag tag) {
Elliott Hughesdbb40792011-11-18 17:05:22 -08001222 switch (tag) {
1223 case JDWP::JT_VOID:
1224 return 0;
1225 case JDWP::JT_BYTE:
1226 case JDWP::JT_BOOLEAN:
1227 return 1;
1228 case JDWP::JT_CHAR:
1229 case JDWP::JT_SHORT:
1230 return 2;
1231 case JDWP::JT_FLOAT:
1232 case JDWP::JT_INT:
1233 return 4;
1234 case JDWP::JT_ARRAY:
1235 case JDWP::JT_OBJECT:
1236 case JDWP::JT_STRING:
1237 case JDWP::JT_THREAD:
1238 case JDWP::JT_THREAD_GROUP:
1239 case JDWP::JT_CLASS_LOADER:
1240 case JDWP::JT_CLASS_OBJECT:
1241 return sizeof(JDWP::ObjectId);
1242 case JDWP::JT_DOUBLE:
1243 case JDWP::JT_LONG:
1244 return 8;
1245 default:
Elliott Hughes3d30d9b2011-12-07 17:35:48 -08001246 LOG(FATAL) << "Unknown tag " << tag;
Elliott Hughesdbb40792011-11-18 17:05:22 -08001247 return -1;
1248 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001249}
1250
Elliott Hughes88d63092013-01-09 09:55:54 -08001251JDWP::JdwpError Dbg::GetArrayLength(JDWP::ObjectId array_id, int& length) {
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -08001252 JDWP::JdwpError status;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001253 mirror::Array* a = DecodeArray(array_id, status);
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -08001254 if (a == NULL) {
1255 return status;
Elliott Hughes24437992011-11-30 14:49:33 -08001256 }
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -08001257 length = a->GetLength();
1258 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001259}
1260
Elliott Hughes88d63092013-01-09 09:55:54 -08001261JDWP::JdwpError Dbg::OutputArray(JDWP::ObjectId array_id, int offset, int count, JDWP::ExpandBuf* pReply) {
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -08001262 JDWP::JdwpError status;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001263 mirror::Array* a = DecodeArray(array_id, status);
Ian Rogers98379392014-02-24 16:53:16 -08001264 if (a == nullptr) {
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -08001265 return status;
1266 }
Elliott Hughes24437992011-11-30 14:49:33 -08001267
1268 if (offset < 0 || count < 0 || offset > a->GetLength() || a->GetLength() - offset < count) {
1269 LOG(WARNING) << __FUNCTION__ << " access out of bounds: offset=" << offset << "; count=" << count;
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -08001270 return JDWP::ERR_INVALID_LENGTH;
Elliott Hughes24437992011-11-30 14:49:33 -08001271 }
Mathieu Chartierf8322842014-05-16 10:59:25 -07001272 std::string descriptor(a->GetClass()->GetDescriptor());
Elliott Hughes24437992011-11-30 14:49:33 -08001273 JDWP::JdwpTag tag = BasicTagFromDescriptor(descriptor.c_str() + 1);
1274
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -08001275 expandBufAdd1(pReply, tag);
1276 expandBufAdd4BE(pReply, count);
1277
Elliott Hughes24437992011-11-30 14:49:33 -08001278 if (IsPrimitiveTag(tag)) {
1279 size_t width = GetTagWidth(tag);
Elliott Hughes24437992011-11-30 14:49:33 -08001280 uint8_t* dst = expandBufAddSpace(pReply, count * width);
1281 if (width == 8) {
Ian Rogersef7d42f2014-01-06 12:55:46 -08001282 const uint64_t* src8 = reinterpret_cast<uint64_t*>(a->GetRawData(sizeof(uint64_t), 0));
Elliott Hughes24437992011-11-30 14:49:33 -08001283 for (int i = 0; i < count; ++i) JDWP::Write8BE(&dst, src8[offset + i]);
1284 } else if (width == 4) {
Ian Rogersef7d42f2014-01-06 12:55:46 -08001285 const uint32_t* src4 = reinterpret_cast<uint32_t*>(a->GetRawData(sizeof(uint32_t), 0));
Elliott Hughes24437992011-11-30 14:49:33 -08001286 for (int i = 0; i < count; ++i) JDWP::Write4BE(&dst, src4[offset + i]);
1287 } else if (width == 2) {
Ian Rogersef7d42f2014-01-06 12:55:46 -08001288 const uint16_t* src2 = reinterpret_cast<uint16_t*>(a->GetRawData(sizeof(uint16_t), 0));
Elliott Hughes24437992011-11-30 14:49:33 -08001289 for (int i = 0; i < count; ++i) JDWP::Write2BE(&dst, src2[offset + i]);
1290 } else {
Ian Rogersef7d42f2014-01-06 12:55:46 -08001291 const uint8_t* src = reinterpret_cast<uint8_t*>(a->GetRawData(sizeof(uint8_t), 0));
Elliott Hughes24437992011-11-30 14:49:33 -08001292 memcpy(dst, &src[offset * width], count * width);
1293 }
1294 } else {
Ian Rogers98379392014-02-24 16:53:16 -08001295 ScopedObjectAccessUnchecked soa(Thread::Current());
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001296 mirror::ObjectArray<mirror::Object>* oa = a->AsObjectArray<mirror::Object>();
Elliott Hughes24437992011-11-30 14:49:33 -08001297 for (int i = 0; i < count; ++i) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001298 mirror::Object* element = oa->Get(offset + i);
Ian Rogers98379392014-02-24 16:53:16 -08001299 JDWP::JdwpTag specific_tag = (element != nullptr) ? TagFromObject(soa, element)
1300 : tag;
Elliott Hughes24437992011-11-30 14:49:33 -08001301 expandBufAdd1(pReply, specific_tag);
1302 expandBufAddObjectId(pReply, gRegistry->Add(element));
1303 }
1304 }
1305
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -08001306 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001307}
1308
Ian Rogersef7d42f2014-01-06 12:55:46 -08001309template <typename T>
1310static void CopyArrayData(mirror::Array* a, JDWP::Request& src, int offset, int count)
1311 NO_THREAD_SAFETY_ANALYSIS {
1312 // TODO: fix when annotalysis correctly handles non-member functions.
Elliott Hughes4b9702c2013-02-20 18:13:24 -08001313 DCHECK(a->GetClass()->IsPrimitiveArray());
1314
Ian Rogersef7d42f2014-01-06 12:55:46 -08001315 T* dst = reinterpret_cast<T*>(a->GetRawData(sizeof(T), offset));
Elliott Hughes4b9702c2013-02-20 18:13:24 -08001316 for (int i = 0; i < count; ++i) {
1317 *dst++ = src.ReadValue(sizeof(T));
1318 }
1319}
1320
Elliott Hughes88d63092013-01-09 09:55:54 -08001321JDWP::JdwpError Dbg::SetArrayElements(JDWP::ObjectId array_id, int offset, int count,
Elliott Hughes4b9702c2013-02-20 18:13:24 -08001322 JDWP::Request& request)
Ian Rogersb726dcb2012-09-05 08:57:23 -07001323 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -08001324 JDWP::JdwpError status;
Elliott Hughes4b9702c2013-02-20 18:13:24 -08001325 mirror::Array* dst = DecodeArray(array_id, status);
1326 if (dst == NULL) {
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -08001327 return status;
1328 }
Elliott Hughesf03b8f62011-12-02 14:26:25 -08001329
Elliott Hughes4b9702c2013-02-20 18:13:24 -08001330 if (offset < 0 || count < 0 || offset > dst->GetLength() || dst->GetLength() - offset < count) {
Elliott Hughesf03b8f62011-12-02 14:26:25 -08001331 LOG(WARNING) << __FUNCTION__ << " access out of bounds: offset=" << offset << "; count=" << count;
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -08001332 return JDWP::ERR_INVALID_LENGTH;
Elliott Hughesf03b8f62011-12-02 14:26:25 -08001333 }
Mathieu Chartierf8322842014-05-16 10:59:25 -07001334 std::string descriptor = dst->GetClass()->GetDescriptor();
1335 JDWP::JdwpTag tag = BasicTagFromDescriptor(descriptor.c_str() + 1);
Elliott Hughesf03b8f62011-12-02 14:26:25 -08001336
1337 if (IsPrimitiveTag(tag)) {
1338 size_t width = GetTagWidth(tag);
Elliott Hughesf03b8f62011-12-02 14:26:25 -08001339 if (width == 8) {
Elliott Hughes4b9702c2013-02-20 18:13:24 -08001340 CopyArrayData<uint64_t>(dst, request, offset, count);
Elliott Hughesf03b8f62011-12-02 14:26:25 -08001341 } else if (width == 4) {
Elliott Hughes4b9702c2013-02-20 18:13:24 -08001342 CopyArrayData<uint32_t>(dst, request, offset, count);
Elliott Hughesf03b8f62011-12-02 14:26:25 -08001343 } else if (width == 2) {
Elliott Hughes4b9702c2013-02-20 18:13:24 -08001344 CopyArrayData<uint16_t>(dst, request, offset, count);
Elliott Hughesf03b8f62011-12-02 14:26:25 -08001345 } else {
Elliott Hughes4b9702c2013-02-20 18:13:24 -08001346 CopyArrayData<uint8_t>(dst, request, offset, count);
Elliott Hughesf03b8f62011-12-02 14:26:25 -08001347 }
1348 } else {
Elliott Hughes4b9702c2013-02-20 18:13:24 -08001349 mirror::ObjectArray<mirror::Object>* oa = dst->AsObjectArray<mirror::Object>();
Elliott Hughesf03b8f62011-12-02 14:26:25 -08001350 for (int i = 0; i < count; ++i) {
Elliott Hughes4b9702c2013-02-20 18:13:24 -08001351 JDWP::ObjectId id = request.ReadObjectId();
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001352 mirror::Object* o = gRegistry->Get<mirror::Object*>(id);
Elliott Hughes64f574f2013-02-20 14:57:12 -08001353 if (o == ObjectRegistry::kInvalidObject) {
Elliott Hughes436e3722012-02-17 20:01:47 -08001354 return JDWP::ERR_INVALID_OBJECT;
1355 }
Sebastien Hertzd2fe10a2014-01-15 10:20:56 +01001356 oa->Set<false>(offset + i, o);
Elliott Hughesf03b8f62011-12-02 14:26:25 -08001357 }
1358 }
1359
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -08001360 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001361}
1362
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -08001363JDWP::ObjectId Dbg::CreateString(const std::string& str) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001364 return gRegistry->Add(mirror::String::AllocFromModifiedUtf8(Thread::Current(), str.c_str()));
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001365}
1366
Elliott Hughes88d63092013-01-09 09:55:54 -08001367JDWP::JdwpError Dbg::CreateObject(JDWP::RefTypeId class_id, JDWP::ObjectId& new_object) {
Elliott Hughes436e3722012-02-17 20:01:47 -08001368 JDWP::JdwpError status;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001369 mirror::Class* c = DecodeClass(class_id, status);
Elliott Hughes436e3722012-02-17 20:01:47 -08001370 if (c == NULL) {
1371 return status;
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -08001372 }
Ian Rogers50b35e22012-10-04 10:09:15 -07001373 new_object = gRegistry->Add(c->AllocObject(Thread::Current()));
Elliott Hughes436e3722012-02-17 20:01:47 -08001374 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001375}
1376
Elliott Hughesbf13d362011-12-08 15:51:37 -08001377/*
1378 * Used by Eclipse's "Display" view to evaluate "new byte[5]" to get "(byte[]) [0, 0, 0, 0, 0]".
1379 */
Elliott Hughes88d63092013-01-09 09:55:54 -08001380JDWP::JdwpError Dbg::CreateArrayObject(JDWP::RefTypeId array_class_id, uint32_t length,
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001381 JDWP::ObjectId& new_array) {
Elliott Hughes436e3722012-02-17 20:01:47 -08001382 JDWP::JdwpError status;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001383 mirror::Class* c = DecodeClass(array_class_id, status);
Elliott Hughes436e3722012-02-17 20:01:47 -08001384 if (c == NULL) {
1385 return status;
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -08001386 }
Ian Rogers6fac4472014-02-25 17:01:10 -08001387 new_array = gRegistry->Add(mirror::Array::Alloc<true>(Thread::Current(), c, length,
1388 c->GetComponentSize(),
1389 Runtime::Current()->GetHeap()->GetCurrentAllocator()));
Elliott Hughes436e3722012-02-17 20:01:47 -08001390 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001391}
1392
Elliott Hughes88d63092013-01-09 09:55:54 -08001393bool Dbg::MatchType(JDWP::RefTypeId instance_class_id, JDWP::RefTypeId class_id) {
Elliott Hughes436e3722012-02-17 20:01:47 -08001394 JDWP::JdwpError status;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001395 mirror::Class* c1 = DecodeClass(instance_class_id, status);
Elliott Hughesa656a0f2012-02-21 18:03:44 -08001396 CHECK(c1 != NULL);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001397 mirror::Class* c2 = DecodeClass(class_id, status);
Elliott Hughesa656a0f2012-02-21 18:03:44 -08001398 CHECK(c2 != NULL);
Sebastien Hertz123756a2013-11-27 15:49:42 +01001399 return c2->IsAssignableFrom(c1);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001400}
1401
Brian Carlstromea46f952013-07-30 01:26:50 -07001402static JDWP::FieldId ToFieldId(const mirror::ArtField* f)
Ian Rogersb726dcb2012-09-05 08:57:23 -07001403 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Mathieu Chartier590fee92013-09-13 13:46:47 -07001404 CHECK(!kMovingFields);
Elliott Hughes03181a82011-11-17 17:22:21 -08001405 return static_cast<JDWP::FieldId>(reinterpret_cast<uintptr_t>(f));
Elliott Hughes03181a82011-11-17 17:22:21 -08001406}
1407
Brian Carlstromea46f952013-07-30 01:26:50 -07001408static JDWP::MethodId ToMethodId(const mirror::ArtMethod* m)
Ian Rogersb726dcb2012-09-05 08:57:23 -07001409 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Mathieu Chartier590fee92013-09-13 13:46:47 -07001410 CHECK(!kMovingMethods);
Elliott Hughes03181a82011-11-17 17:22:21 -08001411 return static_cast<JDWP::MethodId>(reinterpret_cast<uintptr_t>(m));
Elliott Hughes03181a82011-11-17 17:22:21 -08001412}
1413
Brian Carlstromea46f952013-07-30 01:26:50 -07001414static mirror::ArtField* FromFieldId(JDWP::FieldId fid)
Ian Rogersb726dcb2012-09-05 08:57:23 -07001415 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Mathieu Chartier590fee92013-09-13 13:46:47 -07001416 CHECK(!kMovingFields);
Brian Carlstromea46f952013-07-30 01:26:50 -07001417 return reinterpret_cast<mirror::ArtField*>(static_cast<uintptr_t>(fid));
Elliott Hughesaed4be92011-12-02 16:16:23 -08001418}
1419
Brian Carlstromea46f952013-07-30 01:26:50 -07001420static mirror::ArtMethod* FromMethodId(JDWP::MethodId mid)
Ian Rogersb726dcb2012-09-05 08:57:23 -07001421 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Mathieu Chartier590fee92013-09-13 13:46:47 -07001422 CHECK(!kMovingMethods);
Brian Carlstromea46f952013-07-30 01:26:50 -07001423 return reinterpret_cast<mirror::ArtMethod*>(static_cast<uintptr_t>(mid));
Elliott Hughes03181a82011-11-17 17:22:21 -08001424}
1425
Brian Carlstromea46f952013-07-30 01:26:50 -07001426static void SetLocation(JDWP::JdwpLocation& location, mirror::ArtMethod* m, uint32_t dex_pc)
Ian Rogersb726dcb2012-09-05 08:57:23 -07001427 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08001428 if (m == NULL) {
1429 memset(&location, 0, sizeof(location));
1430 } else {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001431 mirror::Class* c = m->GetDeclaringClass();
Sebastien Hertz4d8fd492014-03-28 16:29:41 +01001432 location.type_tag = GetTypeTag(c);
Sebastien Hertzcb19ebf2014-03-11 15:26:35 +01001433 location.class_id = gRegistry->AddRefType(c);
Elliott Hughes74847412012-06-20 18:10:21 -07001434 location.method_id = ToMethodId(m);
Sebastien Hertzcb19ebf2014-03-11 15:26:35 +01001435 location.dex_pc = (m->IsNative() || m->IsProxyMethod()) ? static_cast<uint64_t>(-1) : dex_pc;
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08001436 }
Elliott Hughesd07986f2011-12-06 18:27:45 -08001437}
1438
Elliott Hughesa96836a2013-01-17 12:27:49 -08001439std::string Dbg::GetMethodName(JDWP::MethodId method_id)
Ian Rogersb726dcb2012-09-05 08:57:23 -07001440 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Brian Carlstromea46f952013-07-30 01:26:50 -07001441 mirror::ArtMethod* m = FromMethodId(method_id);
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07001442 return m->GetName();
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001443}
1444
Elliott Hughesa96836a2013-01-17 12:27:49 -08001445std::string Dbg::GetFieldName(JDWP::FieldId field_id)
1446 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Mathieu Chartier61c5ebc2014-06-05 17:42:53 -07001447 return FromFieldId(field_id)->GetName();
Elliott Hughesa96836a2013-01-17 12:27:49 -08001448}
1449
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001450/*
1451 * Augment the access flags for synthetic methods and fields by setting
1452 * the (as described by the spec) "0xf0000000 bit". Also, strip out any
1453 * flags not specified by the Java programming language.
1454 */
1455static uint32_t MangleAccessFlags(uint32_t accessFlags) {
1456 accessFlags &= kAccJavaFlagsMask;
1457 if ((accessFlags & kAccSynthetic) != 0) {
1458 accessFlags |= 0xf0000000;
1459 }
1460 return accessFlags;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001461}
1462
Elliott Hughesdbb40792011-11-18 17:05:22 -08001463/*
Jeff Haob7cefc72013-11-14 14:51:09 -08001464 * Circularly shifts registers so that arguments come first. Debuggers
1465 * expect slots to begin with arguments, but dex code places them at
1466 * the end.
Elliott Hughesdbb40792011-11-18 17:05:22 -08001467 */
Jeff Haob7cefc72013-11-14 14:51:09 -08001468static uint16_t MangleSlot(uint16_t slot, mirror::ArtMethod* m)
1469 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07001470 const DexFile::CodeItem* code_item = m->GetCodeItem();
Sebastien Hertzcb19ebf2014-03-11 15:26:35 +01001471 if (code_item == nullptr) {
1472 // We should not get here for a method without code (native, proxy or abstract). Log it and
1473 // return the slot as is since all registers are arguments.
1474 LOG(WARNING) << "Trying to mangle slot for method without code " << PrettyMethod(m);
1475 return slot;
1476 }
Jeff Haob7cefc72013-11-14 14:51:09 -08001477 uint16_t ins_size = code_item->ins_size_;
1478 uint16_t locals_size = code_item->registers_size_ - ins_size;
1479 if (slot >= locals_size) {
1480 return slot - locals_size;
1481 } else {
1482 return slot + ins_size;
Elliott Hughesdbb40792011-11-18 17:05:22 -08001483 }
Elliott Hughesdbb40792011-11-18 17:05:22 -08001484}
1485
Jeff Haob7cefc72013-11-14 14:51:09 -08001486/*
1487 * Circularly shifts registers so that arguments come last. Reverts
1488 * slots to dex style argument placement.
1489 */
Brian Carlstromea46f952013-07-30 01:26:50 -07001490static uint16_t DemangleSlot(uint16_t slot, mirror::ArtMethod* m)
Ian Rogersb726dcb2012-09-05 08:57:23 -07001491 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07001492 const DexFile::CodeItem* code_item = m->GetCodeItem();
Sebastien Hertzcb19ebf2014-03-11 15:26:35 +01001493 if (code_item == nullptr) {
1494 // We should not get here for a method without code (native, proxy or abstract). Log it and
1495 // return the slot as is since all registers are arguments.
1496 LOG(WARNING) << "Trying to demangle slot for method without code " << PrettyMethod(m);
1497 return slot;
1498 }
Jeff Haob7cefc72013-11-14 14:51:09 -08001499 uint16_t ins_size = code_item->ins_size_;
1500 uint16_t locals_size = code_item->registers_size_ - ins_size;
1501 if (slot < ins_size) {
1502 return slot + locals_size;
1503 } else {
1504 return slot - ins_size;
Elliott Hughesdbb40792011-11-18 17:05:22 -08001505 }
Elliott Hughesdbb40792011-11-18 17:05:22 -08001506}
1507
Elliott Hughes88d63092013-01-09 09:55:54 -08001508JDWP::JdwpError Dbg::OutputDeclaredFields(JDWP::RefTypeId class_id, bool with_generic, JDWP::ExpandBuf* pReply) {
Elliott Hughes436e3722012-02-17 20:01:47 -08001509 JDWP::JdwpError status;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001510 mirror::Class* c = DecodeClass(class_id, status);
Elliott Hughes436e3722012-02-17 20:01:47 -08001511 if (c == NULL) {
1512 return status;
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -08001513 }
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001514
1515 size_t instance_field_count = c->NumInstanceFields();
1516 size_t static_field_count = c->NumStaticFields();
1517
1518 expandBufAdd4BE(pReply, instance_field_count + static_field_count);
1519
1520 for (size_t i = 0; i < instance_field_count + static_field_count; ++i) {
Brian Carlstromea46f952013-07-30 01:26:50 -07001521 mirror::ArtField* f = (i < instance_field_count) ? c->GetInstanceField(i) : c->GetStaticField(i - instance_field_count);
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001522 expandBufAddFieldId(pReply, ToFieldId(f));
Mathieu Chartier61c5ebc2014-06-05 17:42:53 -07001523 expandBufAddUtf8String(pReply, f->GetName());
1524 expandBufAddUtf8String(pReply, f->GetTypeDescriptor());
Elliott Hughesc5b734a2011-12-01 17:20:58 -08001525 if (with_generic) {
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001526 static const char genericSignature[1] = "";
1527 expandBufAddUtf8String(pReply, genericSignature);
1528 }
1529 expandBufAdd4BE(pReply, MangleAccessFlags(f->GetAccessFlags()));
1530 }
Elliott Hughes436e3722012-02-17 20:01:47 -08001531 return JDWP::ERR_NONE;
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001532}
1533
Elliott Hughes88d63092013-01-09 09:55:54 -08001534JDWP::JdwpError Dbg::OutputDeclaredMethods(JDWP::RefTypeId class_id, bool with_generic,
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001535 JDWP::ExpandBuf* pReply) {
Elliott Hughes436e3722012-02-17 20:01:47 -08001536 JDWP::JdwpError status;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001537 mirror::Class* c = DecodeClass(class_id, status);
Elliott Hughes436e3722012-02-17 20:01:47 -08001538 if (c == NULL) {
1539 return status;
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -08001540 }
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001541
1542 size_t direct_method_count = c->NumDirectMethods();
1543 size_t virtual_method_count = c->NumVirtualMethods();
1544
1545 expandBufAdd4BE(pReply, direct_method_count + virtual_method_count);
1546
1547 for (size_t i = 0; i < direct_method_count + virtual_method_count; ++i) {
Brian Carlstromea46f952013-07-30 01:26:50 -07001548 mirror::ArtMethod* m = (i < direct_method_count) ? c->GetDirectMethod(i) : c->GetVirtualMethod(i - direct_method_count);
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001549 expandBufAddMethodId(pReply, ToMethodId(m));
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07001550 expandBufAddUtf8String(pReply, m->GetName());
1551 expandBufAddUtf8String(pReply, m->GetSignature().ToString());
Elliott Hughesc5b734a2011-12-01 17:20:58 -08001552 if (with_generic) {
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001553 static const char genericSignature[1] = "";
1554 expandBufAddUtf8String(pReply, genericSignature);
1555 }
1556 expandBufAdd4BE(pReply, MangleAccessFlags(m->GetAccessFlags()));
1557 }
Elliott Hughes436e3722012-02-17 20:01:47 -08001558 return JDWP::ERR_NONE;
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001559}
1560
Elliott Hughes88d63092013-01-09 09:55:54 -08001561JDWP::JdwpError Dbg::OutputDeclaredInterfaces(JDWP::RefTypeId class_id, JDWP::ExpandBuf* pReply) {
Elliott Hughes436e3722012-02-17 20:01:47 -08001562 JDWP::JdwpError status;
Mathieu Chartierf8322842014-05-16 10:59:25 -07001563 Thread* self = Thread::Current();
1564 StackHandleScope<1> hs(self);
1565 Handle<mirror::Class> c(hs.NewHandle(DecodeClass(class_id, status)));
1566 if (c.Get() == nullptr) {
Elliott Hughes436e3722012-02-17 20:01:47 -08001567 return status;
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -08001568 }
Mathieu Chartierf8322842014-05-16 10:59:25 -07001569 size_t interface_count = c->NumDirectInterfaces();
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001570 expandBufAdd4BE(pReply, interface_count);
1571 for (size_t i = 0; i < interface_count; ++i) {
Mathieu Chartierf8322842014-05-16 10:59:25 -07001572 expandBufAddRefTypeId(pReply,
1573 gRegistry->AddRefType(mirror::Class::GetDirectInterface(self, c, i)));
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001574 }
Elliott Hughes436e3722012-02-17 20:01:47 -08001575 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001576}
1577
Elliott Hughes88d63092013-01-09 09:55:54 -08001578void Dbg::OutputLineTable(JDWP::RefTypeId, JDWP::MethodId method_id, JDWP::ExpandBuf* pReply)
Ian Rogersb726dcb2012-09-05 08:57:23 -07001579 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Elliott Hughes03181a82011-11-17 17:22:21 -08001580 struct DebugCallbackContext {
1581 int numItems;
1582 JDWP::ExpandBuf* pReply;
1583
Elliott Hughes2435a572012-02-17 16:07:41 -08001584 static bool Callback(void* context, uint32_t address, uint32_t line_number) {
Elliott Hughes03181a82011-11-17 17:22:21 -08001585 DebugCallbackContext* pContext = reinterpret_cast<DebugCallbackContext*>(context);
1586 expandBufAdd8BE(pContext->pReply, address);
Elliott Hughes2435a572012-02-17 16:07:41 -08001587 expandBufAdd4BE(pContext->pReply, line_number);
Elliott Hughes03181a82011-11-17 17:22:21 -08001588 pContext->numItems++;
Sebastien Hertzf2910ee2013-10-19 16:39:24 +02001589 return false;
Elliott Hughes03181a82011-11-17 17:22:21 -08001590 }
1591 };
Brian Carlstromea46f952013-07-30 01:26:50 -07001592 mirror::ArtMethod* m = FromMethodId(method_id);
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07001593 const DexFile::CodeItem* code_item = m->GetCodeItem();
Elliott Hughes03181a82011-11-17 17:22:21 -08001594 uint64_t start, end;
Sebastien Hertzcb19ebf2014-03-11 15:26:35 +01001595 if (code_item == nullptr) {
1596 DCHECK(m->IsNative() || m->IsProxyMethod());
Elliott Hughes03181a82011-11-17 17:22:21 -08001597 start = -1;
1598 end = -1;
1599 } else {
1600 start = 0;
jeffhao14f0db92012-12-14 17:50:42 -08001601 // Return the index of the last instruction
Sebastien Hertzcb19ebf2014-03-11 15:26:35 +01001602 end = code_item->insns_size_in_code_units_ - 1;
Elliott Hughes03181a82011-11-17 17:22:21 -08001603 }
1604
1605 expandBufAdd8BE(pReply, start);
1606 expandBufAdd8BE(pReply, end);
1607
1608 // Add numLines later
1609 size_t numLinesOffset = expandBufGetLength(pReply);
1610 expandBufAdd4BE(pReply, 0);
1611
1612 DebugCallbackContext context;
1613 context.numItems = 0;
1614 context.pReply = pReply;
1615
Sebastien Hertzcb19ebf2014-03-11 15:26:35 +01001616 if (code_item != nullptr) {
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07001617 m->GetDexFile()->DecodeDebugInfo(code_item, m->IsStatic(), m->GetDexMethodIndex(),
1618 DebugCallbackContext::Callback, NULL, &context);
Sebastien Hertzcb19ebf2014-03-11 15:26:35 +01001619 }
Elliott Hughes03181a82011-11-17 17:22:21 -08001620
1621 JDWP::Set4BE(expandBufGetBuffer(pReply) + numLinesOffset, context.numItems);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001622}
1623
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07001624void Dbg::OutputVariableTable(JDWP::RefTypeId, JDWP::MethodId method_id, bool with_generic,
1625 JDWP::ExpandBuf* pReply) {
Elliott Hughesdbb40792011-11-18 17:05:22 -08001626 struct DebugCallbackContext {
Jeff Haob7cefc72013-11-14 14:51:09 -08001627 mirror::ArtMethod* method;
Elliott Hughesdbb40792011-11-18 17:05:22 -08001628 JDWP::ExpandBuf* pReply;
Elliott Hughesc5b734a2011-12-01 17:20:58 -08001629 size_t variable_count;
1630 bool with_generic;
Elliott Hughesdbb40792011-11-18 17:05:22 -08001631
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07001632 static void Callback(void* context, uint16_t slot, uint32_t startAddress, uint32_t endAddress,
1633 const char* name, const char* descriptor, const char* signature)
Jeff Haob7cefc72013-11-14 14:51:09 -08001634 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Elliott Hughesdbb40792011-11-18 17:05:22 -08001635 DebugCallbackContext* pContext = reinterpret_cast<DebugCallbackContext*>(context);
1636
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07001637 VLOG(jdwp) << StringPrintf(" %2zd: %d(%d) '%s' '%s' '%s' actual slot=%d mangled slot=%d",
1638 pContext->variable_count, startAddress, endAddress - startAddress,
1639 name, descriptor, signature, slot,
1640 MangleSlot(slot, pContext->method));
Elliott Hughesdbb40792011-11-18 17:05:22 -08001641
Jeff Haob7cefc72013-11-14 14:51:09 -08001642 slot = MangleSlot(slot, pContext->method);
Elliott Hughes68fdbd02011-11-29 19:22:47 -08001643
Elliott Hughesdbb40792011-11-18 17:05:22 -08001644 expandBufAdd8BE(pContext->pReply, startAddress);
1645 expandBufAddUtf8String(pContext->pReply, name);
1646 expandBufAddUtf8String(pContext->pReply, descriptor);
Elliott Hughesc5b734a2011-12-01 17:20:58 -08001647 if (pContext->with_generic) {
Elliott Hughesdbb40792011-11-18 17:05:22 -08001648 expandBufAddUtf8String(pContext->pReply, signature);
1649 }
1650 expandBufAdd4BE(pContext->pReply, endAddress - startAddress);
1651 expandBufAdd4BE(pContext->pReply, slot);
1652
Elliott Hughesc5b734a2011-12-01 17:20:58 -08001653 ++pContext->variable_count;
Elliott Hughesdbb40792011-11-18 17:05:22 -08001654 }
1655 };
Brian Carlstromea46f952013-07-30 01:26:50 -07001656 mirror::ArtMethod* m = FromMethodId(method_id);
Elliott Hughesdbb40792011-11-18 17:05:22 -08001657
Elliott Hughesc5b734a2011-12-01 17:20:58 -08001658 // arg_count considers doubles and longs to take 2 units.
1659 // variable_count considers everything to take 1 unit.
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07001660 std::string shorty(m->GetShorty());
Brian Carlstromea46f952013-07-30 01:26:50 -07001661 expandBufAdd4BE(pReply, mirror::ArtMethod::NumArgRegisters(shorty));
Elliott Hughesdbb40792011-11-18 17:05:22 -08001662
Elliott Hughesc5b734a2011-12-01 17:20:58 -08001663 // We don't know the total number of variables yet, so leave a blank and update it later.
1664 size_t variable_count_offset = expandBufGetLength(pReply);
Elliott Hughesdbb40792011-11-18 17:05:22 -08001665 expandBufAdd4BE(pReply, 0);
1666
1667 DebugCallbackContext context;
Jeff Haob7cefc72013-11-14 14:51:09 -08001668 context.method = m;
Elliott Hughesdbb40792011-11-18 17:05:22 -08001669 context.pReply = pReply;
Elliott Hughesc5b734a2011-12-01 17:20:58 -08001670 context.variable_count = 0;
1671 context.with_generic = with_generic;
Elliott Hughesdbb40792011-11-18 17:05:22 -08001672
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07001673 const DexFile::CodeItem* code_item = m->GetCodeItem();
Sebastien Hertzcb19ebf2014-03-11 15:26:35 +01001674 if (code_item != nullptr) {
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07001675 m->GetDexFile()->DecodeDebugInfo(
1676 code_item, m->IsStatic(), m->GetDexMethodIndex(), NULL, DebugCallbackContext::Callback,
1677 &context);
Sebastien Hertzcb19ebf2014-03-11 15:26:35 +01001678 }
Elliott Hughesdbb40792011-11-18 17:05:22 -08001679
Elliott Hughesc5b734a2011-12-01 17:20:58 -08001680 JDWP::Set4BE(expandBufGetBuffer(pReply) + variable_count_offset, context.variable_count);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001681}
1682
Jeff Hao579b0242013-11-18 13:16:49 -08001683void Dbg::OutputMethodReturnValue(JDWP::MethodId method_id, const JValue* return_value,
1684 JDWP::ExpandBuf* pReply) {
1685 mirror::ArtMethod* m = FromMethodId(method_id);
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07001686 JDWP::JdwpTag tag = BasicTagFromDescriptor(m->GetShorty());
Jeff Hao579b0242013-11-18 13:16:49 -08001687 OutputJValue(tag, return_value, pReply);
1688}
1689
Sebastien Hertz3f52eaf2014-04-04 17:50:18 +02001690void Dbg::OutputFieldValue(JDWP::FieldId field_id, const JValue* field_value,
1691 JDWP::ExpandBuf* pReply) {
1692 mirror::ArtField* f = FromFieldId(field_id);
Mathieu Chartier61c5ebc2014-06-05 17:42:53 -07001693 JDWP::JdwpTag tag = BasicTagFromDescriptor(f->GetTypeDescriptor());
Sebastien Hertz3f52eaf2014-04-04 17:50:18 +02001694 OutputJValue(tag, field_value, pReply);
1695}
1696
Elliott Hughes9777ba22013-01-17 09:04:19 -08001697JDWP::JdwpError Dbg::GetBytecodes(JDWP::RefTypeId, JDWP::MethodId method_id,
1698 std::vector<uint8_t>& bytecodes)
1699 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Brian Carlstromea46f952013-07-30 01:26:50 -07001700 mirror::ArtMethod* m = FromMethodId(method_id);
Elliott Hughes9777ba22013-01-17 09:04:19 -08001701 if (m == NULL) {
1702 return JDWP::ERR_INVALID_METHODID;
1703 }
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07001704 const DexFile::CodeItem* code_item = m->GetCodeItem();
Elliott Hughes9777ba22013-01-17 09:04:19 -08001705 size_t byte_count = code_item->insns_size_in_code_units_ * 2;
1706 const uint8_t* begin = reinterpret_cast<const uint8_t*>(code_item->insns_);
1707 const uint8_t* end = begin + byte_count;
1708 for (const uint8_t* p = begin; p != end; ++p) {
1709 bytecodes.push_back(*p);
1710 }
1711 return JDWP::ERR_NONE;
1712}
1713
Elliott Hughes88d63092013-01-09 09:55:54 -08001714JDWP::JdwpTag Dbg::GetFieldBasicTag(JDWP::FieldId field_id) {
Mathieu Chartier61c5ebc2014-06-05 17:42:53 -07001715 return BasicTagFromDescriptor(FromFieldId(field_id)->GetTypeDescriptor());
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001716}
1717
Elliott Hughes88d63092013-01-09 09:55:54 -08001718JDWP::JdwpTag Dbg::GetStaticFieldBasicTag(JDWP::FieldId field_id) {
Mathieu Chartier61c5ebc2014-06-05 17:42:53 -07001719 return BasicTagFromDescriptor(FromFieldId(field_id)->GetTypeDescriptor());
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001720}
1721
Elliott Hughes88d63092013-01-09 09:55:54 -08001722static JDWP::JdwpError GetFieldValueImpl(JDWP::RefTypeId ref_type_id, JDWP::ObjectId object_id,
1723 JDWP::FieldId field_id, JDWP::ExpandBuf* pReply,
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001724 bool is_static)
Ian Rogersb726dcb2012-09-05 08:57:23 -07001725 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Elliott Hughes0cf74332012-02-23 23:14:00 -08001726 JDWP::JdwpError status;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001727 mirror::Class* c = DecodeClass(ref_type_id, status);
Elliott Hughes88d63092013-01-09 09:55:54 -08001728 if (ref_type_id != 0 && c == NULL) {
Elliott Hughes0cf74332012-02-23 23:14:00 -08001729 return status;
1730 }
1731
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001732 mirror::Object* o = gRegistry->Get<mirror::Object*>(object_id);
Elliott Hughes64f574f2013-02-20 14:57:12 -08001733 if ((!is_static && o == NULL) || o == ObjectRegistry::kInvalidObject) {
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08001734 return JDWP::ERR_INVALID_OBJECT;
1735 }
Brian Carlstromea46f952013-07-30 01:26:50 -07001736 mirror::ArtField* f = FromFieldId(field_id);
Elliott Hughes0cf74332012-02-23 23:14:00 -08001737
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001738 mirror::Class* receiver_class = c;
Elliott Hughes0cf74332012-02-23 23:14:00 -08001739 if (receiver_class == NULL && o != NULL) {
1740 receiver_class = o->GetClass();
1741 }
1742 // TODO: should we give up now if receiver_class is NULL?
1743 if (receiver_class != NULL && !f->GetDeclaringClass()->IsAssignableFrom(receiver_class)) {
1744 LOG(INFO) << "ERR_INVALID_FIELDID: " << PrettyField(f) << " " << PrettyClass(receiver_class);
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08001745 return JDWP::ERR_INVALID_FIELDID;
1746 }
Elliott Hughesaed4be92011-12-02 16:16:23 -08001747
Elliott Hughes0cf74332012-02-23 23:14:00 -08001748 // The RI only enforces the static/non-static mismatch in one direction.
1749 // TODO: should we change the tests and check both?
1750 if (is_static) {
1751 if (!f->IsStatic()) {
1752 return JDWP::ERR_INVALID_FIELDID;
1753 }
1754 } else {
1755 if (f->IsStatic()) {
1756 LOG(WARNING) << "Ignoring non-NULL receiver for ObjectReference.SetValues on static field " << PrettyField(f);
Elliott Hughes0cf74332012-02-23 23:14:00 -08001757 }
1758 }
jeffhao0dfbb7e2012-11-28 15:26:03 -08001759 if (f->IsStatic()) {
1760 o = f->GetDeclaringClass();
1761 }
Elliott Hughes0cf74332012-02-23 23:14:00 -08001762
Mathieu Chartier61c5ebc2014-06-05 17:42:53 -07001763 JDWP::JdwpTag tag = BasicTagFromDescriptor(f->GetTypeDescriptor());
Jeff Hao579b0242013-11-18 13:16:49 -08001764 JValue field_value;
1765 if (tag == JDWP::JT_VOID) {
1766 LOG(FATAL) << "Unknown tag: " << tag;
1767 } else if (!IsPrimitiveTag(tag)) {
1768 field_value.SetL(f->GetObject(o));
1769 } else if (tag == JDWP::JT_DOUBLE || tag == JDWP::JT_LONG) {
1770 field_value.SetJ(f->Get64(o));
Elliott Hughesaed4be92011-12-02 16:16:23 -08001771 } else {
Jeff Hao579b0242013-11-18 13:16:49 -08001772 field_value.SetI(f->Get32(o));
Elliott Hughesaed4be92011-12-02 16:16:23 -08001773 }
Jeff Hao579b0242013-11-18 13:16:49 -08001774 Dbg::OutputJValue(tag, &field_value, pReply);
1775
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08001776 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001777}
1778
Elliott Hughes88d63092013-01-09 09:55:54 -08001779JDWP::JdwpError Dbg::GetFieldValue(JDWP::ObjectId object_id, JDWP::FieldId field_id,
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001780 JDWP::ExpandBuf* pReply) {
Elliott Hughes88d63092013-01-09 09:55:54 -08001781 return GetFieldValueImpl(0, object_id, field_id, pReply, false);
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08001782}
1783
Elliott Hughes88d63092013-01-09 09:55:54 -08001784JDWP::JdwpError Dbg::GetStaticFieldValue(JDWP::RefTypeId ref_type_id, JDWP::FieldId field_id, JDWP::ExpandBuf* pReply) {
1785 return GetFieldValueImpl(ref_type_id, 0, field_id, pReply, true);
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08001786}
1787
Elliott Hughes88d63092013-01-09 09:55:54 -08001788static JDWP::JdwpError SetFieldValueImpl(JDWP::ObjectId object_id, JDWP::FieldId field_id,
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001789 uint64_t value, int width, bool is_static)
Ian Rogersb726dcb2012-09-05 08:57:23 -07001790 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001791 mirror::Object* o = gRegistry->Get<mirror::Object*>(object_id);
Elliott Hughes64f574f2013-02-20 14:57:12 -08001792 if ((!is_static && o == NULL) || o == ObjectRegistry::kInvalidObject) {
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08001793 return JDWP::ERR_INVALID_OBJECT;
1794 }
Brian Carlstromea46f952013-07-30 01:26:50 -07001795 mirror::ArtField* f = FromFieldId(field_id);
Elliott Hughes0cf74332012-02-23 23:14:00 -08001796
1797 // The RI only enforces the static/non-static mismatch in one direction.
1798 // TODO: should we change the tests and check both?
1799 if (is_static) {
1800 if (!f->IsStatic()) {
1801 return JDWP::ERR_INVALID_FIELDID;
1802 }
1803 } else {
1804 if (f->IsStatic()) {
1805 LOG(WARNING) << "Ignoring non-NULL receiver for ObjectReference.SetValues on static field " << PrettyField(f);
Elliott Hughes0cf74332012-02-23 23:14:00 -08001806 }
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08001807 }
jeffhao0dfbb7e2012-11-28 15:26:03 -08001808 if (f->IsStatic()) {
1809 o = f->GetDeclaringClass();
1810 }
Elliott Hughesaed4be92011-12-02 16:16:23 -08001811
Mathieu Chartier61c5ebc2014-06-05 17:42:53 -07001812 JDWP::JdwpTag tag = BasicTagFromDescriptor(f->GetTypeDescriptor());
Elliott Hughesaed4be92011-12-02 16:16:23 -08001813
1814 if (IsPrimitiveTag(tag)) {
1815 if (tag == JDWP::JT_DOUBLE || tag == JDWP::JT_LONG) {
Elliott Hughes1bac54f2012-03-16 12:48:31 -07001816 CHECK_EQ(width, 8);
Sebastien Hertzd2fe10a2014-01-15 10:20:56 +01001817 // Debugging can't use transactional mode (runtime only).
1818 f->Set64<false>(o, value);
Elliott Hughesaed4be92011-12-02 16:16:23 -08001819 } else {
Elliott Hughes1bac54f2012-03-16 12:48:31 -07001820 CHECK_LE(width, 4);
Sebastien Hertzd2fe10a2014-01-15 10:20:56 +01001821 // Debugging can't use transactional mode (runtime only).
1822 f->Set32<false>(o, value);
Elliott Hughesaed4be92011-12-02 16:16:23 -08001823 }
1824 } else {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001825 mirror::Object* v = gRegistry->Get<mirror::Object*>(value);
Elliott Hughes64f574f2013-02-20 14:57:12 -08001826 if (v == ObjectRegistry::kInvalidObject) {
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -08001827 return JDWP::ERR_INVALID_OBJECT;
1828 }
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08001829 if (v != NULL) {
Mathieu Chartier61c5ebc2014-06-05 17:42:53 -07001830 mirror::Class* field_type;
1831 {
1832 StackHandleScope<3> hs(Thread::Current());
1833 HandleWrapper<mirror::Object> h_v(hs.NewHandleWrapper(&v));
1834 HandleWrapper<mirror::ArtField> h_f(hs.NewHandleWrapper(&f));
1835 HandleWrapper<mirror::Object> h_o(hs.NewHandleWrapper(&o));
1836 field_type = FieldHelper(h_f).GetType();
1837 }
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08001838 if (!field_type->IsAssignableFrom(v->GetClass())) {
1839 return JDWP::ERR_INVALID_OBJECT;
1840 }
1841 }
Sebastien Hertzd2fe10a2014-01-15 10:20:56 +01001842 // Debugging can't use transactional mode (runtime only).
1843 f->SetObject<false>(o, v);
Elliott Hughesaed4be92011-12-02 16:16:23 -08001844 }
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -08001845
1846 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001847}
1848
Elliott Hughes88d63092013-01-09 09:55:54 -08001849JDWP::JdwpError Dbg::SetFieldValue(JDWP::ObjectId object_id, JDWP::FieldId field_id, uint64_t value,
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001850 int width) {
Elliott Hughes88d63092013-01-09 09:55:54 -08001851 return SetFieldValueImpl(object_id, field_id, value, width, false);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001852}
1853
Elliott Hughes88d63092013-01-09 09:55:54 -08001854JDWP::JdwpError Dbg::SetStaticFieldValue(JDWP::FieldId field_id, uint64_t value, int width) {
1855 return SetFieldValueImpl(0, field_id, value, width, true);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001856}
1857
Elliott Hughes88d63092013-01-09 09:55:54 -08001858std::string Dbg::StringToUtf8(JDWP::ObjectId string_id) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001859 mirror::String* s = gRegistry->Get<mirror::String*>(string_id);
Elliott Hughes68fdbd02011-11-29 19:22:47 -08001860 return s->ToModifiedUtf8();
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001861}
1862
Jeff Hao579b0242013-11-18 13:16:49 -08001863void Dbg::OutputJValue(JDWP::JdwpTag tag, const JValue* return_value, JDWP::ExpandBuf* pReply) {
1864 if (IsPrimitiveTag(tag)) {
1865 expandBufAdd1(pReply, tag);
1866 if (tag == JDWP::JT_BOOLEAN || tag == JDWP::JT_BYTE) {
1867 expandBufAdd1(pReply, return_value->GetI());
1868 } else if (tag == JDWP::JT_CHAR || tag == JDWP::JT_SHORT) {
1869 expandBufAdd2BE(pReply, return_value->GetI());
1870 } else if (tag == JDWP::JT_FLOAT || tag == JDWP::JT_INT) {
1871 expandBufAdd4BE(pReply, return_value->GetI());
1872 } else if (tag == JDWP::JT_DOUBLE || tag == JDWP::JT_LONG) {
1873 expandBufAdd8BE(pReply, return_value->GetJ());
1874 } else {
1875 CHECK_EQ(tag, JDWP::JT_VOID);
1876 }
1877 } else {
Ian Rogers98379392014-02-24 16:53:16 -08001878 ScopedObjectAccessUnchecked soa(Thread::Current());
Jeff Hao579b0242013-11-18 13:16:49 -08001879 mirror::Object* value = return_value->GetL();
Ian Rogers98379392014-02-24 16:53:16 -08001880 expandBufAdd1(pReply, TagFromObject(soa, value));
Jeff Hao579b0242013-11-18 13:16:49 -08001881 expandBufAddObjectId(pReply, gRegistry->Add(value));
1882 }
1883}
1884
Elliott Hughes221229c2013-01-08 18:17:50 -08001885JDWP::JdwpError Dbg::GetThreadName(JDWP::ObjectId thread_id, std::string& name) {
jeffhaoa77f0f62012-12-05 17:19:31 -08001886 ScopedObjectAccessUnchecked soa(Thread::Current());
1887 MutexLock mu(soa.Self(), *Locks::thread_list_lock_);
Elliott Hughes221229c2013-01-08 18:17:50 -08001888 Thread* thread;
1889 JDWP::JdwpError error = DecodeThread(soa, thread_id, thread);
1890 if (error != JDWP::ERR_NONE && error != JDWP::ERR_THREAD_NOT_ALIVE) {
1891 return error;
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001892 }
Elliott Hughes221229c2013-01-08 18:17:50 -08001893
1894 // We still need to report the zombie threads' names, so we can't just call Thread::GetThreadName.
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001895 mirror::Object* thread_object = gRegistry->Get<mirror::Object*>(thread_id);
Brian Carlstromea46f952013-07-30 01:26:50 -07001896 mirror::ArtField* java_lang_Thread_name_field =
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001897 soa.DecodeField(WellKnownClasses::java_lang_Thread_name);
1898 mirror::String* s =
1899 reinterpret_cast<mirror::String*>(java_lang_Thread_name_field->GetObject(thread_object));
Elliott Hughes221229c2013-01-08 18:17:50 -08001900 if (s != NULL) {
1901 name = s->ToModifiedUtf8();
1902 }
1903 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001904}
1905
Elliott Hughes221229c2013-01-08 18:17:50 -08001906JDWP::JdwpError Dbg::GetThreadGroup(JDWP::ObjectId thread_id, JDWP::ExpandBuf* pReply) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001907 ScopedObjectAccess soa(Thread::Current());
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001908 mirror::Object* thread_object = gRegistry->Get<mirror::Object*>(thread_id);
Elliott Hughes64f574f2013-02-20 14:57:12 -08001909 if (thread_object == ObjectRegistry::kInvalidObject) {
Elliott Hughes2435a572012-02-17 16:07:41 -08001910 return JDWP::ERR_INVALID_OBJECT;
1911 }
Ian Rogers98379392014-02-24 16:53:16 -08001912 const char* old_cause = soa.Self()->StartAssertNoThreadSuspension("Debugger: GetThreadGroup");
Elliott Hughes2435a572012-02-17 16:07:41 -08001913 // Okay, so it's an object, but is it actually a thread?
Hiroshi Yamauchib5a9e3d2014-06-09 12:11:20 -07001914 JDWP::JdwpError error;
1915 {
1916 MutexLock mu(soa.Self(), *Locks::thread_list_lock_);
1917 Thread* thread;
1918 error = DecodeThread(soa, thread_id, thread);
1919 }
Elliott Hughes221229c2013-01-08 18:17:50 -08001920 if (error == JDWP::ERR_THREAD_NOT_ALIVE) {
1921 // Zombie threads are in the null group.
1922 expandBufAddObjectId(pReply, JDWP::ObjectId(0));
Sebastien Hertz52d131d2014-03-13 16:17:40 +01001923 error = JDWP::ERR_NONE;
1924 } else if (error == JDWP::ERR_NONE) {
1925 mirror::Class* c = soa.Decode<mirror::Class*>(WellKnownClasses::java_lang_Thread);
1926 CHECK(c != nullptr);
1927 mirror::ArtField* f = c->FindInstanceField("group", "Ljava/lang/ThreadGroup;");
Hiroshi Yamauchib5a9e3d2014-06-09 12:11:20 -07001928 CHECK(f != nullptr);
Sebastien Hertz52d131d2014-03-13 16:17:40 +01001929 mirror::Object* group = f->GetObject(thread_object);
Hiroshi Yamauchib5a9e3d2014-06-09 12:11:20 -07001930 CHECK(group != nullptr);
Sebastien Hertz52d131d2014-03-13 16:17:40 +01001931 JDWP::ObjectId thread_group_id = gRegistry->Add(group);
1932 expandBufAddObjectId(pReply, thread_group_id);
Elliott Hughes221229c2013-01-08 18:17:50 -08001933 }
Ian Rogers98379392014-02-24 16:53:16 -08001934 soa.Self()->EndAssertNoThreadSuspension(old_cause);
Sebastien Hertz52d131d2014-03-13 16:17:40 +01001935 return error;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001936}
1937
Elliott Hughes88d63092013-01-09 09:55:54 -08001938std::string Dbg::GetThreadGroupName(JDWP::ObjectId thread_group_id) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001939 ScopedObjectAccess soa(Thread::Current());
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001940 mirror::Object* thread_group = gRegistry->Get<mirror::Object*>(thread_group_id);
Ian Rogers98379392014-02-24 16:53:16 -08001941 CHECK(thread_group != nullptr);
1942 const char* old_cause = soa.Self()->StartAssertNoThreadSuspension("Debugger: GetThreadGroupName");
1943 mirror::Class* c = soa.Decode<mirror::Class*>(WellKnownClasses::java_lang_ThreadGroup);
1944 CHECK(c != nullptr);
Brian Carlstromea46f952013-07-30 01:26:50 -07001945 mirror::ArtField* f = c->FindInstanceField("name", "Ljava/lang/String;");
Elliott Hughes499c5132011-11-17 14:55:11 -08001946 CHECK(f != NULL);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001947 mirror::String* s = reinterpret_cast<mirror::String*>(f->GetObject(thread_group));
Ian Rogers98379392014-02-24 16:53:16 -08001948 soa.Self()->EndAssertNoThreadSuspension(old_cause);
Elliott Hughes499c5132011-11-17 14:55:11 -08001949 return s->ToModifiedUtf8();
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001950}
1951
Elliott Hughes88d63092013-01-09 09:55:54 -08001952JDWP::ObjectId Dbg::GetThreadGroupParent(JDWP::ObjectId thread_group_id) {
Ian Rogers98379392014-02-24 16:53:16 -08001953 ScopedObjectAccessUnchecked soa(Thread::Current());
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001954 mirror::Object* thread_group = gRegistry->Get<mirror::Object*>(thread_group_id);
Ian Rogers98379392014-02-24 16:53:16 -08001955 CHECK(thread_group != nullptr);
1956 const char* old_cause = soa.Self()->StartAssertNoThreadSuspension("Debugger: GetThreadGroupParent");
1957 mirror::Class* c = soa.Decode<mirror::Class*>(WellKnownClasses::java_lang_ThreadGroup);
1958 CHECK(c != nullptr);
Brian Carlstromea46f952013-07-30 01:26:50 -07001959 mirror::ArtField* f = c->FindInstanceField("parent", "Ljava/lang/ThreadGroup;");
Elliott Hughes4e235312011-12-02 11:34:15 -08001960 CHECK(f != NULL);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001961 mirror::Object* parent = f->GetObject(thread_group);
Ian Rogers98379392014-02-24 16:53:16 -08001962 soa.Self()->EndAssertNoThreadSuspension(old_cause);
Elliott Hughes4e235312011-12-02 11:34:15 -08001963 return gRegistry->Add(parent);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001964}
1965
1966JDWP::ObjectId Dbg::GetSystemThreadGroupId() {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001967 ScopedObjectAccessUnchecked soa(Thread::Current());
Brian Carlstromea46f952013-07-30 01:26:50 -07001968 mirror::ArtField* f = soa.DecodeField(WellKnownClasses::java_lang_ThreadGroup_systemThreadGroup);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001969 mirror::Object* group = f->GetObject(f->GetDeclaringClass());
Ian Rogers365c1022012-06-22 15:05:28 -07001970 return gRegistry->Add(group);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001971}
1972
1973JDWP::ObjectId Dbg::GetMainThreadGroupId() {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001974 ScopedObjectAccess soa(Thread::Current());
Brian Carlstromea46f952013-07-30 01:26:50 -07001975 mirror::ArtField* f = soa.DecodeField(WellKnownClasses::java_lang_ThreadGroup_mainThreadGroup);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001976 mirror::Object* group = f->GetObject(f->GetDeclaringClass());
Ian Rogers365c1022012-06-22 15:05:28 -07001977 return gRegistry->Add(group);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001978}
1979
Jeff Hao920af3e2013-08-28 15:46:38 -07001980JDWP::JdwpThreadStatus Dbg::ToJdwpThreadStatus(ThreadState state) {
1981 switch (state) {
1982 case kBlocked:
1983 return JDWP::TS_MONITOR;
1984 case kNative:
1985 case kRunnable:
1986 case kSuspended:
1987 return JDWP::TS_RUNNING;
1988 case kSleeping:
1989 return JDWP::TS_SLEEPING;
1990 case kStarting:
1991 case kTerminated:
1992 return JDWP::TS_ZOMBIE;
1993 case kTimedWaiting:
1994 case kWaitingForDebuggerSend:
1995 case kWaitingForDebuggerSuspension:
1996 case kWaitingForDebuggerToAttach:
Sebastien Hertz138dbfc2013-12-04 18:15:25 +01001997 case kWaitingForDeoptimization:
Jeff Hao920af3e2013-08-28 15:46:38 -07001998 case kWaitingForGcToComplete:
1999 case kWaitingForCheckPointsToRun:
2000 case kWaitingForJniOnLoad:
2001 case kWaitingForSignalCatcherOutput:
2002 case kWaitingInMainDebuggerLoop:
2003 case kWaitingInMainSignalCatcherLoop:
2004 case kWaitingPerformingGc:
2005 case kWaiting:
2006 return JDWP::TS_WAIT;
2007 // Don't add a 'default' here so the compiler can spot incompatible enum changes.
2008 }
2009 LOG(FATAL) << "Unknown thread state: " << state;
2010 return JDWP::TS_ZOMBIE;
2011}
2012
Sebastien Hertz52d131d2014-03-13 16:17:40 +01002013JDWP::JdwpError Dbg::GetThreadStatus(JDWP::ObjectId thread_id, JDWP::JdwpThreadStatus* pThreadStatus,
2014 JDWP::JdwpSuspendStatus* pSuspendStatus) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002015 ScopedObjectAccess soa(Thread::Current());
Elliott Hughes499c5132011-11-17 14:55:11 -08002016
Elliott Hughes9e0c1752013-01-09 14:02:58 -08002017 *pSuspendStatus = JDWP::SUSPEND_STATUS_NOT_SUSPENDED;
2018
Ian Rogers50b35e22012-10-04 10:09:15 -07002019 MutexLock mu(soa.Self(), *Locks::thread_list_lock_);
Elliott Hughes221229c2013-01-08 18:17:50 -08002020 Thread* thread;
2021 JDWP::JdwpError error = DecodeThread(soa, thread_id, thread);
2022 if (error != JDWP::ERR_NONE) {
2023 if (error == JDWP::ERR_THREAD_NOT_ALIVE) {
2024 *pThreadStatus = JDWP::TS_ZOMBIE;
Elliott Hughes221229c2013-01-08 18:17:50 -08002025 return JDWP::ERR_NONE;
2026 }
2027 return error;
Elliott Hughes499c5132011-11-17 14:55:11 -08002028 }
2029
Elliott Hughes9e0c1752013-01-09 14:02:58 -08002030 if (IsSuspendedForDebugger(soa, thread)) {
2031 *pSuspendStatus = JDWP::SUSPEND_STATUS_SUSPENDED;
Elliott Hughes499c5132011-11-17 14:55:11 -08002032 }
2033
Jeff Hao920af3e2013-08-28 15:46:38 -07002034 *pThreadStatus = ToJdwpThreadStatus(thread->GetState());
Elliott Hughes221229c2013-01-08 18:17:50 -08002035 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002036}
2037
Elliott Hughes221229c2013-01-08 18:17:50 -08002038JDWP::JdwpError Dbg::GetThreadDebugSuspendCount(JDWP::ObjectId thread_id, JDWP::ExpandBuf* pReply) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002039 ScopedObjectAccess soa(Thread::Current());
Ian Rogers50b35e22012-10-04 10:09:15 -07002040 MutexLock mu(soa.Self(), *Locks::thread_list_lock_);
Elliott Hughes221229c2013-01-08 18:17:50 -08002041 Thread* thread;
2042 JDWP::JdwpError error = DecodeThread(soa, thread_id, thread);
2043 if (error != JDWP::ERR_NONE) {
2044 return error;
Elliott Hughes2435a572012-02-17 16:07:41 -08002045 }
Ian Rogers50b35e22012-10-04 10:09:15 -07002046 MutexLock mu2(soa.Self(), *Locks::thread_suspend_count_lock_);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002047 expandBufAdd4BE(pReply, thread->GetDebugSuspendCount());
Elliott Hughes2435a572012-02-17 16:07:41 -08002048 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002049}
2050
Elliott Hughesf9501702013-01-11 11:22:27 -08002051JDWP::JdwpError Dbg::Interrupt(JDWP::ObjectId thread_id) {
2052 ScopedObjectAccess soa(Thread::Current());
2053 MutexLock mu(soa.Self(), *Locks::thread_list_lock_);
2054 Thread* thread;
2055 JDWP::JdwpError error = DecodeThread(soa, thread_id, thread);
2056 if (error != JDWP::ERR_NONE) {
2057 return error;
2058 }
Ian Rogersdd7624d2014-03-14 17:43:00 -07002059 thread->Interrupt(soa.Self());
Elliott Hughesf9501702013-01-11 11:22:27 -08002060 return JDWP::ERR_NONE;
2061}
2062
Elliott Hughescaf76542012-06-28 16:08:22 -07002063void Dbg::GetThreads(JDWP::ObjectId thread_group_id, std::vector<JDWP::ObjectId>& thread_ids) {
Ian Rogers365c1022012-06-22 15:05:28 -07002064 class ThreadListVisitor {
2065 public:
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002066 ThreadListVisitor(const ScopedObjectAccessUnchecked& soa, mirror::Object* desired_thread_group,
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002067 std::vector<JDWP::ObjectId>& thread_ids)
Ian Rogersb726dcb2012-09-05 08:57:23 -07002068 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_)
jeffhao0dfbb7e2012-11-28 15:26:03 -08002069 : soa_(soa), desired_thread_group_(desired_thread_group), thread_ids_(thread_ids) {}
Ian Rogers365c1022012-06-22 15:05:28 -07002070
Elliott Hughesa2155262011-11-16 16:26:58 -08002071 static void Visit(Thread* t, void* arg) {
2072 reinterpret_cast<ThreadListVisitor*>(arg)->Visit(t);
2073 }
2074
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002075 // TODO: Enable annotalysis. We know lock is held in constructor, but abstraction confuses
2076 // annotalysis.
2077 void Visit(Thread* t) NO_THREAD_SAFETY_ANALYSIS {
Elliott Hughesa2155262011-11-16 16:26:58 -08002078 if (t == Dbg::GetDebugThread()) {
2079 // Skip the JDWP thread. Some debuggers get bent out of shape when they can't suspend and
2080 // query all threads, so it's easier if we just don't tell them about this thread.
2081 return;
2082 }
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002083 mirror::Object* peer = t->GetPeer();
jeffhao0dfbb7e2012-11-28 15:26:03 -08002084 if (IsInDesiredThreadGroup(peer)) {
Ian Rogers120f1c72012-09-28 17:17:10 -07002085 thread_ids_.push_back(gRegistry->Add(peer));
Elliott Hughesa2155262011-11-16 16:26:58 -08002086 }
2087 }
2088
Ian Rogers365c1022012-06-22 15:05:28 -07002089 private:
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002090 bool IsInDesiredThreadGroup(mirror::Object* peer)
jeffhao0dfbb7e2012-11-28 15:26:03 -08002091 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
jeffhao0dfbb7e2012-11-28 15:26:03 -08002092 // peer might be NULL if the thread is still starting up.
2093 if (peer == NULL) {
2094 // We can't tell the debugger about this thread yet.
2095 // TODO: if we identified threads to the debugger by their Thread*
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002096 // rather than their peer's mirror::Object*, we could fix this.
jeffhao0dfbb7e2012-11-28 15:26:03 -08002097 // Doing so might help us report ZOMBIE threads too.
2098 return false;
2099 }
jeffhaoc1e04902012-12-13 12:41:10 -08002100 // Do we want threads from all thread groups?
2101 if (desired_thread_group_ == NULL) {
2102 return true;
2103 }
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002104 mirror::Object* group = soa_.DecodeField(WellKnownClasses::java_lang_Thread_group)->GetObject(peer);
jeffhao0dfbb7e2012-11-28 15:26:03 -08002105 return (group == desired_thread_group_);
2106 }
2107
Mathieu Chartierdbe6f462012-09-25 16:54:50 -07002108 const ScopedObjectAccessUnchecked& soa_;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002109 mirror::Object* const desired_thread_group_;
Elliott Hughescaf76542012-06-28 16:08:22 -07002110 std::vector<JDWP::ObjectId>& thread_ids_;
Elliott Hughesa2155262011-11-16 16:26:58 -08002111 };
2112
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002113 ScopedObjectAccessUnchecked soa(Thread::Current());
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002114 mirror::Object* thread_group = gRegistry->Get<mirror::Object*>(thread_group_id);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002115 ThreadListVisitor tlv(soa, thread_group, thread_ids);
Ian Rogers50b35e22012-10-04 10:09:15 -07002116 MutexLock mu(soa.Self(), *Locks::thread_list_lock_);
Elliott Hughesf8349362012-06-18 15:00:06 -07002117 Runtime::Current()->GetThreadList()->ForEach(ThreadListVisitor::Visit, &tlv);
Elliott Hughescaf76542012-06-28 16:08:22 -07002118}
Elliott Hughesa2155262011-11-16 16:26:58 -08002119
Elliott Hughescaf76542012-06-28 16:08:22 -07002120void Dbg::GetChildThreadGroups(JDWP::ObjectId thread_group_id, std::vector<JDWP::ObjectId>& child_thread_group_ids) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002121 ScopedObjectAccess soa(Thread::Current());
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002122 mirror::Object* thread_group = gRegistry->Get<mirror::Object*>(thread_group_id);
Elliott Hughescaf76542012-06-28 16:08:22 -07002123
2124 // Get the ArrayList<ThreadGroup> "groups" out of this thread group...
Brian Carlstromea46f952013-07-30 01:26:50 -07002125 mirror::ArtField* groups_field = thread_group->GetClass()->FindInstanceField("groups", "Ljava/util/List;");
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002126 mirror::Object* groups_array_list = groups_field->GetObject(thread_group);
Elliott Hughescaf76542012-06-28 16:08:22 -07002127
2128 // Get the array and size out of the ArrayList<ThreadGroup>...
Brian Carlstromea46f952013-07-30 01:26:50 -07002129 mirror::ArtField* array_field = groups_array_list->GetClass()->FindInstanceField("array", "[Ljava/lang/Object;");
2130 mirror::ArtField* size_field = groups_array_list->GetClass()->FindInstanceField("size", "I");
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002131 mirror::ObjectArray<mirror::Object>* groups_array =
2132 array_field->GetObject(groups_array_list)->AsObjectArray<mirror::Object>();
Elliott Hughescaf76542012-06-28 16:08:22 -07002133 const int32_t size = size_field->GetInt(groups_array_list);
2134
2135 // Copy the first 'size' elements out of the array into the result.
2136 for (int32_t i = 0; i < size; ++i) {
2137 child_thread_group_ids.push_back(gRegistry->Add(groups_array->Get(i)));
Elliott Hughesa2155262011-11-16 16:26:58 -08002138 }
2139}
2140
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002141static int GetStackDepth(Thread* thread)
Ian Rogersb726dcb2012-09-05 08:57:23 -07002142 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Ian Rogers0399dde2012-06-06 17:09:28 -07002143 struct CountStackDepthVisitor : public StackVisitor {
Brian Carlstrom93ba8932013-07-17 21:31:49 -07002144 explicit CountStackDepthVisitor(Thread* thread)
Ian Rogers7a22fa62013-01-23 12:16:16 -08002145 : StackVisitor(thread, NULL), depth(0) {}
Ian Rogers0399dde2012-06-06 17:09:28 -07002146
Elliott Hughes64f574f2013-02-20 14:57:12 -08002147 // TODO: Enable annotalysis. We know lock is held in constructor, but abstraction confuses
2148 // annotalysis.
2149 bool VisitFrame() NO_THREAD_SAFETY_ANALYSIS {
Ian Rogers0399dde2012-06-06 17:09:28 -07002150 if (!GetMethod()->IsRuntimeMethod()) {
Elliott Hughesf8a2df72011-12-01 12:19:54 -08002151 ++depth;
2152 }
Elliott Hughes530fa002012-03-12 11:44:49 -07002153 return true;
Elliott Hughesa2e54f62011-11-17 13:01:30 -08002154 }
2155 size_t depth;
2156 };
Elliott Hughes08fc03a2012-06-26 17:34:00 -07002157
Ian Rogers7a22fa62013-01-23 12:16:16 -08002158 CountStackDepthVisitor visitor(thread);
Ian Rogers0399dde2012-06-06 17:09:28 -07002159 visitor.WalkStack();
Elliott Hughesa2e54f62011-11-17 13:01:30 -08002160 return visitor.depth;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002161}
2162
Elliott Hughes221229c2013-01-08 18:17:50 -08002163JDWP::JdwpError Dbg::GetThreadFrameCount(JDWP::ObjectId thread_id, size_t& result) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002164 ScopedObjectAccess soa(Thread::Current());
jeffhaoa77f0f62012-12-05 17:19:31 -08002165 MutexLock mu(soa.Self(), *Locks::thread_list_lock_);
Elliott Hughes221229c2013-01-08 18:17:50 -08002166 Thread* thread;
2167 JDWP::JdwpError error = DecodeThread(soa, thread_id, thread);
2168 if (error != JDWP::ERR_NONE) {
2169 return error;
2170 }
Elliott Hughesf15f4a02013-01-09 10:09:38 -08002171 if (!IsSuspendedForDebugger(soa, thread)) {
2172 return JDWP::ERR_THREAD_NOT_SUSPENDED;
2173 }
Elliott Hughes221229c2013-01-08 18:17:50 -08002174 result = GetStackDepth(thread);
2175 return JDWP::ERR_NONE;
Elliott Hughes86964332012-02-15 19:37:42 -08002176}
2177
Ian Rogers306057f2012-11-26 12:45:53 -08002178JDWP::JdwpError Dbg::GetThreadFrames(JDWP::ObjectId thread_id, size_t start_frame,
2179 size_t frame_count, JDWP::ExpandBuf* buf) {
Elliott Hughes6e9d22c2012-06-22 15:02:37 -07002180 class GetFrameVisitor : public StackVisitor {
2181 public:
Ian Rogers7a22fa62013-01-23 12:16:16 -08002182 GetFrameVisitor(Thread* thread, size_t start_frame, size_t frame_count, JDWP::ExpandBuf* buf)
Ian Rogersb726dcb2012-09-05 08:57:23 -07002183 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_)
Ian Rogers7a22fa62013-01-23 12:16:16 -08002184 : StackVisitor(thread, NULL), depth_(0),
Elliott Hughes6e9d22c2012-06-22 15:02:37 -07002185 start_frame_(start_frame), frame_count_(frame_count), buf_(buf) {
2186 expandBufAdd4BE(buf_, frame_count_);
Elliott Hughes03181a82011-11-17 17:22:21 -08002187 }
Ian Rogers0399dde2012-06-06 17:09:28 -07002188
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002189 // TODO: Enable annotalysis. We know lock is held in constructor, but abstraction confuses
2190 // annotalysis.
2191 virtual bool VisitFrame() NO_THREAD_SAFETY_ANALYSIS {
Ian Rogers0399dde2012-06-06 17:09:28 -07002192 if (GetMethod()->IsRuntimeMethod()) {
Brian Carlstrom7934ac22013-07-26 10:54:15 -07002193 return true; // The debugger can't do anything useful with a frame that has no Method*.
Elliott Hughes03181a82011-11-17 17:22:21 -08002194 }
Elliott Hughes6e9d22c2012-06-22 15:02:37 -07002195 if (depth_ >= start_frame_ + frame_count_) {
Elliott Hughes530fa002012-03-12 11:44:49 -07002196 return false;
Elliott Hughes03181a82011-11-17 17:22:21 -08002197 }
Elliott Hughes6e9d22c2012-06-22 15:02:37 -07002198 if (depth_ >= start_frame_) {
2199 JDWP::FrameId frame_id(GetFrameId());
2200 JDWP::JdwpLocation location;
2201 SetLocation(location, GetMethod(), GetDexPc());
Ian Rogersef7d42f2014-01-06 12:55:46 -08002202 VLOG(jdwp) << StringPrintf(" Frame %3zd: id=%3" PRIu64 " ", depth_, frame_id) << location;
Elliott Hughes6e9d22c2012-06-22 15:02:37 -07002203 expandBufAdd8BE(buf_, frame_id);
2204 expandBufAddLocation(buf_, location);
2205 }
2206 ++depth_;
Elliott Hughes530fa002012-03-12 11:44:49 -07002207 return true;
Elliott Hughes03181a82011-11-17 17:22:21 -08002208 }
Elliott Hughes6e9d22c2012-06-22 15:02:37 -07002209
2210 private:
2211 size_t depth_;
2212 const size_t start_frame_;
2213 const size_t frame_count_;
2214 JDWP::ExpandBuf* buf_;
Elliott Hughes03181a82011-11-17 17:22:21 -08002215 };
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002216
2217 ScopedObjectAccessUnchecked soa(Thread::Current());
jeffhaoa77f0f62012-12-05 17:19:31 -08002218 MutexLock mu(soa.Self(), *Locks::thread_list_lock_);
Elliott Hughes221229c2013-01-08 18:17:50 -08002219 Thread* thread;
2220 JDWP::JdwpError error = DecodeThread(soa, thread_id, thread);
2221 if (error != JDWP::ERR_NONE) {
2222 return error;
2223 }
Elliott Hughesf15f4a02013-01-09 10:09:38 -08002224 if (!IsSuspendedForDebugger(soa, thread)) {
2225 return JDWP::ERR_THREAD_NOT_SUSPENDED;
2226 }
Ian Rogers7a22fa62013-01-23 12:16:16 -08002227 GetFrameVisitor visitor(thread, start_frame, frame_count, buf);
Ian Rogers0399dde2012-06-06 17:09:28 -07002228 visitor.WalkStack();
Elliott Hughes6e9d22c2012-06-22 15:02:37 -07002229 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002230}
2231
2232JDWP::ObjectId Dbg::GetThreadSelfId() {
Mathieu Chartierdbe6f462012-09-25 16:54:50 -07002233 ScopedObjectAccessUnchecked soa(Thread::Current());
Ian Rogerscfaa4552012-11-26 21:00:08 -08002234 return gRegistry->Add(soa.Self()->GetPeer());
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002235}
2236
Elliott Hughes475fc232011-10-25 15:00:35 -07002237void Dbg::SuspendVM() {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002238 Runtime::Current()->GetThreadList()->SuspendAllForDebugger();
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002239}
2240
2241void Dbg::ResumeVM() {
Elliott Hughesc61a2672012-06-21 14:52:29 -07002242 Runtime::Current()->GetThreadList()->UndoDebuggerSuspensions();
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002243}
2244
Elliott Hughes221229c2013-01-08 18:17:50 -08002245JDWP::JdwpError Dbg::SuspendThread(JDWP::ObjectId thread_id, bool request_suspension) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002246 ScopedLocalRef<jobject> peer(Thread::Current()->GetJniEnv(), NULL);
2247 {
2248 ScopedObjectAccess soa(Thread::Current());
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002249 peer.reset(soa.AddLocalReference<jobject>(gRegistry->Get<mirror::Object*>(thread_id)));
Elliott Hughes4e235312011-12-02 11:34:15 -08002250 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002251 if (peer.get() == NULL) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002252 return JDWP::ERR_THREAD_NOT_ALIVE;
2253 }
2254 // Suspend thread to build stack trace.
Elliott Hughesf327e072013-01-09 16:01:26 -08002255 bool timed_out;
Ian Rogersd9c4fc92013-10-01 19:45:43 -07002256 Thread* thread = ThreadList::SuspendThreadByPeer(peer.get(), request_suspension, true,
2257 &timed_out);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002258 if (thread != NULL) {
2259 return JDWP::ERR_NONE;
Elliott Hughesf327e072013-01-09 16:01:26 -08002260 } else if (timed_out) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002261 return JDWP::ERR_INTERNAL;
2262 } else {
2263 return JDWP::ERR_THREAD_NOT_ALIVE;
2264 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002265}
2266
Elliott Hughes221229c2013-01-08 18:17:50 -08002267void Dbg::ResumeThread(JDWP::ObjectId thread_id) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002268 ScopedObjectAccessUnchecked soa(Thread::Current());
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002269 mirror::Object* peer = gRegistry->Get<mirror::Object*>(thread_id);
jeffhaoa77f0f62012-12-05 17:19:31 -08002270 Thread* thread;
2271 {
2272 MutexLock mu(soa.Self(), *Locks::thread_list_lock_);
2273 thread = Thread::FromManagedThread(soa, peer);
2274 }
Elliott Hughes4e235312011-12-02 11:34:15 -08002275 if (thread == NULL) {
2276 LOG(WARNING) << "No such thread for resume: " << peer;
2277 return;
2278 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002279 bool needs_resume;
2280 {
Ian Rogers50b35e22012-10-04 10:09:15 -07002281 MutexLock mu2(soa.Self(), *Locks::thread_suspend_count_lock_);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002282 needs_resume = thread->GetSuspendCount() > 0;
2283 }
2284 if (needs_resume) {
Elliott Hughes546b9862012-06-20 16:06:13 -07002285 Runtime::Current()->GetThreadList()->Resume(thread, true);
2286 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002287}
2288
2289void Dbg::SuspendSelf() {
Elliott Hughes475fc232011-10-25 15:00:35 -07002290 Runtime::Current()->GetThreadList()->SuspendSelfForDebugger();
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002291}
2292
Ian Rogers0399dde2012-06-06 17:09:28 -07002293struct GetThisVisitor : public StackVisitor {
Ian Rogers7a22fa62013-01-23 12:16:16 -08002294 GetThisVisitor(Thread* thread, Context* context, JDWP::FrameId frame_id)
Ian Rogersb726dcb2012-09-05 08:57:23 -07002295 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_)
Ian Rogers7a22fa62013-01-23 12:16:16 -08002296 : StackVisitor(thread, context), this_object(NULL), frame_id(frame_id) {}
Ian Rogers0399dde2012-06-06 17:09:28 -07002297
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002298 // TODO: Enable annotalysis. We know lock is held in constructor, but abstraction confuses
2299 // annotalysis.
2300 virtual bool VisitFrame() NO_THREAD_SAFETY_ANALYSIS {
Elliott Hughes6e9d22c2012-06-22 15:02:37 -07002301 if (frame_id != GetFrameId()) {
Ian Rogers0399dde2012-06-06 17:09:28 -07002302 return true; // continue
Ian Rogers0399dde2012-06-06 17:09:28 -07002303 } else {
Ian Rogers62d6c772013-02-27 08:32:07 -08002304 this_object = GetThisObject();
2305 return false;
Ian Rogers0399dde2012-06-06 17:09:28 -07002306 }
Elliott Hughes86b00102011-12-05 17:54:26 -08002307 }
Ian Rogers0399dde2012-06-06 17:09:28 -07002308
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002309 mirror::Object* this_object;
Elliott Hughes6e9d22c2012-06-22 15:02:37 -07002310 JDWP::FrameId frame_id;
Ian Rogers0399dde2012-06-06 17:09:28 -07002311};
2312
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002313JDWP::JdwpError Dbg::GetThisObject(JDWP::ObjectId thread_id, JDWP::FrameId frame_id,
2314 JDWP::ObjectId* result) {
2315 ScopedObjectAccessUnchecked soa(Thread::Current());
2316 Thread* thread;
2317 {
Ian Rogers50b35e22012-10-04 10:09:15 -07002318 MutexLock mu(soa.Self(), *Locks::thread_list_lock_);
Elliott Hughes221229c2013-01-08 18:17:50 -08002319 JDWP::JdwpError error = DecodeThread(soa, thread_id, thread);
2320 if (error != JDWP::ERR_NONE) {
2321 return error;
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002322 }
Elliott Hughes9e0c1752013-01-09 14:02:58 -08002323 if (!IsSuspendedForDebugger(soa, thread)) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002324 return JDWP::ERR_THREAD_NOT_SUSPENDED;
2325 }
Elliott Hughes6e9d22c2012-06-22 15:02:37 -07002326 }
Ian Rogers700a4022014-05-19 16:49:03 -07002327 std::unique_ptr<Context> context(Context::Create());
Ian Rogers7a22fa62013-01-23 12:16:16 -08002328 GetThisVisitor visitor(thread, context.get(), frame_id);
Ian Rogers0399dde2012-06-06 17:09:28 -07002329 visitor.WalkStack();
Elliott Hughes6e9d22c2012-06-22 15:02:37 -07002330 *result = gRegistry->Add(visitor.this_object);
2331 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002332}
2333
Sebastien Hertzcb19ebf2014-03-11 15:26:35 +01002334JDWP::JdwpError Dbg::GetLocalValue(JDWP::ObjectId thread_id, JDWP::FrameId frame_id, int slot,
2335 JDWP::JdwpTag tag, uint8_t* buf, size_t width) {
Ian Rogers0399dde2012-06-06 17:09:28 -07002336 struct GetLocalVisitor : public StackVisitor {
Ian Rogers98379392014-02-24 16:53:16 -08002337 GetLocalVisitor(const ScopedObjectAccessUnchecked& soa, Thread* thread, Context* context,
2338 JDWP::FrameId frame_id, int slot, JDWP::JdwpTag tag, uint8_t* buf, size_t width)
Ian Rogersb726dcb2012-09-05 08:57:23 -07002339 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_)
Ian Rogers98379392014-02-24 16:53:16 -08002340 : StackVisitor(thread, context), soa_(soa), frame_id_(frame_id), slot_(slot), tag_(tag),
Sebastien Hertzcb19ebf2014-03-11 15:26:35 +01002341 buf_(buf), width_(width), error_(JDWP::ERR_NONE) {}
Ian Rogersca190662012-06-26 15:45:57 -07002342
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002343 // TODO: Enable annotalysis. We know lock is held in constructor, but abstraction confuses
2344 // annotalysis.
2345 bool VisitFrame() NO_THREAD_SAFETY_ANALYSIS {
Ian Rogers0399dde2012-06-06 17:09:28 -07002346 if (GetFrameId() != frame_id_) {
2347 return true; // Not our frame, carry on.
Elliott Hughesdbb40792011-11-18 17:05:22 -08002348 }
Ian Rogers0399dde2012-06-06 17:09:28 -07002349 // TODO: check that the tag is compatible with the actual type of the slot!
Sebastien Hertzcb19ebf2014-03-11 15:26:35 +01002350 // TODO: check slot is valid for this method or return INVALID_SLOT error.
Brian Carlstromea46f952013-07-30 01:26:50 -07002351 mirror::ArtMethod* m = GetMethod();
Sebastien Hertzcb19ebf2014-03-11 15:26:35 +01002352 if (m->IsNative()) {
2353 // We can't read local value from native method.
2354 error_ = JDWP::ERR_OPAQUE_FRAME;
2355 return false;
2356 }
Ian Rogers0399dde2012-06-06 17:09:28 -07002357 uint16_t reg = DemangleSlot(slot_, m);
Elliott Hughesdbb40792011-11-18 17:05:22 -08002358
Ian Rogers0399dde2012-06-06 17:09:28 -07002359 switch (tag_) {
2360 case JDWP::JT_BOOLEAN:
2361 {
2362 CHECK_EQ(width_, 1U);
Ian Rogers2bcb4a42012-11-08 10:39:18 -08002363 uint32_t intVal = GetVReg(m, reg, kIntVReg);
Ian Rogers0399dde2012-06-06 17:09:28 -07002364 VLOG(jdwp) << "get boolean local " << reg << " = " << intVal;
2365 JDWP::Set1(buf_+1, intVal != 0);
2366 }
2367 break;
2368 case JDWP::JT_BYTE:
2369 {
2370 CHECK_EQ(width_, 1U);
Ian Rogers2bcb4a42012-11-08 10:39:18 -08002371 uint32_t intVal = GetVReg(m, reg, kIntVReg);
Ian Rogers0399dde2012-06-06 17:09:28 -07002372 VLOG(jdwp) << "get byte local " << reg << " = " << intVal;
2373 JDWP::Set1(buf_+1, intVal);
2374 }
2375 break;
2376 case JDWP::JT_SHORT:
2377 case JDWP::JT_CHAR:
2378 {
2379 CHECK_EQ(width_, 2U);
Ian Rogers2bcb4a42012-11-08 10:39:18 -08002380 uint32_t intVal = GetVReg(m, reg, kIntVReg);
Ian Rogers0399dde2012-06-06 17:09:28 -07002381 VLOG(jdwp) << "get short/char local " << reg << " = " << intVal;
2382 JDWP::Set2BE(buf_+1, intVal);
2383 }
2384 break;
2385 case JDWP::JT_INT:
Ian Rogers2bcb4a42012-11-08 10:39:18 -08002386 {
2387 CHECK_EQ(width_, 4U);
2388 uint32_t intVal = GetVReg(m, reg, kIntVReg);
2389 VLOG(jdwp) << "get int local " << reg << " = " << intVal;
2390 JDWP::Set4BE(buf_+1, intVal);
2391 }
2392 break;
Ian Rogers0399dde2012-06-06 17:09:28 -07002393 case JDWP::JT_FLOAT:
2394 {
2395 CHECK_EQ(width_, 4U);
Ian Rogers2bcb4a42012-11-08 10:39:18 -08002396 uint32_t intVal = GetVReg(m, reg, kFloatVReg);
Ian Rogers0399dde2012-06-06 17:09:28 -07002397 VLOG(jdwp) << "get int/float local " << reg << " = " << intVal;
2398 JDWP::Set4BE(buf_+1, intVal);
2399 }
2400 break;
2401 case JDWP::JT_ARRAY:
2402 {
2403 CHECK_EQ(width_, sizeof(JDWP::ObjectId));
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002404 mirror::Object* o = reinterpret_cast<mirror::Object*>(GetVReg(m, reg, kReferenceVReg));
Ian Rogers0399dde2012-06-06 17:09:28 -07002405 VLOG(jdwp) << "get array local " << reg << " = " << o;
Mathieu Chartier590fee92013-09-13 13:46:47 -07002406 if (!Runtime::Current()->GetHeap()->IsValidObjectAddress(o)) {
Ian Rogers0399dde2012-06-06 17:09:28 -07002407 LOG(FATAL) << "Register " << reg << " expected to hold array: " << o;
2408 }
2409 JDWP::SetObjectId(buf_+1, gRegistry->Add(o));
2410 }
2411 break;
2412 case JDWP::JT_CLASS_LOADER:
2413 case JDWP::JT_CLASS_OBJECT:
2414 case JDWP::JT_OBJECT:
2415 case JDWP::JT_STRING:
2416 case JDWP::JT_THREAD:
2417 case JDWP::JT_THREAD_GROUP:
2418 {
2419 CHECK_EQ(width_, sizeof(JDWP::ObjectId));
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002420 mirror::Object* o = reinterpret_cast<mirror::Object*>(GetVReg(m, reg, kReferenceVReg));
Ian Rogers0399dde2012-06-06 17:09:28 -07002421 VLOG(jdwp) << "get object local " << reg << " = " << o;
Mathieu Chartier590fee92013-09-13 13:46:47 -07002422 if (!Runtime::Current()->GetHeap()->IsValidObjectAddress(o)) {
Ian Rogers0399dde2012-06-06 17:09:28 -07002423 LOG(FATAL) << "Register " << reg << " expected to hold object: " << o;
2424 }
Ian Rogers98379392014-02-24 16:53:16 -08002425 tag_ = TagFromObject(soa_, o);
Ian Rogers0399dde2012-06-06 17:09:28 -07002426 JDWP::SetObjectId(buf_+1, gRegistry->Add(o));
2427 }
2428 break;
2429 case JDWP::JT_DOUBLE:
Ian Rogers2bcb4a42012-11-08 10:39:18 -08002430 {
2431 CHECK_EQ(width_, 8U);
2432 uint32_t lo = GetVReg(m, reg, kDoubleLoVReg);
2433 uint64_t hi = GetVReg(m, reg + 1, kDoubleHiVReg);
2434 uint64_t longVal = (hi << 32) | lo;
2435 VLOG(jdwp) << "get double/long local " << hi << ":" << lo << " = " << longVal;
2436 JDWP::Set8BE(buf_+1, longVal);
2437 }
2438 break;
Ian Rogers0399dde2012-06-06 17:09:28 -07002439 case JDWP::JT_LONG:
2440 {
2441 CHECK_EQ(width_, 8U);
Ian Rogers2bcb4a42012-11-08 10:39:18 -08002442 uint32_t lo = GetVReg(m, reg, kLongLoVReg);
2443 uint64_t hi = GetVReg(m, reg + 1, kLongHiVReg);
Ian Rogers0399dde2012-06-06 17:09:28 -07002444 uint64_t longVal = (hi << 32) | lo;
2445 VLOG(jdwp) << "get double/long local " << hi << ":" << lo << " = " << longVal;
2446 JDWP::Set8BE(buf_+1, longVal);
2447 }
2448 break;
2449 default:
2450 LOG(FATAL) << "Unknown tag " << tag_;
2451 break;
2452 }
2453
2454 // Prepend tag, which may have been updated.
2455 JDWP::Set1(buf_, tag_);
2456 return false;
2457 }
Ian Rogers98379392014-02-24 16:53:16 -08002458 const ScopedObjectAccessUnchecked& soa_;
Ian Rogers0399dde2012-06-06 17:09:28 -07002459 const JDWP::FrameId frame_id_;
2460 const int slot_;
2461 JDWP::JdwpTag tag_;
2462 uint8_t* const buf_;
2463 const size_t width_;
Sebastien Hertzcb19ebf2014-03-11 15:26:35 +01002464 JDWP::JdwpError error_;
Ian Rogers0399dde2012-06-06 17:09:28 -07002465 };
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002466
2467 ScopedObjectAccessUnchecked soa(Thread::Current());
jeffhaoa77f0f62012-12-05 17:19:31 -08002468 MutexLock mu(soa.Self(), *Locks::thread_list_lock_);
Elliott Hughes221229c2013-01-08 18:17:50 -08002469 Thread* thread;
2470 JDWP::JdwpError error = DecodeThread(soa, thread_id, thread);
2471 if (error != JDWP::ERR_NONE) {
Sebastien Hertzcb19ebf2014-03-11 15:26:35 +01002472 return error;
Elliott Hughes221229c2013-01-08 18:17:50 -08002473 }
Sebastien Hertzcb19ebf2014-03-11 15:26:35 +01002474 // TODO check thread is suspended by the debugger ?
Ian Rogers700a4022014-05-19 16:49:03 -07002475 std::unique_ptr<Context> context(Context::Create());
Ian Rogers98379392014-02-24 16:53:16 -08002476 GetLocalVisitor visitor(soa, thread, context.get(), frame_id, slot, tag, buf, width);
Ian Rogers0399dde2012-06-06 17:09:28 -07002477 visitor.WalkStack();
Sebastien Hertzcb19ebf2014-03-11 15:26:35 +01002478 return visitor.error_;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002479}
2480
Sebastien Hertzcb19ebf2014-03-11 15:26:35 +01002481JDWP::JdwpError Dbg::SetLocalValue(JDWP::ObjectId thread_id, JDWP::FrameId frame_id, int slot,
2482 JDWP::JdwpTag tag, uint64_t value, size_t width) {
Ian Rogers0399dde2012-06-06 17:09:28 -07002483 struct SetLocalVisitor : public StackVisitor {
Ian Rogers7a22fa62013-01-23 12:16:16 -08002484 SetLocalVisitor(Thread* thread, Context* context,
Ian Rogers0399dde2012-06-06 17:09:28 -07002485 JDWP::FrameId frame_id, int slot, JDWP::JdwpTag tag, uint64_t value,
Ian Rogersca190662012-06-26 15:45:57 -07002486 size_t width)
Ian Rogersb726dcb2012-09-05 08:57:23 -07002487 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_)
Ian Rogers7a22fa62013-01-23 12:16:16 -08002488 : StackVisitor(thread, context),
Sebastien Hertzcb19ebf2014-03-11 15:26:35 +01002489 frame_id_(frame_id), slot_(slot), tag_(tag), value_(value), width_(width),
2490 error_(JDWP::ERR_NONE) {}
Ian Rogersca190662012-06-26 15:45:57 -07002491
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002492 // TODO: Enable annotalysis. We know lock is held in constructor, but abstraction confuses
2493 // annotalysis.
2494 bool VisitFrame() NO_THREAD_SAFETY_ANALYSIS {
Ian Rogers0399dde2012-06-06 17:09:28 -07002495 if (GetFrameId() != frame_id_) {
2496 return true; // Not our frame, carry on.
2497 }
2498 // TODO: check that the tag is compatible with the actual type of the slot!
Sebastien Hertzcb19ebf2014-03-11 15:26:35 +01002499 // TODO: check slot is valid for this method or return INVALID_SLOT error.
Brian Carlstromea46f952013-07-30 01:26:50 -07002500 mirror::ArtMethod* m = GetMethod();
Sebastien Hertzcb19ebf2014-03-11 15:26:35 +01002501 if (m->IsNative()) {
2502 // We can't read local value from native method.
2503 error_ = JDWP::ERR_OPAQUE_FRAME;
2504 return false;
2505 }
Ian Rogers0399dde2012-06-06 17:09:28 -07002506 uint16_t reg = DemangleSlot(slot_, m);
2507
2508 switch (tag_) {
2509 case JDWP::JT_BOOLEAN:
2510 case JDWP::JT_BYTE:
2511 CHECK_EQ(width_, 1U);
Ian Rogers2bcb4a42012-11-08 10:39:18 -08002512 SetVReg(m, reg, static_cast<uint32_t>(value_), kIntVReg);
Ian Rogers0399dde2012-06-06 17:09:28 -07002513 break;
2514 case JDWP::JT_SHORT:
2515 case JDWP::JT_CHAR:
2516 CHECK_EQ(width_, 2U);
Ian Rogers2bcb4a42012-11-08 10:39:18 -08002517 SetVReg(m, reg, static_cast<uint32_t>(value_), kIntVReg);
Ian Rogers0399dde2012-06-06 17:09:28 -07002518 break;
2519 case JDWP::JT_INT:
Ian Rogers2bcb4a42012-11-08 10:39:18 -08002520 CHECK_EQ(width_, 4U);
2521 SetVReg(m, reg, static_cast<uint32_t>(value_), kIntVReg);
2522 break;
Ian Rogers0399dde2012-06-06 17:09:28 -07002523 case JDWP::JT_FLOAT:
2524 CHECK_EQ(width_, 4U);
Ian Rogers2bcb4a42012-11-08 10:39:18 -08002525 SetVReg(m, reg, static_cast<uint32_t>(value_), kFloatVReg);
Ian Rogers0399dde2012-06-06 17:09:28 -07002526 break;
2527 case JDWP::JT_ARRAY:
2528 case JDWP::JT_OBJECT:
2529 case JDWP::JT_STRING:
2530 {
2531 CHECK_EQ(width_, sizeof(JDWP::ObjectId));
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002532 mirror::Object* o = gRegistry->Get<mirror::Object*>(static_cast<JDWP::ObjectId>(value_));
Elliott Hughes64f574f2013-02-20 14:57:12 -08002533 if (o == ObjectRegistry::kInvalidObject) {
Ian Rogers0399dde2012-06-06 17:09:28 -07002534 UNIMPLEMENTED(FATAL) << "return an error code when given an invalid object to store";
2535 }
Ian Rogers2bcb4a42012-11-08 10:39:18 -08002536 SetVReg(m, reg, static_cast<uint32_t>(reinterpret_cast<uintptr_t>(o)), kReferenceVReg);
Ian Rogers0399dde2012-06-06 17:09:28 -07002537 }
2538 break;
2539 case JDWP::JT_DOUBLE:
Ian Rogers2bcb4a42012-11-08 10:39:18 -08002540 CHECK_EQ(width_, 8U);
2541 SetVReg(m, reg, static_cast<uint32_t>(value_), kDoubleLoVReg);
2542 SetVReg(m, reg + 1, static_cast<uint32_t>(value_ >> 32), kDoubleHiVReg);
2543 break;
Ian Rogers0399dde2012-06-06 17:09:28 -07002544 case JDWP::JT_LONG:
2545 CHECK_EQ(width_, 8U);
Ian Rogers2bcb4a42012-11-08 10:39:18 -08002546 SetVReg(m, reg, static_cast<uint32_t>(value_), kLongLoVReg);
2547 SetVReg(m, reg + 1, static_cast<uint32_t>(value_ >> 32), kLongHiVReg);
Ian Rogers0399dde2012-06-06 17:09:28 -07002548 break;
2549 default:
2550 LOG(FATAL) << "Unknown tag " << tag_;
2551 break;
2552 }
2553 return false;
2554 }
2555
2556 const JDWP::FrameId frame_id_;
2557 const int slot_;
2558 const JDWP::JdwpTag tag_;
2559 const uint64_t value_;
2560 const size_t width_;
Sebastien Hertzcb19ebf2014-03-11 15:26:35 +01002561 JDWP::JdwpError error_;
Ian Rogers0399dde2012-06-06 17:09:28 -07002562 };
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002563
2564 ScopedObjectAccessUnchecked soa(Thread::Current());
jeffhaoa77f0f62012-12-05 17:19:31 -08002565 MutexLock mu(soa.Self(), *Locks::thread_list_lock_);
Elliott Hughes221229c2013-01-08 18:17:50 -08002566 Thread* thread;
2567 JDWP::JdwpError error = DecodeThread(soa, thread_id, thread);
2568 if (error != JDWP::ERR_NONE) {
Sebastien Hertzcb19ebf2014-03-11 15:26:35 +01002569 return error;
Elliott Hughes221229c2013-01-08 18:17:50 -08002570 }
Sebastien Hertzcb19ebf2014-03-11 15:26:35 +01002571 // TODO check thread is suspended by the debugger ?
Ian Rogers700a4022014-05-19 16:49:03 -07002572 std::unique_ptr<Context> context(Context::Create());
Ian Rogers7a22fa62013-01-23 12:16:16 -08002573 SetLocalVisitor visitor(thread, context.get(), frame_id, slot, tag, value, width);
Ian Rogers0399dde2012-06-06 17:09:28 -07002574 visitor.WalkStack();
Sebastien Hertzcb19ebf2014-03-11 15:26:35 +01002575 return visitor.error_;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002576}
2577
Sebastien Hertz3f52eaf2014-04-04 17:50:18 +02002578JDWP::ObjectId Dbg::GetThisObjectIdForEvent(mirror::Object* this_object) {
2579 // If 'this_object' isn't already in the registry, we know that we're not looking for it, so
2580 // there's no point adding it to the registry and burning through ids.
2581 // When registering an event request with an instance filter, we've been given an existing object
2582 // id so it must already be present in the registry when the event fires.
2583 JDWP::ObjectId this_id = 0;
2584 if (this_object != nullptr && gRegistry->Contains(this_object)) {
2585 this_id = gRegistry->Add(this_object);
2586 }
2587 return this_id;
2588}
2589
Ian Rogersef7d42f2014-01-06 12:55:46 -08002590void Dbg::PostLocationEvent(mirror::ArtMethod* m, int dex_pc, mirror::Object* this_object,
Jeff Hao579b0242013-11-18 13:16:49 -08002591 int event_flags, const JValue* return_value) {
Sebastien Hertz3f52eaf2014-04-04 17:50:18 +02002592 if (!IsDebuggerActive()) {
2593 return;
2594 }
2595 DCHECK(m != nullptr);
2596 DCHECK_EQ(m->IsStatic(), this_object == nullptr);
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08002597 JDWP::JdwpLocation location;
Sebastien Hertzcb19ebf2014-03-11 15:26:35 +01002598 SetLocation(location, m, dex_pc);
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08002599
Sebastien Hertz3f52eaf2014-04-04 17:50:18 +02002600 // We need 'this' for InstanceOnly filters only.
2601 JDWP::ObjectId this_id = GetThisObjectIdForEvent(this_object);
Jeff Hao579b0242013-11-18 13:16:49 -08002602 gJdwpState->PostLocationEvent(&location, this_id, event_flags, return_value);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002603}
2604
Sebastien Hertz3f52eaf2014-04-04 17:50:18 +02002605void Dbg::PostFieldAccessEvent(mirror::ArtMethod* m, int dex_pc,
2606 mirror::Object* this_object, mirror::ArtField* f) {
2607 if (!IsDebuggerActive()) {
2608 return;
2609 }
2610 DCHECK(m != nullptr);
2611 DCHECK(f != nullptr);
2612 JDWP::JdwpLocation location;
2613 SetLocation(location, m, dex_pc);
2614
2615 JDWP::RefTypeId type_id = gRegistry->AddRefType(f->GetDeclaringClass());
2616 JDWP::FieldId field_id = ToFieldId(f);
2617 JDWP::ObjectId this_id = gRegistry->Add(this_object);
2618
2619 gJdwpState->PostFieldEvent(&location, type_id, field_id, this_id, nullptr, false);
2620}
2621
2622void Dbg::PostFieldModificationEvent(mirror::ArtMethod* m, int dex_pc,
2623 mirror::Object* this_object, mirror::ArtField* f,
2624 const JValue* field_value) {
2625 if (!IsDebuggerActive()) {
2626 return;
2627 }
2628 DCHECK(m != nullptr);
2629 DCHECK(f != nullptr);
2630 DCHECK(field_value != nullptr);
2631 JDWP::JdwpLocation location;
2632 SetLocation(location, m, dex_pc);
2633
2634 JDWP::RefTypeId type_id = gRegistry->AddRefType(f->GetDeclaringClass());
2635 JDWP::FieldId field_id = ToFieldId(f);
2636 JDWP::ObjectId this_id = gRegistry->Add(this_object);
2637
2638 gJdwpState->PostFieldEvent(&location, type_id, field_id, this_id, field_value, true);
2639}
2640
2641void Dbg::PostException(const ThrowLocation& throw_location,
Brian Carlstromea46f952013-07-30 01:26:50 -07002642 mirror::ArtMethod* catch_method,
Elliott Hughes64f574f2013-02-20 14:57:12 -08002643 uint32_t catch_dex_pc, mirror::Throwable* exception_object) {
Elliott Hughesc0f09332012-03-26 13:27:06 -07002644 if (!IsDebuggerActive()) {
Ian Rogers0ad5bb82011-12-07 10:16:32 -08002645 return;
2646 }
Elliott Hughes4740cdf2011-12-07 14:07:12 -08002647
Ian Rogers62d6c772013-02-27 08:32:07 -08002648 JDWP::JdwpLocation jdwp_throw_location;
2649 SetLocation(jdwp_throw_location, throw_location.GetMethod(), throw_location.GetDexPc());
Elliott Hughesd07986f2011-12-06 18:27:45 -08002650 JDWP::JdwpLocation catch_location;
Elliott Hughescaf76542012-06-28 16:08:22 -07002651 SetLocation(catch_location, catch_method, catch_dex_pc);
Elliott Hughesd07986f2011-12-06 18:27:45 -08002652
Sebastien Hertz3f52eaf2014-04-04 17:50:18 +02002653 // We need 'this' for InstanceOnly filters only.
2654 JDWP::ObjectId this_id = GetThisObjectIdForEvent(throw_location.GetThis());
Elliott Hughes64f574f2013-02-20 14:57:12 -08002655 JDWP::ObjectId exception_id = gRegistry->Add(exception_object);
2656 JDWP::RefTypeId exception_class_id = gRegistry->AddRefType(exception_object->GetClass());
Elliott Hughesd07986f2011-12-06 18:27:45 -08002657
Ian Rogers62d6c772013-02-27 08:32:07 -08002658 gJdwpState->PostException(&jdwp_throw_location, exception_id, exception_class_id, &catch_location,
2659 this_id);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002660}
2661
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002662void Dbg::PostClassPrepare(mirror::Class* c) {
Elliott Hughesc0f09332012-03-26 13:27:06 -07002663 if (!IsDebuggerActive()) {
Elliott Hughes4740cdf2011-12-07 14:07:12 -08002664 return;
2665 }
2666
Elliott Hughes3d30d9b2011-12-07 17:35:48 -08002667 // OLD-TODO - we currently always send both "verified" and "prepared" since
Elliott Hughes4740cdf2011-12-07 14:07:12 -08002668 // debuggers seem to like that. There might be some advantage to honesty,
2669 // since the class may not yet be verified.
2670 int state = JDWP::CS_VERIFIED | JDWP::CS_PREPARED;
Sebastien Hertz4d8fd492014-03-28 16:29:41 +01002671 JDWP::JdwpTypeTag tag = GetTypeTag(c);
Mathieu Chartierf8322842014-05-16 10:59:25 -07002672 gJdwpState->PostClassPrepare(tag, gRegistry->Add(c), c->GetDescriptor(), state);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002673}
2674
Ian Rogers62d6c772013-02-27 08:32:07 -08002675void Dbg::UpdateDebugger(Thread* thread, mirror::Object* this_object,
Sebastien Hertz8379b222014-02-24 17:38:15 +01002676 mirror::ArtMethod* m, uint32_t dex_pc,
2677 int event_flags, const JValue* return_value) {
Ian Rogers62d6c772013-02-27 08:32:07 -08002678 if (!IsDebuggerActive() || dex_pc == static_cast<uint32_t>(-2) /* fake method exit */) {
Elliott Hughes2aa2e392012-02-17 17:15:43 -08002679 return;
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08002680 }
2681
Elliott Hughes86964332012-02-15 19:37:42 -08002682 if (IsBreakpoint(m, dex_pc)) {
2683 event_flags |= kBreakpoint;
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08002684 }
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08002685
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01002686 // If the debugger is single-stepping one of our threads, check to
2687 // see if we're that thread and we've reached a step point.
2688 const SingleStepControl* single_step_control = thread->GetSingleStepControl();
2689 DCHECK(single_step_control != nullptr);
2690 if (single_step_control->is_active) {
2691 CHECK(!m->IsNative());
2692 if (single_step_control->step_depth == JDWP::SD_INTO) {
2693 // Step into method calls. We break when the line number
2694 // or method pointer changes. If we're in SS_MIN mode, we
2695 // always stop.
2696 if (single_step_control->method != m) {
2697 event_flags |= kSingleStep;
2698 VLOG(jdwp) << "SS new method";
2699 } else if (single_step_control->step_size == JDWP::SS_MIN) {
2700 event_flags |= kSingleStep;
2701 VLOG(jdwp) << "SS new instruction";
Sebastien Hertzbb43b432014-04-14 11:59:08 +02002702 } else if (single_step_control->ContainsDexPc(dex_pc)) {
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01002703 event_flags |= kSingleStep;
2704 VLOG(jdwp) << "SS new line";
2705 }
2706 } else if (single_step_control->step_depth == JDWP::SD_OVER) {
2707 // Step over method calls. We break when the line number is
2708 // different and the frame depth is <= the original frame
2709 // depth. (We can't just compare on the method, because we
2710 // might get unrolled past it by an exception, and it's tricky
2711 // to identify recursion.)
2712
2713 int stack_depth = GetStackDepth(thread);
2714
2715 if (stack_depth < single_step_control->stack_depth) {
2716 // Popped up one or more frames, always trigger.
2717 event_flags |= kSingleStep;
2718 VLOG(jdwp) << "SS method pop";
2719 } else if (stack_depth == single_step_control->stack_depth) {
2720 // Same depth, see if we moved.
2721 if (single_step_control->step_size == JDWP::SS_MIN) {
Elliott Hughes86964332012-02-15 19:37:42 -08002722 event_flags |= kSingleStep;
2723 VLOG(jdwp) << "SS new instruction";
Sebastien Hertzbb43b432014-04-14 11:59:08 +02002724 } else if (single_step_control->ContainsDexPc(dex_pc)) {
Elliott Hughes2435a572012-02-17 16:07:41 -08002725 event_flags |= kSingleStep;
2726 VLOG(jdwp) << "SS new line";
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08002727 }
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01002728 }
2729 } else {
2730 CHECK_EQ(single_step_control->step_depth, JDWP::SD_OUT);
2731 // Return from the current method. We break when the frame
2732 // depth pops up.
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08002733
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01002734 // This differs from the "method exit" break in that it stops
2735 // with the PC at the next instruction in the returned-to
2736 // function, rather than the end of the returning function.
Elliott Hughes86964332012-02-15 19:37:42 -08002737
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01002738 int stack_depth = GetStackDepth(thread);
2739 if (stack_depth < single_step_control->stack_depth) {
2740 event_flags |= kSingleStep;
2741 VLOG(jdwp) << "SS method pop";
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08002742 }
2743 }
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08002744 }
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08002745
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08002746 // If there's something interesting going on, see if it matches one
2747 // of the debugger filters.
2748 if (event_flags != 0) {
Sebastien Hertz8379b222014-02-24 17:38:15 +01002749 Dbg::PostLocationEvent(m, dex_pc, this_object, event_flags, return_value);
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08002750 }
2751}
2752
Sebastien Hertz42cd43f2014-05-13 14:15:41 +02002753size_t* Dbg::GetReferenceCounterForEvent(uint32_t instrumentation_event) {
2754 switch (instrumentation_event) {
2755 case instrumentation::Instrumentation::kMethodEntered:
2756 return &method_enter_event_ref_count_;
2757 case instrumentation::Instrumentation::kMethodExited:
2758 return &method_exit_event_ref_count_;
2759 case instrumentation::Instrumentation::kDexPcMoved:
2760 return &dex_pc_change_event_ref_count_;
2761 case instrumentation::Instrumentation::kFieldRead:
2762 return &field_read_event_ref_count_;
2763 case instrumentation::Instrumentation::kFieldWritten:
2764 return &field_write_event_ref_count_;
2765 case instrumentation::Instrumentation::kExceptionCaught:
2766 return &exception_catch_event_ref_count_;
2767 default:
2768 return nullptr;
2769 }
2770}
2771
Sebastien Hertz4d25df32014-03-21 17:44:46 +01002772// Process request while all mutator threads are suspended.
2773void Dbg::ProcessDeoptimizationRequest(const DeoptimizationRequest& request) {
Sebastien Hertz138dbfc2013-12-04 18:15:25 +01002774 instrumentation::Instrumentation* instrumentation = Runtime::Current()->GetInstrumentation();
Sebastien Hertz4d25df32014-03-21 17:44:46 +01002775 switch (request.kind) {
2776 case DeoptimizationRequest::kNothing:
2777 LOG(WARNING) << "Ignoring empty deoptimization request.";
2778 break;
Sebastien Hertz42cd43f2014-05-13 14:15:41 +02002779 case DeoptimizationRequest::kRegisterForEvent:
2780 VLOG(jdwp) << StringPrintf("Add debugger as listener for instrumentation event 0x%x",
2781 request.instrumentation_event);
2782 instrumentation->AddListener(&gDebugInstrumentationListener, request.instrumentation_event);
2783 instrumentation_events_ |= request.instrumentation_event;
2784 break;
2785 case DeoptimizationRequest::kUnregisterForEvent:
2786 VLOG(jdwp) << StringPrintf("Remove debugger as listener for instrumentation event 0x%x",
2787 request.instrumentation_event);
2788 instrumentation->RemoveListener(&gDebugInstrumentationListener,
2789 request.instrumentation_event);
2790 instrumentation_events_ &= ~request.instrumentation_event;
2791 break;
Sebastien Hertz4d25df32014-03-21 17:44:46 +01002792 case DeoptimizationRequest::kFullDeoptimization:
Sebastien Hertz7ec2f1c2014-03-27 20:06:47 +01002793 VLOG(jdwp) << "Deoptimize the world ...";
Sebastien Hertz4d25df32014-03-21 17:44:46 +01002794 instrumentation->DeoptimizeEverything();
Sebastien Hertz7ec2f1c2014-03-27 20:06:47 +01002795 VLOG(jdwp) << "Deoptimize the world DONE";
Sebastien Hertz4d25df32014-03-21 17:44:46 +01002796 break;
2797 case DeoptimizationRequest::kFullUndeoptimization:
Sebastien Hertz7ec2f1c2014-03-27 20:06:47 +01002798 VLOG(jdwp) << "Undeoptimize the world ...";
Sebastien Hertz4d25df32014-03-21 17:44:46 +01002799 instrumentation->UndeoptimizeEverything();
Sebastien Hertz7ec2f1c2014-03-27 20:06:47 +01002800 VLOG(jdwp) << "Undeoptimize the world DONE";
Sebastien Hertz4d25df32014-03-21 17:44:46 +01002801 break;
2802 case DeoptimizationRequest::kSelectiveDeoptimization:
Sebastien Hertz7ec2f1c2014-03-27 20:06:47 +01002803 VLOG(jdwp) << "Deoptimize method " << PrettyMethod(request.method) << " ...";
Sebastien Hertz4d25df32014-03-21 17:44:46 +01002804 instrumentation->Deoptimize(request.method);
Sebastien Hertz7ec2f1c2014-03-27 20:06:47 +01002805 VLOG(jdwp) << "Deoptimize method " << PrettyMethod(request.method) << " DONE";
Sebastien Hertz4d25df32014-03-21 17:44:46 +01002806 break;
2807 case DeoptimizationRequest::kSelectiveUndeoptimization:
Sebastien Hertz7ec2f1c2014-03-27 20:06:47 +01002808 VLOG(jdwp) << "Undeoptimize method " << PrettyMethod(request.method) << " ...";
Sebastien Hertz4d25df32014-03-21 17:44:46 +01002809 instrumentation->Undeoptimize(request.method);
Sebastien Hertz7ec2f1c2014-03-27 20:06:47 +01002810 VLOG(jdwp) << "Undeoptimize method " << PrettyMethod(request.method) << " DONE";
Sebastien Hertz4d25df32014-03-21 17:44:46 +01002811 break;
2812 default:
2813 LOG(FATAL) << "Unsupported deoptimization request kind " << request.kind;
2814 break;
Sebastien Hertz138dbfc2013-12-04 18:15:25 +01002815 }
Sebastien Hertz138dbfc2013-12-04 18:15:25 +01002816}
2817
Sebastien Hertz7ec2f1c2014-03-27 20:06:47 +01002818void Dbg::DelayFullUndeoptimization() {
2819 MutexLock mu(Thread::Current(), *deoptimization_lock_);
2820 ++delayed_full_undeoptimization_count_;
2821 DCHECK_LE(delayed_full_undeoptimization_count_, full_deoptimization_event_count_);
2822}
2823
2824void Dbg::ProcessDelayedFullUndeoptimizations() {
2825 // TODO: avoid taking the lock twice (once here and once in ManageDeoptimization).
2826 {
2827 MutexLock mu(Thread::Current(), *deoptimization_lock_);
2828 while (delayed_full_undeoptimization_count_ > 0) {
2829 DeoptimizationRequest req;
2830 req.kind = DeoptimizationRequest::kFullUndeoptimization;
2831 req.method = nullptr;
2832 RequestDeoptimizationLocked(req);
2833 --delayed_full_undeoptimization_count_;
2834 }
2835 }
2836 ManageDeoptimization();
2837}
2838
Sebastien Hertz4d25df32014-03-21 17:44:46 +01002839void Dbg::RequestDeoptimization(const DeoptimizationRequest& req) {
2840 if (req.kind == DeoptimizationRequest::kNothing) {
2841 // Nothing to do.
2842 return;
2843 }
2844 MutexLock mu(Thread::Current(), *deoptimization_lock_);
Sebastien Hertz7ec2f1c2014-03-27 20:06:47 +01002845 RequestDeoptimizationLocked(req);
2846}
2847
2848void Dbg::RequestDeoptimizationLocked(const DeoptimizationRequest& req) {
Sebastien Hertz4d25df32014-03-21 17:44:46 +01002849 switch (req.kind) {
Sebastien Hertz42cd43f2014-05-13 14:15:41 +02002850 case DeoptimizationRequest::kRegisterForEvent: {
2851 DCHECK_NE(req.instrumentation_event, 0u);
2852 size_t* counter = GetReferenceCounterForEvent(req.instrumentation_event);
2853 CHECK(counter != nullptr) << StringPrintf("No counter for instrumentation event 0x%x",
2854 req.instrumentation_event);
2855 if (*counter == 0) {
Sebastien Hertz7d2ae432014-05-15 11:26:34 +02002856 VLOG(jdwp) << StringPrintf("Queue request #%zd to start listening to instrumentation event 0x%x",
Sebastien Hertz42cd43f2014-05-13 14:15:41 +02002857 deoptimization_requests_.size(), req.instrumentation_event);
2858 deoptimization_requests_.push_back(req);
2859 }
2860 *counter = *counter + 1;
2861 break;
2862 }
2863 case DeoptimizationRequest::kUnregisterForEvent: {
2864 DCHECK_NE(req.instrumentation_event, 0u);
2865 size_t* counter = GetReferenceCounterForEvent(req.instrumentation_event);
2866 CHECK(counter != nullptr) << StringPrintf("No counter for instrumentation event 0x%x",
2867 req.instrumentation_event);
2868 *counter = *counter - 1;
2869 if (*counter == 0) {
Sebastien Hertz7d2ae432014-05-15 11:26:34 +02002870 VLOG(jdwp) << StringPrintf("Queue request #%zd to stop listening to instrumentation event 0x%x",
Sebastien Hertz42cd43f2014-05-13 14:15:41 +02002871 deoptimization_requests_.size(), req.instrumentation_event);
2872 deoptimization_requests_.push_back(req);
2873 }
2874 break;
2875 }
Sebastien Hertz4d25df32014-03-21 17:44:46 +01002876 case DeoptimizationRequest::kFullDeoptimization: {
2877 DCHECK(req.method == nullptr);
2878 if (full_deoptimization_event_count_ == 0) {
Sebastien Hertz7ec2f1c2014-03-27 20:06:47 +01002879 VLOG(jdwp) << "Queue request #" << deoptimization_requests_.size()
2880 << " for full deoptimization";
Sebastien Hertz4d25df32014-03-21 17:44:46 +01002881 deoptimization_requests_.push_back(req);
2882 }
2883 ++full_deoptimization_event_count_;
2884 break;
2885 }
2886 case DeoptimizationRequest::kFullUndeoptimization: {
2887 DCHECK(req.method == nullptr);
Sebastien Hertze713d932014-05-15 10:48:53 +02002888 DCHECK_GT(full_deoptimization_event_count_, 0U);
Sebastien Hertz4d25df32014-03-21 17:44:46 +01002889 --full_deoptimization_event_count_;
2890 if (full_deoptimization_event_count_ == 0) {
Sebastien Hertz7ec2f1c2014-03-27 20:06:47 +01002891 VLOG(jdwp) << "Queue request #" << deoptimization_requests_.size()
2892 << " for full undeoptimization";
Sebastien Hertz4d25df32014-03-21 17:44:46 +01002893 deoptimization_requests_.push_back(req);
2894 }
2895 break;
2896 }
2897 case DeoptimizationRequest::kSelectiveDeoptimization: {
2898 DCHECK(req.method != nullptr);
Sebastien Hertz7ec2f1c2014-03-27 20:06:47 +01002899 VLOG(jdwp) << "Queue request #" << deoptimization_requests_.size()
2900 << " for deoptimization of " << PrettyMethod(req.method);
Sebastien Hertz4d25df32014-03-21 17:44:46 +01002901 deoptimization_requests_.push_back(req);
2902 break;
2903 }
2904 case DeoptimizationRequest::kSelectiveUndeoptimization: {
2905 DCHECK(req.method != nullptr);
Sebastien Hertz7ec2f1c2014-03-27 20:06:47 +01002906 VLOG(jdwp) << "Queue request #" << deoptimization_requests_.size()
2907 << " for undeoptimization of " << PrettyMethod(req.method);
Sebastien Hertz4d25df32014-03-21 17:44:46 +01002908 deoptimization_requests_.push_back(req);
2909 break;
2910 }
2911 default: {
2912 LOG(FATAL) << "Unknown deoptimization request kind " << req.kind;
2913 break;
2914 }
2915 }
2916}
2917
Sebastien Hertz138dbfc2013-12-04 18:15:25 +01002918void Dbg::ManageDeoptimization() {
2919 Thread* const self = Thread::Current();
2920 {
2921 // Avoid suspend/resume if there is no pending request.
Sebastien Hertz4d25df32014-03-21 17:44:46 +01002922 MutexLock mu(self, *deoptimization_lock_);
2923 if (deoptimization_requests_.empty()) {
Sebastien Hertz138dbfc2013-12-04 18:15:25 +01002924 return;
2925 }
2926 }
2927 CHECK_EQ(self->GetState(), kRunnable);
2928 self->TransitionFromRunnableToSuspended(kWaitingForDeoptimization);
2929 // We need to suspend mutator threads first.
2930 Runtime* const runtime = Runtime::Current();
2931 runtime->GetThreadList()->SuspendAll();
2932 const ThreadState old_state = self->SetStateUnsafe(kRunnable);
Sebastien Hertz4d25df32014-03-21 17:44:46 +01002933 {
2934 MutexLock mu(self, *deoptimization_lock_);
Sebastien Hertz7ec2f1c2014-03-27 20:06:47 +01002935 size_t req_index = 0;
Sebastien Hertz4d25df32014-03-21 17:44:46 +01002936 for (const DeoptimizationRequest& request : deoptimization_requests_) {
Sebastien Hertz7ec2f1c2014-03-27 20:06:47 +01002937 VLOG(jdwp) << "Process deoptimization request #" << req_index++;
Sebastien Hertz4d25df32014-03-21 17:44:46 +01002938 ProcessDeoptimizationRequest(request);
2939 }
2940 deoptimization_requests_.clear();
2941 }
Sebastien Hertz138dbfc2013-12-04 18:15:25 +01002942 CHECK_EQ(self->SetStateUnsafe(old_state), kRunnable);
2943 runtime->GetThreadList()->ResumeAll();
2944 self->TransitionFromSuspendedToRunnable();
2945}
2946
Sebastien Hertza76a6d42014-03-20 16:40:17 +01002947static bool IsMethodPossiblyInlined(Thread* self, mirror::ArtMethod* m)
2948 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07002949 const DexFile::CodeItem* code_item = m->GetCodeItem();
Sebastien Hertza76a6d42014-03-20 16:40:17 +01002950 if (code_item == nullptr) {
2951 // TODO We should not be asked to watch location in a native or abstract method so the code item
2952 // should never be null. We could just check we never encounter this case.
2953 return false;
Sebastien Hertz138dbfc2013-12-04 18:15:25 +01002954 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002955 StackHandleScope<2> hs(self);
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07002956 mirror::Class* declaring_class = m->GetDeclaringClass();
2957 Handle<mirror::DexCache> dex_cache(hs.NewHandle(declaring_class->GetDexCache()));
2958 Handle<mirror::ClassLoader> class_loader(hs.NewHandle(declaring_class->GetClassLoader()));
2959 verifier::MethodVerifier verifier(dex_cache->GetDexFile(), &dex_cache, &class_loader,
2960 &m->GetClassDef(), code_item, m->GetDexMethodIndex(), m,
Ian Rogers46960fe2014-05-23 10:43:43 -07002961 m->GetAccessFlags(), false, true, false);
Sebastien Hertza76a6d42014-03-20 16:40:17 +01002962 // Note: we don't need to verify the method.
2963 return InlineMethodAnalyser::AnalyseMethodCode(&verifier, nullptr);
2964}
Sebastien Hertz138dbfc2013-12-04 18:15:25 +01002965
Sebastien Hertza76a6d42014-03-20 16:40:17 +01002966static const Breakpoint* FindFirstBreakpointForMethod(mirror::ArtMethod* m)
2967 EXCLUSIVE_LOCKS_REQUIRED(Locks::breakpoint_lock_) {
2968 for (const Breakpoint& breakpoint : gBreakpoints) {
2969 if (breakpoint.method == m) {
2970 return &breakpoint;
2971 }
2972 }
2973 return nullptr;
2974}
2975
2976// Sanity checks all existing breakpoints on the same method.
2977static void SanityCheckExistingBreakpoints(mirror::ArtMethod* m, bool need_full_deoptimization)
2978 EXCLUSIVE_LOCKS_REQUIRED(Locks::breakpoint_lock_) {
2979 if (kIsDebugBuild) {
2980 for (const Breakpoint& breakpoint : gBreakpoints) {
2981 CHECK_EQ(need_full_deoptimization, breakpoint.need_full_deoptimization);
2982 }
2983 if (need_full_deoptimization) {
2984 // We should have deoptimized everything but not "selectively" deoptimized this method.
2985 CHECK(Runtime::Current()->GetInstrumentation()->AreAllMethodsDeoptimized());
2986 CHECK(!Runtime::Current()->GetInstrumentation()->IsDeoptimized(m));
2987 } else {
2988 // We should have "selectively" deoptimized this method.
2989 // Note: while we have not deoptimized everything for this method, we may have done it for
2990 // another event.
2991 CHECK(Runtime::Current()->GetInstrumentation()->IsDeoptimized(m));
2992 }
Sebastien Hertz138dbfc2013-12-04 18:15:25 +01002993 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002994}
2995
Sebastien Hertza76a6d42014-03-20 16:40:17 +01002996// Installs a breakpoint at the specified location. Also indicates through the deoptimization
2997// request if we need to deoptimize.
2998void Dbg::WatchLocation(const JDWP::JdwpLocation* location, DeoptimizationRequest* req) {
2999 Thread* const self = Thread::Current();
Brian Carlstromea46f952013-07-30 01:26:50 -07003000 mirror::ArtMethod* m = FromMethodId(location->method_id);
Sebastien Hertza76a6d42014-03-20 16:40:17 +01003001 DCHECK(m != nullptr) << "No method for method id " << location->method_id;
Sebastien Hertz138dbfc2013-12-04 18:15:25 +01003002
Sebastien Hertza76a6d42014-03-20 16:40:17 +01003003 MutexLock mu(self, *Locks::breakpoint_lock_);
3004 const Breakpoint* const existing_breakpoint = FindFirstBreakpointForMethod(m);
3005 bool need_full_deoptimization;
3006 if (existing_breakpoint == nullptr) {
3007 // There is no breakpoint on this method yet: we need to deoptimize. If this method may be
3008 // inlined, we deoptimize everything; otherwise we deoptimize only this method.
3009 need_full_deoptimization = IsMethodPossiblyInlined(self, m);
3010 if (need_full_deoptimization) {
3011 req->kind = DeoptimizationRequest::kFullDeoptimization;
3012 req->method = nullptr;
3013 } else {
3014 req->kind = DeoptimizationRequest::kSelectiveDeoptimization;
3015 req->method = m;
Sebastien Hertz138dbfc2013-12-04 18:15:25 +01003016 }
Sebastien Hertza76a6d42014-03-20 16:40:17 +01003017 } else {
3018 // There is at least one breakpoint for this method: we don't need to deoptimize.
3019 req->kind = DeoptimizationRequest::kNothing;
3020 req->method = nullptr;
3021
3022 need_full_deoptimization = existing_breakpoint->need_full_deoptimization;
3023 SanityCheckExistingBreakpoints(m, need_full_deoptimization);
Sebastien Hertz138dbfc2013-12-04 18:15:25 +01003024 }
3025
Sebastien Hertza76a6d42014-03-20 16:40:17 +01003026 gBreakpoints.push_back(Breakpoint(m, location->dex_pc, need_full_deoptimization));
3027 VLOG(jdwp) << "Set breakpoint #" << (gBreakpoints.size() - 1) << ": "
3028 << gBreakpoints[gBreakpoints.size() - 1];
3029}
3030
3031// Uninstalls a breakpoint at the specified location. Also indicates through the deoptimization
3032// request if we need to undeoptimize.
3033void Dbg::UnwatchLocation(const JDWP::JdwpLocation* location, DeoptimizationRequest* req) {
3034 mirror::ArtMethod* m = FromMethodId(location->method_id);
3035 DCHECK(m != nullptr) << "No method for method id " << location->method_id;
3036
3037 MutexLock mu(Thread::Current(), *Locks::breakpoint_lock_);
3038 bool need_full_deoptimization = false;
3039 for (size_t i = 0, e = gBreakpoints.size(); i < e; ++i) {
3040 if (gBreakpoints[i].method == m && gBreakpoints[i].dex_pc == location->dex_pc) {
3041 VLOG(jdwp) << "Removed breakpoint #" << i << ": " << gBreakpoints[i];
3042 need_full_deoptimization = gBreakpoints[i].need_full_deoptimization;
3043 DCHECK_NE(need_full_deoptimization, Runtime::Current()->GetInstrumentation()->IsDeoptimized(m));
3044 gBreakpoints.erase(gBreakpoints.begin() + i);
3045 break;
3046 }
3047 }
3048 const Breakpoint* const existing_breakpoint = FindFirstBreakpointForMethod(m);
3049 if (existing_breakpoint == nullptr) {
3050 // There is no more breakpoint on this method: we need to undeoptimize.
3051 if (need_full_deoptimization) {
3052 // This method required full deoptimization: we need to undeoptimize everything.
3053 req->kind = DeoptimizationRequest::kFullUndeoptimization;
3054 req->method = nullptr;
3055 } else {
3056 // This method required selective deoptimization: we need to undeoptimize only that method.
3057 req->kind = DeoptimizationRequest::kSelectiveUndeoptimization;
3058 req->method = m;
3059 }
3060 } else {
3061 // There is at least one breakpoint for this method: we don't need to undeoptimize.
3062 req->kind = DeoptimizationRequest::kNothing;
3063 req->method = nullptr;
3064 SanityCheckExistingBreakpoints(m, need_full_deoptimization);
Elliott Hughes86964332012-02-15 19:37:42 -08003065 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -07003066}
3067
Jeff Hao449db332013-04-12 18:30:52 -07003068// Scoped utility class to suspend a thread so that we may do tasks such as walk its stack. Doesn't
3069// cause suspension if the thread is the current thread.
3070class ScopedThreadSuspension {
3071 public:
Ian Rogers33e95662013-05-20 20:29:14 -07003072 ScopedThreadSuspension(Thread* self, JDWP::ObjectId thread_id)
Sebastien Hertz52d131d2014-03-13 16:17:40 +01003073 LOCKS_EXCLUDED(Locks::thread_list_lock_)
Ian Rogers33e95662013-05-20 20:29:14 -07003074 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) :
Jeff Hao449db332013-04-12 18:30:52 -07003075 thread_(NULL),
3076 error_(JDWP::ERR_NONE),
3077 self_suspend_(false),
Ian Rogers33e95662013-05-20 20:29:14 -07003078 other_suspend_(false) {
Jeff Hao449db332013-04-12 18:30:52 -07003079 ScopedObjectAccessUnchecked soa(self);
3080 {
3081 MutexLock mu(soa.Self(), *Locks::thread_list_lock_);
3082 error_ = DecodeThread(soa, thread_id, thread_);
3083 }
3084 if (error_ == JDWP::ERR_NONE) {
3085 if (thread_ == soa.Self()) {
3086 self_suspend_ = true;
3087 } else {
3088 soa.Self()->TransitionFromRunnableToSuspended(kWaitingForDebuggerSuspension);
3089 jobject thread_peer = gRegistry->GetJObject(thread_id);
3090 bool timed_out;
Ian Rogersd9c4fc92013-10-01 19:45:43 -07003091 Thread* suspended_thread = ThreadList::SuspendThreadByPeer(thread_peer, true, true,
3092 &timed_out);
Jeff Hao449db332013-04-12 18:30:52 -07003093 CHECK_EQ(soa.Self()->TransitionFromSuspendedToRunnable(), kWaitingForDebuggerSuspension);
3094 if (suspended_thread == NULL) {
3095 // Thread terminated from under us while suspending.
3096 error_ = JDWP::ERR_INVALID_THREAD;
3097 } else {
3098 CHECK_EQ(suspended_thread, thread_);
3099 other_suspend_ = true;
3100 }
3101 }
3102 }
Elliott Hughes2435a572012-02-17 16:07:41 -08003103 }
Elliott Hughes86964332012-02-15 19:37:42 -08003104
Jeff Hao449db332013-04-12 18:30:52 -07003105 Thread* GetThread() const {
3106 return thread_;
3107 }
3108
3109 JDWP::JdwpError GetError() const {
3110 return error_;
3111 }
3112
3113 ~ScopedThreadSuspension() {
3114 if (other_suspend_) {
3115 Runtime::Current()->GetThreadList()->Resume(thread_, true);
3116 }
3117 }
3118
3119 private:
3120 Thread* thread_;
3121 JDWP::JdwpError error_;
3122 bool self_suspend_;
3123 bool other_suspend_;
3124};
3125
3126JDWP::JdwpError Dbg::ConfigureStep(JDWP::ObjectId thread_id, JDWP::JdwpStepSize step_size,
3127 JDWP::JdwpStepDepth step_depth) {
3128 Thread* self = Thread::Current();
3129 ScopedThreadSuspension sts(self, thread_id);
3130 if (sts.GetError() != JDWP::ERR_NONE) {
3131 return sts.GetError();
3132 }
3133
Elliott Hughes2435a572012-02-17 16:07:41 -08003134 //
3135 // Work out what Method* we're in, the current line number, and how deep the stack currently
3136 // is for step-out.
3137 //
3138
Ian Rogers0399dde2012-06-06 17:09:28 -07003139 struct SingleStepStackVisitor : public StackVisitor {
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01003140 explicit SingleStepStackVisitor(Thread* thread, SingleStepControl* single_step_control,
3141 int32_t* line_number)
Ian Rogersb726dcb2012-09-05 08:57:23 -07003142 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_)
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01003143 : StackVisitor(thread, NULL), single_step_control_(single_step_control),
3144 line_number_(line_number) {
3145 DCHECK_EQ(single_step_control_, thread->GetSingleStepControl());
3146 single_step_control_->method = NULL;
3147 single_step_control_->stack_depth = 0;
Elliott Hughes86964332012-02-15 19:37:42 -08003148 }
Ian Rogersca190662012-06-26 15:45:57 -07003149
Ian Rogers00f7d0e2012-07-19 15:28:27 -07003150 // TODO: Enable annotalysis. We know lock is held in constructor, but abstraction confuses
3151 // annotalysis.
3152 bool VisitFrame() NO_THREAD_SAFETY_ANALYSIS {
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01003153 mirror::ArtMethod* m = GetMethod();
Ian Rogers0399dde2012-06-06 17:09:28 -07003154 if (!m->IsRuntimeMethod()) {
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01003155 ++single_step_control_->stack_depth;
3156 if (single_step_control_->method == NULL) {
Ian Rogersef7d42f2014-01-06 12:55:46 -08003157 mirror::DexCache* dex_cache = m->GetDeclaringClass()->GetDexCache();
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01003158 single_step_control_->method = m;
3159 *line_number_ = -1;
Elliott Hughes2435a572012-02-17 16:07:41 -08003160 if (dex_cache != NULL) {
Ian Rogers4445a7e2012-10-05 17:19:13 -07003161 const DexFile& dex_file = *dex_cache->GetDexFile();
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01003162 *line_number_ = dex_file.GetLineNumFromPC(m, GetDexPc());
Elliott Hughes2435a572012-02-17 16:07:41 -08003163 }
Elliott Hughes86964332012-02-15 19:37:42 -08003164 }
3165 }
Elliott Hughes530fa002012-03-12 11:44:49 -07003166 return true;
Elliott Hughes86964332012-02-15 19:37:42 -08003167 }
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01003168
3169 SingleStepControl* const single_step_control_;
3170 int32_t* const line_number_;
Elliott Hughes86964332012-02-15 19:37:42 -08003171 };
Jeff Hao449db332013-04-12 18:30:52 -07003172
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01003173 Thread* const thread = sts.GetThread();
3174 SingleStepControl* const single_step_control = thread->GetSingleStepControl();
3175 DCHECK(single_step_control != nullptr);
3176 int32_t line_number = -1;
3177 SingleStepStackVisitor visitor(thread, single_step_control, &line_number);
Ian Rogers0399dde2012-06-06 17:09:28 -07003178 visitor.WalkStack();
Elliott Hughes86964332012-02-15 19:37:42 -08003179
Elliott Hughes2435a572012-02-17 16:07:41 -08003180 //
3181 // Find the dex_pc values that correspond to the current line, for line-based single-stepping.
3182 //
3183
3184 struct DebugCallbackContext {
Sebastien Hertzbb43b432014-04-14 11:59:08 +02003185 explicit DebugCallbackContext(SingleStepControl* single_step_control, int32_t line_number,
3186 const DexFile::CodeItem* code_item)
3187 : single_step_control_(single_step_control), line_number_(line_number), code_item_(code_item),
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01003188 last_pc_valid(false), last_pc(0) {
Elliott Hughes2435a572012-02-17 16:07:41 -08003189 }
3190
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01003191 static bool Callback(void* raw_context, uint32_t address, uint32_t line_number) {
Elliott Hughes2435a572012-02-17 16:07:41 -08003192 DebugCallbackContext* context = reinterpret_cast<DebugCallbackContext*>(raw_context);
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01003193 if (static_cast<int32_t>(line_number) == context->line_number_) {
Elliott Hughes2435a572012-02-17 16:07:41 -08003194 if (!context->last_pc_valid) {
3195 // Everything from this address until the next line change is ours.
3196 context->last_pc = address;
3197 context->last_pc_valid = true;
3198 }
3199 // Otherwise, if we're already in a valid range for this line,
3200 // just keep going (shouldn't really happen)...
Brian Carlstrom7934ac22013-07-26 10:54:15 -07003201 } else if (context->last_pc_valid) { // and the line number is new
Elliott Hughes2435a572012-02-17 16:07:41 -08003202 // Add everything from the last entry up until here to the set
3203 for (uint32_t dex_pc = context->last_pc; dex_pc < address; ++dex_pc) {
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01003204 context->single_step_control_->dex_pcs.insert(dex_pc);
Elliott Hughes2435a572012-02-17 16:07:41 -08003205 }
3206 context->last_pc_valid = false;
3207 }
Brian Carlstrom7934ac22013-07-26 10:54:15 -07003208 return false; // There may be multiple entries for any given line.
Elliott Hughes2435a572012-02-17 16:07:41 -08003209 }
3210
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01003211 ~DebugCallbackContext() {
Elliott Hughes2435a572012-02-17 16:07:41 -08003212 // If the line number was the last in the position table...
3213 if (last_pc_valid) {
Sebastien Hertzbb43b432014-04-14 11:59:08 +02003214 size_t end = code_item_->insns_size_in_code_units_;
Elliott Hughes2435a572012-02-17 16:07:41 -08003215 for (uint32_t dex_pc = last_pc; dex_pc < end; ++dex_pc) {
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01003216 single_step_control_->dex_pcs.insert(dex_pc);
Elliott Hughes2435a572012-02-17 16:07:41 -08003217 }
3218 }
3219 }
3220
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01003221 SingleStepControl* const single_step_control_;
3222 const int32_t line_number_;
Sebastien Hertzbb43b432014-04-14 11:59:08 +02003223 const DexFile::CodeItem* const code_item_;
Elliott Hughes2435a572012-02-17 16:07:41 -08003224 bool last_pc_valid;
3225 uint32_t last_pc;
3226 };
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01003227 single_step_control->dex_pcs.clear();
Ian Rogersef7d42f2014-01-06 12:55:46 -08003228 mirror::ArtMethod* m = single_step_control->method;
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01003229 if (!m->IsNative()) {
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07003230 const DexFile::CodeItem* const code_item = m->GetCodeItem();
Sebastien Hertzbb43b432014-04-14 11:59:08 +02003231 DebugCallbackContext context(single_step_control, line_number, code_item);
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07003232 m->GetDexFile()->DecodeDebugInfo(code_item, m->IsStatic(), m->GetDexMethodIndex(),
3233 DebugCallbackContext::Callback, NULL, &context);
Elliott Hughes3e2e1a22012-02-21 11:33:41 -08003234 }
Elliott Hughes2435a572012-02-17 16:07:41 -08003235
3236 //
3237 // Everything else...
3238 //
3239
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01003240 single_step_control->step_size = step_size;
3241 single_step_control->step_depth = step_depth;
3242 single_step_control->is_active = true;
Elliott Hughes86964332012-02-15 19:37:42 -08003243
Elliott Hughes2435a572012-02-17 16:07:41 -08003244 if (VLOG_IS_ON(jdwp)) {
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01003245 VLOG(jdwp) << "Single-step thread: " << *thread;
3246 VLOG(jdwp) << "Single-step step size: " << single_step_control->step_size;
3247 VLOG(jdwp) << "Single-step step depth: " << single_step_control->step_depth;
3248 VLOG(jdwp) << "Single-step current method: " << PrettyMethod(single_step_control->method);
3249 VLOG(jdwp) << "Single-step current line: " << line_number;
3250 VLOG(jdwp) << "Single-step current stack depth: " << single_step_control->stack_depth;
Elliott Hughes2435a572012-02-17 16:07:41 -08003251 VLOG(jdwp) << "Single-step dex_pc values:";
Sebastien Hertzbb43b432014-04-14 11:59:08 +02003252 for (uint32_t dex_pc : single_step_control->dex_pcs) {
3253 VLOG(jdwp) << StringPrintf(" %#x", dex_pc);
Elliott Hughes2435a572012-02-17 16:07:41 -08003254 }
3255 }
3256
3257 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07003258}
3259
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01003260void Dbg::UnconfigureStep(JDWP::ObjectId thread_id) {
3261 ScopedObjectAccessUnchecked soa(Thread::Current());
3262 MutexLock mu(soa.Self(), *Locks::thread_list_lock_);
3263 Thread* thread;
3264 JDWP::JdwpError error = DecodeThread(soa, thread_id, thread);
Sebastien Hertz87118ed2013-11-26 17:57:18 +01003265 if (error == JDWP::ERR_NONE) {
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01003266 SingleStepControl* single_step_control = thread->GetSingleStepControl();
3267 DCHECK(single_step_control != nullptr);
Sebastien Hertzbb43b432014-04-14 11:59:08 +02003268 single_step_control->Clear();
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01003269 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -07003270}
3271
Elliott Hughes45651fd2012-02-21 15:48:20 -08003272static char JdwpTagToShortyChar(JDWP::JdwpTag tag) {
3273 switch (tag) {
3274 default:
3275 LOG(FATAL) << "unknown JDWP tag: " << PrintableChar(tag);
3276
3277 // Primitives.
3278 case JDWP::JT_BYTE: return 'B';
3279 case JDWP::JT_CHAR: return 'C';
3280 case JDWP::JT_FLOAT: return 'F';
3281 case JDWP::JT_DOUBLE: return 'D';
3282 case JDWP::JT_INT: return 'I';
3283 case JDWP::JT_LONG: return 'J';
3284 case JDWP::JT_SHORT: return 'S';
3285 case JDWP::JT_VOID: return 'V';
3286 case JDWP::JT_BOOLEAN: return 'Z';
3287
3288 // Reference types.
3289 case JDWP::JT_ARRAY:
3290 case JDWP::JT_OBJECT:
3291 case JDWP::JT_STRING:
3292 case JDWP::JT_THREAD:
3293 case JDWP::JT_THREAD_GROUP:
3294 case JDWP::JT_CLASS_LOADER:
3295 case JDWP::JT_CLASS_OBJECT:
3296 return 'L';
3297 }
3298}
3299
Elliott Hughes88d63092013-01-09 09:55:54 -08003300JDWP::JdwpError Dbg::InvokeMethod(JDWP::ObjectId thread_id, JDWP::ObjectId object_id,
3301 JDWP::RefTypeId class_id, JDWP::MethodId method_id,
Ian Rogers00f7d0e2012-07-19 15:28:27 -07003302 uint32_t arg_count, uint64_t* arg_values,
3303 JDWP::JdwpTag* arg_types, uint32_t options,
3304 JDWP::JdwpTag* pResultTag, uint64_t* pResultValue,
3305 JDWP::ObjectId* pExceptionId) {
Elliott Hughesd07986f2011-12-06 18:27:45 -08003306 ThreadList* thread_list = Runtime::Current()->GetThreadList();
3307
3308 Thread* targetThread = NULL;
3309 DebugInvokeReq* req = NULL;
Ian Rogers00f7d0e2012-07-19 15:28:27 -07003310 Thread* self = Thread::Current();
Elliott Hughesd07986f2011-12-06 18:27:45 -08003311 {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07003312 ScopedObjectAccessUnchecked soa(self);
Ian Rogers50b35e22012-10-04 10:09:15 -07003313 MutexLock mu(soa.Self(), *Locks::thread_list_lock_);
Elliott Hughes221229c2013-01-08 18:17:50 -08003314 JDWP::JdwpError error = DecodeThread(soa, thread_id, targetThread);
3315 if (error != JDWP::ERR_NONE) {
3316 LOG(ERROR) << "InvokeMethod request for invalid thread id " << thread_id;
3317 return error;
Elliott Hughesd07986f2011-12-06 18:27:45 -08003318 }
3319 req = targetThread->GetInvokeReq();
3320 if (!req->ready) {
3321 LOG(ERROR) << "InvokeMethod request for thread not stopped by event: " << *targetThread;
3322 return JDWP::ERR_INVALID_THREAD;
3323 }
3324
3325 /*
3326 * We currently have a bug where we don't successfully resume the
3327 * target thread if the suspend count is too deep. We're expected to
3328 * require one "resume" for each "suspend", but when asked to execute
3329 * a method we have to resume fully and then re-suspend it back to the
3330 * same level. (The easiest way to cause this is to type "suspend"
3331 * multiple times in jdb.)
3332 *
3333 * It's unclear what this means when the event specifies "resume all"
3334 * and some threads are suspended more deeply than others. This is
3335 * a rare problem, so for now we just prevent it from hanging forever
3336 * by rejecting the method invocation request. Without this, we will
3337 * be stuck waiting on a suspended thread.
3338 */
Ian Rogers00f7d0e2012-07-19 15:28:27 -07003339 int suspend_count;
3340 {
Ian Rogers50b35e22012-10-04 10:09:15 -07003341 MutexLock mu2(soa.Self(), *Locks::thread_suspend_count_lock_);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07003342 suspend_count = targetThread->GetSuspendCount();
3343 }
Elliott Hughesd07986f2011-12-06 18:27:45 -08003344 if (suspend_count > 1) {
3345 LOG(ERROR) << *targetThread << " suspend count too deep for method invocation: " << suspend_count;
Brian Carlstrom7934ac22013-07-26 10:54:15 -07003346 return JDWP::ERR_THREAD_SUSPENDED; // Probably not expected here.
Elliott Hughesd07986f2011-12-06 18:27:45 -08003347 }
3348
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08003349 JDWP::JdwpError status;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003350 mirror::Object* receiver = gRegistry->Get<mirror::Object*>(object_id);
Elliott Hughes64f574f2013-02-20 14:57:12 -08003351 if (receiver == ObjectRegistry::kInvalidObject) {
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08003352 return JDWP::ERR_INVALID_OBJECT;
3353 }
Elliott Hughes45651fd2012-02-21 15:48:20 -08003354
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003355 mirror::Object* thread = gRegistry->Get<mirror::Object*>(thread_id);
Elliott Hughes64f574f2013-02-20 14:57:12 -08003356 if (thread == ObjectRegistry::kInvalidObject) {
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08003357 return JDWP::ERR_INVALID_OBJECT;
3358 }
Elliott Hughes45651fd2012-02-21 15:48:20 -08003359 // TODO: check that 'thread' is actually a java.lang.Thread!
3360
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003361 mirror::Class* c = DecodeClass(class_id, status);
Elliott Hughes45651fd2012-02-21 15:48:20 -08003362 if (c == NULL) {
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08003363 return status;
3364 }
Elliott Hughes45651fd2012-02-21 15:48:20 -08003365
Brian Carlstromea46f952013-07-30 01:26:50 -07003366 mirror::ArtMethod* m = FromMethodId(method_id);
Elliott Hughes45651fd2012-02-21 15:48:20 -08003367 if (m->IsStatic() != (receiver == NULL)) {
3368 return JDWP::ERR_INVALID_METHODID;
3369 }
3370 if (m->IsStatic()) {
3371 if (m->GetDeclaringClass() != c) {
3372 return JDWP::ERR_INVALID_METHODID;
3373 }
3374 } else {
3375 if (!m->GetDeclaringClass()->IsAssignableFrom(c)) {
3376 return JDWP::ERR_INVALID_METHODID;
3377 }
3378 }
3379
3380 // Check the argument list matches the method.
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07003381 uint32_t shorty_len = 0;
3382 const char* shorty = m->GetShorty(&shorty_len);
3383 if (shorty_len - 1 != arg_count) {
Elliott Hughes45651fd2012-02-21 15:48:20 -08003384 return JDWP::ERR_ILLEGAL_ARGUMENT;
3385 }
Elliott Hughes09201632013-04-15 15:50:07 -07003386
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07003387 {
3388 StackHandleScope<3> hs(soa.Self());
3389 MethodHelper mh(hs.NewHandle(m));
3390 HandleWrapper<mirror::Object> h_obj(hs.NewHandleWrapper(&receiver));
3391 HandleWrapper<mirror::Class> h_klass(hs.NewHandleWrapper(&c));
3392 const DexFile::TypeList* types = m->GetParameterTypeList();
3393 for (size_t i = 0; i < arg_count; ++i) {
3394 if (shorty[i + 1] != JdwpTagToShortyChar(arg_types[i])) {
Elliott Hughes09201632013-04-15 15:50:07 -07003395 return JDWP::ERR_ILLEGAL_ARGUMENT;
3396 }
3397
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07003398 if (shorty[i + 1] == 'L') {
3399 // Did we really get an argument of an appropriate reference type?
3400 mirror::Class* parameter_type = mh.GetClassFromTypeIdx(types->GetTypeItem(i).type_idx_);
3401 mirror::Object* argument = gRegistry->Get<mirror::Object*>(arg_values[i]);
3402 if (argument == ObjectRegistry::kInvalidObject) {
3403 return JDWP::ERR_INVALID_OBJECT;
3404 }
3405 if (argument != NULL && !argument->InstanceOf(parameter_type)) {
3406 return JDWP::ERR_ILLEGAL_ARGUMENT;
3407 }
3408
3409 // Turn the on-the-wire ObjectId into a jobject.
3410 jvalue& v = reinterpret_cast<jvalue&>(arg_values[i]);
3411 v.l = gRegistry->GetJObject(arg_values[i]);
3412 }
Elliott Hughes09201632013-04-15 15:50:07 -07003413 }
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07003414 // Update in case it moved.
3415 m = mh.GetMethod();
Elliott Hughes45651fd2012-02-21 15:48:20 -08003416 }
3417
Sebastien Hertzd38667a2013-11-25 15:43:54 +01003418 req->receiver = receiver;
3419 req->thread = thread;
3420 req->klass = c;
3421 req->method = m;
3422 req->arg_count = arg_count;
3423 req->arg_values = arg_values;
3424 req->options = options;
3425 req->invoke_needed = true;
Elliott Hughesd07986f2011-12-06 18:27:45 -08003426 }
3427
3428 // The fact that we've released the thread list lock is a bit risky --- if the thread goes
3429 // away we're sitting high and dry -- but we must release this before the ResumeAllThreads
3430 // call, and it's unwise to hold it during WaitForSuspend.
3431
3432 {
3433 /*
3434 * We change our (JDWP thread) status, which should be THREAD_RUNNING,
Elliott Hughes81ff3182012-03-23 20:35:56 -07003435 * so we can suspend for a GC if the invoke request causes us to
Elliott Hughesd07986f2011-12-06 18:27:45 -08003436 * run out of memory. It's also a good idea to change it before locking
3437 * the invokeReq mutex, although that should never be held for long.
3438 */
Ian Rogers00f7d0e2012-07-19 15:28:27 -07003439 self->TransitionFromRunnableToSuspended(kWaitingForDebuggerSend);
Elliott Hughesd07986f2011-12-06 18:27:45 -08003440
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08003441 VLOG(jdwp) << " Transferring control to event thread";
Elliott Hughesd07986f2011-12-06 18:27:45 -08003442 {
Sebastien Hertzd38667a2013-11-25 15:43:54 +01003443 MutexLock mu(self, req->lock);
Elliott Hughesd07986f2011-12-06 18:27:45 -08003444
3445 if ((options & JDWP::INVOKE_SINGLE_THREADED) == 0) {
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08003446 VLOG(jdwp) << " Resuming all threads";
Ian Rogers00f7d0e2012-07-19 15:28:27 -07003447 thread_list->UndoDebuggerSuspensions();
Elliott Hughesd07986f2011-12-06 18:27:45 -08003448 } else {
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08003449 VLOG(jdwp) << " Resuming event thread only";
Elliott Hughesd07986f2011-12-06 18:27:45 -08003450 thread_list->Resume(targetThread, true);
3451 }
3452
3453 // Wait for the request to finish executing.
Sebastien Hertzd38667a2013-11-25 15:43:54 +01003454 while (req->invoke_needed) {
3455 req->cond.Wait(self);
Elliott Hughesd07986f2011-12-06 18:27:45 -08003456 }
3457 }
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08003458 VLOG(jdwp) << " Control has returned from event thread";
Elliott Hughesd07986f2011-12-06 18:27:45 -08003459
3460 /* wait for thread to re-suspend itself */
Brian Carlstromdf629502013-07-17 22:39:56 -07003461 SuspendThread(thread_id, false /* request_suspension */);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07003462 self->TransitionFromSuspendedToRunnable();
Elliott Hughesd07986f2011-12-06 18:27:45 -08003463 }
3464
3465 /*
3466 * Suspend the threads. We waited for the target thread to suspend
3467 * itself, so all we need to do is suspend the others.
3468 *
3469 * The suspendAllThreads() call will double-suspend the event thread,
3470 * so we want to resume the target thread once to keep the books straight.
3471 */
3472 if ((options & JDWP::INVOKE_SINGLE_THREADED) == 0) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07003473 self->TransitionFromRunnableToSuspended(kWaitingForDebuggerSuspension);
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08003474 VLOG(jdwp) << " Suspending all threads";
Ian Rogers00f7d0e2012-07-19 15:28:27 -07003475 thread_list->SuspendAllForDebugger();
3476 self->TransitionFromSuspendedToRunnable();
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08003477 VLOG(jdwp) << " Resuming event thread to balance the count";
Elliott Hughesd07986f2011-12-06 18:27:45 -08003478 thread_list->Resume(targetThread, true);
3479 }
3480
3481 // Copy the result.
3482 *pResultTag = req->result_tag;
3483 if (IsPrimitiveTag(req->result_tag)) {
Elliott Hughesf24d3ce2012-04-11 17:43:37 -07003484 *pResultValue = req->result_value.GetJ();
Elliott Hughesd07986f2011-12-06 18:27:45 -08003485 } else {
Elliott Hughesf24d3ce2012-04-11 17:43:37 -07003486 *pResultValue = gRegistry->Add(req->result_value.GetL());
Elliott Hughesd07986f2011-12-06 18:27:45 -08003487 }
3488 *pExceptionId = req->exception;
3489 return req->error;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07003490}
3491
3492void Dbg::ExecuteMethod(DebugInvokeReq* pReq) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07003493 ScopedObjectAccess soa(Thread::Current());
Elliott Hughesd07986f2011-12-06 18:27:45 -08003494
Elliott Hughes81ff3182012-03-23 20:35:56 -07003495 // We can be called while an exception is pending. We need
Elliott Hughesd07986f2011-12-06 18:27:45 -08003496 // to preserve that across the method invocation.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003497 StackHandleScope<4> hs(soa.Self());
3498 auto old_throw_this_object = hs.NewHandle<mirror::Object>(nullptr);
3499 auto old_throw_method = hs.NewHandle<mirror::ArtMethod>(nullptr);
3500 auto old_exception = hs.NewHandle<mirror::Throwable>(nullptr);
Ian Rogers62d6c772013-02-27 08:32:07 -08003501 uint32_t old_throw_dex_pc;
Sebastien Hertz9f102032014-05-23 08:59:42 +02003502 bool old_exception_report_flag;
Ian Rogers62d6c772013-02-27 08:32:07 -08003503 {
3504 ThrowLocation old_throw_location;
3505 mirror::Throwable* old_exception_obj = soa.Self()->GetException(&old_throw_location);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003506 old_throw_this_object.Assign(old_throw_location.GetThis());
3507 old_throw_method.Assign(old_throw_location.GetMethod());
3508 old_exception.Assign(old_exception_obj);
Ian Rogers62d6c772013-02-27 08:32:07 -08003509 old_throw_dex_pc = old_throw_location.GetDexPc();
Sebastien Hertz9f102032014-05-23 08:59:42 +02003510 old_exception_report_flag = soa.Self()->IsExceptionReportedToInstrumentation();
Ian Rogers62d6c772013-02-27 08:32:07 -08003511 soa.Self()->ClearException();
3512 }
Elliott Hughesd07986f2011-12-06 18:27:45 -08003513
3514 // Translate the method through the vtable, unless the debugger wants to suppress it.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003515 Handle<mirror::ArtMethod> m(hs.NewHandle(pReq->method));
Sebastien Hertzd38667a2013-11-25 15:43:54 +01003516 if ((pReq->options & JDWP::INVOKE_NONVIRTUAL) == 0 && pReq->receiver != NULL) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003517 mirror::ArtMethod* actual_method = pReq->klass->FindVirtualMethodForVirtualOrInterface(m.Get());
3518 if (actual_method != m.Get()) {
3519 VLOG(jdwp) << "ExecuteMethod translated " << PrettyMethod(m.Get()) << " to " << PrettyMethod(actual_method);
3520 m.Assign(actual_method);
Elliott Hughes45651fd2012-02-21 15:48:20 -08003521 }
Elliott Hughesd07986f2011-12-06 18:27:45 -08003522 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003523 VLOG(jdwp) << "ExecuteMethod " << PrettyMethod(m.Get())
Sebastien Hertzd38667a2013-11-25 15:43:54 +01003524 << " receiver=" << pReq->receiver
3525 << " arg_count=" << pReq->arg_count;
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003526 CHECK(m.Get() != nullptr);
Elliott Hughesd07986f2011-12-06 18:27:45 -08003527
3528 CHECK_EQ(sizeof(jvalue), sizeof(uint64_t));
3529
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003530 pReq->result_value = InvokeWithJValues(soa, pReq->receiver, soa.EncodeMethod(m.Get()),
Ian Rogers53b8b092014-03-13 23:45:53 -07003531 reinterpret_cast<jvalue*>(pReq->arg_values));
Elliott Hughesd07986f2011-12-06 18:27:45 -08003532
Ian Rogers62d6c772013-02-27 08:32:07 -08003533 mirror::Throwable* exception = soa.Self()->GetException(NULL);
3534 soa.Self()->ClearException();
3535 pReq->exception = gRegistry->Add(exception);
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07003536 pReq->result_tag = BasicTagFromDescriptor(m.Get()->GetShorty());
Elliott Hughesd07986f2011-12-06 18:27:45 -08003537 if (pReq->exception != 0) {
Ian Rogers62d6c772013-02-27 08:32:07 -08003538 VLOG(jdwp) << " JDWP invocation returning with exception=" << exception
3539 << " " << exception->Dump();
Elliott Hughesf24d3ce2012-04-11 17:43:37 -07003540 pReq->result_value.SetJ(0);
Elliott Hughesd07986f2011-12-06 18:27:45 -08003541 } else if (pReq->result_tag == JDWP::JT_OBJECT) {
3542 /* if no exception thrown, examine object result more closely */
Ian Rogers98379392014-02-24 16:53:16 -08003543 JDWP::JdwpTag new_tag = TagFromObject(soa, pReq->result_value.GetL());
Elliott Hughesd07986f2011-12-06 18:27:45 -08003544 if (new_tag != pReq->result_tag) {
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08003545 VLOG(jdwp) << " JDWP promoted result from " << pReq->result_tag << " to " << new_tag;
Elliott Hughesd07986f2011-12-06 18:27:45 -08003546 pReq->result_tag = new_tag;
3547 }
3548
3549 /*
3550 * Register the object. We don't actually need an ObjectId yet,
3551 * but we do need to be sure that the GC won't move or discard the
3552 * object when we switch out of RUNNING. The ObjectId conversion
3553 * will add the object to the "do not touch" list.
3554 *
3555 * We can't use the "tracked allocation" mechanism here because
3556 * the object is going to be handed off to a different thread.
3557 */
Elliott Hughesf24d3ce2012-04-11 17:43:37 -07003558 gRegistry->Add(pReq->result_value.GetL());
Elliott Hughesd07986f2011-12-06 18:27:45 -08003559 }
3560
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003561 if (old_exception.Get() != NULL) {
3562 ThrowLocation gc_safe_throw_location(old_throw_this_object.Get(), old_throw_method.Get(),
Ian Rogers62d6c772013-02-27 08:32:07 -08003563 old_throw_dex_pc);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003564 soa.Self()->SetException(gc_safe_throw_location, old_exception.Get());
Sebastien Hertz9f102032014-05-23 08:59:42 +02003565 soa.Self()->SetExceptionReportedToInstrumentation(old_exception_report_flag);
Elliott Hughesd07986f2011-12-06 18:27:45 -08003566 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -07003567}
3568
Elliott Hughesd07986f2011-12-06 18:27:45 -08003569/*
Elliott Hughes4b9702c2013-02-20 18:13:24 -08003570 * "request" contains a full JDWP packet, possibly with multiple chunks. We
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07003571 * need to process each, accumulate the replies, and ship the whole thing
3572 * back.
3573 *
3574 * Returns "true" if we have a reply. The reply buffer is newly allocated,
3575 * and includes the chunk type/length, followed by the data.
3576 *
Elliott Hughes3d30d9b2011-12-07 17:35:48 -08003577 * OLD-TODO: we currently assume that the request and reply include a single
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07003578 * chunk. If this becomes inconvenient we will need to adapt.
3579 */
Elliott Hughes4b9702c2013-02-20 18:13:24 -08003580bool Dbg::DdmHandlePacket(JDWP::Request& request, uint8_t** pReplyBuf, int* pReplyLen) {
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07003581 Thread* self = Thread::Current();
3582 JNIEnv* env = self->GetJniEnv();
3583
Elliott Hughes4b9702c2013-02-20 18:13:24 -08003584 uint32_t type = request.ReadUnsigned32("type");
3585 uint32_t length = request.ReadUnsigned32("length");
3586
3587 // Create a byte[] corresponding to 'request'.
3588 size_t request_length = request.size();
3589 ScopedLocalRef<jbyteArray> dataArray(env, env->NewByteArray(request_length));
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003590 if (dataArray.get() == NULL) {
Elliott Hughes4b9702c2013-02-20 18:13:24 -08003591 LOG(WARNING) << "byte[] allocation failed: " << request_length;
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07003592 env->ExceptionClear();
3593 return false;
3594 }
Elliott Hughes4b9702c2013-02-20 18:13:24 -08003595 env->SetByteArrayRegion(dataArray.get(), 0, request_length, reinterpret_cast<const jbyte*>(request.data()));
3596 request.Skip(request_length);
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07003597
3598 // Run through and find all chunks. [Currently just find the first.]
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003599 ScopedByteArrayRO contents(env, dataArray.get());
Elliott Hughes4b9702c2013-02-20 18:13:24 -08003600 if (length != request_length) {
Ian Rogersef7d42f2014-01-06 12:55:46 -08003601 LOG(WARNING) << StringPrintf("bad chunk found (len=%u pktLen=%zd)", length, request_length);
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07003602 return false;
3603 }
3604
3605 // Call "private static Chunk dispatch(int type, byte[] data, int offset, int length)".
Elliott Hugheseac76672012-05-24 21:56:51 -07003606 ScopedLocalRef<jobject> chunk(env, env->CallStaticObjectMethod(WellKnownClasses::org_apache_harmony_dalvik_ddmc_DdmServer,
3607 WellKnownClasses::org_apache_harmony_dalvik_ddmc_DdmServer_dispatch,
Elliott Hughes4b9702c2013-02-20 18:13:24 -08003608 type, dataArray.get(), 0, length));
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07003609 if (env->ExceptionCheck()) {
3610 LOG(INFO) << StringPrintf("Exception thrown by dispatcher for 0x%08x", type);
3611 env->ExceptionDescribe();
3612 env->ExceptionClear();
3613 return false;
3614 }
3615
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003616 if (chunk.get() == NULL) {
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07003617 return false;
3618 }
3619
3620 /*
3621 * Pull the pieces out of the chunk. We copy the results into a
3622 * newly-allocated buffer that the caller can free. We don't want to
3623 * continue using the Chunk object because nothing has a reference to it.
3624 *
3625 * We could avoid this by returning type/data/offset/length and having
3626 * the caller be aware of the object lifetime issues, but that
Elliott Hughes81ff3182012-03-23 20:35:56 -07003627 * integrates the JDWP code more tightly into the rest of the runtime, and doesn't work
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07003628 * if we have responses for multiple chunks.
3629 *
3630 * So we're pretty much stuck with copying data around multiple times.
3631 */
Elliott Hugheseac76672012-05-24 21:56:51 -07003632 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 -08003633 jint offset = env->GetIntField(chunk.get(), WellKnownClasses::org_apache_harmony_dalvik_ddmc_Chunk_offset);
Elliott Hugheseac76672012-05-24 21:56:51 -07003634 length = env->GetIntField(chunk.get(), WellKnownClasses::org_apache_harmony_dalvik_ddmc_Chunk_length);
Elliott Hugheseac76672012-05-24 21:56:51 -07003635 type = env->GetIntField(chunk.get(), WellKnownClasses::org_apache_harmony_dalvik_ddmc_Chunk_type);
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07003636
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08003637 VLOG(jdwp) << StringPrintf("DDM reply: type=0x%08x data=%p offset=%d length=%d", type, replyData.get(), offset, length);
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003638 if (length == 0 || replyData.get() == NULL) {
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07003639 return false;
3640 }
3641
Elliott Hughes4b9702c2013-02-20 18:13:24 -08003642 const int kChunkHdrLen = 8;
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07003643 uint8_t* reply = new uint8_t[length + kChunkHdrLen];
3644 if (reply == NULL) {
3645 LOG(WARNING) << "malloc failed: " << (length + kChunkHdrLen);
3646 return false;
3647 }
Elliott Hughesf7c3b662011-10-27 12:04:56 -07003648 JDWP::Set4BE(reply + 0, type);
3649 JDWP::Set4BE(reply + 4, length);
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003650 env->GetByteArrayRegion(replyData.get(), offset, length, reinterpret_cast<jbyte*>(reply + kChunkHdrLen));
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07003651
3652 *pReplyBuf = reply;
3653 *pReplyLen = length + kChunkHdrLen;
3654
Elliott Hughes4b9702c2013-02-20 18:13:24 -08003655 VLOG(jdwp) << StringPrintf("dvmHandleDdm returning type=%.4s %p len=%d", reinterpret_cast<char*>(reply), reply, length);
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07003656 return true;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07003657}
3658
Elliott Hughesa2155262011-11-16 16:26:58 -08003659void Dbg::DdmBroadcast(bool connect) {
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08003660 VLOG(jdwp) << "Broadcasting DDM " << (connect ? "connect" : "disconnect") << "...";
Elliott Hughes47fce012011-10-25 18:37:19 -07003661
3662 Thread* self = Thread::Current();
Ian Rogers50b35e22012-10-04 10:09:15 -07003663 if (self->GetState() != kRunnable) {
3664 LOG(ERROR) << "DDM broadcast in thread state " << self->GetState();
3665 /* try anyway? */
Elliott Hughes47fce012011-10-25 18:37:19 -07003666 }
3667
3668 JNIEnv* env = self->GetJniEnv();
Elliott Hughes47fce012011-10-25 18:37:19 -07003669 jint event = connect ? 1 /*DdmServer.CONNECTED*/ : 2 /*DdmServer.DISCONNECTED*/;
Elliott Hugheseac76672012-05-24 21:56:51 -07003670 env->CallStaticVoidMethod(WellKnownClasses::org_apache_harmony_dalvik_ddmc_DdmServer,
3671 WellKnownClasses::org_apache_harmony_dalvik_ddmc_DdmServer_broadcast,
3672 event);
Elliott Hughes47fce012011-10-25 18:37:19 -07003673 if (env->ExceptionCheck()) {
3674 LOG(ERROR) << "DdmServer.broadcast " << event << " failed";
3675 env->ExceptionDescribe();
3676 env->ExceptionClear();
3677 }
3678}
3679
Elliott Hughes872d4ec2011-10-21 17:07:15 -07003680void Dbg::DdmConnected() {
Elliott Hughesa2155262011-11-16 16:26:58 -08003681 Dbg::DdmBroadcast(true);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07003682}
3683
3684void Dbg::DdmDisconnected() {
Elliott Hughesa2155262011-11-16 16:26:58 -08003685 Dbg::DdmBroadcast(false);
Elliott Hughes47fce012011-10-25 18:37:19 -07003686 gDdmThreadNotification = false;
3687}
3688
3689/*
Elliott Hughes82188472011-11-07 18:11:48 -08003690 * Send a notification when a thread starts, stops, or changes its name.
Elliott Hughes47fce012011-10-25 18:37:19 -07003691 *
3692 * Because we broadcast the full set of threads when the notifications are
3693 * first enabled, it's possible for "thread" to be actively executing.
3694 */
Elliott Hughes82188472011-11-07 18:11:48 -08003695void Dbg::DdmSendThreadNotification(Thread* t, uint32_t type) {
Elliott Hughes47fce012011-10-25 18:37:19 -07003696 if (!gDdmThreadNotification) {
3697 return;
3698 }
3699
Elliott Hughes82188472011-11-07 18:11:48 -08003700 if (type == CHUNK_TYPE("THDE")) {
Elliott Hughes47fce012011-10-25 18:37:19 -07003701 uint8_t buf[4];
Ian Rogersd9c4fc92013-10-01 19:45:43 -07003702 JDWP::Set4BE(&buf[0], t->GetThreadId());
Elliott Hughes47fce012011-10-25 18:37:19 -07003703 Dbg::DdmSendChunk(CHUNK_TYPE("THDE"), 4, buf);
Elliott Hughes82188472011-11-07 18:11:48 -08003704 } else {
3705 CHECK(type == CHUNK_TYPE("THCR") || type == CHUNK_TYPE("THNM")) << type;
Ian Rogers00f7d0e2012-07-19 15:28:27 -07003706 ScopedObjectAccessUnchecked soa(Thread::Current());
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003707 StackHandleScope<1> hs(soa.Self());
3708 Handle<mirror::String> name(hs.NewHandle(t->GetThreadName(soa)));
3709 size_t char_count = (name.Get() != NULL) ? name->GetLength() : 0;
3710 const jchar* chars = (name.Get() != NULL) ? name->GetCharArray()->GetData() : NULL;
Elliott Hughes82188472011-11-07 18:11:48 -08003711
Elliott Hughes21f32d72011-11-09 17:44:13 -08003712 std::vector<uint8_t> bytes;
Ian Rogersd9c4fc92013-10-01 19:45:43 -07003713 JDWP::Append4BE(bytes, t->GetThreadId());
Elliott Hughes545a0642011-11-08 19:10:03 -08003714 JDWP::AppendUtf16BE(bytes, chars, char_count);
Elliott Hughes21f32d72011-11-09 17:44:13 -08003715 CHECK_EQ(bytes.size(), char_count*2 + sizeof(uint32_t)*2);
3716 Dbg::DdmSendChunk(type, bytes);
Elliott Hughes47fce012011-10-25 18:37:19 -07003717 }
3718}
3719
Elliott Hughes47fce012011-10-25 18:37:19 -07003720void Dbg::DdmSetThreadNotification(bool enable) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07003721 // Enable/disable thread notifications.
Elliott Hughes47fce012011-10-25 18:37:19 -07003722 gDdmThreadNotification = enable;
3723 if (enable) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07003724 // Suspend the VM then post thread start notifications for all threads. Threads attaching will
3725 // see a suspension in progress and block until that ends. They then post their own start
3726 // notification.
3727 SuspendVM();
3728 std::list<Thread*> threads;
Ian Rogers50b35e22012-10-04 10:09:15 -07003729 Thread* self = Thread::Current();
Ian Rogers00f7d0e2012-07-19 15:28:27 -07003730 {
Ian Rogers50b35e22012-10-04 10:09:15 -07003731 MutexLock mu(self, *Locks::thread_list_lock_);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07003732 threads = Runtime::Current()->GetThreadList()->GetList();
3733 }
3734 {
Ian Rogers50b35e22012-10-04 10:09:15 -07003735 ScopedObjectAccess soa(self);
Mathieu Chartier02e25112013-08-14 16:14:24 -07003736 for (Thread* thread : threads) {
3737 Dbg::DdmSendThreadNotification(thread, CHUNK_TYPE("THCR"));
Ian Rogers00f7d0e2012-07-19 15:28:27 -07003738 }
3739 }
3740 ResumeVM();
Elliott Hughes47fce012011-10-25 18:37:19 -07003741 }
3742}
3743
Elliott Hughesa2155262011-11-16 16:26:58 -08003744void Dbg::PostThreadStartOrStop(Thread* t, uint32_t type) {
Elliott Hughesc0f09332012-03-26 13:27:06 -07003745 if (IsDebuggerActive()) {
Mathieu Chartierdbe6f462012-09-25 16:54:50 -07003746 ScopedObjectAccessUnchecked soa(Thread::Current());
Ian Rogerscfaa4552012-11-26 21:00:08 -08003747 JDWP::ObjectId id = gRegistry->Add(t->GetPeer());
Elliott Hughes82188472011-11-07 18:11:48 -08003748 gJdwpState->PostThreadChange(id, type == CHUNK_TYPE("THCR"));
Elliott Hughes47fce012011-10-25 18:37:19 -07003749 }
Elliott Hughes82188472011-11-07 18:11:48 -08003750 Dbg::DdmSendThreadNotification(t, type);
Elliott Hughes47fce012011-10-25 18:37:19 -07003751}
3752
3753void Dbg::PostThreadStart(Thread* t) {
Elliott Hughesa2155262011-11-16 16:26:58 -08003754 Dbg::PostThreadStartOrStop(t, CHUNK_TYPE("THCR"));
Elliott Hughes47fce012011-10-25 18:37:19 -07003755}
3756
3757void Dbg::PostThreadDeath(Thread* t) {
Elliott Hughesa2155262011-11-16 16:26:58 -08003758 Dbg::PostThreadStartOrStop(t, CHUNK_TYPE("THDE"));
Elliott Hughes872d4ec2011-10-21 17:07:15 -07003759}
3760
Elliott Hughes82188472011-11-07 18:11:48 -08003761void Dbg::DdmSendChunk(uint32_t type, size_t byte_count, const uint8_t* buf) {
Elliott Hughes3bb81562011-10-21 18:52:59 -07003762 CHECK(buf != NULL);
3763 iovec vec[1];
3764 vec[0].iov_base = reinterpret_cast<void*>(const_cast<uint8_t*>(buf));
3765 vec[0].iov_len = byte_count;
3766 Dbg::DdmSendChunkV(type, vec, 1);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07003767}
3768
Elliott Hughes21f32d72011-11-09 17:44:13 -08003769void Dbg::DdmSendChunk(uint32_t type, const std::vector<uint8_t>& bytes) {
3770 DdmSendChunk(type, bytes.size(), &bytes[0]);
3771}
3772
Brian Carlstromf5293522013-07-19 00:24:00 -07003773void Dbg::DdmSendChunkV(uint32_t type, const iovec* iov, int iov_count) {
Elliott Hughes3bb81562011-10-21 18:52:59 -07003774 if (gJdwpState == NULL) {
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08003775 VLOG(jdwp) << "Debugger thread not active, ignoring DDM send: " << type;
Elliott Hughes3bb81562011-10-21 18:52:59 -07003776 } else {
Elliott Hughescccd84f2011-12-05 16:51:54 -08003777 gJdwpState->DdmSendChunkV(type, iov, iov_count);
Elliott Hughes3bb81562011-10-21 18:52:59 -07003778 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -07003779}
3780
Elliott Hughes767a1472011-10-26 18:49:02 -07003781int Dbg::DdmHandleHpifChunk(HpifWhen when) {
3782 if (when == HPIF_WHEN_NOW) {
Elliott Hughes7162ad92011-10-27 14:08:42 -07003783 DdmSendHeapInfo(when);
Elliott Hughes767a1472011-10-26 18:49:02 -07003784 return true;
3785 }
3786
3787 if (when != HPIF_WHEN_NEVER && when != HPIF_WHEN_NEXT_GC && when != HPIF_WHEN_EVERY_GC) {
3788 LOG(ERROR) << "invalid HpifWhen value: " << static_cast<int>(when);
3789 return false;
3790 }
3791
3792 gDdmHpifWhen = when;
3793 return true;
3794}
3795
3796bool Dbg::DdmHandleHpsgNhsgChunk(Dbg::HpsgWhen when, Dbg::HpsgWhat what, bool native) {
3797 if (when != HPSG_WHEN_NEVER && when != HPSG_WHEN_EVERY_GC) {
3798 LOG(ERROR) << "invalid HpsgWhen value: " << static_cast<int>(when);
3799 return false;
3800 }
3801
3802 if (what != HPSG_WHAT_MERGED_OBJECTS && what != HPSG_WHAT_DISTINCT_OBJECTS) {
3803 LOG(ERROR) << "invalid HpsgWhat value: " << static_cast<int>(what);
3804 return false;
3805 }
3806
3807 if (native) {
3808 gDdmNhsgWhen = when;
3809 gDdmNhsgWhat = what;
3810 } else {
3811 gDdmHpsgWhen = when;
3812 gDdmHpsgWhat = what;
3813 }
3814 return true;
3815}
3816
Elliott Hughes7162ad92011-10-27 14:08:42 -07003817void Dbg::DdmSendHeapInfo(HpifWhen reason) {
3818 // If there's a one-shot 'when', reset it.
3819 if (reason == gDdmHpifWhen) {
3820 if (gDdmHpifWhen == HPIF_WHEN_NEXT_GC) {
3821 gDdmHpifWhen = HPIF_WHEN_NEVER;
3822 }
3823 }
3824
3825 /*
3826 * Chunk HPIF (client --> server)
3827 *
3828 * Heap Info. General information about the heap,
3829 * suitable for a summary display.
3830 *
3831 * [u4]: number of heaps
3832 *
3833 * For each heap:
3834 * [u4]: heap ID
3835 * [u8]: timestamp in ms since Unix epoch
3836 * [u1]: capture reason (same as 'when' value from server)
3837 * [u4]: max heap size in bytes (-Xmx)
3838 * [u4]: current heap size in bytes
3839 * [u4]: current number of bytes allocated
3840 * [u4]: current number of objects allocated
3841 */
3842 uint8_t heap_count = 1;
Ian Rogers1d54e732013-05-02 21:10:01 -07003843 gc::Heap* heap = Runtime::Current()->GetHeap();
Elliott Hughes21f32d72011-11-09 17:44:13 -08003844 std::vector<uint8_t> bytes;
Elliott Hughes545a0642011-11-08 19:10:03 -08003845 JDWP::Append4BE(bytes, heap_count);
Brian Carlstrom7934ac22013-07-26 10:54:15 -07003846 JDWP::Append4BE(bytes, 1); // Heap id (bogus; we only have one heap).
Elliott Hughes545a0642011-11-08 19:10:03 -08003847 JDWP::Append8BE(bytes, MilliTime());
3848 JDWP::Append1BE(bytes, reason);
Brian Carlstrom7934ac22013-07-26 10:54:15 -07003849 JDWP::Append4BE(bytes, heap->GetMaxMemory()); // Max allowed heap size in bytes.
3850 JDWP::Append4BE(bytes, heap->GetTotalMemory()); // Current heap size in bytes.
Elliott Hughesb3bd5f02012-03-08 21:05:27 -08003851 JDWP::Append4BE(bytes, heap->GetBytesAllocated());
3852 JDWP::Append4BE(bytes, heap->GetObjectsAllocated());
Elliott Hughes21f32d72011-11-09 17:44:13 -08003853 CHECK_EQ(bytes.size(), 4U + (heap_count * (4 + 8 + 1 + 4 + 4 + 4 + 4)));
3854 Dbg::DdmSendChunk(CHUNK_TYPE("HPIF"), bytes);
Elliott Hughes767a1472011-10-26 18:49:02 -07003855}
3856
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003857enum HpsgSolidity {
3858 SOLIDITY_FREE = 0,
3859 SOLIDITY_HARD = 1,
3860 SOLIDITY_SOFT = 2,
3861 SOLIDITY_WEAK = 3,
3862 SOLIDITY_PHANTOM = 4,
3863 SOLIDITY_FINALIZABLE = 5,
3864 SOLIDITY_SWEEP = 6,
3865};
3866
3867enum HpsgKind {
3868 KIND_OBJECT = 0,
3869 KIND_CLASS_OBJECT = 1,
3870 KIND_ARRAY_1 = 2,
3871 KIND_ARRAY_2 = 3,
3872 KIND_ARRAY_4 = 4,
3873 KIND_ARRAY_8 = 5,
3874 KIND_UNKNOWN = 6,
3875 KIND_NATIVE = 7,
3876};
3877
3878#define HPSG_PARTIAL (1<<7)
3879#define HPSG_STATE(solidity, kind) ((uint8_t)((((kind) & 0x7) << 3) | ((solidity) & 0x7)))
3880
Ian Rogers30fab402012-01-23 15:43:46 -08003881class HeapChunkContext {
3882 public:
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003883 // Maximum chunk size. Obtain this from the formula:
3884 // (((maximum_heap_size / ALLOCATION_UNIT_SIZE) + 255) / 256) * 2
3885 HeapChunkContext(bool merge, bool native)
Ian Rogers30fab402012-01-23 15:43:46 -08003886 : buf_(16384 - 16),
3887 type_(0),
3888 merge_(merge) {
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003889 Reset();
3890 if (native) {
Ian Rogers30fab402012-01-23 15:43:46 -08003891 type_ = CHUNK_TYPE("NHSG");
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003892 } else {
Ian Rogers30fab402012-01-23 15:43:46 -08003893 type_ = merge ? CHUNK_TYPE("HPSG") : CHUNK_TYPE("HPSO");
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003894 }
3895 }
3896
3897 ~HeapChunkContext() {
Ian Rogers30fab402012-01-23 15:43:46 -08003898 if (p_ > &buf_[0]) {
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003899 Flush();
3900 }
3901 }
3902
3903 void EnsureHeader(const void* chunk_ptr) {
Ian Rogers30fab402012-01-23 15:43:46 -08003904 if (!needHeader_) {
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003905 return;
3906 }
3907
3908 // Start a new HPSx chunk.
Brian Carlstrom7934ac22013-07-26 10:54:15 -07003909 JDWP::Write4BE(&p_, 1); // Heap id (bogus; we only have one heap).
3910 JDWP::Write1BE(&p_, 8); // Size of allocation unit, in bytes.
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003911
Brian Carlstrom7934ac22013-07-26 10:54:15 -07003912 JDWP::Write4BE(&p_, reinterpret_cast<uintptr_t>(chunk_ptr)); // virtual address of segment start.
3913 JDWP::Write4BE(&p_, 0); // offset of this piece (relative to the virtual address).
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003914 // [u4]: length of piece, in allocation units
3915 // 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 -08003916 pieceLenField_ = p_;
3917 JDWP::Write4BE(&p_, 0x55555555);
3918 needHeader_ = false;
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003919 }
3920
Ian Rogersb726dcb2012-09-05 08:57:23 -07003921 void Flush() SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Ian Rogersd636b062013-01-18 17:51:18 -08003922 if (pieceLenField_ == NULL) {
3923 // Flush immediately post Reset (maybe back-to-back Flush). Ignore.
3924 CHECK(needHeader_);
3925 return;
3926 }
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003927 // Patch the "length of piece" field.
Ian Rogers30fab402012-01-23 15:43:46 -08003928 CHECK_LE(&buf_[0], pieceLenField_);
3929 CHECK_LE(pieceLenField_, p_);
3930 JDWP::Set4BE(pieceLenField_, totalAllocationUnits_);
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003931
Ian Rogers30fab402012-01-23 15:43:46 -08003932 Dbg::DdmSendChunk(type_, p_ - &buf_[0], &buf_[0]);
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003933 Reset();
3934 }
3935
Ian Rogers00f7d0e2012-07-19 15:28:27 -07003936 static void HeapChunkCallback(void* start, void* end, size_t used_bytes, void* arg)
Ian Rogersb726dcb2012-09-05 08:57:23 -07003937 SHARED_LOCKS_REQUIRED(Locks::heap_bitmap_lock_,
3938 Locks::mutator_lock_) {
Ian Rogers30fab402012-01-23 15:43:46 -08003939 reinterpret_cast<HeapChunkContext*>(arg)->HeapChunkCallback(start, end, used_bytes);
Elliott Hughesa2155262011-11-16 16:26:58 -08003940 }
3941
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003942 private:
Elliott Hughesa2155262011-11-16 16:26:58 -08003943 enum { ALLOCATION_UNIT_SIZE = 8 };
3944
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003945 void Reset() {
Ian Rogers30fab402012-01-23 15:43:46 -08003946 p_ = &buf_[0];
Ian Rogers15bf2d32012-08-28 17:33:04 -07003947 startOfNextMemoryChunk_ = NULL;
Ian Rogers30fab402012-01-23 15:43:46 -08003948 totalAllocationUnits_ = 0;
3949 needHeader_ = true;
3950 pieceLenField_ = NULL;
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003951 }
3952
Ian Rogers00f7d0e2012-07-19 15:28:27 -07003953 void HeapChunkCallback(void* start, void* /*end*/, size_t used_bytes)
Ian Rogersb726dcb2012-09-05 08:57:23 -07003954 SHARED_LOCKS_REQUIRED(Locks::heap_bitmap_lock_,
3955 Locks::mutator_lock_) {
Ian Rogers30fab402012-01-23 15:43:46 -08003956 // Note: heap call backs cannot manipulate the heap upon which they are crawling, care is taken
3957 // in the following code not to allocate memory, by ensuring buf_ is of the correct size
Ian Rogers15bf2d32012-08-28 17:33:04 -07003958 if (used_bytes == 0) {
3959 if (start == NULL) {
3960 // Reset for start of new heap.
3961 startOfNextMemoryChunk_ = NULL;
3962 Flush();
3963 }
3964 // Only process in use memory so that free region information
3965 // also includes dlmalloc book keeping.
Elliott Hughesa2155262011-11-16 16:26:58 -08003966 return;
Elliott Hughesa2155262011-11-16 16:26:58 -08003967 }
3968
Ian Rogers15bf2d32012-08-28 17:33:04 -07003969 /* If we're looking at the native heap, we'll just return
3970 * (SOLIDITY_HARD, KIND_NATIVE) for all allocated chunks
3971 */
3972 bool native = type_ == CHUNK_TYPE("NHSG");
3973
3974 if (startOfNextMemoryChunk_ != NULL) {
3975 // Transmit any pending free memory. Native free memory of
3976 // over kMaxFreeLen could be because of the use of mmaps, so
3977 // don't report. If not free memory then start a new segment.
3978 bool flush = true;
3979 if (start > startOfNextMemoryChunk_) {
3980 const size_t kMaxFreeLen = 2 * kPageSize;
3981 void* freeStart = startOfNextMemoryChunk_;
3982 void* freeEnd = start;
Brian Carlstrom2d888622013-07-18 17:02:00 -07003983 size_t freeLen = reinterpret_cast<char*>(freeEnd) - reinterpret_cast<char*>(freeStart);
Ian Rogers15bf2d32012-08-28 17:33:04 -07003984 if (!native || freeLen < kMaxFreeLen) {
3985 AppendChunk(HPSG_STATE(SOLIDITY_FREE, 0), freeStart, freeLen);
3986 flush = false;
3987 }
3988 }
3989 if (flush) {
3990 startOfNextMemoryChunk_ = NULL;
3991 Flush();
3992 }
3993 }
Ian Rogersef7d42f2014-01-06 12:55:46 -08003994 mirror::Object* obj = reinterpret_cast<mirror::Object*>(start);
Elliott Hughesa2155262011-11-16 16:26:58 -08003995
3996 // Determine the type of this chunk.
3997 // OLD-TODO: if context.merge, see if this chunk is different from the last chunk.
3998 // If it's the same, we should combine them.
Ian Rogers15bf2d32012-08-28 17:33:04 -07003999 uint8_t state = ExamineObject(obj, native);
4000 // dlmalloc's chunk header is 2 * sizeof(size_t), but if the previous chunk is in use for an
4001 // allocation then the first sizeof(size_t) may belong to it.
4002 const size_t dlMallocOverhead = sizeof(size_t);
4003 AppendChunk(state, start, used_bytes + dlMallocOverhead);
Brian Carlstrom2d888622013-07-18 17:02:00 -07004004 startOfNextMemoryChunk_ = reinterpret_cast<char*>(start) + used_bytes + dlMallocOverhead;
Ian Rogers15bf2d32012-08-28 17:33:04 -07004005 }
Elliott Hughesa2155262011-11-16 16:26:58 -08004006
Ian Rogers15bf2d32012-08-28 17:33:04 -07004007 void AppendChunk(uint8_t state, void* ptr, size_t length)
Ian Rogersb726dcb2012-09-05 08:57:23 -07004008 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Ian Rogers15bf2d32012-08-28 17:33:04 -07004009 // Make sure there's enough room left in the buffer.
4010 // We need to use two bytes for every fractional 256 allocation units used by the chunk plus
4011 // 17 bytes for any header.
4012 size_t needed = (((length/ALLOCATION_UNIT_SIZE + 255) / 256) * 2) + 17;
4013 size_t bytesLeft = buf_.size() - (size_t)(p_ - &buf_[0]);
4014 if (bytesLeft < needed) {
4015 Flush();
4016 }
4017
4018 bytesLeft = buf_.size() - (size_t)(p_ - &buf_[0]);
4019 if (bytesLeft < needed) {
4020 LOG(WARNING) << "Chunk is too big to transmit (chunk_len=" << length << ", "
4021 << needed << " bytes)";
4022 return;
4023 }
4024 EnsureHeader(ptr);
Elliott Hughesa2155262011-11-16 16:26:58 -08004025 // Write out the chunk description.
Ian Rogers15bf2d32012-08-28 17:33:04 -07004026 length /= ALLOCATION_UNIT_SIZE; // Convert to allocation units.
4027 totalAllocationUnits_ += length;
4028 while (length > 256) {
Ian Rogers30fab402012-01-23 15:43:46 -08004029 *p_++ = state | HPSG_PARTIAL;
4030 *p_++ = 255; // length - 1
Ian Rogers15bf2d32012-08-28 17:33:04 -07004031 length -= 256;
Elliott Hughesa2155262011-11-16 16:26:58 -08004032 }
Ian Rogers30fab402012-01-23 15:43:46 -08004033 *p_++ = state;
Ian Rogers15bf2d32012-08-28 17:33:04 -07004034 *p_++ = length - 1;
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004035 }
4036
Ian Rogersef7d42f2014-01-06 12:55:46 -08004037 uint8_t ExamineObject(mirror::Object* o, bool is_native_heap)
4038 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_, Locks::heap_bitmap_lock_) {
Elliott Hughesa2155262011-11-16 16:26:58 -08004039 if (o == NULL) {
4040 return HPSG_STATE(SOLIDITY_FREE, 0);
4041 }
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004042
Elliott Hughesa2155262011-11-16 16:26:58 -08004043 // It's an allocated chunk. Figure out what it is.
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004044
Elliott Hughesa2155262011-11-16 16:26:58 -08004045 // If we're looking at the native heap, we'll just return
4046 // (SOLIDITY_HARD, KIND_NATIVE) for all allocated chunks.
Ian Rogers00f7d0e2012-07-19 15:28:27 -07004047 if (is_native_heap) {
Elliott Hughesa2155262011-11-16 16:26:58 -08004048 return HPSG_STATE(SOLIDITY_HARD, KIND_NATIVE);
4049 }
4050
Ian Rogers5bfa60f2012-09-02 21:17:56 -07004051 if (!Runtime::Current()->GetHeap()->IsLiveObjectLocked(o)) {
Ian Rogers15bf2d32012-08-28 17:33:04 -07004052 return HPSG_STATE(SOLIDITY_HARD, KIND_NATIVE);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07004053 }
4054
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08004055 mirror::Class* c = o->GetClass();
Elliott Hughesa2155262011-11-16 16:26:58 -08004056 if (c == NULL) {
4057 // The object was probably just created but hasn't been initialized yet.
4058 return HPSG_STATE(SOLIDITY_HARD, KIND_OBJECT);
4059 }
4060
Mathieu Chartier590fee92013-09-13 13:46:47 -07004061 if (!Runtime::Current()->GetHeap()->IsValidObjectAddress(c)) {
Ian Rogers15bf2d32012-08-28 17:33:04 -07004062 LOG(ERROR) << "Invalid class for managed heap object: " << o << " " << c;
Elliott Hughesa2155262011-11-16 16:26:58 -08004063 return HPSG_STATE(SOLIDITY_HARD, KIND_UNKNOWN);
4064 }
4065
4066 if (c->IsClassClass()) {
4067 return HPSG_STATE(SOLIDITY_HARD, KIND_CLASS_OBJECT);
4068 }
4069
4070 if (c->IsArrayClass()) {
4071 if (o->IsObjectArray()) {
4072 return HPSG_STATE(SOLIDITY_HARD, KIND_ARRAY_4);
4073 }
4074 switch (c->GetComponentSize()) {
4075 case 1: return HPSG_STATE(SOLIDITY_HARD, KIND_ARRAY_1);
4076 case 2: return HPSG_STATE(SOLIDITY_HARD, KIND_ARRAY_2);
4077 case 4: return HPSG_STATE(SOLIDITY_HARD, KIND_ARRAY_4);
4078 case 8: return HPSG_STATE(SOLIDITY_HARD, KIND_ARRAY_8);
4079 }
4080 }
4081
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004082 return HPSG_STATE(SOLIDITY_HARD, KIND_OBJECT);
4083 }
4084
Ian Rogers30fab402012-01-23 15:43:46 -08004085 std::vector<uint8_t> buf_;
4086 uint8_t* p_;
4087 uint8_t* pieceLenField_;
Ian Rogers15bf2d32012-08-28 17:33:04 -07004088 void* startOfNextMemoryChunk_;
Ian Rogers30fab402012-01-23 15:43:46 -08004089 size_t totalAllocationUnits_;
4090 uint32_t type_;
4091 bool merge_;
4092 bool needHeader_;
4093
Elliott Hughesa2155262011-11-16 16:26:58 -08004094 DISALLOW_COPY_AND_ASSIGN(HeapChunkContext);
4095};
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004096
4097void Dbg::DdmSendHeapSegments(bool native) {
4098 Dbg::HpsgWhen when;
4099 Dbg::HpsgWhat what;
4100 if (!native) {
4101 when = gDdmHpsgWhen;
4102 what = gDdmHpsgWhat;
4103 } else {
4104 when = gDdmNhsgWhen;
4105 what = gDdmNhsgWhat;
4106 }
4107 if (when == HPSG_WHEN_NEVER) {
4108 return;
4109 }
4110
4111 // Figure out what kind of chunks we'll be sending.
4112 CHECK(what == HPSG_WHAT_MERGED_OBJECTS || what == HPSG_WHAT_DISTINCT_OBJECTS) << static_cast<int>(what);
4113
4114 // First, send a heap start chunk.
4115 uint8_t heap_id[4];
Brian Carlstrom7934ac22013-07-26 10:54:15 -07004116 JDWP::Set4BE(&heap_id[0], 1); // Heap id (bogus; we only have one heap).
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004117 Dbg::DdmSendChunk(native ? CHUNK_TYPE("NHST") : CHUNK_TYPE("HPST"), sizeof(heap_id), heap_id);
4118
Hiroshi Yamauchicf58d4a2013-09-26 14:21:22 -07004119 Thread* self = Thread::Current();
4120
4121 // To allow the Walk/InspectAll() below to exclusively-lock the
4122 // mutator lock, temporarily release the shared access to the
4123 // mutator lock here by transitioning to the suspended state.
4124 Locks::mutator_lock_->AssertSharedHeld(self);
4125 self->TransitionFromRunnableToSuspended(kSuspended);
4126
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004127 // Send a series of heap segment chunks.
Elliott Hughesa2155262011-11-16 16:26:58 -08004128 HeapChunkContext context((what == HPSG_WHAT_MERGED_OBJECTS), native);
4129 if (native) {
Christopher Ferrisc4ddc042014-05-13 14:47:50 -07004130#ifdef USE_DLMALLOC
Ian Rogers1d54e732013-05-02 21:10:01 -07004131 dlmalloc_inspect_all(HeapChunkContext::HeapChunkCallback, &context);
Christopher Ferrisc4ddc042014-05-13 14:47:50 -07004132#else
4133 UNIMPLEMENTED(WARNING) << "Native heap inspection is only supported with dlmalloc";
4134#endif
Elliott Hughesa2155262011-11-16 16:26:58 -08004135 } else {
Ian Rogers1d54e732013-05-02 21:10:01 -07004136 gc::Heap* heap = Runtime::Current()->GetHeap();
4137 const std::vector<gc::space::ContinuousSpace*>& spaces = heap->GetContinuousSpaces();
Ian Rogers1d54e732013-05-02 21:10:01 -07004138 typedef std::vector<gc::space::ContinuousSpace*>::const_iterator It;
4139 for (It cur = spaces.begin(), end = spaces.end(); cur != end; ++cur) {
Hiroshi Yamauchicf58d4a2013-09-26 14:21:22 -07004140 if ((*cur)->IsMallocSpace()) {
4141 (*cur)->AsMallocSpace()->Walk(HeapChunkContext::HeapChunkCallback, &context);
Mathieu Chartierb062fdd2012-07-03 09:51:48 -07004142 }
4143 }
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -07004144 // Walk the large objects, these are not in the AllocSpace.
4145 heap->GetLargeObjectsSpace()->Walk(HeapChunkContext::HeapChunkCallback, &context);
Elliott Hughesa2155262011-11-16 16:26:58 -08004146 }
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004147
Hiroshi Yamauchicf58d4a2013-09-26 14:21:22 -07004148 // Shared-lock the mutator lock back.
4149 self->TransitionFromSuspendedToRunnable();
4150 Locks::mutator_lock_->AssertSharedHeld(self);
4151
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004152 // Finally, send a heap end chunk.
4153 Dbg::DdmSendChunk(native ? CHUNK_TYPE("NHEN") : CHUNK_TYPE("HPEN"), sizeof(heap_id), heap_id);
Elliott Hughes767a1472011-10-26 18:49:02 -07004154}
4155
Elliott Hughesb1a58792013-07-11 18:10:58 -07004156static size_t GetAllocTrackerMax() {
4157#ifdef HAVE_ANDROID_OS
4158 // Check whether there's a system property overriding the number of records.
4159 const char* propertyName = "dalvik.vm.allocTrackerMax";
4160 char allocRecordMaxString[PROPERTY_VALUE_MAX];
4161 if (property_get(propertyName, allocRecordMaxString, "") > 0) {
4162 char* end;
4163 size_t value = strtoul(allocRecordMaxString, &end, 10);
4164 if (*end != '\0') {
Ruben Brunk3e47a742013-09-09 17:56:07 -07004165 LOG(ERROR) << "Ignoring " << propertyName << " '" << allocRecordMaxString
4166 << "' --- invalid";
Elliott Hughesb1a58792013-07-11 18:10:58 -07004167 return kDefaultNumAllocRecords;
4168 }
4169 if (!IsPowerOfTwo(value)) {
Ruben Brunk3e47a742013-09-09 17:56:07 -07004170 LOG(ERROR) << "Ignoring " << propertyName << " '" << allocRecordMaxString
4171 << "' --- not power of two";
Elliott Hughesb1a58792013-07-11 18:10:58 -07004172 return kDefaultNumAllocRecords;
4173 }
4174 return value;
4175 }
4176#endif
4177 return kDefaultNumAllocRecords;
4178}
4179
Elliott Hughes545a0642011-11-08 19:10:03 -08004180void Dbg::SetAllocTrackingEnabled(bool enabled) {
Elliott Hughes545a0642011-11-08 19:10:03 -08004181 if (enabled) {
Sebastien Hertzb98063a2014-03-26 10:57:20 +01004182 {
4183 MutexLock mu(Thread::Current(), *alloc_tracker_lock_);
4184 if (recent_allocation_records_ == NULL) {
4185 alloc_record_max_ = GetAllocTrackerMax();
4186 LOG(INFO) << "Enabling alloc tracker (" << alloc_record_max_ << " entries of "
4187 << kMaxAllocRecordStackDepth << " frames, taking "
4188 << PrettySize(sizeof(AllocRecord) * alloc_record_max_) << ")";
4189 alloc_record_head_ = alloc_record_count_ = 0;
4190 recent_allocation_records_ = new AllocRecord[alloc_record_max_];
4191 CHECK(recent_allocation_records_ != NULL);
4192 }
Elliott Hughes545a0642011-11-08 19:10:03 -08004193 }
Ian Rogersfa824272013-11-05 16:12:57 -08004194 Runtime::Current()->GetInstrumentation()->InstrumentQuickAllocEntryPoints();
Elliott Hughes545a0642011-11-08 19:10:03 -08004195 } else {
Ian Rogersfa824272013-11-05 16:12:57 -08004196 Runtime::Current()->GetInstrumentation()->UninstrumentQuickAllocEntryPoints();
Sebastien Hertzb98063a2014-03-26 10:57:20 +01004197 {
4198 MutexLock mu(Thread::Current(), *alloc_tracker_lock_);
4199 delete[] recent_allocation_records_;
4200 recent_allocation_records_ = NULL;
4201 }
Elliott Hughes545a0642011-11-08 19:10:03 -08004202 }
4203}
4204
Ian Rogers0399dde2012-06-06 17:09:28 -07004205struct AllocRecordStackVisitor : public StackVisitor {
Ian Rogers7a22fa62013-01-23 12:16:16 -08004206 AllocRecordStackVisitor(Thread* thread, AllocRecord* record)
Ian Rogersb726dcb2012-09-05 08:57:23 -07004207 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_)
Ian Rogers7a22fa62013-01-23 12:16:16 -08004208 : StackVisitor(thread, NULL), record(record), depth(0) {}
Elliott Hughes545a0642011-11-08 19:10:03 -08004209
Ian Rogers00f7d0e2012-07-19 15:28:27 -07004210 // TODO: Enable annotalysis. We know lock is held in constructor, but abstraction confuses
4211 // annotalysis.
4212 bool VisitFrame() NO_THREAD_SAFETY_ANALYSIS {
Elliott Hughes545a0642011-11-08 19:10:03 -08004213 if (depth >= kMaxAllocRecordStackDepth) {
Elliott Hughes530fa002012-03-12 11:44:49 -07004214 return false;
Elliott Hughes545a0642011-11-08 19:10:03 -08004215 }
Brian Carlstromea46f952013-07-30 01:26:50 -07004216 mirror::ArtMethod* m = GetMethod();
Ian Rogers0399dde2012-06-06 17:09:28 -07004217 if (!m->IsRuntimeMethod()) {
Hiroshi Yamauchib5a9e3d2014-06-09 12:11:20 -07004218 record->StackElement(depth)->SetMethod(m);
4219 record->StackElement(depth)->SetDexPc(GetDexPc());
Elliott Hughes530fa002012-03-12 11:44:49 -07004220 ++depth;
Elliott Hughes545a0642011-11-08 19:10:03 -08004221 }
Elliott Hughes530fa002012-03-12 11:44:49 -07004222 return true;
Elliott Hughes545a0642011-11-08 19:10:03 -08004223 }
4224
4225 ~AllocRecordStackVisitor() {
4226 // Clear out any unused stack trace elements.
4227 for (; depth < kMaxAllocRecordStackDepth; ++depth) {
Hiroshi Yamauchib5a9e3d2014-06-09 12:11:20 -07004228 record->StackElement(depth)->SetMethod(nullptr);
4229 record->StackElement(depth)->SetDexPc(0);
Elliott Hughes545a0642011-11-08 19:10:03 -08004230 }
4231 }
4232
4233 AllocRecord* record;
4234 size_t depth;
4235};
4236
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08004237void Dbg::RecordAllocation(mirror::Class* type, size_t byte_count) {
Elliott Hughes545a0642011-11-08 19:10:03 -08004238 Thread* self = Thread::Current();
4239 CHECK(self != NULL);
4240
Ian Rogers719d1a32014-03-06 12:13:39 -08004241 MutexLock mu(self, *alloc_tracker_lock_);
Elliott Hughes545a0642011-11-08 19:10:03 -08004242 if (recent_allocation_records_ == NULL) {
4243 return;
4244 }
4245
4246 // Advance and clip.
Ian Rogers719d1a32014-03-06 12:13:39 -08004247 if (++alloc_record_head_ == alloc_record_max_) {
4248 alloc_record_head_ = 0;
Elliott Hughes545a0642011-11-08 19:10:03 -08004249 }
4250
4251 // Fill in the basics.
Ian Rogers719d1a32014-03-06 12:13:39 -08004252 AllocRecord* record = &recent_allocation_records_[alloc_record_head_];
Hiroshi Yamauchib5a9e3d2014-06-09 12:11:20 -07004253 record->SetType(type);
4254 record->SetByteCount(byte_count);
4255 record->SetThinLockId(self->GetThreadId());
Elliott Hughes545a0642011-11-08 19:10:03 -08004256
4257 // Fill in the stack trace.
Ian Rogers7a22fa62013-01-23 12:16:16 -08004258 AllocRecordStackVisitor visitor(self, record);
Ian Rogers0399dde2012-06-06 17:09:28 -07004259 visitor.WalkStack();
Elliott Hughes545a0642011-11-08 19:10:03 -08004260
Ian Rogers719d1a32014-03-06 12:13:39 -08004261 if (alloc_record_count_ < alloc_record_max_) {
4262 ++alloc_record_count_;
Elliott Hughes545a0642011-11-08 19:10:03 -08004263 }
4264}
4265
Elliott Hughesa8f93cb2012-06-08 17:08:48 -07004266// Returns the index of the head element.
4267//
4268// We point at the most-recently-written record, so if gAllocRecordCount is 1
4269// we want to use the current element. Take "head+1" and subtract count
4270// from it.
4271//
4272// We need to handle underflow in our circular buffer, so we add
Elliott Hughesb1a58792013-07-11 18:10:58 -07004273// gAllocRecordMax and then mask it back down.
Ian Rogers719d1a32014-03-06 12:13:39 -08004274size_t Dbg::HeadIndex() {
4275 return (Dbg::alloc_record_head_ + 1 + Dbg::alloc_record_max_ - Dbg::alloc_record_count_) &
4276 (Dbg::alloc_record_max_ - 1);
Elliott Hughes545a0642011-11-08 19:10:03 -08004277}
4278
4279void Dbg::DumpRecentAllocations() {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07004280 ScopedObjectAccess soa(Thread::Current());
Ian Rogers719d1a32014-03-06 12:13:39 -08004281 MutexLock mu(soa.Self(), *alloc_tracker_lock_);
Elliott Hughes545a0642011-11-08 19:10:03 -08004282 if (recent_allocation_records_ == NULL) {
4283 LOG(INFO) << "Not recording tracked allocations";
4284 return;
4285 }
4286
4287 // "i" is the head of the list. We want to start at the end of the
4288 // list and move forward to the tail.
Elliott Hughesa8f93cb2012-06-08 17:08:48 -07004289 size_t i = HeadIndex();
Ian Rogers719d1a32014-03-06 12:13:39 -08004290 size_t count = alloc_record_count_;
Elliott Hughes545a0642011-11-08 19:10:03 -08004291
Ian Rogers719d1a32014-03-06 12:13:39 -08004292 LOG(INFO) << "Tracked allocations, (head=" << alloc_record_head_ << " count=" << count << ")";
Elliott Hughes545a0642011-11-08 19:10:03 -08004293 while (count--) {
4294 AllocRecord* record = &recent_allocation_records_[i];
4295
Hiroshi Yamauchib5a9e3d2014-06-09 12:11:20 -07004296 LOG(INFO) << StringPrintf(" Thread %-2d %6zd bytes ", record->ThinLockId(), record->ByteCount())
4297 << PrettyClass(record->Type());
Elliott Hughes545a0642011-11-08 19:10:03 -08004298
4299 for (size_t stack_frame = 0; stack_frame < kMaxAllocRecordStackDepth; ++stack_frame) {
Hiroshi Yamauchib5a9e3d2014-06-09 12:11:20 -07004300 AllocRecordStackTraceElement* stack_element = record->StackElement(stack_frame);
4301 mirror::ArtMethod* m = stack_element->Method();
Elliott Hughes545a0642011-11-08 19:10:03 -08004302 if (m == NULL) {
4303 break;
4304 }
Hiroshi Yamauchib5a9e3d2014-06-09 12:11:20 -07004305 LOG(INFO) << " " << PrettyMethod(m) << " line " << stack_element->LineNumber();
Elliott Hughes545a0642011-11-08 19:10:03 -08004306 }
4307
4308 // pause periodically to help logcat catch up
4309 if ((count % 5) == 0) {
4310 usleep(40000);
4311 }
4312
Ian Rogers719d1a32014-03-06 12:13:39 -08004313 i = (i + 1) & (alloc_record_max_ - 1);
Elliott Hughes545a0642011-11-08 19:10:03 -08004314 }
4315}
4316
4317class StringTable {
4318 public:
4319 StringTable() {
4320 }
4321
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08004322 void Add(const char* s) {
Elliott Hughes545a0642011-11-08 19:10:03 -08004323 table_.insert(s);
4324 }
4325
Elliott Hughesa8f93cb2012-06-08 17:08:48 -07004326 size_t IndexOf(const char* s) const {
Mathieu Chartier02e25112013-08-14 16:14:24 -07004327 auto it = table_.find(s);
Elliott Hughesa8f93cb2012-06-08 17:08:48 -07004328 if (it == table_.end()) {
4329 LOG(FATAL) << "IndexOf(\"" << s << "\") failed";
4330 }
4331 return std::distance(table_.begin(), it);
Elliott Hughes545a0642011-11-08 19:10:03 -08004332 }
4333
Elliott Hughesa8f93cb2012-06-08 17:08:48 -07004334 size_t Size() const {
Elliott Hughes545a0642011-11-08 19:10:03 -08004335 return table_.size();
4336 }
4337
Elliott Hughesa8f93cb2012-06-08 17:08:48 -07004338 void WriteTo(std::vector<uint8_t>& bytes) const {
Mathieu Chartier02e25112013-08-14 16:14:24 -07004339 for (const std::string& str : table_) {
4340 const char* s = str.c_str();
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08004341 size_t s_len = CountModifiedUtf8Chars(s);
Ian Rogers700a4022014-05-19 16:49:03 -07004342 std::unique_ptr<uint16_t> s_utf16(new uint16_t[s_len]);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08004343 ConvertModifiedUtf8ToUtf16(s_utf16.get(), s);
4344 JDWP::AppendUtf16BE(bytes, s_utf16.get(), s_len);
Elliott Hughes545a0642011-11-08 19:10:03 -08004345 }
4346 }
4347
4348 private:
Elliott Hughesa8f93cb2012-06-08 17:08:48 -07004349 std::set<std::string> table_;
Elliott Hughes545a0642011-11-08 19:10:03 -08004350 DISALLOW_COPY_AND_ASSIGN(StringTable);
4351};
4352
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07004353static const char* GetMethodSourceFile(mirror::ArtMethod* method)
Sebastien Hertz280286a2014-04-28 09:26:50 +02004354 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07004355 DCHECK(method != nullptr);
4356 const char* source_file = method->GetDeclaringClassSourceFile();
Sebastien Hertz280286a2014-04-28 09:26:50 +02004357 return (source_file != nullptr) ? source_file : "";
4358}
4359
Elliott Hughes545a0642011-11-08 19:10:03 -08004360/*
4361 * The data we send to DDMS contains everything we have recorded.
4362 *
4363 * Message header (all values big-endian):
4364 * (1b) message header len (to allow future expansion); includes itself
4365 * (1b) entry header len
4366 * (1b) stack frame len
4367 * (2b) number of entries
4368 * (4b) offset to string table from start of message
4369 * (2b) number of class name strings
4370 * (2b) number of method name strings
4371 * (2b) number of source file name strings
4372 * For each entry:
4373 * (4b) total allocation size
Elliott Hughes221229c2013-01-08 18:17:50 -08004374 * (2b) thread id
Elliott Hughes545a0642011-11-08 19:10:03 -08004375 * (2b) allocated object's class name index
4376 * (1b) stack depth
4377 * For each stack frame:
4378 * (2b) method's class name
4379 * (2b) method name
4380 * (2b) method source file
4381 * (2b) line number, clipped to 32767; -2 if native; -1 if no source
4382 * (xb) class name strings
4383 * (xb) method name strings
4384 * (xb) source file strings
4385 *
4386 * As with other DDM traffic, strings are sent as a 4-byte length
4387 * followed by UTF-16 data.
4388 *
4389 * We send up 16-bit unsigned indexes into string tables. In theory there
Elliott Hughesb1a58792013-07-11 18:10:58 -07004390 * can be (kMaxAllocRecordStackDepth * gAllocRecordMax) unique strings in
Elliott Hughes545a0642011-11-08 19:10:03 -08004391 * each table, but in practice there should be far fewer.
4392 *
4393 * The chief reason for using a string table here is to keep the size of
4394 * the DDMS message to a minimum. This is partly to make the protocol
4395 * efficient, but also because we have to form the whole thing up all at
4396 * once in a memory buffer.
4397 *
4398 * We use separate string tables for class names, method names, and source
4399 * files to keep the indexes small. There will generally be no overlap
4400 * between the contents of these tables.
4401 */
4402jbyteArray Dbg::GetRecentAllocations() {
4403 if (false) {
4404 DumpRecentAllocations();
4405 }
4406
Ian Rogers50b35e22012-10-04 10:09:15 -07004407 Thread* self = Thread::Current();
Elliott Hughes545a0642011-11-08 19:10:03 -08004408 std::vector<uint8_t> bytes;
Mathieu Chartier46e811b2013-07-10 17:09:14 -07004409 {
Ian Rogers719d1a32014-03-06 12:13:39 -08004410 MutexLock mu(self, *alloc_tracker_lock_);
Mathieu Chartier46e811b2013-07-10 17:09:14 -07004411 //
4412 // Part 1: generate string tables.
4413 //
4414 StringTable class_names;
4415 StringTable method_names;
4416 StringTable filenames;
Elliott Hughes545a0642011-11-08 19:10:03 -08004417
Ian Rogers719d1a32014-03-06 12:13:39 -08004418 int count = alloc_record_count_;
Mathieu Chartier46e811b2013-07-10 17:09:14 -07004419 int idx = HeadIndex();
4420 while (count--) {
4421 AllocRecord* record = &recent_allocation_records_[idx];
Elliott Hughes545a0642011-11-08 19:10:03 -08004422
Hiroshi Yamauchib5a9e3d2014-06-09 12:11:20 -07004423 class_names.Add(record->Type()->GetDescriptor().c_str());
Elliott Hughes545a0642011-11-08 19:10:03 -08004424
Mathieu Chartier46e811b2013-07-10 17:09:14 -07004425 for (size_t i = 0; i < kMaxAllocRecordStackDepth; i++) {
Hiroshi Yamauchib5a9e3d2014-06-09 12:11:20 -07004426 mirror::ArtMethod* m = record->StackElement(i)->Method();
Mathieu Chartier46e811b2013-07-10 17:09:14 -07004427 if (m != NULL) {
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07004428 class_names.Add(m->GetDeclaringClassDescriptor());
4429 method_names.Add(m->GetName());
4430 filenames.Add(GetMethodSourceFile(m));
Mathieu Chartier46e811b2013-07-10 17:09:14 -07004431 }
4432 }
Elliott Hughes545a0642011-11-08 19:10:03 -08004433
Ian Rogers719d1a32014-03-06 12:13:39 -08004434 idx = (idx + 1) & (alloc_record_max_ - 1);
Elliott Hughes545a0642011-11-08 19:10:03 -08004435 }
4436
Ian Rogers719d1a32014-03-06 12:13:39 -08004437 LOG(INFO) << "allocation records: " << alloc_record_count_;
Mathieu Chartier46e811b2013-07-10 17:09:14 -07004438
4439 //
4440 // Part 2: Generate the output and store it in the buffer.
4441 //
4442
4443 // (1b) message header len (to allow future expansion); includes itself
4444 // (1b) entry header len
4445 // (1b) stack frame len
4446 const int kMessageHeaderLen = 15;
4447 const int kEntryHeaderLen = 9;
4448 const int kStackFrameLen = 8;
4449 JDWP::Append1BE(bytes, kMessageHeaderLen);
4450 JDWP::Append1BE(bytes, kEntryHeaderLen);
4451 JDWP::Append1BE(bytes, kStackFrameLen);
4452
4453 // (2b) number of entries
4454 // (4b) offset to string table from start of message
4455 // (2b) number of class name strings
4456 // (2b) number of method name strings
4457 // (2b) number of source file name strings
Ian Rogers719d1a32014-03-06 12:13:39 -08004458 JDWP::Append2BE(bytes, alloc_record_count_);
Mathieu Chartier46e811b2013-07-10 17:09:14 -07004459 size_t string_table_offset = bytes.size();
Brian Carlstrom7934ac22013-07-26 10:54:15 -07004460 JDWP::Append4BE(bytes, 0); // We'll patch this later...
Mathieu Chartier46e811b2013-07-10 17:09:14 -07004461 JDWP::Append2BE(bytes, class_names.Size());
4462 JDWP::Append2BE(bytes, method_names.Size());
4463 JDWP::Append2BE(bytes, filenames.Size());
4464
Ian Rogers719d1a32014-03-06 12:13:39 -08004465 count = alloc_record_count_;
Mathieu Chartier46e811b2013-07-10 17:09:14 -07004466 idx = HeadIndex();
Mathieu Chartier46e811b2013-07-10 17:09:14 -07004467 while (count--) {
4468 // For each entry:
4469 // (4b) total allocation size
4470 // (2b) thread id
4471 // (2b) allocated object's class name index
4472 // (1b) stack depth
4473 AllocRecord* record = &recent_allocation_records_[idx];
4474 size_t stack_depth = record->GetDepth();
Mathieu Chartierf8322842014-05-16 10:59:25 -07004475 size_t allocated_object_class_name_index =
Hiroshi Yamauchib5a9e3d2014-06-09 12:11:20 -07004476 class_names.IndexOf(record->Type()->GetDescriptor().c_str());
4477 JDWP::Append4BE(bytes, record->ByteCount());
4478 JDWP::Append2BE(bytes, record->ThinLockId());
Mathieu Chartier46e811b2013-07-10 17:09:14 -07004479 JDWP::Append2BE(bytes, allocated_object_class_name_index);
4480 JDWP::Append1BE(bytes, stack_depth);
4481
Mathieu Chartier46e811b2013-07-10 17:09:14 -07004482 for (size_t stack_frame = 0; stack_frame < stack_depth; ++stack_frame) {
4483 // For each stack frame:
4484 // (2b) method's class name
4485 // (2b) method name
4486 // (2b) method source file
4487 // (2b) line number, clipped to 32767; -2 if native; -1 if no source
Hiroshi Yamauchib5a9e3d2014-06-09 12:11:20 -07004488 mirror::ArtMethod* m = record->StackElement(stack_frame)->Method();
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07004489 size_t class_name_index = class_names.IndexOf(m->GetDeclaringClassDescriptor());
4490 size_t method_name_index = method_names.IndexOf(m->GetName());
4491 size_t file_name_index = filenames.IndexOf(GetMethodSourceFile(m));
Mathieu Chartier46e811b2013-07-10 17:09:14 -07004492 JDWP::Append2BE(bytes, class_name_index);
4493 JDWP::Append2BE(bytes, method_name_index);
4494 JDWP::Append2BE(bytes, file_name_index);
Hiroshi Yamauchib5a9e3d2014-06-09 12:11:20 -07004495 JDWP::Append2BE(bytes, record->StackElement(stack_frame)->LineNumber());
Mathieu Chartier46e811b2013-07-10 17:09:14 -07004496 }
4497
Ian Rogers719d1a32014-03-06 12:13:39 -08004498 idx = (idx + 1) & (alloc_record_max_ - 1);
Mathieu Chartier46e811b2013-07-10 17:09:14 -07004499 }
4500
4501 // (xb) class name strings
4502 // (xb) method name strings
4503 // (xb) source file strings
4504 JDWP::Set4BE(&bytes[string_table_offset], bytes.size());
4505 class_names.WriteTo(bytes);
4506 method_names.WriteTo(bytes);
4507 filenames.WriteTo(bytes);
Elliott Hughes545a0642011-11-08 19:10:03 -08004508 }
Ian Rogers50b35e22012-10-04 10:09:15 -07004509 JNIEnv* env = self->GetJniEnv();
Elliott Hughes545a0642011-11-08 19:10:03 -08004510 jbyteArray result = env->NewByteArray(bytes.size());
4511 if (result != NULL) {
4512 env->SetByteArrayRegion(result, 0, bytes.size(), reinterpret_cast<const jbyte*>(&bytes[0]));
4513 }
4514 return result;
4515}
4516
Elliott Hughes872d4ec2011-10-21 17:07:15 -07004517} // namespace art