blob: e1e130bc01798e6d0eb2bf0fff8ba2b87b801b2f [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"
Igor Murashkinbc1d78d2015-07-30 16:39:45 -070027#include "base/out.h"
Elliott Hughes545a0642011-11-08 19:10:03 -080028#include "class_linker.h"
Ian Rogers2dd0e2c2013-01-24 12:42:14 -080029#include "class_linker-inl.h"
Ian Rogers4f6ad8a2013-03-18 15:27:28 -070030#include "dex_file-inl.h"
Ian Rogers776ac1f2012-04-13 23:36:36 -070031#include "dex_instruction.h"
Ian Rogers1d54e732013-05-02 21:10:01 -070032#include "gc/accounting/card_table-inl.h"
Man Cao8c2ff642015-05-27 17:25:30 -070033#include "gc/allocation_record.h"
Ian Rogers1d54e732013-05-02 21:10:01 -070034#include "gc/space/large_object_space.h"
35#include "gc/space/space-inl.h"
Mathieu Chartiereb8167a2014-05-07 15:43:14 -070036#include "handle_scope.h"
Sebastien Hertzcbc50642015-06-01 17:33:12 +020037#include "jdwp/jdwp_priv.h"
Elliott Hughes64f574f2013-02-20 14:57:12 -080038#include "jdwp/object_registry.h"
Ian Rogers2dd0e2c2013-01-24 12:42:14 -080039#include "mirror/class.h"
40#include "mirror/class-inl.h"
41#include "mirror/class_loader.h"
Ian Rogers2dd0e2c2013-01-24 12:42:14 -080042#include "mirror/object-inl.h"
43#include "mirror/object_array-inl.h"
Ian Rogersb0fa5dc2014-04-28 16:47:08 -070044#include "mirror/string-inl.h"
Ian Rogers2dd0e2c2013-01-24 12:42:14 -080045#include "mirror/throwable.h"
Sebastien Hertza76a6d42014-03-20 16:40:17 +010046#include "quick/inline_method_analyser.h"
Ian Rogers53b8b092014-03-13 23:45:53 -070047#include "reflection.h"
Elliott Hughesa0e18062012-04-13 15:59:59 -070048#include "safe_map.h"
Elliott Hughes64f574f2013-02-20 14:57:12 -080049#include "scoped_thread_state_change.h"
Elliott Hughes6a5bd492011-10-28 14:33:57 -070050#include "ScopedLocalRef.h"
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -070051#include "ScopedPrimitiveArray.h"
Mathieu Chartiereb8167a2014-05-07 15:43:14 -070052#include "handle_scope-inl.h"
Elliott Hughes475fc232011-10-25 15:00:35 -070053#include "thread_list.h"
Ian Rogers2dd0e2c2013-01-24 12:42:14 -080054#include "utf.h"
Sebastien Hertza76a6d42014-03-20 16:40:17 +010055#include "verifier/method_verifier-inl.h"
Elliott Hugheseac76672012-05-24 21:56:51 -070056#include "well_known_classes.h"
Elliott Hughes475fc232011-10-25 15:00:35 -070057
Elliott Hughes872d4ec2011-10-21 17:07:15 -070058namespace art {
59
Sebastien Hertz0462c4c2015-04-01 16:34:17 +020060// The key identifying the debugger to update instrumentation.
61static constexpr const char* kDbgInstrumentationKey = "Debugger";
62
Man Cao8c2ff642015-05-27 17:25:30 -070063// 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 -070064static uint16_t CappedAllocRecordCount(size_t alloc_record_count) {
Man Cao1ed11b92015-06-11 22:47:35 -070065 const size_t cap = 0xffff;
Man Cao8c2ff642015-05-27 17:25:30 -070066 if (alloc_record_count > cap) {
67 return cap;
Brian Carlstrom306db812014-09-05 13:01:41 -070068 }
69 return alloc_record_count;
70}
Elliott Hughes475fc232011-10-25 15:00:35 -070071
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -070072class Breakpoint {
73 public:
Mathieu Chartiere401d142015-04-22 13:56:20 -070074 Breakpoint(ArtMethod* method, uint32_t dex_pc,
Sebastien Hertzf3928792014-11-17 19:00:37 +010075 DeoptimizationRequest::Kind deoptimization_kind)
Mathieu Chartier90443472015-07-16 20:32:27 -070076 SHARED_REQUIRES(Locks::mutator_lock_)
Sebastien Hertzf3928792014-11-17 19:00:37 +010077 : method_(nullptr), dex_pc_(dex_pc), deoptimization_kind_(deoptimization_kind) {
78 CHECK(deoptimization_kind_ == DeoptimizationRequest::kNothing ||
79 deoptimization_kind_ == DeoptimizationRequest::kSelectiveDeoptimization ||
80 deoptimization_kind_ == DeoptimizationRequest::kFullDeoptimization);
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -070081 ScopedObjectAccessUnchecked soa(Thread::Current());
82 method_ = soa.EncodeMethod(method);
83 }
84
Mathieu Chartier90443472015-07-16 20:32:27 -070085 Breakpoint(const Breakpoint& other) SHARED_REQUIRES(Locks::mutator_lock_)
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -070086 : method_(nullptr), dex_pc_(other.dex_pc_),
Sebastien Hertzf3928792014-11-17 19:00:37 +010087 deoptimization_kind_(other.deoptimization_kind_) {
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -070088 ScopedObjectAccessUnchecked soa(Thread::Current());
89 method_ = soa.EncodeMethod(other.Method());
90 }
91
Mathieu Chartier90443472015-07-16 20:32:27 -070092 ArtMethod* Method() const SHARED_REQUIRES(Locks::mutator_lock_) {
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -070093 ScopedObjectAccessUnchecked soa(Thread::Current());
94 return soa.DecodeMethod(method_);
95 }
96
97 uint32_t DexPc() const {
98 return dex_pc_;
99 }
100
Sebastien Hertzf3928792014-11-17 19:00:37 +0100101 DeoptimizationRequest::Kind GetDeoptimizationKind() const {
102 return deoptimization_kind_;
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -0700103 }
104
105 private:
Sebastien Hertza76a6d42014-03-20 16:40:17 +0100106 // The location of this breakpoint.
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -0700107 jmethodID method_;
108 uint32_t dex_pc_;
Sebastien Hertza76a6d42014-03-20 16:40:17 +0100109
110 // Indicates whether breakpoint needs full deoptimization or selective deoptimization.
Sebastien Hertzf3928792014-11-17 19:00:37 +0100111 DeoptimizationRequest::Kind deoptimization_kind_;
Elliott Hughes86964332012-02-15 19:37:42 -0800112};
113
Sebastien Hertzed2be172014-08-19 15:33:43 +0200114static std::ostream& operator<<(std::ostream& os, const Breakpoint& rhs)
Mathieu Chartier90443472015-07-16 20:32:27 -0700115 SHARED_REQUIRES(Locks::mutator_lock_) {
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -0700116 os << StringPrintf("Breakpoint[%s @%#x]", PrettyMethod(rhs.Method()).c_str(), rhs.DexPc());
Elliott Hughes86964332012-02-15 19:37:42 -0800117 return os;
118}
119
Sebastien Hertz3f52eaf2014-04-04 17:50:18 +0200120class DebugInstrumentationListener FINAL : public instrumentation::InstrumentationListener {
Ian Rogers62d6c772013-02-27 08:32:07 -0800121 public:
122 DebugInstrumentationListener() {}
123 virtual ~DebugInstrumentationListener() {}
124
Mathieu Chartiere401d142015-04-22 13:56:20 -0700125 void MethodEntered(Thread* thread, mirror::Object* this_object, ArtMethod* method,
Sebastien Hertz9d6bf692015-04-10 12:12:33 +0200126 uint32_t dex_pc)
Mathieu Chartier90443472015-07-16 20:32:27 -0700127 OVERRIDE SHARED_REQUIRES(Locks::mutator_lock_) {
Ian Rogers62d6c772013-02-27 08:32:07 -0800128 if (method->IsNative()) {
129 // TODO: post location events is a suspension point and native method entry stubs aren't.
130 return;
131 }
Sebastien Hertz9d6bf692015-04-10 12:12:33 +0200132 if (IsListeningToDexPcMoved()) {
133 // We also listen to kDexPcMoved instrumentation event so we know the DexPcMoved method is
134 // going to be called right after us. To avoid sending JDWP events twice for this location,
135 // we report the event in DexPcMoved. However, we must remind this is method entry so we
136 // send the METHOD_ENTRY event. And we can also group it with other events for this location
137 // like BREAKPOINT or SINGLE_STEP (or even METHOD_EXIT if this is a RETURN instruction).
138 thread->SetDebugMethodEntry();
139 } else if (IsListeningToMethodExit() && IsReturn(method, dex_pc)) {
140 // We also listen to kMethodExited instrumentation event and the current instruction is a
141 // RETURN so we know the MethodExited method is going to be called right after us. To avoid
142 // sending JDWP events twice for this location, we report the event(s) in MethodExited.
143 // However, we must remind this is method entry so we send the METHOD_ENTRY event. And we can
144 // also group it with other events for this location like BREAKPOINT or SINGLE_STEP.
145 thread->SetDebugMethodEntry();
146 } else {
147 Dbg::UpdateDebugger(thread, this_object, method, 0, Dbg::kMethodEntry, nullptr);
148 }
Ian Rogers62d6c772013-02-27 08:32:07 -0800149 }
150
Mathieu Chartiere401d142015-04-22 13:56:20 -0700151 void MethodExited(Thread* thread, mirror::Object* this_object, ArtMethod* method,
Sebastien Hertz3f52eaf2014-04-04 17:50:18 +0200152 uint32_t dex_pc, const JValue& return_value)
Mathieu Chartier90443472015-07-16 20:32:27 -0700153 OVERRIDE SHARED_REQUIRES(Locks::mutator_lock_) {
Ian Rogers62d6c772013-02-27 08:32:07 -0800154 if (method->IsNative()) {
155 // TODO: post location events is a suspension point and native method entry stubs aren't.
156 return;
157 }
Sebastien Hertz9d6bf692015-04-10 12:12:33 +0200158 uint32_t events = Dbg::kMethodExit;
159 if (thread->IsDebugMethodEntry()) {
160 // It is also the method entry.
161 DCHECK(IsReturn(method, dex_pc));
162 events |= Dbg::kMethodEntry;
163 thread->ClearDebugMethodEntry();
164 }
165 Dbg::UpdateDebugger(thread, this_object, method, dex_pc, events, &return_value);
Ian Rogers62d6c772013-02-27 08:32:07 -0800166 }
167
Sebastien Hertz9d6bf692015-04-10 12:12:33 +0200168 void MethodUnwind(Thread* thread ATTRIBUTE_UNUSED, mirror::Object* this_object ATTRIBUTE_UNUSED,
Mathieu Chartiere401d142015-04-22 13:56:20 -0700169 ArtMethod* method, uint32_t dex_pc)
Mathieu Chartier90443472015-07-16 20:32:27 -0700170 OVERRIDE SHARED_REQUIRES(Locks::mutator_lock_) {
Ian Rogers62d6c772013-02-27 08:32:07 -0800171 // We're not recorded to listen to this kind of event, so complain.
172 LOG(ERROR) << "Unexpected method unwind event in debugger " << PrettyMethod(method)
Sebastien Hertz51db44a2013-11-19 10:00:29 +0100173 << " " << dex_pc;
Ian Rogers62d6c772013-02-27 08:32:07 -0800174 }
175
Mathieu Chartiere401d142015-04-22 13:56:20 -0700176 void DexPcMoved(Thread* thread, mirror::Object* this_object, ArtMethod* method,
Sebastien Hertz3f52eaf2014-04-04 17:50:18 +0200177 uint32_t new_dex_pc)
Mathieu Chartier90443472015-07-16 20:32:27 -0700178 OVERRIDE SHARED_REQUIRES(Locks::mutator_lock_) {
Sebastien Hertz9d6bf692015-04-10 12:12:33 +0200179 if (IsListeningToMethodExit() && IsReturn(method, new_dex_pc)) {
180 // We also listen to kMethodExited instrumentation event and the current instruction is a
181 // RETURN so we know the MethodExited method is going to be called right after us. Like in
182 // MethodEntered, we delegate event reporting to MethodExited.
183 // Besides, if this RETURN instruction is the only one in the method, we can send multiple
184 // JDWP events in the same packet: METHOD_ENTRY, METHOD_EXIT, BREAKPOINT and/or SINGLE_STEP.
185 // Therefore, we must not clear the debug method entry flag here.
186 } else {
187 uint32_t events = 0;
188 if (thread->IsDebugMethodEntry()) {
189 // It is also the method entry.
190 events = Dbg::kMethodEntry;
191 thread->ClearDebugMethodEntry();
192 }
193 Dbg::UpdateDebugger(thread, this_object, method, new_dex_pc, events, nullptr);
194 }
Ian Rogers62d6c772013-02-27 08:32:07 -0800195 }
196
Sebastien Hertz9d6bf692015-04-10 12:12:33 +0200197 void FieldRead(Thread* thread ATTRIBUTE_UNUSED, mirror::Object* this_object,
Mathieu Chartiere401d142015-04-22 13:56:20 -0700198 ArtMethod* method, uint32_t dex_pc, ArtField* field)
Mathieu Chartier90443472015-07-16 20:32:27 -0700199 OVERRIDE SHARED_REQUIRES(Locks::mutator_lock_) {
Sebastien Hertz3f52eaf2014-04-04 17:50:18 +0200200 Dbg::PostFieldAccessEvent(method, dex_pc, this_object, field);
Ian Rogers62d6c772013-02-27 08:32:07 -0800201 }
Sebastien Hertz3f52eaf2014-04-04 17:50:18 +0200202
Ian Rogers6a3c1fc2014-10-31 00:33:20 -0700203 void FieldWritten(Thread* thread ATTRIBUTE_UNUSED, mirror::Object* this_object,
Mathieu Chartiere401d142015-04-22 13:56:20 -0700204 ArtMethod* method, uint32_t dex_pc, ArtField* field,
Ian Rogers6a3c1fc2014-10-31 00:33:20 -0700205 const JValue& field_value)
Mathieu Chartier90443472015-07-16 20:32:27 -0700206 OVERRIDE SHARED_REQUIRES(Locks::mutator_lock_) {
Sebastien Hertz3f52eaf2014-04-04 17:50:18 +0200207 Dbg::PostFieldModificationEvent(method, dex_pc, this_object, field, &field_value);
208 }
209
Nicolas Geoffray14691c52015-03-05 10:40:17 +0000210 void ExceptionCaught(Thread* thread ATTRIBUTE_UNUSED, mirror::Throwable* exception_object)
Mathieu Chartier90443472015-07-16 20:32:27 -0700211 OVERRIDE SHARED_REQUIRES(Locks::mutator_lock_) {
Nicolas Geoffray14691c52015-03-05 10:40:17 +0000212 Dbg::PostException(exception_object);
Sebastien Hertz3f52eaf2014-04-04 17:50:18 +0200213 }
214
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800215 // We only care about how many backward branches were executed in the Jit.
Mathieu Chartiere401d142015-04-22 13:56:20 -0700216 void BackwardBranch(Thread* /*thread*/, ArtMethod* method, int32_t dex_pc_offset)
Mathieu Chartier90443472015-07-16 20:32:27 -0700217 OVERRIDE SHARED_REQUIRES(Locks::mutator_lock_) {
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800218 LOG(ERROR) << "Unexpected backward branch event in debugger " << PrettyMethod(method)
219 << " " << dex_pc_offset;
220 }
221
Sebastien Hertz3f52eaf2014-04-04 17:50:18 +0200222 private:
Mathieu Chartiere401d142015-04-22 13:56:20 -0700223 static bool IsReturn(ArtMethod* method, uint32_t dex_pc)
Mathieu Chartier90443472015-07-16 20:32:27 -0700224 SHARED_REQUIRES(Locks::mutator_lock_) {
Sebastien Hertz9d6bf692015-04-10 12:12:33 +0200225 const DexFile::CodeItem* code_item = method->GetCodeItem();
226 const Instruction* instruction = Instruction::At(&code_item->insns_[dex_pc]);
227 return instruction->IsReturn();
228 }
229
Mathieu Chartier90443472015-07-16 20:32:27 -0700230 static bool IsListeningToDexPcMoved() SHARED_REQUIRES(Locks::mutator_lock_) {
Sebastien Hertz9d6bf692015-04-10 12:12:33 +0200231 return IsListeningTo(instrumentation::Instrumentation::kDexPcMoved);
232 }
233
Mathieu Chartier90443472015-07-16 20:32:27 -0700234 static bool IsListeningToMethodExit() SHARED_REQUIRES(Locks::mutator_lock_) {
Sebastien Hertz9d6bf692015-04-10 12:12:33 +0200235 return IsListeningTo(instrumentation::Instrumentation::kMethodExited);
236 }
237
238 static bool IsListeningTo(instrumentation::Instrumentation::InstrumentationEvent event)
Mathieu Chartier90443472015-07-16 20:32:27 -0700239 SHARED_REQUIRES(Locks::mutator_lock_) {
Sebastien Hertz9d6bf692015-04-10 12:12:33 +0200240 return (Dbg::GetInstrumentationEvents() & event) != 0;
241 }
242
Sebastien Hertz3f52eaf2014-04-04 17:50:18 +0200243 DISALLOW_COPY_AND_ASSIGN(DebugInstrumentationListener);
Ian Rogers62d6c772013-02-27 08:32:07 -0800244} gDebugInstrumentationListener;
245
Elliott Hughes4ffd3132011-10-24 12:06:42 -0700246// JDWP is allowed unless the Zygote forbids it.
247static bool gJdwpAllowed = true;
248
Elliott Hughesc0f09332012-03-26 13:27:06 -0700249// Was there a -Xrunjdwp or -agentlib:jdwp= argument on the command line?
Elliott Hughes3bb81562011-10-21 18:52:59 -0700250static bool gJdwpConfigured = false;
251
Sebastien Hertzb3b173b2015-02-06 09:16:32 +0100252// JDWP options for debugging. Only valid if IsJdwpConfigured() is true.
253static JDWP::JdwpOptions gJdwpOptions;
254
Elliott Hughes3bb81562011-10-21 18:52:59 -0700255// Runtime JDWP state.
Ian Rogersc0542af2014-09-03 16:16:56 -0700256static JDWP::JdwpState* gJdwpState = nullptr;
Elliott Hughes3bb81562011-10-21 18:52:59 -0700257static bool gDebuggerConnected; // debugger or DDMS is connected.
Elliott Hughes3bb81562011-10-21 18:52:59 -0700258
Elliott Hughes47fce012011-10-25 18:37:19 -0700259static bool gDdmThreadNotification = false;
260
Elliott Hughes767a1472011-10-26 18:49:02 -0700261// DDMS GC-related settings.
262static Dbg::HpifWhen gDdmHpifWhen = Dbg::HPIF_WHEN_NEVER;
263static Dbg::HpsgWhen gDdmHpsgWhen = Dbg::HPSG_WHEN_NEVER;
264static Dbg::HpsgWhat gDdmHpsgWhat;
265static Dbg::HpsgWhen gDdmNhsgWhen = Dbg::HPSG_WHEN_NEVER;
266static Dbg::HpsgWhat gDdmNhsgWhat;
267
Daniel Mihalyieb076692014-08-22 17:33:31 +0200268bool Dbg::gDebuggerActive = false;
Sebastien Hertz4e5b2082015-03-24 19:03:40 +0100269bool Dbg::gDisposed = false;
Sebastien Hertz6995c602014-09-09 12:10:13 +0200270ObjectRegistry* Dbg::gRegistry = nullptr;
Elliott Hughes475fc232011-10-25 15:00:35 -0700271
Sebastien Hertz138dbfc2013-12-04 18:15:25 +0100272// Deoptimization support.
Sebastien Hertz4d25df32014-03-21 17:44:46 +0100273std::vector<DeoptimizationRequest> Dbg::deoptimization_requests_;
274size_t Dbg::full_deoptimization_event_count_ = 0;
Sebastien Hertz138dbfc2013-12-04 18:15:25 +0100275
Sebastien Hertz42cd43f2014-05-13 14:15:41 +0200276// Instrumentation event reference counters.
277size_t Dbg::dex_pc_change_event_ref_count_ = 0;
278size_t Dbg::method_enter_event_ref_count_ = 0;
279size_t Dbg::method_exit_event_ref_count_ = 0;
280size_t Dbg::field_read_event_ref_count_ = 0;
281size_t Dbg::field_write_event_ref_count_ = 0;
282size_t Dbg::exception_catch_event_ref_count_ = 0;
283uint32_t Dbg::instrumentation_events_ = 0;
284
Sebastien Hertz138dbfc2013-12-04 18:15:25 +0100285// Breakpoints.
jeffhao09bfc6a2012-12-11 18:11:43 -0800286static std::vector<Breakpoint> gBreakpoints GUARDED_BY(Locks::breakpoint_lock_);
Elliott Hughes86964332012-02-15 19:37:42 -0800287
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -0700288void DebugInvokeReq::VisitRoots(RootVisitor* visitor, const RootInfo& root_info) {
289 receiver.VisitRootIfNonNull(visitor, root_info); // null for static method call.
290 klass.VisitRoot(visitor, root_info);
Mathieu Chartier3b05e9b2014-03-25 09:29:43 -0700291}
292
Sebastien Hertz597c4f02015-01-26 17:37:14 +0100293void SingleStepControl::AddDexPc(uint32_t dex_pc) {
294 dex_pcs_.insert(dex_pc);
Sebastien Hertzbb43b432014-04-14 11:59:08 +0200295}
296
Sebastien Hertz597c4f02015-01-26 17:37:14 +0100297bool SingleStepControl::ContainsDexPc(uint32_t dex_pc) const {
298 return dex_pcs_.find(dex_pc) == dex_pcs_.end();
Sebastien Hertzbb43b432014-04-14 11:59:08 +0200299}
300
Mathieu Chartiere401d142015-04-22 13:56:20 -0700301static bool IsBreakpoint(const ArtMethod* m, uint32_t dex_pc)
Mathieu Chartier90443472015-07-16 20:32:27 -0700302 REQUIRES(!Locks::breakpoint_lock_)
303 SHARED_REQUIRES(Locks::mutator_lock_) {
Sebastien Hertzed2be172014-08-19 15:33:43 +0200304 ReaderMutexLock mu(Thread::Current(), *Locks::breakpoint_lock_);
Sebastien Hertz138dbfc2013-12-04 18:15:25 +0100305 for (size_t i = 0, e = gBreakpoints.size(); i < e; ++i) {
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -0700306 if (gBreakpoints[i].DexPc() == dex_pc && gBreakpoints[i].Method() == m) {
Elliott Hughes86964332012-02-15 19:37:42 -0800307 VLOG(jdwp) << "Hit breakpoint #" << i << ": " << gBreakpoints[i];
308 return true;
309 }
310 }
311 return false;
312}
313
Sebastien Hertz52d131d2014-03-13 16:17:40 +0100314static bool IsSuspendedForDebugger(ScopedObjectAccessUnchecked& soa, Thread* thread)
Mathieu Chartier90443472015-07-16 20:32:27 -0700315 REQUIRES(!Locks::thread_suspend_count_lock_) {
Elliott Hughes9e0c1752013-01-09 14:02:58 -0800316 MutexLock mu(soa.Self(), *Locks::thread_suspend_count_lock_);
317 // A thread may be suspended for GC; in this code, we really want to know whether
318 // there's a debugger suspension active.
319 return thread->IsSuspended() && thread->GetDebugSuspendCount() > 0;
320}
321
Ian Rogersc0542af2014-09-03 16:16:56 -0700322static mirror::Array* DecodeNonNullArray(JDWP::RefTypeId id, JDWP::JdwpError* error)
Mathieu Chartier90443472015-07-16 20:32:27 -0700323 SHARED_REQUIRES(Locks::mutator_lock_) {
Sebastien Hertz6995c602014-09-09 12:10:13 +0200324 mirror::Object* o = Dbg::GetObjectRegistry()->Get<mirror::Object*>(id, error);
Ian Rogersc0542af2014-09-03 16:16:56 -0700325 if (o == nullptr) {
326 *error = JDWP::ERR_INVALID_OBJECT;
327 return nullptr;
Elliott Hughes436e3722012-02-17 20:01:47 -0800328 }
329 if (!o->IsArrayInstance()) {
Ian Rogersc0542af2014-09-03 16:16:56 -0700330 *error = JDWP::ERR_INVALID_ARRAY;
331 return nullptr;
Elliott Hughes436e3722012-02-17 20:01:47 -0800332 }
Ian Rogersc0542af2014-09-03 16:16:56 -0700333 *error = JDWP::ERR_NONE;
Elliott Hughes436e3722012-02-17 20:01:47 -0800334 return o->AsArray();
335}
336
Ian Rogersc0542af2014-09-03 16:16:56 -0700337static mirror::Class* DecodeClass(JDWP::RefTypeId id, JDWP::JdwpError* error)
Mathieu Chartier90443472015-07-16 20:32:27 -0700338 SHARED_REQUIRES(Locks::mutator_lock_) {
Sebastien Hertz6995c602014-09-09 12:10:13 +0200339 mirror::Object* o = Dbg::GetObjectRegistry()->Get<mirror::Object*>(id, error);
Ian Rogersc0542af2014-09-03 16:16:56 -0700340 if (o == nullptr) {
341 *error = JDWP::ERR_INVALID_OBJECT;
342 return nullptr;
Elliott Hughes436e3722012-02-17 20:01:47 -0800343 }
344 if (!o->IsClass()) {
Ian Rogersc0542af2014-09-03 16:16:56 -0700345 *error = JDWP::ERR_INVALID_CLASS;
346 return nullptr;
Elliott Hughes436e3722012-02-17 20:01:47 -0800347 }
Ian Rogersc0542af2014-09-03 16:16:56 -0700348 *error = JDWP::ERR_NONE;
Elliott Hughes436e3722012-02-17 20:01:47 -0800349 return o->AsClass();
350}
351
Ian Rogersc0542af2014-09-03 16:16:56 -0700352static Thread* DecodeThread(ScopedObjectAccessUnchecked& soa, JDWP::ObjectId thread_id,
353 JDWP::JdwpError* error)
Mathieu Chartier90443472015-07-16 20:32:27 -0700354 SHARED_REQUIRES(Locks::mutator_lock_)
355 REQUIRES(!Locks::thread_list_lock_, !Locks::thread_suspend_count_lock_) {
Sebastien Hertz6995c602014-09-09 12:10:13 +0200356 mirror::Object* thread_peer = Dbg::GetObjectRegistry()->Get<mirror::Object*>(thread_id, error);
Ian Rogersc0542af2014-09-03 16:16:56 -0700357 if (thread_peer == nullptr) {
Elliott Hughes221229c2013-01-08 18:17:50 -0800358 // This isn't even an object.
Ian Rogersc0542af2014-09-03 16:16:56 -0700359 *error = JDWP::ERR_INVALID_OBJECT;
360 return nullptr;
Elliott Hughes436e3722012-02-17 20:01:47 -0800361 }
Elliott Hughes221229c2013-01-08 18:17:50 -0800362
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800363 mirror::Class* java_lang_Thread = soa.Decode<mirror::Class*>(WellKnownClasses::java_lang_Thread);
Elliott Hughes221229c2013-01-08 18:17:50 -0800364 if (!java_lang_Thread->IsAssignableFrom(thread_peer->GetClass())) {
365 // This isn't a thread.
Ian Rogersc0542af2014-09-03 16:16:56 -0700366 *error = JDWP::ERR_INVALID_THREAD;
367 return nullptr;
Elliott Hughes221229c2013-01-08 18:17:50 -0800368 }
369
Sebastien Hertz69206392015-04-07 15:54:25 +0200370 MutexLock mu(soa.Self(), *Locks::thread_list_lock_);
Ian Rogersc0542af2014-09-03 16:16:56 -0700371 Thread* thread = Thread::FromManagedThread(soa, thread_peer);
372 // If thread is null then this a java.lang.Thread without a Thread*. Must be a un-started or a
373 // zombie.
374 *error = (thread == nullptr) ? JDWP::ERR_THREAD_NOT_ALIVE : JDWP::ERR_NONE;
375 return thread;
Elliott Hughes436e3722012-02-17 20:01:47 -0800376}
377
Elliott Hughes24437992011-11-30 14:49:33 -0800378static JDWP::JdwpTag BasicTagFromDescriptor(const char* descriptor) {
379 // JDWP deliberately uses the descriptor characters' ASCII values for its enum.
380 // Note that by "basic" we mean that we don't get more specific than JT_OBJECT.
381 return static_cast<JDWP::JdwpTag>(descriptor[0]);
382}
383
Ian Rogers1ff3c982014-08-12 02:30:58 -0700384static JDWP::JdwpTag BasicTagFromClass(mirror::Class* klass)
Mathieu Chartier90443472015-07-16 20:32:27 -0700385 SHARED_REQUIRES(Locks::mutator_lock_) {
Ian Rogers1ff3c982014-08-12 02:30:58 -0700386 std::string temp;
387 const char* descriptor = klass->GetDescriptor(&temp);
388 return BasicTagFromDescriptor(descriptor);
389}
390
Ian Rogers98379392014-02-24 16:53:16 -0800391static JDWP::JdwpTag TagFromClass(const ScopedObjectAccessUnchecked& soa, mirror::Class* c)
Mathieu Chartier90443472015-07-16 20:32:27 -0700392 SHARED_REQUIRES(Locks::mutator_lock_) {
Ian Rogersc0542af2014-09-03 16:16:56 -0700393 CHECK(c != nullptr);
Elliott Hughes24437992011-11-30 14:49:33 -0800394 if (c->IsArrayClass()) {
395 return JDWP::JT_ARRAY;
396 }
Elliott Hughes24437992011-11-30 14:49:33 -0800397 if (c->IsStringClass()) {
398 return JDWP::JT_STRING;
Elliott Hughes24437992011-11-30 14:49:33 -0800399 }
Ian Rogers98379392014-02-24 16:53:16 -0800400 if (c->IsClassClass()) {
401 return JDWP::JT_CLASS_OBJECT;
402 }
403 {
404 mirror::Class* thread_class = soa.Decode<mirror::Class*>(WellKnownClasses::java_lang_Thread);
405 if (thread_class->IsAssignableFrom(c)) {
406 return JDWP::JT_THREAD;
407 }
408 }
409 {
410 mirror::Class* thread_group_class =
411 soa.Decode<mirror::Class*>(WellKnownClasses::java_lang_ThreadGroup);
412 if (thread_group_class->IsAssignableFrom(c)) {
413 return JDWP::JT_THREAD_GROUP;
414 }
415 }
416 {
417 mirror::Class* class_loader_class =
418 soa.Decode<mirror::Class*>(WellKnownClasses::java_lang_ClassLoader);
419 if (class_loader_class->IsAssignableFrom(c)) {
420 return JDWP::JT_CLASS_LOADER;
421 }
422 }
423 return JDWP::JT_OBJECT;
Elliott Hughes24437992011-11-30 14:49:33 -0800424}
425
426/*
427 * Objects declared to hold Object might actually hold a more specific
428 * type. The debugger may take a special interest in these (e.g. it
429 * wants to display the contents of Strings), so we want to return an
430 * appropriate tag.
431 *
432 * Null objects are tagged JT_OBJECT.
433 */
Sebastien Hertz6995c602014-09-09 12:10:13 +0200434JDWP::JdwpTag Dbg::TagFromObject(const ScopedObjectAccessUnchecked& soa, mirror::Object* o) {
Ian Rogersc0542af2014-09-03 16:16:56 -0700435 return (o == nullptr) ? JDWP::JT_OBJECT : TagFromClass(soa, o->GetClass());
Elliott Hughes24437992011-11-30 14:49:33 -0800436}
437
438static bool IsPrimitiveTag(JDWP::JdwpTag tag) {
439 switch (tag) {
440 case JDWP::JT_BOOLEAN:
441 case JDWP::JT_BYTE:
442 case JDWP::JT_CHAR:
443 case JDWP::JT_FLOAT:
444 case JDWP::JT_DOUBLE:
445 case JDWP::JT_INT:
446 case JDWP::JT_LONG:
447 case JDWP::JT_SHORT:
448 case JDWP::JT_VOID:
449 return true;
450 default:
451 return false;
452 }
453}
454
Sebastien Hertzb3b173b2015-02-06 09:16:32 +0100455void Dbg::StartJdwp() {
Elliott Hughesc0f09332012-03-26 13:27:06 -0700456 if (!gJdwpAllowed || !IsJdwpConfigured()) {
Elliott Hughes376a7a02011-10-24 18:35:55 -0700457 // No JDWP for you!
458 return;
459 }
460
Ian Rogers719d1a32014-03-06 12:13:39 -0800461 CHECK(gRegistry == nullptr);
Elliott Hughes475fc232011-10-25 15:00:35 -0700462 gRegistry = new ObjectRegistry;
463
Elliott Hughesd1cc8362011-10-24 16:58:50 -0700464 // Init JDWP if the debugger is enabled. This may connect out to a
465 // debugger, passively listen for a debugger, or block waiting for a
466 // debugger.
Sebastien Hertzb3b173b2015-02-06 09:16:32 +0100467 gJdwpState = JDWP::JdwpState::Create(&gJdwpOptions);
Ian Rogersc0542af2014-09-03 16:16:56 -0700468 if (gJdwpState == nullptr) {
Elliott Hughesf8a2df72011-12-01 12:19:54 -0800469 // We probably failed because some other process has the port already, which means that
470 // if we don't abort the user is likely to think they're talking to us when they're actually
471 // talking to that other process.
Elliott Hughes3d30d9b2011-12-07 17:35:48 -0800472 LOG(FATAL) << "Debugger thread failed to initialize";
Elliott Hughesd1cc8362011-10-24 16:58:50 -0700473 }
474
475 // If a debugger has already attached, send the "welcome" message.
476 // This may cause us to suspend all threads.
Elliott Hughes376a7a02011-10-24 18:35:55 -0700477 if (gJdwpState->IsActive()) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700478 ScopedObjectAccess soa(Thread::Current());
Sebastien Hertz7d955652014-10-22 10:57:10 +0200479 gJdwpState->PostVMStart();
Elliott Hughesd1cc8362011-10-24 16:58:50 -0700480 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700481}
482
Elliott Hughesd1cc8362011-10-24 16:58:50 -0700483void Dbg::StopJdwp() {
Sebastien Hertzc6345ef2014-08-18 19:26:39 +0200484 // Post VM_DEATH event before the JDWP connection is closed (either by the JDWP thread or the
485 // destruction of gJdwpState).
486 if (gJdwpState != nullptr && gJdwpState->IsActive()) {
487 gJdwpState->PostVMDeath();
488 }
Sebastien Hertz0376e6b2014-02-06 18:12:59 +0100489 // Prevent the JDWP thread from processing JDWP incoming packets after we close the connection.
Sebastien Hertz4e5b2082015-03-24 19:03:40 +0100490 Dispose();
Elliott Hughes376a7a02011-10-24 18:35:55 -0700491 delete gJdwpState;
Ian Rogers719d1a32014-03-06 12:13:39 -0800492 gJdwpState = nullptr;
Elliott Hughes475fc232011-10-25 15:00:35 -0700493 delete gRegistry;
Ian Rogers719d1a32014-03-06 12:13:39 -0800494 gRegistry = nullptr;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700495}
496
Elliott Hughes767a1472011-10-26 18:49:02 -0700497void Dbg::GcDidFinish() {
498 if (gDdmHpifWhen != HPIF_WHEN_NEVER) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700499 ScopedObjectAccess soa(Thread::Current());
Brian Carlstrom4d466a82014-05-08 19:05:29 -0700500 VLOG(jdwp) << "Sending heap info to DDM";
Elliott Hughes7162ad92011-10-27 14:08:42 -0700501 DdmSendHeapInfo(gDdmHpifWhen);
Elliott Hughes767a1472011-10-26 18:49:02 -0700502 }
503 if (gDdmHpsgWhen != HPSG_WHEN_NEVER) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700504 ScopedObjectAccess soa(Thread::Current());
Brian Carlstrom4d466a82014-05-08 19:05:29 -0700505 VLOG(jdwp) << "Dumping heap to DDM";
Elliott Hughes6a5bd492011-10-28 14:33:57 -0700506 DdmSendHeapSegments(false);
Elliott Hughes767a1472011-10-26 18:49:02 -0700507 }
508 if (gDdmNhsgWhen != HPSG_WHEN_NEVER) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700509 ScopedObjectAccess soa(Thread::Current());
Brian Carlstrom4d466a82014-05-08 19:05:29 -0700510 VLOG(jdwp) << "Dumping native heap to DDM";
Elliott Hughes6a5bd492011-10-28 14:33:57 -0700511 DdmSendHeapSegments(true);
Elliott Hughes767a1472011-10-26 18:49:02 -0700512 }
513}
514
Elliott Hughes4ffd3132011-10-24 12:06:42 -0700515void Dbg::SetJdwpAllowed(bool allowed) {
516 gJdwpAllowed = allowed;
517}
518
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700519DebugInvokeReq* Dbg::GetInvokeReq() {
Elliott Hughes475fc232011-10-25 15:00:35 -0700520 return Thread::Current()->GetInvokeReq();
521}
522
523Thread* Dbg::GetDebugThread() {
Ian Rogersc0542af2014-09-03 16:16:56 -0700524 return (gJdwpState != nullptr) ? gJdwpState->GetDebugThread() : nullptr;
Elliott Hughes475fc232011-10-25 15:00:35 -0700525}
526
527void Dbg::ClearWaitForEventThread() {
Sebastien Hertz2bf93f42015-01-09 18:44:05 +0100528 gJdwpState->ReleaseJdwpTokenForEvent();
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700529}
530
531void Dbg::Connected() {
Elliott Hughes3bb81562011-10-21 18:52:59 -0700532 CHECK(!gDebuggerConnected);
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -0800533 VLOG(jdwp) << "JDWP has attached";
Elliott Hughes3bb81562011-10-21 18:52:59 -0700534 gDebuggerConnected = true;
Elliott Hughes86964332012-02-15 19:37:42 -0800535 gDisposed = false;
536}
537
Sebastien Hertzf3928792014-11-17 19:00:37 +0100538bool Dbg::RequiresDeoptimization() {
539 // We don't need deoptimization if everything runs with interpreter after
540 // enabling -Xint mode.
541 return !Runtime::Current()->GetInstrumentation()->IsForcedInterpretOnly();
542}
543
Elliott Hughesa2155262011-11-16 16:26:58 -0800544void Dbg::GoActive() {
545 // Enable all debugging features, including scans for breakpoints.
546 // This is a no-op if we're already active.
547 // Only called from the JDWP handler thread.
Daniel Mihalyieb076692014-08-22 17:33:31 +0200548 if (IsDebuggerActive()) {
Elliott Hughesa2155262011-11-16 16:26:58 -0800549 return;
550 }
551
Elliott Hughesc0f09332012-03-26 13:27:06 -0700552 {
553 // TODO: dalvik only warned if there were breakpoints left over. clear in Dbg::Disconnected?
Sebastien Hertzed2be172014-08-19 15:33:43 +0200554 ReaderMutexLock mu(Thread::Current(), *Locks::breakpoint_lock_);
Elliott Hughesc0f09332012-03-26 13:27:06 -0700555 CHECK_EQ(gBreakpoints.size(), 0U);
556 }
Elliott Hughesa2155262011-11-16 16:26:58 -0800557
Sebastien Hertz138dbfc2013-12-04 18:15:25 +0100558 {
Brian Carlstrom306db812014-09-05 13:01:41 -0700559 MutexLock mu(Thread::Current(), *Locks::deoptimization_lock_);
Sebastien Hertz4d25df32014-03-21 17:44:46 +0100560 CHECK_EQ(deoptimization_requests_.size(), 0U);
561 CHECK_EQ(full_deoptimization_event_count_, 0U);
Sebastien Hertz42cd43f2014-05-13 14:15:41 +0200562 CHECK_EQ(dex_pc_change_event_ref_count_, 0U);
563 CHECK_EQ(method_enter_event_ref_count_, 0U);
564 CHECK_EQ(method_exit_event_ref_count_, 0U);
565 CHECK_EQ(field_read_event_ref_count_, 0U);
566 CHECK_EQ(field_write_event_ref_count_, 0U);
567 CHECK_EQ(exception_catch_event_ref_count_, 0U);
Sebastien Hertz138dbfc2013-12-04 18:15:25 +0100568 }
569
Ian Rogers62d6c772013-02-27 08:32:07 -0800570 Runtime* runtime = Runtime::Current();
Mathieu Chartierbf9fc582015-03-13 17:21:25 -0700571 runtime->GetThreadList()->SuspendAll(__FUNCTION__);
Ian Rogers62d6c772013-02-27 08:32:07 -0800572 Thread* self = Thread::Current();
573 ThreadState old_state = self->SetStateUnsafe(kRunnable);
574 CHECK_NE(old_state, kRunnable);
Sebastien Hertzf3928792014-11-17 19:00:37 +0100575 if (RequiresDeoptimization()) {
576 runtime->GetInstrumentation()->EnableDeoptimization();
577 }
Sebastien Hertz42cd43f2014-05-13 14:15:41 +0200578 instrumentation_events_ = 0;
Elliott Hughesa2155262011-11-16 16:26:58 -0800579 gDebuggerActive = true;
Ian Rogers62d6c772013-02-27 08:32:07 -0800580 CHECK_EQ(self->SetStateUnsafe(old_state), kRunnable);
581 runtime->GetThreadList()->ResumeAll();
582
583 LOG(INFO) << "Debugger is active";
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700584}
585
586void Dbg::Disconnected() {
Elliott Hughes234ab152011-10-26 14:02:26 -0700587 CHECK(gDebuggerConnected);
588
Elliott Hughesc0f09332012-03-26 13:27:06 -0700589 LOG(INFO) << "Debugger is no longer active";
Elliott Hughes234ab152011-10-26 14:02:26 -0700590
Ian Rogers62d6c772013-02-27 08:32:07 -0800591 // Suspend all threads and exclusively acquire the mutator lock. Set the state of the thread
592 // to kRunnable to avoid scoped object access transitions. Remove the debugger as a listener
593 // and clear the object registry.
594 Runtime* runtime = Runtime::Current();
Mathieu Chartierbf9fc582015-03-13 17:21:25 -0700595 runtime->GetThreadList()->SuspendAll(__FUNCTION__);
Ian Rogers62d6c772013-02-27 08:32:07 -0800596 Thread* self = Thread::Current();
597 ThreadState old_state = self->SetStateUnsafe(kRunnable);
Sebastien Hertzaaea7342014-02-25 15:10:04 +0100598
599 // Debugger may not be active at this point.
Daniel Mihalyieb076692014-08-22 17:33:31 +0200600 if (IsDebuggerActive()) {
Sebastien Hertzaaea7342014-02-25 15:10:04 +0100601 {
602 // Since we're going to disable deoptimization, we clear the deoptimization requests queue.
603 // This prevents us from having any pending deoptimization request when the debugger attaches
604 // to us again while no event has been requested yet.
Brian Carlstrom306db812014-09-05 13:01:41 -0700605 MutexLock mu(Thread::Current(), *Locks::deoptimization_lock_);
Sebastien Hertz4d25df32014-03-21 17:44:46 +0100606 deoptimization_requests_.clear();
607 full_deoptimization_event_count_ = 0U;
Sebastien Hertzaaea7342014-02-25 15:10:04 +0100608 }
Sebastien Hertz42cd43f2014-05-13 14:15:41 +0200609 if (instrumentation_events_ != 0) {
610 runtime->GetInstrumentation()->RemoveListener(&gDebugInstrumentationListener,
611 instrumentation_events_);
612 instrumentation_events_ = 0;
613 }
Sebastien Hertzf3928792014-11-17 19:00:37 +0100614 if (RequiresDeoptimization()) {
Sebastien Hertz0462c4c2015-04-01 16:34:17 +0200615 runtime->GetInstrumentation()->DisableDeoptimization(kDbgInstrumentationKey);
Sebastien Hertzf3928792014-11-17 19:00:37 +0100616 }
Sebastien Hertzaaea7342014-02-25 15:10:04 +0100617 gDebuggerActive = false;
Sebastien Hertz138dbfc2013-12-04 18:15:25 +0100618 }
Ian Rogers62d6c772013-02-27 08:32:07 -0800619 CHECK_EQ(self->SetStateUnsafe(old_state), kRunnable);
620 runtime->GetThreadList()->ResumeAll();
Sebastien Hertz55f65342015-01-13 22:48:34 +0100621
622 {
623 ScopedObjectAccess soa(self);
624 gRegistry->Clear();
625 }
626
627 gDebuggerConnected = false;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700628}
629
Sebastien Hertzb3b173b2015-02-06 09:16:32 +0100630void Dbg::ConfigureJdwp(const JDWP::JdwpOptions& jdwp_options) {
631 CHECK_NE(jdwp_options.transport, JDWP::kJdwpTransportUnknown);
632 gJdwpOptions = jdwp_options;
633 gJdwpConfigured = true;
634}
635
Elliott Hughesc0f09332012-03-26 13:27:06 -0700636bool Dbg::IsJdwpConfigured() {
Elliott Hughes3bb81562011-10-21 18:52:59 -0700637 return gJdwpConfigured;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700638}
639
640int64_t Dbg::LastDebuggerActivity() {
Elliott Hughesca951522011-12-05 12:01:32 -0800641 return gJdwpState->LastDebuggerActivity();
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700642}
643
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700644void Dbg::UndoDebuggerSuspensions() {
Elliott Hughes234ab152011-10-26 14:02:26 -0700645 Runtime::Current()->GetThreadList()->UndoDebuggerSuspensions();
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700646}
647
Elliott Hughes88d63092013-01-09 09:55:54 -0800648std::string Dbg::GetClassName(JDWP::RefTypeId class_id) {
Ian Rogersc0542af2014-09-03 16:16:56 -0700649 JDWP::JdwpError error;
650 mirror::Object* o = gRegistry->Get<mirror::Object*>(class_id, &error);
651 if (o == nullptr) {
652 if (error == JDWP::ERR_NONE) {
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700653 return "null";
Ian Rogersc0542af2014-09-03 16:16:56 -0700654 } else {
655 return StringPrintf("invalid object %p", reinterpret_cast<void*>(class_id));
656 }
Elliott Hughes436e3722012-02-17 20:01:47 -0800657 }
658 if (!o->IsClass()) {
Brian Carlstrom7934ac22013-07-26 10:54:15 -0700659 return StringPrintf("non-class %p", o); // This is only used for debugging output anyway.
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -0800660 }
Sebastien Hertz6995c602014-09-09 12:10:13 +0200661 return GetClassName(o->AsClass());
662}
663
664std::string Dbg::GetClassName(mirror::Class* klass) {
Sebastien Hertza9aa0ff2014-09-19 12:07:51 +0200665 if (klass == nullptr) {
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700666 return "null";
Sebastien Hertza9aa0ff2014-09-19 12:07:51 +0200667 }
Ian Rogers1ff3c982014-08-12 02:30:58 -0700668 std::string temp;
Sebastien Hertz6995c602014-09-09 12:10:13 +0200669 return DescriptorToName(klass->GetDescriptor(&temp));
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700670}
671
Ian Rogersc0542af2014-09-03 16:16:56 -0700672JDWP::JdwpError Dbg::GetClassObject(JDWP::RefTypeId id, JDWP::ObjectId* class_object_id) {
Elliott Hughes436e3722012-02-17 20:01:47 -0800673 JDWP::JdwpError status;
Ian Rogersc0542af2014-09-03 16:16:56 -0700674 mirror::Class* c = DecodeClass(id, &status);
675 if (c == nullptr) {
676 *class_object_id = 0;
Elliott Hughes436e3722012-02-17 20:01:47 -0800677 return status;
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -0800678 }
Ian Rogersc0542af2014-09-03 16:16:56 -0700679 *class_object_id = gRegistry->Add(c);
Elliott Hughes436e3722012-02-17 20:01:47 -0800680 return JDWP::ERR_NONE;
Elliott Hughes86964332012-02-15 19:37:42 -0800681}
682
Ian Rogersc0542af2014-09-03 16:16:56 -0700683JDWP::JdwpError Dbg::GetSuperclass(JDWP::RefTypeId id, JDWP::RefTypeId* superclass_id) {
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -0800684 JDWP::JdwpError status;
Ian Rogersc0542af2014-09-03 16:16:56 -0700685 mirror::Class* c = DecodeClass(id, &status);
686 if (c == nullptr) {
687 *superclass_id = 0;
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -0800688 return status;
689 }
690 if (c->IsInterface()) {
691 // http://code.google.com/p/android/issues/detail?id=20856
Ian Rogersc0542af2014-09-03 16:16:56 -0700692 *superclass_id = 0;
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -0800693 } else {
Ian Rogersc0542af2014-09-03 16:16:56 -0700694 *superclass_id = gRegistry->Add(c->GetSuperClass());
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -0800695 }
696 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700697}
698
Elliott Hughes436e3722012-02-17 20:01:47 -0800699JDWP::JdwpError Dbg::GetClassLoader(JDWP::RefTypeId id, JDWP::ExpandBuf* pReply) {
Ian Rogersc0542af2014-09-03 16:16:56 -0700700 JDWP::JdwpError error;
701 mirror::Object* o = gRegistry->Get<mirror::Object*>(id, &error);
702 if (o == nullptr) {
Elliott Hughes436e3722012-02-17 20:01:47 -0800703 return JDWP::ERR_INVALID_OBJECT;
704 }
705 expandBufAddObjectId(pReply, gRegistry->Add(o->GetClass()->GetClassLoader()));
706 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700707}
708
Elliott Hughes436e3722012-02-17 20:01:47 -0800709JDWP::JdwpError Dbg::GetModifiers(JDWP::RefTypeId id, JDWP::ExpandBuf* pReply) {
Ian Rogersc0542af2014-09-03 16:16:56 -0700710 JDWP::JdwpError error;
711 mirror::Class* c = DecodeClass(id, &error);
712 if (c == nullptr) {
713 return error;
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -0800714 }
Elliott Hughes436e3722012-02-17 20:01:47 -0800715
716 uint32_t access_flags = c->GetAccessFlags() & kAccJavaFlagsMask;
717
Yevgeny Roubande34eea2014-02-15 01:06:03 +0700718 // Set ACC_SUPER. Dex files don't contain this flag but only classes are supposed to have it set,
719 // not interfaces.
Elliott Hughes436e3722012-02-17 20:01:47 -0800720 // Class.getModifiers doesn't return it, but JDWP does, so we set it here.
Yevgeny Roubande34eea2014-02-15 01:06:03 +0700721 if ((access_flags & kAccInterface) == 0) {
722 access_flags |= kAccSuper;
723 }
Elliott Hughes436e3722012-02-17 20:01:47 -0800724
725 expandBufAdd4BE(pReply, access_flags);
726
727 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700728}
729
Ian Rogersc0542af2014-09-03 16:16:56 -0700730JDWP::JdwpError Dbg::GetMonitorInfo(JDWP::ObjectId object_id, JDWP::ExpandBuf* reply) {
731 JDWP::JdwpError error;
732 mirror::Object* o = gRegistry->Get<mirror::Object*>(object_id, &error);
733 if (o == nullptr) {
Elliott Hughesf327e072013-01-09 16:01:26 -0800734 return JDWP::ERR_INVALID_OBJECT;
735 }
736
737 // Ensure all threads are suspended while we read objects' lock words.
738 Thread* self = Thread::Current();
Sebastien Hertz54263242014-03-19 18:16:50 +0100739 CHECK_EQ(self->GetState(), kRunnable);
740 self->TransitionFromRunnableToSuspended(kSuspended);
Mathieu Chartierbf9fc582015-03-13 17:21:25 -0700741 Runtime::Current()->GetThreadList()->SuspendAll(__FUNCTION__);
Elliott Hughesf327e072013-01-09 16:01:26 -0800742
743 MonitorInfo monitor_info(o);
744
Sebastien Hertz54263242014-03-19 18:16:50 +0100745 Runtime::Current()->GetThreadList()->ResumeAll();
746 self->TransitionFromSuspendedToRunnable();
Elliott Hughesf327e072013-01-09 16:01:26 -0800747
Ian Rogersc0542af2014-09-03 16:16:56 -0700748 if (monitor_info.owner_ != nullptr) {
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700749 expandBufAddObjectId(reply, gRegistry->Add(monitor_info.owner_->GetPeer()));
Elliott Hughesf327e072013-01-09 16:01:26 -0800750 } else {
Ian Rogersc0542af2014-09-03 16:16:56 -0700751 expandBufAddObjectId(reply, gRegistry->Add(nullptr));
Elliott Hughesf327e072013-01-09 16:01:26 -0800752 }
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700753 expandBufAdd4BE(reply, monitor_info.entry_count_);
754 expandBufAdd4BE(reply, monitor_info.waiters_.size());
755 for (size_t i = 0; i < monitor_info.waiters_.size(); ++i) {
756 expandBufAddObjectId(reply, gRegistry->Add(monitor_info.waiters_[i]->GetPeer()));
Elliott Hughesf327e072013-01-09 16:01:26 -0800757 }
758 return JDWP::ERR_NONE;
759}
760
Elliott Hughes734b8c62013-01-11 15:32:45 -0800761JDWP::JdwpError Dbg::GetOwnedMonitors(JDWP::ObjectId thread_id,
Ian Rogersc0542af2014-09-03 16:16:56 -0700762 std::vector<JDWP::ObjectId>* monitors,
763 std::vector<uint32_t>* stack_depths) {
Elliott Hughes4993bbc2013-01-10 15:41:25 -0800764 struct OwnedMonitorVisitor : public StackVisitor {
Hiroshi Yamauchib5a9e3d2014-06-09 12:11:20 -0700765 OwnedMonitorVisitor(Thread* thread, Context* context,
Hiroshi Yamauchicc8c5c52014-06-13 15:08:05 -0700766 std::vector<JDWP::ObjectId>* monitor_vector,
Hiroshi Yamauchib5a9e3d2014-06-09 12:11:20 -0700767 std::vector<uint32_t>* stack_depth_vector)
Mathieu Chartier90443472015-07-16 20:32:27 -0700768 SHARED_REQUIRES(Locks::mutator_lock_)
Nicolas Geoffray8e5bd182015-05-06 11:34:34 +0100769 : StackVisitor(thread, context, StackVisitor::StackWalkKind::kIncludeInlinedFrames),
770 current_stack_depth(0),
771 monitors(monitor_vector),
772 stack_depths(stack_depth_vector) {}
Elliott Hughes4993bbc2013-01-10 15:41:25 -0800773
774 // TODO: Enable annotalysis. We know lock is held in constructor, but abstraction confuses
775 // annotalysis.
776 bool VisitFrame() NO_THREAD_SAFETY_ANALYSIS {
777 if (!GetMethod()->IsRuntimeMethod()) {
778 Monitor::VisitLocks(this, AppendOwnedMonitors, this);
Elliott Hughes734b8c62013-01-11 15:32:45 -0800779 ++current_stack_depth;
Elliott Hughes4993bbc2013-01-10 15:41:25 -0800780 }
781 return true;
782 }
783
Hiroshi Yamauchicc8c5c52014-06-13 15:08:05 -0700784 static void AppendOwnedMonitors(mirror::Object* owned_monitor, void* arg)
Mathieu Chartier90443472015-07-16 20:32:27 -0700785 SHARED_REQUIRES(Locks::mutator_lock_) {
Ian Rogers7a22fa62013-01-23 12:16:16 -0800786 OwnedMonitorVisitor* visitor = reinterpret_cast<OwnedMonitorVisitor*>(arg);
Hiroshi Yamauchicc8c5c52014-06-13 15:08:05 -0700787 visitor->monitors->push_back(gRegistry->Add(owned_monitor));
Hiroshi Yamauchib5a9e3d2014-06-09 12:11:20 -0700788 visitor->stack_depths->push_back(visitor->current_stack_depth);
Elliott Hughes4993bbc2013-01-10 15:41:25 -0800789 }
790
Elliott Hughes734b8c62013-01-11 15:32:45 -0800791 size_t current_stack_depth;
Ian Rogersc0542af2014-09-03 16:16:56 -0700792 std::vector<JDWP::ObjectId>* const monitors;
793 std::vector<uint32_t>* const stack_depths;
Elliott Hughes4993bbc2013-01-10 15:41:25 -0800794 };
Elliott Hughes4993bbc2013-01-10 15:41:25 -0800795
Hiroshi Yamauchib5a9e3d2014-06-09 12:11:20 -0700796 ScopedObjectAccessUnchecked soa(Thread::Current());
Sebastien Hertz69206392015-04-07 15:54:25 +0200797 JDWP::JdwpError error;
798 Thread* thread = DecodeThread(soa, thread_id, &error);
799 if (thread == nullptr) {
800 return error;
801 }
802 if (!IsSuspendedForDebugger(soa, thread)) {
803 return JDWP::ERR_THREAD_NOT_SUSPENDED;
Hiroshi Yamauchib5a9e3d2014-06-09 12:11:20 -0700804 }
Hiroshi Yamauchicc8c5c52014-06-13 15:08:05 -0700805 std::unique_ptr<Context> context(Context::Create());
Ian Rogersc0542af2014-09-03 16:16:56 -0700806 OwnedMonitorVisitor visitor(thread, context.get(), monitors, stack_depths);
Hiroshi Yamauchicc8c5c52014-06-13 15:08:05 -0700807 visitor.WalkStack();
Elliott Hughes4993bbc2013-01-10 15:41:25 -0800808 return JDWP::ERR_NONE;
809}
810
Sebastien Hertz52d131d2014-03-13 16:17:40 +0100811JDWP::JdwpError Dbg::GetContendedMonitor(JDWP::ObjectId thread_id,
Ian Rogersc0542af2014-09-03 16:16:56 -0700812 JDWP::ObjectId* contended_monitor) {
Elliott Hughesf9501702013-01-11 11:22:27 -0800813 ScopedObjectAccessUnchecked soa(Thread::Current());
Ian Rogersc0542af2014-09-03 16:16:56 -0700814 *contended_monitor = 0;
Sebastien Hertz69206392015-04-07 15:54:25 +0200815 JDWP::JdwpError error;
816 Thread* thread = DecodeThread(soa, thread_id, &error);
817 if (thread == nullptr) {
818 return error;
Elliott Hughesf9501702013-01-11 11:22:27 -0800819 }
Sebastien Hertz69206392015-04-07 15:54:25 +0200820 if (!IsSuspendedForDebugger(soa, thread)) {
821 return JDWP::ERR_THREAD_NOT_SUSPENDED;
822 }
823 mirror::Object* contended_monitor_obj = Monitor::GetContendedMonitor(thread);
Hiroshi Yamauchib5a9e3d2014-06-09 12:11:20 -0700824 // Add() requires the thread_list_lock_ not held to avoid the lock
825 // level violation.
Ian Rogersc0542af2014-09-03 16:16:56 -0700826 *contended_monitor = gRegistry->Add(contended_monitor_obj);
Elliott Hughesf9501702013-01-11 11:22:27 -0800827 return JDWP::ERR_NONE;
828}
829
Elliott Hughesec0f83d2013-01-15 16:54:08 -0800830JDWP::JdwpError Dbg::GetInstanceCounts(const std::vector<JDWP::RefTypeId>& class_ids,
Ian Rogersc0542af2014-09-03 16:16:56 -0700831 std::vector<uint64_t>* counts) {
Mathieu Chartier412c7fc2014-02-07 12:18:39 -0800832 gc::Heap* heap = Runtime::Current()->GetHeap();
833 heap->CollectGarbage(false);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800834 std::vector<mirror::Class*> classes;
Ian Rogersc0542af2014-09-03 16:16:56 -0700835 counts->clear();
Elliott Hughesec0f83d2013-01-15 16:54:08 -0800836 for (size_t i = 0; i < class_ids.size(); ++i) {
Ian Rogersc0542af2014-09-03 16:16:56 -0700837 JDWP::JdwpError error;
838 mirror::Class* c = DecodeClass(class_ids[i], &error);
839 if (c == nullptr) {
840 return error;
Elliott Hughesec0f83d2013-01-15 16:54:08 -0800841 }
842 classes.push_back(c);
Ian Rogersc0542af2014-09-03 16:16:56 -0700843 counts->push_back(0);
Elliott Hughesec0f83d2013-01-15 16:54:08 -0800844 }
Ian Rogersc0542af2014-09-03 16:16:56 -0700845 heap->CountInstances(classes, false, &(*counts)[0]);
Elliott Hughesec0f83d2013-01-15 16:54:08 -0800846 return JDWP::ERR_NONE;
847}
848
Ian Rogersc0542af2014-09-03 16:16:56 -0700849JDWP::JdwpError Dbg::GetInstances(JDWP::RefTypeId class_id, int32_t max_count,
850 std::vector<JDWP::ObjectId>* instances) {
Mathieu Chartier412c7fc2014-02-07 12:18:39 -0800851 gc::Heap* heap = Runtime::Current()->GetHeap();
852 // We only want reachable instances, so do a GC.
853 heap->CollectGarbage(false);
Ian Rogersc0542af2014-09-03 16:16:56 -0700854 JDWP::JdwpError error;
855 mirror::Class* c = DecodeClass(class_id, &error);
Mathieu Chartier412c7fc2014-02-07 12:18:39 -0800856 if (c == nullptr) {
Ian Rogersc0542af2014-09-03 16:16:56 -0700857 return error;
Elliott Hughes3b78c942013-01-15 17:35:41 -0800858 }
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800859 std::vector<mirror::Object*> raw_instances;
Elliott Hughes3b78c942013-01-15 17:35:41 -0800860 Runtime::Current()->GetHeap()->GetInstances(c, max_count, raw_instances);
861 for (size_t i = 0; i < raw_instances.size(); ++i) {
Ian Rogersc0542af2014-09-03 16:16:56 -0700862 instances->push_back(gRegistry->Add(raw_instances[i]));
Elliott Hughes3b78c942013-01-15 17:35:41 -0800863 }
864 return JDWP::ERR_NONE;
865}
866
Elliott Hughes0cbaff52013-01-16 15:28:01 -0800867JDWP::JdwpError Dbg::GetReferringObjects(JDWP::ObjectId object_id, int32_t max_count,
Ian Rogersc0542af2014-09-03 16:16:56 -0700868 std::vector<JDWP::ObjectId>* referring_objects) {
Mathieu Chartier412c7fc2014-02-07 12:18:39 -0800869 gc::Heap* heap = Runtime::Current()->GetHeap();
870 heap->CollectGarbage(false);
Ian Rogersc0542af2014-09-03 16:16:56 -0700871 JDWP::JdwpError error;
872 mirror::Object* o = gRegistry->Get<mirror::Object*>(object_id, &error);
873 if (o == nullptr) {
Elliott Hughes0cbaff52013-01-16 15:28:01 -0800874 return JDWP::ERR_INVALID_OBJECT;
875 }
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800876 std::vector<mirror::Object*> raw_instances;
Mathieu Chartier412c7fc2014-02-07 12:18:39 -0800877 heap->GetReferringObjects(o, max_count, raw_instances);
Elliott Hughes0cbaff52013-01-16 15:28:01 -0800878 for (size_t i = 0; i < raw_instances.size(); ++i) {
Ian Rogersc0542af2014-09-03 16:16:56 -0700879 referring_objects->push_back(gRegistry->Add(raw_instances[i]));
Elliott Hughes0cbaff52013-01-16 15:28:01 -0800880 }
881 return JDWP::ERR_NONE;
882}
883
Ian Rogersc0542af2014-09-03 16:16:56 -0700884JDWP::JdwpError Dbg::DisableCollection(JDWP::ObjectId object_id) {
885 JDWP::JdwpError error;
886 mirror::Object* o = gRegistry->Get<mirror::Object*>(object_id, &error);
887 if (o == nullptr) {
Sebastien Hertze96060a2013-12-11 12:06:28 +0100888 return JDWP::ERR_INVALID_OBJECT;
889 }
Elliott Hughes64f574f2013-02-20 14:57:12 -0800890 gRegistry->DisableCollection(object_id);
891 return JDWP::ERR_NONE;
892}
893
Ian Rogersc0542af2014-09-03 16:16:56 -0700894JDWP::JdwpError Dbg::EnableCollection(JDWP::ObjectId object_id) {
895 JDWP::JdwpError error;
896 mirror::Object* o = gRegistry->Get<mirror::Object*>(object_id, &error);
Sebastien Hertze96060a2013-12-11 12:06:28 +0100897 // Unlike DisableCollection, JDWP specs do not state an invalid object causes an error. The RI
898 // also ignores these cases and never return an error. However it's not obvious why this command
899 // should behave differently from DisableCollection and IsCollected commands. So let's be more
900 // strict and return an error if this happens.
Ian Rogersc0542af2014-09-03 16:16:56 -0700901 if (o == nullptr) {
Sebastien Hertze96060a2013-12-11 12:06:28 +0100902 return JDWP::ERR_INVALID_OBJECT;
903 }
Elliott Hughes64f574f2013-02-20 14:57:12 -0800904 gRegistry->EnableCollection(object_id);
905 return JDWP::ERR_NONE;
906}
907
Ian Rogersc0542af2014-09-03 16:16:56 -0700908JDWP::JdwpError Dbg::IsCollected(JDWP::ObjectId object_id, bool* is_collected) {
909 *is_collected = true;
Sebastien Hertz65637eb2014-01-10 17:40:02 +0100910 if (object_id == 0) {
911 // Null object id is invalid.
Sebastien Hertze96060a2013-12-11 12:06:28 +0100912 return JDWP::ERR_INVALID_OBJECT;
913 }
Sebastien Hertz65637eb2014-01-10 17:40:02 +0100914 // JDWP specs state an INVALID_OBJECT error is returned if the object ID is not valid. However
915 // the RI seems to ignore this and assume object has been collected.
Ian Rogersc0542af2014-09-03 16:16:56 -0700916 JDWP::JdwpError error;
917 mirror::Object* o = gRegistry->Get<mirror::Object*>(object_id, &error);
918 if (o != nullptr) {
919 *is_collected = gRegistry->IsCollected(object_id);
Sebastien Hertz65637eb2014-01-10 17:40:02 +0100920 }
Elliott Hughes64f574f2013-02-20 14:57:12 -0800921 return JDWP::ERR_NONE;
922}
923
Ian Rogersc0542af2014-09-03 16:16:56 -0700924void Dbg::DisposeObject(JDWP::ObjectId object_id, uint32_t reference_count) {
Elliott Hughes64f574f2013-02-20 14:57:12 -0800925 gRegistry->DisposeObject(object_id, reference_count);
926}
927
Sebastien Hertz6995c602014-09-09 12:10:13 +0200928JDWP::JdwpTypeTag Dbg::GetTypeTag(mirror::Class* klass) {
Sebastien Hertz4d8fd492014-03-28 16:29:41 +0100929 DCHECK(klass != nullptr);
930 if (klass->IsArrayClass()) {
931 return JDWP::TT_ARRAY;
932 } else if (klass->IsInterface()) {
933 return JDWP::TT_INTERFACE;
934 } else {
935 return JDWP::TT_CLASS;
936 }
937}
938
Elliott Hughes88d63092013-01-09 09:55:54 -0800939JDWP::JdwpError Dbg::GetReflectedType(JDWP::RefTypeId class_id, JDWP::ExpandBuf* pReply) {
Ian Rogersc0542af2014-09-03 16:16:56 -0700940 JDWP::JdwpError error;
941 mirror::Class* c = DecodeClass(class_id, &error);
942 if (c == nullptr) {
943 return error;
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -0800944 }
Elliott Hughes436e3722012-02-17 20:01:47 -0800945
Sebastien Hertz4d8fd492014-03-28 16:29:41 +0100946 JDWP::JdwpTypeTag type_tag = GetTypeTag(c);
947 expandBufAdd1(pReply, type_tag);
Elliott Hughes88d63092013-01-09 09:55:54 -0800948 expandBufAddRefTypeId(pReply, class_id);
Elliott Hughes436e3722012-02-17 20:01:47 -0800949 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700950}
951
Mathieu Chartiere0671ce2015-07-28 17:23:28 -0700952// Get the complete list of reference classes (i.e. all classes except
953// the primitive types).
954// Returns a newly-allocated buffer full of RefTypeId values.
955class ClassListCreator : public ClassVisitor {
956 public:
957 explicit ClassListCreator(std::vector<JDWP::RefTypeId>* classes) : classes_(classes) {}
958
959 bool Visit(mirror::Class* c) OVERRIDE SHARED_REQUIRES(Locks::mutator_lock_) {
960 if (!c->IsPrimitive()) {
961 classes_->push_back(Dbg::GetObjectRegistry()->AddRefType(c));
962 }
963 return true;
964 }
965
966 private:
967 std::vector<JDWP::RefTypeId>* const classes_;
968};
969
Ian Rogersc0542af2014-09-03 16:16:56 -0700970void Dbg::GetClassList(std::vector<JDWP::RefTypeId>* classes) {
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -0800971 ClassListCreator clc(classes);
Mathieu Chartiere0671ce2015-07-28 17:23:28 -0700972 Runtime::Current()->GetClassLinker()->VisitClassesWithoutClassesLock(&clc);
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700973}
974
Ian Rogers1ff3c982014-08-12 02:30:58 -0700975JDWP::JdwpError Dbg::GetClassInfo(JDWP::RefTypeId class_id, JDWP::JdwpTypeTag* pTypeTag,
976 uint32_t* pStatus, std::string* pDescriptor) {
Ian Rogersc0542af2014-09-03 16:16:56 -0700977 JDWP::JdwpError error;
978 mirror::Class* c = DecodeClass(class_id, &error);
979 if (c == nullptr) {
980 return error;
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -0800981 }
982
Elliott Hughesa2155262011-11-16 16:26:58 -0800983 if (c->IsArrayClass()) {
984 *pStatus = JDWP::CS_VERIFIED | JDWP::CS_PREPARED;
985 *pTypeTag = JDWP::TT_ARRAY;
986 } else {
987 if (c->IsErroneous()) {
988 *pStatus = JDWP::CS_ERROR;
989 } else {
990 *pStatus = JDWP::CS_VERIFIED | JDWP::CS_PREPARED | JDWP::CS_INITIALIZED;
991 }
992 *pTypeTag = c->IsInterface() ? JDWP::TT_INTERFACE : JDWP::TT_CLASS;
993 }
994
Ian Rogersc0542af2014-09-03 16:16:56 -0700995 if (pDescriptor != nullptr) {
Ian Rogers1ff3c982014-08-12 02:30:58 -0700996 std::string temp;
997 *pDescriptor = c->GetDescriptor(&temp);
Elliott Hughesa2155262011-11-16 16:26:58 -0800998 }
Elliott Hughes436e3722012-02-17 20:01:47 -0800999 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001000}
1001
Ian Rogersc0542af2014-09-03 16:16:56 -07001002void Dbg::FindLoadedClassBySignature(const char* descriptor, std::vector<JDWP::RefTypeId>* ids) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001003 std::vector<mirror::Class*> classes;
Igor Murashkinbc1d78d2015-07-30 16:39:45 -07001004 Runtime::Current()->GetClassLinker()->LookupClasses(descriptor, outof(classes));
Ian Rogersc0542af2014-09-03 16:16:56 -07001005 ids->clear();
Elliott Hughes6fa602d2011-12-02 17:54:25 -08001006 for (size_t i = 0; i < classes.size(); ++i) {
Ian Rogersc0542af2014-09-03 16:16:56 -07001007 ids->push_back(gRegistry->Add(classes[i]));
Elliott Hughes6fa602d2011-12-02 17:54:25 -08001008 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001009}
1010
Ian Rogersc0542af2014-09-03 16:16:56 -07001011JDWP::JdwpError Dbg::GetReferenceType(JDWP::ObjectId object_id, JDWP::ExpandBuf* pReply) {
1012 JDWP::JdwpError error;
1013 mirror::Object* o = gRegistry->Get<mirror::Object*>(object_id, &error);
1014 if (o == nullptr) {
Elliott Hughes2435a572012-02-17 16:07:41 -08001015 return JDWP::ERR_INVALID_OBJECT;
Elliott Hughes499c5132011-11-17 14:55:11 -08001016 }
Elliott Hughes2435a572012-02-17 16:07:41 -08001017
Sebastien Hertz4d8fd492014-03-28 16:29:41 +01001018 JDWP::JdwpTypeTag type_tag = GetTypeTag(o->GetClass());
Elliott Hughes64f574f2013-02-20 14:57:12 -08001019 JDWP::RefTypeId type_id = gRegistry->AddRefType(o->GetClass());
Elliott Hughes2435a572012-02-17 16:07:41 -08001020
1021 expandBufAdd1(pReply, type_tag);
1022 expandBufAddRefTypeId(pReply, type_id);
1023
1024 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001025}
1026
Ian Rogersfc0e94b2013-09-23 23:51:32 -07001027JDWP::JdwpError Dbg::GetSignature(JDWP::RefTypeId class_id, std::string* signature) {
Ian Rogersc0542af2014-09-03 16:16:56 -07001028 JDWP::JdwpError error;
1029 mirror::Class* c = DecodeClass(class_id, &error);
1030 if (c == nullptr) {
1031 return error;
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -08001032 }
Ian Rogers1ff3c982014-08-12 02:30:58 -07001033 std::string temp;
1034 *signature = c->GetDescriptor(&temp);
Elliott Hughes1fe7afb2012-02-13 17:23:03 -08001035 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001036}
1037
Ian Rogersc0542af2014-09-03 16:16:56 -07001038JDWP::JdwpError Dbg::GetSourceFile(JDWP::RefTypeId class_id, std::string* result) {
1039 JDWP::JdwpError error;
1040 mirror::Class* c = DecodeClass(class_id, &error);
Sebastien Hertz4206eb52014-06-05 10:15:45 +02001041 if (c == nullptr) {
Ian Rogersc0542af2014-09-03 16:16:56 -07001042 return error;
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -08001043 }
Sebastien Hertz4206eb52014-06-05 10:15:45 +02001044 const char* source_file = c->GetSourceFile();
1045 if (source_file == nullptr) {
Sebastien Hertzb7054ba2014-03-13 11:52:31 +01001046 return JDWP::ERR_ABSENT_INFORMATION;
1047 }
Ian Rogersc0542af2014-09-03 16:16:56 -07001048 *result = source_file;
Elliott Hughes436e3722012-02-17 20:01:47 -08001049 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001050}
1051
Ian Rogersc0542af2014-09-03 16:16:56 -07001052JDWP::JdwpError Dbg::GetObjectTag(JDWP::ObjectId object_id, uint8_t* tag) {
Ian Rogers98379392014-02-24 16:53:16 -08001053 ScopedObjectAccessUnchecked soa(Thread::Current());
Ian Rogersc0542af2014-09-03 16:16:56 -07001054 JDWP::JdwpError error;
1055 mirror::Object* o = gRegistry->Get<mirror::Object*>(object_id, &error);
1056 if (error != JDWP::ERR_NONE) {
1057 *tag = JDWP::JT_VOID;
1058 return error;
Elliott Hughes546b9862012-06-20 16:06:13 -07001059 }
Ian Rogersc0542af2014-09-03 16:16:56 -07001060 *tag = TagFromObject(soa, o);
Elliott Hughes546b9862012-06-20 16:06:13 -07001061 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001062}
1063
Elliott Hughesaed4be92011-12-02 16:16:23 -08001064size_t Dbg::GetTagWidth(JDWP::JdwpTag tag) {
Elliott Hughesdbb40792011-11-18 17:05:22 -08001065 switch (tag) {
1066 case JDWP::JT_VOID:
1067 return 0;
1068 case JDWP::JT_BYTE:
1069 case JDWP::JT_BOOLEAN:
1070 return 1;
1071 case JDWP::JT_CHAR:
1072 case JDWP::JT_SHORT:
1073 return 2;
1074 case JDWP::JT_FLOAT:
1075 case JDWP::JT_INT:
1076 return 4;
1077 case JDWP::JT_ARRAY:
1078 case JDWP::JT_OBJECT:
1079 case JDWP::JT_STRING:
1080 case JDWP::JT_THREAD:
1081 case JDWP::JT_THREAD_GROUP:
1082 case JDWP::JT_CLASS_LOADER:
1083 case JDWP::JT_CLASS_OBJECT:
1084 return sizeof(JDWP::ObjectId);
1085 case JDWP::JT_DOUBLE:
1086 case JDWP::JT_LONG:
1087 return 8;
1088 default:
Elliott Hughes3d30d9b2011-12-07 17:35:48 -08001089 LOG(FATAL) << "Unknown tag " << tag;
Elliott Hughesdbb40792011-11-18 17:05:22 -08001090 return -1;
1091 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001092}
1093
Ian Rogersc0542af2014-09-03 16:16:56 -07001094JDWP::JdwpError Dbg::GetArrayLength(JDWP::ObjectId array_id, int32_t* length) {
1095 JDWP::JdwpError error;
1096 mirror::Array* a = DecodeNonNullArray(array_id, &error);
1097 if (a == nullptr) {
1098 return error;
Elliott Hughes24437992011-11-30 14:49:33 -08001099 }
Ian Rogersc0542af2014-09-03 16:16:56 -07001100 *length = a->GetLength();
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -08001101 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001102}
1103
Elliott Hughes88d63092013-01-09 09:55:54 -08001104JDWP::JdwpError Dbg::OutputArray(JDWP::ObjectId array_id, int offset, int count, JDWP::ExpandBuf* pReply) {
Ian Rogersc0542af2014-09-03 16:16:56 -07001105 JDWP::JdwpError error;
1106 mirror::Array* a = DecodeNonNullArray(array_id, &error);
Ian Rogers98379392014-02-24 16:53:16 -08001107 if (a == nullptr) {
Ian Rogersc0542af2014-09-03 16:16:56 -07001108 return error;
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -08001109 }
Elliott Hughes24437992011-11-30 14:49:33 -08001110
1111 if (offset < 0 || count < 0 || offset > a->GetLength() || a->GetLength() - offset < count) {
1112 LOG(WARNING) << __FUNCTION__ << " access out of bounds: offset=" << offset << "; count=" << count;
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -08001113 return JDWP::ERR_INVALID_LENGTH;
Elliott Hughes24437992011-11-30 14:49:33 -08001114 }
Ian Rogers1ff3c982014-08-12 02:30:58 -07001115 JDWP::JdwpTag element_tag = BasicTagFromClass(a->GetClass()->GetComponentType());
1116 expandBufAdd1(pReply, element_tag);
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -08001117 expandBufAdd4BE(pReply, count);
1118
Ian Rogers1ff3c982014-08-12 02:30:58 -07001119 if (IsPrimitiveTag(element_tag)) {
1120 size_t width = GetTagWidth(element_tag);
Elliott Hughes24437992011-11-30 14:49:33 -08001121 uint8_t* dst = expandBufAddSpace(pReply, count * width);
1122 if (width == 8) {
Ian Rogersef7d42f2014-01-06 12:55:46 -08001123 const uint64_t* src8 = reinterpret_cast<uint64_t*>(a->GetRawData(sizeof(uint64_t), 0));
Elliott Hughes24437992011-11-30 14:49:33 -08001124 for (int i = 0; i < count; ++i) JDWP::Write8BE(&dst, src8[offset + i]);
1125 } else if (width == 4) {
Ian Rogersef7d42f2014-01-06 12:55:46 -08001126 const uint32_t* src4 = reinterpret_cast<uint32_t*>(a->GetRawData(sizeof(uint32_t), 0));
Elliott Hughes24437992011-11-30 14:49:33 -08001127 for (int i = 0; i < count; ++i) JDWP::Write4BE(&dst, src4[offset + i]);
1128 } else if (width == 2) {
Ian Rogersef7d42f2014-01-06 12:55:46 -08001129 const uint16_t* src2 = reinterpret_cast<uint16_t*>(a->GetRawData(sizeof(uint16_t), 0));
Elliott Hughes24437992011-11-30 14:49:33 -08001130 for (int i = 0; i < count; ++i) JDWP::Write2BE(&dst, src2[offset + i]);
1131 } else {
Ian Rogersef7d42f2014-01-06 12:55:46 -08001132 const uint8_t* src = reinterpret_cast<uint8_t*>(a->GetRawData(sizeof(uint8_t), 0));
Elliott Hughes24437992011-11-30 14:49:33 -08001133 memcpy(dst, &src[offset * width], count * width);
1134 }
1135 } else {
Ian Rogers98379392014-02-24 16:53:16 -08001136 ScopedObjectAccessUnchecked soa(Thread::Current());
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001137 mirror::ObjectArray<mirror::Object>* oa = a->AsObjectArray<mirror::Object>();
Elliott Hughes24437992011-11-30 14:49:33 -08001138 for (int i = 0; i < count; ++i) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001139 mirror::Object* element = oa->Get(offset + i);
Ian Rogers98379392014-02-24 16:53:16 -08001140 JDWP::JdwpTag specific_tag = (element != nullptr) ? TagFromObject(soa, element)
Ian Rogers1ff3c982014-08-12 02:30:58 -07001141 : element_tag;
Elliott Hughes24437992011-11-30 14:49:33 -08001142 expandBufAdd1(pReply, specific_tag);
1143 expandBufAddObjectId(pReply, gRegistry->Add(element));
1144 }
1145 }
1146
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -08001147 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001148}
1149
Ian Rogersef7d42f2014-01-06 12:55:46 -08001150template <typename T>
Ian Rogersc0542af2014-09-03 16:16:56 -07001151static void CopyArrayData(mirror::Array* a, JDWP::Request* src, int offset, int count)
Ian Rogersef7d42f2014-01-06 12:55:46 -08001152 NO_THREAD_SAFETY_ANALYSIS {
1153 // TODO: fix when annotalysis correctly handles non-member functions.
Elliott Hughes4b9702c2013-02-20 18:13:24 -08001154 DCHECK(a->GetClass()->IsPrimitiveArray());
1155
Ian Rogersef7d42f2014-01-06 12:55:46 -08001156 T* dst = reinterpret_cast<T*>(a->GetRawData(sizeof(T), offset));
Elliott Hughes4b9702c2013-02-20 18:13:24 -08001157 for (int i = 0; i < count; ++i) {
Ian Rogersc0542af2014-09-03 16:16:56 -07001158 *dst++ = src->ReadValue(sizeof(T));
Elliott Hughes4b9702c2013-02-20 18:13:24 -08001159 }
1160}
1161
Elliott Hughes88d63092013-01-09 09:55:54 -08001162JDWP::JdwpError Dbg::SetArrayElements(JDWP::ObjectId array_id, int offset, int count,
Ian Rogersc0542af2014-09-03 16:16:56 -07001163 JDWP::Request* request) {
1164 JDWP::JdwpError error;
1165 mirror::Array* dst = DecodeNonNullArray(array_id, &error);
1166 if (dst == nullptr) {
1167 return error;
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -08001168 }
Elliott Hughesf03b8f62011-12-02 14:26:25 -08001169
Elliott Hughes4b9702c2013-02-20 18:13:24 -08001170 if (offset < 0 || count < 0 || offset > dst->GetLength() || dst->GetLength() - offset < count) {
Elliott Hughesf03b8f62011-12-02 14:26:25 -08001171 LOG(WARNING) << __FUNCTION__ << " access out of bounds: offset=" << offset << "; count=" << count;
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -08001172 return JDWP::ERR_INVALID_LENGTH;
Elliott Hughesf03b8f62011-12-02 14:26:25 -08001173 }
Ian Rogers1ff3c982014-08-12 02:30:58 -07001174 JDWP::JdwpTag element_tag = BasicTagFromClass(dst->GetClass()->GetComponentType());
Elliott Hughesf03b8f62011-12-02 14:26:25 -08001175
Ian Rogers1ff3c982014-08-12 02:30:58 -07001176 if (IsPrimitiveTag(element_tag)) {
1177 size_t width = GetTagWidth(element_tag);
Elliott Hughesf03b8f62011-12-02 14:26:25 -08001178 if (width == 8) {
Elliott Hughes4b9702c2013-02-20 18:13:24 -08001179 CopyArrayData<uint64_t>(dst, request, offset, count);
Elliott Hughesf03b8f62011-12-02 14:26:25 -08001180 } else if (width == 4) {
Elliott Hughes4b9702c2013-02-20 18:13:24 -08001181 CopyArrayData<uint32_t>(dst, request, offset, count);
Elliott Hughesf03b8f62011-12-02 14:26:25 -08001182 } else if (width == 2) {
Elliott Hughes4b9702c2013-02-20 18:13:24 -08001183 CopyArrayData<uint16_t>(dst, request, offset, count);
Elliott Hughesf03b8f62011-12-02 14:26:25 -08001184 } else {
Elliott Hughes4b9702c2013-02-20 18:13:24 -08001185 CopyArrayData<uint8_t>(dst, request, offset, count);
Elliott Hughesf03b8f62011-12-02 14:26:25 -08001186 }
1187 } else {
Elliott Hughes4b9702c2013-02-20 18:13:24 -08001188 mirror::ObjectArray<mirror::Object>* oa = dst->AsObjectArray<mirror::Object>();
Elliott Hughesf03b8f62011-12-02 14:26:25 -08001189 for (int i = 0; i < count; ++i) {
Ian Rogersc0542af2014-09-03 16:16:56 -07001190 JDWP::ObjectId id = request->ReadObjectId();
Ian Rogersc0542af2014-09-03 16:16:56 -07001191 mirror::Object* o = gRegistry->Get<mirror::Object*>(id, &error);
1192 if (error != JDWP::ERR_NONE) {
1193 return error;
Elliott Hughes436e3722012-02-17 20:01:47 -08001194 }
Sebastien Hertzd2fe10a2014-01-15 10:20:56 +01001195 oa->Set<false>(offset + i, o);
Elliott Hughesf03b8f62011-12-02 14:26:25 -08001196 }
1197 }
1198
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -08001199 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001200}
1201
Sebastien Hertz2c3e77a2015-04-02 16:26:48 +02001202JDWP::JdwpError Dbg::CreateString(const std::string& str, JDWP::ObjectId* new_string_id) {
1203 Thread* self = Thread::Current();
1204 mirror::String* new_string = mirror::String::AllocFromModifiedUtf8(self, str.c_str());
1205 if (new_string == nullptr) {
1206 DCHECK(self->IsExceptionPending());
1207 self->ClearException();
1208 LOG(ERROR) << "Could not allocate string";
1209 *new_string_id = 0;
1210 return JDWP::ERR_OUT_OF_MEMORY;
1211 }
1212 *new_string_id = gRegistry->Add(new_string);
1213 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001214}
1215
Sebastien Hertz2c3e77a2015-04-02 16:26:48 +02001216JDWP::JdwpError Dbg::CreateObject(JDWP::RefTypeId class_id, JDWP::ObjectId* new_object_id) {
Ian Rogersc0542af2014-09-03 16:16:56 -07001217 JDWP::JdwpError error;
1218 mirror::Class* c = DecodeClass(class_id, &error);
1219 if (c == nullptr) {
Sebastien Hertz2c3e77a2015-04-02 16:26:48 +02001220 *new_object_id = 0;
Ian Rogersc0542af2014-09-03 16:16:56 -07001221 return error;
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -08001222 }
Sebastien Hertz2c3e77a2015-04-02 16:26:48 +02001223 Thread* self = Thread::Current();
1224 mirror::Object* new_object = c->AllocObject(self);
1225 if (new_object == nullptr) {
1226 DCHECK(self->IsExceptionPending());
1227 self->ClearException();
1228 LOG(ERROR) << "Could not allocate object of type " << PrettyDescriptor(c);
1229 *new_object_id = 0;
1230 return JDWP::ERR_OUT_OF_MEMORY;
1231 }
1232 *new_object_id = gRegistry->Add(new_object);
Elliott Hughes436e3722012-02-17 20:01:47 -08001233 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001234}
1235
Elliott Hughesbf13d362011-12-08 15:51:37 -08001236/*
1237 * Used by Eclipse's "Display" view to evaluate "new byte[5]" to get "(byte[]) [0, 0, 0, 0, 0]".
1238 */
Elliott Hughes88d63092013-01-09 09:55:54 -08001239JDWP::JdwpError Dbg::CreateArrayObject(JDWP::RefTypeId array_class_id, uint32_t length,
Sebastien Hertz2c3e77a2015-04-02 16:26:48 +02001240 JDWP::ObjectId* new_array_id) {
Ian Rogersc0542af2014-09-03 16:16:56 -07001241 JDWP::JdwpError error;
1242 mirror::Class* c = DecodeClass(array_class_id, &error);
1243 if (c == nullptr) {
Sebastien Hertz2c3e77a2015-04-02 16:26:48 +02001244 *new_array_id = 0;
Ian Rogersc0542af2014-09-03 16:16:56 -07001245 return error;
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -08001246 }
Sebastien Hertz2c3e77a2015-04-02 16:26:48 +02001247 Thread* self = Thread::Current();
1248 gc::Heap* heap = Runtime::Current()->GetHeap();
1249 mirror::Array* new_array = mirror::Array::Alloc<true>(self, c, length,
1250 c->GetComponentSizeShift(),
1251 heap->GetCurrentAllocator());
1252 if (new_array == nullptr) {
1253 DCHECK(self->IsExceptionPending());
1254 self->ClearException();
1255 LOG(ERROR) << "Could not allocate array of type " << PrettyDescriptor(c);
1256 *new_array_id = 0;
1257 return JDWP::ERR_OUT_OF_MEMORY;
1258 }
1259 *new_array_id = gRegistry->Add(new_array);
Elliott Hughes436e3722012-02-17 20:01:47 -08001260 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001261}
1262
Mathieu Chartierc7853442015-03-27 14:35:38 -07001263JDWP::FieldId Dbg::ToFieldId(const ArtField* f) {
Elliott Hughes03181a82011-11-17 17:22:21 -08001264 return static_cast<JDWP::FieldId>(reinterpret_cast<uintptr_t>(f));
Elliott Hughes03181a82011-11-17 17:22:21 -08001265}
1266
Mathieu Chartiere401d142015-04-22 13:56:20 -07001267static JDWP::MethodId ToMethodId(const ArtMethod* m)
Mathieu Chartier90443472015-07-16 20:32:27 -07001268 SHARED_REQUIRES(Locks::mutator_lock_) {
Elliott Hughes03181a82011-11-17 17:22:21 -08001269 return static_cast<JDWP::MethodId>(reinterpret_cast<uintptr_t>(m));
Elliott Hughes03181a82011-11-17 17:22:21 -08001270}
1271
Mathieu Chartierc7853442015-03-27 14:35:38 -07001272static ArtField* FromFieldId(JDWP::FieldId fid)
Mathieu Chartier90443472015-07-16 20:32:27 -07001273 SHARED_REQUIRES(Locks::mutator_lock_) {
Mathieu Chartierc7853442015-03-27 14:35:38 -07001274 return reinterpret_cast<ArtField*>(static_cast<uintptr_t>(fid));
Elliott Hughesaed4be92011-12-02 16:16:23 -08001275}
1276
Mathieu Chartiere401d142015-04-22 13:56:20 -07001277static ArtMethod* FromMethodId(JDWP::MethodId mid)
Mathieu Chartier90443472015-07-16 20:32:27 -07001278 SHARED_REQUIRES(Locks::mutator_lock_) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07001279 return reinterpret_cast<ArtMethod*>(static_cast<uintptr_t>(mid));
Elliott Hughes03181a82011-11-17 17:22:21 -08001280}
1281
Sebastien Hertz6995c602014-09-09 12:10:13 +02001282bool Dbg::MatchThread(JDWP::ObjectId expected_thread_id, Thread* event_thread) {
1283 CHECK(event_thread != nullptr);
1284 JDWP::JdwpError error;
Mathieu Chartiere401d142015-04-22 13:56:20 -07001285 mirror::Object* expected_thread_peer = gRegistry->Get<mirror::Object*>(
1286 expected_thread_id, &error);
Sebastien Hertz6995c602014-09-09 12:10:13 +02001287 return expected_thread_peer == event_thread->GetPeer();
1288}
1289
1290bool Dbg::MatchLocation(const JDWP::JdwpLocation& expected_location,
1291 const JDWP::EventLocation& event_location) {
1292 if (expected_location.dex_pc != event_location.dex_pc) {
1293 return false;
1294 }
Mathieu Chartiere401d142015-04-22 13:56:20 -07001295 ArtMethod* m = FromMethodId(expected_location.method_id);
Sebastien Hertz6995c602014-09-09 12:10:13 +02001296 return m == event_location.method;
1297}
1298
1299bool Dbg::MatchType(mirror::Class* event_class, JDWP::RefTypeId class_id) {
Sebastien Hertza9aa0ff2014-09-19 12:07:51 +02001300 if (event_class == nullptr) {
1301 return false;
1302 }
Sebastien Hertz6995c602014-09-09 12:10:13 +02001303 JDWP::JdwpError error;
1304 mirror::Class* expected_class = DecodeClass(class_id, &error);
1305 CHECK(expected_class != nullptr);
1306 return expected_class->IsAssignableFrom(event_class);
1307}
1308
1309bool Dbg::MatchField(JDWP::RefTypeId expected_type_id, JDWP::FieldId expected_field_id,
Mathieu Chartierc7853442015-03-27 14:35:38 -07001310 ArtField* event_field) {
1311 ArtField* expected_field = FromFieldId(expected_field_id);
Sebastien Hertz6995c602014-09-09 12:10:13 +02001312 if (expected_field != event_field) {
1313 return false;
1314 }
1315 return Dbg::MatchType(event_field->GetDeclaringClass(), expected_type_id);
1316}
1317
1318bool Dbg::MatchInstance(JDWP::ObjectId expected_instance_id, mirror::Object* event_instance) {
1319 JDWP::JdwpError error;
1320 mirror::Object* modifier_instance = gRegistry->Get<mirror::Object*>(expected_instance_id, &error);
1321 return modifier_instance == event_instance;
1322}
1323
Mathieu Chartier90443472015-07-16 20:32:27 -07001324void Dbg::SetJdwpLocation(JDWP::JdwpLocation* location, ArtMethod* m, uint32_t dex_pc) {
Ian Rogersc0542af2014-09-03 16:16:56 -07001325 if (m == nullptr) {
Sebastien Hertza9aa0ff2014-09-19 12:07:51 +02001326 memset(location, 0, sizeof(*location));
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08001327 } else {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001328 mirror::Class* c = m->GetDeclaringClass();
Ian Rogersc0542af2014-09-03 16:16:56 -07001329 location->type_tag = GetTypeTag(c);
1330 location->class_id = gRegistry->AddRefType(c);
1331 location->method_id = ToMethodId(m);
1332 location->dex_pc = (m->IsNative() || m->IsProxyMethod()) ? static_cast<uint64_t>(-1) : dex_pc;
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08001333 }
Elliott Hughesd07986f2011-12-06 18:27:45 -08001334}
1335
Ian Rogersc0542af2014-09-03 16:16:56 -07001336std::string Dbg::GetMethodName(JDWP::MethodId method_id) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07001337 ArtMethod* m = FromMethodId(method_id);
Sebastien Hertza9aa0ff2014-09-19 12:07:51 +02001338 if (m == nullptr) {
Mathieu Chartier2cebb242015-04-21 16:50:40 -07001339 return "null";
Sebastien Hertza9aa0ff2014-09-19 12:07:51 +02001340 }
Sebastien Hertz415fd082015-06-01 11:42:27 +02001341 return m->GetInterfaceMethodIfProxy(sizeof(void*))->GetName();
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001342}
1343
Ian Rogersc0542af2014-09-03 16:16:56 -07001344std::string Dbg::GetFieldName(JDWP::FieldId field_id) {
Mathieu Chartierc7853442015-03-27 14:35:38 -07001345 ArtField* f = FromFieldId(field_id);
Sebastien Hertza9aa0ff2014-09-19 12:07:51 +02001346 if (f == nullptr) {
Mathieu Chartier2cebb242015-04-21 16:50:40 -07001347 return "null";
Sebastien Hertza9aa0ff2014-09-19 12:07:51 +02001348 }
1349 return f->GetName();
Elliott Hughesa96836a2013-01-17 12:27:49 -08001350}
1351
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001352/*
1353 * Augment the access flags for synthetic methods and fields by setting
1354 * the (as described by the spec) "0xf0000000 bit". Also, strip out any
1355 * flags not specified by the Java programming language.
1356 */
1357static uint32_t MangleAccessFlags(uint32_t accessFlags) {
1358 accessFlags &= kAccJavaFlagsMask;
1359 if ((accessFlags & kAccSynthetic) != 0) {
1360 accessFlags |= 0xf0000000;
1361 }
1362 return accessFlags;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001363}
1364
Elliott Hughesdbb40792011-11-18 17:05:22 -08001365/*
Jeff Haob7cefc72013-11-14 14:51:09 -08001366 * Circularly shifts registers so that arguments come first. Debuggers
1367 * expect slots to begin with arguments, but dex code places them at
1368 * the end.
Elliott Hughesdbb40792011-11-18 17:05:22 -08001369 */
Mathieu Chartiere401d142015-04-22 13:56:20 -07001370static uint16_t MangleSlot(uint16_t slot, ArtMethod* m)
Mathieu Chartier90443472015-07-16 20:32:27 -07001371 SHARED_REQUIRES(Locks::mutator_lock_) {
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07001372 const DexFile::CodeItem* code_item = m->GetCodeItem();
Sebastien Hertzcb19ebf2014-03-11 15:26:35 +01001373 if (code_item == nullptr) {
1374 // We should not get here for a method without code (native, proxy or abstract). Log it and
1375 // return the slot as is since all registers are arguments.
1376 LOG(WARNING) << "Trying to mangle slot for method without code " << PrettyMethod(m);
1377 return slot;
1378 }
Jeff Haob7cefc72013-11-14 14:51:09 -08001379 uint16_t ins_size = code_item->ins_size_;
1380 uint16_t locals_size = code_item->registers_size_ - ins_size;
1381 if (slot >= locals_size) {
1382 return slot - locals_size;
1383 } else {
1384 return slot + ins_size;
Elliott Hughesdbb40792011-11-18 17:05:22 -08001385 }
Elliott Hughesdbb40792011-11-18 17:05:22 -08001386}
1387
Jeff Haob7cefc72013-11-14 14:51:09 -08001388/*
1389 * Circularly shifts registers so that arguments come last. Reverts
1390 * slots to dex style argument placement.
1391 */
Mathieu Chartiere401d142015-04-22 13:56:20 -07001392static uint16_t DemangleSlot(uint16_t slot, ArtMethod* m, JDWP::JdwpError* error)
Mathieu Chartier90443472015-07-16 20:32:27 -07001393 SHARED_REQUIRES(Locks::mutator_lock_) {
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07001394 const DexFile::CodeItem* code_item = m->GetCodeItem();
Sebastien Hertzcb19ebf2014-03-11 15:26:35 +01001395 if (code_item == nullptr) {
1396 // We should not get here for a method without code (native, proxy or abstract). Log it and
1397 // return the slot as is since all registers are arguments.
1398 LOG(WARNING) << "Trying to demangle slot for method without code " << PrettyMethod(m);
Mathieu Chartiere401d142015-04-22 13:56:20 -07001399 uint16_t vreg_count = ArtMethod::NumArgRegisters(m->GetShorty());
Sebastien Hertzabbabc82015-03-26 08:47:47 +01001400 if (slot < vreg_count) {
1401 *error = JDWP::ERR_NONE;
1402 return slot;
1403 }
Jeff Haob7cefc72013-11-14 14:51:09 -08001404 } else {
Sebastien Hertzabbabc82015-03-26 08:47:47 +01001405 if (slot < code_item->registers_size_) {
1406 uint16_t ins_size = code_item->ins_size_;
1407 uint16_t locals_size = code_item->registers_size_ - ins_size;
1408 *error = JDWP::ERR_NONE;
1409 return (slot < ins_size) ? slot + locals_size : slot - ins_size;
1410 }
Elliott Hughesdbb40792011-11-18 17:05:22 -08001411 }
Sebastien Hertzabbabc82015-03-26 08:47:47 +01001412
1413 // Slot is invalid in the method.
1414 LOG(ERROR) << "Invalid local slot " << slot << " for method " << PrettyMethod(m);
1415 *error = JDWP::ERR_INVALID_SLOT;
1416 return DexFile::kDexNoIndex16;
Elliott Hughesdbb40792011-11-18 17:05:22 -08001417}
1418
Mathieu Chartier90443472015-07-16 20:32:27 -07001419JDWP::JdwpError Dbg::OutputDeclaredFields(JDWP::RefTypeId class_id, bool with_generic,
1420 JDWP::ExpandBuf* pReply) {
Ian Rogersc0542af2014-09-03 16:16:56 -07001421 JDWP::JdwpError error;
1422 mirror::Class* c = DecodeClass(class_id, &error);
1423 if (c == nullptr) {
1424 return error;
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -08001425 }
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001426
1427 size_t instance_field_count = c->NumInstanceFields();
1428 size_t static_field_count = c->NumStaticFields();
1429
1430 expandBufAdd4BE(pReply, instance_field_count + static_field_count);
1431
1432 for (size_t i = 0; i < instance_field_count + static_field_count; ++i) {
Mathieu Chartier90443472015-07-16 20:32:27 -07001433 ArtField* f = (i < instance_field_count) ? c->GetInstanceField(i) :
1434 c->GetStaticField(i - instance_field_count);
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001435 expandBufAddFieldId(pReply, ToFieldId(f));
Mathieu Chartier61c5ebc2014-06-05 17:42:53 -07001436 expandBufAddUtf8String(pReply, f->GetName());
1437 expandBufAddUtf8String(pReply, f->GetTypeDescriptor());
Elliott Hughesc5b734a2011-12-01 17:20:58 -08001438 if (with_generic) {
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001439 static const char genericSignature[1] = "";
1440 expandBufAddUtf8String(pReply, genericSignature);
1441 }
1442 expandBufAdd4BE(pReply, MangleAccessFlags(f->GetAccessFlags()));
1443 }
Elliott Hughes436e3722012-02-17 20:01:47 -08001444 return JDWP::ERR_NONE;
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001445}
1446
Elliott Hughes88d63092013-01-09 09:55:54 -08001447JDWP::JdwpError Dbg::OutputDeclaredMethods(JDWP::RefTypeId class_id, bool with_generic,
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001448 JDWP::ExpandBuf* pReply) {
Ian Rogersc0542af2014-09-03 16:16:56 -07001449 JDWP::JdwpError error;
1450 mirror::Class* c = DecodeClass(class_id, &error);
1451 if (c == nullptr) {
1452 return error;
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -08001453 }
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001454
1455 size_t direct_method_count = c->NumDirectMethods();
1456 size_t virtual_method_count = c->NumVirtualMethods();
1457
1458 expandBufAdd4BE(pReply, direct_method_count + virtual_method_count);
1459
Mathieu Chartiere401d142015-04-22 13:56:20 -07001460 auto* cl = Runtime::Current()->GetClassLinker();
1461 auto ptr_size = cl->GetImagePointerSize();
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001462 for (size_t i = 0; i < direct_method_count + virtual_method_count; ++i) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07001463 ArtMethod* m = i < direct_method_count ?
1464 c->GetDirectMethod(i, ptr_size) : c->GetVirtualMethod(i - direct_method_count, ptr_size);
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001465 expandBufAddMethodId(pReply, ToMethodId(m));
Sebastien Hertz415fd082015-06-01 11:42:27 +02001466 expandBufAddUtf8String(pReply, m->GetInterfaceMethodIfProxy(sizeof(void*))->GetName());
1467 expandBufAddUtf8String(pReply,
1468 m->GetInterfaceMethodIfProxy(sizeof(void*))->GetSignature().ToString());
Elliott Hughesc5b734a2011-12-01 17:20:58 -08001469 if (with_generic) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07001470 const char* generic_signature = "";
1471 expandBufAddUtf8String(pReply, generic_signature);
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001472 }
1473 expandBufAdd4BE(pReply, MangleAccessFlags(m->GetAccessFlags()));
1474 }
Elliott Hughes436e3722012-02-17 20:01:47 -08001475 return JDWP::ERR_NONE;
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001476}
1477
Elliott Hughes88d63092013-01-09 09:55:54 -08001478JDWP::JdwpError Dbg::OutputDeclaredInterfaces(JDWP::RefTypeId class_id, JDWP::ExpandBuf* pReply) {
Ian Rogersc0542af2014-09-03 16:16:56 -07001479 JDWP::JdwpError error;
Mathieu Chartierf8322842014-05-16 10:59:25 -07001480 Thread* self = Thread::Current();
1481 StackHandleScope<1> hs(self);
Ian Rogersc0542af2014-09-03 16:16:56 -07001482 Handle<mirror::Class> c(hs.NewHandle(DecodeClass(class_id, &error)));
Mathieu Chartierf8322842014-05-16 10:59:25 -07001483 if (c.Get() == nullptr) {
Ian Rogersc0542af2014-09-03 16:16:56 -07001484 return error;
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -08001485 }
Mathieu Chartierf8322842014-05-16 10:59:25 -07001486 size_t interface_count = c->NumDirectInterfaces();
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001487 expandBufAdd4BE(pReply, interface_count);
1488 for (size_t i = 0; i < interface_count; ++i) {
Mathieu Chartierf8322842014-05-16 10:59:25 -07001489 expandBufAddRefTypeId(pReply,
1490 gRegistry->AddRefType(mirror::Class::GetDirectInterface(self, c, i)));
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001491 }
Elliott Hughes436e3722012-02-17 20:01:47 -08001492 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001493}
1494
Ian Rogersc0542af2014-09-03 16:16:56 -07001495void Dbg::OutputLineTable(JDWP::RefTypeId, JDWP::MethodId method_id, JDWP::ExpandBuf* pReply) {
Elliott Hughes03181a82011-11-17 17:22:21 -08001496 struct DebugCallbackContext {
1497 int numItems;
1498 JDWP::ExpandBuf* pReply;
1499
Elliott Hughes2435a572012-02-17 16:07:41 -08001500 static bool Callback(void* context, uint32_t address, uint32_t line_number) {
Elliott Hughes03181a82011-11-17 17:22:21 -08001501 DebugCallbackContext* pContext = reinterpret_cast<DebugCallbackContext*>(context);
1502 expandBufAdd8BE(pContext->pReply, address);
Elliott Hughes2435a572012-02-17 16:07:41 -08001503 expandBufAdd4BE(pContext->pReply, line_number);
Elliott Hughes03181a82011-11-17 17:22:21 -08001504 pContext->numItems++;
Sebastien Hertzf2910ee2013-10-19 16:39:24 +02001505 return false;
Elliott Hughes03181a82011-11-17 17:22:21 -08001506 }
1507 };
Mathieu Chartiere401d142015-04-22 13:56:20 -07001508 ArtMethod* m = FromMethodId(method_id);
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07001509 const DexFile::CodeItem* code_item = m->GetCodeItem();
Elliott Hughes03181a82011-11-17 17:22:21 -08001510 uint64_t start, end;
Sebastien Hertzcb19ebf2014-03-11 15:26:35 +01001511 if (code_item == nullptr) {
1512 DCHECK(m->IsNative() || m->IsProxyMethod());
Elliott Hughes03181a82011-11-17 17:22:21 -08001513 start = -1;
1514 end = -1;
1515 } else {
1516 start = 0;
jeffhao14f0db92012-12-14 17:50:42 -08001517 // Return the index of the last instruction
Sebastien Hertzcb19ebf2014-03-11 15:26:35 +01001518 end = code_item->insns_size_in_code_units_ - 1;
Elliott Hughes03181a82011-11-17 17:22:21 -08001519 }
1520
1521 expandBufAdd8BE(pReply, start);
1522 expandBufAdd8BE(pReply, end);
1523
1524 // Add numLines later
1525 size_t numLinesOffset = expandBufGetLength(pReply);
1526 expandBufAdd4BE(pReply, 0);
1527
1528 DebugCallbackContext context;
1529 context.numItems = 0;
1530 context.pReply = pReply;
1531
Sebastien Hertzcb19ebf2014-03-11 15:26:35 +01001532 if (code_item != nullptr) {
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07001533 m->GetDexFile()->DecodeDebugInfo(code_item, m->IsStatic(), m->GetDexMethodIndex(),
Ian Rogersc0542af2014-09-03 16:16:56 -07001534 DebugCallbackContext::Callback, nullptr, &context);
Sebastien Hertzcb19ebf2014-03-11 15:26:35 +01001535 }
Elliott Hughes03181a82011-11-17 17:22:21 -08001536
1537 JDWP::Set4BE(expandBufGetBuffer(pReply) + numLinesOffset, context.numItems);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001538}
1539
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07001540void Dbg::OutputVariableTable(JDWP::RefTypeId, JDWP::MethodId method_id, bool with_generic,
1541 JDWP::ExpandBuf* pReply) {
Elliott Hughesdbb40792011-11-18 17:05:22 -08001542 struct DebugCallbackContext {
Mathieu Chartiere401d142015-04-22 13:56:20 -07001543 ArtMethod* method;
Elliott Hughesdbb40792011-11-18 17:05:22 -08001544 JDWP::ExpandBuf* pReply;
Elliott Hughesc5b734a2011-12-01 17:20:58 -08001545 size_t variable_count;
1546 bool with_generic;
Elliott Hughesdbb40792011-11-18 17:05:22 -08001547
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07001548 static void Callback(void* context, uint16_t slot, uint32_t startAddress, uint32_t endAddress,
1549 const char* name, const char* descriptor, const char* signature)
Mathieu Chartier90443472015-07-16 20:32:27 -07001550 SHARED_REQUIRES(Locks::mutator_lock_) {
Elliott Hughesdbb40792011-11-18 17:05:22 -08001551 DebugCallbackContext* pContext = reinterpret_cast<DebugCallbackContext*>(context);
1552
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07001553 VLOG(jdwp) << StringPrintf(" %2zd: %d(%d) '%s' '%s' '%s' actual slot=%d mangled slot=%d",
1554 pContext->variable_count, startAddress, endAddress - startAddress,
1555 name, descriptor, signature, slot,
1556 MangleSlot(slot, pContext->method));
Elliott Hughesdbb40792011-11-18 17:05:22 -08001557
Jeff Haob7cefc72013-11-14 14:51:09 -08001558 slot = MangleSlot(slot, pContext->method);
Elliott Hughes68fdbd02011-11-29 19:22:47 -08001559
Elliott Hughesdbb40792011-11-18 17:05:22 -08001560 expandBufAdd8BE(pContext->pReply, startAddress);
1561 expandBufAddUtf8String(pContext->pReply, name);
1562 expandBufAddUtf8String(pContext->pReply, descriptor);
Elliott Hughesc5b734a2011-12-01 17:20:58 -08001563 if (pContext->with_generic) {
Elliott Hughesdbb40792011-11-18 17:05:22 -08001564 expandBufAddUtf8String(pContext->pReply, signature);
1565 }
1566 expandBufAdd4BE(pContext->pReply, endAddress - startAddress);
1567 expandBufAdd4BE(pContext->pReply, slot);
1568
Elliott Hughesc5b734a2011-12-01 17:20:58 -08001569 ++pContext->variable_count;
Elliott Hughesdbb40792011-11-18 17:05:22 -08001570 }
1571 };
Mathieu Chartiere401d142015-04-22 13:56:20 -07001572 ArtMethod* m = FromMethodId(method_id);
Elliott Hughesdbb40792011-11-18 17:05:22 -08001573
Elliott Hughesc5b734a2011-12-01 17:20:58 -08001574 // arg_count considers doubles and longs to take 2 units.
1575 // variable_count considers everything to take 1 unit.
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07001576 std::string shorty(m->GetShorty());
Mathieu Chartiere401d142015-04-22 13:56:20 -07001577 expandBufAdd4BE(pReply, ArtMethod::NumArgRegisters(shorty));
Elliott Hughesdbb40792011-11-18 17:05:22 -08001578
Elliott Hughesc5b734a2011-12-01 17:20:58 -08001579 // We don't know the total number of variables yet, so leave a blank and update it later.
1580 size_t variable_count_offset = expandBufGetLength(pReply);
Elliott Hughesdbb40792011-11-18 17:05:22 -08001581 expandBufAdd4BE(pReply, 0);
1582
1583 DebugCallbackContext context;
Jeff Haob7cefc72013-11-14 14:51:09 -08001584 context.method = m;
Elliott Hughesdbb40792011-11-18 17:05:22 -08001585 context.pReply = pReply;
Elliott Hughesc5b734a2011-12-01 17:20:58 -08001586 context.variable_count = 0;
1587 context.with_generic = with_generic;
Elliott Hughesdbb40792011-11-18 17:05:22 -08001588
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07001589 const DexFile::CodeItem* code_item = m->GetCodeItem();
Sebastien Hertzcb19ebf2014-03-11 15:26:35 +01001590 if (code_item != nullptr) {
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07001591 m->GetDexFile()->DecodeDebugInfo(
Ian Rogersc0542af2014-09-03 16:16:56 -07001592 code_item, m->IsStatic(), m->GetDexMethodIndex(), nullptr, DebugCallbackContext::Callback,
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07001593 &context);
Sebastien Hertzcb19ebf2014-03-11 15:26:35 +01001594 }
Elliott Hughesdbb40792011-11-18 17:05:22 -08001595
Elliott Hughesc5b734a2011-12-01 17:20:58 -08001596 JDWP::Set4BE(expandBufGetBuffer(pReply) + variable_count_offset, context.variable_count);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001597}
1598
Jeff Hao579b0242013-11-18 13:16:49 -08001599void Dbg::OutputMethodReturnValue(JDWP::MethodId method_id, const JValue* return_value,
1600 JDWP::ExpandBuf* pReply) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07001601 ArtMethod* m = FromMethodId(method_id);
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07001602 JDWP::JdwpTag tag = BasicTagFromDescriptor(m->GetShorty());
Jeff Hao579b0242013-11-18 13:16:49 -08001603 OutputJValue(tag, return_value, pReply);
1604}
1605
Sebastien Hertz3f52eaf2014-04-04 17:50:18 +02001606void Dbg::OutputFieldValue(JDWP::FieldId field_id, const JValue* field_value,
1607 JDWP::ExpandBuf* pReply) {
Mathieu Chartierc7853442015-03-27 14:35:38 -07001608 ArtField* f = FromFieldId(field_id);
Mathieu Chartier61c5ebc2014-06-05 17:42:53 -07001609 JDWP::JdwpTag tag = BasicTagFromDescriptor(f->GetTypeDescriptor());
Sebastien Hertz3f52eaf2014-04-04 17:50:18 +02001610 OutputJValue(tag, field_value, pReply);
1611}
1612
Elliott Hughes9777ba22013-01-17 09:04:19 -08001613JDWP::JdwpError Dbg::GetBytecodes(JDWP::RefTypeId, JDWP::MethodId method_id,
Ian Rogersc0542af2014-09-03 16:16:56 -07001614 std::vector<uint8_t>* bytecodes) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07001615 ArtMethod* m = FromMethodId(method_id);
Ian Rogersc0542af2014-09-03 16:16:56 -07001616 if (m == nullptr) {
Elliott Hughes9777ba22013-01-17 09:04:19 -08001617 return JDWP::ERR_INVALID_METHODID;
1618 }
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07001619 const DexFile::CodeItem* code_item = m->GetCodeItem();
Elliott Hughes9777ba22013-01-17 09:04:19 -08001620 size_t byte_count = code_item->insns_size_in_code_units_ * 2;
1621 const uint8_t* begin = reinterpret_cast<const uint8_t*>(code_item->insns_);
1622 const uint8_t* end = begin + byte_count;
1623 for (const uint8_t* p = begin; p != end; ++p) {
Ian Rogersc0542af2014-09-03 16:16:56 -07001624 bytecodes->push_back(*p);
Elliott Hughes9777ba22013-01-17 09:04:19 -08001625 }
1626 return JDWP::ERR_NONE;
1627}
1628
Elliott Hughes88d63092013-01-09 09:55:54 -08001629JDWP::JdwpTag Dbg::GetFieldBasicTag(JDWP::FieldId field_id) {
Mathieu Chartier61c5ebc2014-06-05 17:42:53 -07001630 return BasicTagFromDescriptor(FromFieldId(field_id)->GetTypeDescriptor());
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001631}
1632
Elliott Hughes88d63092013-01-09 09:55:54 -08001633JDWP::JdwpTag Dbg::GetStaticFieldBasicTag(JDWP::FieldId field_id) {
Mathieu Chartier61c5ebc2014-06-05 17:42:53 -07001634 return BasicTagFromDescriptor(FromFieldId(field_id)->GetTypeDescriptor());
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001635}
1636
Sebastien Hertz05c26b32015-06-11 18:42:58 +02001637static JValue GetArtFieldValue(ArtField* f, mirror::Object* o)
Mathieu Chartier90443472015-07-16 20:32:27 -07001638 SHARED_REQUIRES(Locks::mutator_lock_) {
Sebastien Hertz05c26b32015-06-11 18:42:58 +02001639 Primitive::Type fieldType = f->GetTypeAsPrimitiveType();
1640 JValue field_value;
1641 switch (fieldType) {
1642 case Primitive::kPrimBoolean:
1643 field_value.SetZ(f->GetBoolean(o));
1644 return field_value;
1645
1646 case Primitive::kPrimByte:
1647 field_value.SetB(f->GetByte(o));
1648 return field_value;
1649
1650 case Primitive::kPrimChar:
1651 field_value.SetC(f->GetChar(o));
1652 return field_value;
1653
1654 case Primitive::kPrimShort:
1655 field_value.SetS(f->GetShort(o));
1656 return field_value;
1657
1658 case Primitive::kPrimInt:
1659 case Primitive::kPrimFloat:
1660 // Int and Float must be treated as 32-bit values in JDWP.
1661 field_value.SetI(f->GetInt(o));
1662 return field_value;
1663
1664 case Primitive::kPrimLong:
1665 case Primitive::kPrimDouble:
1666 // Long and Double must be treated as 64-bit values in JDWP.
1667 field_value.SetJ(f->GetLong(o));
1668 return field_value;
1669
1670 case Primitive::kPrimNot:
1671 field_value.SetL(f->GetObject(o));
1672 return field_value;
1673
1674 case Primitive::kPrimVoid:
1675 LOG(FATAL) << "Attempt to read from field of type 'void'";
1676 UNREACHABLE();
1677 }
1678 LOG(FATAL) << "Attempt to read from field of unknown type";
1679 UNREACHABLE();
1680}
1681
Elliott Hughes88d63092013-01-09 09:55:54 -08001682static JDWP::JdwpError GetFieldValueImpl(JDWP::RefTypeId ref_type_id, JDWP::ObjectId object_id,
1683 JDWP::FieldId field_id, JDWP::ExpandBuf* pReply,
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001684 bool is_static)
Mathieu Chartier90443472015-07-16 20:32:27 -07001685 SHARED_REQUIRES(Locks::mutator_lock_) {
Ian Rogersc0542af2014-09-03 16:16:56 -07001686 JDWP::JdwpError error;
1687 mirror::Class* c = DecodeClass(ref_type_id, &error);
1688 if (ref_type_id != 0 && c == nullptr) {
1689 return error;
Elliott Hughes0cf74332012-02-23 23:14:00 -08001690 }
1691
Sebastien Hertz6995c602014-09-09 12:10:13 +02001692 mirror::Object* o = Dbg::GetObjectRegistry()->Get<mirror::Object*>(object_id, &error);
Ian Rogersc0542af2014-09-03 16:16:56 -07001693 if ((!is_static && o == nullptr) || error != JDWP::ERR_NONE) {
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08001694 return JDWP::ERR_INVALID_OBJECT;
1695 }
Mathieu Chartierc7853442015-03-27 14:35:38 -07001696 ArtField* f = FromFieldId(field_id);
Elliott Hughes0cf74332012-02-23 23:14:00 -08001697
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001698 mirror::Class* receiver_class = c;
Ian Rogersc0542af2014-09-03 16:16:56 -07001699 if (receiver_class == nullptr && o != nullptr) {
Elliott Hughes0cf74332012-02-23 23:14:00 -08001700 receiver_class = o->GetClass();
1701 }
Mathieu Chartier2cebb242015-04-21 16:50:40 -07001702 // TODO: should we give up now if receiver_class is null?
Ian Rogersc0542af2014-09-03 16:16:56 -07001703 if (receiver_class != nullptr && !f->GetDeclaringClass()->IsAssignableFrom(receiver_class)) {
Elliott Hughes0cf74332012-02-23 23:14:00 -08001704 LOG(INFO) << "ERR_INVALID_FIELDID: " << PrettyField(f) << " " << PrettyClass(receiver_class);
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08001705 return JDWP::ERR_INVALID_FIELDID;
1706 }
Elliott Hughesaed4be92011-12-02 16:16:23 -08001707
Elliott Hughes0cf74332012-02-23 23:14:00 -08001708 // The RI only enforces the static/non-static mismatch in one direction.
1709 // TODO: should we change the tests and check both?
1710 if (is_static) {
1711 if (!f->IsStatic()) {
1712 return JDWP::ERR_INVALID_FIELDID;
1713 }
1714 } else {
1715 if (f->IsStatic()) {
Sebastien Hertz05c26b32015-06-11 18:42:58 +02001716 LOG(WARNING) << "Ignoring non-nullptr receiver for ObjectReference.GetValues"
1717 << " on static field " << PrettyField(f);
Elliott Hughes0cf74332012-02-23 23:14:00 -08001718 }
1719 }
jeffhao0dfbb7e2012-11-28 15:26:03 -08001720 if (f->IsStatic()) {
1721 o = f->GetDeclaringClass();
1722 }
Elliott Hughes0cf74332012-02-23 23:14:00 -08001723
Sebastien Hertz05c26b32015-06-11 18:42:58 +02001724 JValue field_value(GetArtFieldValue(f, o));
Mathieu Chartier61c5ebc2014-06-05 17:42:53 -07001725 JDWP::JdwpTag tag = BasicTagFromDescriptor(f->GetTypeDescriptor());
Jeff Hao579b0242013-11-18 13:16:49 -08001726 Dbg::OutputJValue(tag, &field_value, pReply);
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08001727 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001728}
1729
Elliott Hughes88d63092013-01-09 09:55:54 -08001730JDWP::JdwpError Dbg::GetFieldValue(JDWP::ObjectId object_id, JDWP::FieldId field_id,
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001731 JDWP::ExpandBuf* pReply) {
Elliott Hughes88d63092013-01-09 09:55:54 -08001732 return GetFieldValueImpl(0, object_id, field_id, pReply, false);
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08001733}
1734
Ian Rogersc0542af2014-09-03 16:16:56 -07001735JDWP::JdwpError Dbg::GetStaticFieldValue(JDWP::RefTypeId ref_type_id, JDWP::FieldId field_id,
1736 JDWP::ExpandBuf* pReply) {
Elliott Hughes88d63092013-01-09 09:55:54 -08001737 return GetFieldValueImpl(ref_type_id, 0, field_id, pReply, true);
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08001738}
1739
Sebastien Hertz05c26b32015-06-11 18:42:58 +02001740static JDWP::JdwpError SetArtFieldValue(ArtField* f, mirror::Object* o, uint64_t value, int width)
Mathieu Chartier90443472015-07-16 20:32:27 -07001741 SHARED_REQUIRES(Locks::mutator_lock_) {
Sebastien Hertz05c26b32015-06-11 18:42:58 +02001742 Primitive::Type fieldType = f->GetTypeAsPrimitiveType();
1743 // Debugging only happens at runtime so we know we are not running in a transaction.
1744 static constexpr bool kNoTransactionMode = false;
1745 switch (fieldType) {
1746 case Primitive::kPrimBoolean:
1747 CHECK_EQ(width, 1);
1748 f->SetBoolean<kNoTransactionMode>(o, static_cast<uint8_t>(value));
1749 return JDWP::ERR_NONE;
1750
1751 case Primitive::kPrimByte:
1752 CHECK_EQ(width, 1);
1753 f->SetByte<kNoTransactionMode>(o, static_cast<uint8_t>(value));
1754 return JDWP::ERR_NONE;
1755
1756 case Primitive::kPrimChar:
1757 CHECK_EQ(width, 2);
1758 f->SetChar<kNoTransactionMode>(o, static_cast<uint16_t>(value));
1759 return JDWP::ERR_NONE;
1760
1761 case Primitive::kPrimShort:
1762 CHECK_EQ(width, 2);
1763 f->SetShort<kNoTransactionMode>(o, static_cast<int16_t>(value));
1764 return JDWP::ERR_NONE;
1765
1766 case Primitive::kPrimInt:
1767 case Primitive::kPrimFloat:
1768 CHECK_EQ(width, 4);
1769 // Int and Float must be treated as 32-bit values in JDWP.
1770 f->SetInt<kNoTransactionMode>(o, static_cast<int32_t>(value));
1771 return JDWP::ERR_NONE;
1772
1773 case Primitive::kPrimLong:
1774 case Primitive::kPrimDouble:
1775 CHECK_EQ(width, 8);
1776 // Long and Double must be treated as 64-bit values in JDWP.
1777 f->SetLong<kNoTransactionMode>(o, value);
1778 return JDWP::ERR_NONE;
1779
1780 case Primitive::kPrimNot: {
1781 JDWP::JdwpError error;
1782 mirror::Object* v = Dbg::GetObjectRegistry()->Get<mirror::Object*>(value, &error);
1783 if (error != JDWP::ERR_NONE) {
1784 return JDWP::ERR_INVALID_OBJECT;
1785 }
1786 if (v != nullptr) {
1787 mirror::Class* field_type;
1788 {
1789 StackHandleScope<2> hs(Thread::Current());
1790 HandleWrapper<mirror::Object> h_v(hs.NewHandleWrapper(&v));
1791 HandleWrapper<mirror::Object> h_o(hs.NewHandleWrapper(&o));
1792 field_type = f->GetType<true>();
1793 }
1794 if (!field_type->IsAssignableFrom(v->GetClass())) {
1795 return JDWP::ERR_INVALID_OBJECT;
1796 }
1797 }
1798 f->SetObject<kNoTransactionMode>(o, v);
1799 return JDWP::ERR_NONE;
1800 }
1801
1802 case Primitive::kPrimVoid:
1803 LOG(FATAL) << "Attempt to write to field of type 'void'";
1804 UNREACHABLE();
1805 }
1806 LOG(FATAL) << "Attempt to write to field of unknown type";
1807 UNREACHABLE();
1808}
1809
Elliott Hughes88d63092013-01-09 09:55:54 -08001810static JDWP::JdwpError SetFieldValueImpl(JDWP::ObjectId object_id, JDWP::FieldId field_id,
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001811 uint64_t value, int width, bool is_static)
Mathieu Chartier90443472015-07-16 20:32:27 -07001812 SHARED_REQUIRES(Locks::mutator_lock_) {
Ian Rogersc0542af2014-09-03 16:16:56 -07001813 JDWP::JdwpError error;
Sebastien Hertz6995c602014-09-09 12:10:13 +02001814 mirror::Object* o = Dbg::GetObjectRegistry()->Get<mirror::Object*>(object_id, &error);
Ian Rogersc0542af2014-09-03 16:16:56 -07001815 if ((!is_static && o == nullptr) || error != JDWP::ERR_NONE) {
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08001816 return JDWP::ERR_INVALID_OBJECT;
1817 }
Mathieu Chartierc7853442015-03-27 14:35:38 -07001818 ArtField* f = FromFieldId(field_id);
Elliott Hughes0cf74332012-02-23 23:14:00 -08001819
1820 // The RI only enforces the static/non-static mismatch in one direction.
1821 // TODO: should we change the tests and check both?
1822 if (is_static) {
1823 if (!f->IsStatic()) {
1824 return JDWP::ERR_INVALID_FIELDID;
1825 }
1826 } else {
1827 if (f->IsStatic()) {
Sebastien Hertz05c26b32015-06-11 18:42:58 +02001828 LOG(WARNING) << "Ignoring non-nullptr receiver for ObjectReference.SetValues"
1829 << " on static field " << PrettyField(f);
Elliott Hughes0cf74332012-02-23 23:14:00 -08001830 }
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08001831 }
jeffhao0dfbb7e2012-11-28 15:26:03 -08001832 if (f->IsStatic()) {
1833 o = f->GetDeclaringClass();
1834 }
Sebastien Hertz05c26b32015-06-11 18:42:58 +02001835 return SetArtFieldValue(f, o, value, width);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001836}
1837
Elliott Hughes88d63092013-01-09 09:55:54 -08001838JDWP::JdwpError Dbg::SetFieldValue(JDWP::ObjectId object_id, JDWP::FieldId field_id, uint64_t value,
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001839 int width) {
Elliott Hughes88d63092013-01-09 09:55:54 -08001840 return SetFieldValueImpl(object_id, field_id, value, width, false);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001841}
1842
Elliott Hughes88d63092013-01-09 09:55:54 -08001843JDWP::JdwpError Dbg::SetStaticFieldValue(JDWP::FieldId field_id, uint64_t value, int width) {
1844 return SetFieldValueImpl(0, field_id, value, width, true);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001845}
1846
Sebastien Hertzb0b0b492014-09-15 11:27:27 +02001847JDWP::JdwpError Dbg::StringToUtf8(JDWP::ObjectId string_id, std::string* str) {
Ian Rogersc0542af2014-09-03 16:16:56 -07001848 JDWP::JdwpError error;
Sebastien Hertzb0b0b492014-09-15 11:27:27 +02001849 mirror::Object* obj = gRegistry->Get<mirror::Object*>(string_id, &error);
1850 if (error != JDWP::ERR_NONE) {
1851 return error;
1852 }
1853 if (obj == nullptr) {
1854 return JDWP::ERR_INVALID_OBJECT;
1855 }
1856 {
1857 ScopedObjectAccessUnchecked soa(Thread::Current());
1858 mirror::Class* java_lang_String = soa.Decode<mirror::Class*>(WellKnownClasses::java_lang_String);
1859 if (!java_lang_String->IsAssignableFrom(obj->GetClass())) {
1860 // This isn't a string.
1861 return JDWP::ERR_INVALID_STRING;
1862 }
1863 }
1864 *str = obj->AsString()->ToModifiedUtf8();
1865 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001866}
1867
Jeff Hao579b0242013-11-18 13:16:49 -08001868void Dbg::OutputJValue(JDWP::JdwpTag tag, const JValue* return_value, JDWP::ExpandBuf* pReply) {
1869 if (IsPrimitiveTag(tag)) {
1870 expandBufAdd1(pReply, tag);
1871 if (tag == JDWP::JT_BOOLEAN || tag == JDWP::JT_BYTE) {
1872 expandBufAdd1(pReply, return_value->GetI());
1873 } else if (tag == JDWP::JT_CHAR || tag == JDWP::JT_SHORT) {
1874 expandBufAdd2BE(pReply, return_value->GetI());
1875 } else if (tag == JDWP::JT_FLOAT || tag == JDWP::JT_INT) {
1876 expandBufAdd4BE(pReply, return_value->GetI());
1877 } else if (tag == JDWP::JT_DOUBLE || tag == JDWP::JT_LONG) {
1878 expandBufAdd8BE(pReply, return_value->GetJ());
1879 } else {
1880 CHECK_EQ(tag, JDWP::JT_VOID);
1881 }
1882 } else {
Ian Rogers98379392014-02-24 16:53:16 -08001883 ScopedObjectAccessUnchecked soa(Thread::Current());
Jeff Hao579b0242013-11-18 13:16:49 -08001884 mirror::Object* value = return_value->GetL();
Ian Rogers98379392014-02-24 16:53:16 -08001885 expandBufAdd1(pReply, TagFromObject(soa, value));
Jeff Hao579b0242013-11-18 13:16:49 -08001886 expandBufAddObjectId(pReply, gRegistry->Add(value));
1887 }
1888}
1889
Ian Rogersc0542af2014-09-03 16:16:56 -07001890JDWP::JdwpError Dbg::GetThreadName(JDWP::ObjectId thread_id, std::string* name) {
jeffhaoa77f0f62012-12-05 17:19:31 -08001891 ScopedObjectAccessUnchecked soa(Thread::Current());
Ian Rogersc0542af2014-09-03 16:16:56 -07001892 JDWP::JdwpError error;
1893 Thread* thread = DecodeThread(soa, thread_id, &error);
1894 UNUSED(thread);
Elliott Hughes221229c2013-01-08 18:17:50 -08001895 if (error != JDWP::ERR_NONE && error != JDWP::ERR_THREAD_NOT_ALIVE) {
1896 return error;
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001897 }
Elliott Hughes221229c2013-01-08 18:17:50 -08001898
1899 // We still need to report the zombie threads' names, so we can't just call Thread::GetThreadName.
Ian Rogersc0542af2014-09-03 16:16:56 -07001900 mirror::Object* thread_object = gRegistry->Get<mirror::Object*>(thread_id, &error);
1901 CHECK(thread_object != nullptr) << error;
Mathieu Chartierc7853442015-03-27 14:35:38 -07001902 ArtField* java_lang_Thread_name_field =
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001903 soa.DecodeField(WellKnownClasses::java_lang_Thread_name);
1904 mirror::String* s =
1905 reinterpret_cast<mirror::String*>(java_lang_Thread_name_field->GetObject(thread_object));
Ian Rogersc0542af2014-09-03 16:16:56 -07001906 if (s != nullptr) {
1907 *name = s->ToModifiedUtf8();
Elliott Hughes221229c2013-01-08 18:17:50 -08001908 }
1909 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001910}
1911
Elliott Hughes221229c2013-01-08 18:17:50 -08001912JDWP::JdwpError Dbg::GetThreadGroup(JDWP::ObjectId thread_id, JDWP::ExpandBuf* pReply) {
Sebastien Hertza06430c2014-09-15 19:21:30 +02001913 ScopedObjectAccessUnchecked soa(Thread::Current());
Ian Rogersc0542af2014-09-03 16:16:56 -07001914 JDWP::JdwpError error;
1915 mirror::Object* thread_object = gRegistry->Get<mirror::Object*>(thread_id, &error);
1916 if (error != JDWP::ERR_NONE) {
Elliott Hughes2435a572012-02-17 16:07:41 -08001917 return JDWP::ERR_INVALID_OBJECT;
1918 }
Mathieu Chartier2d5f39e2014-09-19 17:52:37 -07001919 ScopedAssertNoThreadSuspension ants(soa.Self(), "Debugger: GetThreadGroup");
Elliott Hughes2435a572012-02-17 16:07:41 -08001920 // Okay, so it's an object, but is it actually a thread?
Sebastien Hertz69206392015-04-07 15:54:25 +02001921 Thread* thread = DecodeThread(soa, thread_id, &error);
1922 UNUSED(thread);
Elliott Hughes221229c2013-01-08 18:17:50 -08001923 if (error == JDWP::ERR_THREAD_NOT_ALIVE) {
1924 // Zombie threads are in the null group.
1925 expandBufAddObjectId(pReply, JDWP::ObjectId(0));
Sebastien Hertz52d131d2014-03-13 16:17:40 +01001926 error = JDWP::ERR_NONE;
1927 } else if (error == JDWP::ERR_NONE) {
1928 mirror::Class* c = soa.Decode<mirror::Class*>(WellKnownClasses::java_lang_Thread);
1929 CHECK(c != nullptr);
Mathieu Chartierc7853442015-03-27 14:35:38 -07001930 ArtField* f = soa.DecodeField(WellKnownClasses::java_lang_Thread_group);
Hiroshi Yamauchib5a9e3d2014-06-09 12:11:20 -07001931 CHECK(f != nullptr);
Sebastien Hertz52d131d2014-03-13 16:17:40 +01001932 mirror::Object* group = f->GetObject(thread_object);
Hiroshi Yamauchib5a9e3d2014-06-09 12:11:20 -07001933 CHECK(group != nullptr);
Sebastien Hertz52d131d2014-03-13 16:17:40 +01001934 JDWP::ObjectId thread_group_id = gRegistry->Add(group);
1935 expandBufAddObjectId(pReply, thread_group_id);
Elliott Hughes221229c2013-01-08 18:17:50 -08001936 }
Sebastien Hertz52d131d2014-03-13 16:17:40 +01001937 return error;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001938}
1939
Sebastien Hertza06430c2014-09-15 19:21:30 +02001940static mirror::Object* DecodeThreadGroup(ScopedObjectAccessUnchecked& soa,
1941 JDWP::ObjectId thread_group_id, JDWP::JdwpError* error)
Mathieu Chartier90443472015-07-16 20:32:27 -07001942 SHARED_REQUIRES(Locks::mutator_lock_) {
Sebastien Hertz6995c602014-09-09 12:10:13 +02001943 mirror::Object* thread_group = Dbg::GetObjectRegistry()->Get<mirror::Object*>(thread_group_id,
1944 error);
Sebastien Hertza06430c2014-09-15 19:21:30 +02001945 if (*error != JDWP::ERR_NONE) {
1946 return nullptr;
1947 }
1948 if (thread_group == nullptr) {
1949 *error = JDWP::ERR_INVALID_OBJECT;
1950 return nullptr;
1951 }
Ian Rogers98379392014-02-24 16:53:16 -08001952 mirror::Class* c = soa.Decode<mirror::Class*>(WellKnownClasses::java_lang_ThreadGroup);
1953 CHECK(c != nullptr);
Sebastien Hertza06430c2014-09-15 19:21:30 +02001954 if (!c->IsAssignableFrom(thread_group->GetClass())) {
1955 // This is not a java.lang.ThreadGroup.
1956 *error = JDWP::ERR_INVALID_THREAD_GROUP;
1957 return nullptr;
1958 }
1959 *error = JDWP::ERR_NONE;
1960 return thread_group;
1961}
1962
1963JDWP::JdwpError Dbg::GetThreadGroupName(JDWP::ObjectId thread_group_id, JDWP::ExpandBuf* pReply) {
1964 ScopedObjectAccessUnchecked soa(Thread::Current());
1965 JDWP::JdwpError error;
1966 mirror::Object* thread_group = DecodeThreadGroup(soa, thread_group_id, &error);
1967 if (error != JDWP::ERR_NONE) {
1968 return error;
1969 }
Mathieu Chartier2d5f39e2014-09-19 17:52:37 -07001970 ScopedAssertNoThreadSuspension ants(soa.Self(), "Debugger: GetThreadGroupName");
Mathieu Chartierc7853442015-03-27 14:35:38 -07001971 ArtField* f = soa.DecodeField(WellKnownClasses::java_lang_ThreadGroup_name);
Ian Rogersc0542af2014-09-03 16:16:56 -07001972 CHECK(f != nullptr);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001973 mirror::String* s = reinterpret_cast<mirror::String*>(f->GetObject(thread_group));
Sebastien Hertza06430c2014-09-15 19:21:30 +02001974
1975 std::string thread_group_name(s->ToModifiedUtf8());
1976 expandBufAddUtf8String(pReply, thread_group_name);
1977 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001978}
1979
Sebastien Hertza06430c2014-09-15 19:21:30 +02001980JDWP::JdwpError Dbg::GetThreadGroupParent(JDWP::ObjectId thread_group_id, JDWP::ExpandBuf* pReply) {
Ian Rogers98379392014-02-24 16:53:16 -08001981 ScopedObjectAccessUnchecked soa(Thread::Current());
Ian Rogersc0542af2014-09-03 16:16:56 -07001982 JDWP::JdwpError error;
Sebastien Hertza06430c2014-09-15 19:21:30 +02001983 mirror::Object* thread_group = DecodeThreadGroup(soa, thread_group_id, &error);
1984 if (error != JDWP::ERR_NONE) {
1985 return error;
1986 }
Mathieu Chartier2d5f39e2014-09-19 17:52:37 -07001987 mirror::Object* parent;
1988 {
1989 ScopedAssertNoThreadSuspension ants(soa.Self(), "Debugger: GetThreadGroupParent");
Mathieu Chartierc7853442015-03-27 14:35:38 -07001990 ArtField* f = soa.DecodeField(WellKnownClasses::java_lang_ThreadGroup_parent);
Mathieu Chartier2d5f39e2014-09-19 17:52:37 -07001991 CHECK(f != nullptr);
1992 parent = f->GetObject(thread_group);
1993 }
Sebastien Hertza06430c2014-09-15 19:21:30 +02001994 JDWP::ObjectId parent_group_id = gRegistry->Add(parent);
1995 expandBufAddObjectId(pReply, parent_group_id);
1996 return JDWP::ERR_NONE;
1997}
1998
1999static void GetChildThreadGroups(ScopedObjectAccessUnchecked& soa, mirror::Object* thread_group,
2000 std::vector<JDWP::ObjectId>* child_thread_group_ids)
Mathieu Chartier90443472015-07-16 20:32:27 -07002001 SHARED_REQUIRES(Locks::mutator_lock_) {
Sebastien Hertza06430c2014-09-15 19:21:30 +02002002 CHECK(thread_group != nullptr);
2003
2004 // Get the ArrayList<ThreadGroup> "groups" out of this thread group...
Mathieu Chartierc7853442015-03-27 14:35:38 -07002005 ArtField* groups_field = soa.DecodeField(WellKnownClasses::java_lang_ThreadGroup_groups);
Sebastien Hertza06430c2014-09-15 19:21:30 +02002006 mirror::Object* groups_array_list = groups_field->GetObject(thread_group);
Sebastien Hertze49e1952014-10-13 11:27:13 +02002007 {
2008 // The "groups" field is declared as a java.util.List: check it really is
2009 // an instance of java.util.ArrayList.
2010 CHECK(groups_array_list != nullptr);
2011 mirror::Class* java_util_ArrayList_class =
2012 soa.Decode<mirror::Class*>(WellKnownClasses::java_util_ArrayList);
2013 CHECK(groups_array_list->InstanceOf(java_util_ArrayList_class));
2014 }
Sebastien Hertza06430c2014-09-15 19:21:30 +02002015
2016 // Get the array and size out of the ArrayList<ThreadGroup>...
Mathieu Chartierc7853442015-03-27 14:35:38 -07002017 ArtField* array_field = soa.DecodeField(WellKnownClasses::java_util_ArrayList_array);
2018 ArtField* size_field = soa.DecodeField(WellKnownClasses::java_util_ArrayList_size);
Sebastien Hertza06430c2014-09-15 19:21:30 +02002019 mirror::ObjectArray<mirror::Object>* groups_array =
2020 array_field->GetObject(groups_array_list)->AsObjectArray<mirror::Object>();
2021 const int32_t size = size_field->GetInt(groups_array_list);
2022
2023 // Copy the first 'size' elements out of the array into the result.
Sebastien Hertz6995c602014-09-09 12:10:13 +02002024 ObjectRegistry* registry = Dbg::GetObjectRegistry();
Sebastien Hertza06430c2014-09-15 19:21:30 +02002025 for (int32_t i = 0; i < size; ++i) {
Sebastien Hertz6995c602014-09-09 12:10:13 +02002026 child_thread_group_ids->push_back(registry->Add(groups_array->Get(i)));
Sebastien Hertza06430c2014-09-15 19:21:30 +02002027 }
2028}
2029
2030JDWP::JdwpError Dbg::GetThreadGroupChildren(JDWP::ObjectId thread_group_id,
2031 JDWP::ExpandBuf* pReply) {
2032 ScopedObjectAccessUnchecked soa(Thread::Current());
2033 JDWP::JdwpError error;
2034 mirror::Object* thread_group = DecodeThreadGroup(soa, thread_group_id, &error);
2035 if (error != JDWP::ERR_NONE) {
2036 return error;
2037 }
2038
2039 // Add child threads.
2040 {
2041 std::vector<JDWP::ObjectId> child_thread_ids;
2042 GetThreads(thread_group, &child_thread_ids);
2043 expandBufAdd4BE(pReply, child_thread_ids.size());
2044 for (JDWP::ObjectId child_thread_id : child_thread_ids) {
2045 expandBufAddObjectId(pReply, child_thread_id);
2046 }
2047 }
2048
2049 // Add child thread groups.
2050 {
2051 std::vector<JDWP::ObjectId> child_thread_groups_ids;
2052 GetChildThreadGroups(soa, thread_group, &child_thread_groups_ids);
2053 expandBufAdd4BE(pReply, child_thread_groups_ids.size());
2054 for (JDWP::ObjectId child_thread_group_id : child_thread_groups_ids) {
2055 expandBufAddObjectId(pReply, child_thread_group_id);
2056 }
2057 }
2058
2059 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002060}
2061
2062JDWP::ObjectId Dbg::GetSystemThreadGroupId() {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002063 ScopedObjectAccessUnchecked soa(Thread::Current());
Mathieu Chartierc7853442015-03-27 14:35:38 -07002064 ArtField* f = soa.DecodeField(WellKnownClasses::java_lang_ThreadGroup_systemThreadGroup);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002065 mirror::Object* group = f->GetObject(f->GetDeclaringClass());
Ian Rogers365c1022012-06-22 15:05:28 -07002066 return gRegistry->Add(group);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002067}
2068
Jeff Hao920af3e2013-08-28 15:46:38 -07002069JDWP::JdwpThreadStatus Dbg::ToJdwpThreadStatus(ThreadState state) {
2070 switch (state) {
2071 case kBlocked:
2072 return JDWP::TS_MONITOR;
2073 case kNative:
2074 case kRunnable:
2075 case kSuspended:
2076 return JDWP::TS_RUNNING;
2077 case kSleeping:
2078 return JDWP::TS_SLEEPING;
2079 case kStarting:
2080 case kTerminated:
2081 return JDWP::TS_ZOMBIE;
2082 case kTimedWaiting:
Sebastien Hertzbae182c2013-12-17 10:42:03 +01002083 case kWaitingForCheckPointsToRun:
Jeff Hao920af3e2013-08-28 15:46:38 -07002084 case kWaitingForDebuggerSend:
2085 case kWaitingForDebuggerSuspension:
2086 case kWaitingForDebuggerToAttach:
Sebastien Hertz138dbfc2013-12-04 18:15:25 +01002087 case kWaitingForDeoptimization:
Jeff Hao920af3e2013-08-28 15:46:38 -07002088 case kWaitingForGcToComplete:
Mathieu Chartierb43390c2015-05-12 10:47:11 -07002089 case kWaitingForGetObjectsAllocated:
Jeff Hao920af3e2013-08-28 15:46:38 -07002090 case kWaitingForJniOnLoad:
Sebastien Hertzbae182c2013-12-17 10:42:03 +01002091 case kWaitingForMethodTracingStart:
Jeff Hao920af3e2013-08-28 15:46:38 -07002092 case kWaitingForSignalCatcherOutput:
Hiroshi Yamauchi0c8c3032015-01-16 16:54:35 -08002093 case kWaitingForVisitObjects:
Jeff Hao920af3e2013-08-28 15:46:38 -07002094 case kWaitingInMainDebuggerLoop:
2095 case kWaitingInMainSignalCatcherLoop:
2096 case kWaitingPerformingGc:
Mathieu Chartier90ef3db2015-08-04 15:19:41 -07002097 case kWaitingWeakGcRootRead:
Jeff Hao920af3e2013-08-28 15:46:38 -07002098 case kWaiting:
2099 return JDWP::TS_WAIT;
2100 // Don't add a 'default' here so the compiler can spot incompatible enum changes.
2101 }
2102 LOG(FATAL) << "Unknown thread state: " << state;
2103 return JDWP::TS_ZOMBIE;
2104}
2105
Sebastien Hertz52d131d2014-03-13 16:17:40 +01002106JDWP::JdwpError Dbg::GetThreadStatus(JDWP::ObjectId thread_id, JDWP::JdwpThreadStatus* pThreadStatus,
2107 JDWP::JdwpSuspendStatus* pSuspendStatus) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002108 ScopedObjectAccess soa(Thread::Current());
Elliott Hughes499c5132011-11-17 14:55:11 -08002109
Elliott Hughes9e0c1752013-01-09 14:02:58 -08002110 *pSuspendStatus = JDWP::SUSPEND_STATUS_NOT_SUSPENDED;
2111
Ian Rogersc0542af2014-09-03 16:16:56 -07002112 JDWP::JdwpError error;
2113 Thread* thread = DecodeThread(soa, thread_id, &error);
Elliott Hughes221229c2013-01-08 18:17:50 -08002114 if (error != JDWP::ERR_NONE) {
2115 if (error == JDWP::ERR_THREAD_NOT_ALIVE) {
2116 *pThreadStatus = JDWP::TS_ZOMBIE;
Elliott Hughes221229c2013-01-08 18:17:50 -08002117 return JDWP::ERR_NONE;
2118 }
2119 return error;
Elliott Hughes499c5132011-11-17 14:55:11 -08002120 }
2121
Elliott Hughes9e0c1752013-01-09 14:02:58 -08002122 if (IsSuspendedForDebugger(soa, thread)) {
2123 *pSuspendStatus = JDWP::SUSPEND_STATUS_SUSPENDED;
Elliott Hughes499c5132011-11-17 14:55:11 -08002124 }
2125
Jeff Hao920af3e2013-08-28 15:46:38 -07002126 *pThreadStatus = ToJdwpThreadStatus(thread->GetState());
Elliott Hughes221229c2013-01-08 18:17:50 -08002127 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002128}
2129
Elliott Hughes221229c2013-01-08 18:17:50 -08002130JDWP::JdwpError Dbg::GetThreadDebugSuspendCount(JDWP::ObjectId thread_id, JDWP::ExpandBuf* pReply) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002131 ScopedObjectAccess soa(Thread::Current());
Ian Rogersc0542af2014-09-03 16:16:56 -07002132 JDWP::JdwpError error;
2133 Thread* thread = DecodeThread(soa, thread_id, &error);
Elliott Hughes221229c2013-01-08 18:17:50 -08002134 if (error != JDWP::ERR_NONE) {
2135 return error;
Elliott Hughes2435a572012-02-17 16:07:41 -08002136 }
Ian Rogers50b35e22012-10-04 10:09:15 -07002137 MutexLock mu2(soa.Self(), *Locks::thread_suspend_count_lock_);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002138 expandBufAdd4BE(pReply, thread->GetDebugSuspendCount());
Elliott Hughes2435a572012-02-17 16:07:41 -08002139 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002140}
2141
Elliott Hughesf9501702013-01-11 11:22:27 -08002142JDWP::JdwpError Dbg::Interrupt(JDWP::ObjectId thread_id) {
2143 ScopedObjectAccess soa(Thread::Current());
Ian Rogersc0542af2014-09-03 16:16:56 -07002144 JDWP::JdwpError error;
2145 Thread* thread = DecodeThread(soa, thread_id, &error);
Elliott Hughesf9501702013-01-11 11:22:27 -08002146 if (error != JDWP::ERR_NONE) {
2147 return error;
2148 }
Ian Rogersdd7624d2014-03-14 17:43:00 -07002149 thread->Interrupt(soa.Self());
Elliott Hughesf9501702013-01-11 11:22:27 -08002150 return JDWP::ERR_NONE;
2151}
2152
Sebastien Hertz070f7322014-09-09 12:08:49 +02002153static bool IsInDesiredThreadGroup(ScopedObjectAccessUnchecked& soa,
2154 mirror::Object* desired_thread_group, mirror::Object* peer)
Mathieu Chartier90443472015-07-16 20:32:27 -07002155 SHARED_REQUIRES(Locks::mutator_lock_) {
Sebastien Hertz070f7322014-09-09 12:08:49 +02002156 // Do we want threads from all thread groups?
2157 if (desired_thread_group == nullptr) {
2158 return true;
2159 }
Mathieu Chartierc7853442015-03-27 14:35:38 -07002160 ArtField* thread_group_field = soa.DecodeField(WellKnownClasses::java_lang_Thread_group);
Sebastien Hertz070f7322014-09-09 12:08:49 +02002161 DCHECK(thread_group_field != nullptr);
2162 mirror::Object* group = thread_group_field->GetObject(peer);
2163 return (group == desired_thread_group);
2164}
2165
Sebastien Hertza06430c2014-09-15 19:21:30 +02002166void Dbg::GetThreads(mirror::Object* thread_group, std::vector<JDWP::ObjectId>* thread_ids) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002167 ScopedObjectAccessUnchecked soa(Thread::Current());
Sebastien Hertz070f7322014-09-09 12:08:49 +02002168 std::list<Thread*> all_threads_list;
2169 {
2170 MutexLock mu(Thread::Current(), *Locks::thread_list_lock_);
2171 all_threads_list = Runtime::Current()->GetThreadList()->GetList();
2172 }
2173 for (Thread* t : all_threads_list) {
2174 if (t == Dbg::GetDebugThread()) {
2175 // Skip the JDWP thread. Some debuggers get bent out of shape when they can't suspend and
2176 // query all threads, so it's easier if we just don't tell them about this thread.
2177 continue;
2178 }
2179 if (t->IsStillStarting()) {
2180 // This thread is being started (and has been registered in the thread list). However, it is
2181 // not completely started yet so we must ignore it.
2182 continue;
2183 }
2184 mirror::Object* peer = t->GetPeer();
2185 if (peer == nullptr) {
Mathieu Chartier2cebb242015-04-21 16:50:40 -07002186 // 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 +02002187 // this thread yet.
2188 // TODO: if we identified threads to the debugger by their Thread*
2189 // rather than their peer's mirror::Object*, we could fix this.
2190 // Doing so might help us report ZOMBIE threads too.
2191 continue;
2192 }
2193 if (IsInDesiredThreadGroup(soa, thread_group, peer)) {
2194 thread_ids->push_back(gRegistry->Add(peer));
2195 }
2196 }
Elliott Hughescaf76542012-06-28 16:08:22 -07002197}
Elliott Hughesa2155262011-11-16 16:26:58 -08002198
Mathieu Chartier90443472015-07-16 20:32:27 -07002199static int GetStackDepth(Thread* thread) SHARED_REQUIRES(Locks::mutator_lock_) {
Ian Rogers0399dde2012-06-06 17:09:28 -07002200 struct CountStackDepthVisitor : public StackVisitor {
Andreas Gampe277ccbd2014-11-03 21:36:10 -08002201 explicit CountStackDepthVisitor(Thread* thread_in)
Nicolas Geoffray8e5bd182015-05-06 11:34:34 +01002202 : StackVisitor(thread_in, nullptr, StackVisitor::StackWalkKind::kIncludeInlinedFrames),
2203 depth(0) {}
Ian Rogers0399dde2012-06-06 17:09:28 -07002204
Elliott Hughes64f574f2013-02-20 14:57:12 -08002205 // TODO: Enable annotalysis. We know lock is held in constructor, but abstraction confuses
2206 // annotalysis.
2207 bool VisitFrame() NO_THREAD_SAFETY_ANALYSIS {
Ian Rogers0399dde2012-06-06 17:09:28 -07002208 if (!GetMethod()->IsRuntimeMethod()) {
Elliott Hughesf8a2df72011-12-01 12:19:54 -08002209 ++depth;
2210 }
Elliott Hughes530fa002012-03-12 11:44:49 -07002211 return true;
Elliott Hughesa2e54f62011-11-17 13:01:30 -08002212 }
2213 size_t depth;
2214 };
Elliott Hughes08fc03a2012-06-26 17:34:00 -07002215
Ian Rogers7a22fa62013-01-23 12:16:16 -08002216 CountStackDepthVisitor visitor(thread);
Ian Rogers0399dde2012-06-06 17:09:28 -07002217 visitor.WalkStack();
Elliott Hughesa2e54f62011-11-17 13:01:30 -08002218 return visitor.depth;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002219}
2220
Ian Rogersc0542af2014-09-03 16:16:56 -07002221JDWP::JdwpError Dbg::GetThreadFrameCount(JDWP::ObjectId thread_id, size_t* result) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002222 ScopedObjectAccess soa(Thread::Current());
Ian Rogersc0542af2014-09-03 16:16:56 -07002223 JDWP::JdwpError error;
2224 *result = 0;
2225 Thread* thread = DecodeThread(soa, thread_id, &error);
Elliott Hughes221229c2013-01-08 18:17:50 -08002226 if (error != JDWP::ERR_NONE) {
2227 return error;
2228 }
Elliott Hughesf15f4a02013-01-09 10:09:38 -08002229 if (!IsSuspendedForDebugger(soa, thread)) {
2230 return JDWP::ERR_THREAD_NOT_SUSPENDED;
2231 }
Ian Rogersc0542af2014-09-03 16:16:56 -07002232 *result = GetStackDepth(thread);
Elliott Hughes221229c2013-01-08 18:17:50 -08002233 return JDWP::ERR_NONE;
Elliott Hughes86964332012-02-15 19:37:42 -08002234}
2235
Ian Rogers306057f2012-11-26 12:45:53 -08002236JDWP::JdwpError Dbg::GetThreadFrames(JDWP::ObjectId thread_id, size_t start_frame,
2237 size_t frame_count, JDWP::ExpandBuf* buf) {
Elliott Hughes6e9d22c2012-06-22 15:02:37 -07002238 class GetFrameVisitor : public StackVisitor {
2239 public:
Andreas Gampe277ccbd2014-11-03 21:36:10 -08002240 GetFrameVisitor(Thread* thread, size_t start_frame_in, size_t frame_count_in,
2241 JDWP::ExpandBuf* buf_in)
Mathieu Chartier90443472015-07-16 20:32:27 -07002242 SHARED_REQUIRES(Locks::mutator_lock_)
Nicolas Geoffray8e5bd182015-05-06 11:34:34 +01002243 : StackVisitor(thread, nullptr, StackVisitor::StackWalkKind::kIncludeInlinedFrames),
2244 depth_(0),
2245 start_frame_(start_frame_in),
2246 frame_count_(frame_count_in),
2247 buf_(buf_in) {
Elliott Hughes6e9d22c2012-06-22 15:02:37 -07002248 expandBufAdd4BE(buf_, frame_count_);
Elliott Hughes03181a82011-11-17 17:22:21 -08002249 }
Ian Rogers0399dde2012-06-06 17:09:28 -07002250
Mathieu Chartier90443472015-07-16 20:32:27 -07002251 bool VisitFrame() OVERRIDE SHARED_REQUIRES(Locks::mutator_lock_) {
Ian Rogers0399dde2012-06-06 17:09:28 -07002252 if (GetMethod()->IsRuntimeMethod()) {
Brian Carlstrom7934ac22013-07-26 10:54:15 -07002253 return true; // The debugger can't do anything useful with a frame that has no Method*.
Elliott Hughes03181a82011-11-17 17:22:21 -08002254 }
Elliott Hughes6e9d22c2012-06-22 15:02:37 -07002255 if (depth_ >= start_frame_ + frame_count_) {
Elliott Hughes530fa002012-03-12 11:44:49 -07002256 return false;
Elliott Hughes03181a82011-11-17 17:22:21 -08002257 }
Elliott Hughes6e9d22c2012-06-22 15:02:37 -07002258 if (depth_ >= start_frame_) {
2259 JDWP::FrameId frame_id(GetFrameId());
2260 JDWP::JdwpLocation location;
Sebastien Hertz6995c602014-09-09 12:10:13 +02002261 SetJdwpLocation(&location, GetMethod(), GetDexPc());
Ian Rogersef7d42f2014-01-06 12:55:46 -08002262 VLOG(jdwp) << StringPrintf(" Frame %3zd: id=%3" PRIu64 " ", depth_, frame_id) << location;
Elliott Hughes6e9d22c2012-06-22 15:02:37 -07002263 expandBufAdd8BE(buf_, frame_id);
2264 expandBufAddLocation(buf_, location);
2265 }
2266 ++depth_;
Elliott Hughes530fa002012-03-12 11:44:49 -07002267 return true;
Elliott Hughes03181a82011-11-17 17:22:21 -08002268 }
Elliott Hughes6e9d22c2012-06-22 15:02:37 -07002269
2270 private:
2271 size_t depth_;
2272 const size_t start_frame_;
2273 const size_t frame_count_;
2274 JDWP::ExpandBuf* buf_;
Elliott Hughes03181a82011-11-17 17:22:21 -08002275 };
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002276
2277 ScopedObjectAccessUnchecked soa(Thread::Current());
Ian Rogersc0542af2014-09-03 16:16:56 -07002278 JDWP::JdwpError error;
2279 Thread* thread = DecodeThread(soa, thread_id, &error);
Elliott Hughes221229c2013-01-08 18:17:50 -08002280 if (error != JDWP::ERR_NONE) {
2281 return error;
2282 }
Elliott Hughesf15f4a02013-01-09 10:09:38 -08002283 if (!IsSuspendedForDebugger(soa, thread)) {
2284 return JDWP::ERR_THREAD_NOT_SUSPENDED;
2285 }
Ian Rogers7a22fa62013-01-23 12:16:16 -08002286 GetFrameVisitor visitor(thread, start_frame, frame_count, buf);
Ian Rogers0399dde2012-06-06 17:09:28 -07002287 visitor.WalkStack();
Elliott Hughes6e9d22c2012-06-22 15:02:37 -07002288 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002289}
2290
2291JDWP::ObjectId Dbg::GetThreadSelfId() {
Sebastien Hertz6995c602014-09-09 12:10:13 +02002292 return GetThreadId(Thread::Current());
2293}
2294
2295JDWP::ObjectId Dbg::GetThreadId(Thread* thread) {
Mathieu Chartierdbe6f462012-09-25 16:54:50 -07002296 ScopedObjectAccessUnchecked soa(Thread::Current());
Sebastien Hertz6995c602014-09-09 12:10:13 +02002297 return gRegistry->Add(thread->GetPeer());
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002298}
2299
Elliott Hughes475fc232011-10-25 15:00:35 -07002300void Dbg::SuspendVM() {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002301 Runtime::Current()->GetThreadList()->SuspendAllForDebugger();
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002302}
2303
2304void Dbg::ResumeVM() {
Sebastien Hertz253fa552014-10-14 17:27:15 +02002305 Runtime::Current()->GetThreadList()->ResumeAllForDebugger();
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002306}
2307
Elliott Hughes221229c2013-01-08 18:17:50 -08002308JDWP::JdwpError Dbg::SuspendThread(JDWP::ObjectId thread_id, bool request_suspension) {
Ian Rogersf3d874c2014-07-17 18:52:42 -07002309 Thread* self = Thread::Current();
Ian Rogersc0542af2014-09-03 16:16:56 -07002310 ScopedLocalRef<jobject> peer(self->GetJniEnv(), nullptr);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002311 {
Ian Rogersf3d874c2014-07-17 18:52:42 -07002312 ScopedObjectAccess soa(self);
Ian Rogersc0542af2014-09-03 16:16:56 -07002313 JDWP::JdwpError error;
2314 peer.reset(soa.AddLocalReference<jobject>(gRegistry->Get<mirror::Object*>(thread_id, &error)));
Elliott Hughes4e235312011-12-02 11:34:15 -08002315 }
Ian Rogersc0542af2014-09-03 16:16:56 -07002316 if (peer.get() == nullptr) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002317 return JDWP::ERR_THREAD_NOT_ALIVE;
2318 }
Ian Rogers4ad5cd32014-11-11 23:08:07 -08002319 // Suspend thread to build stack trace.
Elliott Hughesf327e072013-01-09 16:01:26 -08002320 bool timed_out;
Brian Carlstromba32de42014-08-27 23:43:46 -07002321 ThreadList* thread_list = Runtime::Current()->GetThreadList();
2322 Thread* thread = thread_list->SuspendThreadByPeer(peer.get(), request_suspension, true,
2323 &timed_out);
Ian Rogersc0542af2014-09-03 16:16:56 -07002324 if (thread != nullptr) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002325 return JDWP::ERR_NONE;
Elliott Hughesf327e072013-01-09 16:01:26 -08002326 } else if (timed_out) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002327 return JDWP::ERR_INTERNAL;
2328 } else {
2329 return JDWP::ERR_THREAD_NOT_ALIVE;
2330 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002331}
2332
Elliott Hughes221229c2013-01-08 18:17:50 -08002333void Dbg::ResumeThread(JDWP::ObjectId thread_id) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002334 ScopedObjectAccessUnchecked soa(Thread::Current());
Ian Rogersc0542af2014-09-03 16:16:56 -07002335 JDWP::JdwpError error;
2336 mirror::Object* peer = gRegistry->Get<mirror::Object*>(thread_id, &error);
2337 CHECK(peer != nullptr) << error;
jeffhaoa77f0f62012-12-05 17:19:31 -08002338 Thread* thread;
2339 {
2340 MutexLock mu(soa.Self(), *Locks::thread_list_lock_);
2341 thread = Thread::FromManagedThread(soa, peer);
2342 }
Ian Rogersc0542af2014-09-03 16:16:56 -07002343 if (thread == nullptr) {
Elliott Hughes4e235312011-12-02 11:34:15 -08002344 LOG(WARNING) << "No such thread for resume: " << peer;
2345 return;
2346 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002347 bool needs_resume;
2348 {
Ian Rogers50b35e22012-10-04 10:09:15 -07002349 MutexLock mu2(soa.Self(), *Locks::thread_suspend_count_lock_);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002350 needs_resume = thread->GetSuspendCount() > 0;
2351 }
2352 if (needs_resume) {
Elliott Hughes546b9862012-06-20 16:06:13 -07002353 Runtime::Current()->GetThreadList()->Resume(thread, true);
2354 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002355}
2356
2357void Dbg::SuspendSelf() {
Elliott Hughes475fc232011-10-25 15:00:35 -07002358 Runtime::Current()->GetThreadList()->SuspendSelfForDebugger();
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002359}
2360
Ian Rogers0399dde2012-06-06 17:09:28 -07002361struct GetThisVisitor : public StackVisitor {
Andreas Gampe277ccbd2014-11-03 21:36:10 -08002362 GetThisVisitor(Thread* thread, Context* context, JDWP::FrameId frame_id_in)
Mathieu Chartier90443472015-07-16 20:32:27 -07002363 SHARED_REQUIRES(Locks::mutator_lock_)
Nicolas Geoffray8e5bd182015-05-06 11:34:34 +01002364 : StackVisitor(thread, context, StackVisitor::StackWalkKind::kIncludeInlinedFrames),
2365 this_object(nullptr),
2366 frame_id(frame_id_in) {}
Ian Rogers0399dde2012-06-06 17:09:28 -07002367
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002368 // TODO: Enable annotalysis. We know lock is held in constructor, but abstraction confuses
2369 // annotalysis.
2370 virtual bool VisitFrame() NO_THREAD_SAFETY_ANALYSIS {
Elliott Hughes6e9d22c2012-06-22 15:02:37 -07002371 if (frame_id != GetFrameId()) {
Ian Rogers0399dde2012-06-06 17:09:28 -07002372 return true; // continue
Ian Rogers0399dde2012-06-06 17:09:28 -07002373 } else {
Ian Rogers62d6c772013-02-27 08:32:07 -08002374 this_object = GetThisObject();
2375 return false;
Ian Rogers0399dde2012-06-06 17:09:28 -07002376 }
Elliott Hughes86b00102011-12-05 17:54:26 -08002377 }
Ian Rogers0399dde2012-06-06 17:09:28 -07002378
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002379 mirror::Object* this_object;
Elliott Hughes6e9d22c2012-06-22 15:02:37 -07002380 JDWP::FrameId frame_id;
Ian Rogers0399dde2012-06-06 17:09:28 -07002381};
2382
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002383JDWP::JdwpError Dbg::GetThisObject(JDWP::ObjectId thread_id, JDWP::FrameId frame_id,
2384 JDWP::ObjectId* result) {
2385 ScopedObjectAccessUnchecked soa(Thread::Current());
Sebastien Hertz69206392015-04-07 15:54:25 +02002386 JDWP::JdwpError error;
2387 Thread* thread = DecodeThread(soa, thread_id, &error);
2388 if (error != JDWP::ERR_NONE) {
2389 return error;
2390 }
2391 if (!IsSuspendedForDebugger(soa, thread)) {
2392 return JDWP::ERR_THREAD_NOT_SUSPENDED;
Elliott Hughes6e9d22c2012-06-22 15:02:37 -07002393 }
Ian Rogers700a4022014-05-19 16:49:03 -07002394 std::unique_ptr<Context> context(Context::Create());
Ian Rogers7a22fa62013-01-23 12:16:16 -08002395 GetThisVisitor visitor(thread, context.get(), frame_id);
Ian Rogers0399dde2012-06-06 17:09:28 -07002396 visitor.WalkStack();
Elliott Hughes6e9d22c2012-06-22 15:02:37 -07002397 *result = gRegistry->Add(visitor.this_object);
2398 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002399}
2400
Sebastien Hertz8009f392014-09-01 17:07:11 +02002401// Walks the stack until we find the frame with the given FrameId.
2402class FindFrameVisitor FINAL : public StackVisitor {
2403 public:
2404 FindFrameVisitor(Thread* thread, Context* context, JDWP::FrameId frame_id)
Mathieu Chartier90443472015-07-16 20:32:27 -07002405 SHARED_REQUIRES(Locks::mutator_lock_)
Nicolas Geoffray8e5bd182015-05-06 11:34:34 +01002406 : StackVisitor(thread, context, StackVisitor::StackWalkKind::kIncludeInlinedFrames),
2407 frame_id_(frame_id),
2408 error_(JDWP::ERR_INVALID_FRAMEID) {}
Ian Rogersca190662012-06-26 15:45:57 -07002409
Sebastien Hertz8009f392014-09-01 17:07:11 +02002410 // TODO: Enable annotalysis. We know lock is held in constructor, but abstraction confuses
2411 // annotalysis.
2412 bool VisitFrame() NO_THREAD_SAFETY_ANALYSIS {
2413 if (GetFrameId() != frame_id_) {
2414 return true; // Not our frame, carry on.
Ian Rogers0399dde2012-06-06 17:09:28 -07002415 }
Mathieu Chartiere401d142015-04-22 13:56:20 -07002416 ArtMethod* m = GetMethod();
Sebastien Hertz8009f392014-09-01 17:07:11 +02002417 if (m->IsNative()) {
2418 // We can't read/write local value from/into native method.
2419 error_ = JDWP::ERR_OPAQUE_FRAME;
2420 } else {
2421 // We found our frame.
2422 error_ = JDWP::ERR_NONE;
2423 }
2424 return false;
2425 }
2426
2427 JDWP::JdwpError GetError() const {
2428 return error_;
2429 }
2430
2431 private:
2432 const JDWP::FrameId frame_id_;
2433 JDWP::JdwpError error_;
2434};
2435
2436JDWP::JdwpError Dbg::GetLocalValues(JDWP::Request* request, JDWP::ExpandBuf* pReply) {
2437 JDWP::ObjectId thread_id = request->ReadThreadId();
2438 JDWP::FrameId frame_id = request->ReadFrameId();
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002439
2440 ScopedObjectAccessUnchecked soa(Thread::Current());
Sebastien Hertz69206392015-04-07 15:54:25 +02002441 JDWP::JdwpError error;
2442 Thread* thread = DecodeThread(soa, thread_id, &error);
2443 if (error != JDWP::ERR_NONE) {
2444 return error;
2445 }
2446 if (!IsSuspendedForDebugger(soa, thread)) {
2447 return JDWP::ERR_THREAD_NOT_SUSPENDED;
Elliott Hughes221229c2013-01-08 18:17:50 -08002448 }
Sebastien Hertz8009f392014-09-01 17:07:11 +02002449 // Find the frame with the given frame_id.
Ian Rogers700a4022014-05-19 16:49:03 -07002450 std::unique_ptr<Context> context(Context::Create());
Sebastien Hertz8009f392014-09-01 17:07:11 +02002451 FindFrameVisitor visitor(thread, context.get(), frame_id);
Ian Rogers0399dde2012-06-06 17:09:28 -07002452 visitor.WalkStack();
Sebastien Hertz8009f392014-09-01 17:07:11 +02002453 if (visitor.GetError() != JDWP::ERR_NONE) {
2454 return visitor.GetError();
2455 }
2456
2457 // Read the values from visitor's context.
2458 int32_t slot_count = request->ReadSigned32("slot count");
2459 expandBufAdd4BE(pReply, slot_count); /* "int values" */
2460 for (int32_t i = 0; i < slot_count; ++i) {
2461 uint32_t slot = request->ReadUnsigned32("slot");
2462 JDWP::JdwpTag reqSigByte = request->ReadTag();
2463
2464 VLOG(jdwp) << " --> slot " << slot << " " << reqSigByte;
2465
2466 size_t width = Dbg::GetTagWidth(reqSigByte);
Sebastien Hertz7d955652014-10-22 10:57:10 +02002467 uint8_t* ptr = expandBufAddSpace(pReply, width + 1);
Sebastien Hertz69206392015-04-07 15:54:25 +02002468 error = Dbg::GetLocalValue(visitor, soa, slot, reqSigByte, ptr, width);
Sebastien Hertz8009f392014-09-01 17:07:11 +02002469 if (error != JDWP::ERR_NONE) {
2470 return error;
2471 }
2472 }
2473 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002474}
2475
Sebastien Hertzabbabc82015-03-26 08:47:47 +01002476constexpr JDWP::JdwpError kStackFrameLocalAccessError = JDWP::ERR_ABSENT_INFORMATION;
2477
2478static std::string GetStackContextAsString(const StackVisitor& visitor)
Mathieu Chartier90443472015-07-16 20:32:27 -07002479 SHARED_REQUIRES(Locks::mutator_lock_) {
Sebastien Hertzabbabc82015-03-26 08:47:47 +01002480 return StringPrintf(" at DEX pc 0x%08x in method %s", visitor.GetDexPc(false),
2481 PrettyMethod(visitor.GetMethod()).c_str());
2482}
2483
2484static JDWP::JdwpError FailGetLocalValue(const StackVisitor& visitor, uint16_t vreg,
2485 JDWP::JdwpTag tag)
Mathieu Chartier90443472015-07-16 20:32:27 -07002486 SHARED_REQUIRES(Locks::mutator_lock_) {
Sebastien Hertzabbabc82015-03-26 08:47:47 +01002487 LOG(ERROR) << "Failed to read " << tag << " local from register v" << vreg
2488 << GetStackContextAsString(visitor);
2489 return kStackFrameLocalAccessError;
2490}
2491
Sebastien Hertz8009f392014-09-01 17:07:11 +02002492JDWP::JdwpError Dbg::GetLocalValue(const StackVisitor& visitor, ScopedObjectAccessUnchecked& soa,
2493 int slot, JDWP::JdwpTag tag, uint8_t* buf, size_t width) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07002494 ArtMethod* m = visitor.GetMethod();
Sebastien Hertzabbabc82015-03-26 08:47:47 +01002495 JDWP::JdwpError error = JDWP::ERR_NONE;
2496 uint16_t vreg = DemangleSlot(slot, m, &error);
2497 if (error != JDWP::ERR_NONE) {
2498 return error;
2499 }
Sebastien Hertz8009f392014-09-01 17:07:11 +02002500 // TODO: check that the tag is compatible with the actual type of the slot!
Sebastien Hertz8009f392014-09-01 17:07:11 +02002501 switch (tag) {
2502 case JDWP::JT_BOOLEAN: {
2503 CHECK_EQ(width, 1U);
2504 uint32_t intVal;
Sebastien Hertzabbabc82015-03-26 08:47:47 +01002505 if (!visitor.GetVReg(m, vreg, kIntVReg, &intVal)) {
2506 return FailGetLocalValue(visitor, vreg, tag);
Ian Rogers0399dde2012-06-06 17:09:28 -07002507 }
Sebastien Hertzabbabc82015-03-26 08:47:47 +01002508 VLOG(jdwp) << "get boolean local " << vreg << " = " << intVal;
2509 JDWP::Set1(buf + 1, intVal != 0);
Sebastien Hertz8009f392014-09-01 17:07:11 +02002510 break;
Ian Rogers0399dde2012-06-06 17:09:28 -07002511 }
Sebastien Hertz8009f392014-09-01 17:07:11 +02002512 case JDWP::JT_BYTE: {
2513 CHECK_EQ(width, 1U);
2514 uint32_t intVal;
Sebastien Hertzabbabc82015-03-26 08:47:47 +01002515 if (!visitor.GetVReg(m, vreg, kIntVReg, &intVal)) {
2516 return FailGetLocalValue(visitor, vreg, tag);
Sebastien Hertz8009f392014-09-01 17:07:11 +02002517 }
Sebastien Hertzabbabc82015-03-26 08:47:47 +01002518 VLOG(jdwp) << "get byte local " << vreg << " = " << intVal;
2519 JDWP::Set1(buf + 1, intVal);
Sebastien Hertz8009f392014-09-01 17:07:11 +02002520 break;
2521 }
2522 case JDWP::JT_SHORT:
2523 case JDWP::JT_CHAR: {
2524 CHECK_EQ(width, 2U);
2525 uint32_t intVal;
Sebastien Hertzabbabc82015-03-26 08:47:47 +01002526 if (!visitor.GetVReg(m, vreg, kIntVReg, &intVal)) {
2527 return FailGetLocalValue(visitor, vreg, tag);
Sebastien Hertz8009f392014-09-01 17:07:11 +02002528 }
Sebastien Hertzabbabc82015-03-26 08:47:47 +01002529 VLOG(jdwp) << "get short/char local " << vreg << " = " << intVal;
2530 JDWP::Set2BE(buf + 1, intVal);
Sebastien Hertz8009f392014-09-01 17:07:11 +02002531 break;
2532 }
2533 case JDWP::JT_INT: {
2534 CHECK_EQ(width, 4U);
2535 uint32_t intVal;
Sebastien Hertzabbabc82015-03-26 08:47:47 +01002536 if (!visitor.GetVReg(m, vreg, kIntVReg, &intVal)) {
2537 return FailGetLocalValue(visitor, vreg, tag);
Sebastien Hertz8009f392014-09-01 17:07:11 +02002538 }
Sebastien Hertzabbabc82015-03-26 08:47:47 +01002539 VLOG(jdwp) << "get int local " << vreg << " = " << intVal;
2540 JDWP::Set4BE(buf + 1, intVal);
Sebastien Hertz8009f392014-09-01 17:07:11 +02002541 break;
2542 }
2543 case JDWP::JT_FLOAT: {
2544 CHECK_EQ(width, 4U);
2545 uint32_t intVal;
Sebastien Hertzabbabc82015-03-26 08:47:47 +01002546 if (!visitor.GetVReg(m, vreg, kFloatVReg, &intVal)) {
2547 return FailGetLocalValue(visitor, vreg, tag);
Sebastien Hertz8009f392014-09-01 17:07:11 +02002548 }
Sebastien Hertzabbabc82015-03-26 08:47:47 +01002549 VLOG(jdwp) << "get float local " << vreg << " = " << intVal;
2550 JDWP::Set4BE(buf + 1, intVal);
Sebastien Hertz8009f392014-09-01 17:07:11 +02002551 break;
2552 }
2553 case JDWP::JT_ARRAY:
2554 case JDWP::JT_CLASS_LOADER:
2555 case JDWP::JT_CLASS_OBJECT:
2556 case JDWP::JT_OBJECT:
2557 case JDWP::JT_STRING:
2558 case JDWP::JT_THREAD:
2559 case JDWP::JT_THREAD_GROUP: {
2560 CHECK_EQ(width, sizeof(JDWP::ObjectId));
2561 uint32_t intVal;
Sebastien Hertzabbabc82015-03-26 08:47:47 +01002562 if (!visitor.GetVReg(m, vreg, kReferenceVReg, &intVal)) {
2563 return FailGetLocalValue(visitor, vreg, tag);
Sebastien Hertz8009f392014-09-01 17:07:11 +02002564 }
Sebastien Hertzabbabc82015-03-26 08:47:47 +01002565 mirror::Object* o = reinterpret_cast<mirror::Object*>(intVal);
2566 VLOG(jdwp) << "get " << tag << " object local " << vreg << " = " << o;
2567 if (!Runtime::Current()->GetHeap()->IsValidObjectAddress(o)) {
2568 LOG(FATAL) << StringPrintf("Found invalid object %#" PRIxPTR " in register v%u",
2569 reinterpret_cast<uintptr_t>(o), vreg)
2570 << GetStackContextAsString(visitor);
2571 UNREACHABLE();
2572 }
2573 tag = TagFromObject(soa, o);
2574 JDWP::SetObjectId(buf + 1, gRegistry->Add(o));
Sebastien Hertz8009f392014-09-01 17:07:11 +02002575 break;
2576 }
2577 case JDWP::JT_DOUBLE: {
2578 CHECK_EQ(width, 8U);
2579 uint64_t longVal;
Sebastien Hertzabbabc82015-03-26 08:47:47 +01002580 if (!visitor.GetVRegPair(m, vreg, kDoubleLoVReg, kDoubleHiVReg, &longVal)) {
2581 return FailGetLocalValue(visitor, vreg, tag);
Sebastien Hertz8009f392014-09-01 17:07:11 +02002582 }
Sebastien Hertzabbabc82015-03-26 08:47:47 +01002583 VLOG(jdwp) << "get double local " << vreg << " = " << longVal;
2584 JDWP::Set8BE(buf + 1, longVal);
Sebastien Hertz8009f392014-09-01 17:07:11 +02002585 break;
2586 }
2587 case JDWP::JT_LONG: {
2588 CHECK_EQ(width, 8U);
2589 uint64_t longVal;
Sebastien Hertzabbabc82015-03-26 08:47:47 +01002590 if (!visitor.GetVRegPair(m, vreg, kLongLoVReg, kLongHiVReg, &longVal)) {
2591 return FailGetLocalValue(visitor, vreg, tag);
Sebastien Hertz8009f392014-09-01 17:07:11 +02002592 }
Sebastien Hertzabbabc82015-03-26 08:47:47 +01002593 VLOG(jdwp) << "get long local " << vreg << " = " << longVal;
2594 JDWP::Set8BE(buf + 1, longVal);
Sebastien Hertz8009f392014-09-01 17:07:11 +02002595 break;
2596 }
2597 default:
2598 LOG(FATAL) << "Unknown tag " << tag;
Sebastien Hertzabbabc82015-03-26 08:47:47 +01002599 UNREACHABLE();
Sebastien Hertz8009f392014-09-01 17:07:11 +02002600 }
Ian Rogers0399dde2012-06-06 17:09:28 -07002601
Sebastien Hertz8009f392014-09-01 17:07:11 +02002602 // Prepend tag, which may have been updated.
2603 JDWP::Set1(buf, tag);
2604 return JDWP::ERR_NONE;
2605}
2606
2607JDWP::JdwpError Dbg::SetLocalValues(JDWP::Request* request) {
2608 JDWP::ObjectId thread_id = request->ReadThreadId();
2609 JDWP::FrameId frame_id = request->ReadFrameId();
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002610
2611 ScopedObjectAccessUnchecked soa(Thread::Current());
Sebastien Hertz69206392015-04-07 15:54:25 +02002612 JDWP::JdwpError error;
2613 Thread* thread = DecodeThread(soa, thread_id, &error);
2614 if (error != JDWP::ERR_NONE) {
2615 return error;
2616 }
2617 if (!IsSuspendedForDebugger(soa, thread)) {
2618 return JDWP::ERR_THREAD_NOT_SUSPENDED;
Elliott Hughes221229c2013-01-08 18:17:50 -08002619 }
Sebastien Hertz8009f392014-09-01 17:07:11 +02002620 // Find the frame with the given frame_id.
Ian Rogers700a4022014-05-19 16:49:03 -07002621 std::unique_ptr<Context> context(Context::Create());
Sebastien Hertz8009f392014-09-01 17:07:11 +02002622 FindFrameVisitor visitor(thread, context.get(), frame_id);
Ian Rogers0399dde2012-06-06 17:09:28 -07002623 visitor.WalkStack();
Sebastien Hertz8009f392014-09-01 17:07:11 +02002624 if (visitor.GetError() != JDWP::ERR_NONE) {
2625 return visitor.GetError();
2626 }
2627
2628 // Writes the values into visitor's context.
2629 int32_t slot_count = request->ReadSigned32("slot count");
2630 for (int32_t i = 0; i < slot_count; ++i) {
2631 uint32_t slot = request->ReadUnsigned32("slot");
2632 JDWP::JdwpTag sigByte = request->ReadTag();
2633 size_t width = Dbg::GetTagWidth(sigByte);
2634 uint64_t value = request->ReadValue(width);
2635
2636 VLOG(jdwp) << " --> slot " << slot << " " << sigByte << " " << value;
Sebastien Hertz69206392015-04-07 15:54:25 +02002637 error = Dbg::SetLocalValue(visitor, slot, sigByte, value, width);
Sebastien Hertz8009f392014-09-01 17:07:11 +02002638 if (error != JDWP::ERR_NONE) {
2639 return error;
2640 }
2641 }
2642 return JDWP::ERR_NONE;
2643}
2644
Sebastien Hertzabbabc82015-03-26 08:47:47 +01002645template<typename T>
2646static JDWP::JdwpError FailSetLocalValue(const StackVisitor& visitor, uint16_t vreg,
2647 JDWP::JdwpTag tag, T value)
Mathieu Chartier90443472015-07-16 20:32:27 -07002648 SHARED_REQUIRES(Locks::mutator_lock_) {
Sebastien Hertzabbabc82015-03-26 08:47:47 +01002649 LOG(ERROR) << "Failed to write " << tag << " local " << value
2650 << " (0x" << std::hex << value << ") into register v" << vreg
2651 << GetStackContextAsString(visitor);
2652 return kStackFrameLocalAccessError;
2653}
2654
Sebastien Hertz8009f392014-09-01 17:07:11 +02002655JDWP::JdwpError Dbg::SetLocalValue(StackVisitor& visitor, int slot, JDWP::JdwpTag tag,
2656 uint64_t value, size_t width) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07002657 ArtMethod* m = visitor.GetMethod();
Sebastien Hertzabbabc82015-03-26 08:47:47 +01002658 JDWP::JdwpError error = JDWP::ERR_NONE;
2659 uint16_t vreg = DemangleSlot(slot, m, &error);
2660 if (error != JDWP::ERR_NONE) {
2661 return error;
2662 }
Sebastien Hertz8009f392014-09-01 17:07:11 +02002663 // TODO: check that the tag is compatible with the actual type of the slot!
Sebastien Hertz8009f392014-09-01 17:07:11 +02002664 switch (tag) {
2665 case JDWP::JT_BOOLEAN:
2666 case JDWP::JT_BYTE:
2667 CHECK_EQ(width, 1U);
Sebastien Hertzabbabc82015-03-26 08:47:47 +01002668 if (!visitor.SetVReg(m, vreg, static_cast<uint32_t>(value), kIntVReg)) {
2669 return FailSetLocalValue(visitor, vreg, tag, static_cast<uint32_t>(value));
Sebastien Hertz8009f392014-09-01 17:07:11 +02002670 }
2671 break;
2672 case JDWP::JT_SHORT:
2673 case JDWP::JT_CHAR:
2674 CHECK_EQ(width, 2U);
Sebastien Hertzabbabc82015-03-26 08:47:47 +01002675 if (!visitor.SetVReg(m, vreg, static_cast<uint32_t>(value), kIntVReg)) {
2676 return FailSetLocalValue(visitor, vreg, tag, static_cast<uint32_t>(value));
Sebastien Hertz8009f392014-09-01 17:07:11 +02002677 }
2678 break;
2679 case JDWP::JT_INT:
2680 CHECK_EQ(width, 4U);
Sebastien Hertzabbabc82015-03-26 08:47:47 +01002681 if (!visitor.SetVReg(m, vreg, static_cast<uint32_t>(value), kIntVReg)) {
2682 return FailSetLocalValue(visitor, vreg, tag, static_cast<uint32_t>(value));
Sebastien Hertz8009f392014-09-01 17:07:11 +02002683 }
2684 break;
2685 case JDWP::JT_FLOAT:
2686 CHECK_EQ(width, 4U);
Sebastien Hertzabbabc82015-03-26 08:47:47 +01002687 if (!visitor.SetVReg(m, vreg, static_cast<uint32_t>(value), kFloatVReg)) {
2688 return FailSetLocalValue(visitor, vreg, tag, static_cast<uint32_t>(value));
Sebastien Hertz8009f392014-09-01 17:07:11 +02002689 }
2690 break;
2691 case JDWP::JT_ARRAY:
2692 case JDWP::JT_CLASS_LOADER:
2693 case JDWP::JT_CLASS_OBJECT:
2694 case JDWP::JT_OBJECT:
2695 case JDWP::JT_STRING:
2696 case JDWP::JT_THREAD:
2697 case JDWP::JT_THREAD_GROUP: {
2698 CHECK_EQ(width, sizeof(JDWP::ObjectId));
Sebastien Hertz8009f392014-09-01 17:07:11 +02002699 mirror::Object* o = gRegistry->Get<mirror::Object*>(static_cast<JDWP::ObjectId>(value),
2700 &error);
2701 if (error != JDWP::ERR_NONE) {
2702 VLOG(jdwp) << tag << " object " << o << " is an invalid object";
2703 return JDWP::ERR_INVALID_OBJECT;
Sebastien Hertzabbabc82015-03-26 08:47:47 +01002704 }
2705 if (!visitor.SetVReg(m, vreg, static_cast<uint32_t>(reinterpret_cast<uintptr_t>(o)),
2706 kReferenceVReg)) {
2707 return FailSetLocalValue(visitor, vreg, tag, reinterpret_cast<uintptr_t>(o));
Sebastien Hertz8009f392014-09-01 17:07:11 +02002708 }
2709 break;
2710 }
2711 case JDWP::JT_DOUBLE: {
2712 CHECK_EQ(width, 8U);
Sebastien Hertzabbabc82015-03-26 08:47:47 +01002713 if (!visitor.SetVRegPair(m, vreg, value, kDoubleLoVReg, kDoubleHiVReg)) {
2714 return FailSetLocalValue(visitor, vreg, tag, value);
Sebastien Hertz8009f392014-09-01 17:07:11 +02002715 }
2716 break;
2717 }
2718 case JDWP::JT_LONG: {
2719 CHECK_EQ(width, 8U);
Sebastien Hertzabbabc82015-03-26 08:47:47 +01002720 if (!visitor.SetVRegPair(m, vreg, value, kLongLoVReg, kLongHiVReg)) {
2721 return FailSetLocalValue(visitor, vreg, tag, value);
Sebastien Hertz8009f392014-09-01 17:07:11 +02002722 }
2723 break;
2724 }
2725 default:
2726 LOG(FATAL) << "Unknown tag " << tag;
Sebastien Hertzabbabc82015-03-26 08:47:47 +01002727 UNREACHABLE();
Sebastien Hertz8009f392014-09-01 17:07:11 +02002728 }
2729 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002730}
2731
Mathieu Chartiere401d142015-04-22 13:56:20 -07002732static void SetEventLocation(JDWP::EventLocation* location, ArtMethod* m, uint32_t dex_pc)
Mathieu Chartier90443472015-07-16 20:32:27 -07002733 SHARED_REQUIRES(Locks::mutator_lock_) {
Sebastien Hertz6995c602014-09-09 12:10:13 +02002734 DCHECK(location != nullptr);
2735 if (m == nullptr) {
2736 memset(location, 0, sizeof(*location));
2737 } else {
2738 location->method = m;
2739 location->dex_pc = (m->IsNative() || m->IsProxyMethod()) ? static_cast<uint32_t>(-1) : dex_pc;
Sebastien Hertz3f52eaf2014-04-04 17:50:18 +02002740 }
Sebastien Hertz3f52eaf2014-04-04 17:50:18 +02002741}
2742
Mathieu Chartiere401d142015-04-22 13:56:20 -07002743void Dbg::PostLocationEvent(ArtMethod* m, int dex_pc, mirror::Object* this_object,
Jeff Hao579b0242013-11-18 13:16:49 -08002744 int event_flags, const JValue* return_value) {
Sebastien Hertz3f52eaf2014-04-04 17:50:18 +02002745 if (!IsDebuggerActive()) {
2746 return;
2747 }
2748 DCHECK(m != nullptr);
2749 DCHECK_EQ(m->IsStatic(), this_object == nullptr);
Sebastien Hertz6995c602014-09-09 12:10:13 +02002750 JDWP::EventLocation location;
2751 SetEventLocation(&location, m, dex_pc);
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08002752
Sebastien Hertzde48aa62015-05-26 11:53:39 +02002753 // We need to be sure no exception is pending when calling JdwpState::PostLocationEvent.
2754 // This is required to be able to call JNI functions to create JDWP ids. To achieve this,
2755 // we temporarily clear the current thread's exception (if any) and will restore it after
2756 // the call.
2757 // Note: the only way to get a pending exception here is to suspend on a move-exception
2758 // instruction.
2759 Thread* const self = Thread::Current();
2760 StackHandleScope<1> hs(self);
2761 Handle<mirror::Throwable> pending_exception(hs.NewHandle(self->GetException()));
2762 self->ClearException();
2763 if (kIsDebugBuild && pending_exception.Get() != nullptr) {
2764 const DexFile::CodeItem* code_item = location.method->GetCodeItem();
2765 const Instruction* instr = Instruction::At(&code_item->insns_[location.dex_pc]);
2766 CHECK_EQ(Instruction::MOVE_EXCEPTION, instr->Opcode());
2767 }
2768
Sebastien Hertz6995c602014-09-09 12:10:13 +02002769 gJdwpState->PostLocationEvent(&location, this_object, event_flags, return_value);
Sebastien Hertzde48aa62015-05-26 11:53:39 +02002770
2771 if (pending_exception.Get() != nullptr) {
2772 self->SetException(pending_exception.Get());
2773 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002774}
2775
Mathieu Chartiere401d142015-04-22 13:56:20 -07002776void Dbg::PostFieldAccessEvent(ArtMethod* m, int dex_pc,
Mathieu Chartierc7853442015-03-27 14:35:38 -07002777 mirror::Object* this_object, ArtField* f) {
Sebastien Hertz3f52eaf2014-04-04 17:50:18 +02002778 if (!IsDebuggerActive()) {
2779 return;
2780 }
2781 DCHECK(m != nullptr);
2782 DCHECK(f != nullptr);
Sebastien Hertz6995c602014-09-09 12:10:13 +02002783 JDWP::EventLocation location;
2784 SetEventLocation(&location, m, dex_pc);
Sebastien Hertz3f52eaf2014-04-04 17:50:18 +02002785
Sebastien Hertz6995c602014-09-09 12:10:13 +02002786 gJdwpState->PostFieldEvent(&location, f, this_object, nullptr, false);
Sebastien Hertz3f52eaf2014-04-04 17:50:18 +02002787}
2788
Mathieu Chartiere401d142015-04-22 13:56:20 -07002789void Dbg::PostFieldModificationEvent(ArtMethod* m, int dex_pc,
Mathieu Chartierc7853442015-03-27 14:35:38 -07002790 mirror::Object* this_object, ArtField* f,
Sebastien Hertz3f52eaf2014-04-04 17:50:18 +02002791 const JValue* field_value) {
2792 if (!IsDebuggerActive()) {
2793 return;
2794 }
2795 DCHECK(m != nullptr);
2796 DCHECK(f != nullptr);
2797 DCHECK(field_value != nullptr);
Sebastien Hertz6995c602014-09-09 12:10:13 +02002798 JDWP::EventLocation location;
2799 SetEventLocation(&location, m, dex_pc);
Sebastien Hertz3f52eaf2014-04-04 17:50:18 +02002800
Sebastien Hertz6995c602014-09-09 12:10:13 +02002801 gJdwpState->PostFieldEvent(&location, f, this_object, field_value, true);
Sebastien Hertz3f52eaf2014-04-04 17:50:18 +02002802}
2803
Nicolas Geoffray14691c52015-03-05 10:40:17 +00002804/**
2805 * Finds the location where this exception will be caught. We search until we reach the top
2806 * frame, in which case this exception is considered uncaught.
2807 */
2808class CatchLocationFinder : public StackVisitor {
2809 public:
2810 CatchLocationFinder(Thread* self, const Handle<mirror::Throwable>& exception, Context* context)
Mathieu Chartier90443472015-07-16 20:32:27 -07002811 SHARED_REQUIRES(Locks::mutator_lock_)
Nicolas Geoffray8e5bd182015-05-06 11:34:34 +01002812 : StackVisitor(self, context, StackVisitor::StackWalkKind::kIncludeInlinedFrames),
Nicolas Geoffray14691c52015-03-05 10:40:17 +00002813 self_(self),
2814 exception_(exception),
2815 handle_scope_(self),
2816 this_at_throw_(handle_scope_.NewHandle<mirror::Object>(nullptr)),
Mathieu Chartiere401d142015-04-22 13:56:20 -07002817 catch_method_(nullptr),
2818 throw_method_(nullptr),
Nicolas Geoffray14691c52015-03-05 10:40:17 +00002819 catch_dex_pc_(DexFile::kDexNoIndex),
2820 throw_dex_pc_(DexFile::kDexNoIndex) {
2821 }
2822
Mathieu Chartier90443472015-07-16 20:32:27 -07002823 bool VisitFrame() OVERRIDE SHARED_REQUIRES(Locks::mutator_lock_) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07002824 ArtMethod* method = GetMethod();
Nicolas Geoffray14691c52015-03-05 10:40:17 +00002825 DCHECK(method != nullptr);
2826 if (method->IsRuntimeMethod()) {
2827 // Ignore callee save method.
2828 DCHECK(method->IsCalleeSaveMethod());
2829 return true;
2830 }
2831
2832 uint32_t dex_pc = GetDexPc();
Mathieu Chartiere401d142015-04-22 13:56:20 -07002833 if (throw_method_ == nullptr) {
Nicolas Geoffray14691c52015-03-05 10:40:17 +00002834 // First Java method found. It is either the method that threw the exception,
2835 // or the Java native method that is reporting an exception thrown by
2836 // native code.
2837 this_at_throw_.Assign(GetThisObject());
Mathieu Chartiere401d142015-04-22 13:56:20 -07002838 throw_method_ = method;
Nicolas Geoffray14691c52015-03-05 10:40:17 +00002839 throw_dex_pc_ = dex_pc;
2840 }
2841
2842 if (dex_pc != DexFile::kDexNoIndex) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07002843 StackHandleScope<1> hs(self_);
Nicolas Geoffray14691c52015-03-05 10:40:17 +00002844 uint32_t found_dex_pc;
2845 Handle<mirror::Class> exception_class(hs.NewHandle(exception_->GetClass()));
Nicolas Geoffray14691c52015-03-05 10:40:17 +00002846 bool unused_clear_exception;
Mathieu Chartiere401d142015-04-22 13:56:20 -07002847 found_dex_pc = method->FindCatchBlock(exception_class, dex_pc, &unused_clear_exception);
Nicolas Geoffray14691c52015-03-05 10:40:17 +00002848 if (found_dex_pc != DexFile::kDexNoIndex) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07002849 catch_method_ = method;
Nicolas Geoffray14691c52015-03-05 10:40:17 +00002850 catch_dex_pc_ = found_dex_pc;
2851 return false; // End stack walk.
2852 }
2853 }
2854 return true; // Continue stack walk.
2855 }
2856
Mathieu Chartier90443472015-07-16 20:32:27 -07002857 ArtMethod* GetCatchMethod() SHARED_REQUIRES(Locks::mutator_lock_) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07002858 return catch_method_;
Nicolas Geoffray14691c52015-03-05 10:40:17 +00002859 }
2860
Mathieu Chartier90443472015-07-16 20:32:27 -07002861 ArtMethod* GetThrowMethod() SHARED_REQUIRES(Locks::mutator_lock_) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07002862 return throw_method_;
Nicolas Geoffray14691c52015-03-05 10:40:17 +00002863 }
2864
Mathieu Chartier90443472015-07-16 20:32:27 -07002865 mirror::Object* GetThisAtThrow() SHARED_REQUIRES(Locks::mutator_lock_) {
Nicolas Geoffray14691c52015-03-05 10:40:17 +00002866 return this_at_throw_.Get();
2867 }
2868
2869 uint32_t GetCatchDexPc() const {
2870 return catch_dex_pc_;
2871 }
2872
2873 uint32_t GetThrowDexPc() const {
2874 return throw_dex_pc_;
2875 }
2876
2877 private:
2878 Thread* const self_;
2879 const Handle<mirror::Throwable>& exception_;
Mathieu Chartiere401d142015-04-22 13:56:20 -07002880 StackHandleScope<1> handle_scope_;
Nicolas Geoffray14691c52015-03-05 10:40:17 +00002881 MutableHandle<mirror::Object> this_at_throw_;
Mathieu Chartiere401d142015-04-22 13:56:20 -07002882 ArtMethod* catch_method_;
2883 ArtMethod* throw_method_;
Nicolas Geoffray14691c52015-03-05 10:40:17 +00002884 uint32_t catch_dex_pc_;
2885 uint32_t throw_dex_pc_;
2886
2887 DISALLOW_COPY_AND_ASSIGN(CatchLocationFinder);
2888};
2889
2890void Dbg::PostException(mirror::Throwable* exception_object) {
Elliott Hughesc0f09332012-03-26 13:27:06 -07002891 if (!IsDebuggerActive()) {
Ian Rogers0ad5bb82011-12-07 10:16:32 -08002892 return;
2893 }
Sebastien Hertz261bc042015-04-08 09:36:07 +02002894 Thread* const self = Thread::Current();
2895 StackHandleScope<1> handle_scope(self);
Nicolas Geoffray14691c52015-03-05 10:40:17 +00002896 Handle<mirror::Throwable> h_exception(handle_scope.NewHandle(exception_object));
2897 std::unique_ptr<Context> context(Context::Create());
Sebastien Hertz261bc042015-04-08 09:36:07 +02002898 CatchLocationFinder clf(self, h_exception, context.get());
Nicolas Geoffray14691c52015-03-05 10:40:17 +00002899 clf.WalkStack(/* include_transitions */ false);
Sebastien Hertz6995c602014-09-09 12:10:13 +02002900 JDWP::EventLocation exception_throw_location;
Nicolas Geoffray14691c52015-03-05 10:40:17 +00002901 SetEventLocation(&exception_throw_location, clf.GetThrowMethod(), clf.GetThrowDexPc());
Sebastien Hertz6995c602014-09-09 12:10:13 +02002902 JDWP::EventLocation exception_catch_location;
Nicolas Geoffray14691c52015-03-05 10:40:17 +00002903 SetEventLocation(&exception_catch_location, clf.GetCatchMethod(), clf.GetCatchDexPc());
Elliott Hughes4740cdf2011-12-07 14:07:12 -08002904
Nicolas Geoffray14691c52015-03-05 10:40:17 +00002905 gJdwpState->PostException(&exception_throw_location, h_exception.Get(), &exception_catch_location,
2906 clf.GetThisAtThrow());
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002907}
2908
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002909void Dbg::PostClassPrepare(mirror::Class* c) {
Elliott Hughesc0f09332012-03-26 13:27:06 -07002910 if (!IsDebuggerActive()) {
Elliott Hughes4740cdf2011-12-07 14:07:12 -08002911 return;
2912 }
Sebastien Hertz6995c602014-09-09 12:10:13 +02002913 gJdwpState->PostClassPrepare(c);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002914}
2915
Ian Rogers62d6c772013-02-27 08:32:07 -08002916void Dbg::UpdateDebugger(Thread* thread, mirror::Object* this_object,
Mathieu Chartiere401d142015-04-22 13:56:20 -07002917 ArtMethod* m, uint32_t dex_pc,
Sebastien Hertz8379b222014-02-24 17:38:15 +01002918 int event_flags, const JValue* return_value) {
Ian Rogers62d6c772013-02-27 08:32:07 -08002919 if (!IsDebuggerActive() || dex_pc == static_cast<uint32_t>(-2) /* fake method exit */) {
Elliott Hughes2aa2e392012-02-17 17:15:43 -08002920 return;
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08002921 }
2922
Elliott Hughes86964332012-02-15 19:37:42 -08002923 if (IsBreakpoint(m, dex_pc)) {
2924 event_flags |= kBreakpoint;
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08002925 }
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08002926
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01002927 // If the debugger is single-stepping one of our threads, check to
2928 // see if we're that thread and we've reached a step point.
2929 const SingleStepControl* single_step_control = thread->GetSingleStepControl();
Sebastien Hertz597c4f02015-01-26 17:37:14 +01002930 if (single_step_control != nullptr) {
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01002931 CHECK(!m->IsNative());
Sebastien Hertz597c4f02015-01-26 17:37:14 +01002932 if (single_step_control->GetStepDepth() == JDWP::SD_INTO) {
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01002933 // Step into method calls. We break when the line number
2934 // or method pointer changes. If we're in SS_MIN mode, we
2935 // always stop.
Sebastien Hertz597c4f02015-01-26 17:37:14 +01002936 if (single_step_control->GetMethod() != m) {
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01002937 event_flags |= kSingleStep;
2938 VLOG(jdwp) << "SS new method";
Sebastien Hertz597c4f02015-01-26 17:37:14 +01002939 } else if (single_step_control->GetStepSize() == JDWP::SS_MIN) {
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01002940 event_flags |= kSingleStep;
2941 VLOG(jdwp) << "SS new instruction";
Sebastien Hertzbb43b432014-04-14 11:59:08 +02002942 } else if (single_step_control->ContainsDexPc(dex_pc)) {
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01002943 event_flags |= kSingleStep;
2944 VLOG(jdwp) << "SS new line";
2945 }
Sebastien Hertz597c4f02015-01-26 17:37:14 +01002946 } else if (single_step_control->GetStepDepth() == JDWP::SD_OVER) {
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01002947 // Step over method calls. We break when the line number is
2948 // different and the frame depth is <= the original frame
2949 // depth. (We can't just compare on the method, because we
2950 // might get unrolled past it by an exception, and it's tricky
2951 // to identify recursion.)
2952
2953 int stack_depth = GetStackDepth(thread);
2954
Sebastien Hertz597c4f02015-01-26 17:37:14 +01002955 if (stack_depth < single_step_control->GetStackDepth()) {
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01002956 // Popped up one or more frames, always trigger.
2957 event_flags |= kSingleStep;
2958 VLOG(jdwp) << "SS method pop";
Sebastien Hertz597c4f02015-01-26 17:37:14 +01002959 } else if (stack_depth == single_step_control->GetStackDepth()) {
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01002960 // Same depth, see if we moved.
Sebastien Hertz597c4f02015-01-26 17:37:14 +01002961 if (single_step_control->GetStepSize() == JDWP::SS_MIN) {
Elliott Hughes86964332012-02-15 19:37:42 -08002962 event_flags |= kSingleStep;
2963 VLOG(jdwp) << "SS new instruction";
Sebastien Hertzbb43b432014-04-14 11:59:08 +02002964 } else if (single_step_control->ContainsDexPc(dex_pc)) {
Elliott Hughes2435a572012-02-17 16:07:41 -08002965 event_flags |= kSingleStep;
2966 VLOG(jdwp) << "SS new line";
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08002967 }
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01002968 }
2969 } else {
Sebastien Hertz597c4f02015-01-26 17:37:14 +01002970 CHECK_EQ(single_step_control->GetStepDepth(), JDWP::SD_OUT);
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01002971 // Return from the current method. We break when the frame
2972 // depth pops up.
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08002973
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01002974 // This differs from the "method exit" break in that it stops
2975 // with the PC at the next instruction in the returned-to
2976 // function, rather than the end of the returning function.
Elliott Hughes86964332012-02-15 19:37:42 -08002977
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01002978 int stack_depth = GetStackDepth(thread);
Sebastien Hertz597c4f02015-01-26 17:37:14 +01002979 if (stack_depth < single_step_control->GetStackDepth()) {
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01002980 event_flags |= kSingleStep;
2981 VLOG(jdwp) << "SS method pop";
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08002982 }
2983 }
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08002984 }
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08002985
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08002986 // If there's something interesting going on, see if it matches one
2987 // of the debugger filters.
2988 if (event_flags != 0) {
Sebastien Hertz8379b222014-02-24 17:38:15 +01002989 Dbg::PostLocationEvent(m, dex_pc, this_object, event_flags, return_value);
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08002990 }
2991}
2992
Sebastien Hertz42cd43f2014-05-13 14:15:41 +02002993size_t* Dbg::GetReferenceCounterForEvent(uint32_t instrumentation_event) {
2994 switch (instrumentation_event) {
2995 case instrumentation::Instrumentation::kMethodEntered:
2996 return &method_enter_event_ref_count_;
2997 case instrumentation::Instrumentation::kMethodExited:
2998 return &method_exit_event_ref_count_;
2999 case instrumentation::Instrumentation::kDexPcMoved:
3000 return &dex_pc_change_event_ref_count_;
3001 case instrumentation::Instrumentation::kFieldRead:
3002 return &field_read_event_ref_count_;
3003 case instrumentation::Instrumentation::kFieldWritten:
3004 return &field_write_event_ref_count_;
3005 case instrumentation::Instrumentation::kExceptionCaught:
3006 return &exception_catch_event_ref_count_;
3007 default:
3008 return nullptr;
3009 }
3010}
3011
Sebastien Hertz4d25df32014-03-21 17:44:46 +01003012// Process request while all mutator threads are suspended.
3013void Dbg::ProcessDeoptimizationRequest(const DeoptimizationRequest& request) {
Sebastien Hertz138dbfc2013-12-04 18:15:25 +01003014 instrumentation::Instrumentation* instrumentation = Runtime::Current()->GetInstrumentation();
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003015 switch (request.GetKind()) {
Sebastien Hertz4d25df32014-03-21 17:44:46 +01003016 case DeoptimizationRequest::kNothing:
3017 LOG(WARNING) << "Ignoring empty deoptimization request.";
3018 break;
Sebastien Hertz42cd43f2014-05-13 14:15:41 +02003019 case DeoptimizationRequest::kRegisterForEvent:
3020 VLOG(jdwp) << StringPrintf("Add debugger as listener for instrumentation event 0x%x",
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003021 request.InstrumentationEvent());
3022 instrumentation->AddListener(&gDebugInstrumentationListener, request.InstrumentationEvent());
3023 instrumentation_events_ |= request.InstrumentationEvent();
Sebastien Hertz42cd43f2014-05-13 14:15:41 +02003024 break;
3025 case DeoptimizationRequest::kUnregisterForEvent:
3026 VLOG(jdwp) << StringPrintf("Remove debugger as listener for instrumentation event 0x%x",
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003027 request.InstrumentationEvent());
Sebastien Hertz42cd43f2014-05-13 14:15:41 +02003028 instrumentation->RemoveListener(&gDebugInstrumentationListener,
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003029 request.InstrumentationEvent());
3030 instrumentation_events_ &= ~request.InstrumentationEvent();
Sebastien Hertz42cd43f2014-05-13 14:15:41 +02003031 break;
Sebastien Hertz4d25df32014-03-21 17:44:46 +01003032 case DeoptimizationRequest::kFullDeoptimization:
Sebastien Hertz7ec2f1c2014-03-27 20:06:47 +01003033 VLOG(jdwp) << "Deoptimize the world ...";
Sebastien Hertz0462c4c2015-04-01 16:34:17 +02003034 instrumentation->DeoptimizeEverything(kDbgInstrumentationKey);
Sebastien Hertz7ec2f1c2014-03-27 20:06:47 +01003035 VLOG(jdwp) << "Deoptimize the world DONE";
Sebastien Hertz4d25df32014-03-21 17:44:46 +01003036 break;
3037 case DeoptimizationRequest::kFullUndeoptimization:
Sebastien Hertz7ec2f1c2014-03-27 20:06:47 +01003038 VLOG(jdwp) << "Undeoptimize the world ...";
Sebastien Hertz0462c4c2015-04-01 16:34:17 +02003039 instrumentation->UndeoptimizeEverything(kDbgInstrumentationKey);
Sebastien Hertz7ec2f1c2014-03-27 20:06:47 +01003040 VLOG(jdwp) << "Undeoptimize the world DONE";
Sebastien Hertz4d25df32014-03-21 17:44:46 +01003041 break;
3042 case DeoptimizationRequest::kSelectiveDeoptimization:
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003043 VLOG(jdwp) << "Deoptimize method " << PrettyMethod(request.Method()) << " ...";
3044 instrumentation->Deoptimize(request.Method());
3045 VLOG(jdwp) << "Deoptimize method " << PrettyMethod(request.Method()) << " DONE";
Sebastien Hertz4d25df32014-03-21 17:44:46 +01003046 break;
3047 case DeoptimizationRequest::kSelectiveUndeoptimization:
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003048 VLOG(jdwp) << "Undeoptimize method " << PrettyMethod(request.Method()) << " ...";
3049 instrumentation->Undeoptimize(request.Method());
3050 VLOG(jdwp) << "Undeoptimize method " << PrettyMethod(request.Method()) << " DONE";
Sebastien Hertz4d25df32014-03-21 17:44:46 +01003051 break;
3052 default:
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003053 LOG(FATAL) << "Unsupported deoptimization request kind " << request.GetKind();
Sebastien Hertz4d25df32014-03-21 17:44:46 +01003054 break;
Sebastien Hertz138dbfc2013-12-04 18:15:25 +01003055 }
Sebastien Hertz138dbfc2013-12-04 18:15:25 +01003056}
3057
Sebastien Hertz4d25df32014-03-21 17:44:46 +01003058void Dbg::RequestDeoptimization(const DeoptimizationRequest& req) {
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003059 if (req.GetKind() == DeoptimizationRequest::kNothing) {
Sebastien Hertz4d25df32014-03-21 17:44:46 +01003060 // Nothing to do.
3061 return;
3062 }
Brian Carlstrom306db812014-09-05 13:01:41 -07003063 MutexLock mu(Thread::Current(), *Locks::deoptimization_lock_);
Sebastien Hertz7ec2f1c2014-03-27 20:06:47 +01003064 RequestDeoptimizationLocked(req);
3065}
3066
3067void Dbg::RequestDeoptimizationLocked(const DeoptimizationRequest& req) {
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003068 switch (req.GetKind()) {
Sebastien Hertz42cd43f2014-05-13 14:15:41 +02003069 case DeoptimizationRequest::kRegisterForEvent: {
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003070 DCHECK_NE(req.InstrumentationEvent(), 0u);
3071 size_t* counter = GetReferenceCounterForEvent(req.InstrumentationEvent());
Sebastien Hertz42cd43f2014-05-13 14:15:41 +02003072 CHECK(counter != nullptr) << StringPrintf("No counter for instrumentation event 0x%x",
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003073 req.InstrumentationEvent());
Sebastien Hertz42cd43f2014-05-13 14:15:41 +02003074 if (*counter == 0) {
Sebastien Hertz7d2ae432014-05-15 11:26:34 +02003075 VLOG(jdwp) << StringPrintf("Queue request #%zd to start listening to instrumentation event 0x%x",
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003076 deoptimization_requests_.size(), req.InstrumentationEvent());
Sebastien Hertz42cd43f2014-05-13 14:15:41 +02003077 deoptimization_requests_.push_back(req);
3078 }
3079 *counter = *counter + 1;
3080 break;
3081 }
3082 case DeoptimizationRequest::kUnregisterForEvent: {
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003083 DCHECK_NE(req.InstrumentationEvent(), 0u);
3084 size_t* counter = GetReferenceCounterForEvent(req.InstrumentationEvent());
Sebastien Hertz42cd43f2014-05-13 14:15:41 +02003085 CHECK(counter != nullptr) << StringPrintf("No counter for instrumentation event 0x%x",
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003086 req.InstrumentationEvent());
Sebastien Hertz42cd43f2014-05-13 14:15:41 +02003087 *counter = *counter - 1;
3088 if (*counter == 0) {
Sebastien Hertz7d2ae432014-05-15 11:26:34 +02003089 VLOG(jdwp) << StringPrintf("Queue request #%zd to stop listening to instrumentation event 0x%x",
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003090 deoptimization_requests_.size(), req.InstrumentationEvent());
Sebastien Hertz42cd43f2014-05-13 14:15:41 +02003091 deoptimization_requests_.push_back(req);
3092 }
3093 break;
3094 }
Sebastien Hertz4d25df32014-03-21 17:44:46 +01003095 case DeoptimizationRequest::kFullDeoptimization: {
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003096 DCHECK(req.Method() == nullptr);
Sebastien Hertz4d25df32014-03-21 17:44:46 +01003097 if (full_deoptimization_event_count_ == 0) {
Sebastien Hertz7ec2f1c2014-03-27 20:06:47 +01003098 VLOG(jdwp) << "Queue request #" << deoptimization_requests_.size()
3099 << " for full deoptimization";
Sebastien Hertz4d25df32014-03-21 17:44:46 +01003100 deoptimization_requests_.push_back(req);
3101 }
3102 ++full_deoptimization_event_count_;
3103 break;
3104 }
3105 case DeoptimizationRequest::kFullUndeoptimization: {
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003106 DCHECK(req.Method() == nullptr);
Sebastien Hertze713d932014-05-15 10:48:53 +02003107 DCHECK_GT(full_deoptimization_event_count_, 0U);
Sebastien Hertz4d25df32014-03-21 17:44:46 +01003108 --full_deoptimization_event_count_;
3109 if (full_deoptimization_event_count_ == 0) {
Sebastien Hertz7ec2f1c2014-03-27 20:06:47 +01003110 VLOG(jdwp) << "Queue request #" << deoptimization_requests_.size()
3111 << " for full undeoptimization";
Sebastien Hertz4d25df32014-03-21 17:44:46 +01003112 deoptimization_requests_.push_back(req);
3113 }
3114 break;
3115 }
3116 case DeoptimizationRequest::kSelectiveDeoptimization: {
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003117 DCHECK(req.Method() != nullptr);
Sebastien Hertz7ec2f1c2014-03-27 20:06:47 +01003118 VLOG(jdwp) << "Queue request #" << deoptimization_requests_.size()
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003119 << " for deoptimization of " << PrettyMethod(req.Method());
Sebastien Hertz4d25df32014-03-21 17:44:46 +01003120 deoptimization_requests_.push_back(req);
3121 break;
3122 }
3123 case DeoptimizationRequest::kSelectiveUndeoptimization: {
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003124 DCHECK(req.Method() != nullptr);
Sebastien Hertz7ec2f1c2014-03-27 20:06:47 +01003125 VLOG(jdwp) << "Queue request #" << deoptimization_requests_.size()
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003126 << " for undeoptimization of " << PrettyMethod(req.Method());
Sebastien Hertz4d25df32014-03-21 17:44:46 +01003127 deoptimization_requests_.push_back(req);
3128 break;
3129 }
3130 default: {
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003131 LOG(FATAL) << "Unknown deoptimization request kind " << req.GetKind();
Sebastien Hertz4d25df32014-03-21 17:44:46 +01003132 break;
3133 }
3134 }
3135}
3136
Sebastien Hertz138dbfc2013-12-04 18:15:25 +01003137void Dbg::ManageDeoptimization() {
3138 Thread* const self = Thread::Current();
3139 {
3140 // Avoid suspend/resume if there is no pending request.
Brian Carlstrom306db812014-09-05 13:01:41 -07003141 MutexLock mu(self, *Locks::deoptimization_lock_);
Sebastien Hertz4d25df32014-03-21 17:44:46 +01003142 if (deoptimization_requests_.empty()) {
Sebastien Hertz138dbfc2013-12-04 18:15:25 +01003143 return;
3144 }
3145 }
3146 CHECK_EQ(self->GetState(), kRunnable);
3147 self->TransitionFromRunnableToSuspended(kWaitingForDeoptimization);
3148 // We need to suspend mutator threads first.
3149 Runtime* const runtime = Runtime::Current();
Mathieu Chartierbf9fc582015-03-13 17:21:25 -07003150 runtime->GetThreadList()->SuspendAll(__FUNCTION__);
Sebastien Hertz138dbfc2013-12-04 18:15:25 +01003151 const ThreadState old_state = self->SetStateUnsafe(kRunnable);
Sebastien Hertz4d25df32014-03-21 17:44:46 +01003152 {
Brian Carlstrom306db812014-09-05 13:01:41 -07003153 MutexLock mu(self, *Locks::deoptimization_lock_);
Sebastien Hertz7ec2f1c2014-03-27 20:06:47 +01003154 size_t req_index = 0;
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003155 for (DeoptimizationRequest& request : deoptimization_requests_) {
Sebastien Hertz7ec2f1c2014-03-27 20:06:47 +01003156 VLOG(jdwp) << "Process deoptimization request #" << req_index++;
Sebastien Hertz4d25df32014-03-21 17:44:46 +01003157 ProcessDeoptimizationRequest(request);
3158 }
3159 deoptimization_requests_.clear();
3160 }
Sebastien Hertz138dbfc2013-12-04 18:15:25 +01003161 CHECK_EQ(self->SetStateUnsafe(old_state), kRunnable);
3162 runtime->GetThreadList()->ResumeAll();
3163 self->TransitionFromSuspendedToRunnable();
3164}
3165
Mathieu Chartiere401d142015-04-22 13:56:20 -07003166static bool IsMethodPossiblyInlined(Thread* self, ArtMethod* m)
Mathieu Chartier90443472015-07-16 20:32:27 -07003167 SHARED_REQUIRES(Locks::mutator_lock_) {
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07003168 const DexFile::CodeItem* code_item = m->GetCodeItem();
Sebastien Hertza76a6d42014-03-20 16:40:17 +01003169 if (code_item == nullptr) {
3170 // TODO We should not be asked to watch location in a native or abstract method so the code item
3171 // should never be null. We could just check we never encounter this case.
3172 return false;
Sebastien Hertz138dbfc2013-12-04 18:15:25 +01003173 }
Sebastien Hertz4d1e9ab2014-09-18 16:03:34 +02003174 // Note: method verifier may cause thread suspension.
3175 self->AssertThreadSuspensionIsAllowable();
Mathieu Chartiere401d142015-04-22 13:56:20 -07003176 StackHandleScope<2> hs(self);
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07003177 mirror::Class* declaring_class = m->GetDeclaringClass();
3178 Handle<mirror::DexCache> dex_cache(hs.NewHandle(declaring_class->GetDexCache()));
3179 Handle<mirror::ClassLoader> class_loader(hs.NewHandle(declaring_class->GetClassLoader()));
Ian Rogers7b078e82014-09-10 14:44:24 -07003180 verifier::MethodVerifier verifier(self, dex_cache->GetDexFile(), dex_cache, class_loader,
Mathieu Chartiere401d142015-04-22 13:56:20 -07003181 &m->GetClassDef(), code_item, m->GetDexMethodIndex(), m,
Mathieu Chartier4306ef82014-12-19 18:41:47 -08003182 m->GetAccessFlags(), false, true, false, true);
Sebastien Hertza76a6d42014-03-20 16:40:17 +01003183 // Note: we don't need to verify the method.
3184 return InlineMethodAnalyser::AnalyseMethodCode(&verifier, nullptr);
3185}
Sebastien Hertz138dbfc2013-12-04 18:15:25 +01003186
Mathieu Chartiere401d142015-04-22 13:56:20 -07003187static const Breakpoint* FindFirstBreakpointForMethod(ArtMethod* m)
Mathieu Chartier90443472015-07-16 20:32:27 -07003188 SHARED_REQUIRES(Locks::mutator_lock_, Locks::breakpoint_lock_) {
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003189 for (Breakpoint& breakpoint : gBreakpoints) {
3190 if (breakpoint.Method() == m) {
Sebastien Hertza76a6d42014-03-20 16:40:17 +01003191 return &breakpoint;
3192 }
3193 }
3194 return nullptr;
3195}
3196
Mathieu Chartiere401d142015-04-22 13:56:20 -07003197bool Dbg::MethodHasAnyBreakpoints(ArtMethod* method) {
Mathieu Chartierd8565452015-03-26 09:41:50 -07003198 ReaderMutexLock mu(Thread::Current(), *Locks::breakpoint_lock_);
3199 return FindFirstBreakpointForMethod(method) != nullptr;
3200}
3201
Sebastien Hertza76a6d42014-03-20 16:40:17 +01003202// Sanity checks all existing breakpoints on the same method.
Mathieu Chartiere401d142015-04-22 13:56:20 -07003203static void SanityCheckExistingBreakpoints(ArtMethod* m,
Sebastien Hertzf3928792014-11-17 19:00:37 +01003204 DeoptimizationRequest::Kind deoptimization_kind)
Mathieu Chartier90443472015-07-16 20:32:27 -07003205 SHARED_REQUIRES(Locks::mutator_lock_, Locks::breakpoint_lock_) {
Sebastien Hertz4d1e9ab2014-09-18 16:03:34 +02003206 for (const Breakpoint& breakpoint : gBreakpoints) {
Sebastien Hertzf3928792014-11-17 19:00:37 +01003207 if (breakpoint.Method() == m) {
3208 CHECK_EQ(deoptimization_kind, breakpoint.GetDeoptimizationKind());
3209 }
Sebastien Hertz4d1e9ab2014-09-18 16:03:34 +02003210 }
Sebastien Hertzf3928792014-11-17 19:00:37 +01003211 instrumentation::Instrumentation* instrumentation = Runtime::Current()->GetInstrumentation();
3212 if (deoptimization_kind == DeoptimizationRequest::kFullDeoptimization) {
Sebastien Hertz4d1e9ab2014-09-18 16:03:34 +02003213 // We should have deoptimized everything but not "selectively" deoptimized this method.
Sebastien Hertzf3928792014-11-17 19:00:37 +01003214 CHECK(instrumentation->AreAllMethodsDeoptimized());
3215 CHECK(!instrumentation->IsDeoptimized(m));
3216 } else if (deoptimization_kind == DeoptimizationRequest::kSelectiveDeoptimization) {
Sebastien Hertz4d1e9ab2014-09-18 16:03:34 +02003217 // We should have "selectively" deoptimized this method.
3218 // Note: while we have not deoptimized everything for this method, we may have done it for
3219 // another event.
Sebastien Hertzf3928792014-11-17 19:00:37 +01003220 CHECK(instrumentation->IsDeoptimized(m));
3221 } else {
3222 // This method does not require deoptimization.
3223 CHECK_EQ(deoptimization_kind, DeoptimizationRequest::kNothing);
3224 CHECK(!instrumentation->IsDeoptimized(m));
3225 }
3226}
3227
Sebastien Hertzabe93e02014-12-17 16:35:50 +01003228// Returns the deoptimization kind required to set a breakpoint in a method.
3229// If a breakpoint has already been set, we also return the first breakpoint
3230// through the given 'existing_brkpt' pointer.
Sebastien Hertzf3928792014-11-17 19:00:37 +01003231static DeoptimizationRequest::Kind GetRequiredDeoptimizationKind(Thread* self,
Mathieu Chartiere401d142015-04-22 13:56:20 -07003232 ArtMethod* m,
Sebastien Hertzabe93e02014-12-17 16:35:50 +01003233 const Breakpoint** existing_brkpt)
Mathieu Chartier90443472015-07-16 20:32:27 -07003234 SHARED_REQUIRES(Locks::mutator_lock_) {
Sebastien Hertzf3928792014-11-17 19:00:37 +01003235 if (!Dbg::RequiresDeoptimization()) {
3236 // We already run in interpreter-only mode so we don't need to deoptimize anything.
3237 VLOG(jdwp) << "No need for deoptimization when fully running with interpreter for method "
3238 << PrettyMethod(m);
3239 return DeoptimizationRequest::kNothing;
3240 }
Sebastien Hertzabe93e02014-12-17 16:35:50 +01003241 const Breakpoint* first_breakpoint;
Sebastien Hertzf3928792014-11-17 19:00:37 +01003242 {
3243 ReaderMutexLock mu(self, *Locks::breakpoint_lock_);
Sebastien Hertzabe93e02014-12-17 16:35:50 +01003244 first_breakpoint = FindFirstBreakpointForMethod(m);
3245 *existing_brkpt = first_breakpoint;
Sebastien Hertzf3928792014-11-17 19:00:37 +01003246 }
Sebastien Hertzabe93e02014-12-17 16:35:50 +01003247
3248 if (first_breakpoint == nullptr) {
Sebastien Hertzf3928792014-11-17 19:00:37 +01003249 // There is no breakpoint on this method yet: we need to deoptimize. If this method may be
3250 // inlined, we deoptimize everything; otherwise we deoptimize only this method.
3251 // Note: IsMethodPossiblyInlined goes into the method verifier and may cause thread suspension.
3252 // Therefore we must not hold any lock when we call it.
3253 bool need_full_deoptimization = IsMethodPossiblyInlined(self, m);
3254 if (need_full_deoptimization) {
3255 VLOG(jdwp) << "Need full deoptimization because of possible inlining of method "
3256 << PrettyMethod(m);
3257 return DeoptimizationRequest::kFullDeoptimization;
3258 } else {
3259 // We don't need to deoptimize if the method has not been compiled.
3260 ClassLinker* const class_linker = Runtime::Current()->GetClassLinker();
3261 const bool is_compiled = class_linker->GetOatMethodQuickCodeFor(m) != nullptr;
3262 if (is_compiled) {
Sebastien Hertz6963e442014-11-26 22:11:27 +01003263 // If the method may be called through its direct code pointer (without loading
3264 // its updated entrypoint), we need full deoptimization to not miss the breakpoint.
3265 if (class_linker->MayBeCalledWithDirectCodePointer(m)) {
3266 VLOG(jdwp) << "Need full deoptimization because of possible direct code call "
3267 << "into image for compiled method " << PrettyMethod(m);
3268 return DeoptimizationRequest::kFullDeoptimization;
3269 } else {
3270 VLOG(jdwp) << "Need selective deoptimization for compiled method " << PrettyMethod(m);
3271 return DeoptimizationRequest::kSelectiveDeoptimization;
3272 }
Sebastien Hertzf3928792014-11-17 19:00:37 +01003273 } else {
3274 // Method is not compiled: we don't need to deoptimize.
3275 VLOG(jdwp) << "No need for deoptimization for non-compiled method " << PrettyMethod(m);
3276 return DeoptimizationRequest::kNothing;
3277 }
3278 }
3279 } else {
3280 // There is at least one breakpoint for this method: we don't need to deoptimize.
3281 // Let's check that all breakpoints are configured the same way for deoptimization.
3282 VLOG(jdwp) << "Breakpoint already set: no deoptimization is required";
Sebastien Hertzabe93e02014-12-17 16:35:50 +01003283 DeoptimizationRequest::Kind deoptimization_kind = first_breakpoint->GetDeoptimizationKind();
Sebastien Hertzf3928792014-11-17 19:00:37 +01003284 if (kIsDebugBuild) {
3285 ReaderMutexLock mu(self, *Locks::breakpoint_lock_);
3286 SanityCheckExistingBreakpoints(m, deoptimization_kind);
3287 }
3288 return DeoptimizationRequest::kNothing;
Sebastien Hertz138dbfc2013-12-04 18:15:25 +01003289 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -07003290}
3291
Sebastien Hertza76a6d42014-03-20 16:40:17 +01003292// Installs a breakpoint at the specified location. Also indicates through the deoptimization
3293// request if we need to deoptimize.
3294void Dbg::WatchLocation(const JDWP::JdwpLocation* location, DeoptimizationRequest* req) {
3295 Thread* const self = Thread::Current();
Mathieu Chartiere401d142015-04-22 13:56:20 -07003296 ArtMethod* m = FromMethodId(location->method_id);
Sebastien Hertza76a6d42014-03-20 16:40:17 +01003297 DCHECK(m != nullptr) << "No method for method id " << location->method_id;
Sebastien Hertz138dbfc2013-12-04 18:15:25 +01003298
Sebastien Hertzabe93e02014-12-17 16:35:50 +01003299 const Breakpoint* existing_breakpoint = nullptr;
3300 const DeoptimizationRequest::Kind deoptimization_kind =
3301 GetRequiredDeoptimizationKind(self, m, &existing_breakpoint);
Sebastien Hertzf3928792014-11-17 19:00:37 +01003302 req->SetKind(deoptimization_kind);
3303 if (deoptimization_kind == DeoptimizationRequest::kSelectiveDeoptimization) {
3304 req->SetMethod(m);
Sebastien Hertza76a6d42014-03-20 16:40:17 +01003305 } else {
Sebastien Hertzf3928792014-11-17 19:00:37 +01003306 CHECK(deoptimization_kind == DeoptimizationRequest::kNothing ||
3307 deoptimization_kind == DeoptimizationRequest::kFullDeoptimization);
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003308 req->SetMethod(nullptr);
Sebastien Hertz138dbfc2013-12-04 18:15:25 +01003309 }
3310
Sebastien Hertz4d1e9ab2014-09-18 16:03:34 +02003311 {
3312 WriterMutexLock mu(self, *Locks::breakpoint_lock_);
Sebastien Hertzabe93e02014-12-17 16:35:50 +01003313 // If there is at least one existing breakpoint on the same method, the new breakpoint
3314 // must have the same deoptimization kind than the existing breakpoint(s).
3315 DeoptimizationRequest::Kind breakpoint_deoptimization_kind;
3316 if (existing_breakpoint != nullptr) {
3317 breakpoint_deoptimization_kind = existing_breakpoint->GetDeoptimizationKind();
3318 } else {
3319 breakpoint_deoptimization_kind = deoptimization_kind;
3320 }
3321 gBreakpoints.push_back(Breakpoint(m, location->dex_pc, breakpoint_deoptimization_kind));
Sebastien Hertz4d1e9ab2014-09-18 16:03:34 +02003322 VLOG(jdwp) << "Set breakpoint #" << (gBreakpoints.size() - 1) << ": "
3323 << gBreakpoints[gBreakpoints.size() - 1];
3324 }
Sebastien Hertza76a6d42014-03-20 16:40:17 +01003325}
3326
3327// Uninstalls a breakpoint at the specified location. Also indicates through the deoptimization
3328// request if we need to undeoptimize.
3329void Dbg::UnwatchLocation(const JDWP::JdwpLocation* location, DeoptimizationRequest* req) {
Sebastien Hertzed2be172014-08-19 15:33:43 +02003330 WriterMutexLock mu(Thread::Current(), *Locks::breakpoint_lock_);
Mathieu Chartiere401d142015-04-22 13:56:20 -07003331 ArtMethod* m = FromMethodId(location->method_id);
Sebastien Hertza76a6d42014-03-20 16:40:17 +01003332 DCHECK(m != nullptr) << "No method for method id " << location->method_id;
Sebastien Hertzf3928792014-11-17 19:00:37 +01003333 DeoptimizationRequest::Kind deoptimization_kind = DeoptimizationRequest::kNothing;
Sebastien Hertza76a6d42014-03-20 16:40:17 +01003334 for (size_t i = 0, e = gBreakpoints.size(); i < e; ++i) {
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003335 if (gBreakpoints[i].DexPc() == location->dex_pc && gBreakpoints[i].Method() == m) {
Sebastien Hertza76a6d42014-03-20 16:40:17 +01003336 VLOG(jdwp) << "Removed breakpoint #" << i << ": " << gBreakpoints[i];
Sebastien Hertzf3928792014-11-17 19:00:37 +01003337 deoptimization_kind = gBreakpoints[i].GetDeoptimizationKind();
3338 DCHECK_EQ(deoptimization_kind == DeoptimizationRequest::kSelectiveDeoptimization,
3339 Runtime::Current()->GetInstrumentation()->IsDeoptimized(m));
Sebastien Hertza76a6d42014-03-20 16:40:17 +01003340 gBreakpoints.erase(gBreakpoints.begin() + i);
3341 break;
3342 }
3343 }
3344 const Breakpoint* const existing_breakpoint = FindFirstBreakpointForMethod(m);
3345 if (existing_breakpoint == nullptr) {
3346 // There is no more breakpoint on this method: we need to undeoptimize.
Sebastien Hertzf3928792014-11-17 19:00:37 +01003347 if (deoptimization_kind == DeoptimizationRequest::kFullDeoptimization) {
Sebastien Hertza76a6d42014-03-20 16:40:17 +01003348 // This method required full deoptimization: we need to undeoptimize everything.
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003349 req->SetKind(DeoptimizationRequest::kFullUndeoptimization);
3350 req->SetMethod(nullptr);
Sebastien Hertzf3928792014-11-17 19:00:37 +01003351 } else if (deoptimization_kind == DeoptimizationRequest::kSelectiveDeoptimization) {
Sebastien Hertza76a6d42014-03-20 16:40:17 +01003352 // This method required selective deoptimization: we need to undeoptimize only that method.
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003353 req->SetKind(DeoptimizationRequest::kSelectiveUndeoptimization);
3354 req->SetMethod(m);
Sebastien Hertzf3928792014-11-17 19:00:37 +01003355 } else {
3356 // This method had no need for deoptimization: do nothing.
3357 CHECK_EQ(deoptimization_kind, DeoptimizationRequest::kNothing);
3358 req->SetKind(DeoptimizationRequest::kNothing);
3359 req->SetMethod(nullptr);
Sebastien Hertza76a6d42014-03-20 16:40:17 +01003360 }
3361 } else {
3362 // There is at least one breakpoint for this method: we don't need to undeoptimize.
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003363 req->SetKind(DeoptimizationRequest::kNothing);
3364 req->SetMethod(nullptr);
Sebastien Hertz4d1e9ab2014-09-18 16:03:34 +02003365 if (kIsDebugBuild) {
Sebastien Hertzf3928792014-11-17 19:00:37 +01003366 SanityCheckExistingBreakpoints(m, deoptimization_kind);
Sebastien Hertz4d1e9ab2014-09-18 16:03:34 +02003367 }
Elliott Hughes86964332012-02-15 19:37:42 -08003368 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -07003369}
3370
Mathieu Chartiere401d142015-04-22 13:56:20 -07003371bool Dbg::IsForcedInterpreterNeededForCallingImpl(Thread* thread, ArtMethod* m) {
Daniel Mihalyieb076692014-08-22 17:33:31 +02003372 const SingleStepControl* const ssc = thread->GetSingleStepControl();
3373 if (ssc == nullptr) {
3374 // If we are not single-stepping, then we don't have to force interpreter.
3375 return false;
3376 }
3377 if (Runtime::Current()->GetInstrumentation()->InterpretOnly()) {
3378 // If we are in interpreter only mode, then we don't have to force interpreter.
3379 return false;
3380 }
3381
3382 if (!m->IsNative() && !m->IsProxyMethod()) {
3383 // If we want to step into a method, then we have to force interpreter on that call.
3384 if (ssc->GetStepDepth() == JDWP::SD_INTO) {
3385 return true;
3386 }
3387 }
3388 return false;
3389}
3390
Mathieu Chartiere401d142015-04-22 13:56:20 -07003391bool Dbg::IsForcedInterpreterNeededForResolutionImpl(Thread* thread, ArtMethod* m) {
Daniel Mihalyieb076692014-08-22 17:33:31 +02003392 instrumentation::Instrumentation* const instrumentation =
3393 Runtime::Current()->GetInstrumentation();
3394 // If we are in interpreter only mode, then we don't have to force interpreter.
3395 if (instrumentation->InterpretOnly()) {
3396 return false;
3397 }
3398 // We can only interpret pure Java method.
3399 if (m->IsNative() || m->IsProxyMethod()) {
3400 return false;
3401 }
3402 const SingleStepControl* const ssc = thread->GetSingleStepControl();
3403 if (ssc != nullptr) {
3404 // If we want to step into a method, then we have to force interpreter on that call.
3405 if (ssc->GetStepDepth() == JDWP::SD_INTO) {
3406 return true;
3407 }
3408 // If we are stepping out from a static initializer, by issuing a step
3409 // in or step over, that was implicitly invoked by calling a static method,
3410 // then we need to step into that method. Having a lower stack depth than
3411 // the one the single step control has indicates that the step originates
3412 // from the static initializer.
3413 if (ssc->GetStepDepth() != JDWP::SD_OUT &&
3414 ssc->GetStackDepth() > GetStackDepth(thread)) {
3415 return true;
3416 }
3417 }
3418 // There are cases where we have to force interpreter on deoptimized methods,
3419 // because in some cases the call will not be performed by invoking an entry
3420 // point that has been replaced by the deoptimization, but instead by directly
3421 // invoking the compiled code of the method, for example.
3422 return instrumentation->IsDeoptimized(m);
3423}
3424
Mathieu Chartiere401d142015-04-22 13:56:20 -07003425bool Dbg::IsForcedInstrumentationNeededForResolutionImpl(Thread* thread, ArtMethod* m) {
Mathieu Chartier2cebb242015-04-21 16:50:40 -07003426 // The upcall can be null and in that case we don't need to do anything.
Daniel Mihalyieb076692014-08-22 17:33:31 +02003427 if (m == nullptr) {
3428 return false;
3429 }
3430 instrumentation::Instrumentation* const instrumentation =
3431 Runtime::Current()->GetInstrumentation();
3432 // If we are in interpreter only mode, then we don't have to force interpreter.
3433 if (instrumentation->InterpretOnly()) {
3434 return false;
3435 }
3436 // We can only interpret pure Java method.
3437 if (m->IsNative() || m->IsProxyMethod()) {
3438 return false;
3439 }
3440 const SingleStepControl* const ssc = thread->GetSingleStepControl();
3441 if (ssc != nullptr) {
3442 // If we are stepping out from a static initializer, by issuing a step
3443 // out, that was implicitly invoked by calling a static method, then we
3444 // need to step into the caller of that method. Having a lower stack
3445 // depth than the one the single step control has indicates that the
3446 // step originates from the static initializer.
3447 if (ssc->GetStepDepth() == JDWP::SD_OUT &&
3448 ssc->GetStackDepth() > GetStackDepth(thread)) {
3449 return true;
3450 }
3451 }
3452 // If we are returning from a static intializer, that was implicitly
3453 // invoked by calling a static method and the caller is deoptimized,
3454 // then we have to deoptimize the stack without forcing interpreter
3455 // on the static method that was called originally. This problem can
3456 // be solved easily by forcing instrumentation on the called method,
3457 // because the instrumentation exit hook will recognise the need of
3458 // stack deoptimization by calling IsForcedInterpreterNeededForUpcall.
3459 return instrumentation->IsDeoptimized(m);
3460}
3461
Mathieu Chartiere401d142015-04-22 13:56:20 -07003462bool Dbg::IsForcedInterpreterNeededForUpcallImpl(Thread* thread, ArtMethod* m) {
Mathieu Chartier2cebb242015-04-21 16:50:40 -07003463 // The upcall can be null and in that case we don't need to do anything.
Daniel Mihalyieb076692014-08-22 17:33:31 +02003464 if (m == nullptr) {
3465 return false;
3466 }
3467 instrumentation::Instrumentation* const instrumentation =
3468 Runtime::Current()->GetInstrumentation();
3469 // If we are in interpreter only mode, then we don't have to force interpreter.
3470 if (instrumentation->InterpretOnly()) {
3471 return false;
3472 }
3473 // We can only interpret pure Java method.
3474 if (m->IsNative() || m->IsProxyMethod()) {
3475 return false;
3476 }
3477 const SingleStepControl* const ssc = thread->GetSingleStepControl();
3478 if (ssc != nullptr) {
3479 // The debugger is not interested in what is happening under the level
3480 // of the step, thus we only force interpreter when we are not below of
3481 // the step.
3482 if (ssc->GetStackDepth() >= GetStackDepth(thread)) {
3483 return true;
3484 }
3485 }
3486 // We have to require stack deoptimization if the upcall is deoptimized.
3487 return instrumentation->IsDeoptimized(m);
3488}
3489
Jeff Hao449db332013-04-12 18:30:52 -07003490// Scoped utility class to suspend a thread so that we may do tasks such as walk its stack. Doesn't
3491// cause suspension if the thread is the current thread.
3492class ScopedThreadSuspension {
3493 public:
Ian Rogers33e95662013-05-20 20:29:14 -07003494 ScopedThreadSuspension(Thread* self, JDWP::ObjectId thread_id)
Mathieu Chartier90443472015-07-16 20:32:27 -07003495 REQUIRES(!Locks::thread_list_lock_)
3496 SHARED_REQUIRES(Locks::mutator_lock_) :
Ian Rogersf3d874c2014-07-17 18:52:42 -07003497 thread_(nullptr),
Jeff Hao449db332013-04-12 18:30:52 -07003498 error_(JDWP::ERR_NONE),
3499 self_suspend_(false),
Ian Rogers33e95662013-05-20 20:29:14 -07003500 other_suspend_(false) {
Jeff Hao449db332013-04-12 18:30:52 -07003501 ScopedObjectAccessUnchecked soa(self);
Sebastien Hertz69206392015-04-07 15:54:25 +02003502 thread_ = DecodeThread(soa, thread_id, &error_);
Jeff Hao449db332013-04-12 18:30:52 -07003503 if (error_ == JDWP::ERR_NONE) {
3504 if (thread_ == soa.Self()) {
3505 self_suspend_ = true;
3506 } else {
3507 soa.Self()->TransitionFromRunnableToSuspended(kWaitingForDebuggerSuspension);
Sebastien Hertz6995c602014-09-09 12:10:13 +02003508 jobject thread_peer = Dbg::GetObjectRegistry()->GetJObject(thread_id);
Jeff Hao449db332013-04-12 18:30:52 -07003509 bool timed_out;
Ian Rogers4ad5cd32014-11-11 23:08:07 -08003510 ThreadList* thread_list = Runtime::Current()->GetThreadList();
3511 Thread* suspended_thread = thread_list->SuspendThreadByPeer(thread_peer, true, true,
3512 &timed_out);
Jeff Hao449db332013-04-12 18:30:52 -07003513 CHECK_EQ(soa.Self()->TransitionFromSuspendedToRunnable(), kWaitingForDebuggerSuspension);
Ian Rogersf3d874c2014-07-17 18:52:42 -07003514 if (suspended_thread == nullptr) {
Jeff Hao449db332013-04-12 18:30:52 -07003515 // Thread terminated from under us while suspending.
3516 error_ = JDWP::ERR_INVALID_THREAD;
3517 } else {
3518 CHECK_EQ(suspended_thread, thread_);
3519 other_suspend_ = true;
3520 }
3521 }
3522 }
Elliott Hughes2435a572012-02-17 16:07:41 -08003523 }
Elliott Hughes86964332012-02-15 19:37:42 -08003524
Jeff Hao449db332013-04-12 18:30:52 -07003525 Thread* GetThread() const {
3526 return thread_;
3527 }
3528
3529 JDWP::JdwpError GetError() const {
3530 return error_;
3531 }
3532
3533 ~ScopedThreadSuspension() {
3534 if (other_suspend_) {
3535 Runtime::Current()->GetThreadList()->Resume(thread_, true);
3536 }
3537 }
3538
3539 private:
3540 Thread* thread_;
3541 JDWP::JdwpError error_;
3542 bool self_suspend_;
3543 bool other_suspend_;
3544};
3545
3546JDWP::JdwpError Dbg::ConfigureStep(JDWP::ObjectId thread_id, JDWP::JdwpStepSize step_size,
3547 JDWP::JdwpStepDepth step_depth) {
3548 Thread* self = Thread::Current();
3549 ScopedThreadSuspension sts(self, thread_id);
3550 if (sts.GetError() != JDWP::ERR_NONE) {
3551 return sts.GetError();
3552 }
3553
Sebastien Hertz597c4f02015-01-26 17:37:14 +01003554 // Work out what ArtMethod* we're in, the current line number, and how deep the stack currently
Elliott Hughes2435a572012-02-17 16:07:41 -08003555 // is for step-out.
Ian Rogers0399dde2012-06-06 17:09:28 -07003556 struct SingleStepStackVisitor : public StackVisitor {
Mathieu Chartier90443472015-07-16 20:32:27 -07003557 explicit SingleStepStackVisitor(Thread* thread) SHARED_REQUIRES(Locks::mutator_lock_)
Nicolas Geoffray8e5bd182015-05-06 11:34:34 +01003558 : StackVisitor(thread, nullptr, StackVisitor::StackWalkKind::kIncludeInlinedFrames),
3559 stack_depth(0),
3560 method(nullptr),
3561 line_number(-1) {}
Ian Rogersca190662012-06-26 15:45:57 -07003562
Ian Rogers00f7d0e2012-07-19 15:28:27 -07003563 // TODO: Enable annotalysis. We know lock is held in constructor, but abstraction confuses
3564 // annotalysis.
3565 bool VisitFrame() NO_THREAD_SAFETY_ANALYSIS {
Mathieu Chartiere401d142015-04-22 13:56:20 -07003566 ArtMethod* m = GetMethod();
Ian Rogers0399dde2012-06-06 17:09:28 -07003567 if (!m->IsRuntimeMethod()) {
Sebastien Hertz597c4f02015-01-26 17:37:14 +01003568 ++stack_depth;
3569 if (method == nullptr) {
Ian Rogersef7d42f2014-01-06 12:55:46 -08003570 mirror::DexCache* dex_cache = m->GetDeclaringClass()->GetDexCache();
Sebastien Hertz597c4f02015-01-26 17:37:14 +01003571 method = m;
Ian Rogersc0542af2014-09-03 16:16:56 -07003572 if (dex_cache != nullptr) {
Ian Rogers4445a7e2012-10-05 17:19:13 -07003573 const DexFile& dex_file = *dex_cache->GetDexFile();
Sebastien Hertz597c4f02015-01-26 17:37:14 +01003574 line_number = dex_file.GetLineNumFromPC(m, GetDexPc());
Elliott Hughes2435a572012-02-17 16:07:41 -08003575 }
Elliott Hughes86964332012-02-15 19:37:42 -08003576 }
3577 }
Elliott Hughes530fa002012-03-12 11:44:49 -07003578 return true;
Elliott Hughes86964332012-02-15 19:37:42 -08003579 }
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01003580
Sebastien Hertz597c4f02015-01-26 17:37:14 +01003581 int stack_depth;
Mathieu Chartiere401d142015-04-22 13:56:20 -07003582 ArtMethod* method;
Sebastien Hertz597c4f02015-01-26 17:37:14 +01003583 int32_t line_number;
Elliott Hughes86964332012-02-15 19:37:42 -08003584 };
Jeff Hao449db332013-04-12 18:30:52 -07003585
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01003586 Thread* const thread = sts.GetThread();
Sebastien Hertz597c4f02015-01-26 17:37:14 +01003587 SingleStepStackVisitor visitor(thread);
Ian Rogers0399dde2012-06-06 17:09:28 -07003588 visitor.WalkStack();
Elliott Hughes86964332012-02-15 19:37:42 -08003589
Elliott Hughes2435a572012-02-17 16:07:41 -08003590 // Find the dex_pc values that correspond to the current line, for line-based single-stepping.
Elliott Hughes2435a572012-02-17 16:07:41 -08003591 struct DebugCallbackContext {
Sebastien Hertz597c4f02015-01-26 17:37:14 +01003592 explicit DebugCallbackContext(SingleStepControl* single_step_control_cb,
3593 int32_t line_number_cb, const DexFile::CodeItem* code_item)
Andreas Gampe277ccbd2014-11-03 21:36:10 -08003594 : single_step_control_(single_step_control_cb), line_number_(line_number_cb),
3595 code_item_(code_item), last_pc_valid(false), last_pc(0) {
Elliott Hughes2435a572012-02-17 16:07:41 -08003596 }
3597
Andreas Gampe277ccbd2014-11-03 21:36:10 -08003598 static bool Callback(void* raw_context, uint32_t address, uint32_t line_number_cb) {
Elliott Hughes2435a572012-02-17 16:07:41 -08003599 DebugCallbackContext* context = reinterpret_cast<DebugCallbackContext*>(raw_context);
Andreas Gampe277ccbd2014-11-03 21:36:10 -08003600 if (static_cast<int32_t>(line_number_cb) == context->line_number_) {
Elliott Hughes2435a572012-02-17 16:07:41 -08003601 if (!context->last_pc_valid) {
3602 // Everything from this address until the next line change is ours.
3603 context->last_pc = address;
3604 context->last_pc_valid = true;
3605 }
3606 // Otherwise, if we're already in a valid range for this line,
3607 // just keep going (shouldn't really happen)...
Brian Carlstrom7934ac22013-07-26 10:54:15 -07003608 } else if (context->last_pc_valid) { // and the line number is new
Elliott Hughes2435a572012-02-17 16:07:41 -08003609 // Add everything from the last entry up until here to the set
3610 for (uint32_t dex_pc = context->last_pc; dex_pc < address; ++dex_pc) {
Sebastien Hertz597c4f02015-01-26 17:37:14 +01003611 context->single_step_control_->AddDexPc(dex_pc);
Elliott Hughes2435a572012-02-17 16:07:41 -08003612 }
3613 context->last_pc_valid = false;
3614 }
Brian Carlstrom7934ac22013-07-26 10:54:15 -07003615 return false; // There may be multiple entries for any given line.
Elliott Hughes2435a572012-02-17 16:07:41 -08003616 }
3617
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01003618 ~DebugCallbackContext() {
Elliott Hughes2435a572012-02-17 16:07:41 -08003619 // If the line number was the last in the position table...
3620 if (last_pc_valid) {
Sebastien Hertzbb43b432014-04-14 11:59:08 +02003621 size_t end = code_item_->insns_size_in_code_units_;
Elliott Hughes2435a572012-02-17 16:07:41 -08003622 for (uint32_t dex_pc = last_pc; dex_pc < end; ++dex_pc) {
Sebastien Hertz597c4f02015-01-26 17:37:14 +01003623 single_step_control_->AddDexPc(dex_pc);
Elliott Hughes2435a572012-02-17 16:07:41 -08003624 }
3625 }
3626 }
3627
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01003628 SingleStepControl* const single_step_control_;
3629 const int32_t line_number_;
Sebastien Hertzbb43b432014-04-14 11:59:08 +02003630 const DexFile::CodeItem* const code_item_;
Elliott Hughes2435a572012-02-17 16:07:41 -08003631 bool last_pc_valid;
3632 uint32_t last_pc;
3633 };
Sebastien Hertz597c4f02015-01-26 17:37:14 +01003634
3635 // Allocate single step.
Sebastien Hertz1558b572015-02-25 15:05:59 +01003636 SingleStepControl* single_step_control =
3637 new (std::nothrow) SingleStepControl(step_size, step_depth,
3638 visitor.stack_depth, visitor.method);
3639 if (single_step_control == nullptr) {
3640 LOG(ERROR) << "Failed to allocate SingleStepControl";
3641 return JDWP::ERR_OUT_OF_MEMORY;
3642 }
3643
Mathieu Chartiere401d142015-04-22 13:56:20 -07003644 ArtMethod* m = single_step_control->GetMethod();
Sebastien Hertz597c4f02015-01-26 17:37:14 +01003645 const int32_t line_number = visitor.line_number;
Sebastien Hertz52f5f932015-05-28 11:00:57 +02003646 // Note: if the thread is not running Java code (pure native thread), there is no "current"
3647 // method on the stack (and no line number either).
3648 if (m != nullptr && !m->IsNative()) {
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07003649 const DexFile::CodeItem* const code_item = m->GetCodeItem();
Sebastien Hertzbb43b432014-04-14 11:59:08 +02003650 DebugCallbackContext context(single_step_control, line_number, code_item);
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07003651 m->GetDexFile()->DecodeDebugInfo(code_item, m->IsStatic(), m->GetDexMethodIndex(),
Ian Rogersc0542af2014-09-03 16:16:56 -07003652 DebugCallbackContext::Callback, nullptr, &context);
Elliott Hughes3e2e1a22012-02-21 11:33:41 -08003653 }
Elliott Hughes2435a572012-02-17 16:07:41 -08003654
Sebastien Hertz597c4f02015-01-26 17:37:14 +01003655 // Activate single-step in the thread.
3656 thread->ActivateSingleStepControl(single_step_control);
Elliott Hughes86964332012-02-15 19:37:42 -08003657
Elliott Hughes2435a572012-02-17 16:07:41 -08003658 if (VLOG_IS_ON(jdwp)) {
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01003659 VLOG(jdwp) << "Single-step thread: " << *thread;
Sebastien Hertz597c4f02015-01-26 17:37:14 +01003660 VLOG(jdwp) << "Single-step step size: " << single_step_control->GetStepSize();
3661 VLOG(jdwp) << "Single-step step depth: " << single_step_control->GetStepDepth();
3662 VLOG(jdwp) << "Single-step current method: " << PrettyMethod(single_step_control->GetMethod());
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01003663 VLOG(jdwp) << "Single-step current line: " << line_number;
Sebastien Hertz597c4f02015-01-26 17:37:14 +01003664 VLOG(jdwp) << "Single-step current stack depth: " << single_step_control->GetStackDepth();
Elliott Hughes2435a572012-02-17 16:07:41 -08003665 VLOG(jdwp) << "Single-step dex_pc values:";
Sebastien Hertz597c4f02015-01-26 17:37:14 +01003666 for (uint32_t dex_pc : single_step_control->GetDexPcs()) {
Sebastien Hertzbb43b432014-04-14 11:59:08 +02003667 VLOG(jdwp) << StringPrintf(" %#x", dex_pc);
Elliott Hughes2435a572012-02-17 16:07:41 -08003668 }
3669 }
3670
3671 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07003672}
3673
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01003674void Dbg::UnconfigureStep(JDWP::ObjectId thread_id) {
3675 ScopedObjectAccessUnchecked soa(Thread::Current());
Ian Rogersc0542af2014-09-03 16:16:56 -07003676 JDWP::JdwpError error;
3677 Thread* thread = DecodeThread(soa, thread_id, &error);
Sebastien Hertz87118ed2013-11-26 17:57:18 +01003678 if (error == JDWP::ERR_NONE) {
Sebastien Hertz597c4f02015-01-26 17:37:14 +01003679 thread->DeactivateSingleStepControl();
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01003680 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -07003681}
3682
Elliott Hughes45651fd2012-02-21 15:48:20 -08003683static char JdwpTagToShortyChar(JDWP::JdwpTag tag) {
3684 switch (tag) {
3685 default:
3686 LOG(FATAL) << "unknown JDWP tag: " << PrintableChar(tag);
Ian Rogersfc787ec2014-10-09 21:56:44 -07003687 UNREACHABLE();
Elliott Hughes45651fd2012-02-21 15:48:20 -08003688
3689 // Primitives.
3690 case JDWP::JT_BYTE: return 'B';
3691 case JDWP::JT_CHAR: return 'C';
3692 case JDWP::JT_FLOAT: return 'F';
3693 case JDWP::JT_DOUBLE: return 'D';
3694 case JDWP::JT_INT: return 'I';
3695 case JDWP::JT_LONG: return 'J';
3696 case JDWP::JT_SHORT: return 'S';
3697 case JDWP::JT_VOID: return 'V';
3698 case JDWP::JT_BOOLEAN: return 'Z';
3699
3700 // Reference types.
3701 case JDWP::JT_ARRAY:
3702 case JDWP::JT_OBJECT:
3703 case JDWP::JT_STRING:
3704 case JDWP::JT_THREAD:
3705 case JDWP::JT_THREAD_GROUP:
3706 case JDWP::JT_CLASS_LOADER:
3707 case JDWP::JT_CLASS_OBJECT:
3708 return 'L';
3709 }
3710}
3711
Sebastien Hertzcbc50642015-06-01 17:33:12 +02003712JDWP::JdwpError Dbg::PrepareInvokeMethod(uint32_t request_id, JDWP::ObjectId thread_id,
3713 JDWP::ObjectId object_id, JDWP::RefTypeId class_id,
3714 JDWP::MethodId method_id, uint32_t arg_count,
3715 uint64_t arg_values[], JDWP::JdwpTag* arg_types,
3716 uint32_t options) {
3717 Thread* const self = Thread::Current();
3718 CHECK_EQ(self, GetDebugThread()) << "This must be called by the JDWP thread";
Elliott Hughesd07986f2011-12-06 18:27:45 -08003719
Sebastien Hertzcbc50642015-06-01 17:33:12 +02003720 ThreadList* thread_list = Runtime::Current()->GetThreadList();
Ian Rogersc0542af2014-09-03 16:16:56 -07003721 Thread* targetThread = nullptr;
Elliott Hughesd07986f2011-12-06 18:27:45 -08003722 {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07003723 ScopedObjectAccessUnchecked soa(self);
Ian Rogersc0542af2014-09-03 16:16:56 -07003724 JDWP::JdwpError error;
3725 targetThread = DecodeThread(soa, thread_id, &error);
Elliott Hughes221229c2013-01-08 18:17:50 -08003726 if (error != JDWP::ERR_NONE) {
3727 LOG(ERROR) << "InvokeMethod request for invalid thread id " << thread_id;
3728 return error;
Elliott Hughesd07986f2011-12-06 18:27:45 -08003729 }
Sebastien Hertz1558b572015-02-25 15:05:59 +01003730 if (targetThread->GetInvokeReq() != nullptr) {
3731 // Thread is already invoking a method on behalf of the debugger.
3732 LOG(ERROR) << "InvokeMethod request for thread already invoking a method: " << *targetThread;
3733 return JDWP::ERR_ALREADY_INVOKING;
3734 }
3735 if (!targetThread->IsReadyForDebugInvoke()) {
3736 // Thread is not suspended by an event so it cannot invoke a method.
Elliott Hughesd07986f2011-12-06 18:27:45 -08003737 LOG(ERROR) << "InvokeMethod request for thread not stopped by event: " << *targetThread;
3738 return JDWP::ERR_INVALID_THREAD;
3739 }
3740
3741 /*
3742 * We currently have a bug where we don't successfully resume the
3743 * target thread if the suspend count is too deep. We're expected to
3744 * require one "resume" for each "suspend", but when asked to execute
3745 * a method we have to resume fully and then re-suspend it back to the
3746 * same level. (The easiest way to cause this is to type "suspend"
3747 * multiple times in jdb.)
3748 *
3749 * It's unclear what this means when the event specifies "resume all"
3750 * and some threads are suspended more deeply than others. This is
3751 * a rare problem, so for now we just prevent it from hanging forever
3752 * by rejecting the method invocation request. Without this, we will
3753 * be stuck waiting on a suspended thread.
3754 */
Ian Rogers00f7d0e2012-07-19 15:28:27 -07003755 int suspend_count;
3756 {
Ian Rogers50b35e22012-10-04 10:09:15 -07003757 MutexLock mu2(soa.Self(), *Locks::thread_suspend_count_lock_);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07003758 suspend_count = targetThread->GetSuspendCount();
3759 }
Elliott Hughesd07986f2011-12-06 18:27:45 -08003760 if (suspend_count > 1) {
3761 LOG(ERROR) << *targetThread << " suspend count too deep for method invocation: " << suspend_count;
Brian Carlstrom7934ac22013-07-26 10:54:15 -07003762 return JDWP::ERR_THREAD_SUSPENDED; // Probably not expected here.
Elliott Hughesd07986f2011-12-06 18:27:45 -08003763 }
3764
Ian Rogersc0542af2014-09-03 16:16:56 -07003765 mirror::Object* receiver = gRegistry->Get<mirror::Object*>(object_id, &error);
3766 if (error != JDWP::ERR_NONE) {
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08003767 return JDWP::ERR_INVALID_OBJECT;
3768 }
Elliott Hughes45651fd2012-02-21 15:48:20 -08003769
Sebastien Hertz1558b572015-02-25 15:05:59 +01003770 gRegistry->Get<mirror::Object*>(thread_id, &error);
Ian Rogersc0542af2014-09-03 16:16:56 -07003771 if (error != JDWP::ERR_NONE) {
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08003772 return JDWP::ERR_INVALID_OBJECT;
3773 }
Elliott Hughes45651fd2012-02-21 15:48:20 -08003774
Ian Rogersc0542af2014-09-03 16:16:56 -07003775 mirror::Class* c = DecodeClass(class_id, &error);
3776 if (c == nullptr) {
3777 return error;
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08003778 }
Elliott Hughes45651fd2012-02-21 15:48:20 -08003779
Mathieu Chartiere401d142015-04-22 13:56:20 -07003780 ArtMethod* m = FromMethodId(method_id);
Ian Rogersc0542af2014-09-03 16:16:56 -07003781 if (m->IsStatic() != (receiver == nullptr)) {
Elliott Hughes45651fd2012-02-21 15:48:20 -08003782 return JDWP::ERR_INVALID_METHODID;
3783 }
3784 if (m->IsStatic()) {
3785 if (m->GetDeclaringClass() != c) {
3786 return JDWP::ERR_INVALID_METHODID;
3787 }
3788 } else {
3789 if (!m->GetDeclaringClass()->IsAssignableFrom(c)) {
3790 return JDWP::ERR_INVALID_METHODID;
3791 }
3792 }
3793
3794 // Check the argument list matches the method.
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07003795 uint32_t shorty_len = 0;
3796 const char* shorty = m->GetShorty(&shorty_len);
3797 if (shorty_len - 1 != arg_count) {
Elliott Hughes45651fd2012-02-21 15:48:20 -08003798 return JDWP::ERR_ILLEGAL_ARGUMENT;
3799 }
Elliott Hughes09201632013-04-15 15:50:07 -07003800
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07003801 {
Mathieu Chartiere401d142015-04-22 13:56:20 -07003802 StackHandleScope<2> hs(soa.Self());
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07003803 HandleWrapper<mirror::Object> h_obj(hs.NewHandleWrapper(&receiver));
3804 HandleWrapper<mirror::Class> h_klass(hs.NewHandleWrapper(&c));
3805 const DexFile::TypeList* types = m->GetParameterTypeList();
3806 for (size_t i = 0; i < arg_count; ++i) {
3807 if (shorty[i + 1] != JdwpTagToShortyChar(arg_types[i])) {
Elliott Hughes09201632013-04-15 15:50:07 -07003808 return JDWP::ERR_ILLEGAL_ARGUMENT;
3809 }
3810
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07003811 if (shorty[i + 1] == 'L') {
3812 // Did we really get an argument of an appropriate reference type?
Ian Rogersa0485602014-12-02 15:48:04 -08003813 mirror::Class* parameter_type =
Mathieu Chartiere401d142015-04-22 13:56:20 -07003814 m->GetClassFromTypeIndex(types->GetTypeItem(i).type_idx_, true);
Ian Rogersc0542af2014-09-03 16:16:56 -07003815 mirror::Object* argument = gRegistry->Get<mirror::Object*>(arg_values[i], &error);
3816 if (error != JDWP::ERR_NONE) {
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07003817 return JDWP::ERR_INVALID_OBJECT;
3818 }
Ian Rogersc0542af2014-09-03 16:16:56 -07003819 if (argument != nullptr && !argument->InstanceOf(parameter_type)) {
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07003820 return JDWP::ERR_ILLEGAL_ARGUMENT;
3821 }
3822
3823 // Turn the on-the-wire ObjectId into a jobject.
3824 jvalue& v = reinterpret_cast<jvalue&>(arg_values[i]);
3825 v.l = gRegistry->GetJObject(arg_values[i]);
3826 }
Elliott Hughes09201632013-04-15 15:50:07 -07003827 }
Elliott Hughes45651fd2012-02-21 15:48:20 -08003828 }
3829
Sebastien Hertz1558b572015-02-25 15:05:59 +01003830 // Allocates a DebugInvokeReq.
Sebastien Hertzcbc50642015-06-01 17:33:12 +02003831 DebugInvokeReq* req = new (std::nothrow) DebugInvokeReq(request_id, thread_id, receiver, c, m,
3832 options, arg_values, arg_count);
3833 if (req == nullptr) {
Sebastien Hertz1558b572015-02-25 15:05:59 +01003834 LOG(ERROR) << "Failed to allocate DebugInvokeReq";
3835 return JDWP::ERR_OUT_OF_MEMORY;
3836 }
3837
Sebastien Hertzcbc50642015-06-01 17:33:12 +02003838 // Attaches the DebugInvokeReq to the target thread so it executes the method when
3839 // it is resumed. Once the invocation completes, the target thread will delete it before
3840 // suspending itself (see ThreadList::SuspendSelfForDebugger).
3841 targetThread->SetDebugInvokeReq(req);
Elliott Hughesd07986f2011-12-06 18:27:45 -08003842 }
3843
3844 // 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 +02003845 // away we're sitting high and dry -- but we must release this before the UndoDebuggerSuspensions
3846 // call.
Elliott Hughesd07986f2011-12-06 18:27:45 -08003847
Elliott Hughesd07986f2011-12-06 18:27:45 -08003848 if ((options & JDWP::INVOKE_SINGLE_THREADED) == 0) {
Sebastien Hertzcbc50642015-06-01 17:33:12 +02003849 VLOG(jdwp) << " Resuming all threads";
3850 thread_list->UndoDebuggerSuspensions();
3851 } else {
3852 VLOG(jdwp) << " Resuming event thread only";
Elliott Hughesd07986f2011-12-06 18:27:45 -08003853 thread_list->Resume(targetThread, true);
3854 }
3855
Sebastien Hertzcbc50642015-06-01 17:33:12 +02003856 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07003857}
3858
3859void Dbg::ExecuteMethod(DebugInvokeReq* pReq) {
Sebastien Hertzcbc50642015-06-01 17:33:12 +02003860 Thread* const self = Thread::Current();
3861 CHECK_NE(self, GetDebugThread()) << "This must be called by the event thread";
3862
3863 ScopedObjectAccess soa(self);
Elliott Hughesd07986f2011-12-06 18:27:45 -08003864
Elliott Hughes81ff3182012-03-23 20:35:56 -07003865 // We can be called while an exception is pending. We need
Elliott Hughesd07986f2011-12-06 18:27:45 -08003866 // to preserve that across the method invocation.
Sebastien Hertzcbc50642015-06-01 17:33:12 +02003867 StackHandleScope<1> hs(soa.Self());
3868 Handle<mirror::Throwable> old_exception = hs.NewHandle(soa.Self()->GetException());
Sebastien Hertz1558b572015-02-25 15:05:59 +01003869 soa.Self()->ClearException();
Elliott Hughesd07986f2011-12-06 18:27:45 -08003870
Sebastien Hertzcbc50642015-06-01 17:33:12 +02003871 // Execute the method then sends reply to the debugger.
3872 ExecuteMethodWithoutPendingException(soa, pReq);
3873
3874 // If an exception was pending before the invoke, restore it now.
3875 if (old_exception.Get() != nullptr) {
3876 soa.Self()->SetException(old_exception.Get());
3877 }
3878}
3879
3880// Helper function: write a variable-width value into the output input buffer.
3881static void WriteValue(JDWP::ExpandBuf* pReply, int width, uint64_t value) {
3882 switch (width) {
3883 case 1:
3884 expandBufAdd1(pReply, value);
3885 break;
3886 case 2:
3887 expandBufAdd2BE(pReply, value);
3888 break;
3889 case 4:
3890 expandBufAdd4BE(pReply, value);
3891 break;
3892 case 8:
3893 expandBufAdd8BE(pReply, value);
3894 break;
3895 default:
3896 LOG(FATAL) << width;
3897 UNREACHABLE();
3898 }
3899}
3900
3901void Dbg::ExecuteMethodWithoutPendingException(ScopedObjectAccess& soa, DebugInvokeReq* pReq) {
3902 soa.Self()->AssertNoPendingException();
3903
Elliott Hughesd07986f2011-12-06 18:27:45 -08003904 // Translate the method through the vtable, unless the debugger wants to suppress it.
Sebastien Hertzcbc50642015-06-01 17:33:12 +02003905 ArtMethod* m = pReq->method;
3906 size_t image_pointer_size = Runtime::Current()->GetClassLinker()->GetImagePointerSize();
Sebastien Hertz1558b572015-02-25 15:05:59 +01003907 if ((pReq->options & JDWP::INVOKE_NONVIRTUAL) == 0 && pReq->receiver.Read() != nullptr) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07003908 ArtMethod* actual_method =
3909 pReq->klass.Read()->FindVirtualMethodForVirtualOrInterface(m, image_pointer_size);
3910 if (actual_method != m) {
3911 VLOG(jdwp) << "ExecuteMethod translated " << PrettyMethod(m)
Sebastien Hertz1558b572015-02-25 15:05:59 +01003912 << " to " << PrettyMethod(actual_method);
Mathieu Chartiere401d142015-04-22 13:56:20 -07003913 m = actual_method;
Elliott Hughes45651fd2012-02-21 15:48:20 -08003914 }
Elliott Hughesd07986f2011-12-06 18:27:45 -08003915 }
Mathieu Chartiere401d142015-04-22 13:56:20 -07003916 VLOG(jdwp) << "ExecuteMethod " << PrettyMethod(m)
Sebastien Hertz1558b572015-02-25 15:05:59 +01003917 << " receiver=" << pReq->receiver.Read()
Sebastien Hertzd38667a2013-11-25 15:43:54 +01003918 << " arg_count=" << pReq->arg_count;
Mathieu Chartiere401d142015-04-22 13:56:20 -07003919 CHECK(m != nullptr);
Elliott Hughesd07986f2011-12-06 18:27:45 -08003920
Roland Levillain33d69032015-06-18 18:20:59 +01003921 static_assert(sizeof(jvalue) == sizeof(uint64_t), "jvalue and uint64_t have different sizes.");
Elliott Hughesd07986f2011-12-06 18:27:45 -08003922
Sebastien Hertzcbc50642015-06-01 17:33:12 +02003923 // Invoke the method.
Jeff Hao39b6c242015-05-19 20:30:23 -07003924 ScopedLocalRef<jobject> ref(soa.Env(), soa.AddLocalReference<jobject>(pReq->receiver.Read()));
Mathieu Chartiere401d142015-04-22 13:56:20 -07003925 JValue result = InvokeWithJValues(soa, ref.get(), soa.EncodeMethod(m),
Sebastien Hertzcbc50642015-06-01 17:33:12 +02003926 reinterpret_cast<jvalue*>(pReq->arg_values.get()));
Elliott Hughesd07986f2011-12-06 18:27:45 -08003927
Sebastien Hertzcbc50642015-06-01 17:33:12 +02003928 // Prepare JDWP ids for the reply.
3929 JDWP::JdwpTag result_tag = BasicTagFromDescriptor(m->GetShorty());
3930 const bool is_object_result = (result_tag == JDWP::JT_OBJECT);
3931 StackHandleScope<2> hs(soa.Self());
Sebastien Hertz1558b572015-02-25 15:05:59 +01003932 Handle<mirror::Object> object_result = hs.NewHandle(is_object_result ? result.GetL() : nullptr);
3933 Handle<mirror::Throwable> exception = hs.NewHandle(soa.Self()->GetException());
3934 soa.Self()->ClearException();
Sebastien Hertzcbc50642015-06-01 17:33:12 +02003935
3936 if (!IsDebuggerActive()) {
3937 // The debugger detached: we must not re-suspend threads. We also don't need to fill the reply
3938 // because it won't be sent either.
3939 return;
3940 }
3941
3942 JDWP::ObjectId exceptionObjectId = gRegistry->Add(exception);
3943 uint64_t result_value = 0;
3944 if (exceptionObjectId != 0) {
Sebastien Hertz1558b572015-02-25 15:05:59 +01003945 VLOG(jdwp) << " JDWP invocation returning with exception=" << exception.Get()
3946 << " " << exception->Dump();
Sebastien Hertzcbc50642015-06-01 17:33:12 +02003947 result_value = 0;
Sebastien Hertz1558b572015-02-25 15:05:59 +01003948 } else if (is_object_result) {
Sebastien Hertzcbc50642015-06-01 17:33:12 +02003949 /* if no exception was thrown, examine object result more closely */
Sebastien Hertz1558b572015-02-25 15:05:59 +01003950 JDWP::JdwpTag new_tag = TagFromObject(soa, object_result.Get());
Sebastien Hertzcbc50642015-06-01 17:33:12 +02003951 if (new_tag != result_tag) {
3952 VLOG(jdwp) << " JDWP promoted result from " << result_tag << " to " << new_tag;
3953 result_tag = new_tag;
Elliott Hughesd07986f2011-12-06 18:27:45 -08003954 }
3955
Sebastien Hertz1558b572015-02-25 15:05:59 +01003956 // Register the object in the registry and reference its ObjectId. This ensures
3957 // GC safety and prevents from accessing stale reference if the object is moved.
Sebastien Hertzcbc50642015-06-01 17:33:12 +02003958 result_value = gRegistry->Add(object_result.Get());
Sebastien Hertz1558b572015-02-25 15:05:59 +01003959 } else {
3960 // Primitive result.
Sebastien Hertzcbc50642015-06-01 17:33:12 +02003961 DCHECK(IsPrimitiveTag(result_tag));
3962 result_value = result.GetJ();
3963 }
3964 const bool is_constructor = m->IsConstructor() && !m->IsStatic();
3965 if (is_constructor) {
3966 // If we invoked a constructor (which actually returns void), return the receiver,
3967 // unless we threw, in which case we return null.
3968 result_tag = JDWP::JT_OBJECT;
3969 if (exceptionObjectId == 0) {
3970 // TODO we could keep the receiver ObjectId in the DebugInvokeReq to avoid looking into the
3971 // object registry.
3972 result_value = GetObjectRegistry()->Add(pReq->receiver.Read());
3973 } else {
3974 result_value = 0;
3975 }
Elliott Hughesd07986f2011-12-06 18:27:45 -08003976 }
3977
Sebastien Hertzcbc50642015-06-01 17:33:12 +02003978 // Suspend other threads if the invoke is not single-threaded.
3979 if ((pReq->options & JDWP::INVOKE_SINGLE_THREADED) == 0) {
3980 soa.Self()->TransitionFromRunnableToSuspended(kWaitingForDebuggerSuspension);
3981 VLOG(jdwp) << " Suspending all threads";
3982 Runtime::Current()->GetThreadList()->SuspendAllForDebugger();
3983 soa.Self()->TransitionFromSuspendedToRunnable();
3984 }
3985
3986 VLOG(jdwp) << " --> returned " << result_tag
3987 << StringPrintf(" %#" PRIx64 " (except=%#" PRIx64 ")", result_value,
3988 exceptionObjectId);
3989
3990 // Show detailed debug output.
3991 if (result_tag == JDWP::JT_STRING && exceptionObjectId == 0) {
3992 if (result_value != 0) {
3993 if (VLOG_IS_ON(jdwp)) {
3994 std::string result_string;
3995 JDWP::JdwpError error = Dbg::StringToUtf8(result_value, &result_string);
3996 CHECK_EQ(error, JDWP::ERR_NONE);
3997 VLOG(jdwp) << " string '" << result_string << "'";
3998 }
3999 } else {
4000 VLOG(jdwp) << " string (null)";
4001 }
4002 }
4003
4004 // Attach the reply to DebugInvokeReq so it can be sent to the debugger when the event thread
4005 // is ready to suspend.
4006 BuildInvokeReply(pReq->reply, pReq->request_id, result_tag, result_value, exceptionObjectId);
4007}
4008
4009void Dbg::BuildInvokeReply(JDWP::ExpandBuf* pReply, uint32_t request_id, JDWP::JdwpTag result_tag,
4010 uint64_t result_value, JDWP::ObjectId exception) {
4011 // Make room for the JDWP header since we do not know the size of the reply yet.
4012 JDWP::expandBufAddSpace(pReply, kJDWPHeaderLen);
4013
4014 size_t width = GetTagWidth(result_tag);
4015 JDWP::expandBufAdd1(pReply, result_tag);
4016 if (width != 0) {
4017 WriteValue(pReply, width, result_value);
4018 }
4019 JDWP::expandBufAdd1(pReply, JDWP::JT_OBJECT);
4020 JDWP::expandBufAddObjectId(pReply, exception);
4021
4022 // Now we know the size, we can complete the JDWP header.
4023 uint8_t* buf = expandBufGetBuffer(pReply);
4024 JDWP::Set4BE(buf + kJDWPHeaderSizeOffset, expandBufGetLength(pReply));
4025 JDWP::Set4BE(buf + kJDWPHeaderIdOffset, request_id);
4026 JDWP::Set1(buf + kJDWPHeaderFlagsOffset, kJDWPFlagReply); // flags
4027 JDWP::Set2BE(buf + kJDWPHeaderErrorCodeOffset, JDWP::ERR_NONE);
4028}
4029
4030void Dbg::FinishInvokeMethod(DebugInvokeReq* pReq) {
4031 CHECK_NE(Thread::Current(), GetDebugThread()) << "This must be called by the event thread";
4032
4033 JDWP::ExpandBuf* const pReply = pReq->reply;
4034 CHECK(pReply != nullptr) << "No reply attached to DebugInvokeReq";
4035
4036 // We need to prevent other threads (including JDWP thread) from interacting with the debugger
4037 // while we send the reply but are not yet suspended. The JDWP token will be released just before
4038 // we suspend ourself again (see ThreadList::SuspendSelfForDebugger).
4039 gJdwpState->AcquireJdwpTokenForEvent(pReq->thread_id);
4040
4041 // Send the reply unless the debugger detached before the completion of the method.
4042 if (IsDebuggerActive()) {
4043 const size_t replyDataLength = expandBufGetLength(pReply) - kJDWPHeaderLen;
4044 VLOG(jdwp) << StringPrintf("REPLY INVOKE id=0x%06x (length=%zu)",
4045 pReq->request_id, replyDataLength);
4046
4047 gJdwpState->SendRequest(pReply);
4048 } else {
4049 VLOG(jdwp) << "Not sending invoke reply because debugger detached";
Elliott Hughesd07986f2011-12-06 18:27:45 -08004050 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -07004051}
4052
Elliott Hughesd07986f2011-12-06 18:27:45 -08004053/*
Elliott Hughes4b9702c2013-02-20 18:13:24 -08004054 * "request" contains a full JDWP packet, possibly with multiple chunks. We
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07004055 * need to process each, accumulate the replies, and ship the whole thing
4056 * back.
4057 *
4058 * Returns "true" if we have a reply. The reply buffer is newly allocated,
4059 * and includes the chunk type/length, followed by the data.
4060 *
Elliott Hughes3d30d9b2011-12-07 17:35:48 -08004061 * OLD-TODO: we currently assume that the request and reply include a single
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07004062 * chunk. If this becomes inconvenient we will need to adapt.
4063 */
Ian Rogersc0542af2014-09-03 16:16:56 -07004064bool Dbg::DdmHandlePacket(JDWP::Request* request, uint8_t** pReplyBuf, int* pReplyLen) {
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07004065 Thread* self = Thread::Current();
4066 JNIEnv* env = self->GetJniEnv();
4067
Ian Rogersc0542af2014-09-03 16:16:56 -07004068 uint32_t type = request->ReadUnsigned32("type");
4069 uint32_t length = request->ReadUnsigned32("length");
Elliott Hughes4b9702c2013-02-20 18:13:24 -08004070
4071 // Create a byte[] corresponding to 'request'.
Ian Rogersc0542af2014-09-03 16:16:56 -07004072 size_t request_length = request->size();
Elliott Hughes4b9702c2013-02-20 18:13:24 -08004073 ScopedLocalRef<jbyteArray> dataArray(env, env->NewByteArray(request_length));
Ian Rogersc0542af2014-09-03 16:16:56 -07004074 if (dataArray.get() == nullptr) {
Elliott Hughes4b9702c2013-02-20 18:13:24 -08004075 LOG(WARNING) << "byte[] allocation failed: " << request_length;
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07004076 env->ExceptionClear();
4077 return false;
4078 }
Ian Rogersc0542af2014-09-03 16:16:56 -07004079 env->SetByteArrayRegion(dataArray.get(), 0, request_length,
4080 reinterpret_cast<const jbyte*>(request->data()));
4081 request->Skip(request_length);
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07004082
4083 // Run through and find all chunks. [Currently just find the first.]
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004084 ScopedByteArrayRO contents(env, dataArray.get());
Elliott Hughes4b9702c2013-02-20 18:13:24 -08004085 if (length != request_length) {
Ian Rogersef7d42f2014-01-06 12:55:46 -08004086 LOG(WARNING) << StringPrintf("bad chunk found (len=%u pktLen=%zd)", length, request_length);
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07004087 return false;
4088 }
4089
4090 // Call "private static Chunk dispatch(int type, byte[] data, int offset, int length)".
Elliott Hugheseac76672012-05-24 21:56:51 -07004091 ScopedLocalRef<jobject> chunk(env, env->CallStaticObjectMethod(WellKnownClasses::org_apache_harmony_dalvik_ddmc_DdmServer,
4092 WellKnownClasses::org_apache_harmony_dalvik_ddmc_DdmServer_dispatch,
Elliott Hughes4b9702c2013-02-20 18:13:24 -08004093 type, dataArray.get(), 0, length));
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07004094 if (env->ExceptionCheck()) {
4095 LOG(INFO) << StringPrintf("Exception thrown by dispatcher for 0x%08x", type);
4096 env->ExceptionDescribe();
4097 env->ExceptionClear();
4098 return false;
4099 }
4100
Ian Rogersc0542af2014-09-03 16:16:56 -07004101 if (chunk.get() == nullptr) {
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07004102 return false;
4103 }
4104
4105 /*
4106 * Pull the pieces out of the chunk. We copy the results into a
4107 * newly-allocated buffer that the caller can free. We don't want to
4108 * continue using the Chunk object because nothing has a reference to it.
4109 *
4110 * We could avoid this by returning type/data/offset/length and having
4111 * the caller be aware of the object lifetime issues, but that
Elliott Hughes81ff3182012-03-23 20:35:56 -07004112 * integrates the JDWP code more tightly into the rest of the runtime, and doesn't work
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07004113 * if we have responses for multiple chunks.
4114 *
4115 * So we're pretty much stuck with copying data around multiple times.
4116 */
Elliott Hugheseac76672012-05-24 21:56:51 -07004117 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 -08004118 jint offset = env->GetIntField(chunk.get(), WellKnownClasses::org_apache_harmony_dalvik_ddmc_Chunk_offset);
Elliott Hugheseac76672012-05-24 21:56:51 -07004119 length = env->GetIntField(chunk.get(), WellKnownClasses::org_apache_harmony_dalvik_ddmc_Chunk_length);
Elliott Hugheseac76672012-05-24 21:56:51 -07004120 type = env->GetIntField(chunk.get(), WellKnownClasses::org_apache_harmony_dalvik_ddmc_Chunk_type);
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07004121
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08004122 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 -07004123 if (length == 0 || replyData.get() == nullptr) {
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07004124 return false;
4125 }
4126
Elliott Hughes4b9702c2013-02-20 18:13:24 -08004127 const int kChunkHdrLen = 8;
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07004128 uint8_t* reply = new uint8_t[length + kChunkHdrLen];
Ian Rogersc0542af2014-09-03 16:16:56 -07004129 if (reply == nullptr) {
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07004130 LOG(WARNING) << "malloc failed: " << (length + kChunkHdrLen);
4131 return false;
4132 }
Elliott Hughesf7c3b662011-10-27 12:04:56 -07004133 JDWP::Set4BE(reply + 0, type);
4134 JDWP::Set4BE(reply + 4, length);
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004135 env->GetByteArrayRegion(replyData.get(), offset, length, reinterpret_cast<jbyte*>(reply + kChunkHdrLen));
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07004136
4137 *pReplyBuf = reply;
4138 *pReplyLen = length + kChunkHdrLen;
4139
Elliott Hughes4b9702c2013-02-20 18:13:24 -08004140 VLOG(jdwp) << StringPrintf("dvmHandleDdm returning type=%.4s %p len=%d", reinterpret_cast<char*>(reply), reply, length);
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07004141 return true;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07004142}
4143
Elliott Hughesa2155262011-11-16 16:26:58 -08004144void Dbg::DdmBroadcast(bool connect) {
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08004145 VLOG(jdwp) << "Broadcasting DDM " << (connect ? "connect" : "disconnect") << "...";
Elliott Hughes47fce012011-10-25 18:37:19 -07004146
4147 Thread* self = Thread::Current();
Ian Rogers50b35e22012-10-04 10:09:15 -07004148 if (self->GetState() != kRunnable) {
4149 LOG(ERROR) << "DDM broadcast in thread state " << self->GetState();
4150 /* try anyway? */
Elliott Hughes47fce012011-10-25 18:37:19 -07004151 }
4152
4153 JNIEnv* env = self->GetJniEnv();
Elliott Hughes47fce012011-10-25 18:37:19 -07004154 jint event = connect ? 1 /*DdmServer.CONNECTED*/ : 2 /*DdmServer.DISCONNECTED*/;
Elliott Hugheseac76672012-05-24 21:56:51 -07004155 env->CallStaticVoidMethod(WellKnownClasses::org_apache_harmony_dalvik_ddmc_DdmServer,
4156 WellKnownClasses::org_apache_harmony_dalvik_ddmc_DdmServer_broadcast,
4157 event);
Elliott Hughes47fce012011-10-25 18:37:19 -07004158 if (env->ExceptionCheck()) {
4159 LOG(ERROR) << "DdmServer.broadcast " << event << " failed";
4160 env->ExceptionDescribe();
4161 env->ExceptionClear();
4162 }
4163}
4164
Elliott Hughes872d4ec2011-10-21 17:07:15 -07004165void Dbg::DdmConnected() {
Elliott Hughesa2155262011-11-16 16:26:58 -08004166 Dbg::DdmBroadcast(true);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07004167}
4168
4169void Dbg::DdmDisconnected() {
Elliott Hughesa2155262011-11-16 16:26:58 -08004170 Dbg::DdmBroadcast(false);
Elliott Hughes47fce012011-10-25 18:37:19 -07004171 gDdmThreadNotification = false;
4172}
4173
4174/*
Elliott Hughes82188472011-11-07 18:11:48 -08004175 * Send a notification when a thread starts, stops, or changes its name.
Elliott Hughes47fce012011-10-25 18:37:19 -07004176 *
4177 * Because we broadcast the full set of threads when the notifications are
4178 * first enabled, it's possible for "thread" to be actively executing.
4179 */
Elliott Hughes82188472011-11-07 18:11:48 -08004180void Dbg::DdmSendThreadNotification(Thread* t, uint32_t type) {
Elliott Hughes47fce012011-10-25 18:37:19 -07004181 if (!gDdmThreadNotification) {
4182 return;
4183 }
4184
Elliott Hughes82188472011-11-07 18:11:48 -08004185 if (type == CHUNK_TYPE("THDE")) {
Elliott Hughes47fce012011-10-25 18:37:19 -07004186 uint8_t buf[4];
Ian Rogersd9c4fc92013-10-01 19:45:43 -07004187 JDWP::Set4BE(&buf[0], t->GetThreadId());
Elliott Hughes47fce012011-10-25 18:37:19 -07004188 Dbg::DdmSendChunk(CHUNK_TYPE("THDE"), 4, buf);
Elliott Hughes82188472011-11-07 18:11:48 -08004189 } else {
4190 CHECK(type == CHUNK_TYPE("THCR") || type == CHUNK_TYPE("THNM")) << type;
Ian Rogers00f7d0e2012-07-19 15:28:27 -07004191 ScopedObjectAccessUnchecked soa(Thread::Current());
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004192 StackHandleScope<1> hs(soa.Self());
4193 Handle<mirror::String> name(hs.NewHandle(t->GetThreadName(soa)));
Ian Rogersc0542af2014-09-03 16:16:56 -07004194 size_t char_count = (name.Get() != nullptr) ? name->GetLength() : 0;
Jeff Hao848f70a2014-01-15 13:49:50 -08004195 const jchar* chars = (name.Get() != nullptr) ? name->GetValue() : nullptr;
Elliott Hughes82188472011-11-07 18:11:48 -08004196
Elliott Hughes21f32d72011-11-09 17:44:13 -08004197 std::vector<uint8_t> bytes;
Ian Rogersd9c4fc92013-10-01 19:45:43 -07004198 JDWP::Append4BE(bytes, t->GetThreadId());
Elliott Hughes545a0642011-11-08 19:10:03 -08004199 JDWP::AppendUtf16BE(bytes, chars, char_count);
Elliott Hughes21f32d72011-11-09 17:44:13 -08004200 CHECK_EQ(bytes.size(), char_count*2 + sizeof(uint32_t)*2);
4201 Dbg::DdmSendChunk(type, bytes);
Elliott Hughes47fce012011-10-25 18:37:19 -07004202 }
4203}
4204
Elliott Hughes47fce012011-10-25 18:37:19 -07004205void Dbg::DdmSetThreadNotification(bool enable) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07004206 // Enable/disable thread notifications.
Elliott Hughes47fce012011-10-25 18:37:19 -07004207 gDdmThreadNotification = enable;
4208 if (enable) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07004209 // Suspend the VM then post thread start notifications for all threads. Threads attaching will
4210 // see a suspension in progress and block until that ends. They then post their own start
4211 // notification.
4212 SuspendVM();
4213 std::list<Thread*> threads;
Ian Rogers50b35e22012-10-04 10:09:15 -07004214 Thread* self = Thread::Current();
Ian Rogers00f7d0e2012-07-19 15:28:27 -07004215 {
Ian Rogers50b35e22012-10-04 10:09:15 -07004216 MutexLock mu(self, *Locks::thread_list_lock_);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07004217 threads = Runtime::Current()->GetThreadList()->GetList();
4218 }
4219 {
Ian Rogers50b35e22012-10-04 10:09:15 -07004220 ScopedObjectAccess soa(self);
Mathieu Chartier02e25112013-08-14 16:14:24 -07004221 for (Thread* thread : threads) {
4222 Dbg::DdmSendThreadNotification(thread, CHUNK_TYPE("THCR"));
Ian Rogers00f7d0e2012-07-19 15:28:27 -07004223 }
4224 }
4225 ResumeVM();
Elliott Hughes47fce012011-10-25 18:37:19 -07004226 }
4227}
4228
Elliott Hughesa2155262011-11-16 16:26:58 -08004229void Dbg::PostThreadStartOrStop(Thread* t, uint32_t type) {
Elliott Hughesc0f09332012-03-26 13:27:06 -07004230 if (IsDebuggerActive()) {
Sebastien Hertz6995c602014-09-09 12:10:13 +02004231 gJdwpState->PostThreadChange(t, type == CHUNK_TYPE("THCR"));
Elliott Hughes47fce012011-10-25 18:37:19 -07004232 }
Elliott Hughes82188472011-11-07 18:11:48 -08004233 Dbg::DdmSendThreadNotification(t, type);
Elliott Hughes47fce012011-10-25 18:37:19 -07004234}
4235
4236void Dbg::PostThreadStart(Thread* t) {
Elliott Hughesa2155262011-11-16 16:26:58 -08004237 Dbg::PostThreadStartOrStop(t, CHUNK_TYPE("THCR"));
Elliott Hughes47fce012011-10-25 18:37:19 -07004238}
4239
4240void Dbg::PostThreadDeath(Thread* t) {
Elliott Hughesa2155262011-11-16 16:26:58 -08004241 Dbg::PostThreadStartOrStop(t, CHUNK_TYPE("THDE"));
Elliott Hughes872d4ec2011-10-21 17:07:15 -07004242}
4243
Elliott Hughes82188472011-11-07 18:11:48 -08004244void Dbg::DdmSendChunk(uint32_t type, size_t byte_count, const uint8_t* buf) {
Ian Rogersc0542af2014-09-03 16:16:56 -07004245 CHECK(buf != nullptr);
Elliott Hughes3bb81562011-10-21 18:52:59 -07004246 iovec vec[1];
4247 vec[0].iov_base = reinterpret_cast<void*>(const_cast<uint8_t*>(buf));
4248 vec[0].iov_len = byte_count;
4249 Dbg::DdmSendChunkV(type, vec, 1);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07004250}
4251
Elliott Hughes21f32d72011-11-09 17:44:13 -08004252void Dbg::DdmSendChunk(uint32_t type, const std::vector<uint8_t>& bytes) {
4253 DdmSendChunk(type, bytes.size(), &bytes[0]);
4254}
4255
Brian Carlstromf5293522013-07-19 00:24:00 -07004256void Dbg::DdmSendChunkV(uint32_t type, const iovec* iov, int iov_count) {
Ian Rogersc0542af2014-09-03 16:16:56 -07004257 if (gJdwpState == nullptr) {
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08004258 VLOG(jdwp) << "Debugger thread not active, ignoring DDM send: " << type;
Elliott Hughes3bb81562011-10-21 18:52:59 -07004259 } else {
Elliott Hughescccd84f2011-12-05 16:51:54 -08004260 gJdwpState->DdmSendChunkV(type, iov, iov_count);
Elliott Hughes3bb81562011-10-21 18:52:59 -07004261 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -07004262}
4263
Mathieu Chartierad466ad2015-01-08 16:28:08 -08004264JDWP::JdwpState* Dbg::GetJdwpState() {
4265 return gJdwpState;
4266}
4267
Elliott Hughes767a1472011-10-26 18:49:02 -07004268int Dbg::DdmHandleHpifChunk(HpifWhen when) {
4269 if (when == HPIF_WHEN_NOW) {
Elliott Hughes7162ad92011-10-27 14:08:42 -07004270 DdmSendHeapInfo(when);
Elliott Hughes767a1472011-10-26 18:49:02 -07004271 return true;
4272 }
4273
4274 if (when != HPIF_WHEN_NEVER && when != HPIF_WHEN_NEXT_GC && when != HPIF_WHEN_EVERY_GC) {
4275 LOG(ERROR) << "invalid HpifWhen value: " << static_cast<int>(when);
4276 return false;
4277 }
4278
4279 gDdmHpifWhen = when;
4280 return true;
4281}
4282
4283bool Dbg::DdmHandleHpsgNhsgChunk(Dbg::HpsgWhen when, Dbg::HpsgWhat what, bool native) {
4284 if (when != HPSG_WHEN_NEVER && when != HPSG_WHEN_EVERY_GC) {
4285 LOG(ERROR) << "invalid HpsgWhen value: " << static_cast<int>(when);
4286 return false;
4287 }
4288
4289 if (what != HPSG_WHAT_MERGED_OBJECTS && what != HPSG_WHAT_DISTINCT_OBJECTS) {
4290 LOG(ERROR) << "invalid HpsgWhat value: " << static_cast<int>(what);
4291 return false;
4292 }
4293
4294 if (native) {
4295 gDdmNhsgWhen = when;
4296 gDdmNhsgWhat = what;
4297 } else {
4298 gDdmHpsgWhen = when;
4299 gDdmHpsgWhat = what;
4300 }
4301 return true;
4302}
4303
Elliott Hughes7162ad92011-10-27 14:08:42 -07004304void Dbg::DdmSendHeapInfo(HpifWhen reason) {
4305 // If there's a one-shot 'when', reset it.
4306 if (reason == gDdmHpifWhen) {
4307 if (gDdmHpifWhen == HPIF_WHEN_NEXT_GC) {
4308 gDdmHpifWhen = HPIF_WHEN_NEVER;
4309 }
4310 }
4311
4312 /*
4313 * Chunk HPIF (client --> server)
4314 *
4315 * Heap Info. General information about the heap,
4316 * suitable for a summary display.
4317 *
4318 * [u4]: number of heaps
4319 *
4320 * For each heap:
4321 * [u4]: heap ID
4322 * [u8]: timestamp in ms since Unix epoch
4323 * [u1]: capture reason (same as 'when' value from server)
4324 * [u4]: max heap size in bytes (-Xmx)
4325 * [u4]: current heap size in bytes
4326 * [u4]: current number of bytes allocated
4327 * [u4]: current number of objects allocated
4328 */
4329 uint8_t heap_count = 1;
Ian Rogers1d54e732013-05-02 21:10:01 -07004330 gc::Heap* heap = Runtime::Current()->GetHeap();
Elliott Hughes21f32d72011-11-09 17:44:13 -08004331 std::vector<uint8_t> bytes;
Elliott Hughes545a0642011-11-08 19:10:03 -08004332 JDWP::Append4BE(bytes, heap_count);
Brian Carlstrom7934ac22013-07-26 10:54:15 -07004333 JDWP::Append4BE(bytes, 1); // Heap id (bogus; we only have one heap).
Elliott Hughes545a0642011-11-08 19:10:03 -08004334 JDWP::Append8BE(bytes, MilliTime());
4335 JDWP::Append1BE(bytes, reason);
Brian Carlstrom7934ac22013-07-26 10:54:15 -07004336 JDWP::Append4BE(bytes, heap->GetMaxMemory()); // Max allowed heap size in bytes.
4337 JDWP::Append4BE(bytes, heap->GetTotalMemory()); // Current heap size in bytes.
Elliott Hughesb3bd5f02012-03-08 21:05:27 -08004338 JDWP::Append4BE(bytes, heap->GetBytesAllocated());
4339 JDWP::Append4BE(bytes, heap->GetObjectsAllocated());
Elliott Hughes21f32d72011-11-09 17:44:13 -08004340 CHECK_EQ(bytes.size(), 4U + (heap_count * (4 + 8 + 1 + 4 + 4 + 4 + 4)));
4341 Dbg::DdmSendChunk(CHUNK_TYPE("HPIF"), bytes);
Elliott Hughes767a1472011-10-26 18:49:02 -07004342}
4343
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004344enum HpsgSolidity {
4345 SOLIDITY_FREE = 0,
4346 SOLIDITY_HARD = 1,
4347 SOLIDITY_SOFT = 2,
4348 SOLIDITY_WEAK = 3,
4349 SOLIDITY_PHANTOM = 4,
4350 SOLIDITY_FINALIZABLE = 5,
4351 SOLIDITY_SWEEP = 6,
4352};
4353
4354enum HpsgKind {
4355 KIND_OBJECT = 0,
4356 KIND_CLASS_OBJECT = 1,
4357 KIND_ARRAY_1 = 2,
4358 KIND_ARRAY_2 = 3,
4359 KIND_ARRAY_4 = 4,
4360 KIND_ARRAY_8 = 5,
4361 KIND_UNKNOWN = 6,
4362 KIND_NATIVE = 7,
4363};
4364
4365#define HPSG_PARTIAL (1<<7)
4366#define HPSG_STATE(solidity, kind) ((uint8_t)((((kind) & 0x7) << 3) | ((solidity) & 0x7)))
4367
Ian Rogers30fab402012-01-23 15:43:46 -08004368class HeapChunkContext {
4369 public:
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004370 // Maximum chunk size. Obtain this from the formula:
4371 // (((maximum_heap_size / ALLOCATION_UNIT_SIZE) + 255) / 256) * 2
4372 HeapChunkContext(bool merge, bool native)
Ian Rogers30fab402012-01-23 15:43:46 -08004373 : buf_(16384 - 16),
4374 type_(0),
Mathieu Chartier36dab362014-07-30 14:59:56 -07004375 chunk_overhead_(0) {
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004376 Reset();
4377 if (native) {
Ian Rogers30fab402012-01-23 15:43:46 -08004378 type_ = CHUNK_TYPE("NHSG");
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004379 } else {
Ian Rogers30fab402012-01-23 15:43:46 -08004380 type_ = merge ? CHUNK_TYPE("HPSG") : CHUNK_TYPE("HPSO");
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004381 }
4382 }
4383
4384 ~HeapChunkContext() {
Ian Rogers30fab402012-01-23 15:43:46 -08004385 if (p_ > &buf_[0]) {
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004386 Flush();
4387 }
4388 }
4389
Mathieu Chartier36dab362014-07-30 14:59:56 -07004390 void SetChunkOverhead(size_t chunk_overhead) {
4391 chunk_overhead_ = chunk_overhead;
4392 }
4393
4394 void ResetStartOfNextChunk() {
4395 startOfNextMemoryChunk_ = nullptr;
4396 }
4397
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004398 void EnsureHeader(const void* chunk_ptr) {
Ian Rogers30fab402012-01-23 15:43:46 -08004399 if (!needHeader_) {
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004400 return;
4401 }
4402
4403 // Start a new HPSx chunk.
Brian Carlstrom7934ac22013-07-26 10:54:15 -07004404 JDWP::Write4BE(&p_, 1); // Heap id (bogus; we only have one heap).
4405 JDWP::Write1BE(&p_, 8); // Size of allocation unit, in bytes.
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004406
Brian Carlstrom7934ac22013-07-26 10:54:15 -07004407 JDWP::Write4BE(&p_, reinterpret_cast<uintptr_t>(chunk_ptr)); // virtual address of segment start.
4408 JDWP::Write4BE(&p_, 0); // offset of this piece (relative to the virtual address).
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004409 // [u4]: length of piece, in allocation units
4410 // 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 -08004411 pieceLenField_ = p_;
4412 JDWP::Write4BE(&p_, 0x55555555);
4413 needHeader_ = false;
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004414 }
4415
Mathieu Chartier90443472015-07-16 20:32:27 -07004416 void Flush() SHARED_REQUIRES(Locks::mutator_lock_) {
Ian Rogersc0542af2014-09-03 16:16:56 -07004417 if (pieceLenField_ == nullptr) {
Ian Rogersd636b062013-01-18 17:51:18 -08004418 // Flush immediately post Reset (maybe back-to-back Flush). Ignore.
4419 CHECK(needHeader_);
4420 return;
4421 }
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004422 // Patch the "length of piece" field.
Ian Rogers30fab402012-01-23 15:43:46 -08004423 CHECK_LE(&buf_[0], pieceLenField_);
4424 CHECK_LE(pieceLenField_, p_);
4425 JDWP::Set4BE(pieceLenField_, totalAllocationUnits_);
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004426
Ian Rogers30fab402012-01-23 15:43:46 -08004427 Dbg::DdmSendChunk(type_, p_ - &buf_[0], &buf_[0]);
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004428 Reset();
4429 }
4430
Mathieu Chartierbc689b72014-12-14 17:01:31 -08004431 static void HeapChunkJavaCallback(void* start, void* end, size_t used_bytes, void* arg)
Mathieu Chartier90443472015-07-16 20:32:27 -07004432 SHARED_REQUIRES(Locks::heap_bitmap_lock_,
Ian Rogersb726dcb2012-09-05 08:57:23 -07004433 Locks::mutator_lock_) {
Mathieu Chartierbc689b72014-12-14 17:01:31 -08004434 reinterpret_cast<HeapChunkContext*>(arg)->HeapChunkJavaCallback(start, end, used_bytes);
4435 }
4436
4437 static void HeapChunkNativeCallback(void* start, void* end, size_t used_bytes, void* arg)
Mathieu Chartier90443472015-07-16 20:32:27 -07004438 SHARED_REQUIRES(Locks::mutator_lock_) {
Mathieu Chartierbc689b72014-12-14 17:01:31 -08004439 reinterpret_cast<HeapChunkContext*>(arg)->HeapChunkNativeCallback(start, end, used_bytes);
Elliott Hughesa2155262011-11-16 16:26:58 -08004440 }
4441
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004442 private:
Elliott Hughesa2155262011-11-16 16:26:58 -08004443 enum { ALLOCATION_UNIT_SIZE = 8 };
4444
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004445 void Reset() {
Ian Rogers30fab402012-01-23 15:43:46 -08004446 p_ = &buf_[0];
Mathieu Chartier36dab362014-07-30 14:59:56 -07004447 ResetStartOfNextChunk();
Ian Rogers30fab402012-01-23 15:43:46 -08004448 totalAllocationUnits_ = 0;
4449 needHeader_ = true;
Ian Rogersc0542af2014-09-03 16:16:56 -07004450 pieceLenField_ = nullptr;
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004451 }
4452
Mathieu Chartierbc689b72014-12-14 17:01:31 -08004453 bool IsNative() const {
4454 return type_ == CHUNK_TYPE("NHSG");
4455 }
4456
4457 // Returns true if the object is not an empty chunk.
Mathieu Chartier90443472015-07-16 20:32:27 -07004458 bool ProcessRecord(void* start, size_t used_bytes) SHARED_REQUIRES(Locks::mutator_lock_) {
Ian Rogers30fab402012-01-23 15:43:46 -08004459 // Note: heap call backs cannot manipulate the heap upon which they are crawling, care is taken
4460 // in the following code not to allocate memory, by ensuring buf_ is of the correct size
Ian Rogers15bf2d32012-08-28 17:33:04 -07004461 if (used_bytes == 0) {
Mathieu Chartierbc689b72014-12-14 17:01:31 -08004462 if (start == nullptr) {
4463 // Reset for start of new heap.
4464 startOfNextMemoryChunk_ = nullptr;
4465 Flush();
4466 }
4467 // Only process in use memory so that free region information
4468 // also includes dlmalloc book keeping.
4469 return false;
Elliott Hughesa2155262011-11-16 16:26:58 -08004470 }
Ian Rogersc0542af2014-09-03 16:16:56 -07004471 if (startOfNextMemoryChunk_ != nullptr) {
Mathieu Chartierbc689b72014-12-14 17:01:31 -08004472 // Transmit any pending free memory. Native free memory of over kMaxFreeLen could be because
4473 // of the use of mmaps, so don't report. If not free memory then start a new segment.
4474 bool flush = true;
4475 if (start > startOfNextMemoryChunk_) {
4476 const size_t kMaxFreeLen = 2 * kPageSize;
4477 void* free_start = startOfNextMemoryChunk_;
4478 void* free_end = start;
4479 const size_t free_len =
4480 reinterpret_cast<uintptr_t>(free_end) - reinterpret_cast<uintptr_t>(free_start);
4481 if (!IsNative() || free_len < kMaxFreeLen) {
4482 AppendChunk(HPSG_STATE(SOLIDITY_FREE, 0), free_start, free_len, IsNative());
4483 flush = false;
Ian Rogers15bf2d32012-08-28 17:33:04 -07004484 }
Mathieu Chartierbc689b72014-12-14 17:01:31 -08004485 }
4486 if (flush) {
4487 startOfNextMemoryChunk_ = nullptr;
4488 Flush();
4489 }
Ian Rogers15bf2d32012-08-28 17:33:04 -07004490 }
Mathieu Chartierbc689b72014-12-14 17:01:31 -08004491 return true;
Ian Rogers15bf2d32012-08-28 17:33:04 -07004492 }
Elliott Hughesa2155262011-11-16 16:26:58 -08004493
Mathieu Chartierbc689b72014-12-14 17:01:31 -08004494 void HeapChunkNativeCallback(void* start, void* /*end*/, size_t used_bytes)
Mathieu Chartier90443472015-07-16 20:32:27 -07004495 SHARED_REQUIRES(Locks::mutator_lock_) {
Mathieu Chartierbc689b72014-12-14 17:01:31 -08004496 if (ProcessRecord(start, used_bytes)) {
4497 uint8_t state = ExamineNativeObject(start);
4498 AppendChunk(state, start, used_bytes + chunk_overhead_, true /*is_native*/);
4499 startOfNextMemoryChunk_ = reinterpret_cast<char*>(start) + used_bytes + chunk_overhead_;
4500 }
4501 }
4502
4503 void HeapChunkJavaCallback(void* start, void* /*end*/, size_t used_bytes)
Mathieu Chartier90443472015-07-16 20:32:27 -07004504 SHARED_REQUIRES(Locks::heap_bitmap_lock_, Locks::mutator_lock_) {
Mathieu Chartierbc689b72014-12-14 17:01:31 -08004505 if (ProcessRecord(start, used_bytes)) {
4506 // Determine the type of this chunk.
4507 // OLD-TODO: if context.merge, see if this chunk is different from the last chunk.
4508 // If it's the same, we should combine them.
4509 uint8_t state = ExamineJavaObject(reinterpret_cast<mirror::Object*>(start));
4510 AppendChunk(state, start, used_bytes + chunk_overhead_, false /*is_native*/);
4511 startOfNextMemoryChunk_ = reinterpret_cast<char*>(start) + used_bytes + chunk_overhead_;
4512 }
4513 }
4514
4515 void AppendChunk(uint8_t state, void* ptr, size_t length, bool is_native)
Mathieu Chartier90443472015-07-16 20:32:27 -07004516 SHARED_REQUIRES(Locks::mutator_lock_) {
Ian Rogers15bf2d32012-08-28 17:33:04 -07004517 // Make sure there's enough room left in the buffer.
4518 // We need to use two bytes for every fractional 256 allocation units used by the chunk plus
4519 // 17 bytes for any header.
Mathieu Chartierbc689b72014-12-14 17:01:31 -08004520 const size_t needed = ((RoundUp(length / ALLOCATION_UNIT_SIZE, 256) / 256) * 2) + 17;
4521 size_t byte_left = &buf_.back() - p_;
4522 if (byte_left < needed) {
4523 if (is_native) {
Pavel Vyssotski7522c742014-12-08 13:38:26 +06004524 // Cannot trigger memory allocation while walking native heap.
Pavel Vyssotski7522c742014-12-08 13:38:26 +06004525 return;
4526 }
Ian Rogers15bf2d32012-08-28 17:33:04 -07004527 Flush();
4528 }
4529
Mathieu Chartierbc689b72014-12-14 17:01:31 -08004530 byte_left = &buf_.back() - p_;
4531 if (byte_left < needed) {
Ian Rogers15bf2d32012-08-28 17:33:04 -07004532 LOG(WARNING) << "Chunk is too big to transmit (chunk_len=" << length << ", "
4533 << needed << " bytes)";
4534 return;
4535 }
4536 EnsureHeader(ptr);
Elliott Hughesa2155262011-11-16 16:26:58 -08004537 // Write out the chunk description.
Ian Rogers15bf2d32012-08-28 17:33:04 -07004538 length /= ALLOCATION_UNIT_SIZE; // Convert to allocation units.
4539 totalAllocationUnits_ += length;
4540 while (length > 256) {
Ian Rogers30fab402012-01-23 15:43:46 -08004541 *p_++ = state | HPSG_PARTIAL;
4542 *p_++ = 255; // length - 1
Ian Rogers15bf2d32012-08-28 17:33:04 -07004543 length -= 256;
Elliott Hughesa2155262011-11-16 16:26:58 -08004544 }
Ian Rogers30fab402012-01-23 15:43:46 -08004545 *p_++ = state;
Ian Rogers15bf2d32012-08-28 17:33:04 -07004546 *p_++ = length - 1;
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004547 }
4548
Mathieu Chartier90443472015-07-16 20:32:27 -07004549 uint8_t ExamineNativeObject(const void* p) SHARED_REQUIRES(Locks::mutator_lock_) {
Mathieu Chartierbc689b72014-12-14 17:01:31 -08004550 return p == nullptr ? HPSG_STATE(SOLIDITY_FREE, 0) : HPSG_STATE(SOLIDITY_HARD, KIND_NATIVE);
4551 }
4552
4553 uint8_t ExamineJavaObject(mirror::Object* o)
Mathieu Chartier90443472015-07-16 20:32:27 -07004554 SHARED_REQUIRES(Locks::mutator_lock_, Locks::heap_bitmap_lock_) {
Ian Rogersc0542af2014-09-03 16:16:56 -07004555 if (o == nullptr) {
Elliott Hughesa2155262011-11-16 16:26:58 -08004556 return HPSG_STATE(SOLIDITY_FREE, 0);
4557 }
Elliott Hughesa2155262011-11-16 16:26:58 -08004558 // It's an allocated chunk. Figure out what it is.
Mathieu Chartierbc689b72014-12-14 17:01:31 -08004559 gc::Heap* heap = Runtime::Current()->GetHeap();
4560 if (!heap->IsLiveObjectLocked(o)) {
4561 LOG(ERROR) << "Invalid object in managed heap: " << o;
Elliott Hughesa2155262011-11-16 16:26:58 -08004562 return HPSG_STATE(SOLIDITY_HARD, KIND_NATIVE);
4563 }
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08004564 mirror::Class* c = o->GetClass();
Ian Rogersc0542af2014-09-03 16:16:56 -07004565 if (c == nullptr) {
Elliott Hughesa2155262011-11-16 16:26:58 -08004566 // The object was probably just created but hasn't been initialized yet.
4567 return HPSG_STATE(SOLIDITY_HARD, KIND_OBJECT);
4568 }
Mathieu Chartierbc689b72014-12-14 17:01:31 -08004569 if (!heap->IsValidObjectAddress(c)) {
Ian Rogers15bf2d32012-08-28 17:33:04 -07004570 LOG(ERROR) << "Invalid class for managed heap object: " << o << " " << c;
Elliott Hughesa2155262011-11-16 16:26:58 -08004571 return HPSG_STATE(SOLIDITY_HARD, KIND_UNKNOWN);
4572 }
Mathieu Chartierf26e1b32015-01-29 10:47:10 -08004573 if (c->GetClass() == nullptr) {
4574 LOG(ERROR) << "Null class of class " << c << " for object " << o;
4575 return HPSG_STATE(SOLIDITY_HARD, KIND_UNKNOWN);
4576 }
Elliott Hughesa2155262011-11-16 16:26:58 -08004577 if (c->IsClassClass()) {
4578 return HPSG_STATE(SOLIDITY_HARD, KIND_CLASS_OBJECT);
4579 }
Elliott Hughesa2155262011-11-16 16:26:58 -08004580 if (c->IsArrayClass()) {
Elliott Hughesa2155262011-11-16 16:26:58 -08004581 switch (c->GetComponentSize()) {
4582 case 1: return HPSG_STATE(SOLIDITY_HARD, KIND_ARRAY_1);
4583 case 2: return HPSG_STATE(SOLIDITY_HARD, KIND_ARRAY_2);
4584 case 4: return HPSG_STATE(SOLIDITY_HARD, KIND_ARRAY_4);
4585 case 8: return HPSG_STATE(SOLIDITY_HARD, KIND_ARRAY_8);
4586 }
4587 }
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004588 return HPSG_STATE(SOLIDITY_HARD, KIND_OBJECT);
4589 }
4590
Ian Rogers30fab402012-01-23 15:43:46 -08004591 std::vector<uint8_t> buf_;
4592 uint8_t* p_;
4593 uint8_t* pieceLenField_;
Ian Rogers15bf2d32012-08-28 17:33:04 -07004594 void* startOfNextMemoryChunk_;
Ian Rogers30fab402012-01-23 15:43:46 -08004595 size_t totalAllocationUnits_;
4596 uint32_t type_;
Ian Rogers30fab402012-01-23 15:43:46 -08004597 bool needHeader_;
Mathieu Chartier36dab362014-07-30 14:59:56 -07004598 size_t chunk_overhead_;
Ian Rogers30fab402012-01-23 15:43:46 -08004599
Elliott Hughesa2155262011-11-16 16:26:58 -08004600 DISALLOW_COPY_AND_ASSIGN(HeapChunkContext);
4601};
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004602
Mathieu Chartier36dab362014-07-30 14:59:56 -07004603static void BumpPointerSpaceCallback(mirror::Object* obj, void* arg)
Mathieu Chartier90443472015-07-16 20:32:27 -07004604 SHARED_REQUIRES(Locks::mutator_lock_) REQUIRES(Locks::heap_bitmap_lock_) {
Mathieu Chartier36dab362014-07-30 14:59:56 -07004605 const size_t size = RoundUp(obj->SizeOf(), kObjectAlignment);
Mathieu Chartierbc689b72014-12-14 17:01:31 -08004606 HeapChunkContext::HeapChunkJavaCallback(
Mathieu Chartier36dab362014-07-30 14:59:56 -07004607 obj, reinterpret_cast<void*>(reinterpret_cast<uintptr_t>(obj) + size), size, arg);
4608}
4609
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004610void Dbg::DdmSendHeapSegments(bool native) {
Mathieu Chartierbc689b72014-12-14 17:01:31 -08004611 Dbg::HpsgWhen when = native ? gDdmNhsgWhen : gDdmHpsgWhen;
4612 Dbg::HpsgWhat what = native ? gDdmNhsgWhat : gDdmHpsgWhat;
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004613 if (when == HPSG_WHEN_NEVER) {
4614 return;
4615 }
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004616 // Figure out what kind of chunks we'll be sending.
Mathieu Chartierbc689b72014-12-14 17:01:31 -08004617 CHECK(what == HPSG_WHAT_MERGED_OBJECTS || what == HPSG_WHAT_DISTINCT_OBJECTS)
4618 << static_cast<int>(what);
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004619
4620 // First, send a heap start chunk.
4621 uint8_t heap_id[4];
Brian Carlstrom7934ac22013-07-26 10:54:15 -07004622 JDWP::Set4BE(&heap_id[0], 1); // Heap id (bogus; we only have one heap).
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004623 Dbg::DdmSendChunk(native ? CHUNK_TYPE("NHST") : CHUNK_TYPE("HPST"), sizeof(heap_id), heap_id);
Hiroshi Yamauchicf58d4a2013-09-26 14:21:22 -07004624 Thread* self = Thread::Current();
Hiroshi Yamauchicf58d4a2013-09-26 14:21:22 -07004625 Locks::mutator_lock_->AssertSharedHeld(self);
Hiroshi Yamauchicf58d4a2013-09-26 14:21:22 -07004626
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004627 // Send a series of heap segment chunks.
Mathieu Chartierbc689b72014-12-14 17:01:31 -08004628 HeapChunkContext context(what == HPSG_WHAT_MERGED_OBJECTS, native);
Elliott Hughesa2155262011-11-16 16:26:58 -08004629 if (native) {
Andreas Gampec60e1b72015-07-30 08:57:50 -07004630#if defined(__ANDROID__) && defined(USE_DLMALLOC)
Mathieu Chartierbc689b72014-12-14 17:01:31 -08004631 dlmalloc_inspect_all(HeapChunkContext::HeapChunkNativeCallback, &context);
4632 HeapChunkContext::HeapChunkNativeCallback(nullptr, nullptr, 0, &context); // Indicate end of a space.
Christopher Ferrisc4ddc042014-05-13 14:47:50 -07004633#else
4634 UNIMPLEMENTED(WARNING) << "Native heap inspection is only supported with dlmalloc";
4635#endif
Elliott Hughesa2155262011-11-16 16:26:58 -08004636 } else {
Ian Rogers1d54e732013-05-02 21:10:01 -07004637 gc::Heap* heap = Runtime::Current()->GetHeap();
Mathieu Chartier36dab362014-07-30 14:59:56 -07004638 for (const auto& space : heap->GetContinuousSpaces()) {
4639 if (space->IsDlMallocSpace()) {
Mathieu Chartier4c69d7f2014-10-10 12:45:50 -07004640 ReaderMutexLock mu(self, *Locks::heap_bitmap_lock_);
Mathieu Chartier36dab362014-07-30 14:59:56 -07004641 // dlmalloc's chunk header is 2 * sizeof(size_t), but if the previous chunk is in use for an
4642 // allocation then the first sizeof(size_t) may belong to it.
4643 context.SetChunkOverhead(sizeof(size_t));
Mathieu Chartierbc689b72014-12-14 17:01:31 -08004644 space->AsDlMallocSpace()->Walk(HeapChunkContext::HeapChunkJavaCallback, &context);
Mathieu Chartier36dab362014-07-30 14:59:56 -07004645 } else if (space->IsRosAllocSpace()) {
4646 context.SetChunkOverhead(0);
Mathieu Chartier4c69d7f2014-10-10 12:45:50 -07004647 // Need to acquire the mutator lock before the heap bitmap lock with exclusive access since
4648 // RosAlloc's internal logic doesn't know to release and reacquire the heap bitmap lock.
4649 self->TransitionFromRunnableToSuspended(kSuspended);
4650 ThreadList* tl = Runtime::Current()->GetThreadList();
Mathieu Chartierbf9fc582015-03-13 17:21:25 -07004651 tl->SuspendAll(__FUNCTION__);
Mathieu Chartier4c69d7f2014-10-10 12:45:50 -07004652 {
4653 ReaderMutexLock mu(self, *Locks::heap_bitmap_lock_);
Mathieu Chartierbc689b72014-12-14 17:01:31 -08004654 space->AsRosAllocSpace()->Walk(HeapChunkContext::HeapChunkJavaCallback, &context);
Mathieu Chartier4c69d7f2014-10-10 12:45:50 -07004655 }
4656 tl->ResumeAll();
4657 self->TransitionFromSuspendedToRunnable();
Mathieu Chartier36dab362014-07-30 14:59:56 -07004658 } else if (space->IsBumpPointerSpace()) {
Mathieu Chartier4c69d7f2014-10-10 12:45:50 -07004659 ReaderMutexLock mu(self, *Locks::heap_bitmap_lock_);
Mathieu Chartier36dab362014-07-30 14:59:56 -07004660 context.SetChunkOverhead(0);
Mathieu Chartier36dab362014-07-30 14:59:56 -07004661 space->AsBumpPointerSpace()->Walk(BumpPointerSpaceCallback, &context);
Mathieu Chartierbc689b72014-12-14 17:01:31 -08004662 HeapChunkContext::HeapChunkJavaCallback(nullptr, nullptr, 0, &context);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08004663 } else if (space->IsRegionSpace()) {
4664 heap->IncrementDisableMovingGC(self);
4665 self->TransitionFromRunnableToSuspended(kSuspended);
4666 ThreadList* tl = Runtime::Current()->GetThreadList();
Mathieu Chartierbf9fc582015-03-13 17:21:25 -07004667 tl->SuspendAll(__FUNCTION__);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08004668 ReaderMutexLock mu(self, *Locks::heap_bitmap_lock_);
4669 context.SetChunkOverhead(0);
4670 space->AsRegionSpace()->Walk(BumpPointerSpaceCallback, &context);
4671 HeapChunkContext::HeapChunkJavaCallback(nullptr, nullptr, 0, &context);
4672 tl->ResumeAll();
4673 self->TransitionFromSuspendedToRunnable();
4674 heap->DecrementDisableMovingGC(self);
Mathieu Chartier36dab362014-07-30 14:59:56 -07004675 } else {
4676 UNIMPLEMENTED(WARNING) << "Not counting objects in space " << *space;
Mathieu Chartierb062fdd2012-07-03 09:51:48 -07004677 }
Mathieu Chartier36dab362014-07-30 14:59:56 -07004678 context.ResetStartOfNextChunk();
Mathieu Chartierb062fdd2012-07-03 09:51:48 -07004679 }
Mathieu Chartier4c69d7f2014-10-10 12:45:50 -07004680 ReaderMutexLock mu(self, *Locks::heap_bitmap_lock_);
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -07004681 // Walk the large objects, these are not in the AllocSpace.
Mathieu Chartier36dab362014-07-30 14:59:56 -07004682 context.SetChunkOverhead(0);
Mathieu Chartierbc689b72014-12-14 17:01:31 -08004683 heap->GetLargeObjectsSpace()->Walk(HeapChunkContext::HeapChunkJavaCallback, &context);
Elliott Hughesa2155262011-11-16 16:26:58 -08004684 }
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004685
4686 // Finally, send a heap end chunk.
4687 Dbg::DdmSendChunk(native ? CHUNK_TYPE("NHEN") : CHUNK_TYPE("HPEN"), sizeof(heap_id), heap_id);
Elliott Hughes767a1472011-10-26 18:49:02 -07004688}
4689
Brian Carlstrom306db812014-09-05 13:01:41 -07004690void Dbg::SetAllocTrackingEnabled(bool enable) {
Man Cao8c2ff642015-05-27 17:25:30 -07004691 gc::AllocRecordObjectMap::SetAllocTrackingEnabled(enable);
Elliott Hughes545a0642011-11-08 19:10:03 -08004692}
4693
4694void Dbg::DumpRecentAllocations() {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07004695 ScopedObjectAccess soa(Thread::Current());
Brian Carlstrom306db812014-09-05 13:01:41 -07004696 MutexLock mu(soa.Self(), *Locks::alloc_tracker_lock_);
Man Cao8c2ff642015-05-27 17:25:30 -07004697 if (!Runtime::Current()->GetHeap()->IsAllocTrackingEnabled()) {
Elliott Hughes545a0642011-11-08 19:10:03 -08004698 LOG(INFO) << "Not recording tracked allocations";
4699 return;
4700 }
Man Cao8c2ff642015-05-27 17:25:30 -07004701 gc::AllocRecordObjectMap* records = Runtime::Current()->GetHeap()->GetAllocationRecords();
4702 CHECK(records != nullptr);
Elliott Hughes545a0642011-11-08 19:10:03 -08004703
Man Cao1ed11b92015-06-11 22:47:35 -07004704 const uint16_t capped_count = CappedAllocRecordCount(records->GetRecentAllocationSize());
Brian Carlstrom306db812014-09-05 13:01:41 -07004705 uint16_t count = capped_count;
Elliott Hughes545a0642011-11-08 19:10:03 -08004706
Man Cao8c2ff642015-05-27 17:25:30 -07004707 LOG(INFO) << "Tracked allocations, (count=" << count << ")";
4708 for (auto it = records->RBegin(), end = records->REnd();
4709 count > 0 && it != end; count--, it++) {
4710 const gc::AllocRecord* record = it->second;
Elliott Hughes545a0642011-11-08 19:10:03 -08004711
Man Cao8c2ff642015-05-27 17:25:30 -07004712 LOG(INFO) << StringPrintf(" Thread %-2d %6zd bytes ", record->GetTid(), record->ByteCount())
Man Cao42c3c332015-06-23 16:38:25 -07004713 << PrettyClass(record->GetClass());
Elliott Hughes545a0642011-11-08 19:10:03 -08004714
Man Cao8c2ff642015-05-27 17:25:30 -07004715 for (size_t stack_frame = 0, depth = record->GetDepth(); stack_frame < depth; ++stack_frame) {
4716 const gc::AllocRecordStackTraceElement& stack_element = record->StackElement(stack_frame);
4717 ArtMethod* m = stack_element.GetMethod();
4718 LOG(INFO) << " " << PrettyMethod(m) << " line " << stack_element.ComputeLineNumber();
Elliott Hughes545a0642011-11-08 19:10:03 -08004719 }
4720
4721 // pause periodically to help logcat catch up
4722 if ((count % 5) == 0) {
4723 usleep(40000);
4724 }
Elliott Hughes545a0642011-11-08 19:10:03 -08004725 }
4726}
4727
4728class StringTable {
4729 public:
4730 StringTable() {
4731 }
4732
Mathieu Chartier4345c462014-06-27 10:20:14 -07004733 void Add(const std::string& str) {
4734 table_.insert(str);
4735 }
4736
4737 void Add(const char* str) {
4738 table_.insert(str);
Elliott Hughes545a0642011-11-08 19:10:03 -08004739 }
4740
Elliott Hughesa8f93cb2012-06-08 17:08:48 -07004741 size_t IndexOf(const char* s) const {
Mathieu Chartier02e25112013-08-14 16:14:24 -07004742 auto it = table_.find(s);
Elliott Hughesa8f93cb2012-06-08 17:08:48 -07004743 if (it == table_.end()) {
4744 LOG(FATAL) << "IndexOf(\"" << s << "\") failed";
4745 }
4746 return std::distance(table_.begin(), it);
Elliott Hughes545a0642011-11-08 19:10:03 -08004747 }
4748
Elliott Hughesa8f93cb2012-06-08 17:08:48 -07004749 size_t Size() const {
Elliott Hughes545a0642011-11-08 19:10:03 -08004750 return table_.size();
4751 }
4752
Elliott Hughesa8f93cb2012-06-08 17:08:48 -07004753 void WriteTo(std::vector<uint8_t>& bytes) const {
Mathieu Chartier02e25112013-08-14 16:14:24 -07004754 for (const std::string& str : table_) {
4755 const char* s = str.c_str();
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08004756 size_t s_len = CountModifiedUtf8Chars(s);
Christopher Ferris8a354052015-04-24 17:23:53 -07004757 std::unique_ptr<uint16_t[]> s_utf16(new uint16_t[s_len]);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08004758 ConvertModifiedUtf8ToUtf16(s_utf16.get(), s);
4759 JDWP::AppendUtf16BE(bytes, s_utf16.get(), s_len);
Elliott Hughes545a0642011-11-08 19:10:03 -08004760 }
4761 }
4762
4763 private:
Elliott Hughesa8f93cb2012-06-08 17:08:48 -07004764 std::set<std::string> table_;
Elliott Hughes545a0642011-11-08 19:10:03 -08004765 DISALLOW_COPY_AND_ASSIGN(StringTable);
4766};
4767
Mathieu Chartiere401d142015-04-22 13:56:20 -07004768static const char* GetMethodSourceFile(ArtMethod* method)
Mathieu Chartier90443472015-07-16 20:32:27 -07004769 SHARED_REQUIRES(Locks::mutator_lock_) {
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07004770 DCHECK(method != nullptr);
4771 const char* source_file = method->GetDeclaringClassSourceFile();
Sebastien Hertz280286a2014-04-28 09:26:50 +02004772 return (source_file != nullptr) ? source_file : "";
4773}
4774
Elliott Hughes545a0642011-11-08 19:10:03 -08004775/*
4776 * The data we send to DDMS contains everything we have recorded.
4777 *
4778 * Message header (all values big-endian):
4779 * (1b) message header len (to allow future expansion); includes itself
4780 * (1b) entry header len
4781 * (1b) stack frame len
4782 * (2b) number of entries
4783 * (4b) offset to string table from start of message
4784 * (2b) number of class name strings
4785 * (2b) number of method name strings
4786 * (2b) number of source file name strings
4787 * For each entry:
4788 * (4b) total allocation size
Elliott Hughes221229c2013-01-08 18:17:50 -08004789 * (2b) thread id
Elliott Hughes545a0642011-11-08 19:10:03 -08004790 * (2b) allocated object's class name index
4791 * (1b) stack depth
4792 * For each stack frame:
4793 * (2b) method's class name
4794 * (2b) method name
4795 * (2b) method source file
4796 * (2b) line number, clipped to 32767; -2 if native; -1 if no source
4797 * (xb) class name strings
4798 * (xb) method name strings
4799 * (xb) source file strings
4800 *
4801 * As with other DDM traffic, strings are sent as a 4-byte length
4802 * followed by UTF-16 data.
4803 *
4804 * We send up 16-bit unsigned indexes into string tables. In theory there
Brian Carlstrom306db812014-09-05 13:01:41 -07004805 * can be (kMaxAllocRecordStackDepth * alloc_record_max_) unique strings in
Elliott Hughes545a0642011-11-08 19:10:03 -08004806 * each table, but in practice there should be far fewer.
4807 *
4808 * The chief reason for using a string table here is to keep the size of
4809 * the DDMS message to a minimum. This is partly to make the protocol
4810 * efficient, but also because we have to form the whole thing up all at
4811 * once in a memory buffer.
4812 *
4813 * We use separate string tables for class names, method names, and source
4814 * files to keep the indexes small. There will generally be no overlap
4815 * between the contents of these tables.
4816 */
4817jbyteArray Dbg::GetRecentAllocations() {
Ian Rogerscf7f1912014-10-22 22:06:39 -07004818 if ((false)) {
Elliott Hughes545a0642011-11-08 19:10:03 -08004819 DumpRecentAllocations();
4820 }
4821
Ian Rogers50b35e22012-10-04 10:09:15 -07004822 Thread* self = Thread::Current();
Elliott Hughes545a0642011-11-08 19:10:03 -08004823 std::vector<uint8_t> bytes;
Mathieu Chartier46e811b2013-07-10 17:09:14 -07004824 {
Brian Carlstrom306db812014-09-05 13:01:41 -07004825 MutexLock mu(self, *Locks::alloc_tracker_lock_);
Man Cao8c2ff642015-05-27 17:25:30 -07004826 gc::AllocRecordObjectMap* records = Runtime::Current()->GetHeap()->GetAllocationRecords();
4827 // In case this method is called when allocation tracker is disabled,
4828 // we should still send some data back.
4829 gc::AllocRecordObjectMap dummy;
4830 if (records == nullptr) {
4831 CHECK(!Runtime::Current()->GetHeap()->IsAllocTrackingEnabled());
4832 records = &dummy;
4833 }
Man Cao41656de2015-07-06 18:53:15 -07004834 // We don't need to wait on the condition variable records->new_record_condition_, because this
4835 // function only reads the class objects, which are already marked so it doesn't change their
4836 // reachability.
Man Cao8c2ff642015-05-27 17:25:30 -07004837
Mathieu Chartier46e811b2013-07-10 17:09:14 -07004838 //
4839 // Part 1: generate string tables.
4840 //
4841 StringTable class_names;
4842 StringTable method_names;
4843 StringTable filenames;
Elliott Hughes545a0642011-11-08 19:10:03 -08004844
Man Cao1ed11b92015-06-11 22:47:35 -07004845 const uint16_t capped_count = CappedAllocRecordCount(records->GetRecentAllocationSize());
Brian Carlstrom306db812014-09-05 13:01:41 -07004846 uint16_t count = capped_count;
Man Cao8c2ff642015-05-27 17:25:30 -07004847 for (auto it = records->RBegin(), end = records->REnd();
4848 count > 0 && it != end; count--, it++) {
4849 const gc::AllocRecord* record = it->second;
Ian Rogers1ff3c982014-08-12 02:30:58 -07004850 std::string temp;
Man Cao41656de2015-07-06 18:53:15 -07004851 class_names.Add(record->GetClassDescriptor(&temp));
Man Cao8c2ff642015-05-27 17:25:30 -07004852 for (size_t i = 0, depth = record->GetDepth(); i < depth; i++) {
4853 ArtMethod* m = record->StackElement(i).GetMethod();
4854 class_names.Add(m->GetDeclaringClassDescriptor());
4855 method_names.Add(m->GetName());
4856 filenames.Add(GetMethodSourceFile(m));
Mathieu Chartier46e811b2013-07-10 17:09:14 -07004857 }
Elliott Hughes545a0642011-11-08 19:10:03 -08004858 }
4859
Man Cao8c2ff642015-05-27 17:25:30 -07004860 LOG(INFO) << "recent allocation records: " << capped_count;
4861 LOG(INFO) << "allocation records all objects: " << records->Size();
Mathieu Chartier46e811b2013-07-10 17:09:14 -07004862
4863 //
4864 // Part 2: Generate the output and store it in the buffer.
4865 //
4866
4867 // (1b) message header len (to allow future expansion); includes itself
4868 // (1b) entry header len
4869 // (1b) stack frame len
4870 const int kMessageHeaderLen = 15;
4871 const int kEntryHeaderLen = 9;
4872 const int kStackFrameLen = 8;
4873 JDWP::Append1BE(bytes, kMessageHeaderLen);
4874 JDWP::Append1BE(bytes, kEntryHeaderLen);
4875 JDWP::Append1BE(bytes, kStackFrameLen);
4876
4877 // (2b) number of entries
4878 // (4b) offset to string table from start of message
4879 // (2b) number of class name strings
4880 // (2b) number of method name strings
4881 // (2b) number of source file name strings
Brian Carlstrom306db812014-09-05 13:01:41 -07004882 JDWP::Append2BE(bytes, capped_count);
Mathieu Chartier46e811b2013-07-10 17:09:14 -07004883 size_t string_table_offset = bytes.size();
Brian Carlstrom7934ac22013-07-26 10:54:15 -07004884 JDWP::Append4BE(bytes, 0); // We'll patch this later...
Mathieu Chartier46e811b2013-07-10 17:09:14 -07004885 JDWP::Append2BE(bytes, class_names.Size());
4886 JDWP::Append2BE(bytes, method_names.Size());
4887 JDWP::Append2BE(bytes, filenames.Size());
4888
Ian Rogers1ff3c982014-08-12 02:30:58 -07004889 std::string temp;
Man Cao8c2ff642015-05-27 17:25:30 -07004890 count = capped_count;
4891 // The last "count" number of allocation records in "records" are the most recent "count" number
4892 // of allocations. Reverse iterate to get them. The most recent allocation is sent first.
4893 for (auto it = records->RBegin(), end = records->REnd();
4894 count > 0 && it != end; count--, it++) {
Mathieu Chartier46e811b2013-07-10 17:09:14 -07004895 // For each entry:
4896 // (4b) total allocation size
4897 // (2b) thread id
4898 // (2b) allocated object's class name index
4899 // (1b) stack depth
Man Cao8c2ff642015-05-27 17:25:30 -07004900 const gc::AllocRecord* record = it->second;
Mathieu Chartier46e811b2013-07-10 17:09:14 -07004901 size_t stack_depth = record->GetDepth();
Mathieu Chartierf8322842014-05-16 10:59:25 -07004902 size_t allocated_object_class_name_index =
Man Cao41656de2015-07-06 18:53:15 -07004903 class_names.IndexOf(record->GetClassDescriptor(&temp));
Hiroshi Yamauchib5a9e3d2014-06-09 12:11:20 -07004904 JDWP::Append4BE(bytes, record->ByteCount());
Man Cao8c2ff642015-05-27 17:25:30 -07004905 JDWP::Append2BE(bytes, static_cast<uint16_t>(record->GetTid()));
Mathieu Chartier46e811b2013-07-10 17:09:14 -07004906 JDWP::Append2BE(bytes, allocated_object_class_name_index);
4907 JDWP::Append1BE(bytes, stack_depth);
4908
Mathieu Chartier46e811b2013-07-10 17:09:14 -07004909 for (size_t stack_frame = 0; stack_frame < stack_depth; ++stack_frame) {
4910 // For each stack frame:
4911 // (2b) method's class name
4912 // (2b) method name
4913 // (2b) method source file
4914 // (2b) line number, clipped to 32767; -2 if native; -1 if no source
Man Cao8c2ff642015-05-27 17:25:30 -07004915 ArtMethod* m = record->StackElement(stack_frame).GetMethod();
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07004916 size_t class_name_index = class_names.IndexOf(m->GetDeclaringClassDescriptor());
4917 size_t method_name_index = method_names.IndexOf(m->GetName());
4918 size_t file_name_index = filenames.IndexOf(GetMethodSourceFile(m));
Mathieu Chartier46e811b2013-07-10 17:09:14 -07004919 JDWP::Append2BE(bytes, class_name_index);
4920 JDWP::Append2BE(bytes, method_name_index);
4921 JDWP::Append2BE(bytes, file_name_index);
Man Cao8c2ff642015-05-27 17:25:30 -07004922 JDWP::Append2BE(bytes, record->StackElement(stack_frame).ComputeLineNumber());
Mathieu Chartier46e811b2013-07-10 17:09:14 -07004923 }
Mathieu Chartier46e811b2013-07-10 17:09:14 -07004924 }
4925
4926 // (xb) class name strings
4927 // (xb) method name strings
4928 // (xb) source file strings
4929 JDWP::Set4BE(&bytes[string_table_offset], bytes.size());
4930 class_names.WriteTo(bytes);
4931 method_names.WriteTo(bytes);
4932 filenames.WriteTo(bytes);
Elliott Hughes545a0642011-11-08 19:10:03 -08004933 }
Ian Rogers50b35e22012-10-04 10:09:15 -07004934 JNIEnv* env = self->GetJniEnv();
Elliott Hughes545a0642011-11-08 19:10:03 -08004935 jbyteArray result = env->NewByteArray(bytes.size());
Ian Rogersc0542af2014-09-03 16:16:56 -07004936 if (result != nullptr) {
Elliott Hughes545a0642011-11-08 19:10:03 -08004937 env->SetByteArrayRegion(result, 0, bytes.size(), reinterpret_cast<const jbyte*>(&bytes[0]));
4938 }
4939 return result;
4940}
4941
Mathieu Chartiere401d142015-04-22 13:56:20 -07004942ArtMethod* DeoptimizationRequest::Method() const {
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07004943 ScopedObjectAccessUnchecked soa(Thread::Current());
4944 return soa.DecodeMethod(method_);
4945}
4946
Mathieu Chartiere401d142015-04-22 13:56:20 -07004947void DeoptimizationRequest::SetMethod(ArtMethod* m) {
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07004948 ScopedObjectAccessUnchecked soa(Thread::Current());
4949 method_ = soa.EncodeMethod(m);
4950}
4951
Elliott Hughes872d4ec2011-10-21 17:07:15 -07004952} // namespace art