blob: 8afb96856b4510a59f3945000928078040724b26 [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
Elliott Hughes872d4ec2011-10-21 17:07:15 -070057namespace art {
58
Sebastien Hertz0462c4c2015-04-01 16:34:17 +020059// The key identifying the debugger to update instrumentation.
60static constexpr const char* kDbgInstrumentationKey = "Debugger";
61
Man Cao8c2ff642015-05-27 17:25:30 -070062// 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 -070063static uint16_t CappedAllocRecordCount(size_t alloc_record_count) {
Man Cao1ed11b92015-06-11 22:47:35 -070064 const size_t cap = 0xffff;
Man Cao8c2ff642015-05-27 17:25:30 -070065 if (alloc_record_count > cap) {
66 return cap;
Brian Carlstrom306db812014-09-05 13:01:41 -070067 }
68 return alloc_record_count;
69}
Elliott Hughes475fc232011-10-25 15:00:35 -070070
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -070071class Breakpoint {
72 public:
Mathieu Chartiere401d142015-04-22 13:56:20 -070073 Breakpoint(ArtMethod* method, uint32_t dex_pc,
Sebastien Hertzf3928792014-11-17 19:00:37 +010074 DeoptimizationRequest::Kind deoptimization_kind)
Mathieu Chartier90443472015-07-16 20:32:27 -070075 SHARED_REQUIRES(Locks::mutator_lock_)
Sebastien Hertzf3928792014-11-17 19:00:37 +010076 : method_(nullptr), dex_pc_(dex_pc), deoptimization_kind_(deoptimization_kind) {
77 CHECK(deoptimization_kind_ == DeoptimizationRequest::kNothing ||
78 deoptimization_kind_ == DeoptimizationRequest::kSelectiveDeoptimization ||
79 deoptimization_kind_ == DeoptimizationRequest::kFullDeoptimization);
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -070080 ScopedObjectAccessUnchecked soa(Thread::Current());
81 method_ = soa.EncodeMethod(method);
82 }
83
Mathieu Chartier90443472015-07-16 20:32:27 -070084 Breakpoint(const Breakpoint& other) SHARED_REQUIRES(Locks::mutator_lock_)
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -070085 : method_(nullptr), dex_pc_(other.dex_pc_),
Sebastien Hertzf3928792014-11-17 19:00:37 +010086 deoptimization_kind_(other.deoptimization_kind_) {
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -070087 ScopedObjectAccessUnchecked soa(Thread::Current());
88 method_ = soa.EncodeMethod(other.Method());
89 }
90
Mathieu Chartier90443472015-07-16 20:32:27 -070091 ArtMethod* Method() const SHARED_REQUIRES(Locks::mutator_lock_) {
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -070092 ScopedObjectAccessUnchecked soa(Thread::Current());
93 return soa.DecodeMethod(method_);
94 }
95
96 uint32_t DexPc() const {
97 return dex_pc_;
98 }
99
Sebastien Hertzf3928792014-11-17 19:00:37 +0100100 DeoptimizationRequest::Kind GetDeoptimizationKind() const {
101 return deoptimization_kind_;
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -0700102 }
103
104 private:
Sebastien Hertza76a6d42014-03-20 16:40:17 +0100105 // The location of this breakpoint.
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -0700106 jmethodID method_;
107 uint32_t dex_pc_;
Sebastien Hertza76a6d42014-03-20 16:40:17 +0100108
109 // Indicates whether breakpoint needs full deoptimization or selective deoptimization.
Sebastien Hertzf3928792014-11-17 19:00:37 +0100110 DeoptimizationRequest::Kind deoptimization_kind_;
Elliott Hughes86964332012-02-15 19:37:42 -0800111};
112
Sebastien Hertzed2be172014-08-19 15:33:43 +0200113static std::ostream& operator<<(std::ostream& os, const Breakpoint& rhs)
Mathieu Chartier90443472015-07-16 20:32:27 -0700114 SHARED_REQUIRES(Locks::mutator_lock_) {
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -0700115 os << StringPrintf("Breakpoint[%s @%#x]", PrettyMethod(rhs.Method()).c_str(), rhs.DexPc());
Elliott Hughes86964332012-02-15 19:37:42 -0800116 return os;
117}
118
Sebastien Hertz3f52eaf2014-04-04 17:50:18 +0200119class DebugInstrumentationListener FINAL : public instrumentation::InstrumentationListener {
Ian Rogers62d6c772013-02-27 08:32:07 -0800120 public:
121 DebugInstrumentationListener() {}
122 virtual ~DebugInstrumentationListener() {}
123
Mathieu Chartiere401d142015-04-22 13:56:20 -0700124 void MethodEntered(Thread* thread, mirror::Object* this_object, ArtMethod* method,
Sebastien Hertz9d6bf692015-04-10 12:12:33 +0200125 uint32_t dex_pc)
Mathieu Chartier90443472015-07-16 20:32:27 -0700126 OVERRIDE SHARED_REQUIRES(Locks::mutator_lock_) {
Ian Rogers62d6c772013-02-27 08:32:07 -0800127 if (method->IsNative()) {
128 // TODO: post location events is a suspension point and native method entry stubs aren't.
129 return;
130 }
Sebastien Hertz9d6bf692015-04-10 12:12:33 +0200131 if (IsListeningToDexPcMoved()) {
132 // We also listen to kDexPcMoved instrumentation event so we know the DexPcMoved method is
133 // going to be called right after us. To avoid sending JDWP events twice for this location,
134 // we report the event in DexPcMoved. However, we must remind this is method entry so we
135 // send the METHOD_ENTRY event. And we can also group it with other events for this location
136 // like BREAKPOINT or SINGLE_STEP (or even METHOD_EXIT if this is a RETURN instruction).
137 thread->SetDebugMethodEntry();
138 } else if (IsListeningToMethodExit() && IsReturn(method, dex_pc)) {
139 // We also listen to kMethodExited instrumentation event and the current instruction is a
140 // RETURN so we know the MethodExited method is going to be called right after us. To avoid
141 // sending JDWP events twice for this location, we report the event(s) in MethodExited.
142 // However, we must remind this is method entry so we send the METHOD_ENTRY event. And we can
143 // also group it with other events for this location like BREAKPOINT or SINGLE_STEP.
144 thread->SetDebugMethodEntry();
145 } else {
146 Dbg::UpdateDebugger(thread, this_object, method, 0, Dbg::kMethodEntry, nullptr);
147 }
Ian Rogers62d6c772013-02-27 08:32:07 -0800148 }
149
Mathieu Chartiere401d142015-04-22 13:56:20 -0700150 void MethodExited(Thread* thread, mirror::Object* this_object, ArtMethod* method,
Sebastien Hertz3f52eaf2014-04-04 17:50:18 +0200151 uint32_t dex_pc, const JValue& return_value)
Mathieu Chartier90443472015-07-16 20:32:27 -0700152 OVERRIDE SHARED_REQUIRES(Locks::mutator_lock_) {
Ian Rogers62d6c772013-02-27 08:32:07 -0800153 if (method->IsNative()) {
154 // TODO: post location events is a suspension point and native method entry stubs aren't.
155 return;
156 }
Sebastien Hertz9d6bf692015-04-10 12:12:33 +0200157 uint32_t events = Dbg::kMethodExit;
158 if (thread->IsDebugMethodEntry()) {
159 // It is also the method entry.
160 DCHECK(IsReturn(method, dex_pc));
161 events |= Dbg::kMethodEntry;
162 thread->ClearDebugMethodEntry();
163 }
164 Dbg::UpdateDebugger(thread, this_object, method, dex_pc, events, &return_value);
Ian Rogers62d6c772013-02-27 08:32:07 -0800165 }
166
Sebastien Hertz9d6bf692015-04-10 12:12:33 +0200167 void MethodUnwind(Thread* thread ATTRIBUTE_UNUSED, mirror::Object* this_object ATTRIBUTE_UNUSED,
Mathieu Chartiere401d142015-04-22 13:56:20 -0700168 ArtMethod* method, uint32_t dex_pc)
Mathieu Chartier90443472015-07-16 20:32:27 -0700169 OVERRIDE SHARED_REQUIRES(Locks::mutator_lock_) {
Ian Rogers62d6c772013-02-27 08:32:07 -0800170 // We're not recorded to listen to this kind of event, so complain.
171 LOG(ERROR) << "Unexpected method unwind event in debugger " << PrettyMethod(method)
Sebastien Hertz51db44a2013-11-19 10:00:29 +0100172 << " " << dex_pc;
Ian Rogers62d6c772013-02-27 08:32:07 -0800173 }
174
Mathieu Chartiere401d142015-04-22 13:56:20 -0700175 void DexPcMoved(Thread* thread, mirror::Object* this_object, ArtMethod* method,
Sebastien Hertz3f52eaf2014-04-04 17:50:18 +0200176 uint32_t new_dex_pc)
Mathieu Chartier90443472015-07-16 20:32:27 -0700177 OVERRIDE SHARED_REQUIRES(Locks::mutator_lock_) {
Sebastien Hertz9d6bf692015-04-10 12:12:33 +0200178 if (IsListeningToMethodExit() && IsReturn(method, new_dex_pc)) {
179 // We also listen to kMethodExited instrumentation event and the current instruction is a
180 // RETURN so we know the MethodExited method is going to be called right after us. Like in
181 // MethodEntered, we delegate event reporting to MethodExited.
182 // Besides, if this RETURN instruction is the only one in the method, we can send multiple
183 // JDWP events in the same packet: METHOD_ENTRY, METHOD_EXIT, BREAKPOINT and/or SINGLE_STEP.
184 // Therefore, we must not clear the debug method entry flag here.
185 } else {
186 uint32_t events = 0;
187 if (thread->IsDebugMethodEntry()) {
188 // It is also the method entry.
189 events = Dbg::kMethodEntry;
190 thread->ClearDebugMethodEntry();
191 }
192 Dbg::UpdateDebugger(thread, this_object, method, new_dex_pc, events, nullptr);
193 }
Ian Rogers62d6c772013-02-27 08:32:07 -0800194 }
195
Sebastien Hertz9d6bf692015-04-10 12:12:33 +0200196 void FieldRead(Thread* thread ATTRIBUTE_UNUSED, mirror::Object* this_object,
Mathieu Chartiere401d142015-04-22 13:56:20 -0700197 ArtMethod* method, uint32_t dex_pc, ArtField* field)
Mathieu Chartier90443472015-07-16 20:32:27 -0700198 OVERRIDE SHARED_REQUIRES(Locks::mutator_lock_) {
Sebastien Hertz3f52eaf2014-04-04 17:50:18 +0200199 Dbg::PostFieldAccessEvent(method, dex_pc, this_object, field);
Ian Rogers62d6c772013-02-27 08:32:07 -0800200 }
Sebastien Hertz3f52eaf2014-04-04 17:50:18 +0200201
Ian Rogers6a3c1fc2014-10-31 00:33:20 -0700202 void FieldWritten(Thread* thread ATTRIBUTE_UNUSED, mirror::Object* this_object,
Mathieu Chartiere401d142015-04-22 13:56:20 -0700203 ArtMethod* method, uint32_t dex_pc, ArtField* field,
Ian Rogers6a3c1fc2014-10-31 00:33:20 -0700204 const JValue& field_value)
Mathieu Chartier90443472015-07-16 20:32:27 -0700205 OVERRIDE SHARED_REQUIRES(Locks::mutator_lock_) {
Sebastien Hertz3f52eaf2014-04-04 17:50:18 +0200206 Dbg::PostFieldModificationEvent(method, dex_pc, this_object, field, &field_value);
207 }
208
Nicolas Geoffray14691c52015-03-05 10:40:17 +0000209 void ExceptionCaught(Thread* thread ATTRIBUTE_UNUSED, mirror::Throwable* exception_object)
Mathieu Chartier90443472015-07-16 20:32:27 -0700210 OVERRIDE SHARED_REQUIRES(Locks::mutator_lock_) {
Nicolas Geoffray14691c52015-03-05 10:40:17 +0000211 Dbg::PostException(exception_object);
Sebastien Hertz3f52eaf2014-04-04 17:50:18 +0200212 }
213
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800214 // We only care about how many backward branches were executed in the Jit.
Mathieu Chartiere401d142015-04-22 13:56:20 -0700215 void BackwardBranch(Thread* /*thread*/, ArtMethod* method, int32_t dex_pc_offset)
Mathieu Chartier90443472015-07-16 20:32:27 -0700216 OVERRIDE SHARED_REQUIRES(Locks::mutator_lock_) {
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800217 LOG(ERROR) << "Unexpected backward branch event in debugger " << PrettyMethod(method)
218 << " " << dex_pc_offset;
219 }
220
Sebastien Hertz3f52eaf2014-04-04 17:50:18 +0200221 private:
Mathieu Chartiere401d142015-04-22 13:56:20 -0700222 static bool IsReturn(ArtMethod* method, uint32_t dex_pc)
Mathieu Chartier90443472015-07-16 20:32:27 -0700223 SHARED_REQUIRES(Locks::mutator_lock_) {
Sebastien Hertz9d6bf692015-04-10 12:12:33 +0200224 const DexFile::CodeItem* code_item = method->GetCodeItem();
225 const Instruction* instruction = Instruction::At(&code_item->insns_[dex_pc]);
226 return instruction->IsReturn();
227 }
228
Mathieu Chartier90443472015-07-16 20:32:27 -0700229 static bool IsListeningToDexPcMoved() SHARED_REQUIRES(Locks::mutator_lock_) {
Sebastien Hertz9d6bf692015-04-10 12:12:33 +0200230 return IsListeningTo(instrumentation::Instrumentation::kDexPcMoved);
231 }
232
Mathieu Chartier90443472015-07-16 20:32:27 -0700233 static bool IsListeningToMethodExit() SHARED_REQUIRES(Locks::mutator_lock_) {
Sebastien Hertz9d6bf692015-04-10 12:12:33 +0200234 return IsListeningTo(instrumentation::Instrumentation::kMethodExited);
235 }
236
237 static bool IsListeningTo(instrumentation::Instrumentation::InstrumentationEvent event)
Mathieu Chartier90443472015-07-16 20:32:27 -0700238 SHARED_REQUIRES(Locks::mutator_lock_) {
Sebastien Hertz9d6bf692015-04-10 12:12:33 +0200239 return (Dbg::GetInstrumentationEvents() & event) != 0;
240 }
241
Sebastien Hertz3f52eaf2014-04-04 17:50:18 +0200242 DISALLOW_COPY_AND_ASSIGN(DebugInstrumentationListener);
Ian Rogers62d6c772013-02-27 08:32:07 -0800243} gDebugInstrumentationListener;
244
Elliott Hughes4ffd3132011-10-24 12:06:42 -0700245// JDWP is allowed unless the Zygote forbids it.
246static bool gJdwpAllowed = true;
247
Elliott Hughesc0f09332012-03-26 13:27:06 -0700248// Was there a -Xrunjdwp or -agentlib:jdwp= argument on the command line?
Elliott Hughes3bb81562011-10-21 18:52:59 -0700249static bool gJdwpConfigured = false;
250
Sebastien Hertzb3b173b2015-02-06 09:16:32 +0100251// JDWP options for debugging. Only valid if IsJdwpConfigured() is true.
252static JDWP::JdwpOptions gJdwpOptions;
253
Elliott Hughes3bb81562011-10-21 18:52:59 -0700254// Runtime JDWP state.
Ian Rogersc0542af2014-09-03 16:16:56 -0700255static JDWP::JdwpState* gJdwpState = nullptr;
Elliott Hughes3bb81562011-10-21 18:52:59 -0700256static bool gDebuggerConnected; // debugger or DDMS is connected.
Elliott Hughes3bb81562011-10-21 18:52:59 -0700257
Elliott Hughes47fce012011-10-25 18:37:19 -0700258static bool gDdmThreadNotification = false;
259
Elliott Hughes767a1472011-10-26 18:49:02 -0700260// DDMS GC-related settings.
261static Dbg::HpifWhen gDdmHpifWhen = Dbg::HPIF_WHEN_NEVER;
262static Dbg::HpsgWhen gDdmHpsgWhen = Dbg::HPSG_WHEN_NEVER;
263static Dbg::HpsgWhat gDdmHpsgWhat;
264static Dbg::HpsgWhen gDdmNhsgWhen = Dbg::HPSG_WHEN_NEVER;
265static Dbg::HpsgWhat gDdmNhsgWhat;
266
Daniel Mihalyieb076692014-08-22 17:33:31 +0200267bool Dbg::gDebuggerActive = false;
Sebastien Hertz4e5b2082015-03-24 19:03:40 +0100268bool Dbg::gDisposed = false;
Sebastien Hertz6995c602014-09-09 12:10:13 +0200269ObjectRegistry* Dbg::gRegistry = nullptr;
Elliott Hughes475fc232011-10-25 15:00:35 -0700270
Sebastien Hertz138dbfc2013-12-04 18:15:25 +0100271// Deoptimization support.
Sebastien Hertz4d25df32014-03-21 17:44:46 +0100272std::vector<DeoptimizationRequest> Dbg::deoptimization_requests_;
273size_t Dbg::full_deoptimization_event_count_ = 0;
Sebastien Hertz138dbfc2013-12-04 18:15:25 +0100274
Sebastien Hertz42cd43f2014-05-13 14:15:41 +0200275// Instrumentation event reference counters.
276size_t Dbg::dex_pc_change_event_ref_count_ = 0;
277size_t Dbg::method_enter_event_ref_count_ = 0;
278size_t Dbg::method_exit_event_ref_count_ = 0;
279size_t Dbg::field_read_event_ref_count_ = 0;
280size_t Dbg::field_write_event_ref_count_ = 0;
281size_t Dbg::exception_catch_event_ref_count_ = 0;
282uint32_t Dbg::instrumentation_events_ = 0;
283
Sebastien Hertz138dbfc2013-12-04 18:15:25 +0100284// Breakpoints.
jeffhao09bfc6a2012-12-11 18:11:43 -0800285static std::vector<Breakpoint> gBreakpoints GUARDED_BY(Locks::breakpoint_lock_);
Elliott Hughes86964332012-02-15 19:37:42 -0800286
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -0700287void DebugInvokeReq::VisitRoots(RootVisitor* visitor, const RootInfo& root_info) {
288 receiver.VisitRootIfNonNull(visitor, root_info); // null for static method call.
289 klass.VisitRoot(visitor, root_info);
Mathieu Chartier3b05e9b2014-03-25 09:29:43 -0700290}
291
Sebastien Hertz597c4f02015-01-26 17:37:14 +0100292void SingleStepControl::AddDexPc(uint32_t dex_pc) {
293 dex_pcs_.insert(dex_pc);
Sebastien Hertzbb43b432014-04-14 11:59:08 +0200294}
295
Sebastien Hertz597c4f02015-01-26 17:37:14 +0100296bool SingleStepControl::ContainsDexPc(uint32_t dex_pc) const {
297 return dex_pcs_.find(dex_pc) == dex_pcs_.end();
Sebastien Hertzbb43b432014-04-14 11:59:08 +0200298}
299
Mathieu Chartiere401d142015-04-22 13:56:20 -0700300static bool IsBreakpoint(const ArtMethod* m, uint32_t dex_pc)
Mathieu Chartier90443472015-07-16 20:32:27 -0700301 REQUIRES(!Locks::breakpoint_lock_)
302 SHARED_REQUIRES(Locks::mutator_lock_) {
Sebastien Hertzed2be172014-08-19 15:33:43 +0200303 ReaderMutexLock mu(Thread::Current(), *Locks::breakpoint_lock_);
Sebastien Hertz138dbfc2013-12-04 18:15:25 +0100304 for (size_t i = 0, e = gBreakpoints.size(); i < e; ++i) {
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -0700305 if (gBreakpoints[i].DexPc() == dex_pc && gBreakpoints[i].Method() == m) {
Elliott Hughes86964332012-02-15 19:37:42 -0800306 VLOG(jdwp) << "Hit breakpoint #" << i << ": " << gBreakpoints[i];
307 return true;
308 }
309 }
310 return false;
311}
312
Sebastien Hertz52d131d2014-03-13 16:17:40 +0100313static bool IsSuspendedForDebugger(ScopedObjectAccessUnchecked& soa, Thread* thread)
Mathieu Chartier90443472015-07-16 20:32:27 -0700314 REQUIRES(!Locks::thread_suspend_count_lock_) {
Elliott Hughes9e0c1752013-01-09 14:02:58 -0800315 MutexLock mu(soa.Self(), *Locks::thread_suspend_count_lock_);
316 // A thread may be suspended for GC; in this code, we really want to know whether
317 // there's a debugger suspension active.
318 return thread->IsSuspended() && thread->GetDebugSuspendCount() > 0;
319}
320
Ian Rogersc0542af2014-09-03 16:16:56 -0700321static mirror::Array* DecodeNonNullArray(JDWP::RefTypeId id, JDWP::JdwpError* error)
Mathieu Chartier90443472015-07-16 20:32:27 -0700322 SHARED_REQUIRES(Locks::mutator_lock_) {
Sebastien Hertz6995c602014-09-09 12:10:13 +0200323 mirror::Object* o = Dbg::GetObjectRegistry()->Get<mirror::Object*>(id, error);
Ian Rogersc0542af2014-09-03 16:16:56 -0700324 if (o == nullptr) {
325 *error = JDWP::ERR_INVALID_OBJECT;
326 return nullptr;
Elliott Hughes436e3722012-02-17 20:01:47 -0800327 }
328 if (!o->IsArrayInstance()) {
Ian Rogersc0542af2014-09-03 16:16:56 -0700329 *error = JDWP::ERR_INVALID_ARRAY;
330 return nullptr;
Elliott Hughes436e3722012-02-17 20:01:47 -0800331 }
Ian Rogersc0542af2014-09-03 16:16:56 -0700332 *error = JDWP::ERR_NONE;
Elliott Hughes436e3722012-02-17 20:01:47 -0800333 return o->AsArray();
334}
335
Ian Rogersc0542af2014-09-03 16:16:56 -0700336static mirror::Class* DecodeClass(JDWP::RefTypeId id, JDWP::JdwpError* error)
Mathieu Chartier90443472015-07-16 20:32:27 -0700337 SHARED_REQUIRES(Locks::mutator_lock_) {
Sebastien Hertz6995c602014-09-09 12:10:13 +0200338 mirror::Object* o = Dbg::GetObjectRegistry()->Get<mirror::Object*>(id, error);
Ian Rogersc0542af2014-09-03 16:16:56 -0700339 if (o == nullptr) {
340 *error = JDWP::ERR_INVALID_OBJECT;
341 return nullptr;
Elliott Hughes436e3722012-02-17 20:01:47 -0800342 }
343 if (!o->IsClass()) {
Ian Rogersc0542af2014-09-03 16:16:56 -0700344 *error = JDWP::ERR_INVALID_CLASS;
345 return nullptr;
Elliott Hughes436e3722012-02-17 20:01:47 -0800346 }
Ian Rogersc0542af2014-09-03 16:16:56 -0700347 *error = JDWP::ERR_NONE;
Elliott Hughes436e3722012-02-17 20:01:47 -0800348 return o->AsClass();
349}
350
Ian Rogersc0542af2014-09-03 16:16:56 -0700351static Thread* DecodeThread(ScopedObjectAccessUnchecked& soa, JDWP::ObjectId thread_id,
352 JDWP::JdwpError* error)
Mathieu Chartier90443472015-07-16 20:32:27 -0700353 SHARED_REQUIRES(Locks::mutator_lock_)
354 REQUIRES(!Locks::thread_list_lock_, !Locks::thread_suspend_count_lock_) {
Sebastien Hertz6995c602014-09-09 12:10:13 +0200355 mirror::Object* thread_peer = Dbg::GetObjectRegistry()->Get<mirror::Object*>(thread_id, error);
Ian Rogersc0542af2014-09-03 16:16:56 -0700356 if (thread_peer == nullptr) {
Elliott Hughes221229c2013-01-08 18:17:50 -0800357 // This isn't even an object.
Ian Rogersc0542af2014-09-03 16:16:56 -0700358 *error = JDWP::ERR_INVALID_OBJECT;
359 return nullptr;
Elliott Hughes436e3722012-02-17 20:01:47 -0800360 }
Elliott Hughes221229c2013-01-08 18:17:50 -0800361
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800362 mirror::Class* java_lang_Thread = soa.Decode<mirror::Class*>(WellKnownClasses::java_lang_Thread);
Elliott Hughes221229c2013-01-08 18:17:50 -0800363 if (!java_lang_Thread->IsAssignableFrom(thread_peer->GetClass())) {
364 // This isn't a thread.
Ian Rogersc0542af2014-09-03 16:16:56 -0700365 *error = JDWP::ERR_INVALID_THREAD;
366 return nullptr;
Elliott Hughes221229c2013-01-08 18:17:50 -0800367 }
368
Sebastien Hertz69206392015-04-07 15:54:25 +0200369 MutexLock mu(soa.Self(), *Locks::thread_list_lock_);
Ian Rogersc0542af2014-09-03 16:16:56 -0700370 Thread* thread = Thread::FromManagedThread(soa, thread_peer);
371 // If thread is null then this a java.lang.Thread without a Thread*. Must be a un-started or a
372 // zombie.
373 *error = (thread == nullptr) ? JDWP::ERR_THREAD_NOT_ALIVE : JDWP::ERR_NONE;
374 return thread;
Elliott Hughes436e3722012-02-17 20:01:47 -0800375}
376
Elliott Hughes24437992011-11-30 14:49:33 -0800377static JDWP::JdwpTag BasicTagFromDescriptor(const char* descriptor) {
378 // JDWP deliberately uses the descriptor characters' ASCII values for its enum.
379 // Note that by "basic" we mean that we don't get more specific than JT_OBJECT.
380 return static_cast<JDWP::JdwpTag>(descriptor[0]);
381}
382
Ian Rogers1ff3c982014-08-12 02:30:58 -0700383static JDWP::JdwpTag BasicTagFromClass(mirror::Class* klass)
Mathieu Chartier90443472015-07-16 20:32:27 -0700384 SHARED_REQUIRES(Locks::mutator_lock_) {
Ian Rogers1ff3c982014-08-12 02:30:58 -0700385 std::string temp;
386 const char* descriptor = klass->GetDescriptor(&temp);
387 return BasicTagFromDescriptor(descriptor);
388}
389
Ian Rogers98379392014-02-24 16:53:16 -0800390static JDWP::JdwpTag TagFromClass(const ScopedObjectAccessUnchecked& soa, mirror::Class* c)
Mathieu Chartier90443472015-07-16 20:32:27 -0700391 SHARED_REQUIRES(Locks::mutator_lock_) {
Ian Rogersc0542af2014-09-03 16:16:56 -0700392 CHECK(c != nullptr);
Elliott Hughes24437992011-11-30 14:49:33 -0800393 if (c->IsArrayClass()) {
394 return JDWP::JT_ARRAY;
395 }
Elliott Hughes24437992011-11-30 14:49:33 -0800396 if (c->IsStringClass()) {
397 return JDWP::JT_STRING;
Elliott Hughes24437992011-11-30 14:49:33 -0800398 }
Ian Rogers98379392014-02-24 16:53:16 -0800399 if (c->IsClassClass()) {
400 return JDWP::JT_CLASS_OBJECT;
401 }
402 {
403 mirror::Class* thread_class = soa.Decode<mirror::Class*>(WellKnownClasses::java_lang_Thread);
404 if (thread_class->IsAssignableFrom(c)) {
405 return JDWP::JT_THREAD;
406 }
407 }
408 {
409 mirror::Class* thread_group_class =
410 soa.Decode<mirror::Class*>(WellKnownClasses::java_lang_ThreadGroup);
411 if (thread_group_class->IsAssignableFrom(c)) {
412 return JDWP::JT_THREAD_GROUP;
413 }
414 }
415 {
416 mirror::Class* class_loader_class =
417 soa.Decode<mirror::Class*>(WellKnownClasses::java_lang_ClassLoader);
418 if (class_loader_class->IsAssignableFrom(c)) {
419 return JDWP::JT_CLASS_LOADER;
420 }
421 }
422 return JDWP::JT_OBJECT;
Elliott Hughes24437992011-11-30 14:49:33 -0800423}
424
425/*
426 * Objects declared to hold Object might actually hold a more specific
427 * type. The debugger may take a special interest in these (e.g. it
428 * wants to display the contents of Strings), so we want to return an
429 * appropriate tag.
430 *
431 * Null objects are tagged JT_OBJECT.
432 */
Sebastien Hertz6995c602014-09-09 12:10:13 +0200433JDWP::JdwpTag Dbg::TagFromObject(const ScopedObjectAccessUnchecked& soa, mirror::Object* o) {
Ian Rogersc0542af2014-09-03 16:16:56 -0700434 return (o == nullptr) ? JDWP::JT_OBJECT : TagFromClass(soa, o->GetClass());
Elliott Hughes24437992011-11-30 14:49:33 -0800435}
436
437static bool IsPrimitiveTag(JDWP::JdwpTag tag) {
438 switch (tag) {
439 case JDWP::JT_BOOLEAN:
440 case JDWP::JT_BYTE:
441 case JDWP::JT_CHAR:
442 case JDWP::JT_FLOAT:
443 case JDWP::JT_DOUBLE:
444 case JDWP::JT_INT:
445 case JDWP::JT_LONG:
446 case JDWP::JT_SHORT:
447 case JDWP::JT_VOID:
448 return true;
449 default:
450 return false;
451 }
452}
453
Sebastien Hertzb3b173b2015-02-06 09:16:32 +0100454void Dbg::StartJdwp() {
Elliott Hughesc0f09332012-03-26 13:27:06 -0700455 if (!gJdwpAllowed || !IsJdwpConfigured()) {
Elliott Hughes376a7a02011-10-24 18:35:55 -0700456 // No JDWP for you!
457 return;
458 }
459
Ian Rogers719d1a32014-03-06 12:13:39 -0800460 CHECK(gRegistry == nullptr);
Elliott Hughes475fc232011-10-25 15:00:35 -0700461 gRegistry = new ObjectRegistry;
462
Elliott Hughesd1cc8362011-10-24 16:58:50 -0700463 // Init JDWP if the debugger is enabled. This may connect out to a
464 // debugger, passively listen for a debugger, or block waiting for a
465 // debugger.
Sebastien Hertzb3b173b2015-02-06 09:16:32 +0100466 gJdwpState = JDWP::JdwpState::Create(&gJdwpOptions);
Ian Rogersc0542af2014-09-03 16:16:56 -0700467 if (gJdwpState == nullptr) {
Elliott Hughesf8a2df72011-12-01 12:19:54 -0800468 // We probably failed because some other process has the port already, which means that
469 // if we don't abort the user is likely to think they're talking to us when they're actually
470 // talking to that other process.
Elliott Hughes3d30d9b2011-12-07 17:35:48 -0800471 LOG(FATAL) << "Debugger thread failed to initialize";
Elliott Hughesd1cc8362011-10-24 16:58:50 -0700472 }
473
474 // If a debugger has already attached, send the "welcome" message.
475 // This may cause us to suspend all threads.
Elliott Hughes376a7a02011-10-24 18:35:55 -0700476 if (gJdwpState->IsActive()) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700477 ScopedObjectAccess soa(Thread::Current());
Sebastien Hertz7d955652014-10-22 10:57:10 +0200478 gJdwpState->PostVMStart();
Elliott Hughesd1cc8362011-10-24 16:58:50 -0700479 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700480}
481
Elliott Hughesd1cc8362011-10-24 16:58:50 -0700482void Dbg::StopJdwp() {
Sebastien Hertzc6345ef2014-08-18 19:26:39 +0200483 // Post VM_DEATH event before the JDWP connection is closed (either by the JDWP thread or the
484 // destruction of gJdwpState).
485 if (gJdwpState != nullptr && gJdwpState->IsActive()) {
486 gJdwpState->PostVMDeath();
487 }
Sebastien Hertz0376e6b2014-02-06 18:12:59 +0100488 // Prevent the JDWP thread from processing JDWP incoming packets after we close the connection.
Sebastien Hertz4e5b2082015-03-24 19:03:40 +0100489 Dispose();
Elliott Hughes376a7a02011-10-24 18:35:55 -0700490 delete gJdwpState;
Ian Rogers719d1a32014-03-06 12:13:39 -0800491 gJdwpState = nullptr;
Elliott Hughes475fc232011-10-25 15:00:35 -0700492 delete gRegistry;
Ian Rogers719d1a32014-03-06 12:13:39 -0800493 gRegistry = nullptr;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700494}
495
Elliott Hughes767a1472011-10-26 18:49:02 -0700496void Dbg::GcDidFinish() {
497 if (gDdmHpifWhen != HPIF_WHEN_NEVER) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700498 ScopedObjectAccess soa(Thread::Current());
Brian Carlstrom4d466a82014-05-08 19:05:29 -0700499 VLOG(jdwp) << "Sending heap info to DDM";
Elliott Hughes7162ad92011-10-27 14:08:42 -0700500 DdmSendHeapInfo(gDdmHpifWhen);
Elliott Hughes767a1472011-10-26 18:49:02 -0700501 }
502 if (gDdmHpsgWhen != HPSG_WHEN_NEVER) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700503 ScopedObjectAccess soa(Thread::Current());
Brian Carlstrom4d466a82014-05-08 19:05:29 -0700504 VLOG(jdwp) << "Dumping heap to DDM";
Elliott Hughes6a5bd492011-10-28 14:33:57 -0700505 DdmSendHeapSegments(false);
Elliott Hughes767a1472011-10-26 18:49:02 -0700506 }
507 if (gDdmNhsgWhen != HPSG_WHEN_NEVER) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700508 ScopedObjectAccess soa(Thread::Current());
Brian Carlstrom4d466a82014-05-08 19:05:29 -0700509 VLOG(jdwp) << "Dumping native heap to DDM";
Elliott Hughes6a5bd492011-10-28 14:33:57 -0700510 DdmSendHeapSegments(true);
Elliott Hughes767a1472011-10-26 18:49:02 -0700511 }
512}
513
Elliott Hughes4ffd3132011-10-24 12:06:42 -0700514void Dbg::SetJdwpAllowed(bool allowed) {
515 gJdwpAllowed = allowed;
516}
517
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700518DebugInvokeReq* Dbg::GetInvokeReq() {
Elliott Hughes475fc232011-10-25 15:00:35 -0700519 return Thread::Current()->GetInvokeReq();
520}
521
522Thread* Dbg::GetDebugThread() {
Ian Rogersc0542af2014-09-03 16:16:56 -0700523 return (gJdwpState != nullptr) ? gJdwpState->GetDebugThread() : nullptr;
Elliott Hughes475fc232011-10-25 15:00:35 -0700524}
525
526void Dbg::ClearWaitForEventThread() {
Sebastien Hertz2bf93f42015-01-09 18:44:05 +0100527 gJdwpState->ReleaseJdwpTokenForEvent();
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700528}
529
530void Dbg::Connected() {
Elliott Hughes3bb81562011-10-21 18:52:59 -0700531 CHECK(!gDebuggerConnected);
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -0800532 VLOG(jdwp) << "JDWP has attached";
Elliott Hughes3bb81562011-10-21 18:52:59 -0700533 gDebuggerConnected = true;
Elliott Hughes86964332012-02-15 19:37:42 -0800534 gDisposed = false;
535}
536
Sebastien Hertzf3928792014-11-17 19:00:37 +0100537bool Dbg::RequiresDeoptimization() {
538 // We don't need deoptimization if everything runs with interpreter after
539 // enabling -Xint mode.
540 return !Runtime::Current()->GetInstrumentation()->IsForcedInterpretOnly();
541}
542
Elliott Hughesa2155262011-11-16 16:26:58 -0800543void Dbg::GoActive() {
544 // Enable all debugging features, including scans for breakpoints.
545 // This is a no-op if we're already active.
546 // Only called from the JDWP handler thread.
Daniel Mihalyieb076692014-08-22 17:33:31 +0200547 if (IsDebuggerActive()) {
Elliott Hughesa2155262011-11-16 16:26:58 -0800548 return;
549 }
550
Elliott Hughesc0f09332012-03-26 13:27:06 -0700551 {
552 // TODO: dalvik only warned if there were breakpoints left over. clear in Dbg::Disconnected?
Sebastien Hertzed2be172014-08-19 15:33:43 +0200553 ReaderMutexLock mu(Thread::Current(), *Locks::breakpoint_lock_);
Elliott Hughesc0f09332012-03-26 13:27:06 -0700554 CHECK_EQ(gBreakpoints.size(), 0U);
555 }
Elliott Hughesa2155262011-11-16 16:26:58 -0800556
Sebastien Hertz138dbfc2013-12-04 18:15:25 +0100557 {
Brian Carlstrom306db812014-09-05 13:01:41 -0700558 MutexLock mu(Thread::Current(), *Locks::deoptimization_lock_);
Sebastien Hertz4d25df32014-03-21 17:44:46 +0100559 CHECK_EQ(deoptimization_requests_.size(), 0U);
560 CHECK_EQ(full_deoptimization_event_count_, 0U);
Sebastien Hertz42cd43f2014-05-13 14:15:41 +0200561 CHECK_EQ(dex_pc_change_event_ref_count_, 0U);
562 CHECK_EQ(method_enter_event_ref_count_, 0U);
563 CHECK_EQ(method_exit_event_ref_count_, 0U);
564 CHECK_EQ(field_read_event_ref_count_, 0U);
565 CHECK_EQ(field_write_event_ref_count_, 0U);
566 CHECK_EQ(exception_catch_event_ref_count_, 0U);
Sebastien Hertz138dbfc2013-12-04 18:15:25 +0100567 }
568
Ian Rogers62d6c772013-02-27 08:32:07 -0800569 Runtime* runtime = Runtime::Current();
Mathieu Chartierbf9fc582015-03-13 17:21:25 -0700570 runtime->GetThreadList()->SuspendAll(__FUNCTION__);
Ian Rogers62d6c772013-02-27 08:32:07 -0800571 Thread* self = Thread::Current();
572 ThreadState old_state = self->SetStateUnsafe(kRunnable);
573 CHECK_NE(old_state, kRunnable);
Sebastien Hertzf3928792014-11-17 19:00:37 +0100574 if (RequiresDeoptimization()) {
575 runtime->GetInstrumentation()->EnableDeoptimization();
576 }
Sebastien Hertz42cd43f2014-05-13 14:15:41 +0200577 instrumentation_events_ = 0;
Elliott Hughesa2155262011-11-16 16:26:58 -0800578 gDebuggerActive = true;
Ian Rogers62d6c772013-02-27 08:32:07 -0800579 CHECK_EQ(self->SetStateUnsafe(old_state), kRunnable);
580 runtime->GetThreadList()->ResumeAll();
581
582 LOG(INFO) << "Debugger is active";
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700583}
584
585void Dbg::Disconnected() {
Elliott Hughes234ab152011-10-26 14:02:26 -0700586 CHECK(gDebuggerConnected);
587
Elliott Hughesc0f09332012-03-26 13:27:06 -0700588 LOG(INFO) << "Debugger is no longer active";
Elliott Hughes234ab152011-10-26 14:02:26 -0700589
Ian Rogers62d6c772013-02-27 08:32:07 -0800590 // Suspend all threads and exclusively acquire the mutator lock. Set the state of the thread
591 // to kRunnable to avoid scoped object access transitions. Remove the debugger as a listener
592 // and clear the object registry.
593 Runtime* runtime = Runtime::Current();
Mathieu Chartierbf9fc582015-03-13 17:21:25 -0700594 runtime->GetThreadList()->SuspendAll(__FUNCTION__);
Ian Rogers62d6c772013-02-27 08:32:07 -0800595 Thread* self = Thread::Current();
596 ThreadState old_state = self->SetStateUnsafe(kRunnable);
Sebastien Hertzaaea7342014-02-25 15:10:04 +0100597
598 // Debugger may not be active at this point.
Daniel Mihalyieb076692014-08-22 17:33:31 +0200599 if (IsDebuggerActive()) {
Sebastien Hertzaaea7342014-02-25 15:10:04 +0100600 {
601 // Since we're going to disable deoptimization, we clear the deoptimization requests queue.
602 // This prevents us from having any pending deoptimization request when the debugger attaches
603 // to us again while no event has been requested yet.
Brian Carlstrom306db812014-09-05 13:01:41 -0700604 MutexLock mu(Thread::Current(), *Locks::deoptimization_lock_);
Sebastien Hertz4d25df32014-03-21 17:44:46 +0100605 deoptimization_requests_.clear();
606 full_deoptimization_event_count_ = 0U;
Sebastien Hertzaaea7342014-02-25 15:10:04 +0100607 }
Sebastien Hertz42cd43f2014-05-13 14:15:41 +0200608 if (instrumentation_events_ != 0) {
609 runtime->GetInstrumentation()->RemoveListener(&gDebugInstrumentationListener,
610 instrumentation_events_);
611 instrumentation_events_ = 0;
612 }
Sebastien Hertzf3928792014-11-17 19:00:37 +0100613 if (RequiresDeoptimization()) {
Sebastien Hertz0462c4c2015-04-01 16:34:17 +0200614 runtime->GetInstrumentation()->DisableDeoptimization(kDbgInstrumentationKey);
Sebastien Hertzf3928792014-11-17 19:00:37 +0100615 }
Sebastien Hertzaaea7342014-02-25 15:10:04 +0100616 gDebuggerActive = false;
Sebastien Hertz138dbfc2013-12-04 18:15:25 +0100617 }
Ian Rogers62d6c772013-02-27 08:32:07 -0800618 CHECK_EQ(self->SetStateUnsafe(old_state), kRunnable);
619 runtime->GetThreadList()->ResumeAll();
Sebastien Hertz55f65342015-01-13 22:48:34 +0100620
621 {
622 ScopedObjectAccess soa(self);
623 gRegistry->Clear();
624 }
625
626 gDebuggerConnected = false;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700627}
628
Sebastien Hertzb3b173b2015-02-06 09:16:32 +0100629void Dbg::ConfigureJdwp(const JDWP::JdwpOptions& jdwp_options) {
630 CHECK_NE(jdwp_options.transport, JDWP::kJdwpTransportUnknown);
631 gJdwpOptions = jdwp_options;
632 gJdwpConfigured = true;
633}
634
Elliott Hughesc0f09332012-03-26 13:27:06 -0700635bool Dbg::IsJdwpConfigured() {
Elliott Hughes3bb81562011-10-21 18:52:59 -0700636 return gJdwpConfigured;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700637}
638
639int64_t Dbg::LastDebuggerActivity() {
Elliott Hughesca951522011-12-05 12:01:32 -0800640 return gJdwpState->LastDebuggerActivity();
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700641}
642
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700643void Dbg::UndoDebuggerSuspensions() {
Elliott Hughes234ab152011-10-26 14:02:26 -0700644 Runtime::Current()->GetThreadList()->UndoDebuggerSuspensions();
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700645}
646
Elliott Hughes88d63092013-01-09 09:55:54 -0800647std::string Dbg::GetClassName(JDWP::RefTypeId class_id) {
Ian Rogersc0542af2014-09-03 16:16:56 -0700648 JDWP::JdwpError error;
649 mirror::Object* o = gRegistry->Get<mirror::Object*>(class_id, &error);
650 if (o == nullptr) {
651 if (error == JDWP::ERR_NONE) {
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700652 return "null";
Ian Rogersc0542af2014-09-03 16:16:56 -0700653 } else {
654 return StringPrintf("invalid object %p", reinterpret_cast<void*>(class_id));
655 }
Elliott Hughes436e3722012-02-17 20:01:47 -0800656 }
657 if (!o->IsClass()) {
Brian Carlstrom7934ac22013-07-26 10:54:15 -0700658 return StringPrintf("non-class %p", o); // This is only used for debugging output anyway.
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -0800659 }
Sebastien Hertz6995c602014-09-09 12:10:13 +0200660 return GetClassName(o->AsClass());
661}
662
663std::string Dbg::GetClassName(mirror::Class* klass) {
Sebastien Hertza9aa0ff2014-09-19 12:07:51 +0200664 if (klass == nullptr) {
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700665 return "null";
Sebastien Hertza9aa0ff2014-09-19 12:07:51 +0200666 }
Ian Rogers1ff3c982014-08-12 02:30:58 -0700667 std::string temp;
Sebastien Hertz6995c602014-09-09 12:10:13 +0200668 return DescriptorToName(klass->GetDescriptor(&temp));
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700669}
670
Ian Rogersc0542af2014-09-03 16:16:56 -0700671JDWP::JdwpError Dbg::GetClassObject(JDWP::RefTypeId id, JDWP::ObjectId* class_object_id) {
Elliott Hughes436e3722012-02-17 20:01:47 -0800672 JDWP::JdwpError status;
Ian Rogersc0542af2014-09-03 16:16:56 -0700673 mirror::Class* c = DecodeClass(id, &status);
674 if (c == nullptr) {
675 *class_object_id = 0;
Elliott Hughes436e3722012-02-17 20:01:47 -0800676 return status;
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -0800677 }
Ian Rogersc0542af2014-09-03 16:16:56 -0700678 *class_object_id = gRegistry->Add(c);
Elliott Hughes436e3722012-02-17 20:01:47 -0800679 return JDWP::ERR_NONE;
Elliott Hughes86964332012-02-15 19:37:42 -0800680}
681
Ian Rogersc0542af2014-09-03 16:16:56 -0700682JDWP::JdwpError Dbg::GetSuperclass(JDWP::RefTypeId id, JDWP::RefTypeId* superclass_id) {
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -0800683 JDWP::JdwpError status;
Ian Rogersc0542af2014-09-03 16:16:56 -0700684 mirror::Class* c = DecodeClass(id, &status);
685 if (c == nullptr) {
686 *superclass_id = 0;
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -0800687 return status;
688 }
689 if (c->IsInterface()) {
690 // http://code.google.com/p/android/issues/detail?id=20856
Ian Rogersc0542af2014-09-03 16:16:56 -0700691 *superclass_id = 0;
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -0800692 } else {
Ian Rogersc0542af2014-09-03 16:16:56 -0700693 *superclass_id = gRegistry->Add(c->GetSuperClass());
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -0800694 }
695 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700696}
697
Elliott Hughes436e3722012-02-17 20:01:47 -0800698JDWP::JdwpError Dbg::GetClassLoader(JDWP::RefTypeId id, JDWP::ExpandBuf* pReply) {
Ian Rogersc0542af2014-09-03 16:16:56 -0700699 JDWP::JdwpError error;
700 mirror::Object* o = gRegistry->Get<mirror::Object*>(id, &error);
701 if (o == nullptr) {
Elliott Hughes436e3722012-02-17 20:01:47 -0800702 return JDWP::ERR_INVALID_OBJECT;
703 }
704 expandBufAddObjectId(pReply, gRegistry->Add(o->GetClass()->GetClassLoader()));
705 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700706}
707
Elliott Hughes436e3722012-02-17 20:01:47 -0800708JDWP::JdwpError Dbg::GetModifiers(JDWP::RefTypeId id, JDWP::ExpandBuf* pReply) {
Ian Rogersc0542af2014-09-03 16:16:56 -0700709 JDWP::JdwpError error;
710 mirror::Class* c = DecodeClass(id, &error);
711 if (c == nullptr) {
712 return error;
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -0800713 }
Elliott Hughes436e3722012-02-17 20:01:47 -0800714
715 uint32_t access_flags = c->GetAccessFlags() & kAccJavaFlagsMask;
716
Yevgeny Roubande34eea2014-02-15 01:06:03 +0700717 // Set ACC_SUPER. Dex files don't contain this flag but only classes are supposed to have it set,
718 // not interfaces.
Elliott Hughes436e3722012-02-17 20:01:47 -0800719 // Class.getModifiers doesn't return it, but JDWP does, so we set it here.
Yevgeny Roubande34eea2014-02-15 01:06:03 +0700720 if ((access_flags & kAccInterface) == 0) {
721 access_flags |= kAccSuper;
722 }
Elliott Hughes436e3722012-02-17 20:01:47 -0800723
724 expandBufAdd4BE(pReply, access_flags);
725
726 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700727}
728
Ian Rogersc0542af2014-09-03 16:16:56 -0700729JDWP::JdwpError Dbg::GetMonitorInfo(JDWP::ObjectId object_id, JDWP::ExpandBuf* reply) {
730 JDWP::JdwpError error;
731 mirror::Object* o = gRegistry->Get<mirror::Object*>(object_id, &error);
732 if (o == nullptr) {
Elliott Hughesf327e072013-01-09 16:01:26 -0800733 return JDWP::ERR_INVALID_OBJECT;
734 }
735
736 // Ensure all threads are suspended while we read objects' lock words.
737 Thread* self = Thread::Current();
Sebastien Hertz54263242014-03-19 18:16:50 +0100738 CHECK_EQ(self->GetState(), kRunnable);
739 self->TransitionFromRunnableToSuspended(kSuspended);
Mathieu Chartierbf9fc582015-03-13 17:21:25 -0700740 Runtime::Current()->GetThreadList()->SuspendAll(__FUNCTION__);
Elliott Hughesf327e072013-01-09 16:01:26 -0800741
742 MonitorInfo monitor_info(o);
743
Sebastien Hertz54263242014-03-19 18:16:50 +0100744 Runtime::Current()->GetThreadList()->ResumeAll();
745 self->TransitionFromSuspendedToRunnable();
Elliott Hughesf327e072013-01-09 16:01:26 -0800746
Ian Rogersc0542af2014-09-03 16:16:56 -0700747 if (monitor_info.owner_ != nullptr) {
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700748 expandBufAddObjectId(reply, gRegistry->Add(monitor_info.owner_->GetPeer()));
Elliott Hughesf327e072013-01-09 16:01:26 -0800749 } else {
Ian Rogersc0542af2014-09-03 16:16:56 -0700750 expandBufAddObjectId(reply, gRegistry->Add(nullptr));
Elliott Hughesf327e072013-01-09 16:01:26 -0800751 }
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700752 expandBufAdd4BE(reply, monitor_info.entry_count_);
753 expandBufAdd4BE(reply, monitor_info.waiters_.size());
754 for (size_t i = 0; i < monitor_info.waiters_.size(); ++i) {
755 expandBufAddObjectId(reply, gRegistry->Add(monitor_info.waiters_[i]->GetPeer()));
Elliott Hughesf327e072013-01-09 16:01:26 -0800756 }
757 return JDWP::ERR_NONE;
758}
759
Elliott Hughes734b8c62013-01-11 15:32:45 -0800760JDWP::JdwpError Dbg::GetOwnedMonitors(JDWP::ObjectId thread_id,
Ian Rogersc0542af2014-09-03 16:16:56 -0700761 std::vector<JDWP::ObjectId>* monitors,
762 std::vector<uint32_t>* stack_depths) {
Elliott Hughes4993bbc2013-01-10 15:41:25 -0800763 struct OwnedMonitorVisitor : public StackVisitor {
Hiroshi Yamauchib5a9e3d2014-06-09 12:11:20 -0700764 OwnedMonitorVisitor(Thread* thread, Context* context,
Hiroshi Yamauchicc8c5c52014-06-13 15:08:05 -0700765 std::vector<JDWP::ObjectId>* monitor_vector,
Hiroshi Yamauchib5a9e3d2014-06-09 12:11:20 -0700766 std::vector<uint32_t>* stack_depth_vector)
Mathieu Chartier90443472015-07-16 20:32:27 -0700767 SHARED_REQUIRES(Locks::mutator_lock_)
Nicolas Geoffray8e5bd182015-05-06 11:34:34 +0100768 : StackVisitor(thread, context, StackVisitor::StackWalkKind::kIncludeInlinedFrames),
769 current_stack_depth(0),
770 monitors(monitor_vector),
771 stack_depths(stack_depth_vector) {}
Elliott Hughes4993bbc2013-01-10 15:41:25 -0800772
773 // TODO: Enable annotalysis. We know lock is held in constructor, but abstraction confuses
774 // annotalysis.
775 bool VisitFrame() NO_THREAD_SAFETY_ANALYSIS {
776 if (!GetMethod()->IsRuntimeMethod()) {
777 Monitor::VisitLocks(this, AppendOwnedMonitors, this);
Elliott Hughes734b8c62013-01-11 15:32:45 -0800778 ++current_stack_depth;
Elliott Hughes4993bbc2013-01-10 15:41:25 -0800779 }
780 return true;
781 }
782
Hiroshi Yamauchicc8c5c52014-06-13 15:08:05 -0700783 static void AppendOwnedMonitors(mirror::Object* owned_monitor, void* arg)
Mathieu Chartier90443472015-07-16 20:32:27 -0700784 SHARED_REQUIRES(Locks::mutator_lock_) {
Ian Rogers7a22fa62013-01-23 12:16:16 -0800785 OwnedMonitorVisitor* visitor = reinterpret_cast<OwnedMonitorVisitor*>(arg);
Hiroshi Yamauchicc8c5c52014-06-13 15:08:05 -0700786 visitor->monitors->push_back(gRegistry->Add(owned_monitor));
Hiroshi Yamauchib5a9e3d2014-06-09 12:11:20 -0700787 visitor->stack_depths->push_back(visitor->current_stack_depth);
Elliott Hughes4993bbc2013-01-10 15:41:25 -0800788 }
789
Elliott Hughes734b8c62013-01-11 15:32:45 -0800790 size_t current_stack_depth;
Ian Rogersc0542af2014-09-03 16:16:56 -0700791 std::vector<JDWP::ObjectId>* const monitors;
792 std::vector<uint32_t>* const stack_depths;
Elliott Hughes4993bbc2013-01-10 15:41:25 -0800793 };
Elliott Hughes4993bbc2013-01-10 15:41:25 -0800794
Hiroshi Yamauchib5a9e3d2014-06-09 12:11:20 -0700795 ScopedObjectAccessUnchecked soa(Thread::Current());
Sebastien Hertz69206392015-04-07 15:54:25 +0200796 JDWP::JdwpError error;
797 Thread* thread = DecodeThread(soa, thread_id, &error);
798 if (thread == nullptr) {
799 return error;
800 }
801 if (!IsSuspendedForDebugger(soa, thread)) {
802 return JDWP::ERR_THREAD_NOT_SUSPENDED;
Hiroshi Yamauchib5a9e3d2014-06-09 12:11:20 -0700803 }
Hiroshi Yamauchicc8c5c52014-06-13 15:08:05 -0700804 std::unique_ptr<Context> context(Context::Create());
Ian Rogersc0542af2014-09-03 16:16:56 -0700805 OwnedMonitorVisitor visitor(thread, context.get(), monitors, stack_depths);
Hiroshi Yamauchicc8c5c52014-06-13 15:08:05 -0700806 visitor.WalkStack();
Elliott Hughes4993bbc2013-01-10 15:41:25 -0800807 return JDWP::ERR_NONE;
808}
809
Sebastien Hertz52d131d2014-03-13 16:17:40 +0100810JDWP::JdwpError Dbg::GetContendedMonitor(JDWP::ObjectId thread_id,
Ian Rogersc0542af2014-09-03 16:16:56 -0700811 JDWP::ObjectId* contended_monitor) {
Elliott Hughesf9501702013-01-11 11:22:27 -0800812 ScopedObjectAccessUnchecked soa(Thread::Current());
Ian Rogersc0542af2014-09-03 16:16:56 -0700813 *contended_monitor = 0;
Sebastien Hertz69206392015-04-07 15:54:25 +0200814 JDWP::JdwpError error;
815 Thread* thread = DecodeThread(soa, thread_id, &error);
816 if (thread == nullptr) {
817 return error;
Elliott Hughesf9501702013-01-11 11:22:27 -0800818 }
Sebastien Hertz69206392015-04-07 15:54:25 +0200819 if (!IsSuspendedForDebugger(soa, thread)) {
820 return JDWP::ERR_THREAD_NOT_SUSPENDED;
821 }
822 mirror::Object* contended_monitor_obj = Monitor::GetContendedMonitor(thread);
Hiroshi Yamauchib5a9e3d2014-06-09 12:11:20 -0700823 // Add() requires the thread_list_lock_ not held to avoid the lock
824 // level violation.
Ian Rogersc0542af2014-09-03 16:16:56 -0700825 *contended_monitor = gRegistry->Add(contended_monitor_obj);
Elliott Hughesf9501702013-01-11 11:22:27 -0800826 return JDWP::ERR_NONE;
827}
828
Elliott Hughesec0f83d2013-01-15 16:54:08 -0800829JDWP::JdwpError Dbg::GetInstanceCounts(const std::vector<JDWP::RefTypeId>& class_ids,
Ian Rogersc0542af2014-09-03 16:16:56 -0700830 std::vector<uint64_t>* counts) {
Mathieu Chartier412c7fc2014-02-07 12:18:39 -0800831 gc::Heap* heap = Runtime::Current()->GetHeap();
832 heap->CollectGarbage(false);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800833 std::vector<mirror::Class*> classes;
Ian Rogersc0542af2014-09-03 16:16:56 -0700834 counts->clear();
Elliott Hughesec0f83d2013-01-15 16:54:08 -0800835 for (size_t i = 0; i < class_ids.size(); ++i) {
Ian Rogersc0542af2014-09-03 16:16:56 -0700836 JDWP::JdwpError error;
837 mirror::Class* c = DecodeClass(class_ids[i], &error);
838 if (c == nullptr) {
839 return error;
Elliott Hughesec0f83d2013-01-15 16:54:08 -0800840 }
841 classes.push_back(c);
Ian Rogersc0542af2014-09-03 16:16:56 -0700842 counts->push_back(0);
Elliott Hughesec0f83d2013-01-15 16:54:08 -0800843 }
Ian Rogersc0542af2014-09-03 16:16:56 -0700844 heap->CountInstances(classes, false, &(*counts)[0]);
Elliott Hughesec0f83d2013-01-15 16:54:08 -0800845 return JDWP::ERR_NONE;
846}
847
Ian Rogersc0542af2014-09-03 16:16:56 -0700848JDWP::JdwpError Dbg::GetInstances(JDWP::RefTypeId class_id, int32_t max_count,
849 std::vector<JDWP::ObjectId>* instances) {
Mathieu Chartier412c7fc2014-02-07 12:18:39 -0800850 gc::Heap* heap = Runtime::Current()->GetHeap();
851 // We only want reachable instances, so do a GC.
852 heap->CollectGarbage(false);
Ian Rogersc0542af2014-09-03 16:16:56 -0700853 JDWP::JdwpError error;
854 mirror::Class* c = DecodeClass(class_id, &error);
Mathieu Chartier412c7fc2014-02-07 12:18:39 -0800855 if (c == nullptr) {
Ian Rogersc0542af2014-09-03 16:16:56 -0700856 return error;
Elliott Hughes3b78c942013-01-15 17:35:41 -0800857 }
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800858 std::vector<mirror::Object*> raw_instances;
Elliott Hughes3b78c942013-01-15 17:35:41 -0800859 Runtime::Current()->GetHeap()->GetInstances(c, max_count, raw_instances);
860 for (size_t i = 0; i < raw_instances.size(); ++i) {
Ian Rogersc0542af2014-09-03 16:16:56 -0700861 instances->push_back(gRegistry->Add(raw_instances[i]));
Elliott Hughes3b78c942013-01-15 17:35:41 -0800862 }
863 return JDWP::ERR_NONE;
864}
865
Elliott Hughes0cbaff52013-01-16 15:28:01 -0800866JDWP::JdwpError Dbg::GetReferringObjects(JDWP::ObjectId object_id, int32_t max_count,
Ian Rogersc0542af2014-09-03 16:16:56 -0700867 std::vector<JDWP::ObjectId>* referring_objects) {
Mathieu Chartier412c7fc2014-02-07 12:18:39 -0800868 gc::Heap* heap = Runtime::Current()->GetHeap();
869 heap->CollectGarbage(false);
Ian Rogersc0542af2014-09-03 16:16:56 -0700870 JDWP::JdwpError error;
871 mirror::Object* o = gRegistry->Get<mirror::Object*>(object_id, &error);
872 if (o == nullptr) {
Elliott Hughes0cbaff52013-01-16 15:28:01 -0800873 return JDWP::ERR_INVALID_OBJECT;
874 }
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800875 std::vector<mirror::Object*> raw_instances;
Mathieu Chartier412c7fc2014-02-07 12:18:39 -0800876 heap->GetReferringObjects(o, max_count, raw_instances);
Elliott Hughes0cbaff52013-01-16 15:28:01 -0800877 for (size_t i = 0; i < raw_instances.size(); ++i) {
Ian Rogersc0542af2014-09-03 16:16:56 -0700878 referring_objects->push_back(gRegistry->Add(raw_instances[i]));
Elliott Hughes0cbaff52013-01-16 15:28:01 -0800879 }
880 return JDWP::ERR_NONE;
881}
882
Ian Rogersc0542af2014-09-03 16:16:56 -0700883JDWP::JdwpError Dbg::DisableCollection(JDWP::ObjectId object_id) {
884 JDWP::JdwpError error;
885 mirror::Object* o = gRegistry->Get<mirror::Object*>(object_id, &error);
886 if (o == nullptr) {
Sebastien Hertze96060a2013-12-11 12:06:28 +0100887 return JDWP::ERR_INVALID_OBJECT;
888 }
Elliott Hughes64f574f2013-02-20 14:57:12 -0800889 gRegistry->DisableCollection(object_id);
890 return JDWP::ERR_NONE;
891}
892
Ian Rogersc0542af2014-09-03 16:16:56 -0700893JDWP::JdwpError Dbg::EnableCollection(JDWP::ObjectId object_id) {
894 JDWP::JdwpError error;
895 mirror::Object* o = gRegistry->Get<mirror::Object*>(object_id, &error);
Sebastien Hertze96060a2013-12-11 12:06:28 +0100896 // Unlike DisableCollection, JDWP specs do not state an invalid object causes an error. The RI
897 // also ignores these cases and never return an error. However it's not obvious why this command
898 // should behave differently from DisableCollection and IsCollected commands. So let's be more
899 // strict and return an error if this happens.
Ian Rogersc0542af2014-09-03 16:16:56 -0700900 if (o == nullptr) {
Sebastien Hertze96060a2013-12-11 12:06:28 +0100901 return JDWP::ERR_INVALID_OBJECT;
902 }
Elliott Hughes64f574f2013-02-20 14:57:12 -0800903 gRegistry->EnableCollection(object_id);
904 return JDWP::ERR_NONE;
905}
906
Ian Rogersc0542af2014-09-03 16:16:56 -0700907JDWP::JdwpError Dbg::IsCollected(JDWP::ObjectId object_id, bool* is_collected) {
908 *is_collected = true;
Sebastien Hertz65637eb2014-01-10 17:40:02 +0100909 if (object_id == 0) {
910 // Null object id is invalid.
Sebastien Hertze96060a2013-12-11 12:06:28 +0100911 return JDWP::ERR_INVALID_OBJECT;
912 }
Sebastien Hertz65637eb2014-01-10 17:40:02 +0100913 // JDWP specs state an INVALID_OBJECT error is returned if the object ID is not valid. However
914 // the RI seems to ignore this and assume object has been collected.
Ian Rogersc0542af2014-09-03 16:16:56 -0700915 JDWP::JdwpError error;
916 mirror::Object* o = gRegistry->Get<mirror::Object*>(object_id, &error);
917 if (o != nullptr) {
918 *is_collected = gRegistry->IsCollected(object_id);
Sebastien Hertz65637eb2014-01-10 17:40:02 +0100919 }
Elliott Hughes64f574f2013-02-20 14:57:12 -0800920 return JDWP::ERR_NONE;
921}
922
Ian Rogersc0542af2014-09-03 16:16:56 -0700923void Dbg::DisposeObject(JDWP::ObjectId object_id, uint32_t reference_count) {
Elliott Hughes64f574f2013-02-20 14:57:12 -0800924 gRegistry->DisposeObject(object_id, reference_count);
925}
926
Sebastien Hertz6995c602014-09-09 12:10:13 +0200927JDWP::JdwpTypeTag Dbg::GetTypeTag(mirror::Class* klass) {
Sebastien Hertz4d8fd492014-03-28 16:29:41 +0100928 DCHECK(klass != nullptr);
929 if (klass->IsArrayClass()) {
930 return JDWP::TT_ARRAY;
931 } else if (klass->IsInterface()) {
932 return JDWP::TT_INTERFACE;
933 } else {
934 return JDWP::TT_CLASS;
935 }
936}
937
Elliott Hughes88d63092013-01-09 09:55:54 -0800938JDWP::JdwpError Dbg::GetReflectedType(JDWP::RefTypeId class_id, JDWP::ExpandBuf* pReply) {
Ian Rogersc0542af2014-09-03 16:16:56 -0700939 JDWP::JdwpError error;
940 mirror::Class* c = DecodeClass(class_id, &error);
941 if (c == nullptr) {
942 return error;
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -0800943 }
Elliott Hughes436e3722012-02-17 20:01:47 -0800944
Sebastien Hertz4d8fd492014-03-28 16:29:41 +0100945 JDWP::JdwpTypeTag type_tag = GetTypeTag(c);
946 expandBufAdd1(pReply, type_tag);
Elliott Hughes88d63092013-01-09 09:55:54 -0800947 expandBufAddRefTypeId(pReply, class_id);
Elliott Hughes436e3722012-02-17 20:01:47 -0800948 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700949}
950
Mathieu Chartiere0671ce2015-07-28 17:23:28 -0700951// Get the complete list of reference classes (i.e. all classes except
952// the primitive types).
953// Returns a newly-allocated buffer full of RefTypeId values.
954class ClassListCreator : public ClassVisitor {
955 public:
956 explicit ClassListCreator(std::vector<JDWP::RefTypeId>* classes) : classes_(classes) {}
957
958 bool Visit(mirror::Class* c) OVERRIDE SHARED_REQUIRES(Locks::mutator_lock_) {
959 if (!c->IsPrimitive()) {
960 classes_->push_back(Dbg::GetObjectRegistry()->AddRefType(c));
961 }
962 return true;
963 }
964
965 private:
966 std::vector<JDWP::RefTypeId>* const classes_;
967};
968
Ian Rogersc0542af2014-09-03 16:16:56 -0700969void Dbg::GetClassList(std::vector<JDWP::RefTypeId>* classes) {
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -0800970 ClassListCreator clc(classes);
Mathieu Chartiere0671ce2015-07-28 17:23:28 -0700971 Runtime::Current()->GetClassLinker()->VisitClassesWithoutClassesLock(&clc);
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700972}
973
Ian Rogers1ff3c982014-08-12 02:30:58 -0700974JDWP::JdwpError Dbg::GetClassInfo(JDWP::RefTypeId class_id, JDWP::JdwpTypeTag* pTypeTag,
975 uint32_t* pStatus, std::string* pDescriptor) {
Ian Rogersc0542af2014-09-03 16:16:56 -0700976 JDWP::JdwpError error;
977 mirror::Class* c = DecodeClass(class_id, &error);
978 if (c == nullptr) {
979 return error;
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -0800980 }
981
Elliott Hughesa2155262011-11-16 16:26:58 -0800982 if (c->IsArrayClass()) {
983 *pStatus = JDWP::CS_VERIFIED | JDWP::CS_PREPARED;
984 *pTypeTag = JDWP::TT_ARRAY;
985 } else {
986 if (c->IsErroneous()) {
987 *pStatus = JDWP::CS_ERROR;
988 } else {
989 *pStatus = JDWP::CS_VERIFIED | JDWP::CS_PREPARED | JDWP::CS_INITIALIZED;
990 }
991 *pTypeTag = c->IsInterface() ? JDWP::TT_INTERFACE : JDWP::TT_CLASS;
992 }
993
Ian Rogersc0542af2014-09-03 16:16:56 -0700994 if (pDescriptor != nullptr) {
Ian Rogers1ff3c982014-08-12 02:30:58 -0700995 std::string temp;
996 *pDescriptor = c->GetDescriptor(&temp);
Elliott Hughesa2155262011-11-16 16:26:58 -0800997 }
Elliott Hughes436e3722012-02-17 20:01:47 -0800998 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700999}
1000
Ian Rogersc0542af2014-09-03 16:16:56 -07001001void Dbg::FindLoadedClassBySignature(const char* descriptor, std::vector<JDWP::RefTypeId>* ids) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001002 std::vector<mirror::Class*> classes;
Igor Murashkinb1d8c312015-08-04 11:18:43 -07001003 Runtime::Current()->GetClassLinker()->LookupClasses(descriptor, classes);
Ian Rogersc0542af2014-09-03 16:16:56 -07001004 ids->clear();
Elliott Hughes6fa602d2011-12-02 17:54:25 -08001005 for (size_t i = 0; i < classes.size(); ++i) {
Ian Rogersc0542af2014-09-03 16:16:56 -07001006 ids->push_back(gRegistry->Add(classes[i]));
Elliott Hughes6fa602d2011-12-02 17:54:25 -08001007 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001008}
1009
Ian Rogersc0542af2014-09-03 16:16:56 -07001010JDWP::JdwpError Dbg::GetReferenceType(JDWP::ObjectId object_id, JDWP::ExpandBuf* pReply) {
1011 JDWP::JdwpError error;
1012 mirror::Object* o = gRegistry->Get<mirror::Object*>(object_id, &error);
1013 if (o == nullptr) {
Elliott Hughes2435a572012-02-17 16:07:41 -08001014 return JDWP::ERR_INVALID_OBJECT;
Elliott Hughes499c5132011-11-17 14:55:11 -08001015 }
Elliott Hughes2435a572012-02-17 16:07:41 -08001016
Sebastien Hertz4d8fd492014-03-28 16:29:41 +01001017 JDWP::JdwpTypeTag type_tag = GetTypeTag(o->GetClass());
Elliott Hughes64f574f2013-02-20 14:57:12 -08001018 JDWP::RefTypeId type_id = gRegistry->AddRefType(o->GetClass());
Elliott Hughes2435a572012-02-17 16:07:41 -08001019
1020 expandBufAdd1(pReply, type_tag);
1021 expandBufAddRefTypeId(pReply, type_id);
1022
1023 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001024}
1025
Ian Rogersfc0e94b2013-09-23 23:51:32 -07001026JDWP::JdwpError Dbg::GetSignature(JDWP::RefTypeId class_id, std::string* signature) {
Ian Rogersc0542af2014-09-03 16:16:56 -07001027 JDWP::JdwpError error;
1028 mirror::Class* c = DecodeClass(class_id, &error);
1029 if (c == nullptr) {
1030 return error;
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -08001031 }
Ian Rogers1ff3c982014-08-12 02:30:58 -07001032 std::string temp;
1033 *signature = c->GetDescriptor(&temp);
Elliott Hughes1fe7afb2012-02-13 17:23:03 -08001034 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001035}
1036
Ian Rogersc0542af2014-09-03 16:16:56 -07001037JDWP::JdwpError Dbg::GetSourceFile(JDWP::RefTypeId class_id, std::string* result) {
1038 JDWP::JdwpError error;
1039 mirror::Class* c = DecodeClass(class_id, &error);
Sebastien Hertz4206eb52014-06-05 10:15:45 +02001040 if (c == nullptr) {
Ian Rogersc0542af2014-09-03 16:16:56 -07001041 return error;
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -08001042 }
Sebastien Hertz4206eb52014-06-05 10:15:45 +02001043 const char* source_file = c->GetSourceFile();
1044 if (source_file == nullptr) {
Sebastien Hertzb7054ba2014-03-13 11:52:31 +01001045 return JDWP::ERR_ABSENT_INFORMATION;
1046 }
Ian Rogersc0542af2014-09-03 16:16:56 -07001047 *result = source_file;
Elliott Hughes436e3722012-02-17 20:01:47 -08001048 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001049}
1050
Ian Rogersc0542af2014-09-03 16:16:56 -07001051JDWP::JdwpError Dbg::GetObjectTag(JDWP::ObjectId object_id, uint8_t* tag) {
Ian Rogers98379392014-02-24 16:53:16 -08001052 ScopedObjectAccessUnchecked soa(Thread::Current());
Ian Rogersc0542af2014-09-03 16:16:56 -07001053 JDWP::JdwpError error;
1054 mirror::Object* o = gRegistry->Get<mirror::Object*>(object_id, &error);
1055 if (error != JDWP::ERR_NONE) {
1056 *tag = JDWP::JT_VOID;
1057 return error;
Elliott Hughes546b9862012-06-20 16:06:13 -07001058 }
Ian Rogersc0542af2014-09-03 16:16:56 -07001059 *tag = TagFromObject(soa, o);
Elliott Hughes546b9862012-06-20 16:06:13 -07001060 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001061}
1062
Elliott Hughesaed4be92011-12-02 16:16:23 -08001063size_t Dbg::GetTagWidth(JDWP::JdwpTag tag) {
Elliott Hughesdbb40792011-11-18 17:05:22 -08001064 switch (tag) {
1065 case JDWP::JT_VOID:
1066 return 0;
1067 case JDWP::JT_BYTE:
1068 case JDWP::JT_BOOLEAN:
1069 return 1;
1070 case JDWP::JT_CHAR:
1071 case JDWP::JT_SHORT:
1072 return 2;
1073 case JDWP::JT_FLOAT:
1074 case JDWP::JT_INT:
1075 return 4;
1076 case JDWP::JT_ARRAY:
1077 case JDWP::JT_OBJECT:
1078 case JDWP::JT_STRING:
1079 case JDWP::JT_THREAD:
1080 case JDWP::JT_THREAD_GROUP:
1081 case JDWP::JT_CLASS_LOADER:
1082 case JDWP::JT_CLASS_OBJECT:
1083 return sizeof(JDWP::ObjectId);
1084 case JDWP::JT_DOUBLE:
1085 case JDWP::JT_LONG:
1086 return 8;
1087 default:
Elliott Hughes3d30d9b2011-12-07 17:35:48 -08001088 LOG(FATAL) << "Unknown tag " << tag;
Elliott Hughesdbb40792011-11-18 17:05:22 -08001089 return -1;
1090 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001091}
1092
Ian Rogersc0542af2014-09-03 16:16:56 -07001093JDWP::JdwpError Dbg::GetArrayLength(JDWP::ObjectId array_id, int32_t* length) {
1094 JDWP::JdwpError error;
1095 mirror::Array* a = DecodeNonNullArray(array_id, &error);
1096 if (a == nullptr) {
1097 return error;
Elliott Hughes24437992011-11-30 14:49:33 -08001098 }
Ian Rogersc0542af2014-09-03 16:16:56 -07001099 *length = a->GetLength();
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -08001100 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001101}
1102
Elliott Hughes88d63092013-01-09 09:55:54 -08001103JDWP::JdwpError Dbg::OutputArray(JDWP::ObjectId array_id, int offset, int count, JDWP::ExpandBuf* pReply) {
Ian Rogersc0542af2014-09-03 16:16:56 -07001104 JDWP::JdwpError error;
1105 mirror::Array* a = DecodeNonNullArray(array_id, &error);
Ian Rogers98379392014-02-24 16:53:16 -08001106 if (a == nullptr) {
Ian Rogersc0542af2014-09-03 16:16:56 -07001107 return error;
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -08001108 }
Elliott Hughes24437992011-11-30 14:49:33 -08001109
1110 if (offset < 0 || count < 0 || offset > a->GetLength() || a->GetLength() - offset < count) {
1111 LOG(WARNING) << __FUNCTION__ << " access out of bounds: offset=" << offset << "; count=" << count;
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -08001112 return JDWP::ERR_INVALID_LENGTH;
Elliott Hughes24437992011-11-30 14:49:33 -08001113 }
Ian Rogers1ff3c982014-08-12 02:30:58 -07001114 JDWP::JdwpTag element_tag = BasicTagFromClass(a->GetClass()->GetComponentType());
1115 expandBufAdd1(pReply, element_tag);
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -08001116 expandBufAdd4BE(pReply, count);
1117
Ian Rogers1ff3c982014-08-12 02:30:58 -07001118 if (IsPrimitiveTag(element_tag)) {
1119 size_t width = GetTagWidth(element_tag);
Elliott Hughes24437992011-11-30 14:49:33 -08001120 uint8_t* dst = expandBufAddSpace(pReply, count * width);
1121 if (width == 8) {
Ian Rogersef7d42f2014-01-06 12:55:46 -08001122 const uint64_t* src8 = reinterpret_cast<uint64_t*>(a->GetRawData(sizeof(uint64_t), 0));
Elliott Hughes24437992011-11-30 14:49:33 -08001123 for (int i = 0; i < count; ++i) JDWP::Write8BE(&dst, src8[offset + i]);
1124 } else if (width == 4) {
Ian Rogersef7d42f2014-01-06 12:55:46 -08001125 const uint32_t* src4 = reinterpret_cast<uint32_t*>(a->GetRawData(sizeof(uint32_t), 0));
Elliott Hughes24437992011-11-30 14:49:33 -08001126 for (int i = 0; i < count; ++i) JDWP::Write4BE(&dst, src4[offset + i]);
1127 } else if (width == 2) {
Ian Rogersef7d42f2014-01-06 12:55:46 -08001128 const uint16_t* src2 = reinterpret_cast<uint16_t*>(a->GetRawData(sizeof(uint16_t), 0));
Elliott Hughes24437992011-11-30 14:49:33 -08001129 for (int i = 0; i < count; ++i) JDWP::Write2BE(&dst, src2[offset + i]);
1130 } else {
Ian Rogersef7d42f2014-01-06 12:55:46 -08001131 const uint8_t* src = reinterpret_cast<uint8_t*>(a->GetRawData(sizeof(uint8_t), 0));
Elliott Hughes24437992011-11-30 14:49:33 -08001132 memcpy(dst, &src[offset * width], count * width);
1133 }
1134 } else {
Ian Rogers98379392014-02-24 16:53:16 -08001135 ScopedObjectAccessUnchecked soa(Thread::Current());
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001136 mirror::ObjectArray<mirror::Object>* oa = a->AsObjectArray<mirror::Object>();
Elliott Hughes24437992011-11-30 14:49:33 -08001137 for (int i = 0; i < count; ++i) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001138 mirror::Object* element = oa->Get(offset + i);
Ian Rogers98379392014-02-24 16:53:16 -08001139 JDWP::JdwpTag specific_tag = (element != nullptr) ? TagFromObject(soa, element)
Ian Rogers1ff3c982014-08-12 02:30:58 -07001140 : element_tag;
Elliott Hughes24437992011-11-30 14:49:33 -08001141 expandBufAdd1(pReply, specific_tag);
1142 expandBufAddObjectId(pReply, gRegistry->Add(element));
1143 }
1144 }
1145
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -08001146 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001147}
1148
Ian Rogersef7d42f2014-01-06 12:55:46 -08001149template <typename T>
Ian Rogersc0542af2014-09-03 16:16:56 -07001150static void CopyArrayData(mirror::Array* a, JDWP::Request* src, int offset, int count)
Ian Rogersef7d42f2014-01-06 12:55:46 -08001151 NO_THREAD_SAFETY_ANALYSIS {
1152 // TODO: fix when annotalysis correctly handles non-member functions.
Elliott Hughes4b9702c2013-02-20 18:13:24 -08001153 DCHECK(a->GetClass()->IsPrimitiveArray());
1154
Ian Rogersef7d42f2014-01-06 12:55:46 -08001155 T* dst = reinterpret_cast<T*>(a->GetRawData(sizeof(T), offset));
Elliott Hughes4b9702c2013-02-20 18:13:24 -08001156 for (int i = 0; i < count; ++i) {
Ian Rogersc0542af2014-09-03 16:16:56 -07001157 *dst++ = src->ReadValue(sizeof(T));
Elliott Hughes4b9702c2013-02-20 18:13:24 -08001158 }
1159}
1160
Elliott Hughes88d63092013-01-09 09:55:54 -08001161JDWP::JdwpError Dbg::SetArrayElements(JDWP::ObjectId array_id, int offset, int count,
Ian Rogersc0542af2014-09-03 16:16:56 -07001162 JDWP::Request* request) {
1163 JDWP::JdwpError error;
1164 mirror::Array* dst = DecodeNonNullArray(array_id, &error);
1165 if (dst == nullptr) {
1166 return error;
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -08001167 }
Elliott Hughesf03b8f62011-12-02 14:26:25 -08001168
Elliott Hughes4b9702c2013-02-20 18:13:24 -08001169 if (offset < 0 || count < 0 || offset > dst->GetLength() || dst->GetLength() - offset < count) {
Elliott Hughesf03b8f62011-12-02 14:26:25 -08001170 LOG(WARNING) << __FUNCTION__ << " access out of bounds: offset=" << offset << "; count=" << count;
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -08001171 return JDWP::ERR_INVALID_LENGTH;
Elliott Hughesf03b8f62011-12-02 14:26:25 -08001172 }
Ian Rogers1ff3c982014-08-12 02:30:58 -07001173 JDWP::JdwpTag element_tag = BasicTagFromClass(dst->GetClass()->GetComponentType());
Elliott Hughesf03b8f62011-12-02 14:26:25 -08001174
Ian Rogers1ff3c982014-08-12 02:30:58 -07001175 if (IsPrimitiveTag(element_tag)) {
1176 size_t width = GetTagWidth(element_tag);
Elliott Hughesf03b8f62011-12-02 14:26:25 -08001177 if (width == 8) {
Elliott Hughes4b9702c2013-02-20 18:13:24 -08001178 CopyArrayData<uint64_t>(dst, request, offset, count);
Elliott Hughesf03b8f62011-12-02 14:26:25 -08001179 } else if (width == 4) {
Elliott Hughes4b9702c2013-02-20 18:13:24 -08001180 CopyArrayData<uint32_t>(dst, request, offset, count);
Elliott Hughesf03b8f62011-12-02 14:26:25 -08001181 } else if (width == 2) {
Elliott Hughes4b9702c2013-02-20 18:13:24 -08001182 CopyArrayData<uint16_t>(dst, request, offset, count);
Elliott Hughesf03b8f62011-12-02 14:26:25 -08001183 } else {
Elliott Hughes4b9702c2013-02-20 18:13:24 -08001184 CopyArrayData<uint8_t>(dst, request, offset, count);
Elliott Hughesf03b8f62011-12-02 14:26:25 -08001185 }
1186 } else {
Elliott Hughes4b9702c2013-02-20 18:13:24 -08001187 mirror::ObjectArray<mirror::Object>* oa = dst->AsObjectArray<mirror::Object>();
Elliott Hughesf03b8f62011-12-02 14:26:25 -08001188 for (int i = 0; i < count; ++i) {
Ian Rogersc0542af2014-09-03 16:16:56 -07001189 JDWP::ObjectId id = request->ReadObjectId();
Ian Rogersc0542af2014-09-03 16:16:56 -07001190 mirror::Object* o = gRegistry->Get<mirror::Object*>(id, &error);
1191 if (error != JDWP::ERR_NONE) {
1192 return error;
Elliott Hughes436e3722012-02-17 20:01:47 -08001193 }
Sebastien Hertz2e1c16d2015-08-28 11:57:49 +02001194 // Check if the object's type is compatible with the array's type.
1195 if (o != nullptr && !o->InstanceOf(oa->GetClass()->GetComponentType())) {
1196 return JDWP::ERR_TYPE_MISMATCH;
1197 }
Sebastien Hertzd2fe10a2014-01-15 10:20:56 +01001198 oa->Set<false>(offset + i, o);
Elliott Hughesf03b8f62011-12-02 14:26:25 -08001199 }
1200 }
1201
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -08001202 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001203}
1204
Sebastien Hertz2c3e77a2015-04-02 16:26:48 +02001205JDWP::JdwpError Dbg::CreateString(const std::string& str, JDWP::ObjectId* new_string_id) {
1206 Thread* self = Thread::Current();
1207 mirror::String* new_string = mirror::String::AllocFromModifiedUtf8(self, str.c_str());
1208 if (new_string == nullptr) {
1209 DCHECK(self->IsExceptionPending());
1210 self->ClearException();
1211 LOG(ERROR) << "Could not allocate string";
1212 *new_string_id = 0;
1213 return JDWP::ERR_OUT_OF_MEMORY;
1214 }
1215 *new_string_id = gRegistry->Add(new_string);
1216 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001217}
1218
Sebastien Hertz2c3e77a2015-04-02 16:26:48 +02001219JDWP::JdwpError Dbg::CreateObject(JDWP::RefTypeId class_id, JDWP::ObjectId* new_object_id) {
Ian Rogersc0542af2014-09-03 16:16:56 -07001220 JDWP::JdwpError error;
1221 mirror::Class* c = DecodeClass(class_id, &error);
1222 if (c == nullptr) {
Sebastien Hertz2c3e77a2015-04-02 16:26:48 +02001223 *new_object_id = 0;
Ian Rogersc0542af2014-09-03 16:16:56 -07001224 return error;
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -08001225 }
Sebastien Hertz2c3e77a2015-04-02 16:26:48 +02001226 Thread* self = Thread::Current();
1227 mirror::Object* new_object = c->AllocObject(self);
1228 if (new_object == nullptr) {
1229 DCHECK(self->IsExceptionPending());
1230 self->ClearException();
1231 LOG(ERROR) << "Could not allocate object of type " << PrettyDescriptor(c);
1232 *new_object_id = 0;
1233 return JDWP::ERR_OUT_OF_MEMORY;
1234 }
1235 *new_object_id = gRegistry->Add(new_object);
Elliott Hughes436e3722012-02-17 20:01:47 -08001236 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001237}
1238
Elliott Hughesbf13d362011-12-08 15:51:37 -08001239/*
1240 * Used by Eclipse's "Display" view to evaluate "new byte[5]" to get "(byte[]) [0, 0, 0, 0, 0]".
1241 */
Elliott Hughes88d63092013-01-09 09:55:54 -08001242JDWP::JdwpError Dbg::CreateArrayObject(JDWP::RefTypeId array_class_id, uint32_t length,
Sebastien Hertz2c3e77a2015-04-02 16:26:48 +02001243 JDWP::ObjectId* new_array_id) {
Ian Rogersc0542af2014-09-03 16:16:56 -07001244 JDWP::JdwpError error;
1245 mirror::Class* c = DecodeClass(array_class_id, &error);
1246 if (c == nullptr) {
Sebastien Hertz2c3e77a2015-04-02 16:26:48 +02001247 *new_array_id = 0;
Ian Rogersc0542af2014-09-03 16:16:56 -07001248 return error;
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -08001249 }
Sebastien Hertz2c3e77a2015-04-02 16:26:48 +02001250 Thread* self = Thread::Current();
1251 gc::Heap* heap = Runtime::Current()->GetHeap();
1252 mirror::Array* new_array = mirror::Array::Alloc<true>(self, c, length,
1253 c->GetComponentSizeShift(),
1254 heap->GetCurrentAllocator());
1255 if (new_array == nullptr) {
1256 DCHECK(self->IsExceptionPending());
1257 self->ClearException();
1258 LOG(ERROR) << "Could not allocate array of type " << PrettyDescriptor(c);
1259 *new_array_id = 0;
1260 return JDWP::ERR_OUT_OF_MEMORY;
1261 }
1262 *new_array_id = gRegistry->Add(new_array);
Elliott Hughes436e3722012-02-17 20:01:47 -08001263 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001264}
1265
Mathieu Chartierc7853442015-03-27 14:35:38 -07001266JDWP::FieldId Dbg::ToFieldId(const ArtField* f) {
Elliott Hughes03181a82011-11-17 17:22:21 -08001267 return static_cast<JDWP::FieldId>(reinterpret_cast<uintptr_t>(f));
Elliott Hughes03181a82011-11-17 17:22:21 -08001268}
1269
Mathieu Chartiere401d142015-04-22 13:56:20 -07001270static JDWP::MethodId ToMethodId(const ArtMethod* m)
Mathieu Chartier90443472015-07-16 20:32:27 -07001271 SHARED_REQUIRES(Locks::mutator_lock_) {
Elliott Hughes03181a82011-11-17 17:22:21 -08001272 return static_cast<JDWP::MethodId>(reinterpret_cast<uintptr_t>(m));
Elliott Hughes03181a82011-11-17 17:22:21 -08001273}
1274
Mathieu Chartierc7853442015-03-27 14:35:38 -07001275static ArtField* FromFieldId(JDWP::FieldId fid)
Mathieu Chartier90443472015-07-16 20:32:27 -07001276 SHARED_REQUIRES(Locks::mutator_lock_) {
Mathieu Chartierc7853442015-03-27 14:35:38 -07001277 return reinterpret_cast<ArtField*>(static_cast<uintptr_t>(fid));
Elliott Hughesaed4be92011-12-02 16:16:23 -08001278}
1279
Mathieu Chartiere401d142015-04-22 13:56:20 -07001280static ArtMethod* FromMethodId(JDWP::MethodId mid)
Mathieu Chartier90443472015-07-16 20:32:27 -07001281 SHARED_REQUIRES(Locks::mutator_lock_) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07001282 return reinterpret_cast<ArtMethod*>(static_cast<uintptr_t>(mid));
Elliott Hughes03181a82011-11-17 17:22:21 -08001283}
1284
Sebastien Hertz6995c602014-09-09 12:10:13 +02001285bool Dbg::MatchThread(JDWP::ObjectId expected_thread_id, Thread* event_thread) {
1286 CHECK(event_thread != nullptr);
1287 JDWP::JdwpError error;
Mathieu Chartiere401d142015-04-22 13:56:20 -07001288 mirror::Object* expected_thread_peer = gRegistry->Get<mirror::Object*>(
1289 expected_thread_id, &error);
Sebastien Hertz6995c602014-09-09 12:10:13 +02001290 return expected_thread_peer == event_thread->GetPeer();
1291}
1292
1293bool Dbg::MatchLocation(const JDWP::JdwpLocation& expected_location,
1294 const JDWP::EventLocation& event_location) {
1295 if (expected_location.dex_pc != event_location.dex_pc) {
1296 return false;
1297 }
Mathieu Chartiere401d142015-04-22 13:56:20 -07001298 ArtMethod* m = FromMethodId(expected_location.method_id);
Sebastien Hertz6995c602014-09-09 12:10:13 +02001299 return m == event_location.method;
1300}
1301
1302bool Dbg::MatchType(mirror::Class* event_class, JDWP::RefTypeId class_id) {
Sebastien Hertza9aa0ff2014-09-19 12:07:51 +02001303 if (event_class == nullptr) {
1304 return false;
1305 }
Sebastien Hertz6995c602014-09-09 12:10:13 +02001306 JDWP::JdwpError error;
1307 mirror::Class* expected_class = DecodeClass(class_id, &error);
1308 CHECK(expected_class != nullptr);
1309 return expected_class->IsAssignableFrom(event_class);
1310}
1311
1312bool Dbg::MatchField(JDWP::RefTypeId expected_type_id, JDWP::FieldId expected_field_id,
Mathieu Chartierc7853442015-03-27 14:35:38 -07001313 ArtField* event_field) {
1314 ArtField* expected_field = FromFieldId(expected_field_id);
Sebastien Hertz6995c602014-09-09 12:10:13 +02001315 if (expected_field != event_field) {
1316 return false;
1317 }
1318 return Dbg::MatchType(event_field->GetDeclaringClass(), expected_type_id);
1319}
1320
1321bool Dbg::MatchInstance(JDWP::ObjectId expected_instance_id, mirror::Object* event_instance) {
1322 JDWP::JdwpError error;
1323 mirror::Object* modifier_instance = gRegistry->Get<mirror::Object*>(expected_instance_id, &error);
1324 return modifier_instance == event_instance;
1325}
1326
Mathieu Chartier90443472015-07-16 20:32:27 -07001327void Dbg::SetJdwpLocation(JDWP::JdwpLocation* location, ArtMethod* m, uint32_t dex_pc) {
Ian Rogersc0542af2014-09-03 16:16:56 -07001328 if (m == nullptr) {
Sebastien Hertza9aa0ff2014-09-19 12:07:51 +02001329 memset(location, 0, sizeof(*location));
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08001330 } else {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001331 mirror::Class* c = m->GetDeclaringClass();
Ian Rogersc0542af2014-09-03 16:16:56 -07001332 location->type_tag = GetTypeTag(c);
1333 location->class_id = gRegistry->AddRefType(c);
1334 location->method_id = ToMethodId(m);
1335 location->dex_pc = (m->IsNative() || m->IsProxyMethod()) ? static_cast<uint64_t>(-1) : dex_pc;
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08001336 }
Elliott Hughesd07986f2011-12-06 18:27:45 -08001337}
1338
Ian Rogersc0542af2014-09-03 16:16:56 -07001339std::string Dbg::GetMethodName(JDWP::MethodId method_id) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07001340 ArtMethod* m = FromMethodId(method_id);
Sebastien Hertza9aa0ff2014-09-19 12:07:51 +02001341 if (m == nullptr) {
Mathieu Chartier2cebb242015-04-21 16:50:40 -07001342 return "null";
Sebastien Hertza9aa0ff2014-09-19 12:07:51 +02001343 }
Sebastien Hertz415fd082015-06-01 11:42:27 +02001344 return m->GetInterfaceMethodIfProxy(sizeof(void*))->GetName();
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001345}
1346
Ian Rogersc0542af2014-09-03 16:16:56 -07001347std::string Dbg::GetFieldName(JDWP::FieldId field_id) {
Mathieu Chartierc7853442015-03-27 14:35:38 -07001348 ArtField* f = FromFieldId(field_id);
Sebastien Hertza9aa0ff2014-09-19 12:07:51 +02001349 if (f == nullptr) {
Mathieu Chartier2cebb242015-04-21 16:50:40 -07001350 return "null";
Sebastien Hertza9aa0ff2014-09-19 12:07:51 +02001351 }
1352 return f->GetName();
Elliott Hughesa96836a2013-01-17 12:27:49 -08001353}
1354
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001355/*
1356 * Augment the access flags for synthetic methods and fields by setting
1357 * the (as described by the spec) "0xf0000000 bit". Also, strip out any
1358 * flags not specified by the Java programming language.
1359 */
1360static uint32_t MangleAccessFlags(uint32_t accessFlags) {
1361 accessFlags &= kAccJavaFlagsMask;
1362 if ((accessFlags & kAccSynthetic) != 0) {
1363 accessFlags |= 0xf0000000;
1364 }
1365 return accessFlags;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001366}
1367
Elliott Hughesdbb40792011-11-18 17:05:22 -08001368/*
Jeff Haob7cefc72013-11-14 14:51:09 -08001369 * Circularly shifts registers so that arguments come first. Debuggers
1370 * expect slots to begin with arguments, but dex code places them at
1371 * the end.
Elliott Hughesdbb40792011-11-18 17:05:22 -08001372 */
Mathieu Chartiere401d142015-04-22 13:56:20 -07001373static uint16_t MangleSlot(uint16_t slot, ArtMethod* m)
Mathieu Chartier90443472015-07-16 20:32:27 -07001374 SHARED_REQUIRES(Locks::mutator_lock_) {
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07001375 const DexFile::CodeItem* code_item = m->GetCodeItem();
Sebastien Hertzcb19ebf2014-03-11 15:26:35 +01001376 if (code_item == nullptr) {
1377 // We should not get here for a method without code (native, proxy or abstract). Log it and
1378 // return the slot as is since all registers are arguments.
1379 LOG(WARNING) << "Trying to mangle slot for method without code " << PrettyMethod(m);
1380 return slot;
1381 }
Jeff Haob7cefc72013-11-14 14:51:09 -08001382 uint16_t ins_size = code_item->ins_size_;
1383 uint16_t locals_size = code_item->registers_size_ - ins_size;
1384 if (slot >= locals_size) {
1385 return slot - locals_size;
1386 } else {
1387 return slot + ins_size;
Elliott Hughesdbb40792011-11-18 17:05:22 -08001388 }
Elliott Hughesdbb40792011-11-18 17:05:22 -08001389}
1390
Jeff Haob7cefc72013-11-14 14:51:09 -08001391/*
1392 * Circularly shifts registers so that arguments come last. Reverts
1393 * slots to dex style argument placement.
1394 */
Mathieu Chartiere401d142015-04-22 13:56:20 -07001395static uint16_t DemangleSlot(uint16_t slot, ArtMethod* m, JDWP::JdwpError* error)
Mathieu Chartier90443472015-07-16 20:32:27 -07001396 SHARED_REQUIRES(Locks::mutator_lock_) {
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07001397 const DexFile::CodeItem* code_item = m->GetCodeItem();
Sebastien Hertzcb19ebf2014-03-11 15:26:35 +01001398 if (code_item == nullptr) {
1399 // We should not get here for a method without code (native, proxy or abstract). Log it and
1400 // return the slot as is since all registers are arguments.
1401 LOG(WARNING) << "Trying to demangle slot for method without code " << PrettyMethod(m);
Mathieu Chartiere401d142015-04-22 13:56:20 -07001402 uint16_t vreg_count = ArtMethod::NumArgRegisters(m->GetShorty());
Sebastien Hertzabbabc82015-03-26 08:47:47 +01001403 if (slot < vreg_count) {
1404 *error = JDWP::ERR_NONE;
1405 return slot;
1406 }
Jeff Haob7cefc72013-11-14 14:51:09 -08001407 } else {
Sebastien Hertzabbabc82015-03-26 08:47:47 +01001408 if (slot < code_item->registers_size_) {
1409 uint16_t ins_size = code_item->ins_size_;
1410 uint16_t locals_size = code_item->registers_size_ - ins_size;
1411 *error = JDWP::ERR_NONE;
1412 return (slot < ins_size) ? slot + locals_size : slot - ins_size;
1413 }
Elliott Hughesdbb40792011-11-18 17:05:22 -08001414 }
Sebastien Hertzabbabc82015-03-26 08:47:47 +01001415
1416 // Slot is invalid in the method.
1417 LOG(ERROR) << "Invalid local slot " << slot << " for method " << PrettyMethod(m);
1418 *error = JDWP::ERR_INVALID_SLOT;
1419 return DexFile::kDexNoIndex16;
Elliott Hughesdbb40792011-11-18 17:05:22 -08001420}
1421
Mathieu Chartier90443472015-07-16 20:32:27 -07001422JDWP::JdwpError Dbg::OutputDeclaredFields(JDWP::RefTypeId class_id, bool with_generic,
1423 JDWP::ExpandBuf* pReply) {
Ian Rogersc0542af2014-09-03 16:16:56 -07001424 JDWP::JdwpError error;
1425 mirror::Class* c = DecodeClass(class_id, &error);
1426 if (c == nullptr) {
1427 return error;
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -08001428 }
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001429
1430 size_t instance_field_count = c->NumInstanceFields();
1431 size_t static_field_count = c->NumStaticFields();
1432
1433 expandBufAdd4BE(pReply, instance_field_count + static_field_count);
1434
1435 for (size_t i = 0; i < instance_field_count + static_field_count; ++i) {
Mathieu Chartier90443472015-07-16 20:32:27 -07001436 ArtField* f = (i < instance_field_count) ? c->GetInstanceField(i) :
1437 c->GetStaticField(i - instance_field_count);
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001438 expandBufAddFieldId(pReply, ToFieldId(f));
Mathieu Chartier61c5ebc2014-06-05 17:42:53 -07001439 expandBufAddUtf8String(pReply, f->GetName());
1440 expandBufAddUtf8String(pReply, f->GetTypeDescriptor());
Elliott Hughesc5b734a2011-12-01 17:20:58 -08001441 if (with_generic) {
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001442 static const char genericSignature[1] = "";
1443 expandBufAddUtf8String(pReply, genericSignature);
1444 }
1445 expandBufAdd4BE(pReply, MangleAccessFlags(f->GetAccessFlags()));
1446 }
Elliott Hughes436e3722012-02-17 20:01:47 -08001447 return JDWP::ERR_NONE;
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001448}
1449
Elliott Hughes88d63092013-01-09 09:55:54 -08001450JDWP::JdwpError Dbg::OutputDeclaredMethods(JDWP::RefTypeId class_id, bool with_generic,
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001451 JDWP::ExpandBuf* pReply) {
Ian Rogersc0542af2014-09-03 16:16:56 -07001452 JDWP::JdwpError error;
1453 mirror::Class* c = DecodeClass(class_id, &error);
1454 if (c == nullptr) {
1455 return error;
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -08001456 }
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001457
1458 size_t direct_method_count = c->NumDirectMethods();
1459 size_t virtual_method_count = c->NumVirtualMethods();
1460
1461 expandBufAdd4BE(pReply, direct_method_count + virtual_method_count);
1462
Mathieu Chartiere401d142015-04-22 13:56:20 -07001463 auto* cl = Runtime::Current()->GetClassLinker();
1464 auto ptr_size = cl->GetImagePointerSize();
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001465 for (size_t i = 0; i < direct_method_count + virtual_method_count; ++i) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07001466 ArtMethod* m = i < direct_method_count ?
1467 c->GetDirectMethod(i, ptr_size) : c->GetVirtualMethod(i - direct_method_count, ptr_size);
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001468 expandBufAddMethodId(pReply, ToMethodId(m));
Sebastien Hertz415fd082015-06-01 11:42:27 +02001469 expandBufAddUtf8String(pReply, m->GetInterfaceMethodIfProxy(sizeof(void*))->GetName());
1470 expandBufAddUtf8String(pReply,
1471 m->GetInterfaceMethodIfProxy(sizeof(void*))->GetSignature().ToString());
Elliott Hughesc5b734a2011-12-01 17:20:58 -08001472 if (with_generic) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07001473 const char* generic_signature = "";
1474 expandBufAddUtf8String(pReply, generic_signature);
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001475 }
1476 expandBufAdd4BE(pReply, MangleAccessFlags(m->GetAccessFlags()));
1477 }
Elliott Hughes436e3722012-02-17 20:01:47 -08001478 return JDWP::ERR_NONE;
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001479}
1480
Elliott Hughes88d63092013-01-09 09:55:54 -08001481JDWP::JdwpError Dbg::OutputDeclaredInterfaces(JDWP::RefTypeId class_id, JDWP::ExpandBuf* pReply) {
Ian Rogersc0542af2014-09-03 16:16:56 -07001482 JDWP::JdwpError error;
Mathieu Chartierf8322842014-05-16 10:59:25 -07001483 Thread* self = Thread::Current();
1484 StackHandleScope<1> hs(self);
Ian Rogersc0542af2014-09-03 16:16:56 -07001485 Handle<mirror::Class> c(hs.NewHandle(DecodeClass(class_id, &error)));
Mathieu Chartierf8322842014-05-16 10:59:25 -07001486 if (c.Get() == nullptr) {
Ian Rogersc0542af2014-09-03 16:16:56 -07001487 return error;
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -08001488 }
Mathieu Chartierf8322842014-05-16 10:59:25 -07001489 size_t interface_count = c->NumDirectInterfaces();
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001490 expandBufAdd4BE(pReply, interface_count);
1491 for (size_t i = 0; i < interface_count; ++i) {
Mathieu Chartierf8322842014-05-16 10:59:25 -07001492 expandBufAddRefTypeId(pReply,
1493 gRegistry->AddRefType(mirror::Class::GetDirectInterface(self, c, i)));
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001494 }
Elliott Hughes436e3722012-02-17 20:01:47 -08001495 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001496}
1497
Ian Rogersc0542af2014-09-03 16:16:56 -07001498void Dbg::OutputLineTable(JDWP::RefTypeId, JDWP::MethodId method_id, JDWP::ExpandBuf* pReply) {
Elliott Hughes03181a82011-11-17 17:22:21 -08001499 struct DebugCallbackContext {
1500 int numItems;
1501 JDWP::ExpandBuf* pReply;
1502
Elliott Hughes2435a572012-02-17 16:07:41 -08001503 static bool Callback(void* context, uint32_t address, uint32_t line_number) {
Elliott Hughes03181a82011-11-17 17:22:21 -08001504 DebugCallbackContext* pContext = reinterpret_cast<DebugCallbackContext*>(context);
1505 expandBufAdd8BE(pContext->pReply, address);
Elliott Hughes2435a572012-02-17 16:07:41 -08001506 expandBufAdd4BE(pContext->pReply, line_number);
Elliott Hughes03181a82011-11-17 17:22:21 -08001507 pContext->numItems++;
Sebastien Hertzf2910ee2013-10-19 16:39:24 +02001508 return false;
Elliott Hughes03181a82011-11-17 17:22:21 -08001509 }
1510 };
Mathieu Chartiere401d142015-04-22 13:56:20 -07001511 ArtMethod* m = FromMethodId(method_id);
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07001512 const DexFile::CodeItem* code_item = m->GetCodeItem();
Elliott Hughes03181a82011-11-17 17:22:21 -08001513 uint64_t start, end;
Sebastien Hertzcb19ebf2014-03-11 15:26:35 +01001514 if (code_item == nullptr) {
1515 DCHECK(m->IsNative() || m->IsProxyMethod());
Elliott Hughes03181a82011-11-17 17:22:21 -08001516 start = -1;
1517 end = -1;
1518 } else {
1519 start = 0;
jeffhao14f0db92012-12-14 17:50:42 -08001520 // Return the index of the last instruction
Sebastien Hertzcb19ebf2014-03-11 15:26:35 +01001521 end = code_item->insns_size_in_code_units_ - 1;
Elliott Hughes03181a82011-11-17 17:22:21 -08001522 }
1523
1524 expandBufAdd8BE(pReply, start);
1525 expandBufAdd8BE(pReply, end);
1526
1527 // Add numLines later
1528 size_t numLinesOffset = expandBufGetLength(pReply);
1529 expandBufAdd4BE(pReply, 0);
1530
1531 DebugCallbackContext context;
1532 context.numItems = 0;
1533 context.pReply = pReply;
1534
Sebastien Hertzcb19ebf2014-03-11 15:26:35 +01001535 if (code_item != nullptr) {
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07001536 m->GetDexFile()->DecodeDebugInfo(code_item, m->IsStatic(), m->GetDexMethodIndex(),
Ian Rogersc0542af2014-09-03 16:16:56 -07001537 DebugCallbackContext::Callback, nullptr, &context);
Sebastien Hertzcb19ebf2014-03-11 15:26:35 +01001538 }
Elliott Hughes03181a82011-11-17 17:22:21 -08001539
1540 JDWP::Set4BE(expandBufGetBuffer(pReply) + numLinesOffset, context.numItems);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001541}
1542
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07001543void Dbg::OutputVariableTable(JDWP::RefTypeId, JDWP::MethodId method_id, bool with_generic,
1544 JDWP::ExpandBuf* pReply) {
Elliott Hughesdbb40792011-11-18 17:05:22 -08001545 struct DebugCallbackContext {
Mathieu Chartiere401d142015-04-22 13:56:20 -07001546 ArtMethod* method;
Elliott Hughesdbb40792011-11-18 17:05:22 -08001547 JDWP::ExpandBuf* pReply;
Elliott Hughesc5b734a2011-12-01 17:20:58 -08001548 size_t variable_count;
1549 bool with_generic;
Elliott Hughesdbb40792011-11-18 17:05:22 -08001550
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07001551 static void Callback(void* context, uint16_t slot, uint32_t startAddress, uint32_t endAddress,
1552 const char* name, const char* descriptor, const char* signature)
Mathieu Chartier90443472015-07-16 20:32:27 -07001553 SHARED_REQUIRES(Locks::mutator_lock_) {
Elliott Hughesdbb40792011-11-18 17:05:22 -08001554 DebugCallbackContext* pContext = reinterpret_cast<DebugCallbackContext*>(context);
1555
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07001556 VLOG(jdwp) << StringPrintf(" %2zd: %d(%d) '%s' '%s' '%s' actual slot=%d mangled slot=%d",
1557 pContext->variable_count, startAddress, endAddress - startAddress,
1558 name, descriptor, signature, slot,
1559 MangleSlot(slot, pContext->method));
Elliott Hughesdbb40792011-11-18 17:05:22 -08001560
Jeff Haob7cefc72013-11-14 14:51:09 -08001561 slot = MangleSlot(slot, pContext->method);
Elliott Hughes68fdbd02011-11-29 19:22:47 -08001562
Elliott Hughesdbb40792011-11-18 17:05:22 -08001563 expandBufAdd8BE(pContext->pReply, startAddress);
1564 expandBufAddUtf8String(pContext->pReply, name);
1565 expandBufAddUtf8String(pContext->pReply, descriptor);
Elliott Hughesc5b734a2011-12-01 17:20:58 -08001566 if (pContext->with_generic) {
Elliott Hughesdbb40792011-11-18 17:05:22 -08001567 expandBufAddUtf8String(pContext->pReply, signature);
1568 }
1569 expandBufAdd4BE(pContext->pReply, endAddress - startAddress);
1570 expandBufAdd4BE(pContext->pReply, slot);
1571
Elliott Hughesc5b734a2011-12-01 17:20:58 -08001572 ++pContext->variable_count;
Elliott Hughesdbb40792011-11-18 17:05:22 -08001573 }
1574 };
Mathieu Chartiere401d142015-04-22 13:56:20 -07001575 ArtMethod* m = FromMethodId(method_id);
Elliott Hughesdbb40792011-11-18 17:05:22 -08001576
Elliott Hughesc5b734a2011-12-01 17:20:58 -08001577 // arg_count considers doubles and longs to take 2 units.
1578 // variable_count considers everything to take 1 unit.
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07001579 std::string shorty(m->GetShorty());
Mathieu Chartiere401d142015-04-22 13:56:20 -07001580 expandBufAdd4BE(pReply, ArtMethod::NumArgRegisters(shorty));
Elliott Hughesdbb40792011-11-18 17:05:22 -08001581
Elliott Hughesc5b734a2011-12-01 17:20:58 -08001582 // We don't know the total number of variables yet, so leave a blank and update it later.
1583 size_t variable_count_offset = expandBufGetLength(pReply);
Elliott Hughesdbb40792011-11-18 17:05:22 -08001584 expandBufAdd4BE(pReply, 0);
1585
1586 DebugCallbackContext context;
Jeff Haob7cefc72013-11-14 14:51:09 -08001587 context.method = m;
Elliott Hughesdbb40792011-11-18 17:05:22 -08001588 context.pReply = pReply;
Elliott Hughesc5b734a2011-12-01 17:20:58 -08001589 context.variable_count = 0;
1590 context.with_generic = with_generic;
Elliott Hughesdbb40792011-11-18 17:05:22 -08001591
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07001592 const DexFile::CodeItem* code_item = m->GetCodeItem();
Sebastien Hertzcb19ebf2014-03-11 15:26:35 +01001593 if (code_item != nullptr) {
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07001594 m->GetDexFile()->DecodeDebugInfo(
Ian Rogersc0542af2014-09-03 16:16:56 -07001595 code_item, m->IsStatic(), m->GetDexMethodIndex(), nullptr, DebugCallbackContext::Callback,
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07001596 &context);
Sebastien Hertzcb19ebf2014-03-11 15:26:35 +01001597 }
Elliott Hughesdbb40792011-11-18 17:05:22 -08001598
Elliott Hughesc5b734a2011-12-01 17:20:58 -08001599 JDWP::Set4BE(expandBufGetBuffer(pReply) + variable_count_offset, context.variable_count);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001600}
1601
Jeff Hao579b0242013-11-18 13:16:49 -08001602void Dbg::OutputMethodReturnValue(JDWP::MethodId method_id, const JValue* return_value,
1603 JDWP::ExpandBuf* pReply) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07001604 ArtMethod* m = FromMethodId(method_id);
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07001605 JDWP::JdwpTag tag = BasicTagFromDescriptor(m->GetShorty());
Jeff Hao579b0242013-11-18 13:16:49 -08001606 OutputJValue(tag, return_value, pReply);
1607}
1608
Sebastien Hertz3f52eaf2014-04-04 17:50:18 +02001609void Dbg::OutputFieldValue(JDWP::FieldId field_id, const JValue* field_value,
1610 JDWP::ExpandBuf* pReply) {
Mathieu Chartierc7853442015-03-27 14:35:38 -07001611 ArtField* f = FromFieldId(field_id);
Mathieu Chartier61c5ebc2014-06-05 17:42:53 -07001612 JDWP::JdwpTag tag = BasicTagFromDescriptor(f->GetTypeDescriptor());
Sebastien Hertz3f52eaf2014-04-04 17:50:18 +02001613 OutputJValue(tag, field_value, pReply);
1614}
1615
Elliott Hughes9777ba22013-01-17 09:04:19 -08001616JDWP::JdwpError Dbg::GetBytecodes(JDWP::RefTypeId, JDWP::MethodId method_id,
Ian Rogersc0542af2014-09-03 16:16:56 -07001617 std::vector<uint8_t>* bytecodes) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07001618 ArtMethod* m = FromMethodId(method_id);
Ian Rogersc0542af2014-09-03 16:16:56 -07001619 if (m == nullptr) {
Elliott Hughes9777ba22013-01-17 09:04:19 -08001620 return JDWP::ERR_INVALID_METHODID;
1621 }
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07001622 const DexFile::CodeItem* code_item = m->GetCodeItem();
Elliott Hughes9777ba22013-01-17 09:04:19 -08001623 size_t byte_count = code_item->insns_size_in_code_units_ * 2;
1624 const uint8_t* begin = reinterpret_cast<const uint8_t*>(code_item->insns_);
1625 const uint8_t* end = begin + byte_count;
1626 for (const uint8_t* p = begin; p != end; ++p) {
Ian Rogersc0542af2014-09-03 16:16:56 -07001627 bytecodes->push_back(*p);
Elliott Hughes9777ba22013-01-17 09:04:19 -08001628 }
1629 return JDWP::ERR_NONE;
1630}
1631
Elliott Hughes88d63092013-01-09 09:55:54 -08001632JDWP::JdwpTag Dbg::GetFieldBasicTag(JDWP::FieldId field_id) {
Mathieu Chartier61c5ebc2014-06-05 17:42:53 -07001633 return BasicTagFromDescriptor(FromFieldId(field_id)->GetTypeDescriptor());
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001634}
1635
Elliott Hughes88d63092013-01-09 09:55:54 -08001636JDWP::JdwpTag Dbg::GetStaticFieldBasicTag(JDWP::FieldId field_id) {
Mathieu Chartier61c5ebc2014-06-05 17:42:53 -07001637 return BasicTagFromDescriptor(FromFieldId(field_id)->GetTypeDescriptor());
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001638}
1639
Sebastien Hertz05c26b32015-06-11 18:42:58 +02001640static JValue GetArtFieldValue(ArtField* f, mirror::Object* o)
Mathieu Chartier90443472015-07-16 20:32:27 -07001641 SHARED_REQUIRES(Locks::mutator_lock_) {
Sebastien Hertz05c26b32015-06-11 18:42:58 +02001642 Primitive::Type fieldType = f->GetTypeAsPrimitiveType();
1643 JValue field_value;
1644 switch (fieldType) {
1645 case Primitive::kPrimBoolean:
1646 field_value.SetZ(f->GetBoolean(o));
1647 return field_value;
1648
1649 case Primitive::kPrimByte:
1650 field_value.SetB(f->GetByte(o));
1651 return field_value;
1652
1653 case Primitive::kPrimChar:
1654 field_value.SetC(f->GetChar(o));
1655 return field_value;
1656
1657 case Primitive::kPrimShort:
1658 field_value.SetS(f->GetShort(o));
1659 return field_value;
1660
1661 case Primitive::kPrimInt:
1662 case Primitive::kPrimFloat:
1663 // Int and Float must be treated as 32-bit values in JDWP.
1664 field_value.SetI(f->GetInt(o));
1665 return field_value;
1666
1667 case Primitive::kPrimLong:
1668 case Primitive::kPrimDouble:
1669 // Long and Double must be treated as 64-bit values in JDWP.
1670 field_value.SetJ(f->GetLong(o));
1671 return field_value;
1672
1673 case Primitive::kPrimNot:
1674 field_value.SetL(f->GetObject(o));
1675 return field_value;
1676
1677 case Primitive::kPrimVoid:
1678 LOG(FATAL) << "Attempt to read from field of type 'void'";
1679 UNREACHABLE();
1680 }
1681 LOG(FATAL) << "Attempt to read from field of unknown type";
1682 UNREACHABLE();
1683}
1684
Elliott Hughes88d63092013-01-09 09:55:54 -08001685static JDWP::JdwpError GetFieldValueImpl(JDWP::RefTypeId ref_type_id, JDWP::ObjectId object_id,
1686 JDWP::FieldId field_id, JDWP::ExpandBuf* pReply,
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001687 bool is_static)
Mathieu Chartier90443472015-07-16 20:32:27 -07001688 SHARED_REQUIRES(Locks::mutator_lock_) {
Ian Rogersc0542af2014-09-03 16:16:56 -07001689 JDWP::JdwpError error;
1690 mirror::Class* c = DecodeClass(ref_type_id, &error);
1691 if (ref_type_id != 0 && c == nullptr) {
1692 return error;
Elliott Hughes0cf74332012-02-23 23:14:00 -08001693 }
1694
Sebastien Hertz6995c602014-09-09 12:10:13 +02001695 mirror::Object* o = Dbg::GetObjectRegistry()->Get<mirror::Object*>(object_id, &error);
Ian Rogersc0542af2014-09-03 16:16:56 -07001696 if ((!is_static && o == nullptr) || error != JDWP::ERR_NONE) {
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08001697 return JDWP::ERR_INVALID_OBJECT;
1698 }
Mathieu Chartierc7853442015-03-27 14:35:38 -07001699 ArtField* f = FromFieldId(field_id);
Elliott Hughes0cf74332012-02-23 23:14:00 -08001700
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001701 mirror::Class* receiver_class = c;
Ian Rogersc0542af2014-09-03 16:16:56 -07001702 if (receiver_class == nullptr && o != nullptr) {
Elliott Hughes0cf74332012-02-23 23:14:00 -08001703 receiver_class = o->GetClass();
1704 }
Mathieu Chartier2cebb242015-04-21 16:50:40 -07001705 // TODO: should we give up now if receiver_class is null?
Ian Rogersc0542af2014-09-03 16:16:56 -07001706 if (receiver_class != nullptr && !f->GetDeclaringClass()->IsAssignableFrom(receiver_class)) {
Elliott Hughes0cf74332012-02-23 23:14:00 -08001707 LOG(INFO) << "ERR_INVALID_FIELDID: " << PrettyField(f) << " " << PrettyClass(receiver_class);
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08001708 return JDWP::ERR_INVALID_FIELDID;
1709 }
Elliott Hughesaed4be92011-12-02 16:16:23 -08001710
Elliott Hughes0cf74332012-02-23 23:14:00 -08001711 // The RI only enforces the static/non-static mismatch in one direction.
1712 // TODO: should we change the tests and check both?
1713 if (is_static) {
1714 if (!f->IsStatic()) {
1715 return JDWP::ERR_INVALID_FIELDID;
1716 }
1717 } else {
1718 if (f->IsStatic()) {
Sebastien Hertz05c26b32015-06-11 18:42:58 +02001719 LOG(WARNING) << "Ignoring non-nullptr receiver for ObjectReference.GetValues"
1720 << " on static field " << PrettyField(f);
Elliott Hughes0cf74332012-02-23 23:14:00 -08001721 }
1722 }
jeffhao0dfbb7e2012-11-28 15:26:03 -08001723 if (f->IsStatic()) {
1724 o = f->GetDeclaringClass();
1725 }
Elliott Hughes0cf74332012-02-23 23:14:00 -08001726
Sebastien Hertz05c26b32015-06-11 18:42:58 +02001727 JValue field_value(GetArtFieldValue(f, o));
Mathieu Chartier61c5ebc2014-06-05 17:42:53 -07001728 JDWP::JdwpTag tag = BasicTagFromDescriptor(f->GetTypeDescriptor());
Jeff Hao579b0242013-11-18 13:16:49 -08001729 Dbg::OutputJValue(tag, &field_value, pReply);
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08001730 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001731}
1732
Elliott Hughes88d63092013-01-09 09:55:54 -08001733JDWP::JdwpError Dbg::GetFieldValue(JDWP::ObjectId object_id, JDWP::FieldId field_id,
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001734 JDWP::ExpandBuf* pReply) {
Elliott Hughes88d63092013-01-09 09:55:54 -08001735 return GetFieldValueImpl(0, object_id, field_id, pReply, false);
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08001736}
1737
Ian Rogersc0542af2014-09-03 16:16:56 -07001738JDWP::JdwpError Dbg::GetStaticFieldValue(JDWP::RefTypeId ref_type_id, JDWP::FieldId field_id,
1739 JDWP::ExpandBuf* pReply) {
Elliott Hughes88d63092013-01-09 09:55:54 -08001740 return GetFieldValueImpl(ref_type_id, 0, field_id, pReply, true);
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08001741}
1742
Sebastien Hertz05c26b32015-06-11 18:42:58 +02001743static JDWP::JdwpError SetArtFieldValue(ArtField* f, mirror::Object* o, uint64_t value, int width)
Mathieu Chartier90443472015-07-16 20:32:27 -07001744 SHARED_REQUIRES(Locks::mutator_lock_) {
Sebastien Hertz05c26b32015-06-11 18:42:58 +02001745 Primitive::Type fieldType = f->GetTypeAsPrimitiveType();
1746 // Debugging only happens at runtime so we know we are not running in a transaction.
1747 static constexpr bool kNoTransactionMode = false;
1748 switch (fieldType) {
1749 case Primitive::kPrimBoolean:
1750 CHECK_EQ(width, 1);
1751 f->SetBoolean<kNoTransactionMode>(o, static_cast<uint8_t>(value));
1752 return JDWP::ERR_NONE;
1753
1754 case Primitive::kPrimByte:
1755 CHECK_EQ(width, 1);
1756 f->SetByte<kNoTransactionMode>(o, static_cast<uint8_t>(value));
1757 return JDWP::ERR_NONE;
1758
1759 case Primitive::kPrimChar:
1760 CHECK_EQ(width, 2);
1761 f->SetChar<kNoTransactionMode>(o, static_cast<uint16_t>(value));
1762 return JDWP::ERR_NONE;
1763
1764 case Primitive::kPrimShort:
1765 CHECK_EQ(width, 2);
1766 f->SetShort<kNoTransactionMode>(o, static_cast<int16_t>(value));
1767 return JDWP::ERR_NONE;
1768
1769 case Primitive::kPrimInt:
1770 case Primitive::kPrimFloat:
1771 CHECK_EQ(width, 4);
1772 // Int and Float must be treated as 32-bit values in JDWP.
1773 f->SetInt<kNoTransactionMode>(o, static_cast<int32_t>(value));
1774 return JDWP::ERR_NONE;
1775
1776 case Primitive::kPrimLong:
1777 case Primitive::kPrimDouble:
1778 CHECK_EQ(width, 8);
1779 // Long and Double must be treated as 64-bit values in JDWP.
1780 f->SetLong<kNoTransactionMode>(o, value);
1781 return JDWP::ERR_NONE;
1782
1783 case Primitive::kPrimNot: {
1784 JDWP::JdwpError error;
1785 mirror::Object* v = Dbg::GetObjectRegistry()->Get<mirror::Object*>(value, &error);
1786 if (error != JDWP::ERR_NONE) {
1787 return JDWP::ERR_INVALID_OBJECT;
1788 }
1789 if (v != nullptr) {
1790 mirror::Class* field_type;
1791 {
1792 StackHandleScope<2> hs(Thread::Current());
1793 HandleWrapper<mirror::Object> h_v(hs.NewHandleWrapper(&v));
1794 HandleWrapper<mirror::Object> h_o(hs.NewHandleWrapper(&o));
1795 field_type = f->GetType<true>();
1796 }
1797 if (!field_type->IsAssignableFrom(v->GetClass())) {
1798 return JDWP::ERR_INVALID_OBJECT;
1799 }
1800 }
1801 f->SetObject<kNoTransactionMode>(o, v);
1802 return JDWP::ERR_NONE;
1803 }
1804
1805 case Primitive::kPrimVoid:
1806 LOG(FATAL) << "Attempt to write to field of type 'void'";
1807 UNREACHABLE();
1808 }
1809 LOG(FATAL) << "Attempt to write to field of unknown type";
1810 UNREACHABLE();
1811}
1812
Elliott Hughes88d63092013-01-09 09:55:54 -08001813static JDWP::JdwpError SetFieldValueImpl(JDWP::ObjectId object_id, JDWP::FieldId field_id,
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001814 uint64_t value, int width, bool is_static)
Mathieu Chartier90443472015-07-16 20:32:27 -07001815 SHARED_REQUIRES(Locks::mutator_lock_) {
Ian Rogersc0542af2014-09-03 16:16:56 -07001816 JDWP::JdwpError error;
Sebastien Hertz6995c602014-09-09 12:10:13 +02001817 mirror::Object* o = Dbg::GetObjectRegistry()->Get<mirror::Object*>(object_id, &error);
Ian Rogersc0542af2014-09-03 16:16:56 -07001818 if ((!is_static && o == nullptr) || error != JDWP::ERR_NONE) {
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08001819 return JDWP::ERR_INVALID_OBJECT;
1820 }
Mathieu Chartierc7853442015-03-27 14:35:38 -07001821 ArtField* f = FromFieldId(field_id);
Elliott Hughes0cf74332012-02-23 23:14:00 -08001822
1823 // The RI only enforces the static/non-static mismatch in one direction.
1824 // TODO: should we change the tests and check both?
1825 if (is_static) {
1826 if (!f->IsStatic()) {
1827 return JDWP::ERR_INVALID_FIELDID;
1828 }
1829 } else {
1830 if (f->IsStatic()) {
Sebastien Hertz05c26b32015-06-11 18:42:58 +02001831 LOG(WARNING) << "Ignoring non-nullptr receiver for ObjectReference.SetValues"
1832 << " on static field " << PrettyField(f);
Elliott Hughes0cf74332012-02-23 23:14:00 -08001833 }
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08001834 }
jeffhao0dfbb7e2012-11-28 15:26:03 -08001835 if (f->IsStatic()) {
1836 o = f->GetDeclaringClass();
1837 }
Sebastien Hertz05c26b32015-06-11 18:42:58 +02001838 return SetArtFieldValue(f, o, value, width);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001839}
1840
Elliott Hughes88d63092013-01-09 09:55:54 -08001841JDWP::JdwpError Dbg::SetFieldValue(JDWP::ObjectId object_id, JDWP::FieldId field_id, uint64_t value,
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001842 int width) {
Elliott Hughes88d63092013-01-09 09:55:54 -08001843 return SetFieldValueImpl(object_id, field_id, value, width, false);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001844}
1845
Elliott Hughes88d63092013-01-09 09:55:54 -08001846JDWP::JdwpError Dbg::SetStaticFieldValue(JDWP::FieldId field_id, uint64_t value, int width) {
1847 return SetFieldValueImpl(0, field_id, value, width, true);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001848}
1849
Sebastien Hertzb0b0b492014-09-15 11:27:27 +02001850JDWP::JdwpError Dbg::StringToUtf8(JDWP::ObjectId string_id, std::string* str) {
Ian Rogersc0542af2014-09-03 16:16:56 -07001851 JDWP::JdwpError error;
Sebastien Hertzb0b0b492014-09-15 11:27:27 +02001852 mirror::Object* obj = gRegistry->Get<mirror::Object*>(string_id, &error);
1853 if (error != JDWP::ERR_NONE) {
1854 return error;
1855 }
1856 if (obj == nullptr) {
1857 return JDWP::ERR_INVALID_OBJECT;
1858 }
1859 {
1860 ScopedObjectAccessUnchecked soa(Thread::Current());
1861 mirror::Class* java_lang_String = soa.Decode<mirror::Class*>(WellKnownClasses::java_lang_String);
1862 if (!java_lang_String->IsAssignableFrom(obj->GetClass())) {
1863 // This isn't a string.
1864 return JDWP::ERR_INVALID_STRING;
1865 }
1866 }
1867 *str = obj->AsString()->ToModifiedUtf8();
1868 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001869}
1870
Jeff Hao579b0242013-11-18 13:16:49 -08001871void Dbg::OutputJValue(JDWP::JdwpTag tag, const JValue* return_value, JDWP::ExpandBuf* pReply) {
1872 if (IsPrimitiveTag(tag)) {
1873 expandBufAdd1(pReply, tag);
1874 if (tag == JDWP::JT_BOOLEAN || tag == JDWP::JT_BYTE) {
1875 expandBufAdd1(pReply, return_value->GetI());
1876 } else if (tag == JDWP::JT_CHAR || tag == JDWP::JT_SHORT) {
1877 expandBufAdd2BE(pReply, return_value->GetI());
1878 } else if (tag == JDWP::JT_FLOAT || tag == JDWP::JT_INT) {
1879 expandBufAdd4BE(pReply, return_value->GetI());
1880 } else if (tag == JDWP::JT_DOUBLE || tag == JDWP::JT_LONG) {
1881 expandBufAdd8BE(pReply, return_value->GetJ());
1882 } else {
1883 CHECK_EQ(tag, JDWP::JT_VOID);
1884 }
1885 } else {
Ian Rogers98379392014-02-24 16:53:16 -08001886 ScopedObjectAccessUnchecked soa(Thread::Current());
Jeff Hao579b0242013-11-18 13:16:49 -08001887 mirror::Object* value = return_value->GetL();
Ian Rogers98379392014-02-24 16:53:16 -08001888 expandBufAdd1(pReply, TagFromObject(soa, value));
Jeff Hao579b0242013-11-18 13:16:49 -08001889 expandBufAddObjectId(pReply, gRegistry->Add(value));
1890 }
1891}
1892
Ian Rogersc0542af2014-09-03 16:16:56 -07001893JDWP::JdwpError Dbg::GetThreadName(JDWP::ObjectId thread_id, std::string* name) {
jeffhaoa77f0f62012-12-05 17:19:31 -08001894 ScopedObjectAccessUnchecked soa(Thread::Current());
Ian Rogersc0542af2014-09-03 16:16:56 -07001895 JDWP::JdwpError error;
1896 Thread* thread = DecodeThread(soa, thread_id, &error);
1897 UNUSED(thread);
Elliott Hughes221229c2013-01-08 18:17:50 -08001898 if (error != JDWP::ERR_NONE && error != JDWP::ERR_THREAD_NOT_ALIVE) {
1899 return error;
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001900 }
Elliott Hughes221229c2013-01-08 18:17:50 -08001901
1902 // We still need to report the zombie threads' names, so we can't just call Thread::GetThreadName.
Ian Rogersc0542af2014-09-03 16:16:56 -07001903 mirror::Object* thread_object = gRegistry->Get<mirror::Object*>(thread_id, &error);
1904 CHECK(thread_object != nullptr) << error;
Mathieu Chartierc7853442015-03-27 14:35:38 -07001905 ArtField* java_lang_Thread_name_field =
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001906 soa.DecodeField(WellKnownClasses::java_lang_Thread_name);
1907 mirror::String* s =
1908 reinterpret_cast<mirror::String*>(java_lang_Thread_name_field->GetObject(thread_object));
Ian Rogersc0542af2014-09-03 16:16:56 -07001909 if (s != nullptr) {
1910 *name = s->ToModifiedUtf8();
Elliott Hughes221229c2013-01-08 18:17:50 -08001911 }
1912 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001913}
1914
Elliott Hughes221229c2013-01-08 18:17:50 -08001915JDWP::JdwpError Dbg::GetThreadGroup(JDWP::ObjectId thread_id, JDWP::ExpandBuf* pReply) {
Sebastien Hertza06430c2014-09-15 19:21:30 +02001916 ScopedObjectAccessUnchecked soa(Thread::Current());
Ian Rogersc0542af2014-09-03 16:16:56 -07001917 JDWP::JdwpError error;
1918 mirror::Object* thread_object = gRegistry->Get<mirror::Object*>(thread_id, &error);
1919 if (error != JDWP::ERR_NONE) {
Elliott Hughes2435a572012-02-17 16:07:41 -08001920 return JDWP::ERR_INVALID_OBJECT;
1921 }
Mathieu Chartier2d5f39e2014-09-19 17:52:37 -07001922 ScopedAssertNoThreadSuspension ants(soa.Self(), "Debugger: GetThreadGroup");
Elliott Hughes2435a572012-02-17 16:07:41 -08001923 // Okay, so it's an object, but is it actually a thread?
Sebastien Hertz69206392015-04-07 15:54:25 +02001924 Thread* thread = DecodeThread(soa, thread_id, &error);
1925 UNUSED(thread);
Elliott Hughes221229c2013-01-08 18:17:50 -08001926 if (error == JDWP::ERR_THREAD_NOT_ALIVE) {
1927 // Zombie threads are in the null group.
1928 expandBufAddObjectId(pReply, JDWP::ObjectId(0));
Sebastien Hertz52d131d2014-03-13 16:17:40 +01001929 error = JDWP::ERR_NONE;
1930 } else if (error == JDWP::ERR_NONE) {
1931 mirror::Class* c = soa.Decode<mirror::Class*>(WellKnownClasses::java_lang_Thread);
1932 CHECK(c != nullptr);
Mathieu Chartierc7853442015-03-27 14:35:38 -07001933 ArtField* f = soa.DecodeField(WellKnownClasses::java_lang_Thread_group);
Hiroshi Yamauchib5a9e3d2014-06-09 12:11:20 -07001934 CHECK(f != nullptr);
Sebastien Hertz52d131d2014-03-13 16:17:40 +01001935 mirror::Object* group = f->GetObject(thread_object);
Hiroshi Yamauchib5a9e3d2014-06-09 12:11:20 -07001936 CHECK(group != nullptr);
Sebastien Hertz52d131d2014-03-13 16:17:40 +01001937 JDWP::ObjectId thread_group_id = gRegistry->Add(group);
1938 expandBufAddObjectId(pReply, thread_group_id);
Elliott Hughes221229c2013-01-08 18:17:50 -08001939 }
Sebastien Hertz52d131d2014-03-13 16:17:40 +01001940 return error;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001941}
1942
Sebastien Hertza06430c2014-09-15 19:21:30 +02001943static mirror::Object* DecodeThreadGroup(ScopedObjectAccessUnchecked& soa,
1944 JDWP::ObjectId thread_group_id, JDWP::JdwpError* error)
Mathieu Chartier90443472015-07-16 20:32:27 -07001945 SHARED_REQUIRES(Locks::mutator_lock_) {
Sebastien Hertz6995c602014-09-09 12:10:13 +02001946 mirror::Object* thread_group = Dbg::GetObjectRegistry()->Get<mirror::Object*>(thread_group_id,
1947 error);
Sebastien Hertza06430c2014-09-15 19:21:30 +02001948 if (*error != JDWP::ERR_NONE) {
1949 return nullptr;
1950 }
1951 if (thread_group == nullptr) {
1952 *error = JDWP::ERR_INVALID_OBJECT;
1953 return nullptr;
1954 }
Ian Rogers98379392014-02-24 16:53:16 -08001955 mirror::Class* c = soa.Decode<mirror::Class*>(WellKnownClasses::java_lang_ThreadGroup);
1956 CHECK(c != nullptr);
Sebastien Hertza06430c2014-09-15 19:21:30 +02001957 if (!c->IsAssignableFrom(thread_group->GetClass())) {
1958 // This is not a java.lang.ThreadGroup.
1959 *error = JDWP::ERR_INVALID_THREAD_GROUP;
1960 return nullptr;
1961 }
1962 *error = JDWP::ERR_NONE;
1963 return thread_group;
1964}
1965
1966JDWP::JdwpError Dbg::GetThreadGroupName(JDWP::ObjectId thread_group_id, JDWP::ExpandBuf* pReply) {
1967 ScopedObjectAccessUnchecked soa(Thread::Current());
1968 JDWP::JdwpError error;
1969 mirror::Object* thread_group = DecodeThreadGroup(soa, thread_group_id, &error);
1970 if (error != JDWP::ERR_NONE) {
1971 return error;
1972 }
Mathieu Chartier2d5f39e2014-09-19 17:52:37 -07001973 ScopedAssertNoThreadSuspension ants(soa.Self(), "Debugger: GetThreadGroupName");
Mathieu Chartierc7853442015-03-27 14:35:38 -07001974 ArtField* f = soa.DecodeField(WellKnownClasses::java_lang_ThreadGroup_name);
Ian Rogersc0542af2014-09-03 16:16:56 -07001975 CHECK(f != nullptr);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001976 mirror::String* s = reinterpret_cast<mirror::String*>(f->GetObject(thread_group));
Sebastien Hertza06430c2014-09-15 19:21:30 +02001977
1978 std::string thread_group_name(s->ToModifiedUtf8());
1979 expandBufAddUtf8String(pReply, thread_group_name);
1980 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001981}
1982
Sebastien Hertza06430c2014-09-15 19:21:30 +02001983JDWP::JdwpError Dbg::GetThreadGroupParent(JDWP::ObjectId thread_group_id, JDWP::ExpandBuf* pReply) {
Ian Rogers98379392014-02-24 16:53:16 -08001984 ScopedObjectAccessUnchecked soa(Thread::Current());
Ian Rogersc0542af2014-09-03 16:16:56 -07001985 JDWP::JdwpError error;
Sebastien Hertza06430c2014-09-15 19:21:30 +02001986 mirror::Object* thread_group = DecodeThreadGroup(soa, thread_group_id, &error);
1987 if (error != JDWP::ERR_NONE) {
1988 return error;
1989 }
Mathieu Chartier2d5f39e2014-09-19 17:52:37 -07001990 mirror::Object* parent;
1991 {
1992 ScopedAssertNoThreadSuspension ants(soa.Self(), "Debugger: GetThreadGroupParent");
Mathieu Chartierc7853442015-03-27 14:35:38 -07001993 ArtField* f = soa.DecodeField(WellKnownClasses::java_lang_ThreadGroup_parent);
Mathieu Chartier2d5f39e2014-09-19 17:52:37 -07001994 CHECK(f != nullptr);
1995 parent = f->GetObject(thread_group);
1996 }
Sebastien Hertza06430c2014-09-15 19:21:30 +02001997 JDWP::ObjectId parent_group_id = gRegistry->Add(parent);
1998 expandBufAddObjectId(pReply, parent_group_id);
1999 return JDWP::ERR_NONE;
2000}
2001
2002static void GetChildThreadGroups(ScopedObjectAccessUnchecked& soa, mirror::Object* thread_group,
2003 std::vector<JDWP::ObjectId>* child_thread_group_ids)
Mathieu Chartier90443472015-07-16 20:32:27 -07002004 SHARED_REQUIRES(Locks::mutator_lock_) {
Sebastien Hertza06430c2014-09-15 19:21:30 +02002005 CHECK(thread_group != nullptr);
2006
2007 // Get the ArrayList<ThreadGroup> "groups" out of this thread group...
Mathieu Chartierc7853442015-03-27 14:35:38 -07002008 ArtField* groups_field = soa.DecodeField(WellKnownClasses::java_lang_ThreadGroup_groups);
Sebastien Hertza06430c2014-09-15 19:21:30 +02002009 mirror::Object* groups_array_list = groups_field->GetObject(thread_group);
Sebastien Hertze49e1952014-10-13 11:27:13 +02002010 {
2011 // The "groups" field is declared as a java.util.List: check it really is
2012 // an instance of java.util.ArrayList.
2013 CHECK(groups_array_list != nullptr);
2014 mirror::Class* java_util_ArrayList_class =
2015 soa.Decode<mirror::Class*>(WellKnownClasses::java_util_ArrayList);
2016 CHECK(groups_array_list->InstanceOf(java_util_ArrayList_class));
2017 }
Sebastien Hertza06430c2014-09-15 19:21:30 +02002018
2019 // Get the array and size out of the ArrayList<ThreadGroup>...
Mathieu Chartierc7853442015-03-27 14:35:38 -07002020 ArtField* array_field = soa.DecodeField(WellKnownClasses::java_util_ArrayList_array);
2021 ArtField* size_field = soa.DecodeField(WellKnownClasses::java_util_ArrayList_size);
Sebastien Hertza06430c2014-09-15 19:21:30 +02002022 mirror::ObjectArray<mirror::Object>* groups_array =
2023 array_field->GetObject(groups_array_list)->AsObjectArray<mirror::Object>();
2024 const int32_t size = size_field->GetInt(groups_array_list);
2025
2026 // Copy the first 'size' elements out of the array into the result.
Sebastien Hertz6995c602014-09-09 12:10:13 +02002027 ObjectRegistry* registry = Dbg::GetObjectRegistry();
Sebastien Hertza06430c2014-09-15 19:21:30 +02002028 for (int32_t i = 0; i < size; ++i) {
Sebastien Hertz6995c602014-09-09 12:10:13 +02002029 child_thread_group_ids->push_back(registry->Add(groups_array->Get(i)));
Sebastien Hertza06430c2014-09-15 19:21:30 +02002030 }
2031}
2032
2033JDWP::JdwpError Dbg::GetThreadGroupChildren(JDWP::ObjectId thread_group_id,
2034 JDWP::ExpandBuf* pReply) {
2035 ScopedObjectAccessUnchecked soa(Thread::Current());
2036 JDWP::JdwpError error;
2037 mirror::Object* thread_group = DecodeThreadGroup(soa, thread_group_id, &error);
2038 if (error != JDWP::ERR_NONE) {
2039 return error;
2040 }
2041
2042 // Add child threads.
2043 {
2044 std::vector<JDWP::ObjectId> child_thread_ids;
2045 GetThreads(thread_group, &child_thread_ids);
2046 expandBufAdd4BE(pReply, child_thread_ids.size());
2047 for (JDWP::ObjectId child_thread_id : child_thread_ids) {
2048 expandBufAddObjectId(pReply, child_thread_id);
2049 }
2050 }
2051
2052 // Add child thread groups.
2053 {
2054 std::vector<JDWP::ObjectId> child_thread_groups_ids;
2055 GetChildThreadGroups(soa, thread_group, &child_thread_groups_ids);
2056 expandBufAdd4BE(pReply, child_thread_groups_ids.size());
2057 for (JDWP::ObjectId child_thread_group_id : child_thread_groups_ids) {
2058 expandBufAddObjectId(pReply, child_thread_group_id);
2059 }
2060 }
2061
2062 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002063}
2064
2065JDWP::ObjectId Dbg::GetSystemThreadGroupId() {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002066 ScopedObjectAccessUnchecked soa(Thread::Current());
Mathieu Chartierc7853442015-03-27 14:35:38 -07002067 ArtField* f = soa.DecodeField(WellKnownClasses::java_lang_ThreadGroup_systemThreadGroup);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002068 mirror::Object* group = f->GetObject(f->GetDeclaringClass());
Ian Rogers365c1022012-06-22 15:05:28 -07002069 return gRegistry->Add(group);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002070}
2071
Jeff Hao920af3e2013-08-28 15:46:38 -07002072JDWP::JdwpThreadStatus Dbg::ToJdwpThreadStatus(ThreadState state) {
2073 switch (state) {
2074 case kBlocked:
2075 return JDWP::TS_MONITOR;
2076 case kNative:
2077 case kRunnable:
2078 case kSuspended:
2079 return JDWP::TS_RUNNING;
2080 case kSleeping:
2081 return JDWP::TS_SLEEPING;
2082 case kStarting:
2083 case kTerminated:
2084 return JDWP::TS_ZOMBIE;
2085 case kTimedWaiting:
Sebastien Hertzbae182c2013-12-17 10:42:03 +01002086 case kWaitingForCheckPointsToRun:
Jeff Hao920af3e2013-08-28 15:46:38 -07002087 case kWaitingForDebuggerSend:
2088 case kWaitingForDebuggerSuspension:
2089 case kWaitingForDebuggerToAttach:
Sebastien Hertz138dbfc2013-12-04 18:15:25 +01002090 case kWaitingForDeoptimization:
Jeff Hao920af3e2013-08-28 15:46:38 -07002091 case kWaitingForGcToComplete:
Mathieu Chartierb43390c2015-05-12 10:47:11 -07002092 case kWaitingForGetObjectsAllocated:
Jeff Hao920af3e2013-08-28 15:46:38 -07002093 case kWaitingForJniOnLoad:
Sebastien Hertzbae182c2013-12-17 10:42:03 +01002094 case kWaitingForMethodTracingStart:
Jeff Hao920af3e2013-08-28 15:46:38 -07002095 case kWaitingForSignalCatcherOutput:
Hiroshi Yamauchi0c8c3032015-01-16 16:54:35 -08002096 case kWaitingForVisitObjects:
Jeff Hao920af3e2013-08-28 15:46:38 -07002097 case kWaitingInMainDebuggerLoop:
2098 case kWaitingInMainSignalCatcherLoop:
2099 case kWaitingPerformingGc:
Mathieu Chartier90ef3db2015-08-04 15:19:41 -07002100 case kWaitingWeakGcRootRead:
Hiroshi Yamauchi76f55b02015-08-21 16:10:39 -07002101 case kWaitingForGcThreadFlip:
Jeff Hao920af3e2013-08-28 15:46:38 -07002102 case kWaiting:
2103 return JDWP::TS_WAIT;
2104 // Don't add a 'default' here so the compiler can spot incompatible enum changes.
2105 }
2106 LOG(FATAL) << "Unknown thread state: " << state;
2107 return JDWP::TS_ZOMBIE;
2108}
2109
Sebastien Hertz52d131d2014-03-13 16:17:40 +01002110JDWP::JdwpError Dbg::GetThreadStatus(JDWP::ObjectId thread_id, JDWP::JdwpThreadStatus* pThreadStatus,
2111 JDWP::JdwpSuspendStatus* pSuspendStatus) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002112 ScopedObjectAccess soa(Thread::Current());
Elliott Hughes499c5132011-11-17 14:55:11 -08002113
Elliott Hughes9e0c1752013-01-09 14:02:58 -08002114 *pSuspendStatus = JDWP::SUSPEND_STATUS_NOT_SUSPENDED;
2115
Ian Rogersc0542af2014-09-03 16:16:56 -07002116 JDWP::JdwpError error;
2117 Thread* thread = DecodeThread(soa, thread_id, &error);
Elliott Hughes221229c2013-01-08 18:17:50 -08002118 if (error != JDWP::ERR_NONE) {
2119 if (error == JDWP::ERR_THREAD_NOT_ALIVE) {
2120 *pThreadStatus = JDWP::TS_ZOMBIE;
Elliott Hughes221229c2013-01-08 18:17:50 -08002121 return JDWP::ERR_NONE;
2122 }
2123 return error;
Elliott Hughes499c5132011-11-17 14:55:11 -08002124 }
2125
Elliott Hughes9e0c1752013-01-09 14:02:58 -08002126 if (IsSuspendedForDebugger(soa, thread)) {
2127 *pSuspendStatus = JDWP::SUSPEND_STATUS_SUSPENDED;
Elliott Hughes499c5132011-11-17 14:55:11 -08002128 }
2129
Jeff Hao920af3e2013-08-28 15:46:38 -07002130 *pThreadStatus = ToJdwpThreadStatus(thread->GetState());
Elliott Hughes221229c2013-01-08 18:17:50 -08002131 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002132}
2133
Elliott Hughes221229c2013-01-08 18:17:50 -08002134JDWP::JdwpError Dbg::GetThreadDebugSuspendCount(JDWP::ObjectId thread_id, JDWP::ExpandBuf* pReply) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002135 ScopedObjectAccess soa(Thread::Current());
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 return error;
Elliott Hughes2435a572012-02-17 16:07:41 -08002140 }
Ian Rogers50b35e22012-10-04 10:09:15 -07002141 MutexLock mu2(soa.Self(), *Locks::thread_suspend_count_lock_);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002142 expandBufAdd4BE(pReply, thread->GetDebugSuspendCount());
Elliott Hughes2435a572012-02-17 16:07:41 -08002143 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002144}
2145
Elliott Hughesf9501702013-01-11 11:22:27 -08002146JDWP::JdwpError Dbg::Interrupt(JDWP::ObjectId thread_id) {
2147 ScopedObjectAccess soa(Thread::Current());
Ian Rogersc0542af2014-09-03 16:16:56 -07002148 JDWP::JdwpError error;
2149 Thread* thread = DecodeThread(soa, thread_id, &error);
Elliott Hughesf9501702013-01-11 11:22:27 -08002150 if (error != JDWP::ERR_NONE) {
2151 return error;
2152 }
Ian Rogersdd7624d2014-03-14 17:43:00 -07002153 thread->Interrupt(soa.Self());
Elliott Hughesf9501702013-01-11 11:22:27 -08002154 return JDWP::ERR_NONE;
2155}
2156
Sebastien Hertz070f7322014-09-09 12:08:49 +02002157static bool IsInDesiredThreadGroup(ScopedObjectAccessUnchecked& soa,
2158 mirror::Object* desired_thread_group, mirror::Object* peer)
Mathieu Chartier90443472015-07-16 20:32:27 -07002159 SHARED_REQUIRES(Locks::mutator_lock_) {
Sebastien Hertz070f7322014-09-09 12:08:49 +02002160 // Do we want threads from all thread groups?
2161 if (desired_thread_group == nullptr) {
2162 return true;
2163 }
Mathieu Chartierc7853442015-03-27 14:35:38 -07002164 ArtField* thread_group_field = soa.DecodeField(WellKnownClasses::java_lang_Thread_group);
Sebastien Hertz070f7322014-09-09 12:08:49 +02002165 DCHECK(thread_group_field != nullptr);
2166 mirror::Object* group = thread_group_field->GetObject(peer);
2167 return (group == desired_thread_group);
2168}
2169
Sebastien Hertza06430c2014-09-15 19:21:30 +02002170void Dbg::GetThreads(mirror::Object* thread_group, std::vector<JDWP::ObjectId>* thread_ids) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002171 ScopedObjectAccessUnchecked soa(Thread::Current());
Sebastien Hertz070f7322014-09-09 12:08:49 +02002172 std::list<Thread*> all_threads_list;
2173 {
2174 MutexLock mu(Thread::Current(), *Locks::thread_list_lock_);
2175 all_threads_list = Runtime::Current()->GetThreadList()->GetList();
2176 }
2177 for (Thread* t : all_threads_list) {
2178 if (t == Dbg::GetDebugThread()) {
2179 // Skip the JDWP thread. Some debuggers get bent out of shape when they can't suspend and
2180 // query all threads, so it's easier if we just don't tell them about this thread.
2181 continue;
2182 }
2183 if (t->IsStillStarting()) {
2184 // This thread is being started (and has been registered in the thread list). However, it is
2185 // not completely started yet so we must ignore it.
2186 continue;
2187 }
2188 mirror::Object* peer = t->GetPeer();
2189 if (peer == nullptr) {
Mathieu Chartier2cebb242015-04-21 16:50:40 -07002190 // 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 +02002191 // this thread yet.
2192 // TODO: if we identified threads to the debugger by their Thread*
2193 // rather than their peer's mirror::Object*, we could fix this.
2194 // Doing so might help us report ZOMBIE threads too.
2195 continue;
2196 }
2197 if (IsInDesiredThreadGroup(soa, thread_group, peer)) {
2198 thread_ids->push_back(gRegistry->Add(peer));
2199 }
2200 }
Elliott Hughescaf76542012-06-28 16:08:22 -07002201}
Elliott Hughesa2155262011-11-16 16:26:58 -08002202
Mathieu Chartier90443472015-07-16 20:32:27 -07002203static int GetStackDepth(Thread* thread) SHARED_REQUIRES(Locks::mutator_lock_) {
Ian Rogers0399dde2012-06-06 17:09:28 -07002204 struct CountStackDepthVisitor : public StackVisitor {
Andreas Gampe277ccbd2014-11-03 21:36:10 -08002205 explicit CountStackDepthVisitor(Thread* thread_in)
Nicolas Geoffray8e5bd182015-05-06 11:34:34 +01002206 : StackVisitor(thread_in, nullptr, StackVisitor::StackWalkKind::kIncludeInlinedFrames),
2207 depth(0) {}
Ian Rogers0399dde2012-06-06 17:09:28 -07002208
Elliott Hughes64f574f2013-02-20 14:57:12 -08002209 // TODO: Enable annotalysis. We know lock is held in constructor, but abstraction confuses
2210 // annotalysis.
2211 bool VisitFrame() NO_THREAD_SAFETY_ANALYSIS {
Ian Rogers0399dde2012-06-06 17:09:28 -07002212 if (!GetMethod()->IsRuntimeMethod()) {
Elliott Hughesf8a2df72011-12-01 12:19:54 -08002213 ++depth;
2214 }
Elliott Hughes530fa002012-03-12 11:44:49 -07002215 return true;
Elliott Hughesa2e54f62011-11-17 13:01:30 -08002216 }
2217 size_t depth;
2218 };
Elliott Hughes08fc03a2012-06-26 17:34:00 -07002219
Ian Rogers7a22fa62013-01-23 12:16:16 -08002220 CountStackDepthVisitor visitor(thread);
Ian Rogers0399dde2012-06-06 17:09:28 -07002221 visitor.WalkStack();
Elliott Hughesa2e54f62011-11-17 13:01:30 -08002222 return visitor.depth;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002223}
2224
Ian Rogersc0542af2014-09-03 16:16:56 -07002225JDWP::JdwpError Dbg::GetThreadFrameCount(JDWP::ObjectId thread_id, size_t* result) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002226 ScopedObjectAccess soa(Thread::Current());
Ian Rogersc0542af2014-09-03 16:16:56 -07002227 JDWP::JdwpError error;
2228 *result = 0;
2229 Thread* thread = DecodeThread(soa, thread_id, &error);
Elliott Hughes221229c2013-01-08 18:17:50 -08002230 if (error != JDWP::ERR_NONE) {
2231 return error;
2232 }
Elliott Hughesf15f4a02013-01-09 10:09:38 -08002233 if (!IsSuspendedForDebugger(soa, thread)) {
2234 return JDWP::ERR_THREAD_NOT_SUSPENDED;
2235 }
Ian Rogersc0542af2014-09-03 16:16:56 -07002236 *result = GetStackDepth(thread);
Elliott Hughes221229c2013-01-08 18:17:50 -08002237 return JDWP::ERR_NONE;
Elliott Hughes86964332012-02-15 19:37:42 -08002238}
2239
Ian Rogers306057f2012-11-26 12:45:53 -08002240JDWP::JdwpError Dbg::GetThreadFrames(JDWP::ObjectId thread_id, size_t start_frame,
2241 size_t frame_count, JDWP::ExpandBuf* buf) {
Elliott Hughes6e9d22c2012-06-22 15:02:37 -07002242 class GetFrameVisitor : public StackVisitor {
2243 public:
Andreas Gampe277ccbd2014-11-03 21:36:10 -08002244 GetFrameVisitor(Thread* thread, size_t start_frame_in, size_t frame_count_in,
2245 JDWP::ExpandBuf* buf_in)
Mathieu Chartier90443472015-07-16 20:32:27 -07002246 SHARED_REQUIRES(Locks::mutator_lock_)
Nicolas Geoffray8e5bd182015-05-06 11:34:34 +01002247 : StackVisitor(thread, nullptr, StackVisitor::StackWalkKind::kIncludeInlinedFrames),
2248 depth_(0),
2249 start_frame_(start_frame_in),
2250 frame_count_(frame_count_in),
2251 buf_(buf_in) {
Elliott Hughes6e9d22c2012-06-22 15:02:37 -07002252 expandBufAdd4BE(buf_, frame_count_);
Elliott Hughes03181a82011-11-17 17:22:21 -08002253 }
Ian Rogers0399dde2012-06-06 17:09:28 -07002254
Mathieu Chartier90443472015-07-16 20:32:27 -07002255 bool VisitFrame() OVERRIDE SHARED_REQUIRES(Locks::mutator_lock_) {
Ian Rogers0399dde2012-06-06 17:09:28 -07002256 if (GetMethod()->IsRuntimeMethod()) {
Brian Carlstrom7934ac22013-07-26 10:54:15 -07002257 return true; // The debugger can't do anything useful with a frame that has no Method*.
Elliott Hughes03181a82011-11-17 17:22:21 -08002258 }
Elliott Hughes6e9d22c2012-06-22 15:02:37 -07002259 if (depth_ >= start_frame_ + frame_count_) {
Elliott Hughes530fa002012-03-12 11:44:49 -07002260 return false;
Elliott Hughes03181a82011-11-17 17:22:21 -08002261 }
Elliott Hughes6e9d22c2012-06-22 15:02:37 -07002262 if (depth_ >= start_frame_) {
2263 JDWP::FrameId frame_id(GetFrameId());
2264 JDWP::JdwpLocation location;
Sebastien Hertz6995c602014-09-09 12:10:13 +02002265 SetJdwpLocation(&location, GetMethod(), GetDexPc());
Ian Rogersef7d42f2014-01-06 12:55:46 -08002266 VLOG(jdwp) << StringPrintf(" Frame %3zd: id=%3" PRIu64 " ", depth_, frame_id) << location;
Elliott Hughes6e9d22c2012-06-22 15:02:37 -07002267 expandBufAdd8BE(buf_, frame_id);
2268 expandBufAddLocation(buf_, location);
2269 }
2270 ++depth_;
Elliott Hughes530fa002012-03-12 11:44:49 -07002271 return true;
Elliott Hughes03181a82011-11-17 17:22:21 -08002272 }
Elliott Hughes6e9d22c2012-06-22 15:02:37 -07002273
2274 private:
2275 size_t depth_;
2276 const size_t start_frame_;
2277 const size_t frame_count_;
2278 JDWP::ExpandBuf* buf_;
Elliott Hughes03181a82011-11-17 17:22:21 -08002279 };
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002280
2281 ScopedObjectAccessUnchecked soa(Thread::Current());
Ian Rogersc0542af2014-09-03 16:16:56 -07002282 JDWP::JdwpError error;
2283 Thread* thread = DecodeThread(soa, thread_id, &error);
Elliott Hughes221229c2013-01-08 18:17:50 -08002284 if (error != JDWP::ERR_NONE) {
2285 return error;
2286 }
Elliott Hughesf15f4a02013-01-09 10:09:38 -08002287 if (!IsSuspendedForDebugger(soa, thread)) {
2288 return JDWP::ERR_THREAD_NOT_SUSPENDED;
2289 }
Ian Rogers7a22fa62013-01-23 12:16:16 -08002290 GetFrameVisitor visitor(thread, start_frame, frame_count, buf);
Ian Rogers0399dde2012-06-06 17:09:28 -07002291 visitor.WalkStack();
Elliott Hughes6e9d22c2012-06-22 15:02:37 -07002292 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002293}
2294
2295JDWP::ObjectId Dbg::GetThreadSelfId() {
Sebastien Hertz6995c602014-09-09 12:10:13 +02002296 return GetThreadId(Thread::Current());
2297}
2298
2299JDWP::ObjectId Dbg::GetThreadId(Thread* thread) {
Mathieu Chartierdbe6f462012-09-25 16:54:50 -07002300 ScopedObjectAccessUnchecked soa(Thread::Current());
Sebastien Hertz6995c602014-09-09 12:10:13 +02002301 return gRegistry->Add(thread->GetPeer());
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002302}
2303
Elliott Hughes475fc232011-10-25 15:00:35 -07002304void Dbg::SuspendVM() {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002305 Runtime::Current()->GetThreadList()->SuspendAllForDebugger();
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002306}
2307
2308void Dbg::ResumeVM() {
Sebastien Hertz253fa552014-10-14 17:27:15 +02002309 Runtime::Current()->GetThreadList()->ResumeAllForDebugger();
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002310}
2311
Elliott Hughes221229c2013-01-08 18:17:50 -08002312JDWP::JdwpError Dbg::SuspendThread(JDWP::ObjectId thread_id, bool request_suspension) {
Ian Rogersf3d874c2014-07-17 18:52:42 -07002313 Thread* self = Thread::Current();
Ian Rogersc0542af2014-09-03 16:16:56 -07002314 ScopedLocalRef<jobject> peer(self->GetJniEnv(), nullptr);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002315 {
Ian Rogersf3d874c2014-07-17 18:52:42 -07002316 ScopedObjectAccess soa(self);
Ian Rogersc0542af2014-09-03 16:16:56 -07002317 JDWP::JdwpError error;
2318 peer.reset(soa.AddLocalReference<jobject>(gRegistry->Get<mirror::Object*>(thread_id, &error)));
Elliott Hughes4e235312011-12-02 11:34:15 -08002319 }
Ian Rogersc0542af2014-09-03 16:16:56 -07002320 if (peer.get() == nullptr) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002321 return JDWP::ERR_THREAD_NOT_ALIVE;
2322 }
Ian Rogers4ad5cd32014-11-11 23:08:07 -08002323 // Suspend thread to build stack trace.
Elliott Hughesf327e072013-01-09 16:01:26 -08002324 bool timed_out;
Brian Carlstromba32de42014-08-27 23:43:46 -07002325 ThreadList* thread_list = Runtime::Current()->GetThreadList();
2326 Thread* thread = thread_list->SuspendThreadByPeer(peer.get(), request_suspension, true,
2327 &timed_out);
Ian Rogersc0542af2014-09-03 16:16:56 -07002328 if (thread != nullptr) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002329 return JDWP::ERR_NONE;
Elliott Hughesf327e072013-01-09 16:01:26 -08002330 } else if (timed_out) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002331 return JDWP::ERR_INTERNAL;
2332 } else {
2333 return JDWP::ERR_THREAD_NOT_ALIVE;
2334 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002335}
2336
Elliott Hughes221229c2013-01-08 18:17:50 -08002337void Dbg::ResumeThread(JDWP::ObjectId thread_id) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002338 ScopedObjectAccessUnchecked soa(Thread::Current());
Ian Rogersc0542af2014-09-03 16:16:56 -07002339 JDWP::JdwpError error;
2340 mirror::Object* peer = gRegistry->Get<mirror::Object*>(thread_id, &error);
2341 CHECK(peer != nullptr) << error;
jeffhaoa77f0f62012-12-05 17:19:31 -08002342 Thread* thread;
2343 {
2344 MutexLock mu(soa.Self(), *Locks::thread_list_lock_);
2345 thread = Thread::FromManagedThread(soa, peer);
2346 }
Ian Rogersc0542af2014-09-03 16:16:56 -07002347 if (thread == nullptr) {
Elliott Hughes4e235312011-12-02 11:34:15 -08002348 LOG(WARNING) << "No such thread for resume: " << peer;
2349 return;
2350 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002351 bool needs_resume;
2352 {
Ian Rogers50b35e22012-10-04 10:09:15 -07002353 MutexLock mu2(soa.Self(), *Locks::thread_suspend_count_lock_);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002354 needs_resume = thread->GetSuspendCount() > 0;
2355 }
2356 if (needs_resume) {
Elliott Hughes546b9862012-06-20 16:06:13 -07002357 Runtime::Current()->GetThreadList()->Resume(thread, true);
2358 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002359}
2360
2361void Dbg::SuspendSelf() {
Elliott Hughes475fc232011-10-25 15:00:35 -07002362 Runtime::Current()->GetThreadList()->SuspendSelfForDebugger();
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002363}
2364
Ian Rogers0399dde2012-06-06 17:09:28 -07002365struct GetThisVisitor : public StackVisitor {
Andreas Gampe277ccbd2014-11-03 21:36:10 -08002366 GetThisVisitor(Thread* thread, Context* context, JDWP::FrameId frame_id_in)
Mathieu Chartier90443472015-07-16 20:32:27 -07002367 SHARED_REQUIRES(Locks::mutator_lock_)
Nicolas Geoffray8e5bd182015-05-06 11:34:34 +01002368 : StackVisitor(thread, context, StackVisitor::StackWalkKind::kIncludeInlinedFrames),
2369 this_object(nullptr),
2370 frame_id(frame_id_in) {}
Ian Rogers0399dde2012-06-06 17:09:28 -07002371
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002372 // TODO: Enable annotalysis. We know lock is held in constructor, but abstraction confuses
2373 // annotalysis.
2374 virtual bool VisitFrame() NO_THREAD_SAFETY_ANALYSIS {
Elliott Hughes6e9d22c2012-06-22 15:02:37 -07002375 if (frame_id != GetFrameId()) {
Ian Rogers0399dde2012-06-06 17:09:28 -07002376 return true; // continue
Ian Rogers0399dde2012-06-06 17:09:28 -07002377 } else {
Ian Rogers62d6c772013-02-27 08:32:07 -08002378 this_object = GetThisObject();
2379 return false;
Ian Rogers0399dde2012-06-06 17:09:28 -07002380 }
Elliott Hughes86b00102011-12-05 17:54:26 -08002381 }
Ian Rogers0399dde2012-06-06 17:09:28 -07002382
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002383 mirror::Object* this_object;
Elliott Hughes6e9d22c2012-06-22 15:02:37 -07002384 JDWP::FrameId frame_id;
Ian Rogers0399dde2012-06-06 17:09:28 -07002385};
2386
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002387JDWP::JdwpError Dbg::GetThisObject(JDWP::ObjectId thread_id, JDWP::FrameId frame_id,
2388 JDWP::ObjectId* result) {
2389 ScopedObjectAccessUnchecked soa(Thread::Current());
Sebastien Hertz69206392015-04-07 15:54:25 +02002390 JDWP::JdwpError error;
2391 Thread* thread = DecodeThread(soa, thread_id, &error);
2392 if (error != JDWP::ERR_NONE) {
2393 return error;
2394 }
2395 if (!IsSuspendedForDebugger(soa, thread)) {
2396 return JDWP::ERR_THREAD_NOT_SUSPENDED;
Elliott Hughes6e9d22c2012-06-22 15:02:37 -07002397 }
Ian Rogers700a4022014-05-19 16:49:03 -07002398 std::unique_ptr<Context> context(Context::Create());
Ian Rogers7a22fa62013-01-23 12:16:16 -08002399 GetThisVisitor visitor(thread, context.get(), frame_id);
Ian Rogers0399dde2012-06-06 17:09:28 -07002400 visitor.WalkStack();
Elliott Hughes6e9d22c2012-06-22 15:02:37 -07002401 *result = gRegistry->Add(visitor.this_object);
2402 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002403}
2404
Sebastien Hertz8009f392014-09-01 17:07:11 +02002405// Walks the stack until we find the frame with the given FrameId.
2406class FindFrameVisitor FINAL : public StackVisitor {
2407 public:
2408 FindFrameVisitor(Thread* thread, Context* context, JDWP::FrameId frame_id)
Mathieu Chartier90443472015-07-16 20:32:27 -07002409 SHARED_REQUIRES(Locks::mutator_lock_)
Nicolas Geoffray8e5bd182015-05-06 11:34:34 +01002410 : StackVisitor(thread, context, StackVisitor::StackWalkKind::kIncludeInlinedFrames),
2411 frame_id_(frame_id),
2412 error_(JDWP::ERR_INVALID_FRAMEID) {}
Ian Rogersca190662012-06-26 15:45:57 -07002413
Sebastien Hertz8009f392014-09-01 17:07:11 +02002414 // TODO: Enable annotalysis. We know lock is held in constructor, but abstraction confuses
2415 // annotalysis.
2416 bool VisitFrame() NO_THREAD_SAFETY_ANALYSIS {
2417 if (GetFrameId() != frame_id_) {
2418 return true; // Not our frame, carry on.
Ian Rogers0399dde2012-06-06 17:09:28 -07002419 }
Mathieu Chartiere401d142015-04-22 13:56:20 -07002420 ArtMethod* m = GetMethod();
Sebastien Hertz8009f392014-09-01 17:07:11 +02002421 if (m->IsNative()) {
2422 // We can't read/write local value from/into native method.
2423 error_ = JDWP::ERR_OPAQUE_FRAME;
2424 } else {
2425 // We found our frame.
2426 error_ = JDWP::ERR_NONE;
2427 }
2428 return false;
2429 }
2430
2431 JDWP::JdwpError GetError() const {
2432 return error_;
2433 }
2434
2435 private:
2436 const JDWP::FrameId frame_id_;
2437 JDWP::JdwpError error_;
2438};
2439
2440JDWP::JdwpError Dbg::GetLocalValues(JDWP::Request* request, JDWP::ExpandBuf* pReply) {
2441 JDWP::ObjectId thread_id = request->ReadThreadId();
2442 JDWP::FrameId frame_id = request->ReadFrameId();
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002443
2444 ScopedObjectAccessUnchecked soa(Thread::Current());
Sebastien Hertz69206392015-04-07 15:54:25 +02002445 JDWP::JdwpError error;
2446 Thread* thread = DecodeThread(soa, thread_id, &error);
2447 if (error != JDWP::ERR_NONE) {
2448 return error;
2449 }
2450 if (!IsSuspendedForDebugger(soa, thread)) {
2451 return JDWP::ERR_THREAD_NOT_SUSPENDED;
Elliott Hughes221229c2013-01-08 18:17:50 -08002452 }
Sebastien Hertz8009f392014-09-01 17:07:11 +02002453 // Find the frame with the given frame_id.
Ian Rogers700a4022014-05-19 16:49:03 -07002454 std::unique_ptr<Context> context(Context::Create());
Sebastien Hertz8009f392014-09-01 17:07:11 +02002455 FindFrameVisitor visitor(thread, context.get(), frame_id);
Ian Rogers0399dde2012-06-06 17:09:28 -07002456 visitor.WalkStack();
Sebastien Hertz8009f392014-09-01 17:07:11 +02002457 if (visitor.GetError() != JDWP::ERR_NONE) {
2458 return visitor.GetError();
2459 }
2460
2461 // Read the values from visitor's context.
2462 int32_t slot_count = request->ReadSigned32("slot count");
2463 expandBufAdd4BE(pReply, slot_count); /* "int values" */
2464 for (int32_t i = 0; i < slot_count; ++i) {
2465 uint32_t slot = request->ReadUnsigned32("slot");
2466 JDWP::JdwpTag reqSigByte = request->ReadTag();
2467
2468 VLOG(jdwp) << " --> slot " << slot << " " << reqSigByte;
2469
2470 size_t width = Dbg::GetTagWidth(reqSigByte);
Sebastien Hertz7d955652014-10-22 10:57:10 +02002471 uint8_t* ptr = expandBufAddSpace(pReply, width + 1);
Sebastien Hertz69206392015-04-07 15:54:25 +02002472 error = Dbg::GetLocalValue(visitor, soa, slot, reqSigByte, ptr, width);
Sebastien Hertz8009f392014-09-01 17:07:11 +02002473 if (error != JDWP::ERR_NONE) {
2474 return error;
2475 }
2476 }
2477 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002478}
2479
Sebastien Hertzabbabc82015-03-26 08:47:47 +01002480constexpr JDWP::JdwpError kStackFrameLocalAccessError = JDWP::ERR_ABSENT_INFORMATION;
2481
2482static std::string GetStackContextAsString(const StackVisitor& visitor)
Mathieu Chartier90443472015-07-16 20:32:27 -07002483 SHARED_REQUIRES(Locks::mutator_lock_) {
Sebastien Hertzabbabc82015-03-26 08:47:47 +01002484 return StringPrintf(" at DEX pc 0x%08x in method %s", visitor.GetDexPc(false),
2485 PrettyMethod(visitor.GetMethod()).c_str());
2486}
2487
2488static JDWP::JdwpError FailGetLocalValue(const StackVisitor& visitor, uint16_t vreg,
2489 JDWP::JdwpTag tag)
Mathieu Chartier90443472015-07-16 20:32:27 -07002490 SHARED_REQUIRES(Locks::mutator_lock_) {
Sebastien Hertzabbabc82015-03-26 08:47:47 +01002491 LOG(ERROR) << "Failed to read " << tag << " local from register v" << vreg
2492 << GetStackContextAsString(visitor);
2493 return kStackFrameLocalAccessError;
2494}
2495
Sebastien Hertz8009f392014-09-01 17:07:11 +02002496JDWP::JdwpError Dbg::GetLocalValue(const StackVisitor& visitor, ScopedObjectAccessUnchecked& soa,
2497 int slot, JDWP::JdwpTag tag, uint8_t* buf, size_t width) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07002498 ArtMethod* m = visitor.GetMethod();
Sebastien Hertzabbabc82015-03-26 08:47:47 +01002499 JDWP::JdwpError error = JDWP::ERR_NONE;
2500 uint16_t vreg = DemangleSlot(slot, m, &error);
2501 if (error != JDWP::ERR_NONE) {
2502 return error;
2503 }
Sebastien Hertz8009f392014-09-01 17:07:11 +02002504 // TODO: check that the tag is compatible with the actual type of the slot!
Sebastien Hertz8009f392014-09-01 17:07:11 +02002505 switch (tag) {
2506 case JDWP::JT_BOOLEAN: {
2507 CHECK_EQ(width, 1U);
2508 uint32_t intVal;
Sebastien Hertzabbabc82015-03-26 08:47:47 +01002509 if (!visitor.GetVReg(m, vreg, kIntVReg, &intVal)) {
2510 return FailGetLocalValue(visitor, vreg, tag);
Ian Rogers0399dde2012-06-06 17:09:28 -07002511 }
Sebastien Hertzabbabc82015-03-26 08:47:47 +01002512 VLOG(jdwp) << "get boolean local " << vreg << " = " << intVal;
2513 JDWP::Set1(buf + 1, intVal != 0);
Sebastien Hertz8009f392014-09-01 17:07:11 +02002514 break;
Ian Rogers0399dde2012-06-06 17:09:28 -07002515 }
Sebastien Hertz8009f392014-09-01 17:07:11 +02002516 case JDWP::JT_BYTE: {
2517 CHECK_EQ(width, 1U);
2518 uint32_t intVal;
Sebastien Hertzabbabc82015-03-26 08:47:47 +01002519 if (!visitor.GetVReg(m, vreg, kIntVReg, &intVal)) {
2520 return FailGetLocalValue(visitor, vreg, tag);
Sebastien Hertz8009f392014-09-01 17:07:11 +02002521 }
Sebastien Hertzabbabc82015-03-26 08:47:47 +01002522 VLOG(jdwp) << "get byte local " << vreg << " = " << intVal;
2523 JDWP::Set1(buf + 1, intVal);
Sebastien Hertz8009f392014-09-01 17:07:11 +02002524 break;
2525 }
2526 case JDWP::JT_SHORT:
2527 case JDWP::JT_CHAR: {
2528 CHECK_EQ(width, 2U);
2529 uint32_t intVal;
Sebastien Hertzabbabc82015-03-26 08:47:47 +01002530 if (!visitor.GetVReg(m, vreg, kIntVReg, &intVal)) {
2531 return FailGetLocalValue(visitor, vreg, tag);
Sebastien Hertz8009f392014-09-01 17:07:11 +02002532 }
Sebastien Hertzabbabc82015-03-26 08:47:47 +01002533 VLOG(jdwp) << "get short/char local " << vreg << " = " << intVal;
2534 JDWP::Set2BE(buf + 1, intVal);
Sebastien Hertz8009f392014-09-01 17:07:11 +02002535 break;
2536 }
2537 case JDWP::JT_INT: {
2538 CHECK_EQ(width, 4U);
2539 uint32_t intVal;
Sebastien Hertzabbabc82015-03-26 08:47:47 +01002540 if (!visitor.GetVReg(m, vreg, kIntVReg, &intVal)) {
2541 return FailGetLocalValue(visitor, vreg, tag);
Sebastien Hertz8009f392014-09-01 17:07:11 +02002542 }
Sebastien Hertzabbabc82015-03-26 08:47:47 +01002543 VLOG(jdwp) << "get int local " << vreg << " = " << intVal;
2544 JDWP::Set4BE(buf + 1, intVal);
Sebastien Hertz8009f392014-09-01 17:07:11 +02002545 break;
2546 }
2547 case JDWP::JT_FLOAT: {
2548 CHECK_EQ(width, 4U);
2549 uint32_t intVal;
Sebastien Hertzabbabc82015-03-26 08:47:47 +01002550 if (!visitor.GetVReg(m, vreg, kFloatVReg, &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 float local " << vreg << " = " << intVal;
2554 JDWP::Set4BE(buf + 1, intVal);
Sebastien Hertz8009f392014-09-01 17:07:11 +02002555 break;
2556 }
2557 case JDWP::JT_ARRAY:
2558 case JDWP::JT_CLASS_LOADER:
2559 case JDWP::JT_CLASS_OBJECT:
2560 case JDWP::JT_OBJECT:
2561 case JDWP::JT_STRING:
2562 case JDWP::JT_THREAD:
2563 case JDWP::JT_THREAD_GROUP: {
2564 CHECK_EQ(width, sizeof(JDWP::ObjectId));
2565 uint32_t intVal;
Sebastien Hertzabbabc82015-03-26 08:47:47 +01002566 if (!visitor.GetVReg(m, vreg, kReferenceVReg, &intVal)) {
2567 return FailGetLocalValue(visitor, vreg, tag);
Sebastien Hertz8009f392014-09-01 17:07:11 +02002568 }
Sebastien Hertzabbabc82015-03-26 08:47:47 +01002569 mirror::Object* o = reinterpret_cast<mirror::Object*>(intVal);
2570 VLOG(jdwp) << "get " << tag << " object local " << vreg << " = " << o;
2571 if (!Runtime::Current()->GetHeap()->IsValidObjectAddress(o)) {
2572 LOG(FATAL) << StringPrintf("Found invalid object %#" PRIxPTR " in register v%u",
2573 reinterpret_cast<uintptr_t>(o), vreg)
2574 << GetStackContextAsString(visitor);
2575 UNREACHABLE();
2576 }
2577 tag = TagFromObject(soa, o);
2578 JDWP::SetObjectId(buf + 1, gRegistry->Add(o));
Sebastien Hertz8009f392014-09-01 17:07:11 +02002579 break;
2580 }
2581 case JDWP::JT_DOUBLE: {
2582 CHECK_EQ(width, 8U);
2583 uint64_t longVal;
Sebastien Hertzabbabc82015-03-26 08:47:47 +01002584 if (!visitor.GetVRegPair(m, vreg, kDoubleLoVReg, kDoubleHiVReg, &longVal)) {
2585 return FailGetLocalValue(visitor, vreg, tag);
Sebastien Hertz8009f392014-09-01 17:07:11 +02002586 }
Sebastien Hertzabbabc82015-03-26 08:47:47 +01002587 VLOG(jdwp) << "get double local " << vreg << " = " << longVal;
2588 JDWP::Set8BE(buf + 1, longVal);
Sebastien Hertz8009f392014-09-01 17:07:11 +02002589 break;
2590 }
2591 case JDWP::JT_LONG: {
2592 CHECK_EQ(width, 8U);
2593 uint64_t longVal;
Sebastien Hertzabbabc82015-03-26 08:47:47 +01002594 if (!visitor.GetVRegPair(m, vreg, kLongLoVReg, kLongHiVReg, &longVal)) {
2595 return FailGetLocalValue(visitor, vreg, tag);
Sebastien Hertz8009f392014-09-01 17:07:11 +02002596 }
Sebastien Hertzabbabc82015-03-26 08:47:47 +01002597 VLOG(jdwp) << "get long local " << vreg << " = " << longVal;
2598 JDWP::Set8BE(buf + 1, longVal);
Sebastien Hertz8009f392014-09-01 17:07:11 +02002599 break;
2600 }
2601 default:
2602 LOG(FATAL) << "Unknown tag " << tag;
Sebastien Hertzabbabc82015-03-26 08:47:47 +01002603 UNREACHABLE();
Sebastien Hertz8009f392014-09-01 17:07:11 +02002604 }
Ian Rogers0399dde2012-06-06 17:09:28 -07002605
Sebastien Hertz8009f392014-09-01 17:07:11 +02002606 // Prepend tag, which may have been updated.
2607 JDWP::Set1(buf, tag);
2608 return JDWP::ERR_NONE;
2609}
2610
2611JDWP::JdwpError Dbg::SetLocalValues(JDWP::Request* request) {
2612 JDWP::ObjectId thread_id = request->ReadThreadId();
2613 JDWP::FrameId frame_id = request->ReadFrameId();
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002614
2615 ScopedObjectAccessUnchecked soa(Thread::Current());
Sebastien Hertz69206392015-04-07 15:54:25 +02002616 JDWP::JdwpError error;
2617 Thread* thread = DecodeThread(soa, thread_id, &error);
2618 if (error != JDWP::ERR_NONE) {
2619 return error;
2620 }
2621 if (!IsSuspendedForDebugger(soa, thread)) {
2622 return JDWP::ERR_THREAD_NOT_SUSPENDED;
Elliott Hughes221229c2013-01-08 18:17:50 -08002623 }
Sebastien Hertz8009f392014-09-01 17:07:11 +02002624 // Find the frame with the given frame_id.
Ian Rogers700a4022014-05-19 16:49:03 -07002625 std::unique_ptr<Context> context(Context::Create());
Sebastien Hertz8009f392014-09-01 17:07:11 +02002626 FindFrameVisitor visitor(thread, context.get(), frame_id);
Ian Rogers0399dde2012-06-06 17:09:28 -07002627 visitor.WalkStack();
Sebastien Hertz8009f392014-09-01 17:07:11 +02002628 if (visitor.GetError() != JDWP::ERR_NONE) {
2629 return visitor.GetError();
2630 }
2631
2632 // Writes the values into visitor's context.
2633 int32_t slot_count = request->ReadSigned32("slot count");
2634 for (int32_t i = 0; i < slot_count; ++i) {
2635 uint32_t slot = request->ReadUnsigned32("slot");
2636 JDWP::JdwpTag sigByte = request->ReadTag();
2637 size_t width = Dbg::GetTagWidth(sigByte);
2638 uint64_t value = request->ReadValue(width);
2639
2640 VLOG(jdwp) << " --> slot " << slot << " " << sigByte << " " << value;
Sebastien Hertz69206392015-04-07 15:54:25 +02002641 error = Dbg::SetLocalValue(visitor, slot, sigByte, value, width);
Sebastien Hertz8009f392014-09-01 17:07:11 +02002642 if (error != JDWP::ERR_NONE) {
2643 return error;
2644 }
2645 }
2646 return JDWP::ERR_NONE;
2647}
2648
Sebastien Hertzabbabc82015-03-26 08:47:47 +01002649template<typename T>
2650static JDWP::JdwpError FailSetLocalValue(const StackVisitor& visitor, uint16_t vreg,
2651 JDWP::JdwpTag tag, T value)
Mathieu Chartier90443472015-07-16 20:32:27 -07002652 SHARED_REQUIRES(Locks::mutator_lock_) {
Sebastien Hertzabbabc82015-03-26 08:47:47 +01002653 LOG(ERROR) << "Failed to write " << tag << " local " << value
2654 << " (0x" << std::hex << value << ") into register v" << vreg
2655 << GetStackContextAsString(visitor);
2656 return kStackFrameLocalAccessError;
2657}
2658
Sebastien Hertz8009f392014-09-01 17:07:11 +02002659JDWP::JdwpError Dbg::SetLocalValue(StackVisitor& visitor, int slot, JDWP::JdwpTag tag,
2660 uint64_t value, size_t width) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07002661 ArtMethod* m = visitor.GetMethod();
Sebastien Hertzabbabc82015-03-26 08:47:47 +01002662 JDWP::JdwpError error = JDWP::ERR_NONE;
2663 uint16_t vreg = DemangleSlot(slot, m, &error);
2664 if (error != JDWP::ERR_NONE) {
2665 return error;
2666 }
Sebastien Hertz8009f392014-09-01 17:07:11 +02002667 // TODO: check that the tag is compatible with the actual type of the slot!
Sebastien Hertz8009f392014-09-01 17:07:11 +02002668 switch (tag) {
2669 case JDWP::JT_BOOLEAN:
2670 case JDWP::JT_BYTE:
2671 CHECK_EQ(width, 1U);
Sebastien Hertzabbabc82015-03-26 08:47:47 +01002672 if (!visitor.SetVReg(m, vreg, static_cast<uint32_t>(value), kIntVReg)) {
2673 return FailSetLocalValue(visitor, vreg, tag, static_cast<uint32_t>(value));
Sebastien Hertz8009f392014-09-01 17:07:11 +02002674 }
2675 break;
2676 case JDWP::JT_SHORT:
2677 case JDWP::JT_CHAR:
2678 CHECK_EQ(width, 2U);
Sebastien Hertzabbabc82015-03-26 08:47:47 +01002679 if (!visitor.SetVReg(m, vreg, static_cast<uint32_t>(value), kIntVReg)) {
2680 return FailSetLocalValue(visitor, vreg, tag, static_cast<uint32_t>(value));
Sebastien Hertz8009f392014-09-01 17:07:11 +02002681 }
2682 break;
2683 case JDWP::JT_INT:
2684 CHECK_EQ(width, 4U);
Sebastien Hertzabbabc82015-03-26 08:47:47 +01002685 if (!visitor.SetVReg(m, vreg, static_cast<uint32_t>(value), kIntVReg)) {
2686 return FailSetLocalValue(visitor, vreg, tag, static_cast<uint32_t>(value));
Sebastien Hertz8009f392014-09-01 17:07:11 +02002687 }
2688 break;
2689 case JDWP::JT_FLOAT:
2690 CHECK_EQ(width, 4U);
Sebastien Hertzabbabc82015-03-26 08:47:47 +01002691 if (!visitor.SetVReg(m, vreg, static_cast<uint32_t>(value), kFloatVReg)) {
2692 return FailSetLocalValue(visitor, vreg, tag, static_cast<uint32_t>(value));
Sebastien Hertz8009f392014-09-01 17:07:11 +02002693 }
2694 break;
2695 case JDWP::JT_ARRAY:
2696 case JDWP::JT_CLASS_LOADER:
2697 case JDWP::JT_CLASS_OBJECT:
2698 case JDWP::JT_OBJECT:
2699 case JDWP::JT_STRING:
2700 case JDWP::JT_THREAD:
2701 case JDWP::JT_THREAD_GROUP: {
2702 CHECK_EQ(width, sizeof(JDWP::ObjectId));
Sebastien Hertz8009f392014-09-01 17:07:11 +02002703 mirror::Object* o = gRegistry->Get<mirror::Object*>(static_cast<JDWP::ObjectId>(value),
2704 &error);
2705 if (error != JDWP::ERR_NONE) {
2706 VLOG(jdwp) << tag << " object " << o << " is an invalid object";
2707 return JDWP::ERR_INVALID_OBJECT;
Sebastien Hertzabbabc82015-03-26 08:47:47 +01002708 }
2709 if (!visitor.SetVReg(m, vreg, static_cast<uint32_t>(reinterpret_cast<uintptr_t>(o)),
2710 kReferenceVReg)) {
2711 return FailSetLocalValue(visitor, vreg, tag, reinterpret_cast<uintptr_t>(o));
Sebastien Hertz8009f392014-09-01 17:07:11 +02002712 }
2713 break;
2714 }
2715 case JDWP::JT_DOUBLE: {
2716 CHECK_EQ(width, 8U);
Sebastien Hertzabbabc82015-03-26 08:47:47 +01002717 if (!visitor.SetVRegPair(m, vreg, value, kDoubleLoVReg, kDoubleHiVReg)) {
2718 return FailSetLocalValue(visitor, vreg, tag, value);
Sebastien Hertz8009f392014-09-01 17:07:11 +02002719 }
2720 break;
2721 }
2722 case JDWP::JT_LONG: {
2723 CHECK_EQ(width, 8U);
Sebastien Hertzabbabc82015-03-26 08:47:47 +01002724 if (!visitor.SetVRegPair(m, vreg, value, kLongLoVReg, kLongHiVReg)) {
2725 return FailSetLocalValue(visitor, vreg, tag, value);
Sebastien Hertz8009f392014-09-01 17:07:11 +02002726 }
2727 break;
2728 }
2729 default:
2730 LOG(FATAL) << "Unknown tag " << tag;
Sebastien Hertzabbabc82015-03-26 08:47:47 +01002731 UNREACHABLE();
Sebastien Hertz8009f392014-09-01 17:07:11 +02002732 }
2733 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002734}
2735
Mathieu Chartiere401d142015-04-22 13:56:20 -07002736static void SetEventLocation(JDWP::EventLocation* location, ArtMethod* m, uint32_t dex_pc)
Mathieu Chartier90443472015-07-16 20:32:27 -07002737 SHARED_REQUIRES(Locks::mutator_lock_) {
Sebastien Hertz6995c602014-09-09 12:10:13 +02002738 DCHECK(location != nullptr);
2739 if (m == nullptr) {
2740 memset(location, 0, sizeof(*location));
2741 } else {
2742 location->method = m;
2743 location->dex_pc = (m->IsNative() || m->IsProxyMethod()) ? static_cast<uint32_t>(-1) : dex_pc;
Sebastien Hertz3f52eaf2014-04-04 17:50:18 +02002744 }
Sebastien Hertz3f52eaf2014-04-04 17:50:18 +02002745}
2746
Mathieu Chartiere401d142015-04-22 13:56:20 -07002747void Dbg::PostLocationEvent(ArtMethod* m, int dex_pc, mirror::Object* this_object,
Jeff Hao579b0242013-11-18 13:16:49 -08002748 int event_flags, const JValue* return_value) {
Sebastien Hertz3f52eaf2014-04-04 17:50:18 +02002749 if (!IsDebuggerActive()) {
2750 return;
2751 }
2752 DCHECK(m != nullptr);
2753 DCHECK_EQ(m->IsStatic(), this_object == nullptr);
Sebastien Hertz6995c602014-09-09 12:10:13 +02002754 JDWP::EventLocation location;
2755 SetEventLocation(&location, m, dex_pc);
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08002756
Sebastien Hertzde48aa62015-05-26 11:53:39 +02002757 // We need to be sure no exception is pending when calling JdwpState::PostLocationEvent.
2758 // This is required to be able to call JNI functions to create JDWP ids. To achieve this,
2759 // we temporarily clear the current thread's exception (if any) and will restore it after
2760 // the call.
2761 // Note: the only way to get a pending exception here is to suspend on a move-exception
2762 // instruction.
2763 Thread* const self = Thread::Current();
2764 StackHandleScope<1> hs(self);
2765 Handle<mirror::Throwable> pending_exception(hs.NewHandle(self->GetException()));
2766 self->ClearException();
2767 if (kIsDebugBuild && pending_exception.Get() != nullptr) {
2768 const DexFile::CodeItem* code_item = location.method->GetCodeItem();
2769 const Instruction* instr = Instruction::At(&code_item->insns_[location.dex_pc]);
2770 CHECK_EQ(Instruction::MOVE_EXCEPTION, instr->Opcode());
2771 }
2772
Sebastien Hertz6995c602014-09-09 12:10:13 +02002773 gJdwpState->PostLocationEvent(&location, this_object, event_flags, return_value);
Sebastien Hertzde48aa62015-05-26 11:53:39 +02002774
2775 if (pending_exception.Get() != nullptr) {
2776 self->SetException(pending_exception.Get());
2777 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002778}
2779
Mathieu Chartiere401d142015-04-22 13:56:20 -07002780void Dbg::PostFieldAccessEvent(ArtMethod* m, int dex_pc,
Mathieu Chartierc7853442015-03-27 14:35:38 -07002781 mirror::Object* this_object, ArtField* f) {
Sebastien Hertz3f52eaf2014-04-04 17:50:18 +02002782 if (!IsDebuggerActive()) {
2783 return;
2784 }
2785 DCHECK(m != nullptr);
2786 DCHECK(f != nullptr);
Sebastien Hertz6995c602014-09-09 12:10:13 +02002787 JDWP::EventLocation location;
2788 SetEventLocation(&location, m, dex_pc);
Sebastien Hertz3f52eaf2014-04-04 17:50:18 +02002789
Sebastien Hertz6995c602014-09-09 12:10:13 +02002790 gJdwpState->PostFieldEvent(&location, f, this_object, nullptr, false);
Sebastien Hertz3f52eaf2014-04-04 17:50:18 +02002791}
2792
Mathieu Chartiere401d142015-04-22 13:56:20 -07002793void Dbg::PostFieldModificationEvent(ArtMethod* m, int dex_pc,
Mathieu Chartierc7853442015-03-27 14:35:38 -07002794 mirror::Object* this_object, ArtField* f,
Sebastien Hertz3f52eaf2014-04-04 17:50:18 +02002795 const JValue* field_value) {
2796 if (!IsDebuggerActive()) {
2797 return;
2798 }
2799 DCHECK(m != nullptr);
2800 DCHECK(f != nullptr);
2801 DCHECK(field_value != nullptr);
Sebastien Hertz6995c602014-09-09 12:10:13 +02002802 JDWP::EventLocation location;
2803 SetEventLocation(&location, m, dex_pc);
Sebastien Hertz3f52eaf2014-04-04 17:50:18 +02002804
Sebastien Hertz6995c602014-09-09 12:10:13 +02002805 gJdwpState->PostFieldEvent(&location, f, this_object, field_value, true);
Sebastien Hertz3f52eaf2014-04-04 17:50:18 +02002806}
2807
Nicolas Geoffray14691c52015-03-05 10:40:17 +00002808/**
2809 * Finds the location where this exception will be caught. We search until we reach the top
2810 * frame, in which case this exception is considered uncaught.
2811 */
2812class CatchLocationFinder : public StackVisitor {
2813 public:
2814 CatchLocationFinder(Thread* self, const Handle<mirror::Throwable>& exception, Context* context)
Mathieu Chartier90443472015-07-16 20:32:27 -07002815 SHARED_REQUIRES(Locks::mutator_lock_)
Nicolas Geoffray8e5bd182015-05-06 11:34:34 +01002816 : StackVisitor(self, context, StackVisitor::StackWalkKind::kIncludeInlinedFrames),
Nicolas Geoffray14691c52015-03-05 10:40:17 +00002817 self_(self),
2818 exception_(exception),
2819 handle_scope_(self),
2820 this_at_throw_(handle_scope_.NewHandle<mirror::Object>(nullptr)),
Mathieu Chartiere401d142015-04-22 13:56:20 -07002821 catch_method_(nullptr),
2822 throw_method_(nullptr),
Nicolas Geoffray14691c52015-03-05 10:40:17 +00002823 catch_dex_pc_(DexFile::kDexNoIndex),
2824 throw_dex_pc_(DexFile::kDexNoIndex) {
2825 }
2826
Mathieu Chartier90443472015-07-16 20:32:27 -07002827 bool VisitFrame() OVERRIDE SHARED_REQUIRES(Locks::mutator_lock_) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07002828 ArtMethod* method = GetMethod();
Nicolas Geoffray14691c52015-03-05 10:40:17 +00002829 DCHECK(method != nullptr);
2830 if (method->IsRuntimeMethod()) {
2831 // Ignore callee save method.
2832 DCHECK(method->IsCalleeSaveMethod());
2833 return true;
2834 }
2835
2836 uint32_t dex_pc = GetDexPc();
Mathieu Chartiere401d142015-04-22 13:56:20 -07002837 if (throw_method_ == nullptr) {
Nicolas Geoffray14691c52015-03-05 10:40:17 +00002838 // First Java method found. It is either the method that threw the exception,
2839 // or the Java native method that is reporting an exception thrown by
2840 // native code.
2841 this_at_throw_.Assign(GetThisObject());
Mathieu Chartiere401d142015-04-22 13:56:20 -07002842 throw_method_ = method;
Nicolas Geoffray14691c52015-03-05 10:40:17 +00002843 throw_dex_pc_ = dex_pc;
2844 }
2845
2846 if (dex_pc != DexFile::kDexNoIndex) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07002847 StackHandleScope<1> hs(self_);
Nicolas Geoffray14691c52015-03-05 10:40:17 +00002848 uint32_t found_dex_pc;
2849 Handle<mirror::Class> exception_class(hs.NewHandle(exception_->GetClass()));
Nicolas Geoffray14691c52015-03-05 10:40:17 +00002850 bool unused_clear_exception;
Mathieu Chartiere401d142015-04-22 13:56:20 -07002851 found_dex_pc = method->FindCatchBlock(exception_class, dex_pc, &unused_clear_exception);
Nicolas Geoffray14691c52015-03-05 10:40:17 +00002852 if (found_dex_pc != DexFile::kDexNoIndex) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07002853 catch_method_ = method;
Nicolas Geoffray14691c52015-03-05 10:40:17 +00002854 catch_dex_pc_ = found_dex_pc;
2855 return false; // End stack walk.
2856 }
2857 }
2858 return true; // Continue stack walk.
2859 }
2860
Mathieu Chartier90443472015-07-16 20:32:27 -07002861 ArtMethod* GetCatchMethod() SHARED_REQUIRES(Locks::mutator_lock_) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07002862 return catch_method_;
Nicolas Geoffray14691c52015-03-05 10:40:17 +00002863 }
2864
Mathieu Chartier90443472015-07-16 20:32:27 -07002865 ArtMethod* GetThrowMethod() SHARED_REQUIRES(Locks::mutator_lock_) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07002866 return throw_method_;
Nicolas Geoffray14691c52015-03-05 10:40:17 +00002867 }
2868
Mathieu Chartier90443472015-07-16 20:32:27 -07002869 mirror::Object* GetThisAtThrow() SHARED_REQUIRES(Locks::mutator_lock_) {
Nicolas Geoffray14691c52015-03-05 10:40:17 +00002870 return this_at_throw_.Get();
2871 }
2872
2873 uint32_t GetCatchDexPc() const {
2874 return catch_dex_pc_;
2875 }
2876
2877 uint32_t GetThrowDexPc() const {
2878 return throw_dex_pc_;
2879 }
2880
2881 private:
2882 Thread* const self_;
2883 const Handle<mirror::Throwable>& exception_;
Mathieu Chartiere401d142015-04-22 13:56:20 -07002884 StackHandleScope<1> handle_scope_;
Nicolas Geoffray14691c52015-03-05 10:40:17 +00002885 MutableHandle<mirror::Object> this_at_throw_;
Mathieu Chartiere401d142015-04-22 13:56:20 -07002886 ArtMethod* catch_method_;
2887 ArtMethod* throw_method_;
Nicolas Geoffray14691c52015-03-05 10:40:17 +00002888 uint32_t catch_dex_pc_;
2889 uint32_t throw_dex_pc_;
2890
2891 DISALLOW_COPY_AND_ASSIGN(CatchLocationFinder);
2892};
2893
2894void Dbg::PostException(mirror::Throwable* exception_object) {
Elliott Hughesc0f09332012-03-26 13:27:06 -07002895 if (!IsDebuggerActive()) {
Ian Rogers0ad5bb82011-12-07 10:16:32 -08002896 return;
2897 }
Sebastien Hertz261bc042015-04-08 09:36:07 +02002898 Thread* const self = Thread::Current();
2899 StackHandleScope<1> handle_scope(self);
Nicolas Geoffray14691c52015-03-05 10:40:17 +00002900 Handle<mirror::Throwable> h_exception(handle_scope.NewHandle(exception_object));
2901 std::unique_ptr<Context> context(Context::Create());
Sebastien Hertz261bc042015-04-08 09:36:07 +02002902 CatchLocationFinder clf(self, h_exception, context.get());
Nicolas Geoffray14691c52015-03-05 10:40:17 +00002903 clf.WalkStack(/* include_transitions */ false);
Sebastien Hertz6995c602014-09-09 12:10:13 +02002904 JDWP::EventLocation exception_throw_location;
Nicolas Geoffray14691c52015-03-05 10:40:17 +00002905 SetEventLocation(&exception_throw_location, clf.GetThrowMethod(), clf.GetThrowDexPc());
Sebastien Hertz6995c602014-09-09 12:10:13 +02002906 JDWP::EventLocation exception_catch_location;
Nicolas Geoffray14691c52015-03-05 10:40:17 +00002907 SetEventLocation(&exception_catch_location, clf.GetCatchMethod(), clf.GetCatchDexPc());
Elliott Hughes4740cdf2011-12-07 14:07:12 -08002908
Nicolas Geoffray14691c52015-03-05 10:40:17 +00002909 gJdwpState->PostException(&exception_throw_location, h_exception.Get(), &exception_catch_location,
2910 clf.GetThisAtThrow());
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002911}
2912
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002913void Dbg::PostClassPrepare(mirror::Class* c) {
Elliott Hughesc0f09332012-03-26 13:27:06 -07002914 if (!IsDebuggerActive()) {
Elliott Hughes4740cdf2011-12-07 14:07:12 -08002915 return;
2916 }
Sebastien Hertz6995c602014-09-09 12:10:13 +02002917 gJdwpState->PostClassPrepare(c);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002918}
2919
Ian Rogers62d6c772013-02-27 08:32:07 -08002920void Dbg::UpdateDebugger(Thread* thread, mirror::Object* this_object,
Mathieu Chartiere401d142015-04-22 13:56:20 -07002921 ArtMethod* m, uint32_t dex_pc,
Sebastien Hertz8379b222014-02-24 17:38:15 +01002922 int event_flags, const JValue* return_value) {
Ian Rogers62d6c772013-02-27 08:32:07 -08002923 if (!IsDebuggerActive() || dex_pc == static_cast<uint32_t>(-2) /* fake method exit */) {
Elliott Hughes2aa2e392012-02-17 17:15:43 -08002924 return;
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08002925 }
2926
Elliott Hughes86964332012-02-15 19:37:42 -08002927 if (IsBreakpoint(m, dex_pc)) {
2928 event_flags |= kBreakpoint;
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08002929 }
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08002930
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01002931 // If the debugger is single-stepping one of our threads, check to
2932 // see if we're that thread and we've reached a step point.
2933 const SingleStepControl* single_step_control = thread->GetSingleStepControl();
Sebastien Hertz597c4f02015-01-26 17:37:14 +01002934 if (single_step_control != nullptr) {
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01002935 CHECK(!m->IsNative());
Sebastien Hertz597c4f02015-01-26 17:37:14 +01002936 if (single_step_control->GetStepDepth() == JDWP::SD_INTO) {
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01002937 // Step into method calls. We break when the line number
2938 // or method pointer changes. If we're in SS_MIN mode, we
2939 // always stop.
Sebastien Hertz597c4f02015-01-26 17:37:14 +01002940 if (single_step_control->GetMethod() != m) {
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01002941 event_flags |= kSingleStep;
2942 VLOG(jdwp) << "SS new method";
Sebastien Hertz597c4f02015-01-26 17:37:14 +01002943 } else if (single_step_control->GetStepSize() == JDWP::SS_MIN) {
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01002944 event_flags |= kSingleStep;
2945 VLOG(jdwp) << "SS new instruction";
Sebastien Hertzbb43b432014-04-14 11:59:08 +02002946 } else if (single_step_control->ContainsDexPc(dex_pc)) {
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01002947 event_flags |= kSingleStep;
2948 VLOG(jdwp) << "SS new line";
2949 }
Sebastien Hertz597c4f02015-01-26 17:37:14 +01002950 } else if (single_step_control->GetStepDepth() == JDWP::SD_OVER) {
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01002951 // Step over method calls. We break when the line number is
2952 // different and the frame depth is <= the original frame
2953 // depth. (We can't just compare on the method, because we
2954 // might get unrolled past it by an exception, and it's tricky
2955 // to identify recursion.)
2956
2957 int stack_depth = GetStackDepth(thread);
2958
Sebastien Hertz597c4f02015-01-26 17:37:14 +01002959 if (stack_depth < single_step_control->GetStackDepth()) {
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01002960 // Popped up one or more frames, always trigger.
2961 event_flags |= kSingleStep;
2962 VLOG(jdwp) << "SS method pop";
Sebastien Hertz597c4f02015-01-26 17:37:14 +01002963 } else if (stack_depth == single_step_control->GetStackDepth()) {
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01002964 // Same depth, see if we moved.
Sebastien Hertz597c4f02015-01-26 17:37:14 +01002965 if (single_step_control->GetStepSize() == JDWP::SS_MIN) {
Elliott Hughes86964332012-02-15 19:37:42 -08002966 event_flags |= kSingleStep;
2967 VLOG(jdwp) << "SS new instruction";
Sebastien Hertzbb43b432014-04-14 11:59:08 +02002968 } else if (single_step_control->ContainsDexPc(dex_pc)) {
Elliott Hughes2435a572012-02-17 16:07:41 -08002969 event_flags |= kSingleStep;
2970 VLOG(jdwp) << "SS new line";
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08002971 }
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01002972 }
2973 } else {
Sebastien Hertz597c4f02015-01-26 17:37:14 +01002974 CHECK_EQ(single_step_control->GetStepDepth(), JDWP::SD_OUT);
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01002975 // Return from the current method. We break when the frame
2976 // depth pops up.
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08002977
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01002978 // This differs from the "method exit" break in that it stops
2979 // with the PC at the next instruction in the returned-to
2980 // function, rather than the end of the returning function.
Elliott Hughes86964332012-02-15 19:37:42 -08002981
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01002982 int stack_depth = GetStackDepth(thread);
Sebastien Hertz597c4f02015-01-26 17:37:14 +01002983 if (stack_depth < single_step_control->GetStackDepth()) {
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01002984 event_flags |= kSingleStep;
2985 VLOG(jdwp) << "SS method pop";
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08002986 }
2987 }
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08002988 }
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08002989
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08002990 // If there's something interesting going on, see if it matches one
2991 // of the debugger filters.
2992 if (event_flags != 0) {
Sebastien Hertz8379b222014-02-24 17:38:15 +01002993 Dbg::PostLocationEvent(m, dex_pc, this_object, event_flags, return_value);
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08002994 }
2995}
2996
Sebastien Hertz42cd43f2014-05-13 14:15:41 +02002997size_t* Dbg::GetReferenceCounterForEvent(uint32_t instrumentation_event) {
2998 switch (instrumentation_event) {
2999 case instrumentation::Instrumentation::kMethodEntered:
3000 return &method_enter_event_ref_count_;
3001 case instrumentation::Instrumentation::kMethodExited:
3002 return &method_exit_event_ref_count_;
3003 case instrumentation::Instrumentation::kDexPcMoved:
3004 return &dex_pc_change_event_ref_count_;
3005 case instrumentation::Instrumentation::kFieldRead:
3006 return &field_read_event_ref_count_;
3007 case instrumentation::Instrumentation::kFieldWritten:
3008 return &field_write_event_ref_count_;
3009 case instrumentation::Instrumentation::kExceptionCaught:
3010 return &exception_catch_event_ref_count_;
3011 default:
3012 return nullptr;
3013 }
3014}
3015
Sebastien Hertz4d25df32014-03-21 17:44:46 +01003016// Process request while all mutator threads are suspended.
3017void Dbg::ProcessDeoptimizationRequest(const DeoptimizationRequest& request) {
Sebastien Hertz138dbfc2013-12-04 18:15:25 +01003018 instrumentation::Instrumentation* instrumentation = Runtime::Current()->GetInstrumentation();
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003019 switch (request.GetKind()) {
Sebastien Hertz4d25df32014-03-21 17:44:46 +01003020 case DeoptimizationRequest::kNothing:
3021 LOG(WARNING) << "Ignoring empty deoptimization request.";
3022 break;
Sebastien Hertz42cd43f2014-05-13 14:15:41 +02003023 case DeoptimizationRequest::kRegisterForEvent:
3024 VLOG(jdwp) << StringPrintf("Add debugger as listener for instrumentation event 0x%x",
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003025 request.InstrumentationEvent());
3026 instrumentation->AddListener(&gDebugInstrumentationListener, request.InstrumentationEvent());
3027 instrumentation_events_ |= request.InstrumentationEvent();
Sebastien Hertz42cd43f2014-05-13 14:15:41 +02003028 break;
3029 case DeoptimizationRequest::kUnregisterForEvent:
3030 VLOG(jdwp) << StringPrintf("Remove debugger as listener for instrumentation event 0x%x",
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003031 request.InstrumentationEvent());
Sebastien Hertz42cd43f2014-05-13 14:15:41 +02003032 instrumentation->RemoveListener(&gDebugInstrumentationListener,
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003033 request.InstrumentationEvent());
3034 instrumentation_events_ &= ~request.InstrumentationEvent();
Sebastien Hertz42cd43f2014-05-13 14:15:41 +02003035 break;
Sebastien Hertz4d25df32014-03-21 17:44:46 +01003036 case DeoptimizationRequest::kFullDeoptimization:
Sebastien Hertz7ec2f1c2014-03-27 20:06:47 +01003037 VLOG(jdwp) << "Deoptimize the world ...";
Sebastien Hertz0462c4c2015-04-01 16:34:17 +02003038 instrumentation->DeoptimizeEverything(kDbgInstrumentationKey);
Sebastien Hertz7ec2f1c2014-03-27 20:06:47 +01003039 VLOG(jdwp) << "Deoptimize the world DONE";
Sebastien Hertz4d25df32014-03-21 17:44:46 +01003040 break;
3041 case DeoptimizationRequest::kFullUndeoptimization:
Sebastien Hertz7ec2f1c2014-03-27 20:06:47 +01003042 VLOG(jdwp) << "Undeoptimize the world ...";
Sebastien Hertz0462c4c2015-04-01 16:34:17 +02003043 instrumentation->UndeoptimizeEverything(kDbgInstrumentationKey);
Sebastien Hertz7ec2f1c2014-03-27 20:06:47 +01003044 VLOG(jdwp) << "Undeoptimize the world DONE";
Sebastien Hertz4d25df32014-03-21 17:44:46 +01003045 break;
3046 case DeoptimizationRequest::kSelectiveDeoptimization:
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003047 VLOG(jdwp) << "Deoptimize method " << PrettyMethod(request.Method()) << " ...";
3048 instrumentation->Deoptimize(request.Method());
3049 VLOG(jdwp) << "Deoptimize method " << PrettyMethod(request.Method()) << " DONE";
Sebastien Hertz4d25df32014-03-21 17:44:46 +01003050 break;
3051 case DeoptimizationRequest::kSelectiveUndeoptimization:
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003052 VLOG(jdwp) << "Undeoptimize method " << PrettyMethod(request.Method()) << " ...";
3053 instrumentation->Undeoptimize(request.Method());
3054 VLOG(jdwp) << "Undeoptimize method " << PrettyMethod(request.Method()) << " DONE";
Sebastien Hertz4d25df32014-03-21 17:44:46 +01003055 break;
3056 default:
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003057 LOG(FATAL) << "Unsupported deoptimization request kind " << request.GetKind();
Sebastien Hertz4d25df32014-03-21 17:44:46 +01003058 break;
Sebastien Hertz138dbfc2013-12-04 18:15:25 +01003059 }
Sebastien Hertz138dbfc2013-12-04 18:15:25 +01003060}
3061
Sebastien Hertz4d25df32014-03-21 17:44:46 +01003062void Dbg::RequestDeoptimization(const DeoptimizationRequest& req) {
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003063 if (req.GetKind() == DeoptimizationRequest::kNothing) {
Sebastien Hertz4d25df32014-03-21 17:44:46 +01003064 // Nothing to do.
3065 return;
3066 }
Brian Carlstrom306db812014-09-05 13:01:41 -07003067 MutexLock mu(Thread::Current(), *Locks::deoptimization_lock_);
Sebastien Hertz7ec2f1c2014-03-27 20:06:47 +01003068 RequestDeoptimizationLocked(req);
3069}
3070
3071void Dbg::RequestDeoptimizationLocked(const DeoptimizationRequest& req) {
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003072 switch (req.GetKind()) {
Sebastien Hertz42cd43f2014-05-13 14:15:41 +02003073 case DeoptimizationRequest::kRegisterForEvent: {
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003074 DCHECK_NE(req.InstrumentationEvent(), 0u);
3075 size_t* counter = GetReferenceCounterForEvent(req.InstrumentationEvent());
Sebastien Hertz42cd43f2014-05-13 14:15:41 +02003076 CHECK(counter != nullptr) << StringPrintf("No counter for instrumentation event 0x%x",
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003077 req.InstrumentationEvent());
Sebastien Hertz42cd43f2014-05-13 14:15:41 +02003078 if (*counter == 0) {
Sebastien Hertz7d2ae432014-05-15 11:26:34 +02003079 VLOG(jdwp) << StringPrintf("Queue request #%zd to start listening to instrumentation event 0x%x",
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003080 deoptimization_requests_.size(), req.InstrumentationEvent());
Sebastien Hertz42cd43f2014-05-13 14:15:41 +02003081 deoptimization_requests_.push_back(req);
3082 }
3083 *counter = *counter + 1;
3084 break;
3085 }
3086 case DeoptimizationRequest::kUnregisterForEvent: {
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003087 DCHECK_NE(req.InstrumentationEvent(), 0u);
3088 size_t* counter = GetReferenceCounterForEvent(req.InstrumentationEvent());
Sebastien Hertz42cd43f2014-05-13 14:15:41 +02003089 CHECK(counter != nullptr) << StringPrintf("No counter for instrumentation event 0x%x",
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003090 req.InstrumentationEvent());
Sebastien Hertz42cd43f2014-05-13 14:15:41 +02003091 *counter = *counter - 1;
3092 if (*counter == 0) {
Sebastien Hertz7d2ae432014-05-15 11:26:34 +02003093 VLOG(jdwp) << StringPrintf("Queue request #%zd to stop listening to instrumentation event 0x%x",
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003094 deoptimization_requests_.size(), req.InstrumentationEvent());
Sebastien Hertz42cd43f2014-05-13 14:15:41 +02003095 deoptimization_requests_.push_back(req);
3096 }
3097 break;
3098 }
Sebastien Hertz4d25df32014-03-21 17:44:46 +01003099 case DeoptimizationRequest::kFullDeoptimization: {
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003100 DCHECK(req.Method() == nullptr);
Sebastien Hertz4d25df32014-03-21 17:44:46 +01003101 if (full_deoptimization_event_count_ == 0) {
Sebastien Hertz7ec2f1c2014-03-27 20:06:47 +01003102 VLOG(jdwp) << "Queue request #" << deoptimization_requests_.size()
3103 << " for full deoptimization";
Sebastien Hertz4d25df32014-03-21 17:44:46 +01003104 deoptimization_requests_.push_back(req);
3105 }
3106 ++full_deoptimization_event_count_;
3107 break;
3108 }
3109 case DeoptimizationRequest::kFullUndeoptimization: {
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003110 DCHECK(req.Method() == nullptr);
Sebastien Hertze713d932014-05-15 10:48:53 +02003111 DCHECK_GT(full_deoptimization_event_count_, 0U);
Sebastien Hertz4d25df32014-03-21 17:44:46 +01003112 --full_deoptimization_event_count_;
3113 if (full_deoptimization_event_count_ == 0) {
Sebastien Hertz7ec2f1c2014-03-27 20:06:47 +01003114 VLOG(jdwp) << "Queue request #" << deoptimization_requests_.size()
3115 << " for full undeoptimization";
Sebastien Hertz4d25df32014-03-21 17:44:46 +01003116 deoptimization_requests_.push_back(req);
3117 }
3118 break;
3119 }
3120 case DeoptimizationRequest::kSelectiveDeoptimization: {
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003121 DCHECK(req.Method() != nullptr);
Sebastien Hertz7ec2f1c2014-03-27 20:06:47 +01003122 VLOG(jdwp) << "Queue request #" << deoptimization_requests_.size()
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003123 << " for deoptimization of " << PrettyMethod(req.Method());
Sebastien Hertz4d25df32014-03-21 17:44:46 +01003124 deoptimization_requests_.push_back(req);
3125 break;
3126 }
3127 case DeoptimizationRequest::kSelectiveUndeoptimization: {
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003128 DCHECK(req.Method() != nullptr);
Sebastien Hertz7ec2f1c2014-03-27 20:06:47 +01003129 VLOG(jdwp) << "Queue request #" << deoptimization_requests_.size()
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003130 << " for undeoptimization of " << PrettyMethod(req.Method());
Sebastien Hertz4d25df32014-03-21 17:44:46 +01003131 deoptimization_requests_.push_back(req);
3132 break;
3133 }
3134 default: {
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003135 LOG(FATAL) << "Unknown deoptimization request kind " << req.GetKind();
Sebastien Hertz4d25df32014-03-21 17:44:46 +01003136 break;
3137 }
3138 }
3139}
3140
Sebastien Hertz138dbfc2013-12-04 18:15:25 +01003141void Dbg::ManageDeoptimization() {
3142 Thread* const self = Thread::Current();
3143 {
3144 // Avoid suspend/resume if there is no pending request.
Brian Carlstrom306db812014-09-05 13:01:41 -07003145 MutexLock mu(self, *Locks::deoptimization_lock_);
Sebastien Hertz4d25df32014-03-21 17:44:46 +01003146 if (deoptimization_requests_.empty()) {
Sebastien Hertz138dbfc2013-12-04 18:15:25 +01003147 return;
3148 }
3149 }
3150 CHECK_EQ(self->GetState(), kRunnable);
3151 self->TransitionFromRunnableToSuspended(kWaitingForDeoptimization);
3152 // We need to suspend mutator threads first.
3153 Runtime* const runtime = Runtime::Current();
Mathieu Chartierbf9fc582015-03-13 17:21:25 -07003154 runtime->GetThreadList()->SuspendAll(__FUNCTION__);
Sebastien Hertz138dbfc2013-12-04 18:15:25 +01003155 const ThreadState old_state = self->SetStateUnsafe(kRunnable);
Sebastien Hertz4d25df32014-03-21 17:44:46 +01003156 {
Brian Carlstrom306db812014-09-05 13:01:41 -07003157 MutexLock mu(self, *Locks::deoptimization_lock_);
Sebastien Hertz7ec2f1c2014-03-27 20:06:47 +01003158 size_t req_index = 0;
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003159 for (DeoptimizationRequest& request : deoptimization_requests_) {
Sebastien Hertz7ec2f1c2014-03-27 20:06:47 +01003160 VLOG(jdwp) << "Process deoptimization request #" << req_index++;
Sebastien Hertz4d25df32014-03-21 17:44:46 +01003161 ProcessDeoptimizationRequest(request);
3162 }
3163 deoptimization_requests_.clear();
3164 }
Sebastien Hertz138dbfc2013-12-04 18:15:25 +01003165 CHECK_EQ(self->SetStateUnsafe(old_state), kRunnable);
3166 runtime->GetThreadList()->ResumeAll();
3167 self->TransitionFromSuspendedToRunnable();
3168}
3169
Mathieu Chartiere401d142015-04-22 13:56:20 -07003170static bool IsMethodPossiblyInlined(Thread* self, ArtMethod* m)
Mathieu Chartier90443472015-07-16 20:32:27 -07003171 SHARED_REQUIRES(Locks::mutator_lock_) {
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07003172 const DexFile::CodeItem* code_item = m->GetCodeItem();
Sebastien Hertza76a6d42014-03-20 16:40:17 +01003173 if (code_item == nullptr) {
3174 // TODO We should not be asked to watch location in a native or abstract method so the code item
3175 // should never be null. We could just check we never encounter this case.
3176 return false;
Sebastien Hertz138dbfc2013-12-04 18:15:25 +01003177 }
Sebastien Hertz4d1e9ab2014-09-18 16:03:34 +02003178 // Note: method verifier may cause thread suspension.
3179 self->AssertThreadSuspensionIsAllowable();
Mathieu Chartiere401d142015-04-22 13:56:20 -07003180 StackHandleScope<2> hs(self);
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07003181 mirror::Class* declaring_class = m->GetDeclaringClass();
3182 Handle<mirror::DexCache> dex_cache(hs.NewHandle(declaring_class->GetDexCache()));
3183 Handle<mirror::ClassLoader> class_loader(hs.NewHandle(declaring_class->GetClassLoader()));
Ian Rogers7b078e82014-09-10 14:44:24 -07003184 verifier::MethodVerifier verifier(self, dex_cache->GetDexFile(), dex_cache, class_loader,
Mathieu Chartiere401d142015-04-22 13:56:20 -07003185 &m->GetClassDef(), code_item, m->GetDexMethodIndex(), m,
Mathieu Chartier4306ef82014-12-19 18:41:47 -08003186 m->GetAccessFlags(), false, true, false, true);
Sebastien Hertza76a6d42014-03-20 16:40:17 +01003187 // Note: we don't need to verify the method.
3188 return InlineMethodAnalyser::AnalyseMethodCode(&verifier, nullptr);
3189}
Sebastien Hertz138dbfc2013-12-04 18:15:25 +01003190
Mathieu Chartiere401d142015-04-22 13:56:20 -07003191static const Breakpoint* FindFirstBreakpointForMethod(ArtMethod* m)
Mathieu Chartier90443472015-07-16 20:32:27 -07003192 SHARED_REQUIRES(Locks::mutator_lock_, Locks::breakpoint_lock_) {
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003193 for (Breakpoint& breakpoint : gBreakpoints) {
3194 if (breakpoint.Method() == m) {
Sebastien Hertza76a6d42014-03-20 16:40:17 +01003195 return &breakpoint;
3196 }
3197 }
3198 return nullptr;
3199}
3200
Mathieu Chartiere401d142015-04-22 13:56:20 -07003201bool Dbg::MethodHasAnyBreakpoints(ArtMethod* method) {
Mathieu Chartierd8565452015-03-26 09:41:50 -07003202 ReaderMutexLock mu(Thread::Current(), *Locks::breakpoint_lock_);
3203 return FindFirstBreakpointForMethod(method) != nullptr;
3204}
3205
Sebastien Hertza76a6d42014-03-20 16:40:17 +01003206// Sanity checks all existing breakpoints on the same method.
Mathieu Chartiere401d142015-04-22 13:56:20 -07003207static void SanityCheckExistingBreakpoints(ArtMethod* m,
Sebastien Hertzf3928792014-11-17 19:00:37 +01003208 DeoptimizationRequest::Kind deoptimization_kind)
Mathieu Chartier90443472015-07-16 20:32:27 -07003209 SHARED_REQUIRES(Locks::mutator_lock_, Locks::breakpoint_lock_) {
Sebastien Hertz4d1e9ab2014-09-18 16:03:34 +02003210 for (const Breakpoint& breakpoint : gBreakpoints) {
Sebastien Hertzf3928792014-11-17 19:00:37 +01003211 if (breakpoint.Method() == m) {
3212 CHECK_EQ(deoptimization_kind, breakpoint.GetDeoptimizationKind());
3213 }
Sebastien Hertz4d1e9ab2014-09-18 16:03:34 +02003214 }
Sebastien Hertzf3928792014-11-17 19:00:37 +01003215 instrumentation::Instrumentation* instrumentation = Runtime::Current()->GetInstrumentation();
3216 if (deoptimization_kind == DeoptimizationRequest::kFullDeoptimization) {
Sebastien Hertz4d1e9ab2014-09-18 16:03:34 +02003217 // We should have deoptimized everything but not "selectively" deoptimized this method.
Sebastien Hertzf3928792014-11-17 19:00:37 +01003218 CHECK(instrumentation->AreAllMethodsDeoptimized());
3219 CHECK(!instrumentation->IsDeoptimized(m));
3220 } else if (deoptimization_kind == DeoptimizationRequest::kSelectiveDeoptimization) {
Sebastien Hertz4d1e9ab2014-09-18 16:03:34 +02003221 // We should have "selectively" deoptimized this method.
3222 // Note: while we have not deoptimized everything for this method, we may have done it for
3223 // another event.
Sebastien Hertzf3928792014-11-17 19:00:37 +01003224 CHECK(instrumentation->IsDeoptimized(m));
3225 } else {
3226 // This method does not require deoptimization.
3227 CHECK_EQ(deoptimization_kind, DeoptimizationRequest::kNothing);
3228 CHECK(!instrumentation->IsDeoptimized(m));
3229 }
3230}
3231
Sebastien Hertzabe93e02014-12-17 16:35:50 +01003232// Returns the deoptimization kind required to set a breakpoint in a method.
3233// If a breakpoint has already been set, we also return the first breakpoint
3234// through the given 'existing_brkpt' pointer.
Sebastien Hertzf3928792014-11-17 19:00:37 +01003235static DeoptimizationRequest::Kind GetRequiredDeoptimizationKind(Thread* self,
Mathieu Chartiere401d142015-04-22 13:56:20 -07003236 ArtMethod* m,
Sebastien Hertzabe93e02014-12-17 16:35:50 +01003237 const Breakpoint** existing_brkpt)
Mathieu Chartier90443472015-07-16 20:32:27 -07003238 SHARED_REQUIRES(Locks::mutator_lock_) {
Sebastien Hertzf3928792014-11-17 19:00:37 +01003239 if (!Dbg::RequiresDeoptimization()) {
3240 // We already run in interpreter-only mode so we don't need to deoptimize anything.
3241 VLOG(jdwp) << "No need for deoptimization when fully running with interpreter for method "
3242 << PrettyMethod(m);
3243 return DeoptimizationRequest::kNothing;
3244 }
Sebastien Hertzabe93e02014-12-17 16:35:50 +01003245 const Breakpoint* first_breakpoint;
Sebastien Hertzf3928792014-11-17 19:00:37 +01003246 {
3247 ReaderMutexLock mu(self, *Locks::breakpoint_lock_);
Sebastien Hertzabe93e02014-12-17 16:35:50 +01003248 first_breakpoint = FindFirstBreakpointForMethod(m);
3249 *existing_brkpt = first_breakpoint;
Sebastien Hertzf3928792014-11-17 19:00:37 +01003250 }
Sebastien Hertzabe93e02014-12-17 16:35:50 +01003251
3252 if (first_breakpoint == nullptr) {
Sebastien Hertzf3928792014-11-17 19:00:37 +01003253 // There is no breakpoint on this method yet: we need to deoptimize. If this method may be
3254 // inlined, we deoptimize everything; otherwise we deoptimize only this method.
3255 // Note: IsMethodPossiblyInlined goes into the method verifier and may cause thread suspension.
3256 // Therefore we must not hold any lock when we call it.
3257 bool need_full_deoptimization = IsMethodPossiblyInlined(self, m);
3258 if (need_full_deoptimization) {
3259 VLOG(jdwp) << "Need full deoptimization because of possible inlining of method "
3260 << PrettyMethod(m);
3261 return DeoptimizationRequest::kFullDeoptimization;
3262 } else {
3263 // We don't need to deoptimize if the method has not been compiled.
3264 ClassLinker* const class_linker = Runtime::Current()->GetClassLinker();
3265 const bool is_compiled = class_linker->GetOatMethodQuickCodeFor(m) != nullptr;
3266 if (is_compiled) {
Sebastien Hertz6963e442014-11-26 22:11:27 +01003267 // If the method may be called through its direct code pointer (without loading
3268 // its updated entrypoint), we need full deoptimization to not miss the breakpoint.
3269 if (class_linker->MayBeCalledWithDirectCodePointer(m)) {
3270 VLOG(jdwp) << "Need full deoptimization because of possible direct code call "
3271 << "into image for compiled method " << PrettyMethod(m);
3272 return DeoptimizationRequest::kFullDeoptimization;
3273 } else {
3274 VLOG(jdwp) << "Need selective deoptimization for compiled method " << PrettyMethod(m);
3275 return DeoptimizationRequest::kSelectiveDeoptimization;
3276 }
Sebastien Hertzf3928792014-11-17 19:00:37 +01003277 } else {
3278 // Method is not compiled: we don't need to deoptimize.
3279 VLOG(jdwp) << "No need for deoptimization for non-compiled method " << PrettyMethod(m);
3280 return DeoptimizationRequest::kNothing;
3281 }
3282 }
3283 } else {
3284 // There is at least one breakpoint for this method: we don't need to deoptimize.
3285 // Let's check that all breakpoints are configured the same way for deoptimization.
3286 VLOG(jdwp) << "Breakpoint already set: no deoptimization is required";
Sebastien Hertzabe93e02014-12-17 16:35:50 +01003287 DeoptimizationRequest::Kind deoptimization_kind = first_breakpoint->GetDeoptimizationKind();
Sebastien Hertzf3928792014-11-17 19:00:37 +01003288 if (kIsDebugBuild) {
3289 ReaderMutexLock mu(self, *Locks::breakpoint_lock_);
3290 SanityCheckExistingBreakpoints(m, deoptimization_kind);
3291 }
3292 return DeoptimizationRequest::kNothing;
Sebastien Hertz138dbfc2013-12-04 18:15:25 +01003293 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -07003294}
3295
Sebastien Hertza76a6d42014-03-20 16:40:17 +01003296// Installs a breakpoint at the specified location. Also indicates through the deoptimization
3297// request if we need to deoptimize.
3298void Dbg::WatchLocation(const JDWP::JdwpLocation* location, DeoptimizationRequest* req) {
3299 Thread* const self = Thread::Current();
Mathieu Chartiere401d142015-04-22 13:56:20 -07003300 ArtMethod* m = FromMethodId(location->method_id);
Sebastien Hertza76a6d42014-03-20 16:40:17 +01003301 DCHECK(m != nullptr) << "No method for method id " << location->method_id;
Sebastien Hertz138dbfc2013-12-04 18:15:25 +01003302
Sebastien Hertzabe93e02014-12-17 16:35:50 +01003303 const Breakpoint* existing_breakpoint = nullptr;
3304 const DeoptimizationRequest::Kind deoptimization_kind =
3305 GetRequiredDeoptimizationKind(self, m, &existing_breakpoint);
Sebastien Hertzf3928792014-11-17 19:00:37 +01003306 req->SetKind(deoptimization_kind);
3307 if (deoptimization_kind == DeoptimizationRequest::kSelectiveDeoptimization) {
3308 req->SetMethod(m);
Sebastien Hertza76a6d42014-03-20 16:40:17 +01003309 } else {
Sebastien Hertzf3928792014-11-17 19:00:37 +01003310 CHECK(deoptimization_kind == DeoptimizationRequest::kNothing ||
3311 deoptimization_kind == DeoptimizationRequest::kFullDeoptimization);
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003312 req->SetMethod(nullptr);
Sebastien Hertz138dbfc2013-12-04 18:15:25 +01003313 }
3314
Sebastien Hertz4d1e9ab2014-09-18 16:03:34 +02003315 {
3316 WriterMutexLock mu(self, *Locks::breakpoint_lock_);
Sebastien Hertzabe93e02014-12-17 16:35:50 +01003317 // If there is at least one existing breakpoint on the same method, the new breakpoint
3318 // must have the same deoptimization kind than the existing breakpoint(s).
3319 DeoptimizationRequest::Kind breakpoint_deoptimization_kind;
3320 if (existing_breakpoint != nullptr) {
3321 breakpoint_deoptimization_kind = existing_breakpoint->GetDeoptimizationKind();
3322 } else {
3323 breakpoint_deoptimization_kind = deoptimization_kind;
3324 }
3325 gBreakpoints.push_back(Breakpoint(m, location->dex_pc, breakpoint_deoptimization_kind));
Sebastien Hertz4d1e9ab2014-09-18 16:03:34 +02003326 VLOG(jdwp) << "Set breakpoint #" << (gBreakpoints.size() - 1) << ": "
3327 << gBreakpoints[gBreakpoints.size() - 1];
3328 }
Sebastien Hertza76a6d42014-03-20 16:40:17 +01003329}
3330
3331// Uninstalls a breakpoint at the specified location. Also indicates through the deoptimization
3332// request if we need to undeoptimize.
3333void Dbg::UnwatchLocation(const JDWP::JdwpLocation* location, DeoptimizationRequest* req) {
Sebastien Hertzed2be172014-08-19 15:33:43 +02003334 WriterMutexLock mu(Thread::Current(), *Locks::breakpoint_lock_);
Mathieu Chartiere401d142015-04-22 13:56:20 -07003335 ArtMethod* m = FromMethodId(location->method_id);
Sebastien Hertza76a6d42014-03-20 16:40:17 +01003336 DCHECK(m != nullptr) << "No method for method id " << location->method_id;
Sebastien Hertzf3928792014-11-17 19:00:37 +01003337 DeoptimizationRequest::Kind deoptimization_kind = DeoptimizationRequest::kNothing;
Sebastien Hertza76a6d42014-03-20 16:40:17 +01003338 for (size_t i = 0, e = gBreakpoints.size(); i < e; ++i) {
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003339 if (gBreakpoints[i].DexPc() == location->dex_pc && gBreakpoints[i].Method() == m) {
Sebastien Hertza76a6d42014-03-20 16:40:17 +01003340 VLOG(jdwp) << "Removed breakpoint #" << i << ": " << gBreakpoints[i];
Sebastien Hertzf3928792014-11-17 19:00:37 +01003341 deoptimization_kind = gBreakpoints[i].GetDeoptimizationKind();
3342 DCHECK_EQ(deoptimization_kind == DeoptimizationRequest::kSelectiveDeoptimization,
3343 Runtime::Current()->GetInstrumentation()->IsDeoptimized(m));
Sebastien Hertza76a6d42014-03-20 16:40:17 +01003344 gBreakpoints.erase(gBreakpoints.begin() + i);
3345 break;
3346 }
3347 }
3348 const Breakpoint* const existing_breakpoint = FindFirstBreakpointForMethod(m);
3349 if (existing_breakpoint == nullptr) {
3350 // There is no more breakpoint on this method: we need to undeoptimize.
Sebastien Hertzf3928792014-11-17 19:00:37 +01003351 if (deoptimization_kind == DeoptimizationRequest::kFullDeoptimization) {
Sebastien Hertza76a6d42014-03-20 16:40:17 +01003352 // This method required full deoptimization: we need to undeoptimize everything.
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003353 req->SetKind(DeoptimizationRequest::kFullUndeoptimization);
3354 req->SetMethod(nullptr);
Sebastien Hertzf3928792014-11-17 19:00:37 +01003355 } else if (deoptimization_kind == DeoptimizationRequest::kSelectiveDeoptimization) {
Sebastien Hertza76a6d42014-03-20 16:40:17 +01003356 // This method required selective deoptimization: we need to undeoptimize only that method.
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003357 req->SetKind(DeoptimizationRequest::kSelectiveUndeoptimization);
3358 req->SetMethod(m);
Sebastien Hertzf3928792014-11-17 19:00:37 +01003359 } else {
3360 // This method had no need for deoptimization: do nothing.
3361 CHECK_EQ(deoptimization_kind, DeoptimizationRequest::kNothing);
3362 req->SetKind(DeoptimizationRequest::kNothing);
3363 req->SetMethod(nullptr);
Sebastien Hertza76a6d42014-03-20 16:40:17 +01003364 }
3365 } else {
3366 // There is at least one breakpoint for this method: we don't need to undeoptimize.
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003367 req->SetKind(DeoptimizationRequest::kNothing);
3368 req->SetMethod(nullptr);
Sebastien Hertz4d1e9ab2014-09-18 16:03:34 +02003369 if (kIsDebugBuild) {
Sebastien Hertzf3928792014-11-17 19:00:37 +01003370 SanityCheckExistingBreakpoints(m, deoptimization_kind);
Sebastien Hertz4d1e9ab2014-09-18 16:03:34 +02003371 }
Elliott Hughes86964332012-02-15 19:37:42 -08003372 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -07003373}
3374
Mathieu Chartiere401d142015-04-22 13:56:20 -07003375bool Dbg::IsForcedInterpreterNeededForCallingImpl(Thread* thread, ArtMethod* m) {
Daniel Mihalyieb076692014-08-22 17:33:31 +02003376 const SingleStepControl* const ssc = thread->GetSingleStepControl();
3377 if (ssc == nullptr) {
3378 // If we are not single-stepping, then we don't have to force interpreter.
3379 return false;
3380 }
3381 if (Runtime::Current()->GetInstrumentation()->InterpretOnly()) {
3382 // If we are in interpreter only mode, then we don't have to force interpreter.
3383 return false;
3384 }
3385
3386 if (!m->IsNative() && !m->IsProxyMethod()) {
3387 // If we want to step into a method, then we have to force interpreter on that call.
3388 if (ssc->GetStepDepth() == JDWP::SD_INTO) {
3389 return true;
3390 }
3391 }
3392 return false;
3393}
3394
Mathieu Chartiere401d142015-04-22 13:56:20 -07003395bool Dbg::IsForcedInterpreterNeededForResolutionImpl(Thread* thread, ArtMethod* m) {
Daniel Mihalyieb076692014-08-22 17:33:31 +02003396 instrumentation::Instrumentation* const instrumentation =
3397 Runtime::Current()->GetInstrumentation();
3398 // If we are in interpreter only mode, then we don't have to force interpreter.
3399 if (instrumentation->InterpretOnly()) {
3400 return false;
3401 }
3402 // We can only interpret pure Java method.
3403 if (m->IsNative() || m->IsProxyMethod()) {
3404 return false;
3405 }
3406 const SingleStepControl* const ssc = thread->GetSingleStepControl();
3407 if (ssc != nullptr) {
3408 // If we want to step into a method, then we have to force interpreter on that call.
3409 if (ssc->GetStepDepth() == JDWP::SD_INTO) {
3410 return true;
3411 }
3412 // If we are stepping out from a static initializer, by issuing a step
3413 // in or step over, that was implicitly invoked by calling a static method,
3414 // then we need to step into that method. Having a lower stack depth than
3415 // the one the single step control has indicates that the step originates
3416 // from the static initializer.
3417 if (ssc->GetStepDepth() != JDWP::SD_OUT &&
3418 ssc->GetStackDepth() > GetStackDepth(thread)) {
3419 return true;
3420 }
3421 }
3422 // There are cases where we have to force interpreter on deoptimized methods,
3423 // because in some cases the call will not be performed by invoking an entry
3424 // point that has been replaced by the deoptimization, but instead by directly
3425 // invoking the compiled code of the method, for example.
3426 return instrumentation->IsDeoptimized(m);
3427}
3428
Mathieu Chartiere401d142015-04-22 13:56:20 -07003429bool Dbg::IsForcedInstrumentationNeededForResolutionImpl(Thread* thread, ArtMethod* m) {
Mathieu Chartier2cebb242015-04-21 16:50:40 -07003430 // The upcall can be null and in that case we don't need to do anything.
Daniel Mihalyieb076692014-08-22 17:33:31 +02003431 if (m == nullptr) {
3432 return false;
3433 }
3434 instrumentation::Instrumentation* const instrumentation =
3435 Runtime::Current()->GetInstrumentation();
3436 // If we are in interpreter only mode, then we don't have to force interpreter.
3437 if (instrumentation->InterpretOnly()) {
3438 return false;
3439 }
3440 // We can only interpret pure Java method.
3441 if (m->IsNative() || m->IsProxyMethod()) {
3442 return false;
3443 }
3444 const SingleStepControl* const ssc = thread->GetSingleStepControl();
3445 if (ssc != nullptr) {
3446 // If we are stepping out from a static initializer, by issuing a step
3447 // out, that was implicitly invoked by calling a static method, then we
3448 // need to step into the caller of that method. Having a lower stack
3449 // depth than the one the single step control has indicates that the
3450 // step originates from the static initializer.
3451 if (ssc->GetStepDepth() == JDWP::SD_OUT &&
3452 ssc->GetStackDepth() > GetStackDepth(thread)) {
3453 return true;
3454 }
3455 }
3456 // If we are returning from a static intializer, that was implicitly
3457 // invoked by calling a static method and the caller is deoptimized,
3458 // then we have to deoptimize the stack without forcing interpreter
3459 // on the static method that was called originally. This problem can
3460 // be solved easily by forcing instrumentation on the called method,
3461 // because the instrumentation exit hook will recognise the need of
3462 // stack deoptimization by calling IsForcedInterpreterNeededForUpcall.
3463 return instrumentation->IsDeoptimized(m);
3464}
3465
Mathieu Chartiere401d142015-04-22 13:56:20 -07003466bool Dbg::IsForcedInterpreterNeededForUpcallImpl(Thread* thread, ArtMethod* m) {
Mathieu Chartier2cebb242015-04-21 16:50:40 -07003467 // The upcall can be null and in that case we don't need to do anything.
Daniel Mihalyieb076692014-08-22 17:33:31 +02003468 if (m == nullptr) {
3469 return false;
3470 }
3471 instrumentation::Instrumentation* const instrumentation =
3472 Runtime::Current()->GetInstrumentation();
3473 // If we are in interpreter only mode, then we don't have to force interpreter.
3474 if (instrumentation->InterpretOnly()) {
3475 return false;
3476 }
3477 // We can only interpret pure Java method.
3478 if (m->IsNative() || m->IsProxyMethod()) {
3479 return false;
3480 }
3481 const SingleStepControl* const ssc = thread->GetSingleStepControl();
3482 if (ssc != nullptr) {
3483 // The debugger is not interested in what is happening under the level
3484 // of the step, thus we only force interpreter when we are not below of
3485 // the step.
3486 if (ssc->GetStackDepth() >= GetStackDepth(thread)) {
3487 return true;
3488 }
3489 }
3490 // We have to require stack deoptimization if the upcall is deoptimized.
3491 return instrumentation->IsDeoptimized(m);
3492}
3493
Jeff Hao449db332013-04-12 18:30:52 -07003494// Scoped utility class to suspend a thread so that we may do tasks such as walk its stack. Doesn't
3495// cause suspension if the thread is the current thread.
3496class ScopedThreadSuspension {
3497 public:
Ian Rogers33e95662013-05-20 20:29:14 -07003498 ScopedThreadSuspension(Thread* self, JDWP::ObjectId thread_id)
Mathieu Chartier90443472015-07-16 20:32:27 -07003499 REQUIRES(!Locks::thread_list_lock_)
3500 SHARED_REQUIRES(Locks::mutator_lock_) :
Ian Rogersf3d874c2014-07-17 18:52:42 -07003501 thread_(nullptr),
Jeff Hao449db332013-04-12 18:30:52 -07003502 error_(JDWP::ERR_NONE),
3503 self_suspend_(false),
Ian Rogers33e95662013-05-20 20:29:14 -07003504 other_suspend_(false) {
Jeff Hao449db332013-04-12 18:30:52 -07003505 ScopedObjectAccessUnchecked soa(self);
Sebastien Hertz69206392015-04-07 15:54:25 +02003506 thread_ = DecodeThread(soa, thread_id, &error_);
Jeff Hao449db332013-04-12 18:30:52 -07003507 if (error_ == JDWP::ERR_NONE) {
3508 if (thread_ == soa.Self()) {
3509 self_suspend_ = true;
3510 } else {
3511 soa.Self()->TransitionFromRunnableToSuspended(kWaitingForDebuggerSuspension);
Sebastien Hertz6995c602014-09-09 12:10:13 +02003512 jobject thread_peer = Dbg::GetObjectRegistry()->GetJObject(thread_id);
Jeff Hao449db332013-04-12 18:30:52 -07003513 bool timed_out;
Ian Rogers4ad5cd32014-11-11 23:08:07 -08003514 ThreadList* thread_list = Runtime::Current()->GetThreadList();
3515 Thread* suspended_thread = thread_list->SuspendThreadByPeer(thread_peer, true, true,
3516 &timed_out);
Jeff Hao449db332013-04-12 18:30:52 -07003517 CHECK_EQ(soa.Self()->TransitionFromSuspendedToRunnable(), kWaitingForDebuggerSuspension);
Ian Rogersf3d874c2014-07-17 18:52:42 -07003518 if (suspended_thread == nullptr) {
Jeff Hao449db332013-04-12 18:30:52 -07003519 // Thread terminated from under us while suspending.
3520 error_ = JDWP::ERR_INVALID_THREAD;
3521 } else {
3522 CHECK_EQ(suspended_thread, thread_);
3523 other_suspend_ = true;
3524 }
3525 }
3526 }
Elliott Hughes2435a572012-02-17 16:07:41 -08003527 }
Elliott Hughes86964332012-02-15 19:37:42 -08003528
Jeff Hao449db332013-04-12 18:30:52 -07003529 Thread* GetThread() const {
3530 return thread_;
3531 }
3532
3533 JDWP::JdwpError GetError() const {
3534 return error_;
3535 }
3536
3537 ~ScopedThreadSuspension() {
3538 if (other_suspend_) {
3539 Runtime::Current()->GetThreadList()->Resume(thread_, true);
3540 }
3541 }
3542
3543 private:
3544 Thread* thread_;
3545 JDWP::JdwpError error_;
3546 bool self_suspend_;
3547 bool other_suspend_;
3548};
3549
3550JDWP::JdwpError Dbg::ConfigureStep(JDWP::ObjectId thread_id, JDWP::JdwpStepSize step_size,
3551 JDWP::JdwpStepDepth step_depth) {
3552 Thread* self = Thread::Current();
3553 ScopedThreadSuspension sts(self, thread_id);
3554 if (sts.GetError() != JDWP::ERR_NONE) {
3555 return sts.GetError();
3556 }
3557
Sebastien Hertz597c4f02015-01-26 17:37:14 +01003558 // Work out what ArtMethod* we're in, the current line number, and how deep the stack currently
Elliott Hughes2435a572012-02-17 16:07:41 -08003559 // is for step-out.
Ian Rogers0399dde2012-06-06 17:09:28 -07003560 struct SingleStepStackVisitor : public StackVisitor {
Mathieu Chartier90443472015-07-16 20:32:27 -07003561 explicit SingleStepStackVisitor(Thread* thread) SHARED_REQUIRES(Locks::mutator_lock_)
Nicolas Geoffray8e5bd182015-05-06 11:34:34 +01003562 : StackVisitor(thread, nullptr, StackVisitor::StackWalkKind::kIncludeInlinedFrames),
3563 stack_depth(0),
3564 method(nullptr),
3565 line_number(-1) {}
Ian Rogersca190662012-06-26 15:45:57 -07003566
Ian Rogers00f7d0e2012-07-19 15:28:27 -07003567 // TODO: Enable annotalysis. We know lock is held in constructor, but abstraction confuses
3568 // annotalysis.
3569 bool VisitFrame() NO_THREAD_SAFETY_ANALYSIS {
Mathieu Chartiere401d142015-04-22 13:56:20 -07003570 ArtMethod* m = GetMethod();
Ian Rogers0399dde2012-06-06 17:09:28 -07003571 if (!m->IsRuntimeMethod()) {
Sebastien Hertz597c4f02015-01-26 17:37:14 +01003572 ++stack_depth;
3573 if (method == nullptr) {
Ian Rogersef7d42f2014-01-06 12:55:46 -08003574 mirror::DexCache* dex_cache = m->GetDeclaringClass()->GetDexCache();
Sebastien Hertz597c4f02015-01-26 17:37:14 +01003575 method = m;
Ian Rogersc0542af2014-09-03 16:16:56 -07003576 if (dex_cache != nullptr) {
Ian Rogers4445a7e2012-10-05 17:19:13 -07003577 const DexFile& dex_file = *dex_cache->GetDexFile();
Sebastien Hertz597c4f02015-01-26 17:37:14 +01003578 line_number = dex_file.GetLineNumFromPC(m, GetDexPc());
Elliott Hughes2435a572012-02-17 16:07:41 -08003579 }
Elliott Hughes86964332012-02-15 19:37:42 -08003580 }
3581 }
Elliott Hughes530fa002012-03-12 11:44:49 -07003582 return true;
Elliott Hughes86964332012-02-15 19:37:42 -08003583 }
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01003584
Sebastien Hertz597c4f02015-01-26 17:37:14 +01003585 int stack_depth;
Mathieu Chartiere401d142015-04-22 13:56:20 -07003586 ArtMethod* method;
Sebastien Hertz597c4f02015-01-26 17:37:14 +01003587 int32_t line_number;
Elliott Hughes86964332012-02-15 19:37:42 -08003588 };
Jeff Hao449db332013-04-12 18:30:52 -07003589
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01003590 Thread* const thread = sts.GetThread();
Sebastien Hertz597c4f02015-01-26 17:37:14 +01003591 SingleStepStackVisitor visitor(thread);
Ian Rogers0399dde2012-06-06 17:09:28 -07003592 visitor.WalkStack();
Elliott Hughes86964332012-02-15 19:37:42 -08003593
Elliott Hughes2435a572012-02-17 16:07:41 -08003594 // Find the dex_pc values that correspond to the current line, for line-based single-stepping.
Elliott Hughes2435a572012-02-17 16:07:41 -08003595 struct DebugCallbackContext {
Roland Levillain3887c462015-08-12 18:15:42 +01003596 DebugCallbackContext(SingleStepControl* single_step_control_cb,
3597 int32_t line_number_cb, const DexFile::CodeItem* code_item)
3598 : single_step_control_(single_step_control_cb), line_number_(line_number_cb),
3599 code_item_(code_item), last_pc_valid(false), last_pc(0) {
Elliott Hughes2435a572012-02-17 16:07:41 -08003600 }
3601
Andreas Gampe277ccbd2014-11-03 21:36:10 -08003602 static bool Callback(void* raw_context, uint32_t address, uint32_t line_number_cb) {
Elliott Hughes2435a572012-02-17 16:07:41 -08003603 DebugCallbackContext* context = reinterpret_cast<DebugCallbackContext*>(raw_context);
Andreas Gampe277ccbd2014-11-03 21:36:10 -08003604 if (static_cast<int32_t>(line_number_cb) == context->line_number_) {
Elliott Hughes2435a572012-02-17 16:07:41 -08003605 if (!context->last_pc_valid) {
3606 // Everything from this address until the next line change is ours.
3607 context->last_pc = address;
3608 context->last_pc_valid = true;
3609 }
3610 // Otherwise, if we're already in a valid range for this line,
3611 // just keep going (shouldn't really happen)...
Brian Carlstrom7934ac22013-07-26 10:54:15 -07003612 } else if (context->last_pc_valid) { // and the line number is new
Elliott Hughes2435a572012-02-17 16:07:41 -08003613 // Add everything from the last entry up until here to the set
3614 for (uint32_t dex_pc = context->last_pc; dex_pc < address; ++dex_pc) {
Sebastien Hertz597c4f02015-01-26 17:37:14 +01003615 context->single_step_control_->AddDexPc(dex_pc);
Elliott Hughes2435a572012-02-17 16:07:41 -08003616 }
3617 context->last_pc_valid = false;
3618 }
Brian Carlstrom7934ac22013-07-26 10:54:15 -07003619 return false; // There may be multiple entries for any given line.
Elliott Hughes2435a572012-02-17 16:07:41 -08003620 }
3621
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01003622 ~DebugCallbackContext() {
Elliott Hughes2435a572012-02-17 16:07:41 -08003623 // If the line number was the last in the position table...
3624 if (last_pc_valid) {
Sebastien Hertzbb43b432014-04-14 11:59:08 +02003625 size_t end = code_item_->insns_size_in_code_units_;
Elliott Hughes2435a572012-02-17 16:07:41 -08003626 for (uint32_t dex_pc = last_pc; dex_pc < end; ++dex_pc) {
Sebastien Hertz597c4f02015-01-26 17:37:14 +01003627 single_step_control_->AddDexPc(dex_pc);
Elliott Hughes2435a572012-02-17 16:07:41 -08003628 }
3629 }
3630 }
3631
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01003632 SingleStepControl* const single_step_control_;
3633 const int32_t line_number_;
Sebastien Hertzbb43b432014-04-14 11:59:08 +02003634 const DexFile::CodeItem* const code_item_;
Elliott Hughes2435a572012-02-17 16:07:41 -08003635 bool last_pc_valid;
3636 uint32_t last_pc;
3637 };
Sebastien Hertz597c4f02015-01-26 17:37:14 +01003638
3639 // Allocate single step.
Sebastien Hertz1558b572015-02-25 15:05:59 +01003640 SingleStepControl* single_step_control =
3641 new (std::nothrow) SingleStepControl(step_size, step_depth,
3642 visitor.stack_depth, visitor.method);
3643 if (single_step_control == nullptr) {
3644 LOG(ERROR) << "Failed to allocate SingleStepControl";
3645 return JDWP::ERR_OUT_OF_MEMORY;
3646 }
3647
Mathieu Chartiere401d142015-04-22 13:56:20 -07003648 ArtMethod* m = single_step_control->GetMethod();
Sebastien Hertz597c4f02015-01-26 17:37:14 +01003649 const int32_t line_number = visitor.line_number;
Sebastien Hertz52f5f932015-05-28 11:00:57 +02003650 // Note: if the thread is not running Java code (pure native thread), there is no "current"
3651 // method on the stack (and no line number either).
3652 if (m != nullptr && !m->IsNative()) {
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07003653 const DexFile::CodeItem* const code_item = m->GetCodeItem();
Sebastien Hertzbb43b432014-04-14 11:59:08 +02003654 DebugCallbackContext context(single_step_control, line_number, code_item);
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07003655 m->GetDexFile()->DecodeDebugInfo(code_item, m->IsStatic(), m->GetDexMethodIndex(),
Ian Rogersc0542af2014-09-03 16:16:56 -07003656 DebugCallbackContext::Callback, nullptr, &context);
Elliott Hughes3e2e1a22012-02-21 11:33:41 -08003657 }
Elliott Hughes2435a572012-02-17 16:07:41 -08003658
Sebastien Hertz597c4f02015-01-26 17:37:14 +01003659 // Activate single-step in the thread.
3660 thread->ActivateSingleStepControl(single_step_control);
Elliott Hughes86964332012-02-15 19:37:42 -08003661
Elliott Hughes2435a572012-02-17 16:07:41 -08003662 if (VLOG_IS_ON(jdwp)) {
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01003663 VLOG(jdwp) << "Single-step thread: " << *thread;
Sebastien Hertz597c4f02015-01-26 17:37:14 +01003664 VLOG(jdwp) << "Single-step step size: " << single_step_control->GetStepSize();
3665 VLOG(jdwp) << "Single-step step depth: " << single_step_control->GetStepDepth();
3666 VLOG(jdwp) << "Single-step current method: " << PrettyMethod(single_step_control->GetMethod());
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01003667 VLOG(jdwp) << "Single-step current line: " << line_number;
Sebastien Hertz597c4f02015-01-26 17:37:14 +01003668 VLOG(jdwp) << "Single-step current stack depth: " << single_step_control->GetStackDepth();
Elliott Hughes2435a572012-02-17 16:07:41 -08003669 VLOG(jdwp) << "Single-step dex_pc values:";
Sebastien Hertz597c4f02015-01-26 17:37:14 +01003670 for (uint32_t dex_pc : single_step_control->GetDexPcs()) {
Sebastien Hertzbb43b432014-04-14 11:59:08 +02003671 VLOG(jdwp) << StringPrintf(" %#x", dex_pc);
Elliott Hughes2435a572012-02-17 16:07:41 -08003672 }
3673 }
3674
3675 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07003676}
3677
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01003678void Dbg::UnconfigureStep(JDWP::ObjectId thread_id) {
3679 ScopedObjectAccessUnchecked soa(Thread::Current());
Ian Rogersc0542af2014-09-03 16:16:56 -07003680 JDWP::JdwpError error;
3681 Thread* thread = DecodeThread(soa, thread_id, &error);
Sebastien Hertz87118ed2013-11-26 17:57:18 +01003682 if (error == JDWP::ERR_NONE) {
Sebastien Hertz597c4f02015-01-26 17:37:14 +01003683 thread->DeactivateSingleStepControl();
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01003684 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -07003685}
3686
Elliott Hughes45651fd2012-02-21 15:48:20 -08003687static char JdwpTagToShortyChar(JDWP::JdwpTag tag) {
3688 switch (tag) {
3689 default:
3690 LOG(FATAL) << "unknown JDWP tag: " << PrintableChar(tag);
Ian Rogersfc787ec2014-10-09 21:56:44 -07003691 UNREACHABLE();
Elliott Hughes45651fd2012-02-21 15:48:20 -08003692
3693 // Primitives.
3694 case JDWP::JT_BYTE: return 'B';
3695 case JDWP::JT_CHAR: return 'C';
3696 case JDWP::JT_FLOAT: return 'F';
3697 case JDWP::JT_DOUBLE: return 'D';
3698 case JDWP::JT_INT: return 'I';
3699 case JDWP::JT_LONG: return 'J';
3700 case JDWP::JT_SHORT: return 'S';
3701 case JDWP::JT_VOID: return 'V';
3702 case JDWP::JT_BOOLEAN: return 'Z';
3703
3704 // Reference types.
3705 case JDWP::JT_ARRAY:
3706 case JDWP::JT_OBJECT:
3707 case JDWP::JT_STRING:
3708 case JDWP::JT_THREAD:
3709 case JDWP::JT_THREAD_GROUP:
3710 case JDWP::JT_CLASS_LOADER:
3711 case JDWP::JT_CLASS_OBJECT:
3712 return 'L';
3713 }
3714}
3715
Sebastien Hertzcbc50642015-06-01 17:33:12 +02003716JDWP::JdwpError Dbg::PrepareInvokeMethod(uint32_t request_id, JDWP::ObjectId thread_id,
3717 JDWP::ObjectId object_id, JDWP::RefTypeId class_id,
3718 JDWP::MethodId method_id, uint32_t arg_count,
3719 uint64_t arg_values[], JDWP::JdwpTag* arg_types,
3720 uint32_t options) {
3721 Thread* const self = Thread::Current();
3722 CHECK_EQ(self, GetDebugThread()) << "This must be called by the JDWP thread";
Sebastien Hertzd4032e42015-06-12 15:47:34 +02003723 const bool resume_all_threads = ((options & JDWP::INVOKE_SINGLE_THREADED) == 0);
Elliott Hughesd07986f2011-12-06 18:27:45 -08003724
Sebastien Hertzcbc50642015-06-01 17:33:12 +02003725 ThreadList* thread_list = Runtime::Current()->GetThreadList();
Ian Rogersc0542af2014-09-03 16:16:56 -07003726 Thread* targetThread = nullptr;
Elliott Hughesd07986f2011-12-06 18:27:45 -08003727 {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07003728 ScopedObjectAccessUnchecked soa(self);
Ian Rogersc0542af2014-09-03 16:16:56 -07003729 JDWP::JdwpError error;
3730 targetThread = DecodeThread(soa, thread_id, &error);
Elliott Hughes221229c2013-01-08 18:17:50 -08003731 if (error != JDWP::ERR_NONE) {
3732 LOG(ERROR) << "InvokeMethod request for invalid thread id " << thread_id;
3733 return error;
Elliott Hughesd07986f2011-12-06 18:27:45 -08003734 }
Sebastien Hertz1558b572015-02-25 15:05:59 +01003735 if (targetThread->GetInvokeReq() != nullptr) {
3736 // Thread is already invoking a method on behalf of the debugger.
3737 LOG(ERROR) << "InvokeMethod request for thread already invoking a method: " << *targetThread;
3738 return JDWP::ERR_ALREADY_INVOKING;
3739 }
3740 if (!targetThread->IsReadyForDebugInvoke()) {
3741 // Thread is not suspended by an event so it cannot invoke a method.
Elliott Hughesd07986f2011-12-06 18:27:45 -08003742 LOG(ERROR) << "InvokeMethod request for thread not stopped by event: " << *targetThread;
3743 return JDWP::ERR_INVALID_THREAD;
3744 }
3745
3746 /*
Sebastien Hertzd4032e42015-06-12 15:47:34 +02003747 * According to the JDWP specs, we are expected to resume all threads (or only the
3748 * target thread) once. So if a thread has been suspended more than once (either by
3749 * the debugger for an event or by the runtime for GC), it will remain suspended before
3750 * the invoke is executed. This means the debugger is responsible to properly resume all
3751 * the threads it has suspended so the target thread can execute the method.
Elliott Hughesd07986f2011-12-06 18:27:45 -08003752 *
Sebastien Hertzd4032e42015-06-12 15:47:34 +02003753 * However, for compatibility reason with older versions of debuggers (like Eclipse), we
3754 * fully resume all threads (by canceling *all* debugger suspensions) when the debugger
3755 * wants us to resume all threads. This is to avoid ending up in deadlock situation.
3756 *
3757 * On the other hand, if we are asked to only resume the target thread, then we follow the
3758 * JDWP specs by resuming that thread only once. This means the thread will remain suspended
3759 * if it has been suspended more than once before the invoke (and again, this is the
3760 * responsibility of the debugger to properly resume that thread before invoking a method).
Elliott Hughesd07986f2011-12-06 18:27:45 -08003761 */
Ian Rogers00f7d0e2012-07-19 15:28:27 -07003762 int suspend_count;
3763 {
Ian Rogers50b35e22012-10-04 10:09:15 -07003764 MutexLock mu2(soa.Self(), *Locks::thread_suspend_count_lock_);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07003765 suspend_count = targetThread->GetSuspendCount();
3766 }
Sebastien Hertzd4032e42015-06-12 15:47:34 +02003767 if (suspend_count > 1 && resume_all_threads) {
3768 // The target thread will remain suspended even after we resume it. Let's emit a warning
3769 // to indicate the invoke won't be executed until the thread is resumed.
3770 LOG(WARNING) << *targetThread << " suspended more than once (suspend count == "
3771 << suspend_count << "). This thread will invoke the method only once "
3772 << "it is fully resumed.";
Elliott Hughesd07986f2011-12-06 18:27:45 -08003773 }
3774
Ian Rogersc0542af2014-09-03 16:16:56 -07003775 mirror::Object* receiver = gRegistry->Get<mirror::Object*>(object_id, &error);
3776 if (error != JDWP::ERR_NONE) {
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08003777 return JDWP::ERR_INVALID_OBJECT;
3778 }
Elliott Hughes45651fd2012-02-21 15:48:20 -08003779
Sebastien Hertz1558b572015-02-25 15:05:59 +01003780 gRegistry->Get<mirror::Object*>(thread_id, &error);
Ian Rogersc0542af2014-09-03 16:16:56 -07003781 if (error != JDWP::ERR_NONE) {
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08003782 return JDWP::ERR_INVALID_OBJECT;
3783 }
Elliott Hughes45651fd2012-02-21 15:48:20 -08003784
Ian Rogersc0542af2014-09-03 16:16:56 -07003785 mirror::Class* c = DecodeClass(class_id, &error);
3786 if (c == nullptr) {
3787 return error;
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08003788 }
Elliott Hughes45651fd2012-02-21 15:48:20 -08003789
Mathieu Chartiere401d142015-04-22 13:56:20 -07003790 ArtMethod* m = FromMethodId(method_id);
Ian Rogersc0542af2014-09-03 16:16:56 -07003791 if (m->IsStatic() != (receiver == nullptr)) {
Elliott Hughes45651fd2012-02-21 15:48:20 -08003792 return JDWP::ERR_INVALID_METHODID;
3793 }
3794 if (m->IsStatic()) {
3795 if (m->GetDeclaringClass() != c) {
3796 return JDWP::ERR_INVALID_METHODID;
3797 }
3798 } else {
3799 if (!m->GetDeclaringClass()->IsAssignableFrom(c)) {
3800 return JDWP::ERR_INVALID_METHODID;
3801 }
3802 }
3803
3804 // Check the argument list matches the method.
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07003805 uint32_t shorty_len = 0;
3806 const char* shorty = m->GetShorty(&shorty_len);
3807 if (shorty_len - 1 != arg_count) {
Elliott Hughes45651fd2012-02-21 15:48:20 -08003808 return JDWP::ERR_ILLEGAL_ARGUMENT;
3809 }
Elliott Hughes09201632013-04-15 15:50:07 -07003810
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07003811 {
Mathieu Chartiere401d142015-04-22 13:56:20 -07003812 StackHandleScope<2> hs(soa.Self());
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07003813 HandleWrapper<mirror::Object> h_obj(hs.NewHandleWrapper(&receiver));
3814 HandleWrapper<mirror::Class> h_klass(hs.NewHandleWrapper(&c));
3815 const DexFile::TypeList* types = m->GetParameterTypeList();
3816 for (size_t i = 0; i < arg_count; ++i) {
3817 if (shorty[i + 1] != JdwpTagToShortyChar(arg_types[i])) {
Elliott Hughes09201632013-04-15 15:50:07 -07003818 return JDWP::ERR_ILLEGAL_ARGUMENT;
3819 }
3820
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07003821 if (shorty[i + 1] == 'L') {
3822 // Did we really get an argument of an appropriate reference type?
Ian Rogersa0485602014-12-02 15:48:04 -08003823 mirror::Class* parameter_type =
Vladimir Marko05792b92015-08-03 11:56:49 +01003824 m->GetClassFromTypeIndex(types->GetTypeItem(i).type_idx_,
3825 true /* resolve */,
3826 sizeof(void*));
Ian Rogersc0542af2014-09-03 16:16:56 -07003827 mirror::Object* argument = gRegistry->Get<mirror::Object*>(arg_values[i], &error);
3828 if (error != JDWP::ERR_NONE) {
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07003829 return JDWP::ERR_INVALID_OBJECT;
3830 }
Ian Rogersc0542af2014-09-03 16:16:56 -07003831 if (argument != nullptr && !argument->InstanceOf(parameter_type)) {
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07003832 return JDWP::ERR_ILLEGAL_ARGUMENT;
3833 }
3834
3835 // Turn the on-the-wire ObjectId into a jobject.
3836 jvalue& v = reinterpret_cast<jvalue&>(arg_values[i]);
3837 v.l = gRegistry->GetJObject(arg_values[i]);
3838 }
Elliott Hughes09201632013-04-15 15:50:07 -07003839 }
Elliott Hughes45651fd2012-02-21 15:48:20 -08003840 }
3841
Sebastien Hertz1558b572015-02-25 15:05:59 +01003842 // Allocates a DebugInvokeReq.
Sebastien Hertzcbc50642015-06-01 17:33:12 +02003843 DebugInvokeReq* req = new (std::nothrow) DebugInvokeReq(request_id, thread_id, receiver, c, m,
3844 options, arg_values, arg_count);
3845 if (req == nullptr) {
Sebastien Hertz1558b572015-02-25 15:05:59 +01003846 LOG(ERROR) << "Failed to allocate DebugInvokeReq";
3847 return JDWP::ERR_OUT_OF_MEMORY;
3848 }
3849
Sebastien Hertzcbc50642015-06-01 17:33:12 +02003850 // Attaches the DebugInvokeReq to the target thread so it executes the method when
3851 // it is resumed. Once the invocation completes, the target thread will delete it before
3852 // suspending itself (see ThreadList::SuspendSelfForDebugger).
3853 targetThread->SetDebugInvokeReq(req);
Elliott Hughesd07986f2011-12-06 18:27:45 -08003854 }
3855
3856 // 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 +02003857 // away we're sitting high and dry -- but we must release this before the UndoDebuggerSuspensions
3858 // call.
Sebastien Hertzd4032e42015-06-12 15:47:34 +02003859 if (resume_all_threads) {
Sebastien Hertzcbc50642015-06-01 17:33:12 +02003860 VLOG(jdwp) << " Resuming all threads";
3861 thread_list->UndoDebuggerSuspensions();
3862 } else {
3863 VLOG(jdwp) << " Resuming event thread only";
Elliott Hughesd07986f2011-12-06 18:27:45 -08003864 thread_list->Resume(targetThread, true);
3865 }
3866
Sebastien Hertzcbc50642015-06-01 17:33:12 +02003867 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07003868}
3869
3870void Dbg::ExecuteMethod(DebugInvokeReq* pReq) {
Sebastien Hertzcbc50642015-06-01 17:33:12 +02003871 Thread* const self = Thread::Current();
3872 CHECK_NE(self, GetDebugThread()) << "This must be called by the event thread";
3873
3874 ScopedObjectAccess soa(self);
Elliott Hughesd07986f2011-12-06 18:27:45 -08003875
Elliott Hughes81ff3182012-03-23 20:35:56 -07003876 // We can be called while an exception is pending. We need
Elliott Hughesd07986f2011-12-06 18:27:45 -08003877 // to preserve that across the method invocation.
Sebastien Hertzcbc50642015-06-01 17:33:12 +02003878 StackHandleScope<1> hs(soa.Self());
3879 Handle<mirror::Throwable> old_exception = hs.NewHandle(soa.Self()->GetException());
Sebastien Hertz1558b572015-02-25 15:05:59 +01003880 soa.Self()->ClearException();
Elliott Hughesd07986f2011-12-06 18:27:45 -08003881
Sebastien Hertzcbc50642015-06-01 17:33:12 +02003882 // Execute the method then sends reply to the debugger.
3883 ExecuteMethodWithoutPendingException(soa, pReq);
3884
3885 // If an exception was pending before the invoke, restore it now.
3886 if (old_exception.Get() != nullptr) {
3887 soa.Self()->SetException(old_exception.Get());
3888 }
3889}
3890
3891// Helper function: write a variable-width value into the output input buffer.
3892static void WriteValue(JDWP::ExpandBuf* pReply, int width, uint64_t value) {
3893 switch (width) {
3894 case 1:
3895 expandBufAdd1(pReply, value);
3896 break;
3897 case 2:
3898 expandBufAdd2BE(pReply, value);
3899 break;
3900 case 4:
3901 expandBufAdd4BE(pReply, value);
3902 break;
3903 case 8:
3904 expandBufAdd8BE(pReply, value);
3905 break;
3906 default:
3907 LOG(FATAL) << width;
3908 UNREACHABLE();
3909 }
3910}
3911
3912void Dbg::ExecuteMethodWithoutPendingException(ScopedObjectAccess& soa, DebugInvokeReq* pReq) {
3913 soa.Self()->AssertNoPendingException();
3914
Elliott Hughesd07986f2011-12-06 18:27:45 -08003915 // Translate the method through the vtable, unless the debugger wants to suppress it.
Sebastien Hertzcbc50642015-06-01 17:33:12 +02003916 ArtMethod* m = pReq->method;
3917 size_t image_pointer_size = Runtime::Current()->GetClassLinker()->GetImagePointerSize();
Sebastien Hertz1558b572015-02-25 15:05:59 +01003918 if ((pReq->options & JDWP::INVOKE_NONVIRTUAL) == 0 && pReq->receiver.Read() != nullptr) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07003919 ArtMethod* actual_method =
3920 pReq->klass.Read()->FindVirtualMethodForVirtualOrInterface(m, image_pointer_size);
3921 if (actual_method != m) {
3922 VLOG(jdwp) << "ExecuteMethod translated " << PrettyMethod(m)
Sebastien Hertz1558b572015-02-25 15:05:59 +01003923 << " to " << PrettyMethod(actual_method);
Mathieu Chartiere401d142015-04-22 13:56:20 -07003924 m = actual_method;
Elliott Hughes45651fd2012-02-21 15:48:20 -08003925 }
Elliott Hughesd07986f2011-12-06 18:27:45 -08003926 }
Mathieu Chartiere401d142015-04-22 13:56:20 -07003927 VLOG(jdwp) << "ExecuteMethod " << PrettyMethod(m)
Sebastien Hertz1558b572015-02-25 15:05:59 +01003928 << " receiver=" << pReq->receiver.Read()
Sebastien Hertzd38667a2013-11-25 15:43:54 +01003929 << " arg_count=" << pReq->arg_count;
Mathieu Chartiere401d142015-04-22 13:56:20 -07003930 CHECK(m != nullptr);
Elliott Hughesd07986f2011-12-06 18:27:45 -08003931
Roland Levillain33d69032015-06-18 18:20:59 +01003932 static_assert(sizeof(jvalue) == sizeof(uint64_t), "jvalue and uint64_t have different sizes.");
Elliott Hughesd07986f2011-12-06 18:27:45 -08003933
Sebastien Hertzcbc50642015-06-01 17:33:12 +02003934 // Invoke the method.
Jeff Hao39b6c242015-05-19 20:30:23 -07003935 ScopedLocalRef<jobject> ref(soa.Env(), soa.AddLocalReference<jobject>(pReq->receiver.Read()));
Mathieu Chartiere401d142015-04-22 13:56:20 -07003936 JValue result = InvokeWithJValues(soa, ref.get(), soa.EncodeMethod(m),
Sebastien Hertzcbc50642015-06-01 17:33:12 +02003937 reinterpret_cast<jvalue*>(pReq->arg_values.get()));
Elliott Hughesd07986f2011-12-06 18:27:45 -08003938
Sebastien Hertzcbc50642015-06-01 17:33:12 +02003939 // Prepare JDWP ids for the reply.
3940 JDWP::JdwpTag result_tag = BasicTagFromDescriptor(m->GetShorty());
3941 const bool is_object_result = (result_tag == JDWP::JT_OBJECT);
3942 StackHandleScope<2> hs(soa.Self());
Sebastien Hertz1558b572015-02-25 15:05:59 +01003943 Handle<mirror::Object> object_result = hs.NewHandle(is_object_result ? result.GetL() : nullptr);
3944 Handle<mirror::Throwable> exception = hs.NewHandle(soa.Self()->GetException());
3945 soa.Self()->ClearException();
Sebastien Hertzcbc50642015-06-01 17:33:12 +02003946
3947 if (!IsDebuggerActive()) {
3948 // The debugger detached: we must not re-suspend threads. We also don't need to fill the reply
3949 // because it won't be sent either.
3950 return;
3951 }
3952
3953 JDWP::ObjectId exceptionObjectId = gRegistry->Add(exception);
3954 uint64_t result_value = 0;
3955 if (exceptionObjectId != 0) {
Sebastien Hertz1558b572015-02-25 15:05:59 +01003956 VLOG(jdwp) << " JDWP invocation returning with exception=" << exception.Get()
3957 << " " << exception->Dump();
Sebastien Hertzcbc50642015-06-01 17:33:12 +02003958 result_value = 0;
Sebastien Hertz1558b572015-02-25 15:05:59 +01003959 } else if (is_object_result) {
Sebastien Hertzcbc50642015-06-01 17:33:12 +02003960 /* if no exception was thrown, examine object result more closely */
Sebastien Hertz1558b572015-02-25 15:05:59 +01003961 JDWP::JdwpTag new_tag = TagFromObject(soa, object_result.Get());
Sebastien Hertzcbc50642015-06-01 17:33:12 +02003962 if (new_tag != result_tag) {
3963 VLOG(jdwp) << " JDWP promoted result from " << result_tag << " to " << new_tag;
3964 result_tag = new_tag;
Elliott Hughesd07986f2011-12-06 18:27:45 -08003965 }
3966
Sebastien Hertz1558b572015-02-25 15:05:59 +01003967 // Register the object in the registry and reference its ObjectId. This ensures
3968 // GC safety and prevents from accessing stale reference if the object is moved.
Sebastien Hertzcbc50642015-06-01 17:33:12 +02003969 result_value = gRegistry->Add(object_result.Get());
Sebastien Hertz1558b572015-02-25 15:05:59 +01003970 } else {
3971 // Primitive result.
Sebastien Hertzcbc50642015-06-01 17:33:12 +02003972 DCHECK(IsPrimitiveTag(result_tag));
3973 result_value = result.GetJ();
3974 }
3975 const bool is_constructor = m->IsConstructor() && !m->IsStatic();
3976 if (is_constructor) {
3977 // If we invoked a constructor (which actually returns void), return the receiver,
3978 // unless we threw, in which case we return null.
3979 result_tag = JDWP::JT_OBJECT;
3980 if (exceptionObjectId == 0) {
3981 // TODO we could keep the receiver ObjectId in the DebugInvokeReq to avoid looking into the
3982 // object registry.
3983 result_value = GetObjectRegistry()->Add(pReq->receiver.Read());
3984 } else {
3985 result_value = 0;
3986 }
Elliott Hughesd07986f2011-12-06 18:27:45 -08003987 }
3988
Sebastien Hertzcbc50642015-06-01 17:33:12 +02003989 // Suspend other threads if the invoke is not single-threaded.
3990 if ((pReq->options & JDWP::INVOKE_SINGLE_THREADED) == 0) {
3991 soa.Self()->TransitionFromRunnableToSuspended(kWaitingForDebuggerSuspension);
3992 VLOG(jdwp) << " Suspending all threads";
3993 Runtime::Current()->GetThreadList()->SuspendAllForDebugger();
3994 soa.Self()->TransitionFromSuspendedToRunnable();
3995 }
3996
3997 VLOG(jdwp) << " --> returned " << result_tag
3998 << StringPrintf(" %#" PRIx64 " (except=%#" PRIx64 ")", result_value,
3999 exceptionObjectId);
4000
4001 // Show detailed debug output.
4002 if (result_tag == JDWP::JT_STRING && exceptionObjectId == 0) {
4003 if (result_value != 0) {
4004 if (VLOG_IS_ON(jdwp)) {
4005 std::string result_string;
4006 JDWP::JdwpError error = Dbg::StringToUtf8(result_value, &result_string);
4007 CHECK_EQ(error, JDWP::ERR_NONE);
4008 VLOG(jdwp) << " string '" << result_string << "'";
4009 }
4010 } else {
4011 VLOG(jdwp) << " string (null)";
4012 }
4013 }
4014
4015 // Attach the reply to DebugInvokeReq so it can be sent to the debugger when the event thread
4016 // is ready to suspend.
4017 BuildInvokeReply(pReq->reply, pReq->request_id, result_tag, result_value, exceptionObjectId);
4018}
4019
4020void Dbg::BuildInvokeReply(JDWP::ExpandBuf* pReply, uint32_t request_id, JDWP::JdwpTag result_tag,
4021 uint64_t result_value, JDWP::ObjectId exception) {
4022 // Make room for the JDWP header since we do not know the size of the reply yet.
4023 JDWP::expandBufAddSpace(pReply, kJDWPHeaderLen);
4024
4025 size_t width = GetTagWidth(result_tag);
4026 JDWP::expandBufAdd1(pReply, result_tag);
4027 if (width != 0) {
4028 WriteValue(pReply, width, result_value);
4029 }
4030 JDWP::expandBufAdd1(pReply, JDWP::JT_OBJECT);
4031 JDWP::expandBufAddObjectId(pReply, exception);
4032
4033 // Now we know the size, we can complete the JDWP header.
4034 uint8_t* buf = expandBufGetBuffer(pReply);
4035 JDWP::Set4BE(buf + kJDWPHeaderSizeOffset, expandBufGetLength(pReply));
4036 JDWP::Set4BE(buf + kJDWPHeaderIdOffset, request_id);
4037 JDWP::Set1(buf + kJDWPHeaderFlagsOffset, kJDWPFlagReply); // flags
4038 JDWP::Set2BE(buf + kJDWPHeaderErrorCodeOffset, JDWP::ERR_NONE);
4039}
4040
4041void Dbg::FinishInvokeMethod(DebugInvokeReq* pReq) {
4042 CHECK_NE(Thread::Current(), GetDebugThread()) << "This must be called by the event thread";
4043
4044 JDWP::ExpandBuf* const pReply = pReq->reply;
4045 CHECK(pReply != nullptr) << "No reply attached to DebugInvokeReq";
4046
4047 // We need to prevent other threads (including JDWP thread) from interacting with the debugger
4048 // while we send the reply but are not yet suspended. The JDWP token will be released just before
4049 // we suspend ourself again (see ThreadList::SuspendSelfForDebugger).
4050 gJdwpState->AcquireJdwpTokenForEvent(pReq->thread_id);
4051
4052 // Send the reply unless the debugger detached before the completion of the method.
4053 if (IsDebuggerActive()) {
4054 const size_t replyDataLength = expandBufGetLength(pReply) - kJDWPHeaderLen;
4055 VLOG(jdwp) << StringPrintf("REPLY INVOKE id=0x%06x (length=%zu)",
4056 pReq->request_id, replyDataLength);
4057
4058 gJdwpState->SendRequest(pReply);
4059 } else {
4060 VLOG(jdwp) << "Not sending invoke reply because debugger detached";
Elliott Hughesd07986f2011-12-06 18:27:45 -08004061 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -07004062}
4063
Elliott Hughesd07986f2011-12-06 18:27:45 -08004064/*
Elliott Hughes4b9702c2013-02-20 18:13:24 -08004065 * "request" contains a full JDWP packet, possibly with multiple chunks. We
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07004066 * need to process each, accumulate the replies, and ship the whole thing
4067 * back.
4068 *
4069 * Returns "true" if we have a reply. The reply buffer is newly allocated,
4070 * and includes the chunk type/length, followed by the data.
4071 *
Elliott Hughes3d30d9b2011-12-07 17:35:48 -08004072 * OLD-TODO: we currently assume that the request and reply include a single
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07004073 * chunk. If this becomes inconvenient we will need to adapt.
4074 */
Ian Rogersc0542af2014-09-03 16:16:56 -07004075bool Dbg::DdmHandlePacket(JDWP::Request* request, uint8_t** pReplyBuf, int* pReplyLen) {
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07004076 Thread* self = Thread::Current();
4077 JNIEnv* env = self->GetJniEnv();
4078
Ian Rogersc0542af2014-09-03 16:16:56 -07004079 uint32_t type = request->ReadUnsigned32("type");
4080 uint32_t length = request->ReadUnsigned32("length");
Elliott Hughes4b9702c2013-02-20 18:13:24 -08004081
4082 // Create a byte[] corresponding to 'request'.
Ian Rogersc0542af2014-09-03 16:16:56 -07004083 size_t request_length = request->size();
Elliott Hughes4b9702c2013-02-20 18:13:24 -08004084 ScopedLocalRef<jbyteArray> dataArray(env, env->NewByteArray(request_length));
Ian Rogersc0542af2014-09-03 16:16:56 -07004085 if (dataArray.get() == nullptr) {
Elliott Hughes4b9702c2013-02-20 18:13:24 -08004086 LOG(WARNING) << "byte[] allocation failed: " << request_length;
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07004087 env->ExceptionClear();
4088 return false;
4089 }
Ian Rogersc0542af2014-09-03 16:16:56 -07004090 env->SetByteArrayRegion(dataArray.get(), 0, request_length,
4091 reinterpret_cast<const jbyte*>(request->data()));
4092 request->Skip(request_length);
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07004093
4094 // Run through and find all chunks. [Currently just find the first.]
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004095 ScopedByteArrayRO contents(env, dataArray.get());
Elliott Hughes4b9702c2013-02-20 18:13:24 -08004096 if (length != request_length) {
Ian Rogersef7d42f2014-01-06 12:55:46 -08004097 LOG(WARNING) << StringPrintf("bad chunk found (len=%u pktLen=%zd)", length, request_length);
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07004098 return false;
4099 }
4100
4101 // Call "private static Chunk dispatch(int type, byte[] data, int offset, int length)".
Elliott Hugheseac76672012-05-24 21:56:51 -07004102 ScopedLocalRef<jobject> chunk(env, env->CallStaticObjectMethod(WellKnownClasses::org_apache_harmony_dalvik_ddmc_DdmServer,
4103 WellKnownClasses::org_apache_harmony_dalvik_ddmc_DdmServer_dispatch,
Elliott Hughes4b9702c2013-02-20 18:13:24 -08004104 type, dataArray.get(), 0, length));
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07004105 if (env->ExceptionCheck()) {
4106 LOG(INFO) << StringPrintf("Exception thrown by dispatcher for 0x%08x", type);
4107 env->ExceptionDescribe();
4108 env->ExceptionClear();
4109 return false;
4110 }
4111
Ian Rogersc0542af2014-09-03 16:16:56 -07004112 if (chunk.get() == nullptr) {
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07004113 return false;
4114 }
4115
4116 /*
4117 * Pull the pieces out of the chunk. We copy the results into a
4118 * newly-allocated buffer that the caller can free. We don't want to
4119 * continue using the Chunk object because nothing has a reference to it.
4120 *
4121 * We could avoid this by returning type/data/offset/length and having
4122 * the caller be aware of the object lifetime issues, but that
Elliott Hughes81ff3182012-03-23 20:35:56 -07004123 * integrates the JDWP code more tightly into the rest of the runtime, and doesn't work
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07004124 * if we have responses for multiple chunks.
4125 *
4126 * So we're pretty much stuck with copying data around multiple times.
4127 */
Elliott Hugheseac76672012-05-24 21:56:51 -07004128 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 -08004129 jint offset = env->GetIntField(chunk.get(), WellKnownClasses::org_apache_harmony_dalvik_ddmc_Chunk_offset);
Elliott Hugheseac76672012-05-24 21:56:51 -07004130 length = env->GetIntField(chunk.get(), WellKnownClasses::org_apache_harmony_dalvik_ddmc_Chunk_length);
Elliott Hugheseac76672012-05-24 21:56:51 -07004131 type = env->GetIntField(chunk.get(), WellKnownClasses::org_apache_harmony_dalvik_ddmc_Chunk_type);
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07004132
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08004133 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 -07004134 if (length == 0 || replyData.get() == nullptr) {
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07004135 return false;
4136 }
4137
Elliott Hughes4b9702c2013-02-20 18:13:24 -08004138 const int kChunkHdrLen = 8;
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07004139 uint8_t* reply = new uint8_t[length + kChunkHdrLen];
Ian Rogersc0542af2014-09-03 16:16:56 -07004140 if (reply == nullptr) {
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07004141 LOG(WARNING) << "malloc failed: " << (length + kChunkHdrLen);
4142 return false;
4143 }
Elliott Hughesf7c3b662011-10-27 12:04:56 -07004144 JDWP::Set4BE(reply + 0, type);
4145 JDWP::Set4BE(reply + 4, length);
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004146 env->GetByteArrayRegion(replyData.get(), offset, length, reinterpret_cast<jbyte*>(reply + kChunkHdrLen));
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07004147
4148 *pReplyBuf = reply;
4149 *pReplyLen = length + kChunkHdrLen;
4150
Elliott Hughes4b9702c2013-02-20 18:13:24 -08004151 VLOG(jdwp) << StringPrintf("dvmHandleDdm returning type=%.4s %p len=%d", reinterpret_cast<char*>(reply), reply, length);
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07004152 return true;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07004153}
4154
Elliott Hughesa2155262011-11-16 16:26:58 -08004155void Dbg::DdmBroadcast(bool connect) {
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08004156 VLOG(jdwp) << "Broadcasting DDM " << (connect ? "connect" : "disconnect") << "...";
Elliott Hughes47fce012011-10-25 18:37:19 -07004157
4158 Thread* self = Thread::Current();
Ian Rogers50b35e22012-10-04 10:09:15 -07004159 if (self->GetState() != kRunnable) {
4160 LOG(ERROR) << "DDM broadcast in thread state " << self->GetState();
4161 /* try anyway? */
Elliott Hughes47fce012011-10-25 18:37:19 -07004162 }
4163
4164 JNIEnv* env = self->GetJniEnv();
Elliott Hughes47fce012011-10-25 18:37:19 -07004165 jint event = connect ? 1 /*DdmServer.CONNECTED*/ : 2 /*DdmServer.DISCONNECTED*/;
Elliott Hugheseac76672012-05-24 21:56:51 -07004166 env->CallStaticVoidMethod(WellKnownClasses::org_apache_harmony_dalvik_ddmc_DdmServer,
4167 WellKnownClasses::org_apache_harmony_dalvik_ddmc_DdmServer_broadcast,
4168 event);
Elliott Hughes47fce012011-10-25 18:37:19 -07004169 if (env->ExceptionCheck()) {
4170 LOG(ERROR) << "DdmServer.broadcast " << event << " failed";
4171 env->ExceptionDescribe();
4172 env->ExceptionClear();
4173 }
4174}
4175
Elliott Hughes872d4ec2011-10-21 17:07:15 -07004176void Dbg::DdmConnected() {
Elliott Hughesa2155262011-11-16 16:26:58 -08004177 Dbg::DdmBroadcast(true);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07004178}
4179
4180void Dbg::DdmDisconnected() {
Elliott Hughesa2155262011-11-16 16:26:58 -08004181 Dbg::DdmBroadcast(false);
Elliott Hughes47fce012011-10-25 18:37:19 -07004182 gDdmThreadNotification = false;
4183}
4184
4185/*
Elliott Hughes82188472011-11-07 18:11:48 -08004186 * Send a notification when a thread starts, stops, or changes its name.
Elliott Hughes47fce012011-10-25 18:37:19 -07004187 *
4188 * Because we broadcast the full set of threads when the notifications are
4189 * first enabled, it's possible for "thread" to be actively executing.
4190 */
Elliott Hughes82188472011-11-07 18:11:48 -08004191void Dbg::DdmSendThreadNotification(Thread* t, uint32_t type) {
Elliott Hughes47fce012011-10-25 18:37:19 -07004192 if (!gDdmThreadNotification) {
4193 return;
4194 }
4195
Elliott Hughes82188472011-11-07 18:11:48 -08004196 if (type == CHUNK_TYPE("THDE")) {
Elliott Hughes47fce012011-10-25 18:37:19 -07004197 uint8_t buf[4];
Ian Rogersd9c4fc92013-10-01 19:45:43 -07004198 JDWP::Set4BE(&buf[0], t->GetThreadId());
Elliott Hughes47fce012011-10-25 18:37:19 -07004199 Dbg::DdmSendChunk(CHUNK_TYPE("THDE"), 4, buf);
Elliott Hughes82188472011-11-07 18:11:48 -08004200 } else {
4201 CHECK(type == CHUNK_TYPE("THCR") || type == CHUNK_TYPE("THNM")) << type;
Ian Rogers00f7d0e2012-07-19 15:28:27 -07004202 ScopedObjectAccessUnchecked soa(Thread::Current());
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004203 StackHandleScope<1> hs(soa.Self());
4204 Handle<mirror::String> name(hs.NewHandle(t->GetThreadName(soa)));
Ian Rogersc0542af2014-09-03 16:16:56 -07004205 size_t char_count = (name.Get() != nullptr) ? name->GetLength() : 0;
Jeff Hao848f70a2014-01-15 13:49:50 -08004206 const jchar* chars = (name.Get() != nullptr) ? name->GetValue() : nullptr;
Elliott Hughes82188472011-11-07 18:11:48 -08004207
Elliott Hughes21f32d72011-11-09 17:44:13 -08004208 std::vector<uint8_t> bytes;
Ian Rogersd9c4fc92013-10-01 19:45:43 -07004209 JDWP::Append4BE(bytes, t->GetThreadId());
Elliott Hughes545a0642011-11-08 19:10:03 -08004210 JDWP::AppendUtf16BE(bytes, chars, char_count);
Elliott Hughes21f32d72011-11-09 17:44:13 -08004211 CHECK_EQ(bytes.size(), char_count*2 + sizeof(uint32_t)*2);
4212 Dbg::DdmSendChunk(type, bytes);
Elliott Hughes47fce012011-10-25 18:37:19 -07004213 }
4214}
4215
Elliott Hughes47fce012011-10-25 18:37:19 -07004216void Dbg::DdmSetThreadNotification(bool enable) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07004217 // Enable/disable thread notifications.
Elliott Hughes47fce012011-10-25 18:37:19 -07004218 gDdmThreadNotification = enable;
4219 if (enable) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07004220 // Suspend the VM then post thread start notifications for all threads. Threads attaching will
4221 // see a suspension in progress and block until that ends. They then post their own start
4222 // notification.
4223 SuspendVM();
4224 std::list<Thread*> threads;
Ian Rogers50b35e22012-10-04 10:09:15 -07004225 Thread* self = Thread::Current();
Ian Rogers00f7d0e2012-07-19 15:28:27 -07004226 {
Ian Rogers50b35e22012-10-04 10:09:15 -07004227 MutexLock mu(self, *Locks::thread_list_lock_);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07004228 threads = Runtime::Current()->GetThreadList()->GetList();
4229 }
4230 {
Ian Rogers50b35e22012-10-04 10:09:15 -07004231 ScopedObjectAccess soa(self);
Mathieu Chartier02e25112013-08-14 16:14:24 -07004232 for (Thread* thread : threads) {
4233 Dbg::DdmSendThreadNotification(thread, CHUNK_TYPE("THCR"));
Ian Rogers00f7d0e2012-07-19 15:28:27 -07004234 }
4235 }
4236 ResumeVM();
Elliott Hughes47fce012011-10-25 18:37:19 -07004237 }
4238}
4239
Elliott Hughesa2155262011-11-16 16:26:58 -08004240void Dbg::PostThreadStartOrStop(Thread* t, uint32_t type) {
Elliott Hughesc0f09332012-03-26 13:27:06 -07004241 if (IsDebuggerActive()) {
Sebastien Hertz6995c602014-09-09 12:10:13 +02004242 gJdwpState->PostThreadChange(t, type == CHUNK_TYPE("THCR"));
Elliott Hughes47fce012011-10-25 18:37:19 -07004243 }
Elliott Hughes82188472011-11-07 18:11:48 -08004244 Dbg::DdmSendThreadNotification(t, type);
Elliott Hughes47fce012011-10-25 18:37:19 -07004245}
4246
4247void Dbg::PostThreadStart(Thread* t) {
Elliott Hughesa2155262011-11-16 16:26:58 -08004248 Dbg::PostThreadStartOrStop(t, CHUNK_TYPE("THCR"));
Elliott Hughes47fce012011-10-25 18:37:19 -07004249}
4250
4251void Dbg::PostThreadDeath(Thread* t) {
Elliott Hughesa2155262011-11-16 16:26:58 -08004252 Dbg::PostThreadStartOrStop(t, CHUNK_TYPE("THDE"));
Elliott Hughes872d4ec2011-10-21 17:07:15 -07004253}
4254
Elliott Hughes82188472011-11-07 18:11:48 -08004255void Dbg::DdmSendChunk(uint32_t type, size_t byte_count, const uint8_t* buf) {
Ian Rogersc0542af2014-09-03 16:16:56 -07004256 CHECK(buf != nullptr);
Elliott Hughes3bb81562011-10-21 18:52:59 -07004257 iovec vec[1];
4258 vec[0].iov_base = reinterpret_cast<void*>(const_cast<uint8_t*>(buf));
4259 vec[0].iov_len = byte_count;
4260 Dbg::DdmSendChunkV(type, vec, 1);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07004261}
4262
Elliott Hughes21f32d72011-11-09 17:44:13 -08004263void Dbg::DdmSendChunk(uint32_t type, const std::vector<uint8_t>& bytes) {
4264 DdmSendChunk(type, bytes.size(), &bytes[0]);
4265}
4266
Brian Carlstromf5293522013-07-19 00:24:00 -07004267void Dbg::DdmSendChunkV(uint32_t type, const iovec* iov, int iov_count) {
Ian Rogersc0542af2014-09-03 16:16:56 -07004268 if (gJdwpState == nullptr) {
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08004269 VLOG(jdwp) << "Debugger thread not active, ignoring DDM send: " << type;
Elliott Hughes3bb81562011-10-21 18:52:59 -07004270 } else {
Elliott Hughescccd84f2011-12-05 16:51:54 -08004271 gJdwpState->DdmSendChunkV(type, iov, iov_count);
Elliott Hughes3bb81562011-10-21 18:52:59 -07004272 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -07004273}
4274
Mathieu Chartierad466ad2015-01-08 16:28:08 -08004275JDWP::JdwpState* Dbg::GetJdwpState() {
4276 return gJdwpState;
4277}
4278
Elliott Hughes767a1472011-10-26 18:49:02 -07004279int Dbg::DdmHandleHpifChunk(HpifWhen when) {
4280 if (when == HPIF_WHEN_NOW) {
Elliott Hughes7162ad92011-10-27 14:08:42 -07004281 DdmSendHeapInfo(when);
Elliott Hughes767a1472011-10-26 18:49:02 -07004282 return true;
4283 }
4284
4285 if (when != HPIF_WHEN_NEVER && when != HPIF_WHEN_NEXT_GC && when != HPIF_WHEN_EVERY_GC) {
4286 LOG(ERROR) << "invalid HpifWhen value: " << static_cast<int>(when);
4287 return false;
4288 }
4289
4290 gDdmHpifWhen = when;
4291 return true;
4292}
4293
4294bool Dbg::DdmHandleHpsgNhsgChunk(Dbg::HpsgWhen when, Dbg::HpsgWhat what, bool native) {
4295 if (when != HPSG_WHEN_NEVER && when != HPSG_WHEN_EVERY_GC) {
4296 LOG(ERROR) << "invalid HpsgWhen value: " << static_cast<int>(when);
4297 return false;
4298 }
4299
4300 if (what != HPSG_WHAT_MERGED_OBJECTS && what != HPSG_WHAT_DISTINCT_OBJECTS) {
4301 LOG(ERROR) << "invalid HpsgWhat value: " << static_cast<int>(what);
4302 return false;
4303 }
4304
4305 if (native) {
4306 gDdmNhsgWhen = when;
4307 gDdmNhsgWhat = what;
4308 } else {
4309 gDdmHpsgWhen = when;
4310 gDdmHpsgWhat = what;
4311 }
4312 return true;
4313}
4314
Elliott Hughes7162ad92011-10-27 14:08:42 -07004315void Dbg::DdmSendHeapInfo(HpifWhen reason) {
4316 // If there's a one-shot 'when', reset it.
4317 if (reason == gDdmHpifWhen) {
4318 if (gDdmHpifWhen == HPIF_WHEN_NEXT_GC) {
4319 gDdmHpifWhen = HPIF_WHEN_NEVER;
4320 }
4321 }
4322
4323 /*
4324 * Chunk HPIF (client --> server)
4325 *
4326 * Heap Info. General information about the heap,
4327 * suitable for a summary display.
4328 *
4329 * [u4]: number of heaps
4330 *
4331 * For each heap:
4332 * [u4]: heap ID
4333 * [u8]: timestamp in ms since Unix epoch
4334 * [u1]: capture reason (same as 'when' value from server)
4335 * [u4]: max heap size in bytes (-Xmx)
4336 * [u4]: current heap size in bytes
4337 * [u4]: current number of bytes allocated
4338 * [u4]: current number of objects allocated
4339 */
4340 uint8_t heap_count = 1;
Ian Rogers1d54e732013-05-02 21:10:01 -07004341 gc::Heap* heap = Runtime::Current()->GetHeap();
Elliott Hughes21f32d72011-11-09 17:44:13 -08004342 std::vector<uint8_t> bytes;
Elliott Hughes545a0642011-11-08 19:10:03 -08004343 JDWP::Append4BE(bytes, heap_count);
Brian Carlstrom7934ac22013-07-26 10:54:15 -07004344 JDWP::Append4BE(bytes, 1); // Heap id (bogus; we only have one heap).
Elliott Hughes545a0642011-11-08 19:10:03 -08004345 JDWP::Append8BE(bytes, MilliTime());
4346 JDWP::Append1BE(bytes, reason);
Brian Carlstrom7934ac22013-07-26 10:54:15 -07004347 JDWP::Append4BE(bytes, heap->GetMaxMemory()); // Max allowed heap size in bytes.
4348 JDWP::Append4BE(bytes, heap->GetTotalMemory()); // Current heap size in bytes.
Elliott Hughesb3bd5f02012-03-08 21:05:27 -08004349 JDWP::Append4BE(bytes, heap->GetBytesAllocated());
4350 JDWP::Append4BE(bytes, heap->GetObjectsAllocated());
Elliott Hughes21f32d72011-11-09 17:44:13 -08004351 CHECK_EQ(bytes.size(), 4U + (heap_count * (4 + 8 + 1 + 4 + 4 + 4 + 4)));
4352 Dbg::DdmSendChunk(CHUNK_TYPE("HPIF"), bytes);
Elliott Hughes767a1472011-10-26 18:49:02 -07004353}
4354
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004355enum HpsgSolidity {
4356 SOLIDITY_FREE = 0,
4357 SOLIDITY_HARD = 1,
4358 SOLIDITY_SOFT = 2,
4359 SOLIDITY_WEAK = 3,
4360 SOLIDITY_PHANTOM = 4,
4361 SOLIDITY_FINALIZABLE = 5,
4362 SOLIDITY_SWEEP = 6,
4363};
4364
4365enum HpsgKind {
4366 KIND_OBJECT = 0,
4367 KIND_CLASS_OBJECT = 1,
4368 KIND_ARRAY_1 = 2,
4369 KIND_ARRAY_2 = 3,
4370 KIND_ARRAY_4 = 4,
4371 KIND_ARRAY_8 = 5,
4372 KIND_UNKNOWN = 6,
4373 KIND_NATIVE = 7,
4374};
4375
4376#define HPSG_PARTIAL (1<<7)
4377#define HPSG_STATE(solidity, kind) ((uint8_t)((((kind) & 0x7) << 3) | ((solidity) & 0x7)))
4378
Ian Rogers30fab402012-01-23 15:43:46 -08004379class HeapChunkContext {
4380 public:
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004381 // Maximum chunk size. Obtain this from the formula:
4382 // (((maximum_heap_size / ALLOCATION_UNIT_SIZE) + 255) / 256) * 2
4383 HeapChunkContext(bool merge, bool native)
Ian Rogers30fab402012-01-23 15:43:46 -08004384 : buf_(16384 - 16),
4385 type_(0),
Mathieu Chartier36dab362014-07-30 14:59:56 -07004386 chunk_overhead_(0) {
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004387 Reset();
4388 if (native) {
Ian Rogers30fab402012-01-23 15:43:46 -08004389 type_ = CHUNK_TYPE("NHSG");
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004390 } else {
Ian Rogers30fab402012-01-23 15:43:46 -08004391 type_ = merge ? CHUNK_TYPE("HPSG") : CHUNK_TYPE("HPSO");
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004392 }
4393 }
4394
4395 ~HeapChunkContext() {
Ian Rogers30fab402012-01-23 15:43:46 -08004396 if (p_ > &buf_[0]) {
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004397 Flush();
4398 }
4399 }
4400
Mathieu Chartier36dab362014-07-30 14:59:56 -07004401 void SetChunkOverhead(size_t chunk_overhead) {
4402 chunk_overhead_ = chunk_overhead;
4403 }
4404
4405 void ResetStartOfNextChunk() {
4406 startOfNextMemoryChunk_ = nullptr;
4407 }
4408
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004409 void EnsureHeader(const void* chunk_ptr) {
Ian Rogers30fab402012-01-23 15:43:46 -08004410 if (!needHeader_) {
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004411 return;
4412 }
4413
4414 // Start a new HPSx chunk.
Brian Carlstrom7934ac22013-07-26 10:54:15 -07004415 JDWP::Write4BE(&p_, 1); // Heap id (bogus; we only have one heap).
4416 JDWP::Write1BE(&p_, 8); // Size of allocation unit, in bytes.
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004417
Brian Carlstrom7934ac22013-07-26 10:54:15 -07004418 JDWP::Write4BE(&p_, reinterpret_cast<uintptr_t>(chunk_ptr)); // virtual address of segment start.
4419 JDWP::Write4BE(&p_, 0); // offset of this piece (relative to the virtual address).
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004420 // [u4]: length of piece, in allocation units
4421 // 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 -08004422 pieceLenField_ = p_;
4423 JDWP::Write4BE(&p_, 0x55555555);
4424 needHeader_ = false;
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004425 }
4426
Mathieu Chartier90443472015-07-16 20:32:27 -07004427 void Flush() SHARED_REQUIRES(Locks::mutator_lock_) {
Ian Rogersc0542af2014-09-03 16:16:56 -07004428 if (pieceLenField_ == nullptr) {
Ian Rogersd636b062013-01-18 17:51:18 -08004429 // Flush immediately post Reset (maybe back-to-back Flush). Ignore.
4430 CHECK(needHeader_);
4431 return;
4432 }
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004433 // Patch the "length of piece" field.
Ian Rogers30fab402012-01-23 15:43:46 -08004434 CHECK_LE(&buf_[0], pieceLenField_);
4435 CHECK_LE(pieceLenField_, p_);
4436 JDWP::Set4BE(pieceLenField_, totalAllocationUnits_);
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004437
Ian Rogers30fab402012-01-23 15:43:46 -08004438 Dbg::DdmSendChunk(type_, p_ - &buf_[0], &buf_[0]);
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004439 Reset();
4440 }
4441
Mathieu Chartierbc689b72014-12-14 17:01:31 -08004442 static void HeapChunkJavaCallback(void* start, void* end, size_t used_bytes, void* arg)
Mathieu Chartier90443472015-07-16 20:32:27 -07004443 SHARED_REQUIRES(Locks::heap_bitmap_lock_,
Ian Rogersb726dcb2012-09-05 08:57:23 -07004444 Locks::mutator_lock_) {
Mathieu Chartierbc689b72014-12-14 17:01:31 -08004445 reinterpret_cast<HeapChunkContext*>(arg)->HeapChunkJavaCallback(start, end, used_bytes);
4446 }
4447
4448 static void HeapChunkNativeCallback(void* start, void* end, size_t used_bytes, void* arg)
Mathieu Chartier90443472015-07-16 20:32:27 -07004449 SHARED_REQUIRES(Locks::mutator_lock_) {
Mathieu Chartierbc689b72014-12-14 17:01:31 -08004450 reinterpret_cast<HeapChunkContext*>(arg)->HeapChunkNativeCallback(start, end, used_bytes);
Elliott Hughesa2155262011-11-16 16:26:58 -08004451 }
4452
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004453 private:
Elliott Hughesa2155262011-11-16 16:26:58 -08004454 enum { ALLOCATION_UNIT_SIZE = 8 };
4455
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004456 void Reset() {
Ian Rogers30fab402012-01-23 15:43:46 -08004457 p_ = &buf_[0];
Mathieu Chartier36dab362014-07-30 14:59:56 -07004458 ResetStartOfNextChunk();
Ian Rogers30fab402012-01-23 15:43:46 -08004459 totalAllocationUnits_ = 0;
4460 needHeader_ = true;
Ian Rogersc0542af2014-09-03 16:16:56 -07004461 pieceLenField_ = nullptr;
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004462 }
4463
Mathieu Chartierbc689b72014-12-14 17:01:31 -08004464 bool IsNative() const {
4465 return type_ == CHUNK_TYPE("NHSG");
4466 }
4467
4468 // Returns true if the object is not an empty chunk.
Mathieu Chartier90443472015-07-16 20:32:27 -07004469 bool ProcessRecord(void* start, size_t used_bytes) SHARED_REQUIRES(Locks::mutator_lock_) {
Ian Rogers30fab402012-01-23 15:43:46 -08004470 // Note: heap call backs cannot manipulate the heap upon which they are crawling, care is taken
4471 // in the following code not to allocate memory, by ensuring buf_ is of the correct size
Ian Rogers15bf2d32012-08-28 17:33:04 -07004472 if (used_bytes == 0) {
Mathieu Chartierbc689b72014-12-14 17:01:31 -08004473 if (start == nullptr) {
4474 // Reset for start of new heap.
4475 startOfNextMemoryChunk_ = nullptr;
4476 Flush();
4477 }
4478 // Only process in use memory so that free region information
4479 // also includes dlmalloc book keeping.
4480 return false;
Elliott Hughesa2155262011-11-16 16:26:58 -08004481 }
Ian Rogersc0542af2014-09-03 16:16:56 -07004482 if (startOfNextMemoryChunk_ != nullptr) {
Mathieu Chartierbc689b72014-12-14 17:01:31 -08004483 // Transmit any pending free memory. Native free memory of over kMaxFreeLen could be because
4484 // of the use of mmaps, so don't report. If not free memory then start a new segment.
4485 bool flush = true;
4486 if (start > startOfNextMemoryChunk_) {
4487 const size_t kMaxFreeLen = 2 * kPageSize;
4488 void* free_start = startOfNextMemoryChunk_;
4489 void* free_end = start;
4490 const size_t free_len =
4491 reinterpret_cast<uintptr_t>(free_end) - reinterpret_cast<uintptr_t>(free_start);
4492 if (!IsNative() || free_len < kMaxFreeLen) {
4493 AppendChunk(HPSG_STATE(SOLIDITY_FREE, 0), free_start, free_len, IsNative());
4494 flush = false;
Ian Rogers15bf2d32012-08-28 17:33:04 -07004495 }
Mathieu Chartierbc689b72014-12-14 17:01:31 -08004496 }
4497 if (flush) {
4498 startOfNextMemoryChunk_ = nullptr;
4499 Flush();
4500 }
Ian Rogers15bf2d32012-08-28 17:33:04 -07004501 }
Mathieu Chartierbc689b72014-12-14 17:01:31 -08004502 return true;
Ian Rogers15bf2d32012-08-28 17:33:04 -07004503 }
Elliott Hughesa2155262011-11-16 16:26:58 -08004504
Mathieu Chartierbc689b72014-12-14 17:01:31 -08004505 void HeapChunkNativeCallback(void* start, void* /*end*/, size_t used_bytes)
Mathieu Chartier90443472015-07-16 20:32:27 -07004506 SHARED_REQUIRES(Locks::mutator_lock_) {
Mathieu Chartierbc689b72014-12-14 17:01:31 -08004507 if (ProcessRecord(start, used_bytes)) {
4508 uint8_t state = ExamineNativeObject(start);
4509 AppendChunk(state, start, used_bytes + chunk_overhead_, true /*is_native*/);
4510 startOfNextMemoryChunk_ = reinterpret_cast<char*>(start) + used_bytes + chunk_overhead_;
4511 }
4512 }
4513
4514 void HeapChunkJavaCallback(void* start, void* /*end*/, size_t used_bytes)
Mathieu Chartier90443472015-07-16 20:32:27 -07004515 SHARED_REQUIRES(Locks::heap_bitmap_lock_, Locks::mutator_lock_) {
Mathieu Chartierbc689b72014-12-14 17:01:31 -08004516 if (ProcessRecord(start, used_bytes)) {
4517 // Determine the type of this chunk.
4518 // OLD-TODO: if context.merge, see if this chunk is different from the last chunk.
4519 // If it's the same, we should combine them.
4520 uint8_t state = ExamineJavaObject(reinterpret_cast<mirror::Object*>(start));
4521 AppendChunk(state, start, used_bytes + chunk_overhead_, false /*is_native*/);
4522 startOfNextMemoryChunk_ = reinterpret_cast<char*>(start) + used_bytes + chunk_overhead_;
4523 }
4524 }
4525
4526 void AppendChunk(uint8_t state, void* ptr, size_t length, bool is_native)
Mathieu Chartier90443472015-07-16 20:32:27 -07004527 SHARED_REQUIRES(Locks::mutator_lock_) {
Ian Rogers15bf2d32012-08-28 17:33:04 -07004528 // Make sure there's enough room left in the buffer.
4529 // We need to use two bytes for every fractional 256 allocation units used by the chunk plus
4530 // 17 bytes for any header.
Mathieu Chartierbc689b72014-12-14 17:01:31 -08004531 const size_t needed = ((RoundUp(length / ALLOCATION_UNIT_SIZE, 256) / 256) * 2) + 17;
4532 size_t byte_left = &buf_.back() - p_;
4533 if (byte_left < needed) {
4534 if (is_native) {
Pavel Vyssotski7522c742014-12-08 13:38:26 +06004535 // Cannot trigger memory allocation while walking native heap.
Pavel Vyssotski7522c742014-12-08 13:38:26 +06004536 return;
4537 }
Ian Rogers15bf2d32012-08-28 17:33:04 -07004538 Flush();
4539 }
4540
Mathieu Chartierbc689b72014-12-14 17:01:31 -08004541 byte_left = &buf_.back() - p_;
4542 if (byte_left < needed) {
Ian Rogers15bf2d32012-08-28 17:33:04 -07004543 LOG(WARNING) << "Chunk is too big to transmit (chunk_len=" << length << ", "
4544 << needed << " bytes)";
4545 return;
4546 }
4547 EnsureHeader(ptr);
Elliott Hughesa2155262011-11-16 16:26:58 -08004548 // Write out the chunk description.
Ian Rogers15bf2d32012-08-28 17:33:04 -07004549 length /= ALLOCATION_UNIT_SIZE; // Convert to allocation units.
4550 totalAllocationUnits_ += length;
4551 while (length > 256) {
Ian Rogers30fab402012-01-23 15:43:46 -08004552 *p_++ = state | HPSG_PARTIAL;
4553 *p_++ = 255; // length - 1
Ian Rogers15bf2d32012-08-28 17:33:04 -07004554 length -= 256;
Elliott Hughesa2155262011-11-16 16:26:58 -08004555 }
Ian Rogers30fab402012-01-23 15:43:46 -08004556 *p_++ = state;
Ian Rogers15bf2d32012-08-28 17:33:04 -07004557 *p_++ = length - 1;
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004558 }
4559
Mathieu Chartier90443472015-07-16 20:32:27 -07004560 uint8_t ExamineNativeObject(const void* p) SHARED_REQUIRES(Locks::mutator_lock_) {
Mathieu Chartierbc689b72014-12-14 17:01:31 -08004561 return p == nullptr ? HPSG_STATE(SOLIDITY_FREE, 0) : HPSG_STATE(SOLIDITY_HARD, KIND_NATIVE);
4562 }
4563
4564 uint8_t ExamineJavaObject(mirror::Object* o)
Mathieu Chartier90443472015-07-16 20:32:27 -07004565 SHARED_REQUIRES(Locks::mutator_lock_, Locks::heap_bitmap_lock_) {
Ian Rogersc0542af2014-09-03 16:16:56 -07004566 if (o == nullptr) {
Elliott Hughesa2155262011-11-16 16:26:58 -08004567 return HPSG_STATE(SOLIDITY_FREE, 0);
4568 }
Elliott Hughesa2155262011-11-16 16:26:58 -08004569 // It's an allocated chunk. Figure out what it is.
Mathieu Chartierbc689b72014-12-14 17:01:31 -08004570 gc::Heap* heap = Runtime::Current()->GetHeap();
4571 if (!heap->IsLiveObjectLocked(o)) {
4572 LOG(ERROR) << "Invalid object in managed heap: " << o;
Elliott Hughesa2155262011-11-16 16:26:58 -08004573 return HPSG_STATE(SOLIDITY_HARD, KIND_NATIVE);
4574 }
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08004575 mirror::Class* c = o->GetClass();
Ian Rogersc0542af2014-09-03 16:16:56 -07004576 if (c == nullptr) {
Elliott Hughesa2155262011-11-16 16:26:58 -08004577 // The object was probably just created but hasn't been initialized yet.
4578 return HPSG_STATE(SOLIDITY_HARD, KIND_OBJECT);
4579 }
Mathieu Chartierbc689b72014-12-14 17:01:31 -08004580 if (!heap->IsValidObjectAddress(c)) {
Ian Rogers15bf2d32012-08-28 17:33:04 -07004581 LOG(ERROR) << "Invalid class for managed heap object: " << o << " " << c;
Elliott Hughesa2155262011-11-16 16:26:58 -08004582 return HPSG_STATE(SOLIDITY_HARD, KIND_UNKNOWN);
4583 }
Mathieu Chartierf26e1b32015-01-29 10:47:10 -08004584 if (c->GetClass() == nullptr) {
4585 LOG(ERROR) << "Null class of class " << c << " for object " << o;
4586 return HPSG_STATE(SOLIDITY_HARD, KIND_UNKNOWN);
4587 }
Elliott Hughesa2155262011-11-16 16:26:58 -08004588 if (c->IsClassClass()) {
4589 return HPSG_STATE(SOLIDITY_HARD, KIND_CLASS_OBJECT);
4590 }
Elliott Hughesa2155262011-11-16 16:26:58 -08004591 if (c->IsArrayClass()) {
Elliott Hughesa2155262011-11-16 16:26:58 -08004592 switch (c->GetComponentSize()) {
4593 case 1: return HPSG_STATE(SOLIDITY_HARD, KIND_ARRAY_1);
4594 case 2: return HPSG_STATE(SOLIDITY_HARD, KIND_ARRAY_2);
4595 case 4: return HPSG_STATE(SOLIDITY_HARD, KIND_ARRAY_4);
4596 case 8: return HPSG_STATE(SOLIDITY_HARD, KIND_ARRAY_8);
4597 }
4598 }
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004599 return HPSG_STATE(SOLIDITY_HARD, KIND_OBJECT);
4600 }
4601
Ian Rogers30fab402012-01-23 15:43:46 -08004602 std::vector<uint8_t> buf_;
4603 uint8_t* p_;
4604 uint8_t* pieceLenField_;
Ian Rogers15bf2d32012-08-28 17:33:04 -07004605 void* startOfNextMemoryChunk_;
Ian Rogers30fab402012-01-23 15:43:46 -08004606 size_t totalAllocationUnits_;
4607 uint32_t type_;
Ian Rogers30fab402012-01-23 15:43:46 -08004608 bool needHeader_;
Mathieu Chartier36dab362014-07-30 14:59:56 -07004609 size_t chunk_overhead_;
Ian Rogers30fab402012-01-23 15:43:46 -08004610
Elliott Hughesa2155262011-11-16 16:26:58 -08004611 DISALLOW_COPY_AND_ASSIGN(HeapChunkContext);
4612};
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004613
Mathieu Chartier36dab362014-07-30 14:59:56 -07004614static void BumpPointerSpaceCallback(mirror::Object* obj, void* arg)
Mathieu Chartier90443472015-07-16 20:32:27 -07004615 SHARED_REQUIRES(Locks::mutator_lock_) REQUIRES(Locks::heap_bitmap_lock_) {
Mathieu Chartier36dab362014-07-30 14:59:56 -07004616 const size_t size = RoundUp(obj->SizeOf(), kObjectAlignment);
Mathieu Chartierbc689b72014-12-14 17:01:31 -08004617 HeapChunkContext::HeapChunkJavaCallback(
Mathieu Chartier36dab362014-07-30 14:59:56 -07004618 obj, reinterpret_cast<void*>(reinterpret_cast<uintptr_t>(obj) + size), size, arg);
4619}
4620
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004621void Dbg::DdmSendHeapSegments(bool native) {
Mathieu Chartierbc689b72014-12-14 17:01:31 -08004622 Dbg::HpsgWhen when = native ? gDdmNhsgWhen : gDdmHpsgWhen;
4623 Dbg::HpsgWhat what = native ? gDdmNhsgWhat : gDdmHpsgWhat;
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004624 if (when == HPSG_WHEN_NEVER) {
4625 return;
4626 }
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004627 // Figure out what kind of chunks we'll be sending.
Mathieu Chartierbc689b72014-12-14 17:01:31 -08004628 CHECK(what == HPSG_WHAT_MERGED_OBJECTS || what == HPSG_WHAT_DISTINCT_OBJECTS)
4629 << static_cast<int>(what);
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004630
4631 // First, send a heap start chunk.
4632 uint8_t heap_id[4];
Brian Carlstrom7934ac22013-07-26 10:54:15 -07004633 JDWP::Set4BE(&heap_id[0], 1); // Heap id (bogus; we only have one heap).
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004634 Dbg::DdmSendChunk(native ? CHUNK_TYPE("NHST") : CHUNK_TYPE("HPST"), sizeof(heap_id), heap_id);
Hiroshi Yamauchicf58d4a2013-09-26 14:21:22 -07004635 Thread* self = Thread::Current();
Hiroshi Yamauchicf58d4a2013-09-26 14:21:22 -07004636 Locks::mutator_lock_->AssertSharedHeld(self);
Hiroshi Yamauchicf58d4a2013-09-26 14:21:22 -07004637
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004638 // Send a series of heap segment chunks.
Mathieu Chartierbc689b72014-12-14 17:01:31 -08004639 HeapChunkContext context(what == HPSG_WHAT_MERGED_OBJECTS, native);
Elliott Hughesa2155262011-11-16 16:26:58 -08004640 if (native) {
Andreas Gampec60e1b72015-07-30 08:57:50 -07004641#if defined(__ANDROID__) && defined(USE_DLMALLOC)
Mathieu Chartierbc689b72014-12-14 17:01:31 -08004642 dlmalloc_inspect_all(HeapChunkContext::HeapChunkNativeCallback, &context);
4643 HeapChunkContext::HeapChunkNativeCallback(nullptr, nullptr, 0, &context); // Indicate end of a space.
Christopher Ferrisc4ddc042014-05-13 14:47:50 -07004644#else
4645 UNIMPLEMENTED(WARNING) << "Native heap inspection is only supported with dlmalloc";
4646#endif
Elliott Hughesa2155262011-11-16 16:26:58 -08004647 } else {
Ian Rogers1d54e732013-05-02 21:10:01 -07004648 gc::Heap* heap = Runtime::Current()->GetHeap();
Mathieu Chartier36dab362014-07-30 14:59:56 -07004649 for (const auto& space : heap->GetContinuousSpaces()) {
4650 if (space->IsDlMallocSpace()) {
Mathieu Chartier4c69d7f2014-10-10 12:45:50 -07004651 ReaderMutexLock mu(self, *Locks::heap_bitmap_lock_);
Mathieu Chartier36dab362014-07-30 14:59:56 -07004652 // dlmalloc's chunk header is 2 * sizeof(size_t), but if the previous chunk is in use for an
4653 // allocation then the first sizeof(size_t) may belong to it.
4654 context.SetChunkOverhead(sizeof(size_t));
Mathieu Chartierbc689b72014-12-14 17:01:31 -08004655 space->AsDlMallocSpace()->Walk(HeapChunkContext::HeapChunkJavaCallback, &context);
Mathieu Chartier36dab362014-07-30 14:59:56 -07004656 } else if (space->IsRosAllocSpace()) {
4657 context.SetChunkOverhead(0);
Mathieu Chartier4c69d7f2014-10-10 12:45:50 -07004658 // Need to acquire the mutator lock before the heap bitmap lock with exclusive access since
4659 // RosAlloc's internal logic doesn't know to release and reacquire the heap bitmap lock.
4660 self->TransitionFromRunnableToSuspended(kSuspended);
4661 ThreadList* tl = Runtime::Current()->GetThreadList();
Mathieu Chartierbf9fc582015-03-13 17:21:25 -07004662 tl->SuspendAll(__FUNCTION__);
Mathieu Chartier4c69d7f2014-10-10 12:45:50 -07004663 {
4664 ReaderMutexLock mu(self, *Locks::heap_bitmap_lock_);
Mathieu Chartierbc689b72014-12-14 17:01:31 -08004665 space->AsRosAllocSpace()->Walk(HeapChunkContext::HeapChunkJavaCallback, &context);
Mathieu Chartier4c69d7f2014-10-10 12:45:50 -07004666 }
4667 tl->ResumeAll();
4668 self->TransitionFromSuspendedToRunnable();
Mathieu Chartier36dab362014-07-30 14:59:56 -07004669 } else if (space->IsBumpPointerSpace()) {
Mathieu Chartier4c69d7f2014-10-10 12:45:50 -07004670 ReaderMutexLock mu(self, *Locks::heap_bitmap_lock_);
Mathieu Chartier36dab362014-07-30 14:59:56 -07004671 context.SetChunkOverhead(0);
Mathieu Chartier36dab362014-07-30 14:59:56 -07004672 space->AsBumpPointerSpace()->Walk(BumpPointerSpaceCallback, &context);
Mathieu Chartierbc689b72014-12-14 17:01:31 -08004673 HeapChunkContext::HeapChunkJavaCallback(nullptr, nullptr, 0, &context);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08004674 } else if (space->IsRegionSpace()) {
4675 heap->IncrementDisableMovingGC(self);
4676 self->TransitionFromRunnableToSuspended(kSuspended);
4677 ThreadList* tl = Runtime::Current()->GetThreadList();
Mathieu Chartierbf9fc582015-03-13 17:21:25 -07004678 tl->SuspendAll(__FUNCTION__);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08004679 ReaderMutexLock mu(self, *Locks::heap_bitmap_lock_);
4680 context.SetChunkOverhead(0);
4681 space->AsRegionSpace()->Walk(BumpPointerSpaceCallback, &context);
4682 HeapChunkContext::HeapChunkJavaCallback(nullptr, nullptr, 0, &context);
4683 tl->ResumeAll();
4684 self->TransitionFromSuspendedToRunnable();
4685 heap->DecrementDisableMovingGC(self);
Mathieu Chartier36dab362014-07-30 14:59:56 -07004686 } else {
4687 UNIMPLEMENTED(WARNING) << "Not counting objects in space " << *space;
Mathieu Chartierb062fdd2012-07-03 09:51:48 -07004688 }
Mathieu Chartier36dab362014-07-30 14:59:56 -07004689 context.ResetStartOfNextChunk();
Mathieu Chartierb062fdd2012-07-03 09:51:48 -07004690 }
Mathieu Chartier4c69d7f2014-10-10 12:45:50 -07004691 ReaderMutexLock mu(self, *Locks::heap_bitmap_lock_);
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -07004692 // Walk the large objects, these are not in the AllocSpace.
Mathieu Chartier36dab362014-07-30 14:59:56 -07004693 context.SetChunkOverhead(0);
Mathieu Chartierbc689b72014-12-14 17:01:31 -08004694 heap->GetLargeObjectsSpace()->Walk(HeapChunkContext::HeapChunkJavaCallback, &context);
Elliott Hughesa2155262011-11-16 16:26:58 -08004695 }
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004696
4697 // Finally, send a heap end chunk.
4698 Dbg::DdmSendChunk(native ? CHUNK_TYPE("NHEN") : CHUNK_TYPE("HPEN"), sizeof(heap_id), heap_id);
Elliott Hughes767a1472011-10-26 18:49:02 -07004699}
4700
Brian Carlstrom306db812014-09-05 13:01:41 -07004701void Dbg::SetAllocTrackingEnabled(bool enable) {
Man Cao8c2ff642015-05-27 17:25:30 -07004702 gc::AllocRecordObjectMap::SetAllocTrackingEnabled(enable);
Elliott Hughes545a0642011-11-08 19:10:03 -08004703}
4704
4705void Dbg::DumpRecentAllocations() {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07004706 ScopedObjectAccess soa(Thread::Current());
Brian Carlstrom306db812014-09-05 13:01:41 -07004707 MutexLock mu(soa.Self(), *Locks::alloc_tracker_lock_);
Man Cao8c2ff642015-05-27 17:25:30 -07004708 if (!Runtime::Current()->GetHeap()->IsAllocTrackingEnabled()) {
Elliott Hughes545a0642011-11-08 19:10:03 -08004709 LOG(INFO) << "Not recording tracked allocations";
4710 return;
4711 }
Man Cao8c2ff642015-05-27 17:25:30 -07004712 gc::AllocRecordObjectMap* records = Runtime::Current()->GetHeap()->GetAllocationRecords();
4713 CHECK(records != nullptr);
Elliott Hughes545a0642011-11-08 19:10:03 -08004714
Man Cao1ed11b92015-06-11 22:47:35 -07004715 const uint16_t capped_count = CappedAllocRecordCount(records->GetRecentAllocationSize());
Brian Carlstrom306db812014-09-05 13:01:41 -07004716 uint16_t count = capped_count;
Elliott Hughes545a0642011-11-08 19:10:03 -08004717
Man Cao8c2ff642015-05-27 17:25:30 -07004718 LOG(INFO) << "Tracked allocations, (count=" << count << ")";
4719 for (auto it = records->RBegin(), end = records->REnd();
4720 count > 0 && it != end; count--, it++) {
4721 const gc::AllocRecord* record = it->second;
Elliott Hughes545a0642011-11-08 19:10:03 -08004722
Man Cao8c2ff642015-05-27 17:25:30 -07004723 LOG(INFO) << StringPrintf(" Thread %-2d %6zd bytes ", record->GetTid(), record->ByteCount())
Man Cao42c3c332015-06-23 16:38:25 -07004724 << PrettyClass(record->GetClass());
Elliott Hughes545a0642011-11-08 19:10:03 -08004725
Man Cao8c2ff642015-05-27 17:25:30 -07004726 for (size_t stack_frame = 0, depth = record->GetDepth(); stack_frame < depth; ++stack_frame) {
4727 const gc::AllocRecordStackTraceElement& stack_element = record->StackElement(stack_frame);
4728 ArtMethod* m = stack_element.GetMethod();
4729 LOG(INFO) << " " << PrettyMethod(m) << " line " << stack_element.ComputeLineNumber();
Elliott Hughes545a0642011-11-08 19:10:03 -08004730 }
4731
4732 // pause periodically to help logcat catch up
4733 if ((count % 5) == 0) {
4734 usleep(40000);
4735 }
Elliott Hughes545a0642011-11-08 19:10:03 -08004736 }
4737}
4738
4739class StringTable {
4740 public:
4741 StringTable() {
4742 }
4743
Mathieu Chartier4345c462014-06-27 10:20:14 -07004744 void Add(const std::string& str) {
4745 table_.insert(str);
4746 }
4747
4748 void Add(const char* str) {
4749 table_.insert(str);
Elliott Hughes545a0642011-11-08 19:10:03 -08004750 }
4751
Elliott Hughesa8f93cb2012-06-08 17:08:48 -07004752 size_t IndexOf(const char* s) const {
Mathieu Chartier02e25112013-08-14 16:14:24 -07004753 auto it = table_.find(s);
Elliott Hughesa8f93cb2012-06-08 17:08:48 -07004754 if (it == table_.end()) {
4755 LOG(FATAL) << "IndexOf(\"" << s << "\") failed";
4756 }
4757 return std::distance(table_.begin(), it);
Elliott Hughes545a0642011-11-08 19:10:03 -08004758 }
4759
Elliott Hughesa8f93cb2012-06-08 17:08:48 -07004760 size_t Size() const {
Elliott Hughes545a0642011-11-08 19:10:03 -08004761 return table_.size();
4762 }
4763
Elliott Hughesa8f93cb2012-06-08 17:08:48 -07004764 void WriteTo(std::vector<uint8_t>& bytes) const {
Mathieu Chartier02e25112013-08-14 16:14:24 -07004765 for (const std::string& str : table_) {
4766 const char* s = str.c_str();
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08004767 size_t s_len = CountModifiedUtf8Chars(s);
Christopher Ferris8a354052015-04-24 17:23:53 -07004768 std::unique_ptr<uint16_t[]> s_utf16(new uint16_t[s_len]);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08004769 ConvertModifiedUtf8ToUtf16(s_utf16.get(), s);
4770 JDWP::AppendUtf16BE(bytes, s_utf16.get(), s_len);
Elliott Hughes545a0642011-11-08 19:10:03 -08004771 }
4772 }
4773
4774 private:
Elliott Hughesa8f93cb2012-06-08 17:08:48 -07004775 std::set<std::string> table_;
Elliott Hughes545a0642011-11-08 19:10:03 -08004776 DISALLOW_COPY_AND_ASSIGN(StringTable);
4777};
4778
Mathieu Chartiere401d142015-04-22 13:56:20 -07004779static const char* GetMethodSourceFile(ArtMethod* method)
Mathieu Chartier90443472015-07-16 20:32:27 -07004780 SHARED_REQUIRES(Locks::mutator_lock_) {
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07004781 DCHECK(method != nullptr);
4782 const char* source_file = method->GetDeclaringClassSourceFile();
Sebastien Hertz280286a2014-04-28 09:26:50 +02004783 return (source_file != nullptr) ? source_file : "";
4784}
4785
Elliott Hughes545a0642011-11-08 19:10:03 -08004786/*
4787 * The data we send to DDMS contains everything we have recorded.
4788 *
4789 * Message header (all values big-endian):
4790 * (1b) message header len (to allow future expansion); includes itself
4791 * (1b) entry header len
4792 * (1b) stack frame len
4793 * (2b) number of entries
4794 * (4b) offset to string table from start of message
4795 * (2b) number of class name strings
4796 * (2b) number of method name strings
4797 * (2b) number of source file name strings
4798 * For each entry:
4799 * (4b) total allocation size
Elliott Hughes221229c2013-01-08 18:17:50 -08004800 * (2b) thread id
Elliott Hughes545a0642011-11-08 19:10:03 -08004801 * (2b) allocated object's class name index
4802 * (1b) stack depth
4803 * For each stack frame:
4804 * (2b) method's class name
4805 * (2b) method name
4806 * (2b) method source file
4807 * (2b) line number, clipped to 32767; -2 if native; -1 if no source
4808 * (xb) class name strings
4809 * (xb) method name strings
4810 * (xb) source file strings
4811 *
4812 * As with other DDM traffic, strings are sent as a 4-byte length
4813 * followed by UTF-16 data.
4814 *
4815 * We send up 16-bit unsigned indexes into string tables. In theory there
Brian Carlstrom306db812014-09-05 13:01:41 -07004816 * can be (kMaxAllocRecordStackDepth * alloc_record_max_) unique strings in
Elliott Hughes545a0642011-11-08 19:10:03 -08004817 * each table, but in practice there should be far fewer.
4818 *
4819 * The chief reason for using a string table here is to keep the size of
4820 * the DDMS message to a minimum. This is partly to make the protocol
4821 * efficient, but also because we have to form the whole thing up all at
4822 * once in a memory buffer.
4823 *
4824 * We use separate string tables for class names, method names, and source
4825 * files to keep the indexes small. There will generally be no overlap
4826 * between the contents of these tables.
4827 */
4828jbyteArray Dbg::GetRecentAllocations() {
Ian Rogerscf7f1912014-10-22 22:06:39 -07004829 if ((false)) {
Elliott Hughes545a0642011-11-08 19:10:03 -08004830 DumpRecentAllocations();
4831 }
4832
Ian Rogers50b35e22012-10-04 10:09:15 -07004833 Thread* self = Thread::Current();
Elliott Hughes545a0642011-11-08 19:10:03 -08004834 std::vector<uint8_t> bytes;
Mathieu Chartier46e811b2013-07-10 17:09:14 -07004835 {
Brian Carlstrom306db812014-09-05 13:01:41 -07004836 MutexLock mu(self, *Locks::alloc_tracker_lock_);
Man Cao8c2ff642015-05-27 17:25:30 -07004837 gc::AllocRecordObjectMap* records = Runtime::Current()->GetHeap()->GetAllocationRecords();
4838 // In case this method is called when allocation tracker is disabled,
4839 // we should still send some data back.
4840 gc::AllocRecordObjectMap dummy;
4841 if (records == nullptr) {
4842 CHECK(!Runtime::Current()->GetHeap()->IsAllocTrackingEnabled());
4843 records = &dummy;
4844 }
Man Cao41656de2015-07-06 18:53:15 -07004845 // We don't need to wait on the condition variable records->new_record_condition_, because this
4846 // function only reads the class objects, which are already marked so it doesn't change their
4847 // reachability.
Man Cao8c2ff642015-05-27 17:25:30 -07004848
Mathieu Chartier46e811b2013-07-10 17:09:14 -07004849 //
4850 // Part 1: generate string tables.
4851 //
4852 StringTable class_names;
4853 StringTable method_names;
4854 StringTable filenames;
Elliott Hughes545a0642011-11-08 19:10:03 -08004855
Man Cao1ed11b92015-06-11 22:47:35 -07004856 const uint16_t capped_count = CappedAllocRecordCount(records->GetRecentAllocationSize());
Brian Carlstrom306db812014-09-05 13:01:41 -07004857 uint16_t count = capped_count;
Man Cao8c2ff642015-05-27 17:25:30 -07004858 for (auto it = records->RBegin(), end = records->REnd();
4859 count > 0 && it != end; count--, it++) {
4860 const gc::AllocRecord* record = it->second;
Ian Rogers1ff3c982014-08-12 02:30:58 -07004861 std::string temp;
Man Cao41656de2015-07-06 18:53:15 -07004862 class_names.Add(record->GetClassDescriptor(&temp));
Man Cao8c2ff642015-05-27 17:25:30 -07004863 for (size_t i = 0, depth = record->GetDepth(); i < depth; i++) {
4864 ArtMethod* m = record->StackElement(i).GetMethod();
4865 class_names.Add(m->GetDeclaringClassDescriptor());
4866 method_names.Add(m->GetName());
4867 filenames.Add(GetMethodSourceFile(m));
Mathieu Chartier46e811b2013-07-10 17:09:14 -07004868 }
Elliott Hughes545a0642011-11-08 19:10:03 -08004869 }
4870
Man Cao8c2ff642015-05-27 17:25:30 -07004871 LOG(INFO) << "recent allocation records: " << capped_count;
4872 LOG(INFO) << "allocation records all objects: " << records->Size();
Mathieu Chartier46e811b2013-07-10 17:09:14 -07004873
4874 //
4875 // Part 2: Generate the output and store it in the buffer.
4876 //
4877
4878 // (1b) message header len (to allow future expansion); includes itself
4879 // (1b) entry header len
4880 // (1b) stack frame len
4881 const int kMessageHeaderLen = 15;
4882 const int kEntryHeaderLen = 9;
4883 const int kStackFrameLen = 8;
4884 JDWP::Append1BE(bytes, kMessageHeaderLen);
4885 JDWP::Append1BE(bytes, kEntryHeaderLen);
4886 JDWP::Append1BE(bytes, kStackFrameLen);
4887
4888 // (2b) number of entries
4889 // (4b) offset to string table from start of message
4890 // (2b) number of class name strings
4891 // (2b) number of method name strings
4892 // (2b) number of source file name strings
Brian Carlstrom306db812014-09-05 13:01:41 -07004893 JDWP::Append2BE(bytes, capped_count);
Mathieu Chartier46e811b2013-07-10 17:09:14 -07004894 size_t string_table_offset = bytes.size();
Brian Carlstrom7934ac22013-07-26 10:54:15 -07004895 JDWP::Append4BE(bytes, 0); // We'll patch this later...
Mathieu Chartier46e811b2013-07-10 17:09:14 -07004896 JDWP::Append2BE(bytes, class_names.Size());
4897 JDWP::Append2BE(bytes, method_names.Size());
4898 JDWP::Append2BE(bytes, filenames.Size());
4899
Ian Rogers1ff3c982014-08-12 02:30:58 -07004900 std::string temp;
Man Cao8c2ff642015-05-27 17:25:30 -07004901 count = capped_count;
4902 // The last "count" number of allocation records in "records" are the most recent "count" number
4903 // of allocations. Reverse iterate to get them. The most recent allocation is sent first.
4904 for (auto it = records->RBegin(), end = records->REnd();
4905 count > 0 && it != end; count--, it++) {
Mathieu Chartier46e811b2013-07-10 17:09:14 -07004906 // For each entry:
4907 // (4b) total allocation size
4908 // (2b) thread id
4909 // (2b) allocated object's class name index
4910 // (1b) stack depth
Man Cao8c2ff642015-05-27 17:25:30 -07004911 const gc::AllocRecord* record = it->second;
Mathieu Chartier46e811b2013-07-10 17:09:14 -07004912 size_t stack_depth = record->GetDepth();
Mathieu Chartierf8322842014-05-16 10:59:25 -07004913 size_t allocated_object_class_name_index =
Man Cao41656de2015-07-06 18:53:15 -07004914 class_names.IndexOf(record->GetClassDescriptor(&temp));
Hiroshi Yamauchib5a9e3d2014-06-09 12:11:20 -07004915 JDWP::Append4BE(bytes, record->ByteCount());
Man Cao8c2ff642015-05-27 17:25:30 -07004916 JDWP::Append2BE(bytes, static_cast<uint16_t>(record->GetTid()));
Mathieu Chartier46e811b2013-07-10 17:09:14 -07004917 JDWP::Append2BE(bytes, allocated_object_class_name_index);
4918 JDWP::Append1BE(bytes, stack_depth);
4919
Mathieu Chartier46e811b2013-07-10 17:09:14 -07004920 for (size_t stack_frame = 0; stack_frame < stack_depth; ++stack_frame) {
4921 // For each stack frame:
4922 // (2b) method's class name
4923 // (2b) method name
4924 // (2b) method source file
4925 // (2b) line number, clipped to 32767; -2 if native; -1 if no source
Man Cao8c2ff642015-05-27 17:25:30 -07004926 ArtMethod* m = record->StackElement(stack_frame).GetMethod();
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07004927 size_t class_name_index = class_names.IndexOf(m->GetDeclaringClassDescriptor());
4928 size_t method_name_index = method_names.IndexOf(m->GetName());
4929 size_t file_name_index = filenames.IndexOf(GetMethodSourceFile(m));
Mathieu Chartier46e811b2013-07-10 17:09:14 -07004930 JDWP::Append2BE(bytes, class_name_index);
4931 JDWP::Append2BE(bytes, method_name_index);
4932 JDWP::Append2BE(bytes, file_name_index);
Man Cao8c2ff642015-05-27 17:25:30 -07004933 JDWP::Append2BE(bytes, record->StackElement(stack_frame).ComputeLineNumber());
Mathieu Chartier46e811b2013-07-10 17:09:14 -07004934 }
Mathieu Chartier46e811b2013-07-10 17:09:14 -07004935 }
4936
4937 // (xb) class name strings
4938 // (xb) method name strings
4939 // (xb) source file strings
4940 JDWP::Set4BE(&bytes[string_table_offset], bytes.size());
4941 class_names.WriteTo(bytes);
4942 method_names.WriteTo(bytes);
4943 filenames.WriteTo(bytes);
Elliott Hughes545a0642011-11-08 19:10:03 -08004944 }
Ian Rogers50b35e22012-10-04 10:09:15 -07004945 JNIEnv* env = self->GetJniEnv();
Elliott Hughes545a0642011-11-08 19:10:03 -08004946 jbyteArray result = env->NewByteArray(bytes.size());
Ian Rogersc0542af2014-09-03 16:16:56 -07004947 if (result != nullptr) {
Elliott Hughes545a0642011-11-08 19:10:03 -08004948 env->SetByteArrayRegion(result, 0, bytes.size(), reinterpret_cast<const jbyte*>(&bytes[0]));
4949 }
4950 return result;
4951}
4952
Mathieu Chartiere401d142015-04-22 13:56:20 -07004953ArtMethod* DeoptimizationRequest::Method() const {
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07004954 ScopedObjectAccessUnchecked soa(Thread::Current());
4955 return soa.DecodeMethod(method_);
4956}
4957
Mathieu Chartiere401d142015-04-22 13:56:20 -07004958void DeoptimizationRequest::SetMethod(ArtMethod* m) {
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07004959 ScopedObjectAccessUnchecked soa(Thread::Current());
4960 method_ = soa.EncodeMethod(m);
4961}
4962
Elliott Hughes872d4ec2011-10-21 17:07:15 -07004963} // namespace art