blob: 50e962460ddbde3a99eea210978a7ecc7d2fa212 [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,
Hiroshi Yamauchicc8c5c52014-06-13 15:08:05 -0700906 std::vector<JDWP::ObjectId>* monitor_vector,
Hiroshi Yamauchib5a9e3d2014-06-09 12:11:20 -0700907 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
Hiroshi Yamauchicc8c5c52014-06-13 15:08:05 -0700922 static void AppendOwnedMonitors(mirror::Object* owned_monitor, void* arg)
923 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Ian Rogers7a22fa62013-01-23 12:16:16 -0800924 OwnedMonitorVisitor* visitor = reinterpret_cast<OwnedMonitorVisitor*>(arg);
Hiroshi Yamauchicc8c5c52014-06-13 15:08:05 -0700925 visitor->monitors->push_back(gRegistry->Add(owned_monitor));
Hiroshi Yamauchib5a9e3d2014-06-09 12:11:20 -0700926 visitor->stack_depths->push_back(visitor->current_stack_depth);
Elliott Hughes4993bbc2013-01-10 15:41:25 -0800927 }
928
Elliott Hughes734b8c62013-01-11 15:32:45 -0800929 size_t current_stack_depth;
Hiroshi Yamauchicc8c5c52014-06-13 15:08:05 -0700930 std::vector<JDWP::ObjectId>* monitors;
Hiroshi Yamauchib5a9e3d2014-06-09 12:11:20 -0700931 std::vector<uint32_t>* stack_depths;
Elliott Hughes4993bbc2013-01-10 15:41:25 -0800932 };
Elliott Hughes4993bbc2013-01-10 15:41:25 -0800933
Hiroshi Yamauchib5a9e3d2014-06-09 12:11:20 -0700934 ScopedObjectAccessUnchecked soa(Thread::Current());
Hiroshi Yamauchicc8c5c52014-06-13 15:08:05 -0700935 Thread* thread;
Hiroshi Yamauchib5a9e3d2014-06-09 12:11:20 -0700936 {
937 MutexLock mu(soa.Self(), *Locks::thread_list_lock_);
Hiroshi Yamauchib5a9e3d2014-06-09 12:11:20 -0700938 JDWP::JdwpError error = DecodeThread(soa, thread_id, thread);
939 if (error != JDWP::ERR_NONE) {
940 return error;
941 }
942 if (!IsSuspendedForDebugger(soa, thread)) {
943 return JDWP::ERR_THREAD_NOT_SUSPENDED;
944 }
Hiroshi Yamauchib5a9e3d2014-06-09 12:11:20 -0700945 }
Hiroshi Yamauchicc8c5c52014-06-13 15:08:05 -0700946 std::unique_ptr<Context> context(Context::Create());
947 OwnedMonitorVisitor visitor(thread, context.get(), &monitors, &stack_depths);
948 visitor.WalkStack();
Elliott Hughes4993bbc2013-01-10 15:41:25 -0800949 return JDWP::ERR_NONE;
950}
951
Sebastien Hertz52d131d2014-03-13 16:17:40 +0100952JDWP::JdwpError Dbg::GetContendedMonitor(JDWP::ObjectId thread_id,
953 JDWP::ObjectId& contended_monitor) {
Hiroshi Yamauchib5a9e3d2014-06-09 12:11:20 -0700954 mirror::Object* contended_monitor_obj;
Elliott Hughesf9501702013-01-11 11:22:27 -0800955 ScopedObjectAccessUnchecked soa(Thread::Current());
Hiroshi Yamauchib5a9e3d2014-06-09 12:11:20 -0700956 {
957 MutexLock mu(soa.Self(), *Locks::thread_list_lock_);
958 Thread* thread;
959 JDWP::JdwpError error = DecodeThread(soa, thread_id, thread);
960 if (error != JDWP::ERR_NONE) {
961 return error;
962 }
963 if (!IsSuspendedForDebugger(soa, thread)) {
964 return JDWP::ERR_THREAD_NOT_SUSPENDED;
965 }
966 contended_monitor_obj = Monitor::GetContendedMonitor(thread);
Elliott Hughesf9501702013-01-11 11:22:27 -0800967 }
Hiroshi Yamauchib5a9e3d2014-06-09 12:11:20 -0700968 // Add() requires the thread_list_lock_ not held to avoid the lock
969 // level violation.
970 contended_monitor = gRegistry->Add(contended_monitor_obj);
Elliott Hughesf9501702013-01-11 11:22:27 -0800971 return JDWP::ERR_NONE;
972}
973
Elliott Hughesec0f83d2013-01-15 16:54:08 -0800974JDWP::JdwpError Dbg::GetInstanceCounts(const std::vector<JDWP::RefTypeId>& class_ids,
975 std::vector<uint64_t>& counts)
976 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Mathieu Chartier412c7fc2014-02-07 12:18:39 -0800977 gc::Heap* heap = Runtime::Current()->GetHeap();
978 heap->CollectGarbage(false);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800979 std::vector<mirror::Class*> classes;
Elliott Hughesec0f83d2013-01-15 16:54:08 -0800980 counts.clear();
981 for (size_t i = 0; i < class_ids.size(); ++i) {
982 JDWP::JdwpError status;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800983 mirror::Class* c = DecodeClass(class_ids[i], status);
Elliott Hughesec0f83d2013-01-15 16:54:08 -0800984 if (c == NULL) {
985 return status;
986 }
987 classes.push_back(c);
988 counts.push_back(0);
989 }
Mathieu Chartier412c7fc2014-02-07 12:18:39 -0800990 heap->CountInstances(classes, false, &counts[0]);
Elliott Hughesec0f83d2013-01-15 16:54:08 -0800991 return JDWP::ERR_NONE;
992}
993
Elliott Hughes3b78c942013-01-15 17:35:41 -0800994JDWP::JdwpError Dbg::GetInstances(JDWP::RefTypeId class_id, int32_t max_count, std::vector<JDWP::ObjectId>& instances)
995 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Mathieu Chartier412c7fc2014-02-07 12:18:39 -0800996 gc::Heap* heap = Runtime::Current()->GetHeap();
997 // We only want reachable instances, so do a GC.
998 heap->CollectGarbage(false);
Elliott Hughes3b78c942013-01-15 17:35:41 -0800999 JDWP::JdwpError status;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001000 mirror::Class* c = DecodeClass(class_id, status);
Mathieu Chartier412c7fc2014-02-07 12:18:39 -08001001 if (c == nullptr) {
Elliott Hughes3b78c942013-01-15 17:35:41 -08001002 return status;
1003 }
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001004 std::vector<mirror::Object*> raw_instances;
Elliott Hughes3b78c942013-01-15 17:35:41 -08001005 Runtime::Current()->GetHeap()->GetInstances(c, max_count, raw_instances);
1006 for (size_t i = 0; i < raw_instances.size(); ++i) {
1007 instances.push_back(gRegistry->Add(raw_instances[i]));
1008 }
1009 return JDWP::ERR_NONE;
1010}
1011
Elliott Hughes0cbaff52013-01-16 15:28:01 -08001012JDWP::JdwpError Dbg::GetReferringObjects(JDWP::ObjectId object_id, int32_t max_count,
1013 std::vector<JDWP::ObjectId>& referring_objects)
1014 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Mathieu Chartier412c7fc2014-02-07 12:18:39 -08001015 gc::Heap* heap = Runtime::Current()->GetHeap();
1016 heap->CollectGarbage(false);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001017 mirror::Object* o = gRegistry->Get<mirror::Object*>(object_id);
Elliott Hughes64f574f2013-02-20 14:57:12 -08001018 if (o == NULL || o == ObjectRegistry::kInvalidObject) {
Elliott Hughes0cbaff52013-01-16 15:28:01 -08001019 return JDWP::ERR_INVALID_OBJECT;
1020 }
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001021 std::vector<mirror::Object*> raw_instances;
Mathieu Chartier412c7fc2014-02-07 12:18:39 -08001022 heap->GetReferringObjects(o, max_count, raw_instances);
Elliott Hughes0cbaff52013-01-16 15:28:01 -08001023 for (size_t i = 0; i < raw_instances.size(); ++i) {
1024 referring_objects.push_back(gRegistry->Add(raw_instances[i]));
1025 }
1026 return JDWP::ERR_NONE;
1027}
1028
Elliott Hughes64f574f2013-02-20 14:57:12 -08001029JDWP::JdwpError Dbg::DisableCollection(JDWP::ObjectId object_id)
1030 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Sebastien Hertze96060a2013-12-11 12:06:28 +01001031 mirror::Object* o = gRegistry->Get<mirror::Object*>(object_id);
1032 if (o == NULL || o == ObjectRegistry::kInvalidObject) {
1033 return JDWP::ERR_INVALID_OBJECT;
1034 }
Elliott Hughes64f574f2013-02-20 14:57:12 -08001035 gRegistry->DisableCollection(object_id);
1036 return JDWP::ERR_NONE;
1037}
1038
1039JDWP::JdwpError Dbg::EnableCollection(JDWP::ObjectId object_id)
1040 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Sebastien Hertze96060a2013-12-11 12:06:28 +01001041 mirror::Object* o = gRegistry->Get<mirror::Object*>(object_id);
1042 // Unlike DisableCollection, JDWP specs do not state an invalid object causes an error. The RI
1043 // also ignores these cases and never return an error. However it's not obvious why this command
1044 // should behave differently from DisableCollection and IsCollected commands. So let's be more
1045 // strict and return an error if this happens.
1046 if (o == NULL || o == ObjectRegistry::kInvalidObject) {
1047 return JDWP::ERR_INVALID_OBJECT;
1048 }
Elliott Hughes64f574f2013-02-20 14:57:12 -08001049 gRegistry->EnableCollection(object_id);
1050 return JDWP::ERR_NONE;
1051}
1052
1053JDWP::JdwpError Dbg::IsCollected(JDWP::ObjectId object_id, bool& is_collected)
1054 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Sebastien Hertz65637eb2014-01-10 17:40:02 +01001055 if (object_id == 0) {
1056 // Null object id is invalid.
Sebastien Hertze96060a2013-12-11 12:06:28 +01001057 return JDWP::ERR_INVALID_OBJECT;
1058 }
Sebastien Hertz65637eb2014-01-10 17:40:02 +01001059 // JDWP specs state an INVALID_OBJECT error is returned if the object ID is not valid. However
1060 // the RI seems to ignore this and assume object has been collected.
1061 mirror::Object* o = gRegistry->Get<mirror::Object*>(object_id);
1062 if (o == NULL || o == ObjectRegistry::kInvalidObject) {
1063 is_collected = true;
1064 } else {
1065 is_collected = gRegistry->IsCollected(object_id);
1066 }
Elliott Hughes64f574f2013-02-20 14:57:12 -08001067 return JDWP::ERR_NONE;
1068}
1069
1070void Dbg::DisposeObject(JDWP::ObjectId object_id, uint32_t reference_count)
1071 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
1072 gRegistry->DisposeObject(object_id, reference_count);
1073}
1074
Sebastien Hertz4d8fd492014-03-28 16:29:41 +01001075static JDWP::JdwpTypeTag GetTypeTag(mirror::Class* klass)
1076 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
1077 DCHECK(klass != nullptr);
1078 if (klass->IsArrayClass()) {
1079 return JDWP::TT_ARRAY;
1080 } else if (klass->IsInterface()) {
1081 return JDWP::TT_INTERFACE;
1082 } else {
1083 return JDWP::TT_CLASS;
1084 }
1085}
1086
Elliott Hughes88d63092013-01-09 09:55:54 -08001087JDWP::JdwpError Dbg::GetReflectedType(JDWP::RefTypeId class_id, JDWP::ExpandBuf* pReply) {
Elliott Hughes436e3722012-02-17 20:01:47 -08001088 JDWP::JdwpError status;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001089 mirror::Class* c = DecodeClass(class_id, status);
Elliott Hughes436e3722012-02-17 20:01:47 -08001090 if (c == NULL) {
1091 return status;
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -08001092 }
Elliott Hughes436e3722012-02-17 20:01:47 -08001093
Sebastien Hertz4d8fd492014-03-28 16:29:41 +01001094 JDWP::JdwpTypeTag type_tag = GetTypeTag(c);
1095 expandBufAdd1(pReply, type_tag);
Elliott Hughes88d63092013-01-09 09:55:54 -08001096 expandBufAddRefTypeId(pReply, class_id);
Elliott Hughes436e3722012-02-17 20:01:47 -08001097 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001098}
1099
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -08001100void Dbg::GetClassList(std::vector<JDWP::RefTypeId>& classes) {
Elliott Hughesa2155262011-11-16 16:26:58 -08001101 // Get the complete list of reference classes (i.e. all classes except
1102 // the primitive types).
1103 // Returns a newly-allocated buffer full of RefTypeId values.
1104 struct ClassListCreator {
Elliott Hughesba8eee12012-01-24 20:25:24 -08001105 explicit ClassListCreator(std::vector<JDWP::RefTypeId>& classes) : classes(classes) {
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -08001106 }
1107
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001108 static bool Visit(mirror::Class* c, void* arg) {
Elliott Hughesa2155262011-11-16 16:26:58 -08001109 return reinterpret_cast<ClassListCreator*>(arg)->Visit(c);
1110 }
1111
Elliott Hughes64f574f2013-02-20 14:57:12 -08001112 // TODO: Enable annotalysis. We know lock is held in constructor, but abstraction confuses
1113 // annotalysis.
1114 bool Visit(mirror::Class* c) NO_THREAD_SAFETY_ANALYSIS {
Elliott Hughesa2155262011-11-16 16:26:58 -08001115 if (!c->IsPrimitive()) {
Elliott Hughes64f574f2013-02-20 14:57:12 -08001116 classes.push_back(gRegistry->AddRefType(c));
Elliott Hughesa2155262011-11-16 16:26:58 -08001117 }
1118 return true;
1119 }
1120
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -08001121 std::vector<JDWP::RefTypeId>& classes;
Elliott Hughesa2155262011-11-16 16:26:58 -08001122 };
1123
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -08001124 ClassListCreator clc(classes);
Elliott Hughesa2155262011-11-16 16:26:58 -08001125 Runtime::Current()->GetClassLinker()->VisitClasses(ClassListCreator::Visit, &clc);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001126}
1127
Elliott Hughes88d63092013-01-09 09:55:54 -08001128JDWP::JdwpError Dbg::GetClassInfo(JDWP::RefTypeId class_id, JDWP::JdwpTypeTag* pTypeTag, uint32_t* pStatus, std::string* pDescriptor) {
Elliott Hughes436e3722012-02-17 20:01:47 -08001129 JDWP::JdwpError status;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001130 mirror::Class* c = DecodeClass(class_id, status);
Elliott Hughes436e3722012-02-17 20:01:47 -08001131 if (c == NULL) {
1132 return status;
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -08001133 }
1134
Elliott Hughesa2155262011-11-16 16:26:58 -08001135 if (c->IsArrayClass()) {
1136 *pStatus = JDWP::CS_VERIFIED | JDWP::CS_PREPARED;
1137 *pTypeTag = JDWP::TT_ARRAY;
1138 } else {
1139 if (c->IsErroneous()) {
1140 *pStatus = JDWP::CS_ERROR;
1141 } else {
1142 *pStatus = JDWP::CS_VERIFIED | JDWP::CS_PREPARED | JDWP::CS_INITIALIZED;
1143 }
1144 *pTypeTag = c->IsInterface() ? JDWP::TT_INTERFACE : JDWP::TT_CLASS;
1145 }
1146
1147 if (pDescriptor != NULL) {
Mathieu Chartierf8322842014-05-16 10:59:25 -07001148 *pDescriptor = c->GetDescriptor();
Elliott Hughesa2155262011-11-16 16:26:58 -08001149 }
Elliott Hughes436e3722012-02-17 20:01:47 -08001150 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001151}
1152
Elliott Hughesc3b77c72011-12-15 20:56:48 -08001153void Dbg::FindLoadedClassBySignature(const char* descriptor, std::vector<JDWP::RefTypeId>& ids) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001154 std::vector<mirror::Class*> classes;
Elliott Hughes6fa602d2011-12-02 17:54:25 -08001155 Runtime::Current()->GetClassLinker()->LookupClasses(descriptor, classes);
1156 ids.clear();
1157 for (size_t i = 0; i < classes.size(); ++i) {
1158 ids.push_back(gRegistry->Add(classes[i]));
1159 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001160}
1161
Elliott Hughes64f574f2013-02-20 14:57:12 -08001162JDWP::JdwpError Dbg::GetReferenceType(JDWP::ObjectId object_id, JDWP::ExpandBuf* pReply)
1163 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001164 mirror::Object* o = gRegistry->Get<mirror::Object*>(object_id);
Elliott Hughes64f574f2013-02-20 14:57:12 -08001165 if (o == NULL || o == ObjectRegistry::kInvalidObject) {
Elliott Hughes2435a572012-02-17 16:07:41 -08001166 return JDWP::ERR_INVALID_OBJECT;
Elliott Hughes499c5132011-11-17 14:55:11 -08001167 }
Elliott Hughes2435a572012-02-17 16:07:41 -08001168
Sebastien Hertz4d8fd492014-03-28 16:29:41 +01001169 JDWP::JdwpTypeTag type_tag = GetTypeTag(o->GetClass());
Elliott Hughes64f574f2013-02-20 14:57:12 -08001170 JDWP::RefTypeId type_id = gRegistry->AddRefType(o->GetClass());
Elliott Hughes2435a572012-02-17 16:07:41 -08001171
1172 expandBufAdd1(pReply, type_tag);
1173 expandBufAddRefTypeId(pReply, type_id);
1174
1175 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001176}
1177
Ian Rogersfc0e94b2013-09-23 23:51:32 -07001178JDWP::JdwpError Dbg::GetSignature(JDWP::RefTypeId class_id, std::string* signature) {
Elliott Hughes1fe7afb2012-02-13 17:23:03 -08001179 JDWP::JdwpError status;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001180 mirror::Class* c = DecodeClass(class_id, status);
Elliott Hughes1fe7afb2012-02-13 17:23:03 -08001181 if (c == NULL) {
1182 return status;
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -08001183 }
Mathieu Chartierf8322842014-05-16 10:59:25 -07001184 *signature = c->GetDescriptor();
Elliott Hughes1fe7afb2012-02-13 17:23:03 -08001185 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001186}
1187
Elliott Hughes88d63092013-01-09 09:55:54 -08001188JDWP::JdwpError Dbg::GetSourceFile(JDWP::RefTypeId class_id, std::string& result) {
Elliott Hughes436e3722012-02-17 20:01:47 -08001189 JDWP::JdwpError status;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001190 mirror::Class* c = DecodeClass(class_id, status);
Sebastien Hertz4206eb52014-06-05 10:15:45 +02001191 if (c == nullptr) {
Elliott Hughes436e3722012-02-17 20:01:47 -08001192 return status;
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -08001193 }
Sebastien Hertz4206eb52014-06-05 10:15:45 +02001194 const char* source_file = c->GetSourceFile();
1195 if (source_file == nullptr) {
Sebastien Hertzb7054ba2014-03-13 11:52:31 +01001196 return JDWP::ERR_ABSENT_INFORMATION;
1197 }
Sebastien Hertz4206eb52014-06-05 10:15:45 +02001198 result = source_file;
Elliott Hughes436e3722012-02-17 20:01:47 -08001199 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001200}
1201
Elliott Hughes88d63092013-01-09 09:55:54 -08001202JDWP::JdwpError Dbg::GetObjectTag(JDWP::ObjectId object_id, uint8_t& tag) {
Ian Rogers98379392014-02-24 16:53:16 -08001203 ScopedObjectAccessUnchecked soa(Thread::Current());
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001204 mirror::Object* o = gRegistry->Get<mirror::Object*>(object_id);
Elliott Hughes64f574f2013-02-20 14:57:12 -08001205 if (o == ObjectRegistry::kInvalidObject) {
Elliott Hughes546b9862012-06-20 16:06:13 -07001206 return JDWP::ERR_INVALID_OBJECT;
1207 }
Ian Rogers98379392014-02-24 16:53:16 -08001208 tag = TagFromObject(soa, o);
Elliott Hughes546b9862012-06-20 16:06:13 -07001209 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001210}
1211
Elliott Hughesaed4be92011-12-02 16:16:23 -08001212size_t Dbg::GetTagWidth(JDWP::JdwpTag tag) {
Elliott Hughesdbb40792011-11-18 17:05:22 -08001213 switch (tag) {
1214 case JDWP::JT_VOID:
1215 return 0;
1216 case JDWP::JT_BYTE:
1217 case JDWP::JT_BOOLEAN:
1218 return 1;
1219 case JDWP::JT_CHAR:
1220 case JDWP::JT_SHORT:
1221 return 2;
1222 case JDWP::JT_FLOAT:
1223 case JDWP::JT_INT:
1224 return 4;
1225 case JDWP::JT_ARRAY:
1226 case JDWP::JT_OBJECT:
1227 case JDWP::JT_STRING:
1228 case JDWP::JT_THREAD:
1229 case JDWP::JT_THREAD_GROUP:
1230 case JDWP::JT_CLASS_LOADER:
1231 case JDWP::JT_CLASS_OBJECT:
1232 return sizeof(JDWP::ObjectId);
1233 case JDWP::JT_DOUBLE:
1234 case JDWP::JT_LONG:
1235 return 8;
1236 default:
Elliott Hughes3d30d9b2011-12-07 17:35:48 -08001237 LOG(FATAL) << "Unknown tag " << tag;
Elliott Hughesdbb40792011-11-18 17:05:22 -08001238 return -1;
1239 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001240}
1241
Elliott Hughes88d63092013-01-09 09:55:54 -08001242JDWP::JdwpError Dbg::GetArrayLength(JDWP::ObjectId array_id, int& length) {
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -08001243 JDWP::JdwpError status;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001244 mirror::Array* a = DecodeArray(array_id, status);
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -08001245 if (a == NULL) {
1246 return status;
Elliott Hughes24437992011-11-30 14:49:33 -08001247 }
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -08001248 length = a->GetLength();
1249 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001250}
1251
Elliott Hughes88d63092013-01-09 09:55:54 -08001252JDWP::JdwpError Dbg::OutputArray(JDWP::ObjectId array_id, int offset, int count, JDWP::ExpandBuf* pReply) {
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -08001253 JDWP::JdwpError status;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001254 mirror::Array* a = DecodeArray(array_id, status);
Ian Rogers98379392014-02-24 16:53:16 -08001255 if (a == nullptr) {
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -08001256 return status;
1257 }
Elliott Hughes24437992011-11-30 14:49:33 -08001258
1259 if (offset < 0 || count < 0 || offset > a->GetLength() || a->GetLength() - offset < count) {
1260 LOG(WARNING) << __FUNCTION__ << " access out of bounds: offset=" << offset << "; count=" << count;
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -08001261 return JDWP::ERR_INVALID_LENGTH;
Elliott Hughes24437992011-11-30 14:49:33 -08001262 }
Mathieu Chartierf8322842014-05-16 10:59:25 -07001263 std::string descriptor(a->GetClass()->GetDescriptor());
Elliott Hughes24437992011-11-30 14:49:33 -08001264 JDWP::JdwpTag tag = BasicTagFromDescriptor(descriptor.c_str() + 1);
1265
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -08001266 expandBufAdd1(pReply, tag);
1267 expandBufAdd4BE(pReply, count);
1268
Elliott Hughes24437992011-11-30 14:49:33 -08001269 if (IsPrimitiveTag(tag)) {
1270 size_t width = GetTagWidth(tag);
Elliott Hughes24437992011-11-30 14:49:33 -08001271 uint8_t* dst = expandBufAddSpace(pReply, count * width);
1272 if (width == 8) {
Ian Rogersef7d42f2014-01-06 12:55:46 -08001273 const uint64_t* src8 = reinterpret_cast<uint64_t*>(a->GetRawData(sizeof(uint64_t), 0));
Elliott Hughes24437992011-11-30 14:49:33 -08001274 for (int i = 0; i < count; ++i) JDWP::Write8BE(&dst, src8[offset + i]);
1275 } else if (width == 4) {
Ian Rogersef7d42f2014-01-06 12:55:46 -08001276 const uint32_t* src4 = reinterpret_cast<uint32_t*>(a->GetRawData(sizeof(uint32_t), 0));
Elliott Hughes24437992011-11-30 14:49:33 -08001277 for (int i = 0; i < count; ++i) JDWP::Write4BE(&dst, src4[offset + i]);
1278 } else if (width == 2) {
Ian Rogersef7d42f2014-01-06 12:55:46 -08001279 const uint16_t* src2 = reinterpret_cast<uint16_t*>(a->GetRawData(sizeof(uint16_t), 0));
Elliott Hughes24437992011-11-30 14:49:33 -08001280 for (int i = 0; i < count; ++i) JDWP::Write2BE(&dst, src2[offset + i]);
1281 } else {
Ian Rogersef7d42f2014-01-06 12:55:46 -08001282 const uint8_t* src = reinterpret_cast<uint8_t*>(a->GetRawData(sizeof(uint8_t), 0));
Elliott Hughes24437992011-11-30 14:49:33 -08001283 memcpy(dst, &src[offset * width], count * width);
1284 }
1285 } else {
Ian Rogers98379392014-02-24 16:53:16 -08001286 ScopedObjectAccessUnchecked soa(Thread::Current());
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001287 mirror::ObjectArray<mirror::Object>* oa = a->AsObjectArray<mirror::Object>();
Elliott Hughes24437992011-11-30 14:49:33 -08001288 for (int i = 0; i < count; ++i) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001289 mirror::Object* element = oa->Get(offset + i);
Ian Rogers98379392014-02-24 16:53:16 -08001290 JDWP::JdwpTag specific_tag = (element != nullptr) ? TagFromObject(soa, element)
1291 : tag;
Elliott Hughes24437992011-11-30 14:49:33 -08001292 expandBufAdd1(pReply, specific_tag);
1293 expandBufAddObjectId(pReply, gRegistry->Add(element));
1294 }
1295 }
1296
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -08001297 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001298}
1299
Ian Rogersef7d42f2014-01-06 12:55:46 -08001300template <typename T>
1301static void CopyArrayData(mirror::Array* a, JDWP::Request& src, int offset, int count)
1302 NO_THREAD_SAFETY_ANALYSIS {
1303 // TODO: fix when annotalysis correctly handles non-member functions.
Elliott Hughes4b9702c2013-02-20 18:13:24 -08001304 DCHECK(a->GetClass()->IsPrimitiveArray());
1305
Ian Rogersef7d42f2014-01-06 12:55:46 -08001306 T* dst = reinterpret_cast<T*>(a->GetRawData(sizeof(T), offset));
Elliott Hughes4b9702c2013-02-20 18:13:24 -08001307 for (int i = 0; i < count; ++i) {
1308 *dst++ = src.ReadValue(sizeof(T));
1309 }
1310}
1311
Elliott Hughes88d63092013-01-09 09:55:54 -08001312JDWP::JdwpError Dbg::SetArrayElements(JDWP::ObjectId array_id, int offset, int count,
Elliott Hughes4b9702c2013-02-20 18:13:24 -08001313 JDWP::Request& request)
Ian Rogersb726dcb2012-09-05 08:57:23 -07001314 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -08001315 JDWP::JdwpError status;
Elliott Hughes4b9702c2013-02-20 18:13:24 -08001316 mirror::Array* dst = DecodeArray(array_id, status);
1317 if (dst == NULL) {
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -08001318 return status;
1319 }
Elliott Hughesf03b8f62011-12-02 14:26:25 -08001320
Elliott Hughes4b9702c2013-02-20 18:13:24 -08001321 if (offset < 0 || count < 0 || offset > dst->GetLength() || dst->GetLength() - offset < count) {
Elliott Hughesf03b8f62011-12-02 14:26:25 -08001322 LOG(WARNING) << __FUNCTION__ << " access out of bounds: offset=" << offset << "; count=" << count;
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -08001323 return JDWP::ERR_INVALID_LENGTH;
Elliott Hughesf03b8f62011-12-02 14:26:25 -08001324 }
Mathieu Chartierf8322842014-05-16 10:59:25 -07001325 std::string descriptor = dst->GetClass()->GetDescriptor();
1326 JDWP::JdwpTag tag = BasicTagFromDescriptor(descriptor.c_str() + 1);
Elliott Hughesf03b8f62011-12-02 14:26:25 -08001327
1328 if (IsPrimitiveTag(tag)) {
1329 size_t width = GetTagWidth(tag);
Elliott Hughesf03b8f62011-12-02 14:26:25 -08001330 if (width == 8) {
Elliott Hughes4b9702c2013-02-20 18:13:24 -08001331 CopyArrayData<uint64_t>(dst, request, offset, count);
Elliott Hughesf03b8f62011-12-02 14:26:25 -08001332 } else if (width == 4) {
Elliott Hughes4b9702c2013-02-20 18:13:24 -08001333 CopyArrayData<uint32_t>(dst, request, offset, count);
Elliott Hughesf03b8f62011-12-02 14:26:25 -08001334 } else if (width == 2) {
Elliott Hughes4b9702c2013-02-20 18:13:24 -08001335 CopyArrayData<uint16_t>(dst, request, offset, count);
Elliott Hughesf03b8f62011-12-02 14:26:25 -08001336 } else {
Elliott Hughes4b9702c2013-02-20 18:13:24 -08001337 CopyArrayData<uint8_t>(dst, request, offset, count);
Elliott Hughesf03b8f62011-12-02 14:26:25 -08001338 }
1339 } else {
Elliott Hughes4b9702c2013-02-20 18:13:24 -08001340 mirror::ObjectArray<mirror::Object>* oa = dst->AsObjectArray<mirror::Object>();
Elliott Hughesf03b8f62011-12-02 14:26:25 -08001341 for (int i = 0; i < count; ++i) {
Elliott Hughes4b9702c2013-02-20 18:13:24 -08001342 JDWP::ObjectId id = request.ReadObjectId();
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001343 mirror::Object* o = gRegistry->Get<mirror::Object*>(id);
Elliott Hughes64f574f2013-02-20 14:57:12 -08001344 if (o == ObjectRegistry::kInvalidObject) {
Elliott Hughes436e3722012-02-17 20:01:47 -08001345 return JDWP::ERR_INVALID_OBJECT;
1346 }
Sebastien Hertzd2fe10a2014-01-15 10:20:56 +01001347 oa->Set<false>(offset + i, o);
Elliott Hughesf03b8f62011-12-02 14:26:25 -08001348 }
1349 }
1350
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -08001351 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001352}
1353
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -08001354JDWP::ObjectId Dbg::CreateString(const std::string& str) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001355 return gRegistry->Add(mirror::String::AllocFromModifiedUtf8(Thread::Current(), str.c_str()));
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001356}
1357
Elliott Hughes88d63092013-01-09 09:55:54 -08001358JDWP::JdwpError Dbg::CreateObject(JDWP::RefTypeId class_id, JDWP::ObjectId& new_object) {
Elliott Hughes436e3722012-02-17 20:01:47 -08001359 JDWP::JdwpError status;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001360 mirror::Class* c = DecodeClass(class_id, status);
Elliott Hughes436e3722012-02-17 20:01:47 -08001361 if (c == NULL) {
1362 return status;
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -08001363 }
Ian Rogers50b35e22012-10-04 10:09:15 -07001364 new_object = gRegistry->Add(c->AllocObject(Thread::Current()));
Elliott Hughes436e3722012-02-17 20:01:47 -08001365 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001366}
1367
Elliott Hughesbf13d362011-12-08 15:51:37 -08001368/*
1369 * Used by Eclipse's "Display" view to evaluate "new byte[5]" to get "(byte[]) [0, 0, 0, 0, 0]".
1370 */
Elliott Hughes88d63092013-01-09 09:55:54 -08001371JDWP::JdwpError Dbg::CreateArrayObject(JDWP::RefTypeId array_class_id, uint32_t length,
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001372 JDWP::ObjectId& new_array) {
Elliott Hughes436e3722012-02-17 20:01:47 -08001373 JDWP::JdwpError status;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001374 mirror::Class* c = DecodeClass(array_class_id, status);
Elliott Hughes436e3722012-02-17 20:01:47 -08001375 if (c == NULL) {
1376 return status;
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -08001377 }
Ian Rogers6fac4472014-02-25 17:01:10 -08001378 new_array = gRegistry->Add(mirror::Array::Alloc<true>(Thread::Current(), c, length,
1379 c->GetComponentSize(),
1380 Runtime::Current()->GetHeap()->GetCurrentAllocator()));
Elliott Hughes436e3722012-02-17 20:01:47 -08001381 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001382}
1383
Elliott Hughes88d63092013-01-09 09:55:54 -08001384bool Dbg::MatchType(JDWP::RefTypeId instance_class_id, JDWP::RefTypeId class_id) {
Elliott Hughes436e3722012-02-17 20:01:47 -08001385 JDWP::JdwpError status;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001386 mirror::Class* c1 = DecodeClass(instance_class_id, status);
Elliott Hughesa656a0f2012-02-21 18:03:44 -08001387 CHECK(c1 != NULL);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001388 mirror::Class* c2 = DecodeClass(class_id, status);
Elliott Hughesa656a0f2012-02-21 18:03:44 -08001389 CHECK(c2 != NULL);
Sebastien Hertz123756a2013-11-27 15:49:42 +01001390 return c2->IsAssignableFrom(c1);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001391}
1392
Brian Carlstromea46f952013-07-30 01:26:50 -07001393static JDWP::FieldId ToFieldId(const mirror::ArtField* f)
Ian Rogersb726dcb2012-09-05 08:57:23 -07001394 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Mathieu Chartier590fee92013-09-13 13:46:47 -07001395 CHECK(!kMovingFields);
Elliott Hughes03181a82011-11-17 17:22:21 -08001396 return static_cast<JDWP::FieldId>(reinterpret_cast<uintptr_t>(f));
Elliott Hughes03181a82011-11-17 17:22:21 -08001397}
1398
Brian Carlstromea46f952013-07-30 01:26:50 -07001399static JDWP::MethodId ToMethodId(const mirror::ArtMethod* m)
Ian Rogersb726dcb2012-09-05 08:57:23 -07001400 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Mathieu Chartier590fee92013-09-13 13:46:47 -07001401 CHECK(!kMovingMethods);
Elliott Hughes03181a82011-11-17 17:22:21 -08001402 return static_cast<JDWP::MethodId>(reinterpret_cast<uintptr_t>(m));
Elliott Hughes03181a82011-11-17 17:22:21 -08001403}
1404
Brian Carlstromea46f952013-07-30 01:26:50 -07001405static mirror::ArtField* FromFieldId(JDWP::FieldId fid)
Ian Rogersb726dcb2012-09-05 08:57:23 -07001406 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Mathieu Chartier590fee92013-09-13 13:46:47 -07001407 CHECK(!kMovingFields);
Brian Carlstromea46f952013-07-30 01:26:50 -07001408 return reinterpret_cast<mirror::ArtField*>(static_cast<uintptr_t>(fid));
Elliott Hughesaed4be92011-12-02 16:16:23 -08001409}
1410
Brian Carlstromea46f952013-07-30 01:26:50 -07001411static mirror::ArtMethod* FromMethodId(JDWP::MethodId mid)
Ian Rogersb726dcb2012-09-05 08:57:23 -07001412 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Mathieu Chartier590fee92013-09-13 13:46:47 -07001413 CHECK(!kMovingMethods);
Brian Carlstromea46f952013-07-30 01:26:50 -07001414 return reinterpret_cast<mirror::ArtMethod*>(static_cast<uintptr_t>(mid));
Elliott Hughes03181a82011-11-17 17:22:21 -08001415}
1416
Brian Carlstromea46f952013-07-30 01:26:50 -07001417static void SetLocation(JDWP::JdwpLocation& location, mirror::ArtMethod* m, uint32_t dex_pc)
Ian Rogersb726dcb2012-09-05 08:57:23 -07001418 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08001419 if (m == NULL) {
1420 memset(&location, 0, sizeof(location));
1421 } else {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001422 mirror::Class* c = m->GetDeclaringClass();
Sebastien Hertz4d8fd492014-03-28 16:29:41 +01001423 location.type_tag = GetTypeTag(c);
Sebastien Hertzcb19ebf2014-03-11 15:26:35 +01001424 location.class_id = gRegistry->AddRefType(c);
Elliott Hughes74847412012-06-20 18:10:21 -07001425 location.method_id = ToMethodId(m);
Sebastien Hertzcb19ebf2014-03-11 15:26:35 +01001426 location.dex_pc = (m->IsNative() || m->IsProxyMethod()) ? static_cast<uint64_t>(-1) : dex_pc;
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08001427 }
Elliott Hughesd07986f2011-12-06 18:27:45 -08001428}
1429
Elliott Hughesa96836a2013-01-17 12:27:49 -08001430std::string Dbg::GetMethodName(JDWP::MethodId method_id)
Ian Rogersb726dcb2012-09-05 08:57:23 -07001431 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Brian Carlstromea46f952013-07-30 01:26:50 -07001432 mirror::ArtMethod* m = FromMethodId(method_id);
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07001433 return m->GetName();
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001434}
1435
Elliott Hughesa96836a2013-01-17 12:27:49 -08001436std::string Dbg::GetFieldName(JDWP::FieldId field_id)
1437 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Mathieu Chartier61c5ebc2014-06-05 17:42:53 -07001438 return FromFieldId(field_id)->GetName();
Elliott Hughesa96836a2013-01-17 12:27:49 -08001439}
1440
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001441/*
1442 * Augment the access flags for synthetic methods and fields by setting
1443 * the (as described by the spec) "0xf0000000 bit". Also, strip out any
1444 * flags not specified by the Java programming language.
1445 */
1446static uint32_t MangleAccessFlags(uint32_t accessFlags) {
1447 accessFlags &= kAccJavaFlagsMask;
1448 if ((accessFlags & kAccSynthetic) != 0) {
1449 accessFlags |= 0xf0000000;
1450 }
1451 return accessFlags;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001452}
1453
Elliott Hughesdbb40792011-11-18 17:05:22 -08001454/*
Jeff Haob7cefc72013-11-14 14:51:09 -08001455 * Circularly shifts registers so that arguments come first. Debuggers
1456 * expect slots to begin with arguments, but dex code places them at
1457 * the end.
Elliott Hughesdbb40792011-11-18 17:05:22 -08001458 */
Jeff Haob7cefc72013-11-14 14:51:09 -08001459static uint16_t MangleSlot(uint16_t slot, mirror::ArtMethod* m)
1460 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07001461 const DexFile::CodeItem* code_item = m->GetCodeItem();
Sebastien Hertzcb19ebf2014-03-11 15:26:35 +01001462 if (code_item == nullptr) {
1463 // We should not get here for a method without code (native, proxy or abstract). Log it and
1464 // return the slot as is since all registers are arguments.
1465 LOG(WARNING) << "Trying to mangle slot for method without code " << PrettyMethod(m);
1466 return slot;
1467 }
Jeff Haob7cefc72013-11-14 14:51:09 -08001468 uint16_t ins_size = code_item->ins_size_;
1469 uint16_t locals_size = code_item->registers_size_ - ins_size;
1470 if (slot >= locals_size) {
1471 return slot - locals_size;
1472 } else {
1473 return slot + ins_size;
Elliott Hughesdbb40792011-11-18 17:05:22 -08001474 }
Elliott Hughesdbb40792011-11-18 17:05:22 -08001475}
1476
Jeff Haob7cefc72013-11-14 14:51:09 -08001477/*
1478 * Circularly shifts registers so that arguments come last. Reverts
1479 * slots to dex style argument placement.
1480 */
Brian Carlstromea46f952013-07-30 01:26:50 -07001481static uint16_t DemangleSlot(uint16_t slot, mirror::ArtMethod* m)
Ian Rogersb726dcb2012-09-05 08:57:23 -07001482 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07001483 const DexFile::CodeItem* code_item = m->GetCodeItem();
Sebastien Hertzcb19ebf2014-03-11 15:26:35 +01001484 if (code_item == nullptr) {
1485 // We should not get here for a method without code (native, proxy or abstract). Log it and
1486 // return the slot as is since all registers are arguments.
1487 LOG(WARNING) << "Trying to demangle slot for method without code " << PrettyMethod(m);
1488 return slot;
1489 }
Jeff Haob7cefc72013-11-14 14:51:09 -08001490 uint16_t ins_size = code_item->ins_size_;
1491 uint16_t locals_size = code_item->registers_size_ - ins_size;
1492 if (slot < ins_size) {
1493 return slot + locals_size;
1494 } else {
1495 return slot - ins_size;
Elliott Hughesdbb40792011-11-18 17:05:22 -08001496 }
Elliott Hughesdbb40792011-11-18 17:05:22 -08001497}
1498
Elliott Hughes88d63092013-01-09 09:55:54 -08001499JDWP::JdwpError Dbg::OutputDeclaredFields(JDWP::RefTypeId class_id, bool with_generic, JDWP::ExpandBuf* pReply) {
Elliott Hughes436e3722012-02-17 20:01:47 -08001500 JDWP::JdwpError status;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001501 mirror::Class* c = DecodeClass(class_id, status);
Elliott Hughes436e3722012-02-17 20:01:47 -08001502 if (c == NULL) {
1503 return status;
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -08001504 }
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001505
1506 size_t instance_field_count = c->NumInstanceFields();
1507 size_t static_field_count = c->NumStaticFields();
1508
1509 expandBufAdd4BE(pReply, instance_field_count + static_field_count);
1510
1511 for (size_t i = 0; i < instance_field_count + static_field_count; ++i) {
Brian Carlstromea46f952013-07-30 01:26:50 -07001512 mirror::ArtField* f = (i < instance_field_count) ? c->GetInstanceField(i) : c->GetStaticField(i - instance_field_count);
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001513 expandBufAddFieldId(pReply, ToFieldId(f));
Mathieu Chartier61c5ebc2014-06-05 17:42:53 -07001514 expandBufAddUtf8String(pReply, f->GetName());
1515 expandBufAddUtf8String(pReply, f->GetTypeDescriptor());
Elliott Hughesc5b734a2011-12-01 17:20:58 -08001516 if (with_generic) {
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001517 static const char genericSignature[1] = "";
1518 expandBufAddUtf8String(pReply, genericSignature);
1519 }
1520 expandBufAdd4BE(pReply, MangleAccessFlags(f->GetAccessFlags()));
1521 }
Elliott Hughes436e3722012-02-17 20:01:47 -08001522 return JDWP::ERR_NONE;
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001523}
1524
Elliott Hughes88d63092013-01-09 09:55:54 -08001525JDWP::JdwpError Dbg::OutputDeclaredMethods(JDWP::RefTypeId class_id, bool with_generic,
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001526 JDWP::ExpandBuf* pReply) {
Elliott Hughes436e3722012-02-17 20:01:47 -08001527 JDWP::JdwpError status;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001528 mirror::Class* c = DecodeClass(class_id, status);
Elliott Hughes436e3722012-02-17 20:01:47 -08001529 if (c == NULL) {
1530 return status;
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -08001531 }
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001532
1533 size_t direct_method_count = c->NumDirectMethods();
1534 size_t virtual_method_count = c->NumVirtualMethods();
1535
1536 expandBufAdd4BE(pReply, direct_method_count + virtual_method_count);
1537
1538 for (size_t i = 0; i < direct_method_count + virtual_method_count; ++i) {
Brian Carlstromea46f952013-07-30 01:26:50 -07001539 mirror::ArtMethod* m = (i < direct_method_count) ? c->GetDirectMethod(i) : c->GetVirtualMethod(i - direct_method_count);
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001540 expandBufAddMethodId(pReply, ToMethodId(m));
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07001541 expandBufAddUtf8String(pReply, m->GetName());
1542 expandBufAddUtf8String(pReply, m->GetSignature().ToString());
Elliott Hughesc5b734a2011-12-01 17:20:58 -08001543 if (with_generic) {
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001544 static const char genericSignature[1] = "";
1545 expandBufAddUtf8String(pReply, genericSignature);
1546 }
1547 expandBufAdd4BE(pReply, MangleAccessFlags(m->GetAccessFlags()));
1548 }
Elliott Hughes436e3722012-02-17 20:01:47 -08001549 return JDWP::ERR_NONE;
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001550}
1551
Elliott Hughes88d63092013-01-09 09:55:54 -08001552JDWP::JdwpError Dbg::OutputDeclaredInterfaces(JDWP::RefTypeId class_id, JDWP::ExpandBuf* pReply) {
Elliott Hughes436e3722012-02-17 20:01:47 -08001553 JDWP::JdwpError status;
Mathieu Chartierf8322842014-05-16 10:59:25 -07001554 Thread* self = Thread::Current();
1555 StackHandleScope<1> hs(self);
1556 Handle<mirror::Class> c(hs.NewHandle(DecodeClass(class_id, status)));
1557 if (c.Get() == nullptr) {
Elliott Hughes436e3722012-02-17 20:01:47 -08001558 return status;
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -08001559 }
Mathieu Chartierf8322842014-05-16 10:59:25 -07001560 size_t interface_count = c->NumDirectInterfaces();
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001561 expandBufAdd4BE(pReply, interface_count);
1562 for (size_t i = 0; i < interface_count; ++i) {
Mathieu Chartierf8322842014-05-16 10:59:25 -07001563 expandBufAddRefTypeId(pReply,
1564 gRegistry->AddRefType(mirror::Class::GetDirectInterface(self, c, i)));
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001565 }
Elliott Hughes436e3722012-02-17 20:01:47 -08001566 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001567}
1568
Elliott Hughes88d63092013-01-09 09:55:54 -08001569void Dbg::OutputLineTable(JDWP::RefTypeId, JDWP::MethodId method_id, JDWP::ExpandBuf* pReply)
Ian Rogersb726dcb2012-09-05 08:57:23 -07001570 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Elliott Hughes03181a82011-11-17 17:22:21 -08001571 struct DebugCallbackContext {
1572 int numItems;
1573 JDWP::ExpandBuf* pReply;
1574
Elliott Hughes2435a572012-02-17 16:07:41 -08001575 static bool Callback(void* context, uint32_t address, uint32_t line_number) {
Elliott Hughes03181a82011-11-17 17:22:21 -08001576 DebugCallbackContext* pContext = reinterpret_cast<DebugCallbackContext*>(context);
1577 expandBufAdd8BE(pContext->pReply, address);
Elliott Hughes2435a572012-02-17 16:07:41 -08001578 expandBufAdd4BE(pContext->pReply, line_number);
Elliott Hughes03181a82011-11-17 17:22:21 -08001579 pContext->numItems++;
Sebastien Hertzf2910ee2013-10-19 16:39:24 +02001580 return false;
Elliott Hughes03181a82011-11-17 17:22:21 -08001581 }
1582 };
Brian Carlstromea46f952013-07-30 01:26:50 -07001583 mirror::ArtMethod* m = FromMethodId(method_id);
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07001584 const DexFile::CodeItem* code_item = m->GetCodeItem();
Elliott Hughes03181a82011-11-17 17:22:21 -08001585 uint64_t start, end;
Sebastien Hertzcb19ebf2014-03-11 15:26:35 +01001586 if (code_item == nullptr) {
1587 DCHECK(m->IsNative() || m->IsProxyMethod());
Elliott Hughes03181a82011-11-17 17:22:21 -08001588 start = -1;
1589 end = -1;
1590 } else {
1591 start = 0;
jeffhao14f0db92012-12-14 17:50:42 -08001592 // Return the index of the last instruction
Sebastien Hertzcb19ebf2014-03-11 15:26:35 +01001593 end = code_item->insns_size_in_code_units_ - 1;
Elliott Hughes03181a82011-11-17 17:22:21 -08001594 }
1595
1596 expandBufAdd8BE(pReply, start);
1597 expandBufAdd8BE(pReply, end);
1598
1599 // Add numLines later
1600 size_t numLinesOffset = expandBufGetLength(pReply);
1601 expandBufAdd4BE(pReply, 0);
1602
1603 DebugCallbackContext context;
1604 context.numItems = 0;
1605 context.pReply = pReply;
1606
Sebastien Hertzcb19ebf2014-03-11 15:26:35 +01001607 if (code_item != nullptr) {
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07001608 m->GetDexFile()->DecodeDebugInfo(code_item, m->IsStatic(), m->GetDexMethodIndex(),
1609 DebugCallbackContext::Callback, NULL, &context);
Sebastien Hertzcb19ebf2014-03-11 15:26:35 +01001610 }
Elliott Hughes03181a82011-11-17 17:22:21 -08001611
1612 JDWP::Set4BE(expandBufGetBuffer(pReply) + numLinesOffset, context.numItems);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001613}
1614
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07001615void Dbg::OutputVariableTable(JDWP::RefTypeId, JDWP::MethodId method_id, bool with_generic,
1616 JDWP::ExpandBuf* pReply) {
Elliott Hughesdbb40792011-11-18 17:05:22 -08001617 struct DebugCallbackContext {
Jeff Haob7cefc72013-11-14 14:51:09 -08001618 mirror::ArtMethod* method;
Elliott Hughesdbb40792011-11-18 17:05:22 -08001619 JDWP::ExpandBuf* pReply;
Elliott Hughesc5b734a2011-12-01 17:20:58 -08001620 size_t variable_count;
1621 bool with_generic;
Elliott Hughesdbb40792011-11-18 17:05:22 -08001622
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07001623 static void Callback(void* context, uint16_t slot, uint32_t startAddress, uint32_t endAddress,
1624 const char* name, const char* descriptor, const char* signature)
Jeff Haob7cefc72013-11-14 14:51:09 -08001625 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Elliott Hughesdbb40792011-11-18 17:05:22 -08001626 DebugCallbackContext* pContext = reinterpret_cast<DebugCallbackContext*>(context);
1627
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07001628 VLOG(jdwp) << StringPrintf(" %2zd: %d(%d) '%s' '%s' '%s' actual slot=%d mangled slot=%d",
1629 pContext->variable_count, startAddress, endAddress - startAddress,
1630 name, descriptor, signature, slot,
1631 MangleSlot(slot, pContext->method));
Elliott Hughesdbb40792011-11-18 17:05:22 -08001632
Jeff Haob7cefc72013-11-14 14:51:09 -08001633 slot = MangleSlot(slot, pContext->method);
Elliott Hughes68fdbd02011-11-29 19:22:47 -08001634
Elliott Hughesdbb40792011-11-18 17:05:22 -08001635 expandBufAdd8BE(pContext->pReply, startAddress);
1636 expandBufAddUtf8String(pContext->pReply, name);
1637 expandBufAddUtf8String(pContext->pReply, descriptor);
Elliott Hughesc5b734a2011-12-01 17:20:58 -08001638 if (pContext->with_generic) {
Elliott Hughesdbb40792011-11-18 17:05:22 -08001639 expandBufAddUtf8String(pContext->pReply, signature);
1640 }
1641 expandBufAdd4BE(pContext->pReply, endAddress - startAddress);
1642 expandBufAdd4BE(pContext->pReply, slot);
1643
Elliott Hughesc5b734a2011-12-01 17:20:58 -08001644 ++pContext->variable_count;
Elliott Hughesdbb40792011-11-18 17:05:22 -08001645 }
1646 };
Brian Carlstromea46f952013-07-30 01:26:50 -07001647 mirror::ArtMethod* m = FromMethodId(method_id);
Elliott Hughesdbb40792011-11-18 17:05:22 -08001648
Elliott Hughesc5b734a2011-12-01 17:20:58 -08001649 // arg_count considers doubles and longs to take 2 units.
1650 // variable_count considers everything to take 1 unit.
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07001651 std::string shorty(m->GetShorty());
Brian Carlstromea46f952013-07-30 01:26:50 -07001652 expandBufAdd4BE(pReply, mirror::ArtMethod::NumArgRegisters(shorty));
Elliott Hughesdbb40792011-11-18 17:05:22 -08001653
Elliott Hughesc5b734a2011-12-01 17:20:58 -08001654 // We don't know the total number of variables yet, so leave a blank and update it later.
1655 size_t variable_count_offset = expandBufGetLength(pReply);
Elliott Hughesdbb40792011-11-18 17:05:22 -08001656 expandBufAdd4BE(pReply, 0);
1657
1658 DebugCallbackContext context;
Jeff Haob7cefc72013-11-14 14:51:09 -08001659 context.method = m;
Elliott Hughesdbb40792011-11-18 17:05:22 -08001660 context.pReply = pReply;
Elliott Hughesc5b734a2011-12-01 17:20:58 -08001661 context.variable_count = 0;
1662 context.with_generic = with_generic;
Elliott Hughesdbb40792011-11-18 17:05:22 -08001663
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07001664 const DexFile::CodeItem* code_item = m->GetCodeItem();
Sebastien Hertzcb19ebf2014-03-11 15:26:35 +01001665 if (code_item != nullptr) {
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07001666 m->GetDexFile()->DecodeDebugInfo(
1667 code_item, m->IsStatic(), m->GetDexMethodIndex(), NULL, DebugCallbackContext::Callback,
1668 &context);
Sebastien Hertzcb19ebf2014-03-11 15:26:35 +01001669 }
Elliott Hughesdbb40792011-11-18 17:05:22 -08001670
Elliott Hughesc5b734a2011-12-01 17:20:58 -08001671 JDWP::Set4BE(expandBufGetBuffer(pReply) + variable_count_offset, context.variable_count);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001672}
1673
Jeff Hao579b0242013-11-18 13:16:49 -08001674void Dbg::OutputMethodReturnValue(JDWP::MethodId method_id, const JValue* return_value,
1675 JDWP::ExpandBuf* pReply) {
1676 mirror::ArtMethod* m = FromMethodId(method_id);
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07001677 JDWP::JdwpTag tag = BasicTagFromDescriptor(m->GetShorty());
Jeff Hao579b0242013-11-18 13:16:49 -08001678 OutputJValue(tag, return_value, pReply);
1679}
1680
Sebastien Hertz3f52eaf2014-04-04 17:50:18 +02001681void Dbg::OutputFieldValue(JDWP::FieldId field_id, const JValue* field_value,
1682 JDWP::ExpandBuf* pReply) {
1683 mirror::ArtField* f = FromFieldId(field_id);
Mathieu Chartier61c5ebc2014-06-05 17:42:53 -07001684 JDWP::JdwpTag tag = BasicTagFromDescriptor(f->GetTypeDescriptor());
Sebastien Hertz3f52eaf2014-04-04 17:50:18 +02001685 OutputJValue(tag, field_value, pReply);
1686}
1687
Elliott Hughes9777ba22013-01-17 09:04:19 -08001688JDWP::JdwpError Dbg::GetBytecodes(JDWP::RefTypeId, JDWP::MethodId method_id,
1689 std::vector<uint8_t>& bytecodes)
1690 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Brian Carlstromea46f952013-07-30 01:26:50 -07001691 mirror::ArtMethod* m = FromMethodId(method_id);
Elliott Hughes9777ba22013-01-17 09:04:19 -08001692 if (m == NULL) {
1693 return JDWP::ERR_INVALID_METHODID;
1694 }
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07001695 const DexFile::CodeItem* code_item = m->GetCodeItem();
Elliott Hughes9777ba22013-01-17 09:04:19 -08001696 size_t byte_count = code_item->insns_size_in_code_units_ * 2;
1697 const uint8_t* begin = reinterpret_cast<const uint8_t*>(code_item->insns_);
1698 const uint8_t* end = begin + byte_count;
1699 for (const uint8_t* p = begin; p != end; ++p) {
1700 bytecodes.push_back(*p);
1701 }
1702 return JDWP::ERR_NONE;
1703}
1704
Elliott Hughes88d63092013-01-09 09:55:54 -08001705JDWP::JdwpTag Dbg::GetFieldBasicTag(JDWP::FieldId field_id) {
Mathieu Chartier61c5ebc2014-06-05 17:42:53 -07001706 return BasicTagFromDescriptor(FromFieldId(field_id)->GetTypeDescriptor());
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001707}
1708
Elliott Hughes88d63092013-01-09 09:55:54 -08001709JDWP::JdwpTag Dbg::GetStaticFieldBasicTag(JDWP::FieldId field_id) {
Mathieu Chartier61c5ebc2014-06-05 17:42:53 -07001710 return BasicTagFromDescriptor(FromFieldId(field_id)->GetTypeDescriptor());
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001711}
1712
Elliott Hughes88d63092013-01-09 09:55:54 -08001713static JDWP::JdwpError GetFieldValueImpl(JDWP::RefTypeId ref_type_id, JDWP::ObjectId object_id,
1714 JDWP::FieldId field_id, JDWP::ExpandBuf* pReply,
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001715 bool is_static)
Ian Rogersb726dcb2012-09-05 08:57:23 -07001716 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Elliott Hughes0cf74332012-02-23 23:14:00 -08001717 JDWP::JdwpError status;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001718 mirror::Class* c = DecodeClass(ref_type_id, status);
Elliott Hughes88d63092013-01-09 09:55:54 -08001719 if (ref_type_id != 0 && c == NULL) {
Elliott Hughes0cf74332012-02-23 23:14:00 -08001720 return status;
1721 }
1722
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001723 mirror::Object* o = gRegistry->Get<mirror::Object*>(object_id);
Elliott Hughes64f574f2013-02-20 14:57:12 -08001724 if ((!is_static && o == NULL) || o == ObjectRegistry::kInvalidObject) {
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08001725 return JDWP::ERR_INVALID_OBJECT;
1726 }
Brian Carlstromea46f952013-07-30 01:26:50 -07001727 mirror::ArtField* f = FromFieldId(field_id);
Elliott Hughes0cf74332012-02-23 23:14:00 -08001728
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001729 mirror::Class* receiver_class = c;
Elliott Hughes0cf74332012-02-23 23:14:00 -08001730 if (receiver_class == NULL && o != NULL) {
1731 receiver_class = o->GetClass();
1732 }
1733 // TODO: should we give up now if receiver_class is NULL?
1734 if (receiver_class != NULL && !f->GetDeclaringClass()->IsAssignableFrom(receiver_class)) {
1735 LOG(INFO) << "ERR_INVALID_FIELDID: " << PrettyField(f) << " " << PrettyClass(receiver_class);
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08001736 return JDWP::ERR_INVALID_FIELDID;
1737 }
Elliott Hughesaed4be92011-12-02 16:16:23 -08001738
Elliott Hughes0cf74332012-02-23 23:14:00 -08001739 // The RI only enforces the static/non-static mismatch in one direction.
1740 // TODO: should we change the tests and check both?
1741 if (is_static) {
1742 if (!f->IsStatic()) {
1743 return JDWP::ERR_INVALID_FIELDID;
1744 }
1745 } else {
1746 if (f->IsStatic()) {
1747 LOG(WARNING) << "Ignoring non-NULL receiver for ObjectReference.SetValues on static field " << PrettyField(f);
Elliott Hughes0cf74332012-02-23 23:14:00 -08001748 }
1749 }
jeffhao0dfbb7e2012-11-28 15:26:03 -08001750 if (f->IsStatic()) {
1751 o = f->GetDeclaringClass();
1752 }
Elliott Hughes0cf74332012-02-23 23:14:00 -08001753
Mathieu Chartier61c5ebc2014-06-05 17:42:53 -07001754 JDWP::JdwpTag tag = BasicTagFromDescriptor(f->GetTypeDescriptor());
Jeff Hao579b0242013-11-18 13:16:49 -08001755 JValue field_value;
1756 if (tag == JDWP::JT_VOID) {
1757 LOG(FATAL) << "Unknown tag: " << tag;
1758 } else if (!IsPrimitiveTag(tag)) {
1759 field_value.SetL(f->GetObject(o));
1760 } else if (tag == JDWP::JT_DOUBLE || tag == JDWP::JT_LONG) {
1761 field_value.SetJ(f->Get64(o));
Elliott Hughesaed4be92011-12-02 16:16:23 -08001762 } else {
Jeff Hao579b0242013-11-18 13:16:49 -08001763 field_value.SetI(f->Get32(o));
Elliott Hughesaed4be92011-12-02 16:16:23 -08001764 }
Jeff Hao579b0242013-11-18 13:16:49 -08001765 Dbg::OutputJValue(tag, &field_value, pReply);
1766
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08001767 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001768}
1769
Elliott Hughes88d63092013-01-09 09:55:54 -08001770JDWP::JdwpError Dbg::GetFieldValue(JDWP::ObjectId object_id, JDWP::FieldId field_id,
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001771 JDWP::ExpandBuf* pReply) {
Elliott Hughes88d63092013-01-09 09:55:54 -08001772 return GetFieldValueImpl(0, object_id, field_id, pReply, false);
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08001773}
1774
Elliott Hughes88d63092013-01-09 09:55:54 -08001775JDWP::JdwpError Dbg::GetStaticFieldValue(JDWP::RefTypeId ref_type_id, JDWP::FieldId field_id, JDWP::ExpandBuf* pReply) {
1776 return GetFieldValueImpl(ref_type_id, 0, field_id, pReply, true);
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08001777}
1778
Elliott Hughes88d63092013-01-09 09:55:54 -08001779static JDWP::JdwpError SetFieldValueImpl(JDWP::ObjectId object_id, JDWP::FieldId field_id,
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001780 uint64_t value, int width, bool is_static)
Ian Rogersb726dcb2012-09-05 08:57:23 -07001781 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001782 mirror::Object* o = gRegistry->Get<mirror::Object*>(object_id);
Elliott Hughes64f574f2013-02-20 14:57:12 -08001783 if ((!is_static && o == NULL) || o == ObjectRegistry::kInvalidObject) {
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08001784 return JDWP::ERR_INVALID_OBJECT;
1785 }
Brian Carlstromea46f952013-07-30 01:26:50 -07001786 mirror::ArtField* f = FromFieldId(field_id);
Elliott Hughes0cf74332012-02-23 23:14:00 -08001787
1788 // The RI only enforces the static/non-static mismatch in one direction.
1789 // TODO: should we change the tests and check both?
1790 if (is_static) {
1791 if (!f->IsStatic()) {
1792 return JDWP::ERR_INVALID_FIELDID;
1793 }
1794 } else {
1795 if (f->IsStatic()) {
1796 LOG(WARNING) << "Ignoring non-NULL receiver for ObjectReference.SetValues on static field " << PrettyField(f);
Elliott Hughes0cf74332012-02-23 23:14:00 -08001797 }
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08001798 }
jeffhao0dfbb7e2012-11-28 15:26:03 -08001799 if (f->IsStatic()) {
1800 o = f->GetDeclaringClass();
1801 }
Elliott Hughesaed4be92011-12-02 16:16:23 -08001802
Mathieu Chartier61c5ebc2014-06-05 17:42:53 -07001803 JDWP::JdwpTag tag = BasicTagFromDescriptor(f->GetTypeDescriptor());
Elliott Hughesaed4be92011-12-02 16:16:23 -08001804
1805 if (IsPrimitiveTag(tag)) {
1806 if (tag == JDWP::JT_DOUBLE || tag == JDWP::JT_LONG) {
Elliott Hughes1bac54f2012-03-16 12:48:31 -07001807 CHECK_EQ(width, 8);
Sebastien Hertzd2fe10a2014-01-15 10:20:56 +01001808 // Debugging can't use transactional mode (runtime only).
1809 f->Set64<false>(o, value);
Elliott Hughesaed4be92011-12-02 16:16:23 -08001810 } else {
Elliott Hughes1bac54f2012-03-16 12:48:31 -07001811 CHECK_LE(width, 4);
Sebastien Hertzd2fe10a2014-01-15 10:20:56 +01001812 // Debugging can't use transactional mode (runtime only).
1813 f->Set32<false>(o, value);
Elliott Hughesaed4be92011-12-02 16:16:23 -08001814 }
1815 } else {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001816 mirror::Object* v = gRegistry->Get<mirror::Object*>(value);
Elliott Hughes64f574f2013-02-20 14:57:12 -08001817 if (v == ObjectRegistry::kInvalidObject) {
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -08001818 return JDWP::ERR_INVALID_OBJECT;
1819 }
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08001820 if (v != NULL) {
Mathieu Chartier61c5ebc2014-06-05 17:42:53 -07001821 mirror::Class* field_type;
1822 {
1823 StackHandleScope<3> hs(Thread::Current());
1824 HandleWrapper<mirror::Object> h_v(hs.NewHandleWrapper(&v));
1825 HandleWrapper<mirror::ArtField> h_f(hs.NewHandleWrapper(&f));
1826 HandleWrapper<mirror::Object> h_o(hs.NewHandleWrapper(&o));
1827 field_type = FieldHelper(h_f).GetType();
1828 }
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08001829 if (!field_type->IsAssignableFrom(v->GetClass())) {
1830 return JDWP::ERR_INVALID_OBJECT;
1831 }
1832 }
Sebastien Hertzd2fe10a2014-01-15 10:20:56 +01001833 // Debugging can't use transactional mode (runtime only).
1834 f->SetObject<false>(o, v);
Elliott Hughesaed4be92011-12-02 16:16:23 -08001835 }
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -08001836
1837 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001838}
1839
Elliott Hughes88d63092013-01-09 09:55:54 -08001840JDWP::JdwpError Dbg::SetFieldValue(JDWP::ObjectId object_id, JDWP::FieldId field_id, uint64_t value,
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001841 int width) {
Elliott Hughes88d63092013-01-09 09:55:54 -08001842 return SetFieldValueImpl(object_id, field_id, value, width, false);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001843}
1844
Elliott Hughes88d63092013-01-09 09:55:54 -08001845JDWP::JdwpError Dbg::SetStaticFieldValue(JDWP::FieldId field_id, uint64_t value, int width) {
1846 return SetFieldValueImpl(0, field_id, value, width, true);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001847}
1848
Elliott Hughes88d63092013-01-09 09:55:54 -08001849std::string Dbg::StringToUtf8(JDWP::ObjectId string_id) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001850 mirror::String* s = gRegistry->Get<mirror::String*>(string_id);
Elliott Hughes68fdbd02011-11-29 19:22:47 -08001851 return s->ToModifiedUtf8();
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001852}
1853
Jeff Hao579b0242013-11-18 13:16:49 -08001854void Dbg::OutputJValue(JDWP::JdwpTag tag, const JValue* return_value, JDWP::ExpandBuf* pReply) {
1855 if (IsPrimitiveTag(tag)) {
1856 expandBufAdd1(pReply, tag);
1857 if (tag == JDWP::JT_BOOLEAN || tag == JDWP::JT_BYTE) {
1858 expandBufAdd1(pReply, return_value->GetI());
1859 } else if (tag == JDWP::JT_CHAR || tag == JDWP::JT_SHORT) {
1860 expandBufAdd2BE(pReply, return_value->GetI());
1861 } else if (tag == JDWP::JT_FLOAT || tag == JDWP::JT_INT) {
1862 expandBufAdd4BE(pReply, return_value->GetI());
1863 } else if (tag == JDWP::JT_DOUBLE || tag == JDWP::JT_LONG) {
1864 expandBufAdd8BE(pReply, return_value->GetJ());
1865 } else {
1866 CHECK_EQ(tag, JDWP::JT_VOID);
1867 }
1868 } else {
Ian Rogers98379392014-02-24 16:53:16 -08001869 ScopedObjectAccessUnchecked soa(Thread::Current());
Jeff Hao579b0242013-11-18 13:16:49 -08001870 mirror::Object* value = return_value->GetL();
Ian Rogers98379392014-02-24 16:53:16 -08001871 expandBufAdd1(pReply, TagFromObject(soa, value));
Jeff Hao579b0242013-11-18 13:16:49 -08001872 expandBufAddObjectId(pReply, gRegistry->Add(value));
1873 }
1874}
1875
Elliott Hughes221229c2013-01-08 18:17:50 -08001876JDWP::JdwpError Dbg::GetThreadName(JDWP::ObjectId thread_id, std::string& name) {
jeffhaoa77f0f62012-12-05 17:19:31 -08001877 ScopedObjectAccessUnchecked soa(Thread::Current());
1878 MutexLock mu(soa.Self(), *Locks::thread_list_lock_);
Elliott Hughes221229c2013-01-08 18:17:50 -08001879 Thread* thread;
1880 JDWP::JdwpError error = DecodeThread(soa, thread_id, thread);
1881 if (error != JDWP::ERR_NONE && error != JDWP::ERR_THREAD_NOT_ALIVE) {
1882 return error;
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001883 }
Elliott Hughes221229c2013-01-08 18:17:50 -08001884
1885 // We still need to report the zombie threads' names, so we can't just call Thread::GetThreadName.
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001886 mirror::Object* thread_object = gRegistry->Get<mirror::Object*>(thread_id);
Brian Carlstromea46f952013-07-30 01:26:50 -07001887 mirror::ArtField* java_lang_Thread_name_field =
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001888 soa.DecodeField(WellKnownClasses::java_lang_Thread_name);
1889 mirror::String* s =
1890 reinterpret_cast<mirror::String*>(java_lang_Thread_name_field->GetObject(thread_object));
Elliott Hughes221229c2013-01-08 18:17:50 -08001891 if (s != NULL) {
1892 name = s->ToModifiedUtf8();
1893 }
1894 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001895}
1896
Elliott Hughes221229c2013-01-08 18:17:50 -08001897JDWP::JdwpError Dbg::GetThreadGroup(JDWP::ObjectId thread_id, JDWP::ExpandBuf* pReply) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001898 ScopedObjectAccess soa(Thread::Current());
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001899 mirror::Object* thread_object = gRegistry->Get<mirror::Object*>(thread_id);
Elliott Hughes64f574f2013-02-20 14:57:12 -08001900 if (thread_object == ObjectRegistry::kInvalidObject) {
Elliott Hughes2435a572012-02-17 16:07:41 -08001901 return JDWP::ERR_INVALID_OBJECT;
1902 }
Ian Rogers98379392014-02-24 16:53:16 -08001903 const char* old_cause = soa.Self()->StartAssertNoThreadSuspension("Debugger: GetThreadGroup");
Elliott Hughes2435a572012-02-17 16:07:41 -08001904 // Okay, so it's an object, but is it actually a thread?
Hiroshi Yamauchib5a9e3d2014-06-09 12:11:20 -07001905 JDWP::JdwpError error;
1906 {
1907 MutexLock mu(soa.Self(), *Locks::thread_list_lock_);
1908 Thread* thread;
1909 error = DecodeThread(soa, thread_id, thread);
1910 }
Elliott Hughes221229c2013-01-08 18:17:50 -08001911 if (error == JDWP::ERR_THREAD_NOT_ALIVE) {
1912 // Zombie threads are in the null group.
1913 expandBufAddObjectId(pReply, JDWP::ObjectId(0));
Sebastien Hertz52d131d2014-03-13 16:17:40 +01001914 error = JDWP::ERR_NONE;
1915 } else if (error == JDWP::ERR_NONE) {
1916 mirror::Class* c = soa.Decode<mirror::Class*>(WellKnownClasses::java_lang_Thread);
1917 CHECK(c != nullptr);
1918 mirror::ArtField* f = c->FindInstanceField("group", "Ljava/lang/ThreadGroup;");
Hiroshi Yamauchib5a9e3d2014-06-09 12:11:20 -07001919 CHECK(f != nullptr);
Sebastien Hertz52d131d2014-03-13 16:17:40 +01001920 mirror::Object* group = f->GetObject(thread_object);
Hiroshi Yamauchib5a9e3d2014-06-09 12:11:20 -07001921 CHECK(group != nullptr);
Sebastien Hertz52d131d2014-03-13 16:17:40 +01001922 JDWP::ObjectId thread_group_id = gRegistry->Add(group);
1923 expandBufAddObjectId(pReply, thread_group_id);
Elliott Hughes221229c2013-01-08 18:17:50 -08001924 }
Ian Rogers98379392014-02-24 16:53:16 -08001925 soa.Self()->EndAssertNoThreadSuspension(old_cause);
Sebastien Hertz52d131d2014-03-13 16:17:40 +01001926 return error;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001927}
1928
Elliott Hughes88d63092013-01-09 09:55:54 -08001929std::string Dbg::GetThreadGroupName(JDWP::ObjectId thread_group_id) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001930 ScopedObjectAccess soa(Thread::Current());
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001931 mirror::Object* thread_group = gRegistry->Get<mirror::Object*>(thread_group_id);
Ian Rogers98379392014-02-24 16:53:16 -08001932 CHECK(thread_group != nullptr);
1933 const char* old_cause = soa.Self()->StartAssertNoThreadSuspension("Debugger: GetThreadGroupName");
1934 mirror::Class* c = soa.Decode<mirror::Class*>(WellKnownClasses::java_lang_ThreadGroup);
1935 CHECK(c != nullptr);
Brian Carlstromea46f952013-07-30 01:26:50 -07001936 mirror::ArtField* f = c->FindInstanceField("name", "Ljava/lang/String;");
Elliott Hughes499c5132011-11-17 14:55:11 -08001937 CHECK(f != NULL);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001938 mirror::String* s = reinterpret_cast<mirror::String*>(f->GetObject(thread_group));
Ian Rogers98379392014-02-24 16:53:16 -08001939 soa.Self()->EndAssertNoThreadSuspension(old_cause);
Elliott Hughes499c5132011-11-17 14:55:11 -08001940 return s->ToModifiedUtf8();
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001941}
1942
Elliott Hughes88d63092013-01-09 09:55:54 -08001943JDWP::ObjectId Dbg::GetThreadGroupParent(JDWP::ObjectId thread_group_id) {
Ian Rogers98379392014-02-24 16:53:16 -08001944 ScopedObjectAccessUnchecked soa(Thread::Current());
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001945 mirror::Object* thread_group = gRegistry->Get<mirror::Object*>(thread_group_id);
Ian Rogers98379392014-02-24 16:53:16 -08001946 CHECK(thread_group != nullptr);
1947 const char* old_cause = soa.Self()->StartAssertNoThreadSuspension("Debugger: GetThreadGroupParent");
1948 mirror::Class* c = soa.Decode<mirror::Class*>(WellKnownClasses::java_lang_ThreadGroup);
1949 CHECK(c != nullptr);
Brian Carlstromea46f952013-07-30 01:26:50 -07001950 mirror::ArtField* f = c->FindInstanceField("parent", "Ljava/lang/ThreadGroup;");
Elliott Hughes4e235312011-12-02 11:34:15 -08001951 CHECK(f != NULL);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001952 mirror::Object* parent = f->GetObject(thread_group);
Ian Rogers98379392014-02-24 16:53:16 -08001953 soa.Self()->EndAssertNoThreadSuspension(old_cause);
Elliott Hughes4e235312011-12-02 11:34:15 -08001954 return gRegistry->Add(parent);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001955}
1956
1957JDWP::ObjectId Dbg::GetSystemThreadGroupId() {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001958 ScopedObjectAccessUnchecked soa(Thread::Current());
Brian Carlstromea46f952013-07-30 01:26:50 -07001959 mirror::ArtField* f = soa.DecodeField(WellKnownClasses::java_lang_ThreadGroup_systemThreadGroup);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001960 mirror::Object* group = f->GetObject(f->GetDeclaringClass());
Ian Rogers365c1022012-06-22 15:05:28 -07001961 return gRegistry->Add(group);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001962}
1963
1964JDWP::ObjectId Dbg::GetMainThreadGroupId() {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001965 ScopedObjectAccess soa(Thread::Current());
Brian Carlstromea46f952013-07-30 01:26:50 -07001966 mirror::ArtField* f = soa.DecodeField(WellKnownClasses::java_lang_ThreadGroup_mainThreadGroup);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001967 mirror::Object* group = f->GetObject(f->GetDeclaringClass());
Ian Rogers365c1022012-06-22 15:05:28 -07001968 return gRegistry->Add(group);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001969}
1970
Jeff Hao920af3e2013-08-28 15:46:38 -07001971JDWP::JdwpThreadStatus Dbg::ToJdwpThreadStatus(ThreadState state) {
1972 switch (state) {
1973 case kBlocked:
1974 return JDWP::TS_MONITOR;
1975 case kNative:
1976 case kRunnable:
1977 case kSuspended:
1978 return JDWP::TS_RUNNING;
1979 case kSleeping:
1980 return JDWP::TS_SLEEPING;
1981 case kStarting:
1982 case kTerminated:
1983 return JDWP::TS_ZOMBIE;
1984 case kTimedWaiting:
1985 case kWaitingForDebuggerSend:
1986 case kWaitingForDebuggerSuspension:
1987 case kWaitingForDebuggerToAttach:
Sebastien Hertz138dbfc2013-12-04 18:15:25 +01001988 case kWaitingForDeoptimization:
Jeff Hao920af3e2013-08-28 15:46:38 -07001989 case kWaitingForGcToComplete:
1990 case kWaitingForCheckPointsToRun:
1991 case kWaitingForJniOnLoad:
1992 case kWaitingForSignalCatcherOutput:
1993 case kWaitingInMainDebuggerLoop:
1994 case kWaitingInMainSignalCatcherLoop:
1995 case kWaitingPerformingGc:
1996 case kWaiting:
1997 return JDWP::TS_WAIT;
1998 // Don't add a 'default' here so the compiler can spot incompatible enum changes.
1999 }
2000 LOG(FATAL) << "Unknown thread state: " << state;
2001 return JDWP::TS_ZOMBIE;
2002}
2003
Sebastien Hertz52d131d2014-03-13 16:17:40 +01002004JDWP::JdwpError Dbg::GetThreadStatus(JDWP::ObjectId thread_id, JDWP::JdwpThreadStatus* pThreadStatus,
2005 JDWP::JdwpSuspendStatus* pSuspendStatus) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002006 ScopedObjectAccess soa(Thread::Current());
Elliott Hughes499c5132011-11-17 14:55:11 -08002007
Elliott Hughes9e0c1752013-01-09 14:02:58 -08002008 *pSuspendStatus = JDWP::SUSPEND_STATUS_NOT_SUSPENDED;
2009
Ian Rogers50b35e22012-10-04 10:09:15 -07002010 MutexLock mu(soa.Self(), *Locks::thread_list_lock_);
Elliott Hughes221229c2013-01-08 18:17:50 -08002011 Thread* thread;
2012 JDWP::JdwpError error = DecodeThread(soa, thread_id, thread);
2013 if (error != JDWP::ERR_NONE) {
2014 if (error == JDWP::ERR_THREAD_NOT_ALIVE) {
2015 *pThreadStatus = JDWP::TS_ZOMBIE;
Elliott Hughes221229c2013-01-08 18:17:50 -08002016 return JDWP::ERR_NONE;
2017 }
2018 return error;
Elliott Hughes499c5132011-11-17 14:55:11 -08002019 }
2020
Elliott Hughes9e0c1752013-01-09 14:02:58 -08002021 if (IsSuspendedForDebugger(soa, thread)) {
2022 *pSuspendStatus = JDWP::SUSPEND_STATUS_SUSPENDED;
Elliott Hughes499c5132011-11-17 14:55:11 -08002023 }
2024
Jeff Hao920af3e2013-08-28 15:46:38 -07002025 *pThreadStatus = ToJdwpThreadStatus(thread->GetState());
Elliott Hughes221229c2013-01-08 18:17:50 -08002026 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002027}
2028
Elliott Hughes221229c2013-01-08 18:17:50 -08002029JDWP::JdwpError Dbg::GetThreadDebugSuspendCount(JDWP::ObjectId thread_id, JDWP::ExpandBuf* pReply) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002030 ScopedObjectAccess soa(Thread::Current());
Ian Rogers50b35e22012-10-04 10:09:15 -07002031 MutexLock mu(soa.Self(), *Locks::thread_list_lock_);
Elliott Hughes221229c2013-01-08 18:17:50 -08002032 Thread* thread;
2033 JDWP::JdwpError error = DecodeThread(soa, thread_id, thread);
2034 if (error != JDWP::ERR_NONE) {
2035 return error;
Elliott Hughes2435a572012-02-17 16:07:41 -08002036 }
Ian Rogers50b35e22012-10-04 10:09:15 -07002037 MutexLock mu2(soa.Self(), *Locks::thread_suspend_count_lock_);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002038 expandBufAdd4BE(pReply, thread->GetDebugSuspendCount());
Elliott Hughes2435a572012-02-17 16:07:41 -08002039 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002040}
2041
Elliott Hughesf9501702013-01-11 11:22:27 -08002042JDWP::JdwpError Dbg::Interrupt(JDWP::ObjectId thread_id) {
2043 ScopedObjectAccess soa(Thread::Current());
2044 MutexLock mu(soa.Self(), *Locks::thread_list_lock_);
2045 Thread* thread;
2046 JDWP::JdwpError error = DecodeThread(soa, thread_id, thread);
2047 if (error != JDWP::ERR_NONE) {
2048 return error;
2049 }
Ian Rogersdd7624d2014-03-14 17:43:00 -07002050 thread->Interrupt(soa.Self());
Elliott Hughesf9501702013-01-11 11:22:27 -08002051 return JDWP::ERR_NONE;
2052}
2053
Elliott Hughescaf76542012-06-28 16:08:22 -07002054void Dbg::GetThreads(JDWP::ObjectId thread_group_id, std::vector<JDWP::ObjectId>& thread_ids) {
Ian Rogers365c1022012-06-22 15:05:28 -07002055 class ThreadListVisitor {
2056 public:
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002057 ThreadListVisitor(const ScopedObjectAccessUnchecked& soa, mirror::Object* desired_thread_group,
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002058 std::vector<JDWP::ObjectId>& thread_ids)
Ian Rogersb726dcb2012-09-05 08:57:23 -07002059 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_)
jeffhao0dfbb7e2012-11-28 15:26:03 -08002060 : soa_(soa), desired_thread_group_(desired_thread_group), thread_ids_(thread_ids) {}
Ian Rogers365c1022012-06-22 15:05:28 -07002061
Elliott Hughesa2155262011-11-16 16:26:58 -08002062 static void Visit(Thread* t, void* arg) {
2063 reinterpret_cast<ThreadListVisitor*>(arg)->Visit(t);
2064 }
2065
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002066 // TODO: Enable annotalysis. We know lock is held in constructor, but abstraction confuses
2067 // annotalysis.
2068 void Visit(Thread* t) NO_THREAD_SAFETY_ANALYSIS {
Elliott Hughesa2155262011-11-16 16:26:58 -08002069 if (t == Dbg::GetDebugThread()) {
2070 // Skip the JDWP thread. Some debuggers get bent out of shape when they can't suspend and
2071 // query all threads, so it's easier if we just don't tell them about this thread.
2072 return;
2073 }
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002074 mirror::Object* peer = t->GetPeer();
jeffhao0dfbb7e2012-11-28 15:26:03 -08002075 if (IsInDesiredThreadGroup(peer)) {
Ian Rogers120f1c72012-09-28 17:17:10 -07002076 thread_ids_.push_back(gRegistry->Add(peer));
Elliott Hughesa2155262011-11-16 16:26:58 -08002077 }
2078 }
2079
Ian Rogers365c1022012-06-22 15:05:28 -07002080 private:
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002081 bool IsInDesiredThreadGroup(mirror::Object* peer)
jeffhao0dfbb7e2012-11-28 15:26:03 -08002082 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
jeffhao0dfbb7e2012-11-28 15:26:03 -08002083 // peer might be NULL if the thread is still starting up.
2084 if (peer == NULL) {
2085 // We can't tell the debugger about this thread yet.
2086 // TODO: if we identified threads to the debugger by their Thread*
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002087 // rather than their peer's mirror::Object*, we could fix this.
jeffhao0dfbb7e2012-11-28 15:26:03 -08002088 // Doing so might help us report ZOMBIE threads too.
2089 return false;
2090 }
jeffhaoc1e04902012-12-13 12:41:10 -08002091 // Do we want threads from all thread groups?
2092 if (desired_thread_group_ == NULL) {
2093 return true;
2094 }
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002095 mirror::Object* group = soa_.DecodeField(WellKnownClasses::java_lang_Thread_group)->GetObject(peer);
jeffhao0dfbb7e2012-11-28 15:26:03 -08002096 return (group == desired_thread_group_);
2097 }
2098
Mathieu Chartierdbe6f462012-09-25 16:54:50 -07002099 const ScopedObjectAccessUnchecked& soa_;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002100 mirror::Object* const desired_thread_group_;
Elliott Hughescaf76542012-06-28 16:08:22 -07002101 std::vector<JDWP::ObjectId>& thread_ids_;
Elliott Hughesa2155262011-11-16 16:26:58 -08002102 };
2103
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002104 ScopedObjectAccessUnchecked soa(Thread::Current());
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002105 mirror::Object* thread_group = gRegistry->Get<mirror::Object*>(thread_group_id);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002106 ThreadListVisitor tlv(soa, thread_group, thread_ids);
Ian Rogers50b35e22012-10-04 10:09:15 -07002107 MutexLock mu(soa.Self(), *Locks::thread_list_lock_);
Elliott Hughesf8349362012-06-18 15:00:06 -07002108 Runtime::Current()->GetThreadList()->ForEach(ThreadListVisitor::Visit, &tlv);
Elliott Hughescaf76542012-06-28 16:08:22 -07002109}
Elliott Hughesa2155262011-11-16 16:26:58 -08002110
Elliott Hughescaf76542012-06-28 16:08:22 -07002111void Dbg::GetChildThreadGroups(JDWP::ObjectId thread_group_id, std::vector<JDWP::ObjectId>& child_thread_group_ids) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002112 ScopedObjectAccess soa(Thread::Current());
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002113 mirror::Object* thread_group = gRegistry->Get<mirror::Object*>(thread_group_id);
Elliott Hughescaf76542012-06-28 16:08:22 -07002114
2115 // Get the ArrayList<ThreadGroup> "groups" out of this thread group...
Brian Carlstromea46f952013-07-30 01:26:50 -07002116 mirror::ArtField* groups_field = thread_group->GetClass()->FindInstanceField("groups", "Ljava/util/List;");
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002117 mirror::Object* groups_array_list = groups_field->GetObject(thread_group);
Elliott Hughescaf76542012-06-28 16:08:22 -07002118
2119 // Get the array and size out of the ArrayList<ThreadGroup>...
Brian Carlstromea46f952013-07-30 01:26:50 -07002120 mirror::ArtField* array_field = groups_array_list->GetClass()->FindInstanceField("array", "[Ljava/lang/Object;");
2121 mirror::ArtField* size_field = groups_array_list->GetClass()->FindInstanceField("size", "I");
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002122 mirror::ObjectArray<mirror::Object>* groups_array =
2123 array_field->GetObject(groups_array_list)->AsObjectArray<mirror::Object>();
Elliott Hughescaf76542012-06-28 16:08:22 -07002124 const int32_t size = size_field->GetInt(groups_array_list);
2125
2126 // Copy the first 'size' elements out of the array into the result.
2127 for (int32_t i = 0; i < size; ++i) {
2128 child_thread_group_ids.push_back(gRegistry->Add(groups_array->Get(i)));
Elliott Hughesa2155262011-11-16 16:26:58 -08002129 }
2130}
2131
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002132static int GetStackDepth(Thread* thread)
Ian Rogersb726dcb2012-09-05 08:57:23 -07002133 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Ian Rogers0399dde2012-06-06 17:09:28 -07002134 struct CountStackDepthVisitor : public StackVisitor {
Brian Carlstrom93ba8932013-07-17 21:31:49 -07002135 explicit CountStackDepthVisitor(Thread* thread)
Ian Rogers7a22fa62013-01-23 12:16:16 -08002136 : StackVisitor(thread, NULL), depth(0) {}
Ian Rogers0399dde2012-06-06 17:09:28 -07002137
Elliott Hughes64f574f2013-02-20 14:57:12 -08002138 // TODO: Enable annotalysis. We know lock is held in constructor, but abstraction confuses
2139 // annotalysis.
2140 bool VisitFrame() NO_THREAD_SAFETY_ANALYSIS {
Ian Rogers0399dde2012-06-06 17:09:28 -07002141 if (!GetMethod()->IsRuntimeMethod()) {
Elliott Hughesf8a2df72011-12-01 12:19:54 -08002142 ++depth;
2143 }
Elliott Hughes530fa002012-03-12 11:44:49 -07002144 return true;
Elliott Hughesa2e54f62011-11-17 13:01:30 -08002145 }
2146 size_t depth;
2147 };
Elliott Hughes08fc03a2012-06-26 17:34:00 -07002148
Ian Rogers7a22fa62013-01-23 12:16:16 -08002149 CountStackDepthVisitor visitor(thread);
Ian Rogers0399dde2012-06-06 17:09:28 -07002150 visitor.WalkStack();
Elliott Hughesa2e54f62011-11-17 13:01:30 -08002151 return visitor.depth;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002152}
2153
Elliott Hughes221229c2013-01-08 18:17:50 -08002154JDWP::JdwpError Dbg::GetThreadFrameCount(JDWP::ObjectId thread_id, size_t& result) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002155 ScopedObjectAccess soa(Thread::Current());
jeffhaoa77f0f62012-12-05 17:19:31 -08002156 MutexLock mu(soa.Self(), *Locks::thread_list_lock_);
Elliott Hughes221229c2013-01-08 18:17:50 -08002157 Thread* thread;
2158 JDWP::JdwpError error = DecodeThread(soa, thread_id, thread);
2159 if (error != JDWP::ERR_NONE) {
2160 return error;
2161 }
Elliott Hughesf15f4a02013-01-09 10:09:38 -08002162 if (!IsSuspendedForDebugger(soa, thread)) {
2163 return JDWP::ERR_THREAD_NOT_SUSPENDED;
2164 }
Elliott Hughes221229c2013-01-08 18:17:50 -08002165 result = GetStackDepth(thread);
2166 return JDWP::ERR_NONE;
Elliott Hughes86964332012-02-15 19:37:42 -08002167}
2168
Ian Rogers306057f2012-11-26 12:45:53 -08002169JDWP::JdwpError Dbg::GetThreadFrames(JDWP::ObjectId thread_id, size_t start_frame,
2170 size_t frame_count, JDWP::ExpandBuf* buf) {
Elliott Hughes6e9d22c2012-06-22 15:02:37 -07002171 class GetFrameVisitor : public StackVisitor {
2172 public:
Ian Rogers7a22fa62013-01-23 12:16:16 -08002173 GetFrameVisitor(Thread* thread, size_t start_frame, size_t frame_count, JDWP::ExpandBuf* buf)
Ian Rogersb726dcb2012-09-05 08:57:23 -07002174 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_)
Ian Rogers7a22fa62013-01-23 12:16:16 -08002175 : StackVisitor(thread, NULL), depth_(0),
Elliott Hughes6e9d22c2012-06-22 15:02:37 -07002176 start_frame_(start_frame), frame_count_(frame_count), buf_(buf) {
2177 expandBufAdd4BE(buf_, frame_count_);
Elliott Hughes03181a82011-11-17 17:22:21 -08002178 }
Ian Rogers0399dde2012-06-06 17:09:28 -07002179
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002180 // TODO: Enable annotalysis. We know lock is held in constructor, but abstraction confuses
2181 // annotalysis.
2182 virtual bool VisitFrame() NO_THREAD_SAFETY_ANALYSIS {
Ian Rogers0399dde2012-06-06 17:09:28 -07002183 if (GetMethod()->IsRuntimeMethod()) {
Brian Carlstrom7934ac22013-07-26 10:54:15 -07002184 return true; // The debugger can't do anything useful with a frame that has no Method*.
Elliott Hughes03181a82011-11-17 17:22:21 -08002185 }
Elliott Hughes6e9d22c2012-06-22 15:02:37 -07002186 if (depth_ >= start_frame_ + frame_count_) {
Elliott Hughes530fa002012-03-12 11:44:49 -07002187 return false;
Elliott Hughes03181a82011-11-17 17:22:21 -08002188 }
Elliott Hughes6e9d22c2012-06-22 15:02:37 -07002189 if (depth_ >= start_frame_) {
2190 JDWP::FrameId frame_id(GetFrameId());
2191 JDWP::JdwpLocation location;
2192 SetLocation(location, GetMethod(), GetDexPc());
Ian Rogersef7d42f2014-01-06 12:55:46 -08002193 VLOG(jdwp) << StringPrintf(" Frame %3zd: id=%3" PRIu64 " ", depth_, frame_id) << location;
Elliott Hughes6e9d22c2012-06-22 15:02:37 -07002194 expandBufAdd8BE(buf_, frame_id);
2195 expandBufAddLocation(buf_, location);
2196 }
2197 ++depth_;
Elliott Hughes530fa002012-03-12 11:44:49 -07002198 return true;
Elliott Hughes03181a82011-11-17 17:22:21 -08002199 }
Elliott Hughes6e9d22c2012-06-22 15:02:37 -07002200
2201 private:
2202 size_t depth_;
2203 const size_t start_frame_;
2204 const size_t frame_count_;
2205 JDWP::ExpandBuf* buf_;
Elliott Hughes03181a82011-11-17 17:22:21 -08002206 };
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002207
2208 ScopedObjectAccessUnchecked soa(Thread::Current());
jeffhaoa77f0f62012-12-05 17:19:31 -08002209 MutexLock mu(soa.Self(), *Locks::thread_list_lock_);
Elliott Hughes221229c2013-01-08 18:17:50 -08002210 Thread* thread;
2211 JDWP::JdwpError error = DecodeThread(soa, thread_id, thread);
2212 if (error != JDWP::ERR_NONE) {
2213 return error;
2214 }
Elliott Hughesf15f4a02013-01-09 10:09:38 -08002215 if (!IsSuspendedForDebugger(soa, thread)) {
2216 return JDWP::ERR_THREAD_NOT_SUSPENDED;
2217 }
Ian Rogers7a22fa62013-01-23 12:16:16 -08002218 GetFrameVisitor visitor(thread, start_frame, frame_count, buf);
Ian Rogers0399dde2012-06-06 17:09:28 -07002219 visitor.WalkStack();
Elliott Hughes6e9d22c2012-06-22 15:02:37 -07002220 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002221}
2222
2223JDWP::ObjectId Dbg::GetThreadSelfId() {
Mathieu Chartierdbe6f462012-09-25 16:54:50 -07002224 ScopedObjectAccessUnchecked soa(Thread::Current());
Ian Rogerscfaa4552012-11-26 21:00:08 -08002225 return gRegistry->Add(soa.Self()->GetPeer());
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002226}
2227
Elliott Hughes475fc232011-10-25 15:00:35 -07002228void Dbg::SuspendVM() {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002229 Runtime::Current()->GetThreadList()->SuspendAllForDebugger();
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002230}
2231
2232void Dbg::ResumeVM() {
Elliott Hughesc61a2672012-06-21 14:52:29 -07002233 Runtime::Current()->GetThreadList()->UndoDebuggerSuspensions();
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002234}
2235
Elliott Hughes221229c2013-01-08 18:17:50 -08002236JDWP::JdwpError Dbg::SuspendThread(JDWP::ObjectId thread_id, bool request_suspension) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002237 ScopedLocalRef<jobject> peer(Thread::Current()->GetJniEnv(), NULL);
2238 {
2239 ScopedObjectAccess soa(Thread::Current());
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002240 peer.reset(soa.AddLocalReference<jobject>(gRegistry->Get<mirror::Object*>(thread_id)));
Elliott Hughes4e235312011-12-02 11:34:15 -08002241 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002242 if (peer.get() == NULL) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002243 return JDWP::ERR_THREAD_NOT_ALIVE;
2244 }
2245 // Suspend thread to build stack trace.
Elliott Hughesf327e072013-01-09 16:01:26 -08002246 bool timed_out;
Ian Rogersd9c4fc92013-10-01 19:45:43 -07002247 Thread* thread = ThreadList::SuspendThreadByPeer(peer.get(), request_suspension, true,
2248 &timed_out);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002249 if (thread != NULL) {
2250 return JDWP::ERR_NONE;
Elliott Hughesf327e072013-01-09 16:01:26 -08002251 } else if (timed_out) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002252 return JDWP::ERR_INTERNAL;
2253 } else {
2254 return JDWP::ERR_THREAD_NOT_ALIVE;
2255 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002256}
2257
Elliott Hughes221229c2013-01-08 18:17:50 -08002258void Dbg::ResumeThread(JDWP::ObjectId thread_id) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002259 ScopedObjectAccessUnchecked soa(Thread::Current());
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002260 mirror::Object* peer = gRegistry->Get<mirror::Object*>(thread_id);
jeffhaoa77f0f62012-12-05 17:19:31 -08002261 Thread* thread;
2262 {
2263 MutexLock mu(soa.Self(), *Locks::thread_list_lock_);
2264 thread = Thread::FromManagedThread(soa, peer);
2265 }
Elliott Hughes4e235312011-12-02 11:34:15 -08002266 if (thread == NULL) {
2267 LOG(WARNING) << "No such thread for resume: " << peer;
2268 return;
2269 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002270 bool needs_resume;
2271 {
Ian Rogers50b35e22012-10-04 10:09:15 -07002272 MutexLock mu2(soa.Self(), *Locks::thread_suspend_count_lock_);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002273 needs_resume = thread->GetSuspendCount() > 0;
2274 }
2275 if (needs_resume) {
Elliott Hughes546b9862012-06-20 16:06:13 -07002276 Runtime::Current()->GetThreadList()->Resume(thread, true);
2277 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002278}
2279
2280void Dbg::SuspendSelf() {
Elliott Hughes475fc232011-10-25 15:00:35 -07002281 Runtime::Current()->GetThreadList()->SuspendSelfForDebugger();
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002282}
2283
Ian Rogers0399dde2012-06-06 17:09:28 -07002284struct GetThisVisitor : public StackVisitor {
Ian Rogers7a22fa62013-01-23 12:16:16 -08002285 GetThisVisitor(Thread* thread, Context* context, JDWP::FrameId frame_id)
Ian Rogersb726dcb2012-09-05 08:57:23 -07002286 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_)
Ian Rogers7a22fa62013-01-23 12:16:16 -08002287 : StackVisitor(thread, context), this_object(NULL), frame_id(frame_id) {}
Ian Rogers0399dde2012-06-06 17:09:28 -07002288
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002289 // TODO: Enable annotalysis. We know lock is held in constructor, but abstraction confuses
2290 // annotalysis.
2291 virtual bool VisitFrame() NO_THREAD_SAFETY_ANALYSIS {
Elliott Hughes6e9d22c2012-06-22 15:02:37 -07002292 if (frame_id != GetFrameId()) {
Ian Rogers0399dde2012-06-06 17:09:28 -07002293 return true; // continue
Ian Rogers0399dde2012-06-06 17:09:28 -07002294 } else {
Ian Rogers62d6c772013-02-27 08:32:07 -08002295 this_object = GetThisObject();
2296 return false;
Ian Rogers0399dde2012-06-06 17:09:28 -07002297 }
Elliott Hughes86b00102011-12-05 17:54:26 -08002298 }
Ian Rogers0399dde2012-06-06 17:09:28 -07002299
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002300 mirror::Object* this_object;
Elliott Hughes6e9d22c2012-06-22 15:02:37 -07002301 JDWP::FrameId frame_id;
Ian Rogers0399dde2012-06-06 17:09:28 -07002302};
2303
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002304JDWP::JdwpError Dbg::GetThisObject(JDWP::ObjectId thread_id, JDWP::FrameId frame_id,
2305 JDWP::ObjectId* result) {
2306 ScopedObjectAccessUnchecked soa(Thread::Current());
2307 Thread* thread;
2308 {
Ian Rogers50b35e22012-10-04 10:09:15 -07002309 MutexLock mu(soa.Self(), *Locks::thread_list_lock_);
Elliott Hughes221229c2013-01-08 18:17:50 -08002310 JDWP::JdwpError error = DecodeThread(soa, thread_id, thread);
2311 if (error != JDWP::ERR_NONE) {
2312 return error;
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002313 }
Elliott Hughes9e0c1752013-01-09 14:02:58 -08002314 if (!IsSuspendedForDebugger(soa, thread)) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002315 return JDWP::ERR_THREAD_NOT_SUSPENDED;
2316 }
Elliott Hughes6e9d22c2012-06-22 15:02:37 -07002317 }
Ian Rogers700a4022014-05-19 16:49:03 -07002318 std::unique_ptr<Context> context(Context::Create());
Ian Rogers7a22fa62013-01-23 12:16:16 -08002319 GetThisVisitor visitor(thread, context.get(), frame_id);
Ian Rogers0399dde2012-06-06 17:09:28 -07002320 visitor.WalkStack();
Elliott Hughes6e9d22c2012-06-22 15:02:37 -07002321 *result = gRegistry->Add(visitor.this_object);
2322 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002323}
2324
Sebastien Hertzcb19ebf2014-03-11 15:26:35 +01002325JDWP::JdwpError Dbg::GetLocalValue(JDWP::ObjectId thread_id, JDWP::FrameId frame_id, int slot,
2326 JDWP::JdwpTag tag, uint8_t* buf, size_t width) {
Ian Rogers0399dde2012-06-06 17:09:28 -07002327 struct GetLocalVisitor : public StackVisitor {
Ian Rogers98379392014-02-24 16:53:16 -08002328 GetLocalVisitor(const ScopedObjectAccessUnchecked& soa, Thread* thread, Context* context,
2329 JDWP::FrameId frame_id, int slot, JDWP::JdwpTag tag, uint8_t* buf, size_t width)
Ian Rogersb726dcb2012-09-05 08:57:23 -07002330 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_)
Ian Rogers98379392014-02-24 16:53:16 -08002331 : StackVisitor(thread, context), soa_(soa), frame_id_(frame_id), slot_(slot), tag_(tag),
Sebastien Hertzcb19ebf2014-03-11 15:26:35 +01002332 buf_(buf), width_(width), error_(JDWP::ERR_NONE) {}
Ian Rogersca190662012-06-26 15:45:57 -07002333
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002334 // TODO: Enable annotalysis. We know lock is held in constructor, but abstraction confuses
2335 // annotalysis.
2336 bool VisitFrame() NO_THREAD_SAFETY_ANALYSIS {
Ian Rogers0399dde2012-06-06 17:09:28 -07002337 if (GetFrameId() != frame_id_) {
2338 return true; // Not our frame, carry on.
Elliott Hughesdbb40792011-11-18 17:05:22 -08002339 }
Ian Rogers0399dde2012-06-06 17:09:28 -07002340 // TODO: check that the tag is compatible with the actual type of the slot!
Sebastien Hertzcb19ebf2014-03-11 15:26:35 +01002341 // TODO: check slot is valid for this method or return INVALID_SLOT error.
Brian Carlstromea46f952013-07-30 01:26:50 -07002342 mirror::ArtMethod* m = GetMethod();
Sebastien Hertzcb19ebf2014-03-11 15:26:35 +01002343 if (m->IsNative()) {
2344 // We can't read local value from native method.
2345 error_ = JDWP::ERR_OPAQUE_FRAME;
2346 return false;
2347 }
Ian Rogers0399dde2012-06-06 17:09:28 -07002348 uint16_t reg = DemangleSlot(slot_, m);
Sebastien Hertz8ebd94a2014-06-17 09:49:21 +00002349
Ian Rogers0399dde2012-06-06 17:09:28 -07002350 switch (tag_) {
Sebastien Hertz8ebd94a2014-06-17 09:49:21 +00002351 case JDWP::JT_BOOLEAN:
2352 {
Ian Rogers0399dde2012-06-06 17:09:28 -07002353 CHECK_EQ(width_, 1U);
Sebastien Hertz8ebd94a2014-06-17 09:49:21 +00002354 uint32_t intVal = GetVReg(m, reg, kIntVReg);
2355 VLOG(jdwp) << "get boolean local " << reg << " = " << intVal;
2356 JDWP::Set1(buf_+1, intVal != 0);
Ian Rogers0399dde2012-06-06 17:09:28 -07002357 }
Sebastien Hertz8ebd94a2014-06-17 09:49:21 +00002358 break;
2359 case JDWP::JT_BYTE:
2360 {
Ian Rogers0399dde2012-06-06 17:09:28 -07002361 CHECK_EQ(width_, 1U);
Sebastien Hertz8ebd94a2014-06-17 09:49:21 +00002362 uint32_t intVal = GetVReg(m, reg, kIntVReg);
2363 VLOG(jdwp) << "get byte local " << reg << " = " << intVal;
2364 JDWP::Set1(buf_+1, intVal);
Ian Rogers0399dde2012-06-06 17:09:28 -07002365 }
Sebastien Hertz8ebd94a2014-06-17 09:49:21 +00002366 break;
2367 case JDWP::JT_SHORT:
2368 case JDWP::JT_CHAR:
2369 {
Ian Rogers0399dde2012-06-06 17:09:28 -07002370 CHECK_EQ(width_, 2U);
Sebastien Hertz8ebd94a2014-06-17 09:49:21 +00002371 uint32_t intVal = GetVReg(m, reg, kIntVReg);
2372 VLOG(jdwp) << "get short/char local " << reg << " = " << intVal;
2373 JDWP::Set2BE(buf_+1, intVal);
Ian Rogers0399dde2012-06-06 17:09:28 -07002374 }
Sebastien Hertz8ebd94a2014-06-17 09:49:21 +00002375 break;
2376 case JDWP::JT_INT:
2377 {
Sebastien Hertzaa9b3ae2014-06-13 14:49:27 +02002378 CHECK_EQ(width_, 4U);
Sebastien Hertz8ebd94a2014-06-17 09:49:21 +00002379 uint32_t intVal = GetVReg(m, reg, kIntVReg);
2380 VLOG(jdwp) << "get int local " << reg << " = " << intVal;
2381 JDWP::Set4BE(buf_+1, intVal);
Ian Rogers0399dde2012-06-06 17:09:28 -07002382 }
Sebastien Hertz8ebd94a2014-06-17 09:49:21 +00002383 break;
2384 case JDWP::JT_FLOAT:
2385 {
Sebastien Hertzaa9b3ae2014-06-13 14:49:27 +02002386 CHECK_EQ(width_, 4U);
Sebastien Hertz8ebd94a2014-06-17 09:49:21 +00002387 uint32_t intVal = GetVReg(m, reg, kFloatVReg);
2388 VLOG(jdwp) << "get int/float local " << reg << " = " << intVal;
2389 JDWP::Set4BE(buf_+1, intVal);
Sebastien Hertzaa9b3ae2014-06-13 14:49:27 +02002390 }
Sebastien Hertz8ebd94a2014-06-17 09:49:21 +00002391 break;
2392 case JDWP::JT_ARRAY:
2393 {
Sebastien Hertzaa9b3ae2014-06-13 14:49:27 +02002394 CHECK_EQ(width_, sizeof(JDWP::ObjectId));
Sebastien Hertz8ebd94a2014-06-17 09:49:21 +00002395 mirror::Object* o = reinterpret_cast<mirror::Object*>(GetVReg(m, reg, kReferenceVReg));
2396 VLOG(jdwp) << "get array local " << reg << " = " << o;
2397 if (!Runtime::Current()->GetHeap()->IsValidObjectAddress(o)) {
2398 LOG(FATAL) << "Register " << reg << " expected to hold array: " << o;
Sebastien Hertzaa9b3ae2014-06-13 14:49:27 +02002399 }
Sebastien Hertz8ebd94a2014-06-17 09:49:21 +00002400 JDWP::SetObjectId(buf_+1, gRegistry->Add(o));
Sebastien Hertzaa9b3ae2014-06-13 14:49:27 +02002401 }
Sebastien Hertz8ebd94a2014-06-17 09:49:21 +00002402 break;
2403 case JDWP::JT_CLASS_LOADER:
2404 case JDWP::JT_CLASS_OBJECT:
2405 case JDWP::JT_OBJECT:
2406 case JDWP::JT_STRING:
2407 case JDWP::JT_THREAD:
2408 case JDWP::JT_THREAD_GROUP:
2409 {
2410 CHECK_EQ(width_, sizeof(JDWP::ObjectId));
2411 mirror::Object* o = reinterpret_cast<mirror::Object*>(GetVReg(m, reg, kReferenceVReg));
2412 VLOG(jdwp) << "get object local " << reg << " = " << o;
2413 if (!Runtime::Current()->GetHeap()->IsValidObjectAddress(o)) {
2414 LOG(FATAL) << "Register " << reg << " expected to hold object: " << o;
2415 }
2416 tag_ = TagFromObject(soa_, o);
2417 JDWP::SetObjectId(buf_+1, gRegistry->Add(o));
2418 }
2419 break;
2420 case JDWP::JT_DOUBLE:
2421 {
Ian Rogers2bcb4a42012-11-08 10:39:18 -08002422 CHECK_EQ(width_, 8U);
Sebastien Hertz8ebd94a2014-06-17 09:49:21 +00002423 uint32_t lo = GetVReg(m, reg, kDoubleLoVReg);
2424 uint64_t hi = GetVReg(m, reg + 1, kDoubleHiVReg);
2425 uint64_t longVal = (hi << 32) | lo;
2426 VLOG(jdwp) << "get double/long local " << hi << ":" << lo << " = " << longVal;
2427 JDWP::Set8BE(buf_+1, longVal);
Ian Rogers2bcb4a42012-11-08 10:39:18 -08002428 }
Sebastien Hertz8ebd94a2014-06-17 09:49:21 +00002429 break;
2430 case JDWP::JT_LONG:
2431 {
Ian Rogers0399dde2012-06-06 17:09:28 -07002432 CHECK_EQ(width_, 8U);
Sebastien Hertz8ebd94a2014-06-17 09:49:21 +00002433 uint32_t lo = GetVReg(m, reg, kLongLoVReg);
2434 uint64_t hi = GetVReg(m, reg + 1, kLongHiVReg);
2435 uint64_t longVal = (hi << 32) | lo;
2436 VLOG(jdwp) << "get double/long local " << hi << ":" << lo << " = " << longVal;
2437 JDWP::Set8BE(buf_+1, longVal);
Ian Rogers0399dde2012-06-06 17:09:28 -07002438 }
Sebastien Hertz8ebd94a2014-06-17 09:49:21 +00002439 break;
2440 default:
2441 LOG(FATAL) << "Unknown tag " << tag_;
2442 break;
Ian Rogers0399dde2012-06-06 17:09:28 -07002443 }
2444
2445 // Prepend tag, which may have been updated.
2446 JDWP::Set1(buf_, tag_);
2447 return false;
2448 }
Ian Rogers98379392014-02-24 16:53:16 -08002449 const ScopedObjectAccessUnchecked& soa_;
Ian Rogers0399dde2012-06-06 17:09:28 -07002450 const JDWP::FrameId frame_id_;
2451 const int slot_;
2452 JDWP::JdwpTag tag_;
2453 uint8_t* const buf_;
2454 const size_t width_;
Sebastien Hertzcb19ebf2014-03-11 15:26:35 +01002455 JDWP::JdwpError error_;
Ian Rogers0399dde2012-06-06 17:09:28 -07002456 };
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002457
2458 ScopedObjectAccessUnchecked soa(Thread::Current());
jeffhaoa77f0f62012-12-05 17:19:31 -08002459 MutexLock mu(soa.Self(), *Locks::thread_list_lock_);
Elliott Hughes221229c2013-01-08 18:17:50 -08002460 Thread* thread;
2461 JDWP::JdwpError error = DecodeThread(soa, thread_id, thread);
2462 if (error != JDWP::ERR_NONE) {
Sebastien Hertzcb19ebf2014-03-11 15:26:35 +01002463 return error;
Elliott Hughes221229c2013-01-08 18:17:50 -08002464 }
Sebastien Hertzcb19ebf2014-03-11 15:26:35 +01002465 // TODO check thread is suspended by the debugger ?
Ian Rogers700a4022014-05-19 16:49:03 -07002466 std::unique_ptr<Context> context(Context::Create());
Ian Rogers98379392014-02-24 16:53:16 -08002467 GetLocalVisitor visitor(soa, thread, context.get(), frame_id, slot, tag, buf, width);
Ian Rogers0399dde2012-06-06 17:09:28 -07002468 visitor.WalkStack();
Sebastien Hertzcb19ebf2014-03-11 15:26:35 +01002469 return visitor.error_;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002470}
2471
Sebastien Hertzcb19ebf2014-03-11 15:26:35 +01002472JDWP::JdwpError Dbg::SetLocalValue(JDWP::ObjectId thread_id, JDWP::FrameId frame_id, int slot,
2473 JDWP::JdwpTag tag, uint64_t value, size_t width) {
Ian Rogers0399dde2012-06-06 17:09:28 -07002474 struct SetLocalVisitor : public StackVisitor {
Ian Rogers7a22fa62013-01-23 12:16:16 -08002475 SetLocalVisitor(Thread* thread, Context* context,
Ian Rogers0399dde2012-06-06 17:09:28 -07002476 JDWP::FrameId frame_id, int slot, JDWP::JdwpTag tag, uint64_t value,
Ian Rogersca190662012-06-26 15:45:57 -07002477 size_t width)
Ian Rogersb726dcb2012-09-05 08:57:23 -07002478 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_)
Ian Rogers7a22fa62013-01-23 12:16:16 -08002479 : StackVisitor(thread, context),
Sebastien Hertzcb19ebf2014-03-11 15:26:35 +01002480 frame_id_(frame_id), slot_(slot), tag_(tag), value_(value), width_(width),
2481 error_(JDWP::ERR_NONE) {}
Ian Rogersca190662012-06-26 15:45:57 -07002482
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002483 // TODO: Enable annotalysis. We know lock is held in constructor, but abstraction confuses
2484 // annotalysis.
2485 bool VisitFrame() NO_THREAD_SAFETY_ANALYSIS {
Ian Rogers0399dde2012-06-06 17:09:28 -07002486 if (GetFrameId() != frame_id_) {
2487 return true; // Not our frame, carry on.
2488 }
2489 // TODO: check that the tag is compatible with the actual type of the slot!
Sebastien Hertzcb19ebf2014-03-11 15:26:35 +01002490 // TODO: check slot is valid for this method or return INVALID_SLOT error.
Brian Carlstromea46f952013-07-30 01:26:50 -07002491 mirror::ArtMethod* m = GetMethod();
Sebastien Hertzcb19ebf2014-03-11 15:26:35 +01002492 if (m->IsNative()) {
2493 // We can't read local value from native method.
2494 error_ = JDWP::ERR_OPAQUE_FRAME;
2495 return false;
2496 }
Ian Rogers0399dde2012-06-06 17:09:28 -07002497 uint16_t reg = DemangleSlot(slot_, m);
Sebastien Hertz8ebd94a2014-06-17 09:49:21 +00002498
Ian Rogers0399dde2012-06-06 17:09:28 -07002499 switch (tag_) {
2500 case JDWP::JT_BOOLEAN:
2501 case JDWP::JT_BYTE:
2502 CHECK_EQ(width_, 1U);
Sebastien Hertz8ebd94a2014-06-17 09:49:21 +00002503 SetVReg(m, reg, static_cast<uint32_t>(value_), kIntVReg);
Ian Rogers0399dde2012-06-06 17:09:28 -07002504 break;
2505 case JDWP::JT_SHORT:
2506 case JDWP::JT_CHAR:
2507 CHECK_EQ(width_, 2U);
Sebastien Hertz8ebd94a2014-06-17 09:49:21 +00002508 SetVReg(m, reg, static_cast<uint32_t>(value_), kIntVReg);
Ian Rogers0399dde2012-06-06 17:09:28 -07002509 break;
2510 case JDWP::JT_INT:
Ian Rogers2bcb4a42012-11-08 10:39:18 -08002511 CHECK_EQ(width_, 4U);
Sebastien Hertz8ebd94a2014-06-17 09:49:21 +00002512 SetVReg(m, reg, static_cast<uint32_t>(value_), kIntVReg);
Ian Rogers2bcb4a42012-11-08 10:39:18 -08002513 break;
Ian Rogers0399dde2012-06-06 17:09:28 -07002514 case JDWP::JT_FLOAT:
2515 CHECK_EQ(width_, 4U);
Sebastien Hertz8ebd94a2014-06-17 09:49:21 +00002516 SetVReg(m, reg, static_cast<uint32_t>(value_), kFloatVReg);
Ian Rogers0399dde2012-06-06 17:09:28 -07002517 break;
2518 case JDWP::JT_ARRAY:
2519 case JDWP::JT_OBJECT:
2520 case JDWP::JT_STRING:
Sebastien Hertz8ebd94a2014-06-17 09:49:21 +00002521 {
Ian Rogers0399dde2012-06-06 17:09:28 -07002522 CHECK_EQ(width_, sizeof(JDWP::ObjectId));
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002523 mirror::Object* o = gRegistry->Get<mirror::Object*>(static_cast<JDWP::ObjectId>(value_));
Elliott Hughes64f574f2013-02-20 14:57:12 -08002524 if (o == ObjectRegistry::kInvalidObject) {
Sebastien Hertz8ebd94a2014-06-17 09:49:21 +00002525 UNIMPLEMENTED(FATAL) << "return an error code when given an invalid object to store";
Ian Rogers0399dde2012-06-06 17:09:28 -07002526 }
Sebastien Hertz8ebd94a2014-06-17 09:49:21 +00002527 SetVReg(m, reg, static_cast<uint32_t>(reinterpret_cast<uintptr_t>(o)), kReferenceVReg);
Ian Rogers0399dde2012-06-06 17:09:28 -07002528 }
Sebastien Hertz8ebd94a2014-06-17 09:49:21 +00002529 break;
2530 case JDWP::JT_DOUBLE:
Ian Rogers2bcb4a42012-11-08 10:39:18 -08002531 CHECK_EQ(width_, 8U);
Sebastien Hertz8ebd94a2014-06-17 09:49:21 +00002532 SetVReg(m, reg, static_cast<uint32_t>(value_), kDoubleLoVReg);
2533 SetVReg(m, reg + 1, static_cast<uint32_t>(value_ >> 32), kDoubleHiVReg);
Ian Rogers2bcb4a42012-11-08 10:39:18 -08002534 break;
Sebastien Hertz8ebd94a2014-06-17 09:49:21 +00002535 case JDWP::JT_LONG:
Ian Rogers0399dde2012-06-06 17:09:28 -07002536 CHECK_EQ(width_, 8U);
Sebastien Hertz8ebd94a2014-06-17 09:49:21 +00002537 SetVReg(m, reg, static_cast<uint32_t>(value_), kLongLoVReg);
2538 SetVReg(m, reg + 1, static_cast<uint32_t>(value_ >> 32), kLongHiVReg);
Ian Rogers0399dde2012-06-06 17:09:28 -07002539 break;
2540 default:
2541 LOG(FATAL) << "Unknown tag " << tag_;
2542 break;
2543 }
2544 return false;
2545 }
2546
2547 const JDWP::FrameId frame_id_;
2548 const int slot_;
2549 const JDWP::JdwpTag tag_;
2550 const uint64_t value_;
2551 const size_t width_;
Sebastien Hertzcb19ebf2014-03-11 15:26:35 +01002552 JDWP::JdwpError error_;
Ian Rogers0399dde2012-06-06 17:09:28 -07002553 };
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002554
2555 ScopedObjectAccessUnchecked soa(Thread::Current());
jeffhaoa77f0f62012-12-05 17:19:31 -08002556 MutexLock mu(soa.Self(), *Locks::thread_list_lock_);
Elliott Hughes221229c2013-01-08 18:17:50 -08002557 Thread* thread;
2558 JDWP::JdwpError error = DecodeThread(soa, thread_id, thread);
2559 if (error != JDWP::ERR_NONE) {
Sebastien Hertzcb19ebf2014-03-11 15:26:35 +01002560 return error;
Elliott Hughes221229c2013-01-08 18:17:50 -08002561 }
Sebastien Hertzcb19ebf2014-03-11 15:26:35 +01002562 // TODO check thread is suspended by the debugger ?
Ian Rogers700a4022014-05-19 16:49:03 -07002563 std::unique_ptr<Context> context(Context::Create());
Ian Rogers7a22fa62013-01-23 12:16:16 -08002564 SetLocalVisitor visitor(thread, context.get(), frame_id, slot, tag, value, width);
Ian Rogers0399dde2012-06-06 17:09:28 -07002565 visitor.WalkStack();
Sebastien Hertzcb19ebf2014-03-11 15:26:35 +01002566 return visitor.error_;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002567}
2568
Sebastien Hertz3f52eaf2014-04-04 17:50:18 +02002569JDWP::ObjectId Dbg::GetThisObjectIdForEvent(mirror::Object* this_object) {
2570 // If 'this_object' isn't already in the registry, we know that we're not looking for it, so
2571 // there's no point adding it to the registry and burning through ids.
2572 // When registering an event request with an instance filter, we've been given an existing object
2573 // id so it must already be present in the registry when the event fires.
2574 JDWP::ObjectId this_id = 0;
2575 if (this_object != nullptr && gRegistry->Contains(this_object)) {
2576 this_id = gRegistry->Add(this_object);
2577 }
2578 return this_id;
2579}
2580
Ian Rogersef7d42f2014-01-06 12:55:46 -08002581void Dbg::PostLocationEvent(mirror::ArtMethod* m, int dex_pc, mirror::Object* this_object,
Jeff Hao579b0242013-11-18 13:16:49 -08002582 int event_flags, const JValue* return_value) {
Sebastien Hertz3f52eaf2014-04-04 17:50:18 +02002583 if (!IsDebuggerActive()) {
2584 return;
2585 }
2586 DCHECK(m != nullptr);
2587 DCHECK_EQ(m->IsStatic(), this_object == nullptr);
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08002588 JDWP::JdwpLocation location;
Sebastien Hertzcb19ebf2014-03-11 15:26:35 +01002589 SetLocation(location, m, dex_pc);
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08002590
Sebastien Hertz3f52eaf2014-04-04 17:50:18 +02002591 // We need 'this' for InstanceOnly filters only.
2592 JDWP::ObjectId this_id = GetThisObjectIdForEvent(this_object);
Jeff Hao579b0242013-11-18 13:16:49 -08002593 gJdwpState->PostLocationEvent(&location, this_id, event_flags, return_value);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002594}
2595
Sebastien Hertz3f52eaf2014-04-04 17:50:18 +02002596void Dbg::PostFieldAccessEvent(mirror::ArtMethod* m, int dex_pc,
2597 mirror::Object* this_object, mirror::ArtField* f) {
2598 if (!IsDebuggerActive()) {
2599 return;
2600 }
2601 DCHECK(m != nullptr);
2602 DCHECK(f != nullptr);
2603 JDWP::JdwpLocation location;
2604 SetLocation(location, m, dex_pc);
2605
2606 JDWP::RefTypeId type_id = gRegistry->AddRefType(f->GetDeclaringClass());
2607 JDWP::FieldId field_id = ToFieldId(f);
2608 JDWP::ObjectId this_id = gRegistry->Add(this_object);
2609
2610 gJdwpState->PostFieldEvent(&location, type_id, field_id, this_id, nullptr, false);
2611}
2612
2613void Dbg::PostFieldModificationEvent(mirror::ArtMethod* m, int dex_pc,
2614 mirror::Object* this_object, mirror::ArtField* f,
2615 const JValue* field_value) {
2616 if (!IsDebuggerActive()) {
2617 return;
2618 }
2619 DCHECK(m != nullptr);
2620 DCHECK(f != nullptr);
2621 DCHECK(field_value != nullptr);
2622 JDWP::JdwpLocation location;
2623 SetLocation(location, m, dex_pc);
2624
2625 JDWP::RefTypeId type_id = gRegistry->AddRefType(f->GetDeclaringClass());
2626 JDWP::FieldId field_id = ToFieldId(f);
2627 JDWP::ObjectId this_id = gRegistry->Add(this_object);
2628
2629 gJdwpState->PostFieldEvent(&location, type_id, field_id, this_id, field_value, true);
2630}
2631
2632void Dbg::PostException(const ThrowLocation& throw_location,
Brian Carlstromea46f952013-07-30 01:26:50 -07002633 mirror::ArtMethod* catch_method,
Elliott Hughes64f574f2013-02-20 14:57:12 -08002634 uint32_t catch_dex_pc, mirror::Throwable* exception_object) {
Elliott Hughesc0f09332012-03-26 13:27:06 -07002635 if (!IsDebuggerActive()) {
Ian Rogers0ad5bb82011-12-07 10:16:32 -08002636 return;
2637 }
Elliott Hughes4740cdf2011-12-07 14:07:12 -08002638
Ian Rogers62d6c772013-02-27 08:32:07 -08002639 JDWP::JdwpLocation jdwp_throw_location;
2640 SetLocation(jdwp_throw_location, throw_location.GetMethod(), throw_location.GetDexPc());
Elliott Hughesd07986f2011-12-06 18:27:45 -08002641 JDWP::JdwpLocation catch_location;
Elliott Hughescaf76542012-06-28 16:08:22 -07002642 SetLocation(catch_location, catch_method, catch_dex_pc);
Elliott Hughesd07986f2011-12-06 18:27:45 -08002643
Sebastien Hertz3f52eaf2014-04-04 17:50:18 +02002644 // We need 'this' for InstanceOnly filters only.
2645 JDWP::ObjectId this_id = GetThisObjectIdForEvent(throw_location.GetThis());
Elliott Hughes64f574f2013-02-20 14:57:12 -08002646 JDWP::ObjectId exception_id = gRegistry->Add(exception_object);
2647 JDWP::RefTypeId exception_class_id = gRegistry->AddRefType(exception_object->GetClass());
Elliott Hughesd07986f2011-12-06 18:27:45 -08002648
Ian Rogers62d6c772013-02-27 08:32:07 -08002649 gJdwpState->PostException(&jdwp_throw_location, exception_id, exception_class_id, &catch_location,
2650 this_id);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002651}
2652
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002653void Dbg::PostClassPrepare(mirror::Class* c) {
Elliott Hughesc0f09332012-03-26 13:27:06 -07002654 if (!IsDebuggerActive()) {
Elliott Hughes4740cdf2011-12-07 14:07:12 -08002655 return;
2656 }
2657
Elliott Hughes3d30d9b2011-12-07 17:35:48 -08002658 // OLD-TODO - we currently always send both "verified" and "prepared" since
Elliott Hughes4740cdf2011-12-07 14:07:12 -08002659 // debuggers seem to like that. There might be some advantage to honesty,
2660 // since the class may not yet be verified.
2661 int state = JDWP::CS_VERIFIED | JDWP::CS_PREPARED;
Sebastien Hertz4d8fd492014-03-28 16:29:41 +01002662 JDWP::JdwpTypeTag tag = GetTypeTag(c);
Mathieu Chartierf8322842014-05-16 10:59:25 -07002663 gJdwpState->PostClassPrepare(tag, gRegistry->Add(c), c->GetDescriptor(), state);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002664}
2665
Ian Rogers62d6c772013-02-27 08:32:07 -08002666void Dbg::UpdateDebugger(Thread* thread, mirror::Object* this_object,
Sebastien Hertz8379b222014-02-24 17:38:15 +01002667 mirror::ArtMethod* m, uint32_t dex_pc,
2668 int event_flags, const JValue* return_value) {
Ian Rogers62d6c772013-02-27 08:32:07 -08002669 if (!IsDebuggerActive() || dex_pc == static_cast<uint32_t>(-2) /* fake method exit */) {
Elliott Hughes2aa2e392012-02-17 17:15:43 -08002670 return;
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08002671 }
2672
Elliott Hughes86964332012-02-15 19:37:42 -08002673 if (IsBreakpoint(m, dex_pc)) {
2674 event_flags |= kBreakpoint;
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08002675 }
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08002676
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01002677 // If the debugger is single-stepping one of our threads, check to
2678 // see if we're that thread and we've reached a step point.
2679 const SingleStepControl* single_step_control = thread->GetSingleStepControl();
2680 DCHECK(single_step_control != nullptr);
2681 if (single_step_control->is_active) {
2682 CHECK(!m->IsNative());
2683 if (single_step_control->step_depth == JDWP::SD_INTO) {
2684 // Step into method calls. We break when the line number
2685 // or method pointer changes. If we're in SS_MIN mode, we
2686 // always stop.
2687 if (single_step_control->method != m) {
2688 event_flags |= kSingleStep;
2689 VLOG(jdwp) << "SS new method";
2690 } else if (single_step_control->step_size == JDWP::SS_MIN) {
2691 event_flags |= kSingleStep;
2692 VLOG(jdwp) << "SS new instruction";
Sebastien Hertzbb43b432014-04-14 11:59:08 +02002693 } else if (single_step_control->ContainsDexPc(dex_pc)) {
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01002694 event_flags |= kSingleStep;
2695 VLOG(jdwp) << "SS new line";
2696 }
2697 } else if (single_step_control->step_depth == JDWP::SD_OVER) {
2698 // Step over method calls. We break when the line number is
2699 // different and the frame depth is <= the original frame
2700 // depth. (We can't just compare on the method, because we
2701 // might get unrolled past it by an exception, and it's tricky
2702 // to identify recursion.)
2703
2704 int stack_depth = GetStackDepth(thread);
2705
2706 if (stack_depth < single_step_control->stack_depth) {
2707 // Popped up one or more frames, always trigger.
2708 event_flags |= kSingleStep;
2709 VLOG(jdwp) << "SS method pop";
2710 } else if (stack_depth == single_step_control->stack_depth) {
2711 // Same depth, see if we moved.
2712 if (single_step_control->step_size == JDWP::SS_MIN) {
Elliott Hughes86964332012-02-15 19:37:42 -08002713 event_flags |= kSingleStep;
2714 VLOG(jdwp) << "SS new instruction";
Sebastien Hertzbb43b432014-04-14 11:59:08 +02002715 } else if (single_step_control->ContainsDexPc(dex_pc)) {
Elliott Hughes2435a572012-02-17 16:07:41 -08002716 event_flags |= kSingleStep;
2717 VLOG(jdwp) << "SS new line";
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08002718 }
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01002719 }
2720 } else {
2721 CHECK_EQ(single_step_control->step_depth, JDWP::SD_OUT);
2722 // Return from the current method. We break when the frame
2723 // depth pops up.
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08002724
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01002725 // This differs from the "method exit" break in that it stops
2726 // with the PC at the next instruction in the returned-to
2727 // function, rather than the end of the returning function.
Elliott Hughes86964332012-02-15 19:37:42 -08002728
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01002729 int stack_depth = GetStackDepth(thread);
2730 if (stack_depth < single_step_control->stack_depth) {
2731 event_flags |= kSingleStep;
2732 VLOG(jdwp) << "SS method pop";
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08002733 }
2734 }
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08002735 }
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08002736
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08002737 // If there's something interesting going on, see if it matches one
2738 // of the debugger filters.
2739 if (event_flags != 0) {
Sebastien Hertz8379b222014-02-24 17:38:15 +01002740 Dbg::PostLocationEvent(m, dex_pc, this_object, event_flags, return_value);
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08002741 }
2742}
2743
Sebastien Hertz42cd43f2014-05-13 14:15:41 +02002744size_t* Dbg::GetReferenceCounterForEvent(uint32_t instrumentation_event) {
2745 switch (instrumentation_event) {
2746 case instrumentation::Instrumentation::kMethodEntered:
2747 return &method_enter_event_ref_count_;
2748 case instrumentation::Instrumentation::kMethodExited:
2749 return &method_exit_event_ref_count_;
2750 case instrumentation::Instrumentation::kDexPcMoved:
2751 return &dex_pc_change_event_ref_count_;
2752 case instrumentation::Instrumentation::kFieldRead:
2753 return &field_read_event_ref_count_;
2754 case instrumentation::Instrumentation::kFieldWritten:
2755 return &field_write_event_ref_count_;
2756 case instrumentation::Instrumentation::kExceptionCaught:
2757 return &exception_catch_event_ref_count_;
2758 default:
2759 return nullptr;
2760 }
2761}
2762
Sebastien Hertz4d25df32014-03-21 17:44:46 +01002763// Process request while all mutator threads are suspended.
2764void Dbg::ProcessDeoptimizationRequest(const DeoptimizationRequest& request) {
Sebastien Hertz138dbfc2013-12-04 18:15:25 +01002765 instrumentation::Instrumentation* instrumentation = Runtime::Current()->GetInstrumentation();
Sebastien Hertz4d25df32014-03-21 17:44:46 +01002766 switch (request.kind) {
2767 case DeoptimizationRequest::kNothing:
2768 LOG(WARNING) << "Ignoring empty deoptimization request.";
2769 break;
Sebastien Hertz42cd43f2014-05-13 14:15:41 +02002770 case DeoptimizationRequest::kRegisterForEvent:
2771 VLOG(jdwp) << StringPrintf("Add debugger as listener for instrumentation event 0x%x",
2772 request.instrumentation_event);
2773 instrumentation->AddListener(&gDebugInstrumentationListener, request.instrumentation_event);
2774 instrumentation_events_ |= request.instrumentation_event;
2775 break;
2776 case DeoptimizationRequest::kUnregisterForEvent:
2777 VLOG(jdwp) << StringPrintf("Remove debugger as listener for instrumentation event 0x%x",
2778 request.instrumentation_event);
2779 instrumentation->RemoveListener(&gDebugInstrumentationListener,
2780 request.instrumentation_event);
2781 instrumentation_events_ &= ~request.instrumentation_event;
2782 break;
Sebastien Hertz4d25df32014-03-21 17:44:46 +01002783 case DeoptimizationRequest::kFullDeoptimization:
Sebastien Hertz7ec2f1c2014-03-27 20:06:47 +01002784 VLOG(jdwp) << "Deoptimize the world ...";
Sebastien Hertz4d25df32014-03-21 17:44:46 +01002785 instrumentation->DeoptimizeEverything();
Sebastien Hertz7ec2f1c2014-03-27 20:06:47 +01002786 VLOG(jdwp) << "Deoptimize the world DONE";
Sebastien Hertz4d25df32014-03-21 17:44:46 +01002787 break;
2788 case DeoptimizationRequest::kFullUndeoptimization:
Sebastien Hertz7ec2f1c2014-03-27 20:06:47 +01002789 VLOG(jdwp) << "Undeoptimize the world ...";
Sebastien Hertz4d25df32014-03-21 17:44:46 +01002790 instrumentation->UndeoptimizeEverything();
Sebastien Hertz7ec2f1c2014-03-27 20:06:47 +01002791 VLOG(jdwp) << "Undeoptimize the world DONE";
Sebastien Hertz4d25df32014-03-21 17:44:46 +01002792 break;
2793 case DeoptimizationRequest::kSelectiveDeoptimization:
Sebastien Hertz7ec2f1c2014-03-27 20:06:47 +01002794 VLOG(jdwp) << "Deoptimize method " << PrettyMethod(request.method) << " ...";
Sebastien Hertz4d25df32014-03-21 17:44:46 +01002795 instrumentation->Deoptimize(request.method);
Sebastien Hertz7ec2f1c2014-03-27 20:06:47 +01002796 VLOG(jdwp) << "Deoptimize method " << PrettyMethod(request.method) << " DONE";
Sebastien Hertz4d25df32014-03-21 17:44:46 +01002797 break;
2798 case DeoptimizationRequest::kSelectiveUndeoptimization:
Sebastien Hertz7ec2f1c2014-03-27 20:06:47 +01002799 VLOG(jdwp) << "Undeoptimize method " << PrettyMethod(request.method) << " ...";
Sebastien Hertz4d25df32014-03-21 17:44:46 +01002800 instrumentation->Undeoptimize(request.method);
Sebastien Hertz7ec2f1c2014-03-27 20:06:47 +01002801 VLOG(jdwp) << "Undeoptimize method " << PrettyMethod(request.method) << " DONE";
Sebastien Hertz4d25df32014-03-21 17:44:46 +01002802 break;
2803 default:
2804 LOG(FATAL) << "Unsupported deoptimization request kind " << request.kind;
2805 break;
Sebastien Hertz138dbfc2013-12-04 18:15:25 +01002806 }
Sebastien Hertz138dbfc2013-12-04 18:15:25 +01002807}
2808
Sebastien Hertz7ec2f1c2014-03-27 20:06:47 +01002809void Dbg::DelayFullUndeoptimization() {
2810 MutexLock mu(Thread::Current(), *deoptimization_lock_);
2811 ++delayed_full_undeoptimization_count_;
2812 DCHECK_LE(delayed_full_undeoptimization_count_, full_deoptimization_event_count_);
2813}
2814
2815void Dbg::ProcessDelayedFullUndeoptimizations() {
2816 // TODO: avoid taking the lock twice (once here and once in ManageDeoptimization).
2817 {
2818 MutexLock mu(Thread::Current(), *deoptimization_lock_);
2819 while (delayed_full_undeoptimization_count_ > 0) {
2820 DeoptimizationRequest req;
2821 req.kind = DeoptimizationRequest::kFullUndeoptimization;
2822 req.method = nullptr;
2823 RequestDeoptimizationLocked(req);
2824 --delayed_full_undeoptimization_count_;
2825 }
2826 }
2827 ManageDeoptimization();
2828}
2829
Sebastien Hertz4d25df32014-03-21 17:44:46 +01002830void Dbg::RequestDeoptimization(const DeoptimizationRequest& req) {
2831 if (req.kind == DeoptimizationRequest::kNothing) {
2832 // Nothing to do.
2833 return;
2834 }
2835 MutexLock mu(Thread::Current(), *deoptimization_lock_);
Sebastien Hertz7ec2f1c2014-03-27 20:06:47 +01002836 RequestDeoptimizationLocked(req);
2837}
2838
2839void Dbg::RequestDeoptimizationLocked(const DeoptimizationRequest& req) {
Sebastien Hertz4d25df32014-03-21 17:44:46 +01002840 switch (req.kind) {
Sebastien Hertz42cd43f2014-05-13 14:15:41 +02002841 case DeoptimizationRequest::kRegisterForEvent: {
2842 DCHECK_NE(req.instrumentation_event, 0u);
2843 size_t* counter = GetReferenceCounterForEvent(req.instrumentation_event);
2844 CHECK(counter != nullptr) << StringPrintf("No counter for instrumentation event 0x%x",
2845 req.instrumentation_event);
2846 if (*counter == 0) {
Sebastien Hertz7d2ae432014-05-15 11:26:34 +02002847 VLOG(jdwp) << StringPrintf("Queue request #%zd to start listening to instrumentation event 0x%x",
Sebastien Hertz42cd43f2014-05-13 14:15:41 +02002848 deoptimization_requests_.size(), req.instrumentation_event);
2849 deoptimization_requests_.push_back(req);
2850 }
2851 *counter = *counter + 1;
2852 break;
2853 }
2854 case DeoptimizationRequest::kUnregisterForEvent: {
2855 DCHECK_NE(req.instrumentation_event, 0u);
2856 size_t* counter = GetReferenceCounterForEvent(req.instrumentation_event);
2857 CHECK(counter != nullptr) << StringPrintf("No counter for instrumentation event 0x%x",
2858 req.instrumentation_event);
2859 *counter = *counter - 1;
2860 if (*counter == 0) {
Sebastien Hertz7d2ae432014-05-15 11:26:34 +02002861 VLOG(jdwp) << StringPrintf("Queue request #%zd to stop listening to instrumentation event 0x%x",
Sebastien Hertz42cd43f2014-05-13 14:15:41 +02002862 deoptimization_requests_.size(), req.instrumentation_event);
2863 deoptimization_requests_.push_back(req);
2864 }
2865 break;
2866 }
Sebastien Hertz4d25df32014-03-21 17:44:46 +01002867 case DeoptimizationRequest::kFullDeoptimization: {
2868 DCHECK(req.method == nullptr);
2869 if (full_deoptimization_event_count_ == 0) {
Sebastien Hertz7ec2f1c2014-03-27 20:06:47 +01002870 VLOG(jdwp) << "Queue request #" << deoptimization_requests_.size()
2871 << " for full deoptimization";
Sebastien Hertz4d25df32014-03-21 17:44:46 +01002872 deoptimization_requests_.push_back(req);
2873 }
2874 ++full_deoptimization_event_count_;
2875 break;
2876 }
2877 case DeoptimizationRequest::kFullUndeoptimization: {
2878 DCHECK(req.method == nullptr);
Sebastien Hertze713d932014-05-15 10:48:53 +02002879 DCHECK_GT(full_deoptimization_event_count_, 0U);
Sebastien Hertz4d25df32014-03-21 17:44:46 +01002880 --full_deoptimization_event_count_;
2881 if (full_deoptimization_event_count_ == 0) {
Sebastien Hertz7ec2f1c2014-03-27 20:06:47 +01002882 VLOG(jdwp) << "Queue request #" << deoptimization_requests_.size()
2883 << " for full undeoptimization";
Sebastien Hertz4d25df32014-03-21 17:44:46 +01002884 deoptimization_requests_.push_back(req);
2885 }
2886 break;
2887 }
2888 case DeoptimizationRequest::kSelectiveDeoptimization: {
2889 DCHECK(req.method != nullptr);
Sebastien Hertz7ec2f1c2014-03-27 20:06:47 +01002890 VLOG(jdwp) << "Queue request #" << deoptimization_requests_.size()
2891 << " for deoptimization of " << PrettyMethod(req.method);
Sebastien Hertz4d25df32014-03-21 17:44:46 +01002892 deoptimization_requests_.push_back(req);
2893 break;
2894 }
2895 case DeoptimizationRequest::kSelectiveUndeoptimization: {
2896 DCHECK(req.method != nullptr);
Sebastien Hertz7ec2f1c2014-03-27 20:06:47 +01002897 VLOG(jdwp) << "Queue request #" << deoptimization_requests_.size()
2898 << " for undeoptimization of " << PrettyMethod(req.method);
Sebastien Hertz4d25df32014-03-21 17:44:46 +01002899 deoptimization_requests_.push_back(req);
2900 break;
2901 }
2902 default: {
2903 LOG(FATAL) << "Unknown deoptimization request kind " << req.kind;
2904 break;
2905 }
2906 }
2907}
2908
Sebastien Hertz138dbfc2013-12-04 18:15:25 +01002909void Dbg::ManageDeoptimization() {
2910 Thread* const self = Thread::Current();
2911 {
2912 // Avoid suspend/resume if there is no pending request.
Sebastien Hertz4d25df32014-03-21 17:44:46 +01002913 MutexLock mu(self, *deoptimization_lock_);
2914 if (deoptimization_requests_.empty()) {
Sebastien Hertz138dbfc2013-12-04 18:15:25 +01002915 return;
2916 }
2917 }
2918 CHECK_EQ(self->GetState(), kRunnable);
2919 self->TransitionFromRunnableToSuspended(kWaitingForDeoptimization);
2920 // We need to suspend mutator threads first.
2921 Runtime* const runtime = Runtime::Current();
2922 runtime->GetThreadList()->SuspendAll();
2923 const ThreadState old_state = self->SetStateUnsafe(kRunnable);
Sebastien Hertz4d25df32014-03-21 17:44:46 +01002924 {
2925 MutexLock mu(self, *deoptimization_lock_);
Sebastien Hertz7ec2f1c2014-03-27 20:06:47 +01002926 size_t req_index = 0;
Sebastien Hertz4d25df32014-03-21 17:44:46 +01002927 for (const DeoptimizationRequest& request : deoptimization_requests_) {
Sebastien Hertz7ec2f1c2014-03-27 20:06:47 +01002928 VLOG(jdwp) << "Process deoptimization request #" << req_index++;
Sebastien Hertz4d25df32014-03-21 17:44:46 +01002929 ProcessDeoptimizationRequest(request);
2930 }
2931 deoptimization_requests_.clear();
2932 }
Sebastien Hertz138dbfc2013-12-04 18:15:25 +01002933 CHECK_EQ(self->SetStateUnsafe(old_state), kRunnable);
2934 runtime->GetThreadList()->ResumeAll();
2935 self->TransitionFromSuspendedToRunnable();
2936}
2937
Sebastien Hertza76a6d42014-03-20 16:40:17 +01002938static bool IsMethodPossiblyInlined(Thread* self, mirror::ArtMethod* m)
2939 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07002940 const DexFile::CodeItem* code_item = m->GetCodeItem();
Sebastien Hertza76a6d42014-03-20 16:40:17 +01002941 if (code_item == nullptr) {
2942 // TODO We should not be asked to watch location in a native or abstract method so the code item
2943 // should never be null. We could just check we never encounter this case.
2944 return false;
Sebastien Hertz138dbfc2013-12-04 18:15:25 +01002945 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002946 StackHandleScope<2> hs(self);
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07002947 mirror::Class* declaring_class = m->GetDeclaringClass();
2948 Handle<mirror::DexCache> dex_cache(hs.NewHandle(declaring_class->GetDexCache()));
2949 Handle<mirror::ClassLoader> class_loader(hs.NewHandle(declaring_class->GetClassLoader()));
2950 verifier::MethodVerifier verifier(dex_cache->GetDexFile(), &dex_cache, &class_loader,
2951 &m->GetClassDef(), code_item, m->GetDexMethodIndex(), m,
Ian Rogers46960fe2014-05-23 10:43:43 -07002952 m->GetAccessFlags(), false, true, false);
Sebastien Hertza76a6d42014-03-20 16:40:17 +01002953 // Note: we don't need to verify the method.
2954 return InlineMethodAnalyser::AnalyseMethodCode(&verifier, nullptr);
2955}
Sebastien Hertz138dbfc2013-12-04 18:15:25 +01002956
Sebastien Hertza76a6d42014-03-20 16:40:17 +01002957static const Breakpoint* FindFirstBreakpointForMethod(mirror::ArtMethod* m)
2958 EXCLUSIVE_LOCKS_REQUIRED(Locks::breakpoint_lock_) {
2959 for (const Breakpoint& breakpoint : gBreakpoints) {
2960 if (breakpoint.method == m) {
2961 return &breakpoint;
2962 }
2963 }
2964 return nullptr;
2965}
2966
2967// Sanity checks all existing breakpoints on the same method.
2968static void SanityCheckExistingBreakpoints(mirror::ArtMethod* m, bool need_full_deoptimization)
2969 EXCLUSIVE_LOCKS_REQUIRED(Locks::breakpoint_lock_) {
2970 if (kIsDebugBuild) {
2971 for (const Breakpoint& breakpoint : gBreakpoints) {
2972 CHECK_EQ(need_full_deoptimization, breakpoint.need_full_deoptimization);
2973 }
2974 if (need_full_deoptimization) {
2975 // We should have deoptimized everything but not "selectively" deoptimized this method.
2976 CHECK(Runtime::Current()->GetInstrumentation()->AreAllMethodsDeoptimized());
2977 CHECK(!Runtime::Current()->GetInstrumentation()->IsDeoptimized(m));
2978 } else {
2979 // We should have "selectively" deoptimized this method.
2980 // Note: while we have not deoptimized everything for this method, we may have done it for
2981 // another event.
2982 CHECK(Runtime::Current()->GetInstrumentation()->IsDeoptimized(m));
2983 }
Sebastien Hertz138dbfc2013-12-04 18:15:25 +01002984 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002985}
2986
Sebastien Hertza76a6d42014-03-20 16:40:17 +01002987// Installs a breakpoint at the specified location. Also indicates through the deoptimization
2988// request if we need to deoptimize.
2989void Dbg::WatchLocation(const JDWP::JdwpLocation* location, DeoptimizationRequest* req) {
2990 Thread* const self = Thread::Current();
Brian Carlstromea46f952013-07-30 01:26:50 -07002991 mirror::ArtMethod* m = FromMethodId(location->method_id);
Sebastien Hertza76a6d42014-03-20 16:40:17 +01002992 DCHECK(m != nullptr) << "No method for method id " << location->method_id;
Sebastien Hertz138dbfc2013-12-04 18:15:25 +01002993
Sebastien Hertza76a6d42014-03-20 16:40:17 +01002994 MutexLock mu(self, *Locks::breakpoint_lock_);
2995 const Breakpoint* const existing_breakpoint = FindFirstBreakpointForMethod(m);
2996 bool need_full_deoptimization;
2997 if (existing_breakpoint == nullptr) {
2998 // There is no breakpoint on this method yet: we need to deoptimize. If this method may be
2999 // inlined, we deoptimize everything; otherwise we deoptimize only this method.
3000 need_full_deoptimization = IsMethodPossiblyInlined(self, m);
3001 if (need_full_deoptimization) {
3002 req->kind = DeoptimizationRequest::kFullDeoptimization;
3003 req->method = nullptr;
3004 } else {
3005 req->kind = DeoptimizationRequest::kSelectiveDeoptimization;
3006 req->method = m;
Sebastien Hertz138dbfc2013-12-04 18:15:25 +01003007 }
Sebastien Hertza76a6d42014-03-20 16:40:17 +01003008 } else {
3009 // There is at least one breakpoint for this method: we don't need to deoptimize.
3010 req->kind = DeoptimizationRequest::kNothing;
3011 req->method = nullptr;
3012
3013 need_full_deoptimization = existing_breakpoint->need_full_deoptimization;
3014 SanityCheckExistingBreakpoints(m, need_full_deoptimization);
Sebastien Hertz138dbfc2013-12-04 18:15:25 +01003015 }
3016
Sebastien Hertza76a6d42014-03-20 16:40:17 +01003017 gBreakpoints.push_back(Breakpoint(m, location->dex_pc, need_full_deoptimization));
3018 VLOG(jdwp) << "Set breakpoint #" << (gBreakpoints.size() - 1) << ": "
3019 << gBreakpoints[gBreakpoints.size() - 1];
3020}
3021
3022// Uninstalls a breakpoint at the specified location. Also indicates through the deoptimization
3023// request if we need to undeoptimize.
3024void Dbg::UnwatchLocation(const JDWP::JdwpLocation* location, DeoptimizationRequest* req) {
3025 mirror::ArtMethod* m = FromMethodId(location->method_id);
3026 DCHECK(m != nullptr) << "No method for method id " << location->method_id;
3027
3028 MutexLock mu(Thread::Current(), *Locks::breakpoint_lock_);
3029 bool need_full_deoptimization = false;
3030 for (size_t i = 0, e = gBreakpoints.size(); i < e; ++i) {
3031 if (gBreakpoints[i].method == m && gBreakpoints[i].dex_pc == location->dex_pc) {
3032 VLOG(jdwp) << "Removed breakpoint #" << i << ": " << gBreakpoints[i];
3033 need_full_deoptimization = gBreakpoints[i].need_full_deoptimization;
3034 DCHECK_NE(need_full_deoptimization, Runtime::Current()->GetInstrumentation()->IsDeoptimized(m));
3035 gBreakpoints.erase(gBreakpoints.begin() + i);
3036 break;
3037 }
3038 }
3039 const Breakpoint* const existing_breakpoint = FindFirstBreakpointForMethod(m);
3040 if (existing_breakpoint == nullptr) {
3041 // There is no more breakpoint on this method: we need to undeoptimize.
3042 if (need_full_deoptimization) {
3043 // This method required full deoptimization: we need to undeoptimize everything.
3044 req->kind = DeoptimizationRequest::kFullUndeoptimization;
3045 req->method = nullptr;
3046 } else {
3047 // This method required selective deoptimization: we need to undeoptimize only that method.
3048 req->kind = DeoptimizationRequest::kSelectiveUndeoptimization;
3049 req->method = m;
3050 }
3051 } else {
3052 // There is at least one breakpoint for this method: we don't need to undeoptimize.
3053 req->kind = DeoptimizationRequest::kNothing;
3054 req->method = nullptr;
3055 SanityCheckExistingBreakpoints(m, need_full_deoptimization);
Elliott Hughes86964332012-02-15 19:37:42 -08003056 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -07003057}
3058
Jeff Hao449db332013-04-12 18:30:52 -07003059// Scoped utility class to suspend a thread so that we may do tasks such as walk its stack. Doesn't
3060// cause suspension if the thread is the current thread.
3061class ScopedThreadSuspension {
3062 public:
Ian Rogers33e95662013-05-20 20:29:14 -07003063 ScopedThreadSuspension(Thread* self, JDWP::ObjectId thread_id)
Sebastien Hertz52d131d2014-03-13 16:17:40 +01003064 LOCKS_EXCLUDED(Locks::thread_list_lock_)
Ian Rogers33e95662013-05-20 20:29:14 -07003065 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) :
Jeff Hao449db332013-04-12 18:30:52 -07003066 thread_(NULL),
3067 error_(JDWP::ERR_NONE),
3068 self_suspend_(false),
Ian Rogers33e95662013-05-20 20:29:14 -07003069 other_suspend_(false) {
Jeff Hao449db332013-04-12 18:30:52 -07003070 ScopedObjectAccessUnchecked soa(self);
3071 {
3072 MutexLock mu(soa.Self(), *Locks::thread_list_lock_);
3073 error_ = DecodeThread(soa, thread_id, thread_);
3074 }
3075 if (error_ == JDWP::ERR_NONE) {
3076 if (thread_ == soa.Self()) {
3077 self_suspend_ = true;
3078 } else {
3079 soa.Self()->TransitionFromRunnableToSuspended(kWaitingForDebuggerSuspension);
3080 jobject thread_peer = gRegistry->GetJObject(thread_id);
3081 bool timed_out;
Ian Rogersd9c4fc92013-10-01 19:45:43 -07003082 Thread* suspended_thread = ThreadList::SuspendThreadByPeer(thread_peer, true, true,
3083 &timed_out);
Jeff Hao449db332013-04-12 18:30:52 -07003084 CHECK_EQ(soa.Self()->TransitionFromSuspendedToRunnable(), kWaitingForDebuggerSuspension);
3085 if (suspended_thread == NULL) {
3086 // Thread terminated from under us while suspending.
3087 error_ = JDWP::ERR_INVALID_THREAD;
3088 } else {
3089 CHECK_EQ(suspended_thread, thread_);
3090 other_suspend_ = true;
3091 }
3092 }
3093 }
Elliott Hughes2435a572012-02-17 16:07:41 -08003094 }
Elliott Hughes86964332012-02-15 19:37:42 -08003095
Jeff Hao449db332013-04-12 18:30:52 -07003096 Thread* GetThread() const {
3097 return thread_;
3098 }
3099
3100 JDWP::JdwpError GetError() const {
3101 return error_;
3102 }
3103
3104 ~ScopedThreadSuspension() {
3105 if (other_suspend_) {
3106 Runtime::Current()->GetThreadList()->Resume(thread_, true);
3107 }
3108 }
3109
3110 private:
3111 Thread* thread_;
3112 JDWP::JdwpError error_;
3113 bool self_suspend_;
3114 bool other_suspend_;
3115};
3116
3117JDWP::JdwpError Dbg::ConfigureStep(JDWP::ObjectId thread_id, JDWP::JdwpStepSize step_size,
3118 JDWP::JdwpStepDepth step_depth) {
3119 Thread* self = Thread::Current();
3120 ScopedThreadSuspension sts(self, thread_id);
3121 if (sts.GetError() != JDWP::ERR_NONE) {
3122 return sts.GetError();
3123 }
3124
Elliott Hughes2435a572012-02-17 16:07:41 -08003125 //
3126 // Work out what Method* we're in, the current line number, and how deep the stack currently
3127 // is for step-out.
3128 //
3129
Ian Rogers0399dde2012-06-06 17:09:28 -07003130 struct SingleStepStackVisitor : public StackVisitor {
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01003131 explicit SingleStepStackVisitor(Thread* thread, SingleStepControl* single_step_control,
3132 int32_t* line_number)
Ian Rogersb726dcb2012-09-05 08:57:23 -07003133 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_)
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01003134 : StackVisitor(thread, NULL), single_step_control_(single_step_control),
3135 line_number_(line_number) {
3136 DCHECK_EQ(single_step_control_, thread->GetSingleStepControl());
3137 single_step_control_->method = NULL;
3138 single_step_control_->stack_depth = 0;
Elliott Hughes86964332012-02-15 19:37:42 -08003139 }
Ian Rogersca190662012-06-26 15:45:57 -07003140
Ian Rogers00f7d0e2012-07-19 15:28:27 -07003141 // TODO: Enable annotalysis. We know lock is held in constructor, but abstraction confuses
3142 // annotalysis.
3143 bool VisitFrame() NO_THREAD_SAFETY_ANALYSIS {
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01003144 mirror::ArtMethod* m = GetMethod();
Ian Rogers0399dde2012-06-06 17:09:28 -07003145 if (!m->IsRuntimeMethod()) {
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01003146 ++single_step_control_->stack_depth;
3147 if (single_step_control_->method == NULL) {
Ian Rogersef7d42f2014-01-06 12:55:46 -08003148 mirror::DexCache* dex_cache = m->GetDeclaringClass()->GetDexCache();
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01003149 single_step_control_->method = m;
3150 *line_number_ = -1;
Elliott Hughes2435a572012-02-17 16:07:41 -08003151 if (dex_cache != NULL) {
Ian Rogers4445a7e2012-10-05 17:19:13 -07003152 const DexFile& dex_file = *dex_cache->GetDexFile();
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01003153 *line_number_ = dex_file.GetLineNumFromPC(m, GetDexPc());
Elliott Hughes2435a572012-02-17 16:07:41 -08003154 }
Elliott Hughes86964332012-02-15 19:37:42 -08003155 }
3156 }
Elliott Hughes530fa002012-03-12 11:44:49 -07003157 return true;
Elliott Hughes86964332012-02-15 19:37:42 -08003158 }
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01003159
3160 SingleStepControl* const single_step_control_;
3161 int32_t* const line_number_;
Elliott Hughes86964332012-02-15 19:37:42 -08003162 };
Jeff Hao449db332013-04-12 18:30:52 -07003163
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01003164 Thread* const thread = sts.GetThread();
3165 SingleStepControl* const single_step_control = thread->GetSingleStepControl();
3166 DCHECK(single_step_control != nullptr);
3167 int32_t line_number = -1;
3168 SingleStepStackVisitor visitor(thread, single_step_control, &line_number);
Ian Rogers0399dde2012-06-06 17:09:28 -07003169 visitor.WalkStack();
Elliott Hughes86964332012-02-15 19:37:42 -08003170
Elliott Hughes2435a572012-02-17 16:07:41 -08003171 //
3172 // Find the dex_pc values that correspond to the current line, for line-based single-stepping.
3173 //
3174
3175 struct DebugCallbackContext {
Sebastien Hertzbb43b432014-04-14 11:59:08 +02003176 explicit DebugCallbackContext(SingleStepControl* single_step_control, int32_t line_number,
3177 const DexFile::CodeItem* code_item)
3178 : single_step_control_(single_step_control), line_number_(line_number), code_item_(code_item),
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01003179 last_pc_valid(false), last_pc(0) {
Elliott Hughes2435a572012-02-17 16:07:41 -08003180 }
3181
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01003182 static bool Callback(void* raw_context, uint32_t address, uint32_t line_number) {
Elliott Hughes2435a572012-02-17 16:07:41 -08003183 DebugCallbackContext* context = reinterpret_cast<DebugCallbackContext*>(raw_context);
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01003184 if (static_cast<int32_t>(line_number) == context->line_number_) {
Elliott Hughes2435a572012-02-17 16:07:41 -08003185 if (!context->last_pc_valid) {
3186 // Everything from this address until the next line change is ours.
3187 context->last_pc = address;
3188 context->last_pc_valid = true;
3189 }
3190 // Otherwise, if we're already in a valid range for this line,
3191 // just keep going (shouldn't really happen)...
Brian Carlstrom7934ac22013-07-26 10:54:15 -07003192 } else if (context->last_pc_valid) { // and the line number is new
Elliott Hughes2435a572012-02-17 16:07:41 -08003193 // Add everything from the last entry up until here to the set
3194 for (uint32_t dex_pc = context->last_pc; dex_pc < address; ++dex_pc) {
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01003195 context->single_step_control_->dex_pcs.insert(dex_pc);
Elliott Hughes2435a572012-02-17 16:07:41 -08003196 }
3197 context->last_pc_valid = false;
3198 }
Brian Carlstrom7934ac22013-07-26 10:54:15 -07003199 return false; // There may be multiple entries for any given line.
Elliott Hughes2435a572012-02-17 16:07:41 -08003200 }
3201
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01003202 ~DebugCallbackContext() {
Elliott Hughes2435a572012-02-17 16:07:41 -08003203 // If the line number was the last in the position table...
3204 if (last_pc_valid) {
Sebastien Hertzbb43b432014-04-14 11:59:08 +02003205 size_t end = code_item_->insns_size_in_code_units_;
Elliott Hughes2435a572012-02-17 16:07:41 -08003206 for (uint32_t dex_pc = last_pc; dex_pc < end; ++dex_pc) {
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01003207 single_step_control_->dex_pcs.insert(dex_pc);
Elliott Hughes2435a572012-02-17 16:07:41 -08003208 }
3209 }
3210 }
3211
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01003212 SingleStepControl* const single_step_control_;
3213 const int32_t line_number_;
Sebastien Hertzbb43b432014-04-14 11:59:08 +02003214 const DexFile::CodeItem* const code_item_;
Elliott Hughes2435a572012-02-17 16:07:41 -08003215 bool last_pc_valid;
3216 uint32_t last_pc;
3217 };
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01003218 single_step_control->dex_pcs.clear();
Ian Rogersef7d42f2014-01-06 12:55:46 -08003219 mirror::ArtMethod* m = single_step_control->method;
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01003220 if (!m->IsNative()) {
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07003221 const DexFile::CodeItem* const code_item = m->GetCodeItem();
Sebastien Hertzbb43b432014-04-14 11:59:08 +02003222 DebugCallbackContext context(single_step_control, line_number, code_item);
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07003223 m->GetDexFile()->DecodeDebugInfo(code_item, m->IsStatic(), m->GetDexMethodIndex(),
3224 DebugCallbackContext::Callback, NULL, &context);
Elliott Hughes3e2e1a22012-02-21 11:33:41 -08003225 }
Elliott Hughes2435a572012-02-17 16:07:41 -08003226
3227 //
3228 // Everything else...
3229 //
3230
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01003231 single_step_control->step_size = step_size;
3232 single_step_control->step_depth = step_depth;
3233 single_step_control->is_active = true;
Elliott Hughes86964332012-02-15 19:37:42 -08003234
Elliott Hughes2435a572012-02-17 16:07:41 -08003235 if (VLOG_IS_ON(jdwp)) {
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01003236 VLOG(jdwp) << "Single-step thread: " << *thread;
3237 VLOG(jdwp) << "Single-step step size: " << single_step_control->step_size;
3238 VLOG(jdwp) << "Single-step step depth: " << single_step_control->step_depth;
3239 VLOG(jdwp) << "Single-step current method: " << PrettyMethod(single_step_control->method);
3240 VLOG(jdwp) << "Single-step current line: " << line_number;
3241 VLOG(jdwp) << "Single-step current stack depth: " << single_step_control->stack_depth;
Elliott Hughes2435a572012-02-17 16:07:41 -08003242 VLOG(jdwp) << "Single-step dex_pc values:";
Sebastien Hertzbb43b432014-04-14 11:59:08 +02003243 for (uint32_t dex_pc : single_step_control->dex_pcs) {
3244 VLOG(jdwp) << StringPrintf(" %#x", dex_pc);
Elliott Hughes2435a572012-02-17 16:07:41 -08003245 }
3246 }
3247
3248 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07003249}
3250
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01003251void Dbg::UnconfigureStep(JDWP::ObjectId thread_id) {
3252 ScopedObjectAccessUnchecked soa(Thread::Current());
3253 MutexLock mu(soa.Self(), *Locks::thread_list_lock_);
3254 Thread* thread;
3255 JDWP::JdwpError error = DecodeThread(soa, thread_id, thread);
Sebastien Hertz87118ed2013-11-26 17:57:18 +01003256 if (error == JDWP::ERR_NONE) {
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01003257 SingleStepControl* single_step_control = thread->GetSingleStepControl();
3258 DCHECK(single_step_control != nullptr);
Sebastien Hertzbb43b432014-04-14 11:59:08 +02003259 single_step_control->Clear();
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01003260 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -07003261}
3262
Elliott Hughes45651fd2012-02-21 15:48:20 -08003263static char JdwpTagToShortyChar(JDWP::JdwpTag tag) {
3264 switch (tag) {
3265 default:
3266 LOG(FATAL) << "unknown JDWP tag: " << PrintableChar(tag);
3267
3268 // Primitives.
3269 case JDWP::JT_BYTE: return 'B';
3270 case JDWP::JT_CHAR: return 'C';
3271 case JDWP::JT_FLOAT: return 'F';
3272 case JDWP::JT_DOUBLE: return 'D';
3273 case JDWP::JT_INT: return 'I';
3274 case JDWP::JT_LONG: return 'J';
3275 case JDWP::JT_SHORT: return 'S';
3276 case JDWP::JT_VOID: return 'V';
3277 case JDWP::JT_BOOLEAN: return 'Z';
3278
3279 // Reference types.
3280 case JDWP::JT_ARRAY:
3281 case JDWP::JT_OBJECT:
3282 case JDWP::JT_STRING:
3283 case JDWP::JT_THREAD:
3284 case JDWP::JT_THREAD_GROUP:
3285 case JDWP::JT_CLASS_LOADER:
3286 case JDWP::JT_CLASS_OBJECT:
3287 return 'L';
3288 }
3289}
3290
Elliott Hughes88d63092013-01-09 09:55:54 -08003291JDWP::JdwpError Dbg::InvokeMethod(JDWP::ObjectId thread_id, JDWP::ObjectId object_id,
3292 JDWP::RefTypeId class_id, JDWP::MethodId method_id,
Ian Rogers00f7d0e2012-07-19 15:28:27 -07003293 uint32_t arg_count, uint64_t* arg_values,
3294 JDWP::JdwpTag* arg_types, uint32_t options,
3295 JDWP::JdwpTag* pResultTag, uint64_t* pResultValue,
3296 JDWP::ObjectId* pExceptionId) {
Elliott Hughesd07986f2011-12-06 18:27:45 -08003297 ThreadList* thread_list = Runtime::Current()->GetThreadList();
3298
3299 Thread* targetThread = NULL;
3300 DebugInvokeReq* req = NULL;
Ian Rogers00f7d0e2012-07-19 15:28:27 -07003301 Thread* self = Thread::Current();
Elliott Hughesd07986f2011-12-06 18:27:45 -08003302 {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07003303 ScopedObjectAccessUnchecked soa(self);
Ian Rogers50b35e22012-10-04 10:09:15 -07003304 MutexLock mu(soa.Self(), *Locks::thread_list_lock_);
Elliott Hughes221229c2013-01-08 18:17:50 -08003305 JDWP::JdwpError error = DecodeThread(soa, thread_id, targetThread);
3306 if (error != JDWP::ERR_NONE) {
3307 LOG(ERROR) << "InvokeMethod request for invalid thread id " << thread_id;
3308 return error;
Elliott Hughesd07986f2011-12-06 18:27:45 -08003309 }
3310 req = targetThread->GetInvokeReq();
3311 if (!req->ready) {
3312 LOG(ERROR) << "InvokeMethod request for thread not stopped by event: " << *targetThread;
3313 return JDWP::ERR_INVALID_THREAD;
3314 }
3315
3316 /*
3317 * We currently have a bug where we don't successfully resume the
3318 * target thread if the suspend count is too deep. We're expected to
3319 * require one "resume" for each "suspend", but when asked to execute
3320 * a method we have to resume fully and then re-suspend it back to the
3321 * same level. (The easiest way to cause this is to type "suspend"
3322 * multiple times in jdb.)
3323 *
3324 * It's unclear what this means when the event specifies "resume all"
3325 * and some threads are suspended more deeply than others. This is
3326 * a rare problem, so for now we just prevent it from hanging forever
3327 * by rejecting the method invocation request. Without this, we will
3328 * be stuck waiting on a suspended thread.
3329 */
Ian Rogers00f7d0e2012-07-19 15:28:27 -07003330 int suspend_count;
3331 {
Ian Rogers50b35e22012-10-04 10:09:15 -07003332 MutexLock mu2(soa.Self(), *Locks::thread_suspend_count_lock_);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07003333 suspend_count = targetThread->GetSuspendCount();
3334 }
Elliott Hughesd07986f2011-12-06 18:27:45 -08003335 if (suspend_count > 1) {
3336 LOG(ERROR) << *targetThread << " suspend count too deep for method invocation: " << suspend_count;
Brian Carlstrom7934ac22013-07-26 10:54:15 -07003337 return JDWP::ERR_THREAD_SUSPENDED; // Probably not expected here.
Elliott Hughesd07986f2011-12-06 18:27:45 -08003338 }
3339
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08003340 JDWP::JdwpError status;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003341 mirror::Object* receiver = gRegistry->Get<mirror::Object*>(object_id);
Elliott Hughes64f574f2013-02-20 14:57:12 -08003342 if (receiver == ObjectRegistry::kInvalidObject) {
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08003343 return JDWP::ERR_INVALID_OBJECT;
3344 }
Elliott Hughes45651fd2012-02-21 15:48:20 -08003345
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003346 mirror::Object* thread = gRegistry->Get<mirror::Object*>(thread_id);
Elliott Hughes64f574f2013-02-20 14:57:12 -08003347 if (thread == ObjectRegistry::kInvalidObject) {
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08003348 return JDWP::ERR_INVALID_OBJECT;
3349 }
Elliott Hughes45651fd2012-02-21 15:48:20 -08003350 // TODO: check that 'thread' is actually a java.lang.Thread!
3351
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003352 mirror::Class* c = DecodeClass(class_id, status);
Elliott Hughes45651fd2012-02-21 15:48:20 -08003353 if (c == NULL) {
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08003354 return status;
3355 }
Elliott Hughes45651fd2012-02-21 15:48:20 -08003356
Brian Carlstromea46f952013-07-30 01:26:50 -07003357 mirror::ArtMethod* m = FromMethodId(method_id);
Elliott Hughes45651fd2012-02-21 15:48:20 -08003358 if (m->IsStatic() != (receiver == NULL)) {
3359 return JDWP::ERR_INVALID_METHODID;
3360 }
3361 if (m->IsStatic()) {
3362 if (m->GetDeclaringClass() != c) {
3363 return JDWP::ERR_INVALID_METHODID;
3364 }
3365 } else {
3366 if (!m->GetDeclaringClass()->IsAssignableFrom(c)) {
3367 return JDWP::ERR_INVALID_METHODID;
3368 }
3369 }
3370
3371 // Check the argument list matches the method.
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07003372 uint32_t shorty_len = 0;
3373 const char* shorty = m->GetShorty(&shorty_len);
3374 if (shorty_len - 1 != arg_count) {
Elliott Hughes45651fd2012-02-21 15:48:20 -08003375 return JDWP::ERR_ILLEGAL_ARGUMENT;
3376 }
Elliott Hughes09201632013-04-15 15:50:07 -07003377
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07003378 {
3379 StackHandleScope<3> hs(soa.Self());
3380 MethodHelper mh(hs.NewHandle(m));
3381 HandleWrapper<mirror::Object> h_obj(hs.NewHandleWrapper(&receiver));
3382 HandleWrapper<mirror::Class> h_klass(hs.NewHandleWrapper(&c));
3383 const DexFile::TypeList* types = m->GetParameterTypeList();
3384 for (size_t i = 0; i < arg_count; ++i) {
3385 if (shorty[i + 1] != JdwpTagToShortyChar(arg_types[i])) {
Elliott Hughes09201632013-04-15 15:50:07 -07003386 return JDWP::ERR_ILLEGAL_ARGUMENT;
3387 }
3388
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07003389 if (shorty[i + 1] == 'L') {
3390 // Did we really get an argument of an appropriate reference type?
3391 mirror::Class* parameter_type = mh.GetClassFromTypeIdx(types->GetTypeItem(i).type_idx_);
3392 mirror::Object* argument = gRegistry->Get<mirror::Object*>(arg_values[i]);
3393 if (argument == ObjectRegistry::kInvalidObject) {
3394 return JDWP::ERR_INVALID_OBJECT;
3395 }
3396 if (argument != NULL && !argument->InstanceOf(parameter_type)) {
3397 return JDWP::ERR_ILLEGAL_ARGUMENT;
3398 }
3399
3400 // Turn the on-the-wire ObjectId into a jobject.
3401 jvalue& v = reinterpret_cast<jvalue&>(arg_values[i]);
3402 v.l = gRegistry->GetJObject(arg_values[i]);
3403 }
Elliott Hughes09201632013-04-15 15:50:07 -07003404 }
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07003405 // Update in case it moved.
3406 m = mh.GetMethod();
Elliott Hughes45651fd2012-02-21 15:48:20 -08003407 }
3408
Sebastien Hertzd38667a2013-11-25 15:43:54 +01003409 req->receiver = receiver;
3410 req->thread = thread;
3411 req->klass = c;
3412 req->method = m;
3413 req->arg_count = arg_count;
3414 req->arg_values = arg_values;
3415 req->options = options;
3416 req->invoke_needed = true;
Elliott Hughesd07986f2011-12-06 18:27:45 -08003417 }
3418
3419 // The fact that we've released the thread list lock is a bit risky --- if the thread goes
3420 // away we're sitting high and dry -- but we must release this before the ResumeAllThreads
3421 // call, and it's unwise to hold it during WaitForSuspend.
3422
3423 {
3424 /*
3425 * We change our (JDWP thread) status, which should be THREAD_RUNNING,
Elliott Hughes81ff3182012-03-23 20:35:56 -07003426 * so we can suspend for a GC if the invoke request causes us to
Elliott Hughesd07986f2011-12-06 18:27:45 -08003427 * run out of memory. It's also a good idea to change it before locking
3428 * the invokeReq mutex, although that should never be held for long.
3429 */
Ian Rogers00f7d0e2012-07-19 15:28:27 -07003430 self->TransitionFromRunnableToSuspended(kWaitingForDebuggerSend);
Elliott Hughesd07986f2011-12-06 18:27:45 -08003431
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08003432 VLOG(jdwp) << " Transferring control to event thread";
Elliott Hughesd07986f2011-12-06 18:27:45 -08003433 {
Sebastien Hertzd38667a2013-11-25 15:43:54 +01003434 MutexLock mu(self, req->lock);
Elliott Hughesd07986f2011-12-06 18:27:45 -08003435
3436 if ((options & JDWP::INVOKE_SINGLE_THREADED) == 0) {
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08003437 VLOG(jdwp) << " Resuming all threads";
Ian Rogers00f7d0e2012-07-19 15:28:27 -07003438 thread_list->UndoDebuggerSuspensions();
Elliott Hughesd07986f2011-12-06 18:27:45 -08003439 } else {
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08003440 VLOG(jdwp) << " Resuming event thread only";
Elliott Hughesd07986f2011-12-06 18:27:45 -08003441 thread_list->Resume(targetThread, true);
3442 }
3443
3444 // Wait for the request to finish executing.
Sebastien Hertzd38667a2013-11-25 15:43:54 +01003445 while (req->invoke_needed) {
3446 req->cond.Wait(self);
Elliott Hughesd07986f2011-12-06 18:27:45 -08003447 }
3448 }
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08003449 VLOG(jdwp) << " Control has returned from event thread";
Elliott Hughesd07986f2011-12-06 18:27:45 -08003450
3451 /* wait for thread to re-suspend itself */
Brian Carlstromdf629502013-07-17 22:39:56 -07003452 SuspendThread(thread_id, false /* request_suspension */);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07003453 self->TransitionFromSuspendedToRunnable();
Elliott Hughesd07986f2011-12-06 18:27:45 -08003454 }
3455
3456 /*
3457 * Suspend the threads. We waited for the target thread to suspend
3458 * itself, so all we need to do is suspend the others.
3459 *
3460 * The suspendAllThreads() call will double-suspend the event thread,
3461 * so we want to resume the target thread once to keep the books straight.
3462 */
3463 if ((options & JDWP::INVOKE_SINGLE_THREADED) == 0) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07003464 self->TransitionFromRunnableToSuspended(kWaitingForDebuggerSuspension);
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08003465 VLOG(jdwp) << " Suspending all threads";
Ian Rogers00f7d0e2012-07-19 15:28:27 -07003466 thread_list->SuspendAllForDebugger();
3467 self->TransitionFromSuspendedToRunnable();
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08003468 VLOG(jdwp) << " Resuming event thread to balance the count";
Elliott Hughesd07986f2011-12-06 18:27:45 -08003469 thread_list->Resume(targetThread, true);
3470 }
3471
3472 // Copy the result.
3473 *pResultTag = req->result_tag;
3474 if (IsPrimitiveTag(req->result_tag)) {
Elliott Hughesf24d3ce2012-04-11 17:43:37 -07003475 *pResultValue = req->result_value.GetJ();
Elliott Hughesd07986f2011-12-06 18:27:45 -08003476 } else {
Elliott Hughesf24d3ce2012-04-11 17:43:37 -07003477 *pResultValue = gRegistry->Add(req->result_value.GetL());
Elliott Hughesd07986f2011-12-06 18:27:45 -08003478 }
3479 *pExceptionId = req->exception;
3480 return req->error;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07003481}
3482
3483void Dbg::ExecuteMethod(DebugInvokeReq* pReq) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07003484 ScopedObjectAccess soa(Thread::Current());
Elliott Hughesd07986f2011-12-06 18:27:45 -08003485
Elliott Hughes81ff3182012-03-23 20:35:56 -07003486 // We can be called while an exception is pending. We need
Elliott Hughesd07986f2011-12-06 18:27:45 -08003487 // to preserve that across the method invocation.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003488 StackHandleScope<4> hs(soa.Self());
3489 auto old_throw_this_object = hs.NewHandle<mirror::Object>(nullptr);
3490 auto old_throw_method = hs.NewHandle<mirror::ArtMethod>(nullptr);
3491 auto old_exception = hs.NewHandle<mirror::Throwable>(nullptr);
Ian Rogers62d6c772013-02-27 08:32:07 -08003492 uint32_t old_throw_dex_pc;
Sebastien Hertz9f102032014-05-23 08:59:42 +02003493 bool old_exception_report_flag;
Ian Rogers62d6c772013-02-27 08:32:07 -08003494 {
3495 ThrowLocation old_throw_location;
3496 mirror::Throwable* old_exception_obj = soa.Self()->GetException(&old_throw_location);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003497 old_throw_this_object.Assign(old_throw_location.GetThis());
3498 old_throw_method.Assign(old_throw_location.GetMethod());
3499 old_exception.Assign(old_exception_obj);
Ian Rogers62d6c772013-02-27 08:32:07 -08003500 old_throw_dex_pc = old_throw_location.GetDexPc();
Sebastien Hertz9f102032014-05-23 08:59:42 +02003501 old_exception_report_flag = soa.Self()->IsExceptionReportedToInstrumentation();
Ian Rogers62d6c772013-02-27 08:32:07 -08003502 soa.Self()->ClearException();
3503 }
Elliott Hughesd07986f2011-12-06 18:27:45 -08003504
3505 // Translate the method through the vtable, unless the debugger wants to suppress it.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003506 Handle<mirror::ArtMethod> m(hs.NewHandle(pReq->method));
Sebastien Hertzd38667a2013-11-25 15:43:54 +01003507 if ((pReq->options & JDWP::INVOKE_NONVIRTUAL) == 0 && pReq->receiver != NULL) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003508 mirror::ArtMethod* actual_method = pReq->klass->FindVirtualMethodForVirtualOrInterface(m.Get());
3509 if (actual_method != m.Get()) {
3510 VLOG(jdwp) << "ExecuteMethod translated " << PrettyMethod(m.Get()) << " to " << PrettyMethod(actual_method);
3511 m.Assign(actual_method);
Elliott Hughes45651fd2012-02-21 15:48:20 -08003512 }
Elliott Hughesd07986f2011-12-06 18:27:45 -08003513 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003514 VLOG(jdwp) << "ExecuteMethod " << PrettyMethod(m.Get())
Sebastien Hertzd38667a2013-11-25 15:43:54 +01003515 << " receiver=" << pReq->receiver
3516 << " arg_count=" << pReq->arg_count;
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003517 CHECK(m.Get() != nullptr);
Elliott Hughesd07986f2011-12-06 18:27:45 -08003518
3519 CHECK_EQ(sizeof(jvalue), sizeof(uint64_t));
3520
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003521 pReq->result_value = InvokeWithJValues(soa, pReq->receiver, soa.EncodeMethod(m.Get()),
Ian Rogers53b8b092014-03-13 23:45:53 -07003522 reinterpret_cast<jvalue*>(pReq->arg_values));
Elliott Hughesd07986f2011-12-06 18:27:45 -08003523
Ian Rogers62d6c772013-02-27 08:32:07 -08003524 mirror::Throwable* exception = soa.Self()->GetException(NULL);
3525 soa.Self()->ClearException();
3526 pReq->exception = gRegistry->Add(exception);
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07003527 pReq->result_tag = BasicTagFromDescriptor(m.Get()->GetShorty());
Elliott Hughesd07986f2011-12-06 18:27:45 -08003528 if (pReq->exception != 0) {
Ian Rogers62d6c772013-02-27 08:32:07 -08003529 VLOG(jdwp) << " JDWP invocation returning with exception=" << exception
3530 << " " << exception->Dump();
Elliott Hughesf24d3ce2012-04-11 17:43:37 -07003531 pReq->result_value.SetJ(0);
Elliott Hughesd07986f2011-12-06 18:27:45 -08003532 } else if (pReq->result_tag == JDWP::JT_OBJECT) {
3533 /* if no exception thrown, examine object result more closely */
Ian Rogers98379392014-02-24 16:53:16 -08003534 JDWP::JdwpTag new_tag = TagFromObject(soa, pReq->result_value.GetL());
Elliott Hughesd07986f2011-12-06 18:27:45 -08003535 if (new_tag != pReq->result_tag) {
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08003536 VLOG(jdwp) << " JDWP promoted result from " << pReq->result_tag << " to " << new_tag;
Elliott Hughesd07986f2011-12-06 18:27:45 -08003537 pReq->result_tag = new_tag;
3538 }
3539
3540 /*
3541 * Register the object. We don't actually need an ObjectId yet,
3542 * but we do need to be sure that the GC won't move or discard the
3543 * object when we switch out of RUNNING. The ObjectId conversion
3544 * will add the object to the "do not touch" list.
3545 *
3546 * We can't use the "tracked allocation" mechanism here because
3547 * the object is going to be handed off to a different thread.
3548 */
Elliott Hughesf24d3ce2012-04-11 17:43:37 -07003549 gRegistry->Add(pReq->result_value.GetL());
Elliott Hughesd07986f2011-12-06 18:27:45 -08003550 }
3551
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003552 if (old_exception.Get() != NULL) {
3553 ThrowLocation gc_safe_throw_location(old_throw_this_object.Get(), old_throw_method.Get(),
Ian Rogers62d6c772013-02-27 08:32:07 -08003554 old_throw_dex_pc);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003555 soa.Self()->SetException(gc_safe_throw_location, old_exception.Get());
Sebastien Hertz9f102032014-05-23 08:59:42 +02003556 soa.Self()->SetExceptionReportedToInstrumentation(old_exception_report_flag);
Elliott Hughesd07986f2011-12-06 18:27:45 -08003557 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -07003558}
3559
Elliott Hughesd07986f2011-12-06 18:27:45 -08003560/*
Elliott Hughes4b9702c2013-02-20 18:13:24 -08003561 * "request" contains a full JDWP packet, possibly with multiple chunks. We
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07003562 * need to process each, accumulate the replies, and ship the whole thing
3563 * back.
3564 *
3565 * Returns "true" if we have a reply. The reply buffer is newly allocated,
3566 * and includes the chunk type/length, followed by the data.
3567 *
Elliott Hughes3d30d9b2011-12-07 17:35:48 -08003568 * OLD-TODO: we currently assume that the request and reply include a single
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07003569 * chunk. If this becomes inconvenient we will need to adapt.
3570 */
Elliott Hughes4b9702c2013-02-20 18:13:24 -08003571bool Dbg::DdmHandlePacket(JDWP::Request& request, uint8_t** pReplyBuf, int* pReplyLen) {
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07003572 Thread* self = Thread::Current();
3573 JNIEnv* env = self->GetJniEnv();
3574
Elliott Hughes4b9702c2013-02-20 18:13:24 -08003575 uint32_t type = request.ReadUnsigned32("type");
3576 uint32_t length = request.ReadUnsigned32("length");
3577
3578 // Create a byte[] corresponding to 'request'.
3579 size_t request_length = request.size();
3580 ScopedLocalRef<jbyteArray> dataArray(env, env->NewByteArray(request_length));
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003581 if (dataArray.get() == NULL) {
Elliott Hughes4b9702c2013-02-20 18:13:24 -08003582 LOG(WARNING) << "byte[] allocation failed: " << request_length;
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07003583 env->ExceptionClear();
3584 return false;
3585 }
Elliott Hughes4b9702c2013-02-20 18:13:24 -08003586 env->SetByteArrayRegion(dataArray.get(), 0, request_length, reinterpret_cast<const jbyte*>(request.data()));
3587 request.Skip(request_length);
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07003588
3589 // Run through and find all chunks. [Currently just find the first.]
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003590 ScopedByteArrayRO contents(env, dataArray.get());
Elliott Hughes4b9702c2013-02-20 18:13:24 -08003591 if (length != request_length) {
Ian Rogersef7d42f2014-01-06 12:55:46 -08003592 LOG(WARNING) << StringPrintf("bad chunk found (len=%u pktLen=%zd)", length, request_length);
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07003593 return false;
3594 }
3595
3596 // Call "private static Chunk dispatch(int type, byte[] data, int offset, int length)".
Elliott Hugheseac76672012-05-24 21:56:51 -07003597 ScopedLocalRef<jobject> chunk(env, env->CallStaticObjectMethod(WellKnownClasses::org_apache_harmony_dalvik_ddmc_DdmServer,
3598 WellKnownClasses::org_apache_harmony_dalvik_ddmc_DdmServer_dispatch,
Elliott Hughes4b9702c2013-02-20 18:13:24 -08003599 type, dataArray.get(), 0, length));
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07003600 if (env->ExceptionCheck()) {
3601 LOG(INFO) << StringPrintf("Exception thrown by dispatcher for 0x%08x", type);
3602 env->ExceptionDescribe();
3603 env->ExceptionClear();
3604 return false;
3605 }
3606
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003607 if (chunk.get() == NULL) {
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07003608 return false;
3609 }
3610
3611 /*
3612 * Pull the pieces out of the chunk. We copy the results into a
3613 * newly-allocated buffer that the caller can free. We don't want to
3614 * continue using the Chunk object because nothing has a reference to it.
3615 *
3616 * We could avoid this by returning type/data/offset/length and having
3617 * the caller be aware of the object lifetime issues, but that
Elliott Hughes81ff3182012-03-23 20:35:56 -07003618 * integrates the JDWP code more tightly into the rest of the runtime, and doesn't work
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07003619 * if we have responses for multiple chunks.
3620 *
3621 * So we're pretty much stuck with copying data around multiple times.
3622 */
Elliott Hugheseac76672012-05-24 21:56:51 -07003623 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 -08003624 jint offset = env->GetIntField(chunk.get(), WellKnownClasses::org_apache_harmony_dalvik_ddmc_Chunk_offset);
Elliott Hugheseac76672012-05-24 21:56:51 -07003625 length = env->GetIntField(chunk.get(), WellKnownClasses::org_apache_harmony_dalvik_ddmc_Chunk_length);
Elliott Hugheseac76672012-05-24 21:56:51 -07003626 type = env->GetIntField(chunk.get(), WellKnownClasses::org_apache_harmony_dalvik_ddmc_Chunk_type);
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07003627
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08003628 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 -07003629 if (length == 0 || replyData.get() == NULL) {
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07003630 return false;
3631 }
3632
Elliott Hughes4b9702c2013-02-20 18:13:24 -08003633 const int kChunkHdrLen = 8;
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07003634 uint8_t* reply = new uint8_t[length + kChunkHdrLen];
3635 if (reply == NULL) {
3636 LOG(WARNING) << "malloc failed: " << (length + kChunkHdrLen);
3637 return false;
3638 }
Elliott Hughesf7c3b662011-10-27 12:04:56 -07003639 JDWP::Set4BE(reply + 0, type);
3640 JDWP::Set4BE(reply + 4, length);
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003641 env->GetByteArrayRegion(replyData.get(), offset, length, reinterpret_cast<jbyte*>(reply + kChunkHdrLen));
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07003642
3643 *pReplyBuf = reply;
3644 *pReplyLen = length + kChunkHdrLen;
3645
Elliott Hughes4b9702c2013-02-20 18:13:24 -08003646 VLOG(jdwp) << StringPrintf("dvmHandleDdm returning type=%.4s %p len=%d", reinterpret_cast<char*>(reply), reply, length);
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07003647 return true;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07003648}
3649
Elliott Hughesa2155262011-11-16 16:26:58 -08003650void Dbg::DdmBroadcast(bool connect) {
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08003651 VLOG(jdwp) << "Broadcasting DDM " << (connect ? "connect" : "disconnect") << "...";
Elliott Hughes47fce012011-10-25 18:37:19 -07003652
3653 Thread* self = Thread::Current();
Ian Rogers50b35e22012-10-04 10:09:15 -07003654 if (self->GetState() != kRunnable) {
3655 LOG(ERROR) << "DDM broadcast in thread state " << self->GetState();
3656 /* try anyway? */
Elliott Hughes47fce012011-10-25 18:37:19 -07003657 }
3658
3659 JNIEnv* env = self->GetJniEnv();
Elliott Hughes47fce012011-10-25 18:37:19 -07003660 jint event = connect ? 1 /*DdmServer.CONNECTED*/ : 2 /*DdmServer.DISCONNECTED*/;
Elliott Hugheseac76672012-05-24 21:56:51 -07003661 env->CallStaticVoidMethod(WellKnownClasses::org_apache_harmony_dalvik_ddmc_DdmServer,
3662 WellKnownClasses::org_apache_harmony_dalvik_ddmc_DdmServer_broadcast,
3663 event);
Elliott Hughes47fce012011-10-25 18:37:19 -07003664 if (env->ExceptionCheck()) {
3665 LOG(ERROR) << "DdmServer.broadcast " << event << " failed";
3666 env->ExceptionDescribe();
3667 env->ExceptionClear();
3668 }
3669}
3670
Elliott Hughes872d4ec2011-10-21 17:07:15 -07003671void Dbg::DdmConnected() {
Elliott Hughesa2155262011-11-16 16:26:58 -08003672 Dbg::DdmBroadcast(true);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07003673}
3674
3675void Dbg::DdmDisconnected() {
Elliott Hughesa2155262011-11-16 16:26:58 -08003676 Dbg::DdmBroadcast(false);
Elliott Hughes47fce012011-10-25 18:37:19 -07003677 gDdmThreadNotification = false;
3678}
3679
3680/*
Elliott Hughes82188472011-11-07 18:11:48 -08003681 * Send a notification when a thread starts, stops, or changes its name.
Elliott Hughes47fce012011-10-25 18:37:19 -07003682 *
3683 * Because we broadcast the full set of threads when the notifications are
3684 * first enabled, it's possible for "thread" to be actively executing.
3685 */
Elliott Hughes82188472011-11-07 18:11:48 -08003686void Dbg::DdmSendThreadNotification(Thread* t, uint32_t type) {
Elliott Hughes47fce012011-10-25 18:37:19 -07003687 if (!gDdmThreadNotification) {
3688 return;
3689 }
3690
Elliott Hughes82188472011-11-07 18:11:48 -08003691 if (type == CHUNK_TYPE("THDE")) {
Elliott Hughes47fce012011-10-25 18:37:19 -07003692 uint8_t buf[4];
Ian Rogersd9c4fc92013-10-01 19:45:43 -07003693 JDWP::Set4BE(&buf[0], t->GetThreadId());
Elliott Hughes47fce012011-10-25 18:37:19 -07003694 Dbg::DdmSendChunk(CHUNK_TYPE("THDE"), 4, buf);
Elliott Hughes82188472011-11-07 18:11:48 -08003695 } else {
3696 CHECK(type == CHUNK_TYPE("THCR") || type == CHUNK_TYPE("THNM")) << type;
Ian Rogers00f7d0e2012-07-19 15:28:27 -07003697 ScopedObjectAccessUnchecked soa(Thread::Current());
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003698 StackHandleScope<1> hs(soa.Self());
3699 Handle<mirror::String> name(hs.NewHandle(t->GetThreadName(soa)));
3700 size_t char_count = (name.Get() != NULL) ? name->GetLength() : 0;
3701 const jchar* chars = (name.Get() != NULL) ? name->GetCharArray()->GetData() : NULL;
Elliott Hughes82188472011-11-07 18:11:48 -08003702
Elliott Hughes21f32d72011-11-09 17:44:13 -08003703 std::vector<uint8_t> bytes;
Ian Rogersd9c4fc92013-10-01 19:45:43 -07003704 JDWP::Append4BE(bytes, t->GetThreadId());
Elliott Hughes545a0642011-11-08 19:10:03 -08003705 JDWP::AppendUtf16BE(bytes, chars, char_count);
Elliott Hughes21f32d72011-11-09 17:44:13 -08003706 CHECK_EQ(bytes.size(), char_count*2 + sizeof(uint32_t)*2);
3707 Dbg::DdmSendChunk(type, bytes);
Elliott Hughes47fce012011-10-25 18:37:19 -07003708 }
3709}
3710
Elliott Hughes47fce012011-10-25 18:37:19 -07003711void Dbg::DdmSetThreadNotification(bool enable) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07003712 // Enable/disable thread notifications.
Elliott Hughes47fce012011-10-25 18:37:19 -07003713 gDdmThreadNotification = enable;
3714 if (enable) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07003715 // Suspend the VM then post thread start notifications for all threads. Threads attaching will
3716 // see a suspension in progress and block until that ends. They then post their own start
3717 // notification.
3718 SuspendVM();
3719 std::list<Thread*> threads;
Ian Rogers50b35e22012-10-04 10:09:15 -07003720 Thread* self = Thread::Current();
Ian Rogers00f7d0e2012-07-19 15:28:27 -07003721 {
Ian Rogers50b35e22012-10-04 10:09:15 -07003722 MutexLock mu(self, *Locks::thread_list_lock_);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07003723 threads = Runtime::Current()->GetThreadList()->GetList();
3724 }
3725 {
Ian Rogers50b35e22012-10-04 10:09:15 -07003726 ScopedObjectAccess soa(self);
Mathieu Chartier02e25112013-08-14 16:14:24 -07003727 for (Thread* thread : threads) {
3728 Dbg::DdmSendThreadNotification(thread, CHUNK_TYPE("THCR"));
Ian Rogers00f7d0e2012-07-19 15:28:27 -07003729 }
3730 }
3731 ResumeVM();
Elliott Hughes47fce012011-10-25 18:37:19 -07003732 }
3733}
3734
Elliott Hughesa2155262011-11-16 16:26:58 -08003735void Dbg::PostThreadStartOrStop(Thread* t, uint32_t type) {
Elliott Hughesc0f09332012-03-26 13:27:06 -07003736 if (IsDebuggerActive()) {
Mathieu Chartierdbe6f462012-09-25 16:54:50 -07003737 ScopedObjectAccessUnchecked soa(Thread::Current());
Ian Rogerscfaa4552012-11-26 21:00:08 -08003738 JDWP::ObjectId id = gRegistry->Add(t->GetPeer());
Elliott Hughes82188472011-11-07 18:11:48 -08003739 gJdwpState->PostThreadChange(id, type == CHUNK_TYPE("THCR"));
Elliott Hughes47fce012011-10-25 18:37:19 -07003740 }
Elliott Hughes82188472011-11-07 18:11:48 -08003741 Dbg::DdmSendThreadNotification(t, type);
Elliott Hughes47fce012011-10-25 18:37:19 -07003742}
3743
3744void Dbg::PostThreadStart(Thread* t) {
Elliott Hughesa2155262011-11-16 16:26:58 -08003745 Dbg::PostThreadStartOrStop(t, CHUNK_TYPE("THCR"));
Elliott Hughes47fce012011-10-25 18:37:19 -07003746}
3747
3748void Dbg::PostThreadDeath(Thread* t) {
Elliott Hughesa2155262011-11-16 16:26:58 -08003749 Dbg::PostThreadStartOrStop(t, CHUNK_TYPE("THDE"));
Elliott Hughes872d4ec2011-10-21 17:07:15 -07003750}
3751
Elliott Hughes82188472011-11-07 18:11:48 -08003752void Dbg::DdmSendChunk(uint32_t type, size_t byte_count, const uint8_t* buf) {
Elliott Hughes3bb81562011-10-21 18:52:59 -07003753 CHECK(buf != NULL);
3754 iovec vec[1];
3755 vec[0].iov_base = reinterpret_cast<void*>(const_cast<uint8_t*>(buf));
3756 vec[0].iov_len = byte_count;
3757 Dbg::DdmSendChunkV(type, vec, 1);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07003758}
3759
Elliott Hughes21f32d72011-11-09 17:44:13 -08003760void Dbg::DdmSendChunk(uint32_t type, const std::vector<uint8_t>& bytes) {
3761 DdmSendChunk(type, bytes.size(), &bytes[0]);
3762}
3763
Brian Carlstromf5293522013-07-19 00:24:00 -07003764void Dbg::DdmSendChunkV(uint32_t type, const iovec* iov, int iov_count) {
Elliott Hughes3bb81562011-10-21 18:52:59 -07003765 if (gJdwpState == NULL) {
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08003766 VLOG(jdwp) << "Debugger thread not active, ignoring DDM send: " << type;
Elliott Hughes3bb81562011-10-21 18:52:59 -07003767 } else {
Elliott Hughescccd84f2011-12-05 16:51:54 -08003768 gJdwpState->DdmSendChunkV(type, iov, iov_count);
Elliott Hughes3bb81562011-10-21 18:52:59 -07003769 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -07003770}
3771
Elliott Hughes767a1472011-10-26 18:49:02 -07003772int Dbg::DdmHandleHpifChunk(HpifWhen when) {
3773 if (when == HPIF_WHEN_NOW) {
Elliott Hughes7162ad92011-10-27 14:08:42 -07003774 DdmSendHeapInfo(when);
Elliott Hughes767a1472011-10-26 18:49:02 -07003775 return true;
3776 }
3777
3778 if (when != HPIF_WHEN_NEVER && when != HPIF_WHEN_NEXT_GC && when != HPIF_WHEN_EVERY_GC) {
3779 LOG(ERROR) << "invalid HpifWhen value: " << static_cast<int>(when);
3780 return false;
3781 }
3782
3783 gDdmHpifWhen = when;
3784 return true;
3785}
3786
3787bool Dbg::DdmHandleHpsgNhsgChunk(Dbg::HpsgWhen when, Dbg::HpsgWhat what, bool native) {
3788 if (when != HPSG_WHEN_NEVER && when != HPSG_WHEN_EVERY_GC) {
3789 LOG(ERROR) << "invalid HpsgWhen value: " << static_cast<int>(when);
3790 return false;
3791 }
3792
3793 if (what != HPSG_WHAT_MERGED_OBJECTS && what != HPSG_WHAT_DISTINCT_OBJECTS) {
3794 LOG(ERROR) << "invalid HpsgWhat value: " << static_cast<int>(what);
3795 return false;
3796 }
3797
3798 if (native) {
3799 gDdmNhsgWhen = when;
3800 gDdmNhsgWhat = what;
3801 } else {
3802 gDdmHpsgWhen = when;
3803 gDdmHpsgWhat = what;
3804 }
3805 return true;
3806}
3807
Elliott Hughes7162ad92011-10-27 14:08:42 -07003808void Dbg::DdmSendHeapInfo(HpifWhen reason) {
3809 // If there's a one-shot 'when', reset it.
3810 if (reason == gDdmHpifWhen) {
3811 if (gDdmHpifWhen == HPIF_WHEN_NEXT_GC) {
3812 gDdmHpifWhen = HPIF_WHEN_NEVER;
3813 }
3814 }
3815
3816 /*
3817 * Chunk HPIF (client --> server)
3818 *
3819 * Heap Info. General information about the heap,
3820 * suitable for a summary display.
3821 *
3822 * [u4]: number of heaps
3823 *
3824 * For each heap:
3825 * [u4]: heap ID
3826 * [u8]: timestamp in ms since Unix epoch
3827 * [u1]: capture reason (same as 'when' value from server)
3828 * [u4]: max heap size in bytes (-Xmx)
3829 * [u4]: current heap size in bytes
3830 * [u4]: current number of bytes allocated
3831 * [u4]: current number of objects allocated
3832 */
3833 uint8_t heap_count = 1;
Ian Rogers1d54e732013-05-02 21:10:01 -07003834 gc::Heap* heap = Runtime::Current()->GetHeap();
Elliott Hughes21f32d72011-11-09 17:44:13 -08003835 std::vector<uint8_t> bytes;
Elliott Hughes545a0642011-11-08 19:10:03 -08003836 JDWP::Append4BE(bytes, heap_count);
Brian Carlstrom7934ac22013-07-26 10:54:15 -07003837 JDWP::Append4BE(bytes, 1); // Heap id (bogus; we only have one heap).
Elliott Hughes545a0642011-11-08 19:10:03 -08003838 JDWP::Append8BE(bytes, MilliTime());
3839 JDWP::Append1BE(bytes, reason);
Brian Carlstrom7934ac22013-07-26 10:54:15 -07003840 JDWP::Append4BE(bytes, heap->GetMaxMemory()); // Max allowed heap size in bytes.
3841 JDWP::Append4BE(bytes, heap->GetTotalMemory()); // Current heap size in bytes.
Elliott Hughesb3bd5f02012-03-08 21:05:27 -08003842 JDWP::Append4BE(bytes, heap->GetBytesAllocated());
3843 JDWP::Append4BE(bytes, heap->GetObjectsAllocated());
Elliott Hughes21f32d72011-11-09 17:44:13 -08003844 CHECK_EQ(bytes.size(), 4U + (heap_count * (4 + 8 + 1 + 4 + 4 + 4 + 4)));
3845 Dbg::DdmSendChunk(CHUNK_TYPE("HPIF"), bytes);
Elliott Hughes767a1472011-10-26 18:49:02 -07003846}
3847
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003848enum HpsgSolidity {
3849 SOLIDITY_FREE = 0,
3850 SOLIDITY_HARD = 1,
3851 SOLIDITY_SOFT = 2,
3852 SOLIDITY_WEAK = 3,
3853 SOLIDITY_PHANTOM = 4,
3854 SOLIDITY_FINALIZABLE = 5,
3855 SOLIDITY_SWEEP = 6,
3856};
3857
3858enum HpsgKind {
3859 KIND_OBJECT = 0,
3860 KIND_CLASS_OBJECT = 1,
3861 KIND_ARRAY_1 = 2,
3862 KIND_ARRAY_2 = 3,
3863 KIND_ARRAY_4 = 4,
3864 KIND_ARRAY_8 = 5,
3865 KIND_UNKNOWN = 6,
3866 KIND_NATIVE = 7,
3867};
3868
3869#define HPSG_PARTIAL (1<<7)
3870#define HPSG_STATE(solidity, kind) ((uint8_t)((((kind) & 0x7) << 3) | ((solidity) & 0x7)))
3871
Ian Rogers30fab402012-01-23 15:43:46 -08003872class HeapChunkContext {
3873 public:
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003874 // Maximum chunk size. Obtain this from the formula:
3875 // (((maximum_heap_size / ALLOCATION_UNIT_SIZE) + 255) / 256) * 2
3876 HeapChunkContext(bool merge, bool native)
Ian Rogers30fab402012-01-23 15:43:46 -08003877 : buf_(16384 - 16),
3878 type_(0),
3879 merge_(merge) {
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003880 Reset();
3881 if (native) {
Ian Rogers30fab402012-01-23 15:43:46 -08003882 type_ = CHUNK_TYPE("NHSG");
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003883 } else {
Ian Rogers30fab402012-01-23 15:43:46 -08003884 type_ = merge ? CHUNK_TYPE("HPSG") : CHUNK_TYPE("HPSO");
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003885 }
3886 }
3887
3888 ~HeapChunkContext() {
Ian Rogers30fab402012-01-23 15:43:46 -08003889 if (p_ > &buf_[0]) {
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003890 Flush();
3891 }
3892 }
3893
3894 void EnsureHeader(const void* chunk_ptr) {
Ian Rogers30fab402012-01-23 15:43:46 -08003895 if (!needHeader_) {
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003896 return;
3897 }
3898
3899 // Start a new HPSx chunk.
Brian Carlstrom7934ac22013-07-26 10:54:15 -07003900 JDWP::Write4BE(&p_, 1); // Heap id (bogus; we only have one heap).
3901 JDWP::Write1BE(&p_, 8); // Size of allocation unit, in bytes.
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003902
Brian Carlstrom7934ac22013-07-26 10:54:15 -07003903 JDWP::Write4BE(&p_, reinterpret_cast<uintptr_t>(chunk_ptr)); // virtual address of segment start.
3904 JDWP::Write4BE(&p_, 0); // offset of this piece (relative to the virtual address).
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003905 // [u4]: length of piece, in allocation units
3906 // 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 -08003907 pieceLenField_ = p_;
3908 JDWP::Write4BE(&p_, 0x55555555);
3909 needHeader_ = false;
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003910 }
3911
Ian Rogersb726dcb2012-09-05 08:57:23 -07003912 void Flush() SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Ian Rogersd636b062013-01-18 17:51:18 -08003913 if (pieceLenField_ == NULL) {
3914 // Flush immediately post Reset (maybe back-to-back Flush). Ignore.
3915 CHECK(needHeader_);
3916 return;
3917 }
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003918 // Patch the "length of piece" field.
Ian Rogers30fab402012-01-23 15:43:46 -08003919 CHECK_LE(&buf_[0], pieceLenField_);
3920 CHECK_LE(pieceLenField_, p_);
3921 JDWP::Set4BE(pieceLenField_, totalAllocationUnits_);
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003922
Ian Rogers30fab402012-01-23 15:43:46 -08003923 Dbg::DdmSendChunk(type_, p_ - &buf_[0], &buf_[0]);
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003924 Reset();
3925 }
3926
Ian Rogers00f7d0e2012-07-19 15:28:27 -07003927 static void HeapChunkCallback(void* start, void* end, size_t used_bytes, void* arg)
Ian Rogersb726dcb2012-09-05 08:57:23 -07003928 SHARED_LOCKS_REQUIRED(Locks::heap_bitmap_lock_,
3929 Locks::mutator_lock_) {
Ian Rogers30fab402012-01-23 15:43:46 -08003930 reinterpret_cast<HeapChunkContext*>(arg)->HeapChunkCallback(start, end, used_bytes);
Elliott Hughesa2155262011-11-16 16:26:58 -08003931 }
3932
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003933 private:
Elliott Hughesa2155262011-11-16 16:26:58 -08003934 enum { ALLOCATION_UNIT_SIZE = 8 };
3935
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003936 void Reset() {
Ian Rogers30fab402012-01-23 15:43:46 -08003937 p_ = &buf_[0];
Ian Rogers15bf2d32012-08-28 17:33:04 -07003938 startOfNextMemoryChunk_ = NULL;
Ian Rogers30fab402012-01-23 15:43:46 -08003939 totalAllocationUnits_ = 0;
3940 needHeader_ = true;
3941 pieceLenField_ = NULL;
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003942 }
3943
Ian Rogers00f7d0e2012-07-19 15:28:27 -07003944 void HeapChunkCallback(void* start, void* /*end*/, size_t used_bytes)
Ian Rogersb726dcb2012-09-05 08:57:23 -07003945 SHARED_LOCKS_REQUIRED(Locks::heap_bitmap_lock_,
3946 Locks::mutator_lock_) {
Ian Rogers30fab402012-01-23 15:43:46 -08003947 // Note: heap call backs cannot manipulate the heap upon which they are crawling, care is taken
3948 // in the following code not to allocate memory, by ensuring buf_ is of the correct size
Ian Rogers15bf2d32012-08-28 17:33:04 -07003949 if (used_bytes == 0) {
3950 if (start == NULL) {
3951 // Reset for start of new heap.
3952 startOfNextMemoryChunk_ = NULL;
3953 Flush();
3954 }
3955 // Only process in use memory so that free region information
3956 // also includes dlmalloc book keeping.
Elliott Hughesa2155262011-11-16 16:26:58 -08003957 return;
Elliott Hughesa2155262011-11-16 16:26:58 -08003958 }
3959
Ian Rogers15bf2d32012-08-28 17:33:04 -07003960 /* If we're looking at the native heap, we'll just return
3961 * (SOLIDITY_HARD, KIND_NATIVE) for all allocated chunks
3962 */
3963 bool native = type_ == CHUNK_TYPE("NHSG");
3964
3965 if (startOfNextMemoryChunk_ != NULL) {
3966 // Transmit any pending free memory. Native free memory of
3967 // over kMaxFreeLen could be because of the use of mmaps, so
3968 // don't report. If not free memory then start a new segment.
3969 bool flush = true;
3970 if (start > startOfNextMemoryChunk_) {
3971 const size_t kMaxFreeLen = 2 * kPageSize;
3972 void* freeStart = startOfNextMemoryChunk_;
3973 void* freeEnd = start;
Brian Carlstrom2d888622013-07-18 17:02:00 -07003974 size_t freeLen = reinterpret_cast<char*>(freeEnd) - reinterpret_cast<char*>(freeStart);
Ian Rogers15bf2d32012-08-28 17:33:04 -07003975 if (!native || freeLen < kMaxFreeLen) {
3976 AppendChunk(HPSG_STATE(SOLIDITY_FREE, 0), freeStart, freeLen);
3977 flush = false;
3978 }
3979 }
3980 if (flush) {
3981 startOfNextMemoryChunk_ = NULL;
3982 Flush();
3983 }
3984 }
Ian Rogersef7d42f2014-01-06 12:55:46 -08003985 mirror::Object* obj = reinterpret_cast<mirror::Object*>(start);
Elliott Hughesa2155262011-11-16 16:26:58 -08003986
3987 // Determine the type of this chunk.
3988 // OLD-TODO: if context.merge, see if this chunk is different from the last chunk.
3989 // If it's the same, we should combine them.
Ian Rogers15bf2d32012-08-28 17:33:04 -07003990 uint8_t state = ExamineObject(obj, native);
3991 // dlmalloc's chunk header is 2 * sizeof(size_t), but if the previous chunk is in use for an
3992 // allocation then the first sizeof(size_t) may belong to it.
3993 const size_t dlMallocOverhead = sizeof(size_t);
3994 AppendChunk(state, start, used_bytes + dlMallocOverhead);
Brian Carlstrom2d888622013-07-18 17:02:00 -07003995 startOfNextMemoryChunk_ = reinterpret_cast<char*>(start) + used_bytes + dlMallocOverhead;
Ian Rogers15bf2d32012-08-28 17:33:04 -07003996 }
Elliott Hughesa2155262011-11-16 16:26:58 -08003997
Ian Rogers15bf2d32012-08-28 17:33:04 -07003998 void AppendChunk(uint8_t state, void* ptr, size_t length)
Ian Rogersb726dcb2012-09-05 08:57:23 -07003999 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Ian Rogers15bf2d32012-08-28 17:33:04 -07004000 // Make sure there's enough room left in the buffer.
4001 // We need to use two bytes for every fractional 256 allocation units used by the chunk plus
4002 // 17 bytes for any header.
4003 size_t needed = (((length/ALLOCATION_UNIT_SIZE + 255) / 256) * 2) + 17;
4004 size_t bytesLeft = buf_.size() - (size_t)(p_ - &buf_[0]);
4005 if (bytesLeft < needed) {
4006 Flush();
4007 }
4008
4009 bytesLeft = buf_.size() - (size_t)(p_ - &buf_[0]);
4010 if (bytesLeft < needed) {
4011 LOG(WARNING) << "Chunk is too big to transmit (chunk_len=" << length << ", "
4012 << needed << " bytes)";
4013 return;
4014 }
4015 EnsureHeader(ptr);
Elliott Hughesa2155262011-11-16 16:26:58 -08004016 // Write out the chunk description.
Ian Rogers15bf2d32012-08-28 17:33:04 -07004017 length /= ALLOCATION_UNIT_SIZE; // Convert to allocation units.
4018 totalAllocationUnits_ += length;
4019 while (length > 256) {
Ian Rogers30fab402012-01-23 15:43:46 -08004020 *p_++ = state | HPSG_PARTIAL;
4021 *p_++ = 255; // length - 1
Ian Rogers15bf2d32012-08-28 17:33:04 -07004022 length -= 256;
Elliott Hughesa2155262011-11-16 16:26:58 -08004023 }
Ian Rogers30fab402012-01-23 15:43:46 -08004024 *p_++ = state;
Ian Rogers15bf2d32012-08-28 17:33:04 -07004025 *p_++ = length - 1;
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004026 }
4027
Ian Rogersef7d42f2014-01-06 12:55:46 -08004028 uint8_t ExamineObject(mirror::Object* o, bool is_native_heap)
4029 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_, Locks::heap_bitmap_lock_) {
Elliott Hughesa2155262011-11-16 16:26:58 -08004030 if (o == NULL) {
4031 return HPSG_STATE(SOLIDITY_FREE, 0);
4032 }
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004033
Elliott Hughesa2155262011-11-16 16:26:58 -08004034 // It's an allocated chunk. Figure out what it is.
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004035
Elliott Hughesa2155262011-11-16 16:26:58 -08004036 // If we're looking at the native heap, we'll just return
4037 // (SOLIDITY_HARD, KIND_NATIVE) for all allocated chunks.
Ian Rogers00f7d0e2012-07-19 15:28:27 -07004038 if (is_native_heap) {
Elliott Hughesa2155262011-11-16 16:26:58 -08004039 return HPSG_STATE(SOLIDITY_HARD, KIND_NATIVE);
4040 }
4041
Ian Rogers5bfa60f2012-09-02 21:17:56 -07004042 if (!Runtime::Current()->GetHeap()->IsLiveObjectLocked(o)) {
Ian Rogers15bf2d32012-08-28 17:33:04 -07004043 return HPSG_STATE(SOLIDITY_HARD, KIND_NATIVE);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07004044 }
4045
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08004046 mirror::Class* c = o->GetClass();
Elliott Hughesa2155262011-11-16 16:26:58 -08004047 if (c == NULL) {
4048 // The object was probably just created but hasn't been initialized yet.
4049 return HPSG_STATE(SOLIDITY_HARD, KIND_OBJECT);
4050 }
4051
Mathieu Chartier590fee92013-09-13 13:46:47 -07004052 if (!Runtime::Current()->GetHeap()->IsValidObjectAddress(c)) {
Ian Rogers15bf2d32012-08-28 17:33:04 -07004053 LOG(ERROR) << "Invalid class for managed heap object: " << o << " " << c;
Elliott Hughesa2155262011-11-16 16:26:58 -08004054 return HPSG_STATE(SOLIDITY_HARD, KIND_UNKNOWN);
4055 }
4056
4057 if (c->IsClassClass()) {
4058 return HPSG_STATE(SOLIDITY_HARD, KIND_CLASS_OBJECT);
4059 }
4060
4061 if (c->IsArrayClass()) {
4062 if (o->IsObjectArray()) {
4063 return HPSG_STATE(SOLIDITY_HARD, KIND_ARRAY_4);
4064 }
4065 switch (c->GetComponentSize()) {
4066 case 1: return HPSG_STATE(SOLIDITY_HARD, KIND_ARRAY_1);
4067 case 2: return HPSG_STATE(SOLIDITY_HARD, KIND_ARRAY_2);
4068 case 4: return HPSG_STATE(SOLIDITY_HARD, KIND_ARRAY_4);
4069 case 8: return HPSG_STATE(SOLIDITY_HARD, KIND_ARRAY_8);
4070 }
4071 }
4072
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004073 return HPSG_STATE(SOLIDITY_HARD, KIND_OBJECT);
4074 }
4075
Ian Rogers30fab402012-01-23 15:43:46 -08004076 std::vector<uint8_t> buf_;
4077 uint8_t* p_;
4078 uint8_t* pieceLenField_;
Ian Rogers15bf2d32012-08-28 17:33:04 -07004079 void* startOfNextMemoryChunk_;
Ian Rogers30fab402012-01-23 15:43:46 -08004080 size_t totalAllocationUnits_;
4081 uint32_t type_;
4082 bool merge_;
4083 bool needHeader_;
4084
Elliott Hughesa2155262011-11-16 16:26:58 -08004085 DISALLOW_COPY_AND_ASSIGN(HeapChunkContext);
4086};
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004087
4088void Dbg::DdmSendHeapSegments(bool native) {
4089 Dbg::HpsgWhen when;
4090 Dbg::HpsgWhat what;
4091 if (!native) {
4092 when = gDdmHpsgWhen;
4093 what = gDdmHpsgWhat;
4094 } else {
4095 when = gDdmNhsgWhen;
4096 what = gDdmNhsgWhat;
4097 }
4098 if (when == HPSG_WHEN_NEVER) {
4099 return;
4100 }
4101
4102 // Figure out what kind of chunks we'll be sending.
4103 CHECK(what == HPSG_WHAT_MERGED_OBJECTS || what == HPSG_WHAT_DISTINCT_OBJECTS) << static_cast<int>(what);
4104
4105 // First, send a heap start chunk.
4106 uint8_t heap_id[4];
Brian Carlstrom7934ac22013-07-26 10:54:15 -07004107 JDWP::Set4BE(&heap_id[0], 1); // Heap id (bogus; we only have one heap).
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004108 Dbg::DdmSendChunk(native ? CHUNK_TYPE("NHST") : CHUNK_TYPE("HPST"), sizeof(heap_id), heap_id);
4109
Hiroshi Yamauchicf58d4a2013-09-26 14:21:22 -07004110 Thread* self = Thread::Current();
4111
4112 // To allow the Walk/InspectAll() below to exclusively-lock the
4113 // mutator lock, temporarily release the shared access to the
4114 // mutator lock here by transitioning to the suspended state.
4115 Locks::mutator_lock_->AssertSharedHeld(self);
4116 self->TransitionFromRunnableToSuspended(kSuspended);
4117
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004118 // Send a series of heap segment chunks.
Elliott Hughesa2155262011-11-16 16:26:58 -08004119 HeapChunkContext context((what == HPSG_WHAT_MERGED_OBJECTS), native);
4120 if (native) {
Christopher Ferrisc4ddc042014-05-13 14:47:50 -07004121#ifdef USE_DLMALLOC
Ian Rogers1d54e732013-05-02 21:10:01 -07004122 dlmalloc_inspect_all(HeapChunkContext::HeapChunkCallback, &context);
Christopher Ferrisc4ddc042014-05-13 14:47:50 -07004123#else
4124 UNIMPLEMENTED(WARNING) << "Native heap inspection is only supported with dlmalloc";
4125#endif
Elliott Hughesa2155262011-11-16 16:26:58 -08004126 } else {
Ian Rogers1d54e732013-05-02 21:10:01 -07004127 gc::Heap* heap = Runtime::Current()->GetHeap();
4128 const std::vector<gc::space::ContinuousSpace*>& spaces = heap->GetContinuousSpaces();
Ian Rogers1d54e732013-05-02 21:10:01 -07004129 typedef std::vector<gc::space::ContinuousSpace*>::const_iterator It;
4130 for (It cur = spaces.begin(), end = spaces.end(); cur != end; ++cur) {
Hiroshi Yamauchicf58d4a2013-09-26 14:21:22 -07004131 if ((*cur)->IsMallocSpace()) {
4132 (*cur)->AsMallocSpace()->Walk(HeapChunkContext::HeapChunkCallback, &context);
Mathieu Chartierb062fdd2012-07-03 09:51:48 -07004133 }
4134 }
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -07004135 // Walk the large objects, these are not in the AllocSpace.
4136 heap->GetLargeObjectsSpace()->Walk(HeapChunkContext::HeapChunkCallback, &context);
Elliott Hughesa2155262011-11-16 16:26:58 -08004137 }
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004138
Hiroshi Yamauchicf58d4a2013-09-26 14:21:22 -07004139 // Shared-lock the mutator lock back.
4140 self->TransitionFromSuspendedToRunnable();
4141 Locks::mutator_lock_->AssertSharedHeld(self);
4142
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004143 // Finally, send a heap end chunk.
4144 Dbg::DdmSendChunk(native ? CHUNK_TYPE("NHEN") : CHUNK_TYPE("HPEN"), sizeof(heap_id), heap_id);
Elliott Hughes767a1472011-10-26 18:49:02 -07004145}
4146
Elliott Hughesb1a58792013-07-11 18:10:58 -07004147static size_t GetAllocTrackerMax() {
4148#ifdef HAVE_ANDROID_OS
4149 // Check whether there's a system property overriding the number of records.
4150 const char* propertyName = "dalvik.vm.allocTrackerMax";
4151 char allocRecordMaxString[PROPERTY_VALUE_MAX];
4152 if (property_get(propertyName, allocRecordMaxString, "") > 0) {
4153 char* end;
4154 size_t value = strtoul(allocRecordMaxString, &end, 10);
4155 if (*end != '\0') {
Ruben Brunk3e47a742013-09-09 17:56:07 -07004156 LOG(ERROR) << "Ignoring " << propertyName << " '" << allocRecordMaxString
4157 << "' --- invalid";
Elliott Hughesb1a58792013-07-11 18:10:58 -07004158 return kDefaultNumAllocRecords;
4159 }
4160 if (!IsPowerOfTwo(value)) {
Ruben Brunk3e47a742013-09-09 17:56:07 -07004161 LOG(ERROR) << "Ignoring " << propertyName << " '" << allocRecordMaxString
4162 << "' --- not power of two";
Elliott Hughesb1a58792013-07-11 18:10:58 -07004163 return kDefaultNumAllocRecords;
4164 }
4165 return value;
4166 }
4167#endif
4168 return kDefaultNumAllocRecords;
4169}
4170
Elliott Hughes545a0642011-11-08 19:10:03 -08004171void Dbg::SetAllocTrackingEnabled(bool enabled) {
Elliott Hughes545a0642011-11-08 19:10:03 -08004172 if (enabled) {
Sebastien Hertzb98063a2014-03-26 10:57:20 +01004173 {
4174 MutexLock mu(Thread::Current(), *alloc_tracker_lock_);
4175 if (recent_allocation_records_ == NULL) {
4176 alloc_record_max_ = GetAllocTrackerMax();
4177 LOG(INFO) << "Enabling alloc tracker (" << alloc_record_max_ << " entries of "
4178 << kMaxAllocRecordStackDepth << " frames, taking "
4179 << PrettySize(sizeof(AllocRecord) * alloc_record_max_) << ")";
4180 alloc_record_head_ = alloc_record_count_ = 0;
4181 recent_allocation_records_ = new AllocRecord[alloc_record_max_];
4182 CHECK(recent_allocation_records_ != NULL);
4183 }
Elliott Hughes545a0642011-11-08 19:10:03 -08004184 }
Ian Rogersfa824272013-11-05 16:12:57 -08004185 Runtime::Current()->GetInstrumentation()->InstrumentQuickAllocEntryPoints();
Elliott Hughes545a0642011-11-08 19:10:03 -08004186 } else {
Ian Rogersfa824272013-11-05 16:12:57 -08004187 Runtime::Current()->GetInstrumentation()->UninstrumentQuickAllocEntryPoints();
Sebastien Hertzb98063a2014-03-26 10:57:20 +01004188 {
4189 MutexLock mu(Thread::Current(), *alloc_tracker_lock_);
4190 delete[] recent_allocation_records_;
4191 recent_allocation_records_ = NULL;
4192 }
Elliott Hughes545a0642011-11-08 19:10:03 -08004193 }
4194}
4195
Ian Rogers0399dde2012-06-06 17:09:28 -07004196struct AllocRecordStackVisitor : public StackVisitor {
Ian Rogers7a22fa62013-01-23 12:16:16 -08004197 AllocRecordStackVisitor(Thread* thread, AllocRecord* record)
Ian Rogersb726dcb2012-09-05 08:57:23 -07004198 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_)
Ian Rogers7a22fa62013-01-23 12:16:16 -08004199 : StackVisitor(thread, NULL), record(record), depth(0) {}
Elliott Hughes545a0642011-11-08 19:10:03 -08004200
Ian Rogers00f7d0e2012-07-19 15:28:27 -07004201 // TODO: Enable annotalysis. We know lock is held in constructor, but abstraction confuses
4202 // annotalysis.
4203 bool VisitFrame() NO_THREAD_SAFETY_ANALYSIS {
Elliott Hughes545a0642011-11-08 19:10:03 -08004204 if (depth >= kMaxAllocRecordStackDepth) {
Elliott Hughes530fa002012-03-12 11:44:49 -07004205 return false;
Elliott Hughes545a0642011-11-08 19:10:03 -08004206 }
Brian Carlstromea46f952013-07-30 01:26:50 -07004207 mirror::ArtMethod* m = GetMethod();
Ian Rogers0399dde2012-06-06 17:09:28 -07004208 if (!m->IsRuntimeMethod()) {
Hiroshi Yamauchib5a9e3d2014-06-09 12:11:20 -07004209 record->StackElement(depth)->SetMethod(m);
4210 record->StackElement(depth)->SetDexPc(GetDexPc());
Elliott Hughes530fa002012-03-12 11:44:49 -07004211 ++depth;
Elliott Hughes545a0642011-11-08 19:10:03 -08004212 }
Elliott Hughes530fa002012-03-12 11:44:49 -07004213 return true;
Elliott Hughes545a0642011-11-08 19:10:03 -08004214 }
4215
4216 ~AllocRecordStackVisitor() {
4217 // Clear out any unused stack trace elements.
4218 for (; depth < kMaxAllocRecordStackDepth; ++depth) {
Hiroshi Yamauchib5a9e3d2014-06-09 12:11:20 -07004219 record->StackElement(depth)->SetMethod(nullptr);
4220 record->StackElement(depth)->SetDexPc(0);
Elliott Hughes545a0642011-11-08 19:10:03 -08004221 }
4222 }
4223
4224 AllocRecord* record;
4225 size_t depth;
4226};
4227
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08004228void Dbg::RecordAllocation(mirror::Class* type, size_t byte_count) {
Elliott Hughes545a0642011-11-08 19:10:03 -08004229 Thread* self = Thread::Current();
4230 CHECK(self != NULL);
4231
Ian Rogers719d1a32014-03-06 12:13:39 -08004232 MutexLock mu(self, *alloc_tracker_lock_);
Elliott Hughes545a0642011-11-08 19:10:03 -08004233 if (recent_allocation_records_ == NULL) {
4234 return;
4235 }
4236
4237 // Advance and clip.
Ian Rogers719d1a32014-03-06 12:13:39 -08004238 if (++alloc_record_head_ == alloc_record_max_) {
4239 alloc_record_head_ = 0;
Elliott Hughes545a0642011-11-08 19:10:03 -08004240 }
4241
4242 // Fill in the basics.
Ian Rogers719d1a32014-03-06 12:13:39 -08004243 AllocRecord* record = &recent_allocation_records_[alloc_record_head_];
Hiroshi Yamauchib5a9e3d2014-06-09 12:11:20 -07004244 record->SetType(type);
4245 record->SetByteCount(byte_count);
4246 record->SetThinLockId(self->GetThreadId());
Elliott Hughes545a0642011-11-08 19:10:03 -08004247
4248 // Fill in the stack trace.
Ian Rogers7a22fa62013-01-23 12:16:16 -08004249 AllocRecordStackVisitor visitor(self, record);
Ian Rogers0399dde2012-06-06 17:09:28 -07004250 visitor.WalkStack();
Elliott Hughes545a0642011-11-08 19:10:03 -08004251
Ian Rogers719d1a32014-03-06 12:13:39 -08004252 if (alloc_record_count_ < alloc_record_max_) {
4253 ++alloc_record_count_;
Elliott Hughes545a0642011-11-08 19:10:03 -08004254 }
4255}
4256
Elliott Hughesa8f93cb2012-06-08 17:08:48 -07004257// Returns the index of the head element.
4258//
4259// We point at the most-recently-written record, so if gAllocRecordCount is 1
4260// we want to use the current element. Take "head+1" and subtract count
4261// from it.
4262//
4263// We need to handle underflow in our circular buffer, so we add
Elliott Hughesb1a58792013-07-11 18:10:58 -07004264// gAllocRecordMax and then mask it back down.
Ian Rogers719d1a32014-03-06 12:13:39 -08004265size_t Dbg::HeadIndex() {
4266 return (Dbg::alloc_record_head_ + 1 + Dbg::alloc_record_max_ - Dbg::alloc_record_count_) &
4267 (Dbg::alloc_record_max_ - 1);
Elliott Hughes545a0642011-11-08 19:10:03 -08004268}
4269
4270void Dbg::DumpRecentAllocations() {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07004271 ScopedObjectAccess soa(Thread::Current());
Ian Rogers719d1a32014-03-06 12:13:39 -08004272 MutexLock mu(soa.Self(), *alloc_tracker_lock_);
Elliott Hughes545a0642011-11-08 19:10:03 -08004273 if (recent_allocation_records_ == NULL) {
4274 LOG(INFO) << "Not recording tracked allocations";
4275 return;
4276 }
4277
4278 // "i" is the head of the list. We want to start at the end of the
4279 // list and move forward to the tail.
Elliott Hughesa8f93cb2012-06-08 17:08:48 -07004280 size_t i = HeadIndex();
Ian Rogers719d1a32014-03-06 12:13:39 -08004281 size_t count = alloc_record_count_;
Elliott Hughes545a0642011-11-08 19:10:03 -08004282
Ian Rogers719d1a32014-03-06 12:13:39 -08004283 LOG(INFO) << "Tracked allocations, (head=" << alloc_record_head_ << " count=" << count << ")";
Elliott Hughes545a0642011-11-08 19:10:03 -08004284 while (count--) {
4285 AllocRecord* record = &recent_allocation_records_[i];
4286
Hiroshi Yamauchib5a9e3d2014-06-09 12:11:20 -07004287 LOG(INFO) << StringPrintf(" Thread %-2d %6zd bytes ", record->ThinLockId(), record->ByteCount())
4288 << PrettyClass(record->Type());
Elliott Hughes545a0642011-11-08 19:10:03 -08004289
4290 for (size_t stack_frame = 0; stack_frame < kMaxAllocRecordStackDepth; ++stack_frame) {
Hiroshi Yamauchib5a9e3d2014-06-09 12:11:20 -07004291 AllocRecordStackTraceElement* stack_element = record->StackElement(stack_frame);
4292 mirror::ArtMethod* m = stack_element->Method();
Elliott Hughes545a0642011-11-08 19:10:03 -08004293 if (m == NULL) {
4294 break;
4295 }
Hiroshi Yamauchib5a9e3d2014-06-09 12:11:20 -07004296 LOG(INFO) << " " << PrettyMethod(m) << " line " << stack_element->LineNumber();
Elliott Hughes545a0642011-11-08 19:10:03 -08004297 }
4298
4299 // pause periodically to help logcat catch up
4300 if ((count % 5) == 0) {
4301 usleep(40000);
4302 }
4303
Ian Rogers719d1a32014-03-06 12:13:39 -08004304 i = (i + 1) & (alloc_record_max_ - 1);
Elliott Hughes545a0642011-11-08 19:10:03 -08004305 }
4306}
4307
4308class StringTable {
4309 public:
4310 StringTable() {
4311 }
4312
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08004313 void Add(const char* s) {
Elliott Hughes545a0642011-11-08 19:10:03 -08004314 table_.insert(s);
4315 }
4316
Elliott Hughesa8f93cb2012-06-08 17:08:48 -07004317 size_t IndexOf(const char* s) const {
Mathieu Chartier02e25112013-08-14 16:14:24 -07004318 auto it = table_.find(s);
Elliott Hughesa8f93cb2012-06-08 17:08:48 -07004319 if (it == table_.end()) {
4320 LOG(FATAL) << "IndexOf(\"" << s << "\") failed";
4321 }
4322 return std::distance(table_.begin(), it);
Elliott Hughes545a0642011-11-08 19:10:03 -08004323 }
4324
Elliott Hughesa8f93cb2012-06-08 17:08:48 -07004325 size_t Size() const {
Elliott Hughes545a0642011-11-08 19:10:03 -08004326 return table_.size();
4327 }
4328
Elliott Hughesa8f93cb2012-06-08 17:08:48 -07004329 void WriteTo(std::vector<uint8_t>& bytes) const {
Mathieu Chartier02e25112013-08-14 16:14:24 -07004330 for (const std::string& str : table_) {
4331 const char* s = str.c_str();
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08004332 size_t s_len = CountModifiedUtf8Chars(s);
Ian Rogers700a4022014-05-19 16:49:03 -07004333 std::unique_ptr<uint16_t> s_utf16(new uint16_t[s_len]);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08004334 ConvertModifiedUtf8ToUtf16(s_utf16.get(), s);
4335 JDWP::AppendUtf16BE(bytes, s_utf16.get(), s_len);
Elliott Hughes545a0642011-11-08 19:10:03 -08004336 }
4337 }
4338
4339 private:
Elliott Hughesa8f93cb2012-06-08 17:08:48 -07004340 std::set<std::string> table_;
Elliott Hughes545a0642011-11-08 19:10:03 -08004341 DISALLOW_COPY_AND_ASSIGN(StringTable);
4342};
4343
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07004344static const char* GetMethodSourceFile(mirror::ArtMethod* method)
Sebastien Hertz280286a2014-04-28 09:26:50 +02004345 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07004346 DCHECK(method != nullptr);
4347 const char* source_file = method->GetDeclaringClassSourceFile();
Sebastien Hertz280286a2014-04-28 09:26:50 +02004348 return (source_file != nullptr) ? source_file : "";
4349}
4350
Elliott Hughes545a0642011-11-08 19:10:03 -08004351/*
4352 * The data we send to DDMS contains everything we have recorded.
4353 *
4354 * Message header (all values big-endian):
4355 * (1b) message header len (to allow future expansion); includes itself
4356 * (1b) entry header len
4357 * (1b) stack frame len
4358 * (2b) number of entries
4359 * (4b) offset to string table from start of message
4360 * (2b) number of class name strings
4361 * (2b) number of method name strings
4362 * (2b) number of source file name strings
4363 * For each entry:
4364 * (4b) total allocation size
Elliott Hughes221229c2013-01-08 18:17:50 -08004365 * (2b) thread id
Elliott Hughes545a0642011-11-08 19:10:03 -08004366 * (2b) allocated object's class name index
4367 * (1b) stack depth
4368 * For each stack frame:
4369 * (2b) method's class name
4370 * (2b) method name
4371 * (2b) method source file
4372 * (2b) line number, clipped to 32767; -2 if native; -1 if no source
4373 * (xb) class name strings
4374 * (xb) method name strings
4375 * (xb) source file strings
4376 *
4377 * As with other DDM traffic, strings are sent as a 4-byte length
4378 * followed by UTF-16 data.
4379 *
4380 * We send up 16-bit unsigned indexes into string tables. In theory there
Elliott Hughesb1a58792013-07-11 18:10:58 -07004381 * can be (kMaxAllocRecordStackDepth * gAllocRecordMax) unique strings in
Elliott Hughes545a0642011-11-08 19:10:03 -08004382 * each table, but in practice there should be far fewer.
4383 *
4384 * The chief reason for using a string table here is to keep the size of
4385 * the DDMS message to a minimum. This is partly to make the protocol
4386 * efficient, but also because we have to form the whole thing up all at
4387 * once in a memory buffer.
4388 *
4389 * We use separate string tables for class names, method names, and source
4390 * files to keep the indexes small. There will generally be no overlap
4391 * between the contents of these tables.
4392 */
4393jbyteArray Dbg::GetRecentAllocations() {
4394 if (false) {
4395 DumpRecentAllocations();
4396 }
4397
Ian Rogers50b35e22012-10-04 10:09:15 -07004398 Thread* self = Thread::Current();
Elliott Hughes545a0642011-11-08 19:10:03 -08004399 std::vector<uint8_t> bytes;
Mathieu Chartier46e811b2013-07-10 17:09:14 -07004400 {
Ian Rogers719d1a32014-03-06 12:13:39 -08004401 MutexLock mu(self, *alloc_tracker_lock_);
Mathieu Chartier46e811b2013-07-10 17:09:14 -07004402 //
4403 // Part 1: generate string tables.
4404 //
4405 StringTable class_names;
4406 StringTable method_names;
4407 StringTable filenames;
Elliott Hughes545a0642011-11-08 19:10:03 -08004408
Ian Rogers719d1a32014-03-06 12:13:39 -08004409 int count = alloc_record_count_;
Mathieu Chartier46e811b2013-07-10 17:09:14 -07004410 int idx = HeadIndex();
4411 while (count--) {
4412 AllocRecord* record = &recent_allocation_records_[idx];
Elliott Hughes545a0642011-11-08 19:10:03 -08004413
Hiroshi Yamauchib5a9e3d2014-06-09 12:11:20 -07004414 class_names.Add(record->Type()->GetDescriptor().c_str());
Elliott Hughes545a0642011-11-08 19:10:03 -08004415
Mathieu Chartier46e811b2013-07-10 17:09:14 -07004416 for (size_t i = 0; i < kMaxAllocRecordStackDepth; i++) {
Hiroshi Yamauchib5a9e3d2014-06-09 12:11:20 -07004417 mirror::ArtMethod* m = record->StackElement(i)->Method();
Mathieu Chartier46e811b2013-07-10 17:09:14 -07004418 if (m != NULL) {
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07004419 class_names.Add(m->GetDeclaringClassDescriptor());
4420 method_names.Add(m->GetName());
4421 filenames.Add(GetMethodSourceFile(m));
Mathieu Chartier46e811b2013-07-10 17:09:14 -07004422 }
4423 }
Elliott Hughes545a0642011-11-08 19:10:03 -08004424
Ian Rogers719d1a32014-03-06 12:13:39 -08004425 idx = (idx + 1) & (alloc_record_max_ - 1);
Elliott Hughes545a0642011-11-08 19:10:03 -08004426 }
4427
Ian Rogers719d1a32014-03-06 12:13:39 -08004428 LOG(INFO) << "allocation records: " << alloc_record_count_;
Mathieu Chartier46e811b2013-07-10 17:09:14 -07004429
4430 //
4431 // Part 2: Generate the output and store it in the buffer.
4432 //
4433
4434 // (1b) message header len (to allow future expansion); includes itself
4435 // (1b) entry header len
4436 // (1b) stack frame len
4437 const int kMessageHeaderLen = 15;
4438 const int kEntryHeaderLen = 9;
4439 const int kStackFrameLen = 8;
4440 JDWP::Append1BE(bytes, kMessageHeaderLen);
4441 JDWP::Append1BE(bytes, kEntryHeaderLen);
4442 JDWP::Append1BE(bytes, kStackFrameLen);
4443
4444 // (2b) number of entries
4445 // (4b) offset to string table from start of message
4446 // (2b) number of class name strings
4447 // (2b) number of method name strings
4448 // (2b) number of source file name strings
Ian Rogers719d1a32014-03-06 12:13:39 -08004449 JDWP::Append2BE(bytes, alloc_record_count_);
Mathieu Chartier46e811b2013-07-10 17:09:14 -07004450 size_t string_table_offset = bytes.size();
Brian Carlstrom7934ac22013-07-26 10:54:15 -07004451 JDWP::Append4BE(bytes, 0); // We'll patch this later...
Mathieu Chartier46e811b2013-07-10 17:09:14 -07004452 JDWP::Append2BE(bytes, class_names.Size());
4453 JDWP::Append2BE(bytes, method_names.Size());
4454 JDWP::Append2BE(bytes, filenames.Size());
4455
Ian Rogers719d1a32014-03-06 12:13:39 -08004456 count = alloc_record_count_;
Mathieu Chartier46e811b2013-07-10 17:09:14 -07004457 idx = HeadIndex();
Mathieu Chartier46e811b2013-07-10 17:09:14 -07004458 while (count--) {
4459 // For each entry:
4460 // (4b) total allocation size
4461 // (2b) thread id
4462 // (2b) allocated object's class name index
4463 // (1b) stack depth
4464 AllocRecord* record = &recent_allocation_records_[idx];
4465 size_t stack_depth = record->GetDepth();
Mathieu Chartierf8322842014-05-16 10:59:25 -07004466 size_t allocated_object_class_name_index =
Hiroshi Yamauchib5a9e3d2014-06-09 12:11:20 -07004467 class_names.IndexOf(record->Type()->GetDescriptor().c_str());
4468 JDWP::Append4BE(bytes, record->ByteCount());
4469 JDWP::Append2BE(bytes, record->ThinLockId());
Mathieu Chartier46e811b2013-07-10 17:09:14 -07004470 JDWP::Append2BE(bytes, allocated_object_class_name_index);
4471 JDWP::Append1BE(bytes, stack_depth);
4472
Mathieu Chartier46e811b2013-07-10 17:09:14 -07004473 for (size_t stack_frame = 0; stack_frame < stack_depth; ++stack_frame) {
4474 // For each stack frame:
4475 // (2b) method's class name
4476 // (2b) method name
4477 // (2b) method source file
4478 // (2b) line number, clipped to 32767; -2 if native; -1 if no source
Hiroshi Yamauchib5a9e3d2014-06-09 12:11:20 -07004479 mirror::ArtMethod* m = record->StackElement(stack_frame)->Method();
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07004480 size_t class_name_index = class_names.IndexOf(m->GetDeclaringClassDescriptor());
4481 size_t method_name_index = method_names.IndexOf(m->GetName());
4482 size_t file_name_index = filenames.IndexOf(GetMethodSourceFile(m));
Mathieu Chartier46e811b2013-07-10 17:09:14 -07004483 JDWP::Append2BE(bytes, class_name_index);
4484 JDWP::Append2BE(bytes, method_name_index);
4485 JDWP::Append2BE(bytes, file_name_index);
Hiroshi Yamauchib5a9e3d2014-06-09 12:11:20 -07004486 JDWP::Append2BE(bytes, record->StackElement(stack_frame)->LineNumber());
Mathieu Chartier46e811b2013-07-10 17:09:14 -07004487 }
4488
Ian Rogers719d1a32014-03-06 12:13:39 -08004489 idx = (idx + 1) & (alloc_record_max_ - 1);
Mathieu Chartier46e811b2013-07-10 17:09:14 -07004490 }
4491
4492 // (xb) class name strings
4493 // (xb) method name strings
4494 // (xb) source file strings
4495 JDWP::Set4BE(&bytes[string_table_offset], bytes.size());
4496 class_names.WriteTo(bytes);
4497 method_names.WriteTo(bytes);
4498 filenames.WriteTo(bytes);
Elliott Hughes545a0642011-11-08 19:10:03 -08004499 }
Ian Rogers50b35e22012-10-04 10:09:15 -07004500 JNIEnv* env = self->GetJniEnv();
Elliott Hughes545a0642011-11-08 19:10:03 -08004501 jbyteArray result = env->NewByteArray(bytes.size());
4502 if (result != NULL) {
4503 env->SetByteArrayRegion(result, 0, bytes.size(), reinterpret_cast<const jbyte*>(&bytes[0]));
4504 }
4505 return result;
4506}
4507
Elliott Hughes872d4ec2011-10-21 17:07:15 -07004508} // namespace art