blob: f84e10c628c79fa3551842ded070fcfe6d079ff4 [file] [log] [blame]
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001/*
2 * Copyright (C) 2008 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17#include "debugger.h"
18
Elliott Hughes3bb81562011-10-21 18:52:59 -070019#include <sys/uio.h>
20
Elliott Hughes545a0642011-11-08 19:10:03 -080021#include <set>
22
Ian Rogers166db042013-07-26 12:05:57 -070023#include "arch/context.h"
Mathieu Chartierc7853442015-03-27 14:35:38 -070024#include "art_field-inl.h"
Mathieu Chartiere401d142015-04-22 13:56:20 -070025#include "art_method-inl.h"
Vladimir Marko80afd022015-05-19 18:08:00 +010026#include "base/time_utils.h"
Elliott Hughes545a0642011-11-08 19:10:03 -080027#include "class_linker.h"
Ian Rogers2dd0e2c2013-01-24 12:42:14 -080028#include "class_linker-inl.h"
Ian Rogers4f6ad8a2013-03-18 15:27:28 -070029#include "dex_file-inl.h"
Ian Rogers776ac1f2012-04-13 23:36:36 -070030#include "dex_instruction.h"
Ian Rogers1d54e732013-05-02 21:10:01 -070031#include "gc/accounting/card_table-inl.h"
Man Cao8c2ff642015-05-27 17:25:30 -070032#include "gc/allocation_record.h"
Ian Rogers1d54e732013-05-02 21:10:01 -070033#include "gc/space/large_object_space.h"
34#include "gc/space/space-inl.h"
Mathieu Chartiereb8167a2014-05-07 15:43:14 -070035#include "handle_scope.h"
Sebastien Hertzcbc50642015-06-01 17:33:12 +020036#include "jdwp/jdwp_priv.h"
Elliott Hughes64f574f2013-02-20 14:57:12 -080037#include "jdwp/object_registry.h"
Ian Rogers2dd0e2c2013-01-24 12:42:14 -080038#include "mirror/class.h"
39#include "mirror/class-inl.h"
40#include "mirror/class_loader.h"
Ian Rogers2dd0e2c2013-01-24 12:42:14 -080041#include "mirror/object-inl.h"
42#include "mirror/object_array-inl.h"
Ian Rogersb0fa5dc2014-04-28 16:47:08 -070043#include "mirror/string-inl.h"
Ian Rogers2dd0e2c2013-01-24 12:42:14 -080044#include "mirror/throwable.h"
Sebastien Hertza76a6d42014-03-20 16:40:17 +010045#include "quick/inline_method_analyser.h"
Ian Rogers53b8b092014-03-13 23:45:53 -070046#include "reflection.h"
Elliott Hughesa0e18062012-04-13 15:59:59 -070047#include "safe_map.h"
Elliott Hughes64f574f2013-02-20 14:57:12 -080048#include "scoped_thread_state_change.h"
Elliott Hughes6a5bd492011-10-28 14:33:57 -070049#include "ScopedLocalRef.h"
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -070050#include "ScopedPrimitiveArray.h"
Mathieu Chartiereb8167a2014-05-07 15:43:14 -070051#include "handle_scope-inl.h"
Elliott Hughes475fc232011-10-25 15:00:35 -070052#include "thread_list.h"
Ian Rogers2dd0e2c2013-01-24 12:42:14 -080053#include "utf.h"
Sebastien Hertza76a6d42014-03-20 16:40:17 +010054#include "verifier/method_verifier-inl.h"
Elliott Hugheseac76672012-05-24 21:56:51 -070055#include "well_known_classes.h"
Elliott Hughes475fc232011-10-25 15:00:35 -070056
Brian Carlstrom3d92d522013-07-12 09:03:08 -070057#ifdef HAVE_ANDROID_OS
58#include "cutils/properties.h"
59#endif
60
Elliott Hughes872d4ec2011-10-21 17:07:15 -070061namespace art {
62
Sebastien Hertz0462c4c2015-04-01 16:34:17 +020063// The key identifying the debugger to update instrumentation.
64static constexpr const char* kDbgInstrumentationKey = "Debugger";
65
Man Cao8c2ff642015-05-27 17:25:30 -070066// Limit alloc_record_count to the 2BE value (64k-1) that is the limit of the current protocol.
Brian Carlstrom306db812014-09-05 13:01:41 -070067static uint16_t CappedAllocRecordCount(size_t alloc_record_count) {
Man Cao8c2ff642015-05-27 17:25:30 -070068 size_t cap = 0xffff;
69#ifdef HAVE_ANDROID_OS
70 // Check whether there's a system property overriding the number of recent records.
71 const char* propertyName = "dalvik.vm.recentAllocMax";
72 char recentAllocMaxString[PROPERTY_VALUE_MAX];
73 if (property_get(propertyName, recentAllocMaxString, "") > 0) {
74 char* end;
75 size_t value = strtoul(recentAllocMaxString, &end, 10);
76 if (*end != '\0') {
77 LOG(ERROR) << "Ignoring " << propertyName << " '" << recentAllocMaxString
78 << "' --- invalid";
79 } else {
80 cap = value;
81 }
82 }
83#endif
84 if (alloc_record_count > cap) {
85 return cap;
Brian Carlstrom306db812014-09-05 13:01:41 -070086 }
87 return alloc_record_count;
88}
Elliott Hughes475fc232011-10-25 15:00:35 -070089
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -070090class Breakpoint {
91 public:
Mathieu Chartiere401d142015-04-22 13:56:20 -070092 Breakpoint(ArtMethod* method, uint32_t dex_pc,
Sebastien Hertzf3928792014-11-17 19:00:37 +010093 DeoptimizationRequest::Kind deoptimization_kind)
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -070094 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_)
Sebastien Hertzf3928792014-11-17 19:00:37 +010095 : method_(nullptr), dex_pc_(dex_pc), deoptimization_kind_(deoptimization_kind) {
96 CHECK(deoptimization_kind_ == DeoptimizationRequest::kNothing ||
97 deoptimization_kind_ == DeoptimizationRequest::kSelectiveDeoptimization ||
98 deoptimization_kind_ == DeoptimizationRequest::kFullDeoptimization);
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -070099 ScopedObjectAccessUnchecked soa(Thread::Current());
100 method_ = soa.EncodeMethod(method);
101 }
102
103 Breakpoint(const Breakpoint& other) SHARED_LOCKS_REQUIRED(Locks::mutator_lock_)
104 : method_(nullptr), dex_pc_(other.dex_pc_),
Sebastien Hertzf3928792014-11-17 19:00:37 +0100105 deoptimization_kind_(other.deoptimization_kind_) {
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -0700106 ScopedObjectAccessUnchecked soa(Thread::Current());
107 method_ = soa.EncodeMethod(other.Method());
108 }
109
Mathieu Chartiere401d142015-04-22 13:56:20 -0700110 ArtMethod* Method() const SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -0700111 ScopedObjectAccessUnchecked soa(Thread::Current());
112 return soa.DecodeMethod(method_);
113 }
114
115 uint32_t DexPc() const {
116 return dex_pc_;
117 }
118
Sebastien Hertzf3928792014-11-17 19:00:37 +0100119 DeoptimizationRequest::Kind GetDeoptimizationKind() const {
120 return deoptimization_kind_;
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -0700121 }
122
123 private:
Sebastien Hertza76a6d42014-03-20 16:40:17 +0100124 // The location of this breakpoint.
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -0700125 jmethodID method_;
126 uint32_t dex_pc_;
Sebastien Hertza76a6d42014-03-20 16:40:17 +0100127
128 // Indicates whether breakpoint needs full deoptimization or selective deoptimization.
Sebastien Hertzf3928792014-11-17 19:00:37 +0100129 DeoptimizationRequest::Kind deoptimization_kind_;
Elliott Hughes86964332012-02-15 19:37:42 -0800130};
131
Sebastien Hertzed2be172014-08-19 15:33:43 +0200132static std::ostream& operator<<(std::ostream& os, const Breakpoint& rhs)
Ian Rogersb726dcb2012-09-05 08:57:23 -0700133 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -0700134 os << StringPrintf("Breakpoint[%s @%#x]", PrettyMethod(rhs.Method()).c_str(), rhs.DexPc());
Elliott Hughes86964332012-02-15 19:37:42 -0800135 return os;
136}
137
Sebastien Hertz3f52eaf2014-04-04 17:50:18 +0200138class DebugInstrumentationListener FINAL : public instrumentation::InstrumentationListener {
Ian Rogers62d6c772013-02-27 08:32:07 -0800139 public:
140 DebugInstrumentationListener() {}
141 virtual ~DebugInstrumentationListener() {}
142
Mathieu Chartiere401d142015-04-22 13:56:20 -0700143 void MethodEntered(Thread* thread, mirror::Object* this_object, ArtMethod* method,
Sebastien Hertz9d6bf692015-04-10 12:12:33 +0200144 uint32_t dex_pc)
Sebastien Hertz3f52eaf2014-04-04 17:50:18 +0200145 OVERRIDE SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Ian Rogers62d6c772013-02-27 08:32:07 -0800146 if (method->IsNative()) {
147 // TODO: post location events is a suspension point and native method entry stubs aren't.
148 return;
149 }
Sebastien Hertz9d6bf692015-04-10 12:12:33 +0200150 if (IsListeningToDexPcMoved()) {
151 // We also listen to kDexPcMoved instrumentation event so we know the DexPcMoved method is
152 // going to be called right after us. To avoid sending JDWP events twice for this location,
153 // we report the event in DexPcMoved. However, we must remind this is method entry so we
154 // send the METHOD_ENTRY event. And we can also group it with other events for this location
155 // like BREAKPOINT or SINGLE_STEP (or even METHOD_EXIT if this is a RETURN instruction).
156 thread->SetDebugMethodEntry();
157 } else if (IsListeningToMethodExit() && IsReturn(method, dex_pc)) {
158 // We also listen to kMethodExited instrumentation event and the current instruction is a
159 // RETURN so we know the MethodExited method is going to be called right after us. To avoid
160 // sending JDWP events twice for this location, we report the event(s) in MethodExited.
161 // However, we must remind this is method entry so we send the METHOD_ENTRY event. And we can
162 // also group it with other events for this location like BREAKPOINT or SINGLE_STEP.
163 thread->SetDebugMethodEntry();
164 } else {
165 Dbg::UpdateDebugger(thread, this_object, method, 0, Dbg::kMethodEntry, nullptr);
166 }
Ian Rogers62d6c772013-02-27 08:32:07 -0800167 }
168
Mathieu Chartiere401d142015-04-22 13:56:20 -0700169 void MethodExited(Thread* thread, mirror::Object* this_object, ArtMethod* method,
Sebastien Hertz3f52eaf2014-04-04 17:50:18 +0200170 uint32_t dex_pc, const JValue& return_value)
171 OVERRIDE SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Ian Rogers62d6c772013-02-27 08:32:07 -0800172 if (method->IsNative()) {
173 // TODO: post location events is a suspension point and native method entry stubs aren't.
174 return;
175 }
Sebastien Hertz9d6bf692015-04-10 12:12:33 +0200176 uint32_t events = Dbg::kMethodExit;
177 if (thread->IsDebugMethodEntry()) {
178 // It is also the method entry.
179 DCHECK(IsReturn(method, dex_pc));
180 events |= Dbg::kMethodEntry;
181 thread->ClearDebugMethodEntry();
182 }
183 Dbg::UpdateDebugger(thread, this_object, method, dex_pc, events, &return_value);
Ian Rogers62d6c772013-02-27 08:32:07 -0800184 }
185
Sebastien Hertz9d6bf692015-04-10 12:12:33 +0200186 void MethodUnwind(Thread* thread ATTRIBUTE_UNUSED, mirror::Object* this_object ATTRIBUTE_UNUSED,
Mathieu Chartiere401d142015-04-22 13:56:20 -0700187 ArtMethod* method, uint32_t dex_pc)
Sebastien Hertz3f52eaf2014-04-04 17:50:18 +0200188 OVERRIDE SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Ian Rogers62d6c772013-02-27 08:32:07 -0800189 // We're not recorded to listen to this kind of event, so complain.
190 LOG(ERROR) << "Unexpected method unwind event in debugger " << PrettyMethod(method)
Sebastien Hertz51db44a2013-11-19 10:00:29 +0100191 << " " << dex_pc;
Ian Rogers62d6c772013-02-27 08:32:07 -0800192 }
193
Mathieu Chartiere401d142015-04-22 13:56:20 -0700194 void DexPcMoved(Thread* thread, mirror::Object* this_object, ArtMethod* method,
Sebastien Hertz3f52eaf2014-04-04 17:50:18 +0200195 uint32_t new_dex_pc)
196 OVERRIDE SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Sebastien Hertz9d6bf692015-04-10 12:12:33 +0200197 if (IsListeningToMethodExit() && IsReturn(method, new_dex_pc)) {
198 // We also listen to kMethodExited instrumentation event and the current instruction is a
199 // RETURN so we know the MethodExited method is going to be called right after us. Like in
200 // MethodEntered, we delegate event reporting to MethodExited.
201 // Besides, if this RETURN instruction is the only one in the method, we can send multiple
202 // JDWP events in the same packet: METHOD_ENTRY, METHOD_EXIT, BREAKPOINT and/or SINGLE_STEP.
203 // Therefore, we must not clear the debug method entry flag here.
204 } else {
205 uint32_t events = 0;
206 if (thread->IsDebugMethodEntry()) {
207 // It is also the method entry.
208 events = Dbg::kMethodEntry;
209 thread->ClearDebugMethodEntry();
210 }
211 Dbg::UpdateDebugger(thread, this_object, method, new_dex_pc, events, nullptr);
212 }
Ian Rogers62d6c772013-02-27 08:32:07 -0800213 }
214
Sebastien Hertz9d6bf692015-04-10 12:12:33 +0200215 void FieldRead(Thread* thread ATTRIBUTE_UNUSED, mirror::Object* this_object,
Mathieu Chartiere401d142015-04-22 13:56:20 -0700216 ArtMethod* method, uint32_t dex_pc, ArtField* field)
Sebastien Hertz3f52eaf2014-04-04 17:50:18 +0200217 OVERRIDE SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
218 Dbg::PostFieldAccessEvent(method, dex_pc, this_object, field);
Ian Rogers62d6c772013-02-27 08:32:07 -0800219 }
Sebastien Hertz3f52eaf2014-04-04 17:50:18 +0200220
Ian Rogers6a3c1fc2014-10-31 00:33:20 -0700221 void FieldWritten(Thread* thread ATTRIBUTE_UNUSED, mirror::Object* this_object,
Mathieu Chartiere401d142015-04-22 13:56:20 -0700222 ArtMethod* method, uint32_t dex_pc, ArtField* field,
Ian Rogers6a3c1fc2014-10-31 00:33:20 -0700223 const JValue& field_value)
Sebastien Hertz3f52eaf2014-04-04 17:50:18 +0200224 OVERRIDE SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
225 Dbg::PostFieldModificationEvent(method, dex_pc, this_object, field, &field_value);
226 }
227
Nicolas Geoffray14691c52015-03-05 10:40:17 +0000228 void ExceptionCaught(Thread* thread ATTRIBUTE_UNUSED, mirror::Throwable* exception_object)
Sebastien Hertz3f52eaf2014-04-04 17:50:18 +0200229 OVERRIDE SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Nicolas Geoffray14691c52015-03-05 10:40:17 +0000230 Dbg::PostException(exception_object);
Sebastien Hertz3f52eaf2014-04-04 17:50:18 +0200231 }
232
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800233 // We only care about how many backward branches were executed in the Jit.
Mathieu Chartiere401d142015-04-22 13:56:20 -0700234 void BackwardBranch(Thread* /*thread*/, ArtMethod* method, int32_t dex_pc_offset)
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800235 OVERRIDE SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
236 LOG(ERROR) << "Unexpected backward branch event in debugger " << PrettyMethod(method)
237 << " " << dex_pc_offset;
238 }
239
Sebastien Hertz3f52eaf2014-04-04 17:50:18 +0200240 private:
Mathieu Chartiere401d142015-04-22 13:56:20 -0700241 static bool IsReturn(ArtMethod* method, uint32_t dex_pc)
Sebastien Hertz9d6bf692015-04-10 12:12:33 +0200242 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
243 const DexFile::CodeItem* code_item = method->GetCodeItem();
244 const Instruction* instruction = Instruction::At(&code_item->insns_[dex_pc]);
245 return instruction->IsReturn();
246 }
247
248 static bool IsListeningToDexPcMoved() SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
249 return IsListeningTo(instrumentation::Instrumentation::kDexPcMoved);
250 }
251
252 static bool IsListeningToMethodExit() SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
253 return IsListeningTo(instrumentation::Instrumentation::kMethodExited);
254 }
255
256 static bool IsListeningTo(instrumentation::Instrumentation::InstrumentationEvent event)
257 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
258 return (Dbg::GetInstrumentationEvents() & event) != 0;
259 }
260
Sebastien Hertz3f52eaf2014-04-04 17:50:18 +0200261 DISALLOW_COPY_AND_ASSIGN(DebugInstrumentationListener);
Ian Rogers62d6c772013-02-27 08:32:07 -0800262} gDebugInstrumentationListener;
263
Elliott Hughes4ffd3132011-10-24 12:06:42 -0700264// JDWP is allowed unless the Zygote forbids it.
265static bool gJdwpAllowed = true;
266
Elliott Hughesc0f09332012-03-26 13:27:06 -0700267// Was there a -Xrunjdwp or -agentlib:jdwp= argument on the command line?
Elliott Hughes3bb81562011-10-21 18:52:59 -0700268static bool gJdwpConfigured = false;
269
Sebastien Hertzb3b173b2015-02-06 09:16:32 +0100270// JDWP options for debugging. Only valid if IsJdwpConfigured() is true.
271static JDWP::JdwpOptions gJdwpOptions;
272
Elliott Hughes3bb81562011-10-21 18:52:59 -0700273// Runtime JDWP state.
Ian Rogersc0542af2014-09-03 16:16:56 -0700274static JDWP::JdwpState* gJdwpState = nullptr;
Elliott Hughes3bb81562011-10-21 18:52:59 -0700275static bool gDebuggerConnected; // debugger or DDMS is connected.
Elliott Hughes3bb81562011-10-21 18:52:59 -0700276
Elliott Hughes47fce012011-10-25 18:37:19 -0700277static bool gDdmThreadNotification = false;
278
Elliott Hughes767a1472011-10-26 18:49:02 -0700279// DDMS GC-related settings.
280static Dbg::HpifWhen gDdmHpifWhen = Dbg::HPIF_WHEN_NEVER;
281static Dbg::HpsgWhen gDdmHpsgWhen = Dbg::HPSG_WHEN_NEVER;
282static Dbg::HpsgWhat gDdmHpsgWhat;
283static Dbg::HpsgWhen gDdmNhsgWhen = Dbg::HPSG_WHEN_NEVER;
284static Dbg::HpsgWhat gDdmNhsgWhat;
285
Daniel Mihalyieb076692014-08-22 17:33:31 +0200286bool Dbg::gDebuggerActive = false;
Sebastien Hertz4e5b2082015-03-24 19:03:40 +0100287bool Dbg::gDisposed = false;
Sebastien Hertz6995c602014-09-09 12:10:13 +0200288ObjectRegistry* Dbg::gRegistry = nullptr;
Elliott Hughes475fc232011-10-25 15:00:35 -0700289
Sebastien Hertz138dbfc2013-12-04 18:15:25 +0100290// Deoptimization support.
Sebastien Hertz4d25df32014-03-21 17:44:46 +0100291std::vector<DeoptimizationRequest> Dbg::deoptimization_requests_;
292size_t Dbg::full_deoptimization_event_count_ = 0;
Sebastien Hertz138dbfc2013-12-04 18:15:25 +0100293
Sebastien Hertz42cd43f2014-05-13 14:15:41 +0200294// Instrumentation event reference counters.
295size_t Dbg::dex_pc_change_event_ref_count_ = 0;
296size_t Dbg::method_enter_event_ref_count_ = 0;
297size_t Dbg::method_exit_event_ref_count_ = 0;
298size_t Dbg::field_read_event_ref_count_ = 0;
299size_t Dbg::field_write_event_ref_count_ = 0;
300size_t Dbg::exception_catch_event_ref_count_ = 0;
301uint32_t Dbg::instrumentation_events_ = 0;
302
Sebastien Hertz138dbfc2013-12-04 18:15:25 +0100303// Breakpoints.
jeffhao09bfc6a2012-12-11 18:11:43 -0800304static std::vector<Breakpoint> gBreakpoints GUARDED_BY(Locks::breakpoint_lock_);
Elliott Hughes86964332012-02-15 19:37:42 -0800305
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -0700306void DebugInvokeReq::VisitRoots(RootVisitor* visitor, const RootInfo& root_info) {
307 receiver.VisitRootIfNonNull(visitor, root_info); // null for static method call.
308 klass.VisitRoot(visitor, root_info);
Mathieu Chartier3b05e9b2014-03-25 09:29:43 -0700309}
310
Sebastien Hertz597c4f02015-01-26 17:37:14 +0100311void SingleStepControl::AddDexPc(uint32_t dex_pc) {
312 dex_pcs_.insert(dex_pc);
Sebastien Hertzbb43b432014-04-14 11:59:08 +0200313}
314
Sebastien Hertz597c4f02015-01-26 17:37:14 +0100315bool SingleStepControl::ContainsDexPc(uint32_t dex_pc) const {
316 return dex_pcs_.find(dex_pc) == dex_pcs_.end();
Sebastien Hertzbb43b432014-04-14 11:59:08 +0200317}
318
Mathieu Chartiere401d142015-04-22 13:56:20 -0700319static bool IsBreakpoint(const ArtMethod* m, uint32_t dex_pc)
jeffhao09bfc6a2012-12-11 18:11:43 -0800320 LOCKS_EXCLUDED(Locks::breakpoint_lock_)
Ian Rogersb726dcb2012-09-05 08:57:23 -0700321 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Sebastien Hertzed2be172014-08-19 15:33:43 +0200322 ReaderMutexLock mu(Thread::Current(), *Locks::breakpoint_lock_);
Sebastien Hertz138dbfc2013-12-04 18:15:25 +0100323 for (size_t i = 0, e = gBreakpoints.size(); i < e; ++i) {
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -0700324 if (gBreakpoints[i].DexPc() == dex_pc && gBreakpoints[i].Method() == m) {
Elliott Hughes86964332012-02-15 19:37:42 -0800325 VLOG(jdwp) << "Hit breakpoint #" << i << ": " << gBreakpoints[i];
326 return true;
327 }
328 }
329 return false;
330}
331
Sebastien Hertz52d131d2014-03-13 16:17:40 +0100332static bool IsSuspendedForDebugger(ScopedObjectAccessUnchecked& soa, Thread* thread)
333 LOCKS_EXCLUDED(Locks::thread_suspend_count_lock_) {
Elliott Hughes9e0c1752013-01-09 14:02:58 -0800334 MutexLock mu(soa.Self(), *Locks::thread_suspend_count_lock_);
335 // A thread may be suspended for GC; in this code, we really want to know whether
336 // there's a debugger suspension active.
337 return thread->IsSuspended() && thread->GetDebugSuspendCount() > 0;
338}
339
Ian Rogersc0542af2014-09-03 16:16:56 -0700340static mirror::Array* DecodeNonNullArray(JDWP::RefTypeId id, JDWP::JdwpError* error)
Ian Rogersb726dcb2012-09-05 08:57:23 -0700341 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Sebastien Hertz6995c602014-09-09 12:10:13 +0200342 mirror::Object* o = Dbg::GetObjectRegistry()->Get<mirror::Object*>(id, error);
Ian Rogersc0542af2014-09-03 16:16:56 -0700343 if (o == nullptr) {
344 *error = JDWP::ERR_INVALID_OBJECT;
345 return nullptr;
Elliott Hughes436e3722012-02-17 20:01:47 -0800346 }
347 if (!o->IsArrayInstance()) {
Ian Rogersc0542af2014-09-03 16:16:56 -0700348 *error = JDWP::ERR_INVALID_ARRAY;
349 return nullptr;
Elliott Hughes436e3722012-02-17 20:01:47 -0800350 }
Ian Rogersc0542af2014-09-03 16:16:56 -0700351 *error = JDWP::ERR_NONE;
Elliott Hughes436e3722012-02-17 20:01:47 -0800352 return o->AsArray();
353}
354
Ian Rogersc0542af2014-09-03 16:16:56 -0700355static mirror::Class* DecodeClass(JDWP::RefTypeId id, JDWP::JdwpError* error)
Ian Rogersb726dcb2012-09-05 08:57:23 -0700356 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Sebastien Hertz6995c602014-09-09 12:10:13 +0200357 mirror::Object* o = Dbg::GetObjectRegistry()->Get<mirror::Object*>(id, error);
Ian Rogersc0542af2014-09-03 16:16:56 -0700358 if (o == nullptr) {
359 *error = JDWP::ERR_INVALID_OBJECT;
360 return nullptr;
Elliott Hughes436e3722012-02-17 20:01:47 -0800361 }
362 if (!o->IsClass()) {
Ian Rogersc0542af2014-09-03 16:16:56 -0700363 *error = JDWP::ERR_INVALID_CLASS;
364 return nullptr;
Elliott Hughes436e3722012-02-17 20:01:47 -0800365 }
Ian Rogersc0542af2014-09-03 16:16:56 -0700366 *error = JDWP::ERR_NONE;
Elliott Hughes436e3722012-02-17 20:01:47 -0800367 return o->AsClass();
368}
369
Ian Rogersc0542af2014-09-03 16:16:56 -0700370static Thread* DecodeThread(ScopedObjectAccessUnchecked& soa, JDWP::ObjectId thread_id,
371 JDWP::JdwpError* error)
Sebastien Hertz69206392015-04-07 15:54:25 +0200372 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_)
373 LOCKS_EXCLUDED(Locks::thread_list_lock_, Locks::thread_suspend_count_lock_) {
Sebastien Hertz6995c602014-09-09 12:10:13 +0200374 mirror::Object* thread_peer = Dbg::GetObjectRegistry()->Get<mirror::Object*>(thread_id, error);
Ian Rogersc0542af2014-09-03 16:16:56 -0700375 if (thread_peer == nullptr) {
Elliott Hughes221229c2013-01-08 18:17:50 -0800376 // This isn't even an object.
Ian Rogersc0542af2014-09-03 16:16:56 -0700377 *error = JDWP::ERR_INVALID_OBJECT;
378 return nullptr;
Elliott Hughes436e3722012-02-17 20:01:47 -0800379 }
Elliott Hughes221229c2013-01-08 18:17:50 -0800380
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800381 mirror::Class* java_lang_Thread = soa.Decode<mirror::Class*>(WellKnownClasses::java_lang_Thread);
Elliott Hughes221229c2013-01-08 18:17:50 -0800382 if (!java_lang_Thread->IsAssignableFrom(thread_peer->GetClass())) {
383 // This isn't a thread.
Ian Rogersc0542af2014-09-03 16:16:56 -0700384 *error = JDWP::ERR_INVALID_THREAD;
385 return nullptr;
Elliott Hughes221229c2013-01-08 18:17:50 -0800386 }
387
Sebastien Hertz69206392015-04-07 15:54:25 +0200388 MutexLock mu(soa.Self(), *Locks::thread_list_lock_);
Ian Rogersc0542af2014-09-03 16:16:56 -0700389 Thread* thread = Thread::FromManagedThread(soa, thread_peer);
390 // If thread is null then this a java.lang.Thread without a Thread*. Must be a un-started or a
391 // zombie.
392 *error = (thread == nullptr) ? JDWP::ERR_THREAD_NOT_ALIVE : JDWP::ERR_NONE;
393 return thread;
Elliott Hughes436e3722012-02-17 20:01:47 -0800394}
395
Elliott Hughes24437992011-11-30 14:49:33 -0800396static JDWP::JdwpTag BasicTagFromDescriptor(const char* descriptor) {
397 // JDWP deliberately uses the descriptor characters' ASCII values for its enum.
398 // Note that by "basic" we mean that we don't get more specific than JT_OBJECT.
399 return static_cast<JDWP::JdwpTag>(descriptor[0]);
400}
401
Ian Rogers1ff3c982014-08-12 02:30:58 -0700402static JDWP::JdwpTag BasicTagFromClass(mirror::Class* klass)
403 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
404 std::string temp;
405 const char* descriptor = klass->GetDescriptor(&temp);
406 return BasicTagFromDescriptor(descriptor);
407}
408
Ian Rogers98379392014-02-24 16:53:16 -0800409static JDWP::JdwpTag TagFromClass(const ScopedObjectAccessUnchecked& soa, mirror::Class* c)
Ian Rogersb726dcb2012-09-05 08:57:23 -0700410 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Ian Rogersc0542af2014-09-03 16:16:56 -0700411 CHECK(c != nullptr);
Elliott Hughes24437992011-11-30 14:49:33 -0800412 if (c->IsArrayClass()) {
413 return JDWP::JT_ARRAY;
414 }
Elliott Hughes24437992011-11-30 14:49:33 -0800415 if (c->IsStringClass()) {
416 return JDWP::JT_STRING;
Elliott Hughes24437992011-11-30 14:49:33 -0800417 }
Ian Rogers98379392014-02-24 16:53:16 -0800418 if (c->IsClassClass()) {
419 return JDWP::JT_CLASS_OBJECT;
420 }
421 {
422 mirror::Class* thread_class = soa.Decode<mirror::Class*>(WellKnownClasses::java_lang_Thread);
423 if (thread_class->IsAssignableFrom(c)) {
424 return JDWP::JT_THREAD;
425 }
426 }
427 {
428 mirror::Class* thread_group_class =
429 soa.Decode<mirror::Class*>(WellKnownClasses::java_lang_ThreadGroup);
430 if (thread_group_class->IsAssignableFrom(c)) {
431 return JDWP::JT_THREAD_GROUP;
432 }
433 }
434 {
435 mirror::Class* class_loader_class =
436 soa.Decode<mirror::Class*>(WellKnownClasses::java_lang_ClassLoader);
437 if (class_loader_class->IsAssignableFrom(c)) {
438 return JDWP::JT_CLASS_LOADER;
439 }
440 }
441 return JDWP::JT_OBJECT;
Elliott Hughes24437992011-11-30 14:49:33 -0800442}
443
444/*
445 * Objects declared to hold Object might actually hold a more specific
446 * type. The debugger may take a special interest in these (e.g. it
447 * wants to display the contents of Strings), so we want to return an
448 * appropriate tag.
449 *
450 * Null objects are tagged JT_OBJECT.
451 */
Sebastien Hertz6995c602014-09-09 12:10:13 +0200452JDWP::JdwpTag Dbg::TagFromObject(const ScopedObjectAccessUnchecked& soa, mirror::Object* o) {
Ian Rogersc0542af2014-09-03 16:16:56 -0700453 return (o == nullptr) ? JDWP::JT_OBJECT : TagFromClass(soa, o->GetClass());
Elliott Hughes24437992011-11-30 14:49:33 -0800454}
455
456static bool IsPrimitiveTag(JDWP::JdwpTag tag) {
457 switch (tag) {
458 case JDWP::JT_BOOLEAN:
459 case JDWP::JT_BYTE:
460 case JDWP::JT_CHAR:
461 case JDWP::JT_FLOAT:
462 case JDWP::JT_DOUBLE:
463 case JDWP::JT_INT:
464 case JDWP::JT_LONG:
465 case JDWP::JT_SHORT:
466 case JDWP::JT_VOID:
467 return true;
468 default:
469 return false;
470 }
471}
472
Sebastien Hertzb3b173b2015-02-06 09:16:32 +0100473void Dbg::StartJdwp() {
Elliott Hughesc0f09332012-03-26 13:27:06 -0700474 if (!gJdwpAllowed || !IsJdwpConfigured()) {
Elliott Hughes376a7a02011-10-24 18:35:55 -0700475 // No JDWP for you!
476 return;
477 }
478
Ian Rogers719d1a32014-03-06 12:13:39 -0800479 CHECK(gRegistry == nullptr);
Elliott Hughes475fc232011-10-25 15:00:35 -0700480 gRegistry = new ObjectRegistry;
481
Elliott Hughesd1cc8362011-10-24 16:58:50 -0700482 // Init JDWP if the debugger is enabled. This may connect out to a
483 // debugger, passively listen for a debugger, or block waiting for a
484 // debugger.
Sebastien Hertzb3b173b2015-02-06 09:16:32 +0100485 gJdwpState = JDWP::JdwpState::Create(&gJdwpOptions);
Ian Rogersc0542af2014-09-03 16:16:56 -0700486 if (gJdwpState == nullptr) {
Elliott Hughesf8a2df72011-12-01 12:19:54 -0800487 // We probably failed because some other process has the port already, which means that
488 // if we don't abort the user is likely to think they're talking to us when they're actually
489 // talking to that other process.
Elliott Hughes3d30d9b2011-12-07 17:35:48 -0800490 LOG(FATAL) << "Debugger thread failed to initialize";
Elliott Hughesd1cc8362011-10-24 16:58:50 -0700491 }
492
493 // If a debugger has already attached, send the "welcome" message.
494 // This may cause us to suspend all threads.
Elliott Hughes376a7a02011-10-24 18:35:55 -0700495 if (gJdwpState->IsActive()) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700496 ScopedObjectAccess soa(Thread::Current());
Sebastien Hertz7d955652014-10-22 10:57:10 +0200497 gJdwpState->PostVMStart();
Elliott Hughesd1cc8362011-10-24 16:58:50 -0700498 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700499}
500
Elliott Hughesd1cc8362011-10-24 16:58:50 -0700501void Dbg::StopJdwp() {
Sebastien Hertzc6345ef2014-08-18 19:26:39 +0200502 // Post VM_DEATH event before the JDWP connection is closed (either by the JDWP thread or the
503 // destruction of gJdwpState).
504 if (gJdwpState != nullptr && gJdwpState->IsActive()) {
505 gJdwpState->PostVMDeath();
506 }
Sebastien Hertz0376e6b2014-02-06 18:12:59 +0100507 // Prevent the JDWP thread from processing JDWP incoming packets after we close the connection.
Sebastien Hertz4e5b2082015-03-24 19:03:40 +0100508 Dispose();
Elliott Hughes376a7a02011-10-24 18:35:55 -0700509 delete gJdwpState;
Ian Rogers719d1a32014-03-06 12:13:39 -0800510 gJdwpState = nullptr;
Elliott Hughes475fc232011-10-25 15:00:35 -0700511 delete gRegistry;
Ian Rogers719d1a32014-03-06 12:13:39 -0800512 gRegistry = nullptr;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700513}
514
Elliott Hughes767a1472011-10-26 18:49:02 -0700515void Dbg::GcDidFinish() {
516 if (gDdmHpifWhen != HPIF_WHEN_NEVER) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700517 ScopedObjectAccess soa(Thread::Current());
Brian Carlstrom4d466a82014-05-08 19:05:29 -0700518 VLOG(jdwp) << "Sending heap info to DDM";
Elliott Hughes7162ad92011-10-27 14:08:42 -0700519 DdmSendHeapInfo(gDdmHpifWhen);
Elliott Hughes767a1472011-10-26 18:49:02 -0700520 }
521 if (gDdmHpsgWhen != HPSG_WHEN_NEVER) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700522 ScopedObjectAccess soa(Thread::Current());
Brian Carlstrom4d466a82014-05-08 19:05:29 -0700523 VLOG(jdwp) << "Dumping heap to DDM";
Elliott Hughes6a5bd492011-10-28 14:33:57 -0700524 DdmSendHeapSegments(false);
Elliott Hughes767a1472011-10-26 18:49:02 -0700525 }
526 if (gDdmNhsgWhen != HPSG_WHEN_NEVER) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700527 ScopedObjectAccess soa(Thread::Current());
Brian Carlstrom4d466a82014-05-08 19:05:29 -0700528 VLOG(jdwp) << "Dumping native heap to DDM";
Elliott Hughes6a5bd492011-10-28 14:33:57 -0700529 DdmSendHeapSegments(true);
Elliott Hughes767a1472011-10-26 18:49:02 -0700530 }
531}
532
Elliott Hughes4ffd3132011-10-24 12:06:42 -0700533void Dbg::SetJdwpAllowed(bool allowed) {
534 gJdwpAllowed = allowed;
535}
536
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700537DebugInvokeReq* Dbg::GetInvokeReq() {
Elliott Hughes475fc232011-10-25 15:00:35 -0700538 return Thread::Current()->GetInvokeReq();
539}
540
541Thread* Dbg::GetDebugThread() {
Ian Rogersc0542af2014-09-03 16:16:56 -0700542 return (gJdwpState != nullptr) ? gJdwpState->GetDebugThread() : nullptr;
Elliott Hughes475fc232011-10-25 15:00:35 -0700543}
544
545void Dbg::ClearWaitForEventThread() {
Sebastien Hertz2bf93f42015-01-09 18:44:05 +0100546 gJdwpState->ReleaseJdwpTokenForEvent();
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700547}
548
549void Dbg::Connected() {
Elliott Hughes3bb81562011-10-21 18:52:59 -0700550 CHECK(!gDebuggerConnected);
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -0800551 VLOG(jdwp) << "JDWP has attached";
Elliott Hughes3bb81562011-10-21 18:52:59 -0700552 gDebuggerConnected = true;
Elliott Hughes86964332012-02-15 19:37:42 -0800553 gDisposed = false;
554}
555
Sebastien Hertzf3928792014-11-17 19:00:37 +0100556bool Dbg::RequiresDeoptimization() {
557 // We don't need deoptimization if everything runs with interpreter after
558 // enabling -Xint mode.
559 return !Runtime::Current()->GetInstrumentation()->IsForcedInterpretOnly();
560}
561
Elliott Hughesa2155262011-11-16 16:26:58 -0800562void Dbg::GoActive() {
563 // Enable all debugging features, including scans for breakpoints.
564 // This is a no-op if we're already active.
565 // Only called from the JDWP handler thread.
Daniel Mihalyieb076692014-08-22 17:33:31 +0200566 if (IsDebuggerActive()) {
Elliott Hughesa2155262011-11-16 16:26:58 -0800567 return;
568 }
569
Elliott Hughesc0f09332012-03-26 13:27:06 -0700570 {
571 // TODO: dalvik only warned if there were breakpoints left over. clear in Dbg::Disconnected?
Sebastien Hertzed2be172014-08-19 15:33:43 +0200572 ReaderMutexLock mu(Thread::Current(), *Locks::breakpoint_lock_);
Elliott Hughesc0f09332012-03-26 13:27:06 -0700573 CHECK_EQ(gBreakpoints.size(), 0U);
574 }
Elliott Hughesa2155262011-11-16 16:26:58 -0800575
Sebastien Hertz138dbfc2013-12-04 18:15:25 +0100576 {
Brian Carlstrom306db812014-09-05 13:01:41 -0700577 MutexLock mu(Thread::Current(), *Locks::deoptimization_lock_);
Sebastien Hertz4d25df32014-03-21 17:44:46 +0100578 CHECK_EQ(deoptimization_requests_.size(), 0U);
579 CHECK_EQ(full_deoptimization_event_count_, 0U);
Sebastien Hertz42cd43f2014-05-13 14:15:41 +0200580 CHECK_EQ(dex_pc_change_event_ref_count_, 0U);
581 CHECK_EQ(method_enter_event_ref_count_, 0U);
582 CHECK_EQ(method_exit_event_ref_count_, 0U);
583 CHECK_EQ(field_read_event_ref_count_, 0U);
584 CHECK_EQ(field_write_event_ref_count_, 0U);
585 CHECK_EQ(exception_catch_event_ref_count_, 0U);
Sebastien Hertz138dbfc2013-12-04 18:15:25 +0100586 }
587
Ian Rogers62d6c772013-02-27 08:32:07 -0800588 Runtime* runtime = Runtime::Current();
Mathieu Chartierbf9fc582015-03-13 17:21:25 -0700589 runtime->GetThreadList()->SuspendAll(__FUNCTION__);
Ian Rogers62d6c772013-02-27 08:32:07 -0800590 Thread* self = Thread::Current();
591 ThreadState old_state = self->SetStateUnsafe(kRunnable);
592 CHECK_NE(old_state, kRunnable);
Sebastien Hertzf3928792014-11-17 19:00:37 +0100593 if (RequiresDeoptimization()) {
594 runtime->GetInstrumentation()->EnableDeoptimization();
595 }
Sebastien Hertz42cd43f2014-05-13 14:15:41 +0200596 instrumentation_events_ = 0;
Elliott Hughesa2155262011-11-16 16:26:58 -0800597 gDebuggerActive = true;
Ian Rogers62d6c772013-02-27 08:32:07 -0800598 CHECK_EQ(self->SetStateUnsafe(old_state), kRunnable);
599 runtime->GetThreadList()->ResumeAll();
600
601 LOG(INFO) << "Debugger is active";
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700602}
603
604void Dbg::Disconnected() {
Elliott Hughes234ab152011-10-26 14:02:26 -0700605 CHECK(gDebuggerConnected);
606
Elliott Hughesc0f09332012-03-26 13:27:06 -0700607 LOG(INFO) << "Debugger is no longer active";
Elliott Hughes234ab152011-10-26 14:02:26 -0700608
Ian Rogers62d6c772013-02-27 08:32:07 -0800609 // Suspend all threads and exclusively acquire the mutator lock. Set the state of the thread
610 // to kRunnable to avoid scoped object access transitions. Remove the debugger as a listener
611 // and clear the object registry.
612 Runtime* runtime = Runtime::Current();
Mathieu Chartierbf9fc582015-03-13 17:21:25 -0700613 runtime->GetThreadList()->SuspendAll(__FUNCTION__);
Ian Rogers62d6c772013-02-27 08:32:07 -0800614 Thread* self = Thread::Current();
615 ThreadState old_state = self->SetStateUnsafe(kRunnable);
Sebastien Hertzaaea7342014-02-25 15:10:04 +0100616
617 // Debugger may not be active at this point.
Daniel Mihalyieb076692014-08-22 17:33:31 +0200618 if (IsDebuggerActive()) {
Sebastien Hertzaaea7342014-02-25 15:10:04 +0100619 {
620 // Since we're going to disable deoptimization, we clear the deoptimization requests queue.
621 // This prevents us from having any pending deoptimization request when the debugger attaches
622 // to us again while no event has been requested yet.
Brian Carlstrom306db812014-09-05 13:01:41 -0700623 MutexLock mu(Thread::Current(), *Locks::deoptimization_lock_);
Sebastien Hertz4d25df32014-03-21 17:44:46 +0100624 deoptimization_requests_.clear();
625 full_deoptimization_event_count_ = 0U;
Sebastien Hertzaaea7342014-02-25 15:10:04 +0100626 }
Sebastien Hertz42cd43f2014-05-13 14:15:41 +0200627 if (instrumentation_events_ != 0) {
628 runtime->GetInstrumentation()->RemoveListener(&gDebugInstrumentationListener,
629 instrumentation_events_);
630 instrumentation_events_ = 0;
631 }
Sebastien Hertzf3928792014-11-17 19:00:37 +0100632 if (RequiresDeoptimization()) {
Sebastien Hertz0462c4c2015-04-01 16:34:17 +0200633 runtime->GetInstrumentation()->DisableDeoptimization(kDbgInstrumentationKey);
Sebastien Hertzf3928792014-11-17 19:00:37 +0100634 }
Sebastien Hertzaaea7342014-02-25 15:10:04 +0100635 gDebuggerActive = false;
Sebastien Hertz138dbfc2013-12-04 18:15:25 +0100636 }
Ian Rogers62d6c772013-02-27 08:32:07 -0800637 CHECK_EQ(self->SetStateUnsafe(old_state), kRunnable);
638 runtime->GetThreadList()->ResumeAll();
Sebastien Hertz55f65342015-01-13 22:48:34 +0100639
640 {
641 ScopedObjectAccess soa(self);
642 gRegistry->Clear();
643 }
644
645 gDebuggerConnected = false;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700646}
647
Sebastien Hertzb3b173b2015-02-06 09:16:32 +0100648void Dbg::ConfigureJdwp(const JDWP::JdwpOptions& jdwp_options) {
649 CHECK_NE(jdwp_options.transport, JDWP::kJdwpTransportUnknown);
650 gJdwpOptions = jdwp_options;
651 gJdwpConfigured = true;
652}
653
Elliott Hughesc0f09332012-03-26 13:27:06 -0700654bool Dbg::IsJdwpConfigured() {
Elliott Hughes3bb81562011-10-21 18:52:59 -0700655 return gJdwpConfigured;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700656}
657
658int64_t Dbg::LastDebuggerActivity() {
Elliott Hughesca951522011-12-05 12:01:32 -0800659 return gJdwpState->LastDebuggerActivity();
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700660}
661
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700662void Dbg::UndoDebuggerSuspensions() {
Elliott Hughes234ab152011-10-26 14:02:26 -0700663 Runtime::Current()->GetThreadList()->UndoDebuggerSuspensions();
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700664}
665
Elliott Hughes88d63092013-01-09 09:55:54 -0800666std::string Dbg::GetClassName(JDWP::RefTypeId class_id) {
Ian Rogersc0542af2014-09-03 16:16:56 -0700667 JDWP::JdwpError error;
668 mirror::Object* o = gRegistry->Get<mirror::Object*>(class_id, &error);
669 if (o == nullptr) {
670 if (error == JDWP::ERR_NONE) {
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700671 return "null";
Ian Rogersc0542af2014-09-03 16:16:56 -0700672 } else {
673 return StringPrintf("invalid object %p", reinterpret_cast<void*>(class_id));
674 }
Elliott Hughes436e3722012-02-17 20:01:47 -0800675 }
676 if (!o->IsClass()) {
Brian Carlstrom7934ac22013-07-26 10:54:15 -0700677 return StringPrintf("non-class %p", o); // This is only used for debugging output anyway.
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -0800678 }
Sebastien Hertz6995c602014-09-09 12:10:13 +0200679 return GetClassName(o->AsClass());
680}
681
682std::string Dbg::GetClassName(mirror::Class* klass) {
Sebastien Hertza9aa0ff2014-09-19 12:07:51 +0200683 if (klass == nullptr) {
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700684 return "null";
Sebastien Hertza9aa0ff2014-09-19 12:07:51 +0200685 }
Ian Rogers1ff3c982014-08-12 02:30:58 -0700686 std::string temp;
Sebastien Hertz6995c602014-09-09 12:10:13 +0200687 return DescriptorToName(klass->GetDescriptor(&temp));
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700688}
689
Ian Rogersc0542af2014-09-03 16:16:56 -0700690JDWP::JdwpError Dbg::GetClassObject(JDWP::RefTypeId id, JDWP::ObjectId* class_object_id) {
Elliott Hughes436e3722012-02-17 20:01:47 -0800691 JDWP::JdwpError status;
Ian Rogersc0542af2014-09-03 16:16:56 -0700692 mirror::Class* c = DecodeClass(id, &status);
693 if (c == nullptr) {
694 *class_object_id = 0;
Elliott Hughes436e3722012-02-17 20:01:47 -0800695 return status;
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -0800696 }
Ian Rogersc0542af2014-09-03 16:16:56 -0700697 *class_object_id = gRegistry->Add(c);
Elliott Hughes436e3722012-02-17 20:01:47 -0800698 return JDWP::ERR_NONE;
Elliott Hughes86964332012-02-15 19:37:42 -0800699}
700
Ian Rogersc0542af2014-09-03 16:16:56 -0700701JDWP::JdwpError Dbg::GetSuperclass(JDWP::RefTypeId id, JDWP::RefTypeId* superclass_id) {
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -0800702 JDWP::JdwpError status;
Ian Rogersc0542af2014-09-03 16:16:56 -0700703 mirror::Class* c = DecodeClass(id, &status);
704 if (c == nullptr) {
705 *superclass_id = 0;
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -0800706 return status;
707 }
708 if (c->IsInterface()) {
709 // http://code.google.com/p/android/issues/detail?id=20856
Ian Rogersc0542af2014-09-03 16:16:56 -0700710 *superclass_id = 0;
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -0800711 } else {
Ian Rogersc0542af2014-09-03 16:16:56 -0700712 *superclass_id = gRegistry->Add(c->GetSuperClass());
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -0800713 }
714 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700715}
716
Elliott Hughes436e3722012-02-17 20:01:47 -0800717JDWP::JdwpError Dbg::GetClassLoader(JDWP::RefTypeId id, JDWP::ExpandBuf* pReply) {
Ian Rogersc0542af2014-09-03 16:16:56 -0700718 JDWP::JdwpError error;
719 mirror::Object* o = gRegistry->Get<mirror::Object*>(id, &error);
720 if (o == nullptr) {
Elliott Hughes436e3722012-02-17 20:01:47 -0800721 return JDWP::ERR_INVALID_OBJECT;
722 }
723 expandBufAddObjectId(pReply, gRegistry->Add(o->GetClass()->GetClassLoader()));
724 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700725}
726
Elliott Hughes436e3722012-02-17 20:01:47 -0800727JDWP::JdwpError Dbg::GetModifiers(JDWP::RefTypeId id, JDWP::ExpandBuf* pReply) {
Ian Rogersc0542af2014-09-03 16:16:56 -0700728 JDWP::JdwpError error;
729 mirror::Class* c = DecodeClass(id, &error);
730 if (c == nullptr) {
731 return error;
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -0800732 }
Elliott Hughes436e3722012-02-17 20:01:47 -0800733
734 uint32_t access_flags = c->GetAccessFlags() & kAccJavaFlagsMask;
735
Yevgeny Roubande34eea2014-02-15 01:06:03 +0700736 // Set ACC_SUPER. Dex files don't contain this flag but only classes are supposed to have it set,
737 // not interfaces.
Elliott Hughes436e3722012-02-17 20:01:47 -0800738 // Class.getModifiers doesn't return it, but JDWP does, so we set it here.
Yevgeny Roubande34eea2014-02-15 01:06:03 +0700739 if ((access_flags & kAccInterface) == 0) {
740 access_flags |= kAccSuper;
741 }
Elliott Hughes436e3722012-02-17 20:01:47 -0800742
743 expandBufAdd4BE(pReply, access_flags);
744
745 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700746}
747
Ian Rogersc0542af2014-09-03 16:16:56 -0700748JDWP::JdwpError Dbg::GetMonitorInfo(JDWP::ObjectId object_id, JDWP::ExpandBuf* reply) {
749 JDWP::JdwpError error;
750 mirror::Object* o = gRegistry->Get<mirror::Object*>(object_id, &error);
751 if (o == nullptr) {
Elliott Hughesf327e072013-01-09 16:01:26 -0800752 return JDWP::ERR_INVALID_OBJECT;
753 }
754
755 // Ensure all threads are suspended while we read objects' lock words.
756 Thread* self = Thread::Current();
Sebastien Hertz54263242014-03-19 18:16:50 +0100757 CHECK_EQ(self->GetState(), kRunnable);
758 self->TransitionFromRunnableToSuspended(kSuspended);
Mathieu Chartierbf9fc582015-03-13 17:21:25 -0700759 Runtime::Current()->GetThreadList()->SuspendAll(__FUNCTION__);
Elliott Hughesf327e072013-01-09 16:01:26 -0800760
761 MonitorInfo monitor_info(o);
762
Sebastien Hertz54263242014-03-19 18:16:50 +0100763 Runtime::Current()->GetThreadList()->ResumeAll();
764 self->TransitionFromSuspendedToRunnable();
Elliott Hughesf327e072013-01-09 16:01:26 -0800765
Ian Rogersc0542af2014-09-03 16:16:56 -0700766 if (monitor_info.owner_ != nullptr) {
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700767 expandBufAddObjectId(reply, gRegistry->Add(monitor_info.owner_->GetPeer()));
Elliott Hughesf327e072013-01-09 16:01:26 -0800768 } else {
Ian Rogersc0542af2014-09-03 16:16:56 -0700769 expandBufAddObjectId(reply, gRegistry->Add(nullptr));
Elliott Hughesf327e072013-01-09 16:01:26 -0800770 }
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700771 expandBufAdd4BE(reply, monitor_info.entry_count_);
772 expandBufAdd4BE(reply, monitor_info.waiters_.size());
773 for (size_t i = 0; i < monitor_info.waiters_.size(); ++i) {
774 expandBufAddObjectId(reply, gRegistry->Add(monitor_info.waiters_[i]->GetPeer()));
Elliott Hughesf327e072013-01-09 16:01:26 -0800775 }
776 return JDWP::ERR_NONE;
777}
778
Elliott Hughes734b8c62013-01-11 15:32:45 -0800779JDWP::JdwpError Dbg::GetOwnedMonitors(JDWP::ObjectId thread_id,
Ian Rogersc0542af2014-09-03 16:16:56 -0700780 std::vector<JDWP::ObjectId>* monitors,
781 std::vector<uint32_t>* stack_depths) {
Elliott Hughes4993bbc2013-01-10 15:41:25 -0800782 struct OwnedMonitorVisitor : public StackVisitor {
Hiroshi Yamauchib5a9e3d2014-06-09 12:11:20 -0700783 OwnedMonitorVisitor(Thread* thread, Context* context,
Hiroshi Yamauchicc8c5c52014-06-13 15:08:05 -0700784 std::vector<JDWP::ObjectId>* monitor_vector,
Hiroshi Yamauchib5a9e3d2014-06-09 12:11:20 -0700785 std::vector<uint32_t>* stack_depth_vector)
Elliott Hughes4993bbc2013-01-10 15:41:25 -0800786 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_)
Nicolas Geoffray8e5bd182015-05-06 11:34:34 +0100787 : StackVisitor(thread, context, StackVisitor::StackWalkKind::kIncludeInlinedFrames),
788 current_stack_depth(0),
789 monitors(monitor_vector),
790 stack_depths(stack_depth_vector) {}
Elliott Hughes4993bbc2013-01-10 15:41:25 -0800791
792 // TODO: Enable annotalysis. We know lock is held in constructor, but abstraction confuses
793 // annotalysis.
794 bool VisitFrame() NO_THREAD_SAFETY_ANALYSIS {
795 if (!GetMethod()->IsRuntimeMethod()) {
796 Monitor::VisitLocks(this, AppendOwnedMonitors, this);
Elliott Hughes734b8c62013-01-11 15:32:45 -0800797 ++current_stack_depth;
Elliott Hughes4993bbc2013-01-10 15:41:25 -0800798 }
799 return true;
800 }
801
Hiroshi Yamauchicc8c5c52014-06-13 15:08:05 -0700802 static void AppendOwnedMonitors(mirror::Object* owned_monitor, void* arg)
803 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Ian Rogers7a22fa62013-01-23 12:16:16 -0800804 OwnedMonitorVisitor* visitor = reinterpret_cast<OwnedMonitorVisitor*>(arg);
Hiroshi Yamauchicc8c5c52014-06-13 15:08:05 -0700805 visitor->monitors->push_back(gRegistry->Add(owned_monitor));
Hiroshi Yamauchib5a9e3d2014-06-09 12:11:20 -0700806 visitor->stack_depths->push_back(visitor->current_stack_depth);
Elliott Hughes4993bbc2013-01-10 15:41:25 -0800807 }
808
Elliott Hughes734b8c62013-01-11 15:32:45 -0800809 size_t current_stack_depth;
Ian Rogersc0542af2014-09-03 16:16:56 -0700810 std::vector<JDWP::ObjectId>* const monitors;
811 std::vector<uint32_t>* const stack_depths;
Elliott Hughes4993bbc2013-01-10 15:41:25 -0800812 };
Elliott Hughes4993bbc2013-01-10 15:41:25 -0800813
Hiroshi Yamauchib5a9e3d2014-06-09 12:11:20 -0700814 ScopedObjectAccessUnchecked soa(Thread::Current());
Sebastien Hertz69206392015-04-07 15:54:25 +0200815 JDWP::JdwpError error;
816 Thread* thread = DecodeThread(soa, thread_id, &error);
817 if (thread == nullptr) {
818 return error;
819 }
820 if (!IsSuspendedForDebugger(soa, thread)) {
821 return JDWP::ERR_THREAD_NOT_SUSPENDED;
Hiroshi Yamauchib5a9e3d2014-06-09 12:11:20 -0700822 }
Hiroshi Yamauchicc8c5c52014-06-13 15:08:05 -0700823 std::unique_ptr<Context> context(Context::Create());
Ian Rogersc0542af2014-09-03 16:16:56 -0700824 OwnedMonitorVisitor visitor(thread, context.get(), monitors, stack_depths);
Hiroshi Yamauchicc8c5c52014-06-13 15:08:05 -0700825 visitor.WalkStack();
Elliott Hughes4993bbc2013-01-10 15:41:25 -0800826 return JDWP::ERR_NONE;
827}
828
Sebastien Hertz52d131d2014-03-13 16:17:40 +0100829JDWP::JdwpError Dbg::GetContendedMonitor(JDWP::ObjectId thread_id,
Ian Rogersc0542af2014-09-03 16:16:56 -0700830 JDWP::ObjectId* contended_monitor) {
Elliott Hughesf9501702013-01-11 11:22:27 -0800831 ScopedObjectAccessUnchecked soa(Thread::Current());
Ian Rogersc0542af2014-09-03 16:16:56 -0700832 *contended_monitor = 0;
Sebastien Hertz69206392015-04-07 15:54:25 +0200833 JDWP::JdwpError error;
834 Thread* thread = DecodeThread(soa, thread_id, &error);
835 if (thread == nullptr) {
836 return error;
Elliott Hughesf9501702013-01-11 11:22:27 -0800837 }
Sebastien Hertz69206392015-04-07 15:54:25 +0200838 if (!IsSuspendedForDebugger(soa, thread)) {
839 return JDWP::ERR_THREAD_NOT_SUSPENDED;
840 }
841 mirror::Object* contended_monitor_obj = Monitor::GetContendedMonitor(thread);
Hiroshi Yamauchib5a9e3d2014-06-09 12:11:20 -0700842 // Add() requires the thread_list_lock_ not held to avoid the lock
843 // level violation.
Ian Rogersc0542af2014-09-03 16:16:56 -0700844 *contended_monitor = gRegistry->Add(contended_monitor_obj);
Elliott Hughesf9501702013-01-11 11:22:27 -0800845 return JDWP::ERR_NONE;
846}
847
Elliott Hughesec0f83d2013-01-15 16:54:08 -0800848JDWP::JdwpError Dbg::GetInstanceCounts(const std::vector<JDWP::RefTypeId>& class_ids,
Ian Rogersc0542af2014-09-03 16:16:56 -0700849 std::vector<uint64_t>* counts) {
Mathieu Chartier412c7fc2014-02-07 12:18:39 -0800850 gc::Heap* heap = Runtime::Current()->GetHeap();
851 heap->CollectGarbage(false);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800852 std::vector<mirror::Class*> classes;
Ian Rogersc0542af2014-09-03 16:16:56 -0700853 counts->clear();
Elliott Hughesec0f83d2013-01-15 16:54:08 -0800854 for (size_t i = 0; i < class_ids.size(); ++i) {
Ian Rogersc0542af2014-09-03 16:16:56 -0700855 JDWP::JdwpError error;
856 mirror::Class* c = DecodeClass(class_ids[i], &error);
857 if (c == nullptr) {
858 return error;
Elliott Hughesec0f83d2013-01-15 16:54:08 -0800859 }
860 classes.push_back(c);
Ian Rogersc0542af2014-09-03 16:16:56 -0700861 counts->push_back(0);
Elliott Hughesec0f83d2013-01-15 16:54:08 -0800862 }
Ian Rogersc0542af2014-09-03 16:16:56 -0700863 heap->CountInstances(classes, false, &(*counts)[0]);
Elliott Hughesec0f83d2013-01-15 16:54:08 -0800864 return JDWP::ERR_NONE;
865}
866
Ian Rogersc0542af2014-09-03 16:16:56 -0700867JDWP::JdwpError Dbg::GetInstances(JDWP::RefTypeId class_id, int32_t max_count,
868 std::vector<JDWP::ObjectId>* instances) {
Mathieu Chartier412c7fc2014-02-07 12:18:39 -0800869 gc::Heap* heap = Runtime::Current()->GetHeap();
870 // We only want reachable instances, so do a GC.
871 heap->CollectGarbage(false);
Ian Rogersc0542af2014-09-03 16:16:56 -0700872 JDWP::JdwpError error;
873 mirror::Class* c = DecodeClass(class_id, &error);
Mathieu Chartier412c7fc2014-02-07 12:18:39 -0800874 if (c == nullptr) {
Ian Rogersc0542af2014-09-03 16:16:56 -0700875 return error;
Elliott Hughes3b78c942013-01-15 17:35:41 -0800876 }
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800877 std::vector<mirror::Object*> raw_instances;
Elliott Hughes3b78c942013-01-15 17:35:41 -0800878 Runtime::Current()->GetHeap()->GetInstances(c, max_count, raw_instances);
879 for (size_t i = 0; i < raw_instances.size(); ++i) {
Ian Rogersc0542af2014-09-03 16:16:56 -0700880 instances->push_back(gRegistry->Add(raw_instances[i]));
Elliott Hughes3b78c942013-01-15 17:35:41 -0800881 }
882 return JDWP::ERR_NONE;
883}
884
Elliott Hughes0cbaff52013-01-16 15:28:01 -0800885JDWP::JdwpError Dbg::GetReferringObjects(JDWP::ObjectId object_id, int32_t max_count,
Ian Rogersc0542af2014-09-03 16:16:56 -0700886 std::vector<JDWP::ObjectId>* referring_objects) {
Mathieu Chartier412c7fc2014-02-07 12:18:39 -0800887 gc::Heap* heap = Runtime::Current()->GetHeap();
888 heap->CollectGarbage(false);
Ian Rogersc0542af2014-09-03 16:16:56 -0700889 JDWP::JdwpError error;
890 mirror::Object* o = gRegistry->Get<mirror::Object*>(object_id, &error);
891 if (o == nullptr) {
Elliott Hughes0cbaff52013-01-16 15:28:01 -0800892 return JDWP::ERR_INVALID_OBJECT;
893 }
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800894 std::vector<mirror::Object*> raw_instances;
Mathieu Chartier412c7fc2014-02-07 12:18:39 -0800895 heap->GetReferringObjects(o, max_count, raw_instances);
Elliott Hughes0cbaff52013-01-16 15:28:01 -0800896 for (size_t i = 0; i < raw_instances.size(); ++i) {
Ian Rogersc0542af2014-09-03 16:16:56 -0700897 referring_objects->push_back(gRegistry->Add(raw_instances[i]));
Elliott Hughes0cbaff52013-01-16 15:28:01 -0800898 }
899 return JDWP::ERR_NONE;
900}
901
Ian Rogersc0542af2014-09-03 16:16:56 -0700902JDWP::JdwpError Dbg::DisableCollection(JDWP::ObjectId object_id) {
903 JDWP::JdwpError error;
904 mirror::Object* o = gRegistry->Get<mirror::Object*>(object_id, &error);
905 if (o == nullptr) {
Sebastien Hertze96060a2013-12-11 12:06:28 +0100906 return JDWP::ERR_INVALID_OBJECT;
907 }
Elliott Hughes64f574f2013-02-20 14:57:12 -0800908 gRegistry->DisableCollection(object_id);
909 return JDWP::ERR_NONE;
910}
911
Ian Rogersc0542af2014-09-03 16:16:56 -0700912JDWP::JdwpError Dbg::EnableCollection(JDWP::ObjectId object_id) {
913 JDWP::JdwpError error;
914 mirror::Object* o = gRegistry->Get<mirror::Object*>(object_id, &error);
Sebastien Hertze96060a2013-12-11 12:06:28 +0100915 // Unlike DisableCollection, JDWP specs do not state an invalid object causes an error. The RI
916 // also ignores these cases and never return an error. However it's not obvious why this command
917 // should behave differently from DisableCollection and IsCollected commands. So let's be more
918 // strict and return an error if this happens.
Ian Rogersc0542af2014-09-03 16:16:56 -0700919 if (o == nullptr) {
Sebastien Hertze96060a2013-12-11 12:06:28 +0100920 return JDWP::ERR_INVALID_OBJECT;
921 }
Elliott Hughes64f574f2013-02-20 14:57:12 -0800922 gRegistry->EnableCollection(object_id);
923 return JDWP::ERR_NONE;
924}
925
Ian Rogersc0542af2014-09-03 16:16:56 -0700926JDWP::JdwpError Dbg::IsCollected(JDWP::ObjectId object_id, bool* is_collected) {
927 *is_collected = true;
Sebastien Hertz65637eb2014-01-10 17:40:02 +0100928 if (object_id == 0) {
929 // Null object id is invalid.
Sebastien Hertze96060a2013-12-11 12:06:28 +0100930 return JDWP::ERR_INVALID_OBJECT;
931 }
Sebastien Hertz65637eb2014-01-10 17:40:02 +0100932 // JDWP specs state an INVALID_OBJECT error is returned if the object ID is not valid. However
933 // the RI seems to ignore this and assume object has been collected.
Ian Rogersc0542af2014-09-03 16:16:56 -0700934 JDWP::JdwpError error;
935 mirror::Object* o = gRegistry->Get<mirror::Object*>(object_id, &error);
936 if (o != nullptr) {
937 *is_collected = gRegistry->IsCollected(object_id);
Sebastien Hertz65637eb2014-01-10 17:40:02 +0100938 }
Elliott Hughes64f574f2013-02-20 14:57:12 -0800939 return JDWP::ERR_NONE;
940}
941
Ian Rogersc0542af2014-09-03 16:16:56 -0700942void Dbg::DisposeObject(JDWP::ObjectId object_id, uint32_t reference_count) {
Elliott Hughes64f574f2013-02-20 14:57:12 -0800943 gRegistry->DisposeObject(object_id, reference_count);
944}
945
Sebastien Hertz6995c602014-09-09 12:10:13 +0200946JDWP::JdwpTypeTag Dbg::GetTypeTag(mirror::Class* klass) {
Sebastien Hertz4d8fd492014-03-28 16:29:41 +0100947 DCHECK(klass != nullptr);
948 if (klass->IsArrayClass()) {
949 return JDWP::TT_ARRAY;
950 } else if (klass->IsInterface()) {
951 return JDWP::TT_INTERFACE;
952 } else {
953 return JDWP::TT_CLASS;
954 }
955}
956
Elliott Hughes88d63092013-01-09 09:55:54 -0800957JDWP::JdwpError Dbg::GetReflectedType(JDWP::RefTypeId class_id, JDWP::ExpandBuf* pReply) {
Ian Rogersc0542af2014-09-03 16:16:56 -0700958 JDWP::JdwpError error;
959 mirror::Class* c = DecodeClass(class_id, &error);
960 if (c == nullptr) {
961 return error;
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -0800962 }
Elliott Hughes436e3722012-02-17 20:01:47 -0800963
Sebastien Hertz4d8fd492014-03-28 16:29:41 +0100964 JDWP::JdwpTypeTag type_tag = GetTypeTag(c);
965 expandBufAdd1(pReply, type_tag);
Elliott Hughes88d63092013-01-09 09:55:54 -0800966 expandBufAddRefTypeId(pReply, class_id);
Elliott Hughes436e3722012-02-17 20:01:47 -0800967 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700968}
969
Ian Rogersc0542af2014-09-03 16:16:56 -0700970void Dbg::GetClassList(std::vector<JDWP::RefTypeId>* classes) {
Elliott Hughesa2155262011-11-16 16:26:58 -0800971 // Get the complete list of reference classes (i.e. all classes except
972 // the primitive types).
973 // Returns a newly-allocated buffer full of RefTypeId values.
974 struct ClassListCreator {
Andreas Gampe277ccbd2014-11-03 21:36:10 -0800975 explicit ClassListCreator(std::vector<JDWP::RefTypeId>* classes_in) : classes(classes_in) {
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -0800976 }
977
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800978 static bool Visit(mirror::Class* c, void* arg) {
Elliott Hughesa2155262011-11-16 16:26:58 -0800979 return reinterpret_cast<ClassListCreator*>(arg)->Visit(c);
980 }
981
Elliott Hughes64f574f2013-02-20 14:57:12 -0800982 // TODO: Enable annotalysis. We know lock is held in constructor, but abstraction confuses
983 // annotalysis.
984 bool Visit(mirror::Class* c) NO_THREAD_SAFETY_ANALYSIS {
Elliott Hughesa2155262011-11-16 16:26:58 -0800985 if (!c->IsPrimitive()) {
Ian Rogersc0542af2014-09-03 16:16:56 -0700986 classes->push_back(gRegistry->AddRefType(c));
Elliott Hughesa2155262011-11-16 16:26:58 -0800987 }
988 return true;
989 }
990
Ian Rogersc0542af2014-09-03 16:16:56 -0700991 std::vector<JDWP::RefTypeId>* const classes;
Elliott Hughesa2155262011-11-16 16:26:58 -0800992 };
993
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -0800994 ClassListCreator clc(classes);
Sebastien Hertz4537c412014-08-28 14:41:50 +0200995 Runtime::Current()->GetClassLinker()->VisitClassesWithoutClassesLock(ClassListCreator::Visit,
996 &clc);
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700997}
998
Ian Rogers1ff3c982014-08-12 02:30:58 -0700999JDWP::JdwpError Dbg::GetClassInfo(JDWP::RefTypeId class_id, JDWP::JdwpTypeTag* pTypeTag,
1000 uint32_t* pStatus, std::string* pDescriptor) {
Ian Rogersc0542af2014-09-03 16:16:56 -07001001 JDWP::JdwpError error;
1002 mirror::Class* c = DecodeClass(class_id, &error);
1003 if (c == nullptr) {
1004 return error;
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -08001005 }
1006
Elliott Hughesa2155262011-11-16 16:26:58 -08001007 if (c->IsArrayClass()) {
1008 *pStatus = JDWP::CS_VERIFIED | JDWP::CS_PREPARED;
1009 *pTypeTag = JDWP::TT_ARRAY;
1010 } else {
1011 if (c->IsErroneous()) {
1012 *pStatus = JDWP::CS_ERROR;
1013 } else {
1014 *pStatus = JDWP::CS_VERIFIED | JDWP::CS_PREPARED | JDWP::CS_INITIALIZED;
1015 }
1016 *pTypeTag = c->IsInterface() ? JDWP::TT_INTERFACE : JDWP::TT_CLASS;
1017 }
1018
Ian Rogersc0542af2014-09-03 16:16:56 -07001019 if (pDescriptor != nullptr) {
Ian Rogers1ff3c982014-08-12 02:30:58 -07001020 std::string temp;
1021 *pDescriptor = c->GetDescriptor(&temp);
Elliott Hughesa2155262011-11-16 16:26:58 -08001022 }
Elliott Hughes436e3722012-02-17 20:01:47 -08001023 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001024}
1025
Ian Rogersc0542af2014-09-03 16:16:56 -07001026void Dbg::FindLoadedClassBySignature(const char* descriptor, std::vector<JDWP::RefTypeId>* ids) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001027 std::vector<mirror::Class*> classes;
Elliott Hughes6fa602d2011-12-02 17:54:25 -08001028 Runtime::Current()->GetClassLinker()->LookupClasses(descriptor, classes);
Ian Rogersc0542af2014-09-03 16:16:56 -07001029 ids->clear();
Elliott Hughes6fa602d2011-12-02 17:54:25 -08001030 for (size_t i = 0; i < classes.size(); ++i) {
Ian Rogersc0542af2014-09-03 16:16:56 -07001031 ids->push_back(gRegistry->Add(classes[i]));
Elliott Hughes6fa602d2011-12-02 17:54:25 -08001032 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001033}
1034
Ian Rogersc0542af2014-09-03 16:16:56 -07001035JDWP::JdwpError Dbg::GetReferenceType(JDWP::ObjectId object_id, JDWP::ExpandBuf* pReply) {
1036 JDWP::JdwpError error;
1037 mirror::Object* o = gRegistry->Get<mirror::Object*>(object_id, &error);
1038 if (o == nullptr) {
Elliott Hughes2435a572012-02-17 16:07:41 -08001039 return JDWP::ERR_INVALID_OBJECT;
Elliott Hughes499c5132011-11-17 14:55:11 -08001040 }
Elliott Hughes2435a572012-02-17 16:07:41 -08001041
Sebastien Hertz4d8fd492014-03-28 16:29:41 +01001042 JDWP::JdwpTypeTag type_tag = GetTypeTag(o->GetClass());
Elliott Hughes64f574f2013-02-20 14:57:12 -08001043 JDWP::RefTypeId type_id = gRegistry->AddRefType(o->GetClass());
Elliott Hughes2435a572012-02-17 16:07:41 -08001044
1045 expandBufAdd1(pReply, type_tag);
1046 expandBufAddRefTypeId(pReply, type_id);
1047
1048 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001049}
1050
Ian Rogersfc0e94b2013-09-23 23:51:32 -07001051JDWP::JdwpError Dbg::GetSignature(JDWP::RefTypeId class_id, std::string* signature) {
Ian Rogersc0542af2014-09-03 16:16:56 -07001052 JDWP::JdwpError error;
1053 mirror::Class* c = DecodeClass(class_id, &error);
1054 if (c == nullptr) {
1055 return error;
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -08001056 }
Ian Rogers1ff3c982014-08-12 02:30:58 -07001057 std::string temp;
1058 *signature = c->GetDescriptor(&temp);
Elliott Hughes1fe7afb2012-02-13 17:23:03 -08001059 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001060}
1061
Ian Rogersc0542af2014-09-03 16:16:56 -07001062JDWP::JdwpError Dbg::GetSourceFile(JDWP::RefTypeId class_id, std::string* result) {
1063 JDWP::JdwpError error;
1064 mirror::Class* c = DecodeClass(class_id, &error);
Sebastien Hertz4206eb52014-06-05 10:15:45 +02001065 if (c == nullptr) {
Ian Rogersc0542af2014-09-03 16:16:56 -07001066 return error;
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -08001067 }
Sebastien Hertz4206eb52014-06-05 10:15:45 +02001068 const char* source_file = c->GetSourceFile();
1069 if (source_file == nullptr) {
Sebastien Hertzb7054ba2014-03-13 11:52:31 +01001070 return JDWP::ERR_ABSENT_INFORMATION;
1071 }
Ian Rogersc0542af2014-09-03 16:16:56 -07001072 *result = source_file;
Elliott Hughes436e3722012-02-17 20:01:47 -08001073 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001074}
1075
Ian Rogersc0542af2014-09-03 16:16:56 -07001076JDWP::JdwpError Dbg::GetObjectTag(JDWP::ObjectId object_id, uint8_t* tag) {
Ian Rogers98379392014-02-24 16:53:16 -08001077 ScopedObjectAccessUnchecked soa(Thread::Current());
Ian Rogersc0542af2014-09-03 16:16:56 -07001078 JDWP::JdwpError error;
1079 mirror::Object* o = gRegistry->Get<mirror::Object*>(object_id, &error);
1080 if (error != JDWP::ERR_NONE) {
1081 *tag = JDWP::JT_VOID;
1082 return error;
Elliott Hughes546b9862012-06-20 16:06:13 -07001083 }
Ian Rogersc0542af2014-09-03 16:16:56 -07001084 *tag = TagFromObject(soa, o);
Elliott Hughes546b9862012-06-20 16:06:13 -07001085 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001086}
1087
Elliott Hughesaed4be92011-12-02 16:16:23 -08001088size_t Dbg::GetTagWidth(JDWP::JdwpTag tag) {
Elliott Hughesdbb40792011-11-18 17:05:22 -08001089 switch (tag) {
1090 case JDWP::JT_VOID:
1091 return 0;
1092 case JDWP::JT_BYTE:
1093 case JDWP::JT_BOOLEAN:
1094 return 1;
1095 case JDWP::JT_CHAR:
1096 case JDWP::JT_SHORT:
1097 return 2;
1098 case JDWP::JT_FLOAT:
1099 case JDWP::JT_INT:
1100 return 4;
1101 case JDWP::JT_ARRAY:
1102 case JDWP::JT_OBJECT:
1103 case JDWP::JT_STRING:
1104 case JDWP::JT_THREAD:
1105 case JDWP::JT_THREAD_GROUP:
1106 case JDWP::JT_CLASS_LOADER:
1107 case JDWP::JT_CLASS_OBJECT:
1108 return sizeof(JDWP::ObjectId);
1109 case JDWP::JT_DOUBLE:
1110 case JDWP::JT_LONG:
1111 return 8;
1112 default:
Elliott Hughes3d30d9b2011-12-07 17:35:48 -08001113 LOG(FATAL) << "Unknown tag " << tag;
Elliott Hughesdbb40792011-11-18 17:05:22 -08001114 return -1;
1115 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001116}
1117
Ian Rogersc0542af2014-09-03 16:16:56 -07001118JDWP::JdwpError Dbg::GetArrayLength(JDWP::ObjectId array_id, int32_t* length) {
1119 JDWP::JdwpError error;
1120 mirror::Array* a = DecodeNonNullArray(array_id, &error);
1121 if (a == nullptr) {
1122 return error;
Elliott Hughes24437992011-11-30 14:49:33 -08001123 }
Ian Rogersc0542af2014-09-03 16:16:56 -07001124 *length = a->GetLength();
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -08001125 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001126}
1127
Elliott Hughes88d63092013-01-09 09:55:54 -08001128JDWP::JdwpError Dbg::OutputArray(JDWP::ObjectId array_id, int offset, int count, JDWP::ExpandBuf* pReply) {
Ian Rogersc0542af2014-09-03 16:16:56 -07001129 JDWP::JdwpError error;
1130 mirror::Array* a = DecodeNonNullArray(array_id, &error);
Ian Rogers98379392014-02-24 16:53:16 -08001131 if (a == nullptr) {
Ian Rogersc0542af2014-09-03 16:16:56 -07001132 return error;
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -08001133 }
Elliott Hughes24437992011-11-30 14:49:33 -08001134
1135 if (offset < 0 || count < 0 || offset > a->GetLength() || a->GetLength() - offset < count) {
1136 LOG(WARNING) << __FUNCTION__ << " access out of bounds: offset=" << offset << "; count=" << count;
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -08001137 return JDWP::ERR_INVALID_LENGTH;
Elliott Hughes24437992011-11-30 14:49:33 -08001138 }
Ian Rogers1ff3c982014-08-12 02:30:58 -07001139 JDWP::JdwpTag element_tag = BasicTagFromClass(a->GetClass()->GetComponentType());
1140 expandBufAdd1(pReply, element_tag);
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -08001141 expandBufAdd4BE(pReply, count);
1142
Ian Rogers1ff3c982014-08-12 02:30:58 -07001143 if (IsPrimitiveTag(element_tag)) {
1144 size_t width = GetTagWidth(element_tag);
Elliott Hughes24437992011-11-30 14:49:33 -08001145 uint8_t* dst = expandBufAddSpace(pReply, count * width);
1146 if (width == 8) {
Ian Rogersef7d42f2014-01-06 12:55:46 -08001147 const uint64_t* src8 = reinterpret_cast<uint64_t*>(a->GetRawData(sizeof(uint64_t), 0));
Elliott Hughes24437992011-11-30 14:49:33 -08001148 for (int i = 0; i < count; ++i) JDWP::Write8BE(&dst, src8[offset + i]);
1149 } else if (width == 4) {
Ian Rogersef7d42f2014-01-06 12:55:46 -08001150 const uint32_t* src4 = reinterpret_cast<uint32_t*>(a->GetRawData(sizeof(uint32_t), 0));
Elliott Hughes24437992011-11-30 14:49:33 -08001151 for (int i = 0; i < count; ++i) JDWP::Write4BE(&dst, src4[offset + i]);
1152 } else if (width == 2) {
Ian Rogersef7d42f2014-01-06 12:55:46 -08001153 const uint16_t* src2 = reinterpret_cast<uint16_t*>(a->GetRawData(sizeof(uint16_t), 0));
Elliott Hughes24437992011-11-30 14:49:33 -08001154 for (int i = 0; i < count; ++i) JDWP::Write2BE(&dst, src2[offset + i]);
1155 } else {
Ian Rogersef7d42f2014-01-06 12:55:46 -08001156 const uint8_t* src = reinterpret_cast<uint8_t*>(a->GetRawData(sizeof(uint8_t), 0));
Elliott Hughes24437992011-11-30 14:49:33 -08001157 memcpy(dst, &src[offset * width], count * width);
1158 }
1159 } else {
Ian Rogers98379392014-02-24 16:53:16 -08001160 ScopedObjectAccessUnchecked soa(Thread::Current());
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001161 mirror::ObjectArray<mirror::Object>* oa = a->AsObjectArray<mirror::Object>();
Elliott Hughes24437992011-11-30 14:49:33 -08001162 for (int i = 0; i < count; ++i) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001163 mirror::Object* element = oa->Get(offset + i);
Ian Rogers98379392014-02-24 16:53:16 -08001164 JDWP::JdwpTag specific_tag = (element != nullptr) ? TagFromObject(soa, element)
Ian Rogers1ff3c982014-08-12 02:30:58 -07001165 : element_tag;
Elliott Hughes24437992011-11-30 14:49:33 -08001166 expandBufAdd1(pReply, specific_tag);
1167 expandBufAddObjectId(pReply, gRegistry->Add(element));
1168 }
1169 }
1170
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -08001171 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001172}
1173
Ian Rogersef7d42f2014-01-06 12:55:46 -08001174template <typename T>
Ian Rogersc0542af2014-09-03 16:16:56 -07001175static void CopyArrayData(mirror::Array* a, JDWP::Request* src, int offset, int count)
Ian Rogersef7d42f2014-01-06 12:55:46 -08001176 NO_THREAD_SAFETY_ANALYSIS {
1177 // TODO: fix when annotalysis correctly handles non-member functions.
Elliott Hughes4b9702c2013-02-20 18:13:24 -08001178 DCHECK(a->GetClass()->IsPrimitiveArray());
1179
Ian Rogersef7d42f2014-01-06 12:55:46 -08001180 T* dst = reinterpret_cast<T*>(a->GetRawData(sizeof(T), offset));
Elliott Hughes4b9702c2013-02-20 18:13:24 -08001181 for (int i = 0; i < count; ++i) {
Ian Rogersc0542af2014-09-03 16:16:56 -07001182 *dst++ = src->ReadValue(sizeof(T));
Elliott Hughes4b9702c2013-02-20 18:13:24 -08001183 }
1184}
1185
Elliott Hughes88d63092013-01-09 09:55:54 -08001186JDWP::JdwpError Dbg::SetArrayElements(JDWP::ObjectId array_id, int offset, int count,
Ian Rogersc0542af2014-09-03 16:16:56 -07001187 JDWP::Request* request) {
1188 JDWP::JdwpError error;
1189 mirror::Array* dst = DecodeNonNullArray(array_id, &error);
1190 if (dst == nullptr) {
1191 return error;
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -08001192 }
Elliott Hughesf03b8f62011-12-02 14:26:25 -08001193
Elliott Hughes4b9702c2013-02-20 18:13:24 -08001194 if (offset < 0 || count < 0 || offset > dst->GetLength() || dst->GetLength() - offset < count) {
Elliott Hughesf03b8f62011-12-02 14:26:25 -08001195 LOG(WARNING) << __FUNCTION__ << " access out of bounds: offset=" << offset << "; count=" << count;
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -08001196 return JDWP::ERR_INVALID_LENGTH;
Elliott Hughesf03b8f62011-12-02 14:26:25 -08001197 }
Ian Rogers1ff3c982014-08-12 02:30:58 -07001198 JDWP::JdwpTag element_tag = BasicTagFromClass(dst->GetClass()->GetComponentType());
Elliott Hughesf03b8f62011-12-02 14:26:25 -08001199
Ian Rogers1ff3c982014-08-12 02:30:58 -07001200 if (IsPrimitiveTag(element_tag)) {
1201 size_t width = GetTagWidth(element_tag);
Elliott Hughesf03b8f62011-12-02 14:26:25 -08001202 if (width == 8) {
Elliott Hughes4b9702c2013-02-20 18:13:24 -08001203 CopyArrayData<uint64_t>(dst, request, offset, count);
Elliott Hughesf03b8f62011-12-02 14:26:25 -08001204 } else if (width == 4) {
Elliott Hughes4b9702c2013-02-20 18:13:24 -08001205 CopyArrayData<uint32_t>(dst, request, offset, count);
Elliott Hughesf03b8f62011-12-02 14:26:25 -08001206 } else if (width == 2) {
Elliott Hughes4b9702c2013-02-20 18:13:24 -08001207 CopyArrayData<uint16_t>(dst, request, offset, count);
Elliott Hughesf03b8f62011-12-02 14:26:25 -08001208 } else {
Elliott Hughes4b9702c2013-02-20 18:13:24 -08001209 CopyArrayData<uint8_t>(dst, request, offset, count);
Elliott Hughesf03b8f62011-12-02 14:26:25 -08001210 }
1211 } else {
Elliott Hughes4b9702c2013-02-20 18:13:24 -08001212 mirror::ObjectArray<mirror::Object>* oa = dst->AsObjectArray<mirror::Object>();
Elliott Hughesf03b8f62011-12-02 14:26:25 -08001213 for (int i = 0; i < count; ++i) {
Ian Rogersc0542af2014-09-03 16:16:56 -07001214 JDWP::ObjectId id = request->ReadObjectId();
Ian Rogersc0542af2014-09-03 16:16:56 -07001215 mirror::Object* o = gRegistry->Get<mirror::Object*>(id, &error);
1216 if (error != JDWP::ERR_NONE) {
1217 return error;
Elliott Hughes436e3722012-02-17 20:01:47 -08001218 }
Sebastien Hertzd2fe10a2014-01-15 10:20:56 +01001219 oa->Set<false>(offset + i, o);
Elliott Hughesf03b8f62011-12-02 14:26:25 -08001220 }
1221 }
1222
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -08001223 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001224}
1225
Sebastien Hertz2c3e77a2015-04-02 16:26:48 +02001226JDWP::JdwpError Dbg::CreateString(const std::string& str, JDWP::ObjectId* new_string_id) {
1227 Thread* self = Thread::Current();
1228 mirror::String* new_string = mirror::String::AllocFromModifiedUtf8(self, str.c_str());
1229 if (new_string == nullptr) {
1230 DCHECK(self->IsExceptionPending());
1231 self->ClearException();
1232 LOG(ERROR) << "Could not allocate string";
1233 *new_string_id = 0;
1234 return JDWP::ERR_OUT_OF_MEMORY;
1235 }
1236 *new_string_id = gRegistry->Add(new_string);
1237 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001238}
1239
Sebastien Hertz2c3e77a2015-04-02 16:26:48 +02001240JDWP::JdwpError Dbg::CreateObject(JDWP::RefTypeId class_id, JDWP::ObjectId* new_object_id) {
Ian Rogersc0542af2014-09-03 16:16:56 -07001241 JDWP::JdwpError error;
1242 mirror::Class* c = DecodeClass(class_id, &error);
1243 if (c == nullptr) {
Sebastien Hertz2c3e77a2015-04-02 16:26:48 +02001244 *new_object_id = 0;
Ian Rogersc0542af2014-09-03 16:16:56 -07001245 return error;
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -08001246 }
Sebastien Hertz2c3e77a2015-04-02 16:26:48 +02001247 Thread* self = Thread::Current();
1248 mirror::Object* new_object = c->AllocObject(self);
1249 if (new_object == nullptr) {
1250 DCHECK(self->IsExceptionPending());
1251 self->ClearException();
1252 LOG(ERROR) << "Could not allocate object of type " << PrettyDescriptor(c);
1253 *new_object_id = 0;
1254 return JDWP::ERR_OUT_OF_MEMORY;
1255 }
1256 *new_object_id = gRegistry->Add(new_object);
Elliott Hughes436e3722012-02-17 20:01:47 -08001257 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001258}
1259
Elliott Hughesbf13d362011-12-08 15:51:37 -08001260/*
1261 * Used by Eclipse's "Display" view to evaluate "new byte[5]" to get "(byte[]) [0, 0, 0, 0, 0]".
1262 */
Elliott Hughes88d63092013-01-09 09:55:54 -08001263JDWP::JdwpError Dbg::CreateArrayObject(JDWP::RefTypeId array_class_id, uint32_t length,
Sebastien Hertz2c3e77a2015-04-02 16:26:48 +02001264 JDWP::ObjectId* new_array_id) {
Ian Rogersc0542af2014-09-03 16:16:56 -07001265 JDWP::JdwpError error;
1266 mirror::Class* c = DecodeClass(array_class_id, &error);
1267 if (c == nullptr) {
Sebastien Hertz2c3e77a2015-04-02 16:26:48 +02001268 *new_array_id = 0;
Ian Rogersc0542af2014-09-03 16:16:56 -07001269 return error;
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -08001270 }
Sebastien Hertz2c3e77a2015-04-02 16:26:48 +02001271 Thread* self = Thread::Current();
1272 gc::Heap* heap = Runtime::Current()->GetHeap();
1273 mirror::Array* new_array = mirror::Array::Alloc<true>(self, c, length,
1274 c->GetComponentSizeShift(),
1275 heap->GetCurrentAllocator());
1276 if (new_array == nullptr) {
1277 DCHECK(self->IsExceptionPending());
1278 self->ClearException();
1279 LOG(ERROR) << "Could not allocate array of type " << PrettyDescriptor(c);
1280 *new_array_id = 0;
1281 return JDWP::ERR_OUT_OF_MEMORY;
1282 }
1283 *new_array_id = gRegistry->Add(new_array);
Elliott Hughes436e3722012-02-17 20:01:47 -08001284 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001285}
1286
Mathieu Chartierc7853442015-03-27 14:35:38 -07001287JDWP::FieldId Dbg::ToFieldId(const ArtField* f) {
Elliott Hughes03181a82011-11-17 17:22:21 -08001288 return static_cast<JDWP::FieldId>(reinterpret_cast<uintptr_t>(f));
Elliott Hughes03181a82011-11-17 17:22:21 -08001289}
1290
Mathieu Chartiere401d142015-04-22 13:56:20 -07001291static JDWP::MethodId ToMethodId(const ArtMethod* m)
Ian Rogersb726dcb2012-09-05 08:57:23 -07001292 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Elliott Hughes03181a82011-11-17 17:22:21 -08001293 return static_cast<JDWP::MethodId>(reinterpret_cast<uintptr_t>(m));
Elliott Hughes03181a82011-11-17 17:22:21 -08001294}
1295
Mathieu Chartierc7853442015-03-27 14:35:38 -07001296static ArtField* FromFieldId(JDWP::FieldId fid)
Ian Rogersb726dcb2012-09-05 08:57:23 -07001297 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Mathieu Chartierc7853442015-03-27 14:35:38 -07001298 return reinterpret_cast<ArtField*>(static_cast<uintptr_t>(fid));
Elliott Hughesaed4be92011-12-02 16:16:23 -08001299}
1300
Mathieu Chartiere401d142015-04-22 13:56:20 -07001301static ArtMethod* FromMethodId(JDWP::MethodId mid)
Ian Rogersb726dcb2012-09-05 08:57:23 -07001302 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07001303 return reinterpret_cast<ArtMethod*>(static_cast<uintptr_t>(mid));
Elliott Hughes03181a82011-11-17 17:22:21 -08001304}
1305
Sebastien Hertz6995c602014-09-09 12:10:13 +02001306bool Dbg::MatchThread(JDWP::ObjectId expected_thread_id, Thread* event_thread) {
1307 CHECK(event_thread != nullptr);
1308 JDWP::JdwpError error;
Mathieu Chartiere401d142015-04-22 13:56:20 -07001309 mirror::Object* expected_thread_peer = gRegistry->Get<mirror::Object*>(
1310 expected_thread_id, &error);
Sebastien Hertz6995c602014-09-09 12:10:13 +02001311 return expected_thread_peer == event_thread->GetPeer();
1312}
1313
1314bool Dbg::MatchLocation(const JDWP::JdwpLocation& expected_location,
1315 const JDWP::EventLocation& event_location) {
1316 if (expected_location.dex_pc != event_location.dex_pc) {
1317 return false;
1318 }
Mathieu Chartiere401d142015-04-22 13:56:20 -07001319 ArtMethod* m = FromMethodId(expected_location.method_id);
Sebastien Hertz6995c602014-09-09 12:10:13 +02001320 return m == event_location.method;
1321}
1322
1323bool Dbg::MatchType(mirror::Class* event_class, JDWP::RefTypeId class_id) {
Sebastien Hertza9aa0ff2014-09-19 12:07:51 +02001324 if (event_class == nullptr) {
1325 return false;
1326 }
Sebastien Hertz6995c602014-09-09 12:10:13 +02001327 JDWP::JdwpError error;
1328 mirror::Class* expected_class = DecodeClass(class_id, &error);
1329 CHECK(expected_class != nullptr);
1330 return expected_class->IsAssignableFrom(event_class);
1331}
1332
1333bool Dbg::MatchField(JDWP::RefTypeId expected_type_id, JDWP::FieldId expected_field_id,
Mathieu Chartierc7853442015-03-27 14:35:38 -07001334 ArtField* event_field) {
1335 ArtField* expected_field = FromFieldId(expected_field_id);
Sebastien Hertz6995c602014-09-09 12:10:13 +02001336 if (expected_field != event_field) {
1337 return false;
1338 }
1339 return Dbg::MatchType(event_field->GetDeclaringClass(), expected_type_id);
1340}
1341
1342bool Dbg::MatchInstance(JDWP::ObjectId expected_instance_id, mirror::Object* event_instance) {
1343 JDWP::JdwpError error;
1344 mirror::Object* modifier_instance = gRegistry->Get<mirror::Object*>(expected_instance_id, &error);
1345 return modifier_instance == event_instance;
1346}
1347
Mathieu Chartiere401d142015-04-22 13:56:20 -07001348void Dbg::SetJdwpLocation(JDWP::JdwpLocation* location, ArtMethod* m, uint32_t dex_pc)
Sebastien Hertz69206392015-04-07 15:54:25 +02001349 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_)
1350 LOCKS_EXCLUDED(Locks::thread_list_lock_,
1351 Locks::thread_suspend_count_lock_) {
Ian Rogersc0542af2014-09-03 16:16:56 -07001352 if (m == nullptr) {
Sebastien Hertza9aa0ff2014-09-19 12:07:51 +02001353 memset(location, 0, sizeof(*location));
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08001354 } else {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001355 mirror::Class* c = m->GetDeclaringClass();
Ian Rogersc0542af2014-09-03 16:16:56 -07001356 location->type_tag = GetTypeTag(c);
1357 location->class_id = gRegistry->AddRefType(c);
1358 location->method_id = ToMethodId(m);
1359 location->dex_pc = (m->IsNative() || m->IsProxyMethod()) ? static_cast<uint64_t>(-1) : dex_pc;
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08001360 }
Elliott Hughesd07986f2011-12-06 18:27:45 -08001361}
1362
Ian Rogersc0542af2014-09-03 16:16:56 -07001363std::string Dbg::GetMethodName(JDWP::MethodId method_id) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07001364 ArtMethod* m = FromMethodId(method_id);
Sebastien Hertza9aa0ff2014-09-19 12:07:51 +02001365 if (m == nullptr) {
Mathieu Chartier2cebb242015-04-21 16:50:40 -07001366 return "null";
Sebastien Hertza9aa0ff2014-09-19 12:07:51 +02001367 }
Sebastien Hertz415fd082015-06-01 11:42:27 +02001368 return m->GetInterfaceMethodIfProxy(sizeof(void*))->GetName();
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001369}
1370
Ian Rogersc0542af2014-09-03 16:16:56 -07001371std::string Dbg::GetFieldName(JDWP::FieldId field_id) {
Mathieu Chartierc7853442015-03-27 14:35:38 -07001372 ArtField* f = FromFieldId(field_id);
Sebastien Hertza9aa0ff2014-09-19 12:07:51 +02001373 if (f == nullptr) {
Mathieu Chartier2cebb242015-04-21 16:50:40 -07001374 return "null";
Sebastien Hertza9aa0ff2014-09-19 12:07:51 +02001375 }
1376 return f->GetName();
Elliott Hughesa96836a2013-01-17 12:27:49 -08001377}
1378
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001379/*
1380 * Augment the access flags for synthetic methods and fields by setting
1381 * the (as described by the spec) "0xf0000000 bit". Also, strip out any
1382 * flags not specified by the Java programming language.
1383 */
1384static uint32_t MangleAccessFlags(uint32_t accessFlags) {
1385 accessFlags &= kAccJavaFlagsMask;
1386 if ((accessFlags & kAccSynthetic) != 0) {
1387 accessFlags |= 0xf0000000;
1388 }
1389 return accessFlags;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001390}
1391
Elliott Hughesdbb40792011-11-18 17:05:22 -08001392/*
Jeff Haob7cefc72013-11-14 14:51:09 -08001393 * Circularly shifts registers so that arguments come first. Debuggers
1394 * expect slots to begin with arguments, but dex code places them at
1395 * the end.
Elliott Hughesdbb40792011-11-18 17:05:22 -08001396 */
Mathieu Chartiere401d142015-04-22 13:56:20 -07001397static uint16_t MangleSlot(uint16_t slot, ArtMethod* m)
Jeff Haob7cefc72013-11-14 14:51:09 -08001398 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07001399 const DexFile::CodeItem* code_item = m->GetCodeItem();
Sebastien Hertzcb19ebf2014-03-11 15:26:35 +01001400 if (code_item == nullptr) {
1401 // We should not get here for a method without code (native, proxy or abstract). Log it and
1402 // return the slot as is since all registers are arguments.
1403 LOG(WARNING) << "Trying to mangle slot for method without code " << PrettyMethod(m);
1404 return slot;
1405 }
Jeff Haob7cefc72013-11-14 14:51:09 -08001406 uint16_t ins_size = code_item->ins_size_;
1407 uint16_t locals_size = code_item->registers_size_ - ins_size;
1408 if (slot >= locals_size) {
1409 return slot - locals_size;
1410 } else {
1411 return slot + ins_size;
Elliott Hughesdbb40792011-11-18 17:05:22 -08001412 }
Elliott Hughesdbb40792011-11-18 17:05:22 -08001413}
1414
Jeff Haob7cefc72013-11-14 14:51:09 -08001415/*
1416 * Circularly shifts registers so that arguments come last. Reverts
1417 * slots to dex style argument placement.
1418 */
Mathieu Chartiere401d142015-04-22 13:56:20 -07001419static uint16_t DemangleSlot(uint16_t slot, ArtMethod* m, JDWP::JdwpError* error)
Ian Rogersb726dcb2012-09-05 08:57:23 -07001420 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07001421 const DexFile::CodeItem* code_item = m->GetCodeItem();
Sebastien Hertzcb19ebf2014-03-11 15:26:35 +01001422 if (code_item == nullptr) {
1423 // We should not get here for a method without code (native, proxy or abstract). Log it and
1424 // return the slot as is since all registers are arguments.
1425 LOG(WARNING) << "Trying to demangle slot for method without code " << PrettyMethod(m);
Mathieu Chartiere401d142015-04-22 13:56:20 -07001426 uint16_t vreg_count = ArtMethod::NumArgRegisters(m->GetShorty());
Sebastien Hertzabbabc82015-03-26 08:47:47 +01001427 if (slot < vreg_count) {
1428 *error = JDWP::ERR_NONE;
1429 return slot;
1430 }
Jeff Haob7cefc72013-11-14 14:51:09 -08001431 } else {
Sebastien Hertzabbabc82015-03-26 08:47:47 +01001432 if (slot < code_item->registers_size_) {
1433 uint16_t ins_size = code_item->ins_size_;
1434 uint16_t locals_size = code_item->registers_size_ - ins_size;
1435 *error = JDWP::ERR_NONE;
1436 return (slot < ins_size) ? slot + locals_size : slot - ins_size;
1437 }
Elliott Hughesdbb40792011-11-18 17:05:22 -08001438 }
Sebastien Hertzabbabc82015-03-26 08:47:47 +01001439
1440 // Slot is invalid in the method.
1441 LOG(ERROR) << "Invalid local slot " << slot << " for method " << PrettyMethod(m);
1442 *error = JDWP::ERR_INVALID_SLOT;
1443 return DexFile::kDexNoIndex16;
Elliott Hughesdbb40792011-11-18 17:05:22 -08001444}
1445
Elliott Hughes88d63092013-01-09 09:55:54 -08001446JDWP::JdwpError Dbg::OutputDeclaredFields(JDWP::RefTypeId class_id, bool with_generic, JDWP::ExpandBuf* pReply) {
Ian Rogersc0542af2014-09-03 16:16:56 -07001447 JDWP::JdwpError error;
1448 mirror::Class* c = DecodeClass(class_id, &error);
1449 if (c == nullptr) {
1450 return error;
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -08001451 }
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001452
1453 size_t instance_field_count = c->NumInstanceFields();
1454 size_t static_field_count = c->NumStaticFields();
1455
1456 expandBufAdd4BE(pReply, instance_field_count + static_field_count);
1457
1458 for (size_t i = 0; i < instance_field_count + static_field_count; ++i) {
Mathieu Chartierc7853442015-03-27 14:35:38 -07001459 ArtField* f = (i < instance_field_count) ? c->GetInstanceField(i) : c->GetStaticField(i - instance_field_count);
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001460 expandBufAddFieldId(pReply, ToFieldId(f));
Mathieu Chartier61c5ebc2014-06-05 17:42:53 -07001461 expandBufAddUtf8String(pReply, f->GetName());
1462 expandBufAddUtf8String(pReply, f->GetTypeDescriptor());
Elliott Hughesc5b734a2011-12-01 17:20:58 -08001463 if (with_generic) {
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001464 static const char genericSignature[1] = "";
1465 expandBufAddUtf8String(pReply, genericSignature);
1466 }
1467 expandBufAdd4BE(pReply, MangleAccessFlags(f->GetAccessFlags()));
1468 }
Elliott Hughes436e3722012-02-17 20:01:47 -08001469 return JDWP::ERR_NONE;
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001470}
1471
Elliott Hughes88d63092013-01-09 09:55:54 -08001472JDWP::JdwpError Dbg::OutputDeclaredMethods(JDWP::RefTypeId class_id, bool with_generic,
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001473 JDWP::ExpandBuf* pReply) {
Ian Rogersc0542af2014-09-03 16:16:56 -07001474 JDWP::JdwpError error;
1475 mirror::Class* c = DecodeClass(class_id, &error);
1476 if (c == nullptr) {
1477 return error;
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -08001478 }
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001479
1480 size_t direct_method_count = c->NumDirectMethods();
1481 size_t virtual_method_count = c->NumVirtualMethods();
1482
1483 expandBufAdd4BE(pReply, direct_method_count + virtual_method_count);
1484
Mathieu Chartiere401d142015-04-22 13:56:20 -07001485 auto* cl = Runtime::Current()->GetClassLinker();
1486 auto ptr_size = cl->GetImagePointerSize();
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001487 for (size_t i = 0; i < direct_method_count + virtual_method_count; ++i) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07001488 ArtMethod* m = i < direct_method_count ?
1489 c->GetDirectMethod(i, ptr_size) : c->GetVirtualMethod(i - direct_method_count, ptr_size);
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001490 expandBufAddMethodId(pReply, ToMethodId(m));
Sebastien Hertz415fd082015-06-01 11:42:27 +02001491 expandBufAddUtf8String(pReply, m->GetInterfaceMethodIfProxy(sizeof(void*))->GetName());
1492 expandBufAddUtf8String(pReply,
1493 m->GetInterfaceMethodIfProxy(sizeof(void*))->GetSignature().ToString());
Elliott Hughesc5b734a2011-12-01 17:20:58 -08001494 if (with_generic) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07001495 const char* generic_signature = "";
1496 expandBufAddUtf8String(pReply, generic_signature);
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001497 }
1498 expandBufAdd4BE(pReply, MangleAccessFlags(m->GetAccessFlags()));
1499 }
Elliott Hughes436e3722012-02-17 20:01:47 -08001500 return JDWP::ERR_NONE;
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001501}
1502
Elliott Hughes88d63092013-01-09 09:55:54 -08001503JDWP::JdwpError Dbg::OutputDeclaredInterfaces(JDWP::RefTypeId class_id, JDWP::ExpandBuf* pReply) {
Ian Rogersc0542af2014-09-03 16:16:56 -07001504 JDWP::JdwpError error;
Mathieu Chartierf8322842014-05-16 10:59:25 -07001505 Thread* self = Thread::Current();
1506 StackHandleScope<1> hs(self);
Ian Rogersc0542af2014-09-03 16:16:56 -07001507 Handle<mirror::Class> c(hs.NewHandle(DecodeClass(class_id, &error)));
Mathieu Chartierf8322842014-05-16 10:59:25 -07001508 if (c.Get() == nullptr) {
Ian Rogersc0542af2014-09-03 16:16:56 -07001509 return error;
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -08001510 }
Mathieu Chartierf8322842014-05-16 10:59:25 -07001511 size_t interface_count = c->NumDirectInterfaces();
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001512 expandBufAdd4BE(pReply, interface_count);
1513 for (size_t i = 0; i < interface_count; ++i) {
Mathieu Chartierf8322842014-05-16 10:59:25 -07001514 expandBufAddRefTypeId(pReply,
1515 gRegistry->AddRefType(mirror::Class::GetDirectInterface(self, c, i)));
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001516 }
Elliott Hughes436e3722012-02-17 20:01:47 -08001517 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001518}
1519
Ian Rogersc0542af2014-09-03 16:16:56 -07001520void Dbg::OutputLineTable(JDWP::RefTypeId, JDWP::MethodId method_id, JDWP::ExpandBuf* pReply) {
Elliott Hughes03181a82011-11-17 17:22:21 -08001521 struct DebugCallbackContext {
1522 int numItems;
1523 JDWP::ExpandBuf* pReply;
1524
Elliott Hughes2435a572012-02-17 16:07:41 -08001525 static bool Callback(void* context, uint32_t address, uint32_t line_number) {
Elliott Hughes03181a82011-11-17 17:22:21 -08001526 DebugCallbackContext* pContext = reinterpret_cast<DebugCallbackContext*>(context);
1527 expandBufAdd8BE(pContext->pReply, address);
Elliott Hughes2435a572012-02-17 16:07:41 -08001528 expandBufAdd4BE(pContext->pReply, line_number);
Elliott Hughes03181a82011-11-17 17:22:21 -08001529 pContext->numItems++;
Sebastien Hertzf2910ee2013-10-19 16:39:24 +02001530 return false;
Elliott Hughes03181a82011-11-17 17:22:21 -08001531 }
1532 };
Mathieu Chartiere401d142015-04-22 13:56:20 -07001533 ArtMethod* m = FromMethodId(method_id);
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07001534 const DexFile::CodeItem* code_item = m->GetCodeItem();
Elliott Hughes03181a82011-11-17 17:22:21 -08001535 uint64_t start, end;
Sebastien Hertzcb19ebf2014-03-11 15:26:35 +01001536 if (code_item == nullptr) {
1537 DCHECK(m->IsNative() || m->IsProxyMethod());
Elliott Hughes03181a82011-11-17 17:22:21 -08001538 start = -1;
1539 end = -1;
1540 } else {
1541 start = 0;
jeffhao14f0db92012-12-14 17:50:42 -08001542 // Return the index of the last instruction
Sebastien Hertzcb19ebf2014-03-11 15:26:35 +01001543 end = code_item->insns_size_in_code_units_ - 1;
Elliott Hughes03181a82011-11-17 17:22:21 -08001544 }
1545
1546 expandBufAdd8BE(pReply, start);
1547 expandBufAdd8BE(pReply, end);
1548
1549 // Add numLines later
1550 size_t numLinesOffset = expandBufGetLength(pReply);
1551 expandBufAdd4BE(pReply, 0);
1552
1553 DebugCallbackContext context;
1554 context.numItems = 0;
1555 context.pReply = pReply;
1556
Sebastien Hertzcb19ebf2014-03-11 15:26:35 +01001557 if (code_item != nullptr) {
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07001558 m->GetDexFile()->DecodeDebugInfo(code_item, m->IsStatic(), m->GetDexMethodIndex(),
Ian Rogersc0542af2014-09-03 16:16:56 -07001559 DebugCallbackContext::Callback, nullptr, &context);
Sebastien Hertzcb19ebf2014-03-11 15:26:35 +01001560 }
Elliott Hughes03181a82011-11-17 17:22:21 -08001561
1562 JDWP::Set4BE(expandBufGetBuffer(pReply) + numLinesOffset, context.numItems);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001563}
1564
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07001565void Dbg::OutputVariableTable(JDWP::RefTypeId, JDWP::MethodId method_id, bool with_generic,
1566 JDWP::ExpandBuf* pReply) {
Elliott Hughesdbb40792011-11-18 17:05:22 -08001567 struct DebugCallbackContext {
Mathieu Chartiere401d142015-04-22 13:56:20 -07001568 ArtMethod* method;
Elliott Hughesdbb40792011-11-18 17:05:22 -08001569 JDWP::ExpandBuf* pReply;
Elliott Hughesc5b734a2011-12-01 17:20:58 -08001570 size_t variable_count;
1571 bool with_generic;
Elliott Hughesdbb40792011-11-18 17:05:22 -08001572
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07001573 static void Callback(void* context, uint16_t slot, uint32_t startAddress, uint32_t endAddress,
1574 const char* name, const char* descriptor, const char* signature)
Jeff Haob7cefc72013-11-14 14:51:09 -08001575 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Elliott Hughesdbb40792011-11-18 17:05:22 -08001576 DebugCallbackContext* pContext = reinterpret_cast<DebugCallbackContext*>(context);
1577
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07001578 VLOG(jdwp) << StringPrintf(" %2zd: %d(%d) '%s' '%s' '%s' actual slot=%d mangled slot=%d",
1579 pContext->variable_count, startAddress, endAddress - startAddress,
1580 name, descriptor, signature, slot,
1581 MangleSlot(slot, pContext->method));
Elliott Hughesdbb40792011-11-18 17:05:22 -08001582
Jeff Haob7cefc72013-11-14 14:51:09 -08001583 slot = MangleSlot(slot, pContext->method);
Elliott Hughes68fdbd02011-11-29 19:22:47 -08001584
Elliott Hughesdbb40792011-11-18 17:05:22 -08001585 expandBufAdd8BE(pContext->pReply, startAddress);
1586 expandBufAddUtf8String(pContext->pReply, name);
1587 expandBufAddUtf8String(pContext->pReply, descriptor);
Elliott Hughesc5b734a2011-12-01 17:20:58 -08001588 if (pContext->with_generic) {
Elliott Hughesdbb40792011-11-18 17:05:22 -08001589 expandBufAddUtf8String(pContext->pReply, signature);
1590 }
1591 expandBufAdd4BE(pContext->pReply, endAddress - startAddress);
1592 expandBufAdd4BE(pContext->pReply, slot);
1593
Elliott Hughesc5b734a2011-12-01 17:20:58 -08001594 ++pContext->variable_count;
Elliott Hughesdbb40792011-11-18 17:05:22 -08001595 }
1596 };
Mathieu Chartiere401d142015-04-22 13:56:20 -07001597 ArtMethod* m = FromMethodId(method_id);
Elliott Hughesdbb40792011-11-18 17:05:22 -08001598
Elliott Hughesc5b734a2011-12-01 17:20:58 -08001599 // arg_count considers doubles and longs to take 2 units.
1600 // variable_count considers everything to take 1 unit.
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07001601 std::string shorty(m->GetShorty());
Mathieu Chartiere401d142015-04-22 13:56:20 -07001602 expandBufAdd4BE(pReply, ArtMethod::NumArgRegisters(shorty));
Elliott Hughesdbb40792011-11-18 17:05:22 -08001603
Elliott Hughesc5b734a2011-12-01 17:20:58 -08001604 // We don't know the total number of variables yet, so leave a blank and update it later.
1605 size_t variable_count_offset = expandBufGetLength(pReply);
Elliott Hughesdbb40792011-11-18 17:05:22 -08001606 expandBufAdd4BE(pReply, 0);
1607
1608 DebugCallbackContext context;
Jeff Haob7cefc72013-11-14 14:51:09 -08001609 context.method = m;
Elliott Hughesdbb40792011-11-18 17:05:22 -08001610 context.pReply = pReply;
Elliott Hughesc5b734a2011-12-01 17:20:58 -08001611 context.variable_count = 0;
1612 context.with_generic = with_generic;
Elliott Hughesdbb40792011-11-18 17:05:22 -08001613
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07001614 const DexFile::CodeItem* code_item = m->GetCodeItem();
Sebastien Hertzcb19ebf2014-03-11 15:26:35 +01001615 if (code_item != nullptr) {
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07001616 m->GetDexFile()->DecodeDebugInfo(
Ian Rogersc0542af2014-09-03 16:16:56 -07001617 code_item, m->IsStatic(), m->GetDexMethodIndex(), nullptr, DebugCallbackContext::Callback,
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07001618 &context);
Sebastien Hertzcb19ebf2014-03-11 15:26:35 +01001619 }
Elliott Hughesdbb40792011-11-18 17:05:22 -08001620
Elliott Hughesc5b734a2011-12-01 17:20:58 -08001621 JDWP::Set4BE(expandBufGetBuffer(pReply) + variable_count_offset, context.variable_count);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001622}
1623
Jeff Hao579b0242013-11-18 13:16:49 -08001624void Dbg::OutputMethodReturnValue(JDWP::MethodId method_id, const JValue* return_value,
1625 JDWP::ExpandBuf* pReply) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07001626 ArtMethod* m = FromMethodId(method_id);
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07001627 JDWP::JdwpTag tag = BasicTagFromDescriptor(m->GetShorty());
Jeff Hao579b0242013-11-18 13:16:49 -08001628 OutputJValue(tag, return_value, pReply);
1629}
1630
Sebastien Hertz3f52eaf2014-04-04 17:50:18 +02001631void Dbg::OutputFieldValue(JDWP::FieldId field_id, const JValue* field_value,
1632 JDWP::ExpandBuf* pReply) {
Mathieu Chartierc7853442015-03-27 14:35:38 -07001633 ArtField* f = FromFieldId(field_id);
Mathieu Chartier61c5ebc2014-06-05 17:42:53 -07001634 JDWP::JdwpTag tag = BasicTagFromDescriptor(f->GetTypeDescriptor());
Sebastien Hertz3f52eaf2014-04-04 17:50:18 +02001635 OutputJValue(tag, field_value, pReply);
1636}
1637
Elliott Hughes9777ba22013-01-17 09:04:19 -08001638JDWP::JdwpError Dbg::GetBytecodes(JDWP::RefTypeId, JDWP::MethodId method_id,
Ian Rogersc0542af2014-09-03 16:16:56 -07001639 std::vector<uint8_t>* bytecodes) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07001640 ArtMethod* m = FromMethodId(method_id);
Ian Rogersc0542af2014-09-03 16:16:56 -07001641 if (m == nullptr) {
Elliott Hughes9777ba22013-01-17 09:04:19 -08001642 return JDWP::ERR_INVALID_METHODID;
1643 }
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07001644 const DexFile::CodeItem* code_item = m->GetCodeItem();
Elliott Hughes9777ba22013-01-17 09:04:19 -08001645 size_t byte_count = code_item->insns_size_in_code_units_ * 2;
1646 const uint8_t* begin = reinterpret_cast<const uint8_t*>(code_item->insns_);
1647 const uint8_t* end = begin + byte_count;
1648 for (const uint8_t* p = begin; p != end; ++p) {
Ian Rogersc0542af2014-09-03 16:16:56 -07001649 bytecodes->push_back(*p);
Elliott Hughes9777ba22013-01-17 09:04:19 -08001650 }
1651 return JDWP::ERR_NONE;
1652}
1653
Elliott Hughes88d63092013-01-09 09:55:54 -08001654JDWP::JdwpTag Dbg::GetFieldBasicTag(JDWP::FieldId field_id) {
Mathieu Chartier61c5ebc2014-06-05 17:42:53 -07001655 return BasicTagFromDescriptor(FromFieldId(field_id)->GetTypeDescriptor());
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001656}
1657
Elliott Hughes88d63092013-01-09 09:55:54 -08001658JDWP::JdwpTag Dbg::GetStaticFieldBasicTag(JDWP::FieldId field_id) {
Mathieu Chartier61c5ebc2014-06-05 17:42:53 -07001659 return BasicTagFromDescriptor(FromFieldId(field_id)->GetTypeDescriptor());
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001660}
1661
Sebastien Hertz05c26b32015-06-11 18:42:58 +02001662static JValue GetArtFieldValue(ArtField* f, mirror::Object* o)
1663 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
1664 Primitive::Type fieldType = f->GetTypeAsPrimitiveType();
1665 JValue field_value;
1666 switch (fieldType) {
1667 case Primitive::kPrimBoolean:
1668 field_value.SetZ(f->GetBoolean(o));
1669 return field_value;
1670
1671 case Primitive::kPrimByte:
1672 field_value.SetB(f->GetByte(o));
1673 return field_value;
1674
1675 case Primitive::kPrimChar:
1676 field_value.SetC(f->GetChar(o));
1677 return field_value;
1678
1679 case Primitive::kPrimShort:
1680 field_value.SetS(f->GetShort(o));
1681 return field_value;
1682
1683 case Primitive::kPrimInt:
1684 case Primitive::kPrimFloat:
1685 // Int and Float must be treated as 32-bit values in JDWP.
1686 field_value.SetI(f->GetInt(o));
1687 return field_value;
1688
1689 case Primitive::kPrimLong:
1690 case Primitive::kPrimDouble:
1691 // Long and Double must be treated as 64-bit values in JDWP.
1692 field_value.SetJ(f->GetLong(o));
1693 return field_value;
1694
1695 case Primitive::kPrimNot:
1696 field_value.SetL(f->GetObject(o));
1697 return field_value;
1698
1699 case Primitive::kPrimVoid:
1700 LOG(FATAL) << "Attempt to read from field of type 'void'";
1701 UNREACHABLE();
1702 }
1703 LOG(FATAL) << "Attempt to read from field of unknown type";
1704 UNREACHABLE();
1705}
1706
Elliott Hughes88d63092013-01-09 09:55:54 -08001707static JDWP::JdwpError GetFieldValueImpl(JDWP::RefTypeId ref_type_id, JDWP::ObjectId object_id,
1708 JDWP::FieldId field_id, JDWP::ExpandBuf* pReply,
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001709 bool is_static)
Ian Rogersb726dcb2012-09-05 08:57:23 -07001710 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Ian Rogersc0542af2014-09-03 16:16:56 -07001711 JDWP::JdwpError error;
1712 mirror::Class* c = DecodeClass(ref_type_id, &error);
1713 if (ref_type_id != 0 && c == nullptr) {
1714 return error;
Elliott Hughes0cf74332012-02-23 23:14:00 -08001715 }
1716
Sebastien Hertz6995c602014-09-09 12:10:13 +02001717 mirror::Object* o = Dbg::GetObjectRegistry()->Get<mirror::Object*>(object_id, &error);
Ian Rogersc0542af2014-09-03 16:16:56 -07001718 if ((!is_static && o == nullptr) || error != JDWP::ERR_NONE) {
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08001719 return JDWP::ERR_INVALID_OBJECT;
1720 }
Mathieu Chartierc7853442015-03-27 14:35:38 -07001721 ArtField* f = FromFieldId(field_id);
Elliott Hughes0cf74332012-02-23 23:14:00 -08001722
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001723 mirror::Class* receiver_class = c;
Ian Rogersc0542af2014-09-03 16:16:56 -07001724 if (receiver_class == nullptr && o != nullptr) {
Elliott Hughes0cf74332012-02-23 23:14:00 -08001725 receiver_class = o->GetClass();
1726 }
Mathieu Chartier2cebb242015-04-21 16:50:40 -07001727 // TODO: should we give up now if receiver_class is null?
Ian Rogersc0542af2014-09-03 16:16:56 -07001728 if (receiver_class != nullptr && !f->GetDeclaringClass()->IsAssignableFrom(receiver_class)) {
Elliott Hughes0cf74332012-02-23 23:14:00 -08001729 LOG(INFO) << "ERR_INVALID_FIELDID: " << PrettyField(f) << " " << PrettyClass(receiver_class);
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08001730 return JDWP::ERR_INVALID_FIELDID;
1731 }
Elliott Hughesaed4be92011-12-02 16:16:23 -08001732
Elliott Hughes0cf74332012-02-23 23:14:00 -08001733 // The RI only enforces the static/non-static mismatch in one direction.
1734 // TODO: should we change the tests and check both?
1735 if (is_static) {
1736 if (!f->IsStatic()) {
1737 return JDWP::ERR_INVALID_FIELDID;
1738 }
1739 } else {
1740 if (f->IsStatic()) {
Sebastien Hertz05c26b32015-06-11 18:42:58 +02001741 LOG(WARNING) << "Ignoring non-nullptr receiver for ObjectReference.GetValues"
1742 << " on static field " << PrettyField(f);
Elliott Hughes0cf74332012-02-23 23:14:00 -08001743 }
1744 }
jeffhao0dfbb7e2012-11-28 15:26:03 -08001745 if (f->IsStatic()) {
1746 o = f->GetDeclaringClass();
1747 }
Elliott Hughes0cf74332012-02-23 23:14:00 -08001748
Sebastien Hertz05c26b32015-06-11 18:42:58 +02001749 JValue field_value(GetArtFieldValue(f, o));
Mathieu Chartier61c5ebc2014-06-05 17:42:53 -07001750 JDWP::JdwpTag tag = BasicTagFromDescriptor(f->GetTypeDescriptor());
Jeff Hao579b0242013-11-18 13:16:49 -08001751 Dbg::OutputJValue(tag, &field_value, pReply);
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08001752 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001753}
1754
Elliott Hughes88d63092013-01-09 09:55:54 -08001755JDWP::JdwpError Dbg::GetFieldValue(JDWP::ObjectId object_id, JDWP::FieldId field_id,
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001756 JDWP::ExpandBuf* pReply) {
Elliott Hughes88d63092013-01-09 09:55:54 -08001757 return GetFieldValueImpl(0, object_id, field_id, pReply, false);
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08001758}
1759
Ian Rogersc0542af2014-09-03 16:16:56 -07001760JDWP::JdwpError Dbg::GetStaticFieldValue(JDWP::RefTypeId ref_type_id, JDWP::FieldId field_id,
1761 JDWP::ExpandBuf* pReply) {
Elliott Hughes88d63092013-01-09 09:55:54 -08001762 return GetFieldValueImpl(ref_type_id, 0, field_id, pReply, true);
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08001763}
1764
Sebastien Hertz05c26b32015-06-11 18:42:58 +02001765static JDWP::JdwpError SetArtFieldValue(ArtField* f, mirror::Object* o, uint64_t value, int width)
1766 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
1767 Primitive::Type fieldType = f->GetTypeAsPrimitiveType();
1768 // Debugging only happens at runtime so we know we are not running in a transaction.
1769 static constexpr bool kNoTransactionMode = false;
1770 switch (fieldType) {
1771 case Primitive::kPrimBoolean:
1772 CHECK_EQ(width, 1);
1773 f->SetBoolean<kNoTransactionMode>(o, static_cast<uint8_t>(value));
1774 return JDWP::ERR_NONE;
1775
1776 case Primitive::kPrimByte:
1777 CHECK_EQ(width, 1);
1778 f->SetByte<kNoTransactionMode>(o, static_cast<uint8_t>(value));
1779 return JDWP::ERR_NONE;
1780
1781 case Primitive::kPrimChar:
1782 CHECK_EQ(width, 2);
1783 f->SetChar<kNoTransactionMode>(o, static_cast<uint16_t>(value));
1784 return JDWP::ERR_NONE;
1785
1786 case Primitive::kPrimShort:
1787 CHECK_EQ(width, 2);
1788 f->SetShort<kNoTransactionMode>(o, static_cast<int16_t>(value));
1789 return JDWP::ERR_NONE;
1790
1791 case Primitive::kPrimInt:
1792 case Primitive::kPrimFloat:
1793 CHECK_EQ(width, 4);
1794 // Int and Float must be treated as 32-bit values in JDWP.
1795 f->SetInt<kNoTransactionMode>(o, static_cast<int32_t>(value));
1796 return JDWP::ERR_NONE;
1797
1798 case Primitive::kPrimLong:
1799 case Primitive::kPrimDouble:
1800 CHECK_EQ(width, 8);
1801 // Long and Double must be treated as 64-bit values in JDWP.
1802 f->SetLong<kNoTransactionMode>(o, value);
1803 return JDWP::ERR_NONE;
1804
1805 case Primitive::kPrimNot: {
1806 JDWP::JdwpError error;
1807 mirror::Object* v = Dbg::GetObjectRegistry()->Get<mirror::Object*>(value, &error);
1808 if (error != JDWP::ERR_NONE) {
1809 return JDWP::ERR_INVALID_OBJECT;
1810 }
1811 if (v != nullptr) {
1812 mirror::Class* field_type;
1813 {
1814 StackHandleScope<2> hs(Thread::Current());
1815 HandleWrapper<mirror::Object> h_v(hs.NewHandleWrapper(&v));
1816 HandleWrapper<mirror::Object> h_o(hs.NewHandleWrapper(&o));
1817 field_type = f->GetType<true>();
1818 }
1819 if (!field_type->IsAssignableFrom(v->GetClass())) {
1820 return JDWP::ERR_INVALID_OBJECT;
1821 }
1822 }
1823 f->SetObject<kNoTransactionMode>(o, v);
1824 return JDWP::ERR_NONE;
1825 }
1826
1827 case Primitive::kPrimVoid:
1828 LOG(FATAL) << "Attempt to write to field of type 'void'";
1829 UNREACHABLE();
1830 }
1831 LOG(FATAL) << "Attempt to write to field of unknown type";
1832 UNREACHABLE();
1833}
1834
Elliott Hughes88d63092013-01-09 09:55:54 -08001835static JDWP::JdwpError SetFieldValueImpl(JDWP::ObjectId object_id, JDWP::FieldId field_id,
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001836 uint64_t value, int width, bool is_static)
Ian Rogersb726dcb2012-09-05 08:57:23 -07001837 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Ian Rogersc0542af2014-09-03 16:16:56 -07001838 JDWP::JdwpError error;
Sebastien Hertz6995c602014-09-09 12:10:13 +02001839 mirror::Object* o = Dbg::GetObjectRegistry()->Get<mirror::Object*>(object_id, &error);
Ian Rogersc0542af2014-09-03 16:16:56 -07001840 if ((!is_static && o == nullptr) || error != JDWP::ERR_NONE) {
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08001841 return JDWP::ERR_INVALID_OBJECT;
1842 }
Mathieu Chartierc7853442015-03-27 14:35:38 -07001843 ArtField* f = FromFieldId(field_id);
Elliott Hughes0cf74332012-02-23 23:14:00 -08001844
1845 // The RI only enforces the static/non-static mismatch in one direction.
1846 // TODO: should we change the tests and check both?
1847 if (is_static) {
1848 if (!f->IsStatic()) {
1849 return JDWP::ERR_INVALID_FIELDID;
1850 }
1851 } else {
1852 if (f->IsStatic()) {
Sebastien Hertz05c26b32015-06-11 18:42:58 +02001853 LOG(WARNING) << "Ignoring non-nullptr receiver for ObjectReference.SetValues"
1854 << " on static field " << PrettyField(f);
Elliott Hughes0cf74332012-02-23 23:14:00 -08001855 }
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08001856 }
jeffhao0dfbb7e2012-11-28 15:26:03 -08001857 if (f->IsStatic()) {
1858 o = f->GetDeclaringClass();
1859 }
Sebastien Hertz05c26b32015-06-11 18:42:58 +02001860 return SetArtFieldValue(f, o, value, width);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001861}
1862
Elliott Hughes88d63092013-01-09 09:55:54 -08001863JDWP::JdwpError Dbg::SetFieldValue(JDWP::ObjectId object_id, JDWP::FieldId field_id, uint64_t value,
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001864 int width) {
Elliott Hughes88d63092013-01-09 09:55:54 -08001865 return SetFieldValueImpl(object_id, field_id, value, width, false);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001866}
1867
Elliott Hughes88d63092013-01-09 09:55:54 -08001868JDWP::JdwpError Dbg::SetStaticFieldValue(JDWP::FieldId field_id, uint64_t value, int width) {
1869 return SetFieldValueImpl(0, field_id, value, width, true);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001870}
1871
Sebastien Hertzb0b0b492014-09-15 11:27:27 +02001872JDWP::JdwpError Dbg::StringToUtf8(JDWP::ObjectId string_id, std::string* str) {
Ian Rogersc0542af2014-09-03 16:16:56 -07001873 JDWP::JdwpError error;
Sebastien Hertzb0b0b492014-09-15 11:27:27 +02001874 mirror::Object* obj = gRegistry->Get<mirror::Object*>(string_id, &error);
1875 if (error != JDWP::ERR_NONE) {
1876 return error;
1877 }
1878 if (obj == nullptr) {
1879 return JDWP::ERR_INVALID_OBJECT;
1880 }
1881 {
1882 ScopedObjectAccessUnchecked soa(Thread::Current());
1883 mirror::Class* java_lang_String = soa.Decode<mirror::Class*>(WellKnownClasses::java_lang_String);
1884 if (!java_lang_String->IsAssignableFrom(obj->GetClass())) {
1885 // This isn't a string.
1886 return JDWP::ERR_INVALID_STRING;
1887 }
1888 }
1889 *str = obj->AsString()->ToModifiedUtf8();
1890 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001891}
1892
Jeff Hao579b0242013-11-18 13:16:49 -08001893void Dbg::OutputJValue(JDWP::JdwpTag tag, const JValue* return_value, JDWP::ExpandBuf* pReply) {
1894 if (IsPrimitiveTag(tag)) {
1895 expandBufAdd1(pReply, tag);
1896 if (tag == JDWP::JT_BOOLEAN || tag == JDWP::JT_BYTE) {
1897 expandBufAdd1(pReply, return_value->GetI());
1898 } else if (tag == JDWP::JT_CHAR || tag == JDWP::JT_SHORT) {
1899 expandBufAdd2BE(pReply, return_value->GetI());
1900 } else if (tag == JDWP::JT_FLOAT || tag == JDWP::JT_INT) {
1901 expandBufAdd4BE(pReply, return_value->GetI());
1902 } else if (tag == JDWP::JT_DOUBLE || tag == JDWP::JT_LONG) {
1903 expandBufAdd8BE(pReply, return_value->GetJ());
1904 } else {
1905 CHECK_EQ(tag, JDWP::JT_VOID);
1906 }
1907 } else {
Ian Rogers98379392014-02-24 16:53:16 -08001908 ScopedObjectAccessUnchecked soa(Thread::Current());
Jeff Hao579b0242013-11-18 13:16:49 -08001909 mirror::Object* value = return_value->GetL();
Ian Rogers98379392014-02-24 16:53:16 -08001910 expandBufAdd1(pReply, TagFromObject(soa, value));
Jeff Hao579b0242013-11-18 13:16:49 -08001911 expandBufAddObjectId(pReply, gRegistry->Add(value));
1912 }
1913}
1914
Ian Rogersc0542af2014-09-03 16:16:56 -07001915JDWP::JdwpError Dbg::GetThreadName(JDWP::ObjectId thread_id, std::string* name) {
jeffhaoa77f0f62012-12-05 17:19:31 -08001916 ScopedObjectAccessUnchecked soa(Thread::Current());
Ian Rogersc0542af2014-09-03 16:16:56 -07001917 JDWP::JdwpError error;
1918 Thread* thread = DecodeThread(soa, thread_id, &error);
1919 UNUSED(thread);
Elliott Hughes221229c2013-01-08 18:17:50 -08001920 if (error != JDWP::ERR_NONE && error != JDWP::ERR_THREAD_NOT_ALIVE) {
1921 return error;
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001922 }
Elliott Hughes221229c2013-01-08 18:17:50 -08001923
1924 // We still need to report the zombie threads' names, so we can't just call Thread::GetThreadName.
Ian Rogersc0542af2014-09-03 16:16:56 -07001925 mirror::Object* thread_object = gRegistry->Get<mirror::Object*>(thread_id, &error);
1926 CHECK(thread_object != nullptr) << error;
Mathieu Chartierc7853442015-03-27 14:35:38 -07001927 ArtField* java_lang_Thread_name_field =
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001928 soa.DecodeField(WellKnownClasses::java_lang_Thread_name);
1929 mirror::String* s =
1930 reinterpret_cast<mirror::String*>(java_lang_Thread_name_field->GetObject(thread_object));
Ian Rogersc0542af2014-09-03 16:16:56 -07001931 if (s != nullptr) {
1932 *name = s->ToModifiedUtf8();
Elliott Hughes221229c2013-01-08 18:17:50 -08001933 }
1934 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001935}
1936
Elliott Hughes221229c2013-01-08 18:17:50 -08001937JDWP::JdwpError Dbg::GetThreadGroup(JDWP::ObjectId thread_id, JDWP::ExpandBuf* pReply) {
Sebastien Hertza06430c2014-09-15 19:21:30 +02001938 ScopedObjectAccessUnchecked soa(Thread::Current());
Ian Rogersc0542af2014-09-03 16:16:56 -07001939 JDWP::JdwpError error;
1940 mirror::Object* thread_object = gRegistry->Get<mirror::Object*>(thread_id, &error);
1941 if (error != JDWP::ERR_NONE) {
Elliott Hughes2435a572012-02-17 16:07:41 -08001942 return JDWP::ERR_INVALID_OBJECT;
1943 }
Mathieu Chartier2d5f39e2014-09-19 17:52:37 -07001944 ScopedAssertNoThreadSuspension ants(soa.Self(), "Debugger: GetThreadGroup");
Elliott Hughes2435a572012-02-17 16:07:41 -08001945 // Okay, so it's an object, but is it actually a thread?
Sebastien Hertz69206392015-04-07 15:54:25 +02001946 Thread* thread = DecodeThread(soa, thread_id, &error);
1947 UNUSED(thread);
Elliott Hughes221229c2013-01-08 18:17:50 -08001948 if (error == JDWP::ERR_THREAD_NOT_ALIVE) {
1949 // Zombie threads are in the null group.
1950 expandBufAddObjectId(pReply, JDWP::ObjectId(0));
Sebastien Hertz52d131d2014-03-13 16:17:40 +01001951 error = JDWP::ERR_NONE;
1952 } else if (error == JDWP::ERR_NONE) {
1953 mirror::Class* c = soa.Decode<mirror::Class*>(WellKnownClasses::java_lang_Thread);
1954 CHECK(c != nullptr);
Mathieu Chartierc7853442015-03-27 14:35:38 -07001955 ArtField* f = soa.DecodeField(WellKnownClasses::java_lang_Thread_group);
Hiroshi Yamauchib5a9e3d2014-06-09 12:11:20 -07001956 CHECK(f != nullptr);
Sebastien Hertz52d131d2014-03-13 16:17:40 +01001957 mirror::Object* group = f->GetObject(thread_object);
Hiroshi Yamauchib5a9e3d2014-06-09 12:11:20 -07001958 CHECK(group != nullptr);
Sebastien Hertz52d131d2014-03-13 16:17:40 +01001959 JDWP::ObjectId thread_group_id = gRegistry->Add(group);
1960 expandBufAddObjectId(pReply, thread_group_id);
Elliott Hughes221229c2013-01-08 18:17:50 -08001961 }
Sebastien Hertz52d131d2014-03-13 16:17:40 +01001962 return error;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001963}
1964
Sebastien Hertza06430c2014-09-15 19:21:30 +02001965static mirror::Object* DecodeThreadGroup(ScopedObjectAccessUnchecked& soa,
1966 JDWP::ObjectId thread_group_id, JDWP::JdwpError* error)
1967 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Sebastien Hertz6995c602014-09-09 12:10:13 +02001968 mirror::Object* thread_group = Dbg::GetObjectRegistry()->Get<mirror::Object*>(thread_group_id,
1969 error);
Sebastien Hertza06430c2014-09-15 19:21:30 +02001970 if (*error != JDWP::ERR_NONE) {
1971 return nullptr;
1972 }
1973 if (thread_group == nullptr) {
1974 *error = JDWP::ERR_INVALID_OBJECT;
1975 return nullptr;
1976 }
Ian Rogers98379392014-02-24 16:53:16 -08001977 mirror::Class* c = soa.Decode<mirror::Class*>(WellKnownClasses::java_lang_ThreadGroup);
1978 CHECK(c != nullptr);
Sebastien Hertza06430c2014-09-15 19:21:30 +02001979 if (!c->IsAssignableFrom(thread_group->GetClass())) {
1980 // This is not a java.lang.ThreadGroup.
1981 *error = JDWP::ERR_INVALID_THREAD_GROUP;
1982 return nullptr;
1983 }
1984 *error = JDWP::ERR_NONE;
1985 return thread_group;
1986}
1987
1988JDWP::JdwpError Dbg::GetThreadGroupName(JDWP::ObjectId thread_group_id, JDWP::ExpandBuf* pReply) {
1989 ScopedObjectAccessUnchecked soa(Thread::Current());
1990 JDWP::JdwpError error;
1991 mirror::Object* thread_group = DecodeThreadGroup(soa, thread_group_id, &error);
1992 if (error != JDWP::ERR_NONE) {
1993 return error;
1994 }
Mathieu Chartier2d5f39e2014-09-19 17:52:37 -07001995 ScopedAssertNoThreadSuspension ants(soa.Self(), "Debugger: GetThreadGroupName");
Mathieu Chartierc7853442015-03-27 14:35:38 -07001996 ArtField* f = soa.DecodeField(WellKnownClasses::java_lang_ThreadGroup_name);
Ian Rogersc0542af2014-09-03 16:16:56 -07001997 CHECK(f != nullptr);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001998 mirror::String* s = reinterpret_cast<mirror::String*>(f->GetObject(thread_group));
Sebastien Hertza06430c2014-09-15 19:21:30 +02001999
2000 std::string thread_group_name(s->ToModifiedUtf8());
2001 expandBufAddUtf8String(pReply, thread_group_name);
2002 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002003}
2004
Sebastien Hertza06430c2014-09-15 19:21:30 +02002005JDWP::JdwpError Dbg::GetThreadGroupParent(JDWP::ObjectId thread_group_id, JDWP::ExpandBuf* pReply) {
Ian Rogers98379392014-02-24 16:53:16 -08002006 ScopedObjectAccessUnchecked soa(Thread::Current());
Ian Rogersc0542af2014-09-03 16:16:56 -07002007 JDWP::JdwpError error;
Sebastien Hertza06430c2014-09-15 19:21:30 +02002008 mirror::Object* thread_group = DecodeThreadGroup(soa, thread_group_id, &error);
2009 if (error != JDWP::ERR_NONE) {
2010 return error;
2011 }
Mathieu Chartier2d5f39e2014-09-19 17:52:37 -07002012 mirror::Object* parent;
2013 {
2014 ScopedAssertNoThreadSuspension ants(soa.Self(), "Debugger: GetThreadGroupParent");
Mathieu Chartierc7853442015-03-27 14:35:38 -07002015 ArtField* f = soa.DecodeField(WellKnownClasses::java_lang_ThreadGroup_parent);
Mathieu Chartier2d5f39e2014-09-19 17:52:37 -07002016 CHECK(f != nullptr);
2017 parent = f->GetObject(thread_group);
2018 }
Sebastien Hertza06430c2014-09-15 19:21:30 +02002019 JDWP::ObjectId parent_group_id = gRegistry->Add(parent);
2020 expandBufAddObjectId(pReply, parent_group_id);
2021 return JDWP::ERR_NONE;
2022}
2023
2024static void GetChildThreadGroups(ScopedObjectAccessUnchecked& soa, mirror::Object* thread_group,
2025 std::vector<JDWP::ObjectId>* child_thread_group_ids)
2026 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
2027 CHECK(thread_group != nullptr);
2028
2029 // Get the ArrayList<ThreadGroup> "groups" out of this thread group...
Mathieu Chartierc7853442015-03-27 14:35:38 -07002030 ArtField* groups_field = soa.DecodeField(WellKnownClasses::java_lang_ThreadGroup_groups);
Sebastien Hertza06430c2014-09-15 19:21:30 +02002031 mirror::Object* groups_array_list = groups_field->GetObject(thread_group);
Sebastien Hertze49e1952014-10-13 11:27:13 +02002032 {
2033 // The "groups" field is declared as a java.util.List: check it really is
2034 // an instance of java.util.ArrayList.
2035 CHECK(groups_array_list != nullptr);
2036 mirror::Class* java_util_ArrayList_class =
2037 soa.Decode<mirror::Class*>(WellKnownClasses::java_util_ArrayList);
2038 CHECK(groups_array_list->InstanceOf(java_util_ArrayList_class));
2039 }
Sebastien Hertza06430c2014-09-15 19:21:30 +02002040
2041 // Get the array and size out of the ArrayList<ThreadGroup>...
Mathieu Chartierc7853442015-03-27 14:35:38 -07002042 ArtField* array_field = soa.DecodeField(WellKnownClasses::java_util_ArrayList_array);
2043 ArtField* size_field = soa.DecodeField(WellKnownClasses::java_util_ArrayList_size);
Sebastien Hertza06430c2014-09-15 19:21:30 +02002044 mirror::ObjectArray<mirror::Object>* groups_array =
2045 array_field->GetObject(groups_array_list)->AsObjectArray<mirror::Object>();
2046 const int32_t size = size_field->GetInt(groups_array_list);
2047
2048 // Copy the first 'size' elements out of the array into the result.
Sebastien Hertz6995c602014-09-09 12:10:13 +02002049 ObjectRegistry* registry = Dbg::GetObjectRegistry();
Sebastien Hertza06430c2014-09-15 19:21:30 +02002050 for (int32_t i = 0; i < size; ++i) {
Sebastien Hertz6995c602014-09-09 12:10:13 +02002051 child_thread_group_ids->push_back(registry->Add(groups_array->Get(i)));
Sebastien Hertza06430c2014-09-15 19:21:30 +02002052 }
2053}
2054
2055JDWP::JdwpError Dbg::GetThreadGroupChildren(JDWP::ObjectId thread_group_id,
2056 JDWP::ExpandBuf* pReply) {
2057 ScopedObjectAccessUnchecked soa(Thread::Current());
2058 JDWP::JdwpError error;
2059 mirror::Object* thread_group = DecodeThreadGroup(soa, thread_group_id, &error);
2060 if (error != JDWP::ERR_NONE) {
2061 return error;
2062 }
2063
2064 // Add child threads.
2065 {
2066 std::vector<JDWP::ObjectId> child_thread_ids;
2067 GetThreads(thread_group, &child_thread_ids);
2068 expandBufAdd4BE(pReply, child_thread_ids.size());
2069 for (JDWP::ObjectId child_thread_id : child_thread_ids) {
2070 expandBufAddObjectId(pReply, child_thread_id);
2071 }
2072 }
2073
2074 // Add child thread groups.
2075 {
2076 std::vector<JDWP::ObjectId> child_thread_groups_ids;
2077 GetChildThreadGroups(soa, thread_group, &child_thread_groups_ids);
2078 expandBufAdd4BE(pReply, child_thread_groups_ids.size());
2079 for (JDWP::ObjectId child_thread_group_id : child_thread_groups_ids) {
2080 expandBufAddObjectId(pReply, child_thread_group_id);
2081 }
2082 }
2083
2084 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002085}
2086
2087JDWP::ObjectId Dbg::GetSystemThreadGroupId() {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002088 ScopedObjectAccessUnchecked soa(Thread::Current());
Mathieu Chartierc7853442015-03-27 14:35:38 -07002089 ArtField* f = soa.DecodeField(WellKnownClasses::java_lang_ThreadGroup_systemThreadGroup);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002090 mirror::Object* group = f->GetObject(f->GetDeclaringClass());
Ian Rogers365c1022012-06-22 15:05:28 -07002091 return gRegistry->Add(group);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002092}
2093
Jeff Hao920af3e2013-08-28 15:46:38 -07002094JDWP::JdwpThreadStatus Dbg::ToJdwpThreadStatus(ThreadState state) {
2095 switch (state) {
2096 case kBlocked:
2097 return JDWP::TS_MONITOR;
2098 case kNative:
2099 case kRunnable:
2100 case kSuspended:
2101 return JDWP::TS_RUNNING;
2102 case kSleeping:
2103 return JDWP::TS_SLEEPING;
2104 case kStarting:
2105 case kTerminated:
2106 return JDWP::TS_ZOMBIE;
2107 case kTimedWaiting:
Sebastien Hertzbae182c2013-12-17 10:42:03 +01002108 case kWaitingForCheckPointsToRun:
Jeff Hao920af3e2013-08-28 15:46:38 -07002109 case kWaitingForDebuggerSend:
2110 case kWaitingForDebuggerSuspension:
2111 case kWaitingForDebuggerToAttach:
Sebastien Hertz138dbfc2013-12-04 18:15:25 +01002112 case kWaitingForDeoptimization:
Jeff Hao920af3e2013-08-28 15:46:38 -07002113 case kWaitingForGcToComplete:
Mathieu Chartierb43390c2015-05-12 10:47:11 -07002114 case kWaitingForGetObjectsAllocated:
Jeff Hao920af3e2013-08-28 15:46:38 -07002115 case kWaitingForJniOnLoad:
Sebastien Hertzbae182c2013-12-17 10:42:03 +01002116 case kWaitingForMethodTracingStart:
Jeff Hao920af3e2013-08-28 15:46:38 -07002117 case kWaitingForSignalCatcherOutput:
Hiroshi Yamauchi0c8c3032015-01-16 16:54:35 -08002118 case kWaitingForVisitObjects:
Jeff Hao920af3e2013-08-28 15:46:38 -07002119 case kWaitingInMainDebuggerLoop:
2120 case kWaitingInMainSignalCatcherLoop:
2121 case kWaitingPerformingGc:
2122 case kWaiting:
2123 return JDWP::TS_WAIT;
2124 // Don't add a 'default' here so the compiler can spot incompatible enum changes.
2125 }
2126 LOG(FATAL) << "Unknown thread state: " << state;
2127 return JDWP::TS_ZOMBIE;
2128}
2129
Sebastien Hertz52d131d2014-03-13 16:17:40 +01002130JDWP::JdwpError Dbg::GetThreadStatus(JDWP::ObjectId thread_id, JDWP::JdwpThreadStatus* pThreadStatus,
2131 JDWP::JdwpSuspendStatus* pSuspendStatus) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002132 ScopedObjectAccess soa(Thread::Current());
Elliott Hughes499c5132011-11-17 14:55:11 -08002133
Elliott Hughes9e0c1752013-01-09 14:02:58 -08002134 *pSuspendStatus = JDWP::SUSPEND_STATUS_NOT_SUSPENDED;
2135
Ian Rogersc0542af2014-09-03 16:16:56 -07002136 JDWP::JdwpError error;
2137 Thread* thread = DecodeThread(soa, thread_id, &error);
Elliott Hughes221229c2013-01-08 18:17:50 -08002138 if (error != JDWP::ERR_NONE) {
2139 if (error == JDWP::ERR_THREAD_NOT_ALIVE) {
2140 *pThreadStatus = JDWP::TS_ZOMBIE;
Elliott Hughes221229c2013-01-08 18:17:50 -08002141 return JDWP::ERR_NONE;
2142 }
2143 return error;
Elliott Hughes499c5132011-11-17 14:55:11 -08002144 }
2145
Elliott Hughes9e0c1752013-01-09 14:02:58 -08002146 if (IsSuspendedForDebugger(soa, thread)) {
2147 *pSuspendStatus = JDWP::SUSPEND_STATUS_SUSPENDED;
Elliott Hughes499c5132011-11-17 14:55:11 -08002148 }
2149
Jeff Hao920af3e2013-08-28 15:46:38 -07002150 *pThreadStatus = ToJdwpThreadStatus(thread->GetState());
Elliott Hughes221229c2013-01-08 18:17:50 -08002151 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002152}
2153
Elliott Hughes221229c2013-01-08 18:17:50 -08002154JDWP::JdwpError Dbg::GetThreadDebugSuspendCount(JDWP::ObjectId thread_id, JDWP::ExpandBuf* pReply) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002155 ScopedObjectAccess soa(Thread::Current());
Ian Rogersc0542af2014-09-03 16:16:56 -07002156 JDWP::JdwpError error;
2157 Thread* thread = DecodeThread(soa, thread_id, &error);
Elliott Hughes221229c2013-01-08 18:17:50 -08002158 if (error != JDWP::ERR_NONE) {
2159 return error;
Elliott Hughes2435a572012-02-17 16:07:41 -08002160 }
Ian Rogers50b35e22012-10-04 10:09:15 -07002161 MutexLock mu2(soa.Self(), *Locks::thread_suspend_count_lock_);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002162 expandBufAdd4BE(pReply, thread->GetDebugSuspendCount());
Elliott Hughes2435a572012-02-17 16:07:41 -08002163 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002164}
2165
Elliott Hughesf9501702013-01-11 11:22:27 -08002166JDWP::JdwpError Dbg::Interrupt(JDWP::ObjectId thread_id) {
2167 ScopedObjectAccess soa(Thread::Current());
Ian Rogersc0542af2014-09-03 16:16:56 -07002168 JDWP::JdwpError error;
2169 Thread* thread = DecodeThread(soa, thread_id, &error);
Elliott Hughesf9501702013-01-11 11:22:27 -08002170 if (error != JDWP::ERR_NONE) {
2171 return error;
2172 }
Ian Rogersdd7624d2014-03-14 17:43:00 -07002173 thread->Interrupt(soa.Self());
Elliott Hughesf9501702013-01-11 11:22:27 -08002174 return JDWP::ERR_NONE;
2175}
2176
Sebastien Hertz070f7322014-09-09 12:08:49 +02002177static bool IsInDesiredThreadGroup(ScopedObjectAccessUnchecked& soa,
2178 mirror::Object* desired_thread_group, mirror::Object* peer)
2179 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
2180 // Do we want threads from all thread groups?
2181 if (desired_thread_group == nullptr) {
2182 return true;
2183 }
Mathieu Chartierc7853442015-03-27 14:35:38 -07002184 ArtField* thread_group_field = soa.DecodeField(WellKnownClasses::java_lang_Thread_group);
Sebastien Hertz070f7322014-09-09 12:08:49 +02002185 DCHECK(thread_group_field != nullptr);
2186 mirror::Object* group = thread_group_field->GetObject(peer);
2187 return (group == desired_thread_group);
2188}
2189
Sebastien Hertza06430c2014-09-15 19:21:30 +02002190void Dbg::GetThreads(mirror::Object* thread_group, std::vector<JDWP::ObjectId>* thread_ids) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002191 ScopedObjectAccessUnchecked soa(Thread::Current());
Sebastien Hertz070f7322014-09-09 12:08:49 +02002192 std::list<Thread*> all_threads_list;
2193 {
2194 MutexLock mu(Thread::Current(), *Locks::thread_list_lock_);
2195 all_threads_list = Runtime::Current()->GetThreadList()->GetList();
2196 }
2197 for (Thread* t : all_threads_list) {
2198 if (t == Dbg::GetDebugThread()) {
2199 // Skip the JDWP thread. Some debuggers get bent out of shape when they can't suspend and
2200 // query all threads, so it's easier if we just don't tell them about this thread.
2201 continue;
2202 }
2203 if (t->IsStillStarting()) {
2204 // This thread is being started (and has been registered in the thread list). However, it is
2205 // not completely started yet so we must ignore it.
2206 continue;
2207 }
2208 mirror::Object* peer = t->GetPeer();
2209 if (peer == nullptr) {
Mathieu Chartier2cebb242015-04-21 16:50:40 -07002210 // peer might be null if the thread is still starting up. We can't tell the debugger about
Sebastien Hertz070f7322014-09-09 12:08:49 +02002211 // this thread yet.
2212 // TODO: if we identified threads to the debugger by their Thread*
2213 // rather than their peer's mirror::Object*, we could fix this.
2214 // Doing so might help us report ZOMBIE threads too.
2215 continue;
2216 }
2217 if (IsInDesiredThreadGroup(soa, thread_group, peer)) {
2218 thread_ids->push_back(gRegistry->Add(peer));
2219 }
2220 }
Elliott Hughescaf76542012-06-28 16:08:22 -07002221}
Elliott Hughesa2155262011-11-16 16:26:58 -08002222
Ian Rogersc0542af2014-09-03 16:16:56 -07002223static int GetStackDepth(Thread* thread) SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Ian Rogers0399dde2012-06-06 17:09:28 -07002224 struct CountStackDepthVisitor : public StackVisitor {
Andreas Gampe277ccbd2014-11-03 21:36:10 -08002225 explicit CountStackDepthVisitor(Thread* thread_in)
Nicolas Geoffray8e5bd182015-05-06 11:34:34 +01002226 : StackVisitor(thread_in, nullptr, StackVisitor::StackWalkKind::kIncludeInlinedFrames),
2227 depth(0) {}
Ian Rogers0399dde2012-06-06 17:09:28 -07002228
Elliott Hughes64f574f2013-02-20 14:57:12 -08002229 // TODO: Enable annotalysis. We know lock is held in constructor, but abstraction confuses
2230 // annotalysis.
2231 bool VisitFrame() NO_THREAD_SAFETY_ANALYSIS {
Ian Rogers0399dde2012-06-06 17:09:28 -07002232 if (!GetMethod()->IsRuntimeMethod()) {
Elliott Hughesf8a2df72011-12-01 12:19:54 -08002233 ++depth;
2234 }
Elliott Hughes530fa002012-03-12 11:44:49 -07002235 return true;
Elliott Hughesa2e54f62011-11-17 13:01:30 -08002236 }
2237 size_t depth;
2238 };
Elliott Hughes08fc03a2012-06-26 17:34:00 -07002239
Ian Rogers7a22fa62013-01-23 12:16:16 -08002240 CountStackDepthVisitor visitor(thread);
Ian Rogers0399dde2012-06-06 17:09:28 -07002241 visitor.WalkStack();
Elliott Hughesa2e54f62011-11-17 13:01:30 -08002242 return visitor.depth;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002243}
2244
Ian Rogersc0542af2014-09-03 16:16:56 -07002245JDWP::JdwpError Dbg::GetThreadFrameCount(JDWP::ObjectId thread_id, size_t* result) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002246 ScopedObjectAccess soa(Thread::Current());
Ian Rogersc0542af2014-09-03 16:16:56 -07002247 JDWP::JdwpError error;
2248 *result = 0;
2249 Thread* thread = DecodeThread(soa, thread_id, &error);
Elliott Hughes221229c2013-01-08 18:17:50 -08002250 if (error != JDWP::ERR_NONE) {
2251 return error;
2252 }
Elliott Hughesf15f4a02013-01-09 10:09:38 -08002253 if (!IsSuspendedForDebugger(soa, thread)) {
2254 return JDWP::ERR_THREAD_NOT_SUSPENDED;
2255 }
Ian Rogersc0542af2014-09-03 16:16:56 -07002256 *result = GetStackDepth(thread);
Elliott Hughes221229c2013-01-08 18:17:50 -08002257 return JDWP::ERR_NONE;
Elliott Hughes86964332012-02-15 19:37:42 -08002258}
2259
Ian Rogers306057f2012-11-26 12:45:53 -08002260JDWP::JdwpError Dbg::GetThreadFrames(JDWP::ObjectId thread_id, size_t start_frame,
2261 size_t frame_count, JDWP::ExpandBuf* buf) {
Elliott Hughes6e9d22c2012-06-22 15:02:37 -07002262 class GetFrameVisitor : public StackVisitor {
2263 public:
Andreas Gampe277ccbd2014-11-03 21:36:10 -08002264 GetFrameVisitor(Thread* thread, size_t start_frame_in, size_t frame_count_in,
2265 JDWP::ExpandBuf* buf_in)
Ian Rogersb726dcb2012-09-05 08:57:23 -07002266 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_)
Nicolas Geoffray8e5bd182015-05-06 11:34:34 +01002267 : StackVisitor(thread, nullptr, StackVisitor::StackWalkKind::kIncludeInlinedFrames),
2268 depth_(0),
2269 start_frame_(start_frame_in),
2270 frame_count_(frame_count_in),
2271 buf_(buf_in) {
Elliott Hughes6e9d22c2012-06-22 15:02:37 -07002272 expandBufAdd4BE(buf_, frame_count_);
Elliott Hughes03181a82011-11-17 17:22:21 -08002273 }
Ian Rogers0399dde2012-06-06 17:09:28 -07002274
Sebastien Hertz69206392015-04-07 15:54:25 +02002275 bool VisitFrame() OVERRIDE SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Ian Rogers0399dde2012-06-06 17:09:28 -07002276 if (GetMethod()->IsRuntimeMethod()) {
Brian Carlstrom7934ac22013-07-26 10:54:15 -07002277 return true; // The debugger can't do anything useful with a frame that has no Method*.
Elliott Hughes03181a82011-11-17 17:22:21 -08002278 }
Elliott Hughes6e9d22c2012-06-22 15:02:37 -07002279 if (depth_ >= start_frame_ + frame_count_) {
Elliott Hughes530fa002012-03-12 11:44:49 -07002280 return false;
Elliott Hughes03181a82011-11-17 17:22:21 -08002281 }
Elliott Hughes6e9d22c2012-06-22 15:02:37 -07002282 if (depth_ >= start_frame_) {
2283 JDWP::FrameId frame_id(GetFrameId());
2284 JDWP::JdwpLocation location;
Sebastien Hertz6995c602014-09-09 12:10:13 +02002285 SetJdwpLocation(&location, GetMethod(), GetDexPc());
Ian Rogersef7d42f2014-01-06 12:55:46 -08002286 VLOG(jdwp) << StringPrintf(" Frame %3zd: id=%3" PRIu64 " ", depth_, frame_id) << location;
Elliott Hughes6e9d22c2012-06-22 15:02:37 -07002287 expandBufAdd8BE(buf_, frame_id);
2288 expandBufAddLocation(buf_, location);
2289 }
2290 ++depth_;
Elliott Hughes530fa002012-03-12 11:44:49 -07002291 return true;
Elliott Hughes03181a82011-11-17 17:22:21 -08002292 }
Elliott Hughes6e9d22c2012-06-22 15:02:37 -07002293
2294 private:
2295 size_t depth_;
2296 const size_t start_frame_;
2297 const size_t frame_count_;
2298 JDWP::ExpandBuf* buf_;
Elliott Hughes03181a82011-11-17 17:22:21 -08002299 };
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002300
2301 ScopedObjectAccessUnchecked soa(Thread::Current());
Ian Rogersc0542af2014-09-03 16:16:56 -07002302 JDWP::JdwpError error;
2303 Thread* thread = DecodeThread(soa, thread_id, &error);
Elliott Hughes221229c2013-01-08 18:17:50 -08002304 if (error != JDWP::ERR_NONE) {
2305 return error;
2306 }
Elliott Hughesf15f4a02013-01-09 10:09:38 -08002307 if (!IsSuspendedForDebugger(soa, thread)) {
2308 return JDWP::ERR_THREAD_NOT_SUSPENDED;
2309 }
Ian Rogers7a22fa62013-01-23 12:16:16 -08002310 GetFrameVisitor visitor(thread, start_frame, frame_count, buf);
Ian Rogers0399dde2012-06-06 17:09:28 -07002311 visitor.WalkStack();
Elliott Hughes6e9d22c2012-06-22 15:02:37 -07002312 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002313}
2314
2315JDWP::ObjectId Dbg::GetThreadSelfId() {
Sebastien Hertz6995c602014-09-09 12:10:13 +02002316 return GetThreadId(Thread::Current());
2317}
2318
2319JDWP::ObjectId Dbg::GetThreadId(Thread* thread) {
Mathieu Chartierdbe6f462012-09-25 16:54:50 -07002320 ScopedObjectAccessUnchecked soa(Thread::Current());
Sebastien Hertz6995c602014-09-09 12:10:13 +02002321 return gRegistry->Add(thread->GetPeer());
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002322}
2323
Elliott Hughes475fc232011-10-25 15:00:35 -07002324void Dbg::SuspendVM() {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002325 Runtime::Current()->GetThreadList()->SuspendAllForDebugger();
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002326}
2327
2328void Dbg::ResumeVM() {
Sebastien Hertz253fa552014-10-14 17:27:15 +02002329 Runtime::Current()->GetThreadList()->ResumeAllForDebugger();
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002330}
2331
Elliott Hughes221229c2013-01-08 18:17:50 -08002332JDWP::JdwpError Dbg::SuspendThread(JDWP::ObjectId thread_id, bool request_suspension) {
Ian Rogersf3d874c2014-07-17 18:52:42 -07002333 Thread* self = Thread::Current();
Ian Rogersc0542af2014-09-03 16:16:56 -07002334 ScopedLocalRef<jobject> peer(self->GetJniEnv(), nullptr);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002335 {
Ian Rogersf3d874c2014-07-17 18:52:42 -07002336 ScopedObjectAccess soa(self);
Ian Rogersc0542af2014-09-03 16:16:56 -07002337 JDWP::JdwpError error;
2338 peer.reset(soa.AddLocalReference<jobject>(gRegistry->Get<mirror::Object*>(thread_id, &error)));
Elliott Hughes4e235312011-12-02 11:34:15 -08002339 }
Ian Rogersc0542af2014-09-03 16:16:56 -07002340 if (peer.get() == nullptr) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002341 return JDWP::ERR_THREAD_NOT_ALIVE;
2342 }
Ian Rogers4ad5cd32014-11-11 23:08:07 -08002343 // Suspend thread to build stack trace.
Elliott Hughesf327e072013-01-09 16:01:26 -08002344 bool timed_out;
Brian Carlstromba32de42014-08-27 23:43:46 -07002345 ThreadList* thread_list = Runtime::Current()->GetThreadList();
2346 Thread* thread = thread_list->SuspendThreadByPeer(peer.get(), request_suspension, true,
2347 &timed_out);
Ian Rogersc0542af2014-09-03 16:16:56 -07002348 if (thread != nullptr) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002349 return JDWP::ERR_NONE;
Elliott Hughesf327e072013-01-09 16:01:26 -08002350 } else if (timed_out) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002351 return JDWP::ERR_INTERNAL;
2352 } else {
2353 return JDWP::ERR_THREAD_NOT_ALIVE;
2354 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002355}
2356
Elliott Hughes221229c2013-01-08 18:17:50 -08002357void Dbg::ResumeThread(JDWP::ObjectId thread_id) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002358 ScopedObjectAccessUnchecked soa(Thread::Current());
Ian Rogersc0542af2014-09-03 16:16:56 -07002359 JDWP::JdwpError error;
2360 mirror::Object* peer = gRegistry->Get<mirror::Object*>(thread_id, &error);
2361 CHECK(peer != nullptr) << error;
jeffhaoa77f0f62012-12-05 17:19:31 -08002362 Thread* thread;
2363 {
2364 MutexLock mu(soa.Self(), *Locks::thread_list_lock_);
2365 thread = Thread::FromManagedThread(soa, peer);
2366 }
Ian Rogersc0542af2014-09-03 16:16:56 -07002367 if (thread == nullptr) {
Elliott Hughes4e235312011-12-02 11:34:15 -08002368 LOG(WARNING) << "No such thread for resume: " << peer;
2369 return;
2370 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002371 bool needs_resume;
2372 {
Ian Rogers50b35e22012-10-04 10:09:15 -07002373 MutexLock mu2(soa.Self(), *Locks::thread_suspend_count_lock_);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002374 needs_resume = thread->GetSuspendCount() > 0;
2375 }
2376 if (needs_resume) {
Elliott Hughes546b9862012-06-20 16:06:13 -07002377 Runtime::Current()->GetThreadList()->Resume(thread, true);
2378 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002379}
2380
2381void Dbg::SuspendSelf() {
Elliott Hughes475fc232011-10-25 15:00:35 -07002382 Runtime::Current()->GetThreadList()->SuspendSelfForDebugger();
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002383}
2384
Ian Rogers0399dde2012-06-06 17:09:28 -07002385struct GetThisVisitor : public StackVisitor {
Andreas Gampe277ccbd2014-11-03 21:36:10 -08002386 GetThisVisitor(Thread* thread, Context* context, JDWP::FrameId frame_id_in)
Ian Rogersb726dcb2012-09-05 08:57:23 -07002387 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_)
Nicolas Geoffray8e5bd182015-05-06 11:34:34 +01002388 : StackVisitor(thread, context, StackVisitor::StackWalkKind::kIncludeInlinedFrames),
2389 this_object(nullptr),
2390 frame_id(frame_id_in) {}
Ian Rogers0399dde2012-06-06 17:09:28 -07002391
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002392 // TODO: Enable annotalysis. We know lock is held in constructor, but abstraction confuses
2393 // annotalysis.
2394 virtual bool VisitFrame() NO_THREAD_SAFETY_ANALYSIS {
Elliott Hughes6e9d22c2012-06-22 15:02:37 -07002395 if (frame_id != GetFrameId()) {
Ian Rogers0399dde2012-06-06 17:09:28 -07002396 return true; // continue
Ian Rogers0399dde2012-06-06 17:09:28 -07002397 } else {
Ian Rogers62d6c772013-02-27 08:32:07 -08002398 this_object = GetThisObject();
2399 return false;
Ian Rogers0399dde2012-06-06 17:09:28 -07002400 }
Elliott Hughes86b00102011-12-05 17:54:26 -08002401 }
Ian Rogers0399dde2012-06-06 17:09:28 -07002402
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002403 mirror::Object* this_object;
Elliott Hughes6e9d22c2012-06-22 15:02:37 -07002404 JDWP::FrameId frame_id;
Ian Rogers0399dde2012-06-06 17:09:28 -07002405};
2406
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002407JDWP::JdwpError Dbg::GetThisObject(JDWP::ObjectId thread_id, JDWP::FrameId frame_id,
2408 JDWP::ObjectId* result) {
2409 ScopedObjectAccessUnchecked soa(Thread::Current());
Sebastien Hertz69206392015-04-07 15:54:25 +02002410 JDWP::JdwpError error;
2411 Thread* thread = DecodeThread(soa, thread_id, &error);
2412 if (error != JDWP::ERR_NONE) {
2413 return error;
2414 }
2415 if (!IsSuspendedForDebugger(soa, thread)) {
2416 return JDWP::ERR_THREAD_NOT_SUSPENDED;
Elliott Hughes6e9d22c2012-06-22 15:02:37 -07002417 }
Ian Rogers700a4022014-05-19 16:49:03 -07002418 std::unique_ptr<Context> context(Context::Create());
Ian Rogers7a22fa62013-01-23 12:16:16 -08002419 GetThisVisitor visitor(thread, context.get(), frame_id);
Ian Rogers0399dde2012-06-06 17:09:28 -07002420 visitor.WalkStack();
Elliott Hughes6e9d22c2012-06-22 15:02:37 -07002421 *result = gRegistry->Add(visitor.this_object);
2422 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002423}
2424
Sebastien Hertz8009f392014-09-01 17:07:11 +02002425// Walks the stack until we find the frame with the given FrameId.
2426class FindFrameVisitor FINAL : public StackVisitor {
2427 public:
2428 FindFrameVisitor(Thread* thread, Context* context, JDWP::FrameId frame_id)
2429 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_)
Nicolas Geoffray8e5bd182015-05-06 11:34:34 +01002430 : StackVisitor(thread, context, StackVisitor::StackWalkKind::kIncludeInlinedFrames),
2431 frame_id_(frame_id),
2432 error_(JDWP::ERR_INVALID_FRAMEID) {}
Ian Rogersca190662012-06-26 15:45:57 -07002433
Sebastien Hertz8009f392014-09-01 17:07:11 +02002434 // TODO: Enable annotalysis. We know lock is held in constructor, but abstraction confuses
2435 // annotalysis.
2436 bool VisitFrame() NO_THREAD_SAFETY_ANALYSIS {
2437 if (GetFrameId() != frame_id_) {
2438 return true; // Not our frame, carry on.
Ian Rogers0399dde2012-06-06 17:09:28 -07002439 }
Mathieu Chartiere401d142015-04-22 13:56:20 -07002440 ArtMethod* m = GetMethod();
Sebastien Hertz8009f392014-09-01 17:07:11 +02002441 if (m->IsNative()) {
2442 // We can't read/write local value from/into native method.
2443 error_ = JDWP::ERR_OPAQUE_FRAME;
2444 } else {
2445 // We found our frame.
2446 error_ = JDWP::ERR_NONE;
2447 }
2448 return false;
2449 }
2450
2451 JDWP::JdwpError GetError() const {
2452 return error_;
2453 }
2454
2455 private:
2456 const JDWP::FrameId frame_id_;
2457 JDWP::JdwpError error_;
2458};
2459
2460JDWP::JdwpError Dbg::GetLocalValues(JDWP::Request* request, JDWP::ExpandBuf* pReply) {
2461 JDWP::ObjectId thread_id = request->ReadThreadId();
2462 JDWP::FrameId frame_id = request->ReadFrameId();
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002463
2464 ScopedObjectAccessUnchecked soa(Thread::Current());
Sebastien Hertz69206392015-04-07 15:54:25 +02002465 JDWP::JdwpError error;
2466 Thread* thread = DecodeThread(soa, thread_id, &error);
2467 if (error != JDWP::ERR_NONE) {
2468 return error;
2469 }
2470 if (!IsSuspendedForDebugger(soa, thread)) {
2471 return JDWP::ERR_THREAD_NOT_SUSPENDED;
Elliott Hughes221229c2013-01-08 18:17:50 -08002472 }
Sebastien Hertz8009f392014-09-01 17:07:11 +02002473 // Find the frame with the given frame_id.
Ian Rogers700a4022014-05-19 16:49:03 -07002474 std::unique_ptr<Context> context(Context::Create());
Sebastien Hertz8009f392014-09-01 17:07:11 +02002475 FindFrameVisitor visitor(thread, context.get(), frame_id);
Ian Rogers0399dde2012-06-06 17:09:28 -07002476 visitor.WalkStack();
Sebastien Hertz8009f392014-09-01 17:07:11 +02002477 if (visitor.GetError() != JDWP::ERR_NONE) {
2478 return visitor.GetError();
2479 }
2480
2481 // Read the values from visitor's context.
2482 int32_t slot_count = request->ReadSigned32("slot count");
2483 expandBufAdd4BE(pReply, slot_count); /* "int values" */
2484 for (int32_t i = 0; i < slot_count; ++i) {
2485 uint32_t slot = request->ReadUnsigned32("slot");
2486 JDWP::JdwpTag reqSigByte = request->ReadTag();
2487
2488 VLOG(jdwp) << " --> slot " << slot << " " << reqSigByte;
2489
2490 size_t width = Dbg::GetTagWidth(reqSigByte);
Sebastien Hertz7d955652014-10-22 10:57:10 +02002491 uint8_t* ptr = expandBufAddSpace(pReply, width + 1);
Sebastien Hertz69206392015-04-07 15:54:25 +02002492 error = Dbg::GetLocalValue(visitor, soa, slot, reqSigByte, ptr, width);
Sebastien Hertz8009f392014-09-01 17:07:11 +02002493 if (error != JDWP::ERR_NONE) {
2494 return error;
2495 }
2496 }
2497 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002498}
2499
Sebastien Hertzabbabc82015-03-26 08:47:47 +01002500constexpr JDWP::JdwpError kStackFrameLocalAccessError = JDWP::ERR_ABSENT_INFORMATION;
2501
2502static std::string GetStackContextAsString(const StackVisitor& visitor)
2503 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
2504 return StringPrintf(" at DEX pc 0x%08x in method %s", visitor.GetDexPc(false),
2505 PrettyMethod(visitor.GetMethod()).c_str());
2506}
2507
2508static JDWP::JdwpError FailGetLocalValue(const StackVisitor& visitor, uint16_t vreg,
2509 JDWP::JdwpTag tag)
2510 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
2511 LOG(ERROR) << "Failed to read " << tag << " local from register v" << vreg
2512 << GetStackContextAsString(visitor);
2513 return kStackFrameLocalAccessError;
2514}
2515
Sebastien Hertz8009f392014-09-01 17:07:11 +02002516JDWP::JdwpError Dbg::GetLocalValue(const StackVisitor& visitor, ScopedObjectAccessUnchecked& soa,
2517 int slot, JDWP::JdwpTag tag, uint8_t* buf, size_t width) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07002518 ArtMethod* m = visitor.GetMethod();
Sebastien Hertzabbabc82015-03-26 08:47:47 +01002519 JDWP::JdwpError error = JDWP::ERR_NONE;
2520 uint16_t vreg = DemangleSlot(slot, m, &error);
2521 if (error != JDWP::ERR_NONE) {
2522 return error;
2523 }
Sebastien Hertz8009f392014-09-01 17:07:11 +02002524 // TODO: check that the tag is compatible with the actual type of the slot!
Sebastien Hertz8009f392014-09-01 17:07:11 +02002525 switch (tag) {
2526 case JDWP::JT_BOOLEAN: {
2527 CHECK_EQ(width, 1U);
2528 uint32_t intVal;
Sebastien Hertzabbabc82015-03-26 08:47:47 +01002529 if (!visitor.GetVReg(m, vreg, kIntVReg, &intVal)) {
2530 return FailGetLocalValue(visitor, vreg, tag);
Ian Rogers0399dde2012-06-06 17:09:28 -07002531 }
Sebastien Hertzabbabc82015-03-26 08:47:47 +01002532 VLOG(jdwp) << "get boolean local " << vreg << " = " << intVal;
2533 JDWP::Set1(buf + 1, intVal != 0);
Sebastien Hertz8009f392014-09-01 17:07:11 +02002534 break;
Ian Rogers0399dde2012-06-06 17:09:28 -07002535 }
Sebastien Hertz8009f392014-09-01 17:07:11 +02002536 case JDWP::JT_BYTE: {
2537 CHECK_EQ(width, 1U);
2538 uint32_t intVal;
Sebastien Hertzabbabc82015-03-26 08:47:47 +01002539 if (!visitor.GetVReg(m, vreg, kIntVReg, &intVal)) {
2540 return FailGetLocalValue(visitor, vreg, tag);
Sebastien Hertz8009f392014-09-01 17:07:11 +02002541 }
Sebastien Hertzabbabc82015-03-26 08:47:47 +01002542 VLOG(jdwp) << "get byte local " << vreg << " = " << intVal;
2543 JDWP::Set1(buf + 1, intVal);
Sebastien Hertz8009f392014-09-01 17:07:11 +02002544 break;
2545 }
2546 case JDWP::JT_SHORT:
2547 case JDWP::JT_CHAR: {
2548 CHECK_EQ(width, 2U);
2549 uint32_t intVal;
Sebastien Hertzabbabc82015-03-26 08:47:47 +01002550 if (!visitor.GetVReg(m, vreg, kIntVReg, &intVal)) {
2551 return FailGetLocalValue(visitor, vreg, tag);
Sebastien Hertz8009f392014-09-01 17:07:11 +02002552 }
Sebastien Hertzabbabc82015-03-26 08:47:47 +01002553 VLOG(jdwp) << "get short/char local " << vreg << " = " << intVal;
2554 JDWP::Set2BE(buf + 1, intVal);
Sebastien Hertz8009f392014-09-01 17:07:11 +02002555 break;
2556 }
2557 case JDWP::JT_INT: {
2558 CHECK_EQ(width, 4U);
2559 uint32_t intVal;
Sebastien Hertzabbabc82015-03-26 08:47:47 +01002560 if (!visitor.GetVReg(m, vreg, kIntVReg, &intVal)) {
2561 return FailGetLocalValue(visitor, vreg, tag);
Sebastien Hertz8009f392014-09-01 17:07:11 +02002562 }
Sebastien Hertzabbabc82015-03-26 08:47:47 +01002563 VLOG(jdwp) << "get int local " << vreg << " = " << intVal;
2564 JDWP::Set4BE(buf + 1, intVal);
Sebastien Hertz8009f392014-09-01 17:07:11 +02002565 break;
2566 }
2567 case JDWP::JT_FLOAT: {
2568 CHECK_EQ(width, 4U);
2569 uint32_t intVal;
Sebastien Hertzabbabc82015-03-26 08:47:47 +01002570 if (!visitor.GetVReg(m, vreg, kFloatVReg, &intVal)) {
2571 return FailGetLocalValue(visitor, vreg, tag);
Sebastien Hertz8009f392014-09-01 17:07:11 +02002572 }
Sebastien Hertzabbabc82015-03-26 08:47:47 +01002573 VLOG(jdwp) << "get float local " << vreg << " = " << intVal;
2574 JDWP::Set4BE(buf + 1, intVal);
Sebastien Hertz8009f392014-09-01 17:07:11 +02002575 break;
2576 }
2577 case JDWP::JT_ARRAY:
2578 case JDWP::JT_CLASS_LOADER:
2579 case JDWP::JT_CLASS_OBJECT:
2580 case JDWP::JT_OBJECT:
2581 case JDWP::JT_STRING:
2582 case JDWP::JT_THREAD:
2583 case JDWP::JT_THREAD_GROUP: {
2584 CHECK_EQ(width, sizeof(JDWP::ObjectId));
2585 uint32_t intVal;
Sebastien Hertzabbabc82015-03-26 08:47:47 +01002586 if (!visitor.GetVReg(m, vreg, kReferenceVReg, &intVal)) {
2587 return FailGetLocalValue(visitor, vreg, tag);
Sebastien Hertz8009f392014-09-01 17:07:11 +02002588 }
Sebastien Hertzabbabc82015-03-26 08:47:47 +01002589 mirror::Object* o = reinterpret_cast<mirror::Object*>(intVal);
2590 VLOG(jdwp) << "get " << tag << " object local " << vreg << " = " << o;
2591 if (!Runtime::Current()->GetHeap()->IsValidObjectAddress(o)) {
2592 LOG(FATAL) << StringPrintf("Found invalid object %#" PRIxPTR " in register v%u",
2593 reinterpret_cast<uintptr_t>(o), vreg)
2594 << GetStackContextAsString(visitor);
2595 UNREACHABLE();
2596 }
2597 tag = TagFromObject(soa, o);
2598 JDWP::SetObjectId(buf + 1, gRegistry->Add(o));
Sebastien Hertz8009f392014-09-01 17:07:11 +02002599 break;
2600 }
2601 case JDWP::JT_DOUBLE: {
2602 CHECK_EQ(width, 8U);
2603 uint64_t longVal;
Sebastien Hertzabbabc82015-03-26 08:47:47 +01002604 if (!visitor.GetVRegPair(m, vreg, kDoubleLoVReg, kDoubleHiVReg, &longVal)) {
2605 return FailGetLocalValue(visitor, vreg, tag);
Sebastien Hertz8009f392014-09-01 17:07:11 +02002606 }
Sebastien Hertzabbabc82015-03-26 08:47:47 +01002607 VLOG(jdwp) << "get double local " << vreg << " = " << longVal;
2608 JDWP::Set8BE(buf + 1, longVal);
Sebastien Hertz8009f392014-09-01 17:07:11 +02002609 break;
2610 }
2611 case JDWP::JT_LONG: {
2612 CHECK_EQ(width, 8U);
2613 uint64_t longVal;
Sebastien Hertzabbabc82015-03-26 08:47:47 +01002614 if (!visitor.GetVRegPair(m, vreg, kLongLoVReg, kLongHiVReg, &longVal)) {
2615 return FailGetLocalValue(visitor, vreg, tag);
Sebastien Hertz8009f392014-09-01 17:07:11 +02002616 }
Sebastien Hertzabbabc82015-03-26 08:47:47 +01002617 VLOG(jdwp) << "get long local " << vreg << " = " << longVal;
2618 JDWP::Set8BE(buf + 1, longVal);
Sebastien Hertz8009f392014-09-01 17:07:11 +02002619 break;
2620 }
2621 default:
2622 LOG(FATAL) << "Unknown tag " << tag;
Sebastien Hertzabbabc82015-03-26 08:47:47 +01002623 UNREACHABLE();
Sebastien Hertz8009f392014-09-01 17:07:11 +02002624 }
Ian Rogers0399dde2012-06-06 17:09:28 -07002625
Sebastien Hertz8009f392014-09-01 17:07:11 +02002626 // Prepend tag, which may have been updated.
2627 JDWP::Set1(buf, tag);
2628 return JDWP::ERR_NONE;
2629}
2630
2631JDWP::JdwpError Dbg::SetLocalValues(JDWP::Request* request) {
2632 JDWP::ObjectId thread_id = request->ReadThreadId();
2633 JDWP::FrameId frame_id = request->ReadFrameId();
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002634
2635 ScopedObjectAccessUnchecked soa(Thread::Current());
Sebastien Hertz69206392015-04-07 15:54:25 +02002636 JDWP::JdwpError error;
2637 Thread* thread = DecodeThread(soa, thread_id, &error);
2638 if (error != JDWP::ERR_NONE) {
2639 return error;
2640 }
2641 if (!IsSuspendedForDebugger(soa, thread)) {
2642 return JDWP::ERR_THREAD_NOT_SUSPENDED;
Elliott Hughes221229c2013-01-08 18:17:50 -08002643 }
Sebastien Hertz8009f392014-09-01 17:07:11 +02002644 // Find the frame with the given frame_id.
Ian Rogers700a4022014-05-19 16:49:03 -07002645 std::unique_ptr<Context> context(Context::Create());
Sebastien Hertz8009f392014-09-01 17:07:11 +02002646 FindFrameVisitor visitor(thread, context.get(), frame_id);
Ian Rogers0399dde2012-06-06 17:09:28 -07002647 visitor.WalkStack();
Sebastien Hertz8009f392014-09-01 17:07:11 +02002648 if (visitor.GetError() != JDWP::ERR_NONE) {
2649 return visitor.GetError();
2650 }
2651
2652 // Writes the values into visitor's context.
2653 int32_t slot_count = request->ReadSigned32("slot count");
2654 for (int32_t i = 0; i < slot_count; ++i) {
2655 uint32_t slot = request->ReadUnsigned32("slot");
2656 JDWP::JdwpTag sigByte = request->ReadTag();
2657 size_t width = Dbg::GetTagWidth(sigByte);
2658 uint64_t value = request->ReadValue(width);
2659
2660 VLOG(jdwp) << " --> slot " << slot << " " << sigByte << " " << value;
Sebastien Hertz69206392015-04-07 15:54:25 +02002661 error = Dbg::SetLocalValue(visitor, slot, sigByte, value, width);
Sebastien Hertz8009f392014-09-01 17:07:11 +02002662 if (error != JDWP::ERR_NONE) {
2663 return error;
2664 }
2665 }
2666 return JDWP::ERR_NONE;
2667}
2668
Sebastien Hertzabbabc82015-03-26 08:47:47 +01002669template<typename T>
2670static JDWP::JdwpError FailSetLocalValue(const StackVisitor& visitor, uint16_t vreg,
2671 JDWP::JdwpTag tag, T value)
2672 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
2673 LOG(ERROR) << "Failed to write " << tag << " local " << value
2674 << " (0x" << std::hex << value << ") into register v" << vreg
2675 << GetStackContextAsString(visitor);
2676 return kStackFrameLocalAccessError;
2677}
2678
Sebastien Hertz8009f392014-09-01 17:07:11 +02002679JDWP::JdwpError Dbg::SetLocalValue(StackVisitor& visitor, int slot, JDWP::JdwpTag tag,
2680 uint64_t value, size_t width) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07002681 ArtMethod* m = visitor.GetMethod();
Sebastien Hertzabbabc82015-03-26 08:47:47 +01002682 JDWP::JdwpError error = JDWP::ERR_NONE;
2683 uint16_t vreg = DemangleSlot(slot, m, &error);
2684 if (error != JDWP::ERR_NONE) {
2685 return error;
2686 }
Sebastien Hertz8009f392014-09-01 17:07:11 +02002687 // TODO: check that the tag is compatible with the actual type of the slot!
Sebastien Hertz8009f392014-09-01 17:07:11 +02002688 switch (tag) {
2689 case JDWP::JT_BOOLEAN:
2690 case JDWP::JT_BYTE:
2691 CHECK_EQ(width, 1U);
Sebastien Hertzabbabc82015-03-26 08:47:47 +01002692 if (!visitor.SetVReg(m, vreg, static_cast<uint32_t>(value), kIntVReg)) {
2693 return FailSetLocalValue(visitor, vreg, tag, static_cast<uint32_t>(value));
Sebastien Hertz8009f392014-09-01 17:07:11 +02002694 }
2695 break;
2696 case JDWP::JT_SHORT:
2697 case JDWP::JT_CHAR:
2698 CHECK_EQ(width, 2U);
Sebastien Hertzabbabc82015-03-26 08:47:47 +01002699 if (!visitor.SetVReg(m, vreg, static_cast<uint32_t>(value), kIntVReg)) {
2700 return FailSetLocalValue(visitor, vreg, tag, static_cast<uint32_t>(value));
Sebastien Hertz8009f392014-09-01 17:07:11 +02002701 }
2702 break;
2703 case JDWP::JT_INT:
2704 CHECK_EQ(width, 4U);
Sebastien Hertzabbabc82015-03-26 08:47:47 +01002705 if (!visitor.SetVReg(m, vreg, static_cast<uint32_t>(value), kIntVReg)) {
2706 return FailSetLocalValue(visitor, vreg, tag, static_cast<uint32_t>(value));
Sebastien Hertz8009f392014-09-01 17:07:11 +02002707 }
2708 break;
2709 case JDWP::JT_FLOAT:
2710 CHECK_EQ(width, 4U);
Sebastien Hertzabbabc82015-03-26 08:47:47 +01002711 if (!visitor.SetVReg(m, vreg, static_cast<uint32_t>(value), kFloatVReg)) {
2712 return FailSetLocalValue(visitor, vreg, tag, static_cast<uint32_t>(value));
Sebastien Hertz8009f392014-09-01 17:07:11 +02002713 }
2714 break;
2715 case JDWP::JT_ARRAY:
2716 case JDWP::JT_CLASS_LOADER:
2717 case JDWP::JT_CLASS_OBJECT:
2718 case JDWP::JT_OBJECT:
2719 case JDWP::JT_STRING:
2720 case JDWP::JT_THREAD:
2721 case JDWP::JT_THREAD_GROUP: {
2722 CHECK_EQ(width, sizeof(JDWP::ObjectId));
Sebastien Hertz8009f392014-09-01 17:07:11 +02002723 mirror::Object* o = gRegistry->Get<mirror::Object*>(static_cast<JDWP::ObjectId>(value),
2724 &error);
2725 if (error != JDWP::ERR_NONE) {
2726 VLOG(jdwp) << tag << " object " << o << " is an invalid object";
2727 return JDWP::ERR_INVALID_OBJECT;
Sebastien Hertzabbabc82015-03-26 08:47:47 +01002728 }
2729 if (!visitor.SetVReg(m, vreg, static_cast<uint32_t>(reinterpret_cast<uintptr_t>(o)),
2730 kReferenceVReg)) {
2731 return FailSetLocalValue(visitor, vreg, tag, reinterpret_cast<uintptr_t>(o));
Sebastien Hertz8009f392014-09-01 17:07:11 +02002732 }
2733 break;
2734 }
2735 case JDWP::JT_DOUBLE: {
2736 CHECK_EQ(width, 8U);
Sebastien Hertzabbabc82015-03-26 08:47:47 +01002737 if (!visitor.SetVRegPair(m, vreg, value, kDoubleLoVReg, kDoubleHiVReg)) {
2738 return FailSetLocalValue(visitor, vreg, tag, value);
Sebastien Hertz8009f392014-09-01 17:07:11 +02002739 }
2740 break;
2741 }
2742 case JDWP::JT_LONG: {
2743 CHECK_EQ(width, 8U);
Sebastien Hertzabbabc82015-03-26 08:47:47 +01002744 if (!visitor.SetVRegPair(m, vreg, value, kLongLoVReg, kLongHiVReg)) {
2745 return FailSetLocalValue(visitor, vreg, tag, value);
Sebastien Hertz8009f392014-09-01 17:07:11 +02002746 }
2747 break;
2748 }
2749 default:
2750 LOG(FATAL) << "Unknown tag " << tag;
Sebastien Hertzabbabc82015-03-26 08:47:47 +01002751 UNREACHABLE();
Sebastien Hertz8009f392014-09-01 17:07:11 +02002752 }
2753 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002754}
2755
Mathieu Chartiere401d142015-04-22 13:56:20 -07002756static void SetEventLocation(JDWP::EventLocation* location, ArtMethod* m, uint32_t dex_pc)
Sebastien Hertz6995c602014-09-09 12:10:13 +02002757 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
2758 DCHECK(location != nullptr);
2759 if (m == nullptr) {
2760 memset(location, 0, sizeof(*location));
2761 } else {
2762 location->method = m;
2763 location->dex_pc = (m->IsNative() || m->IsProxyMethod()) ? static_cast<uint32_t>(-1) : dex_pc;
Sebastien Hertz3f52eaf2014-04-04 17:50:18 +02002764 }
Sebastien Hertz3f52eaf2014-04-04 17:50:18 +02002765}
2766
Mathieu Chartiere401d142015-04-22 13:56:20 -07002767void Dbg::PostLocationEvent(ArtMethod* m, int dex_pc, mirror::Object* this_object,
Jeff Hao579b0242013-11-18 13:16:49 -08002768 int event_flags, const JValue* return_value) {
Sebastien Hertz3f52eaf2014-04-04 17:50:18 +02002769 if (!IsDebuggerActive()) {
2770 return;
2771 }
2772 DCHECK(m != nullptr);
2773 DCHECK_EQ(m->IsStatic(), this_object == nullptr);
Sebastien Hertz6995c602014-09-09 12:10:13 +02002774 JDWP::EventLocation location;
2775 SetEventLocation(&location, m, dex_pc);
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08002776
Sebastien Hertzde48aa62015-05-26 11:53:39 +02002777 // We need to be sure no exception is pending when calling JdwpState::PostLocationEvent.
2778 // This is required to be able to call JNI functions to create JDWP ids. To achieve this,
2779 // we temporarily clear the current thread's exception (if any) and will restore it after
2780 // the call.
2781 // Note: the only way to get a pending exception here is to suspend on a move-exception
2782 // instruction.
2783 Thread* const self = Thread::Current();
2784 StackHandleScope<1> hs(self);
2785 Handle<mirror::Throwable> pending_exception(hs.NewHandle(self->GetException()));
2786 self->ClearException();
2787 if (kIsDebugBuild && pending_exception.Get() != nullptr) {
2788 const DexFile::CodeItem* code_item = location.method->GetCodeItem();
2789 const Instruction* instr = Instruction::At(&code_item->insns_[location.dex_pc]);
2790 CHECK_EQ(Instruction::MOVE_EXCEPTION, instr->Opcode());
2791 }
2792
Sebastien Hertz6995c602014-09-09 12:10:13 +02002793 gJdwpState->PostLocationEvent(&location, this_object, event_flags, return_value);
Sebastien Hertzde48aa62015-05-26 11:53:39 +02002794
2795 if (pending_exception.Get() != nullptr) {
2796 self->SetException(pending_exception.Get());
2797 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002798}
2799
Mathieu Chartiere401d142015-04-22 13:56:20 -07002800void Dbg::PostFieldAccessEvent(ArtMethod* m, int dex_pc,
Mathieu Chartierc7853442015-03-27 14:35:38 -07002801 mirror::Object* this_object, ArtField* f) {
Sebastien Hertz3f52eaf2014-04-04 17:50:18 +02002802 if (!IsDebuggerActive()) {
2803 return;
2804 }
2805 DCHECK(m != nullptr);
2806 DCHECK(f != nullptr);
Sebastien Hertz6995c602014-09-09 12:10:13 +02002807 JDWP::EventLocation location;
2808 SetEventLocation(&location, m, dex_pc);
Sebastien Hertz3f52eaf2014-04-04 17:50:18 +02002809
Sebastien Hertz6995c602014-09-09 12:10:13 +02002810 gJdwpState->PostFieldEvent(&location, f, this_object, nullptr, false);
Sebastien Hertz3f52eaf2014-04-04 17:50:18 +02002811}
2812
Mathieu Chartiere401d142015-04-22 13:56:20 -07002813void Dbg::PostFieldModificationEvent(ArtMethod* m, int dex_pc,
Mathieu Chartierc7853442015-03-27 14:35:38 -07002814 mirror::Object* this_object, ArtField* f,
Sebastien Hertz3f52eaf2014-04-04 17:50:18 +02002815 const JValue* field_value) {
2816 if (!IsDebuggerActive()) {
2817 return;
2818 }
2819 DCHECK(m != nullptr);
2820 DCHECK(f != nullptr);
2821 DCHECK(field_value != nullptr);
Sebastien Hertz6995c602014-09-09 12:10:13 +02002822 JDWP::EventLocation location;
2823 SetEventLocation(&location, m, dex_pc);
Sebastien Hertz3f52eaf2014-04-04 17:50:18 +02002824
Sebastien Hertz6995c602014-09-09 12:10:13 +02002825 gJdwpState->PostFieldEvent(&location, f, this_object, field_value, true);
Sebastien Hertz3f52eaf2014-04-04 17:50:18 +02002826}
2827
Nicolas Geoffray14691c52015-03-05 10:40:17 +00002828/**
2829 * Finds the location where this exception will be caught. We search until we reach the top
2830 * frame, in which case this exception is considered uncaught.
2831 */
2832class CatchLocationFinder : public StackVisitor {
2833 public:
2834 CatchLocationFinder(Thread* self, const Handle<mirror::Throwable>& exception, Context* context)
2835 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_)
Nicolas Geoffray8e5bd182015-05-06 11:34:34 +01002836 : StackVisitor(self, context, StackVisitor::StackWalkKind::kIncludeInlinedFrames),
Nicolas Geoffray14691c52015-03-05 10:40:17 +00002837 self_(self),
2838 exception_(exception),
2839 handle_scope_(self),
2840 this_at_throw_(handle_scope_.NewHandle<mirror::Object>(nullptr)),
Mathieu Chartiere401d142015-04-22 13:56:20 -07002841 catch_method_(nullptr),
2842 throw_method_(nullptr),
Nicolas Geoffray14691c52015-03-05 10:40:17 +00002843 catch_dex_pc_(DexFile::kDexNoIndex),
2844 throw_dex_pc_(DexFile::kDexNoIndex) {
2845 }
2846
2847 bool VisitFrame() OVERRIDE SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07002848 ArtMethod* method = GetMethod();
Nicolas Geoffray14691c52015-03-05 10:40:17 +00002849 DCHECK(method != nullptr);
2850 if (method->IsRuntimeMethod()) {
2851 // Ignore callee save method.
2852 DCHECK(method->IsCalleeSaveMethod());
2853 return true;
2854 }
2855
2856 uint32_t dex_pc = GetDexPc();
Mathieu Chartiere401d142015-04-22 13:56:20 -07002857 if (throw_method_ == nullptr) {
Nicolas Geoffray14691c52015-03-05 10:40:17 +00002858 // First Java method found. It is either the method that threw the exception,
2859 // or the Java native method that is reporting an exception thrown by
2860 // native code.
2861 this_at_throw_.Assign(GetThisObject());
Mathieu Chartiere401d142015-04-22 13:56:20 -07002862 throw_method_ = method;
Nicolas Geoffray14691c52015-03-05 10:40:17 +00002863 throw_dex_pc_ = dex_pc;
2864 }
2865
2866 if (dex_pc != DexFile::kDexNoIndex) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07002867 StackHandleScope<1> hs(self_);
Nicolas Geoffray14691c52015-03-05 10:40:17 +00002868 uint32_t found_dex_pc;
2869 Handle<mirror::Class> exception_class(hs.NewHandle(exception_->GetClass()));
Nicolas Geoffray14691c52015-03-05 10:40:17 +00002870 bool unused_clear_exception;
Mathieu Chartiere401d142015-04-22 13:56:20 -07002871 found_dex_pc = method->FindCatchBlock(exception_class, dex_pc, &unused_clear_exception);
Nicolas Geoffray14691c52015-03-05 10:40:17 +00002872 if (found_dex_pc != DexFile::kDexNoIndex) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07002873 catch_method_ = method;
Nicolas Geoffray14691c52015-03-05 10:40:17 +00002874 catch_dex_pc_ = found_dex_pc;
2875 return false; // End stack walk.
2876 }
2877 }
2878 return true; // Continue stack walk.
2879 }
2880
Mathieu Chartiere401d142015-04-22 13:56:20 -07002881 ArtMethod* GetCatchMethod() SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
2882 return catch_method_;
Nicolas Geoffray14691c52015-03-05 10:40:17 +00002883 }
2884
Mathieu Chartiere401d142015-04-22 13:56:20 -07002885 ArtMethod* GetThrowMethod() SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
2886 return throw_method_;
Nicolas Geoffray14691c52015-03-05 10:40:17 +00002887 }
2888
2889 mirror::Object* GetThisAtThrow() SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
2890 return this_at_throw_.Get();
2891 }
2892
2893 uint32_t GetCatchDexPc() const {
2894 return catch_dex_pc_;
2895 }
2896
2897 uint32_t GetThrowDexPc() const {
2898 return throw_dex_pc_;
2899 }
2900
2901 private:
2902 Thread* const self_;
2903 const Handle<mirror::Throwable>& exception_;
Mathieu Chartiere401d142015-04-22 13:56:20 -07002904 StackHandleScope<1> handle_scope_;
Nicolas Geoffray14691c52015-03-05 10:40:17 +00002905 MutableHandle<mirror::Object> this_at_throw_;
Mathieu Chartiere401d142015-04-22 13:56:20 -07002906 ArtMethod* catch_method_;
2907 ArtMethod* throw_method_;
Nicolas Geoffray14691c52015-03-05 10:40:17 +00002908 uint32_t catch_dex_pc_;
2909 uint32_t throw_dex_pc_;
2910
2911 DISALLOW_COPY_AND_ASSIGN(CatchLocationFinder);
2912};
2913
2914void Dbg::PostException(mirror::Throwable* exception_object) {
Elliott Hughesc0f09332012-03-26 13:27:06 -07002915 if (!IsDebuggerActive()) {
Ian Rogers0ad5bb82011-12-07 10:16:32 -08002916 return;
2917 }
Sebastien Hertz261bc042015-04-08 09:36:07 +02002918 Thread* const self = Thread::Current();
2919 StackHandleScope<1> handle_scope(self);
Nicolas Geoffray14691c52015-03-05 10:40:17 +00002920 Handle<mirror::Throwable> h_exception(handle_scope.NewHandle(exception_object));
2921 std::unique_ptr<Context> context(Context::Create());
Sebastien Hertz261bc042015-04-08 09:36:07 +02002922 CatchLocationFinder clf(self, h_exception, context.get());
Nicolas Geoffray14691c52015-03-05 10:40:17 +00002923 clf.WalkStack(/* include_transitions */ false);
Sebastien Hertz6995c602014-09-09 12:10:13 +02002924 JDWP::EventLocation exception_throw_location;
Nicolas Geoffray14691c52015-03-05 10:40:17 +00002925 SetEventLocation(&exception_throw_location, clf.GetThrowMethod(), clf.GetThrowDexPc());
Sebastien Hertz6995c602014-09-09 12:10:13 +02002926 JDWP::EventLocation exception_catch_location;
Nicolas Geoffray14691c52015-03-05 10:40:17 +00002927 SetEventLocation(&exception_catch_location, clf.GetCatchMethod(), clf.GetCatchDexPc());
Elliott Hughes4740cdf2011-12-07 14:07:12 -08002928
Nicolas Geoffray14691c52015-03-05 10:40:17 +00002929 gJdwpState->PostException(&exception_throw_location, h_exception.Get(), &exception_catch_location,
2930 clf.GetThisAtThrow());
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002931}
2932
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002933void Dbg::PostClassPrepare(mirror::Class* c) {
Elliott Hughesc0f09332012-03-26 13:27:06 -07002934 if (!IsDebuggerActive()) {
Elliott Hughes4740cdf2011-12-07 14:07:12 -08002935 return;
2936 }
Sebastien Hertz6995c602014-09-09 12:10:13 +02002937 gJdwpState->PostClassPrepare(c);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002938}
2939
Ian Rogers62d6c772013-02-27 08:32:07 -08002940void Dbg::UpdateDebugger(Thread* thread, mirror::Object* this_object,
Mathieu Chartiere401d142015-04-22 13:56:20 -07002941 ArtMethod* m, uint32_t dex_pc,
Sebastien Hertz8379b222014-02-24 17:38:15 +01002942 int event_flags, const JValue* return_value) {
Ian Rogers62d6c772013-02-27 08:32:07 -08002943 if (!IsDebuggerActive() || dex_pc == static_cast<uint32_t>(-2) /* fake method exit */) {
Elliott Hughes2aa2e392012-02-17 17:15:43 -08002944 return;
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08002945 }
2946
Elliott Hughes86964332012-02-15 19:37:42 -08002947 if (IsBreakpoint(m, dex_pc)) {
2948 event_flags |= kBreakpoint;
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08002949 }
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08002950
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01002951 // If the debugger is single-stepping one of our threads, check to
2952 // see if we're that thread and we've reached a step point.
2953 const SingleStepControl* single_step_control = thread->GetSingleStepControl();
Sebastien Hertz597c4f02015-01-26 17:37:14 +01002954 if (single_step_control != nullptr) {
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01002955 CHECK(!m->IsNative());
Sebastien Hertz597c4f02015-01-26 17:37:14 +01002956 if (single_step_control->GetStepDepth() == JDWP::SD_INTO) {
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01002957 // Step into method calls. We break when the line number
2958 // or method pointer changes. If we're in SS_MIN mode, we
2959 // always stop.
Sebastien Hertz597c4f02015-01-26 17:37:14 +01002960 if (single_step_control->GetMethod() != m) {
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01002961 event_flags |= kSingleStep;
2962 VLOG(jdwp) << "SS new method";
Sebastien Hertz597c4f02015-01-26 17:37:14 +01002963 } else if (single_step_control->GetStepSize() == JDWP::SS_MIN) {
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01002964 event_flags |= kSingleStep;
2965 VLOG(jdwp) << "SS new instruction";
Sebastien Hertzbb43b432014-04-14 11:59:08 +02002966 } else if (single_step_control->ContainsDexPc(dex_pc)) {
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01002967 event_flags |= kSingleStep;
2968 VLOG(jdwp) << "SS new line";
2969 }
Sebastien Hertz597c4f02015-01-26 17:37:14 +01002970 } else if (single_step_control->GetStepDepth() == JDWP::SD_OVER) {
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01002971 // Step over method calls. We break when the line number is
2972 // different and the frame depth is <= the original frame
2973 // depth. (We can't just compare on the method, because we
2974 // might get unrolled past it by an exception, and it's tricky
2975 // to identify recursion.)
2976
2977 int stack_depth = GetStackDepth(thread);
2978
Sebastien Hertz597c4f02015-01-26 17:37:14 +01002979 if (stack_depth < single_step_control->GetStackDepth()) {
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01002980 // Popped up one or more frames, always trigger.
2981 event_flags |= kSingleStep;
2982 VLOG(jdwp) << "SS method pop";
Sebastien Hertz597c4f02015-01-26 17:37:14 +01002983 } else if (stack_depth == single_step_control->GetStackDepth()) {
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01002984 // Same depth, see if we moved.
Sebastien Hertz597c4f02015-01-26 17:37:14 +01002985 if (single_step_control->GetStepSize() == JDWP::SS_MIN) {
Elliott Hughes86964332012-02-15 19:37:42 -08002986 event_flags |= kSingleStep;
2987 VLOG(jdwp) << "SS new instruction";
Sebastien Hertzbb43b432014-04-14 11:59:08 +02002988 } else if (single_step_control->ContainsDexPc(dex_pc)) {
Elliott Hughes2435a572012-02-17 16:07:41 -08002989 event_flags |= kSingleStep;
2990 VLOG(jdwp) << "SS new line";
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08002991 }
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01002992 }
2993 } else {
Sebastien Hertz597c4f02015-01-26 17:37:14 +01002994 CHECK_EQ(single_step_control->GetStepDepth(), JDWP::SD_OUT);
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01002995 // Return from the current method. We break when the frame
2996 // depth pops up.
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08002997
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01002998 // This differs from the "method exit" break in that it stops
2999 // with the PC at the next instruction in the returned-to
3000 // function, rather than the end of the returning function.
Elliott Hughes86964332012-02-15 19:37:42 -08003001
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01003002 int stack_depth = GetStackDepth(thread);
Sebastien Hertz597c4f02015-01-26 17:37:14 +01003003 if (stack_depth < single_step_control->GetStackDepth()) {
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01003004 event_flags |= kSingleStep;
3005 VLOG(jdwp) << "SS method pop";
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08003006 }
3007 }
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08003008 }
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08003009
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08003010 // If there's something interesting going on, see if it matches one
3011 // of the debugger filters.
3012 if (event_flags != 0) {
Sebastien Hertz8379b222014-02-24 17:38:15 +01003013 Dbg::PostLocationEvent(m, dex_pc, this_object, event_flags, return_value);
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08003014 }
3015}
3016
Sebastien Hertz42cd43f2014-05-13 14:15:41 +02003017size_t* Dbg::GetReferenceCounterForEvent(uint32_t instrumentation_event) {
3018 switch (instrumentation_event) {
3019 case instrumentation::Instrumentation::kMethodEntered:
3020 return &method_enter_event_ref_count_;
3021 case instrumentation::Instrumentation::kMethodExited:
3022 return &method_exit_event_ref_count_;
3023 case instrumentation::Instrumentation::kDexPcMoved:
3024 return &dex_pc_change_event_ref_count_;
3025 case instrumentation::Instrumentation::kFieldRead:
3026 return &field_read_event_ref_count_;
3027 case instrumentation::Instrumentation::kFieldWritten:
3028 return &field_write_event_ref_count_;
3029 case instrumentation::Instrumentation::kExceptionCaught:
3030 return &exception_catch_event_ref_count_;
3031 default:
3032 return nullptr;
3033 }
3034}
3035
Sebastien Hertz4d25df32014-03-21 17:44:46 +01003036// Process request while all mutator threads are suspended.
3037void Dbg::ProcessDeoptimizationRequest(const DeoptimizationRequest& request) {
Sebastien Hertz138dbfc2013-12-04 18:15:25 +01003038 instrumentation::Instrumentation* instrumentation = Runtime::Current()->GetInstrumentation();
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003039 switch (request.GetKind()) {
Sebastien Hertz4d25df32014-03-21 17:44:46 +01003040 case DeoptimizationRequest::kNothing:
3041 LOG(WARNING) << "Ignoring empty deoptimization request.";
3042 break;
Sebastien Hertz42cd43f2014-05-13 14:15:41 +02003043 case DeoptimizationRequest::kRegisterForEvent:
3044 VLOG(jdwp) << StringPrintf("Add debugger as listener for instrumentation event 0x%x",
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003045 request.InstrumentationEvent());
3046 instrumentation->AddListener(&gDebugInstrumentationListener, request.InstrumentationEvent());
3047 instrumentation_events_ |= request.InstrumentationEvent();
Sebastien Hertz42cd43f2014-05-13 14:15:41 +02003048 break;
3049 case DeoptimizationRequest::kUnregisterForEvent:
3050 VLOG(jdwp) << StringPrintf("Remove debugger as listener for instrumentation event 0x%x",
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003051 request.InstrumentationEvent());
Sebastien Hertz42cd43f2014-05-13 14:15:41 +02003052 instrumentation->RemoveListener(&gDebugInstrumentationListener,
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003053 request.InstrumentationEvent());
3054 instrumentation_events_ &= ~request.InstrumentationEvent();
Sebastien Hertz42cd43f2014-05-13 14:15:41 +02003055 break;
Sebastien Hertz4d25df32014-03-21 17:44:46 +01003056 case DeoptimizationRequest::kFullDeoptimization:
Sebastien Hertz7ec2f1c2014-03-27 20:06:47 +01003057 VLOG(jdwp) << "Deoptimize the world ...";
Sebastien Hertz0462c4c2015-04-01 16:34:17 +02003058 instrumentation->DeoptimizeEverything(kDbgInstrumentationKey);
Sebastien Hertz7ec2f1c2014-03-27 20:06:47 +01003059 VLOG(jdwp) << "Deoptimize the world DONE";
Sebastien Hertz4d25df32014-03-21 17:44:46 +01003060 break;
3061 case DeoptimizationRequest::kFullUndeoptimization:
Sebastien Hertz7ec2f1c2014-03-27 20:06:47 +01003062 VLOG(jdwp) << "Undeoptimize the world ...";
Sebastien Hertz0462c4c2015-04-01 16:34:17 +02003063 instrumentation->UndeoptimizeEverything(kDbgInstrumentationKey);
Sebastien Hertz7ec2f1c2014-03-27 20:06:47 +01003064 VLOG(jdwp) << "Undeoptimize the world DONE";
Sebastien Hertz4d25df32014-03-21 17:44:46 +01003065 break;
3066 case DeoptimizationRequest::kSelectiveDeoptimization:
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003067 VLOG(jdwp) << "Deoptimize method " << PrettyMethod(request.Method()) << " ...";
3068 instrumentation->Deoptimize(request.Method());
3069 VLOG(jdwp) << "Deoptimize method " << PrettyMethod(request.Method()) << " DONE";
Sebastien Hertz4d25df32014-03-21 17:44:46 +01003070 break;
3071 case DeoptimizationRequest::kSelectiveUndeoptimization:
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003072 VLOG(jdwp) << "Undeoptimize method " << PrettyMethod(request.Method()) << " ...";
3073 instrumentation->Undeoptimize(request.Method());
3074 VLOG(jdwp) << "Undeoptimize method " << PrettyMethod(request.Method()) << " DONE";
Sebastien Hertz4d25df32014-03-21 17:44:46 +01003075 break;
3076 default:
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003077 LOG(FATAL) << "Unsupported deoptimization request kind " << request.GetKind();
Sebastien Hertz4d25df32014-03-21 17:44:46 +01003078 break;
Sebastien Hertz138dbfc2013-12-04 18:15:25 +01003079 }
Sebastien Hertz138dbfc2013-12-04 18:15:25 +01003080}
3081
Sebastien Hertz4d25df32014-03-21 17:44:46 +01003082void Dbg::RequestDeoptimization(const DeoptimizationRequest& req) {
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003083 if (req.GetKind() == DeoptimizationRequest::kNothing) {
Sebastien Hertz4d25df32014-03-21 17:44:46 +01003084 // Nothing to do.
3085 return;
3086 }
Brian Carlstrom306db812014-09-05 13:01:41 -07003087 MutexLock mu(Thread::Current(), *Locks::deoptimization_lock_);
Sebastien Hertz7ec2f1c2014-03-27 20:06:47 +01003088 RequestDeoptimizationLocked(req);
3089}
3090
3091void Dbg::RequestDeoptimizationLocked(const DeoptimizationRequest& req) {
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003092 switch (req.GetKind()) {
Sebastien Hertz42cd43f2014-05-13 14:15:41 +02003093 case DeoptimizationRequest::kRegisterForEvent: {
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003094 DCHECK_NE(req.InstrumentationEvent(), 0u);
3095 size_t* counter = GetReferenceCounterForEvent(req.InstrumentationEvent());
Sebastien Hertz42cd43f2014-05-13 14:15:41 +02003096 CHECK(counter != nullptr) << StringPrintf("No counter for instrumentation event 0x%x",
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003097 req.InstrumentationEvent());
Sebastien Hertz42cd43f2014-05-13 14:15:41 +02003098 if (*counter == 0) {
Sebastien Hertz7d2ae432014-05-15 11:26:34 +02003099 VLOG(jdwp) << StringPrintf("Queue request #%zd to start listening to instrumentation event 0x%x",
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003100 deoptimization_requests_.size(), req.InstrumentationEvent());
Sebastien Hertz42cd43f2014-05-13 14:15:41 +02003101 deoptimization_requests_.push_back(req);
3102 }
3103 *counter = *counter + 1;
3104 break;
3105 }
3106 case DeoptimizationRequest::kUnregisterForEvent: {
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003107 DCHECK_NE(req.InstrumentationEvent(), 0u);
3108 size_t* counter = GetReferenceCounterForEvent(req.InstrumentationEvent());
Sebastien Hertz42cd43f2014-05-13 14:15:41 +02003109 CHECK(counter != nullptr) << StringPrintf("No counter for instrumentation event 0x%x",
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003110 req.InstrumentationEvent());
Sebastien Hertz42cd43f2014-05-13 14:15:41 +02003111 *counter = *counter - 1;
3112 if (*counter == 0) {
Sebastien Hertz7d2ae432014-05-15 11:26:34 +02003113 VLOG(jdwp) << StringPrintf("Queue request #%zd to stop listening to instrumentation event 0x%x",
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003114 deoptimization_requests_.size(), req.InstrumentationEvent());
Sebastien Hertz42cd43f2014-05-13 14:15:41 +02003115 deoptimization_requests_.push_back(req);
3116 }
3117 break;
3118 }
Sebastien Hertz4d25df32014-03-21 17:44:46 +01003119 case DeoptimizationRequest::kFullDeoptimization: {
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003120 DCHECK(req.Method() == nullptr);
Sebastien Hertz4d25df32014-03-21 17:44:46 +01003121 if (full_deoptimization_event_count_ == 0) {
Sebastien Hertz7ec2f1c2014-03-27 20:06:47 +01003122 VLOG(jdwp) << "Queue request #" << deoptimization_requests_.size()
3123 << " for full deoptimization";
Sebastien Hertz4d25df32014-03-21 17:44:46 +01003124 deoptimization_requests_.push_back(req);
3125 }
3126 ++full_deoptimization_event_count_;
3127 break;
3128 }
3129 case DeoptimizationRequest::kFullUndeoptimization: {
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003130 DCHECK(req.Method() == nullptr);
Sebastien Hertze713d932014-05-15 10:48:53 +02003131 DCHECK_GT(full_deoptimization_event_count_, 0U);
Sebastien Hertz4d25df32014-03-21 17:44:46 +01003132 --full_deoptimization_event_count_;
3133 if (full_deoptimization_event_count_ == 0) {
Sebastien Hertz7ec2f1c2014-03-27 20:06:47 +01003134 VLOG(jdwp) << "Queue request #" << deoptimization_requests_.size()
3135 << " for full undeoptimization";
Sebastien Hertz4d25df32014-03-21 17:44:46 +01003136 deoptimization_requests_.push_back(req);
3137 }
3138 break;
3139 }
3140 case DeoptimizationRequest::kSelectiveDeoptimization: {
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003141 DCHECK(req.Method() != nullptr);
Sebastien Hertz7ec2f1c2014-03-27 20:06:47 +01003142 VLOG(jdwp) << "Queue request #" << deoptimization_requests_.size()
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003143 << " for deoptimization of " << PrettyMethod(req.Method());
Sebastien Hertz4d25df32014-03-21 17:44:46 +01003144 deoptimization_requests_.push_back(req);
3145 break;
3146 }
3147 case DeoptimizationRequest::kSelectiveUndeoptimization: {
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003148 DCHECK(req.Method() != nullptr);
Sebastien Hertz7ec2f1c2014-03-27 20:06:47 +01003149 VLOG(jdwp) << "Queue request #" << deoptimization_requests_.size()
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003150 << " for undeoptimization of " << PrettyMethod(req.Method());
Sebastien Hertz4d25df32014-03-21 17:44:46 +01003151 deoptimization_requests_.push_back(req);
3152 break;
3153 }
3154 default: {
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003155 LOG(FATAL) << "Unknown deoptimization request kind " << req.GetKind();
Sebastien Hertz4d25df32014-03-21 17:44:46 +01003156 break;
3157 }
3158 }
3159}
3160
Sebastien Hertz138dbfc2013-12-04 18:15:25 +01003161void Dbg::ManageDeoptimization() {
3162 Thread* const self = Thread::Current();
3163 {
3164 // Avoid suspend/resume if there is no pending request.
Brian Carlstrom306db812014-09-05 13:01:41 -07003165 MutexLock mu(self, *Locks::deoptimization_lock_);
Sebastien Hertz4d25df32014-03-21 17:44:46 +01003166 if (deoptimization_requests_.empty()) {
Sebastien Hertz138dbfc2013-12-04 18:15:25 +01003167 return;
3168 }
3169 }
3170 CHECK_EQ(self->GetState(), kRunnable);
3171 self->TransitionFromRunnableToSuspended(kWaitingForDeoptimization);
3172 // We need to suspend mutator threads first.
3173 Runtime* const runtime = Runtime::Current();
Mathieu Chartierbf9fc582015-03-13 17:21:25 -07003174 runtime->GetThreadList()->SuspendAll(__FUNCTION__);
Sebastien Hertz138dbfc2013-12-04 18:15:25 +01003175 const ThreadState old_state = self->SetStateUnsafe(kRunnable);
Sebastien Hertz4d25df32014-03-21 17:44:46 +01003176 {
Brian Carlstrom306db812014-09-05 13:01:41 -07003177 MutexLock mu(self, *Locks::deoptimization_lock_);
Sebastien Hertz7ec2f1c2014-03-27 20:06:47 +01003178 size_t req_index = 0;
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003179 for (DeoptimizationRequest& request : deoptimization_requests_) {
Sebastien Hertz7ec2f1c2014-03-27 20:06:47 +01003180 VLOG(jdwp) << "Process deoptimization request #" << req_index++;
Sebastien Hertz4d25df32014-03-21 17:44:46 +01003181 ProcessDeoptimizationRequest(request);
3182 }
3183 deoptimization_requests_.clear();
3184 }
Sebastien Hertz138dbfc2013-12-04 18:15:25 +01003185 CHECK_EQ(self->SetStateUnsafe(old_state), kRunnable);
3186 runtime->GetThreadList()->ResumeAll();
3187 self->TransitionFromSuspendedToRunnable();
3188}
3189
Mathieu Chartiere401d142015-04-22 13:56:20 -07003190static bool IsMethodPossiblyInlined(Thread* self, ArtMethod* m)
Sebastien Hertza76a6d42014-03-20 16:40:17 +01003191 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07003192 const DexFile::CodeItem* code_item = m->GetCodeItem();
Sebastien Hertza76a6d42014-03-20 16:40:17 +01003193 if (code_item == nullptr) {
3194 // TODO We should not be asked to watch location in a native or abstract method so the code item
3195 // should never be null. We could just check we never encounter this case.
3196 return false;
Sebastien Hertz138dbfc2013-12-04 18:15:25 +01003197 }
Sebastien Hertz4d1e9ab2014-09-18 16:03:34 +02003198 // Note: method verifier may cause thread suspension.
3199 self->AssertThreadSuspensionIsAllowable();
Mathieu Chartiere401d142015-04-22 13:56:20 -07003200 StackHandleScope<2> hs(self);
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07003201 mirror::Class* declaring_class = m->GetDeclaringClass();
3202 Handle<mirror::DexCache> dex_cache(hs.NewHandle(declaring_class->GetDexCache()));
3203 Handle<mirror::ClassLoader> class_loader(hs.NewHandle(declaring_class->GetClassLoader()));
Ian Rogers7b078e82014-09-10 14:44:24 -07003204 verifier::MethodVerifier verifier(self, dex_cache->GetDexFile(), dex_cache, class_loader,
Mathieu Chartiere401d142015-04-22 13:56:20 -07003205 &m->GetClassDef(), code_item, m->GetDexMethodIndex(), m,
Mathieu Chartier4306ef82014-12-19 18:41:47 -08003206 m->GetAccessFlags(), false, true, false, true);
Sebastien Hertza76a6d42014-03-20 16:40:17 +01003207 // Note: we don't need to verify the method.
3208 return InlineMethodAnalyser::AnalyseMethodCode(&verifier, nullptr);
3209}
Sebastien Hertz138dbfc2013-12-04 18:15:25 +01003210
Mathieu Chartiere401d142015-04-22 13:56:20 -07003211static const Breakpoint* FindFirstBreakpointForMethod(ArtMethod* m)
Sebastien Hertzed2be172014-08-19 15:33:43 +02003212 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_, Locks::breakpoint_lock_) {
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003213 for (Breakpoint& breakpoint : gBreakpoints) {
3214 if (breakpoint.Method() == m) {
Sebastien Hertza76a6d42014-03-20 16:40:17 +01003215 return &breakpoint;
3216 }
3217 }
3218 return nullptr;
3219}
3220
Mathieu Chartiere401d142015-04-22 13:56:20 -07003221bool Dbg::MethodHasAnyBreakpoints(ArtMethod* method) {
Mathieu Chartierd8565452015-03-26 09:41:50 -07003222 ReaderMutexLock mu(Thread::Current(), *Locks::breakpoint_lock_);
3223 return FindFirstBreakpointForMethod(method) != nullptr;
3224}
3225
Sebastien Hertza76a6d42014-03-20 16:40:17 +01003226// Sanity checks all existing breakpoints on the same method.
Mathieu Chartiere401d142015-04-22 13:56:20 -07003227static void SanityCheckExistingBreakpoints(ArtMethod* m,
Sebastien Hertzf3928792014-11-17 19:00:37 +01003228 DeoptimizationRequest::Kind deoptimization_kind)
Sebastien Hertzed2be172014-08-19 15:33:43 +02003229 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_, Locks::breakpoint_lock_) {
Sebastien Hertz4d1e9ab2014-09-18 16:03:34 +02003230 for (const Breakpoint& breakpoint : gBreakpoints) {
Sebastien Hertzf3928792014-11-17 19:00:37 +01003231 if (breakpoint.Method() == m) {
3232 CHECK_EQ(deoptimization_kind, breakpoint.GetDeoptimizationKind());
3233 }
Sebastien Hertz4d1e9ab2014-09-18 16:03:34 +02003234 }
Sebastien Hertzf3928792014-11-17 19:00:37 +01003235 instrumentation::Instrumentation* instrumentation = Runtime::Current()->GetInstrumentation();
3236 if (deoptimization_kind == DeoptimizationRequest::kFullDeoptimization) {
Sebastien Hertz4d1e9ab2014-09-18 16:03:34 +02003237 // We should have deoptimized everything but not "selectively" deoptimized this method.
Sebastien Hertzf3928792014-11-17 19:00:37 +01003238 CHECK(instrumentation->AreAllMethodsDeoptimized());
3239 CHECK(!instrumentation->IsDeoptimized(m));
3240 } else if (deoptimization_kind == DeoptimizationRequest::kSelectiveDeoptimization) {
Sebastien Hertz4d1e9ab2014-09-18 16:03:34 +02003241 // We should have "selectively" deoptimized this method.
3242 // Note: while we have not deoptimized everything for this method, we may have done it for
3243 // another event.
Sebastien Hertzf3928792014-11-17 19:00:37 +01003244 CHECK(instrumentation->IsDeoptimized(m));
3245 } else {
3246 // This method does not require deoptimization.
3247 CHECK_EQ(deoptimization_kind, DeoptimizationRequest::kNothing);
3248 CHECK(!instrumentation->IsDeoptimized(m));
3249 }
3250}
3251
Sebastien Hertzabe93e02014-12-17 16:35:50 +01003252// Returns the deoptimization kind required to set a breakpoint in a method.
3253// If a breakpoint has already been set, we also return the first breakpoint
3254// through the given 'existing_brkpt' pointer.
Sebastien Hertzf3928792014-11-17 19:00:37 +01003255static DeoptimizationRequest::Kind GetRequiredDeoptimizationKind(Thread* self,
Mathieu Chartiere401d142015-04-22 13:56:20 -07003256 ArtMethod* m,
Sebastien Hertzabe93e02014-12-17 16:35:50 +01003257 const Breakpoint** existing_brkpt)
Sebastien Hertzf3928792014-11-17 19:00:37 +01003258 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
3259 if (!Dbg::RequiresDeoptimization()) {
3260 // We already run in interpreter-only mode so we don't need to deoptimize anything.
3261 VLOG(jdwp) << "No need for deoptimization when fully running with interpreter for method "
3262 << PrettyMethod(m);
3263 return DeoptimizationRequest::kNothing;
3264 }
Sebastien Hertzabe93e02014-12-17 16:35:50 +01003265 const Breakpoint* first_breakpoint;
Sebastien Hertzf3928792014-11-17 19:00:37 +01003266 {
3267 ReaderMutexLock mu(self, *Locks::breakpoint_lock_);
Sebastien Hertzabe93e02014-12-17 16:35:50 +01003268 first_breakpoint = FindFirstBreakpointForMethod(m);
3269 *existing_brkpt = first_breakpoint;
Sebastien Hertzf3928792014-11-17 19:00:37 +01003270 }
Sebastien Hertzabe93e02014-12-17 16:35:50 +01003271
3272 if (first_breakpoint == nullptr) {
Sebastien Hertzf3928792014-11-17 19:00:37 +01003273 // There is no breakpoint on this method yet: we need to deoptimize. If this method may be
3274 // inlined, we deoptimize everything; otherwise we deoptimize only this method.
3275 // Note: IsMethodPossiblyInlined goes into the method verifier and may cause thread suspension.
3276 // Therefore we must not hold any lock when we call it.
3277 bool need_full_deoptimization = IsMethodPossiblyInlined(self, m);
3278 if (need_full_deoptimization) {
3279 VLOG(jdwp) << "Need full deoptimization because of possible inlining of method "
3280 << PrettyMethod(m);
3281 return DeoptimizationRequest::kFullDeoptimization;
3282 } else {
3283 // We don't need to deoptimize if the method has not been compiled.
3284 ClassLinker* const class_linker = Runtime::Current()->GetClassLinker();
3285 const bool is_compiled = class_linker->GetOatMethodQuickCodeFor(m) != nullptr;
3286 if (is_compiled) {
Sebastien Hertz6963e442014-11-26 22:11:27 +01003287 // If the method may be called through its direct code pointer (without loading
3288 // its updated entrypoint), we need full deoptimization to not miss the breakpoint.
3289 if (class_linker->MayBeCalledWithDirectCodePointer(m)) {
3290 VLOG(jdwp) << "Need full deoptimization because of possible direct code call "
3291 << "into image for compiled method " << PrettyMethod(m);
3292 return DeoptimizationRequest::kFullDeoptimization;
3293 } else {
3294 VLOG(jdwp) << "Need selective deoptimization for compiled method " << PrettyMethod(m);
3295 return DeoptimizationRequest::kSelectiveDeoptimization;
3296 }
Sebastien Hertzf3928792014-11-17 19:00:37 +01003297 } else {
3298 // Method is not compiled: we don't need to deoptimize.
3299 VLOG(jdwp) << "No need for deoptimization for non-compiled method " << PrettyMethod(m);
3300 return DeoptimizationRequest::kNothing;
3301 }
3302 }
3303 } else {
3304 // There is at least one breakpoint for this method: we don't need to deoptimize.
3305 // Let's check that all breakpoints are configured the same way for deoptimization.
3306 VLOG(jdwp) << "Breakpoint already set: no deoptimization is required";
Sebastien Hertzabe93e02014-12-17 16:35:50 +01003307 DeoptimizationRequest::Kind deoptimization_kind = first_breakpoint->GetDeoptimizationKind();
Sebastien Hertzf3928792014-11-17 19:00:37 +01003308 if (kIsDebugBuild) {
3309 ReaderMutexLock mu(self, *Locks::breakpoint_lock_);
3310 SanityCheckExistingBreakpoints(m, deoptimization_kind);
3311 }
3312 return DeoptimizationRequest::kNothing;
Sebastien Hertz138dbfc2013-12-04 18:15:25 +01003313 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -07003314}
3315
Sebastien Hertza76a6d42014-03-20 16:40:17 +01003316// Installs a breakpoint at the specified location. Also indicates through the deoptimization
3317// request if we need to deoptimize.
3318void Dbg::WatchLocation(const JDWP::JdwpLocation* location, DeoptimizationRequest* req) {
3319 Thread* const self = Thread::Current();
Mathieu Chartiere401d142015-04-22 13:56:20 -07003320 ArtMethod* m = FromMethodId(location->method_id);
Sebastien Hertza76a6d42014-03-20 16:40:17 +01003321 DCHECK(m != nullptr) << "No method for method id " << location->method_id;
Sebastien Hertz138dbfc2013-12-04 18:15:25 +01003322
Sebastien Hertzabe93e02014-12-17 16:35:50 +01003323 const Breakpoint* existing_breakpoint = nullptr;
3324 const DeoptimizationRequest::Kind deoptimization_kind =
3325 GetRequiredDeoptimizationKind(self, m, &existing_breakpoint);
Sebastien Hertzf3928792014-11-17 19:00:37 +01003326 req->SetKind(deoptimization_kind);
3327 if (deoptimization_kind == DeoptimizationRequest::kSelectiveDeoptimization) {
3328 req->SetMethod(m);
Sebastien Hertza76a6d42014-03-20 16:40:17 +01003329 } else {
Sebastien Hertzf3928792014-11-17 19:00:37 +01003330 CHECK(deoptimization_kind == DeoptimizationRequest::kNothing ||
3331 deoptimization_kind == DeoptimizationRequest::kFullDeoptimization);
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003332 req->SetMethod(nullptr);
Sebastien Hertz138dbfc2013-12-04 18:15:25 +01003333 }
3334
Sebastien Hertz4d1e9ab2014-09-18 16:03:34 +02003335 {
3336 WriterMutexLock mu(self, *Locks::breakpoint_lock_);
Sebastien Hertzabe93e02014-12-17 16:35:50 +01003337 // If there is at least one existing breakpoint on the same method, the new breakpoint
3338 // must have the same deoptimization kind than the existing breakpoint(s).
3339 DeoptimizationRequest::Kind breakpoint_deoptimization_kind;
3340 if (existing_breakpoint != nullptr) {
3341 breakpoint_deoptimization_kind = existing_breakpoint->GetDeoptimizationKind();
3342 } else {
3343 breakpoint_deoptimization_kind = deoptimization_kind;
3344 }
3345 gBreakpoints.push_back(Breakpoint(m, location->dex_pc, breakpoint_deoptimization_kind));
Sebastien Hertz4d1e9ab2014-09-18 16:03:34 +02003346 VLOG(jdwp) << "Set breakpoint #" << (gBreakpoints.size() - 1) << ": "
3347 << gBreakpoints[gBreakpoints.size() - 1];
3348 }
Sebastien Hertza76a6d42014-03-20 16:40:17 +01003349}
3350
3351// Uninstalls a breakpoint at the specified location. Also indicates through the deoptimization
3352// request if we need to undeoptimize.
3353void Dbg::UnwatchLocation(const JDWP::JdwpLocation* location, DeoptimizationRequest* req) {
Sebastien Hertzed2be172014-08-19 15:33:43 +02003354 WriterMutexLock mu(Thread::Current(), *Locks::breakpoint_lock_);
Mathieu Chartiere401d142015-04-22 13:56:20 -07003355 ArtMethod* m = FromMethodId(location->method_id);
Sebastien Hertza76a6d42014-03-20 16:40:17 +01003356 DCHECK(m != nullptr) << "No method for method id " << location->method_id;
Sebastien Hertzf3928792014-11-17 19:00:37 +01003357 DeoptimizationRequest::Kind deoptimization_kind = DeoptimizationRequest::kNothing;
Sebastien Hertza76a6d42014-03-20 16:40:17 +01003358 for (size_t i = 0, e = gBreakpoints.size(); i < e; ++i) {
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003359 if (gBreakpoints[i].DexPc() == location->dex_pc && gBreakpoints[i].Method() == m) {
Sebastien Hertza76a6d42014-03-20 16:40:17 +01003360 VLOG(jdwp) << "Removed breakpoint #" << i << ": " << gBreakpoints[i];
Sebastien Hertzf3928792014-11-17 19:00:37 +01003361 deoptimization_kind = gBreakpoints[i].GetDeoptimizationKind();
3362 DCHECK_EQ(deoptimization_kind == DeoptimizationRequest::kSelectiveDeoptimization,
3363 Runtime::Current()->GetInstrumentation()->IsDeoptimized(m));
Sebastien Hertza76a6d42014-03-20 16:40:17 +01003364 gBreakpoints.erase(gBreakpoints.begin() + i);
3365 break;
3366 }
3367 }
3368 const Breakpoint* const existing_breakpoint = FindFirstBreakpointForMethod(m);
3369 if (existing_breakpoint == nullptr) {
3370 // There is no more breakpoint on this method: we need to undeoptimize.
Sebastien Hertzf3928792014-11-17 19:00:37 +01003371 if (deoptimization_kind == DeoptimizationRequest::kFullDeoptimization) {
Sebastien Hertza76a6d42014-03-20 16:40:17 +01003372 // This method required full deoptimization: we need to undeoptimize everything.
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003373 req->SetKind(DeoptimizationRequest::kFullUndeoptimization);
3374 req->SetMethod(nullptr);
Sebastien Hertzf3928792014-11-17 19:00:37 +01003375 } else if (deoptimization_kind == DeoptimizationRequest::kSelectiveDeoptimization) {
Sebastien Hertza76a6d42014-03-20 16:40:17 +01003376 // This method required selective deoptimization: we need to undeoptimize only that method.
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003377 req->SetKind(DeoptimizationRequest::kSelectiveUndeoptimization);
3378 req->SetMethod(m);
Sebastien Hertzf3928792014-11-17 19:00:37 +01003379 } else {
3380 // This method had no need for deoptimization: do nothing.
3381 CHECK_EQ(deoptimization_kind, DeoptimizationRequest::kNothing);
3382 req->SetKind(DeoptimizationRequest::kNothing);
3383 req->SetMethod(nullptr);
Sebastien Hertza76a6d42014-03-20 16:40:17 +01003384 }
3385 } else {
3386 // There is at least one breakpoint for this method: we don't need to undeoptimize.
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003387 req->SetKind(DeoptimizationRequest::kNothing);
3388 req->SetMethod(nullptr);
Sebastien Hertz4d1e9ab2014-09-18 16:03:34 +02003389 if (kIsDebugBuild) {
Sebastien Hertzf3928792014-11-17 19:00:37 +01003390 SanityCheckExistingBreakpoints(m, deoptimization_kind);
Sebastien Hertz4d1e9ab2014-09-18 16:03:34 +02003391 }
Elliott Hughes86964332012-02-15 19:37:42 -08003392 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -07003393}
3394
Mathieu Chartiere401d142015-04-22 13:56:20 -07003395bool Dbg::IsForcedInterpreterNeededForCallingImpl(Thread* thread, ArtMethod* m) {
Daniel Mihalyieb076692014-08-22 17:33:31 +02003396 const SingleStepControl* const ssc = thread->GetSingleStepControl();
3397 if (ssc == nullptr) {
3398 // If we are not single-stepping, then we don't have to force interpreter.
3399 return false;
3400 }
3401 if (Runtime::Current()->GetInstrumentation()->InterpretOnly()) {
3402 // If we are in interpreter only mode, then we don't have to force interpreter.
3403 return false;
3404 }
3405
3406 if (!m->IsNative() && !m->IsProxyMethod()) {
3407 // If we want to step into a method, then we have to force interpreter on that call.
3408 if (ssc->GetStepDepth() == JDWP::SD_INTO) {
3409 return true;
3410 }
3411 }
3412 return false;
3413}
3414
Mathieu Chartiere401d142015-04-22 13:56:20 -07003415bool Dbg::IsForcedInterpreterNeededForResolutionImpl(Thread* thread, ArtMethod* m) {
Daniel Mihalyieb076692014-08-22 17:33:31 +02003416 instrumentation::Instrumentation* const instrumentation =
3417 Runtime::Current()->GetInstrumentation();
3418 // If we are in interpreter only mode, then we don't have to force interpreter.
3419 if (instrumentation->InterpretOnly()) {
3420 return false;
3421 }
3422 // We can only interpret pure Java method.
3423 if (m->IsNative() || m->IsProxyMethod()) {
3424 return false;
3425 }
3426 const SingleStepControl* const ssc = thread->GetSingleStepControl();
3427 if (ssc != nullptr) {
3428 // If we want to step into a method, then we have to force interpreter on that call.
3429 if (ssc->GetStepDepth() == JDWP::SD_INTO) {
3430 return true;
3431 }
3432 // If we are stepping out from a static initializer, by issuing a step
3433 // in or step over, that was implicitly invoked by calling a static method,
3434 // then we need to step into that method. Having a lower stack depth than
3435 // the one the single step control has indicates that the step originates
3436 // from the static initializer.
3437 if (ssc->GetStepDepth() != JDWP::SD_OUT &&
3438 ssc->GetStackDepth() > GetStackDepth(thread)) {
3439 return true;
3440 }
3441 }
3442 // There are cases where we have to force interpreter on deoptimized methods,
3443 // because in some cases the call will not be performed by invoking an entry
3444 // point that has been replaced by the deoptimization, but instead by directly
3445 // invoking the compiled code of the method, for example.
3446 return instrumentation->IsDeoptimized(m);
3447}
3448
Mathieu Chartiere401d142015-04-22 13:56:20 -07003449bool Dbg::IsForcedInstrumentationNeededForResolutionImpl(Thread* thread, ArtMethod* m) {
Mathieu Chartier2cebb242015-04-21 16:50:40 -07003450 // The upcall can be null and in that case we don't need to do anything.
Daniel Mihalyieb076692014-08-22 17:33:31 +02003451 if (m == nullptr) {
3452 return false;
3453 }
3454 instrumentation::Instrumentation* const instrumentation =
3455 Runtime::Current()->GetInstrumentation();
3456 // If we are in interpreter only mode, then we don't have to force interpreter.
3457 if (instrumentation->InterpretOnly()) {
3458 return false;
3459 }
3460 // We can only interpret pure Java method.
3461 if (m->IsNative() || m->IsProxyMethod()) {
3462 return false;
3463 }
3464 const SingleStepControl* const ssc = thread->GetSingleStepControl();
3465 if (ssc != nullptr) {
3466 // If we are stepping out from a static initializer, by issuing a step
3467 // out, that was implicitly invoked by calling a static method, then we
3468 // need to step into the caller of that method. Having a lower stack
3469 // depth than the one the single step control has indicates that the
3470 // step originates from the static initializer.
3471 if (ssc->GetStepDepth() == JDWP::SD_OUT &&
3472 ssc->GetStackDepth() > GetStackDepth(thread)) {
3473 return true;
3474 }
3475 }
3476 // If we are returning from a static intializer, that was implicitly
3477 // invoked by calling a static method and the caller is deoptimized,
3478 // then we have to deoptimize the stack without forcing interpreter
3479 // on the static method that was called originally. This problem can
3480 // be solved easily by forcing instrumentation on the called method,
3481 // because the instrumentation exit hook will recognise the need of
3482 // stack deoptimization by calling IsForcedInterpreterNeededForUpcall.
3483 return instrumentation->IsDeoptimized(m);
3484}
3485
Mathieu Chartiere401d142015-04-22 13:56:20 -07003486bool Dbg::IsForcedInterpreterNeededForUpcallImpl(Thread* thread, ArtMethod* m) {
Mathieu Chartier2cebb242015-04-21 16:50:40 -07003487 // The upcall can be null and in that case we don't need to do anything.
Daniel Mihalyieb076692014-08-22 17:33:31 +02003488 if (m == nullptr) {
3489 return false;
3490 }
3491 instrumentation::Instrumentation* const instrumentation =
3492 Runtime::Current()->GetInstrumentation();
3493 // If we are in interpreter only mode, then we don't have to force interpreter.
3494 if (instrumentation->InterpretOnly()) {
3495 return false;
3496 }
3497 // We can only interpret pure Java method.
3498 if (m->IsNative() || m->IsProxyMethod()) {
3499 return false;
3500 }
3501 const SingleStepControl* const ssc = thread->GetSingleStepControl();
3502 if (ssc != nullptr) {
3503 // The debugger is not interested in what is happening under the level
3504 // of the step, thus we only force interpreter when we are not below of
3505 // the step.
3506 if (ssc->GetStackDepth() >= GetStackDepth(thread)) {
3507 return true;
3508 }
3509 }
3510 // We have to require stack deoptimization if the upcall is deoptimized.
3511 return instrumentation->IsDeoptimized(m);
3512}
3513
Jeff Hao449db332013-04-12 18:30:52 -07003514// Scoped utility class to suspend a thread so that we may do tasks such as walk its stack. Doesn't
3515// cause suspension if the thread is the current thread.
3516class ScopedThreadSuspension {
3517 public:
Ian Rogers33e95662013-05-20 20:29:14 -07003518 ScopedThreadSuspension(Thread* self, JDWP::ObjectId thread_id)
Sebastien Hertz52d131d2014-03-13 16:17:40 +01003519 LOCKS_EXCLUDED(Locks::thread_list_lock_)
Ian Rogers33e95662013-05-20 20:29:14 -07003520 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) :
Ian Rogersf3d874c2014-07-17 18:52:42 -07003521 thread_(nullptr),
Jeff Hao449db332013-04-12 18:30:52 -07003522 error_(JDWP::ERR_NONE),
3523 self_suspend_(false),
Ian Rogers33e95662013-05-20 20:29:14 -07003524 other_suspend_(false) {
Jeff Hao449db332013-04-12 18:30:52 -07003525 ScopedObjectAccessUnchecked soa(self);
Sebastien Hertz69206392015-04-07 15:54:25 +02003526 thread_ = DecodeThread(soa, thread_id, &error_);
Jeff Hao449db332013-04-12 18:30:52 -07003527 if (error_ == JDWP::ERR_NONE) {
3528 if (thread_ == soa.Self()) {
3529 self_suspend_ = true;
3530 } else {
3531 soa.Self()->TransitionFromRunnableToSuspended(kWaitingForDebuggerSuspension);
Sebastien Hertz6995c602014-09-09 12:10:13 +02003532 jobject thread_peer = Dbg::GetObjectRegistry()->GetJObject(thread_id);
Jeff Hao449db332013-04-12 18:30:52 -07003533 bool timed_out;
Ian Rogers4ad5cd32014-11-11 23:08:07 -08003534 ThreadList* thread_list = Runtime::Current()->GetThreadList();
3535 Thread* suspended_thread = thread_list->SuspendThreadByPeer(thread_peer, true, true,
3536 &timed_out);
Jeff Hao449db332013-04-12 18:30:52 -07003537 CHECK_EQ(soa.Self()->TransitionFromSuspendedToRunnable(), kWaitingForDebuggerSuspension);
Ian Rogersf3d874c2014-07-17 18:52:42 -07003538 if (suspended_thread == nullptr) {
Jeff Hao449db332013-04-12 18:30:52 -07003539 // Thread terminated from under us while suspending.
3540 error_ = JDWP::ERR_INVALID_THREAD;
3541 } else {
3542 CHECK_EQ(suspended_thread, thread_);
3543 other_suspend_ = true;
3544 }
3545 }
3546 }
Elliott Hughes2435a572012-02-17 16:07:41 -08003547 }
Elliott Hughes86964332012-02-15 19:37:42 -08003548
Jeff Hao449db332013-04-12 18:30:52 -07003549 Thread* GetThread() const {
3550 return thread_;
3551 }
3552
3553 JDWP::JdwpError GetError() const {
3554 return error_;
3555 }
3556
3557 ~ScopedThreadSuspension() {
3558 if (other_suspend_) {
3559 Runtime::Current()->GetThreadList()->Resume(thread_, true);
3560 }
3561 }
3562
3563 private:
3564 Thread* thread_;
3565 JDWP::JdwpError error_;
3566 bool self_suspend_;
3567 bool other_suspend_;
3568};
3569
3570JDWP::JdwpError Dbg::ConfigureStep(JDWP::ObjectId thread_id, JDWP::JdwpStepSize step_size,
3571 JDWP::JdwpStepDepth step_depth) {
3572 Thread* self = Thread::Current();
3573 ScopedThreadSuspension sts(self, thread_id);
3574 if (sts.GetError() != JDWP::ERR_NONE) {
3575 return sts.GetError();
3576 }
3577
Sebastien Hertz597c4f02015-01-26 17:37:14 +01003578 // Work out what ArtMethod* we're in, the current line number, and how deep the stack currently
Elliott Hughes2435a572012-02-17 16:07:41 -08003579 // is for step-out.
Ian Rogers0399dde2012-06-06 17:09:28 -07003580 struct SingleStepStackVisitor : public StackVisitor {
Sebastien Hertz597c4f02015-01-26 17:37:14 +01003581 explicit SingleStepStackVisitor(Thread* thread) SHARED_LOCKS_REQUIRED(Locks::mutator_lock_)
Nicolas Geoffray8e5bd182015-05-06 11:34:34 +01003582 : StackVisitor(thread, nullptr, StackVisitor::StackWalkKind::kIncludeInlinedFrames),
3583 stack_depth(0),
3584 method(nullptr),
3585 line_number(-1) {}
Ian Rogersca190662012-06-26 15:45:57 -07003586
Ian Rogers00f7d0e2012-07-19 15:28:27 -07003587 // TODO: Enable annotalysis. We know lock is held in constructor, but abstraction confuses
3588 // annotalysis.
3589 bool VisitFrame() NO_THREAD_SAFETY_ANALYSIS {
Mathieu Chartiere401d142015-04-22 13:56:20 -07003590 ArtMethod* m = GetMethod();
Ian Rogers0399dde2012-06-06 17:09:28 -07003591 if (!m->IsRuntimeMethod()) {
Sebastien Hertz597c4f02015-01-26 17:37:14 +01003592 ++stack_depth;
3593 if (method == nullptr) {
Ian Rogersef7d42f2014-01-06 12:55:46 -08003594 mirror::DexCache* dex_cache = m->GetDeclaringClass()->GetDexCache();
Sebastien Hertz597c4f02015-01-26 17:37:14 +01003595 method = m;
Ian Rogersc0542af2014-09-03 16:16:56 -07003596 if (dex_cache != nullptr) {
Ian Rogers4445a7e2012-10-05 17:19:13 -07003597 const DexFile& dex_file = *dex_cache->GetDexFile();
Sebastien Hertz597c4f02015-01-26 17:37:14 +01003598 line_number = dex_file.GetLineNumFromPC(m, GetDexPc());
Elliott Hughes2435a572012-02-17 16:07:41 -08003599 }
Elliott Hughes86964332012-02-15 19:37:42 -08003600 }
3601 }
Elliott Hughes530fa002012-03-12 11:44:49 -07003602 return true;
Elliott Hughes86964332012-02-15 19:37:42 -08003603 }
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01003604
Sebastien Hertz597c4f02015-01-26 17:37:14 +01003605 int stack_depth;
Mathieu Chartiere401d142015-04-22 13:56:20 -07003606 ArtMethod* method;
Sebastien Hertz597c4f02015-01-26 17:37:14 +01003607 int32_t line_number;
Elliott Hughes86964332012-02-15 19:37:42 -08003608 };
Jeff Hao449db332013-04-12 18:30:52 -07003609
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01003610 Thread* const thread = sts.GetThread();
Sebastien Hertz597c4f02015-01-26 17:37:14 +01003611 SingleStepStackVisitor visitor(thread);
Ian Rogers0399dde2012-06-06 17:09:28 -07003612 visitor.WalkStack();
Elliott Hughes86964332012-02-15 19:37:42 -08003613
Elliott Hughes2435a572012-02-17 16:07:41 -08003614 // Find the dex_pc values that correspond to the current line, for line-based single-stepping.
Elliott Hughes2435a572012-02-17 16:07:41 -08003615 struct DebugCallbackContext {
Sebastien Hertz597c4f02015-01-26 17:37:14 +01003616 explicit DebugCallbackContext(SingleStepControl* single_step_control_cb,
3617 int32_t line_number_cb, const DexFile::CodeItem* code_item)
Andreas Gampe277ccbd2014-11-03 21:36:10 -08003618 : single_step_control_(single_step_control_cb), line_number_(line_number_cb),
3619 code_item_(code_item), last_pc_valid(false), last_pc(0) {
Elliott Hughes2435a572012-02-17 16:07:41 -08003620 }
3621
Andreas Gampe277ccbd2014-11-03 21:36:10 -08003622 static bool Callback(void* raw_context, uint32_t address, uint32_t line_number_cb) {
Elliott Hughes2435a572012-02-17 16:07:41 -08003623 DebugCallbackContext* context = reinterpret_cast<DebugCallbackContext*>(raw_context);
Andreas Gampe277ccbd2014-11-03 21:36:10 -08003624 if (static_cast<int32_t>(line_number_cb) == context->line_number_) {
Elliott Hughes2435a572012-02-17 16:07:41 -08003625 if (!context->last_pc_valid) {
3626 // Everything from this address until the next line change is ours.
3627 context->last_pc = address;
3628 context->last_pc_valid = true;
3629 }
3630 // Otherwise, if we're already in a valid range for this line,
3631 // just keep going (shouldn't really happen)...
Brian Carlstrom7934ac22013-07-26 10:54:15 -07003632 } else if (context->last_pc_valid) { // and the line number is new
Elliott Hughes2435a572012-02-17 16:07:41 -08003633 // Add everything from the last entry up until here to the set
3634 for (uint32_t dex_pc = context->last_pc; dex_pc < address; ++dex_pc) {
Sebastien Hertz597c4f02015-01-26 17:37:14 +01003635 context->single_step_control_->AddDexPc(dex_pc);
Elliott Hughes2435a572012-02-17 16:07:41 -08003636 }
3637 context->last_pc_valid = false;
3638 }
Brian Carlstrom7934ac22013-07-26 10:54:15 -07003639 return false; // There may be multiple entries for any given line.
Elliott Hughes2435a572012-02-17 16:07:41 -08003640 }
3641
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01003642 ~DebugCallbackContext() {
Elliott Hughes2435a572012-02-17 16:07:41 -08003643 // If the line number was the last in the position table...
3644 if (last_pc_valid) {
Sebastien Hertzbb43b432014-04-14 11:59:08 +02003645 size_t end = code_item_->insns_size_in_code_units_;
Elliott Hughes2435a572012-02-17 16:07:41 -08003646 for (uint32_t dex_pc = last_pc; dex_pc < end; ++dex_pc) {
Sebastien Hertz597c4f02015-01-26 17:37:14 +01003647 single_step_control_->AddDexPc(dex_pc);
Elliott Hughes2435a572012-02-17 16:07:41 -08003648 }
3649 }
3650 }
3651
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01003652 SingleStepControl* const single_step_control_;
3653 const int32_t line_number_;
Sebastien Hertzbb43b432014-04-14 11:59:08 +02003654 const DexFile::CodeItem* const code_item_;
Elliott Hughes2435a572012-02-17 16:07:41 -08003655 bool last_pc_valid;
3656 uint32_t last_pc;
3657 };
Sebastien Hertz597c4f02015-01-26 17:37:14 +01003658
3659 // Allocate single step.
Sebastien Hertz1558b572015-02-25 15:05:59 +01003660 SingleStepControl* single_step_control =
3661 new (std::nothrow) SingleStepControl(step_size, step_depth,
3662 visitor.stack_depth, visitor.method);
3663 if (single_step_control == nullptr) {
3664 LOG(ERROR) << "Failed to allocate SingleStepControl";
3665 return JDWP::ERR_OUT_OF_MEMORY;
3666 }
3667
Mathieu Chartiere401d142015-04-22 13:56:20 -07003668 ArtMethod* m = single_step_control->GetMethod();
Sebastien Hertz597c4f02015-01-26 17:37:14 +01003669 const int32_t line_number = visitor.line_number;
Sebastien Hertz52f5f932015-05-28 11:00:57 +02003670 // Note: if the thread is not running Java code (pure native thread), there is no "current"
3671 // method on the stack (and no line number either).
3672 if (m != nullptr && !m->IsNative()) {
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07003673 const DexFile::CodeItem* const code_item = m->GetCodeItem();
Sebastien Hertzbb43b432014-04-14 11:59:08 +02003674 DebugCallbackContext context(single_step_control, line_number, code_item);
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07003675 m->GetDexFile()->DecodeDebugInfo(code_item, m->IsStatic(), m->GetDexMethodIndex(),
Ian Rogersc0542af2014-09-03 16:16:56 -07003676 DebugCallbackContext::Callback, nullptr, &context);
Elliott Hughes3e2e1a22012-02-21 11:33:41 -08003677 }
Elliott Hughes2435a572012-02-17 16:07:41 -08003678
Sebastien Hertz597c4f02015-01-26 17:37:14 +01003679 // Activate single-step in the thread.
3680 thread->ActivateSingleStepControl(single_step_control);
Elliott Hughes86964332012-02-15 19:37:42 -08003681
Elliott Hughes2435a572012-02-17 16:07:41 -08003682 if (VLOG_IS_ON(jdwp)) {
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01003683 VLOG(jdwp) << "Single-step thread: " << *thread;
Sebastien Hertz597c4f02015-01-26 17:37:14 +01003684 VLOG(jdwp) << "Single-step step size: " << single_step_control->GetStepSize();
3685 VLOG(jdwp) << "Single-step step depth: " << single_step_control->GetStepDepth();
3686 VLOG(jdwp) << "Single-step current method: " << PrettyMethod(single_step_control->GetMethod());
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01003687 VLOG(jdwp) << "Single-step current line: " << line_number;
Sebastien Hertz597c4f02015-01-26 17:37:14 +01003688 VLOG(jdwp) << "Single-step current stack depth: " << single_step_control->GetStackDepth();
Elliott Hughes2435a572012-02-17 16:07:41 -08003689 VLOG(jdwp) << "Single-step dex_pc values:";
Sebastien Hertz597c4f02015-01-26 17:37:14 +01003690 for (uint32_t dex_pc : single_step_control->GetDexPcs()) {
Sebastien Hertzbb43b432014-04-14 11:59:08 +02003691 VLOG(jdwp) << StringPrintf(" %#x", dex_pc);
Elliott Hughes2435a572012-02-17 16:07:41 -08003692 }
3693 }
3694
3695 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07003696}
3697
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01003698void Dbg::UnconfigureStep(JDWP::ObjectId thread_id) {
3699 ScopedObjectAccessUnchecked soa(Thread::Current());
Ian Rogersc0542af2014-09-03 16:16:56 -07003700 JDWP::JdwpError error;
3701 Thread* thread = DecodeThread(soa, thread_id, &error);
Sebastien Hertz87118ed2013-11-26 17:57:18 +01003702 if (error == JDWP::ERR_NONE) {
Sebastien Hertz597c4f02015-01-26 17:37:14 +01003703 thread->DeactivateSingleStepControl();
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01003704 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -07003705}
3706
Elliott Hughes45651fd2012-02-21 15:48:20 -08003707static char JdwpTagToShortyChar(JDWP::JdwpTag tag) {
3708 switch (tag) {
3709 default:
3710 LOG(FATAL) << "unknown JDWP tag: " << PrintableChar(tag);
Ian Rogersfc787ec2014-10-09 21:56:44 -07003711 UNREACHABLE();
Elliott Hughes45651fd2012-02-21 15:48:20 -08003712
3713 // Primitives.
3714 case JDWP::JT_BYTE: return 'B';
3715 case JDWP::JT_CHAR: return 'C';
3716 case JDWP::JT_FLOAT: return 'F';
3717 case JDWP::JT_DOUBLE: return 'D';
3718 case JDWP::JT_INT: return 'I';
3719 case JDWP::JT_LONG: return 'J';
3720 case JDWP::JT_SHORT: return 'S';
3721 case JDWP::JT_VOID: return 'V';
3722 case JDWP::JT_BOOLEAN: return 'Z';
3723
3724 // Reference types.
3725 case JDWP::JT_ARRAY:
3726 case JDWP::JT_OBJECT:
3727 case JDWP::JT_STRING:
3728 case JDWP::JT_THREAD:
3729 case JDWP::JT_THREAD_GROUP:
3730 case JDWP::JT_CLASS_LOADER:
3731 case JDWP::JT_CLASS_OBJECT:
3732 return 'L';
3733 }
3734}
3735
Sebastien Hertzcbc50642015-06-01 17:33:12 +02003736JDWP::JdwpError Dbg::PrepareInvokeMethod(uint32_t request_id, JDWP::ObjectId thread_id,
3737 JDWP::ObjectId object_id, JDWP::RefTypeId class_id,
3738 JDWP::MethodId method_id, uint32_t arg_count,
3739 uint64_t arg_values[], JDWP::JdwpTag* arg_types,
3740 uint32_t options) {
3741 Thread* const self = Thread::Current();
3742 CHECK_EQ(self, GetDebugThread()) << "This must be called by the JDWP thread";
Elliott Hughesd07986f2011-12-06 18:27:45 -08003743
Sebastien Hertzcbc50642015-06-01 17:33:12 +02003744 ThreadList* thread_list = Runtime::Current()->GetThreadList();
Ian Rogersc0542af2014-09-03 16:16:56 -07003745 Thread* targetThread = nullptr;
Elliott Hughesd07986f2011-12-06 18:27:45 -08003746 {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07003747 ScopedObjectAccessUnchecked soa(self);
Ian Rogersc0542af2014-09-03 16:16:56 -07003748 JDWP::JdwpError error;
3749 targetThread = DecodeThread(soa, thread_id, &error);
Elliott Hughes221229c2013-01-08 18:17:50 -08003750 if (error != JDWP::ERR_NONE) {
3751 LOG(ERROR) << "InvokeMethod request for invalid thread id " << thread_id;
3752 return error;
Elliott Hughesd07986f2011-12-06 18:27:45 -08003753 }
Sebastien Hertz1558b572015-02-25 15:05:59 +01003754 if (targetThread->GetInvokeReq() != nullptr) {
3755 // Thread is already invoking a method on behalf of the debugger.
3756 LOG(ERROR) << "InvokeMethod request for thread already invoking a method: " << *targetThread;
3757 return JDWP::ERR_ALREADY_INVOKING;
3758 }
3759 if (!targetThread->IsReadyForDebugInvoke()) {
3760 // Thread is not suspended by an event so it cannot invoke a method.
Elliott Hughesd07986f2011-12-06 18:27:45 -08003761 LOG(ERROR) << "InvokeMethod request for thread not stopped by event: " << *targetThread;
3762 return JDWP::ERR_INVALID_THREAD;
3763 }
3764
3765 /*
3766 * We currently have a bug where we don't successfully resume the
3767 * target thread if the suspend count is too deep. We're expected to
3768 * require one "resume" for each "suspend", but when asked to execute
3769 * a method we have to resume fully and then re-suspend it back to the
3770 * same level. (The easiest way to cause this is to type "suspend"
3771 * multiple times in jdb.)
3772 *
3773 * It's unclear what this means when the event specifies "resume all"
3774 * and some threads are suspended more deeply than others. This is
3775 * a rare problem, so for now we just prevent it from hanging forever
3776 * by rejecting the method invocation request. Without this, we will
3777 * be stuck waiting on a suspended thread.
3778 */
Ian Rogers00f7d0e2012-07-19 15:28:27 -07003779 int suspend_count;
3780 {
Ian Rogers50b35e22012-10-04 10:09:15 -07003781 MutexLock mu2(soa.Self(), *Locks::thread_suspend_count_lock_);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07003782 suspend_count = targetThread->GetSuspendCount();
3783 }
Elliott Hughesd07986f2011-12-06 18:27:45 -08003784 if (suspend_count > 1) {
3785 LOG(ERROR) << *targetThread << " suspend count too deep for method invocation: " << suspend_count;
Brian Carlstrom7934ac22013-07-26 10:54:15 -07003786 return JDWP::ERR_THREAD_SUSPENDED; // Probably not expected here.
Elliott Hughesd07986f2011-12-06 18:27:45 -08003787 }
3788
Ian Rogersc0542af2014-09-03 16:16:56 -07003789 mirror::Object* receiver = gRegistry->Get<mirror::Object*>(object_id, &error);
3790 if (error != JDWP::ERR_NONE) {
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08003791 return JDWP::ERR_INVALID_OBJECT;
3792 }
Elliott Hughes45651fd2012-02-21 15:48:20 -08003793
Sebastien Hertz1558b572015-02-25 15:05:59 +01003794 gRegistry->Get<mirror::Object*>(thread_id, &error);
Ian Rogersc0542af2014-09-03 16:16:56 -07003795 if (error != JDWP::ERR_NONE) {
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08003796 return JDWP::ERR_INVALID_OBJECT;
3797 }
Elliott Hughes45651fd2012-02-21 15:48:20 -08003798
Ian Rogersc0542af2014-09-03 16:16:56 -07003799 mirror::Class* c = DecodeClass(class_id, &error);
3800 if (c == nullptr) {
3801 return error;
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08003802 }
Elliott Hughes45651fd2012-02-21 15:48:20 -08003803
Mathieu Chartiere401d142015-04-22 13:56:20 -07003804 ArtMethod* m = FromMethodId(method_id);
Ian Rogersc0542af2014-09-03 16:16:56 -07003805 if (m->IsStatic() != (receiver == nullptr)) {
Elliott Hughes45651fd2012-02-21 15:48:20 -08003806 return JDWP::ERR_INVALID_METHODID;
3807 }
3808 if (m->IsStatic()) {
3809 if (m->GetDeclaringClass() != c) {
3810 return JDWP::ERR_INVALID_METHODID;
3811 }
3812 } else {
3813 if (!m->GetDeclaringClass()->IsAssignableFrom(c)) {
3814 return JDWP::ERR_INVALID_METHODID;
3815 }
3816 }
3817
3818 // Check the argument list matches the method.
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07003819 uint32_t shorty_len = 0;
3820 const char* shorty = m->GetShorty(&shorty_len);
3821 if (shorty_len - 1 != arg_count) {
Elliott Hughes45651fd2012-02-21 15:48:20 -08003822 return JDWP::ERR_ILLEGAL_ARGUMENT;
3823 }
Elliott Hughes09201632013-04-15 15:50:07 -07003824
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07003825 {
Mathieu Chartiere401d142015-04-22 13:56:20 -07003826 StackHandleScope<2> hs(soa.Self());
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07003827 HandleWrapper<mirror::Object> h_obj(hs.NewHandleWrapper(&receiver));
3828 HandleWrapper<mirror::Class> h_klass(hs.NewHandleWrapper(&c));
3829 const DexFile::TypeList* types = m->GetParameterTypeList();
3830 for (size_t i = 0; i < arg_count; ++i) {
3831 if (shorty[i + 1] != JdwpTagToShortyChar(arg_types[i])) {
Elliott Hughes09201632013-04-15 15:50:07 -07003832 return JDWP::ERR_ILLEGAL_ARGUMENT;
3833 }
3834
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07003835 if (shorty[i + 1] == 'L') {
3836 // Did we really get an argument of an appropriate reference type?
Ian Rogersa0485602014-12-02 15:48:04 -08003837 mirror::Class* parameter_type =
Mathieu Chartiere401d142015-04-22 13:56:20 -07003838 m->GetClassFromTypeIndex(types->GetTypeItem(i).type_idx_, true);
Ian Rogersc0542af2014-09-03 16:16:56 -07003839 mirror::Object* argument = gRegistry->Get<mirror::Object*>(arg_values[i], &error);
3840 if (error != JDWP::ERR_NONE) {
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07003841 return JDWP::ERR_INVALID_OBJECT;
3842 }
Ian Rogersc0542af2014-09-03 16:16:56 -07003843 if (argument != nullptr && !argument->InstanceOf(parameter_type)) {
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07003844 return JDWP::ERR_ILLEGAL_ARGUMENT;
3845 }
3846
3847 // Turn the on-the-wire ObjectId into a jobject.
3848 jvalue& v = reinterpret_cast<jvalue&>(arg_values[i]);
3849 v.l = gRegistry->GetJObject(arg_values[i]);
3850 }
Elliott Hughes09201632013-04-15 15:50:07 -07003851 }
Elliott Hughes45651fd2012-02-21 15:48:20 -08003852 }
3853
Sebastien Hertz1558b572015-02-25 15:05:59 +01003854 // Allocates a DebugInvokeReq.
Sebastien Hertzcbc50642015-06-01 17:33:12 +02003855 DebugInvokeReq* req = new (std::nothrow) DebugInvokeReq(request_id, thread_id, receiver, c, m,
3856 options, arg_values, arg_count);
3857 if (req == nullptr) {
Sebastien Hertz1558b572015-02-25 15:05:59 +01003858 LOG(ERROR) << "Failed to allocate DebugInvokeReq";
3859 return JDWP::ERR_OUT_OF_MEMORY;
3860 }
3861
Sebastien Hertzcbc50642015-06-01 17:33:12 +02003862 // Attaches the DebugInvokeReq to the target thread so it executes the method when
3863 // it is resumed. Once the invocation completes, the target thread will delete it before
3864 // suspending itself (see ThreadList::SuspendSelfForDebugger).
3865 targetThread->SetDebugInvokeReq(req);
Elliott Hughesd07986f2011-12-06 18:27:45 -08003866 }
3867
3868 // The fact that we've released the thread list lock is a bit risky --- if the thread goes
Sebastien Hertzcbc50642015-06-01 17:33:12 +02003869 // away we're sitting high and dry -- but we must release this before the UndoDebuggerSuspensions
3870 // call.
Elliott Hughesd07986f2011-12-06 18:27:45 -08003871
Elliott Hughesd07986f2011-12-06 18:27:45 -08003872 if ((options & JDWP::INVOKE_SINGLE_THREADED) == 0) {
Sebastien Hertzcbc50642015-06-01 17:33:12 +02003873 VLOG(jdwp) << " Resuming all threads";
3874 thread_list->UndoDebuggerSuspensions();
3875 } else {
3876 VLOG(jdwp) << " Resuming event thread only";
Elliott Hughesd07986f2011-12-06 18:27:45 -08003877 thread_list->Resume(targetThread, true);
3878 }
3879
Sebastien Hertzcbc50642015-06-01 17:33:12 +02003880 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07003881}
3882
3883void Dbg::ExecuteMethod(DebugInvokeReq* pReq) {
Sebastien Hertzcbc50642015-06-01 17:33:12 +02003884 Thread* const self = Thread::Current();
3885 CHECK_NE(self, GetDebugThread()) << "This must be called by the event thread";
3886
3887 ScopedObjectAccess soa(self);
Elliott Hughesd07986f2011-12-06 18:27:45 -08003888
Elliott Hughes81ff3182012-03-23 20:35:56 -07003889 // We can be called while an exception is pending. We need
Elliott Hughesd07986f2011-12-06 18:27:45 -08003890 // to preserve that across the method invocation.
Sebastien Hertzcbc50642015-06-01 17:33:12 +02003891 StackHandleScope<1> hs(soa.Self());
3892 Handle<mirror::Throwable> old_exception = hs.NewHandle(soa.Self()->GetException());
Sebastien Hertz1558b572015-02-25 15:05:59 +01003893 soa.Self()->ClearException();
Elliott Hughesd07986f2011-12-06 18:27:45 -08003894
Sebastien Hertzcbc50642015-06-01 17:33:12 +02003895 // Execute the method then sends reply to the debugger.
3896 ExecuteMethodWithoutPendingException(soa, pReq);
3897
3898 // If an exception was pending before the invoke, restore it now.
3899 if (old_exception.Get() != nullptr) {
3900 soa.Self()->SetException(old_exception.Get());
3901 }
3902}
3903
3904// Helper function: write a variable-width value into the output input buffer.
3905static void WriteValue(JDWP::ExpandBuf* pReply, int width, uint64_t value) {
3906 switch (width) {
3907 case 1:
3908 expandBufAdd1(pReply, value);
3909 break;
3910 case 2:
3911 expandBufAdd2BE(pReply, value);
3912 break;
3913 case 4:
3914 expandBufAdd4BE(pReply, value);
3915 break;
3916 case 8:
3917 expandBufAdd8BE(pReply, value);
3918 break;
3919 default:
3920 LOG(FATAL) << width;
3921 UNREACHABLE();
3922 }
3923}
3924
3925void Dbg::ExecuteMethodWithoutPendingException(ScopedObjectAccess& soa, DebugInvokeReq* pReq) {
3926 soa.Self()->AssertNoPendingException();
3927
Elliott Hughesd07986f2011-12-06 18:27:45 -08003928 // Translate the method through the vtable, unless the debugger wants to suppress it.
Sebastien Hertzcbc50642015-06-01 17:33:12 +02003929 ArtMethod* m = pReq->method;
3930 size_t image_pointer_size = Runtime::Current()->GetClassLinker()->GetImagePointerSize();
Sebastien Hertz1558b572015-02-25 15:05:59 +01003931 if ((pReq->options & JDWP::INVOKE_NONVIRTUAL) == 0 && pReq->receiver.Read() != nullptr) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07003932 ArtMethod* actual_method =
3933 pReq->klass.Read()->FindVirtualMethodForVirtualOrInterface(m, image_pointer_size);
3934 if (actual_method != m) {
3935 VLOG(jdwp) << "ExecuteMethod translated " << PrettyMethod(m)
Sebastien Hertz1558b572015-02-25 15:05:59 +01003936 << " to " << PrettyMethod(actual_method);
Mathieu Chartiere401d142015-04-22 13:56:20 -07003937 m = actual_method;
Elliott Hughes45651fd2012-02-21 15:48:20 -08003938 }
Elliott Hughesd07986f2011-12-06 18:27:45 -08003939 }
Mathieu Chartiere401d142015-04-22 13:56:20 -07003940 VLOG(jdwp) << "ExecuteMethod " << PrettyMethod(m)
Sebastien Hertz1558b572015-02-25 15:05:59 +01003941 << " receiver=" << pReq->receiver.Read()
Sebastien Hertzd38667a2013-11-25 15:43:54 +01003942 << " arg_count=" << pReq->arg_count;
Mathieu Chartiere401d142015-04-22 13:56:20 -07003943 CHECK(m != nullptr);
Elliott Hughesd07986f2011-12-06 18:27:45 -08003944
Roland Levillain33d69032015-06-18 18:20:59 +01003945 static_assert(sizeof(jvalue) == sizeof(uint64_t), "jvalue and uint64_t have different sizes.");
Elliott Hughesd07986f2011-12-06 18:27:45 -08003946
Sebastien Hertzcbc50642015-06-01 17:33:12 +02003947 // Invoke the method.
Jeff Hao39b6c242015-05-19 20:30:23 -07003948 ScopedLocalRef<jobject> ref(soa.Env(), soa.AddLocalReference<jobject>(pReq->receiver.Read()));
Mathieu Chartiere401d142015-04-22 13:56:20 -07003949 JValue result = InvokeWithJValues(soa, ref.get(), soa.EncodeMethod(m),
Sebastien Hertzcbc50642015-06-01 17:33:12 +02003950 reinterpret_cast<jvalue*>(pReq->arg_values.get()));
Elliott Hughesd07986f2011-12-06 18:27:45 -08003951
Sebastien Hertzcbc50642015-06-01 17:33:12 +02003952 // Prepare JDWP ids for the reply.
3953 JDWP::JdwpTag result_tag = BasicTagFromDescriptor(m->GetShorty());
3954 const bool is_object_result = (result_tag == JDWP::JT_OBJECT);
3955 StackHandleScope<2> hs(soa.Self());
Sebastien Hertz1558b572015-02-25 15:05:59 +01003956 Handle<mirror::Object> object_result = hs.NewHandle(is_object_result ? result.GetL() : nullptr);
3957 Handle<mirror::Throwable> exception = hs.NewHandle(soa.Self()->GetException());
3958 soa.Self()->ClearException();
Sebastien Hertzcbc50642015-06-01 17:33:12 +02003959
3960 if (!IsDebuggerActive()) {
3961 // The debugger detached: we must not re-suspend threads. We also don't need to fill the reply
3962 // because it won't be sent either.
3963 return;
3964 }
3965
3966 JDWP::ObjectId exceptionObjectId = gRegistry->Add(exception);
3967 uint64_t result_value = 0;
3968 if (exceptionObjectId != 0) {
Sebastien Hertz1558b572015-02-25 15:05:59 +01003969 VLOG(jdwp) << " JDWP invocation returning with exception=" << exception.Get()
3970 << " " << exception->Dump();
Sebastien Hertzcbc50642015-06-01 17:33:12 +02003971 result_value = 0;
Sebastien Hertz1558b572015-02-25 15:05:59 +01003972 } else if (is_object_result) {
Sebastien Hertzcbc50642015-06-01 17:33:12 +02003973 /* if no exception was thrown, examine object result more closely */
Sebastien Hertz1558b572015-02-25 15:05:59 +01003974 JDWP::JdwpTag new_tag = TagFromObject(soa, object_result.Get());
Sebastien Hertzcbc50642015-06-01 17:33:12 +02003975 if (new_tag != result_tag) {
3976 VLOG(jdwp) << " JDWP promoted result from " << result_tag << " to " << new_tag;
3977 result_tag = new_tag;
Elliott Hughesd07986f2011-12-06 18:27:45 -08003978 }
3979
Sebastien Hertz1558b572015-02-25 15:05:59 +01003980 // Register the object in the registry and reference its ObjectId. This ensures
3981 // GC safety and prevents from accessing stale reference if the object is moved.
Sebastien Hertzcbc50642015-06-01 17:33:12 +02003982 result_value = gRegistry->Add(object_result.Get());
Sebastien Hertz1558b572015-02-25 15:05:59 +01003983 } else {
3984 // Primitive result.
Sebastien Hertzcbc50642015-06-01 17:33:12 +02003985 DCHECK(IsPrimitiveTag(result_tag));
3986 result_value = result.GetJ();
3987 }
3988 const bool is_constructor = m->IsConstructor() && !m->IsStatic();
3989 if (is_constructor) {
3990 // If we invoked a constructor (which actually returns void), return the receiver,
3991 // unless we threw, in which case we return null.
3992 result_tag = JDWP::JT_OBJECT;
3993 if (exceptionObjectId == 0) {
3994 // TODO we could keep the receiver ObjectId in the DebugInvokeReq to avoid looking into the
3995 // object registry.
3996 result_value = GetObjectRegistry()->Add(pReq->receiver.Read());
3997 } else {
3998 result_value = 0;
3999 }
Elliott Hughesd07986f2011-12-06 18:27:45 -08004000 }
4001
Sebastien Hertzcbc50642015-06-01 17:33:12 +02004002 // Suspend other threads if the invoke is not single-threaded.
4003 if ((pReq->options & JDWP::INVOKE_SINGLE_THREADED) == 0) {
4004 soa.Self()->TransitionFromRunnableToSuspended(kWaitingForDebuggerSuspension);
4005 VLOG(jdwp) << " Suspending all threads";
4006 Runtime::Current()->GetThreadList()->SuspendAllForDebugger();
4007 soa.Self()->TransitionFromSuspendedToRunnable();
4008 }
4009
4010 VLOG(jdwp) << " --> returned " << result_tag
4011 << StringPrintf(" %#" PRIx64 " (except=%#" PRIx64 ")", result_value,
4012 exceptionObjectId);
4013
4014 // Show detailed debug output.
4015 if (result_tag == JDWP::JT_STRING && exceptionObjectId == 0) {
4016 if (result_value != 0) {
4017 if (VLOG_IS_ON(jdwp)) {
4018 std::string result_string;
4019 JDWP::JdwpError error = Dbg::StringToUtf8(result_value, &result_string);
4020 CHECK_EQ(error, JDWP::ERR_NONE);
4021 VLOG(jdwp) << " string '" << result_string << "'";
4022 }
4023 } else {
4024 VLOG(jdwp) << " string (null)";
4025 }
4026 }
4027
4028 // Attach the reply to DebugInvokeReq so it can be sent to the debugger when the event thread
4029 // is ready to suspend.
4030 BuildInvokeReply(pReq->reply, pReq->request_id, result_tag, result_value, exceptionObjectId);
4031}
4032
4033void Dbg::BuildInvokeReply(JDWP::ExpandBuf* pReply, uint32_t request_id, JDWP::JdwpTag result_tag,
4034 uint64_t result_value, JDWP::ObjectId exception) {
4035 // Make room for the JDWP header since we do not know the size of the reply yet.
4036 JDWP::expandBufAddSpace(pReply, kJDWPHeaderLen);
4037
4038 size_t width = GetTagWidth(result_tag);
4039 JDWP::expandBufAdd1(pReply, result_tag);
4040 if (width != 0) {
4041 WriteValue(pReply, width, result_value);
4042 }
4043 JDWP::expandBufAdd1(pReply, JDWP::JT_OBJECT);
4044 JDWP::expandBufAddObjectId(pReply, exception);
4045
4046 // Now we know the size, we can complete the JDWP header.
4047 uint8_t* buf = expandBufGetBuffer(pReply);
4048 JDWP::Set4BE(buf + kJDWPHeaderSizeOffset, expandBufGetLength(pReply));
4049 JDWP::Set4BE(buf + kJDWPHeaderIdOffset, request_id);
4050 JDWP::Set1(buf + kJDWPHeaderFlagsOffset, kJDWPFlagReply); // flags
4051 JDWP::Set2BE(buf + kJDWPHeaderErrorCodeOffset, JDWP::ERR_NONE);
4052}
4053
4054void Dbg::FinishInvokeMethod(DebugInvokeReq* pReq) {
4055 CHECK_NE(Thread::Current(), GetDebugThread()) << "This must be called by the event thread";
4056
4057 JDWP::ExpandBuf* const pReply = pReq->reply;
4058 CHECK(pReply != nullptr) << "No reply attached to DebugInvokeReq";
4059
4060 // We need to prevent other threads (including JDWP thread) from interacting with the debugger
4061 // while we send the reply but are not yet suspended. The JDWP token will be released just before
4062 // we suspend ourself again (see ThreadList::SuspendSelfForDebugger).
4063 gJdwpState->AcquireJdwpTokenForEvent(pReq->thread_id);
4064
4065 // Send the reply unless the debugger detached before the completion of the method.
4066 if (IsDebuggerActive()) {
4067 const size_t replyDataLength = expandBufGetLength(pReply) - kJDWPHeaderLen;
4068 VLOG(jdwp) << StringPrintf("REPLY INVOKE id=0x%06x (length=%zu)",
4069 pReq->request_id, replyDataLength);
4070
4071 gJdwpState->SendRequest(pReply);
4072 } else {
4073 VLOG(jdwp) << "Not sending invoke reply because debugger detached";
Elliott Hughesd07986f2011-12-06 18:27:45 -08004074 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -07004075}
4076
Elliott Hughesd07986f2011-12-06 18:27:45 -08004077/*
Elliott Hughes4b9702c2013-02-20 18:13:24 -08004078 * "request" contains a full JDWP packet, possibly with multiple chunks. We
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07004079 * need to process each, accumulate the replies, and ship the whole thing
4080 * back.
4081 *
4082 * Returns "true" if we have a reply. The reply buffer is newly allocated,
4083 * and includes the chunk type/length, followed by the data.
4084 *
Elliott Hughes3d30d9b2011-12-07 17:35:48 -08004085 * OLD-TODO: we currently assume that the request and reply include a single
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07004086 * chunk. If this becomes inconvenient we will need to adapt.
4087 */
Ian Rogersc0542af2014-09-03 16:16:56 -07004088bool Dbg::DdmHandlePacket(JDWP::Request* request, uint8_t** pReplyBuf, int* pReplyLen) {
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07004089 Thread* self = Thread::Current();
4090 JNIEnv* env = self->GetJniEnv();
4091
Ian Rogersc0542af2014-09-03 16:16:56 -07004092 uint32_t type = request->ReadUnsigned32("type");
4093 uint32_t length = request->ReadUnsigned32("length");
Elliott Hughes4b9702c2013-02-20 18:13:24 -08004094
4095 // Create a byte[] corresponding to 'request'.
Ian Rogersc0542af2014-09-03 16:16:56 -07004096 size_t request_length = request->size();
Elliott Hughes4b9702c2013-02-20 18:13:24 -08004097 ScopedLocalRef<jbyteArray> dataArray(env, env->NewByteArray(request_length));
Ian Rogersc0542af2014-09-03 16:16:56 -07004098 if (dataArray.get() == nullptr) {
Elliott Hughes4b9702c2013-02-20 18:13:24 -08004099 LOG(WARNING) << "byte[] allocation failed: " << request_length;
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07004100 env->ExceptionClear();
4101 return false;
4102 }
Ian Rogersc0542af2014-09-03 16:16:56 -07004103 env->SetByteArrayRegion(dataArray.get(), 0, request_length,
4104 reinterpret_cast<const jbyte*>(request->data()));
4105 request->Skip(request_length);
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07004106
4107 // Run through and find all chunks. [Currently just find the first.]
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004108 ScopedByteArrayRO contents(env, dataArray.get());
Elliott Hughes4b9702c2013-02-20 18:13:24 -08004109 if (length != request_length) {
Ian Rogersef7d42f2014-01-06 12:55:46 -08004110 LOG(WARNING) << StringPrintf("bad chunk found (len=%u pktLen=%zd)", length, request_length);
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07004111 return false;
4112 }
4113
4114 // Call "private static Chunk dispatch(int type, byte[] data, int offset, int length)".
Elliott Hugheseac76672012-05-24 21:56:51 -07004115 ScopedLocalRef<jobject> chunk(env, env->CallStaticObjectMethod(WellKnownClasses::org_apache_harmony_dalvik_ddmc_DdmServer,
4116 WellKnownClasses::org_apache_harmony_dalvik_ddmc_DdmServer_dispatch,
Elliott Hughes4b9702c2013-02-20 18:13:24 -08004117 type, dataArray.get(), 0, length));
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07004118 if (env->ExceptionCheck()) {
4119 LOG(INFO) << StringPrintf("Exception thrown by dispatcher for 0x%08x", type);
4120 env->ExceptionDescribe();
4121 env->ExceptionClear();
4122 return false;
4123 }
4124
Ian Rogersc0542af2014-09-03 16:16:56 -07004125 if (chunk.get() == nullptr) {
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07004126 return false;
4127 }
4128
4129 /*
4130 * Pull the pieces out of the chunk. We copy the results into a
4131 * newly-allocated buffer that the caller can free. We don't want to
4132 * continue using the Chunk object because nothing has a reference to it.
4133 *
4134 * We could avoid this by returning type/data/offset/length and having
4135 * the caller be aware of the object lifetime issues, but that
Elliott Hughes81ff3182012-03-23 20:35:56 -07004136 * integrates the JDWP code more tightly into the rest of the runtime, and doesn't work
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07004137 * if we have responses for multiple chunks.
4138 *
4139 * So we're pretty much stuck with copying data around multiple times.
4140 */
Elliott Hugheseac76672012-05-24 21:56:51 -07004141 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 -08004142 jint offset = env->GetIntField(chunk.get(), WellKnownClasses::org_apache_harmony_dalvik_ddmc_Chunk_offset);
Elliott Hugheseac76672012-05-24 21:56:51 -07004143 length = env->GetIntField(chunk.get(), WellKnownClasses::org_apache_harmony_dalvik_ddmc_Chunk_length);
Elliott Hugheseac76672012-05-24 21:56:51 -07004144 type = env->GetIntField(chunk.get(), WellKnownClasses::org_apache_harmony_dalvik_ddmc_Chunk_type);
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07004145
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08004146 VLOG(jdwp) << StringPrintf("DDM reply: type=0x%08x data=%p offset=%d length=%d", type, replyData.get(), offset, length);
Ian Rogersc0542af2014-09-03 16:16:56 -07004147 if (length == 0 || replyData.get() == nullptr) {
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07004148 return false;
4149 }
4150
Elliott Hughes4b9702c2013-02-20 18:13:24 -08004151 const int kChunkHdrLen = 8;
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07004152 uint8_t* reply = new uint8_t[length + kChunkHdrLen];
Ian Rogersc0542af2014-09-03 16:16:56 -07004153 if (reply == nullptr) {
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07004154 LOG(WARNING) << "malloc failed: " << (length + kChunkHdrLen);
4155 return false;
4156 }
Elliott Hughesf7c3b662011-10-27 12:04:56 -07004157 JDWP::Set4BE(reply + 0, type);
4158 JDWP::Set4BE(reply + 4, length);
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004159 env->GetByteArrayRegion(replyData.get(), offset, length, reinterpret_cast<jbyte*>(reply + kChunkHdrLen));
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07004160
4161 *pReplyBuf = reply;
4162 *pReplyLen = length + kChunkHdrLen;
4163
Elliott Hughes4b9702c2013-02-20 18:13:24 -08004164 VLOG(jdwp) << StringPrintf("dvmHandleDdm returning type=%.4s %p len=%d", reinterpret_cast<char*>(reply), reply, length);
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07004165 return true;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07004166}
4167
Elliott Hughesa2155262011-11-16 16:26:58 -08004168void Dbg::DdmBroadcast(bool connect) {
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08004169 VLOG(jdwp) << "Broadcasting DDM " << (connect ? "connect" : "disconnect") << "...";
Elliott Hughes47fce012011-10-25 18:37:19 -07004170
4171 Thread* self = Thread::Current();
Ian Rogers50b35e22012-10-04 10:09:15 -07004172 if (self->GetState() != kRunnable) {
4173 LOG(ERROR) << "DDM broadcast in thread state " << self->GetState();
4174 /* try anyway? */
Elliott Hughes47fce012011-10-25 18:37:19 -07004175 }
4176
4177 JNIEnv* env = self->GetJniEnv();
Elliott Hughes47fce012011-10-25 18:37:19 -07004178 jint event = connect ? 1 /*DdmServer.CONNECTED*/ : 2 /*DdmServer.DISCONNECTED*/;
Elliott Hugheseac76672012-05-24 21:56:51 -07004179 env->CallStaticVoidMethod(WellKnownClasses::org_apache_harmony_dalvik_ddmc_DdmServer,
4180 WellKnownClasses::org_apache_harmony_dalvik_ddmc_DdmServer_broadcast,
4181 event);
Elliott Hughes47fce012011-10-25 18:37:19 -07004182 if (env->ExceptionCheck()) {
4183 LOG(ERROR) << "DdmServer.broadcast " << event << " failed";
4184 env->ExceptionDescribe();
4185 env->ExceptionClear();
4186 }
4187}
4188
Elliott Hughes872d4ec2011-10-21 17:07:15 -07004189void Dbg::DdmConnected() {
Elliott Hughesa2155262011-11-16 16:26:58 -08004190 Dbg::DdmBroadcast(true);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07004191}
4192
4193void Dbg::DdmDisconnected() {
Elliott Hughesa2155262011-11-16 16:26:58 -08004194 Dbg::DdmBroadcast(false);
Elliott Hughes47fce012011-10-25 18:37:19 -07004195 gDdmThreadNotification = false;
4196}
4197
4198/*
Elliott Hughes82188472011-11-07 18:11:48 -08004199 * Send a notification when a thread starts, stops, or changes its name.
Elliott Hughes47fce012011-10-25 18:37:19 -07004200 *
4201 * Because we broadcast the full set of threads when the notifications are
4202 * first enabled, it's possible for "thread" to be actively executing.
4203 */
Elliott Hughes82188472011-11-07 18:11:48 -08004204void Dbg::DdmSendThreadNotification(Thread* t, uint32_t type) {
Elliott Hughes47fce012011-10-25 18:37:19 -07004205 if (!gDdmThreadNotification) {
4206 return;
4207 }
4208
Elliott Hughes82188472011-11-07 18:11:48 -08004209 if (type == CHUNK_TYPE("THDE")) {
Elliott Hughes47fce012011-10-25 18:37:19 -07004210 uint8_t buf[4];
Ian Rogersd9c4fc92013-10-01 19:45:43 -07004211 JDWP::Set4BE(&buf[0], t->GetThreadId());
Elliott Hughes47fce012011-10-25 18:37:19 -07004212 Dbg::DdmSendChunk(CHUNK_TYPE("THDE"), 4, buf);
Elliott Hughes82188472011-11-07 18:11:48 -08004213 } else {
4214 CHECK(type == CHUNK_TYPE("THCR") || type == CHUNK_TYPE("THNM")) << type;
Ian Rogers00f7d0e2012-07-19 15:28:27 -07004215 ScopedObjectAccessUnchecked soa(Thread::Current());
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004216 StackHandleScope<1> hs(soa.Self());
4217 Handle<mirror::String> name(hs.NewHandle(t->GetThreadName(soa)));
Ian Rogersc0542af2014-09-03 16:16:56 -07004218 size_t char_count = (name.Get() != nullptr) ? name->GetLength() : 0;
Jeff Hao848f70a2014-01-15 13:49:50 -08004219 const jchar* chars = (name.Get() != nullptr) ? name->GetValue() : nullptr;
Elliott Hughes82188472011-11-07 18:11:48 -08004220
Elliott Hughes21f32d72011-11-09 17:44:13 -08004221 std::vector<uint8_t> bytes;
Ian Rogersd9c4fc92013-10-01 19:45:43 -07004222 JDWP::Append4BE(bytes, t->GetThreadId());
Elliott Hughes545a0642011-11-08 19:10:03 -08004223 JDWP::AppendUtf16BE(bytes, chars, char_count);
Elliott Hughes21f32d72011-11-09 17:44:13 -08004224 CHECK_EQ(bytes.size(), char_count*2 + sizeof(uint32_t)*2);
4225 Dbg::DdmSendChunk(type, bytes);
Elliott Hughes47fce012011-10-25 18:37:19 -07004226 }
4227}
4228
Elliott Hughes47fce012011-10-25 18:37:19 -07004229void Dbg::DdmSetThreadNotification(bool enable) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07004230 // Enable/disable thread notifications.
Elliott Hughes47fce012011-10-25 18:37:19 -07004231 gDdmThreadNotification = enable;
4232 if (enable) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07004233 // Suspend the VM then post thread start notifications for all threads. Threads attaching will
4234 // see a suspension in progress and block until that ends. They then post their own start
4235 // notification.
4236 SuspendVM();
4237 std::list<Thread*> threads;
Ian Rogers50b35e22012-10-04 10:09:15 -07004238 Thread* self = Thread::Current();
Ian Rogers00f7d0e2012-07-19 15:28:27 -07004239 {
Ian Rogers50b35e22012-10-04 10:09:15 -07004240 MutexLock mu(self, *Locks::thread_list_lock_);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07004241 threads = Runtime::Current()->GetThreadList()->GetList();
4242 }
4243 {
Ian Rogers50b35e22012-10-04 10:09:15 -07004244 ScopedObjectAccess soa(self);
Mathieu Chartier02e25112013-08-14 16:14:24 -07004245 for (Thread* thread : threads) {
4246 Dbg::DdmSendThreadNotification(thread, CHUNK_TYPE("THCR"));
Ian Rogers00f7d0e2012-07-19 15:28:27 -07004247 }
4248 }
4249 ResumeVM();
Elliott Hughes47fce012011-10-25 18:37:19 -07004250 }
4251}
4252
Elliott Hughesa2155262011-11-16 16:26:58 -08004253void Dbg::PostThreadStartOrStop(Thread* t, uint32_t type) {
Elliott Hughesc0f09332012-03-26 13:27:06 -07004254 if (IsDebuggerActive()) {
Sebastien Hertz6995c602014-09-09 12:10:13 +02004255 gJdwpState->PostThreadChange(t, type == CHUNK_TYPE("THCR"));
Elliott Hughes47fce012011-10-25 18:37:19 -07004256 }
Elliott Hughes82188472011-11-07 18:11:48 -08004257 Dbg::DdmSendThreadNotification(t, type);
Elliott Hughes47fce012011-10-25 18:37:19 -07004258}
4259
4260void Dbg::PostThreadStart(Thread* t) {
Elliott Hughesa2155262011-11-16 16:26:58 -08004261 Dbg::PostThreadStartOrStop(t, CHUNK_TYPE("THCR"));
Elliott Hughes47fce012011-10-25 18:37:19 -07004262}
4263
4264void Dbg::PostThreadDeath(Thread* t) {
Elliott Hughesa2155262011-11-16 16:26:58 -08004265 Dbg::PostThreadStartOrStop(t, CHUNK_TYPE("THDE"));
Elliott Hughes872d4ec2011-10-21 17:07:15 -07004266}
4267
Elliott Hughes82188472011-11-07 18:11:48 -08004268void Dbg::DdmSendChunk(uint32_t type, size_t byte_count, const uint8_t* buf) {
Ian Rogersc0542af2014-09-03 16:16:56 -07004269 CHECK(buf != nullptr);
Elliott Hughes3bb81562011-10-21 18:52:59 -07004270 iovec vec[1];
4271 vec[0].iov_base = reinterpret_cast<void*>(const_cast<uint8_t*>(buf));
4272 vec[0].iov_len = byte_count;
4273 Dbg::DdmSendChunkV(type, vec, 1);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07004274}
4275
Elliott Hughes21f32d72011-11-09 17:44:13 -08004276void Dbg::DdmSendChunk(uint32_t type, const std::vector<uint8_t>& bytes) {
4277 DdmSendChunk(type, bytes.size(), &bytes[0]);
4278}
4279
Brian Carlstromf5293522013-07-19 00:24:00 -07004280void Dbg::DdmSendChunkV(uint32_t type, const iovec* iov, int iov_count) {
Ian Rogersc0542af2014-09-03 16:16:56 -07004281 if (gJdwpState == nullptr) {
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08004282 VLOG(jdwp) << "Debugger thread not active, ignoring DDM send: " << type;
Elliott Hughes3bb81562011-10-21 18:52:59 -07004283 } else {
Elliott Hughescccd84f2011-12-05 16:51:54 -08004284 gJdwpState->DdmSendChunkV(type, iov, iov_count);
Elliott Hughes3bb81562011-10-21 18:52:59 -07004285 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -07004286}
4287
Mathieu Chartierad466ad2015-01-08 16:28:08 -08004288JDWP::JdwpState* Dbg::GetJdwpState() {
4289 return gJdwpState;
4290}
4291
Elliott Hughes767a1472011-10-26 18:49:02 -07004292int Dbg::DdmHandleHpifChunk(HpifWhen when) {
4293 if (when == HPIF_WHEN_NOW) {
Elliott Hughes7162ad92011-10-27 14:08:42 -07004294 DdmSendHeapInfo(when);
Elliott Hughes767a1472011-10-26 18:49:02 -07004295 return true;
4296 }
4297
4298 if (when != HPIF_WHEN_NEVER && when != HPIF_WHEN_NEXT_GC && when != HPIF_WHEN_EVERY_GC) {
4299 LOG(ERROR) << "invalid HpifWhen value: " << static_cast<int>(when);
4300 return false;
4301 }
4302
4303 gDdmHpifWhen = when;
4304 return true;
4305}
4306
4307bool Dbg::DdmHandleHpsgNhsgChunk(Dbg::HpsgWhen when, Dbg::HpsgWhat what, bool native) {
4308 if (when != HPSG_WHEN_NEVER && when != HPSG_WHEN_EVERY_GC) {
4309 LOG(ERROR) << "invalid HpsgWhen value: " << static_cast<int>(when);
4310 return false;
4311 }
4312
4313 if (what != HPSG_WHAT_MERGED_OBJECTS && what != HPSG_WHAT_DISTINCT_OBJECTS) {
4314 LOG(ERROR) << "invalid HpsgWhat value: " << static_cast<int>(what);
4315 return false;
4316 }
4317
4318 if (native) {
4319 gDdmNhsgWhen = when;
4320 gDdmNhsgWhat = what;
4321 } else {
4322 gDdmHpsgWhen = when;
4323 gDdmHpsgWhat = what;
4324 }
4325 return true;
4326}
4327
Elliott Hughes7162ad92011-10-27 14:08:42 -07004328void Dbg::DdmSendHeapInfo(HpifWhen reason) {
4329 // If there's a one-shot 'when', reset it.
4330 if (reason == gDdmHpifWhen) {
4331 if (gDdmHpifWhen == HPIF_WHEN_NEXT_GC) {
4332 gDdmHpifWhen = HPIF_WHEN_NEVER;
4333 }
4334 }
4335
4336 /*
4337 * Chunk HPIF (client --> server)
4338 *
4339 * Heap Info. General information about the heap,
4340 * suitable for a summary display.
4341 *
4342 * [u4]: number of heaps
4343 *
4344 * For each heap:
4345 * [u4]: heap ID
4346 * [u8]: timestamp in ms since Unix epoch
4347 * [u1]: capture reason (same as 'when' value from server)
4348 * [u4]: max heap size in bytes (-Xmx)
4349 * [u4]: current heap size in bytes
4350 * [u4]: current number of bytes allocated
4351 * [u4]: current number of objects allocated
4352 */
4353 uint8_t heap_count = 1;
Ian Rogers1d54e732013-05-02 21:10:01 -07004354 gc::Heap* heap = Runtime::Current()->GetHeap();
Elliott Hughes21f32d72011-11-09 17:44:13 -08004355 std::vector<uint8_t> bytes;
Elliott Hughes545a0642011-11-08 19:10:03 -08004356 JDWP::Append4BE(bytes, heap_count);
Brian Carlstrom7934ac22013-07-26 10:54:15 -07004357 JDWP::Append4BE(bytes, 1); // Heap id (bogus; we only have one heap).
Elliott Hughes545a0642011-11-08 19:10:03 -08004358 JDWP::Append8BE(bytes, MilliTime());
4359 JDWP::Append1BE(bytes, reason);
Brian Carlstrom7934ac22013-07-26 10:54:15 -07004360 JDWP::Append4BE(bytes, heap->GetMaxMemory()); // Max allowed heap size in bytes.
4361 JDWP::Append4BE(bytes, heap->GetTotalMemory()); // Current heap size in bytes.
Elliott Hughesb3bd5f02012-03-08 21:05:27 -08004362 JDWP::Append4BE(bytes, heap->GetBytesAllocated());
4363 JDWP::Append4BE(bytes, heap->GetObjectsAllocated());
Elliott Hughes21f32d72011-11-09 17:44:13 -08004364 CHECK_EQ(bytes.size(), 4U + (heap_count * (4 + 8 + 1 + 4 + 4 + 4 + 4)));
4365 Dbg::DdmSendChunk(CHUNK_TYPE("HPIF"), bytes);
Elliott Hughes767a1472011-10-26 18:49:02 -07004366}
4367
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004368enum HpsgSolidity {
4369 SOLIDITY_FREE = 0,
4370 SOLIDITY_HARD = 1,
4371 SOLIDITY_SOFT = 2,
4372 SOLIDITY_WEAK = 3,
4373 SOLIDITY_PHANTOM = 4,
4374 SOLIDITY_FINALIZABLE = 5,
4375 SOLIDITY_SWEEP = 6,
4376};
4377
4378enum HpsgKind {
4379 KIND_OBJECT = 0,
4380 KIND_CLASS_OBJECT = 1,
4381 KIND_ARRAY_1 = 2,
4382 KIND_ARRAY_2 = 3,
4383 KIND_ARRAY_4 = 4,
4384 KIND_ARRAY_8 = 5,
4385 KIND_UNKNOWN = 6,
4386 KIND_NATIVE = 7,
4387};
4388
4389#define HPSG_PARTIAL (1<<7)
4390#define HPSG_STATE(solidity, kind) ((uint8_t)((((kind) & 0x7) << 3) | ((solidity) & 0x7)))
4391
Ian Rogers30fab402012-01-23 15:43:46 -08004392class HeapChunkContext {
4393 public:
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004394 // Maximum chunk size. Obtain this from the formula:
4395 // (((maximum_heap_size / ALLOCATION_UNIT_SIZE) + 255) / 256) * 2
4396 HeapChunkContext(bool merge, bool native)
Ian Rogers30fab402012-01-23 15:43:46 -08004397 : buf_(16384 - 16),
4398 type_(0),
Mathieu Chartier36dab362014-07-30 14:59:56 -07004399 chunk_overhead_(0) {
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004400 Reset();
4401 if (native) {
Ian Rogers30fab402012-01-23 15:43:46 -08004402 type_ = CHUNK_TYPE("NHSG");
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004403 } else {
Ian Rogers30fab402012-01-23 15:43:46 -08004404 type_ = merge ? CHUNK_TYPE("HPSG") : CHUNK_TYPE("HPSO");
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004405 }
4406 }
4407
4408 ~HeapChunkContext() {
Ian Rogers30fab402012-01-23 15:43:46 -08004409 if (p_ > &buf_[0]) {
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004410 Flush();
4411 }
4412 }
4413
Mathieu Chartier36dab362014-07-30 14:59:56 -07004414 void SetChunkOverhead(size_t chunk_overhead) {
4415 chunk_overhead_ = chunk_overhead;
4416 }
4417
4418 void ResetStartOfNextChunk() {
4419 startOfNextMemoryChunk_ = nullptr;
4420 }
4421
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004422 void EnsureHeader(const void* chunk_ptr) {
Ian Rogers30fab402012-01-23 15:43:46 -08004423 if (!needHeader_) {
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004424 return;
4425 }
4426
4427 // Start a new HPSx chunk.
Brian Carlstrom7934ac22013-07-26 10:54:15 -07004428 JDWP::Write4BE(&p_, 1); // Heap id (bogus; we only have one heap).
4429 JDWP::Write1BE(&p_, 8); // Size of allocation unit, in bytes.
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004430
Brian Carlstrom7934ac22013-07-26 10:54:15 -07004431 JDWP::Write4BE(&p_, reinterpret_cast<uintptr_t>(chunk_ptr)); // virtual address of segment start.
4432 JDWP::Write4BE(&p_, 0); // offset of this piece (relative to the virtual address).
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004433 // [u4]: length of piece, in allocation units
4434 // 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 -08004435 pieceLenField_ = p_;
4436 JDWP::Write4BE(&p_, 0x55555555);
4437 needHeader_ = false;
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004438 }
4439
Ian Rogersb726dcb2012-09-05 08:57:23 -07004440 void Flush() SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Ian Rogersc0542af2014-09-03 16:16:56 -07004441 if (pieceLenField_ == nullptr) {
Ian Rogersd636b062013-01-18 17:51:18 -08004442 // Flush immediately post Reset (maybe back-to-back Flush). Ignore.
4443 CHECK(needHeader_);
4444 return;
4445 }
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004446 // Patch the "length of piece" field.
Ian Rogers30fab402012-01-23 15:43:46 -08004447 CHECK_LE(&buf_[0], pieceLenField_);
4448 CHECK_LE(pieceLenField_, p_);
4449 JDWP::Set4BE(pieceLenField_, totalAllocationUnits_);
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004450
Ian Rogers30fab402012-01-23 15:43:46 -08004451 Dbg::DdmSendChunk(type_, p_ - &buf_[0], &buf_[0]);
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004452 Reset();
4453 }
4454
Mathieu Chartierbc689b72014-12-14 17:01:31 -08004455 static void HeapChunkJavaCallback(void* start, void* end, size_t used_bytes, void* arg)
Ian Rogersb726dcb2012-09-05 08:57:23 -07004456 SHARED_LOCKS_REQUIRED(Locks::heap_bitmap_lock_,
4457 Locks::mutator_lock_) {
Mathieu Chartierbc689b72014-12-14 17:01:31 -08004458 reinterpret_cast<HeapChunkContext*>(arg)->HeapChunkJavaCallback(start, end, used_bytes);
4459 }
4460
4461 static void HeapChunkNativeCallback(void* start, void* end, size_t used_bytes, void* arg)
4462 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
4463 reinterpret_cast<HeapChunkContext*>(arg)->HeapChunkNativeCallback(start, end, used_bytes);
Elliott Hughesa2155262011-11-16 16:26:58 -08004464 }
4465
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004466 private:
Elliott Hughesa2155262011-11-16 16:26:58 -08004467 enum { ALLOCATION_UNIT_SIZE = 8 };
4468
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004469 void Reset() {
Ian Rogers30fab402012-01-23 15:43:46 -08004470 p_ = &buf_[0];
Mathieu Chartier36dab362014-07-30 14:59:56 -07004471 ResetStartOfNextChunk();
Ian Rogers30fab402012-01-23 15:43:46 -08004472 totalAllocationUnits_ = 0;
4473 needHeader_ = true;
Ian Rogersc0542af2014-09-03 16:16:56 -07004474 pieceLenField_ = nullptr;
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004475 }
4476
Mathieu Chartierbc689b72014-12-14 17:01:31 -08004477 bool IsNative() const {
4478 return type_ == CHUNK_TYPE("NHSG");
4479 }
4480
4481 // Returns true if the object is not an empty chunk.
4482 bool ProcessRecord(void* start, size_t used_bytes) SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Ian Rogers30fab402012-01-23 15:43:46 -08004483 // Note: heap call backs cannot manipulate the heap upon which they are crawling, care is taken
4484 // in the following code not to allocate memory, by ensuring buf_ is of the correct size
Ian Rogers15bf2d32012-08-28 17:33:04 -07004485 if (used_bytes == 0) {
Mathieu Chartierbc689b72014-12-14 17:01:31 -08004486 if (start == nullptr) {
4487 // Reset for start of new heap.
4488 startOfNextMemoryChunk_ = nullptr;
4489 Flush();
4490 }
4491 // Only process in use memory so that free region information
4492 // also includes dlmalloc book keeping.
4493 return false;
Elliott Hughesa2155262011-11-16 16:26:58 -08004494 }
Ian Rogersc0542af2014-09-03 16:16:56 -07004495 if (startOfNextMemoryChunk_ != nullptr) {
Mathieu Chartierbc689b72014-12-14 17:01:31 -08004496 // Transmit any pending free memory. Native free memory of over kMaxFreeLen could be because
4497 // of the use of mmaps, so don't report. If not free memory then start a new segment.
4498 bool flush = true;
4499 if (start > startOfNextMemoryChunk_) {
4500 const size_t kMaxFreeLen = 2 * kPageSize;
4501 void* free_start = startOfNextMemoryChunk_;
4502 void* free_end = start;
4503 const size_t free_len =
4504 reinterpret_cast<uintptr_t>(free_end) - reinterpret_cast<uintptr_t>(free_start);
4505 if (!IsNative() || free_len < kMaxFreeLen) {
4506 AppendChunk(HPSG_STATE(SOLIDITY_FREE, 0), free_start, free_len, IsNative());
4507 flush = false;
Ian Rogers15bf2d32012-08-28 17:33:04 -07004508 }
Mathieu Chartierbc689b72014-12-14 17:01:31 -08004509 }
4510 if (flush) {
4511 startOfNextMemoryChunk_ = nullptr;
4512 Flush();
4513 }
Ian Rogers15bf2d32012-08-28 17:33:04 -07004514 }
Mathieu Chartierbc689b72014-12-14 17:01:31 -08004515 return true;
Ian Rogers15bf2d32012-08-28 17:33:04 -07004516 }
Elliott Hughesa2155262011-11-16 16:26:58 -08004517
Mathieu Chartierbc689b72014-12-14 17:01:31 -08004518 void HeapChunkNativeCallback(void* start, void* /*end*/, size_t used_bytes)
4519 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
4520 if (ProcessRecord(start, used_bytes)) {
4521 uint8_t state = ExamineNativeObject(start);
4522 AppendChunk(state, start, used_bytes + chunk_overhead_, true /*is_native*/);
4523 startOfNextMemoryChunk_ = reinterpret_cast<char*>(start) + used_bytes + chunk_overhead_;
4524 }
4525 }
4526
4527 void HeapChunkJavaCallback(void* start, void* /*end*/, size_t used_bytes)
4528 SHARED_LOCKS_REQUIRED(Locks::heap_bitmap_lock_, Locks::mutator_lock_) {
4529 if (ProcessRecord(start, used_bytes)) {
4530 // Determine the type of this chunk.
4531 // OLD-TODO: if context.merge, see if this chunk is different from the last chunk.
4532 // If it's the same, we should combine them.
4533 uint8_t state = ExamineJavaObject(reinterpret_cast<mirror::Object*>(start));
4534 AppendChunk(state, start, used_bytes + chunk_overhead_, false /*is_native*/);
4535 startOfNextMemoryChunk_ = reinterpret_cast<char*>(start) + used_bytes + chunk_overhead_;
4536 }
4537 }
4538
4539 void AppendChunk(uint8_t state, void* ptr, size_t length, bool is_native)
Ian Rogersb726dcb2012-09-05 08:57:23 -07004540 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Ian Rogers15bf2d32012-08-28 17:33:04 -07004541 // Make sure there's enough room left in the buffer.
4542 // We need to use two bytes for every fractional 256 allocation units used by the chunk plus
4543 // 17 bytes for any header.
Mathieu Chartierbc689b72014-12-14 17:01:31 -08004544 const size_t needed = ((RoundUp(length / ALLOCATION_UNIT_SIZE, 256) / 256) * 2) + 17;
4545 size_t byte_left = &buf_.back() - p_;
4546 if (byte_left < needed) {
4547 if (is_native) {
Pavel Vyssotski7522c742014-12-08 13:38:26 +06004548 // Cannot trigger memory allocation while walking native heap.
Pavel Vyssotski7522c742014-12-08 13:38:26 +06004549 return;
4550 }
Ian Rogers15bf2d32012-08-28 17:33:04 -07004551 Flush();
4552 }
4553
Mathieu Chartierbc689b72014-12-14 17:01:31 -08004554 byte_left = &buf_.back() - p_;
4555 if (byte_left < needed) {
Ian Rogers15bf2d32012-08-28 17:33:04 -07004556 LOG(WARNING) << "Chunk is too big to transmit (chunk_len=" << length << ", "
4557 << needed << " bytes)";
4558 return;
4559 }
4560 EnsureHeader(ptr);
Elliott Hughesa2155262011-11-16 16:26:58 -08004561 // Write out the chunk description.
Ian Rogers15bf2d32012-08-28 17:33:04 -07004562 length /= ALLOCATION_UNIT_SIZE; // Convert to allocation units.
4563 totalAllocationUnits_ += length;
4564 while (length > 256) {
Ian Rogers30fab402012-01-23 15:43:46 -08004565 *p_++ = state | HPSG_PARTIAL;
4566 *p_++ = 255; // length - 1
Ian Rogers15bf2d32012-08-28 17:33:04 -07004567 length -= 256;
Elliott Hughesa2155262011-11-16 16:26:58 -08004568 }
Ian Rogers30fab402012-01-23 15:43:46 -08004569 *p_++ = state;
Ian Rogers15bf2d32012-08-28 17:33:04 -07004570 *p_++ = length - 1;
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004571 }
4572
Mathieu Chartierbc689b72014-12-14 17:01:31 -08004573 uint8_t ExamineNativeObject(const void* p) SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
4574 return p == nullptr ? HPSG_STATE(SOLIDITY_FREE, 0) : HPSG_STATE(SOLIDITY_HARD, KIND_NATIVE);
4575 }
4576
4577 uint8_t ExamineJavaObject(mirror::Object* o)
Ian Rogersef7d42f2014-01-06 12:55:46 -08004578 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_, Locks::heap_bitmap_lock_) {
Ian Rogersc0542af2014-09-03 16:16:56 -07004579 if (o == nullptr) {
Elliott Hughesa2155262011-11-16 16:26:58 -08004580 return HPSG_STATE(SOLIDITY_FREE, 0);
4581 }
Elliott Hughesa2155262011-11-16 16:26:58 -08004582 // It's an allocated chunk. Figure out what it is.
Mathieu Chartierbc689b72014-12-14 17:01:31 -08004583 gc::Heap* heap = Runtime::Current()->GetHeap();
4584 if (!heap->IsLiveObjectLocked(o)) {
4585 LOG(ERROR) << "Invalid object in managed heap: " << o;
Elliott Hughesa2155262011-11-16 16:26:58 -08004586 return HPSG_STATE(SOLIDITY_HARD, KIND_NATIVE);
4587 }
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08004588 mirror::Class* c = o->GetClass();
Ian Rogersc0542af2014-09-03 16:16:56 -07004589 if (c == nullptr) {
Elliott Hughesa2155262011-11-16 16:26:58 -08004590 // The object was probably just created but hasn't been initialized yet.
4591 return HPSG_STATE(SOLIDITY_HARD, KIND_OBJECT);
4592 }
Mathieu Chartierbc689b72014-12-14 17:01:31 -08004593 if (!heap->IsValidObjectAddress(c)) {
Ian Rogers15bf2d32012-08-28 17:33:04 -07004594 LOG(ERROR) << "Invalid class for managed heap object: " << o << " " << c;
Elliott Hughesa2155262011-11-16 16:26:58 -08004595 return HPSG_STATE(SOLIDITY_HARD, KIND_UNKNOWN);
4596 }
Mathieu Chartierf26e1b32015-01-29 10:47:10 -08004597 if (c->GetClass() == nullptr) {
4598 LOG(ERROR) << "Null class of class " << c << " for object " << o;
4599 return HPSG_STATE(SOLIDITY_HARD, KIND_UNKNOWN);
4600 }
Elliott Hughesa2155262011-11-16 16:26:58 -08004601 if (c->IsClassClass()) {
4602 return HPSG_STATE(SOLIDITY_HARD, KIND_CLASS_OBJECT);
4603 }
Elliott Hughesa2155262011-11-16 16:26:58 -08004604 if (c->IsArrayClass()) {
Elliott Hughesa2155262011-11-16 16:26:58 -08004605 switch (c->GetComponentSize()) {
4606 case 1: return HPSG_STATE(SOLIDITY_HARD, KIND_ARRAY_1);
4607 case 2: return HPSG_STATE(SOLIDITY_HARD, KIND_ARRAY_2);
4608 case 4: return HPSG_STATE(SOLIDITY_HARD, KIND_ARRAY_4);
4609 case 8: return HPSG_STATE(SOLIDITY_HARD, KIND_ARRAY_8);
4610 }
4611 }
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004612 return HPSG_STATE(SOLIDITY_HARD, KIND_OBJECT);
4613 }
4614
Ian Rogers30fab402012-01-23 15:43:46 -08004615 std::vector<uint8_t> buf_;
4616 uint8_t* p_;
4617 uint8_t* pieceLenField_;
Ian Rogers15bf2d32012-08-28 17:33:04 -07004618 void* startOfNextMemoryChunk_;
Ian Rogers30fab402012-01-23 15:43:46 -08004619 size_t totalAllocationUnits_;
4620 uint32_t type_;
Ian Rogers30fab402012-01-23 15:43:46 -08004621 bool needHeader_;
Mathieu Chartier36dab362014-07-30 14:59:56 -07004622 size_t chunk_overhead_;
Ian Rogers30fab402012-01-23 15:43:46 -08004623
Elliott Hughesa2155262011-11-16 16:26:58 -08004624 DISALLOW_COPY_AND_ASSIGN(HeapChunkContext);
4625};
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004626
Mathieu Chartier36dab362014-07-30 14:59:56 -07004627static void BumpPointerSpaceCallback(mirror::Object* obj, void* arg)
4628 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) EXCLUSIVE_LOCKS_REQUIRED(Locks::heap_bitmap_lock_) {
4629 const size_t size = RoundUp(obj->SizeOf(), kObjectAlignment);
Mathieu Chartierbc689b72014-12-14 17:01:31 -08004630 HeapChunkContext::HeapChunkJavaCallback(
Mathieu Chartier36dab362014-07-30 14:59:56 -07004631 obj, reinterpret_cast<void*>(reinterpret_cast<uintptr_t>(obj) + size), size, arg);
4632}
4633
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004634void Dbg::DdmSendHeapSegments(bool native) {
Mathieu Chartierbc689b72014-12-14 17:01:31 -08004635 Dbg::HpsgWhen when = native ? gDdmNhsgWhen : gDdmHpsgWhen;
4636 Dbg::HpsgWhat what = native ? gDdmNhsgWhat : gDdmHpsgWhat;
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004637 if (when == HPSG_WHEN_NEVER) {
4638 return;
4639 }
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004640 // Figure out what kind of chunks we'll be sending.
Mathieu Chartierbc689b72014-12-14 17:01:31 -08004641 CHECK(what == HPSG_WHAT_MERGED_OBJECTS || what == HPSG_WHAT_DISTINCT_OBJECTS)
4642 << static_cast<int>(what);
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004643
4644 // First, send a heap start chunk.
4645 uint8_t heap_id[4];
Brian Carlstrom7934ac22013-07-26 10:54:15 -07004646 JDWP::Set4BE(&heap_id[0], 1); // Heap id (bogus; we only have one heap).
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004647 Dbg::DdmSendChunk(native ? CHUNK_TYPE("NHST") : CHUNK_TYPE("HPST"), sizeof(heap_id), heap_id);
Hiroshi Yamauchicf58d4a2013-09-26 14:21:22 -07004648 Thread* self = Thread::Current();
Hiroshi Yamauchicf58d4a2013-09-26 14:21:22 -07004649 Locks::mutator_lock_->AssertSharedHeld(self);
Hiroshi Yamauchicf58d4a2013-09-26 14:21:22 -07004650
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004651 // Send a series of heap segment chunks.
Mathieu Chartierbc689b72014-12-14 17:01:31 -08004652 HeapChunkContext context(what == HPSG_WHAT_MERGED_OBJECTS, native);
Elliott Hughesa2155262011-11-16 16:26:58 -08004653 if (native) {
Ian Rogers872dd822014-10-30 11:19:14 -07004654#if defined(HAVE_ANDROID_OS) && defined(USE_DLMALLOC)
Mathieu Chartierbc689b72014-12-14 17:01:31 -08004655 dlmalloc_inspect_all(HeapChunkContext::HeapChunkNativeCallback, &context);
4656 HeapChunkContext::HeapChunkNativeCallback(nullptr, nullptr, 0, &context); // Indicate end of a space.
Christopher Ferrisc4ddc042014-05-13 14:47:50 -07004657#else
4658 UNIMPLEMENTED(WARNING) << "Native heap inspection is only supported with dlmalloc";
4659#endif
Elliott Hughesa2155262011-11-16 16:26:58 -08004660 } else {
Ian Rogers1d54e732013-05-02 21:10:01 -07004661 gc::Heap* heap = Runtime::Current()->GetHeap();
Mathieu Chartier36dab362014-07-30 14:59:56 -07004662 for (const auto& space : heap->GetContinuousSpaces()) {
4663 if (space->IsDlMallocSpace()) {
Mathieu Chartier4c69d7f2014-10-10 12:45:50 -07004664 ReaderMutexLock mu(self, *Locks::heap_bitmap_lock_);
Mathieu Chartier36dab362014-07-30 14:59:56 -07004665 // dlmalloc's chunk header is 2 * sizeof(size_t), but if the previous chunk is in use for an
4666 // allocation then the first sizeof(size_t) may belong to it.
4667 context.SetChunkOverhead(sizeof(size_t));
Mathieu Chartierbc689b72014-12-14 17:01:31 -08004668 space->AsDlMallocSpace()->Walk(HeapChunkContext::HeapChunkJavaCallback, &context);
Mathieu Chartier36dab362014-07-30 14:59:56 -07004669 } else if (space->IsRosAllocSpace()) {
4670 context.SetChunkOverhead(0);
Mathieu Chartier4c69d7f2014-10-10 12:45:50 -07004671 // Need to acquire the mutator lock before the heap bitmap lock with exclusive access since
4672 // RosAlloc's internal logic doesn't know to release and reacquire the heap bitmap lock.
4673 self->TransitionFromRunnableToSuspended(kSuspended);
4674 ThreadList* tl = Runtime::Current()->GetThreadList();
Mathieu Chartierbf9fc582015-03-13 17:21:25 -07004675 tl->SuspendAll(__FUNCTION__);
Mathieu Chartier4c69d7f2014-10-10 12:45:50 -07004676 {
4677 ReaderMutexLock mu(self, *Locks::heap_bitmap_lock_);
Mathieu Chartierbc689b72014-12-14 17:01:31 -08004678 space->AsRosAllocSpace()->Walk(HeapChunkContext::HeapChunkJavaCallback, &context);
Mathieu Chartier4c69d7f2014-10-10 12:45:50 -07004679 }
4680 tl->ResumeAll();
4681 self->TransitionFromSuspendedToRunnable();
Mathieu Chartier36dab362014-07-30 14:59:56 -07004682 } else if (space->IsBumpPointerSpace()) {
Mathieu Chartier4c69d7f2014-10-10 12:45:50 -07004683 ReaderMutexLock mu(self, *Locks::heap_bitmap_lock_);
Mathieu Chartier36dab362014-07-30 14:59:56 -07004684 context.SetChunkOverhead(0);
Mathieu Chartier36dab362014-07-30 14:59:56 -07004685 space->AsBumpPointerSpace()->Walk(BumpPointerSpaceCallback, &context);
Mathieu Chartierbc689b72014-12-14 17:01:31 -08004686 HeapChunkContext::HeapChunkJavaCallback(nullptr, nullptr, 0, &context);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08004687 } else if (space->IsRegionSpace()) {
4688 heap->IncrementDisableMovingGC(self);
4689 self->TransitionFromRunnableToSuspended(kSuspended);
4690 ThreadList* tl = Runtime::Current()->GetThreadList();
Mathieu Chartierbf9fc582015-03-13 17:21:25 -07004691 tl->SuspendAll(__FUNCTION__);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08004692 ReaderMutexLock mu(self, *Locks::heap_bitmap_lock_);
4693 context.SetChunkOverhead(0);
4694 space->AsRegionSpace()->Walk(BumpPointerSpaceCallback, &context);
4695 HeapChunkContext::HeapChunkJavaCallback(nullptr, nullptr, 0, &context);
4696 tl->ResumeAll();
4697 self->TransitionFromSuspendedToRunnable();
4698 heap->DecrementDisableMovingGC(self);
Mathieu Chartier36dab362014-07-30 14:59:56 -07004699 } else {
4700 UNIMPLEMENTED(WARNING) << "Not counting objects in space " << *space;
Mathieu Chartierb062fdd2012-07-03 09:51:48 -07004701 }
Mathieu Chartier36dab362014-07-30 14:59:56 -07004702 context.ResetStartOfNextChunk();
Mathieu Chartierb062fdd2012-07-03 09:51:48 -07004703 }
Mathieu Chartier4c69d7f2014-10-10 12:45:50 -07004704 ReaderMutexLock mu(self, *Locks::heap_bitmap_lock_);
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -07004705 // Walk the large objects, these are not in the AllocSpace.
Mathieu Chartier36dab362014-07-30 14:59:56 -07004706 context.SetChunkOverhead(0);
Mathieu Chartierbc689b72014-12-14 17:01:31 -08004707 heap->GetLargeObjectsSpace()->Walk(HeapChunkContext::HeapChunkJavaCallback, &context);
Elliott Hughesa2155262011-11-16 16:26:58 -08004708 }
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004709
4710 // Finally, send a heap end chunk.
4711 Dbg::DdmSendChunk(native ? CHUNK_TYPE("NHEN") : CHUNK_TYPE("HPEN"), sizeof(heap_id), heap_id);
Elliott Hughes767a1472011-10-26 18:49:02 -07004712}
4713
Brian Carlstrom306db812014-09-05 13:01:41 -07004714void Dbg::SetAllocTrackingEnabled(bool enable) {
Man Cao8c2ff642015-05-27 17:25:30 -07004715 gc::AllocRecordObjectMap::SetAllocTrackingEnabled(enable);
Elliott Hughes545a0642011-11-08 19:10:03 -08004716}
4717
4718void Dbg::DumpRecentAllocations() {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07004719 ScopedObjectAccess soa(Thread::Current());
Brian Carlstrom306db812014-09-05 13:01:41 -07004720 MutexLock mu(soa.Self(), *Locks::alloc_tracker_lock_);
Man Cao8c2ff642015-05-27 17:25:30 -07004721 if (!Runtime::Current()->GetHeap()->IsAllocTrackingEnabled()) {
Elliott Hughes545a0642011-11-08 19:10:03 -08004722 LOG(INFO) << "Not recording tracked allocations";
4723 return;
4724 }
Man Cao8c2ff642015-05-27 17:25:30 -07004725 gc::AllocRecordObjectMap* records = Runtime::Current()->GetHeap()->GetAllocationRecords();
4726 CHECK(records != nullptr);
Elliott Hughes545a0642011-11-08 19:10:03 -08004727
Man Cao8c2ff642015-05-27 17:25:30 -07004728 const uint16_t capped_count = CappedAllocRecordCount(records->Size());
Brian Carlstrom306db812014-09-05 13:01:41 -07004729 uint16_t count = capped_count;
Elliott Hughes545a0642011-11-08 19:10:03 -08004730
Man Cao8c2ff642015-05-27 17:25:30 -07004731 LOG(INFO) << "Tracked allocations, (count=" << count << ")";
4732 for (auto it = records->RBegin(), end = records->REnd();
4733 count > 0 && it != end; count--, it++) {
4734 const gc::AllocRecord* record = it->second;
Elliott Hughes545a0642011-11-08 19:10:03 -08004735
Man Cao8c2ff642015-05-27 17:25:30 -07004736 LOG(INFO) << StringPrintf(" Thread %-2d %6zd bytes ", record->GetTid(), record->ByteCount())
4737 << PrettyClass(it->first.Read()->GetClass());
Elliott Hughes545a0642011-11-08 19:10:03 -08004738
Man Cao8c2ff642015-05-27 17:25:30 -07004739 for (size_t stack_frame = 0, depth = record->GetDepth(); stack_frame < depth; ++stack_frame) {
4740 const gc::AllocRecordStackTraceElement& stack_element = record->StackElement(stack_frame);
4741 ArtMethod* m = stack_element.GetMethod();
4742 LOG(INFO) << " " << PrettyMethod(m) << " line " << stack_element.ComputeLineNumber();
Elliott Hughes545a0642011-11-08 19:10:03 -08004743 }
4744
4745 // pause periodically to help logcat catch up
4746 if ((count % 5) == 0) {
4747 usleep(40000);
4748 }
Elliott Hughes545a0642011-11-08 19:10:03 -08004749 }
4750}
4751
4752class StringTable {
4753 public:
4754 StringTable() {
4755 }
4756
Mathieu Chartier4345c462014-06-27 10:20:14 -07004757 void Add(const std::string& str) {
4758 table_.insert(str);
4759 }
4760
4761 void Add(const char* str) {
4762 table_.insert(str);
Elliott Hughes545a0642011-11-08 19:10:03 -08004763 }
4764
Elliott Hughesa8f93cb2012-06-08 17:08:48 -07004765 size_t IndexOf(const char* s) const {
Mathieu Chartier02e25112013-08-14 16:14:24 -07004766 auto it = table_.find(s);
Elliott Hughesa8f93cb2012-06-08 17:08:48 -07004767 if (it == table_.end()) {
4768 LOG(FATAL) << "IndexOf(\"" << s << "\") failed";
4769 }
4770 return std::distance(table_.begin(), it);
Elliott Hughes545a0642011-11-08 19:10:03 -08004771 }
4772
Elliott Hughesa8f93cb2012-06-08 17:08:48 -07004773 size_t Size() const {
Elliott Hughes545a0642011-11-08 19:10:03 -08004774 return table_.size();
4775 }
4776
Elliott Hughesa8f93cb2012-06-08 17:08:48 -07004777 void WriteTo(std::vector<uint8_t>& bytes) const {
Mathieu Chartier02e25112013-08-14 16:14:24 -07004778 for (const std::string& str : table_) {
4779 const char* s = str.c_str();
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08004780 size_t s_len = CountModifiedUtf8Chars(s);
Christopher Ferris8a354052015-04-24 17:23:53 -07004781 std::unique_ptr<uint16_t[]> s_utf16(new uint16_t[s_len]);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08004782 ConvertModifiedUtf8ToUtf16(s_utf16.get(), s);
4783 JDWP::AppendUtf16BE(bytes, s_utf16.get(), s_len);
Elliott Hughes545a0642011-11-08 19:10:03 -08004784 }
4785 }
4786
4787 private:
Elliott Hughesa8f93cb2012-06-08 17:08:48 -07004788 std::set<std::string> table_;
Elliott Hughes545a0642011-11-08 19:10:03 -08004789 DISALLOW_COPY_AND_ASSIGN(StringTable);
4790};
4791
Mathieu Chartiere401d142015-04-22 13:56:20 -07004792static const char* GetMethodSourceFile(ArtMethod* method)
Sebastien Hertz280286a2014-04-28 09:26:50 +02004793 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07004794 DCHECK(method != nullptr);
4795 const char* source_file = method->GetDeclaringClassSourceFile();
Sebastien Hertz280286a2014-04-28 09:26:50 +02004796 return (source_file != nullptr) ? source_file : "";
4797}
4798
Elliott Hughes545a0642011-11-08 19:10:03 -08004799/*
4800 * The data we send to DDMS contains everything we have recorded.
4801 *
4802 * Message header (all values big-endian):
4803 * (1b) message header len (to allow future expansion); includes itself
4804 * (1b) entry header len
4805 * (1b) stack frame len
4806 * (2b) number of entries
4807 * (4b) offset to string table from start of message
4808 * (2b) number of class name strings
4809 * (2b) number of method name strings
4810 * (2b) number of source file name strings
4811 * For each entry:
4812 * (4b) total allocation size
Elliott Hughes221229c2013-01-08 18:17:50 -08004813 * (2b) thread id
Elliott Hughes545a0642011-11-08 19:10:03 -08004814 * (2b) allocated object's class name index
4815 * (1b) stack depth
4816 * For each stack frame:
4817 * (2b) method's class name
4818 * (2b) method name
4819 * (2b) method source file
4820 * (2b) line number, clipped to 32767; -2 if native; -1 if no source
4821 * (xb) class name strings
4822 * (xb) method name strings
4823 * (xb) source file strings
4824 *
4825 * As with other DDM traffic, strings are sent as a 4-byte length
4826 * followed by UTF-16 data.
4827 *
4828 * We send up 16-bit unsigned indexes into string tables. In theory there
Brian Carlstrom306db812014-09-05 13:01:41 -07004829 * can be (kMaxAllocRecordStackDepth * alloc_record_max_) unique strings in
Elliott Hughes545a0642011-11-08 19:10:03 -08004830 * each table, but in practice there should be far fewer.
4831 *
4832 * The chief reason for using a string table here is to keep the size of
4833 * the DDMS message to a minimum. This is partly to make the protocol
4834 * efficient, but also because we have to form the whole thing up all at
4835 * once in a memory buffer.
4836 *
4837 * We use separate string tables for class names, method names, and source
4838 * files to keep the indexes small. There will generally be no overlap
4839 * between the contents of these tables.
4840 */
4841jbyteArray Dbg::GetRecentAllocations() {
Ian Rogerscf7f1912014-10-22 22:06:39 -07004842 if ((false)) {
Elliott Hughes545a0642011-11-08 19:10:03 -08004843 DumpRecentAllocations();
4844 }
4845
Ian Rogers50b35e22012-10-04 10:09:15 -07004846 Thread* self = Thread::Current();
Elliott Hughes545a0642011-11-08 19:10:03 -08004847 std::vector<uint8_t> bytes;
Mathieu Chartier46e811b2013-07-10 17:09:14 -07004848 {
Brian Carlstrom306db812014-09-05 13:01:41 -07004849 MutexLock mu(self, *Locks::alloc_tracker_lock_);
Man Cao8c2ff642015-05-27 17:25:30 -07004850 gc::AllocRecordObjectMap* records = Runtime::Current()->GetHeap()->GetAllocationRecords();
4851 // In case this method is called when allocation tracker is disabled,
4852 // we should still send some data back.
4853 gc::AllocRecordObjectMap dummy;
4854 if (records == nullptr) {
4855 CHECK(!Runtime::Current()->GetHeap()->IsAllocTrackingEnabled());
4856 records = &dummy;
4857 }
4858
Mathieu Chartier46e811b2013-07-10 17:09:14 -07004859 //
4860 // Part 1: generate string tables.
4861 //
4862 StringTable class_names;
4863 StringTable method_names;
4864 StringTable filenames;
Elliott Hughes545a0642011-11-08 19:10:03 -08004865
Man Cao8c2ff642015-05-27 17:25:30 -07004866 const uint16_t capped_count = CappedAllocRecordCount(records->Size());
Brian Carlstrom306db812014-09-05 13:01:41 -07004867 uint16_t count = capped_count;
Man Cao8c2ff642015-05-27 17:25:30 -07004868 for (auto it = records->RBegin(), end = records->REnd();
4869 count > 0 && it != end; count--, it++) {
4870 const gc::AllocRecord* record = it->second;
Ian Rogers1ff3c982014-08-12 02:30:58 -07004871 std::string temp;
Man Cao8c2ff642015-05-27 17:25:30 -07004872 class_names.Add(it->first.Read()->GetClass()->GetDescriptor(&temp));
4873 for (size_t i = 0, depth = record->GetDepth(); i < depth; i++) {
4874 ArtMethod* m = record->StackElement(i).GetMethod();
4875 class_names.Add(m->GetDeclaringClassDescriptor());
4876 method_names.Add(m->GetName());
4877 filenames.Add(GetMethodSourceFile(m));
Mathieu Chartier46e811b2013-07-10 17:09:14 -07004878 }
Elliott Hughes545a0642011-11-08 19:10:03 -08004879 }
4880
Man Cao8c2ff642015-05-27 17:25:30 -07004881 LOG(INFO) << "recent allocation records: " << capped_count;
4882 LOG(INFO) << "allocation records all objects: " << records->Size();
Mathieu Chartier46e811b2013-07-10 17:09:14 -07004883
4884 //
4885 // Part 2: Generate the output and store it in the buffer.
4886 //
4887
4888 // (1b) message header len (to allow future expansion); includes itself
4889 // (1b) entry header len
4890 // (1b) stack frame len
4891 const int kMessageHeaderLen = 15;
4892 const int kEntryHeaderLen = 9;
4893 const int kStackFrameLen = 8;
4894 JDWP::Append1BE(bytes, kMessageHeaderLen);
4895 JDWP::Append1BE(bytes, kEntryHeaderLen);
4896 JDWP::Append1BE(bytes, kStackFrameLen);
4897
4898 // (2b) number of entries
4899 // (4b) offset to string table from start of message
4900 // (2b) number of class name strings
4901 // (2b) number of method name strings
4902 // (2b) number of source file name strings
Brian Carlstrom306db812014-09-05 13:01:41 -07004903 JDWP::Append2BE(bytes, capped_count);
Mathieu Chartier46e811b2013-07-10 17:09:14 -07004904 size_t string_table_offset = bytes.size();
Brian Carlstrom7934ac22013-07-26 10:54:15 -07004905 JDWP::Append4BE(bytes, 0); // We'll patch this later...
Mathieu Chartier46e811b2013-07-10 17:09:14 -07004906 JDWP::Append2BE(bytes, class_names.Size());
4907 JDWP::Append2BE(bytes, method_names.Size());
4908 JDWP::Append2BE(bytes, filenames.Size());
4909
Ian Rogers1ff3c982014-08-12 02:30:58 -07004910 std::string temp;
Man Cao8c2ff642015-05-27 17:25:30 -07004911 count = capped_count;
4912 // The last "count" number of allocation records in "records" are the most recent "count" number
4913 // of allocations. Reverse iterate to get them. The most recent allocation is sent first.
4914 for (auto it = records->RBegin(), end = records->REnd();
4915 count > 0 && it != end; count--, it++) {
Mathieu Chartier46e811b2013-07-10 17:09:14 -07004916 // For each entry:
4917 // (4b) total allocation size
4918 // (2b) thread id
4919 // (2b) allocated object's class name index
4920 // (1b) stack depth
Man Cao8c2ff642015-05-27 17:25:30 -07004921 const gc::AllocRecord* record = it->second;
Mathieu Chartier46e811b2013-07-10 17:09:14 -07004922 size_t stack_depth = record->GetDepth();
Mathieu Chartierf8322842014-05-16 10:59:25 -07004923 size_t allocated_object_class_name_index =
Man Cao8c2ff642015-05-27 17:25:30 -07004924 class_names.IndexOf(it->first.Read()->GetClass()->GetDescriptor(&temp));
Hiroshi Yamauchib5a9e3d2014-06-09 12:11:20 -07004925 JDWP::Append4BE(bytes, record->ByteCount());
Man Cao8c2ff642015-05-27 17:25:30 -07004926 JDWP::Append2BE(bytes, static_cast<uint16_t>(record->GetTid()));
Mathieu Chartier46e811b2013-07-10 17:09:14 -07004927 JDWP::Append2BE(bytes, allocated_object_class_name_index);
4928 JDWP::Append1BE(bytes, stack_depth);
4929
Mathieu Chartier46e811b2013-07-10 17:09:14 -07004930 for (size_t stack_frame = 0; stack_frame < stack_depth; ++stack_frame) {
4931 // For each stack frame:
4932 // (2b) method's class name
4933 // (2b) method name
4934 // (2b) method source file
4935 // (2b) line number, clipped to 32767; -2 if native; -1 if no source
Man Cao8c2ff642015-05-27 17:25:30 -07004936 ArtMethod* m = record->StackElement(stack_frame).GetMethod();
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07004937 size_t class_name_index = class_names.IndexOf(m->GetDeclaringClassDescriptor());
4938 size_t method_name_index = method_names.IndexOf(m->GetName());
4939 size_t file_name_index = filenames.IndexOf(GetMethodSourceFile(m));
Mathieu Chartier46e811b2013-07-10 17:09:14 -07004940 JDWP::Append2BE(bytes, class_name_index);
4941 JDWP::Append2BE(bytes, method_name_index);
4942 JDWP::Append2BE(bytes, file_name_index);
Man Cao8c2ff642015-05-27 17:25:30 -07004943 JDWP::Append2BE(bytes, record->StackElement(stack_frame).ComputeLineNumber());
Mathieu Chartier46e811b2013-07-10 17:09:14 -07004944 }
Mathieu Chartier46e811b2013-07-10 17:09:14 -07004945 }
4946
4947 // (xb) class name strings
4948 // (xb) method name strings
4949 // (xb) source file strings
4950 JDWP::Set4BE(&bytes[string_table_offset], bytes.size());
4951 class_names.WriteTo(bytes);
4952 method_names.WriteTo(bytes);
4953 filenames.WriteTo(bytes);
Elliott Hughes545a0642011-11-08 19:10:03 -08004954 }
Ian Rogers50b35e22012-10-04 10:09:15 -07004955 JNIEnv* env = self->GetJniEnv();
Elliott Hughes545a0642011-11-08 19:10:03 -08004956 jbyteArray result = env->NewByteArray(bytes.size());
Ian Rogersc0542af2014-09-03 16:16:56 -07004957 if (result != nullptr) {
Elliott Hughes545a0642011-11-08 19:10:03 -08004958 env->SetByteArrayRegion(result, 0, bytes.size(), reinterpret_cast<const jbyte*>(&bytes[0]));
4959 }
4960 return result;
4961}
4962
Mathieu Chartiere401d142015-04-22 13:56:20 -07004963ArtMethod* DeoptimizationRequest::Method() const {
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07004964 ScopedObjectAccessUnchecked soa(Thread::Current());
4965 return soa.DecodeMethod(method_);
4966}
4967
Mathieu Chartiere401d142015-04-22 13:56:20 -07004968void DeoptimizationRequest::SetMethod(ArtMethod* m) {
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07004969 ScopedObjectAccessUnchecked soa(Thread::Current());
4970 method_ = soa.EncodeMethod(m);
4971}
4972
Elliott Hughes872d4ec2011-10-21 17:07:15 -07004973} // namespace art